blob: f5d8f52e3f9b42d232944a8ec1d679bda8bc49f9 [file] [log] [blame]
Thomas Hellerd4c93202006-03-08 19:35:11 +00001/*
2 * History: First version dated from 3/97, derived from my SCMLIB version
3 * for win16.
4 */
5/*
6 * Related Work:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007 * - calldll http://www.nightmare.com/software.html
8 * - libffi http://sourceware.cygnus.com/libffi/
9 * - ffcall http://clisp.cons.org/~haible/packages-ffcall.html
Thomas Hellerd4c93202006-03-08 19:35:11 +000010 * and, of course, Don Beaudry's MESS package, but this is more ctypes
11 * related.
12 */
13
14
15/*
16 How are functions called, and how are parameters converted to C ?
17
Thomas Heller34596a92009-04-24 20:50:00 +000018 1. _ctypes.c::PyCFuncPtr_call receives an argument tuple 'inargs' and a
Thomas Hellerd4c93202006-03-08 19:35:11 +000019 keyword dictionary 'kwds'.
20
21 2. After several checks, _build_callargs() is called which returns another
22 tuple 'callargs'. This may be the same tuple as 'inargs', a slice of
Terry Jan Reedy0158af32013-03-11 17:42:46 -040023 'inargs', or a completely fresh tuple, depending on several things (is it a
24 COM method?, are 'paramflags' available?).
Thomas Hellerd4c93202006-03-08 19:35:11 +000025
26 3. _build_callargs also calculates bitarrays containing indexes into
27 the callargs tuple, specifying how to build the return value(s) of
28 the function.
29
Thomas Heller34596a92009-04-24 20:50:00 +000030 4. _ctypes_callproc is then called with the 'callargs' tuple. _ctypes_callproc first
Thomas Hellerd4c93202006-03-08 19:35:11 +000031 allocates two arrays. The first is an array of 'struct argument' items, the
Ezio Melotti13925002011-03-16 11:05:33 +020032 second array has 'void *' entries.
Thomas Hellerd4c93202006-03-08 19:35:11 +000033
34 5. If 'converters' are present (converters is a sequence of argtypes'
35 from_param methods), for each item in 'callargs' converter is called and the
36 result passed to ConvParam. If 'converters' are not present, each argument
37 is directly passed to ConvParm.
38
39 6. For each arg, ConvParam stores the contained C data (or a pointer to it,
40 for structures) into the 'struct argument' array.
41
42 7. Finally, a loop fills the 'void *' array so that each item points to the
43 data contained in or pointed to by the 'struct argument' array.
44
45 8. The 'void *' argument array is what _call_function_pointer
46 expects. _call_function_pointer then has very little to do - only some
47 libffi specific stuff, then it calls ffi_call.
48
49 So, there are 4 data structures holding processed arguments:
Thomas Heller34596a92009-04-24 20:50:00 +000050 - the inargs tuple (in PyCFuncPtr_call)
51 - the callargs tuple (in PyCFuncPtr_call)
Ezio Melotti42da6632011-03-15 05:18:48 +020052 - the 'struct arguments' array
Thomas Hellerd4c93202006-03-08 19:35:11 +000053 - the 'void *' array
54
55 */
56
57#include "Python.h"
58#include "structmember.h"
59
60#ifdef MS_WIN32
61#include <windows.h>
Guido van Rossumd8faa362007-04-27 19:54:29 +000062#include <tchar.h>
Thomas Hellerd4c93202006-03-08 19:35:11 +000063#else
64#include "ctypes_dlfcn.h"
65#endif
66
67#ifdef MS_WIN32
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000068#include <malloc.h>
Thomas Hellerd4c93202006-03-08 19:35:11 +000069#endif
70
71#include <ffi.h>
72#include "ctypes.h"
73
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000074#if defined(_DEBUG) || defined(__MINGW32__)
75/* Don't use structured exception handling on Windows if this is defined.
76 MingW, AFAIK, doesn't support it.
77*/
78#define DONT_USE_SEH
Thomas Hellerd4c93202006-03-08 19:35:11 +000079#endif
80
Benjamin Petersonb173f782009-05-05 22:31:58 +000081#define CTYPES_CAPSULE_NAME_PYMEM "_ctypes pymem"
82
83static void pymem_destructor(PyObject *ptr)
84{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000085 void *p = PyCapsule_GetPointer(ptr, CTYPES_CAPSULE_NAME_PYMEM);
86 if (p) {
87 PyMem_Free(p);
88 }
Benjamin Petersonb173f782009-05-05 22:31:58 +000089}
90
Thomas Heller9cac7b62008-06-06 09:31:40 +000091/*
92 ctypes maintains thread-local storage that has space for two error numbers:
93 private copies of the system 'errno' value and, on Windows, the system error code
94 accessed by the GetLastError() and SetLastError() api functions.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000095
Thomas Heller9cac7b62008-06-06 09:31:40 +000096 Foreign functions created with CDLL(..., use_errno=True), when called, swap
97 the system 'errno' value with the private copy just before the actual
98 function call, and swapped again immediately afterwards. The 'use_errno'
99 parameter defaults to False, in this case 'ctypes_errno' is not touched.
100
101 On Windows, foreign functions created with CDLL(..., use_last_error=True) or
102 WinDLL(..., use_last_error=True) swap the system LastError value with the
103 ctypes private copy.
104
105 The values are also swapped immeditately before and after ctypes callback
106 functions are called, if the callbacks are constructed using the new
107 optional use_errno parameter set to True: CFUNCTYPE(..., use_errno=TRUE) or
108 WINFUNCTYPE(..., use_errno=True).
109
110 New ctypes functions are provided to access the ctypes private copies from
111 Python:
112
113 - ctypes.set_errno(value) and ctypes.set_last_error(value) store 'value' in
114 the private copy and returns the previous value.
115
116 - ctypes.get_errno() and ctypes.get_last_error() returns the current ctypes
117 private copies value.
118*/
119
120/*
121 This function creates and returns a thread-local Python object that has
122 space to store two integer error numbers; once created the Python object is
123 kept alive in the thread state dictionary as long as the thread itself.
124*/
125PyObject *
Thomas Heller34596a92009-04-24 20:50:00 +0000126_ctypes_get_errobj(int **pspace)
Thomas Heller9cac7b62008-06-06 09:31:40 +0000127{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000128 PyObject *dict = PyThreadState_GetDict();
129 PyObject *errobj;
130 static PyObject *error_object_name;
131 if (dict == 0) {
132 PyErr_SetString(PyExc_RuntimeError,
133 "cannot get thread state");
134 return NULL;
135 }
136 if (error_object_name == NULL) {
137 error_object_name = PyUnicode_InternFromString("ctypes.error_object");
138 if (error_object_name == NULL)
139 return NULL;
140 }
141 errobj = PyDict_GetItem(dict, error_object_name);
142 if (errobj) {
143 if (!PyCapsule_IsValid(errobj, CTYPES_CAPSULE_NAME_PYMEM)) {
144 PyErr_SetString(PyExc_RuntimeError,
145 "ctypes.error_object is an invalid capsule");
146 return NULL;
147 }
148 Py_INCREF(errobj);
149 }
150 else {
151 void *space = PyMem_Malloc(sizeof(int) * 2);
152 if (space == NULL)
153 return NULL;
154 memset(space, 0, sizeof(int) * 2);
155 errobj = PyCapsule_New(space, CTYPES_CAPSULE_NAME_PYMEM, pymem_destructor);
156 if (errobj == NULL)
157 return NULL;
158 if (-1 == PyDict_SetItem(dict, error_object_name,
159 errobj)) {
160 Py_DECREF(errobj);
161 return NULL;
162 }
163 }
164 *pspace = (int *)PyCapsule_GetPointer(errobj, CTYPES_CAPSULE_NAME_PYMEM);
165 return errobj;
Thomas Heller9cac7b62008-06-06 09:31:40 +0000166}
167
168static PyObject *
169get_error_internal(PyObject *self, PyObject *args, int index)
170{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000171 int *space;
172 PyObject *errobj = _ctypes_get_errobj(&space);
173 PyObject *result;
Thomas Heller9cac7b62008-06-06 09:31:40 +0000174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175 if (errobj == NULL)
176 return NULL;
177 result = PyLong_FromLong(space[index]);
178 Py_DECREF(errobj);
179 return result;
Thomas Heller9cac7b62008-06-06 09:31:40 +0000180}
181
182static PyObject *
183set_error_internal(PyObject *self, PyObject *args, int index)
184{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000185 int new_errno, old_errno;
186 PyObject *errobj;
187 int *space;
Thomas Heller9cac7b62008-06-06 09:31:40 +0000188
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000189 if (!PyArg_ParseTuple(args, "i", &new_errno))
190 return NULL;
191 errobj = _ctypes_get_errobj(&space);
192 if (errobj == NULL)
193 return NULL;
194 old_errno = space[index];
195 space[index] = new_errno;
196 Py_DECREF(errobj);
197 return PyLong_FromLong(old_errno);
Thomas Heller9cac7b62008-06-06 09:31:40 +0000198}
199
200static PyObject *
201get_errno(PyObject *self, PyObject *args)
202{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000203 return get_error_internal(self, args, 0);
Thomas Heller9cac7b62008-06-06 09:31:40 +0000204}
205
206static PyObject *
207set_errno(PyObject *self, PyObject *args)
208{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000209 return set_error_internal(self, args, 0);
Thomas Heller9cac7b62008-06-06 09:31:40 +0000210}
211
Thomas Hellerd4c93202006-03-08 19:35:11 +0000212#ifdef MS_WIN32
Thomas Heller9cac7b62008-06-06 09:31:40 +0000213
214static PyObject *
215get_last_error(PyObject *self, PyObject *args)
216{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000217 return get_error_internal(self, args, 1);
Thomas Heller9cac7b62008-06-06 09:31:40 +0000218}
219
220static PyObject *
221set_last_error(PyObject *self, PyObject *args)
222{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000223 return set_error_internal(self, args, 1);
Thomas Heller9cac7b62008-06-06 09:31:40 +0000224}
225
Thomas Hellerd4c93202006-03-08 19:35:11 +0000226PyObject *ComError;
227
Thomas Heller71fb5132008-11-26 08:45:36 +0000228static WCHAR *FormatError(DWORD code)
Thomas Hellerd4c93202006-03-08 19:35:11 +0000229{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000230 WCHAR *lpMsgBuf;
231 DWORD n;
232 n = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
233 NULL,
234 code,
235 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), /* Default language */
236 (LPWSTR) &lpMsgBuf,
237 0,
238 NULL);
239 if (n) {
240 while (iswspace(lpMsgBuf[n-1]))
241 --n;
242 lpMsgBuf[n] = L'\0'; /* rstrip() */
243 }
244 return lpMsgBuf;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000245}
246
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000247#ifndef DONT_USE_SEH
Thomas Heller84c97af2009-04-25 16:49:23 +0000248static void SetException(DWORD code, EXCEPTION_RECORD *pr)
Thomas Hellerd4c93202006-03-08 19:35:11 +0000249{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000250 /* The 'code' is a normal win32 error code so it could be handled by
251 PyErr_SetFromWindowsErr(). However, for some errors, we have additional
252 information not included in the error code. We handle those here and
253 delegate all others to the generic function. */
254 switch (code) {
255 case EXCEPTION_ACCESS_VIOLATION:
256 /* The thread attempted to read from or write
257 to a virtual address for which it does not
258 have the appropriate access. */
259 if (pr->ExceptionInformation[0] == 0)
260 PyErr_Format(PyExc_WindowsError,
261 "exception: access violation reading %p",
262 pr->ExceptionInformation[1]);
263 else
264 PyErr_Format(PyExc_WindowsError,
265 "exception: access violation writing %p",
266 pr->ExceptionInformation[1]);
267 break;
Thomas Heller84c97af2009-04-25 16:49:23 +0000268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000269 case EXCEPTION_BREAKPOINT:
270 /* A breakpoint was encountered. */
271 PyErr_SetString(PyExc_WindowsError,
272 "exception: breakpoint encountered");
273 break;
Thomas Heller84c97af2009-04-25 16:49:23 +0000274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000275 case EXCEPTION_DATATYPE_MISALIGNMENT:
276 /* The thread attempted to read or write data that is
277 misaligned on hardware that does not provide
278 alignment. For example, 16-bit values must be
279 aligned on 2-byte boundaries, 32-bit values on
280 4-byte boundaries, and so on. */
281 PyErr_SetString(PyExc_WindowsError,
282 "exception: datatype misalignment");
283 break;
Thomas Heller84c97af2009-04-25 16:49:23 +0000284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000285 case EXCEPTION_SINGLE_STEP:
286 /* A trace trap or other single-instruction mechanism
287 signaled that one instruction has been executed. */
288 PyErr_SetString(PyExc_WindowsError,
289 "exception: single step");
290 break;
Thomas Heller84c97af2009-04-25 16:49:23 +0000291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000292 case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
293 /* The thread attempted to access an array element
294 that is out of bounds, and the underlying hardware
295 supports bounds checking. */
296 PyErr_SetString(PyExc_WindowsError,
297 "exception: array bounds exceeded");
298 break;
Thomas Heller84c97af2009-04-25 16:49:23 +0000299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000300 case EXCEPTION_FLT_DENORMAL_OPERAND:
301 /* One of the operands in a floating-point operation
302 is denormal. A denormal value is one that is too
303 small to represent as a standard floating-point
304 value. */
305 PyErr_SetString(PyExc_WindowsError,
306 "exception: floating-point operand denormal");
307 break;
Thomas Heller84c97af2009-04-25 16:49:23 +0000308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000309 case EXCEPTION_FLT_DIVIDE_BY_ZERO:
310 /* The thread attempted to divide a floating-point
311 value by a floating-point divisor of zero. */
312 PyErr_SetString(PyExc_WindowsError,
313 "exception: float divide by zero");
314 break;
Thomas Heller84c97af2009-04-25 16:49:23 +0000315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000316 case EXCEPTION_FLT_INEXACT_RESULT:
317 /* The result of a floating-point operation cannot be
318 represented exactly as a decimal fraction. */
319 PyErr_SetString(PyExc_WindowsError,
320 "exception: float inexact");
321 break;
Thomas Heller84c97af2009-04-25 16:49:23 +0000322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000323 case EXCEPTION_FLT_INVALID_OPERATION:
324 /* This exception represents any floating-point
325 exception not included in this list. */
326 PyErr_SetString(PyExc_WindowsError,
327 "exception: float invalid operation");
328 break;
Thomas Heller84c97af2009-04-25 16:49:23 +0000329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 case EXCEPTION_FLT_OVERFLOW:
331 /* The exponent of a floating-point operation is
332 greater than the magnitude allowed by the
333 corresponding type. */
334 PyErr_SetString(PyExc_WindowsError,
335 "exception: float overflow");
336 break;
Thomas Heller84c97af2009-04-25 16:49:23 +0000337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000338 case EXCEPTION_FLT_STACK_CHECK:
339 /* The stack overflowed or underflowed as the result
340 of a floating-point operation. */
341 PyErr_SetString(PyExc_WindowsError,
342 "exception: stack over/underflow");
343 break;
Thomas Heller84c97af2009-04-25 16:49:23 +0000344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000345 case EXCEPTION_STACK_OVERFLOW:
346 /* The stack overflowed or underflowed as the result
347 of a floating-point operation. */
348 PyErr_SetString(PyExc_WindowsError,
349 "exception: stack overflow");
350 break;
Thomas Heller84c97af2009-04-25 16:49:23 +0000351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000352 case EXCEPTION_FLT_UNDERFLOW:
353 /* The exponent of a floating-point operation is less
354 than the magnitude allowed by the corresponding
355 type. */
356 PyErr_SetString(PyExc_WindowsError,
357 "exception: float underflow");
358 break;
Thomas Heller84c97af2009-04-25 16:49:23 +0000359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000360 case EXCEPTION_INT_DIVIDE_BY_ZERO:
361 /* The thread attempted to divide an integer value by
362 an integer divisor of zero. */
363 PyErr_SetString(PyExc_WindowsError,
364 "exception: integer divide by zero");
365 break;
Thomas Heller84c97af2009-04-25 16:49:23 +0000366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000367 case EXCEPTION_INT_OVERFLOW:
368 /* The result of an integer operation caused a carry
369 out of the most significant bit of the result. */
370 PyErr_SetString(PyExc_WindowsError,
371 "exception: integer overflow");
372 break;
Thomas Heller84c97af2009-04-25 16:49:23 +0000373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000374 case EXCEPTION_PRIV_INSTRUCTION:
375 /* The thread attempted to execute an instruction
376 whose operation is not allowed in the current
377 machine mode. */
378 PyErr_SetString(PyExc_WindowsError,
379 "exception: priviledged instruction");
380 break;
Thomas Heller84c97af2009-04-25 16:49:23 +0000381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000382 case EXCEPTION_NONCONTINUABLE_EXCEPTION:
383 /* The thread attempted to continue execution after a
384 noncontinuable exception occurred. */
385 PyErr_SetString(PyExc_WindowsError,
386 "exception: nocontinuable");
387 break;
Thomas Heller84c97af2009-04-25 16:49:23 +0000388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000389 default:
390 PyErr_SetFromWindowsErr(code);
391 break;
392 }
Thomas Hellerd4c93202006-03-08 19:35:11 +0000393}
394
395static DWORD HandleException(EXCEPTION_POINTERS *ptrs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000396 DWORD *pdw, EXCEPTION_RECORD *record)
Thomas Hellerd4c93202006-03-08 19:35:11 +0000397{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000398 *pdw = ptrs->ExceptionRecord->ExceptionCode;
399 *record = *ptrs->ExceptionRecord;
Kristján Valur Jónsson5aed3302013-03-19 15:24:10 -0700400 /* We don't want to catch breakpoint exceptions, they are used to attach
401 * a debugger to the process.
402 */
403 if (*pdw == EXCEPTION_BREAKPOINT)
404 return EXCEPTION_CONTINUE_SEARCH;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000405 return EXCEPTION_EXECUTE_HANDLER;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000406}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000407#endif
Thomas Hellerd4c93202006-03-08 19:35:11 +0000408
409static PyObject *
410check_hresult(PyObject *self, PyObject *args)
411{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000412 HRESULT hr;
413 if (!PyArg_ParseTuple(args, "i", &hr))
414 return NULL;
415 if (FAILED(hr))
416 return PyErr_SetFromWindowsErr(hr);
417 return PyLong_FromLong(hr);
Thomas Hellerd4c93202006-03-08 19:35:11 +0000418}
419
420#endif
421
422/**************************************************************/
423
424PyCArgObject *
Thomas Heller34596a92009-04-24 20:50:00 +0000425PyCArgObject_new(void)
Thomas Hellerd4c93202006-03-08 19:35:11 +0000426{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000427 PyCArgObject *p;
428 p = PyObject_New(PyCArgObject, &PyCArg_Type);
429 if (p == NULL)
430 return NULL;
431 p->pffi_type = NULL;
432 p->tag = '\0';
433 p->obj = NULL;
434 memset(&p->value, 0, sizeof(p->value));
435 return p;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000436}
437
438static void
439PyCArg_dealloc(PyCArgObject *self)
440{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000441 Py_XDECREF(self->obj);
442 PyObject_Del(self);
Thomas Hellerd4c93202006-03-08 19:35:11 +0000443}
444
445static PyObject *
446PyCArg_repr(PyCArgObject *self)
447{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000448 char buffer[256];
449 switch(self->tag) {
450 case 'b':
451 case 'B':
452 sprintf(buffer, "<cparam '%c' (%d)>",
453 self->tag, self->value.b);
454 break;
455 case 'h':
456 case 'H':
457 sprintf(buffer, "<cparam '%c' (%d)>",
458 self->tag, self->value.h);
459 break;
460 case 'i':
461 case 'I':
462 sprintf(buffer, "<cparam '%c' (%d)>",
463 self->tag, self->value.i);
464 break;
465 case 'l':
466 case 'L':
467 sprintf(buffer, "<cparam '%c' (%ld)>",
468 self->tag, self->value.l);
469 break;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471#ifdef HAVE_LONG_LONG
472 case 'q':
473 case 'Q':
474 sprintf(buffer,
475#ifdef MS_WIN32
476 "<cparam '%c' (%I64d)>",
477#else
478 "<cparam '%c' (%qd)>",
479#endif
480 self->tag, self->value.q);
481 break;
482#endif
483 case 'd':
484 sprintf(buffer, "<cparam '%c' (%f)>",
485 self->tag, self->value.d);
486 break;
487 case 'f':
488 sprintf(buffer, "<cparam '%c' (%f)>",
489 self->tag, self->value.f);
490 break;
491
492 case 'c':
493 sprintf(buffer, "<cparam '%c' (%c)>",
494 self->tag, self->value.c);
495 break;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000496
497/* Hm, are these 'z' and 'Z' codes useful at all?
498 Shouldn't they be replaced by the functionality of c_string
499 and c_wstring ?
500*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 case 'z':
502 case 'Z':
503 case 'P':
504 sprintf(buffer, "<cparam '%c' (%p)>",
505 self->tag, self->value.p);
506 break;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 default:
509 sprintf(buffer, "<cparam '%c' at %p>",
510 self->tag, self);
511 break;
512 }
513 return PyUnicode_FromString(buffer);
Thomas Hellerd4c93202006-03-08 19:35:11 +0000514}
515
516static PyMemberDef PyCArgType_members[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 { "_obj", T_OBJECT,
518 offsetof(PyCArgObject, obj), READONLY,
519 "the wrapped object" },
520 { NULL },
Thomas Hellerd4c93202006-03-08 19:35:11 +0000521};
522
523PyTypeObject PyCArg_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000524 PyVarObject_HEAD_INIT(NULL, 0)
525 "CArgObject",
526 sizeof(PyCArgObject),
527 0,
528 (destructor)PyCArg_dealloc, /* tp_dealloc */
529 0, /* tp_print */
530 0, /* tp_getattr */
531 0, /* tp_setattr */
532 0, /* tp_reserved */
533 (reprfunc)PyCArg_repr, /* tp_repr */
534 0, /* tp_as_number */
535 0, /* tp_as_sequence */
536 0, /* tp_as_mapping */
537 0, /* tp_hash */
538 0, /* tp_call */
539 0, /* tp_str */
540 0, /* tp_getattro */
541 0, /* tp_setattro */
542 0, /* tp_as_buffer */
543 Py_TPFLAGS_DEFAULT, /* tp_flags */
544 0, /* tp_doc */
545 0, /* tp_traverse */
546 0, /* tp_clear */
547 0, /* tp_richcompare */
548 0, /* tp_weaklistoffset */
549 0, /* tp_iter */
550 0, /* tp_iternext */
551 0, /* tp_methods */
552 PyCArgType_members, /* tp_members */
Thomas Hellerd4c93202006-03-08 19:35:11 +0000553};
554
555/****************************************************************/
556/*
557 * Convert a PyObject * into a parameter suitable to pass to an
558 * C function call.
559 *
560 * 1. Python integers are converted to C int and passed by value.
Thomas Heller69b639f2009-09-18 20:08:39 +0000561 * Py_None is converted to a C NULL pointer.
Thomas Hellerd4c93202006-03-08 19:35:11 +0000562 *
563 * 2. 3-tuples are expected to have a format character in the first
564 * item, which must be 'i', 'f', 'd', 'q', or 'P'.
565 * The second item will have to be an integer, float, double, long long
566 * or integer (denoting an address void *), will be converted to the
567 * corresponding C data type and passed by value.
568 *
569 * 3. Other Python objects are tested for an '_as_parameter_' attribute.
570 * The value of this attribute must be an integer which will be passed
571 * by value, or a 2-tuple or 3-tuple which will be used according
572 * to point 2 above. The third item (if any), is ignored. It is normally
573 * used to keep the object alive where this parameter refers to.
574 * XXX This convention is dangerous - you can construct arbitrary tuples
575 * in Python and pass them. Would it be safer to use a custom container
576 * datatype instead of a tuple?
577 *
578 * 4. Other Python objects cannot be passed as parameters - an exception is raised.
579 *
580 * 5. ConvParam will store the converted result in a struct containing format
581 * and value.
582 */
583
584union result {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000585 char c;
586 char b;
587 short h;
588 int i;
589 long l;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000590#ifdef HAVE_LONG_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000591 PY_LONG_LONG q;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000592#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000593 long double D;
594 double d;
595 float f;
596 void *p;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000597};
598
599struct argument {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000600 ffi_type *ffi_type;
601 PyObject *keep;
602 union result value;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000603};
604
605/*
606 * Convert a single Python object into a PyCArgObject and return it.
607 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000608static int ConvParam(PyObject *obj, Py_ssize_t index, struct argument *pa)
Thomas Hellerd4c93202006-03-08 19:35:11 +0000609{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000610 StgDictObject *dict;
611 pa->keep = NULL; /* so we cannot forget it later */
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000613 dict = PyObject_stgdict(obj);
614 if (dict) {
615 PyCArgObject *carg;
616 assert(dict->paramfunc);
617 /* If it has an stgdict, it is a CDataObject */
618 carg = dict->paramfunc((CDataObject *)obj);
619 pa->ffi_type = carg->pffi_type;
620 memcpy(&pa->value, &carg->value, sizeof(pa->value));
621 pa->keep = (PyObject *)carg;
622 return 0;
623 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000624
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000625 if (PyCArg_CheckExact(obj)) {
626 PyCArgObject *carg = (PyCArgObject *)obj;
627 pa->ffi_type = carg->pffi_type;
628 Py_INCREF(obj);
629 pa->keep = obj;
630 memcpy(&pa->value, &carg->value, sizeof(pa->value));
631 return 0;
632 }
Thomas Hellerd4c93202006-03-08 19:35:11 +0000633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 /* check for None, integer, string or unicode and use directly if successful */
635 if (obj == Py_None) {
636 pa->ffi_type = &ffi_type_pointer;
637 pa->value.p = NULL;
638 return 0;
639 }
Thomas Hellerd4c93202006-03-08 19:35:11 +0000640
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 if (PyLong_Check(obj)) {
642 pa->ffi_type = &ffi_type_sint;
643 pa->value.i = (long)PyLong_AsUnsignedLong(obj);
644 if (pa->value.i == -1 && PyErr_Occurred()) {
645 PyErr_Clear();
646 pa->value.i = PyLong_AsLong(obj);
647 if (pa->value.i == -1 && PyErr_Occurred()) {
648 PyErr_SetString(PyExc_OverflowError,
649 "long int too long to convert");
650 return -1;
651 }
652 }
653 return 0;
654 }
Thomas Hellerd4c93202006-03-08 19:35:11 +0000655
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000656 if (PyBytes_Check(obj)) {
657 pa->ffi_type = &ffi_type_pointer;
658 pa->value.p = PyBytes_AsString(obj);
659 Py_INCREF(obj);
660 pa->keep = obj;
661 return 0;
662 }
Thomas Heller7775c712007-07-12 19:19:43 +0000663
Thomas Hellerd4c93202006-03-08 19:35:11 +0000664#ifdef CTYPES_UNICODE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000665 if (PyUnicode_Check(obj)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000666 pa->ffi_type = &ffi_type_pointer;
Victor Stinnerbeb4135b2010-10-07 01:02:42 +0000667 pa->value.p = PyUnicode_AsWideCharString(obj, NULL);
Victor Stinner4c2e4fa2010-09-29 10:37:16 +0000668 if (pa->value.p == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000669 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 pa->keep = PyCapsule_New(pa->value.p, CTYPES_CAPSULE_NAME_PYMEM, pymem_destructor);
671 if (!pa->keep) {
672 PyMem_Free(pa->value.p);
673 return -1;
674 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000675 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 }
Thomas Hellerd4c93202006-03-08 19:35:11 +0000677#endif
678
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000679 {
680 PyObject *arg;
681 arg = PyObject_GetAttrString(obj, "_as_parameter_");
682 /* Which types should we exactly allow here?
683 integers are required for using Python classes
684 as parameters (they have to expose the '_as_parameter_'
685 attribute)
686 */
687 if (arg) {
688 int result;
689 result = ConvParam(arg, index, pa);
690 Py_DECREF(arg);
691 return result;
692 }
693 PyErr_Format(PyExc_TypeError,
694 "Don't know how to convert parameter %d",
695 Py_SAFE_DOWNCAST(index, Py_ssize_t, int));
696 return -1;
697 }
Thomas Hellerd4c93202006-03-08 19:35:11 +0000698}
699
700
Thomas Heller34596a92009-04-24 20:50:00 +0000701ffi_type *_ctypes_get_ffi_type(PyObject *obj)
Thomas Hellerd4c93202006-03-08 19:35:11 +0000702{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000703 StgDictObject *dict;
704 if (obj == NULL)
705 return &ffi_type_sint;
706 dict = PyType_stgdict(obj);
707 if (dict == NULL)
708 return &ffi_type_sint;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000709#if defined(MS_WIN32) && !defined(_WIN32_WCE)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000710 /* This little trick works correctly with MSVC.
711 It returns small structures in registers
712 */
713 if (dict->ffi_type_pointer.type == FFI_TYPE_STRUCT) {
714 if (dict->ffi_type_pointer.size <= 4)
715 return &ffi_type_sint32;
716 else if (dict->ffi_type_pointer.size <= 8)
717 return &ffi_type_sint64;
718 }
Thomas Hellerd4c93202006-03-08 19:35:11 +0000719#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000720 return &dict->ffi_type_pointer;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000721}
722
723
724/*
725 * libffi uses:
726 *
727 * ffi_status ffi_prep_cif(ffi_cif *cif, ffi_abi abi,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000728 * unsigned int nargs,
Thomas Hellerd4c93202006-03-08 19:35:11 +0000729 * ffi_type *rtype,
730 * ffi_type **atypes);
731 *
732 * and then
733 *
734 * void ffi_call(ffi_cif *cif, void *fn, void *rvalue, void **avalues);
735 */
736static int _call_function_pointer(int flags,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000737 PPROC pProc,
738 void **avalues,
739 ffi_type **atypes,
740 ffi_type *restype,
741 void *resmem,
742 int argcount)
Thomas Hellerd4c93202006-03-08 19:35:11 +0000743{
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000744#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000745 PyThreadState *_save = NULL; /* For Py_BLOCK_THREADS and Py_UNBLOCK_THREADS */
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000746#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000747 PyObject *error_object = NULL;
748 int *space;
749 ffi_cif cif;
750 int cc;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000751#ifdef MS_WIN32
Thomas Hellerb00697e2010-06-21 16:00:31 +0000752 int delta;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000753#ifndef DONT_USE_SEH
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000754 DWORD dwExceptionCode = 0;
755 EXCEPTION_RECORD record;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000756#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000757#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 /* XXX check before here */
759 if (restype == NULL) {
760 PyErr_SetString(PyExc_RuntimeError,
761 "No ffi_type for result");
762 return -1;
763 }
Thomas Hellerd4c93202006-03-08 19:35:11 +0000764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000765 cc = FFI_DEFAULT_ABI;
766#if defined(MS_WIN32) && !defined(MS_WIN64) && !defined(_WIN32_WCE)
767 if ((flags & FUNCFLAG_CDECL) == 0)
768 cc = FFI_STDCALL;
769#endif
770 if (FFI_OK != ffi_prep_cif(&cif,
771 cc,
772 argcount,
773 restype,
774 atypes)) {
775 PyErr_SetString(PyExc_RuntimeError,
776 "ffi_prep_cif failed");
777 return -1;
778 }
779
780 if (flags & (FUNCFLAG_USE_ERRNO | FUNCFLAG_USE_LASTERROR)) {
781 error_object = _ctypes_get_errobj(&space);
782 if (error_object == NULL)
783 return -1;
784 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000785#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000786 if ((flags & FUNCFLAG_PYTHONAPI) == 0)
787 Py_UNBLOCK_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000788#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 if (flags & FUNCFLAG_USE_ERRNO) {
790 int temp = space[0];
791 space[0] = errno;
792 errno = temp;
793 }
Thomas Hellerd4c93202006-03-08 19:35:11 +0000794#ifdef MS_WIN32
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000795 if (flags & FUNCFLAG_USE_LASTERROR) {
796 int temp = space[1];
797 space[1] = GetLastError();
798 SetLastError(temp);
799 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000800#ifndef DONT_USE_SEH
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000801 __try {
Thomas Hellerd4c93202006-03-08 19:35:11 +0000802#endif
Thomas Hellerb00697e2010-06-21 16:00:31 +0000803 delta =
Thomas Hellerd4c93202006-03-08 19:35:11 +0000804#endif
Thomas Hellerb00697e2010-06-21 16:00:31 +0000805 ffi_call(&cif, (void *)pProc, resmem, avalues);
Thomas Hellerd4c93202006-03-08 19:35:11 +0000806#ifdef MS_WIN32
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000807#ifndef DONT_USE_SEH
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 }
809 __except (HandleException(GetExceptionInformation(),
810 &dwExceptionCode, &record)) {
811 ;
812 }
Thomas Hellerd4c93202006-03-08 19:35:11 +0000813#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000814 if (flags & FUNCFLAG_USE_LASTERROR) {
815 int temp = space[1];
816 space[1] = GetLastError();
817 SetLastError(temp);
818 }
Thomas Hellerd4c93202006-03-08 19:35:11 +0000819#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000820 if (flags & FUNCFLAG_USE_ERRNO) {
821 int temp = space[0];
822 space[0] = errno;
823 errno = temp;
824 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000825#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000826 if ((flags & FUNCFLAG_PYTHONAPI) == 0)
827 Py_BLOCK_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000828#endif
Kristjan Valur Jonsson9946bd62012-12-21 09:41:25 +0000829 Py_XDECREF(error_object);
Thomas Hellerd4c93202006-03-08 19:35:11 +0000830#ifdef MS_WIN32
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000831#ifndef DONT_USE_SEH
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000832 if (dwExceptionCode) {
833 SetException(dwExceptionCode, &record);
834 return -1;
835 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000836#endif
Thomas Hellerb00697e2010-06-21 16:00:31 +0000837#ifdef MS_WIN64
838 if (delta != 0) {
839 PyErr_Format(PyExc_RuntimeError,
840 "ffi_call failed with code %d",
841 delta);
842 return -1;
843 }
844#else
845 if (delta < 0) {
846 if (flags & FUNCFLAG_CDECL)
847 PyErr_Format(PyExc_ValueError,
848 "Procedure called with not enough "
849 "arguments (%d bytes missing) "
850 "or wrong calling convention",
851 -delta);
852 else
853 PyErr_Format(PyExc_ValueError,
854 "Procedure probably called with not enough "
855 "arguments (%d bytes missing)",
856 -delta);
857 return -1;
858 } else if (delta > 0) {
859 PyErr_Format(PyExc_ValueError,
860 "Procedure probably called with too many "
861 "arguments (%d bytes in excess)",
862 delta);
863 return -1;
864 }
865#endif
Thomas Wouters89f507f2006-12-13 04:49:30 +0000866#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000867 if ((flags & FUNCFLAG_PYTHONAPI) && PyErr_Occurred())
868 return -1;
869 return 0;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000870}
871
872/*
873 * Convert the C value in result into a Python object, depending on restype.
874 *
875 * - If restype is NULL, return a Python integer.
876 * - If restype is None, return None.
877 * - If restype is a simple ctypes type (c_int, c_void_p), call the type's getfunc,
878 * pass the result to checker and return the result.
879 * - If restype is another ctypes type, return an instance of that.
880 * - Otherwise, call restype and return the result.
881 */
882static PyObject *GetResult(PyObject *restype, void *result, PyObject *checker)
883{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000884 StgDictObject *dict;
885 PyObject *retval, *v;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000886
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000887 if (restype == NULL)
888 return PyLong_FromLong(*(int *)result);
Thomas Hellerd4c93202006-03-08 19:35:11 +0000889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000890 if (restype == Py_None) {
891 Py_INCREF(Py_None);
892 return Py_None;
893 }
Thomas Hellerd4c93202006-03-08 19:35:11 +0000894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000895 dict = PyType_stgdict(restype);
896 if (dict == NULL)
897 return PyObject_CallFunction(restype, "i", *(int *)result);
Thomas Hellerd4c93202006-03-08 19:35:11 +0000898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000899 if (dict->getfunc && !_ctypes_simple_instance(restype)) {
900 retval = dict->getfunc(result, dict->size);
901 /* If restype is py_object (detected by comparing getfunc with
902 O_get), we have to call Py_DECREF because O_get has already
903 called Py_INCREF.
904 */
905 if (dict->getfunc == _ctypes_get_fielddesc("O")->getfunc) {
906 Py_DECREF(retval);
907 }
908 } else
909 retval = PyCData_FromBaseObj(restype, NULL, 0, result);
Thomas Hellerd4c93202006-03-08 19:35:11 +0000910
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000911 if (!checker || !retval)
912 return retval;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 v = PyObject_CallFunctionObjArgs(checker, retval, NULL);
915 if (v == NULL)
916 _ctypes_add_traceback("GetResult", "_ctypes/callproc.c", __LINE__-2);
917 Py_DECREF(retval);
918 return v;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000919}
920
921/*
922 * Raise a new exception 'exc_class', adding additional text to the original
923 * exception string.
924 */
Thomas Heller34596a92009-04-24 20:50:00 +0000925void _ctypes_extend_error(PyObject *exc_class, char *fmt, ...)
Thomas Hellerd4c93202006-03-08 19:35:11 +0000926{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000927 va_list vargs;
928 PyObject *tp, *v, *tb, *s, *cls_str, *msg_str;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000929
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000930 va_start(vargs, fmt);
931 s = PyUnicode_FromFormatV(fmt, vargs);
932 va_end(vargs);
933 if (!s)
934 return;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 PyErr_Fetch(&tp, &v, &tb);
937 PyErr_NormalizeException(&tp, &v, &tb);
938 cls_str = PyObject_Str(tp);
939 if (cls_str) {
940 PyUnicode_AppendAndDel(&s, cls_str);
941 PyUnicode_AppendAndDel(&s, PyUnicode_FromString(": "));
942 if (s == NULL)
943 goto error;
944 } else
945 PyErr_Clear();
946 msg_str = PyObject_Str(v);
947 if (msg_str)
948 PyUnicode_AppendAndDel(&s, msg_str);
949 else {
950 PyErr_Clear();
951 PyUnicode_AppendAndDel(&s, PyUnicode_FromString("???"));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 }
Victor Stinner67002af2011-10-02 20:35:10 +0200953 if (s == NULL)
954 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 PyErr_SetObject(exc_class, s);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000956error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000957 Py_XDECREF(tp);
958 Py_XDECREF(v);
959 Py_XDECREF(tb);
960 Py_XDECREF(s);
Thomas Hellerd4c93202006-03-08 19:35:11 +0000961}
962
963
964#ifdef MS_WIN32
965
966static PyObject *
967GetComError(HRESULT errcode, GUID *riid, IUnknown *pIunk)
968{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 HRESULT hr;
970 ISupportErrorInfo *psei = NULL;
971 IErrorInfo *pei = NULL;
972 BSTR descr=NULL, helpfile=NULL, source=NULL;
973 GUID guid;
974 DWORD helpcontext=0;
975 LPOLESTR progid;
976 PyObject *obj;
977 LPOLESTR text;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000978
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 /* We absolutely have to release the GIL during COM method calls,
980 otherwise we may get a deadlock!
981 */
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000982#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000983 Py_BEGIN_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000984#endif
985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 hr = pIunk->lpVtbl->QueryInterface(pIunk, &IID_ISupportErrorInfo, (void **)&psei);
987 if (FAILED(hr))
988 goto failed;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000989
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000990 hr = psei->lpVtbl->InterfaceSupportsErrorInfo(psei, riid);
991 psei->lpVtbl->Release(psei);
992 if (FAILED(hr))
993 goto failed;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000994
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000995 hr = GetErrorInfo(0, &pei);
996 if (hr != S_OK)
997 goto failed;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 pei->lpVtbl->GetDescription(pei, &descr);
1000 pei->lpVtbl->GetGUID(pei, &guid);
1001 pei->lpVtbl->GetHelpContext(pei, &helpcontext);
1002 pei->lpVtbl->GetHelpFile(pei, &helpfile);
1003 pei->lpVtbl->GetSource(pei, &source);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001004
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 pei->lpVtbl->Release(pei);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001006
Thomas Hellerd4c93202006-03-08 19:35:11 +00001007 failed:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001008#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001009 Py_END_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001010#endif
Thomas Hellerd4c93202006-03-08 19:35:11 +00001011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001012 progid = NULL;
1013 ProgIDFromCLSID(&guid, &progid);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 text = FormatError(errcode);
1016 obj = Py_BuildValue(
1017 "iu(uuuiu)",
1018 errcode,
1019 text,
1020 descr, source, helpfile, helpcontext,
1021 progid);
1022 if (obj) {
1023 PyErr_SetObject(ComError, obj);
1024 Py_DECREF(obj);
1025 }
1026 LocalFree(text);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 if (descr)
1029 SysFreeString(descr);
1030 if (helpfile)
1031 SysFreeString(helpfile);
1032 if (source)
1033 SysFreeString(source);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001034
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001035 return NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001036}
1037#endif
1038
1039/*
1040 * Requirements, must be ensured by the caller:
1041 * - argtuple is tuple of arguments
1042 * - argtypes is either NULL, or a tuple of the same size as argtuple
1043 *
1044 * - XXX various requirements for restype, not yet collected
1045 */
Thomas Heller34596a92009-04-24 20:50:00 +00001046PyObject *_ctypes_callproc(PPROC pProc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001047 PyObject *argtuple,
Thomas Hellerd4c93202006-03-08 19:35:11 +00001048#ifdef MS_WIN32
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049 IUnknown *pIunk,
1050 GUID *iid,
Thomas Hellerd4c93202006-03-08 19:35:11 +00001051#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 int flags,
1053 PyObject *argtypes, /* misleading name: This is a tuple of
1054 methods, not types: the .from_param
1055 class methods of the types */
1056 PyObject *restype,
1057 PyObject *checker)
Thomas Hellerd4c93202006-03-08 19:35:11 +00001058{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001059 Py_ssize_t i, n, argcount, argtype_count;
1060 void *resbuf;
1061 struct argument *args, *pa;
1062 ffi_type **atypes;
1063 ffi_type *rtype;
1064 void **avalues;
1065 PyObject *retval = NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001067 n = argcount = PyTuple_GET_SIZE(argtuple);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001068#ifdef MS_WIN32
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001069 /* an optional COM object this pointer */
1070 if (pIunk)
1071 ++argcount;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001072#endif
1073
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001074 args = (struct argument *)alloca(sizeof(struct argument) * argcount);
1075 if (!args) {
1076 PyErr_NoMemory();
1077 return NULL;
1078 }
1079 memset(args, 0, sizeof(struct argument) * argcount);
1080 argtype_count = argtypes ? PyTuple_GET_SIZE(argtypes) : 0;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001081#ifdef MS_WIN32
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 if (pIunk) {
1083 args[0].ffi_type = &ffi_type_pointer;
1084 args[0].value.p = pIunk;
1085 pa = &args[1];
1086 } else
Thomas Hellerd4c93202006-03-08 19:35:11 +00001087#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001088 pa = &args[0];
Thomas Hellerd4c93202006-03-08 19:35:11 +00001089
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001090 /* Convert the arguments */
1091 for (i = 0; i < n; ++i, ++pa) {
1092 PyObject *converter;
1093 PyObject *arg;
1094 int err;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001095
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001096 arg = PyTuple_GET_ITEM(argtuple, i); /* borrowed ref */
1097 /* For cdecl functions, we allow more actual arguments
1098 than the length of the argtypes tuple.
1099 This is checked in _ctypes::PyCFuncPtr_Call
1100 */
1101 if (argtypes && argtype_count > i) {
1102 PyObject *v;
1103 converter = PyTuple_GET_ITEM(argtypes, i);
1104 v = PyObject_CallFunctionObjArgs(converter,
1105 arg,
1106 NULL);
1107 if (v == NULL) {
1108 _ctypes_extend_error(PyExc_ArgError, "argument %d: ", i+1);
1109 goto cleanup;
1110 }
Thomas Hellerd4c93202006-03-08 19:35:11 +00001111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001112 err = ConvParam(v, i+1, pa);
1113 Py_DECREF(v);
1114 if (-1 == err) {
1115 _ctypes_extend_error(PyExc_ArgError, "argument %d: ", i+1);
1116 goto cleanup;
1117 }
1118 } else {
1119 err = ConvParam(arg, i+1, pa);
1120 if (-1 == err) {
1121 _ctypes_extend_error(PyExc_ArgError, "argument %d: ", i+1);
1122 goto cleanup; /* leaking ? */
1123 }
1124 }
1125 }
Thomas Hellerd4c93202006-03-08 19:35:11 +00001126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001127 rtype = _ctypes_get_ffi_type(restype);
1128 resbuf = alloca(max(rtype->size, sizeof(ffi_arg)));
Thomas Hellerd4c93202006-03-08 19:35:11 +00001129
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001130 avalues = (void **)alloca(sizeof(void *) * argcount);
1131 atypes = (ffi_type **)alloca(sizeof(ffi_type *) * argcount);
1132 if (!resbuf || !avalues || !atypes) {
1133 PyErr_NoMemory();
1134 goto cleanup;
1135 }
1136 for (i = 0; i < argcount; ++i) {
1137 atypes[i] = args[i].ffi_type;
Victor Stinner4c2e4fa2010-09-29 10:37:16 +00001138 if (atypes[i]->type == FFI_TYPE_STRUCT
Thomas Hellerb00697e2010-06-21 16:00:31 +00001139#ifdef _WIN64
1140 && atypes[i]->size <= sizeof(void *)
1141#endif
1142 )
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001143 avalues[i] = (void *)args[i].value.p;
1144 else
1145 avalues[i] = (void *)&args[i].value;
1146 }
Thomas Hellerd4c93202006-03-08 19:35:11 +00001147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001148 if (-1 == _call_function_pointer(flags, pProc, avalues, atypes,
1149 rtype, resbuf,
1150 Py_SAFE_DOWNCAST(argcount,
1151 Py_ssize_t,
1152 int)))
1153 goto cleanup;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001154
1155#ifdef WORDS_BIGENDIAN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001156 /* libffi returns the result in a buffer with sizeof(ffi_arg). This
1157 causes problems on big endian machines, since the result buffer
1158 address cannot simply be used as result pointer, instead we must
1159 adjust the pointer value:
1160 */
1161 /*
1162 XXX I should find out and clarify why this is needed at all,
1163 especially why adjusting for ffi_type_float must be avoided on
1164 64-bit platforms.
1165 */
1166 if (rtype->type != FFI_TYPE_FLOAT
1167 && rtype->type != FFI_TYPE_STRUCT
1168 && rtype->size < sizeof(ffi_arg))
1169 resbuf = (char *)resbuf + sizeof(ffi_arg) - rtype->size;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001170#endif
1171
1172#ifdef MS_WIN32
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001173 if (iid && pIunk) {
1174 if (*(int *)resbuf & 0x80000000)
1175 retval = GetComError(*(HRESULT *)resbuf, iid, pIunk);
1176 else
1177 retval = PyLong_FromLong(*(int *)resbuf);
1178 } else if (flags & FUNCFLAG_HRESULT) {
1179 if (*(int *)resbuf & 0x80000000)
1180 retval = PyErr_SetFromWindowsErr(*(int *)resbuf);
1181 else
1182 retval = PyLong_FromLong(*(int *)resbuf);
1183 } else
Thomas Hellerd4c93202006-03-08 19:35:11 +00001184#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001185 retval = GetResult(restype, resbuf, checker);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001186 cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001187 for (i = 0; i < argcount; ++i)
1188 Py_XDECREF(args[i].keep);
1189 return retval;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001190}
1191
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001192static int
1193_parse_voidp(PyObject *obj, void **address)
1194{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195 *address = PyLong_AsVoidPtr(obj);
1196 if (*address == NULL)
1197 return 0;
1198 return 1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001199}
1200
Thomas Hellerd4c93202006-03-08 19:35:11 +00001201#ifdef MS_WIN32
1202
Thomas Hellerd4c93202006-03-08 19:35:11 +00001203static char format_error_doc[] =
1204"FormatError([integer]) -> string\n\
1205\n\
1206Convert a win32 error code into a string. If the error code is not\n\
1207given, the return value of a call to GetLastError() is used.\n";
1208static PyObject *format_error(PyObject *self, PyObject *args)
1209{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001210 PyObject *result;
1211 wchar_t *lpMsgBuf;
1212 DWORD code = 0;
1213 if (!PyArg_ParseTuple(args, "|i:FormatError", &code))
1214 return NULL;
1215 if (code == 0)
1216 code = GetLastError();
1217 lpMsgBuf = FormatError(code);
1218 if (lpMsgBuf) {
1219 result = PyUnicode_FromWideChar(lpMsgBuf, wcslen(lpMsgBuf));
1220 LocalFree(lpMsgBuf);
1221 } else {
1222 result = PyUnicode_FromString("<no description>");
1223 }
1224 return result;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001225}
1226
1227static char load_library_doc[] =
1228"LoadLibrary(name) -> handle\n\
1229\n\
1230Load an executable (usually a DLL), and return a handle to it.\n\
1231The handle may be used to locate exported functions in this\n\
1232module.\n";
1233static PyObject *load_library(PyObject *self, PyObject *args)
1234{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001235 WCHAR *name;
1236 PyObject *nameobj;
1237 PyObject *ignored;
1238 HMODULE hMod;
1239 if (!PyArg_ParseTuple(args, "O|O:LoadLibrary", &nameobj, &ignored))
1240 return NULL;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001242 name = PyUnicode_AsUnicode(nameobj);
1243 if (!name)
1244 return NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001245
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001246 hMod = LoadLibraryW(name);
1247 if (!hMod)
1248 return PyErr_SetFromWindowsErr(GetLastError());
Thomas Wouters89f507f2006-12-13 04:49:30 +00001249#ifdef _WIN64
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001250 return PyLong_FromVoidPtr(hMod);
Thomas Wouters89f507f2006-12-13 04:49:30 +00001251#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001252 return Py_BuildValue("i", hMod);
Thomas Wouters89f507f2006-12-13 04:49:30 +00001253#endif
Thomas Hellerd4c93202006-03-08 19:35:11 +00001254}
1255
1256static char free_library_doc[] =
1257"FreeLibrary(handle) -> void\n\
1258\n\
1259Free the handle of an executable previously loaded by LoadLibrary.\n";
1260static PyObject *free_library(PyObject *self, PyObject *args)
1261{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001262 void *hMod;
1263 if (!PyArg_ParseTuple(args, "O&:FreeLibrary", &_parse_voidp, &hMod))
1264 return NULL;
1265 if (!FreeLibrary((HMODULE)hMod))
1266 return PyErr_SetFromWindowsErr(GetLastError());
1267 Py_INCREF(Py_None);
1268 return Py_None;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001269}
1270
1271/* obsolete, should be removed */
1272/* Only used by sample code (in samples\Windows\COM.py) */
1273static PyObject *
1274call_commethod(PyObject *self, PyObject *args)
1275{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001276 IUnknown *pIunk;
1277 int index;
1278 PyObject *arguments;
1279 PPROC *lpVtbl;
1280 PyObject *result;
1281 CDataObject *pcom;
1282 PyObject *argtypes = NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001284 if (!PyArg_ParseTuple(args,
1285 "OiO!|O!",
1286 &pcom, &index,
1287 &PyTuple_Type, &arguments,
1288 &PyTuple_Type, &argtypes))
1289 return NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001290
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001291 if (argtypes && (PyTuple_GET_SIZE(arguments) != PyTuple_GET_SIZE(argtypes))) {
1292 PyErr_Format(PyExc_TypeError,
1293 "Method takes %d arguments (%d given)",
1294 PyTuple_GET_SIZE(argtypes), PyTuple_GET_SIZE(arguments));
1295 return NULL;
1296 }
Thomas Hellerd4c93202006-03-08 19:35:11 +00001297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001298 if (!CDataObject_Check(pcom) || (pcom->b_size != sizeof(void *))) {
1299 PyErr_Format(PyExc_TypeError,
1300 "COM Pointer expected instead of %s instance",
1301 Py_TYPE(pcom)->tp_name);
1302 return NULL;
1303 }
Thomas Hellerd4c93202006-03-08 19:35:11 +00001304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001305 if ((*(void **)(pcom->b_ptr)) == NULL) {
1306 PyErr_SetString(PyExc_ValueError,
1307 "The COM 'this' pointer is NULL");
1308 return NULL;
1309 }
Thomas Hellerd4c93202006-03-08 19:35:11 +00001310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001311 pIunk = (IUnknown *)(*(void **)(pcom->b_ptr));
1312 lpVtbl = (PPROC *)(pIunk->lpVtbl);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001314 result = _ctypes_callproc(lpVtbl[index],
1315 arguments,
Thomas Hellerd4c93202006-03-08 19:35:11 +00001316#ifdef MS_WIN32
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001317 pIunk,
1318 NULL,
Thomas Hellerd4c93202006-03-08 19:35:11 +00001319#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001320 FUNCFLAG_HRESULT, /* flags */
1321 argtypes, /* self->argtypes */
1322 NULL, /* self->restype */
1323 NULL); /* checker */
1324 return result;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001325}
1326
1327static char copy_com_pointer_doc[] =
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001328"CopyComPointer(src, dst) -> HRESULT value\n";
Thomas Hellerd4c93202006-03-08 19:35:11 +00001329
1330static PyObject *
1331copy_com_pointer(PyObject *self, PyObject *args)
1332{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001333 PyObject *p1, *p2, *r = NULL;
1334 struct argument a, b;
1335 IUnknown *src, **pdst;
1336 if (!PyArg_ParseTuple(args, "OO:CopyComPointer", &p1, &p2))
1337 return NULL;
1338 a.keep = b.keep = NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001340 if (-1 == ConvParam(p1, 0, &a) || -1 == ConvParam(p2, 1, &b))
1341 goto done;
1342 src = (IUnknown *)a.value.p;
1343 pdst = (IUnknown **)b.value.p;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001345 if (pdst == NULL)
1346 r = PyLong_FromLong(E_POINTER);
1347 else {
1348 if (src)
1349 src->lpVtbl->AddRef(src);
1350 *pdst = src;
1351 r = PyLong_FromLong(S_OK);
1352 }
Thomas Hellerd4c93202006-03-08 19:35:11 +00001353 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001354 Py_XDECREF(a.keep);
1355 Py_XDECREF(b.keep);
1356 return r;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001357}
1358#else
1359
1360static PyObject *py_dl_open(PyObject *self, PyObject *args)
1361{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001362 PyObject *name, *name2;
1363 char *name_str;
1364 void * handle;
1365#ifdef RTLD_LOCAL
1366 int mode = RTLD_NOW | RTLD_LOCAL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001367#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001368 /* cygwin doesn't define RTLD_LOCAL */
1369 int mode = RTLD_NOW;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001370#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001371 if (!PyArg_ParseTuple(args, "O|i:dlopen", &name, &mode))
1372 return NULL;
1373 mode |= RTLD_NOW;
1374 if (name != Py_None) {
1375 if (PyUnicode_FSConverter(name, &name2) == 0)
1376 return NULL;
1377 if (PyBytes_Check(name2))
1378 name_str = PyBytes_AS_STRING(name2);
1379 else
1380 name_str = PyByteArray_AS_STRING(name2);
1381 } else {
1382 name_str = NULL;
1383 name2 = NULL;
1384 }
1385 handle = ctypes_dlopen(name_str, mode);
1386 Py_XDECREF(name2);
1387 if (!handle) {
1388 char *errmsg = ctypes_dlerror();
1389 if (!errmsg)
1390 errmsg = "dlopen() error";
1391 PyErr_SetString(PyExc_OSError,
1392 errmsg);
1393 return NULL;
1394 }
1395 return PyLong_FromVoidPtr(handle);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001396}
1397
1398static PyObject *py_dl_close(PyObject *self, PyObject *args)
1399{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001400 void *handle;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001402 if (!PyArg_ParseTuple(args, "O&:dlclose", &_parse_voidp, &handle))
1403 return NULL;
1404 if (dlclose(handle)) {
1405 PyErr_SetString(PyExc_OSError,
1406 ctypes_dlerror());
1407 return NULL;
1408 }
1409 Py_INCREF(Py_None);
1410 return Py_None;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001411}
1412
1413static PyObject *py_dl_sym(PyObject *self, PyObject *args)
1414{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001415 char *name;
1416 void *handle;
1417 void *ptr;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001418
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001419 if (!PyArg_ParseTuple(args, "O&s:dlsym",
1420 &_parse_voidp, &handle, &name))
1421 return NULL;
1422 ptr = ctypes_dlsym((void*)handle, name);
1423 if (!ptr) {
1424 PyErr_SetString(PyExc_OSError,
1425 ctypes_dlerror());
1426 return NULL;
1427 }
1428 return PyLong_FromVoidPtr(ptr);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001429}
1430#endif
1431
1432/*
1433 * Only for debugging so far: So that we can call CFunction instances
1434 *
1435 * XXX Needs to accept more arguments: flags, argtypes, restype
1436 */
1437static PyObject *
1438call_function(PyObject *self, PyObject *args)
1439{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001440 void *func;
1441 PyObject *arguments;
1442 PyObject *result;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001443
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001444 if (!PyArg_ParseTuple(args,
1445 "O&O!",
1446 &_parse_voidp, &func,
1447 &PyTuple_Type, &arguments))
1448 return NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001450 result = _ctypes_callproc((PPROC)func,
1451 arguments,
Thomas Hellerd4c93202006-03-08 19:35:11 +00001452#ifdef MS_WIN32
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001453 NULL,
1454 NULL,
Thomas Hellerd4c93202006-03-08 19:35:11 +00001455#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001456 0, /* flags */
1457 NULL, /* self->argtypes */
1458 NULL, /* self->restype */
1459 NULL); /* checker */
1460 return result;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001461}
1462
1463/*
1464 * Only for debugging so far: So that we can call CFunction instances
1465 *
1466 * XXX Needs to accept more arguments: flags, argtypes, restype
1467 */
1468static PyObject *
1469call_cdeclfunction(PyObject *self, PyObject *args)
1470{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001471 void *func;
1472 PyObject *arguments;
1473 PyObject *result;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001475 if (!PyArg_ParseTuple(args,
1476 "O&O!",
1477 &_parse_voidp, &func,
1478 &PyTuple_Type, &arguments))
1479 return NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001481 result = _ctypes_callproc((PPROC)func,
1482 arguments,
Thomas Hellerd4c93202006-03-08 19:35:11 +00001483#ifdef MS_WIN32
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001484 NULL,
1485 NULL,
Thomas Hellerd4c93202006-03-08 19:35:11 +00001486#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001487 FUNCFLAG_CDECL, /* flags */
1488 NULL, /* self->argtypes */
1489 NULL, /* self->restype */
1490 NULL); /* checker */
1491 return result;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001492}
1493
1494/*****************************************************************
1495 * functions
1496 */
1497static char sizeof_doc[] =
1498"sizeof(C type) -> integer\n"
1499"sizeof(C instance) -> integer\n"
1500"Return the size in bytes of a C instance";
1501
1502static PyObject *
1503sizeof_func(PyObject *self, PyObject *obj)
1504{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001505 StgDictObject *dict;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001507 dict = PyType_stgdict(obj);
1508 if (dict)
1509 return PyLong_FromSsize_t(dict->size);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001511 if (CDataObject_Check(obj))
1512 return PyLong_FromSsize_t(((CDataObject *)obj)->b_size);
1513 PyErr_SetString(PyExc_TypeError,
1514 "this type has no size");
1515 return NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001516}
1517
1518static char alignment_doc[] =
1519"alignment(C type) -> integer\n"
1520"alignment(C instance) -> integer\n"
1521"Return the alignment requirements of a C instance";
1522
1523static PyObject *
1524align_func(PyObject *self, PyObject *obj)
1525{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001526 StgDictObject *dict;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001528 dict = PyType_stgdict(obj);
1529 if (dict)
1530 return PyLong_FromSsize_t(dict->align);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001532 dict = PyObject_stgdict(obj);
1533 if (dict)
1534 return PyLong_FromSsize_t(dict->align);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001536 PyErr_SetString(PyExc_TypeError,
1537 "no alignment info");
1538 return NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001539}
1540
1541static char byref_doc[] =
Thomas Hellerc5d01262008-06-10 15:08:51 +00001542"byref(C instance[, offset=0]) -> byref-object\n"
Thomas Hellerd4c93202006-03-08 19:35:11 +00001543"Return a pointer lookalike to a C instance, only usable\n"
1544"as function argument";
1545
1546/*
1547 * We must return something which can be converted to a parameter,
1548 * but still has a reference to self.
1549 */
1550static PyObject *
Thomas Hellerc5d01262008-06-10 15:08:51 +00001551byref(PyObject *self, PyObject *args)
Thomas Hellerd4c93202006-03-08 19:35:11 +00001552{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001553 PyCArgObject *parg;
1554 PyObject *obj;
1555 PyObject *pyoffset = NULL;
1556 Py_ssize_t offset = 0;
Thomas Hellerc5d01262008-06-10 15:08:51 +00001557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001558 if (!PyArg_UnpackTuple(args, "byref", 1, 2,
1559 &obj, &pyoffset))
1560 return NULL;
1561 if (pyoffset) {
1562 offset = PyNumber_AsSsize_t(pyoffset, NULL);
1563 if (offset == -1 && PyErr_Occurred())
1564 return NULL;
1565 }
1566 if (!CDataObject_Check(obj)) {
1567 PyErr_Format(PyExc_TypeError,
1568 "byref() argument must be a ctypes instance, not '%s'",
1569 Py_TYPE(obj)->tp_name);
1570 return NULL;
1571 }
Thomas Hellerd4c93202006-03-08 19:35:11 +00001572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001573 parg = PyCArgObject_new();
1574 if (parg == NULL)
1575 return NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001577 parg->tag = 'P';
1578 parg->pffi_type = &ffi_type_pointer;
1579 Py_INCREF(obj);
1580 parg->obj = obj;
1581 parg->value.p = (char *)((CDataObject *)obj)->b_ptr + offset;
1582 return (PyObject *)parg;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001583}
1584
1585static char addressof_doc[] =
1586"addressof(C instance) -> integer\n"
1587"Return the address of the C instance internal buffer";
1588
1589static PyObject *
1590addressof(PyObject *self, PyObject *obj)
1591{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001592 if (CDataObject_Check(obj))
1593 return PyLong_FromVoidPtr(((CDataObject *)obj)->b_ptr);
1594 PyErr_SetString(PyExc_TypeError,
1595 "invalid type");
1596 return NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001597}
1598
1599static int
1600converter(PyObject *obj, void **address)
1601{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001602 *address = PyLong_AsVoidPtr(obj);
1603 return *address != NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001604}
1605
1606static PyObject *
1607My_PyObj_FromPtr(PyObject *self, PyObject *args)
1608{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001609 PyObject *ob;
1610 if (!PyArg_ParseTuple(args, "O&:PyObj_FromPtr", converter, &ob))
1611 return NULL;
1612 Py_INCREF(ob);
1613 return ob;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001614}
1615
1616static PyObject *
1617My_Py_INCREF(PyObject *self, PyObject *arg)
1618{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001619 Py_INCREF(arg); /* that's what this function is for */
1620 Py_INCREF(arg); /* that for returning it */
1621 return arg;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001622}
1623
1624static PyObject *
1625My_Py_DECREF(PyObject *self, PyObject *arg)
1626{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001627 Py_DECREF(arg); /* that's what this function is for */
1628 Py_INCREF(arg); /* that's for returning it */
1629 return arg;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001630}
1631
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001632static PyObject *
1633resize(PyObject *self, PyObject *args)
1634{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001635 CDataObject *obj;
1636 StgDictObject *dict;
1637 Py_ssize_t size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001639 if (!PyArg_ParseTuple(args,
1640 "On:resize",
1641 &obj, &size))
1642 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001643
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001644 dict = PyObject_stgdict((PyObject *)obj);
1645 if (dict == NULL) {
1646 PyErr_SetString(PyExc_TypeError,
1647 "excepted ctypes instance");
1648 return NULL;
1649 }
1650 if (size < dict->size) {
1651 PyErr_Format(PyExc_ValueError,
1652 "minimum size is %zd",
1653 dict->size);
1654 return NULL;
1655 }
1656 if (obj->b_needsfree == 0) {
1657 PyErr_Format(PyExc_ValueError,
1658 "Memory cannot be resized because this object doesn't own it");
1659 return NULL;
1660 }
1661 if (size <= sizeof(obj->b_value)) {
1662 /* internal default buffer is large enough */
1663 obj->b_size = size;
1664 goto done;
1665 }
Antoine Pitrou305e1a72012-12-08 11:05:50 +01001666 if (!_CDataObject_HasExternalBuffer(obj)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001667 /* We are currently using the objects default buffer, but it
1668 isn't large enough any more. */
1669 void *ptr = PyMem_Malloc(size);
1670 if (ptr == NULL)
1671 return PyErr_NoMemory();
1672 memset(ptr, 0, size);
1673 memmove(ptr, obj->b_ptr, obj->b_size);
1674 obj->b_ptr = ptr;
1675 obj->b_size = size;
1676 } else {
1677 void * ptr = PyMem_Realloc(obj->b_ptr, size);
1678 if (ptr == NULL)
1679 return PyErr_NoMemory();
1680 obj->b_ptr = ptr;
1681 obj->b_size = size;
1682 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001683 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001684 Py_INCREF(Py_None);
1685 return Py_None;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001686}
1687
Thomas Heller13394e92008-02-13 20:40:44 +00001688static PyObject *
1689unpickle(PyObject *self, PyObject *args)
1690{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001691 PyObject *typ;
1692 PyObject *state;
1693 PyObject *result;
1694 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001695 _Py_IDENTIFIER(__new__);
1696 _Py_IDENTIFIER(__setstate__);
Thomas Heller13394e92008-02-13 20:40:44 +00001697
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001698 if (!PyArg_ParseTuple(args, "OO", &typ, &state))
1699 return NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001700 result = _PyObject_CallMethodId(typ, &PyId___new__, "O", typ);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001701 if (result == NULL)
1702 return NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001703 tmp = _PyObject_CallMethodId(result, &PyId___setstate__, "O", state);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001704 if (tmp == NULL) {
1705 Py_DECREF(result);
1706 return NULL;
1707 }
1708 Py_DECREF(tmp);
1709 return result;
Thomas Heller13394e92008-02-13 20:40:44 +00001710}
1711
Thomas Heller3071f812008-04-14 16:17:33 +00001712static PyObject *
1713POINTER(PyObject *self, PyObject *cls)
1714{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001715 PyObject *result;
1716 PyTypeObject *typ;
1717 PyObject *key;
1718 char *buf;
Thomas Heller3071f812008-04-14 16:17:33 +00001719
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001720 result = PyDict_GetItem(_ctypes_ptrtype_cache, cls);
1721 if (result) {
1722 Py_INCREF(result);
1723 return result;
1724 }
1725 if (PyUnicode_CheckExact(cls)) {
1726 char *name = _PyUnicode_AsString(cls);
1727 buf = alloca(strlen(name) + 3 + 1);
1728 sprintf(buf, "LP_%s", name);
1729 result = PyObject_CallFunction((PyObject *)Py_TYPE(&PyCPointer_Type),
1730 "s(O){}",
1731 buf,
1732 &PyCPointer_Type);
1733 if (result == NULL)
1734 return result;
1735 key = PyLong_FromVoidPtr(result);
1736 } else if (PyType_Check(cls)) {
1737 typ = (PyTypeObject *)cls;
1738 buf = alloca(strlen(typ->tp_name) + 3 + 1);
1739 sprintf(buf, "LP_%s", typ->tp_name);
1740 result = PyObject_CallFunction((PyObject *)Py_TYPE(&PyCPointer_Type),
1741 "s(O){sO}",
1742 buf,
1743 &PyCPointer_Type,
1744 "_type_", cls);
1745 if (result == NULL)
1746 return result;
1747 Py_INCREF(cls);
1748 key = cls;
1749 } else {
1750 PyErr_SetString(PyExc_TypeError, "must be a ctypes type");
1751 return NULL;
1752 }
1753 if (-1 == PyDict_SetItem(_ctypes_ptrtype_cache, key, result)) {
1754 Py_DECREF(result);
1755 Py_DECREF(key);
1756 return NULL;
1757 }
1758 Py_DECREF(key);
1759 return result;
Thomas Heller3071f812008-04-14 16:17:33 +00001760}
1761
1762static PyObject *
1763pointer(PyObject *self, PyObject *arg)
1764{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001765 PyObject *result;
1766 PyObject *typ;
Thomas Heller3071f812008-04-14 16:17:33 +00001767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001768 typ = PyDict_GetItem(_ctypes_ptrtype_cache, (PyObject *)Py_TYPE(arg));
1769 if (typ)
1770 return PyObject_CallFunctionObjArgs(typ, arg, NULL);
1771 typ = POINTER(NULL, (PyObject *)Py_TYPE(arg));
1772 if (typ == NULL)
1773 return NULL;
1774 result = PyObject_CallFunctionObjArgs(typ, arg, NULL);
1775 Py_DECREF(typ);
1776 return result;
Thomas Heller3071f812008-04-14 16:17:33 +00001777}
1778
Thomas Hellerb041fda2008-04-30 17:11:46 +00001779static PyObject *
1780buffer_info(PyObject *self, PyObject *arg)
1781{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001782 StgDictObject *dict = PyType_stgdict(arg);
1783 PyObject *shape;
1784 Py_ssize_t i;
Thomas Hellerb041fda2008-04-30 17:11:46 +00001785
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001786 if (dict == NULL)
1787 dict = PyObject_stgdict(arg);
1788 if (dict == NULL) {
1789 PyErr_SetString(PyExc_TypeError,
1790 "not a ctypes type or object");
1791 return NULL;
1792 }
1793 shape = PyTuple_New(dict->ndim);
1794 if (shape == NULL)
1795 return NULL;
1796 for (i = 0; i < (int)dict->ndim; ++i)
1797 PyTuple_SET_ITEM(shape, i, PyLong_FromSsize_t(dict->shape[i]));
Thomas Hellerb041fda2008-04-30 17:11:46 +00001798
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001799 if (PyErr_Occurred()) {
1800 Py_DECREF(shape);
1801 return NULL;
1802 }
1803 return Py_BuildValue("siN", dict->format, dict->ndim, shape);
Thomas Hellerb041fda2008-04-30 17:11:46 +00001804}
1805
Thomas Heller34596a92009-04-24 20:50:00 +00001806PyMethodDef _ctypes_module_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001807 {"get_errno", get_errno, METH_NOARGS},
1808 {"set_errno", set_errno, METH_VARARGS},
1809 {"POINTER", POINTER, METH_O },
1810 {"pointer", pointer, METH_O },
1811 {"_unpickle", unpickle, METH_VARARGS },
1812 {"buffer_info", buffer_info, METH_O, "Return buffer interface information"},
1813 {"resize", resize, METH_VARARGS, "Resize the memory buffer of a ctypes instance"},
Thomas Hellerd4c93202006-03-08 19:35:11 +00001814#ifdef MS_WIN32
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001815 {"get_last_error", get_last_error, METH_NOARGS},
1816 {"set_last_error", set_last_error, METH_VARARGS},
1817 {"CopyComPointer", copy_com_pointer, METH_VARARGS, copy_com_pointer_doc},
1818 {"FormatError", format_error, METH_VARARGS, format_error_doc},
1819 {"LoadLibrary", load_library, METH_VARARGS, load_library_doc},
1820 {"FreeLibrary", free_library, METH_VARARGS, free_library_doc},
1821 {"call_commethod", call_commethod, METH_VARARGS },
1822 {"_check_HRESULT", check_hresult, METH_VARARGS},
Thomas Hellerd4c93202006-03-08 19:35:11 +00001823#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001824 {"dlopen", py_dl_open, METH_VARARGS,
1825 "dlopen(name, flag={RTLD_GLOBAL|RTLD_LOCAL}) open a shared library"},
1826 {"dlclose", py_dl_close, METH_VARARGS, "dlclose a library"},
1827 {"dlsym", py_dl_sym, METH_VARARGS, "find symbol in shared library"},
Thomas Hellerd4c93202006-03-08 19:35:11 +00001828#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001829 {"alignment", align_func, METH_O, alignment_doc},
1830 {"sizeof", sizeof_func, METH_O, sizeof_doc},
1831 {"byref", byref, METH_VARARGS, byref_doc},
1832 {"addressof", addressof, METH_O, addressof_doc},
1833 {"call_function", call_function, METH_VARARGS },
1834 {"call_cdeclfunction", call_cdeclfunction, METH_VARARGS },
1835 {"PyObj_FromPtr", My_PyObj_FromPtr, METH_VARARGS },
1836 {"Py_INCREF", My_Py_INCREF, METH_O },
1837 {"Py_DECREF", My_Py_DECREF, METH_O },
1838 {NULL, NULL} /* Sentinel */
Thomas Hellerd4c93202006-03-08 19:35:11 +00001839};
1840
1841/*
1842 Local Variables:
1843 compile-command: "cd .. && python setup.py -q build -g && python setup.py -q build install --home ~"
1844 End:
1845*/