callproc.c 53.2 KB
Newer Older
1 2 3 4 5 6
/*
 * History: First version dated from 3/97, derived from my SCMLIB version
 * for win16.
 */
/*
 * Related Work:
7 8 9
 *      - calldll       http://www.nightmare.com/software.html
 *      - libffi        http://sourceware.cygnus.com/libffi/
 *      - ffcall        http://clisp.cons.org/~haible/packages-ffcall.html
10 11 12 13 14 15 16 17
 *   and, of course, Don Beaudry's MESS package, but this is more ctypes
 *   related.
 */


/*
  How are functions called, and how are parameters converted to C ?

18
  1. _ctypes.c::PyCFuncPtr_call receives an argument tuple 'inargs' and a
19 20 21 22 23 24 25 26 27 28 29
  keyword dictionary 'kwds'.

  2. After several checks, _build_callargs() is called which returns another
  tuple 'callargs'.  This may be the same tuple as 'inargs', a slice of
  'inargs', or a completely fresh tuple, depending on several things (is is a
  COM method, are 'paramflags' available).

  3. _build_callargs also calculates bitarrays containing indexes into
  the callargs tuple, specifying how to build the return value(s) of
  the function.

30
  4. _ctypes_callproc is then called with the 'callargs' tuple.  _ctypes_callproc first
31
  allocates two arrays.  The first is an array of 'struct argument' items, the
32
  second array has 'void *' entries.
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49

  5. If 'converters' are present (converters is a sequence of argtypes'
  from_param methods), for each item in 'callargs' converter is called and the
  result passed to ConvParam.  If 'converters' are not present, each argument
  is directly passed to ConvParm.

  6. For each arg, ConvParam stores the contained C data (or a pointer to it,
  for structures) into the 'struct argument' array.

  7. Finally, a loop fills the 'void *' array so that each item points to the
  data contained in or pointed to by the 'struct argument' array.

  8. The 'void *' argument array is what _call_function_pointer
  expects. _call_function_pointer then has very little to do - only some
  libffi specific stuff, then it calls ffi_call.

  So, there are 4 data structures holding processed arguments:
50 51
  - the inargs tuple (in PyCFuncPtr_call)
  - the callargs tuple (in PyCFuncPtr_call)
52
  - the 'struct arguments' array
53 54 55 56 57 58 59 60 61
  - the 'void *' array

 */

#include "Python.h"
#include "structmember.h"

#ifdef MS_WIN32
#include <windows.h>
62
#include <tchar.h>
63 64 65 66 67
#else
#include "ctypes_dlfcn.h"
#endif

#ifdef MS_WIN32
68
#include <malloc.h>
69 70 71 72 73
#endif

#include <ffi.h>
#include "ctypes.h"

74 75 76 77 78
#if defined(_DEBUG) || defined(__MINGW32__)
/* Don't use structured exception handling on Windows if this is defined.
   MingW, AFAIK, doesn't support it.
*/
#define DONT_USE_SEH
79 80
#endif

81 82 83 84
#define CTYPES_CAPSULE_NAME_PYMEM "_ctypes pymem"

static void pymem_destructor(PyObject *ptr)
{
85 86 87 88
    void *p = PyCapsule_GetPointer(ptr, CTYPES_CAPSULE_NAME_PYMEM);
    if (p) {
        PyMem_Free(p);
    }
89 90
}

91 92 93 94
/*
  ctypes maintains thread-local storage that has space for two error numbers:
  private copies of the system 'errno' value and, on Windows, the system error code
  accessed by the GetLastError() and SetLastError() api functions.
95

96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
  Foreign functions created with CDLL(..., use_errno=True), when called, swap
  the system 'errno' value with the private copy just before the actual
  function call, and swapped again immediately afterwards.  The 'use_errno'
  parameter defaults to False, in this case 'ctypes_errno' is not touched.

  On Windows, foreign functions created with CDLL(..., use_last_error=True) or
  WinDLL(..., use_last_error=True) swap the system LastError value with the
  ctypes private copy.

  The values are also swapped immeditately before and after ctypes callback
  functions are called, if the callbacks are constructed using the new
  optional use_errno parameter set to True: CFUNCTYPE(..., use_errno=TRUE) or
  WINFUNCTYPE(..., use_errno=True).

  New ctypes functions are provided to access the ctypes private copies from
  Python:

  - ctypes.set_errno(value) and ctypes.set_last_error(value) store 'value' in
    the private copy and returns the previous value.

  - ctypes.get_errno() and ctypes.get_last_error() returns the current ctypes
    private copies value.
*/

/*
  This function creates and returns a thread-local Python object that has
  space to store two integer error numbers; once created the Python object is
  kept alive in the thread state dictionary as long as the thread itself.
*/
PyObject *
126
_ctypes_get_errobj(int **pspace)
127
{
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
    PyObject *dict = PyThreadState_GetDict();
    PyObject *errobj;
    static PyObject *error_object_name;
    if (dict == 0) {
        PyErr_SetString(PyExc_RuntimeError,
                        "cannot get thread state");
        return NULL;
    }
    if (error_object_name == NULL) {
        error_object_name = PyUnicode_InternFromString("ctypes.error_object");
        if (error_object_name == NULL)
            return NULL;
    }
    errobj = PyDict_GetItem(dict, error_object_name);
    if (errobj) {
        if (!PyCapsule_IsValid(errobj, CTYPES_CAPSULE_NAME_PYMEM)) {
            PyErr_SetString(PyExc_RuntimeError,
                "ctypes.error_object is an invalid capsule");
            return NULL;
        }
        Py_INCREF(errobj);
    }
    else {
        void *space = PyMem_Malloc(sizeof(int) * 2);
        if (space == NULL)
            return NULL;
        memset(space, 0, sizeof(int) * 2);
        errobj = PyCapsule_New(space, CTYPES_CAPSULE_NAME_PYMEM, pymem_destructor);
        if (errobj == NULL)
            return NULL;
        if (-1 == PyDict_SetItem(dict, error_object_name,
                                 errobj)) {
            Py_DECREF(errobj);
            return NULL;
        }
    }
    *pspace = (int *)PyCapsule_GetPointer(errobj, CTYPES_CAPSULE_NAME_PYMEM);
    return errobj;
166 167 168 169 170
}

static PyObject *
get_error_internal(PyObject *self, PyObject *args, int index)
{
171 172 173 174 175 176 177 178 179
    int *space;
    PyObject *errobj = _ctypes_get_errobj(&space);
    PyObject *result;

    if (errobj == NULL)
        return NULL;
    result = PyLong_FromLong(space[index]);
    Py_DECREF(errobj);
    return result;
180 181 182 183 184
}

static PyObject *
set_error_internal(PyObject *self, PyObject *args, int index)
{
185 186 187 188 189 190 191 192 193 194 195 196 197
    int new_errno, old_errno;
    PyObject *errobj;
    int *space;

    if (!PyArg_ParseTuple(args, "i", &new_errno))
        return NULL;
    errobj = _ctypes_get_errobj(&space);
    if (errobj == NULL)
        return NULL;
    old_errno = space[index];
    space[index] = new_errno;
    Py_DECREF(errobj);
    return PyLong_FromLong(old_errno);
198 199 200 201 202
}

static PyObject *
get_errno(PyObject *self, PyObject *args)
{
203
    return get_error_internal(self, args, 0);
204 205 206 207 208
}

static PyObject *
set_errno(PyObject *self, PyObject *args)
{
209
    return set_error_internal(self, args, 0);
210 211
}

212
#ifdef MS_WIN32
213 214 215 216

static PyObject *
get_last_error(PyObject *self, PyObject *args)
{
217
    return get_error_internal(self, args, 1);
218 219 220 221 222
}

static PyObject *
set_last_error(PyObject *self, PyObject *args)
{
223
    return set_error_internal(self, args, 1);
224 225
}

226 227
PyObject *ComError;

