You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

vengine_cpy.py 40KB

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