PageRenderTime 52ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/rpython/rtyper/lltypesystem/rffi.py

https://bitbucket.org/pjenvey/pypy-mq
Python | 1297 lines | 1144 code | 44 blank | 109 comment | 58 complexity | 36314a8894a7fa59a90ecbbce44eb2af MD5 | raw file
Possible License(s): Apache-2.0, AGPL-3.0, BSD-3-Clause

Large files files are truncated, but you can click here to view the full file

  1. import py
  2. from rpython.annotator import model as annmodel
  3. from rpython.rtyper.llannotation import SomePtr
  4. from rpython.rtyper.lltypesystem import lltype
  5. from rpython.rtyper.lltypesystem import ll2ctypes
  6. from rpython.rtyper.lltypesystem.llmemory import cast_ptr_to_adr
  7. from rpython.rtyper.lltypesystem.llmemory import itemoffsetof
  8. from rpython.rtyper.llannotation import lltype_to_annotation
  9. from rpython.tool.sourcetools import func_with_new_name
  10. from rpython.rlib.objectmodel import Symbolic
  11. from rpython.rlib.objectmodel import keepalive_until_here, enforceargs
  12. from rpython.rlib import rarithmetic, rgc
  13. from rpython.rtyper.extregistry import ExtRegistryEntry
  14. from rpython.rlib.unroll import unrolling_iterable
  15. from rpython.rtyper.tool.rfficache import platform, sizeof_c_type
  16. from rpython.translator.tool.cbuild import ExternalCompilationInfo
  17. from rpython.rtyper.annlowlevel import llhelper
  18. from rpython.rlib.objectmodel import we_are_translated, we_are_translated_to_c
  19. from rpython.rlib.rstring import StringBuilder, UnicodeBuilder, assert_str0
  20. from rpython.rlib import jit
  21. from rpython.rtyper.lltypesystem import llmemory
  22. from rpython.rlib.rarithmetic import maxint, LONG_BIT
  23. from rpython.translator.platform import CompilationError
  24. import os, sys
  25. class CConstant(Symbolic):
  26. """ A C-level constant, maybe #define, rendered directly.
  27. """
  28. def __init__(self, c_name, TP):
  29. self.c_name = c_name
  30. self.TP = TP
  31. def __repr__(self):
  32. return '%s(%r, %s)' % (self.__class__.__name__,
  33. self.c_name, self.TP)
  34. def annotation(self):
  35. return lltype_to_annotation(self.TP)
  36. def lltype(self):
  37. return self.TP
  38. def _isfunctype(TP):
  39. """ Evil hack to get rid of flow objspace inability
  40. to accept .TO when TP is not a pointer
  41. """
  42. return isinstance(TP, lltype.Ptr) and isinstance(TP.TO, lltype.FuncType)
  43. _isfunctype._annspecialcase_ = 'specialize:memo'
  44. def _isllptr(p):
  45. """ Second evil hack to detect if 'p' is a low-level pointer or not """
  46. return isinstance(p, lltype._ptr)
  47. class _IsLLPtrEntry(ExtRegistryEntry):
  48. _about_ = _isllptr
  49. def compute_result_annotation(self, s_p):
  50. result = isinstance(s_p, SomePtr)
  51. return self.bookkeeper.immutablevalue(result)
  52. def specialize_call(self, hop):
  53. hop.exception_cannot_occur()
  54. return hop.inputconst(lltype.Bool, hop.s_result.const)
  55. RFFI_SAVE_ERRNO = 1 # save the real errno after the call
  56. RFFI_READSAVED_ERRNO = 2 # copy saved errno into real errno before call
  57. RFFI_ZERO_ERRNO_BEFORE = 4 # copy the value 0 into real errno before call
  58. RFFI_FULL_ERRNO = RFFI_SAVE_ERRNO | RFFI_READSAVED_ERRNO
  59. RFFI_FULL_ERRNO_ZERO = RFFI_SAVE_ERRNO | RFFI_ZERO_ERRNO_BEFORE
  60. RFFI_SAVE_LASTERROR = 8 # win32: save GetLastError() after the call
  61. RFFI_READSAVED_LASTERROR = 16 # win32: call SetLastError() before the call
  62. RFFI_SAVE_WSALASTERROR = 32 # win32: save WSAGetLastError() after the call
  63. RFFI_FULL_LASTERROR = RFFI_SAVE_LASTERROR | RFFI_READSAVED_LASTERROR
  64. RFFI_ERR_NONE = 0
  65. RFFI_ERR_ALL = RFFI_FULL_ERRNO | RFFI_FULL_LASTERROR
  66. RFFI_ALT_ERRNO = 64 # read, save using alt tl destination
  67. def llexternal(name, args, result, _callable=None,
  68. compilation_info=ExternalCompilationInfo(),
  69. sandboxsafe=False, releasegil='auto',
  70. _nowrapper=False, calling_conv='c',
  71. elidable_function=False, macro=None,
  72. random_effects_on_gcobjs='auto',
  73. save_err=RFFI_ERR_NONE):
  74. """Build an external function that will invoke the C function 'name'
  75. with the given 'args' types and 'result' type.
  76. You get by default a wrapper that casts between number types as needed
  77. to match the arguments. You can also pass an RPython string when a
  78. CCHARP argument is expected, and the C function receives a 'const char*'
  79. pointing to a read-only null-terminated character of arrays, as usual
  80. for C.
  81. The C function can have callbacks, but they must be specified explicitly
  82. as constant RPython functions. We don't support yet C functions that
  83. invoke callbacks passed otherwise (e.g. set by a previous C call).
  84. releasegil: whether it's ok to release the GIL around the call.
  85. Default is yes, unless sandboxsafe is set, in which case
  86. we consider that the function is really short-running and
  87. don't bother releasing the GIL. An explicit True or False
  88. overrides this logic.
  89. """
  90. if _callable is not None:
  91. assert callable(_callable)
  92. ext_type = lltype.FuncType(args, result)
  93. if _callable is None:
  94. if macro is not None:
  95. if macro is True:
  96. macro = name
  97. _callable = generate_macro_wrapper(
  98. name, macro, ext_type, compilation_info)
  99. else:
  100. _callable = ll2ctypes.LL2CtypesCallable(ext_type, calling_conv)
  101. else:
  102. assert macro is None, "'macro' is useless if you specify '_callable'"
  103. if elidable_function:
  104. _callable._elidable_function_ = True
  105. kwds = {}
  106. has_callback = False
  107. for ARG in args:
  108. if _isfunctype(ARG):
  109. has_callback = True
  110. if has_callback:
  111. kwds['_callbacks'] = callbackholder = CallbackHolder()
  112. else:
  113. callbackholder = None
  114. if releasegil in (False, True):
  115. # invoke the around-handlers, which release the GIL, if and only if
  116. # the C function is thread-safe.
  117. invoke_around_handlers = releasegil
  118. else:
  119. # default case:
  120. # invoke the around-handlers only for "not too small" external calls;
  121. # sandboxsafe is a hint for "too-small-ness" (e.g. math functions).
  122. # Also, _nowrapper functions cannot release the GIL, by default.
  123. invoke_around_handlers = not sandboxsafe and not _nowrapper
  124. if random_effects_on_gcobjs not in (False, True):
  125. random_effects_on_gcobjs = (
  126. invoke_around_handlers or # because it can release the GIL
  127. has_callback) # because the callback can do it
  128. assert not (elidable_function and random_effects_on_gcobjs)
  129. funcptr = lltype.functionptr(ext_type, name, external='C',
  130. compilation_info=compilation_info,
  131. _callable=_callable,
  132. _safe_not_sandboxed=sandboxsafe,
  133. _debugexc=True, # on top of llinterp
  134. canraise=False,
  135. random_effects_on_gcobjs=
  136. random_effects_on_gcobjs,
  137. calling_conv=calling_conv,
  138. **kwds)
  139. if isinstance(_callable, ll2ctypes.LL2CtypesCallable):
  140. _callable.funcptr = funcptr
  141. if _nowrapper:
  142. assert save_err == RFFI_ERR_NONE
  143. return funcptr
  144. if invoke_around_handlers:
  145. # The around-handlers are releasing the GIL in a threaded pypy.
  146. # We need tons of care to ensure that no GC operation and no
  147. # exception checking occurs while the GIL is released.
  148. # The actual call is done by this small piece of non-inlinable
  149. # generated code in order to avoid seeing any GC pointer:
  150. # neither '*args' nor the GC objects originally passed in as
  151. # argument to wrapper(), if any (e.g. RPython strings).
  152. argnames = ', '.join(['a%d' % i for i in range(len(args))])
  153. source = py.code.Source("""
  154. from rpython.rlib import rgil
  155. def call_external_function(%(argnames)s):
  156. rgil.release()
  157. # NB. it is essential that no exception checking occurs here!
  158. if %(save_err)d:
  159. from rpython.rlib import rposix
  160. rposix._errno_before(%(save_err)d)
  161. res = funcptr(%(argnames)s)
  162. if %(save_err)d:
  163. from rpython.rlib import rposix
  164. rposix._errno_after(%(save_err)d)
  165. rgil.acquire()
  166. return res
  167. """ % locals())
  168. miniglobals = {'funcptr': funcptr,
  169. '__name__': __name__, # for module name propagation
  170. }
  171. exec source.compile() in miniglobals
  172. call_external_function = miniglobals['call_external_function']
  173. call_external_function._dont_inline_ = True
  174. call_external_function._annspecialcase_ = 'specialize:ll'
  175. call_external_function._gctransformer_hint_close_stack_ = True
  176. #
  177. # '_call_aroundstate_target_' is used by the JIT to generate a
  178. # CALL_RELEASE_GIL directly to 'funcptr'. This doesn't work if
  179. # 'funcptr' might be a C macro, though.
  180. if macro is None:
  181. call_external_function._call_aroundstate_target_ = funcptr, save_err
  182. #
  183. call_external_function = func_with_new_name(call_external_function,
  184. 'ccall_' + name)
  185. # don't inline, as a hack to guarantee that no GC pointer is alive
  186. # anywhere in call_external_function
  187. else:
  188. # if we don't have to invoke the GIL handling, we can just call
  189. # the low-level function pointer carelessly
  190. if macro is None and save_err == RFFI_ERR_NONE:
  191. call_external_function = funcptr
  192. else:
  193. # ...well, unless it's a macro, in which case we still have
  194. # to hide it from the JIT...
  195. argnames = ', '.join(['a%d' % i for i in range(len(args))])
  196. source = py.code.Source("""
  197. def call_external_function(%(argnames)s):
  198. if %(save_err)d:
  199. from rpython.rlib import rposix
  200. rposix._errno_before(%(save_err)d)
  201. res = funcptr(%(argnames)s)
  202. if %(save_err)d:
  203. from rpython.rlib import rposix
  204. rposix._errno_after(%(save_err)d)
  205. return res
  206. """ % locals())
  207. miniglobals = {'funcptr': funcptr,
  208. '__name__': __name__,
  209. }
  210. exec source.compile() in miniglobals
  211. call_external_function = miniglobals['call_external_function']
  212. call_external_function = func_with_new_name(call_external_function,
  213. 'ccall_' + name)
  214. call_external_function = jit.dont_look_inside(
  215. call_external_function)
  216. def _oops():
  217. raise AssertionError("can't pass (any more) a unicode string"
  218. " directly to a VOIDP argument")
  219. _oops._annspecialcase_ = 'specialize:memo'
  220. nb_args = len(args)
  221. unrolling_arg_tps = unrolling_iterable(enumerate(args))
  222. def wrapper(*args):
  223. assert len(args) == nb_args
  224. real_args = ()
  225. # XXX 'to_free' leaks if an allocation fails with MemoryError
  226. # and was not the first in this function
  227. to_free = ()
  228. for i, TARGET in unrolling_arg_tps:
  229. arg = args[i]
  230. if TARGET == CCHARP or TARGET is VOIDP:
  231. if arg is None:
  232. arg = lltype.nullptr(CCHARP.TO) # None => (char*)NULL
  233. to_free = to_free + (arg, '\x04')
  234. elif isinstance(arg, str):
  235. tup = get_nonmovingbuffer_final_null(arg)
  236. to_free = to_free + tup
  237. arg = tup[0]
  238. elif isinstance(arg, unicode):
  239. _oops()
  240. elif TARGET == CWCHARP:
  241. if arg is None:
  242. arg = lltype.nullptr(CWCHARP.TO) # None => (wchar_t*)NULL
  243. to_free = to_free + (arg,)
  244. elif isinstance(arg, unicode):
  245. arg = unicode2wcharp(arg)
  246. to_free = to_free + (arg,)
  247. elif _isfunctype(TARGET) and not _isllptr(arg):
  248. # XXX pass additional arguments
  249. use_gil = invoke_around_handlers
  250. arg = llhelper(TARGET, _make_wrapper_for(TARGET, arg,
  251. callbackholder,
  252. use_gil))
  253. else:
  254. SOURCE = lltype.typeOf(arg)
  255. if SOURCE != TARGET:
  256. if TARGET is lltype.Float:
  257. arg = float(arg)
  258. elif ((isinstance(SOURCE, lltype.Number)
  259. or SOURCE is lltype.Bool)
  260. and (isinstance(TARGET, lltype.Number)
  261. or TARGET is lltype.Bool)):
  262. arg = cast(TARGET, arg)
  263. real_args = real_args + (arg,)
  264. res = call_external_function(*real_args)
  265. for i, TARGET in unrolling_arg_tps:
  266. arg = args[i]
  267. if TARGET == CCHARP or TARGET is VOIDP:
  268. if arg is None:
  269. to_free = to_free[2:]
  270. elif isinstance(arg, str):
  271. free_nonmovingbuffer(arg, to_free[0], to_free[1])
  272. to_free = to_free[2:]
  273. elif TARGET == CWCHARP:
  274. if arg is None:
  275. to_free = to_free[1:]
  276. elif isinstance(arg, unicode):
  277. free_wcharp(to_free[0])
  278. to_free = to_free[1:]
  279. assert len(to_free) == 0
  280. if rarithmetic.r_int is not r_int:
  281. if result is INT:
  282. return cast(lltype.Signed, res)
  283. elif result is UINT:
  284. return cast(lltype.Unsigned, res)
  285. return res
  286. wrapper._annspecialcase_ = 'specialize:ll'
  287. wrapper._always_inline_ = 'try'
  288. # for debugging, stick ll func ptr to that
  289. wrapper._ptr = funcptr
  290. wrapper = func_with_new_name(wrapper, name)
  291. if calling_conv != "c":
  292. wrapper = jit.dont_look_inside(wrapper)
  293. return wrapper
  294. class CallbackHolder:
  295. def __init__(self):
  296. self.callbacks = {}
  297. def _make_wrapper_for(TP, callable, callbackholder, use_gil):
  298. """ Function creating wrappers for callbacks. Note that this is
  299. cheating as we assume constant callbacks and we just memoize wrappers
  300. """
  301. from rpython.rtyper.lltypesystem import lltype
  302. from rpython.rtyper.lltypesystem.lloperation import llop
  303. if hasattr(callable, '_errorcode_'):
  304. errorcode = callable._errorcode_
  305. else:
  306. errorcode = TP.TO.RESULT._defl()
  307. callable_name = getattr(callable, '__name__', '?')
  308. if callbackholder is not None:
  309. callbackholder.callbacks[callable] = True
  310. args = ', '.join(['a%d' % i for i in range(len(TP.TO.ARGS))])
  311. source = py.code.Source(r"""
  312. rgil = None
  313. if use_gil:
  314. from rpython.rlib import rgil
  315. def wrapper(%(args)s): # no *args - no GIL for mallocing the tuple
  316. if rgil is not None:
  317. rgil.acquire()
  318. # from now on we hold the GIL
  319. stackcounter.stacks_counter += 1
  320. llop.gc_stack_bottom(lltype.Void) # marker for trackgcroot.py
  321. try:
  322. result = callable(%(args)s)
  323. except Exception, e:
  324. os.write(2,
  325. "Warning: uncaught exception in callback: %%s %%s\n" %%
  326. (callable_name, str(e)))
  327. if not we_are_translated():
  328. import traceback
  329. traceback.print_exc()
  330. result = errorcode
  331. stackcounter.stacks_counter -= 1
  332. if rgil is not None:
  333. rgil.release()
  334. # here we don't hold the GIL any more. As in the wrapper() produced
  335. # by llexternal, it is essential that no exception checking occurs
  336. # after the call to rgil.release().
  337. return result
  338. """ % locals())
  339. miniglobals = locals().copy()
  340. miniglobals['Exception'] = Exception
  341. miniglobals['os'] = os
  342. miniglobals['we_are_translated'] = we_are_translated
  343. miniglobals['stackcounter'] = stackcounter
  344. exec source.compile() in miniglobals
  345. return miniglobals['wrapper']
  346. _make_wrapper_for._annspecialcase_ = 'specialize:memo'
  347. AroundFnPtr = lltype.Ptr(lltype.FuncType([], lltype.Void))
  348. class StackCounter:
  349. def _cleanup_(self):
  350. self.stacks_counter = 0 # number of "stack pieces": callbacks
  351. # and threads increase it by one
  352. stackcounter = StackCounter()
  353. stackcounter._cleanup_()
  354. def llexternal_use_eci(compilation_info):
  355. """Return a dummy function that, if called in a RPython program,
  356. adds the given ExternalCompilationInfo to it."""
  357. eci = ExternalCompilationInfo(post_include_bits=['#define PYPY_NO_OP()'])
  358. eci = eci.merge(compilation_info)
  359. return llexternal('PYPY_NO_OP', [], lltype.Void,
  360. compilation_info=eci, sandboxsafe=True, _nowrapper=True,
  361. _callable=lambda: None)
  362. def generate_macro_wrapper(name, macro, functype, eci):
  363. """Wraps a function-like macro inside a real function, and expose
  364. it with llexternal."""
  365. # Generate the function call
  366. from rpython.translator.c.database import LowLevelDatabase
  367. from rpython.translator.c.support import cdecl
  368. wrapper_name = 'pypy_macro_wrapper_%s' % (name,)
  369. argnames = ['arg%d' % (i,) for i in range(len(functype.ARGS))]
  370. db = LowLevelDatabase()
  371. implementationtypename = db.gettype(functype, argnames=argnames)
  372. if functype.RESULT is lltype.Void:
  373. pattern = '%s%s { %s(%s); }'
  374. else:
  375. pattern = '%s%s { return %s(%s); }'
  376. source = pattern % (
  377. 'RPY_EXTERN ',
  378. cdecl(implementationtypename, wrapper_name),
  379. macro, ', '.join(argnames))
  380. # Now stuff this source into a "companion" eci that will be used
  381. # by ll2ctypes. We replace eci._with_ctypes, so that only one
  382. # shared library is actually compiled (when ll2ctypes calls the
  383. # first function)
  384. ctypes_eci = eci.merge(ExternalCompilationInfo(
  385. separate_module_sources=[source],
  386. ))
  387. if hasattr(eci, '_with_ctypes'):
  388. ctypes_eci = eci._with_ctypes.merge(ctypes_eci)
  389. eci._with_ctypes = ctypes_eci
  390. func = llexternal(wrapper_name, functype.ARGS, functype.RESULT,
  391. compilation_info=eci, _nowrapper=True)
  392. # _nowrapper=True returns a pointer which is not hashable
  393. return lambda *args: func(*args)
  394. # ____________________________________________________________
  395. # Few helpers for keeping callback arguments alive
  396. # this makes passing opaque objects possible (they don't even pass
  397. # through C, only integer specifying number passes)
  398. _KEEPER_CACHE = {}
  399. def _keeper_for_type(TP):
  400. try:
  401. return _KEEPER_CACHE[TP]
  402. except KeyError:
  403. tp_str = str(TP) # make annotator happy
  404. class KeepaliveKeeper(object):
  405. def __init__(self):
  406. self.stuff_to_keepalive = []
  407. self.free_positions = []
  408. keeper = KeepaliveKeeper()
  409. _KEEPER_CACHE[TP] = keeper
  410. return keeper
  411. _keeper_for_type._annspecialcase_ = 'specialize:memo'
  412. def register_keepalive(obj):
  413. """ Register object obj to be kept alive,
  414. returns a position for that object
  415. """
  416. keeper = _keeper_for_type(lltype.typeOf(obj))
  417. if len(keeper.free_positions):
  418. pos = keeper.free_positions.pop()
  419. keeper.stuff_to_keepalive[pos] = obj
  420. return pos
  421. # we don't have any free positions
  422. pos = len(keeper.stuff_to_keepalive)
  423. keeper.stuff_to_keepalive.append(obj)
  424. return pos
  425. register_keepalive._annspecialcase_ = 'specialize:argtype(0)'
  426. def get_keepalive_object(pos, TP):
  427. keeper = _keeper_for_type(TP)
  428. return keeper.stuff_to_keepalive[pos]
  429. get_keepalive_object._annspecialcase_ = 'specialize:arg(1)'
  430. def unregister_keepalive(pos, TP):
  431. """ Unregister an object of type TP, stored at position
  432. pos (position previously returned by register_keepalive)
  433. """
  434. keeper = _keeper_for_type(TP)
  435. keeper.stuff_to_keepalive[pos] = None
  436. keeper.free_positions.append(pos)
  437. unregister_keepalive._annspecialcase_ = 'specialize:arg(1)'
  438. # ____________________________________________________________
  439. TYPES = []
  440. for _name in 'short int long'.split():
  441. for name in (_name, 'unsigned ' + _name):
  442. TYPES.append(name)
  443. TYPES += ['signed char', 'unsigned char',
  444. 'long long', 'unsigned long long',
  445. 'size_t', 'time_t', 'wchar_t',
  446. 'uintptr_t', 'intptr_t', # C note: these two are _integer_ types
  447. 'void*'] # generic pointer type
  448. # This is a bit of a hack since we can't use rffi_platform here.
  449. try:
  450. sizeof_c_type('__int128_t', ignore_errors=True)
  451. TYPES += ['__int128_t']
  452. except CompilationError:
  453. pass
  454. if os.name != 'nt':
  455. TYPES.append('mode_t')
  456. TYPES.append('pid_t')
  457. TYPES.append('ssize_t')
  458. # the types below are rare enough and not available on Windows
  459. TYPES.extend(['ptrdiff_t',
  460. 'int_least8_t', 'uint_least8_t',
  461. 'int_least16_t', 'uint_least16_t',
  462. 'int_least32_t', 'uint_least32_t',
  463. 'int_least64_t', 'uint_least64_t',
  464. 'int_fast8_t', 'uint_fast8_t',
  465. 'int_fast16_t', 'uint_fast16_t',
  466. 'int_fast32_t', 'uint_fast32_t',
  467. 'int_fast64_t', 'uint_fast64_t',
  468. 'intmax_t', 'uintmax_t'])
  469. else:
  470. MODE_T = lltype.Signed
  471. PID_T = lltype.Signed
  472. SSIZE_T = lltype.Signed
  473. def populate_inttypes():
  474. names = []
  475. populatelist = []
  476. for name in TYPES:
  477. c_name = name
  478. if name.startswith('unsigned'):
  479. name = 'u' + name[9:]
  480. signed = False
  481. elif name == 'size_t' or name.startswith('uint'):
  482. signed = False
  483. else:
  484. signed = True
  485. name = name.replace(' ', '')
  486. names.append(name)
  487. populatelist.append((name.upper(), c_name, signed))
  488. platform.populate_inttypes(populatelist)
  489. return names
  490. def setup():
  491. """ creates necessary c-level types
  492. """
  493. names = populate_inttypes()
  494. result = []
  495. for name in names:
  496. tp = platform.types[name.upper()]
  497. globals()['r_' + name] = platform.numbertype_to_rclass[tp]
  498. globals()[name.upper()] = tp
  499. tpp = lltype.Ptr(lltype.Array(tp, hints={'nolength': True}))
  500. globals()[name.upper()+'P'] = tpp
  501. result.append(tp)
  502. return result
  503. NUMBER_TYPES = setup()
  504. platform.numbertype_to_rclass[lltype.Signed] = int # avoid "r_long" for common cases
  505. r_int_real = rarithmetic.build_int("r_int_real", r_int.SIGN, r_int.BITS, True)
  506. INT_real = lltype.build_number("INT", r_int_real)
  507. platform.numbertype_to_rclass[INT_real] = r_int_real
  508. NUMBER_TYPES.append(INT_real)
  509. # ^^^ this creates at least the following names:
  510. # --------------------------------------------------------------------
  511. # Type RPython integer class doing wrap-around
  512. # --------------------------------------------------------------------
  513. # SIGNEDCHAR r_signedchar
  514. # UCHAR r_uchar
  515. # SHORT r_short
  516. # USHORT r_ushort
  517. # INT r_int
  518. # UINT r_uint
  519. # LONG r_long
  520. # ULONG r_ulong
  521. # LONGLONG r_longlong
  522. # ULONGLONG r_ulonglong
  523. # WCHAR_T r_wchar_t
  524. # SIZE_T r_size_t
  525. # SSIZE_T r_ssize_t
  526. # TIME_T r_time_t
  527. # --------------------------------------------------------------------
  528. # Note that rffi.r_int is not necessarily the same as
  529. # rarithmetic.r_int, etc! rffi.INT/r_int correspond to the C-level
  530. # 'int' type, whereas rarithmetic.r_int corresponds to the
  531. # Python-level int type (which is a C long). Fun.
  532. def CStruct(name, *fields, **kwds):
  533. """ A small helper to create external C structure, not the
  534. pypy one
  535. """
  536. hints = kwds.get('hints', {})
  537. hints = hints.copy()
  538. kwds['hints'] = hints
  539. hints['external'] = 'C'
  540. hints['c_name'] = name
  541. # Hack: prefix all attribute names with 'c_' to cope with names starting
  542. # with '_'. The genc backend removes the 'c_' prefixes...
  543. c_fields = [('c_' + key, value) for key, value in fields]
  544. return lltype.Struct(name, *c_fields, **kwds)
  545. def CStructPtr(*args, **kwds):
  546. return lltype.Ptr(CStruct(*args, **kwds))
  547. def CFixedArray(tp, size):
  548. return lltype.FixedSizeArray(tp, size)
  549. CFixedArray._annspecialcase_ = 'specialize:memo'
  550. def CArray(tp):
  551. return lltype.Array(tp, hints={'nolength': True})
  552. CArray._annspecialcase_ = 'specialize:memo'
  553. def CArrayPtr(tp):
  554. return lltype.Ptr(CArray(tp))
  555. CArrayPtr._annspecialcase_ = 'specialize:memo'
  556. def CCallback(args, res):
  557. return lltype.Ptr(lltype.FuncType(args, res))
  558. CCallback._annspecialcase_ = 'specialize:memo'
  559. def COpaque(name=None, ptr_typedef=None, hints=None, compilation_info=None):
  560. if compilation_info is None:
  561. compilation_info = ExternalCompilationInfo()
  562. if hints is None:
  563. hints = {}
  564. else:
  565. hints = hints.copy()
  566. hints['external'] = 'C'
  567. if name is not None:
  568. hints['c_name'] = name
  569. if ptr_typedef is not None:
  570. hints['c_pointer_typedef'] = ptr_typedef
  571. def lazy_getsize(cache={}):
  572. from rpython.rtyper.tool import rffi_platform
  573. try:
  574. return cache[name]
  575. except KeyError:
  576. val = rffi_platform.sizeof(name, compilation_info)
  577. cache[name] = val
  578. return val
  579. hints['getsize'] = lazy_getsize
  580. return lltype.OpaqueType(name, hints)
  581. def COpaquePtr(*args, **kwds):
  582. typedef = kwds.pop('typedef', None)
  583. return lltype.Ptr(COpaque(ptr_typedef=typedef, *args, **kwds))
  584. def CExternVariable(TYPE, name, eci, _CConstantClass=CConstant,
  585. sandboxsafe=False, _nowrapper=False,
  586. c_type=None, getter_only=False,
  587. declare_as_extern=(sys.platform != 'win32')):
  588. """Return a pair of functions - a getter and a setter - to access
  589. the given global C variable.
  590. """
  591. from rpython.translator.c.primitive import PrimitiveType
  592. from rpython.translator.tool.cbuild import ExternalCompilationInfo
  593. # XXX we cannot really enumerate all C types here, do it on a case-by-case
  594. # basis
  595. if c_type is None:
  596. if TYPE == CCHARPP:
  597. c_type = 'char **'
  598. elif TYPE == CCHARP:
  599. c_type = 'char *'
  600. elif TYPE == INT or TYPE == LONG:
  601. assert False, "ambiguous type on 32-bit machines: give a c_type"
  602. else:
  603. c_type = PrimitiveType[TYPE]
  604. assert c_type.endswith(' @')
  605. c_type = c_type[:-2] # cut the trailing ' @'
  606. getter_name = 'get_' + name
  607. setter_name = 'set_' + name
  608. getter_prototype = (
  609. "RPY_EXTERN %(c_type)s %(getter_name)s ();" % locals())
  610. setter_prototype = (
  611. "RPY_EXTERN void %(setter_name)s (%(c_type)s v);" % locals())
  612. c_getter = "%(c_type)s %(getter_name)s () { return %(name)s; }" % locals()
  613. c_setter = "void %(setter_name)s (%(c_type)s v) { %(name)s = v; }" % locals()
  614. lines = ["#include <%s>" % i for i in eci.includes]
  615. if declare_as_extern:
  616. lines.append('extern %s %s;' % (c_type, name))
  617. lines.append(c_getter)
  618. if not getter_only:
  619. lines.append(c_setter)
  620. prototypes = [getter_prototype]
  621. if not getter_only:
  622. prototypes.append(setter_prototype)
  623. sources = ('\n'.join(lines),)
  624. new_eci = eci.merge(ExternalCompilationInfo(
  625. separate_module_sources = sources,
  626. post_include_bits = prototypes,
  627. ))
  628. getter = llexternal(getter_name, [], TYPE, compilation_info=new_eci,
  629. sandboxsafe=sandboxsafe, _nowrapper=_nowrapper)
  630. if getter_only:
  631. return getter
  632. else:
  633. setter = llexternal(setter_name, [TYPE], lltype.Void,
  634. compilation_info=new_eci, sandboxsafe=sandboxsafe,
  635. _nowrapper=_nowrapper)
  636. return getter, setter
  637. # char, represented as a Python character
  638. # (use SIGNEDCHAR or UCHAR for the small integer types)
  639. CHAR = lltype.Char
  640. # double
  641. DOUBLE = lltype.Float
  642. LONGDOUBLE = lltype.LongFloat
  643. # float - corresponds to rpython.rlib.rarithmetic.r_float, and supports no
  644. # operation except rffi.cast() between FLOAT and DOUBLE
  645. FLOAT = lltype.SingleFloat
  646. r_singlefloat = rarithmetic.r_singlefloat
  647. # void * - for now, represented as char *
  648. VOIDP = lltype.Ptr(lltype.Array(lltype.Char, hints={'nolength': True, 'render_as_void': True}))
  649. NULL = None
  650. # void **
  651. VOIDPP = CArrayPtr(VOIDP)
  652. # char *
  653. CCHARP = lltype.Ptr(lltype.Array(lltype.Char, hints={'nolength': True}))
  654. # const char *
  655. CONST_CCHARP = lltype.Ptr(lltype.Array(lltype.Char, hints={'nolength': True,
  656. 'render_as_const': True}))
  657. # wchar_t *
  658. CWCHARP = lltype.Ptr(lltype.Array(lltype.UniChar, hints={'nolength': True}))
  659. # int *, unsigned int *, etc.
  660. #INTP = ... see setup() above
  661. # double *
  662. DOUBLEP = lltype.Ptr(lltype.Array(DOUBLE, hints={'nolength': True}))
  663. # float *
  664. FLOATP = lltype.Ptr(lltype.Array(FLOAT, hints={'nolength': True}))
  665. # long double *
  666. LONGDOUBLEP = lltype.Ptr(lltype.Array(LONGDOUBLE, hints={'nolength': True}))
  667. # Signed, Signed *
  668. SIGNED = lltype.Signed
  669. SIGNEDP = lltype.Ptr(lltype.Array(SIGNED, hints={'nolength': True}))
  670. # various type mapping
  671. # conversions between str and char*
  672. # conversions between unicode and wchar_t*
  673. def make_string_mappings(strtype):
  674. if strtype is str:
  675. from rpython.rtyper.lltypesystem.rstr import (STR as STRTYPE,
  676. copy_string_to_raw,
  677. copy_raw_to_string,
  678. copy_string_contents,
  679. mallocstr as mallocfn)
  680. from rpython.rtyper.annlowlevel import llstr as llstrtype
  681. from rpython.rtyper.annlowlevel import hlstr as hlstrtype
  682. TYPEP = CCHARP
  683. ll_char_type = lltype.Char
  684. lastchar = '\x00'
  685. else:
  686. from rpython.rtyper.lltypesystem.rstr import (
  687. UNICODE as STRTYPE,
  688. copy_unicode_to_raw as copy_string_to_raw,
  689. copy_raw_to_unicode as copy_raw_to_string,
  690. copy_unicode_contents as copy_string_contents,
  691. mallocunicode as mallocfn)
  692. from rpython.rtyper.annlowlevel import llunicode as llstrtype
  693. from rpython.rtyper.annlowlevel import hlunicode as hlstrtype
  694. TYPEP = CWCHARP
  695. ll_char_type = lltype.UniChar
  696. lastchar = u'\x00'
  697. # str -> char*
  698. def str2charp(s, track_allocation=True):
  699. """ str -> char*
  700. """
  701. if track_allocation:
  702. array = lltype.malloc(TYPEP.TO, len(s) + 1, flavor='raw', track_allocation=True)
  703. else:
  704. array = lltype.malloc(TYPEP.TO, len(s) + 1, flavor='raw', track_allocation=False)
  705. i = len(s)
  706. ll_s = llstrtype(s)
  707. copy_string_to_raw(ll_s, array, 0, i)
  708. array[i] = lastchar
  709. return array
  710. str2charp._annenforceargs_ = [strtype, bool]
  711. def free_charp(cp, track_allocation=True):
  712. if track_allocation:
  713. lltype.free(cp, flavor='raw', track_allocation=True)
  714. else:
  715. lltype.free(cp, flavor='raw', track_allocation=False)
  716. # str -> already-existing char[maxsize]
  717. def str2chararray(s, array, maxsize):
  718. length = min(len(s), maxsize)
  719. ll_s = llstrtype(s)
  720. copy_string_to_raw(ll_s, array, 0, length)
  721. return length
  722. str2chararray._annenforceargs_ = [strtype, None, int]
  723. # s[start:start+length] -> already-existing char[],
  724. # all characters including zeros
  725. def str2rawmem(s, array, start, length):
  726. ll_s = llstrtype(s)
  727. copy_string_to_raw(ll_s, array, start, length)
  728. # char* -> str
  729. # doesn't free char*
  730. def charp2str(cp):
  731. size = 0
  732. while cp[size] != lastchar:
  733. size += 1
  734. return assert_str0(charpsize2str(cp, size))
  735. charp2str._annenforceargs_ = [lltype.SomePtr(TYPEP)]
  736. # str -> char*, bool, bool
  737. # Can't inline this because of the raw address manipulation.
  738. @jit.dont_look_inside
  739. def get_nonmovingbuffer(data):
  740. """
  741. Either returns a non-moving copy or performs neccessary pointer
  742. arithmetic to return a pointer to the characters of a string if the
  743. string is already nonmovable or could be pinned. Must be followed by a
  744. free_nonmovingbuffer call.
  745. Also returns a char:
  746. * \4: no pinning, returned pointer is inside 'data' which is nonmovable
  747. * \5: 'data' was pinned, returned pointer is inside
  748. * \6: pinning failed, returned pointer is raw malloced
  749. For strings (not unicodes), the len()th character of the resulting
  750. raw buffer is available, but not initialized. Use
  751. get_nonmovingbuffer_final_null() instead of get_nonmovingbuffer()
  752. to get a regular null-terminated "char *".
  753. """
  754. lldata = llstrtype(data)
  755. count = len(data)
  756. if we_are_translated_to_c() and not rgc.can_move(data):
  757. flag = '\x04'
  758. else:
  759. if we_are_translated_to_c() and rgc.pin(data):
  760. flag = '\x05'
  761. else:
  762. buf = lltype.malloc(TYPEP.TO, count + (TYPEP is CCHARP),
  763. flavor='raw')
  764. copy_string_to_raw(lldata, buf, 0, count)
  765. return buf, '\x06'
  766. # ^^^ raw malloc used to get a nonmovable copy
  767. #
  768. # following code is executed after we're translated to C, if:
  769. # - rgc.can_move(data) and rgc.pin(data) both returned true
  770. # - rgc.can_move(data) returned false
  771. data_start = cast_ptr_to_adr(lldata) + \
  772. offsetof(STRTYPE, 'chars') + itemoffsetof(STRTYPE.chars, 0)
  773. return cast(TYPEP, data_start), flag
  774. # ^^^ already nonmovable. Therefore it's not raw allocated nor
  775. # pinned.
  776. get_nonmovingbuffer._always_inline_ = 'try' # get rid of the returned tuple
  777. get_nonmovingbuffer._annenforceargs_ = [strtype]
  778. @jit.dont_look_inside
  779. def get_nonmovingbuffer_final_null(data):
  780. tup = get_nonmovingbuffer(data)
  781. buf, flag = tup
  782. buf[len(data)] = lastchar
  783. return tup
  784. get_nonmovingbuffer_final_null._always_inline_ = 'try'
  785. get_nonmovingbuffer_final_null._annenforceargs_ = [strtype]
  786. # (str, char*, char) -> None
  787. # Can't inline this because of the raw address manipulation.
  788. @jit.dont_look_inside
  789. def free_nonmovingbuffer(data, buf, flag):
  790. """
  791. Keep 'data' alive and unpin it if it was pinned (flag==\5).
  792. Otherwise free the non-moving copy (flag==\6).
  793. """
  794. if flag == '\x05':
  795. rgc.unpin(data)
  796. if flag == '\x06':
  797. lltype.free(buf, flavor='raw')
  798. # if flag == '\x04': data was already nonmovable,
  799. # we have nothing to clean up
  800. keepalive_until_here(data)
  801. free_nonmovingbuffer._annenforceargs_ = [strtype, None, None]
  802. # int -> (char*, str, int)
  803. # Can't inline this because of the raw address manipulation.
  804. @jit.dont_look_inside
  805. def alloc_buffer(count):
  806. """
  807. Returns a (raw_buffer, gc_buffer, case_num) triple,
  808. allocated with count bytes.
  809. The raw_buffer can be safely passed to a native function which expects
  810. it to not move. Call str_from_buffer with the returned values to get a
  811. safe high-level string. When the garbage collector cooperates, this
  812. allows for the process to be performed without an extra copy.
  813. Make sure to call keep_buffer_alive_until_here on the returned values.
  814. """
  815. new_buf = mallocfn(count)
  816. pinned = 0
  817. if rgc.can_move(new_buf):
  818. if rgc.pin(new_buf):
  819. pinned = 1
  820. else:
  821. raw_buf = lltype.malloc(TYPEP.TO, count, flavor='raw')
  822. return raw_buf, new_buf, 2
  823. #
  824. # following code is executed if:
  825. # - rgc.can_move(data) and rgc.pin(data) both returned true
  826. # - rgc.can_move(data) returned false
  827. data_start = cast_ptr_to_adr(new_buf) + \
  828. offsetof(STRTYPE, 'chars') + itemoffsetof(STRTYPE.chars, 0)
  829. return cast(TYPEP, data_start), new_buf, pinned
  830. alloc_buffer._always_inline_ = 'try' # to get rid of the returned tuple
  831. alloc_buffer._annenforceargs_ = [int]
  832. # (char*, str, int, int) -> None
  833. @jit.dont_look_inside
  834. @enforceargs(None, None, int, int, int)
  835. def str_from_buffer(raw_buf, gc_buf, case_num, allocated_size, needed_size):
  836. """
  837. Converts from a pair returned by alloc_buffer to a high-level string.
  838. The returned string will be truncated to needed_size.
  839. """
  840. assert allocated_size >= needed_size
  841. if allocated_size != needed_size:
  842. from rpython.rtyper.lltypesystem.lloperation import llop
  843. if llop.shrink_array(lltype.Bool, gc_buf, needed_size):
  844. pass # now 'gc_buf' is smaller
  845. else:
  846. gc_buf = mallocfn(needed_size)
  847. case_num = 2
  848. if case_num == 2:
  849. copy_raw_to_string(raw_buf, gc_buf, 0, needed_size)
  850. return hlstrtype(gc_buf)
  851. # (char*, str, int) -> None
  852. @jit.dont_look_inside
  853. def keep_buffer_alive_until_here(raw_buf, gc_buf, case_num):
  854. """
  855. Keeps buffers alive or frees temporary buffers created by alloc_buffer.
  856. This must be called after a call to alloc_buffer, usually in a
  857. try/finally block.
  858. """
  859. keepalive_until_here(gc_buf)
  860. if case_num == 1:
  861. rgc.unpin(gc_buf)
  862. if case_num == 2:
  863. lltype.free(raw_buf, flavor='raw')
  864. # char* -> str, with an upper bound on the length in case there is no \x00
  865. @enforceargs(None, int)
  866. def charp2strn(cp, maxlen):
  867. size = 0
  868. while size < maxlen and cp[size] != lastchar:
  869. size += 1
  870. return assert_str0(charpsize2str(cp, size))
  871. # char* and size -> str (which can contain null bytes)
  872. def charpsize2str(cp, size):
  873. ll_str = mallocfn(size)
  874. copy_raw_to_string(cp, ll_str, 0, size)
  875. result = hlstrtype(ll_str)
  876. assert result is not None
  877. return result
  878. charpsize2str._annenforceargs_ = [None, int]
  879. return (str2charp, free_charp, charp2str,
  880. get_nonmovingbuffer, free_nonmovingbuffer,
  881. get_nonmovingbuffer_final_null,
  882. alloc_buffer, str_from_buffer, keep_buffer_alive_until_here,
  883. charp2strn, charpsize2str, str2chararray, str2rawmem,
  884. )
  885. (str2charp, free_charp, charp2str,
  886. get_nonmovingbuffer, free_nonmovingbuffer, get_nonmovingbuffer_final_null,
  887. alloc_buffer, str_from_buffer, keep_buffer_alive_until_here,
  888. charp2strn, charpsize2str, str2chararray, str2rawmem,
  889. ) = make_string_mappings(str)
  890. (unicode2wcharp, free_wcharp, wcharp2unicode,
  891. get_nonmoving_unicodebuffer, free_nonmoving_unicodebuffer, __not_usable,
  892. alloc_unicodebuffer, unicode_from_buffer, keep_unicodebuffer_alive_until_here,
  893. wcharp2unicoden, wcharpsize2unicode, unicode2wchararray, unicode2rawmem,
  894. ) = make_string_mappings(unicode)
  895. # char**
  896. CCHARPP = lltype.Ptr(lltype.Array(CCHARP, hints={'nolength': True}))
  897. def liststr2charpp(l):
  898. """ list[str] -> char**, NULL terminated
  899. """
  900. array = lltype.malloc(CCHARPP.TO, len(l) + 1, flavor='raw')
  901. for i in range(len(l)):
  902. array[i] = str2charp(l[i])
  903. array[len(l)] = lltype.nullptr(CCHARP.TO)
  904. return array
  905. liststr2charpp._annenforceargs_ = [[annmodel.s_Str0]] # List of strings
  906. # Make a copy for rposix.py
  907. ll_liststr2charpp = func_with_new_name(liststr2charpp, 'll_liststr2charpp')
  908. def free_charpp(ref):
  909. """ frees list of char**, NULL terminated
  910. """
  911. i = 0
  912. while ref[i]:
  913. free_charp(ref[i])
  914. i += 1
  915. lltype.free(ref, flavor='raw')
  916. def charpp2liststr(p):
  917. """ char** NULL terminated -> list[str]. No freeing is done.
  918. """
  919. result = []
  920. i = 0
  921. while p[i]:
  922. result.append(charp2str(p[i]))
  923. i += 1
  924. return result
  925. cast = ll2ctypes.force_cast # a forced, no-checking cast
  926. ptradd = ll2ctypes.force_ptradd # equivalent of "ptr + n" in C.
  927. # the ptr must point to an array.
  928. def size_and_sign(tp):
  929. size = sizeof(tp)
  930. try:
  931. unsigned = not tp._type.SIGNED
  932. except AttributeError:
  933. if not isinstance(tp, lltype.Primitive):
  934. unsigned = False
  935. elif tp in (lltype.Signed, FLOAT, DOUBLE, llmemory.Address):
  936. unsigned = False
  937. elif tp in (lltype.Char, lltype.UniChar, lltype.Bool):
  938. unsigned = True
  939. else:
  940. raise AssertionError("size_and_sign(%r)" % (tp,))
  941. return size, unsigned
  942. def sizeof(tp):
  943. """Similar to llmemory.sizeof() but tries hard to return a integer
  944. instead of a symbolic value.
  945. """
  946. if isinstance(tp, lltype.Typedef):
  947. tp = tp.OF
  948. if isinstance(tp, lltype.FixedSizeArray):
  949. return sizeof(tp.OF) * tp.length
  950. if isinstance(tp, lltype.Struct):
  951. # the hint is present in structures probed by rffi_platform.
  952. size = tp._hints.get('size')
  953. if size is None:
  954. size = llmemory.sizeof(tp) # a symbolic result in this case
  955. return size
  956. if isinstance(tp, lltype.Ptr) or tp is llmemory.Address:
  957. return globals()['r_void*'].BITS/8
  958. if tp is lltype.Char or tp is lltype.Bool:
  959. return 1
  960. if tp is lltype.UniChar:
  961. return r_wchar_t.BITS/8
  962. if tp is lltype.Float:
  963. return 8
  964. if tp is lltype.SingleFloat:
  965. return 4
  966. if tp is lltype.LongFloat:
  967. # :-/
  968. return sizeof_c_type("long double")
  969. assert isinstance(tp, lltype.Number)
  970. if tp is lltype.Signed:
  971. return LONG_BIT/8
  972. return tp._type.BITS/8
  973. sizeof._annspecialcase_ = 'specialize:memo'
  974. def offsetof(STRUCT, fieldname):
  975. """Similar to llmemory.offsetof() but tries hard to return a integer
  976. instead of a symbolic value.
  977. """
  978. # the hint is present in structures probed by rffi_platform.
  979. fieldoffsets = STRUCT._hints.get('fieldoffsets')
  980. if fieldoffsets is not None:
  981. # a numeric result when known
  982. for index, name in enumerate(STRUCT._names):
  983. if name == fieldname:
  984. return fieldoffsets[index]
  985. # a symbolic result as a fallback
  986. return llmemory.offsetof(STRUCT, fieldname)
  987. offsetof._annspecialcase_ = 'specialize:memo'
  988. # check that we have a sane configuration
  989. assert maxint == (1 << (8 * sizeof(llmemory.Address) - 1)) - 1, (
  990. "Mixed configuration of the word size of the machine:\n\t"
  991. "the underlying Python was compiled with maxint=%d,\n\t"
  992. "but the C compiler says that 'void *' is %d bytes" % (
  993. maxint, sizeof(llmemory.Address)))
  994. assert sizeof(lltype.Signed) == sizeof(llmemory.Address), (
  995. "Bad configuration: we should manage to get lltype.Signed "
  996. "be an integer type of the same size as llmemory.Address, "
  997. "but we got %s != %s" % (sizeof(lltype.Signed),
  998. sizeof(llmemory.Address)))
  999. # ********************** some helpers *******************
  1000. def make(STRUCT, **fields):
  1001. """ Malloc a structure and populate it's fields
  1002. """
  1003. ptr = lltype.malloc(STRUCT, flavor='raw')
  1004. for name, value in fields.items():
  1005. setattr(ptr, name, value)
  1006. return ptr
  1007. class MakeEntry(ExtRegistryEntry):
  1008. _about_ = make
  1009. def compute_result_annotation(self, s_type, **s_fields):
  1010. TP = s_type.const
  1011. if not isinstance(TP, lltype.Struct):
  1012. raise TypeError("make called with %s instead of Struct as first argument" % TP)
  1013. return SomePtr(lltype.Ptr(TP))
  1014. def specialize_call(self, hop, **fields):
  1015. assert hop.args_s[0].is_constant()
  1016. vlist = [hop.inputarg(lltype.Void, arg=0)]
  1017. flags = {'flavor':'raw'}
  1018. vlist.append(hop.inputconst(lltype.Void, flags))
  1019. hop.has_implicit_exception(MemoryError) # record that we know about it
  1020. hop.exception_is_here()
  1021. v_ptr = hop.genop('malloc', vlist, resulttype=hop.r_result.lowleveltype)
  1022. for name, i in fields.items():
  1023. name = name[2:]
  1024. v_arg = hop.inputarg(hop.args_r[i], arg=i)
  1025. v_name = hop.inputconst(lltype.Void, name)
  1026. hop.genop('setfield', [v_ptr, v_name, v_arg])
  1027. return v_ptr
  1028. def structcopy(pdst, psrc):
  1029. """Copy all the fields of the structure given by 'psrc'
  1030. into the structure given by 'pdst'.
  1031. """
  1032. copy_fn = _get_structcopy_fn(lltype.typeOf(pdst), lltype.typeOf(psrc))
  1033. copy_fn(pdst, psrc)
  1034. structcopy._annspecialcase_ = 'specialize:ll'
  1035. def _get_structcopy_fn(PDST, PSRC):
  1036. assert PDST == PSRC
  1037. if isinstance(PDST.TO, lltype.Struct):
  1038. STRUCT = PDST.TO
  1039. padding = STRUCT._hints.get('padding', ())
  1040. fields = [(name, STRUCT._flds[name]) for name in STRUCT._names
  1041. if name not in padding]
  1042. unrollfields = unrolling_iterable(fields)
  1043. def copyfn(pdst, psrc):
  1044. for name, TYPE in unrollfields:
  1045. if isinstance(TYPE, lltype.ContainerType):
  1046. structcopy(getattr(pdst, name), getattr(psrc, name))
  1047. else:
  1048. setattr(pdst, name, getattr(psrc, name))
  1049. return copyfn
  1050. else:
  1051. raise NotImplementedError('structcopy: type %r' % (PDST.TO,))
  1052. _get_structcopy_fn._annspecialcase_ = 'specialize:memo'
  1053. def setintfield(pdst, fieldname, value):
  1054. """Maybe temporary: a helper to set an integer field into a structure,
  1055. transparently casting between the various integer types.
  1056. """
  1057. STRUCT = lltype.typeOf(pdst).TO
  1058. TSRC = lltype.typeOf(value)
  1059. TDST = getattr(STRUCT, fieldname)
  1060. assert isinstance(TSRC, lltype.Number)
  1061. assert isinstance(TDST, lltype.Number)
  1062. setattr(pdst, fieldname, cast(TDST, value))
  1063. setintfield._annspecialcase_ = 'specialize:ll_and_arg(1)'
  1064. def getintfield(pdst, fieldname):
  1065. """As temporary as previous: get integer from a field in structure,
  1066. casting it to lltype.Signed
  1067. """
  1068. return cast(lltype.Signed, getattr(pdst, fieldname))
  1069. getintfield._annspecialcase_ = 'specialize:ll_and_arg(1)'
  1070. class scoped_str2charp:
  1071. def __init__(self, value):
  1072. if value is not None:
  1073. self.buf = str2charp(value)
  1074. else:
  1075. self.buf = lltype.nullptr(CCHARP.TO)
  1076. __init__._annenforceargs_ = [None, annmodel.SomeString(can_be_None=True)]
  1077. def __enter__(self):
  1078. return self.buf
  1079. def __exit__(self, *args):
  1080. if self.buf:
  1081. free_charp(self.buf)
  1082. class scoped_unicode2wcharp:
  1083. def __init__(self, value):
  1084. if value is not None:
  1085. self.buf = unicode2wcharp(value)
  1086. else:
  1087. self.buf = lltype.nullptr(CWCHARP.TO)
  1088. __init__._annenforceargs_ = [None,
  1089. annmodel.SomeUnicodeString(can_be_None=True)]
  1090. def __enter__(self):
  1091. return self.buf
  1092. def __exit__(self, *args):
  1093. if self.buf:
  1094. free_wcharp(self.buf)
  1095. class scoped_nonmovingbuffer:
  1096. def __init__(self, data):
  1097. self.data = data
  1098. def __enter__(self):
  1099. self.buf, self.flag = get_nonmovingbuffer(self.data)
  1100. return self.buf
  1101. def __exit__(self, *args):
  1102. free_nonmovingbuffer(self.data, self.buf, self.flag)
  1103. __init__._always_inline_ = 'try'
  1104. __enter__._always_inline_ = 'try'
  1105. __exit__._always_inline_ = 'try'
  1106. class scoped_view_charp:
  1107. """Returns a 'char *' that (tries to) point inside the given RPython
  1108. string (which must not be None). You can replace scoped_str2charp()
  1109. with scoped_view_charp() in all places that guarantee that the
  1110. content of the 'char[]' array will not be modified.
  1111. """
  1112. def __init__(self, data):
  1113. self.data = data
  1114. __init__._annenforceargs_ = [None, annmodel.SomeString(can_be_None=False)]
  1115. def __enter__(self):
  1116. self.buf, self.flag = get_nonmovingbuffer_final_null(self.data)
  1117. return self.buf
  1118. def __exit__(self, *args):
  1119. free_nonmovingbuffer(self.data, self.buf, self.flag)
  1120. __init__._always_inline_ = 'try'
  1121. __enter__._always_inline_ = 'try'
  1122. __exit__._always_inline_ = 'try'
  1123. class scoped_nonmoving_unicodebuffer:
  1124. def __init__(self, data):
  1125. self.data = data
  1126. def __enter__(self):
  1127. self.buf, self.flag = get_nonmoving_unicodebuffer(self.data)
  1128. return self.buf
  1129. def __exit__(self, *args):
  1130. free_nonmoving_unicodebuffer(self.data, self.buf, self.flag)
  1131. __init__._always_inline_ = 'try'
  1132. __enter__._always_inline_ = 'try'
  1133. __exit__._always_inline_ = 'try'
  1134. class scoped_alloc_buffer:
  1135. def __init__(self, size):
  1136. self.size = size
  1137. def __enter__(self):
  1138. self.raw, self.gc_buf, self.case_num = alloc_buffer(self.size)
  1139. return self
  1140. def __exit__(self, *args):
  1141. keep_buffer_alive_until_here(self.raw, self.gc_buf, self.case_num)
  1142. def str(self, length):
  1143. return str_from_buffer(self.raw, self.gc_buf, self.case_num,
  1144. self.size, length)
  1145. class scoped_alloc_unicodebuffer:
  1146. def __init__(self, size):
  1147. self.size = size
  1148. def __enter__(self):
  1149. self.raw, self.gc_buf, self.case_num = alloc_unicodebuffer(self.size)
  1150. return self
  1151. def __exit__(self, *args):
  1152. keep_unicodebuffer_alive_until_here(self.raw, self.gc_buf, self.case_num)
  1153. def str(self, length):
  1154. return unicode_from_buffer(

Large files files are truncated, but you can click here to view the full file