callbacks.c 16.9 KB
Newer Older
1 2 3 4 5 6 7 8 9
#include "Python.h"
#include "frameobject.h"

#include <ffi.h>
#ifdef MS_WIN32
#include <windows.h>
#endif
#include "ctypes.h"

10 11
/**************************************************************/

Thomas Heller's avatar
Thomas Heller committed
12
static void
13
CThunkObject_dealloc(PyObject *myself)
14
{
15
    CThunkObject *self = (CThunkObject *)myself;
16
    PyObject_GC_UnTrack(self);
17 18 19
    Py_XDECREF(self->converters);
    Py_XDECREF(self->callable);
    Py_XDECREF(self->restype);
20 21
    if (self->pcl_write)
        ffi_closure_free(self->pcl_write);
22
    PyObject_GC_Del(self);
23 24 25
}

static int
26
CThunkObject_traverse(PyObject *myself, visitproc visit, void *arg)
27
{
28
    CThunkObject *self = (CThunkObject *)myself;
29 30 31 32
    Py_VISIT(self->converters);
    Py_VISIT(self->callable);
    Py_VISIT(self->restype);
    return 0;
33 34 35
}

static int
36
CThunkObject_clear(PyObject *myself)
37
{
38
    CThunkObject *self = (CThunkObject *)myself;
39 40 41 42
    Py_CLEAR(self->converters);
    Py_CLEAR(self->callable);
    Py_CLEAR(self->restype);
    return 0;
43 44
}

45
PyTypeObject PyCThunk_Type = {
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
    PyVarObject_HEAD_INIT(NULL, 0)
    "_ctypes.CThunkObject",
    sizeof(CThunkObject),                       /* tp_basicsize */
    sizeof(ffi_type),                           /* tp_itemsize */
    CThunkObject_dealloc,                       /* tp_dealloc */
    0,                                          /* tp_print */
    0,                                          /* tp_getattr */
    0,                                          /* tp_setattr */
    0,                                          /* tp_reserved */
    0,                                          /* 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 | Py_TPFLAGS_HAVE_GC,                            /* tp_flags */
    "CThunkObject",                             /* tp_doc */
    CThunkObject_traverse,                      /* tp_traverse */
    CThunkObject_clear,                         /* tp_clear */
    0,                                          /* tp_richcompare */
    0,                                          /* tp_weaklistoffset */
    0,                                          /* tp_iter */
    0,                                          /* tp_iternext */
    0,                                          /* tp_methods */
    0,                                          /* tp_members */
75 76 77 78
};

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

79
static void
80
PrintError(const char *msg, ...)
81
{
82
    char buf[512];
83
    PyObject *f = PySys_GetObject("stderr");
84 85 86 87 88 89 90 91
    va_list marker;

    va_start(marker, msg);
    vsnprintf(buf, sizeof(buf), msg, marker);
    va_end(marker);
    if (f != NULL && f != Py_None)
        PyFile_WriteString(buf, f);
    PyErr_Print();
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
}


#ifdef MS_WIN32
/*
 * We must call AddRef() on non-NULL COM pointers we receive as arguments
 * to callback functions - these functions are COM method implementations.
 * The Python instances we create have a __del__ method which calls Release().
 *
 * The presence of a class attribute named '_needs_com_addref_' triggers this
 * behaviour.  It would also be possible to call the AddRef() Python method,
 * after checking for PyObject_IsTrue(), but this would probably be somewhat
 * slower.
 */
static void
TryAddRef(StgDictObject *dict, CDataObject *obj)
{
109
    IUnknown *punk;
110

111 112
    if (NULL == PyDict_GetItemString((PyObject *)dict, "_needs_com_addref_"))
        return;
113

114 115 116 117
    punk = *(IUnknown **)obj->b_ptr;
    if (punk)
        punk->lpVtbl->AddRef(punk);
    return;
118 119 120 121 122 123 124 125 126
}
#endif

