Debian Codegraph @

src/c/ffi_obj.c

raw
1
2 /* An FFI object has methods like ffi.new(). It is also a container
3 for the type declarations (typedefs and structs) that you can use,
4 say in ffi.new().
5
6 CTypeDescrObjects are internally stored in the dict 'types_dict'.
7 The types_dict is lazily filled with CTypeDescrObjects made from
8 reading a _cffi_type_context_s structure.
9
10 In "modern" mode, the FFI instance is made by the C extension
11 module originally created by recompile(). The _cffi_type_context_s
12 structure comes from global data in the C extension module.
13
14 In "compatibility" mode, an FFI instance is created explicitly by
15 the user, and its _cffi_type_context_s is initially empty. You
16 need to call ffi.cdef() to add more information to it.
17 */
18
19 #ifdef MS_WIN32
20 #include "misc_win32.h"
21 #else
22 #include "misc_thread_posix.h"
23 #endif
24 #include "misc_thread_common.h"
25
26 #define FFI_COMPLEXITY_OUTPUT 1200 /* xxx should grow as needed */
27
28 #define FFIObject_Check(op) PyObject_TypeCheck(op, &FFI_Type)
29 #define LibObject_Check(ob) ((Py_TYPE(ob) == &Lib_Type))
30
31 struct FFIObject_s {
32 PyObject_HEAD
33 PyObject *gc_wrefs, *gc_wrefs_freelist;
34 PyObject *init_once_cache;
35 char ctx_is_static, ctx_is_nonempty;
36 builder_c_t types_builder;
37 };
38
39 static FFIObject *ffi_internal_new(PyTypeObject *ffitype,
40 const struct _cffi_type_context_s *static_ctx)
41 {
42 FFIObject *ffi;
43 if (static_ctx != NULL) {
44 ffi = (FFIObject *)PyObject_GC_New(FFIObject, ffitype);
45 /* we don't call PyObject_GC_Track() here: from _cffi_init_module()
46 it is not needed, because in this case the ffi object is immortal */
47 }
48 else {
49 ffi = (FFIObject *)ffitype->tp_alloc(ffitype, 0);
50 }
51 if (ffi == NULL)
52 return NULL;
53
54 if (init_builder_c(&ffi->types_builder, static_ctx) < 0) {
55 Py_DECREF(ffi);
56 return NULL;
57 }
58 ffi->gc_wrefs = NULL;
59 ffi->gc_wrefs_freelist = NULL;
60 ffi->init_once_cache = NULL;
61 ffi->ctx_is_static = (static_ctx != NULL);
62 ffi->ctx_is_nonempty = (static_ctx != NULL);
63 return ffi;
64 }
65
66 static void ffi_dealloc(FFIObject *ffi)
67 {
68 PyObject_GC_UnTrack(ffi);
69 Py_XDECREF(ffi->gc_wrefs);
70 Py_XDECREF(ffi->gc_wrefs_freelist);
71 Py_XDECREF(ffi->init_once_cache);
72
73 free_builder_c(&ffi->types_builder, ffi->ctx_is_static);
74
75 Py_TYPE(ffi)->tp_free((PyObject *)ffi);
76 }
77
78 static int ffi_traverse(FFIObject *ffi, visitproc visit, void *arg)
79 {
80 Py_VISIT(ffi->types_builder.types_dict);
81 Py_VISIT(ffi->types_builder.included_ffis);
82 Py_VISIT(ffi->types_builder.included_libs);
83 Py_VISIT(ffi->gc_wrefs);
84 return 0;
85 }
86
87 static PyObject *ffiobj_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
88 {
89 /* user-facing initialization code, for explicit FFI() calls */
90 return (PyObject *)ffi_internal_new(type, NULL);
91 }
92
93 /* forward, declared in cdlopen.c because it's mostly useful for this case */
94 static int ffiobj_init(PyObject *self, PyObject *args, PyObject *kwds);
95
96 static PyObject *ffi_fetch_int_constant(FFIObject *ffi, const char *name,
97 int recursion)
98 {
99 int index;
100
101 index = search_in_globals(&ffi->types_builder.ctx, name, strlen(name));
102 if (index >= 0) {
103 const struct _cffi_global_s *g;
104 g = &ffi->types_builder.ctx.globals[index];
105
106 switch (_CFFI_GETOP(g->type_op)) {
107 case _CFFI_OP_CONSTANT_INT:
108 case _CFFI_OP_ENUM:
109 return realize_global_int(&ffi->types_builder, index);
110
111 default:
112 PyErr_Format(FFIError,
113 "function, global variable or non-integer constant "
114 "'%.200s' must be fetched from its original 'lib' "
115 "object", name);
116 return NULL;
117 }
118 }
119
120 if (ffi->types_builder.included_ffis != NULL) {
121 Py_ssize_t i;
122 PyObject *included_ffis = ffi->types_builder.included_ffis;
123
124 if (recursion > 100) {
125 PyErr_SetString(PyExc_RuntimeError,
126 "recursion overflow in ffi.include() delegations");
127 return NULL;
128 }
129
130 for (i = 0; i < PyTuple_GET_SIZE(included_ffis); i++) {
131 FFIObject *ffi1;
132 PyObject *x;
133
134 ffi1 = (FFIObject *)PyTuple_GET_ITEM(included_ffis, i);
135 x = ffi_fetch_int_constant(ffi1, name, recursion + 1);
136 if (x != NULL || PyErr_Occurred())
137 return x;
138 }
139 }
140 return NULL; /* no exception set, means "not found" */
141 }
142
143 #define ACCEPT_STRING 1
144 #define ACCEPT_CTYPE 2
145 #define ACCEPT_CDATA 4
146 #define ACCEPT_ALL (ACCEPT_STRING | ACCEPT_CTYPE | ACCEPT_CDATA)
147 #define CONSIDER_FN_AS_FNPTR 8
148
149 static PyObject *_ffi_bad_type(struct _cffi_parse_info_s *info,
150 const char *input_text)
151 {
152 size_t length = strlen(input_text);
153 char *extra;
154
155 if (length > 500) {
156 extra = "";
157 }
158 else {
159 char *p;
160 size_t i, num_spaces = info->error_location;
161 extra = alloca(length + num_spaces + 4);
162 p = extra;
163 *p++ = '\n';
164 for (i = 0; i < length; i++) {
165 if (' ' <= input_text[i] && input_text[i] < 0x7f)
166 *p++ = input_text[i];
167 else if (input_text[i] == '\t' || input_text[i] == '\n')
168 *p++ = ' ';
169 else
170 *p++ = '?';
171 }
172 *p++ = '\n';
173 memset(p, ' ', num_spaces);
174 p += num_spaces;
175 *p++ = '^';
176 *p++ = 0;
177 }
178 PyErr_Format(FFIError, "%s%s", info->error_message, extra);
179 return NULL;
180 }
181
182 static CTypeDescrObject *_ffi_type(FFIObject *ffi, PyObject *arg,
183 int accept)
184 {
185 /* Returns the CTypeDescrObject from the user-supplied 'arg'.
186 Does not return a new reference!
187 */
188 if ((accept & ACCEPT_STRING) && PyUnicode_Check(arg)) {
189 PyObject *types_dict = ffi->types_builder.types_dict;
190 /* The types_dict keeps the reference alive. Items are never removed */
191 PyObject *x = PyDict_GetItem(types_dict, arg);
192
193 if (x == NULL) {
194 const char *input_text = PyUnicode_AsUTF8(arg);
195 struct _cffi_parse_info_s info;
196 info.ctx = &ffi->types_builder.ctx;
197 info.output_size = FFI_COMPLEXITY_OUTPUT;
198 info.output = PyMem_Malloc(FFI_COMPLEXITY_OUTPUT * sizeof(_cffi_opcode_t));
199 if (info.output == NULL) {
200 PyErr_NoMemory();
201 return NULL;
202 }
203 int index = parse_c_type(&info, input_text);
204 if (index < 0) {
205 x = _ffi_bad_type(&info, input_text);
206 }
207 else {
208 x = realize_c_type_or_func(&ffi->types_builder,
209 info.output, index);
210 }
211 PyMem_Free(info.output);
212 if (x == NULL)
213 return NULL;
214
215 /* Cache under the name given by 'arg', in addition to the
216 fact that the same ct is probably already cached under
217 its standardized name. In a few cases, it is not, e.g.
218 if it is a primitive; for the purpose of this function,
219 the important point is the following line, which makes
220 sure that in any case the next _ffi_type() with the same
221 'arg' will succeed early, in PyDict_GetItem() above.
222 */
223 PyObject *value = PyDict_SetDefault(types_dict, arg, x);
224 if (value == NULL) {
225 return NULL;
226 }
227 Py_DECREF(x); /* we know types_dict holds a strong ref */
228 x = value;
229 }
230
231 if (CTypeDescr_Check(x))
232 return (CTypeDescrObject *)x;
233 else if (accept & CONSIDER_FN_AS_FNPTR)
234 return unwrap_fn_as_fnptr(x);
235 else
236 return unexpected_fn_type(x);
237 }
238 else if ((accept & ACCEPT_CTYPE) && CTypeDescr_Check(arg)) {
239 return (CTypeDescrObject *)arg;
240 }
241 else if ((accept & ACCEPT_CDATA) && CData_Check(arg)) {
242 return ((CDataObject *)arg)->c_type;
243 }
244 else {
245 const char *m1 = (accept & ACCEPT_STRING) ? "string" : "";
246 const char *m2 = (accept & ACCEPT_CTYPE) ? "ctype object" : "";
247 const char *m3 = (accept & ACCEPT_CDATA) ? "cdata object" : "";
248 const char *s12 = (*m1 && (*m2 || *m3)) ? " or " : "";
249 const char *s23 = (*m2 && *m3) ? " or " : "";
250 PyErr_Format(PyExc_TypeError, "expected a %s%s%s%s%s, got '%.200s'",
251 m1, s12, m2, s23, m3,
252 Py_TYPE(arg)->tp_name);
253 return NULL;
254 }
255 }
256
257 PyDoc_STRVAR(ffi_sizeof_doc,
258 "Return the size in bytes of the argument.\n"
259 "It can be a string naming a C type, or a 'cdata' instance.");
260
261 static PyObject *ffi_sizeof(FFIObject *self, PyObject *arg)
262 {
263 Py_ssize_t size;
264
265 if (CData_Check(arg)) {
266 size = direct_sizeof_cdata((CDataObject *)arg);
267 }
268 else {
269 CTypeDescrObject *ct = _ffi_type(self, arg, ACCEPT_ALL);
270 if (ct == NULL)
271 return NULL;
272 if (ct->ct_flags & (CT_STRUCT | CT_UNION)) {
273 if (force_lazy_struct(ct) < 0)
274 return NULL;
275 }
276 size = cffi_get_size(ct);
277 if (size < 0) {
278 PyErr_Format(FFIError, "don't know the size of ctype '%s'",
279 ct->ct_name);
280 return NULL;
281 }
282 }
283 return PyLong_FromSsize_t(size);
284 }
285
286 PyDoc_STRVAR(ffi_alignof_doc,
287 "Return the natural alignment size in bytes of the argument.\n"
288 "It can be a string naming a C type, or a 'cdata' instance.");
289
290 static PyObject *ffi_alignof(FFIObject *self, PyObject *arg)
291 {
292 int align;
293 CTypeDescrObject *ct = _ffi_type(self, arg, ACCEPT_ALL);
294 if (ct == NULL)
295 return NULL;
296
297 align = get_alignment(ct);
298 if (align < 0)
299 return NULL;
300 return PyLong_FromLong(align);
301 }
302
303 PyDoc_STRVAR(ffi_typeof_doc,
304 "Parse the C type given as a string and return the\n"
305 "corresponding <ctype> object.\n"
306 "It can also be used on 'cdata' instance to get its C type.");
307
308 static PyObject *_cpyextfunc_type_index(PyObject *x); /* forward */
309
310 static PyObject *ffi_typeof(FFIObject *self, PyObject *arg)
311 {
312 PyObject *x = (PyObject *)_ffi_type(self, arg, ACCEPT_STRING|ACCEPT_CDATA);
313 if (x != NULL) {
314 Py_INCREF(x);
315 }
316 else {
317 x = _cpyextfunc_type_index(arg);
318 }
319 return x;
320 }
321
322 PyDoc_STRVAR(ffi_new_doc,
323 "Allocate an instance according to the specified C type and return a\n"
324 "pointer to it. The specified C type must be either a pointer or an\n"
325 "array: ``new('X *')`` allocates an X and returns a pointer to it,\n"
326 "whereas ``new('X[n]')`` allocates an array of n X'es and returns an\n"
327 "array referencing it (which works mostly like a pointer, like in C).\n"
328 "You can also use ``new('X[]', n)`` to allocate an array of a\n"
329 "non-constant length n.\n"
330 "\n"
331 "The memory is initialized following the rules of declaring a global\n"
332 "variable in C: by default it is zero-initialized, but an explicit\n"
333 "initializer can be given which can be used to fill all or part of the\n"
334 "memory.\n"
335 "\n"
336 "When the returned <cdata> object goes out of scope, the memory is\n"
337 "freed. In other words the returned <cdata> object has ownership of\n"
338 "the value of type 'cdecl' that it points to. This means that the raw\n"
339 "data can be used as long as this object is kept alive, but must not be\n"
340 "used for a longer time. Be careful about that when copying the\n"
341 "pointer to the memory somewhere else, e.g. into another structure.");
342
343 static PyObject *_ffi_new(FFIObject *self, PyObject *args, PyObject *kwds,
344 const cffi_allocator_t *allocator)
345 {
346 CTypeDescrObject *ct;
347 PyObject *arg, *init = Py_None;
348 static char *keywords[] = {"cdecl", "init", NULL};
349 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:new", keywords,
350 &arg, &init))
351 return NULL;
352
353 ct = _ffi_type(self, arg, ACCEPT_STRING|ACCEPT_CTYPE);
354 if (ct == NULL)
355 return NULL;
356
357 return direct_newp(ct, init, allocator);
358 }
359
360 static PyObject *ffi_new(FFIObject *self, PyObject *args, PyObject *kwds)
361 {
362 return _ffi_new(self, args, kwds, &default_allocator);
363 }
364
365 static PyObject *_ffi_new_with_allocator(PyObject *allocator, PyObject *args,
366 PyObject *kwds)
367 {
368 cffi_allocator_t alloc1;
369 PyObject *my_alloc, *my_free;
370 my_alloc = PyTuple_GET_ITEM(allocator, 1);
371 my_free = PyTuple_GET_ITEM(allocator, 2);
372 alloc1.ca_alloc = (my_alloc == Py_None ? NULL : my_alloc);
373 alloc1.ca_free = (my_free == Py_None ? NULL : my_free);
374 alloc1.ca_dont_clear = (PyTuple_GET_ITEM(allocator, 3) == Py_False);
375
376 return _ffi_new((FFIObject *)PyTuple_GET_ITEM(allocator, 0),
377 args, kwds, &alloc1);
378 }
379
380 PyDoc_STRVAR(ffi_new_allocator_doc,
381 "Return a new allocator, i.e. a function that behaves like ffi.new()\n"
382 "but uses the provided low-level 'alloc' and 'free' functions.\n"
383 "\n"
384 "'alloc' is called with the size as argument. If it returns NULL, a\n"
385 "MemoryError is raised. 'free' is called with the result of 'alloc'\n"
386 "as argument. Both can be either Python functions or directly C\n"
387 "functions. If 'free' is None, then no free function is called.\n"
388 "If both 'alloc' and 'free' are None, the default is used.\n"
389 "\n"
390 "If 'should_clear_after_alloc' is set to False, then the memory\n"
391 "returned by 'alloc' is assumed to be already cleared (or you are\n"
392 "fine with garbage); otherwise CFFI will clear it.");
393
394 static PyObject *ffi_new_allocator(FFIObject *self, PyObject *args,
395 PyObject *kwds)
396 {
397 PyObject *allocator, *result;
398 PyObject *my_alloc = Py_None, *my_free = Py_None;
399 int should_clear_after_alloc = 1;
400 static char *keywords[] = {"alloc", "free", "should_clear_after_alloc",
401 NULL};
402 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOi:new_allocator", keywords,
403 &my_alloc, &my_free,
404 &should_clear_after_alloc))
405 return NULL;
406
407 if (my_alloc == Py_None && my_free != Py_None) {
408 PyErr_SetString(PyExc_TypeError, "cannot pass 'free' without 'alloc'");
409 return NULL;
410 }
411
412 allocator = PyTuple_Pack(4,
413 (PyObject *)self,
414 my_alloc,
415 my_free,
416 PyBool_FromLong(should_clear_after_alloc));
417 if (allocator == NULL)
418 return NULL;
419
420 {
421 static PyMethodDef md = {"allocator",
422 (PyCFunction)_ffi_new_with_allocator,
423 METH_VARARGS | METH_KEYWORDS};
424 result = PyCFunction_New(&md, allocator);
425 }
426 Py_DECREF(allocator);
427 return result;
428 }
429
430 PyDoc_STRVAR(ffi_cast_doc,
431 "Similar to a C cast: returns an instance of the named C\n"
432 "type initialized with the given 'source'. The source is\n"
433 "casted between integers or pointers of any type.");
434
435 static PyObject *ffi_cast(FFIObject *self, PyObject *args)
436 {
437 CTypeDescrObject *ct;
438 PyObject *ob, *arg;
439 if (!PyArg_ParseTuple(args, "OO:cast", &arg, &ob))
440 return NULL;
441
442 ct = _ffi_type(self, arg, ACCEPT_STRING|ACCEPT_CTYPE);
443 if (ct == NULL)
444 return NULL;
445
446 return do_cast(ct, ob);
447 }
448
449 PyDoc_STRVAR(ffi_string_doc,
450 "Return a Python string (or unicode string) from the 'cdata'. If\n"
451 "'cdata' is a pointer or array of characters or bytes, returns the\n"
452 "null-terminated string. The returned string extends until the first\n"
453 "null character, or at most 'maxlen' characters. If 'cdata' is an\n"
454 "array then 'maxlen' defaults to its length.\n"
455 "\n"
456 "If 'cdata' is a pointer or array of wchar_t, returns a unicode string\n"
457 "following the same rules.\n"
458 "\n"
459 "If 'cdata' is a single character or byte or a wchar_t, returns it as a\n"
460 "string or unicode string.\n"
461 "\n"
462 "If 'cdata' is an enum, returns the value of the enumerator as a\n"
463 "string, or 'NUMBER' if the value is out of range.");
464
465 #define ffi_string b_string /* ffi_string() => b_string()
466 from _cffi_backend.c */
467
468 PyDoc_STRVAR(ffi_unpack_doc,
469 "Unpack an array of C data of the given length,\n"
470 "returning a Python string/unicode/list.\n"
471 "\n"
472 "If 'cdata' is a pointer to 'char', returns a byte string.\n"
473 "It does not stop at the first null. This is equivalent to:\n"
474 "ffi.buffer(cdata, length)[:]\n"
475 "\n"
476 "If 'cdata' is a pointer to 'wchar_t', returns a unicode string.\n"
477 "'length' is measured in wchar_t's; it is not the size in bytes.\n"
478 "\n"
479 "If 'cdata' is a pointer to anything else, returns a list of\n"
480 "'length' items. This is a faster equivalent to:\n"
481 "[cdata[i] for i in range(length)]");
482
483 #define ffi_unpack b_unpack /* ffi_unpack() => b_unpack()
484 from _cffi_backend.c */
485
486
487 PyDoc_STRVAR(ffi_offsetof_doc,
488 "Return the offset of the named field inside the given structure or\n"
489 "array, which must be given as a C type name. You can give several\n"
490 "field names in case of nested structures. You can also give numeric\n"
491 "values which correspond to array items, in case of an array type.");
492
493 static PyObject *ffi_offsetof(FFIObject *self, PyObject *args)
494 {
495 PyObject *arg;
496 CTypeDescrObject *ct;
497 Py_ssize_t i, offset;
498
499 if (PyTuple_Size(args) < 2) {
500 PyErr_SetString(PyExc_TypeError,
501 "offsetof() expects at least 2 arguments");
502 return NULL;
503 }
504
505 arg = PyTuple_GET_ITEM(args, 0);
506 ct = _ffi_type(self, arg, ACCEPT_STRING|ACCEPT_CTYPE);
507 if (ct == NULL)
508 return NULL;
509
510 offset = 0;
511 for (i = 1; i < PyTuple_GET_SIZE(args); i++) {
512 Py_ssize_t ofs1;
513 ct = direct_typeoffsetof(ct, PyTuple_GET_ITEM(args, i), i > 1, &ofs1);
514 if (ct == NULL)
515 return NULL;
516 offset += ofs1;
517 }
518 return PyLong_FromSsize_t(offset);
519 }
520
521 PyDoc_STRVAR(ffi_addressof_doc,
522 "Limited equivalent to the '&' operator in C:\n"
523 "\n"
524 "1. ffi.addressof(<cdata 'struct-or-union'>) returns a cdata that is a\n"
525 "pointer to this struct or union.\n"
526 "\n"
527 "2. ffi.addressof(<cdata>, field-or-index...) returns the address of a\n"
528 "field or array item inside the given structure or array, recursively\n"
529 "in case of nested structures or arrays.\n"
530 "\n"
531 "3. ffi.addressof(<library>, \"name\") returns the address of the named\n"
532 "function or global variable.");
533
534 static PyObject *address_of_global_var(PyObject *args); /* forward */
535
536 static PyObject *ffi_addressof(FFIObject *self, PyObject *args)
537 {
538 PyObject *arg, *z, *result;
539 CTypeDescrObject *ct;
540 Py_ssize_t i, offset = 0;
541 int accepted_flags;
542
543 if (PyTuple_Size(args) < 1) {
544 PyErr_SetString(PyExc_TypeError,
545 "addressof() expects at least 1 argument");
546 return NULL;
547 }
548
549 arg = PyTuple_GET_ITEM(args, 0);
550 if (LibObject_Check(arg)) {
551 /* case 3 in the docstring */
552 return address_of_global_var(args);
553 }
554
555 ct = _ffi_type(self, arg, ACCEPT_CDATA);
556 if (ct == NULL)
557 return NULL;
558
559 if (PyTuple_GET_SIZE(args) == 1) {
560 /* case 1 in the docstring */
561 accepted_flags = CT_STRUCT | CT_UNION | CT_ARRAY;
562 if ((ct->ct_flags & accepted_flags) == 0) {
563 PyErr_SetString(PyExc_TypeError,
564 "expected a cdata struct/union/array object");
565 return NULL;
566 }
567 }
568 else {
569 /* case 2 in the docstring */
570 accepted_flags = CT_STRUCT | CT_UNION | CT_ARRAY | CT_POINTER;
571 if ((ct->ct_flags & accepted_flags) == 0) {
572 PyErr_SetString(PyExc_TypeError,
573 "expected a cdata struct/union/array/pointer object");
574 return NULL;
575 }
576 for (i = 1; i < PyTuple_GET_SIZE(args); i++) {
577 Py_ssize_t ofs1;
578 ct = direct_typeoffsetof(ct, PyTuple_GET_ITEM(args, i),
579 i > 1, &ofs1);
580 if (ct == NULL)
581 return NULL;
582 offset += ofs1;
583 }
584 }
585
586 z = new_pointer_type(ct);
587 if (z == NULL)
588 return NULL;
589
590 result = new_simple_cdata(((CDataObject *)arg)->c_data + offset,
591 (CTypeDescrObject *)z);
592 Py_DECREF(z);
593 return result;
594 }
595
596 static PyObject *_combine_type_name_l(CTypeDescrObject *ct,
597 size_t extra_text_len)
598 {
599 size_t base_name_len;
600 PyObject *result;
601 char *p;
602
603 base_name_len = strlen(ct->ct_name);
604 result = PyBytes_FromStringAndSize(NULL, base_name_len + extra_text_len);
605 if (result == NULL)
606 return NULL;
607
608 p = PyBytes_AS_STRING(result);
609 memcpy(p, ct->ct_name, ct->ct_name_position);
610 p += ct->ct_name_position;
611 p += extra_text_len;
612 memcpy(p, ct->ct_name + ct->ct_name_position,
613 base_name_len - ct->ct_name_position);
614 return result;
615 }
616
617 PyDoc_STRVAR(ffi_getctype_doc,
618 "Return a string giving the C type 'cdecl', which may be itself a\n"
619 "string or a <ctype> object. If 'replace_with' is given, it gives\n"
620 "extra text to append (or insert for more complicated C types), like a\n"
621 "variable name, or '*' to get actually the C type 'pointer-to-cdecl'.");
622
623 static PyObject *ffi_getctype(FFIObject *self, PyObject *args, PyObject *kwds)
624 {
625 PyObject *c_decl, *res;
626 char *p, *replace_with = "";
627 int add_paren, add_space;
628 CTypeDescrObject *ct;
629 size_t replace_with_len;
630 static char *keywords[] = {"cdecl", "replace_with", NULL};
631 PyObject *u;
632
633 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|s:getctype", keywords,
634 &c_decl, &replace_with))
635 return NULL;
636
637 ct = _ffi_type(self, c_decl, ACCEPT_STRING|ACCEPT_CTYPE);
638 if (ct == NULL)
639 return NULL;
640
641 while (replace_with[0] != 0 && isspace(replace_with[0]))
642 replace_with++;
643 replace_with_len = strlen(replace_with);
644 while (replace_with_len > 0 && isspace(replace_with[replace_with_len - 1]))
645 replace_with_len--;
646
647 add_paren = (replace_with[0] == '*' &&
648 ((ct->ct_flags & CT_ARRAY) != 0));
649 add_space = (!add_paren && replace_with_len > 0 &&
650 replace_with[0] != '[' && replace_with[0] != '(');
651
652 res = _combine_type_name_l(ct, replace_with_len + add_space + 2*add_paren);
653 if (res == NULL)
654 return NULL;
655
656 p = PyBytes_AS_STRING(res) + ct->ct_name_position;
657 if (add_paren)
658 *p++ = '(';
659 if (add_space)
660 *p++ = ' ';
661 memcpy(p, replace_with, replace_with_len);
662 if (add_paren)
663 p[replace_with_len] = ')';
664
665 /* bytes -> unicode string */
666 u = PyUnicode_DecodeLatin1(PyBytes_AS_STRING(res),
667 PyBytes_GET_SIZE(res),
668 NULL);
669 Py_DECREF(res);
670 res = u;
671
672 return res;
673 }
674
675 PyDoc_STRVAR(ffi_new_handle_doc,
676 "Return a non-NULL cdata of type 'void *' that contains an opaque\n"
677 "reference to the argument, which can be any Python object. To cast it\n"
678 "back to the original object, use from_handle(). You must keep alive\n"
679 "the cdata object returned by new_handle()!");
680
681 static PyObject *ffi_new_handle(FFIObject *self, PyObject *arg)
682 {
683 /* g_ct_voidp is equal to <ctype 'void *'> */
684 return newp_handle(g_ct_voidp, arg);
685 }
686
687 PyDoc_STRVAR(ffi_from_handle_doc,
688 "Cast a 'void *' back to a Python object. Must be used *only* on the\n"
689 "pointers returned by new_handle(), and *only* as long as the exact\n"
690 "cdata object returned by new_handle() is still alive (somewhere else\n"
691 "in the program). Failure to follow these rules will crash.");
692
693 #define ffi_from_handle b_from_handle /* ffi_from_handle => b_from_handle
694 from _cffi_backend.c */
695
696 PyDoc_STRVAR(ffi_from_buffer_doc,
697 "Return a <cdata 'char[]'> that points to the data of the given Python\n"
698 "object, which must support the buffer interface. Note that this is\n"
699 "not meant to be used on the built-in types str or unicode\n"
700 "(you can build 'char[]' arrays explicitly) but only on objects\n"
701 "containing large quantities of raw data in some other format, like\n"
702 "'array.array' or numpy arrays.");
703
704 static PyObject *ffi_from_buffer(FFIObject *self, PyObject *args,
705 PyObject *kwds)
706 {
707 PyObject *cdecl1, *python_buf = NULL;
708 CTypeDescrObject *ct;
709 int require_writable = 0;
710 static char *keywords[] = {"cdecl", "python_buffer",
711 "require_writable", NULL};
712
713 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|Oi:from_buffer", keywords,
714 &cdecl1, &python_buf, &require_writable))
715 return NULL;
716
717 if (python_buf == NULL) {
718 python_buf = cdecl1;
719 ct = g_ct_chararray;
720 }
721 else {
722 ct = _ffi_type(self, cdecl1, ACCEPT_STRING|ACCEPT_CTYPE);
723 if (ct == NULL)
724 return NULL;
725 }
726 return direct_from_buffer(ct, python_buf, require_writable);
727 }
728
729 PyDoc_STRVAR(ffi_gc_doc,
730 "Return a new cdata object that points to the same data.\n"
731 "Later, when this new cdata object is garbage-collected,\n"
732 "'destructor(old_cdata_object)' will be called.\n"
733 "\n"
734 "The optional 'size' gives an estimate of the size, used to\n"
735 "trigger the garbage collection more eagerly. So far only used\n"
736 "on PyPy. It tells the GC that the returned object keeps alive\n"
737 "roughly 'size' bytes of external memory.");
738
739 #define ffi_gc b_gcp /* ffi_gc() => b_gcp()
740 from _cffi_backend.c */
741
742 PyDoc_STRVAR(ffi_def_extern_doc,
743 "A decorator. Attaches the decorated Python function to the C code\n"
744 "generated for the 'extern \"Python\"' function of the same name.\n"
745 "Calling the C function will then invoke the Python function.\n"
746 "\n"
747 "Optional arguments: 'name' is the name of the C function, if\n"
748 "different from the Python function; and 'error' and 'onerror'\n"
749 "handle what occurs if the Python function raises an exception\n"
750 "(see the docs for details).");
751
752 /* forward; see call_python.c */
753 static PyObject *_ffi_def_extern_decorator(PyObject *, PyObject *);
754
755 static PyObject *ffi_def_extern(FFIObject *self, PyObject *args,
756 PyObject *kwds)
757 {
758 static PyMethodDef md = {"def_extern_decorator",
759 (PyCFunction)_ffi_def_extern_decorator, METH_O};
760 PyObject *name = Py_None, *error = Py_None;
761 PyObject *res, *onerror = Py_None;
762 static char *keywords[] = {"name", "error", "onerror", NULL};
763
764 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOO", keywords,
765 &name, &error, &onerror))
766 return NULL;
767
768 args = Py_BuildValue("(OOOO)", (PyObject *)self, name, error, onerror);
769 if (args == NULL)
770 return NULL;
771
772 res = PyCFunction_New(&md, args);
773 Py_DECREF(args);
774 return res;
775 }
776
777 PyDoc_STRVAR(ffi_callback_doc,
778 "Return a callback object or a decorator making such a callback object.\n"
779 "'cdecl' must name a C function pointer type. The callback invokes the\n"
780 "specified 'python_callable' (which may be provided either directly or\n"
781 "via a decorator). Important: the callback object must be manually\n"
782 "kept alive for as long as the callback may be invoked from the C code.");
783
784 static PyObject *_ffi_callback_decorator(PyObject *outer_args, PyObject *fn)
785 {
786 PyObject *res, *old;
787
788 old = PyTuple_GET_ITEM(outer_args, 1);
789 PyTuple_SET_ITEM(outer_args, 1, fn);
790 res = b_callback(NULL, outer_args);
791 PyTuple_SET_ITEM(outer_args, 1, old);
792 return res;
793 }
794
795 static PyObject *ffi_callback(FFIObject *self, PyObject *args, PyObject *kwds)
796 {
797 PyObject *c_decl, *python_callable = Py_None, *error = Py_None;
798 PyObject *res, *onerror = Py_None;
799 static char *keywords[] = {"cdecl", "python_callable", "error",
800 "onerror", NULL};
801
802 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|OOO", keywords,
803 &c_decl, &python_callable, &error,
804 &onerror))
805 return NULL;
806
807 c_decl = (PyObject *)_ffi_type(self, c_decl, ACCEPT_STRING | ACCEPT_CTYPE |
808 CONSIDER_FN_AS_FNPTR);
809 if (c_decl == NULL)
810 return NULL;
811
812 args = Py_BuildValue("(OOOO)", c_decl, python_callable, error, onerror);
813 if (args == NULL)
814 return NULL;
815
816 if (python_callable != Py_None) {
817 res = b_callback(NULL, args);
818 }
819 else {
820 static PyMethodDef md = {"callback_decorator",
821 (PyCFunction)_ffi_callback_decorator, METH_O};
822 res = PyCFunction_New(&md, args);
823 }
824 Py_DECREF(args);
825 return res;
826 }
827
828 #ifdef MS_WIN32
829 PyDoc_STRVAR(ffi_getwinerror_doc,
830 "Return either the GetLastError() or the error number given by the\n"
831 "optional 'code' argument, as a tuple '(code, message)'.");
832
833 #define ffi_getwinerror b_getwinerror /* ffi_getwinerror() => b_getwinerror()
834 from misc_win32.h */
835 #endif
836
837 PyDoc_STRVAR(ffi_errno_doc, "the value of 'errno' from/to the C calls");
838
839 static PyObject *ffi_get_errno(PyObject *self, void *closure)
840 {
841 /* xxx maybe think about how to make the saved errno local
842 to an ffi instance */
843 return b_get_errno(NULL, NULL);
844 }
845
846 static int ffi_set_errno(PyObject *self, PyObject *newval, void *closure)
847 {
848 PyObject *x = b_set_errno(NULL, newval);
849 if (x == NULL)
850 return -1;
851 Py_DECREF(x);
852 return 0;
853 }
854
855 PyDoc_STRVAR(ffi_dlopen_doc,
856 "Load and return a dynamic library identified by 'name'. The standard\n"
857 "C library can be loaded by passing None.\n"
858 "\n"
859 "Note that functions and types declared with 'ffi.cdef()' are not\n"
860 "linked to a particular library, just like C headers. In the library\n"
861 "we only look for the actual (untyped) symbols at the time of their\n"
862 "first access.");
863
864 PyDoc_STRVAR(ffi_dlclose_doc,
865 "Close a library obtained with ffi.dlopen(). After this call, access to\n"
866 "functions or variables from the library will fail (possibly with a\n"
867 "segmentation fault).");
868
869 static PyObject *ffi_dlopen(PyObject *self, PyObject *args); /* forward */
870 static PyObject *ffi_dlclose(PyObject *self, PyObject *args); /* forward */
871
872 PyDoc_STRVAR(ffi_int_const_doc,
873 "Get the value of an integer constant.\n"
874 "\n"
875 "'ffi.integer_const(\"xxx\")' is equivalent to 'lib.xxx' if xxx names an\n"
876 "integer constant. The point of this function is limited to use cases\n"
877 "where you have an 'ffi' object but not any associated 'lib' object.");
878
879 static PyObject *ffi_int_const(FFIObject *self, PyObject *args, PyObject *kwds)
880 {
881 char *name;
882 PyObject *x;
883 static char *keywords[] = {"name", NULL};
884
885 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s", keywords, &name))
886 return NULL;
887
888 x = ffi_fetch_int_constant(self, name, 0);
889
890 if (x == NULL && !PyErr_Occurred()) {
891 PyErr_Format(PyExc_AttributeError,
892 "integer constant '%.200s' not found", name);
893 }
894 return x;
895 }
896
897 PyDoc_STRVAR(ffi_list_types_doc,
898 "Returns the user type names known to this FFI instance.\n"
899 "This returns a tuple containing three lists of names:\n"
900 "(typedef_names, names_of_structs, names_of_unions)");
901
902 static PyObject *ffi_list_types(FFIObject *self, PyObject *noargs)
903 {
904 Py_ssize_t i, n1 = self->types_builder.ctx.num_typenames;
905 Py_ssize_t n23 = self->types_builder.ctx.num_struct_unions;
906 PyObject *o, *lst[3] = {NULL, NULL, NULL}, *result = NULL;
907
908 lst[0] = PyList_New(n1);
909 if (lst[0] == NULL)
910 goto error;
911 lst[1] = PyList_New(0);
912 if (lst[1] == NULL)
913 goto error;
914 lst[2] = PyList_New(0);
915 if (lst[2] == NULL)
916 goto error;
917
918 for (i = 0; i < n1; i++) {
919 o = PyUnicode_FromString(self->types_builder.ctx.typenames[i].name);
920 if (o == NULL)
921 goto error;
922 PyList_SET_ITEM(lst[0], i, o);
923 }
924
925 for (i = 0; i < n23; i++) {
926 const struct _cffi_struct_union_s *s;
927 int err, index;
928
929 s = &self->types_builder.ctx.struct_unions[i];
930 if (s->name[0] == '$')
931 continue;
932
933 o = PyUnicode_FromString(s->name);
934 if (o == NULL)
935 goto error;
936 index = (s->flags & _CFFI_F_UNION) ? 2 : 1;
937 err = PyList_Append(lst[index], o);
938 Py_DECREF(o);
939 if (err < 0)
940 goto error;
941 }
942 result = PyTuple_Pack(3, lst[0], lst[1], lst[2]);
943 /* fall-through */
944 error:
945 Py_XDECREF(lst[2]);
946 Py_XDECREF(lst[1]);
947 Py_XDECREF(lst[0]);
948 return result;
949 }
950
951 PyDoc_STRVAR(ffi_memmove_doc,
952 "ffi.memmove(dest, src, n) copies n bytes of memory from src to dest.\n"
953 "\n"
954 "Like the C function memmove(), the memory areas may overlap;\n"
955 "apart from that it behaves like the C function memcpy().\n"
956 "\n"
957 "'src' can be any cdata ptr or array, or any Python buffer object.\n"
958 "'dest' can be any cdata ptr or array, or a writable Python buffer\n"
959 "object. The size to copy, 'n', is always measured in bytes.\n"
960 "\n"
961 "Unlike other methods, this one supports all Python buffer including\n"
962 "byte strings and bytearrays---but it still does not support\n"
963 "non-contiguous buffers.");
964
965 #define ffi_memmove b_memmove /* ffi_memmove() => b_memmove()
966 from _cffi_backend.c */
967
968 PyDoc_STRVAR(ffi_init_once_doc,
969 "init_once(function, tag): run function() once. More precisely,\n"
970 "'function()' is called the first time we see a given 'tag'.\n"
971 "\n"
972 "The return value of function() is remembered and returned by the current\n"
973 "and all future init_once() with the same tag. If init_once() is called\n"
974 "from multiple threads in parallel, all calls block until the execution\n"
975 "of function() is done. If function() raises an exception, it is\n"
976 "propagated and nothing is cached.");
977
978 static void _free_init_once_lock(PyObject *capsule)
979 {
980 PyThread_type_lock lock;
981 lock = PyCapsule_GetPointer(capsule, "cffi_init_once_lock");
982 if (lock != NULL)
983 PyThread_free_lock(lock);
984 }
985
986 static PyObject *ffi_init_once(FFIObject *self, PyObject *args, PyObject *kwds)
987 {
988 static char *keywords[] = {"func", "tag", NULL};
989 PyObject *cache, *func, *tag, *tup, *res, *x, *lockobj;
990 PyThread_type_lock lock;
991
992 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO", keywords, &func, &tag))
993 return NULL;
994
995 /* a lot of fun with reference counting and error checking
996 in this function */
997
998 /* atomically get or create a new dict (no GIL release) */
999 Py_BEGIN_CRITICAL_SECTION(self);
1000 cache = self->init_once_cache;
1001 if (cache == NULL) {
1002 self->init_once_cache = cache = PyDict_New();
1003 }
1004 Py_END_CRITICAL_SECTION();
1005
1006 if (cache == NULL) {
1007 return NULL;
1008 }
1009
1010 /* get the tuple from cache[tag], or make a new one: (False, lock) */
1011 if (PyDict_GetItemRef(cache, tag, &tup) < 0) {
1012 return NULL;
1013 }
1014 if (tup == NULL) {
1015 lock = PyThread_allocate_lock();
1016 if (lock == NULL)
1017 return NULL;
1018 x = PyCapsule_New(lock, "cffi_init_once_lock", _free_init_once_lock);
1019 if (x == NULL) {
1020 PyThread_free_lock(lock);
1021 return NULL;
1022 }
1023 tup = PyTuple_Pack(2, Py_False, x);
1024 Py_DECREF(x);
1025 if (tup == NULL)
1026 return NULL;
1027 x = tup;
1028
1029 /* Possible corner case if 'tag' is an object overriding __eq__
1030 in pure Python: the GIL may be released when we are running it.
1031 We really need to call dict.setdefault(). */
1032 tup = PyObject_CallMethod(cache, "setdefault", "OO", tag, x);
1033 Py_DECREF(x);
1034 if (tup == NULL)
1035 return NULL;
1036 }
1037
1038 res = PyTuple_GET_ITEM(tup, 1);
1039 Py_INCREF(res);
1040
1041 if (PyTuple_GET_ITEM(tup, 0) == Py_True) {
1042 /* tup == (True, result): return the result. */
1043 Py_DECREF(tup);
1044 return res;
1045 }
1046 Py_DECREF(tup);
1047
1048 /* tup == (False, lock) */
1049 lockobj = res;
1050 lock = (PyThread_type_lock)PyCapsule_GetPointer(lockobj,
1051 "cffi_init_once_lock");
1052 if (lock == NULL) {
1053 Py_DECREF(lockobj);
1054 return NULL;
1055 }
1056
1057 Py_BEGIN_ALLOW_THREADS
1058 PyThread_acquire_lock(lock, WAIT_LOCK);
1059 Py_END_ALLOW_THREADS
1060
1061 x = PyDict_GetItem(cache, tag);
1062 if (x != NULL && PyTuple_GET_ITEM(x, 0) == Py_True) {
1063 /* the real result was put in the dict while we were waiting
1064 for PyThread_acquire_lock() above */
1065 res = PyTuple_GET_ITEM(x, 1);
1066 Py_INCREF(res);
1067 }
1068 else {
1069 res = PyObject_CallFunction(func, "");
1070 if (res != NULL) {
1071 tup = PyTuple_Pack(2, Py_True, res);
1072 if (tup == NULL || PyDict_SetItem(cache, tag, tup) < 0) {
1073 Py_DECREF(res);
1074 res = NULL;
1075 }
1076 Py_XDECREF(tup);
1077 }
1078 }
1079
1080 PyThread_release_lock(lock);
1081 Py_DECREF(lockobj);
1082 return res;
1083 }
1084
1085 PyDoc_STRVAR(ffi_release_doc,
1086 "Release now the resources held by a 'cdata' object from ffi.new(),\n"
1087 "ffi.gc() or ffi.from_buffer(). The cdata object must not be used\n"
1088 "afterwards.\n"
1089 "\n"
1090 "'ffi.release(cdata)' is equivalent to 'cdata.__exit__()'.\n"
1091 "\n"
1092 "Note that on CPython this method has no effect (so far) on objects\n"
1093 "returned by ffi.new(), because the memory is allocated inline with the\n"
1094 "cdata object and cannot be freed independently. It might be fixed in\n"
1095 "future releases of cffi.");
1096
1097 #define ffi_release b_release /* ffi_release() => b_release()
1098 from _cffi_backend.c */
1099
1100
1101 #define METH_VKW (METH_VARARGS | METH_KEYWORDS)
1102 static PyMethodDef ffi_methods[] = {
1103 {"addressof", (PyCFunction)ffi_addressof, METH_VARARGS, ffi_addressof_doc},
1104 {"alignof", (PyCFunction)ffi_alignof, METH_O, ffi_alignof_doc},
1105 {"def_extern", (PyCFunction)ffi_def_extern, METH_VKW, ffi_def_extern_doc},
1106 {"callback", (PyCFunction)ffi_callback, METH_VKW, ffi_callback_doc},
1107 {"cast", (PyCFunction)ffi_cast, METH_VARARGS, ffi_cast_doc},
1108 {"dlclose", (PyCFunction)ffi_dlclose, METH_VARARGS, ffi_dlclose_doc},
1109 {"dlopen", (PyCFunction)ffi_dlopen, METH_VARARGS, ffi_dlopen_doc},
1110 {"from_buffer",(PyCFunction)ffi_from_buffer,METH_VKW, ffi_from_buffer_doc},
1111 {"from_handle",(PyCFunction)ffi_from_handle,METH_O, ffi_from_handle_doc},
1112 {"gc", (PyCFunction)ffi_gc, METH_VKW, ffi_gc_doc},
1113 {"getctype", (PyCFunction)ffi_getctype, METH_VKW, ffi_getctype_doc},
1114 #ifdef MS_WIN32
1115 {"getwinerror",(PyCFunction)ffi_getwinerror,METH_VKW, ffi_getwinerror_doc},
1116 #endif
1117 {"init_once", (PyCFunction)ffi_init_once, METH_VKW, ffi_init_once_doc},
1118 {"integer_const",(PyCFunction)ffi_int_const,METH_VKW, ffi_int_const_doc},
1119 {"list_types", (PyCFunction)ffi_list_types, METH_NOARGS, ffi_list_types_doc},
1120 {"memmove", (PyCFunction)ffi_memmove, METH_VKW, ffi_memmove_doc},
1121 {"new", (PyCFunction)ffi_new, METH_VKW, ffi_new_doc},
1122 {"new_allocator",(PyCFunction)ffi_new_allocator,METH_VKW,ffi_new_allocator_doc},
1123 {"new_handle", (PyCFunction)ffi_new_handle, METH_O, ffi_new_handle_doc},
1124 {"offsetof", (PyCFunction)ffi_offsetof, METH_VARARGS, ffi_offsetof_doc},
1125 {"release", (PyCFunction)ffi_release, METH_O, ffi_release_doc},
1126 {"sizeof", (PyCFunction)ffi_sizeof, METH_O, ffi_sizeof_doc},
1127 {"string", (PyCFunction)ffi_string, METH_VKW, ffi_string_doc},
1128 {"typeof", (PyCFunction)ffi_typeof, METH_O, ffi_typeof_doc},
1129 {"unpack", (PyCFunction)ffi_unpack, METH_VKW, ffi_unpack_doc},
1130 {NULL}
1131 };
1132
1133 static PyGetSetDef ffi_getsets[] = {
1134 {"errno", ffi_get_errno, ffi_set_errno, ffi_errno_doc},
1135 {NULL}
1136 };
1137
1138 static PyTypeObject FFI_Type = {
1139 PyVarObject_HEAD_INIT(NULL, 0)
1140 "_cffi_backend.FFI",
1141 sizeof(FFIObject),
1142 0,
1143 (destructor)ffi_dealloc, /* tp_dealloc */
1144 0, /* tp_print */
1145 0, /* tp_getattr */
1146 0, /* tp_setattr */
1147 0, /* tp_compare */
1148 0, /* tp_repr */
1149 0, /* tp_as_number */
1150 0, /* tp_as_sequence */
1151 0, /* tp_as_mapping */
1152 0, /* tp_hash */
1153 0, /* tp_call */
1154 0, /* tp_str */
1155 PyObject_GenericGetAttr, /* tp_getattro */
1156 0, /* tp_setattro */
1157 0, /* tp_as_buffer */
1158 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1159 Py_TPFLAGS_BASETYPE, /* tp_flags */
1160 0, /* tp_doc */
1161 (traverseproc)ffi_traverse, /* tp_traverse */
1162 0, /* tp_clear */
1163 0, /* tp_richcompare */
1164 0, /* tp_weaklistoffset */
1165 0, /* tp_iter */
1166 0, /* tp_iternext */
1167 ffi_methods, /* tp_methods */
1168 0, /* tp_members */
1169 ffi_getsets, /* tp_getset */
1170 0, /* tp_base */
1171 0, /* tp_dict */
1172 0, /* tp_descr_get */
1173 0, /* tp_descr_set */
1174 0, /* tp_dictoffset */
1175 ffiobj_init, /* tp_init */
1176 0, /* tp_alloc */
1177 ffiobj_new, /* tp_new */
1178 PyObject_GC_Del, /* tp_free */
1179 };
1180
1181
1182 static PyObject *
1183 _fetch_external_struct_or_union(const struct _cffi_struct_union_s *s,
1184 PyObject *included_ffis, int recursion)
1185 {
1186 Py_ssize_t i;
1187
1188 if (included_ffis == NULL)
1189 return NULL;
1190
1191 if (recursion > 100) {
1192 PyErr_SetString(PyExc_RuntimeError,
1193 "recursion overflow in ffi.include() delegations");
1194 return NULL;
1195 }
1196
1197 for (i = 0; i < PyTuple_GET_SIZE(included_ffis); i++) {
1198 FFIObject *ffi1;
1199 const struct _cffi_struct_union_s *s1;
1200 int sindex;
1201 PyObject *x;
1202
1203 ffi1 = (FFIObject *)PyTuple_GET_ITEM(included_ffis, i);
1204 sindex = search_in_struct_unions(&ffi1->types_builder.ctx, s->name,
1205 strlen(s->name));
1206 if (sindex < 0) /* not found at all */
1207 continue;
1208 s1 = &ffi1->types_builder.ctx.struct_unions[sindex];
1209 if ((s1->flags & (_CFFI_F_EXTERNAL | _CFFI_F_UNION))
1210 == (s->flags & _CFFI_F_UNION)) {
1211 /* s1 is not external, and the same kind (struct or union) as s */
1212 return _realize_c_struct_or_union(&ffi1->types_builder, sindex);
1213 }
1214 /* not found, look more recursively */
1215 x = _fetch_external_struct_or_union(
1216 s, ffi1->types_builder.included_ffis, recursion + 1);
1217 if (x != NULL || PyErr_Occurred())
1218 return x; /* either found, or got an error */
1219 }
1220 return NULL; /* not found at all, leave without an error */
1221 }