228
static WCHAR *FormatError(DWORD code)
229
{
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
    WCHAR *lpMsgBuf;
    DWORD n;
    n = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
                       NULL,
                       code,
                       MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), /* Default language */
               (LPWSTR) &lpMsgBuf,
               0,
               NULL);
    if (n) {
        while (iswspace(lpMsgBuf[n-1]))
            --n;
        lpMsgBuf[n] = L'\0'; /* rstrip() */
    }
    return lpMsgBuf;
245 246
}

247
#ifndef DONT_USE_SEH
248
static void SetException(DWORD code, EXCEPTION_RECORD *pr)
249
{
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392
    /* The 'code' is a normal win32 error code so it could be handled by
    PyErr_SetFromWindowsErr(). However, for some errors, we have additional
    information not included in the error code. We handle those here and
    delegate all others to the generic function. */
    switch (code) {
    case EXCEPTION_ACCESS_VIOLATION:
        /* The thread attempted to read from or write
           to a virtual address for which it does not
           have the appropriate access. */
        if (pr->ExceptionInformation[0] == 0)
            PyErr_Format(PyExc_WindowsError,
                         "exception: access violation reading %p",
                         pr->ExceptionInformation[1]);
        else
            PyErr_Format(PyExc_WindowsError,
                         "exception: access violation writing %p",
                         pr->ExceptionInformation[1]);
        break;

    case EXCEPTION_BREAKPOINT:
        /* A breakpoint was encountered. */
        PyErr_SetString(PyExc_WindowsError,
                        "exception: breakpoint encountered");
        break;

    case EXCEPTION_DATATYPE_MISALIGNMENT:
        /* The thread attempted to read or write data that is
           misaligned on hardware that does not provide
           alignment. For example, 16-bit values must be
           aligned on 2-byte boundaries, 32-bit values on
           4-byte boundaries, and so on. */
        PyErr_SetString(PyExc_WindowsError,
                        "exception: datatype misalignment");
        break;

    case EXCEPTION_SINGLE_STEP:
        /* A trace trap or other single-instruction mechanism
           signaled that one instruction has been executed. */
        PyErr_SetString(PyExc_WindowsError,
                        "exception: single step");
        break;

    case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
        /* The thread attempted to access an array element
           that is out of bounds, and the underlying hardware
           supports bounds checking. */
        PyErr_SetString(PyExc_WindowsError,
                        "exception: array bounds exceeded");
        break;

    case EXCEPTION_FLT_DENORMAL_OPERAND:
        /* One of the operands in a floating-point operation
           is denormal. A denormal value is one that is too
           small to represent as a standard floating-point
           value. */
        PyErr_SetString(PyExc_WindowsError,
                        "exception: floating-point operand denormal");
        break;

    case EXCEPTION_FLT_DIVIDE_BY_ZERO:
        /* The thread attempted to divide a floating-point
           value by a floating-point divisor of zero. */
        PyErr_SetString(PyExc_WindowsError,
                        "exception: float divide by zero");
        break;

    case EXCEPTION_FLT_INEXACT_RESULT:
        /* The result of a floating-point operation cannot be
           represented exactly as a decimal fraction. */
        PyErr_SetString(PyExc_WindowsError,
                        "exception: float inexact");
        break;

    case EXCEPTION_FLT_INVALID_OPERATION:
        /* This exception represents any floating-point
           exception not included in this list. */
        PyErr_SetString(PyExc_WindowsError,
                        "exception: float invalid operation");
        break;

    case EXCEPTION_FLT_OVERFLOW:
        /* The exponent of a floating-point operation is
           greater than the magnitude allowed by the
           corresponding type. */
        PyErr_SetString(PyExc_WindowsError,
                        "exception: float overflow");
        break;

    case EXCEPTION_FLT_STACK_CHECK:
        /* The stack overflowed or underflowed as the result
           of a floating-point operation. */
        PyErr_SetString(PyExc_WindowsError,
                        "exception: stack over/underflow");
        break;

    case EXCEPTION_STACK_OVERFLOW:
        /* The stack overflowed or underflowed as the result
           of a floating-point operation. */
        PyErr_SetString(PyExc_WindowsError,
                        "exception: stack overflow");
        break;

    case EXCEPTION_FLT_UNDERFLOW:
        /* The exponent of a floating-point operation is less
           than the magnitude allowed by the corresponding
           type. */
        PyErr_SetString(PyExc_WindowsError,
                        "exception: float underflow");
        break;

    case EXCEPTION_INT_DIVIDE_BY_ZERO:
        /* The thread attempted to divide an integer value by
           an integer divisor of zero. */
        PyErr_SetString(PyExc_WindowsError,
                        "exception: integer divide by zero");
        break;

    case EXCEPTION_INT_OVERFLOW:
        /* The result of an integer operation caused a carry
           out of the most significant bit of the result. */
        PyErr_SetString(PyExc_WindowsError,
                        "exception: integer overflow");
        break;

    case EXCEPTION_PRIV_INSTRUCTION:
        /* The thread attempted to execute an instruction
           whose operation is not allowed in the current
           machine mode. */
        PyErr_SetString(PyExc_WindowsError,
                        "exception: priviledged instruction");
        break;

    case EXCEPTION_NONCONTINUABLE_EXCEPTION:
        /* The thread attempted to continue execution after a
           noncontinuable exception occurred. */
        PyErr_SetString(PyExc_WindowsError,
                        "exception: nocontinuable");
        break;

    default:
        PyErr_SetFromWindowsErr(code);
        break;
    }
393 394 395
}

static DWORD HandleException(EXCEPTION_POINTERS *ptrs,
396
                             DWORD *pdw, EXCEPTION_RECORD *record)
397
{
398 399 400
    *pdw = ptrs->ExceptionRecord->ExceptionCode;
    *record = *ptrs->ExceptionRecord;
    return EXCEPTION_EXECUTE_HANDLER;
401
}
402
#endif
403 404 405 406

static PyObject *
check_hresult(PyObject *self, PyObject *args)
{
407 408 409 410 411 412
    HRESULT hr;
    if (!PyArg_ParseTuple(args, "i", &hr))
        return NULL;
    if (FAILED(hr))
        return PyErr_SetFromWindowsErr(hr);
    return PyLong_FromLong(hr);
413 414 415 416 417 418 419
}

#endif

/**************************************************************/

PyCArgObject *
420
PyCArgObject_new(void)
421
{
422 423 424 425 426 427 428 429 430
    PyCArgObject *p;
    p = PyObject_New(PyCArgObject, &PyCArg_Type);
    if (p == NULL)
        return NULL;
    p->pffi_type = NULL;
    p->tag = '\0';
    p->obj = NULL;
    memset(&p->value, 0, sizeof(p->value));
    return p;
431 432 433 434 435
}

static void
PyCArg_dealloc(PyCArgObject *self)
{
436 437
    Py_XDECREF(self->obj);
    PyObject_Del(self);
438 439 440 441 442
}

static PyObject *
PyCArg_repr(PyCArgObject *self)
{
443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
    char buffer[256];
    switch(self->tag) {
    case 'b':
    case 'B':
        sprintf(buffer, "<cparam '%c' (%d)>",
            self->tag, self->value.b);
        break;
    case 'h':
    case 'H':
        sprintf(buffer, "<cparam '%c' (%d)>",
            self->tag, self->value.h);
        break;
    case 'i':
    case 'I':
        sprintf(buffer, "<cparam '%c' (%d)>",
            self->tag, self->value.i);
        break;
    case 'l':
    case 'L':
        sprintf(buffer, "<cparam '%c' (%ld)>",
            self->tag, self->value.l);
        break;

466
#ifdef HAVE_LONG_LONG
467 468 469
    case 'q':
    case 'Q':
        sprintf(buffer,
470
#ifdef MS_WIN32
471
            "<cparam '%c' (%I64d)>",
472
#else
473
            "<cparam '%c' (%qd)>",
474
#endif
475 476
            self->tag, self->value.q);
        break;
477
#endif
478 479 480 481 482 483 484 485 486 487 488 489 490
    case 'd':
        sprintf(buffer, "<cparam '%c' (%f)>",
            self->tag, self->value.d);
        break;
    case 'f':
        sprintf(buffer, "<cparam '%c' (%f)>",
            self->tag, self->value.f);
        break;

    case 'c':
        sprintf(buffer, "<cparam '%c' (%c)>",
            self->tag, self->value.c);
        break;
491 492 493 494 495

/* Hm, are these 'z' and 'Z' codes useful at all?
   Shouldn't they be replaced by the functionality of c_string
   and c_wstring ?
*/
496 497 498 499 500 501 502 503 504 505 506 507 508
    case 'z':
    case 'Z':
    case 'P':
        sprintf(buffer, "<cparam '%c' (%p)>",
            self->tag, self->value.p);
        break;

    default:
        sprintf(buffer, "<cparam '%c' at %p>",
            self->tag, self);
        break;
    }
    return PyUnicode_FromString(buffer);
509 510 511
}

