Debian Codegraph @

rpython/rtyper/tool/rffi_platform.py

raw symbols SCIP
1 #! /usr/bin/env python
2 from __future__ import print_function
3
4 import os
5 import sys
6 import struct
7 import py
8 from rpython.rtyper.lltypesystem import lltype
9 from rpython.rtyper.lltypesystem import rffi
10 from rpython.rtyper.lltypesystem import llmemory
11 from rpython.tool.gcc_cache import build_executable_cache, try_compile_cache
12 from rpython.translator.tool.cbuild import ExternalCompilationInfo
13 from rpython.translator.platform import CompilationError
14 from rpython.tool.udir import udir
15 from rpython.rlib.rarithmetic import r_uint, r_longlong, r_ulonglong, intmask, LONG_BIT
16
17 # ____________________________________________________________
18 #
19 # Helpers for simple cases
20
21 def eci_from_header(c_header_source, include_dirs=None, libraries=None):
22 if include_dirs is None:
23 include_dirs = []
24 if libraries is None:
25 libraries = []
26 return ExternalCompilationInfo(
27 post_include_bits=[c_header_source],
28 include_dirs=include_dirs,
29 libraries=libraries,
30 )
31
32 def getstruct(name, c_header_source, interesting_fields):
33 class CConfig:
34 _compilation_info_ = eci_from_header(c_header_source)
35 STRUCT = Struct(name, interesting_fields)
36 return configure(CConfig)['STRUCT']
37
38 def getsimpletype(name, c_header_source, ctype_hint=rffi.INT):
39 class CConfig:
40 _compilation_info_ = eci_from_header(c_header_source)
41 TYPE = SimpleType(name, ctype_hint)
42 return configure(CConfig)['TYPE']
43
44 def getconstantinteger(name, c_header_source):
45 class CConfig:
46 _compilation_info_ = eci_from_header(c_header_source)
47 CONST = ConstantInteger(name)
48 return configure(CConfig)['CONST']
49
50 def getdefined(macro, c_header_source):
51 class CConfig:
52 _compilation_info_ = eci_from_header(c_header_source)
53 DEFINED = Defined(macro)
54 return configure(CConfig)['DEFINED']
55
56 def getdefineddouble(macro, c_header_source):
57 class CConfig:
58 _compilation_info_ = eci_from_header(c_header_source)
59 DEFINED = DefinedConstantDouble(macro)
60 return configure(CConfig)['DEFINED']
61
62 def getdefinedinteger(macro, c_header_source):
63 class CConfig:
64 _compilation_info_ = eci_from_header(c_header_source)
65 DEFINED = DefinedConstantInteger(macro)
66 return configure(CConfig)['DEFINED']
67
68 def getdefinedstring(macro, c_header_source):
69 class CConfig:
70 _compilation_info_ = eci_from_header(c_header_source)
71 DEFINED = DefinedConstantString(macro)
72 return configure(CConfig)['DEFINED']
73
74 def getintegerfunctionresult(function, args=None, c_header_source='', includes=[]):
75 class CConfig:
76 _compilation_info_ = eci_from_header(c_header_source)
77 RESULT = IntegerFunctionResult(function, args)
78 if includes:
79 CConfig._compilation_info_.includes = includes
80 return configure(CConfig)['RESULT']
81
82 def has(name, c_header_source, include_dirs=None, libraries=None):
83 class CConfig:
84 _compilation_info_ = \
85 eci_from_header(c_header_source, include_dirs, libraries)
86 HAS = Has(name)
87 return configure(CConfig)['HAS']
88
89 def verify_eci(eci):
90 """Check if a given ExternalCompilationInfo compiles and links.
91 If not, raises CompilationError."""
92 class CConfig:
93 _compilation_info_ = eci
94 WORKS = Works()
95 configure(CConfig)
96
97 def checkcompiles(expression, c_header_source, include_dirs=None):
98 """Check if expression compiles. If not, returns False"""
99 return has(expression, c_header_source, include_dirs)
100
101 def sizeof(name, eci, **kwds):
102 class CConfig:
103 _compilation_info_ = eci
104 SIZE = SizeOf(name)
105 for k, v in kwds.items():
106 setattr(CConfig, k, v)
107 return configure(CConfig)['SIZE']
108
109 def memory_alignment():
110 """Return the alignment (in bytes) of memory allocations.
111 This is enough to make sure a structure with pointers and 'double'
112 fields is properly aligned."""
113 global _memory_alignment
114 if _memory_alignment is None:
115 if sys.platform == 'win32':
116 _memory_alignment = LONG_BIT // 8
117 else:
118 S = getstruct('struct memory_alignment_test', """
119 struct memory_alignment_test {
120 double d;
121 void* p;
122 };
123 """, [])
124 result = S._hints['align']
125 assert result & (result-1) == 0, "not a power of two??"
126 _memory_alignment = result
127 return _memory_alignment
128 _memory_alignment = None
129
130 # ____________________________________________________________
131 #
132 # General interface
133
134 class ConfigResult:
135 def __init__(self, eci, info):
136 self.eci = eci
137 self.info = info
138 self.result = {}
139
140 def get_entry_result(self, entry):
141 try:
142 return self.result[entry]
143 except KeyError:
144 pass
145 info = self.info[entry]
146 self.result[entry] = entry.build_result(info, self)
147 return self.result[entry]
148
149
150 class _CWriter(object):
151 """ A simple class which aggregates config parts
152 """
153 def __init__(self, eci):
154 self.path = uniquefilepath()
155 self.f = self.path.open("w")
156 self.eci = eci
157
158 def write_header(self):
159 f = self.f
160 self.eci.write_c_header(f)
161 print(C_HEADER, file=f)
162 print(file=f)
163
164 def write_entry(self, key, entry):
165 f = self.f
166 print('void dump_section_%s(void) {' % (key,), file=f)
167 for line in entry.prepare_code():
168 if line and line[0] != '#':
169 line = '\t' + line
170 print(line, file=f)
171 print('}', file=f)
172 print(file=f)
173
174 def write_entry_main(self, key):
175 print('\tprintf("-+- %s\\n");' % (key,), file=self.f)
176 print('\tdump_section_%s();' % (key,), file=self.f)
177 print('\tprintf("---\\n");', file=self.f)
178
179 def start_main(self):
180 print('int main(int argc, char *argv[]) {', file=self.f)
181
182 def close(self):
183 f = self.f
184 print('\treturn 0;', file=f)
185 print('}', file=f)
186 f.close()
187
188 def ask_gcc(self, question):
189 self.start_main()
190 self.f.write(question + "\n")
191 self.close()
192 try_compile_cache([self.path], self.eci)
193
194 def configure(CConfig, ignore_errors=False):
195 """Examine the local system by running the C compiler.
196 The CConfig class contains CConfigEntry attribues that describe
197 what should be inspected; configure() returns a dict mapping
198 names to the results.
199 """
200 for attr in ['_includes_', '_libraries_', '_sources_', '_library_dirs_',
201 '_include_dirs_', '_header_']:
202 assert not hasattr(CConfig, attr), \
203 "Found legacy attribute %s on CConfig" % attr
204
205 eci = CConfig._compilation_info_
206 entries = {}
207 for key in dir(CConfig):
208 value = getattr(CConfig, key)
209 if isinstance(value, CConfigEntry):
210 entries[key] = value
211
212 res = {}
213 if entries: # can be empty if there are only CConfigSingleEntries
214 results = configure_entries(
215 entries.values(), eci, ignore_errors=ignore_errors)
216 for name, result in zip(entries, results):
217 res[name] = result
218
219 for key in dir(CConfig):
220 value = getattr(CConfig, key)
221 if isinstance(value, CConfigSingleEntry):
222 writer = _CWriter(eci)
223 writer.write_header()
224 res[key] = value.question(writer.ask_gcc)
225
226 return res
227
228
229 def configure_entries(entries, eci, ignore_errors=False):
230 writer = _CWriter(eci)
231 writer.write_header()
232 for i, entry in enumerate(entries):
233 writer.write_entry(str(i), entry)
234
235 writer.start_main()
236 for i, entry in enumerate(entries):
237 writer.write_entry_main(str(i))
238 writer.close()
239
240 infolist = list(run_example_code(
241 writer.path, eci, ignore_errors=ignore_errors))
242 assert len(infolist) == len(entries)
243
244 resultinfo = {}
245 for info, entry in zip(infolist, entries):
246 resultinfo[entry] = info
247
248 result = ConfigResult(eci, resultinfo)
249 for entry in entries:
250 yield result.get_entry_result(entry)
251
252 # ____________________________________________________________
253
254
255 class CConfigEntry(object):
256 "Abstract base class."
257
258
259 class Struct(CConfigEntry):
260 """An entry in a CConfig class that stands for an externally
261 defined structure.
262 """
263 def __init__(self, name, interesting_fields, ifdef=None, adtmeths={}):
264 self.name = name
265 self.interesting_fields = interesting_fields
266 self.ifdef = ifdef
267 self.adtmeths = adtmeths
268
269 def prepare_code(self):
270 if self.ifdef is not None:
271 yield '#ifdef %s' % (self.ifdef,)
272 yield 'typedef %s platcheck_t;' % (self.name,)
273 yield 'typedef struct {'
274 yield ' char c;'
275 yield ' platcheck_t s;'
276 yield '} platcheck2_t;'
277 yield ''
278 yield 'platcheck_t s;'
279 if self.ifdef is not None:
280 yield 'dump("defined", 1);'
281 yield 'dump("align", offsetof(platcheck2_t, s));'
282 yield 'dump("size", sizeof(platcheck_t));'
283 for fieldname, fieldtype in self.interesting_fields:
284 yield 'dump("fldofs %s", offsetof(platcheck_t, %s));'%(
285 fieldname, fieldname)
286 yield 'dump("fldsize %s", sizeof(s.%s));' % (
287 fieldname, fieldname)
288 if fieldtype in integer_class:
289 yield 's.%s = 0; s.%s = ~s.%s;' % (fieldname,
290 fieldname,
291 fieldname)
292 yield 'dump("fldunsigned %s", s.%s > 0);' % (fieldname,
293 fieldname)
294 if self.ifdef is not None:
295 yield '#else'
296 yield 'dump("defined", 0);'
297 yield '#endif'
298
299 def build_result(self, info, config_result):
300 if self.ifdef is not None:
301 if not info['defined']:
302 return None
303 layout = [None] * info['size']
304 for fieldname, fieldtype in self.interesting_fields:
305 if isinstance(fieldtype, Struct):
306 offset = info['fldofs ' + fieldname]
307 size = info['fldsize ' + fieldname]
308 c_fieldtype = config_result.get_entry_result(fieldtype)
309 layout_addfield(layout, offset, c_fieldtype, fieldname)
310 else:
311 offset = info['fldofs ' + fieldname]
312 size = info['fldsize ' + fieldname]
313 sign = info.get('fldunsigned ' + fieldname, False)
314 if is_array_nolength(fieldtype):
315 pass # ignore size and sign
316 elif (size, sign) != rffi.size_and_sign(fieldtype):
317 fieldtype = fixup_ctype(fieldtype, fieldname, (size, sign))
318 layout_addfield(layout, offset, fieldtype, fieldname)
319
320 n = 0
321 padfields = []
322 for i, cell in enumerate(layout):
323 if cell is not None:
324 continue
325 name = '_pad%d' % (n,)
326 layout_addfield(layout, i, rffi.UCHAR, name)
327 padfields.append('c_' + name)
328 n += 1
329
330 # build the lltype Structure
331 seen = {}
332 fields = []
333 fieldoffsets = []
334 for offset, cell in enumerate(layout):
335 if cell in seen:
336 continue
337 fields.append((cell.name, cell.ctype))
338 fieldoffsets.append(offset)
339 seen[cell] = True
340
341 allfields = tuple(['c_' + name for name, _ in fields])
342 padfields = tuple(padfields)
343 name = self.name
344 eci = config_result.eci
345 padding_drop = PaddingDrop(name, allfields, padfields, eci)
346 hints = {'align': info['align'],
347 'size': info['size'],
348 'fieldoffsets': tuple(fieldoffsets),
349 'padding': padfields,
350 'get_padding_drop': padding_drop,
351 'eci': eci}
352 if name.startswith('struct '):
353 name = name[7:]
354 else:
355 hints['typedef'] = True
356 kwds = {'hints': hints, 'adtmeths': self.adtmeths}
357 return rffi.CStruct(name, *fields, **kwds)
358
359 class SimpleType(CConfigEntry):
360 """An entry in a CConfig class that stands for an externally
361 defined simple numeric type.
362 """
363 def __init__(self, name, ctype_hint=rffi.INT, ifdef=None):
364 self.name = name
365 self.ctype_hint = ctype_hint
366 self.ifdef = ifdef
367
368 def prepare_code(self):
369 if self.ifdef is not None:
370 yield '#ifdef %s' % (self.ifdef,)
371 yield 'typedef %s platcheck_t;' % (self.name,)
372 yield ''
373 yield 'platcheck_t x;'
374 if self.ifdef is not None:
375 yield 'dump("defined", 1);'
376 yield 'dump("size", sizeof(platcheck_t));'
377 if self.ctype_hint in integer_class:
378 yield 'x = 0; x = ~x;'
379 yield 'dump("unsigned", x > 0);'
380 if self.ifdef is not None:
381 yield '#else'
382 yield 'dump("defined", 0);'
383 yield '#endif'
384
385 def build_result(self, info, config_result):
386 if self.ifdef is not None and not info['defined']:
387 return None
388 size = info['size']
389 sign = info.get('unsigned', False)
390 ctype = self.ctype_hint
391 if (size, sign) != rffi.size_and_sign(ctype):
392 ctype = fixup_ctype(ctype, self.name, (size, sign))
393 return ctype
394
395
396 class ConstantInteger(CConfigEntry):
397 """An entry in a CConfig class that stands for an externally
398 defined integer constant.
399 """
400 def __init__(self, name):
401 self.name = name
402
403 def prepare_code(self):
404 yield 'if ((%s) <= 0) {' % (self.name,)
405 yield ' long long x = (long long)(%s);' % (self.name,)
406 yield ' printf("value: %lld\\n", x);'
407 yield '} else {'
408 yield ' unsigned long long x = (unsigned long long)(%s);' % (
409 self.name,)
410 yield ' printf("value: %llu\\n", x);'
411 yield '}'
412
413 def build_result(self, info, config_result):
414 return expose_value_as_rpython(info['value'])
415
416 class IntegerFunctionResult(CConfigEntry):
417 """An entry in a CConfig class that stands for an externally
418 defined integer constant.
419 """
420 def __init__(self, name, args=None):
421 self.name = name
422 self.args = args if args else []
423
424 def prepare_code(self):
425 yield 'long int result = %s(%s);' % (self.name,
426 ', '.join([str(s) for s in self.args]))
427 yield 'if ((result) <= 0) {'
428 yield ' long long x = (long long)(result);'
429 yield ' printf("value: %lld\\n", x);'
430 yield '} else {'
431 yield ' unsigned long long x = (unsigned long long)(result);'
432 yield ' printf("value: %llu\\n", x);'
433 yield '}'
434
435 def build_result(self, info, config_result):
436 return expose_value_as_rpython(info['value'])
437
438 class DefinedConstantInteger(CConfigEntry):
439 """An entry in a CConfig class that stands for an externally
440 defined integer constant. If not #defined the value will be None.
441 """
442 def __init__(self, macro):
443 self.name = self.macro = macro
444
445 def prepare_code(self):
446 yield '#ifdef %s' % self.macro
447 yield 'dump("defined", 1);'
448 yield 'if ((%s) <= 0) {' % (self.macro,)
449 yield ' long long x = (long long)(%s);' % (self.macro,)
450 yield ' printf("value: %lld\\n", x);'
451 yield '} else {'
452 yield ' unsigned long long x = (unsigned long long)(%s);' % (
453 self.macro,)
454 yield ' printf("value: %llu\\n", x);'
455 yield '}'
456 yield '#else'
457 yield 'dump("defined", 0);'
458 yield '#endif'
459
460 def build_result(self, info, config_result):
461 if info["defined"]:
462 return expose_value_as_rpython(info['value'])
463 return None
464
465 class DefinedConstantDouble(CConfigEntry):
466
467 def __init__(self, macro):
468 self.name = self.macro = macro
469
470 def prepare_code(self):
471 yield '#ifdef %s' % (self.macro,)
472 yield 'int i;'
473 yield 'double x = %s;' % (self.macro,)
474 yield 'unsigned char *p = (unsigned char *)&x;'
475 yield 'dump("defined", 1);'
476 yield 'for (i = 0; i < 8; i++) {'
477 yield ' printf("value_%d: %d\\n", i, p[i]);'
478 yield '}'
479 yield '#else'
480 yield 'dump("defined", 0);'
481 yield '#endif'
482
483 def build_result(self, info, config_result):
484 if info["defined"]:
485 data = [chr(info["value_%d" % (i,)]) for i in range(8)]
486 # N.B. This depends on IEEE 754 being implemented.
487 return struct.unpack("d", ''.join(data))[0]
488 return None
489
490 class DefinedConstantString(CConfigEntry):
491 """
492 """
493 def __init__(self, macro, name=None):
494 self.macro = macro
495 self.name = name or macro
496
497 def prepare_code(self):
498 yield '#ifdef %s' % self.macro
499 yield 'int i;'
500 yield 'const char *p = %s;' % self.name
501 yield 'dump("defined", 1);'
502 yield 'for (i = 0; p[i] != 0; i++ ) {'
503 yield ' printf("value_%d: %d\\n", i, (int)(unsigned char)p[i]);'
504 yield '}'
505 yield '#else'
506 yield 'dump("defined", 0);'
507 yield '#endif'
508
509 def build_result(self, info, config_result):
510 if info["defined"]:
511 string = ''
512 d = 0
513 while info.has_key('value_%d' % d):
514 string += chr(info['value_%d' % d])
515 d += 1
516 return string
517 return None
518
519
520 class Defined(CConfigEntry):
521 """A boolean, corresponding to an #ifdef.
522 """
523 def __init__(self, macro):
524 self.macro = macro
525 self.name = macro
526
527 def prepare_code(self):
528 yield '#ifdef %s' % (self.macro,)
529 yield 'dump("defined", 1);'
530 yield '#else'
531 yield 'dump("defined", 0);'
532 yield '#endif'
533
534 def build_result(self, info, config_result):
535 return bool(info['defined'])
536
537 class CConfigSingleEntry(object):
538 """ An abstract class of type which requires
539 gcc succeeding/failing instead of only asking
540 """
541 pass
542
543 class Has(CConfigSingleEntry):
544 def __init__(self, name):
545 self.name = name
546
547 def question(self, ask_gcc):
548 try:
549 ask_gcc('(void)' + self.name + ';')
550 return True
551 except CompilationError:
552 return False
553
554 class Works(CConfigSingleEntry):
555 def question(self, ask_gcc):
556 ask_gcc("")
557
558 class SizeOf(CConfigEntry):
559 """An entry in a CConfig class that stands for
560 some external opaque type
561 """
562 def __init__(self, name):
563 self.name = name
564
565 def prepare_code(self):
566 yield 'dump("size", sizeof(%s));' % self.name
567
568 def build_result(self, info, config_result):
569 return info['size']
570
571 # ____________________________________________________________
572
573 class PaddingDrop(object):
574 # Compute (lazily) the padding_drop for a structure.
575 # See test_generate_padding for more information.
576 cache = None
577
578 def __init__(self, name, allfields, padfields, eci):
579 self.name = name
580 self.allfields = allfields
581 self.padfields = padfields
582 self.eci = eci
583
584 def __call__(self, types):
585 if self.cache is None:
586 self.compute_now(types)
587 return self.cache
588
589 def compute_now(self, types):
590 # Some simplifying assumptions there. We assume that all fields
591 # are either integers or pointers, so can be written in C as '0'.
592 # We also assume that the C backend gives us in 'types' a dictionary
593 # mapping non-padding field names to their C type (without '@').
594 drops = []
595 staticfields = []
596 consecutive_pads = []
597 for fieldname in self.allfields:
598 if fieldname in self.padfields:
599 consecutive_pads.append(fieldname)
600 continue
601 staticfields.append(types[fieldname])
602 if consecutive_pads:
603 # In that case we have to ask: how many of these pads are
604 # really needed? The correct answer might be between none
605 # and all of the pads listed in 'consecutive_pads'.
606 for i in range(len(consecutive_pads)+1):
607 class CConfig:
608 _compilation_info_ = self.eci
609 FIELDLOOKUP = _PaddingDropFieldLookup(self.name,
610 staticfields,
611 fieldname)
612 try:
613 got = configure(CConfig)['FIELDLOOKUP']
614 if got == 1:
615 break # found
616 except CompilationError:
617 pass
618 staticfields.insert(-1, None)
619 else:
620 raise Exception("could not determine the detailed field"
621 " layout of %r" % (self.name,))
622 # succeeded with 'i' pads. Drop all pads beyond that.
623 drops += consecutive_pads[i:]
624 consecutive_pads = []
625 drops += consecutive_pads # drop the final pads too
626 self.cache = drops
627
628 class _PaddingDropFieldLookup(CConfigEntry):
629 def __init__(self, name, staticfields, fieldname):
630 self.name = name
631 self.staticfields = staticfields
632 self.fieldname = fieldname
633
634 def prepare_code(self):
635 yield 'typedef %s platcheck_t;' % (self.name,)
636 yield 'static platcheck_t s = {'
637 for i, type in enumerate(self.staticfields):
638 if i == len(self.staticfields)-1:
639 value = -1
640 else:
641 value = 0
642 if type:
643 yield '\t(%s)%s,' % (type, value)
644 else:
645 yield '\t%s,' % (value,)
646 yield '};'
647 fieldname = self.fieldname
648 assert fieldname.startswith('c_')
649 yield 'dump("fieldlookup", s.%s != 0);' % (fieldname[2:],)
650
651 def build_result(self, info, config_result):
652 return info['fieldlookup']
653
654 # ____________________________________________________________
655 #
656 # internal helpers
657
658 def uniquefilepath(LAST=[0]):
659 i = LAST[0]
660 LAST[0] += 1
661 return udir.join('platcheck_%d.c' % i)
662
663 integer_class = [rffi.SIGNEDCHAR, rffi.UCHAR, rffi.CHAR,
664 rffi.SHORT, rffi.USHORT,
665 rffi.INT, rffi.UINT,
666 rffi.INT_real, rffi.UINT_real,
667 rffi.LONG, rffi.ULONG,
668 rffi.LONGLONG, rffi.ULONGLONG]
669 # XXX SIZE_T?
670
671 float_class = [rffi.DOUBLE]
672
673 def _sizeof(tp):
674 # XXX don't use this! internal purpose only, not really a sane logic
675 if isinstance(tp, lltype.Struct):
676 return sum([_sizeof(i) for i in tp._flds.values()])
677 return rffi.sizeof(tp)
678
679 class Field(object):
680 def __init__(self, name, ctype):
681 self.name = name
682 self.ctype = ctype
683 def __repr__(self):
684 return '<field %s: %s>' % (self.name, self.ctype)
685
686 def is_array_nolength(TYPE):
687 return isinstance(TYPE, lltype.Array) and TYPE._hints.get('nolength', False)
688
689 def layout_addfield(layout, offset, ctype, prefix):
690 if is_array_nolength(ctype):
691 size = len(layout) - offset # all the rest of the struct
692 else:
693 size = _sizeof(ctype)
694 name = prefix
695 i = 0
696 while name in layout:
697 i += 1
698 name = '%s_%d' % (prefix, i)
699 field = Field(name, ctype)
700 for i in range(offset, offset+size):
701 assert layout[i] is None, "%s overlaps %r" % (name, layout[i])
702 layout[i] = field
703 return field
704
705 def fixup_ctype(fieldtype, fieldname, expected_size_and_sign):
706 for typeclass in [integer_class, float_class]:
707 if fieldtype in typeclass:
708 for ctype in typeclass:
709 if rffi.size_and_sign(ctype) == expected_size_and_sign:
710 return ctype
711 if isinstance(fieldtype, lltype.FixedSizeArray):
712 size, _ = expected_size_and_sign
713 return lltype.FixedSizeArray(fieldtype.OF, size/_sizeof(fieldtype.OF))
714 raise TypeError("conflict between translating python and compiler field"
715 " type %r for symbol %r, expected size+sign %r" % (
716 fieldtype, fieldname, expected_size_and_sign))
717
718 def expose_value_as_rpython(value):
719 if intmask(value) == value:
720 return value
721 if r_uint(value) == value:
722 return r_uint(value)
723 try:
724 if r_longlong(value) == value:
725 return r_longlong(value)
726 except OverflowError:
727 pass
728 if r_ulonglong(value) == value:
729 return r_ulonglong(value)
730 raise OverflowError("value %d does not fit into any RPython integer type"
731 % (value,))
732
733 C_HEADER = """
734 #include <stdio.h>
735 #include <stddef.h> /* for offsetof() */
736
737 void dump(char* key, int value) {
738 printf("%s: %d\\n", key, value);
739 }
740 """
741
742 def run_example_code(filepath, eci, ignore_errors=False):
743 eci = eci.convert_sources_to_files()
744 files = [filepath]
745 output = build_executable_cache(files, eci, ignore_errors=ignore_errors)
746 if not output.startswith('-+- '):
747 raise Exception("run_example_code failed!\nlocals = %r" % (locals(),))
748 section = None
749 for line in output.splitlines():
750 line = line.strip()
751 if line.startswith('-+- '): # start of a new section
752 section = {}
753 elif line == '---': # section end
754 assert section is not None
755 yield section
756 section = None
757 elif line:
758 assert section is not None
759 key, value = line.split(': ')
760 section[key] = int(value)
761
762 # ____________________________________________________________
763
764 from os.path import dirname
765 import rpython
766
767 PYPY_EXTERNAL_DIR = py.path.local(dirname(rpython.__file__)).join('..', '..')
768 # XXX make this configurable
769 if sys.platform == 'win32':
770 for libdir in [
771 py.path.local('c:/buildslave/support'), # on the bigboard buildbot
772 py.path.local('d:/myslave'), # on the snakepit buildbot
773 ]:
774 if libdir.check():
775 PYPY_EXTERNAL_DIR = libdir
776 break
777
778 def configure_external_library(name, eci, configurations,
779 symbol=None, _cache={}):
780 """try to find the external library.
781 On Unix, this simply tests and returns the given eci.
782
783 On Windows, various configurations may be tried to compile the
784 given eci object. These configurations are a list of dicts,
785 containing:
786
787 - prefix: if an absolute path, will prefix each include and
788 library directories. If a relative path, the external
789 directory is searched for directories which names start
790 with the prefix. The last one in alphabetical order
791 chosen, and becomes the prefix.
792
793 - include_dir: prefix + include_dir is added to the include directories
794
795 - library_dir: prefix + library_dir is added to the library directories
796 """
797
798 if sys.platform != 'win32':
799 configurations = []
800
801 key = (name, eci)
802 try:
803 return _cache[key]
804 except KeyError:
805 last_error = None
806
807 # Always try the default configuration
808 if {} not in configurations:
809 configurations.append({})
810
811 for configuration in configurations:
812 prefix = configuration.get('prefix', '')
813 include_dir = configuration.get('include_dir', '')
814 library_dir = configuration.get('library_dir', '')
815
816 if prefix and not os.path.isabs(prefix):
817 import glob
818
819 entries = glob.glob(str(PYPY_EXTERNAL_DIR.join(prefix + '*')))
820 if entries:
821 # Get last version
822 prefix = sorted(entries)[-1]
823 else:
824 continue
825
826 include_dir = os.path.join(prefix, include_dir)
827 library_dir = os.path.join(prefix, library_dir)
828
829 eci_lib = ExternalCompilationInfo(
830 include_dirs=include_dir and [include_dir] or [],
831 library_dirs=library_dir and [library_dir] or [],
832 )
833 eci_lib = eci_lib.merge(eci)
834
835 # verify that this eci can be compiled
836 try:
837 verify_eci(eci_lib)
838 except CompilationError as e:
839 last_error = e
840 else:
841 _cache[key] = eci_lib
842 return eci_lib
843
844 # Nothing found
845 if last_error:
846 raise last_error
847 else:
848 raise CompilationError("Library %s is not installed" % (name,))
849
850 def configure_boehm(platform=None):
851 if platform is None:
852 from rpython.translator.platform import platform
853 if sys.platform == 'win32':
854 import platform as host_platform # just to ask for the arch. Confusion-alert!
855 if host_platform.architecture()[0] == '32bit':
856 library_dir = 'Release'
857 libraries = ['gc']
858 includes=['gc.h']
859 else:
860 library_dir = ''
861 libraries = ['gc64_dll']
862 includes = ['gc.h']
863 # since config_external_library does not use a platform kwarg,
864 # somehow using a platform kw arg make the merge fail in
865 # config_external_library
866 platform = None
867 else:
868 library_dir = ''
869 libraries = ['gc']
870 includes=['gc/gc.h']
871 try:
872 eci = ExternalCompilationInfo.from_pkg_config('bdw-gc')
873 eci.includes += tuple(includes)
874 return eci
875 except ImportError:
876 eci = ExternalCompilationInfo(
877 platform=platform,
878 includes=includes,
879 libraries=libraries,
880 )
881 return configure_external_library(
882 'gc', eci,
883 [dict(prefix='gc-', include_dir='include', library_dir=library_dir)],
884 symbol='GC_init')
885
886 if __name__ == '__main__':
887 doc = """Example:
888
889 rffi_platform.py -h sys/types.h -h netinet/in.h
890 'struct sockaddr_in'
891 sin_port INT
892 """
893 import getopt
894 opts, args = getopt.gnu_getopt(sys.argv[1:], 'h:')
895 if not args:
896 print(doc, file=sys.stderr)
897 else:
898 assert len(args) % 2 == 1
899 headers = []
900 for opt, value in opts:
901 if opt == '-h':
902 headers.append('#include <%s>' % (value,))
903 name = args[0]
904 fields = []
905 for i in range(1, len(args), 2):
906 ctype = getattr(rffi, args[i+1])
907 fields.append((args[i], ctype))
908
909 S = getstruct(name, '\n'.join(headers), fields)
910
911 for name in S._names:
912 print(name, getattr(S, name))