/******************************************************************************
 *
 * Call the python object with all arguments
 *
 */
static void _CallPythonObject(void *mem,
127 128 129 130 131 132
                              ffi_type *restype,
                              SETFUNC setfunc,
                              PyObject *callable,
                              PyObject *converters,
                              int flags,
                              void **pArgs)
133
{
134 135 136 137 138 139 140
    Py_ssize_t i;
    PyObject *result;
    PyObject *arglist = NULL;
    Py_ssize_t nArgs;
    PyObject *error_object = NULL;
    int *space;
    PyGILState_STATE state = PyGILState_Ensure();
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 166 167 168 169 170 171 172 173 174 175 176 177
    nArgs = PySequence_Length(converters);
    /* Hm. What to return in case of error?
       For COM, 0xFFFFFFFF seems better than 0.
    */
    if (nArgs < 0) {
        PrintError("BUG: PySequence_Length");
        goto Done;
    }

    arglist = PyTuple_New(nArgs);
    if (!arglist) {
        PrintError("PyTuple_New()");
        goto Done;
    }
    for (i = 0; i < nArgs; ++i) {
        /* Note: new reference! */
        PyObject *cnv = PySequence_GetItem(converters, i);
        StgDictObject *dict;
        if (cnv)
            dict = PyType_stgdict(cnv);
        else {
            PrintError("Getting argument converter %d\n", i);
            goto Done;
        }

        if (dict && dict->getfunc && !_ctypes_simple_instance(cnv)) {
            PyObject *v = dict->getfunc(*pArgs, dict->size);
            if (!v) {
                PrintError("create argument %d:\n", i);
                Py_DECREF(cnv);
                goto Done;
            }
            PyTuple_SET_ITEM(arglist, i, v);
            /* XXX XXX XX
               We have the problem that c_byte or c_short have dict->size of
               1 resp. 4, but these parameters are pushed as sizeof(int) bytes.
178
               BTW, the same problem occurs when they are pushed as parameters
179 180 181
            */
        } else if (dict) {
            /* Hm, shouldn't we use PyCData_AtAddress() or something like that instead? */
182
            CDataObject *obj = (CDataObject *)_PyObject_CallNoArg(cnv);
183 184 185 186 187 188 189 190 191 192 193 194 195
            if (!obj) {
                PrintError("create argument %d:\n", i);
                Py_DECREF(cnv);
                goto Done;
            }
            if (!CDataObject_Check(obj)) {
                Py_DECREF(obj);
                Py_DECREF(cnv);
                PrintError("unexpected result of create argument %d:\n", i);
                goto Done;
            }
            memcpy(obj->b_ptr, *pArgs, dict->size);
            PyTuple_SET_ITEM(arglist, i, (PyObject *)obj);
196
#ifdef MS_WIN32
197
            TryAddRef(dict, obj);
198
#endif
199 200 201 202 203 204 205 206 207 208 209
        } else {
            PyErr_SetString(PyExc_TypeError,
                            "cannot build parameter");
            PrintError("Parsing argument %d\n", i);
            Py_DECREF(cnv);
            goto Done;
        }
        Py_DECREF(cnv);
        /* XXX error handling! */
        pArgs++;
    }
210 211

#define CHECK(what, x) \
212
if (x == NULL) _PyTraceback_Add(what, "_ctypes/callbacks.c", __LINE__ - 1), PyErr_Print()
213

214 215 216 217 218 219 220 221 222
    if (flags & (FUNCFLAG_USE_ERRNO | FUNCFLAG_USE_LASTERROR)) {
        error_object = _ctypes_get_errobj(&space);
        if (error_object == NULL)
            goto Done;
        if (flags & FUNCFLAG_USE_ERRNO) {
            int temp = space[0];
            space[0] = errno;
            errno = temp;
        }
223
#ifdef MS_WIN32
224 225 226 227 228
        if (flags & FUNCFLAG_USE_LASTERROR) {
            int temp = space[1];
            space[1] = GetLastError();
            SetLastError(temp);
        }
229
#endif
230
    }
231

232 233
    result = PyObject_CallObject(callable, arglist);
    CHECK("'calling callback function'", result);
234 235

#ifdef MS_WIN32
236 237 238 239 240
    if (flags & FUNCFLAG_USE_LASTERROR) {
        int temp = space[1];
        space[1] = GetLastError();
        SetLastError(temp);
    }
241
#endif
242 243 244 245 246 247 248 249 250 251
    if (flags & FUNCFLAG_USE_ERRNO) {
        int temp = space[0];
        space[0] = errno;
        errno = temp;
    }
    Py_XDECREF(error_object);

    if ((restype != &ffi_type_void) && result) {
        PyObject *keep;
        assert(setfunc);
252
#ifdef WORDS_BIGENDIAN
253 254 255
        /* See the corresponding code in callproc.c, around line 961 */
        if (restype->type != FFI_TYPE_FLOAT && restype->size < sizeof(ffi_arg))
            mem = (char *)mem + sizeof(ffi_arg) - restype->size;
256
#endif
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
        keep = setfunc(mem, result, 0);
        CHECK("'converting callback result'", keep);
        /* keep is an object we have to keep alive so that the result
           stays valid.  If there is no such object, the setfunc will
           have returned Py_None.

           If there is such an object, we have no choice than to keep
           it alive forever - but a refcount and/or memory leak will
           be the result.  EXCEPT when restype is py_object - Python
           itself knows how to manage the refcount of these objects.
        */
        if (keep == NULL) /* Could not convert callback result. */
            PyErr_WriteUnraisable(callable);
        else if (keep == Py_None) /* Nothing to keep */
            Py_DECREF(keep);
        else if (setfunc != _ctypes_get_fielddesc("O")->setfunc) {
            if (-1 == PyErr_WarnEx(PyExc_RuntimeWarning,
                                   "memory leak in callback function.",
                                   1))
                PyErr_WriteUnraisable(callable);
        }
    }
    Py_XDECREF(result);
280
  Done:
281 282
    Py_XDECREF(arglist);
    PyGILState_Release(state);
283 284 285
}