static PyMemberDef PyCArgType_members[] = {
512 513 514 515
    { "_obj", T_OBJECT,
      offsetof(PyCArgObject, obj), READONLY,
      "the wrapped object" },
    { NULL },
516 517 518
};

PyTypeObject PyCArg_Type = {
519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547
    PyVarObject_HEAD_INIT(NULL, 0)
    "CArgObject",
    sizeof(PyCArgObject),
    0,
    (destructor)PyCArg_dealloc,                 /* tp_dealloc */
    0,                                          /* tp_print */
    0,                                          /* tp_getattr */
    0,                                          /* tp_setattr */
    0,                                          /* tp_reserved */
    (reprfunc)PyCArg_repr,                      /* tp_repr */
    0,                                          /* tp_as_number */
    0,                                          /* tp_as_sequence */
    0,                                          /* tp_as_mapping */
    0,                                          /* tp_hash */
    0,                                          /* tp_call */
    0,                                          /* tp_str */
    0,                                          /* tp_getattro */
    0,                                          /* tp_setattro */
    0,                                          /* tp_as_buffer */
    Py_TPFLAGS_DEFAULT,                         /* tp_flags */
    0,                                          /* tp_doc */
    0,                                          /* tp_traverse */
    0,                                          /* tp_clear */
    0,                                          /* tp_richcompare */
    0,                                          /* tp_weaklistoffset */
    0,                                          /* tp_iter */
    0,                                          /* tp_iternext */
    0,                                          /* tp_methods */
    PyCArgType_members,                         /* tp_members */
548 549 550 551 552 553 554 555
};

/****************************************************************/
/*
 * Convert a PyObject * into a parameter suitable to pass to an
 * C function call.
 *
 * 1. Python integers are converted to C int and passed by value.
556
 *    Py_None is converted to a C NULL pointer.
557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579
 *
 * 2. 3-tuples are expected to have a format character in the first
 *    item, which must be 'i', 'f', 'd', 'q', or 'P'.
 *    The second item will have to be an integer, float, double, long long
 *    or integer (denoting an address void *), will be converted to the
 *    corresponding C data type and passed by value.
 *
 * 3. Other Python objects are tested for an '_as_parameter_' attribute.
 *    The value of this attribute must be an integer which will be passed
 *    by value, or a 2-tuple or 3-tuple which will be used according
 *    to point 2 above. The third item (if any), is ignored. It is normally
 *    used to keep the object alive where this parameter refers to.
 *    XXX This convention is dangerous - you can construct arbitrary tuples
 *    in Python and pass them. Would it be safer to use a custom container
 *    datatype instead of a tuple?
 *
 * 4. Other Python objects cannot be passed as parameters - an exception is raised.
 *
 * 5. ConvParam will store the converted result in a struct containing format
 *    and value.
 */

union result {
580 581 582 583 584
    char c;
    char b;
    short h;
    int i;
    long l;
585
#ifdef HAVE_LONG_LONG
586
    PY_LONG_LONG q;
587
#endif
588 589 590 591
    long double D;
    double d;
    float f;
    void *p;
592 593 594
};

struct argument {
595 596 597
    ffi_type *ffi_type;
    PyObject *keep;
    union result value;
598 599 600 601 602
};

/*
 * Convert a single Python object into a PyCArgObject and return it.
 */
603
static int ConvParam(PyObject *obj, Py_ssize_t index, struct argument *pa)
604
{
605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657
    StgDictObject *dict;
    pa->keep = NULL; /* so we cannot forget it later */

    dict = PyObject_stgdict(obj);
    if (dict) {
        PyCArgObject *carg;
        assert(dict->paramfunc);
        /* If it has an stgdict, it is a CDataObject */
        carg = dict->paramfunc((CDataObject *)obj);
        pa->ffi_type = carg->pffi_type;
        memcpy(&pa->value, &carg->value, sizeof(pa->value));
        pa->keep = (PyObject *)carg;
        return 0;
    }

    if (PyCArg_CheckExact(obj)) {
        PyCArgObject *carg = (PyCArgObject *)obj;
        pa->ffi_type = carg->pffi_type;
        Py_INCREF(obj);
        pa->keep = obj;
        memcpy(&pa->value, &carg->value, sizeof(pa->value));
        return 0;
    }

    /* check for None, integer, string or unicode and use directly if successful */
    if (obj == Py_None) {
        pa->ffi_type = &ffi_type_pointer;
        pa->value.p = NULL;
        return 0;
    }

    if (PyLong_Check(obj)) {
        pa->ffi_type = &ffi_type_sint;
        pa->value.i = (long)PyLong_AsUnsignedLong(obj);
        if (pa->value.i == -1 && PyErr_Occurred()) {
            PyErr_Clear();
            pa->value.i = PyLong_AsLong(obj);
            if (pa->value.i == -1 && PyErr_Occurred()) {
                PyErr_SetString(PyExc_OverflowError,
                                "long int too long to convert");
                return -1;
            }
        }
        return 0;
    }

    if (PyBytes_Check(obj)) {
        pa->ffi_type = &ffi_type_pointer;
        pa->value.p = PyBytes_AsString(obj);
        Py_INCREF(obj);
        pa->keep = obj;
        return 0;
    }
658

659
#ifdef CTYPES_UNICODE
660
    if (PyUnicode_Check(obj)) {
661
#if Py_UNICODE_SIZE == SIZEOF_WCHAR_T
662 663 664 665 666
        pa->ffi_type = &ffi_type_pointer;
        pa->value.p = PyUnicode_AS_UNICODE(obj);
        Py_INCREF(obj);
        pa->keep = obj;
        return 0;
667
#else
668
        pa->ffi_type = &ffi_type_pointer;
669
        pa->value.p = PyUnicode_AsWideCharString(obj, NULL);
670
        if (pa->value.p == NULL)
671 672 673 674 675 676 677
            return -1;
        pa->keep = PyCapsule_New(pa->value.p, CTYPES_CAPSULE_NAME_PYMEM, pymem_destructor);
        if (!pa->keep) {
            PyMem_Free(pa->value.p);
            return -1;
        }
        return 0;
678
#endif
679
    }
680 681
#endif

682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700
    {
        PyObject *arg;
        arg = PyObject_GetAttrString(obj, "_as_parameter_");
        /* Which types should we exactly allow here?
           integers are required for using Python classes
           as parameters (they have to expose the '_as_parameter_'
           attribute)
        */
        if (arg) {
            int result;
            result = ConvParam(arg, index, pa);
            Py_DECREF(arg);
            return result;
        }
        PyErr_Format(PyExc_TypeError,
                     "Don't know how to convert parameter %d",
                     Py_SAFE_DOWNCAST(index, Py_ssize_t, int));
        return -1;
    }
701 702 703
}


