Debian Codegraph @

src/c/call_python.c

raw
1 static PyObject *_current_interp_key(void)
2 {
3 PyInterpreterState *interp = PyInterpreterState_Get();
4 return PyInterpreterState_GetDict(interp); /* shared reference */
5 }
6
7 static PyObject *_get_interpstate_dict(void)
8 {
9 /* Hack around to return a dict that is subinterpreter-local.
10 Does not return a new reference. Returns NULL in case of
11 error, but without setting any exception. (If called late
12 during shutdown, we *can't* set an exception!)
13 */
14 static PyObject *attr_name = NULL;
15 PyThreadState *tstate;
16 PyObject *d, *interpdict;
17 int err;
18 PyInterpreterState *interp;
19
20 #if PY_VERSION_HEX >= 0x030D0000
21 tstate = PyThreadState_GetUnchecked();
22 #else
23 tstate = _PyThreadState_UncheckedGet();
24 #endif
25 if (tstate == NULL) {
26 /* no thread state! */
27 return NULL;
28 }
29
30 interp = PyThreadState_GetInterpreter(tstate);
31 interpdict = PyInterpreterState_GetDict(interp); /* shared reference */
32 if (interpdict == NULL) {
33 /* subinterpreter was cleared already, or is being cleared right now,
34 to a point that is too much for us to continue */
35 return NULL;
36 }
37
38 /* from there on, we know the (sub-)interpreter is still valid */
39
40 if (attr_name == NULL) {
41 attr_name = PyUnicode_InternFromString("__cffi_backend_extern_py");
42 if (attr_name == NULL)
43 goto error;
44 }
45
46 d = PyDict_GetItem(interpdict, attr_name);
47 if (d == NULL) {
48 d = PyDict_New();
49 if (d == NULL)
50 goto error;
51 err = PyDict_SetItem(interpdict, attr_name, d);
52 Py_DECREF(d); /* if successful, there is one ref left in interpdict */
53 if (err < 0)
54 goto error;
55 }
56 return d;
57
58 error:
59 PyErr_Clear(); /* typically a MemoryError */
60 return NULL;
61 }
62
63 static PyObject *_ffi_def_extern_decorator(PyObject *outer_args, PyObject *fn)
64 {
65 const char *s;
66 PyObject *error, *onerror, *infotuple, *old1;
67 int index, err;
68 const struct _cffi_global_s *g;
69 struct _cffi_externpy_s *externpy;
70 CTypeDescrObject *ct;
71 FFIObject *ffi;
72 builder_c_t *types_builder;
73 PyObject *name = NULL;
74 PyObject *interpstate_dict;
75 PyObject *interpstate_key;
76
77 if (!PyArg_ParseTuple(outer_args, "OzOO", &ffi, &s, &error, &onerror))
78 return NULL;
79
80 if (s == NULL) {
81 name = PyObject_GetAttrString(fn, "__name__");
82 if (name == NULL)
83 return NULL;
84 s = PyUnicode_AsUTF8(name);
85 if (s == NULL) {
86 Py_DECREF(name);
87 return NULL;
88 }
89 }
90
91 types_builder = &ffi->types_builder;
92 index = search_in_globals(&types_builder->ctx, s, strlen(s));
93 if (index < 0)
94 goto not_found;
95 g = &types_builder->ctx.globals[index];
96 if (_CFFI_GETOP(g->type_op) != _CFFI_OP_EXTERN_PYTHON)
97 goto not_found;
98 Py_XDECREF(name);
99
100 ct = realize_c_type(types_builder, types_builder->ctx.types,
101 _CFFI_GETARG(g->type_op));
102 if (ct == NULL)
103 return NULL;
104
105 infotuple = prepare_callback_info_tuple(ct, fn, error, onerror, 0);
106 Py_DECREF(ct);
107 if (infotuple == NULL)
108 return NULL;
109
110 /* don't directly attach infotuple to externpy: in the presence of
111 subinterpreters, each time we switch to a different
112 subinterpreter and call the C function, it will notice the
113 change and look up infotuple from the interpstate_dict.
114 */
115 interpstate_dict = _get_interpstate_dict();
116 if (interpstate_dict == NULL) {
117 Py_DECREF(infotuple);
118 return PyErr_NoMemory();
119 }
120
121 externpy = (struct _cffi_externpy_s *)g->address;
122 interpstate_key = PyLong_FromVoidPtr((void *)externpy);
123 if (interpstate_key == NULL) {
124 Py_DECREF(infotuple);
125 return NULL;
126 }
127
128 err = PyDict_SetItem(interpstate_dict, interpstate_key, infotuple);
129 Py_DECREF(interpstate_key);
130 Py_DECREF(infotuple); /* interpstate_dict owns the last ref */
131 if (err < 0)
132 return NULL;
133
134 /* force _update_cache_to_call_python() to be called the next time
135 the C function invokes cffi_call_python, to update the cache */
136 old1 = externpy->reserved1;
137 externpy->reserved1 = Py_None; /* a non-NULL value */
138 Py_INCREF(Py_None);
139 Py_XDECREF(old1);
140
141 /* return the function object unmodified */
142 Py_INCREF(fn);
143 return fn;
144
145 not_found:
146 PyErr_Format(FFIError, "ffi.def_extern('%s'): no 'extern \"Python\"' "
147 "function with this name", s);
148 Py_XDECREF(name);
149 return NULL;
150 }
151
152
153 static int _update_cache_to_call_python(struct _cffi_externpy_s *externpy)
154 {
155 PyObject *interpstate_dict, *interpstate_key, *infotuple, *old1, *new1;
156 PyObject *old2;
157
158 interpstate_dict = _get_interpstate_dict();
159 if (interpstate_dict == NULL)
160 return 4; /* oops, shutdown issue? */
161
162 interpstate_key = PyLong_FromVoidPtr((void *)externpy);
163 if (interpstate_key == NULL)
164 goto error;
165
166 infotuple = PyDict_GetItem(interpstate_dict, interpstate_key);
167 Py_DECREF(interpstate_key);
168 if (infotuple == NULL)
169 return 3; /* no ffi.def_extern() from this subinterpreter */
170
171 new1 = _current_interp_key();
172 Py_INCREF(new1);
173 Py_INCREF(infotuple);
174 old1 = (PyObject *)externpy->reserved1;
175 old2 = (PyObject *)externpy->reserved2;
176 externpy->reserved1 = new1; /* holds a reference */
177 externpy->reserved2 = infotuple; /* holds a reference (issue #246) */
178 Py_XDECREF(old1);
179 Py_XDECREF(old2);
180
181 return 0; /* no error */
182
183 error:
184 PyErr_Clear();
185 return 2; /* out of memory? */
186 }
187
188 #if (defined(WITH_THREAD) && !defined(_MSC_VER) && \
189 !defined(__amd64__) && !defined(__x86_64__) && \
190 !defined(__i386__) && !defined(__i386))
191 # if defined(HAVE_SYNC_SYNCHRONIZE)
192 # define read_barrier() __sync_synchronize()
193 # elif defined(_AIX)
194 # define read_barrier() __lwsync()
195 # elif defined(__SUNPRO_C) || defined(__SUNPRO_CC)
196 # include <mbarrier.h>
197 # define read_barrier() __compiler_barrier()
198 # elif defined(__hpux)
199 # define read_barrier() _Asm_mf()
200 # else
201 # define read_barrier() /* missing */
202 # warning "no definition for read_barrier(), missing synchronization for\
203 multi-thread initialization in embedded mode"
204 # endif
205 #else
206 # define read_barrier() (void)0
207 #endif
208
209 static void cffi_call_python(struct _cffi_externpy_s *externpy, char *args)
210 {
211 /* Invoked by the helpers generated from extern "Python" in the cdef.
212
213 'externpy' is a static structure that describes which of the
214 extern "Python" functions is called. It has got fields 'name' and
215 'type_index' describing the function, and more reserved fields
216 that are initially zero. These reserved fields are set up by
217 ffi.def_extern(), which invokes _ffi_def_extern_decorator() above.
218
219 'args' is a pointer to an array of 8-byte entries. Each entry
220 contains an argument. If an argument is less than 8 bytes, only
221 the part at the beginning of the entry is initialized. If an
222 argument is 'long double' or a struct/union, then it is passed
223 by reference.
224
225 'args' is also used as the place to write the result to
226 (directly, even if more than 8 bytes). In all cases, 'args' is
227 at least 8 bytes in size.
228 */
229 int err = 0;
230
231 /* This read barrier is needed for _embedding.h. It is paired
232 with the write_barrier() there. Without this barrier, we can
233 in theory see the following situation: the Python
234 initialization code already ran (in another thread), and the
235 '_cffi_call_python' function pointer directed execution here;
236 but any number of other data could still be seen as
237 uninitialized below. For example, 'externpy' would still
238 contain NULLs even though it was correctly set up, or
239 'interpreter_lock' (the GIL inside CPython) would still be seen
240 as NULL, or 'autoInterpreterState' (used by
241 PyGILState_Ensure()) would be NULL or contain bogus fields.
242 */
243 read_barrier();
244
245 save_errno();
246
247 /* We need the infotuple here. We could always go through
248 _update_cache_to_call_python(), but to avoid the extra dict
249 lookups, we cache in (reserved1, reserved2) the last seen pair
250 (interp->modules, infotuple). The first item in this tuple is
251 a random PyObject that identifies the subinterpreter.
252 */
253 if (externpy->reserved1 == NULL) {
254 /* Not initialized! We didn't call @ffi.def_extern() on this
255 externpy object from any subinterpreter at all. */
256 err = 1;
257 }
258 else {
259 PyGILState_STATE state = gil_ensure();
260 if (externpy->reserved1 != _current_interp_key()) {
261 /* Update the (reserved1, reserved2) cache. This will fail
262 if we didn't call @ffi.def_extern() in this particular
263 subinterpreter. */
264 err = _update_cache_to_call_python(externpy);
265 }
266 if (!err) {
267 general_invoke_callback(0, args, args, externpy->reserved2);
268 }
269 gil_release(state);
270 }
271 if (err) {
272 static const char *msg[] = {
273 "no code was attached to it yet with @ffi.def_extern()",
274 "got internal exception (out of memory?)",
275 "@ffi.def_extern() was not called in the current subinterpreter",
276 "got internal exception (shutdown issue?)",
277 };
278 fprintf(stderr, "extern \"Python\": function %s() called, "
279 "but %s. Returning 0.\n", externpy->name, msg[err-1]);
280 memset(args, 0, externpy->size_of_result);
281 }
282 restore_errno();
283 }