blob: d9857833b427c1b0be804b5c6049f9742f21c1a2 [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)
Andrew Svetlov2606a6f2012-12-19 14:33:35 +0200260 PyErr_Format(PyExc_OSError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000261 "exception: access violation reading %p",
262 pr->ExceptionInformation[1]);
263 else
Andrew Svetlov2606a6f2012-12-19 14:33:35 +0200264 PyErr_Format(PyExc_OSError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000265 "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. */
Andrew Svetlov2606a6f2012-12-19 14:33:35 +0200271 PyErr_SetString(PyExc_OSError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000272 "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. */
Andrew Svetlov2606a6f2012-12-19 14:33:35 +0200281 PyErr_SetString(PyExc_OSError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000282 "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. */
Andrew Svetlov2606a6f2012-12-19 14:33:35 +0200288 PyErr_SetString(PyExc_OSError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000289 "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. */
Andrew Svetlov2606a6f2012-12-19 14:33:35 +0200296 PyErr_SetString(PyExc_OSError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000297 "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. */
Andrew Svetlov2606a6f2012-12-19 14:33:35 +0200305 PyErr_SetString(PyExc_OSError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000306 "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. */
Andrew Svetlov2606a6f2012-12-19 14:33:35 +0200312 PyErr_SetString(PyExc_OSError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000313 "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. */
Andrew Svetlov2606a6f2012-12-19 14:33:35 +0200319 PyErr_SetString(PyExc_OSError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000320 "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. */
Andrew Svetlov2606a6f2012-12-19 14:33:35 +0200326 PyErr_SetString(PyExc_OSError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000327 "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. */
Andrew Svetlov2606a6f2012-12-19 14:33:35 +0200334 PyErr_SetString(PyExc_OSError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000335 "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. */
Andrew Svetlov2606a6f2012-12-19 14:33:35 +0200341 PyErr_SetString(PyExc_OSError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000342 "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. */
Andrew Svetlov2606a6f2012-12-19 14:33:35 +0200348 PyErr_SetString(PyExc_OSError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000349 "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. */
Andrew Svetlov2606a6f2012-12-19 14:33:35 +0200356 PyErr_SetString(PyExc_OSError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000357 "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. */
Andrew Svetlov2606a6f2012-12-19 14:33:35 +0200363 PyErr_SetString(PyExc_OSError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000364 "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. */
Andrew Svetlov2606a6f2012-12-19 14:33:35 +0200370 PyErr_SetString(PyExc_OSError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000371 "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. */
Andrew Svetlov2606a6f2012-12-19 14:33:35 +0200378 PyErr_SetString(PyExc_OSError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000379 "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. */
Andrew Svetlov2606a6f2012-12-19 14:33:35 +0200385 PyErr_SetString(PyExc_OSError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000386 "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];
Eli Benderskyca832332013-03-06 06:30:23 -08001086 } 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);
Eli Benderskyd867bad2013-03-06 05:45:57 -08001104 v = PyObject_CallFunctionObjArgs(converter, arg, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001105 if (v == NULL) {
1106 _ctypes_extend_error(PyExc_ArgError, "argument %d: ", i+1);
1107 goto cleanup;
1108 }
Thomas Hellerd4c93202006-03-08 19:35:11 +00001109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001110 err = ConvParam(v, i+1, pa);
1111 Py_DECREF(v);
1112 if (-1 == err) {
1113 _ctypes_extend_error(PyExc_ArgError, "argument %d: ", i+1);
1114 goto cleanup;
1115 }
1116 } else {
1117 err = ConvParam(arg, i+1, pa);
1118 if (-1 == err) {
1119 _ctypes_extend_error(PyExc_ArgError, "argument %d: ", i+1);
1120 goto cleanup; /* leaking ? */
1121 }
1122 }
1123 }
Thomas Hellerd4c93202006-03-08 19:35:11 +00001124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001125 rtype = _ctypes_get_ffi_type(restype);
1126 resbuf = alloca(max(rtype->size, sizeof(ffi_arg)));
Thomas Hellerd4c93202006-03-08 19:35:11 +00001127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001128 avalues = (void **)alloca(sizeof(void *) * argcount);
1129 atypes = (ffi_type **)alloca(sizeof(ffi_type *) * argcount);
1130 if (!resbuf || !avalues || !atypes) {
1131 PyErr_NoMemory();
1132 goto cleanup;
1133 }
1134 for (i = 0; i < argcount; ++i) {
1135 atypes[i] = args[i].ffi_type;
Victor Stinner4c2e4fa2010-09-29 10:37:16 +00001136 if (atypes[i]->type == FFI_TYPE_STRUCT
Thomas Hellerb00697e2010-06-21 16:00:31 +00001137#ifdef _WIN64
1138 && atypes[i]->size <= sizeof(void *)
1139#endif
1140 )
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001141 avalues[i] = (void *)args[i].value.p;
1142 else
1143 avalues[i] = (void *)&args[i].value;
1144 }
Thomas Hellerd4c93202006-03-08 19:35:11 +00001145
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001146 if (-1 == _call_function_pointer(flags, pProc, avalues, atypes,
1147 rtype, resbuf,
1148 Py_SAFE_DOWNCAST(argcount,
1149 Py_ssize_t,
1150 int)))
1151 goto cleanup;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001152
1153#ifdef WORDS_BIGENDIAN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001154 /* libffi returns the result in a buffer with sizeof(ffi_arg). This
1155 causes problems on big endian machines, since the result buffer
1156 address cannot simply be used as result pointer, instead we must
1157 adjust the pointer value:
1158 */
1159 /*
1160 XXX I should find out and clarify why this is needed at all,
1161 especially why adjusting for ffi_type_float must be avoided on
1162 64-bit platforms.
1163 */
1164 if (rtype->type != FFI_TYPE_FLOAT
1165 && rtype->type != FFI_TYPE_STRUCT
1166 && rtype->size < sizeof(ffi_arg))
1167 resbuf = (char *)resbuf + sizeof(ffi_arg) - rtype->size;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001168#endif
1169
1170#ifdef MS_WIN32
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001171 if (iid && pIunk) {
1172 if (*(int *)resbuf & 0x80000000)
1173 retval = GetComError(*(HRESULT *)resbuf, iid, pIunk);
1174 else
1175 retval = PyLong_FromLong(*(int *)resbuf);
1176 } else if (flags & FUNCFLAG_HRESULT) {
1177 if (*(int *)resbuf & 0x80000000)
1178 retval = PyErr_SetFromWindowsErr(*(int *)resbuf);
1179 else
1180 retval = PyLong_FromLong(*(int *)resbuf);
Eli Benderskyca832332013-03-06 06:30:23 -08001181 } else
Thomas Hellerd4c93202006-03-08 19:35:11 +00001182#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 retval = GetResult(restype, resbuf, checker);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001184 cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001185 for (i = 0; i < argcount; ++i)
1186 Py_XDECREF(args[i].keep);
1187 return retval;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001188}
1189
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001190static int
1191_parse_voidp(PyObject *obj, void **address)
1192{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001193 *address = PyLong_AsVoidPtr(obj);
1194 if (*address == NULL)
1195 return 0;
1196 return 1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001197}
1198
Thomas Hellerd4c93202006-03-08 19:35:11 +00001199#ifdef MS_WIN32
1200
Thomas Hellerd4c93202006-03-08 19:35:11 +00001201static char format_error_doc[] =
1202"FormatError([integer]) -> string\n\
1203\n\
1204Convert a win32 error code into a string. If the error code is not\n\
1205given, the return value of a call to GetLastError() is used.\n";
1206static PyObject *format_error(PyObject *self, PyObject *args)
1207{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001208 PyObject *result;
1209 wchar_t *lpMsgBuf;
1210 DWORD code = 0;
1211 if (!PyArg_ParseTuple(args, "|i:FormatError", &code))
1212 return NULL;
1213 if (code == 0)
1214 code = GetLastError();
1215 lpMsgBuf = FormatError(code);
1216 if (lpMsgBuf) {
1217 result = PyUnicode_FromWideChar(lpMsgBuf, wcslen(lpMsgBuf));
1218 LocalFree(lpMsgBuf);
1219 } else {
1220 result = PyUnicode_FromString("<no description>");
1221 }
1222 return result;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001223}
1224
1225static char load_library_doc[] =
1226"LoadLibrary(name) -> handle\n\
1227\n\
1228Load an executable (usually a DLL), and return a handle to it.\n\
1229The handle may be used to locate exported functions in this\n\
1230module.\n";
1231static PyObject *load_library(PyObject *self, PyObject *args)
1232{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001233 WCHAR *name;
1234 PyObject *nameobj;
1235 PyObject *ignored;
1236 HMODULE hMod;
1237 if (!PyArg_ParseTuple(args, "O|O:LoadLibrary", &nameobj, &ignored))
1238 return NULL;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001240 name = PyUnicode_AsUnicode(nameobj);
1241 if (!name)
1242 return NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001244 hMod = LoadLibraryW(name);
1245 if (!hMod)
1246 return PyErr_SetFromWindowsErr(GetLastError());
Thomas Wouters89f507f2006-12-13 04:49:30 +00001247#ifdef _WIN64
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001248 return PyLong_FromVoidPtr(hMod);
Thomas Wouters89f507f2006-12-13 04:49:30 +00001249#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001250 return Py_BuildValue("i", hMod);
Thomas Wouters89f507f2006-12-13 04:49:30 +00001251#endif
Thomas Hellerd4c93202006-03-08 19:35:11 +00001252}
1253
1254static char free_library_doc[] =
1255"FreeLibrary(handle) -> void\n\
1256\n\
1257Free the handle of an executable previously loaded by LoadLibrary.\n";
1258static PyObject *free_library(PyObject *self, PyObject *args)
1259{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001260 void *hMod;
1261 if (!PyArg_ParseTuple(args, "O&:FreeLibrary", &_parse_voidp, &hMod))
1262 return NULL;
1263 if (!FreeLibrary((HMODULE)hMod))
1264 return PyErr_SetFromWindowsErr(GetLastError());
1265 Py_INCREF(Py_None);
1266 return Py_None;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001267}
1268
Thomas Hellerd4c93202006-03-08 19:35:11 +00001269static char copy_com_pointer_doc[] =
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001270"CopyComPointer(src, dst) -> HRESULT value\n";
Thomas Hellerd4c93202006-03-08 19:35:11 +00001271
1272static PyObject *
1273copy_com_pointer(PyObject *self, PyObject *args)
1274{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001275 PyObject *p1, *p2, *r = NULL;
1276 struct argument a, b;
1277 IUnknown *src, **pdst;
1278 if (!PyArg_ParseTuple(args, "OO:CopyComPointer", &p1, &p2))
1279 return NULL;
1280 a.keep = b.keep = NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001282 if (-1 == ConvParam(p1, 0, &a) || -1 == ConvParam(p2, 1, &b))
1283 goto done;
1284 src = (IUnknown *)a.value.p;
1285 pdst = (IUnknown **)b.value.p;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001287 if (pdst == NULL)
1288 r = PyLong_FromLong(E_POINTER);
1289 else {
1290 if (src)
1291 src->lpVtbl->AddRef(src);
1292 *pdst = src;
1293 r = PyLong_FromLong(S_OK);
1294 }
Thomas Hellerd4c93202006-03-08 19:35:11 +00001295 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001296 Py_XDECREF(a.keep);
1297 Py_XDECREF(b.keep);
1298 return r;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001299}
1300#else
1301
1302static PyObject *py_dl_open(PyObject *self, PyObject *args)
1303{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001304 PyObject *name, *name2;
1305 char *name_str;
1306 void * handle;
1307#ifdef RTLD_LOCAL
1308 int mode = RTLD_NOW | RTLD_LOCAL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001309#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001310 /* cygwin doesn't define RTLD_LOCAL */
1311 int mode = RTLD_NOW;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001312#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001313 if (!PyArg_ParseTuple(args, "O|i:dlopen", &name, &mode))
1314 return NULL;
1315 mode |= RTLD_NOW;
1316 if (name != Py_None) {
1317 if (PyUnicode_FSConverter(name, &name2) == 0)
1318 return NULL;
1319 if (PyBytes_Check(name2))
1320 name_str = PyBytes_AS_STRING(name2);
1321 else
1322 name_str = PyByteArray_AS_STRING(name2);
1323 } else {
1324 name_str = NULL;
1325 name2 = NULL;
1326 }
1327 handle = ctypes_dlopen(name_str, mode);
1328 Py_XDECREF(name2);
1329 if (!handle) {
1330 char *errmsg = ctypes_dlerror();
1331 if (!errmsg)
1332 errmsg = "dlopen() error";
1333 PyErr_SetString(PyExc_OSError,
1334 errmsg);
1335 return NULL;
1336 }
1337 return PyLong_FromVoidPtr(handle);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001338}
1339
1340static PyObject *py_dl_close(PyObject *self, PyObject *args)
1341{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001342 void *handle;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001344 if (!PyArg_ParseTuple(args, "O&:dlclose", &_parse_voidp, &handle))
1345 return NULL;
1346 if (dlclose(handle)) {
1347 PyErr_SetString(PyExc_OSError,
1348 ctypes_dlerror());
1349 return NULL;
1350 }
1351 Py_INCREF(Py_None);
1352 return Py_None;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001353}
1354
1355static PyObject *py_dl_sym(PyObject *self, PyObject *args)
1356{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001357 char *name;
1358 void *handle;
1359 void *ptr;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001360
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001361 if (!PyArg_ParseTuple(args, "O&s:dlsym",
1362 &_parse_voidp, &handle, &name))
1363 return NULL;
1364 ptr = ctypes_dlsym((void*)handle, name);
1365 if (!ptr) {
1366 PyErr_SetString(PyExc_OSError,
1367 ctypes_dlerror());
1368 return NULL;
1369 }
1370 return PyLong_FromVoidPtr(ptr);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001371}
1372#endif
1373
1374/*
1375 * Only for debugging so far: So that we can call CFunction instances
1376 *
1377 * XXX Needs to accept more arguments: flags, argtypes, restype
1378 */
1379static PyObject *
1380call_function(PyObject *self, PyObject *args)
1381{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001382 void *func;
1383 PyObject *arguments;
1384 PyObject *result;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001386 if (!PyArg_ParseTuple(args,
1387 "O&O!",
1388 &_parse_voidp, &func,
1389 &PyTuple_Type, &arguments))
1390 return NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001392 result = _ctypes_callproc((PPROC)func,
1393 arguments,
Thomas Hellerd4c93202006-03-08 19:35:11 +00001394#ifdef MS_WIN32
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001395 NULL,
1396 NULL,
Thomas Hellerd4c93202006-03-08 19:35:11 +00001397#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001398 0, /* flags */
1399 NULL, /* self->argtypes */
1400 NULL, /* self->restype */
1401 NULL); /* checker */
1402 return result;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001403}
1404
1405/*
1406 * Only for debugging so far: So that we can call CFunction instances
1407 *
1408 * XXX Needs to accept more arguments: flags, argtypes, restype
1409 */
1410static PyObject *
1411call_cdeclfunction(PyObject *self, PyObject *args)
1412{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001413 void *func;
1414 PyObject *arguments;
1415 PyObject *result;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001417 if (!PyArg_ParseTuple(args,
1418 "O&O!",
1419 &_parse_voidp, &func,
1420 &PyTuple_Type, &arguments))
1421 return NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001423 result = _ctypes_callproc((PPROC)func,
1424 arguments,
Thomas Hellerd4c93202006-03-08 19:35:11 +00001425#ifdef MS_WIN32
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001426 NULL,
1427 NULL,
Thomas Hellerd4c93202006-03-08 19:35:11 +00001428#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001429 FUNCFLAG_CDECL, /* flags */
Eli Benderskyd867bad2013-03-06 05:45:57 -08001430 NULL, /* self->argtypes */
1431 NULL, /* self->restype */
1432 NULL); /* checker */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001433 return result;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001434}
1435
1436/*****************************************************************
1437 * functions
1438 */
1439static char sizeof_doc[] =
1440"sizeof(C type) -> integer\n"
1441"sizeof(C instance) -> integer\n"
1442"Return the size in bytes of a C instance";
1443
1444static PyObject *
1445sizeof_func(PyObject *self, PyObject *obj)
1446{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001447 StgDictObject *dict;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001449 dict = PyType_stgdict(obj);
1450 if (dict)
1451 return PyLong_FromSsize_t(dict->size);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001453 if (CDataObject_Check(obj))
1454 return PyLong_FromSsize_t(((CDataObject *)obj)->b_size);
1455 PyErr_SetString(PyExc_TypeError,
1456 "this type has no size");
1457 return NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001458}
1459
1460static char alignment_doc[] =
1461"alignment(C type) -> integer\n"
1462"alignment(C instance) -> integer\n"
1463"Return the alignment requirements of a C instance";
1464
1465static PyObject *
1466align_func(PyObject *self, PyObject *obj)
1467{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001468 StgDictObject *dict;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001470 dict = PyType_stgdict(obj);
1471 if (dict)
1472 return PyLong_FromSsize_t(dict->align);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001474 dict = PyObject_stgdict(obj);
1475 if (dict)
1476 return PyLong_FromSsize_t(dict->align);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001478 PyErr_SetString(PyExc_TypeError,
1479 "no alignment info");
1480 return NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001481}
1482
1483static char byref_doc[] =
Thomas Hellerc5d01262008-06-10 15:08:51 +00001484"byref(C instance[, offset=0]) -> byref-object\n"
Thomas Hellerd4c93202006-03-08 19:35:11 +00001485"Return a pointer lookalike to a C instance, only usable\n"
1486"as function argument";
1487
1488/*
1489 * We must return something which can be converted to a parameter,
1490 * but still has a reference to self.
1491 */
1492static PyObject *
Thomas Hellerc5d01262008-06-10 15:08:51 +00001493byref(PyObject *self, PyObject *args)
Thomas Hellerd4c93202006-03-08 19:35:11 +00001494{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001495 PyCArgObject *parg;
1496 PyObject *obj;
1497 PyObject *pyoffset = NULL;
1498 Py_ssize_t offset = 0;
Thomas Hellerc5d01262008-06-10 15:08:51 +00001499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001500 if (!PyArg_UnpackTuple(args, "byref", 1, 2,
1501 &obj, &pyoffset))
1502 return NULL;
1503 if (pyoffset) {
1504 offset = PyNumber_AsSsize_t(pyoffset, NULL);
1505 if (offset == -1 && PyErr_Occurred())
1506 return NULL;
1507 }
1508 if (!CDataObject_Check(obj)) {
1509 PyErr_Format(PyExc_TypeError,
1510 "byref() argument must be a ctypes instance, not '%s'",
1511 Py_TYPE(obj)->tp_name);
1512 return NULL;
1513 }
Thomas Hellerd4c93202006-03-08 19:35:11 +00001514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001515 parg = PyCArgObject_new();
1516 if (parg == NULL)
1517 return NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001519 parg->tag = 'P';
1520 parg->pffi_type = &ffi_type_pointer;
1521 Py_INCREF(obj);
1522 parg->obj = obj;
1523 parg->value.p = (char *)((CDataObject *)obj)->b_ptr + offset;
1524 return (PyObject *)parg;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001525}
1526
1527static char addressof_doc[] =
1528"addressof(C instance) -> integer\n"
1529"Return the address of the C instance internal buffer";
1530
1531static PyObject *
1532addressof(PyObject *self, PyObject *obj)
1533{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001534 if (CDataObject_Check(obj))
1535 return PyLong_FromVoidPtr(((CDataObject *)obj)->b_ptr);
1536 PyErr_SetString(PyExc_TypeError,
1537 "invalid type");
1538 return NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001539}
1540
1541static int
1542converter(PyObject *obj, void **address)
1543{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001544 *address = PyLong_AsVoidPtr(obj);
1545 return *address != NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001546}
1547
1548static PyObject *
1549My_PyObj_FromPtr(PyObject *self, PyObject *args)
1550{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001551 PyObject *ob;
1552 if (!PyArg_ParseTuple(args, "O&:PyObj_FromPtr", converter, &ob))
1553 return NULL;
1554 Py_INCREF(ob);
1555 return ob;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001556}
1557
1558static PyObject *
1559My_Py_INCREF(PyObject *self, PyObject *arg)
1560{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001561 Py_INCREF(arg); /* that's what this function is for */
1562 Py_INCREF(arg); /* that for returning it */
1563 return arg;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001564}
1565
1566static PyObject *
1567My_Py_DECREF(PyObject *self, PyObject *arg)
1568{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001569 Py_DECREF(arg); /* that's what this function is for */
1570 Py_INCREF(arg); /* that's for returning it */
1571 return arg;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001572}
1573
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001574static PyObject *
1575resize(PyObject *self, PyObject *args)
1576{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001577 CDataObject *obj;
1578 StgDictObject *dict;
1579 Py_ssize_t size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001581 if (!PyArg_ParseTuple(args,
1582 "On:resize",
1583 &obj, &size))
1584 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001586 dict = PyObject_stgdict((PyObject *)obj);
1587 if (dict == NULL) {
1588 PyErr_SetString(PyExc_TypeError,
1589 "excepted ctypes instance");
1590 return NULL;
1591 }
1592 if (size < dict->size) {
1593 PyErr_Format(PyExc_ValueError,
1594 "minimum size is %zd",
1595 dict->size);
1596 return NULL;
1597 }
1598 if (obj->b_needsfree == 0) {
1599 PyErr_Format(PyExc_ValueError,
1600 "Memory cannot be resized because this object doesn't own it");
1601 return NULL;
1602 }
1603 if (size <= sizeof(obj->b_value)) {
1604 /* internal default buffer is large enough */
1605 obj->b_size = size;
1606 goto done;
1607 }
Antoine Pitrou305e1a72012-12-08 11:05:50 +01001608 if (!_CDataObject_HasExternalBuffer(obj)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001609 /* We are currently using the objects default buffer, but it
1610 isn't large enough any more. */
1611 void *ptr = PyMem_Malloc(size);
1612 if (ptr == NULL)
1613 return PyErr_NoMemory();
1614 memset(ptr, 0, size);
1615 memmove(ptr, obj->b_ptr, obj->b_size);
1616 obj->b_ptr = ptr;
1617 obj->b_size = size;
1618 } else {
1619 void * ptr = PyMem_Realloc(obj->b_ptr, size);
1620 if (ptr == NULL)
1621 return PyErr_NoMemory();
1622 obj->b_ptr = ptr;
1623 obj->b_size = size;
1624 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001625 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001626 Py_INCREF(Py_None);
1627 return Py_None;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001628}
1629
Thomas Heller13394e92008-02-13 20:40:44 +00001630static PyObject *
1631unpickle(PyObject *self, PyObject *args)
1632{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001633 PyObject *typ;
1634 PyObject *state;
1635 PyObject *result;
1636 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001637 _Py_IDENTIFIER(__new__);
1638 _Py_IDENTIFIER(__setstate__);
Thomas Heller13394e92008-02-13 20:40:44 +00001639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001640 if (!PyArg_ParseTuple(args, "OO", &typ, &state))
1641 return NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001642 result = _PyObject_CallMethodId(typ, &PyId___new__, "O", typ);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001643 if (result == NULL)
1644 return NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001645 tmp = _PyObject_CallMethodId(result, &PyId___setstate__, "O", state);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001646 if (tmp == NULL) {
1647 Py_DECREF(result);
1648 return NULL;
1649 }
1650 Py_DECREF(tmp);
1651 return result;
Thomas Heller13394e92008-02-13 20:40:44 +00001652}
1653
Thomas Heller3071f812008-04-14 16:17:33 +00001654static PyObject *
1655POINTER(PyObject *self, PyObject *cls)
1656{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001657 PyObject *result;
1658 PyTypeObject *typ;
1659 PyObject *key;
1660 char *buf;
Thomas Heller3071f812008-04-14 16:17:33 +00001661
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001662 result = PyDict_GetItem(_ctypes_ptrtype_cache, cls);
1663 if (result) {
1664 Py_INCREF(result);
1665 return result;
1666 }
1667 if (PyUnicode_CheckExact(cls)) {
1668 char *name = _PyUnicode_AsString(cls);
1669 buf = alloca(strlen(name) + 3 + 1);
1670 sprintf(buf, "LP_%s", name);
1671 result = PyObject_CallFunction((PyObject *)Py_TYPE(&PyCPointer_Type),
1672 "s(O){}",
1673 buf,
1674 &PyCPointer_Type);
1675 if (result == NULL)
1676 return result;
1677 key = PyLong_FromVoidPtr(result);
1678 } else if (PyType_Check(cls)) {
1679 typ = (PyTypeObject *)cls;
1680 buf = alloca(strlen(typ->tp_name) + 3 + 1);
1681 sprintf(buf, "LP_%s", typ->tp_name);
1682 result = PyObject_CallFunction((PyObject *)Py_TYPE(&PyCPointer_Type),
1683 "s(O){sO}",
1684 buf,
1685 &PyCPointer_Type,
1686 "_type_", cls);
1687 if (result == NULL)
1688 return result;
1689 Py_INCREF(cls);
1690 key = cls;
1691 } else {
1692 PyErr_SetString(PyExc_TypeError, "must be a ctypes type");
1693 return NULL;
1694 }
1695 if (-1 == PyDict_SetItem(_ctypes_ptrtype_cache, key, result)) {
1696 Py_DECREF(result);
1697 Py_DECREF(key);
1698 return NULL;
1699 }
1700 Py_DECREF(key);
1701 return result;
Thomas Heller3071f812008-04-14 16:17:33 +00001702}
1703
1704static PyObject *
1705pointer(PyObject *self, PyObject *arg)
1706{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001707 PyObject *result;
1708 PyObject *typ;
Thomas Heller3071f812008-04-14 16:17:33 +00001709
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001710 typ = PyDict_GetItem(_ctypes_ptrtype_cache, (PyObject *)Py_TYPE(arg));
1711 if (typ)
1712 return PyObject_CallFunctionObjArgs(typ, arg, NULL);
1713 typ = POINTER(NULL, (PyObject *)Py_TYPE(arg));
1714 if (typ == NULL)
1715 return NULL;
1716 result = PyObject_CallFunctionObjArgs(typ, arg, NULL);
1717 Py_DECREF(typ);
1718 return result;
Thomas Heller3071f812008-04-14 16:17:33 +00001719}
1720
Thomas Hellerb041fda2008-04-30 17:11:46 +00001721static PyObject *
1722buffer_info(PyObject *self, PyObject *arg)
1723{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001724 StgDictObject *dict = PyType_stgdict(arg);
1725 PyObject *shape;
1726 Py_ssize_t i;
Thomas Hellerb041fda2008-04-30 17:11:46 +00001727
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001728 if (dict == NULL)
1729 dict = PyObject_stgdict(arg);
1730 if (dict == NULL) {
1731 PyErr_SetString(PyExc_TypeError,
1732 "not a ctypes type or object");
1733 return NULL;
1734 }
1735 shape = PyTuple_New(dict->ndim);
1736 if (shape == NULL)
1737 return NULL;
1738 for (i = 0; i < (int)dict->ndim; ++i)
1739 PyTuple_SET_ITEM(shape, i, PyLong_FromSsize_t(dict->shape[i]));
Thomas Hellerb041fda2008-04-30 17:11:46 +00001740
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001741 if (PyErr_Occurred()) {
1742 Py_DECREF(shape);
1743 return NULL;
1744 }
1745 return Py_BuildValue("siN", dict->format, dict->ndim, shape);
Thomas Hellerb041fda2008-04-30 17:11:46 +00001746}
1747
Thomas Heller34596a92009-04-24 20:50:00 +00001748PyMethodDef _ctypes_module_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001749 {"get_errno", get_errno, METH_NOARGS},
1750 {"set_errno", set_errno, METH_VARARGS},
1751 {"POINTER", POINTER, METH_O },
1752 {"pointer", pointer, METH_O },
1753 {"_unpickle", unpickle, METH_VARARGS },
1754 {"buffer_info", buffer_info, METH_O, "Return buffer interface information"},
1755 {"resize", resize, METH_VARARGS, "Resize the memory buffer of a ctypes instance"},
Thomas Hellerd4c93202006-03-08 19:35:11 +00001756#ifdef MS_WIN32
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001757 {"get_last_error", get_last_error, METH_NOARGS},
1758 {"set_last_error", set_last_error, METH_VARARGS},
1759 {"CopyComPointer", copy_com_pointer, METH_VARARGS, copy_com_pointer_doc},
1760 {"FormatError", format_error, METH_VARARGS, format_error_doc},
1761 {"LoadLibrary", load_library, METH_VARARGS, load_library_doc},
1762 {"FreeLibrary", free_library, METH_VARARGS, free_library_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001763 {"_check_HRESULT", check_hresult, METH_VARARGS},
Thomas Hellerd4c93202006-03-08 19:35:11 +00001764#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001765 {"dlopen", py_dl_open, METH_VARARGS,
1766 "dlopen(name, flag={RTLD_GLOBAL|RTLD_LOCAL}) open a shared library"},
1767 {"dlclose", py_dl_close, METH_VARARGS, "dlclose a library"},
1768 {"dlsym", py_dl_sym, METH_VARARGS, "find symbol in shared library"},
Thomas Hellerd4c93202006-03-08 19:35:11 +00001769#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001770 {"alignment", align_func, METH_O, alignment_doc},
1771 {"sizeof", sizeof_func, METH_O, sizeof_doc},
1772 {"byref", byref, METH_VARARGS, byref_doc},
1773 {"addressof", addressof, METH_O, addressof_doc},
1774 {"call_function", call_function, METH_VARARGS },
1775 {"call_cdeclfunction", call_cdeclfunction, METH_VARARGS },
1776 {"PyObj_FromPtr", My_PyObj_FromPtr, METH_VARARGS },
1777 {"Py_INCREF", My_Py_INCREF, METH_O },
1778 {"Py_DECREF", My_Py_DECREF, METH_O },
1779 {NULL, NULL} /* Sentinel */
Thomas Hellerd4c93202006-03-08 19:35:11 +00001780};
1781
1782/*
1783 Local Variables:
1784 compile-command: "cd .. && python setup.py -q build -g && python setup.py -q build install --home ~"
1785 End:
1786*/