recompiler.py 64 KB

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