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