static void closure_fcn(ffi_cif *cif,
286 287 288
                        void *resp,
                        void **args,
                        void *userdata)
289
{
290 291 292 293 294 295 296 297 298
    CThunkObject *p = (CThunkObject *)userdata;

    _CallPythonObject(resp,
                      p->ffi_restype,
                      p->setfunc,
                      p->callable,
                      p->converters,
                      p->flags,
                      args);
299 300
}

301 302
static CThunkObject* CThunkObject_new(Py_ssize_t nArgs)
{
303
    CThunkObject *p;
304
    Py_ssize_t i;
305 306 307 308 309 310 311

    p = PyObject_GC_NewVar(CThunkObject, &PyCThunk_Type, nArgs);
    if (p == NULL) {
        PyErr_NoMemory();
        return NULL;
    }

312
    p->pcl_write = NULL;
313
    p->pcl_exec = NULL;
314
    memset(&p->cif, 0, sizeof(p->cif));
315
    p->flags = 0;
316 317
    p->converters = NULL;
    p->callable = NULL;
318
    p->restype = NULL;
319 320 321 322 323 324 325
    p->setfunc = NULL;
    p->ffi_restype = NULL;

    for (i = 0; i < nArgs + 1; ++i)
        p->atypes[i] = NULL;
    PyObject_GC_Track((PyObject *)p);
    return p;
326 327
}

328
CThunkObject *_ctypes_alloc_callback(PyObject *callable,
329 330 331
                                    PyObject *converters,
                                    PyObject *restype,
                                    int flags)
