Debian Codegraph @

rpython/translator/tool/cbuild.py

raw symbols SCIP
1 from __future__ import print_function
2
3 import py
4 import sys, os, subprocess
5
6 from rpython.translator.platform import host
7 from rpython.translator import cdir
8 from rpython.tool.udir import udir
9
10
11 class ExternalCompilationInfo(object):
12
13 _ATTRIBUTES = ['pre_include_bits', 'includes', 'include_dirs',
14 'post_include_bits', 'libraries', 'library_dirs',
15 'separate_module_sources', 'separate_module_files',
16 'compile_extra', 'link_extra',
17 'frameworks', 'link_files', 'testonly_libraries']
18 _DUPLICATES_OK = ['compile_extra', 'link_extra']
19 _EXTRA_ATTRIBUTES = ['use_cpp_linker', 'platform']
20
21 def __init__(self,
22 pre_include_bits = [],
23 includes = [],
24 include_dirs = [],
25 post_include_bits = [],
26 libraries = [],
27 library_dirs = [],
28 separate_module_sources = [],
29 separate_module_files = [],
30 compile_extra = [],
31 link_extra = [],
32 frameworks = [],
33 link_files = [],
34 testonly_libraries = [],
35 use_cpp_linker = False,
36 platform = None):
37 """
38 pre_include_bits: list of pieces of text that should be put at the top
39 of the generated .c files, before any #include. They shouldn't
40 contain an #include themselves. (Duplicate pieces are removed.)
41
42 includes: list of .h file names to be #include'd from the
43 generated .c files.
44
45 include_dirs: list of dir names that is passed to the C compiler
46
47 post_include_bits: list of pieces of text that should be put at the top
48 of the generated .c files, after the #includes. (Duplicate pieces are
49 removed.)
50
51 libraries: list of library names that is passed to the linker
52
53 library_dirs: list of dir names that is passed to the linker
54
55 separate_module_sources: list of multiline strings that are
56 each written to a .c file and compiled separately and linked
57 later on. (If function prototypes are needed for other .c files
58 to access this, they can be put in post_include_bits.)
59
60 separate_module_files: list of .c file names that are compiled
61 separately and linked later on. (If an .h file is needed for
62 other .c files to access this, it can be put in includes.)
63
64 (export_symbols: killed; you need, depending on the case, to
65 add the RPY_EXTERN or RPY_EXPORTED macro just before the
66 declaration of each function in the C header file, as explained
67 in translator/c/src/precommondefs.h; or you need the decorator
68 @rlib.entrypoint.export_symbol)
69
70 compile_extra: list of parameters which will be directly passed to
71 the compiler
72
73 link_extra: list of parameters which will be directly passed to
74 the linker
75
76 frameworks: list of Mac OS X frameworks which should passed to the
77 linker. Use this instead of the 'libraries' parameter if you want to
78 link to a framework bundle. Not suitable for unix-like .dylib
79 installations.
80
81 link_files: list of file names which will be directly passed to the
82 linker
83
84 testonly_libraries: list of libraries that are searched for during
85 testing only, by ll2ctypes. Useful to search for a name in a dynamic
86 library during testing but use the static library for compilation.
87
88 use_cpp_linker: a flag to tell if g++ should be used instead of gcc
89 when linking (a bit custom so far)
90
91 platform: an object that can identify the platform
92 """
93 for name in self._ATTRIBUTES:
94 value = locals()[name]
95 assert isinstance(value, (list, tuple))
96 setattr(self, name, tuple(value))
97 self.use_cpp_linker = use_cpp_linker
98 self._platform = platform
99
100 @property
101 def platform(self):
102 if self._platform is None:
103 from rpython.translator.platform import platform
104 return platform
105 return self._platform
106
107 @classmethod
108 def from_compiler_flags(cls, flags):
109 """Returns a new ExternalCompilationInfo instance by parsing
110 the string 'flags', which is in the typical Unix compiler flags
111 format."""
112 pre_include_bits = []
113 include_dirs = []
114 compile_extra = []
115 for arg in flags.split():
116 if arg.startswith('-I'):
117 include_dirs.append(arg[2:])
118 elif arg.startswith('-D'):
119 macro = arg[2:]
120 if '=' in macro:
121 macro, value = macro.split('=')
122 else:
123 value = '1'
124 if macro == '_XOPEN_SOURCE':
125 # use default _XOPEN_SOURCE since we always define
126 # _GNU_SOURCE, which then defines a _XOPEN_SOURCE itself
127 continue
128 pre_include_bits.append('#define %s %s' % (macro, value))
129 elif arg.startswith('-L') or arg.startswith('-l'):
130 raise ValueError('linker flag found in compiler options: %r'
131 % (arg,))
132 else:
133 compile_extra.append(arg)
134 return cls(pre_include_bits=pre_include_bits,
135 include_dirs=include_dirs,
136 compile_extra=compile_extra)
137
138 @classmethod
139 def from_linker_flags(cls, flags):
140 """Returns a new ExternalCompilationInfo instance by parsing
141 the string 'flags', which is in the typical Unix linker flags
142 format."""
143 libraries = []
144 library_dirs = []
145 link_extra = []
146 for arg in flags.split():
147 if arg.startswith('-L'):
148 library_dirs.append(arg[2:])
149 elif arg.startswith('-l'):
150 libraries.append(arg[2:])
151 elif arg.startswith('-I') or arg.startswith('-D'):
152 raise ValueError('compiler flag found in linker options: %r'
153 % (arg,))
154 else:
155 link_extra.append(arg)
156 return cls(libraries=libraries,
157 library_dirs=library_dirs,
158 link_extra=link_extra)
159
160 @classmethod
161 def from_config_tool(cls, execonfigtool):
162 """Returns a new ExternalCompilationInfo instance by executing
163 the 'execonfigtool' with --cflags and --libs arguments."""
164 path = py.path.local.sysfind(execonfigtool)
165 if not path:
166 raise ImportError("cannot find %r" % (execonfigtool,))
167 # we raise ImportError to be nice to the pypy.config.pypyoption
168 # logic of skipping modules depending on non-installed libs
169 return cls._run_config_tool('"%s"' % (str(path),))
170
171 @classmethod
172 def from_pkg_config(cls, pkgname):
173 """Returns a new ExternalCompilationInfo instance by executing
174 'pkg-config <pkgname>' with --cflags and --libs arguments."""
175 assert isinstance(pkgname, str)
176 try:
177 popen = subprocess.Popen(['pkg-config', pkgname, '--exists'])
178 result = popen.wait()
179 except OSError:
180 result = -1
181 if result != 0:
182 raise ImportError("failed: 'pkg-config %s --exists'" % pkgname)
183 return cls._run_config_tool('pkg-config "%s"' % pkgname)
184
185 @classmethod
186 def _run_config_tool(cls, command):
187 cflags = py.process.cmdexec('%s --cflags' % command)
188 eci1 = cls.from_compiler_flags(cflags)
189 libs = py.process.cmdexec('%s --libs' % command)
190 eci2 = cls.from_linker_flags(libs)
191 return eci1.merge(eci2)
192
193 def _value(self):
194 return tuple([getattr(self, x)
195 for x in self._ATTRIBUTES + self._EXTRA_ATTRIBUTES])
196
197 def __hash__(self):
198 return hash(self._value())
199
200 def __eq__(self, other):
201 return self.__class__ is other.__class__ and \
202 self._value() == other._value()
203
204 def __ne__(self, other):
205 return not self == other
206
207 def __repr__(self):
208 info = []
209 for attr in self._ATTRIBUTES + self._EXTRA_ATTRIBUTES:
210 val = getattr(self, attr)
211 info.append("%s=%s" % (attr, repr(val)))
212 return "<ExternalCompilationInfo (%s)>" % ", ".join(info)
213
214 def merge(self, *others):
215 def unique_elements(l):
216 seen = set()
217 new_objs = []
218 for obj in l:
219 if obj not in seen:
220 new_objs.append(obj)
221 seen.add(obj)
222 return new_objs
223 others = unique_elements(list(others))
224
225 attrs = {}
226 for name in self._ATTRIBUTES:
227 if name in self._DUPLICATES_OK:
228 s = []
229 for i in [self] + others:
230 s += getattr(i, name)
231 attrs[name] = s
232 else:
233 s = set()
234 attr = []
235 for one in [self] + others:
236 for elem in getattr(one, name):
237 if elem not in s:
238 s.add(elem)
239 attr.append(elem)
240 attrs[name] = attr
241 use_cpp_linker = self.use_cpp_linker
242 for other in others:
243 use_cpp_linker = use_cpp_linker or other.use_cpp_linker
244 attrs['use_cpp_linker'] = use_cpp_linker
245 for other in others:
246 if other.platform != self.platform:
247 raise Exception("Mixing ECI for different platforms %s and %s"%
248 (other.platform, self.platform))
249 attrs['platform'] = self.platform
250 return ExternalCompilationInfo(**attrs)
251
252 def write_c_header(self, fileobj):
253 f = open(os.path.join(cdir, 'src', 'precommondefs.h'))
254 fileobj.write(f.read())
255 f.close()
256 print(file=fileobj)
257 for piece in self.pre_include_bits:
258 print(piece, file=fileobj)
259 for path in self.includes:
260 print('#include <%s>' % (path,), file=fileobj)
261 for piece in self.post_include_bits:
262 print(piece, file=fileobj)
263
264 def _copy_attributes(self):
265 d = {}
266 for attr in self._ATTRIBUTES + self._EXTRA_ATTRIBUTES:
267 d[attr] = getattr(self, attr)
268 return d
269
270 def convert_sources_to_files(self, cache_dir=None):
271 if not self.separate_module_sources:
272 return self
273 if cache_dir is None:
274 cache_dir = udir.join('module_cache').ensure(dir=1)
275 num = 0
276 files = []
277 for source in self.separate_module_sources:
278 while 1:
279 filename = cache_dir.join('module_%d.c' % num)
280 num += 1
281 if not filename.check():
282 break
283 f = filename.open("w")
284 self.write_c_header(f)
285 source = str(source)
286 f.write(source)
287 if not source.endswith('\n'):
288 f.write('\n')
289 f.close()
290 files.append(str(filename))
291 d = self._copy_attributes()
292 d['separate_module_sources'] = ()
293 d['separate_module_files'] += tuple(files)
294 return ExternalCompilationInfo(**d)
295
296 def get_module_files(self):
297 d = self._copy_attributes()
298 files = d['separate_module_files']
299 d['separate_module_files'] = ()
300 return files, ExternalCompilationInfo(**d)
301
302 def compile_shared_lib(self, outputfilename=None, ignore_a_files=False,
303 debug_mode=True, defines=[], symbolic=False):
304 self = self.convert_sources_to_files()
305 if ignore_a_files:
306 if not [fn for fn in self.link_files if fn.endswith('.a')]:
307 ignore_a_files = False # there are none
308 if not self.separate_module_files and not ignore_a_files:
309 return self # xxx there was some condition about win32 here
310 else:
311 #basepath = py.path.local(self.separate_module_files[0]).dirpath()
312 basepath = udir.join('shared_cache')
313 if outputfilename is None:
314 # find more or less unique name there
315 pth = basepath.join('externmod').new(ext=host.so_ext)
316 num = 0
317 while pth.check():
318 pth = basepath.join(
319 'externmod_%d' % (num,)).new(ext=host.so_ext)
320 num += 1
321 basepath.ensure(dir=1)
322 outputfilename = str(pth.dirpath().join(pth.purebasename))
323
324 d = self._copy_attributes()
325 if ignore_a_files:
326 d['link_files'] = [fn for fn in d['link_files']
327 if not fn.endswith('.a')]
328 if debug_mode and sys.platform != 'win32':
329 d['compile_extra'] = d['compile_extra'] + ('-g', '-O0')
330 d['compile_extra'] = d['compile_extra'] + (
331 '-DRPY_EXTERN=RPY_EXPORTED',)
332 for define in defines:
333 d['compile_extra'] += ('-D%s' % define,)
334 # On ELF platforms (Linux), prevent symbol interposition: when the host
335 # interpreter (e.g. pypy2.7) also exports symbols like pypysig_counter,
336 # the shared lib's own references would otherwise resolve to the host's
337 # copy via the GOT. -Bsymbolic makes the shared lib bind its own global
338 # symbol references to its own definitions. Only needed when running
339 # under a host interpreter (tests), not during translation.
340 if symbolic and sys.platform not in ('win32', 'darwin'):
341 d['link_extra'] = d['link_extra'] + ('-Wl,-Bsymbolic',)
342 self = ExternalCompilationInfo(**d)
343
344 lib = str(host.compile([], self, outputfilename=outputfilename,
345 standalone=False))
346 d = self._copy_attributes()
347 d['libraries'] += (lib,)
348 d['separate_module_files'] = ()
349 d['separate_module_sources'] = ()
350 return ExternalCompilationInfo(**d)
351
352 def copy_without(self, *names):
353 d = self._copy_attributes()
354 for name in names:
355 del d[name]
356 return ExternalCompilationInfo(**d)