recompiler.py 64 KB

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