-
Notifications
You must be signed in to change notification settings - Fork 42
/
test_verify1.py
2383 lines (2203 loc) · 79.6 KB
/
test_verify1.py
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
import os, sys, math
import pytest
from cffi import FFI, FFIError, VerificationError, VerificationMissing, model
from cffi import CDefError
from cffi import recompiler
from testing.support import *
from testing.support import _verify, extra_compile_args, is_musl
import _cffi_backend
lib_m = ['m']
if sys.platform == 'win32':
#there is a small chance this fails on Mingw via environ $CC
import distutils.ccompiler
if distutils.ccompiler.get_default_compiler() == 'msvc':
lib_m = ['msvcrt']
class FFI(FFI):
error = _cffi_backend.FFI.error
_extra_compile_args = extra_compile_args
_verify_counter = 0
def verify(self, preamble='', *args, **kwds):
# HACK to reuse the tests from ../cffi0/test_verify.py
FFI._verify_counter += 1
module_name = 'verify%d' % FFI._verify_counter
try:
del self._assigned_source
except AttributeError:
pass
self.set_source(module_name, preamble)
return _verify(self, module_name, preamble, *args,
extra_compile_args=self._extra_compile_args, **kwds)
class FFI_warnings_not_error(FFI):
_extra_compile_args = []
def test_missing_function(ffi=None):
# uses the FFI hacked above with '-Werror'
if ffi is None:
ffi = FFI()
ffi.cdef("void some_completely_unknown_function();")
try:
lib = ffi.verify()
except (VerificationError, OSError, ImportError):
pass # expected case: we get a VerificationError
else:
# but depending on compiler and loader details, maybe
# 'lib' could actually be imported but will fail if we
# actually try to call the unknown function... Hard
# to test anything more.
pass
def test_missing_function_import_error():
# uses the original FFI that just gives a warning during compilation
test_missing_function(ffi=FFI_warnings_not_error())
def test_simple_case():
ffi = FFI()
ffi.cdef("double sin(double x);")
lib = ffi.verify('#include <math.h>', libraries=lib_m)
assert lib.sin(1.23) == math.sin(1.23)
def _Wconversion(cdef, source, **kargs):
if sys.platform in ('win32', 'darwin'):
pytest.skip("needs GCC")
if '-Wno-error=sign-conversion' in extra_compile_args:
pytest.skip("gcc 9.2.0 compiler bug exposed by Python 3.12+ prevents compilation with sign-conversion warnings-as-errors")
ffi = FFI()
ffi.cdef(cdef)
pytest.raises(VerificationError, ffi.verify, source, **kargs)
extra_compile_args_orig = extra_compile_args[:]
extra_compile_args.remove('-Wconversion')
try:
lib = ffi.verify(source, **kargs)
finally:
extra_compile_args[:] = extra_compile_args_orig
return lib
def test_Wconversion_unsigned():
_Wconversion("unsigned foo(void);",
"int foo(void) { return -1;}")
def test_Wconversion_integer():
_Wconversion("short foo(void);",
"long long foo(void) { return 1<<sizeof(short);}")
def test_Wconversion_floating():
lib = _Wconversion("float sin(double);",
"#include <math.h>", libraries=lib_m)
res = lib.sin(1.23)
assert res != math.sin(1.23) # not exact, because of double->float
assert abs(res - math.sin(1.23)) < 1E-5
def test_Wconversion_float2int():
_Wconversion("int sinf(float);",
"#include <math.h>", libraries=lib_m)
def test_Wconversion_double2int():
_Wconversion("int sin(double);",
"#include <math.h>", libraries=lib_m)
def test_rounding_1():
ffi = FFI()
ffi.cdef("double sinf(float x);")
lib = ffi.verify('#include <math.h>', libraries=lib_m)
res = lib.sinf(1.23)
assert res != math.sin(1.23) # not exact, because of double->float
assert abs(res - math.sin(1.23)) < 1E-5
def test_rounding_2():
ffi = FFI()
ffi.cdef("double sin(float x);")
lib = ffi.verify('#include <math.h>', libraries=lib_m)
res = lib.sin(1.23)
assert res != math.sin(1.23) # not exact, because of double->float
assert abs(res - math.sin(1.23)) < 1E-5
def test_strlen_exact():
ffi = FFI()
ffi.cdef("size_t strlen(const char *s);")
lib = ffi.verify("#include <string.h>")
assert lib.strlen(b"hi there!") == 9
def test_strlen_approximate():
lib = _Wconversion("int strlen(char *s);",
"#include <string.h>")
assert lib.strlen(b"hi there!") == 9
def test_return_approximate():
for typename in ['short', 'int', 'long', 'long long']:
ffi = FFI()
ffi.cdef("%s foo(signed char x);" % typename)
lib = ffi.verify("signed char foo(signed char x) { return x;}")
assert lib.foo(-128) == -128
assert lib.foo(+127) == +127
def test_strlen_array_of_char():
ffi = FFI()
ffi.cdef("size_t strlen(char[]);")
lib = ffi.verify("#include <string.h>")
assert lib.strlen(b"hello") == 5
def test_longdouble():
ffi = FFI()
ffi.cdef("long double sinl(long double x);")
lib = ffi.verify('#include <math.h>', libraries=lib_m)
for input in [1.23,
ffi.cast("double", 1.23),
ffi.cast("long double", 1.23)]:
x = lib.sinl(input)
assert repr(x).startswith("<cdata 'long double'")
assert (float(x) - math.sin(1.23)) < 1E-10
def test_longdouble_precision():
# Test that we don't loose any precision of 'long double' when
# passing through Python and CFFI.
ffi = FFI()
ffi.cdef("long double step1(long double x);")
SAME_SIZE = ffi.sizeof("long double") == ffi.sizeof("double")
lib = ffi.verify("""
long double step1(long double x)
{
return 4*x-x*x;
}
""")
def do(cast_to_double):
x = 0.9789
for i in range(10000):
x = lib.step1(x)
if cast_to_double:
x = float(x)
return float(x)
more_precise = do(False)
less_precise = do(True)
if SAME_SIZE:
assert more_precise == less_precise
else:
assert abs(more_precise - less_precise) > 0.1
# Check the particular results on Intel
import platform
if (platform.machine().startswith('i386') or
platform.machine().startswith('i486') or
platform.machine().startswith('i586') or
platform.machine().startswith('i686') or
platform.machine().startswith('x86')):
assert abs(more_precise - 0.656769) < 0.001
assert abs(less_precise - 3.99091) < 0.001
else:
pytest.skip("don't know the very exact precision of 'long double'")
all_primitive_types = model.PrimitiveType.ALL_PRIMITIVE_TYPES
if sys.platform == 'win32':
all_primitive_types = all_primitive_types.copy()
del all_primitive_types['ssize_t']
all_integer_types = sorted(tp for tp in all_primitive_types
if all_primitive_types[tp] == 'i')
all_float_types = sorted(tp for tp in all_primitive_types
if all_primitive_types[tp] == 'f')
def all_signed_integer_types(ffi):
return [x for x in all_integer_types if int(ffi.cast(x, -1)) < 0]
def all_unsigned_integer_types(ffi):
return [x for x in all_integer_types if int(ffi.cast(x, -1)) > 0]
def test_primitive_category():
for typename in all_primitive_types:
tp = model.PrimitiveType(typename)
C = tp.is_char_type()
F = tp.is_float_type()
X = tp.is_complex_type()
I = tp.is_integer_type()
assert C == (typename in ('char', 'wchar_t', 'char16_t', 'char32_t'))
assert F == (typename in ('float', 'double', 'long double'))
assert X == (typename in ('_cffi_float_complex_t', '_cffi_double_complex_t'))
assert I + F + C + X == 1 # one and only one of them is true
def test_all_integer_and_float_types():
typenames = []
for typename in all_primitive_types:
if (all_primitive_types[typename] == 'c' or
all_primitive_types[typename] == 'j' or # complex
typename == '_Bool' or typename == 'long double'):
pass
else:
typenames.append(typename)
#
ffi = FFI()
ffi.cdef('\n'.join(["%s foo_%s(%s);" % (tp, tp.replace(' ', '_'), tp)
for tp in typenames]))
lib = ffi.verify('\n'.join(["%s foo_%s(%s x) { return (%s)(x+1); }" %
(tp, tp.replace(' ', '_'), tp, tp)
for tp in typenames]))
for typename in typenames:
foo = getattr(lib, 'foo_%s' % typename.replace(' ', '_'))
assert foo(42) == 43
if sys.version < '3':
assert foo(long(44)) == 45
assert foo(ffi.cast(typename, 46)) == 47
pytest.raises(TypeError, foo, ffi.NULL)
#
# check for overflow cases
if all_primitive_types[typename] == 'f':
continue
for value in [-2**80, -2**40, -2**20, -2**10, -2**5, -1,
2**5, 2**10, 2**20, 2**40, 2**80]:
overflows = int(ffi.cast(typename, value)) != value
if overflows:
pytest.raises(OverflowError, foo, value)
else:
assert foo(value) == value + 1
def test_all_complex_types():
if sys.platform == 'win32':
typenames = ['_Fcomplex', '_Dcomplex']
header = '#include <complex.h>\n'
else:
typenames = ['float _Complex', 'double _Complex']
header = ''
#
ffi = FFI()
ffi.cdef('\n'.join(["%s foo_%s(%s);" % (tp, tp.replace(' ', '_'), tp)
for tp in typenames]))
lib = ffi.verify(
header + '\n'.join(["%s foo_%s(%s x) { return x; }" %
(tp, tp.replace(' ', '_'), tp)
for tp in typenames]))
for typename in typenames:
foo = getattr(lib, 'foo_%s' % typename.replace(' ', '_'))
assert foo(42 + 1j) == 42 + 1j
assert foo(ffi.cast(typename, 46 - 3j)) == 46 - 3j
pytest.raises(TypeError, foo, ffi.NULL)
def test_var_signed_integer_types():
ffi = FFI()
lst = all_signed_integer_types(ffi)
csource = "\n".join(["static %s somevar_%s;" % (tp, tp.replace(' ', '_'))
for tp in lst])
ffi.cdef(csource)
lib = ffi.verify(csource)
for tp in lst:
varname = 'somevar_%s' % tp.replace(' ', '_')
sz = ffi.sizeof(tp)
max = (1 << (8*sz-1)) - 1
min = -(1 << (8*sz-1))
setattr(lib, varname, max)
assert getattr(lib, varname) == max
setattr(lib, varname, min)
assert getattr(lib, varname) == min
pytest.raises(OverflowError, setattr, lib, varname, max+1)
pytest.raises(OverflowError, setattr, lib, varname, min-1)
def test_var_unsigned_integer_types():
ffi = FFI()
lst = all_unsigned_integer_types(ffi)
csource = "\n".join(["static %s somevar_%s;" % (tp, tp.replace(' ', '_'))
for tp in lst])
ffi.cdef(csource)
lib = ffi.verify(csource)
for tp in lst:
varname = 'somevar_%s' % tp.replace(' ', '_')
sz = ffi.sizeof(tp)
if tp != '_Bool':
max = (1 << (8*sz)) - 1
else:
max = 1
setattr(lib, varname, max)
assert getattr(lib, varname) == max
setattr(lib, varname, 0)
assert getattr(lib, varname) == 0
pytest.raises(OverflowError, setattr, lib, varname, max+1)
pytest.raises(OverflowError, setattr, lib, varname, -1)
def test_fn_signed_integer_types():
ffi = FFI()
lst = all_signed_integer_types(ffi)
cdefsrc = "\n".join(["%s somefn_%s(%s);" % (tp, tp.replace(' ', '_'), tp)
for tp in lst])
ffi.cdef(cdefsrc)
verifysrc = "\n".join(["%s somefn_%s(%s x) { return x; }" %
(tp, tp.replace(' ', '_'), tp) for tp in lst])
lib = ffi.verify(verifysrc)
for tp in lst:
fnname = 'somefn_%s' % tp.replace(' ', '_')
sz = ffi.sizeof(tp)
max = (1 << (8*sz-1)) - 1
min = -(1 << (8*sz-1))
fn = getattr(lib, fnname)
assert fn(max) == max
assert fn(min) == min
pytest.raises(OverflowError, fn, max + 1)
pytest.raises(OverflowError, fn, min - 1)
def test_fn_unsigned_integer_types():
ffi = FFI()
lst = all_unsigned_integer_types(ffi)
cdefsrc = "\n".join(["%s somefn_%s(%s);" % (tp, tp.replace(' ', '_'), tp)
for tp in lst])
ffi.cdef(cdefsrc)
verifysrc = "\n".join(["%s somefn_%s(%s x) { return x; }" %
(tp, tp.replace(' ', '_'), tp) for tp in lst])
lib = ffi.verify(verifysrc)
for tp in lst:
fnname = 'somefn_%s' % tp.replace(' ', '_')
sz = ffi.sizeof(tp)
if tp != '_Bool':
max = (1 << (8*sz)) - 1
else:
max = 1
fn = getattr(lib, fnname)
assert fn(max) == max
assert fn(0) == 0
pytest.raises(OverflowError, fn, max + 1)
pytest.raises(OverflowError, fn, -1)
def test_char_type():
ffi = FFI()
ffi.cdef("char foo(char);")
lib = ffi.verify("char foo(char x) { return ++x; }")
assert lib.foo(b"A") == b"B"
pytest.raises(TypeError, lib.foo, b"bar")
pytest.raises(TypeError, lib.foo, "bar")
def test_wchar_type():
ffi = FFI()
if ffi.sizeof('wchar_t') == 2:
uniexample1 = u+'\u1234'
uniexample2 = u+'\u1235'
else:
uniexample1 = u+'\U00012345'
uniexample2 = u+'\U00012346'
#
ffi.cdef("wchar_t foo(wchar_t);")
lib = ffi.verify("wchar_t foo(wchar_t x) { return x+1; }")
assert lib.foo(uniexample1) == uniexample2
def test_no_argument():
ffi = FFI()
ffi.cdef("int foo(void);")
lib = ffi.verify("int foo(void) { return 42; }")
assert lib.foo() == 42
def test_two_arguments():
ffi = FFI()
ffi.cdef("int foo(int, int);")
lib = ffi.verify("int foo(int a, int b) { return a - b; }")
assert lib.foo(40, -2) == 42
def test_macro():
ffi = FFI()
ffi.cdef("int foo(int, int);")
lib = ffi.verify("#define foo(a, b) ((a) * (b))")
assert lib.foo(-6, -7) == 42
def test_ptr():
ffi = FFI()
ffi.cdef("int *foo(int *);")
lib = ffi.verify("int *foo(int *a) { return a; }")
assert lib.foo(ffi.NULL) == ffi.NULL
p = ffi.new("int *", 42)
q = ffi.new("int *", 42)
assert lib.foo(p) == p
assert lib.foo(q) != p
def test_bogus_ptr():
ffi = FFI()
ffi.cdef("int *foo(int *);")
lib = ffi.verify("int *foo(int *a) { return a; }")
pytest.raises(TypeError, lib.foo, ffi.new("short *", 42))
def test_verify_typedefs():
pytest.skip("ignored so far")
types = ['signed char', 'unsigned char', 'int', 'long']
for cdefed in types:
for real in types:
ffi = FFI()
ffi.cdef("typedef %s foo_t;" % cdefed)
if cdefed == real:
ffi.verify("typedef %s foo_t;" % real)
else:
pytest.raises(VerificationError, ffi.verify,
"typedef %s foo_t;" % real)
def test_nondecl_struct():
ffi = FFI()
ffi.cdef("typedef struct foo_s foo_t; int bar(foo_t *);")
lib = ffi.verify("typedef struct foo_s foo_t;\n"
"int bar(foo_t *f) { (void)f; return 42; }\n")
assert lib.bar(ffi.NULL) == 42
def test_ffi_full_struct():
def check(verified_code):
ffi = FFI()
ffi.cdef("struct foo_s { char x; int y; long *z; };")
ffi.verify(verified_code)
ffi.new("struct foo_s *", {})
check("struct foo_s { char x; int y; long *z; };")
#
if sys.platform != 'win32': # XXX fixme: only gives warnings
pytest.raises(VerificationError, check,
"struct foo_s { char x; int y; int *z; };")
#
pytest.raises(VerificationError, check,
"struct foo_s { int y; long *z; };") # cdef'ed field x is missing
#
e = pytest.raises(FFI.error, check,
"struct foo_s { int y; char x; long *z; };")
assert str(e.value).startswith(
"struct foo_s: wrong offset for field 'x'"
" (cdef says 0, but C compiler says 4)")
#
e = pytest.raises(FFI.error, check,
"struct foo_s { char x; int y; long *z; char extra; };")
assert str(e.value).startswith(
"struct foo_s: wrong total size"
" (cdef says %d, but C compiler says %d)" % (
8 + FFI().sizeof('long *'),
8 + FFI().sizeof('long *') * 2))
#
# a corner case that we cannot really detect, but where it has no
# bad consequences: the size is the same, but there is an extra field
# that replaces what is just padding in our declaration above
check("struct foo_s { char x, extra; int y; long *z; };")
#
e = pytest.raises(FFI.error, check,
"struct foo_s { char x; short pad; short y; long *z; };")
assert str(e.value).startswith(
"struct foo_s: wrong size for field 'y'"
" (cdef says 4, but C compiler says 2)")
def test_ffi_nonfull_struct():
ffi = FFI()
ffi.cdef("""
struct foo_s {
int x;
...;
};
""")
pytest.raises(VerificationMissing, ffi.sizeof, 'struct foo_s')
pytest.raises(VerificationMissing, ffi.offsetof, 'struct foo_s', 'x')
pytest.raises(VerificationMissing, ffi.new, 'struct foo_s *')
ffi.verify("""
struct foo_s {
int a, b, x, c, d, e;
};
""")
assert ffi.sizeof('struct foo_s') == 6 * ffi.sizeof('int')
assert ffi.offsetof('struct foo_s', 'x') == 2 * ffi.sizeof('int')
def test_ffi_nonfull_alignment():
ffi = FFI()
ffi.cdef("struct foo_s { char x; ...; };")
ffi.verify("struct foo_s { int a, b; char x; };")
assert ffi.sizeof('struct foo_s') == 3 * ffi.sizeof('int')
assert ffi.alignof('struct foo_s') == ffi.sizeof('int')
def _check_field_match(typename, real, expect_mismatch):
ffi = FFI()
testing_by_size = (expect_mismatch == 'by_size')
if testing_by_size:
expect_mismatch = ffi.sizeof(typename) != ffi.sizeof(real)
ffi.cdef("struct foo_s { %s x; ...; };" % typename)
try:
ffi.verify("struct foo_s { %s x; };" % real)
ffi.new("struct foo_s *", []) # because some mismatches show up lazily
except (VerificationError, ffi.error):
if not expect_mismatch:
if testing_by_size and typename != real:
print("ignoring mismatch between %s* and %s* even though "
"they have the same size" % (typename, real))
return
raise AssertionError("unexpected mismatch: %s should be accepted "
"as equal to %s" % (typename, real))
else:
if expect_mismatch:
raise AssertionError("mismatch not detected: "
"%s != %s" % (typename, real))
def test_struct_bad_sized_integer():
for typename in ['int8_t', 'int16_t', 'int32_t', 'int64_t']:
for real in ['int8_t', 'int16_t', 'int32_t', 'int64_t']:
_check_field_match(typename, real, "by_size")
def test_struct_bad_sized_float():
for typename in all_float_types:
for real in all_float_types:
_check_field_match(typename, real, "by_size")
def test_struct_signedness_ignored():
_check_field_match("int", "unsigned int", expect_mismatch=False)
_check_field_match("unsigned short", "signed short", expect_mismatch=False)
def test_struct_float_vs_int():
if sys.platform == 'win32':
pytest.skip("XXX fixme: only gives warnings")
ffi = FFI()
for typename in all_signed_integer_types(ffi):
for real in all_float_types:
_check_field_match(typename, real, expect_mismatch=True)
for typename in all_float_types:
for real in all_signed_integer_types(ffi):
_check_field_match(typename, real, expect_mismatch=True)
def test_struct_array_field():
ffi = FFI()
ffi.cdef("struct foo_s { int a[17]; ...; };")
ffi.verify("struct foo_s { int x; int a[17]; int y; };")
assert ffi.sizeof('struct foo_s') == 19 * ffi.sizeof('int')
s = ffi.new("struct foo_s *")
assert ffi.sizeof(s.a) == 17 * ffi.sizeof('int')
def test_struct_array_no_length():
ffi = FFI()
ffi.cdef("struct foo_s { int a[]; int y; ...; };\n"
"int bar(struct foo_s *);\n")
lib = ffi.verify("struct foo_s { int x; int a[17]; int y; };\n"
"int bar(struct foo_s *f) { return f->a[14]; }\n")
assert ffi.sizeof('struct foo_s') == 19 * ffi.sizeof('int')
s = ffi.new("struct foo_s *")
assert ffi.typeof(s.a) is ffi.typeof('int[]') # implicit max length
assert len(s.a) == 18 # max length, computed from the size and start offset
s.a[14] = 4242
assert lib.bar(s) == 4242
# with no declared length, out-of-bound accesses are not detected
s.a[17] = -521
assert s.y == s.a[17] == -521
#
s = ffi.new("struct foo_s *", {'a': list(range(17))})
assert s.a[16] == 16
# overflows at construction time not detected either
s = ffi.new("struct foo_s *", {'a': list(range(18))})
assert s.y == s.a[17] == 17
def test_struct_array_guess_length():
ffi = FFI()
ffi.cdef("struct foo_s { int a[...]; };")
ffi.verify("struct foo_s { int x; int a[17]; int y; };")
assert ffi.sizeof('struct foo_s') == 19 * ffi.sizeof('int')
s = ffi.new("struct foo_s *")
assert ffi.sizeof(s.a) == 17 * ffi.sizeof('int')
with pytest.raises(IndexError):
s.a[17]
def test_struct_array_c99_1():
if sys.platform == 'win32':
pytest.skip("requires C99")
ffi = FFI()
ffi.cdef("struct foo_s { int x; int a[]; };")
ffi.verify("struct foo_s { int x; int a[]; };")
assert ffi.sizeof('struct foo_s') == 1 * ffi.sizeof('int')
s = ffi.new("struct foo_s *", [424242, 4])
assert ffi.sizeof(ffi.typeof(s[0])) == 1 * ffi.sizeof('int')
assert ffi.sizeof(s[0]) == 5 * ffi.sizeof('int')
# ^^^ explanation: if you write in C: "char x[5];", then
# "sizeof(x)" will evaluate to 5. The behavior above is
# a generalization of that to "struct foo_s[len(a)=5] x;"
# if you could do that in C.
assert s.a[3] == 0
s = ffi.new("struct foo_s *", [424242, [-40, -30, -20, -10]])
assert ffi.sizeof(s[0]) == 5 * ffi.sizeof('int')
assert s.a[3] == -10
s = ffi.new("struct foo_s *")
assert ffi.sizeof(s[0]) == 1 * ffi.sizeof('int')
s = ffi.new("struct foo_s *", [424242])
assert ffi.sizeof(s[0]) == 1 * ffi.sizeof('int')
def test_struct_array_c99_2():
if sys.platform == 'win32':
pytest.skip("requires C99")
ffi = FFI()
ffi.cdef("struct foo_s { int x; int a[]; ...; };")
ffi.verify("struct foo_s { int x, y; int a[]; };")
assert ffi.sizeof('struct foo_s') == 2 * ffi.sizeof('int')
s = ffi.new("struct foo_s *", [424242, 4])
assert ffi.sizeof(s[0]) == 6 * ffi.sizeof('int')
assert s.a[3] == 0
s = ffi.new("struct foo_s *", [424242, [-40, -30, -20, -10]])
assert ffi.sizeof(s[0]) == 6 * ffi.sizeof('int')
assert s.a[3] == -10
s = ffi.new("struct foo_s *")
assert ffi.sizeof(s[0]) == 2 * ffi.sizeof('int')
s = ffi.new("struct foo_s *", [424242])
assert ffi.sizeof(s[0]) == 2 * ffi.sizeof('int')
def test_struct_ptr_to_array_field():
ffi = FFI()
ffi.cdef("struct foo_s { int (*a)[17]; ...; }; struct bar_s { ...; };")
ffi.verify("struct foo_s { int x; int (*a)[17]; int y; };\n"
"struct bar_s { int x; int *a; int y; };")
assert ffi.sizeof('struct foo_s') == ffi.sizeof("struct bar_s")
s = ffi.new("struct foo_s *")
assert ffi.sizeof(s.a) == ffi.sizeof('int(*)[17]') == ffi.sizeof("int *")
def test_struct_with_bitfield_exact():
ffi = FFI()
ffi.cdef("struct foo_s { int a:2, b:3; };")
ffi.verify("struct foo_s { int a:2, b:3; };")
s = ffi.new("struct foo_s *")
s.b = 3
with pytest.raises(OverflowError):
s.b = 4
assert s.b == 3
def test_struct_with_bitfield_enum():
ffi = FFI()
code = """
typedef enum { AA, BB, CC } foo_e;
typedef struct { foo_e f:2; } foo_s;
"""
ffi.cdef(code)
ffi.verify(code)
s = ffi.new("foo_s *")
s.f = 1
assert s.f == 1
if int(ffi.cast("foo_e", -1)) < 0:
two = -2
else:
two = 2
s.f = two
assert s.f == two
def test_unsupported_struct_with_bitfield_ellipsis():
ffi = FFI()
pytest.raises(NotImplementedError, ffi.cdef,
"struct foo_s { int a:2, b:3; ...; };")
def test_global_constants():
ffi = FFI()
# use 'static const int', as generally documented, although in this
# case the 'static' is completely ignored.
ffi.cdef("static const int AA, BB, CC, DD;")
lib = ffi.verify("#define AA 42\n"
"#define BB (-43) // blah\n"
"#define CC (22*2) /* foobar */\n"
"#define DD ((unsigned int)142) /* foo\nbar */\n")
assert lib.AA == 42
assert lib.BB == -43
assert lib.CC == 44
assert lib.DD == 142
def test_global_const_int_size():
# integer constants: ignore the declared type, always just use the value
for value in [-2**63, -2**31, -2**15,
2**15-1, 2**15, 2**31-1, 2**31, 2**32-1, 2**32,
2**63-1, 2**63, 2**64-1]:
ffi = FFI()
if value == int(ffi.cast("long long", value)):
if value < 0:
vstr = '(-%dLL-1)' % (~value,)
else:
vstr = '%dLL' % value
elif value == int(ffi.cast("unsigned long long", value)):
vstr = '%dULL' % value
else:
raise AssertionError(value)
ffi.cdef("static const unsigned short AA;")
lib = ffi.verify("#define AA %s\n" % vstr)
assert lib.AA == value
assert type(lib.AA) is type(int(lib.AA))
def test_global_constants_non_int():
ffi = FFI()
ffi.cdef("static char *const PP;")
lib = ffi.verify('static char *const PP = "testing!";\n')
assert ffi.typeof(lib.PP) == ffi.typeof("char *")
assert ffi.string(lib.PP) == b"testing!"
def test_nonfull_enum():
ffi = FFI()
ffi.cdef("enum ee { EE1, EE2, EE3, ... \n \t };")
pytest.raises(VerificationMissing, ffi.cast, 'enum ee', 'EE2')
ffi.verify("enum ee { EE1=10, EE2, EE3=-10, EE4 };")
assert ffi.string(ffi.cast('enum ee', 11)) == "EE2"
assert ffi.string(ffi.cast('enum ee', -10)) == "EE3"
#
assert ffi.typeof("enum ee").relements == {'EE1': 10, 'EE2': 11, 'EE3': -10}
assert ffi.typeof("enum ee").elements == {10: 'EE1', 11: 'EE2', -10: 'EE3'}
def test_full_enum():
ffi = FFI()
ffi.cdef("enum ee { EE1, EE2, EE3 };")
lib = ffi.verify("enum ee { EE1, EE2, EE3 };")
assert [lib.EE1, lib.EE2, lib.EE3] == [0, 1, 2]
def test_enum_usage():
ffi = FFI()
ffi.cdef("enum ee { EE1,EE2 }; typedef struct { enum ee x; } *sp;")
lib = ffi.verify("enum ee { EE1,EE2 }; typedef struct { enum ee x; } *sp;")
assert lib.EE2 == 1
s = ffi.new("sp", [lib.EE2])
assert s.x == 1
s.x = 17
assert s.x == 17
def test_anonymous_enum():
ffi = FFI()
ffi.cdef("enum { EE1 }; enum { EE2, EE3 };")
lib = ffi.verify("enum { EE1 }; enum { EE2, EE3 };")
assert lib.EE1 == 0
assert lib.EE2 == 0
assert lib.EE3 == 1
def test_nonfull_anonymous_enum():
ffi = FFI()
ffi.cdef("enum { EE1, ... }; enum { EE3, ... };")
lib = ffi.verify("enum { EE2, EE1 }; enum { EE3 };")
assert lib.EE1 == 1
assert lib.EE3 == 0
def test_nonfull_enum_syntax2():
ffi = FFI()
ffi.cdef("enum ee { EE1, EE2=\t..., EE3 };")
pytest.raises(VerificationMissing, ffi.cast, 'enum ee', 'EE1')
ffi.verify("enum ee { EE1=10, EE2, EE3=-10, EE4 };")
assert ffi.string(ffi.cast('enum ee', 11)) == 'EE2'
assert ffi.string(ffi.cast('enum ee', -10)) == 'EE3'
#
ffi = FFI()
ffi.cdef("enum ee { EE1, EE2=\t... };")
pytest.raises(VerificationMissing, ffi.cast, 'enum ee', 'EE1')
ffi.verify("enum ee { EE1=10, EE2, EE3=-10, EE4 };")
assert ffi.string(ffi.cast('enum ee', 11)) == 'EE2'
#
ffi = FFI()
ffi.cdef("enum ee2 { EE4=..., EE5=..., ... };")
ffi.verify("enum ee2 { EE4=-1234-5, EE5 }; ")
assert ffi.string(ffi.cast('enum ee2', -1239)) == 'EE4'
assert ffi.string(ffi.cast('enum ee2', -1238)) == 'EE5'
def test_get_set_errno():
ffi = FFI()
ffi.cdef("int foo(int);")
lib = ffi.verify("""
static int foo(int x)
{
errno += 1;
return x * 7;
}
""")
ffi.errno = 15
assert lib.foo(6) == 42
assert ffi.errno == 16
def test_define_int():
ffi = FFI()
ffi.cdef("#define FOO ...\n"
"\t#\tdefine\tBAR\t...\t\n"
"#define BAZ ...\n")
lib = ffi.verify("#define FOO 42\n"
"#define BAR (-44)\n"
"#define BAZ 0xffffffffffffffffULL\n")
assert lib.FOO == 42
assert lib.BAR == -44
assert lib.BAZ == 0xffffffffffffffff
def test_access_variable():
ffi = FFI()
ffi.cdef("static int foo(void);\n"
"static int somenumber;")
lib = ffi.verify("""
static int somenumber = 2;
static int foo(void) {
return somenumber * 7;
}
""")
assert lib.somenumber == 2
assert lib.foo() == 14
lib.somenumber = -6
assert lib.foo() == -42
assert lib.somenumber == -6
lib.somenumber = 2 # reset for the next run, if any
def test_access_address_of_variable():
# access the address of 'somenumber': need a trick
ffi = FFI()
ffi.cdef("static int somenumber; static int *const somenumberptr;")
lib = ffi.verify("""
static int somenumber = 2;
#define somenumberptr (&somenumber)
""")
assert lib.somenumber == 2
lib.somenumberptr[0] = 42
assert lib.somenumber == 42
lib.somenumber = 2 # reset for the next run, if any
def test_access_array_variable(length=5):
ffi = FFI()
ffi.cdef("static int foo(int);\n"
"static int somenumber[%s];" % (length,))
lib = ffi.verify("""
static int somenumber[] = {2, 2, 3, 4, 5};
static int foo(int i) {
return somenumber[i] * 7;
}
""")
if length == '':
# a global variable of an unknown array length is implicitly
# transformed into a global pointer variable, because we can only
# work with array instances whose length we know. using a pointer
# instead of an array gives the correct effects.
assert repr(lib.somenumber).startswith("<cdata 'int *' 0x")
pytest.raises(TypeError, len, lib.somenumber)
else:
assert repr(lib.somenumber).startswith("<cdata 'int[%s]' 0x" % length)
assert len(lib.somenumber) == 5
assert lib.somenumber[3] == 4
assert lib.foo(3) == 28
lib.somenumber[3] = -6
assert lib.foo(3) == -42
assert lib.somenumber[3] == -6
assert lib.somenumber[4] == 5
lib.somenumber[3] = 4 # reset for the next run, if any
def test_access_array_variable_length_hidden():
test_access_array_variable(length='')
def test_access_struct_variable():
ffi = FFI()
ffi.cdef("struct foo { int x; ...; };\n"
"static int foo(int);\n"
"static struct foo stuff;")
lib = ffi.verify("""
struct foo { int x, y, z; };
static struct foo stuff = {2, 5, 8};
static int foo(int i) {
switch (i) {
case 0: return stuff.x * 7;
case 1: return stuff.y * 7;
case 2: return stuff.z * 7;
}
return -1;
}
""")
assert lib.stuff.x == 2
assert lib.foo(0) == 14
assert lib.foo(1) == 35
assert lib.foo(2) == 56
lib.stuff.x = -6
assert lib.foo(0) == -42
assert lib.foo(1) == 35
lib.stuff.x = 2 # reset for the next run, if any
def test_access_callback():
ffi = FFI()
ffi.cdef("static int (*cb)(int);\n"
"static int foo(int);\n"
"static void reset_cb(void);")
lib = ffi.verify("""
static int g(int x) { return x * 7; }
static int (*cb)(int);
static int foo(int i) { return cb(i) - 1; }
static void reset_cb(void) { cb = g; }
""")
lib.reset_cb()
assert lib.foo(6) == 41
my_callback = ffi.callback("int(*)(int)", lambda n: n * 222)
lib.cb = my_callback
assert lib.foo(4) == 887
def test_access_callback_function_typedef():
ffi = FFI()
ffi.cdef("typedef int mycallback_t(int);\n"
"static mycallback_t *cb;\n"
"static int foo(int);\n"
"static void reset_cb(void);")
lib = ffi.verify("""
static int g(int x) { return x * 7; }
static int (*cb)(int);
static int foo(int i) { return cb(i) - 1; }
static void reset_cb(void) { cb = g; }
""")
lib.reset_cb()
assert lib.foo(6) == 41
my_callback = ffi.callback("int(*)(int)", lambda n: n * 222)
lib.cb = my_callback
assert lib.foo(4) == 887
def test_call_with_struct_ptr():
ffi = FFI()
ffi.cdef("typedef struct { int x; ...; } foo_t; int foo(foo_t *);")
lib = ffi.verify("""
typedef struct { int y, x; } foo_t;
static int foo(foo_t *f) { return f->x * 7; }
""")
f = ffi.new("foo_t *")
f.x = 6
assert lib.foo(f) == 42
def test_unknown_type():
ffi = FFI()
ffi.cdef("""
typedef ... token_t;
int foo(token_t *);
#define TOKEN_SIZE ...
""")
lib = ffi.verify("""
typedef float token_t;
static int foo(token_t *tk) {
if (!tk)
return -42;
*tk += 1.601f;
return (int)*tk;
}
#define TOKEN_SIZE sizeof(token_t)
""")
# we cannot let ffi.new("token_t *") work, because we don't know ahead of
# time if it's ok to ask 'sizeof(token_t)' in the C code or not.
# See test_unknown_type_2. Workaround.
tkmem = ffi.new("char[]", lib.TOKEN_SIZE) # zero-initialized
tk = ffi.cast("token_t *", tkmem)
results = [lib.foo(tk) for i in range(6)]
assert results == [1, 3, 4, 6, 8, 9]
assert lib.foo(ffi.NULL) == -42
def test_unknown_type_2():
ffi = FFI()
ffi.cdef("typedef ... token_t;")
lib = ffi.verify("typedef struct token_s token_t;")
# assert did not crash, even though 'sizeof(token_t)' is not valid in C.
def test_unknown_type_3():
ffi = FFI()
ffi.cdef("""
typedef ... *token_p;
token_p foo(token_p);
""")
lib = ffi.verify("""
typedef struct _token_s *token_p;
token_p foo(token_p arg) {
if (arg)
return (token_p)0x12347;
else
return (token_p)0x12345;
}
""")
p = lib.foo(ffi.NULL)
assert int(ffi.cast("intptr_t", p)) == 0x12345
q = lib.foo(p)
assert int(ffi.cast("intptr_t", q)) == 0x12347
def test_varargs():
ffi = FFI()
ffi.cdef("int foo(int x, ...);")
lib = ffi.verify("""
int foo(int x, ...) {
va_list vargs;
va_start(vargs, x);
x -= va_arg(vargs, int);
x -= va_arg(vargs, int);
va_end(vargs);
return x;
}
""")
assert lib.foo(50, ffi.cast("int", 5), ffi.cast("int", 3)) == 42