Debian Codegraph @

Modules/_ctypes/cfield.c

raw
1 #ifndef Py_BUILD_CORE_BUILTIN
2 # define Py_BUILD_CORE_MODULE 1
3 #endif
4
5 #include "Python.h"
6 // windows.h must be included before pycore internal headers
7 #ifdef MS_WIN32
8 # include <windows.h>
9 #endif
10
11 #include "pycore_bitutils.h" // _Py_bswap32()
12 #include "pycore_call.h" // _PyObject_CallNoArgs()
13
14 #include <ffi.h>
15 #include "ctypes.h"
16
17 #define CTYPES_CFIELD_CAPSULE_NAME_PYMEM "_ctypes/cfield.c pymem"
18
19 /*[clinic input]
20 module _ctypes
21 [clinic start generated code]*/
22 /*[clinic end generated code: output=da39a3ee5e6b4b0d input=476a19c49b31a75c]*/
23
24 #include "clinic/cfield.c.h"
25
26 static void pymem_destructor(PyObject *ptr)
27 {
28 void *p = PyCapsule_GetPointer(ptr, CTYPES_CFIELD_CAPSULE_NAME_PYMEM);
29 if (p) {
30 PyMem_Free(p);
31 }
32 }
33
34
35 /******************************************************************/
36 /*
37 PyCField_Type
38 */
39 /*[clinic input]
40 class _ctypes.CField "PyObject *" "PyObject"
41 [clinic start generated code]*/
42 /*[clinic end generated code: output=da39a3ee5e6b4b0d input=602817ea3ffc709c]*/
43
44 static inline
45 Py_ssize_t NUM_BITS(Py_ssize_t bitsize);
46 static inline
47 Py_ssize_t LOW_BIT(Py_ssize_t offset);
48
49
50 /*[clinic input]
51 @classmethod
52 _ctypes.CField.__new__ as PyCField_new
53
54 *
55 name: object(subclass_of='&PyUnicode_Type')
56 type as proto: object
57 byte_size: Py_ssize_t
58 byte_offset: Py_ssize_t
59 index: Py_ssize_t
60 _internal_use: bool
61 bit_size as bit_size_obj: object = None
62 bit_offset as bit_offset_obj: object = None
63
64 [clinic start generated code]*/
65
66 static PyObject *
67 PyCField_new_impl(PyTypeObject *type, PyObject *name, PyObject *proto,
68 Py_ssize_t byte_size, Py_ssize_t byte_offset,
69 Py_ssize_t index, int _internal_use,
70 PyObject *bit_size_obj, PyObject *bit_offset_obj)
71 /*[clinic end generated code: output=3f2885ee4108b6e2 input=b343436e33c0d782]*/
72 {
73 CFieldObject* self = NULL;
74
75 if (!_internal_use) {
76 // Do not instantiate outside ctypes, yet.
77 // The constructor is internal API and may change without warning.
78 PyErr_Format(PyExc_TypeError, "cannot create %T object", type);
79 goto error;
80 }
81 if (byte_size < 0) {
82 PyErr_Format(PyExc_ValueError,
83 "byte size of field %R must not be negative, got %zd",
84 name, byte_size);
85 goto error;
86 }
87
88 ctypes_state *st = get_module_state_by_class(type);
89 StgInfo *info;
90 if (PyStgInfo_FromType(st, proto, &info) < 0) {
91 goto error;
92 }
93 if (info == NULL) {
94 PyErr_Format(PyExc_TypeError,
95 "type of field %R must be a C type", name);
96 goto error;
97 }
98 if (byte_size != info->size) {
99 PyErr_Format(PyExc_ValueError,
100 "byte size of field %R (%zd) does not match type size (%zd)",
101 name, byte_size, info->size);
102 goto error;
103 }
104
105 Py_ssize_t bitfield_size = 0;
106 Py_ssize_t bit_offset = 0;
107 if (bit_size_obj != Py_None) {
108 // It's a bit field!
109 switch(info->ffi_type_pointer.type) {
110 case FFI_TYPE_UINT8:
111 case FFI_TYPE_UINT16:
112 case FFI_TYPE_UINT32:
113 case FFI_TYPE_SINT64:
114 case FFI_TYPE_UINT64:
115 break;
116
117 case FFI_TYPE_SINT8:
118 case FFI_TYPE_SINT16:
119 case FFI_TYPE_SINT32:
120 if (info->getfunc != _ctypes_get_fielddesc("c")->getfunc
121 && info->getfunc != _ctypes_get_fielddesc("u")->getfunc)
122 {
123 break;
124 }
125 _Py_FALLTHROUGH; /* else fall through */
126 default:
127 PyErr_Format(PyExc_TypeError,
128 "bit fields not allowed for type %s",
129 ((PyTypeObject*)proto)->tp_name);
130 goto error;
131 }
132
133 if (byte_size > 100) {
134 // Bitfields must "live" in a field defined by a ffi type,
135 // so they're limited to about 8 bytes.
136 // This check is here to avoid overflow in later checks.
137 PyErr_Format(PyExc_ValueError,
138 "bit field %R size too large, got %zd",
139 name, byte_size);
140 goto error;
141 }
142 bitfield_size = PyLong_AsSsize_t(bit_size_obj);
143 if ((bitfield_size <= 0) || (bitfield_size > 255)) {
144 if (!PyErr_Occurred()) {
145 PyErr_Format(PyExc_ValueError,
146 "bit size of field %R out of range, got %zd",
147 name, bitfield_size);
148 }
149 goto error;
150 }
151 bit_offset = PyLong_AsSsize_t(bit_offset_obj);
152 if ((bit_offset < 0) || (bit_offset > 255)) {
153 if (!PyErr_Occurred()) {
154 PyErr_Format(PyExc_ValueError,
155 "bit offset of field %R out of range, got %zd",
156 name, bit_offset);
157 }
158 goto error;
159 }
160 if ((bitfield_size + bit_offset) > byte_size * 8) {
161 PyErr_Format(
162 PyExc_ValueError,
163 "bit field %R overflows its type (%zd + %zd > %zd)",
164 name, bit_offset, bitfield_size, byte_size * 8);
165 goto error;
166 }
167 }
168 else {
169 if (bit_offset_obj != Py_None) {
170 PyErr_Format(
171 PyExc_ValueError,
172 "field %R: bit_offset must be specified if bit_size is",
173 name);
174 goto error;
175 }
176 }
177
178 self = _CFieldObject_CAST(type->tp_alloc(type, 0));
179 if (!self) {
180 return NULL;
181 }
182 self->name = PyUnicode_FromObject(name);
183 if (!self->name) {
184 goto error;
185 }
186 assert(PyUnicode_CheckExact(self->name));
187
188 self->proto = Py_NewRef(proto);
189 self->byte_size = byte_size;
190 self->byte_offset = byte_offset;
191 self->bitfield_size = (uint8_t)bitfield_size;
192 self->bit_offset = (uint8_t)bit_offset;
193
194 self->index = index;
195
196 /* Field descriptors for 'c_char * n' are be special cased to
197 return a Python string instead of an Array object instance...
198 */
199 self->setfunc = NULL;
200 self->getfunc = NULL;
201 if (PyCArrayTypeObject_Check(st, proto)) {
202 StgInfo *ainfo;
203 if (PyStgInfo_FromType(st, proto, &ainfo) < 0) {
204 goto error;
205 }
206
207 if (ainfo && ainfo->proto) {
208 StgInfo *iinfo;
209 if (PyStgInfo_FromType(st, ainfo->proto, &iinfo) < 0) {
210 goto error;
211 }
212 if (!iinfo) {
213 PyErr_SetString(PyExc_TypeError,
214 "has no _stginfo_");
215 goto error;
216 }
217 if (iinfo->getfunc == _ctypes_get_fielddesc("c")->getfunc) {
218 struct fielddesc *fd = _ctypes_get_fielddesc("s");
219 self->getfunc = fd->getfunc;
220 self->setfunc = fd->setfunc;
221 }
222 if (iinfo->getfunc == _ctypes_get_fielddesc("u")->getfunc) {
223 struct fielddesc *fd = _ctypes_get_fielddesc("U");
224 self->getfunc = fd->getfunc;
225 self->setfunc = fd->setfunc;
226 }
227 }
228 }
229
230 return (PyObject *)self;
231 error:
232 Py_XDECREF(self);
233 return NULL;
234 }
235
236 static inline Py_ssize_t
237 _pack_legacy_size(CFieldObject *field)
238 {
239 if (field->bitfield_size) {
240 Py_ssize_t bit_offset = field->bit_offset;
241 return (field->bitfield_size << 16) | bit_offset;
242 }
243 return field->byte_size;
244 }
245
246 static int
247 PyCField_set_lock_held(PyObject *op, PyObject *inst, PyObject *value)
248 {
249 CDataObject *dst;
250 char *ptr;
251 CFieldObject *self = _CFieldObject_CAST(op);
252 ctypes_state *st = get_module_state_by_class(Py_TYPE(self));
253 if (!CDataObject_Check(st, inst)) {
254 PyErr_SetString(PyExc_TypeError,
255 "not a ctype instance");
256 return -1;
257 }
258 dst = _CDataObject_CAST(inst);
259 ptr = dst->b_ptr + self->byte_offset;
260 if (value == NULL) {
261 PyErr_SetString(PyExc_TypeError,
262 "can't delete attribute");
263 return -1;
264 }
265 return PyCData_set(st, inst, self->proto, self->setfunc, value,
266 self->index, _pack_legacy_size(self), ptr);
267 }
268
269 static int
270 PyCField_set(PyObject *op, PyObject *inst, PyObject *value)
271 {
272 int res;
273 Py_BEGIN_CRITICAL_SECTION(inst);
274 res = PyCField_set_lock_held(op, inst, value);
275 Py_END_CRITICAL_SECTION();
276 return res;
277 }
278
279 static PyObject *
280 PyCField_get(PyObject *op, PyObject *inst, PyObject *type)
281 {
282 CDataObject *src;
283 CFieldObject *self = _CFieldObject_CAST(op);
284 if (inst == NULL) {
285 return Py_NewRef(self);
286 }
287 ctypes_state *st = get_module_state_by_class(Py_TYPE(self));
288 if (!CDataObject_Check(st, inst)) {
289 PyErr_SetString(PyExc_TypeError,
290 "not a ctype instance");
291 return NULL;
292 }
293 src = _CDataObject_CAST(inst);
294 PyObject *res;
295 Py_BEGIN_CRITICAL_SECTION(inst);
296 res = PyCData_get(st, self->proto, self->getfunc, inst,
297 self->index, _pack_legacy_size(self),
298 src->b_ptr + self->byte_offset);
299 Py_END_CRITICAL_SECTION();
300 return res;
301 }
302
303 static PyObject *
304 PyCField_get_legacy_size(PyObject *self, void *Py_UNUSED(closure))
305 {
306 CFieldObject *field = _CFieldObject_CAST(self);
307 return PyLong_FromSsize_t(_pack_legacy_size(field));
308 }
309
310 static PyObject *
311 PyCField_get_bit_size(PyObject *self, void *Py_UNUSED(closure))
312 {
313 CFieldObject *field = _CFieldObject_CAST(self);
314 if (field->bitfield_size) {
315 return PyLong_FromSsize_t(field->bitfield_size);
316 }
317 if (field->byte_size < PY_SSIZE_T_MAX / 8) {
318 return PyLong_FromSsize_t(field->byte_size * 8);
319 }
320
321 // If the bit size overflows Py_ssize_t, we don't try fitting it in
322 // a bigger C type. Use Python ints.
323 PyObject *byte_size_obj = NULL;
324 PyObject *eight = NULL;
325 PyObject *result = NULL;
326
327 byte_size_obj = PyLong_FromSsize_t(field->byte_size);
328 if (!byte_size_obj) {
329 goto finally;
330 }
331 eight = PyLong_FromLong(8);
332 if (!eight) {
333 goto finally;
334 }
335 result = PyNumber_Multiply(byte_size_obj, eight);
336 finally:
337 Py_XDECREF(byte_size_obj);
338 Py_XDECREF(eight);
339 return result;
340 }
341
342 static PyObject *
343 PyCField_is_bitfield(PyObject *self, void *Py_UNUSED(closure))
344 {
345 return PyBool_FromLong(_CFieldObject_CAST(self)->bitfield_size);
346 }
347
348 static PyObject *
349 PyCField_is_anonymous(PyObject *self, void *Py_UNUSED(closure))
350 {
351 return PyBool_FromLong(_CFieldObject_CAST(self)->anonymous);
352 }
353
354 static PyGetSetDef PyCField_getset[] = {
355 { "size", PyCField_get_legacy_size, NULL,
356 PyDoc_STR("size in bytes of this field. For bitfields, this is a "
357 "legacy packed value; use byte_size instead") },
358
359 { "bit_size", PyCField_get_bit_size, NULL,
360 PyDoc_STR("size of this field in bits") },
361 { "is_bitfield", PyCField_is_bitfield, NULL,
362 PyDoc_STR("true if this is a bitfield") },
363 { "is_anonymous", PyCField_is_anonymous, NULL,
364 PyDoc_STR("true if this field is anonymous") },
365 { NULL },
366 };
367
368 static PyMemberDef PyCField_members[] = {
369 { "name",
370 .type = Py_T_OBJECT_EX,
371 .offset = offsetof(CFieldObject, name),
372 .flags = Py_READONLY,
373 .doc = PyDoc_STR("name of this field") },
374 { "type",
375 .type = Py_T_OBJECT_EX,
376 .offset = offsetof(CFieldObject, proto),
377 .flags = Py_READONLY,
378 .doc = PyDoc_STR("type of this field") },
379 { "offset",
380 .type = Py_T_PYSSIZET,
381 .offset = offsetof(CFieldObject, byte_offset),
382 .flags = Py_READONLY,
383 .doc = PyDoc_STR(
384 "offset in bytes of this field (same as byte_offset)") },
385 { "byte_offset",
386 .type = Py_T_PYSSIZET,
387 .offset = offsetof(CFieldObject, byte_offset),
388 .flags = Py_READONLY,
389 .doc = PyDoc_STR("offset in bytes of this field. "
390 "For bitfields: excludes bit_offset.") },
391 { "byte_size",
392 .type = Py_T_PYSSIZET,
393 .offset = offsetof(CFieldObject, byte_size),
394 .flags = Py_READONLY,
395 .doc = PyDoc_STR("size of this field in bytes") },
396 { "bit_offset",
397 .type = Py_T_UBYTE,
398 .offset = offsetof(CFieldObject, bit_offset),
399 .flags = Py_READONLY,
400 .doc = PyDoc_STR("additional offset in bits (relative to byte_offset);"
401 " zero for non-bitfields") },
402 { NULL },
403 };
404
405 static int
406 PyCField_traverse(PyObject *op, visitproc visit, void *arg)
407 {
408 CFieldObject *self = _CFieldObject_CAST(op);
409 Py_VISIT(Py_TYPE(self));
410 Py_VISIT(self->proto);
411 return 0;
412 }
413
414 static int
415 PyCField_clear(PyObject *op)
416 {
417 CFieldObject *self = _CFieldObject_CAST(op);
418 Py_CLEAR(self->proto);
419 Py_CLEAR(self->name);
420 return 0;
421 }
422
423 static void
424 PyCField_dealloc(PyObject *self)
425 {
426 PyTypeObject *tp = Py_TYPE(self);
427 PyObject_GC_UnTrack(self);
428 (void)PyCField_clear(self);
429 Py_TYPE(self)->tp_free(self);
430 Py_DECREF(tp);
431 }
432
433 static PyObject *
434 PyCField_repr(PyObject *self)
435 {
436 CFieldObject *field = _CFieldObject_CAST(self);
437 PyObject *result;
438 const char *tp_name = ((PyTypeObject *)field->proto)->tp_name;
439
440 if (field->bitfield_size) {
441 result = PyUnicode_FromFormat(
442 "<%T %R type=%s, ofs=%zd, bit_size=%zd, bit_offset=%zd>",
443 self,
444 field->name, tp_name, field->byte_offset,
445 (Py_ssize_t)field->bitfield_size,
446 (Py_ssize_t)field->bit_offset);
447 }
448 else {
449 result = PyUnicode_FromFormat(
450 "<%T %R type=%s, ofs=%zd, size=%zd>",
451 self,
452 field->name, tp_name, field->byte_offset,
453 field->byte_size);
454 }
455 return result;
456 }
457
458 static PyType_Slot cfield_slots[] = {
459 {Py_tp_new, PyCField_new},
460 {Py_tp_dealloc, PyCField_dealloc},
461 {Py_tp_repr, PyCField_repr},
462 {Py_tp_doc, (void *)PyDoc_STR("Structure/Union member")},
463 {Py_tp_traverse, PyCField_traverse},
464 {Py_tp_clear, PyCField_clear},
465 {Py_tp_getset, PyCField_getset},
466 {Py_tp_members, PyCField_members},
467 {Py_tp_descr_get, PyCField_get},
468 {Py_tp_descr_set, PyCField_set},
469 {0, NULL},
470 };
471
472 PyType_Spec cfield_spec = {
473 .name = "ctypes.CField",
474 .basicsize = sizeof(CFieldObject),
475 .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
476 Py_TPFLAGS_IMMUTABLETYPE),
477 .slots = cfield_slots,
478 };
479
480
481 /*****************************************************************
482 * Integer fields, with bitfield support
483 */
484
485 /* how to decode the size field, for integer get/set functions */
486 static inline
487 Py_ssize_t LOW_BIT(Py_ssize_t offset) {
488 return offset & 0xFFFF;
489 }
490 static inline
491 Py_ssize_t NUM_BITS(Py_ssize_t bitsize) {
492 return bitsize >> 16;
493 }
494
495 /* Doesn't work if NUM_BITS(size) == 0, but it never happens in SET() call. */
496 #define BIT_MASK(type, size) (((((type)1 << (NUM_BITS(size) - 1)) - 1) << 1) + 1)
497
498 /* This macro CHANGES the first parameter IN PLACE. For proper sign handling,
499 we must first shift left, then right.
500 */
501 #define GET_BITFIELD(v, size) \
502 if (NUM_BITS(size)) { \
503 v <<= (sizeof(v)*8 - LOW_BIT(size) - NUM_BITS(size)); \
504 v >>= (sizeof(v)*8 - NUM_BITS(size)); \
505 }
506
507 /* This macro RETURNS the first parameter with the bit field CHANGED. */
508 #define SET(type, x, v, size) \
509 (NUM_BITS(size) ? \
510 ( ( (type)(x) & ~(BIT_MASK(type, size) << LOW_BIT(size)) ) | ( ((type)(v) & BIT_MASK(type, size)) << LOW_BIT(size) ) ) \
511 : (type)(v))
512
513 /*****************************************************************
514 * The setter methods return an object which must be kept alive, to keep the
515 * data valid which has been stored in the memory block. The ctypes object
516 * instance inserts this object into its 'b_objects' list.
517 *
518 * For simple Python types like integers or characters, there is nothing that
519 * has to been kept alive, so Py_None is returned in these cases. But this
520 * makes inspecting the 'b_objects' list, which is accessible from Python for
521 * debugging, less useful.
522 *
523 * So, defining the _CTYPES_DEBUG_KEEP symbol returns the original value
524 * instead of Py_None.
525 */
526
527 #ifdef _CTYPES_DEBUG_KEEP
528 #define _RET(x) Py_INCREF(x); return x
529 #else
530 #define _RET(X) Py_RETURN_NONE
531 #endif
532
533 /*****************************************************************
534 * accessor methods for fixed-width integers (e.g. int8_t, uint64_t),
535 * supporting bit fields.
536 * These are named e.g. `i8_set`/`i8_get` or `u64_set`/`u64_get`,
537 * and are all alike, so they're defined using a macro.
538 */
539
540 #define FIXINT_GETSET(TAG, CTYPE, NBITS, PYAPI_FROMFUNC) \
541 static PyObject * \
542 TAG ## _set(void *ptr, PyObject *value, Py_ssize_t size_arg) \
543 { \
544 assert(NUM_BITS(size_arg) || (size_arg == (NBITS) / 8)); \
545 CTYPE val; \
546 if (PyLong_Check(value) \
547 && PyUnstable_Long_IsCompact((PyLongObject *)value)) \
548 { \
549 val = (CTYPE)PyUnstable_Long_CompactValue( \
550 (PyLongObject *)value); \
551 } \
552 else { \
553 Py_ssize_t res = PyLong_AsNativeBytes( \
554 value, &val, (NBITS) / 8, \
555 Py_ASNATIVEBYTES_NATIVE_ENDIAN \
556 | Py_ASNATIVEBYTES_ALLOW_INDEX); \
557 if (res < 0) { \
558 return NULL; \
559 } \
560 } \
561 CTYPE prev; \
562 memcpy(&prev, ptr, (NBITS) / 8); \
563 val = SET(CTYPE, prev, val, size_arg); \
564 memcpy(ptr, &val, (NBITS) / 8); \
565 _RET(value); \
566 } \
567 \
568 static PyObject * \
569 TAG ## _get(void *ptr, Py_ssize_t size_arg) \
570 { \
571 assert(NUM_BITS(size_arg) || (size_arg == (NBITS) / 8)); \
572 CTYPE val; \
573 memcpy(&val, ptr, sizeof(val)); \
574 GET_BITFIELD(val, size_arg); \
575 return PYAPI_FROMFUNC(val); \
576 } \
577 ///////////////////////////////////////////////////////////////////////////
578
579 /* Another macro for byte-swapped variants (e.g. `i8_set_sw`/`i8_get_sw`) */
580
581 #define FIXINT_GETSET_SW(TAG, CTYPE, NBITS, PYAPI_FROMFUNC, PY_SWAPFUNC) \
582 static PyObject * \
583 TAG ## _set_sw(void *ptr, PyObject *value, Py_ssize_t size_arg) \
584 { \
585 CTYPE val; \
586 PyObject *res = TAG ## _set(&val, value, (NBITS) / 8); \
587 if (res == NULL) { \
588 return NULL; \
589 } \
590 Py_DECREF(res); \
591 CTYPE field; \
592 memcpy(&field, ptr, sizeof(field)); \
593 field = PY_SWAPFUNC(field); \
594 field = SET(CTYPE, field, val, size_arg); \
595 field = PY_SWAPFUNC(field); \
596 memcpy(ptr, &field, sizeof(field)); \
597 _RET(value); \
598 } \
599 \
600 static PyObject * \
601 TAG ## _get_sw(void *ptr, Py_ssize_t size_arg) \
602 { \
603 assert(NUM_BITS(size_arg) || (size_arg == (NBITS) / 8)); \
604 CTYPE val; \
605 memcpy(&val, ptr, sizeof(val)); \
606 val = PY_SWAPFUNC(val); \
607 GET_BITFIELD(val, size_arg); \
608 return PYAPI_FROMFUNC(val); \
609 } \
610 ///////////////////////////////////////////////////////////////////////////
611
612 /* These macros are expanded for all supported combinations of byte sizes
613 * (1, 2, 4, 8), signed and unsigned, native and swapped byteorder.
614 * That's a lot, so generate the list with Argument Clinic (`make clinic`).
615 */
616
617 /*[python input]
618 for nbits in 8, 16, 32, 64:
619 for sgn in 'i', 'u':
620 u = 'u' if sgn == 'u' else ''
621 U = u.upper()
622 apibits = max(nbits, 32)
623 parts = [
624 f'{sgn}{nbits}',
625 f'{u}int{nbits}_t',
626 f'{nbits}',
627 f'PyLong_From{U}Int{apibits}',
628 ]
629 print(f'FIXINT_GETSET({", ".join(parts)})')
630 if nbits > 8:
631 parts.append(f'_Py_bswap{nbits}')
632 print(f'FIXINT_GETSET_SW({", ".join(parts)})')
633 [python start generated code]*/
634 FIXINT_GETSET(i8, int8_t, 8, PyLong_FromInt32)
635 FIXINT_GETSET(u8, uint8_t, 8, PyLong_FromUInt32)
636 FIXINT_GETSET(i16, int16_t, 16, PyLong_FromInt32)
637 FIXINT_GETSET_SW(i16, int16_t, 16, PyLong_FromInt32, _Py_bswap16)
638 FIXINT_GETSET(u16, uint16_t, 16, PyLong_FromUInt32)
639 FIXINT_GETSET_SW(u16, uint16_t, 16, PyLong_FromUInt32, _Py_bswap16)
640 FIXINT_GETSET(i32, int32_t, 32, PyLong_FromInt32)
641 FIXINT_GETSET_SW(i32, int32_t, 32, PyLong_FromInt32, _Py_bswap32)
642 FIXINT_GETSET(u32, uint32_t, 32, PyLong_FromUInt32)
643 FIXINT_GETSET_SW(u32, uint32_t, 32, PyLong_FromUInt32, _Py_bswap32)
644 FIXINT_GETSET(i64, int64_t, 64, PyLong_FromInt64)
645 FIXINT_GETSET_SW(i64, int64_t, 64, PyLong_FromInt64, _Py_bswap64)
646 FIXINT_GETSET(u64, uint64_t, 64, PyLong_FromUInt64)
647 FIXINT_GETSET_SW(u64, uint64_t, 64, PyLong_FromUInt64, _Py_bswap64)
648 /*[python end generated code: output=3d60c96fa58e07d5 input=0b7e166f2ea18e70]*/
649
650 // For one-byte types, swapped variants are the same as native
651 #define i8_set_sw i8_set
652 #define i8_get_sw i8_get
653 #define u8_set_sw u8_set
654 #define u8_get_sw u8_get
655
656 #undef FIXINT_GETSET
657 #undef FIXINT_GETSET_SW
658
659 /*****************************************************************
660 * non-integer accessor methods, not supporting bit fields
661 */
662
663 #ifndef MS_WIN32
664 /* http://msdn.microsoft.com/en-us/library/cc237864.aspx */
665 #define VARIANT_FALSE 0x0000
666 #define VARIANT_TRUE 0xFFFF
667 #endif
668 /* v: short BOOL - VARIANT_BOOL */
669 static PyObject *
670 v_set(void *ptr, PyObject *value, Py_ssize_t size)
671 {
672 assert(NUM_BITS(size) || (size == sizeof(short int)));
673 switch (PyObject_IsTrue(value)) {
674 case -1:
675 return NULL;
676 case 0:
677 *(short int *)ptr = VARIANT_FALSE;
678 _RET(value);
679 default:
680 *(short int *)ptr = VARIANT_TRUE;
681 _RET(value);
682 }
683 }
684
685 static PyObject *
686 v_get(void *ptr, Py_ssize_t size)
687 {
688 assert(NUM_BITS(size) || (size == sizeof(short int)));
689 return PyBool_FromLong((long)*(short int *)ptr);
690 }
691
692 /* bool ('?'): bool (i.e. _Bool) */
693 static PyObject *
694 bool_set(void *ptr, PyObject *value, Py_ssize_t size)
695 {
696 assert(NUM_BITS(size) || (size == sizeof(bool)));
697 switch (PyObject_IsTrue(value)) {
698 case -1:
699 return NULL;
700 case 0:
701 *(bool *)ptr = 0;
702 _RET(value);
703 default:
704 *(bool *)ptr = 1;
705 _RET(value);
706 }
707 }
708
709 static PyObject *
710 bool_get(void *ptr, Py_ssize_t size)
711 {
712 assert(NUM_BITS(size) || (size == sizeof(bool)));
713 return PyBool_FromLong((long)*(bool *)ptr);
714 }
715
716 /* g: long double */
717 static PyObject *
718 g_set(void *ptr, PyObject *value, Py_ssize_t size)
719 {
720 assert(NUM_BITS(size) || (size == sizeof(long double)));
721 long double x;
722
723 x = PyFloat_AsDouble(value);
724 if (x == -1 && PyErr_Occurred())
725 return NULL;
726 memcpy(ptr, &x, sizeof(long double));
727 _RET(value);
728 }
729
730 static PyObject *
731 g_get(void *ptr, Py_ssize_t size)
732 {
733 assert(NUM_BITS(size) || (size == sizeof(long double)));
734 long double val;
735 memcpy(&val, ptr, sizeof(long double));
736 return PyFloat_FromDouble(val);
737 }
738
739 /* d: double */
740 static PyObject *
741 d_set(void *ptr, PyObject *value, Py_ssize_t size)
742 {
743 assert(NUM_BITS(size) || (size == sizeof(double)));
744 double x;
745
746 x = PyFloat_AsDouble(value);
747 if (x == -1 && PyErr_Occurred())
748 return NULL;
749 memcpy(ptr, &x, sizeof(double));
750 _RET(value);
751 }
752
753 static PyObject *
754 d_get(void *ptr, Py_ssize_t size)
755 {
756 assert(NUM_BITS(size) || (size == sizeof(double)));
757 double val;
758 memcpy(&val, ptr, sizeof(val));
759 return PyFloat_FromDouble(val);
760 }
761
762 #if defined(_Py_FFI_SUPPORT_C_COMPLEX)
763
764 /* We don't use _Complex types here, using arrays instead, as the C11+
765 standard says: "Each complex type has the same representation and alignment
766 requirements as an array type containing exactly two elements of the
767 corresponding real type; the first element is equal to the real part, and
768 the second element to the imaginary part, of the complex number." */
769
770 /* D: double complex */
771 static PyObject *
772 D_set(void *ptr, PyObject *value, Py_ssize_t size)
773 {
774 assert(NUM_BITS(size) || (size == 2*sizeof(double)));
775 Py_complex c = PyComplex_AsCComplex(value);
776
777 if (c.real == -1 && PyErr_Occurred()) {
778 return NULL;
779 }
780 double x[2] = {c.real, c.imag};
781 memcpy(ptr, &x, sizeof(x));
782 _RET(value);
783 }
784
785 static PyObject *
786 D_get(void *ptr, Py_ssize_t size)
787 {
788 assert(NUM_BITS(size) || (size == 2*sizeof(double)));
789 double x[2];
790
791 memcpy(&x, ptr, sizeof(x));
792 return PyComplex_FromDoubles(x[0], x[1]);
793 }
794
795 static PyObject *
796 D_set_sw(void *ptr, PyObject *value, Py_ssize_t size)
797 {
798 assert(NUM_BITS(size) || (size == 2*sizeof(double)));
799 Py_complex c = PyComplex_AsCComplex(value);
800
801 if (c.real == -1 && PyErr_Occurred()) {
802 return NULL;
803 }
804 #ifdef WORDS_BIGENDIAN
805 if (PyFloat_Pack8(c.real, ptr, 1)
806 || PyFloat_Pack8(c.imag, ptr + sizeof(double), 1))
807 {
808 return NULL;
809 }
810 #else
811 if (PyFloat_Pack8(c.real, ptr, 0)
812 || PyFloat_Pack8(c.imag, ptr + sizeof(double), 0))
813 {
814 return NULL;
815 }
816 #endif
817 _RET(value);
818 }
819
820 static PyObject *
821 D_get_sw(void *ptr, Py_ssize_t size)
822 {
823 assert(NUM_BITS(size) || (size == 2*sizeof(double)));
824 #ifdef WORDS_BIGENDIAN
825 return PyComplex_FromDoubles(PyFloat_Unpack8(ptr, 1),
826 PyFloat_Unpack8(ptr + sizeof(double), 1));
827 #else
828 return PyComplex_FromDoubles(PyFloat_Unpack8(ptr, 0),
829 PyFloat_Unpack8(ptr + sizeof(double), 0));
830 #endif
831 }
832
833 /* F: float complex */
834 static PyObject *
835 F_set(void *ptr, PyObject *value, Py_ssize_t size)
836 {
837 assert(NUM_BITS(size) || (size == 2*sizeof(float)));
838 Py_complex c = PyComplex_AsCComplex(value);
839
840 if (c.real == -1 && PyErr_Occurred()) {
841 return NULL;
842 }
843 float x[2] = {(float)c.real, (float)c.imag};
844 memcpy(ptr, &x, sizeof(x));
845 _RET(value);
846 }
847
848 static PyObject *
849 F_get(void *ptr, Py_ssize_t size)
850 {
851 assert(NUM_BITS(size) || (size == 2*sizeof(float)));
852 float x[2];
853
854 memcpy(&x, ptr, sizeof(x));
855 return PyComplex_FromDoubles(x[0], x[1]);
856 }
857
858 static PyObject *
859 F_set_sw(void *ptr, PyObject *value, Py_ssize_t size)
860 {
861 assert(NUM_BITS(size) || (size == 2*sizeof(float)));
862 Py_complex c = PyComplex_AsCComplex(value);
863
864 if (c.real == -1 && PyErr_Occurred()) {
865 return NULL;
866 }
867 #ifdef WORDS_BIGENDIAN
868 if (PyFloat_Pack4(c.real, ptr, 1)
869 || PyFloat_Pack4(c.imag, ptr + sizeof(float), 1))
870 {
871 return NULL;
872 }
873 #else
874 if (PyFloat_Pack4(c.real, ptr, 0)
875 || PyFloat_Pack4(c.imag, ptr + sizeof(float), 0))
876 {
877 return NULL;
878 }
879 #endif
880 _RET(value);
881 }
882
883 static PyObject *
884 F_get_sw(void *ptr, Py_ssize_t size)
885 {
886 assert(NUM_BITS(size) || (size == 2*sizeof(float)));
887 #ifdef WORDS_BIGENDIAN
888 return PyComplex_FromDoubles(PyFloat_Unpack4(ptr, 1),
889 PyFloat_Unpack4(ptr + sizeof(float), 1));
890 #else
891 return PyComplex_FromDoubles(PyFloat_Unpack4(ptr, 0),
892 PyFloat_Unpack4(ptr + sizeof(float), 0));
893 #endif
894 }
895
896 /* G: long double complex */
897 static PyObject *
898 G_set(void *ptr, PyObject *value, Py_ssize_t size)
899 {
900 assert(NUM_BITS(size) || (size == 2*sizeof(long double)));
901 Py_complex c = PyComplex_AsCComplex(value);
902
903 if (c.real == -1 && PyErr_Occurred()) {
904 return NULL;
905 }
906 long double x[2] = {c.real, c.imag};
907 memcpy(ptr, &x, sizeof(x));
908 _RET(value);
909 }
910
911 static PyObject *
912 G_get(void *ptr, Py_ssize_t size)
913 {
914 assert(NUM_BITS(size) || (size == 2*sizeof(long double)));
915 long double x[2];
916
917 memcpy(&x, ptr, sizeof(x));
918 return PyComplex_FromDoubles((double)x[0], (double)x[1]);
919 }
920 #endif
921
922 /* d: double */
923 static PyObject *
924 d_set_sw(void *ptr, PyObject *value, Py_ssize_t size)
925 {
926 assert(NUM_BITS(size) || (size == sizeof(double)));
927 double x;
928
929 x = PyFloat_AsDouble(value);
930 if (x == -1 && PyErr_Occurred())
931 return NULL;
932 #ifdef WORDS_BIGENDIAN
933 if (PyFloat_Pack8(x, ptr, 1))
934 return NULL;
935 #else
936 if (PyFloat_Pack8(x, ptr, 0))
937 return NULL;
938 #endif
939 _RET(value);
940 }
941
942 static PyObject *
943 d_get_sw(void *ptr, Py_ssize_t size)
944 {
945 assert(NUM_BITS(size) || (size == sizeof(double)));
946 #ifdef WORDS_BIGENDIAN
947 return PyFloat_FromDouble(PyFloat_Unpack8(ptr, 1));
948 #else
949 return PyFloat_FromDouble(PyFloat_Unpack8(ptr, 0));
950 #endif
951 }
952
953 /* f: float */
954 static PyObject *
955 f_set(void *ptr, PyObject *value, Py_ssize_t size)
956 {
957 assert(NUM_BITS(size) || (size == sizeof(float)));
958 float x;
959
960 x = (float)PyFloat_AsDouble(value);
961 if (x == -1 && PyErr_Occurred())
962 return NULL;
963 memcpy(ptr, &x, sizeof(x));
964 _RET(value);
965 }
966
967 static PyObject *
968 f_get(void *ptr, Py_ssize_t size)
969 {
970 assert(NUM_BITS(size) || (size == sizeof(float)));
971 float val;
972 memcpy(&val, ptr, sizeof(val));
973 return PyFloat_FromDouble(val);
974 }
975
976 static PyObject *
977 f_set_sw(void *ptr, PyObject *value, Py_ssize_t size)
978 {
979 assert(NUM_BITS(size) || (size == sizeof(float)));
980 float x;
981
982 x = (float)PyFloat_AsDouble(value);
983 if (x == -1 && PyErr_Occurred())
984 return NULL;
985 #ifdef WORDS_BIGENDIAN
986 if (PyFloat_Pack4(x, ptr, 1))
987 return NULL;
988 #else
989 if (PyFloat_Pack4(x, ptr, 0))
990 return NULL;
991 #endif
992 _RET(value);
993 }
994
995 static PyObject *
996 f_get_sw(void *ptr, Py_ssize_t size)
997 {
998 assert(NUM_BITS(size) || (size == sizeof(float)));
999 #ifdef WORDS_BIGENDIAN
1000 return PyFloat_FromDouble(PyFloat_Unpack4(ptr, 1));
1001 #else
1002 return PyFloat_FromDouble(PyFloat_Unpack4(ptr, 0));
1003 #endif
1004 }
1005
1006 /* O: Python object */
1007 /*
1008 py_object refcounts:
1009
1010 1. If we have a py_object instance, O_get must Py_INCREF the returned
1011 object, of course. If O_get is called from a function result, no py_object
1012 instance is created - so callproc.c::GetResult has to call Py_DECREF.
1013
1014 2. The memory block in py_object owns a refcount. So, py_object must call
1015 Py_DECREF on destruction. Maybe only when b_needsfree is non-zero.
1016 */
1017 static PyObject *
1018 O_get(void *ptr, Py_ssize_t size)
1019 {
1020 assert(NUM_BITS(size) || (size == sizeof(PyObject *)));
1021 PyObject *ob = *(PyObject **)ptr;
1022 if (ob == NULL) {
1023 if (!PyErr_Occurred())
1024 /* Set an error if not yet set */
1025 PyErr_SetString(PyExc_ValueError,
1026 "PyObject is NULL");
1027 return NULL;
1028 }
1029 return Py_NewRef(ob);
1030 }
1031
1032 static PyObject *
1033 O_set(void *ptr, PyObject *value, Py_ssize_t size)
1034 {
1035 assert(NUM_BITS(size) || (size == sizeof(PyObject *)));
1036 /* Hm, does the memory block need it's own refcount or not? */
1037 *(PyObject **)ptr = value;
1038 return Py_NewRef(value);
1039 }
1040
1041
1042 /* c: a single byte-character */
1043 static PyObject *
1044 c_set(void *ptr, PyObject *value, Py_ssize_t size)
1045 {
1046 assert(NUM_BITS(size) || (size == sizeof(char)));
1047 if (PyBytes_Check(value)) {
1048 if (PyBytes_GET_SIZE(value) != 1) {
1049 PyErr_Format(PyExc_TypeError,
1050 "one character bytes, bytearray, or an integer "
1051 "in range(256) expected, not bytes of length %zd",
1052 PyBytes_GET_SIZE(value));
1053 return NULL;
1054 }
1055 *(char *)ptr = PyBytes_AS_STRING(value)[0];
1056 _RET(value);
1057 }
1058 if (PyByteArray_Check(value)) {
1059 if (PyByteArray_GET_SIZE(value) != 1) {
1060 PyErr_Format(PyExc_TypeError,
1061 "one character bytes, bytearray, or an integer "
1062 "in range(256) expected, not bytearray of length %zd",
1063 PyByteArray_GET_SIZE(value));
1064 return NULL;
1065 }
1066 *(char *)ptr = PyByteArray_AS_STRING(value)[0];
1067 _RET(value);
1068 }
1069 if (PyLong_Check(value)) {
1070 int overflow;
1071 long longval = PyLong_AsLongAndOverflow(value, &overflow);
1072 if (longval == -1 && PyErr_Occurred()) {
1073 return NULL;
1074 }
1075 if (overflow || longval < 0 || longval >= 256) {
1076 PyErr_SetString(PyExc_TypeError, "integer not in range(256)");
1077 return NULL;
1078 }
1079 *(char *)ptr = (char)longval;
1080 _RET(value);
1081 }
1082 PyErr_Format(PyExc_TypeError,
1083 "one character bytes, bytearray, or an integer "
1084 "in range(256) expected, not %T",
1085 value);
1086 return NULL;
1087 }
1088
1089
1090 static PyObject *
1091 c_get(void *ptr, Py_ssize_t size)
1092 {
1093 assert(NUM_BITS(size) || (size == sizeof(char)));
1094 return PyBytes_FromStringAndSize((char *)ptr, 1);
1095 }
1096
1097 /* u: a single wchar_t character */
1098 static PyObject *
1099 u_set(void *ptr, PyObject *value, Py_ssize_t size)
1100 {
1101 assert(NUM_BITS(size) || (size == sizeof(wchar_t)));
1102 Py_ssize_t len;
1103 wchar_t chars[2];
1104 if (!PyUnicode_Check(value)) {
1105 PyErr_Format(PyExc_TypeError,
1106 "a unicode character expected, not instance of %T",
1107 value);
1108 return NULL;
1109 }
1110
1111 len = PyUnicode_AsWideChar(value, chars, 2);
1112 if (len != 1) {
1113 if (PyUnicode_GET_LENGTH(value) != 1) {
1114 PyErr_Format(PyExc_TypeError,
1115 "a unicode character expected, not a string of length %zd",
1116 PyUnicode_GET_LENGTH(value));
1117 }
1118 else {
1119 PyErr_Format(PyExc_TypeError,
1120 "the string %A cannot be converted to a single wchar_t character",
1121 value);
1122 }
1123 return NULL;
1124 }
1125
1126 *(wchar_t *)ptr = chars[0];
1127
1128 _RET(value);
1129 }
1130
1131
1132 static PyObject *
1133 u_get(void *ptr, Py_ssize_t size)
1134 {
1135 assert(NUM_BITS(size) || (size == sizeof(wchar_t)));
1136 return PyUnicode_FromWideChar((wchar_t *)ptr, 1);
1137 }
1138
1139 /* U: a wchar_t* unicode string */
1140 static PyObject *
1141 U_get(void *ptr, Py_ssize_t size)
1142 {
1143 Py_ssize_t len;
1144 wchar_t *p;
1145
1146 size /= sizeof(wchar_t); /* we count character units here, not bytes */
1147
1148 /* We need 'result' to be able to count the characters with wcslen,
1149 since ptr may not be NUL terminated. If the length is smaller (if
1150 it was actually NUL terminated, we construct a new one and throw
1151 away the result.
1152 */
1153 /* chop off at the first NUL character, if any. */
1154 p = (wchar_t*)ptr;
1155 for (len = 0; len < size; ++len) {
1156 if (!p[len])
1157 break;
1158 }
1159
1160 return PyUnicode_FromWideChar((wchar_t *)ptr, len);
1161 }
1162
1163 static PyObject *
1164 U_set(void *ptr, PyObject *value, Py_ssize_t length)
1165 {
1166 /* It's easier to calculate in characters than in bytes */
1167 length /= sizeof(wchar_t);
1168
1169 if (!PyUnicode_Check(value)) {
1170 PyErr_Format(PyExc_TypeError,
1171 "unicode string expected instead of %s instance",
1172 Py_TYPE(value)->tp_name);
1173 return NULL;
1174 }
1175
1176 Py_ssize_t size = PyUnicode_AsWideChar(value, NULL, 0);
1177 if (size < 0) {
1178 return NULL;
1179 }
1180 // PyUnicode_AsWideChar() returns number of wchars including trailing null byte,
1181 // when it is called with NULL.
1182 size--;
1183 assert(size >= 0);
1184 if (size > length) {
1185 PyErr_Format(PyExc_ValueError,
1186 "string too long (%zd, maximum length %zd)",
1187 size, length);
1188 return NULL;
1189 }
1190 if (PyUnicode_AsWideChar(value, (wchar_t *)ptr, length) == -1) {
1191 return NULL;
1192 }
1193
1194 return Py_NewRef(value);
1195 }
1196
1197
1198 /* s: a byte string */
1199 static PyObject *
1200 s_get(void *ptr, Py_ssize_t size)
1201 {
1202 Py_ssize_t i;
1203 char *p;
1204
1205 p = (char *)ptr;
1206 for (i = 0; i < size; ++i) {
1207 if (*p++ == '\0')
1208 break;
1209 }
1210
1211 return PyBytes_FromStringAndSize((char *)ptr, (Py_ssize_t)i);
1212 }
1213
1214 static PyObject *
1215 s_set(void *ptr, PyObject *value, Py_ssize_t length)
1216 {
1217 const char *data;
1218 Py_ssize_t size;
1219
1220 if(!PyBytes_Check(value)) {
1221 PyErr_Format(PyExc_TypeError,
1222 "expected bytes, %s found",
1223 Py_TYPE(value)->tp_name);
1224 return NULL;
1225 }
1226
1227 data = PyBytes_AS_STRING(value);
1228 // bpo-39593: Use strlen() to truncate the string at the first null character.
1229 size = strlen(data);
1230
1231 if (size < length) {
1232 /* This will copy the terminating NUL character
1233 * if there is space for it.
1234 */
1235 ++size;
1236 } else if (size > length) {
1237 PyErr_Format(PyExc_ValueError,
1238 "bytes too long (%zd, maximum length %zd)",
1239 size, length);
1240 return NULL;
1241 }
1242 /* Also copy the terminating NUL character if there is space */
1243 memcpy((char *)ptr, data, size);
1244
1245 _RET(value);
1246 }
1247
1248 /* z: a byte string, can be set from integer pointer */
1249 static PyObject *
1250 z_set(void *ptr, PyObject *value, Py_ssize_t size)
1251 {
1252 if (value == Py_None) {
1253 *(char **)ptr = NULL;
1254 return Py_NewRef(value);
1255 }
1256 if (PyBytes_Check(value)) {
1257 *(const char **)ptr = PyBytes_AsString(value);
1258 return Py_NewRef(value);
1259 } else if (PyLong_Check(value)) {
1260 #if SIZEOF_VOID_P == SIZEOF_LONG_LONG
1261 *(char **)ptr = (char *)PyLong_AsUnsignedLongLongMask(value);
1262 #else
1263 *(char **)ptr = (char *)PyLong_AsUnsignedLongMask(value);
1264 #endif
1265 _RET(value);
1266 }
1267 PyErr_Format(PyExc_TypeError,
1268 "bytes or integer address expected instead of %s instance",
1269 Py_TYPE(value)->tp_name);
1270 return NULL;
1271 }
1272
1273 static PyObject *
1274 z_get(void *ptr, Py_ssize_t size)
1275 {
1276 /* XXX What about invalid pointers ??? */
1277 if (*(void **)ptr) {
1278 return PyBytes_FromStringAndSize(*(char **)ptr,
1279 strlen(*(char **)ptr));
1280 } else {
1281 Py_RETURN_NONE;
1282 }
1283 }
1284
1285 /* Z: a wchar* string, can be set from integer pointer */
1286 static PyObject *
1287 Z_set(void *ptr, PyObject *value, Py_ssize_t size)
1288 {
1289 PyObject *keep;
1290 wchar_t *buffer;
1291 Py_ssize_t bsize;
1292
1293 if (value == Py_None) {
1294 *(wchar_t **)ptr = NULL;
1295 return Py_NewRef(value);
1296 }
1297 if (PyLong_Check(value)) {
1298 #if SIZEOF_VOID_P == SIZEOF_LONG_LONG
1299 *(wchar_t **)ptr = (wchar_t *)PyLong_AsUnsignedLongLongMask(value);
1300 #else
1301 *(wchar_t **)ptr = (wchar_t *)PyLong_AsUnsignedLongMask(value);
1302 #endif
1303 Py_RETURN_NONE;
1304 }
1305 if (!PyUnicode_Check(value)) {
1306 PyErr_Format(PyExc_TypeError,
1307 "unicode string or integer address expected instead of %s instance",
1308 Py_TYPE(value)->tp_name);
1309 return NULL;
1310 }
1311
1312 /* We must create a wchar_t* buffer from the unicode object,
1313 and keep it alive */
1314 buffer = PyUnicode_AsWideCharString(value, &bsize);
1315 if (!buffer)
1316 return NULL;
1317 keep = PyCapsule_New(buffer, CTYPES_CFIELD_CAPSULE_NAME_PYMEM, pymem_destructor);
1318 if (!keep) {
1319 PyMem_Free(buffer);
1320 return NULL;
1321 }
1322 *(wchar_t **)ptr = buffer;
1323 return keep;
1324 }
1325
1326 static PyObject *
1327 Z_get(void *ptr, Py_ssize_t size)
1328 {
1329 wchar_t *p;
1330 p = *(wchar_t **)ptr;
1331 if (p) {
1332 return PyUnicode_FromWideChar(p, wcslen(p));
1333 } else {
1334 Py_RETURN_NONE;
1335 }
1336 }
1337
1338
1339 #ifdef MS_WIN32
1340 /* X: COM BSTR (wide-char string to be handled handled using Windows API) */
1341 static PyObject *
1342 X_set(void *ptr, PyObject *value, Py_ssize_t size)
1343 {
1344 BSTR bstr;
1345
1346 /* convert value into a PyUnicodeObject or NULL */
1347 if (Py_None == value) {
1348 value = NULL;
1349 } else if (!PyUnicode_Check(value)) {
1350 PyErr_Format(PyExc_TypeError,
1351 "unicode string expected instead of %s instance",
1352 Py_TYPE(value)->tp_name);
1353 return NULL;
1354 }
1355
1356 /* create a BSTR from value */
1357 if (value) {
1358 Py_ssize_t wsize;
1359 wchar_t *wvalue = PyUnicode_AsWideCharString(value, &wsize);
1360 if (wvalue == NULL) {
1361 return NULL;
1362 }
1363 if ((unsigned) wsize != wsize) {
1364 PyErr_SetString(PyExc_ValueError, "String too long for BSTR");
1365 PyMem_Free(wvalue);
1366 return NULL;
1367 }
1368 bstr = SysAllocStringLen(wvalue, (unsigned)wsize);
1369 PyMem_Free(wvalue);
1370 } else
1371 bstr = NULL;
1372
1373 /* free the previous contents, if any */
1374 if (*(BSTR *)ptr)
1375 SysFreeString(*(BSTR *)ptr);
1376
1377 /* and store it */
1378 *(BSTR *)ptr = bstr;
1379
1380 /* We don't need to keep any other object */
1381 _RET(value);
1382 }
1383
1384
1385 static PyObject *
1386 X_get(void *ptr, Py_ssize_t size)
1387 {
1388 BSTR p;
1389 p = *(BSTR *)ptr;
1390 if (p)
1391 return PyUnicode_FromWideChar(p, SysStringLen(p));
1392 else {
1393 /* Hm, it seems NULL pointer and zero length string are the
1394 same in BSTR, see Don Box, p 81
1395 */
1396 Py_RETURN_NONE;
1397 }
1398 }
1399 #endif
1400
1401 /* P: generic pointer */
1402 static PyObject *
1403 P_set(void *ptr, PyObject *value, Py_ssize_t size)
1404 {
1405 assert(NUM_BITS(size) || (size == sizeof(void *)));
1406 void *v;
1407 if (value == Py_None) {
1408 *(void **)ptr = NULL;
1409 _RET(value);
1410 }
1411
1412 if (!PyLong_Check(value)) {
1413 PyErr_SetString(PyExc_TypeError,
1414 "cannot be converted to pointer");
1415 return NULL;
1416 }
1417
1418 #if SIZEOF_VOID_P <= SIZEOF_LONG
1419 v = (void *)PyLong_AsUnsignedLongMask(value);
1420 #else
1421 #if SIZEOF_LONG_LONG < SIZEOF_VOID_P
1422 # error "PyLong_AsVoidPtr: sizeof(long long) < sizeof(void*)"
1423 #endif
1424 v = (void *)PyLong_AsUnsignedLongLongMask(value);
1425 #endif
1426
1427 if (PyErr_Occurred())
1428 return NULL;
1429
1430 *(void **)ptr = v;
1431 _RET(value);
1432 }
1433
1434 static PyObject *
1435 P_get(void *ptr, Py_ssize_t size)
1436 {
1437 assert(NUM_BITS(size) || (size == sizeof(void *)));
1438 if (*(void **)ptr == NULL) {
1439 Py_RETURN_NONE;
1440 }
1441 return PyLong_FromVoidPtr(*(void **)ptr);
1442 }
1443
1444 /* Table with info about all formats.
1445 * Must be accessed via _ctypes_get_fielddesc, which initializes it on
1446 * first use. After initialization it's treated as constant & read-only.
1447 */
1448
1449 struct formattable {
1450 /*[python input]
1451 for nbytes in 8, 16, 32, 64:
1452 for sgn in 'i', 'u':
1453 print(f' struct fielddesc fmt_{sgn}{nbytes};')
1454 for code in 'sbBcdFDGgfhHiIlLqQPzuUZXvO':
1455 print(f' struct fielddesc fmt_{code};')
1456 [python start generated code]*/
1457 struct fielddesc fmt_i8;
1458 struct fielddesc fmt_u8;
1459 struct fielddesc fmt_i16;
1460 struct fielddesc fmt_u16;
1461 struct fielddesc fmt_i32;
1462 struct fielddesc fmt_u32;
1463 struct fielddesc fmt_i64;
1464 struct fielddesc fmt_u64;
1465 struct fielddesc fmt_s;
1466 struct fielddesc fmt_b;
1467 struct fielddesc fmt_B;
1468 struct fielddesc fmt_c;
1469 struct fielddesc fmt_d;
1470 struct fielddesc fmt_F;
1471 struct fielddesc fmt_D;
1472 struct fielddesc fmt_G;
1473 struct fielddesc fmt_g;
1474 struct fielddesc fmt_f;
1475 struct fielddesc fmt_h;
1476 struct fielddesc fmt_H;
1477 struct fielddesc fmt_i;
1478 struct fielddesc fmt_I;
1479 struct fielddesc fmt_l;
1480 struct fielddesc fmt_L;
1481 struct fielddesc fmt_q;
1482 struct fielddesc fmt_Q;
1483 struct fielddesc fmt_P;
1484 struct fielddesc fmt_z;
1485 struct fielddesc fmt_u;
1486 struct fielddesc fmt_U;
1487 struct fielddesc fmt_Z;
1488 struct fielddesc fmt_X;
1489 struct fielddesc fmt_v;
1490 struct fielddesc fmt_O;
1491 /*[python end generated code: output=f5a07c066fedaca6 input=ffa5d46c29dfb07a]*/
1492
1493 // bool has code '?':
1494 struct fielddesc fmt_bool;
1495
1496 // always contains NULLs:
1497 struct fielddesc fmt_nil;
1498
1499 // Result of _ctypes_get_simple_type_chars. Initialized just after
1500 // the rest of formattable, so we stash it here.
1501 char simple_type_chars[26];
1502 };
1503
1504 static struct formattable formattable;
1505
1506
1507 /* Get fielddesc info for a fixed-width integer.
1508 * N.B: - must be called after (or from) _ctypes_init_fielddesc!
1509 * - nbytes must be one of the supported values
1510 */
1511
1512 static inline struct fielddesc *
1513 _ctypes_fixint_fielddesc(Py_ssize_t nbytes, bool is_signed)
1514 {
1515 #define _PACK(NBYTES, SGN) ((NBYTES<<2) + (SGN ? 1 : 0))
1516 switch (_PACK(nbytes, is_signed)) {
1517 /*[python input]
1518 for nbytes in 8, 16, 32, 64:
1519 for sgn in 'i', 'u':
1520 is_signed = sgn == 'i'
1521 print(f' case (_PACK({nbytes // 8}, {int(is_signed)})): '
1522 + f'return &formattable.fmt_{sgn}{nbytes};')
1523 [python start generated code]*/
1524 case (_PACK(1, 1)): return &formattable.fmt_i8;
1525 case (_PACK(1, 0)): return &formattable.fmt_u8;
1526 case (_PACK(2, 1)): return &formattable.fmt_i16;
1527 case (_PACK(2, 0)): return &formattable.fmt_u16;
1528 case (_PACK(4, 1)): return &formattable.fmt_i32;
1529 case (_PACK(4, 0)): return &formattable.fmt_u32;
1530 case (_PACK(8, 1)): return &formattable.fmt_i64;
1531 case (_PACK(8, 0)): return &formattable.fmt_u64;
1532 /*[python end generated code: output=0194ba35c4d64ff3 input=ee9f6f5bb872d645]*/
1533 #undef _PACK
1534 }
1535 /* ctypes currently only supports platforms where the basic integer types
1536 * (`char`, `short`, `int`, `long`, `long long`) have 1, 2, 4, or 8 bytes
1537 * (i.e. 8 to 64 bits).
1538 */
1539 Py_UNREACHABLE();
1540 }
1541
1542
1543 /* Macro to call _ctypes_fixint_fielddesc for a given C type. */
1544
1545 _Py_COMP_DIAG_PUSH
1546 #if defined(__GNUC__) && (__GNUC__ < 14)
1547 /* The signedness check expands to an expression that's always true or false.
1548 * Older GCC gives a '-Wtype-limits' warning for this, which is a GCC bug
1549 * (docs say it should "not warn for constant expressions"):
1550 * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=86647
1551 * Silence that warning.
1552 */
1553 #pragma GCC diagnostic ignored "-Wtype-limits"
1554 #endif
1555
1556 #define FIXINT_FIELDDESC_FOR(C_TYPE) \
1557 _ctypes_fixint_fielddesc(sizeof(C_TYPE), (C_TYPE)-1 < 0)
1558
1559
1560 /* Delayed initialization. Windows cannot statically reference dynamically
1561 loaded addresses from DLLs. */
1562 void
1563 _ctypes_init_fielddesc(void)
1564 {
1565 /* Fixed-width integers */
1566
1567 /*[python input]
1568 for nbytes in 8, 16, 32, 64:
1569 for sgn in 'i', 'u':
1570 is_signed = sgn == 'i'
1571 u = 'u' if sgn == 'u' else 's'
1572 parts = [
1573 f"0",
1574 f'&ffi_type_{u}int{nbytes}',
1575 f'{sgn}{nbytes}_set',
1576 f'{sgn}{nbytes}_get',
1577 f'{sgn}{nbytes}_set_sw',
1578 f'{sgn}{nbytes}_get_sw',
1579 ]
1580 print(f' formattable.fmt_{sgn}{nbytes} = (struct fielddesc){{')
1581 print(f' {", ".join(parts)} }};')
1582 [python start generated code]*/
1583 formattable.fmt_i8 = (struct fielddesc){
1584 0, &ffi_type_sint8, i8_set, i8_get, i8_set_sw, i8_get_sw };
1585 formattable.fmt_u8 = (struct fielddesc){
1586 0, &ffi_type_uint8, u8_set, u8_get, u8_set_sw, u8_get_sw };
1587 formattable.fmt_i16 = (struct fielddesc){
1588 0, &ffi_type_sint16, i16_set, i16_get, i16_set_sw, i16_get_sw };
1589 formattable.fmt_u16 = (struct fielddesc){
1590 0, &ffi_type_uint16, u16_set, u16_get, u16_set_sw, u16_get_sw };
1591 formattable.fmt_i32 = (struct fielddesc){
1592 0, &ffi_type_sint32, i32_set, i32_get, i32_set_sw, i32_get_sw };
1593 formattable.fmt_u32 = (struct fielddesc){
1594 0, &ffi_type_uint32, u32_set, u32_get, u32_set_sw, u32_get_sw };
1595 formattable.fmt_i64 = (struct fielddesc){
1596 0, &ffi_type_sint64, i64_set, i64_get, i64_set_sw, i64_get_sw };
1597 formattable.fmt_u64 = (struct fielddesc){
1598 0, &ffi_type_uint64, u64_set, u64_get, u64_set_sw, u64_get_sw };
1599 /*[python end generated code: output=16806fe0ca3a9c4c input=96348a06e575f801]*/
1600
1601
1602 /* Native C integers.
1603 * These use getters/setters for fixed-width ints but have their own
1604 * `code` and `pffi_type`.
1605 */
1606
1607 /*[python input]
1608 for base_code, base_c_type in [
1609 ('b', 'char'),
1610 ('h', 'short'),
1611 ('i', 'int'),
1612 ('l', 'long'),
1613 ('q', 'long long'),
1614 ]:
1615 for code, c_type, ffi_type in [
1616 (base_code, 'signed ' + base_c_type, 's' + base_c_type),
1617 (base_code.upper(), 'unsigned ' + base_c_type, 'u' + base_c_type),
1618 ]:
1619 print(f' formattable.fmt_{code} = *FIXINT_FIELDDESC_FOR({c_type});')
1620 print(f" formattable.fmt_{code}.code = '{code}';")
1621 if base_code == 'q':
1622 # ffi doesn't have `long long`; keep use the fixint type
1623 pass
1624 else:
1625 print(f' formattable.fmt_{code}.pffi_type = &ffi_type_{ffi_type};')
1626 [python start generated code]*/
1627 formattable.fmt_b = *FIXINT_FIELDDESC_FOR(signed char);
1628 formattable.fmt_b.code = 'b';
1629 formattable.fmt_b.pffi_type = &ffi_type_schar;
1630 formattable.fmt_B = *FIXINT_FIELDDESC_FOR(unsigned char);
1631 formattable.fmt_B.code = 'B';
1632 formattable.fmt_B.pffi_type = &ffi_type_uchar;
1633 formattable.fmt_h = *FIXINT_FIELDDESC_FOR(signed short);
1634 formattable.fmt_h.code = 'h';
1635 formattable.fmt_h.pffi_type = &ffi_type_sshort;
1636 formattable.fmt_H = *FIXINT_FIELDDESC_FOR(unsigned short);
1637 formattable.fmt_H.code = 'H';
1638 formattable.fmt_H.pffi_type = &ffi_type_ushort;
1639 formattable.fmt_i = *FIXINT_FIELDDESC_FOR(signed int);
1640 formattable.fmt_i.code = 'i';
1641 formattable.fmt_i.pffi_type = &ffi_type_sint;
1642 formattable.fmt_I = *FIXINT_FIELDDESC_FOR(unsigned int);
1643 formattable.fmt_I.code = 'I';
1644 formattable.fmt_I.pffi_type = &ffi_type_uint;
1645 formattable.fmt_l = *FIXINT_FIELDDESC_FOR(signed long);
1646 formattable.fmt_l.code = 'l';
1647 formattable.fmt_l.pffi_type = &ffi_type_slong;
1648 formattable.fmt_L = *FIXINT_FIELDDESC_FOR(unsigned long);
1649 formattable.fmt_L.code = 'L';
1650 formattable.fmt_L.pffi_type = &ffi_type_ulong;
1651 formattable.fmt_q = *FIXINT_FIELDDESC_FOR(signed long long);
1652 formattable.fmt_q.code = 'q';
1653 formattable.fmt_Q = *FIXINT_FIELDDESC_FOR(unsigned long long);
1654 formattable.fmt_Q.code = 'Q';
1655 /*[python end generated code: output=873c87a2e6b5075a input=ee814ca263aac18e]*/
1656
1657
1658 /* Other types have bespoke setters and getters named `@_set` and `@_get`,
1659 * where `@` is the type code.
1660 * Some have swapped variants, `@_set_sw` and `@_get_sw`
1661 */
1662
1663 #define _TABLE_ENTRY(SYMBOL, FFI_TYPE, ...) \
1664 formattable.fmt_ ## SYMBOL = \
1665 (struct fielddesc){(#SYMBOL)[0], (FFI_TYPE), __VA_ARGS__}; \
1666 ///////////////////////////////////////////////////////////////////////////
1667
1668 #define TABLE_ENTRY(SYMBOL, FFI_TYPE) \
1669 _TABLE_ENTRY(SYMBOL, FFI_TYPE, SYMBOL ## _set, SYMBOL ## _get) \
1670 ///////////////////////////////////////////////////////////////////////////
1671
1672 #define TABLE_ENTRY_SW(SYMBOL, FFI_TYPE) \
1673 _TABLE_ENTRY(SYMBOL, FFI_TYPE, SYMBOL ## _set, \
1674 SYMBOL ## _get, SYMBOL ## _set_sw, SYMBOL ## _get_sw) \
1675 ///////////////////////////////////////////////////////////////////////////
1676
1677 TABLE_ENTRY_SW(d, &ffi_type_double);
1678 #if defined(_Py_FFI_SUPPORT_C_COMPLEX)
1679 if (Py_FFI_COMPLEX_AVAILABLE) {
1680 TABLE_ENTRY(D, &ffi_type_complex_double);
1681 TABLE_ENTRY_SW(D, &ffi_type_complex_double);
1682 TABLE_ENTRY(F, &ffi_type_complex_float);
1683 TABLE_ENTRY_SW(F, &ffi_type_complex_float);
1684 TABLE_ENTRY(G, &ffi_type_complex_longdouble);
1685 }
1686 #endif
1687 TABLE_ENTRY(g, &ffi_type_longdouble);
1688 TABLE_ENTRY_SW(f, &ffi_type_float);
1689 TABLE_ENTRY(v, &ffi_type_sshort); /* vBOOL */
1690
1691 // ctypes.c_char is signed for FFI, even where C wchar_t is unsigned.
1692 TABLE_ENTRY(c, _ctypes_fixint_fielddesc(sizeof(char), true)->pffi_type);
1693 // ctypes.c_wchar is signed for FFI, even where C wchar_t is unsigned.
1694 TABLE_ENTRY(u, _ctypes_fixint_fielddesc(sizeof(wchar_t), true)->pffi_type);
1695
1696 TABLE_ENTRY(s, &ffi_type_pointer);
1697 TABLE_ENTRY(P, &ffi_type_pointer);
1698 TABLE_ENTRY(z, &ffi_type_pointer);
1699 TABLE_ENTRY(U, &ffi_type_pointer);
1700 TABLE_ENTRY(Z, &ffi_type_pointer);
1701 #ifdef MS_WIN32
1702 TABLE_ENTRY(X, &ffi_type_pointer);
1703 #endif
1704 TABLE_ENTRY(O, &ffi_type_pointer);
1705
1706 #undef TABLE_ENTRY_SW
1707 #undef TABLE_ENTRY
1708 #undef _TABLE_ENTRY
1709
1710 /* bool has code '?', fill it in manually */
1711
1712 // ctypes.c_bool is unsigned for FFI, even where C bool is signed.
1713 formattable.fmt_bool = *_ctypes_fixint_fielddesc(sizeof(bool), false);
1714 formattable.fmt_bool.code = '?';
1715 formattable.fmt_bool.setfunc = bool_set;
1716 formattable.fmt_bool.getfunc = bool_get;
1717
1718 /*[python input]
1719 all_chars = "cbBhHiIlLdDFGfuzZqQPXOv?g"
1720 print(f' assert(sizeof(formattable.simple_type_chars) == {len(all_chars)+1});')
1721 print(f' int i = 0;')
1722 for char in all_chars:
1723 ident_char = {'?': 'bool'}.get(char, char)
1724 print(f" if (formattable.fmt_{ident_char}.code) "
1725 + f"formattable.simple_type_chars[i++] = '{char}';")
1726 print(f" formattable.simple_type_chars[i] = 0;")
1727 [python start generated code]*/
1728 assert(sizeof(formattable.simple_type_chars) == 26);
1729 int i = 0;
1730 if (formattable.fmt_c.code) formattable.simple_type_chars[i++] = 'c';
1731 if (formattable.fmt_b.code) formattable.simple_type_chars[i++] = 'b';
1732 if (formattable.fmt_B.code) formattable.simple_type_chars[i++] = 'B';
1733 if (formattable.fmt_h.code) formattable.simple_type_chars[i++] = 'h';
1734 if (formattable.fmt_H.code) formattable.simple_type_chars[i++] = 'H';
1735 if (formattable.fmt_i.code) formattable.simple_type_chars[i++] = 'i';
1736 if (formattable.fmt_I.code) formattable.simple_type_chars[i++] = 'I';
1737 if (formattable.fmt_l.code) formattable.simple_type_chars[i++] = 'l';
1738 if (formattable.fmt_L.code) formattable.simple_type_chars[i++] = 'L';
1739 if (formattable.fmt_d.code) formattable.simple_type_chars[i++] = 'd';
1740 if (formattable.fmt_D.code) formattable.simple_type_chars[i++] = 'D';
1741 if (formattable.fmt_F.code) formattable.simple_type_chars[i++] = 'F';
1742 if (formattable.fmt_G.code) formattable.simple_type_chars[i++] = 'G';
1743 if (formattable.fmt_f.code) formattable.simple_type_chars[i++] = 'f';
1744 if (formattable.fmt_u.code) formattable.simple_type_chars[i++] = 'u';
1745 if (formattable.fmt_z.code) formattable.simple_type_chars[i++] = 'z';
1746 if (formattable.fmt_Z.code) formattable.simple_type_chars[i++] = 'Z';
1747 if (formattable.fmt_q.code) formattable.simple_type_chars[i++] = 'q';
1748 if (formattable.fmt_Q.code) formattable.simple_type_chars[i++] = 'Q';
1749 if (formattable.fmt_P.code) formattable.simple_type_chars[i++] = 'P';
1750 if (formattable.fmt_X.code) formattable.simple_type_chars[i++] = 'X';
1751 if (formattable.fmt_O.code) formattable.simple_type_chars[i++] = 'O';
1752 if (formattable.fmt_v.code) formattable.simple_type_chars[i++] = 'v';
1753 if (formattable.fmt_bool.code) formattable.simple_type_chars[i++] = '?';
1754 if (formattable.fmt_g.code) formattable.simple_type_chars[i++] = 'g';
1755 formattable.simple_type_chars[i] = 0;
1756 /*[python end generated code: output=2aa52670d1570f18 input=cff3e7cb95adac61]*/
1757
1758 }
1759 #undef FIXINT_FIELDDESC_FOR
1760 _Py_COMP_DIAG_POP
1761
1762 char *
1763 _ctypes_get_simple_type_chars(void) {
1764 return formattable.simple_type_chars;
1765 }
1766
1767 struct fielddesc *
1768 _ctypes_get_fielddesc(const char *fmt)
1769 {
1770 struct fielddesc *result = NULL;
1771 switch(fmt[0]) {
1772 /*[python input]
1773 for code in 'sbBcdDFGgfhHiIlLqQPzuUZXvO':
1774 print(f" case '{code}': result = &formattable.fmt_{code}; break;")
1775 [python start generated code]*/
1776 case 's': result = &formattable.fmt_s; break;
1777 case 'b': result = &formattable.fmt_b; break;
1778 case 'B': result = &formattable.fmt_B; break;
1779 case 'c': result = &formattable.fmt_c; break;
1780 case 'd': result = &formattable.fmt_d; break;
1781 case 'D': result = &formattable.fmt_D; break;
1782 case 'F': result = &formattable.fmt_F; break;
1783 case 'G': result = &formattable.fmt_G; break;
1784 case 'g': result = &formattable.fmt_g; break;
1785 case 'f': result = &formattable.fmt_f; break;
1786 case 'h': result = &formattable.fmt_h; break;
1787 case 'H': result = &formattable.fmt_H; break;
1788 case 'i': result = &formattable.fmt_i; break;
1789 case 'I': result = &formattable.fmt_I; break;
1790 case 'l': result = &formattable.fmt_l; break;
1791 case 'L': result = &formattable.fmt_L; break;
1792 case 'q': result = &formattable.fmt_q; break;
1793 case 'Q': result = &formattable.fmt_Q; break;
1794 case 'P': result = &formattable.fmt_P; break;
1795 case 'z': result = &formattable.fmt_z; break;
1796 case 'u': result = &formattable.fmt_u; break;
1797 case 'U': result = &formattable.fmt_U; break;
1798 case 'Z': result = &formattable.fmt_Z; break;
1799 case 'X': result = &formattable.fmt_X; break;
1800 case 'v': result = &formattable.fmt_v; break;
1801 case 'O': result = &formattable.fmt_O; break;
1802 /*[python end generated code: output=6e5c91940732fde9 input=902223feffc2fe38]*/
1803 case '?': result = &formattable.fmt_bool; break;
1804 }
1805 if (!result || !result->code) {
1806 return NULL;
1807 }
1808 assert(result->pffi_type);
1809 assert(result->setfunc);
1810 assert(result->getfunc);
1811 return result;
1812 }
1813
1814 /*
1815 Ideas: Implement VARIANT in this table, using 'V' code.
1816 */
1817
1818 /*---------------- EOF ----------------*/