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