aboutsummaryrefslogtreecommitdiff
path: root/tools/Internals/tools/gnu_gcc.py
blob: eddf1fbf23e44e36e6a772e5cbc9242ea676ab1c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
#!/usr/bin/env python3
""" These functions bring the GNU Compiler Collection, more precisely
	the C/C++ compiler, to the libcarrot build tools.

	When configured for a non-native target, GCC will install its binary as
	`<bfd target>-gcc` in the host binary directory, so we're looking for
	something like `<arch>-<os or format>-gcc`, e.g. `sh3eb-elf-gcc` for
	platform-independent gcc for the SuperH Core 3, big endian version,
	generating ELF object files or executables.

	If there is no appropriate non-native target, the native compiler might
	just be usable. We just have to check the BFD target using
	GCC's `-dumpmachine` option.
"""

import os
from subprocess import call, check_output, DEVNULL
from tempfile import mkstemp
from .utils import *

__all__ = ["GNU_GCC"]

#*****************************************************************************#
# Discovery, configuration                                                    #
#*****************************************************************************#
def __get_gcc_bfd(path):
	""" Get the BFD target out of the gcc binary path. """

	# Make the dump command with the default locale, get the output.
	env = os.environ.copy()
	env['LANG'] = 'en_US'
	out = check_output([path, '-dumpmachine'], env=env).decode()

	return out.strip()

def __iter_gcc(arch):
	""" Iterate through all of the `gcc` occurrences among the system. """

	for elt in getgnu(arch, 'gcc'):
		yield elt
	for elt in getutil(['gcc', 'gcc.exe']):
		yield elt

def __testcc(typ, path='/usr/bin/gcc', flags=[],
	text='int main(void) { return (0); }'):
	""" Try to compile, see if it works. """

	if typ == "cc":
		source_suffix = '.c'
		gcc_lang = 'c'
	elif typ == "cxx":
		source_suffix = '.cpp'
		gcc_lang = 'c++'
	elif typ == "asmc":
		source_suffix = '.sx'
		gcc_lang = 'assembler-with-cpp'

	sfd, sf = mkstemp(suffix=source_suffix, text=text)
	os.close(sfd)

	ofd, of = mkstemp(suffix='.o')
	os.close(ofd)

	cl = [path, '-x', gcc_lang, '-o', of, sf, '-nostdlib'] + flags
	if call(cl, shell=False, stdout=DEVNULL, stderr=DEVNULL):
		worked = False
	else:
		worked = True

	try: os.remove(of)
	except: pass
	try: os.remove(sf)
	except: pass

	return worked

def __teststd(typ, path, standards):
	''' Test if GCC supports those standards using the `-std` option. '''

	for s in standards:
		if not __testcc(typ, path, ['-std=%s'%s]):
			return False
	return True

def __getparams(typ, arch, objfmt, std=[]):
	""" Get the GNU Compiler Collection respecting some
		pre-defined constraints. """

	# Prepare the minimum compilation flags.
	cflags = []
	if arch[:2] == 'sh':
		cflags += ['-mhitachi', '-fomit-frame-pointer']
		if arch[-3:] == 'dsp':
			cflags.append('-Wa,-dsp')
			arch = arch[:-3]
		cflags += ['-m%s'%arch[2:], '-mb']
	else:
		# FIXME: is it like this for everything? raise exception here?
		cflags.append('-march=%s'%arch)

	# Get the utility.
	path = None
	for gcc in __iter_gcc(arch):
		if not bfd_are_equivalent(__get_gcc_bfd(gcc), arch, 'big', objfmt):
			continue
		if not __testcc(typ, gcc, cflags):
			continue
		if typ != "asmc" and not __teststd(typ, gcc, std):
			continue

		path = gcc
		break
	if not path:
		Raise(ToolNotFoundException)

	# Get the rest of the compilation flags.
	# TODO: use `-ffreestanding` (implies `-fno-builtin`?)
	cflags += ['-Wall', '-Wextra', '-Wno-attributes',
		'-O2', '-nostartfiles', '-fno-builtin-function']

	return {'path': path, 'flags': cflags}
#*****************************************************************************#
# Use the parameters                                                          #
#*****************************************************************************#
def __makeenv(incdirs):
	incpath = os.pathsep.join(incdirs)
	env = os.environ.copy()
	env['CPATH']              = incpath
	env['C_INCLUDE_PATH']     = incpath
	env['CPLUS_INCLUDE_PATH'] = incpath
	return env

def __cc(params, obj, src, incdirs, std):
	''' Compile a C file. '''

	# Set up the command line.
	commandline  = [params['path'], '-x', 'c', '-std=' + std, '-pedantic']
	commandline += ['-c', '-o', obj, src]
	commandline += params['flags']

	# Make the call.
	return call(commandline, env=__makeenv(incdirs))

def __cxx(params, obj, src, incdirs, std):
	# Set up the command line.
	commandline  = [params['path'], '-x', 'c++', '-std=' + std, '-pedantic']
	commandline += ['-c', '-o', obj, src]
	commandline += params['flags']

	# Make the call.
	return call(commandline, env=__makeenv(incdirs))

def __asmc(params, obj, src, incdirs):
	# Set up the command line.
	commandline  = [params['path'], '-x', 'assembler-with-cpp']
	commandline += ['-c', '-o', obj, src]

	# Make the call.
	return call(commandline, env=__makeenv(incdirs))

#*****************************************************************************#
# Main utility descriptor                                                     #
#*****************************************************************************#
GNU_GCC = {
	'getparams': __getparams,
	'cc':        __cc,
	'cxx':       __cxx,
	'asmc':      __asmc
}

# End of file.