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
pymem_destructor(PyObject * ptr)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 *
_ctypes_get_errobj(ctypes_state * st,int ** pspace)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 *
get_error_internal(PyObject * self,PyObject * args,int index)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 *
set_error_internal(PyObject * self,PyObject * args,int index)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 *
get_errno(PyObject * self,PyObject * args)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 *
set_errno(PyObject * self,PyObject * args)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 *
get_last_error(PyObject * self,PyObject * args)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 *
set_last_error(PyObject * self,PyObject * args)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
FormatError(DWORD code)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
SetException(DWORD code,EXCEPTION_RECORD * pr)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
HandleException(EXCEPTION_POINTERS * ptrs,DWORD * pdw,EXCEPTION_RECORD * record)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 *
check_hresult(PyObject * self,PyObject * args)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 *
PyCArgObject_new(ctypes_state * st)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
PyCArg_traverse(PyCArgObject * self,visitproc visit,void * arg)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
PyCArg_clear(PyCArgObject * self)500 PyCArg_clear(PyCArgObject *self)
501 {
502 Py_CLEAR(self->obj);
503 return 0;
504 }
505
506 static void
PyCArg_dealloc(PyCArgObject * self)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
is_literal_char(unsigned char c)517 is_literal_char(unsigned char c)
518 {
519 return c < 128 && _PyUnicode_IsPrintable(c) && c != '\\' && c != '\'';
520 }
521
522 static PyObject *
PyCArg_repr(PyCArgObject * self)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 */
ConvParam(ctypes_state * st,PyObject * obj,Py_ssize_t index,struct argument * pa)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 */
can_return_struct_as_int(size_t s)768 int can_return_struct_as_int(size_t s)
769 {
770 return s == 1 || s == 2 || s == 4;
771 }
772
can_return_struct_as_sint64(size_t s)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
_ctypes_get_ffi_type(ctypes_state * st,PyObject * obj)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 */
_call_function_pointer(ctypes_state * st,int flags,PPROC pProc,void ** avalues,ffi_type ** atypes,ffi_type * restype,void * resmem,int argcount,int argtypecount)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 */
GetResult(ctypes_state * st,PyObject * restype,void * result,PyObject * checker)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_DECREF because O_get has already
1020 called Py_INCREF.
1021 */
1022 if (info->getfunc == _ctypes_get_fielddesc("O")->getfunc) {
1023 Py_DECREF(retval);
1024 }
1025 }
1026 else {
1027 retval = PyCData_FromBaseObj(st, restype, NULL, 0, result);
1028 }
1029 if (!checker || !retval)
1030 return retval;
1031
1032 v = PyObject_CallOneArg(checker, retval);
1033 if (v == NULL)
1034 _PyTraceback_Add("GetResult", "_ctypes/callproc.c", __LINE__-2);
1035 Py_DECREF(retval);
1036 return v;
1037 }
1038
1039 /*
1040 * Raise a new exception 'exc_class', adding additional text to the original
1041 * exception string.
1042 */
_ctypes_extend_error(PyObject * exc_class,const char * fmt,...)1043 void _ctypes_extend_error(PyObject *exc_class, const char *fmt, ...)
1044 {
1045 va_list vargs;
1046
1047 va_start(vargs, fmt);
1048 PyObject *s = PyUnicode_FromFormatV(fmt, vargs);
1049 va_end(vargs);
1050 if (s == NULL) {
1051 return;
1052 }
1053
1054 assert(PyErr_Occurred());
1055 PyObject *exc = PyErr_GetRaisedException();
1056 assert(exc != NULL);
1057 PyObject *cls_str = PyType_GetName(Py_TYPE(exc));
1058 if (cls_str) {
1059 PyUnicode_AppendAndDel(&s, cls_str);
1060 PyUnicode_AppendAndDel(&s, PyUnicode_FromString(": "));
1061 if (s == NULL) {
1062 goto error;
1063 }
1064 }
1065 else {
1066 PyErr_Clear();
1067 }
1068
1069 PyObject *msg_str = PyObject_Str(exc);
1070 if (msg_str) {
1071 PyUnicode_AppendAndDel(&s, msg_str);
1072 }
1073 else {
1074 PyErr_Clear();
1075 PyUnicode_AppendAndDel(&s, PyUnicode_FromString("???"));
1076 }
1077 if (s == NULL) {
1078 goto error;
1079 }
1080 PyErr_SetObject(exc_class, s);
1081 error:
1082 Py_XDECREF(exc);
1083 Py_XDECREF(s);
1084 }
1085
1086
1087 #ifdef MS_WIN32
1088
1089 static PyObject *
GetComError(ctypes_state * st,HRESULT errcode,GUID * riid,IUnknown * pIunk)1090 GetComError(ctypes_state *st, HRESULT errcode, GUID *riid, IUnknown *pIunk)
1091 {
1092 HRESULT hr;
1093 ISupportErrorInfo *psei = NULL;
1094 IErrorInfo *pei = NULL;
1095 BSTR descr=NULL, helpfile=NULL, source=NULL;
1096 GUID guid;
1097 DWORD helpcontext=0;
1098 LPOLESTR progid;
1099 PyObject *obj;
1100 LPOLESTR text;
1101
1102 /* We absolutely have to release the GIL during COM method calls,
1103 otherwise we may get a deadlock!
1104 */
1105 Py_BEGIN_ALLOW_THREADS
1106
1107 hr = pIunk->lpVtbl->QueryInterface(pIunk, &IID_ISupportErrorInfo, (void **)&psei);
1108 if (FAILED(hr))
1109 goto failed;
1110
1111 hr = psei->lpVtbl->InterfaceSupportsErrorInfo(psei, riid);
1112 psei->lpVtbl->Release(psei);
1113 if (FAILED(hr))
1114 goto failed;
1115
1116 hr = GetErrorInfo(0, &pei);
1117 if (hr != S_OK)
1118 goto failed;
1119
1120 pei->lpVtbl->GetDescription(pei, &descr);
1121 pei->lpVtbl->GetGUID(pei, &guid);
1122 pei->lpVtbl->GetHelpContext(pei, &helpcontext);
1123 pei->lpVtbl->GetHelpFile(pei, &helpfile);
1124 pei->lpVtbl->GetSource(pei, &source);
1125
1126 pei->lpVtbl->Release(pei);
1127
1128 failed:
1129 Py_END_ALLOW_THREADS
1130
1131 progid = NULL;
1132 ProgIDFromCLSID(&guid, &progid);
1133
1134 text = FormatError(errcode);
1135 obj = Py_BuildValue(
1136 "iu(uuuiu)",
1137 errcode,
1138 text,
1139 descr, source, helpfile, helpcontext,
1140 progid);
1141 if (obj) {
1142 PyErr_SetObject((PyObject *)st->PyComError_Type, obj);
1143 Py_DECREF(obj);
1144 }
1145 LocalFree(text);
1146
1147 if (descr)
1148 SysFreeString(descr);
1149 if (helpfile)
1150 SysFreeString(helpfile);
1151 if (source)
1152 SysFreeString(source);
1153
1154 return NULL;
1155 }
1156 #endif
1157
1158 #if (defined(__x86_64__) && (defined(__MINGW64__) || defined(__CYGWIN__))) || \
1159 defined(__aarch64__) || defined(__riscv)
1160 #define CTYPES_PASS_BY_REF_HACK
1161 #define POW2(x) (((x & ~(x - 1)) == x) ? x : 0)
1162 #define IS_PASS_BY_REF(x) (x > 8 || !POW2(x))
1163 #endif
1164
1165 /*
1166 * Requirements, must be ensured by the caller:
1167 * - argtuple is tuple of arguments
1168 * - argtypes is either NULL, or a tuple of the same size as argtuple
1169 *
1170 * - XXX various requirements for restype, not yet collected
1171 */
_ctypes_callproc(ctypes_state * st,PPROC pProc,PyObject * argtuple,IUnknown * pIunk,GUID * iid,int flags,PyObject * argtypes,PyObject * restype,PyObject * checker)1172 PyObject *_ctypes_callproc(ctypes_state *st,
1173 PPROC pProc,
1174 PyObject *argtuple,
1175 #ifdef MS_WIN32
1176 IUnknown *pIunk,
1177 GUID *iid,
1178 #endif
1179 int flags,
1180 PyObject *argtypes, /* misleading name: This is a tuple of
1181 methods, not types: the .from_param
1182 class methods of the types */
1183 PyObject *restype,
1184 PyObject *checker)
1185 {
1186 Py_ssize_t i, n, argcount, argtype_count;
1187 void *resbuf;
1188 struct argument *args, *pa;
1189 ffi_type **atypes;
1190 ffi_type *rtype;
1191 void **avalues;
1192 PyObject *retval = NULL;
1193
1194 n = argcount = PyTuple_GET_SIZE(argtuple);
1195 #ifdef MS_WIN32
1196 /* an optional COM object this pointer */
1197 if (pIunk)
1198 ++argcount;
1199 #endif
1200
1201 if (argcount > CTYPES_MAX_ARGCOUNT)
1202 {
1203 PyErr_Format(st->PyExc_ArgError, "too many arguments (%zi), maximum is %i",
1204 argcount, CTYPES_MAX_ARGCOUNT);
1205 return NULL;
1206 }
1207
1208 args = alloca(sizeof(struct argument) * argcount);
1209 memset(args, 0, sizeof(struct argument) * argcount);
1210 argtype_count = argtypes ? PyTuple_GET_SIZE(argtypes) : 0;
1211 #ifdef MS_WIN32
1212 if (pIunk) {
1213 args[0].ffi_type = &ffi_type_pointer;
1214 args[0].value.p = pIunk;
1215 pa = &args[1];
1216 } else
1217 #endif
1218 pa = &args[0];
1219
1220 /* Convert the arguments */
1221 for (i = 0; i < n; ++i, ++pa) {
1222 PyObject *converter;
1223 PyObject *arg;
1224 int err;
1225
1226 arg = PyTuple_GET_ITEM(argtuple, i); /* borrowed ref */
1227 /* For cdecl functions, we allow more actual arguments
1228 than the length of the argtypes tuple.
1229 This is checked in _ctypes::PyCFuncPtr_Call
1230 */
1231 if (argtypes && argtype_count > i) {
1232 PyObject *v;
1233 converter = PyTuple_GET_ITEM(argtypes, i);
1234 v = PyObject_CallOneArg(converter, arg);
1235 if (v == NULL) {
1236 _ctypes_extend_error(st->PyExc_ArgError, "argument %zd: ", i+1);
1237 goto cleanup;
1238 }
1239
1240 err = ConvParam(st, v, i+1, pa);
1241 Py_DECREF(v);
1242 if (-1 == err) {
1243 _ctypes_extend_error(st->PyExc_ArgError, "argument %zd: ", i+1);
1244 goto cleanup;
1245 }
1246 } else {
1247 err = ConvParam(st, arg, i+1, pa);
1248 if (-1 == err) {
1249 _ctypes_extend_error(st->PyExc_ArgError, "argument %zd: ", i+1);
1250 goto cleanup; /* leaking ? */
1251 }
1252 }
1253 }
1254
1255 if (restype == Py_None) {
1256 rtype = &ffi_type_void;
1257 } else {
1258 rtype = _ctypes_get_ffi_type(st, restype);
1259 }
1260 if (!rtype) {
1261 goto cleanup;
1262 }
1263
1264 resbuf = alloca(max(rtype->size, sizeof(ffi_arg)));
1265
1266 #ifdef _Py_MEMORY_SANITIZER
1267 /* ffi_call actually initializes resbuf, but from asm, which
1268 * MemorySanitizer can't detect. Avoid false positives from MSan. */
1269 if (resbuf != NULL) {
1270 __msan_unpoison(resbuf, max(rtype->size, sizeof(ffi_arg)));
1271 }
1272 #endif
1273 avalues = (void **)alloca(sizeof(void *) * argcount);
1274 atypes = (ffi_type **)alloca(sizeof(ffi_type *) * argcount);
1275 if (!resbuf || !avalues || !atypes) {
1276 PyErr_NoMemory();
1277 goto cleanup;
1278 }
1279 for (i = 0; i < argcount; ++i) {
1280 atypes[i] = args[i].ffi_type;
1281 #ifdef CTYPES_PASS_BY_REF_HACK
1282 size_t size = atypes[i]->size;
1283 if (IS_PASS_BY_REF(size)) {
1284 void *tmp = alloca(size);
1285 if (atypes[i]->type == FFI_TYPE_STRUCT)
1286 memcpy(tmp, args[i].value.p, size);
1287 else
1288 memcpy(tmp, (void*)&args[i].value, size);
1289
1290 avalues[i] = tmp;
1291 }
1292 else
1293 #endif
1294 if (atypes[i]->type == FFI_TYPE_STRUCT)
1295 avalues[i] = (void *)args[i].value.p;
1296 else
1297 avalues[i] = (void *)&args[i].value;
1298 }
1299
1300 if (-1 == _call_function_pointer(st, flags, pProc, avalues, atypes,
1301 rtype, resbuf,
1302 Py_SAFE_DOWNCAST(argcount, Py_ssize_t, int),
1303 Py_SAFE_DOWNCAST(argtype_count, Py_ssize_t, int)))
1304 goto cleanup;
1305
1306 #ifdef WORDS_BIGENDIAN
1307 /* libffi returns the result in a buffer with sizeof(ffi_arg). This
1308 causes problems on big endian machines, since the result buffer
1309 address cannot simply be used as result pointer, instead we must
1310 adjust the pointer value:
1311 */
1312 /*
1313 XXX I should find out and clarify why this is needed at all,
1314 especially why adjusting for ffi_type_float must be avoided on
1315 64-bit platforms.
1316 */
1317 if (rtype->type != FFI_TYPE_FLOAT
1318 && rtype->type != FFI_TYPE_STRUCT
1319 && rtype->size < sizeof(ffi_arg))
1320 {
1321 resbuf = (char *)resbuf + sizeof(ffi_arg) - rtype->size;
1322 }
1323 #endif
1324
1325 #ifdef MS_WIN32
1326 if (iid && pIunk) {
1327 if (*(int *)resbuf & 0x80000000)
1328 retval = GetComError(st, *(HRESULT *)resbuf, iid, pIunk);
1329 else
1330 retval = PyLong_FromLong(*(int *)resbuf);
1331 } else if (flags & FUNCFLAG_HRESULT) {
1332 if (*(int *)resbuf & 0x80000000)
1333 retval = PyErr_SetFromWindowsErr(*(int *)resbuf);
1334 else
1335 retval = PyLong_FromLong(*(int *)resbuf);
1336 } else
1337 #endif
1338 retval = GetResult(st, restype, resbuf, checker);
1339 cleanup:
1340 for (i = 0; i < argcount; ++i)
1341 Py_XDECREF(args[i].keep);
1342 return retval;
1343 }
1344
1345 static int
_parse_voidp(PyObject * obj,void ** address)1346 _parse_voidp(PyObject *obj, void **address)
1347 {
1348 *address = PyLong_AsVoidPtr(obj);
1349 if (*address == NULL)
1350 return 0;
1351 return 1;
1352 }
1353
1354 #ifdef MS_WIN32
1355
1356 PyDoc_STRVAR(format_error_doc,
1357 "FormatError([integer]) -> string\n\
1358 \n\
1359 Convert a win32 error code into a string. If the error code is not\n\
1360 given, the return value of a call to GetLastError() is used.\n");
format_error(PyObject * self,PyObject * args)1361 static PyObject *format_error(PyObject *self, PyObject *args)
1362 {
1363 PyObject *result;
1364 wchar_t *lpMsgBuf;
1365 DWORD code = 0;
1366 if (!PyArg_ParseTuple(args, "|i:FormatError", &code))
1367 return NULL;
1368 if (code == 0)
1369 code = GetLastError();
1370 lpMsgBuf = FormatError(code);
1371 if (lpMsgBuf) {
1372 result = PyUnicode_FromWideChar(lpMsgBuf, wcslen(lpMsgBuf));
1373 LocalFree(lpMsgBuf);
1374 } else {
1375 result = PyUnicode_FromString("<no description>");
1376 }
1377 return result;
1378 }
1379
1380 PyDoc_STRVAR(load_library_doc,
1381 "LoadLibrary(name, load_flags) -> handle\n\
1382 \n\
1383 Load an executable (usually a DLL), and return a handle to it.\n\
1384 The handle may be used to locate exported functions in this\n\
1385 module. load_flags are as defined for LoadLibraryEx in the\n\
1386 Windows API.\n");
load_library(PyObject * self,PyObject * args)1387 static PyObject *load_library(PyObject *self, PyObject *args)
1388 {
1389 PyObject *nameobj;
1390 int load_flags = 0;
1391 HMODULE hMod;
1392 DWORD err;
1393
1394 if (!PyArg_ParseTuple(args, "U|i:LoadLibrary", &nameobj, &load_flags))
1395 return NULL;
1396
1397 if (PySys_Audit("ctypes.dlopen", "O", nameobj) < 0) {
1398 return NULL;
1399 }
1400
1401 WCHAR *name = PyUnicode_AsWideCharString(nameobj, NULL);
1402 if (!name)
1403 return NULL;
1404
1405 Py_BEGIN_ALLOW_THREADS
1406 /* bpo-36085: Limit DLL search directories to avoid pre-loading
1407 * attacks and enable use of the AddDllDirectory function.
1408 */
1409 hMod = LoadLibraryExW(name, NULL, (DWORD)load_flags);
1410 err = hMod ? 0 : GetLastError();
1411 Py_END_ALLOW_THREADS
1412
1413 PyMem_Free(name);
1414 if (err == ERROR_MOD_NOT_FOUND) {
1415 PyErr_Format(PyExc_FileNotFoundError,
1416 ("Could not find module '%.500S' (or one of its "
1417 "dependencies). Try using the full path with "
1418 "constructor syntax."),
1419 nameobj);
1420 return NULL;
1421 } else if (err) {
1422 return PyErr_SetFromWindowsErr(err);
1423 }
1424 #ifdef _WIN64
1425 return PyLong_FromVoidPtr(hMod);
1426 #else
1427 return PyLong_FromLong((int)hMod);
1428 #endif
1429 }
1430
1431 PyDoc_STRVAR(free_library_doc,
1432 "FreeLibrary(handle) -> void\n\
1433 \n\
1434 Free the handle of an executable previously loaded by LoadLibrary.\n");
free_library(PyObject * self,PyObject * args)1435 static PyObject *free_library(PyObject *self, PyObject *args)
1436 {
1437 void *hMod;
1438 BOOL result;
1439 DWORD err;
1440 if (!PyArg_ParseTuple(args, "O&:FreeLibrary", &_parse_voidp, &hMod))
1441 return NULL;
1442
1443 Py_BEGIN_ALLOW_THREADS
1444 result = FreeLibrary((HMODULE)hMod);
1445 err = result ? 0 : GetLastError();
1446 Py_END_ALLOW_THREADS
1447
1448 if (!result) {
1449 return PyErr_SetFromWindowsErr(err);
1450 }
1451 Py_RETURN_NONE;
1452 }
1453
1454 PyDoc_STRVAR(copy_com_pointer_doc,
1455 "CopyComPointer(src, dst) -> HRESULT value\n");
1456
1457 static PyObject *
copy_com_pointer(PyObject * self,PyObject * args)1458 copy_com_pointer(PyObject *self, PyObject *args)
1459 {
1460 PyObject *p1, *p2, *r = NULL;
1461 struct argument a, b;
1462 IUnknown *src, **pdst;
1463 if (!PyArg_ParseTuple(args, "OO:CopyComPointer", &p1, &p2))
1464 return NULL;
1465 a.keep = b.keep = NULL;
1466
1467 ctypes_state *st = get_module_state(self);
1468 if (ConvParam(st, p1, 0, &a) < 0 || ConvParam(st, p2, 1, &b) < 0) {
1469 goto done;
1470 }
1471 src = (IUnknown *)a.value.p;
1472 pdst = (IUnknown **)b.value.p;
1473
1474 if (pdst == NULL)
1475 r = PyLong_FromLong(E_POINTER);
1476 else {
1477 if (src)
1478 src->lpVtbl->AddRef(src);
1479 *pdst = src;
1480 r = PyLong_FromLong(S_OK);
1481 }
1482 done:
1483 Py_XDECREF(a.keep);
1484 Py_XDECREF(b.keep);
1485 return r;
1486 }
1487 #else
1488 #ifdef __APPLE__
1489 #ifdef HAVE_DYLD_SHARED_CACHE_CONTAINS_PATH
1490 # ifdef HAVE_BUILTIN_AVAILABLE
1491 # define HAVE_DYLD_SHARED_CACHE_CONTAINS_PATH_RUNTIME \
1492 __builtin_available(macOS 11.0, iOS 14.0, tvOS 14.0, watchOS 7.0, *)
1493 # else
1494 # define HAVE_DYLD_SHARED_CACHE_CONTAINS_PATH_RUNTIME \
1495 (_dyld_shared_cache_contains_path != NULL)
1496 # endif
1497 #else
1498 // Support the deprecated case of compiling on an older macOS version
1499 static void *libsystem_b_handle;
1500 static bool (*_dyld_shared_cache_contains_path)(const char *path);
1501
load_dyld_shared_cache_contains_path(void)1502 __attribute__((constructor)) void load_dyld_shared_cache_contains_path(void) {
1503 libsystem_b_handle = dlopen("/usr/lib/libSystem.B.dylib", RTLD_LAZY);
1504 if (libsystem_b_handle != NULL) {
1505 _dyld_shared_cache_contains_path = dlsym(libsystem_b_handle, "_dyld_shared_cache_contains_path");
1506 }
1507 }
1508
unload_dyld_shared_cache_contains_path(void)1509 __attribute__((destructor)) void unload_dyld_shared_cache_contains_path(void) {
1510 if (libsystem_b_handle != NULL) {
1511 dlclose(libsystem_b_handle);
1512 }
1513 }
1514 #define HAVE_DYLD_SHARED_CACHE_CONTAINS_PATH_RUNTIME \
1515 _dyld_shared_cache_contains_path != NULL
1516 #endif
1517
py_dyld_shared_cache_contains_path(PyObject * self,PyObject * args)1518 static PyObject *py_dyld_shared_cache_contains_path(PyObject *self, PyObject *args)
1519 {
1520 PyObject *name, *name2;
1521 char *name_str;
1522
1523 if (HAVE_DYLD_SHARED_CACHE_CONTAINS_PATH_RUNTIME) {
1524 int r;
1525
1526 if (!PyArg_ParseTuple(args, "O", &name))
1527 return NULL;
1528
1529 if (name == Py_None)
1530 Py_RETURN_FALSE;
1531
1532 if (PyUnicode_FSConverter(name, &name2) == 0)
1533 return NULL;
1534 name_str = PyBytes_AS_STRING(name2);
1535
1536 r = _dyld_shared_cache_contains_path(name_str);
1537 Py_DECREF(name2);
1538
1539 if (r) {
1540 Py_RETURN_TRUE;
1541 } else {
1542 Py_RETURN_FALSE;
1543 }
1544
1545 } else {
1546 PyErr_SetString(PyExc_NotImplementedError, "_dyld_shared_cache_contains_path symbol is missing");
1547 return NULL;
1548 }
1549
1550 }
1551 #endif
1552
py_dl_open(PyObject * self,PyObject * args)1553 static PyObject *py_dl_open(PyObject *self, PyObject *args)
1554 {
1555 PyObject *name, *name2;
1556 const char *name_str;
1557 void * handle;
1558 #if HAVE_DECL_RTLD_LOCAL
1559 int mode = RTLD_NOW | RTLD_LOCAL;
1560 #else
1561 /* cygwin doesn't define RTLD_LOCAL */
1562 int mode = RTLD_NOW;
1563 #endif
1564 if (!PyArg_ParseTuple(args, "O|i:dlopen", &name, &mode))
1565 return NULL;
1566 mode |= RTLD_NOW;
1567 if (name != Py_None) {
1568 if (PyUnicode_FSConverter(name, &name2) == 0)
1569 return NULL;
1570 name_str = PyBytes_AS_STRING(name2);
1571 } else {
1572 name_str = NULL;
1573 name2 = NULL;
1574 }
1575 if (PySys_Audit("ctypes.dlopen", "O", name) < 0) {
1576 return NULL;
1577 }
1578 handle = dlopen(name_str, mode);
1579 Py_XDECREF(name2);
1580 if (!handle) {
1581 const char *errmsg = dlerror();
1582 if (!errmsg)
1583 errmsg = "dlopen() error";
1584 PyErr_SetString(PyExc_OSError,
1585 errmsg);
1586 return NULL;
1587 }
1588 return PyLong_FromVoidPtr(handle);
1589 }
1590
py_dl_close(PyObject * self,PyObject * args)1591 static PyObject *py_dl_close(PyObject *self, PyObject *args)
1592 {
1593 void *handle;
1594
1595 if (!PyArg_ParseTuple(args, "O&:dlclose", &_parse_voidp, &handle))
1596 return NULL;
1597 if (dlclose(handle)) {
1598 PyErr_SetString(PyExc_OSError,
1599 dlerror());
1600 return NULL;
1601 }
1602 Py_RETURN_NONE;
1603 }
1604
py_dl_sym(PyObject * self,PyObject * args)1605 static PyObject *py_dl_sym(PyObject *self, PyObject *args)
1606 {
1607 char *name;
1608 void *handle;
1609 void *ptr;
1610
1611 if (!PyArg_ParseTuple(args, "O&s:dlsym",
1612 &_parse_voidp, &handle, &name))
1613 return NULL;
1614 if (PySys_Audit("ctypes.dlsym/handle", "O", args) < 0) {
1615 return NULL;
1616 }
1617 #undef USE_DLERROR
1618 #ifdef __CYGWIN__
1619 // dlerror() isn't very helpful on cygwin
1620 #else
1621 #define USE_DLERROR
1622 /* dlerror() always returns the latest error.
1623 *
1624 * Clear the previous value before calling dlsym(),
1625 * to ensure we can tell if our call resulted in an error.
1626 */
1627 (void)dlerror();
1628 #endif
1629 ptr = dlsym((void*)handle, name);
1630 if (ptr) {
1631 return PyLong_FromVoidPtr(ptr);
1632 }
1633 #ifdef USE_DLERROR
1634 const char *dlerr = dlerror();
1635 if (dlerr) {
1636 PyObject *message = PyUnicode_DecodeLocale(dlerr, "surrogateescape");
1637 if (message) {
1638 PyErr_SetObject(PyExc_OSError, message);
1639 Py_DECREF(message);
1640 return NULL;
1641 }
1642 // Ignore errors from PyUnicode_DecodeLocale,
1643 // fall back to the generic error below.
1644 PyErr_Clear();
1645 }
1646 #endif
1647 #undef USE_DLERROR
1648 PyErr_Format(PyExc_OSError, "symbol '%s' not found", name);
1649 return NULL;
1650 }
1651 #endif
1652
1653 /*
1654 * Only for debugging so far: So that we can call CFunction instances
1655 *
1656 * XXX Needs to accept more arguments: flags, argtypes, restype
1657 */
1658 static PyObject *
call_function(PyObject * self,PyObject * args)1659 call_function(PyObject *self, PyObject *args)
1660 {
1661 void *func;
1662 PyObject *arguments;
1663 PyObject *result;
1664
1665 if (!PyArg_ParseTuple(args,
1666 "O&O!",
1667 &_parse_voidp, &func,
1668 &PyTuple_Type, &arguments))
1669 return NULL;
1670 if (PySys_Audit("ctypes.call_function", "nO",
1671 (Py_ssize_t)func, arguments) < 0) {
1672 return NULL;
1673 }
1674
1675 ctypes_state *st = get_module_state(self);
1676 result = _ctypes_callproc(st,
1677 (PPROC)func,
1678 arguments,
1679 #ifdef MS_WIN32
1680 NULL,
1681 NULL,
1682 #endif
1683 0, /* flags */
1684 NULL, /* self->argtypes */
1685 NULL, /* self->restype */
1686 NULL); /* checker */
1687 return result;
1688 }
1689
1690 /*
1691 * Only for debugging so far: So that we can call CFunction instances
1692 *
1693 * XXX Needs to accept more arguments: flags, argtypes, restype
1694 */
1695 static PyObject *
call_cdeclfunction(PyObject * self,PyObject * args)1696 call_cdeclfunction(PyObject *self, PyObject *args)
1697 {
1698 void *func;
1699 PyObject *arguments;
1700 PyObject *result;
1701
1702 if (!PyArg_ParseTuple(args,
1703 "O&O!",
1704 &_parse_voidp, &func,
1705 &PyTuple_Type, &arguments))
1706 return NULL;
1707 if (PySys_Audit("ctypes.call_function", "nO",
1708 (Py_ssize_t)func, arguments) < 0) {
1709 return NULL;
1710 }
1711
1712 ctypes_state *st = get_module_state(self);
1713 result = _ctypes_callproc(st,
1714 (PPROC)func,
1715 arguments,
1716 #ifdef MS_WIN32
1717 NULL,
1718 NULL,
1719 #endif
1720 FUNCFLAG_CDECL, /* flags */
1721 NULL, /* self->argtypes */
1722 NULL, /* self->restype */
1723 NULL); /* checker */
1724 return result;
1725 }
1726
1727 /*****************************************************************
1728 * functions
1729 */
1730 PyDoc_STRVAR(sizeof_doc,
1731 "sizeof(C type) -> integer\n"
1732 "sizeof(C instance) -> integer\n"
1733 "Return the size in bytes of a C instance");
1734
1735 static PyObject *
sizeof_func(PyObject * self,PyObject * obj)1736 sizeof_func(PyObject *self, PyObject *obj)
1737 {
1738 ctypes_state *st = get_module_state(self);
1739
1740 StgInfo *info;
1741 if (PyStgInfo_FromType(st, obj, &info) < 0) {
1742 return NULL;
1743 }
1744 if (info) {
1745 return PyLong_FromSsize_t(info->size);
1746 }
1747
1748 if (CDataObject_Check(st, obj)) {
1749 return PyLong_FromSsize_t(((CDataObject *)obj)->b_size);
1750 }
1751 PyErr_SetString(PyExc_TypeError,
1752 "this type has no size");
1753 return NULL;
1754 }
1755
1756 PyDoc_STRVAR(alignment_doc,
1757 "alignment(C type) -> integer\n"
1758 "alignment(C instance) -> integer\n"
1759 "Return the alignment requirements of a C instance");
1760
1761 static PyObject *
align_func(PyObject * self,PyObject * obj)1762 align_func(PyObject *self, PyObject *obj)
1763 {
1764 ctypes_state *st = get_module_state(self);
1765 StgInfo *info;
1766 if (PyStgInfo_FromAny(st, obj, &info) < 0) {
1767 return NULL;
1768 }
1769 if (info) {
1770 return PyLong_FromSsize_t(info->align);
1771 }
1772 PyErr_SetString(PyExc_TypeError,
1773 "no alignment info");
1774 return NULL;
1775 }
1776
1777 PyDoc_STRVAR(byref_doc,
1778 "byref(C instance[, offset=0]) -> byref-object\n"
1779 "Return a pointer lookalike to a C instance, only usable\n"
1780 "as function argument");
1781
1782 /*
1783 * We must return something which can be converted to a parameter,
1784 * but still has a reference to self.
1785 */
1786 static PyObject *
byref(PyObject * self,PyObject * args)1787 byref(PyObject *self, PyObject *args)
1788 {
1789 PyCArgObject *parg;
1790 PyObject *obj;
1791 PyObject *pyoffset = NULL;
1792 Py_ssize_t offset = 0;
1793
1794 if (!PyArg_UnpackTuple(args, "byref", 1, 2,
1795 &obj, &pyoffset))
1796 return NULL;
1797 if (pyoffset) {
1798 offset = PyNumber_AsSsize_t(pyoffset, NULL);
1799 if (offset == -1 && PyErr_Occurred())
1800 return NULL;
1801 }
1802 ctypes_state *st = get_module_state(self);
1803 if (!CDataObject_Check(st, obj)) {
1804 PyErr_Format(PyExc_TypeError,
1805 "byref() argument must be a ctypes instance, not '%s'",
1806 Py_TYPE(obj)->tp_name);
1807 return NULL;
1808 }
1809
1810 parg = PyCArgObject_new(st);
1811 if (parg == NULL)
1812 return NULL;
1813
1814 parg->tag = 'P';
1815 parg->pffi_type = &ffi_type_pointer;
1816 parg->obj = Py_NewRef(obj);
1817 parg->value.p = (char *)((CDataObject *)obj)->b_ptr + offset;
1818 return (PyObject *)parg;
1819 }
1820
1821 PyDoc_STRVAR(addressof_doc,
1822 "addressof(C instance) -> integer\n"
1823 "Return the address of the C instance internal buffer");
1824
1825 static PyObject *
addressof(PyObject * self,PyObject * obj)1826 addressof(PyObject *self, PyObject *obj)
1827 {
1828 ctypes_state *st = get_module_state(self);
1829 if (!CDataObject_Check(st, obj)) {
1830 PyErr_SetString(PyExc_TypeError,
1831 "invalid type");
1832 return NULL;
1833 }
1834 if (PySys_Audit("ctypes.addressof", "(O)", obj) < 0) {
1835 return NULL;
1836 }
1837 return PyLong_FromVoidPtr(((CDataObject *)obj)->b_ptr);
1838 }
1839
1840 static int
converter(PyObject * obj,void ** address)1841 converter(PyObject *obj, void **address)
1842 {
1843 *address = PyLong_AsVoidPtr(obj);
1844 return *address != NULL;
1845 }
1846
1847 static PyObject *
My_PyObj_FromPtr(PyObject * self,PyObject * args)1848 My_PyObj_FromPtr(PyObject *self, PyObject *args)
1849 {
1850 PyObject *ob;
1851 if (!PyArg_ParseTuple(args, "O&:PyObj_FromPtr", converter, &ob)) {
1852 return NULL;
1853 }
1854 if (PySys_Audit("ctypes.PyObj_FromPtr", "(O)", ob) < 0) {
1855 return NULL;
1856 }
1857 return Py_NewRef(ob);
1858 }
1859
1860 static PyObject *
My_Py_INCREF(PyObject * self,PyObject * arg)1861 My_Py_INCREF(PyObject *self, PyObject *arg)
1862 {
1863 Py_INCREF(arg); /* that's what this function is for */
1864 Py_INCREF(arg); /* that for returning it */
1865 return arg;
1866 }
1867
1868 static PyObject *
My_Py_DECREF(PyObject * self,PyObject * arg)1869 My_Py_DECREF(PyObject *self, PyObject *arg)
1870 {
1871 Py_DECREF(arg); /* that's what this function is for */
1872 Py_INCREF(arg); /* that's for returning it */
1873 return arg;
1874 }
1875
1876 static PyObject *
resize(PyObject * self,PyObject * args)1877 resize(PyObject *self, PyObject *args)
1878 {
1879 CDataObject *obj;
1880 Py_ssize_t size;
1881
1882 if (!PyArg_ParseTuple(args,
1883 "On:resize",
1884 &obj, &size))
1885 return NULL;
1886
1887 ctypes_state *st = get_module_state(self);
1888 StgInfo *info;
1889 int result = PyStgInfo_FromObject(st, (PyObject *)obj, &info);
1890 if (result < 0) {
1891 return NULL;
1892 }
1893 if (info == NULL) {
1894 PyErr_SetString(PyExc_TypeError,
1895 "expected ctypes instance");
1896 return NULL;
1897 }
1898 if (size < info->size) {
1899 PyErr_Format(PyExc_ValueError,
1900 "minimum size is %zd",
1901 info->size);
1902 return NULL;
1903 }
1904 if (obj->b_needsfree == 0) {
1905 PyErr_Format(PyExc_ValueError,
1906 "Memory cannot be resized because this object doesn't own it");
1907 return NULL;
1908 }
1909 if ((size_t)size <= sizeof(obj->b_value)) {
1910 /* internal default buffer is large enough */
1911 obj->b_size = size;
1912 goto done;
1913 }
1914 if (!_CDataObject_HasExternalBuffer(obj)) {
1915 /* We are currently using the objects default buffer, but it
1916 isn't large enough any more. */
1917 void *ptr = PyMem_Calloc(1, size);
1918 if (ptr == NULL)
1919 return PyErr_NoMemory();
1920 memmove(ptr, obj->b_ptr, obj->b_size);
1921 obj->b_ptr = ptr;
1922 obj->b_size = size;
1923 } else {
1924 void * ptr = PyMem_Realloc(obj->b_ptr, size);
1925 if (ptr == NULL)
1926 return PyErr_NoMemory();
1927 obj->b_ptr = ptr;
1928 obj->b_size = size;
1929 }
1930 done:
1931 Py_RETURN_NONE;
1932 }
1933
1934 static PyObject *
unpickle(PyObject * self,PyObject * args)1935 unpickle(PyObject *self, PyObject *args)
1936 {
1937 PyObject *typ, *state, *meth, *obj, *result;
1938
1939 if (!PyArg_ParseTuple(args, "OO!", &typ, &PyTuple_Type, &state))
1940 return NULL;
1941 obj = PyObject_CallMethodOneArg(typ, &_Py_ID(__new__), typ);
1942 if (obj == NULL)
1943 return NULL;
1944
1945 meth = PyObject_GetAttr(obj, &_Py_ID(__setstate__));
1946 if (meth == NULL) {
1947 goto error;
1948 }
1949
1950 result = PyObject_Call(meth, state, NULL);
1951 Py_DECREF(meth);
1952 if (result == NULL) {
1953 goto error;
1954 }
1955 Py_DECREF(result);
1956
1957 return obj;
1958
1959 error:
1960 Py_DECREF(obj);
1961 return NULL;
1962 }
1963
1964 /*[clinic input]
1965 _ctypes.POINTER as create_pointer_type
1966
1967 type as cls: object
1968 A ctypes type.
1969 /
1970
1971 Create and return a new ctypes pointer type.
1972
1973 Pointer types are cached and reused internally,
1974 so calling this function repeatedly is cheap.
1975 [clinic start generated code]*/
1976
1977 static PyObject *
create_pointer_type(PyObject * module,PyObject * cls)1978 create_pointer_type(PyObject *module, PyObject *cls)
1979 /*[clinic end generated code: output=98c3547ab6f4f40b input=3b81cff5ff9b9d5b]*/
1980 {
1981 PyObject *result;
1982 PyTypeObject *typ;
1983 PyObject *key;
1984
1985 assert(module);
1986 ctypes_state *st = get_module_state(module);
1987 if (PyDict_GetItemRef(st->_ctypes_ptrtype_cache, cls, &result) != 0) {
1988 // found or error
1989 return result;
1990 }
1991 // not found
1992 if (PyUnicode_CheckExact(cls)) {
1993 PyObject *name = PyUnicode_FromFormat("LP_%U", cls);
1994 result = PyObject_CallFunction((PyObject *)Py_TYPE(st->PyCPointer_Type),
1995 "N(O){}",
1996 name,
1997 st->PyCPointer_Type);
1998 if (result == NULL)
1999 return result;
2000 key = PyLong_FromVoidPtr(result);
2001 if (key == NULL) {
2002 Py_DECREF(result);
2003 return NULL;
2004 }
2005 } else if (PyType_Check(cls)) {
2006 typ = (PyTypeObject *)cls;
2007 PyObject *name = PyUnicode_FromFormat("LP_%s", typ->tp_name);
2008 result = PyObject_CallFunction((PyObject *)Py_TYPE(st->PyCPointer_Type),
2009 "N(O){sO}",
2010 name,
2011 st->PyCPointer_Type,
2012 "_type_", cls);
2013 if (result == NULL)
2014 return result;
2015 key = Py_NewRef(cls);
2016 } else {
2017 PyErr_SetString(PyExc_TypeError, "must be a ctypes type");
2018 return NULL;
2019 }
2020 if (PyDict_SetItem(st->_ctypes_ptrtype_cache, key, result) < 0) {
2021 Py_DECREF(result);
2022 Py_DECREF(key);
2023 return NULL;
2024 }
2025 Py_DECREF(key);
2026 return result;
2027 }
2028
2029 /*[clinic input]
2030 _ctypes.pointer as create_pointer_inst
2031
2032 obj as arg: object
2033 /
2034
2035 Create a new pointer instance, pointing to 'obj'.
2036
2037 The returned object is of the type POINTER(type(obj)). Note that if you
2038 just want to pass a pointer to an object to a foreign function call, you
2039 should use byref(obj) which is much faster.
2040 [clinic start generated code]*/
2041
2042 static PyObject *
create_pointer_inst(PyObject * module,PyObject * arg)2043 create_pointer_inst(PyObject *module, PyObject *arg)
2044 /*[clinic end generated code: output=3b543bc9f0de2180 input=713685fdb4d9bc27]*/
2045 {
2046 PyObject *result;
2047 PyObject *typ;
2048
2049 ctypes_state *st = get_module_state(module);
2050 if (PyDict_GetItemRef(st->_ctypes_ptrtype_cache, (PyObject *)Py_TYPE(arg), &typ) < 0) {
2051 return NULL;
2052 }
2053 if (typ == NULL) {
2054 typ = create_pointer_type(module, (PyObject *)Py_TYPE(arg));
2055 if (typ == NULL)
2056 return NULL;
2057 }
2058 result = PyObject_CallOneArg(typ, arg);
2059 Py_DECREF(typ);
2060 return result;
2061 }
2062
2063 static PyObject *
buffer_info(PyObject * self,PyObject * arg)2064 buffer_info(PyObject *self, PyObject *arg)
2065 {
2066 PyObject *shape;
2067 Py_ssize_t i;
2068
2069 ctypes_state *st = get_module_state(self);
2070 StgInfo *info;
2071 if (PyStgInfo_FromAny(st, arg, &info) < 0) {
2072 return NULL;
2073 }
2074 if (info == NULL) {
2075 PyErr_SetString(PyExc_TypeError,
2076 "not a ctypes type or object");
2077 return NULL;
2078 }
2079 shape = PyTuple_New(info->ndim);
2080 if (shape == NULL)
2081 return NULL;
2082 for (i = 0; i < (int)info->ndim; ++i)
2083 PyTuple_SET_ITEM(shape, i, PyLong_FromSsize_t(info->shape[i]));
2084
2085 if (PyErr_Occurred()) {
2086 Py_DECREF(shape);
2087 return NULL;
2088 }
2089 return Py_BuildValue("siN", info->format, info->ndim, shape);
2090 }
2091
2092
2093
2094 PyMethodDef _ctypes_module_methods[] = {
2095 {"get_errno", get_errno, METH_NOARGS},
2096 {"set_errno", set_errno, METH_VARARGS},
2097 CREATE_POINTER_TYPE_METHODDEF
2098 CREATE_POINTER_INST_METHODDEF
2099 {"_unpickle", unpickle, METH_VARARGS },
2100 {"buffer_info", buffer_info, METH_O, "Return buffer interface information"},
2101 {"resize", resize, METH_VARARGS, "Resize the memory buffer of a ctypes instance"},
2102 #ifdef MS_WIN32
2103 {"get_last_error", get_last_error, METH_NOARGS},
2104 {"set_last_error", set_last_error, METH_VARARGS},
2105 {"CopyComPointer", copy_com_pointer, METH_VARARGS, copy_com_pointer_doc},
2106 {"FormatError", format_error, METH_VARARGS, format_error_doc},
2107 {"LoadLibrary", load_library, METH_VARARGS, load_library_doc},
2108 {"FreeLibrary", free_library, METH_VARARGS, free_library_doc},
2109 {"_check_HRESULT", check_hresult, METH_VARARGS},
2110 #else
2111 {"dlopen", py_dl_open, METH_VARARGS,
2112 "dlopen(name, flag={RTLD_GLOBAL|RTLD_LOCAL}) open a shared library"},
2113 {"dlclose", py_dl_close, METH_VARARGS, "dlclose a library"},
2114 {"dlsym", py_dl_sym, METH_VARARGS, "find symbol in shared library"},
2115 #endif
2116 #ifdef __APPLE__
2117 {"_dyld_shared_cache_contains_path", py_dyld_shared_cache_contains_path, METH_VARARGS, "check if path is in the shared cache"},
2118 #endif
2119 {"alignment", align_func, METH_O, alignment_doc},
2120 {"sizeof", sizeof_func, METH_O, sizeof_doc},
2121 {"byref", byref, METH_VARARGS, byref_doc},
2122 {"addressof", addressof, METH_O, addressof_doc},
2123 {"call_function", call_function, METH_VARARGS },
2124 {"call_cdeclfunction", call_cdeclfunction, METH_VARARGS },
2125 {"PyObj_FromPtr", My_PyObj_FromPtr, METH_VARARGS },
2126 {"Py_INCREF", My_Py_INCREF, METH_O },
2127 {"Py_DECREF", My_Py_DECREF, METH_O },
2128 {NULL, NULL} /* Sentinel */
2129 };
2130
2131 /*
2132 Local Variables:
2133 compile-command: "cd .. && python setup.py -q build -g && python setup.py -q build install --home ~"
2134 End:
2135 */
2136