-
Notifications
You must be signed in to change notification settings - Fork 41
/
_cffi_backend.c
8120 lines (7385 loc) · 270 KB
/
_cffi_backend.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include "structmember.h"
#define CFFI_VERSION "1.16.0"
#ifdef MS_WIN32
#include <windows.h>
#include "misc_win32.h"
#else
#include <stddef.h>
#include <stdint.h>
#include <dlfcn.h>
#include <errno.h>
#include <ffi.h>
#include <sys/mman.h>
#endif
/* this block of #ifs should be kept exactly identical between
c/_cffi_backend.c, cffi/vengine_cpy.py, cffi/vengine_gen.py */
#if defined(_MSC_VER)
# include <malloc.h> /* for alloca() */
# if _MSC_VER < 1600 /* MSVC < 2010 */
typedef __int8 int8_t;
typedef __int16 int16_t;
typedef __int32 int32_t;
typedef __int64 int64_t;
typedef unsigned __int8 uint8_t;
typedef unsigned __int16 uint16_t;
typedef unsigned __int32 uint32_t;
typedef unsigned __int64 uint64_t;
typedef __int8 int_least8_t;
typedef __int16 int_least16_t;
typedef __int32 int_least32_t;
typedef __int64 int_least64_t;
typedef unsigned __int8 uint_least8_t;
typedef unsigned __int16 uint_least16_t;
typedef unsigned __int32 uint_least32_t;
typedef unsigned __int64 uint_least64_t;
typedef __int8 int_fast8_t;
typedef __int16 int_fast16_t;
typedef __int32 int_fast32_t;
typedef __int64 int_fast64_t;
typedef unsigned __int8 uint_fast8_t;
typedef unsigned __int16 uint_fast16_t;
typedef unsigned __int32 uint_fast32_t;
typedef unsigned __int64 uint_fast64_t;
typedef __int64 intmax_t;
typedef unsigned __int64 uintmax_t;
# else
# include <stdint.h>
# endif
# if _MSC_VER < 1800 /* MSVC < 2013 */
typedef unsigned char _Bool;
# endif
#else
# include <stdint.h>
# if (defined (__SVR4) && defined (__sun)) || defined(_AIX) || defined(__hpux)
# include <alloca.h>
# endif
#endif
/* Convert from closure pointer to function pointer. */
#if defined(__hppa__) && !defined(__LP64__)
#define CFFI_CLOSURE_TO_FNPTR(type, f) ((type)((unsigned int)(f) | 2))
#else
#define CFFI_CLOSURE_TO_FNPTR(type, f) ((type)(f))
#endif
/* Define the following macro ONLY if you trust libffi's version of
* ffi_closure_alloc() more than the code in malloc_closure.h.
* IMPORTANT: DO NOT ENABLE THIS ON LINUX, unless you understand exactly
* why I recommend against it and decide that you trust it more than my
* analysis below.
*
* There are two versions of this code: one inside libffi itself, and
* one inside malloc_closure.h here. Both should be fine as long as the
* Linux distribution does _not_ enable extra security features. If it
* does, then the code in malloc_closure.h will cleanly crash because
* there is no reasonable way to obtain a read-write-execute memory
* page. On the other hand, the code in libffi will appear to
* work---but will actually randomly crash after a fork() if the child
* does not immediately call exec(). This second crash is of the kind
* that can be turned into an attack vector by a motivated attacker.
* So, _enabling_ extra security features _opens_ an attack vector.
* That sounds like a horribly bad idea to me, and is the reason for why
* I prefer CFFI crashing cleanly.
*
* Currently, we use libffi's ffi_closure_alloc() on NetBSD. It is
* known that on the NetBSD kernel, a different strategy is used which
* should not be open to the fork() bug.
*
* This is also used on macOS, provided we are executing on macOS 10.15 or
* above. It's a mess because it needs runtime checks in that case.
*/
#ifdef __NetBSD__
# define CFFI_CHECK_FFI_CLOSURE_ALLOC 1
# define CFFI_CHECK_FFI_CLOSURE_ALLOC_MAYBE 1
# define CFFI_CHECK_FFI_PREP_CLOSURE_LOC 1
# define CFFI_CHECK_FFI_PREP_CLOSURE_LOC_MAYBE 1
# define CFFI_CHECK_FFI_PREP_CIF_VAR 0
# define CFFI_CHECK_FFI_PREP_CIF_VAR_MAYBE 0
#elif defined(__APPLE__) && defined(FFI_AVAILABLE_APPLE)
# define CFFI_CHECK_FFI_CLOSURE_ALLOC __builtin_available(macos 10.15, ios 13, watchos 6, tvos 13, *)
# define CFFI_CHECK_FFI_CLOSURE_ALLOC_MAYBE 1
# define CFFI_CHECK_FFI_PREP_CLOSURE_LOC __builtin_available(macos 10.15, ios 13, watchos 6, tvos 13, *)
# define CFFI_CHECK_FFI_PREP_CLOSURE_LOC_MAYBE 1
# define CFFI_CHECK_FFI_PREP_CIF_VAR __builtin_available(macos 10.15, ios 13, watchos 6, tvos 13, *)
# define CFFI_CHECK_FFI_PREP_CIF_VAR_MAYBE 1
#else
# define CFFI_CHECK_FFI_CLOSURE_ALLOC 0
# define CFFI_CHECK_FFI_CLOSURE_ALLOC_MAYBE 0
# define CFFI_CHECK_FFI_PREP_CLOSURE_LOC 0
# define CFFI_CHECK_FFI_PREP_CLOSURE_LOC_MAYBE 0
# define CFFI_CHECK_FFI_PREP_CIF_VAR 0
# define CFFI_CHECK_FFI_PREP_CIF_VAR_MAYBE 0
#endif
/* always includes this, even if it turns out not to be used on NetBSD
because calls are behind "if (0)" */
#include "malloc_closure.h"
#if PY_MAJOR_VERSION >= 3
# define STR_OR_BYTES "bytes"
# define PyText_Type PyUnicode_Type
# define PyText_Check PyUnicode_Check
# define PyTextAny_Check PyUnicode_Check
# define PyText_FromFormat PyUnicode_FromFormat
# define PyText_AsUTF8 _PyUnicode_AsString /* PyUnicode_AsUTF8 in Py3.3 */
# define PyText_AS_UTF8 _PyUnicode_AsString
# if PY_VERSION_HEX >= 0x03030000
# define PyText_GetSize PyUnicode_GetLength
# else
# define PyText_GetSize PyUnicode_GetSize
# endif
# define PyText_FromString PyUnicode_FromString
# define PyText_FromStringAndSize PyUnicode_FromStringAndSize
# define PyText_InternInPlace PyUnicode_InternInPlace
# define PyText_InternFromString PyUnicode_InternFromString
# define PyIntOrLong_Check PyLong_Check
#else
# define STR_OR_BYTES "str"
# define PyText_Type PyString_Type
# define PyText_Check PyString_Check
# define PyTextAny_Check(op) (PyString_Check(op) || PyUnicode_Check(op))
# define PyText_FromFormat PyString_FromFormat
# define PyText_AsUTF8 PyString_AsString
# define PyText_AS_UTF8 PyString_AS_STRING
# define PyText_GetSize PyString_Size
# define PyText_FromString PyString_FromString
# define PyText_FromStringAndSize PyString_FromStringAndSize
# define PyText_InternInPlace PyString_InternInPlace
# define PyText_InternFromString PyString_InternFromString
# define PyIntOrLong_Check(op) (PyInt_Check(op) || PyLong_Check(op))
#endif
#if PY_MAJOR_VERSION >= 3
# define PyInt_FromLong PyLong_FromLong
# define PyInt_FromSsize_t PyLong_FromSsize_t
# define PyInt_AsSsize_t PyLong_AsSsize_t
# define PyInt_AsLong PyLong_AsLong
#endif
#if PY_MAJOR_VERSION >= 3
/* This is the default on Python3 and constant has been removed. */
# define Py_TPFLAGS_CHECKTYPES 0
#endif
#if PY_MAJOR_VERSION < 3
# undef PyCapsule_GetPointer
# undef PyCapsule_New
# define PyCapsule_GetPointer(capsule, name) \
(PyCObject_AsVoidPtr(capsule))
# define PyCapsule_New(pointer, name, destructor) \
(PyCObject_FromVoidPtr(pointer, destructor))
#endif
#if PY_VERSION_HEX < 0x030900a4
# define Py_SET_REFCNT(obj, val) (Py_REFCNT(obj) = (val))
#endif
#if PY_VERSION_HEX >= 0x03080000
# define USE_WRITEUNRAISABLEMSG
#endif
/************************************************************/
/* base type flag: exactly one of the following: */
#define CT_PRIMITIVE_SIGNED 0x001 /* signed integer */
#define CT_PRIMITIVE_UNSIGNED 0x002 /* unsigned integer */
#define CT_PRIMITIVE_CHAR 0x004 /* char, wchar_t, charN_t */
#define CT_PRIMITIVE_FLOAT 0x008 /* float, double, long double */
#define CT_POINTER 0x010 /* pointer, excluding ptr-to-func */
#define CT_ARRAY 0x020 /* array */
#define CT_STRUCT 0x040 /* struct */
#define CT_UNION 0x080 /* union */
#define CT_FUNCTIONPTR 0x100 /* pointer to function */
#define CT_VOID 0x200 /* void */
#define CT_PRIMITIVE_COMPLEX 0x400 /* float _Complex, double _Complex */
/* other flags that may also be set in addition to the base flag: */
#define CT_IS_VOIDCHAR_PTR 0x00001000
#define CT_PRIMITIVE_FITS_LONG 0x00002000
#define CT_IS_OPAQUE 0x00004000
#define CT_IS_ENUM 0x00008000
#define CT_IS_PTR_TO_OWNED 0x00010000 /* only owned if CDataOwning_Type */
#define CT_CUSTOM_FIELD_POS 0x00020000
#define CT_IS_LONGDOUBLE 0x00040000
#define CT_IS_BOOL 0x00080000
#define CT_IS_FILE 0x00100000
#define CT_IS_VOID_PTR 0x00200000
#define CT_WITH_VAR_ARRAY 0x00400000 /* with open-ended array, anywhere */
/* unused 0x00800000 */
#define CT_LAZY_FIELD_LIST 0x01000000
#define CT_WITH_PACKED_CHANGE 0x02000000
#define CT_IS_SIGNED_WCHAR 0x04000000
#define CT_PRIMITIVE_ANY (CT_PRIMITIVE_SIGNED | \
CT_PRIMITIVE_UNSIGNED | \
CT_PRIMITIVE_CHAR | \
CT_PRIMITIVE_FLOAT | \
CT_PRIMITIVE_COMPLEX)
typedef struct _ctypedescr {
PyObject_VAR_HEAD
struct _ctypedescr *ct_itemdescr; /* ptrs and arrays: the item type */
PyObject *ct_stuff; /* structs: dict of the fields
arrays: ctypedescr of the ptr type
function: tuple(abi, ctres, ctargs..)
enum: pair {"name":x},{x:"name"}
ptrs: lazily, ctypedescr of array */
void *ct_extra; /* structs: first field (not a ref!)
function types: cif_description
primitives: prebuilt "cif" object */
PyObject *ct_weakreflist; /* weakref support */
PyObject *ct_unique_key; /* key in unique_cache (a string, but not
human-readable) */
Py_ssize_t ct_size; /* size of instances, or -1 if unknown */
Py_ssize_t ct_length; /* length of arrays, or -1 if unknown;
or alignment of primitive and struct types;
always -1 for pointers */
int ct_flags; /* CT_xxx flags */
int ct_name_position; /* index in ct_name of where to put a var name */
char ct_name[1]; /* string, e.g. "int *" for pointers to ints */
} CTypeDescrObject;
typedef struct {
PyObject_HEAD
CTypeDescrObject *c_type;
char *c_data;
PyObject *c_weakreflist;
} CDataObject;
typedef struct cfieldobject_s {
PyObject_HEAD
CTypeDescrObject *cf_type;
Py_ssize_t cf_offset;
short cf_bitshift; /* >= 0: bitshift; or BS_REGULAR or BS_EMPTY_ARRAY */
short cf_bitsize;
unsigned char cf_flags; /* BF_... */
struct cfieldobject_s *cf_next;
} CFieldObject;
#define BS_REGULAR (-1) /* a regular field, not with bitshift */
#define BS_EMPTY_ARRAY (-2) /* a field declared 'type[0]' or 'type[]' */
#define BF_IGNORE_IN_CTOR 0x01 /* union field not in the first place */
static PyTypeObject CTypeDescr_Type;
static PyTypeObject CField_Type;
static PyTypeObject CData_Type;
static PyTypeObject CDataOwning_Type;
static PyTypeObject CDataOwningGC_Type;
static PyTypeObject CDataFromBuf_Type;
static PyTypeObject CDataGCP_Type;
#define CTypeDescr_Check(ob) (Py_TYPE(ob) == &CTypeDescr_Type)
#define CData_Check(ob) (Py_TYPE(ob) == &CData_Type || \
Py_TYPE(ob) == &CDataOwning_Type || \
Py_TYPE(ob) == &CDataOwningGC_Type || \
Py_TYPE(ob) == &CDataFromBuf_Type || \
Py_TYPE(ob) == &CDataGCP_Type)
#define CDataOwn_Check(ob) (Py_TYPE(ob) == &CDataOwning_Type || \
Py_TYPE(ob) == &CDataOwningGC_Type)
typedef union {
unsigned char m_char;
unsigned short m_short;
unsigned int m_int;
unsigned long m_long;
unsigned long long m_longlong;
float m_float;
double m_double;
long double m_longdouble;
} union_alignment;
typedef struct {
CDataObject head;
union_alignment alignment;
} CDataObject_casted_primitive;
typedef struct {
CDataObject head;
union_alignment alignment;
} CDataObject_own_nolength;
typedef struct {
CDataObject head;
Py_ssize_t length;
union_alignment alignment;
} CDataObject_own_length;
typedef struct {
CDataObject head;
PyObject *structobj; /* for ffi.new_handle() or ffi.new("struct *") */
} CDataObject_own_structptr;
typedef struct {
CDataObject head;
Py_ssize_t length; /* same as CDataObject_own_length up to here */
Py_buffer *bufferview;
} CDataObject_frombuf;
typedef struct {
CDataObject head;
Py_ssize_t length; /* same as CDataObject_own_length up to here */
PyObject *origobj;
PyObject *destructor;
} CDataObject_gcp;
typedef struct {
CDataObject head;
ffi_closure *closure;
} CDataObject_closure;
typedef struct {
ffi_cif cif;
/* the following information is used when doing the call:
- a buffer of size 'exchange_size' is malloced
- the arguments are converted from Python objects to raw data
- the i'th raw data is stored at 'buffer + exchange_offset_arg[1+i]'
- the call is done
- the result is read back from 'buffer + exchange_offset_arg[0]' */
Py_ssize_t exchange_size;
Py_ssize_t exchange_offset_arg[1];
} cif_description_t;
#define ADD_WRAPAROUND(x, y) ((Py_ssize_t)(((size_t)(x)) + ((size_t)(y))))
#define MUL_WRAPAROUND(x, y) ((Py_ssize_t)(((size_t)(x)) * ((size_t)(y))))
/* whenever running Python code, the errno is saved in this thread-local
variable */
#ifndef MS_WIN32
# include "misc_thread_posix.h"
#endif
#include "minibuffer.h"
#if PY_MAJOR_VERSION >= 3
# include "file_emulator.h"
#endif
#ifdef PyUnicode_KIND /* Python >= 3.3 */
# include "wchar_helper_3.h"
#else
# include "wchar_helper.h"
#endif
#include "../cffi/_cffi_errors.h"
typedef struct _cffi_allocator_s {
PyObject *ca_alloc, *ca_free;
int ca_dont_clear;
} cffi_allocator_t;
static const cffi_allocator_t default_allocator = { NULL, NULL, 0 };
static PyObject *FFIError;
static PyObject *unique_cache;
/************************************************************/
static CTypeDescrObject *
ctypedescr_new(int name_size)
{
CTypeDescrObject *ct = PyObject_GC_NewVar(CTypeDescrObject,
&CTypeDescr_Type,
name_size);
if (ct == NULL)
return NULL;
ct->ct_itemdescr = NULL;
ct->ct_stuff = NULL;
ct->ct_weakreflist = NULL;
ct->ct_unique_key = NULL;
PyObject_GC_Track(ct);
return ct;
}
static CTypeDescrObject *
ctypedescr_new_on_top(CTypeDescrObject *ct_base, const char *extra_text,
int extra_position)
{
int base_name_len = strlen(ct_base->ct_name);
int extra_name_len = strlen(extra_text);
CTypeDescrObject *ct = ctypedescr_new(base_name_len + extra_name_len + 1);
char *p;
if (ct == NULL)
return NULL;
Py_INCREF(ct_base);
ct->ct_itemdescr = ct_base;
ct->ct_name_position = ct_base->ct_name_position + extra_position;
p = ct->ct_name;
memcpy(p, ct_base->ct_name, ct_base->ct_name_position);
p += ct_base->ct_name_position;
memcpy(p, extra_text, extra_name_len);
p += extra_name_len;
memcpy(p, ct_base->ct_name + ct_base->ct_name_position,
base_name_len - ct_base->ct_name_position + 1);
return ct;
}
static PyObject *
ctypedescr_repr(CTypeDescrObject *ct)
{
return PyText_FromFormat("<ctype '%s'>", ct->ct_name);
}
static void
ctypedescr_dealloc(CTypeDescrObject *ct)
{
PyObject_GC_UnTrack(ct);
if (ct->ct_weakreflist != NULL)
PyObject_ClearWeakRefs((PyObject *) ct);
if (ct->ct_unique_key != NULL) {
/* revive dead object temporarily for DelItem */
Py_SET_REFCNT(ct, 43);
PyDict_DelItem(unique_cache, ct->ct_unique_key);
assert(Py_REFCNT(ct) == 42);
Py_SET_REFCNT(ct, 0);
Py_DECREF(ct->ct_unique_key);
}
Py_XDECREF(ct->ct_itemdescr);
Py_XDECREF(ct->ct_stuff);
if (ct->ct_flags & CT_FUNCTIONPTR)
PyObject_Free(ct->ct_extra);
Py_TYPE(ct)->tp_free((PyObject *)ct);
}
static int
ctypedescr_traverse(CTypeDescrObject *ct, visitproc visit, void *arg)
{
Py_VISIT(ct->ct_itemdescr);
Py_VISIT(ct->ct_stuff);
return 0;
}
static int
ctypedescr_clear(CTypeDescrObject *ct)
{
Py_CLEAR(ct->ct_itemdescr);
Py_CLEAR(ct->ct_stuff);
return 0;
}
static PyObject *nosuchattr(const char *attr)
{
PyErr_SetString(PyExc_AttributeError, attr);
return NULL;
}
static PyObject *ctypeget_kind(CTypeDescrObject *ct, void *context)
{
char *result;
if (ct->ct_flags & CT_PRIMITIVE_ANY) {
if (ct->ct_flags & CT_IS_ENUM)
result = "enum";
else
result = "primitive";
}
else if (ct->ct_flags & CT_POINTER) {
result = "pointer";
}
else if (ct->ct_flags & CT_ARRAY) {
result = "array";
}
else if (ct->ct_flags & CT_VOID) {
result = "void";
}
else if (ct->ct_flags & CT_STRUCT) {
result = "struct";
}
else if (ct->ct_flags & CT_UNION) {
result = "union";
}
else if (ct->ct_flags & CT_FUNCTIONPTR) {
result = "function";
}
else
result = "?";
return PyText_FromString(result);
}
static PyObject *ctypeget_cname(CTypeDescrObject *ct, void *context)
{
return PyText_FromString(ct->ct_name);
}
static PyObject *ctypeget_item(CTypeDescrObject *ct, void *context)
{
if (ct->ct_flags & (CT_POINTER | CT_ARRAY)) {
Py_INCREF(ct->ct_itemdescr);
return (PyObject *)ct->ct_itemdescr;
}
return nosuchattr("item");
}
static PyObject *ctypeget_length(CTypeDescrObject *ct, void *context)
{
if (ct->ct_flags & CT_ARRAY) {
if (ct->ct_length >= 0) {
return PyInt_FromSsize_t(ct->ct_length);
}
else {
Py_INCREF(Py_None);
return Py_None;
}
}
return nosuchattr("length");
}
static PyObject *
get_field_name(CTypeDescrObject *ct, CFieldObject *cf); /* forward */
/* returns 0 if the struct ctype is opaque, 1 if it is not, or -1 if
an exception occurs */
#define force_lazy_struct(ct) \
((ct)->ct_stuff != NULL ? 1 : do_realize_lazy_struct(ct))
static int do_realize_lazy_struct(CTypeDescrObject *ct);
/* forward, implemented in realize_c_type.c */
static PyObject *ctypeget_fields(CTypeDescrObject *ct, void *context)
{
if (ct->ct_flags & (CT_STRUCT | CT_UNION)) {
if (!(ct->ct_flags & CT_IS_OPAQUE)) {
CFieldObject *cf;
PyObject *res;
if (force_lazy_struct(ct) < 0)
return NULL;
res = PyList_New(0);
if (res == NULL)
return NULL;
for (cf = (CFieldObject *)ct->ct_extra;
cf != NULL; cf = cf->cf_next) {
PyObject *o = PyTuple_Pack(2, get_field_name(ct, cf),
(PyObject *)cf);
int err = (o != NULL) ? PyList_Append(res, o) : -1;
Py_XDECREF(o);
if (err < 0) {
Py_DECREF(res);
return NULL;
}
}
return res;
}
else {
Py_INCREF(Py_None);
return Py_None;
}
}
return nosuchattr("fields");
}
static PyObject *ctypeget_args(CTypeDescrObject *ct, void *context)
{
if (ct->ct_flags & CT_FUNCTIONPTR) {
PyObject *t = ct->ct_stuff;
return PyTuple_GetSlice(t, 2, PyTuple_GET_SIZE(t));
}
return nosuchattr("args");
}
static PyObject *ctypeget_result(CTypeDescrObject *ct, void *context)
{
if (ct->ct_flags & CT_FUNCTIONPTR) {
PyObject *res = PyTuple_GetItem(ct->ct_stuff, 1);
Py_XINCREF(res);
return res;
}
return nosuchattr("result");
}
static PyObject *ctypeget_ellipsis(CTypeDescrObject *ct, void *context)
{
if (ct->ct_flags & CT_FUNCTIONPTR) {
PyObject *res = ct->ct_extra ? Py_False : Py_True;
Py_INCREF(res);
return res;
}
return nosuchattr("ellipsis");
}
static PyObject *ctypeget_abi(CTypeDescrObject *ct, void *context)
{
if (ct->ct_flags & CT_FUNCTIONPTR) {
PyObject *res = PyTuple_GetItem(ct->ct_stuff, 0);
Py_XINCREF(res);
return res;
}
return nosuchattr("abi");
}
static PyObject *ctypeget_elements(CTypeDescrObject *ct, void *context)
{
if (ct->ct_flags & CT_IS_ENUM) {
PyObject *res = PyTuple_GetItem(ct->ct_stuff, 1);
if (res) res = PyDict_Copy(res);
return res;
}
return nosuchattr("elements");
}
static PyObject *ctypeget_relements(CTypeDescrObject *ct, void *context)
{
if (ct->ct_flags & CT_IS_ENUM) {
PyObject *res = PyTuple_GetItem(ct->ct_stuff, 0);
if (res) res = PyDict_Copy(res);
return res;
}
return nosuchattr("relements");
}
static PyGetSetDef ctypedescr_getsets[] = {
{"kind", (getter)ctypeget_kind, NULL, "kind"},
{"cname", (getter)ctypeget_cname, NULL, "C name"},
{"item", (getter)ctypeget_item, NULL, "pointer to, or array of"},
{"length", (getter)ctypeget_length, NULL, "array length or None"},
{"fields", (getter)ctypeget_fields, NULL, "struct or union fields"},
{"args", (getter)ctypeget_args, NULL, "function argument types"},
{"result", (getter)ctypeget_result, NULL, "function result type"},
{"ellipsis", (getter)ctypeget_ellipsis, NULL, "function has '...'"},
{"abi", (getter)ctypeget_abi, NULL, "function ABI"},
{"elements", (getter)ctypeget_elements, NULL, "enum elements"},
{"relements", (getter)ctypeget_relements, NULL, "enum elements, reverse"},
{NULL} /* sentinel */
};
static PyObject *
ctypedescr_dir(PyObject *ct, PyObject *noarg)
{
int err;
struct PyGetSetDef *gsdef;
PyObject *res = PyList_New(0);
if (res == NULL)
return NULL;
for (gsdef = ctypedescr_getsets; gsdef->name; gsdef++) {
PyObject *x = PyObject_GetAttrString(ct, gsdef->name);
if (x == NULL) {
PyErr_Clear();
}
else {
Py_DECREF(x);
x = PyText_FromString(gsdef->name);
err = (x != NULL) ? PyList_Append(res, x) : -1;
Py_XDECREF(x);
if (err < 0) {
Py_DECREF(res);
return NULL;
}
}
}
return res;
}
static PyMethodDef ctypedescr_methods[] = {
{"__dir__", ctypedescr_dir, METH_NOARGS},
{NULL, NULL} /* sentinel */
};
static PyTypeObject CTypeDescr_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
"_cffi_backend.CType",
offsetof(CTypeDescrObject, ct_name),
sizeof(char),
(destructor)ctypedescr_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_compare */
(reprfunc)ctypedescr_repr, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
PyObject_GenericGetAttr, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
0, /* tp_doc */
(traverseproc)ctypedescr_traverse, /* tp_traverse */
(inquiry)ctypedescr_clear, /* tp_clear */
0, /* tp_richcompare */
offsetof(CTypeDescrObject, ct_weakreflist), /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
ctypedescr_methods, /* tp_methods */
0, /* tp_members */
ctypedescr_getsets, /* tp_getset */
};
/************************************************************/
static PyObject *
get_field_name(CTypeDescrObject *ct, CFieldObject *cf)
{
Py_ssize_t i = 0;
PyObject *d_key, *d_value;
while (PyDict_Next(ct->ct_stuff, &i, &d_key, &d_value)) {
if (d_value == (PyObject *)cf)
return d_key;
}
Py_FatalError("_cffi_backend: get_field_name()");
return NULL;
}
static void
cfield_dealloc(CFieldObject *cf)
{
Py_DECREF(cf->cf_type);
PyObject_Del(cf);
}
#undef OFF
#define OFF(x) offsetof(CFieldObject, x)
static PyMemberDef cfield_members[] = {
{"type", T_OBJECT, OFF(cf_type), READONLY},
{"offset", T_PYSSIZET, OFF(cf_offset), READONLY},
{"bitshift", T_SHORT, OFF(cf_bitshift), READONLY},
{"bitsize", T_SHORT, OFF(cf_bitsize), READONLY},
{"flags", T_UBYTE, OFF(cf_flags), READONLY},
{NULL} /* Sentinel */
};
#undef OFF
static PyTypeObject CField_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
"_cffi_backend.CField",
sizeof(CFieldObject),
0,
(destructor)cfield_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_compare */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
PyObject_GenericGetAttr, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT, /* tp_flags */
0, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
0, /* tp_methods */
cfield_members, /* tp_members */
};
/************************************************************/
static int
CDataObject_Or_PyFloat_Check(PyObject *ob)
{
return (PyFloat_Check(ob) ||
(CData_Check(ob) &&
(((CDataObject *)ob)->c_type->ct_flags & CT_PRIMITIVE_FLOAT)));
}
static PY_LONG_LONG
_my_PyLong_AsLongLong(PyObject *ob)
{
/* (possibly) convert and cast a Python object to a long long.
Like PyLong_AsLongLong(), this version accepts a Python int too, and
does convertions from other types of objects. The difference is that
this version refuses floats. */
#if PY_MAJOR_VERSION < 3
if (PyInt_Check(ob)) {
return PyInt_AS_LONG(ob);
}
else
#endif
if (PyLong_Check(ob)) {
return PyLong_AsLongLong(ob);
}
else {
PyObject *io;
PY_LONG_LONG res;
PyNumberMethods *nb = ob->ob_type->tp_as_number;
if (CDataObject_Or_PyFloat_Check(ob) ||
nb == NULL || nb->nb_int == NULL) {
PyErr_SetString(PyExc_TypeError, "an integer is required");
return -1;
}
io = (*nb->nb_int) (ob);
if (io == NULL)
return -1;
if (PyIntOrLong_Check(io)) {
res = _my_PyLong_AsLongLong(io);
}
else {
PyErr_SetString(PyExc_TypeError, "integer conversion failed");
res = -1;
}
Py_DECREF(io);
return res;
}
}
static unsigned PY_LONG_LONG
_my_PyLong_AsUnsignedLongLong(PyObject *ob, int strict)
{
/* (possibly) convert and cast a Python object to an unsigned long long.
Like PyLong_AsLongLong(), this version accepts a Python int too, and
does convertions from other types of objects. If 'strict', complains
with OverflowError and refuses floats. If '!strict', rounds floats
and masks the result. */
#if PY_MAJOR_VERSION < 3
if (PyInt_Check(ob)) {
long value1 = PyInt_AS_LONG(ob);
if (strict && value1 < 0)
goto negative;
return (unsigned PY_LONG_LONG)(PY_LONG_LONG)value1;
}
else
#endif
if (PyLong_Check(ob)) {
if (strict) {
if (_PyLong_Sign(ob) < 0)
goto negative;
return PyLong_AsUnsignedLongLong(ob);
}
else {
return PyLong_AsUnsignedLongLongMask(ob);
}
}
else {
PyObject *io;
unsigned PY_LONG_LONG res;
PyNumberMethods *nb = ob->ob_type->tp_as_number;
if ((strict && CDataObject_Or_PyFloat_Check(ob)) ||
nb == NULL || nb->nb_int == NULL) {
PyErr_SetString(PyExc_TypeError, "an integer is required");
return (unsigned PY_LONG_LONG)-1;
}
io = (*nb->nb_int) (ob);
if (io == NULL)
return (unsigned PY_LONG_LONG)-1;
if (PyIntOrLong_Check(io)) {
res = _my_PyLong_AsUnsignedLongLong(io, strict);
}
else {
PyErr_SetString(PyExc_TypeError, "integer conversion failed");
res = (unsigned PY_LONG_LONG)-1;
}
Py_DECREF(io);
return res;
}
negative:
PyErr_SetString(PyExc_OverflowError,
"can't convert negative number to unsigned");
return (unsigned PY_LONG_LONG)-1;
}
#define _read_raw_data(type) \
do { \
if (size == sizeof(type)) { \
type r; \
memcpy(&r, target, sizeof(type)); \
return r; \
} \
} while(0)
static PY_LONG_LONG
read_raw_signed_data(char *target, int size)
{
_read_raw_data(signed char);
_read_raw_data(short);
_read_raw_data(int);
_read_raw_data(long);
_read_raw_data(PY_LONG_LONG);
Py_FatalError("read_raw_signed_data: bad integer size");
return 0;
}
static unsigned PY_LONG_LONG
read_raw_unsigned_data(char *target, int size)
{
_read_raw_data(unsigned char);
_read_raw_data(unsigned short);
_read_raw_data(unsigned int);
_read_raw_data(unsigned long);
_read_raw_data(unsigned PY_LONG_LONG);
Py_FatalError("read_raw_unsigned_data: bad integer size");
return 0;
}
#ifdef __GNUC__
/* This is a workaround for what I think is a GCC bug on several
platforms. See issue #378. */
__attribute__((noinline))
#endif
void _cffi_memcpy(char *target, const void *src, size_t size)
{
memcpy(target, src, size);
}
#define _write_raw_data(type) \
do { \
if (size == sizeof(type)) { \
type r = (type)source; \
_cffi_memcpy(target, &r, sizeof(type)); \
return; \
} \
} while(0)
static void
write_raw_integer_data(char *target, unsigned PY_LONG_LONG source, int size)
{
_write_raw_data(unsigned char);
_write_raw_data(unsigned short);
_write_raw_data(unsigned int);
_write_raw_data(unsigned long);
_write_raw_data(unsigned PY_LONG_LONG);
Py_FatalError("write_raw_integer_data: bad integer size");
}
static double
read_raw_float_data(char *target, int size)
{
_read_raw_data(float);
_read_raw_data(double);
Py_FatalError("read_raw_float_data: bad float size");
return 0;
}
static long double
read_raw_longdouble_data(char *target)
{
int size = sizeof(long double);
_read_raw_data(long double);
Py_FatalError("read_raw_longdouble_data: bad long double size");
return 0;
}
static Py_complex
read_raw_complex_data(char *target, int size)
{
Py_complex r = {0.0, 0.0};
if (size == 2*sizeof(float)) {
float real_part, imag_part;
memcpy(&real_part, target + 0, sizeof(float));
memcpy(&imag_part, target + sizeof(float), sizeof(float));
r.real = real_part;
r.imag = imag_part;
return r;
}
if (size == 2*sizeof(double)) {