Debian Codegraph @

rpython/translator/platform/__init__.py

raw symbols SCIP
1 """Platform-specific support for compiling/executing C sources."""
2
3 import py, os, sys
4
5 from rpython.tool.runsubprocess import run_subprocess as _run_subprocess
6 from rpython.tool.udir import udir
7 from rpython.tool.version import rpythonroot
8 from rpython.tool.ansi_print import AnsiLogger
9
10 log = AnsiLogger("platform")
11
12
13 class CompilationError(Exception):
14 def __init__(self, out, err):
15 self.out = out.replace('\r\n', '\n')
16 self.err = err.replace('\r\n', '\n')
17
18 def __repr__(self):
19 if self.err:
20 attr = 'err'
21 else:
22 attr = 'out'
23 text = getattr(self, attr).replace('\n', '\n\t')
24 return 'CompilationError(%s="""\n\t%s""")' % (attr, text)
25
26 __str__ = __repr__
27
28 class ExecutionResult(object):
29 def __init__(self, returncode, out, err):
30 self.returncode = returncode
31 self.out = out.replace('\r\n', '\n')
32 self.err = err.replace('\r\n', '\n')
33
34 def __repr__(self):
35 return "<ExecutionResult retcode=%d>" % (self.returncode,)
36
37 class Platform(object):
38 name = "abstract platform"
39 c_environ = None
40 # which branch to check out in get_external.py
41 externals_branch='main'
42 # where to put the externals, as an absolute path
43 externals = str(py.path.local(__file__).parts()[-5] / 'externals')
44 relevant_environ = ()
45 log_errors = True
46
47 so_prefixes = ('',)
48
49 extra_libs = ()
50
51 def __init__(self, cc):
52 if self.__class__ is Platform:
53 raise TypeError("You should not instantiate Platform class directly")
54 self.cc = cc
55
56 def compile(self, cfiles, eci, outputfilename=None, standalone=True):
57 ofiles = self._compile_o_files(cfiles, eci, standalone)
58 return self._finish_linking(ofiles, eci, outputfilename, standalone)
59
60 def _all_cfiles(self, cfiles, eci):
61 seen = set()
62 result = []
63 for cfile in list(cfiles) + list(eci.separate_module_files):
64 cfile = py.path.local(cfile)
65 if cfile not in seen:
66 seen.add(cfile)
67 result.append(cfile)
68 return result
69
70 def _compile_o_files(self, cfiles, eci, standalone=True):
71 cfiles = self._all_cfiles(cfiles, eci)
72 compile_args = self._compile_args_from_eci(eci, standalone)
73 ofiles = []
74 for cfile in cfiles:
75 # Windows hack: use masm for files ending in .asm
76 if str(cfile).lower().endswith('.asm'):
77 ofiles.append(self._compile_c_file(self.masm, cfile, []))
78 else:
79 ofiles.append(self._compile_c_file(self.cc, cfile, compile_args))
80 return ofiles
81
82 def execute(self, executable, args=None, env=None, compilation_info=None):
83 if env is None:
84 env = os.environ.copy()
85 else:
86 env = env.copy()
87
88 # On Windows, %SystemRoot% must be present for most programs to start
89 if (os.name == 'nt' and
90 "SystemRoot" not in env and
91 "SystemRoot" in os.environ):
92 env["SystemRoot"] = os.environ["SystemRoot"]
93
94 # Set LD_LIBRARY_PATH on posix platforms
95 if os.name == 'posix' and compilation_info is not None:
96 library_path = ':'.join([str(i) for i in compilation_info.library_dirs])
97 if sys.platform == 'darwin':
98 env['DYLD_LIBRARY_PATH'] = library_path
99 else:
100 env['LD_LIBRARY_PATH'] = library_path
101
102 returncode, stdout, stderr = _run_subprocess(str(executable), args,
103 env)
104 return ExecutionResult(returncode, stdout, stderr)
105
106 def gen_makefile(self, cfiles, eci, exe_name=None, path=None,
107 shared=False, headers_to_precompile=[],
108 no_precompile_cfiles = [], profopt=False, config=None):
109 raise NotImplementedError("Pure abstract baseclass")
110
111 def __repr__(self):
112 return '<%s cc=%s>' % (self.__class__.__name__, self.cc)
113
114 def __hash__(self):
115 return hash(self.__class__.__name__)
116
117 def __ne__(self, other):
118 return not self == other
119
120 def __eq__(self, other):
121 return (self.__class__ is other.__class__ and
122 self.__dict__ == other.__dict__)
123
124 def key(self):
125 bits = [self.__class__.__name__, 'cc=%r' % self.cc]
126 for varname in self.relevant_environ:
127 bits.append('%s=%r' % (varname, os.environ.get(varname)))
128 # adding sys.maxint to disambiguate windows
129 bits.append('%s=%r' % ('sys.maxint', sys.maxint))
130 return ' '.join(bits)
131
132 # some helpers which seem to be cross-platform enough
133
134 def _execute_c_compiler(self, cc, args, outname, cwd=None):
135 #log.execute(cc + ' ' + ' '.join(args))
136 # 'cc' can also contain some options for the C compiler;
137 # e.g. it can be "gcc -m32". We handle it by splitting on ' '.
138 cclist = cc.split()
139 cc = cclist[0]
140 args = cclist[1:] + args
141 returncode, stdout, stderr = _run_subprocess(cc, args, self.c_environ,
142 cwd)
143 self._handle_error(returncode, stdout, stderr, outname)
144
145 def _handle_error(self, returncode, stdout, stderr, outname):
146 if returncode != 0:
147 errorfile = outname.new(ext='errors')
148 errorfile.write(stderr, 'wb')
149 if self.log_errors:
150 stderrlines = stderr.splitlines()
151 for line in stderrlines:
152 log.Error(line)
153 # ^^^ don't use ERROR, because it might actually be fine.
154 # Also, ERROR confuses lib-python/conftest.py.
155 raise CompilationError(stdout, stderr)
156 else:
157 if self.log_errors:
158 for line in stderr.splitlines():
159 log.WARNING(line)
160
161 def _make_o_file(self, cfile, ext):
162 """Create an object file name under the udir for a .c file"""
163 ofile = cfile.new(ext=ext)
164 if ofile.relto(udir):
165 return ofile
166 assert ofile.relto(rpythonroot), (
167 "%r should be relative to either %r or %r" % (
168 ofile, rpythonroot, udir))
169 ofile = udir.join(ofile.relto(rpythonroot))
170 ofile.dirpath().ensure(dir=True)
171 return ofile
172
173 def preprocess_include_dirs(self, include_dirs):
174 if 'PYPY_LOCALBASE' in os.environ:
175 dirs = list(self._preprocess_include_dirs(include_dirs))
176 return [os.environ['PYPY_LOCALBASE'] + '/include'] + dirs
177 return self._preprocess_include_dirs(include_dirs)
178
179 def _preprocess_include_dirs(self, include_dirs):
180 return include_dirs
181
182 def _compile_args_from_eci(self, eci, standalone):
183 include_dirs = self.preprocess_include_dirs(eci.include_dirs)
184 args = self._includedirs(include_dirs)
185 if standalone:
186 extra = self.standalone_only
187 else:
188 extra = self.get_shared_only_compile_flags()
189 cflags = list(self.cflags) + list(extra)
190 return (cflags + list(eci.compile_extra) + args)
191
192 def get_shared_only_compile_flags(self):
193 return tuple(self.shared_only)
194
195 def preprocess_library_dirs(self, library_dirs):
196 if 'PYPY_LOCALBASE' in os.environ:
197 dirs = list(self._preprocess_library_dirs(library_dirs))
198 return [os.environ['PYPY_LOCALBASE'] + '/lib'] + dirs
199 return self._preprocess_library_dirs(library_dirs)
200
201 def _preprocess_library_dirs(self, library_dirs):
202 return library_dirs
203
204 def _link_args_from_eci(self, eci, standalone):
205 library_dirs = self.preprocess_library_dirs(eci.library_dirs)
206 library_dirs = self._libdirs(library_dirs)
207 libraries = self._libs(eci.libraries)
208 link_files = self._linkfiles(eci.link_files)
209 export_flags = self._exportsymbols_link_flags()
210 return (library_dirs + list(self.link_flags) + export_flags +
211 link_files + list(eci.link_extra) + libraries +
212 list(self.extra_libs))
213
214 def _exportsymbols_link_flags(self):
215 return []
216
217 def _finish_linking(self, ofiles, eci, outputfilename, standalone):
218 if outputfilename is None:
219 outputfilename = ofiles[0].purebasename
220 if ofiles:
221 dirname = ofiles[0].dirpath()
222 else:
223 dirname = udir.join('module_cache')
224 exe_name = dirname.join(outputfilename, abs=True)
225 if standalone:
226 if self.exe_ext:
227 exe_name += '.' + self.exe_ext
228 else:
229 exe_name += '.' + self.so_ext
230 if eci.use_cpp_linker:
231 cc_link = 'g++' # XXX hard-coded so far
232 else:
233 cc_link = self.cc
234 largs = self._link_args_from_eci(eci, standalone)
235 return self._link(cc_link, ofiles, largs, standalone, exe_name)
236
237 # below are some detailed information for platforms
238
239 def include_dirs_for_libffi(self):
240 dirs = self._include_dirs_for_libffi()
241 if 'PYPY_LOCALBASE' in os.environ:
242 return [os.environ['PYPY_LOCALBASE'] + '/include'] + dirs
243 return dirs
244
245 def library_dirs_for_libffi(self):
246 dirs = self._library_dirs_for_libffi()
247 if 'PYPY_LOCALBASE' in os.environ:
248 return [os.environ['PYPY_LOCALBASE'] + '/lib'] + dirs
249 return dirs
250
251 def _include_dirs_for_libffi(self):
252 raise NotImplementedError("Needs to be overwritten")
253
254 def _library_dirs_for_libffi(self):
255 raise NotImplementedError("Needs to be overwritten")
256
257 def include_dirs_for_openssl(self):
258 dirs = self._include_dirs_for_openssl()
259 if 'PYPY_LOCALBASE' in os.environ:
260 return [os.environ['PYPY_LOCALBASE'] + '/include'] + dirs
261 return dirs
262
263 def library_dirs_for_openssl(self):
264 dirs = self._library_dirs_for_openssl()
265 if 'PYPY_LOCALBASE' in os.environ:
266 return [os.environ['PYPY_LOCALBASE'] + '/lib'] + dirs
267 return dirs
268
269 def _include_dirs_for_openssl(self):
270 return []
271
272 def _library_dirs_for_openssl(self):
273 return []
274
275 def check___thread(self):
276 return True
277
278 def get_multiarch(self):
279 return ''
280
281 if sys.platform.startswith('linux'):
282 from rpython.translator.platform.linux import Linux
283 host_factory = Linux
284 elif sys.platform == 'darwin':
285 from rpython.translator.platform.darwin import Darwin_i386, Darwin_x86_64, Darwin_PowerPC, Darwin_arm64
286 import platform
287
288 if platform.machine() == 'Power Macintosh':
289 host_factory = Darwin_PowerPC
290 elif sys.maxint <= 2147483647:
291 host_factory = Darwin_i386
292 elif platform.machine() == 'x86_64':
293 host_factory = Darwin_x86_64
294 elif platform.machine() == 'arm64':
295 host_factory = Darwin_arm64
296 else:
297 assert False, platform.machine()
298 elif "gnukfreebsd" in sys.platform:
299 from rpython.translator.platform.freebsd import GNUkFreebsd, GNUkFreebsd_64
300 import platform
301 if platform.architecture()[0] == '32bit':
302 host_factory = GNUkFreebsd
303 else:
304 host_factory = GNUkFreebsd_64
305 elif "freebsd" in sys.platform:
306 from rpython.translator.platform.freebsd import Freebsd, Freebsd_64
307 import platform
308 if platform.architecture()[0] == '32bit':
309 host_factory = Freebsd
310 else:
311 host_factory = Freebsd_64
312 elif sys.platform.startswith('netbsd'):
313 from rpython.translator.platform.netbsd import Netbsd, Netbsd_64
314 import platform
315 if platform.architecture()[0] == '32bit':
316 host_factory = Netbsd
317 else:
318 host_factory = Netbsd_64
319 elif "openbsd" in sys.platform:
320 from rpython.translator.platform.openbsd import OpenBSD, OpenBSD_64
321 import platform
322 if platform.architecture()[0] == '32bit':
323 host_factory = OpenBSD
324 else:
325 host_factory = OpenBSD_64
326 elif sys.platform.startswith('gnu'):
327 from rpython.translator.platform.hurd import Hurd
328 import platform
329 if platform.architecture()[0] == '32bit':
330 host_factory = Hurd
331 else:
332 host_factory = Hurd_64
333 elif os.name == 'nt':
334 from rpython.translator.platform.windows import Windows, Windows_x64
335 import platform
336 if platform.architecture()[0] == '32bit':
337 host_factory = Windows
338 else:
339 host_factory = Windows_x64
340 elif sys.platform == 'cygwin':
341 from rpython.translator.platform.cygwin import Cygwin, Cygwin64
342 import platform
343 if platform.architecture()[0] == '32bit':
344 host_factory = Cygwin
345 else:
346 host_factory = Cygwin64
347 else:
348 raise ValueError('unknown sys.platform "%s"', sys.platform)
349
350 platform = host = host_factory()
351
352 def pick_platform(new_platform, cc):
353 if new_platform == 'host':
354 return host_factory(cc)
355 elif new_platform == 'arm':
356 from rpython.translator.platform.arm import ARM
357 return ARM(cc)
358 else:
359 raise ValueError("platform = %s" % (new_platform,))
360
361 def set_platform(new_platform, cc):
362 global platform
363 platform = pick_platform(new_platform, cc)
364 if not platform:
365 raise ValueError("pick_platform(%r, %s) failed"%(new_platform, cc))
366 log.msg("Set platform with %r cc=%s, using cc=%r, version=%r" % (new_platform, cc,
367 getattr(platform, 'cc','Unknown'),
368 getattr(platform, 'version','Unknown'),
369 ))
370
371 if new_platform == 'host':
372 global host
373 host = platform
374
375
376 def is_host_build():
377 return host == platform