Debian Codegraph @

pypy/module/_cffi_backend/test/_backend_test_c.py

raw symbols SCIP
1 # Copied from <cffi>/c/test_c.py
2 # Make sure the files are identical starting from the # ________ line below
3
4 import contextlib
5
6 import pytest
7 from pytest import skip
8 import sys
9 import typing as t
10
11 is_musl = False
12 if sys.platform == 'linux':
13 try:
14 from packaging.tags import platform_tags
15 is_musl = any(t.startswith('musllinux') for t in platform_tags())
16 del platform_tags
17 except ImportError:
18 pass
19
20 def _setup_path():
21 import os, sys
22 sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
23 _setup_path()
24 from _cffi_backend import *
25 from _cffi_backend import _get_types, _get_common_types
26 try:
27 from _cffi_backend import _testfunc
28 except ImportError:
29 def _testfunc(num):
30 skip("_testunc() not available")
31 from _cffi_backend import __version__
32
33
34 @contextlib.contextmanager
35 def _assert_unraisable(error_type, message='', traceback_tokens = None):
36 """Assert that a given sys.unraisablehook interaction occurred (or did not
37 occur, if error_type is None) while this context was active"""
38 # This check and the test_callback_exception test are skipped, since PyPy
39 # raises an error but one frame above the CPython one (in the callback
40 # caller)
41 import traceback
42 raised_errors: list[Exception] = []
43 raised_traceback: str = ''
44
45 # sys.unraisablehook is called more than once for chained exceptions; accumulate the errors and tracebacks for inspection
46 def _capture_unraisable_hook(ur_args):
47 nonlocal raised_traceback
48 raised_errors.append(ur_args.exc_value)
49
50 # NB: need to use the old etype/value/tb form until 3.10 is the minimum
51 raised_traceback += (ur_args.err_msg or '' + '\n') + ''.join(traceback.format_exception(None, ur_args.exc_value, ur_args.exc_traceback))
52
53
54 old_unraisable = sys.unraisablehook
55 try:
56 sys.unraisablehook = _capture_unraisable_hook
57 yield
58 finally:
59 sys.unraisablehook = old_unraisable
60
61 if error_type is None:
62 assert not raised_errors
63 assert not raised_traceback
64 return
65
66 assert any(type(raised_error) is error_type for raised_error in raised_errors)
67 assert any(message in str(raised_error) for raised_error in raised_errors)
68 for t in traceback_tokens or []:
69 assert t in raised_traceback
70
71 # ____________________________________________________________
72
73 import sys
74 assert __version__ == "1.18.0.dev0", ("This test_c.py file is for testing a version"
75 " of cffi that differs from the one that we"
76 " get from 'import _cffi_backend'")
77 if sys.version_info < (3,):
78 type_or_class = "type"
79 mandatory_b_prefix = ''
80 mandatory_u_prefix = 'u'
81 bytechr = chr
82 bitem2bchr = lambda x: x
83 class U(object):
84 def __add__(self, other):
85 return eval('u'+repr(other).replace(r'\\u', r'\u')
86 .replace(r'\\U', r'\U'))
87 u = U()
88 str2bytes = str
89 strict_compare = False
90 else:
91 type_or_class = "class"
92 long = int
93 unicode = str
94 unichr = chr
95 mandatory_b_prefix = 'b'
96 mandatory_u_prefix = ''
97 bytechr = lambda n: bytes([n])
98 bitem2bchr = bytechr
99 u = ""
100 str2bytes = lambda s: bytes(s, "ascii")
101 strict_compare = True
102
103 def size_of_int():
104 BInt = new_primitive_type("int")
105 return sizeof(BInt)
106
107 def size_of_long():
108 BLong = new_primitive_type("long")
109 return sizeof(BLong)
110
111 def size_of_ptr():
112 BInt = new_primitive_type("int")
113 BPtr = new_pointer_type(BInt)
114 return sizeof(BPtr)
115
116
117 def find_and_load_library(name, flags=RTLD_NOW):
118 import ctypes.util
119 if name is None:
120 path = None
121 else:
122 path = ctypes.util.find_library(name)
123 if path is None and sys.platform == 'darwin' and sys.version_info[:2] == (3, 8):
124 pytest.xfail("find_library usually broken on MacOS Python 3.8")
125 if path is None and name == 'c':
126 assert sys.platform == 'win32'
127 assert (sys.version_info >= (3,) or
128 '__pypy__' in sys.builtin_module_names)
129 skip("dlopen(None) cannot work on Windows "
130 "with PyPy or Python 3")
131 return load_library(path, flags)
132
133 def test_load_library():
134 x = find_and_load_library('c')
135 assert repr(x).startswith("<clibrary '")
136 x = find_and_load_library('c', RTLD_NOW | RTLD_GLOBAL)
137 assert repr(x).startswith("<clibrary '")
138 x = find_and_load_library('c', RTLD_LAZY)
139 assert repr(x).startswith("<clibrary '")
140
141 def test_all_rtld_symbols():
142 import sys
143 FFI_DEFAULT_ABI # these symbols must be defined
144 FFI_CDECL
145 RTLD_LAZY
146 RTLD_NOW
147 RTLD_GLOBAL
148 RTLD_LOCAL
149 if sys.platform.startswith("linux"):
150 RTLD_NODELETE
151 RTLD_NOLOAD
152 if not is_musl:
153 RTLD_DEEPBIND
154
155 def test_new_primitive_type():
156 pytest.raises(KeyError, new_primitive_type, "foo")
157 p = new_primitive_type("signed char")
158 assert repr(p) == "<ctype 'signed char'>"
159
160 def check_dir(p, expected):
161 got = [name for name in dir(p) if not name.startswith('_')]
162 assert got == sorted(expected)
163
164 def test_inspect_primitive_type():
165 p = new_primitive_type("signed char")
166 assert p.kind == "primitive"
167 assert p.cname == "signed char"
168 check_dir(p, ['cname', 'kind'])
169
170 def test_cast_to_signed_char():
171 p = new_primitive_type("signed char")
172 x = cast(p, -65 + 17*256)
173 assert repr(x) == "<cdata 'signed char' -65>"
174 assert repr(type(x)) == "<%s '_cffi_backend._CDataBase'>" % type_or_class
175 assert int(x) == -65
176 x = cast(p, -66 + (1<<199)*256)
177 assert repr(x) == "<cdata 'signed char' -66>"
178 assert int(x) == -66
179 assert (x == cast(p, -66)) is True
180 assert (x != cast(p, -66)) is False
181 q = new_primitive_type("short")
182 assert (x == cast(q, -66)) is True
183 assert (x != cast(q, -66)) is False
184
185 def test_sizeof_type():
186 pytest.raises(TypeError, sizeof, 42.5)
187 p = new_primitive_type("short")
188 assert sizeof(p) == 2
189
190 def test_integer_types():
191 for name in ['signed char', 'short', 'int', 'long', 'long long']:
192 p = new_primitive_type(name)
193 size = sizeof(p)
194 min = -(1 << (8*size-1))
195 max = (1 << (8*size-1)) - 1
196 assert int(cast(p, min)) == min
197 assert int(cast(p, max)) == max
198 assert int(cast(p, min - 1)) == max
199 assert int(cast(p, max + 1)) == min
200 pytest.raises(TypeError, cast, p, None)
201 assert long(cast(p, min - 1)) == max
202 assert int(cast(p, b'\x08')) == 8
203 assert int(cast(p, u+'\x08')) == 8
204 for name in ['char', 'short', 'int', 'long', 'long long']:
205 p = new_primitive_type('unsigned ' + name)
206 size = sizeof(p)
207 max = (1 << (8*size)) - 1
208 assert int(cast(p, 0)) == 0
209 assert int(cast(p, max)) == max
210 assert int(cast(p, -1)) == max
211 assert int(cast(p, max + 1)) == 0
212 assert long(cast(p, -1)) == max
213 assert int(cast(p, b'\xFE')) == 254
214 assert int(cast(p, u+'\xFE')) == 254
215
216 def test_no_float_on_int_types():
217 p = new_primitive_type('long')
218 pytest.raises(TypeError, float, cast(p, 42))
219 pytest.raises(TypeError, complex, cast(p, 42))
220
221 def test_float_types():
222 INF = 1E200 * 1E200
223 for name in ["float", "double"]:
224 p = new_primitive_type(name)
225 assert bool(cast(p, 0)) is False # since 1.7
226 assert bool(cast(p, -0.0)) is False # since 1.7
227 assert bool(cast(p, 1e-42)) is True
228 assert bool(cast(p, -1e-42)) is True
229 assert bool(cast(p, INF))
230 assert bool(cast(p, -INF))
231 assert bool(cast(p, float("nan")))
232 assert int(cast(p, -150)) == -150
233 assert int(cast(p, 61.91)) == 61
234 assert long(cast(p, 61.91)) == 61
235 assert type(int(cast(p, 61.91))) is int
236 assert type(int(cast(p, 1E22))) is long
237 assert type(long(cast(p, 61.91))) is long
238 assert type(long(cast(p, 1E22))) is long
239 pytest.raises(OverflowError, int, cast(p, INF))
240 pytest.raises(OverflowError, int, cast(p, -INF))
241 assert float(cast(p, 1.25)) == 1.25
242 assert float(cast(p, INF)) == INF
243 assert float(cast(p, -INF)) == -INF
244 if name == "float":
245 assert float(cast(p, 1.1)) != 1.1 # rounding error
246 assert float(cast(p, 1E200)) == INF # limited range
247
248 assert cast(p, -1.1) == cast(p, -1.1)
249 assert repr(float(cast(p, -0.0))) == '-0.0'
250 assert float(cast(p, b'\x09')) == 9.0
251 assert float(cast(p, u+'\x09')) == 9.0
252 assert float(cast(p, True)) == 1.0
253 pytest.raises(TypeError, cast, p, None)
254
255 def test_complex_types():
256 INF = 1E200 * 1E200
257 for name in ["float", "double"]:
258 p = new_primitive_type("_cffi_" + name + "_complex_t")
259 assert bool(cast(p, 0)) is False
260 assert bool(cast(p, INF))
261 assert bool(cast(p, -INF))
262 assert bool(cast(p, 0j)) is False
263 assert bool(cast(p, INF*1j))
264 assert bool(cast(p, -INF*1j))
265 # "can't convert complex to float", like CPython's "float(0j)"
266 pytest.raises(TypeError, int, cast(p, -150))
267 pytest.raises(TypeError, long, cast(p, -150))
268 pytest.raises(TypeError, float, cast(p, -150))
269 assert complex(cast(p, 1.25)) == 1.25
270 assert complex(cast(p, 1.25j)) == 1.25j
271 assert complex(cast(p, complex(0,INF))) == complex(0,INF)
272 assert complex(cast(p, -INF)) == -INF
273 if name == "float":
274 assert complex(cast(p, 1.1j)) != 1.1j # rounding error
275 assert complex(cast(p, 1E200+3j)) == INF+3j # limited range
276 assert complex(cast(p, complex(3,1E200))) == complex(3,INF) # limited range
277
278 assert cast(p, -1.1j) == cast(p, -1.1j)
279 assert repr(complex(cast(p, -0.0)).real) == '-0.0'
280 #assert repr(complex(cast(p, -0j))) == '-0j' # http://bugs.python.org/issue29602
281 assert complex(cast(p, b'\x09')) == 9.0 + 0j
282 assert complex(cast(p, u+'\x09')) == 9.0 + 0j
283 assert complex(cast(p, True)) == 1.0 + 0j
284 pytest.raises(TypeError, cast, p, None)
285 #
286 pytest.raises(TypeError, cast, new_primitive_type(name), 1+0j)
287 #
288 for basetype in ["char", "int", "uint64_t", "float",
289 "double", "long double"]:
290 baseobj = cast(new_primitive_type(basetype), 65)
291 pytest.raises(TypeError, complex, baseobj)
292 #
293 BArray = new_array_type(new_pointer_type(p), 10)
294 x = newp(BArray, None)
295 x[5] = 12.34 + 56.78j
296 assert type(x[5]) is complex
297 assert abs(x[5] - (12.34 + 56.78j)) < 1e-5
298 assert (x[5] == 12.34 + 56.78j) == (name == "double") # rounding error
299 #
300 class Foo:
301 def __complex__(self):
302 return 2 + 3j
303 assert complex(Foo()) == 2 + 3j
304 assert complex(cast(p, Foo())) == 2 + 3j
305 pytest.raises(TypeError, cast, new_primitive_type("int"), 1+0j)
306
307 def test_character_type():
308 p = new_primitive_type("char")
309 assert bool(cast(p, 'A')) is True
310 assert bool(cast(p, '\x00')) is False # since 1.7
311 assert cast(p, '\x00') == cast(p, -17*256)
312 assert int(cast(p, 'A')) == 65
313 assert long(cast(p, 'A')) == 65
314 assert type(int(cast(p, 'A'))) is int
315 assert type(long(cast(p, 'A'))) is long
316 assert str(cast(p, 'A')) == repr(cast(p, 'A'))
317 assert repr(cast(p, 'A')) == "<cdata 'char' %s'A'>" % mandatory_b_prefix
318 assert repr(cast(p, 255)) == r"<cdata 'char' %s'\xff'>" % mandatory_b_prefix
319 assert repr(cast(p, 0)) == r"<cdata 'char' %s'\x00'>" % mandatory_b_prefix
320
321 def test_pointer_type():
322 p = new_primitive_type("int")
323 assert repr(p) == "<ctype 'int'>"
324 p = new_pointer_type(p)
325 assert repr(p) == "<ctype 'int *'>"
326 p = new_pointer_type(p)
327 assert repr(p) == "<ctype 'int * *'>"
328 p = new_pointer_type(p)
329 assert repr(p) == "<ctype 'int * * *'>"
330
331 def test_inspect_pointer_type():
332 p1 = new_primitive_type("int")
333 p2 = new_pointer_type(p1)
334 assert p2.kind == "pointer"
335 assert p2.cname == "int *"
336 assert p2.item is p1
337 check_dir(p2, ['cname', 'kind', 'item'])
338 p3 = new_pointer_type(p2)
339 assert p3.item is p2
340
341 def test_pointer_to_int():
342 BInt = new_primitive_type("int")
343 pytest.raises(TypeError, newp, BInt)
344 pytest.raises(TypeError, newp, BInt, None)
345 BPtr = new_pointer_type(BInt)
346 p = newp(BPtr)
347 assert repr(p) == "<cdata 'int *' owning %d bytes>" % size_of_int()
348 p = newp(BPtr, None)
349 assert repr(p) == "<cdata 'int *' owning %d bytes>" % size_of_int()
350 p = newp(BPtr, 5000)
351 assert repr(p) == "<cdata 'int *' owning %d bytes>" % size_of_int()
352 q = cast(BPtr, p)
353 assert repr(q).startswith("<cdata 'int *' 0x")
354 assert p == q
355 assert hash(p) == hash(q)
356 e = pytest.raises(TypeError, newp, new_array_type(BPtr, None), None)
357 assert str(e.value) == (
358 "expected new array length or list/tuple/str, not NoneType")
359
360 def test_pointer_bool():
361 BInt = new_primitive_type("int")
362 BPtr = new_pointer_type(BInt)
363 p = cast(BPtr, 0)
364 assert bool(p) is False
365 p = cast(BPtr, 42)
366 assert bool(p) is True
367
368 def test_pointer_to_pointer():
369 BInt = new_primitive_type("int")
370 BPtr = new_pointer_type(BInt)
371 BPtrPtr = new_pointer_type(BPtr)
372 p = newp(BPtrPtr, None)
373 assert repr(p) == "<cdata 'int * *' owning %d bytes>" % size_of_ptr()
374
375 def test_reading_pointer_to_int():
376 BInt = new_primitive_type("int")
377 BPtr = new_pointer_type(BInt)
378 p = newp(BPtr, None)
379 assert p[0] == 0
380 p = newp(BPtr, 5000)
381 assert p[0] == 5000
382 with pytest.raises(IndexError):
383 p[1]
384 with pytest.raises(IndexError):
385 p[-1]
386
387 def test_reading_pointer_to_float():
388 BFloat = new_primitive_type("float")
389 pytest.raises(TypeError, newp, BFloat, None)
390 BPtr = new_pointer_type(BFloat)
391 p = newp(BPtr, None)
392 assert p[0] == 0.0 and type(p[0]) is float
393 p = newp(BPtr, 1.25)
394 assert p[0] == 1.25 and type(p[0]) is float
395 p = newp(BPtr, 1.1)
396 assert p[0] != 1.1 and abs(p[0] - 1.1) < 1E-5 # rounding errors
397
398 def test_cast_float_to_int():
399 for type in ["int", "unsigned int", "long", "unsigned long",
400 "long long", "unsigned long long"]:
401 p = new_primitive_type(type)
402 assert int(cast(p, 4.2)) == 4
403 pytest.raises(TypeError, newp, new_pointer_type(p), 4.2)
404
405 def test_newp_integer_types():
406 for name in ['signed char', 'short', 'int', 'long', 'long long']:
407 p = new_primitive_type(name)
408 pp = new_pointer_type(p)
409 size = sizeof(p)
410 min = -(1 << (8*size-1))
411 max = (1 << (8*size-1)) - 1
412 assert newp(pp, min)[0] == min
413 assert newp(pp, max)[0] == max
414 pytest.raises(OverflowError, newp, pp, min - 2 ** 32)
415 pytest.raises(OverflowError, newp, pp, min - 2 ** 64)
416 pytest.raises(OverflowError, newp, pp, max + 2 ** 32)
417 pytest.raises(OverflowError, newp, pp, max + 2 ** 64)
418 pytest.raises(OverflowError, newp, pp, min - 1)
419 pytest.raises(OverflowError, newp, pp, max + 1)
420 pytest.raises(OverflowError, newp, pp, min - 1 - 2 ** 32)
421 pytest.raises(OverflowError, newp, pp, min - 1 - 2 ** 64)
422 pytest.raises(OverflowError, newp, pp, max + 1)
423 pytest.raises(OverflowError, newp, pp, max + 1 + 2 ** 32)
424 pytest.raises(OverflowError, newp, pp, max + 1 + 2 ** 64)
425 pytest.raises(TypeError, newp, pp, 1.0)
426 for name in ['char', 'short', 'int', 'long', 'long long']:
427 p = new_primitive_type('unsigned ' + name)
428 pp = new_pointer_type(p)
429 size = sizeof(p)
430 max = (1 << (8*size)) - 1
431 assert newp(pp, 0)[0] == 0
432 assert newp(pp, max)[0] == max
433 pytest.raises(OverflowError, newp, pp, -1)
434 pytest.raises(OverflowError, newp, pp, max + 1)
435
436 def test_reading_pointer_to_char():
437 BChar = new_primitive_type("char")
438 pytest.raises(TypeError, newp, BChar, None)
439 BPtr = new_pointer_type(BChar)
440 p = newp(BPtr, None)
441 assert p[0] == b'\x00'
442 p = newp(BPtr, b'A')
443 assert p[0] == b'A'
444 pytest.raises(TypeError, newp, BPtr, 65)
445 pytest.raises(TypeError, newp, BPtr, b"foo")
446 pytest.raises(TypeError, newp, BPtr, u+"foo")
447 c = cast(BChar, b'A')
448 assert str(c) == repr(c)
449 assert int(c) == ord(b'A')
450 pytest.raises(TypeError, cast, BChar, b'foo')
451 pytest.raises(TypeError, cast, BChar, u+'foo')
452 e = pytest.raises(TypeError, newp, new_array_type(BPtr, None), 12.3)
453 assert str(e.value) == (
454 "expected new array length or list/tuple/str, not float")
455
456 def test_reading_pointer_to_pointer():
457 BVoidP = new_pointer_type(new_void_type())
458 BCharP = new_pointer_type(new_primitive_type("char"))
459 BInt = new_primitive_type("int")
460 BIntPtr = new_pointer_type(BInt)
461 BIntPtrPtr = new_pointer_type(BIntPtr)
462 q = newp(BIntPtr, 42)
463 assert q[0] == 42
464 p = newp(BIntPtrPtr, None)
465 assert p[0] is not None
466 assert p[0] == cast(BVoidP, 0)
467 assert p[0] == cast(BCharP, 0)
468 assert p[0] != None
469 assert repr(p[0]) == "<cdata 'int *' NULL>"
470 p[0] = q
471 assert p[0] != cast(BVoidP, 0)
472 assert p[0] != cast(BCharP, 0)
473 assert p[0][0] == 42
474 q[0] += 1
475 assert p[0][0] == 43
476 p = newp(BIntPtrPtr, q)
477 assert p[0][0] == 43
478
479 def test_load_standard_library():
480 if sys.platform == "win32":
481 pytest.raises(OSError, find_and_load_library, None)
482 return
483 x = find_and_load_library(None)
484 BVoidP = new_pointer_type(new_void_type())
485 assert x.load_function(BVoidP, 'strcpy')
486 pytest.raises(AttributeError, x.load_function,
487 BVoidP, 'xxx_this_function_does_not_exist')
488 # the next one is from 'libm', not 'libc', but we assume
489 # that it is already loaded too, so it should work
490 assert x.load_function(BVoidP, 'sqrt')
491 #
492 x.close_lib()
493 pytest.raises(ValueError, x.load_function, BVoidP, 'sqrt')
494 x.close_lib()
495
496 def test_no_len_on_nonarray():
497 p = new_primitive_type("int")
498 pytest.raises(TypeError, len, cast(p, 42))
499
500 def test_cmp_none():
501 p = new_primitive_type("int")
502 x = cast(p, 42)
503 assert (x == None) is False
504 assert (x != None) is True
505 assert (x == ["hello"]) is False
506 assert (x != ["hello"]) is True
507 y = cast(p, 0)
508 assert (y == None) is False
509
510 def test_invalid_indexing():
511 p = new_primitive_type("int")
512 x = cast(p, 42)
513 with pytest.raises(TypeError):
514 x[0]
515
516 def test_default_str():
517 BChar = new_primitive_type("char")
518 x = cast(BChar, 42)
519 assert str(x) == repr(x)
520 BInt = new_primitive_type("int")
521 x = cast(BInt, 42)
522 assert str(x) == repr(x)
523 BArray = new_array_type(new_pointer_type(BInt), 10)
524 x = newp(BArray, None)
525 assert str(x) == repr(x)
526
527 def test_default_unicode():
528 BInt = new_primitive_type("int")
529 x = cast(BInt, 42)
530 assert unicode(x) == unicode(repr(x))
531 BArray = new_array_type(new_pointer_type(BInt), 10)
532 x = newp(BArray, None)
533 assert unicode(x) == unicode(repr(x))
534
535 def test_cast_from_cdataint():
536 BInt = new_primitive_type("int")
537 x = cast(BInt, 0)
538 y = cast(new_pointer_type(BInt), x)
539 assert bool(y) is False
540 #
541 x = cast(BInt, 42)
542 y = cast(BInt, x)
543 assert int(y) == 42
544 y = cast(new_primitive_type("char"), x)
545 assert int(y) == 42
546 y = cast(new_primitive_type("float"), x)
547 assert float(y) == 42.0
548 #
549 z = cast(BInt, 42.5)
550 assert int(z) == 42
551 z = cast(BInt, y)
552 assert int(z) == 42
553
554 def test_void_type():
555 p = new_void_type()
556 assert p.kind == "void"
557 assert p.cname == "void"
558 check_dir(p, ['kind', 'cname'])
559
560 def test_array_type():
561 p = new_primitive_type("int")
562 assert repr(p) == "<ctype 'int'>"
563 #
564 pytest.raises(TypeError, new_array_type, new_pointer_type(p), "foo")
565 pytest.raises(ValueError, new_array_type, new_pointer_type(p), -42)
566 #
567 p1 = new_array_type(new_pointer_type(p), None)
568 assert repr(p1) == "<ctype 'int[]'>"
569 pytest.raises(ValueError, new_array_type, new_pointer_type(p1), 42)
570 #
571 p1 = new_array_type(new_pointer_type(p), 42)
572 p2 = new_array_type(new_pointer_type(p1), 25)
573 assert repr(p2) == "<ctype 'int[25][42]'>"
574 p2 = new_array_type(new_pointer_type(p1), None)
575 assert repr(p2) == "<ctype 'int[][42]'>"
576 #
577 pytest.raises(OverflowError,
578 new_array_type, new_pointer_type(p), sys.maxsize+1)
579 pytest.raises(OverflowError,
580 new_array_type, new_pointer_type(p), sys.maxsize // 3)
581
582 def test_inspect_array_type():
583 p = new_primitive_type("int")
584 p1 = new_array_type(new_pointer_type(p), None)
585 assert p1.kind == "array"
586 assert p1.cname == "int[]"
587 assert p1.item is p
588 assert p1.length is None
589 check_dir(p1, ['cname', 'kind', 'item', 'length'])
590 p1 = new_array_type(new_pointer_type(p), 42)
591 assert p1.kind == "array"
592 assert p1.cname == "int[42]"
593 assert p1.item is p
594 assert p1.length == 42
595 check_dir(p1, ['cname', 'kind', 'item', 'length'])
596
597 def test_array_instance():
598 LENGTH = 1423
599 p = new_primitive_type("int")
600 p1 = new_array_type(new_pointer_type(p), LENGTH)
601 a = newp(p1, None)
602 assert repr(a) == "<cdata 'int[%d]' owning %d bytes>" % (
603 LENGTH, LENGTH * size_of_int())
604 assert len(a) == LENGTH
605 for i in range(LENGTH):
606 assert a[i] == 0
607 with pytest.raises(IndexError):
608 a[LENGTH]
609 with pytest.raises(IndexError):
610 a[-1]
611 for i in range(LENGTH):
612 a[i] = i * i + 1
613 for i in range(LENGTH):
614 assert a[i] == i * i + 1
615 with pytest.raises(IndexError) as e:
616 a[LENGTH+100] = 500
617 assert ('(expected %d < %d)' % (LENGTH+100, LENGTH)) in str(e.value)
618 pytest.raises(TypeError, int, a)
619
620 def test_array_of_unknown_length_instance():
621 p = new_primitive_type("int")
622 p1 = new_array_type(new_pointer_type(p), None)
623 pytest.raises(TypeError, newp, p1, None)
624 pytest.raises(ValueError, newp, p1, -42)
625 a = newp(p1, 42)
626 assert len(a) == 42
627 for i in range(42):
628 a[i] -= i
629 for i in range(42):
630 assert a[i] == -i
631 with pytest.raises(IndexError):
632 a[42]
633 with pytest.raises(IndexError):
634 a[-1]
635 with pytest.raises(IndexError):
636 a[42] = 123
637 with pytest.raises(IndexError):
638 a[-1] = 456
639
640 def test_array_of_unknown_length_instance_with_initializer():
641 p = new_primitive_type("int")
642 p1 = new_array_type(new_pointer_type(p), None)
643 a = newp(p1, list(range(42)))
644 assert len(a) == 42
645 a = newp(p1, tuple(range(142)))
646 assert len(a) == 142
647
648 def test_array_initializer():
649 p = new_primitive_type("int")
650 p1 = new_array_type(new_pointer_type(p), None)
651 a = newp(p1, list(range(100, 142)))
652 for i in range(42):
653 assert a[i] == 100 + i
654 #
655 p2 = new_array_type(new_pointer_type(p), 43)
656 a = newp(p2, tuple(range(100, 142)))
657 for i in range(42):
658 assert a[i] == 100 + i
659 assert a[42] == 0 # extra uninitialized item
660
661 def test_array_add():
662 p = new_primitive_type("int")
663 p1 = new_array_type(new_pointer_type(p), 5) # int[5]
664 p2 = new_array_type(new_pointer_type(p1), 3) # int[3][5]
665 a = newp(p2, [list(range(n, n+5)) for n in [100, 200, 300]])
666 assert repr(a) == "<cdata 'int[3][5]' owning %d bytes>" % (
667 3*5*size_of_int(),)
668 assert repr(a + 0).startswith("<cdata 'int(*)[5]' 0x")
669 assert 0 + a == a + 0 != 1 + a == a + 1
670 assert repr(a[0]).startswith("<cdata 'int[5]' 0x")
671 assert repr((a + 0)[0]).startswith("<cdata 'int[5]' 0x")
672 assert repr(a[0] + 0).startswith("<cdata 'int *' 0x")
673 assert type(a[0][0]) is int
674 assert type((a[0] + 0)[0]) is int
675
676 def test_array_sub():
677 BInt = new_primitive_type("int")
678 BArray = new_array_type(new_pointer_type(BInt), 5) # int[5]
679 a = newp(BArray, None)
680 p = a + 1
681 assert p - a == 1
682 assert p - (a+0) == 1
683 assert a == (p - 1)
684 BPtr = new_pointer_type(new_primitive_type("short"))
685 q = newp(BPtr, None)
686 with pytest.raises(TypeError):
687 p - q
688 with pytest.raises(TypeError):
689 q - p
690 with pytest.raises(TypeError):
691 a - q
692 with pytest.raises(TypeError) as e:
693 q - a
694 assert str(e.value) == "cannot subtract cdata 'short *' and cdata 'int *'"
695
696 def test_ptr_sub_unaligned():
697 BInt = new_primitive_type("int")
698 BIntPtr = new_pointer_type(BInt)
699 a = cast(BIntPtr, 1240)
700 for bi in range(1430, 1438):
701 b = cast(BIntPtr, bi)
702 if ((bi - 1240) % size_of_int()) == 0:
703 assert b - a == (bi - 1240) // size_of_int()
704 assert a - b == (1240 - bi) // size_of_int()
705 else:
706 with pytest.raises(ValueError):
707 b - a
708 with pytest.raises(ValueError):
709 a - b
710
711 def test_cast_primitive_from_cdata():
712 p = new_primitive_type("int")
713 n = cast(p, cast(p, -42))
714 assert int(n) == -42
715 #
716 p = new_primitive_type("unsigned int")
717 n = cast(p, cast(p, 42))
718 assert int(n) == 42
719 #
720 p = new_primitive_type("long long")
721 n = cast(p, cast(p, -(1<<60)))
722 assert int(n) == -(1<<60)
723 #
724 p = new_primitive_type("unsigned long long")
725 n = cast(p, cast(p, 1<<63))
726 assert int(n) == 1<<63
727 #
728 p = new_primitive_type("float")
729 n = cast(p, cast(p, 42.5))
730 assert float(n) == 42.5
731 #
732 p = new_primitive_type("char")
733 n = cast(p, cast(p, "A"))
734 assert int(n) == ord("A")
735
736 def test_new_primitive_from_cdata():
737 p = new_primitive_type("int")
738 p1 = new_pointer_type(p)
739 n = newp(p1, cast(p, -42))
740 assert n[0] == -42
741 #
742 p = new_primitive_type("unsigned int")
743 p1 = new_pointer_type(p)
744 n = newp(p1, cast(p, 42))
745 assert n[0] == 42
746 #
747 p = new_primitive_type("float")
748 p1 = new_pointer_type(p)
749 n = newp(p1, cast(p, 42.5))
750 assert n[0] == 42.5
751 #
752 p = new_primitive_type("char")
753 p1 = new_pointer_type(p)
754 n = newp(p1, cast(p, "A"))
755 assert n[0] == b"A"
756
757 def test_cast_between_pointers():
758 BIntP = new_pointer_type(new_primitive_type("int"))
759 BIntA = new_array_type(BIntP, None)
760 a = newp(BIntA, [40, 41, 42, 43, 44])
761 BShortP = new_pointer_type(new_primitive_type("short"))
762 b = cast(BShortP, a)
763 c = cast(BIntP, b)
764 assert c[3] == 43
765 BLongLong = new_primitive_type("long long")
766 d = cast(BLongLong, c)
767 e = cast(BIntP, d)
768 assert e[3] == 43
769 f = cast(BIntP, int(d))
770 assert f[3] == 43
771 #
772 b = cast(BShortP, 0)
773 assert not b
774 c = cast(BIntP, b)
775 assert not c
776 assert int(cast(BLongLong, c)) == 0
777
778 def test_alignof():
779 BInt = new_primitive_type("int")
780 assert alignof(BInt) == sizeof(BInt)
781 BPtr = new_pointer_type(BInt)
782 assert alignof(BPtr) == sizeof(BPtr)
783 BArray = new_array_type(BPtr, None)
784 assert alignof(BArray) == alignof(BInt)
785
786 def test_new_struct_type():
787 BStruct = new_struct_type("foo")
788 assert repr(BStruct) == "<ctype 'foo'>"
789 BStruct = new_struct_type("struct foo")
790 assert repr(BStruct) == "<ctype 'struct foo'>"
791 BPtr = new_pointer_type(BStruct)
792 assert repr(BPtr) == "<ctype 'struct foo *'>"
793 pytest.raises(ValueError, sizeof, BStruct)
794 pytest.raises(ValueError, alignof, BStruct)
795
796 def test_new_union_type():
797 BUnion = new_union_type("union foo")
798 assert repr(BUnion) == "<ctype 'union foo'>"
799 BPtr = new_pointer_type(BUnion)
800 assert repr(BPtr) == "<ctype 'union foo *'>"
801
802 def test_complete_struct():
803 BLong = new_primitive_type("long")
804 BChar = new_primitive_type("char")
805 BShort = new_primitive_type("short")
806 BStruct = new_struct_type("struct foo")
807 assert BStruct.kind == "struct"
808 assert BStruct.cname == "struct foo"
809 assert BStruct.fields is None
810 check_dir(BStruct, ['cname', 'kind', 'fields'])
811 #
812 complete_struct_or_union(BStruct, [('a1', BLong, -1),
813 ('a2', BChar, -1),
814 ('a3', BShort, -1)])
815 d = BStruct.fields
816 assert len(d) == 3
817 assert d[0][0] == 'a1'
818 assert d[0][1].type is BLong
819 assert d[0][1].offset == 0
820 assert d[0][1].bitshift == -1
821 assert d[0][1].bitsize == -1
822 assert d[1][0] == 'a2'
823 assert d[1][1].type is BChar
824 assert d[1][1].offset == sizeof(BLong)
825 assert d[1][1].bitshift == -1
826 assert d[1][1].bitsize == -1
827 assert d[2][0] == 'a3'
828 assert d[2][1].type is BShort
829 assert d[2][1].offset == sizeof(BLong) + sizeof(BShort)
830 assert d[2][1].bitshift == -1
831 assert d[2][1].bitsize == -1
832 assert sizeof(BStruct) == 2 * sizeof(BLong)
833 assert alignof(BStruct) == alignof(BLong)
834
835 def test_complete_union():
836 BLong = new_primitive_type("long")
837 BChar = new_primitive_type("char")
838 BUnion = new_union_type("union foo")
839 assert BUnion.kind == "union"
840 assert BUnion.cname == "union foo"
841 assert BUnion.fields is None
842 complete_struct_or_union(BUnion, [('a1', BLong, -1),
843 ('a2', BChar, -1)])
844 d = BUnion.fields
845 assert len(d) == 2
846 assert d[0][0] == 'a1'
847 assert d[0][1].type is BLong
848 assert d[0][1].offset == 0
849 assert d[1][0] == 'a2'
850 assert d[1][1].type is BChar
851 assert d[1][1].offset == 0
852 assert sizeof(BUnion) == sizeof(BLong)
853 assert alignof(BUnion) == alignof(BLong)
854
855 def test_struct_instance():
856 BInt = new_primitive_type("int")
857 BStruct = new_struct_type("struct foo")
858 BStructPtr = new_pointer_type(BStruct)
859 p = cast(BStructPtr, 42)
860 with pytest.raises(AttributeError) as e:
861 p.a1 # opaque
862 assert str(e.value) == ("cdata 'struct foo *' points to an opaque type: "
863 "cannot read fields")
864 with pytest.raises(AttributeError) as e:
865 p.a1 = 10 # opaque
866 assert str(e.value) == ("cdata 'struct foo *' points to an opaque type: "
867 "cannot write fields")
868
869 complete_struct_or_union(BStruct, [('a1', BInt, -1),
870 ('a2', BInt, -1)])
871 p = newp(BStructPtr, None)
872 s = p[0]
873 assert s.a1 == 0
874 s.a2 = 123
875 assert s.a1 == 0
876 assert s.a2 == 123
877 with pytest.raises(OverflowError):
878 s.a1 = sys.maxsize+1
879 assert s.a1 == 0
880 with pytest.raises(AttributeError) as e:
881 p.foobar
882 assert str(e.value) == "cdata 'struct foo *' has no field 'foobar'"
883 with pytest.raises(AttributeError) as e:
884 p.foobar = 42
885 assert str(e.value) == "cdata 'struct foo *' has no field 'foobar'"
886 with pytest.raises(AttributeError) as e:
887 s.foobar
888 assert str(e.value) == "cdata 'struct foo' has no field 'foobar'"
889 with pytest.raises(AttributeError) as e:
890 s.foobar = 42
891 assert str(e.value) == "cdata 'struct foo' has no field 'foobar'"
892 j = cast(BInt, 42)
893 with pytest.raises(AttributeError) as e:
894 j.foobar
895 assert str(e.value) == "cdata 'int' has no attribute 'foobar'"
896 with pytest.raises(AttributeError) as e:
897 j.foobar = 42
898 assert str(e.value) == "cdata 'int' has no attribute 'foobar'"
899 j = cast(new_pointer_type(BInt), 42)
900 with pytest.raises(AttributeError) as e:
901 j.foobar
902 assert str(e.value) == "cdata 'int *' has no attribute 'foobar'"
903 with pytest.raises(AttributeError) as e:
904 j.foobar = 42
905 assert str(e.value) == "cdata 'int *' has no attribute 'foobar'"
906 pp = newp(new_pointer_type(BStructPtr), p)
907 with pytest.raises(AttributeError) as e:
908 pp.a1
909 assert str(e.value) == "cdata 'struct foo * *' has no attribute 'a1'"
910 with pytest.raises(AttributeError) as e:
911 pp.a1 = 42
912 assert str(e.value) == "cdata 'struct foo * *' has no attribute 'a1'"
913
914 def test_union_instance():
915 BInt = new_primitive_type("int")
916 BUInt = new_primitive_type("unsigned int")
917 BUnion = new_union_type("union bar")
918 complete_struct_or_union(BUnion, [('a1', BInt, -1), ('a2', BUInt, -1)])
919 p = newp(new_pointer_type(BUnion), [-42])
920 bigval = -42 + (1 << (8*size_of_int()))
921 assert p.a1 == -42
922 assert p.a2 == bigval
923 p = newp(new_pointer_type(BUnion), {'a2': bigval})
924 assert p.a1 == -42
925 assert p.a2 == bigval
926 pytest.raises(OverflowError, newp, new_pointer_type(BUnion),
927 {'a1': bigval})
928 p = newp(new_pointer_type(BUnion), [])
929 assert p.a1 == p.a2 == 0
930
931 def test_struct_pointer():
932 BInt = new_primitive_type("int")
933 BStruct = new_struct_type("struct foo")
934 BStructPtr = new_pointer_type(BStruct)
935 complete_struct_or_union(BStruct, [('a1', BInt, -1),
936 ('a2', BInt, -1)])
937 p = newp(BStructPtr, None)
938 assert p.a1 == 0 # read/write via the pointer (C equivalent: '->')
939 p.a2 = 123
940 assert p.a1 == 0
941 assert p.a2 == 123
942
943 def test_struct_init_list():
944 BVoidP = new_pointer_type(new_void_type())
945 BInt = new_primitive_type("int")
946 BIntPtr = new_pointer_type(BInt)
947 BStruct = new_struct_type("struct foo")
948 BStructPtr = new_pointer_type(BStruct)
949 complete_struct_or_union(BStruct, [('a1', BInt, -1),
950 ('a2', BInt, -1),
951 ('a3', BInt, -1),
952 ('p4', BIntPtr, -1)])
953 s = newp(BStructPtr, [123, 456])
954 assert s.a1 == 123
955 assert s.a2 == 456
956 assert s.a3 == 0
957 assert s.p4 == cast(BVoidP, 0)
958 assert s.p4 != 0
959 #
960 s = newp(BStructPtr, {'a2': 41122, 'a3': -123})
961 assert s.a1 == 0
962 assert s.a2 == 41122
963 assert s.a3 == -123
964 assert s.p4 == cast(BVoidP, 0)
965 #
966 pytest.raises(KeyError, newp, BStructPtr, {'foobar': 0})
967 #
968 p = newp(BIntPtr, 14141)
969 s = newp(BStructPtr, [12, 34, 56, p])
970 assert s.p4 == p
971 assert s.p4
972 #
973 s = newp(BStructPtr, [12, 34, 56, cast(BVoidP, 0)])
974 assert s.p4 == cast(BVoidP, 0)
975 assert not s.p4
976 #
977 pytest.raises(TypeError, newp, BStructPtr, [12, 34, 56, None])
978
979 def test_array_in_struct():
980 BInt = new_primitive_type("int")
981 BStruct = new_struct_type("struct foo")
982 BArrayInt5 = new_array_type(new_pointer_type(BInt), 5)
983 complete_struct_or_union(BStruct, [('a1', BArrayInt5, -1)])
984 s = newp(new_pointer_type(BStruct), [[20, 24, 27, 29, 30]])
985 assert s.a1[2] == 27
986 assert repr(s.a1).startswith("<cdata 'int[5]' 0x")
987
988 def test_offsetof():
989 def offsetof(BType, fieldname):
990 return typeoffsetof(BType, fieldname)[1]
991 BInt = new_primitive_type("int")
992 BStruct = new_struct_type("struct foo")
993 pytest.raises(TypeError, offsetof, BInt, "abc")
994 pytest.raises(TypeError, offsetof, BStruct, "abc")
995 complete_struct_or_union(BStruct, [('abc', BInt, -1), ('def', BInt, -1)])
996 assert offsetof(BStruct, 'abc') == 0
997 assert offsetof(BStruct, 'def') == size_of_int()
998 pytest.raises(KeyError, offsetof, BStruct, "ghi")
999 assert offsetof(new_pointer_type(BStruct), "def") == size_of_int()
1000
1001 def test_function_type():
1002 BInt = new_primitive_type("int")
1003 BFunc = new_function_type((BInt, BInt), BInt, False)
1004 assert repr(BFunc) == "<ctype 'int(*)(int, int)'>"
1005 BFunc2 = new_function_type((), BFunc, False)
1006 assert repr(BFunc2) == "<ctype 'int(*(*)())(int, int)'>"
1007
1008 def test_inspect_function_type():
1009 BInt = new_primitive_type("int")
1010 BFunc = new_function_type((BInt, BInt), BInt, False)
1011 assert BFunc.kind == "function"
1012 assert BFunc.cname == "int(*)(int, int)"
1013 assert BFunc.args == (BInt, BInt)
1014 assert BFunc.result is BInt
1015 assert BFunc.ellipsis is False
1016 assert BFunc.abi == FFI_DEFAULT_ABI
1017
1018 def test_function_type_taking_struct():
1019 BChar = new_primitive_type("char")
1020 BShort = new_primitive_type("short")
1021 BStruct = new_struct_type("struct foo")
1022 complete_struct_or_union(BStruct, [('a1', BChar, -1),
1023 ('a2', BShort, -1)])
1024 BFunc = new_function_type((BStruct,), BShort, False)
1025 assert repr(BFunc) == "<ctype 'short(*)(struct foo)'>"
1026
1027 def test_function_void_result():
1028 BVoid = new_void_type()
1029 BInt = new_primitive_type("int")
1030 BFunc = new_function_type((BInt, BInt), BVoid, False)
1031 assert repr(BFunc) == "<ctype 'void(*)(int, int)'>"
1032
1033 def test_function_void_arg():
1034 BVoid = new_void_type()
1035 BInt = new_primitive_type("int")
1036 pytest.raises(TypeError, new_function_type, (BVoid,), BInt, False)
1037
1038 def test_call_function_0():
1039 BSignedChar = new_primitive_type("signed char")
1040 BFunc0 = new_function_type((BSignedChar, BSignedChar), BSignedChar, False)
1041 f = cast(BFunc0, _testfunc(0))
1042 assert f(40, 2) == 42
1043 assert f(-100, -100) == -200 + 256
1044 pytest.raises(OverflowError, f, 128, 0)
1045 pytest.raises(OverflowError, f, 0, 128)
1046
1047 def test_call_function_0_pretend_bool_result():
1048 BSignedChar = new_primitive_type("signed char")
1049 BBool = new_primitive_type("_Bool")
1050 BFunc0 = new_function_type((BSignedChar, BSignedChar), BBool, False)
1051 f = cast(BFunc0, _testfunc(0))
1052 assert f(40, -39) is True
1053 assert f(40, -40) is False
1054 pytest.raises(ValueError, f, 40, 2)
1055
1056 def test_call_function_1():
1057 BInt = new_primitive_type("int")
1058 BLong = new_primitive_type("long")
1059 BFunc1 = new_function_type((BInt, BLong), BLong, False)
1060 f = cast(BFunc1, _testfunc(1))
1061 assert f(40, 2) == 42
1062 assert f(-100, -100) == -200
1063 int_max = (1 << (8*size_of_int()-1)) - 1
1064 long_max = (1 << (8*size_of_long()-1)) - 1
1065 if int_max == long_max:
1066 assert f(int_max, 1) == - int_max - 1
1067 else:
1068 assert f(int_max, 1) == int_max + 1
1069
1070 def test_call_function_2():
1071 BLongLong = new_primitive_type("long long")
1072 BFunc2 = new_function_type((BLongLong, BLongLong), BLongLong, False)
1073 f = cast(BFunc2, _testfunc(2))
1074 longlong_max = (1 << (8*sizeof(BLongLong)-1)) - 1
1075 assert f(longlong_max - 42, 42) == longlong_max
1076 assert f(43, longlong_max - 42) == - longlong_max - 1
1077
1078 def test_call_function_3():
1079 BFloat = new_primitive_type("float")
1080 BDouble = new_primitive_type("double")
1081 BFunc3 = new_function_type((BFloat, BDouble), BDouble, False)
1082 f = cast(BFunc3, _testfunc(3))
1083 assert f(1.25, 5.1) == 1.25 + 5.1 # exact
1084 res = f(1.3, 5.1)
1085 assert res != 6.4 and abs(res - 6.4) < 1E-5 # inexact
1086
1087 def test_call_function_4():
1088 BFloat = new_primitive_type("float")
1089 BDouble = new_primitive_type("double")
1090 BFunc4 = new_function_type((BFloat, BDouble), BFloat, False)
1091 f = cast(BFunc4, _testfunc(4))
1092 res = f(1.25, 5.1)
1093 assert res != 6.35 and abs(res - 6.35) < 1E-5 # inexact
1094
1095 def test_call_function_5():
1096 BVoid = new_void_type()
1097 BFunc5 = new_function_type((), BVoid, False)
1098 f = cast(BFunc5, _testfunc(5))
1099 f() # did not crash
1100
1101 def test_call_function_6():
1102 BInt = new_primitive_type("int")
1103 BIntPtr = new_pointer_type(BInt)
1104 BFunc6 = new_function_type((BIntPtr,), BIntPtr, False)
1105 f = cast(BFunc6, _testfunc(6))
1106 x = newp(BIntPtr, 42)
1107 res = f(x)
1108 assert typeof(res) is BIntPtr
1109 assert res[0] == 42 - 1000
1110 #
1111 BIntArray = new_array_type(BIntPtr, None)
1112 BFunc6bis = new_function_type((BIntArray,), BIntPtr, False)
1113 f = cast(BFunc6bis, _testfunc(6))
1114 #
1115 res = f([142])
1116 assert typeof(res) is BIntPtr
1117 assert res[0] == 142 - 1000
1118 #
1119 res = f((143,))
1120 assert typeof(res) is BIntPtr
1121 assert res[0] == 143 - 1000
1122 #
1123 x = newp(BIntArray, [242])
1124 res = f(x)
1125 assert typeof(res) is BIntPtr
1126 assert res[0] == 242 - 1000
1127 #
1128 pytest.raises(TypeError, f, 123456)
1129 pytest.raises(TypeError, f, "foo")
1130 pytest.raises(TypeError, f, u+"bar")
1131
1132 def test_call_function_7():
1133 BChar = new_primitive_type("char")
1134 BShort = new_primitive_type("short")
1135 BStruct = new_struct_type("struct foo")
1136 BStructPtr = new_pointer_type(BStruct)
1137 complete_struct_or_union(BStruct, [('a1', BChar, -1),
1138 ('a2', BShort, -1)])
1139 BFunc7 = new_function_type((BStruct,), BShort, False)
1140 f = cast(BFunc7, _testfunc(7))
1141 res = f({'a1': b'A', 'a2': -4042})
1142 assert res == -4042 + ord(b'A')
1143 #
1144 x = newp(BStructPtr, {'a1': b'A', 'a2': -4042})
1145 res = f(x[0])
1146 assert res == -4042 + ord(b'A')
1147
1148 def test_call_function_20():
1149 BChar = new_primitive_type("char")
1150 BShort = new_primitive_type("short")
1151 BStruct = new_struct_type("struct foo")
1152 BStructPtr = new_pointer_type(BStruct)
1153 complete_struct_or_union(BStruct, [('a1', BChar, -1),
1154 ('a2', BShort, -1)])
1155 BFunc20 = new_function_type((BStructPtr,), BShort, False)
1156 f = cast(BFunc20, _testfunc(20))
1157 x = newp(BStructPtr, {'a1': b'A', 'a2': -4042})
1158 # can't pass a 'struct foo'
1159 pytest.raises(TypeError, f, x[0])
1160
1161 def test_call_function_21():
1162 BInt = new_primitive_type("int")
1163 BStruct = new_struct_type("struct foo")
1164 complete_struct_or_union(BStruct, [('a', BInt, -1),
1165 ('b', BInt, -1),
1166 ('c', BInt, -1),
1167 ('d', BInt, -1),
1168 ('e', BInt, -1),
1169 ('f', BInt, -1),
1170 ('g', BInt, -1),
1171 ('h', BInt, -1),
1172 ('i', BInt, -1),
1173 ('j', BInt, -1)])
1174 BFunc21 = new_function_type((BStruct,), BInt, False)
1175 f = cast(BFunc21, _testfunc(21))
1176 res = f(list(range(13, 3, -1)))
1177 lst = [(n << i) for (i, n) in enumerate(range(13, 3, -1))]
1178 assert res == sum(lst)
1179
1180 def test_call_function_22():
1181 BInt = new_primitive_type("int")
1182 BArray10 = new_array_type(new_pointer_type(BInt), 10)
1183 BStruct = new_struct_type("struct foo")
1184 BStructP = new_pointer_type(BStruct)
1185 complete_struct_or_union(BStruct, [('a', BArray10, -1)])
1186 BFunc22 = new_function_type((BStruct, BStruct), BStruct, False)
1187 f = cast(BFunc22, _testfunc(22))
1188 p1 = newp(BStructP, {'a': list(range(100, 110))})
1189 p2 = newp(BStructP, {'a': list(range(1000, 1100, 10))})
1190 res = f(p1[0], p2[0])
1191 for i in range(10):
1192 assert res.a[i] == p1.a[i] - p2.a[i]
1193
1194 def test_call_function_23():
1195 BVoid = new_void_type() # declaring the function as int(void*)
1196 BVoidP = new_pointer_type(BVoid)
1197 BInt = new_primitive_type("int")
1198 BFunc23 = new_function_type((BVoidP,), BInt, False)
1199 f = cast(BFunc23, _testfunc(23))
1200 res = f(b"foo")
1201 assert res == 1000 * ord(b'f')
1202 res = f(cast(BVoidP, 0)) # NULL
1203 assert res == -42
1204 pytest.raises(TypeError, f, None)
1205 pytest.raises(TypeError, f, 0)
1206 pytest.raises(TypeError, f, 0.0)
1207
1208 def test_call_function_23_bis():
1209 # declaring the function as int(unsigned char*)
1210 BUChar = new_primitive_type("unsigned char")
1211 BUCharP = new_pointer_type(BUChar)
1212 BInt = new_primitive_type("int")
1213 BFunc23 = new_function_type((BUCharP,), BInt, False)
1214 f = cast(BFunc23, _testfunc(23))
1215 res = f(b"foo")
1216 assert res == 1000 * ord(b'f')
1217
1218 def test_call_function_23_bool_array():
1219 # declaring the function as int(_Bool*)
1220 BBool = new_primitive_type("_Bool")
1221 BBoolP = new_pointer_type(BBool)
1222 BInt = new_primitive_type("int")
1223 BFunc23 = new_function_type((BBoolP,), BInt, False)
1224 f = cast(BFunc23, _testfunc(23))
1225 res = f(b"\x01\x01")
1226 assert res == 1000
1227 pytest.raises(ValueError, f, b"\x02\x02")
1228
1229 def test_cannot_pass_struct_with_array_of_length_0():
1230 BInt = new_primitive_type("int")
1231 BArray0 = new_array_type(new_pointer_type(BInt), 0)
1232 BStruct = new_struct_type("struct foo")
1233 BStructP = new_pointer_type(BStruct)
1234 complete_struct_or_union(BStruct, [('a', BArray0)])
1235 BFunc = new_function_type((BStruct,), BInt, False)
1236 pytest.raises(NotImplementedError, cast(BFunc, 123), cast(BStructP, 123))
1237 BFunc2 = new_function_type((BInt,), BStruct, False)
1238 pytest.raises(NotImplementedError, cast(BFunc2, 123), 123)
1239
1240 def test_call_function_9():
1241 BInt = new_primitive_type("int")
1242 BFunc9 = new_function_type((BInt,), BInt, True) # vararg
1243 f = cast(BFunc9, _testfunc(9))
1244 assert f(0) == 0
1245 assert f(1, cast(BInt, 42)) == 42
1246 assert f(2, cast(BInt, 40), cast(BInt, 2)) == 42
1247 pytest.raises(TypeError, f, 1, 42)
1248 pytest.raises(TypeError, f, 2, None)
1249 # promotion of chars and shorts to ints
1250 BSChar = new_primitive_type("signed char")
1251 BUChar = new_primitive_type("unsigned char")
1252 BSShort = new_primitive_type("short")
1253 assert f(3, cast(BSChar, -3), cast(BUChar, 200), cast(BSShort, -5)) == 192
1254
1255 def test_call_function_24():
1256 BFloat = new_primitive_type("float")
1257 BFloatComplex = new_primitive_type("_cffi_float_complex_t")
1258 BFunc3 = new_function_type((BFloat, BFloat), BFloatComplex, False)
1259 if 0: # libffi returning nonsense silently, so logic disabled for now
1260 f = cast(BFunc3, _testfunc(24))
1261 result = f(1.25, 5.1)
1262 assert type(result) == complex
1263 assert result.real == 1.25 # exact
1264 assert (result.imag != 2*5.1) and (abs(result.imag - 2*5.1) < 1e-5) # inexact
1265 else:
1266 f = cast(BFunc3, _testfunc(9))
1267 pytest.raises(NotImplementedError, f, 12.3, 34.5)
1268
1269 def test_call_function_25():
1270 BDouble = new_primitive_type("double")
1271 BDoubleComplex = new_primitive_type("_cffi_double_complex_t")
1272 BFunc3 = new_function_type((BDouble, BDouble), BDoubleComplex, False)
1273 if 0: # libffi returning nonsense silently, so logic disabled for now
1274 f = cast(BFunc3, _testfunc(25))
1275 result = f(1.25, 5.1)
1276 assert type(result) == complex
1277 assert result.real == 1.25 # exact
1278 assert (result.imag != 2*5.1) and (abs(result.imag - 2*5.1) < 1e-10) # inexact
1279 else:
1280 f = cast(BFunc3, _testfunc(9))
1281 pytest.raises(NotImplementedError, f, 12.3, 34.5)
1282
1283 def test_cannot_call_with_a_autocompleted_struct():
1284 BSChar = new_primitive_type("signed char")
1285 BDouble = new_primitive_type("double")
1286 BStruct = new_struct_type("struct foo")
1287 BStructPtr = new_pointer_type(BStruct)
1288 complete_struct_or_union(BStruct, [('c', BDouble, -1, 8),
1289 ('a', BSChar, -1, 2),
1290 ('b', BSChar, -1, 0)])
1291 BFunc = new_function_type((BStruct,), BDouble) # internally not callable
1292 dummy_func = cast(BFunc, 42)
1293 e = pytest.raises(NotImplementedError, dummy_func, "?")
1294 msg = ("ctype 'struct foo' not supported as argument. It is a struct "
1295 'declared with "...;", but the C calling convention may depend '
1296 "on the missing fields; or, it contains anonymous struct/unions. "
1297 "Such structs are only supported as argument if the function is "
1298 "'API mode' and non-variadic (i.e. declared inside ffibuilder."
1299 "cdef()+ffibuilder.set_source() and not taking a final '...' "
1300 "argument)")
1301 assert str(e.value) == msg
1302
1303 def test_new_charp():
1304 BChar = new_primitive_type("char")
1305 BCharP = new_pointer_type(BChar)
1306 BCharA = new_array_type(BCharP, None)
1307 x = newp(BCharA, 42)
1308 assert len(x) == 42
1309 x = newp(BCharA, b"foobar")
1310 assert len(x) == 7
1311
1312 def test_load_and_call_function():
1313 BChar = new_primitive_type("char")
1314 BCharP = new_pointer_type(BChar)
1315 BLong = new_primitive_type("long")
1316 BFunc = new_function_type((BCharP,), BLong, False)
1317 ll = find_and_load_library('c')
1318 strlen = ll.load_function(BFunc, "strlen")
1319 input = newp(new_array_type(BCharP, None), b"foobar")
1320 assert strlen(input) == 6
1321 #
1322 assert strlen(b"foobarbaz") == 9
1323 #
1324 BVoidP = new_pointer_type(new_void_type())
1325 strlenaddr = ll.load_function(BVoidP, "strlen")
1326 assert strlenaddr == cast(BVoidP, strlen)
1327
1328 def test_read_variable():
1329 ## FIXME: this test assumes glibc specific behavior, it's not compliant with C standard
1330 ## https://bugs.pypy.org/issue1643
1331 if not sys.platform.startswith("linux"):
1332 skip("untested")
1333 BVoidP = new_pointer_type(new_void_type())
1334 ll = find_and_load_library('c')
1335 stderr = ll.read_variable(BVoidP, "stderr")
1336 assert stderr == cast(BVoidP, _testfunc(8))
1337 #
1338 ll.close_lib()
1339 pytest.raises(ValueError, ll.read_variable, BVoidP, "stderr")
1340
1341 def test_read_variable_as_unknown_length_array():
1342 ## FIXME: this test assumes glibc specific behavior, it's not compliant with C standard
1343 ## https://bugs.pypy.org/issue1643
1344 if not sys.platform.startswith("linux"):
1345 skip("untested")
1346 BCharP = new_pointer_type(new_primitive_type("char"))
1347 BArray = new_array_type(BCharP, None)
1348 ll = find_and_load_library('c')
1349 stderr = ll.read_variable(BArray, "stderr")
1350 assert repr(stderr).startswith("<cdata 'char *' 0x")
1351 # ^^ and not 'char[]', which is basically not allowed and would crash
1352
1353 def test_write_variable():
1354 ## FIXME: this test assumes glibc specific behavior, it's not compliant with C standard
1355 ## https://bugs.pypy.org/issue1643
1356 if not sys.platform.startswith("linux") or is_musl:
1357 skip("untested")
1358 BVoidP = new_pointer_type(new_void_type())
1359 ll = find_and_load_library('c')
1360 stderr = ll.read_variable(BVoidP, "stderr")
1361 ll.write_variable(BVoidP, "stderr", cast(BVoidP, 0))
1362 assert ll.read_variable(BVoidP, "stderr") is not None
1363 assert not ll.read_variable(BVoidP, "stderr")
1364 ll.write_variable(BVoidP, "stderr", stderr)
1365 assert ll.read_variable(BVoidP, "stderr") == stderr
1366 #
1367 ll.close_lib()
1368 pytest.raises(ValueError, ll.write_variable, BVoidP, "stderr", stderr)
1369
1370
1371 def test_callback():
1372 BInt = new_primitive_type("int")
1373 def make_callback():
1374 def cb(n):
1375 return n + 1
1376 BFunc = new_function_type((BInt,), BInt, False)
1377 return callback(BFunc, cb, 42) # 'cb' and 'BFunc' go out of scope
1378 f = make_callback()
1379 assert f(-142) == -141
1380 assert repr(f).startswith(
1381 "<cdata 'int(*)(int)' calling <function ")
1382 assert "cb at 0x" in repr(f)
1383 e = pytest.raises(TypeError, f)
1384 assert str(e.value) == "'int(*)(int)' expects 1 arguments, got 0"
1385
1386
1387 def test_callback_exception():
1388 def check_value(x):
1389 if x == 10000:
1390 raise ValueError(42)
1391 def Zcb1(x):
1392 check_value(x)
1393 return x * 3
1394 BShort = new_primitive_type("short")
1395 BFunc = new_function_type((BShort,), BShort, False)
1396
1397 f = callback(BFunc, Zcb1, -42)
1398 seen = []
1399 oops_result = None
1400 def oops(*args):
1401 seen.append(args)
1402 return oops_result
1403 ff = callback(BFunc, Zcb1, -42, oops)
1404 with _assert_unraisable(None):
1405 assert f(100) == 300
1406 with _assert_unraisable(ValueError, '42', ['in Zcb1', 'in check_value']):
1407 assert f(10000) == -42
1408
1409 bigvalue = 20000
1410 with _assert_unraisable(OverflowError, "integer 60000 does not fit 'short'", ['callback', 'Zcb1']):
1411 assert f(bigvalue) == -42
1412 assert len(seen) == 0
1413
1414 with _assert_unraisable(None):
1415 assert ff(bigvalue) == -42
1416 assert len(seen) == 1
1417 exc, val, tb = seen[0]
1418 assert exc is OverflowError
1419 assert str(val) == "integer 60000 does not fit 'short'"
1420
1421 del seen[:]
1422 oops_result = 81
1423 with _assert_unraisable(None):
1424 assert ff(bigvalue) == 81
1425
1426 assert len(seen) == 1
1427 exc, val, tb = seen[0]
1428 assert exc is OverflowError
1429 assert str(val) == "integer 60000 does not fit 'short'"
1430
1431 del seen[:]
1432 oops_result = "xy" # not None and not an int!
1433
1434 with _assert_unraisable(TypeError, "an integer is required", ["integer 60000 does not fit 'short'"]):
1435 assert ff(bigvalue) == -42
1436
1437 seen = "not a list" # this makes the oops() function crash
1438 oops_result = None
1439 with _assert_unraisable(AttributeError, "'str' object has no attribute 'append", ['Zcb1', 'ff', 'oops']):
1440 assert ff(bigvalue) == -42
1441
1442
1443 def test_callback_return_type():
1444 for rettype in ["signed char", "short", "int", "long", "long long",
1445 "unsigned char", "unsigned short", "unsigned int",
1446 "unsigned long", "unsigned long long"]:
1447 BRet = new_primitive_type(rettype)
1448 def cb(n):
1449 return n + 1
1450 BFunc = new_function_type((BRet,), BRet)
1451 f = callback(BFunc, cb, 42)
1452 assert f(41) == 42
1453 if rettype.startswith("unsigned "):
1454 min = 0
1455 max = (1 << (8*sizeof(BRet))) - 1
1456 else:
1457 min = -(1 << (8*sizeof(BRet)-1))
1458 max = (1 << (8*sizeof(BRet)-1)) - 1
1459 assert f(min) == min + 1
1460 assert f(max - 1) == max
1461 assert f(max) == 42
1462
1463 def test_a_lot_of_callbacks():
1464 BIGNUM = 10000
1465 if 'PY_DOT_PY' in globals(): BIGNUM = 100 # tests on py.py
1466 #
1467 BInt = new_primitive_type("int")
1468 BFunc = new_function_type((BInt,), BInt, False)
1469 def make_callback(m):
1470 def cb(n):
1471 return n + m
1472 return callback(BFunc, cb, 42) # 'cb' goes out of scope
1473 #
1474 flist = [make_callback(i) for i in range(BIGNUM)]
1475 for i, f in enumerate(flist):
1476 assert f(-142) == -142 + i
1477
1478 def test_callback_receiving_tiny_struct():
1479 BSChar = new_primitive_type("signed char")
1480 BInt = new_primitive_type("int")
1481 BStruct = new_struct_type("struct foo")
1482 BStructPtr = new_pointer_type(BStruct)
1483 complete_struct_or_union(BStruct, [('a', BSChar, -1),
1484 ('b', BSChar, -1)])
1485 def cb(s):
1486 return s.a + 10 * s.b
1487 BFunc = new_function_type((BStruct,), BInt)
1488 f = callback(BFunc, cb)
1489 p = newp(BStructPtr, [-2, -4])
1490 n = f(p[0])
1491 assert n == -42
1492
1493 def test_callback_returning_tiny_struct():
1494 BSChar = new_primitive_type("signed char")
1495 BInt = new_primitive_type("int")
1496 BStruct = new_struct_type("struct foo")
1497 BStructPtr = new_pointer_type(BStruct)
1498 complete_struct_or_union(BStruct, [('a', BSChar, -1),
1499 ('b', BSChar, -1)])
1500 def cb(n):
1501 return newp(BStructPtr, [-n, -3*n])[0]
1502 BFunc = new_function_type((BInt,), BStruct)
1503 f = callback(BFunc, cb)
1504 s = f(10)
1505 assert typeof(s) is BStruct
1506 assert repr(s) == "<cdata 'struct foo' owning 2 bytes>"
1507 assert s.a == -10
1508 assert s.b == -30
1509
1510 def test_callback_receiving_struct():
1511 BSChar = new_primitive_type("signed char")
1512 BInt = new_primitive_type("int")
1513 BDouble = new_primitive_type("double")
1514 BStruct = new_struct_type("struct foo")
1515 BStructPtr = new_pointer_type(BStruct)
1516 complete_struct_or_union(BStruct, [('a', BSChar, -1),
1517 ('b', BDouble, -1)])
1518 def cb(s):
1519 return s.a + int(s.b)
1520 BFunc = new_function_type((BStruct,), BInt)
1521 f = callback(BFunc, cb)
1522 p = newp(BStructPtr, [-2, 44.444])
1523 n = f(p[0])
1524 assert n == 42
1525
1526 def test_callback_returning_struct():
1527 BSChar = new_primitive_type("signed char")
1528 BInt = new_primitive_type("int")
1529 BDouble = new_primitive_type("double")
1530 BStruct = new_struct_type("struct foo")
1531 BStructPtr = new_pointer_type(BStruct)
1532 complete_struct_or_union(BStruct, [('a', BSChar, -1),
1533 ('b', BDouble, -1)])
1534 def cb(n):
1535 return newp(BStructPtr, [-n, 1E-42])[0]
1536 BFunc = new_function_type((BInt,), BStruct)
1537 f = callback(BFunc, cb)
1538 s = f(10)
1539 assert typeof(s) is BStruct
1540 assert repr(s) in ["<cdata 'struct foo' owning 12 bytes>",
1541 "<cdata 'struct foo' owning 16 bytes>"]
1542 assert s.a == -10
1543 assert s.b == 1E-42
1544
1545 def test_callback_receiving_big_struct():
1546 BInt = new_primitive_type("int")
1547 BStruct = new_struct_type("struct foo")
1548 BStructPtr = new_pointer_type(BStruct)
1549 complete_struct_or_union(BStruct, [('a', BInt, -1),
1550 ('b', BInt, -1),
1551 ('c', BInt, -1),
1552 ('d', BInt, -1),
1553 ('e', BInt, -1),
1554 ('f', BInt, -1),
1555 ('g', BInt, -1),
1556 ('h', BInt, -1),
1557 ('i', BInt, -1),
1558 ('j', BInt, -1)])
1559 def cb(s):
1560 for i, name in enumerate("abcdefghij"):
1561 assert getattr(s, name) == 13 - i
1562 return 42
1563 BFunc = new_function_type((BStruct,), BInt)
1564 f = callback(BFunc, cb)
1565 p = newp(BStructPtr, list(range(13, 3, -1)))
1566 n = f(p[0])
1567 assert n == 42
1568
1569 def test_callback_returning_big_struct():
1570 BInt = new_primitive_type("int")
1571 BStruct = new_struct_type("struct foo")
1572 BStructPtr = new_pointer_type(BStruct)
1573 complete_struct_or_union(BStruct, [('a', BInt, -1),
1574 ('b', BInt, -1),
1575 ('c', BInt, -1),
1576 ('d', BInt, -1),
1577 ('e', BInt, -1),
1578 ('f', BInt, -1),
1579 ('g', BInt, -1),
1580 ('h', BInt, -1),
1581 ('i', BInt, -1),
1582 ('j', BInt, -1)])
1583 def cb():
1584 return newp(BStructPtr, list(range(13, 3, -1)))[0]
1585 BFunc = new_function_type((), BStruct)
1586 f = callback(BFunc, cb)
1587 s = f()
1588 assert typeof(s) is BStruct
1589 assert repr(s) in ["<cdata 'struct foo' owning 40 bytes>",
1590 "<cdata 'struct foo' owning 80 bytes>"]
1591 for i, name in enumerate("abcdefghij"):
1592 assert getattr(s, name) == 13 - i
1593
1594 def test_callback_returning_void():
1595 BVoid = new_void_type()
1596 BFunc = new_function_type((), BVoid, False)
1597 def cb():
1598 seen.append(42)
1599 f = callback(BFunc, cb)
1600 seen = []
1601 f()
1602 assert seen == [42]
1603 pytest.raises(TypeError, callback, BFunc, cb, -42)
1604
1605 def test_enum_type():
1606 BUInt = new_primitive_type("unsigned int")
1607 BEnum = new_enum_type("foo", (), (), BUInt)
1608 assert repr(BEnum) == "<ctype 'foo'>"
1609 assert BEnum.kind == "enum"
1610 assert BEnum.cname == "foo"
1611 assert BEnum.elements == {}
1612 #
1613 BInt = new_primitive_type("int")
1614 BEnum = new_enum_type("enum foo", ('def', 'c', 'ab'), (0, 1, -20), BInt)
1615 assert BEnum.kind == "enum"
1616 assert BEnum.cname == "enum foo"
1617 assert BEnum.elements == {-20: 'ab', 0: 'def', 1: 'c'}
1618 # 'elements' is not the real dict, but merely a copy
1619 BEnum.elements[2] = '??'
1620 assert BEnum.elements == {-20: 'ab', 0: 'def', 1: 'c'}
1621 #
1622 BEnum = new_enum_type("enum bar", ('ab', 'cd'), (5, 5), BUInt)
1623 assert BEnum.elements == {5: 'ab'}
1624 assert BEnum.relements == {'ab': 5, 'cd': 5}
1625
1626 def test_cast_to_enum():
1627 BInt = new_primitive_type("int")
1628 BEnum = new_enum_type("enum foo", ('def', 'c', 'ab'), (0, 1, -20), BInt)
1629 assert sizeof(BEnum) == sizeof(BInt)
1630 e = cast(BEnum, 0)
1631 assert repr(e) == "<cdata 'enum foo' 0: def>"
1632 assert repr(cast(BEnum, -42)) == "<cdata 'enum foo' -42>"
1633 assert repr(cast(BEnum, -20)) == "<cdata 'enum foo' -20: ab>"
1634 assert string(e) == 'def'
1635 assert string(cast(BEnum, -20)) == 'ab'
1636 assert int(cast(BEnum, 1)) == 1
1637 assert int(cast(BEnum, 0)) == 0
1638 assert int(cast(BEnum, -242 + 2**128)) == -242
1639 assert string(cast(BEnum, -242 + 2**128)) == '-242'
1640 #
1641 BUInt = new_primitive_type("unsigned int")
1642 BEnum = new_enum_type("enum bar", ('def', 'c', 'ab'), (0, 1, 20), BUInt)
1643 e = cast(BEnum, -1)
1644 assert repr(e) == "<cdata 'enum bar' 4294967295>" # unsigned int
1645 #
1646 BLong = new_primitive_type("long")
1647 BEnum = new_enum_type("enum baz", (), (), BLong)
1648 assert sizeof(BEnum) == sizeof(BLong)
1649 e = cast(BEnum, -1)
1650 assert repr(e) == "<cdata 'enum baz' -1>"
1651
1652 def test_enum_with_non_injective_mapping():
1653 BInt = new_primitive_type("int")
1654 BEnum = new_enum_type("enum foo", ('ab', 'cd'), (7, 7), BInt)
1655 e = cast(BEnum, 7)
1656 assert repr(e) == "<cdata 'enum foo' 7: ab>"
1657 assert string(e) == 'ab'
1658
1659 def test_enum_in_struct():
1660 BInt = new_primitive_type("int")
1661 BEnum = new_enum_type("enum foo", ('def', 'c', 'ab'), (0, 1, -20), BInt)
1662 BStruct = new_struct_type("struct bar")
1663 BStructPtr = new_pointer_type(BStruct)
1664 complete_struct_or_union(BStruct, [('a1', BEnum, -1)])
1665 p = newp(BStructPtr, [-20])
1666 assert p.a1 == -20
1667 p = newp(BStructPtr, [12])
1668 assert p.a1 == 12
1669 e = pytest.raises(TypeError, newp, BStructPtr, [None])
1670 msg = str(e.value)
1671 assert ("an integer is required" in msg or # CPython
1672 "unsupported operand type for int(): 'NoneType'" in msg or # old PyPys
1673 "expected integer, got NoneType object" in msg) # newer PyPys
1674 with pytest.raises(TypeError):
1675 p.a1 = "def"
1676 if sys.version_info < (3,):
1677 BEnum2 = new_enum_type(unicode("foo"), (unicode('abc'),), (5,), BInt)
1678 assert string(cast(BEnum2, 5)) == 'abc'
1679 assert type(string(cast(BEnum2, 5))) is str
1680
1681 def test_enum_overflow():
1682 max_uint = 2 ** (size_of_int()*8) - 1
1683 max_int = max_uint // 2
1684 max_ulong = 2 ** (size_of_long()*8) - 1
1685 max_long = max_ulong // 2
1686 for BPrimitive in [new_primitive_type("int"),
1687 new_primitive_type("unsigned int"),
1688 new_primitive_type("long"),
1689 new_primitive_type("unsigned long")]:
1690 for x in [max_uint, max_int, max_ulong, max_long]:
1691 for testcase in [x, x+1, -x-1, -x-2]:
1692 if int(cast(BPrimitive, testcase)) == testcase:
1693 # fits
1694 BEnum = new_enum_type("foo", ("AA",), (testcase,),
1695 BPrimitive)
1696 assert int(cast(BEnum, testcase)) == testcase
1697 else:
1698 # overflows
1699 pytest.raises(OverflowError, new_enum_type,
1700 "foo", ("AA",), (testcase,), BPrimitive)
1701
1702 def test_callback_returning_enum():
1703 BInt = new_primitive_type("int")
1704 BEnum = new_enum_type("foo", ('def', 'c', 'ab'), (0, 1, -20), BInt)
1705 def cb(n):
1706 if n & 1:
1707 return cast(BEnum, n)
1708 else:
1709 return n
1710 BFunc = new_function_type((BInt,), BEnum)
1711 f = callback(BFunc, cb)
1712 assert f(0) == 0
1713 assert f(1) == 1
1714 assert f(-20) == -20
1715 assert f(20) == 20
1716 assert f(21) == 21
1717
1718 def test_callback_returning_enum_unsigned():
1719 BInt = new_primitive_type("int")
1720 BUInt = new_primitive_type("unsigned int")
1721 BEnum = new_enum_type("foo", ('def', 'c', 'ab'), (0, 1, 20), BUInt)
1722 def cb(n):
1723 if n & 1:
1724 return cast(BEnum, n)
1725 else:
1726 return n
1727 BFunc = new_function_type((BInt,), BEnum)
1728 f = callback(BFunc, cb)
1729 assert f(0) == 0
1730 assert f(1) == 1
1731 assert f(-21) == 2**32 - 21
1732 assert f(20) == 20
1733 assert f(21) == 21
1734
1735 def test_callback_returning_char():
1736 BInt = new_primitive_type("int")
1737 BChar = new_primitive_type("char")
1738 def cb(n):
1739 return bytechr(n)
1740 BFunc = new_function_type((BInt,), BChar)
1741 f = callback(BFunc, cb)
1742 assert f(0) == b'\x00'
1743 assert f(255) == b'\xFF'
1744
1745 def _hacked_pypy_uni4():
1746 pyuni4 = {1: True, 2: False}[len(u+'\U00012345')]
1747 return 'PY_DOT_PY' in globals() and not pyuni4
1748
1749 def test_callback_returning_wchar_t():
1750 BInt = new_primitive_type("int")
1751 BWChar = new_primitive_type("wchar_t")
1752 def cb(n):
1753 if n == -1:
1754 return u+'\U00012345'
1755 if n == -2:
1756 raise ValueError
1757 return unichr(n)
1758 BFunc = new_function_type((BInt,), BWChar)
1759 f = callback(BFunc, cb)
1760 assert f(0) == unichr(0)
1761 assert f(255) == unichr(255)
1762 assert f(0x1234) == u+'\u1234'
1763 if sizeof(BWChar) == 4 and not _hacked_pypy_uni4():
1764 assert f(-1) == u+'\U00012345'
1765 assert f(-2) == u+'\x00' # and an exception printed to stderr
1766
1767 def test_struct_with_bitfields():
1768 BLong = new_primitive_type("long")
1769 BStruct = new_struct_type("struct foo")
1770 LONGBITS = 8 * sizeof(BLong)
1771 complete_struct_or_union(BStruct, [('a1', BLong, 1),
1772 ('a2', BLong, 2),
1773 ('a3', BLong, 3),
1774 ('a4', BLong, LONGBITS - 5)])
1775 d = BStruct.fields
1776 assert d[0][1].offset == d[1][1].offset == d[2][1].offset == 0
1777 assert d[3][1].offset == sizeof(BLong)
1778 def f(m, r):
1779 if sys.byteorder == 'little':
1780 return r
1781 else:
1782 return LONGBITS - m - r
1783 assert d[0][1].bitshift == f(1, 0)
1784 assert d[0][1].bitsize == 1
1785 assert d[1][1].bitshift == f(2, 1)
1786 assert d[1][1].bitsize == 2
1787 assert d[2][1].bitshift == f(3, 3)
1788 assert d[2][1].bitsize == 3
1789 assert d[3][1].bitshift == f(LONGBITS - 5, 0)
1790 assert d[3][1].bitsize == LONGBITS - 5
1791 assert sizeof(BStruct) == 2 * sizeof(BLong)
1792 assert alignof(BStruct) == alignof(BLong)
1793
1794 def test_bitfield_instance():
1795 BInt = new_primitive_type("int")
1796 BUnsignedInt = new_primitive_type("unsigned int")
1797 BStruct = new_struct_type("struct foo")
1798 complete_struct_or_union(BStruct, [('a1', BInt, 1),
1799 ('a2', BUnsignedInt, 2),
1800 ('a3', BInt, 3)])
1801 p = newp(new_pointer_type(BStruct), None)
1802 p.a1 = -1
1803 assert p.a1 == -1
1804 p.a1 = 0
1805 with pytest.raises(OverflowError):
1806 p.a1 = 2
1807 assert p.a1 == 0
1808 #
1809 p.a1 = -1
1810 p.a2 = 3
1811 p.a3 = -4
1812 with pytest.raises(OverflowError):
1813 p.a3 = 4
1814 with pytest.raises(OverflowError) as e:
1815 p.a3 = -5
1816 assert str(e.value) == ("value -5 outside the range allowed by the "
1817 "bit field width: -4 <= x <= 3")
1818 assert p.a1 == -1 and p.a2 == 3 and p.a3 == -4
1819 #
1820 # special case for convenience: "int x:1", while normally signed,
1821 # allows also setting the value "1" (it still gets read back as -1)
1822 p.a1 = 1
1823 assert p.a1 == -1
1824 with pytest.raises(OverflowError) as e:
1825 p.a1 = -2
1826 assert str(e.value) == ("value -2 outside the range allowed by the "
1827 "bit field width: -1 <= x <= 1")
1828
1829 def test_bitfield_instance_init():
1830 BInt = new_primitive_type("int")
1831 BStruct = new_struct_type("struct foo")
1832 complete_struct_or_union(BStruct, [('a1', BInt, 1)])
1833 p = newp(new_pointer_type(BStruct), [-1])
1834 assert p.a1 == -1
1835 p = newp(new_pointer_type(BStruct), {'a1': -1})
1836 assert p.a1 == -1
1837 #
1838 BUnion = new_union_type("union bar")
1839 complete_struct_or_union(BUnion, [('a1', BInt, 1)])
1840 p = newp(new_pointer_type(BUnion), [-1])
1841 assert p.a1 == -1
1842
1843 def test_weakref():
1844 import _weakref
1845 BInt = new_primitive_type("int")
1846 BPtr = new_pointer_type(BInt)
1847 rlist = [_weakref.ref(BInt),
1848 _weakref.ref(newp(BPtr, 42)),
1849 _weakref.ref(cast(BPtr, 42)),
1850 _weakref.ref(cast(BInt, 42)),
1851 _weakref.ref(buffer(newp(BPtr, 42))),
1852 ]
1853 for i in range(5):
1854 import gc; gc.collect()
1855 if [r() for r in rlist] == [None for r in rlist]:
1856 break
1857
1858 def test_no_inheritance():
1859 BInt = new_primitive_type("int")
1860 try:
1861 class foo(type(BInt)): pass
1862 except TypeError:
1863 pass
1864 else:
1865 raise AssertionError
1866 x = cast(BInt, 42)
1867 try:
1868 class foo(type(x)): pass
1869 except TypeError:
1870 pass
1871 else:
1872 raise AssertionError
1873
1874 def test_assign_string():
1875 BChar = new_primitive_type("char")
1876 BArray1 = new_array_type(new_pointer_type(BChar), 5)
1877 BArray2 = new_array_type(new_pointer_type(BArray1), 5)
1878 a = newp(BArray2, [b"abc", b"de", b"ghij"])
1879 assert string(a[1]) == b"de"
1880 assert string(a[2]) == b"ghij"
1881 a[2] = b"."
1882 assert string(a[2]) == b"."
1883 a[2] = b"12345"
1884 assert string(a[2]) == b"12345"
1885 with pytest.raises(IndexError) as e:
1886 a[2] = b"123456"
1887 assert 'char[5]' in str(e.value)
1888 assert 'got 6 characters' in str(e.value)
1889
1890 def test_add_error():
1891 x = cast(new_primitive_type("int"), 42)
1892 with pytest.raises(TypeError):
1893 x + 1
1894 with pytest.raises(TypeError):
1895 x - 1
1896
1897 def test_void_errors():
1898 pytest.raises(ValueError, alignof, new_void_type())
1899 pytest.raises(TypeError, newp, new_pointer_type(new_void_type()), None)
1900
1901 def test_too_many_items():
1902 BChar = new_primitive_type("char")
1903 BArray = new_array_type(new_pointer_type(BChar), 5)
1904 pytest.raises(IndexError, newp, BArray, tuple(b'123456'))
1905 pytest.raises(IndexError, newp, BArray, list(b'123456'))
1906 pytest.raises(IndexError, newp, BArray, b'123456')
1907 BStruct = new_struct_type("struct foo")
1908 complete_struct_or_union(BStruct, [])
1909 pytest.raises(TypeError, newp, new_pointer_type(BStruct), b'')
1910 pytest.raises(ValueError, newp, new_pointer_type(BStruct), [b'1'])
1911
1912 def test_more_type_errors():
1913 BInt = new_primitive_type("int")
1914 BChar = new_primitive_type("char")
1915 BArray = new_array_type(new_pointer_type(BChar), 5)
1916 pytest.raises(TypeError, newp, BArray, 12.34)
1917 BArray = new_array_type(new_pointer_type(BInt), 5)
1918 pytest.raises(TypeError, newp, BArray, 12.34)
1919 BFloat = new_primitive_type("float")
1920 pytest.raises(TypeError, cast, BFloat, newp(BArray, None))
1921
1922 def test_more_overflow_errors():
1923 BUInt = new_primitive_type("unsigned int")
1924 pytest.raises(OverflowError, newp, new_pointer_type(BUInt), -1)
1925 pytest.raises(OverflowError, newp, new_pointer_type(BUInt), 2**32)
1926
1927 def test_newp_copying():
1928 """Test that we can do newp(<type>, <cdata of the given type>) for most
1929 types, including same-type arrays.
1930 """
1931 BInt = new_primitive_type("int")
1932 p = newp(new_pointer_type(BInt), cast(BInt, 42))
1933 assert p[0] == 42
1934 #
1935 BUInt = new_primitive_type("unsigned int")
1936 p = newp(new_pointer_type(BUInt), cast(BUInt, 42))
1937 assert p[0] == 42
1938 #
1939 BChar = new_primitive_type("char")
1940 p = newp(new_pointer_type(BChar), cast(BChar, '!'))
1941 assert p[0] == b'!'
1942 #
1943 BFloat = new_primitive_type("float")
1944 p = newp(new_pointer_type(BFloat), cast(BFloat, 12.25))
1945 assert p[0] == 12.25
1946 #
1947 BStruct = new_struct_type("struct foo_s")
1948 BStructPtr = new_pointer_type(BStruct)
1949 complete_struct_or_union(BStruct, [('a1', BInt, -1)])
1950 s1 = newp(BStructPtr, [42])
1951 p1 = newp(new_pointer_type(BStructPtr), s1)
1952 assert p1[0] == s1
1953 #
1954 BArray = new_array_type(new_pointer_type(BInt), None)
1955 a1 = newp(BArray, [1, 2, 3, 4])
1956 pytest.raises(TypeError, newp, BArray, a1)
1957 BArray6 = new_array_type(new_pointer_type(BInt), 6)
1958 a1 = newp(BArray6, [10, 20, 30])
1959 a2 = newp(BArray6, a1)
1960 assert list(a2) == [10, 20, 30, 0, 0, 0]
1961 #
1962 s1 = newp(BStructPtr, [42])
1963 s2 = newp(BStructPtr, s1[0])
1964 assert s2.a1 == 42
1965 #
1966 BUnion = new_union_type("union foo_u")
1967 BUnionPtr = new_pointer_type(BUnion)
1968 complete_struct_or_union(BUnion, [('a1', BInt, -1)])
1969 u1 = newp(BUnionPtr, [42])
1970 u2 = newp(BUnionPtr, u1[0])
1971 assert u2.a1 == 42
1972 #
1973 BFunc = new_function_type((BInt,), BUInt)
1974 p1 = cast(BFunc, 42)
1975 p2 = newp(new_pointer_type(BFunc), p1)
1976 assert p2[0] == p1
1977
1978 def test_string():
1979 BChar = new_primitive_type("char")
1980 assert string(cast(BChar, 42)) == b'*'
1981 assert string(cast(BChar, 0)) == b'\x00'
1982 BCharP = new_pointer_type(BChar)
1983 BArray = new_array_type(BCharP, 10)
1984 a = newp(BArray, b"hello")
1985 assert len(a) == 10
1986 assert string(a) == b"hello"
1987 p = a + 2
1988 assert string(p) == b"llo"
1989 assert string(newp(new_array_type(BCharP, 4), b"abcd")) == b"abcd"
1990 pytest.raises(RuntimeError, string, cast(BCharP, 0))
1991 assert string(a, 4) == b"hell"
1992 assert string(a, 5) == b"hello"
1993 assert string(a, 6) == b"hello"
1994
1995 def test_string_byte():
1996 BByte = new_primitive_type("signed char")
1997 assert string(cast(BByte, 42)) == b'*'
1998 assert string(cast(BByte, 0)) == b'\x00'
1999 BArray = new_array_type(new_pointer_type(BByte), None)
2000 a = newp(BArray, [65, 66, 67])
2001 assert type(string(a)) is bytes and string(a) == b'ABC'
2002 #
2003 BByte = new_primitive_type("unsigned char")
2004 assert string(cast(BByte, 42)) == b'*'
2005 assert string(cast(BByte, 0)) == b'\x00'
2006 BArray = new_array_type(new_pointer_type(BByte), None)
2007 a = newp(BArray, [65, 66, 67])
2008 assert type(string(a)) is bytes and string(a) == b'ABC'
2009 if 'PY_DOT_PY' not in globals() and sys.version_info < (3,):
2010 assert string(a, 8).startswith(b'ABC') # may contain additional garbage
2011
2012 def test_string_wchar():
2013 for typename in ["wchar_t", "char16_t", "char32_t"]:
2014 _test_string_wchar_variant(typename)
2015
2016 def _test_string_wchar_variant(typename):
2017 BWChar = new_primitive_type(typename)
2018 assert string(cast(BWChar, 42)) == u+'*'
2019 assert string(cast(BWChar, 0x4253)) == u+'\u4253'
2020 assert string(cast(BWChar, 0)) == u+'\x00'
2021 BArray = new_array_type(new_pointer_type(BWChar), None)
2022 a = newp(BArray, [u+'A', u+'B', u+'C'])
2023 assert type(string(a)) is unicode and string(a) == u+'ABC'
2024 if 'PY_DOT_PY' not in globals() and sys.version_info < (3,):
2025 try:
2026 # may contain additional garbage
2027 assert string(a, 8).startswith(u+'ABC')
2028 except ValueError: # garbage contains values > 0x10FFFF
2029 assert sizeof(BWChar) == 4
2030
2031 def test_string_typeerror():
2032 BShort = new_primitive_type("short")
2033 BArray = new_array_type(new_pointer_type(BShort), None)
2034 a = newp(BArray, [65, 66, 67])
2035 pytest.raises(TypeError, string, a)
2036
2037 def test_bug_convert_to_ptr():
2038 BChar = new_primitive_type("char")
2039 BCharP = new_pointer_type(BChar)
2040 BDouble = new_primitive_type("double")
2041 x = cast(BDouble, 42)
2042 pytest.raises(TypeError, newp, new_pointer_type(BCharP), x)
2043
2044 def test_set_struct_fields():
2045 BChar = new_primitive_type("char")
2046 BCharP = new_pointer_type(BChar)
2047 BCharArray10 = new_array_type(BCharP, 10)
2048 BStruct = new_struct_type("struct foo")
2049 BStructPtr = new_pointer_type(BStruct)
2050 complete_struct_or_union(BStruct, [('a1', BCharArray10, -1)])
2051 p = newp(BStructPtr, None)
2052 assert string(p.a1) == b''
2053 p.a1 = b'foo'
2054 assert string(p.a1) == b'foo'
2055 assert list(p.a1) == [b'f', b'o', b'o'] + [b'\x00'] * 7
2056 p.a1 = [b'x', b'y']
2057 assert string(p.a1) == b'xyo'
2058
2059 def test_invalid_function_result_types():
2060 BFunc = new_function_type((), new_void_type())
2061 BArray = new_array_type(new_pointer_type(BFunc), 5) # works
2062 new_function_type((), BFunc) # works
2063 new_function_type((), new_primitive_type("int"))
2064 new_function_type((), new_pointer_type(BFunc))
2065 BUnion = new_union_type("union foo_u")
2066 complete_struct_or_union(BUnion, [])
2067 BFunc = new_function_type((), BUnion)
2068 pytest.raises(NotImplementedError, cast(BFunc, 123))
2069 pytest.raises(TypeError, new_function_type, (), BArray)
2070
2071 def test_struct_return_in_func():
2072 BChar = new_primitive_type("char")
2073 BShort = new_primitive_type("short")
2074 BFloat = new_primitive_type("float")
2075 BDouble = new_primitive_type("double")
2076 BInt = new_primitive_type("int")
2077 BStruct = new_struct_type("struct foo_s")
2078 complete_struct_or_union(BStruct, [('a1', BChar, -1),
2079 ('a2', BShort, -1)])
2080 BFunc10 = new_function_type((BInt,), BStruct)
2081 f = cast(BFunc10, _testfunc(10))
2082 s = f(40)
2083 assert repr(s) == "<cdata 'struct foo_s' owning 4 bytes>"
2084 assert s.a1 == bytechr(40)
2085 assert s.a2 == 40 * 40
2086 #
2087 BStruct11 = new_struct_type("struct test11")
2088 complete_struct_or_union(BStruct11, [('a1', BInt, -1),
2089 ('a2', BInt, -1)])
2090 BFunc11 = new_function_type((BInt,), BStruct11)
2091 f = cast(BFunc11, _testfunc(11))
2092 s = f(40)
2093 assert repr(s) == "<cdata 'struct test11' owning 8 bytes>"
2094 assert s.a1 == 40
2095 assert s.a2 == 40 * 40
2096 #
2097 BStruct12 = new_struct_type("struct test12")
2098 complete_struct_or_union(BStruct12, [('a1', BDouble, -1),
2099 ])
2100 BFunc12 = new_function_type((BInt,), BStruct12)
2101 f = cast(BFunc12, _testfunc(12))
2102 s = f(40)
2103 assert repr(s) == "<cdata 'struct test12' owning 8 bytes>"
2104 assert s.a1 == 40.0
2105 #
2106 BStruct13 = new_struct_type("struct test13")
2107 complete_struct_or_union(BStruct13, [('a1', BInt, -1),
2108 ('a2', BInt, -1),
2109 ('a3', BInt, -1)])
2110 BFunc13 = new_function_type((BInt,), BStruct13)
2111 f = cast(BFunc13, _testfunc(13))
2112 s = f(40)
2113 assert repr(s) == "<cdata 'struct test13' owning 12 bytes>"
2114 assert s.a1 == 40
2115 assert s.a2 == 40 * 40
2116 assert s.a3 == 40 * 40 * 40
2117 #
2118 BStruct14 = new_struct_type("struct test14")
2119 complete_struct_or_union(BStruct14, [('a1', BFloat, -1),
2120 ])
2121 BFunc14 = new_function_type((BInt,), BStruct14)
2122 f = cast(BFunc14, _testfunc(14))
2123 s = f(40)
2124 assert repr(s) == "<cdata 'struct test14' owning 4 bytes>"
2125 assert s.a1 == 40.0
2126 #
2127 BStruct15 = new_struct_type("struct test15")
2128 complete_struct_or_union(BStruct15, [('a1', BFloat, -1),
2129 ('a2', BInt, -1)])
2130 BFunc15 = new_function_type((BInt,), BStruct15)
2131 f = cast(BFunc15, _testfunc(15))
2132 s = f(40)
2133 assert repr(s) == "<cdata 'struct test15' owning 8 bytes>"
2134 assert s.a1 == 40.0
2135 assert s.a2 == 40 * 40
2136 #
2137 BStruct16 = new_struct_type("struct test16")
2138 complete_struct_or_union(BStruct16, [('a1', BFloat, -1),
2139 ('a2', BFloat, -1)])
2140 BFunc16 = new_function_type((BInt,), BStruct16)
2141 f = cast(BFunc16, _testfunc(16))
2142 s = f(40)
2143 assert repr(s) == "<cdata 'struct test16' owning 8 bytes>"
2144 assert s.a1 == 40.0
2145 assert s.a2 == -40.0
2146 #
2147 BStruct17 = new_struct_type("struct test17")
2148 complete_struct_or_union(BStruct17, [('a1', BInt, -1),
2149 ('a2', BFloat, -1)])
2150 BFunc17 = new_function_type((BInt,), BStruct17)
2151 f = cast(BFunc17, _testfunc(17))
2152 s = f(40)
2153 assert repr(s) == "<cdata 'struct test17' owning 8 bytes>"
2154 assert s.a1 == 40
2155 assert s.a2 == 40.0 * 40.0
2156 #
2157 BStruct17Ptr = new_pointer_type(BStruct17)
2158 BFunc18 = new_function_type((BStruct17Ptr,), BInt)
2159 f = cast(BFunc18, _testfunc(18))
2160 x = f([[40, 2.5]])
2161 assert x == 42
2162 x = f([{'a2': 43.1}])
2163 assert x == 43
2164
2165 def test_cast_with_functionptr():
2166 BFunc = new_function_type((), new_void_type())
2167 BFunc2 = new_function_type((), new_primitive_type("short"))
2168 BCharP = new_pointer_type(new_primitive_type("char"))
2169 BIntP = new_pointer_type(new_primitive_type("int"))
2170 BStruct = new_struct_type("struct foo")
2171 BStructPtr = new_pointer_type(BStruct)
2172 complete_struct_or_union(BStruct, [('a1', BFunc, -1)])
2173 newp(BStructPtr, [cast(BFunc, 0)])
2174 newp(BStructPtr, [cast(BCharP, 0)])
2175 pytest.raises(TypeError, newp, BStructPtr, [cast(BIntP, 0)])
2176 pytest.raises(TypeError, newp, BStructPtr, [cast(BFunc2, 0)])
2177
2178 def test_wchar():
2179 _test_wchar_variant("wchar_t")
2180 if sys.platform.startswith("linux"):
2181 BWChar = new_primitive_type("wchar_t")
2182 assert sizeof(BWChar) == 4
2183 # wchar_t is often signed on Linux, but not always (e.g. on ARM)
2184 assert int(cast(BWChar, -1)) in (-1, 4294967295)
2185
2186 def test_char16():
2187 BChar16 = new_primitive_type("char16_t")
2188 assert sizeof(BChar16) == 2
2189 _test_wchar_variant("char16_t")
2190 assert int(cast(BChar16, -1)) == 0xffff # always unsigned
2191
2192 def test_char32():
2193 BChar32 = new_primitive_type("char32_t")
2194 assert sizeof(BChar32) == 4
2195 _test_wchar_variant("char32_t")
2196 assert int(cast(BChar32, -1)) == 0xffffffff # always unsigned
2197
2198 def _test_wchar_variant(typename):
2199 BWChar = new_primitive_type(typename)
2200 BInt = new_primitive_type("int")
2201 pyuni4 = {1: True, 2: False}[len(u+'\U00012345')]
2202 wchar4 = {2: False, 4: True}[sizeof(BWChar)]
2203 assert str(cast(BWChar, 0x45)) == "<cdata '%s' %s'E'>" % (
2204 typename, mandatory_u_prefix)
2205 assert str(cast(BWChar, 0x1234)) == "<cdata '%s' %s'\u1234'>" % (
2206 typename, mandatory_u_prefix)
2207 if not _hacked_pypy_uni4():
2208 if wchar4:
2209 x = cast(BWChar, 0x12345)
2210 assert str(x) == "<cdata '%s' %s'\U00012345'>" % (
2211 typename, mandatory_u_prefix)
2212 assert int(x) == 0x12345
2213 else:
2214 x = cast(BWChar, 0x18345)
2215 assert str(x) == "<cdata '%s' %s'\u8345'>" % (
2216 typename, mandatory_u_prefix)
2217 assert int(x) == 0x8345
2218 #
2219 BWCharP = new_pointer_type(BWChar)
2220 BStruct = new_struct_type("struct foo_s")
2221 BStructPtr = new_pointer_type(BStruct)
2222 complete_struct_or_union(BStruct, [('a1', BWChar, -1),
2223 ('a2', BWCharP, -1)])
2224 s = newp(BStructPtr)
2225 s.a1 = u+'\x00'
2226 assert s.a1 == u+'\x00'
2227 with pytest.raises(TypeError):
2228 s.a1 = b'a'
2229 with pytest.raises(TypeError):
2230 s.a1 = bytechr(0xFF)
2231 s.a1 = u+'\u1234'
2232 assert s.a1 == u+'\u1234'
2233 if pyuni4:
2234 if wchar4:
2235 s.a1 = u+'\U00012345'
2236 assert s.a1 == u+'\U00012345'
2237 elif wchar4:
2238 if not _hacked_pypy_uni4():
2239 s.a1 = cast(BWChar, 0x12345)
2240 assert s.a1 == u+'\ud808\udf45'
2241 s.a1 = u+'\ud807\udf44'
2242 assert s.a1 == u+'\U00011f44'
2243 else:
2244 with pytest.raises(TypeError):
2245 s.a1 = u+'\U00012345'
2246 #
2247 BWCharArray = new_array_type(BWCharP, None)
2248 a = newp(BWCharArray, u+'hello \u1234 world')
2249 assert len(a) == 14 # including the final null
2250 assert string(a) == u+'hello \u1234 world'
2251 a[13] = u+'!'
2252 assert string(a) == u+'hello \u1234 world!'
2253 assert str(a) == repr(a)
2254 assert a[6] == u+'\u1234'
2255 a[6] = u+'-'
2256 assert string(a) == u+'hello - world!'
2257 assert str(a) == repr(a)
2258 #
2259 if wchar4 and not _hacked_pypy_uni4():
2260 u1 = u+'\U00012345\U00012346\U00012347'
2261 a = newp(BWCharArray, u1)
2262 assert len(a) == 4
2263 assert string(a) == u1
2264 assert len(list(a)) == 4
2265 expected = [u+'\U00012345', u+'\U00012346', u+'\U00012347', unichr(0)]
2266 assert list(a) == expected
2267 got = [a[i] for i in range(4)]
2268 assert got == expected
2269 with pytest.raises(IndexError):
2270 a[4]
2271 #
2272 w = cast(BWChar, 'a')
2273 assert repr(w) == "<cdata '%s' %s'a'>" % (typename, mandatory_u_prefix)
2274 assert str(w) == repr(w)
2275 assert string(w) == u+'a'
2276 assert int(w) == ord('a')
2277 w = cast(BWChar, 0x1234)
2278 assert repr(w) == "<cdata '%s' %s'\u1234'>" % (typename, mandatory_u_prefix)
2279 assert str(w) == repr(w)
2280 assert string(w) == u+'\u1234'
2281 assert int(w) == 0x1234
2282 w = cast(BWChar, u+'\u8234')
2283 assert repr(w) == "<cdata '%s' %s'\u8234'>" % (typename, mandatory_u_prefix)
2284 assert str(w) == repr(w)
2285 assert string(w) == u+'\u8234'
2286 assert int(w) == 0x8234
2287 w = cast(BInt, u+'\u1234')
2288 assert repr(w) == "<cdata 'int' 4660>"
2289 if wchar4 and not _hacked_pypy_uni4():
2290 w = cast(BWChar, u+'\U00012345')
2291 assert repr(w) == "<cdata '%s' %s'\U00012345'>" % (
2292 typename, mandatory_u_prefix)
2293 assert str(w) == repr(w)
2294 assert string(w) == u+'\U00012345'
2295 assert int(w) == 0x12345
2296 w = cast(BInt, u+'\U00012345')
2297 assert repr(w) == "<cdata 'int' 74565>"
2298 pytest.raises(TypeError, cast, BInt, u+'')
2299 pytest.raises(TypeError, cast, BInt, u+'XX')
2300 assert int(cast(BInt, u+'a')) == ord('a')
2301 #
2302 a = newp(BWCharArray, u+'hello - world')
2303 p = cast(BWCharP, a)
2304 assert string(p) == u+'hello - world'
2305 p[6] = u+'\u2345'
2306 assert string(p) == u+'hello \u2345 world'
2307 #
2308 s = newp(BStructPtr, [u+'\u1234', p])
2309 assert s.a1 == u+'\u1234'
2310 assert s.a2 == p
2311 assert str(s.a2) == repr(s.a2)
2312 assert string(s.a2) == u+'hello \u2345 world'
2313 #
2314 q = cast(BWCharP, 0)
2315 assert str(q) == repr(q)
2316 pytest.raises(RuntimeError, string, q)
2317 #
2318 def cb(p):
2319 assert repr(p).startswith("<cdata '%s *' 0x" % typename)
2320 return len(string(p))
2321 BFunc = new_function_type((BWCharP,), BInt, False)
2322 f = callback(BFunc, cb, -42)
2323 assert f(u+'a\u1234b') == 3
2324 #
2325 if wchar4 and not pyuni4 and not _hacked_pypy_uni4():
2326 # try out-of-range wchar_t values
2327 x = cast(BWChar, 1114112)
2328 pytest.raises(ValueError, string, x)
2329 x = cast(BWChar, -1)
2330 pytest.raises(ValueError, string, x)
2331
2332 def test_wchar_variants_mix():
2333 BWChar = new_primitive_type("wchar_t")
2334 BChar16 = new_primitive_type("char16_t")
2335 BChar32 = new_primitive_type("char32_t")
2336 assert int(cast(BChar32, cast(BChar16, -2))) == 0xfffe
2337 assert int(cast(BWChar, cast(BChar16, -2))) == 0xfffe
2338 assert int(cast(BChar16, cast(BChar32, 0x0001f345))) == 0xf345
2339 assert int(cast(BChar16, cast(BWChar, 0x0001f345))) == 0xf345
2340 #
2341 BChar16A = new_array_type(new_pointer_type(BChar16), None)
2342 BChar32A = new_array_type(new_pointer_type(BChar32), None)
2343 x = cast(BChar32, 'A')
2344 pytest.raises(TypeError, newp, BChar16A, [x])
2345 x = cast(BChar16, 'A')
2346 pytest.raises(TypeError, newp, BChar32A, [x])
2347 #
2348 a = newp(BChar16A, u+'\U00012345')
2349 assert len(a) == 3
2350 a = newp(BChar32A, u+'\U00012345')
2351 assert len(a) == 2 # even if the Python unicode string above is 2 chars
2352
2353 def test_keepalive_struct():
2354 # exception to the no-keepalive rule: p=newp(BStructPtr) returns a
2355 # pointer owning the memory, and p[0] returns a pointer to the
2356 # struct that *also* owns the memory
2357 BStruct = new_struct_type("struct foo")
2358 BStructPtr = new_pointer_type(BStruct)
2359 complete_struct_or_union(BStruct, [('a1', new_primitive_type("int"), -1),
2360 ('a2', new_primitive_type("int"), -1),
2361 ('a3', new_primitive_type("int"), -1)])
2362 p = newp(BStructPtr)
2363 assert repr(p) == "<cdata 'struct foo *' owning 12 bytes>"
2364 q = p[0]
2365 assert repr(q) == "<cdata 'struct foo' owning 12 bytes>"
2366 q.a1 = 123456
2367 assert p.a1 == 123456
2368 r = cast(BStructPtr, p)
2369 assert repr(r[0]).startswith("<cdata 'struct foo &' 0x")
2370 del p
2371 import gc; gc.collect()
2372 assert q.a1 == 123456
2373 assert repr(q) == "<cdata 'struct foo' owning 12 bytes>"
2374 assert q.a1 == 123456
2375
2376 def test_nokeepalive_struct():
2377 BStruct = new_struct_type("struct foo")
2378 BStructPtr = new_pointer_type(BStruct)
2379 BStructPtrPtr = new_pointer_type(BStructPtr)
2380 complete_struct_or_union(BStruct, [('a1', new_primitive_type("int"), -1)])
2381 p = newp(BStructPtr)
2382 pp = newp(BStructPtrPtr)
2383 pp[0] = p
2384 s = pp[0][0]
2385 assert repr(s).startswith("<cdata 'struct foo &' 0x")
2386
2387 def test_owning_repr():
2388 BInt = new_primitive_type("int")
2389 BArray = new_array_type(new_pointer_type(BInt), None) # int[]
2390 p = newp(BArray, 7)
2391 assert repr(p) == "<cdata 'int[]' owning 28 bytes>"
2392 assert sizeof(p) == 28
2393 #
2394 BArray = new_array_type(new_pointer_type(BInt), 7) # int[7]
2395 p = newp(BArray, None)
2396 assert repr(p) == "<cdata 'int[7]' owning 28 bytes>"
2397 assert sizeof(p) == 28
2398
2399 def test_cannot_dereference_void():
2400 BVoidP = new_pointer_type(new_void_type())
2401 p = cast(BVoidP, 123456)
2402 with pytest.raises(TypeError):
2403 p[0]
2404 p = cast(BVoidP, 0)
2405 with pytest.raises((TypeError, RuntimeError)):
2406 p[0]
2407
2408 def test_iter():
2409 BInt = new_primitive_type("int")
2410 BIntP = new_pointer_type(BInt)
2411 BArray = new_array_type(BIntP, None) # int[]
2412 p = newp(BArray, 7)
2413 assert list(p) == list(iter(p)) == [0] * 7
2414 #
2415 pytest.raises(TypeError, iter, cast(BInt, 5))
2416 pytest.raises(TypeError, iter, cast(BIntP, 123456))
2417
2418 def test_cmp():
2419 BInt = new_primitive_type("int")
2420 BIntP = new_pointer_type(BInt)
2421 BVoidP = new_pointer_type(new_void_type())
2422 p = newp(BIntP, 123)
2423 q = cast(BInt, 124)
2424 assert (p == q) is False
2425 assert (p != q) is True
2426 assert (q == p) is False
2427 assert (q != p) is True
2428 if strict_compare:
2429 with pytest.raises(TypeError): p < q
2430 with pytest.raises(TypeError): p <= q
2431 with pytest.raises(TypeError): q < p
2432 with pytest.raises(TypeError): q <= p
2433 with pytest.raises(TypeError): p > q
2434 with pytest.raises(TypeError): p >= q
2435 r = cast(BVoidP, p)
2436 assert (p < r) is False
2437 assert (p <= r) is True
2438 assert (p == r) is True
2439 assert (p != r) is False
2440 assert (p > r) is False
2441 assert (p >= r) is True
2442 s = newp(BIntP, 125)
2443 assert (p == s) is False
2444 assert (p != s) is True
2445 assert (p < s) is (p <= s) is (s > p) is (s >= p)
2446 assert (p > s) is (p >= s) is (s < p) is (s <= p)
2447 assert (p < s) ^ (p > s)
2448
2449 def test_buffer():
2450 try:
2451 import __builtin__
2452 except ImportError:
2453 import builtins as __builtin__
2454 BShort = new_primitive_type("short")
2455 s = newp(new_pointer_type(BShort), 100)
2456 assert sizeof(s) == size_of_ptr()
2457 assert sizeof(BShort) == 2
2458 assert len(buffer(s)) == 2
2459 #
2460 BChar = new_primitive_type("char")
2461 BCharArray = new_array_type(new_pointer_type(BChar), None)
2462 c = newp(BCharArray, b"hi there")
2463 #
2464 buf = buffer(c)
2465 assert repr(buf).startswith('<_cffi_backend.buffer object at 0x')
2466 assert bytes(buf) == b"hi there\x00"
2467 assert type(buf) is buffer
2468 if sys.version_info < (3,):
2469 assert str(buf) == "hi there\x00"
2470 assert unicode(buf) == u+"hi there\x00"
2471 else:
2472 assert str(buf) == repr(buf)
2473 # --mb_length--
2474 assert len(buf) == len(b"hi there\x00")
2475 # --mb_item--
2476 for i in range(-12, 12):
2477 try:
2478 expected = b"hi there\x00"[i]
2479 except IndexError:
2480 with pytest.raises(IndexError):
2481 buf[i]
2482 else:
2483 assert buf[i] == bitem2bchr(expected)
2484 # --mb_slice--
2485 assert buf[:] == b"hi there\x00"
2486 for i in range(-12, 12):
2487 assert buf[i:] == b"hi there\x00"[i:]
2488 assert buf[:i] == b"hi there\x00"[:i]
2489 for j in range(-12, 12):
2490 assert buf[i:j] == b"hi there\x00"[i:j]
2491 # --misc--
2492 assert list(buf) == list(map(bitem2bchr, b"hi there\x00"))
2493 # --mb_as_buffer--
2494 if hasattr(__builtin__, 'buffer'): # Python <= 2.7
2495 pytest.raises(TypeError, __builtin__.buffer, c)
2496 bf1 = __builtin__.buffer(buf)
2497 assert len(bf1) == len(buf) and bf1[3] == "t"
2498 if hasattr(__builtin__, 'memoryview'): # Python >= 2.7
2499 pytest.raises(TypeError, memoryview, c)
2500 mv1 = memoryview(buf)
2501 assert len(mv1) == len(buf) and mv1[3] in (b"t", ord(b"t"))
2502 # --mb_ass_item--
2503 expected = list(map(bitem2bchr, b"hi there\x00"))
2504 for i in range(-12, 12):
2505 try:
2506 expected[i] = bytechr(i & 0xff)
2507 except IndexError:
2508 with pytest.raises(IndexError):
2509 buf[i] = bytechr(i & 0xff)
2510 else:
2511 buf[i] = bytechr(i & 0xff)
2512 assert list(buf) == expected
2513 # --mb_ass_slice--
2514 buf[:] = b"hi there\x00"
2515 assert list(buf) == list(c) == list(map(bitem2bchr, b"hi there\x00"))
2516 with pytest.raises(ValueError):
2517 buf[:] = b"shorter"
2518 with pytest.raises(ValueError):
2519 buf[:] = b"this is much too long!"
2520 buf[4:2] = b"" # no effect, but should work
2521 assert buf[:] == b"hi there\x00"
2522 buf[:2] = b"HI"
2523 assert buf[:] == b"HI there\x00"
2524 buf[:2] = b"hi"
2525 expected = list(map(bitem2bchr, b"hi there\x00"))
2526 x = 0
2527 for i in range(-12, 12):
2528 for j in range(-12, 12):
2529 start = i if i >= 0 else i + len(buf)
2530 stop = j if j >= 0 else j + len(buf)
2531 start = max(0, min(len(buf), start))
2532 stop = max(0, min(len(buf), stop))
2533 sample = bytechr(x & 0xff) * (stop - start)
2534 x += 1
2535 buf[i:j] = sample
2536 expected[i:j] = map(bitem2bchr, sample)
2537 assert list(buf) == expected
2538
2539 def test_getcname():
2540 BUChar = new_primitive_type("unsigned char")
2541 BArray = new_array_type(new_pointer_type(BUChar), 123)
2542 assert getcname(BArray, "<-->") == "unsigned char<-->[123]"
2543
2544 def test_errno():
2545 BVoid = new_void_type()
2546 BFunc5 = new_function_type((), BVoid)
2547 f = cast(BFunc5, _testfunc(5))
2548 set_errno(50)
2549 f()
2550 assert get_errno() == 65
2551 f(); f()
2552 assert get_errno() == 95
2553
2554 def test_errno_callback():
2555 if globals().get('PY_DOT_PY'):
2556 skip("cannot run this test on py.py (e.g. fails on Windows)")
2557 set_errno(95)
2558 def cb():
2559 e = get_errno()
2560 set_errno(e - 6)
2561 BVoid = new_void_type()
2562 BFunc5 = new_function_type((), BVoid)
2563 f = callback(BFunc5, cb)
2564 f()
2565 assert get_errno() == 89
2566 f(); f()
2567 assert get_errno() == 77
2568
2569 def test_cast_to_array():
2570 # not valid in C! extension to get a non-owning <cdata 'int[3]'>
2571 BInt = new_primitive_type("int")
2572 BIntP = new_pointer_type(BInt)
2573 BArray = new_array_type(BIntP, 3)
2574 x = cast(BArray, 0)
2575 assert repr(x) == "<cdata 'int[3]' NULL>"
2576
2577 def test_cast_invalid():
2578 BStruct = new_struct_type("struct foo")
2579 complete_struct_or_union(BStruct, [])
2580 p = cast(new_pointer_type(BStruct), 123456)
2581 s = p[0]
2582 pytest.raises(TypeError, cast, BStruct, s)
2583
2584 def test_bug_float_convertion():
2585 BDouble = new_primitive_type("double")
2586 BDoubleP = new_pointer_type(BDouble)
2587 pytest.raises(TypeError, newp, BDoubleP, "foobar")
2588
2589 def test_bug_delitem():
2590 BChar = new_primitive_type("char")
2591 BCharP = new_pointer_type(BChar)
2592 x = newp(BCharP)
2593 with pytest.raises(TypeError):
2594 del x[0]
2595
2596 def test_bug_delattr():
2597 BLong = new_primitive_type("long")
2598 BStruct = new_struct_type("struct foo")
2599 complete_struct_or_union(BStruct, [('a1', BLong, -1)])
2600 x = newp(new_pointer_type(BStruct))
2601 with pytest.raises(AttributeError):
2602 del x.a1
2603
2604 def test_variable_length_struct():
2605 skip("later")
2606 BLong = new_primitive_type("long")
2607 BArray = new_array_type(new_pointer_type(BLong), None)
2608 BStruct = new_struct_type("struct foo")
2609 BStructP = new_pointer_type(BStruct)
2610 complete_struct_or_union(BStruct, [('a1', BLong, -1),
2611 ('a2', BArray, -1)])
2612 assert sizeof(BStruct) == size_of_long()
2613 assert alignof(BStruct) == alignof(BLong)
2614 #
2615 pytest.raises(TypeError, newp, BStructP, None)
2616 x = newp(BStructP, 5)
2617 assert sizeof(x) == 6 * size_of_long()
2618 x[4] = 123
2619 assert x[4] == 123
2620 with pytest.raises(IndexError):
2621 x[5]
2622 assert len(x.a2) == 5
2623 #
2624 pytest.raises(TypeError, newp, BStructP, [123])
2625 x = newp(BStructP, [123, 5])
2626 assert x.a1 == 123
2627 assert len(x.a2) == 5
2628 assert list(x.a2) == [0] * 5
2629 #
2630 x = newp(BStructP, {'a2': 5})
2631 assert x.a1 == 0
2632 assert len(x.a2) == 5
2633 assert list(x.a2) == [0] * 5
2634 #
2635 x = newp(BStructP, [123, (4, 5)])
2636 assert x.a1 == 123
2637 assert len(x.a2) == 2
2638 assert list(x.a2) == [4, 5]
2639 #
2640 x = newp(BStructP, {'a2': (4, 5)})
2641 assert x.a1 == 0
2642 assert len(x.a2) == 2
2643 assert list(x.a2) == [4, 5]
2644
2645 def test_autocast_int():
2646 BInt = new_primitive_type("int")
2647 BIntPtr = new_pointer_type(BInt)
2648 BLongLong = new_primitive_type("long long")
2649 BULongLong = new_primitive_type("unsigned long long")
2650 BULongLongPtr = new_pointer_type(BULongLong)
2651 x = newp(BIntPtr, cast(BInt, 42))
2652 assert x[0] == 42
2653 x = newp(BIntPtr, cast(BLongLong, 42))
2654 assert x[0] == 42
2655 x = newp(BIntPtr, cast(BULongLong, 42))
2656 assert x[0] == 42
2657 x = newp(BULongLongPtr, cast(BInt, 42))
2658 assert x[0] == 42
2659 pytest.raises(OverflowError, newp, BULongLongPtr, cast(BInt, -42))
2660 x = cast(BInt, cast(BInt, 42))
2661 assert int(x) == 42
2662 x = cast(BInt, cast(BLongLong, 42))
2663 assert int(x) == 42
2664 x = cast(BInt, cast(BULongLong, 42))
2665 assert int(x) == 42
2666 x = cast(BULongLong, cast(BInt, 42))
2667 assert int(x) == 42
2668 x = cast(BULongLong, cast(BInt, -42))
2669 assert int(x) == 2 ** 64 - 42
2670 x = cast(BIntPtr, cast(BInt, 42))
2671 assert int(cast(BInt, x)) == 42
2672
2673 def test_autocast_float():
2674 BFloat = new_primitive_type("float")
2675 BDouble = new_primitive_type("float")
2676 BFloatPtr = new_pointer_type(BFloat)
2677 x = newp(BFloatPtr, cast(BDouble, 12.5))
2678 assert x[0] == 12.5
2679 x = cast(BFloat, cast(BDouble, 12.5))
2680 assert float(x) == 12.5
2681
2682 def test_longdouble():
2683 py_py = 'PY_DOT_PY' in globals()
2684 BInt = new_primitive_type("int")
2685 BLongDouble = new_primitive_type("long double")
2686 BLongDoublePtr = new_pointer_type(BLongDouble)
2687 BLongDoubleArray = new_array_type(BLongDoublePtr, None)
2688 a = newp(BLongDoubleArray, 1)
2689 x = a[0]
2690 if not py_py:
2691 assert repr(x).startswith("<cdata 'long double' 0.0")
2692 assert float(x) == 0.0
2693 assert int(x) == 0
2694 #
2695 b = newp(BLongDoubleArray, [1.23])
2696 x = b[0]
2697 if not py_py:
2698 assert repr(x).startswith("<cdata 'long double' 1.23")
2699 assert float(x) == 1.23
2700 assert int(x) == 1
2701 #
2702 BFunc19 = new_function_type((BLongDouble, BInt), BLongDouble)
2703 f = cast(BFunc19, _testfunc(19))
2704 start = lstart = 1.5
2705 for i in range(107):
2706 start = 4 * start - start * start
2707 lstart = f(lstart, 1)
2708 lother = f(1.5, 107)
2709 if not py_py:
2710 assert float(lstart) == float(lother)
2711 assert repr(lstart) == repr(lother)
2712 if sizeof(BLongDouble) > sizeof(new_primitive_type("double")):
2713 assert float(lstart) != start
2714 assert repr(lstart).startswith("<cdata 'long double' ")
2715 #
2716 c = newp(BLongDoubleArray, [lstart])
2717 x = c[0]
2718 assert float(f(lstart, 107)) == float(f(x, 107))
2719
2720 def test_get_array_of_length_zero():
2721 for length in [0, 5, 10]:
2722 BLong = new_primitive_type("long")
2723 BLongP = new_pointer_type(BLong)
2724 BArray0 = new_array_type(BLongP, length)
2725 BStruct = new_struct_type("struct foo")
2726 BStructPtr = new_pointer_type(BStruct)
2727 complete_struct_or_union(BStruct, [('a1', BArray0, -1)])
2728 p = newp(BStructPtr, None)
2729 if length == 0:
2730 assert repr(p.a1).startswith("<cdata 'long *' 0x")
2731 else:
2732 assert repr(p.a1).startswith("<cdata 'long[%d]' 0x" % length)
2733
2734 def test_nested_anonymous_struct():
2735 BInt = new_primitive_type("int")
2736 BChar = new_primitive_type("char")
2737 BStruct = new_struct_type("struct foo")
2738 BInnerStruct = new_struct_type("struct foo")
2739 complete_struct_or_union(BInnerStruct, [('a1', BInt, -1),
2740 ('a2', BChar, -1)])
2741 complete_struct_or_union(BStruct, [('', BInnerStruct, -1),
2742 ('a3', BChar, -1)])
2743 assert sizeof(BInnerStruct) == sizeof(BInt) * 2 # with alignment
2744 assert sizeof(BStruct) == sizeof(BInt) * 3 # 'a3' is placed after
2745 d = BStruct.fields
2746 assert len(d) == 3
2747 assert d[0][0] == 'a1'
2748 assert d[0][1].type is BInt
2749 assert d[0][1].offset == 0
2750 assert d[0][1].bitshift == -1
2751 assert d[0][1].bitsize == -1
2752 assert d[1][0] == 'a2'
2753 assert d[1][1].type is BChar
2754 assert d[1][1].offset == sizeof(BInt)
2755 assert d[1][1].bitshift == -1
2756 assert d[1][1].bitsize == -1
2757 assert d[2][0] == 'a3'
2758 assert d[2][1].type is BChar
2759 assert d[2][1].offset == sizeof(BInt) * 2
2760 assert d[2][1].bitshift == -1
2761 assert d[2][1].bitsize == -1
2762
2763 def test_nested_anonymous_struct_2():
2764 BInt = new_primitive_type("int")
2765 BStruct = new_struct_type("struct foo")
2766 BInnerUnion = new_union_type("union bar")
2767 complete_struct_or_union(BInnerUnion, [('a1', BInt, -1),
2768 ('a2', BInt, -1)])
2769 complete_struct_or_union(BStruct, [('b1', BInt, -1),
2770 ('', BInnerUnion, -1),
2771 ('b2', BInt, -1)])
2772 assert sizeof(BInnerUnion) == sizeof(BInt)
2773 assert sizeof(BStruct) == sizeof(BInt) * 3
2774 fields = [(name, fld.offset, fld.flags) for (name, fld) in BStruct.fields]
2775 assert fields == [
2776 ('b1', 0 * sizeof(BInt), 0),
2777 ('a1', 1 * sizeof(BInt), 0),
2778 ('a2', 1 * sizeof(BInt), 1),
2779 ('b2', 2 * sizeof(BInt), 0),
2780 ]
2781
2782 def test_sizeof_union():
2783 # a union has the largest alignment of its members, and a total size
2784 # that is the largest of its items *possibly further aligned* if
2785 # another smaller item has a larger alignment...
2786 BChar = new_primitive_type("char")
2787 BShort = new_primitive_type("short")
2788 assert sizeof(BShort) == alignof(BShort) == 2
2789 BStruct = new_struct_type("struct foo")
2790 complete_struct_or_union(BStruct, [('a1', BChar),
2791 ('a2', BChar),
2792 ('a3', BChar)])
2793 assert sizeof(BStruct) == 3 and alignof(BStruct) == 1
2794 BUnion = new_union_type("union u")
2795 complete_struct_or_union(BUnion, [('s', BStruct),
2796 ('i', BShort)])
2797 assert sizeof(BUnion) == 4
2798 assert alignof(BUnion) == 2
2799
2800 def test_unaligned_struct():
2801 BInt = new_primitive_type("int")
2802 BStruct = new_struct_type("struct foo")
2803 complete_struct_or_union(BStruct, [('b', BInt, -1, 1)],
2804 None, 5, 1)
2805
2806 def test_CData_CType():
2807 CData, CType = _get_types()
2808 BChar = new_primitive_type("char")
2809 BCharP = new_pointer_type(BChar)
2810 nullchr = cast(BChar, 0)
2811 chrref = newp(BCharP, None)
2812 assert isinstance(nullchr, CData)
2813 assert isinstance(chrref, CData)
2814 assert not isinstance(BChar, CData)
2815 assert not isinstance(nullchr, CType)
2816 assert not isinstance(chrref, CType)
2817 assert isinstance(BChar, CType)
2818
2819 def test_no_cdata_float():
2820 BInt = new_primitive_type("int")
2821 BIntP = new_pointer_type(BInt)
2822 BUInt = new_primitive_type("unsigned int")
2823 BUIntP = new_pointer_type(BUInt)
2824 BFloat = new_primitive_type("float")
2825 pytest.raises(TypeError, newp, BIntP, cast(BFloat, 0.0))
2826 pytest.raises(TypeError, newp, BUIntP, cast(BFloat, 0.0))
2827
2828 def test_bool():
2829 BBool = new_primitive_type("_Bool")
2830 BBoolP = new_pointer_type(BBool)
2831 assert int(cast(BBool, False)) == 0
2832 assert int(cast(BBool, True)) == 1
2833 assert bool(cast(BBool, False)) is False # since 1.7
2834 assert bool(cast(BBool, True)) is True
2835 assert int(cast(BBool, 3)) == 1
2836 assert int(cast(BBool, long(3))) == 1
2837 assert int(cast(BBool, long(10)**4000)) == 1
2838 assert int(cast(BBool, -0.1)) == 1
2839 assert int(cast(BBool, -0.0)) == 0
2840 assert int(cast(BBool, '\x00')) == 0
2841 assert int(cast(BBool, '\xff')) == 1
2842 assert newp(BBoolP, False)[0] == 0
2843 assert newp(BBoolP, True)[0] == 1
2844 assert newp(BBoolP, 0)[0] == 0
2845 assert newp(BBoolP, 1)[0] == 1
2846 pytest.raises(TypeError, newp, BBoolP, 1.0)
2847 pytest.raises(TypeError, newp, BBoolP, '\x00')
2848 pytest.raises(OverflowError, newp, BBoolP, 2)
2849 pytest.raises(OverflowError, newp, BBoolP, -1)
2850 BCharP = new_pointer_type(new_primitive_type("char"))
2851 p = newp(BCharP, b'\x01')
2852 q = cast(BBoolP, p)
2853 assert q[0] is True
2854 p = newp(BCharP, b'\x00')
2855 q = cast(BBoolP, p)
2856 assert q[0] is False
2857 pytest.raises(TypeError, string, cast(BBool, False))
2858 BDouble = new_primitive_type("double")
2859 assert int(cast(BBool, cast(BDouble, 0.1))) == 1
2860 assert int(cast(BBool, cast(BDouble, 0.0))) == 0
2861 BBoolA = new_array_type(BBoolP, None)
2862 p = newp(BBoolA, b'\x01\x00')
2863 assert p[0] is True
2864 assert p[1] is False
2865
2866 def test_bool_forbidden_cases():
2867 BBool = new_primitive_type("_Bool")
2868 BBoolP = new_pointer_type(BBool)
2869 BBoolA = new_array_type(BBoolP, None)
2870 BCharP = new_pointer_type(new_primitive_type("char"))
2871 p = newp(BCharP, b'X')
2872 q = cast(BBoolP, p)
2873 with pytest.raises(ValueError):
2874 q[0]
2875 pytest.raises(TypeError, newp, BBoolP, b'\x00')
2876 assert newp(BBoolP, 0)[0] is False
2877 assert newp(BBoolP, 1)[0] is True
2878 pytest.raises(OverflowError, newp, BBoolP, 2)
2879 pytest.raises(OverflowError, newp, BBoolP, -1)
2880 pytest.raises(ValueError, newp, BBoolA, b'\x00\x01\x02')
2881 pytest.raises(OverflowError, newp, BBoolA, [0, 1, 2])
2882 pytest.raises(TypeError, string, newp(BBoolP, 1))
2883 pytest.raises(TypeError, string, newp(BBoolA, [1]))
2884
2885 def test_typeoffsetof():
2886 BChar = new_primitive_type("char")
2887 BStruct = new_struct_type("struct foo")
2888 BStructPtr = new_pointer_type(BStruct)
2889 complete_struct_or_union(BStruct, [('a1', BChar, -1),
2890 ('a2', BChar, -1),
2891 ('a3', BChar, -1)])
2892 pytest.raises(TypeError, typeoffsetof, BStructPtr, None)
2893 pytest.raises(TypeError, typeoffsetof, BStruct, None)
2894 assert typeoffsetof(BStructPtr, 'a1') == (BChar, 0)
2895 assert typeoffsetof(BStruct, 'a1') == (BChar, 0)
2896 assert typeoffsetof(BStructPtr, 'a2') == (BChar, 1)
2897 assert typeoffsetof(BStruct, 'a3') == (BChar, 2)
2898 assert typeoffsetof(BStructPtr, 'a2', 0) == (BChar, 1)
2899 assert typeoffsetof(BStruct, u+'a3') == (BChar, 2)
2900 pytest.raises(TypeError, typeoffsetof, BStructPtr, 'a2', 1)
2901 pytest.raises(KeyError, typeoffsetof, BStructPtr, 'a4')
2902 pytest.raises(KeyError, typeoffsetof, BStruct, 'a5')
2903 pytest.raises(TypeError, typeoffsetof, BStruct, 42)
2904 pytest.raises(TypeError, typeoffsetof, BChar, 'a1')
2905
2906 def test_typeoffsetof_array():
2907 BInt = new_primitive_type("int")
2908 BIntP = new_pointer_type(BInt)
2909 BArray = new_array_type(BIntP, None)
2910 pytest.raises(TypeError, typeoffsetof, BArray, None)
2911 pytest.raises(TypeError, typeoffsetof, BArray, 'a1')
2912 assert typeoffsetof(BArray, 51) == (BInt, 51 * size_of_int())
2913 assert typeoffsetof(BIntP, 51) == (BInt, 51 * size_of_int())
2914 assert typeoffsetof(BArray, -51) == (BInt, -51 * size_of_int())
2915 MAX = sys.maxsize // size_of_int()
2916 assert typeoffsetof(BArray, MAX) == (BInt, MAX * size_of_int())
2917 assert typeoffsetof(BIntP, MAX) == (BInt, MAX * size_of_int())
2918 pytest.raises(OverflowError, typeoffsetof, BArray, MAX + 1)
2919
2920 def test_typeoffsetof_no_bitfield():
2921 BInt = new_primitive_type("int")
2922 BStruct = new_struct_type("struct foo")
2923 complete_struct_or_union(BStruct, [('a1', BInt, 4)])
2924 pytest.raises(TypeError, typeoffsetof, BStruct, 'a1')
2925
2926 def test_rawaddressof():
2927 BChar = new_primitive_type("char")
2928 BCharP = new_pointer_type(BChar)
2929 BStruct = new_struct_type("struct foo")
2930 BStructPtr = new_pointer_type(BStruct)
2931 complete_struct_or_union(BStruct, [('a1', BChar, -1),
2932 ('a2', BChar, -1),
2933 ('a3', BChar, -1)])
2934 p = newp(BStructPtr)
2935 assert repr(p) == "<cdata 'struct foo *' owning 3 bytes>"
2936 s = p[0]
2937 assert repr(s) == "<cdata 'struct foo' owning 3 bytes>"
2938 a = rawaddressof(BStructPtr, s, 0)
2939 assert repr(a).startswith("<cdata 'struct foo *' 0x")
2940 pytest.raises(TypeError, rawaddressof, BStruct, s, 0)
2941 b = rawaddressof(BCharP, s, 0)
2942 assert b == cast(BCharP, p)
2943 c = rawaddressof(BStructPtr, a, 0)
2944 assert c == a
2945 pytest.raises(TypeError, rawaddressof, BStructPtr, cast(BChar, '?'), 0)
2946 #
2947 d = rawaddressof(BCharP, s, 1)
2948 assert d == cast(BCharP, p) + 1
2949 #
2950 e = cast(BCharP, 109238)
2951 f = rawaddressof(BCharP, e, 42)
2952 assert f == e + 42
2953 #
2954 BCharA = new_array_type(BCharP, None)
2955 e = newp(BCharA, 50)
2956 f = rawaddressof(BCharP, e, 42)
2957 assert f == e + 42
2958
2959 def test_newp_signed_unsigned_char():
2960 BCharArray = new_array_type(
2961 new_pointer_type(new_primitive_type("char")), None)
2962 p = newp(BCharArray, b"foo")
2963 assert len(p) == 4
2964 assert list(p) == [b"f", b"o", b"o", b"\x00"]
2965 #
2966 BUCharArray = new_array_type(
2967 new_pointer_type(new_primitive_type("unsigned char")), None)
2968 p = newp(BUCharArray, b"fo\xff")
2969 assert len(p) == 4
2970 assert list(p) == [ord("f"), ord("o"), 0xff, 0]
2971 #
2972 BSCharArray = new_array_type(
2973 new_pointer_type(new_primitive_type("signed char")), None)
2974 p = newp(BSCharArray, b"fo\xff")
2975 assert len(p) == 4
2976 assert list(p) == [ord("f"), ord("o"), -1, 0]
2977
2978 def test_newp_from_bytearray_doesnt_work():
2979 BCharArray = new_array_type(
2980 new_pointer_type(new_primitive_type("char")), None)
2981 pytest.raises(TypeError, newp, BCharArray, bytearray(b"foo"))
2982 p = newp(BCharArray, 5)
2983 buffer(p)[:] = bytearray(b"foo.\x00")
2984 assert len(p) == 5
2985 assert list(p) == [b"f", b"o", b"o", b".", b"\x00"]
2986 p[1:3] = bytearray(b"XY")
2987 assert list(p) == [b"f", b"X", b"Y", b".", b"\x00"]
2988
2989 def test_string_assignment_to_byte_array():
2990 BByteArray = new_array_type(
2991 new_pointer_type(new_primitive_type("unsigned char")), None)
2992 p = newp(BByteArray, 5)
2993 p[0:3] = bytearray(b"XYZ")
2994 assert list(p) == [ord("X"), ord("Y"), ord("Z"), 0, 0]
2995
2996 # XXX hack
2997 if sys.version_info >= (3,):
2998 try:
2999 import posix, io
3000 posix.fdopen = io.open
3001 except ImportError:
3002 pass # win32
3003
3004 def test_FILE():
3005 if sys.platform == "win32":
3006 skip("testing FILE not implemented")
3007 # XXX patch start
3008 if sys.platform == "darwin":
3009 skip("testing variadic broken on macos (issue 4937)")
3010 # XXX patch end
3011 BFILE = new_struct_type("struct _IO_FILE")
3012 BFILEP = new_pointer_type(BFILE)
3013 BChar = new_primitive_type("char")
3014 BCharP = new_pointer_type(BChar)
3015 BInt = new_primitive_type("int")
3016 BFunc = new_function_type((BCharP, BFILEP), BInt, False)
3017 BFunc2 = new_function_type((BFILEP, BCharP), BInt, True)
3018 ll = find_and_load_library('c')
3019 fputs = ll.load_function(BFunc, "fputs")
3020 fscanf = ll.load_function(BFunc2, "fscanf")
3021 #
3022 import posix
3023 fdr, fdw = posix.pipe()
3024 fr1 = posix.fdopen(fdr, 'rb', 256)
3025 fw1 = posix.fdopen(fdw, 'wb', 256)
3026 #
3027 fw1.write(b"X")
3028 res = fputs(b"hello world\n", fw1)
3029 assert res >= 0
3030 fw1.flush() # should not be needed
3031 #
3032 p = newp(new_array_type(BCharP, 100), None)
3033 res = fscanf(fr1, b"%s\n", p)
3034 assert res == 1
3035 assert string(p) == b"Xhello"
3036 fr1.close()
3037 fw1.close()
3038
3039 def test_FILE_only_for_FILE_arg():
3040 if sys.platform == "win32":
3041 skip("testing FILE not implemented")
3042 #
3043 B_NOT_FILE = new_struct_type("struct NOT_FILE")
3044 B_NOT_FILEP = new_pointer_type(B_NOT_FILE)
3045 BChar = new_primitive_type("char")
3046 BCharP = new_pointer_type(BChar)
3047 BInt = new_primitive_type("int")
3048 BFunc = new_function_type((BCharP, B_NOT_FILEP), BInt, False)
3049 ll = find_and_load_library('c')
3050 fputs = ll.load_function(BFunc, "fputs")
3051 #
3052 import posix
3053 fdr, fdw = posix.pipe()
3054 fr1 = posix.fdopen(fdr, 'r')
3055 fw1 = posix.fdopen(fdw, 'w')
3056 #
3057 e = pytest.raises(TypeError, fputs, b"hello world\n", fw1)
3058 assert str(e.value).startswith(
3059 "initializer for ctype 'struct NOT_FILE *' must "
3060 "be a cdata pointer, not ")
3061
3062 def test_FILE_object():
3063 if sys.platform == "win32":
3064 skip("testing FILE not implemented")
3065 #
3066 BFILE = new_struct_type("FILE")
3067 BFILEP = new_pointer_type(BFILE)
3068 BChar = new_primitive_type("char")
3069 BCharP = new_pointer_type(BChar)
3070 BInt = new_primitive_type("int")
3071 BFunc = new_function_type((BCharP, BFILEP), BInt, False)
3072 BFunc2 = new_function_type((BFILEP,), BInt, False)
3073 ll = find_and_load_library('c')
3074 fputs = ll.load_function(BFunc, "fputs")
3075 fileno = ll.load_function(BFunc2, "fileno")
3076 #
3077 import posix
3078 fdr, fdw = posix.pipe()
3079 fw1 = posix.fdopen(fdw, 'wb', 256)
3080 #
3081 fw1p = cast(BFILEP, fw1)
3082 fw1.write(b"X")
3083 fw1.flush()
3084 res = fputs(b"hello\n", fw1p)
3085 assert res >= 0
3086 res = fileno(fw1p)
3087 assert (res == fdw) == (sys.version_info < (3,))
3088 fw1.close()
3089 #
3090 data = posix.read(fdr, 256)
3091 assert data == b"Xhello\n"
3092 posix.close(fdr)
3093
3094 def test_errno_saved():
3095 set_errno(42)
3096 # a random function that will reset errno to 0 (at least on non-windows)
3097 import os; os.stat('.')
3098 #
3099 res = get_errno()
3100 assert res == 42
3101
3102 def test_GetLastError():
3103 if sys.platform != "win32":
3104 skip("GetLastError(): only for Windows")
3105 #
3106 lib = find_and_load_library('KERNEL32.DLL')
3107 BInt = new_primitive_type("int")
3108 BVoid = new_void_type()
3109 BFunc1 = new_function_type((BInt,), BVoid, False)
3110 BFunc2 = new_function_type((), BInt, False)
3111 SetLastError = lib.load_function(BFunc1, "SetLastError")
3112 GetLastError = lib.load_function(BFunc2, "GetLastError")
3113 #
3114 SetLastError(42)
3115 # a random function that will reset the real GetLastError() to 0
3116 import nt; nt.stat('.')
3117 #
3118 res = GetLastError()
3119 assert res == 42
3120 #
3121 SetLastError(2)
3122 code, message = getwinerror()
3123 assert code == 2
3124 assert message == "The system cannot find the file specified"
3125 #
3126 code, message = getwinerror(1155)
3127 assert code == 1155
3128 assert message == ("No application is associated with the "
3129 "specified file for this operation")
3130
3131 def test_nonstandard_integer_types():
3132 for typename in ['int8_t', 'uint8_t', 'int16_t', 'uint16_t', 'int32_t',
3133 'uint32_t', 'int64_t', 'uint64_t', 'intptr_t',
3134 'uintptr_t', 'ptrdiff_t', 'size_t', 'ssize_t',
3135 'int_least8_t', 'uint_least8_t',
3136 'int_least16_t', 'uint_least16_t',
3137 'int_least32_t', 'uint_least32_t',
3138 'int_least64_t', 'uint_least64_t',
3139 'int_fast8_t', 'uint_fast8_t',
3140 'int_fast16_t', 'uint_fast16_t',
3141 'int_fast32_t', 'uint_fast32_t',
3142 'int_fast64_t', 'uint_fast64_t',
3143 'intmax_t', 'uintmax_t']:
3144 new_primitive_type(typename) # works
3145
3146 def test_cannot_convert_unicode_to_charp():
3147 BCharP = new_pointer_type(new_primitive_type("char"))
3148 BCharArray = new_array_type(BCharP, None)
3149 pytest.raises(TypeError, newp, BCharArray, u+'foobar')
3150
3151 def test_buffer_keepalive():
3152 BCharP = new_pointer_type(new_primitive_type("char"))
3153 BCharArray = new_array_type(BCharP, None)
3154 buflist = []
3155 for i in range(20):
3156 c = newp(BCharArray, str2bytes("hi there %d" % i))
3157 buflist.append(buffer(c))
3158 import gc; gc.collect()
3159 for i in range(20):
3160 buf = buflist[i]
3161 assert buf[:] == str2bytes("hi there %d\x00" % i)
3162
3163 def test_slice():
3164 BIntP = new_pointer_type(new_primitive_type("int"))
3165 BIntArray = new_array_type(BIntP, None)
3166 c = newp(BIntArray, 5)
3167 assert len(c) == 5
3168 assert repr(c) == "<cdata 'int[]' owning 20 bytes>"
3169 d = c[1:4]
3170 assert len(d) == 3
3171 assert repr(d) == "<cdata 'int[]' sliced length 3>"
3172 d[0] = 123
3173 d[2] = 456
3174 assert c[1] == 123
3175 assert c[3] == 456
3176 assert d[2] == 456
3177 with pytest.raises(IndexError):
3178 d[3]
3179 with pytest.raises(IndexError):
3180 d[-1]
3181
3182 def test_slice_ptr():
3183 BIntP = new_pointer_type(new_primitive_type("int"))
3184 BIntArray = new_array_type(BIntP, None)
3185 c = newp(BIntArray, 5)
3186 d = (c+1)[0:2]
3187 assert len(d) == 2
3188 assert repr(d) == "<cdata 'int[]' sliced length 2>"
3189 d[1] += 50
3190 assert c[2] == 50
3191
3192 def test_slice_array_checkbounds():
3193 BIntP = new_pointer_type(new_primitive_type("int"))
3194 BIntArray = new_array_type(BIntP, None)
3195 c = newp(BIntArray, 5)
3196 c[0:5]
3197 assert len(c[5:5]) == 0
3198 with pytest.raises(IndexError):
3199 c[-1:1]
3200 cp = c + 0
3201 cp[-1:1]
3202
3203 def test_nonstandard_slice():
3204 BIntP = new_pointer_type(new_primitive_type("int"))
3205 BIntArray = new_array_type(BIntP, None)
3206 c = newp(BIntArray, 5)
3207 with pytest.raises(IndexError) as e:
3208 c[:5]
3209 assert str(e.value) == "slice start must be specified"
3210 with pytest.raises(IndexError) as e:
3211 c[4:]
3212 assert str(e.value) == "slice stop must be specified"
3213 with pytest.raises(IndexError) as e:
3214 c[1:2:3]
3215 assert str(e.value) == "slice with step not supported"
3216 with pytest.raises(IndexError) as e:
3217 c[1:2:1]
3218 assert str(e.value) == "slice with step not supported"
3219 with pytest.raises(IndexError) as e:
3220 c[4:2]
3221 assert str(e.value) == "slice start > stop"
3222 with pytest.raises(IndexError) as e:
3223 c[6:6]
3224 assert str(e.value) == "index too large (expected 6 <= 5)"
3225
3226 def test_setslice():
3227 BIntP = new_pointer_type(new_primitive_type("int"))
3228 BIntArray = new_array_type(BIntP, None)
3229 c = newp(BIntArray, 5)
3230 c[1:3] = [100, 200]
3231 assert list(c) == [0, 100, 200, 0, 0]
3232 cp = c + 3
3233 cp[-1:1] = [300, 400]
3234 assert list(c) == [0, 100, 300, 400, 0]
3235 cp[-1:1] = iter([500, 600])
3236 assert list(c) == [0, 100, 500, 600, 0]
3237 with pytest.raises(ValueError):
3238 cp[-1:1] = [1000]
3239 assert list(c) == [0, 100, 1000, 600, 0]
3240 with pytest.raises(ValueError):
3241 cp[-1:1] = (700, 800, 900)
3242 assert list(c) == [0, 100, 700, 800, 0]
3243
3244 def test_setslice_array():
3245 BIntP = new_pointer_type(new_primitive_type("int"))
3246 BIntArray = new_array_type(BIntP, None)
3247 c = newp(BIntArray, 5)
3248 d = newp(BIntArray, [10, 20, 30])
3249 c[1:4] = d
3250 assert list(c) == [0, 10, 20, 30, 0]
3251 #
3252 BShortP = new_pointer_type(new_primitive_type("short"))
3253 BShortArray = new_array_type(BShortP, None)
3254 d = newp(BShortArray, [40, 50])
3255 c[1:3] = d
3256 assert list(c) == [0, 40, 50, 30, 0]
3257
3258 def test_cdata_name_module_doc():
3259 p = new_primitive_type("signed char")
3260 x = cast(p, 17)
3261 assert x.__module__ == '_cffi_backend'
3262 assert x.__name__ == '<cdata>'
3263 assert hasattr(x, '__doc__')
3264
3265 def test_different_types_of_ptr_equality():
3266 BVoidP = new_pointer_type(new_void_type())
3267 BIntP = new_pointer_type(new_primitive_type("int"))
3268 x = cast(BVoidP, 12345)
3269 assert x == cast(BIntP, 12345)
3270 assert x != cast(BIntP, 12344)
3271 assert hash(x) == hash(cast(BIntP, 12345))
3272
3273 def test_new_handle():
3274 import _weakref
3275 BVoidP = new_pointer_type(new_void_type())
3276 BCharP = new_pointer_type(new_primitive_type("char"))
3277 class mylist(list):
3278 pass
3279 o = mylist([2, 3, 4])
3280 x = newp_handle(BVoidP, o)
3281 assert repr(x) == "<cdata 'void *' handle to [2, 3, 4]>"
3282 assert x
3283 assert from_handle(x) is o
3284 assert from_handle(cast(BCharP, x)) is o
3285 wr = _weakref.ref(o)
3286 del o
3287 import gc; gc.collect()
3288 assert wr() is not None
3289 assert from_handle(x) == list((2, 3, 4))
3290 assert from_handle(cast(BCharP, x)) == list((2, 3, 4))
3291 del x
3292 for i in range(3):
3293 if wr() is not None:
3294 import gc; gc.collect()
3295 assert wr() is None
3296 pytest.raises(RuntimeError, from_handle, cast(BCharP, 0))
3297
3298 def test_new_handle_cycle():
3299 import _weakref
3300 BVoidP = new_pointer_type(new_void_type())
3301 class A(object):
3302 pass
3303 o = A()
3304 o.cycle = newp_handle(BVoidP, o)
3305 wr = _weakref.ref(o)
3306 del o
3307 for i in range(3):
3308 if wr() is not None:
3309 import gc; gc.collect()
3310 assert wr() is None
3311
3312 def _test_bitfield_details(flag):
3313 BChar = new_primitive_type("char")
3314 BShort = new_primitive_type("short")
3315 BInt = new_primitive_type("int")
3316 BUInt = new_primitive_type("unsigned int")
3317 BStruct = new_struct_type("struct foo1")
3318 complete_struct_or_union(BStruct, [('a', BChar, -1),
3319 ('b1', BInt, 9),
3320 ('b2', BUInt, 7),
3321 ('c', BChar, -1)], -1, -1, -1, flag)
3322 if not (flag & SF_MSVC_BITFIELDS): # gcc, any variant
3323 assert typeoffsetof(BStruct, 'c') == (BChar, 3)
3324 assert sizeof(BStruct) == 4
3325 else: # msvc
3326 assert typeoffsetof(BStruct, 'c') == (BChar, 8)
3327 assert sizeof(BStruct) == 12
3328 assert alignof(BStruct) == 4
3329 #
3330 p = newp(new_pointer_type(BStruct), None)
3331 p.a = b'A'
3332 p.b1 = -201
3333 p.b2 = 99
3334 p.c = b'\x9D'
3335 raw = buffer(p)[:]
3336 if sys.byteorder == 'little':
3337 if flag & SF_MSVC_BITFIELDS:
3338 assert raw == b'A\x00\x00\x007\xC7\x00\x00\x9D\x00\x00\x00'
3339 elif flag & SF_GCC_LITTLE_ENDIAN:
3340 assert raw == b'A7\xC7\x9D'
3341 elif flag & SF_GCC_BIG_ENDIAN:
3342 assert raw == b'A\xE3\x9B\x9D'
3343 else:
3344 raise AssertionError("bad flag")
3345 else:
3346 if flag & SF_MSVC_BITFIELDS:
3347 assert raw == b'A\x00\x00\x00\x00\x00\xC77\x9D\x00\x00\x00'
3348 elif flag & SF_GCC_LITTLE_ENDIAN:
3349 assert raw == b'A\xC77\x9D'
3350 elif flag & SF_GCC_BIG_ENDIAN:
3351 assert raw == b'A\x9B\xE3\x9D'
3352 else:
3353 raise AssertionError("bad flag")
3354 #
3355 BStruct = new_struct_type("struct foo2")
3356 complete_struct_or_union(BStruct, [('a', BChar, -1),
3357 ('', BShort, 9),
3358 ('c', BChar, -1)], -1, -1, -1, flag)
3359 assert typeoffsetof(BStruct, 'c') == (BChar, 4)
3360 if flag & SF_MSVC_BITFIELDS:
3361 assert sizeof(BStruct) == 6
3362 assert alignof(BStruct) == 2
3363 elif flag & SF_GCC_X86_BITFIELDS:
3364 assert sizeof(BStruct) == 5
3365 assert alignof(BStruct) == 1
3366 elif flag & SF_GCC_ARM_BITFIELDS:
3367 assert sizeof(BStruct) == 6
3368 assert alignof(BStruct) == 2
3369 else:
3370 raise AssertionError("bad flag")
3371 #
3372 BStruct = new_struct_type("struct foo2")
3373 complete_struct_or_union(BStruct, [('a', BChar, -1),
3374 ('', BInt, 0),
3375 ('', BInt, 0),
3376 ('c', BChar, -1)], -1, -1, -1, flag)
3377 if flag & SF_MSVC_BITFIELDS:
3378 assert typeoffsetof(BStruct, 'c') == (BChar, 1)
3379 assert sizeof(BStruct) == 2
3380 assert alignof(BStruct) == 1
3381 elif flag & SF_GCC_X86_BITFIELDS:
3382 assert typeoffsetof(BStruct, 'c') == (BChar, 4)
3383 assert sizeof(BStruct) == 5
3384 assert alignof(BStruct) == 1
3385 elif flag & SF_GCC_ARM_BITFIELDS:
3386 assert typeoffsetof(BStruct, 'c') == (BChar, 4)
3387 assert sizeof(BStruct) == 8
3388 assert alignof(BStruct) == 4
3389 else:
3390 raise AssertionError("bad flag")
3391
3392
3393 SF_MSVC_BITFIELDS = 0x01
3394 SF_GCC_ARM_BITFIELDS = 0x02
3395 SF_GCC_X86_BITFIELDS = 0x10
3396
3397 SF_GCC_BIG_ENDIAN = 0x04
3398 SF_GCC_LITTLE_ENDIAN = 0x40
3399
3400 SF_PACKED = 0x08
3401
3402 def test_bitfield_as_x86_gcc():
3403 _test_bitfield_details(flag=SF_GCC_X86_BITFIELDS|SF_GCC_LITTLE_ENDIAN)
3404
3405 def test_bitfield_as_msvc():
3406 _test_bitfield_details(flag=SF_MSVC_BITFIELDS|SF_GCC_LITTLE_ENDIAN)
3407
3408 def test_bitfield_as_arm_gcc():
3409 _test_bitfield_details(flag=SF_GCC_ARM_BITFIELDS|SF_GCC_LITTLE_ENDIAN)
3410
3411 def test_bitfield_as_ppc_gcc():
3412 # PowerPC uses the same format as X86, but is big-endian
3413 _test_bitfield_details(flag=SF_GCC_X86_BITFIELDS|SF_GCC_BIG_ENDIAN)
3414
3415
3416 def buffer_warning(cdata):
3417 import warnings
3418 buf = buffer(cdata)
3419 bytes = len(buf)
3420 with warnings.catch_warnings(record=True) as w:
3421 warnings.simplefilter("always")
3422 buffer(cdata, bytes)
3423 assert len(w) == 0
3424 buffer(cdata, bytes + 1)
3425 assert len(w) <= 1
3426 return len(w) == 1
3427
3428 def test_struct_array_no_length():
3429 BInt = new_primitive_type("int")
3430 BIntP = new_pointer_type(BInt)
3431 BArray = new_array_type(BIntP, None)
3432 BStruct = new_struct_type("foo")
3433 pytest.raises(TypeError, complete_struct_or_union,
3434 BStruct, [('x', BArray),
3435 ('y', BInt)])
3436 #
3437 BStruct = new_struct_type("foo")
3438 complete_struct_or_union(BStruct, [('x', BInt),
3439 ('y', BArray)])
3440 assert sizeof(BStruct) == size_of_int()
3441 d = BStruct.fields
3442 assert len(d) == 2
3443 assert d[0][0] == 'x'
3444 assert d[0][1].type is BInt
3445 assert d[0][1].offset == 0
3446 assert d[0][1].bitshift == -1
3447 assert d[0][1].bitsize == -1
3448 assert d[1][0] == 'y'
3449 assert d[1][1].type is BArray
3450 assert d[1][1].offset == size_of_int()
3451 assert d[1][1].bitshift == -2
3452 assert d[1][1].bitsize == -1
3453 #
3454 p = newp(new_pointer_type(BStruct))
3455 p.x = 42
3456 assert p.x == 42
3457 assert typeof(p.y) is BArray
3458 assert len(p.y) == 0
3459 assert p.y == cast(BIntP, p) + 1
3460 #
3461 p = newp(new_pointer_type(BStruct), [100])
3462 assert p.x == 100
3463 assert len(p.y) == 0
3464 #
3465 # Tests for
3466 # ffi.new("struct_with_var_array *", [field.., [the_array_items..]])
3467 # ffi.new("struct_with_var_array *", [field.., array_size])
3468 plist = []
3469 for i in range(20):
3470 if i % 2 == 0:
3471 p = newp(new_pointer_type(BStruct), [100, [200, i, 400]])
3472 else:
3473 p = newp(new_pointer_type(BStruct), [100, 3])
3474 p.y[1] = i
3475 p.y[0] = 200
3476 assert p.y[2] == 0
3477 p.y[2] = 400
3478 assert len(p.y) == 3
3479 assert len(p[0].y) == 3
3480 assert len(buffer(p)) == sizeof(BInt) * 4
3481 assert sizeof(p[0]) == sizeof(BInt) * 4
3482 plist.append(p)
3483 for i in range(20):
3484 p = plist[i]
3485 assert p.x == 100
3486 assert p.y[0] == 200
3487 assert p.y[1] == i
3488 assert p.y[2] == 400
3489 assert list(p.y) == [200, i, 400]
3490 #
3491 # the following assignment works, as it normally would, for any array field
3492 p.y = [501, 601]
3493 assert list(p.y) == [501, 601, 400]
3494 p[0].y = [500, 600]
3495 assert list(p[0].y) == [500, 600, 400]
3496 assert repr(p) == "<cdata 'foo *' owning %d bytes>" % (
3497 sizeof(BStruct) + 3 * sizeof(BInt),)
3498 assert repr(p[0]) == "<cdata 'foo' owning %d bytes>" % (
3499 sizeof(BStruct) + 3 * sizeof(BInt),)
3500 assert sizeof(p[0]) == sizeof(BStruct) + 3 * sizeof(BInt)
3501 #
3502 # from a non-owning pointer, we can't get the length
3503 q = cast(new_pointer_type(BStruct), p)
3504 assert q.y[0] == 500
3505 assert q[0].y[0] == 500
3506 pytest.raises(TypeError, len, q.y)
3507 pytest.raises(TypeError, len, q[0].y)
3508 assert typeof(q.y) is BIntP
3509 assert typeof(q[0].y) is BIntP
3510 assert sizeof(q[0]) == sizeof(BStruct)
3511 #
3512 # error cases
3513 with pytest.raises(IndexError):
3514 p.y[4]
3515 with pytest.raises(TypeError):
3516 p.y = cast(BIntP, 0)
3517 with pytest.raises(TypeError):
3518 p.y = 15
3519 with pytest.raises(TypeError):
3520 p.y = None
3521 #
3522 # accepting this may be specified by the C99 standard,
3523 # or a GCC strangeness...
3524 BStruct2 = new_struct_type("bar")
3525 complete_struct_or_union(BStruct2, [('f', BStruct),
3526 ('n', BInt)])
3527 p = newp(new_pointer_type(BStruct2), {'n': 42})
3528 assert p.n == 42
3529 #
3530 # more error cases
3531 pytest.raises(TypeError, newp, new_pointer_type(BStruct), [100, None])
3532 BArray4 = new_array_type(BIntP, 4)
3533 BStruct4 = new_struct_type("test4")
3534 complete_struct_or_union(BStruct4, [('a', BArray4)]) # not varsized
3535 pytest.raises(TypeError, newp, new_pointer_type(BStruct4), [None])
3536 pytest.raises(TypeError, newp, new_pointer_type(BStruct4), [4])
3537 p = newp(new_pointer_type(BStruct4), [[10, 20, 30]])
3538 assert p.a[0] == 10
3539 assert p.a[1] == 20
3540 assert p.a[2] == 30
3541 assert p.a[3] == 0
3542 assert buffer_warning(p)
3543 #
3544 # struct of struct of varsized array
3545 BStruct2 = new_struct_type("bar")
3546 complete_struct_or_union(BStruct2, [('head', BInt),
3547 ('tail', BStruct)])
3548 for i in range(2): # try to detect heap overwrites
3549 p = newp(new_pointer_type(BStruct2), [100, [200, list(range(50))]])
3550 assert p.tail.y[49] == 49
3551 assert buffer_warning(p)
3552 assert not buffer_warning(cast(new_pointer_type(BStruct2), p))
3553 assert not buffer_warning(cast(BIntP, p))
3554
3555 def test_more_buffer_warning():
3556 BChar = new_primitive_type("unsigned char")
3557 BCharP = new_pointer_type(BChar)
3558 BArray = new_array_type(BCharP, 10) # char[10]
3559 p = newp(BArray)
3560 assert buffer_warning(p)
3561 assert not buffer_warning(cast(BCharP, p))
3562 p = newp(BCharP)
3563 assert buffer_warning(p)
3564 assert not buffer_warning(cast(BCharP, p))
3565
3566
3567 def test_struct_array_no_length_explicit_position():
3568 BInt = new_primitive_type("int")
3569 BIntP = new_pointer_type(BInt)
3570 BArray = new_array_type(BIntP, None)
3571 BStruct = new_struct_type("foo")
3572 complete_struct_or_union(BStruct, [('x', BArray, -1, 0), # actually 3 items
3573 ('y', BInt, -1, 12)])
3574 p = newp(new_pointer_type(BStruct), [[10, 20], 30])
3575 assert p.x[0] == 10
3576 assert p.x[1] == 20
3577 assert p.x[2] == 0
3578 assert p.y == 30
3579 p = newp(new_pointer_type(BStruct), {'x': [40], 'y': 50})
3580 assert p.x[0] == 40
3581 assert p.x[1] == 0
3582 assert p.x[2] == 0
3583 assert p.y == 50
3584 p = newp(new_pointer_type(BStruct), {'y': 60})
3585 assert p.x[0] == 0
3586 assert p.x[1] == 0
3587 assert p.x[2] == 0
3588 assert p.y == 60
3589 #
3590 # This "should" work too, allocating a larger structure
3591 # (a bit strange in this case, but useful in general)
3592 plist = []
3593 for i in range(20):
3594 p = newp(new_pointer_type(BStruct), [[10, 20, 30, 40, 50, 60, 70]])
3595 plist.append(p)
3596 for i in range(20):
3597 p = plist[i]
3598 assert p.x[0] == 10
3599 assert p.x[1] == 20
3600 assert p.x[2] == 30
3601 assert p.x[3] == 40 == p.y
3602 assert p.x[4] == 50
3603 assert p.x[5] == 60
3604 assert p.x[6] == 70
3605
3606 def test_struct_array_not_aligned():
3607 # struct a { int x; char y; char z[]; };
3608 # ends up of size 8, but 'z' is at offset 5
3609 BChar = new_primitive_type("char")
3610 BInt = new_primitive_type("int")
3611 BCharP = new_pointer_type(BChar)
3612 BArray = new_array_type(BCharP, None)
3613 BStruct = new_struct_type("foo")
3614 complete_struct_or_union(BStruct, [('x', BInt),
3615 ('y', BChar),
3616 ('z', BArray)])
3617 assert sizeof(BStruct) == 2 * size_of_int()
3618 def offsetof(BType, fieldname):
3619 return typeoffsetof(BType, fieldname)[1]
3620 base = offsetof(BStruct, 'z')
3621 assert base == size_of_int() + 1
3622 #
3623 p = newp(new_pointer_type(BStruct), {'z': 3})
3624 assert sizeof(p[0]) == base + 3
3625 q = newp(new_pointer_type(BStruct), {'z': size_of_int()})
3626 assert sizeof(q) == size_of_ptr()
3627 assert sizeof(q[0]) == base + size_of_int()
3628 assert len(p.z) == 3
3629 assert len(p[0].z) == 3
3630 assert len(q.z) == size_of_int()
3631 assert len(q[0].z) == size_of_int()
3632
3633 def test_ass_slice():
3634 BChar = new_primitive_type("char")
3635 BArray = new_array_type(new_pointer_type(BChar), None)
3636 p = newp(BArray, b"foobar")
3637 p[2:5] = [b"*", b"Z", b"T"]
3638 p[1:3] = b"XY"
3639 assert list(p) == [b"f", b"X", b"Y", b"Z", b"T", b"r", b"\x00"]
3640 with pytest.raises(TypeError):
3641 p[1:5] = u+'XYZT'
3642 with pytest.raises(TypeError):
3643 p[1:5] = [1, 2, 3, 4]
3644 #
3645 for typename in ["wchar_t", "char16_t", "char32_t"]:
3646 BUniChar = new_primitive_type(typename)
3647 BArray = new_array_type(new_pointer_type(BUniChar), None)
3648 p = newp(BArray, u+"foobar")
3649 p[2:5] = [u+"*", u+"Z", u+"T"]
3650 p[1:3] = u+"XY"
3651 assert list(p) == [u+"f", u+"X", u+"Y", u+"Z", u+"T", u+"r", u+"\x00"]
3652 with pytest.raises(TypeError):
3653 p[1:5] = b'XYZT'
3654 with pytest.raises(TypeError):
3655 p[1:5] = [1, 2, 3, 4]
3656
3657 def test_void_p_arithmetic():
3658 BVoid = new_void_type()
3659 BInt = new_primitive_type("intptr_t")
3660 p = cast(new_pointer_type(BVoid), 100000)
3661 assert int(cast(BInt, p)) == 100000
3662 assert int(cast(BInt, p + 42)) == 100042
3663 assert int(cast(BInt, p - (-42))) == 100042
3664 assert (p + 42) - p == 42
3665 q = cast(new_pointer_type(new_primitive_type("char")), 100000)
3666 with pytest.raises(TypeError):
3667 p - q
3668 with pytest.raises(TypeError):
3669 q - p
3670 with pytest.raises(TypeError):
3671 p + cast(new_primitive_type('int'), 42)
3672 with pytest.raises(TypeError):
3673 p - cast(new_primitive_type('int'), 42)
3674
3675 def test_sizeof_sliced_array():
3676 BInt = new_primitive_type("int")
3677 BArray = new_array_type(new_pointer_type(BInt), 10)
3678 p = newp(BArray, None)
3679 assert sizeof(p[2:9]) == 7 * sizeof(BInt)
3680
3681 def test_packed():
3682 BLong = new_primitive_type("long")
3683 BChar = new_primitive_type("char")
3684 BShort = new_primitive_type("short")
3685 for extra_args in [(SF_PACKED,), (0, 1)]:
3686 BStruct = new_struct_type("struct foo")
3687 complete_struct_or_union(BStruct, [('a1', BLong, -1),
3688 ('a2', BChar, -1),
3689 ('a3', BShort, -1)],
3690 None, -1, -1, *extra_args)
3691 d = BStruct.fields
3692 assert len(d) == 3
3693 assert d[0][0] == 'a1'
3694 assert d[0][1].type is BLong
3695 assert d[0][1].offset == 0
3696 assert d[0][1].bitshift == -1
3697 assert d[0][1].bitsize == -1
3698 assert d[1][0] == 'a2'
3699 assert d[1][1].type is BChar
3700 assert d[1][1].offset == sizeof(BLong)
3701 assert d[1][1].bitshift == -1
3702 assert d[1][1].bitsize == -1
3703 assert d[2][0] == 'a3'
3704 assert d[2][1].type is BShort
3705 assert d[2][1].offset == sizeof(BLong) + sizeof(BChar)
3706 assert d[2][1].bitshift == -1
3707 assert d[2][1].bitsize == -1
3708 assert sizeof(BStruct) == sizeof(BLong) + sizeof(BChar) + sizeof(BShort)
3709 assert alignof(BStruct) == 1
3710 #
3711 BStruct2 = new_struct_type("struct foo")
3712 complete_struct_or_union(BStruct2, [('b1', BChar, -1),
3713 ('b2', BLong, -1)],
3714 None, -1, -1, 0, 2)
3715 d = BStruct2.fields
3716 assert len(d) == 2
3717 assert d[0][0] == 'b1'
3718 assert d[0][1].type is BChar
3719 assert d[0][1].offset == 0
3720 assert d[0][1].bitshift == -1
3721 assert d[0][1].bitsize == -1
3722 assert d[1][0] == 'b2'
3723 assert d[1][1].type is BLong
3724 assert d[1][1].offset == 2
3725 assert d[1][1].bitshift == -1
3726 assert d[1][1].bitsize == -1
3727 assert sizeof(BStruct2) == 2 + sizeof(BLong)
3728 assert alignof(BStruct2) == 2
3729
3730 def test_packed_with_bitfields():
3731 if sys.platform == "win32":
3732 skip("testing gcc behavior")
3733 BLong = new_primitive_type("long")
3734 BChar = new_primitive_type("char")
3735 BStruct = new_struct_type("struct foo")
3736 pytest.raises(NotImplementedError,
3737 complete_struct_or_union,
3738 BStruct, [('a1', BLong, 30),
3739 ('a2', BChar, 5)],
3740 None, -1, -1, SF_PACKED)
3741
3742 def test_from_buffer():
3743 import array
3744 a = array.array('H', [10000, 20000, 30000])
3745 BChar = new_primitive_type("char")
3746 BCharP = new_pointer_type(BChar)
3747 BCharA = new_array_type(BCharP, None)
3748 c = from_buffer(BCharA, a)
3749 assert typeof(c) is BCharA
3750 assert len(c) == 6
3751 assert repr(c) == "<cdata 'char[]' buffer len 6 from 'array.array' object>"
3752 p = new_pointer_type(new_primitive_type("unsigned short"))
3753 cast(p, c)[1] += 500
3754 assert list(a) == [10000, 20500, 30000]
3755
3756 def test_from_buffer_not_str_unicode():
3757 BChar = new_primitive_type("char")
3758 BCharP = new_pointer_type(BChar)
3759 BCharA = new_array_type(BCharP, None)
3760 p1 = from_buffer(BCharA, b"foo")
3761 assert p1 == from_buffer(BCharA, b"foo")
3762 import gc; gc.collect()
3763 assert p1 == from_buffer(BCharA, b"foo")
3764 pytest.raises(TypeError, from_buffer, BCharA, u+"foo")
3765 try:
3766 from __builtin__ import buffer
3767 except ImportError:
3768 pass
3769 else:
3770 # Python 2 only
3771 contents = from_buffer(BCharA, buffer(b"foo"))
3772 assert len(contents) == len(p1)
3773 for i in range(len(contents)):
3774 assert contents[i] == p1[i]
3775 p4 = buffer(u+"foo")
3776 contents = from_buffer(BCharA, buffer(u+"foo"))
3777 assert len(contents) == len(p4)
3778 for i in range(len(contents)):
3779 assert contents[i] == p4[i]
3780 try:
3781 from __builtin__ import memoryview
3782 except ImportError:
3783 pass
3784 else:
3785 contents = from_buffer(BCharA, memoryview(b"foo"))
3786 assert len(contents) == len(p1)
3787 for i in range(len(contents)):
3788 assert contents[i] == p1[i]
3789
3790
3791 def test_from_buffer_bytearray():
3792 a = bytearray(b"xyz")
3793 BChar = new_primitive_type("char")
3794 BCharP = new_pointer_type(BChar)
3795 BCharA = new_array_type(BCharP, None)
3796 p = from_buffer(BCharA, a)
3797 assert typeof(p) is BCharA
3798 assert len(p) == 3
3799 assert repr(p) == "<cdata 'char[]' buffer len 3 from 'bytearray' object>"
3800 assert p[2] == b"z"
3801 p[2] = b"."
3802 assert a[2] == ord(".")
3803 a[2] = ord("?")
3804 assert p[2] == b"?"
3805
3806 def test_from_buffer_more_cases():
3807 try:
3808 from _cffi_backend import _testbuff
3809 except ImportError:
3810 skip("not for pypy")
3811 BChar = new_primitive_type("char")
3812 BCharP = new_pointer_type(BChar)
3813 BCharA = new_array_type(BCharP, None)
3814 #
3815 def check1(bufobj, expected):
3816 c = from_buffer(BCharA, bufobj)
3817 assert typeof(c) is BCharA
3818 if sys.version_info >= (3,):
3819 expected = [bytes(c, "ascii") for c in expected]
3820 assert list(c) == list(expected)
3821 #
3822 def check(methods, expected, expected_for_memoryview=None):
3823 if sys.version_info >= (3,):
3824 if methods <= 7:
3825 return
3826 if expected_for_memoryview is not None:
3827 expected = expected_for_memoryview
3828 class X(object):
3829 pass
3830 _testbuff(X, methods)
3831 bufobj = X()
3832 check1(bufobj, expected)
3833 try:
3834 from __builtin__ import buffer
3835 bufobjb = buffer(bufobj)
3836 except (TypeError, ImportError):
3837 pass
3838 else:
3839 check1(bufobjb, expected)
3840 try:
3841 bufobjm = memoryview(bufobj)
3842 except (TypeError, NameError):
3843 pass
3844 else:
3845 check1(bufobjm, expected_for_memoryview or expected)
3846 #
3847 check(1, "RDB")
3848 check(2, "WRB")
3849 check(4, "CHB")
3850 check(8, "GTB")
3851 check(16, "ROB")
3852 #
3853 check(1 | 2, "RDB")
3854 check(1 | 4, "RDB")
3855 check(2 | 4, "CHB")
3856 check(1 | 8, "RDB", "GTB")
3857 check(1 | 16, "RDB", "ROB")
3858 check(2 | 8, "WRB", "GTB")
3859 check(2 | 16, "WRB", "ROB")
3860 check(4 | 8, "CHB", "GTB")
3861 check(4 | 16, "CHB", "ROB")
3862
3863 def test_from_buffer_require_writable():
3864 BChar = new_primitive_type("char")
3865 BCharP = new_pointer_type(BChar)
3866 BCharA = new_array_type(BCharP, None)
3867 p1 = from_buffer(BCharA, b"foo", False)
3868 assert p1 == from_buffer(BCharA, b"foo", False)
3869 pytest.raises((TypeError, BufferError), from_buffer, BCharA, b"foo", True)
3870 ba = bytearray(b"foo")
3871 p1 = from_buffer(BCharA, ba, True)
3872 p1[0] = b"g"
3873 assert ba == b"goo"
3874
3875 def test_from_buffer_types():
3876 BInt = new_primitive_type("int")
3877 BIntP = new_pointer_type(BInt)
3878 BIntA = new_array_type(BIntP, None)
3879 lst = [-12345678, 87654321, 489148]
3880 bytestring = bytearray(buffer(newp(BIntA, lst))[:] + b'XYZ')
3881 lst2 = lst + [42, -999999999]
3882 bytestring2 = bytearray(buffer(newp(BIntA, lst2))[:] + b'XYZ')
3883 #
3884 p1 = from_buffer(BIntA, bytestring) # int[]
3885 assert typeof(p1) is BIntA
3886 assert len(p1) == 3
3887 assert p1[0] == lst[0]
3888 assert p1[1] == lst[1]
3889 assert p1[2] == lst[2]
3890 with pytest.raises(IndexError):
3891 p1[3]
3892 with pytest.raises(IndexError):
3893 p1[-1]
3894 #
3895 pytest.raises(TypeError, from_buffer, BInt, bytestring)
3896 #
3897 p2 = from_buffer(BIntP, bytestring) # int *
3898 assert p2 == p1 or 'PY_DOT_PY' in globals()
3899 # note: on py.py ^^^, bytearray buffers are not emulated well enough
3900 assert typeof(p2) is BIntP
3901 assert p2[0] == lst[0]
3902 assert p2[1] == lst[1]
3903 assert p2[2] == lst[2]
3904 # hopefully does not crash, but doesn't raise an exception:
3905 p2[3]
3906 p2[-1]
3907 # not enough data even for one, but this is not enforced:
3908 from_buffer(BIntP, b"")
3909 #
3910 BIntA2 = new_array_type(BIntP, 2)
3911 p2 = from_buffer(BIntA2, bytestring) # int[2]
3912 assert typeof(p2) is BIntA2
3913 assert len(p2) == 2
3914 assert p2[0] == lst[0]
3915 assert p2[1] == lst[1]
3916 with pytest.raises(IndexError):
3917 p2[2]
3918 with pytest.raises(IndexError):
3919 p2[-1]
3920 assert p2 == p1 or 'PY_DOT_PY' in globals()
3921 #
3922 BIntA4 = new_array_type(BIntP, 4) # int[4]: too big
3923 pytest.raises(ValueError, from_buffer, BIntA4, bytestring)
3924 #
3925 BStruct = new_struct_type("foo")
3926 complete_struct_or_union(BStruct, [('a1', BInt, -1),
3927 ('a2', BInt, -1)])
3928 BStructP = new_pointer_type(BStruct)
3929 BStructA = new_array_type(BStructP, None)
3930 p1 = from_buffer(BStructA, bytestring2) # struct[]
3931 assert len(p1) == 2
3932 assert typeof(p1) is BStructA
3933 assert p1[0].a1 == lst2[0]
3934 assert p1[0].a2 == lst2[1]
3935 assert p1[1].a1 == lst2[2]
3936 assert p1[1].a2 == lst2[3]
3937 with pytest.raises(IndexError):
3938 p1[2]
3939 with pytest.raises(IndexError):
3940 p1[-1]
3941 assert repr(p1) == "<cdata 'foo[]' buffer len 2 from 'bytearray' object>"
3942 #
3943 p2 = from_buffer(BStructP, bytestring2) # 'struct *'
3944 assert p2 == p1 or 'PY_DOT_PY' in globals()
3945 assert typeof(p2) is BStructP
3946 assert p2.a1 == lst2[0]
3947 assert p2.a2 == lst2[1]
3948 assert p2[0].a1 == lst2[0]
3949 assert p2[0].a2 == lst2[1]
3950 assert p2[1].a1 == lst2[2]
3951 assert p2[1].a2 == lst2[3]
3952 # does not crash:
3953 p2[2]
3954 p2[-1]
3955 # not enough data even for one, but this is not enforced:
3956 from_buffer(BStructP, b"")
3957 from_buffer(BStructP, b"1234567")
3958 #
3959 release(p1)
3960 assert repr(p1) == "<cdata 'foo[]' buffer RELEASED>"
3961 #
3962 BEmptyStruct = new_struct_type("empty")
3963 complete_struct_or_union(BEmptyStruct, [], Ellipsis, 0)
3964 assert sizeof(BEmptyStruct) == 0
3965 BEmptyStructP = new_pointer_type(BEmptyStruct)
3966 BEmptyStructA = new_array_type(BEmptyStructP, None)
3967 pytest.raises(ZeroDivisionError, from_buffer, # empty[]
3968 BEmptyStructA, bytestring)
3969 #
3970 BEmptyStructA5 = new_array_type(BEmptyStructP, 5)
3971 p1 = from_buffer(BEmptyStructA5, bytestring) # struct empty[5]
3972 assert typeof(p1) is BEmptyStructA5
3973 assert len(p1) == 5
3974 assert (cast(BIntP, p1) == from_buffer(BIntA, bytestring)
3975 or 'PY_DOT_PY' in globals())
3976 #
3977 BVarStruct = new_struct_type("varfoo")
3978 BVarStructP = new_pointer_type(BVarStruct)
3979 complete_struct_or_union(BVarStruct, [('a1', BInt, -1),
3980 ('va', BIntA, -1)])
3981 with pytest.raises(TypeError):
3982 from_buffer(BVarStruct, bytestring)
3983 pv = from_buffer(BVarStructP, bytestring) # varfoo *
3984 assert pv.a1 == lst[0]
3985 assert pv.va[0] == lst[1]
3986 assert pv.va[1] == lst[2]
3987 assert sizeof(pv[0]) == 1 * size_of_int()
3988 with pytest.raises(TypeError):
3989 len(pv.va)
3990 # hopefully does not crash, but doesn't raise an exception:
3991 pv.va[2]
3992 pv.va[-1]
3993 # not enough data even for one, but this is not enforced:
3994 from_buffer(BVarStructP, b"")
3995 assert repr(pv) == "<cdata 'varfoo *' buffer from 'bytearray' object>"
3996 assert repr(pv[0]).startswith("<cdata 'varfoo &' ")
3997 #
3998 release(pv)
3999 assert repr(pv) == "<cdata 'varfoo *' buffer RELEASED>"
4000 assert repr(pv[0]).startswith("<cdata 'varfoo &' ")
4001 #
4002 pv = from_buffer(BVarStructP, bytestring) # make a fresh one
4003 with pytest.raises(ValueError):
4004 release(pv[0])
4005
4006 def test_issue483():
4007 BInt = new_primitive_type("int")
4008 BIntP = new_pointer_type(BInt)
4009 BIntA = new_array_type(BIntP, None)
4010 lst = list(range(25))
4011 bytestring = bytearray(buffer(newp(BIntA, lst))[:] + b'XYZ')
4012 p1 = from_buffer(BIntA, bytestring) # int[]
4013 assert len(buffer(p1)) == 25 * size_of_int()
4014 assert sizeof(p1) == 25 * size_of_int()
4015 #
4016 p2 = from_buffer(BIntP, bytestring)
4017 assert sizeof(p2) == size_of_ptr()
4018 assert len(buffer(p2)) == size_of_int() # first element only, by default
4019
4020 def test_memmove():
4021 Short = new_primitive_type("short")
4022 ShortA = new_array_type(new_pointer_type(Short), None)
4023 Char = new_primitive_type("char")
4024 CharA = new_array_type(new_pointer_type(Char), None)
4025 p = newp(ShortA, [-1234, -2345, -3456, -4567, -5678])
4026 memmove(p, p + 1, 4)
4027 assert list(p) == [-2345, -3456, -3456, -4567, -5678]
4028 p[2] = 999
4029 memmove(p + 2, p, 6)
4030 assert list(p) == [-2345, -3456, -2345, -3456, 999]
4031 memmove(p + 4, newp(CharA, b"\x71\x72"), 2)
4032 if sys.byteorder == 'little':
4033 assert list(p) == [-2345, -3456, -2345, -3456, 0x7271]
4034 else:
4035 assert list(p) == [-2345, -3456, -2345, -3456, 0x7172]
4036
4037 def test_memmove_buffer():
4038 import array
4039 Short = new_primitive_type("short")
4040 ShortA = new_array_type(new_pointer_type(Short), None)
4041 a = array.array('H', [10000, 20000, 30000])
4042 p = newp(ShortA, 5)
4043 memmove(p, a, 6)
4044 assert list(p) == [10000, 20000, 30000, 0, 0]
4045 memmove(p + 1, a, 6)
4046 assert list(p) == [10000, 10000, 20000, 30000, 0]
4047 b = array.array('h', [-1000, -2000, -3000])
4048 memmove(b, a, 4)
4049 assert b.tolist() == [10000, 20000, -3000]
4050 assert a.tolist() == [10000, 20000, 30000]
4051 p[0] = 999
4052 p[1] = 998
4053 p[2] = 997
4054 p[3] = 996
4055 p[4] = 995
4056 memmove(b, p, 2)
4057 assert b.tolist() == [999, 20000, -3000]
4058 memmove(b, p + 2, 4)
4059 assert b.tolist() == [997, 996, -3000]
4060 p[2] = -p[2]
4061 p[3] = -p[3]
4062 memmove(b, p + 2, 6)
4063 assert b.tolist() == [-997, -996, 995]
4064
4065 def test_memmove_readonly_readwrite():
4066 SignedChar = new_primitive_type("signed char")
4067 SignedCharA = new_array_type(new_pointer_type(SignedChar), None)
4068 p = newp(SignedCharA, 5)
4069 memmove(p, b"abcde", 3)
4070 assert list(p) == [ord("a"), ord("b"), ord("c"), 0, 0]
4071 memmove(p, bytearray(b"ABCDE"), 2)
4072 assert list(p) == [ord("A"), ord("B"), ord("c"), 0, 0]
4073 pytest.raises((TypeError, BufferError), memmove, b"abcde", p, 3)
4074 ba = bytearray(b"xxxxx")
4075 memmove(dest=ba, src=p, n=3)
4076 assert ba == bytearray(b"ABcxx")
4077 memmove(ba, b"EFGH", 4)
4078 assert ba == bytearray(b"EFGHx")
4079
4080 def test_memmove_sign_check():
4081 SignedChar = new_primitive_type("signed char")
4082 SignedCharA = new_array_type(new_pointer_type(SignedChar), None)
4083 p = newp(SignedCharA, 5)
4084 pytest.raises(ValueError, memmove, p, p + 1, -1) # not segfault
4085
4086 def test_memmove_bad_cdata():
4087 BInt = new_primitive_type("int")
4088 p = cast(BInt, 42)
4089 pytest.raises(TypeError, memmove, p, bytearray(b'a'), 1)
4090 pytest.raises(TypeError, memmove, bytearray(b'a'), p, 1)
4091
4092 def test_dereference_null_ptr():
4093 BInt = new_primitive_type("int")
4094 BIntPtr = new_pointer_type(BInt)
4095 p = cast(BIntPtr, 0)
4096 with pytest.raises(RuntimeError):
4097 p[0]
4098 with pytest.raises(RuntimeError):
4099 p[0] = 42
4100 with pytest.raises(RuntimeError):
4101 p[42]
4102 with pytest.raises(RuntimeError):
4103 p[42] = -1
4104
4105 def test_mixup():
4106 BStruct1 = new_struct_type("foo")
4107 BStruct2 = new_struct_type("foo") # <= same name as BStruct1
4108 BStruct3 = new_struct_type("bar")
4109 BStruct1Ptr = new_pointer_type(BStruct1)
4110 BStruct2Ptr = new_pointer_type(BStruct2)
4111 BStruct3Ptr = new_pointer_type(BStruct3)
4112 BStruct1PtrPtr = new_pointer_type(BStruct1Ptr)
4113 BStruct2PtrPtr = new_pointer_type(BStruct2Ptr)
4114 BStruct3PtrPtr = new_pointer_type(BStruct3Ptr)
4115 pp1 = newp(BStruct1PtrPtr)
4116 pp2 = newp(BStruct2PtrPtr)
4117 pp3 = newp(BStruct3PtrPtr)
4118 pp1[0] = pp1[0]
4119 with pytest.raises(TypeError) as e:
4120 pp3[0] = pp1[0]
4121 assert str(e.value).startswith("initializer for ctype 'bar *' must be a ")
4122 assert str(e.value).endswith(", not cdata 'foo *'")
4123 with pytest.raises(TypeError) as e:
4124 pp2[0] = pp1[0]
4125 assert str(e.value) == ("initializer for ctype 'foo *' appears indeed to "
4126 "be 'foo *', but the types are different (check "
4127 "that you are not e.g. mixing up different ffi "
4128 "instances)")
4129
4130 def test_stdcall_function_type():
4131 assert FFI_CDECL == FFI_DEFAULT_ABI
4132 try:
4133 stdcall = FFI_STDCALL
4134 except NameError:
4135 stdcall = FFI_DEFAULT_ABI
4136 BInt = new_primitive_type("int")
4137 BFunc = new_function_type((BInt, BInt), BInt, False, stdcall)
4138 if stdcall != FFI_DEFAULT_ABI:
4139 assert repr(BFunc) == "<ctype 'int(__stdcall *)(int, int)'>"
4140 else:
4141 assert repr(BFunc) == "<ctype 'int(*)(int, int)'>"
4142
4143 def test_get_common_types():
4144 d = {}
4145 _get_common_types(d)
4146 assert d['bool'] == '_Bool'
4147
4148 def test_unpack():
4149 BChar = new_primitive_type("char")
4150 BArray = new_array_type(new_pointer_type(BChar), 10) # char[10]
4151 p = newp(BArray, b"abc\x00def")
4152 p0 = p
4153 assert unpack(p, 10) == b"abc\x00def\x00\x00\x00"
4154 assert unpack(p+1, 5) == b"bc\x00de"
4155
4156 for typename in ["wchar_t", "char16_t", "char32_t"]:
4157 BWChar = new_primitive_type(typename)
4158 BArray = new_array_type(new_pointer_type(BWChar), 10) # wchar_t[10]
4159 p = newp(BArray, u"abc\x00def")
4160 assert unpack(p, 10) == u"abc\x00def\x00\x00\x00"
4161
4162 for typename, samples in [
4163 ("uint8_t", [0, 2**8-1]),
4164 ("uint16_t", [0, 2**16-1]),
4165 ("uint32_t", [0, 2**32-1]),
4166 ("uint64_t", [0, 2**64-1]),
4167 ("int8_t", [-2**7, 2**7-1]),
4168 ("int16_t", [-2**15, 2**15-1]),
4169 ("int32_t", [-2**31, 2**31-1]),
4170 ("int64_t", [-2**63, 2**63-1]),
4171 ("_Bool", [False, True]),
4172 ("float", [0.0, 10.5]),
4173 ("double", [12.34, 56.78]),
4174 ]:
4175 BItem = new_primitive_type(typename)
4176 BArray = new_array_type(new_pointer_type(BItem), 10)
4177 p = newp(BArray, samples)
4178 result = unpack(p, len(samples))
4179 assert result == samples
4180 for i in range(len(samples)):
4181 assert result[i] == p[i] and type(result[i]) is type(p[i])
4182 assert (type(result[i]) is bool) == (type(samples[i]) is bool)
4183 #
4184 BInt = new_primitive_type("int")
4185 pytest.raises(TypeError, unpack, p)
4186 pytest.raises(TypeError, unpack, b"foobar", 6)
4187 pytest.raises(TypeError, unpack, cast(BInt, 42), 1)
4188 #
4189 BPtr = new_pointer_type(BInt)
4190 random_ptr = cast(BPtr, -424344)
4191 other_ptr = cast(BPtr, 54321)
4192 BArray = new_array_type(new_pointer_type(BPtr), None)
4193 lst = unpack(newp(BArray, [random_ptr, other_ptr]), 2)
4194 assert lst == [random_ptr, other_ptr]
4195 #
4196 BFunc = new_function_type((BInt, BInt), BInt, False)
4197 BFuncPtr = new_pointer_type(BFunc)
4198 lst = unpack(newp(new_array_type(BFuncPtr, None), 2), 2)
4199 assert len(lst) == 2
4200 assert not lst[0] and not lst[1]
4201 assert typeof(lst[0]) is BFunc
4202 #
4203 BStruct = new_struct_type("foo")
4204 BStructPtr = new_pointer_type(BStruct)
4205 e = pytest.raises(ValueError, unpack, cast(BStructPtr, 42), 5)
4206 assert str(e.value) == "'foo *' points to items of unknown size"
4207 complete_struct_or_union(BStruct, [('a1', BInt, -1),
4208 ('a2', BInt, -1)])
4209 array_of_structs = newp(new_array_type(BStructPtr, None), [[4,5], [6,7]])
4210 lst = unpack(array_of_structs, 2)
4211 assert typeof(lst[0]) is BStruct
4212 assert lst[0].a1 == 4 and lst[1].a2 == 7
4213 #
4214 pytest.raises(RuntimeError, unpack, cast(new_pointer_type(BChar), 0), 0)
4215 pytest.raises(RuntimeError, unpack, cast(new_pointer_type(BChar), 0), 10)
4216 #
4217 pytest.raises(ValueError, unpack, p0, -1)
4218 pytest.raises(ValueError, unpack, p, -1)
4219
4220 def test_cdata_dir():
4221 BInt = new_primitive_type("int")
4222 p = cast(BInt, 42)
4223 check_dir(p, [])
4224 p = newp(new_array_type(new_pointer_type(BInt), None), 5)
4225 check_dir(p, [])
4226 BStruct = new_struct_type("foo")
4227 p = cast(new_pointer_type(BStruct), 0)
4228 check_dir(p, []) # opaque
4229 complete_struct_or_union(BStruct, [('a2', BInt, -1),
4230 ('a1', BInt, -1)])
4231 check_dir(p, ['a1', 'a2']) # always sorted
4232 p = newp(new_pointer_type(BStruct), None)
4233 check_dir(p, ['a1', 'a2'])
4234 check_dir(p[0], ['a1', 'a2'])
4235 pp = newp(new_pointer_type(new_pointer_type(BStruct)), p)
4236 check_dir(pp, [])
4237 check_dir(pp[0], ['a1', 'a2'])
4238 check_dir(pp[0][0], ['a1', 'a2'])
4239
4240 def test_char_pointer_conversion():
4241 import warnings
4242 assert __version__.startswith("1."), (
4243 "the warning will be an error if we ever release cffi 2.x")
4244 BCharP = new_pointer_type(new_primitive_type("char"))
4245 BIntP = new_pointer_type(new_primitive_type("int"))
4246 BVoidP = new_pointer_type(new_void_type())
4247 BUCharP = new_pointer_type(new_primitive_type("unsigned char"))
4248 z1 = cast(BCharP, 0)
4249 z2 = cast(BIntP, 0)
4250 z3 = cast(BVoidP, 0)
4251 z4 = cast(BUCharP, 0)
4252 with warnings.catch_warnings(record=True) as w:
4253 warnings.simplefilter("always")
4254 newp(new_pointer_type(BIntP), z1) # warn
4255 assert len(w) == 1
4256 newp(new_pointer_type(BVoidP), z1) # fine
4257 assert len(w) == 1
4258 newp(new_pointer_type(BCharP), z2) # warn
4259 assert len(w) == 2
4260 newp(new_pointer_type(BVoidP), z2) # fine
4261 assert len(w) == 2
4262 newp(new_pointer_type(BCharP), z3) # fine
4263 assert len(w) == 2
4264 newp(new_pointer_type(BIntP), z3) # fine
4265 assert len(w) == 2
4266 newp(new_pointer_type(BCharP), z4) # fine (ignore signedness here)
4267 assert len(w) == 2
4268 newp(new_pointer_type(BUCharP), z1) # fine (ignore signedness here)
4269 assert len(w) == 2
4270 newp(new_pointer_type(BUCharP), z3) # fine
4271 assert len(w) == 2
4272 # check that the warnings are associated with lines in this file
4273 assert w[1].lineno == w[0].lineno + 4
4274
4275 def test_primitive_comparison():
4276 def assert_eq(a, b):
4277 assert (a == b) is True
4278 assert (b == a) is True
4279 assert (a != b) is False
4280 assert (b != a) is False
4281 assert (a < b) is False
4282 assert (a <= b) is True
4283 assert (a > b) is False
4284 assert (a >= b) is True
4285 assert (b < a) is False
4286 assert (b <= a) is True
4287 assert (b > a) is False
4288 assert (b >= a) is True
4289 assert hash(a) == hash(b)
4290 def assert_lt(a, b, check_hash=True):
4291 assert (a == b) is False
4292 assert (b == a) is False
4293 assert (a != b) is True
4294 assert (b != a) is True
4295 assert (a < b) is True
4296 assert (a <= b) is True
4297 assert (a > b) is False
4298 assert (a >= b) is False
4299 assert (b < a) is False
4300 assert (b <= a) is False
4301 assert (b > a) is True
4302 assert (b >= a) is True
4303 if check_hash:
4304 assert hash(a) != hash(b) # (or at least, it is unlikely)
4305 def assert_gt(a, b, check_hash=True):
4306 assert_lt(b, a, check_hash)
4307 def assert_ne(a, b):
4308 assert (a == b) is False
4309 assert (b == a) is False
4310 assert (a != b) is True
4311 assert (b != a) is True
4312 if strict_compare:
4313 with pytest.raises(TypeError): a < b
4314 with pytest.raises(TypeError): a <= b
4315 with pytest.raises(TypeError): a > b
4316 with pytest.raises(TypeError): a >= b
4317 with pytest.raises(TypeError): b < a
4318 with pytest.raises(TypeError): b <= a
4319 with pytest.raises(TypeError): b > a
4320 with pytest.raises(TypeError): b >= a
4321 elif a < b:
4322 assert_lt(a, b)
4323 else:
4324 assert_lt(b, a)
4325 assert_eq(5, 5)
4326 assert_lt(3, 5)
4327 assert_ne('5', 5)
4328 #
4329 t1 = new_primitive_type("char")
4330 t2 = new_primitive_type("int")
4331 t3 = new_primitive_type("unsigned char")
4332 t4 = new_primitive_type("unsigned int")
4333 t5 = new_primitive_type("float")
4334 t6 = new_primitive_type("double")
4335 assert_eq(cast(t1, 65), b'A')
4336 assert_lt(cast(t1, 64), b'\x99')
4337 assert_gt(cast(t1, 200), b'A')
4338 assert_ne(cast(t1, 65), 65)
4339 assert_eq(cast(t2, -25), -25)
4340 assert_lt(cast(t2, -25), -24)
4341 assert_gt(cast(t2, -25), -26)
4342 assert_eq(cast(t3, 65), 65)
4343 assert_ne(cast(t3, 65), b'A')
4344 assert_ne(cast(t3, 65), cast(t1, 65))
4345 assert_gt(cast(t4, -1), -1, check_hash=False)
4346 assert_gt(cast(t4, -1), cast(t2, -1), check_hash=False)
4347 assert_gt(cast(t4, -1), 99999)
4348 assert_eq(cast(t4, -1), 256 ** size_of_int() - 1)
4349 assert_eq(cast(t5, 3.0), 3)
4350 assert_eq(cast(t5, 3.5), 3.5)
4351 assert_lt(cast(t5, 3.3), 3.3) # imperfect rounding
4352 assert_eq(cast(t6, 3.3), 3.3)
4353 assert_eq(cast(t5, 3.5), cast(t6, 3.5))
4354 assert_lt(cast(t5, 3.1), cast(t6, 3.1)) # imperfect rounding
4355 assert_eq(cast(t5, 7.0), cast(t3, 7))
4356 assert_lt(cast(t5, 3.1), 3.101)
4357 assert_gt(cast(t5, 3.1), 3)
4358
4359 def test_explicit_release_new():
4360 # release() on a ffi.new() object has no effect on CPython, but
4361 # really releases memory on PyPy. We can't test that effect
4362 # though, because a released cdata is not marked.
4363 BIntP = new_pointer_type(new_primitive_type("int"))
4364 p = newp(BIntP)
4365 p[0] = 42
4366 with pytest.raises(IndexError):
4367 p[1]
4368 release(p)
4369 # here, reading p[0] might give garbage or segfault...
4370 release(p) # no effect
4371 #
4372 BStruct = new_struct_type("struct foo")
4373 BStructP = new_pointer_type(BStruct)
4374 complete_struct_or_union(BStruct, [('p', BIntP, -1)])
4375 pstruct = newp(BStructP)
4376 assert pstruct.p == cast(BIntP, 0)
4377 release(pstruct)
4378 # here, reading pstruct.p might give garbage or segfault...
4379 release(pstruct) # no effect
4380
4381 def test_explicit_release_new_contextmgr():
4382 BIntP = new_pointer_type(new_primitive_type("int"))
4383 with newp(BIntP) as p:
4384 p[0] = 42
4385 assert p[0] == 42
4386 # here, reading p[0] might give garbage or segfault...
4387 release(p) # no effect
4388
4389 def test_explicit_release_badtype():
4390 BIntP = new_pointer_type(new_primitive_type("int"))
4391 p = cast(BIntP, 12345)
4392 pytest.raises(ValueError, release, p)
4393 pytest.raises(ValueError, release, p)
4394 BStruct = new_struct_type("struct foo")
4395 BStructP = new_pointer_type(BStruct)
4396 complete_struct_or_union(BStruct, [('p', BIntP, -1)])
4397 pstruct = newp(BStructP)
4398 pytest.raises(ValueError, release, pstruct[0])
4399
4400 def test_explicit_release_badtype_contextmgr():
4401 BIntP = new_pointer_type(new_primitive_type("int"))
4402 p = cast(BIntP, 12345)
4403 with pytest.raises(ValueError):
4404 with p:
4405 pass
4406 with pytest.raises(ValueError):
4407 with p:
4408 pass
4409
4410 def test_explicit_release_gc():
4411 BIntP = new_pointer_type(new_primitive_type("int"))
4412 seen = []
4413 intp1 = newp(BIntP, 12345)
4414 p1 = cast(BIntP, intp1)
4415 p = gcp(p1, seen.append)
4416 assert seen == []
4417 release(p)
4418 assert seen == [p1]
4419 assert p1[0] == 12345
4420 assert p[0] == 12345 # true so far, but might change to raise RuntimeError
4421 release(p) # no effect
4422
4423 def test_explicit_release_gc_contextmgr():
4424 BIntP = new_pointer_type(new_primitive_type("int"))
4425 seen = []
4426 intp1 = newp(BIntP, 12345)
4427 p1 = cast(BIntP, intp1)
4428 p = gcp(p1, seen.append)
4429 with p:
4430 assert p[0] == 12345
4431 assert seen == []
4432 assert seen == [p1]
4433 assert p1[0] == 12345
4434 assert p[0] == 12345 # true so far, but might change to raise RuntimeError
4435 release(p) # no effect
4436
4437 def test_explicit_release_from_buffer():
4438 a = bytearray(b"xyz")
4439 BChar = new_primitive_type("char")
4440 BCharP = new_pointer_type(BChar)
4441 BCharA = new_array_type(BCharP, None)
4442 p = from_buffer(BCharA, a)
4443 assert p[2] == b"z"
4444 assert repr(p) == "<cdata 'char[]' buffer len 3 from 'bytearray' object>"
4445 release(p)
4446 assert p[2] == b"z" # true so far, but might change to raise RuntimeError
4447 assert repr(p) == "<cdata 'char[]' buffer RELEASED>"
4448 release(p) # no effect
4449
4450 def test_explicit_release_from_buffer_contextmgr():
4451 a = bytearray(b"xyz")
4452 BChar = new_primitive_type("char")
4453 BCharP = new_pointer_type(BChar)
4454 BCharA = new_array_type(BCharP, None)
4455 p = from_buffer(BCharA, a)
4456 with p:
4457 assert p[2] == b"z"
4458 assert p[2] == b"z" # true so far, but might change to raise RuntimeError
4459 assert repr(p) == "<cdata 'char[]' buffer RELEASED>"
4460 release(p) # no effect
4461
4462 def test_explicit_release_bytearray_on_cpython():
4463 if '__pypy__' in sys.builtin_module_names:
4464 skip("pypy's bytearray are never locked")
4465 a = bytearray(b"xyz")
4466 BChar = new_primitive_type("char")
4467 BCharP = new_pointer_type(BChar)
4468 BCharA = new_array_type(BCharP, None)
4469 a += b't' * 10
4470 p = from_buffer(BCharA, a)
4471 with pytest.raises(BufferError):
4472 a += b'u' * 100
4473 release(p)
4474 a += b'v' * 100
4475 release(p) # no effect
4476 a += b'w' * 1000
4477 assert a == bytearray(b"xyz" + b't' * 10 + b'v' * 100 + b'w' * 1000)
4478
4479 def test_int_doesnt_give_bool():
4480 BBool = new_primitive_type("_Bool")
4481 x = int(cast(BBool, 42))
4482 assert type(x) is int and x == 1
4483 x = long(cast(BBool, 42))
4484 assert type(x) is long and x == 1
4485 with pytest.raises(TypeError):
4486 float(cast(BBool, 42))
4487 with pytest.raises(TypeError):
4488 complex(cast(BBool, 42))
4489
4490 def test_cannot_call_null_function_pointer():
4491 BInt = new_primitive_type("int")
4492 BFunc = new_function_type((BInt, BInt), BInt, False)
4493 f = cast(BFunc, 0)
4494 with pytest.raises(RuntimeError):
4495 f(40, 2)
4496
4497 def test_huge_structure():
4498 BChar = new_primitive_type("char")
4499 BArray = new_array_type(new_pointer_type(BChar), sys.maxsize)
4500 assert sizeof(BArray) == sys.maxsize
4501 BStruct = new_struct_type("struct foo")
4502 complete_struct_or_union(BStruct, [('a1', BArray, -1)])
4503 assert sizeof(BStruct) == sys.maxsize
4504
4505 def test_get_types():
4506 import _cffi_backend
4507 CData, CType = _get_types()
4508 assert CData is _cffi_backend._CDataBase
4509 assert CType is _cffi_backend.CType
4510
4511 def test_type_available_with_correct_names():
4512 import _cffi_backend
4513 check_names = [
4514 'CType',
4515 'CField',
4516 'CLibrary',
4517 '_CDataBase',
4518 'FFI',
4519 'Lib',
4520 'buffer',
4521 ]
4522 if '__pypy__' in sys.builtin_module_names:
4523 check_names += [
4524 '__CData_iterator',
4525 '__FFIGlobSupport',
4526 '__FFIAllocator',
4527 '__FFIFunctionWrapper',
4528 ]
4529 else:
4530 check_names += [
4531 '__CDataOwn',
4532 '__CDataOwnGC',
4533 '__CDataFromBuf',
4534 '__CDataGCP',
4535 '__CData_iterator',
4536 '__FFIGlobSupport',
4537 ]
4538 for name in check_names:
4539 tp = getattr(_cffi_backend, name)
4540 assert isinstance(tp, type)
4541 assert (tp.__module__, tp.__name__) == ('_cffi_backend', name)
4542
4543 def test_unaligned_types():
4544 BByteArray = new_array_type(
4545 new_pointer_type(new_primitive_type("unsigned char")), None)
4546 pbuf = newp(BByteArray, 40)
4547 buf = buffer(pbuf)
4548 #
4549 for name in ['short', 'int', 'long', 'long long', 'float', 'double',
4550 '_cffi_float_complex_t', '_cffi_double_complex_t']:
4551 p = new_primitive_type(name)
4552 if name.endswith('_complex_t'):
4553 num = cast(p, 1.23 - 4.56j)
4554 else:
4555 num = cast(p, 0x0123456789abcdef)
4556 size = sizeof(p)
4557 buf[0:40] = b"\x00" * 40
4558 pbuf1 = cast(new_pointer_type(p), pbuf + 1)
4559 pbuf1[0] = num
4560 assert pbuf1[0] == num
4561 assert buf[0] == b'\x00'
4562 assert buf[1 + size] == b'\x00'