PageRenderTime 201ms CodeModel.GetById 40ms app.highlight 117ms RepoModel.GetById 14ms app.codeStats 1ms

/Modules/_ctypes/callproc.c

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