Debian Codegraph @

src/cffi/vengine_cpy.py

raw
1 #
2 # DEPRECATED: implementation for ffi.verify()
3 #
4 import sys
5 from . import model
6 from .error import VerificationError
7 from . import _imp_emulation as imp
8
9
10 class VCPythonEngine:
11 _class_key = 'x'
12 _gen_python_module = True
13
14 def __init__(self, verifier):
15 self.verifier = verifier
16 self.ffi = verifier.ffi
17 self._struct_pending_verification = {}
18 self._types_of_builtin_functions = {}
19
20 def patch_extension_kwds(self, kwds):
21 pass
22
23 def find_module(self, module_name, path, so_suffixes):
24 try:
25 f, filename, descr = imp.find_module(module_name, path)
26 except ImportError:
27 return None
28 if f is not None:
29 f.close()
30 # Note that after a setuptools installation, there are both .py
31 # and .so files with the same basename. The code here relies on
32 # imp.find_module() locating the .so in priority.
33 if descr[0] not in so_suffixes:
34 return None
35 return filename
36
37 def collect_types(self):
38 self._typesdict = {}
39 self._generate("collecttype")
40
41 def _prnt(self, what=''):
42 self._f.write(what + '\n')
43
44 def _gettypenum(self, type):
45 # a KeyError here is a bug. please report it! :-)
46 return self._typesdict[type]
47
48 def _do_collect_type(self, tp):
49 if ((not isinstance(tp, model.PrimitiveType)
50 or tp.name == 'long double')
51 and tp not in self._typesdict):
52 num = len(self._typesdict)
53 self._typesdict[tp] = num
54
55 def write_source_to_f(self):
56 self.collect_types()
57 #
58 # The new module will have a _cffi_setup() function that receives
59 # objects from the ffi world, and that calls some setup code in
60 # the module. This setup code is split in several independent
61 # functions, e.g. one per constant. The functions are "chained"
62 # by ending in a tail call to each other.
63 #
64 # This is further split in two chained lists, depending on if we
65 # can do it at import-time or if we must wait for _cffi_setup() to
66 # provide us with the <ctype> objects. This is needed because we
67 # need the values of the enum constants in order to build the
68 # <ctype 'enum'> that we may have to pass to _cffi_setup().
69 #
70 # The following two 'chained_list_constants' items contains
71 # the head of these two chained lists, as a string that gives the
72 # call to do, if any.
73 self._chained_list_constants = ['((void)lib,0)', '((void)lib,0)']
74 #
75 prnt = self._prnt
76 # first paste some standard set of lines that are mostly '#define'
77 prnt(cffimod_header)
78 prnt()
79 # then paste the C source given by the user, verbatim.
80 prnt(self.verifier.preamble)
81 prnt()
82 #
83 # call generate_cpy_xxx_decl(), for every xxx found from
84 # ffi._parser._declarations. This generates all the functions.
85 self._generate("decl")
86 #
87 # implement the function _cffi_setup_custom() as calling the
88 # head of the chained list.
89 self._generate_setup_custom()
90 prnt()
91 #
92 # produce the method table, including the entries for the
93 # generated Python->C function wrappers, which are done
94 # by generate_cpy_function_method().
95 prnt('static PyMethodDef _cffi_methods[] = {')
96 self._generate("method")
97 prnt(' {"_cffi_setup", _cffi_setup, METH_VARARGS, NULL},')
98 prnt(' {NULL, NULL, 0, NULL} /* Sentinel */')
99 prnt('};')
100 prnt()
101 #
102 # standard init.
103 modname = self.verifier.get_module_name()
104 constants = self._chained_list_constants[False]
105 prnt('static struct PyModuleDef _cffi_module_def = {')
106 prnt(' PyModuleDef_HEAD_INIT,')
107 prnt(' "%s",' % modname)
108 prnt(' NULL,')
109 prnt(' -1,')
110 prnt(' _cffi_methods,')
111 prnt(' NULL, NULL, NULL, NULL')
112 prnt('};')
113 prnt()
114 prnt('PyMODINIT_FUNC')
115 prnt('PyInit_%s(void)' % modname)
116 prnt('{')
117 prnt(' PyObject *lib;')
118 prnt(' lib = PyModule_Create(&_cffi_module_def);')
119 prnt(' if (lib == NULL)')
120 prnt(' return NULL;')
121 prnt(' if (%s < 0 || _cffi_init() < 0) {' % (constants,))
122 prnt(' Py_DECREF(lib);')
123 prnt(' return NULL;')
124 prnt(' }')
125 prnt('#if Py_GIL_DISABLED')
126 prnt(' PyUnstable_Module_SetGIL(lib, Py_MOD_GIL_NOT_USED);')
127 prnt('#endif')
128 prnt(' return lib;')
129 prnt('}')
130 prnt()
131
132 def load_library(self, flags=None):
133 # XXX review all usages of 'self' here!
134 # import it as a new extension module
135 imp.acquire_lock()
136 try:
137 if hasattr(sys, "getdlopenflags"):
138 previous_flags = sys.getdlopenflags()
139 try:
140 if hasattr(sys, "setdlopenflags") and flags is not None:
141 sys.setdlopenflags(flags)
142 module = imp.load_dynamic(self.verifier.get_module_name(),
143 self.verifier.modulefilename)
144 except ImportError as e:
145 error = "importing %r: %s" % (self.verifier.modulefilename, e)
146 raise VerificationError(error)
147 finally:
148 if hasattr(sys, "setdlopenflags"):
149 sys.setdlopenflags(previous_flags)
150 finally:
151 imp.release_lock()
152 #
153 # call loading_cpy_struct() to get the struct layout inferred by
154 # the C compiler
155 self._load(module, 'loading')
156 #
157 # the C code will need the <ctype> objects. Collect them in
158 # order in a list.
159 revmapping = dict([(value, key)
160 for (key, value) in self._typesdict.items()])
161 lst = [revmapping[i] for i in range(len(revmapping))]
162 lst = list(map(self.ffi._get_cached_btype, lst))
163 #
164 # build the FFILibrary class and instance and call _cffi_setup().
165 # this will set up some fields like '_cffi_types', and only then
166 # it will invoke the chained list of functions that will really
167 # build (notably) the constant objects, as <cdata> if they are
168 # pointers, and store them as attributes on the 'library' object.
169 class FFILibrary:
170 _cffi_python_module = module
171 _cffi_ffi = self.ffi
172 _cffi_dir = []
173 def __dir__(self):
174 return FFILibrary._cffi_dir + list(self.__dict__)
175 library = FFILibrary()
176 if module._cffi_setup(lst, VerificationError, library):
177 import warnings
178 warnings.warn("reimporting %r might overwrite older definitions"
179 % (self.verifier.get_module_name()))
180 #
181 # finally, call the loaded_cpy_xxx() functions. This will perform
182 # the final adjustments, like copying the Python->C wrapper
183 # functions from the module to the 'library' object, and setting
184 # up the FFILibrary class with properties for the global C variables.
185 self._load(module, 'loaded', library=library)
186 module._cffi_original_ffi = self.ffi
187 module._cffi_types_of_builtin_funcs = self._types_of_builtin_functions
188 return library
189
190 def _get_declarations(self):
191 lst = [(key, tp) for (key, (tp, qual)) in
192 self.ffi._parser._declarations.items()]
193 lst.sort()
194 return lst
195
196 def _generate(self, step_name):
197 for name, tp in self._get_declarations():
198 kind, realname = name.split(' ', 1)
199 try:
200 method = getattr(self, '_generate_cpy_%s_%s' % (kind,
201 step_name))
202 except AttributeError:
203 raise VerificationError(
204 "not implemented in verify(): %r" % name)
205 try:
206 method(tp, realname)
207 except Exception as e:
208 model.attach_exception_info(e, name)
209 raise
210
211 def _load(self, module, step_name, **kwds):
212 for name, tp in self._get_declarations():
213 kind, realname = name.split(' ', 1)
214 method = getattr(self, '_%s_cpy_%s' % (step_name, kind))
215 try:
216 method(tp, realname, module, **kwds)
217 except Exception as e:
218 model.attach_exception_info(e, name)
219 raise
220
221 def _generate_nothing(self, tp, name):
222 pass
223
224 def _loaded_noop(self, tp, name, module, **kwds):
225 pass
226
227 # ----------
228
229 def _convert_funcarg_to_c(self, tp, fromvar, tovar, errcode):
230 extraarg = ''
231 if isinstance(tp, model.PrimitiveType):
232 if tp.is_integer_type() and tp.name != '_Bool':
233 converter = '_cffi_to_c_int'
234 extraarg = ', %s' % tp.name
235 elif tp.is_complex_type():
236 raise VerificationError(
237 "not implemented in verify(): complex types")
238 else:
239 converter = '(%s)_cffi_to_c_%s' % (tp.get_c_name(''),
240 tp.name.replace(' ', '_'))
241 errvalue = '-1'
242 #
243 elif isinstance(tp, model.PointerType):
244 self._convert_funcarg_to_c_ptr_or_array(tp, fromvar,
245 tovar, errcode)
246 return
247 #
248 elif isinstance(tp, (model.StructOrUnion, model.EnumType)):
249 # a struct (not a struct pointer) as a function argument
250 self._prnt(' if (_cffi_to_c((char *)&%s, _cffi_type(%d), %s) < 0)'
251 % (tovar, self._gettypenum(tp), fromvar))
252 self._prnt(' %s;' % errcode)
253 return
254 #
255 elif isinstance(tp, model.FunctionPtrType):
256 converter = '(%s)_cffi_to_c_pointer' % tp.get_c_name('')
257 extraarg = ', _cffi_type(%d)' % self._gettypenum(tp)
258 errvalue = 'NULL'
259 #
260 else:
261 raise NotImplementedError(tp)
262 #
263 self._prnt(' %s = %s(%s%s);' % (tovar, converter, fromvar, extraarg))
264 self._prnt(' if (%s == (%s)%s && PyErr_Occurred())' % (
265 tovar, tp.get_c_name(''), errvalue))
266 self._prnt(' %s;' % errcode)
267
268 def _extra_local_variables(self, tp, localvars, freelines):
269 if isinstance(tp, model.PointerType):
270 localvars.add('Py_ssize_t datasize')
271 localvars.add('struct _cffi_freeme_s *large_args_free = NULL')
272 freelines.add('if (large_args_free != NULL)'
273 ' _cffi_free_array_arguments(large_args_free);')
274
275 def _convert_funcarg_to_c_ptr_or_array(self, tp, fromvar, tovar, errcode):
276 self._prnt(' datasize = _cffi_prepare_pointer_call_argument(')
277 self._prnt(' _cffi_type(%d), %s, (char **)&%s);' % (
278 self._gettypenum(tp), fromvar, tovar))
279 self._prnt(' if (datasize != 0) {')
280 self._prnt(' %s = ((size_t)datasize) <= 640 ? '
281 'alloca((size_t)datasize) : NULL;' % (tovar,))
282 self._prnt(' if (_cffi_convert_array_argument(_cffi_type(%d), %s, '
283 '(char **)&%s,' % (self._gettypenum(tp), fromvar, tovar))
284 self._prnt(' datasize, &large_args_free) < 0)')
285 self._prnt(' %s;' % errcode)
286 self._prnt(' }')
287
288 def _convert_expr_from_c(self, tp, var, context):
289 if isinstance(tp, model.PrimitiveType):
290 if tp.is_integer_type() and tp.name != '_Bool':
291 return '_cffi_from_c_int(%s, %s)' % (var, tp.name)
292 elif tp.name != 'long double':
293 return '_cffi_from_c_%s(%s)' % (tp.name.replace(' ', '_'), var)
294 else:
295 return '_cffi_from_c_deref((char *)&%s, _cffi_type(%d))' % (
296 var, self._gettypenum(tp))
297 elif isinstance(tp, (model.PointerType, model.FunctionPtrType)):
298 return '_cffi_from_c_pointer((char *)%s, _cffi_type(%d))' % (
299 var, self._gettypenum(tp))
300 elif isinstance(tp, model.ArrayType):
301 return '_cffi_from_c_pointer((char *)%s, _cffi_type(%d))' % (
302 var, self._gettypenum(model.PointerType(tp.item)))
303 elif isinstance(tp, model.StructOrUnion):
304 if tp.fldnames is None:
305 raise TypeError("'%s' is used as %s, but is opaque" % (
306 tp._get_c_name(), context))
307 return '_cffi_from_c_struct((char *)&%s, _cffi_type(%d))' % (
308 var, self._gettypenum(tp))
309 elif isinstance(tp, model.EnumType):
310 return '_cffi_from_c_deref((char *)&%s, _cffi_type(%d))' % (
311 var, self._gettypenum(tp))
312 else:
313 raise NotImplementedError(tp)
314
315 # ----------
316 # typedefs: generates no code so far
317
318 _generate_cpy_typedef_collecttype = _generate_nothing
319 _generate_cpy_typedef_decl = _generate_nothing
320 _generate_cpy_typedef_method = _generate_nothing
321 _loading_cpy_typedef = _loaded_noop
322 _loaded_cpy_typedef = _loaded_noop
323
324 # ----------
325 # function declarations
326
327 def _generate_cpy_function_collecttype(self, tp, name):
328 assert isinstance(tp, model.FunctionPtrType)
329 if tp.ellipsis:
330 self._do_collect_type(tp)
331 else:
332 # don't call _do_collect_type(tp) in this common case,
333 # otherwise test_autofilled_struct_as_argument fails
334 for type in tp.args:
335 self._do_collect_type(type)
336 self._do_collect_type(tp.result)
337
338 def _generate_cpy_function_decl(self, tp, name):
339 assert isinstance(tp, model.FunctionPtrType)
340 if tp.ellipsis:
341 # cannot support vararg functions better than this: check for its
342 # exact type (including the fixed arguments), and build it as a
343 # constant function pointer (no CPython wrapper)
344 self._generate_cpy_const(False, name, tp)
345 return
346 prnt = self._prnt
347 numargs = len(tp.args)
348 if numargs == 0:
349 argname = 'noarg'
350 elif numargs == 1:
351 argname = 'arg0'
352 else:
353 argname = 'args'
354 prnt('static PyObject *')
355 prnt('_cffi_f_%s(PyObject *self, PyObject *%s)' % (name, argname))
356 prnt('{')
357 #
358 context = 'argument of %s' % name
359 for i, type in enumerate(tp.args):
360 prnt(' %s;' % type.get_c_name(' x%d' % i, context))
361 #
362 localvars = set()
363 freelines = set()
364 for type in tp.args:
365 self._extra_local_variables(type, localvars, freelines)
366 for decl in sorted(localvars):
367 prnt(' %s;' % (decl,))
368 #
369 if not isinstance(tp.result, model.VoidType):
370 result_code = 'result = '
371 context = 'result of %s' % name
372 prnt(' %s;' % tp.result.get_c_name(' result', context))
373 prnt(' PyObject *pyresult;')
374 else:
375 result_code = ''
376 #
377 if len(tp.args) > 1:
378 rng = range(len(tp.args))
379 for i in rng:
380 prnt(' PyObject *arg%d;' % i)
381 prnt()
382 prnt(' if (!PyArg_ParseTuple(args, "%s:%s", %s))' % (
383 'O' * numargs, name, ', '.join(['&arg%d' % i for i in rng])))
384 prnt(' return NULL;')
385 prnt()
386 #
387 for i, type in enumerate(tp.args):
388 self._convert_funcarg_to_c(type, 'arg%d' % i, 'x%d' % i,
389 'return NULL')
390 prnt()
391 #
392 prnt(' Py_BEGIN_ALLOW_THREADS')
393 prnt(' _cffi_restore_errno();')
394 prnt(' { %s%s(%s); }' % (
395 result_code, name,
396 ', '.join(['x%d' % i for i in range(len(tp.args))])))
397 prnt(' _cffi_save_errno();')
398 prnt(' Py_END_ALLOW_THREADS')
399 prnt()
400 #
401 prnt(' (void)self; /* unused */')
402 if numargs == 0:
403 prnt(' (void)noarg; /* unused */')
404 if result_code:
405 prnt(' pyresult = %s;' %
406 self._convert_expr_from_c(tp.result, 'result', 'result type'))
407 for freeline in freelines:
408 prnt(' ' + freeline)
409 prnt(' return pyresult;')
410 else:
411 for freeline in freelines:
412 prnt(' ' + freeline)
413 prnt(' Py_INCREF(Py_None);')
414 prnt(' return Py_None;')
415 prnt('}')
416 prnt()
417
418 def _generate_cpy_function_method(self, tp, name):
419 if tp.ellipsis:
420 return
421 numargs = len(tp.args)
422 if numargs == 0:
423 meth = 'METH_NOARGS'
424 elif numargs == 1:
425 meth = 'METH_O'
426 else:
427 meth = 'METH_VARARGS'
428 self._prnt(' {"%s", _cffi_f_%s, %s, NULL},' % (name, name, meth))
429
430 _loading_cpy_function = _loaded_noop
431
432 def _loaded_cpy_function(self, tp, name, module, library):
433 if tp.ellipsis:
434 return
435 func = getattr(module, name)
436 setattr(library, name, func)
437 self._types_of_builtin_functions[func] = tp
438
439 # ----------
440 # named structs
441
442 _generate_cpy_struct_collecttype = _generate_nothing
443 def _generate_cpy_struct_decl(self, tp, name):
444 assert name == tp.name
445 self._generate_struct_or_union_decl(tp, 'struct', name)
446 def _generate_cpy_struct_method(self, tp, name):
447 self._generate_struct_or_union_method(tp, 'struct', name)
448 def _loading_cpy_struct(self, tp, name, module):
449 self._loading_struct_or_union(tp, 'struct', name, module)
450 def _loaded_cpy_struct(self, tp, name, module, **kwds):
451 self._loaded_struct_or_union(tp)
452
453 _generate_cpy_union_collecttype = _generate_nothing
454 def _generate_cpy_union_decl(self, tp, name):
455 assert name == tp.name
456 self._generate_struct_or_union_decl(tp, 'union', name)
457 def _generate_cpy_union_method(self, tp, name):
458 self._generate_struct_or_union_method(tp, 'union', name)
459 def _loading_cpy_union(self, tp, name, module):
460 self._loading_struct_or_union(tp, 'union', name, module)
461 def _loaded_cpy_union(self, tp, name, module, **kwds):
462 self._loaded_struct_or_union(tp)
463
464 def _generate_struct_or_union_decl(self, tp, prefix, name):
465 if tp.fldnames is None:
466 return # nothing to do with opaque structs
467 checkfuncname = '_cffi_check_%s_%s' % (prefix, name)
468 layoutfuncname = '_cffi_layout_%s_%s' % (prefix, name)
469 cname = ('%s %s' % (prefix, name)).strip()
470 #
471 prnt = self._prnt
472 prnt('static void %s(%s *p)' % (checkfuncname, cname))
473 prnt('{')
474 prnt(' /* only to generate compile-time warnings or errors */')
475 prnt(' (void)p;')
476 for fname, ftype, fbitsize, fqual in tp.enumfields():
477 if (isinstance(ftype, model.PrimitiveType)
478 and ftype.is_integer_type()) or fbitsize >= 0:
479 # accept all integers, but complain on float or double
480 prnt(' (void)((p->%s) << 1);' % fname)
481 else:
482 # only accept exactly the type declared.
483 try:
484 prnt(' { %s = &p->%s; (void)tmp; }' % (
485 ftype.get_c_name('*tmp', 'field %r'%fname, quals=fqual),
486 fname))
487 except VerificationError as e:
488 prnt(' /* %s */' % str(e)) # cannot verify it, ignore
489 prnt('}')
490 prnt('static PyObject *')
491 prnt('%s(PyObject *self, PyObject *noarg)' % (layoutfuncname,))
492 prnt('{')
493 prnt(' struct _cffi_aligncheck { char x; %s y; };' % cname)
494 prnt(' static Py_ssize_t nums[] = {')
495 prnt(' sizeof(%s),' % cname)
496 prnt(' offsetof(struct _cffi_aligncheck, y),')
497 for fname, ftype, fbitsize, fqual in tp.enumfields():
498 if fbitsize >= 0:
499 continue # xxx ignore fbitsize for now
500 prnt(' offsetof(%s, %s),' % (cname, fname))
501 if isinstance(ftype, model.ArrayType) and ftype.length is None:
502 prnt(' 0, /* %s */' % ftype._get_c_name())
503 else:
504 prnt(' sizeof(((%s *)0)->%s),' % (cname, fname))
505 prnt(' -1')
506 prnt(' };')
507 prnt(' (void)self; /* unused */')
508 prnt(' (void)noarg; /* unused */')
509 prnt(' return _cffi_get_struct_layout(nums);')
510 prnt(' /* the next line is not executed, but compiled */')
511 prnt(' %s(0);' % (checkfuncname,))
512 prnt('}')
513 prnt()
514
515 def _generate_struct_or_union_method(self, tp, prefix, name):
516 if tp.fldnames is None:
517 return # nothing to do with opaque structs
518 layoutfuncname = '_cffi_layout_%s_%s' % (prefix, name)
519 self._prnt(' {"%s", %s, METH_NOARGS, NULL},' % (layoutfuncname,
520 layoutfuncname))
521
522 def _loading_struct_or_union(self, tp, prefix, name, module):
523 if tp.fldnames is None:
524 return # nothing to do with opaque structs
525 layoutfuncname = '_cffi_layout_%s_%s' % (prefix, name)
526 #
527 function = getattr(module, layoutfuncname)
528 layout = function()
529 if isinstance(tp, model.StructOrUnion) and tp.partial:
530 # use the function()'s sizes and offsets to guide the
531 # layout of the struct
532 totalsize = layout[0]
533 totalalignment = layout[1]
534 fieldofs = layout[2::2]
535 fieldsize = layout[3::2]
536 tp.force_flatten()
537 assert len(fieldofs) == len(fieldsize) == len(tp.fldnames)
538 tp.fixedlayout = fieldofs, fieldsize, totalsize, totalalignment
539 else:
540 cname = ('%s %s' % (prefix, name)).strip()
541 self._struct_pending_verification[tp] = layout, cname
542
543 def _loaded_struct_or_union(self, tp):
544 if tp.fldnames is None:
545 return # nothing to do with opaque structs
546 self.ffi._get_cached_btype(tp) # force 'fixedlayout' to be considered
547
548 if tp in self._struct_pending_verification:
549 # check that the layout sizes and offsets match the real ones
550 def check(realvalue, expectedvalue, msg):
551 if realvalue != expectedvalue:
552 raise VerificationError(
553 "%s (we have %d, but C compiler says %d)"
554 % (msg, expectedvalue, realvalue))
555 ffi = self.ffi
556 BStruct = ffi._get_cached_btype(tp)
557 layout, cname = self._struct_pending_verification.pop(tp)
558 check(layout[0], ffi.sizeof(BStruct), "wrong total size")
559 check(layout[1], ffi.alignof(BStruct), "wrong total alignment")
560 i = 2
561 for fname, ftype, fbitsize, fqual in tp.enumfields():
562 if fbitsize >= 0:
563 continue # xxx ignore fbitsize for now
564 check(layout[i], ffi.offsetof(BStruct, fname),
565 "wrong offset for field %r" % (fname,))
566 if layout[i+1] != 0:
567 BField = ffi._get_cached_btype(ftype)
568 check(layout[i+1], ffi.sizeof(BField),
569 "wrong size for field %r" % (fname,))
570 i += 2
571 assert i == len(layout)
572
573 # ----------
574 # 'anonymous' declarations. These are produced for anonymous structs
575 # or unions; the 'name' is obtained by a typedef.
576
577 _generate_cpy_anonymous_collecttype = _generate_nothing
578
579 def _generate_cpy_anonymous_decl(self, tp, name):
580 if isinstance(tp, model.EnumType):
581 self._generate_cpy_enum_decl(tp, name, '')
582 else:
583 self._generate_struct_or_union_decl(tp, '', name)
584
585 def _generate_cpy_anonymous_method(self, tp, name):
586 if not isinstance(tp, model.EnumType):
587 self._generate_struct_or_union_method(tp, '', name)
588
589 def _loading_cpy_anonymous(self, tp, name, module):
590 if isinstance(tp, model.EnumType):
591 self._loading_cpy_enum(tp, name, module)
592 else:
593 self._loading_struct_or_union(tp, '', name, module)
594
595 def _loaded_cpy_anonymous(self, tp, name, module, **kwds):
596 if isinstance(tp, model.EnumType):
597 self._loaded_cpy_enum(tp, name, module, **kwds)
598 else:
599 self._loaded_struct_or_union(tp)
600
601 # ----------
602 # constants, likely declared with '#define'
603
604 def _generate_cpy_const(self, is_int, name, tp=None, category='const',
605 vartp=None, delayed=True, size_too=False,
606 check_value=None):
607 prnt = self._prnt
608 funcname = '_cffi_%s_%s' % (category, name)
609 prnt('static int %s(PyObject *lib)' % funcname)
610 prnt('{')
611 prnt(' PyObject *o;')
612 prnt(' int res;')
613 if not is_int:
614 prnt(' %s;' % (vartp or tp).get_c_name(' i', name))
615 else:
616 assert category == 'const'
617 #
618 if check_value is not None:
619 self._check_int_constant_value(name, check_value)
620 #
621 if not is_int:
622 if category == 'var':
623 realexpr = '&' + name
624 else:
625 realexpr = name
626 prnt(' i = (%s);' % (realexpr,))
627 prnt(' o = %s;' % (self._convert_expr_from_c(tp, 'i',
628 'variable type'),))
629 assert delayed
630 else:
631 prnt(' o = _cffi_from_c_int_const(%s);' % name)
632 prnt(' if (o == NULL)')
633 prnt(' return -1;')
634 if size_too:
635 prnt(' {')
636 prnt(' PyObject *o1 = o;')
637 prnt(' o = Py_BuildValue("On", o1, (Py_ssize_t)sizeof(%s));'
638 % (name,))
639 prnt(' Py_DECREF(o1);')
640 prnt(' if (o == NULL)')
641 prnt(' return -1;')
642 prnt(' }')
643 prnt(' res = PyObject_SetAttrString(lib, "%s", o);' % name)
644 prnt(' Py_DECREF(o);')
645 prnt(' if (res < 0)')
646 prnt(' return -1;')
647 prnt(' return %s;' % self._chained_list_constants[delayed])
648 self._chained_list_constants[delayed] = funcname + '(lib)'
649 prnt('}')
650 prnt()
651
652 def _generate_cpy_constant_collecttype(self, tp, name):
653 is_int = isinstance(tp, model.PrimitiveType) and tp.is_integer_type()
654 if not is_int:
655 self._do_collect_type(tp)
656
657 def _generate_cpy_constant_decl(self, tp, name):
658 is_int = isinstance(tp, model.PrimitiveType) and tp.is_integer_type()
659 self._generate_cpy_const(is_int, name, tp)
660
661 _generate_cpy_constant_method = _generate_nothing
662 _loading_cpy_constant = _loaded_noop
663 _loaded_cpy_constant = _loaded_noop
664
665 # ----------
666 # enums
667
668 def _check_int_constant_value(self, name, value, err_prefix=''):
669 prnt = self._prnt
670 if value <= 0:
671 prnt(' if ((%s) > 0 || (long)(%s) != %dL) {' % (
672 name, name, value))
673 else:
674 prnt(' if ((%s) <= 0 || (unsigned long)(%s) != %dUL) {' % (
675 name, name, value))
676 prnt(' char buf[64];')
677 prnt(' if ((%s) <= 0)' % name)
678 prnt(' snprintf(buf, 63, "%%ld", (long)(%s));' % name)
679 prnt(' else')
680 prnt(' snprintf(buf, 63, "%%lu", (unsigned long)(%s));' %
681 name)
682 prnt(' PyErr_Format(_cffi_VerificationError,')
683 prnt(' "%s%s has the real value %s, not %s",')
684 prnt(' "%s", "%s", buf, "%d");' % (
685 err_prefix, name, value))
686 prnt(' return -1;')
687 prnt(' }')
688
689 def _enum_funcname(self, prefix, name):
690 # "$enum_$1" => "___D_enum____D_1"
691 name = name.replace('$', '___D_')
692 return '_cffi_e_%s_%s' % (prefix, name)
693
694 def _generate_cpy_enum_decl(self, tp, name, prefix='enum'):
695 if tp.partial:
696 for enumerator in tp.enumerators:
697 self._generate_cpy_const(True, enumerator, delayed=False)
698 return
699 #
700 funcname = self._enum_funcname(prefix, name)
701 prnt = self._prnt
702 prnt('static int %s(PyObject *lib)' % funcname)
703 prnt('{')
704 for enumerator, enumvalue in zip(tp.enumerators, tp.enumvalues):
705 self._check_int_constant_value(enumerator, enumvalue,
706 "enum %s: " % name)
707 prnt(' return %s;' % self._chained_list_constants[True])
708 self._chained_list_constants[True] = funcname + '(lib)'
709 prnt('}')
710 prnt()
711
712 _generate_cpy_enum_collecttype = _generate_nothing
713 _generate_cpy_enum_method = _generate_nothing
714
715 def _loading_cpy_enum(self, tp, name, module):
716 if tp.partial:
717 enumvalues = [getattr(module, enumerator)
718 for enumerator in tp.enumerators]
719 tp.enumvalues = tuple(enumvalues)
720 tp.partial_resolved = True
721
722 def _loaded_cpy_enum(self, tp, name, module, library):
723 for enumerator, enumvalue in zip(tp.enumerators, tp.enumvalues):
724 setattr(library, enumerator, enumvalue)
725
726 # ----------
727 # macros: for now only for integers
728
729 def _generate_cpy_macro_decl(self, tp, name):
730 if tp == '...':
731 check_value = None
732 else:
733 check_value = tp # an integer
734 self._generate_cpy_const(True, name, check_value=check_value)
735
736 _generate_cpy_macro_collecttype = _generate_nothing
737 _generate_cpy_macro_method = _generate_nothing
738 _loading_cpy_macro = _loaded_noop
739 _loaded_cpy_macro = _loaded_noop
740
741 # ----------
742 # global variables
743
744 def _generate_cpy_variable_collecttype(self, tp, name):
745 if isinstance(tp, model.ArrayType):
746 tp_ptr = model.PointerType(tp.item)
747 else:
748 tp_ptr = model.PointerType(tp)
749 self._do_collect_type(tp_ptr)
750
751 def _generate_cpy_variable_decl(self, tp, name):
752 if isinstance(tp, model.ArrayType):
753 tp_ptr = model.PointerType(tp.item)
754 self._generate_cpy_const(False, name, tp, vartp=tp_ptr,
755 size_too = tp.length_is_unknown())
756 else:
757 tp_ptr = model.PointerType(tp)
758 self._generate_cpy_const(False, name, tp_ptr, category='var')
759
760 _generate_cpy_variable_method = _generate_nothing
761 _loading_cpy_variable = _loaded_noop
762
763 def _loaded_cpy_variable(self, tp, name, module, library):
764 value = getattr(library, name)
765 if isinstance(tp, model.ArrayType): # int a[5] is "constant" in the
766 # sense that "a=..." is forbidden
767 if tp.length_is_unknown():
768 assert isinstance(value, tuple)
769 (value, size) = value
770 BItemType = self.ffi._get_cached_btype(tp.item)
771 length, rest = divmod(size, self.ffi.sizeof(BItemType))
772 if rest != 0:
773 raise VerificationError(
774 "bad size: %r does not seem to be an array of %s" %
775 (name, tp.item))
776 tp = tp.resolve_length(length)
777 # 'value' is a <cdata 'type *'> which we have to replace with
778 # a <cdata 'type[N]'> if the N is actually known
779 if tp.length is not None:
780 BArray = self.ffi._get_cached_btype(tp)
781 value = self.ffi.cast(BArray, value)
782 setattr(library, name, value)
783 return
784 # remove ptr=<cdata 'int *'> from the library instance, and replace
785 # it by a property on the class, which reads/writes into ptr[0].
786 ptr = value
787 delattr(library, name)
788 def getter(library):
789 return ptr[0]
790 def setter(library, value):
791 ptr[0] = value
792 setattr(type(library), name, property(getter, setter))
793 type(library)._cffi_dir.append(name)
794
795 # ----------
796
797 def _generate_setup_custom(self):
798 prnt = self._prnt
799 prnt('static int _cffi_setup_custom(PyObject *lib)')
800 prnt('{')
801 prnt(' return %s;' % self._chained_list_constants[True])
802 prnt('}')
803
804 cffimod_header = r'''
805 #include <Python.h>
806 #include <stddef.h>
807
808 /* this block of #ifs should be kept exactly identical between
809 c/_cffi_backend.c, cffi/vengine_cpy.py, cffi/vengine_gen.py
810 and cffi/_cffi_include.h */
811 #if defined(_MSC_VER)
812 # include <malloc.h> /* for alloca() */
813 # if _MSC_VER < 1600 /* MSVC < 2010 */
814 typedef __int8 int8_t;
815 typedef __int16 int16_t;
816 typedef __int32 int32_t;
817 typedef __int64 int64_t;
818 typedef unsigned __int8 uint8_t;
819 typedef unsigned __int16 uint16_t;
820 typedef unsigned __int32 uint32_t;
821 typedef unsigned __int64 uint64_t;
822 typedef __int8 int_least8_t;
823 typedef __int16 int_least16_t;
824 typedef __int32 int_least32_t;
825 typedef __int64 int_least64_t;
826 typedef unsigned __int8 uint_least8_t;
827 typedef unsigned __int16 uint_least16_t;
828 typedef unsigned __int32 uint_least32_t;
829 typedef unsigned __int64 uint_least64_t;
830 typedef __int8 int_fast8_t;
831 typedef __int16 int_fast16_t;
832 typedef __int32 int_fast32_t;
833 typedef __int64 int_fast64_t;
834 typedef unsigned __int8 uint_fast8_t;
835 typedef unsigned __int16 uint_fast16_t;
836 typedef unsigned __int32 uint_fast32_t;
837 typedef unsigned __int64 uint_fast64_t;
838 typedef __int64 intmax_t;
839 typedef unsigned __int64 uintmax_t;
840 # else
841 # include <stdint.h>
842 # endif
843 # if _MSC_VER < 1800 /* MSVC < 2013 */
844 # ifndef __cplusplus
845 typedef unsigned char _Bool;
846 # endif
847 # endif
848 # define _cffi_float_complex_t _Fcomplex /* include <complex.h> for it */
849 # define _cffi_double_complex_t _Dcomplex /* include <complex.h> for it */
850 #else
851 # include <stdint.h>
852 # if (defined (__SVR4) && defined (__sun)) || defined(_AIX) || defined(__hpux)
853 # include <alloca.h>
854 # endif
855 # define _cffi_float_complex_t float _Complex
856 # define _cffi_double_complex_t double _Complex
857 #endif
858
859 #define _cffi_from_c_double PyFloat_FromDouble
860 #define _cffi_from_c_float PyFloat_FromDouble
861 #define _cffi_from_c_long PyLong_FromLong
862 #define _cffi_from_c_ulong PyLong_FromUnsignedLong
863 #define _cffi_from_c_longlong PyLong_FromLongLong
864 #define _cffi_from_c_ulonglong PyLong_FromUnsignedLongLong
865 #define _cffi_from_c__Bool PyBool_FromLong
866
867 #define _cffi_to_c_double PyFloat_AsDouble
868 #define _cffi_to_c_float PyFloat_AsDouble
869
870 #define _cffi_from_c_int_const(x) \
871 (((x) > 0) ? \
872 ((unsigned long long)(x) <= (unsigned long long)LONG_MAX) ? \
873 PyLong_FromLong((long)(x)) : \
874 PyLong_FromUnsignedLongLong((unsigned long long)(x)) : \
875 ((long long)(x) >= (long long)LONG_MIN) ? \
876 PyLong_FromLong((long)(x)) : \
877 PyLong_FromLongLong((long long)(x)))
878
879 #define _cffi_from_c_int(x, type) \
880 (((type)-1) > 0 ? /* unsigned */ \
881 (sizeof(type) < sizeof(long) ? \
882 PyLong_FromLong((long)x) : \
883 sizeof(type) == sizeof(long) ? \
884 PyLong_FromUnsignedLong((unsigned long)x) : \
885 PyLong_FromUnsignedLongLong((unsigned long long)x)) : \
886 (sizeof(type) <= sizeof(long) ? \
887 PyLong_FromLong((long)x) : \
888 PyLong_FromLongLong((long long)x)))
889
890 #define _cffi_to_c_int(o, type) \
891 ((type)( \
892 sizeof(type) == 1 ? (((type)-1) > 0 ? (type)_cffi_to_c_u8(o) \
893 : (type)_cffi_to_c_i8(o)) : \
894 sizeof(type) == 2 ? (((type)-1) > 0 ? (type)_cffi_to_c_u16(o) \
895 : (type)_cffi_to_c_i16(o)) : \
896 sizeof(type) == 4 ? (((type)-1) > 0 ? (type)_cffi_to_c_u32(o) \
897 : (type)_cffi_to_c_i32(o)) : \
898 sizeof(type) == 8 ? (((type)-1) > 0 ? (type)_cffi_to_c_u64(o) \
899 : (type)_cffi_to_c_i64(o)) : \
900 (Py_FatalError("unsupported size for type " #type), (type)0)))
901
902 #define _cffi_to_c_i8 \
903 ((int(*)(PyObject *))_cffi_exports[1])
904 #define _cffi_to_c_u8 \
905 ((int(*)(PyObject *))_cffi_exports[2])
906 #define _cffi_to_c_i16 \
907 ((int(*)(PyObject *))_cffi_exports[3])
908 #define _cffi_to_c_u16 \
909 ((int(*)(PyObject *))_cffi_exports[4])
910 #define _cffi_to_c_i32 \
911 ((int(*)(PyObject *))_cffi_exports[5])
912 #define _cffi_to_c_u32 \
913 ((unsigned int(*)(PyObject *))_cffi_exports[6])
914 #define _cffi_to_c_i64 \
915 ((long long(*)(PyObject *))_cffi_exports[7])
916 #define _cffi_to_c_u64 \
917 ((unsigned long long(*)(PyObject *))_cffi_exports[8])
918 #define _cffi_to_c_char \
919 ((int(*)(PyObject *))_cffi_exports[9])
920 #define _cffi_from_c_pointer \
921 ((PyObject *(*)(char *, CTypeDescrObject *))_cffi_exports[10])
922 #define _cffi_to_c_pointer \
923 ((char *(*)(PyObject *, CTypeDescrObject *))_cffi_exports[11])
924 #define _cffi_get_struct_layout \
925 ((PyObject *(*)(Py_ssize_t[]))_cffi_exports[12])
926 #define _cffi_restore_errno \
927 ((void(*)(void))_cffi_exports[13])
928 #define _cffi_save_errno \
929 ((void(*)(void))_cffi_exports[14])
930 #define _cffi_from_c_char \
931 ((PyObject *(*)(char))_cffi_exports[15])
932 #define _cffi_from_c_deref \
933 ((PyObject *(*)(char *, CTypeDescrObject *))_cffi_exports[16])
934 #define _cffi_to_c \
935 ((int(*)(char *, CTypeDescrObject *, PyObject *))_cffi_exports[17])
936 #define _cffi_from_c_struct \
937 ((PyObject *(*)(char *, CTypeDescrObject *))_cffi_exports[18])
938 #define _cffi_to_c_wchar_t \
939 ((wchar_t(*)(PyObject *))_cffi_exports[19])
940 #define _cffi_from_c_wchar_t \
941 ((PyObject *(*)(wchar_t))_cffi_exports[20])
942 #define _cffi_to_c_long_double \
943 ((long double(*)(PyObject *))_cffi_exports[21])
944 #define _cffi_to_c__Bool \
945 ((_Bool(*)(PyObject *))_cffi_exports[22])
946 #define _cffi_prepare_pointer_call_argument \
947 ((Py_ssize_t(*)(CTypeDescrObject *, PyObject *, char **))_cffi_exports[23])
948 #define _cffi_convert_array_from_object \
949 ((int(*)(char *, CTypeDescrObject *, PyObject *))_cffi_exports[24])
950 #define _CFFI_NUM_EXPORTS 25
951
952 typedef struct _ctypedescr CTypeDescrObject;
953
954 static void *_cffi_exports[_CFFI_NUM_EXPORTS];
955 static PyObject *_cffi_types, *_cffi_VerificationError;
956
957 static int _cffi_setup_custom(PyObject *lib); /* forward */
958
959 static PyObject *_cffi_setup(PyObject *self, PyObject *args)
960 {
961 PyObject *library;
962 int was_alive = (_cffi_types != NULL);
963 (void)self; /* unused */
964 if (!PyArg_ParseTuple(args, "OOO", &_cffi_types, &_cffi_VerificationError,
965 &library))
966 return NULL;
967 Py_INCREF(_cffi_types);
968 Py_INCREF(_cffi_VerificationError);
969 if (_cffi_setup_custom(library) < 0)
970 return NULL;
971 return PyBool_FromLong(was_alive);
972 }
973
974 union _cffi_union_alignment_u {
975 unsigned char m_char;
976 unsigned short m_short;
977 unsigned int m_int;
978 unsigned long m_long;
979 unsigned long long m_longlong;
980 float m_float;
981 double m_double;
982 long double m_longdouble;
983 };
984
985 struct _cffi_freeme_s {
986 struct _cffi_freeme_s *next;
987 union _cffi_union_alignment_u alignment;
988 };
989
990 #ifdef __GNUC__
991 __attribute__((unused))
992 #endif
993 static int _cffi_convert_array_argument(CTypeDescrObject *ctptr, PyObject *arg,
994 char **output_data, Py_ssize_t datasize,
995 struct _cffi_freeme_s **freeme)
996 {
997 char *p;
998 if (datasize < 0)
999 return -1;
1000
1001 p = *output_data;
1002 if (p == NULL) {
1003 struct _cffi_freeme_s *fp = (struct _cffi_freeme_s *)PyObject_Malloc(
1004 offsetof(struct _cffi_freeme_s, alignment) + (size_t)datasize);
1005 if (fp == NULL)
1006 return -1;
1007 fp->next = *freeme;
1008 *freeme = fp;
1009 p = *output_data = (char *)&fp->alignment;
1010 }
1011 memset((void *)p, 0, (size_t)datasize);
1012 return _cffi_convert_array_from_object(p, ctptr, arg);
1013 }
1014
1015 #ifdef __GNUC__
1016 __attribute__((unused))
1017 #endif
1018 static void _cffi_free_array_arguments(struct _cffi_freeme_s *freeme)
1019 {
1020 do {
1021 void *p = (void *)freeme;
1022 freeme = freeme->next;
1023 PyObject_Free(p);
1024 } while (freeme != NULL);
1025 }
1026
1027 static int _cffi_init(void)
1028 {
1029 PyObject *module, *c_api_object = NULL;
1030
1031 module = PyImport_ImportModule("_cffi_backend");
1032 if (module == NULL)
1033 goto failure;
1034
1035 c_api_object = PyObject_GetAttrString(module, "_C_API");
1036 if (c_api_object == NULL)
1037 goto failure;
1038 if (!PyCapsule_CheckExact(c_api_object)) {
1039 PyErr_SetNone(PyExc_ImportError);
1040 goto failure;
1041 }
1042 memcpy(_cffi_exports, PyCapsule_GetPointer(c_api_object, "cffi"),
1043 _CFFI_NUM_EXPORTS * sizeof(void *));
1044
1045 Py_DECREF(module);
1046 Py_DECREF(c_api_object);
1047 return 0;
1048
1049 failure:
1050 Py_XDECREF(module);
1051 Py_XDECREF(c_api_object);
1052 return -1;
1053 }
1054
1055 #define _cffi_type(num) ((CTypeDescrObject *)PyList_GET_ITEM(_cffi_types, num))
1056
1057 /**********/
1058 '''