Debian Codegraph @

rpython/rlib/test/test_libffi.py

raw symbols SCIP
1 import gc
2 import os
3 import py
4
5 from rpython.rlib.rarithmetic import r_singlefloat, r_longlong, r_ulonglong
6 from rpython.rlib.test.test_clibffi import BaseFfiTest, make_struct_ffitype_e
7 from rpython.rtyper.lltypesystem import rffi, lltype
8 from rpython.rtyper.lltypesystem.ll2ctypes import ALLOCATED
9 from rpython.rtyper.llinterp import LLException
10 from rpython.translator import cdir
11 from rpython.rlib.libffi import (CDLL, ArgChain, types,
12 IS_32_BIT, IS_WIN64, array_getitem, array_setitem)
13 from rpython.rlib.libffi import (struct_getfield_int, struct_setfield_int,
14 struct_getfield_longlong, struct_setfield_longlong,
15 struct_getfield_float, struct_setfield_float,
16 struct_getfield_singlefloat, struct_setfield_singlefloat)
17
18 class TestLibffiMisc(BaseFfiTest):
19
20 CDLL = CDLL
21
22 def test_argchain(self):
23 chain = ArgChain()
24 assert chain.numargs == 0
25 chain2 = chain.arg(42)
26 assert chain2 is chain
27 assert chain.numargs == 1
28 intarg = chain.first
29 assert chain.last is intarg
30 assert intarg.intval == 42
31 chain.arg(123.45)
32 assert chain.numargs == 2
33 assert chain.first is intarg
34 assert intarg.next is chain.last
35 floatarg = intarg.next
36 assert floatarg.floatval == 123.45
37
38 def test_wrong_args(self):
39 # so far the test passes but for the wrong reason :-), i.e. because
40 # .arg() only supports integers and floats
41 chain = ArgChain()
42 x = lltype.malloc(lltype.GcStruct('xxx'))
43 y = lltype.malloc(lltype.GcArray(rffi.SIGNED), 3)
44 z = lltype.malloc(lltype.Array(rffi.SIGNED), 4, flavor='raw')
45 py.test.raises(TypeError, "chain.arg(x)")
46 py.test.raises(TypeError, "chain.arg(y)")
47 py.test.raises(TypeError, "chain.arg(z)")
48 lltype.free(z, flavor='raw')
49
50 def test_library_open(self):
51 lib = self.get_libc()
52 del lib
53 gc.collect()
54 assert not ALLOCATED
55
56 def test_library_get_func(self):
57 lib = self.get_libc()
58 ptr = lib.getpointer('fopen', [], types.void)
59 py.test.raises(KeyError, lib.getpointer, 'xxxxxxxxxxxxxxx', [], types.void)
60 del ptr
61 del lib
62 gc.collect()
63 assert not ALLOCATED
64
65 def test_struct_fields(self):
66 longsize = 4 if IS_32_BIT or IS_WIN64 else 8
67 POINT = lltype.Struct('POINT',
68 ('x', rffi.LONG),
69 ('y', rffi.SHORT),
70 ('z', rffi.VOIDP),
71 )
72 y_ofs = longsize
73 z_ofs = longsize*2
74 p = lltype.malloc(POINT, flavor='raw')
75 if IS_WIN64:
76 p.x = rffi.cast(rffi.LONG, 42)
77 else:
78 p.x = 42
79 p.y = rffi.cast(rffi.SHORT, -1)
80 p.z = rffi.cast(rffi.VOIDP, 0x1234)
81 addr = rffi.cast(rffi.VOIDP, p)
82 assert struct_getfield_int(types.slong, addr, 0) == 42
83 assert struct_getfield_int(types.sshort, addr, y_ofs) == -1
84 assert struct_getfield_int(types.pointer, addr, z_ofs) == 0x1234
85 #
86 struct_setfield_int(types.slong, addr, 0, 43)
87 struct_setfield_int(types.sshort, addr, y_ofs, 0x1234FFFE) # 0x1234 is masked out
88 struct_setfield_int(types.pointer, addr, z_ofs, 0x4321)
89 assert p.x == 43
90 assert p.y == -2
91 assert rffi.cast(rffi.LONG, p.z) == 0x4321
92 #
93 lltype.free(p, flavor='raw')
94
95 def test_array_fields(self):
96 POINT = lltype.Struct("POINT",
97 ("x", lltype.Float),
98 ("y", lltype.Float),
99 )
100 points = lltype.malloc(rffi.CArray(POINT), 2, flavor="raw")
101 points[0].x = 1.0
102 points[0].y = 2.0
103 points[1].x = 3.0
104 points[1].y = 4.0
105 points = rffi.cast(rffi.CArrayPtr(lltype.Char), points)
106 assert array_getitem(types.double, 16, points, 0, 0) == 1.0
107 assert array_getitem(types.double, 16, points, 0, 8) == 2.0
108 assert array_getitem(types.double, 16, points, 1, 0) == 3.0
109 assert array_getitem(types.double, 16, points, 1, 8) == 4.0
110 #
111 array_setitem(types.double, 16, points, 0, 0, 10.0)
112 array_setitem(types.double, 16, points, 0, 8, 20.0)
113 array_setitem(types.double, 16, points, 1, 0, 30.0)
114 array_setitem(types.double, 16, points, 1, 8, 40.0)
115 #
116 assert array_getitem(types.double, 16, points, 0, 0) == 10.0
117 assert array_getitem(types.double, 16, points, 0, 8) == 20.0
118 assert array_getitem(types.double, 16, points, 1, 0) == 30.0
119 assert array_getitem(types.double, 16, points, 1, 8) == 40.0
120 #
121 lltype.free(points, flavor="raw")
122
123
124 def test_struct_fields_longlong(self):
125 POINT = lltype.Struct('POINT',
126 ('x', rffi.LONGLONG),
127 ('y', rffi.ULONGLONG)
128 )
129 y_ofs = 8
130 p = lltype.malloc(POINT, flavor='raw')
131 p.x = r_longlong(123)
132 p.y = r_ulonglong(456)
133 addr = rffi.cast(rffi.VOIDP, p)
134 assert struct_getfield_longlong(types.slonglong, addr, 0) == 123
135 assert struct_getfield_longlong(types.ulonglong, addr, y_ofs) == 456
136 #
137 v = rffi.cast(lltype.SignedLongLong, r_ulonglong(9223372036854775808))
138 struct_setfield_longlong(types.slonglong, addr, 0, v)
139 struct_setfield_longlong(types.ulonglong, addr, y_ofs, r_longlong(-1))
140 assert p.x == -9223372036854775808
141 assert rffi.cast(lltype.UnsignedLongLong, p.y) == 18446744073709551615
142 #
143 lltype.free(p, flavor='raw')
144
145 def test_struct_fields_float(self):
146 POINT = lltype.Struct('POINT',
147 ('x', rffi.DOUBLE),
148 ('y', rffi.DOUBLE)
149 )
150 y_ofs = 8
151 p = lltype.malloc(POINT, flavor='raw')
152 p.x = 123.4
153 p.y = 567.8
154 addr = rffi.cast(rffi.VOIDP, p)
155 assert struct_getfield_float(types.double, addr, 0) == 123.4
156 assert struct_getfield_float(types.double, addr, y_ofs) == 567.8
157 #
158 struct_setfield_float(types.double, addr, 0, 321.0)
159 struct_setfield_float(types.double, addr, y_ofs, 876.5)
160 assert p.x == 321.0
161 assert p.y == 876.5
162 #
163 lltype.free(p, flavor='raw')
164
165 def test_struct_fields_singlefloat(self):
166 POINT = lltype.Struct('POINT',
167 ('x', rffi.FLOAT),
168 ('y', rffi.FLOAT)
169 )
170 y_ofs = 4
171 p = lltype.malloc(POINT, flavor='raw')
172 p.x = r_singlefloat(123.4)
173 p.y = r_singlefloat(567.8)
174 addr = rffi.cast(rffi.VOIDP, p)
175 assert struct_getfield_singlefloat(types.double, addr, 0) == r_singlefloat(123.4)
176 assert struct_getfield_singlefloat(types.double, addr, y_ofs) == r_singlefloat(567.8)
177 #
178 struct_setfield_singlefloat(types.double, addr, 0, r_singlefloat(321.0))
179 struct_setfield_singlefloat(types.double, addr, y_ofs, r_singlefloat(876.5))
180 assert p.x == r_singlefloat(321.0)
181 assert p.y == r_singlefloat(876.5)
182 #
183 lltype.free(p, flavor='raw')
184
185 def test_windll(self):
186 if os.name != 'nt':
187 py.test.skip('Run only on windows')
188 from rpython.rlib.libffi import WinDLL
189 dll = WinDLL('Kernel32.dll')
190 sleep = dll.getpointer('Sleep',[types.uint], types.void)
191 chain = ArgChain()
192 chain.arg(10)
193 sleep.call(chain, lltype.Void, is_struct=False)
194
195 class TestLibffiCall(BaseFfiTest):
196 """
197 Test various kind of calls through libffi.
198
199 The peculiarity of these tests is that they are run both directly (going
200 really through libffi) and by jit/metainterp/test/test_fficall.py, which
201 tests the call when JITted.
202
203 If you need to test a behaviour than it's not affected by JITing (e.g.,
204 typechecking), you should put your test in TestLibffiMisc.
205 """
206
207 CDLL = CDLL
208
209 @classmethod
210 def setup_class(cls):
211 from rpython.tool.udir import udir
212 from rpython.translator.tool.cbuild import ExternalCompilationInfo
213 from rpython.translator.platform import platform
214
215 BaseFfiTest.setup_class()
216 # prepare C code as an example, so we can load it and call
217 # it via rlib.libffi
218 c_file = udir.ensure("test_libffi", dir=1).join("foolib.c")
219 # automatically collect the C source from the docstrings of the tests
220 snippets = []
221 for name in dir(cls):
222 if name.startswith('test_'):
223 meth = getattr(cls, name)
224 # the heuristic to determine it it's really C code could be
225 # improved: so far we just check that there is a '{' :-)
226 if meth.__doc__ is not None and '{' in meth.__doc__:
227 snippets.append(meth.__doc__)
228 #
229 INCLUDE = '#include "src/precommondefs.h"\n'
230 c_file.write(INCLUDE + str(py.code.Source('\n'.join(snippets))))
231 eci = ExternalCompilationInfo(include_dirs=[cdir])
232 cls.libfoo_name = str(platform.compile([c_file], eci, 'x',
233 standalone=False))
234 cls.dll = cls.CDLL(cls.libfoo_name)
235
236 def teardown_class(cls):
237 if cls.dll:
238 cls.dll.__del__()
239 # Why doesn't this call cls.dll.__del__() ?
240 #del cls.dll
241
242 def get_libfoo(self):
243 return self.dll
244
245 def call(self, funcspec, args, RESULT, is_struct=False, jitif=[]):
246 """
247 Call the specified function after constructing and ArgChain with the
248 arguments in ``args``.
249
250 The function is specified with ``funcspec``, which is a tuple of the
251 form (lib, name, argtypes, restype).
252
253 This method is overridden by metainterp/test/test_fficall.py in
254 order to do the call in a loop and JIT it. The optional arguments are
255 used only by that overridden method.
256
257 """
258 lib, name, argtypes, restype = funcspec
259 func = lib.getpointer(name, argtypes, restype)
260 chain = ArgChain()
261 for arg in args:
262 if isinstance(arg, tuple):
263 methname, arg = arg
264 meth = getattr(chain, methname)
265 meth(arg)
266 else:
267 chain.arg(arg)
268 return func.call(chain, RESULT, is_struct=is_struct)
269
270 # ------------------------------------------------------------------------
271
272 def test_very_simple(self):
273 """
274 RPY_EXPORTED
275 int diff_xy(int x, Signed y)
276 {
277 return x - y;
278 }
279 """
280 libfoo = self.get_libfoo()
281 func = (libfoo, 'diff_xy', [types.sint, types.signed], types.sint)
282 res = self.call(func, [50, 8], rffi.INT)
283 assert res == 42
284
285 def test_simple(self):
286 """
287 RPY_EXPORTED
288 int sum_xy(int x, double y)
289 {
290 return (x + (int)y);
291 }
292 """
293 libfoo = self.get_libfoo()
294 func = (libfoo, 'sum_xy', [types.sint, types.double], types.sint)
295 res = self.call(func, [38, 4.2], rffi.INT, jitif=["floats"])
296 assert res == 42
297
298 def test_float_result(self):
299 libm = self.get_libm()
300 func = (libm, 'pow', [types.double, types.double], types.double)
301 res = self.call(func, [2.0, 3.0], rffi.DOUBLE, jitif=["floats"])
302 assert res == 8.0
303
304 def test_cast_result(self):
305 """
306 RPY_EXPORTED
307 unsigned char cast_to_uchar_and_ovf(int x)
308 {
309 return 200+(unsigned char)x;
310 }
311 """
312 libfoo = self.get_libfoo()
313 func = (libfoo, 'cast_to_uchar_and_ovf', [types.sint], types.uchar)
314 res = self.call(func, [0], rffi.UCHAR)
315 assert res == 200
316
317 def test_cast_argument(self):
318 """
319 RPY_EXPORTED
320 int many_args(char a, int b)
321 {
322 return a+b;
323 }
324 """
325 libfoo = self.get_libfoo()
326 func = (libfoo, 'many_args', [types.uchar, types.sint], types.sint)
327 res = self.call(func, [chr(20), 22], rffi.INT)
328 assert res == 42
329
330 def test_char_args(self):
331 """
332 RPY_EXPORTED
333 char sum_args(char a, char b) {
334 return a + b;
335 }
336 """
337 libfoo = self.get_libfoo()
338 func = (libfoo, 'sum_args', [types.schar, types.schar], types.schar)
339 res = self.call(func, [123, 43], rffi.CHAR)
340 assert res == chr(166)
341
342 def test_unsigned_short_args(self):
343 """
344 RPY_EXPORTED
345 unsigned short sum_xy_us(unsigned short x, unsigned short y)
346 {
347 return x+y;
348 }
349 """
350 libfoo = self.get_libfoo()
351 func = (libfoo, 'sum_xy_us', [types.ushort, types.ushort], types.ushort)
352 res = self.call(func, [32000, 8000], rffi.USHORT)
353 assert res == 40000
354
355
356 def test_pointer_as_argument(self):
357 """#include <stdlib.h>
358 RPY_EXPORTED
359 Signed inc(Signed* x)
360 {
361 Signed oldval;
362 if (x == NULL)
363 return -1;
364 oldval = *x;
365 *x = oldval+1;
366 return oldval;
367 }
368 """
369 libfoo = self.get_libfoo()
370 func = (libfoo, 'inc', [types.pointer], types.signed)
371 null = lltype.nullptr(rffi.SIGNEDP.TO)
372 res = self.call(func, [null], rffi.SIGNED)
373 assert res == -1
374 #
375 ptr_result = lltype.malloc(rffi.SIGNEDP.TO, 1, flavor='raw')
376 ptr_result[0] = 41
377 res = self.call(func, [ptr_result], rffi.SIGNED)
378 if self.__class__ is TestLibffiCall:
379 # the function was called only once
380 assert res == 41
381 assert ptr_result[0] == 42
382 lltype.free(ptr_result, flavor='raw')
383 # the test does not make sense when run with the JIT through
384 # meta_interp, because the __del__ are not properly called (hence
385 # we "leak" memory)
386 del libfoo
387 gc.collect()
388 assert not ALLOCATED
389 else:
390 # the function as been called 9 times
391 assert res == 50
392 assert ptr_result[0] == 51
393 lltype.free(ptr_result, flavor='raw')
394
395 def test_return_pointer(self):
396 """
397 struct pair {
398 Signed a;
399 Signed b;
400 };
401
402 struct pair my_static_pair = {10, 20};
403
404 RPY_EXPORTED
405 Signed* get_pointer_to_b()
406 {
407 return &my_static_pair.b;
408 }
409 """
410 libfoo = self.get_libfoo()
411 func = (libfoo, 'get_pointer_to_b', [], types.pointer)
412 res = self.call(func, [], rffi.SIGNEDP)
413 assert res[0] == 20
414
415 def test_void_result(self):
416 """
417 int dummy;
418 RPY_EXPORTED
419 void set_dummy(int val) { dummy = val; }
420 RPY_EXPORTED
421 int get_dummy() { return dummy; }
422 """
423 libfoo = self.get_libfoo()
424 set_dummy = (libfoo, 'set_dummy', [types.sint], types.void)
425 get_dummy = (libfoo, 'get_dummy', [], types.sint)
426 #
427 initval = self.call(get_dummy, [], rffi.INT)
428 #
429 res = self.call(set_dummy, [initval+1], lltype.Void)
430 assert res is None
431 #
432 res = self.call(get_dummy, [], rffi.INT)
433 assert res == initval+1
434
435 def test_single_float_args(self):
436 """
437 RPY_EXPORTED
438 float sum_xy_float(float x, float y)
439 {
440 return x+y;
441 }
442 """
443 from ctypes import c_float # this is used only to compute the expected result
444 libfoo = self.get_libfoo()
445 func = (libfoo, 'sum_xy_float', [types.float, types.float], types.float)
446 x = r_singlefloat(12.34)
447 y = r_singlefloat(56.78)
448 res = self.call(func, [x, y], rffi.FLOAT, jitif=["singlefloats"])
449 expected = c_float(c_float(12.34).value + c_float(56.78).value).value
450 assert float(res) == expected
451
452 def test_slonglong_args(self):
453 """
454 RPY_EXPORTED
455 long long sum_xy_longlong(long long x, long long y)
456 {
457 return x+y;
458 }
459 """
460 maxint32 = 2147483647 # we cannot really go above maxint on 64 bits
461 # (and we would not test anything, as there long
462 # is the same as long long)
463 libfoo = self.get_libfoo()
464 func = (libfoo, 'sum_xy_longlong', [types.slonglong, types.slonglong],
465 types.slonglong)
466 if IS_32_BIT:
467 x = r_longlong(maxint32+1)
468 y = r_longlong(maxint32+2)
469 else:
470 x = maxint32+1
471 y = maxint32+2
472 res = self.call(func, [x, y], rffi.LONGLONG, jitif=["longlong"])
473 expected = maxint32*2 + 3
474 assert res == expected
475
476 def test_ulonglong_args(self):
477 """
478 RPY_EXPORTED
479 unsigned long long sum_xy_ulonglong(unsigned long long x,
480 unsigned long long y)
481 {
482 return x+y;
483 }
484 """
485 maxint64 = 9223372036854775807 # maxint64+1 does not fit into a
486 # longlong, but it does into a
487 # ulonglong
488 libfoo = self.get_libfoo()
489 func = (libfoo, 'sum_xy_ulonglong', [types.ulonglong, types.ulonglong],
490 types.ulonglong)
491 x = r_ulonglong(maxint64+1)
492 y = r_ulonglong(2)
493 res = self.call(func, [x, y], rffi.ULONGLONG, jitif=["longlong"])
494 expected = maxint64 + 3
495 assert res == expected
496
497 def test_wrong_number_of_arguments(self):
498 from rpython.rtyper.llinterp import LLException
499 libfoo = self.get_libfoo()
500 func = (libfoo, 'sum_xy', [types.sint, types.double], types.sint)
501
502 glob = globals()
503 loc = locals()
504 def my_raises(s):
505 try:
506 exec(s, glob, loc)
507 except TypeError:
508 pass
509 except LLException as e:
510 if str(e) != "<LLException 'TypeError'>":
511 raise
512 else:
513 assert False, 'Did not raise'
514
515 my_raises("self.call(func, [38], rffi.SIGNED)") # one less
516 my_raises("self.call(func, [38, 12.3, 42], rffi.SIGNED)") # one more
517
518
519 def test_byval_argument(self):
520 """
521 struct Point {
522 Signed x;
523 Signed y;
524 };
525
526 RPY_EXPORTED
527 Signed sum_point(struct Point p) {
528 return p.x + p.y;
529 }
530 """
531 libfoo = CDLL(self.libfoo_name)
532 ffi_point_struct = make_struct_ffitype_e(0, 0, [types.signed, types.signed])
533 ffi_point = ffi_point_struct.ffistruct
534 sum_point = (libfoo, 'sum_point', [ffi_point], types.signed)
535 #
536 ARRAY = rffi.CArray(rffi.SIGNED)
537 buf = lltype.malloc(ARRAY, 2, flavor='raw')
538 buf[0] = 30
539 buf[1] = 12
540 adr = rffi.cast(rffi.VOIDP, buf)
541 res = self.call(sum_point, [('arg_raw', adr)], rffi.SIGNED,
542 jitif=["byval"])
543 assert res == 42
544 # check that we still have the ownership on the buffer
545 assert buf[0] == 30
546 assert buf[1] == 12
547 lltype.free(buf, flavor='raw')
548 lltype.free(ffi_point_struct, flavor='raw')
549
550 def test_byval_result(self):
551 """
552 RPY_EXPORTED
553 struct Point make_point(Signed x, Signed y) {
554 struct Point p;
555 p.x = x;
556 p.y = y;
557 return p;
558 }
559 """
560 libfoo = CDLL(self.libfoo_name)
561 ffi_point_struct = make_struct_ffitype_e(rffi.sizeof(rffi.SIGNED)*2, 0, [types.signed, types.signed])
562 ffi_point = ffi_point_struct.ffistruct
563
564 libfoo = CDLL(self.libfoo_name)
565 make_point = (libfoo, 'make_point', [types.signed, types.signed], ffi_point)
566 #
567 PTR = lltype.Ptr(rffi.CArray(rffi.SIGNED))
568 p = self.call(make_point, [12, 34], PTR, is_struct=True,
569 jitif=["byval"])
570 assert p[0] == 12
571 assert p[1] == 34
572 lltype.free(p, flavor='raw')
573 lltype.free(ffi_point_struct, flavor='raw')
574
575 if os.name == 'nt':
576 def test_stdcall_simple(self):
577 """
578 RPY_EXPORTED
579 int __stdcall std_diff_xy(int x, Signed y)
580 {
581 return x - y;
582 }
583 """
584 libfoo = self.get_libfoo()
585 # __stdcall without a DEF file decorates the name with the number of bytes
586 # that the callee will remove from the call stack
587 # identical to __fastcall for amd64
588 if IS_32_BIT:
589 f_name = '_std_diff_xy@8'
590 else:
591 f_name = 'std_diff_xy'
592 func = (libfoo, f_name, [types.sint, types.signed], types.sint)
593 try:
594 res = self.call(func, [50, 8], rffi.INT)
595 except ValueError as e:
596 assert e.message == 'Procedure called with not enough ' + \
597 'arguments (8 bytes missing) or wrong calling convention'
598 assert IS_32_BIT
599 except LLException as e:
600 #jitted code raises this
601 assert str(e) == "<LLException 'StackCheckError'>"
602 assert IS_32_BIT
603 else:
604 if IS_32_BIT:
605 assert 0, 'wrong calling convention should have raised'
606 else:
607 assert res == 42
608
609 def test_by_ordinal(self):
610 """
611 RPY_EXPORTED
612 int AAA_first_ordinal_function()
613 {
614 return 42;
615 }
616 """
617 libfoo = self.get_libfoo()
618 f_by_name = libfoo.getpointer('AAA_first_ordinal_function' ,[],
619 types.sint)
620 f_by_ordinal = libfoo.getpointer_by_ordinal(1 ,[], types.sint)
621 print dir(f_by_name)
622 assert f_by_name.funcsym == f_by_ordinal.funcsym
623 chain = ArgChain()
624 assert 42 == f_by_ordinal.call(chain, rffi.INT, is_struct=False)
625
626 def test_by_ordinal2(self):
627 """
628 RPY_EXPORTED
629 int __stdcall BBB_second_ordinal_function()
630 {
631 return 24;
632 }
633 """
634 from rpython.rlib.libffi import WinDLL
635 dll = WinDLL(self.libfoo_name)
636 # __stdcall without a DEF file decorates the name with the number of bytes
637 # that the callee will remove from the call stack
638 # identical to __fastcall for amd64
639 if IS_32_BIT:
640 f_name = '_BBB_second_ordinal_function@0'
641 else:
642 f_name = 'BBB_second_ordinal_function'
643 f_by_name = dll.getpointer(f_name, [], types.sint)
644 f_by_ordinal = dll.getpointer_by_ordinal(2 ,[], types.sint)
645 print dir(f_by_name)
646 assert f_by_name.funcsym == f_by_ordinal.funcsym
647 chain = ArgChain()
648 assert 24 == f_by_ordinal.call(chain, rffi.INT, is_struct=False)
649
650
651