Debian Codegraph @

src/cffi/recompiler.py

raw
1 import io, os, sys, sysconfig
2 from . import ffiplatform, model
3 from .error import VerificationError
4 from .cffi_opcode import *
5
6 VERSION_BASE = 0x2601
7 VERSION_EMBEDDED = 0x2701
8 VERSION_CHAR16CHAR32 = 0x2801
9
10 FREE_THREADED_BUILD = sysconfig.get_config_var("Py_GIL_DISABLED")
11 USE_LIMITED_API = ((sys.platform != 'win32' or sys.version_info < (3, 0) or
12 sys.version_info >= (3, 5)) and
13 # free-threaded build doesn't support the stable ABI until Python 3.15
14 (not FREE_THREADED_BUILD or sys.version_info >= (3, 15)))
15
16 class GlobalExpr:
17 def __init__(self, name, address, type_op, size=0, check_value=0):
18 self.name = name
19 self.address = address
20 self.type_op = type_op
21 self.size = size
22 self.check_value = check_value
23
24 def as_c_expr(self):
25 return ' { "%s", (void *)%s, %s, (void *)%s },' % (
26 self.name, self.address, self.type_op.as_c_expr(), self.size)
27
28 def as_python_expr(self):
29 return "b'%s%s',%d" % (self.type_op.as_python_bytes(), self.name,
30 self.check_value)
31
32 class FieldExpr:
33 def __init__(self, name, field_offset, field_size, fbitsize, field_type_op):
34 self.name = name
35 self.field_offset = field_offset
36 self.field_size = field_size
37 self.fbitsize = fbitsize
38 self.field_type_op = field_type_op
39
40 def as_c_expr(self):
41 spaces = " " * len(self.name)
42 return (' { "%s", %s,\n' % (self.name, self.field_offset) +
43 ' %s %s,\n' % (spaces, self.field_size) +
44 ' %s %s },' % (spaces, self.field_type_op.as_c_expr()))
45
46 def as_python_expr(self):
47 raise NotImplementedError
48
49 def as_field_python_expr(self):
50 if self.field_type_op.op == OP_NOOP:
51 size_expr = ''
52 elif self.field_type_op.op == OP_BITFIELD:
53 size_expr = format_four_bytes(self.fbitsize)
54 else:
55 raise NotImplementedError
56 return "b'%s%s%s'" % (self.field_type_op.as_python_bytes(),
57 size_expr,
58 self.name)
59
60 class StructUnionExpr:
61 def __init__(self, name, type_index, flags, size, alignment, comment,
62 first_field_index, c_fields):
63 self.name = name
64 self.type_index = type_index
65 self.flags = flags
66 self.size = size
67 self.alignment = alignment
68 self.comment = comment
69 self.first_field_index = first_field_index
70 self.c_fields = c_fields
71
72 def as_c_expr(self):
73 return (' { "%s", %d, %s,' % (self.name, self.type_index, self.flags)
74 + '\n %s, %s, ' % (self.size, self.alignment)
75 + '%d, %d ' % (self.first_field_index, len(self.c_fields))
76 + ('/* %s */ ' % self.comment if self.comment else '')
77 + '},')
78
79 def as_python_expr(self):
80 flags = eval(self.flags, G_FLAGS)
81 fields_expr = [c_field.as_field_python_expr()
82 for c_field in self.c_fields]
83 return "(b'%s%s%s',%s)" % (
84 format_four_bytes(self.type_index),
85 format_four_bytes(flags),
86 self.name,
87 ','.join(fields_expr))
88
89 class EnumExpr:
90 def __init__(self, name, type_index, size, signed, allenums):
91 self.name = name
92 self.type_index = type_index
93 self.size = size
94 self.signed = signed
95 self.allenums = allenums
96
97 def as_c_expr(self):
98 lines = [' { "%s", %d, _cffi_prim_int(%s, %s),' % (self.name, self.type_index,
99 self.size, self.signed,)]
100 pending = 0
101 while len(self.allenums) > pending + 110:
102 j = self.allenums.find(',', pending + 100)
103 if j < 0:
104 break
105 j += 1
106 lines.append(' "%s"' % (self.allenums[pending:j],))
107 pending = j
108 lines.append(' "%s" },' % (self.allenums[pending:],))
109 return '\n'.join(lines)
110
111 def as_python_expr(self):
112 prim_index = {
113 (1, 0): PRIM_UINT8, (1, 1): PRIM_INT8,
114 (2, 0): PRIM_UINT16, (2, 1): PRIM_INT16,
115 (4, 0): PRIM_UINT32, (4, 1): PRIM_INT32,
116 (8, 0): PRIM_UINT64, (8, 1): PRIM_INT64,
117 }[self.size, self.signed]
118 return "b'%s%s%s\\x00%s'" % (format_four_bytes(self.type_index),
119 format_four_bytes(prim_index),
120 self.name, self.allenums)
121
122 class TypenameExpr:
123 def __init__(self, name, type_index):
124 self.name = name
125 self.type_index = type_index
126
127 def as_c_expr(self):
128 return ' { "%s", %d },' % (self.name, self.type_index)
129
130 def as_python_expr(self):
131 return "b'%s%s'" % (format_four_bytes(self.type_index), self.name)
132
133
134 # ____________________________________________________________
135
136
137 class Recompiler:
138 _num_externpy = 0
139
140 def __init__(self, ffi, module_name, target_is_python=False):
141 self.ffi = ffi
142 self.module_name = module_name
143 self.target_is_python = target_is_python
144 self._version = VERSION_BASE
145
146 def needs_version(self, ver):
147 self._version = max(self._version, ver)
148
149 def collect_type_table(self):
150 self._typesdict = {}
151 self._generate("collecttype")
152 #
153 all_decls = sorted(self._typesdict, key=str)
154 #
155 # prepare all FUNCTION bytecode sequences first
156 self.cffi_types = []
157 for tp in all_decls:
158 if tp.is_raw_function:
159 assert self._typesdict[tp] is None
160 self._typesdict[tp] = len(self.cffi_types)
161 self.cffi_types.append(tp) # placeholder
162 for tp1 in tp.args:
163 assert isinstance(tp1, (model.VoidType,
164 model.BasePrimitiveType,
165 model.PointerType,
166 model.StructOrUnionOrEnum,
167 model.FunctionPtrType))
168 if self._typesdict[tp1] is None:
169 self._typesdict[tp1] = len(self.cffi_types)
170 self.cffi_types.append(tp1) # placeholder
171 self.cffi_types.append('END') # placeholder
172 #
173 # prepare all OTHER bytecode sequences
174 for tp in all_decls:
175 if not tp.is_raw_function and self._typesdict[tp] is None:
176 self._typesdict[tp] = len(self.cffi_types)
177 self.cffi_types.append(tp) # placeholder
178 if tp.is_array_type and tp.length is not None:
179 self.cffi_types.append('LEN') # placeholder
180 assert None not in self._typesdict.values()
181 #
182 # collect all structs and unions and enums
183 self._struct_unions = {}
184 self._enums = {}
185 for tp in all_decls:
186 if isinstance(tp, model.StructOrUnion):
187 self._struct_unions[tp] = None
188 elif isinstance(tp, model.EnumType):
189 self._enums[tp] = None
190 for i, tp in enumerate(sorted(self._struct_unions,
191 key=lambda tp: tp.name)):
192 self._struct_unions[tp] = i
193 for i, tp in enumerate(sorted(self._enums,
194 key=lambda tp: tp.name)):
195 self._enums[tp] = i
196 #
197 # emit all bytecode sequences now
198 for tp in all_decls:
199 method = getattr(self, '_emit_bytecode_' + tp.__class__.__name__)
200 method(tp, self._typesdict[tp])
201 #
202 # consistency check
203 for op in self.cffi_types:
204 assert isinstance(op, CffiOp)
205 self.cffi_types = tuple(self.cffi_types) # don't change any more
206
207 def _enum_fields(self, tp):
208 # When producing C, expand all anonymous struct/union fields.
209 # That's necessary to have C code checking the offsets of the
210 # individual fields contained in them. When producing Python,
211 # don't do it and instead write it like it is, with the
212 # corresponding fields having an empty name. Empty names are
213 # recognized at runtime when we import the generated Python
214 # file.
215 expand_anonymous_struct_union = not self.target_is_python
216 return tp.enumfields(expand_anonymous_struct_union)
217
218 def _do_collect_type(self, tp):
219 if not isinstance(tp, model.BaseTypeByIdentity):
220 if isinstance(tp, tuple):
221 for x in tp:
222 self._do_collect_type(x)
223 return
224 if tp not in self._typesdict:
225 self._typesdict[tp] = None
226 if isinstance(tp, model.FunctionPtrType):
227 self._do_collect_type(tp.as_raw_function())
228 elif isinstance(tp, model.StructOrUnion):
229 if tp.fldtypes is not None and (
230 tp not in self.ffi._parser._included_declarations):
231 for name1, tp1, _, _ in self._enum_fields(tp):
232 self._do_collect_type(self._field_type(tp, name1, tp1))
233 else:
234 for _, x in tp._get_items():
235 self._do_collect_type(x)
236
237 def _generate(self, step_name):
238 lst = self.ffi._parser._declarations.items()
239 for name, (tp, quals) in sorted(lst):
240 kind, realname = name.split(' ', 1)
241 try:
242 method = getattr(self, '_generate_cpy_%s_%s' % (kind,
243 step_name))
244 except AttributeError:
245 raise VerificationError(
246 "not implemented in recompile(): %r" % name)
247 try:
248 self._current_quals = quals
249 method(tp, realname)
250 except Exception as e:
251 model.attach_exception_info(e, name)
252 raise
253
254 # ----------
255
256 ALL_STEPS = ["global", "field", "struct_union", "enum", "typename"]
257
258 def collect_step_tables(self):
259 # collect the declarations for '_cffi_globals', '_cffi_typenames', etc.
260 self._lsts = {}
261 for step_name in self.ALL_STEPS:
262 self._lsts[step_name] = []
263 self._seen_struct_unions = set()
264 self._generate("ctx")
265 self._add_missing_struct_unions()
266 #
267 for step_name in self.ALL_STEPS:
268 lst = self._lsts[step_name]
269 if step_name != "field":
270 lst.sort(key=lambda entry: entry.name)
271 self._lsts[step_name] = tuple(lst) # don't change any more
272 #
273 # check for a possible internal inconsistency: _cffi_struct_unions
274 # should have been generated with exactly self._struct_unions
275 lst = self._lsts["struct_union"]
276 for tp, i in self._struct_unions.items():
277 assert i < len(lst)
278 assert lst[i].name == tp.name
279 assert len(lst) == len(self._struct_unions)
280 # same with enums
281 lst = self._lsts["enum"]
282 for tp, i in self._enums.items():
283 assert i < len(lst)
284 assert lst[i].name == tp.name
285 assert len(lst) == len(self._enums)
286
287 # ----------
288
289 def _prnt(self, what=''):
290 self._f.write(what + '\n')
291
292 def write_source_to_f(self, f, preamble):
293 if self.target_is_python:
294 assert preamble is None
295 self.write_py_source_to_f(f)
296 else:
297 assert preamble is not None
298 self.write_c_source_to_f(f, preamble)
299
300 def _rel_readlines(self, filename):
301 with open(os.path.join(os.path.dirname(__file__), filename), 'r') as g:
302 return g.readlines()
303
304 def write_c_source_to_f(self, f, preamble):
305 self._f = f
306 prnt = self._prnt
307 if self.ffi._embedding is not None:
308 prnt('#define _CFFI_USE_EMBEDDING')
309 if not USE_LIMITED_API:
310 prnt('#define _CFFI_NO_LIMITED_API')
311 #
312 # first the '#include' (actually done by inlining the file's content)
313 lines = self._rel_readlines('_cffi_include.h')
314 i = lines.index('#include "parse_c_type.h"\n')
315 lines[i:i+1] = self._rel_readlines('parse_c_type.h')
316 prnt(''.join(lines))
317 #
318 # if we have ffi._embedding != None, we give it here as a macro
319 # and include an extra file
320 base_module_name = self.module_name.split('.')[-1]
321 if self.ffi._embedding is not None:
322 prnt('#define _CFFI_MODULE_NAME "%s"' % (self.module_name,))
323 prnt('static const char _CFFI_PYTHON_STARTUP_CODE[] = {')
324 self._print_string_literal_in_array(self.ffi._embedding)
325 prnt('0 };')
326 prnt('#ifdef PYPY_VERSION')
327 prnt('# define _CFFI_PYTHON_STARTUP_FUNC _cffi_pypyinit_%s' % (
328 base_module_name,))
329 prnt('#else')
330 prnt('# define _CFFI_PYTHON_STARTUP_FUNC PyInit_%s' % (
331 base_module_name,))
332 prnt('#endif')
333 lines = self._rel_readlines('_embedding.h')
334 i = lines.index('#include "_cffi_errors.h"\n')
335 lines[i:i+1] = self._rel_readlines('_cffi_errors.h')
336 prnt(''.join(lines))
337 self.needs_version(VERSION_EMBEDDED)
338 #
339 # then paste the C source given by the user, verbatim.
340 prnt('/************************************************************/')
341 prnt()
342 prnt(preamble)
343 prnt()
344 prnt('/************************************************************/')
345 prnt()
346 #
347 # the declaration of '_cffi_types'
348 prnt('static void *_cffi_types[] = {')
349 typeindex2type = dict([(i, tp) for (tp, i) in self._typesdict.items()])
350 for i, op in enumerate(self.cffi_types):
351 comment = ''
352 if i in typeindex2type:
353 comment = ' // ' + typeindex2type[i]._get_c_name()
354 prnt('/* %2d */ %s,%s' % (i, op.as_c_expr(), comment))
355 if not self.cffi_types:
356 prnt(' 0')
357 prnt('};')
358 prnt()
359 #
360 # call generate_cpy_xxx_decl(), for every xxx found from
361 # ffi._parser._declarations. This generates all the functions.
362 self._seen_constants = set()
363 self._generate("decl")
364 #
365 # the declaration of '_cffi_globals' and '_cffi_typenames'
366 nums = {}
367 for step_name in self.ALL_STEPS:
368 lst = self._lsts[step_name]
369 nums[step_name] = len(lst)
370 if nums[step_name] > 0:
371 prnt('static const struct _cffi_%s_s _cffi_%ss[] = {' % (
372 step_name, step_name))
373 for entry in lst:
374 prnt(entry.as_c_expr())
375 prnt('};')
376 prnt()
377 #
378 # the declaration of '_cffi_includes'
379 if self.ffi._included_ffis:
380 prnt('static const char * const _cffi_includes[] = {')
381 for ffi_to_include in self.ffi._included_ffis:
382 try:
383 included_module_name, included_source = (
384 ffi_to_include._assigned_source[:2])
385 except AttributeError:
386 raise VerificationError(
387 "ffi object %r includes %r, but the latter has not "
388 "been prepared with set_source()" % (
389 self.ffi, ffi_to_include,))
390 if included_source is None:
391 raise VerificationError(
392 "not implemented yet: ffi.include() of a Python-based "
393 "ffi inside a C-based ffi")
394 prnt(' "%s",' % (included_module_name,))
395 prnt(' NULL')
396 prnt('};')
397 prnt()
398 #
399 # the declaration of '_cffi_type_context'
400 prnt('static const struct _cffi_type_context_s _cffi_type_context = {')
401 prnt(' _cffi_types,')
402 for step_name in self.ALL_STEPS:
403 if nums[step_name] > 0:
404 prnt(' _cffi_%ss,' % step_name)
405 else:
406 prnt(' NULL, /* no %ss */' % step_name)
407 for step_name in self.ALL_STEPS:
408 if step_name != "field":
409 prnt(' %d, /* num_%ss */' % (nums[step_name], step_name))
410 if self.ffi._included_ffis:
411 prnt(' _cffi_includes,')
412 else:
413 prnt(' NULL, /* no includes */')
414 prnt(' %d, /* num_types */' % (len(self.cffi_types),))
415 flags = 0
416 if self._num_externpy > 0 or self.ffi._embedding is not None:
417 flags |= 1 # set to mean that we use extern "Python"
418 prnt(' %d, /* flags */' % flags)
419 prnt('};')
420 prnt()
421 #
422 # the init function
423 prnt('#ifdef __GNUC__')
424 prnt('# pragma GCC visibility push(default) /* for -fvisibility= */')
425 prnt('#endif')
426 prnt()
427 prnt('#ifdef PYPY_VERSION')
428 prnt('PyMODINIT_FUNC')
429 prnt('_cffi_pypyinit_%s(const void *p[])' % (base_module_name,))
430 prnt('{')
431 if flags & 1:
432 prnt(' if (((intptr_t)p[0]) >= 0x0A03) {')
433 prnt(' _cffi_call_python_org = '
434 '(void(*)(struct _cffi_externpy_s *, char *))p[1];')
435 prnt(' }')
436 prnt(' p[0] = (const void *)0x%x;' % self._version)
437 prnt(' p[1] = &_cffi_type_context;')
438 prnt(' return NULL;')
439 prnt('}')
440 # on Windows, distutils insists on putting init_cffi_xyz in
441 # 'export_symbols', so instead of fighting it, just give up and
442 # give it one
443 prnt('# ifdef _MSC_VER')
444 prnt(' PyMODINIT_FUNC')
445 prnt(' PyInit_%s(void) { return NULL; }' % (base_module_name,))
446 prnt('# endif')
447 prnt('#else')
448 prnt('PyMODINIT_FUNC')
449 prnt('PyInit_%s(void)' % (base_module_name,))
450 prnt('{')
451 prnt(' return _cffi_init("%s", 0x%x, &_cffi_type_context);' % (
452 self.module_name, self._version))
453 prnt('}')
454 prnt('#endif')
455 prnt()
456 prnt('#ifdef __GNUC__')
457 prnt('# pragma GCC visibility pop')
458 prnt('#endif')
459 self._version = None
460
461 def _to_py(self, x):
462 if isinstance(x, str):
463 return "b'%s'" % (x,)
464 if isinstance(x, (list, tuple)):
465 rep = [self._to_py(item) for item in x]
466 if len(rep) == 1:
467 rep.append('')
468 return "(%s)" % (','.join(rep),)
469 return x.as_python_expr() # Py2: unicode unexpected; Py3: bytes unexp.
470
471 def write_py_source_to_f(self, f):
472 self._f = f
473 prnt = self._prnt
474 #
475 # header
476 prnt("# auto-generated file")
477 prnt("import _cffi_backend")
478 #
479 # the 'import' of the included ffis
480 num_includes = len(self.ffi._included_ffis or ())
481 for i in range(num_includes):
482 ffi_to_include = self.ffi._included_ffis[i]
483 try:
484 included_module_name, included_source = (
485 ffi_to_include._assigned_source[:2])
486 except AttributeError:
487 raise VerificationError(
488 "ffi object %r includes %r, but the latter has not "
489 "been prepared with set_source()" % (
490 self.ffi, ffi_to_include,))
491 if included_source is not None:
492 raise VerificationError(
493 "not implemented yet: ffi.include() of a C-based "
494 "ffi inside a Python-based ffi")
495 prnt('from %s import ffi as _ffi%d' % (included_module_name, i))
496 prnt()
497 prnt("ffi = _cffi_backend.FFI('%s'," % (self.module_name,))
498 prnt(" _version = 0x%x," % (self._version,))
499 self._version = None
500 #
501 # the '_types' keyword argument
502 self.cffi_types = tuple(self.cffi_types) # don't change any more
503 types_lst = [op.as_python_bytes() for op in self.cffi_types]
504 prnt(' _types = %s,' % (self._to_py(''.join(types_lst)),))
505 typeindex2type = dict([(i, tp) for (tp, i) in self._typesdict.items()])
506 #
507 # the keyword arguments from ALL_STEPS
508 for step_name in self.ALL_STEPS:
509 lst = self._lsts[step_name]
510 if len(lst) > 0 and step_name != "field":
511 prnt(' _%ss = %s,' % (step_name, self._to_py(lst)))
512 #
513 # the '_includes' keyword argument
514 if num_includes > 0:
515 prnt(' _includes = (%s,),' % (
516 ', '.join(['_ffi%d' % i for i in range(num_includes)]),))
517 #
518 # the footer
519 prnt(')')
520
521 # ----------
522
523 def _gettypenum(self, type):
524 # a KeyError here is a bug. please report it! :-)
525 return self._typesdict[type]
526
527 def _convert_funcarg_to_c(self, tp, fromvar, tovar, errcode):
528 extraarg = ''
529 if isinstance(tp, model.BasePrimitiveType) and not tp.is_complex_type():
530 if tp.is_integer_type() and tp.name != '_Bool':
531 converter = '_cffi_to_c_int'
532 extraarg = ', %s' % tp.name
533 elif isinstance(tp, model.UnknownFloatType):
534 # don't check with is_float_type(): it may be a 'long
535 # double' here, and _cffi_to_c_double would loose precision
536 converter = '(%s)_cffi_to_c_double' % (tp.get_c_name(''),)
537 else:
538 cname = tp.get_c_name('')
539 converter = '(%s)_cffi_to_c_%s' % (cname,
540 tp.name.replace(' ', '_'))
541 if cname in ('char16_t', 'char32_t'):
542 self.needs_version(VERSION_CHAR16CHAR32)
543 errvalue = '-1'
544 #
545 elif isinstance(tp, model.PointerType):
546 self._convert_funcarg_to_c_ptr_or_array(tp, fromvar,
547 tovar, errcode)
548 return
549 #
550 elif (isinstance(tp, (model.StructOrUnionOrEnum, model.BasePrimitiveType))):
551 # a struct (not a struct pointer) as a function argument;
552 # or, a complex (the same code works)
553 self._prnt(' if (_cffi_to_c((char *)&%s, _cffi_type(%d), %s) < 0)'
554 % (tovar, self._gettypenum(tp), fromvar))
555 self._prnt(' %s;' % errcode)
556 return
557 #
558 elif isinstance(tp, model.FunctionPtrType):
559 converter = '(%s)_cffi_to_c_pointer' % tp.get_c_name('')
560 extraarg = ', _cffi_type(%d)' % self._gettypenum(tp)
561 errvalue = 'NULL'
562 #
563 else:
564 raise NotImplementedError(tp)
565 #
566 self._prnt(' %s = %s(%s%s);' % (tovar, converter, fromvar, extraarg))
567 self._prnt(' if (%s == (%s)%s && PyErr_Occurred())' % (
568 tovar, tp.get_c_name(''), errvalue))
569 self._prnt(' %s;' % errcode)
570
571 def _extra_local_variables(self, tp, localvars, freelines):
572 if isinstance(tp, model.PointerType):
573 localvars.add('Py_ssize_t datasize')
574 localvars.add('struct _cffi_freeme_s *large_args_free = NULL')
575 freelines.add('if (large_args_free != NULL)'
576 ' _cffi_free_array_arguments(large_args_free);')
577
578 def _convert_funcarg_to_c_ptr_or_array(self, tp, fromvar, tovar, errcode):
579 self._prnt(' datasize = _cffi_prepare_pointer_call_argument(')
580 self._prnt(' _cffi_type(%d), %s, (char **)&%s);' % (
581 self._gettypenum(tp), fromvar, tovar))
582 self._prnt(' if (datasize != 0) {')
583 self._prnt(' %s = ((size_t)datasize) <= 640 ? '
584 '(%s)alloca((size_t)datasize) : NULL;' % (
585 tovar, tp.get_c_name('')))
586 self._prnt(' if (_cffi_convert_array_argument(_cffi_type(%d), %s, '
587 '(char **)&%s,' % (self._gettypenum(tp), fromvar, tovar))
588 self._prnt(' datasize, &large_args_free) < 0)')
589 self._prnt(' %s;' % errcode)
590 self._prnt(' }')
591
592 def _convert_expr_from_c(self, tp, var, context):
593 if isinstance(tp, model.BasePrimitiveType):
594 if tp.is_integer_type() and tp.name != '_Bool':
595 return '_cffi_from_c_int(%s, %s)' % (var, tp.name)
596 elif isinstance(tp, model.UnknownFloatType):
597 return '_cffi_from_c_double(%s)' % (var,)
598 elif tp.name != 'long double' and not tp.is_complex_type():
599 cname = tp.name.replace(' ', '_')
600 if cname in ('char16_t', 'char32_t'):
601 self.needs_version(VERSION_CHAR16CHAR32)
602 return '_cffi_from_c_%s(%s)' % (cname, var)
603 else:
604 return '_cffi_from_c_deref((char *)&%s, _cffi_type(%d))' % (
605 var, self._gettypenum(tp))
606 elif isinstance(tp, (model.PointerType, model.FunctionPtrType)):
607 return '_cffi_from_c_pointer((char *)%s, _cffi_type(%d))' % (
608 var, self._gettypenum(tp))
609 elif isinstance(tp, model.ArrayType):
610 return '_cffi_from_c_pointer((char *)%s, _cffi_type(%d))' % (
611 var, self._gettypenum(model.PointerType(tp.item)))
612 elif isinstance(tp, model.StructOrUnion):
613 if tp.fldnames is None:
614 raise TypeError("'%s' is used as %s, but is opaque" % (
615 tp._get_c_name(), context))
616 return '_cffi_from_c_struct((char *)&%s, _cffi_type(%d))' % (
617 var, self._gettypenum(tp))
618 elif isinstance(tp, model.EnumType):
619 return '_cffi_from_c_deref((char *)&%s, _cffi_type(%d))' % (
620 var, self._gettypenum(tp))
621 else:
622 raise NotImplementedError(tp)
623
624 # ----------
625 # typedefs
626
627 def _typedef_type(self, tp, name):
628 return self._global_type(tp, "(*(%s *)0)" % (name,))
629
630 def _generate_cpy_typedef_collecttype(self, tp, name):
631 self._do_collect_type(self._typedef_type(tp, name))
632
633 def _generate_cpy_typedef_decl(self, tp, name):
634 pass
635
636 def _typedef_ctx(self, tp, name):
637 type_index = self._typesdict[tp]
638 self._lsts["typename"].append(TypenameExpr(name, type_index))
639
640 def _generate_cpy_typedef_ctx(self, tp, name):
641 tp = self._typedef_type(tp, name)
642 self._typedef_ctx(tp, name)
643 if getattr(tp, "origin", None) == "unknown_type":
644 self._struct_ctx(tp, tp.name, approxname=None)
645 elif isinstance(tp, model.NamedPointerType):
646 self._struct_ctx(tp.totype, tp.totype.name, approxname=tp.name,
647 named_ptr=tp)
648
649 # ----------
650 # function declarations
651
652 def _generate_cpy_function_collecttype(self, tp, name):
653 self._do_collect_type(tp.as_raw_function())
654 if tp.ellipsis and not self.target_is_python:
655 self._do_collect_type(tp)
656
657 def _generate_cpy_function_decl(self, tp, name):
658 assert not self.target_is_python
659 assert isinstance(tp, model.FunctionPtrType)
660 if tp.ellipsis:
661 # cannot support vararg functions better than this: check for its
662 # exact type (including the fixed arguments), and build it as a
663 # constant function pointer (no CPython wrapper)
664 self._generate_cpy_constant_decl(tp, name)
665 return
666 prnt = self._prnt
667 numargs = len(tp.args)
668 if numargs == 0:
669 argname = 'noarg'
670 elif numargs == 1:
671 argname = 'arg0'
672 else:
673 argname = 'args'
674 #
675 # ------------------------------
676 # the 'd' version of the function, only for addressof(lib, 'func')
677 arguments = []
678 call_arguments = []
679 context = 'argument of %s' % name
680 for i, type in enumerate(tp.args):
681 arguments.append(type.get_c_name(' x%d' % i, context))
682 call_arguments.append('x%d' % i)
683 repr_arguments = ', '.join(arguments)
684 repr_arguments = repr_arguments or 'void'
685 if tp.abi:
686 abi = tp.abi + ' '
687 else:
688 abi = ''
689 name_and_arguments = '%s_cffi_d_%s(%s)' % (abi, name, repr_arguments)
690 prnt('static %s' % (tp.result.get_c_name(name_and_arguments),))
691 prnt('{')
692 call_arguments = ', '.join(call_arguments)
693 result_code = 'return '
694 if isinstance(tp.result, model.VoidType):
695 result_code = ''
696 prnt(' %s%s(%s);' % (result_code, name, call_arguments))
697 prnt('}')
698 #
699 prnt('#ifndef PYPY_VERSION') # ------------------------------
700 #
701 prnt('static PyObject *')
702 prnt('_cffi_f_%s(PyObject *self, PyObject *%s)' % (name, argname))
703 prnt('{')
704 #
705 context = 'argument of %s' % name
706 for i, type in enumerate(tp.args):
707 arg = type.get_c_name(' x%d' % i, context)
708 prnt(' %s;' % arg)
709 #
710 localvars = set()
711 freelines = set()
712 for type in tp.args:
713 self._extra_local_variables(type, localvars, freelines)
714 for decl in sorted(localvars):
715 prnt(' %s;' % (decl,))
716 #
717 if not isinstance(tp.result, model.VoidType):
718 result_code = 'result = '
719 context = 'result of %s' % name
720 result_decl = ' %s;' % tp.result.get_c_name(' result', context)
721 prnt(result_decl)
722 prnt(' PyObject *pyresult;')
723 else:
724 result_decl = None
725 result_code = ''
726 #
727 if len(tp.args) > 1:
728 rng = range(len(tp.args))
729 for i in rng:
730 prnt(' PyObject *arg%d;' % i)
731 prnt()
732 prnt(' if (!PyArg_UnpackTuple(args, "%s", %d, %d, %s))' % (
733 name, len(rng), len(rng),
734 ', '.join(['&arg%d' % i for i in rng])))
735 prnt(' return NULL;')
736 prnt()
737 #
738 for i, type in enumerate(tp.args):
739 self._convert_funcarg_to_c(type, 'arg%d' % i, 'x%d' % i,
740 'return NULL')
741 prnt()
742 #
743 prnt(' Py_BEGIN_ALLOW_THREADS')
744 prnt(' _cffi_restore_errno();')
745 call_arguments = ['x%d' % i for i in range(len(tp.args))]
746 call_arguments = ', '.join(call_arguments)
747 prnt(' { %s%s(%s); }' % (result_code, name, call_arguments))
748 prnt(' _cffi_save_errno();')
749 prnt(' Py_END_ALLOW_THREADS')
750 prnt()
751 #
752 prnt(' (void)self; /* unused */')
753 if numargs == 0:
754 prnt(' (void)noarg; /* unused */')
755 if result_code:
756 prnt(' pyresult = %s;' %
757 self._convert_expr_from_c(tp.result, 'result', 'result type'))
758 for freeline in freelines:
759 prnt(' ' + freeline)
760 prnt(' return pyresult;')
761 else:
762 for freeline in freelines:
763 prnt(' ' + freeline)
764 prnt(' Py_INCREF(Py_None);')
765 prnt(' return Py_None;')
766 prnt('}')
767 #
768 prnt('#else') # ------------------------------
769 #
770 # the PyPy version: need to replace struct/union arguments with
771 # pointers, and if the result is a struct/union, insert a first
772 # arg that is a pointer to the result. We also do that for
773 # complex args and return type.
774 def need_indirection(type):
775 return (isinstance(type, model.StructOrUnion) or
776 (isinstance(type, model.PrimitiveType) and
777 type.is_complex_type()))
778 difference = False
779 arguments = []
780 call_arguments = []
781 context = 'argument of %s' % name
782 for i, type in enumerate(tp.args):
783 indirection = ''
784 if need_indirection(type):
785 indirection = '*'
786 difference = True
787 arg = type.get_c_name(' %sx%d' % (indirection, i), context)
788 arguments.append(arg)
789 call_arguments.append('%sx%d' % (indirection, i))
790 tp_result = tp.result
791 if need_indirection(tp_result):
792 context = 'result of %s' % name
793 arg = tp_result.get_c_name(' *result', context)
794 arguments.insert(0, arg)
795 tp_result = model.void_type
796 result_decl = None
797 result_code = '*result = '
798 difference = True
799 if difference:
800 repr_arguments = ', '.join(arguments)
801 repr_arguments = repr_arguments or 'void'
802 name_and_arguments = '%s_cffi_f_%s(%s)' % (abi, name,
803 repr_arguments)
804 prnt('static %s' % (tp_result.get_c_name(name_and_arguments),))
805 prnt('{')
806 if result_decl:
807 prnt(result_decl)
808 call_arguments = ', '.join(call_arguments)
809 prnt(' { %s%s(%s); }' % (result_code, name, call_arguments))
810 if result_decl:
811 prnt(' return result;')
812 prnt('}')
813 else:
814 prnt('# define _cffi_f_%s _cffi_d_%s' % (name, name))
815 #
816 prnt('#endif') # ------------------------------
817 prnt()
818
819 def _generate_cpy_function_ctx(self, tp, name):
820 if tp.ellipsis and not self.target_is_python:
821 self._generate_cpy_constant_ctx(tp, name)
822 return
823 type_index = self._typesdict[tp.as_raw_function()]
824 numargs = len(tp.args)
825 if self.target_is_python:
826 meth_kind = OP_DLOPEN_FUNC
827 elif numargs == 0:
828 meth_kind = OP_CPYTHON_BLTN_N # 'METH_NOARGS'
829 elif numargs == 1:
830 meth_kind = OP_CPYTHON_BLTN_O # 'METH_O'
831 else:
832 meth_kind = OP_CPYTHON_BLTN_V # 'METH_VARARGS'
833 self._lsts["global"].append(
834 GlobalExpr(name, '_cffi_f_%s' % name,
835 CffiOp(meth_kind, type_index),
836 size='_cffi_d_%s' % name))
837
838 # ----------
839 # named structs or unions
840
841 def _field_type(self, tp_struct, field_name, tp_field):
842 if isinstance(tp_field, model.ArrayType):
843 actual_length = tp_field.length
844 if actual_length == '...':
845 ptr_struct_name = tp_struct.get_c_name('*')
846 actual_length = '_cffi_array_len(((%s)0)->%s)' % (
847 ptr_struct_name, field_name)
848 tp_item = self._field_type(tp_struct, '%s[0]' % field_name,
849 tp_field.item)
850 tp_field = model.ArrayType(tp_item, actual_length)
851 return tp_field
852
853 def _struct_collecttype(self, tp):
854 self._do_collect_type(tp)
855 if self.target_is_python:
856 # also requires nested anon struct/unions in ABI mode, recursively
857 for fldtype in tp.anonymous_struct_fields():
858 self._struct_collecttype(fldtype)
859
860 def _struct_decl(self, tp, cname, approxname):
861 if tp.fldtypes is None:
862 return
863 prnt = self._prnt
864 checkfuncname = '_cffi_checkfld_%s' % (approxname,)
865 prnt('_CFFI_UNUSED_FN')
866 prnt('static void %s(%s *p)' % (checkfuncname, cname))
867 prnt('{')
868 prnt(' /* only to generate compile-time warnings or errors */')
869 prnt(' (void)p;')
870 for fname, ftype, fbitsize, fqual in self._enum_fields(tp):
871 try:
872 if ftype.is_integer_type() or fbitsize >= 0:
873 # accept all integers, but complain on float or double
874 if fname != '':
875 prnt(" (void)((p->%s) | 0); /* check that '%s.%s' is "
876 "an integer */" % (fname, cname, fname))
877 continue
878 # only accept exactly the type declared, except that '[]'
879 # is interpreted as a '*' and so will match any array length.
880 # (It would also match '*', but that's harder to detect...)
881 while (isinstance(ftype, model.ArrayType)
882 and (ftype.length is None or ftype.length == '...')):
883 ftype = ftype.item
884 fname = fname + '[0]'
885 prnt(' { %s = &p->%s; (void)tmp; }' % (
886 ftype.get_c_name('*tmp', 'field %r'%fname, quals=fqual),
887 fname))
888 except VerificationError as e:
889 prnt(' /* %s */' % str(e)) # cannot verify it, ignore
890 prnt('}')
891 prnt('struct _cffi_align_%s { char x; %s y; };' % (approxname, cname))
892 prnt()
893
894 def _struct_ctx(self, tp, cname, approxname, named_ptr=None):
895 type_index = self._typesdict[tp]
896 reason_for_not_expanding = None
897 flags = []
898 if isinstance(tp, model.UnionType):
899 flags.append("_CFFI_F_UNION")
900 if tp.fldtypes is None:
901 flags.append("_CFFI_F_OPAQUE")
902 reason_for_not_expanding = "opaque"
903 if (tp not in self.ffi._parser._included_declarations and
904 (named_ptr is None or
905 named_ptr not in self.ffi._parser._included_declarations)):
906 if tp.fldtypes is None:
907 pass # opaque
908 elif tp.partial or any(tp.anonymous_struct_fields()):
909 pass # field layout obtained silently from the C compiler
910 else:
911 flags.append("_CFFI_F_CHECK_FIELDS")
912 if tp.packed:
913 if tp.packed > 1:
914 raise NotImplementedError(
915 "%r is declared with 'pack=%r'; only 0 or 1 are "
916 "supported in API mode (try to use \"...;\", which "
917 "does not require a 'pack' declaration)" %
918 (tp, tp.packed))
919 flags.append("_CFFI_F_PACKED")
920 else:
921 flags.append("_CFFI_F_EXTERNAL")
922 reason_for_not_expanding = "external"
923 flags = '|'.join(flags) or '0'
924 c_fields = []
925 if reason_for_not_expanding is None:
926 enumfields = list(self._enum_fields(tp))
927 for fldname, fldtype, fbitsize, fqual in enumfields:
928 fldtype = self._field_type(tp, fldname, fldtype)
929 self._check_not_opaque(fldtype,
930 "field '%s.%s'" % (tp.name, fldname))
931 # cname is None for _add_missing_struct_unions() only
932 op = OP_NOOP
933 if fbitsize >= 0:
934 op = OP_BITFIELD
935 size = '%d /* bits */' % fbitsize
936 elif cname is None or (
937 isinstance(fldtype, model.ArrayType) and
938 fldtype.length is None):
939 size = '(size_t)-1'
940 else:
941 size = 'sizeof(((%s)0)->%s)' % (
942 tp.get_c_name('*') if named_ptr is None
943 else named_ptr.name,
944 fldname)
945 if cname is None or fbitsize >= 0:
946 offset = '(size_t)-1'
947 elif named_ptr is not None:
948 offset = '(size_t)(((char *)&((%s)4096)->%s) - (char *)4096)' % (
949 named_ptr.name, fldname)
950 else:
951 offset = 'offsetof(%s, %s)' % (tp.get_c_name(''), fldname)
952 c_fields.append(
953 FieldExpr(fldname, offset, size, fbitsize,
954 CffiOp(op, self._typesdict[fldtype])))
955 first_field_index = len(self._lsts["field"])
956 self._lsts["field"].extend(c_fields)
957 #
958 if cname is None: # unknown name, for _add_missing_struct_unions
959 size = '(size_t)-2'
960 align = -2
961 comment = "unnamed"
962 else:
963 if named_ptr is not None:
964 size = 'sizeof(*(%s)0)' % (named_ptr.name,)
965 align = '-1 /* unknown alignment */'
966 else:
967 size = 'sizeof(%s)' % (cname,)
968 align = 'offsetof(struct _cffi_align_%s, y)' % (approxname,)
969 comment = None
970 else:
971 size = '(size_t)-1'
972 align = -1
973 first_field_index = -1
974 comment = reason_for_not_expanding
975 self._lsts["struct_union"].append(
976 StructUnionExpr(tp.name, type_index, flags, size, align, comment,
977 first_field_index, c_fields))
978 self._seen_struct_unions.add(tp)
979
980 def _check_not_opaque(self, tp, location):
981 while isinstance(tp, model.ArrayType):
982 tp = tp.item
983 if isinstance(tp, model.StructOrUnion) and tp.fldtypes is None:
984 raise TypeError(
985 "%s is of an opaque type (not declared in cdef())" % location)
986
987 def _add_missing_struct_unions(self):
988 # not very nice, but some struct declarations might be missing
989 # because they don't have any known C name. Check that they are
990 # not partial (we can't complete or verify them!) and emit them
991 # anonymously.
992 lst = list(self._struct_unions.items())
993 lst.sort(key=lambda tp_order: tp_order[1])
994 for tp, order in lst:
995 if tp not in self._seen_struct_unions:
996 if tp.partial:
997 raise NotImplementedError("internal inconsistency: %r is "
998 "partial but was not seen at "
999 "this point" % (tp,))
1000 if tp.name.startswith('$') and tp.name[1:].isdigit():
1001 approxname = tp.name[1:]
1002 elif tp.name == '_IO_FILE' and tp.forcename == 'FILE':
1003 approxname = 'FILE'
1004 self._typedef_ctx(tp, 'FILE')
1005 else:
1006 raise NotImplementedError("internal inconsistency: %r" %
1007 (tp,))
1008 self._struct_ctx(tp, None, approxname)
1009
1010 def _generate_cpy_struct_collecttype(self, tp, name):
1011 self._struct_collecttype(tp)
1012 _generate_cpy_union_collecttype = _generate_cpy_struct_collecttype
1013
1014 def _struct_names(self, tp):
1015 cname = tp.get_c_name('')
1016 if ' ' in cname:
1017 return cname, cname.replace(' ', '_')
1018 else:
1019 return cname, '_' + cname
1020
1021 def _generate_cpy_struct_decl(self, tp, name):
1022 self._struct_decl(tp, *self._struct_names(tp))
1023 _generate_cpy_union_decl = _generate_cpy_struct_decl
1024
1025 def _generate_cpy_struct_ctx(self, tp, name):
1026 self._struct_ctx(tp, *self._struct_names(tp))
1027 _generate_cpy_union_ctx = _generate_cpy_struct_ctx
1028
1029 # ----------
1030 # 'anonymous' declarations. These are produced for anonymous structs
1031 # or unions; the 'name' is obtained by a typedef.
1032
1033 def _generate_cpy_anonymous_collecttype(self, tp, name):
1034 if isinstance(tp, model.EnumType):
1035 self._generate_cpy_enum_collecttype(tp, name)
1036 else:
1037 self._struct_collecttype(tp)
1038
1039 def _generate_cpy_anonymous_decl(self, tp, name):
1040 if isinstance(tp, model.EnumType):
1041 self._generate_cpy_enum_decl(tp)
1042 else:
1043 self._struct_decl(tp, name, 'typedef_' + name)
1044
1045 def _generate_cpy_anonymous_ctx(self, tp, name):
1046 if isinstance(tp, model.EnumType):
1047 self._enum_ctx(tp, name)
1048 else:
1049 self._struct_ctx(tp, name, 'typedef_' + name)
1050
1051 # ----------
1052 # constants, declared with "static const ..."
1053
1054 def _generate_cpy_const(self, is_int, name, tp=None, category='const',
1055 check_value=None):
1056 if (category, name) in self._seen_constants:
1057 raise VerificationError(
1058 "duplicate declaration of %s '%s'" % (category, name))
1059 self._seen_constants.add((category, name))
1060 #
1061 prnt = self._prnt
1062 funcname = '_cffi_%s_%s' % (category, name)
1063 if is_int:
1064 prnt('static int %s(unsigned long long *o)' % funcname)
1065 prnt('{')
1066 prnt(' int n = (%s) <= 0;' % (name,))
1067 prnt(' *o = (unsigned long long)((%s) | 0);'
1068 ' /* check that %s is an integer */' % (name, name))
1069 if check_value is not None:
1070 if check_value > 0:
1071 check_value = '%dU' % (check_value,)
1072 prnt(' if (!_cffi_check_int(*o, n, %s))' % (check_value,))
1073 prnt(' n |= 2;')
1074 prnt(' return n;')
1075 prnt('}')
1076 else:
1077 assert check_value is None
1078 prnt('static void %s(char *o)' % funcname)
1079 prnt('{')
1080 prnt(' *(%s)o = %s;' % (tp.get_c_name('*'), name))
1081 prnt('}')
1082 prnt()
1083
1084 def _generate_cpy_constant_collecttype(self, tp, name):
1085 is_int = tp.is_integer_type()
1086 if not is_int or self.target_is_python:
1087 self._do_collect_type(tp)
1088
1089 def _generate_cpy_constant_decl(self, tp, name):
1090 is_int = tp.is_integer_type()
1091 self._generate_cpy_const(is_int, name, tp)
1092
1093 def _generate_cpy_constant_ctx(self, tp, name):
1094 if not self.target_is_python and tp.is_integer_type():
1095 type_op = CffiOp(OP_CONSTANT_INT, -1)
1096 else:
1097 if self.target_is_python:
1098 const_kind = OP_DLOPEN_CONST
1099 else:
1100 const_kind = OP_CONSTANT
1101 type_index = self._typesdict[tp]
1102 type_op = CffiOp(const_kind, type_index)
1103 self._lsts["global"].append(
1104 GlobalExpr(name, '_cffi_const_%s' % name, type_op))
1105
1106 # ----------
1107 # enums
1108
1109 def _generate_cpy_enum_collecttype(self, tp, name):
1110 self._do_collect_type(tp)
1111
1112 def _generate_cpy_enum_decl(self, tp, name=None):
1113 for enumerator in tp.enumerators:
1114 self._generate_cpy_const(True, enumerator)
1115
1116 def _enum_ctx(self, tp, cname):
1117 type_index = self._typesdict[tp]
1118 type_op = CffiOp(OP_ENUM, -1)
1119 if self.target_is_python:
1120 tp.check_not_partial()
1121 for enumerator, enumvalue in zip(tp.enumerators, tp.enumvalues):
1122 self._lsts["global"].append(
1123 GlobalExpr(enumerator, '_cffi_const_%s' % enumerator, type_op,
1124 check_value=enumvalue))
1125 #
1126 if cname is not None and '$' not in cname and not self.target_is_python:
1127 size = "sizeof(%s)" % cname
1128 signed = "((%s)-1) <= 0" % cname
1129 else:
1130 basetp = tp.build_baseinttype(self.ffi, [])
1131 size = self.ffi.sizeof(basetp)
1132 signed = int(int(self.ffi.cast(basetp, -1)) < 0)
1133 allenums = ",".join(tp.enumerators)
1134 self._lsts["enum"].append(
1135 EnumExpr(tp.name, type_index, size, signed, allenums))
1136
1137 def _generate_cpy_enum_ctx(self, tp, name):
1138 self._enum_ctx(tp, tp._get_c_name())
1139
1140 # ----------
1141 # macros: for now only for integers
1142
1143 def _generate_cpy_macro_collecttype(self, tp, name):
1144 pass
1145
1146 def _generate_cpy_macro_decl(self, tp, name):
1147 if tp == '...':
1148 check_value = None
1149 else:
1150 check_value = tp # an integer
1151 self._generate_cpy_const(True, name, check_value=check_value)
1152
1153 def _generate_cpy_macro_ctx(self, tp, name):
1154 if tp == '...':
1155 if self.target_is_python:
1156 raise VerificationError(
1157 "cannot use the syntax '...' in '#define %s ...' when "
1158 "using the ABI mode" % (name,))
1159 check_value = None
1160 else:
1161 check_value = tp # an integer
1162 type_op = CffiOp(OP_CONSTANT_INT, -1)
1163 self._lsts["global"].append(
1164 GlobalExpr(name, '_cffi_const_%s' % name, type_op,
1165 check_value=check_value))
1166
1167 # ----------
1168 # global variables
1169
1170 def _global_type(self, tp, global_name):
1171 if isinstance(tp, model.ArrayType):
1172 actual_length = tp.length
1173 if actual_length == '...':
1174 actual_length = '_cffi_array_len(%s)' % (global_name,)
1175 tp_item = self._global_type(tp.item, '%s[0]' % global_name)
1176 tp = model.ArrayType(tp_item, actual_length)
1177 return tp
1178
1179 def _generate_cpy_variable_collecttype(self, tp, name):
1180 self._do_collect_type(self._global_type(tp, name))
1181
1182 def _generate_cpy_variable_decl(self, tp, name):
1183 prnt = self._prnt
1184 tp = self._global_type(tp, name)
1185 if isinstance(tp, model.ArrayType) and tp.length is None:
1186 tp = tp.item
1187 ampersand = ''
1188 else:
1189 ampersand = '&'
1190 # This code assumes that casts from "tp *" to "void *" is a
1191 # no-op, i.e. a function that returns a "tp *" can be called
1192 # as if it returned a "void *". This should be generally true
1193 # on any modern machine. The only exception to that rule (on
1194 # uncommon architectures, and as far as I can tell) might be
1195 # if 'tp' were a function type, but that is not possible here.
1196 # (If 'tp' is a function _pointer_ type, then casts from "fn_t
1197 # **" to "void *" are again no-ops, as far as I can tell.)
1198 decl = '*_cffi_var_%s(void)' % (name,)
1199 prnt('static ' + tp.get_c_name(decl, quals=self._current_quals))
1200 prnt('{')
1201 prnt(' return %s(%s);' % (ampersand, name))
1202 prnt('}')
1203 prnt()
1204
1205 def _generate_cpy_variable_ctx(self, tp, name):
1206 tp = self._global_type(tp, name)
1207 type_index = self._typesdict[tp]
1208 if self.target_is_python:
1209 op = OP_GLOBAL_VAR
1210 else:
1211 op = OP_GLOBAL_VAR_F
1212 self._lsts["global"].append(
1213 GlobalExpr(name, '_cffi_var_%s' % name, CffiOp(op, type_index)))
1214
1215 # ----------
1216 # extern "Python"
1217
1218 def _generate_cpy_extern_python_collecttype(self, tp, name):
1219 assert isinstance(tp, model.FunctionPtrType)
1220 self._do_collect_type(tp)
1221 _generate_cpy_dllexport_python_collecttype = \
1222 _generate_cpy_extern_python_plus_c_collecttype = \
1223 _generate_cpy_extern_python_collecttype
1224
1225 def _extern_python_decl(self, tp, name, tag_and_space):
1226 prnt = self._prnt
1227 if isinstance(tp.result, model.VoidType):
1228 size_of_result = '0'
1229 else:
1230 context = 'result of %s' % name
1231 size_of_result = '(int)sizeof(%s)' % (
1232 tp.result.get_c_name('', context),)
1233 prnt('static struct _cffi_externpy_s _cffi_externpy__%s =' % name)
1234 prnt(' { "%s.%s", %s, 0, 0 };' % (
1235 self.module_name, name, size_of_result))
1236 prnt()
1237 #
1238 arguments = []
1239 context = 'argument of %s' % name
1240 for i, type in enumerate(tp.args):
1241 arg = type.get_c_name(' a%d' % i, context)
1242 arguments.append(arg)
1243 #
1244 repr_arguments = ', '.join(arguments)
1245 repr_arguments = repr_arguments or 'void'
1246 name_and_arguments = '%s(%s)' % (name, repr_arguments)
1247 if tp.abi == "__stdcall":
1248 name_and_arguments = '_cffi_stdcall ' + name_and_arguments
1249 #
1250 def may_need_128_bits(tp):
1251 return (isinstance(tp, model.PrimitiveType) and
1252 tp.name == 'long double')
1253 #
1254 size_of_a = max(len(tp.args)*8, 8)
1255 if may_need_128_bits(tp.result):
1256 size_of_a = max(size_of_a, 16)
1257 if isinstance(tp.result, model.StructOrUnion):
1258 size_of_a = 'sizeof(%s) > %d ? sizeof(%s) : %d' % (
1259 tp.result.get_c_name(''), size_of_a,
1260 tp.result.get_c_name(''), size_of_a)
1261 prnt('%s%s' % (tag_and_space, tp.result.get_c_name(name_and_arguments)))
1262 prnt('{')
1263 prnt(' char a[%s];' % size_of_a)
1264 prnt(' char *p = a;')
1265 for i, type in enumerate(tp.args):
1266 arg = 'a%d' % i
1267 if (isinstance(type, model.StructOrUnion) or
1268 may_need_128_bits(type)):
1269 arg = '&' + arg
1270 type = model.PointerType(type)
1271 prnt(' *(%s)(p + %d) = %s;' % (type.get_c_name('*'), i*8, arg))
1272 prnt(' _cffi_call_python(&_cffi_externpy__%s, p);' % name)
1273 if not isinstance(tp.result, model.VoidType):
1274 prnt(' return *(%s)p;' % (tp.result.get_c_name('*'),))
1275 prnt('}')
1276 prnt()
1277 self._num_externpy += 1
1278
1279 def _generate_cpy_extern_python_decl(self, tp, name):
1280 self._extern_python_decl(tp, name, 'static ')
1281
1282 def _generate_cpy_dllexport_python_decl(self, tp, name):
1283 self._extern_python_decl(tp, name, 'CFFI_DLLEXPORT ')
1284
1285 def _generate_cpy_extern_python_plus_c_decl(self, tp, name):
1286 self._extern_python_decl(tp, name, '')
1287
1288 def _generate_cpy_extern_python_ctx(self, tp, name):
1289 if self.target_is_python:
1290 raise VerificationError(
1291 "cannot use 'extern \"Python\"' in the ABI mode")
1292 if tp.ellipsis:
1293 raise NotImplementedError("a vararg function is extern \"Python\"")
1294 type_index = self._typesdict[tp]
1295 type_op = CffiOp(OP_EXTERN_PYTHON, type_index)
1296 self._lsts["global"].append(
1297 GlobalExpr(name, '&_cffi_externpy__%s' % name, type_op, name))
1298
1299 _generate_cpy_dllexport_python_ctx = \
1300 _generate_cpy_extern_python_plus_c_ctx = \
1301 _generate_cpy_extern_python_ctx
1302
1303 def _print_string_literal_in_array(self, s):
1304 prnt = self._prnt
1305 prnt('// # NB. this is not a string because of a size limit in MSVC')
1306 if not isinstance(s, bytes): # unicode
1307 s = s.encode('utf-8') # -> bytes
1308 else:
1309 s.decode('utf-8') # got bytes, check for valid utf-8
1310 for line in s.splitlines(True):
1311 comment = line
1312 if type('//') is bytes: # python2
1313 line = map(ord, line) # make a list of integers
1314 else: # python3
1315 # type(line) is bytes, which enumerates like a list of integers
1316 comment = ascii(comment)[1:-1]
1317 prnt(('// ' + comment).rstrip())
1318 printed_line = ''
1319 for c in line:
1320 if len(printed_line) >= 76:
1321 prnt(printed_line)
1322 printed_line = ''
1323 printed_line += '%d,' % (c,)
1324 prnt(printed_line)
1325
1326 # ----------
1327 # emitting the opcodes for individual types
1328
1329 def _emit_bytecode_VoidType(self, tp, index):
1330 self.cffi_types[index] = CffiOp(OP_PRIMITIVE, PRIM_VOID)
1331
1332 def _emit_bytecode_PrimitiveType(self, tp, index):
1333 prim_index = PRIMITIVE_TO_INDEX[tp.name]
1334 self.cffi_types[index] = CffiOp(OP_PRIMITIVE, prim_index)
1335
1336 def _emit_bytecode_UnknownIntegerType(self, tp, index):
1337 s = ('_cffi_prim_int(sizeof(%s), (\n'
1338 ' ((%s)-1) | 0 /* check that %s is an integer type */\n'
1339 ' ) <= 0)' % (tp.name, tp.name, tp.name))
1340 self.cffi_types[index] = CffiOp(OP_PRIMITIVE, s)
1341
1342 def _emit_bytecode_UnknownFloatType(self, tp, index):
1343 s = ('_cffi_prim_float(sizeof(%s) *\n'
1344 ' (((%s)1) / 2) * 2 /* integer => 0, float => 1 */\n'
1345 ' )' % (tp.name, tp.name))
1346 self.cffi_types[index] = CffiOp(OP_PRIMITIVE, s)
1347
1348 def _emit_bytecode_RawFunctionType(self, tp, index):
1349 self.cffi_types[index] = CffiOp(OP_FUNCTION, self._typesdict[tp.result])
1350 index += 1
1351 for tp1 in tp.args:
1352 realindex = self._typesdict[tp1]
1353 if index != realindex:
1354 if isinstance(tp1, model.PrimitiveType):
1355 self._emit_bytecode_PrimitiveType(tp1, index)
1356 else:
1357 self.cffi_types[index] = CffiOp(OP_NOOP, realindex)
1358 index += 1
1359 flags = int(tp.ellipsis)
1360 if tp.abi is not None:
1361 if tp.abi == '__stdcall':
1362 flags |= 2
1363 else:
1364 raise NotImplementedError("abi=%r" % (tp.abi,))
1365 self.cffi_types[index] = CffiOp(OP_FUNCTION_END, flags)
1366
1367 def _emit_bytecode_PointerType(self, tp, index):
1368 self.cffi_types[index] = CffiOp(OP_POINTER, self._typesdict[tp.totype])
1369
1370 _emit_bytecode_ConstPointerType = _emit_bytecode_PointerType
1371 _emit_bytecode_NamedPointerType = _emit_bytecode_PointerType
1372
1373 def _emit_bytecode_FunctionPtrType(self, tp, index):
1374 raw = tp.as_raw_function()
1375 self.cffi_types[index] = CffiOp(OP_POINTER, self._typesdict[raw])
1376
1377 def _emit_bytecode_ArrayType(self, tp, index):
1378 item_index = self._typesdict[tp.item]
1379 if tp.length is None:
1380 self.cffi_types[index] = CffiOp(OP_OPEN_ARRAY, item_index)
1381 elif tp.length == '...':
1382 raise VerificationError(
1383 "type %s badly placed: the '...' array length can only be "
1384 "used on global arrays or on fields of structures" % (
1385 str(tp).replace('/*...*/', '...'),))
1386 else:
1387 assert self.cffi_types[index + 1] == 'LEN'
1388 self.cffi_types[index] = CffiOp(OP_ARRAY, item_index)
1389 self.cffi_types[index + 1] = CffiOp(None, str(tp.length))
1390
1391 def _emit_bytecode_StructType(self, tp, index):
1392 struct_index = self._struct_unions[tp]
1393 self.cffi_types[index] = CffiOp(OP_STRUCT_UNION, struct_index)
1394 _emit_bytecode_UnionType = _emit_bytecode_StructType
1395
1396 def _emit_bytecode_EnumType(self, tp, index):
1397 enum_index = self._enums[tp]
1398 self.cffi_types[index] = CffiOp(OP_ENUM, enum_index)
1399
1400
1401 if sys.version_info >= (3,):
1402 NativeIO = io.StringIO
1403 else:
1404 class NativeIO(io.BytesIO):
1405 def write(self, s):
1406 if isinstance(s, unicode):
1407 s = s.encode('ascii')
1408 super().write(s)
1409
1410 def _is_file_like(maybefile):
1411 # compare to xml.etree.ElementTree._get_writer
1412 return hasattr(maybefile, 'write')
1413
1414 def _make_c_or_py_source(ffi, module_name, preamble, target_file, verbose):
1415 if verbose:
1416 print("generating %s" % (target_file,))
1417 recompiler = Recompiler(ffi, module_name,
1418 target_is_python=(preamble is None))
1419 recompiler.collect_type_table()
1420 recompiler.collect_step_tables()
1421 if _is_file_like(target_file):
1422 recompiler.write_source_to_f(target_file, preamble)
1423 return True
1424 f = NativeIO()
1425 recompiler.write_source_to_f(f, preamble)
1426 output = f.getvalue()
1427 try:
1428 with open(target_file, 'r') as f1:
1429 if f1.read(len(output) + 1) != output:
1430 raise OSError
1431 if verbose:
1432 print("(already up-to-date)")
1433 return False # already up-to-date
1434 except OSError:
1435 tmp_file = '%s.~%d' % (target_file, os.getpid())
1436 with open(tmp_file, 'w') as f1:
1437 f1.write(output)
1438 try:
1439 os.rename(tmp_file, target_file)
1440 except OSError:
1441 os.unlink(target_file)
1442 os.rename(tmp_file, target_file)
1443 return True
1444
1445 def make_c_source(ffi, module_name, preamble, target_c_file, verbose=False):
1446 assert preamble is not None
1447 return _make_c_or_py_source(ffi, module_name, preamble, target_c_file,
1448 verbose)
1449
1450 def make_py_source(ffi, module_name, target_py_file, verbose=False):
1451 return _make_c_or_py_source(ffi, module_name, None, target_py_file,
1452 verbose)
1453
1454 def _modname_to_file(outputdir, modname, extension):
1455 parts = modname.split('.')
1456 try:
1457 os.makedirs(os.path.join(outputdir, *parts[:-1]))
1458 except OSError:
1459 pass
1460 parts[-1] += extension
1461 return os.path.join(outputdir, *parts), parts
1462
1463
1464 # Aaargh. Distutils is not tested at all for the purpose of compiling
1465 # DLLs that are not extension modules. Here are some hacks to work
1466 # around that, in the _patch_for_*() functions...
1467
1468 def _patch_meth(patchlist, cls, name, new_meth):
1469 old = getattr(cls, name)
1470 patchlist.append((cls, name, old))
1471 setattr(cls, name, new_meth)
1472 return old
1473
1474 def _unpatch_meths(patchlist):
1475 for cls, name, old_meth in reversed(patchlist):
1476 setattr(cls, name, old_meth)
1477
1478 def _patch_for_embedding(patchlist):
1479 if sys.platform == 'win32':
1480 # we must not remove the manifest when building for embedding!
1481 # FUTURE: this module was removed in setuptools 74; this is likely dead code and should be removed,
1482 # since the toolchain it supports (VS2005-2008) is also long dead.
1483 from cffi._shimmed_dist_utils import MSVCCompiler
1484 if MSVCCompiler is not None:
1485 _patch_meth(patchlist, MSVCCompiler, '_remove_visual_c_ref',
1486 lambda self, manifest_file: manifest_file)
1487
1488 if sys.platform == 'darwin':
1489 # we must not make a '-bundle', but a '-dynamiclib' instead
1490 from cffi._shimmed_dist_utils import CCompiler
1491 def my_link_shared_object(self, *args, **kwds):
1492 if '-bundle' in self.linker_so:
1493 self.linker_so = list(self.linker_so)
1494 i = self.linker_so.index('-bundle')
1495 self.linker_so[i] = '-dynamiclib'
1496 return old_link_shared_object(self, *args, **kwds)
1497 old_link_shared_object = _patch_meth(patchlist, CCompiler,
1498 'link_shared_object',
1499 my_link_shared_object)
1500
1501 def _patch_for_target(patchlist, target):
1502 from cffi._shimmed_dist_utils import build_ext
1503 # if 'target' is different from '*', we need to patch some internal
1504 # method to just return this 'target' value, instead of having it
1505 # built from module_name
1506 if target.endswith('.*'):
1507 target = target[:-2]
1508 if sys.platform == 'win32':
1509 target += '.dll'
1510 elif sys.platform == 'darwin':
1511 target += '.dylib'
1512 else:
1513 target += '.so'
1514 _patch_meth(patchlist, build_ext, 'get_ext_filename',
1515 lambda self, ext_name: target)
1516
1517
1518 def recompile(ffi, module_name, preamble, tmpdir='.', call_c_compiler=True,
1519 c_file=None, source_extension='.c', extradir=None,
1520 compiler_verbose=1, target=None, debug=None,
1521 uses_ffiplatform=True, **kwds):
1522 if not isinstance(module_name, str):
1523 module_name = module_name.encode('ascii')
1524 if ffi._windows_unicode:
1525 ffi._apply_windows_unicode(kwds)
1526 if preamble is not None:
1527 if call_c_compiler and _is_file_like(c_file):
1528 raise TypeError("Writing to file-like objects is not supported "
1529 "with call_c_compiler=True")
1530 embedding = (ffi._embedding is not None)
1531 if embedding:
1532 ffi._apply_embedding_fix(kwds)
1533 if c_file is None:
1534 c_file, parts = _modname_to_file(tmpdir, module_name,
1535 source_extension)
1536 if extradir:
1537 parts = [extradir] + parts
1538 ext_c_file = os.path.join(*parts)
1539 else:
1540 ext_c_file = c_file
1541 #
1542 if target is None:
1543 if embedding:
1544 target = '%s.*' % module_name
1545 else:
1546 target = '*'
1547 #
1548 if uses_ffiplatform:
1549 ext = ffiplatform.get_extension(ext_c_file, module_name, **kwds)
1550 else:
1551 ext = None
1552 updated = make_c_source(ffi, module_name, preamble, c_file,
1553 verbose=compiler_verbose)
1554 if call_c_compiler:
1555 patchlist = []
1556 cwd = os.getcwd()
1557 try:
1558 if embedding:
1559 _patch_for_embedding(patchlist)
1560 if target != '*':
1561 _patch_for_target(patchlist, target)
1562 if compiler_verbose:
1563 if tmpdir == '.':
1564 msg = 'the current directory is'
1565 else:
1566 msg = 'setting the current directory to'
1567 print('%s %r' % (msg, os.path.abspath(tmpdir)))
1568 os.chdir(tmpdir)
1569 outputfilename = ffiplatform.compile('.', ext,
1570 compiler_verbose, debug)
1571 finally:
1572 os.chdir(cwd)
1573 _unpatch_meths(patchlist)
1574 return outputfilename
1575 else:
1576 return ext, updated
1577 else:
1578 if c_file is None:
1579 c_file, _ = _modname_to_file(tmpdir, module_name, '.py')
1580 updated = make_py_source(ffi, module_name, c_file,
1581 verbose=compiler_verbose)
1582 if call_c_compiler:
1583 return c_file
1584 else:
1585 return None, updated
1586