Debian Codegraph @

pypy/module/_rawffi/callback.py

raw symbols SCIP
1 import sys
2 from pypy.interpreter.gateway import interp2app, unwrap_spec
3 from pypy.interpreter.typedef import TypeDef, GetSetProperty
4 from rpython.rtyper.lltypesystem import lltype, rffi
5 from pypy.module._rawffi.interp_rawffi import write_ptr
6 from pypy.module._rawffi.structure import W_Structure
7 from pypy.module._rawffi.interp_rawffi import (W_DataInstance, letter2tp,
8 unwrap_value, unpack_argshapes, got_libffi_error, is_narrow_integer_type,
9 LL_TYPEMAP, NARROW_INTEGER_TYPES)
10 from rpython.rlib.clibffi import USERDATA_P, CallbackFuncPtr, FUNCFLAG_CDECL
11 from rpython.rlib.clibffi import ffi_type_void, LibFFIError
12 from rpython.rlib import rweakref
13 from pypy.module._rawffi.tracker import tracker
14 from pypy.interpreter.error import OperationError
15 from pypy.interpreter import gateway
16 from rpython.rlib.unroll import unrolling_iterable
17
18 BIGENDIAN = sys.byteorder == 'big'
19
20 unroll_narrow_integer_types = unrolling_iterable(NARROW_INTEGER_TYPES)
21
22 app = gateway.applevel('''
23 def tbprint(tb, err):
24 import traceback, sys
25 traceback.print_tb(tb)
26 print(err, file=sys.stderr)
27 ''', filename=__file__)
28
29 tbprint = app.interphook("tbprint")
30
31 def callback(ll_args, ll_res, ll_userdata):
32 userdata = rffi.cast(USERDATA_P, ll_userdata)
33 callback_ptr = global_counter.get(userdata.addarg)
34 w_callable = callback_ptr.w_callable
35 argtypes = callback_ptr.argtypes
36 must_leave = False
37 space = callback_ptr.space
38 try:
39 must_leave = space.threadlocals.try_enter_thread(space)
40 args_w = [None] * len(argtypes)
41 for i in range(len(argtypes)):
42 argtype = argtypes[i]
43 if isinstance(argtype, W_Structure):
44 args_w[i] = argtype.fromaddress(
45 space, rffi.cast(rffi.SIZE_T, ll_args[i]))
46 else:
47 # XXX other types?
48 args_w[i] = space.newint(rffi.cast(lltype.Unsigned, ll_args[i]))
49 w_res = space.call(w_callable, space.newtuple(args_w))
50 if callback_ptr.result is not None: # don't return void
51 ptr = ll_res
52 letter = callback_ptr.result
53 if BIGENDIAN:
54 # take care of narrow integers!
55 for int_type in unroll_narrow_integer_types:
56 if int_type == letter:
57 T = LL_TYPEMAP[int_type]
58 n = rffi.sizeof(lltype.Signed) - rffi.sizeof(T)
59 ptr = rffi.ptradd(ptr, n)
60 break
61 unwrap_value(space, write_ptr, ptr, 0, letter, w_res)
62 except OperationError as e:
63 tbprint(space, e.get_w_traceback(space),
64 space.newtext(e.errorstr(space)))
65 # force the result to be zero
66 if callback_ptr.result is not None:
67 resshape = letter2tp(space, callback_ptr.result)
68 for i in range(resshape.size):
69 ll_res[i] = '\x00'
70 if must_leave:
71 space.threadlocals.leave_thread(space)
72
73 class W_CallbackPtr(W_DataInstance):
74
75 def __init__(self, space, w_callable, w_args, w_result,
76 flags=FUNCFLAG_CDECL):
77 self.space = space
78 self.w_callable = w_callable
79 self.argtypes = unpack_argshapes(space, w_args)
80 ffiargs = [tp.get_basic_ffi_type() for tp in self.argtypes]
81 if not space.is_w(w_result, space.w_None):
82 self.result = space.text_w(w_result)
83 ffiresult = letter2tp(space, self.result).get_basic_ffi_type()
84 else:
85 self.result = None
86 ffiresult = ffi_type_void
87 self.number = global_counter.add(self)
88 try:
89 self.ll_callback = CallbackFuncPtr(ffiargs, ffiresult,
90 callback, self.number, flags)
91 except LibFFIError:
92 raise got_libffi_error(space)
93 self.ll_buffer = rffi.cast(rffi.VOIDP, self.ll_callback.get_closure())
94 if tracker.DO_TRACING:
95 addr = rffi.cast(lltype.Signed, self.ll_callback.get_closure())
96 tracker.trace_allocation(addr, self)
97 #
98 # We must setup the GIL here, in case the callback is invoked in
99 # some other non-Pythonic thread. This is the same as ctypes on
100 # CPython (but only when creating a callback; on CPython it occurs
101 # as soon as we import _ctypes)
102 if space.config.translation.thread:
103 from pypy.module.thread.os_thread import setup_threads
104 setup_threads(space)
105
106 def free(self):
107 if tracker.DO_TRACING:
108 addr = rffi.cast(lltype.Signed, self.ll_callback.get_closure())
109 tracker.trace_free(addr)
110 global_counter.remove(self.number)
111
112 # A global storage to be able to recover W_CallbackPtr object out of number
113 class GlobalCounter:
114 def __init__(self):
115 self.callback_id = 0
116 self.callbacks = rweakref.RWeakValueDictionary(int, W_CallbackPtr)
117
118 def add(self, w_callback):
119 self.callback_id += 1
120 id = self.callback_id
121 self.callbacks.set(id, w_callback)
122 return id
123
124 def remove(self, id):
125 self.callbacks.set(id, None)
126
127 def get(self, id):
128 return self.callbacks.get(id)
129
130 global_counter = GlobalCounter()
131
132 @unwrap_spec(flags=int)
133 def descr_new_callbackptr(space, w_type, w_callable, w_args, w_result,
134 flags=FUNCFLAG_CDECL):
135 return W_CallbackPtr(space, w_callable, w_args, w_result, flags)
136
137 W_CallbackPtr.typedef = TypeDef(
138 'CallbackPtr', None, None, "read",
139 __new__ = interp2app(descr_new_callbackptr),
140 byptr = interp2app(W_CallbackPtr.byptr),
141 buffer = GetSetProperty(W_CallbackPtr.getbuffer),
142 free = interp2app(W_CallbackPtr.free),
143 )