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