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