Debian Codegraph @

pypy/module/_cffi_backend/ctypefunc.py

raw symbols SCIP
1 """
2 Function pointers.
3 """
4
5 import sys
6
7 from rpython.rlib import jit, clibffi, jit_libffi, rgc
8 from rpython.rlib.jit_libffi import (CIF_DESCRIPTION, CIF_DESCRIPTION_P,
9 FFI_TYPE, FFI_TYPE_P, FFI_TYPE_PP, SIZE_OF_FFI_ARG)
10 from rpython.rlib.objectmodel import we_are_translated, instantiate
11 from rpython.rlib.objectmodel import keepalive_until_here
12 from rpython.rtyper.lltypesystem import lltype, llmemory, rffi
13 from rpython.rtyper.annlowlevel import llstr
14
15 from pypy.interpreter.error import OperationError, oefmt
16 from pypy.module._cffi_backend.moduledef import (
17 FFI_DEFAULT_ABI, has_stdcall, FFI_STDCALL)
18 from pypy.module._cffi_backend import ctypearray, cdataobj, cerrno
19 from pypy.module._cffi_backend.ctypeobj import W_CType
20 from pypy.module._cffi_backend.ctypeptr import W_CTypePtrBase, W_CTypePointer
21 from pypy.module._cffi_backend.ctypevoid import W_CTypeVoid
22 from pypy.module._cffi_backend.ctypestruct import W_CTypeStruct, W_CTypeUnion
23 from pypy.module._cffi_backend.ctypeprim import (W_CTypePrimitiveSigned,
24 W_CTypePrimitiveUnsigned, W_CTypePrimitiveCharOrUniChar,
25 W_CTypePrimitiveFloat, W_CTypePrimitiveLongDouble, W_CTypePrimitiveComplex)
26
27
28 class W_CTypeFunc(W_CTypePtrBase):
29 _attrs_ = ['fargs', 'ellipsis', 'abi', 'cif_descr']
30 _immutable_fields_ = ['fargs[*]', 'ellipsis', 'abi', 'cif_descr']
31 kind = "function"
32
33 cif_descr = lltype.nullptr(CIF_DESCRIPTION)
34
35 def __init__(self, space, fargs, fresult, ellipsis,
36 abi=FFI_DEFAULT_ABI):
37 assert isinstance(ellipsis, bool)
38 extra, xpos = self._compute_extra_text(fargs, fresult, ellipsis, abi)
39 size = rffi.sizeof(rffi.VOIDP)
40 W_CTypePtrBase.__init__(self, space, size, extra, xpos, fresult)
41 self.fargs = fargs
42 self.ellipsis = ellipsis
43 self.abi = abi
44 # fresult is stored in self.ctitem
45
46 if not ellipsis:
47 # Functions with '...' varargs are stored without a cif_descr
48 # at all. The cif is computed on every call from the actual
49 # types passed in. For all other functions, the cif_descr
50 # is computed here.
51 builder = CifDescrBuilder(fargs, fresult, abi)
52 try:
53 builder.rawallocate(self)
54 except OperationError as e:
55 if not e.match(space, space.w_NotImplementedError):
56 raise
57 # else, eat the NotImplementedError. We will get the
58 # exception if we see an actual call
59 if self.cif_descr: # should not be True, but you never know
60 lltype.free(self.cif_descr, flavor='raw')
61 self.cif_descr = lltype.nullptr(CIF_DESCRIPTION)
62
63 def is_unichar_ptr_or_array(self):
64 return False
65
66 def is_char_or_unichar_ptr_or_array(self):
67 return False
68
69 def string(self, cdataobj, maxlen):
70 # Can't use ffi.string() on a function pointer
71 return W_CType.string(self, cdataobj, maxlen)
72
73 def new_ctypefunc_completing_argtypes(self, args_w):
74 space = self.space
75 nargs_declared = len(self.fargs)
76 fvarargs = [None] * len(args_w)
77 for i in range(nargs_declared):
78 fvarargs[i] = self.fargs[i]
79 for i in range(nargs_declared, len(args_w)):
80 w_obj = args_w[i]
81 if isinstance(w_obj, cdataobj.W_CData):
82 ct = w_obj.ctype.get_vararg_type()
83 else:
84 raise oefmt(space.w_TypeError,
85 "argument %d passed in the variadic part needs to "
86 "be a cdata object (got %T)", i + 1, w_obj)
87 fvarargs[i] = ct
88 # xxx call instantiate() directly. It's a bit of a hack.
89 ctypefunc = instantiate(W_CTypeFunc)
90 ctypefunc.space = space
91 ctypefunc.fargs = fvarargs
92 ctypefunc.ctitem = self.ctitem
93 #ctypefunc.cif_descr = NULL --- already provided as the default
94 CifDescrBuilder(fvarargs, self.ctitem, self.abi).rawallocate(ctypefunc)
95 return ctypefunc
96
97 @rgc.must_be_light_finalizer
98 def __del__(self):
99 if self.cif_descr:
100 lltype.free(self.cif_descr, flavor='raw')
101
102 def _compute_extra_text(self, fargs, fresult, ellipsis, abi):
103 argnames = ['(*)(']
104 xpos = 2
105 if has_stdcall and abi == FFI_STDCALL:
106 argnames[0] = '(__stdcall *)('
107 xpos += len('__stdcall ')
108 for i, farg in enumerate(fargs):
109 if i > 0:
110 argnames.append(', ')
111 argnames.append(farg.name)
112 if ellipsis:
113 if len(fargs) > 0:
114 argnames.append(', ')
115 argnames.append('...')
116 argnames.append(')')
117 return ''.join(argnames), xpos
118
119 def _fget(self, attrchar):
120 if attrchar == 'a': # args
121 return self.space.newtuple([a for a in self.fargs])
122 if attrchar == 'r': # result
123 return self.ctitem
124 if attrchar == 'E': # ellipsis
125 return self.space.newbool(self.ellipsis)
126 if attrchar == 'A': # abi
127 return self.space.newint(self.abi)
128 return W_CTypePtrBase._fget(self, attrchar)
129
130 def call(self, funcaddr, args_w):
131 if not funcaddr:
132 raise oefmt(self.space.w_RuntimeError,
133 "cannot call null function pointer from cdata '%s'",
134 self.name)
135 if self.cif_descr:
136 # regular case: this function does not take '...' arguments
137 self = jit.promote(self)
138 nargs_declared = len(self.fargs)
139 if len(args_w) != nargs_declared:
140 space = self.space
141 raise oefmt(space.w_TypeError,
142 "'%s' expects %d arguments, got %d",
143 self.name, nargs_declared, len(args_w))
144 return self._call(funcaddr, args_w)
145 else:
146 # call of a variadic function
147 return self.call_varargs(funcaddr, args_w)
148
149 @jit.dont_look_inside
150 def call_varargs(self, funcaddr, args_w):
151 nargs_declared = len(self.fargs)
152 if len(args_w) < nargs_declared:
153 space = self.space
154 raise oefmt(space.w_TypeError,
155 "'%s' expects at least %d arguments, got %d",
156 self.name, nargs_declared, len(args_w))
157 completed = self.new_ctypefunc_completing_argtypes(args_w)
158 return completed._call(funcaddr, args_w)
159
160 # The following is the core of function calls. It is @unroll_safe,
161 # which means that the JIT is free to unroll the argument handling.
162 # But in case the function takes variable arguments, we don't unroll
163 # this (yet) for better safety: this is handled by @dont_look_inside
164 # in call_varargs.
165 @jit.unroll_safe
166 def _call(self, funcaddr, args_w):
167 space = self.space
168 cif_descr = self.cif_descr # 'self' should have been promoted here
169 size = cif_descr.exchange_size
170 mustfree_max_plus_1 = 0
171 keepalives = [llstr(None)] * len(args_w) # llstrings
172 buffer = lltype.malloc(rffi.CCHARP.TO, size, flavor='raw')
173 try:
174 for i in range(len(args_w)):
175 data = rffi.ptradd(buffer, cif_descr.exchange_args[i])
176 w_obj = args_w[i]
177 argtype = self.fargs[i]
178 if argtype.convert_argument_from_object(data, w_obj,
179 keepalives, i):
180 # argtype is a pointer type, and w_obj a list/tuple/str
181 mustfree_max_plus_1 = i + 1
182
183 jit_libffi.jit_ffi_call(cif_descr,
184 rffi.cast(rffi.VOIDP, funcaddr),
185 buffer)
186
187 resultdata = rffi.ptradd(buffer, cif_descr.exchange_result)
188 w_res = self.ctitem.copy_and_convert_to_object(resultdata)
189 finally:
190 for i in range(mustfree_max_plus_1):
191 argtype = self.fargs[i]
192 if isinstance(argtype, W_CTypePointer):
193 data = rffi.ptradd(buffer, cif_descr.exchange_args[i])
194 flag = get_mustfree_flag(data)
195 raw_cdata = rffi.cast(rffi.CCHARPP, data)[0]
196 if flag == 1:
197 lltype.free(raw_cdata, flavor='raw')
198 elif flag == 3:
199 rgc.unpin(keepalives[i])
200 if not we_are_translated():
201 lltype.free(keepalives[i])
202 elif flag >= 4:
203 llobj = keepalives[i]
204 assert llobj # not NULL
205 rffi.free_nonmovingbuffer_ll(raw_cdata,
206 llobj, chr(flag))
207 lltype.free(buffer, flavor='raw')
208 keepalive_until_here(args_w)
209 return w_res
210
211 def get_mustfree_flag(data):
212 return ord(rffi.ptradd(data, -1)[0])
213
214 def set_mustfree_flag(data, flag):
215 """ Set a flag for future handling of the pointer after the call,
216 possible values are:
217 0 - not set
218 1 - free the argument
219 2 - file argument
220 3 - unpin the keepalive
221 4, 5, 6 - free the keepalive slot, different values returned from
222 rffi.get_nonmovingbuffer_ll_final_null
223 """
224 rffi.ptradd(data, -1)[0] = chr(flag)
225
226 # ____________________________________________________________
227
228
229 # ----------
230 # We attach to the classes small methods that return a 'ffi_type'
231
232 def _notimplemented_ffi_type(self, is_result_type, extra=''):
233 if is_result_type:
234 place = "return value"
235 else:
236 place = "argument"
237 raise oefmt(self.space.w_NotImplementedError,
238 "ctype '%s' (size %d) not supported as %s%s",
239 self.name, self.size, place, extra)
240
241 def _missing_ffi_type(self, cifbuilder, is_result_type):
242 if self.size < 0:
243 raise oefmt(self.space.w_TypeError,
244 "ctype '%s' has incomplete type", self.name)
245 raise _notimplemented_ffi_type(self, is_result_type)
246
247 def _struct_ffi_type(self, cifbuilder, is_result_type):
248 if self.size >= 0:
249 return cifbuilder.fb_struct_ffi_type(self, is_result_type)
250 return _missing_ffi_type(self, cifbuilder, is_result_type)
251
252 def _union_ffi_type(self, cifbuilder, is_result_type):
253 if self.size >= 0: # only for a better error message
254 return cifbuilder.fb_union_ffi_type(self, is_result_type)
255 return _missing_ffi_type(self, cifbuilder, is_result_type)
256
257 def _primsigned_ffi_type(self, cifbuilder, is_result_type):
258 size = self.size
259 if size == 1: return clibffi.ffi_type_sint8
260 elif size == 2: return clibffi.ffi_type_sint16
261 elif size == 4: return clibffi.ffi_type_sint32
262 elif size == 8: return clibffi.ffi_type_sint64
263 return _missing_ffi_type(self, cifbuilder, is_result_type)
264
265 def _primunsigned_ffi_type(self, cifbuilder, is_result_type):
266 size = self.size
267 if size == 1: return clibffi.ffi_type_uint8
268 elif size == 2: return clibffi.ffi_type_uint16
269 elif size == 4: return clibffi.ffi_type_uint32
270 elif size == 8: return clibffi.ffi_type_uint64
271 return _missing_ffi_type(self, cifbuilder, is_result_type)
272
273 def _primfloat_ffi_type(self, cifbuilder, is_result_type):
274 size = self.size
275 if size == 4: return clibffi.ffi_type_float
276 elif size == 8: return clibffi.ffi_type_double
277 return _missing_ffi_type(self, cifbuilder, is_result_type)
278
279 def _primlongdouble_ffi_type(self, cifbuilder, is_result_type):
280 return clibffi.ffi_type_longdouble
281
282 def _primcomplex_ffi_type(self, cifbuilder, is_result_type):
283 raise _notimplemented_ffi_type(self, is_result_type,
284 extra = " (the support for complex types inside libffi "
285 "is mostly missing at this point, so CFFI only "
286 "supports complex types as arguments or return "
287 "value in API-mode functions)")
288
289 def _ptr_ffi_type(self, cifbuilder, is_result_type):
290 return clibffi.ffi_type_pointer
291
292 def _void_ffi_type(self, cifbuilder, is_result_type):
293 if is_result_type:
294 return clibffi.ffi_type_void
295 return _missing_ffi_type(self, cifbuilder, is_result_type)
296
297 W_CType._get_ffi_type = _missing_ffi_type
298 W_CTypeStruct._get_ffi_type = _struct_ffi_type
299 W_CTypeUnion._get_ffi_type = _union_ffi_type
300 W_CTypePrimitiveSigned._get_ffi_type = _primsigned_ffi_type
301 W_CTypePrimitiveCharOrUniChar._get_ffi_type = _primunsigned_ffi_type
302 W_CTypePrimitiveUnsigned._get_ffi_type = _primunsigned_ffi_type
303 W_CTypePrimitiveFloat._get_ffi_type = _primfloat_ffi_type
304 W_CTypePrimitiveLongDouble._get_ffi_type = _primlongdouble_ffi_type
305 W_CTypePrimitiveComplex._get_ffi_type = _primcomplex_ffi_type
306 W_CTypePtrBase._get_ffi_type = _ptr_ffi_type
307 W_CTypeVoid._get_ffi_type = _void_ffi_type
308 # ----------
309
310
311 _SUPPORTED_IN_API_MODE = (
312 " are only supported as %s if the function is "
313 "'API mode' and non-variadic (i.e. declared inside ffibuilder"
314 ".cdef()+ffibuilder.set_source() and not taking a final '...' "
315 "argument)")
316
317 class CifDescrBuilder(object):
318 rawmem = lltype.nullptr(rffi.CCHARP.TO)
319
320 def __init__(self, fargs, fresult, fabi):
321 self.fargs = fargs
322 self.fresult = fresult
323 self.fabi = fabi
324
325 def fb_alloc(self, size):
326 size = llmemory.raw_malloc_usage(size)
327 if not self.bufferp:
328 self.nb_bytes += size
329 return lltype.nullptr(rffi.CCHARP.TO)
330 else:
331 result = self.bufferp
332 self.bufferp = rffi.ptradd(result, size)
333 return result
334
335 def fb_fill_type(self, ctype, is_result_type):
336 return ctype._get_ffi_type(self, is_result_type)
337
338 def fb_unsupported(self, ctype, is_result_type, detail):
339 place = "return value" if is_result_type else "argument"
340 raise oefmt(self.space.w_NotImplementedError,
341 "ctype '%s' not supported as %s. %s. "
342 "Such structs" + _SUPPORTED_IN_API_MODE,
343 ctype.name, place, detail, place)
344
345 def fb_union_ffi_type(self, ctype, is_result_type=False):
346 place = "return value" if is_result_type else "argument"
347 raise oefmt(self.space.w_NotImplementedError,
348 "ctype '%s' not supported as %s by libffi. "
349 "Unions" + _SUPPORTED_IN_API_MODE,
350 ctype.name, place, place)
351
352 def fb_struct_ffi_type(self, ctype, is_result_type=False):
353 # We can't pass a struct that was completed by verify().
354 # Issue: assume verify() is given "struct { long b; ...; }".
355 # Then it will complete it in the same way whether it is actually
356 # "struct { long a, b; }" or "struct { double a; long b; }".
357 # But on 64-bit UNIX, these two structs are passed by value
358 # differently: e.g. on x86-64, "b" ends up in register "rsi" in
359 # the first case and "rdi" in the second case.
360 #
361 # Another reason for 'custom_field_pos' would be anonymous
362 # nested structures: we lost the information about having it
363 # here, so better safe (and forbid it) than sorry (and maybe
364 # crash). Note: it seems we only get in this case with
365 # ffi.verify().
366 space = self.space
367 ctype.force_lazy_struct()
368 if ctype._custom_field_pos:
369 # these NotImplementedErrors may be caught and ignored until
370 # a real call is made to a function of this type
371 raise self.fb_unsupported(ctype, is_result_type,
372 "It is a struct declared with \"...;\", but the C "
373 "calling convention may depend on the missing fields; "
374 "or, it contains anonymous struct/unions")
375 # Another reason: __attribute__((packed)) is not supported by libffi.
376 if ctype._with_packed_change:
377 raise self.fb_unsupported(ctype, is_result_type,
378 "It is a 'packed' structure, with a different layout than "
379 "expected by libffi")
380
381 # walk the fields, expanding arrays into repetitions; first,
382 # only count how many flattened fields there are
383 nflat = 0
384 for i, cf in enumerate(ctype._fields_list):
385 if cf.is_bitfield():
386 raise self.fb_unsupported(ctype, is_result_type,
387 "It is a struct with bit fields, which libffi does not "
388 "support")
389 flat = 1
390 ct = cf.ctype
391 while isinstance(ct, ctypearray.W_CTypeArray):
392 flat *= ct.length
393 ct = ct.ctitem
394 if flat <= 0:
395 raise self.fb_unsupported(ctype, is_result_type,
396 "It is a struct with a zero-length array, which libffi "
397 "does not support")
398 nflat += flat
399
400 # allocate an array of (nflat + 1) ffi_types
401 elements = self.fb_alloc(rffi.sizeof(FFI_TYPE_P) * (nflat + 1))
402 elements = rffi.cast(FFI_TYPE_PP, elements)
403
404 # fill it with the ffi types of the fields
405 nflat = 0
406 for i, cf in enumerate(ctype._fields_list):
407 flat = 1
408 ct = cf.ctype
409 while isinstance(ct, ctypearray.W_CTypeArray):
410 flat *= ct.length
411 ct = ct.ctitem
412 ffi_subtype = self.fb_fill_type(ct, False)
413 if elements:
414 for j in range(flat):
415 elements[nflat] = ffi_subtype
416 nflat += 1
417
418 # zero-terminate the array
419 if elements:
420 elements[nflat] = lltype.nullptr(FFI_TYPE_P.TO)
421
422 # allocate and fill an ffi_type for the struct itself
423 ffistruct = self.fb_alloc(rffi.sizeof(FFI_TYPE))
424 ffistruct = rffi.cast(FFI_TYPE_P, ffistruct)
425 if ffistruct:
426 rffi.setintfield(ffistruct, 'c_size', ctype.size)
427 rffi.setintfield(ffistruct, 'c_alignment', ctype.alignof())
428 rffi.setintfield(ffistruct, 'c_type', clibffi.FFI_TYPE_STRUCT)
429 ffistruct.c_elements = elements
430
431 return ffistruct
432
433 def fb_build(self):
434 # Build a CIF_DESCRIPTION. Actually this computes the size and
435 # allocates a larger amount of data. It starts with a
436 # CIF_DESCRIPTION and continues with data needed for the CIF:
437 #
438 # - the argument types, as an array of 'ffi_type *'.
439 #
440 # - optionally, the result's and the arguments' ffi type data
441 # (this is used only for 'struct' ffi types; in other cases the
442 # 'ffi_type *' just points to static data like 'ffi_type_sint32').
443 #
444 nargs = len(self.fargs)
445
446 # start with a cif_description (cif and exchange_* fields)
447 self.fb_alloc(llmemory.sizeof(CIF_DESCRIPTION, nargs))
448
449 # next comes an array of 'ffi_type*', one per argument
450 atypes = self.fb_alloc(rffi.sizeof(FFI_TYPE_P) * nargs)
451 self.atypes = rffi.cast(FFI_TYPE_PP, atypes)
452
453 # next comes the result type data
454 self.rtype = self.fb_fill_type(self.fresult, True)
455
456 # next comes each argument's type data
457 for i, farg in enumerate(self.fargs):
458 atype = self.fb_fill_type(farg, False)
459 if self.atypes:
460 self.atypes[i] = atype
461
462 def align_arg(self, n):
463 return (n + 7) & ~7
464
465 def align_to(self, n, type):
466 a = rffi.getintfield(type, 'c_alignment') - 1
467 return (n + a) & ~a
468
469 def fb_build_exchange(self, cif_descr):
470 nargs = len(self.fargs)
471
472 # first, enough room for an array of 'nargs' pointers
473 exchange_offset = rffi.sizeof(rffi.CCHARP) * nargs
474
475 # then enough room for the result --- which means at least
476 # sizeof(ffi_arg), according to the ffi docs, but we also
477 # align according to the result type, for cffi issue #531
478 exchange_offset = self.align_to(exchange_offset, self.rtype)
479 exchange_offset = self.align_arg(exchange_offset)
480 cif_descr.exchange_result = exchange_offset
481 exchange_offset += max(rffi.getintfield(self.rtype, 'c_size'),
482 SIZE_OF_FFI_ARG)
483
484 # loop over args
485 for i, farg in enumerate(self.fargs):
486 if isinstance(farg, W_CTypePointer):
487 exchange_offset += 1 # for the "must free" flag
488 atype = self.atypes[i]
489 exchange_offset = self.align_to(exchange_offset, atype)
490 exchange_offset = self.align_arg(exchange_offset)
491 cif_descr.exchange_args[i] = exchange_offset
492 exchange_offset += rffi.getintfield(atype, 'c_size')
493
494 # store the exchange data size
495 # we also align it to the next multiple of 8, in an attempt to
496 # work around bugs(?) of libffi (see cffi issue #241)
497 cif_descr.exchange_size = self.align_arg(exchange_offset)
498
499 def fb_extra_fields(self, cif_descr):
500 cif_descr.abi = self.fabi
501 cif_descr.nargs = len(self.fargs)
502 cif_descr.rtype = self.rtype
503 cif_descr.atypes = self.atypes
504
505 @jit.dont_look_inside
506 def rawallocate(self, ctypefunc):
507 space = ctypefunc.space
508 self.space = space
509
510 # compute the total size needed in the CIF_DESCRIPTION buffer
511 self.nb_bytes = 0
512 self.bufferp = lltype.nullptr(rffi.CCHARP.TO)
513 self.fb_build()
514
515 # allocate the buffer
516 if we_are_translated():
517 rawmem = lltype.malloc(rffi.CCHARP.TO, self.nb_bytes,
518 flavor='raw')
519 rawmem = rffi.cast(CIF_DESCRIPTION_P, rawmem)
520 else:
521 # gross overestimation of the length below, but too bad
522 rawmem = lltype.malloc(CIF_DESCRIPTION_P.TO, self.nb_bytes,
523 flavor='raw')
524
525 # the buffer is automatically managed from the W_CTypeFunc instance
526 ctypefunc.cif_descr = rawmem
527
528 # call again fb_build() to really build the libffi data structures
529 self.bufferp = rffi.cast(rffi.CCHARP, rawmem)
530 self.fb_build()
531 assert self.bufferp == rffi.ptradd(rffi.cast(rffi.CCHARP, rawmem),
532 self.nb_bytes)
533
534 # fill in the 'exchange_*' fields
535 self.fb_build_exchange(rawmem)
536
537 # fill in the extra fields
538 self.fb_extra_fields(rawmem)
539
540 # call libffi's ffi_prep_cif() function
541 res = jit_libffi.jit_ffi_prep_cif(rawmem)
542 if res != clibffi.FFI_OK:
543 raise oefmt(space.w_SystemError,
544 "libffi failed to build this function type")