Debian Codegraph @

Modules/_ctypes/callproc.c

raw symbols SCIP
1 /*
2 * History: First version dated from 3/97, derived from my SCMLIB version
3 * for win16.
4 */
5 /*
6 * Related Work:
7 * - calldll http://www.nightmare.com/software.html
8 * - libffi http://sourceware.cygnus.com/libffi/
9 * - ffcall http://clisp.cons.org/~haible/packages-ffcall.html
10 * and, of course, Don Beaudry's MESS package, but this is more ctypes
11 * related.
12 */
13
14
15 /*
16 How are functions called, and how are parameters converted to C ?
17
18 1. _ctypes.c::PyCFuncPtr_call receives an argument tuple 'inargs' and a
19 keyword dictionary 'kwds'.
20
21 2. After several checks, _build_callargs() is called which returns another
22 tuple 'callargs'. This may be the same tuple as 'inargs', a slice of
23 'inargs', or a completely fresh tuple, depending on several things (is it a
24 COM method?, are 'paramflags' available?).
25
26 3. _build_callargs also calculates bitarrays containing indexes into
27 the callargs tuple, specifying how to build the return value(s) of
28 the function.
29
30 4. _ctypes_callproc is then called with the 'callargs' tuple. _ctypes_callproc first
31 allocates two arrays. The first is an array of 'struct argument' items, the
32 second array has 'void *' entries.
33
34 5. If 'converters' are present (converters is a sequence of argtypes'
35 from_param methods), for each item in 'callargs' converter is called and the
36 result passed to ConvParam. If 'converters' are not present, each argument
37 is directly passed to ConvParm.
38
39 6. For each arg, ConvParam stores the contained C data (or a pointer to it,
40 for structures) into the 'struct argument' array.
41
42 7. Finally, a loop fills the 'void *' array so that each item points to the
43 data contained in or pointed to by the 'struct argument' array.
44
45 8. The 'void *' argument array is what _call_function_pointer
46 expects. _call_function_pointer then has very little to do - only some
47 libffi specific stuff, then it calls ffi_call.
48
49 So, there are 4 data structures holding processed arguments:
50 - the inargs tuple (in PyCFuncPtr_call)
51 - the callargs tuple (in PyCFuncPtr_call)
52 - the 'struct arguments' array
53 - the 'void *' array
54
55 */
56
57 /*[clinic input]
58 module _ctypes
59 [clinic start generated code]*/
60 /*[clinic end generated code: output=da39a3ee5e6b4b0d input=476a19c49b31a75c]*/
61
62 #ifndef Py_BUILD_CORE_BUILTIN
63 # define Py_BUILD_CORE_MODULE 1
64 #endif
65
66 #include "Python.h"
67
68
69 #ifdef MS_WIN32
70 #include <windows.h>
71 #include <tchar.h>
72 #else
73 #include <dlfcn.h>
74 #endif
75
76 #ifdef __APPLE__
77 #include <mach-o/dyld.h>
78 #endif
79
80 #ifdef MS_WIN32
81 #include <malloc.h>
82 #endif
83
84 #include <ffi.h>
85 #include "ctypes.h"
86 #ifdef HAVE_ALLOCA_H
87 /* AIX needs alloca.h for alloca() */
88 #include <alloca.h>
89 #endif
90
91 #ifdef _Py_MEMORY_SANITIZER
92 #include <sanitizer/msan_interface.h>
93 #endif
94
95 #if defined(_DEBUG) || defined(__MINGW32__)
96 /* Don't use structured exception handling on Windows if this is defined.
97 MingW, AFAIK, doesn't support it.
98 */
99 #define DONT_USE_SEH
100 #endif
101
102 #include "pycore_runtime.h" // _PyRuntime
103 #include "pycore_global_objects.h"// _Py_ID()
104 #include "pycore_traceback.h" // _PyTraceback_Add()
105
106 #define clinic_state() (get_module_state(module))
107 #include "clinic/callproc.c.h"
108 #undef clinic_state
109
110 #define CTYPES_CAPSULE_NAME_PYMEM "_ctypes pymem"
111
112
113 static void pymem_destructor(PyObject *ptr)
114 {
115 void *p = PyCapsule_GetPointer(ptr, CTYPES_CAPSULE_NAME_PYMEM);
116 if (p) {
117 PyMem_Free(p);
118 }
119 }
120
121 /*
122 ctypes maintains thread-local storage that has space for two error numbers:
123 private copies of the system 'errno' value and, on Windows, the system error code
124 accessed by the GetLastError() and SetLastError() api functions.
125
126 Foreign functions created with CDLL(..., use_errno=True), when called, swap
127 the system 'errno' value with the private copy just before the actual
128 function call, and swapped again immediately afterwards. The 'use_errno'
129 parameter defaults to False, in this case 'ctypes_errno' is not touched.
130
131 On Windows, foreign functions created with CDLL(..., use_last_error=True) or
132 WinDLL(..., use_last_error=True) swap the system LastError value with the
133 ctypes private copy.
134
135 The values are also swapped immediately before and after ctypes callback
136 functions are called, if the callbacks are constructed using the new
137 optional use_errno parameter set to True: CFUNCTYPE(..., use_errno=TRUE) or
138 WINFUNCTYPE(..., use_errno=True).
139
140 New ctypes functions are provided to access the ctypes private copies from
141 Python:
142
143 - ctypes.set_errno(value) and ctypes.set_last_error(value) store 'value' in
144 the private copy and returns the previous value.
145
146 - ctypes.get_errno() and ctypes.get_last_error() returns the current ctypes
147 private copies value.
148 */
149
150 /*
151 This function creates and returns a thread-local Python object that has
152 space to store two integer error numbers; once created the Python object is
153 kept alive in the thread state dictionary as long as the thread itself.
154 */
155 PyObject *
156 _ctypes_get_errobj(ctypes_state *st, int **pspace)
157 {
158 PyObject *dict = PyThreadState_GetDict();
159 PyObject *errobj;
160 if (dict == NULL) {
161 PyErr_SetString(PyExc_RuntimeError,
162 "cannot get thread state");
163 return NULL;
164 }
165 assert(st->error_object_name != NULL);
166 if (PyDict_GetItemRef(dict, st->error_object_name, &errobj) < 0) {
167 return NULL;
168 }
169 if (errobj) {
170 if (!PyCapsule_IsValid(errobj, CTYPES_CAPSULE_NAME_PYMEM)) {
171 PyErr_SetString(PyExc_RuntimeError,
172 "ctypes.error_object is an invalid capsule");
173 Py_DECREF(errobj);
174 return NULL;
175 }
176 }
177 else {
178 void *space = PyMem_Calloc(2, sizeof(int));
179 if (space == NULL) {
180 return PyErr_NoMemory();
181 }
182 errobj = PyCapsule_New(space, CTYPES_CAPSULE_NAME_PYMEM, pymem_destructor);
183 if (errobj == NULL) {
184 PyMem_Free(space);
185 return NULL;
186 }
187 if (PyDict_SetItem(dict, st->error_object_name, errobj) < 0) {
188 Py_DECREF(errobj);
189 return NULL;
190 }
191 }
192 *pspace = (int *)PyCapsule_GetPointer(errobj, CTYPES_CAPSULE_NAME_PYMEM);
193 return errobj;
194 }
195
196 static PyObject *
197 get_error_internal(PyObject *self, PyObject *args, int index)
198 {
199 int *space;
200 ctypes_state *st = get_module_state(self);
201 PyObject *errobj = _ctypes_get_errobj(st, &space);
202 PyObject *result;
203
204 if (errobj == NULL)
205 return NULL;
206 result = PyLong_FromLong(space[index]);
207 Py_DECREF(errobj);
208 return result;
209 }
210
211 static PyObject *
212 set_error_internal(PyObject *self, PyObject *args, int index)
213 {
214 int new_errno, old_errno;
215 PyObject *errobj;
216 int *space;
217
218 if (!PyArg_ParseTuple(args, "i", &new_errno)) {
219 return NULL;
220 }
221 ctypes_state *st = get_module_state(self);
222 errobj = _ctypes_get_errobj(st, &space);
223 if (errobj == NULL)
224 return NULL;
225 old_errno = space[index];
226 space[index] = new_errno;
227 Py_DECREF(errobj);
228 return PyLong_FromLong(old_errno);
229 }
230
231 static PyObject *
232 get_errno(PyObject *self, PyObject *args)
233 {
234 if (PySys_Audit("ctypes.get_errno", NULL) < 0) {
235 return NULL;
236 }
237 return get_error_internal(self, args, 0);
238 }
239
240 static PyObject *
241 set_errno(PyObject *self, PyObject *args)
242 {
243 if (PySys_Audit("ctypes.set_errno", "O", args) < 0) {
244 return NULL;
245 }
246 return set_error_internal(self, args, 0);
247 }
248
249 #ifdef MS_WIN32
250
251 static PyObject *
252 get_last_error(PyObject *self, PyObject *args)
253 {
254 if (PySys_Audit("ctypes.get_last_error", NULL) < 0) {
255 return NULL;
256 }
257 return get_error_internal(self, args, 1);
258 }
259
260 static PyObject *
261 set_last_error(PyObject *self, PyObject *args)
262 {
263 if (PySys_Audit("ctypes.set_last_error", "O", args) < 0) {
264 return NULL;
265 }
266 return set_error_internal(self, args, 1);
267 }
268
269 static WCHAR *FormatError(DWORD code)
270 {
271 WCHAR *lpMsgBuf;
272 DWORD n;
273 n = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
274 FORMAT_MESSAGE_FROM_SYSTEM |
275 FORMAT_MESSAGE_IGNORE_INSERTS,
276 NULL,
277 code,
278 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), /* Default language */
279 (LPWSTR) &lpMsgBuf,
280 0,
281 NULL);
282 if (n) {
283 while (iswspace(lpMsgBuf[n-1]))
284 --n;
285 lpMsgBuf[n] = L'\0'; /* rstrip() */
286 }
287 return lpMsgBuf;
288 }
289
290 #ifndef DONT_USE_SEH
291 static void SetException(DWORD code, EXCEPTION_RECORD *pr)
292 {
293 if (PySys_Audit("ctypes.set_exception", "I", code) < 0) {
294 /* An exception was set by the audit hook */
295 return;
296 }
297
298 /* The 'code' is a normal win32 error code so it could be handled by
299 PyErr_SetFromWindowsErr(). However, for some errors, we have additional
300 information not included in the error code. We handle those here and
301 delegate all others to the generic function. */
302 switch (code) {
303 case EXCEPTION_ACCESS_VIOLATION:
304 /* The thread attempted to read from or write
305 to a virtual address for which it does not
306 have the appropriate access. */
307 if (pr->ExceptionInformation[0] == 0)
308 PyErr_Format(PyExc_OSError,
309 "exception: access violation reading %p",
310 pr->ExceptionInformation[1]);
311 else
312 PyErr_Format(PyExc_OSError,
313 "exception: access violation writing %p",
314 pr->ExceptionInformation[1]);
315 break;
316
317 case EXCEPTION_BREAKPOINT:
318 /* A breakpoint was encountered. */
319 PyErr_SetString(PyExc_OSError,
320 "exception: breakpoint encountered");
321 break;
322
323 case EXCEPTION_DATATYPE_MISALIGNMENT:
324 /* The thread attempted to read or write data that is
325 misaligned on hardware that does not provide
326 alignment. For example, 16-bit values must be
327 aligned on 2-byte boundaries, 32-bit values on
328 4-byte boundaries, and so on. */
329 PyErr_SetString(PyExc_OSError,
330 "exception: datatype misalignment");
331 break;
332
333 case EXCEPTION_SINGLE_STEP:
334 /* A trace trap or other single-instruction mechanism
335 signaled that one instruction has been executed. */
336 PyErr_SetString(PyExc_OSError,
337 "exception: single step");
338 break;
339
340 case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
341 /* The thread attempted to access an array element
342 that is out of bounds, and the underlying hardware
343 supports bounds checking. */
344 PyErr_SetString(PyExc_OSError,
345 "exception: array bounds exceeded");
346 break;
347
348 case EXCEPTION_FLT_DENORMAL_OPERAND:
349 /* One of the operands in a floating-point operation
350 is denormal. A denormal value is one that is too
351 small to represent as a standard floating-point
352 value. */
353 PyErr_SetString(PyExc_OSError,
354 "exception: floating-point operand denormal");
355 break;
356
357 case EXCEPTION_FLT_DIVIDE_BY_ZERO:
358 /* The thread attempted to divide a floating-point
359 value by a floating-point divisor of zero. */
360 PyErr_SetString(PyExc_OSError,
361 "exception: float divide by zero");
362 break;
363
364 case EXCEPTION_FLT_INEXACT_RESULT:
365 /* The result of a floating-point operation cannot be
366 represented exactly as a decimal fraction. */
367 PyErr_SetString(PyExc_OSError,
368 "exception: float inexact");
369 break;
370
371 case EXCEPTION_FLT_INVALID_OPERATION:
372 /* This exception represents any floating-point
373 exception not included in this list. */
374 PyErr_SetString(PyExc_OSError,
375 "exception: float invalid operation");
376 break;
377
378 case EXCEPTION_FLT_OVERFLOW:
379 /* The exponent of a floating-point operation is
380 greater than the magnitude allowed by the
381 corresponding type. */
382 PyErr_SetString(PyExc_OSError,
383 "exception: float overflow");
384 break;
385
386 case EXCEPTION_FLT_STACK_CHECK:
387 /* The stack overflowed or underflowed as the result
388 of a floating-point operation. */
389 PyErr_SetString(PyExc_OSError,
390 "exception: stack over/underflow");
391 break;
392
393 case EXCEPTION_STACK_OVERFLOW:
394 /* The stack overflowed or underflowed as the result
395 of a floating-point operation. */
396 PyErr_SetString(PyExc_OSError,
397 "exception: stack overflow");
398 break;
399
400 case EXCEPTION_FLT_UNDERFLOW:
401 /* The exponent of a floating-point operation is less
402 than the magnitude allowed by the corresponding
403 type. */
404 PyErr_SetString(PyExc_OSError,
405 "exception: float underflow");
406 break;
407
408 case EXCEPTION_INT_DIVIDE_BY_ZERO:
409 /* The thread attempted to divide an integer value by
410 an integer divisor of zero. */
411 PyErr_SetString(PyExc_OSError,
412 "exception: integer divide by zero");
413 break;
414
415 case EXCEPTION_INT_OVERFLOW:
416 /* The result of an integer operation caused a carry
417 out of the most significant bit of the result. */
418 PyErr_SetString(PyExc_OSError,
419 "exception: integer overflow");
420 break;
421
422 case EXCEPTION_PRIV_INSTRUCTION:
423 /* The thread attempted to execute an instruction
424 whose operation is not allowed in the current
425 machine mode. */
426 PyErr_SetString(PyExc_OSError,
427 "exception: privileged instruction");
428 break;
429
430 case EXCEPTION_NONCONTINUABLE_EXCEPTION:
431 /* The thread attempted to continue execution after a
432 noncontinuable exception occurred. */
433 PyErr_SetString(PyExc_OSError,
434 "exception: nocontinuable");
435 break;
436
437 default:
438 PyErr_SetFromWindowsErr(code);
439 break;
440 }
441 }
442
443 static DWORD HandleException(EXCEPTION_POINTERS *ptrs,
444 DWORD *pdw, EXCEPTION_RECORD *record)
445 {
446 *pdw = ptrs->ExceptionRecord->ExceptionCode;
447 *record = *ptrs->ExceptionRecord;
448 /* We don't want to catch breakpoint exceptions, they are used to attach
449 * a debugger to the process.
450 */
451 if (*pdw == EXCEPTION_BREAKPOINT)
452 return EXCEPTION_CONTINUE_SEARCH;
453 return EXCEPTION_EXECUTE_HANDLER;
454 }
455 #endif
456
457 static PyObject *
458 check_hresult(PyObject *self, PyObject *args)
459 {
460 HRESULT hr;
461 if (!PyArg_ParseTuple(args, "i", &hr))
462 return NULL;
463 if (FAILED(hr))
464 return PyErr_SetFromWindowsErr(hr);
465 return PyLong_FromLong(hr);
466 }
467
468 #endif
469
470 /**************************************************************/
471
472 PyCArgObject *
473 PyCArgObject_new(ctypes_state *st)
474 {
475 PyCArgObject *p;
476 p = PyObject_GC_New(PyCArgObject, st->PyCArg_Type);
477 if (p == NULL)
478 return NULL;
479 p->pffi_type = NULL;
480 p->tag = '\0';
481 p->obj = NULL;
482 memset(&p->value, 0, sizeof(p->value));
483 PyObject_GC_Track(p);
484 return p;
485 }
486
487 static int
488 PyCArg_traverse(PyObject *op, visitproc visit, void *arg)
489 {
490 PyCArgObject *self = _PyCArgObject_CAST(op);
491 Py_VISIT(Py_TYPE(self));
492 Py_VISIT(self->obj);
493 return 0;
494 }
495
496 static int
497 PyCArg_clear(PyObject *op)
498 {
499 PyCArgObject *self = _PyCArgObject_CAST(op);
500 Py_CLEAR(self->obj);
501 return 0;
502 }
503
504 static void
505 PyCArg_dealloc(PyObject *self)
506 {
507 PyTypeObject *tp = Py_TYPE(self);
508 PyObject_GC_UnTrack(self);
509 (void)PyCArg_clear(self);
510 tp->tp_free(self);
511 Py_DECREF(tp);
512 }
513
514 static int
515 is_literal_char(unsigned char c)
516 {
517 return c < 128 && _PyUnicode_IsPrintable(c) && c != '\\' && c != '\'';
518 }
519
520 static PyObject *
521 PyCArg_repr(PyObject *op)
522 {
523 PyCArgObject *self = _PyCArgObject_CAST(op);
524 switch(self->tag) {
525 case 'b':
526 case 'B':
527 return PyUnicode_FromFormat("<cparam '%c' (%d)>",
528 self->tag, self->value.b);
529 case 'h':
530 case 'H':
531 return PyUnicode_FromFormat("<cparam '%c' (%d)>",
532 self->tag, self->value.h);
533 case 'i':
534 case 'I':
535 return PyUnicode_FromFormat("<cparam '%c' (%d)>",
536 self->tag, self->value.i);
537 case 'l':
538 case 'L':
539 return PyUnicode_FromFormat("<cparam '%c' (%ld)>",
540 self->tag, self->value.l);
541
542 case 'q':
543 case 'Q':
544 return PyUnicode_FromFormat("<cparam '%c' (%lld)>",
545 self->tag, self->value.q);
546 case 'd':
547 case 'f': {
548 PyObject *f = PyFloat_FromDouble((self->tag == 'f') ? self->value.f : self->value.d);
549 if (f == NULL) {
550 return NULL;
551 }
552 PyObject *result = PyUnicode_FromFormat("<cparam '%c' (%R)>", self->tag, f);
553 Py_DECREF(f);
554 return result;
555 }
556 case 'c':
557 if (is_literal_char((unsigned char)self->value.c)) {
558 return PyUnicode_FromFormat("<cparam '%c' ('%c')>",
559 self->tag, self->value.c);
560 }
561 else {
562 return PyUnicode_FromFormat("<cparam '%c' ('\\x%02x')>",
563 self->tag, (unsigned char)self->value.c);
564 }
565
566 /* Hm, are these 'z' and 'Z' codes useful at all?
567 Shouldn't they be replaced by the functionality of create_string_buffer()
568 and c_wstring() ?
569 */
570 case 'z':
571 case 'Z':
572 case 'P':
573 return PyUnicode_FromFormat("<cparam '%c' (%p)>",
574 self->tag, self->value.p);
575 break;
576
577 default:
578 if (is_literal_char((unsigned char)self->tag)) {
579 return PyUnicode_FromFormat("<cparam '%c' at %p>",
580 (unsigned char)self->tag, (void *)self);
581 }
582 else {
583 return PyUnicode_FromFormat("<cparam 0x%02x at %p>",
584 (unsigned char)self->tag, (void *)self);
585 }
586 }
587 }
588
589 static PyMemberDef PyCArgType_members[] = {
590 { "_obj", _Py_T_OBJECT,
591 offsetof(PyCArgObject, obj), Py_READONLY,
592 "the wrapped object" },
593 { NULL },
594 };
595
596 static PyType_Slot carg_slots[] = {
597 {Py_tp_dealloc, PyCArg_dealloc},
598 {Py_tp_traverse, PyCArg_traverse},
599 {Py_tp_clear, PyCArg_clear},
600 {Py_tp_repr, PyCArg_repr},
601 {Py_tp_members, PyCArgType_members},
602 {0, NULL},
603 };
604
605 PyType_Spec carg_spec = {
606 .name = "_ctypes.CArgObject",
607 .basicsize = sizeof(PyCArgObject),
608 .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
609 Py_TPFLAGS_IMMUTABLETYPE | Py_TPFLAGS_DISALLOW_INSTANTIATION),
610 .slots = carg_slots,
611 };
612
613 /****************************************************************/
614 /*
615 * Convert a PyObject * into a parameter suitable to pass to an
616 * C function call.
617 *
618 * 1. Python integers are converted to C int and passed by value.
619 * Py_None is converted to a C NULL pointer.
620 *
621 * 2. 3-tuples are expected to have a format character in the first
622 * item, which must be 'i', 'f', 'd', 'q', or 'P'.
623 * The second item will have to be an integer, float, double, long long
624 * or integer (denoting an address void *), will be converted to the
625 * corresponding C data type and passed by value.
626 *
627 * 3. Other Python objects are tested for an '_as_parameter_' attribute.
628 * The value of this attribute must be an integer which will be passed
629 * by value, or a 2-tuple or 3-tuple which will be used according
630 * to point 2 above. The third item (if any), is ignored. It is normally
631 * used to keep the object alive where this parameter refers to.
632 * XXX This convention is dangerous - you can construct arbitrary tuples
633 * in Python and pass them. Would it be safer to use a custom container
634 * datatype instead of a tuple?
635 *
636 * 4. Other Python objects cannot be passed as parameters - an exception is raised.
637 *
638 * 5. ConvParam will store the converted result in a struct containing format
639 * and value.
640 */
641
642 union result {
643 char c;
644 char b;
645 short h;
646 int i;
647 long l;
648 long long q;
649 long double g;
650 double d;
651 float f;
652 void *p;
653 double D[2];
654 float F[2];
655 long double G[2];
656 };
657
658 struct argument {
659 ffi_type *ffi_type;
660 PyObject *keep;
661 union result value;
662 };
663
664 /*
665 * Convert a single Python object into a PyCArgObject and return it.
666 */
667 static int ConvParam(ctypes_state *st,
668 PyObject *obj, Py_ssize_t index, struct argument *pa)
669 {
670 pa->keep = NULL; /* so we cannot forget it later */
671
672 StgInfo *info;
673 int result = PyStgInfo_FromObject(st, obj, &info);
674 if (result < 0) {
675 return -1;
676 }
677 if (info) {
678 assert(info);
679 PyCArgObject *carg;
680 assert(info->paramfunc);
681 /* If it has an stginfo, it is a CDataObject */
682 Py_BEGIN_CRITICAL_SECTION(obj);
683 carg = info->paramfunc(st, (CDataObject *)obj);
684 Py_END_CRITICAL_SECTION();
685 if (carg == NULL)
686 return -1;
687 pa->ffi_type = carg->pffi_type;
688 memcpy(&pa->value, &carg->value, sizeof(pa->value));
689 pa->keep = (PyObject *)carg;
690 return 0;
691 }
692
693 if (PyCArg_CheckExact(st, obj)) {
694 PyCArgObject *carg = (PyCArgObject *)obj;
695 pa->ffi_type = carg->pffi_type;
696 pa->keep = Py_NewRef(obj);
697 memcpy(&pa->value, &carg->value, sizeof(pa->value));
698 return 0;
699 }
700
701 /* check for None, integer, string or unicode and use directly if successful */
702 if (obj == Py_None) {
703 pa->ffi_type = &ffi_type_pointer;
704 pa->value.p = NULL;
705 return 0;
706 }
707
708 if (PyLong_Check(obj)) {
709 pa->ffi_type = &ffi_type_sint;
710 pa->value.i = (long)PyLong_AsUnsignedLong(obj);
711 if (pa->value.i == -1 && PyErr_Occurred()) {
712 PyErr_Clear();
713 pa->value.i = PyLong_AsLong(obj);
714 if (pa->value.i == -1 && PyErr_Occurred()) {
715 PyErr_SetString(PyExc_OverflowError,
716 "int too long to convert");
717 return -1;
718 }
719 }
720 return 0;
721 }
722
723 if (PyBytes_Check(obj)) {
724 pa->ffi_type = &ffi_type_pointer;
725 pa->value.p = PyBytes_AsString(obj);
726 pa->keep = Py_NewRef(obj);
727 return 0;
728 }
729
730 if (PyUnicode_Check(obj)) {
731 pa->ffi_type = &ffi_type_pointer;
732 pa->value.p = PyUnicode_AsWideCharString(obj, NULL);
733 if (pa->value.p == NULL)
734 return -1;
735 pa->keep = PyCapsule_New(pa->value.p, CTYPES_CAPSULE_NAME_PYMEM, pymem_destructor);
736 if (!pa->keep) {
737 PyMem_Free(pa->value.p);
738 return -1;
739 }
740 return 0;
741 }
742
743 {
744 PyObject *arg;
745 if (PyObject_GetOptionalAttr(obj, &_Py_ID(_as_parameter_), &arg) < 0) {
746 return -1;
747 }
748 /* Which types should we exactly allow here?
749 integers are required for using Python classes
750 as parameters (they have to expose the '_as_parameter_'
751 attribute)
752 */
753 if (arg) {
754 int result;
755 result = ConvParam(st, arg, index, pa);
756 Py_DECREF(arg);
757 return result;
758 }
759 PyErr_Format(PyExc_TypeError,
760 "Don't know how to convert parameter %d",
761 Py_SAFE_DOWNCAST(index, Py_ssize_t, int));
762 return -1;
763 }
764 }
765
766 #if defined(MS_WIN32) && !defined(_WIN32_WCE)
767 /*
768 Per: https://msdn.microsoft.com/en-us/library/7572ztz4.aspx
769 To be returned by value in RAX, user-defined types must have a length
770 of 1, 2, 4, 8, 16, 32, or 64 bits
771 */
772 int can_return_struct_as_int(size_t s)
773 {
774 return s == 1 || s == 2 || s == 4;
775 }
776
777 int can_return_struct_as_sint64(size_t s)
778 {
779 #ifdef _M_ARM
780 // 8 byte structs cannot be returned in a register on ARM32
781 return 0;
782 #else
783 return s == 8;
784 #endif
785 }
786 #endif
787
788
789 // returns NULL with exception set on error
790 ffi_type *_ctypes_get_ffi_type(ctypes_state *st, PyObject *obj)
791 {
792 if (obj == NULL) {
793 return &ffi_type_sint;
794 }
795
796 StgInfo *info;
797 if (PyStgInfo_FromType(st, obj, &info) < 0) {
798 return NULL;
799 }
800
801 if (info == NULL) {
802 return &ffi_type_sint;
803 }
804 #if defined(MS_WIN32) && !defined(_WIN32_WCE)
805 /* This little trick works correctly with MSVC.
806 It returns small structures in registers
807 */
808 if (info->ffi_type_pointer.type == FFI_TYPE_STRUCT) {
809 if (can_return_struct_as_int(info->ffi_type_pointer.size))
810 return &ffi_type_sint32;
811 else if (can_return_struct_as_sint64 (info->ffi_type_pointer.size))
812 return &ffi_type_sint64;
813 }
814 #endif
815 return &info->ffi_type_pointer;
816 }
817
818
819 /*
820 * libffi uses:
821 *
822 * ffi_status ffi_prep_cif(ffi_cif *cif, ffi_abi abi,
823 * unsigned int nargs,
824 * ffi_type *rtype,
825 * ffi_type **atypes);
826 *
827 * and then
828 *
829 * void ffi_call(ffi_cif *cif, void *fn, void *rvalue, void **avalues);
830 */
831 static int _call_function_pointer(ctypes_state *st,
832 int flags,
833 PPROC pProc,
834 void **avalues,
835 ffi_type **atypes,
836 ffi_type *restype,
837 void *resmem,
838 int argcount,
839 int argtypecount)
840 {
841 PyThreadState *_save = NULL; /* For Py_BLOCK_THREADS and Py_UNBLOCK_THREADS */
842 PyObject *error_object = NULL;
843 int *space;
844 ffi_cif cif;
845 int cc;
846 #if defined(MS_WIN32) && !defined(DONT_USE_SEH)
847 DWORD dwExceptionCode = 0;
848 EXCEPTION_RECORD record;
849 #endif
850 /* XXX check before here */
851 if (restype == NULL) {
852 PyErr_SetString(PyExc_RuntimeError,
853 "No ffi_type for result");
854 return -1;
855 }
856
857 cc = FFI_DEFAULT_ABI;
858 #if defined(MS_WIN32) && !defined(MS_WIN64) && !defined(_WIN32_WCE) && !defined(_M_ARM)
859 if ((flags & FUNCFLAG_CDECL) == 0)
860 cc = FFI_STDCALL;
861 #endif
862
863 # ifdef USING_APPLE_OS_LIBFFI
864 # ifdef HAVE_BUILTIN_AVAILABLE
865 # define HAVE_FFI_PREP_CIF_VAR_RUNTIME __builtin_available(macos 10.15, ios 13, watchos 6, tvos 13, *)
866 # else
867 # define HAVE_FFI_PREP_CIF_VAR_RUNTIME (ffi_prep_cif_var != NULL)
868 # endif
869 # elif HAVE_FFI_PREP_CIF_VAR
870 # define HAVE_FFI_PREP_CIF_VAR_RUNTIME true
871 # else
872 # define HAVE_FFI_PREP_CIF_VAR_RUNTIME false
873 # endif
874
875 /* Even on Apple-arm64 the calling convention for variadic functions coincides
876 * with the standard calling convention in the case that the function called
877 * only with its fixed arguments. Thus, we do not need a special flag to be
878 * set on variadic functions. We treat a function as variadic if it is called
879 * with a nonzero number of variadic arguments */
880 bool is_variadic = (argtypecount != 0 && argcount > argtypecount);
881 (void) is_variadic;
882
883 #if defined(__APPLE__) && defined(__arm64__)
884 if (is_variadic) {
885 if (HAVE_FFI_PREP_CIF_VAR_RUNTIME) {
886 } else {
887 PyErr_SetString(PyExc_NotImplementedError, "ffi_prep_cif_var() is missing");
888 return -1;
889 }
890 }
891 #endif
892
893 #if HAVE_FFI_PREP_CIF_VAR
894 if (is_variadic) {
895 if (HAVE_FFI_PREP_CIF_VAR_RUNTIME) {
896 if (FFI_OK != ffi_prep_cif_var(&cif,
897 cc,
898 argtypecount,
899 argcount,
900 restype,
901 atypes)) {
902 PyErr_SetString(PyExc_RuntimeError,
903 "ffi_prep_cif_var failed");
904 return -1;
905 }
906 } else {
907 if (FFI_OK != ffi_prep_cif(&cif,
908 cc,
909 argcount,
910 restype,
911 atypes)) {
912 PyErr_SetString(PyExc_RuntimeError,
913 "ffi_prep_cif failed");
914 return -1;
915 }
916 }
917 } else
918 #endif
919
920 {
921 if (FFI_OK != ffi_prep_cif(&cif,
922 cc,
923 argcount,
924 restype,
925 atypes)) {
926 PyErr_SetString(PyExc_RuntimeError,
927 "ffi_prep_cif failed");
928 return -1;
929 }
930 }
931
932 if (flags & (FUNCFLAG_USE_ERRNO | FUNCFLAG_USE_LASTERROR)) {
933 error_object = _ctypes_get_errobj(st, &space);
934 if (error_object == NULL)
935 return -1;
936 }
937 if ((flags & FUNCFLAG_PYTHONAPI) == 0)
938 Py_UNBLOCK_THREADS
939 if (flags & FUNCFLAG_USE_ERRNO) {
940 int temp = space[0];
941 space[0] = errno;
942 errno = temp;
943 }
944 #ifdef MS_WIN32
945 if (flags & FUNCFLAG_USE_LASTERROR) {
946 int temp = space[1];
947 space[1] = GetLastError();
948 SetLastError(temp);
949 }
950 #ifndef DONT_USE_SEH
951 __try {
952 #endif
953 #endif
954 ffi_call(&cif, (void *)pProc, resmem, avalues);
955 #ifdef MS_WIN32
956 #ifndef DONT_USE_SEH
957 }
958 __except (HandleException(GetExceptionInformation(),
959 &dwExceptionCode, &record)) {
960 ;
961 }
962 #endif
963 if (flags & FUNCFLAG_USE_LASTERROR) {
964 int temp = space[1];
965 space[1] = GetLastError();
966 SetLastError(temp);
967 }
968 #endif
969 if (flags & FUNCFLAG_USE_ERRNO) {
970 int temp = space[0];
971 space[0] = errno;
972 errno = temp;
973 }
974 if ((flags & FUNCFLAG_PYTHONAPI) == 0)
975 Py_BLOCK_THREADS
976 Py_XDECREF(error_object);
977 #ifdef MS_WIN32
978 #ifndef DONT_USE_SEH
979 if (dwExceptionCode) {
980 SetException(dwExceptionCode, &record);
981 return -1;
982 }
983 #endif
984 #endif
985 if ((flags & FUNCFLAG_PYTHONAPI) && PyErr_Occurred())
986 return -1;
987 return 0;
988 }
989
990 /*
991 * Convert the C value in result into a Python object, depending on restype.
992 *
993 * - If restype is NULL, return a Python integer.
994 * - If restype is None, return None.
995 * - If restype is a simple ctypes type (c_int, c_void_p), call the type's getfunc,
996 * pass the result to checker and return the result.
997 * - If restype is another ctypes type, return an instance of that.
998 * - Otherwise, call restype and return the result.
999 */
1000 static PyObject *GetResult(ctypes_state *st,
1001 PyObject *restype, void *result, PyObject *checker)
1002 {
1003 PyObject *retval, *v;
1004
1005 if (restype == NULL)
1006 return PyLong_FromLong(*(int *)result);
1007
1008 if (restype == Py_None) {
1009 Py_RETURN_NONE;
1010 }
1011
1012 StgInfo *info;
1013 if (PyStgInfo_FromType(st, restype, &info) < 0) {
1014 return NULL;
1015 }
1016 if (info == NULL) {
1017 return PyObject_CallFunction(restype, "i", *(int *)result);
1018 }
1019
1020 if (info->getfunc && !_ctypes_simple_instance(st, restype)) {
1021 retval = info->getfunc(result, info->size);
1022 /* If restype is py_object (detected by comparing getfunc with
1023 O_get), we have to call Py_XDECREF because O_get has already
1024 called Py_INCREF, unless the result was NULL, in which case
1025 an error is set (by the called function, or by O_get).
1026 */
1027 if (info->getfunc == _ctypes_get_fielddesc("O")->getfunc) {
1028 Py_XDECREF(retval);
1029 }
1030 }
1031 else {
1032 retval = PyCData_FromBaseObj(st, restype, NULL, 0, result);
1033 }
1034 if (!checker || !retval)
1035 return retval;
1036
1037 v = PyObject_CallOneArg(checker, retval);
1038 if (v == NULL)
1039 _PyTraceback_Add("GetResult", "_ctypes/callproc.c", __LINE__-2);
1040 Py_DECREF(retval);
1041 return v;
1042 }
1043
1044 /*
1045 * Raise a new exception 'exc_class', adding additional text to the original
1046 * exception string.
1047 */
1048 void _ctypes_extend_error(PyObject *exc_class, const char *fmt, ...)
1049 {
1050 va_list vargs;
1051
1052 va_start(vargs, fmt);
1053 PyObject *s = PyUnicode_FromFormatV(fmt, vargs);
1054 va_end(vargs);
1055 if (s == NULL) {
1056 return;
1057 }
1058
1059 assert(PyErr_Occurred());
1060 PyObject *exc = PyErr_GetRaisedException();
1061 assert(exc != NULL);
1062 PyObject *cls_str = PyType_GetName(Py_TYPE(exc));
1063 if (cls_str) {
1064 PyUnicode_AppendAndDel(&s, cls_str);
1065 PyUnicode_AppendAndDel(&s, PyUnicode_FromString(": "));
1066 if (s == NULL) {
1067 goto error;
1068 }
1069 }
1070 else {
1071 PyErr_Clear();
1072 }
1073
1074 PyObject *msg_str = PyObject_Str(exc);
1075 if (msg_str) {
1076 PyUnicode_AppendAndDel(&s, msg_str);
1077 }
1078 else {
1079 PyErr_Clear();
1080 PyUnicode_AppendAndDel(&s, PyUnicode_FromString("???"));
1081 }
1082 if (s == NULL) {
1083 goto error;
1084 }
1085 PyErr_SetObject(exc_class, s);
1086 error:
1087 Py_XDECREF(exc);
1088 Py_XDECREF(s);
1089 }
1090
1091
1092 #ifdef MS_WIN32
1093
1094 static PyObject *
1095 GetComError(ctypes_state *st, HRESULT errcode, GUID *riid, IUnknown *pIunk)
1096 {
1097 HRESULT hr;
1098 ISupportErrorInfo *psei = NULL;
1099 IErrorInfo *pei = NULL;
1100 BSTR descr=NULL, helpfile=NULL, source=NULL;
1101 GUID guid;
1102 DWORD helpcontext=0;
1103 LPOLESTR progid;
1104 PyObject *obj;
1105 LPOLESTR text;
1106
1107 /* We absolutely have to release the GIL during COM method calls,
1108 otherwise we may get a deadlock!
1109 */
1110 Py_BEGIN_ALLOW_THREADS
1111
1112 hr = pIunk->lpVtbl->QueryInterface(pIunk, &IID_ISupportErrorInfo, (void **)&psei);
1113 if (FAILED(hr))
1114 goto failed;
1115
1116 hr = psei->lpVtbl->InterfaceSupportsErrorInfo(psei, riid);
1117 psei->lpVtbl->Release(psei);
1118 if (FAILED(hr))
1119 goto failed;
1120
1121 hr = GetErrorInfo(0, &pei);
1122 if (hr != S_OK)
1123 goto failed;
1124
1125 pei->lpVtbl->GetDescription(pei, &descr);
1126 pei->lpVtbl->GetGUID(pei, &guid);
1127 pei->lpVtbl->GetHelpContext(pei, &helpcontext);
1128 pei->lpVtbl->GetHelpFile(pei, &helpfile);
1129 pei->lpVtbl->GetSource(pei, &source);
1130
1131 pei->lpVtbl->Release(pei);
1132
1133 failed:
1134 Py_END_ALLOW_THREADS
1135
1136 progid = NULL;
1137 ProgIDFromCLSID(&guid, &progid);
1138
1139 text = FormatError(errcode);
1140 obj = Py_BuildValue(
1141 "iu(uuuiu)",
1142 errcode,
1143 text,
1144 descr, source, helpfile, helpcontext,
1145 progid);
1146 if (obj) {
1147 PyErr_SetObject((PyObject *)st->PyComError_Type, obj);
1148 Py_DECREF(obj);
1149 }
1150 LocalFree(text);
1151
1152 if (descr)
1153 SysFreeString(descr);
1154 if (helpfile)
1155 SysFreeString(helpfile);
1156 if (source)
1157 SysFreeString(source);
1158
1159 return NULL;
1160 }
1161 #endif
1162
1163 #if (defined(__x86_64__) && (defined(__MINGW64__) || defined(__CYGWIN__))) || \
1164 defined(__aarch64__) || defined(__riscv)
1165 #define CTYPES_PASS_BY_REF_HACK
1166 #define POW2(x) (((x & ~(x - 1)) == x) ? x : 0)
1167 #define IS_PASS_BY_REF(x) (x > 8 || !POW2(x))
1168 #endif
1169
1170 /*
1171 * Requirements, must be ensured by the caller:
1172 * - argtuple is tuple of arguments
1173 * - argtypes is either NULL, or a tuple of the same size as argtuple
1174 *
1175 * - XXX various requirements for restype, not yet collected
1176 */
1177 PyObject *_ctypes_callproc(ctypes_state *st,
1178 PPROC pProc,
1179 PyObject *argtuple,
1180 #ifdef MS_WIN32
1181 IUnknown *pIunk,
1182 GUID *iid,
1183 #endif
1184 int flags,
1185 PyObject *argtypes, /* misleading name: This is a tuple of
1186 methods, not types: the .from_param
1187 class methods of the types */
1188 PyObject *restype,
1189 PyObject *checker)
1190 {
1191 Py_ssize_t i, n, argcount, argtype_count;
1192 void *resbuf;
1193 struct argument *args, *pa;
1194 ffi_type **atypes;
1195 ffi_type *rtype;
1196 void **avalues;
1197 PyObject *retval = NULL;
1198
1199 // Both call_function and call_cdeclfunction call us:
1200 #if SIZEOF_VOID_P == SIZEOF_LONG
1201 if (PySys_Audit("ctypes.call_function", "kO",
1202 (unsigned long)pProc, argtuple) < 0) {
1203 #elif SIZEOF_VOID_P == SIZEOF_LONG_LONG
1204 if (PySys_Audit("ctypes.call_function", "KO",
1205 (unsigned long long)pProc, argtuple) < 0) {
1206 #else
1207 # warning "unexpected pointer size, you may see odd values in audit hooks"
1208 if (PySys_Audit("ctypes.call_function", "nO",
1209 (Py_ssize_t)pProc, argtuple) < 0) {
1210 #endif
1211 return NULL;
1212 }
1213
1214 n = argcount = PyTuple_GET_SIZE(argtuple);
1215 #ifdef MS_WIN32
1216 /* an optional COM object this pointer */
1217 if (pIunk)
1218 ++argcount;
1219 #endif
1220
1221 if (argcount > CTYPES_MAX_ARGCOUNT)
1222 {
1223 PyErr_Format(st->PyExc_ArgError, "too many arguments (%zi), maximum is %i",
1224 argcount, CTYPES_MAX_ARGCOUNT);
1225 return NULL;
1226 }
1227
1228 args = alloca(sizeof(struct argument) * argcount);
1229 memset(args, 0, sizeof(struct argument) * argcount);
1230 argtype_count = argtypes ? PyTuple_GET_SIZE(argtypes) : 0;
1231 #ifdef MS_WIN32
1232 if (pIunk) {
1233 args[0].ffi_type = &ffi_type_pointer;
1234 args[0].value.p = pIunk;
1235 pa = &args[1];
1236 } else
1237 #endif
1238 pa = &args[0];
1239
1240 /* Convert the arguments */
1241 for (i = 0; i < n; ++i, ++pa) {
1242 PyObject *converter;
1243 PyObject *arg;
1244 int err;
1245
1246 arg = PyTuple_GET_ITEM(argtuple, i); /* borrowed ref */
1247 /* For cdecl functions, we allow more actual arguments
1248 than the length of the argtypes tuple.
1249 This is checked in _ctypes::PyCFuncPtr_Call
1250 */
1251 if (argtypes && argtype_count > i) {
1252 PyObject *v;
1253 converter = PyTuple_GET_ITEM(argtypes, i);
1254 v = PyObject_CallOneArg(converter, arg);
1255 if (v == NULL) {
1256 _ctypes_extend_error(st->PyExc_ArgError, "argument %zd: ", i+1);
1257 goto cleanup;
1258 }
1259
1260 err = ConvParam(st, v, i+1, pa);
1261 Py_DECREF(v);
1262 if (-1 == err) {
1263 _ctypes_extend_error(st->PyExc_ArgError, "argument %zd: ", i+1);
1264 goto cleanup;
1265 }
1266 } else {
1267 err = ConvParam(st, arg, i+1, pa);
1268 if (-1 == err) {
1269 _ctypes_extend_error(st->PyExc_ArgError, "argument %zd: ", i+1);
1270 goto cleanup; /* leaking ? */
1271 }
1272 }
1273 }
1274
1275 if (restype == Py_None) {
1276 rtype = &ffi_type_void;
1277 } else {
1278 rtype = _ctypes_get_ffi_type(st, restype);
1279 }
1280 if (!rtype) {
1281 goto cleanup;
1282 }
1283
1284 resbuf = alloca(max(rtype->size, sizeof(ffi_arg)));
1285
1286 #ifdef _Py_MEMORY_SANITIZER
1287 /* ffi_call actually initializes resbuf, but from asm, which
1288 * MemorySanitizer can't detect. Avoid false positives from MSan. */
1289 if (resbuf != NULL) {
1290 __msan_unpoison(resbuf, max(rtype->size, sizeof(ffi_arg)));
1291 }
1292 #endif
1293 avalues = (void **)alloca(sizeof(void *) * argcount);
1294 atypes = (ffi_type **)alloca(sizeof(ffi_type *) * argcount);
1295 if (!resbuf || !avalues || !atypes) {
1296 PyErr_NoMemory();
1297 goto cleanup;
1298 }
1299 for (i = 0; i < argcount; ++i) {
1300 atypes[i] = args[i].ffi_type;
1301 #ifdef CTYPES_PASS_BY_REF_HACK
1302 size_t size = atypes[i]->size;
1303 if (IS_PASS_BY_REF(size)) {
1304 void *tmp = alloca(size);
1305 if (atypes[i]->type == FFI_TYPE_STRUCT)
1306 memcpy(tmp, args[i].value.p, size);
1307 else
1308 memcpy(tmp, (void*)&args[i].value, size);
1309
1310 avalues[i] = tmp;
1311 }
1312 else
1313 #endif
1314 if (atypes[i]->type == FFI_TYPE_STRUCT)
1315 avalues[i] = (void *)args[i].value.p;
1316 else
1317 avalues[i] = (void *)&args[i].value;
1318 }
1319
1320 if (-1 == _call_function_pointer(st, flags, pProc, avalues, atypes,
1321 rtype, resbuf,
1322 Py_SAFE_DOWNCAST(argcount, Py_ssize_t, int),
1323 Py_SAFE_DOWNCAST(argtype_count, Py_ssize_t, int)))
1324 goto cleanup;
1325
1326 #ifdef WORDS_BIGENDIAN
1327 /* libffi returns the result in a buffer with sizeof(ffi_arg). This
1328 causes problems on big endian machines, since the result buffer
1329 address cannot simply be used as result pointer, instead we must
1330 adjust the pointer value:
1331 */
1332 /*
1333 XXX I should find out and clarify why this is needed at all,
1334 especially why adjusting for ffi_type_float must be avoided on
1335 64-bit platforms.
1336 */
1337 if (rtype->type != FFI_TYPE_FLOAT
1338 && rtype->type != FFI_TYPE_STRUCT
1339 && rtype->size < sizeof(ffi_arg))
1340 {
1341 resbuf = (char *)resbuf + sizeof(ffi_arg) - rtype->size;
1342 }
1343 #endif
1344
1345 #ifdef MS_WIN32
1346 if (iid && pIunk) {
1347 if (*(int *)resbuf & 0x80000000)
1348 retval = GetComError(st, *(HRESULT *)resbuf, iid, pIunk);
1349 else
1350 retval = PyLong_FromLong(*(int *)resbuf);
1351 } else if (flags & FUNCFLAG_HRESULT) {
1352 if (*(int *)resbuf & 0x80000000)
1353 retval = PyErr_SetFromWindowsErr(*(int *)resbuf);
1354 else
1355 retval = PyLong_FromLong(*(int *)resbuf);
1356 } else
1357 #endif
1358 retval = GetResult(st, restype, resbuf, checker);
1359 cleanup:
1360 for (i = 0; i < argcount; ++i)
1361 Py_XDECREF(args[i].keep);
1362 return retval;
1363 }
1364
1365 static int
1366 _parse_voidp(PyObject *obj, void *arg)
1367 {
1368 void **address = (void **)arg;
1369 *address = PyLong_AsVoidPtr(obj);
1370 if (*address == NULL)
1371 return 0;
1372 return 1;
1373 }
1374
1375 #ifdef MS_WIN32
1376
1377 PyDoc_STRVAR(format_error_doc,
1378 "FormatError([integer]) -> string\n\
1379 \n\
1380 Convert a win32 error code into a string. If the error code is not\n\
1381 given, the return value of a call to GetLastError() is used.\n");
1382 static PyObject *format_error(PyObject *self, PyObject *args)
1383 {
1384 PyObject *result;
1385 wchar_t *lpMsgBuf;
1386 DWORD code = 0;
1387 if (!PyArg_ParseTuple(args, "|i:FormatError", &code))
1388 return NULL;
1389 if (code == 0)
1390 code = GetLastError();
1391 lpMsgBuf = FormatError(code);
1392 if (lpMsgBuf) {
1393 result = PyUnicode_FromWideChar(lpMsgBuf, wcslen(lpMsgBuf));
1394 LocalFree(lpMsgBuf);
1395 } else {
1396 result = PyUnicode_FromString("<no description>");
1397 }
1398 return result;
1399 }
1400
1401 PyDoc_STRVAR(load_library_doc,
1402 "LoadLibrary(name, load_flags) -> handle\n\
1403 \n\
1404 Load an executable (usually a DLL), and return a handle to it.\n\
1405 The handle may be used to locate exported functions in this\n\
1406 module. load_flags are as defined for LoadLibraryEx in the\n\
1407 Windows API.\n");
1408 static PyObject *load_library(PyObject *self, PyObject *args)
1409 {
1410 PyObject *nameobj;
1411 int load_flags = 0;
1412 HMODULE hMod;
1413 DWORD err;
1414
1415 if (!PyArg_ParseTuple(args, "U|i:LoadLibrary", &nameobj, &load_flags))
1416 return NULL;
1417
1418 if (PySys_Audit("ctypes.dlopen", "O", nameobj) < 0) {
1419 return NULL;
1420 }
1421
1422 WCHAR *name = PyUnicode_AsWideCharString(nameobj, NULL);
1423 if (!name)
1424 return NULL;
1425
1426 Py_BEGIN_ALLOW_THREADS
1427 /* bpo-36085: Limit DLL search directories to avoid pre-loading
1428 * attacks and enable use of the AddDllDirectory function.
1429 */
1430 hMod = LoadLibraryExW(name, NULL, (DWORD)load_flags);
1431 err = hMod ? 0 : GetLastError();
1432 Py_END_ALLOW_THREADS
1433
1434 PyMem_Free(name);
1435 if (err == ERROR_MOD_NOT_FOUND) {
1436 PyErr_Format(PyExc_FileNotFoundError,
1437 ("Could not find module '%.500S' (or one of its "
1438 "dependencies). Try using the full path with "
1439 "constructor syntax."),
1440 nameobj);
1441 return NULL;
1442 } else if (err) {
1443 return PyErr_SetFromWindowsErr(err);
1444 }
1445 #ifdef _WIN64
1446 return PyLong_FromVoidPtr(hMod);
1447 #else
1448 return PyLong_FromLong((int)hMod);
1449 #endif
1450 }
1451
1452 PyDoc_STRVAR(free_library_doc,
1453 "FreeLibrary(handle) -> void\n\
1454 \n\
1455 Free the handle of an executable previously loaded by LoadLibrary.\n");
1456 static PyObject *free_library(PyObject *self, PyObject *args)
1457 {
1458 void *hMod;
1459 BOOL result;
1460 DWORD err;
1461 if (!PyArg_ParseTuple(args, "O&:FreeLibrary", &_parse_voidp, &hMod))
1462 return NULL;
1463
1464 Py_BEGIN_ALLOW_THREADS
1465 result = FreeLibrary((HMODULE)hMod);
1466 err = result ? 0 : GetLastError();
1467 Py_END_ALLOW_THREADS
1468
1469 if (!result) {
1470 return PyErr_SetFromWindowsErr(err);
1471 }
1472 Py_RETURN_NONE;
1473 }
1474
1475 PyDoc_STRVAR(copy_com_pointer_doc,
1476 "CopyComPointer(src, dst) -> HRESULT value\n");
1477
1478 static PyObject *
1479 copy_com_pointer(PyObject *self, PyObject *args)
1480 {
1481 PyObject *p1, *p2, *r = NULL;
1482 struct argument a, b;
1483 IUnknown *src, **pdst;
1484 if (!PyArg_ParseTuple(args, "OO:CopyComPointer", &p1, &p2))
1485 return NULL;
1486 a.keep = b.keep = NULL;
1487
1488 ctypes_state *st = get_module_state(self);
1489 if (ConvParam(st, p1, 0, &a) < 0 || ConvParam(st, p2, 1, &b) < 0) {
1490 goto done;
1491 }
1492 src = (IUnknown *)a.value.p;
1493 pdst = (IUnknown **)b.value.p;
1494
1495 if (pdst == NULL)
1496 r = PyLong_FromLong(E_POINTER);
1497 else {
1498 if (src)
1499 src->lpVtbl->AddRef(src);
1500 *pdst = src;
1501 r = PyLong_FromLong(S_OK);
1502 }
1503 done:
1504 Py_XDECREF(a.keep);
1505 Py_XDECREF(b.keep);
1506 return r;
1507 }
1508 #else
1509 #ifdef __APPLE__
1510 #ifdef HAVE_DYLD_SHARED_CACHE_CONTAINS_PATH
1511 # ifdef HAVE_BUILTIN_AVAILABLE
1512 # define HAVE_DYLD_SHARED_CACHE_CONTAINS_PATH_RUNTIME \
1513 __builtin_available(macOS 11.0, iOS 14.0, tvOS 14.0, watchOS 7.0, *)
1514 # else
1515 # define HAVE_DYLD_SHARED_CACHE_CONTAINS_PATH_RUNTIME \
1516 (_dyld_shared_cache_contains_path != NULL)
1517 # endif
1518 #else
1519 // Support the deprecated case of compiling on an older macOS version
1520 static void *libsystem_b_handle;
1521 static bool (*_dyld_shared_cache_contains_path)(const char *path);
1522
1523 __attribute__((constructor)) void load_dyld_shared_cache_contains_path(void) {
1524 libsystem_b_handle = dlopen("/usr/lib/libSystem.B.dylib", RTLD_LAZY);
1525 if (libsystem_b_handle != NULL) {
1526 _dyld_shared_cache_contains_path = dlsym(libsystem_b_handle, "_dyld_shared_cache_contains_path");
1527 }
1528 }
1529
1530 __attribute__((destructor)) void unload_dyld_shared_cache_contains_path(void) {
1531 if (libsystem_b_handle != NULL) {
1532 dlclose(libsystem_b_handle);
1533 }
1534 }
1535 #define HAVE_DYLD_SHARED_CACHE_CONTAINS_PATH_RUNTIME \
1536 _dyld_shared_cache_contains_path != NULL
1537 #endif
1538
1539 static PyObject *py_dyld_shared_cache_contains_path(PyObject *self, PyObject *args)
1540 {
1541 PyObject *name, *name2;
1542 char *name_str;
1543
1544 if (HAVE_DYLD_SHARED_CACHE_CONTAINS_PATH_RUNTIME) {
1545 int r;
1546
1547 if (!PyArg_ParseTuple(args, "O", &name))
1548 return NULL;
1549
1550 if (name == Py_None)
1551 Py_RETURN_FALSE;
1552
1553 if (PyUnicode_FSConverter(name, &name2) == 0)
1554 return NULL;
1555 name_str = PyBytes_AS_STRING(name2);
1556
1557 r = _dyld_shared_cache_contains_path(name_str);
1558 Py_DECREF(name2);
1559
1560 if (r) {
1561 Py_RETURN_TRUE;
1562 } else {
1563 Py_RETURN_FALSE;
1564 }
1565
1566 } else {
1567 PyErr_SetString(PyExc_NotImplementedError, "_dyld_shared_cache_contains_path symbol is missing");
1568 return NULL;
1569 }
1570
1571 }
1572 #endif
1573
1574 static PyObject *py_dl_open(PyObject *self, PyObject *args)
1575 {
1576 PyObject *name, *name2;
1577 const char *name_str;
1578 void * handle;
1579 #if HAVE_DECL_RTLD_LOCAL
1580 int mode = RTLD_NOW | RTLD_LOCAL;
1581 #else
1582 /* cygwin doesn't define RTLD_LOCAL */
1583 int mode = RTLD_NOW;
1584 #endif
1585 if (!PyArg_ParseTuple(args, "O|i:dlopen", &name, &mode))
1586 return NULL;
1587 mode |= RTLD_NOW;
1588 if (name != Py_None) {
1589 if (PyUnicode_FSConverter(name, &name2) == 0)
1590 return NULL;
1591 name_str = PyBytes_AS_STRING(name2);
1592 } else {
1593 name_str = NULL;
1594 name2 = NULL;
1595 }
1596 if (PySys_Audit("ctypes.dlopen", "O", name) < 0) {
1597 return NULL;
1598 }
1599 handle = dlopen(name_str, mode);
1600 Py_XDECREF(name2);
1601 if (!handle) {
1602 const char *errmsg = dlerror();
1603 if (errmsg) {
1604 _PyErr_SetLocaleString(PyExc_OSError, errmsg);
1605 return NULL;
1606 }
1607 PyErr_SetString(PyExc_OSError, "dlopen() error");
1608 return NULL;
1609 }
1610 return PyLong_FromVoidPtr(handle);
1611 }
1612
1613 static PyObject *py_dl_close(PyObject *self, PyObject *args)
1614 {
1615 void *handle;
1616
1617 if (!PyArg_ParseTuple(args, "O&:dlclose", &_parse_voidp, &handle))
1618 return NULL;
1619 if (dlclose(handle)) {
1620 const char *errmsg = dlerror();
1621 if (errmsg) {
1622 _PyErr_SetLocaleString(PyExc_OSError, errmsg);
1623 return NULL;
1624 }
1625 PyErr_SetString(PyExc_OSError, "dlclose() error");
1626 return NULL;
1627 }
1628 Py_RETURN_NONE;
1629 }
1630
1631 static PyObject *py_dl_sym(PyObject *self, PyObject *args)
1632 {
1633 char *name;
1634 void *handle;
1635 void *ptr;
1636
1637 if (!PyArg_ParseTuple(args, "O&s:dlsym",
1638 &_parse_voidp, &handle, &name))
1639 return NULL;
1640 if (PySys_Audit("ctypes.dlsym/handle", "O", args) < 0) {
1641 return NULL;
1642 }
1643 #undef USE_DLERROR
1644 #ifdef __CYGWIN__
1645 // dlerror() isn't very helpful on cygwin
1646 #else
1647 #define USE_DLERROR
1648 /* dlerror() always returns the latest error.
1649 *
1650 * Clear the previous value before calling dlsym(),
1651 * to ensure we can tell if our call resulted in an error.
1652 */
1653 (void)dlerror();
1654 #endif
1655 ptr = dlsym((void*)handle, name);
1656 if (ptr) {
1657 return PyLong_FromVoidPtr(ptr);
1658 }
1659 #ifdef USE_DLERROR
1660 const char *errmsg = dlerror();
1661 if (errmsg) {
1662 _PyErr_SetLocaleString(PyExc_OSError, errmsg);
1663 return NULL;
1664 }
1665 #endif
1666 #undef USE_DLERROR
1667 PyErr_Format(PyExc_OSError, "symbol '%s' not found", name);
1668 return NULL;
1669 }
1670
1671 // Apple platforms use the dyld API in ctypes.util instead.
1672 #if defined(HAVE_DL_ITERATE_PHDR) && !defined(__APPLE__)
1673 #include <link.h>
1674
1675 static int
1676 _dllist_callback(struct dl_phdr_info *info, size_t size, void *data)
1677 {
1678 PyObject *list = (PyObject *)data;
1679 PyObject *name = PyUnicode_DecodeFSDefault(info->dlpi_name);
1680 if (name == NULL) {
1681 return -1;
1682 }
1683 int res = PyList_Append(list, name);
1684 Py_DECREF(name);
1685 return res;
1686 }
1687
1688 static PyObject *
1689 dllist(PyObject *self, PyObject *Py_UNUSED(ignored))
1690 {
1691 // On NetBSD dl_iterate_phdr() only reports the link-map group of the
1692 // caller, so it cannot be called via a libffi trampoline.
1693 PyObject *list = PyList_New(0);
1694 if (list == NULL) {
1695 return NULL;
1696 }
1697 // The return value only echoes the callback result.
1698 dl_iterate_phdr(_dllist_callback, list);
1699 if (PyErr_Occurred()) {
1700 Py_DECREF(list);
1701 return NULL;
1702 }
1703 return list;
1704 }
1705 #endif
1706 #endif
1707
1708 /*
1709 * Only for debugging so far: So that we can call CFunction instances
1710 *
1711 * XXX Needs to accept more arguments: flags, argtypes, restype
1712 */
1713 static PyObject *
1714 call_function(PyObject *self, PyObject *args)
1715 {
1716 void *func;
1717 PyObject *arguments;
1718 PyObject *result;
1719
1720 if (!PyArg_ParseTuple(args,
1721 "O&O!",
1722 &_parse_voidp, &func,
1723 &PyTuple_Type, &arguments))
1724 return NULL;
1725
1726 ctypes_state *st = get_module_state(self);
1727 result = _ctypes_callproc(st,
1728 (PPROC)func,
1729 arguments,
1730 #ifdef MS_WIN32
1731 NULL,
1732 NULL,
1733 #endif
1734 0, /* flags */
1735 NULL, /* self->argtypes */
1736 NULL, /* self->restype */
1737 NULL); /* checker */
1738 return result;
1739 }
1740
1741 /*
1742 * Only for debugging so far: So that we can call CFunction instances
1743 *
1744 * XXX Needs to accept more arguments: flags, argtypes, restype
1745 */
1746 static PyObject *
1747 call_cdeclfunction(PyObject *self, PyObject *args)
1748 {
1749 void *func;
1750 PyObject *arguments;
1751 PyObject *result;
1752
1753 if (!PyArg_ParseTuple(args,
1754 "O&O!",
1755 &_parse_voidp, &func,
1756 &PyTuple_Type, &arguments))
1757 return NULL;
1758
1759 ctypes_state *st = get_module_state(self);
1760 result = _ctypes_callproc(st,
1761 (PPROC)func,
1762 arguments,
1763 #ifdef MS_WIN32
1764 NULL,
1765 NULL,
1766 #endif
1767 FUNCFLAG_CDECL, /* flags */
1768 NULL, /* self->argtypes */
1769 NULL, /* self->restype */
1770 NULL); /* checker */
1771 return result;
1772 }
1773
1774 /*****************************************************************
1775 * functions
1776 */
1777
1778 /*[clinic input]
1779 _ctypes.sizeof
1780 obj: object
1781 /
1782 Return the size in bytes of a C instance.
1783
1784 [clinic start generated code]*/
1785
1786 static PyObject *
1787 _ctypes_sizeof(PyObject *module, PyObject *obj)
1788 /*[clinic end generated code: output=ed38a3f364d7bd3e input=321fd0f65cb2d623]*/
1789 {
1790 ctypes_state *st = get_module_state(module);
1791
1792 StgInfo *info;
1793 if (PyStgInfo_FromType(st, obj, &info) < 0) {
1794 return NULL;
1795 }
1796 if (info) {
1797 return PyLong_FromSsize_t(info->size);
1798 }
1799
1800 if (CDataObject_Check(st, obj)) {
1801 PyObject *ret = NULL;
1802 Py_BEGIN_CRITICAL_SECTION(obj);
1803 ret = PyLong_FromSsize_t(((CDataObject *)obj)->b_size);
1804 Py_END_CRITICAL_SECTION();
1805 return ret;
1806 }
1807 PyErr_SetString(PyExc_TypeError,
1808 "this type has no size");
1809 return NULL;
1810 }
1811
1812 PyDoc_STRVAR(alignment_doc,
1813 "alignment(C type) -> integer\n"
1814 "alignment(C instance) -> integer\n"
1815 "Return the alignment requirements of a C instance");
1816
1817 static PyObject *
1818 align_func(PyObject *self, PyObject *obj)
1819 {
1820 ctypes_state *st = get_module_state(self);
1821 StgInfo *info;
1822 if (PyStgInfo_FromAny(st, obj, &info) < 0) {
1823 return NULL;
1824 }
1825 if (info) {
1826 return PyLong_FromSsize_t(info->align);
1827 }
1828 PyErr_SetString(PyExc_TypeError,
1829 "no alignment info");
1830 return NULL;
1831 }
1832
1833
1834 /*[clinic input]
1835 @critical_section obj
1836 _ctypes.byref
1837 obj: object(subclass_of="clinic_state()->PyCData_Type")
1838 offset: Py_ssize_t = 0
1839 /
1840 Return a pointer lookalike to a C instance, only usable as function argument.
1841
1842 [clinic start generated code]*/
1843
1844 static PyObject *
1845 _ctypes_byref_impl(PyObject *module, PyObject *obj, Py_ssize_t offset)
1846 /*[clinic end generated code: output=60dec5ed520c71de input=6ec02d95d15fbd56]*/
1847 {
1848 ctypes_state *st = get_module_state(module);
1849
1850 PyCArgObject *parg = PyCArgObject_new(st);
1851 if (parg == NULL)
1852 return NULL;
1853
1854 parg->tag = 'P';
1855 parg->pffi_type = &ffi_type_pointer;
1856 parg->obj = Py_NewRef(obj);
1857 parg->value.p = (char *)((CDataObject *)obj)->b_ptr + offset;
1858 return (PyObject *)parg;
1859 }
1860
1861 /*[clinic input]
1862 @critical_section obj
1863 _ctypes.addressof
1864 obj: object(subclass_of="clinic_state()->PyCData_Type")
1865 /
1866 Return the address of the C instance internal buffer
1867
1868 [clinic start generated code]*/
1869
1870 static PyObject *
1871 _ctypes_addressof_impl(PyObject *module, PyObject *obj)
1872 /*[clinic end generated code: output=30d8e80c4bab70c7 input=d83937d105d3a442]*/
1873 {
1874 if (PySys_Audit("ctypes.addressof", "(O)", obj) < 0) {
1875 return NULL;
1876 }
1877 return PyLong_FromVoidPtr(((CDataObject *)obj)->b_ptr);
1878 }
1879
1880 static int
1881 converter(PyObject *obj, void *arg)
1882 {
1883 void **address = (void **)arg;
1884 *address = PyLong_AsVoidPtr(obj);
1885 return *address != NULL;
1886 }
1887
1888 static PyObject *
1889 My_PyObj_FromPtr(PyObject *self, PyObject *args)
1890 {
1891 PyObject *ob;
1892 if (!PyArg_ParseTuple(args, "O&:PyObj_FromPtr", converter, &ob)) {
1893 return NULL;
1894 }
1895 if (PySys_Audit("ctypes.PyObj_FromPtr", "(O)", ob) < 0) {
1896 return NULL;
1897 }
1898 return Py_NewRef(ob);
1899 }
1900
1901 static PyObject *
1902 My_Py_INCREF(PyObject *self, PyObject *arg)
1903 {
1904 Py_INCREF(arg); /* that's what this function is for */
1905 Py_INCREF(arg); /* that for returning it */
1906 return arg;
1907 }
1908
1909 static PyObject *
1910 My_Py_DECREF(PyObject *self, PyObject *arg)
1911 {
1912 Py_DECREF(arg); /* that's what this function is for */
1913 Py_INCREF(arg); /* that's for returning it */
1914 return arg;
1915 }
1916
1917 /*[clinic input]
1918 @critical_section obj
1919 _ctypes.resize
1920 obj: object(subclass_of="clinic_state()->PyCData_Type", type="CDataObject *")
1921 size: Py_ssize_t
1922 /
1923
1924 [clinic start generated code]*/
1925
1926 static PyObject *
1927 _ctypes_resize_impl(PyObject *module, CDataObject *obj, Py_ssize_t size)
1928 /*[clinic end generated code: output=11c89c7dbdbcd53f input=bf5a6aaea8514261]*/
1929 {
1930 ctypes_state *st = get_module_state(module);
1931 StgInfo *info;
1932 int result = PyStgInfo_FromObject(st, (PyObject *)obj, &info);
1933 if (result < 0) {
1934 return NULL;
1935 }
1936 if (info == NULL) {
1937 PyErr_SetString(PyExc_TypeError,
1938 "expected ctypes instance");
1939 return NULL;
1940 }
1941 if (size < info->size) {
1942 PyErr_Format(PyExc_ValueError,
1943 "minimum size is %zd",
1944 info->size);
1945 return NULL;
1946 }
1947 if (obj->b_needsfree == 0) {
1948 PyErr_Format(PyExc_ValueError,
1949 "Memory cannot be resized because this object doesn't own it");
1950 return NULL;
1951 }
1952 if ((size_t)size <= sizeof(obj->b_value)) {
1953 /* internal default buffer is large enough */
1954 obj->b_size = size;
1955 goto done;
1956 }
1957 if (!_CDataObject_HasExternalBuffer(obj)) {
1958 /* We are currently using the objects default buffer, but it
1959 isn't large enough any more. */
1960 void *ptr = PyMem_Calloc(1, size);
1961 if (ptr == NULL)
1962 return PyErr_NoMemory();
1963 memmove(ptr, obj->b_ptr, obj->b_size);
1964 obj->b_ptr = ptr;
1965 obj->b_size = size;
1966 } else {
1967 void * ptr = PyMem_Realloc(obj->b_ptr, size);
1968 if (ptr == NULL)
1969 return PyErr_NoMemory();
1970 obj->b_ptr = ptr;
1971 obj->b_size = size;
1972 }
1973 done:
1974 Py_RETURN_NONE;
1975 }
1976
1977 static PyObject *
1978 unpickle(PyObject *self, PyObject *args)
1979 {
1980 PyObject *typ, *state, *meth, *obj, *result;
1981
1982 if (!PyArg_ParseTuple(args, "OO!", &typ, &PyTuple_Type, &state))
1983 return NULL;
1984 obj = PyObject_CallMethodOneArg(typ, &_Py_ID(__new__), typ);
1985 if (obj == NULL)
1986 return NULL;
1987
1988 meth = PyObject_GetAttr(obj, &_Py_ID(__setstate__));
1989 if (meth == NULL) {
1990 goto error;
1991 }
1992
1993 result = PyObject_Call(meth, state, NULL);
1994 Py_DECREF(meth);
1995 if (result == NULL) {
1996 goto error;
1997 }
1998 Py_DECREF(result);
1999
2000 return obj;
2001
2002 error:
2003 Py_DECREF(obj);
2004 return NULL;
2005 }
2006
2007 static PyObject *
2008 buffer_info(PyObject *self, PyObject *arg)
2009 {
2010 PyObject *shape;
2011 Py_ssize_t i;
2012
2013 ctypes_state *st = get_module_state(self);
2014 StgInfo *info;
2015 if (PyStgInfo_FromAny(st, arg, &info) < 0) {
2016 return NULL;
2017 }
2018 if (info == NULL) {
2019 PyErr_SetString(PyExc_TypeError,
2020 "not a ctypes type or object");
2021 return NULL;
2022 }
2023 shape = PyTuple_New(info->ndim);
2024 if (shape == NULL)
2025 return NULL;
2026 for (i = 0; i < (int)info->ndim; ++i)
2027 PyTuple_SET_ITEM(shape, i, PyLong_FromSsize_t(info->shape[i]));
2028
2029 if (PyErr_Occurred()) {
2030 Py_DECREF(shape);
2031 return NULL;
2032 }
2033 return Py_BuildValue("siN", info->format, info->ndim, shape);
2034 }
2035
2036
2037
2038 PyMethodDef _ctypes_module_methods[] = {
2039 {"get_errno", get_errno, METH_NOARGS},
2040 {"set_errno", set_errno, METH_VARARGS},
2041 {"_unpickle", unpickle, METH_VARARGS },
2042 {"buffer_info", buffer_info, METH_O, "Return buffer interface information"},
2043 _CTYPES_RESIZE_METHODDEF
2044 #ifdef MS_WIN32
2045 {"get_last_error", get_last_error, METH_NOARGS},
2046 {"set_last_error", set_last_error, METH_VARARGS},
2047 {"CopyComPointer", copy_com_pointer, METH_VARARGS, copy_com_pointer_doc},
2048 {"FormatError", format_error, METH_VARARGS, format_error_doc},
2049 {"LoadLibrary", load_library, METH_VARARGS, load_library_doc},
2050 {"FreeLibrary", free_library, METH_VARARGS, free_library_doc},
2051 {"_check_HRESULT", check_hresult, METH_VARARGS},
2052 #else
2053 {"dlopen", py_dl_open, METH_VARARGS,
2054 "dlopen(name, flag={RTLD_GLOBAL|RTLD_LOCAL}) open a shared library"},
2055 {"dlclose", py_dl_close, METH_VARARGS, "dlclose a library"},
2056 {"dlsym", py_dl_sym, METH_VARARGS, "find symbol in shared library"},
2057 #if defined(HAVE_DL_ITERATE_PHDR) && !defined(__APPLE__)
2058 {"dllist", dllist, METH_NOARGS,
2059 "dllist() return a list of loaded shared libraries"},
2060 #endif
2061 #endif
2062 #ifdef __APPLE__
2063 {"_dyld_shared_cache_contains_path", py_dyld_shared_cache_contains_path, METH_VARARGS, "check if path is in the shared cache"},
2064 #endif
2065 {"alignment", align_func, METH_O, alignment_doc},
2066 _CTYPES_SIZEOF_METHODDEF
2067 _CTYPES_BYREF_METHODDEF
2068 _CTYPES_ADDRESSOF_METHODDEF
2069 {"call_function", call_function, METH_VARARGS },
2070 {"call_cdeclfunction", call_cdeclfunction, METH_VARARGS },
2071 {"PyObj_FromPtr", My_PyObj_FromPtr, METH_VARARGS },
2072 {"Py_INCREF", My_Py_INCREF, METH_O },
2073 {"Py_DECREF", My_Py_DECREF, METH_O },
2074 {NULL, NULL} /* Sentinel */
2075 };