/Modules/_ctypes/callproc.c

http://unladen-swallow.googlecode.com/ · C · 1912 lines · 1472 code · 172 blank · 268 comment · 252 complexity · f80ef6b2976f15ba7b0e5bef1aae6f71 MD5 · raw file

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