704
ffi_type *_ctypes_get_ffi_type(PyObject *obj)
705
{
706 707 708 709 710 711
    StgDictObject *dict;
    if (obj == NULL)
        return &ffi_type_sint;
    dict = PyType_stgdict(obj);
    if (dict == NULL)
        return &ffi_type_sint;
712
#if defined(MS_WIN32) && !defined(_WIN32_WCE)
713 714 715 716 717 718 719 720 721
    /* This little trick works correctly with MSVC.
       It returns small structures in registers
    */
    if (dict->ffi_type_pointer.type == FFI_TYPE_STRUCT) {
        if (dict->ffi_type_pointer.size <= 4)
            return &ffi_type_sint32;
        else if (dict->ffi_type_pointer.size <= 8)
            return &ffi_type_sint64;
    }
722
#endif
723
    return &dict->ffi_type_pointer;
724 725 726 727 728 729 730
}


/*
 * libffi uses:
 *
 * ffi_status ffi_prep_cif(ffi_cif *cif, ffi_abi abi,
731
 *                         unsigned int nargs,
732 733 734 735 736 737 738 739
 *                         ffi_type *rtype,
 *                         ffi_type **atypes);
 *
 * and then
 *
 * void ffi_call(ffi_cif *cif, void *fn, void *rvalue, void **avalues);
 */
static int _call_function_pointer(int flags,
740 741 742 743 744 745
                                  PPROC pProc,
                                  void **avalues,
                                  ffi_type **atypes,
                                  ffi_type *restype,
                                  void *resmem,
                                  int argcount)
746
{
747
#ifdef WITH_THREAD
748
    PyThreadState *_save = NULL; /* For Py_BLOCK_THREADS and Py_UNBLOCK_THREADS */
749
#endif
750 751 752 753
    PyObject *error_object = NULL;
    int *space;
    ffi_cif cif;
    int cc;
754
#ifdef MS_WIN32
755
    int delta;
756
#ifndef DONT_USE_SEH
757 758
    DWORD dwExceptionCode = 0;
    EXCEPTION_RECORD record;
759
#endif
760
#endif
761 762 763 764 765 766 767 768
    /* XXX check before here */
    if (restype == NULL) {
        PyErr_SetString(PyExc_RuntimeError,
                        "No ffi_type for result");
        return -1;
    }

    cc = FFI_DEFAULT_ABI;
769
#if defined(MS_WIN32) && !defined(MS_WIN64) && !defined(_WIN32_WCE)
770 771
    if ((flags & FUNCFLAG_CDECL) == 0)
        cc = FFI_STDCALL;
772
#endif
773 774 775 776 777 778 779 780 781 782 783 784 785 786 787
    if (FFI_OK != ffi_prep_cif(&cif,
                               cc,
                               argcount,
                               restype,
                               atypes)) {
        PyErr_SetString(PyExc_RuntimeError,
                        "ffi_prep_cif failed");
        return -1;
    }

    if (flags & (FUNCFLAG_USE_ERRNO | FUNCFLAG_USE_LASTERROR)) {
        error_object = _ctypes_get_errobj(&space);
        if (error_object == NULL)
            return -1;
    }
788
#ifdef WITH_THREAD
789 790
    if ((flags & FUNCFLAG_PYTHONAPI) == 0)
        Py_UNBLOCK_THREADS
791
#endif
792 793 794 795 796
    if (flags & FUNCFLAG_USE_ERRNO) {
        int temp = space[0];
        space[0] = errno;
        errno = temp;
    }
797
#ifdef MS_WIN32
798 799 800 801 802
    if (flags & FUNCFLAG_USE_LASTERROR) {
        int temp = space[1];
        space[1] = GetLastError();
        SetLastError(temp);
    }
803
#ifndef DONT_USE_SEH
804
    __try {
805
#endif
806
        delta =
807
#endif
808
                ffi_call(&cif, (void *)pProc, resmem, avalues);
809
#ifdef MS_WIN32
810
#ifndef DONT_USE_SEH
811 812 813 814 815
    }
    __except (HandleException(GetExceptionInformation(),
                              &dwExceptionCode, &record)) {
        ;
    }
816
#endif
817 818 819 820 821
    if (flags & FUNCFLAG_USE_LASTERROR) {
        int temp = space[1];
        space[1] = GetLastError();
        SetLastError(temp);
    }
822
#endif
823 824 825 826 827 828
    if (flags & FUNCFLAG_USE_ERRNO) {
        int temp = space[0];
        space[0] = errno;
        errno = temp;
    }
    Py_XDECREF(error_object);
829
#ifdef WITH_THREAD
830 831
    if ((flags & FUNCFLAG_PYTHONAPI) == 0)
        Py_BLOCK_THREADS
832
#endif
833
#ifdef MS_WIN32
834
#ifndef DONT_USE_SEH
835 836 837 838
    if (dwExceptionCode) {
        SetException(dwExceptionCode, &record);
        return -1;
    }
839
#endif
840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868
#ifdef MS_WIN64
    if (delta != 0) {
        PyErr_Format(PyExc_RuntimeError,
                 "ffi_call failed with code %d",
                 delta);
        return -1;
    }
#else
    if (delta < 0) {
        if (flags & FUNCFLAG_CDECL)
            PyErr_Format(PyExc_ValueError,
                     "Procedure called with not enough "
                     "arguments (%d bytes missing) "
                     "or wrong calling convention",
                     -delta);
        else
            PyErr_Format(PyExc_ValueError,
                     "Procedure probably called with not enough "
                     "arguments (%d bytes missing)",
                     -delta);
        return -1;
    } else if (delta > 0) {
        PyErr_Format(PyExc_ValueError,
                 "Procedure probably called with too many "
                 "arguments (%d bytes in excess)",
                 delta);
        return -1;
    }
#endif
869
#endif
870 871 872
    if ((flags & FUNCFLAG_PYTHONAPI) && PyErr_Occurred())
        return -1;
    return 0;
873 874 875 876 877 878 879 880 881 882 883 884 885 886
}

/*
 * Convert the C value in result into a Python object, depending on restype.
 *
 * - If restype is NULL, return a Python integer.
 * - If restype is None, return None.
 * - If restype is a simple ctypes type (c_int, c_void_p), call the type's getfunc,
 *   pass the result to checker and return the result.
 * - If restype is another ctypes type, return an instance of that.
 * - Otherwise, call restype and return the result.
 */
static PyObject *GetResult(PyObject *restype, void *result, PyObject *checker)
{
887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921
    StgDictObject *dict;
    PyObject *retval, *v;

    if (restype == NULL)
        return PyLong_FromLong(*(int *)result);

    if (restype == Py_None) {
        Py_INCREF(Py_None);
        return Py_None;
    }

    dict = PyType_stgdict(restype);
    if (dict == NULL)
        return PyObject_CallFunction(restype, "i", *(int *)result);

    if (dict->getfunc && !_ctypes_simple_instance(restype)) {
        retval = dict->getfunc(result, dict->size);
        /* If restype is py_object (detected by comparing getfunc with
           O_get), we have to call Py_DECREF because O_get has already
           called Py_INCREF.
        */
        if (dict->getfunc == _ctypes_get_fielddesc("O")->getfunc) {
            Py_DECREF(retval);
        }
    } else
        retval = PyCData_FromBaseObj(restype, NULL, 0, result);

    if (!checker || !retval)
        return retval;

    v = PyObject_CallFunctionObjArgs(checker, retval, NULL);
    if (v == NULL)
        _ctypes_add_traceback("GetResult", "_ctypes/callproc.c", __LINE__-2);
    Py_DECREF(retval);
    return v;
922 923 924 925 926 927
}

/*
 * Raise a new exception 'exc_class', adding additional text to the original
 * exception string.
 */
