| 1 |
import sys |
| 2 |
from pypy.interpreter.error import oefmt |
| 3 |
from pypy.interpreter.baseobjspace import W_Root |
| 4 |
from pypy.interpreter.typedef import TypeDef, GetSetProperty, ClassAttr |
| 5 |
from pypy.interpreter.gateway import interp2app, unwrap_spec, WrappedDefault |
| 6 |
from rpython.rlib import jit, rgc |
| 7 |
from rpython.rtyper.lltypesystem import lltype, rffi |
| 8 |
|
| 9 |
from pypy.module._cffi_backend.moduledef import get_dict_rtld_constants |
| 10 |
from pypy.module._cffi_backend import parse_c_type, realize_c_type |
| 11 |
from pypy.module._cffi_backend import newtype, cerrno, ccallback, ctypearray |
| 12 |
from pypy.module._cffi_backend import ctypestruct, ctypeptr, handle |
| 13 |
from pypy.module._cffi_backend import cbuffer, func, wrapper, call_python |
| 14 |
from pypy.module._cffi_backend import cffi_opcode, allocator |
| 15 |
from pypy.module._cffi_backend.ctypeobj import W_CType |
| 16 |
from pypy.module._cffi_backend.cdataobj import W_CData |
| 17 |
|
| 18 |
|
| 19 |
ACCEPT_STRING = 1 |
| 20 |
ACCEPT_CTYPE = 2 |
| 21 |
ACCEPT_CDATA = 4 |
| 22 |
ACCEPT_ALL = ACCEPT_STRING | ACCEPT_CTYPE | ACCEPT_CDATA |
| 23 |
CONSIDER_FN_AS_FNPTR = 8 |
| 24 |
|
| 25 |
|
| 26 |
def get_ffi_error(space): |
| 27 |
w_ffitype = space.gettypefor(W_FFIObject) |
| 28 |
return w_ffitype.getdictvalue(space, 'error') |
| 29 |
|
| 30 |
|
| 31 |
class FreeCtxObj(object): |
| 32 |
def __init__(self, ctxobj): |
| 33 |
self.ctxobj = ctxobj |
| 34 |
self.free_mems = [] |
| 35 |
|
| 36 |
def __del__(self): |
| 37 |
ctxobj = self.ctxobj |
| 38 |
free_mems = self.free_mems |
| 39 |
parse_c_type.free_ctxobj(ctxobj) |
| 40 |
i = len(free_mems) - 1 |
| 41 |
while i >= 0: |
| 42 |
lltype.free(free_mems[i], flavor='raw') |
| 43 |
i -= 1 |
| 44 |
|
| 45 |
|
| 46 |
class W_FFIObject(W_Root): |
| 47 |
ACCEPT_STRING = ACCEPT_STRING |
| 48 |
ACCEPT_CTYPE = ACCEPT_CTYPE |
| 49 |
ACCEPT_CDATA = ACCEPT_CDATA |
| 50 |
|
| 51 |
w_gc_wref_remove = None |
| 52 |
w_init_once_cache = None |
| 53 |
jit_init_once_cache = None |
| 54 |
|
| 55 |
@jit.dont_look_inside |
| 56 |
def __init__(self, space, src_ctx): |
| 57 |
self.space = space |
| 58 |
self.types_dict = {} |
| 59 |
self.ctxobj = parse_c_type.allocate_ctxobj(src_ctx) |
| 60 |
self.is_static = bool(src_ctx) |
| 61 |
self.is_nonempty = bool(src_ctx) |
| 62 |
self._finalizer = FreeCtxObj(self.ctxobj) |
| 63 |
if src_ctx: |
| 64 |
self.cached_types = [None] * parse_c_type.get_num_types(src_ctx) |
| 65 |
else: |
| 66 |
self.cached_types = None |
| 67 |
self.w_FFIError = get_ffi_error(space) |
| 68 |
|
| 69 |
|
| 70 |
|
| 71 |
self.included_ffis_libs = [] |
| 72 |
|
| 73 |
def fetch_int_constant(self, name): |
| 74 |
index = parse_c_type.search_in_globals(self.ctxobj.ctx, name) |
| 75 |
if index >= 0: |
| 76 |
g = rffi.cast(rffi.CArrayPtr(parse_c_type.GLOBAL_S), self.ctxobj.ctx.c_globals)[index] |
| 77 |
op = realize_c_type.getop(g.c_type_op) |
| 78 |
if (op == cffi_opcode.OP_CONSTANT_INT or |
| 79 |
op == cffi_opcode.OP_ENUM): |
| 80 |
return realize_c_type.realize_global_int(self, g, index) |
| 81 |
raise oefmt(self.w_FFIError, |
| 82 |
"function, global variable or non-integer constant " |
| 83 |
"'%s' must be fetched from its original 'lib' " |
| 84 |
"object", name) |
| 85 |
|
| 86 |
for ffi1, _ in self.included_ffis_libs: |
| 87 |
w_result = ffi1.fetch_int_constant(name) |
| 88 |
if w_result is not None: |
| 89 |
return w_result |
| 90 |
return None |
| 91 |
|
| 92 |
@jit.elidable_promote() |
| 93 |
def get_string_to_type(self, string, consider_fn_as_fnptr): |
| 94 |
x = self.types_dict[string] |
| 95 |
if isinstance(x, W_CType): |
| 96 |
return x |
| 97 |
else: |
| 98 |
assert isinstance(x, realize_c_type.W_RawFuncType) |
| 99 |
if consider_fn_as_fnptr: |
| 100 |
return x.unwrap_as_fnptr_in_elidable() |
| 101 |
else: |
| 102 |
raise KeyError |
| 103 |
|
| 104 |
def _ffi_bad_type(self, input_text): |
| 105 |
info = self.ctxobj.info |
| 106 |
errmsg = rffi.constcharp2str(info.c_error_message) |
| 107 |
if len(input_text) > 500: |
| 108 |
raise oefmt(self.w_FFIError, "%s", errmsg) |
| 109 |
printable_text = ['?'] * len(input_text) |
| 110 |
for i in range(len(input_text)): |
| 111 |
if ' ' <= input_text[i] < '\x7f': |
| 112 |
printable_text[i] = input_text[i] |
| 113 |
elif input_text[i] == '\t' or input_text[i] == '\n': |
| 114 |
printable_text[i] = ' ' |
| 115 |
num_spaces = rffi.getintfield(info, 'c_error_location') |
| 116 |
raise oefmt(self.w_FFIError, "%s\n%s\n%s^", |
| 117 |
rffi.constcharp2str(info.c_error_message), |
| 118 |
''.join(printable_text), |
| 119 |
" " * num_spaces) |
| 120 |
|
| 121 |
@jit.dont_look_inside |
| 122 |
def parse_string_to_type(self, string, consider_fn_as_fnptr): |
| 123 |
|
| 124 |
|
| 125 |
|
| 126 |
|
| 127 |
|
| 128 |
try: |
| 129 |
x = self.types_dict[string] |
| 130 |
except KeyError: |
| 131 |
info = self.ctxobj.info |
| 132 |
index = parse_c_type.parse_c_type(info, string) |
| 133 |
if index < 0: |
| 134 |
raise self._ffi_bad_type(string) |
| 135 |
x = realize_c_type.realize_c_type_or_func( |
| 136 |
self, self.ctxobj.info.c_output, index) |
| 137 |
assert x is not None |
| 138 |
if isinstance(x, realize_c_type.W_RawFuncType): |
| 139 |
x.unwrap_as_fnptr(self) |
| 140 |
self.types_dict[string] = x |
| 141 |
|
| 142 |
if isinstance(x, W_CType): |
| 143 |
return x |
| 144 |
else: |
| 145 |
assert isinstance(x, realize_c_type.W_RawFuncType) |
| 146 |
if consider_fn_as_fnptr: |
| 147 |
return x.unwrap_as_fnptr_in_elidable() |
| 148 |
else: |
| 149 |
raise x.unexpected_fn_type(self) |
| 150 |
|
| 151 |
def ffi_type(self, w_x, accept): |
| 152 |
space = self.space |
| 153 |
if (accept & ACCEPT_STRING) and ( |
| 154 |
space.isinstance_w(w_x, space.w_text)): |
| 155 |
string = space.text_w(w_x) |
| 156 |
consider_fn_as_fnptr = (accept & CONSIDER_FN_AS_FNPTR) != 0 |
| 157 |
if jit.isconstant(string): |
| 158 |
try: |
| 159 |
return self.get_string_to_type(string, consider_fn_as_fnptr) |
| 160 |
except KeyError: |
| 161 |
pass |
| 162 |
return self.parse_string_to_type(string, consider_fn_as_fnptr) |
| 163 |
if (accept & ACCEPT_CTYPE) and isinstance(w_x, W_CType): |
| 164 |
return w_x |
| 165 |
if (accept & ACCEPT_CDATA) and isinstance(w_x, W_CData): |
| 166 |
return w_x.ctype |
| 167 |
|
| 168 |
m1 = "string" if accept & ACCEPT_STRING else "" |
| 169 |
m2 = "ctype object" if accept & ACCEPT_CTYPE else "" |
| 170 |
m3 = "cdata object" if accept & ACCEPT_CDATA else "" |
| 171 |
s12 = " or " if m1 and (m2 or m3) else "" |
| 172 |
s23 = " or " if m2 and m3 else "" |
| 173 |
raise oefmt(space.w_TypeError, "expected a %s%s%s%s%s, got '%T'", |
| 174 |
m1, s12, m2, s23, m3, w_x) |
| 175 |
|
| 176 |
|
| 177 |
@unwrap_spec(module_name='text', _version=int, _types='bytes') |
| 178 |
def descr_init(self, module_name='?', _version=-1, _types='', |
| 179 |
w__globals=None, w__struct_unions=None, w__enums=None, |
| 180 |
w__typenames=None, w__includes=None): |
| 181 |
from pypy.module._cffi_backend import cdlopen |
| 182 |
|
| 183 |
space = self.space |
| 184 |
if self.is_nonempty: |
| 185 |
raise oefmt(space.w_ValueError, |
| 186 |
"cannot call FFI.__init__() more than once") |
| 187 |
self.is_nonempty = True |
| 188 |
|
| 189 |
cdlopen.ffiobj_init(self, module_name, _version, _types, |
| 190 |
w__globals, w__struct_unions, w__enums, |
| 191 |
w__typenames, w__includes) |
| 192 |
|
| 193 |
|
| 194 |
doc_errno = "the value of 'errno' from/to the C calls" |
| 195 |
|
| 196 |
def get_errno(self, space): |
| 197 |
return cerrno.get_errno(space) |
| 198 |
|
| 199 |
def set_errno(self, space, errno): |
| 200 |
cerrno.set_errno(space, space.c_int_w(errno)) |
| 201 |
|
| 202 |
|
| 203 |
def _more_addressof(self, args_w, w_ctype): |
| 204 |
|
| 205 |
offset = 0 |
| 206 |
for i in range(len(args_w)): |
| 207 |
w_ctype, ofs1 = w_ctype.direct_typeoffsetof(args_w[i], i > 0) |
| 208 |
offset += ofs1 |
| 209 |
return w_ctype, offset |
| 210 |
|
| 211 |
def descr_addressof(self, w_arg, args_w): |
| 212 |
"""\ |
| 213 |
Limited equivalent to the '&' operator in C: |
| 214 |
|
| 215 |
1. ffi.addressof(<cdata 'struct-or-union'>) returns a cdata that is a |
| 216 |
pointer to this struct or union. |
| 217 |
|
| 218 |
2. ffi.addressof(<cdata>, field-or-index...) returns the address of a |
| 219 |
field or array item inside the given structure or array, recursively |
| 220 |
in case of nested structures or arrays. |
| 221 |
|
| 222 |
3. ffi.addressof(<library>, "name") returns the address of the named |
| 223 |
function or global variable.""" |
| 224 |
|
| 225 |
from pypy.module._cffi_backend.lib_obj import W_LibObject |
| 226 |
space = self.space |
| 227 |
if isinstance(w_arg, W_LibObject) and len(args_w) == 1: |
| 228 |
|
| 229 |
return w_arg.address_of_func_or_global_var(space.text_w(args_w[0])) |
| 230 |
|
| 231 |
w_ctype = self.ffi_type(w_arg, ACCEPT_CDATA) |
| 232 |
if len(args_w) == 0: |
| 233 |
|
| 234 |
if (not isinstance(w_ctype, ctypestruct.W_CTypeStructOrUnion) and |
| 235 |
not isinstance(w_ctype, ctypearray.W_CTypeArray)): |
| 236 |
raise oefmt(space.w_TypeError, |
| 237 |
"expected a cdata struct/union/array object") |
| 238 |
offset = 0 |
| 239 |
else: |
| 240 |
|
| 241 |
if (not isinstance(w_ctype, ctypestruct.W_CTypeStructOrUnion) and |
| 242 |
not isinstance(w_ctype, ctypearray.W_CTypeArray) and |
| 243 |
not isinstance(w_ctype, ctypeptr.W_CTypePointer)): |
| 244 |
raise oefmt(space.w_TypeError, |
| 245 |
"expected a cdata struct/union/array/pointer object") |
| 246 |
if len(args_w) == 1: |
| 247 |
w_ctype, offset = w_ctype.direct_typeoffsetof(args_w[0], False) |
| 248 |
else: |
| 249 |
w_ctype, offset = self._more_addressof(args_w, w_ctype) |
| 250 |
|
| 251 |
assert isinstance(w_arg, W_CData) |
| 252 |
cdata = w_arg.unsafe_escaping_ptr() |
| 253 |
cdata = rffi.ptradd(cdata, offset) |
| 254 |
w_ctypeptr = newtype.new_pointer_type(space, w_ctype) |
| 255 |
return W_CData(space, cdata, w_ctypeptr) |
| 256 |
|
| 257 |
|
| 258 |
def descr_alignof(self, w_arg): |
| 259 |
"""\ |
| 260 |
Return the natural alignment size in bytes of the argument. |
| 261 |
It can be a string naming a C type, or a 'cdata' instance.""" |
| 262 |
|
| 263 |
w_ctype = self.ffi_type(w_arg, ACCEPT_ALL) |
| 264 |
align = w_ctype.alignof() |
| 265 |
return self.space.newint(align) |
| 266 |
|
| 267 |
|
| 268 |
@unwrap_spec(w_name=WrappedDefault(None), |
| 269 |
w_error=WrappedDefault(None), |
| 270 |
w_onerror=WrappedDefault(None)) |
| 271 |
def descr_def_extern(self, w_name, w_error, w_onerror): |
| 272 |
"""\ |
| 273 |
A decorator. Attaches the decorated Python function to the C code |
| 274 |
generated for the 'extern "Python" function of the same name. |
| 275 |
Calling the C function will then invoke the Python function. |
| 276 |
|
| 277 |
Optional arguments: 'name' is the name of the C function, if |
| 278 |
different from the Python function; and 'error' and 'onerror' |
| 279 |
handle what occurs if the Python function raises an exception |
| 280 |
(see the docs for details).""" |
| 281 |
|
| 282 |
|
| 283 |
space = self.space |
| 284 |
w_ffi = self |
| 285 |
w_decorator = call_python.get_generic_decorator(space) |
| 286 |
return space.appexec([w_decorator, w_ffi, w_name, w_error, w_onerror], |
| 287 |
"""(decorator, ffi, name, error, onerror): |
| 288 |
return lambda python_callable: decorator(ffi, python_callable, |
| 289 |
name, error, onerror)""") |
| 290 |
|
| 291 |
|
| 292 |
@unwrap_spec(w_python_callable=WrappedDefault(None), |
| 293 |
w_error=WrappedDefault(None), |
| 294 |
w_onerror=WrappedDefault(None)) |
| 295 |
def descr_callback(self, w_cdecl, w_python_callable, w_error, w_onerror): |
| 296 |
"""\ |
| 297 |
Return a callback object or a decorator making such a callback object. |
| 298 |
'cdecl' must name a C function pointer type. The callback invokes the |
| 299 |
specified 'python_callable' (which may be provided either directly or |
| 300 |
via a decorator). Important: the callback object must be manually |
| 301 |
kept alive for as long as the callback may be invoked from the C code.""" |
| 302 |
|
| 303 |
w_ctype = self.ffi_type(w_cdecl, ACCEPT_STRING | ACCEPT_CTYPE | |
| 304 |
CONSIDER_FN_AS_FNPTR) |
| 305 |
space = self.space |
| 306 |
if not space.is_none(w_python_callable): |
| 307 |
return ccallback.make_callback(space, w_ctype, |
| 308 |
w_python_callable, w_error, |
| 309 |
w_onerror) |
| 310 |
else: |
| 311 |
|
| 312 |
return space.appexec([w_ctype, w_error, w_onerror], |
| 313 |
"""(ctype, error, onerror): |
| 314 |
import _cffi_backend |
| 315 |
return lambda python_callable: ( |
| 316 |
_cffi_backend.callback(ctype, python_callable, |
| 317 |
error, onerror))""") |
| 318 |
|
| 319 |
|
| 320 |
def descr_cast(self, w_arg, w_ob): |
| 321 |
"""\ |
| 322 |
Similar to a C cast: returns an instance of the named C |
| 323 |
type initialized with the given 'source'. The source is |
| 324 |
casted between integers or pointers of any type.""" |
| 325 |
|
| 326 |
w_ctype = self.ffi_type(w_arg, ACCEPT_STRING | ACCEPT_CTYPE) |
| 327 |
return w_ctype.cast(w_ob) |
| 328 |
|
| 329 |
|
| 330 |
@unwrap_spec(require_writable=int) |
| 331 |
def descr_from_buffer(self, w_cdecl, w_python_buffer=None, |
| 332 |
require_writable=0): |
| 333 |
"""\ |
| 334 |
Return a <cdata 'char[]'> that points to the data of the given Python |
| 335 |
object, which must support the buffer interface. Note that this is |
| 336 |
not meant to be used on the built-in types str or unicode |
| 337 |
(you can build 'char[]' arrays explicitly) but only on objects |
| 338 |
containing large quantities of raw data in some other format, like |
| 339 |
'array.array' or numpy arrays.""" |
| 340 |
|
| 341 |
if w_python_buffer is None: |
| 342 |
w_python_buffer = w_cdecl |
| 343 |
w_ctype = newtype._new_chara_type(self.space) |
| 344 |
else: |
| 345 |
w_ctype = self.ffi_type(w_cdecl, ACCEPT_STRING | ACCEPT_CTYPE) |
| 346 |
return func.from_buffer(self.space, w_ctype, w_python_buffer, |
| 347 |
require_writable) |
| 348 |
|
| 349 |
|
| 350 |
@unwrap_spec(w_arg=W_CData) |
| 351 |
def descr_from_handle(self, w_arg): |
| 352 |
"""\ |
| 353 |
Cast a 'void *' back to a Python object. Must be used *only* on the |
| 354 |
pointers returned by new_handle(), and *only* as long as the exact |
| 355 |
cdata object returned by new_handle() is still alive (somewhere else |
| 356 |
in the program). Failure to follow these rules will crash.""" |
| 357 |
|
| 358 |
return handle.from_handle(self.space, w_arg) |
| 359 |
|
| 360 |
|
| 361 |
@unwrap_spec(w_cdata=W_CData, size=int) |
| 362 |
def descr_gc(self, w_cdata, w_destructor, size=0): |
| 363 |
"""\ |
| 364 |
Return a new cdata object that points to the same data. |
| 365 |
Later, when this new cdata object is garbage-collected, |
| 366 |
'destructor(old_cdata_object)' will be called.""" |
| 367 |
|
| 368 |
return w_cdata.with_gc(w_destructor, size) |
| 369 |
|
| 370 |
|
| 371 |
@unwrap_spec(replace_with='text') |
| 372 |
def descr_getctype(self, w_cdecl, replace_with=''): |
| 373 |
"""\ |
| 374 |
Return a string giving the C type 'cdecl', which may be itself a |
| 375 |
string or a <ctype> object. If 'replace_with' is given, it gives |
| 376 |
extra text to append (or insert for more complicated C types), like a |
| 377 |
variable name, or '*' to get actually the C type 'pointer-to-cdecl'.""" |
| 378 |
|
| 379 |
w_ctype = self.ffi_type(w_cdecl, ACCEPT_STRING | ACCEPT_CTYPE) |
| 380 |
replace_with = replace_with.strip(' ') |
| 381 |
if len(replace_with) == 0: |
| 382 |
result = w_ctype.name |
| 383 |
else: |
| 384 |
add_paren = (replace_with[0] == '*' and |
| 385 |
isinstance(w_ctype, ctypearray.W_CTypeArray)) |
| 386 |
add_space = (not add_paren and replace_with[0] != '[' |
| 387 |
and replace_with[0] != '(') |
| 388 |
|
| 389 |
result = w_ctype.name[:w_ctype.name_position] |
| 390 |
if add_paren: |
| 391 |
result += '(' |
| 392 |
if add_space: |
| 393 |
result += ' ' |
| 394 |
result += replace_with |
| 395 |
if add_paren: |
| 396 |
result += ')' |
| 397 |
result += w_ctype.name[w_ctype.name_position:] |
| 398 |
|
| 399 |
return self.space.newtext(result) |
| 400 |
|
| 401 |
|
| 402 |
@unwrap_spec(code=int) |
| 403 |
def descr_getwinerror(self, code=-1): |
| 404 |
"""\ |
| 405 |
Return either the GetLastError() or the error number given by the |
| 406 |
optional 'code' argument, as a tuple '(code, message)'.""" |
| 407 |
|
| 408 |
return cerrno.getwinerror(self.space, code) |
| 409 |
|
| 410 |
|
| 411 |
@unwrap_spec(n=int) |
| 412 |
def descr_memmove(self, w_dest, w_src, n): |
| 413 |
"""\ |
| 414 |
ffi.memmove(dest, src, n) copies n bytes of memory from src to dest. |
| 415 |
|
| 416 |
Like the C function memmove(), the memory areas may overlap; |
| 417 |
apart from that it behaves like the C function memcpy(). |
| 418 |
|
| 419 |
'src' can be any cdata ptr or array, or any Python buffer object. |
| 420 |
'dest' can be any cdata ptr or array, or a writable Python buffer |
| 421 |
object. The size to copy, 'n', is always measured in bytes. |
| 422 |
|
| 423 |
Unlike other methods, this one supports all Python buffer including |
| 424 |
byte strings and bytearrays---but it still does not support |
| 425 |
non-contiguous buffers.""" |
| 426 |
|
| 427 |
return func.memmove(self.space, w_dest, w_src, n) |
| 428 |
|
| 429 |
|
| 430 |
@unwrap_spec(w_init=WrappedDefault(None)) |
| 431 |
def descr_new(self, w_arg, w_init): |
| 432 |
"""\ |
| 433 |
Allocate an instance according to the specified C type and return a |
| 434 |
pointer to it. The specified C type must be either a pointer or an |
| 435 |
array: ``new('X *')`` allocates an X and returns a pointer to it, |
| 436 |
whereas ``new('X[n]')`` allocates an array of n X'es and returns an |
| 437 |
array referencing it (which works mostly like a pointer, like in C). |
| 438 |
You can also use ``new('X[]', n)`` to allocate an array of a |
| 439 |
non-constant length n. |
| 440 |
|
| 441 |
The memory is initialized following the rules of declaring a global |
| 442 |
variable in C: by default it is zero-initialized, but an explicit |
| 443 |
initializer can be given which can be used to fill all or part of the |
| 444 |
memory. |
| 445 |
|
| 446 |
When the returned <cdata> object goes out of scope, the memory is |
| 447 |
freed. In other words the returned <cdata> object has ownership of |
| 448 |
the value of type 'cdecl' that it points to. This means that the raw |
| 449 |
data can be used as long as this object is kept alive, but must not be |
| 450 |
used for a longer time. Be careful about that when copying the |
| 451 |
pointer to the memory somewhere else, e.g. into another structure.""" |
| 452 |
|
| 453 |
w_ctype = self.ffi_type(w_arg, ACCEPT_STRING | ACCEPT_CTYPE) |
| 454 |
return w_ctype.newp(w_init, allocator.default_allocator) |
| 455 |
|
| 456 |
|
| 457 |
@unwrap_spec(w_alloc=WrappedDefault(None), |
| 458 |
w_free=WrappedDefault(None), |
| 459 |
should_clear_after_alloc=int) |
| 460 |
def descr_new_allocator(self, w_alloc, w_free, |
| 461 |
should_clear_after_alloc=1): |
| 462 |
"""\ |
| 463 |
Return a new allocator, i.e. a function that behaves like ffi.new() |
| 464 |
but uses the provided low-level 'alloc' and 'free' functions. |
| 465 |
|
| 466 |
'alloc' is called with the size as argument. If it returns NULL, a |
| 467 |
MemoryError is raised. 'free' is called with the result of 'alloc' |
| 468 |
as argument. Both can be either Python functions or directly C |
| 469 |
functions. If 'free' is None, then no free function is called. |
| 470 |
If both 'alloc' and 'free' are None, the default is used. |
| 471 |
|
| 472 |
If 'should_clear_after_alloc' is set to False, then the memory |
| 473 |
returned by 'alloc' is assumed to be already cleared (or you are |
| 474 |
fine with garbage); otherwise CFFI will clear it. |
| 475 |
""" |
| 476 |
|
| 477 |
return allocator.new_allocator(self, w_alloc, w_free, |
| 478 |
should_clear_after_alloc) |
| 479 |
|
| 480 |
|
| 481 |
def descr_new_handle(self, w_arg): |
| 482 |
"""\ |
| 483 |
Return a non-NULL cdata of type 'void *' that contains an opaque |
| 484 |
reference to the argument, which can be any Python object. To cast it |
| 485 |
back to the original object, use from_handle(). You must keep alive |
| 486 |
the cdata object returned by new_handle()!""" |
| 487 |
|
| 488 |
space = self.space |
| 489 |
return handle._newp_handle(space, newtype._new_voidp_type(space), w_arg) |
| 490 |
|
| 491 |
|
| 492 |
def _more_offsetof(self, w_ctype, w_arg0, args_w): |
| 493 |
|
| 494 |
w_ctype, offset = w_ctype.direct_typeoffsetof(w_arg0, False) |
| 495 |
for i in range(len(args_w)): |
| 496 |
w_ctype, ofs1 = w_ctype.direct_typeoffsetof(args_w[i], True) |
| 497 |
offset += ofs1 |
| 498 |
return offset |
| 499 |
|
| 500 |
def descr_offsetof(self, w_arg, w_field_or_array, args_w): |
| 501 |
"""\ |
| 502 |
Return the offset of the named field inside the given structure or |
| 503 |
array, which must be given as a C type name. You can give several |
| 504 |
field names in case of nested structures. You can also give numeric |
| 505 |
values which correspond to array items, in case of an array type.""" |
| 506 |
|
| 507 |
w_ctype = self.ffi_type(w_arg, ACCEPT_STRING | ACCEPT_CTYPE) |
| 508 |
if len(args_w) == 0: |
| 509 |
_, offset = w_ctype.direct_typeoffsetof(w_field_or_array, False) |
| 510 |
else: |
| 511 |
offset = self._more_offsetof(w_ctype, w_field_or_array, args_w) |
| 512 |
return self.space.newint(offset) |
| 513 |
|
| 514 |
|
| 515 |
@unwrap_spec(w_cdata=W_CData, maxlen=int) |
| 516 |
def descr_string(self, w_cdata, maxlen=-1): |
| 517 |
"""\ |
| 518 |
Return a Python string (or unicode string) from the 'cdata'. If |
| 519 |
'cdata' is a pointer or array of characters or bytes, returns the |
| 520 |
null-terminated string. The returned string extends until the first |
| 521 |
null character, or at most 'maxlen' characters. If 'cdata' is an |
| 522 |
array then 'maxlen' defaults to its length. |
| 523 |
|
| 524 |
If 'cdata' is a pointer or array of wchar_t, returns a unicode string |
| 525 |
following the same rules. |
| 526 |
|
| 527 |
If 'cdata' is a single character or byte or a wchar_t, returns it as a |
| 528 |
string or unicode string. |
| 529 |
|
| 530 |
If 'cdata' is an enum, returns the value of the enumerator as a |
| 531 |
string, or 'NUMBER' if the value is out of range.""" |
| 532 |
|
| 533 |
return w_cdata.ctype.string(w_cdata, maxlen) |
| 534 |
|
| 535 |
|
| 536 |
@unwrap_spec(w_cdata=W_CData, length=int) |
| 537 |
def descr_unpack(self, w_cdata, length): |
| 538 |
"""Unpack an array of C data of the given length, |
| 539 |
returning a Python string/unicode/list. |
| 540 |
|
| 541 |
If 'cdata' is a pointer to 'char', returns a byte string. |
| 542 |
It does not stop at the first null. This is equivalent to: |
| 543 |
ffi.buffer(cdata, length)[:] |
| 544 |
|
| 545 |
If 'cdata' is a pointer to 'wchar_t', returns a unicode string. |
| 546 |
'length' is measured in wchar_t's; it is not the size in bytes. |
| 547 |
|
| 548 |
If 'cdata' is a pointer to anything else, returns a list of |
| 549 |
'length' items. This is a faster equivalent to: |
| 550 |
[cdata[i] for i in range(length)]""" |
| 551 |
|
| 552 |
return w_cdata.unpack(length) |
| 553 |
|
| 554 |
|
| 555 |
def descr_sizeof(self, w_arg): |
| 556 |
"""\ |
| 557 |
Return the size in bytes of the argument. |
| 558 |
It can be a string naming a C type, or a 'cdata' instance.""" |
| 559 |
|
| 560 |
if isinstance(w_arg, W_CData): |
| 561 |
w_ctype = w_arg.ctype |
| 562 |
size = w_arg._sizeof() |
| 563 |
else: |
| 564 |
w_ctype = self.ffi_type(w_arg, ACCEPT_ALL) |
| 565 |
size = w_ctype.size |
| 566 |
if size < 0: |
| 567 |
raise oefmt(self.w_FFIError, |
| 568 |
"don't know the size of ctype '%s'", w_ctype.name) |
| 569 |
return self.space.newint(size) |
| 570 |
|
| 571 |
|
| 572 |
def descr_typeof(self, w_arg): |
| 573 |
"""\ |
| 574 |
Parse the C type given as a string and return the |
| 575 |
corresponding <ctype> object. |
| 576 |
It can also be used on 'cdata' instance to get its C type.""" |
| 577 |
|
| 578 |
if isinstance(w_arg, wrapper.W_FunctionWrapper): |
| 579 |
return w_arg.typeof(self) |
| 580 |
return self.ffi_type(w_arg, ACCEPT_STRING | ACCEPT_CDATA) |
| 581 |
|
| 582 |
|
| 583 |
@unwrap_spec(flags=int) |
| 584 |
def descr_dlopen(self, w_filename, flags=0): |
| 585 |
"""\ |
| 586 |
Load and return a dynamic library identified by 'name'. The standard |
| 587 |
C library can be loaded by passing None. |
| 588 |
|
| 589 |
Note that functions and types declared with 'ffi.cdef()' are not |
| 590 |
linked to a particular library, just like C headers. In the library |
| 591 |
we only look for the actual (untyped) symbols at the time of their |
| 592 |
first access.""" |
| 593 |
|
| 594 |
from pypy.module._cffi_backend import cdlopen |
| 595 |
return cdlopen.W_DlOpenLibObject(self, w_filename, flags) |
| 596 |
|
| 597 |
|
| 598 |
def descr_dlclose(self, w_lib): |
| 599 |
"""\ |
| 600 |
Close a library obtained with ffi.dlopen(). After this call, access to |
| 601 |
"functions or variables from the library will fail (possibly with a |
| 602 |
segmentation fault).""" |
| 603 |
|
| 604 |
from pypy.module._cffi_backend.lib_obj import W_LibObject |
| 605 |
lib = self.space.interp_w(W_LibObject, w_lib) |
| 606 |
lib.cdlopen_close() |
| 607 |
|
| 608 |
|
| 609 |
@unwrap_spec(name='text') |
| 610 |
def descr_integer_const(self, name): |
| 611 |
"""\ |
| 612 |
Get the value of an integer constant. |
| 613 |
|
| 614 |
'ffi.integer_const(\"xxx\")' is equivalent to 'lib.xxx' if xxx names an |
| 615 |
integer constant. The point of this function is limited to use cases |
| 616 |
where you have an 'ffi' object but not any associated 'lib' object.""" |
| 617 |
|
| 618 |
w_result = self.fetch_int_constant(name) |
| 619 |
if w_result is None: |
| 620 |
raise oefmt(self.space.w_AttributeError, |
| 621 |
"integer constant '%s' not found", name) |
| 622 |
return w_result |
| 623 |
|
| 624 |
|
| 625 |
def descr_list_types(self): |
| 626 |
"""\ |
| 627 |
Returns the user type names known to this FFI instance. |
| 628 |
This returns a tuple containing three lists of names: |
| 629 |
(typedef_names, names_of_structs, names_of_unions)""" |
| 630 |
|
| 631 |
space = self.space |
| 632 |
ctx = self.ctxobj.ctx |
| 633 |
|
| 634 |
lst1_w = [] |
| 635 |
typenames = rffi.cast(rffi.CArrayPtr(parse_c_type.TYPENAME_S), ctx.c_typenames) |
| 636 |
|
| 637 |
for i in range(rffi.getintfield(ctx, 'c_num_typenames')): |
| 638 |
s = rffi.constcharp2str(typenames[i].c_name) |
| 639 |
lst1_w.append(space.newtext(s)) |
| 640 |
|
| 641 |
lst2_w = [] |
| 642 |
lst3_w = [] |
| 643 |
unions = rffi.cast(rffi.CArrayPtr(parse_c_type.STRUCT_UNION_S), ctx.c_struct_unions) |
| 644 |
for i in range(rffi.getintfield(ctx, 'c_num_struct_unions')): |
| 645 |
su = unions[i] |
| 646 |
if su.c_name[0] == '$': |
| 647 |
continue |
| 648 |
s = rffi.constcharp2str(su.c_name) |
| 649 |
if rffi.getintfield(su, 'c_flags') & cffi_opcode.F_UNION: |
| 650 |
lst_w = lst3_w |
| 651 |
else: |
| 652 |
lst_w = lst2_w |
| 653 |
lst_w.append(space.newtext(s)) |
| 654 |
|
| 655 |
return space.newtuple([space.newlist(lst1_w), |
| 656 |
space.newlist(lst2_w), |
| 657 |
space.newlist(lst3_w)]) |
| 658 |
|
| 659 |
|
| 660 |
def descr_init_once(self, w_func, w_tag): |
| 661 |
"""\ |
| 662 |
init_once(function, tag): run function() once. More precisely, |
| 663 |
'function()' is called the first time we see a given 'tag'. |
| 664 |
|
| 665 |
The return value of function() is remembered and returned by the current |
| 666 |
and all future init_once() with the same tag. If init_once() is called |
| 667 |
from multiple threads in parallel, all calls block until the execution |
| 668 |
of function() is done. If function() raises an exception, it is |
| 669 |
propagated and nothing is cached.""" |
| 670 |
|
| 671 |
|
| 672 |
|
| 673 |
try: |
| 674 |
return self._init_once_elidable(w_tag) |
| 675 |
except KeyError: |
| 676 |
return self._init_once_slowpath(w_func, w_tag) |
| 677 |
|
| 678 |
@jit.elidable |
| 679 |
def _init_once_elidable(self, w_tag): |
| 680 |
jit_cache = self.jit_init_once_cache |
| 681 |
if jit_cache is not None: |
| 682 |
return jit_cache[w_tag] |
| 683 |
else: |
| 684 |
raise KeyError |
| 685 |
|
| 686 |
@jit.dont_look_inside |
| 687 |
def _init_once_slowpath(self, w_func, w_tag): |
| 688 |
space = self.space |
| 689 |
w_cache = self.w_init_once_cache |
| 690 |
if w_cache is None: |
| 691 |
w_cache = self.space.newdict() |
| 692 |
jit_cache = {} |
| 693 |
self.w_init_once_cache = w_cache |
| 694 |
self.jit_init_once_cache = jit_cache |
| 695 |
|
| 696 |
|
| 697 |
w_res = space.finditem(w_cache, w_tag) |
| 698 |
if w_res is None: |
| 699 |
w_res = W_InitOnceLock(space) |
| 700 |
w_res = space.call_method(w_cache, 'setdefault', w_tag, w_res) |
| 701 |
if not isinstance(w_res, W_InitOnceLock): |
| 702 |
return w_res |
| 703 |
with w_res.lock: |
| 704 |
w_res = space.finditem(w_cache, w_tag) |
| 705 |
if w_res is None or isinstance(w_res, W_InitOnceLock): |
| 706 |
w_res = space.call_function(w_func) |
| 707 |
self.jit_init_once_cache[w_tag] = w_res |
| 708 |
space.setitem(w_cache, w_tag, w_res) |
| 709 |
else: |
| 710 |
|
| 711 |
|
| 712 |
pass |
| 713 |
return w_res |
| 714 |
|
| 715 |
@unwrap_spec(w_cdata=W_CData) |
| 716 |
def descr_release(self, w_cdata): |
| 717 |
"""\ |
| 718 |
Release now the resources held by a 'cdata' object from ffi.new(), |
| 719 |
ffi.gc() or ffi.from_buffer(). The cdata object must not be used |
| 720 |
afterwards. |
| 721 |
|
| 722 |
'ffi.release(cdata)' is equivalent to 'cdata.__exit__()'.""" |
| 723 |
w_cdata.enter_exit(True) |
| 724 |
|
| 725 |
|
| 726 |
class W_InitOnceLock(W_Root): |
| 727 |
def __init__(self, space): |
| 728 |
self.lock = space.allocate_lock() |
| 729 |
|
| 730 |
|
| 731 |
@jit.dont_look_inside |
| 732 |
def make_plain_ffi_object(space, w_ffitype=None): |
| 733 |
if w_ffitype is None: |
| 734 |
w_ffitype = space.gettypefor(W_FFIObject) |
| 735 |
r = space.allocate_instance(W_FFIObject, w_ffitype) |
| 736 |
|
| 737 |
src_ctx = rffi.cast(parse_c_type.PCTX, 0) |
| 738 |
r.__init__(space, src_ctx) |
| 739 |
return r |
| 740 |
|
| 741 |
def W_FFIObject___new__(space, w_subtype, __args__): |
| 742 |
return make_plain_ffi_object(space, w_subtype) |
| 743 |
|
| 744 |
def make_CData(space): |
| 745 |
return space.gettypefor(W_CData) |
| 746 |
|
| 747 |
def make_CType(space): |
| 748 |
return space.gettypefor(W_CType) |
| 749 |
|
| 750 |
def make_NULL(space): |
| 751 |
ctvoidp = newtype._new_voidp_type(space) |
| 752 |
w_NULL = ctvoidp.cast(space.newint(0)) |
| 753 |
return w_NULL |
| 754 |
|
| 755 |
def make_error(space): |
| 756 |
return space.appexec([], """(): |
| 757 |
return type('error', (Exception,), {'__module__': 'ffi'})""") |
| 758 |
|
| 759 |
def make_buffer(space): |
| 760 |
return space.gettypefor(cbuffer.MiniBuffer) |
| 761 |
|
| 762 |
_extras = get_dict_rtld_constants() |
| 763 |
if sys.platform == 'win32': |
| 764 |
_extras['getwinerror'] = interp2app(W_FFIObject.descr_getwinerror) |
| 765 |
|
| 766 |
|
| 767 |
W_FFIObject.typedef = TypeDef( |
| 768 |
'_cffi_backend.FFI', |
| 769 |
__new__ = interp2app(W_FFIObject___new__), |
| 770 |
__init__ = interp2app(W_FFIObject.descr_init), |
| 771 |
CData = ClassAttr(make_CData), |
| 772 |
CType = ClassAttr(make_CType), |
| 773 |
NULL = ClassAttr(make_NULL), |
| 774 |
error = ClassAttr(make_error), |
| 775 |
errno = GetSetProperty(W_FFIObject.get_errno, |
| 776 |
W_FFIObject.set_errno, |
| 777 |
doc=W_FFIObject.doc_errno, |
| 778 |
cls=W_FFIObject), |
| 779 |
addressof = interp2app(W_FFIObject.descr_addressof), |
| 780 |
alignof = interp2app(W_FFIObject.descr_alignof), |
| 781 |
buffer = ClassAttr(make_buffer), |
| 782 |
callback = interp2app(W_FFIObject.descr_callback), |
| 783 |
cast = interp2app(W_FFIObject.descr_cast), |
| 784 |
def_extern = interp2app(W_FFIObject.descr_def_extern), |
| 785 |
dlclose = interp2app(W_FFIObject.descr_dlclose), |
| 786 |
dlopen = interp2app(W_FFIObject.descr_dlopen), |
| 787 |
from_buffer = interp2app(W_FFIObject.descr_from_buffer), |
| 788 |
from_handle = interp2app(W_FFIObject.descr_from_handle), |
| 789 |
gc = interp2app(W_FFIObject.descr_gc), |
| 790 |
getctype = interp2app(W_FFIObject.descr_getctype), |
| 791 |
init_once = interp2app(W_FFIObject.descr_init_once), |
| 792 |
integer_const = interp2app(W_FFIObject.descr_integer_const), |
| 793 |
list_types = interp2app(W_FFIObject.descr_list_types), |
| 794 |
memmove = interp2app(W_FFIObject.descr_memmove), |
| 795 |
new = interp2app(W_FFIObject.descr_new), |
| 796 |
new_allocator = interp2app(W_FFIObject.descr_new_allocator), |
| 797 |
new_handle = interp2app(W_FFIObject.descr_new_handle), |
| 798 |
offsetof = interp2app(W_FFIObject.descr_offsetof), |
| 799 |
release = interp2app(W_FFIObject.descr_release), |
| 800 |
sizeof = interp2app(W_FFIObject.descr_sizeof), |
| 801 |
string = interp2app(W_FFIObject.descr_string), |
| 802 |
typeof = interp2app(W_FFIObject.descr_typeof), |
| 803 |
unpack = interp2app(W_FFIObject.descr_unpack), |
| 804 |
**_extras) |