Debian Codegraph @

Modules/_ctypes/callproc.c

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