Debian Codegraph @

Modules/_ctypes/_ctypes.c

raw
1 /*
2 ToDo:
3
4 Get rid of the checker (and also the converters) field in PyCFuncPtrObject and
5 StgInfo, and replace them by slot functions in StgInfo.
6
7 think about a buffer-like object (memory? bytes?)
8
9 Should POINTER(c_char) and POINTER(c_wchar) have a .value property?
10 What about c_char and c_wchar arrays then?
11
12 Add from_mmap, from_file, from_string metaclass methods.
13
14 Maybe we can get away with from_file (calls read) and with a from_buffer
15 method?
16
17 And what about the to_mmap, to_file, to_str(?) methods? They would clobber
18 the namespace, probably. So, functions instead? And we already have memmove...
19 */
20
21 /*
22
23 Name methods, members, getsets
24 ==============================================================================
25
26 PyCStructType_Type __new__(), from_address(), __mul__(), from_param()
27 UnionType_Type __new__(), from_address(), __mul__(), from_param()
28 PyCPointerType_Type __new__(), from_address(), __mul__(), from_param(), set_type()
29 PyCArrayType_Type __new__(), from_address(), __mul__(), from_param()
30 PyCSimpleType_Type __new__(), from_address(), __mul__(), from_param()
31
32 PyCData_Type
33 Struct_Type __new__(), __init__()
34 PyCPointer_Type __new__(), __init__(), _as_parameter_, contents
35 PyCArray_Type __new__(), __init__(), _as_parameter_, __get/setitem__(), __len__()
36 Simple_Type __new__(), __init__(), _as_parameter_
37
38 PyCField_Type
39
40 ==============================================================================
41
42 class methods
43 -------------
44
45 It has some similarity to the byref() construct compared to pointer()
46 from_address(addr)
47 - construct an instance from a given memory block (sharing this memory block)
48
49 from_param(obj)
50 - typecheck and convert a Python object into a C function call parameter
51 The result may be an instance of the type, or an integer or tuple
52 (typecode, value[, obj])
53
54 instance methods/properties
55 ---------------------------
56
57 _as_parameter_
58 - convert self into a C function call parameter
59 This is either an integer, or a 3-tuple (typecode, value, obj)
60
61 functions
62 ---------
63
64 sizeof(cdata)
65 - return the number of bytes the buffer contains
66
67 sizeof(ctype)
68 - return the number of bytes the buffer of an instance would contain
69
70 byref(cdata)
71
72 addressof(cdata)
73
74 pointer(cdata)
75
76 POINTER(ctype)
77
78 bytes(cdata)
79 - return the buffer contents as a sequence of bytes (which is currently a string)
80
81 */
82
83 /*
84 * PyCStructType_Type
85 * UnionType_Type
86 * PyCPointerType_Type
87 * PyCArrayType_Type
88 * PyCSimpleType_Type
89 *
90 * PyCData_Type
91 * Struct_Type
92 * Union_Type
93 * PyCArray_Type
94 * Simple_Type
95 * PyCPointer_Type
96 * PyCField_Type
97 *
98 */
99 #ifndef Py_BUILD_CORE_BUILTIN
100 # define Py_BUILD_CORE_MODULE 1
101 #endif
102
103 #include "Python.h"
104 // windows.h must be included before pycore internal headers
105 #ifdef MS_WIN32
106 # include <windows.h>
107 #endif
108
109 #include "pycore_call.h" // _PyObject_CallNoArgs()
110 #include "pycore_ceval.h" // _Py_EnterRecursiveCall()
111 #ifdef MS_WIN32
112 # include "pycore_modsupport.h" // _PyArg_NoKeywords()
113 #endif
114
115
116 #include <ffi.h>
117 #ifdef MS_WIN32
118 #include <malloc.h>
119 #ifndef IS_INTRESOURCE
120 #define IS_INTRESOURCE(x) (((size_t)(x) >> 16) == 0)
121 #endif
122 #else
123 #include <dlfcn.h>
124 #endif
125 #include "ctypes.h"
126
127 #include "pycore_long.h" // _PyLong_GetZero()
128
129 /*[clinic input]
130 module _ctypes
131 [clinic start generated code]*/
132 /*[clinic end generated code: output=da39a3ee5e6b4b0d input=476a19c49b31a75c]*/
133
134 #define clinic_state() (get_module_state_by_class(cls))
135 #define clinic_state_sub() (get_module_state_by_class(cls->tp_base))
136 #include "clinic/_ctypes.c.h"
137 #undef clinic_state
138 #undef clinic_state_sub
139
140 /****************************************************************/
141
142 typedef struct {
143 PyObject_HEAD
144 PyObject *key;
145 PyObject *dict;
146 } DictRemoverObject;
147
148 static int
149 _DictRemover_traverse(DictRemoverObject *self, visitproc visit, void *arg)
150 {
151 Py_VISIT(Py_TYPE(self));
152 Py_VISIT(self->key);
153 Py_VISIT(self->dict);
154 return 0;
155 }
156
157 static int
158 _DictRemover_clear(DictRemoverObject *self)
159 {
160 Py_CLEAR(self->key);
161 Py_CLEAR(self->dict);
162 return 0;
163 }
164
165 static void
166 _DictRemover_dealloc(PyObject *myself)
167 {
168 PyTypeObject *tp = Py_TYPE(myself);
169 DictRemoverObject *self = (DictRemoverObject *)myself;
170 PyObject_GC_UnTrack(myself);
171 (void)_DictRemover_clear(self);
172 tp->tp_free(myself);
173 Py_DECREF(tp);
174 }
175
176 static PyObject *
177 _DictRemover_call(PyObject *myself, PyObject *args, PyObject *kw)
178 {
179 DictRemoverObject *self = (DictRemoverObject *)myself;
180 if (self->key && self->dict) {
181 if (-1 == PyDict_DelItem(self->dict, self->key)) {
182 PyErr_FormatUnraisable("Exception ignored on calling _ctypes.DictRemover");
183 }
184 Py_CLEAR(self->key);
185 Py_CLEAR(self->dict);
186 }
187 Py_RETURN_NONE;
188 }
189
190 PyDoc_STRVAR(dictremover_doc, "deletes a key from a dictionary");
191
192 static PyType_Slot dictremover_slots[] = {
193 {Py_tp_dealloc, _DictRemover_dealloc},
194 {Py_tp_traverse, _DictRemover_traverse},
195 {Py_tp_clear, _DictRemover_clear},
196 {Py_tp_call, _DictRemover_call},
197 {Py_tp_doc, (void *)dictremover_doc},
198 {0, NULL},
199 };
200
201 static PyType_Spec dictremover_spec = {
202 .name = "_ctypes.DictRemover",
203 .basicsize = sizeof(DictRemoverObject),
204 .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
205 Py_TPFLAGS_IMMUTABLETYPE),
206 .slots = dictremover_slots,
207 };
208
209 int
210 PyDict_SetItemProxy(ctypes_state *st, PyObject *dict, PyObject *key, PyObject *item)
211 {
212 PyObject *obj;
213 DictRemoverObject *remover;
214 PyObject *proxy;
215 int result;
216
217 obj = _PyObject_CallNoArgs((PyObject *)st->DictRemover_Type);
218 if (obj == NULL)
219 return -1;
220
221 remover = (DictRemoverObject *)obj;
222 assert(remover->key == NULL);
223 assert(remover->dict == NULL);
224 remover->key = Py_NewRef(key);
225 remover->dict = Py_NewRef(dict);
226
227 proxy = PyWeakref_NewProxy(item, obj);
228 Py_DECREF(obj);
229 if (proxy == NULL)
230 return -1;
231
232 result = PyDict_SetItem(dict, key, proxy);
233 Py_DECREF(proxy);
234 return result;
235 }
236
237 static int
238 _PyDict_GetItemProxy(PyObject *dict, PyObject *key, PyObject **presult)
239 {
240 int rc = PyDict_GetItemRef(dict, key, presult);
241 PyObject *item = *presult;
242 if (item && PyWeakref_CheckProxy(item)) {
243 rc = PyWeakref_GetRef(item, presult);
244 Py_DECREF(item);
245 }
246 return rc;
247 }
248
249 /******************************************************************/
250
251 /*
252 Allocate a memory block for a pep3118 format string, filled with
253 a suitable PEP 3118 type code corresponding to the given ctypes
254 type. Returns NULL on failure, with the error indicator set.
255
256 This produces type codes in the standard size mode (cf. struct module),
257 since the endianness may need to be swapped to a non-native one
258 later on.
259 */
260 static char *
261 _ctypes_alloc_format_string_for_type(char code, int big_endian)
262 {
263 char *result;
264 char pep_code = '\0';
265
266 switch (code) {
267 #if SIZEOF_INT == 2
268 case 'i': pep_code = 'h'; break;
269 case 'I': pep_code = 'H'; break;
270 #elif SIZEOF_INT == 4
271 case 'i': pep_code = 'i'; break;
272 case 'I': pep_code = 'I'; break;
273 #elif SIZEOF_INT == 8
274 case 'i': pep_code = 'q'; break;
275 case 'I': pep_code = 'Q'; break;
276 #else
277 # error SIZEOF_INT has an unexpected value
278 #endif /* SIZEOF_INT */
279 #if SIZEOF_LONG == 4
280 case 'l': pep_code = 'l'; break;
281 case 'L': pep_code = 'L'; break;
282 #elif SIZEOF_LONG == 8
283 case 'l': pep_code = 'q'; break;
284 case 'L': pep_code = 'Q'; break;
285 #else
286 # error SIZEOF_LONG has an unexpected value
287 #endif /* SIZEOF_LONG */
288 #if SIZEOF__BOOL == 1
289 case '?': pep_code = '?'; break;
290 #elif SIZEOF__BOOL == 2
291 case '?': pep_code = 'H'; break;
292 #elif SIZEOF__BOOL == 4
293 case '?': pep_code = 'L'; break;
294 #elif SIZEOF__BOOL == 8
295 case '?': pep_code = 'Q'; break;
296 #else
297 # error SIZEOF__BOOL has an unexpected value
298 #endif /* SIZEOF__BOOL */
299 default:
300 /* The standard-size code is the same as the ctypes one */
301 pep_code = code;
302 break;
303 }
304
305 result = PyMem_Malloc(3);
306 if (result == NULL) {
307 PyErr_NoMemory();
308 return NULL;
309 }
310
311 result[0] = big_endian ? '>' : '<';
312 result[1] = pep_code;
313 result[2] = '\0';
314 return result;
315 }
316
317 /*
318 Allocate a memory block for a pep3118 format string, copy prefix (if
319 non-null) and suffix into it. Returns NULL on failure, with the error
320 indicator set. If called with a suffix of NULL the error indicator must
321 already be set.
322 */
323 char *
324 _ctypes_alloc_format_string(const char *prefix, const char *suffix)
325 {
326 size_t len;
327 char *result;
328
329 if (suffix == NULL) {
330 assert(PyErr_Occurred());
331 return NULL;
332 }
333 len = strlen(suffix);
334 if (prefix)
335 len += strlen(prefix);
336 result = PyMem_Malloc(len + 1);
337 if (result == NULL) {
338 PyErr_NoMemory();
339 return NULL;
340 }
341 if (prefix)
342 strcpy(result, prefix);
343 else
344 result[0] = '\0';
345 strcat(result, suffix);
346 return result;
347 }
348
349 /*
350 Allocate a memory block for a pep3118 format string, adding
351 the given prefix (if non-null), an additional shape prefix, and a suffix.
352 Returns NULL on failure, with the error indicator set. If called with
353 a suffix of NULL the error indicator must already be set.
354 */
355 char *
356 _ctypes_alloc_format_string_with_shape(int ndim, const Py_ssize_t *shape,
357 const char *prefix, const char *suffix)
358 {
359 char *new_prefix;
360 char *result;
361 char buf[32];
362 Py_ssize_t prefix_len;
363 int k;
364
365 prefix_len = 32 * ndim + 3;
366 if (prefix)
367 prefix_len += strlen(prefix);
368 new_prefix = PyMem_Malloc(prefix_len);
369 if (new_prefix == NULL) {
370 PyErr_NoMemory();
371 return NULL;
372 }
373 new_prefix[0] = '\0';
374 if (prefix)
375 strcpy(new_prefix, prefix);
376 if (ndim > 0) {
377 /* Add the prefix "(shape[0],shape[1],...,shape[ndim-1])" */
378 strcat(new_prefix, "(");
379 for (k = 0; k < ndim; ++k) {
380 if (k < ndim-1) {
381 sprintf(buf, "%zd,", shape[k]);
382 } else {
383 sprintf(buf, "%zd)", shape[k]);
384 }
385 strcat(new_prefix, buf);
386 }
387 }
388 result = _ctypes_alloc_format_string(new_prefix, suffix);
389 PyMem_Free(new_prefix);
390 return result;
391 }
392
393 /* StructParamObject and StructParam_Type are used in _ctypes_callproc()
394 for argument.keep to call PyMem_Free(ptr) on Py_DECREF(argument).
395
396 StructUnionType_paramfunc() creates such object when a ctypes Structure is
397 passed by copy to a C function. */
398 typedef struct {
399 PyObject_HEAD
400 void *ptr;
401 PyObject *keep; // If set, a reference to the original CDataObject.
402 } StructParamObject;
403
404 static int
405 StructParam_traverse(StructParamObject *self, visitproc visit, void *arg)
406 {
407 Py_VISIT(Py_TYPE(self));
408 return 0;
409 }
410
411 static int
412 StructParam_clear(StructParamObject *self)
413 {
414 Py_CLEAR(self->keep);
415 return 0;
416 }
417
418 static void
419 StructParam_dealloc(PyObject *myself)
420 {
421 StructParamObject *self = (StructParamObject *)myself;
422 PyTypeObject *tp = Py_TYPE(self);
423 PyObject_GC_UnTrack(myself);
424 (void)StructParam_clear(self);
425 PyMem_Free(self->ptr);
426 tp->tp_free(myself);
427 Py_DECREF(tp);
428 }
429
430 static PyType_Slot structparam_slots[] = {
431 {Py_tp_traverse, StructParam_traverse},
432 {Py_tp_clear, StructParam_clear},
433 {Py_tp_dealloc, StructParam_dealloc},
434 {0, NULL},
435 };
436
437 static PyType_Spec structparam_spec = {
438 .name = "_ctypes.StructParam_Type",
439 .basicsize = sizeof(StructParamObject),
440 .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_IMMUTABLETYPE |
441 Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_DISALLOW_INSTANTIATION),
442 .slots = structparam_slots,
443 };
444
445 /*
446 CType_Type - a base metaclass. Its instances (classes) have a StgInfo.
447 */
448
449 /*[clinic input]
450 class _ctypes.CType_Type "PyObject *" "clinic_state()->CType_Type"
451 [clinic start generated code]*/
452 /*[clinic end generated code: output=da39a3ee5e6b4b0d input=8389fc5b74a84f2a]*/
453
454 static int
455 CType_Type_traverse(PyObject *self, visitproc visit, void *arg)
456 {
457 StgInfo *info = _PyStgInfo_FromType_NoState(self);
458 if (!info) {
459 PyErr_WriteUnraisable(self);
460 }
461 if (info) {
462 Py_VISIT(info->proto);
463 Py_VISIT(info->argtypes);
464 Py_VISIT(info->converters);
465 Py_VISIT(info->restype);
466 Py_VISIT(info->checker);
467 Py_VISIT(info->module);
468 }
469 Py_VISIT(Py_TYPE(self));
470 return PyType_Type.tp_traverse(self, visit, arg);
471 }
472
473 void
474 ctype_clear_stginfo(StgInfo *info)
475 {
476 assert(info);
477 Py_CLEAR(info->proto);
478 Py_CLEAR(info->argtypes);
479 Py_CLEAR(info->converters);
480 Py_CLEAR(info->restype);
481 Py_CLEAR(info->checker);
482 Py_CLEAR(info->module);
483 }
484
485 static int
486 CType_Type_clear(PyObject *self)
487 {
488 StgInfo *info = _PyStgInfo_FromType_NoState(self);
489 if (!info) {
490 PyErr_WriteUnraisable(self);
491 }
492 if (info) {
493 ctype_clear_stginfo(info);
494 }
495 return PyType_Type.tp_clear(self);
496 }
497
498 static void
499 CType_Type_dealloc(PyObject *self)
500 {
501 StgInfo *info = _PyStgInfo_FromType_NoState(self);
502 if (!info) {
503 PyErr_WriteUnraisable(self);
504 }
505 if (info) {
506 PyMem_Free(info->ffi_type_pointer.elements);
507 info->ffi_type_pointer.elements = NULL;
508 PyMem_Free(info->format);
509 info->format = NULL;
510 PyMem_Free(info->shape);
511 info->shape = NULL;
512 ctype_clear_stginfo(info);
513 }
514
515 PyTypeObject *tp = Py_TYPE(self);
516 PyType_Type.tp_dealloc(self);
517 Py_DECREF(tp);
518 }
519
520 /*[clinic input]
521 _ctypes.CType_Type.__sizeof__
522
523 cls: defining_class
524 /
525 Return memory consumption of the type object.
526 [clinic start generated code]*/
527
528 static PyObject *
529 _ctypes_CType_Type___sizeof___impl(PyObject *self, PyTypeObject *cls)
530 /*[clinic end generated code: output=c68c235be84d03f3 input=d064433b6110d1ce]*/
531 {
532 Py_ssize_t size = Py_TYPE(self)->tp_basicsize;
533 size += Py_TYPE(self)->tp_itemsize * Py_SIZE(self);
534
535 ctypes_state *st = get_module_state_by_class(cls);
536 StgInfo *info;
537 if (PyStgInfo_FromType(st, self, &info) < 0) {
538 return NULL;
539 }
540 if (info) {
541 if (info->format) {
542 size += strlen(info->format) + 1;
543 }
544 if (info->ffi_type_pointer.elements) {
545 size += (info->length + 1) * sizeof(ffi_type *);
546 }
547 size += info->ndim * sizeof(Py_ssize_t);
548 }
549
550 return PyLong_FromSsize_t(size);
551 }
552
553 static PyObject *
554 CType_Type_repeat(PyObject *self, Py_ssize_t length);
555
556
557 static PyMethodDef ctype_methods[] = {
558 _CTYPES_CTYPE_TYPE___SIZEOF___METHODDEF
559 {0},
560 };
561
562 static PyType_Slot ctype_type_slots[] = {
563 {Py_tp_traverse, CType_Type_traverse},
564 {Py_tp_clear, CType_Type_clear},
565 {Py_tp_dealloc, CType_Type_dealloc},
566 {Py_tp_methods, ctype_methods},
567 // Sequence protocol.
568 {Py_sq_repeat, CType_Type_repeat},
569 {0, NULL},
570 };
571
572 static PyType_Spec pyctype_type_spec = {
573 .name = "_ctypes.CType_Type",
574 .basicsize = -(Py_ssize_t)sizeof(StgInfo),
575 .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_IMMUTABLETYPE |
576 Py_TPFLAGS_HAVE_GC |
577 Py_TPFLAGS_BASETYPE ),
578 .slots = ctype_type_slots,
579 };
580
581 /*
582 PyCStructType_Type - a meta type/class. Creating a new class using this one as
583 __metaclass__ will call the constructor StructUnionType_new.
584 It initializes the C accessible fields somehow.
585 */
586
587 static PyCArgObject *
588 StructUnionType_paramfunc(ctypes_state *st, CDataObject *self)
589 {
590 PyCArgObject *parg;
591 PyObject *obj;
592 void *ptr;
593
594 if ((size_t)self->b_size > sizeof(void*)) {
595 ptr = PyMem_Malloc(self->b_size);
596 if (ptr == NULL) {
597 return NULL;
598 }
599 memcpy(ptr, self->b_ptr, self->b_size);
600
601 /* Create a Python object which calls PyMem_Free(ptr) in
602 its deallocator. The object will be destroyed
603 at _ctypes_callproc() cleanup. */
604 PyTypeObject *tp = st->StructParam_Type;
605 obj = tp->tp_alloc(tp, 0);
606 if (obj == NULL) {
607 PyMem_Free(ptr);
608 return NULL;
609 }
610
611 StructParamObject *struct_param = (StructParamObject *)obj;
612 struct_param->ptr = ptr;
613 struct_param->keep = Py_NewRef(self);
614 } else {
615 ptr = self->b_ptr;
616 obj = Py_NewRef(self);
617 }
618
619 parg = PyCArgObject_new(st);
620 if (parg == NULL) {
621 Py_DECREF(obj);
622 return NULL;
623 }
624
625 StgInfo *stginfo;
626 if (PyStgInfo_FromObject(st, (PyObject *)self, &stginfo) < 0) {
627 Py_DECREF(obj);
628 return NULL;
629 }
630 assert(stginfo); /* Cannot be NULL for structure/union instances */
631
632 parg->tag = 'V';
633 parg->pffi_type = &stginfo->ffi_type_pointer;
634 parg->value.p = ptr;
635 parg->size = self->b_size;
636 parg->obj = obj;
637 return parg;
638 }
639
640 static int
641 StructUnionType_init(PyObject *self, PyObject *args, PyObject *kwds, int isStruct)
642 {
643 PyObject *fields;
644
645 PyObject *attrdict = PyType_GetDict((PyTypeObject *)self);
646 if (!attrdict) {
647 return -1;
648 }
649
650 /* keep this for bw compatibility */
651 int r = PyDict_Contains(attrdict, &_Py_ID(_abstract_));
652 if (r > 0) {
653 Py_DECREF(attrdict);
654 return 0;
655 }
656 if (r < 0) {
657 Py_DECREF(attrdict);
658 return -1;
659 }
660
661 ctypes_state *st = get_module_state_by_def(Py_TYPE(self));
662 StgInfo *info = PyStgInfo_Init(st, (PyTypeObject *)self);
663 if (!info) {
664 Py_DECREF(attrdict);
665 return -1;
666 }
667 if (!isStruct) {
668 info->flags |= TYPEFLAG_HASUNION;
669 }
670
671 info->format = _ctypes_alloc_format_string(NULL, "B");
672 if (info->format == NULL) {
673 Py_DECREF(attrdict);
674 return -1;
675 }
676
677 info->paramfunc = StructUnionType_paramfunc;
678
679 if (PyDict_GetItemRef((PyObject *)attrdict, &_Py_ID(_fields_), &fields) < 0) {
680 Py_DECREF(attrdict);
681 return -1;
682 }
683 Py_CLEAR(attrdict);
684 if (fields) {
685 if (PyObject_SetAttr(self, &_Py_ID(_fields_), fields) < 0) {
686 Py_DECREF(fields);
687 return -1;
688 }
689 Py_DECREF(fields);
690 return 0;
691 }
692 else {
693 StgInfo *baseinfo;
694 if (PyStgInfo_FromType(st, (PyObject *)((PyTypeObject *)self)->tp_base,
695 &baseinfo) < 0) {
696 return -1;
697 }
698 if (baseinfo == NULL) {
699 return 0;
700 }
701
702 /* copy base info */
703 if (PyCStgInfo_clone(info, baseinfo) < 0) {
704 return -1;
705 }
706 info->flags &= ~DICTFLAG_FINAL; /* clear the 'final' flag in the subclass info */
707 baseinfo->flags |= DICTFLAG_FINAL; /* set the 'final' flag in the baseclass info */
708 }
709 return 0;
710 }
711
712 static int
713 PyCStructType_init(PyObject *self, PyObject *args, PyObject *kwds)
714 {
715 return StructUnionType_init(self, args, kwds, 1);
716 }
717
718 static int
719 UnionType_init(PyObject *self, PyObject *args, PyObject *kwds)
720 {
721 return StructUnionType_init(self, args, kwds, 0);
722 }
723
724 /*[clinic input]
725 class _ctypes.CDataType "PyObject *" "clinic_state()->CType_Type"
726 [clinic start generated code]*/
727 /*[clinic end generated code: output=da39a3ee5e6b4b0d input=466a505a93d73156]*/
728
729
730 /*[clinic input]
731 _ctypes.CDataType.from_address as CDataType_from_address
732
733 type: self
734 cls: defining_class
735 value: object
736 /
737
738 C.from_address(integer) -> C instance
739
740 Access a C instance at the specified address.
741 [clinic start generated code]*/
742
743 static PyObject *
744 CDataType_from_address_impl(PyObject *type, PyTypeObject *cls,
745 PyObject *value)
746 /*[clinic end generated code: output=5be4a7c0d9aa6c74 input=827a22cefe380c01]*/
747 {
748 void *buf;
749 if (!PyLong_Check(value)) {
750 PyErr_SetString(PyExc_TypeError,
751 "integer expected");
752 return NULL;
753 }
754 buf = (void *)PyLong_AsVoidPtr(value);
755 if (PyErr_Occurred())
756 return NULL;
757 ctypes_state *st = get_module_state_by_class(cls);
758 return PyCData_AtAddress(st, type, buf);
759 }
760
761 static int
762 KeepRef(CDataObject *target, Py_ssize_t index, PyObject *keep);
763
764 /*[clinic input]
765 _ctypes.CDataType.from_buffer as CDataType_from_buffer
766
767 type: self
768 cls: defining_class
769 obj: object
770 offset: Py_ssize_t = 0
771 /
772
773 C.from_buffer(object, offset=0) -> C instance
774
775 Create a C instance from a writeable buffer.
776 [clinic start generated code]*/
777
778 static PyObject *
779 CDataType_from_buffer_impl(PyObject *type, PyTypeObject *cls, PyObject *obj,
780 Py_ssize_t offset)
781 /*[clinic end generated code: output=57604e99635abd31 input=0f36cedd105ca28d]*/
782 {
783 PyObject *mv;
784 PyObject *result;
785 Py_buffer *buffer;
786
787 ctypes_state *st = get_module_state_by_class(cls);
788 StgInfo *info;
789 if (PyStgInfo_FromType(st, type, &info) < 0) {
790 return NULL;
791 }
792 if (!info) {
793 PyErr_SetString(PyExc_TypeError, "abstract class");
794 return NULL;
795 }
796
797 mv = PyMemoryView_FromObject(obj);
798 if (mv == NULL)
799 return NULL;
800
801 buffer = PyMemoryView_GET_BUFFER(mv);
802
803 if (buffer->readonly) {
804 PyErr_SetString(PyExc_TypeError,
805 "underlying buffer is not writable");
806 Py_DECREF(mv);
807 return NULL;
808 }
809
810 if (!PyBuffer_IsContiguous(buffer, 'C')) {
811 PyErr_SetString(PyExc_TypeError,
812 "underlying buffer is not C contiguous");
813 Py_DECREF(mv);
814 return NULL;
815 }
816
817 if (offset < 0) {
818 PyErr_SetString(PyExc_ValueError,
819 "offset cannot be negative");
820 Py_DECREF(mv);
821 return NULL;
822 }
823
824 if (info->size > buffer->len - offset) {
825 PyErr_Format(PyExc_ValueError,
826 "Buffer size too small "
827 "(%zd instead of at least %zd bytes)",
828 buffer->len, info->size + offset);
829 Py_DECREF(mv);
830 return NULL;
831 }
832
833 if (PySys_Audit("ctypes.cdata/buffer", "nnn",
834 (Py_ssize_t)buffer->buf, buffer->len, offset) < 0) {
835 Py_DECREF(mv);
836 return NULL;
837 }
838
839 result = PyCData_AtAddress(st, type, (char *)buffer->buf + offset);
840 if (result == NULL) {
841 Py_DECREF(mv);
842 return NULL;
843 }
844
845 if (-1 == KeepRef((CDataObject *)result, -1, mv)) {
846 Py_DECREF(result);
847 return NULL;
848 }
849
850 return result;
851 }
852
853 static inline PyObject *
854 generic_pycdata_new(ctypes_state *st,
855 PyTypeObject *type, PyObject *args, PyObject *kwds);
856
857 static PyObject *
858 GenericPyCData_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
859
860 /*[clinic input]
861 _ctypes.CDataType.from_buffer_copy as CDataType_from_buffer_copy
862
863 type: self
864 cls: defining_class
865 buffer: Py_buffer
866 offset: Py_ssize_t = 0
867 /
868
869 C.from_buffer_copy(object, offset=0) -> C instance
870
871 Create a C instance from a readable buffer.
872 [clinic start generated code]*/
873
874 static PyObject *
875 CDataType_from_buffer_copy_impl(PyObject *type, PyTypeObject *cls,
876 Py_buffer *buffer, Py_ssize_t offset)
877 /*[clinic end generated code: output=c8fc62b03e5cc6fa input=2a81e11b765a6253]*/
878 {
879 PyObject *result;
880
881 ctypes_state *st = get_module_state_by_class(cls);
882 StgInfo *info;
883 if (PyStgInfo_FromType(st, type, &info) < 0) {
884 return NULL;
885 }
886 if (!info) {
887 PyErr_SetString(PyExc_TypeError, "abstract class");
888 return NULL;
889 }
890
891 if (offset < 0) {
892 PyErr_SetString(PyExc_ValueError,
893 "offset cannot be negative");
894 return NULL;
895 }
896
897 if (info->size > buffer->len - offset) {
898 PyErr_Format(PyExc_ValueError,
899 "Buffer size too small (%zd instead of at least %zd bytes)",
900 buffer->len, info->size + offset);
901 return NULL;
902 }
903
904 if (PySys_Audit("ctypes.cdata/buffer", "nnn",
905 (Py_ssize_t)buffer->buf, buffer->len, offset) < 0) {
906 return NULL;
907 }
908
909 result = generic_pycdata_new(st, (PyTypeObject *)type, NULL, NULL);
910 if (result != NULL) {
911 memcpy(((CDataObject *)result)->b_ptr,
912 (char *)buffer->buf + offset, info->size);
913 }
914 return result;
915 }
916
917 /*[clinic input]
918 _ctypes.CDataType.in_dll as CDataType_in_dll
919
920 type: self
921 cls: defining_class
922 dll: object
923 name: str
924 /
925
926 C.in_dll(dll, name) -> C instance
927
928 Access a C instance in a dll.
929 [clinic start generated code]*/
930
931 static PyObject *
932 CDataType_in_dll_impl(PyObject *type, PyTypeObject *cls, PyObject *dll,
933 const char *name)
934 /*[clinic end generated code: output=d0e5c43b66bfa21f input=f85bf281477042b4]*/
935 {
936 PyObject *obj;
937 void *handle;
938 void *address;
939
940 if (PySys_Audit("ctypes.dlsym", "Os", dll, name) < 0) {
941 return NULL;
942 }
943
944 obj = PyObject_GetAttrString(dll, "_handle");
945 if (!obj)
946 return NULL;
947 if (!PyLong_Check(obj)) {
948 PyErr_SetString(PyExc_TypeError,
949 "the _handle attribute of the second argument must be an integer");
950 Py_DECREF(obj);
951 return NULL;
952 }
953 handle = (void *)PyLong_AsVoidPtr(obj);
954 Py_DECREF(obj);
955 if (PyErr_Occurred()) {
956 PyErr_SetString(PyExc_ValueError,
957 "could not convert the _handle attribute to a pointer");
958 return NULL;
959 }
960
961 #undef USE_DLERROR
962 #ifdef MS_WIN32
963 Py_BEGIN_ALLOW_THREADS
964 address = (void *)GetProcAddress(handle, name);
965 Py_END_ALLOW_THREADS
966 #else
967 #ifdef __CYGWIN__
968 // dlerror() isn't very helpful on cygwin
969 #else
970 #define USE_DLERROR
971 /* dlerror() always returns the latest error.
972 *
973 * Clear the previous value before calling dlsym(),
974 * to ensure we can tell if our call resulted in an error.
975 */
976 (void)dlerror();
977 #endif
978 address = (void *)dlsym(handle, name);
979 #endif
980
981 if (address) {
982 ctypes_state *st = get_module_state_by_def(Py_TYPE(type));
983 return PyCData_AtAddress(st, type, address);
984 }
985
986 #ifdef USE_DLERROR
987 const char *dlerr = dlerror();
988 if (dlerr) {
989 _PyErr_SetLocaleString(PyExc_ValueError, dlerr);
990 return NULL;
991 }
992 #endif
993 #undef USE_DLERROR
994 PyErr_Format(PyExc_ValueError, "symbol '%s' not found", name);
995 return NULL;
996 }
997
998 /*[clinic input]
999 _ctypes.CDataType.from_param as CDataType_from_param
1000
1001 type: self
1002 cls: defining_class
1003 value: object
1004 /
1005
1006 Convert a Python object into a function call parameter.
1007 [clinic start generated code]*/
1008
1009 static PyObject *
1010 CDataType_from_param_impl(PyObject *type, PyTypeObject *cls, PyObject *value)
1011 /*[clinic end generated code: output=8da9e34263309f9e input=275a52c4899ddff0]*/
1012 {
1013 PyObject *as_parameter;
1014 int res = PyObject_IsInstance(value, type);
1015 if (res == -1)
1016 return NULL;
1017 if (res) {
1018 return Py_NewRef(value);
1019 }
1020 ctypes_state *st = get_module_state_by_class(cls);
1021 if (PyCArg_CheckExact(st, value)) {
1022 PyCArgObject *p = (PyCArgObject *)value;
1023 PyObject *ob = p->obj;
1024 const char *ob_name;
1025 StgInfo *info;
1026 if (PyStgInfo_FromType(st, type, &info) < 0) {
1027 return NULL;
1028 }
1029 /* If we got a PyCArgObject, we must check if the object packed in it
1030 is an instance of the type's info->proto */
1031 if(info && ob) {
1032 res = PyObject_IsInstance(ob, info->proto);
1033 if (res == -1)
1034 return NULL;
1035 if (res) {
1036 return Py_NewRef(value);
1037 }
1038 }
1039 ob_name = (ob) ? Py_TYPE(ob)->tp_name : "???";
1040 PyErr_Format(PyExc_TypeError,
1041 "expected %s instance instead of pointer to %s",
1042 ((PyTypeObject *)type)->tp_name, ob_name);
1043 return NULL;
1044 }
1045
1046 if (PyObject_GetOptionalAttr(value, &_Py_ID(_as_parameter_), &as_parameter) < 0) {
1047 return NULL;
1048 }
1049 if (as_parameter) {
1050 if (_Py_EnterRecursiveCall(" while processing _as_parameter_")) {
1051 Py_DECREF(as_parameter);
1052 return NULL;
1053 }
1054 value = CDataType_from_param_impl(type, cls, as_parameter);
1055 Py_DECREF(as_parameter);
1056 _Py_LeaveRecursiveCall();
1057 return value;
1058 }
1059 PyErr_Format(PyExc_TypeError,
1060 "expected %s instance instead of %s",
1061 ((PyTypeObject *)type)->tp_name,
1062 Py_TYPE(value)->tp_name);
1063 return NULL;
1064 }
1065
1066 static PyMethodDef CDataType_methods[] = {
1067 CDATATYPE_FROM_PARAM_METHODDEF
1068 CDATATYPE_FROM_ADDRESS_METHODDEF
1069 CDATATYPE_FROM_BUFFER_METHODDEF
1070 CDATATYPE_FROM_BUFFER_COPY_METHODDEF
1071 CDATATYPE_IN_DLL_METHODDEF
1072 { NULL, NULL },
1073 };
1074
1075 static PyObject *
1076 CType_Type_repeat(PyObject *self, Py_ssize_t length)
1077 {
1078 if (length < 0)
1079 return PyErr_Format(PyExc_ValueError,
1080 "Array length must be >= 0, not %zd",
1081 length);
1082 ctypes_state *st = get_module_state_by_def(Py_TYPE(self));
1083 return PyCArrayType_from_ctype(st, self, length);
1084 }
1085
1086
1087 static int
1088 PyCStructType_setattro(PyObject *self, PyObject *key, PyObject *value)
1089 {
1090 /* XXX Should we disallow deleting _fields_? */
1091 if (-1 == PyType_Type.tp_setattro(self, key, value))
1092 return -1;
1093
1094 if (value && PyUnicode_Check(key) &&
1095 _PyUnicode_EqualToASCIIString(key, "_fields_"))
1096 return PyCStructUnionType_update_stginfo(self, value, 1);
1097 return 0;
1098 }
1099
1100
1101 static int
1102 UnionType_setattro(PyObject *self, PyObject *key, PyObject *value)
1103 {
1104 /* XXX Should we disallow deleting _fields_? */
1105 if (-1 == PyType_Type.tp_setattro(self, key, value))
1106 return -1;
1107
1108 if (PyUnicode_Check(key) &&
1109 _PyUnicode_EqualToASCIIString(key, "_fields_"))
1110 return PyCStructUnionType_update_stginfo(self, value, 0);
1111 return 0;
1112 }
1113
1114 static PyType_Slot pycstruct_type_slots[] = {
1115 {Py_tp_setattro, PyCStructType_setattro},
1116 {Py_tp_doc, PyDoc_STR("metatype for the CData Objects")},
1117 {Py_tp_methods, CDataType_methods},
1118 {Py_tp_init, PyCStructType_init},
1119 {0, NULL},
1120 };
1121
1122 static PyType_Spec pycstruct_type_spec = {
1123 .name = "_ctypes.PyCStructType",
1124 .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
1125 Py_TPFLAGS_IMMUTABLETYPE),
1126 .slots = pycstruct_type_slots,
1127 };
1128
1129 static PyType_Slot union_type_slots[] = {
1130 {Py_tp_setattro, UnionType_setattro},
1131 {Py_tp_doc, PyDoc_STR("metatype for the Union Objects")},
1132 {Py_tp_methods, CDataType_methods},
1133 {Py_tp_init, UnionType_init},
1134 {0, NULL},
1135 };
1136
1137 static PyType_Spec union_type_spec = {
1138 .name = "_ctypes.UnionType",
1139 .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
1140 Py_TPFLAGS_IMMUTABLETYPE),
1141 .slots = union_type_slots,
1142 };
1143
1144 /******************************************************************/
1145
1146 /*
1147
1148 The PyCPointerType_Type metaclass must ensure that the subclass of Pointer can be
1149 created. It must check for a _type_ attribute in the class. Since are no
1150 runtime created properties, a CField is probably *not* needed ?
1151
1152 class IntPointer(Pointer):
1153 _type_ = "i"
1154
1155 The PyCPointer_Type provides the functionality: a contents method/property, a
1156 size property/method, and the sequence protocol.
1157
1158 */
1159
1160 /*[clinic input]
1161 class _ctypes.PyCPointerType "PyObject *" "clinic_state()->PyCPointerType_Type"
1162 [clinic start generated code]*/
1163 /*[clinic end generated code: output=da39a3ee5e6b4b0d input=c45e96c1f7645ab7]*/
1164
1165
1166 static int
1167 PyCPointerType_SetProto(ctypes_state *st, StgInfo *stginfo, PyObject *proto)
1168 {
1169 if (!proto || !PyType_Check(proto)) {
1170 PyErr_SetString(PyExc_TypeError,
1171 "_type_ must be a type");
1172 return -1;
1173 }
1174 StgInfo *info;
1175 if (PyStgInfo_FromType(st, proto, &info) < 0) {
1176 return -1;
1177 }
1178 if (!info) {
1179 PyErr_SetString(PyExc_TypeError,
1180 "_type_ must have storage info");
1181 return -1;
1182 }
1183 Py_INCREF(proto);
1184 Py_XSETREF(stginfo->proto, proto);
1185 return 0;
1186 }
1187
1188 static PyCArgObject *
1189 PyCPointerType_paramfunc(ctypes_state *st, CDataObject *self)
1190 {
1191 PyCArgObject *parg;
1192
1193 parg = PyCArgObject_new(st);
1194 if (parg == NULL)
1195 return NULL;
1196
1197 parg->tag = 'P';
1198 parg->pffi_type = &ffi_type_pointer;
1199 parg->obj = Py_NewRef(self);
1200 parg->value.p = *(void **)self->b_ptr;
1201 return parg;
1202 }
1203
1204 static int
1205 PyCPointerType_init(PyObject *self, PyObject *args, PyObject *kwds)
1206 {
1207 PyObject *proto;
1208 PyObject *typedict;
1209
1210 typedict = PyTuple_GetItem(args, 2);
1211 if (!typedict) {
1212 return -1;
1213 }
1214
1215 /*
1216 stginfo items size, align, length contain info about pointers itself,
1217 stginfo->proto has info about the pointed to type!
1218 */
1219 ctypes_state *st = get_module_state_by_def(Py_TYPE(self));
1220 StgInfo *stginfo = PyStgInfo_Init(st, (PyTypeObject *)self);
1221 if (!stginfo) {
1222 return -1;
1223 }
1224 stginfo->size = sizeof(void *);
1225 stginfo->align = _ctypes_get_fielddesc("P")->pffi_type->alignment;
1226 stginfo->length = 1;
1227 stginfo->ffi_type_pointer = ffi_type_pointer;
1228 stginfo->paramfunc = PyCPointerType_paramfunc;
1229 stginfo->flags |= TYPEFLAG_ISPOINTER;
1230
1231 if (PyDict_GetItemRef(typedict, &_Py_ID(_type_), &proto) < 0) {
1232 return -1;
1233 }
1234 if (proto) {
1235 const char *current_format;
1236 if (PyCPointerType_SetProto(st, stginfo, proto) < 0) {
1237 Py_DECREF(proto);
1238 return -1;
1239 }
1240 StgInfo *iteminfo;
1241 if (PyStgInfo_FromType(st, proto, &iteminfo) < 0) {
1242 Py_DECREF(proto);
1243 return -1;
1244 }
1245 /* PyCPointerType_SetProto has verified proto has a stginfo. */
1246 assert(iteminfo);
1247 /* If iteminfo->format is NULL, then this is a pointer to an
1248 incomplete type. We create a generic format string
1249 'pointer to bytes' in this case. XXX Better would be to
1250 fix the format string later...
1251 */
1252 current_format = iteminfo->format ? iteminfo->format : "B";
1253 if (iteminfo->shape != NULL) {
1254 /* pointer to an array: the shape needs to be prefixed */
1255 stginfo->format = _ctypes_alloc_format_string_with_shape(
1256 iteminfo->ndim, iteminfo->shape, "&", current_format);
1257 } else {
1258 stginfo->format = _ctypes_alloc_format_string("&", current_format);
1259 }
1260 Py_DECREF(proto);
1261 if (stginfo->format == NULL) {
1262 return -1;
1263 }
1264 }
1265
1266 return 0;
1267 }
1268
1269 /*[clinic input]
1270 _ctypes.PyCPointerType.set_type as PyCPointerType_set_type
1271
1272 self: self(type="PyTypeObject *")
1273 cls: defining_class
1274 type: object
1275 /
1276 [clinic start generated code]*/
1277
1278 static PyObject *
1279 PyCPointerType_set_type_impl(PyTypeObject *self, PyTypeObject *cls,
1280 PyObject *type)
1281 /*[clinic end generated code: output=51459d8f429a70ac input=67e1e8df921f123e]*/
1282 {
1283 ctypes_state *st = get_module_state_by_class(cls);
1284 StgInfo *info;
1285 if (PyStgInfo_FromType(st, (PyObject *)self, &info) < 0) {
1286 return NULL;
1287 }
1288 if (!info) {
1289 PyErr_SetString(PyExc_TypeError,
1290 "abstract class");
1291 return NULL;
1292 }
1293
1294 if (PyCPointerType_SetProto(st, info, type) < 0) {
1295 return NULL;
1296 }
1297
1298 if (PyObject_SetAttr((PyObject *)self, &_Py_ID(_type_), type) < 0) {
1299 return NULL;
1300 }
1301 Py_RETURN_NONE;
1302 }
1303
1304 static PyObject *_byref(ctypes_state *, PyObject *);
1305
1306 /*[clinic input]
1307 _ctypes.PyCPointerType.from_param as PyCPointerType_from_param
1308
1309 type: self
1310 cls: defining_class
1311 value: object
1312 /
1313
1314 Convert a Python object into a function call parameter.
1315 [clinic start generated code]*/
1316
1317 static PyObject *
1318 PyCPointerType_from_param_impl(PyObject *type, PyTypeObject *cls,
1319 PyObject *value)
1320 /*[clinic end generated code: output=a4b32d929aabaf64 input=6c231276e3997884]*/
1321 {
1322 if (value == Py_None) {
1323 /* ConvParam will convert to a NULL pointer later */
1324 return Py_NewRef(value);
1325 }
1326
1327 ctypes_state *st = get_module_state_by_class(cls);
1328 StgInfo *typeinfo;
1329 if (PyStgInfo_FromType(st, type, &typeinfo) < 0) {
1330 return NULL;
1331 }
1332 if (!typeinfo) {
1333 PyErr_SetString(PyExc_TypeError,
1334 "abstract class");
1335 return NULL;
1336 }
1337
1338 /* If we expect POINTER(<type>), but receive a <type> instance, accept
1339 it by calling byref(<type>).
1340 */
1341 if (typeinfo->proto == NULL) {
1342 PyErr_SetString(
1343 PyExc_TypeError,
1344 "cannot convert argument: POINTER _type_ type is not set"
1345 );
1346 return NULL;
1347 }
1348 switch (PyObject_IsInstance(value, typeinfo->proto)) {
1349 case 1:
1350 Py_INCREF(value); /* _byref steals a refcount */
1351 return _byref(st, value);
1352 case -1:
1353 return NULL;
1354 default:
1355 break;
1356 }
1357
1358 if (PointerObject_Check(st, value) || ArrayObject_Check(st, value)) {
1359 /* Array instances are also pointers when
1360 the item types are the same.
1361 */
1362 StgInfo *v;
1363 if (PyStgInfo_FromObject(st, value, &v) < 0) {
1364 return NULL;
1365 }
1366 assert(v); /* Cannot be NULL for pointer or array objects */
1367 int ret = PyObject_IsSubclass(v->proto, typeinfo->proto);
1368 if (ret < 0) {
1369 return NULL;
1370 }
1371 if (ret) {
1372 return Py_NewRef(value);
1373 }
1374 }
1375 return CDataType_from_param_impl(type, cls, value);
1376 }
1377
1378 static PyMethodDef PyCPointerType_methods[] = {
1379 CDATATYPE_FROM_ADDRESS_METHODDEF
1380 CDATATYPE_FROM_BUFFER_METHODDEF
1381 CDATATYPE_FROM_BUFFER_COPY_METHODDEF
1382 CDATATYPE_IN_DLL_METHODDEF
1383 PYCPOINTERTYPE_FROM_PARAM_METHODDEF
1384 PYCPOINTERTYPE_SET_TYPE_METHODDEF
1385 { NULL, NULL },
1386 };
1387
1388 static PyType_Slot pycpointer_type_slots[] = {
1389 {Py_tp_doc, PyDoc_STR("metatype for the Pointer Objects")},
1390 {Py_tp_methods, PyCPointerType_methods},
1391 {Py_tp_init, PyCPointerType_init},
1392 {0, NULL},
1393 };
1394
1395 static PyType_Spec pycpointer_type_spec = {
1396 .name = "_ctypes.PyCPointerType",
1397 .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
1398 Py_TPFLAGS_IMMUTABLETYPE),
1399 .slots = pycpointer_type_slots,
1400 };
1401
1402
1403 /******************************************************************/
1404 /*
1405 PyCArrayType_Type
1406 */
1407 /*
1408 PyCArrayType_init ensures that the new Array subclass created has a _length_
1409 attribute, and a _type_ attribute.
1410 */
1411
1412 static int
1413 CharArray_set_raw(CDataObject *self, PyObject *value, void *Py_UNUSED(ignored))
1414 {
1415 char *ptr;
1416 Py_ssize_t size;
1417 Py_buffer view;
1418
1419 if (value == NULL) {
1420 PyErr_SetString(PyExc_AttributeError, "cannot delete attribute");
1421 return -1;
1422 }
1423 if (PyObject_GetBuffer(value, &view, PyBUF_SIMPLE) < 0)
1424 return -1;
1425 size = view.len;
1426 ptr = view.buf;
1427 if (size > self->b_size) {
1428 PyErr_SetString(PyExc_ValueError,
1429 "byte string too long");
1430 goto fail;
1431 }
1432
1433 memcpy(self->b_ptr, ptr, size);
1434
1435 PyBuffer_Release(&view);
1436 return 0;
1437 fail:
1438 PyBuffer_Release(&view);
1439 return -1;
1440 }
1441
1442 static PyObject *
1443 CharArray_get_raw(CDataObject *self, void *Py_UNUSED(ignored))
1444 {
1445 return PyBytes_FromStringAndSize(self->b_ptr, self->b_size);
1446 }
1447
1448 static PyObject *
1449 CharArray_get_value(CDataObject *self, void *Py_UNUSED(ignored))
1450 {
1451 Py_ssize_t i;
1452 char *ptr = self->b_ptr;
1453 for (i = 0; i < self->b_size; ++i)
1454 if (*ptr++ == '\0')
1455 break;
1456 return PyBytes_FromStringAndSize(self->b_ptr, i);
1457 }
1458
1459 static int
1460 CharArray_set_value(CDataObject *self, PyObject *value, void *Py_UNUSED(ignored))
1461 {
1462 const char *ptr;
1463 Py_ssize_t size;
1464
1465 if (value == NULL) {
1466 PyErr_SetString(PyExc_TypeError,
1467 "can't delete attribute");
1468 return -1;
1469 }
1470
1471 if (!PyBytes_Check(value)) {
1472 PyErr_Format(PyExc_TypeError,
1473 "bytes expected instead of %s instance",
1474 Py_TYPE(value)->tp_name);
1475 return -1;
1476 } else
1477 Py_INCREF(value);
1478 size = PyBytes_GET_SIZE(value);
1479 if (size > self->b_size) {
1480 PyErr_SetString(PyExc_ValueError,
1481 "byte string too long");
1482 Py_DECREF(value);
1483 return -1;
1484 }
1485
1486 ptr = PyBytes_AS_STRING(value);
1487 memcpy(self->b_ptr, ptr, size);
1488 if (size < self->b_size)
1489 self->b_ptr[size] = '\0';
1490 Py_DECREF(value);
1491
1492 return 0;
1493 }
1494
1495 static PyGetSetDef CharArray_getsets[] = {
1496 { "raw", (getter)CharArray_get_raw, (setter)CharArray_set_raw,
1497 "value", NULL },
1498 { "value", (getter)CharArray_get_value, (setter)CharArray_set_value,
1499 "string value"},
1500 { NULL, NULL }
1501 };
1502
1503 static PyObject *
1504 WCharArray_get_value(CDataObject *self, void *Py_UNUSED(ignored))
1505 {
1506 Py_ssize_t i;
1507 wchar_t *ptr = (wchar_t *)self->b_ptr;
1508 for (i = 0; i < self->b_size/(Py_ssize_t)sizeof(wchar_t); ++i)
1509 if (*ptr++ == (wchar_t)0)
1510 break;
1511 return PyUnicode_FromWideChar((wchar_t *)self->b_ptr, i);
1512 }
1513
1514 static int
1515 WCharArray_set_value(CDataObject *self, PyObject *value, void *Py_UNUSED(ignored))
1516 {
1517 if (value == NULL) {
1518 PyErr_SetString(PyExc_TypeError,
1519 "can't delete attribute");
1520 return -1;
1521 }
1522 if (!PyUnicode_Check(value)) {
1523 PyErr_Format(PyExc_TypeError,
1524 "unicode string expected instead of %s instance",
1525 Py_TYPE(value)->tp_name);
1526 return -1;
1527 }
1528
1529 Py_ssize_t size = self->b_size / sizeof(wchar_t);
1530 Py_ssize_t len = PyUnicode_AsWideChar(value, NULL, 0);
1531 if (len < 0) {
1532 return -1;
1533 }
1534 // PyUnicode_AsWideChar() returns number of wchars including trailing null byte,
1535 // when it is called with NULL.
1536 assert(len > 0);
1537 if (len - 1 > size) {
1538 PyErr_SetString(PyExc_ValueError, "string too long");
1539 return -1;
1540 }
1541 if (PyUnicode_AsWideChar(value, (wchar_t *)self->b_ptr, size) < 0) {
1542 return -1;
1543 }
1544 return 0;
1545 }
1546
1547 static PyGetSetDef WCharArray_getsets[] = {
1548 { "value", (getter)WCharArray_get_value, (setter)WCharArray_set_value,
1549 "string value"},
1550 { NULL, NULL }
1551 };
1552
1553 /*
1554 The next function is copied from Python's typeobject.c.
1555
1556 It is used to attach getsets to a type *after* it
1557 has been created: Arrays of characters have additional getsets to treat them
1558 as strings.
1559 */
1560
1561 static int
1562 add_getset(PyTypeObject *type, PyGetSetDef *gsp)
1563 {
1564 PyObject *dict = type->tp_dict;
1565 for (; gsp->name != NULL; gsp++) {
1566 PyObject *descr;
1567 descr = PyDescr_NewGetSet(type, gsp);
1568 if (descr == NULL)
1569 return -1;
1570 if (PyDict_SetItemString(dict, gsp->name, descr) < 0) {
1571 Py_DECREF(descr);
1572 return -1;
1573 }
1574 Py_DECREF(descr);
1575 }
1576 return 0;
1577 }
1578
1579 static PyCArgObject *
1580 PyCArrayType_paramfunc(ctypes_state *st, CDataObject *self)
1581 {
1582 PyCArgObject *p = PyCArgObject_new(st);
1583 if (p == NULL)
1584 return NULL;
1585 p->tag = 'P';
1586 p->pffi_type = &ffi_type_pointer;
1587 p->value.p = (char *)self->b_ptr;
1588 p->obj = Py_NewRef(self);
1589 return p;
1590 }
1591
1592 static int
1593 PyCArrayType_init(PyObject *self, PyObject *args, PyObject *kwds)
1594 {
1595 PyObject *length_attr, *type_attr;
1596 Py_ssize_t length;
1597 Py_ssize_t itemsize, itemalign;
1598
1599 /* Initialize these variables to NULL so that we can simplify error
1600 handling by using Py_XDECREF. */
1601 type_attr = NULL;
1602
1603 if (PyObject_GetOptionalAttr(self, &_Py_ID(_length_), &length_attr) < 0) {
1604 goto error;
1605 }
1606 if (!length_attr) {
1607 PyErr_SetString(PyExc_AttributeError,
1608 "class must define a '_length_' attribute");
1609 goto error;
1610 }
1611
1612 if (!PyLong_Check(length_attr)) {
1613 Py_DECREF(length_attr);
1614 PyErr_SetString(PyExc_TypeError,
1615 "The '_length_' attribute must be an integer");
1616 goto error;
1617 }
1618
1619 if (_PyLong_Sign(length_attr) == -1) {
1620 Py_DECREF(length_attr);
1621 PyErr_SetString(PyExc_ValueError,
1622 "The '_length_' attribute must not be negative");
1623 goto error;
1624 }
1625
1626 length = PyLong_AsSsize_t(length_attr);
1627 Py_DECREF(length_attr);
1628 if (length == -1 && PyErr_Occurred()) {
1629 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
1630 PyErr_SetString(PyExc_OverflowError,
1631 "The '_length_' attribute is too large");
1632 }
1633 goto error;
1634 }
1635
1636 if (PyObject_GetOptionalAttr(self, &_Py_ID(_type_), &type_attr) < 0) {
1637 goto error;
1638 }
1639 if (!type_attr) {
1640 PyErr_SetString(PyExc_AttributeError,
1641 "class must define a '_type_' attribute");
1642 goto error;
1643 }
1644
1645 ctypes_state *st = get_module_state_by_def(Py_TYPE(self));
1646 StgInfo *stginfo = PyStgInfo_Init(st, (PyTypeObject*)self);
1647 if (!stginfo) {
1648 goto error;
1649 }
1650
1651 StgInfo *iteminfo;
1652 if (PyStgInfo_FromType(st, type_attr, &iteminfo) < 0) {
1653 goto error;
1654 }
1655 if (!iteminfo) {
1656 PyErr_SetString(PyExc_TypeError,
1657 "_type_ must have storage info");
1658 goto error;
1659 }
1660
1661 assert(iteminfo->format);
1662 stginfo->format = _ctypes_alloc_format_string(NULL, iteminfo->format);
1663 if (stginfo->format == NULL)
1664 goto error;
1665 stginfo->ndim = iteminfo->ndim + 1;
1666 stginfo->shape = PyMem_Malloc(sizeof(Py_ssize_t) * stginfo->ndim);
1667 if (stginfo->shape == NULL) {
1668 PyErr_NoMemory();
1669 goto error;
1670 }
1671 stginfo->shape[0] = length;
1672 if (stginfo->ndim > 1) {
1673 memmove(&stginfo->shape[1], iteminfo->shape,
1674 sizeof(Py_ssize_t) * (stginfo->ndim - 1));
1675 }
1676
1677 itemsize = iteminfo->size;
1678 if (itemsize != 0 && length > PY_SSIZE_T_MAX / itemsize) {
1679 PyErr_SetString(PyExc_OverflowError,
1680 "array too large");
1681 goto error;
1682 }
1683
1684 itemalign = iteminfo->align;
1685
1686 if (iteminfo->flags & (TYPEFLAG_ISPOINTER | TYPEFLAG_HASPOINTER))
1687 stginfo->flags |= TYPEFLAG_HASPOINTER;
1688
1689 stginfo->size = itemsize * length;
1690 stginfo->align = itemalign;
1691 stginfo->length = length;
1692 stginfo->proto = type_attr;
1693 type_attr = NULL;
1694
1695 stginfo->paramfunc = &PyCArrayType_paramfunc;
1696
1697 /* Arrays are passed as pointers to function calls. */
1698 stginfo->ffi_type_pointer = ffi_type_pointer;
1699
1700 /* Special case for character arrays.
1701 A permanent annoyance: char arrays are also strings!
1702 */
1703 if (iteminfo->getfunc == _ctypes_get_fielddesc("c")->getfunc) {
1704 if (-1 == add_getset((PyTypeObject*)self, CharArray_getsets))
1705 goto error;
1706 }
1707 else if (iteminfo->getfunc == _ctypes_get_fielddesc("u")->getfunc) {
1708 if (-1 == add_getset((PyTypeObject*)self, WCharArray_getsets))
1709 goto error;
1710 }
1711
1712 return 0;
1713 error:
1714 Py_XDECREF(type_attr);
1715 return -1;
1716 }
1717
1718 static PyType_Slot pycarray_type_slots[] = {
1719 {Py_tp_doc, PyDoc_STR("metatype for the Array Objects")},
1720 {Py_tp_methods, CDataType_methods},
1721 {Py_tp_init, PyCArrayType_init},
1722 {0, NULL},
1723 };
1724
1725 static PyType_Spec pycarray_type_spec = {
1726 .name = "_ctypes.PyCArrayType",
1727 .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
1728 Py_TPFLAGS_IMMUTABLETYPE),
1729 .slots = pycarray_type_slots,
1730 };
1731
1732 /******************************************************************/
1733 /*
1734 PyCSimpleType_Type
1735 */
1736 /*
1737
1738 PyCSimpleType_init ensures that the new Simple_Type subclass created has a valid
1739 _type_ attribute.
1740
1741 */
1742
1743 /*[clinic input]
1744 class _ctypes.PyCSimpleType "PyObject *" "clinic_state()->PyCSimpleType_Type"
1745 [clinic start generated code]*/
1746 /*[clinic end generated code: output=da39a3ee5e6b4b0d input=d5a45772668e7f49]*/
1747
1748 /*[clinic input]
1749 class _ctypes.c_wchar_p "PyObject *" "clinic_state_sub()->PyCSimpleType_Type"
1750 [clinic start generated code]*/
1751 /*[clinic end generated code: output=da39a3ee5e6b4b0d input=468de7283d622d47]*/
1752
1753 /*[clinic input]
1754 class _ctypes.c_char_p "PyObject *" "clinic_state_sub()->PyCSimpleType_Type"
1755 [clinic start generated code]*/
1756 /*[clinic end generated code: output=da39a3ee5e6b4b0d input=e750865616e7dcea]*/
1757
1758 /*[clinic input]
1759 class _ctypes.c_void_p "PyObject *" "clinic_state_sub()->PyCSimpleType_Type"
1760 [clinic start generated code]*/
1761 /*[clinic end generated code: output=da39a3ee5e6b4b0d input=dd4d9646c56f43a9]*/
1762
1763 static const char SIMPLE_TYPE_CHARS[] = "cbBhHiIlLdfuzZqQPXOv?g";
1764
1765 /*[clinic input]
1766 _ctypes.c_wchar_p.from_param as c_wchar_p_from_param
1767
1768 type: self
1769 cls: defining_class
1770 value: object
1771 /
1772 [clinic start generated code]*/
1773
1774 static PyObject *
1775 c_wchar_p_from_param_impl(PyObject *type, PyTypeObject *cls, PyObject *value)
1776 /*[clinic end generated code: output=e453949a2f725a4c input=d322c7237a319607]*/
1777 {
1778 PyObject *as_parameter;
1779 int res;
1780 if (value == Py_None) {
1781 Py_RETURN_NONE;
1782 }
1783 ctypes_state *st = get_module_state_by_class(cls->tp_base);
1784 if (PyUnicode_Check(value)) {
1785 PyCArgObject *parg;
1786 struct fielddesc *fd = _ctypes_get_fielddesc("Z");
1787
1788 parg = PyCArgObject_new(st);
1789 if (parg == NULL)
1790 return NULL;
1791 parg->pffi_type = &ffi_type_pointer;
1792 parg->tag = 'Z';
1793 parg->obj = fd->setfunc(&parg->value, value, 0);
1794 if (parg->obj == NULL) {
1795 Py_DECREF(parg);
1796 return NULL;
1797 }
1798 return (PyObject *)parg;
1799 }
1800 res = PyObject_IsInstance(value, type);
1801 if (res == -1)
1802 return NULL;
1803 if (res) {
1804 return Py_NewRef(value);
1805 }
1806 if (ArrayObject_Check(st, value) || PointerObject_Check(st, value)) {
1807 /* c_wchar array instance or pointer(c_wchar(...)) */
1808 StgInfo *it;
1809 if (PyStgInfo_FromObject(st, value, &it) < 0) {
1810 return NULL;
1811 }
1812 assert(it); /* Cannot be NULL for pointer or array objects */
1813 StgInfo *info = NULL;
1814 if (it && it->proto) {
1815 if (PyStgInfo_FromType(st, it->proto, &info) < 0) {
1816 return NULL;
1817 }
1818 }
1819 if (info && (info->setfunc == _ctypes_get_fielddesc("u")->setfunc)) {
1820 return Py_NewRef(value);
1821 }
1822 }
1823 if (PyCArg_CheckExact(st, value)) {
1824 /* byref(c_char(...)) */
1825 PyCArgObject *a = (PyCArgObject *)value;
1826 StgInfo *info;
1827 if (PyStgInfo_FromObject(st, a->obj, &info) < 0) {
1828 return NULL;
1829 }
1830 if (info && (info->setfunc == _ctypes_get_fielddesc("u")->setfunc)) {
1831 return Py_NewRef(value);
1832 }
1833 }
1834
1835 if (PyObject_GetOptionalAttr(value, &_Py_ID(_as_parameter_), &as_parameter) < 0) {
1836 return NULL;
1837 }
1838 if (as_parameter) {
1839 if (_Py_EnterRecursiveCall(" while processing _as_parameter_")) {
1840 Py_DECREF(as_parameter);
1841 return NULL;
1842 }
1843 value = c_wchar_p_from_param_impl(type, cls, as_parameter);
1844 Py_DECREF(as_parameter);
1845 _Py_LeaveRecursiveCall();
1846 return value;
1847 }
1848 PyErr_Format(PyExc_TypeError,
1849 "'%.200s' object cannot be interpreted "
1850 "as ctypes.c_wchar_p", Py_TYPE(value)->tp_name);
1851 return NULL;
1852 }
1853
1854 /*[clinic input]
1855 _ctypes.c_char_p.from_param as c_char_p_from_param
1856
1857 type: self
1858 cls: defining_class
1859 value: object
1860 /
1861 [clinic start generated code]*/
1862
1863 static PyObject *
1864 c_char_p_from_param_impl(PyObject *type, PyTypeObject *cls, PyObject *value)
1865 /*[clinic end generated code: output=219652ab7c174aa1 input=6cf0d1b6bb4ede11]*/
1866 {
1867 PyObject *as_parameter;
1868 int res;
1869 if (value == Py_None) {
1870 Py_RETURN_NONE;
1871 }
1872 ctypes_state *st = get_module_state_by_class(cls->tp_base);
1873 if (PyBytes_Check(value)) {
1874 PyCArgObject *parg;
1875 struct fielddesc *fd = _ctypes_get_fielddesc("z");
1876
1877 parg = PyCArgObject_new(st);
1878 if (parg == NULL)
1879 return NULL;
1880 parg->pffi_type = &ffi_type_pointer;
1881 parg->tag = 'z';
1882 parg->obj = fd->setfunc(&parg->value, value, 0);
1883 if (parg->obj == NULL) {
1884 Py_DECREF(parg);
1885 return NULL;
1886 }
1887 return (PyObject *)parg;
1888 }
1889 res = PyObject_IsInstance(value, type);
1890 if (res == -1)
1891 return NULL;
1892 if (res) {
1893 return Py_NewRef(value);
1894 }
1895 if (ArrayObject_Check(st, value) || PointerObject_Check(st, value)) {
1896 /* c_char array instance or pointer(c_char(...)) */
1897 StgInfo *it;
1898 if (PyStgInfo_FromObject(st, value, &it) < 0) {
1899 return NULL;
1900 }
1901 assert(it); /* Cannot be NULL for pointer or array objects */
1902 StgInfo *info = NULL;
1903 if (it && it->proto) {
1904 if (PyStgInfo_FromType(st, it->proto, &info) < 0) {
1905 return NULL;
1906 }
1907 }
1908 if (info && (info->setfunc == _ctypes_get_fielddesc("c")->setfunc)) {
1909 return Py_NewRef(value);
1910 }
1911 }
1912 if (PyCArg_CheckExact(st, value)) {
1913 /* byref(c_char(...)) */
1914 PyCArgObject *a = (PyCArgObject *)value;
1915 StgInfo *info;
1916 if (PyStgInfo_FromObject(st, a->obj, &info) < 0) {
1917 return NULL;
1918 }
1919 if (info && (info->setfunc == _ctypes_get_fielddesc("c")->setfunc)) {
1920 return Py_NewRef(value);
1921 }
1922 }
1923
1924 if (PyObject_GetOptionalAttr(value, &_Py_ID(_as_parameter_), &as_parameter) < 0) {
1925 return NULL;
1926 }
1927 if (as_parameter) {
1928 if (_Py_EnterRecursiveCall(" while processing _as_parameter_")) {
1929 Py_DECREF(as_parameter);
1930 return NULL;
1931 }
1932 value = c_char_p_from_param_impl(type, cls, as_parameter);
1933 Py_DECREF(as_parameter);
1934 _Py_LeaveRecursiveCall();
1935 return value;
1936 }
1937 PyErr_Format(PyExc_TypeError,
1938 "'%.200s' object cannot be interpreted "
1939 "as ctypes.c_char_p", Py_TYPE(value)->tp_name);
1940 return NULL;
1941 }
1942
1943 /*[clinic input]
1944 _ctypes.c_void_p.from_param as c_void_p_from_param
1945
1946 type: self
1947 cls: defining_class
1948 value: object
1949 /
1950 [clinic start generated code]*/
1951
1952 static PyObject *
1953 c_void_p_from_param_impl(PyObject *type, PyTypeObject *cls, PyObject *value)
1954 /*[clinic end generated code: output=984d0075b6038cc7 input=0e8b343fc19c77d4]*/
1955 {
1956 PyObject *as_parameter;
1957 int res;
1958
1959 /* None */
1960 if (value == Py_None) {
1961 Py_RETURN_NONE;
1962 }
1963 ctypes_state *st = get_module_state_by_class(cls->tp_base);
1964
1965 /* Should probably allow buffer interface as well */
1966 /* int, long */
1967 if (PyLong_Check(value)) {
1968 PyCArgObject *parg;
1969 struct fielddesc *fd = _ctypes_get_fielddesc("P");
1970
1971 parg = PyCArgObject_new(st);
1972 if (parg == NULL)
1973 return NULL;
1974 parg->pffi_type = &ffi_type_pointer;
1975 parg->tag = 'P';
1976 parg->obj = fd->setfunc(&parg->value, value, 0);
1977 if (parg->obj == NULL) {
1978 Py_DECREF(parg);
1979 return NULL;
1980 }
1981 return (PyObject *)parg;
1982 }
1983 /* XXX struni: remove later */
1984 /* bytes */
1985 if (PyBytes_Check(value)) {
1986 PyCArgObject *parg;
1987 struct fielddesc *fd = _ctypes_get_fielddesc("z");
1988
1989 parg = PyCArgObject_new(st);
1990 if (parg == NULL)
1991 return NULL;
1992 parg->pffi_type = &ffi_type_pointer;
1993 parg->tag = 'z';
1994 parg->obj = fd->setfunc(&parg->value, value, 0);
1995 if (parg->obj == NULL) {
1996 Py_DECREF(parg);
1997 return NULL;
1998 }
1999 return (PyObject *)parg;
2000 }
2001 /* unicode */
2002 if (PyUnicode_Check(value)) {
2003 PyCArgObject *parg;
2004 struct fielddesc *fd = _ctypes_get_fielddesc("Z");
2005
2006 parg = PyCArgObject_new(st);
2007 if (parg == NULL)
2008 return NULL;
2009 parg->pffi_type = &ffi_type_pointer;
2010 parg->tag = 'Z';
2011 parg->obj = fd->setfunc(&parg->value, value, 0);
2012 if (parg->obj == NULL) {
2013 Py_DECREF(parg);
2014 return NULL;
2015 }
2016 return (PyObject *)parg;
2017 }
2018 /* c_void_p instance (or subclass) */
2019 res = PyObject_IsInstance(value, type);
2020 if (res == -1)
2021 return NULL;
2022 if (res) {
2023 /* c_void_p instances */
2024 return Py_NewRef(value);
2025 }
2026 /* ctypes array or pointer instance */
2027 if (ArrayObject_Check(st, value) || PointerObject_Check(st, value)) {
2028 /* Any array or pointer is accepted */
2029 return Py_NewRef(value);
2030 }
2031 /* byref(...) */
2032 if (PyCArg_CheckExact(st, value)) {
2033 /* byref(c_xxx()) */
2034 PyCArgObject *a = (PyCArgObject *)value;
2035 if (a->tag == 'P') {
2036 return Py_NewRef(value);
2037 }
2038 }
2039 /* function pointer */
2040 if (PyCFuncPtrObject_Check(st, value)) {
2041 PyCArgObject *parg;
2042 PyCFuncPtrObject *func;
2043 func = (PyCFuncPtrObject *)value;
2044 parg = PyCArgObject_new(st);
2045 if (parg == NULL)
2046 return NULL;
2047 parg->pffi_type = &ffi_type_pointer;
2048 parg->tag = 'P';
2049 Py_INCREF(value);
2050 parg->value.p = *(void **)func->b_ptr;
2051 parg->obj = value;
2052 return (PyObject *)parg;
2053 }
2054 /* c_char_p, c_wchar_p */
2055 StgInfo *stgi;
2056 if (PyStgInfo_FromObject(st, value, &stgi) < 0) {
2057 return NULL;
2058 }
2059 if (stgi
2060 && CDataObject_Check(st, value)
2061 && stgi->proto
2062 && PyUnicode_Check(stgi->proto))
2063 {
2064 PyCArgObject *parg;
2065
2066 switch (PyUnicode_AsUTF8(stgi->proto)[0]) {
2067 case 'z': /* c_char_p */
2068 case 'Z': /* c_wchar_p */
2069 parg = PyCArgObject_new(st);
2070 if (parg == NULL)
2071 return NULL;
2072 parg->pffi_type = &ffi_type_pointer;
2073 parg->tag = 'Z';
2074 parg->obj = Py_NewRef(value);
2075 /* Remember: b_ptr points to where the pointer is stored! */
2076 parg->value.p = *(void **)(((CDataObject *)value)->b_ptr);
2077 return (PyObject *)parg;
2078 }
2079 }
2080
2081 if (PyObject_GetOptionalAttr(value, &_Py_ID(_as_parameter_), &as_parameter) < 0) {
2082 return NULL;
2083 }
2084 if (as_parameter) {
2085 if (_Py_EnterRecursiveCall(" while processing _as_parameter_")) {
2086 Py_DECREF(as_parameter);
2087 return NULL;
2088 }
2089 value = c_void_p_from_param_impl(type, cls, as_parameter);
2090 Py_DECREF(as_parameter);
2091 _Py_LeaveRecursiveCall();
2092 return value;
2093 }
2094 PyErr_Format(PyExc_TypeError,
2095 "'%.200s' object cannot be interpreted "
2096 "as ctypes.c_void_p", Py_TYPE(value)->tp_name);
2097 return NULL;
2098 }
2099
2100 static PyMethodDef c_void_p_methods[] = {C_VOID_P_FROM_PARAM_METHODDEF {0}};
2101 static PyMethodDef c_char_p_methods[] = {C_CHAR_P_FROM_PARAM_METHODDEF {0}};
2102 static PyMethodDef c_wchar_p_methods[] = {C_WCHAR_P_FROM_PARAM_METHODDEF {0}};
2103
2104 static PyObject *CreateSwappedType(ctypes_state *st, PyTypeObject *type,
2105 PyObject *args, PyObject *kwds,
2106 PyObject *proto, struct fielddesc *fmt)
2107 {
2108 PyTypeObject *result;
2109 PyObject *name = PyTuple_GET_ITEM(args, 0);
2110 PyObject *newname;
2111 PyObject *swapped_args;
2112 Py_ssize_t i;
2113
2114 swapped_args = PyTuple_New(PyTuple_GET_SIZE(args));
2115 if (!swapped_args)
2116 return NULL;
2117
2118 if (st->swapped_suffix == NULL) {
2119 #ifdef WORDS_BIGENDIAN
2120 st->swapped_suffix = PyUnicode_InternFromString("_le");
2121 #else
2122 st->swapped_suffix = PyUnicode_InternFromString("_be");
2123 #endif
2124 }
2125 if (st->swapped_suffix == NULL) {
2126 Py_DECREF(swapped_args);
2127 return NULL;
2128 }
2129
2130 newname = PyUnicode_Concat(name, st->swapped_suffix);
2131 if (newname == NULL) {
2132 Py_DECREF(swapped_args);
2133 return NULL;
2134 }
2135
2136 PyTuple_SET_ITEM(swapped_args, 0, newname);
2137 for (i=1; i<PyTuple_GET_SIZE(args); ++i) {
2138 PyObject *v = PyTuple_GET_ITEM(args, i);
2139 Py_INCREF(v);
2140 PyTuple_SET_ITEM(swapped_args, i, v);
2141 }
2142
2143 /* create the new instance (which is a class,
2144 since we are a metatype!) */
2145 result = (PyTypeObject *)PyType_Type.tp_new(type, swapped_args, kwds);
2146 Py_DECREF(swapped_args);
2147 if (result == NULL)
2148 return NULL;
2149
2150 StgInfo *stginfo = PyStgInfo_Init(st, result);
2151 if (!stginfo) {
2152 Py_DECREF(result);
2153 return NULL;
2154 }
2155
2156 stginfo->ffi_type_pointer = *fmt->pffi_type;
2157 stginfo->align = fmt->pffi_type->alignment;
2158 stginfo->length = 0;
2159 stginfo->size = fmt->pffi_type->size;
2160 stginfo->setfunc = fmt->setfunc_swapped;
2161 stginfo->getfunc = fmt->getfunc_swapped;
2162
2163 stginfo->proto = Py_NewRef(proto);
2164
2165 return (PyObject *)result;
2166 }
2167
2168 static PyCArgObject *
2169 PyCSimpleType_paramfunc(ctypes_state *st, CDataObject *self)
2170 {
2171 const char *fmt;
2172 PyCArgObject *parg;
2173 struct fielddesc *fd;
2174
2175 StgInfo *info;
2176 if (PyStgInfo_FromObject(st, (PyObject *)self, &info) < 0) {
2177 return NULL;
2178 }
2179 assert(info); /* Cannot be NULL for CDataObject instances */
2180 fmt = PyUnicode_AsUTF8(info->proto);
2181 assert(fmt);
2182
2183 fd = _ctypes_get_fielddesc(fmt);
2184 assert(fd);
2185
2186 parg = PyCArgObject_new(st);
2187 if (parg == NULL)
2188 return NULL;
2189
2190 parg->tag = fmt[0];
2191 parg->pffi_type = fd->pffi_type;
2192 parg->obj = Py_NewRef(self);
2193 memcpy(&parg->value, self->b_ptr, self->b_size);
2194 return parg;
2195 }
2196
2197 static int
2198 PyCSimpleType_init(PyObject *self, PyObject *args, PyObject *kwds)
2199 {
2200 PyObject *proto;
2201 const char *proto_str;
2202 Py_ssize_t proto_len;
2203 PyMethodDef *ml;
2204 struct fielddesc *fmt;
2205
2206 if (PyType_Type.tp_init(self, args, kwds) < 0) {
2207 return -1;
2208 }
2209 if (PyObject_GetOptionalAttr(self, &_Py_ID(_type_), &proto) < 0) {
2210 return -1;
2211 }
2212 if (!proto) {
2213 PyErr_SetString(PyExc_AttributeError,
2214 "class must define a '_type_' attribute");
2215 error:
2216 Py_XDECREF(proto);
2217 return -1;
2218 }
2219 if (PyUnicode_Check(proto)) {
2220 proto_str = PyUnicode_AsUTF8AndSize(proto, &proto_len);
2221 if (!proto_str)
2222 goto error;
2223 } else {
2224 PyErr_SetString(PyExc_TypeError,
2225 "class must define a '_type_' string attribute");
2226 goto error;
2227 }
2228 if (proto_len != 1) {
2229 PyErr_SetString(PyExc_ValueError,
2230 "class must define a '_type_' attribute "
2231 "which must be a string of length 1");
2232 goto error;
2233 }
2234 if (!strchr(SIMPLE_TYPE_CHARS, *proto_str)) {
2235 PyErr_Format(PyExc_AttributeError,
2236 "class must define a '_type_' attribute which must be\n"
2237 "a single character string containing one of '%s'.",
2238 SIMPLE_TYPE_CHARS);
2239 goto error;
2240 }
2241 fmt = _ctypes_get_fielddesc(proto_str);
2242 if (fmt == NULL) {
2243 PyErr_Format(PyExc_ValueError,
2244 "_type_ '%s' not supported", proto_str);
2245 goto error;
2246 }
2247
2248 ctypes_state *st = get_module_state_by_def(Py_TYPE(self));
2249 StgInfo *stginfo = PyStgInfo_Init(st, (PyTypeObject *)self);
2250 if (!stginfo) {
2251 goto error;
2252 }
2253
2254 stginfo->ffi_type_pointer = *fmt->pffi_type;
2255 stginfo->align = fmt->pffi_type->alignment;
2256 stginfo->length = 0;
2257 stginfo->size = fmt->pffi_type->size;
2258 stginfo->setfunc = fmt->setfunc;
2259 stginfo->getfunc = fmt->getfunc;
2260 #ifdef WORDS_BIGENDIAN
2261 stginfo->format = _ctypes_alloc_format_string_for_type(proto_str[0], 1);
2262 #else
2263 stginfo->format = _ctypes_alloc_format_string_for_type(proto_str[0], 0);
2264 #endif
2265 if (stginfo->format == NULL) {
2266 Py_DECREF(proto);
2267 return -1;
2268 }
2269
2270 stginfo->paramfunc = PyCSimpleType_paramfunc;
2271 /*
2272 if (self->tp_base != st->Simple_Type) {
2273 stginfo->setfunc = NULL;
2274 stginfo->getfunc = NULL;
2275 }
2276 */
2277
2278 /* This consumes the refcount on proto which we have */
2279 stginfo->proto = proto;
2280
2281 /* Install from_param class methods in ctypes base classes.
2282 Overrides the PyCSimpleType_from_param generic method.
2283 */
2284 if (((PyTypeObject *)self)->tp_base == st->Simple_Type) {
2285 switch (*proto_str) {
2286 case 'z': /* c_char_p */
2287 ml = c_char_p_methods;
2288 stginfo->flags |= TYPEFLAG_ISPOINTER;
2289 break;
2290 case 'Z': /* c_wchar_p */
2291 ml = c_wchar_p_methods;
2292 stginfo->flags |= TYPEFLAG_ISPOINTER;
2293 break;
2294 case 'P': /* c_void_p */
2295 ml = c_void_p_methods;
2296 stginfo->flags |= TYPEFLAG_ISPOINTER;
2297 break;
2298 case 's':
2299 case 'X':
2300 case 'O':
2301 ml = NULL;
2302 stginfo->flags |= TYPEFLAG_ISPOINTER;
2303 break;
2304 default:
2305 ml = NULL;
2306 break;
2307 }
2308
2309 if (ml) {
2310 PyObject *meth;
2311 int x;
2312 meth = PyDescr_NewClassMethod((PyTypeObject*)self, ml);
2313 if (!meth) {
2314 return -1;
2315 }
2316 PyObject *name = PyUnicode_FromString(ml->ml_name);
2317 if (name == NULL) {
2318 Py_DECREF(meth);
2319 return -1;
2320 }
2321 PyUnicode_InternInPlace(&name);
2322 x = PyDict_SetItem(((PyTypeObject*)self)->tp_dict, name, meth);
2323 Py_DECREF(name);
2324 Py_DECREF(meth);
2325 if (x == -1) {
2326 return -1;
2327 }
2328 }
2329 }
2330
2331 PyTypeObject *type = Py_TYPE(self);
2332 if (type == st->PyCSimpleType_Type
2333 && fmt->setfunc_swapped
2334 && fmt->getfunc_swapped)
2335 {
2336 PyObject *swapped = CreateSwappedType(st, type, args, kwds,
2337 proto, fmt);
2338 if (swapped == NULL) {
2339 return -1;
2340 }
2341 StgInfo *sw_info;
2342 if (PyStgInfo_FromType(st, swapped, &sw_info) < 0) {
2343 return -1;
2344 }
2345 assert(sw_info);
2346 #ifdef WORDS_BIGENDIAN
2347 PyObject_SetAttrString(self, "__ctype_le__", swapped);
2348 PyObject_SetAttrString(self, "__ctype_be__", self);
2349 PyObject_SetAttrString(swapped, "__ctype_be__", self);
2350 PyObject_SetAttrString(swapped, "__ctype_le__", swapped);
2351 /* We are creating the type for the OTHER endian */
2352 sw_info->format = _ctypes_alloc_format_string("<", stginfo->format+1);
2353 #else
2354 PyObject_SetAttrString(self, "__ctype_be__", swapped);
2355 PyObject_SetAttrString(self, "__ctype_le__", self);
2356 PyObject_SetAttrString(swapped, "__ctype_le__", self);
2357 PyObject_SetAttrString(swapped, "__ctype_be__", swapped);
2358 /* We are creating the type for the OTHER endian */
2359 sw_info->format = _ctypes_alloc_format_string(">", stginfo->format+1);
2360 #endif
2361 Py_DECREF(swapped);
2362 if (PyErr_Occurred()) {
2363 return -1;
2364 }
2365 };
2366
2367 return 0;
2368 }
2369
2370 /*
2371 * This is a *class method*.
2372 * Convert a parameter into something that ConvParam can handle.
2373 */
2374
2375 /*[clinic input]
2376 _ctypes.PyCSimpleType.from_param as PyCSimpleType_from_param
2377
2378 type: self
2379 cls: defining_class
2380 value: object
2381 /
2382
2383 Convert a Python object into a function call parameter.
2384 [clinic start generated code]*/
2385
2386 static PyObject *
2387 PyCSimpleType_from_param_impl(PyObject *type, PyTypeObject *cls,
2388 PyObject *value)
2389 /*[clinic end generated code: output=8a8453d9663e3a2e input=61cc48ce3a87a570]*/
2390 {
2391 const char *fmt;
2392 PyCArgObject *parg;
2393 struct fielddesc *fd;
2394 PyObject *as_parameter;
2395 int res;
2396
2397 /* If the value is already an instance of the requested type,
2398 we can use it as is */
2399 res = PyObject_IsInstance(value, type);
2400 if (res == -1)
2401 return NULL;
2402 if (res) {
2403 return Py_NewRef(value);
2404 }
2405
2406 ctypes_state *st = get_module_state_by_class(cls);
2407 StgInfo *info;
2408 if (PyStgInfo_FromType(st, type, &info) < 0) {
2409 return NULL;
2410 }
2411 if (!info) {
2412 PyErr_SetString(PyExc_TypeError,
2413 "abstract class");
2414 return NULL;
2415 }
2416
2417 /* I think we can rely on this being a one-character string */
2418 fmt = PyUnicode_AsUTF8(info->proto);
2419 assert(fmt);
2420
2421 fd = _ctypes_get_fielddesc(fmt);
2422 assert(fd);
2423
2424 parg = PyCArgObject_new(st);
2425 if (parg == NULL)
2426 return NULL;
2427
2428 parg->tag = fmt[0];
2429 parg->pffi_type = fd->pffi_type;
2430 parg->obj = fd->setfunc(&parg->value, value, 0);
2431 if (parg->obj)
2432 return (PyObject *)parg;
2433 PyObject *exc = PyErr_GetRaisedException();
2434 Py_DECREF(parg);
2435
2436 if (PyObject_GetOptionalAttr(value, &_Py_ID(_as_parameter_), &as_parameter) < 0) {
2437 Py_XDECREF(exc);
2438 return NULL;
2439 }
2440 if (as_parameter) {
2441 if (_Py_EnterRecursiveCall(" while processing _as_parameter_")) {
2442 Py_DECREF(as_parameter);
2443 Py_XDECREF(exc);
2444 return NULL;
2445 }
2446 value = PyCSimpleType_from_param_impl(type, cls, as_parameter);
2447 Py_DECREF(as_parameter);
2448 Py_XDECREF(exc);
2449 _Py_LeaveRecursiveCall();
2450 return value;
2451 }
2452 if (exc) {
2453 PyErr_SetRaisedException(exc);
2454 }
2455 else {
2456 PyErr_SetString(PyExc_TypeError, "wrong type");
2457 }
2458 return NULL;
2459 }
2460
2461 static PyMethodDef PyCSimpleType_methods[] = {
2462 PYCSIMPLETYPE_FROM_PARAM_METHODDEF
2463 CDATATYPE_FROM_ADDRESS_METHODDEF
2464 CDATATYPE_FROM_BUFFER_METHODDEF
2465 CDATATYPE_FROM_BUFFER_COPY_METHODDEF
2466 CDATATYPE_IN_DLL_METHODDEF
2467 { NULL, NULL },
2468 };
2469
2470 static PyType_Slot pycsimple_type_slots[] = {
2471 {Py_tp_doc, PyDoc_STR("metatype for the PyCSimpleType Objects")},
2472 {Py_tp_methods, PyCSimpleType_methods},
2473 {Py_tp_init, PyCSimpleType_init},
2474 {0, NULL},
2475 };
2476
2477 static PyType_Spec pycsimple_type_spec = {
2478 .name = "_ctypes.PyCSimpleType",
2479 .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
2480 Py_TPFLAGS_IMMUTABLETYPE),
2481 .slots = pycsimple_type_slots,
2482 };
2483
2484 /******************************************************************/
2485 /*
2486 PyCFuncPtrType_Type
2487 */
2488
2489 static PyObject *
2490 converters_from_argtypes(ctypes_state *st, PyObject *ob)
2491 {
2492 PyObject *converters;
2493 Py_ssize_t i;
2494
2495 ob = PySequence_Tuple(ob); /* new reference */
2496 if (!ob) {
2497 PyErr_SetString(PyExc_TypeError,
2498 "_argtypes_ must be a sequence of types");
2499 return NULL;
2500 }
2501
2502 Py_ssize_t nArgs = PyTuple_GET_SIZE(ob);
2503 if (nArgs > CTYPES_MAX_ARGCOUNT) {
2504 Py_DECREF(ob);
2505 PyErr_Format(st->PyExc_ArgError,
2506 "_argtypes_ has too many arguments (%zi), maximum is %i",
2507 nArgs, CTYPES_MAX_ARGCOUNT);
2508 return NULL;
2509 }
2510
2511 converters = PyTuple_New(nArgs);
2512 if (!converters) {
2513 Py_DECREF(ob);
2514 return NULL;
2515 }
2516
2517 /* I have to check if this is correct. Using c_char, which has a size
2518 of 1, will be assumed to be pushed as only one byte!
2519 Aren't these promoted to integers by the C compiler and pushed as 4 bytes?
2520 */
2521
2522 for (i = 0; i < nArgs; ++i) {
2523 PyObject *cnv;
2524 PyObject *tp = PyTuple_GET_ITEM(ob, i);
2525 /*
2526 * The following checks, relating to bpo-16575 and bpo-16576, have been
2527 * disabled. The reason is that, although there is a definite problem with
2528 * how libffi handles unions (https://github.com/libffi/libffi/issues/33),
2529 * there are numerous libraries which pass structures containing unions
2530 * by values - especially on Windows but examples also exist on Linux
2531 * (https://bugs.python.org/msg359834).
2532 *
2533 * It may not be possible to get proper support for unions and bitfields
2534 * until support is forthcoming in libffi, but for now, adding the checks
2535 * has caused problems in otherwise-working software, which suggests it
2536 * is better to disable the checks.
2537 *
2538 * Although specific examples reported relate specifically to unions and
2539 * not bitfields, the bitfields check is also being disabled as a
2540 * precaution.
2541
2542 StgInfo *stginfo;
2543 if (PyStgInfo_FromType(st, tp, &stginfo) < 0) {
2544 return -1;
2545 }
2546
2547 if (stginfo != NULL) {
2548 if (stginfo->flags & TYPEFLAG_HASUNION) {
2549 Py_DECREF(converters);
2550 Py_DECREF(ob);
2551 if (!PyErr_Occurred()) {
2552 PyErr_Format(PyExc_TypeError,
2553 "item %zd in _argtypes_ passes a union by "
2554 "value, which is unsupported.",
2555 i + 1);
2556 }
2557 return NULL;
2558 }
2559 if (stginfo->flags & TYPEFLAG_HASBITFIELD) {
2560 Py_DECREF(converters);
2561 Py_DECREF(ob);
2562 if (!PyErr_Occurred()) {
2563 PyErr_Format(PyExc_TypeError,
2564 "item %zd in _argtypes_ passes a struct/"
2565 "union with a bitfield by value, which is "
2566 "unsupported.",
2567 i + 1);
2568 }
2569 return NULL;
2570 }
2571 }
2572 */
2573
2574 if (PyObject_GetOptionalAttr(tp, &_Py_ID(from_param), &cnv) <= 0) {
2575 Py_DECREF(converters);
2576 Py_DECREF(ob);
2577 if (!PyErr_Occurred()) {
2578 PyErr_Format(PyExc_TypeError,
2579 "item %zd in _argtypes_ has no from_param method",
2580 i+1);
2581 }
2582 return NULL;
2583 }
2584 PyTuple_SET_ITEM(converters, i, cnv);
2585 }
2586 Py_DECREF(ob);
2587 return converters;
2588 }
2589
2590 static int
2591 make_funcptrtype_dict(ctypes_state *st, PyObject *attrdict, StgInfo *stginfo)
2592 {
2593 PyObject *ob;
2594 PyObject *converters = NULL;
2595
2596 stginfo->align = _ctypes_get_fielddesc("P")->pffi_type->alignment;
2597 stginfo->length = 1;
2598 stginfo->size = sizeof(void *);
2599 stginfo->setfunc = NULL;
2600 stginfo->getfunc = NULL;
2601 stginfo->ffi_type_pointer = ffi_type_pointer;
2602
2603 if (PyDict_GetItemRef((PyObject *)attrdict, &_Py_ID(_flags_), &ob) < 0) {
2604 return -1;
2605 }
2606 if (!ob || !PyLong_Check(ob)) {
2607 PyErr_SetString(PyExc_TypeError,
2608 "class must define _flags_ which must be an integer");
2609 Py_XDECREF(ob);
2610 return -1;
2611 }
2612 stginfo->flags = PyLong_AsUnsignedLongMask(ob) | TYPEFLAG_ISPOINTER;
2613 Py_DECREF(ob);
2614
2615 /* _argtypes_ is optional... */
2616 if (PyDict_GetItemRef((PyObject *)attrdict, &_Py_ID(_argtypes_), &ob) < 0) {
2617 return -1;
2618 }
2619 if (ob) {
2620 converters = converters_from_argtypes(st, ob);
2621 if (!converters) {
2622 Py_DECREF(ob);
2623 return -1;
2624 }
2625 stginfo->argtypes = ob;
2626 stginfo->converters = converters;
2627 }
2628
2629 if (PyDict_GetItemRef((PyObject *)attrdict, &_Py_ID(_restype_), &ob) < 0) {
2630 return -1;
2631 }
2632 if (ob) {
2633 StgInfo *info;
2634 if (PyStgInfo_FromType(st, ob, &info) < 0) {
2635 return -1;
2636 }
2637 if (ob != Py_None && !info && !PyCallable_Check(ob)) {
2638 PyErr_SetString(PyExc_TypeError,
2639 "_restype_ must be a type, a callable, or None");
2640 Py_DECREF(ob);
2641 return -1;
2642 }
2643 stginfo->restype = ob;
2644 if (PyObject_GetOptionalAttr(ob, &_Py_ID(_check_retval_),
2645 &stginfo->checker) < 0)
2646 {
2647 return -1;
2648 }
2649 }
2650 /* XXX later, maybe.
2651 if (PyDict_GetItemRef((PyObject *)attrdict, &_Py _ID(_errcheck_), &ob) < 0) {
2652 return -1;
2653 }
2654 if (ob) {
2655 if (!PyCallable_Check(ob)) {
2656 PyErr_SetString(PyExc_TypeError,
2657 "_errcheck_ must be callable");
2658 Py_DECREF(ob);
2659 return -1;
2660 }
2661 stginfo->errcheck = ob;
2662 }
2663 */
2664 return 0;
2665 }
2666
2667 static PyCArgObject *
2668 PyCFuncPtrType_paramfunc(ctypes_state *st, CDataObject *self)
2669 {
2670 PyCArgObject *parg;
2671
2672 parg = PyCArgObject_new(st);
2673 if (parg == NULL)
2674 return NULL;
2675
2676 parg->tag = 'P';
2677 parg->pffi_type = &ffi_type_pointer;
2678 parg->obj = Py_NewRef(self);
2679 parg->value.p = *(void **)self->b_ptr;
2680 return parg;
2681 }
2682
2683 static int
2684 PyCFuncPtrType_init(PyObject *self, PyObject *args, PyObject *kwds)
2685 {
2686 PyObject *attrdict = PyType_GetDict((PyTypeObject *)self);
2687 if (!attrdict) {
2688 return -1;
2689 }
2690
2691 ctypes_state *st = get_module_state_by_def(Py_TYPE(self));
2692 StgInfo *stginfo = PyStgInfo_Init(st, (PyTypeObject *)self);
2693 if (!stginfo) {
2694 Py_DECREF(attrdict);
2695 return -1;
2696 }
2697
2698 stginfo->paramfunc = PyCFuncPtrType_paramfunc;
2699
2700 /* We do NOT expose the function signature in the format string. It
2701 is impossible, generally, because the only requirement for the
2702 argtypes items is that they have a .from_param method - we do not
2703 know the types of the arguments (although, in practice, most
2704 argtypes would be a ctypes type).
2705 */
2706 stginfo->format = _ctypes_alloc_format_string(NULL, "X{}");
2707 if (stginfo->format == NULL) {
2708 Py_DECREF(attrdict);
2709 return -1;
2710 }
2711 stginfo->flags |= TYPEFLAG_ISPOINTER;
2712
2713 if (make_funcptrtype_dict(st, attrdict, stginfo) < 0) {
2714 Py_DECREF(attrdict);
2715 return -1;
2716 }
2717
2718 Py_DECREF(attrdict);
2719 return 0;
2720 }
2721
2722 static PyType_Slot pycfuncptr_type_slots[] = {
2723 {Py_tp_doc, PyDoc_STR("metatype for C function pointers")},
2724 {Py_tp_methods, CDataType_methods},
2725 {Py_tp_init, PyCFuncPtrType_init},
2726 {0, NULL},
2727 };
2728
2729 static PyType_Spec pycfuncptr_type_spec = {
2730 .name = "_ctypes.PyCFuncPtrType",
2731 .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
2732 Py_TPFLAGS_IMMUTABLETYPE),
2733 .slots = pycfuncptr_type_slots,
2734 };
2735
2736
2737 /*****************************************************************
2738 * Code to keep needed objects alive
2739 */
2740
2741 static CDataObject *
2742 PyCData_GetContainer(CDataObject *self)
2743 {
2744 while (self->b_base)
2745 self = self->b_base;
2746 if (self->b_objects == NULL) {
2747 if (self->b_length) {
2748 self->b_objects = PyDict_New();
2749 if (self->b_objects == NULL)
2750 return NULL;
2751 } else {
2752 self->b_objects = Py_NewRef(Py_None);
2753 }
2754 }
2755 return self;
2756 }
2757
2758 static PyObject *
2759 GetKeepedObjects(CDataObject *target)
2760 {
2761 CDataObject *container;
2762 container = PyCData_GetContainer(target);
2763 if (container == NULL)
2764 return NULL;
2765 return container->b_objects;
2766 }
2767
2768 static PyObject *
2769 unique_key(CDataObject *target, Py_ssize_t index)
2770 {
2771 char string[256];
2772 char *cp = string;
2773 size_t bytes_left;
2774
2775 Py_BUILD_ASSERT(sizeof(string) - 1 > sizeof(Py_ssize_t) * 2);
2776 cp += sprintf(cp, "%x", Py_SAFE_DOWNCAST(index, Py_ssize_t, int));
2777 while (target->b_base) {
2778 bytes_left = sizeof(string) - (cp - string) - 1;
2779 /* Hex format needs 2 characters per byte */
2780 if (bytes_left < sizeof(Py_ssize_t) * 2) {
2781 PyErr_SetString(PyExc_ValueError,
2782 "ctypes object structure too deep");
2783 return NULL;
2784 }
2785 cp += sprintf(cp, ":%x", Py_SAFE_DOWNCAST(target->b_index, Py_ssize_t, int));
2786 target = target->b_base;
2787 }
2788 return PyUnicode_FromStringAndSize(string, cp-string);
2789 }
2790
2791 /*
2792 * Keep a reference to 'keep' in the 'target', at index 'index'.
2793 *
2794 * If 'keep' is None, do nothing.
2795 *
2796 * Otherwise create a dictionary (if it does not yet exist) id the root
2797 * objects 'b_objects' item, which will store the 'keep' object under a unique
2798 * key.
2799 *
2800 * The unique_key helper travels the target's b_base pointer down to the root,
2801 * building a string containing hex-formatted indexes found during traversal,
2802 * separated by colons.
2803 *
2804 * The index tuple is used as a key into the root object's b_objects dict.
2805 *
2806 * Note: This function steals a refcount of the third argument, even if it
2807 * fails!
2808 */
2809 static int
2810 KeepRef(CDataObject *target, Py_ssize_t index, PyObject *keep)
2811 {
2812 int result;
2813 CDataObject *ob;
2814 PyObject *key;
2815
2816 /* Optimization: no need to store None */
2817 if (keep == Py_None) {
2818 Py_DECREF(Py_None);
2819 return 0;
2820 }
2821 ob = PyCData_GetContainer(target);
2822 if (ob == NULL) {
2823 Py_DECREF(keep);
2824 return -1;
2825 }
2826 if (ob->b_objects == NULL || !PyDict_CheckExact(ob->b_objects)) {
2827 Py_XSETREF(ob->b_objects, keep); /* refcount consumed */
2828 return 0;
2829 }
2830 key = unique_key(target, index);
2831 if (key == NULL) {
2832 Py_DECREF(keep);
2833 return -1;
2834 }
2835 result = PyDict_SetItem(ob->b_objects, key, keep);
2836 Py_DECREF(key);
2837 Py_DECREF(keep);
2838 return result;
2839 }
2840
2841 /******************************************************************/
2842 /*
2843 PyCData_Type
2844 */
2845
2846 /*[clinic input]
2847 class _ctypes.PyCData "PyObject *" "clinic_state()->PyCData_Type"
2848 [clinic start generated code]*/
2849 /*[clinic end generated code: output=da39a3ee5e6b4b0d input=ac13df38dee3c22c]*/
2850
2851
2852 static int
2853 PyCData_traverse(CDataObject *self, visitproc visit, void *arg)
2854 {
2855 Py_VISIT(self->b_objects);
2856 Py_VISIT((PyObject *)self->b_base);
2857 PyTypeObject *type = Py_TYPE(self);
2858 Py_VISIT(type);
2859 return 0;
2860 }
2861
2862 static int
2863 PyCData_clear(CDataObject *self)
2864 {
2865 Py_CLEAR(self->b_objects);
2866 if ((self->b_needsfree)
2867 && _CDataObject_HasExternalBuffer(self))
2868 PyMem_Free(self->b_ptr);
2869 self->b_ptr = NULL;
2870 Py_CLEAR(self->b_base);
2871 return 0;
2872 }
2873
2874 static void
2875 PyCData_dealloc(PyObject *self)
2876 {
2877 PyTypeObject *type = Py_TYPE(self);
2878 PyObject_GC_UnTrack(self);
2879 PyCData_clear((CDataObject *)self);
2880 type->tp_free(self);
2881 Py_DECREF(type);
2882 }
2883
2884 static PyMemberDef PyCData_members[] = {
2885 { "_b_base_", _Py_T_OBJECT,
2886 offsetof(CDataObject, b_base), Py_READONLY,
2887 "the base object" },
2888 { "_b_needsfree_", Py_T_INT,
2889 offsetof(CDataObject, b_needsfree), Py_READONLY,
2890 "whether the object owns the memory or not" },
2891 { "_objects", _Py_T_OBJECT,
2892 offsetof(CDataObject, b_objects), Py_READONLY,
2893 "internal objects tree (NEVER CHANGE THIS OBJECT!)"},
2894 { NULL },
2895 };
2896
2897 /* Find the innermost type of an array type, returning a borrowed reference */
2898 static PyObject *
2899 PyCData_item_type(ctypes_state *st, PyObject *type)
2900 {
2901 if (PyCArrayTypeObject_Check(st, type)) {
2902 PyObject *elem_type;
2903
2904 /* asserts used here as these are all guaranteed by construction */
2905 StgInfo *stg_info;
2906 if (PyStgInfo_FromType(st, type, &stg_info) < 0) {
2907 return NULL;
2908 }
2909 assert(stg_info);
2910 elem_type = stg_info->proto;
2911 assert(elem_type);
2912 return PyCData_item_type(st, elem_type);
2913 }
2914 else {
2915 return type;
2916 }
2917 }
2918
2919 static int
2920 PyCData_NewGetBuffer(PyObject *myself, Py_buffer *view, int flags)
2921 {
2922 CDataObject *self = (CDataObject *)myself;
2923
2924 ctypes_state *st = get_module_state_by_def(Py_TYPE(Py_TYPE(myself)));
2925 StgInfo *info;
2926 if (PyStgInfo_FromObject(st, myself, &info) < 0) {
2927 return -1;
2928 }
2929 assert(info);
2930
2931 PyObject *item_type = PyCData_item_type(st, (PyObject*)Py_TYPE(myself));
2932 if (item_type == NULL) {
2933 return 0;
2934 }
2935
2936 if (view == NULL) return 0;
2937
2938 StgInfo *item_info;
2939 if (PyStgInfo_FromType(st, item_type, &item_info) < 0) {
2940 return -1;
2941 }
2942 assert(item_info);
2943
2944 view->buf = self->b_ptr;
2945 view->obj = Py_NewRef(myself);
2946 view->len = self->b_size;
2947 view->readonly = 0;
2948 /* use default format character if not set */
2949 view->format = info->format ? info->format : "B";
2950 view->ndim = info->ndim;
2951 view->shape = info->shape;
2952 view->itemsize = item_info->size;
2953 view->strides = NULL;
2954 view->suboffsets = NULL;
2955 view->internal = NULL;
2956 return 0;
2957 }
2958
2959 /*
2960 * CData objects are mutable, so they cannot be hashable!
2961 */
2962 static Py_hash_t
2963 PyCData_nohash(PyObject *self)
2964 {
2965 PyErr_SetString(PyExc_TypeError, "unhashable type");
2966 return -1;
2967 }
2968
2969 /*[clinic input]
2970 _ctypes.PyCData.__reduce__ as PyCData_reduce
2971
2972 myself: self
2973 cls: defining_class
2974 /
2975 [clinic start generated code]*/
2976
2977 static PyObject *
2978 PyCData_reduce_impl(PyObject *myself, PyTypeObject *cls)
2979 /*[clinic end generated code: output=1a025ccfdd8c935d input=34097a5226ea63c1]*/
2980 {
2981 CDataObject *self = (CDataObject *)myself;
2982
2983 ctypes_state *st = get_module_state_by_class(cls);
2984 StgInfo *info;
2985 if (PyStgInfo_FromObject(st, myself, &info) < 0) {
2986 return NULL;
2987 }
2988 assert(info);
2989
2990 if (info->flags & (TYPEFLAG_ISPOINTER|TYPEFLAG_HASPOINTER)) {
2991 PyErr_SetString(PyExc_ValueError,
2992 "ctypes objects containing pointers cannot be pickled");
2993 return NULL;
2994 }
2995 PyObject *dict = PyObject_GetAttrString(myself, "__dict__");
2996 if (dict == NULL) {
2997 return NULL;
2998 }
2999 return Py_BuildValue("O(O(NN))", st->_unpickle, Py_TYPE(myself), dict,
3000 PyBytes_FromStringAndSize(self->b_ptr, self->b_size));
3001 }
3002
3003 static PyObject *
3004 PyCData_setstate(PyObject *myself, PyObject *args)
3005 {
3006 void *data;
3007 Py_ssize_t len;
3008 int res;
3009 PyObject *dict, *mydict;
3010 CDataObject *self = (CDataObject *)myself;
3011 if (!PyArg_ParseTuple(args, "O!s#",
3012 &PyDict_Type, &dict, &data, &len))
3013 {
3014 return NULL;
3015 }
3016 if (len > self->b_size)
3017 len = self->b_size;
3018 memmove(self->b_ptr, data, len);
3019 mydict = PyObject_GetAttrString(myself, "__dict__");
3020 if (mydict == NULL) {
3021 return NULL;
3022 }
3023 if (!PyDict_Check(mydict)) {
3024 PyErr_Format(PyExc_TypeError,
3025 "%.200s.__dict__ must be a dictionary, not %.200s",
3026 Py_TYPE(myself)->tp_name, Py_TYPE(mydict)->tp_name);
3027 Py_DECREF(mydict);
3028 return NULL;
3029 }
3030 res = PyDict_Update(mydict, dict);
3031 Py_DECREF(mydict);
3032 if (res == -1)
3033 return NULL;
3034 Py_RETURN_NONE;
3035 }
3036
3037 /*
3038 * default __ctypes_from_outparam__ method returns self.
3039 */
3040 static PyObject *
3041 PyCData_from_outparam(PyObject *self, PyObject *args)
3042 {
3043 return Py_NewRef(self);
3044 }
3045
3046 static PyMethodDef PyCData_methods[] = {
3047 { "__ctypes_from_outparam__", PyCData_from_outparam, METH_NOARGS, },
3048 PYCDATA_REDUCE_METHODDEF
3049 { "__setstate__", PyCData_setstate, METH_VARARGS, },
3050 { NULL, NULL },
3051 };
3052
3053 static PyType_Slot pycdata_slots[] = {
3054 {Py_tp_dealloc, PyCData_dealloc},
3055 {Py_tp_hash, PyCData_nohash},
3056 {Py_tp_doc, PyDoc_STR("XXX to be provided")},
3057 {Py_tp_traverse, PyCData_traverse},
3058 {Py_tp_clear, PyCData_clear},
3059 {Py_tp_methods, PyCData_methods},
3060 {Py_tp_members, PyCData_members},
3061 {Py_bf_getbuffer, PyCData_NewGetBuffer},
3062 {0, NULL},
3063 };
3064
3065 static PyType_Spec pycdata_spec = {
3066 .name = "_ctypes._CData",
3067 .basicsize = sizeof(CDataObject),
3068 .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
3069 Py_TPFLAGS_IMMUTABLETYPE | Py_TPFLAGS_DISALLOW_INSTANTIATION),
3070 .slots = pycdata_slots,
3071 };
3072
3073 static int
3074 PyCData_MallocBuffer(CDataObject *obj, StgInfo *info)
3075 {
3076 if ((size_t)info->size <= sizeof(obj->b_value)) {
3077 /* No need to call malloc, can use the default buffer */
3078 obj->b_ptr = (char *)&obj->b_value;
3079 /* The b_needsfree flag does not mean that we actually did
3080 call PyMem_Malloc to allocate the memory block; instead it
3081 means we are the *owner* of the memory and are responsible
3082 for freeing resources associated with the memory. This is
3083 also the reason that b_needsfree is exposed to Python.
3084 */
3085 obj->b_needsfree = 1;
3086 } else {
3087 /* In python 2.4, and ctypes 0.9.6, the malloc call took about
3088 33% of the creation time for c_int().
3089 */
3090 obj->b_ptr = (char *)PyMem_Malloc(info->size);
3091 if (obj->b_ptr == NULL) {
3092 PyErr_NoMemory();
3093 return -1;
3094 }
3095 obj->b_needsfree = 1;
3096 memset(obj->b_ptr, 0, info->size);
3097 }
3098 obj->b_size = info->size;
3099 return 0;
3100 }
3101
3102 PyObject *
3103 PyCData_FromBaseObj(ctypes_state *st,
3104 PyObject *type, PyObject *base, Py_ssize_t index, char *adr)
3105 {
3106 CDataObject *cmem;
3107
3108 assert(PyType_Check(type));
3109
3110 StgInfo *info;
3111 if (PyStgInfo_FromType(st, type, &info) < 0) {
3112 return NULL;
3113 }
3114 if (!info) {
3115 PyErr_SetString(PyExc_TypeError,
3116 "abstract class");
3117 return NULL;
3118 }
3119
3120 info->flags |= DICTFLAG_FINAL;
3121 cmem = (CDataObject *)((PyTypeObject *)type)->tp_alloc((PyTypeObject *)type, 0);
3122 if (cmem == NULL) {
3123 return NULL;
3124 }
3125 assert(CDataObject_Check(st, cmem));
3126 cmem->b_length = info->length;
3127 cmem->b_size = info->size;
3128 if (base) { /* use base's buffer */
3129 assert(CDataObject_Check(st, base));
3130 cmem->b_ptr = adr;
3131 cmem->b_needsfree = 0;
3132 cmem->b_base = (CDataObject *)Py_NewRef(base);
3133 cmem->b_index = index;
3134 } else { /* copy contents of adr */
3135 if (-1 == PyCData_MallocBuffer(cmem, info)) {
3136 Py_DECREF(cmem);
3137 return NULL;
3138 }
3139 memcpy(cmem->b_ptr, adr, info->size);
3140 cmem->b_index = index;
3141 }
3142 return (PyObject *)cmem;
3143 }
3144
3145 /*
3146 Box a memory block into a CData instance.
3147 */
3148 PyObject *
3149 PyCData_AtAddress(ctypes_state *st, PyObject *type, void *buf)
3150 {
3151 CDataObject *pd;
3152
3153 if (PySys_Audit("ctypes.cdata", "n", (Py_ssize_t)buf) < 0) {
3154 return NULL;
3155 }
3156
3157 assert(PyType_Check(type));
3158
3159 StgInfo *info;
3160 if (PyStgInfo_FromType(st, type, &info) < 0) {
3161 return NULL;
3162 }
3163 if (!info) {
3164 PyErr_SetString(PyExc_TypeError,
3165 "abstract class");
3166 return NULL;
3167 }
3168
3169 info->flags |= DICTFLAG_FINAL;
3170
3171 pd = (CDataObject *)((PyTypeObject *)type)->tp_alloc((PyTypeObject *)type, 0);
3172 if (!pd) {
3173 return NULL;
3174 }
3175 assert(CDataObject_Check(st, pd));
3176 pd->b_ptr = (char *)buf;
3177 pd->b_length = info->length;
3178 pd->b_size = info->size;
3179 return (PyObject *)pd;
3180 }
3181
3182 /*
3183 This function returns TRUE for c_int, c_void_p, and these kind of
3184 classes. FALSE otherwise FALSE also for subclasses of c_int and
3185 such.
3186 */
3187 int _ctypes_simple_instance(ctypes_state *st, PyObject *obj)
3188 {
3189 PyTypeObject *type = (PyTypeObject *)obj;
3190
3191 if (PyCSimpleTypeObject_Check(st, type)) {
3192 return type->tp_base != st->Simple_Type;
3193 }
3194 return 0;
3195 }
3196
3197 PyObject *
3198 PyCData_get(ctypes_state *st, PyObject *type, GETFUNC getfunc, PyObject *src,
3199 Py_ssize_t index, Py_ssize_t size, char *adr)
3200 {
3201 if (getfunc)
3202 return getfunc(adr, size);
3203 assert(type);
3204 StgInfo *info;
3205 if (PyStgInfo_FromType(st, type, &info) < 0) {
3206 return NULL;
3207 }
3208 if (info && info->getfunc && !_ctypes_simple_instance(st, type)) {
3209 return info->getfunc(adr, size);
3210 }
3211 return PyCData_FromBaseObj(st, type, src, index, adr);
3212 }
3213
3214 /*
3215 Helper function for PyCData_set below.
3216 */
3217 static PyObject *
3218 _PyCData_set(ctypes_state *st,
3219 CDataObject *dst, PyObject *type, SETFUNC setfunc, PyObject *value,
3220 Py_ssize_t size, char *ptr)
3221 {
3222 CDataObject *src;
3223 int err;
3224
3225 if (setfunc) {
3226 return setfunc(ptr, value, size);
3227 }
3228 if (!CDataObject_Check(st, value)) {
3229 StgInfo *info;
3230 if (PyStgInfo_FromType(st, type, &info) < 0) {
3231 return NULL;
3232 }
3233 if (info && info->setfunc)
3234 return info->setfunc(ptr, value, size);
3235 /*
3236 If value is a tuple, we try to call the type with the tuple
3237 and use the result!
3238 */
3239 assert(PyType_Check(type));
3240 if (PyTuple_Check(value)) {
3241 PyObject *ob;
3242 PyObject *result;
3243 ob = PyObject_CallObject(type, value);
3244 if (ob == NULL) {
3245 _ctypes_extend_error(PyExc_RuntimeError, "(%s) ",
3246 ((PyTypeObject *)type)->tp_name);
3247 return NULL;
3248 }
3249 result = _PyCData_set(st, dst, type, setfunc, ob,
3250 size, ptr);
3251 Py_DECREF(ob);
3252 return result;
3253 } else if (value == Py_None && PyCPointerTypeObject_Check(st, type)) {
3254 *(void **)ptr = NULL;
3255 Py_RETURN_NONE;
3256 } else {
3257 PyErr_Format(PyExc_TypeError,
3258 "expected %s instance, got %s",
3259 ((PyTypeObject *)type)->tp_name,
3260 Py_TYPE(value)->tp_name);
3261 return NULL;
3262 }
3263 }
3264 src = (CDataObject *)value;
3265
3266 err = PyObject_IsInstance(value, type);
3267 if (err == -1)
3268 return NULL;
3269 if (err) {
3270 memcpy(ptr,
3271 src->b_ptr,
3272 size);
3273
3274 if (PyCPointerTypeObject_Check(st, type)) {
3275 /* XXX */
3276 }
3277
3278 value = GetKeepedObjects(src);
3279 if (value == NULL)
3280 return NULL;
3281
3282 return Py_NewRef(value);
3283 }
3284
3285 if (PyCPointerTypeObject_Check(st, type)
3286 && ArrayObject_Check(st, value)) {
3287 PyObject *keep;
3288
3289 StgInfo *p1, *p2;
3290 if (PyStgInfo_FromObject(st, value, &p1) < 0) {
3291 return NULL;
3292 }
3293 assert(p1); /* Cannot be NULL for array instances */
3294 if (PyStgInfo_FromType(st, type, &p2) < 0) {
3295 return NULL;
3296 }
3297 assert(p2); /* Cannot be NULL for pointer types */
3298
3299 if (p1->proto != p2->proto) {
3300 PyErr_Format(PyExc_TypeError,
3301 "incompatible types, %s instance instead of %s instance",
3302 Py_TYPE(value)->tp_name,
3303 ((PyTypeObject *)type)->tp_name);
3304 return NULL;
3305 }
3306 *(void **)ptr = src->b_ptr;
3307
3308 keep = GetKeepedObjects(src);
3309 if (keep == NULL)
3310 return NULL;
3311
3312 /*
3313 We are assigning an array object to a field which represents
3314 a pointer. This has the same effect as converting an array
3315 into a pointer. So, again, we have to keep the whole object
3316 pointed to (which is the array in this case) alive, and not
3317 only it's object list. So we create a tuple, containing
3318 b_objects list PLUS the array itself, and return that!
3319 */
3320 return PyTuple_Pack(2, keep, value);
3321 }
3322 PyErr_Format(PyExc_TypeError,
3323 "incompatible types, %s instance instead of %s instance",
3324 Py_TYPE(value)->tp_name,
3325 ((PyTypeObject *)type)->tp_name);
3326 return NULL;
3327 }
3328
3329 /*
3330 * Set a slice in object 'dst', which has the type 'type',
3331 * to the value 'value'.
3332 */
3333 int
3334 PyCData_set(ctypes_state *st,
3335 PyObject *dst, PyObject *type, SETFUNC setfunc, PyObject *value,
3336 Py_ssize_t index, Py_ssize_t size, char *ptr)
3337 {
3338 CDataObject *mem = (CDataObject *)dst;
3339 PyObject *result;
3340
3341 if (!CDataObject_Check(st, dst)) {
3342 PyErr_SetString(PyExc_TypeError,
3343 "not a ctype instance");
3344 return -1;
3345 }
3346
3347 result = _PyCData_set(st, mem, type, setfunc, value,
3348 size, ptr);
3349 if (result == NULL)
3350 return -1;
3351
3352 /* KeepRef steals a refcount from it's last argument */
3353 /* If KeepRef fails, we are stumped. The dst memory block has already
3354 been changed */
3355 return KeepRef(mem, index, result);
3356 }
3357
3358
3359 /******************************************************************/
3360 static PyObject *
3361 GenericPyCData_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3362 {
3363 ctypes_state *st = get_module_state_by_def(Py_TYPE(type));
3364 return generic_pycdata_new(st, type, args, kwds);
3365 }
3366
3367 static inline PyObject *
3368 generic_pycdata_new(ctypes_state *st,
3369 PyTypeObject *type, PyObject *args, PyObject *kwds)
3370 {
3371 CDataObject *obj;
3372
3373 StgInfo *info;
3374 if (PyStgInfo_FromType(st, (PyObject *)type, &info) < 0) {
3375 return NULL;
3376 }
3377 if (!info) {
3378 PyErr_SetString(PyExc_TypeError,
3379 "abstract class");
3380 return NULL;
3381 }
3382
3383 info->flags |= DICTFLAG_FINAL;
3384
3385 obj = (CDataObject *)type->tp_alloc(type, 0);
3386 if (!obj)
3387 return NULL;
3388
3389 obj->b_base = NULL;
3390 obj->b_index = 0;
3391 obj->b_objects = NULL;
3392 obj->b_length = info->length;
3393
3394 if (-1 == PyCData_MallocBuffer(obj, info)) {
3395 Py_DECREF(obj);
3396 return NULL;
3397 }
3398 return (PyObject *)obj;
3399 }
3400 /*****************************************************************/
3401 /*
3402 PyCFuncPtr_Type
3403 */
3404
3405 static int
3406 _validate_paramflags(ctypes_state *st, PyTypeObject *type, PyObject *paramflags, PyObject *argtypes);
3407
3408 static int
3409 PyCFuncPtr_set_errcheck(PyCFuncPtrObject *self, PyObject *ob, void *Py_UNUSED(ignored))
3410 {
3411 if (ob && !PyCallable_Check(ob)) {
3412 PyErr_SetString(PyExc_TypeError,
3413 "the errcheck attribute must be callable");
3414 return -1;
3415 }
3416 Py_XINCREF(ob);
3417 Py_XSETREF(self->errcheck, ob);
3418 return 0;
3419 }
3420
3421 static PyObject *
3422 PyCFuncPtr_get_errcheck(PyCFuncPtrObject *self, void *Py_UNUSED(ignored))
3423 {
3424 if (self->errcheck) {
3425 return Py_NewRef(self->errcheck);
3426 }
3427 Py_RETURN_NONE;
3428 }
3429
3430 static int
3431 PyCFuncPtr_set_restype(PyCFuncPtrObject *self, PyObject *ob, void *Py_UNUSED(ignored))
3432 {
3433 PyObject *checker, *oldchecker;
3434 if (ob == NULL) {
3435 oldchecker = self->checker;
3436 self->checker = NULL;
3437 Py_CLEAR(self->restype);
3438 Py_XDECREF(oldchecker);
3439 return 0;
3440 }
3441 ctypes_state *st = get_module_state_by_def(Py_TYPE(Py_TYPE(self)));
3442 StgInfo *info;
3443 if (PyStgInfo_FromType(st, ob, &info) < 0) {
3444 return -1;
3445 }
3446 if (ob != Py_None && !info && !PyCallable_Check(ob)) {
3447 PyErr_SetString(PyExc_TypeError,
3448 "restype must be a type, a callable, or None");
3449 return -1;
3450 }
3451 if (PyObject_GetOptionalAttr(ob, &_Py_ID(_check_retval_), &checker) < 0) {
3452 return -1;
3453 }
3454 oldchecker = self->checker;
3455 self->checker = checker;
3456 Py_INCREF(ob);
3457 Py_XSETREF(self->restype, ob);
3458 Py_XDECREF(oldchecker);
3459 return 0;
3460 }
3461
3462 static PyObject *
3463 PyCFuncPtr_get_restype(PyCFuncPtrObject *self, void *Py_UNUSED(ignored))
3464 {
3465 if (self->restype) {
3466 return Py_NewRef(self->restype);
3467 }
3468 ctypes_state *st = get_module_state_by_def(Py_TYPE(Py_TYPE(self)));
3469 StgInfo *info;
3470 if (PyStgInfo_FromObject(st, (PyObject *)self, &info) < 0) {
3471 return NULL;
3472 }
3473 assert(info); /* Cannot be NULL for PyCFuncPtrObject instances */
3474 if (info->restype) {
3475 return Py_NewRef(info->restype);
3476 } else {
3477 Py_RETURN_NONE;
3478 }
3479 }
3480
3481 static int
3482 PyCFuncPtr_set_argtypes(PyCFuncPtrObject *self, PyObject *value, void *Py_UNUSED(ignored))
3483 {
3484 if (value == NULL || value == Py_None) {
3485 Py_CLEAR(self->converters);
3486 Py_CLEAR(self->argtypes);
3487 } else {
3488 PyTypeObject *type = Py_TYPE(self);
3489 ctypes_state *st = get_module_state_by_def(Py_TYPE(type));
3490 PyObject *converters = converters_from_argtypes(st, value);
3491 if (!converters)
3492 return -1;
3493
3494 /* Verify paramflags again due to constraints with argtypes */
3495 if (!_validate_paramflags(st, type, self->paramflags, value)) {
3496 Py_DECREF(converters);
3497 return -1;
3498 }
3499 Py_XSETREF(self->converters, converters);
3500 Py_INCREF(value);
3501 Py_XSETREF(self->argtypes, value);
3502 }
3503 return 0;
3504 }
3505
3506 static PyObject *
3507 PyCFuncPtr_get_argtypes(PyCFuncPtrObject *self, void *Py_UNUSED(ignored))
3508 {
3509 if (self->argtypes) {
3510 return Py_NewRef(self->argtypes);
3511 }
3512 ctypes_state *st = get_module_state_by_def(Py_TYPE(Py_TYPE(self)));
3513 StgInfo *info;
3514 if (PyStgInfo_FromObject(st, (PyObject *)self, &info) < 0) {
3515 return NULL;
3516 }
3517 assert(info); /* Cannot be NULL for PyCFuncPtrObject instances */
3518 if (info->argtypes) {
3519 return Py_NewRef(info->argtypes);
3520 } else {
3521 Py_RETURN_NONE;
3522 }
3523 }
3524
3525 static PyGetSetDef PyCFuncPtr_getsets[] = {
3526 { "errcheck", (getter)PyCFuncPtr_get_errcheck, (setter)PyCFuncPtr_set_errcheck,
3527 "a function to check for errors", NULL },
3528 { "restype", (getter)PyCFuncPtr_get_restype, (setter)PyCFuncPtr_set_restype,
3529 "specify the result type", NULL },
3530 { "argtypes", (getter)PyCFuncPtr_get_argtypes,
3531 (setter)PyCFuncPtr_set_argtypes,
3532 "specify the argument types", NULL },
3533 { NULL, NULL }
3534 };
3535
3536 #ifdef MS_WIN32
3537 static PPROC FindAddress(void *handle, const char *name, PyObject *type)
3538 {
3539 PPROC address;
3540 #ifdef MS_WIN64
3541 /* win64 has no stdcall calling conv, so it should
3542 also not have the name mangling of it.
3543 */
3544 Py_BEGIN_ALLOW_THREADS
3545 address = (PPROC)GetProcAddress(handle, name);
3546 Py_END_ALLOW_THREADS
3547 return address;
3548 #else
3549 char *mangled_name;
3550 int i;
3551
3552 Py_BEGIN_ALLOW_THREADS
3553 address = (PPROC)GetProcAddress(handle, name);
3554 Py_END_ALLOW_THREADS
3555 if (address)
3556 return address;
3557 if (((size_t)name & ~0xFFFF) == 0) {
3558 return NULL;
3559 }
3560
3561 ctypes_state *st = get_module_state_by_def(Py_TYPE(type));
3562 StgInfo *info;
3563 if (PyStgInfo_FromType(st, (PyObject *)type, &info) < 0) {
3564 return NULL;
3565 }
3566 /* It should not happen that info is NULL, but better be safe */
3567 if (info==NULL || info->flags & FUNCFLAG_CDECL)
3568 return address;
3569
3570 /* for stdcall, try mangled names:
3571 funcname -> _funcname@<n>
3572 where n is 0, 4, 8, 12, ..., 128
3573 */
3574 mangled_name = alloca(strlen(name) + 1 + 1 + 1 + 3); /* \0 _ @ %d */
3575 if (!mangled_name)
3576 return NULL;
3577 for (i = 0; i < 32; ++i) {
3578 sprintf(mangled_name, "_%s@%d", name, i*4);
3579 Py_BEGIN_ALLOW_THREADS
3580 address = (PPROC)GetProcAddress(handle, mangled_name);
3581 Py_END_ALLOW_THREADS
3582 if (address)
3583 return address;
3584 }
3585 return NULL;
3586 #endif
3587 }
3588 #endif
3589
3590 /* Return 1 if usable, 0 else and exception set. */
3591 static int
3592 _check_outarg_type(ctypes_state *st, PyObject *arg, Py_ssize_t index)
3593 {
3594 if (PyCPointerTypeObject_Check(st, arg)) {
3595 return 1;
3596 }
3597 if (PyCArrayTypeObject_Check(st, arg)) {
3598 return 1;
3599 }
3600 StgInfo *info;
3601 if (PyStgInfo_FromType(st, arg, &info) < 0) {
3602 return -1;
3603 }
3604 if (info
3605 /* simple pointer types, c_void_p, c_wchar_p, BSTR, ... */
3606 && PyUnicode_Check(info->proto)
3607 /* We only allow c_void_p, c_char_p and c_wchar_p as a simple output parameter type */
3608 && (strchr("PzZ", PyUnicode_AsUTF8(info->proto)[0]))) {
3609 return 1;
3610 }
3611
3612 PyErr_Format(PyExc_TypeError,
3613 "'out' parameter %d must be a pointer type, not %s",
3614 Py_SAFE_DOWNCAST(index, Py_ssize_t, int),
3615 PyType_Check(arg) ?
3616 ((PyTypeObject *)arg)->tp_name :
3617 Py_TYPE(arg)->tp_name);
3618 return 0;
3619 }
3620
3621 /* Returns 1 on success, 0 on error */
3622 static int
3623 _validate_paramflags(ctypes_state *st, PyTypeObject *type, PyObject *paramflags, PyObject *argtypes)
3624 {
3625 Py_ssize_t i, len;
3626
3627 StgInfo *info;
3628 if (PyStgInfo_FromType(st, (PyObject *)type, &info) < 0) {
3629 return -1;
3630 }
3631 if (!info) {
3632 PyErr_SetString(PyExc_TypeError,
3633 "abstract class");
3634 return 0;
3635 }
3636 if (argtypes == NULL) {
3637 argtypes = info->argtypes;
3638 }
3639
3640 if (paramflags == NULL || argtypes == NULL) {
3641 return 1;
3642 }
3643
3644 if (!PyTuple_Check(paramflags)) {
3645 PyErr_SetString(PyExc_TypeError,
3646 "paramflags must be a tuple or None");
3647 return 0;
3648 }
3649
3650 len = PyTuple_GET_SIZE(paramflags);
3651 if (len != PyTuple_GET_SIZE(argtypes)) {
3652 PyErr_SetString(PyExc_ValueError,
3653 "paramflags must have the same length as argtypes");
3654 return 0;
3655 }
3656
3657 for (i = 0; i < len; ++i) {
3658 PyObject *item = PyTuple_GET_ITEM(paramflags, i);
3659 int flag;
3660 PyObject *name = Py_None;
3661 PyObject *defval;
3662 PyObject *typ;
3663 if (!PyArg_ParseTuple(item, "i|OO", &flag, &name, &defval) ||
3664 !(name == Py_None || PyUnicode_Check(name)))
3665 {
3666 PyErr_SetString(PyExc_TypeError,
3667 "paramflags must be a sequence of (int [,string [,value]]) tuples");
3668 return 0;
3669 }
3670 typ = PyTuple_GET_ITEM(argtypes, i);
3671 switch (flag & (PARAMFLAG_FIN | PARAMFLAG_FOUT | PARAMFLAG_FLCID)) {
3672 case 0:
3673 case PARAMFLAG_FIN:
3674 case PARAMFLAG_FIN | PARAMFLAG_FLCID:
3675 case PARAMFLAG_FIN | PARAMFLAG_FOUT:
3676 break;
3677 case PARAMFLAG_FOUT:
3678 if (!_check_outarg_type(st, typ, i+1))
3679 return 0;
3680 break;
3681 default:
3682 PyErr_Format(PyExc_TypeError,
3683 "paramflag value %d not supported",
3684 flag);
3685 return 0;
3686 }
3687 }
3688 return 1;
3689 }
3690
3691 static int
3692 _get_name(PyObject *obj, const char **pname)
3693 {
3694 #ifdef MS_WIN32
3695 if (PyLong_Check(obj)) {
3696 /* We have to use MAKEINTRESOURCEA for Windows CE.
3697 Works on Windows as well, of course.
3698 */
3699 *pname = MAKEINTRESOURCEA(PyLong_AsUnsignedLongMask(obj) & 0xFFFF);
3700 return 1;
3701 }
3702 #endif
3703 if (PyBytes_Check(obj)) {
3704 *pname = PyBytes_AS_STRING(obj);
3705 return *pname ? 1 : 0;
3706 }
3707 if (PyUnicode_Check(obj)) {
3708 *pname = PyUnicode_AsUTF8(obj);
3709 return *pname ? 1 : 0;
3710 }
3711 PyErr_SetString(PyExc_TypeError,
3712 "function name must be string, bytes object or integer");
3713 return 0;
3714 }
3715
3716
3717 static PyObject *
3718 PyCFuncPtr_FromDll(PyTypeObject *type, PyObject *args, PyObject *kwds)
3719 {
3720 const char *name;
3721 int (* address)(void);
3722 PyObject *ftuple;
3723 PyObject *dll;
3724 PyObject *obj;
3725 PyCFuncPtrObject *self;
3726 void *handle;
3727 PyObject *paramflags = NULL;
3728
3729 if (!PyArg_ParseTuple(args, "O|O", &ftuple, &paramflags))
3730 return NULL;
3731 if (paramflags == Py_None)
3732 paramflags = NULL;
3733
3734 ftuple = PySequence_Tuple(ftuple);
3735 if (!ftuple)
3736 /* Here ftuple is a borrowed reference */
3737 return NULL;
3738
3739 if (!PyArg_ParseTuple(ftuple, "O&O;illegal func_spec argument",
3740 _get_name, &name, &dll))
3741 {
3742 Py_DECREF(ftuple);
3743 return NULL;
3744 }
3745
3746 #ifdef MS_WIN32
3747 if (PySys_Audit("ctypes.dlsym",
3748 ((uintptr_t)name & ~0xFFFF) ? "Os" : "On",
3749 dll, name) < 0) {
3750 Py_DECREF(ftuple);
3751 return NULL;
3752 }
3753 #else
3754 if (PySys_Audit("ctypes.dlsym", "Os", dll, name) < 0) {
3755 Py_DECREF(ftuple);
3756 return NULL;
3757 }
3758 #endif
3759
3760 obj = PyObject_GetAttrString(dll, "_handle");
3761 if (!obj) {
3762 Py_DECREF(ftuple);
3763 return NULL;
3764 }
3765 if (!PyLong_Check(obj)) {
3766 PyErr_SetString(PyExc_TypeError,
3767 "the _handle attribute of the second argument must be an integer");
3768 Py_DECREF(ftuple);
3769 Py_DECREF(obj);
3770 return NULL;
3771 }
3772 handle = (void *)PyLong_AsVoidPtr(obj);
3773 Py_DECREF(obj);
3774 if (PyErr_Occurred()) {
3775 PyErr_SetString(PyExc_ValueError,
3776 "could not convert the _handle attribute to a pointer");
3777 Py_DECREF(ftuple);
3778 return NULL;
3779 }
3780
3781 #undef USE_DLERROR
3782 #ifdef MS_WIN32
3783 address = FindAddress(handle, name, (PyObject *)type);
3784 if (!address) {
3785 if (!IS_INTRESOURCE(name))
3786 PyErr_Format(PyExc_AttributeError,
3787 "function '%s' not found",
3788 name);
3789 else
3790 PyErr_Format(PyExc_AttributeError,
3791 "function ordinal %d not found",
3792 (WORD)(size_t)name);
3793 Py_DECREF(ftuple);
3794 return NULL;
3795 }
3796 #else
3797 #ifdef __CYGWIN__
3798 //dlerror() isn't very helpful on cygwin */
3799 #else
3800 #define USE_DLERROR
3801 /* dlerror() always returns the latest error.
3802 *
3803 * Clear the previous value before calling dlsym(),
3804 * to ensure we can tell if our call resulted in an error.
3805 */
3806 (void)dlerror();
3807 #endif
3808 address = (PPROC)dlsym(handle, name);
3809
3810 if (!address) {
3811 #ifdef USE_DLERROR
3812 const char *dlerr = dlerror();
3813 if (dlerr) {
3814 _PyErr_SetLocaleString(PyExc_AttributeError, dlerr);
3815 Py_DECREF(ftuple);
3816 return NULL;
3817 }
3818 #endif
3819 PyErr_Format(PyExc_AttributeError, "function '%s' not found", name);
3820 Py_DECREF(ftuple);
3821 return NULL;
3822 }
3823 #endif
3824 #undef USE_DLERROR
3825 ctypes_state *st = get_module_state_by_def(Py_TYPE(type));
3826 if (!_validate_paramflags(st, type, paramflags, NULL)) {
3827 Py_DECREF(ftuple);
3828 return NULL;
3829 }
3830
3831 self = (PyCFuncPtrObject *)generic_pycdata_new(st, type, args, kwds);
3832 if (!self) {
3833 Py_DECREF(ftuple);
3834 return NULL;
3835 }
3836
3837 self->paramflags = Py_XNewRef(paramflags);
3838
3839 *(void **)self->b_ptr = address;
3840 Py_INCREF(dll);
3841 Py_DECREF(ftuple);
3842 if (-1 == KeepRef((CDataObject *)self, 0, dll)) {
3843 Py_DECREF((PyObject *)self);
3844 return NULL;
3845 }
3846
3847 self->callable = Py_NewRef(self);
3848 return (PyObject *)self;
3849 }
3850
3851 #ifdef MS_WIN32
3852 static PyObject *
3853 PyCFuncPtr_FromVtblIndex(PyTypeObject *type, PyObject *args, PyObject *kwds)
3854 {
3855 PyCFuncPtrObject *self;
3856 int index;
3857 char *name = NULL;
3858 PyObject *paramflags = NULL;
3859 GUID *iid = NULL;
3860 Py_ssize_t iid_len = 0;
3861
3862 if (!PyArg_ParseTuple(args, "is|Oz#", &index, &name, &paramflags, &iid, &iid_len))
3863 return NULL;
3864 if (paramflags == Py_None)
3865 paramflags = NULL;
3866
3867 ctypes_state *st = get_module_state_by_def(Py_TYPE(type));
3868 if (!_validate_paramflags(st, type, paramflags, NULL)) {
3869 return NULL;
3870 }
3871 self = (PyCFuncPtrObject *)generic_pycdata_new(st, type, args, kwds);
3872 self->index = index + 0x1000;
3873 self->paramflags = Py_XNewRef(paramflags);
3874 if (iid_len == sizeof(GUID))
3875 self->iid = iid;
3876 return (PyObject *)self;
3877 }
3878 #endif
3879
3880 /*
3881 PyCFuncPtr_new accepts different argument lists in addition to the standard
3882 _basespec_ keyword arg:
3883
3884 one argument form
3885 "i" - function address
3886 "O" - must be a callable, creates a C callable function
3887
3888 two or more argument forms (the third argument is a paramflags tuple)
3889 "(sO)|..." - (function name, dll object (with an integer handle)), paramflags
3890 "(iO)|..." - (function ordinal, dll object (with an integer handle)), paramflags
3891 "is|..." - vtable index, method name, creates callable calling COM vtbl
3892 */
3893 static PyObject *
3894 PyCFuncPtr_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3895 {
3896 PyCFuncPtrObject *self;
3897 PyObject *callable;
3898 CThunkObject *thunk;
3899
3900 if (PyTuple_GET_SIZE(args) == 0)
3901 return GenericPyCData_new(type, args, kwds);
3902
3903 if (1 <= PyTuple_GET_SIZE(args) && PyTuple_Check(PyTuple_GET_ITEM(args, 0)))
3904 return PyCFuncPtr_FromDll(type, args, kwds);
3905
3906 #ifdef MS_WIN32
3907 if (2 <= PyTuple_GET_SIZE(args) && PyLong_Check(PyTuple_GET_ITEM(args, 0)))
3908 return PyCFuncPtr_FromVtblIndex(type, args, kwds);
3909 #endif
3910
3911 if (1 == PyTuple_GET_SIZE(args)
3912 && (PyLong_Check(PyTuple_GET_ITEM(args, 0)))) {
3913 CDataObject *ob;
3914 void *ptr = PyLong_AsVoidPtr(PyTuple_GET_ITEM(args, 0));
3915 if (ptr == NULL && PyErr_Occurred())
3916 return NULL;
3917 ob = (CDataObject *)GenericPyCData_new(type, args, kwds);
3918 if (ob == NULL)
3919 return NULL;
3920 *(void **)ob->b_ptr = ptr;
3921 return (PyObject *)ob;
3922 }
3923
3924 if (!PyArg_ParseTuple(args, "O", &callable))
3925 return NULL;
3926 if (!PyCallable_Check(callable)) {
3927 PyErr_SetString(PyExc_TypeError,
3928 "argument must be callable or integer function address");
3929 return NULL;
3930 }
3931
3932 /* XXX XXX This would allow passing additional options. For COM
3933 method *implementations*, we would probably want different
3934 behaviour than in 'normal' callback functions: return a HRESULT if
3935 an exception occurs in the callback, and print the traceback not
3936 only on the console, but also to OutputDebugString() or something
3937 like that.
3938 */
3939 /*
3940 if (kwds && _PyDict_GetItemIdWithError(kwds, &PyId_options)) {
3941 ...
3942 }
3943 else if (PyErr_Occurred()) {
3944 return NULL;
3945 }
3946 */
3947
3948 ctypes_state *st = get_module_state_by_def(Py_TYPE(type));
3949 StgInfo *info;
3950 if (PyStgInfo_FromType(st, (PyObject *)type, &info) < 0) {
3951 return NULL;
3952 }
3953 /* XXXX Fails if we do: 'PyCFuncPtr(lambda x: x)' */
3954 if (!info || !info->argtypes) {
3955 PyErr_SetString(PyExc_TypeError,
3956 "cannot construct instance of this class:"
3957 " no argtypes");
3958 return NULL;
3959 }
3960
3961 thunk = _ctypes_alloc_callback(st,
3962 callable,
3963 info->argtypes,
3964 info->restype,
3965 info->flags);
3966 if (!thunk)
3967 return NULL;
3968
3969 self = (PyCFuncPtrObject *)generic_pycdata_new(st, type, args, kwds);
3970 if (self == NULL) {
3971 Py_DECREF(thunk);
3972 return NULL;
3973 }
3974
3975 self->callable = Py_NewRef(callable);
3976
3977 self->thunk = thunk;
3978 *(void **)self->b_ptr = (void *)thunk->pcl_exec;
3979
3980 Py_INCREF((PyObject *)thunk); /* for KeepRef */
3981 if (-1 == KeepRef((CDataObject *)self, 0, (PyObject *)thunk)) {
3982 Py_DECREF((PyObject *)self);
3983 return NULL;
3984 }
3985 return (PyObject *)self;
3986 }
3987
3988
3989 /*
3990 _byref consumes a refcount to its argument
3991 */
3992 static PyObject *
3993 _byref(ctypes_state *st, PyObject *obj)
3994 {
3995 PyCArgObject *parg;
3996
3997 if (!CDataObject_Check(st, obj)) {
3998 PyErr_SetString(PyExc_TypeError,
3999 "expected CData instance");
4000 return NULL;
4001 }
4002
4003 parg = PyCArgObject_new(st);
4004 if (parg == NULL) {
4005 Py_DECREF(obj);
4006 return NULL;
4007 }
4008
4009 parg->tag = 'P';
4010 parg->pffi_type = &ffi_type_pointer;
4011 parg->obj = obj;
4012 parg->value.p = ((CDataObject *)obj)->b_ptr;
4013 return (PyObject *)parg;
4014 }
4015
4016 static PyObject *
4017 _get_arg(int *pindex, PyObject *name, PyObject *defval, PyObject *inargs, PyObject *kwds)
4018 {
4019 PyObject *v;
4020
4021 if (*pindex < PyTuple_GET_SIZE(inargs)) {
4022 v = PyTuple_GET_ITEM(inargs, *pindex);
4023 ++*pindex;
4024 return Py_NewRef(v);
4025 }
4026 if (kwds && name) {
4027 if (PyDict_GetItemRef(kwds, name, &v) < 0) {
4028 return NULL;
4029 }
4030 if (v) {
4031 ++*pindex;
4032 return v;
4033 }
4034 }
4035 if (defval) {
4036 return Py_NewRef(defval);
4037 }
4038 /* we can't currently emit a better error message */
4039 if (name)
4040 PyErr_Format(PyExc_TypeError,
4041 "required argument '%S' missing", name);
4042 else
4043 PyErr_Format(PyExc_TypeError,
4044 "not enough arguments");
4045 return NULL;
4046 }
4047
4048 /*
4049 This function implements higher level functionality plus the ability to call
4050 functions with keyword arguments by looking at parameter flags. parameter
4051 flags is a tuple of 1, 2 or 3-tuples. The first entry in each is an integer
4052 specifying the direction of the data transfer for this parameter - 'in',
4053 'out' or 'inout' (zero means the same as 'in'). The second entry is the
4054 parameter name, and the third is the default value if the parameter is
4055 missing in the function call.
4056
4057 This function builds and returns a new tuple 'callargs' which contains the
4058 parameters to use in the call. Items on this tuple are copied from the
4059 'inargs' tuple for 'in' and 'in, out' parameters, and constructed from the
4060 'argtypes' tuple for 'out' parameters. It also calculates numretvals which
4061 is the number of return values for the function, outmask/inoutmask are
4062 bitmasks containing indexes into the callargs tuple specifying which
4063 parameters have to be returned. _build_result builds the return value of the
4064 function.
4065 */
4066 static PyObject *
4067 _build_callargs(ctypes_state *st, PyCFuncPtrObject *self, PyObject *argtypes,
4068 PyObject *inargs, PyObject *kwds,
4069 int *poutmask, int *pinoutmask, unsigned int *pnumretvals)
4070 {
4071 PyObject *paramflags = self->paramflags;
4072 PyObject *callargs;
4073 Py_ssize_t i, len;
4074 int inargs_index = 0;
4075 /* It's a little bit difficult to determine how many arguments the
4076 function call requires/accepts. For simplicity, we count the consumed
4077 args and compare this to the number of supplied args. */
4078 Py_ssize_t actual_args;
4079
4080 *poutmask = 0;
4081 *pinoutmask = 0;
4082 *pnumretvals = 0;
4083
4084 /* Trivial cases, where we either return inargs itself, or a slice of it. */
4085 if (argtypes == NULL || paramflags == NULL || PyTuple_GET_SIZE(argtypes) == 0) {
4086 #ifdef MS_WIN32
4087 if (self->index)
4088 return PyTuple_GetSlice(inargs, 1, PyTuple_GET_SIZE(inargs));
4089 #endif
4090 return Py_NewRef(inargs);
4091 }
4092
4093 len = PyTuple_GET_SIZE(argtypes);
4094 callargs = PyTuple_New(len); /* the argument tuple we build */
4095 if (callargs == NULL)
4096 return NULL;
4097
4098 #ifdef MS_WIN32
4099 /* For a COM method, skip the first arg */
4100 if (self->index) {
4101 inargs_index = 1;
4102 }
4103 #endif
4104 for (i = 0; i < len; ++i) {
4105 PyObject *item = PyTuple_GET_ITEM(paramflags, i);
4106 PyObject *ob;
4107 unsigned int flag;
4108 PyObject *name = NULL;
4109 PyObject *defval = NULL;
4110
4111 /* This way seems to be ~2 us faster than the PyArg_ParseTuple
4112 calls below. */
4113 /* We HAVE already checked that the tuple can be parsed with "i|ZO", so... */
4114 Py_ssize_t tsize = PyTuple_GET_SIZE(item);
4115 flag = PyLong_AsUnsignedLongMask(PyTuple_GET_ITEM(item, 0));
4116 name = tsize > 1 ? PyTuple_GET_ITEM(item, 1) : NULL;
4117 defval = tsize > 2 ? PyTuple_GET_ITEM(item, 2) : NULL;
4118
4119 switch (flag & (PARAMFLAG_FIN | PARAMFLAG_FOUT | PARAMFLAG_FLCID)) {
4120 case PARAMFLAG_FIN | PARAMFLAG_FLCID:
4121 /* ['in', 'lcid'] parameter. Always taken from defval,
4122 if given, else the integer 0. */
4123 if (defval == NULL) {
4124 defval = _PyLong_GetZero();
4125 }
4126 Py_INCREF(defval);
4127 PyTuple_SET_ITEM(callargs, i, defval);
4128 break;
4129 case (PARAMFLAG_FIN | PARAMFLAG_FOUT):
4130 *pinoutmask |= (1 << i); /* mark as inout arg */
4131 (*pnumretvals)++;
4132 /* fall through */
4133 case 0:
4134 case PARAMFLAG_FIN:
4135 /* 'in' parameter. Copy it from inargs. */
4136 ob =_get_arg(&inargs_index, name, defval, inargs, kwds);
4137 if (ob == NULL)
4138 goto error;
4139 PyTuple_SET_ITEM(callargs, i, ob);
4140 break;
4141 case PARAMFLAG_FOUT:
4142 /* XXX Refactor this code into a separate function. */
4143 /* 'out' parameter.
4144 argtypes[i] must be a POINTER to a c type.
4145
4146 Cannot by supplied in inargs, but a defval will be used
4147 if available. XXX Should we support getting it from kwds?
4148 */
4149 if (defval) {
4150 /* XXX Using mutable objects as defval will
4151 make the function non-threadsafe, unless we
4152 copy the object in each invocation */
4153 Py_INCREF(defval);
4154 PyTuple_SET_ITEM(callargs, i, defval);
4155 *poutmask |= (1 << i); /* mark as out arg */
4156 (*pnumretvals)++;
4157 break;
4158 }
4159 ob = PyTuple_GET_ITEM(argtypes, i);
4160 StgInfo *info;
4161 if (PyStgInfo_FromType(st, ob, &info) < 0) {
4162 goto error;
4163 }
4164 if (info == NULL) {
4165 /* Cannot happen: _validate_paramflags()
4166 would not accept such an object */
4167 PyErr_Format(PyExc_RuntimeError,
4168 "NULL stginfo unexpected");
4169 goto error;
4170 }
4171 if (PyUnicode_Check(info->proto)) {
4172 PyErr_Format(
4173 PyExc_TypeError,
4174 "%s 'out' parameter must be passed as default value",
4175 ((PyTypeObject *)ob)->tp_name);
4176 goto error;
4177 }
4178 if (PyCArrayTypeObject_Check(st, ob)) {
4179 ob = _PyObject_CallNoArgs(ob);
4180 }
4181 else {
4182 /* Create an instance of the pointed-to type */
4183 ob = _PyObject_CallNoArgs(info->proto);
4184 }
4185 /*
4186 XXX Is the following correct any longer?
4187 We must not pass a byref() to the array then but
4188 the array instance itself. Then, we cannot retrieve
4189 the result from the PyCArgObject.
4190 */
4191 if (ob == NULL)
4192 goto error;
4193 /* The .from_param call that will occur later will pass this
4194 as a byref parameter. */
4195 PyTuple_SET_ITEM(callargs, i, ob);
4196 *poutmask |= (1 << i); /* mark as out arg */
4197 (*pnumretvals)++;
4198 break;
4199 default:
4200 PyErr_Format(PyExc_ValueError,
4201 "paramflag %u not yet implemented", flag);
4202 goto error;
4203 break;
4204 }
4205 }
4206
4207 /* We have counted the arguments we have consumed in 'inargs_index'. This
4208 must be the same as len(inargs) + len(kwds), otherwise we have
4209 either too much or not enough arguments. */
4210
4211 actual_args = PyTuple_GET_SIZE(inargs) + (kwds ? PyDict_GET_SIZE(kwds) : 0);
4212 if (actual_args != inargs_index) {
4213 /* When we have default values or named parameters, this error
4214 message is misleading. See unittests/test_paramflags.py
4215 */
4216 PyErr_Format(PyExc_TypeError,
4217 "call takes exactly %d arguments (%zd given)",
4218 inargs_index, actual_args);
4219 goto error;
4220 }
4221
4222 /* outmask is a bitmask containing indexes into callargs. Items at
4223 these indexes contain values to return.
4224 */
4225 return callargs;
4226 error:
4227 Py_DECREF(callargs);
4228 return NULL;
4229 }
4230
4231 /* See also:
4232 http://msdn.microsoft.com/library/en-us/com/html/769127a1-1a14-4ed4-9d38-7cf3e571b661.asp
4233 */
4234 /*
4235 Build return value of a function.
4236
4237 Consumes the refcount on result and callargs.
4238 */
4239 static PyObject *
4240 _build_result(PyObject *result, PyObject *callargs,
4241 int outmask, int inoutmask, unsigned int numretvals)
4242 {
4243 unsigned int i, index;
4244 int bit;
4245 PyObject *tup = NULL;
4246
4247 if (callargs == NULL)
4248 return result;
4249 if (result == NULL || numretvals == 0) {
4250 Py_DECREF(callargs);
4251 return result;
4252 }
4253 Py_DECREF(result);
4254
4255 /* tup will not be allocated if numretvals == 1 */
4256 /* allocate tuple to hold the result */
4257 if (numretvals > 1) {
4258 tup = PyTuple_New(numretvals);
4259 if (tup == NULL) {
4260 Py_DECREF(callargs);
4261 return NULL;
4262 }
4263 }
4264
4265 index = 0;
4266 for (bit = 1, i = 0; i < 32; ++i, bit <<= 1) {
4267 PyObject *v;
4268 if (bit & inoutmask) {
4269 v = PyTuple_GET_ITEM(callargs, i);
4270 Py_INCREF(v);
4271 if (numretvals == 1) {
4272 Py_DECREF(callargs);
4273 return v;
4274 }
4275 PyTuple_SET_ITEM(tup, index, v);
4276 index++;
4277 } else if (bit & outmask) {
4278
4279 v = PyTuple_GET_ITEM(callargs, i);
4280 v = PyObject_CallMethodNoArgs(v, &_Py_ID(__ctypes_from_outparam__));
4281 if (v == NULL || numretvals == 1) {
4282 Py_XDECREF(tup);
4283 Py_DECREF(callargs);
4284 return v;
4285 }
4286 PyTuple_SET_ITEM(tup, index, v);
4287 index++;
4288 }
4289 if (index == numretvals)
4290 break;
4291 }
4292
4293 Py_DECREF(callargs);
4294 return tup;
4295 }
4296
4297 static PyObject *
4298 PyCFuncPtr_call(PyCFuncPtrObject *self, PyObject *inargs, PyObject *kwds)
4299 {
4300 PyObject *restype;
4301 PyObject *converters;
4302 PyObject *checker;
4303 PyObject *argtypes;
4304 PyObject *result;
4305 PyObject *callargs;
4306 PyObject *errcheck;
4307 #ifdef MS_WIN32
4308 IUnknown *piunk = NULL;
4309 #endif
4310 void *pProc = NULL;
4311
4312 int inoutmask;
4313 int outmask;
4314 unsigned int numretvals;
4315
4316 ctypes_state *st = get_module_state_by_def(Py_TYPE(Py_TYPE(self)));
4317 StgInfo *info;
4318 if (PyStgInfo_FromObject(st, (PyObject *)self, &info) < 0) {
4319 return NULL;
4320 }
4321 assert(info); /* Cannot be NULL for PyCFuncPtrObject instances */
4322
4323 restype = self->restype ? self->restype : info->restype;
4324 converters = self->converters ? self->converters : info->converters;
4325 checker = self->checker ? self->checker : info->checker;
4326 argtypes = self->argtypes ? self->argtypes : info->argtypes;
4327 /* later, we probably want to have an errcheck field in stginfo */
4328 errcheck = self->errcheck /* ? self->errcheck : info->errcheck */;
4329
4330
4331 pProc = *(void **)self->b_ptr;
4332 #ifdef MS_WIN32
4333 if (self->index) {
4334 /* It's a COM method */
4335 CDataObject *this;
4336 this = (CDataObject *)PyTuple_GetItem(inargs, 0); /* borrowed ref! */
4337 if (!this) {
4338 PyErr_SetString(PyExc_ValueError,
4339 "native com method call without 'this' parameter");
4340 return NULL;
4341 }
4342 if (!CDataObject_Check(st, this)) {
4343 PyErr_SetString(PyExc_TypeError,
4344 "Expected a COM this pointer as first argument");
4345 return NULL;
4346 }
4347 /* there should be more checks? No, in Python */
4348 /* First arg is a pointer to an interface instance */
4349 if (!this->b_ptr || *(void **)this->b_ptr == NULL) {
4350 PyErr_SetString(PyExc_ValueError,
4351 "NULL COM pointer access");
4352 return NULL;
4353 }
4354 piunk = *(IUnknown **)this->b_ptr;
4355 if (NULL == piunk->lpVtbl) {
4356 PyErr_SetString(PyExc_ValueError,
4357 "COM method call without VTable");
4358 return NULL;
4359 }
4360 pProc = ((void **)piunk->lpVtbl)[self->index - 0x1000];
4361 }
4362 #endif
4363 callargs = _build_callargs(st, self, argtypes,
4364 inargs, kwds,
4365 &outmask, &inoutmask, &numretvals);
4366 if (callargs == NULL)
4367 return NULL;
4368
4369 if (converters) {
4370 int required = Py_SAFE_DOWNCAST(PyTuple_GET_SIZE(converters),
4371 Py_ssize_t, int);
4372 int actual = Py_SAFE_DOWNCAST(PyTuple_GET_SIZE(callargs),
4373 Py_ssize_t, int);
4374
4375 if ((info->flags & FUNCFLAG_CDECL) == FUNCFLAG_CDECL) {
4376 /* For cdecl functions, we allow more actual arguments
4377 than the length of the argtypes tuple.
4378 */
4379 if (required > actual) {
4380 Py_DECREF(callargs);
4381 PyErr_Format(PyExc_TypeError,
4382 "this function takes at least %d argument%s (%d given)",
4383 required,
4384 required == 1 ? "" : "s",
4385 actual);
4386 return NULL;
4387 }
4388 } else if (required != actual) {
4389 Py_DECREF(callargs);
4390 PyErr_Format(PyExc_TypeError,
4391 "this function takes %d argument%s (%d given)",
4392 required,
4393 required == 1 ? "" : "s",
4394 actual);
4395 return NULL;
4396 }
4397 }
4398
4399 result = _ctypes_callproc(st,
4400 pProc,
4401 callargs,
4402 #ifdef MS_WIN32
4403 piunk,
4404 self->iid,
4405 #endif
4406 info->flags,
4407 converters,
4408 restype,
4409 checker);
4410 /* The 'errcheck' protocol */
4411 if (result != NULL && errcheck) {
4412 PyObject *v = PyObject_CallFunctionObjArgs(errcheck,
4413 result,
4414 self,
4415 callargs,
4416 NULL);
4417 /* If the errcheck function failed, return NULL.
4418 If the errcheck function returned callargs unchanged,
4419 continue normal processing.
4420 If the errcheck function returned something else,
4421 use that as result.
4422 */
4423 if (v == NULL || v != callargs) {
4424 Py_DECREF(result);
4425 Py_DECREF(callargs);
4426 return v;
4427 }
4428 Py_DECREF(v);
4429 }
4430
4431 return _build_result(result, callargs,
4432 outmask, inoutmask, numretvals);
4433 }
4434
4435 static int
4436 PyCFuncPtr_traverse(PyCFuncPtrObject *self, visitproc visit, void *arg)
4437 {
4438 Py_VISIT(self->callable);
4439 Py_VISIT(self->restype);
4440 Py_VISIT(self->checker);
4441 Py_VISIT(self->errcheck);
4442 Py_VISIT(self->argtypes);
4443 Py_VISIT(self->converters);
4444 Py_VISIT(self->paramflags);
4445 Py_VISIT(self->thunk);
4446 return PyCData_traverse((CDataObject *)self, visit, arg);
4447 }
4448
4449 static int
4450 PyCFuncPtr_clear(PyCFuncPtrObject *self)
4451 {
4452 Py_CLEAR(self->callable);
4453 Py_CLEAR(self->restype);
4454 Py_CLEAR(self->checker);
4455 Py_CLEAR(self->errcheck);
4456 Py_CLEAR(self->argtypes);
4457 Py_CLEAR(self->converters);
4458 Py_CLEAR(self->paramflags);
4459 Py_CLEAR(self->thunk);
4460 return PyCData_clear((CDataObject *)self);
4461 }
4462
4463 static void
4464 PyCFuncPtr_dealloc(PyCFuncPtrObject *self)
4465 {
4466 PyObject_GC_UnTrack(self);
4467 PyCFuncPtr_clear(self);
4468 PyTypeObject *type = Py_TYPE(self);
4469 type->tp_free((PyObject *)self);
4470 Py_DECREF(type);
4471 }
4472
4473 static PyObject *
4474 PyCFuncPtr_repr(PyCFuncPtrObject *self)
4475 {
4476 #ifdef MS_WIN32
4477 if (self->index)
4478 return PyUnicode_FromFormat("<COM method offset %d: %s at %p>",
4479 self->index - 0x1000,
4480 Py_TYPE(self)->tp_name,
4481 self);
4482 #endif
4483 return PyUnicode_FromFormat("<%s object at %p>",
4484 Py_TYPE(self)->tp_name,
4485 self);
4486 }
4487
4488 static int
4489 PyCFuncPtr_bool(PyCFuncPtrObject *self)
4490 {
4491 return ((*(void **)self->b_ptr != NULL)
4492 #ifdef MS_WIN32
4493 || (self->index != 0)
4494 #endif
4495 );
4496 }
4497
4498 static PyType_Slot pycfuncptr_slots[] = {
4499 {Py_tp_dealloc, PyCFuncPtr_dealloc},
4500 {Py_tp_repr, PyCFuncPtr_repr},
4501 {Py_tp_call, PyCFuncPtr_call},
4502 {Py_tp_doc, PyDoc_STR("Function Pointer")},
4503 {Py_tp_traverse, PyCFuncPtr_traverse},
4504 {Py_tp_clear, PyCFuncPtr_clear},
4505 {Py_tp_getset, PyCFuncPtr_getsets},
4506 {Py_tp_new, PyCFuncPtr_new},
4507 {Py_bf_getbuffer, PyCData_NewGetBuffer},
4508 {Py_nb_bool, PyCFuncPtr_bool},
4509 {0, NULL},
4510 };
4511
4512 static PyType_Spec pycfuncptr_spec = {
4513 .name = "_ctypes.CFuncPtr",
4514 .basicsize = sizeof(PyCFuncPtrObject),
4515 .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
4516 Py_TPFLAGS_IMMUTABLETYPE),
4517 .slots = pycfuncptr_slots,
4518 };
4519
4520 /*****************************************************************/
4521 /*
4522 Struct_Type
4523 */
4524 /*
4525 This function is called to initialize a Structure or Union with positional
4526 arguments. It calls itself recursively for all Structure or Union base
4527 classes, then retrieves the _fields_ member to associate the argument
4528 position with the correct field name.
4529
4530 Returns -1 on error, or the index of next argument on success.
4531 */
4532 static Py_ssize_t
4533 _init_pos_args(PyObject *self, PyTypeObject *type,
4534 PyObject *args, PyObject *kwds,
4535 Py_ssize_t index)
4536 {
4537 PyObject *fields;
4538 Py_ssize_t i;
4539
4540 ctypes_state *st = get_module_state_by_def(Py_TYPE(type));
4541 StgInfo *baseinfo;
4542 if (PyStgInfo_FromType(st, (PyObject *)type->tp_base, &baseinfo) < 0) {
4543 return -1;
4544 }
4545 if (baseinfo) {
4546 index = _init_pos_args(self, type->tp_base,
4547 args, kwds,
4548 index);
4549 if (index == -1)
4550 return -1;
4551 }
4552
4553 StgInfo *info;
4554 if (PyStgInfo_FromType(st, (PyObject *)type, &info) < 0) {
4555 return -1;
4556 }
4557 assert(info);
4558
4559 PyObject *attrdict = PyType_GetDict(type);
4560 assert(attrdict);
4561
4562 fields = PyDict_GetItemWithError((PyObject *)attrdict, &_Py_ID(_fields_));
4563 Py_CLEAR(attrdict);
4564 if (fields == NULL) {
4565 if (PyErr_Occurred()) {
4566 return -1;
4567 }
4568 return index;
4569 }
4570
4571 for (i = index;
4572 i < info->length && i < PyTuple_GET_SIZE(args);
4573 ++i) {
4574 PyObject *pair = PySequence_GetItem(fields, i - index);
4575 PyObject *name, *val;
4576 int res;
4577 if (!pair)
4578 return -1;
4579 name = PySequence_GetItem(pair, 0);
4580 if (!name) {
4581 Py_DECREF(pair);
4582 return -1;
4583 }
4584 val = PyTuple_GET_ITEM(args, i);
4585 if (kwds) {
4586 res = PyDict_Contains(kwds, name);
4587 if (res != 0) {
4588 if (res > 0) {
4589 PyErr_Format(PyExc_TypeError,
4590 "duplicate values for field %R",
4591 name);
4592 }
4593 Py_DECREF(pair);
4594 Py_DECREF(name);
4595 return -1;
4596 }
4597 }
4598
4599 res = PyObject_SetAttr(self, name, val);
4600 Py_DECREF(pair);
4601 Py_DECREF(name);
4602 if (res == -1)
4603 return -1;
4604 }
4605 return info->length;
4606 }
4607
4608 static int
4609 Struct_init(PyObject *self, PyObject *args, PyObject *kwds)
4610 {
4611 /* Optimization possible: Store the attribute names _fields_[x][0]
4612 * in C accessible fields somewhere ?
4613 */
4614 if (!PyTuple_Check(args)) {
4615 PyErr_SetString(PyExc_TypeError,
4616 "args not a tuple?");
4617 return -1;
4618 }
4619 if (PyTuple_GET_SIZE(args)) {
4620 Py_ssize_t res = _init_pos_args(self, Py_TYPE(self),
4621 args, kwds, 0);
4622 if (res == -1)
4623 return -1;
4624 if (res < PyTuple_GET_SIZE(args)) {
4625 PyErr_SetString(PyExc_TypeError,
4626 "too many initializers");
4627 return -1;
4628 }
4629 }
4630
4631 if (kwds) {
4632 PyObject *key, *value;
4633 Py_ssize_t pos = 0;
4634 while(PyDict_Next(kwds, &pos, &key, &value)) {
4635 if (-1 == PyObject_SetAttr(self, key, value))
4636 return -1;
4637 }
4638 }
4639 return 0;
4640 }
4641
4642 static PyType_Slot pycstruct_slots[] = {
4643 {Py_tp_doc, PyDoc_STR("Structure base class")},
4644 {Py_tp_init, Struct_init},
4645 {Py_tp_new, GenericPyCData_new},
4646 {Py_bf_getbuffer, PyCData_NewGetBuffer},
4647 {0, NULL},
4648 };
4649
4650 static PyType_Spec pycstruct_spec = {
4651 .name = "_ctypes.Structure",
4652 .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
4653 Py_TPFLAGS_IMMUTABLETYPE),
4654 .slots = pycstruct_slots,
4655 };
4656
4657 static PyType_Slot pycunion_slots[] = {
4658 {Py_tp_doc, PyDoc_STR("Union base class")},
4659 {Py_tp_init, Struct_init},
4660 {Py_tp_new, GenericPyCData_new},
4661 {Py_bf_getbuffer, PyCData_NewGetBuffer},
4662 {0, NULL},
4663 };
4664
4665 static PyType_Spec pycunion_spec = {
4666 .name = "_ctypes.Union",
4667 .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
4668 Py_TPFLAGS_IMMUTABLETYPE),
4669 .slots = pycunion_slots,
4670 };
4671
4672
4673 /******************************************************************/
4674 /*
4675 PyCArray_Type
4676 */
4677 static int
4678 Array_init(CDataObject *self, PyObject *args, PyObject *kw)
4679 {
4680 Py_ssize_t i;
4681 Py_ssize_t n;
4682
4683 if (!PyTuple_Check(args)) {
4684 PyErr_SetString(PyExc_TypeError,
4685 "args not a tuple?");
4686 return -1;
4687 }
4688 n = PyTuple_GET_SIZE(args);
4689 for (i = 0; i < n; ++i) {
4690 PyObject *v;
4691 v = PyTuple_GET_ITEM(args, i);
4692 if (-1 == PySequence_SetItem((PyObject *)self, i, v))
4693 return -1;
4694 }
4695 return 0;
4696 }
4697
4698 static PyObject *
4699 Array_item(PyObject *myself, Py_ssize_t index)
4700 {
4701 CDataObject *self = (CDataObject *)myself;
4702 Py_ssize_t offset, size;
4703
4704 if (index < 0 || index >= self->b_length) {
4705 PyErr_SetString(PyExc_IndexError,
4706 "invalid index");
4707 return NULL;
4708 }
4709
4710 ctypes_state *st = get_module_state_by_def(Py_TYPE(Py_TYPE(self)));
4711 StgInfo *stginfo;
4712 if (PyStgInfo_FromObject(st, (PyObject *)self, &stginfo) < 0) {
4713 return NULL;
4714 }
4715
4716 /* Would it be clearer if we got the item size from
4717 stginfo->proto's stginfo?
4718 */
4719 size = stginfo->size / stginfo->length;
4720 offset = index * size;
4721
4722 return PyCData_get(st, stginfo->proto, stginfo->getfunc, (PyObject *)self,
4723 index, size, self->b_ptr + offset);
4724 }
4725
4726 static PyObject *
4727 Array_subscript(PyObject *myself, PyObject *item)
4728 {
4729 CDataObject *self = (CDataObject *)myself;
4730
4731 if (PyIndex_Check(item)) {
4732 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
4733
4734 if (i == -1 && PyErr_Occurred())
4735 return NULL;
4736 if (i < 0)
4737 i += self->b_length;
4738 return Array_item(myself, i);
4739 }
4740 else if (PySlice_Check(item)) {
4741 PyObject *proto;
4742 PyObject *np;
4743 Py_ssize_t start, stop, step, slicelen, i;
4744 size_t cur;
4745
4746 if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
4747 return NULL;
4748 }
4749 slicelen = PySlice_AdjustIndices(self->b_length, &start, &stop, step);
4750
4751 ctypes_state *st = get_module_state_by_def(Py_TYPE(Py_TYPE(self)));
4752 StgInfo *stginfo;
4753 if (PyStgInfo_FromObject(st, (PyObject *)self, &stginfo) < 0) {
4754 return NULL;
4755 }
4756 assert(stginfo); /* Cannot be NULL for array object instances */
4757 proto = stginfo->proto;
4758 StgInfo *iteminfo;
4759 if (PyStgInfo_FromType(st, proto, &iteminfo) < 0) {
4760 return NULL;
4761 }
4762 assert(iteminfo); /* proto is the item type of the array, a
4763 ctypes type, so this cannot be NULL */
4764
4765 if (iteminfo->getfunc == _ctypes_get_fielddesc("c")->getfunc) {
4766 char *ptr = (char *)self->b_ptr;
4767 char *dest;
4768
4769 if (slicelen <= 0)
4770 return PyBytes_FromStringAndSize("", 0);
4771 if (step == 1) {
4772 return PyBytes_FromStringAndSize(ptr + start,
4773 slicelen);
4774 }
4775 dest = (char *)PyMem_Malloc(slicelen);
4776
4777 if (dest == NULL)
4778 return PyErr_NoMemory();
4779
4780 for (cur = start, i = 0; i < slicelen;
4781 cur += step, i++) {
4782 dest[i] = ptr[cur];
4783 }
4784
4785 np = PyBytes_FromStringAndSize(dest, slicelen);
4786 PyMem_Free(dest);
4787 return np;
4788 }
4789 if (iteminfo->getfunc == _ctypes_get_fielddesc("u")->getfunc) {
4790 wchar_t *ptr = (wchar_t *)self->b_ptr;
4791 wchar_t *dest;
4792
4793 if (slicelen <= 0)
4794 return PyUnicode_New(0, 0);
4795 if (step == 1) {
4796 return PyUnicode_FromWideChar(ptr + start,
4797 slicelen);
4798 }
4799
4800 dest = PyMem_New(wchar_t, slicelen);
4801 if (dest == NULL) {
4802 PyErr_NoMemory();
4803 return NULL;
4804 }
4805
4806 for (cur = start, i = 0; i < slicelen;
4807 cur += step, i++) {
4808 dest[i] = ptr[cur];
4809 }
4810
4811 np = PyUnicode_FromWideChar(dest, slicelen);
4812 PyMem_Free(dest);
4813 return np;
4814 }
4815
4816 np = PyList_New(slicelen);
4817 if (np == NULL)
4818 return NULL;
4819
4820 for (cur = start, i = 0; i < slicelen;
4821 cur += step, i++) {
4822 PyObject *v = Array_item(myself, cur);
4823 if (v == NULL) {
4824 Py_DECREF(np);
4825 return NULL;
4826 }
4827 PyList_SET_ITEM(np, i, v);
4828 }
4829 return np;
4830 }
4831 else {
4832 PyErr_SetString(PyExc_TypeError,
4833 "indices must be integers");
4834 return NULL;
4835 }
4836
4837 }
4838
4839 static int
4840 Array_ass_item(PyObject *myself, Py_ssize_t index, PyObject *value)
4841 {
4842 CDataObject *self = (CDataObject *)myself;
4843 Py_ssize_t size, offset;
4844 char *ptr;
4845
4846 if (value == NULL) {
4847 PyErr_SetString(PyExc_TypeError,
4848 "Array does not support item deletion");
4849 return -1;
4850 }
4851
4852 ctypes_state *st = get_module_state_by_def(Py_TYPE(Py_TYPE(self)));
4853 StgInfo *stginfo;
4854 if (PyStgInfo_FromObject(st, (PyObject *)self, &stginfo) < 0) {
4855 return -1;
4856 }
4857 assert(stginfo); /* Cannot be NULL for array object instances */
4858
4859 if (index < 0 || index >= stginfo->length) {
4860 PyErr_SetString(PyExc_IndexError,
4861 "invalid index");
4862 return -1;
4863 }
4864 size = stginfo->size / stginfo->length;
4865 offset = index * size;
4866 ptr = self->b_ptr + offset;
4867
4868 return PyCData_set(st, (PyObject *)self, stginfo->proto, stginfo->setfunc, value,
4869 index, size, ptr);
4870 }
4871
4872 static int
4873 Array_ass_subscript(PyObject *myself, PyObject *item, PyObject *value)
4874 {
4875 CDataObject *self = (CDataObject *)myself;
4876
4877 if (value == NULL) {
4878 PyErr_SetString(PyExc_TypeError,
4879 "Array does not support item deletion");
4880 return -1;
4881 }
4882
4883 if (PyIndex_Check(item)) {
4884 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
4885
4886 if (i == -1 && PyErr_Occurred())
4887 return -1;
4888 if (i < 0)
4889 i += self->b_length;
4890 return Array_ass_item(myself, i, value);
4891 }
4892 else if (PySlice_Check(item)) {
4893 Py_ssize_t start, stop, step, slicelen, otherlen, i;
4894 size_t cur;
4895
4896 if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
4897 return -1;
4898 }
4899 slicelen = PySlice_AdjustIndices(self->b_length, &start, &stop, step);
4900 if ((step < 0 && start < stop) ||
4901 (step > 0 && start > stop))
4902 stop = start;
4903
4904 otherlen = PySequence_Length(value);
4905 if (otherlen != slicelen) {
4906 PyErr_SetString(PyExc_ValueError,
4907 "Can only assign sequence of same size");
4908 return -1;
4909 }
4910 for (cur = start, i = 0; i < otherlen; cur += step, i++) {
4911 PyObject *item = PySequence_GetItem(value, i);
4912 int result;
4913 if (item == NULL)
4914 return -1;
4915 result = Array_ass_item(myself, cur, item);
4916 Py_DECREF(item);
4917 if (result == -1)
4918 return -1;
4919 }
4920 return 0;
4921 }
4922 else {
4923 PyErr_SetString(PyExc_TypeError,
4924 "indices must be integer");
4925 return -1;
4926 }
4927 }
4928
4929 static Py_ssize_t
4930 Array_length(PyObject *myself)
4931 {
4932 CDataObject *self = (CDataObject *)myself;
4933 return self->b_length;
4934 }
4935
4936 static PyMethodDef Array_methods[] = {
4937 {"__class_getitem__", Py_GenericAlias,
4938 METH_O|METH_CLASS, PyDoc_STR("See PEP 585")},
4939 { NULL, NULL }
4940 };
4941
4942 PyDoc_STRVAR(array_doc,
4943 "Abstract base class for arrays.\n"
4944 "\n"
4945 "The recommended way to create concrete array types is by multiplying any\n"
4946 "ctypes data type with a non-negative integer. Alternatively, you can subclass\n"
4947 "this type and define _length_ and _type_ class variables. Array elements can\n"
4948 "be read and written using standard subscript and slice accesses for slice\n"
4949 "reads, the resulting object is not itself an Array."
4950 );
4951
4952 static PyType_Slot pycarray_slots[] = {
4953 {Py_tp_doc, (char*)array_doc},
4954 {Py_tp_methods, Array_methods},
4955 {Py_tp_init, Array_init},
4956 {Py_tp_new, GenericPyCData_new},
4957 {Py_bf_getbuffer, PyCData_NewGetBuffer},
4958 {Py_sq_length, Array_length},
4959 {Py_sq_item, Array_item},
4960 {Py_sq_ass_item, Array_ass_item},
4961 {Py_mp_length, Array_length},
4962 {Py_mp_subscript, Array_subscript},
4963 {Py_mp_ass_subscript, Array_ass_subscript},
4964 {0, NULL},
4965 };
4966
4967 static PyType_Spec pycarray_spec = {
4968 .name = "_ctypes.Array",
4969 .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
4970 Py_TPFLAGS_IMMUTABLETYPE),
4971 .slots = pycarray_slots,
4972 };
4973
4974 PyObject *
4975 PyCArrayType_from_ctype(ctypes_state *st, PyObject *itemtype, Py_ssize_t length)
4976 {
4977 PyObject *key;
4978 char name[256];
4979 PyObject *len;
4980
4981 if (st->array_cache == NULL) {
4982 st->array_cache = PyDict_New();
4983 if (st->array_cache == NULL) {
4984 return NULL;
4985 }
4986 }
4987 len = PyLong_FromSsize_t(length);
4988 if (len == NULL)
4989 return NULL;
4990 key = PyTuple_Pack(2, itemtype, len);
4991 Py_DECREF(len);
4992 if (!key)
4993 return NULL;
4994
4995 PyObject *result;
4996 if (_PyDict_GetItemProxy(st->array_cache, key, &result) != 0) {
4997 // found or error
4998 Py_DECREF(key);
4999 return result;
5000 }
5001 // not found
5002 if (!PyType_Check(itemtype)) {
5003 PyErr_SetString(PyExc_TypeError,
5004 "Expected a type object");
5005 Py_DECREF(key);
5006 return NULL;
5007 }
5008 #ifdef MS_WIN64
5009 sprintf(name, "%.200s_Array_%Id",
5010 ((PyTypeObject *)itemtype)->tp_name, length);
5011 #else
5012 sprintf(name, "%.200s_Array_%ld",
5013 ((PyTypeObject *)itemtype)->tp_name, (long)length);
5014 #endif
5015 result = PyObject_CallFunction((PyObject *)st->PyCArrayType_Type,
5016 "s(O){s:n,s:O}",
5017 name,
5018 st->PyCArray_Type,
5019 "_length_",
5020 length,
5021 "_type_",
5022 itemtype
5023 );
5024 if (result == NULL) {
5025 Py_DECREF(key);
5026 return NULL;
5027 }
5028 if (PyDict_SetItemProxy(st, st->array_cache, key, result) < 0) {
5029 Py_DECREF(key);
5030 Py_DECREF(result);
5031 return NULL;
5032 }
5033 Py_DECREF(key);
5034 return result;
5035 }
5036
5037
5038 /******************************************************************/
5039 /*
5040 Simple_Type
5041 */
5042
5043 /*[clinic input]
5044 class _ctypes.Simple "PyObject *" "clinic_state()->Simple_Type"
5045 [clinic start generated code]*/
5046 /*[clinic end generated code: output=da39a3ee5e6b4b0d input=016c476c7aa8b8a8]*/
5047
5048
5049 static int
5050 Simple_set_value(CDataObject *self, PyObject *value, void *Py_UNUSED(ignored))
5051 {
5052 PyObject *result;
5053
5054 if (value == NULL) {
5055 PyErr_SetString(PyExc_TypeError,
5056 "can't delete attribute");
5057 return -1;
5058 }
5059
5060 ctypes_state *st = get_module_state_by_def(Py_TYPE(Py_TYPE(self)));
5061 StgInfo *info;
5062 if (PyStgInfo_FromObject(st, (PyObject *)self, &info) < 0) {
5063 return -1;
5064 }
5065 assert(info); /* Cannot be NULL for CDataObject instances */
5066 assert(info->setfunc);
5067
5068 result = info->setfunc(self->b_ptr, value, info->size);
5069 if (!result)
5070 return -1;
5071
5072 /* consumes the refcount the setfunc returns */
5073 return KeepRef(self, 0, result);
5074 }
5075
5076 static int
5077 Simple_init(CDataObject *self, PyObject *args, PyObject *kw)
5078 {
5079 PyObject *value = NULL;
5080 if (!PyArg_UnpackTuple(args, "__init__", 0, 1, &value))
5081 return -1;
5082 if (value)
5083 return Simple_set_value(self, value, NULL);
5084 return 0;
5085 }
5086
5087 static PyObject *
5088 Simple_get_value(CDataObject *self, void *Py_UNUSED(ignored))
5089 {
5090 ctypes_state *st = get_module_state_by_def(Py_TYPE(Py_TYPE(self)));
5091 StgInfo *info;
5092 if (PyStgInfo_FromObject(st, (PyObject *)self, &info) < 0) {
5093 return NULL;
5094 }
5095 assert(info); /* Cannot be NULL for CDataObject instances */
5096 assert(info->getfunc);
5097 return info->getfunc(self->b_ptr, self->b_size);
5098 }
5099
5100 static PyGetSetDef Simple_getsets[] = {
5101 { "value", (getter)Simple_get_value, (setter)Simple_set_value,
5102 "current value", NULL },
5103 { NULL, NULL }
5104 };
5105
5106 /*[clinic input]
5107 _ctypes.Simple.__ctypes_from_outparam__ as Simple_from_outparm
5108
5109 self: self
5110 cls: defining_class
5111 /
5112 [clinic start generated code]*/
5113
5114 static PyObject *
5115 Simple_from_outparm_impl(PyObject *self, PyTypeObject *cls)
5116 /*[clinic end generated code: output=6c61d90da8aa9b4f input=0f362803fb4629d5]*/
5117 {
5118 ctypes_state *st = get_module_state_by_class(cls);
5119 if (_ctypes_simple_instance(st, (PyObject *)Py_TYPE(self))) {
5120 return Py_NewRef(self);
5121 }
5122 /* call stginfo->getfunc */
5123 return Simple_get_value((CDataObject *)self, NULL);
5124 }
5125
5126 static PyMethodDef Simple_methods[] = {
5127 SIMPLE_FROM_OUTPARM_METHODDEF
5128 { NULL, NULL },
5129 };
5130
5131 static int Simple_bool(CDataObject *self)
5132 {
5133 return memcmp(self->b_ptr, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", self->b_size);
5134 }
5135
5136 /* "%s(%s)" % (self.__class__.__name__, self.value) */
5137 static PyObject *
5138 Simple_repr(CDataObject *self)
5139 {
5140 PyObject *val, *result;
5141 ctypes_state *st = get_module_state_by_def(Py_TYPE(Py_TYPE(self)));
5142
5143 if (Py_TYPE(self)->tp_base != st->Simple_Type) {
5144 return PyUnicode_FromFormat("<%s object at %p>",
5145 Py_TYPE(self)->tp_name, self);
5146 }
5147
5148 val = Simple_get_value(self, NULL);
5149 if (val == NULL)
5150 return NULL;
5151
5152 result = PyUnicode_FromFormat("%s(%R)",
5153 Py_TYPE(self)->tp_name, val);
5154 Py_DECREF(val);
5155 return result;
5156 }
5157
5158 static PyType_Slot pycsimple_slots[] = {
5159 {Py_tp_repr, &Simple_repr},
5160 {Py_tp_doc, PyDoc_STR("XXX to be provided")},
5161 {Py_tp_methods, Simple_methods},
5162 {Py_tp_getset, Simple_getsets},
5163 {Py_tp_init, Simple_init},
5164 {Py_tp_new, GenericPyCData_new},
5165 {Py_bf_getbuffer, PyCData_NewGetBuffer},
5166 {Py_nb_bool, Simple_bool},
5167 {0, NULL},
5168 };
5169
5170 static PyType_Spec pycsimple_spec = {
5171 .name = "_ctypes._SimpleCData",
5172 .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
5173 Py_TPFLAGS_IMMUTABLETYPE),
5174 .slots = pycsimple_slots,
5175 };
5176
5177
5178 /******************************************************************/
5179 /*
5180 PyCPointer_Type
5181 */
5182 static PyObject *
5183 Pointer_item(PyObject *myself, Py_ssize_t index)
5184 {
5185 CDataObject *self = (CDataObject *)myself;
5186 Py_ssize_t size;
5187 Py_ssize_t offset;
5188 PyObject *proto;
5189
5190 if (*(void **)self->b_ptr == NULL) {
5191 PyErr_SetString(PyExc_ValueError,
5192 "NULL pointer access");
5193 return NULL;
5194 }
5195
5196 ctypes_state *st = get_module_state_by_def(Py_TYPE(Py_TYPE(myself)));
5197 StgInfo *stginfo;
5198 if (PyStgInfo_FromObject(st, (PyObject *)self, &stginfo) < 0) {
5199 return NULL;
5200 }
5201 assert(stginfo); /* Cannot be NULL for pointer object instances */
5202
5203 proto = stginfo->proto;
5204 assert(proto);
5205
5206 StgInfo *iteminfo;
5207 if (PyStgInfo_FromType(st, proto, &iteminfo) < 0) {
5208 return NULL;
5209 }
5210 assert(iteminfo); /* proto is the item type of the pointer, a ctypes
5211 type, so this cannot be NULL */
5212
5213 size = iteminfo->size;
5214 offset = index * iteminfo->size;
5215
5216 return PyCData_get(st, proto, stginfo->getfunc, (PyObject *)self,
5217 index, size, (*(char **)self->b_ptr) + offset);
5218 }
5219
5220 static int
5221 Pointer_ass_item(PyObject *myself, Py_ssize_t index, PyObject *value)
5222 {
5223 CDataObject *self = (CDataObject *)myself;
5224 Py_ssize_t size;
5225 Py_ssize_t offset;
5226 PyObject *proto;
5227
5228 if (value == NULL) {
5229 PyErr_SetString(PyExc_TypeError,
5230 "Pointer does not support item deletion");
5231 return -1;
5232 }
5233
5234 if (*(void **)self->b_ptr == NULL) {
5235 PyErr_SetString(PyExc_ValueError,
5236 "NULL pointer access");
5237 return -1;
5238 }
5239
5240 ctypes_state *st = get_module_state_by_def(Py_TYPE(Py_TYPE(myself)));
5241 StgInfo *stginfo;
5242 if (PyStgInfo_FromObject(st, (PyObject *)self, &stginfo) < 0) {
5243 return -1;
5244 }
5245 assert(stginfo); /* Cannot be NULL for pointer instances */
5246
5247 proto = stginfo->proto;
5248 assert(proto);
5249
5250 StgInfo *iteminfo;
5251 if (PyStgInfo_FromType(st, proto, &iteminfo) < 0) {
5252 return -1;
5253 }
5254 assert(iteminfo); /* Cannot be NULL because the itemtype of a pointer
5255 is always a ctypes type */
5256
5257 size = iteminfo->size;
5258 offset = index * iteminfo->size;
5259
5260 return PyCData_set(st, (PyObject *)self, proto, stginfo->setfunc, value,
5261 index, size, (*(char **)self->b_ptr) + offset);
5262 }
5263
5264 static PyObject *
5265 Pointer_get_contents(CDataObject *self, void *closure)
5266 {
5267 if (*(void **)self->b_ptr == NULL) {
5268 PyErr_SetString(PyExc_ValueError,
5269 "NULL pointer access");
5270 return NULL;
5271 }
5272
5273 ctypes_state *st = get_module_state_by_def(Py_TYPE(Py_TYPE(self)));
5274 StgInfo *stginfo;
5275 if (PyStgInfo_FromObject(st, (PyObject *)self, &stginfo) < 0) {
5276 return NULL;
5277 }
5278 assert(stginfo); /* Cannot be NULL for pointer instances */
5279
5280 return PyCData_FromBaseObj(st, stginfo->proto,
5281 (PyObject *)self, 0,
5282 *(void **)self->b_ptr);
5283 }
5284
5285 static int
5286 Pointer_set_contents(CDataObject *self, PyObject *value, void *closure)
5287 {
5288 CDataObject *dst;
5289 PyObject *keep;
5290
5291 if (value == NULL) {
5292 PyErr_SetString(PyExc_TypeError,
5293 "Pointer does not support item deletion");
5294 return -1;
5295 }
5296 ctypes_state *st = get_module_state_by_def(Py_TYPE(Py_TYPE(self)));
5297 StgInfo *stginfo;
5298 if (PyStgInfo_FromObject(st, (PyObject *)self, &stginfo) < 0) {
5299 return -1;
5300 }
5301 assert(stginfo); /* Cannot be NULL for pointer instances */
5302 assert(stginfo->proto);
5303 if (!CDataObject_Check(st, value)) {
5304 int res = PyObject_IsInstance(value, stginfo->proto);
5305 if (res == -1)
5306 return -1;
5307 if (!res) {
5308 PyErr_Format(PyExc_TypeError,
5309 "expected %s instead of %s",
5310 ((PyTypeObject *)(stginfo->proto))->tp_name,
5311 Py_TYPE(value)->tp_name);
5312 return -1;
5313 }
5314 }
5315
5316 dst = (CDataObject *)value;
5317 *(void **)self->b_ptr = dst->b_ptr;
5318
5319 /*
5320 A Pointer instance must keep the value it points to alive. So, a
5321 pointer instance has b_length set to 2 instead of 1, and we set
5322 'value' itself as the second item of the b_objects list, additionally.
5323 */
5324 Py_INCREF(value);
5325 if (-1 == KeepRef(self, 1, value))
5326 return -1;
5327
5328 keep = GetKeepedObjects(dst);
5329 if (keep == NULL)
5330 return -1;
5331
5332 Py_INCREF(keep);
5333 return KeepRef(self, 0, keep);
5334 }
5335
5336 static PyGetSetDef Pointer_getsets[] = {
5337 { "contents", (getter)Pointer_get_contents,
5338 (setter)Pointer_set_contents,
5339 "the object this pointer points to (read-write)", NULL },
5340 { NULL, NULL }
5341 };
5342
5343 static int
5344 Pointer_init(CDataObject *self, PyObject *args, PyObject *kw)
5345 {
5346 PyObject *value = NULL;
5347
5348 if (!PyArg_UnpackTuple(args, "POINTER", 0, 1, &value))
5349 return -1;
5350 if (value == NULL)
5351 return 0;
5352 return Pointer_set_contents(self, value, NULL);
5353 }
5354
5355 static PyObject *
5356 Pointer_new(PyTypeObject *type, PyObject *args, PyObject *kw)
5357 {
5358 ctypes_state *st = get_module_state_by_def(Py_TYPE(type));
5359 StgInfo *info;
5360 if (PyStgInfo_FromType(st, (PyObject *)type, &info) < 0) {
5361 return NULL;
5362 }
5363 if (!info || !info->proto) {
5364 PyErr_SetString(PyExc_TypeError,
5365 "Cannot create instance: has no _type_");
5366 return NULL;
5367 }
5368 return generic_pycdata_new(st, type, args, kw);
5369 }
5370
5371 static PyObject *
5372 Pointer_subscript(PyObject *myself, PyObject *item)
5373 {
5374 CDataObject *self = (CDataObject *)myself;
5375 if (PyIndex_Check(item)) {
5376 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
5377 if (i == -1 && PyErr_Occurred())
5378 return NULL;
5379 return Pointer_item(myself, i);
5380 }
5381 else if (PySlice_Check(item)) {
5382 PySliceObject *slice = (PySliceObject *)item;
5383 Py_ssize_t start, stop, step;
5384 PyObject *np;
5385 PyObject *proto;
5386 Py_ssize_t i, len;
5387 size_t cur;
5388
5389 /* Since pointers have no length, and we want to apply
5390 different semantics to negative indices than normal
5391 slicing, we have to dissect the slice object ourselves.*/
5392 if (slice->step == Py_None) {
5393 step = 1;
5394 }
5395 else {
5396 step = PyNumber_AsSsize_t(slice->step,
5397 PyExc_ValueError);
5398 if (step == -1 && PyErr_Occurred())
5399 return NULL;
5400 if (step == 0) {
5401 PyErr_SetString(PyExc_ValueError,
5402 "slice step cannot be zero");
5403 return NULL;
5404 }
5405 }
5406 if (slice->start == Py_None) {
5407 if (step < 0) {
5408 PyErr_SetString(PyExc_ValueError,
5409 "slice start is required "
5410 "for step < 0");
5411 return NULL;
5412 }
5413 start = 0;
5414 }
5415 else {
5416 start = PyNumber_AsSsize_t(slice->start,
5417 PyExc_ValueError);
5418 if (start == -1 && PyErr_Occurred())
5419 return NULL;
5420 }
5421 if (slice->stop == Py_None) {
5422 PyErr_SetString(PyExc_ValueError,
5423 "slice stop is required");
5424 return NULL;
5425 }
5426 stop = PyNumber_AsSsize_t(slice->stop,
5427 PyExc_ValueError);
5428 if (stop == -1 && PyErr_Occurred())
5429 return NULL;
5430 if ((step > 0 && start > stop) ||
5431 (step < 0 && start < stop))
5432 len = 0;
5433 else if (step > 0)
5434 len = (stop - start - 1) / step + 1;
5435 else
5436 len = (stop - start + 1) / step + 1;
5437
5438 ctypes_state *st = get_module_state_by_def(Py_TYPE(Py_TYPE(myself)));
5439 StgInfo *stginfo;
5440 if (PyStgInfo_FromObject(st, (PyObject *)self, &stginfo) < 0) {
5441 return NULL;
5442 }
5443 assert(stginfo); /* Cannot be NULL for pointer instances */
5444 proto = stginfo->proto;
5445 assert(proto);
5446 StgInfo *iteminfo;
5447 if (PyStgInfo_FromType(st, proto, &iteminfo) < 0) {
5448 return NULL;
5449 }
5450 assert(iteminfo);
5451 if (iteminfo->getfunc == _ctypes_get_fielddesc("c")->getfunc) {
5452 char *ptr = *(char **)self->b_ptr;
5453 char *dest;
5454
5455 if (len <= 0)
5456 return PyBytes_FromStringAndSize("", 0);
5457 if (step == 1) {
5458 return PyBytes_FromStringAndSize(ptr + start,
5459 len);
5460 }
5461 dest = (char *)PyMem_Malloc(len);
5462 if (dest == NULL)
5463 return PyErr_NoMemory();
5464 for (cur = start, i = 0; i < len; cur += step, i++) {
5465 dest[i] = ptr[cur];
5466 }
5467 np = PyBytes_FromStringAndSize(dest, len);
5468 PyMem_Free(dest);
5469 return np;
5470 }
5471 if (iteminfo->getfunc == _ctypes_get_fielddesc("u")->getfunc) {
5472 wchar_t *ptr = *(wchar_t **)self->b_ptr;
5473 wchar_t *dest;
5474
5475 if (len <= 0)
5476 return PyUnicode_New(0, 0);
5477 if (step == 1) {
5478 return PyUnicode_FromWideChar(ptr + start,
5479 len);
5480 }
5481 dest = PyMem_New(wchar_t, len);
5482 if (dest == NULL)
5483 return PyErr_NoMemory();
5484 for (cur = start, i = 0; i < len; cur += step, i++) {
5485 dest[i] = ptr[cur];
5486 }
5487 np = PyUnicode_FromWideChar(dest, len);
5488 PyMem_Free(dest);
5489 return np;
5490 }
5491
5492 np = PyList_New(len);
5493 if (np == NULL)
5494 return NULL;
5495
5496 for (cur = start, i = 0; i < len; cur += step, i++) {
5497 PyObject *v = Pointer_item(myself, cur);
5498 PyList_SET_ITEM(np, i, v);
5499 }
5500 return np;
5501 }
5502 else {
5503 PyErr_SetString(PyExc_TypeError,
5504 "Pointer indices must be integer");
5505 return NULL;
5506 }
5507 }
5508
5509 static int
5510 Pointer_bool(CDataObject *self)
5511 {
5512 return (*(void **)self->b_ptr != NULL);
5513 }
5514
5515 static PyType_Slot pycpointer_slots[] = {
5516 {Py_tp_doc, PyDoc_STR("XXX to be provided")},
5517 {Py_tp_getset, Pointer_getsets},
5518 {Py_tp_init, Pointer_init},
5519 {Py_tp_new, Pointer_new},
5520 {Py_bf_getbuffer, PyCData_NewGetBuffer},
5521 {Py_nb_bool, Pointer_bool},
5522 {Py_mp_subscript, Pointer_subscript},
5523 {Py_sq_item, Pointer_item},
5524 {Py_sq_ass_item, Pointer_ass_item},
5525 {0, NULL},
5526 };
5527
5528 static PyType_Spec pycpointer_spec = {
5529 .name = "_ctypes._Pointer",
5530 .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
5531 Py_TPFLAGS_IMMUTABLETYPE),
5532 .slots = pycpointer_slots,
5533 };
5534
5535 /******************************************************************/
5536 /*
5537 * Module initialization.
5538 */
5539
5540 PyDoc_STRVAR(_ctypes__doc__,
5541 "Create and manipulate C compatible data types in Python.");
5542
5543 #ifdef MS_WIN32
5544
5545 PyDoc_STRVAR(comerror_doc, "Raised when a COM method call failed.");
5546
5547 int
5548 comerror_init(PyObject *self, PyObject *args, PyObject *kwds)
5549 {
5550 PyObject *hresult, *text, *details;
5551 PyObject *a;
5552 int status;
5553
5554 if (!_PyArg_NoKeywords(Py_TYPE(self)->tp_name, kwds))
5555 return -1;
5556
5557 if (!PyArg_ParseTuple(args, "OOO:COMError", &hresult, &text, &details))
5558 return -1;
5559
5560 a = PySequence_GetSlice(args, 1, PyTuple_GET_SIZE(args));
5561 if (!a)
5562 return -1;
5563 status = PyObject_SetAttrString(self, "args", a);
5564 Py_DECREF(a);
5565 if (status < 0)
5566 return -1;
5567
5568 if (PyObject_SetAttrString(self, "hresult", hresult) < 0)
5569 return -1;
5570
5571 if (PyObject_SetAttrString(self, "text", text) < 0)
5572 return -1;
5573
5574 if (PyObject_SetAttrString(self, "details", details) < 0)
5575 return -1;
5576
5577 Py_INCREF(args);
5578 Py_SETREF(((PyBaseExceptionObject *)self)->args, args);
5579
5580 return 0;
5581 }
5582
5583 static int
5584 comerror_clear(PyObject *self)
5585 {
5586 return ((PyTypeObject *)PyExc_BaseException)->tp_clear(self);
5587 }
5588
5589 static int
5590 comerror_traverse(PyObject *self, visitproc visit, void *arg)
5591 {
5592 Py_VISIT(Py_TYPE(self));
5593 return ((PyTypeObject *)PyExc_BaseException)->tp_traverse(self, visit, arg);
5594 }
5595
5596 static void
5597 comerror_dealloc(PyObject *self)
5598 {
5599 PyTypeObject *tp = Py_TYPE(self);
5600 PyObject_GC_UnTrack(self);
5601 (void)comerror_clear(self);
5602 tp->tp_free(self);
5603 Py_DECREF(tp);
5604 }
5605
5606 static PyType_Slot comerror_slots[] = {
5607 {Py_tp_doc, (void *)PyDoc_STR(comerror_doc)},
5608 {Py_tp_init, comerror_init},
5609 {Py_tp_traverse, comerror_traverse},
5610 {Py_tp_dealloc, comerror_dealloc},
5611 {Py_tp_clear, comerror_clear},
5612 {0, NULL},
5613 };
5614
5615 static PyType_Spec comerror_spec = {
5616 .name = "_ctypes.COMError",
5617 .basicsize = sizeof(PyBaseExceptionObject),
5618 .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
5619 Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_IMMUTABLETYPE),
5620 .slots = comerror_slots,
5621 };
5622
5623 #endif // MS_WIN32
5624
5625 static PyObject *
5626 string_at(const char *ptr, int size)
5627 {
5628 if (PySys_Audit("ctypes.string_at", "ni", (Py_ssize_t)ptr, size) < 0) {
5629 return NULL;
5630 }
5631 if (size == -1)
5632 return PyBytes_FromStringAndSize(ptr, strlen(ptr));
5633 return PyBytes_FromStringAndSize(ptr, size);
5634 }
5635
5636 static int
5637 cast_check_pointertype(ctypes_state *st, PyObject *arg)
5638 {
5639 if (PyCPointerTypeObject_Check(st, arg)) {
5640 return 1;
5641 }
5642 if (PyCFuncPtrTypeObject_Check(st, arg)) {
5643 return 1;
5644 }
5645 StgInfo *info;
5646 if (PyStgInfo_FromType(st, arg, &info) < 0) {
5647 return 0;
5648 }
5649 if (info != NULL && info->proto != NULL) {
5650 if (PyUnicode_Check(info->proto)
5651 && (strchr("sPzUZXO", PyUnicode_AsUTF8(info->proto)[0]))) {
5652 /* simple pointer types, c_void_p, c_wchar_p, BSTR, ... */
5653 return 1;
5654 }
5655 }
5656 PyErr_Format(PyExc_TypeError,
5657 "cast() argument 2 must be a pointer type, not %s",
5658 PyType_Check(arg)
5659 ? ((PyTypeObject *)arg)->tp_name
5660 : Py_TYPE(arg)->tp_name);
5661 return 0;
5662 }
5663
5664 static PyObject *
5665 cast(void *ptr, PyObject *src, PyObject *ctype)
5666 {
5667 PyObject *mod = PyType_GetModuleByDef(Py_TYPE(ctype), &_ctypesmodule);
5668 if (!mod) {
5669 PyErr_SetString(PyExc_TypeError,
5670 "cast() argument 2 must be a pointer type");
5671 return NULL;
5672 }
5673 ctypes_state *st = get_module_state(mod);
5674
5675 CDataObject *result;
5676 if (cast_check_pointertype(st, ctype) == 0) {
5677 return NULL;
5678 }
5679 result = (CDataObject *)_PyObject_CallNoArgs(ctype);
5680 if (result == NULL)
5681 return NULL;
5682
5683 /*
5684 The casted objects '_objects' member:
5685
5686 It must certainly contain the source objects one.
5687 It must contain the source object itself.
5688 */
5689 if (CDataObject_Check(st, src)) {
5690 CDataObject *obj = (CDataObject *)src;
5691 CDataObject *container;
5692
5693 /* PyCData_GetContainer will initialize src.b_objects, we need
5694 this so it can be shared */
5695 container = PyCData_GetContainer(obj);
5696 if (container == NULL)
5697 goto failed;
5698
5699 /* But we need a dictionary! */
5700 if (obj->b_objects == Py_None) {
5701 Py_DECREF(Py_None);
5702 obj->b_objects = PyDict_New();
5703 if (obj->b_objects == NULL)
5704 goto failed;
5705 }
5706 result->b_objects = Py_XNewRef(obj->b_objects);
5707 if (result->b_objects && PyDict_CheckExact(result->b_objects)) {
5708 PyObject *index;
5709 int rc;
5710 index = PyLong_FromVoidPtr((void *)src);
5711 if (index == NULL)
5712 goto failed;
5713 rc = PyDict_SetItem(result->b_objects, index, src);
5714 Py_DECREF(index);
5715 if (rc == -1)
5716 goto failed;
5717 }
5718 }
5719 /* Should we assert that result is a pointer type? */
5720 memcpy(result->b_ptr, &ptr, sizeof(void *));
5721 return (PyObject *)result;
5722
5723 failed:
5724 Py_DECREF(result);
5725 return NULL;
5726 }
5727
5728
5729 static PyObject *
5730 wstring_at(const wchar_t *ptr, int size)
5731 {
5732 Py_ssize_t ssize = size;
5733 if (PySys_Audit("ctypes.wstring_at", "nn", (Py_ssize_t)ptr, ssize) < 0) {
5734 return NULL;
5735 }
5736 if (ssize == -1)
5737 ssize = wcslen(ptr);
5738 return PyUnicode_FromWideChar(ptr, ssize);
5739 }
5740
5741
5742 static int
5743 _ctypes_add_types(PyObject *mod)
5744 {
5745 #define TYPE_READY(TYPE) \
5746 if (PyType_Ready(TYPE) < 0) { \
5747 return -1; \
5748 }
5749 #define CREATE_TYPE(TP, SPEC, META, BASE) do { \
5750 PyObject *type = PyType_FromMetaclass(META, mod, SPEC, \
5751 (PyObject *)BASE); \
5752 if (type == NULL) { \
5753 return -1; \
5754 } \
5755 TP = (PyTypeObject *)type; \
5756 } while (0)
5757
5758 #define MOD_ADD_TYPE(TP, SPEC, META, BASE) do { \
5759 CREATE_TYPE(TP, SPEC, META, BASE); \
5760 if (PyModule_AddType(mod, (PyTypeObject *)(TP)) < 0) { \
5761 return -1; \
5762 } \
5763 } while (0)
5764
5765 ctypes_state *st = get_module_state(mod);
5766
5767 /* Note:
5768 ob_type is the metatype (the 'type'), defaults to PyType_Type,
5769 tp_base is the base type, defaults to 'object' aka PyBaseObject_Type.
5770 */
5771 CREATE_TYPE(st->PyCArg_Type, &carg_spec, NULL, NULL);
5772 CREATE_TYPE(st->PyCThunk_Type, &cthunk_spec, NULL, NULL);
5773 CREATE_TYPE(st->PyCData_Type, &pycdata_spec, NULL, NULL);
5774
5775 // Common Metaclass
5776 CREATE_TYPE(st->PyCType_Type, &pyctype_type_spec,
5777 NULL, &PyType_Type);
5778
5779 /*************************************************
5780 *
5781 * Metaclasses
5782 */
5783 CREATE_TYPE(st->PyCStructType_Type, &pycstruct_type_spec,
5784 NULL, st->PyCType_Type);
5785 CREATE_TYPE(st->UnionType_Type, &union_type_spec,
5786 NULL, st->PyCType_Type);
5787 CREATE_TYPE(st->PyCPointerType_Type, &pycpointer_type_spec,
5788 NULL, st->PyCType_Type);
5789 CREATE_TYPE(st->PyCArrayType_Type, &pycarray_type_spec,
5790 NULL, st->PyCType_Type);
5791 CREATE_TYPE(st->PyCSimpleType_Type, &pycsimple_type_spec,
5792 NULL, st->PyCType_Type);
5793 CREATE_TYPE(st->PyCFuncPtrType_Type, &pycfuncptr_type_spec,
5794 NULL, st->PyCType_Type);
5795
5796 /*************************************************
5797 *
5798 * Classes using a custom metaclass
5799 */
5800
5801 MOD_ADD_TYPE(st->Struct_Type, &pycstruct_spec,
5802 st->PyCStructType_Type, st->PyCData_Type);
5803 MOD_ADD_TYPE(st->Union_Type, &pycunion_spec,
5804 st->UnionType_Type, st->PyCData_Type);
5805 MOD_ADD_TYPE(st->PyCPointer_Type, &pycpointer_spec,
5806 st->PyCPointerType_Type, st->PyCData_Type);
5807 MOD_ADD_TYPE(st->PyCArray_Type, &pycarray_spec,
5808 st->PyCArrayType_Type, st->PyCData_Type);
5809 MOD_ADD_TYPE(st->Simple_Type, &pycsimple_spec,
5810 st->PyCSimpleType_Type, st->PyCData_Type);
5811 MOD_ADD_TYPE(st->PyCFuncPtr_Type, &pycfuncptr_spec,
5812 st->PyCFuncPtrType_Type, st->PyCData_Type);
5813
5814 /*************************************************
5815 *
5816 * Simple classes
5817 */
5818
5819 CREATE_TYPE(st->PyCField_Type, &cfield_spec, NULL, NULL);
5820
5821 /*************************************************
5822 *
5823 * Other stuff
5824 */
5825
5826 CREATE_TYPE(st->DictRemover_Type, &dictremover_spec, NULL, NULL);
5827 CREATE_TYPE(st->StructParam_Type, &structparam_spec, NULL, NULL);
5828
5829 #ifdef MS_WIN32
5830 CREATE_TYPE(st->PyComError_Type, &comerror_spec, NULL, PyExc_Exception);
5831 #endif
5832
5833 #undef TYPE_READY
5834 #undef MOD_ADD_TYPE
5835 #undef CREATE_TYPE
5836 return 0;
5837 }
5838
5839
5840 static int
5841 _ctypes_add_objects(PyObject *mod)
5842 {
5843 #define MOD_ADD(name, expr) \
5844 do { \
5845 if (PyModule_Add(mod, name, (expr)) < 0) { \
5846 return -1; \
5847 } \
5848 } while (0)
5849
5850 ctypes_state *st = get_module_state(mod);
5851 MOD_ADD("_pointer_type_cache", Py_NewRef(st->_ctypes_ptrtype_cache));
5852
5853 #ifdef MS_WIN32
5854 MOD_ADD("COMError", Py_NewRef(st->PyComError_Type));
5855 MOD_ADD("FUNCFLAG_HRESULT", PyLong_FromLong(FUNCFLAG_HRESULT));
5856 MOD_ADD("FUNCFLAG_STDCALL", PyLong_FromLong(FUNCFLAG_STDCALL));
5857 #endif
5858 MOD_ADD("FUNCFLAG_CDECL", PyLong_FromLong(FUNCFLAG_CDECL));
5859 MOD_ADD("FUNCFLAG_USE_ERRNO", PyLong_FromLong(FUNCFLAG_USE_ERRNO));
5860 MOD_ADD("FUNCFLAG_USE_LASTERROR", PyLong_FromLong(FUNCFLAG_USE_LASTERROR));
5861 MOD_ADD("FUNCFLAG_PYTHONAPI", PyLong_FromLong(FUNCFLAG_PYTHONAPI));
5862 MOD_ADD("__version__", PyUnicode_FromString("1.1.0"));
5863
5864 MOD_ADD("_memmove_addr", PyLong_FromVoidPtr(memmove));
5865 MOD_ADD("_memset_addr", PyLong_FromVoidPtr(memset));
5866 MOD_ADD("_string_at_addr", PyLong_FromVoidPtr(string_at));
5867 MOD_ADD("_cast_addr", PyLong_FromVoidPtr(cast));
5868 MOD_ADD("_wstring_at_addr", PyLong_FromVoidPtr(wstring_at));
5869
5870 /* If RTLD_LOCAL is not defined (Windows!), set it to zero. */
5871 #if !HAVE_DECL_RTLD_LOCAL
5872 # define RTLD_LOCAL 0
5873 #endif
5874
5875 /* If RTLD_GLOBAL is not defined (cygwin), set it to the same value as
5876 RTLD_LOCAL. */
5877 #if !HAVE_DECL_RTLD_GLOBAL
5878 # define RTLD_GLOBAL RTLD_LOCAL
5879 #endif
5880 MOD_ADD("RTLD_LOCAL", PyLong_FromLong(RTLD_LOCAL));
5881 MOD_ADD("RTLD_GLOBAL", PyLong_FromLong(RTLD_GLOBAL));
5882 MOD_ADD("CTYPES_MAX_ARGCOUNT", PyLong_FromLong(CTYPES_MAX_ARGCOUNT));
5883 MOD_ADD("ArgumentError", Py_NewRef(st->PyExc_ArgError));
5884 MOD_ADD("SIZEOF_TIME_T", PyLong_FromSsize_t(SIZEOF_TIME_T));
5885 return 0;
5886 #undef MOD_ADD
5887 }
5888
5889
5890 static int
5891 _ctypes_mod_exec(PyObject *mod)
5892 {
5893 ctypes_state *st = get_module_state(mod);
5894 st->_unpickle = PyObject_GetAttrString(mod, "_unpickle");
5895 if (st->_unpickle == NULL) {
5896 return -1;
5897 }
5898
5899 st->_ctypes_ptrtype_cache = PyDict_New();
5900 if (st->_ctypes_ptrtype_cache == NULL) {
5901 return -1;
5902 }
5903
5904 st->PyExc_ArgError = PyErr_NewException("ctypes.ArgumentError", NULL, NULL);
5905 if (!st->PyExc_ArgError) {
5906 return -1;
5907 }
5908
5909 if (_ctypes_add_types(mod) < 0) {
5910 return -1;
5911 }
5912
5913 if (_ctypes_add_objects(mod) < 0) {
5914 return -1;
5915 }
5916 return 0;
5917 }
5918
5919
5920 static int
5921 module_traverse(PyObject *module, visitproc visit, void *arg) {
5922 ctypes_state *st = get_module_state(module);
5923 Py_VISIT(st->_ctypes_ptrtype_cache);
5924 Py_VISIT(st->_unpickle);
5925 Py_VISIT(st->array_cache);
5926 Py_VISIT(st->error_object_name);
5927 Py_VISIT(st->PyExc_ArgError);
5928 Py_VISIT(st->swapped_suffix);
5929
5930 Py_VISIT(st->DictRemover_Type);
5931 Py_VISIT(st->PyCArg_Type);
5932 Py_VISIT(st->PyCField_Type);
5933 Py_VISIT(st->PyCThunk_Type);
5934 Py_VISIT(st->StructParam_Type);
5935 Py_VISIT(st->PyCStructType_Type);
5936 Py_VISIT(st->UnionType_Type);
5937 Py_VISIT(st->PyCPointerType_Type);
5938 Py_VISIT(st->PyCArrayType_Type);
5939 Py_VISIT(st->PyCSimpleType_Type);
5940 Py_VISIT(st->PyCFuncPtrType_Type);
5941 Py_VISIT(st->PyCData_Type);
5942 Py_VISIT(st->Struct_Type);
5943 Py_VISIT(st->Union_Type);
5944 Py_VISIT(st->PyCArray_Type);
5945 Py_VISIT(st->Simple_Type);
5946 Py_VISIT(st->PyCPointer_Type);
5947 Py_VISIT(st->PyCFuncPtr_Type);
5948 #ifdef MS_WIN32
5949 Py_VISIT(st->PyComError_Type);
5950 #endif
5951 Py_VISIT(st->PyCType_Type);
5952 return 0;
5953 }
5954
5955 static int
5956 module_clear(PyObject *module) {
5957 ctypes_state *st = get_module_state(module);
5958 Py_CLEAR(st->_ctypes_ptrtype_cache);
5959 Py_CLEAR(st->_unpickle);
5960 Py_CLEAR(st->array_cache);
5961 Py_CLEAR(st->error_object_name);
5962 Py_CLEAR(st->PyExc_ArgError);
5963 Py_CLEAR(st->swapped_suffix);
5964
5965 Py_CLEAR(st->DictRemover_Type);
5966 Py_CLEAR(st->PyCArg_Type);
5967 Py_CLEAR(st->PyCField_Type);
5968 Py_CLEAR(st->PyCThunk_Type);
5969 Py_CLEAR(st->StructParam_Type);
5970 Py_CLEAR(st->PyCStructType_Type);
5971 Py_CLEAR(st->UnionType_Type);
5972 Py_CLEAR(st->PyCPointerType_Type);
5973 Py_CLEAR(st->PyCArrayType_Type);
5974 Py_CLEAR(st->PyCSimpleType_Type);
5975 Py_CLEAR(st->PyCFuncPtrType_Type);
5976 Py_CLEAR(st->PyCData_Type);
5977 Py_CLEAR(st->Struct_Type);
5978 Py_CLEAR(st->Union_Type);
5979 Py_CLEAR(st->PyCArray_Type);
5980 Py_CLEAR(st->Simple_Type);
5981 Py_CLEAR(st->PyCPointer_Type);
5982 Py_CLEAR(st->PyCFuncPtr_Type);
5983 #ifdef MS_WIN32
5984 Py_CLEAR(st->PyComError_Type);
5985 #endif
5986 Py_CLEAR(st->PyCType_Type);
5987 return 0;
5988 }
5989
5990 static void
5991 module_free(void *module)
5992 {
5993 (void)module_clear((PyObject *)module);
5994 }
5995
5996 static PyModuleDef_Slot module_slots[] = {
5997 {Py_mod_exec, _ctypes_mod_exec},
5998 {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
5999 {Py_mod_gil, Py_MOD_GIL_NOT_USED},
6000 {0, NULL}
6001 };
6002
6003 struct PyModuleDef _ctypesmodule = {
6004 PyModuleDef_HEAD_INIT,
6005 .m_name = "_ctypes",
6006 .m_doc = _ctypes__doc__,
6007 .m_size = sizeof(ctypes_state),
6008 .m_methods = _ctypes_module_methods,
6009 .m_slots = module_slots,
6010 .m_traverse = module_traverse,
6011 .m_clear = module_clear,
6012 .m_free = module_free,
6013 };
6014
6015 PyMODINIT_FUNC
6016 PyInit__ctypes(void)
6017 {
6018 return PyModuleDef_Init(&_ctypesmodule);
6019 }
6020
6021 /*
6022 Local Variables:
6023 compile-command: "cd .. && python setup.py -q build -g && python setup.py -q build install --home ~"
6024 End:
6025 */