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