Debian Codegraph @

Modules/_ctypes/callproc.c

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