blob: 09eb653b30f71967574f5ae6f4597b1ca05d7d5d [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"
Christian Heimesf0400ba2013-06-18 13:22:17 +020073#ifdef HAVE_ALLOCA_H
74/* AIX needs alloca.h for alloca() */
Victor Stinner43b26392013-06-17 22:01:53 +020075#include <alloca.h>
Christian Heimesf0400ba2013-06-18 13:22:17 +020076#endif
Thomas Hellerd4c93202006-03-08 19:35:11 +000077
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000078#if defined(_DEBUG) || defined(__MINGW32__)
79/* Don't use structured exception handling on Windows if this is defined.
80 MingW, AFAIK, doesn't support it.
81*/
82#define DONT_USE_SEH
Thomas Hellerd4c93202006-03-08 19:35:11 +000083#endif
84
Benjamin Petersonb173f782009-05-05 22:31:58 +000085#define CTYPES_CAPSULE_NAME_PYMEM "_ctypes pymem"
86
87static void pymem_destructor(PyObject *ptr)
88{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000089 void *p = PyCapsule_GetPointer(ptr, CTYPES_CAPSULE_NAME_PYMEM);
90 if (p) {
91 PyMem_Free(p);
92 }
Benjamin Petersonb173f782009-05-05 22:31:58 +000093}
94
Thomas Heller9cac7b62008-06-06 09:31:40 +000095/*
96 ctypes maintains thread-local storage that has space for two error numbers:
97 private copies of the system 'errno' value and, on Windows, the system error code
98 accessed by the GetLastError() and SetLastError() api functions.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000099
Thomas Heller9cac7b62008-06-06 09:31:40 +0000100 Foreign functions created with CDLL(..., use_errno=True), when called, swap
101 the system 'errno' value with the private copy just before the actual
102 function call, and swapped again immediately afterwards. The 'use_errno'
103 parameter defaults to False, in this case 'ctypes_errno' is not touched.
104
105 On Windows, foreign functions created with CDLL(..., use_last_error=True) or
106 WinDLL(..., use_last_error=True) swap the system LastError value with the
107 ctypes private copy.
108
109 The values are also swapped immeditately before and after ctypes callback
110 functions are called, if the callbacks are constructed using the new
111 optional use_errno parameter set to True: CFUNCTYPE(..., use_errno=TRUE) or
112 WINFUNCTYPE(..., use_errno=True).
113
114 New ctypes functions are provided to access the ctypes private copies from
115 Python:
116
117 - ctypes.set_errno(value) and ctypes.set_last_error(value) store 'value' in
118 the private copy and returns the previous value.
119
120 - ctypes.get_errno() and ctypes.get_last_error() returns the current ctypes
121 private copies value.
122*/
123
124/*
125 This function creates and returns a thread-local Python object that has
126 space to store two integer error numbers; once created the Python object is
127 kept alive in the thread state dictionary as long as the thread itself.
128*/
129PyObject *
Thomas Heller34596a92009-04-24 20:50:00 +0000130_ctypes_get_errobj(int **pspace)
Thomas Heller9cac7b62008-06-06 09:31:40 +0000131{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000132 PyObject *dict = PyThreadState_GetDict();
133 PyObject *errobj;
134 static PyObject *error_object_name;
135 if (dict == 0) {
136 PyErr_SetString(PyExc_RuntimeError,
137 "cannot get thread state");
138 return NULL;
139 }
140 if (error_object_name == NULL) {
141 error_object_name = PyUnicode_InternFromString("ctypes.error_object");
142 if (error_object_name == NULL)
143 return NULL;
144 }
145 errobj = PyDict_GetItem(dict, error_object_name);
146 if (errobj) {
147 if (!PyCapsule_IsValid(errobj, CTYPES_CAPSULE_NAME_PYMEM)) {
148 PyErr_SetString(PyExc_RuntimeError,
149 "ctypes.error_object is an invalid capsule");
150 return NULL;
151 }
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 = PyCapsule_New(space, CTYPES_CAPSULE_NAME_PYMEM, pymem_destructor);
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 *)PyCapsule_GetPointer(errobj, CTYPES_CAPSULE_NAME_PYMEM);
169 return errobj;
Thomas Heller9cac7b62008-06-06 09:31:40 +0000170}
171
172static PyObject *
173get_error_internal(PyObject *self, PyObject *args, int index)
174{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175 int *space;
176 PyObject *errobj = _ctypes_get_errobj(&space);
177 PyObject *result;
Thomas Heller9cac7b62008-06-06 09:31:40 +0000178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000179 if (errobj == NULL)
180 return NULL;
181 result = PyLong_FromLong(space[index]);
182 Py_DECREF(errobj);
183 return result;
Thomas Heller9cac7b62008-06-06 09:31:40 +0000184}
185
186static PyObject *
187set_error_internal(PyObject *self, PyObject *args, int index)
188{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000189 int new_errno, old_errno;
190 PyObject *errobj;
191 int *space;
Thomas Heller9cac7b62008-06-06 09:31:40 +0000192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000193 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 PyLong_FromLong(old_errno);
Thomas Heller9cac7b62008-06-06 09:31:40 +0000202}
203
204static PyObject *
205get_errno(PyObject *self, PyObject *args)
206{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000207 return get_error_internal(self, args, 0);
Thomas Heller9cac7b62008-06-06 09:31:40 +0000208}
209
210static PyObject *
211set_errno(PyObject *self, PyObject *args)
212{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000213 return set_error_internal(self, args, 0);
Thomas Heller9cac7b62008-06-06 09:31:40 +0000214}
215
Thomas Hellerd4c93202006-03-08 19:35:11 +0000216#ifdef MS_WIN32
Thomas Heller9cac7b62008-06-06 09:31:40 +0000217
218static PyObject *
219get_last_error(PyObject *self, PyObject *args)
220{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000221 return get_error_internal(self, args, 1);
Thomas Heller9cac7b62008-06-06 09:31:40 +0000222}
223
224static PyObject *
225set_last_error(PyObject *self, PyObject *args)
226{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000227 return set_error_internal(self, args, 1);
Thomas Heller9cac7b62008-06-06 09:31:40 +0000228}
229
Thomas Hellerd4c93202006-03-08 19:35:11 +0000230PyObject *ComError;
231
Thomas Heller71fb5132008-11-26 08:45:36 +0000232static WCHAR *FormatError(DWORD code)
Thomas Hellerd4c93202006-03-08 19:35:11 +0000233{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000234 WCHAR *lpMsgBuf;
235 DWORD n;
236 n = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
237 NULL,
238 code,
239 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), /* Default language */
240 (LPWSTR) &lpMsgBuf,
241 0,
242 NULL);
243 if (n) {
244 while (iswspace(lpMsgBuf[n-1]))
245 --n;
246 lpMsgBuf[n] = L'\0'; /* rstrip() */
247 }
248 return lpMsgBuf;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000249}
250
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000251#ifndef DONT_USE_SEH
Thomas Heller84c97af2009-04-25 16:49:23 +0000252static void SetException(DWORD code, EXCEPTION_RECORD *pr)
Thomas Hellerd4c93202006-03-08 19:35:11 +0000253{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000254 /* 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;
Thomas Heller84c97af2009-04-25 16:49:23 +0000272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000273 case EXCEPTION_BREAKPOINT:
274 /* A breakpoint was encountered. */
275 PyErr_SetString(PyExc_WindowsError,
276 "exception: breakpoint encountered");
277 break;
Thomas Heller84c97af2009-04-25 16:49:23 +0000278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000279 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;
Thomas Heller84c97af2009-04-25 16:49:23 +0000288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000289 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;
Thomas Heller84c97af2009-04-25 16:49:23 +0000295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000296 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;
Thomas Heller84c97af2009-04-25 16:49:23 +0000303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000304 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;
Thomas Heller84c97af2009-04-25 16:49:23 +0000312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000313 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;
Thomas Heller84c97af2009-04-25 16:49:23 +0000319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000320 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;
Thomas Heller84c97af2009-04-25 16:49:23 +0000326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000327 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;
Thomas Heller84c97af2009-04-25 16:49:23 +0000333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000334 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;
Thomas Heller84c97af2009-04-25 16:49:23 +0000341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000342 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;
Thomas Heller84c97af2009-04-25 16:49:23 +0000348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000349 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;
Thomas Heller84c97af2009-04-25 16:49:23 +0000355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000356 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;
Thomas Heller84c97af2009-04-25 16:49:23 +0000363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000364 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;
Thomas Heller84c97af2009-04-25 16:49:23 +0000370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000371 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;
Thomas Heller84c97af2009-04-25 16:49:23 +0000377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000378 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;
Thomas Heller84c97af2009-04-25 16:49:23 +0000385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000386 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;
Thomas Heller84c97af2009-04-25 16:49:23 +0000392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000393 default:
394 PyErr_SetFromWindowsErr(code);
395 break;
396 }
Thomas Hellerd4c93202006-03-08 19:35:11 +0000397}
398
399static DWORD HandleException(EXCEPTION_POINTERS *ptrs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000400 DWORD *pdw, EXCEPTION_RECORD *record)
Thomas Hellerd4c93202006-03-08 19:35:11 +0000401{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000402 *pdw = ptrs->ExceptionRecord->ExceptionCode;
403 *record = *ptrs->ExceptionRecord;
Kristján Valur Jónsson5aed3302013-03-19 15:24:10 -0700404 /* We don't want to catch breakpoint exceptions, they are used to attach
405 * a debugger to the process.
406 */
407 if (*pdw == EXCEPTION_BREAKPOINT)
408 return EXCEPTION_CONTINUE_SEARCH;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000409 return EXCEPTION_EXECUTE_HANDLER;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000410}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000411#endif
Thomas Hellerd4c93202006-03-08 19:35:11 +0000412
413static PyObject *
414check_hresult(PyObject *self, PyObject *args)
415{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000416 HRESULT hr;
417 if (!PyArg_ParseTuple(args, "i", &hr))
418 return NULL;
419 if (FAILED(hr))
420 return PyErr_SetFromWindowsErr(hr);
421 return PyLong_FromLong(hr);
Thomas Hellerd4c93202006-03-08 19:35:11 +0000422}
423
424#endif
425
426/**************************************************************/
427
428PyCArgObject *
Thomas Heller34596a92009-04-24 20:50:00 +0000429PyCArgObject_new(void)
Thomas Hellerd4c93202006-03-08 19:35:11 +0000430{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 PyCArgObject *p;
432 p = PyObject_New(PyCArgObject, &PyCArg_Type);
433 if (p == NULL)
434 return NULL;
435 p->pffi_type = NULL;
436 p->tag = '\0';
437 p->obj = NULL;
438 memset(&p->value, 0, sizeof(p->value));
439 return p;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000440}
441
442static void
443PyCArg_dealloc(PyCArgObject *self)
444{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000445 Py_XDECREF(self->obj);
446 PyObject_Del(self);
Thomas Hellerd4c93202006-03-08 19:35:11 +0000447}
448
449static PyObject *
450PyCArg_repr(PyCArgObject *self)
451{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000452 char buffer[256];
453 switch(self->tag) {
454 case 'b':
455 case 'B':
456 sprintf(buffer, "<cparam '%c' (%d)>",
457 self->tag, self->value.b);
458 break;
459 case 'h':
460 case 'H':
461 sprintf(buffer, "<cparam '%c' (%d)>",
462 self->tag, self->value.h);
463 break;
464 case 'i':
465 case 'I':
466 sprintf(buffer, "<cparam '%c' (%d)>",
467 self->tag, self->value.i);
468 break;
469 case 'l':
470 case 'L':
471 sprintf(buffer, "<cparam '%c' (%ld)>",
472 self->tag, self->value.l);
473 break;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000475#ifdef HAVE_LONG_LONG
476 case 'q':
477 case 'Q':
478 sprintf(buffer,
479#ifdef MS_WIN32
480 "<cparam '%c' (%I64d)>",
481#else
482 "<cparam '%c' (%qd)>",
483#endif
484 self->tag, self->value.q);
485 break;
486#endif
487 case 'd':
488 sprintf(buffer, "<cparam '%c' (%f)>",
489 self->tag, self->value.d);
490 break;
491 case 'f':
492 sprintf(buffer, "<cparam '%c' (%f)>",
493 self->tag, self->value.f);
494 break;
495
496 case 'c':
497 sprintf(buffer, "<cparam '%c' (%c)>",
498 self->tag, self->value.c);
499 break;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000500
501/* Hm, are these 'z' and 'Z' codes useful at all?
502 Shouldn't they be replaced by the functionality of c_string
503 and c_wstring ?
504*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000505 case 'z':
506 case 'Z':
507 case 'P':
508 sprintf(buffer, "<cparam '%c' (%p)>",
509 self->tag, self->value.p);
510 break;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 default:
513 sprintf(buffer, "<cparam '%c' at %p>",
514 self->tag, self);
515 break;
516 }
517 return PyUnicode_FromString(buffer);
Thomas Hellerd4c93202006-03-08 19:35:11 +0000518}
519
520static PyMemberDef PyCArgType_members[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 { "_obj", T_OBJECT,
522 offsetof(PyCArgObject, obj), READONLY,
523 "the wrapped object" },
524 { NULL },
Thomas Hellerd4c93202006-03-08 19:35:11 +0000525};
526
527PyTypeObject PyCArg_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000528 PyVarObject_HEAD_INIT(NULL, 0)
529 "CArgObject",
530 sizeof(PyCArgObject),
531 0,
532 (destructor)PyCArg_dealloc, /* tp_dealloc */
533 0, /* tp_print */
534 0, /* tp_getattr */
535 0, /* tp_setattr */
536 0, /* tp_reserved */
537 (reprfunc)PyCArg_repr, /* tp_repr */
538 0, /* tp_as_number */
539 0, /* tp_as_sequence */
540 0, /* tp_as_mapping */
541 0, /* tp_hash */
542 0, /* tp_call */
543 0, /* tp_str */
544 0, /* tp_getattro */
545 0, /* tp_setattro */
546 0, /* tp_as_buffer */
547 Py_TPFLAGS_DEFAULT, /* tp_flags */
548 0, /* tp_doc */
549 0, /* tp_traverse */
550 0, /* tp_clear */
551 0, /* tp_richcompare */
552 0, /* tp_weaklistoffset */
553 0, /* tp_iter */
554 0, /* tp_iternext */
555 0, /* tp_methods */
556 PyCArgType_members, /* tp_members */
Thomas Hellerd4c93202006-03-08 19:35:11 +0000557};
558
559/****************************************************************/
560/*
561 * Convert a PyObject * into a parameter suitable to pass to an
562 * C function call.
563 *
564 * 1. Python integers are converted to C int and passed by value.
Thomas Heller69b639f2009-09-18 20:08:39 +0000565 * Py_None is converted to a C NULL pointer.
Thomas Hellerd4c93202006-03-08 19:35:11 +0000566 *
567 * 2. 3-tuples are expected to have a format character in the first
568 * item, which must be 'i', 'f', 'd', 'q', or 'P'.
569 * The second item will have to be an integer, float, double, long long
570 * or integer (denoting an address void *), will be converted to the
571 * corresponding C data type and passed by value.
572 *
573 * 3. Other Python objects are tested for an '_as_parameter_' attribute.
574 * The value of this attribute must be an integer which will be passed
575 * by value, or a 2-tuple or 3-tuple which will be used according
576 * to point 2 above. The third item (if any), is ignored. It is normally
577 * used to keep the object alive where this parameter refers to.
578 * XXX This convention is dangerous - you can construct arbitrary tuples
579 * in Python and pass them. Would it be safer to use a custom container
580 * datatype instead of a tuple?
581 *
582 * 4. Other Python objects cannot be passed as parameters - an exception is raised.
583 *
584 * 5. ConvParam will store the converted result in a struct containing format
585 * and value.
586 */
587
588union result {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 char c;
590 char b;
591 short h;
592 int i;
593 long l;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000594#ifdef HAVE_LONG_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 PY_LONG_LONG q;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000596#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000597 long double D;
598 double d;
599 float f;
600 void *p;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000601};
602
603struct argument {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000604 ffi_type *ffi_type;
605 PyObject *keep;
606 union result value;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000607};
608
609/*
610 * Convert a single Python object into a PyCArgObject and return it.
611 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000612static int ConvParam(PyObject *obj, Py_ssize_t index, struct argument *pa)
Thomas Hellerd4c93202006-03-08 19:35:11 +0000613{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000614 StgDictObject *dict;
615 pa->keep = NULL; /* so we cannot forget it later */
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000617 dict = PyObject_stgdict(obj);
618 if (dict) {
619 PyCArgObject *carg;
620 assert(dict->paramfunc);
621 /* If it has an stgdict, it is a CDataObject */
622 carg = dict->paramfunc((CDataObject *)obj);
623 pa->ffi_type = carg->pffi_type;
624 memcpy(&pa->value, &carg->value, sizeof(pa->value));
625 pa->keep = (PyObject *)carg;
626 return 0;
627 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000628
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000629 if (PyCArg_CheckExact(obj)) {
630 PyCArgObject *carg = (PyCArgObject *)obj;
631 pa->ffi_type = carg->pffi_type;
632 Py_INCREF(obj);
633 pa->keep = obj;
634 memcpy(&pa->value, &carg->value, sizeof(pa->value));
635 return 0;
636 }
Thomas Hellerd4c93202006-03-08 19:35:11 +0000637
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 /* check for None, integer, string or unicode and use directly if successful */
639 if (obj == Py_None) {
640 pa->ffi_type = &ffi_type_pointer;
641 pa->value.p = NULL;
642 return 0;
643 }
Thomas Hellerd4c93202006-03-08 19:35:11 +0000644
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000645 if (PyLong_Check(obj)) {
646 pa->ffi_type = &ffi_type_sint;
647 pa->value.i = (long)PyLong_AsUnsignedLong(obj);
648 if (pa->value.i == -1 && PyErr_Occurred()) {
649 PyErr_Clear();
650 pa->value.i = PyLong_AsLong(obj);
651 if (pa->value.i == -1 && PyErr_Occurred()) {
652 PyErr_SetString(PyExc_OverflowError,
Serhiy Storchaka95949422013-08-27 19:40:23 +0300653 "int too long to convert");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000654 return -1;
655 }
656 }
657 return 0;
658 }
Thomas Hellerd4c93202006-03-08 19:35:11 +0000659
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000660 if (PyBytes_Check(obj)) {
661 pa->ffi_type = &ffi_type_pointer;
662 pa->value.p = PyBytes_AsString(obj);
663 Py_INCREF(obj);
664 pa->keep = obj;
665 return 0;
666 }
Thomas Heller7775c712007-07-12 19:19:43 +0000667
Thomas Hellerd4c93202006-03-08 19:35:11 +0000668#ifdef CTYPES_UNICODE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000669 if (PyUnicode_Check(obj)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 pa->ffi_type = &ffi_type_pointer;
Victor Stinnerbeb4135b2010-10-07 01:02:42 +0000671 pa->value.p = PyUnicode_AsWideCharString(obj, NULL);
Victor Stinner4c2e4fa2010-09-29 10:37:16 +0000672 if (pa->value.p == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000673 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000674 pa->keep = PyCapsule_New(pa->value.p, CTYPES_CAPSULE_NAME_PYMEM, pymem_destructor);
675 if (!pa->keep) {
676 PyMem_Free(pa->value.p);
677 return -1;
678 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000679 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000680 }
Thomas Hellerd4c93202006-03-08 19:35:11 +0000681#endif
682
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000683 {
684 PyObject *arg;
685 arg = PyObject_GetAttrString(obj, "_as_parameter_");
686 /* Which types should we exactly allow here?
687 integers are required for using Python classes
688 as parameters (they have to expose the '_as_parameter_'
689 attribute)
690 */
691 if (arg) {
692 int result;
693 result = ConvParam(arg, index, pa);
694 Py_DECREF(arg);
695 return result;
696 }
697 PyErr_Format(PyExc_TypeError,
698 "Don't know how to convert parameter %d",
699 Py_SAFE_DOWNCAST(index, Py_ssize_t, int));
700 return -1;
701 }
Thomas Hellerd4c93202006-03-08 19:35:11 +0000702}
703
704
Thomas Heller34596a92009-04-24 20:50:00 +0000705ffi_type *_ctypes_get_ffi_type(PyObject *obj)
Thomas Hellerd4c93202006-03-08 19:35:11 +0000706{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000707 StgDictObject *dict;
708 if (obj == NULL)
709 return &ffi_type_sint;
710 dict = PyType_stgdict(obj);
711 if (dict == NULL)
712 return &ffi_type_sint;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000713#if defined(MS_WIN32) && !defined(_WIN32_WCE)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 /* This little trick works correctly with MSVC.
715 It returns small structures in registers
716 */
717 if (dict->ffi_type_pointer.type == FFI_TYPE_STRUCT) {
718 if (dict->ffi_type_pointer.size <= 4)
719 return &ffi_type_sint32;
720 else if (dict->ffi_type_pointer.size <= 8)
721 return &ffi_type_sint64;
722 }
Thomas Hellerd4c93202006-03-08 19:35:11 +0000723#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000724 return &dict->ffi_type_pointer;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000725}
726
727
728/*
729 * libffi uses:
730 *
731 * ffi_status ffi_prep_cif(ffi_cif *cif, ffi_abi abi,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000732 * unsigned int nargs,
Thomas Hellerd4c93202006-03-08 19:35:11 +0000733 * ffi_type *rtype,
734 * ffi_type **atypes);
735 *
736 * and then
737 *
738 * void ffi_call(ffi_cif *cif, void *fn, void *rvalue, void **avalues);
739 */
740static int _call_function_pointer(int flags,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000741 PPROC pProc,
742 void **avalues,
743 ffi_type **atypes,
744 ffi_type *restype,
745 void *resmem,
746 int argcount)
Thomas Hellerd4c93202006-03-08 19:35:11 +0000747{
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000748#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000749 PyThreadState *_save = NULL; /* For Py_BLOCK_THREADS and Py_UNBLOCK_THREADS */
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000750#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000751 PyObject *error_object = NULL;
752 int *space;
753 ffi_cif cif;
754 int cc;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000755#ifdef MS_WIN32
Thomas Hellerb00697e2010-06-21 16:00:31 +0000756 int delta;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000757#ifndef DONT_USE_SEH
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 DWORD dwExceptionCode = 0;
759 EXCEPTION_RECORD record;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000760#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000761#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000762 /* XXX check before here */
763 if (restype == NULL) {
764 PyErr_SetString(PyExc_RuntimeError,
765 "No ffi_type for result");
766 return -1;
767 }
Thomas Hellerd4c93202006-03-08 19:35:11 +0000768
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000769 cc = FFI_DEFAULT_ABI;
770#if defined(MS_WIN32) && !defined(MS_WIN64) && !defined(_WIN32_WCE)
771 if ((flags & FUNCFLAG_CDECL) == 0)
772 cc = FFI_STDCALL;
773#endif
774 if (FFI_OK != ffi_prep_cif(&cif,
775 cc,
776 argcount,
777 restype,
778 atypes)) {
779 PyErr_SetString(PyExc_RuntimeError,
780 "ffi_prep_cif failed");
781 return -1;
782 }
783
784 if (flags & (FUNCFLAG_USE_ERRNO | FUNCFLAG_USE_LASTERROR)) {
785 error_object = _ctypes_get_errobj(&space);
786 if (error_object == NULL)
787 return -1;
788 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000789#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 if ((flags & FUNCFLAG_PYTHONAPI) == 0)
791 Py_UNBLOCK_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000792#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000793 if (flags & FUNCFLAG_USE_ERRNO) {
794 int temp = space[0];
795 space[0] = errno;
796 errno = temp;
797 }
Thomas Hellerd4c93202006-03-08 19:35:11 +0000798#ifdef MS_WIN32
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000799 if (flags & FUNCFLAG_USE_LASTERROR) {
800 int temp = space[1];
801 space[1] = GetLastError();
802 SetLastError(temp);
803 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000804#ifndef DONT_USE_SEH
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000805 __try {
Thomas Hellerd4c93202006-03-08 19:35:11 +0000806#endif
Thomas Hellerb00697e2010-06-21 16:00:31 +0000807 delta =
Thomas Hellerd4c93202006-03-08 19:35:11 +0000808#endif
Thomas Hellerb00697e2010-06-21 16:00:31 +0000809 ffi_call(&cif, (void *)pProc, resmem, avalues);
Thomas Hellerd4c93202006-03-08 19:35:11 +0000810#ifdef MS_WIN32
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000811#ifndef DONT_USE_SEH
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 }
813 __except (HandleException(GetExceptionInformation(),
814 &dwExceptionCode, &record)) {
815 ;
816 }
Thomas Hellerd4c93202006-03-08 19:35:11 +0000817#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000818 if (flags & FUNCFLAG_USE_LASTERROR) {
819 int temp = space[1];
820 space[1] = GetLastError();
821 SetLastError(temp);
822 }
Thomas Hellerd4c93202006-03-08 19:35:11 +0000823#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000824 if (flags & FUNCFLAG_USE_ERRNO) {
825 int temp = space[0];
826 space[0] = errno;
827 errno = temp;
828 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000829#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 if ((flags & FUNCFLAG_PYTHONAPI) == 0)
831 Py_BLOCK_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000832#endif
Kristjan Valur Jonsson9946bd62012-12-21 09:41:25 +0000833 Py_XDECREF(error_object);
Thomas Hellerd4c93202006-03-08 19:35:11 +0000834#ifdef MS_WIN32
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000835#ifndef DONT_USE_SEH
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 if (dwExceptionCode) {
837 SetException(dwExceptionCode, &record);
838 return -1;
839 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000840#endif
Thomas Hellerb00697e2010-06-21 16:00:31 +0000841#ifdef MS_WIN64
842 if (delta != 0) {
843 PyErr_Format(PyExc_RuntimeError,
844 "ffi_call failed with code %d",
845 delta);
846 return -1;
847 }
848#else
849 if (delta < 0) {
850 if (flags & FUNCFLAG_CDECL)
851 PyErr_Format(PyExc_ValueError,
852 "Procedure called with not enough "
853 "arguments (%d bytes missing) "
854 "or wrong calling convention",
855 -delta);
856 else
857 PyErr_Format(PyExc_ValueError,
858 "Procedure probably called with not enough "
859 "arguments (%d bytes missing)",
860 -delta);
861 return -1;
862 } else if (delta > 0) {
863 PyErr_Format(PyExc_ValueError,
864 "Procedure probably called with too many "
865 "arguments (%d bytes in excess)",
866 delta);
867 return -1;
868 }
869#endif
Thomas Wouters89f507f2006-12-13 04:49:30 +0000870#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000871 if ((flags & FUNCFLAG_PYTHONAPI) && PyErr_Occurred())
872 return -1;
873 return 0;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000874}
875
876/*
877 * Convert the C value in result into a Python object, depending on restype.
878 *
879 * - If restype is NULL, return a Python integer.
880 * - If restype is None, return None.
881 * - If restype is a simple ctypes type (c_int, c_void_p), call the type's getfunc,
882 * pass the result to checker and return the result.
883 * - If restype is another ctypes type, return an instance of that.
884 * - Otherwise, call restype and return the result.
885 */
886static PyObject *GetResult(PyObject *restype, void *result, PyObject *checker)
887{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000888 StgDictObject *dict;
889 PyObject *retval, *v;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000891 if (restype == NULL)
892 return PyLong_FromLong(*(int *)result);
Thomas Hellerd4c93202006-03-08 19:35:11 +0000893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 if (restype == Py_None) {
895 Py_INCREF(Py_None);
896 return Py_None;
897 }
Thomas Hellerd4c93202006-03-08 19:35:11 +0000898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000899 dict = PyType_stgdict(restype);
900 if (dict == NULL)
901 return PyObject_CallFunction(restype, "i", *(int *)result);
Thomas Hellerd4c93202006-03-08 19:35:11 +0000902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000903 if (dict->getfunc && !_ctypes_simple_instance(restype)) {
904 retval = dict->getfunc(result, dict->size);
905 /* If restype is py_object (detected by comparing getfunc with
906 O_get), we have to call Py_DECREF because O_get has already
907 called Py_INCREF.
908 */
909 if (dict->getfunc == _ctypes_get_fielddesc("O")->getfunc) {
910 Py_DECREF(retval);
911 }
912 } else
913 retval = PyCData_FromBaseObj(restype, NULL, 0, result);
Thomas Hellerd4c93202006-03-08 19:35:11 +0000914
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000915 if (!checker || !retval)
916 return retval;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 v = PyObject_CallFunctionObjArgs(checker, retval, NULL);
919 if (v == NULL)
920 _ctypes_add_traceback("GetResult", "_ctypes/callproc.c", __LINE__-2);
921 Py_DECREF(retval);
922 return v;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000923}
924
925/*
926 * Raise a new exception 'exc_class', adding additional text to the original
927 * exception string.
928 */
Thomas Heller34596a92009-04-24 20:50:00 +0000929void _ctypes_extend_error(PyObject *exc_class, char *fmt, ...)
Thomas Hellerd4c93202006-03-08 19:35:11 +0000930{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 va_list vargs;
932 PyObject *tp, *v, *tb, *s, *cls_str, *msg_str;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000933
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 va_start(vargs, fmt);
935 s = PyUnicode_FromFormatV(fmt, vargs);
936 va_end(vargs);
937 if (!s)
938 return;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 PyErr_Fetch(&tp, &v, &tb);
941 PyErr_NormalizeException(&tp, &v, &tb);
942 cls_str = PyObject_Str(tp);
943 if (cls_str) {
944 PyUnicode_AppendAndDel(&s, cls_str);
945 PyUnicode_AppendAndDel(&s, PyUnicode_FromString(": "));
946 if (s == NULL)
947 goto error;
948 } else
949 PyErr_Clear();
950 msg_str = PyObject_Str(v);
951 if (msg_str)
952 PyUnicode_AppendAndDel(&s, msg_str);
953 else {
954 PyErr_Clear();
955 PyUnicode_AppendAndDel(&s, PyUnicode_FromString("???"));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000956 }
Victor Stinner67002af2011-10-02 20:35:10 +0200957 if (s == NULL)
958 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 PyErr_SetObject(exc_class, s);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000960error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000961 Py_XDECREF(tp);
962 Py_XDECREF(v);
963 Py_XDECREF(tb);
964 Py_XDECREF(s);
Thomas Hellerd4c93202006-03-08 19:35:11 +0000965}
966
967
968#ifdef MS_WIN32
969
970static PyObject *
971GetComError(HRESULT errcode, GUID *riid, IUnknown *pIunk)
972{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000973 HRESULT hr;
974 ISupportErrorInfo *psei = NULL;
975 IErrorInfo *pei = NULL;
976 BSTR descr=NULL, helpfile=NULL, source=NULL;
977 GUID guid;
978 DWORD helpcontext=0;
979 LPOLESTR progid;
980 PyObject *obj;
981 LPOLESTR text;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000982
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000983 /* We absolutely have to release the GIL during COM method calls,
984 otherwise we may get a deadlock!
985 */
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000986#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987 Py_BEGIN_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000988#endif
989
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000990 hr = pIunk->lpVtbl->QueryInterface(pIunk, &IID_ISupportErrorInfo, (void **)&psei);
991 if (FAILED(hr))
992 goto failed;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000994 hr = psei->lpVtbl->InterfaceSupportsErrorInfo(psei, riid);
995 psei->lpVtbl->Release(psei);
996 if (FAILED(hr))
997 goto failed;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 hr = GetErrorInfo(0, &pei);
1000 if (hr != S_OK)
1001 goto failed;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001002
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001003 pei->lpVtbl->GetDescription(pei, &descr);
1004 pei->lpVtbl->GetGUID(pei, &guid);
1005 pei->lpVtbl->GetHelpContext(pei, &helpcontext);
1006 pei->lpVtbl->GetHelpFile(pei, &helpfile);
1007 pei->lpVtbl->GetSource(pei, &source);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001008
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001009 pei->lpVtbl->Release(pei);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001010
Thomas Hellerd4c93202006-03-08 19:35:11 +00001011 failed:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001012#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001013 Py_END_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001014#endif
Thomas Hellerd4c93202006-03-08 19:35:11 +00001015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 progid = NULL;
1017 ProgIDFromCLSID(&guid, &progid);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 text = FormatError(errcode);
1020 obj = Py_BuildValue(
1021 "iu(uuuiu)",
1022 errcode,
1023 text,
1024 descr, source, helpfile, helpcontext,
1025 progid);
1026 if (obj) {
1027 PyErr_SetObject(ComError, obj);
1028 Py_DECREF(obj);
1029 }
1030 LocalFree(text);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001031
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001032 if (descr)
1033 SysFreeString(descr);
1034 if (helpfile)
1035 SysFreeString(helpfile);
1036 if (source)
1037 SysFreeString(source);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001039 return NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001040}
1041#endif
1042
1043/*
1044 * Requirements, must be ensured by the caller:
1045 * - argtuple is tuple of arguments
1046 * - argtypes is either NULL, or a tuple of the same size as argtuple
1047 *
1048 * - XXX various requirements for restype, not yet collected
1049 */
Thomas Heller34596a92009-04-24 20:50:00 +00001050PyObject *_ctypes_callproc(PPROC pProc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001051 PyObject *argtuple,
Thomas Hellerd4c93202006-03-08 19:35:11 +00001052#ifdef MS_WIN32
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 IUnknown *pIunk,
1054 GUID *iid,
Thomas Hellerd4c93202006-03-08 19:35:11 +00001055#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001056 int flags,
1057 PyObject *argtypes, /* misleading name: This is a tuple of
1058 methods, not types: the .from_param
1059 class methods of the types */
1060 PyObject *restype,
1061 PyObject *checker)
Thomas Hellerd4c93202006-03-08 19:35:11 +00001062{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001063 Py_ssize_t i, n, argcount, argtype_count;
1064 void *resbuf;
1065 struct argument *args, *pa;
1066 ffi_type **atypes;
1067 ffi_type *rtype;
1068 void **avalues;
1069 PyObject *retval = NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001070
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 n = argcount = PyTuple_GET_SIZE(argtuple);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001072#ifdef MS_WIN32
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 /* an optional COM object this pointer */
1074 if (pIunk)
1075 ++argcount;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001076#endif
1077
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 args = (struct argument *)alloca(sizeof(struct argument) * argcount);
1079 if (!args) {
1080 PyErr_NoMemory();
1081 return NULL;
1082 }
1083 memset(args, 0, sizeof(struct argument) * argcount);
1084 argtype_count = argtypes ? PyTuple_GET_SIZE(argtypes) : 0;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001085#ifdef MS_WIN32
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001086 if (pIunk) {
1087 args[0].ffi_type = &ffi_type_pointer;
1088 args[0].value.p = pIunk;
1089 pa = &args[1];
1090 } else
Thomas Hellerd4c93202006-03-08 19:35:11 +00001091#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001092 pa = &args[0];
Thomas Hellerd4c93202006-03-08 19:35:11 +00001093
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001094 /* Convert the arguments */
1095 for (i = 0; i < n; ++i, ++pa) {
1096 PyObject *converter;
1097 PyObject *arg;
1098 int err;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001099
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001100 arg = PyTuple_GET_ITEM(argtuple, i); /* borrowed ref */
1101 /* For cdecl functions, we allow more actual arguments
1102 than the length of the argtypes tuple.
1103 This is checked in _ctypes::PyCFuncPtr_Call
1104 */
1105 if (argtypes && argtype_count > i) {
1106 PyObject *v;
1107 converter = PyTuple_GET_ITEM(argtypes, i);
1108 v = PyObject_CallFunctionObjArgs(converter,
1109 arg,
1110 NULL);
1111 if (v == NULL) {
1112 _ctypes_extend_error(PyExc_ArgError, "argument %d: ", i+1);
1113 goto cleanup;
1114 }
Thomas Hellerd4c93202006-03-08 19:35:11 +00001115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001116 err = ConvParam(v, i+1, pa);
1117 Py_DECREF(v);
1118 if (-1 == err) {
1119 _ctypes_extend_error(PyExc_ArgError, "argument %d: ", i+1);
1120 goto cleanup;
1121 }
1122 } else {
1123 err = ConvParam(arg, i+1, pa);
1124 if (-1 == err) {
1125 _ctypes_extend_error(PyExc_ArgError, "argument %d: ", i+1);
1126 goto cleanup; /* leaking ? */
1127 }
1128 }
1129 }
Thomas Hellerd4c93202006-03-08 19:35:11 +00001130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001131 rtype = _ctypes_get_ffi_type(restype);
1132 resbuf = alloca(max(rtype->size, sizeof(ffi_arg)));
Thomas Hellerd4c93202006-03-08 19:35:11 +00001133
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001134 avalues = (void **)alloca(sizeof(void *) * argcount);
1135 atypes = (ffi_type **)alloca(sizeof(ffi_type *) * argcount);
1136 if (!resbuf || !avalues || !atypes) {
1137 PyErr_NoMemory();
1138 goto cleanup;
1139 }
1140 for (i = 0; i < argcount; ++i) {
1141 atypes[i] = args[i].ffi_type;
Victor Stinner4c2e4fa2010-09-29 10:37:16 +00001142 if (atypes[i]->type == FFI_TYPE_STRUCT
Thomas Hellerb00697e2010-06-21 16:00:31 +00001143#ifdef _WIN64
1144 && atypes[i]->size <= sizeof(void *)
1145#endif
1146 )
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001147 avalues[i] = (void *)args[i].value.p;
1148 else
1149 avalues[i] = (void *)&args[i].value;
1150 }
Thomas Hellerd4c93202006-03-08 19:35:11 +00001151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001152 if (-1 == _call_function_pointer(flags, pProc, avalues, atypes,
1153 rtype, resbuf,
1154 Py_SAFE_DOWNCAST(argcount,
1155 Py_ssize_t,
1156 int)))
1157 goto cleanup;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001158
1159#ifdef WORDS_BIGENDIAN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001160 /* libffi returns the result in a buffer with sizeof(ffi_arg). This
1161 causes problems on big endian machines, since the result buffer
1162 address cannot simply be used as result pointer, instead we must
1163 adjust the pointer value:
1164 */
1165 /*
1166 XXX I should find out and clarify why this is needed at all,
1167 especially why adjusting for ffi_type_float must be avoided on
1168 64-bit platforms.
1169 */
1170 if (rtype->type != FFI_TYPE_FLOAT
1171 && rtype->type != FFI_TYPE_STRUCT
1172 && rtype->size < sizeof(ffi_arg))
1173 resbuf = (char *)resbuf + sizeof(ffi_arg) - rtype->size;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001174#endif
1175
1176#ifdef MS_WIN32
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001177 if (iid && pIunk) {
1178 if (*(int *)resbuf & 0x80000000)
1179 retval = GetComError(*(HRESULT *)resbuf, iid, pIunk);
1180 else
1181 retval = PyLong_FromLong(*(int *)resbuf);
1182 } else if (flags & FUNCFLAG_HRESULT) {
1183 if (*(int *)resbuf & 0x80000000)
1184 retval = PyErr_SetFromWindowsErr(*(int *)resbuf);
1185 else
1186 retval = PyLong_FromLong(*(int *)resbuf);
1187 } else
Thomas Hellerd4c93202006-03-08 19:35:11 +00001188#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001189 retval = GetResult(restype, resbuf, checker);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001190 cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001191 for (i = 0; i < argcount; ++i)
1192 Py_XDECREF(args[i].keep);
1193 return retval;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001194}
1195
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001196static int
1197_parse_voidp(PyObject *obj, void **address)
1198{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001199 *address = PyLong_AsVoidPtr(obj);
1200 if (*address == NULL)
1201 return 0;
1202 return 1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001203}
1204
Thomas Hellerd4c93202006-03-08 19:35:11 +00001205#ifdef MS_WIN32
1206
Thomas Hellerd4c93202006-03-08 19:35:11 +00001207static char format_error_doc[] =
1208"FormatError([integer]) -> string\n\
1209\n\
1210Convert a win32 error code into a string. If the error code is not\n\
1211given, the return value of a call to GetLastError() is used.\n";
1212static PyObject *format_error(PyObject *self, PyObject *args)
1213{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001214 PyObject *result;
1215 wchar_t *lpMsgBuf;
1216 DWORD code = 0;
1217 if (!PyArg_ParseTuple(args, "|i:FormatError", &code))
1218 return NULL;
1219 if (code == 0)
1220 code = GetLastError();
1221 lpMsgBuf = FormatError(code);
1222 if (lpMsgBuf) {
1223 result = PyUnicode_FromWideChar(lpMsgBuf, wcslen(lpMsgBuf));
1224 LocalFree(lpMsgBuf);
1225 } else {
1226 result = PyUnicode_FromString("<no description>");
1227 }
1228 return result;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001229}
1230
1231static char load_library_doc[] =
1232"LoadLibrary(name) -> handle\n\
1233\n\
1234Load an executable (usually a DLL), and return a handle to it.\n\
1235The handle may be used to locate exported functions in this\n\
1236module.\n";
1237static PyObject *load_library(PyObject *self, PyObject *args)
1238{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001239 WCHAR *name;
1240 PyObject *nameobj;
1241 PyObject *ignored;
1242 HMODULE hMod;
1243 if (!PyArg_ParseTuple(args, "O|O:LoadLibrary", &nameobj, &ignored))
1244 return NULL;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001245
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001246 name = PyUnicode_AsUnicode(nameobj);
1247 if (!name)
1248 return NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001250 hMod = LoadLibraryW(name);
1251 if (!hMod)
1252 return PyErr_SetFromWindowsErr(GetLastError());
Thomas Wouters89f507f2006-12-13 04:49:30 +00001253#ifdef _WIN64
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001254 return PyLong_FromVoidPtr(hMod);
Thomas Wouters89f507f2006-12-13 04:49:30 +00001255#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001256 return Py_BuildValue("i", hMod);
Thomas Wouters89f507f2006-12-13 04:49:30 +00001257#endif
Thomas Hellerd4c93202006-03-08 19:35:11 +00001258}
1259
1260static char free_library_doc[] =
1261"FreeLibrary(handle) -> void\n\
1262\n\
1263Free the handle of an executable previously loaded by LoadLibrary.\n";
1264static PyObject *free_library(PyObject *self, PyObject *args)
1265{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001266 void *hMod;
1267 if (!PyArg_ParseTuple(args, "O&:FreeLibrary", &_parse_voidp, &hMod))
1268 return NULL;
1269 if (!FreeLibrary((HMODULE)hMod))
1270 return PyErr_SetFromWindowsErr(GetLastError());
1271 Py_INCREF(Py_None);
1272 return Py_None;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001273}
1274
1275/* obsolete, should be removed */
1276/* Only used by sample code (in samples\Windows\COM.py) */
1277static PyObject *
1278call_commethod(PyObject *self, PyObject *args)
1279{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001280 IUnknown *pIunk;
1281 int index;
1282 PyObject *arguments;
1283 PPROC *lpVtbl;
1284 PyObject *result;
1285 CDataObject *pcom;
1286 PyObject *argtypes = NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001288 if (!PyArg_ParseTuple(args,
1289 "OiO!|O!",
1290 &pcom, &index,
1291 &PyTuple_Type, &arguments,
1292 &PyTuple_Type, &argtypes))
1293 return NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001295 if (argtypes && (PyTuple_GET_SIZE(arguments) != PyTuple_GET_SIZE(argtypes))) {
1296 PyErr_Format(PyExc_TypeError,
1297 "Method takes %d arguments (%d given)",
1298 PyTuple_GET_SIZE(argtypes), PyTuple_GET_SIZE(arguments));
1299 return NULL;
1300 }
Thomas Hellerd4c93202006-03-08 19:35:11 +00001301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001302 if (!CDataObject_Check(pcom) || (pcom->b_size != sizeof(void *))) {
1303 PyErr_Format(PyExc_TypeError,
1304 "COM Pointer expected instead of %s instance",
1305 Py_TYPE(pcom)->tp_name);
1306 return NULL;
1307 }
Thomas Hellerd4c93202006-03-08 19:35:11 +00001308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001309 if ((*(void **)(pcom->b_ptr)) == NULL) {
1310 PyErr_SetString(PyExc_ValueError,
1311 "The COM 'this' pointer is NULL");
1312 return NULL;
1313 }
Thomas Hellerd4c93202006-03-08 19:35:11 +00001314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001315 pIunk = (IUnknown *)(*(void **)(pcom->b_ptr));
1316 lpVtbl = (PPROC *)(pIunk->lpVtbl);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001318 result = _ctypes_callproc(lpVtbl[index],
1319 arguments,
Thomas Hellerd4c93202006-03-08 19:35:11 +00001320#ifdef MS_WIN32
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001321 pIunk,
1322 NULL,
Thomas Hellerd4c93202006-03-08 19:35:11 +00001323#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001324 FUNCFLAG_HRESULT, /* flags */
1325 argtypes, /* self->argtypes */
1326 NULL, /* self->restype */
1327 NULL); /* checker */
1328 return result;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001329}
1330
1331static char copy_com_pointer_doc[] =
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001332"CopyComPointer(src, dst) -> HRESULT value\n";
Thomas Hellerd4c93202006-03-08 19:35:11 +00001333
1334static PyObject *
1335copy_com_pointer(PyObject *self, PyObject *args)
1336{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001337 PyObject *p1, *p2, *r = NULL;
1338 struct argument a, b;
1339 IUnknown *src, **pdst;
1340 if (!PyArg_ParseTuple(args, "OO:CopyComPointer", &p1, &p2))
1341 return NULL;
1342 a.keep = b.keep = NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001344 if (-1 == ConvParam(p1, 0, &a) || -1 == ConvParam(p2, 1, &b))
1345 goto done;
1346 src = (IUnknown *)a.value.p;
1347 pdst = (IUnknown **)b.value.p;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001349 if (pdst == NULL)
1350 r = PyLong_FromLong(E_POINTER);
1351 else {
1352 if (src)
1353 src->lpVtbl->AddRef(src);
1354 *pdst = src;
1355 r = PyLong_FromLong(S_OK);
1356 }
Thomas Hellerd4c93202006-03-08 19:35:11 +00001357 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001358 Py_XDECREF(a.keep);
1359 Py_XDECREF(b.keep);
1360 return r;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001361}
1362#else
1363
1364static PyObject *py_dl_open(PyObject *self, PyObject *args)
1365{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001366 PyObject *name, *name2;
1367 char *name_str;
1368 void * handle;
1369#ifdef RTLD_LOCAL
1370 int mode = RTLD_NOW | RTLD_LOCAL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001371#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001372 /* cygwin doesn't define RTLD_LOCAL */
1373 int mode = RTLD_NOW;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001374#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001375 if (!PyArg_ParseTuple(args, "O|i:dlopen", &name, &mode))
1376 return NULL;
1377 mode |= RTLD_NOW;
1378 if (name != Py_None) {
1379 if (PyUnicode_FSConverter(name, &name2) == 0)
1380 return NULL;
1381 if (PyBytes_Check(name2))
1382 name_str = PyBytes_AS_STRING(name2);
1383 else
1384 name_str = PyByteArray_AS_STRING(name2);
1385 } else {
1386 name_str = NULL;
1387 name2 = NULL;
1388 }
1389 handle = ctypes_dlopen(name_str, mode);
1390 Py_XDECREF(name2);
1391 if (!handle) {
1392 char *errmsg = ctypes_dlerror();
1393 if (!errmsg)
1394 errmsg = "dlopen() error";
1395 PyErr_SetString(PyExc_OSError,
1396 errmsg);
1397 return NULL;
1398 }
1399 return PyLong_FromVoidPtr(handle);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001400}
1401
1402static PyObject *py_dl_close(PyObject *self, PyObject *args)
1403{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001404 void *handle;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001405
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001406 if (!PyArg_ParseTuple(args, "O&:dlclose", &_parse_voidp, &handle))
1407 return NULL;
1408 if (dlclose(handle)) {
1409 PyErr_SetString(PyExc_OSError,
1410 ctypes_dlerror());
1411 return NULL;
1412 }
1413 Py_INCREF(Py_None);
1414 return Py_None;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001415}
1416
1417static PyObject *py_dl_sym(PyObject *self, PyObject *args)
1418{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001419 char *name;
1420 void *handle;
1421 void *ptr;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001423 if (!PyArg_ParseTuple(args, "O&s:dlsym",
1424 &_parse_voidp, &handle, &name))
1425 return NULL;
1426 ptr = ctypes_dlsym((void*)handle, name);
1427 if (!ptr) {
1428 PyErr_SetString(PyExc_OSError,
1429 ctypes_dlerror());
1430 return NULL;
1431 }
1432 return PyLong_FromVoidPtr(ptr);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001433}
1434#endif
1435
1436/*
1437 * Only for debugging so far: So that we can call CFunction instances
1438 *
1439 * XXX Needs to accept more arguments: flags, argtypes, restype
1440 */
1441static PyObject *
1442call_function(PyObject *self, PyObject *args)
1443{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001444 void *func;
1445 PyObject *arguments;
1446 PyObject *result;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001448 if (!PyArg_ParseTuple(args,
1449 "O&O!",
1450 &_parse_voidp, &func,
1451 &PyTuple_Type, &arguments))
1452 return NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001454 result = _ctypes_callproc((PPROC)func,
1455 arguments,
Thomas Hellerd4c93202006-03-08 19:35:11 +00001456#ifdef MS_WIN32
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001457 NULL,
1458 NULL,
Thomas Hellerd4c93202006-03-08 19:35:11 +00001459#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001460 0, /* flags */
1461 NULL, /* self->argtypes */
1462 NULL, /* self->restype */
1463 NULL); /* checker */
1464 return result;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001465}
1466
1467/*
1468 * Only for debugging so far: So that we can call CFunction instances
1469 *
1470 * XXX Needs to accept more arguments: flags, argtypes, restype
1471 */
1472static PyObject *
1473call_cdeclfunction(PyObject *self, PyObject *args)
1474{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001475 void *func;
1476 PyObject *arguments;
1477 PyObject *result;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001479 if (!PyArg_ParseTuple(args,
1480 "O&O!",
1481 &_parse_voidp, &func,
1482 &PyTuple_Type, &arguments))
1483 return NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001485 result = _ctypes_callproc((PPROC)func,
1486 arguments,
Thomas Hellerd4c93202006-03-08 19:35:11 +00001487#ifdef MS_WIN32
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001488 NULL,
1489 NULL,
Thomas Hellerd4c93202006-03-08 19:35:11 +00001490#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001491 FUNCFLAG_CDECL, /* flags */
1492 NULL, /* self->argtypes */
1493 NULL, /* self->restype */
1494 NULL); /* checker */
1495 return result;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001496}
1497
1498/*****************************************************************
1499 * functions
1500 */
1501static char sizeof_doc[] =
1502"sizeof(C type) -> integer\n"
1503"sizeof(C instance) -> integer\n"
1504"Return the size in bytes of a C instance";
1505
1506static PyObject *
1507sizeof_func(PyObject *self, PyObject *obj)
1508{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001509 StgDictObject *dict;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001511 dict = PyType_stgdict(obj);
1512 if (dict)
1513 return PyLong_FromSsize_t(dict->size);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001515 if (CDataObject_Check(obj))
1516 return PyLong_FromSsize_t(((CDataObject *)obj)->b_size);
1517 PyErr_SetString(PyExc_TypeError,
1518 "this type has no size");
1519 return NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001520}
1521
1522static char alignment_doc[] =
1523"alignment(C type) -> integer\n"
1524"alignment(C instance) -> integer\n"
1525"Return the alignment requirements of a C instance";
1526
1527static PyObject *
1528align_func(PyObject *self, PyObject *obj)
1529{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001530 StgDictObject *dict;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001532 dict = PyType_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 dict = PyObject_stgdict(obj);
1537 if (dict)
1538 return PyLong_FromSsize_t(dict->align);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001540 PyErr_SetString(PyExc_TypeError,
1541 "no alignment info");
1542 return NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001543}
1544
1545static char byref_doc[] =
Thomas Hellerc5d01262008-06-10 15:08:51 +00001546"byref(C instance[, offset=0]) -> byref-object\n"
Thomas Hellerd4c93202006-03-08 19:35:11 +00001547"Return a pointer lookalike to a C instance, only usable\n"
1548"as function argument";
1549
1550/*
1551 * We must return something which can be converted to a parameter,
1552 * but still has a reference to self.
1553 */
1554static PyObject *
Thomas Hellerc5d01262008-06-10 15:08:51 +00001555byref(PyObject *self, PyObject *args)
Thomas Hellerd4c93202006-03-08 19:35:11 +00001556{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001557 PyCArgObject *parg;
1558 PyObject *obj;
1559 PyObject *pyoffset = NULL;
1560 Py_ssize_t offset = 0;
Thomas Hellerc5d01262008-06-10 15:08:51 +00001561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001562 if (!PyArg_UnpackTuple(args, "byref", 1, 2,
1563 &obj, &pyoffset))
1564 return NULL;
1565 if (pyoffset) {
1566 offset = PyNumber_AsSsize_t(pyoffset, NULL);
1567 if (offset == -1 && PyErr_Occurred())
1568 return NULL;
1569 }
1570 if (!CDataObject_Check(obj)) {
1571 PyErr_Format(PyExc_TypeError,
1572 "byref() argument must be a ctypes instance, not '%s'",
1573 Py_TYPE(obj)->tp_name);
1574 return NULL;
1575 }
Thomas Hellerd4c93202006-03-08 19:35:11 +00001576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001577 parg = PyCArgObject_new();
1578 if (parg == NULL)
1579 return NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001581 parg->tag = 'P';
1582 parg->pffi_type = &ffi_type_pointer;
1583 Py_INCREF(obj);
1584 parg->obj = obj;
1585 parg->value.p = (char *)((CDataObject *)obj)->b_ptr + offset;
1586 return (PyObject *)parg;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001587}
1588
1589static char addressof_doc[] =
1590"addressof(C instance) -> integer\n"
1591"Return the address of the C instance internal buffer";
1592
1593static PyObject *
1594addressof(PyObject *self, PyObject *obj)
1595{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001596 if (CDataObject_Check(obj))
1597 return PyLong_FromVoidPtr(((CDataObject *)obj)->b_ptr);
1598 PyErr_SetString(PyExc_TypeError,
1599 "invalid type");
1600 return NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001601}
1602
1603static int
1604converter(PyObject *obj, void **address)
1605{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001606 *address = PyLong_AsVoidPtr(obj);
1607 return *address != NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001608}
1609
1610static PyObject *
1611My_PyObj_FromPtr(PyObject *self, PyObject *args)
1612{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001613 PyObject *ob;
1614 if (!PyArg_ParseTuple(args, "O&:PyObj_FromPtr", converter, &ob))
1615 return NULL;
1616 Py_INCREF(ob);
1617 return ob;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001618}
1619
1620static PyObject *
1621My_Py_INCREF(PyObject *self, PyObject *arg)
1622{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001623 Py_INCREF(arg); /* that's what this function is for */
1624 Py_INCREF(arg); /* that for returning it */
1625 return arg;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001626}
1627
1628static PyObject *
1629My_Py_DECREF(PyObject *self, PyObject *arg)
1630{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001631 Py_DECREF(arg); /* that's what this function is for */
1632 Py_INCREF(arg); /* that's for returning it */
1633 return arg;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001634}
1635
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001636static PyObject *
1637resize(PyObject *self, PyObject *args)
1638{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001639 CDataObject *obj;
1640 StgDictObject *dict;
1641 Py_ssize_t size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001643 if (!PyArg_ParseTuple(args,
1644 "On:resize",
1645 &obj, &size))
1646 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001647
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001648 dict = PyObject_stgdict((PyObject *)obj);
1649 if (dict == NULL) {
1650 PyErr_SetString(PyExc_TypeError,
1651 "excepted ctypes instance");
1652 return NULL;
1653 }
1654 if (size < dict->size) {
1655 PyErr_Format(PyExc_ValueError,
1656 "minimum size is %zd",
1657 dict->size);
1658 return NULL;
1659 }
1660 if (obj->b_needsfree == 0) {
1661 PyErr_Format(PyExc_ValueError,
1662 "Memory cannot be resized because this object doesn't own it");
1663 return NULL;
1664 }
1665 if (size <= sizeof(obj->b_value)) {
1666 /* internal default buffer is large enough */
1667 obj->b_size = size;
1668 goto done;
1669 }
Antoine Pitrou305e1a72012-12-08 11:05:50 +01001670 if (!_CDataObject_HasExternalBuffer(obj)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001671 /* We are currently using the objects default buffer, but it
1672 isn't large enough any more. */
1673 void *ptr = PyMem_Malloc(size);
1674 if (ptr == NULL)
1675 return PyErr_NoMemory();
1676 memset(ptr, 0, size);
1677 memmove(ptr, obj->b_ptr, obj->b_size);
1678 obj->b_ptr = ptr;
1679 obj->b_size = size;
1680 } else {
1681 void * ptr = PyMem_Realloc(obj->b_ptr, size);
1682 if (ptr == NULL)
1683 return PyErr_NoMemory();
1684 obj->b_ptr = ptr;
1685 obj->b_size = size;
1686 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001687 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001688 Py_INCREF(Py_None);
1689 return Py_None;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001690}
1691
Thomas Heller13394e92008-02-13 20:40:44 +00001692static PyObject *
1693unpickle(PyObject *self, PyObject *args)
1694{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001695 PyObject *typ;
1696 PyObject *state;
1697 PyObject *result;
1698 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001699 _Py_IDENTIFIER(__new__);
1700 _Py_IDENTIFIER(__setstate__);
Thomas Heller13394e92008-02-13 20:40:44 +00001701
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001702 if (!PyArg_ParseTuple(args, "OO", &typ, &state))
1703 return NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001704 result = _PyObject_CallMethodId(typ, &PyId___new__, "O", typ);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001705 if (result == NULL)
1706 return NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001707 tmp = _PyObject_CallMethodId(result, &PyId___setstate__, "O", state);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001708 if (tmp == NULL) {
1709 Py_DECREF(result);
1710 return NULL;
1711 }
1712 Py_DECREF(tmp);
1713 return result;
Thomas Heller13394e92008-02-13 20:40:44 +00001714}
1715
Thomas Heller3071f812008-04-14 16:17:33 +00001716static PyObject *
1717POINTER(PyObject *self, PyObject *cls)
1718{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001719 PyObject *result;
1720 PyTypeObject *typ;
1721 PyObject *key;
1722 char *buf;
Thomas Heller3071f812008-04-14 16:17:33 +00001723
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001724 result = PyDict_GetItem(_ctypes_ptrtype_cache, cls);
1725 if (result) {
1726 Py_INCREF(result);
1727 return result;
1728 }
1729 if (PyUnicode_CheckExact(cls)) {
1730 char *name = _PyUnicode_AsString(cls);
1731 buf = alloca(strlen(name) + 3 + 1);
1732 sprintf(buf, "LP_%s", name);
1733 result = PyObject_CallFunction((PyObject *)Py_TYPE(&PyCPointer_Type),
1734 "s(O){}",
1735 buf,
1736 &PyCPointer_Type);
1737 if (result == NULL)
1738 return result;
1739 key = PyLong_FromVoidPtr(result);
1740 } else if (PyType_Check(cls)) {
1741 typ = (PyTypeObject *)cls;
1742 buf = alloca(strlen(typ->tp_name) + 3 + 1);
1743 sprintf(buf, "LP_%s", typ->tp_name);
1744 result = PyObject_CallFunction((PyObject *)Py_TYPE(&PyCPointer_Type),
1745 "s(O){sO}",
1746 buf,
1747 &PyCPointer_Type,
1748 "_type_", cls);
1749 if (result == NULL)
1750 return result;
1751 Py_INCREF(cls);
1752 key = cls;
1753 } else {
1754 PyErr_SetString(PyExc_TypeError, "must be a ctypes type");
1755 return NULL;
1756 }
1757 if (-1 == PyDict_SetItem(_ctypes_ptrtype_cache, key, result)) {
1758 Py_DECREF(result);
1759 Py_DECREF(key);
1760 return NULL;
1761 }
1762 Py_DECREF(key);
1763 return result;
Thomas Heller3071f812008-04-14 16:17:33 +00001764}
1765
1766static PyObject *
1767pointer(PyObject *self, PyObject *arg)
1768{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001769 PyObject *result;
1770 PyObject *typ;
Thomas Heller3071f812008-04-14 16:17:33 +00001771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001772 typ = PyDict_GetItem(_ctypes_ptrtype_cache, (PyObject *)Py_TYPE(arg));
1773 if (typ)
1774 return PyObject_CallFunctionObjArgs(typ, arg, NULL);
1775 typ = POINTER(NULL, (PyObject *)Py_TYPE(arg));
1776 if (typ == NULL)
1777 return NULL;
1778 result = PyObject_CallFunctionObjArgs(typ, arg, NULL);
1779 Py_DECREF(typ);
1780 return result;
Thomas Heller3071f812008-04-14 16:17:33 +00001781}
1782
Thomas Hellerb041fda2008-04-30 17:11:46 +00001783static PyObject *
1784buffer_info(PyObject *self, PyObject *arg)
1785{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001786 StgDictObject *dict = PyType_stgdict(arg);
1787 PyObject *shape;
1788 Py_ssize_t i;
Thomas Hellerb041fda2008-04-30 17:11:46 +00001789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001790 if (dict == NULL)
1791 dict = PyObject_stgdict(arg);
1792 if (dict == NULL) {
1793 PyErr_SetString(PyExc_TypeError,
1794 "not a ctypes type or object");
1795 return NULL;
1796 }
1797 shape = PyTuple_New(dict->ndim);
1798 if (shape == NULL)
1799 return NULL;
1800 for (i = 0; i < (int)dict->ndim; ++i)
1801 PyTuple_SET_ITEM(shape, i, PyLong_FromSsize_t(dict->shape[i]));
Thomas Hellerb041fda2008-04-30 17:11:46 +00001802
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001803 if (PyErr_Occurred()) {
1804 Py_DECREF(shape);
1805 return NULL;
1806 }
1807 return Py_BuildValue("siN", dict->format, dict->ndim, shape);
Thomas Hellerb041fda2008-04-30 17:11:46 +00001808}
1809
Thomas Heller34596a92009-04-24 20:50:00 +00001810PyMethodDef _ctypes_module_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001811 {"get_errno", get_errno, METH_NOARGS},
1812 {"set_errno", set_errno, METH_VARARGS},
1813 {"POINTER", POINTER, METH_O },
1814 {"pointer", pointer, METH_O },
1815 {"_unpickle", unpickle, METH_VARARGS },
1816 {"buffer_info", buffer_info, METH_O, "Return buffer interface information"},
1817 {"resize", resize, METH_VARARGS, "Resize the memory buffer of a ctypes instance"},
Thomas Hellerd4c93202006-03-08 19:35:11 +00001818#ifdef MS_WIN32
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001819 {"get_last_error", get_last_error, METH_NOARGS},
1820 {"set_last_error", set_last_error, METH_VARARGS},
1821 {"CopyComPointer", copy_com_pointer, METH_VARARGS, copy_com_pointer_doc},
1822 {"FormatError", format_error, METH_VARARGS, format_error_doc},
1823 {"LoadLibrary", load_library, METH_VARARGS, load_library_doc},
1824 {"FreeLibrary", free_library, METH_VARARGS, free_library_doc},
1825 {"call_commethod", call_commethod, METH_VARARGS },
1826 {"_check_HRESULT", check_hresult, METH_VARARGS},
Thomas Hellerd4c93202006-03-08 19:35:11 +00001827#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001828 {"dlopen", py_dl_open, METH_VARARGS,
1829 "dlopen(name, flag={RTLD_GLOBAL|RTLD_LOCAL}) open a shared library"},
1830 {"dlclose", py_dl_close, METH_VARARGS, "dlclose a library"},
1831 {"dlsym", py_dl_sym, METH_VARARGS, "find symbol in shared library"},
Thomas Hellerd4c93202006-03-08 19:35:11 +00001832#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001833 {"alignment", align_func, METH_O, alignment_doc},
1834 {"sizeof", sizeof_func, METH_O, sizeof_doc},
1835 {"byref", byref, METH_VARARGS, byref_doc},
1836 {"addressof", addressof, METH_O, addressof_doc},
1837 {"call_function", call_function, METH_VARARGS },
1838 {"call_cdeclfunction", call_cdeclfunction, METH_VARARGS },
1839 {"PyObj_FromPtr", My_PyObj_FromPtr, METH_VARARGS },
1840 {"Py_INCREF", My_Py_INCREF, METH_O },
1841 {"Py_DECREF", My_Py_DECREF, METH_O },
1842 {NULL, NULL} /* Sentinel */
Thomas Hellerd4c93202006-03-08 19:35:11 +00001843};
1844
1845/*
1846 Local Variables:
1847 compile-command: "cd .. && python setup.py -q build -g && python setup.py -q build install --home ~"
1848 End:
1849*/