Debian Codegraph @

Modules/_ctypes/stgdict.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_call.h" // _PyObject_CallNoArgs()
12 #include "pycore_dict.h" // _PyDict_SizeOf()
13 #include <ffi.h>
14 #ifdef MS_WIN32
15 # include <malloc.h>
16 #endif
17 #include "ctypes.h"
18
19 /* This file relates to StgInfo -- type-specific information for ctypes.
20 * See ctypes.h for details.
21 */
22
23 int
24 PyCStgInfo_clone(StgInfo *dst_info, StgInfo *src_info)
25 {
26 Py_ssize_t size;
27
28 ctype_clear_stginfo(dst_info);
29 PyMem_Free(dst_info->ffi_type_pointer.elements);
30 PyMem_Free(dst_info->format);
31 dst_info->format = NULL;
32 PyMem_Free(dst_info->shape);
33 dst_info->shape = NULL;
34 dst_info->ffi_type_pointer.elements = NULL;
35
36 memcpy(dst_info, src_info, sizeof(StgInfo));
37
38 Py_XINCREF(dst_info->proto);
39 Py_XINCREF(dst_info->argtypes);
40 Py_XINCREF(dst_info->converters);
41 Py_XINCREF(dst_info->restype);
42 Py_XINCREF(dst_info->checker);
43 Py_XINCREF(dst_info->module);
44
45 if (src_info->format) {
46 dst_info->format = PyMem_Malloc(strlen(src_info->format) + 1);
47 if (dst_info->format == NULL) {
48 PyErr_NoMemory();
49 return -1;
50 }
51 strcpy(dst_info->format, src_info->format);
52 }
53 if (src_info->shape) {
54 dst_info->shape = PyMem_Malloc(sizeof(Py_ssize_t) * src_info->ndim);
55 if (dst_info->shape == NULL) {
56 PyErr_NoMemory();
57 return -1;
58 }
59 memcpy(dst_info->shape, src_info->shape,
60 sizeof(Py_ssize_t) * src_info->ndim);
61 }
62
63 if (src_info->ffi_type_pointer.elements == NULL)
64 return 0;
65 size = sizeof(ffi_type *) * (src_info->length + 1);
66 dst_info->ffi_type_pointer.elements = PyMem_Malloc(size);
67 if (dst_info->ffi_type_pointer.elements == NULL) {
68 PyErr_NoMemory();
69 return -1;
70 }
71 memcpy(dst_info->ffi_type_pointer.elements,
72 src_info->ffi_type_pointer.elements,
73 size);
74 return 0;
75 }
76
77 /* descr is the descriptor for a field marked as anonymous. Get all the
78 _fields_ descriptors from descr->proto, create new descriptors with offset
79 and index adjusted, and stuff them into type.
80 */
81 static int
82 MakeFields(PyObject *type, CFieldObject *descr,
83 Py_ssize_t index, Py_ssize_t offset)
84 {
85 Py_ssize_t i;
86 PyObject *fields;
87 PyObject *fieldlist;
88
89 fields = PyObject_GetAttrString(descr->proto, "_fields_");
90 if (fields == NULL)
91 return -1;
92 fieldlist = PySequence_Fast(fields, "_fields_ must be a sequence");
93 Py_DECREF(fields);
94 if (fieldlist == NULL)
95 return -1;
96
97 ctypes_state *st = get_module_state_by_class(Py_TYPE(descr));
98 PyTypeObject *cfield_tp = st->PyCField_Type;
99 for (i = 0; i < PySequence_Fast_GET_SIZE(fieldlist); ++i) {
100 PyObject *pair = PySequence_Fast_GET_ITEM(fieldlist, i); /* borrowed */
101 PyObject *fname, *ftype, *bits;
102 CFieldObject *fdescr;
103 CFieldObject *new_descr;
104 /* Convert to PyArg_UnpackTuple... */
105 if (!PyArg_ParseTuple(pair, "OO|O", &fname, &ftype, &bits)) {
106 Py_DECREF(fieldlist);
107 return -1;
108 }
109 fdescr = (CFieldObject *)PyObject_GetAttr(descr->proto, fname);
110 if (fdescr == NULL) {
111 Py_DECREF(fieldlist);
112 return -1;
113 }
114 if (!Py_IS_TYPE(fdescr, cfield_tp)) {
115 PyErr_SetString(PyExc_TypeError, "unexpected type");
116 Py_DECREF(fdescr);
117 Py_DECREF(fieldlist);
118 return -1;
119 }
120 if (fdescr->anonymous) {
121 int rc = MakeFields(type, fdescr,
122 index + fdescr->index,
123 offset + fdescr->offset);
124 Py_DECREF(fdescr);
125 if (rc == -1) {
126 Py_DECREF(fieldlist);
127 return -1;
128 }
129 continue;
130 }
131 new_descr = (CFieldObject *)cfield_tp->tp_alloc(cfield_tp, 0);
132 if (new_descr == NULL) {
133 Py_DECREF(fdescr);
134 Py_DECREF(fieldlist);
135 return -1;
136 }
137 assert(Py_IS_TYPE(new_descr, cfield_tp));
138 new_descr->size = fdescr->size;
139 new_descr->offset = fdescr->offset + offset;
140 new_descr->index = fdescr->index + index;
141 new_descr->proto = Py_XNewRef(fdescr->proto);
142 new_descr->getfunc = fdescr->getfunc;
143 new_descr->setfunc = fdescr->setfunc;
144
145 Py_DECREF(fdescr);
146
147 if (-1 == PyObject_SetAttr(type, fname, (PyObject *)new_descr)) {
148 Py_DECREF(fieldlist);
149 Py_DECREF(new_descr);
150 return -1;
151 }
152 Py_DECREF(new_descr);
153 }
154 Py_DECREF(fieldlist);
155 return 0;
156 }
157
158 /* Iterate over the names in the type's _anonymous_ attribute, if present,
159 */
160 static int
161 MakeAnonFields(PyObject *type)
162 {
163 PyObject *anon;
164 PyObject *anon_names;
165 Py_ssize_t i;
166
167 if (PyObject_GetOptionalAttr(type, &_Py_ID(_anonymous_), &anon) < 0) {
168 return -1;
169 }
170 if (anon == NULL) {
171 return 0;
172 }
173 anon_names = PySequence_Fast(anon, "_anonymous_ must be a sequence");
174 Py_DECREF(anon);
175 if (anon_names == NULL)
176 return -1;
177
178 ctypes_state *st = get_module_state_by_def(Py_TYPE(type));
179 PyTypeObject *cfield_tp = st->PyCField_Type;
180 for (i = 0; i < PySequence_Fast_GET_SIZE(anon_names); ++i) {
181 PyObject *fname = PySequence_Fast_GET_ITEM(anon_names, i); /* borrowed */
182 CFieldObject *descr = (CFieldObject *)PyObject_GetAttr(type, fname);
183 if (descr == NULL) {
184 Py_DECREF(anon_names);
185 return -1;
186 }
187 if (!Py_IS_TYPE(descr, cfield_tp)) {
188 PyErr_Format(PyExc_AttributeError,
189 "'%U' is specified in _anonymous_ but not in "
190 "_fields_",
191 fname);
192 Py_DECREF(anon_names);
193 Py_DECREF(descr);
194 return -1;
195 }
196 descr->anonymous = 1;
197
198 /* descr is in the field descriptor. */
199 if (-1 == MakeFields(type, (CFieldObject *)descr,
200 ((CFieldObject *)descr)->index,
201 ((CFieldObject *)descr)->offset)) {
202 Py_DECREF(descr);
203 Py_DECREF(anon_names);
204 return -1;
205 }
206 Py_DECREF(descr);
207 }
208
209 Py_DECREF(anon_names);
210 return 0;
211 }
212
213 /*
214 Allocate a memory block for a pep3118 format string, copy prefix (if
215 non-null) into it and append `{padding}x` to the end.
216 Returns NULL on failure, with the error indicator set.
217 */
218 char *
219 _ctypes_alloc_format_padding(const char *prefix, Py_ssize_t padding)
220 {
221 /* int64 decimal characters + x + null */
222 char buf[19 + 1 + 1];
223
224 assert(padding > 0);
225
226 if (padding == 1) {
227 /* Use x instead of 1x, for brevity */
228 return _ctypes_alloc_format_string(prefix, "x");
229 }
230
231 int ret = PyOS_snprintf(buf, sizeof(buf), "%zdx", padding); (void)ret;
232 assert(0 <= ret && ret < (Py_ssize_t)sizeof(buf));
233 return _ctypes_alloc_format_string(prefix, buf);
234 }
235
236 /*
237 Retrieve the (optional) _pack_ attribute from a type, the _fields_ attribute,
238 and initialize StgInfo. Used for Structure and Union subclasses.
239 */
240 int
241 PyCStructUnionType_update_stginfo(PyObject *type, PyObject *fields, int isStruct)
242 {
243 Py_ssize_t len, offset, size, align, i;
244 Py_ssize_t union_size, total_align, aligned_size;
245 Py_ssize_t field_size = 0;
246 int bitofs;
247 PyObject *tmp;
248 int pack;
249 int forced_alignment = 1;
250 Py_ssize_t ffi_ofs;
251 int big_endian;
252 int arrays_seen = 0;
253
254 if (fields == NULL)
255 return 0;
256
257 int rc = PyObject_HasAttrWithError(type, &_Py_ID(_swappedbytes_));
258 if (rc < 0) {
259 return -1;
260 }
261 if (rc) {
262 big_endian = !PY_BIG_ENDIAN;
263 }
264 else {
265 big_endian = PY_BIG_ENDIAN;
266 }
267
268 if (PyObject_GetOptionalAttr(type, &_Py_ID(_pack_), &tmp) < 0) {
269 return -1;
270 }
271 if (tmp) {
272 pack = PyLong_AsInt(tmp);
273 Py_DECREF(tmp);
274 if (pack < 0) {
275 if (!PyErr_Occurred() ||
276 PyErr_ExceptionMatches(PyExc_TypeError) ||
277 PyErr_ExceptionMatches(PyExc_OverflowError))
278 {
279 PyErr_SetString(PyExc_ValueError,
280 "_pack_ must be a non-negative integer");
281 }
282 return -1;
283 }
284 }
285 else {
286 /* Setting `_pack_ = 0` amounts to using the default alignment */
287 pack = 0;
288 }
289
290 if (PyObject_GetOptionalAttr(type, &_Py_ID(_align_), &tmp) < 0) {
291 return -1;
292 }
293 if (tmp) {
294 forced_alignment = PyLong_AsInt(tmp);
295 Py_DECREF(tmp);
296 if (forced_alignment < 0) {
297 if (!PyErr_Occurred() ||
298 PyErr_ExceptionMatches(PyExc_TypeError) ||
299 PyErr_ExceptionMatches(PyExc_OverflowError))
300 {
301 PyErr_SetString(PyExc_ValueError,
302 "_align_ must be a non-negative integer");
303 }
304 return -1;
305 }
306 }
307 else {
308 /* Setting `_align_ = 0` amounts to using the default alignment */
309 forced_alignment = 1;
310 }
311
312 len = PySequence_Size(fields);
313 if (len == -1) {
314 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
315 PyErr_SetString(PyExc_TypeError,
316 "'_fields_' must be a sequence of pairs");
317 }
318 return -1;
319 }
320
321 ctypes_state *st = get_module_state_by_def(Py_TYPE(type));
322 StgInfo *stginfo;
323 if (PyStgInfo_FromType(st, type, &stginfo) < 0) {
324 return -1;
325 }
326 if (!stginfo) {
327 PyErr_SetString(PyExc_TypeError,
328 "ctypes state is not initialized");
329 return -1;
330 }
331
332 /* If this structure/union is already marked final we cannot assign
333 _fields_ anymore. */
334
335 if (stginfo->flags & DICTFLAG_FINAL) {/* is final ? */
336 PyErr_SetString(PyExc_AttributeError,
337 "_fields_ is final");
338 return -1;
339 }
340
341 if (stginfo->format) {
342 PyMem_Free(stginfo->format);
343 stginfo->format = NULL;
344 }
345
346 if (stginfo->ffi_type_pointer.elements)
347 PyMem_Free(stginfo->ffi_type_pointer.elements);
348
349 StgInfo *baseinfo;
350 if (PyStgInfo_FromType(st, (PyObject *)((PyTypeObject *)type)->tp_base,
351 &baseinfo) < 0) {
352 return -1;
353 }
354 if (baseinfo) {
355 stginfo->flags |= (baseinfo->flags &
356 (TYPEFLAG_HASUNION | TYPEFLAG_HASBITFIELD));
357 }
358 if (!isStruct) {
359 stginfo->flags |= TYPEFLAG_HASUNION;
360 }
361 if (baseinfo) {
362 size = offset = baseinfo->size;
363 align = baseinfo->align;
364 union_size = 0;
365 total_align = align ? align : 1;
366 total_align = max(total_align, forced_alignment);
367 stginfo->ffi_type_pointer.type = FFI_TYPE_STRUCT;
368 stginfo->ffi_type_pointer.elements = PyMem_New(ffi_type *, baseinfo->length + len + 1);
369 if (stginfo->ffi_type_pointer.elements == NULL) {
370 PyErr_NoMemory();
371 return -1;
372 }
373 memset(stginfo->ffi_type_pointer.elements, 0,
374 sizeof(ffi_type *) * (baseinfo->length + len + 1));
375 if (baseinfo->length > 0) {
376 memcpy(stginfo->ffi_type_pointer.elements,
377 baseinfo->ffi_type_pointer.elements,
378 sizeof(ffi_type *) * (baseinfo->length));
379 }
380 ffi_ofs = baseinfo->length;
381 } else {
382 offset = 0;
383 size = 0;
384 align = 0;
385 union_size = 0;
386 total_align = forced_alignment == 0 ? 1 : forced_alignment;
387 stginfo->ffi_type_pointer.type = FFI_TYPE_STRUCT;
388 stginfo->ffi_type_pointer.elements = PyMem_New(ffi_type *, len + 1);
389 if (stginfo->ffi_type_pointer.elements == NULL) {
390 PyErr_NoMemory();
391 return -1;
392 }
393 memset(stginfo->ffi_type_pointer.elements, 0,
394 sizeof(ffi_type *) * (len + 1));
395 ffi_ofs = 0;
396 }
397
398 assert(stginfo->format == NULL);
399 if (isStruct) {
400 stginfo->format = _ctypes_alloc_format_string(NULL, "T{");
401 } else {
402 /* PEP3118 doesn't support union. Use 'B' for bytes. */
403 stginfo->format = _ctypes_alloc_format_string(NULL, "B");
404 }
405 if (stginfo->format == NULL)
406 return -1;
407
408 for (i = 0; i < len; ++i) {
409 PyObject *name = NULL, *desc = NULL;
410 PyObject *pair = PySequence_GetItem(fields, i);
411 PyObject *prop;
412 int bitsize = 0;
413
414 if (!pair || !PyArg_ParseTuple(pair, "UO|i", &name, &desc, &bitsize)) {
415 PyErr_SetString(PyExc_TypeError,
416 "'_fields_' must be a sequence of (name, C type) pairs");
417 Py_XDECREF(pair);
418 return -1;
419 }
420 if (PyCArrayTypeObject_Check(st, desc)) {
421 arrays_seen = 1;
422 }
423
424 StgInfo *info;
425 if (PyStgInfo_FromType(st, desc, &info) < 0) {
426 Py_DECREF(pair);
427 return -1;
428 }
429 if (info == NULL) {
430 Py_DECREF(pair);
431 PyErr_Format(PyExc_TypeError,
432 "second item in _fields_ tuple (index %zd) must be a C type",
433 i);
434 return -1;
435 }
436
437 stginfo->ffi_type_pointer.elements[ffi_ofs + i] = &info->ffi_type_pointer;
438 if (info->flags & (TYPEFLAG_ISPOINTER | TYPEFLAG_HASPOINTER))
439 stginfo->flags |= TYPEFLAG_HASPOINTER;
440 stginfo->flags |= info->flags & (TYPEFLAG_HASUNION | TYPEFLAG_HASBITFIELD);
441 info->flags |= DICTFLAG_FINAL; /* mark field type final */
442 if (PyTuple_Size(pair) == 3) { /* bits specified */
443 stginfo->flags |= TYPEFLAG_HASBITFIELD;
444 switch(info->ffi_type_pointer.type) {
445 case FFI_TYPE_UINT8:
446 case FFI_TYPE_UINT16:
447 case FFI_TYPE_UINT32:
448 case FFI_TYPE_SINT64:
449 case FFI_TYPE_UINT64:
450 break;
451
452 case FFI_TYPE_SINT8:
453 case FFI_TYPE_SINT16:
454 case FFI_TYPE_SINT32:
455 if (info->getfunc != _ctypes_get_fielddesc("c")->getfunc
456 && info->getfunc != _ctypes_get_fielddesc("u")->getfunc
457 )
458 break;
459 /* else fall through */
460 default:
461 PyErr_Format(PyExc_TypeError,
462 "bit fields not allowed for type %s",
463 ((PyTypeObject *)desc)->tp_name);
464 Py_DECREF(pair);
465 return -1;
466 }
467 if (bitsize <= 0 || bitsize > info->size * 8) {
468 PyErr_SetString(PyExc_ValueError,
469 "number of bits invalid for bit field");
470 Py_DECREF(pair);
471 return -1;
472 }
473 } else
474 bitsize = 0;
475
476 if (isStruct) {
477 const char *fieldfmt = info->format ? info->format : "B";
478 const char *fieldname = PyUnicode_AsUTF8(name);
479 char *ptr;
480 Py_ssize_t len;
481 char *buf;
482 Py_ssize_t last_size = size;
483 Py_ssize_t padding;
484
485 if (fieldname == NULL)
486 {
487 Py_DECREF(pair);
488 return -1;
489 }
490
491 /* construct the field now, as `prop->offset` is `offset` with
492 corrected alignment */
493 prop = PyCField_FromDesc(st, desc, i,
494 &field_size, bitsize, &bitofs,
495 &size, &offset, &align,
496 pack, big_endian);
497 if (prop == NULL) {
498 Py_DECREF(pair);
499 return -1;
500 }
501
502 /* number of bytes between the end of the last field and the start
503 of this one */
504 padding = ((CFieldObject *)prop)->offset - last_size;
505
506 if (padding > 0) {
507 ptr = stginfo->format;
508 stginfo->format = _ctypes_alloc_format_padding(ptr, padding);
509 PyMem_Free(ptr);
510 if (stginfo->format == NULL) {
511 Py_DECREF(pair);
512 Py_DECREF(prop);
513 return -1;
514 }
515 }
516
517 len = strlen(fieldname) + strlen(fieldfmt);
518
519 buf = PyMem_Malloc(len + 2 + 1);
520 if (buf == NULL) {
521 Py_DECREF(pair);
522 Py_DECREF(prop);
523 PyErr_NoMemory();
524 return -1;
525 }
526 sprintf(buf, "%s:%s:", fieldfmt, fieldname);
527
528 ptr = stginfo->format;
529 if (info->shape != NULL) {
530 stginfo->format = _ctypes_alloc_format_string_with_shape(
531 info->ndim, info->shape, stginfo->format, buf);
532 } else {
533 stginfo->format = _ctypes_alloc_format_string(stginfo->format, buf);
534 }
535 PyMem_Free(ptr);
536 PyMem_Free(buf);
537
538 if (stginfo->format == NULL) {
539 Py_DECREF(pair);
540 Py_DECREF(prop);
541 return -1;
542 }
543 } else /* union */ {
544 size = 0;
545 offset = 0;
546 align = 0;
547 prop = PyCField_FromDesc(st, desc, i,
548 &field_size, bitsize, &bitofs,
549 &size, &offset, &align,
550 pack, big_endian);
551 if (prop == NULL) {
552 Py_DECREF(pair);
553 return -1;
554 }
555 union_size = max(size, union_size);
556 }
557 total_align = max(align, total_align);
558
559 if (-1 == PyObject_SetAttr(type, name, prop)) {
560 Py_DECREF(prop);
561 Py_DECREF(pair);
562 return -1;
563 }
564 Py_DECREF(pair);
565 Py_DECREF(prop);
566 }
567
568 if (!isStruct) {
569 size = union_size;
570 }
571
572 /* Adjust the size according to the alignment requirements */
573 assert(total_align != 0);
574 aligned_size = ((size + total_align - 1) / total_align) * total_align;
575
576 if (isStruct) {
577 char *ptr;
578 Py_ssize_t padding;
579
580 /* Pad up to the full size of the struct */
581 padding = aligned_size - size;
582 if (padding > 0) {
583 ptr = stginfo->format;
584 stginfo->format = _ctypes_alloc_format_padding(ptr, padding);
585 PyMem_Free(ptr);
586 if (stginfo->format == NULL) {
587 return -1;
588 }
589 }
590
591 ptr = stginfo->format;
592 stginfo->format = _ctypes_alloc_format_string(stginfo->format, "}");
593 PyMem_Free(ptr);
594 if (stginfo->format == NULL)
595 return -1;
596 }
597
598 stginfo->ffi_type_pointer.alignment = Py_SAFE_DOWNCAST(total_align,
599 Py_ssize_t,
600 unsigned short);
601 stginfo->ffi_type_pointer.size = aligned_size;
602
603 stginfo->size = aligned_size;
604 stginfo->align = total_align;
605 stginfo->length = ffi_ofs + len;
606
607 /*
608 * The value of MAX_STRUCT_SIZE depends on the platform Python is running on.
609 */
610 #if defined(__aarch64__) || defined(__arm__) || defined(_M_ARM64)
611 # define MAX_STRUCT_SIZE 32
612 #elif defined(__powerpc64__)
613 # define MAX_STRUCT_SIZE 64
614 #else
615 # define MAX_STRUCT_SIZE 16
616 #endif
617
618 if (arrays_seen && (size <= MAX_STRUCT_SIZE)) {
619 /*
620 * See bpo-22273 and gh-110190. Arrays are normally treated as
621 * pointers, which is fine when an array name is being passed as
622 * parameter, but not when passing structures by value that contain
623 * arrays.
624 * Small structures passed by value are passed in registers, and in
625 * order to do this, libffi needs to know the true type of the array
626 * members of structs. Treating them as pointers breaks things.
627 *
628 * Small structures have different sizes depending on the platform
629 * where Python is running on:
630 *
631 * * x86-64: 16 bytes or less
632 * * Arm platforms (both 32 and 64 bit): 32 bytes or less
633 * * PowerPC 64 Little Endian: 64 bytes or less
634 *
635 * In that case, there can't be more than 16, 32 or 64 elements after
636 * unrolling arrays, as we (will) disallow bitfields.
637 * So we can collect the true ffi_type values in a fixed-size local
638 * array on the stack and, if any arrays were seen, replace the
639 * ffi_type_pointer.elements with a more accurate set, to allow
640 * libffi to marshal them into registers correctly.
641 * It means one more loop over the fields, but if we got here,
642 * the structure is small, so there aren't too many of those.
643 *
644 * Although the passing in registers is specific to the above
645 * platforms, the array-in-struct vs. pointer problem is general.
646 * But we restrict the type transformation to small structs
647 * nonetheless.
648 *
649 * Note that although a union may be small in terms of memory usage, it
650 * could contain many overlapping declarations of arrays, e.g.
651 *
652 * union {
653 * unsigned int_8 foo [16];
654 * unsigned uint_8 bar [16];
655 * unsigned int_16 baz[8];
656 * unsigned uint_16 bozz[8];
657 * unsigned int_32 fizz[4];
658 * unsigned uint_32 buzz[4];
659 * }
660 *
661 * which is still only 16 bytes in size. We need to convert this into
662 * the following equivalent for libffi:
663 *
664 * union {
665 * struct { int_8 e1; int_8 e2; ... int_8 e_16; } f1;
666 * struct { uint_8 e1; uint_8 e2; ... uint_8 e_16; } f2;
667 * struct { int_16 e1; int_16 e2; ... int_16 e_8; } f3;
668 * struct { uint_16 e1; uint_16 e2; ... uint_16 e_8; } f4;
669 * struct { int_32 e1; int_32 e2; ... int_32 e_4; } f5;
670 * struct { uint_32 e1; uint_32 e2; ... uint_32 e_4; } f6;
671 * }
672 *
673 * The same principle applies for a struct 32 or 64 bytes in size.
674 *
675 * So the struct/union needs setting up as follows: all non-array
676 * elements copied across as is, and all array elements replaced with
677 * an equivalent struct which has as many fields as the array has
678 * elements, plus one NULL pointer.
679 */
680
681 Py_ssize_t num_ffi_type_pointers = 0; /* for the dummy fields */
682 Py_ssize_t num_ffi_types = 0; /* for the dummy structures */
683 size_t alloc_size; /* total bytes to allocate */
684 void *type_block; /* to hold all the type information needed */
685 ffi_type **element_types; /* of this struct/union */
686 ffi_type **dummy_types; /* of the dummy struct elements */
687 ffi_type *structs; /* point to struct aliases of arrays */
688 Py_ssize_t element_index; /* index into element_types for this */
689 Py_ssize_t dummy_index = 0; /* index into dummy field pointers */
690 Py_ssize_t struct_index = 0; /* index into dummy structs */
691
692 /* first pass to see how much memory to allocate */
693 for (i = 0; i < len; ++i) {
694 PyObject *name, *desc;
695 PyObject *pair = PySequence_GetItem(fields, i);
696 int bitsize = 0;
697
698 if (pair == NULL) {
699 return -1;
700 }
701 if (!PyArg_ParseTuple(pair, "UO|i", &name, &desc, &bitsize)) {
702 PyErr_SetString(PyExc_TypeError,
703 "'_fields_' must be a sequence of (name, C type) pairs");
704 Py_DECREF(pair);
705 return -1;
706 }
707
708 StgInfo *info;
709 if (PyStgInfo_FromType(st, desc, &info) < 0) {
710 Py_DECREF(pair);
711 return -1;
712 }
713 if (info == NULL) {
714 Py_DECREF(pair);
715 PyErr_Format(PyExc_TypeError,
716 "second item in _fields_ tuple (index %zd) must be a C type",
717 i);
718 return -1;
719 }
720
721 if (!PyCArrayTypeObject_Check(st, desc)) {
722 /* Not an array. Just need an ffi_type pointer. */
723 num_ffi_type_pointers++;
724 }
725 else {
726 /* It's an array. */
727 Py_ssize_t length = info->length;
728
729 StgInfo *einfo;
730 if (PyStgInfo_FromType(st, info->proto, &einfo) < 0) {
731 Py_DECREF(pair);
732 return -1;
733 }
734 if (einfo == NULL) {
735 Py_DECREF(pair);
736 PyErr_Format(PyExc_TypeError,
737 "second item in _fields_ tuple (index %zd) must be a C type",
738 i);
739 return -1;
740 }
741 /*
742 * We need one extra ffi_type to hold the struct, and one
743 * ffi_type pointer per array element + one for a NULL to
744 * mark the end.
745 */
746 num_ffi_types++;
747 num_ffi_type_pointers += length + 1;
748 }
749 Py_DECREF(pair);
750 }
751
752 /*
753 * At this point, we know we need storage for some ffi_types and some
754 * ffi_type pointers. We'll allocate these in one block.
755 * There are three sub-blocks of information: the ffi_type pointers to
756 * this structure/union's elements, the ffi_type_pointers to the
757 * dummy fields standing in for array elements, and the
758 * ffi_types representing the dummy structures.
759 */
760 alloc_size = (ffi_ofs + 1 + len + num_ffi_type_pointers) * sizeof(ffi_type *) +
761 num_ffi_types * sizeof(ffi_type);
762 type_block = PyMem_Malloc(alloc_size);
763
764 if (type_block == NULL) {
765 PyErr_NoMemory();
766 return -1;
767 }
768 /*
769 * the first block takes up ffi_ofs + len + 1 which is the pointers *
770 * for this struct/union. The second block takes up
771 * num_ffi_type_pointers, so the sum of these is ffi_ofs + len + 1 +
772 * num_ffi_type_pointers as allocated above. The last bit is the
773 * num_ffi_types structs.
774 */
775 element_types = (ffi_type **) type_block;
776 dummy_types = &element_types[ffi_ofs + len + 1];
777 structs = (ffi_type *) &dummy_types[num_ffi_type_pointers];
778
779 if (num_ffi_types > 0) {
780 memset(structs, 0, num_ffi_types * sizeof(ffi_type));
781 }
782 if (ffi_ofs && (baseinfo != NULL)) {
783 memcpy(element_types,
784 baseinfo->ffi_type_pointer.elements,
785 ffi_ofs * sizeof(ffi_type *));
786 }
787 element_index = ffi_ofs;
788
789 /* second pass to actually set the type pointers */
790 for (i = 0; i < len; ++i) {
791 PyObject *name, *desc;
792 PyObject *pair = PySequence_GetItem(fields, i);
793 int bitsize = 0;
794
795 if (pair == NULL) {
796 PyMem_Free(type_block);
797 return -1;
798 }
799 /* In theory, we made this call in the first pass, so it *shouldn't*
800 * fail. However, you never know, and the code above might change
801 * later - keeping the check in here is a tad defensive but it
802 * will affect program size only slightly and performance hardly at
803 * all.
804 */
805 if (!PyArg_ParseTuple(pair, "UO|i", &name, &desc, &bitsize)) {
806 PyErr_SetString(PyExc_TypeError,
807 "'_fields_' must be a sequence of (name, C type) pairs");
808 Py_DECREF(pair);
809 PyMem_Free(type_block);
810 return -1;
811 }
812
813 StgInfo *info;
814 if (PyStgInfo_FromType(st, desc, &info) < 0) {
815 Py_DECREF(pair);
816 PyMem_Free(type_block);
817 return -1;
818 }
819
820 /* Possibly this check could be avoided, but see above comment. */
821 if (info == NULL) {
822 Py_DECREF(pair);
823 PyMem_Free(type_block);
824 PyErr_Format(PyExc_TypeError,
825 "second item in _fields_ tuple (index %zd) must be a C type",
826 i);
827 return -1;
828 }
829
830 assert(element_index < (ffi_ofs + len)); /* will be used below */
831 if (!PyCArrayTypeObject_Check(st, desc)) {
832 /* Not an array. Just copy over the element ffi_type. */
833 element_types[element_index++] = &info->ffi_type_pointer;
834 }
835 else {
836 Py_ssize_t length = info->length;
837 StgInfo *einfo;
838 if (PyStgInfo_FromType(st, info->proto, &einfo) < 0) {
839 Py_DECREF(pair);
840 PyMem_Free(type_block);
841 return -1;
842 }
843 if (einfo == NULL) {
844 Py_DECREF(pair);
845 PyMem_Free(type_block);
846 PyErr_Format(PyExc_TypeError,
847 "second item in _fields_ tuple (index %zd) must be a C type",
848 i);
849 return -1;
850 }
851 element_types[element_index++] = &structs[struct_index];
852 structs[struct_index].size = length * einfo->ffi_type_pointer.size;
853 structs[struct_index].alignment = einfo->ffi_type_pointer.alignment;
854 structs[struct_index].type = FFI_TYPE_STRUCT;
855 structs[struct_index].elements = &dummy_types[dummy_index];
856 ++struct_index;
857 /* Copy over the element's type, length times. */
858 while (length > 0) {
859 assert(dummy_index < (num_ffi_type_pointers));
860 dummy_types[dummy_index++] = &einfo->ffi_type_pointer;
861 length--;
862 }
863 assert(dummy_index < (num_ffi_type_pointers));
864 dummy_types[dummy_index++] = NULL;
865 }
866 Py_DECREF(pair);
867 }
868
869 element_types[element_index] = NULL;
870 /*
871 * Replace the old elements with the new, taking into account
872 * base class elements where necessary.
873 */
874 assert(stginfo->ffi_type_pointer.elements);
875 PyMem_Free(stginfo->ffi_type_pointer.elements);
876 stginfo->ffi_type_pointer.elements = element_types;
877 }
878
879 /* We did check that this flag was NOT set above, it must not
880 have been set until now. */
881 if (stginfo->flags & DICTFLAG_FINAL) {
882 PyErr_SetString(PyExc_AttributeError,
883 "Structure or union cannot contain itself");
884 return -1;
885 }
886 stginfo->flags |= DICTFLAG_FINAL;
887
888 return MakeAnonFields(type);
889 }