928
void _ctypes_extend_error(PyObject *exc_class, char *fmt, ...)
929
{
930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958
    va_list vargs;
    PyObject *tp, *v, *tb, *s, *cls_str, *msg_str;

    va_start(vargs, fmt);
    s = PyUnicode_FromFormatV(fmt, vargs);
    va_end(vargs);
    if (!s)
        return;

    PyErr_Fetch(&tp, &v, &tb);
    PyErr_NormalizeException(&tp, &v, &tb);
    cls_str = PyObject_Str(tp);
    if (cls_str) {
        PyUnicode_AppendAndDel(&s, cls_str);
        PyUnicode_AppendAndDel(&s, PyUnicode_FromString(": "));
        if (s == NULL)
            goto error;
    } else
        PyErr_Clear();
    msg_str = PyObject_Str(v);
    if (msg_str)
        PyUnicode_AppendAndDel(&s, msg_str);
    else {
        PyErr_Clear();
        PyUnicode_AppendAndDel(&s, PyUnicode_FromString("???"));
        if (s == NULL)
            goto error;
    }
    PyErr_SetObject(exc_class, s);
959
error:
960 961 962 963
    Py_XDECREF(tp);
    Py_XDECREF(v);
    Py_XDECREF(tb);
    Py_XDECREF(s);
964 965 966 967 968 969 970 971
}


#ifdef MS_WIN32

static PyObject *
GetComError(HRESULT errcode, GUID *riid, IUnknown *pIunk)
{
972 973 974 975 976 977 978 979 980 981 982 983 984
    HRESULT hr;
    ISupportErrorInfo *psei = NULL;
    IErrorInfo *pei = NULL;
    BSTR descr=NULL, helpfile=NULL, source=NULL;
    GUID guid;
    DWORD helpcontext=0;
    LPOLESTR progid;
    PyObject *obj;
    LPOLESTR text;

    /* We absolutely have to release the GIL during COM method calls,
       otherwise we may get a deadlock!
    */
985
#ifdef WITH_THREAD
986
    Py_BEGIN_ALLOW_THREADS
987 988
#endif

989 990 991
    hr = pIunk->lpVtbl->QueryInterface(pIunk, &IID_ISupportErrorInfo, (void **)&psei);
    if (FAILED(hr))
        goto failed;
992

993 994 995 996
    hr = psei->lpVtbl->InterfaceSupportsErrorInfo(psei, riid);
    psei->lpVtbl->Release(psei);
    if (FAILED(hr))
        goto failed;
997

998 999 1000
    hr = GetErrorInfo(0, &pei);
    if (hr != S_OK)
        goto failed;
1001

1002 1003 1004 1005 1006
    pei->lpVtbl->GetDescription(pei, &descr);
    pei->lpVtbl->GetGUID(pei, &guid);
    pei->lpVtbl->GetHelpContext(pei, &helpcontext);
    pei->lpVtbl->GetHelpFile(pei, &helpfile);
    pei->lpVtbl->GetSource(pei, &source);
1007

1008
    pei->lpVtbl->Release(pei);
1009

1010
  failed:
1011
#ifdef WITH_THREAD
1012
    Py_END_ALLOW_THREADS
1013
#endif
1014

1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038
    progid = NULL;
    ProgIDFromCLSID(&guid, &progid);

    text = FormatError(errcode);
    obj = Py_BuildValue(
        "iu(uuuiu)",
        errcode,
        text,
        descr, source, helpfile, helpcontext,
        progid);
    if (obj) {
        PyErr_SetObject(ComError, obj);
        Py_DECREF(obj);
    }
    LocalFree(text);

    if (descr)
        SysFreeString(descr);
    if (helpfile)
        SysFreeString(helpfile);
    if (source)
        SysFreeString(source);

    return NULL;
1039 1040 1041 1042 1043 1044 1045 1046 1047 1048
}
#endif

/*
 * Requirements, must be ensured by the caller:
 * - argtuple is tuple of arguments
 * - argtypes is either NULL, or a tuple of the same size as argtuple
 *
 * - XXX various requirements for restype, not yet collected
 */
1049
PyObject *_ctypes_callproc(PPROC pProc,
1050
                    PyObject *argtuple,
1051
#ifdef MS_WIN32
1052 1053
                    IUnknown *pIunk,
                    GUID *iid,
1054
#endif
1055 1056 1057 1058 1059 1060
                    int flags,
                    PyObject *argtypes, /* misleading name: This is a tuple of
                                           methods, not types: the .from_param
                                           class methods of the types */
            PyObject *restype,
            PyObject *checker)
1061
{
1062 1063 1064 1065 1066 1067 1068 1069 1070
    Py_ssize_t i, n, argcount, argtype_count;
    void *resbuf;
    struct argument *args, *pa;
    ffi_type **atypes;
    ffi_type *rtype;
    void **avalues;
    PyObject *retval = NULL;

    n = argcount = PyTuple_GET_SIZE(argtuple);
1071
#ifdef MS_WIN32
1072 1073 1074
    /* an optional COM object this pointer */
    if (pIunk)
        ++argcount;
1075 1076
#endif

1077 1078 1079 1080 1081 1082 1083
    args = (struct argument *)alloca(sizeof(struct argument) * argcount);
    if (!args) {
        PyErr_NoMemory();
        return NULL;
    }
    memset(args, 0, sizeof(struct argument) * argcount);
    argtype_count = argtypes ? PyTuple_GET_SIZE(argtypes) : 0;
1084
#ifdef MS_WIN32
1085 1086 1087 1088 1089
    if (pIunk) {
        args[0].ffi_type = &ffi_type_pointer;
        args[0].value.p = pIunk;
        pa = &args[1];
    } else
1090
#endif
1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140
        pa = &args[0];

    /* Convert the arguments */
    for (i = 0; i < n; ++i, ++pa) {
        PyObject *converter;
        PyObject *arg;
        int err;

        arg = PyTuple_GET_ITEM(argtuple, i);            /* borrowed ref */
        /* For cdecl functions, we allow more actual arguments
           than the length of the argtypes tuple.
           This is checked in _ctypes::PyCFuncPtr_Call
        */
        if (argtypes && argtype_count > i) {
            PyObject *v;
            converter = PyTuple_GET_ITEM(argtypes, i);
            v = PyObject_CallFunctionObjArgs(converter,
                                               arg,
                                               NULL);
            if (v == NULL) {
                _ctypes_extend_error(PyExc_ArgError, "argument %d: ", i+1);
                goto cleanup;
            }

            err = ConvParam(v, i+1, pa);
            Py_DECREF(v);
            if (-1 == err) {
                _ctypes_extend_error(PyExc_ArgError, "argument %d: ", i+1);
                goto cleanup;
            }
        } else {
            err = ConvParam(arg, i+1, pa);
            if (-1 == err) {
                _ctypes_extend_error(PyExc_ArgError, "argument %d: ", i+1);
                goto cleanup; /* leaking ? */
            }
        }
    }

    rtype = _ctypes_get_ffi_type(restype);
    resbuf = alloca(max(rtype->size, sizeof(ffi_arg)));

    avalues = (void **)alloca(sizeof(void *) * argcount);
    atypes = (ffi_type **)alloca(sizeof(ffi_type *) * argcount);
    if (!resbuf || !avalues || !atypes) {
        PyErr_NoMemory();
        goto cleanup;
    }
    for (i = 0; i < argcount; ++i) {
        atypes[i] = args[i].ffi_type;
1141
        if (atypes[i]->type == FFI_TYPE_STRUCT
1142 1143 1144 1145
#ifdef _WIN64
            && atypes[i]->size <= sizeof(void *)
#endif
            )
1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156
            avalues[i] = (void *)args[i].value.p;
        else
            avalues[i] = (void *)&args[i].value;
    }

    if (-1 == _call_function_pointer(flags, pProc, avalues, atypes,
                                     rtype, resbuf,
                                     Py_SAFE_DOWNCAST(argcount,
                                                      Py_ssize_t,
                                                      int)))
        goto cleanup;
1157 1158

#ifdef WORDS_BIGENDIAN
1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172
    /* libffi returns the result in a buffer with sizeof(ffi_arg). This
       causes problems on big endian machines, since the result buffer
       address cannot simply be used as result pointer, instead we must
       adjust the pointer value:
     */
    /*
      XXX I should find out and clarify why this is needed at all,
      especially why adjusting for ffi_type_float must be avoided on
      64-bit platforms.
     */
    if (rtype->type != FFI_TYPE_FLOAT
        && rtype->type != FFI_TYPE_STRUCT
        && rtype->size < sizeof(ffi_arg))
        resbuf = (char *)resbuf + sizeof(ffi_arg) - rtype->size;
1173 1174 1175
#endif

#ifdef MS_WIN32
1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186
    if (iid && pIunk) {
        if (*(int *)resbuf & 0x80000000)
            retval = GetComError(*(HRESULT *)resbuf, iid, pIunk);
        else
            retval = PyLong_FromLong(*(int *)resbuf);
    } else if (flags & FUNCFLAG_HRESULT) {
        if (*(int *)resbuf & 0x80000000)
            retval = PyErr_SetFromWindowsErr(*(int *)resbuf);
        else
            retval = PyLong_FromLong(*(int *)resbuf);
    } else
1187
#endif
1188
        retval = GetResult(restype, resbuf, checker);
1189
  cleanup:
1190 1191 1192
    for (i = 0; i < argcount; ++i)
        Py_XDECREF(args[i].keep);
    return retval;
1193 1194
}