332
{
333 334 335 336 337 338 339 340 341 342 343 344
    int result;
    CThunkObject *p;
    Py_ssize_t nArgs, i;
    ffi_abi cc;

    nArgs = PySequence_Size(converters);
    p = CThunkObject_new(nArgs);
    if (p == NULL)
        return NULL;

    assert(CThunk_CheckExact((PyObject *)p));

345
    p->pcl_write = ffi_closure_alloc(sizeof(ffi_closure),
346
                                                                         &p->pcl_exec);
347
    if (p->pcl_write == NULL) {
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
        PyErr_NoMemory();
        goto error;
    }

    p->flags = flags;
    for (i = 0; i < nArgs; ++i) {
        PyObject *cnv = PySequence_GetItem(converters, i);
        if (cnv == NULL)
            goto error;
        p->atypes[i] = _ctypes_get_ffi_type(cnv);
        Py_DECREF(cnv);
    }
    p->atypes[i] = NULL;

    Py_INCREF(restype);
    p->restype = restype;
    if (restype == Py_None) {
        p->setfunc = NULL;
        p->ffi_restype = &ffi_type_void;
    } else {
        StgDictObject *dict = PyType_stgdict(restype);
        if (dict == NULL || dict->setfunc == NULL) {
          PyErr_SetString(PyExc_TypeError,
                          "invalid result type for callback function");
          goto error;
        }
        p->setfunc = dict->setfunc;
        p->ffi_restype = &dict->ffi_type_pointer;
    }

    cc = FFI_DEFAULT_ABI;
379
#if defined(MS_WIN32) && !defined(_WIN32_WCE) && !defined(MS_WIN64)
380 381
    if ((flags & FUNCFLAG_CDECL) == 0)
        cc = FFI_STDCALL;
382
#endif
383 384 385 386 387 388 389 390 391
    result = ffi_prep_cif(&p->cif, cc,
                          Py_SAFE_DOWNCAST(nArgs, Py_ssize_t, int),
                          _ctypes_get_ffi_type(restype),
                          &p->atypes[0]);
    if (result != FFI_OK) {
        PyErr_Format(PyExc_RuntimeError,
                     "ffi_prep_cif failed with %d", result);
        goto error;
    }
392 393 394
#if defined(X86_DARWIN) || defined(POWERPC_DARWIN)
    result = ffi_prep_closure(p->pcl_write, &p->cif, closure_fcn, p);
#else
395
    result = ffi_prep_closure_loc(p->pcl_write, &p->cif, closure_fcn,
396 397
                                  p,
                                  p->pcl_exec);
398
#endif
399 400 401 402 403 404 405 406 407 408 409
    if (result != FFI_OK) {
        PyErr_Format(PyExc_RuntimeError,
                     "ffi_prep_closure failed with %d", result);
        goto error;
    }

    Py_INCREF(converters);
    p->converters = converters;
    Py_INCREF(callable);
    p->callable = callable;
    return p;
410

411
  error:
412 413
    Py_XDECREF(p);
    return NULL;
414 415 416 417 418 419
}

#ifdef MS_WIN32

static void LoadPython(void)
{
420 421 422 423
    if (!Py_IsInitialized()) {
        PyEval_InitThreads();
        Py_Initialize();
    }
424 425 426 427 428 429
}

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

