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