1195 1196 1197
static int
_parse_voidp(PyObject *obj, void **address)
{
1198 1199 1200 1201
    *address = PyLong_AsVoidPtr(obj);
    if (*address == NULL)
        return 0;
    return 1;
1202 1203
}

1204 1205 1206 1207 1208 1209 1210 1211 1212
#ifdef MS_WIN32

static char format_error_doc[] =
"FormatError([integer]) -> string\n\
\n\
Convert a win32 error code into a string. If the error code is not\n\
given, the return value of a call to GetLastError() is used.\n";
static PyObject *format_error(PyObject *self, PyObject *args)
{
1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227
    PyObject *result;
    wchar_t *lpMsgBuf;
    DWORD code = 0;
    if (!PyArg_ParseTuple(args, "|i:FormatError", &code))
        return NULL;
    if (code == 0)
        code = GetLastError();
    lpMsgBuf = FormatError(code);
    if (lpMsgBuf) {
        result = PyUnicode_FromWideChar(lpMsgBuf, wcslen(lpMsgBuf));
        LocalFree(lpMsgBuf);
    } else {
        result = PyUnicode_FromString("<no description>");
    }
    return result;
1228 1229 1230 1231 1232 1233 1234 1235 1236 1237
}

static char load_library_doc[] =
"LoadLibrary(name) -> handle\n\
\n\
Load an executable (usually a DLL), and return a handle to it.\n\
The handle may be used to locate exported functions in this\n\
module.\n";
static PyObject *load_library(PyObject *self, PyObject *args)
{
1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251
    WCHAR *name;
    PyObject *nameobj;
    PyObject *ignored;
    HMODULE hMod;
    if (!PyArg_ParseTuple(args, "O|O:LoadLibrary", &nameobj, &ignored))
        return NULL;

    name = PyUnicode_AsUnicode(nameobj);
    if (!name)
        return NULL;

    hMod = LoadLibraryW(name);
    if (!hMod)
        return PyErr_SetFromWindowsErr(GetLastError());
1252
#ifdef _WIN64
1253
    return PyLong_FromVoidPtr(hMod);
1254
#else
1255
    return Py_BuildValue("i", hMod);
1256
#endif
1257 1258 1259 1260 1261 1262 1263 1264
}

static char free_library_doc[] =
"FreeLibrary(handle) -> void\n\
\n\
Free the handle of an executable previously loaded by LoadLibrary.\n";
static PyObject *free_library(PyObject *self, PyObject *args)
{
1265 1266 1267 1268 1269 1270 1271
    void *hMod;
    if (!PyArg_ParseTuple(args, "O&:FreeLibrary", &_parse_voidp, &hMod))
        return NULL;
    if (!FreeLibrary((HMODULE)hMod))
        return PyErr_SetFromWindowsErr(GetLastError());
    Py_INCREF(Py_None);
    return Py_None;
1272 1273 1274 1275 1276 1277 1278
}

/* obsolete, should be removed */
/* Only used by sample code (in samples\Windows\COM.py) */
static PyObject *
call_commethod(PyObject *self, PyObject *args)
{
1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318
    IUnknown *pIunk;
    int index;
    PyObject *arguments;
    PPROC *lpVtbl;
    PyObject *result;
    CDataObject *pcom;
    PyObject *argtypes = NULL;

    if (!PyArg_ParseTuple(args,
                          "OiO!|O!",
                          &pcom, &index,
                          &PyTuple_Type, &arguments,
                          &PyTuple_Type, &argtypes))
        return NULL;

    if (argtypes && (PyTuple_GET_SIZE(arguments) != PyTuple_GET_SIZE(argtypes))) {
        PyErr_Format(PyExc_TypeError,
                     "Method takes %d arguments (%d given)",
                     PyTuple_GET_SIZE(argtypes), PyTuple_GET_SIZE(arguments));
        return NULL;
    }

    if (!CDataObject_Check(pcom) || (pcom->b_size != sizeof(void *))) {
        PyErr_Format(PyExc_TypeError,
                     "COM Pointer expected instead of %s instance",
                     Py_TYPE(pcom)->tp_name);
        return NULL;
    }

    if ((*(void **)(pcom->b_ptr)) == NULL) {
        PyErr_SetString(PyExc_ValueError,
                        "The COM 'this' pointer is NULL");
        return NULL;
    }

    pIunk = (IUnknown *)(*(void **)(pcom->b_ptr));
    lpVtbl = (PPROC *)(pIunk->lpVtbl);

    result =  _ctypes_callproc(lpVtbl[index],
                        arguments,
1319
#ifdef MS_WIN32
1320 1321
                        pIunk,
                        NULL,
1322
#endif
1323 1324 1325 1326 1327
                        FUNCFLAG_HRESULT, /* flags */
                argtypes, /* self->argtypes */
                NULL, /* self->restype */
                NULL); /* checker */
    return result;
1328 1329 1330
}

static char copy_com_pointer_doc[] =
1331
"CopyComPointer(src, dst) -> HRESULT value\n";
1332 1333 1334 1335

static PyObject *
copy_com_pointer(PyObject *self, PyObject *args)
{
1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355
    PyObject *p1, *p2, *r = NULL;
    struct argument a, b;
    IUnknown *src, **pdst;
    if (!PyArg_ParseTuple(args, "OO:CopyComPointer", &p1, &p2))
        return NULL;
    a.keep = b.keep = NULL;

    if (-1 == ConvParam(p1, 0, &a) || -1 == ConvParam(p2, 1, &b))
        goto done;
    src = (IUnknown *)a.value.p;
    pdst = (IUnknown **)b.value.p;

    if (pdst == NULL)
        r = PyLong_FromLong(E_POINTER);
    else {
        if (src)
            src->lpVtbl->AddRef(src);
        *pdst = src;
        r = PyLong_FromLong(S_OK);
    }
1356
  done:
1357 1358 1359
    Py_XDECREF(a.keep);
    Py_XDECREF(b.keep);
    return r;
1360 1361 1362 1363 1364
}
#else

static PyObject *py_dl_open(PyObject *self, PyObject *args)
{
1365 1366 1367 1368 1369
    PyObject *name, *name2;
    char *name_str;
    void * handle;
#ifdef RTLD_LOCAL
    int mode = RTLD_NOW | RTLD_LOCAL;
1370
#else
1371 1372
    /* cygwin doesn't define RTLD_LOCAL */
    int mode = RTLD_NOW;
1373
#endif
1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398
    if (!PyArg_ParseTuple(args, "O|i:dlopen", &name, &mode))
        return NULL;
    mode |= RTLD_NOW;
    if (name != Py_None) {
        if (PyUnicode_FSConverter(name, &name2) == 0)
            return NULL;
        if (PyBytes_Check(name2))
            name_str = PyBytes_AS_STRING(name2);
        else
            name_str = PyByteArray_AS_STRING(name2);
    } else {
        name_str = NULL;
        name2 = NULL;
    }
    handle = ctypes_dlopen(name_str, mode);
    Py_XDECREF(name2);
    if (!handle) {
        char *errmsg = ctypes_dlerror();
        if (!errmsg)
            errmsg = "dlopen() error";
        PyErr_SetString(PyExc_OSError,
                               errmsg);
        return NULL;
    }
    return PyLong_FromVoidPtr(handle);
1399 1400 1401 1402
}

