ยปCore Development>Code coverage>Modules/_ctypes/callproc.c

Python code coverage for Modules/_ctypes/callproc.c

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