long Call_GetClassObject(REFCLSID rclsid, REFIID riid, LPVOID *ppv)
{
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
    PyObject *mod, *func, *result;
    long retval;
    static PyObject *context;

    if (context == NULL)
        context = PyUnicode_InternFromString("_ctypes.DllGetClassObject");

    mod = PyImport_ImportModuleNoBlock("ctypes");
    if (!mod) {
        PyErr_WriteUnraisable(context ? context : Py_None);
        /* There has been a warning before about this already */
        return E_FAIL;
    }

    func = PyObject_GetAttrString(mod, "DllGetClassObject");
    Py_DECREF(mod);
    if (!func) {
        PyErr_WriteUnraisable(context ? context : Py_None);
        return E_FAIL;
    }

    {
        PyObject *py_rclsid = PyLong_FromVoidPtr((void *)rclsid);
        PyObject *py_riid = PyLong_FromVoidPtr((void *)riid);
        PyObject *py_ppv = PyLong_FromVoidPtr(ppv);
        if (!py_rclsid || !py_riid || !py_ppv) {
            Py_XDECREF(py_rclsid);
            Py_XDECREF(py_riid);
            Py_XDECREF(py_ppv);
            Py_DECREF(func);
            PyErr_WriteUnraisable(context ? context : Py_None);
            return E_FAIL;
        }
        result = PyObject_CallFunctionObjArgs(func,
                                              py_rclsid,
                                              py_riid,
                                              py_ppv,
                                              NULL);
        Py_DECREF(py_rclsid);
        Py_DECREF(py_riid);
        Py_DECREF(py_ppv);
    }
    Py_DECREF(func);
    if (!result) {
        PyErr_WriteUnraisable(context ? context : Py_None);
        return E_FAIL;
    }

    retval = PyLong_AsLong(result);
    if (PyErr_Occurred()) {
        PyErr_WriteUnraisable(context ? context : Py_None);
        retval = E_FAIL;
    }
    Py_DECREF(result);
    return retval;
485 486 487
}

STDAPI DllGetClassObject(REFCLSID rclsid,
488 489
                         REFIID riid,
                         LPVOID *ppv)
490
{
491 492
    long result;
    PyGILState_STATE state;
493

494 495 496 497 498
    LoadPython();
    state = PyGILState_Ensure();
    result = Call_GetClassObject(rclsid, riid, ppv);
    PyGILState_Release(state);
    return result;
499 500 501 502
}

long Call_CanUnloadNow(void)
{
503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525
    PyObject *mod, *func, *result;
    long retval;
    static PyObject *context;

    if (context == NULL)
        context = PyUnicode_InternFromString("_ctypes.DllCanUnloadNow");

    mod = PyImport_ImportModuleNoBlock("ctypes");
    if (!mod) {
/*              OutputDebugString("Could not import ctypes"); */
        /* We assume that this error can only occur when shutting
           down, so we silently ignore it */
        PyErr_Clear();
        return E_FAIL;
    }
    /* Other errors cannot be raised, but are printed to stderr */
    func = PyObject_GetAttrString(mod, "DllCanUnloadNow");
    Py_DECREF(mod);
    if (!func) {
        PyErr_WriteUnraisable(context ? context : Py_None);
        return E_FAIL;
    }

526
    result = _PyObject_CallNoArg(func);
527 528 529 530 531 532 533 534 535 536 537 538 539
    Py_DECREF(func);
    if (!result) {
        PyErr_WriteUnraisable(context ? context : Py_None);
        return E_FAIL;
    }

    retval = PyLong_AsLong(result);
    if (PyErr_Occurred()) {
        PyErr_WriteUnraisable(context ? context : Py_None);
        retval = E_FAIL;
    }
    Py_DECREF(result);
    return retval;
540 541 542 543 544 545 546 547
}

/*
  DllRegisterServer and DllUnregisterServer still missing
*/

STDAPI DllCanUnloadNow(void)
{
548 549 550 551 552
    long result;
    PyGILState_STATE state = PyGILState_Ensure();
    result = Call_CanUnloadNow();
    PyGILState_Release(state);
    return result;
553 554 555 556 557
}

#ifndef Py_NO_ENABLE_SHARED
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvRes)
{
558 559 560 561 562 563
    switch(fdwReason) {
    case DLL_PROCESS_ATTACH:
        DisableThreadLibraryCalls(hinstDLL);
        break;
    }
    return TRUE;
564 565 566 567 568 569 570 571 572 573
}
#endif

#endif

/*
 Local Variables:
 compile-command: "cd .. && python setup.py -q build_ext"
 End:
*/