static PyObject *py_dl_close(PyObject *self, PyObject *args)
{
1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413
    void *handle;

    if (!PyArg_ParseTuple(args, "O&:dlclose", &_parse_voidp, &handle))
        return NULL;
    if (dlclose(handle)) {
        PyErr_SetString(PyExc_OSError,
                               ctypes_dlerror());
        return NULL;
    }
    Py_INCREF(Py_None);
    return Py_None;
1414 1415 1416 1417
}

static PyObject *py_dl_sym(PyObject *self, PyObject *args)
{
1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431
    char *name;
    void *handle;
    void *ptr;

    if (!PyArg_ParseTuple(args, "O&s:dlsym",
                          &_parse_voidp, &handle, &name))
        return NULL;
    ptr = ctypes_dlsym((void*)handle, name);
    if (!ptr) {
        PyErr_SetString(PyExc_OSError,
                               ctypes_dlerror());
        return NULL;
    }
    return PyLong_FromVoidPtr(ptr);
1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442
}
#endif

/*
 * Only for debugging so far: So that we can call CFunction instances
 *
 * XXX Needs to accept more arguments: flags, argtypes, restype
 */
static PyObject *
call_function(PyObject *self, PyObject *args)
{
1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454
    void *func;
    PyObject *arguments;
    PyObject *result;

    if (!PyArg_ParseTuple(args,
                          "O&O!",
                          &_parse_voidp, &func,
                          &PyTuple_Type, &arguments))
        return NULL;

    result =  _ctypes_callproc((PPROC)func,
                        arguments,
1455
#ifdef MS_WIN32
1456 1457
                        NULL,
                        NULL,
1458
#endif
1459 1460 1461 1462 1463
                        0, /* flags */
                NULL, /* self->argtypes */
                NULL, /* self->restype */
                NULL); /* checker */
    return result;
1464 1465 1466 1467 1468 1469 1470 1471 1472 1473
}

/*
 * Only for debugging so far: So that we can call CFunction instances
 *
 * XXX Needs to accept more arguments: flags, argtypes, restype
 */
static PyObject *
call_cdeclfunction(PyObject *self, PyObject *args)
{
1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485
    void *func;
    PyObject *arguments;
    PyObject *result;

    if (!PyArg_ParseTuple(args,
                          "O&O!",
                          &_parse_voidp, &func,
                          &PyTuple_Type, &arguments))
        return NULL;

    result =  _ctypes_callproc((PPROC)func,
                        arguments,
1486
#ifdef MS_WIN32
1487 1488
                        NULL,
                        NULL,
1489
#endif
1490 1491 1492 1493 1494
                        FUNCFLAG_CDECL, /* flags */
                NULL, /* self->argtypes */
                NULL, /* self->restype */
                NULL); /* checker */
    return result;
1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507
}

/*****************************************************************
 * functions
 */
static char sizeof_doc[] =
"sizeof(C type) -> integer\n"
"sizeof(C instance) -> integer\n"
"Return the size in bytes of a C instance";

static PyObject *
sizeof_func(PyObject *self, PyObject *obj)
{
1508
    StgDictObject *dict;
1509

1510 1511 1512
    dict = PyType_stgdict(obj);
    if (dict)
        return PyLong_FromSsize_t(dict->size);
1513

1514 1515 1516 1517 1518
    if (CDataObject_Check(obj))
        return PyLong_FromSsize_t(((CDataObject *)obj)->b_size);
    PyErr_SetString(PyExc_TypeError,
                    "this type has no size");
    return NULL;
1519 1520 1521 1522 1523 1524 1525 1526 1527 1528
}

static char alignment_doc[] =
"alignment(C type) -> integer\n"
"alignment(C instance) -> integer\n"
"Return the alignment requirements of a C instance";

static PyObject *
align_func(PyObject *self, PyObject *obj)
{
1529
    StgDictObject *dict;
1530

1531 1532 1533
    dict = PyType_stgdict(obj);
    if (dict)
        return PyLong_FromSsize_t(dict->align);
1534

1535 1536 1537
    dict = PyObject_stgdict(obj);
    if (dict)
        return PyLong_FromSsize_t(dict->align);
1538

1539 1540 1541
    PyErr_SetString(PyExc_TypeError,
                    "no alignment info");
    return NULL;
1542 1543 1544
}

static char byref_doc[] =
1545
"byref(C instance[, offset=0]) -> byref-object\n"
1546 1547 1548 1549 1550 1551 1552 1553
"Return a pointer lookalike to a C instance, only usable\n"
"as function argument";

/*
 * We must return something which can be converted to a parameter,
 * but still has a reference to self.
 */
static PyObject *
1554
byref(PyObject *self, PyObject *args)
1555
{
1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585
    PyCArgObject *parg;
    PyObject *obj;
    PyObject *pyoffset = NULL;
    Py_ssize_t offset = 0;

    if (!PyArg_UnpackTuple(args, "byref", 1, 2,
                           &obj, &pyoffset))
        return NULL;
    if (pyoffset) {
        offset = PyNumber_AsSsize_t(pyoffset, NULL);
        if (offset == -1 && PyErr_Occurred())
            return NULL;
    }
    if (!CDataObject_Check(obj)) {
        PyErr_Format(PyExc_TypeError,
                     "byref() argument must be a ctypes instance, not '%s'",
                     Py_TYPE(obj)->tp_name);
        return NULL;
    }

    parg = PyCArgObject_new();
    if (parg == NULL)
        return NULL;

    parg->tag = 'P';
    parg->pffi_type = &ffi_type_pointer;
    Py_INCREF(obj);
    parg->obj = obj;
    parg->value.p = (char *)((CDataObject *)obj)->b_ptr + offset;
    return (PyObject *)parg;
1586 1587 1588 1589 1590 1591 1592 1593 1594
}

static char addressof_doc[] =
"addressof(C instance) -> integer\n"
"Return the address of the C instance internal buffer";

static PyObject *
addressof(PyObject *self, PyObject *obj)
{
1595 1596 1597 1598 1599
    if (CDataObject_Check(obj))
        return PyLong_FromVoidPtr(((CDataObject *)obj)->b_ptr);
    PyErr_SetString(PyExc_TypeError,
                    "invalid type");
    return NULL;
1600 1601 1602 1603 1604
}

static int
converter(PyObject *obj, void **address)
{
1605 1606
    *address = PyLong_AsVoidPtr(obj);
    return *address != NULL;
1607 1608 1609 1610 1611
}

static PyObject *
My_PyObj_FromPtr(PyObject *self, PyObject *args)
{
1612 1613 1614 1615 1616
    PyObject *ob;
    if (!PyArg_ParseTuple(args, "O&:PyObj_FromPtr", converter, &ob))
        return NULL;
    Py_INCREF(ob);
    return ob;
1617 1618 1619 1620 1621
}

static PyObject *
My_Py_INCREF(PyObject *self, PyObject *arg)
{
1622 1623 1624
    Py_INCREF(arg); /* that's what this function is for */
    Py_INCREF(arg); /* that for returning it */
    return arg;
1625 1626 1627 1628 1629
}

static PyObject *
My_Py_DECREF(PyObject *self, PyObject *arg)
{
1630 1631 1632
    Py_DECREF(arg); /* that's what this function is for */
    Py_INCREF(arg); /* that's for returning it */
    return arg;
1633 1634
}

