Debian Codegraph @

extra_tests/cffi_tests/cffi0/test_verify.py

raw symbols SCIP
1 # Generated by pypy/tool/import_cffi.py
2 import re
3 import pytest
4 import sys, os, math, weakref, random
5 from cffi import FFI, VerificationError, VerificationMissing, model, FFIError
6 from extra_tests.cffi_tests.support import *
7 from extra_tests.cffi_tests.support import extra_compile_args, is_musl
8
9 # eliminate warning noise from common test modules that are repeatedly re-imported
10 pytestmark = [
11 pytest.mark.filterwarnings("ignore:reimporting:UserWarning"),
12 #pytest.mark.filterwarnings("ignore:Deprecated:_DeprecatedConfig")
13 ]
14
15 lib_m = ['m']
16 if sys.platform == 'win32':
17 #there is a small chance this fails on Mingw via environ $CC
18 import distutils.ccompiler
19 if distutils.ccompiler.get_default_compiler() == 'msvc':
20 lib_m = ['msvcrt']
21 pass # no obvious -Werror equivalent on MSVC
22 class FFI(FFI):
23 def verify(self, *args, **kwds):
24 modulename = kwds.get("modulename", "_cffi_test%d_%d" % (
25 random.randint(0,1000000000), random.randint(0,1000000000)))
26 kwds["modulename"] = modulename
27 return super(FFI, self).verify(*args, **kwds)
28
29 else:
30 class FFI(FFI):
31 def verify(self, *args, **kwds):
32 modulename = kwds.get("modulename", "_cffi_test%d_%d" % (
33 random.randint(0,1000000000), random.randint(0,1000000000)))
34 kwds["modulename"] = modulename
35 return super(FFI, self).verify(
36 *args, extra_compile_args=extra_compile_args, **kwds)
37
38 def setup_module():
39 import cffi.verifier
40 #
41 # check that no $ sign is produced in the C file; it used to be the
42 # case that anonymous enums would produce '$enum_$1', which was
43 # used as part of a function name. GCC accepts such names, but it's
44 # apparently non-standard.
45 _r_comment = re.compile(r"/\*.*?\*/|//.*?$", re.DOTALL | re.MULTILINE)
46 _r_string = re.compile(r'\".*?\"')
47 def _write_source_and_check(self, file=None):
48 base_write_source(self, file)
49 if file is None:
50 f = open(self.sourcefilename)
51 data = f.read()
52 f.close()
53 data = _r_comment.sub(' ', data)
54 data = _r_string.sub('"skipped"', data)
55 assert '$' not in data
56 base_write_source = cffi.verifier.Verifier._write_source
57 cffi.verifier.Verifier._write_source = _write_source_and_check
58
59
60 def test_module_type():
61 import cffi.verifier
62 ffi = FFI()
63 lib = ffi.verify()
64 if hasattr(lib, '_cffi_python_module'):
65 pass
66 # print('verify got a PYTHON module')
67 if hasattr(lib, '_cffi_generic_module'):
68 pass
69 # print('verify got a GENERIC module')
70 expected_generic = (cffi.verifier.local._FORCE_GENERIC_ENGINE or
71 '__pypy__' in sys.builtin_module_names)
72 assert hasattr(lib, '_cffi_python_module') == (not expected_generic)
73 assert hasattr(lib, '_cffi_generic_module') == expected_generic
74
75 def test_missing_function(ffi=None):
76 # uses the FFI hacked above with '-Werror'
77 if ffi is None:
78 ffi = FFI()
79 ffi.cdef("void some_completely_unknown_function();")
80 try:
81 lib = ffi.verify()
82 except (VerificationError, OSError):
83 pass # expected case: we get a VerificationError
84 else:
85 # but depending on compiler and loader details, maybe
86 # 'lib' could actually be imported but will fail if we
87 # actually try to call the unknown function... Hard
88 # to test anything more.
89 pass
90
91 def test_missing_function_import_error():
92 # uses the original FFI that just gives a warning during compilation
93 import cffi
94 test_missing_function(ffi=cffi.FFI())
95
96 def test_simple_case():
97 ffi = FFI()
98 ffi.cdef("double sin(double x);")
99 lib = ffi.verify('#include <math.h>', libraries=lib_m)
100 assert lib.sin(1.23) == math.sin(1.23)
101
102 def _Wconversion(cdef, source, **kargs):
103 if sys.platform in ('win32', 'darwin'):
104 pytest.skip("needs GCC")
105 if '-Wno-error=sign-conversion' in extra_compile_args:
106 pytest.skip("gcc 9.2.0 compiler bug exposed by Python 3.12+ prevents compilation with sign-conversion warnings-as-errors")
107 ffi = FFI()
108 ffi.cdef(cdef)
109 pytest.raises(VerificationError, ffi.verify, source, **kargs)
110 extra_compile_args_orig = extra_compile_args[:]
111 extra_compile_args.remove('-Wconversion')
112 try:
113 lib = ffi.verify(source, **kargs)
114 finally:
115 extra_compile_args[:] = extra_compile_args_orig
116 return lib
117
118 def test_Wconversion_unsigned():
119 _Wconversion("unsigned foo(void);",
120 "int foo(void) { return -1;}")
121
122 def test_Wconversion_integer():
123 _Wconversion("short foo(void);",
124 "long long foo(void) { return 1<<sizeof(short);}")
125
126 def test_Wconversion_floating():
127 lib = _Wconversion("float sin(double);",
128 "#include <math.h>", libraries=lib_m)
129 res = lib.sin(1.23)
130 assert res != math.sin(1.23) # not exact, because of double->float
131 assert abs(res - math.sin(1.23)) < 1E-5
132
133 def test_Wconversion_float2int():
134 _Wconversion("int sinf(float);",
135 "#include <math.h>", libraries=lib_m)
136
137 def test_Wconversion_double2int():
138 _Wconversion("int sin(double);",
139 "#include <math.h>", libraries=lib_m)
140
141 def test_rounding_1():
142 ffi = FFI()
143 ffi.cdef("double sinf(float x);")
144 lib = ffi.verify('#include <math.h>', libraries=lib_m)
145 res = lib.sinf(1.23)
146 assert res != math.sin(1.23) # not exact, because of double->float
147 assert abs(res - math.sin(1.23)) < 1E-5
148
149 def test_rounding_2():
150 ffi = FFI()
151 ffi.cdef("double sin(float x);")
152 lib = ffi.verify('#include <math.h>', libraries=lib_m)
153 res = lib.sin(1.23)
154 assert res != math.sin(1.23) # not exact, because of double->float
155 assert abs(res - math.sin(1.23)) < 1E-5
156
157 def test_strlen_exact():
158 ffi = FFI()
159 ffi.cdef("size_t strlen(const char *s);")
160 lib = ffi.verify("#include <string.h>")
161 assert lib.strlen(b"hi there!") == 9
162
163 def test_strlen_approximate():
164 lib = _Wconversion("int strlen(char *s);",
165 "#include <string.h>")
166 assert lib.strlen(b"hi there!") == 9
167
168 def test_return_approximate():
169 for typename in ['short', 'int', 'long', 'long long']:
170 ffi = FFI()
171 ffi.cdef("%s foo(signed char x);" % typename)
172 lib = ffi.verify("signed char foo(signed char x) { return x;}")
173 assert lib.foo(-128) == -128
174 assert lib.foo(+127) == +127
175
176 def test_strlen_array_of_char():
177 ffi = FFI()
178 ffi.cdef("size_t strlen(char[]);")
179 lib = ffi.verify("#include <string.h>")
180 assert lib.strlen(b"hello") == 5
181
182 def test_longdouble():
183 ffi = FFI()
184 ffi.cdef("long double sinl(long double x);")
185 lib = ffi.verify('#include <math.h>', libraries=lib_m)
186 for input in [1.23,
187 ffi.cast("double", 1.23),
188 ffi.cast("long double", 1.23)]:
189 x = lib.sinl(input)
190 assert repr(x).startswith("<cdata 'long double'")
191 assert (float(x) - math.sin(1.23)) < 1E-10
192
193 def test_longdouble_precision():
194 # Test that we don't loose any precision of 'long double' when
195 # passing through Python and CFFI.
196 ffi = FFI()
197 ffi.cdef("long double step1(long double x);")
198 SAME_SIZE = ffi.sizeof("long double") == ffi.sizeof("double")
199 lib = ffi.verify("""
200 long double step1(long double x)
201 {
202 return 4*x-x*x;
203 }
204 """)
205 def do(cast_to_double):
206 x = 0.9789
207 for i in range(10000):
208 x = lib.step1(x)
209 if cast_to_double:
210 x = float(x)
211 return float(x)
212
213 more_precise = do(False)
214 less_precise = do(True)
215 if SAME_SIZE:
216 assert more_precise == less_precise
217 else:
218 assert abs(more_precise - less_precise) > 0.1
219 # Check the particular results on Intel
220 import platform
221 if (platform.machine().startswith('i386') or
222 platform.machine().startswith('i486') or
223 platform.machine().startswith('i586') or
224 platform.machine().startswith('i686') or
225 platform.machine().startswith('x86')):
226 assert abs(more_precise - 0.656769) < 0.001
227 assert abs(less_precise - 3.99091) < 0.001
228 else:
229 pytest.skip("don't know the very exact precision of 'long double'")
230
231
232 all_primitive_types = model.PrimitiveType.ALL_PRIMITIVE_TYPES
233 if sys.platform == 'win32':
234 all_primitive_types = all_primitive_types.copy()
235 del all_primitive_types['ssize_t']
236 all_integer_types = sorted(tp for tp in all_primitive_types
237 if all_primitive_types[tp] == 'i')
238 all_float_types = sorted(tp for tp in all_primitive_types
239 if all_primitive_types[tp] == 'f')
240
241 def all_signed_integer_types(ffi):
242 return [x for x in all_integer_types if int(ffi.cast(x, -1)) < 0]
243
244 def all_unsigned_integer_types(ffi):
245 return [x for x in all_integer_types if int(ffi.cast(x, -1)) > 0]
246
247
248 def test_primitive_category():
249 for typename in all_primitive_types:
250 tp = model.PrimitiveType(typename)
251 C = tp.is_char_type()
252 F = tp.is_float_type()
253 X = tp.is_complex_type()
254 I = tp.is_integer_type()
255 assert C == (typename in ('char', 'wchar_t', 'char16_t', 'char32_t'))
256 assert F == (typename in ('float', 'double', 'long double'))
257 assert X == (typename in ('_cffi_float_complex_t', '_cffi_double_complex_t'))
258 assert I + F + C + X == 1 # one and only one of them is true
259
260 def test_all_integer_and_float_types():
261 typenames = []
262 for typename in all_primitive_types:
263 if (all_primitive_types[typename] == 'c' or
264 all_primitive_types[typename] == 'j' or # complex
265 typename == '_Bool' or typename == 'long double'):
266 pass
267 else:
268 typenames.append(typename)
269 #
270 ffi = FFI()
271 ffi.cdef('\n'.join(["%s foo_%s(%s);" % (tp, tp.replace(' ', '_'), tp)
272 for tp in typenames]))
273 lib = ffi.verify('\n'.join(["%s foo_%s(%s x) { return (%s)(x+1); }" %
274 (tp, tp.replace(' ', '_'), tp, tp)
275 for tp in typenames]))
276 for typename in typenames:
277 foo = getattr(lib, 'foo_%s' % typename.replace(' ', '_'))
278 assert foo(42) == 43
279 if sys.version < '3':
280 assert foo(long(44)) == 45
281 assert foo(ffi.cast(typename, 46)) == 47
282 pytest.raises(TypeError, foo, ffi.NULL)
283 #
284 # check for overflow cases
285 if all_primitive_types[typename] == 'f':
286 continue
287 for value in [-2**80, -2**40, -2**20, -2**10, -2**5, -1,
288 2**5, 2**10, 2**20, 2**40, 2**80]:
289 overflows = int(ffi.cast(typename, value)) != value
290 if overflows:
291 pytest.raises(OverflowError, foo, value)
292 else:
293 assert foo(value) == value + 1
294
295 def test_all_complex_types():
296 pytest.skip("not implemented in verify(): complex types")
297 if sys.platform == 'win32':
298 typenames = ['_Fcomplex', '_Dcomplex']
299 header = '#include <complex.h>\n'
300 else:
301 typenames = ['float _Complex', 'double _Complex']
302 header = ''
303 #
304 ffi = FFI()
305 ffi.cdef('\n'.join(["%s foo_%s(%s);" % (tp, tp.replace(' ', '_'), tp)
306 for tp in typenames]))
307 e = pytest.raises(VerificationError, ffi.verify,
308 header + '\n'.join(["%s foo_%s(%s x) { return x; }" %
309 (tp, tp.replace(' ', '_'), tp)
310 for tp in typenames]))
311
312 def test_var_signed_integer_types():
313 ffi = FFI()
314 lst = all_signed_integer_types(ffi)
315 csource = "\n".join(["static %s somevar_%s;" % (tp, tp.replace(' ', '_'))
316 for tp in lst])
317 ffi.cdef(csource)
318 lib = ffi.verify(csource)
319 for tp in lst:
320 varname = 'somevar_%s' % tp.replace(' ', '_')
321 sz = ffi.sizeof(tp)
322 max = (1 << (8*sz-1)) - 1
323 min = -(1 << (8*sz-1))
324 setattr(lib, varname, max)
325 assert getattr(lib, varname) == max
326 setattr(lib, varname, min)
327 assert getattr(lib, varname) == min
328 pytest.raises(OverflowError, setattr, lib, varname, max+1)
329 pytest.raises(OverflowError, setattr, lib, varname, min-1)
330
331 def test_var_unsigned_integer_types():
332 ffi = FFI()
333 lst = all_unsigned_integer_types(ffi)
334 csource = "\n".join(["static %s somevar_%s;" % (tp, tp.replace(' ', '_'))
335 for tp in lst])
336 ffi.cdef(csource)
337 lib = ffi.verify(csource)
338 for tp in lst:
339 varname = 'somevar_%s' % tp.replace(' ', '_')
340 sz = ffi.sizeof(tp)
341 if tp != '_Bool':
342 max = (1 << (8*sz)) - 1
343 else:
344 max = 1
345 setattr(lib, varname, max)
346 assert getattr(lib, varname) == max
347 setattr(lib, varname, 0)
348 assert getattr(lib, varname) == 0
349 pytest.raises(OverflowError, setattr, lib, varname, max+1)
350 pytest.raises(OverflowError, setattr, lib, varname, -1)
351
352 def test_fn_signed_integer_types():
353 ffi = FFI()
354 lst = all_signed_integer_types(ffi)
355 cdefsrc = "\n".join(["%s somefn_%s(%s);" % (tp, tp.replace(' ', '_'), tp)
356 for tp in lst])
357 ffi.cdef(cdefsrc)
358 verifysrc = "\n".join(["%s somefn_%s(%s x) { return x; }" %
359 (tp, tp.replace(' ', '_'), tp) for tp in lst])
360 lib = ffi.verify(verifysrc)
361 for tp in lst:
362 fnname = 'somefn_%s' % tp.replace(' ', '_')
363 sz = ffi.sizeof(tp)
364 max = (1 << (8*sz-1)) - 1
365 min = -(1 << (8*sz-1))
366 fn = getattr(lib, fnname)
367 assert fn(max) == max
368 assert fn(min) == min
369 pytest.raises(OverflowError, fn, max + 1)
370 pytest.raises(OverflowError, fn, min - 1)
371
372 def test_fn_unsigned_integer_types():
373 ffi = FFI()
374 lst = all_unsigned_integer_types(ffi)
375 cdefsrc = "\n".join(["%s somefn_%s(%s);" % (tp, tp.replace(' ', '_'), tp)
376 for tp in lst])
377 ffi.cdef(cdefsrc)
378 verifysrc = "\n".join(["%s somefn_%s(%s x) { return x; }" %
379 (tp, tp.replace(' ', '_'), tp) for tp in lst])
380 lib = ffi.verify(verifysrc)
381 for tp in lst:
382 fnname = 'somefn_%s' % tp.replace(' ', '_')
383 sz = ffi.sizeof(tp)
384 if tp != '_Bool':
385 max = (1 << (8*sz)) - 1
386 else:
387 max = 1
388 fn = getattr(lib, fnname)
389 assert fn(max) == max
390 assert fn(0) == 0
391 pytest.raises(OverflowError, fn, max + 1)
392 pytest.raises(OverflowError, fn, -1)
393
394 def test_char_type():
395 ffi = FFI()
396 ffi.cdef("char foo(char);")
397 lib = ffi.verify("char foo(char x) { return ++x; }")
398 assert lib.foo(b"A") == b"B"
399 pytest.raises(TypeError, lib.foo, b"bar")
400 pytest.raises(TypeError, lib.foo, "bar")
401
402 def test_wchar_type():
403 ffi = FFI()
404 if ffi.sizeof('wchar_t') == 2:
405 uniexample1 = u+'\u1234'
406 uniexample2 = u+'\u1235'
407 else:
408 uniexample1 = u+'\U00012345'
409 uniexample2 = u+'\U00012346'
410 #
411 ffi.cdef("wchar_t foo(wchar_t);")
412 lib = ffi.verify("wchar_t foo(wchar_t x) { return x+1; }")
413 assert lib.foo(uniexample1) == uniexample2
414
415 def test_char16_char32_type():
416 pytest.skip("XXX test or fully prevent char16_t and char32_t from "
417 "working in ffi.verify() mode")
418
419 def test_no_argument():
420 ffi = FFI()
421 ffi.cdef("int foo(void);")
422 lib = ffi.verify("int foo(void) { return 42; }")
423 assert lib.foo() == 42
424
425 def test_two_arguments():
426 ffi = FFI()
427 ffi.cdef("int foo(int, int);")
428 lib = ffi.verify("int foo(int a, int b) { return a - b; }")
429 assert lib.foo(40, -2) == 42
430
431 def test_macro():
432 ffi = FFI()
433 ffi.cdef("int foo(int, int);")
434 lib = ffi.verify("#define foo(a, b) ((a) * (b))")
435 assert lib.foo(-6, -7) == 42
436
437 def test_ptr():
438 ffi = FFI()
439 ffi.cdef("int *foo(int *);")
440 lib = ffi.verify("int *foo(int *a) { return a; }")
441 assert lib.foo(ffi.NULL) == ffi.NULL
442 p = ffi.new("int *", 42)
443 q = ffi.new("int *", 42)
444 assert lib.foo(p) == p
445 assert lib.foo(q) != p
446
447 def test_bogus_ptr():
448 ffi = FFI()
449 ffi.cdef("int *foo(int *);")
450 lib = ffi.verify("int *foo(int *a) { return a; }")
451 pytest.raises(TypeError, lib.foo, ffi.new("short *", 42))
452
453
454 def test_verify_typedefs():
455 pytest.skip("ignored so far")
456 types = ['signed char', 'unsigned char', 'int', 'long']
457 for cdefed in types:
458 for real in types:
459 ffi = FFI()
460 ffi.cdef("typedef %s foo_t;" % cdefed)
461 if cdefed == real:
462 ffi.verify("typedef %s foo_t;" % real)
463 else:
464 pytest.raises(VerificationError, ffi.verify,
465 "typedef %s foo_t;" % real)
466
467 def test_nondecl_struct():
468 ffi = FFI()
469 ffi.cdef("typedef struct foo_s foo_t; int bar(foo_t *);")
470 lib = ffi.verify("typedef struct foo_s foo_t;\n"
471 "int bar(foo_t *f) { (void)f; return 42; }\n")
472 assert lib.bar(ffi.NULL) == 42
473
474 def test_ffi_full_struct():
475 ffi = FFI()
476 ffi.cdef("struct foo_s { char x; int y; long *z; };")
477 ffi.verify("struct foo_s { char x; int y; long *z; };")
478 #
479 if sys.platform != 'win32': # XXX fixme: only gives warnings
480 pytest.raises(VerificationError, ffi.verify,
481 "struct foo_s { char x; int y; int *z; };")
482 #
483 pytest.raises(VerificationError, ffi.verify,
484 "struct foo_s { int y; long *z; };")
485 #
486 e = pytest.raises(VerificationError, ffi.verify,
487 "struct foo_s { int y; char x; long *z; };")
488 assert str(e.value) == (
489 "struct foo_s: wrong offset for field 'x'"
490 " (we have 0, but C compiler says 4)")
491 #
492 e = pytest.raises(VerificationError, ffi.verify,
493 "struct foo_s { char x; int y; long *z; char extra; };")
494 assert str(e.value) == (
495 "struct foo_s: wrong total size"
496 " (we have %d, but C compiler says %d)" % (
497 ffi.sizeof("struct foo_s"),
498 ffi.sizeof("struct foo_s") + ffi.sizeof("long*")))
499 #
500 # a corner case that we cannot really detect, but where it has no
501 # bad consequences: the size is the same, but there is an extra field
502 # that replaces what is just padding in our declaration above
503 ffi.verify("struct foo_s { char x, extra; int y; long *z; };")
504 #
505 e = pytest.raises(VerificationError, ffi.verify,
506 "struct foo_s { char x; short pad; short y; long *z; };")
507 assert str(e.value) == (
508 "struct foo_s: wrong size for field 'y'"
509 " (we have 4, but C compiler says 2)")
510
511 def test_ffi_nonfull_struct():
512 ffi = FFI()
513 ffi.cdef("""
514 struct foo_s {
515 int x;
516 ...;
517 };
518 """)
519 pytest.raises(VerificationMissing, ffi.sizeof, 'struct foo_s')
520 pytest.raises(VerificationMissing, ffi.offsetof, 'struct foo_s', 'x')
521 pytest.raises(VerificationMissing, ffi.new, 'struct foo_s *')
522 ffi.verify("""
523 struct foo_s {
524 int a, b, x, c, d, e;
525 };
526 """)
527 assert ffi.sizeof('struct foo_s') == 6 * ffi.sizeof('int')
528 assert ffi.offsetof('struct foo_s', 'x') == 2 * ffi.sizeof('int')
529
530 def test_ffi_nonfull_alignment():
531 ffi = FFI()
532 ffi.cdef("struct foo_s { char x; ...; };")
533 ffi.verify("struct foo_s { int a, b; char x; };")
534 assert ffi.sizeof('struct foo_s') == 3 * ffi.sizeof('int')
535 assert ffi.alignof('struct foo_s') == ffi.sizeof('int')
536
537 def _check_field_match(typename, real, expect_mismatch):
538 ffi = FFI()
539 testing_by_size = (expect_mismatch == 'by_size')
540 if testing_by_size:
541 expect_mismatch = ffi.sizeof(typename) != ffi.sizeof(real)
542 ffi.cdef("struct foo_s { %s x; ...; };" % typename)
543 try:
544 ffi.verify("struct foo_s { %s x; };" % real)
545 except VerificationError:
546 if not expect_mismatch:
547 if testing_by_size and typename != real:
548 print("ignoring mismatch between %s* and %s* even though "
549 "they have the same size" % (typename, real))
550 return
551 raise AssertionError("unexpected mismatch: %s should be accepted "
552 "as equal to %s" % (typename, real))
553 else:
554 if expect_mismatch:
555 raise AssertionError("mismatch not detected: "
556 "%s != %s" % (typename, real))
557
558 def test_struct_bad_sized_integer():
559 for typename in ['int8_t', 'int16_t', 'int32_t', 'int64_t']:
560 for real in ['int8_t', 'int16_t', 'int32_t', 'int64_t']:
561 _check_field_match(typename, real, "by_size")
562
563 def test_struct_bad_sized_float():
564 for typename in all_float_types:
565 for real in all_float_types:
566 _check_field_match(typename, real, "by_size")
567
568 def test_struct_signedness_ignored():
569 _check_field_match("int", "unsigned int", expect_mismatch=False)
570 _check_field_match("unsigned short", "signed short", expect_mismatch=False)
571
572 def test_struct_float_vs_int():
573 if sys.platform == 'win32':
574 pytest.skip("XXX fixme: only gives warnings")
575 ffi = FFI()
576 for typename in all_signed_integer_types(ffi):
577 for real in all_float_types:
578 _check_field_match(typename, real, expect_mismatch=True)
579 for typename in all_float_types:
580 for real in all_signed_integer_types(ffi):
581 _check_field_match(typename, real, expect_mismatch=True)
582
583 def test_struct_array_field():
584 ffi = FFI()
585 ffi.cdef("struct foo_s { int a[17]; ...; };")
586 ffi.verify("struct foo_s { int x; int a[17]; int y; };")
587 assert ffi.sizeof('struct foo_s') == 19 * ffi.sizeof('int')
588 s = ffi.new("struct foo_s *")
589 assert ffi.sizeof(s.a) == 17 * ffi.sizeof('int')
590
591 def test_struct_array_no_length():
592 ffi = FFI()
593 ffi.cdef("struct foo_s { int a[]; int y; ...; };\n"
594 "int bar(struct foo_s *);\n")
595 lib = ffi.verify("struct foo_s { int x; int a[17]; int y; };\n"
596 "int bar(struct foo_s *f) { return f->a[14]; }\n")
597 assert ffi.sizeof('struct foo_s') == 19 * ffi.sizeof('int')
598 s = ffi.new("struct foo_s *")
599 assert ffi.typeof(s.a) is ffi.typeof('int[]') # implicit max length
600 assert len(s.a) == 18 # max length, computed from the size and start offset
601 s.a[14] = 4242
602 assert lib.bar(s) == 4242
603 # with no declared length, out-of-bound accesses are not detected
604 s.a[17] = -521
605 assert s.y == s.a[17] == -521
606 #
607 s = ffi.new("struct foo_s *", {'a': list(range(17))})
608 assert s.a[16] == 16
609 # overflows at construction time not detected either
610 s = ffi.new("struct foo_s *", {'a': list(range(18))})
611 assert s.y == s.a[17] == 17
612
613 def test_struct_array_guess_length():
614 ffi = FFI()
615 ffi.cdef("struct foo_s { int a[...]; };")
616 ffi.verify("struct foo_s { int x; int a[17]; int y; };")
617 assert ffi.sizeof('struct foo_s') == 19 * ffi.sizeof('int')
618 s = ffi.new("struct foo_s *")
619 assert ffi.sizeof(s.a) == 17 * ffi.sizeof('int')
620 with pytest.raises(IndexError):
621 s.a[17]
622
623 def test_struct_array_c99_1():
624 if sys.platform == 'win32':
625 pytest.skip("requires C99")
626 ffi = FFI()
627 ffi.cdef("struct foo_s { int x; int a[]; };")
628 ffi.verify("struct foo_s { int x; int a[]; };")
629 assert ffi.sizeof('struct foo_s') == 1 * ffi.sizeof('int')
630 s = ffi.new("struct foo_s *", [424242, 4])
631 assert ffi.sizeof(ffi.typeof(s[0])) == 1 * ffi.sizeof('int')
632 assert ffi.sizeof(s[0]) == 5 * ffi.sizeof('int')
633 # ^^^ explanation: if you write in C: "char x[5];", then
634 # "sizeof(x)" will evaluate to 5. The behavior above is
635 # a generalization of that to "struct foo_s[len(a)=5] x;"
636 # if you could do that in C.
637 assert s.a[3] == 0
638 s = ffi.new("struct foo_s *", [424242, [-40, -30, -20, -10]])
639 assert ffi.sizeof(s[0]) == 5 * ffi.sizeof('int')
640 assert s.a[3] == -10
641 s = ffi.new("struct foo_s *")
642 assert ffi.sizeof(s[0]) == 1 * ffi.sizeof('int')
643 s = ffi.new("struct foo_s *", [424242])
644 assert ffi.sizeof(s[0]) == 1 * ffi.sizeof('int')
645
646 def test_struct_array_c99_2():
647 if sys.platform == 'win32':
648 pytest.skip("requires C99")
649 ffi = FFI()
650 ffi.cdef("struct foo_s { int x; int a[]; ...; };")
651 ffi.verify("struct foo_s { int x, y; int a[]; };")
652 assert ffi.sizeof('struct foo_s') == 2 * ffi.sizeof('int')
653 s = ffi.new("struct foo_s *", [424242, 4])
654 assert ffi.sizeof(s[0]) == 6 * ffi.sizeof('int')
655 assert s.a[3] == 0
656 s = ffi.new("struct foo_s *", [424242, [-40, -30, -20, -10]])
657 assert ffi.sizeof(s[0]) == 6 * ffi.sizeof('int')
658 assert s.a[3] == -10
659 s = ffi.new("struct foo_s *")
660 assert ffi.sizeof(s[0]) == 2 * ffi.sizeof('int')
661 s = ffi.new("struct foo_s *", [424242])
662 assert ffi.sizeof(s[0]) == 2 * ffi.sizeof('int')
663
664 def test_struct_ptr_to_array_field():
665 ffi = FFI()
666 ffi.cdef("struct foo_s { int (*a)[17]; ...; }; struct bar_s { ...; };")
667 ffi.verify("struct foo_s { int x; int (*a)[17]; int y; };\n"
668 "struct bar_s { int x; int *a; int y; };")
669 assert ffi.sizeof('struct foo_s') == ffi.sizeof("struct bar_s")
670 s = ffi.new("struct foo_s *")
671 assert ffi.sizeof(s.a) == ffi.sizeof('int(*)[17]') == ffi.sizeof("int *")
672
673 def test_struct_with_bitfield_exact():
674 ffi = FFI()
675 ffi.cdef("struct foo_s { int a:2, b:3; };")
676 ffi.verify("struct foo_s { int a:2, b:3; };")
677 s = ffi.new("struct foo_s *")
678 s.b = 3
679 with pytest.raises(OverflowError):
680 s.b = 4
681 assert s.b == 3
682
683 def test_struct_with_bitfield_enum():
684 ffi = FFI()
685 code = """
686 typedef enum { AA, BB, CC } foo_e;
687 typedef struct { foo_e f:2; } foo_s;
688 """
689 ffi.cdef(code)
690 ffi.verify(code)
691 s = ffi.new("foo_s *")
692 s.f = 2
693 assert s.f == 2
694
695 def test_unsupported_struct_with_bitfield_ellipsis():
696 ffi = FFI()
697 pytest.raises(NotImplementedError, ffi.cdef,
698 "struct foo_s { int a:2, b:3; ...; };")
699
700 def test_global_constants():
701 ffi = FFI()
702 # use 'static const int', as generally documented, although in this
703 # case the 'static' is completely ignored.
704 ffi.cdef("static const int AA, BB, CC, DD;")
705 lib = ffi.verify("#define AA 42\n"
706 "#define BB (-43) // blah\n"
707 "#define CC (22*2) /* foobar */\n"
708 "#define DD ((unsigned int)142) /* foo\nbar */\n")
709 assert lib.AA == 42
710 assert lib.BB == -43
711 assert lib.CC == 44
712 assert lib.DD == 142
713
714 def test_global_const_int_size():
715 # integer constants: ignore the declared type, always just use the value
716 for value in [-2**63, -2**31, -2**15,
717 2**15-1, 2**15, 2**31-1, 2**31, 2**32-1, 2**32,
718 2**63-1, 2**63, 2**64-1]:
719 ffi = FFI()
720 if value == int(ffi.cast("long long", value)):
721 if value < 0:
722 vstr = '(-%dLL-1)' % (~value,)
723 else:
724 vstr = '%dLL' % value
725 elif value == int(ffi.cast("unsigned long long", value)):
726 vstr = '%dULL' % value
727 else:
728 raise AssertionError(value)
729 ffi.cdef("static const unsigned short AA;")
730 lib = ffi.verify("#define AA %s\n" % vstr)
731 assert lib.AA == value
732 assert type(lib.AA) is type(int(lib.AA))
733
734 def test_global_constants_non_int():
735 ffi = FFI()
736 ffi.cdef("static char *const PP;")
737 lib = ffi.verify('static char *const PP = "testing!";\n')
738 assert ffi.typeof(lib.PP) == ffi.typeof("char *")
739 assert ffi.string(lib.PP) == b"testing!"
740
741 def test_nonfull_enum():
742 ffi = FFI()
743 ffi.cdef("enum ee { EE1, EE2, EE3, ... \n \t };")
744 pytest.raises(VerificationMissing, ffi.cast, 'enum ee', 'EE2')
745 ffi.verify("enum ee { EE1=10, EE2, EE3=-10, EE4 };")
746 assert ffi.string(ffi.cast('enum ee', 11)) == "EE2"
747 assert ffi.string(ffi.cast('enum ee', -10)) == "EE3"
748 #
749 # try again
750 ffi.verify("enum ee { EE1=10, EE2, EE3=-10, EE4 };")
751 assert ffi.string(ffi.cast('enum ee', 11)) == "EE2"
752 #
753 assert ffi.typeof("enum ee").relements == {'EE1': 10, 'EE2': 11, 'EE3': -10}
754 assert ffi.typeof("enum ee").elements == {10: 'EE1', 11: 'EE2', -10: 'EE3'}
755
756 def test_full_enum():
757 ffi = FFI()
758 ffi.cdef("enum ee { EE1, EE2, EE3 };")
759 ffi.verify("enum ee { EE1, EE2, EE3 };")
760 pytest.raises(VerificationError, ffi.verify, "enum ee { EE1, EE2 };")
761 e = pytest.raises(VerificationError, ffi.verify,
762 "enum ee { EE1, EE3, EE2 };")
763 assert str(e.value) == 'enum ee: EE2 has the real value 2, not 1'
764 # extra items cannot be seen and have no bad consequence anyway
765 lib = ffi.verify("enum ee { EE1, EE2, EE3, EE4 };")
766 assert lib.EE3 == 2
767
768 def test_enum_usage():
769 ffi = FFI()
770 ffi.cdef("enum ee { EE1,EE2 }; typedef struct { enum ee x; } *sp;")
771 lib = ffi.verify("enum ee { EE1,EE2 }; typedef struct { enum ee x; } *sp;")
772 assert lib.EE2 == 1
773 s = ffi.new("sp", [lib.EE2])
774 assert s.x == 1
775 s.x = 17
776 assert s.x == 17
777
778 def test_anonymous_enum():
779 ffi = FFI()
780 ffi.cdef("enum { EE1 }; enum { EE2, EE3 };")
781 lib = ffi.verify("enum { EE1 }; enum { EE2, EE3 };")
782 assert lib.EE1 == 0
783 assert lib.EE2 == 0
784 assert lib.EE3 == 1
785
786 def test_nonfull_anonymous_enum():
787 ffi = FFI()
788 ffi.cdef("enum { EE1, ... }; enum { EE3, ... };")
789 lib = ffi.verify("enum { EE2, EE1 }; enum { EE3 };")
790 assert lib.EE1 == 1
791 assert lib.EE3 == 0
792
793 def test_nonfull_enum_syntax2():
794 ffi = FFI()
795 ffi.cdef("enum ee { EE1, EE2=\t..., EE3 };")
796 pytest.raises(VerificationMissing, ffi.cast, 'enum ee', 'EE1')
797 ffi.verify("enum ee { EE1=10, EE2, EE3=-10, EE4 };")
798 assert ffi.string(ffi.cast('enum ee', 11)) == 'EE2'
799 assert ffi.string(ffi.cast('enum ee', -10)) == 'EE3'
800 #
801 ffi = FFI()
802 ffi.cdef("enum ee { EE1, EE2=\t... };")
803 pytest.raises(VerificationMissing, ffi.cast, 'enum ee', 'EE1')
804 ffi.verify("enum ee { EE1=10, EE2, EE3=-10, EE4 };")
805 assert ffi.string(ffi.cast('enum ee', 11)) == 'EE2'
806 #
807 ffi = FFI()
808 ffi.cdef("enum ee2 { EE4=..., EE5=..., ... };")
809 ffi.verify("enum ee2 { EE4=-1234-5, EE5 }; ")
810 assert ffi.string(ffi.cast('enum ee2', -1239)) == 'EE4'
811 assert ffi.string(ffi.cast('enum ee2', -1238)) == 'EE5'
812
813 def test_nonfull_enum_bug3():
814 ffi = FFI()
815 ffi.cdef("enum ee2 { EE4=..., EE5=... };")
816 ffi.cdef("enum ee6 { EE7=10, EE8=..., EE9=... };")
817
818 def test_get_set_errno():
819 ffi = FFI()
820 ffi.cdef("int foo(int);")
821 lib = ffi.verify("""
822 static int foo(int x)
823 {
824 errno += 1;
825 return x * 7;
826 }
827 """)
828 ffi.errno = 15
829 assert lib.foo(6) == 42
830 assert ffi.errno == 16
831
832 def test_define_int():
833 ffi = FFI()
834 ffi.cdef("#define FOO ...\n"
835 "\t#\tdefine\tBAR\t...\t\n"
836 "#define BAZ ...\n")
837 lib = ffi.verify("#define FOO 42\n"
838 "#define BAR (-44)\n"
839 "#define BAZ 0xffffffffffffffffULL\n")
840 assert lib.FOO == 42
841 assert lib.BAR == -44
842 assert lib.BAZ == 0xffffffffffffffff
843
844 def test_access_variable():
845 ffi = FFI()
846 ffi.cdef("static int foo(void);\n"
847 "static int somenumber;")
848 lib = ffi.verify("""
849 static int somenumber = 2;
850 static int foo(void) {
851 return somenumber * 7;
852 }
853 """)
854 assert lib.somenumber == 2
855 assert lib.foo() == 14
856 lib.somenumber = -6
857 assert lib.foo() == -42
858 assert lib.somenumber == -6
859 lib.somenumber = 2 # reset for the next run, if any
860
861 def test_access_address_of_variable():
862 # access the address of 'somenumber': need a trick
863 ffi = FFI()
864 ffi.cdef("static int somenumber; static int *const somenumberptr;")
865 lib = ffi.verify("""
866 static int somenumber = 2;
867 #define somenumberptr (&somenumber)
868 """)
869 assert lib.somenumber == 2
870 lib.somenumberptr[0] = 42
871 assert lib.somenumber == 42
872 lib.somenumber = 2 # reset for the next run, if any
873
874 def test_access_array_variable(length=5):
875 ffi = FFI()
876 ffi.cdef("int foo(int);\n"
877 "static int somenumber[%s];" % (length,))
878 lib = ffi.verify("""
879 static int somenumber[] = {2, 2, 3, 4, 5};
880 static int foo(int i) {
881 return somenumber[i] * 7;
882 }
883 """)
884 if length == '':
885 # a global variable of an unknown array length is implicitly
886 # transformed into a global pointer variable, because we can only
887 # work with array instances whose length we know. using a pointer
888 # instead of an array gives the correct effects.
889 assert repr(lib.somenumber).startswith("<cdata 'int *' 0x")
890 pytest.raises(TypeError, len, lib.somenumber)
891 else:
892 assert repr(lib.somenumber).startswith("<cdata 'int[%s]' 0x" % length)
893 assert len(lib.somenumber) == 5
894 assert lib.somenumber[3] == 4
895 assert lib.foo(3) == 28
896 lib.somenumber[3] = -6
897 assert lib.foo(3) == -42
898 assert lib.somenumber[3] == -6
899 assert lib.somenumber[4] == 5
900 lib.somenumber[3] = 4 # reset for the next run, if any
901
902 def test_access_array_variable_length_hidden():
903 test_access_array_variable(length='')
904
905 def test_access_struct_variable():
906 ffi = FFI()
907 ffi.cdef("struct foo { int x; ...; };\n"
908 "int foo(int);\n"
909 "static struct foo stuff;")
910 lib = ffi.verify("""
911 struct foo { int x, y, z; };
912 static struct foo stuff = {2, 5, 8};
913 static int foo(int i) {
914 switch (i) {
915 case 0: return stuff.x * 7;
916 case 1: return stuff.y * 7;
917 case 2: return stuff.z * 7;
918 }
919 return -1;
920 }
921 """)
922 assert lib.stuff.x == 2
923 assert lib.foo(0) == 14
924 assert lib.foo(1) == 35
925 assert lib.foo(2) == 56
926 lib.stuff.x = -6
927 assert lib.foo(0) == -42
928 assert lib.foo(1) == 35
929 lib.stuff.x = 2 # reset for the next run, if any
930
931 def test_access_callback():
932 ffi = FFI()
933 ffi.cdef("static int (*cb)(int);\n"
934 "static int foo(int);\n"
935 "static void reset_cb(void);")
936 lib = ffi.verify("""
937 static int g(int x) { return x * 7; }
938 static int (*cb)(int);
939 static int foo(int i) { return cb(i) - 1; }
940 static void reset_cb(void) { cb = g; }
941 """)
942 lib.reset_cb()
943 assert lib.foo(6) == 41
944 my_callback = ffi.callback("int(*)(int)", lambda n: n * 222)
945 lib.cb = my_callback
946 assert lib.foo(4) == 887
947
948 def test_access_callback_function_typedef():
949 ffi = FFI()
950 ffi.cdef("typedef int mycallback_t(int);\n"
951 "static mycallback_t *cb;\n"
952 "static int foo(int);\n"
953 "static void reset_cb(void);")
954 lib = ffi.verify("""
955 static int g(int x) { return x * 7; }
956 static int (*cb)(int);
957 static int foo(int i) { return cb(i) - 1; }
958 static void reset_cb(void) { cb = g; }
959 """)
960 lib.reset_cb()
961 assert lib.foo(6) == 41
962 my_callback = ffi.callback("int(*)(int)", lambda n: n * 222)
963 lib.cb = my_callback
964 assert lib.foo(4) == 887
965
966 def test_ctypes_backend_forces_generic_engine():
967 from cffi.backend_ctypes import CTypesBackend
968 ffi = FFI(backend=CTypesBackend())
969 ffi.cdef("int func(int a);")
970 lib = ffi.verify("int func(int a) { return a * 42; }")
971 assert not hasattr(lib, '_cffi_python_module')
972 assert hasattr(lib, '_cffi_generic_module')
973 assert lib.func(100) == 4200
974
975 def test_call_with_struct_ptr():
976 ffi = FFI()
977 ffi.cdef("typedef struct { int x; ...; } foo_t; int foo(foo_t *);")
978 lib = ffi.verify("""
979 typedef struct { int y, x; } foo_t;
980 static int foo(foo_t *f) { return f->x * 7; }
981 """)
982 f = ffi.new("foo_t *")
983 f.x = 6
984 assert lib.foo(f) == 42
985
986 def test_unknown_type():
987 ffi = FFI()
988 ffi.cdef("""
989 typedef ... token_t;
990 int foo(token_t *);
991 #define TOKEN_SIZE ...
992 """)
993 lib = ffi.verify("""
994 typedef float token_t;
995 static int foo(token_t *tk) {
996 if (!tk)
997 return -42;
998 *tk += 1.601f;
999 return (int)*tk;
1000 }
1001 #define TOKEN_SIZE sizeof(token_t)
1002 """)
1003 # we cannot let ffi.new("token_t *") work, because we don't know ahead of
1004 # time if it's ok to ask 'sizeof(token_t)' in the C code or not.
1005 # See test_unknown_type_2. Workaround.
1006 tkmem = ffi.new("char[]", lib.TOKEN_SIZE) # zero-initialized
1007 tk = ffi.cast("token_t *", tkmem)
1008 results = [lib.foo(tk) for i in range(6)]
1009 assert results == [1, 3, 4, 6, 8, 9]
1010 assert lib.foo(ffi.NULL) == -42
1011
1012 def test_unknown_type_2():
1013 ffi = FFI()
1014 ffi.cdef("typedef ... token_t;")
1015 lib = ffi.verify("typedef struct token_s token_t;")
1016 # assert did not crash, even though 'sizeof(token_t)' is not valid in C.
1017
1018 def test_unknown_type_3():
1019 ffi = FFI()
1020 ffi.cdef("""
1021 typedef ... *token_p;
1022 token_p foo(token_p);
1023 """)
1024 lib = ffi.verify("""
1025 typedef struct _token_s *token_p;
1026 token_p foo(token_p arg) {
1027 if (arg)
1028 return (token_p)0x12347;
1029 else
1030 return (token_p)0x12345;
1031 }
1032 """)
1033 p = lib.foo(ffi.NULL)
1034 assert int(ffi.cast("intptr_t", p)) == 0x12345
1035 q = lib.foo(p)
1036 assert int(ffi.cast("intptr_t", q)) == 0x12347
1037
1038 def test_varargs():
1039 ffi = FFI()
1040 ffi.cdef("int foo(int x, ...);")
1041 lib = ffi.verify("""
1042 int foo(int x, ...) {
1043 va_list vargs;
1044 va_start(vargs, x);
1045 x -= va_arg(vargs, int);
1046 x -= va_arg(vargs, int);
1047 va_end(vargs);
1048 return x;
1049 }
1050 """)
1051 assert lib.foo(50, ffi.cast("int", 5), ffi.cast("int", 3)) == 42
1052
1053 def test_varargs_exact():
1054 if sys.platform == 'win32':
1055 pytest.skip("XXX fixme: only gives warnings")
1056 ffi = FFI()
1057 ffi.cdef("int foo(int x, ...);")
1058 pytest.raises(VerificationError, ffi.verify, """
1059 int foo(long long x, ...) {
1060 return x;
1061 }
1062 """)
1063
1064 def test_varargs_struct():
1065 ffi = FFI()
1066 ffi.cdef("struct foo_s { char a; int b; }; int foo(int x, ...);")
1067 lib = ffi.verify("""
1068 struct foo_s {
1069 char a; int b;
1070 };
1071 int foo(int x, ...) {
1072 va_list vargs;
1073 struct foo_s s;
1074 va_start(vargs, x);
1075 s = va_arg(vargs, struct foo_s);
1076 va_end(vargs);
1077 return s.a - s.b;
1078 }
1079 """)
1080 s = ffi.new("struct foo_s *", [b'B', 1])
1081 assert lib.foo(50, s[0]) == ord('A')
1082
1083 def test_autofilled_struct_as_argument():
1084 ffi = FFI()
1085 ffi.cdef("struct foo_s { long a; double b; ...; };\n"
1086 "int foo(struct foo_s);")
1087 lib = ffi.verify("""
1088 struct foo_s {
1089 double b;
1090 long a;
1091 };
1092 int foo(struct foo_s s) {
1093 return (int)s.a - (int)s.b;
1094 }
1095 """)
1096 s = ffi.new("struct foo_s *", [100, 1])
1097 assert lib.foo(s[0]) == 99
1098 assert lib.foo([100, 1]) == 99
1099
1100 def test_autofilled_struct_as_argument_dynamic():
1101 ffi = FFI()
1102 ffi.cdef("struct foo_s { long a; ...; };\n"
1103 "static int (*foo)(struct foo_s);")
1104 lib = ffi.verify("""
1105 struct foo_s {
1106 double b;
1107 long a;
1108 };
1109 int foo1(struct foo_s s) {
1110 return (int)s.a - (int)s.b;
1111 }
1112 static int (*foo)(struct foo_s s) = &foo1;
1113 """)
1114 e = pytest.raises(NotImplementedError, lib.foo, "?")
1115 msg = ("ctype 'struct foo_s' not supported as argument. It is a struct "
1116 'declared with "...;", but the C calling convention may depend on '
1117 "the missing fields; or, it contains anonymous struct/unions. "
1118 "Such structs are only supported as argument "
1119 "if the function is 'API mode' and non-variadic (i.e. declared "
1120 "inside ffibuilder.cdef()+ffibuilder.set_source() and not taking "
1121 "a final '...' argument)")
1122 assert str(e.value) == msg
1123
1124 def test_func_returns_struct():
1125 ffi = FFI()
1126 ffi.cdef("""
1127 struct foo_s { int aa, bb; };
1128 struct foo_s foo(int a, int b);
1129 """)
1130 lib = ffi.verify("""
1131 struct foo_s { int aa, bb; };
1132 struct foo_s foo(int a, int b) {
1133 struct foo_s r;
1134 r.aa = a*a;
1135 r.bb = b*b;
1136 return r;
1137 }
1138 """)
1139 s = lib.foo(6, 7)
1140 assert repr(s) == "<cdata 'struct foo_s' owning 8 bytes>"
1141 assert s.aa == 36
1142 assert s.bb == 49
1143
1144 def test_func_as_funcptr():
1145 ffi = FFI()
1146 ffi.cdef("int *(*const fooptr)(void);")
1147 lib = ffi.verify("""
1148 int *foo(void) {
1149 return (int*)"foobar";
1150 }
1151 int *(*fooptr)(void) = foo;
1152 """)
1153 foochar = ffi.cast("char *(*)(void)", lib.fooptr)
1154 s = foochar()
1155 assert ffi.string(s) == b"foobar"
1156
1157 def test_funcptr_as_argument():
1158 ffi = FFI()
1159 ffi.cdef("""
1160 void qsort(void *base, size_t nel, size_t width,
1161 int (*compar)(const void *, const void *));
1162 """)
1163 ffi.verify("#include <stdlib.h>")
1164
1165 def test_func_as_argument():
1166 ffi = FFI()
1167 ffi.cdef("""
1168 void qsort(void *base, size_t nel, size_t width,
1169 int compar(const void *, const void *));
1170 """)
1171 ffi.verify("#include <stdlib.h>")
1172
1173 def test_array_as_argument():
1174 ffi = FFI()
1175 ffi.cdef("""
1176 size_t strlen(char string[]);
1177 """)
1178 ffi.verify("#include <string.h>")
1179
1180 def test_enum_as_argument():
1181 ffi = FFI()
1182 ffi.cdef("""
1183 enum foo_e { AA, BB, ... };
1184 int foo_func(enum foo_e);
1185 """)
1186 lib = ffi.verify("""
1187 enum foo_e { AA, CC, BB };
1188 int foo_func(enum foo_e e) { return (int)e; }
1189 """)
1190 assert lib.foo_func(lib.BB) == 2
1191 pytest.raises(TypeError, lib.foo_func, "BB")
1192
1193 def test_enum_as_function_result():
1194 ffi = FFI()
1195 ffi.cdef("""
1196 enum foo_e { AA, BB, ... };
1197 enum foo_e foo_func(int x);
1198 """)
1199 lib = ffi.verify("""
1200 enum foo_e { AA, CC, BB };
1201 enum foo_e foo_func(int x) { return (enum foo_e)x; }
1202 """)
1203 assert lib.foo_func(lib.BB) == lib.BB == 2
1204
1205 def test_enum_values():
1206 ffi = FFI()
1207 ffi.cdef("enum enum1_e { AA, BB };")
1208 lib = ffi.verify("enum enum1_e { AA, BB };")
1209 assert lib.AA == 0
1210 assert lib.BB == 1
1211 assert ffi.string(ffi.cast("enum enum1_e", 1)) == 'BB'
1212
1213 def test_typedef_complete_enum():
1214 ffi = FFI()
1215 ffi.cdef("typedef enum { AA, BB } enum1_t;")
1216 lib = ffi.verify("typedef enum { AA, BB } enum1_t;")
1217 assert ffi.string(ffi.cast("enum1_t", 1)) == 'BB'
1218 assert lib.AA == 0
1219 assert lib.BB == 1
1220
1221 def test_typedef_broken_complete_enum():
1222 ffi = FFI()
1223 ffi.cdef("typedef enum { AA, BB } enum1_t;")
1224 pytest.raises(VerificationError, ffi.verify,
1225 "typedef enum { AA, CC, BB } enum1_t;")
1226
1227 def test_typedef_incomplete_enum():
1228 ffi = FFI()
1229 ffi.cdef("typedef enum { AA, BB, ... } enum1_t;")
1230 lib = ffi.verify("typedef enum { AA, CC, BB } enum1_t;")
1231 assert ffi.string(ffi.cast("enum1_t", 1)) == '1'
1232 assert ffi.string(ffi.cast("enum1_t", 2)) == 'BB'
1233 assert lib.AA == 0
1234 assert lib.BB == 2
1235
1236 def test_typedef_enum_as_argument():
1237 ffi = FFI()
1238 ffi.cdef("""
1239 typedef enum { AA, BB, ... } foo_t;
1240 int foo_func(foo_t);
1241 """)
1242 lib = ffi.verify("""
1243 typedef enum { AA, CC, BB } foo_t;
1244 int foo_func(foo_t e) { return (int)e; }
1245 """)
1246 assert lib.foo_func(lib.BB) == lib.BB == 2
1247 pytest.raises(TypeError, lib.foo_func, "BB")
1248
1249 def test_typedef_enum_as_function_result():
1250 ffi = FFI()
1251 ffi.cdef("""
1252 typedef enum { AA, BB, ... } foo_t;
1253 foo_t foo_func(int x);
1254 """)
1255 lib = ffi.verify("""
1256 typedef enum { AA, CC, BB } foo_t;
1257 foo_t foo_func(int x) { return (foo_t)x; }
1258 """)
1259 assert lib.foo_func(lib.BB) == lib.BB == 2
1260
1261 def test_function_typedef():
1262 ffi = FFI()
1263 ffi.cdef("""
1264 typedef double func_t(double);
1265 func_t sin;
1266 """)
1267 lib = ffi.verify('#include <math.h>', libraries=lib_m)
1268 assert lib.sin(1.23) == math.sin(1.23)
1269
1270 def test_opaque_integer_as_function_result():
1271 #import platform
1272 #if platform.machine().startswith('sparc'):
1273 # pytest.skip('Breaks horribly on sparc (SIGILL + corrupted stack)')
1274 #elif platform.machine() == 'mips64' and sys.maxsize > 2**32:
1275 # pytest.skip('Segfaults on mips64el')
1276 # XXX bad abuse of "struct { ...; }". It only works a bit by chance
1277 # anyway. XXX think about something better :-(
1278 ffi = FFI()
1279 ffi.cdef("""
1280 typedef struct { ...; } myhandle_t;
1281 myhandle_t foo(void);
1282 """)
1283 lib = ffi.verify("""
1284 typedef short myhandle_t;
1285 myhandle_t foo(void) { return 42; }
1286 """)
1287 h = lib.foo()
1288 assert ffi.sizeof(h) == ffi.sizeof("short")
1289
1290 def test_return_partial_struct():
1291 ffi = FFI()
1292 ffi.cdef("""
1293 typedef struct { int x; ...; } foo_t;
1294 foo_t foo(void);
1295 """)
1296 lib = ffi.verify("""
1297 typedef struct { int y, x; } foo_t;
1298 foo_t foo(void) { foo_t r = { 45, 81 }; return r; }
1299 """)
1300 h = lib.foo()
1301 assert ffi.sizeof(h) == 2 * ffi.sizeof("int")
1302 assert h.x == 81
1303
1304 def test_take_and_return_partial_structs():
1305 ffi = FFI()
1306 ffi.cdef("""
1307 typedef struct { int x; ...; } foo_t;
1308 foo_t foo(foo_t, foo_t);
1309 """)
1310 lib = ffi.verify("""
1311 typedef struct { int y, x; } foo_t;
1312 foo_t foo(foo_t a, foo_t b) {
1313 foo_t r = { 100, a.x * 5 + b.x * 7 };
1314 return r;
1315 }
1316 """)
1317 args = ffi.new("foo_t[3]")
1318 args[0].x = 1000
1319 args[2].x = -498
1320 h = lib.foo(args[0], args[2])
1321 assert ffi.sizeof(h) == 2 * ffi.sizeof("int")
1322 assert h.x == 1000 * 5 - 498 * 7
1323
1324 def test_cannot_name_struct_type():
1325 ffi = FFI()
1326 ffi.cdef("typedef struct { int x; } **sp; void foo(sp);")
1327 e = pytest.raises(VerificationError, ffi.verify,
1328 "typedef struct { int x; } **sp; void foo(sp x) { }")
1329 assert 'in argument of foo: unknown type name' in str(e.value)
1330
1331 def test_dont_check_unnamable_fields():
1332 ffi = FFI()
1333 ffi.cdef("struct foo_s { struct { int x; } someone; };")
1334 ffi.verify("struct foo_s { struct { int x; } someone; };")
1335 # assert did not crash
1336
1337 def test_nested_anonymous_struct_exact():
1338 if sys.platform == 'win32':
1339 pytest.skip("nested anonymous struct/union")
1340 ffi = FFI()
1341 ffi.cdef("""
1342 struct foo_s { struct { int a; char b; }; union { char c, d; }; };
1343 """)
1344 ffi.verify("""
1345 struct foo_s { struct { int a; char b; }; union { char c, d; }; };
1346 """)
1347 p = ffi.new("struct foo_s *")
1348 assert ffi.sizeof(p[0]) == 3 * ffi.sizeof("int") # with alignment
1349 p.a = 1234567
1350 p.b = b'X'
1351 p.c = b'Y'
1352 assert p.a == 1234567
1353 assert p.b == b'X'
1354 assert p.c == b'Y'
1355 assert p.d == b'Y'
1356
1357 def test_nested_anonymous_struct_exact_error():
1358 if sys.platform == 'win32':
1359 pytest.skip("nested anonymous struct/union")
1360 ffi = FFI()
1361 ffi.cdef("""
1362 struct foo_s { struct { int a; char b; }; union { char c, d; }; };
1363 """)
1364 pytest.raises(VerificationError, ffi.verify, """
1365 struct foo_s { struct { int a; short b; }; union { char c, d; }; };
1366 """)
1367 pytest.raises(VerificationError, ffi.verify, """
1368 struct foo_s { struct { int a; char e, b; }; union { char c, d; }; };
1369 """)
1370
1371 def test_nested_anonymous_struct_inexact_1():
1372 ffi = FFI()
1373 ffi.cdef("""
1374 struct foo_s { struct { char b; ...; }; union { char c, d; }; };
1375 """)
1376 ffi.verify("""
1377 struct foo_s { int a, padding; char c, d, b; };
1378 """)
1379 assert ffi.sizeof("struct foo_s") == 3 * ffi.sizeof("int")
1380
1381 def test_nested_anonymous_struct_inexact_2():
1382 ffi = FFI()
1383 ffi.cdef("""
1384 struct foo_s { union { char c, d; }; struct { int a; char b; }; ...; };
1385 """)
1386 ffi.verify("""
1387 struct foo_s { int a, padding; char c, d, b; };
1388 """)
1389 assert ffi.sizeof("struct foo_s") == 3 * ffi.sizeof("int")
1390
1391 def test_ffi_union():
1392 ffi = FFI()
1393 ffi.cdef("union foo_u { char x; long *z; };")
1394 ffi.verify("union foo_u { char x; int y; long *z; };")
1395
1396 def test_ffi_union_partial():
1397 ffi = FFI()
1398 ffi.cdef("union foo_u { char x; ...; };")
1399 ffi.verify("union foo_u { char x; int y; };")
1400 assert ffi.sizeof("union foo_u") == 4
1401
1402 def test_ffi_union_with_partial_struct():
1403 ffi = FFI()
1404 ffi.cdef("struct foo_s { int x; ...; }; union foo_u { struct foo_s s; };")
1405 ffi.verify("struct foo_s { int a; int x; }; "
1406 "union foo_u { char b[32]; struct foo_s s; };")
1407 assert ffi.sizeof("struct foo_s") == 8
1408 assert ffi.sizeof("union foo_u") == 32
1409
1410 def test_ffi_union_partial_2():
1411 ffi = FFI()
1412 ffi.cdef("typedef union { char x; ...; } u1;")
1413 ffi.verify("typedef union { char x; int y; } u1;")
1414 assert ffi.sizeof("u1") == 4
1415
1416 def test_ffi_union_with_partial_struct_2():
1417 ffi = FFI()
1418 ffi.cdef("typedef struct { int x; ...; } s1;"
1419 "typedef union { s1 s; } u1;")
1420 ffi.verify("typedef struct { int a; int x; } s1; "
1421 "typedef union { char b[32]; s1 s; } u1;")
1422 assert ffi.sizeof("s1") == 8
1423 assert ffi.sizeof("u1") == 32
1424 assert ffi.offsetof("u1", "s") == 0
1425
1426 def test_ffi_struct_packed():
1427 if sys.platform == 'win32':
1428 pytest.skip("needs a GCC extension")
1429 ffi = FFI()
1430 ffi.cdef("struct foo_s { int b; ...; };")
1431 ffi.verify("""
1432 struct foo_s {
1433 char a;
1434 int b;
1435 } __attribute__((packed));
1436 """)
1437
1438 def test_tmpdir():
1439 import tempfile, os
1440 from extra_tests.cffi_tests.udir import udir
1441 tmpdir = tempfile.mkdtemp(dir=str(udir))
1442 ffi = FFI()
1443 ffi.cdef("int foo(int);")
1444 lib = ffi.verify("int foo(int a) { return a + 42; }", tmpdir=tmpdir)
1445 assert os.listdir(tmpdir)
1446 assert lib.foo(100) == 142
1447
1448 def test_relative_to():
1449 import tempfile, os
1450 from extra_tests.cffi_tests.udir import udir
1451 tmpdir = tempfile.mkdtemp(dir=str(udir))
1452 ffi = FFI()
1453 ffi.cdef("int foo(int);")
1454 f = open(os.path.join(tmpdir, 'foo.h'), 'w')
1455 f.write("int foo(int a) { return a + 42; }\n")
1456 f.close()
1457 lib = ffi.verify('#include "foo.h"',
1458 include_dirs=['.'],
1459 relative_to=os.path.join(tmpdir, 'x'))
1460 assert lib.foo(100) == 142
1461
1462 def test_bug1():
1463 ffi = FFI()
1464 ffi.cdef("""
1465 typedef struct tdlhandle_s { ...; } *tdl_handle_t;
1466 typedef struct my_error_code_ {
1467 tdl_handle_t *rh;
1468 } my_error_code_t;
1469 """)
1470 ffi.verify("""
1471 typedef struct tdlhandle_s { int foo; } *tdl_handle_t;
1472 typedef struct my_error_code_ {
1473 tdl_handle_t *rh;
1474 } my_error_code_t;
1475 """)
1476
1477 def test_bool():
1478 if sys.platform == 'win32':
1479 pytest.skip("_Bool not in MSVC")
1480 ffi = FFI()
1481 ffi.cdef("struct foo_s { _Bool x; };"
1482 "_Bool foo(_Bool); static _Bool (*foop)(_Bool);")
1483 lib = ffi.verify("""
1484 struct foo_s { _Bool x; };
1485 int foo(int arg) {
1486 return !arg;
1487 }
1488 _Bool _foofunc(_Bool x) {
1489 return !x;
1490 }
1491 static _Bool (*foop)(_Bool) = _foofunc;
1492 """)
1493 p = ffi.new("struct foo_s *")
1494 p.x = 1
1495 assert p.x is True
1496 with pytest.raises(OverflowError):
1497 p.x = -1
1498 with pytest.raises(TypeError):
1499 p.x = 0.0
1500 assert lib.foop(1) is False
1501 assert lib.foop(True) is False
1502 assert lib.foop(0) is True
1503 pytest.raises(OverflowError, lib.foop, 42)
1504 pytest.raises(TypeError, lib.foop, 0.0)
1505 assert lib.foo(1) is False
1506 assert lib.foo(True) is False
1507 assert lib.foo(0) is True
1508 pytest.raises(OverflowError, lib.foo, 42)
1509 pytest.raises(TypeError, lib.foo, 0.0)
1510 assert int(ffi.cast("_Bool", long(1))) == 1
1511 assert int(ffi.cast("_Bool", long(0))) == 0
1512 assert int(ffi.cast("_Bool", long(-1))) == 1
1513 assert int(ffi.cast("_Bool", 10**200)) == 1
1514 assert int(ffi.cast("_Bool", 10**40000)) == 1
1515 #
1516 class Foo(object):
1517 def __int__(self):
1518 self.seen = 1
1519 return result
1520 f = Foo()
1521 f.seen = 0
1522 result = 42
1523 assert int(ffi.cast("_Bool", f)) == 1
1524 assert f.seen
1525 f.seen = 0
1526 result = 0
1527 assert int(ffi.cast("_Bool", f)) == 0
1528 assert f.seen
1529 #
1530 pytest.raises(TypeError, ffi.cast, "_Bool", [])
1531
1532 def test_bool_on_long_double():
1533 if sys.platform == 'win32':
1534 pytest.skip("_Bool not in MSVC")
1535 f = 1E-250
1536 if f == 0.0 or f*f != 0.0:
1537 pytest.skip("unexpected precision")
1538 ffi = FFI()
1539 ffi.cdef("long double square(long double f); _Bool opposite(_Bool);")
1540 lib = ffi.verify("long double square(long double f) { return f*f; }\n"
1541 "_Bool opposite(_Bool x) { return !x; }")
1542 f0 = lib.square(0.0)
1543 f2 = lib.square(f)
1544 f3 = lib.square(f * 2.0)
1545 if repr(f2) == repr(f3):
1546 pytest.skip("long double doesn't have enough precision")
1547 assert float(f0) == float(f2) == float(f3) == 0.0 # too tiny for 'double'
1548 assert int(ffi.cast("_Bool", f2)) == 1
1549 assert int(ffi.cast("_Bool", f3)) == 1
1550 assert int(ffi.cast("_Bool", f0)) == 0
1551 pytest.raises(TypeError, lib.opposite, f2)
1552
1553 def test_cannot_pass_float():
1554 for basetype in ['char', 'short', 'int', 'long', 'long long']:
1555 for sign in ['signed', 'unsigned']:
1556 type = '%s %s' % (sign, basetype)
1557 ffi = FFI()
1558 ffi.cdef("struct foo_s { %s x; };\n"
1559 "int foo(%s);" % (type, type))
1560 lib = ffi.verify("""
1561 struct foo_s { %s x; };
1562 int foo(%s arg) {
1563 return !arg;
1564 }
1565 """ % (type, type))
1566 p = ffi.new("struct foo_s *")
1567 with pytest.raises(TypeError):
1568 p.x = 0.0
1569 assert lib.foo(42) == 0
1570 assert lib.foo(0) == 1
1571 pytest.raises(TypeError, lib.foo, 0.0)
1572
1573 def test_cast_from_int_type_to_bool():
1574 ffi = FFI()
1575 for basetype in ['char', 'short', 'int', 'long', 'long long']:
1576 for sign in ['signed', 'unsigned']:
1577 type = '%s %s' % (sign, basetype)
1578 assert int(ffi.cast("_Bool", ffi.cast(type, 42))) == 1
1579 assert int(ffi.cast("bool", ffi.cast(type, 42))) == 1
1580 assert int(ffi.cast("_Bool", ffi.cast(type, 0))) == 0
1581
1582 def test_addressof():
1583 ffi = FFI()
1584 ffi.cdef("""
1585 struct point_s { int x, y; };
1586 struct foo_s { int z; struct point_s point; };
1587 struct point_s sum_coord(struct point_s *);
1588 """)
1589 lib = ffi.verify("""
1590 struct point_s { int x, y; };
1591 struct foo_s { int z; struct point_s point; };
1592 struct point_s sum_coord(struct point_s *point) {
1593 struct point_s r;
1594 r.x = point->x + point->y;
1595 r.y = point->x - point->y;
1596 return r;
1597 }
1598 """)
1599 p = ffi.new("struct foo_s *")
1600 p.point.x = 16
1601 p.point.y = 9
1602 pytest.raises(TypeError, lib.sum_coord, p.point)
1603 res = lib.sum_coord(ffi.addressof(p.point))
1604 assert res.x == 25
1605 assert res.y == 7
1606 res2 = lib.sum_coord(ffi.addressof(res))
1607 assert res2.x == 32
1608 assert res2.y == 18
1609 pytest.raises(TypeError, lib.sum_coord, res2)
1610
1611 def test_callback_in_thread():
1612 if sys.platform == 'win32':
1613 pytest.skip("pthread only")
1614 import os, subprocess
1615 from cffi import _imp_emulation as imp
1616 arg = os.path.join(os.path.dirname(__file__), 'callback_in_thread.py')
1617 g = subprocess.Popen([sys.executable, arg,
1618 os.path.dirname(imp.find_module('cffi')[1])])
1619 result = g.wait()
1620 assert result == 0
1621
1622 def test_keepalive_lib():
1623 ffi = FFI()
1624 ffi.cdef("int foobar(void);")
1625 lib = ffi.verify("int foobar(void) { return 42; }")
1626 func = lib.foobar
1627 ffi_r = weakref.ref(ffi)
1628 lib_r = weakref.ref(lib)
1629 del ffi
1630 import gc; gc.collect() # lib stays alive
1631 assert lib_r() is not None
1632 assert ffi_r() is not None
1633 assert func() == 42
1634
1635 def test_keepalive_ffi():
1636 ffi = FFI()
1637 ffi.cdef("int foobar(void);")
1638 lib = ffi.verify("int foobar(void) { return 42; }")
1639 func = lib.foobar
1640 ffi_r = weakref.ref(ffi)
1641 lib_r = weakref.ref(lib)
1642 del lib
1643 import gc; gc.collect() # ffi stays alive
1644 assert ffi_r() is not None
1645 assert lib_r() is not None
1646 assert func() == 42
1647
1648 def test_FILE_stored_in_stdout():
1649 if not sys.platform.startswith('linux') or is_musl:
1650 pytest.skip("likely, we cannot assign to stdout")
1651 ffi = FFI()
1652 ffi.cdef("int printf(const char *, ...); FILE *setstdout(FILE *);")
1653 lib = ffi.verify("""
1654 #include <stdio.h>
1655 FILE *setstdout(FILE *f) {
1656 FILE *result = stdout;
1657 stdout = f;
1658 return result;
1659 }
1660 """)
1661 import os
1662 fdr, fdw = os.pipe()
1663 fw1 = os.fdopen(fdw, 'wb', 256)
1664 old_stdout = lib.setstdout(fw1)
1665 try:
1666 #
1667 fw1.write(b"X")
1668 r = lib.printf(b"hello, %d!\n", ffi.cast("int", 42))
1669 fw1.close()
1670 assert r == len("hello, 42!\n")
1671 #
1672 finally:
1673 lib.setstdout(old_stdout)
1674 #
1675 result = os.read(fdr, 256)
1676 os.close(fdr)
1677 # the 'X' might remain in the user-level buffer of 'fw1' and
1678 # end up showing up after the 'hello, 42!\n'
1679 assert result == b"Xhello, 42!\n" or result == b"hello, 42!\nX"
1680
1681 def test_FILE_stored_explicitly():
1682 ffi = FFI()
1683 ffi.cdef("int myprintf11(const char *, int); extern FILE *myfile;")
1684 lib = ffi.verify("""
1685 #include <stdio.h>
1686 FILE *myfile;
1687 int myprintf11(const char *out, int value) {
1688 return fprintf(myfile, out, value);
1689 }
1690 """)
1691 import os
1692 fdr, fdw = os.pipe()
1693 fw1 = os.fdopen(fdw, 'wb', 256)
1694 lib.myfile = ffi.cast("FILE *", fw1)
1695 #
1696 fw1.write(b"X")
1697 r = lib.myprintf11(b"hello, %d!\n", ffi.cast("int", 42))
1698 fw1.close()
1699 assert r == len("hello, 42!\n")
1700 #
1701 result = os.read(fdr, 256)
1702 os.close(fdr)
1703 # the 'X' might remain in the user-level buffer of 'fw1' and
1704 # end up showing up after the 'hello, 42!\n'
1705 assert result == b"Xhello, 42!\n" or result == b"hello, 42!\nX"
1706
1707 def test_global_array_with_missing_length():
1708 ffi = FFI()
1709 ffi.cdef("extern int fooarray[];")
1710 lib = ffi.verify("int fooarray[50];")
1711 assert repr(lib.fooarray).startswith("<cdata 'int *'")
1712
1713 def test_global_array_with_dotdotdot_length():
1714 ffi = FFI()
1715 ffi.cdef("extern int fooarray[...];")
1716 lib = ffi.verify("int fooarray[50];")
1717 assert repr(lib.fooarray).startswith("<cdata 'int[50]'")
1718
1719 def test_bad_global_array_with_dotdotdot_length():
1720 ffi = FFI()
1721 ffi.cdef("extern int fooarray[...];")
1722 pytest.raises(VerificationError, ffi.verify, "char fooarray[23];")
1723
1724 def test_struct_containing_struct():
1725 ffi = FFI()
1726 ffi.cdef("struct foo_s { ...; }; struct bar_s { struct foo_s f; ...; };")
1727 ffi.verify("struct foo_s { int x; }; struct bar_s { struct foo_s f; };")
1728 #
1729 ffi = FFI()
1730 ffi.cdef("struct foo_s { struct bar_s f; ...; }; struct bar_s { ...; };")
1731 ffi.verify("struct bar_s { int x; }; struct foo_s { struct bar_s f; };")
1732
1733 def test_struct_returned_by_func():
1734 ffi = FFI()
1735 ffi.cdef("typedef ... foo_t; foo_t myfunc(void);")
1736 e = pytest.raises(TypeError, ffi.verify,
1737 "typedef struct { int x; } foo_t; "
1738 "foo_t myfunc(void) { foo_t x = { 42 }; return x; }")
1739 assert str(e.value) == (
1740 "function myfunc: 'foo_t' is used as result type, but is opaque")
1741
1742 def test_include():
1743 ffi1 = FFI()
1744 ffi1.cdef("typedef struct { int x; ...; } foo_t;")
1745 ffi1.verify("typedef struct { int y, x; } foo_t;")
1746 ffi2 = FFI()
1747 ffi2.include(ffi1)
1748 ffi2.cdef("int myfunc(foo_t *);")
1749 lib = ffi2.verify("typedef struct { int y, x; } foo_t;"
1750 "int myfunc(foo_t *p) { return 42 * p->x; }")
1751 res = lib.myfunc(ffi2.new("foo_t *", {'x': 10}))
1752 assert res == 420
1753 res = lib.myfunc(ffi1.new("foo_t *", {'x': -10}))
1754 assert res == -420
1755
1756 def test_include_enum():
1757 ffi1 = FFI()
1758 ffi1.cdef("enum foo_e { AA, ... };")
1759 lib1 = ffi1.verify("enum foo_e { CC, BB, AA };")
1760 ffi2 = FFI()
1761 ffi2.include(ffi1)
1762 ffi2.cdef("int myfunc(enum foo_e);")
1763 lib2 = ffi2.verify("enum foo_e { CC, BB, AA };"
1764 "int myfunc(enum foo_e x) { return (int)x; }")
1765 res = lib2.myfunc(lib2.AA)
1766 assert res == 2
1767
1768 def test_named_pointer_as_argument():
1769 ffi = FFI()
1770 ffi.cdef("typedef struct { int x; } *mystruct_p;\n"
1771 "mystruct_p ff5a(mystruct_p);")
1772 lib = ffi.verify("typedef struct { int x; } *mystruct_p;\n"
1773 "mystruct_p ff5a(mystruct_p p) { p->x += 40; return p; }")
1774 p = ffi.new("mystruct_p", [-2])
1775 q = lib.ff5a(p)
1776 assert q == p
1777 assert p.x == 38
1778
1779 def test_enum_size():
1780 cases = [('123', 4, 4294967295),
1781 ('4294967295U', 4, 4294967295),
1782 ('-123', 4, -1),
1783 ('-2147483647-1', 4, -1),
1784 ]
1785 if FFI().sizeof("long") == 8:
1786 cases += [('4294967296L', 8, 2**64-1),
1787 ('%dUL' % (2**64-1), 8, 2**64-1),
1788 ('-2147483649L', 8, -1),
1789 ('%dL-1L' % (1-2**63), 8, -1)]
1790 for hidden_value, expected_size, expected_minus1 in cases:
1791 if sys.platform == 'win32' and 'U' in hidden_value:
1792 continue # skipped on Windows
1793 ffi = FFI()
1794 ffi.cdef("enum foo_e { AA, BB, ... };")
1795 lib = ffi.verify("enum foo_e { AA, BB=%s };" % hidden_value)
1796 assert lib.AA == 0
1797 assert lib.BB == eval(hidden_value.replace('U', '').replace('L', ''))
1798 assert ffi.sizeof("enum foo_e") == expected_size
1799 assert int(ffi.cast("enum foo_e", -1)) == expected_minus1
1800 # test with the large value hidden:
1801 # disabled so far, doesn't work
1802 ## for hidden_value, expected_size, expected_minus1 in cases:
1803 ## ffi = FFI()
1804 ## ffi.cdef("enum foo_e { AA, BB, ... };")
1805 ## lib = ffi.verify("enum foo_e { AA, BB=%s };" % hidden_value)
1806 ## assert lib.AA == 0
1807 ## assert ffi.sizeof("enum foo_e") == expected_size
1808 ## assert int(ffi.cast("enum foo_e", -1)) == expected_minus1
1809
1810 def test_enum_bug118():
1811 maxulong = 256 ** FFI().sizeof("unsigned long") - 1
1812 for c1, c2, c2c in [(0xffffffff, -1, ''),
1813 (maxulong, -1, ''),
1814 (-1, 0xffffffff, 'U'),
1815 (-1, maxulong, 'UL')]:
1816 if c2c and sys.platform == 'win32':
1817 continue # enums may always be signed with MSVC
1818 ffi = FFI()
1819 ffi.cdef("enum foo_e { AA=%s };" % c1)
1820 e = pytest.raises(VerificationError, ffi.verify,
1821 "enum foo_e { AA=%s%s };" % (c2, c2c))
1822 assert str(e.value) == ('enum foo_e: AA has the real value %d, not %d'
1823 % (c2, c1))
1824
1825 def test_string_to_voidp_arg():
1826 ffi = FFI()
1827 ffi.cdef("int myfunc(void *);")
1828 lib = ffi.verify("int myfunc(void *p) { return ((signed char *)p)[0]; }")
1829 res = lib.myfunc(b"hi!")
1830 assert res == ord(b"h")
1831 p = ffi.new("char[]", b"gah")
1832 res = lib.myfunc(p)
1833 assert res == ord(b"g")
1834 res = lib.myfunc(ffi.cast("void *", p))
1835 assert res == ord(b"g")
1836 res = lib.myfunc(ffi.cast("int *", p))
1837 assert res == ord(b"g")
1838
1839 def test_callback_indirection():
1840 ffi = FFI()
1841 ffi.cdef("""
1842 static int (*python_callback)(int how_many, int *values);
1843 int (*const c_callback)(int,...); /* pass this ptr to C routines */
1844 int some_c_function(int(*cb)(int,...));
1845 """)
1846 lib = ffi.verify("""
1847 #include <stdarg.h>
1848 #ifdef _WIN32
1849 #include <malloc.h>
1850 #define alloca _alloca
1851 #else
1852 # ifdef __FreeBSD__
1853 # include <stdlib.h>
1854 # else
1855 # include <alloca.h>
1856 # endif
1857 #endif
1858 static int (*python_callback)(int how_many, int *values);
1859 static int c_callback(int how_many, ...) {
1860 va_list ap;
1861 /* collect the "..." arguments into the values[] array */
1862 int i, *values = alloca((size_t)how_many * sizeof(int));
1863 va_start(ap, how_many);
1864 for (i=0; i<how_many; i++)
1865 values[i] = va_arg(ap, int);
1866 va_end(ap);
1867 return python_callback(how_many, values);
1868 }
1869 int some_c_function(int(*cb)(int,...)) {
1870 int result = cb(2, 10, 20);
1871 result += cb(3, 30, 40, 50);
1872 return result;
1873 }
1874 """)
1875 seen = []
1876 @ffi.callback("int(int, int*)")
1877 def python_callback(how_many, values):
1878 seen.append([values[i] for i in range(how_many)])
1879 return 42
1880 lib.python_callback = python_callback
1881
1882 res = lib.some_c_function(lib.c_callback)
1883 assert res == 84
1884 assert seen == [[10, 20], [30, 40, 50]]
1885
1886 def test_floatstar_argument():
1887 ffi = FFI()
1888 ffi.cdef("float sum3floats(float *);")
1889 lib = ffi.verify("""
1890 float sum3floats(float *f) {
1891 return f[0] + f[1] + f[2];
1892 }
1893 """)
1894 assert lib.sum3floats((1.5, 2.5, 3.5)) == 7.5
1895 p = ffi.new("float[]", (1.5, 2.5, 3.5))
1896 assert lib.sum3floats(p) == 7.5
1897
1898 def test_charstar_argument():
1899 ffi = FFI()
1900 ffi.cdef("char sum3chars(char *);")
1901 lib = ffi.verify("""
1902 char sum3chars(char *f) {
1903 return (char)(f[0] + f[1] + f[2]);
1904 }
1905 """)
1906 assert lib.sum3chars((b'\x10', b'\x20', b'\x30')) == b'\x60'
1907 p = ffi.new("char[]", b'\x10\x20\x30')
1908 assert lib.sum3chars(p) == b'\x60'
1909
1910 def test_passing_string_or_NULL():
1911 ffi = FFI()
1912 ffi.cdef("int seeme1(char *); int seeme2(int *);")
1913 lib = ffi.verify("""
1914 int seeme1(char *x) {
1915 return (x == NULL);
1916 }
1917 int seeme2(int *x) {
1918 return (x == NULL);
1919 }
1920 """)
1921 assert lib.seeme1(b"foo") == 0
1922 assert lib.seeme1(ffi.NULL) == 1
1923 assert lib.seeme2([42, 43]) == 0
1924 assert lib.seeme2(ffi.NULL) == 1
1925 pytest.raises(TypeError, lib.seeme1, None)
1926 pytest.raises(TypeError, lib.seeme2, None)
1927 pytest.raises(TypeError, lib.seeme1, 0.0)
1928 pytest.raises(TypeError, lib.seeme2, 0.0)
1929 pytest.raises(TypeError, lib.seeme1, 0)
1930 pytest.raises(TypeError, lib.seeme2, 0)
1931 zeroL = 99999999999999999999
1932 zeroL -= 99999999999999999999
1933 pytest.raises(TypeError, lib.seeme2, zeroL)
1934
1935 def test_typeof_function():
1936 ffi = FFI()
1937 ffi.cdef("int foo(int, char);")
1938 lib = ffi.verify("int foo(int x, char y) { (void)x; (void)y; return 42; }")
1939 ctype = ffi.typeof(lib.foo)
1940 assert len(ctype.args) == 2
1941 assert ctype.result == ffi.typeof("int")
1942
1943 def test_call_with_voidstar_arg():
1944 ffi = FFI()
1945 ffi.cdef("int f(void *);")
1946 lib = ffi.verify("int f(void *x) { return ((char*)x)[0]; }")
1947 assert lib.f(b"foobar") == ord(b"f")
1948
1949 def test_dir():
1950 ffi = FFI()
1951 ffi.cdef("""void somefunc(void);
1952 extern int somevar, somearray[2];
1953 static char *const sv2;
1954 enum my_e { AA, BB, ... };
1955 #define FOO ...""")
1956 lib = ffi.verify("""void somefunc(void) { }
1957 int somevar, somearray[2];
1958 #define sv2 "text"
1959 enum my_e { AA, BB };
1960 #define FOO 42""")
1961 assert dir(lib) == ['AA', 'BB', 'FOO', 'somearray',
1962 'somefunc', 'somevar', 'sv2']
1963
1964 def test_typeof_func_with_struct_argument():
1965 ffi = FFI()
1966 ffi.cdef("""struct s { int a; }; int foo(struct s);""")
1967 lib = ffi.verify("""struct s { int a; };
1968 int foo(struct s x) { return x.a; }""")
1969 s = ffi.new("struct s *", [-1234])
1970 m = lib.foo(s[0])
1971 assert m == -1234
1972 assert repr(ffi.typeof(lib.foo)) == "<ctype 'int(*)(struct s)'>"
1973
1974 def test_bug_const_char_ptr_array_1():
1975 ffi = FFI()
1976 ffi.cdef("""extern const char *a[...];""")
1977 lib = ffi.verify("""const char *a[5];""")
1978 assert repr(ffi.typeof(lib.a)) == "<ctype 'char *[5]'>"
1979
1980 def test_bug_const_char_ptr_array_2():
1981 from cffi import FFI # ignore warnings
1982 ffi = FFI()
1983 ffi.cdef("""extern const int a[];""")
1984 lib = ffi.verify("""const int a[5];""")
1985 assert repr(ffi.typeof(lib.a)) == "<ctype 'int *'>"
1986
1987 def _test_various_calls(force_libffi):
1988 cdef_source = """
1989 extern int xvalue;
1990 extern long long ivalue, rvalue;
1991 extern float fvalue;
1992 extern double dvalue;
1993 extern long double Dvalue;
1994 signed char tf_bb(signed char x, signed char c);
1995 unsigned char tf_bB(signed char x, unsigned char c);
1996 short tf_bh(signed char x, short c);
1997 unsigned short tf_bH(signed char x, unsigned short c);
1998 int tf_bi(signed char x, int c);
1999 unsigned int tf_bI(signed char x, unsigned int c);
2000 long tf_bl(signed char x, long c);
2001 unsigned long tf_bL(signed char x, unsigned long c);
2002 long long tf_bq(signed char x, long long c);
2003 unsigned long long tf_bQ(signed char x, unsigned long long c);
2004 float tf_bf(signed char x, float c);
2005 double tf_bd(signed char x, double c);
2006 long double tf_bD(signed char x, long double c);
2007 """
2008 if force_libffi:
2009 cdef_source = (cdef_source
2010 .replace('tf_', '(*const tf_')
2011 .replace('(signed char x', ')(signed char x'))
2012 ffi = FFI()
2013 ffi.cdef(cdef_source)
2014 lib = ffi.verify("""
2015 int xvalue;
2016 long long ivalue, rvalue;
2017 float fvalue;
2018 double dvalue;
2019 long double Dvalue;
2020
2021 typedef signed char b_t;
2022 typedef unsigned char B_t;
2023 typedef short h_t;
2024 typedef unsigned short H_t;
2025 typedef int i_t;
2026 typedef unsigned int I_t;
2027 typedef long l_t;
2028 typedef unsigned long L_t;
2029 typedef long long q_t;
2030 typedef unsigned long long Q_t;
2031 typedef float f_t;
2032 typedef double d_t;
2033 typedef long double D_t;
2034 #define S(letter) xvalue = (int)x; letter##value = (letter##_t)c;
2035 #define R(letter) return (letter##_t)rvalue;
2036
2037 signed char tf_bb(signed char x, signed char c) { S(i) R(b) }
2038 unsigned char tf_bB(signed char x, unsigned char c) { S(i) R(B) }
2039 short tf_bh(signed char x, short c) { S(i) R(h) }
2040 unsigned short tf_bH(signed char x, unsigned short c) { S(i) R(H) }
2041 int tf_bi(signed char x, int c) { S(i) R(i) }
2042 unsigned int tf_bI(signed char x, unsigned int c) { S(i) R(I) }
2043 long tf_bl(signed char x, long c) { S(i) R(l) }
2044 unsigned long tf_bL(signed char x, unsigned long c) { S(i) R(L) }
2045 long long tf_bq(signed char x, long long c) { S(i) R(q) }
2046 unsigned long long tf_bQ(signed char x, unsigned long long c) { S(i) R(Q) }
2047 float tf_bf(signed char x, float c) { S(f) R(f) }
2048 double tf_bd(signed char x, double c) { S(d) R(d) }
2049 long double tf_bD(signed char x, long double c) { S(D) R(D) }
2050 """)
2051 lib.rvalue = 0x7182838485868788
2052 for kind, cname in [('b', 'signed char'),
2053 ('B', 'unsigned char'),
2054 ('h', 'short'),
2055 ('H', 'unsigned short'),
2056 ('i', 'int'),
2057 ('I', 'unsigned int'),
2058 ('l', 'long'),
2059 ('L', 'unsigned long'),
2060 ('q', 'long long'),
2061 ('Q', 'unsigned long long'),
2062 ('f', 'float'),
2063 ('d', 'double'),
2064 ('D', 'long double')]:
2065 sign = +1 if 'unsigned' in cname else -1
2066 lib.xvalue = 0
2067 lib.ivalue = 0
2068 lib.fvalue = 0
2069 lib.dvalue = 0
2070 lib.Dvalue = 0
2071 fun = getattr(lib, 'tf_b' + kind)
2072 res = fun(-42, sign * 99)
2073 if kind == 'D':
2074 res = float(res)
2075 assert res == int(ffi.cast(cname, 0x7182838485868788))
2076 assert lib.xvalue == -42
2077 if kind in 'fdD':
2078 assert float(getattr(lib, kind + 'value')) == -99.0
2079 else:
2080 assert lib.ivalue == sign * 99
2081
2082 def test_various_calls_direct():
2083 _test_various_calls(force_libffi=False)
2084
2085 def test_various_calls_libffi():
2086 _test_various_calls(force_libffi=True)
2087
2088 def test_ptr_to_opaque():
2089 ffi = FFI()
2090 ffi.cdef("typedef ... foo_t; int f1(foo_t*); foo_t *f2(int);")
2091 lib = ffi.verify("""
2092 #include <stdlib.h>
2093 typedef struct { int x; } foo_t;
2094 int f1(foo_t* p) {
2095 int x = p->x;
2096 free(p);
2097 return x;
2098 }
2099 foo_t *f2(int x) {
2100 foo_t *p = malloc(sizeof(foo_t));
2101 p->x = x;
2102 return p;
2103 }
2104 """)
2105 p = lib.f2(42)
2106 x = lib.f1(p)
2107 assert x == 42
2108
2109 def _run_in_multiple_threads(test1):
2110 test1()
2111 import sys
2112 try:
2113 import thread
2114 except ImportError:
2115 import _thread as thread
2116 errors = []
2117 def wrapper(lock):
2118 try:
2119 test1()
2120 except:
2121 errors.append(sys.exc_info())
2122 lock.release()
2123 locks = []
2124 for i in range(10):
2125 _lock = thread.allocate_lock()
2126 _lock.acquire()
2127 thread.start_new_thread(wrapper, (_lock,))
2128 locks.append(_lock)
2129 for _lock in locks:
2130 _lock.acquire()
2131 if errors:
2132 raise errors[0][1]
2133
2134 def test_errno_working_even_with_pypys_jit():
2135 # NOTE: on some platforms, to work correctly, this test needs to be
2136 # compiled with -pthread. Otherwise, the accesses to errno done from f()
2137 # are compiled by assuming this small library won't be used from multiple
2138 # threads, which is wrong. If you see failures _and_ if you pass your
2139 # own CFLAGS environment variable, please make sure "-pthread" is in it.
2140 ffi = FFI()
2141 ffi.cdef("int f(int);")
2142 lib = ffi.verify("""
2143 #include <errno.h>
2144 int f(int x) { return (errno = errno + x); }
2145 """)
2146 @_run_in_multiple_threads
2147 def test1():
2148 ffi.errno = 0
2149 for i in range(10000):
2150 e = lib.f(1)
2151 assert e == i + 1
2152 assert ffi.errno == e
2153 for i in range(10000):
2154 ffi.errno = i
2155 e = lib.f(42)
2156 assert e == i + 42
2157
2158 def test_getlasterror_working_even_with_pypys_jit():
2159 if sys.platform != 'win32':
2160 pytest.skip("win32-only test")
2161 ffi = FFI()
2162 ffi.cdef("void SetLastError(DWORD);")
2163 lib = ffi.dlopen("Kernel32.dll")
2164 @_run_in_multiple_threads
2165 def test1():
2166 for i in range(10000):
2167 n = (1 << 29) + i
2168 lib.SetLastError(n)
2169 assert ffi.getwinerror()[0] == n
2170
2171 def test_verify_dlopen_flags():
2172 # Careful with RTLD_GLOBAL. If by chance the FFI is not deleted
2173 # promptly, like on PyPy, then other tests may see the same
2174 # exported symbols as well. So we must not export a simple name
2175 # like 'foo'!
2176 ffi1 = FFI()
2177 ffi1.cdef("extern int foo_verify_dlopen_flags;")
2178
2179 modulename = "_cffi_test_verify_dlopen_flags_%d" % random.randint(0, 1000000000)
2180 lib1 = ffi1.verify("int foo_verify_dlopen_flags;",
2181 flags=ffi1.RTLD_GLOBAL | ffi1.RTLD_LAZY,
2182 modulename=modulename)
2183 lib2 = get_second_lib(modulename)
2184
2185 lib1.foo_verify_dlopen_flags = 42
2186 assert lib2.foo_verify_dlopen_flags == 42
2187 lib2.foo_verify_dlopen_flags += 1
2188 assert lib1.foo_verify_dlopen_flags == 43
2189
2190 def get_second_lib(modulename):
2191 ffi2 = FFI()
2192 ffi2.cdef("extern int foo_verify_dlopen_flags;")
2193 lib2 = ffi2.verify("int foo_verify_dlopen_flags;",
2194 flags=ffi2.RTLD_GLOBAL | ffi2.RTLD_LAZY,
2195 modulename=modulename)
2196 return lib2
2197
2198 def test_consider_not_implemented_function_type():
2199 ffi = FFI()
2200 ffi.cdef("typedef union { int a; float b; } Data;"
2201 "typedef struct { int a:2; } MyStr;"
2202 "typedef void (*foofunc_t)(Data);"
2203 "typedef Data (*bazfunc_t)(void);"
2204 "typedef MyStr (*barfunc_t)(void);")
2205 fooptr = ffi.cast("foofunc_t", 123)
2206 bazptr = ffi.cast("bazfunc_t", 123)
2207 barptr = ffi.cast("barfunc_t", 123)
2208 # assert did not crash so far
2209 e = pytest.raises(NotImplementedError, fooptr, ffi.new("Data *"))
2210 assert str(e.value) == (
2211 "ctype 'Data' not supported as argument by libffi. Unions are only "
2212 "supported as argument if the function is 'API mode' and "
2213 "non-variadic (i.e. declared inside ffibuilder.cdef()+"
2214 "ffibuilder.set_source() and not taking a final '...' argument)")
2215 e = pytest.raises(NotImplementedError, bazptr)
2216 assert str(e.value) == (
2217 "ctype 'Data' not supported as return value by libffi. Unions are "
2218 "only supported as return value if the function is 'API mode' and "
2219 "non-variadic (i.e. declared inside ffibuilder.cdef()+"
2220 "ffibuilder.set_source() and not taking a final '...' argument)")
2221 e = pytest.raises(NotImplementedError, barptr)
2222 assert str(e.value) == (
2223 "ctype 'MyStr' not supported as return value. It is a struct with "
2224 "bit fields, which libffi does not support. Such structs are only "
2225 "supported as return value if the function is 'API mode' and non-"
2226 "variadic (i.e. declared inside ffibuilder.cdef()+ffibuilder."
2227 "set_source() and not taking a final '...' argument)")
2228
2229 def test_verify_extra_arguments():
2230 ffi = FFI()
2231 ffi.cdef("#define ABA ...")
2232 lib = ffi.verify("", define_macros=[('ABA', '42')])
2233 assert lib.ABA == 42
2234
2235 def test_implicit_unicode_on_windows():
2236 if sys.platform != 'win32':
2237 pytest.skip("win32-only test")
2238 ffi = FFI()
2239 e = pytest.raises(FFIError, ffi.cdef, "int foo(LPTSTR);")
2240 assert str(e.value) == ("The Windows type 'LPTSTR' is only available after"
2241 " you call ffi.set_unicode()")
2242 for with_unicode in [True, False]:
2243 ffi = FFI()
2244 ffi.set_unicode(with_unicode)
2245 ffi.cdef("""
2246 DWORD GetModuleFileName(HMODULE hModule, LPTSTR lpFilename,
2247 DWORD nSize);
2248 """)
2249 lib = ffi.verify("""
2250 #include <windows.h>
2251 """, libraries=['Kernel32'])
2252 outbuf = ffi.new("TCHAR[]", 200)
2253 n = lib.GetModuleFileName(ffi.NULL, outbuf, 500)
2254 assert 0 < n < 500
2255 for i in range(n):
2256 #print repr(outbuf[i])
2257 assert ord(outbuf[i]) != 0
2258 assert ord(outbuf[n]) == 0
2259 assert ord(outbuf[0]) < 128 # should be a letter, or '\'
2260
2261 def test_use_local_dir():
2262 ffi = FFI()
2263 lib = ffi.verify("", modulename="_cffi_test_use_local_dir")
2264 this_dir = os.path.dirname(__file__)
2265 pycache_files = os.listdir(os.path.join(this_dir, '__pycache__'))
2266 assert any('test_use_local_dir' in s for s in pycache_files)
2267
2268 def test_define_known_value():
2269 ffi = FFI()
2270 ffi.cdef("#define FOO 0x123")
2271 lib = ffi.verify("#define FOO 0x123")
2272 assert lib.FOO == 0x123
2273
2274 def test_define_wrong_value():
2275 ffi = FFI()
2276 ffi.cdef("#define FOO 123")
2277 e = pytest.raises(VerificationError, ffi.verify, "#define FOO 124")
2278 assert str(e.value).endswith("FOO has the real value 124, not 123")
2279
2280 def test_static_const_int_known_value():
2281 ffi = FFI()
2282 ffi.cdef("static const int FOO = 0x123;")
2283 lib = ffi.verify("#define FOO 0x123")
2284 assert lib.FOO == 0x123
2285
2286 def test_static_const_int_wrong_value():
2287 ffi = FFI()
2288 ffi.cdef("static const int FOO = 123;")
2289 e = pytest.raises(VerificationError, ffi.verify, "#define FOO 124")
2290 assert str(e.value).endswith("FOO has the real value 124, not 123")
2291
2292 def test_const_struct_global():
2293 ffi = FFI()
2294 ffi.cdef("typedef struct { int x; ...; } T; const T myglob;")
2295 lib = ffi.verify("typedef struct { double y; int x; } T;"
2296 "const T myglob = { 0.1, 42 };")
2297 assert ffi.typeof(lib.myglob) == ffi.typeof("T")
2298 assert lib.myglob.x == 42
2299
2300 def test_dont_support_int_dotdotdot():
2301 ffi = FFI()
2302 ffi.cdef("typedef int... t1;")
2303 e = pytest.raises(VerificationError, ffi.verify, "")
2304 assert str(e.value) == ("feature not supported with ffi.verify(), but only "
2305 "with ffi.set_source(): 'typedef int... t1'")
2306 ffi = FFI()
2307 ffi.cdef("typedef double ... t1;")
2308 e = pytest.raises(VerificationError, ffi.verify, "")
2309 assert str(e.value) == ("feature not supported with ffi.verify(), but only "
2310 "with ffi.set_source(): 'typedef float... t1'")
2311
2312 def test_const_fields():
2313 ffi = FFI()
2314 ffi.cdef("""struct foo_s { const int a; void *const b; };""")
2315 ffi.verify("""struct foo_s { const int a; void *const b; };""")
2316 foo_s = ffi.typeof("struct foo_s")
2317 assert foo_s.fields[0][0] == 'a'
2318 assert foo_s.fields[0][1].type is ffi.typeof("int")
2319 assert foo_s.fields[1][0] == 'b'
2320 assert foo_s.fields[1][1].type is ffi.typeof("void *")
2321
2322 def test_win32_calling_convention_0():
2323 ffi = FFI()
2324 ffi.cdef("""
2325 int call1(int(__cdecl *cb)(int));
2326 int (*const call2)(int(__stdcall *cb)(int));
2327 """)
2328 lib = ffi.verify(r"""
2329 #ifndef _MSC_VER
2330 # define __stdcall /* nothing */
2331 #endif
2332 int call1(int(*cb)(int)) {
2333 int i, result = 0;
2334 //printf("call1: cb = %p\n", cb);
2335 for (i = 0; i < 1000; i++)
2336 result += cb(i);
2337 //printf("result = %d\n", result);
2338 return result;
2339 }
2340 int call2(int(__stdcall *cb)(int)) {
2341 int i, result = 0;
2342 //printf("call2: cb = %p\n", cb);
2343 for (i = 0; i < 1000; i++)
2344 result += cb(-i);
2345 //printf("result = %d\n", result);
2346 return result;
2347 }
2348 """)
2349 @ffi.callback("int(int)")
2350 def cb1(x):
2351 return x * 2
2352 @ffi.callback("int __stdcall(int)")
2353 def cb2(x):
2354 return x * 3
2355 #print 'cb1 =', cb1
2356 res = lib.call1(cb1)
2357 assert res == 500*999*2
2358 #print 'cb2 =', cb2
2359 #print ffi.typeof(lib.call2)
2360 #print 'call2 =', lib.call2
2361 res = lib.call2(cb2)
2362 #print '...'
2363 assert res == -500*999*3
2364 #print 'done'
2365 if sys.platform == 'win32' and sys.maxsize < 2**32:
2366 assert '__stdcall' in str(ffi.typeof(cb2))
2367 assert '__stdcall' not in str(ffi.typeof(cb1))
2368 pytest.raises(TypeError, lib.call1, cb2)
2369 pytest.raises(TypeError, lib.call2, cb1)
2370 else:
2371 assert '__stdcall' not in str(ffi.typeof(cb2))
2372 assert ffi.typeof(cb2) is ffi.typeof(cb1)
2373
2374 def test_win32_calling_convention_1():
2375 ffi = FFI()
2376 ffi.cdef("""
2377 int __cdecl call1(int(__cdecl *cb)(int));
2378 int __stdcall call2(int(__stdcall *cb)(int));
2379 int (__cdecl *const cb1)(int);
2380 int (__stdcall *const cb2)(int);
2381 """)
2382 lib = ffi.verify(r"""
2383 #ifndef _MSC_VER
2384 # define __cdecl
2385 # define __stdcall
2386 #endif
2387 int __cdecl cb1(int x) { return x * 2; }
2388 int __stdcall cb2(int x) { return x * 3; }
2389
2390 int __cdecl call1(int(__cdecl *cb)(int)) {
2391 int i, result = 0;
2392 //printf("here1\n");
2393 //printf("cb = %p, cb1 = %p\n", cb, (void *)cb1);
2394 for (i = 0; i < 1000; i++)
2395 result += cb(i);
2396 //printf("result = %d\n", result);
2397 return result;
2398 }
2399 int __stdcall call2(int(__stdcall *cb)(int)) {
2400 int i, result = 0;
2401 //printf("here1\n");
2402 //printf("cb = %p, cb2 = %p\n", cb, (void *)cb2);
2403 for (i = 0; i < 1000; i++)
2404 result += cb(-i);
2405 //printf("result = %d\n", result);
2406 return result;
2407 }
2408 """)
2409 assert lib.call1(lib.cb1) == 500*999*2
2410 assert lib.call2(lib.cb2) == -500*999*3
2411
2412 def test_win32_calling_convention_2():
2413 # any mistake in the declaration of plain function (including the
2414 # precise argument types and, here, the calling convention) are
2415 # automatically corrected. But this does not apply to the 'cb'
2416 # function pointer argument.
2417 ffi = FFI()
2418 ffi.cdef("""
2419 int __stdcall call1(int(__cdecl *cb)(int));
2420 int __cdecl call2(int(__stdcall *cb)(int));
2421 int (__cdecl *const cb1)(int);
2422 int (__stdcall *const cb2)(int);
2423 """)
2424 lib = ffi.verify(r"""
2425 #ifndef _MSC_VER
2426 # define __cdecl
2427 # define __stdcall
2428 #endif
2429 int __cdecl call1(int(__cdecl *cb)(int)) {
2430 int i, result = 0;
2431 for (i = 0; i < 1000; i++)
2432 result += cb(i);
2433 return result;
2434 }
2435 int __stdcall call2(int(__stdcall *cb)(int)) {
2436 int i, result = 0;
2437 for (i = 0; i < 1000; i++)
2438 result += cb(-i);
2439 return result;
2440 }
2441 int __cdecl cb1(int x) { return x * 2; }
2442 int __stdcall cb2(int x) { return x * 3; }
2443 """)
2444 assert lib.call1(lib.cb1) == 500*999*2
2445 assert lib.call2(lib.cb2) == -500*999*3
2446
2447 def test_win32_calling_convention_3():
2448 ffi = FFI()
2449 ffi.cdef("""
2450 struct point { int x, y; };
2451
2452 int (*const cb1)(struct point);
2453 int (__stdcall *const cb2)(struct point);
2454
2455 struct point __stdcall call1(int(*cb)(struct point));
2456 struct point call2(int(__stdcall *cb)(struct point));
2457 """)
2458 lib = ffi.verify(r"""
2459 #ifndef _MSC_VER
2460 # define __cdecl
2461 # define __stdcall
2462 #endif
2463 struct point { int x, y; };
2464 int cb1(struct point pt) { return pt.x + 10 * pt.y; }
2465 int __stdcall cb2(struct point pt) { return pt.x + 100 * pt.y; }
2466 struct point __stdcall call1(int(__cdecl *cb)(struct point)) {
2467 int i;
2468 struct point result = { 0, 0 };
2469 //printf("here1\n");
2470 //printf("cb = %p, cb1 = %p\n", cb, (void *)cb1);
2471 for (i = 0; i < 1000; i++) {
2472 struct point p = { i, -i };
2473 int r = cb(p);
2474 result.x += r;
2475 result.y -= r;
2476 }
2477 return result;
2478 }
2479 struct point __cdecl call2(int(__stdcall *cb)(struct point)) {
2480 int i;
2481 struct point result = { 0, 0 };
2482 for (i = 0; i < 1000; i++) {
2483 struct point p = { -i, i };
2484 int r = cb(p);
2485 result.x += r;
2486 result.y -= r;
2487 }
2488 return result;
2489 }
2490 """)
2491 if sys.platform == 'win32' and sys.maxsize < 2**32:
2492 pytest.raises(TypeError, lib.call1, lib.cb2)
2493 pytest.raises(TypeError, lib.call2, lib.cb1)
2494 pt = lib.call1(lib.cb1)
2495 assert (pt.x, pt.y) == (-9*500*999, 9*500*999)
2496 pt = lib.call2(lib.cb2)
2497 assert (pt.x, pt.y) == (99*500*999, -99*500*999)
2498
2499 def _only_test_on_linux_intel():
2500 if not sys.platform.startswith('linux'):
2501 pytest.skip('only running the memory-intensive test on Linux')
2502 import platform
2503 machine = platform.machine()
2504 if 'x86' not in machine and 'x64' not in machine:
2505 pytest.skip('only running the memory-intensive test on x86/x64')
2506
2507 def test_ffi_gc_size_arg():
2508 # with PyPy's GC, these calls to ffi.gc() would rapidly consume
2509 # 40 GB of RAM without the third argument
2510 _only_test_on_linux_intel()
2511 ffi = FFI()
2512 ffi.cdef("void *malloc(size_t); void free(void *);")
2513 lib = ffi.verify(r"""
2514 #include <stdlib.h>
2515 """)
2516 for i in range(2000):
2517 p = lib.malloc(20*1024*1024) # 20 MB
2518 p1 = ffi.cast("char *", p)
2519 for j in range(0, 20*1024*1024, 4096):
2520 p1[j] = b'!'
2521 p = ffi.gc(p, lib.free, 20*1024*1024)
2522 del p
2523
2524 def test_ffi_gc_size_arg_2():
2525 # a variant of the above: this "attack" works on cpython's cyclic gc too
2526 # and I found no obvious way to prevent that. So for now, this test
2527 # is skipped on CPython, where it eats all the memory.
2528 if '__pypy__' not in sys.builtin_module_names:
2529 pytest.skip("find a way to tweak the cyclic GC of CPython")
2530 _only_test_on_linux_intel()
2531 ffi = FFI()
2532 ffi.cdef("void *malloc(size_t); void free(void *);")
2533 lib = ffi.verify(r"""
2534 #include <stdlib.h>
2535 """)
2536 class X(object):
2537 pass
2538 for i in range(2000):
2539 p = lib.malloc(50*1024*1024) # 50 MB
2540 p1 = ffi.cast("char *", p)
2541 for j in range(0, 50*1024*1024, 4096):
2542 p1[j] = b'!'
2543 p = ffi.gc(p, lib.free, 50*1024*1024)
2544 x = X()
2545 x.p = p
2546 x.cyclic = x
2547 del p, x
2548
2549 def test_ffi_new_with_cycles():
2550 # still another variant, with ffi.new()
2551 if '__pypy__' not in sys.builtin_module_names:
2552 pytest.skip("find a way to tweak the cyclic GC of CPython")
2553 ffi = FFI()
2554 ffi.cdef("")
2555 lib = ffi.verify("")
2556 class X(object):
2557 pass
2558 for i in range(2000):
2559 p = ffi.new("char[]", 50*1024*1024) # 50 MB
2560 for j in range(0, 50*1024*1024, 4096):
2561 p[j] = b'!'
2562 x = X()
2563 x.p = p
2564 x.cyclic = x
2565 del p, x
2566
2567 def test_arithmetic_in_cdef():
2568 for a in [0, 11, 15]:
2569 ffi = FFI()
2570 ffi.cdef("""
2571 enum FOO {
2572 DIVNN = ((-?) / (-3)),
2573 DIVNP = ((-?) / (+3)),
2574 DIVPN = ((+?) / (-3)),
2575 MODNN = ((-?) % (-3)),
2576 MODNP = ((-?) % (+3)),
2577 MODPN = ((+?) % (-3)),
2578 };
2579 """.replace('?', str(a)))
2580 lib = ffi.verify("""
2581 enum FOO {
2582 DIVNN = ((-?) / (-3)),
2583 DIVNP = ((-?) / (+3)),
2584 DIVPN = ((+?) / (-3)),
2585 MODNN = ((-?) % (-3)),
2586 MODNP = ((-?) % (+3)),
2587 MODPN = ((+?) % (-3)),
2588 };
2589 """.replace('?', str(a)))
2590 # the verify() crashes if the values in the enum are different from
2591 # the values we computed ourselves from the cdef()
2592
2593 def test_passing_large_list():
2594 ffi = FFI()
2595 ffi.cdef("""void passing_large_list(long[]);""")
2596 lib = ffi.verify("""
2597 static void passing_large_list(long a[]) { }
2598 """)
2599 arg = list(range(20000000))
2600 lib.passing_large_list(arg)
2601 # assert did not segfault
2602
2603 def test_no_regen():
2604 from cffi.verifier import Verifier, _caller_dir_pycache
2605 import os
2606 ffi = FFI()
2607 modulename = "_cffi_test_no_regen_%d" % random.randint(0, 1000000000)
2608 ffi.cdef("double sin(double x);")
2609 lib = ffi.verify('#include <math.h>', libraries=lib_m, modulename=modulename)
2610 assert lib.sin(1.23) == math.sin(1.23)
2611 # Make sure that recompiling the same code does not rebuild the C file
2612 cfile = os.path.join(ffi.verifier.tmpdir, f"{modulename}.c")
2613 assert os.path.exists(cfile)
2614 os.unlink(cfile)
2615 assert not os.path.exists(cfile)
2616 lib = ffi.verify('#include <math.h>', libraries=lib_m, modulename=modulename)
2617 assert lib.sin(1.23) == math.sin(1.23)
2618 assert not os.path.exists(cfile)