Debian Codegraph @

rpython/rtyper/lltypesystem/test/test_ll2ctypes.py

raw symbols SCIP
1 import py, pytest
2 import sys, struct
3 import ctypes
4 from rpython.rtyper.lltypesystem import lltype, rffi, llmemory
5 from rpython.rtyper.tool import rffi_platform
6 from rpython.rtyper.lltypesystem.ll2ctypes import lltype2ctypes, ctypes2lltype
7 from rpython.rtyper.lltypesystem.ll2ctypes import standard_c_lib
8 from rpython.rtyper.lltypesystem.ll2ctypes import uninitialized2ctypes
9 from rpython.rtyper.lltypesystem.ll2ctypes import ALLOCATED, force_cast
10 from rpython.rtyper.lltypesystem.ll2ctypes import cast_adr_to_int, get_ctypes_type
11 from rpython.rtyper.lltypesystem.ll2ctypes import _llgcopaque
12 from rpython.rtyper.annlowlevel import llhelper
13 from rpython.rlib import rposix
14 from rpython.rlib.rposix import UNDERSCORE_ON_WIN32
15 from rpython.translator.tool.cbuild import ExternalCompilationInfo
16 from rpython.translator import cdir
17 from rpython.tool.udir import udir
18 from rpython.rtyper.test.test_llinterp import interpret
19 from rpython.annotator.annrpython import RPythonAnnotator
20 from rpython.rtyper.rtyper import RPythonTyper
21 from rpython.rlib.rarithmetic import r_uint, get_long_pattern, is_emulated_long
22 from rpython.rlib.rarithmetic import is_valid_int
23
24 if False: # for now, please keep it False by default
25 from rpython.rtyper.lltypesystem import ll2ctypes
26 ll2ctypes.do_allocation_in_far_regions()
27
28 """
29 Win64:
30 To decouple the cpython machine level long from the faked integer
31 of the target rpython, I replaced most 'lltype.Signed' by 'rffi.LONG'.
32 It would be nicer to replace all lltypes constants by rffi equivalents,
33 or better if we had a way to address the specific different types of
34 the current and the target system layout explicitly.
35 Let's think of that when we go further and make the target completely
36 independent and configurable.
37 Why most and not all replaced?
38 Tests with direct tests become cumbersome, instead of direct number
39 assignment rffi.setintfield(s, 'x', 123) must be used.
40 So in cases with number constants, where the size is not relevant,
41 I kept lltype.signed .
42 """
43
44 class TestLL2Ctypes(object):
45
46 def setup_method(self, meth):
47 ALLOCATED.clear()
48
49 def test_primitive(self):
50 assert lltype2ctypes(5) == 5
51 assert lltype2ctypes('?') == ord('?')
52 assert lltype2ctypes('\xE0') == 0xE0
53 assert lltype2ctypes(unichr(1234)) == 1234
54 assert ctypes2lltype(lltype.Signed, 5) == 5
55 assert ctypes2lltype(lltype.Char, ord('a')) == 'a'
56 assert ctypes2lltype(lltype.UniChar, ord(u'x')) == u'x'
57 assert ctypes2lltype(lltype.Char, 0xFF) == '\xFF'
58 assert lltype2ctypes(5.25) == 5.25
59 assert ctypes2lltype(lltype.Float, 5.25) == 5.25
60 assert lltype2ctypes(u'x') == ord(u'x')
61 res = lltype2ctypes(rffi.r_singlefloat(-3.5))
62 assert isinstance(res, ctypes.c_float)
63 assert res.value == -3.5
64 res = ctypes2lltype(lltype.SingleFloat, ctypes.c_float(-3.5))
65 assert isinstance(res, rffi.r_singlefloat)
66 assert float(res) == -3.5
67 assert lltype2ctypes(rffi.r_ulong(-1)) == (1 << rffi.r_ulong.BITS) - 1
68 res = ctypes2lltype(lltype.Unsigned, sys.maxint * 2 + 1)
69 assert (res, type(res)) == (r_uint(-1), r_uint)
70 assert ctypes2lltype(lltype.Bool, 0) is False
71 assert ctypes2lltype(lltype.Bool, 1) is True
72
73 res = lltype2ctypes(llmemory.sizeof(rffi.LONG))
74 assert res == struct.calcsize("l")
75 S = lltype.Struct('S', ('x', rffi.LONG), ('y', rffi.LONG))
76 res = lltype2ctypes(llmemory.sizeof(S))
77 assert res == struct.calcsize("ll")
78
79 p = lltype.nullptr(S)
80 cptr = lltype2ctypes(p)
81 assert not cptr
82 py.test.raises(ValueError, 'cptr.contents') # NULL pointer access
83 res = ctypes2lltype(lltype.Ptr(S), cptr)
84 assert res == p
85 assert not ALLOCATED # detects memory leaks in the test
86
87 def test_simple_struct(self):
88 S = lltype.Struct('S', ('x', lltype.Signed), ('y', lltype.Signed))
89 s = lltype.malloc(S, flavor='raw')
90 rffi.setintfield(s, 'x', 123)
91 sc = lltype2ctypes(s)
92 assert isinstance(sc.contents, ctypes.Structure)
93 assert sc.contents.x == 123
94 sc.contents.x = 456
95 assert s.x == 456
96 s.x = 789
97 assert sc.contents.x == 789
98 s.y = 52
99 assert sc.contents.y == 52
100 lltype.free(s, flavor='raw')
101 assert not ALLOCATED # detects memory leaks in the test
102
103 def test_get_pointer(self):
104 # Equivalent of the C code::
105 # struct S1 { struct S2 *ptr; struct S2 buf; };
106 # struct S1 s1;
107 # s1.ptr = & s1.buf;
108 S2 = lltype.Struct('S2', ('y', lltype.Signed))
109 S1 = lltype.Struct('S',
110 ('sub', lltype.Struct('SUB',
111 ('ptr', lltype.Ptr(S2)))),
112 ('ptr', lltype.Ptr(S2)),
113 ('buf', S2), # Works when this field is first!
114 )
115 s1 = lltype.malloc(S1, flavor='raw')
116 s1.ptr = s1.buf
117 s1.sub.ptr = s1.buf
118
119 x = rffi.cast(rffi.CCHARP, s1)
120 lltype.free(s1, flavor='raw')
121
122 def test_struct_ptrs(self):
123 S2 = lltype.Struct('S2', ('y', lltype.Signed))
124 S1 = lltype.Struct('S', ('x', lltype.Signed), ('p', lltype.Ptr(S2)))
125 s1 = lltype.malloc(S1, flavor='raw')
126 s2a = lltype.malloc(S2, flavor='raw')
127 s2b = lltype.malloc(S2, flavor='raw')
128 s2a.y = ord('a')
129 s2b.y = ord('b')
130 sc1 = lltype2ctypes(s1)
131 sc1.contents.x = 50
132 assert s1.x == 50
133 sc1.contents.p = lltype2ctypes(s2a)
134 assert s1.p == s2a
135 s1.p.y -= 32
136 assert sc1.contents.p.contents.y == ord('A')
137 s1.p = s2b
138 sc1.contents.p.contents.y -= 32
139 assert s2b.y == ord('B')
140 lltype.free(s1, flavor='raw')
141 lltype.free(s2a, flavor='raw')
142 lltype.free(s2b, flavor='raw')
143 assert not ALLOCATED # detects memory leaks in the test
144
145 def test_simple_array(self):
146 A = lltype.Array(lltype.Signed)
147 a = lltype.malloc(A, 10, flavor='raw')
148 a[0] = 100
149 a[1] = 101
150 a[2] = 102
151 ac = lltype2ctypes(a, normalize=False)
152 assert isinstance(ac.contents, ctypes.Structure)
153 assert ac.contents.length == 10
154 if is_emulated_long:
155 lentype = ctypes.c_longlong
156 else:
157 lentype = ctypes.c_long
158 assert ac.contents._fields_[0] == ('length', lentype)
159 assert ac.contents.items[1] == 101
160 ac.contents.items[2] = 456
161 assert a[2] == 456
162 a[3] = 789
163 assert ac.contents.items[3] == 789
164 lltype.free(a, flavor='raw')
165 assert not ALLOCATED # detects memory leaks in the test
166
167 def test_array_inside_struct(self):
168 # like rstr.STR, but not Gc
169 STR = lltype.Struct('STR', ('x', rffi.LONG), ('y', lltype.Array(lltype.Char)))
170 a = lltype.malloc(STR, 3, flavor='raw')
171 a.y[0] = 'x'
172 a.y[1] = 'y'
173 a.y[2] = 'z'
174 # we need to pass normalize=False, otherwise 'ac' is returned of
175 # a normalized standard type, which complains about IndexError
176 # when doing 'ac.contents.y.items[2]'.
177 ac = lltype2ctypes(a, normalize=False)
178 assert ac.contents.y.length == 3
179 assert ac.contents.y.items[2] == ord('z')
180 lltype.free(a, flavor='raw')
181 assert not ALLOCATED
182
183 def test_array_nolength(self):
184 A = lltype.Array(lltype.Signed, hints={'nolength': True})
185 a = lltype.malloc(A, 10, flavor='raw')
186 a[0] = 100
187 a[1] = 101
188 a[2] = 102
189 ac = lltype2ctypes(a, normalize=False)
190 assert isinstance(ac.contents, ctypes.Structure)
191 assert ac.contents.items[1] == 101
192 ac.contents.items[2] = 456
193 assert a[2] == 456
194 a[3] = 789
195 assert ac.contents.items[3] == 789
196 assert ctypes.sizeof(ac.contents) == 10 * rffi.sizeof(lltype.Signed)
197 lltype.free(a, flavor='raw')
198 assert not ALLOCATED # detects memory leaks in the test
199
200 def test_charp(self):
201 s = rffi.str2charp("hello")
202 sc = lltype2ctypes(s, normalize=False)
203 assert sc.contents.items[0] == ord('h')
204 assert sc.contents.items[1] == ord('e')
205 assert sc.contents.items[2] == ord('l')
206 assert sc.contents.items[3] == ord('l')
207 assert sc.contents.items[4] == ord('o')
208 assert sc.contents.items[5] == 0
209 assert not hasattr(sc.contents, 'length')
210 sc.contents.items[1] = ord('E')
211 assert s[1] == 'E'
212 s[0] = 'H'
213 assert sc.contents.items[0] == ord('H')
214 rffi.free_charp(s)
215 assert not ALLOCATED # detects memory leaks in the test
216
217 def test_unicharp(self):
218 SP = rffi.CArrayPtr(lltype.UniChar)
219 s = lltype.malloc(SP.TO, 4, flavor='raw')
220 s[0] = u'x'
221 s[1] = u'y'
222 s[2] = u'z'
223 s[3] = u'\x00'
224 sc = lltype2ctypes(s, normalize=False)
225 assert sc.contents.items[0] == ord(u'x')
226 assert sc.contents.items[1] == ord(u'y')
227 assert sc.contents.items[2] == ord(u'z')
228 assert not hasattr(sc.contents, 'length')
229 lltype.free(s, flavor='raw')
230 assert not ALLOCATED
231
232 def test_strlen(self):
233 eci = ExternalCompilationInfo(includes=['string.h'])
234 strlen = rffi.llexternal('strlen', [rffi.CCHARP], rffi.SIZE_T,
235 compilation_info=eci)
236 s = rffi.str2charp("xxx")
237 res = strlen(s)
238 rffi.free_charp(s)
239 assert res == 3 # actually r_size_t(3)
240 s = rffi.str2charp("")
241 res = strlen(s)
242 rffi.free_charp(s)
243 assert res == 0 # actually r_size_t(0)
244 assert not ALLOCATED # detects memory leaks in the test
245
246 def test_func_not_in_clib(self):
247 eci = ExternalCompilationInfo(libraries=['m'])
248 foobar = rffi.llexternal('I_really_dont_exist', [], rffi.LONG)
249 py.test.raises(NotImplementedError, foobar)
250
251 foobar = rffi.llexternal('I_really_dont_exist', [], rffi.LONG,
252 compilation_info=eci) # math library
253 py.test.raises(NotImplementedError, foobar)
254
255 eci = ExternalCompilationInfo(libraries=['m', 'z'])
256 foobar = rffi.llexternal('I_really_dont_exist', [], rffi.LONG,
257 compilation_info=eci) # math and zlib
258 py.test.raises(NotImplementedError, foobar)
259
260 eci = ExternalCompilationInfo(libraries=['I_really_dont_exist_either'])
261 foobar = rffi.llexternal('I_really_dont_exist', [], rffi.LONG,
262 compilation_info=eci)
263 py.test.raises(NotImplementedError, foobar)
264 assert not ALLOCATED # detects memory leaks in the test
265
266 def test_cstruct_to_ll(self):
267 S = lltype.Struct('S', ('x', lltype.Signed), ('y', lltype.Signed))
268 s = lltype.malloc(S, flavor='raw')
269 s2 = lltype.malloc(S, flavor='raw')
270 s.x = 123
271 sc = lltype2ctypes(s)
272 t = ctypes2lltype(lltype.Ptr(S), sc)
273 assert lltype.typeOf(t) == lltype.Ptr(S)
274 assert s == t
275 assert not (s != t)
276 assert t == s
277 assert not (t != s)
278 assert t != lltype.nullptr(S)
279 assert not (t == lltype.nullptr(S))
280 assert lltype.nullptr(S) != t
281 assert not (lltype.nullptr(S) == t)
282 assert t != s2
283 assert not (t == s2)
284 assert s2 != t
285 assert not (s2 == t)
286 assert t.x == 123
287 t.x += 1
288 assert s.x == 124
289 s.x += 1
290 assert t.x == 125
291 lltype.free(s, flavor='raw')
292 lltype.free(s2, flavor='raw')
293 assert not ALLOCATED # detects memory leaks in the test
294
295 def test_carray_to_ll(self):
296 A = lltype.Array(lltype.Signed, hints={'nolength': True})
297 a = lltype.malloc(A, 10, flavor='raw')
298 a2 = lltype.malloc(A, 10, flavor='raw')
299 a[0] = 100
300 a[1] = 101
301 a[2] = 110
302 ac = lltype2ctypes(a)
303 b = ctypes2lltype(lltype.Ptr(A), ac)
304 assert lltype.typeOf(b) == lltype.Ptr(A)
305 assert b == a
306 assert not (b != a)
307 assert a == b
308 assert not (a != b)
309 assert b != lltype.nullptr(A)
310 assert not (b == lltype.nullptr(A))
311 assert lltype.nullptr(A) != b
312 assert not (lltype.nullptr(A) == b)
313 assert b != a2
314 assert not (b == a2)
315 assert a2 != b
316 assert not (a2 == b)
317 assert b[2] == 110
318 b[2] *= 2
319 assert a[2] == 220
320 a[2] *= 3
321 assert b[2] == 660
322 lltype.free(a, flavor='raw')
323 lltype.free(a2, flavor='raw')
324 assert not ALLOCATED # detects memory leaks in the test
325
326 def test_strchr(self):
327 eci = ExternalCompilationInfo(includes=['string.h'])
328 strchr = rffi.llexternal('strchr', [rffi.CCHARP, rffi.INT],
329 rffi.CCHARP, compilation_info=eci)
330 s = rffi.str2charp("hello world")
331 res = strchr(s, ord('r'))
332 assert res[0] == 'r'
333 assert res[1] == 'l'
334 assert res[2] == 'd'
335 assert res[3] == '\x00'
336 # XXX maybe we should also allow res[-1], res[-2]...
337 rffi.free_charp(s)
338 assert not ALLOCATED # detects memory leaks in the test
339
340 def test_frexp(self):
341 if sys.platform != 'win32':
342 eci = ExternalCompilationInfo(includes=['math.h'],
343 libraries=['m'])
344 else:
345 eci = ExternalCompilationInfo(includes=['math.h'])
346 A = lltype.FixedSizeArray(rffi.INT, 1)
347 frexp = rffi.llexternal('frexp', [rffi.DOUBLE, lltype.Ptr(A)],
348 rffi.DOUBLE, compilation_info=eci)
349 p = lltype.malloc(A, flavor='raw')
350 res = frexp(2.5, p)
351 assert res == 0.625
352 assert p[0] == 2
353 lltype.free(p, flavor='raw')
354 assert not ALLOCATED # detects memory leaks in the test
355
356 def test_rand(self):
357 eci = ExternalCompilationInfo(includes=['stdlib.h'])
358 rand = rffi.llexternal('rand', [], rffi.INT,
359 compilation_info=eci)
360 srand = rffi.llexternal('srand', [rffi.UINT], lltype.Void,
361 compilation_info=eci)
362 srand(rffi.r_uint(123))
363 res1 = rand()
364 res2 = rand()
365 res3 = rand()
366 srand(rffi.r_uint(123))
367 res1b = rand()
368 res2b = rand()
369 res3b = rand()
370 assert res1 == res1b
371 assert res2 == res2b
372 assert res3 == res3b
373 assert not ALLOCATED # detects memory leaks in the test
374
375 def test_opaque_obj(self):
376 if sys.platform == 'win32':
377 py.test.skip("No gettimeofday on win32")
378 eci = ExternalCompilationInfo(
379 includes = ['sys/time.h', 'time.h']
380 )
381 TIMEVALP = rffi.COpaquePtr('struct timeval', compilation_info=eci)
382 TIMEZONEP = rffi.COpaquePtr('struct timezone', compilation_info=eci)
383 gettimeofday = rffi.llexternal('gettimeofday', [TIMEVALP, TIMEZONEP],
384 rffi.INT, compilation_info=eci)
385 ll_timevalp = lltype.malloc(TIMEVALP.TO, flavor='raw')
386 ll_timezonep = lltype.malloc(TIMEZONEP.TO, flavor='raw')
387 res = gettimeofday(ll_timevalp, ll_timezonep)
388 assert res != -1
389 lltype.free(ll_timezonep, flavor='raw')
390 lltype.free(ll_timevalp, flavor='raw')
391 assert not ALLOCATED # detects memory leaks in the test
392
393 def test_opaque_obj_2(self):
394 FILEP = rffi.COpaquePtr('FILE')
395 fopen = rffi.llexternal('fopen', [rffi.CCHARP, rffi.CCHARP], FILEP)
396 fclose = rffi.llexternal('fclose', [FILEP], rffi.INT)
397 tmppath = udir.join('test_ll2ctypes.test_opaque_obj_2')
398 ll_file = fopen(str(tmppath), "w")
399 assert ll_file
400 fclose(ll_file)
401 assert tmppath.check(file=1)
402 assert not ALLOCATED # detects memory leaks in the test
403
404 assert rffi.cast(FILEP, -1) == rffi.cast(FILEP, -1)
405
406 def test_simple_cast(self):
407 assert rffi.cast(rffi.SIGNEDCHAR, 0x123456) == 0x56
408 assert rffi.cast(rffi.SIGNEDCHAR, 0x123481) == -127
409 assert rffi.cast(rffi.CHAR, 0x123456) == '\x56'
410 assert rffi.cast(rffi.CHAR, 0x123481) == '\x81'
411 assert rffi.cast(rffi.UCHAR, 0x123481) == 0x81
412 assert not ALLOCATED # detects memory leaks in the test
413
414 def test_forced_ptr_cast(self):
415 import array
416 A = lltype.Array(lltype.Signed, hints={'nolength': True})
417 B = lltype.Array(lltype.Char, hints={'nolength': True})
418 a = lltype.malloc(A, 10, flavor='raw')
419 for i in range(10):
420 a[i] = i*i
421
422 b = rffi.cast(lltype.Ptr(B), a)
423
424 expected = ''
425 for i in range(10):
426 expected += get_long_pattern(i*i)
427
428 for i in range(len(expected)):
429 assert b[i] == expected[i]
430
431 c = rffi.cast(rffi.VOIDP, a)
432 addr = lltype2ctypes(c)
433 #assert addr == ctypes.addressof(a._obj._ctypes_storage)
434 d = ctypes2lltype(rffi.VOIDP, addr)
435 assert lltype.typeOf(d) == rffi.VOIDP
436 assert c == d
437 e = rffi.cast(lltype.Ptr(A), d)
438 for i in range(10):
439 assert e[i] == i*i
440
441 c = lltype.nullptr(rffi.VOIDP.TO)
442 addr = rffi.cast(rffi.LONG, c)
443 assert addr == 0
444
445 lltype.free(a, flavor='raw')
446 assert not ALLOCATED # detects memory leaks in the test
447
448 def test_adr_cast(self):
449 from rpython.rtyper.annlowlevel import llstr
450 from rpython.rtyper.lltypesystem.rstr import STR
451 P = lltype.Ptr(lltype.FixedSizeArray(lltype.Char, 1))
452 def f():
453 a = llstr("xyz")
454 b = (llmemory.cast_ptr_to_adr(a) + llmemory.offsetof(STR, 'chars')
455 + llmemory.itemoffsetof(STR.chars, 0))
456 buf = rffi.cast(rffi.VOIDP, b)
457 return buf[2]
458 assert f() == 'z'
459 res = interpret(f, [])
460 assert res == 'z'
461
462 def test_funcptr1(self):
463 def dummy(n):
464 return n+1
465
466 FUNCTYPE = lltype.FuncType([lltype.Signed], lltype.Signed)
467 cdummy = lltype2ctypes(llhelper(lltype.Ptr(FUNCTYPE), dummy))
468 if not is_emulated_long:
469 assert cdummy.argtypes == (ctypes.c_long,)
470 assert cdummy.restype == ctypes.c_long
471 else:
472 # XXX maybe we skip this if it breaks on some platforms
473 assert cdummy.argtypes == (ctypes.c_longlong,)
474 assert cdummy.restype == ctypes.c_longlong
475 res = cdummy(41)
476 assert res == 42
477 lldummy = ctypes2lltype(lltype.Ptr(FUNCTYPE), cdummy)
478 assert lltype.typeOf(lldummy) == lltype.Ptr(FUNCTYPE)
479 res = lldummy(41)
480 assert res == 42
481 assert not ALLOCATED # detects memory leaks in the test
482
483 def test_llhelper_error_value(self, monkeypatch):
484 from rpython.rlib.objectmodel import llhelper_error_value
485 class FooError(Exception):
486 pass
487 @llhelper_error_value(error_value=-7)
488 def dummy(n):
489 raise FooError(n + 2)
490
491 FUNCTYPE = lltype.FuncType([lltype.Signed], lltype.Signed)
492 cdummy = lltype2ctypes(llhelper(lltype.Ptr(FUNCTYPE), dummy))
493 # here we pretend there is C in the middle
494 lldummy = ctypes2lltype(lltype.Ptr(FUNCTYPE), cdummy,
495 force_real_ctypes_function=True)
496 seen = []
497 def custom_except_hook(*args):
498 seen.append(args)
499 monkeypatch.setattr(sys, 'excepthook', custom_except_hook)
500 with pytest.raises(FooError) as exc:
501 lldummy(41)
502 assert exc.value.args == (41 + 2,)
503 assert exc.value._ll2ctypes_c_result == -7
504 assert not seen
505 assert not ALLOCATED # detects memory leaks in the test
506
507 def test_funcptr2(self):
508 FUNCTYPE = lltype.FuncType([rffi.CCHARP], rffi.LONG)
509 cstrlen = standard_c_lib.strlen
510 llstrlen = ctypes2lltype(lltype.Ptr(FUNCTYPE), cstrlen)
511 assert lltype.typeOf(llstrlen) == lltype.Ptr(FUNCTYPE)
512 p = rffi.str2charp("hi there")
513 res = llstrlen(p)
514 assert res == 8
515 cstrlen2 = lltype2ctypes(llstrlen)
516 cp = lltype2ctypes(p)
517 assert cstrlen2.restype == ctypes.c_long
518 res = cstrlen2(cp)
519 assert res == 8
520 rffi.free_charp(p)
521 assert not ALLOCATED # detects memory leaks in the test
522
523 def test_funcptr_cast(self):
524 eci = ExternalCompilationInfo(
525 include_dirs = [cdir],
526 separate_module_sources=["""
527 #include "src/precommondefs.h"
528 long mul(long x, long y) { return x*y; }
529 RPY_EXPORTED long(*get_mul(long x)) () { return &mul; }
530 """])
531 get_mul = rffi.llexternal(
532 'get_mul', [],
533 lltype.Ptr(lltype.FuncType([lltype.Signed], lltype.Signed)),
534 compilation_info=eci)
535 # This call returns a pointer to a function taking one argument
536 funcptr = get_mul()
537 # cast it to the "real" function type
538 FUNCTYPE2 = lltype.FuncType([lltype.Signed, lltype.Signed],
539 lltype.Signed)
540 cmul = rffi.cast(lltype.Ptr(FUNCTYPE2), funcptr)
541 # and it can be called with the expected number of arguments
542 res = cmul(41, 42)
543 assert res == 41 * 42
544 py.test.raises(TypeError, cmul, 41)
545 py.test.raises(TypeError, cmul, 41, 42, 43)
546
547 def test_qsort(self):
548 CMPFUNC = lltype.FuncType([rffi.VOIDP, rffi.VOIDP], rffi.INT)
549 qsort = rffi.llexternal('qsort', [rffi.VOIDP,
550 rffi.SIZE_T,
551 rffi.SIZE_T,
552 lltype.Ptr(CMPFUNC)],
553 lltype.Void)
554
555 lst = [23, 43, 24, 324, 242, 34, 78, 5, 3, 10]
556 A = lltype.Array(lltype.Signed, hints={'nolength': True})
557 a = lltype.malloc(A, 10, flavor='raw')
558 for i in range(10):
559 a[i] = lst[i]
560
561 SIGNEDPTR = lltype.Ptr(lltype.FixedSizeArray(lltype.Signed, 1))
562
563 def my_compar(p1, p2):
564 p1 = rffi.cast(SIGNEDPTR, p1)
565 p2 = rffi.cast(SIGNEDPTR, p2)
566 print 'my_compar:', p1[0], p2[0]
567 return rffi.cast(rffi.INT, cmp(p1[0], p2[0]))
568
569 qsort(rffi.cast(rffi.VOIDP, a),
570 rffi.cast(rffi.SIZE_T, 10),
571 rffi.cast(rffi.SIZE_T, llmemory.sizeof(lltype.Signed)),
572 llhelper(lltype.Ptr(CMPFUNC), my_compar))
573
574 for i in range(10):
575 print a[i],
576 print
577 lst.sort()
578 for i in range(10):
579 assert a[i] == lst[i]
580 lltype.free(a, flavor='raw')
581 assert not ALLOCATED # detects memory leaks in the test
582
583 # def test_signal(self):...
584
585 def test_uninitialized2ctypes(self):
586 # for now, uninitialized fields are filled with 0xDD in the ctypes data
587 def checkobj(o, size):
588 p = ctypes.cast(ctypes.c_void_p(ctypes.addressof(o)),
589 ctypes.POINTER(ctypes.c_ubyte*size))
590 for i in range(size):
591 assert p.contents[i] == 0xDD
592
593 def checkval(v, fmt):
594 res = struct.pack(fmt, v)
595 assert res == "\xDD" * len(res)
596
597 checkval(uninitialized2ctypes(rffi.CHAR), 'B')
598 checkval(uninitialized2ctypes(rffi.SHORT), 'h')
599 if not is_emulated_long:
600 checkval(uninitialized2ctypes(rffi.INT), 'i')
601 checkval(uninitialized2ctypes(rffi.UINT), 'I')
602 checkval(uninitialized2ctypes(rffi.LONGLONG), 'q')
603 checkval(uninitialized2ctypes(rffi.DOUBLE), 'd')
604 checkobj(uninitialized2ctypes(rffi.INTP),
605 ctypes.sizeof(ctypes.c_void_p))
606 checkobj(uninitialized2ctypes(rffi.CCHARP),
607 ctypes.sizeof(ctypes.c_void_p))
608
609 S = lltype.Struct('S', ('x', rffi.LONG), ('y', rffi.LONG))
610 s = lltype.malloc(S, flavor='raw')
611 sc = lltype2ctypes(s)
612 checkval(sc.contents.x, 'l')
613 checkval(sc.contents.y, 'l')
614 lltype.free(s, flavor='raw')
615 assert not ALLOCATED # detects memory leaks in the test
616
617 def test_substructures(self):
618 S1 = lltype.Struct('S1', ('x', lltype.Signed))
619 BIG = lltype.Struct('BIG', ('s1a', S1), ('s1b', S1))
620 s = lltype.malloc(BIG, flavor='raw')
621 s.s1a.x = 123
622 s.s1b.x = 456
623 sc = lltype2ctypes(s)
624 assert sc.contents.s1a.x == 123
625 assert sc.contents.s1b.x == 456
626 sc.contents.s1a.x += 1
627 sc.contents.s1b.x += 10
628 assert s.s1a.x == 124
629 assert s.s1b.x == 466
630 s.s1a.x += 3
631 s.s1b.x += 30
632 assert sc.contents.s1a.x == 127
633 assert sc.contents.s1b.x == 496
634 lltype.free(s, flavor='raw')
635
636 s = lltype.malloc(BIG, flavor='raw')
637 s1ac = lltype2ctypes(s.s1a)
638 s1ac.contents.x = 53
639 sc = lltype2ctypes(s)
640 assert sc.contents.s1a.x == 53
641 sc.contents.s1a.x += 1
642 assert s1ac.contents.x == 54
643 assert s.s1a.x == 54
644 s.s1a.x += 2
645 assert s1ac.contents.x == 56
646 assert sc.contents.s1a.x == 56
647 sc.contents.s1a.x += 3
648 assert s1ac.contents.x == 59
649 assert s.s1a.x == 59
650
651 t = ctypes2lltype(lltype.Ptr(BIG), sc)
652 assert t == s
653 assert t.s1a == s.s1a
654 assert t.s1a.x == 59
655 s.s1b.x = 8888
656 assert t.s1b == s.s1b
657 assert t.s1b.x == 8888
658 t1 = ctypes2lltype(lltype.Ptr(S1), s1ac)
659 assert t.s1a == t1
660 assert t1.x == 59
661 t1.x += 1
662 assert sc.contents.s1a.x == 60
663 lltype.free(s, flavor='raw')
664 assert not ALLOCATED # detects memory leaks in the test
665
666 def test_recursive_struct(self):
667 SX = lltype.ForwardReference()
668 S1 = lltype.Struct('S1', ('p', lltype.Ptr(SX)), ('x', lltype.Signed))
669 SX.become(S1)
670 # a chained list
671 s1 = lltype.malloc(S1, flavor='raw')
672 s2 = lltype.malloc(S1, flavor='raw')
673 s3 = lltype.malloc(S1, flavor='raw')
674 s1.x = 111
675 s2.x = 222
676 s3.x = 333
677 s1.p = s2
678 s2.p = s3
679 s3.p = lltype.nullptr(S1)
680 sc1 = lltype2ctypes(s1)
681 sc2 = sc1.contents.p
682 sc3 = sc2.contents.p
683 assert not sc3.contents.p
684 assert sc1.contents.x == 111
685 assert sc2.contents.x == 222
686 assert sc3.contents.x == 333
687 sc3.contents.x += 1
688 assert s3.x == 334
689 s3.x += 2
690 assert sc3.contents.x == 336
691 lltype.free(s1, flavor='raw')
692 lltype.free(s2, flavor='raw')
693 lltype.free(s3, flavor='raw')
694 # a self-cycle
695 s1 = lltype.malloc(S1, flavor='raw')
696 s1.x = 12
697 s1.p = s1
698 sc1 = lltype2ctypes(s1)
699 assert sc1.contents.x == 12
700 assert (ctypes.addressof(sc1.contents.p.contents) ==
701 ctypes.addressof(sc1.contents))
702 s1.x *= 5
703 assert sc1.contents.p.contents.p.contents.p.contents.x == 60
704 lltype.free(s1, flavor='raw')
705 # a longer cycle
706 s1 = lltype.malloc(S1, flavor='raw')
707 s2 = lltype.malloc(S1, flavor='raw')
708 s1.x = 111
709 s1.p = s2
710 s2.x = 222
711 s2.p = s1
712 sc1 = lltype2ctypes(s1)
713 assert sc1.contents.x == 111
714 assert sc1.contents.p.contents.x == 222
715 assert (ctypes.addressof(sc1.contents.p.contents) !=
716 ctypes.addressof(sc1.contents))
717 assert (ctypes.addressof(sc1.contents.p.contents.p.contents) ==
718 ctypes.addressof(sc1.contents))
719 lltype.free(s1, flavor='raw')
720 lltype.free(s2, flavor='raw')
721 assert not ALLOCATED # detects memory leaks in the test
722
723 def test_indirect_recursive_struct(self):
724 S2Forward = lltype.ForwardReference()
725 S1 = lltype.Struct('S1', ('p', lltype.Ptr(S2Forward)))
726 A2 = lltype.Array(lltype.Ptr(S1), hints={'nolength': True})
727 S2 = lltype.Struct('S2', ('a', lltype.Ptr(A2)))
728 S2Forward.become(S2)
729 s1 = lltype.malloc(S1, flavor='raw')
730 a2 = lltype.malloc(A2, 10, flavor='raw')
731 s2 = lltype.malloc(S2, flavor='raw')
732 s2.a = a2
733 a2[5] = s1
734 s1.p = s2
735 ac2 = lltype2ctypes(a2, normalize=False)
736 sc1 = ac2.contents.items[5]
737 sc2 = sc1.contents.p
738 assert (ctypes.addressof(sc2.contents.a.contents) ==
739 ctypes.addressof(ac2.contents))
740 lltype.free(s1, flavor='raw')
741 lltype.free(a2, flavor='raw')
742 lltype.free(s2, flavor='raw')
743 assert not ALLOCATED # detects memory leaks in the test
744
745 def test_arrayofstruct(self):
746 S1 = lltype.Struct('S2', ('x', lltype.Signed))
747 A = lltype.Array(S1, hints={'nolength': True})
748 a = lltype.malloc(A, 5, flavor='raw')
749 a[0].x = 100
750 a[1].x = 101
751 a[2].x = 102
752 a[3].x = 103
753 a[4].x = 104
754 ac = lltype2ctypes(a, normalize=False)
755 assert ac.contents.items[0].x == 100
756 assert ac.contents.items[2].x == 102
757 ac.contents.items[3].x += 500
758 assert a[3].x == 603
759 a[4].x += 600
760 assert ac.contents.items[4].x == 704
761 a1 = ctypes2lltype(lltype.Ptr(A), ac)
762 assert a1 == a
763 assert a1[2].x == 102
764 aitem1 = ctypes2lltype(lltype.Ptr(S1),
765 ctypes.pointer(ac.contents.items[1]))
766 assert aitem1.x == 101
767 assert aitem1 == a1[1]
768 lltype.free(a, flavor='raw')
769 assert not ALLOCATED # detects memory leaks in the test
770
771 def test_get_errno(self):
772 eci = ExternalCompilationInfo(includes=['string.h'])
773 if sys.platform.startswith('win'):
774 py.test.skip('writing to invalid fd on windows crashes the process')
775 # Note that cpython before 2.7 installs an _invalid_parameter_handler,
776 # which is why the test passes there, but this is no longer
777 # accepted practice.
778 import ctypes
779 SEM_NOGPFAULTERRORBOX = 0x0002 # From MSDN
780 old_err_mode = ctypes.windll.kernel32.GetErrorMode()
781 new_err_mode = old_err_mode | SEM_NOGPFAULTERRORBOX
782 ctypes.windll.kernel32.SetErrorMode(new_err_mode)
783 os_write_no_errno = rffi.llexternal(UNDERSCORE_ON_WIN32 + 'write',
784 [rffi.INT, rffi.CCHARP, rffi.SIZE_T],
785 rffi.SIZE_T, save_err=rffi.RFFI_ERR_NONE)
786 os_write = rffi.llexternal(UNDERSCORE_ON_WIN32 + 'write',
787 [rffi.INT, rffi.CCHARP, rffi.SIZE_T],
788 rffi.SIZE_T, save_err=rffi.RFFI_SAVE_ERRNO)
789 buffer = lltype.malloc(rffi.CCHARP.TO, 5, flavor='raw')
790 written = os_write(12312312, buffer, 5)
791 if sys.platform.startswith('win'):
792 ctypes.windll.kernel32.SetErrorMode(old_err_mode)
793 assert rffi.cast(rffi.LONG, written) < 0
794 # the next line is a different external function call
795 # without RFFI_SAVE_ERRNO, to check that it doesn't reset errno
796 buffer[0] = '\n'
797 os_write_no_errno(2, buffer, 1)
798 lltype.free(buffer, flavor='raw')
799 err = rposix.get_saved_errno()
800 import errno
801 assert err == errno.EBADF
802 assert not ALLOCATED # detects memory leaks in the test
803
804 def test_call_with_struct_argument(self):
805 # XXX is there such a function in the standard C headers?
806 from rpython.rlib import _rsocket_rffi
807 buf = rffi.make(_rsocket_rffi.in_addr)
808 rffi.cast(rffi.CCHARP, buf)[0] = '\x01'
809 rffi.cast(rffi.CCHARP, buf)[1] = '\x02'
810 rffi.cast(rffi.CCHARP, buf)[2] = '\x03'
811 rffi.cast(rffi.CCHARP, buf)[3] = '\x04'
812 p = _rsocket_rffi.inet_ntoa(buf)
813 assert rffi.charp2str(p) == '1.2.3.4'
814 lltype.free(buf, flavor='raw')
815 assert not ALLOCATED # detects memory leaks in the test
816
817 def test_storage_stays_around(self):
818 data = "hello, world!" * 100
819 A = lltype.Array(rffi.CHAR, hints={'nolength': True})
820 S = lltype.Struct('S', ('a', lltype.Ptr(A)))
821 s = lltype.malloc(S, flavor='raw')
822 lltype2ctypes(s) # force it to escape
823 s.a = lltype.malloc(A, len(data), flavor='raw')
824 # the storage for the array should not be freed by lltype even
825 # though the _ptr object appears to go away here
826 for i in xrange(len(data)):
827 s.a[i] = data[i]
828 for i in xrange(len(data)):
829 assert s.a[i] == data[i]
830 lltype.free(s.a, flavor='raw')
831 lltype.free(s, flavor='raw')
832 assert not ALLOCATED # detects memory leaks in the test
833
834 def test_arrayoffloat(self):
835 a = lltype.malloc(rffi.FLOATP.TO, 3, flavor='raw')
836 a[0] = rffi.r_singlefloat(0.0)
837 a[1] = rffi.r_singlefloat(1.1)
838 a[2] = rffi.r_singlefloat(2.2)
839 ac = lltype2ctypes(a, normalize=False)
840 assert ac.contents.items[0] == 0.0
841 assert abs(ac.contents.items[1] - 1.1) < 1E-6
842 assert abs(ac.contents.items[2] - 2.2) < 1E-6
843 b = ctypes2lltype(rffi.FLOATP, ac)
844 assert isinstance(b[0], rffi.r_singlefloat)
845 assert float(b[0]) == 0.0
846 assert isinstance(b[1], rffi.r_singlefloat)
847 assert abs(float(b[1]) - 1.1) < 1E-6
848 assert isinstance(b[2], rffi.r_singlefloat)
849 assert abs(float(b[2]) - 2.2) < 1E-6
850 lltype.free(a, flavor='raw')
851
852 def test_different_signatures(self):
853 if sys.platform=='win32':
854 py.test.skip("No fcntl on win32")
855 fcntl_int = rffi.llexternal('fcntl', [rffi.INT, rffi.INT, rffi.INT],
856 rffi.INT)
857 fcntl_str = rffi.llexternal('fcntl', [rffi.INT, rffi.INT, rffi.CCHARP],
858 rffi.INT)
859 fcntl_int(12345, 1, 0)
860 fcntl_str(12345, 3, "xxx")
861 fcntl_int(12345, 1, 0)
862
863 def test_llexternal_source(self):
864 eci = ExternalCompilationInfo(
865 include_dirs = [cdir],
866 separate_module_sources = ["""
867 #include "src/precommondefs.h"
868 RPY_EXPORTED int fn() { return 42; }
869 """],
870 )
871 fn = rffi.llexternal('fn', [], rffi.INT, compilation_info=eci)
872 res = fn()
873 assert res == 42
874
875 def test_llexternal_macro(self):
876 eci = ExternalCompilationInfo(
877 post_include_bits = ["#define fn(x) (42 + x)"],
878 )
879 fn1 = rffi.llexternal('fn', [rffi.INT], rffi.INT,
880 compilation_info=eci, macro=True)
881 fn2 = rffi.llexternal('fn2', [rffi.DOUBLE], rffi.DOUBLE,
882 compilation_info=eci, macro='fn')
883 res = fn1(10)
884 assert res == 52
885 res = fn2(10.5)
886 assert res == 52.5
887
888 def test_prebuilt_constant(self):
889 header = py.code.Source("""
890 #ifndef _SOME_H
891 #define _SOME_H
892
893 #include <stdlib.h>
894
895 static long x = 3;
896 static int y = 5;
897 char **z = NULL;
898
899 #endif /* _SOME_H */
900 """)
901 h_file = udir.join("some_h.h")
902 h_file.write(header)
903
904 eci = ExternalCompilationInfo(includes=['stdio.h', str(h_file.basename)],
905 include_dirs=[str(udir)])
906
907 get_x, set_x = rffi.CExternVariable(rffi.LONG, 'x', eci, c_type='long')
908 get_y, set_y = rffi.CExternVariable(rffi.INT, 'y', eci, c_type='int')
909 get_z, set_z = rffi.CExternVariable(rffi.CCHARPP, 'z', eci)
910
911 def f():
912 one = get_x()
913 set_x(13)
914 return one + get_x()
915
916 def fy():
917 one = rffi.cast(rffi.LONG, get_y())
918 set_y(rffi.cast(rffi.INT, 13))
919 return one + rffi.cast(rffi.LONG, get_y())
920
921 def g():
922 l = rffi.liststr2charpp(["a", "b", "c"])
923 try:
924 set_z(l)
925 return rffi.charp2str(get_z()[2])
926 finally:
927 rffi.free_charpp(l)
928
929 res = f()
930 assert res == 16
931 res = fy()
932 assert res == 18
933 res = g()
934 assert res == "c"
935
936 def test_c_callback(self):
937 c_source = py.code.Source("""
938 #include "src/precommondefs.h"
939
940 RPY_EXPORTED
941 int eating_callback(int arg, int(*call)(int))
942 {
943 return call(arg);
944 }
945 """)
946
947 eci = ExternalCompilationInfo(include_dirs=[cdir],
948 separate_module_sources=[c_source])
949
950 args = [rffi.INT, rffi.CCallback([rffi.INT], rffi.INT)]
951 eating_callback = rffi.llexternal('eating_callback', args, rffi.INT,
952 compilation_info=eci)
953
954 def g(i):
955 return i + 3
956
957 def f():
958 return eating_callback(3, g)
959
960 assert f() == 6
961
962 def test_qsort_callback(self):
963 TP = rffi.CArrayPtr(rffi.INT)
964 a = lltype.malloc(TP.TO, 5, flavor='raw')
965 a[0] = rffi.r_int(5)
966 a[1] = rffi.r_int(3)
967 a[2] = rffi.r_int(2)
968 a[3] = rffi.r_int(1)
969 a[4] = rffi.r_int(4)
970
971 def compare(a, b):
972 # do not use a,b directly! on a big endian machine
973 # ((void*)ptr)[0] will return 0x0 if the 32 bit value
974 # ptr points to is 0x1
975 a = rffi.cast(rffi.INTP, a)
976 b = rffi.cast(rffi.INTP, b)
977 if a[0] > b[0]:
978 return rffi.r_int(1)
979 else:
980 return rffi.r_int(-1)
981
982 CALLBACK = rffi.CCallback([rffi.VOIDP, rffi.VOIDP], rffi.INT)
983 qsort = rffi.llexternal('qsort', [rffi.VOIDP, rffi.SIZE_T,
984 rffi.SIZE_T, CALLBACK], lltype.Void)
985
986 qsort(rffi.cast(rffi.VOIDP, a), 5, rffi.sizeof(rffi.INT), compare)
987 for i in range(5):
988 assert a[i] == i + 1
989 lltype.free(a, flavor='raw')
990
991 def test_array_type_bug(self):
992 A = lltype.Array(rffi.LONG)
993 a1 = lltype.malloc(A, 0, flavor='raw')
994 a2 = lltype.malloc(A, 0, flavor='raw')
995 c1 = lltype2ctypes(a1)
996 c2 = lltype2ctypes(a2)
997 assert type(c1) is type(c2)
998 lltype.free(a1, flavor='raw')
999 lltype.free(a2, flavor='raw')
1000 assert not ALLOCATED # detects memory leaks in the test
1001
1002 def test_varsized_struct(self):
1003 S = lltype.Struct('S', ('x', lltype.Signed),
1004 ('a', lltype.Array(lltype.Char)))
1005 s1 = lltype.malloc(S, 6, flavor='raw')
1006 s1.x = 5
1007 s1.a[2] = 'F'
1008 sc = lltype2ctypes(s1, normalize=False)
1009 assert isinstance(sc.contents, ctypes.Structure)
1010 assert sc.contents.x == 5
1011 assert sc.contents.a.length == 6
1012 assert sc.contents.a.items[2] == ord('F')
1013 sc.contents.a.items[3] = ord('P')
1014 assert s1.a[3] == 'P'
1015 s1.a[1] = 'y'
1016 assert sc.contents.a.items[1] == ord('y')
1017 # now go back to lltype...
1018 res = ctypes2lltype(lltype.Ptr(S), sc)
1019 assert res == s1
1020 assert res.x == 5
1021 assert len(res.a) == 6
1022 lltype.free(s1, flavor='raw')
1023 assert not ALLOCATED # detects memory leaks in the test
1024
1025 def test_with_explicit_length(self):
1026 A = lltype.Array(lltype.Signed)
1027 a1 = lltype.malloc(A, 5, flavor='raw')
1028 a1[0] = 42
1029 c1 = lltype2ctypes(a1, normalize=False)
1030 assert c1.contents.length == 5
1031 assert c1.contents.items[0] == 42
1032 res = ctypes2lltype(lltype.Ptr(A), c1)
1033 assert res == a1
1034 assert len(res) == 5
1035 assert res[0] == 42
1036 res[0] += 1
1037 assert c1.contents.items[0] == 43
1038 assert a1[0] == 43
1039 a1[0] += 2
1040 assert c1.contents.items[0] == 45
1041 assert a1[0] == 45
1042 c1.contents.items[0] += 3
1043 assert res[0] == 48
1044 assert a1[0] == 48
1045 lltype.free(a1, flavor='raw')
1046 assert not ALLOCATED # detects memory leaks in the test
1047
1048 def test_c_callback_with_void_arg_2(self):
1049 ftest = []
1050 def f(x):
1051 ftest.append(x)
1052 F = lltype.FuncType([lltype.Void], lltype.Void)
1053 fn = lltype.functionptr(F, 'askjh', _callable=f, _void0=-5)
1054 fn(-5)
1055 assert ftest == [-5]
1056 fn2 = lltype2ctypes(fn)
1057 fn2()
1058 assert ftest == [-5, -5]
1059 fn3 = ctypes2lltype(lltype.Ptr(F), fn2)
1060 fn3(-5)
1061 assert ftest == [-5, -5, -5]
1062
1063 def test_c_callback_with_void_arg_3(self):
1064 from rpython.rtyper.lltypesystem.rstr import LLHelpers
1065 def f(i):
1066 x = 'X' * i
1067 return x[-2]
1068 a = RPythonAnnotator()
1069 r = a.build_types(f, [int])
1070 rtyper = RPythonTyper(a)
1071 rtyper.specialize()
1072 a.translator.rtyper = rtyper
1073 graph = a.translator.graphs[0]
1074 op = graph.startblock.operations[-1]
1075 assert op.opname == 'direct_call'
1076 assert op.args[0].value._obj._callable == LLHelpers.ll_stritem.im_func
1077 assert op.args[1].value == LLHelpers
1078 assert op.args[3].value == -2
1079
1080 def test_recursive_struct_more(self):
1081 NODE = lltype.ForwardReference()
1082 NODE.become(lltype.Struct('NODE', ('value', rffi.LONG),
1083 ('next', lltype.Ptr(NODE))))
1084 CNODEPTR = get_ctypes_type(NODE)
1085 pc = CNODEPTR()
1086 pc.value = 42
1087 pc.next = ctypes.pointer(pc)
1088 p = ctypes2lltype(lltype.Ptr(NODE), ctypes.pointer(pc))
1089 assert p.value == 42
1090 assert p.next == p
1091 pc2 = lltype2ctypes(p)
1092 assert pc2.contents.value == 42
1093 assert pc2.contents.next.contents.value == 42
1094
1095 def test_indirect_recursive_struct_more(self):
1096 NODE = lltype.ForwardReference()
1097 NODE2 = lltype.Struct('NODE2', ('ping', lltype.Ptr(NODE)))
1098 NODE.become(lltype.Struct('NODE', ('pong', NODE2)))
1099
1100 # Building NODE2 first used to fail.
1101 get_ctypes_type(NODE2)
1102
1103 CNODEPTR = get_ctypes_type(NODE)
1104 pc = CNODEPTR()
1105 pc.pong.ping = ctypes.pointer(pc)
1106 p = ctypes2lltype(lltype.Ptr(NODE), ctypes.pointer(pc))
1107 assert p.pong.ping == p
1108
1109 def test_typedef(self):
1110 assert ctypes2lltype(lltype.Typedef(rffi.LONG, 'test'), 6) == 6
1111 assert ctypes2lltype(lltype.Typedef(lltype.Float, 'test2'), 3.4) == 3.4
1112
1113 assert get_ctypes_type(rffi.LONG) == get_ctypes_type(
1114 lltype.Typedef(rffi.LONG, 'test3'))
1115
1116 def test_cast_adr_to_int(self):
1117 class someaddr(object):
1118 def _cast_to_int(self):
1119 return sys.maxint/2 * 3
1120
1121 res = cast_adr_to_int(someaddr())
1122 assert is_valid_int(res)
1123 assert res == -sys.maxint/2 - 3
1124
1125 def test_cast_gcref_back_and_forth(self):
1126 NODE = lltype.GcStruct('NODE')
1127 node = lltype.malloc(NODE)
1128 ref = lltype.cast_opaque_ptr(llmemory.GCREF, node)
1129 back = rffi.cast(llmemory.GCREF, rffi.cast(lltype.Signed, ref))
1130 assert lltype.cast_opaque_ptr(lltype.Ptr(NODE), back) == node
1131
1132 def test_gcref_forth_and_back(self):
1133 cp = ctypes.c_void_p(1234)
1134 v = ctypes2lltype(llmemory.GCREF, cp)
1135 assert lltype2ctypes(v).value == cp.value
1136 v1 = ctypes2lltype(llmemory.GCREF, cp)
1137 assert v == v1
1138 assert v
1139 v2 = ctypes2lltype(llmemory.GCREF, ctypes.c_void_p(1235))
1140 assert v2 != v
1141
1142 def test_gcref_type(self):
1143 NODE = lltype.GcStruct('NODE')
1144 node = lltype.malloc(NODE)
1145 ref = lltype.cast_opaque_ptr(llmemory.GCREF, node)
1146 v = lltype2ctypes(ref)
1147 assert isinstance(v, ctypes.c_void_p)
1148
1149 def test_gcref_null(self):
1150 ref = lltype.nullptr(llmemory.GCREF.TO)
1151 v = lltype2ctypes(ref)
1152 assert isinstance(v, ctypes.c_void_p)
1153
1154 def test_cast_null_gcref(self):
1155 ref = lltype.nullptr(llmemory.GCREF.TO)
1156 value = rffi.cast(lltype.Signed, ref)
1157 assert value == 0
1158
1159 def test_cast_null_fakeaddr(self):
1160 ref = llmemory.NULL
1161 value = rffi.cast(lltype.Signed, ref)
1162 assert value == 0
1163
1164 def test_gcref_truth(self):
1165 p0 = ctypes.c_void_p(0)
1166 ref0 = ctypes2lltype(llmemory.GCREF, p0)
1167 assert not ref0
1168
1169 p1234 = ctypes.c_void_p(1234)
1170 ref1234 = ctypes2lltype(llmemory.GCREF, p1234)
1171 assert p1234
1172
1173 def test_gcref_casts(self):
1174 p0 = ctypes.c_void_p(0)
1175 ref0 = ctypes2lltype(llmemory.GCREF, p0)
1176
1177 assert lltype.cast_ptr_to_int(ref0) == 0
1178 assert llmemory.cast_ptr_to_adr(ref0) == llmemory.NULL
1179
1180 NODE = lltype.GcStruct('NODE')
1181 assert lltype.cast_opaque_ptr(lltype.Ptr(NODE), ref0) == lltype.nullptr(NODE)
1182
1183 node = lltype.malloc(NODE)
1184 ref1 = lltype.cast_opaque_ptr(llmemory.GCREF, node)
1185
1186 intval = rffi.cast(lltype.Signed, node)
1187 intval1 = rffi.cast(lltype.Signed, ref1)
1188
1189 assert intval == intval1
1190
1191 ref2 = ctypes2lltype(llmemory.GCREF, intval1)
1192
1193 assert lltype.cast_opaque_ptr(lltype.Ptr(NODE), ref2) == node
1194
1195 #addr = llmemory.cast_ptr_to_adr(ref1)
1196 #assert llmemory.cast_adr_to_int(addr) == intval
1197
1198 #assert lltype.cast_ptr_to_int(ref1) == intval
1199
1200 x = rffi.cast(llmemory.GCREF, -17)
1201 assert lltype.cast_ptr_to_int(x) == -17
1202
1203 def test_ptr_truth(self):
1204 abc = rffi.cast(lltype.Ptr(lltype.FuncType([], lltype.Void)), 0)
1205 assert not abc
1206
1207 def test_mixed_gcref_comparison(self):
1208 NODE = lltype.GcStruct('NODE')
1209 node = lltype.malloc(NODE)
1210 ref1 = lltype.cast_opaque_ptr(llmemory.GCREF, node)
1211 ref2 = rffi.cast(llmemory.GCREF, 123)
1212
1213 assert ref1 != ref2
1214 assert not (ref1 == ref2)
1215
1216 assert ref2 != ref1
1217 assert not (ref2 == ref1)
1218
1219 assert node._obj._storage is True
1220
1221 # forced!
1222 rffi.cast(lltype.Signed, ref1)
1223 assert node._obj._storage not in (True, None)
1224
1225 assert ref1 != ref2
1226 assert not (ref1 == ref2)
1227
1228 assert ref2 != ref1
1229 assert not (ref2 == ref1)
1230
1231 def test_gcref_comparisons_back_and_forth(self):
1232 NODE = lltype.GcStruct('NODE')
1233 node = lltype.malloc(NODE)
1234 ref1 = lltype.cast_opaque_ptr(llmemory.GCREF, node)
1235 numb = rffi.cast(lltype.Signed, ref1)
1236 ref2 = rffi.cast(llmemory.GCREF, numb)
1237 assert ref1 == ref2
1238 assert ref2 == ref1
1239 assert not (ref1 != ref2)
1240 assert not (ref2 != ref1)
1241
1242 def test_convert_subarray(self):
1243 A = lltype.GcArray(lltype.Signed)
1244 a = lltype.malloc(A, 20)
1245 inside = lltype.direct_ptradd(lltype.direct_arrayitems(a), 3)
1246
1247 lltype2ctypes(inside)
1248
1249 start = rffi.cast(lltype.Signed, lltype.direct_arrayitems(a))
1250 inside_int = rffi.cast(lltype.Signed, inside)
1251
1252 assert inside_int == start+rffi.sizeof(lltype.Signed)*3
1253
1254 def test_gcref_comparisons_through_addresses(self):
1255 NODE = lltype.GcStruct('NODE')
1256 n0 = lltype.malloc(NODE)
1257 adr0 = llmemory.cast_ptr_to_adr(n0)
1258
1259 n1 = lltype.malloc(NODE)
1260 i1 = rffi.cast(lltype.Signed, n1)
1261 ref1 = rffi.cast(llmemory.GCREF, i1)
1262 adr1 = llmemory.cast_ptr_to_adr(ref1)
1263
1264 assert adr1 != adr0
1265 assert adr0 != adr1
1266
1267 adr1_2 = llmemory.cast_ptr_to_adr(n1)
1268
1269 #import pdb; pdb.set_trace()
1270 assert adr1_2 == adr1
1271 assert adr1 == adr1_2
1272
1273 def test_object_subclass(self):
1274 from rpython.rtyper import rclass
1275 from rpython.rtyper.annlowlevel import cast_instance_to_base_ptr
1276 from rpython.rtyper.annlowlevel import cast_base_ptr_to_instance
1277 class S:
1278 pass
1279 def f(n):
1280 s = S()
1281 s.x = n
1282 ls = cast_instance_to_base_ptr(s)
1283 as_num = rffi.cast(lltype.Signed, ls)
1284 # --- around this point, only 'as_num' is passed
1285 t = rffi.cast(rclass.OBJECTPTR, as_num)
1286 u = cast_base_ptr_to_instance(S, t)
1287 return u.x
1288 res = interpret(f, [123])
1289 assert res == 123
1290
1291 def test_object_subclass_2(self):
1292 from rpython.rtyper import rclass
1293 SCLASS = lltype.GcStruct('SCLASS',
1294 ('parent', rclass.OBJECT),
1295 ('n', lltype.Signed))
1296 sclass_vtable = lltype.malloc(rclass.OBJECT_VTABLE, zero=True,
1297 immortal=True)
1298 sclass_vtable.name = rclass.alloc_array_name('SClass')
1299 def f(n):
1300 rclass.declare_type_for_typeptr(sclass_vtable, SCLASS)
1301 s = lltype.malloc(SCLASS)
1302 s.parent.typeptr = sclass_vtable
1303 s.n = n
1304 as_num = rffi.cast(lltype.Signed, s)
1305 # --- around this point, only 'as_num' is passed
1306 t = rffi.cast(lltype.Ptr(SCLASS), as_num)
1307 return t.n
1308 res = interpret(f, [123])
1309 assert res == 123
1310
1311 def test_object_subclass_3(self):
1312 from rpython.rtyper import rclass
1313 from rpython.rtyper.annlowlevel import cast_instance_to_base_ptr
1314 from rpython.rtyper.annlowlevel import cast_base_ptr_to_instance
1315 class S:
1316 pass
1317 def f(n):
1318 s = S()
1319 s.x = n
1320 ls = cast_instance_to_base_ptr(s)
1321 as_num = rffi.cast(lltype.Signed, ls)
1322 # --- around this point, only 'as_num' is passed
1323 r = rffi.cast(llmemory.GCREF, as_num)
1324 t = lltype.cast_opaque_ptr(rclass.OBJECTPTR, r)
1325 u = cast_base_ptr_to_instance(S, t)
1326 return u.x
1327 res = interpret(f, [123])
1328 assert res == 123
1329
1330 def test_object_subclass_4(self):
1331 from rpython.rtyper import rclass
1332 SCLASS = lltype.GcStruct('SCLASS',
1333 ('parent', rclass.OBJECT),
1334 ('n', lltype.Signed))
1335 sclass_vtable = lltype.malloc(rclass.OBJECT_VTABLE, zero=True,
1336 immortal=True)
1337 sclass_vtable.name = rclass.alloc_array_name('SClass')
1338 def f(n):
1339 rclass.declare_type_for_typeptr(sclass_vtable, SCLASS)
1340 s = lltype.malloc(SCLASS)
1341 s.parent.typeptr = sclass_vtable
1342 s.n = n
1343 as_num = rffi.cast(lltype.Signed, s)
1344 # --- around this point, only 'as_num' is passed
1345 r = rffi.cast(llmemory.GCREF, as_num)
1346 t = lltype.cast_opaque_ptr(lltype.Ptr(SCLASS), r)
1347 return t.n
1348 res = interpret(f, [123])
1349 assert res == 123
1350
1351 def test_object_subclass_5(self):
1352 from rpython.rtyper import rclass
1353 from rpython.rtyper.annlowlevel import cast_instance_to_base_ptr
1354 from rpython.rtyper.annlowlevel import cast_base_ptr_to_instance
1355 class S:
1356 x = 5 # entry in the vtable
1357 class T(S):
1358 x = 6
1359 def f():
1360 s = T()
1361 ls = cast_instance_to_base_ptr(s)
1362 as_num = rffi.cast(lltype.Signed, ls)
1363 # --- around this point, only 'as_num' is passed
1364 t = rffi.cast(rclass.OBJECTPTR, as_num)
1365 u = cast_base_ptr_to_instance(S, t)
1366 return u.x
1367 res = interpret(f, [])
1368 assert res == 6
1369
1370 def test_force_to_int(self):
1371 S = lltype.Struct('S')
1372 p = lltype.malloc(S, flavor='raw')
1373 a = llmemory.cast_ptr_to_adr(p)
1374 i = llmemory.cast_adr_to_int(a, "forced")
1375 assert is_valid_int(i)
1376 assert i == llmemory.cast_adr_to_int(a, "forced")
1377 lltype.free(p, flavor='raw')
1378
1379 def test_freelist(self):
1380 S = lltype.Struct('S', ('x', lltype.Signed), ('y', lltype.Signed))
1381 SP = lltype.Ptr(S)
1382 chunk = lltype.malloc(rffi.CArrayPtr(S).TO, 10, flavor='raw')
1383 assert lltype.typeOf(chunk) == rffi.CArrayPtr(S)
1384 free_list = lltype.nullptr(rffi.VOIDP.TO)
1385 # build list
1386 current = chunk
1387 for i in range(10):
1388 rffi.cast(rffi.VOIDPP, current)[0] = free_list
1389 free_list = rffi.cast(rffi.VOIDP, current)
1390 current = rffi.ptradd(current, 1)
1391 # get one
1392 p = free_list
1393 free_list = rffi.cast(rffi.VOIDPP, p)[0]
1394 rffi.cast(SP, p).x = 0
1395 # get two
1396 p = free_list
1397 free_list = rffi.cast(rffi.VOIDPP, p)[0]
1398 rffi.cast(SP, p).x = 0
1399 # get three
1400 p = free_list
1401 free_list = rffi.cast(rffi.VOIDPP, p)[0]
1402 rffi.cast(SP, p).x = 0
1403 lltype.free(chunk, flavor='raw')
1404
1405 def test_opaque_tagged_pointers(self):
1406 from rpython.rtyper.annlowlevel import cast_base_ptr_to_instance
1407 from rpython.rtyper.annlowlevel import cast_instance_to_base_ptr
1408 from rpython.rtyper import rclass
1409
1410 class Opaque(object):
1411 llopaque = True
1412
1413 def hide(self):
1414 ptr = cast_instance_to_base_ptr(self)
1415 return lltype.cast_opaque_ptr(llmemory.GCREF, ptr)
1416
1417 @staticmethod
1418 def show(gcref):
1419 ptr = lltype.cast_opaque_ptr(lltype.Ptr(rclass.OBJECT), gcref)
1420 return cast_base_ptr_to_instance(Opaque, ptr)
1421
1422 opaque = Opaque()
1423 round = ctypes2lltype(llmemory.GCREF, lltype2ctypes(opaque.hide()))
1424 assert Opaque.show(round) is opaque
1425
1426 def test_array_of_structs(self):
1427 A = lltype.GcArray(lltype.Struct('x', ('v', lltype.Signed)))
1428 a = lltype.malloc(A, 5)
1429 a2 = ctypes2lltype(lltype.Ptr(A), lltype2ctypes(a))
1430 assert a2._obj.getitem(0)._obj._parentstructure() is a2._obj
1431
1432 def test_array_of_function_pointers(self):
1433 c_source = py.code.Source(r"""
1434 #include "src/precommondefs.h"
1435 #include <stdio.h>
1436
1437 typedef int(*funcptr_t)(void);
1438 static int forty_two(void) { return 42; }
1439 static int forty_three(void) { return 43; }
1440 static funcptr_t testarray[2];
1441 RPY_EXPORTED void runtest(void cb(funcptr_t *)) {
1442 testarray[0] = &forty_two;
1443 testarray[1] = &forty_three;
1444 fprintf(stderr, "&forty_two = %p\n", testarray[0]);
1445 fprintf(stderr, "&forty_three = %p\n", testarray[1]);
1446 cb(testarray);
1447 testarray[0] = 0;
1448 testarray[1] = 0;
1449 }
1450 """)
1451 eci = ExternalCompilationInfo(include_dirs=[cdir],
1452 separate_module_sources=[c_source])
1453
1454 PtrF = lltype.Ptr(lltype.FuncType([], rffi.INT))
1455 ArrayPtrF = rffi.CArrayPtr(PtrF)
1456 CALLBACK = rffi.CCallback([ArrayPtrF], lltype.Void)
1457
1458 runtest = rffi.llexternal('runtest', [CALLBACK], lltype.Void,
1459 compilation_info=eci)
1460 seen = []
1461
1462 def callback(testarray):
1463 seen.append(testarray[0]) # read a PtrF out of testarray
1464 seen.append(testarray[1])
1465
1466 runtest(callback)
1467 assert seen[0]() == 42
1468 assert seen[1]() == 43
1469
1470 def test_keep_value_across_lltype_callable(self):
1471 PtrF = lltype.Ptr(lltype.FuncType([], lltype.Void))
1472 f = rffi.cast(PtrF, 42)
1473 assert lltype.typeOf(f) == PtrF
1474 assert rffi.cast(lltype.Signed, f) == 42
1475
1476 def test_keep_value_across_rffi_llexternal(self):
1477 c_source = py.code.Source(r"""
1478 void ff1(void) { }
1479 void *get_ff1(void) { return &ff1; }
1480 """)
1481 eci = ExternalCompilationInfo(
1482 separate_module_sources=[c_source],
1483 post_include_bits = [
1484 "RPY_EXTERN void ff1(void); RPY_EXTERN void *get_ff1(void);"])
1485 PtrFF1 = lltype.Ptr(lltype.FuncType([], lltype.Void))
1486 f1 = rffi.llexternal('ff1', [], lltype.Void, compilation_info=eci,
1487 _nowrapper=True)
1488 assert lltype.typeOf(f1) == PtrFF1
1489 getff1 = rffi.llexternal('get_ff1', [], PtrFF1, compilation_info=eci,
1490 _nowrapper=True)
1491 f2 = getff1()
1492 assert rffi.cast(lltype.Signed, f2) == rffi.cast(lltype.Signed, f1)
1493 #assert f2 == f1 -- fails, would be nice but oh well
1494
1495 def test_variadic_call(self):
1496 c_source = py.code.Source("""
1497 #include <stdio.h>
1498 #include <stdarg.h>
1499
1500 long variadic_sum(long n, ...) {
1501 va_list ptr;
1502 int sum = 0;
1503 printf("n: %ld\\n", n);
1504
1505 va_start(ptr, n);
1506 for (int i = 0; i < n; i++) {
1507 long foo = va_arg(ptr, long);
1508 sum += foo;
1509 printf("Arg %d: %ld\\n", i, foo);
1510 }
1511 va_end(ptr);
1512 return sum;
1513 }
1514 """)
1515 eci = ExternalCompilationInfo(
1516 separate_module_sources=[c_source],
1517 post_include_bits=[
1518 'RPY_EXTERN long variadic_sum(long n, ...);'
1519 ])
1520 variadic_sum = rffi.llexternal('variadic_sum', [lltype.Signed] * 4,
1521 lltype.Signed, compilation_info=eci, natural_arity=1)
1522 assert variadic_sum(3, 1, 20, 300) == 321
1523
1524
1525 class TestPlatform(object):
1526 def test_lib_on_libpaths(self):
1527 from rpython.translator.platform import platform
1528
1529 tmpdir = udir.join('lib_on_libppaths')
1530 tmpdir.ensure(dir=1)
1531 c_file = tmpdir.join('c_file.c')
1532 c_file.write('''
1533 #include "src/precommondefs.h"
1534 RPY_EXPORTED int f(int a, int b) { return (a + b); }
1535 ''')
1536 eci = ExternalCompilationInfo(include_dirs=[cdir])
1537 so = platform.compile([c_file], eci, standalone=False)
1538 eci = ExternalCompilationInfo(
1539 libraries = ['c_file'],
1540 library_dirs = [str(so.dirpath())]
1541 )
1542 f = rffi.llexternal('f', [rffi.INT, rffi.INT], rffi.INT,
1543 compilation_info=eci)
1544 assert f(3, 4) == 7
1545
1546 def test_prefix(self):
1547
1548 if not sys.platform.startswith('linux'):
1549 py.test.skip("Not supported")
1550
1551 from rpython.translator.platform import platform
1552
1553 tmpdir = udir.join('lib_on_libppaths_prefix')
1554 tmpdir.ensure(dir=1)
1555 c_file = tmpdir.join('c_file.c')
1556 c_file.write('''
1557 #include "src/precommondefs.h"
1558 RPY_EXPORTED int f(int a, int b) { return (a + b); }
1559 ''')
1560 eci = ExternalCompilationInfo(include_dirs=[cdir])
1561 so = platform.compile([c_file], eci, standalone=False)
1562 sopath = py.path.local(so)
1563 sopath.move(sopath.dirpath().join('libc_file.so'))
1564 eci = ExternalCompilationInfo(
1565 libraries = ['c_file'],
1566 library_dirs = [str(so.dirpath())]
1567 )
1568 f = rffi.llexternal('f', [rffi.INT, rffi.INT], rffi.INT,
1569 compilation_info=eci)
1570 assert f(3, 4) == 7
1571
1572 def test_llgcopaque_eq(self):
1573 assert _llgcopaque(1) != None
1574 assert _llgcopaque(0) == None
1575
1576 def test_array_of_struct(self):
1577 A2 = lltype.Array(('a', lltype.Signed), ('b', lltype.Signed))
1578 a = lltype.malloc(A2, 10, flavor='raw')
1579 a[3].b = 42
1580 ac = lltype2ctypes(a[3])
1581 assert ac.contents.b == 42
1582 ac.contents.a = 17
1583 assert a[3].a == 17
1584 #lltype.free(a, flavor='raw')
1585 py.test.skip("free() not working correctly here...")
1586
1587 def test_fixedsizedarray_to_ctypes(self):
1588 T = lltype.Ptr(rffi.CFixedArray(rffi.INT, 1))
1589 inst = lltype.malloc(T.TO, flavor='raw')
1590 inst[0] = rffi.cast(rffi.INT, 42)
1591 assert inst[0] == 42
1592 cinst = lltype2ctypes(inst)
1593 assert rffi.cast(lltype.Signed, inst[0]) == 42
1594 assert cinst.contents.item0 == 42
1595 lltype.free(inst, flavor='raw')
1596
1597 def test_fixedsizedarray_to_ctypes(self):
1598 T = lltype.Ptr(rffi.CFixedArray(rffi.CHAR, 123))
1599 inst = lltype.malloc(T.TO, flavor='raw', zero=True)
1600 cinst = lltype2ctypes(inst)
1601 assert cinst.contents.item0 == 0
1602 lltype.free(inst, flavor='raw')