1635 1636 1637
static PyObject *
resize(PyObject *self, PyObject *args)
{
1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685
    CDataObject *obj;
    StgDictObject *dict;
    Py_ssize_t size;

    if (!PyArg_ParseTuple(args,
                          "On:resize",
                          &obj, &size))
        return NULL;

    dict = PyObject_stgdict((PyObject *)obj);
    if (dict == NULL) {
        PyErr_SetString(PyExc_TypeError,
                        "excepted ctypes instance");
        return NULL;
    }
    if (size < dict->size) {
        PyErr_Format(PyExc_ValueError,
                     "minimum size is %zd",
                     dict->size);
        return NULL;
    }
    if (obj->b_needsfree == 0) {
        PyErr_Format(PyExc_ValueError,
                     "Memory cannot be resized because this object doesn't own it");
        return NULL;
    }
    if (size <= sizeof(obj->b_value)) {
        /* internal default buffer is large enough */
        obj->b_size = size;
        goto done;
    }
    if (obj->b_size <= sizeof(obj->b_value)) {
        /* We are currently using the objects default buffer, but it
           isn't large enough any more. */
        void *ptr = PyMem_Malloc(size);
        if (ptr == NULL)
            return PyErr_NoMemory();
        memset(ptr, 0, size);
        memmove(ptr, obj->b_ptr, obj->b_size);
        obj->b_ptr = ptr;
        obj->b_size = size;
    } else {
        void * ptr = PyMem_Realloc(obj->b_ptr, size);
        if (ptr == NULL)
            return PyErr_NoMemory();
        obj->b_ptr = ptr;
        obj->b_size = size;
    }
1686
  done:
1687 1688
    Py_INCREF(Py_None);
    return Py_None;
1689 1690
}

1691 1692 1693
static PyObject *
unpickle(PyObject *self, PyObject *args)
{
1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710
    PyObject *typ;
    PyObject *state;
    PyObject *result;
    PyObject *tmp;

    if (!PyArg_ParseTuple(args, "OO", &typ, &state))
        return NULL;
    result = PyObject_CallMethod(typ, "__new__", "O", typ);
    if (result == NULL)
        return NULL;
    tmp = PyObject_CallMethod(result, "__setstate__", "O", state);
    if (tmp == NULL) {
        Py_DECREF(result);
        return NULL;
    }
    Py_DECREF(tmp);
    return result;
1711 1712
}

1713 1714 1715
static PyObject *
POINTER(PyObject *self, PyObject *cls)
{
1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760
    PyObject *result;
    PyTypeObject *typ;
    PyObject *key;
    char *buf;

    result = PyDict_GetItem(_ctypes_ptrtype_cache, cls);
    if (result) {
        Py_INCREF(result);
        return result;
    }
    if (PyUnicode_CheckExact(cls)) {
        char *name = _PyUnicode_AsString(cls);
        buf = alloca(strlen(name) + 3 + 1);
        sprintf(buf, "LP_%s", name);
        result = PyObject_CallFunction((PyObject *)Py_TYPE(&PyCPointer_Type),
                                       "s(O){}",
                                       buf,
                                       &PyCPointer_Type);
        if (result == NULL)
            return result;
        key = PyLong_FromVoidPtr(result);
    } else if (PyType_Check(cls)) {
        typ = (PyTypeObject *)cls;
        buf = alloca(strlen(typ->tp_name) + 3 + 1);
        sprintf(buf, "LP_%s", typ->tp_name);
        result = PyObject_CallFunction((PyObject *)Py_TYPE(&PyCPointer_Type),
                                       "s(O){sO}",
                                       buf,
                                       &PyCPointer_Type,
                                       "_type_", cls);
        if (result == NULL)
            return result;
        Py_INCREF(cls);
        key = cls;
    } else {
        PyErr_SetString(PyExc_TypeError, "must be a ctypes type");
        return NULL;
    }
    if (-1 == PyDict_SetItem(_ctypes_ptrtype_cache, key, result)) {
        Py_DECREF(result);
        Py_DECREF(key);
        return NULL;
    }
    Py_DECREF(key);
    return result;
1761 1762 1763 1764 1765
}

static PyObject *
pointer(PyObject *self, PyObject *arg)
{
1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777
    PyObject *result;
    PyObject *typ;

    typ = PyDict_GetItem(_ctypes_ptrtype_cache, (PyObject *)Py_TYPE(arg));
    if (typ)
        return PyObject_CallFunctionObjArgs(typ, arg, NULL);
    typ = POINTER(NULL, (PyObject *)Py_TYPE(arg));
    if (typ == NULL)
                    return NULL;
    result = PyObject_CallFunctionObjArgs(typ, arg, NULL);
    Py_DECREF(typ);
    return result;
1778 1779
}

Thomas Heller's avatar
Thomas Heller committed
1780 1781 1782
static PyObject *
buffer_info(PyObject *self, PyObject *arg)
{
1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804
    StgDictObject *dict = PyType_stgdict(arg);
    PyObject *shape;
    Py_ssize_t i;

    if (dict == NULL)
        dict = PyObject_stgdict(arg);
    if (dict == NULL) {
        PyErr_SetString(PyExc_TypeError,
                        "not a ctypes type or object");
        return NULL;
    }
    shape = PyTuple_New(dict->ndim);
    if (shape == NULL)
        return NULL;
    for (i = 0; i < (int)dict->ndim; ++i)
        PyTuple_SET_ITEM(shape, i, PyLong_FromSsize_t(dict->shape[i]));

    if (PyErr_Occurred()) {
        Py_DECREF(shape);
        return NULL;
    }
    return Py_BuildValue("siN", dict->format, dict->ndim, shape);
Thomas Heller's avatar
Thomas Heller committed
1805 1806
}

1807
PyMethodDef _ctypes_module_methods[] = {
1808 1809 1810 1811 1812 1813 1814
    {"get_errno", get_errno, METH_NOARGS},
    {"set_errno", set_errno, METH_VARARGS},
    {"POINTER", POINTER, METH_O },
    {"pointer", pointer, METH_O },
    {"_unpickle", unpickle, METH_VARARGS },
    {"buffer_info", buffer_info, METH_O, "Return buffer interface information"},
    {"resize", resize, METH_VARARGS, "Resize the memory buffer of a ctypes instance"},
1815
#ifdef MS_WIN32
1816 1817 1818 1819 1820 1821 1822 1823
    {"get_last_error", get_last_error, METH_NOARGS},
    {"set_last_error", set_last_error, METH_VARARGS},
    {"CopyComPointer", copy_com_pointer, METH_VARARGS, copy_com_pointer_doc},
    {"FormatError", format_error, METH_VARARGS, format_error_doc},
    {"LoadLibrary", load_library, METH_VARARGS, load_library_doc},
    {"FreeLibrary", free_library, METH_VARARGS, free_library_doc},
    {"call_commethod", call_commethod, METH_VARARGS },
    {"_check_HRESULT", check_hresult, METH_VARARGS},
1824
#else
1825 1826 1827 1828
    {"dlopen", py_dl_open, METH_VARARGS,
     "dlopen(name, flag={RTLD_GLOBAL|RTLD_LOCAL}) open a shared library"},
    {"dlclose", py_dl_close, METH_VARARGS, "dlclose a library"},
    {"dlsym", py_dl_sym, METH_VARARGS, "find symbol in shared library"},
1829
#endif
1830 1831 1832 1833 1834 1835 1836 1837 1838 1839
    {"alignment", align_func, METH_O, alignment_doc},
    {"sizeof", sizeof_func, METH_O, sizeof_doc},
    {"byref", byref, METH_VARARGS, byref_doc},
    {"addressof", addressof, METH_O, addressof_doc},
    {"call_function", call_function, METH_VARARGS },
    {"call_cdeclfunction", call_cdeclfunction, METH_VARARGS },
    {"PyObj_FromPtr", My_PyObj_FromPtr, METH_VARARGS },
    {"Py_INCREF", My_Py_INCREF, METH_O },
    {"Py_DECREF", My_Py_DECREF, METH_O },
    {NULL,      NULL}        /* Sentinel */
1840 1841 1842 1843 1844 1845 1846
};

/*
 Local Variables:
 compile-command: "cd .. && python setup.py -q build -g && python setup.py -q build install --home ~"
 End:
*/