PageRenderTime 56ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

/rpython/rtyper/lltypesystem/rffi.py

https://bitbucket.org/pypy/pypy/
Python | 1295 lines | 1142 code | 44 blank | 109 comment | 58 complexity | fe1c3773a692379f1d48fc0aa52b31ac MD5 | raw file
Possible License(s): AGPL-3.0, BSD-3-Clause, Apache-2.0

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

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