Debian Codegraph @

rpython/translator/c/test/test_standalone.py

raw symbols SCIP
1 import py
2 import sys, os, re
3 import textwrap
4
5 from rpython.config.translationoption import get_combined_translation_config
6 from rpython.config.translationoption import SUPPORT__THREAD
7 from rpython.rlib.objectmodel import keepalive_until_here
8 from rpython.rlib.rarithmetic import r_longlong
9 from rpython.rlib.debug import ll_assert, have_debug_prints, debug_flush
10 from rpython.rlib.debug import debug_print, debug_start, debug_stop
11 from rpython.rlib.debug import debug_offset, have_debug_prints_for
12 from rpython.rlib.entrypoint import entrypoint_highlevel, secondary_entrypoints
13 from rpython.rtyper.lltypesystem import lltype
14 from rpython.translator.translator import TranslationContext
15 from rpython.translator.backendopt import all
16 from rpython.translator.c.genc import CStandaloneBuilder, ExternalCompilationInfo
17 from rpython.annotator.listdef import s_list_of_strings
18 from rpython.tool.udir import udir
19 from rpython.translator import cdir
20 from rpython.conftest import option
21 from rpython.rlib.jit import JitDriver
22
23 def setup_module(module):
24 if os.name == 'nt':
25 # Do not open dreaded dialog box on segfault
26 import ctypes
27 SEM_NOGPFAULTERRORBOX = 0x0002 # From MSDN
28 if hasattr(ctypes.windll.kernel32, 'GetErrorMode'):
29 old_err_mode = ctypes.windll.kernel32.GetErrorMode()
30 new_err_mode = old_err_mode | SEM_NOGPFAULTERRORBOX
31 ctypes.windll.kernel32.SetErrorMode(new_err_mode)
32 module.old_err_mode = old_err_mode
33
34 def teardown_module(module):
35 if os.name == 'nt' and hasattr(module, 'old_err_mode'):
36 import ctypes
37 ctypes.windll.kernel32.SetErrorMode(module.old_err_mode)
38
39 class StandaloneTests(object):
40 config = None
41
42 def compile(self, entry_point, debug=True, shared=False,
43 stackcheck=False, entrypoints=None, local_icon=None,
44 exe_name=None):
45 t = TranslationContext(self.config)
46 ann = t.buildannotator()
47 ann.build_types(entry_point, [s_list_of_strings])
48 if entrypoints is not None:
49 anns = {}
50 for func, annotation in secondary_entrypoints['test']:
51 anns[func] = annotation
52 for item in entrypoints:
53 ann.build_types(item, anns[item])
54 t.buildrtyper().specialize()
55
56 if stackcheck:
57 from rpython.translator.transform import insert_ll_stackcheck
58 insert_ll_stackcheck(t)
59
60 t.config.translation.shared = shared
61 if local_icon:
62 t.config.translation.icon = os.path.join(os.path.dirname(__file__),
63 local_icon)
64
65 if entrypoints is not None:
66 kwds = {'secondary_entrypoints': [(i, None) for i in entrypoints]}
67 else:
68 kwds = {}
69 cbuilder = CStandaloneBuilder(t, entry_point, t.config, **kwds)
70 if debug:
71 cbuilder.generate_source(defines=cbuilder.DEBUG_DEFINES,
72 exe_name=exe_name)
73 else:
74 cbuilder.generate_source()
75 cbuilder.compile()
76 if option is not None and option.view:
77 t.view()
78 return t, cbuilder
79
80
81 class StandaloneTestsVerified(StandaloneTests):
82
83 def compile(self, *args, **kwds):
84 t, builder = StandaloneTests.compile(self, *args, **kwds)
85 #
86 # verify that the executable re-export symbols, but not too many
87 if sys.platform.startswith('linux') and not kwds.get('shared', False):
88 seen = set()
89 g = os.popen("objdump -T '%s'" % builder.executable_name, 'r')
90 for line in g:
91 if not line.strip():
92 continue
93 if '*UND*' in line:
94 continue
95 name = line.split()[-1]
96 if name.startswith('__'):
97 continue
98 seen.add(name)
99 if name == 'main':
100 continue
101 if name == 'pypy_debug_file': # ok to export this one
102 continue
103 if name == 'rpython_startup_code': # ok for this one too
104 continue
105 if 'pypy' in name.lower() or 'rpy' in name.lower():
106 raise Exception("Unexpected exported name %r. "
107 "What is likely missing is RPY_EXTERN before the "
108 "declaration of this C function or global variable"
109 % (name,))
110 g.close()
111 # list of symbols that we *want* to be exported:
112 for name in ['main', 'pypy_debug_file', 'rpython_startup_code']:
113 assert name in seen, "did not see '%r' exported" % name
114 #
115 return t, builder
116
117
118 class TestStandalone(StandaloneTestsVerified):
119
120 def test_hello_world(self):
121 def entry_point(argv):
122 os.write(1, "hello world\n")
123 argv = argv[1:]
124 os.write(1, "argument count: " + str(len(argv)) + "\n")
125 for s in argv:
126 os.write(1, " '" + str(s) + "'\n")
127 return 0
128
129 t, cbuilder = self.compile(entry_point, local_icon='red.ico')
130 data = cbuilder.cmdexec('hi there')
131 assert data.startswith('''hello world\nargument count: 2\n 'hi'\n 'there'\n''')
132
133 # Verify that the generated C files have sane names:
134 gen_c_files = [str(f) for f in cbuilder.extrafiles]
135 for expfile in ('rpython_rlib.c',
136 'rpython_rtyper_lltypesystem.c',
137 'rpython_translator_c_test.c'):
138 assert cbuilder.targetdir.join(expfile) in gen_c_files
139
140 def test_print(self):
141 def entry_point(argv):
142 print "hello simpler world"
143 argv = argv[1:]
144 print "argument count:", len(argv)
145 print "arguments:", argv
146 print "argument lengths:",
147 print [len(s) for s in argv]
148 return 0
149
150 t, cbuilder = self.compile(entry_point)
151 data = cbuilder.cmdexec('hi there')
152 assert data.startswith('''hello simpler world\n'''
153 '''argument count: 2\n'''
154 '''arguments: [hi, there]\n'''
155 '''argument lengths: [2, 5]\n''')
156 # NB. RPython has only str, not repr, so str() on a list of strings
157 # gives the strings unquoted in the list
158
159 def test_counters(self):
160 from rpython.rtyper.lltypesystem import lltype
161 from rpython.rtyper.lltypesystem.lloperation import llop
162 def entry_point(argv):
163 llop.instrument_count(lltype.Void, 'test', 2)
164 llop.instrument_count(lltype.Void, 'test', 1)
165 llop.instrument_count(lltype.Void, 'test', 1)
166 llop.instrument_count(lltype.Void, 'test', 2)
167 llop.instrument_count(lltype.Void, 'test', 1)
168 return 0
169 t = TranslationContext(self.config)
170 t.config.translation.instrument = True
171 t.buildannotator().build_types(entry_point, [s_list_of_strings])
172 t.buildrtyper().specialize()
173
174 cbuilder = CStandaloneBuilder(t, entry_point, config=t.config) # xxx
175 cbuilder.generate_source()
176 cbuilder.compile()
177
178 counters_fname = udir.join("_counters_")
179 os.environ['PYPY_INSTRUMENT_COUNTERS'] = str(counters_fname)
180 try:
181 data = cbuilder.cmdexec()
182 finally:
183 del os.environ['PYPY_INSTRUMENT_COUNTERS']
184
185 f = counters_fname.open('rb')
186 counters_data = f.read()
187 f.close()
188
189 import struct
190 fmt = "LLL"
191 if sys.platform == 'win32' and sys.maxint > 2**31:
192 fmt = "QQQ"
193 counters = struct.unpack(fmt, counters_data)
194
195 assert counters == (0,3,2)
196
197 def test_prof_inline(self):
198 py.test.skip("broken by 5b0e029514d4, but we don't use it any more")
199 if sys.platform == 'win32':
200 py.test.skip("instrumentation support is unix only for now")
201 def add(a,b):
202 return a + b - b + b - b + b - b + b - b + b - b + b - b + b
203 def entry_point(argv):
204 tot = 0
205 x = int(argv[1])
206 while x > 0:
207 tot = add(tot, x)
208 x -= 1
209 os.write(1, str(tot))
210 return 0
211 from rpython.translator.interactive import Translation
212 t = Translation(entry_point, backend='c')
213 # no counters
214 t.backendopt(inline_threshold=100, profile_based_inline="500")
215 exe = t.compile()
216 out = py.process.cmdexec("%s 500" % exe)
217 assert int(out) == 500*501/2
218
219 t = Translation(entry_point, backend='c')
220 # counters
221 t.backendopt(inline_threshold=all.INLINE_THRESHOLD_FOR_TEST*0.5,
222 profile_based_inline="500")
223 exe = t.compile()
224 out = py.process.cmdexec("%s 500" % exe)
225 assert int(out) == 500*501/2
226
227 def test_frexp(self):
228 import math
229 def entry_point(argv):
230 m, e = math.frexp(0)
231 x, y = math.frexp(0)
232 print m, x
233 return 0
234
235 t, cbuilder = self.compile(entry_point)
236 data = cbuilder.cmdexec('hi there')
237 assert map(float, data.split()) == [0.0, 0.0]
238
239 def test_profopt(self):
240 if sys.platform == 'win32':
241 py.test.skip("no profopt on win32")
242 def add(a,b):
243 return a + b - b + b - b + b - b + b - b + b - b + b - b + b
244 def entry_point(argv):
245 tot = 0
246 x = int(argv[1])
247 while x > 0:
248 tot = add(tot, x)
249 x -= 1
250 os.write(1, str(tot))
251 return 0
252 from rpython.translator.interactive import Translation
253 t = Translation(entry_point, backend='c', profopt=True, profoptargs="10", shared=True)
254 t.backendopt()
255 exe = t.compile()
256 assert (os.path.isfile("%s" % exe))
257
258 t = Translation(entry_point, backend='c', profopt=True, profoptargs="10", shared=False)
259 t.backendopt()
260 exe = t.compile()
261 assert (os.path.isfile("%s" % exe))
262
263 import rpython.translator.goal.targetrpystonedalone as rpy
264 t = Translation(rpy.entry_point, backend='c', profopt=True, profoptargs='1000', shared=False)
265 t.backendopt()
266 exe = t.compile()
267 assert (os.path.isfile("%s" % exe))
268
269
270 if hasattr(os, 'setpgrp'):
271 def test_os_setpgrp(self):
272 def entry_point(argv):
273 os.setpgrp()
274 return 0
275
276 t, cbuilder = self.compile(entry_point)
277 cbuilder.cmdexec("")
278
279
280 def test_profopt_mac_osx_bug(self):
281 if sys.platform == 'win32':
282 py.test.skip("no profopt on win32")
283 def entry_point(argv):
284 import os
285 pid = os.fork()
286 if pid:
287 os.waitpid(pid, 0)
288 else:
289 os._exit(0)
290 return 0
291 from rpython.translator.interactive import Translation
292 # XXX this is mostly a "does not crash option"
293 t = Translation(entry_point, backend='c', profopt=True, profoptargs='10', shared=True)
294 # no counters
295 t.backendopt()
296 exe = t.compile()
297 #py.process.cmdexec(exe)
298 t = Translation(entry_point, backend='c', profopt=True, profoptargs='10', shared=True)
299 # no counters
300 t.backendopt()
301 exe = t.compile()
302 #py.process.cmdexec(exe)
303
304 def test_standalone_large_files(self):
305 filename = str(udir.join('test_standalone_largefile'))
306 r4800000000 = r_longlong(4800000000L)
307 def entry_point(argv):
308 assert str(r4800000000 + r_longlong(len(argv))) == '4800000003'
309 fd = os.open(filename, os.O_RDWR | os.O_CREAT, 0644)
310 os.lseek(fd, r4800000000, 0)
311 newpos = os.lseek(fd, 0, 1)
312 if newpos == r4800000000:
313 print "OK"
314 else:
315 print "BAD POS"
316 os.close(fd)
317 return 0
318 t, cbuilder = self.compile(entry_point)
319 data = cbuilder.cmdexec('hi there')
320 assert data.strip() == "OK"
321
322 def test_separate_files(self):
323 # One file in translator/c/src
324 fname = py.path.local(cdir).join('src', 'll_strtod.c')
325
326 # One file in (another) subdir of the temp directory
327 dirname = udir.join("test_dir").ensure(dir=1)
328 fname2 = dirname.join("test_genc.c")
329 fname2.write("""
330 void f() {
331 LL_strtod_formatd(12.3, 'f', 5);
332 }""")
333
334 files = [fname, fname2]
335
336 def entry_point(argv):
337 return 0
338
339 t = TranslationContext(self.config)
340 t.buildannotator().build_types(entry_point, [s_list_of_strings])
341 t.buildrtyper().specialize()
342
343 cbuilder = CStandaloneBuilder(t, entry_point, t.config)
344 cbuilder.eci = cbuilder.eci.merge(
345 ExternalCompilationInfo(separate_module_files=files))
346 cbuilder.generate_source()
347
348 makefile = udir.join(cbuilder.modulename, 'Makefile').read()
349
350 # generated files are compiled in the same directory
351 assert " ../test_dir/test_genc.c" in makefile
352 assert " ../test_dir/test_genc.o" in makefile
353
354 # but files from pypy source dir must be copied
355 assert "translator/c/src" not in makefile
356 assert " ll_strtod.c" in makefile
357 assert " ll_strtod.o" in makefile
358
359 def test_debug_print_start_stop(self):
360 import sys
361 from rpython.rtyper.lltypesystem import rffi
362 if sys.platform == 'win32':
363 # ftell(stderr) is a bit different under subprocess.Popen
364 tell = 0
365 else:
366 tell = -1
367 def entry_point(argv):
368 x = "got:"
369 if have_debug_prints_for("my"): x += "M"
370 if have_debug_prints_for("myc"): x += "m"
371 debug_start ("mycat")
372 if have_debug_prints(): x += "b"
373 debug_print ("foo", r_longlong(2), "bar", 3)
374 debug_start ("cat2")
375 if have_debug_prints(): x += "c"
376 debug_print ("baz")
377 debug_stop ("cat2")
378 if have_debug_prints(): x += "d"
379 debug_print ("bok")
380 debug_stop ("mycat")
381 if have_debug_prints(): x += "a"
382 debug_print("toplevel")
383 debug_print("some int", rffi.cast(rffi.INT, 3))
384 debug_flush()
385 os.write(1, x + "." + str(debug_offset()) + '.\n')
386 return 0
387 t, cbuilder = self.compile(entry_point)
388 # check with PYPYLOG undefined
389 out, err = cbuilder.cmdexec("", err=True, env={})
390 assert out.strip() == 'got:a.%d.' % tell
391 assert 'toplevel' in err
392 assert 'mycat' not in err
393 assert 'foo 2 bar 3' not in err
394 assert 'cat2' not in err
395 assert 'baz' not in err
396 assert 'bok' not in err
397 # check with PYPYLOG defined to an empty string (same as undefined)
398 out, err = cbuilder.cmdexec("", err=True, env={'PYPYLOG': ''})
399 assert out.strip() == 'got:a.%d.' % tell
400 assert 'toplevel' in err
401 assert 'mycat' not in err
402 assert 'foo 2 bar 3' not in err
403 assert 'cat2' not in err
404 assert 'baz' not in err
405 assert 'bok' not in err
406 # check with PYPYLOG=:- (means print to stderr)
407 out, err = cbuilder.cmdexec("", err=True, env={'PYPYLOG': ':-'})
408 assert out.strip() == 'got:Mmbcda.%d.' % tell
409 assert 'toplevel' in err
410 assert '{mycat' in err
411 assert 'mycat}' in err
412 assert 'foo 2 bar 3' in err
413 assert '{cat2' in err
414 assert 'cat2}' in err
415 assert 'baz' in err
416 assert 'bok' in err
417 assert 'some int 3' in err
418 # check with PYPYLOG=:somefilename
419 path = udir.join('test_debug_xxx.log')
420 out, err = cbuilder.cmdexec("", err=True,
421 env={'PYPYLOG': ':%s' % path})
422 size = os.stat(str(path)).st_size
423 assert out.strip() == 'got:Mmbcda.' + str(size) + '.'
424 assert not err
425 assert path.check(file=1)
426 data = path.read()
427 assert 'toplevel' in data
428 assert '{mycat' in data
429 assert 'mycat}' in data
430 assert 'foo 2 bar 3' in data
431 assert '{cat2' in data
432 assert 'cat2}' in data
433 assert 'baz' in data
434 assert 'bok' in data
435 # check with PYPYLOG=somefilename
436 path = udir.join('test_debug_xxx_prof.log')
437 if str(path).find(':')>=0:
438 # bad choice of udir, there is a ':' in it which messes up the test
439 pass
440 else:
441 out, err = cbuilder.cmdexec("", err=True, env={'PYPYLOG': str(path)})
442 size = os.stat(str(path)).st_size
443 assert out.strip() == 'got:a.' + str(size) + '.'
444 assert not err
445 assert path.check(file=1)
446 data = path.read()
447 assert 'toplevel' in data
448 assert '{mycat' in data
449 assert 'mycat}' in data
450 assert 'foo 2 bar 3' not in data
451 assert '{cat2' in data
452 assert 'cat2}' in data
453 assert 'baz' not in data
454 assert 'bok' not in data
455 # check with PYPYLOG=+somefilename
456 path = udir.join('test_debug_xxx_prof_2.log')
457 out, err = cbuilder.cmdexec("", err=True, env={'PYPYLOG': '+%s' % path})
458 size = os.stat(str(path)).st_size
459 assert out.strip() == 'got:a.' + str(size) + '.'
460 assert not err
461 assert path.check(file=1)
462 data = path.read()
463 assert 'toplevel' in data
464 assert '{mycat' in data
465 assert 'mycat}' in data
466 assert 'foo 2 bar 3' not in data
467 assert '{cat2' in data
468 assert 'cat2}' in data
469 assert 'baz' not in data
470 assert 'bok' not in data
471 # check with PYPYLOG=myc:somefilename (includes mycat but not cat2)
472 path = udir.join('test_debug_xxx_myc.log')
473 out, err = cbuilder.cmdexec("", err=True,
474 env={'PYPYLOG': 'myc:%s' % path})
475 size = os.stat(str(path)).st_size
476 assert out.strip() == 'got:Mmbda.' + str(size) + '.'
477 assert not err
478 assert path.check(file=1)
479 data = path.read()
480 assert 'toplevel' in data
481 assert '{mycat' in data
482 assert 'mycat}' in data
483 assert 'foo 2 bar 3' in data
484 assert 'cat2' not in data
485 assert 'baz' not in data
486 assert 'bok' in data
487 # check with PYPYLOG=cat:somefilename (includes cat2 but not mycat)
488 path = udir.join('test_debug_xxx_cat.log')
489 out, err = cbuilder.cmdexec("", err=True,
490 env={'PYPYLOG': 'cat:%s' % path})
491 size = os.stat(str(path)).st_size
492 assert out.strip() == 'got:ca.' + str(size) + '.'
493 assert not err
494 assert path.check(file=1)
495 data = path.read()
496 assert 'toplevel' in data
497 assert 'mycat' not in data
498 assert 'foo 2 bar 3' not in data
499 assert 'cat2' in data
500 assert 'baz' in data
501 assert 'bok' not in data
502 # check with PYPYLOG=myc,cat2:somefilename (includes mycat and cat2)
503 path = udir.join('test_debug_xxx_myc_cat2.log')
504 out, err = cbuilder.cmdexec("", err=True,
505 env={'PYPYLOG': 'myc,cat2:%s' % path})
506 size = os.stat(str(path)).st_size
507 assert out.strip() == 'got:Mmbcda.' + str(size) + '.'
508 assert not err
509 assert path.check(file=1)
510 data = path.read()
511 assert 'toplevel' in data
512 assert '{mycat' in data
513 assert 'mycat}' in data
514 assert 'foo 2 bar 3' in data
515 assert 'cat2' in data
516 assert 'baz' in data
517 assert 'bok' in data
518 #
519 # finally, check compiling with logging disabled
520 config = get_combined_translation_config(translating=True)
521 config.translation.log = False
522 self.config = config
523 t, cbuilder = self.compile(entry_point)
524 path = udir.join('test_debug_does_not_show_up.log')
525 out, err = cbuilder.cmdexec("", err=True,
526 env={'PYPYLOG': ':%s' % path})
527 assert out.strip() == 'got:.-1.'
528 assert not err
529 assert path.check(file=0)
530
531 def test_debug_start_stop_timestamp(self):
532 from rpython.rlib.rtimer import read_timestamp
533 def entry_point(argv):
534 timestamp = bool(int(argv[1]))
535 ts1 = debug_start("foo", timestamp=timestamp)
536 ts2 = read_timestamp()
537 ts3 = debug_stop("foo", timestamp=timestamp)
538 print ts1
539 print ts2
540 print ts3
541 return 0
542 t, cbuilder = self.compile(entry_point)
543
544 def parse_out(out):
545 lines = out.strip().splitlines()
546 ts1, ts2, ts3 = lines
547 return int(ts1), int(ts2), int(ts3)
548
549 # check with PYPYLOG :-
550 out, err = cbuilder.cmdexec("1", err=True, env={'PYPYLOG': ':-'})
551 ts1, ts2, ts3 = parse_out(out)
552 assert ts3 > ts2 > ts1
553 expected = ('[%x] {foo\n' % ts1 +
554 '[%x] foo}\n' % ts3)
555 assert err == expected
556
557 # check with PYPYLOG profiling only
558 out, err = cbuilder.cmdexec("1", err=True, env={'PYPYLOG': '-'})
559 ts1, ts2, ts3 = parse_out(out)
560 assert ts3 > ts2 > ts1
561 expected = ('[%x] {foo\n' % ts1 +
562 '[%x] foo}\n' % ts3)
563 assert err == expected
564
565 # check with PYPYLOG undefined
566 out, err = cbuilder.cmdexec("1", err=True, env={})
567 ts1, ts2, ts3 = parse_out(out)
568 assert ts3 > ts2 > ts1
569
570 # check with PYPYLOG undefined and timestamp=False
571 out, err = cbuilder.cmdexec("0", err=True, env={})
572 ts1, ts2, ts3 = parse_out(out)
573 assert ts1 == ts3 == 42;
574
575 def test_debug_print_start_stop_nonconst(self):
576 def entry_point(argv):
577 debug_start(argv[1])
578 debug_print(argv[2])
579 debug_stop(argv[1])
580 return 0
581 t, cbuilder = self.compile(entry_point)
582 out, err = cbuilder.cmdexec("foo bar", err=True, env={'PYPYLOG': ':-'})
583 lines = err.splitlines()
584 assert '{foo' in lines[0]
585 assert 'bar' == lines[1]
586 assert 'foo}' in lines[2]
587
588 def test_debug_print_fork(self):
589 if not hasattr(os, 'fork'):
590 py.test.skip("requires fork()")
591
592 def entry_point(argv):
593 print "parentpid =", os.getpid()
594 debug_start("foo")
595 debug_print("test line")
596 childpid = os.fork()
597 debug_print("childpid =", childpid)
598 if childpid == 0:
599 childpid2 = os.fork() # double-fork
600 debug_print("childpid2 =", childpid2)
601 debug_stop("foo")
602 return 0
603 t, cbuilder = self.compile(entry_point)
604 path = udir.join('test_debug_print_fork.log')
605 out, err = cbuilder.cmdexec("", err=True,
606 env={'PYPYLOG': ':%s.%%d' % path})
607 assert not err
608 import time
609 time.sleep(0.5) # time for the forked children to finish
610 #
611 lines = out.splitlines()
612 assert lines[-1].startswith('parentpid = ')
613 parentpid = int(lines[-1][12:])
614 #
615 f = open('%s.%d' % (path, parentpid), 'r')
616 lines = f.readlines()
617 f.close()
618 assert '{foo' in lines[0]
619 assert lines[1] == "test line\n"
620 #offset1 = len(lines[0]) + len(lines[1])
621 assert lines[2].startswith('childpid = ')
622 childpid = int(lines[2][11:])
623 assert childpid != 0
624 assert 'foo}' in lines[3]
625 assert len(lines) == 4
626 #
627 f = open('%s.%d' % (path, childpid), 'r')
628 lines = f.readlines()
629 f.close()
630 #assert lines[0] == 'FORKED: %d %s\n' % (offset1, path)
631 assert lines[0] == 'childpid = 0\n'
632 #offset2 = len(lines[0]) + len(lines[1])
633 assert lines[1].startswith('childpid2 = ')
634 childpid2 = int(lines[1][11:])
635 assert childpid2 != 0
636 assert 'foo}' in lines[2]
637 assert len(lines) == 3
638 #
639 f = open('%s.%d' % (path, childpid2), 'r')
640 lines = f.readlines()
641 f.close()
642 #assert lines[0] == 'FORKED: %d %s.fork%d\n' % (offset2, path, childpid)
643 assert lines[0] == 'childpid2 = 0\n'
644 assert 'foo}' in lines[1]
645 assert len(lines) == 2
646
647 def test_debug_flush_at_exit(self):
648 def entry_point(argv):
649 debug_start("mycat")
650 os._exit(0)
651 return 0
652
653 t, cbuilder = self.compile(entry_point)
654 path = udir.join('test_debug_flush_at_exit.log')
655 cbuilder.cmdexec("", env={'PYPYLOG': ':%s' % path})
656 #
657 f = open(str(path), 'r')
658 lines = f.readlines()
659 f.close()
660 assert lines[0].endswith('{mycat\n')
661
662 def test_fatal_error(self):
663 def g(x):
664 if x == 1:
665 raise ValueError
666 else:
667 raise KeyError
668 def entry_point(argv):
669 if len(argv) < 3:
670 g(len(argv))
671 return 0
672 t, cbuilder = self.compile(entry_point)
673 #
674 out, err = cbuilder.cmdexec("", expect_crash=True)
675 assert out.strip() == ''
676 lines = err.strip().splitlines()
677 idx = lines.index('Fatal RPython error: ValueError') # assert found
678 lines = lines[:idx+1]
679 assert len(lines) >= 5
680 l0, lx, l1, l2 = lines[-5:-1]
681 assert l0 == 'RPython traceback:'
682 # lx is a bit strange with reference counting, ignoring it
683 assert re.match(r' File "\w+.c", line \d+, in entry_point', l1)
684 assert re.match(r' File "\w+.c", line \d+, in g', l2)
685 #
686 out2, err2 = cbuilder.cmdexec("x", expect_crash=True)
687 assert out2.strip() == ''
688 lines2 = err2.strip().splitlines()
689 idx = lines2.index('Fatal RPython error: KeyError') # assert found
690 lines2 = lines2[:idx+1]
691 l0, lx, l1, l2 = lines2[-5:-1]
692 assert l0 == 'RPython traceback:'
693 # lx is a bit strange with reference counting, ignoring it
694 assert re.match(r' File "\w+.c", line \d+, in entry_point', l1)
695 assert re.match(r' File "\w+.c", line \d+, in g', l2)
696 assert lines2[-2] != lines[-2] # different line number
697 assert lines2[-3] == lines[-3] # same line number
698
699 def test_fatal_error_finally_1(self):
700 # a simple case of try:finally:
701 def g(x):
702 if x == 1:
703 raise KeyError
704 def h(x):
705 try:
706 g(x)
707 finally:
708 os.write(1, 'done.\n')
709 def entry_point(argv):
710 if len(argv) < 3:
711 h(len(argv))
712 return 0
713 t, cbuilder = self.compile(entry_point)
714 #
715 out, err = cbuilder.cmdexec("", expect_crash=True)
716 assert out.strip() == 'done.'
717 lines = err.strip().splitlines()
718 idx = lines.index('Fatal RPython error: KeyError') # assert found
719 lines = lines[:idx+1]
720 assert len(lines) >= 6
721 l0, lx, l1, l2, l3 = lines[-6:-1]
722 assert l0 == 'RPython traceback:'
723 # lx is a bit strange with reference counting, ignoring it
724 assert re.match(r' File "\w+.c", line \d+, in entry_point', l1)
725 assert re.match(r' File "\w+.c", line \d+, in h', l2)
726 assert re.match(r' File "\w+.c", line \d+, in g', l3)
727
728 def test_fatal_error_finally_2(self):
729 # a try:finally: in which we raise and catch another exception
730 def raiseme(x):
731 if x == 1:
732 raise ValueError
733 def raise_and_catch(x):
734 try:
735 raiseme(x)
736 except ValueError:
737 pass
738 def g(x):
739 if x == 1:
740 raise KeyError
741 def h(x):
742 try:
743 g(x)
744 finally:
745 raise_and_catch(x)
746 os.write(1, 'done.\n')
747 def entry_point(argv):
748 if len(argv) < 3:
749 h(len(argv))
750 return 0
751 t, cbuilder = self.compile(entry_point)
752 #
753 out, err = cbuilder.cmdexec("", expect_crash=True)
754 assert out.strip() == 'done.'
755 lines = err.strip().splitlines()
756 idx = lines.index('Fatal RPython error: KeyError') # assert found
757 lines = lines[:idx+1]
758 assert len(lines) >= 6
759 l0, lx, l1, l2, l3 = lines[-6:-1]
760 assert l0 == 'RPython traceback:'
761 # lx is a bit strange with reference counting, ignoring it
762 assert re.match(r' File "\w+.c", line \d+, in entry_point', l1)
763 assert re.match(r' File "\w+.c", line \d+, in h', l2)
764 assert re.match(r' File "\w+.c", line \d+, in g', l3)
765
766 def test_fatal_error_finally_3(self):
767 py.test.skip("not implemented: "
768 "a try:finally: in which we raise the *same* exception")
769
770 def test_fatal_error_finally_4(self):
771 # a try:finally: in which we raise (and don't catch) an exception
772 def raiseme(x):
773 if x == 1:
774 raise ValueError
775 def g(x):
776 if x == 1:
777 raise KeyError
778 def h(x):
779 try:
780 g(x)
781 finally:
782 raiseme(x)
783 os.write(1, 'done.\n')
784 def entry_point(argv):
785 if len(argv) < 3:
786 h(len(argv))
787 return 0
788 t, cbuilder = self.compile(entry_point)
789 #
790 out, err = cbuilder.cmdexec("", expect_crash=True)
791 assert out.strip() == ''
792 lines = err.strip().splitlines()
793 idx = lines.index('Fatal RPython error: ValueError') # assert found
794 lines = lines[:idx+1]
795 assert len(lines) >= 6
796 l0, lx, l1, l2, l3 = lines[-6:-1]
797 assert l0 == 'RPython traceback:'
798 # lx is a bit strange with reference counting, ignoring it
799 assert re.match(r' File "\w+.c", line \d+, in entry_point', l1)
800 assert re.match(r' File "\w+.c", line \d+, in h', l2)
801 assert re.match(r' File "\w+.c", line \d+, in raiseme', l3)
802
803 def test_assertion_error_debug(self):
804 def entry_point(argv):
805 assert len(argv) != 1
806 return 0
807 t, cbuilder = self.compile(entry_point, debug=True)
808 out, err = cbuilder.cmdexec("", expect_crash=True)
809 assert out.strip() == ''
810 lines = err.strip().splitlines()
811 assert 'in pypy_g_RPyRaiseException: AssertionError' in lines
812
813 def test_assertion_error_nondebug(self):
814 def g(x):
815 assert x != 1
816 def f(argv):
817 try:
818 g(len(argv))
819 finally:
820 print 'done'
821 def entry_point(argv):
822 f(argv)
823 return 0
824 t, cbuilder = self.compile(entry_point, debug=False)
825 out, err = cbuilder.cmdexec("", expect_crash=True)
826 assert out.strip() == ''
827 lines = err.strip().splitlines()
828 idx = lines.index('Fatal RPython error: AssertionError') # assert found
829 lines = lines[:idx+1]
830 assert len(lines) >= 4
831 l0, l1, l2 = lines[-4:-1]
832 assert l0 == 'RPython traceback:'
833 assert re.match(r' File "\w+.c", line \d+, in f', l1)
834 assert re.match(r' File "\w+.c", line \d+, in g', l2)
835 # The traceback stops at f() because it's the first function that
836 # captures the AssertionError, which makes the program abort.
837
838 def test_int_lshift_too_large(self):
839 from rpython.rlib.rarithmetic import LONG_BIT, LONGLONG_BIT
840 def entry_point(argv):
841 a = int(argv[1])
842 b = int(argv[2])
843 print a << b
844 return 0
845
846 t, cbuilder = self.compile(entry_point, debug=True)
847 out = cbuilder.cmdexec("10 2", expect_crash=False)
848 assert out.strip() == str(10 << 2)
849 cases = [-4, LONG_BIT, LONGLONG_BIT]
850 for x in cases:
851 out, err = cbuilder.cmdexec("%s %s" % (1, x), expect_crash=True)
852 lines = err.strip()
853 assert 'The shift count is outside of the supported range' in lines
854
855 def test_llong_rshift_too_large(self):
856 from rpython.rlib.rarithmetic import LONG_BIT, LONGLONG_BIT
857 def entry_point(argv):
858 a = r_longlong(int(argv[1]))
859 b = r_longlong(int(argv[2]))
860 print a >> b
861 return 0
862
863 t, cbuilder = self.compile(entry_point, debug=True)
864 out = cbuilder.cmdexec("10 2", expect_crash=False)
865 assert out.strip() == str(10 >> 2)
866 out = cbuilder.cmdexec("%s %s" % (-42, LONGLONG_BIT - 1), expect_crash=False)
867 assert out.strip() == '-1'
868 cases = [-4, LONGLONG_BIT]
869 for x in cases:
870 out, err = cbuilder.cmdexec("%s %s" % (1, x), expect_crash=True)
871 lines = err.strip()
872 assert 'The shift count is outside of the supported range' in lines
873
874 def test_ll_assert_error_debug(self):
875 def entry_point(argv):
876 ll_assert(len(argv) != 1, "foobar")
877 return 0
878 t, cbuilder = self.compile(entry_point, debug=True)
879 out, err = cbuilder.cmdexec("", expect_crash=True)
880 assert out.strip() == ''
881 lines = err.strip().splitlines()
882 assert 'in pypy_g_entry_point: foobar' in lines
883
884 def test_ll_assert_error_nondebug(self):
885 py.test.skip("implement later, maybe: tracebacks even with ll_assert")
886 def g(x):
887 ll_assert(x != 1, "foobar")
888 def f(argv):
889 try:
890 g(len(argv))
891 finally:
892 print 'done'
893 def entry_point(argv):
894 f(argv)
895 return 0
896 t, cbuilder = self.compile(entry_point)
897 out, err = cbuilder.cmdexec("", expect_crash=True)
898 assert out.strip() == ''
899 lines = err.strip().splitlines()
900 idx = lines.index('PyPy assertion failed: foobar') # assert found
901 lines = lines[:idx+1]
902 assert len(lines) >= 4
903 l0, l1, l2 = lines[-4:-1]
904 assert l0 == 'RPython traceback:'
905 assert re.match(r' File "\w+.c", line \d+, in f', l1)
906 assert re.match(r' File "\w+.c", line \d+, in g', l2)
907 # The traceback stops at f() because it's the first function that
908 # captures the AssertionError, which makes the program abort.
909
910 def test_shared1(self, monkeypatch):
911 def f(argv):
912 print len(argv)
913 def entry_point(argv):
914 f(argv)
915 return 0
916 # Make sure the '.' in exe_name is propagated
917 t, cbuilder = self.compile(entry_point, shared=True, exe_name='pypy3.9')
918 assert 'pypy3.9' in str(cbuilder.executable_name)
919 assert cbuilder.shared_library_name is not None
920 assert cbuilder.shared_library_name != cbuilder.executable_name
921 assert 'exe' not in str(cbuilder.shared_library_name)
922 # it must be something with a '.basename' to make the driver.py happy
923 assert not isinstance(cbuilder.shared_library_name, str)
924 assert 'pypy3.9' in str(cbuilder.shared_library_name)
925 #Do not set LD_LIBRARY_PATH, make sure $ORIGIN flag is working
926 out, err = cbuilder.cmdexec("a b")
927 assert out == "3"
928 if sys.platform == 'win32':
929 assert 'pypy3.9.exe' not in str(cbuilder.shared_library_name)
930 assert 'pypy3.9.exe' in str(cbuilder.executable_name)
931 # Make sure we have a pypy3.9w.exe
932 # Since stdout, stderr are piped, we will get output
933 exe = cbuilder.executable_name
934 wexe = exe.new(purebasename=exe.purebasename + 'w')
935 out, err = cbuilder.cmdexec("a b", exe = wexe)
936 assert out == "3"
937
938 def test_shared2(self, monkeypatch):
939 def f(argv):
940 print len(argv)
941 def entry_point(argv):
942 f(argv)
943 return 0
944 # Make sure the '.exe' in exe_name is not propagated
945 t, cbuilder = self.compile(entry_point, shared=True, exe_name='pypy')
946 assert 'pypy' == cbuilder.executable_name.purebasename
947 assert 'libpypy' == cbuilder.shared_library_name.purebasename
948
949 def test_gcc_options(self):
950 # check that the env var CC is correctly interpreted, even if
951 # it contains the compiler name followed by some options.
952 if sys.platform == 'win32':
953 py.test.skip("only for gcc")
954
955 from rpython.rtyper.lltypesystem import lltype, rffi
956 dir = udir.ensure('test_gcc_options', dir=1)
957 dir.join('someextraheader.h').write('#define someextrafunc() 42\n')
958 eci = ExternalCompilationInfo(includes=['someextraheader.h'])
959 someextrafunc = rffi.llexternal('someextrafunc', [], lltype.Signed,
960 compilation_info=eci)
961
962 def entry_point(argv):
963 return someextrafunc()
964
965 old_cc = os.environ.get('CC')
966 try:
967 os.environ['CC'] = 'gcc -I%s' % dir
968 t, cbuilder = self.compile(entry_point)
969 finally:
970 if old_cc is None:
971 del os.environ['CC']
972 else:
973 os.environ['CC'] = old_cc
974
975 def test_inhibit_tail_call(self):
976 # the point is to check that the f()->f() recursion stops
977 from rpython.rlib.rstackovf import StackOverflow
978 class Glob:
979 pass
980 glob = Glob()
981 def f(n):
982 glob.n = n
983 if n <= 0:
984 return 42
985 return f(n+1)
986 def entry_point(argv):
987 try:
988 return f(1)
989 except StackOverflow:
990 print 'hi!', glob.n
991 return 0
992 t, cbuilder = self.compile(entry_point, stackcheck=True)
993 out = cbuilder.cmdexec("")
994 text = out.strip()
995 assert text.startswith("hi! ")
996 n = int(text[4:])
997 assert n > 500 and n < 5000000
998
999 def test_set_length_fraction(self):
1000 # check for rpython.rlib.rstack._stack_set_length_fraction()
1001 from rpython.rlib.rstack import _stack_set_length_fraction
1002 from rpython.rlib.rstackovf import StackOverflow
1003 class A:
1004 n = 0
1005 glob = A()
1006 def f(n):
1007 glob.n += 1
1008 if n <= 0:
1009 return 42
1010 return f(n+1)
1011 def entry_point(argv):
1012 _stack_set_length_fraction(0.1)
1013 try:
1014 return f(1)
1015 except StackOverflow:
1016 glob.n = 0
1017 _stack_set_length_fraction(float(argv[1]))
1018 try:
1019 return f(1)
1020 except StackOverflow:
1021 print glob.n
1022 return 0
1023 t, cbuilder = self.compile(entry_point, stackcheck=True)
1024 counts = {}
1025 for fraction in [0.1, 0.4, 1.0]:
1026 out = cbuilder.cmdexec(str(fraction))
1027 print 'counts[%s]: %r' % (fraction, out)
1028 counts[fraction] = int(out.strip())
1029 #
1030 assert counts[1.0] >= 1000
1031 # ^^^ should actually be much more than 1000 for this small test
1032 assert counts[0.1] < counts[0.4] / 3
1033 assert counts[0.4] < counts[1.0] / 2
1034 assert counts[0.1] > counts[0.4] / 7
1035 assert counts[0.4] > counts[1.0] / 4
1036
1037 def test_stack_criticalcode(self):
1038 # check for rpython.rlib.rstack._stack_criticalcode_start/stop()
1039 from rpython.rlib.rstack import _stack_criticalcode_start
1040 from rpython.rlib.rstack import _stack_criticalcode_stop
1041 from rpython.rlib.rstackovf import StackOverflow
1042 class A:
1043 pass
1044 glob = A()
1045 def f(n):
1046 if n <= 0:
1047 return 42
1048 try:
1049 return f(n+1)
1050 except StackOverflow:
1051 if glob.caught:
1052 print 'Oups! already caught!'
1053 glob.caught = True
1054 _stack_criticalcode_start()
1055 critical(100) # recurse another 100 times here
1056 _stack_criticalcode_stop()
1057 return 789
1058 def critical(n):
1059 if n > 0:
1060 n = critical(n - 1)
1061 return n - 42
1062 def entry_point(argv):
1063 glob.caught = False
1064 print f(1)
1065 return 0
1066 t, cbuilder = self.compile(entry_point, stackcheck=True)
1067 out = cbuilder.cmdexec('')
1068 assert out.strip() == '789'
1069
1070 def test_llhelper_stored_in_struct(self):
1071 from rpython.rtyper.annlowlevel import llhelper
1072
1073 def f(x):
1074 return x + 3
1075
1076 FUNC_TP = lltype.Ptr(lltype.FuncType([lltype.Signed], lltype.Signed))
1077
1078 S = lltype.GcStruct('s', ('f', FUNC_TP))
1079
1080 class Glob(object):
1081 pass
1082
1083 glob = Glob()
1084
1085 def entry_point(argv):
1086 x = llhelper(FUNC_TP, f)
1087 s = lltype.malloc(S)
1088 s.f = x
1089 glob.s = s # escape
1090 return 0
1091
1092 self.compile(entry_point)
1093 # assert did not explode
1094
1095 def test_unicode_builder(self):
1096 import random
1097 from rpython.rlib.rstring import UnicodeBuilder
1098
1099 to_do = []
1100 for i in range(15000):
1101 to_do.append(random.randrange(0, 100000))
1102 to_do.append(0)
1103
1104 expected = []
1105 s = ''
1106 for x in to_do:
1107 if x < 1500:
1108 expected.append("``%s''" % (s,))
1109 if x < 1000:
1110 s = ''
1111 elif x < 20000:
1112 s += chr(32 + (x & 63))
1113 elif x < 30000:
1114 s += chr(32 + (x & 63)) * (x % 93)
1115 else:
1116 s += str(x)
1117 expected = '\n'.join(expected)
1118
1119 def entry_point(argv):
1120 b = UnicodeBuilder(32)
1121 for x in to_do:
1122 if x < 1500:
1123 print "``%s''" % str(b.build())
1124 if x < 1000:
1125 b = UnicodeBuilder(32)
1126 elif x < 20000:
1127 b.append(unichr(32 + (x & 63)))
1128 elif x < 30000:
1129 b.append_multiple_char(unichr(32 + (x & 63)), x % 93)
1130 else:
1131 b.append(unicode(str(x)))
1132 return 0
1133
1134 t, cbuilder = self.compile(entry_point)
1135 out = cbuilder.cmdexec('')
1136 assert out.strip() == expected
1137
1138 def test_call_at_startup(self):
1139 from rpython.rtyper.extregistry import ExtRegistryEntry
1140
1141 class State:
1142 seen = 0
1143 state = State()
1144 def startup():
1145 state.seen += 1
1146 def enablestartup():
1147 "NOT_RPYTHON"
1148 def entry_point(argv):
1149 state.seen += 100
1150 assert state.seen == 101
1151 print 'ok'
1152 enablestartup()
1153 return 0
1154
1155 class Entry(ExtRegistryEntry):
1156 _about_ = enablestartup
1157
1158 def compute_result_annotation(self):
1159 bk = self.bookkeeper
1160 s_callable = bk.immutablevalue(startup)
1161 key = (enablestartup,)
1162 bk.emulate_pbc_call(key, s_callable, [])
1163
1164 def specialize_call(self, hop):
1165 hop.exception_cannot_occur()
1166 bk = hop.rtyper.annotator.bookkeeper
1167 s_callable = bk.immutablevalue(startup)
1168 r_callable = hop.rtyper.getrepr(s_callable)
1169 ll_init = r_callable.get_unique_llfn().value
1170 bk.annotator.translator._call_at_startup.append(ll_init)
1171
1172 t, cbuilder = self.compile(entry_point)
1173 out = cbuilder.cmdexec('')
1174 assert out.strip() == 'ok'
1175
1176 def test_gcc_precompiled_header(self):
1177 if sys.platform == 'win32':
1178 py.test.skip("no win")
1179 def entry_point(argv):
1180 os.write(1, "hello world\n")
1181 argv = argv[1:]
1182 os.write(1, "argument count: " + str(len(argv)) + "\n")
1183 for s in argv:
1184 os.write(1, " '" + str(s) + "'\n")
1185 return 0
1186
1187 t, cbuilder = self.compile(entry_point)
1188 if "gcc" not in t.platform.cc:
1189 py.test.skip("gcc only")
1190 data = cbuilder.cmdexec('hi there')
1191 assert data.startswith('''hello world\nargument count: 2\n 'hi'\n 'there'\n''')
1192
1193 # check that the precompiled header was generated
1194 assert cbuilder.targetdir.join("singleheader.h.gch").check()
1195
1196 def test_field_access_stats(self):
1197 t = TranslationContext(self.config)
1198 t.config.translation.countfieldaccess = True
1199 class A:
1200 pass
1201 def entry_point(argv):
1202 l = []
1203 for i in range(100):
1204 a = A()
1205 a.x = i
1206 l.append(a)
1207 res = 0
1208 for a in l + l:
1209 res += a.x
1210 print(res)
1211 return 0
1212 entry_point([])
1213
1214 t.buildannotator().build_types(entry_point, [s_list_of_strings])
1215 t.buildrtyper().specialize()
1216 #
1217 cbuilder = CStandaloneBuilder(t, entry_point, t.config)
1218 cbuilder.generate_source(defines=cbuilder.DEBUG_DEFINES)
1219 cbuilder.compile()
1220 fn = udir.join("fieldstats")
1221 data = cbuilder.cmdexec(env={"PYPYLOG": "stats-fields:%s" % fn})
1222 stats = fn.read()
1223 assert "write a_inst_x 100" in stats
1224 assert "read a_inst_x 200" in stats
1225
1226 class TestThread(object):
1227 gcrootfinder = 'shadowstack'
1228 config = None
1229
1230 def compile(self, entry_point, no__thread=True):
1231 t = TranslationContext(self.config)
1232 t.config.translation.gc = "incminimark"
1233 t.config.translation.gcrootfinder = self.gcrootfinder
1234 t.config.translation.thread = True
1235 t.config.translation.no__thread = no__thread
1236 t.buildannotator().build_types(entry_point, [s_list_of_strings])
1237 t.buildrtyper().specialize()
1238 #
1239 cbuilder = CStandaloneBuilder(t, entry_point, t.config)
1240 cbuilder.generate_source(defines=cbuilder.DEBUG_DEFINES)
1241 cbuilder.compile()
1242 #
1243 return t, cbuilder
1244
1245
1246 def test_stack_size(self):
1247 import time
1248 from rpython.rlib import rthread
1249 from rpython.rtyper.lltypesystem import lltype
1250
1251 class State:
1252 pass
1253 state = State()
1254
1255 def recurse(n):
1256 if n > 0:
1257 return recurse(n-1)+1
1258 else:
1259 time.sleep(0.2) # invokes before/after
1260 return 0
1261
1262 # recurse a lot
1263 RECURSION = 19500
1264 if sys.platform == 'win32':
1265 # If I understand it correctly:
1266 # - The stack size "reserved" for a new thread is a compile-time
1267 # option (by default: 1Mb). This is a minimum that user code
1268 # cannot control.
1269 # - set_stacksize() only sets the initially "committed" size,
1270 # which eventually requires a larger "reserved" size.
1271 # - The limit below is large enough to exceed the "reserved" size,
1272 # for small values of set_stacksize().
1273 RECURSION = 150 * 1000
1274
1275 def bootstrap():
1276 recurse(RECURSION)
1277 state.count += 1
1278
1279 def entry_point(argv):
1280 os.write(1, "hello world\n")
1281 error = rthread.set_stacksize(int(argv[1]))
1282 if error != 0:
1283 os.write(2, "set_stacksize(%d) returned %d\n" % (
1284 int(argv[1]), error))
1285 raise AssertionError
1286 # malloc a bit
1287 s1 = State(); s2 = State(); s3 = State()
1288 s1.x = 0x11111111; s2.x = 0x22222222; s3.x = 0x33333333
1289 # start 3 new threads
1290 state.count = 0
1291 ident1 = rthread.start_new_thread(bootstrap, ())
1292 ident2 = rthread.start_new_thread(bootstrap, ())
1293 ident3 = rthread.start_new_thread(bootstrap, ())
1294 # wait for the 3 threads to finish
1295 while True:
1296 if state.count == 3:
1297 break
1298 time.sleep(0.1) # invokes before/after
1299 # check that the malloced structures were not overwritten
1300 assert s1.x == 0x11111111
1301 assert s2.x == 0x22222222
1302 assert s3.x == 0x33333333
1303 os.write(1, "done\n")
1304 return 0
1305
1306 t, cbuilder = self.compile(entry_point)
1307
1308 # recursing should crash with only 32 KB of stack,
1309 # and it should eventually work with more stack
1310 for test_kb in [32, 128, 512, 1024, 2048, 4096, 8192, 16384,
1311 32768, 65536]:
1312 print >> sys.stderr, 'Trying with %d KB of stack...' % (test_kb,),
1313 try:
1314 data = cbuilder.cmdexec(str(test_kb * 1024))
1315 except Exception as e:
1316 if e.__class__ is not Exception:
1317 raise
1318 print >> sys.stderr, 'segfault'
1319 # got a segfault! try with the next stack size...
1320 else:
1321 # it worked
1322 print >> sys.stderr, 'ok'
1323 assert data == 'hello world\ndone\n'
1324 assert test_kb > 32 # it cannot work with just 32 KB of stack
1325 break # finish
1326 else:
1327 py.test.fail("none of the stack sizes worked")
1328
1329
1330 def test_thread_and_gc(self):
1331 import time, gc
1332 from rpython.rlib import rthread, rposix
1333 from rpython.rtyper.lltypesystem import lltype
1334
1335 class State:
1336 pass
1337 state = State()
1338
1339 class Cons:
1340 def __init__(self, head, tail):
1341 self.head = head
1342 self.tail = tail
1343
1344 def check_errno(value):
1345 rposix.set_saved_errno(value)
1346 for i in range(10000000):
1347 pass
1348 assert rposix.get_saved_errno() == value
1349
1350 def bootstrap():
1351 rthread.gc_thread_start()
1352 check_errno(42)
1353 state.xlist.append(Cons(123, Cons(456, None)))
1354 gc.collect()
1355 rthread.gc_thread_die()
1356
1357 def new_thread():
1358 ident = rthread.start_new_thread(bootstrap, ())
1359 check_errno(41)
1360 time.sleep(0.5) # enough time to start, hopefully
1361 return ident
1362
1363 def entry_point(argv):
1364 os.write(1, "hello world\n")
1365 state.xlist = []
1366 x2 = Cons(51, Cons(62, Cons(74, None)))
1367 # start 5 new threads
1368 ident1 = new_thread()
1369 ident2 = new_thread()
1370 #
1371 gc.collect()
1372 #
1373 ident3 = new_thread()
1374 ident4 = new_thread()
1375 ident5 = new_thread()
1376 # wait for the 5 threads to finish
1377 while True:
1378 gc.collect()
1379 if len(state.xlist) == 5:
1380 break
1381 time.sleep(0.1) # invokes before/after
1382 # check that the malloced structures were not overwritten
1383 assert x2.head == 51
1384 assert x2.tail.head == 62
1385 assert x2.tail.tail.head == 74
1386 assert x2.tail.tail.tail is None
1387 # check the structures produced by the threads
1388 for i in range(5):
1389 assert state.xlist[i].head == 123
1390 assert state.xlist[i].tail.head == 456
1391 assert state.xlist[i].tail.tail is None
1392 os.write(1, "%d ok\n" % (i+1))
1393 return 0
1394
1395 def runme(no__thread):
1396 t, cbuilder = self.compile(entry_point, no__thread=no__thread)
1397 data = cbuilder.cmdexec('')
1398 assert data.splitlines() == ['hello world',
1399 '1 ok',
1400 '2 ok',
1401 '3 ok',
1402 '4 ok',
1403 '5 ok']
1404
1405 if SUPPORT__THREAD:
1406 runme(no__thread=False)
1407 runme(no__thread=True)
1408
1409
1410 def test_gc_with_fork_without_threads(self):
1411 if not hasattr(os, 'fork'):
1412 py.test.skip("requires fork()")
1413
1414 def entry_point(argv):
1415 childpid = os.fork()
1416 if childpid == 0:
1417 print "Testing..."
1418 else:
1419 pid, status = os.waitpid(childpid, 0)
1420 assert pid == childpid
1421 assert status == 0
1422 print "OK."
1423 return 0
1424
1425 t, cbuilder = self.compile(entry_point)
1426 data = cbuilder.cmdexec('')
1427 print repr(data)
1428 assert data.startswith('Testing...\nOK.')
1429
1430 def test_thread_and_gc_with_fork(self):
1431 # This checks that memory allocated for the shadow stacks of the
1432 # other threads is really released when doing a fork() -- or at
1433 # least that the object referenced from stacks that are no longer
1434 # alive are really freed.
1435 import time, gc, os
1436 from rpython.rlib import rthread
1437 if not hasattr(os, 'fork'):
1438 py.test.skip("requires fork()")
1439
1440 from rpython.rtyper.lltypesystem import rffi, lltype
1441 direct_write = rffi.llexternal(
1442 "write", [rffi.INT, rffi.CCHARP, rffi.SIZE_T], lltype.Void,
1443 _nowrapper=True)
1444
1445 class State:
1446 pass
1447 state = State()
1448
1449 class Cons:
1450 def __init__(self, head, tail):
1451 self.head = head
1452 self.tail = tail
1453
1454 class Stuff:
1455 def __del__(self):
1456 p = rffi.str2charp('d')
1457 one = rffi.cast(rffi.SIZE_T, 1)
1458 direct_write(rffi.cast(rffi.INT, state.write_end), p, one)
1459 rffi.free_charp(p)
1460
1461 def allocate_stuff():
1462 s = Stuff()
1463 os.write(state.write_end, 'a')
1464 return s
1465
1466 def run_in_thread():
1467 for i in range(10):
1468 state.xlist.append(Cons(123, Cons(456, None)))
1469 time.sleep(0.01)
1470 childpid = os.fork()
1471 return childpid
1472
1473 def bootstrap():
1474 rthread.gc_thread_start()
1475 childpid = run_in_thread()
1476 gc.collect() # collect both in the child and in the parent
1477 gc.collect()
1478 gc.collect()
1479 if childpid == 0:
1480 os.write(state.write_end, 'c') # "I did not die!" from child
1481 else:
1482 os.write(state.write_end, 'p') # "I did not die!" from parent
1483 rthread.gc_thread_die()
1484
1485 def new_thread():
1486 ident = rthread.start_new_thread(bootstrap, ())
1487 time.sleep(0.5) # enough time to start, hopefully
1488 return ident
1489
1490 def start_arthreads():
1491 s = allocate_stuff()
1492 ident1 = new_thread()
1493 ident2 = new_thread()
1494 ident3 = new_thread()
1495 ident4 = new_thread()
1496 ident5 = new_thread()
1497 # wait for 4 more seconds, which should be plenty of time
1498 time.sleep(4)
1499 keepalive_until_here(s)
1500
1501 def entry_point(argv):
1502 os.write(1, "hello world\n")
1503 state.xlist = []
1504 state.deleted = 0
1505 state.read_end, state.write_end = os.pipe()
1506 x2 = Cons(51, Cons(62, Cons(74, None)))
1507 # start 5 new threads
1508 start_arthreads()
1509 # force freeing
1510 gc.collect()
1511 gc.collect()
1512 gc.collect()
1513 # return everything that was written to the pipe so far,
1514 # followed by the final dot.
1515 os.write(state.write_end, '.')
1516 result = os.read(state.read_end, 256)
1517 os.write(1, "got: %s\n" % result)
1518 return 0
1519
1520 t, cbuilder = self.compile(entry_point)
1521 data = cbuilder.cmdexec('')
1522 print repr(data)
1523 header, footer = data.splitlines()
1524 assert header == 'hello world'
1525 assert footer.startswith('got: ')
1526 result = footer[5:]
1527 # check that all 5 threads and 5 forked processes
1528 # finished successfully, that we did 1 allocation,
1529 # and that it was freed 6 times -- once in the parent
1530 # process and once in every child process.
1531 assert (result[-1] == '.'
1532 and result.count('c') == result.count('p') == 5
1533 and result.count('a') == 1
1534 and result.count('d') == 6)
1535
1536
1537 class TestShared(StandaloneTests):
1538
1539 def test_entrypoint(self):
1540 import ctypes
1541
1542 config = get_combined_translation_config(translating=True)
1543 self.config = config
1544
1545 @entrypoint_highlevel('test', [lltype.Signed], c_name='foo')
1546 def f(a):
1547 return a + 3
1548
1549 def entry_point(argv):
1550 return 0
1551
1552 t, cbuilder = self.compile(entry_point, shared=True,
1553 entrypoints=[f.exported_wrapper],
1554 local_icon='red.ico')
1555 ext_suffix = '.so'
1556 if cbuilder.eci.platform.name == 'msvc':
1557 ext_suffix = '.dll'
1558 elif cbuilder.eci.platform.name.startswith('darwin'):
1559 ext_suffix = '.dylib'
1560 libname = cbuilder.executable_name.join('..', 'lib' +
1561 cbuilder.modulename + ext_suffix)
1562 lib = ctypes.CDLL(str(libname))
1563 if sys.platform == "darwin":
1564 py.test.skip("crashes the interpreter with uninitialized threads")
1565 else:
1566 assert lib.foo(13) == 16