| 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, specialize, not_rpython |
| 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 |
|
| 26 |
class CConstant(Symbolic): |
| 27 |
""" A C-level constant, maybe #define, rendered directly. |
| 28 |
""" |
| 29 |
def __init__(self, c_name, TP): |
| 30 |
self.c_name = c_name |
| 31 |
self.TP = TP |
| 32 |
|
| 33 |
def __repr__(self): |
| 34 |
return '%s(%r, %s)' % (self.__class__.__name__, |
| 35 |
self.c_name, self.TP) |
| 36 |
|
| 37 |
def annotation(self): |
| 38 |
return lltype_to_annotation(self.TP) |
| 39 |
|
| 40 |
def lltype(self): |
| 41 |
return self.TP |
| 42 |
|
| 43 |
def _isfunctype(TP): |
| 44 |
""" Evil hack to get rid of flow objspace inability |
| 45 |
to accept .TO when TP is not a pointer |
| 46 |
""" |
| 47 |
return isinstance(TP, lltype.Ptr) and isinstance(TP.TO, lltype.FuncType) |
| 48 |
_isfunctype._annspecialcase_ = 'specialize:memo' |
| 49 |
|
| 50 |
def _isllptr(p): |
| 51 |
""" Second evil hack to detect if 'p' is a low-level pointer or not """ |
| 52 |
return isinstance(p, lltype._ptr) |
| 53 |
class _IsLLPtrEntry(ExtRegistryEntry): |
| 54 |
_about_ = _isllptr |
| 55 |
def compute_result_annotation(self, s_p): |
| 56 |
result = isinstance(s_p, SomePtr) |
| 57 |
return self.bookkeeper.immutablevalue(result) |
| 58 |
def specialize_call(self, hop): |
| 59 |
hop.exception_cannot_occur() |
| 60 |
return hop.inputconst(lltype.Bool, hop.s_result.const) |
| 61 |
|
| 62 |
RFFI_SAVE_ERRNO = 1 |
| 63 |
RFFI_READSAVED_ERRNO = 2 |
| 64 |
RFFI_ZERO_ERRNO_BEFORE = 4 |
| 65 |
RFFI_FULL_ERRNO = RFFI_SAVE_ERRNO | RFFI_READSAVED_ERRNO |
| 66 |
RFFI_FULL_ERRNO_ZERO = RFFI_SAVE_ERRNO | RFFI_ZERO_ERRNO_BEFORE |
| 67 |
RFFI_SAVE_LASTERROR = 8 |
| 68 |
RFFI_READSAVED_LASTERROR = 16 |
| 69 |
RFFI_SAVE_WSALASTERROR = 32 |
| 70 |
RFFI_FULL_LASTERROR = RFFI_SAVE_LASTERROR | RFFI_READSAVED_LASTERROR |
| 71 |
RFFI_ERR_NONE = 0 |
| 72 |
RFFI_ERR_ALL = RFFI_FULL_ERRNO | RFFI_FULL_LASTERROR |
| 73 |
RFFI_ALT_ERRNO = 64 |
| 74 |
def llexternal(name, args, result, _callable=None, |
| 75 |
compilation_info=ExternalCompilationInfo(), |
| 76 |
sandboxsafe=False, releasegil='auto', |
| 77 |
_nowrapper=False, calling_conv=None, |
| 78 |
elidable_function=False, macro=None, |
| 79 |
random_effects_on_gcobjs='auto', |
| 80 |
save_err=RFFI_ERR_NONE, |
| 81 |
natural_arity=-1): |
| 82 |
"""Build an external function that will invoke the C function 'name' |
| 83 |
with the given 'args' types and 'result' type. |
| 84 |
|
| 85 |
You get by default a wrapper that casts between number types as needed |
| 86 |
to match the arguments. You can also pass an RPython string when a |
| 87 |
CCHARP argument is expected, and the C function receives a 'const char*' |
| 88 |
pointing to a read-only null-terminated character of arrays, as usual |
| 89 |
for C. |
| 90 |
|
| 91 |
The C function can have callbacks, but they must be specified explicitly |
| 92 |
as constant RPython functions. We don't support yet C functions that |
| 93 |
invoke callbacks passed otherwise (e.g. set by a previous C call). |
| 94 |
|
| 95 |
releasegil: whether it's ok to release the GIL around the call. |
| 96 |
Default is yes, unless sandboxsafe is set, in which case |
| 97 |
we consider that the function is really short-running and |
| 98 |
don't bother releasing the GIL. An explicit True or False |
| 99 |
overrides this logic. |
| 100 |
|
| 101 |
calling_conv: if 'unknown' or 'win', the C function is not directly seen |
| 102 |
by the JIT. If 'c', it can be seen (depending on |
| 103 |
releasegil=False). For tests only, or if _nowrapper, |
| 104 |
it defaults to 'c'. |
| 105 |
|
| 106 |
natural_arity: on platforms where it matters, you have to provide the natural |
| 107 |
arity for variadic calls. Important examples are OS X on M1 |
| 108 |
""" |
| 109 |
if calling_conv is None: |
| 110 |
if sys.platform == 'win32' and not _nowrapper: |
| 111 |
calling_conv = 'unknown' |
| 112 |
else: |
| 113 |
calling_conv = 'c' |
| 114 |
if _callable is not None: |
| 115 |
assert callable(_callable) |
| 116 |
ext_type = lltype.FuncType(args, result) |
| 117 |
if _callable is None: |
| 118 |
if macro is not None: |
| 119 |
if macro is True: |
| 120 |
macro = name |
| 121 |
_callable = generate_macro_wrapper( |
| 122 |
name, macro, ext_type, compilation_info) |
| 123 |
else: |
| 124 |
_callable = ll2ctypes.LL2CtypesCallable(ext_type, |
| 125 |
'c' if calling_conv == 'unknown' else calling_conv, |
| 126 |
natural_arity) |
| 127 |
else: |
| 128 |
assert macro is None, "'macro' is useless if you specify '_callable'" |
| 129 |
if elidable_function: |
| 130 |
_callable._elidable_function_ = True |
| 131 |
kwds = {} |
| 132 |
|
| 133 |
has_callback = False |
| 134 |
for ARG in args: |
| 135 |
if _isfunctype(ARG): |
| 136 |
has_callback = True |
| 137 |
if has_callback: |
| 138 |
kwds['_callbacks'] = callbackholder = CallbackHolder() |
| 139 |
else: |
| 140 |
callbackholder = None |
| 141 |
|
| 142 |
if releasegil in (False, True): |
| 143 |
|
| 144 |
|
| 145 |
invoke_around_handlers = releasegil |
| 146 |
else: |
| 147 |
|
| 148 |
|
| 149 |
|
| 150 |
|
| 151 |
invoke_around_handlers = not sandboxsafe and not _nowrapper |
| 152 |
|
| 153 |
if _nowrapper and isinstance(_callable, ll2ctypes.LL2CtypesCallable): |
| 154 |
kwds['_real_integer_addr'] = _callable.get_real_address |
| 155 |
|
| 156 |
if random_effects_on_gcobjs not in (False, True): |
| 157 |
random_effects_on_gcobjs = ( |
| 158 |
invoke_around_handlers or |
| 159 |
has_callback) |
| 160 |
assert not (elidable_function and random_effects_on_gcobjs) |
| 161 |
|
| 162 |
funcptr = lltype.functionptr(ext_type, name, external='C', |
| 163 |
compilation_info=compilation_info, |
| 164 |
_callable=_callable, |
| 165 |
_safe_not_sandboxed=sandboxsafe, |
| 166 |
_debugexc=True, |
| 167 |
canraise=False, |
| 168 |
random_effects_on_gcobjs= |
| 169 |
random_effects_on_gcobjs, |
| 170 |
calling_conv=calling_conv, |
| 171 |
natural_arity=natural_arity, |
| 172 |
**kwds) |
| 173 |
if isinstance(_callable, ll2ctypes.LL2CtypesCallable): |
| 174 |
_callable.funcptr = funcptr |
| 175 |
|
| 176 |
if _nowrapper: |
| 177 |
assert save_err == RFFI_ERR_NONE |
| 178 |
return funcptr |
| 179 |
|
| 180 |
if invoke_around_handlers: |
| 181 |
|
| 182 |
|
| 183 |
|
| 184 |
|
| 185 |
|
| 186 |
|
| 187 |
|
| 188 |
|
| 189 |
|
| 190 |
argnames = ', '.join(['a%d' % i for i in range(len(args))]) |
| 191 |
source = py.code.Source(""" |
| 192 |
from rpython.rlib import rgil |
| 193 |
def call_external_function(%(argnames)s): |
| 194 |
rgil.release() |
| 195 |
# NB. it is essential that no exception checking occurs here! |
| 196 |
if %(save_err)d: |
| 197 |
from rpython.rlib import rposix |
| 198 |
rposix._errno_before(%(save_err)d) |
| 199 |
if we_are_translated(): |
| 200 |
res = funcptr(%(argnames)s) |
| 201 |
else: |
| 202 |
try: # only when non-translated |
| 203 |
res = funcptr(%(argnames)s) |
| 204 |
except: |
| 205 |
rgil.acquire() |
| 206 |
raise |
| 207 |
if %(save_err)d: |
| 208 |
from rpython.rlib import rposix |
| 209 |
rposix._errno_after(%(save_err)d) |
| 210 |
rgil.acquire() |
| 211 |
return res |
| 212 |
""" % locals()) |
| 213 |
miniglobals = {'funcptr': funcptr, |
| 214 |
'__name__': __name__, |
| 215 |
'we_are_translated': we_are_translated, |
| 216 |
} |
| 217 |
exec source.compile() in miniglobals |
| 218 |
call_external_function = miniglobals['call_external_function'] |
| 219 |
call_external_function._dont_inline_ = True |
| 220 |
call_external_function._annspecialcase_ = 'specialize:ll' |
| 221 |
call_external_function._gctransformer_hint_close_stack_ = True |
| 222 |
|
| 223 |
|
| 224 |
|
| 225 |
|
| 226 |
|
| 227 |
if macro is None and natural_arity == -1: |
| 228 |
call_external_function._call_aroundstate_target_ = funcptr, save_err |
| 229 |
|
| 230 |
call_external_function = func_with_new_name(call_external_function, |
| 231 |
'ccall_' + name) |
| 232 |
|
| 233 |
|
| 234 |
else: |
| 235 |
|
| 236 |
|
| 237 |
|
| 238 |
|
| 239 |
|
| 240 |
need_wrapper = (macro is not None or save_err != RFFI_ERR_NONE) |
| 241 |
|
| 242 |
|
| 243 |
if calling_conv != 'c': |
| 244 |
need_wrapper = True |
| 245 |
|
| 246 |
if not need_wrapper: |
| 247 |
call_external_function = funcptr |
| 248 |
else: |
| 249 |
argnames = ', '.join(['a%d' % i for i in range(len(args))]) |
| 250 |
source = py.code.Source(""" |
| 251 |
def call_external_function(%(argnames)s): |
| 252 |
if %(save_err)d: |
| 253 |
from rpython.rlib import rposix |
| 254 |
rposix._errno_before(%(save_err)d) |
| 255 |
res = funcptr(%(argnames)s) |
| 256 |
if %(save_err)d: |
| 257 |
from rpython.rlib import rposix |
| 258 |
rposix._errno_after(%(save_err)d) |
| 259 |
return res |
| 260 |
""" % locals()) |
| 261 |
miniglobals = {'funcptr': funcptr, |
| 262 |
'__name__': __name__, |
| 263 |
} |
| 264 |
exec source.compile() in miniglobals |
| 265 |
call_external_function = miniglobals['call_external_function'] |
| 266 |
call_external_function = func_with_new_name(call_external_function, |
| 267 |
'ccall_' + name) |
| 268 |
call_external_function = jit.dont_look_inside( |
| 269 |
call_external_function) |
| 270 |
|
| 271 |
def _oops(): |
| 272 |
raise AssertionError("can't pass (any more) a unicode string" |
| 273 |
" directly to a VOIDP argument") |
| 274 |
_oops._annspecialcase_ = 'specialize:memo' |
| 275 |
|
| 276 |
nb_args = len(args) |
| 277 |
unrolling_arg_tps = unrolling_iterable(enumerate(args)) |
| 278 |
def wrapper(*args): |
| 279 |
assert len(args) == nb_args |
| 280 |
real_args = () |
| 281 |
|
| 282 |
|
| 283 |
to_free = () |
| 284 |
for i, TARGET in unrolling_arg_tps: |
| 285 |
arg = args[i] |
| 286 |
if TARGET == CCHARP or TARGET is VOIDP: |
| 287 |
if arg is None: |
| 288 |
from rpython.rtyper.annlowlevel import llstr |
| 289 |
arg = lltype.nullptr(CCHARP.TO) |
| 290 |
to_free = to_free + (arg, llstr(None), '\x04') |
| 291 |
elif isinstance(arg, str): |
| 292 |
tup = get_nonmovingbuffer_ll_final_null(arg) |
| 293 |
to_free = to_free + tup |
| 294 |
arg = tup[0] |
| 295 |
elif isinstance(arg, unicode): |
| 296 |
_oops() |
| 297 |
elif TARGET == CWCHARP: |
| 298 |
if arg is None: |
| 299 |
arg = lltype.nullptr(CWCHARP.TO) |
| 300 |
to_free = to_free + (arg,) |
| 301 |
elif isinstance(arg, unicode): |
| 302 |
arg = unicode2wcharp(arg) |
| 303 |
to_free = to_free + (arg,) |
| 304 |
elif _isfunctype(TARGET) and not _isllptr(arg): |
| 305 |
|
| 306 |
use_gil = invoke_around_handlers |
| 307 |
arg = llhelper(TARGET, _make_wrapper_for(TARGET, arg, |
| 308 |
callbackholder, |
| 309 |
use_gil)) |
| 310 |
else: |
| 311 |
SOURCE = lltype.typeOf(arg) |
| 312 |
if SOURCE != TARGET: |
| 313 |
if TARGET is lltype.Float: |
| 314 |
arg = float(arg) |
| 315 |
elif ((isinstance(SOURCE, lltype.Number) |
| 316 |
or SOURCE is lltype.Bool) |
| 317 |
and (isinstance(TARGET, lltype.Number) |
| 318 |
or TARGET is lltype.Bool)): |
| 319 |
arg = cast(TARGET, arg) |
| 320 |
real_args = real_args + (arg,) |
| 321 |
res = call_external_function(*real_args) |
| 322 |
for i, TARGET in unrolling_arg_tps: |
| 323 |
arg = args[i] |
| 324 |
if TARGET == CCHARP or TARGET is VOIDP: |
| 325 |
if arg is None: |
| 326 |
to_free = to_free[3:] |
| 327 |
elif isinstance(arg, str): |
| 328 |
free_nonmovingbuffer_ll(to_free[0], to_free[1], to_free[2]) |
| 329 |
to_free = to_free[3:] |
| 330 |
elif TARGET == CWCHARP: |
| 331 |
if arg is None: |
| 332 |
to_free = to_free[1:] |
| 333 |
elif isinstance(arg, unicode): |
| 334 |
free_wcharp(to_free[0]) |
| 335 |
to_free = to_free[1:] |
| 336 |
assert len(to_free) == 0 |
| 337 |
if rarithmetic.r_int is not r_int: |
| 338 |
if result is INT: |
| 339 |
return cast(lltype.Signed, res) |
| 340 |
elif result is UINT: |
| 341 |
return cast(lltype.Unsigned, res) |
| 342 |
return res |
| 343 |
wrapper._annspecialcase_ = 'specialize:ll' |
| 344 |
wrapper._always_inline_ = 'try' |
| 345 |
|
| 346 |
wrapper._ptr = funcptr |
| 347 |
wrapper = func_with_new_name(wrapper, name) |
| 348 |
return wrapper |
| 349 |
|
| 350 |
|
| 351 |
class CallbackHolder: |
| 352 |
def __init__(self): |
| 353 |
self.callbacks = {} |
| 354 |
|
| 355 |
def _make_wrapper_for(TP, callable, callbackholder, use_gil): |
| 356 |
""" Function creating wrappers for callbacks. Note that this is |
| 357 |
cheating as we assume constant callbacks and we just memoize wrappers |
| 358 |
""" |
| 359 |
from rpython.rtyper.lltypesystem import lltype |
| 360 |
from rpython.rtyper.lltypesystem.lloperation import llop |
| 361 |
if hasattr(callable, '_errorcode_'): |
| 362 |
errorcode = callable._errorcode_ |
| 363 |
else: |
| 364 |
errorcode = TP.TO.RESULT._defl() |
| 365 |
callable_name = getattr(callable, '__name__', '?') |
| 366 |
if callbackholder is not None: |
| 367 |
callbackholder.callbacks[callable] = True |
| 368 |
args = ', '.join(['a%d' % i for i in range(len(TP.TO.ARGS))]) |
| 369 |
source = py.code.Source(r""" |
| 370 |
rgil = None |
| 371 |
if use_gil: |
| 372 |
from rpython.rlib import rgil |
| 373 |
|
| 374 |
def wrapper(%(args)s): # no *args - no GIL for mallocing the tuple |
| 375 |
if rgil is not None: |
| 376 |
rgil.acquire_maybe_in_new_thread() |
| 377 |
# from now on we hold the GIL |
| 378 |
llop.gc_stack_bottom(lltype.Void) # marker to enter RPython from C |
| 379 |
try: |
| 380 |
result = callable(%(args)s) |
| 381 |
except Exception, e: |
| 382 |
os.write(2, |
| 383 |
"Warning: uncaught exception in callback: %%s %%s\n" %% |
| 384 |
(callable_name, str(e))) |
| 385 |
if not we_are_translated(): |
| 386 |
import traceback |
| 387 |
traceback.print_exc() |
| 388 |
result = errorcode |
| 389 |
if rgil is not None: |
| 390 |
rgil.release() |
| 391 |
# here we don't hold the GIL any more. As in the wrapper() produced |
| 392 |
# by llexternal, it is essential that no exception checking occurs |
| 393 |
# after the call to rgil.release(). |
| 394 |
return result |
| 395 |
""" % locals()) |
| 396 |
miniglobals = locals().copy() |
| 397 |
miniglobals['Exception'] = Exception |
| 398 |
miniglobals['os'] = os |
| 399 |
miniglobals['we_are_translated'] = we_are_translated |
| 400 |
exec source.compile() in miniglobals |
| 401 |
return miniglobals['wrapper'] |
| 402 |
_make_wrapper_for._annspecialcase_ = 'specialize:memo' |
| 403 |
|
| 404 |
AroundFnPtr = lltype.Ptr(lltype.FuncType([], lltype.Void)) |
| 405 |
|
| 406 |
|
| 407 |
def llexternal_use_eci(compilation_info): |
| 408 |
"""Return a dummy function that, if called in a RPython program, |
| 409 |
adds the given ExternalCompilationInfo to it.""" |
| 410 |
eci = ExternalCompilationInfo(post_include_bits=['#define PYPY_NO_OP()']) |
| 411 |
eci = eci.merge(compilation_info) |
| 412 |
return llexternal('PYPY_NO_OP', [], lltype.Void, |
| 413 |
compilation_info=eci, sandboxsafe=True, _nowrapper=True, |
| 414 |
_callable=lambda: None) |
| 415 |
|
| 416 |
def generate_macro_wrapper(name, macro, functype, eci): |
| 417 |
"""Wraps a function-like macro inside a real function, and expose |
| 418 |
it with llexternal.""" |
| 419 |
|
| 420 |
|
| 421 |
from rpython.translator.c.database import LowLevelDatabase |
| 422 |
from rpython.translator.c.support import cdecl |
| 423 |
wrapper_name = 'pypy_macro_wrapper_%s' % (name,) |
| 424 |
argnames = ['arg%d' % (i,) for i in range(len(functype.ARGS))] |
| 425 |
db = LowLevelDatabase() |
| 426 |
implementationtypename = db.gettype(functype, argnames=argnames) |
| 427 |
if functype.RESULT is lltype.Void: |
| 428 |
pattern = '%s%s { %s(%s); }' |
| 429 |
else: |
| 430 |
pattern = '%s%s { return %s(%s); }' |
| 431 |
source = pattern % ( |
| 432 |
'RPY_EXTERN ', |
| 433 |
cdecl(implementationtypename, wrapper_name), |
| 434 |
macro, ', '.join(argnames)) |
| 435 |
|
| 436 |
|
| 437 |
|
| 438 |
|
| 439 |
|
| 440 |
ctypes_eci = eci.merge(ExternalCompilationInfo( |
| 441 |
separate_module_sources=[source], |
| 442 |
)) |
| 443 |
if hasattr(eci, '_with_ctypes'): |
| 444 |
ctypes_eci = eci._with_ctypes.merge(ctypes_eci) |
| 445 |
eci._with_ctypes = ctypes_eci |
| 446 |
func = llexternal(wrapper_name, functype.ARGS, functype.RESULT, |
| 447 |
compilation_info=eci, _nowrapper=True) |
| 448 |
|
| 449 |
return lambda *args: func(*args) |
| 450 |
|
| 451 |
|
| 452 |
|
| 453 |
|
| 454 |
|
| 455 |
|
| 456 |
_KEEPER_CACHE = {} |
| 457 |
|
| 458 |
def _keeper_for_type(TP): |
| 459 |
try: |
| 460 |
return _KEEPER_CACHE[TP] |
| 461 |
except KeyError: |
| 462 |
tp_str = str(TP) |
| 463 |
class KeepaliveKeeper(object): |
| 464 |
def __init__(self): |
| 465 |
self.stuff_to_keepalive = [] |
| 466 |
self.free_positions = [] |
| 467 |
keeper = KeepaliveKeeper() |
| 468 |
_KEEPER_CACHE[TP] = keeper |
| 469 |
return keeper |
| 470 |
_keeper_for_type._annspecialcase_ = 'specialize:memo' |
| 471 |
|
| 472 |
def register_keepalive(obj): |
| 473 |
""" Register object obj to be kept alive, |
| 474 |
returns a position for that object |
| 475 |
""" |
| 476 |
keeper = _keeper_for_type(lltype.typeOf(obj)) |
| 477 |
if len(keeper.free_positions): |
| 478 |
pos = keeper.free_positions.pop() |
| 479 |
keeper.stuff_to_keepalive[pos] = obj |
| 480 |
return pos |
| 481 |
|
| 482 |
pos = len(keeper.stuff_to_keepalive) |
| 483 |
keeper.stuff_to_keepalive.append(obj) |
| 484 |
return pos |
| 485 |
register_keepalive._annspecialcase_ = 'specialize:argtype(0)' |
| 486 |
|
| 487 |
def get_keepalive_object(pos, TP): |
| 488 |
keeper = _keeper_for_type(TP) |
| 489 |
return keeper.stuff_to_keepalive[pos] |
| 490 |
get_keepalive_object._annspecialcase_ = 'specialize:arg(1)' |
| 491 |
|
| 492 |
def unregister_keepalive(pos, TP): |
| 493 |
""" Unregister an object of type TP, stored at position |
| 494 |
pos (position previously returned by register_keepalive) |
| 495 |
""" |
| 496 |
keeper = _keeper_for_type(TP) |
| 497 |
keeper.stuff_to_keepalive[pos] = None |
| 498 |
keeper.free_positions.append(pos) |
| 499 |
unregister_keepalive._annspecialcase_ = 'specialize:arg(1)' |
| 500 |
|
| 501 |
|
| 502 |
|
| 503 |
TYPES = [] |
| 504 |
for _name in 'short int long'.split(): |
| 505 |
for name in (_name, 'unsigned ' + _name): |
| 506 |
TYPES.append(name) |
| 507 |
TYPES += ['signed char', 'unsigned char', |
| 508 |
'long long', 'unsigned long long', |
| 509 |
'size_t', 'time_t', 'wchar_t', |
| 510 |
'uintptr_t', 'intptr_t', |
| 511 |
'void*'] |
| 512 |
|
| 513 |
|
| 514 |
try: |
| 515 |
sizeof_c_type('__int128_t', ignore_errors=True) |
| 516 |
TYPES += ['__int128_t', '__uint128_t'] |
| 517 |
except CompilationError: |
| 518 |
pass |
| 519 |
|
| 520 |
if os.name != 'nt': |
| 521 |
TYPES.append('mode_t') |
| 522 |
TYPES.append('pid_t') |
| 523 |
TYPES.append('ssize_t') |
| 524 |
|
| 525 |
TYPES.extend(['ptrdiff_t', |
| 526 |
'int_least8_t', 'uint_least8_t', |
| 527 |
'int_least16_t', 'uint_least16_t', |
| 528 |
'int_least32_t', 'uint_least32_t', |
| 529 |
'int_least64_t', 'uint_least64_t', |
| 530 |
'int_fast8_t', 'uint_fast8_t', |
| 531 |
'int_fast16_t', 'uint_fast16_t', |
| 532 |
'int_fast32_t', 'uint_fast32_t', |
| 533 |
'int_fast64_t', 'uint_fast64_t', |
| 534 |
'intmax_t', 'uintmax_t']) |
| 535 |
else: |
| 536 |
|
| 537 |
PID_T = lltype.Signed |
| 538 |
SSIZE_T = lltype.Signed |
| 539 |
PTRDIFF_T = lltype.Signed |
| 540 |
|
| 541 |
def populate_inttypes(): |
| 542 |
names = [] |
| 543 |
populatelist = [] |
| 544 |
for name in TYPES: |
| 545 |
c_name = name |
| 546 |
if name.startswith('unsigned'): |
| 547 |
name = 'u' + name[9:] |
| 548 |
signed = False |
| 549 |
elif (name == 'size_t' or name.startswith('uint') |
| 550 |
or name.startswith('__uint')): |
| 551 |
signed = False |
| 552 |
elif name == 'wchar_t' and sys.platform == 'win32': |
| 553 |
signed = False |
| 554 |
else: |
| 555 |
signed = True |
| 556 |
name = name.replace(' ', '') |
| 557 |
names.append(name) |
| 558 |
populatelist.append((name.upper(), c_name, signed)) |
| 559 |
platform.populate_inttypes(populatelist) |
| 560 |
return names |
| 561 |
|
| 562 |
def setup(): |
| 563 |
""" creates necessary c-level types |
| 564 |
""" |
| 565 |
names = populate_inttypes() |
| 566 |
result = [] |
| 567 |
for name in names: |
| 568 |
tp = platform.types[name.upper()] |
| 569 |
globals()['r_' + name] = platform.numbertype_to_rclass[tp] |
| 570 |
globals()[name.upper()] = tp |
| 571 |
tpp = lltype.Ptr(lltype.Array(tp, hints={'nolength': True})) |
| 572 |
globals()[name.upper()+'P'] = tpp |
| 573 |
result.append(tp) |
| 574 |
return result |
| 575 |
|
| 576 |
NUMBER_TYPES = setup() |
| 577 |
platform.numbertype_to_rclass[lltype.Signed] = int |
| 578 |
r_int_real = rarithmetic.build_int("r_int_real", r_int.SIGN, r_int.BITS, True) |
| 579 |
INT_real = lltype.build_number("INT", r_int_real) |
| 580 |
platform.numbertype_to_rclass[INT_real] = r_int_real |
| 581 |
NUMBER_TYPES.append(INT_real) |
| 582 |
r_uint_real = rarithmetic.build_int("r_uint_real", r_uint.SIGN, r_uint.BITS, True) |
| 583 |
UINT_real = lltype.build_number("UINT", r_uint_real) |
| 584 |
platform.numbertype_to_rclass[UINT_real] = r_uint_real |
| 585 |
NUMBER_TYPES.append(UINT_real) |
| 586 |
|
| 587 |
|
| 588 |
|
| 589 |
|
| 590 |
|
| 591 |
|
| 592 |
|
| 593 |
|
| 594 |
|
| 595 |
|
| 596 |
|
| 597 |
|
| 598 |
|
| 599 |
|
| 600 |
|
| 601 |
|
| 602 |
|
| 603 |
|
| 604 |
|
| 605 |
|
| 606 |
|
| 607 |
|
| 608 |
|
| 609 |
|
| 610 |
|
| 611 |
if os.name == 'nt': |
| 612 |
MODE_T = INT |
| 613 |
|
| 614 |
def CStruct(name, *fields, **kwds): |
| 615 |
""" A small helper to create external C structure, not the |
| 616 |
pypy one |
| 617 |
""" |
| 618 |
hints = kwds.get('hints', {}) |
| 619 |
hints = hints.copy() |
| 620 |
kwds['hints'] = hints |
| 621 |
hints['external'] = 'C' |
| 622 |
hints['c_name'] = name |
| 623 |
|
| 624 |
|
| 625 |
c_fields = [('c_' + key, value) for key, value in fields] |
| 626 |
return lltype.Struct(name, *c_fields, **kwds) |
| 627 |
|
| 628 |
def CStructPtr(*args, **kwds): |
| 629 |
return lltype.Ptr(CStruct(*args, **kwds)) |
| 630 |
|
| 631 |
def CFixedArray(tp, size): |
| 632 |
return lltype.FixedSizeArray(tp, size) |
| 633 |
CFixedArray._annspecialcase_ = 'specialize:memo' |
| 634 |
|
| 635 |
def CArray(tp): |
| 636 |
return lltype.Array(tp, hints={'nolength': True}) |
| 637 |
CArray._annspecialcase_ = 'specialize:memo' |
| 638 |
|
| 639 |
def CArrayPtr(tp): |
| 640 |
return lltype.Ptr(CArray(tp)) |
| 641 |
CArrayPtr._annspecialcase_ = 'specialize:memo' |
| 642 |
|
| 643 |
def CCallback(args, res): |
| 644 |
return lltype.Ptr(lltype.FuncType(args, res)) |
| 645 |
CCallback._annspecialcase_ = 'specialize:memo' |
| 646 |
|
| 647 |
def COpaque(name=None, ptr_typedef=None, hints=None, compilation_info=None): |
| 648 |
if compilation_info is None: |
| 649 |
compilation_info = ExternalCompilationInfo() |
| 650 |
if hints is None: |
| 651 |
hints = {} |
| 652 |
else: |
| 653 |
hints = hints.copy() |
| 654 |
hints['external'] = 'C' |
| 655 |
if name is not None: |
| 656 |
hints['c_name'] = name |
| 657 |
if ptr_typedef is not None: |
| 658 |
hints['c_pointer_typedef'] = ptr_typedef |
| 659 |
def lazy_getsize(cache={}): |
| 660 |
from rpython.rtyper.tool import rffi_platform |
| 661 |
try: |
| 662 |
return cache[name] |
| 663 |
except KeyError: |
| 664 |
val = rffi_platform.sizeof(name, compilation_info) |
| 665 |
cache[name] = val |
| 666 |
return val |
| 667 |
|
| 668 |
hints['getsize'] = lazy_getsize |
| 669 |
return lltype.OpaqueType(name, hints) |
| 670 |
|
| 671 |
def COpaquePtr(*args, **kwds): |
| 672 |
typedef = kwds.pop('typedef', None) |
| 673 |
return lltype.Ptr(COpaque(ptr_typedef=typedef, *args, **kwds)) |
| 674 |
|
| 675 |
def CExternVariable(TYPE, name, eci, _CConstantClass=CConstant, |
| 676 |
sandboxsafe=False, _nowrapper=False, |
| 677 |
c_type=None, getter_only=False, |
| 678 |
declare_as_extern=(sys.platform != 'win32')): |
| 679 |
"""Return a pair of functions - a getter and a setter - to access |
| 680 |
the given global C variable. |
| 681 |
""" |
| 682 |
from rpython.translator.c.primitive import PrimitiveType |
| 683 |
from rpython.translator.tool.cbuild import ExternalCompilationInfo |
| 684 |
|
| 685 |
|
| 686 |
if c_type is None: |
| 687 |
if TYPE == CCHARPP: |
| 688 |
c_type = 'char **' |
| 689 |
elif TYPE == CCHARP: |
| 690 |
c_type = 'char *' |
| 691 |
elif TYPE == INT or TYPE == LONG: |
| 692 |
assert False, "ambiguous type on 32-bit machines: give a c_type" |
| 693 |
else: |
| 694 |
c_type = PrimitiveType[TYPE] |
| 695 |
assert c_type.endswith(' @') |
| 696 |
c_type = c_type[:-2] |
| 697 |
|
| 698 |
getter_name = 'get_' + name |
| 699 |
setter_name = 'set_' + name |
| 700 |
getter_prototype = ( |
| 701 |
"RPY_EXTERN %(c_type)s %(getter_name)s (void);" % locals()) |
| 702 |
setter_prototype = ( |
| 703 |
"RPY_EXTERN void %(setter_name)s (%(c_type)s v);" % locals()) |
| 704 |
c_getter = "%(c_type)s %(getter_name)s () { return %(name)s; }" % locals() |
| 705 |
c_setter = "void %(setter_name)s (%(c_type)s v) { %(name)s = v; }" % locals() |
| 706 |
|
| 707 |
lines = ["#include <%s>" % i for i in eci.includes] |
| 708 |
if declare_as_extern: |
| 709 |
lines.append('extern %s %s;' % (c_type, name)) |
| 710 |
lines.append(c_getter) |
| 711 |
if not getter_only: |
| 712 |
lines.append(c_setter) |
| 713 |
prototypes = [getter_prototype] |
| 714 |
if not getter_only: |
| 715 |
prototypes.append(setter_prototype) |
| 716 |
sources = ('\n'.join(lines),) |
| 717 |
new_eci = eci.merge(ExternalCompilationInfo( |
| 718 |
separate_module_sources = sources, |
| 719 |
post_include_bits = prototypes, |
| 720 |
)) |
| 721 |
|
| 722 |
getter = llexternal(getter_name, [], TYPE, compilation_info=new_eci, |
| 723 |
sandboxsafe=sandboxsafe, _nowrapper=_nowrapper) |
| 724 |
if getter_only: |
| 725 |
return getter |
| 726 |
else: |
| 727 |
setter = llexternal(setter_name, [TYPE], lltype.Void, |
| 728 |
compilation_info=new_eci, sandboxsafe=sandboxsafe, |
| 729 |
_nowrapper=_nowrapper) |
| 730 |
return getter, setter |
| 731 |
|
| 732 |
|
| 733 |
|
| 734 |
CHAR = lltype.Char |
| 735 |
|
| 736 |
|
| 737 |
DOUBLE = lltype.Float |
| 738 |
LONGDOUBLE = lltype.LongFloat |
| 739 |
|
| 740 |
|
| 741 |
|
| 742 |
FLOAT = lltype.SingleFloat |
| 743 |
r_singlefloat = rarithmetic.r_singlefloat |
| 744 |
|
| 745 |
|
| 746 |
VOIDP = lltype.Ptr(lltype.Array(lltype.Char, hints={'nolength': True, 'render_as_void': True})) |
| 747 |
CONST_VOIDP = lltype.Ptr(lltype.Array(lltype.Char, hints={'nolength': True, 'render_as_void': True, 'render_as_const': True})) |
| 748 |
NULL = None |
| 749 |
|
| 750 |
|
| 751 |
VOIDPP = CArrayPtr(VOIDP) |
| 752 |
|
| 753 |
|
| 754 |
CCHARP = lltype.Ptr(lltype.Array(lltype.Char, hints={'nolength': True})) |
| 755 |
|
| 756 |
|
| 757 |
CONST_CCHARP = lltype.Ptr(lltype.Array(lltype.Char, hints={'nolength': True, |
| 758 |
'render_as_const': True})) |
| 759 |
|
| 760 |
|
| 761 |
CWCHARP = lltype.Ptr(lltype.Array(lltype.UniChar, hints={'nolength': True})) |
| 762 |
|
| 763 |
|
| 764 |
|
| 765 |
INT_realP = lltype.Ptr(lltype.Array(INT_real, hints={'nolength': True})) |
| 766 |
|
| 767 |
|
| 768 |
DOUBLEP = lltype.Ptr(lltype.Array(DOUBLE, hints={'nolength': True})) |
| 769 |
|
| 770 |
|
| 771 |
FLOATP = lltype.Ptr(lltype.Array(FLOAT, hints={'nolength': True})) |
| 772 |
|
| 773 |
|
| 774 |
LONGDOUBLEP = lltype.Ptr(lltype.Array(LONGDOUBLE, hints={'nolength': True})) |
| 775 |
|
| 776 |
|
| 777 |
SIGNED = lltype.Signed |
| 778 |
SIGNEDP = lltype.Ptr(lltype.Array(lltype.Signed, hints={'nolength': True})) |
| 779 |
SIGNEDPP = lltype.Ptr(lltype.Array(SIGNEDP, hints={'nolength': True})) |
| 780 |
|
| 781 |
|
| 782 |
UNSIGNED = lltype.Unsigned |
| 783 |
UNSIGNEDP = lltype.Ptr(lltype.Array(lltype.Unsigned, hints={'nolength': True})) |
| 784 |
|
| 785 |
|
| 786 |
|
| 787 |
|
| 788 |
|
| 789 |
|
| 790 |
def make_string_mappings(strtype): |
| 791 |
|
| 792 |
if strtype is str: |
| 793 |
from rpython.rtyper.lltypesystem.rstr import (STR as STRTYPE, |
| 794 |
copy_string_to_raw, |
| 795 |
copy_raw_to_string, |
| 796 |
copy_string_contents, |
| 797 |
mallocstr as mallocfn) |
| 798 |
from rpython.rtyper.annlowlevel import llstr as llstrtype |
| 799 |
from rpython.rtyper.annlowlevel import hlstr as hlstrtype |
| 800 |
TYPEP = CCHARP |
| 801 |
ll_char_type = lltype.Char |
| 802 |
lastchar = '\x00' |
| 803 |
else: |
| 804 |
from rpython.rtyper.lltypesystem.rstr import ( |
| 805 |
UNICODE as STRTYPE, |
| 806 |
copy_unicode_to_raw as copy_string_to_raw, |
| 807 |
copy_raw_to_unicode as copy_raw_to_string, |
| 808 |
copy_unicode_contents as copy_string_contents, |
| 809 |
mallocunicode as mallocfn) |
| 810 |
from rpython.rtyper.annlowlevel import llunicode as llstrtype |
| 811 |
from rpython.rtyper.annlowlevel import hlunicode as hlstrtype |
| 812 |
TYPEP = CWCHARP |
| 813 |
ll_char_type = lltype.UniChar |
| 814 |
lastchar = u'\x00' |
| 815 |
|
| 816 |
|
| 817 |
def str2charp(s, track_allocation=True): |
| 818 |
""" str -> char* |
| 819 |
""" |
| 820 |
if track_allocation: |
| 821 |
array = lltype.malloc(TYPEP.TO, len(s) + 1, flavor='raw', track_allocation=True) |
| 822 |
else: |
| 823 |
array = lltype.malloc(TYPEP.TO, len(s) + 1, flavor='raw', track_allocation=False) |
| 824 |
i = len(s) |
| 825 |
ll_s = llstrtype(s) |
| 826 |
copy_string_to_raw(ll_s, array, 0, i) |
| 827 |
array[i] = lastchar |
| 828 |
return array |
| 829 |
str2charp._annenforceargs_ = [strtype, bool] |
| 830 |
|
| 831 |
def free_charp(cp, track_allocation=True): |
| 832 |
if track_allocation: |
| 833 |
lltype.free(cp, flavor='raw', track_allocation=True) |
| 834 |
else: |
| 835 |
lltype.free(cp, flavor='raw', track_allocation=False) |
| 836 |
free_charp._annenforceargs_ = [None, bool] |
| 837 |
|
| 838 |
|
| 839 |
def str2chararray(s, array, maxsize): |
| 840 |
length = min(len(s), maxsize) |
| 841 |
ll_s = llstrtype(s) |
| 842 |
copy_string_to_raw(ll_s, array, 0, length) |
| 843 |
return length |
| 844 |
str2chararray._annenforceargs_ = [strtype, None, int] |
| 845 |
|
| 846 |
|
| 847 |
|
| 848 |
def str2rawmem(s, array, start, length): |
| 849 |
ll_s = llstrtype(s) |
| 850 |
copy_string_to_raw(ll_s, array, start, length) |
| 851 |
|
| 852 |
|
| 853 |
|
| 854 |
def charp2str(cp): |
| 855 |
if not we_are_translated(): |
| 856 |
res = [] |
| 857 |
size = 0 |
| 858 |
while True: |
| 859 |
c = cp[size] |
| 860 |
if c == lastchar: |
| 861 |
return assert_str0("".join(res)) |
| 862 |
res.append(c) |
| 863 |
size += 1 |
| 864 |
|
| 865 |
size = 0 |
| 866 |
while cp[size] != lastchar: |
| 867 |
size += 1 |
| 868 |
return assert_str0(charpsize2str(cp, size)) |
| 869 |
charp2str._annenforceargs_ = [lltype.SomePtr(TYPEP)] |
| 870 |
|
| 871 |
|
| 872 |
|
| 873 |
@jit.dont_look_inside |
| 874 |
def get_nonmovingbuffer_ll(data): |
| 875 |
""" |
| 876 |
Either returns a non-moving copy or performs neccessary pointer |
| 877 |
arithmetic to return a pointer to the characters of a string if the |
| 878 |
string is already nonmovable or could be pinned. Must be followed by a |
| 879 |
free_nonmovingbuffer_ll call. |
| 880 |
|
| 881 |
The return type is a 3-tuple containing the "char *" result, |
| 882 |
a pointer to the low-level string object, and a flag as a char: |
| 883 |
|
| 884 |
* \4: no pinning, returned pointer is inside nonmovable 'llobj' |
| 885 |
* \5: 'llobj' was pinned, returned pointer is inside |
| 886 |
* \6: pinning failed, returned pointer is raw malloced |
| 887 |
|
| 888 |
For strings (not unicodes), the len()th character of the resulting |
| 889 |
raw buffer is available, but not initialized. Use |
| 890 |
get_nonmovingbuffer_ll_final_null() instead of get_nonmovingbuffer_ll() |
| 891 |
to get a regular null-terminated "char *". |
| 892 |
""" |
| 893 |
|
| 894 |
llobj = llstrtype(data) |
| 895 |
count = len(data) |
| 896 |
|
| 897 |
if rgc.must_split_gc_address_space(): |
| 898 |
flag = '\x06' |
| 899 |
elif we_are_translated_to_c() and not rgc.can_move(llobj): |
| 900 |
flag = '\x04' |
| 901 |
else: |
| 902 |
if we_are_translated_to_c() and rgc.pin(llobj): |
| 903 |
flag = '\x05' |
| 904 |
else: |
| 905 |
flag = '\x06' |
| 906 |
if flag == '\x06': |
| 907 |
buf = lltype.malloc(TYPEP.TO, count + (TYPEP is CCHARP), |
| 908 |
flavor='raw') |
| 909 |
copy_string_to_raw(llobj, buf, 0, count) |
| 910 |
return buf, llobj, '\x06' |
| 911 |
|
| 912 |
|
| 913 |
|
| 914 |
|
| 915 |
|
| 916 |
data_start = cast_ptr_to_adr(llobj) + \ |
| 917 |
offsetof(STRTYPE, 'chars') + itemoffsetof(STRTYPE.chars, 0) |
| 918 |
|
| 919 |
return cast(TYPEP, data_start), llobj, flag |
| 920 |
|
| 921 |
|
| 922 |
get_nonmovingbuffer_ll._always_inline_ = 'try' |
| 923 |
get_nonmovingbuffer_ll._annenforceargs_ = [strtype] |
| 924 |
|
| 925 |
|
| 926 |
@jit.dont_look_inside |
| 927 |
def get_nonmovingbuffer_ll_final_null(data): |
| 928 |
tup = get_nonmovingbuffer_ll(data) |
| 929 |
buf = tup[0] |
| 930 |
buf[len(data)] = lastchar |
| 931 |
return tup |
| 932 |
get_nonmovingbuffer_ll_final_null._always_inline_ = 'try' |
| 933 |
get_nonmovingbuffer_ll_final_null._annenforceargs_ = [strtype] |
| 934 |
|
| 935 |
|
| 936 |
|
| 937 |
@jit.dont_look_inside |
| 938 |
def free_nonmovingbuffer_ll(buf, llobj, flag): |
| 939 |
""" |
| 940 |
Keep 'llobj' alive and unpin it if it was pinned (flag==\5). |
| 941 |
Otherwise free the non-moving copy (flag==\6). |
| 942 |
""" |
| 943 |
if flag == '\x05': |
| 944 |
rgc.unpin(llobj) |
| 945 |
if flag == '\x06': |
| 946 |
lltype.free(buf, flavor='raw') |
| 947 |
|
| 948 |
|
| 949 |
keepalive_until_here(llobj) |
| 950 |
|
| 951 |
|
| 952 |
|
| 953 |
@jit.dont_look_inside |
| 954 |
def alloc_buffer(count): |
| 955 |
""" |
| 956 |
Returns a (raw_buffer, gc_buffer, case_num) triple, |
| 957 |
allocated with count bytes. |
| 958 |
The raw_buffer can be safely passed to a native function which expects |
| 959 |
it to not move. Call str_from_buffer with the returned values to get a |
| 960 |
safe high-level string. When the garbage collector cooperates, this |
| 961 |
allows for the process to be performed without an extra copy. |
| 962 |
Make sure to call keep_buffer_alive_until_here on the returned values. |
| 963 |
""" |
| 964 |
new_buf = mallocfn(count) |
| 965 |
pinned = 0 |
| 966 |
fallback = False |
| 967 |
if rgc.must_split_gc_address_space(): |
| 968 |
fallback = True |
| 969 |
elif rgc.can_move(new_buf): |
| 970 |
if rgc.pin(new_buf): |
| 971 |
pinned = 1 |
| 972 |
else: |
| 973 |
fallback = True |
| 974 |
if fallback: |
| 975 |
raw_buf = lltype.malloc(TYPEP.TO, count, flavor='raw') |
| 976 |
return raw_buf, new_buf, 2 |
| 977 |
|
| 978 |
|
| 979 |
|
| 980 |
|
| 981 |
data_start = cast_ptr_to_adr(new_buf) + \ |
| 982 |
offsetof(STRTYPE, 'chars') + itemoffsetof(STRTYPE.chars, 0) |
| 983 |
return cast(TYPEP, data_start), new_buf, pinned |
| 984 |
alloc_buffer._always_inline_ = 'try' |
| 985 |
alloc_buffer._annenforceargs_ = [int] |
| 986 |
|
| 987 |
|
| 988 |
@jit.dont_look_inside |
| 989 |
@enforceargs(None, None, int, int, int) |
| 990 |
def str_from_buffer(raw_buf, gc_buf, case_num, allocated_size, needed_size): |
| 991 |
""" |
| 992 |
Converts from a pair returned by alloc_buffer to a high-level string. |
| 993 |
The returned string will be truncated to needed_size. |
| 994 |
""" |
| 995 |
assert allocated_size >= needed_size |
| 996 |
if allocated_size != needed_size: |
| 997 |
from rpython.rtyper.lltypesystem.lloperation import llop |
| 998 |
if llop.shrink_array(lltype.Bool, gc_buf, needed_size): |
| 999 |
pass |
| 1000 |
else: |
| 1001 |
gc_buf = mallocfn(needed_size) |
| 1002 |
case_num = 2 |
| 1003 |
if case_num == 2: |
| 1004 |
copy_raw_to_string(raw_buf, gc_buf, 0, needed_size) |
| 1005 |
return hlstrtype(gc_buf) |
| 1006 |
|
| 1007 |
|
| 1008 |
@jit.dont_look_inside |
| 1009 |
def keep_buffer_alive_until_here(raw_buf, gc_buf, case_num): |
| 1010 |
""" |
| 1011 |
Keeps buffers alive or frees temporary buffers created by alloc_buffer. |
| 1012 |
This must be called after a call to alloc_buffer, usually in a |
| 1013 |
try/finally block. |
| 1014 |
""" |
| 1015 |
keepalive_until_here(gc_buf) |
| 1016 |
if case_num == 1: |
| 1017 |
rgc.unpin(gc_buf) |
| 1018 |
if case_num == 2: |
| 1019 |
lltype.free(raw_buf, flavor='raw') |
| 1020 |
|
| 1021 |
|
| 1022 |
@enforceargs(None, int) |
| 1023 |
def charp2strn(cp, maxlen): |
| 1024 |
size = 0 |
| 1025 |
while size < maxlen and cp[size] != lastchar: |
| 1026 |
size += 1 |
| 1027 |
return assert_str0(charpsize2str(cp, size)) |
| 1028 |
|
| 1029 |
|
| 1030 |
def charpsize2str(cp, size): |
| 1031 |
ll_str = mallocfn(size) |
| 1032 |
copy_raw_to_string(cp, ll_str, 0, size) |
| 1033 |
result = hlstrtype(ll_str) |
| 1034 |
assert result is not None |
| 1035 |
return result |
| 1036 |
charpsize2str._annenforceargs_ = [None, int] |
| 1037 |
|
| 1038 |
return (str2charp, free_charp, charp2str, |
| 1039 |
get_nonmovingbuffer_ll, free_nonmovingbuffer_ll, |
| 1040 |
get_nonmovingbuffer_ll_final_null, |
| 1041 |
alloc_buffer, str_from_buffer, keep_buffer_alive_until_here, |
| 1042 |
charp2strn, charpsize2str, str2chararray, str2rawmem, |
| 1043 |
) |
| 1044 |
|
| 1045 |
(str2charp, free_charp, charp2str, |
| 1046 |
get_nonmovingbuffer_ll, free_nonmovingbuffer_ll, |
| 1047 |
get_nonmovingbuffer_ll_final_null, |
| 1048 |
alloc_buffer, str_from_buffer, keep_buffer_alive_until_here, |
| 1049 |
charp2strn, charpsize2str, str2chararray, str2rawmem, |
| 1050 |
) = make_string_mappings(str) |
| 1051 |
|
| 1052 |
(unicode2wcharp, free_wcharp, wcharp2unicode, |
| 1053 |
get_nonmoving_unicodebuffer_ll, free_nonmoving_unicodebuffer_ll, __not_usable, |
| 1054 |
alloc_unicodebuffer, unicode_from_buffer, keep_unicodebuffer_alive_until_here, |
| 1055 |
wcharp2unicoden, wcharpsize2unicode, unicode2wchararray, unicode2rawmem, |
| 1056 |
) = make_string_mappings(unicode) |
| 1057 |
|
| 1058 |
|
| 1059 |
|
| 1060 |
def constcharp2str(cp): |
| 1061 |
""" |
| 1062 |
Like charp2str, but takes a CONST_CCHARP instead |
| 1063 |
""" |
| 1064 |
cp = cast(CCHARP, cp) |
| 1065 |
return charp2str(cp) |
| 1066 |
constcharp2str._annenforceargs_ = [lltype.SomePtr(CONST_CCHARP)] |
| 1067 |
|
| 1068 |
|
| 1069 |
def constcharpsize2str(cp, size): |
| 1070 |
""" |
| 1071 |
Like charpsize2str, but takes a CONST_CCHARP instead |
| 1072 |
""" |
| 1073 |
cp = cast(CCHARP, cp) |
| 1074 |
return charpsize2str(cp, size) |
| 1075 |
constcharpsize2str._annenforceargs_ = [lltype.SomePtr(CONST_CCHARP), int] |
| 1076 |
|
| 1077 |
def str2constcharp(s, track_allocation=True): |
| 1078 |
""" |
| 1079 |
Like str2charp, but returns a CONST_CCHARP instead |
| 1080 |
""" |
| 1081 |
cp = str2charp(s, track_allocation) |
| 1082 |
return cast(CONST_CCHARP, cp) |
| 1083 |
str2constcharp._annenforceargs_ = [str, bool] |
| 1084 |
|
| 1085 |
@not_rpython |
| 1086 |
def _deprecated_get_nonmovingbuffer(*args): |
| 1087 |
raise Exception( |
| 1088 |
"""The function rffi.get_nonmovingbuffer() has been removed because |
| 1089 |
it was unsafe. Use rffi.get_nonmovingbuffer_ll() instead. It returns |
| 1090 |
a 3-tuple instead of a 2-tuple, and all three arguments must be passed |
| 1091 |
to rffi.free_nonmovingbuffer_ll() (instead of the original string and the |
| 1092 |
two tuple items). Or else, use a high-level API like |
| 1093 |
'with rffi.scoped_nonmovingbuffer()'.""") |
| 1094 |
|
| 1095 |
get_nonmovingbuffer = _deprecated_get_nonmovingbuffer |
| 1096 |
get_nonmovingbuffer_final_null = _deprecated_get_nonmovingbuffer |
| 1097 |
free_nonmovingbuffer = _deprecated_get_nonmovingbuffer |
| 1098 |
|
| 1099 |
|
| 1100 |
def wcharpsize2utf8(w, size): |
| 1101 |
""" Helper to convert WCHARP pointer to utf8 in one go. |
| 1102 |
Equivalent to wcharpsize2unicode().encode("utf8") |
| 1103 |
Raises rutf8.OutOfRange if characters are outside range(0x110000)! |
| 1104 |
""" |
| 1105 |
from rpython.rlib import rutf8 |
| 1106 |
|
| 1107 |
s = StringBuilder(size) |
| 1108 |
for i in range(size): |
| 1109 |
rutf8.unichr_as_utf8_append(s, ord(w[i]), True) |
| 1110 |
return s.build() |
| 1111 |
|
| 1112 |
def wcharp2utf8(w): |
| 1113 |
""" |
| 1114 |
Raises rutf8.OutOfRange if characters are outside range(0x110000)! |
| 1115 |
""" |
| 1116 |
from rpython.rlib import rutf8 |
| 1117 |
|
| 1118 |
s = rutf8.Utf8StringBuilder() |
| 1119 |
i = 0 |
| 1120 |
while ord(w[i]): |
| 1121 |
s.append_code(ord(w[i])) |
| 1122 |
i += 1 |
| 1123 |
return s.build(), i |
| 1124 |
|
| 1125 |
def wcharp2utf8n(w, maxlen): |
| 1126 |
""" |
| 1127 |
Raises rutf8.OutOfRange if characters are outside range(0x110000)! |
| 1128 |
""" |
| 1129 |
from rpython.rlib import rutf8 |
| 1130 |
|
| 1131 |
s = rutf8.Utf8StringBuilder(maxlen) |
| 1132 |
i = 0 |
| 1133 |
while i < maxlen and ord(w[i]): |
| 1134 |
s.append_code(ord(w[i])) |
| 1135 |
i += 1 |
| 1136 |
return s.build(), i |
| 1137 |
|
| 1138 |
def utf82wcharp(utf8, utf8len, track_allocation=True): |
| 1139 |
from rpython.rlib import rutf8 |
| 1140 |
if not we_are_translated(): |
| 1141 |
assert utf8len == rutf8.codepoints_in_utf8(utf8) |
| 1142 |
|
| 1143 |
|
| 1144 |
|
| 1145 |
if track_allocation: |
| 1146 |
w = lltype.malloc(CWCHARP.TO, utf8len + 2, flavor='raw', track_allocation=True) |
| 1147 |
else: |
| 1148 |
w = lltype.malloc(CWCHARP.TO, utf8len + 2, flavor='raw', track_allocation=False) |
| 1149 |
index = 0 |
| 1150 |
for ch in rutf8.Utf8StringIterator(utf8): |
| 1151 |
w[index] = unichr(ch) |
| 1152 |
index += 1 |
| 1153 |
w[index] = unichr(0) |
| 1154 |
return w |
| 1155 |
utf82wcharp._annenforceargs_ = [str, int, bool] |
| 1156 |
|
| 1157 |
def utf82wcharp_ex(utf8, unilen, track_allocation=True): |
| 1158 |
from rpython.rlib import rutf8 |
| 1159 |
|
| 1160 |
|
| 1161 |
|
| 1162 |
wlen = 0 |
| 1163 |
for ch in rutf8.Utf8StringIterator(utf8): |
| 1164 |
if ch > 0xffff: |
| 1165 |
wlen += 1 |
| 1166 |
wlen += 1 |
| 1167 |
w = lltype.malloc(CWCHARP.TO, wlen + 3, flavor='raw', |
| 1168 |
track_allocation=track_allocation) |
| 1169 |
index = 0 |
| 1170 |
for ch in rutf8.Utf8StringIterator(utf8): |
| 1171 |
if ch > 0xffff: |
| 1172 |
w[index] = unichr(0xD800 | ((ch - 0x10000) >> 10)) |
| 1173 |
index += 1 |
| 1174 |
w[index] = unichr(0xDC00 | ((ch - 0x10000) & 0x3FF)) |
| 1175 |
else: |
| 1176 |
w[index] = unichr(ch) |
| 1177 |
index += 1 |
| 1178 |
w[index] = unichr(0) |
| 1179 |
assert wlen == index |
| 1180 |
return w |
| 1181 |
utf82wcharp_ex._annenforceargs_ = [str, int, bool] |
| 1182 |
|
| 1183 |
|
| 1184 |
CCHARPP = lltype.Ptr(lltype.Array(CCHARP, hints={'nolength': True})) |
| 1185 |
CWCHARPP = lltype.Ptr(lltype.Array(CWCHARP, hints={'nolength': True})) |
| 1186 |
|
| 1187 |
def liststr2charpp(l): |
| 1188 |
""" list[str] -> char**, NULL terminated |
| 1189 |
""" |
| 1190 |
array = lltype.malloc(CCHARPP.TO, len(l) + 1, flavor='raw') |
| 1191 |
for i in range(len(l)): |
| 1192 |
array[i] = str2charp(l[i]) |
| 1193 |
array[len(l)] = lltype.nullptr(CCHARP.TO) |
| 1194 |
return array |
| 1195 |
liststr2charpp._annenforceargs_ = [[annmodel.s_Str0]] |
| 1196 |
|
| 1197 |
ll_liststr2charpp = func_with_new_name(liststr2charpp, 'll_liststr2charpp') |
| 1198 |
|
| 1199 |
def free_charpp(ref): |
| 1200 |
""" frees list of char**, NULL terminated |
| 1201 |
""" |
| 1202 |
i = 0 |
| 1203 |
while ref[i]: |
| 1204 |
free_charp(ref[i]) |
| 1205 |
i += 1 |
| 1206 |
lltype.free(ref, flavor='raw') |
| 1207 |
|
| 1208 |
def charpp2liststr(p): |
| 1209 |
""" char** NULL terminated -> list[str]. No freeing is done. |
| 1210 |
""" |
| 1211 |
result = [] |
| 1212 |
i = 0 |
| 1213 |
while p[i]: |
| 1214 |
result.append(charp2str(p[i])) |
| 1215 |
i += 1 |
| 1216 |
return result |
| 1217 |
|
| 1218 |
cast = ll2ctypes.force_cast |
| 1219 |
|
| 1220 |
ptradd = ll2ctypes.force_ptradd |
| 1221 |
|
| 1222 |
|
| 1223 |
def size_and_sign(tp): |
| 1224 |
size = sizeof(tp) |
| 1225 |
try: |
| 1226 |
unsigned = not tp._type.SIGNED |
| 1227 |
except AttributeError: |
| 1228 |
if not isinstance(tp, lltype.Primitive): |
| 1229 |
unsigned = False |
| 1230 |
elif tp in (lltype.Signed, FLOAT, DOUBLE, LONGDOUBLE, llmemory.Address): |
| 1231 |
unsigned = False |
| 1232 |
elif tp in (lltype.Char, lltype.UniChar, lltype.Bool): |
| 1233 |
unsigned = True |
| 1234 |
else: |
| 1235 |
raise AssertionError("size_and_sign(%r)" % (tp,)) |
| 1236 |
return size, unsigned |
| 1237 |
|
| 1238 |
def sizeof(tp): |
| 1239 |
"""Similar to llmemory.sizeof() but tries hard to return a integer |
| 1240 |
instead of a symbolic value. |
| 1241 |
""" |
| 1242 |
if isinstance(tp, lltype.Typedef): |
| 1243 |
tp = tp.OF |
| 1244 |
if isinstance(tp, lltype.FixedSizeArray): |
| 1245 |
return sizeof(tp.OF) * tp.length |
| 1246 |
if isinstance(tp, lltype.Struct): |
| 1247 |
|
| 1248 |
size = tp._hints.get('size') |
| 1249 |
if size is None: |
| 1250 |
size = llmemory.sizeof(tp) |
| 1251 |
return size |
| 1252 |
if (tp is lltype.Signed or isinstance(tp, lltype.Ptr) |
| 1253 |
or tp is llmemory.Address): |
| 1254 |
return LONG_BIT/8 |
| 1255 |
if tp is lltype.Char or tp is lltype.Bool: |
| 1256 |
return 1 |
| 1257 |
if tp is lltype.UniChar: |
| 1258 |
return r_wchar_t.BITS/8 |
| 1259 |
if tp is lltype.Float: |
| 1260 |
return 8 |
| 1261 |
if tp is lltype.SingleFloat: |
| 1262 |
return 4 |
| 1263 |
if tp is lltype.LongFloat: |
| 1264 |
|
| 1265 |
return sizeof_c_type("long double") |
| 1266 |
assert isinstance(tp, lltype.Number) |
| 1267 |
return tp._type.BITS/8 |
| 1268 |
sizeof._annspecialcase_ = 'specialize:memo' |
| 1269 |
|
| 1270 |
def offsetof(STRUCT, fieldname): |
| 1271 |
"""Similar to llmemory.offsetof() but tries hard to return a integer |
| 1272 |
instead of a symbolic value. |
| 1273 |
""" |
| 1274 |
|
| 1275 |
fieldoffsets = STRUCT._hints.get('fieldoffsets') |
| 1276 |
if fieldoffsets is not None: |
| 1277 |
|
| 1278 |
for index, name in enumerate(STRUCT._names): |
| 1279 |
if name == fieldname: |
| 1280 |
return fieldoffsets[index] |
| 1281 |
|
| 1282 |
return llmemory.offsetof(STRUCT, fieldname) |
| 1283 |
offsetof._annspecialcase_ = 'specialize:memo' |
| 1284 |
|
| 1285 |
|
| 1286 |
assert maxint == (1 << (8 * sizeof(llmemory.Address) - 1)) - 1, ( |
| 1287 |
"Mixed configuration of the word size of the machine:\n\t" |
| 1288 |
"the underlying Python was compiled with maxint=%d,\n\t" |
| 1289 |
"but the C compiler says that 'void *' is %d bytes" % ( |
| 1290 |
maxint, sizeof(llmemory.Address))) |
| 1291 |
assert sizeof(lltype.Signed) == sizeof(llmemory.Address), ( |
| 1292 |
"Bad configuration: we should manage to get lltype.Signed " |
| 1293 |
"be an integer type of the same size as llmemory.Address, " |
| 1294 |
"but we got %s != %s" % (sizeof(lltype.Signed), |
| 1295 |
sizeof(llmemory.Address))) |
| 1296 |
|
| 1297 |
|
| 1298 |
|
| 1299 |
def make(STRUCT, **fields): |
| 1300 |
""" Malloc a structure and populate it's fields |
| 1301 |
""" |
| 1302 |
ptr = lltype.malloc(STRUCT, flavor='raw') |
| 1303 |
for name, value in fields.items(): |
| 1304 |
setattr(ptr, name, value) |
| 1305 |
return ptr |
| 1306 |
|
| 1307 |
class MakeEntry(ExtRegistryEntry): |
| 1308 |
_about_ = make |
| 1309 |
|
| 1310 |
def compute_result_annotation(self, s_type, **s_fields): |
| 1311 |
TP = s_type.const |
| 1312 |
if not isinstance(TP, lltype.Struct): |
| 1313 |
raise TypeError("make called with %s instead of Struct as first argument" % TP) |
| 1314 |
return SomePtr(lltype.Ptr(TP)) |
| 1315 |
|
| 1316 |
def specialize_call(self, hop, **fields): |
| 1317 |
assert hop.args_s[0].is_constant() |
| 1318 |
vlist = [hop.inputarg(lltype.Void, arg=0)] |
| 1319 |
flags = {'flavor':'raw'} |
| 1320 |
vlist.append(hop.inputconst(lltype.Void, flags)) |
| 1321 |
hop.has_implicit_exception(MemoryError) |
| 1322 |
hop.exception_is_here() |
| 1323 |
v_ptr = hop.genop('malloc', vlist, resulttype=hop.r_result.lowleveltype) |
| 1324 |
for name, i in fields.items(): |
| 1325 |
name = name[2:] |
| 1326 |
v_arg = hop.inputarg(hop.args_r[i], arg=i) |
| 1327 |
v_name = hop.inputconst(lltype.Void, name) |
| 1328 |
hop.genop('setfield', [v_ptr, v_name, v_arg]) |
| 1329 |
return v_ptr |
| 1330 |
|
| 1331 |
|
| 1332 |
def structcopy(pdst, psrc): |
| 1333 |
"""Copy all the fields of the structure given by 'psrc' |
| 1334 |
into the structure given by 'pdst'. |
| 1335 |
""" |
| 1336 |
copy_fn = _get_structcopy_fn(lltype.typeOf(pdst), lltype.typeOf(psrc)) |
| 1337 |
copy_fn(pdst, psrc) |
| 1338 |
structcopy._annspecialcase_ = 'specialize:ll' |
| 1339 |
|
| 1340 |
def _get_structcopy_fn(PDST, PSRC): |
| 1341 |
assert PDST == PSRC |
| 1342 |
if isinstance(PDST.TO, lltype.Struct): |
| 1343 |
STRUCT = PDST.TO |
| 1344 |
padding = STRUCT._hints.get('padding', ()) |
| 1345 |
fields = [(name, STRUCT._flds[name]) for name in STRUCT._names |
| 1346 |
if name not in padding] |
| 1347 |
unrollfields = unrolling_iterable(fields) |
| 1348 |
|
| 1349 |
def copyfn(pdst, psrc): |
| 1350 |
for name, TYPE in unrollfields: |
| 1351 |
if isinstance(TYPE, lltype.ContainerType): |
| 1352 |
structcopy(getattr(pdst, name), getattr(psrc, name)) |
| 1353 |
else: |
| 1354 |
setattr(pdst, name, getattr(psrc, name)) |
| 1355 |
|
| 1356 |
return copyfn |
| 1357 |
else: |
| 1358 |
raise NotImplementedError('structcopy: type %r' % (PDST.TO,)) |
| 1359 |
_get_structcopy_fn._annspecialcase_ = 'specialize:memo' |
| 1360 |
|
| 1361 |
|
| 1362 |
def setintfield(pdst, fieldname, value): |
| 1363 |
"""Maybe temporary: a helper to set an integer field into a structure, |
| 1364 |
transparently casting between the various integer types. |
| 1365 |
""" |
| 1366 |
STRUCT = lltype.typeOf(pdst).TO |
| 1367 |
TSRC = lltype.typeOf(value) |
| 1368 |
TDST = getattr(STRUCT, fieldname) |
| 1369 |
assert isinstance(TSRC, lltype.Number) |
| 1370 |
assert isinstance(TDST, lltype.Number) |
| 1371 |
setattr(pdst, fieldname, cast(TDST, value)) |
| 1372 |
setintfield._annspecialcase_ = 'specialize:ll_and_arg(1)' |
| 1373 |
|
| 1374 |
def getintfield(pdst, fieldname): |
| 1375 |
"""As temporary as previous: get integer from a field in structure, |
| 1376 |
casting it to lltype.Signed |
| 1377 |
""" |
| 1378 |
return cast(lltype.Signed, getattr(pdst, fieldname)) |
| 1379 |
getintfield._annspecialcase_ = 'specialize:ll_and_arg(1)' |
| 1380 |
|
| 1381 |
class scoped_str2charp: |
| 1382 |
def __init__(self, value): |
| 1383 |
if value is not None: |
| 1384 |
self.buf = str2charp(value) |
| 1385 |
else: |
| 1386 |
self.buf = lltype.nullptr(CCHARP.TO) |
| 1387 |
__init__._annenforceargs_ = [None, annmodel.SomeString(can_be_None=True)] |
| 1388 |
def __enter__(self): |
| 1389 |
return self.buf |
| 1390 |
def __exit__(self, *args): |
| 1391 |
if self.buf: |
| 1392 |
free_charp(self.buf) |
| 1393 |
|
| 1394 |
|
| 1395 |
class scoped_unicode2wcharp: |
| 1396 |
def __init__(self, value): |
| 1397 |
if value is not None: |
| 1398 |
self.buf = unicode2wcharp(value) |
| 1399 |
else: |
| 1400 |
self.buf = lltype.nullptr(CWCHARP.TO) |
| 1401 |
__init__._annenforceargs_ = [None, |
| 1402 |
annmodel.SomeUnicodeString(can_be_None=True)] |
| 1403 |
def __enter__(self): |
| 1404 |
return self.buf |
| 1405 |
def __exit__(self, *args): |
| 1406 |
if self.buf: |
| 1407 |
free_wcharp(self.buf) |
| 1408 |
|
| 1409 |
class scoped_utf82wcharp: |
| 1410 |
def __init__(self, value, unicode_len=-1): |
| 1411 |
from rpython.rlib import rutf8 |
| 1412 |
if value is None: |
| 1413 |
self.buf = lltype.nullptr(CWCHARP.TO) |
| 1414 |
elif unicode_len < 0: |
| 1415 |
self.buf = utf82wcharp(value, rutf8.codepoints_in_utf8(value)) |
| 1416 |
else: |
| 1417 |
self.buf = utf82wcharp(value, unicode_len) |
| 1418 |
def __enter__(self): |
| 1419 |
return self.buf |
| 1420 |
def __exit__(self, *args): |
| 1421 |
if self.buf: |
| 1422 |
free_wcharp(self.buf) |
| 1423 |
|
| 1424 |
|
| 1425 |
class scoped_nonmovingbuffer: |
| 1426 |
|
| 1427 |
def __init__(self, data): |
| 1428 |
self.buf, self.llobj, self.flag = get_nonmovingbuffer_ll(data) |
| 1429 |
__init__._annenforceargs_ = [None, annmodel.SomeString(can_be_None=False)] |
| 1430 |
|
| 1431 |
def __enter__(self): |
| 1432 |
return self.buf |
| 1433 |
def __exit__(self, *args): |
| 1434 |
free_nonmovingbuffer_ll(self.buf, self.llobj, self.flag) |
| 1435 |
__init__._always_inline_ = 'try' |
| 1436 |
__enter__._always_inline_ = 'try' |
| 1437 |
__exit__._always_inline_ = 'try' |
| 1438 |
|
| 1439 |
class scoped_view_charp: |
| 1440 |
"""Returns a 'char *' that (tries to) point inside the given RPython |
| 1441 |
string (which must not be None). You can replace scoped_str2charp() |
| 1442 |
with scoped_view_charp() in all places that guarantee that the |
| 1443 |
content of the 'char[]' array will not be modified. |
| 1444 |
""" |
| 1445 |
def __init__(self, data): |
| 1446 |
self.buf, self.llobj, self.flag = get_nonmovingbuffer_ll_final_null( |
| 1447 |
data) |
| 1448 |
__init__._annenforceargs_ = [None, annmodel.SomeString(can_be_None=False)] |
| 1449 |
def __enter__(self): |
| 1450 |
return self.buf |
| 1451 |
def __exit__(self, *args): |
| 1452 |
free_nonmovingbuffer_ll(self.buf, self.llobj, self.flag) |
| 1453 |
__init__._always_inline_ = 'try' |
| 1454 |
__enter__._always_inline_ = 'try' |
| 1455 |
__exit__._always_inline_ = 'try' |
| 1456 |
|
| 1457 |
class scoped_nonmoving_unicodebuffer: |
| 1458 |
def __init__(self, data): |
| 1459 |
self.buf, self.llobj, self.flag = get_nonmoving_unicodebuffer_ll(data) |
| 1460 |
def __enter__(self): |
| 1461 |
return self.buf |
| 1462 |
def __exit__(self, *args): |
| 1463 |
free_nonmoving_unicodebuffer_ll(self.buf, self.llobj, self.flag) |
| 1464 |
__init__._always_inline_ = 'try' |
| 1465 |
__enter__._always_inline_ = 'try' |
| 1466 |
__exit__._always_inline_ = 'try' |
| 1467 |
|
| 1468 |
class scoped_alloc_buffer: |
| 1469 |
def __init__(self, size): |
| 1470 |
self.size = size |
| 1471 |
def __enter__(self): |
| 1472 |
self.raw, self.gc_buf, self.case_num = alloc_buffer(self.size) |
| 1473 |
return self |
| 1474 |
def __exit__(self, *args): |
| 1475 |
keep_buffer_alive_until_here(self.raw, self.gc_buf, self.case_num) |
| 1476 |
def str(self, length): |
| 1477 |
return str_from_buffer(self.raw, self.gc_buf, self.case_num, |
| 1478 |
self.size, length) |
| 1479 |
|
| 1480 |
class scoped_alloc_unicodebuffer: |
| 1481 |
def __init__(self, size): |
| 1482 |
self.size = size |
| 1483 |
def __enter__(self): |
| 1484 |
self.raw, self.gc_buf, self.case_num = alloc_unicodebuffer(self.size) |
| 1485 |
return self |
| 1486 |
def __exit__(self, *args): |
| 1487 |
keep_unicodebuffer_alive_until_here(self.raw, self.gc_buf, self.case_num) |
| 1488 |
def str(self, length): |
| 1489 |
return unicode_from_buffer(self.raw, self.gc_buf, self.case_num, |
| 1490 |
self.size, length) |
| 1491 |
|
| 1492 |
class scoped_alloc_utf8buffer: |
| 1493 |
def __init__(self, size): |
| 1494 |
self.size = size |
| 1495 |
def __enter__(self): |
| 1496 |
self.raw, self.gc_buf, self.case_num = alloc_unicodebuffer(self.size) |
| 1497 |
return self |
| 1498 |
def __exit__(self, *args): |
| 1499 |
keep_unicodebuffer_alive_until_here(self.raw, self.gc_buf, self.case_num) |
| 1500 |
def str(self, length): |
| 1501 |
|
| 1502 |
return utf8_from_buffer(self.raw, self.gc_buf, self.case_num, |
| 1503 |
self.size, length) |
| 1504 |
|
| 1505 |
|
| 1506 |
|
| 1507 |
|
| 1508 |
c_memcpy = llexternal("memcpy", |
| 1509 |
[VOIDP, CONST_VOIDP, SIZE_T], |
| 1510 |
lltype.Void, |
| 1511 |
releasegil=False, |
| 1512 |
calling_conv='c', |
| 1513 |
) |
| 1514 |
c_memset = llexternal("memset", |
| 1515 |
[VOIDP, lltype.Signed, SIZE_T], |
| 1516 |
lltype.Void, |
| 1517 |
releasegil=False, |
| 1518 |
calling_conv='c', |
| 1519 |
) |
| 1520 |
|
| 1521 |
|
| 1522 |
|
| 1523 |
TEST_RAW_ADDR_KEEP_ALIVE = {} |
| 1524 |
|
| 1525 |
@jit.dont_look_inside |
| 1526 |
def get_raw_address_of_string(string): |
| 1527 |
"""Returns a 'char *' that is valid as long as the rpython string object is alive. |
| 1528 |
Two calls to to this function, given the same string parameter, |
| 1529 |
are guaranteed to return the same pointer. |
| 1530 |
""" |
| 1531 |
assert isinstance(string, str) |
| 1532 |
from rpython.rtyper.annlowlevel import llstr |
| 1533 |
from rpython.rtyper.lltypesystem.rstr import STR |
| 1534 |
from rpython.rtyper.lltypesystem import llmemory |
| 1535 |
from rpython.rlib import rgc |
| 1536 |
|
| 1537 |
if we_are_translated(): |
| 1538 |
if rgc.must_split_gc_address_space(): |
| 1539 |
return _get_raw_address_buf_from_string(string) |
| 1540 |
if rgc.can_move(string): |
| 1541 |
string = rgc.move_out_of_nursery(string) |
| 1542 |
if rgc.can_move(string): |
| 1543 |
return _get_raw_address_buf_from_string(string) |
| 1544 |
|
| 1545 |
|
| 1546 |
lldata = llstr(string) |
| 1547 |
data_start = (llmemory.cast_ptr_to_adr(lldata) + |
| 1548 |
offsetof(STR, 'chars') + |
| 1549 |
llmemory.itemoffsetof(STR.chars, 0)) |
| 1550 |
data_start = cast(CCHARP, data_start) |
| 1551 |
data_start[len(string)] = '\x00' |
| 1552 |
return data_start |
| 1553 |
else: |
| 1554 |
global TEST_RAW_ADDR_KEEP_ALIVE |
| 1555 |
if string in TEST_RAW_ADDR_KEEP_ALIVE: |
| 1556 |
return TEST_RAW_ADDR_KEEP_ALIVE[string] |
| 1557 |
result = str2charp(string, track_allocation=False) |
| 1558 |
TEST_RAW_ADDR_KEEP_ALIVE[string] = result |
| 1559 |
return result |
| 1560 |
|
| 1561 |
class _StrFinalizerQueue(rgc.FinalizerQueue): |
| 1562 |
Class = None |
| 1563 |
print_debugging = False |
| 1564 |
def finalizer_trigger(self): |
| 1565 |
from rpython.rtyper.annlowlevel import hlstr |
| 1566 |
from rpython.rtyper.lltypesystem import rstr |
| 1567 |
from rpython.rlib import objectmodel |
| 1568 |
while True: |
| 1569 |
gcptr = self.next_dead() |
| 1570 |
if not gcptr: |
| 1571 |
break |
| 1572 |
ll_string = lltype.cast_opaque_ptr(lltype.Ptr(rstr.STR), gcptr) |
| 1573 |
string = hlstr(ll_string) |
| 1574 |
key = objectmodel.compute_unique_id(string) |
| 1575 |
ptr = self.raw_copies.get(key, lltype.nullptr(CCHARP.TO)) |
| 1576 |
if ptr: |
| 1577 |
if self.print_debugging: |
| 1578 |
from rpython.rlib.debug import debug_print |
| 1579 |
debug_print("freeing str [", ptr, "]") |
| 1580 |
free_charp(ptr, track_allocation=False) |
| 1581 |
_fq_addr_from_string = _StrFinalizerQueue() |
| 1582 |
_fq_addr_from_string.raw_copies = {} |
| 1583 |
|
| 1584 |
def _get_raw_address_buf_from_string(string): |
| 1585 |
|
| 1586 |
|
| 1587 |
from rpython.rtyper.annlowlevel import llstr |
| 1588 |
from rpython.rlib import objectmodel |
| 1589 |
key = objectmodel.compute_unique_id(string) |
| 1590 |
try: |
| 1591 |
ptr = _fq_addr_from_string.raw_copies[key] |
| 1592 |
except KeyError: |
| 1593 |
ptr = str2charp(string, track_allocation=False) |
| 1594 |
_fq_addr_from_string.raw_copies[key] = ptr |
| 1595 |
ll_string = llstr(string) |
| 1596 |
gcptr = lltype.cast_opaque_ptr(llmemory.GCREF, ll_string) |
| 1597 |
_fq_addr_from_string.register_finalizer(gcptr) |
| 1598 |
return ptr |