Debian Codegraph @

extra_tests/cffi_tests/cffi1/test_function_args.py

raw symbols SCIP
1 # Generated by pypy/tool/import_cffi.py
2 import pytest, sys
3 try:
4 # comment out the following line to run this test.
5 # the latest on x86-64 linux: https://github.com/libffi/libffi/issues/574
6 if sys.platform != 'win32':
7 raise ImportError("this test is skipped because it keeps finding "
8 "failures in libffi, instead of cffi")
9
10 from hypothesis import given, settings, example
11 from hypothesis import strategies as st
12 except ImportError as e:
13 e1 = e
14 def test_types():
15 pytest.skip(str(e1))
16 else:
17
18 from cffi import FFI
19 import sys, random
20 from .test_recompiler import verify
21
22 ALL_PRIMITIVES = [
23 'unsigned char',
24 'short',
25 'int',
26 'long',
27 'long long',
28 'float',
29 'double',
30 #'long double', --- on x86 it can give libffi crashes
31 ]
32 def _make_struct(s):
33 return st.lists(s, min_size=1)
34 types = st.one_of(st.sampled_from(ALL_PRIMITIVES),
35 st.lists(st.sampled_from(ALL_PRIMITIVES), min_size=1))
36 # NB. 'types' could be st.recursive instead, but it doesn't
37 # really seem useful
38
39 def draw_primitive(ffi, typename):
40 value = random.random() * 2**40
41 if typename != 'long double':
42 return ffi.cast(typename, value)
43 else:
44 return value
45
46 TEST_RUN_COUNTER = 0
47
48
49 @given(st.lists(types), types)
50 @settings(max_examples=100, deadline=5000) # 5000ms
51 def test_types(tp_args, tp_result):
52 global TEST_RUN_COUNTER
53 print(tp_args, tp_result)
54 cdefs = []
55 structs = {}
56
57 def build_type(tp):
58 if type(tp) is list:
59 field_types = [build_type(tp1) for tp1 in tp]
60 fields = ['%s f%d;' % (ftp, j)
61 for (j, ftp) in enumerate(field_types)]
62 fields = '\n '.join(fields)
63 name = 's%d' % len(cdefs)
64 cdefs.append("typedef struct {\n %s\n} %s;" % (fields, name))
65 structs[name] = field_types
66 return name
67 else:
68 return tp
69
70 args = [build_type(tp) for tp in tp_args]
71 result = build_type(tp_result)
72
73 TEST_RUN_COUNTER += 1
74 signature = "%s testfargs(%s)" % (result,
75 ', '.join(['%s a%d' % (arg, i) for (i, arg) in enumerate(args)])
76 or 'void')
77
78 source = list(cdefs)
79
80 cdefs.append("%s;" % signature)
81 cdefs.append("extern %s testfargs_result;" % result)
82 for i, arg in enumerate(args):
83 cdefs.append("extern %s testfargs_arg%d;" % (arg, i))
84 source.append("%s testfargs_result;" % result)
85 for i, arg in enumerate(args):
86 source.append("%s testfargs_arg%d;" % (arg, i))
87 source.append(signature)
88 source.append("{")
89 for i, arg in enumerate(args):
90 source.append(" testfargs_arg%d = a%d;" % (i, i))
91 source.append(" return testfargs_result;")
92 source.append("}")
93
94 typedef_line = "typedef %s;" % (signature.replace('testfargs',
95 '(*mycallback_t)'),)
96 assert signature.endswith(')')
97 sig_callback = "%s testfcallback(mycallback_t callback)" % result
98 cdefs.append(typedef_line)
99 cdefs.append("%s;" % sig_callback)
100 source.append(typedef_line)
101 source.append(sig_callback)
102 source.append("{")
103 source.append(" return callback(%s);" %
104 ', '.join(["testfargs_arg%d" % i for i in range(len(args))]))
105 source.append("}")
106
107 ffi = FFI()
108 ffi.cdef("\n".join(cdefs))
109 lib = verify(ffi, 'test_function_args_%d' % TEST_RUN_COUNTER,
110 "\n".join(source), no_cpp=True)
111
112 # when getting segfaults, enable this:
113 if False:
114 from extra_tests.cffi_tests.udir import udir
115 import subprocess
116 f = open(str(udir.join('run1.py')), 'w')
117 f.write('import sys; sys.path = %r\n' % (sys.path,))
118 f.write('from _CFFI_test_function_args_%d import ffi, lib\n' %
119 TEST_RUN_COUNTER)
120 for i in range(len(args)):
121 f.write('a%d = ffi.new("%s *")\n' % (i, args[i]))
122 aliststr = ', '.join(['a%d[0]' % i for i in range(len(args))])
123 f.write('lib.testfargs(%s)\n' % aliststr)
124 f.write('ffi.addressof(lib, "testfargs")(%s)\n' % aliststr)
125 f.close()
126 print("checking for segfault for direct call...")
127 rc = subprocess.call([sys.executable, 'run1.py'], cwd=str(udir))
128 assert rc == 0, rc
129
130 def make_arg(tp):
131 if tp in structs:
132 return [make_arg(tp1) for tp1 in structs[tp]]
133 else:
134 return draw_primitive(ffi, tp)
135
136 passed_args = [make_arg(arg) for arg in args]
137 returned_value = make_arg(result)
138
139 def write(p, v):
140 if type(v) is list:
141 for i, v1 in enumerate(v):
142 write(ffi.addressof(p, 'f%d' % i), v1)
143 else:
144 p[0] = v
145
146 write(ffi.addressof(lib, 'testfargs_result'), returned_value)
147
148 ## CALL forcing libffi
149 print("CALL forcing libffi")
150 received_return = ffi.addressof(lib, 'testfargs')(*passed_args)
151 ##
152
153 _tp_long_double = ffi.typeof("long double")
154 def check(p, v):
155 if type(v) is list:
156 for i, v1 in enumerate(v):
157 check(ffi.addressof(p, 'f%d' % i), v1)
158 else:
159 if ffi.typeof(p).item is _tp_long_double:
160 assert ffi.cast("double", p[0]) == v
161 else:
162 assert p[0] == v
163
164 for i, arg in enumerate(passed_args):
165 check(ffi.addressof(lib, 'testfargs_arg%d' % i), arg)
166 ret = ffi.new(result + "*", received_return)
167 check(ret, returned_value)
168
169 ## CALLBACK
170 def expand(value):
171 if isinstance(value, ffi.CData):
172 t = ffi.typeof(value)
173 if t is _tp_long_double:
174 return float(ffi.cast("double", value))
175 return [expand(getattr(value, 'f%d' % i))
176 for i in range(len(t.fields))]
177 else:
178 return value
179
180 # when getting segfaults, enable this:
181 if False:
182 from extra_tests.cffi_tests.udir import udir
183 import subprocess
184 f = open(str(udir.join('run1.py')), 'w')
185 f.write('import sys; sys.path = %r\n' % (sys.path,))
186 f.write('from _CFFI_test_function_args_%d import ffi, lib\n' %
187 TEST_RUN_COUNTER)
188 f.write('def callback(*args): return ffi.new("%s *")[0]\n' % result)
189 f.write('fptr = ffi.callback("%s(%s)", callback)\n' % (result,
190 ','.join(args)))
191 f.write('print(lib.testfcallback(fptr))\n')
192 f.close()
193 print("checking for segfault for callback...")
194 rc = subprocess.call([sys.executable, 'run1.py'], cwd=str(udir))
195 assert rc == 0, rc
196
197 seen_args = []
198 def callback(*args):
199 seen_args.append([expand(arg) for arg in args])
200 return returned_value
201
202 fptr = ffi.callback("%s(%s)" % (result, ','.join(args)), callback)
203 print("CALL with callback")
204 received_return = lib.testfcallback(fptr)
205
206 assert len(seen_args) == 1
207 assert passed_args == seen_args[0]
208 ret = ffi.new(result + "*", received_return)
209 check(ret, returned_value)