Debian Codegraph @

Modules/_ctypes/callbacks.c

raw
1 #ifndef Py_BUILD_CORE_BUILTIN
2 # define Py_BUILD_CORE_MODULE 1
3 #endif
4
5 #include "Python.h"
6 // windows.h must be included before pycore internal headers
7 #ifdef MS_WIN32
8 # include <windows.h>
9 #endif
10
11 #include "pycore_call.h" // _PyObject_CallNoArgs()
12 #include "pycore_runtime.h" // _Py_ID()
13
14 #include <stdbool.h>
15
16 #ifdef MS_WIN32
17 # include <malloc.h>
18 #endif
19
20 #include <ffi.h>
21 #include "ctypes.h"
22
23 #ifdef HAVE_ALLOCA_H
24 /* AIX needs alloca.h for alloca() */
25 #include <alloca.h>
26 #endif
27
28 /**************************************************************/
29
30 static int
31 CThunkObject_traverse(PyObject *myself, visitproc visit, void *arg)
32 {
33 CThunkObject *self = (CThunkObject *)myself;
34 Py_VISIT(Py_TYPE(self));
35 Py_VISIT(self->converters);
36 Py_VISIT(self->callable);
37 Py_VISIT(self->restype);
38 return 0;
39 }
40
41 static int
42 CThunkObject_clear(PyObject *myself)
43 {
44 CThunkObject *self = (CThunkObject *)myself;
45 Py_CLEAR(self->converters);
46 Py_CLEAR(self->callable);
47 Py_CLEAR(self->restype);
48 return 0;
49 }
50
51 static void
52 CThunkObject_dealloc(PyObject *myself)
53 {
54 CThunkObject *self = (CThunkObject *)myself;
55 PyTypeObject *tp = Py_TYPE(myself);
56 PyObject_GC_UnTrack(self);
57 (void)CThunkObject_clear(myself);
58 if (self->pcl_write) {
59 Py_ffi_closure_free(self->pcl_write);
60 }
61 PyObject_GC_Del(self);
62 Py_DECREF(tp);
63 }
64
65 static PyType_Slot cthunk_slots[] = {
66 {Py_tp_doc, (void *)PyDoc_STR("CThunkObject")},
67 {Py_tp_dealloc, CThunkObject_dealloc},
68 {Py_tp_traverse, CThunkObject_traverse},
69 {Py_tp_clear, CThunkObject_clear},
70 {0, NULL},
71 };
72
73 PyType_Spec cthunk_spec = {
74 .name = "_ctypes.CThunkObject",
75 .basicsize = sizeof(CThunkObject),
76 .itemsize = sizeof(ffi_type),
77 .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
78 Py_TPFLAGS_IMMUTABLETYPE | Py_TPFLAGS_DISALLOW_INSTANTIATION),
79 .slots = cthunk_slots,
80 };
81
82 /**************************************************************/
83
84 #ifdef MS_WIN32
85 /*
86 * We must call AddRef() on non-NULL COM pointers we receive as arguments
87 * to callback functions - these functions are COM method implementations.
88 * The Python instances we create have a __del__ method which calls Release().
89 *
90 * The presence of a class attribute named '_needs_com_addref_' triggers this
91 * behaviour. It would also be possible to call the AddRef() Python method,
92 * after checking for PyObject_IsTrue(), but this would probably be somewhat
93 * slower.
94 */
95 static int
96 TryAddRef(PyObject *cnv, CDataObject *obj)
97 {
98 IUnknown *punk;
99 PyObject *attrdict = _PyType_GetDict((PyTypeObject *)cnv);
100 if (!attrdict) {
101 return 0;
102 }
103 int r = PyDict_Contains(attrdict, &_Py_ID(_needs_com_addref_));
104 if (r <= 0) {
105 return r;
106 }
107
108 punk = *(IUnknown **)obj->b_ptr;
109 if (punk)
110 punk->lpVtbl->AddRef(punk);
111 return 0;
112 }
113 #endif
114
115 /******************************************************************************
116 *
117 * Call the python object with all arguments
118 *
119 */
120
121 // BEWARE: The GIL needs to be held throughout the function
122 static void _CallPythonObject(ctypes_state *st,
123 void *mem,
124 ffi_type *restype,
125 SETFUNC setfunc,
126 PyObject *callable,
127 PyObject *converters,
128 int flags,
129 void **pArgs)
130 {
131 PyObject *result = NULL;
132 Py_ssize_t i = 0, j = 0, nargs = 0;
133 PyObject *error_object = NULL;
134 int *space;
135
136 assert(PyTuple_Check(converters));
137 nargs = PyTuple_GET_SIZE(converters);
138 assert(nargs <= CTYPES_MAX_ARGCOUNT);
139 PyObject **args = alloca(nargs * sizeof(PyObject *));
140 PyObject **cnvs = PySequence_Fast_ITEMS(converters);
141 for (i = 0; i < nargs; i++) {
142 PyObject *cnv = cnvs[i]; // borrowed ref
143
144 StgInfo *info;
145 if (PyStgInfo_FromType(st, cnv, &info) < 0) {
146 goto Error;
147 }
148
149 if (info && info->getfunc && !_ctypes_simple_instance(st, cnv)) {
150 PyObject *v = info->getfunc(*pArgs, info->size);
151 if (!v) {
152 goto Error;
153 }
154 args[i] = v;
155 /* XXX XXX XX
156 We have the problem that c_byte or c_short have info->size of
157 1 resp. 4, but these parameters are pushed as sizeof(int) bytes.
158 BTW, the same problem occurs when they are pushed as parameters
159 */
160 }
161 else if (info) {
162 /* Hm, shouldn't we use PyCData_AtAddress() or something like that instead? */
163 CDataObject *obj = (CDataObject *)_PyObject_CallNoArgs(cnv);
164 if (!obj) {
165 goto Error;
166 }
167 if (!CDataObject_Check(st, obj)) {
168 PyErr_Format(PyExc_TypeError,
169 "%R returned unexpected result of type %T", cnv, obj);
170 Py_DECREF(obj);
171 goto Error;
172 }
173 memcpy(obj->b_ptr, *pArgs, info->size);
174 args[i] = (PyObject *)obj;
175 #ifdef MS_WIN32
176 if (TryAddRef(cnv, obj) < 0) {
177 goto Error;
178 }
179 #endif
180 } else {
181 PyErr_Format(PyExc_TypeError,
182 "cannot build parameter of type %R", cnv);
183 goto Error;
184 }
185 /* XXX error handling! */
186 pArgs++;
187 }
188
189 if (flags & (FUNCFLAG_USE_ERRNO | FUNCFLAG_USE_LASTERROR)) {
190 error_object = _ctypes_get_errobj(st, &space);
191 if (error_object == NULL) {
192 PyErr_FormatUnraisable(
193 "Exception ignored while setting error for "
194 "ctypes callback function %R",
195 callable);
196 goto Done;
197 }
198 if (flags & FUNCFLAG_USE_ERRNO) {
199 int temp = space[0];
200 space[0] = errno;
201 errno = temp;
202 }
203 #ifdef MS_WIN32
204 if (flags & FUNCFLAG_USE_LASTERROR) {
205 int temp = space[1];
206 space[1] = GetLastError();
207 SetLastError(temp);
208 }
209 #endif
210 }
211
212 result = PyObject_Vectorcall(callable, args, nargs, NULL);
213 if (result == NULL) {
214 PyErr_FormatUnraisable(
215 "Exception ignored on calling ctypes callback function %R",
216 callable);
217 }
218
219 #ifdef MS_WIN32
220 if (flags & FUNCFLAG_USE_LASTERROR) {
221 int temp = space[1];
222 space[1] = GetLastError();
223 SetLastError(temp);
224 }
225 #endif
226 if (flags & FUNCFLAG_USE_ERRNO) {
227 int temp = space[0];
228 space[0] = errno;
229 errno = temp;
230 }
231 Py_XDECREF(error_object);
232
233 if (restype != &ffi_type_void && result) {
234 assert(setfunc);
235
236 #ifdef WORDS_BIGENDIAN
237 /* See the corresponding code in _ctypes_callproc():
238 in callproc.c, around line 1219. */
239 if (restype->type != FFI_TYPE_FLOAT && restype->size < sizeof(ffi_arg)) {
240 mem = (char *)mem + sizeof(ffi_arg) - restype->size;
241 }
242 #endif
243
244 /* keep is an object we have to keep alive so that the result
245 stays valid. If there is no such object, the setfunc will
246 have returned Py_None.
247
248 If there is such an object, we have no choice than to keep
249 it alive forever - but a refcount and/or memory leak will
250 be the result. EXCEPT when restype is py_object - Python
251 itself knows how to manage the refcount of these objects.
252 */
253 PyObject *keep = setfunc(mem, result, 0);
254
255 if (keep == NULL) {
256 /* Could not convert callback result. */
257 PyErr_FormatUnraisable(
258 "Exception ignored on converting result "
259 "of ctypes callback function %R",
260 callable);
261 }
262 else if (setfunc != _ctypes_get_fielddesc("O")->setfunc) {
263 if (keep == Py_None) {
264 /* Nothing to keep */
265 Py_DECREF(keep);
266 }
267 else if (PyErr_WarnEx(PyExc_RuntimeWarning,
268 "memory leak in callback function.",
269 1) == -1) {
270 PyErr_FormatUnraisable(
271 "Exception ignored on converting result "
272 "of ctypes callback function %R",
273 callable);
274 }
275 }
276 }
277
278 Py_XDECREF(result);
279
280 Done:
281 for (j = 0; j < i; j++) {
282 Py_DECREF(args[j]);
283 }
284 return;
285
286 Error:
287 PyErr_FormatUnraisable(
288 "Exception ignored while creating argument %zd for "
289 "ctypes callback function %R",
290 i, callable);
291 goto Done;
292 }
293
294 static void closure_fcn(ffi_cif *cif,
295 void *resp,
296 void **args,
297 void *userdata)
298 {
299 PyGILState_STATE state = PyGILState_Ensure();
300
301 CThunkObject *p = (CThunkObject *)userdata;
302 ctypes_state *st = get_module_state_by_class(Py_TYPE(p));
303
304 _CallPythonObject(st,
305 resp,
306 p->ffi_restype,
307 p->setfunc,
308 p->callable,
309 p->converters,
310 p->flags,
311 args);
312
313 PyGILState_Release(state);
314 }
315
316 static CThunkObject* CThunkObject_new(ctypes_state *st, Py_ssize_t nargs)
317 {
318 CThunkObject *p;
319 Py_ssize_t i;
320
321 p = PyObject_GC_NewVar(CThunkObject, st->PyCThunk_Type, nargs);
322 if (p == NULL) {
323 return NULL;
324 }
325
326 p->pcl_write = NULL;
327 p->pcl_exec = NULL;
328 memset(&p->cif, 0, sizeof(p->cif));
329 p->flags = 0;
330 p->converters = NULL;
331 p->callable = NULL;
332 p->restype = NULL;
333 p->setfunc = NULL;
334 p->ffi_restype = NULL;
335
336 for (i = 0; i < nargs + 1; ++i)
337 p->atypes[i] = NULL;
338 PyObject_GC_Track((PyObject *)p);
339 return p;
340 }
341
342 CThunkObject *_ctypes_alloc_callback(ctypes_state *st,
343 PyObject *callable,
344 PyObject *converters,
345 PyObject *restype,
346 int flags)
347 {
348 int result;
349 CThunkObject *p;
350 Py_ssize_t nargs, i;
351 ffi_abi cc;
352
353 assert(PyTuple_Check(converters));
354 nargs = PyTuple_GET_SIZE(converters);
355 p = CThunkObject_new(st, nargs);
356 if (p == NULL)
357 return NULL;
358
359 assert(CThunk_CheckExact(st, (PyObject *)p));
360
361 p->pcl_write = Py_ffi_closure_alloc(sizeof(ffi_closure), &p->pcl_exec);
362 if (p->pcl_write == NULL) {
363 PyErr_NoMemory();
364 goto error;
365 }
366
367 p->flags = flags;
368 PyObject **cnvs = PySequence_Fast_ITEMS(converters);
369 for (i = 0; i < nargs; ++i) {
370 PyObject *cnv = cnvs[i]; // borrowed ref
371 p->atypes[i] = _ctypes_get_ffi_type(st, cnv);
372 }
373 p->atypes[i] = NULL;
374
375 p->restype = Py_NewRef(restype);
376 if (restype == Py_None) {
377 p->setfunc = NULL;
378 p->ffi_restype = &ffi_type_void;
379 } else {
380 StgInfo *info;
381 if (PyStgInfo_FromType(st, restype, &info) < 0) {
382 goto error;
383 }
384
385 if (info == NULL || info->setfunc == NULL) {
386 PyErr_SetString(PyExc_TypeError,
387 "invalid result type for callback function");
388 goto error;
389 }
390 p->setfunc = info->setfunc;
391 p->ffi_restype = &info->ffi_type_pointer;
392 }
393
394 cc = FFI_DEFAULT_ABI;
395 #if defined(MS_WIN32) && !defined(_WIN32_WCE) && !defined(MS_WIN64) && !defined(_M_ARM)
396 if ((flags & FUNCFLAG_CDECL) == 0)
397 cc = FFI_STDCALL;
398 #endif
399 result = ffi_prep_cif(&p->cif, cc,
400 Py_SAFE_DOWNCAST(nargs, Py_ssize_t, int),
401 p->ffi_restype,
402 &p->atypes[0]);
403 if (result != FFI_OK) {
404 PyErr_Format(PyExc_RuntimeError,
405 "ffi_prep_cif failed with %d", result);
406 goto error;
407 }
408
409
410 #if HAVE_FFI_PREP_CLOSURE_LOC
411 # ifdef USING_APPLE_OS_LIBFFI
412 # ifdef HAVE_BUILTIN_AVAILABLE
413 # define HAVE_FFI_PREP_CLOSURE_LOC_RUNTIME __builtin_available(macos 10.15, ios 13, watchos 6, tvos 13, *)
414 # else
415 # define HAVE_FFI_PREP_CLOSURE_LOC_RUNTIME (ffi_prep_closure_loc != NULL)
416 # endif
417 # else
418 # define HAVE_FFI_PREP_CLOSURE_LOC_RUNTIME 1
419 # endif
420 if (HAVE_FFI_PREP_CLOSURE_LOC_RUNTIME) {
421 result = ffi_prep_closure_loc(p->pcl_write, &p->cif, closure_fcn,
422 p,
423 p->pcl_exec);
424 } else
425 #endif
426 {
427 #if defined(USING_APPLE_OS_LIBFFI) && defined(__arm64__)
428 PyErr_Format(PyExc_NotImplementedError, "ffi_prep_closure_loc() is missing");
429 goto error;
430 #else
431 // GH-85272, GH-23327, GH-100540: On macOS,
432 // HAVE_FFI_PREP_CLOSURE_LOC_RUNTIME is checked at runtime because the
433 // symbol might not be available at runtime when targeting macOS 10.14
434 // or earlier. Even if ffi_prep_closure_loc() is called in practice,
435 // the deprecated ffi_prep_closure() code path is needed if
436 // HAVE_FFI_PREP_CLOSURE_LOC_RUNTIME is false.
437 //
438 // On non-macOS platforms, even if HAVE_FFI_PREP_CLOSURE_LOC_RUNTIME is
439 // defined as 1 and ffi_prep_closure_loc() is used in practice, this
440 // code path is still compiled and emits a compiler warning. The
441 // deprecated code path is likely to be removed by a simple
442 // optimization pass.
443 //
444 // Ignore the compiler warning on the ffi_prep_closure() deprecation,
445 // rather than using complex #if/#else code paths for the different
446 // platforms.
447 _Py_COMP_DIAG_PUSH
448 _Py_COMP_DIAG_IGNORE_DEPR_DECLS
449 result = ffi_prep_closure(p->pcl_write, &p->cif, closure_fcn, p);
450 _Py_COMP_DIAG_POP
451 #endif
452 }
453
454 if (result != FFI_OK) {
455 PyErr_Format(PyExc_RuntimeError,
456 "ffi_prep_closure failed with %d", result);
457 goto error;
458 }
459
460 p->converters = Py_NewRef(converters);
461 p->callable = Py_NewRef(callable);
462 return p;
463
464 error:
465 Py_XDECREF(p);
466 return NULL;
467 }
468
469 #ifdef MS_WIN32
470
471 static void LoadPython(void)
472 {
473 if (!Py_IsInitialized()) {
474 Py_Initialize();
475 }
476 }
477
478 /******************************************************************/
479
480 long Call_GetClassObject(REFCLSID rclsid, REFIID riid, LPVOID *ppv)
481 {
482 PyObject *func, *result;
483 long retval;
484 static PyObject *context;
485
486 if (context == NULL)
487 context = PyUnicode_InternFromString("_ctypes.DllGetClassObject");
488
489 func = _PyImport_GetModuleAttrString("ctypes", "DllGetClassObject");
490 if (!func) {
491 PyErr_WriteUnraisable(context ? context : Py_None);
492 /* There has been a warning before about this already */
493 return E_FAIL;
494 }
495
496 {
497 PyObject *py_rclsid = PyLong_FromVoidPtr((void *)rclsid);
498 if (py_rclsid == NULL) {
499 Py_DECREF(func);
500 PyErr_WriteUnraisable(context ? context : Py_None);
501 return E_FAIL;
502 }
503 PyObject *py_riid = PyLong_FromVoidPtr((void *)riid);
504 if (py_riid == NULL) {
505 Py_DECREF(func);
506 Py_DECREF(py_rclsid);
507 PyErr_WriteUnraisable(context ? context : Py_None);
508 return E_FAIL;
509 }
510 PyObject *py_ppv = PyLong_FromVoidPtr(ppv);
511 if (py_ppv == NULL) {
512 Py_DECREF(py_rclsid);
513 Py_DECREF(py_riid);
514 Py_DECREF(func);
515 PyErr_WriteUnraisable(context ? context : Py_None);
516 return E_FAIL;
517 }
518 result = PyObject_CallFunctionObjArgs(func,
519 py_rclsid,
520 py_riid,
521 py_ppv,
522 NULL);
523 Py_DECREF(py_rclsid);
524 Py_DECREF(py_riid);
525 Py_DECREF(py_ppv);
526 }
527 Py_DECREF(func);
528 if (!result) {
529 PyErr_WriteUnraisable(context ? context : Py_None);
530 return E_FAIL;
531 }
532
533 retval = PyLong_AsLong(result);
534 if (PyErr_Occurred()) {
535 PyErr_WriteUnraisable(context ? context : Py_None);
536 retval = E_FAIL;
537 }
538 Py_DECREF(result);
539 return retval;
540 }
541
542 STDAPI DllGetClassObject(REFCLSID rclsid,
543 REFIID riid,
544 LPVOID *ppv)
545 {
546 long result;
547 PyGILState_STATE state;
548
549 LoadPython();
550 state = PyGILState_Ensure();
551 result = Call_GetClassObject(rclsid, riid, ppv);
552 PyGILState_Release(state);
553 return result;
554 }
555
556 long Call_CanUnloadNow(void)
557 {
558 PyObject *mod, *func, *result;
559 long retval;
560 static PyObject *context;
561
562 if (context == NULL)
563 context = PyUnicode_InternFromString("_ctypes.DllCanUnloadNow");
564
565 mod = PyImport_ImportModule("ctypes");
566 if (!mod) {
567 /* OutputDebugString("Could not import ctypes"); */
568 /* We assume that this error can only occur when shutting
569 down, so we silently ignore it */
570 PyErr_Clear();
571 return E_FAIL;
572 }
573 /* Other errors cannot be raised, but are printed to stderr */
574 func = PyObject_GetAttrString(mod, "DllCanUnloadNow");
575 Py_DECREF(mod);
576 if (!func) {
577 PyErr_WriteUnraisable(context ? context : Py_None);
578 return E_FAIL;
579 }
580
581 result = _PyObject_CallNoArgs(func);
582 Py_DECREF(func);
583 if (!result) {
584 PyErr_WriteUnraisable(context ? context : Py_None);
585 return E_FAIL;
586 }
587
588 retval = PyLong_AsLong(result);
589 if (PyErr_Occurred()) {
590 PyErr_WriteUnraisable(context ? context : Py_None);
591 retval = E_FAIL;
592 }
593 Py_DECREF(result);
594 return retval;
595 }
596
597 /*
598 DllRegisterServer and DllUnregisterServer still missing
599 */
600
601 STDAPI DllCanUnloadNow(void)
602 {
603 long result;
604 PyGILState_STATE state = PyGILState_Ensure();
605 result = Call_CanUnloadNow();
606 PyGILState_Release(state);
607 return result;
608 }
609
610 #ifndef Py_NO_ENABLE_SHARED
611 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvRes)
612 {
613 switch(fdwReason) {
614 case DLL_PROCESS_ATTACH:
615 DisableThreadLibraryCalls(hinstDLL);
616 break;
617 }
618 return TRUE;
619 }
620 #endif
621
622 #endif
623
624 /*
625 Local Variables:
626 compile-command: "cd .. && python setup.py -q build_ext"
627 End:
628 */