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