Debian Codegraph @

rpython/translator/c/test/test_newgc.py

raw symbols SCIP
1 import gc
2 import inspect
3 import os
4 import sys
5 import subprocess
6 import random
7
8 import py
9
10 from rpython.conftest import option
11 from rpython.rlib import rgc
12 from rpython.rlib.objectmodel import keepalive_until_here, compute_hash, compute_identity_hash, r_dict
13 from rpython.rlib.rstring import StringBuilder
14 from rpython.rtyper.lltypesystem import lltype, llmemory, rffi
15 from rpython.rtyper.lltypesystem.lloperation import llop
16 from rpython.memory.test import snippet
17 from rpython.tool.udir import udir
18 from rpython.translator.interactive import Translation
19
20
21 class UsingFrameworkTest(object):
22 #gcpolicy = ... specified by subclasses
23 should_be_moving = False
24 removetypeptr = False
25 taggedpointers = False
26 GC_CAN_MOVE = False
27 GC_CAN_SHRINK_ARRAY = False
28
29 _isolated_func = None
30 c_allfuncs = None
31
32 @classmethod
33 def _makefunc_str_int(cls, f):
34 def main(argv):
35 arg0 = argv[1]
36 arg1 = int(argv[2])
37 try:
38 res = f(arg0, arg1)
39 except MemoryError:
40 print "MEMORY-ERROR"
41 else:
42 print res
43 return 0
44
45 t = Translation(main, gc=cls.gcpolicy,
46 taggedpointers=cls.taggedpointers,
47 gcremovetypeptr=cls.removetypeptr)
48 t.disable(['backendopt'])
49 t.set_backend_extra_options(c_debug_defines=True)
50 t.rtype()
51 if option.view:
52 t.viewcg()
53 exename = t.compile()
54
55 def run(s, i, runner=subprocess.check_output):
56 data = runner([str(exename), str(s), str(i)])
57 data = data.strip()
58 if data == 'MEMORY-ERROR':
59 raise MemoryError
60 return data
61
62 return run
63
64 def setup_class(cls):
65 funcs0 = []
66 funcs1 = []
67 funcsstr = []
68 name_to_func = {}
69 for fullname in dir(cls):
70 if not fullname.startswith('define'):
71 continue
72 keyword = option.keyword
73 if keyword.startswith('test_') and not keyword.endswith(':'):
74 keyword = keyword[len('test_'):]
75 if keyword not in fullname:
76 continue
77 prefix, name = fullname.split('_', 1)
78 definefunc = getattr(cls, fullname)
79 func = definefunc.im_func(cls)
80 func.__name__ = 'f_' + name
81 if prefix == 'definestr':
82 funcsstr.append(func)
83 funcs0.append(None)
84 funcs1.append(None)
85 else:
86 numargs = len(inspect.getargspec(func)[0])
87 funcsstr.append(None)
88 if numargs == 0:
89 funcs0.append(func)
90 funcs1.append(None)
91 else:
92 assert numargs == 1
93 funcs0.append(None)
94 funcs1.append(func)
95 assert name not in name_to_func
96 name_to_func[name] = len(name_to_func)
97 assert name_to_func
98
99 def allfuncs(name, arg):
100 num = name_to_func[name]
101 func0 = funcs0[num]
102 if func0:
103 return str(func0())
104 func1 = funcs1[num]
105 if func1:
106 return str(func1(arg))
107 funcstr = funcsstr[num]
108 if funcstr:
109 return funcstr(arg)
110 assert 0, 'unreachable'
111 cls.funcsstr = funcsstr
112 cls.c_allfuncs = staticmethod(cls._makefunc_str_int(allfuncs))
113 cls.allfuncs = staticmethod(allfuncs)
114 cls.name_to_func = name_to_func
115
116 def teardown_class(cls):
117 if hasattr(cls.c_allfuncs, 'close_isolate'):
118 cls.c_allfuncs.close_isolate()
119 cls.c_allfuncs = None
120
121 def run(self, name, *args, **kwds):
122 if not args:
123 args = (-1, )
124 print 'Running %r)' % name
125 res = self.c_allfuncs(name, *args, **kwds)
126 num = self.name_to_func[name]
127 if self.funcsstr[num]:
128 return res
129 return int(res)
130
131 def run_orig(self, name, *args):
132 if not args:
133 args = (-1, )
134 res = self.allfuncs(name, *args)
135 num = self.name_to_func[name]
136 if self.funcsstr[num]:
137 return res
138 return int(res)
139
140 def define_empty_collect(cls):
141 def f():
142 llop.gc__collect(lltype.Void)
143 return 41
144 return f
145
146 def test_empty_collect(self):
147 res = self.run('empty_collect')
148 assert res == 41
149
150 def define_framework_simple(cls):
151 def g(x): # cannot cause a collect
152 return x + 1
153 class A(object):
154 pass
155 def make():
156 a = A()
157 a.b = g(1)
158 return a
159 make._dont_inline_ = True
160 def f():
161 a = make()
162 llop.gc__collect(lltype.Void)
163 return a.b
164 return f
165
166 def test_framework_simple(self):
167 res = self.run('framework_simple')
168 assert res == 2
169
170 def define_framework_safe_pushpop(cls):
171 class A(object):
172 pass
173 class B(object):
174 pass
175 def g(x): # cause a collect
176 llop.gc__collect(lltype.Void)
177 g._dont_inline_ = True
178 global_a = A()
179 global_a.b = B()
180 global_a.b.a = A()
181 global_a.b.a.b = B()
182 global_a.b.a.b.c = 1
183 def make():
184 global_a.b.a.b.c = 40
185 a = global_a.b.a
186 b = a.b
187 b.c = 41
188 g(1)
189 b0 = a.b
190 b0.c = b.c = 42
191 make._dont_inline_ = True
192 def f():
193 make()
194 llop.gc__collect(lltype.Void)
195 return global_a.b.a.b.c
196 return f
197
198 def test_framework_safe_pushpop(self):
199 res = self.run('framework_safe_pushpop')
200 assert res == 42
201
202 def define_framework_protect_getfield(cls):
203 class A(object):
204 pass
205 class B(object):
206 pass
207 def prepare(b, n):
208 a = A()
209 a.value = n
210 b.a = a
211 b.othervalue = 5
212 def g(a):
213 llop.gc__collect(lltype.Void)
214 for i in range(1000):
215 prepare(B(), -1) # probably overwrites collected memory
216 return a.value
217 g._dont_inline_ = True
218 def f():
219 b = B()
220 prepare(b, 123)
221 a = b.a
222 b.a = None
223 return g(a) + b.othervalue
224 return f
225
226 def test_framework_protect_getfield(self):
227 res = self.run('framework_protect_getfield')
228 assert res == 128
229
230 def define_framework_varsized(cls):
231 S = lltype.GcStruct("S", ('x', lltype.Signed))
232 T = lltype.GcStruct("T", ('y', lltype.Signed),
233 ('s', lltype.Ptr(S)))
234 ARRAY_Ts = lltype.GcArray(lltype.Ptr(T))
235
236 def f():
237 r = 0
238 for i in range(30):
239 a = lltype.malloc(ARRAY_Ts, i)
240 for j in range(i):
241 a[j] = lltype.malloc(T)
242 a[j].y = i
243 a[j].s = lltype.malloc(S)
244 a[j].s.x = 2 * i
245 r += a[j].y + a[j].s.x
246 a[j].s = lltype.malloc(S)
247 a[j].s.x = 3 * i
248 r -= a[j].s.x
249 for j in range(i):
250 r += a[j].y
251 return r
252 return f
253
254 def test_framework_varsized(self):
255 res = self.run('framework_varsized')
256 assert res == self.run_orig('framework_varsized')
257
258 def define_framework_using_lists(cls):
259 class A(object):
260 pass
261 N = 1000
262 def f():
263 static_list = []
264 for i in range(N):
265 a = A()
266 a.x = i
267 static_list.append(a)
268 r = 0
269 for a in static_list:
270 r += a.x
271 return r
272 return f
273
274 def test_framework_using_lists(self):
275 N = 1000
276 res = self.run('framework_using_lists')
277 assert res == N * (N - 1) / 2
278
279 def define_framework_static_roots(cls):
280 class A(object):
281 def __init__(self, y):
282 self.y = y
283 a = A(0)
284 a.x = None
285 def make():
286 a.x = A(42)
287 make._dont_inline_ = True
288 def f():
289 make()
290 llop.gc__collect(lltype.Void)
291 return a.x.y
292 return f
293
294 def test_framework_static_roots(self):
295 res = self.run('framework_static_roots')
296 assert res == 42
297
298 def define_framework_nongc_static_root(cls):
299 S = lltype.GcStruct("S", ('x', lltype.Signed))
300 T = lltype.Struct("T", ('p', lltype.Ptr(S)))
301 t = lltype.malloc(T, immortal=True)
302 def f():
303 t.p = lltype.malloc(S)
304 t.p.x = 43
305 for i in range(2500000):
306 s = lltype.malloc(S)
307 s.x = i
308 return t.p.x
309 return f
310
311 def test_framework_nongc_static_root(self):
312 res = self.run('framework_nongc_static_root')
313 assert res == 43
314
315 def define_framework_void_array(cls):
316 A = lltype.GcArray(lltype.Void)
317 a = lltype.malloc(A, 44)
318 def f():
319 return len(a)
320 return f
321
322 def test_framework_void_array(self):
323 res = self.run('framework_void_array')
324 assert res == 44
325
326 def define_framework_malloc_failure(cls):
327 def f():
328 a = [1] * (sys.maxint // 2)
329 return len(a) + a[0]
330 return f
331
332 def test_framework_malloc_failure(self):
333 py.test.raises(MemoryError, self.run, 'framework_malloc_failure')
334
335 def define_framework_array_of_void(cls):
336 def f():
337 a = [None] * 43
338 b = []
339 for i in range(1000000):
340 a.append(None)
341 b.append(len(a))
342 return b[-1]
343 return f
344
345 def test_framework_array_of_void(self):
346 res = self.run('framework_array_of_void')
347 assert res == 43 + 1000000
348
349 def define_framework_opaque(cls):
350 A = lltype.GcStruct('A', ('value', lltype.Signed))
351 O = lltype.GcOpaqueType('test.framework')
352
353 def gethidden(n):
354 a = lltype.malloc(A)
355 a.value = -n * 7
356 return lltype.cast_opaque_ptr(lltype.Ptr(O), a)
357 gethidden._dont_inline_ = True
358 def reveal(o):
359 return lltype.cast_opaque_ptr(lltype.Ptr(A), o)
360 def overwrite(a, i):
361 a.value = i
362 overwrite._dont_inline_ = True
363 def f():
364 o = gethidden(10)
365 llop.gc__collect(lltype.Void)
366 for i in range(1000): # overwrite freed memory
367 overwrite(lltype.malloc(A), i)
368 a = reveal(o)
369 return a.value
370 return f
371
372 def test_framework_opaque(self):
373 res = self.run('framework_opaque')
374 assert res == -70
375
376 def define_framework_finalizer(cls):
377 class B(object):
378 pass
379 b = B()
380 b.nextid = 0
381 b.num_deleted = 0
382 class A(object):
383 def __init__(self):
384 self.id = b.nextid
385 b.nextid += 1
386 def __del__(self):
387 b.num_deleted += 1
388 def f():
389 a = A()
390 i = 0
391 while i < 5:
392 i += 1
393 a = A()
394 llop.gc__collect(lltype.Void)
395 llop.gc__collect(lltype.Void)
396 return b.num_deleted
397 return f
398
399 def test_framework_finalizer(self):
400 res = self.run('framework_finalizer')
401 assert res == 6
402
403 def define_del_catches(cls):
404 def g():
405 pass
406 class A(object):
407 def __del__(self):
408 try:
409 g()
410 except:
411 pass #os.write(1, "hallo")
412 def f1(i):
413 if i:
414 raise TypeError
415 def f(i):
416 a = A()
417 f1(i)
418 a.b = 1
419 llop.gc__collect(lltype.Void)
420 return a.b
421 def h(x):
422 try:
423 return f(x)
424 except TypeError:
425 return 42
426 return h
427
428 def test_del_catches(self):
429 res = self.run('del_catches', 0)
430 assert res == 1
431 res = self.run('del_catches', 1)
432 assert res == 42
433
434 def define_del_raises(cls):
435 class B(object):
436 def __del__(self):
437 raise TypeError
438 def func():
439 b = B()
440 return 0
441 return func
442
443 def test_del_raises(self):
444 self.run('del_raises') # does not raise
445
446 def define_custom_trace(cls):
447 from rpython.rtyper.annlowlevel import llhelper
448 #
449 S = lltype.GcStruct('S', ('x', llmemory.Address))
450 offset_of_x = llmemory.offsetof(S, 'x')
451 def customtrace(gc, obj, callback, arg1, arg2):
452 gc._trace_callback(callback, arg1, arg2, obj + offset_of_x)
453 lambda_customtrace = lambda: customtrace
454 #
455 def setup():
456 rgc.register_custom_trace_hook(S, lambda_customtrace)
457 s = lltype.nullptr(S)
458 for i in range(10000):
459 t = lltype.malloc(S)
460 t.x = llmemory.cast_ptr_to_adr(s)
461 s = t
462 return s
463 def measure_length(s):
464 res = 0
465 while s:
466 res += 1
467 s = llmemory.cast_adr_to_ptr(s.x, lltype.Ptr(S))
468 return res
469 def f(n):
470 s1 = setup()
471 llop.gc__collect(lltype.Void)
472 return measure_length(s1)
473 return f
474
475 def test_custom_trace(self):
476 res = self.run('custom_trace', 0)
477 assert res == 10000
478
479 def define_custom_light_finalizer(cls):
480 from rpython.rtyper.annlowlevel import llhelper
481 #
482 T = lltype.Struct('T', ('count', lltype.Signed))
483 t = lltype.malloc(T, zero=True, immortal=True, flavor='raw')
484 #
485 S = lltype.GcStruct('S', rtti=True)
486 def customlightfinlz(addr):
487 t.count += 1
488 lambda_customlightfinlz = lambda: customlightfinlz
489 #
490 def setup():
491 rgc.register_custom_light_finalizer(S, lambda_customlightfinlz)
492 for i in range(10000):
493 lltype.malloc(S)
494 def f(n):
495 setup()
496 llop.gc__collect(lltype.Void)
497 return t.count
498 return f
499
500 def test_custom_light_finalizer(self):
501 res = self.run('custom_light_finalizer', 0)
502 assert res == 10000
503
504 def define_weakref(cls):
505 import weakref
506
507 class A:
508 pass
509
510 keepalive = []
511 def fn():
512 n = 7000
513 weakrefs = []
514 a = None
515 for i in range(n):
516 if i & 1 == 0:
517 a = A()
518 a.index = i
519 assert a is not None
520 weakrefs.append(weakref.ref(a))
521 if i % 7 == 6:
522 keepalive.append(a)
523 rgc.collect()
524 count_free = 0
525 for i in range(n):
526 a = weakrefs[i]()
527 if i % 7 == 6:
528 assert a is not None
529 if a is not None:
530 assert a.index == i & ~1
531 else:
532 count_free += 1
533 return count_free
534 return fn
535
536 def test_weakref(self):
537 res = self.run('weakref')
538 # more than half of them should have been freed, ideally up to 6000
539 assert 3500 <= res <= 6000
540
541 def define_prebuilt_weakref(cls):
542 import weakref
543 class A:
544 pass
545 a = A()
546 a.hello = 42
547 refs = [weakref.ref(a), weakref.ref(A())]
548 rgc.collect()
549 def fn():
550 result = 0
551 for i in range(2):
552 a = refs[i]()
553 rgc.collect()
554 if a is None:
555 result += (i + 1)
556 else:
557 result += a.hello * (i + 1)
558 return result
559 return fn
560
561 def test_prebuilt_weakref(self):
562 res = self.run('prebuilt_weakref')
563 assert res == self.run_orig('prebuilt_weakref')
564
565 def define_prebuilt_dicts_of_all_sizes(self):
566 class X:
567 pass
568 dlist = []
569 keyslist = []
570 def keq(x, y):
571 return x is y
572 def khash(x):
573 return compute_hash(x)
574 for size in ([random.randrange(0, 260) for i in range(10)] +
575 [random.randrange(260, 60000)]):
576 #print 'PREBUILT DICTIONARY OF SIZE', size
577 keys = [X() for j in range(size)]
578 d = r_dict(keq, khash)
579 for j in range(size):
580 d[keys[j]] = j
581 dlist.append(d)
582 keyslist.append(keys)
583
584 def fn():
585 for n in range(len(dlist)):
586 d = dlist[n]
587 keys = keyslist[n]
588 assert len(d) == len(keys)
589 i = 0
590 while i < len(keys):
591 assert d[keys[i]] == i
592 i += 1
593 return 42
594 return fn
595
596 def test_prebuilt_dicts_of_all_sizes(self):
597 res = self.run('prebuilt_dicts_of_all_sizes')
598 assert res == 42
599
600 def define_framework_malloc_raw(cls):
601 A = lltype.Struct('A', ('value', lltype.Signed))
602
603 def f():
604 p = lltype.malloc(A, flavor='raw')
605 p.value = 123
606 llop.gc__collect(lltype.Void)
607 res = p.value
608 lltype.free(p, flavor='raw')
609 return res
610 return f
611
612 def test_framework_malloc_raw(self):
613 res = self.run('framework_malloc_raw')
614 assert res == 123
615
616 def define_framework_del_seeing_new_types(cls):
617 class B(object):
618 pass
619 class A(object):
620 def __del__(self):
621 B()
622 def f():
623 A()
624 return 42
625 return f
626
627 def test_framework_del_seeing_new_types(self):
628 res = self.run('framework_del_seeing_new_types')
629 assert res == 42
630
631 def define_framework_late_filling_pointers(cls):
632 A = lltype.GcStruct('A', ('x', lltype.Signed))
633 B = lltype.GcStruct('B', ('a', lltype.Ptr(A)))
634
635 def f():
636 p = lltype.malloc(B)
637 llop.gc__collect(lltype.Void)
638 p.a = lltype.malloc(A)
639 return p.a.x
640 return f
641
642 def test_framework_late_filling_pointers(self):
643 # the point is just not to segfault
644 self.run('framework_late_filling_pointers')
645
646 def define_zero_raw_malloc(cls):
647 S = lltype.Struct('S', ('x', lltype.Signed), ('y', lltype.Signed))
648 def f():
649 for i in range(100):
650 p = lltype.malloc(S, flavor='raw', zero=True)
651 if p.x != 0 or p.y != 0:
652 return -1
653 p.x = i
654 p.y = i
655 lltype.free(p, flavor='raw')
656 return 42
657
658 return f
659
660 def test_zero_raw_malloc(self):
661 res = self.run('zero_raw_malloc')
662 assert res == 42
663
664 def define_object_alignment(cls):
665 # all objects returned by the GC should be properly aligned.
666 from rpython.rtyper.lltypesystem import rffi
667 mylist = ['a', 'bc', '84139871', 'ajkdh', '876']
668 def f():
669 result = 0
670 buffer = ""
671 for j in range(100):
672 for s in mylist:
673 buffer += s
674 addr = rffi.cast(lltype.Signed, buffer)
675 result |= addr
676 return result
677
678 return f
679
680 def test_object_alignment(self):
681 res = self.run('object_alignment')
682 from rpython.rtyper.tool import rffi_platform
683 expected_alignment = rffi_platform.memory_alignment()
684 assert (res & (expected_alignment - 1)) == 0
685
686 def define_void_list(cls):
687 class E:
688 def __init__(self):
689 self.l = []
690 def f():
691 e = E()
692 return len(e.l)
693 return f
694
695 def test_void_list(self):
696 assert self.run('void_list') == 0
697
698 filename = str(udir.join('test_open_read_write_close.txt'))
699 def define_open_read_write_seek_close(cls):
700 filename = cls.filename
701 def does_stuff():
702 fd = os.open(filename, os.O_WRONLY | os.O_CREAT, 0777)
703 count = os.write(fd, "hello world\n")
704 assert count == len("hello world\n")
705 os.close(fd)
706 fd = os.open(filename, os.O_RDONLY, 0777)
707 result = os.lseek(fd, 1, 0)
708 assert result == 1
709 data = os.read(fd, 500)
710 assert data == "ello world\n"
711 os.close(fd)
712 return 0
713
714 return does_stuff
715
716 def test_open_read_write_seek_close(self):
717 self.run('open_read_write_seek_close')
718 with open(self.filename, 'r') as fid:
719 assert fid.read() == "hello world\n"
720 os.unlink(self.filename)
721
722 def define_callback_with_collect(cls):
723 from rpython.rlib.clibffi import ffi_type_pointer, cast_type_to_ffitype,\
724 CDLL, ffi_type_void, CallbackFuncPtr, ffi_type_sint
725 ffi_size_t = cast_type_to_ffitype(rffi.SIZE_T)
726
727 from rpython.rlib.clibffi import get_libc_name
728
729 def callback(ll_args, ll_res, stuff):
730 gc.collect()
731 p_a1 = rffi.cast(rffi.VOIDPP, ll_args[0])[0]
732 p_a2 = rffi.cast(rffi.VOIDPP, ll_args[1])[0]
733 a1 = rffi.cast(rffi.SIGNEDP, p_a1)[0]
734 a2 = rffi.cast(rffi.SIGNEDP, p_a2)[0]
735 # related to libffi issue on s390x, we MUST
736 # overwrite the full ffi result which is 64 bit
737 # if not, this leaves garbage in the return value
738 # and qsort does not sort correctly
739 res = rffi.cast(rffi.SIGNEDP, ll_res)
740 if a1 > a2:
741 res[0] = 1
742 else:
743 res[0] = -1
744
745 def f():
746 libc = CDLL(get_libc_name())
747 qsort = libc.getpointer('qsort', [ffi_type_pointer, ffi_size_t,
748 ffi_size_t, ffi_type_pointer],
749 ffi_type_void)
750
751 ptr = CallbackFuncPtr([ffi_type_pointer, ffi_type_pointer, ffi_type_pointer],
752 ffi_type_sint, callback)
753
754 TP = rffi.CArray(lltype.Signed)
755 to_sort = lltype.malloc(TP, 4, flavor='raw')
756 to_sort[0] = 4
757 to_sort[1] = 3
758 to_sort[2] = 1
759 to_sort[3] = 2
760 qsort.push_arg(rffi.cast(rffi.VOIDP, to_sort))
761 qsort.push_arg(rffi.cast(rffi.SIZE_T, 4))
762 qsort.push_arg(rffi.cast(rffi.SIZE_T, rffi.sizeof(lltype.Signed)))
763 qsort.push_arg(rffi.cast(rffi.VOIDP, ptr.get_closure()))
764 qsort.call(lltype.Void)
765 result = [to_sort[i] for i in range(4)] == [1, 2, 3, 4]
766 lltype.free(to_sort, flavor='raw')
767 keepalive_until_here(ptr)
768 return int(result)
769
770 return f
771
772 def test_callback_with_collect(self):
773 assert self.run('callback_with_collect')
774
775 def define_can_move(cls):
776 class A:
777 pass
778 def fn():
779 return rgc.can_move(A())
780 return fn
781
782 def test_can_move(self):
783 assert self.run('can_move') == self.GC_CAN_MOVE
784
785 def define_resizable_buffer(cls):
786 from rpython.rtyper.lltypesystem.rstr import STR
787
788 def f():
789 ptr = lltype.malloc(STR, 3)
790 ptr.hash = 0x62
791 ptr.chars[0] = '0'
792 ptr.chars[1] = 'B'
793 ptr.chars[2] = 'C'
794 ptr2 = rgc.ll_shrink_array(ptr, 2)
795 return ((ptr == ptr2) +
796 ord(ptr2.chars[0]) +
797 (ord(ptr2.chars[1]) << 8) +
798 (len(ptr2.chars) << 16) +
799 (ptr2.hash << 24))
800 return f
801
802 def test_resizable_buffer(self):
803 res = self.run('resizable_buffer')
804 if self.GC_CAN_SHRINK_ARRAY:
805 expected = 0x62024231
806 else:
807 expected = 0x62024230
808 assert res == expected
809
810 def define_hash_preservation(cls):
811 class C:
812 pass
813 class D(C):
814 pass
815 c = C()
816 d = D()
817 h_d = compute_hash(d) # force to be cached on 'd', but not on 'c'
818 h_t = compute_hash(("Hi", None, (7.5, 2)))
819 S = lltype.GcStruct('S', ('x', lltype.Signed),
820 ('a', lltype.Array(lltype.Signed)))
821 s = lltype.malloc(S, 15, zero=True)
822 h_s = compute_identity_hash(s) # varsized: hash not saved/restored
823 #
824 def f():
825 if compute_hash(c) != compute_identity_hash(c):
826 return 12
827 if compute_hash(d) == h_d: # likely *not* preserved
828 return 13
829 if compute_hash(("Hi", None, (7.5, 2))) != h_t:
830 return 14 # ^^ true as long as we're not using e.g. siphash24
831 c2 = C()
832 h_c2 = compute_hash(c2)
833 if compute_hash(c2) != h_c2:
834 return 15
835 if compute_identity_hash(s) == h_s:
836 return 16 # unlikely
837 i = 0
838 while i < 6:
839 rgc.collect()
840 if compute_hash(c2) != h_c2:
841 return i
842 i += 1
843 return 42
844 return f
845
846 def test_hash_preservation(self):
847 res = self.run('hash_preservation')
848 assert res == 42
849
850 def define_hash_overflow(self):
851 class X(object):
852 pass
853
854 def g(n):
855 "Make a chain of n objects."
856 x1 = None
857 i = 0
858 while i < n:
859 x2 = X()
860 x2.prev = x1
861 x1 = x2
862 i += 1
863 return x1
864
865 def build(xr, n):
866 "Build the identity hashes of all n objects of the chain."
867 i = 0
868 while i < n:
869 xr.hash = compute_identity_hash(xr)
870 # ^^^ likely to trigger a collection
871 xr = xr.prev
872 i += 1
873 assert xr is None
874
875 def check(xr, n, step):
876 "Check that the identity hashes are still correct."
877 i = 0
878 while i < n:
879 if xr.hash != compute_identity_hash(xr):
880 os.write(2, "wrong hash! i=%d, n=%d, step=%d\n" % (i, n,
881 step))
882 raise ValueError
883 xr = xr.prev
884 i += 1
885 assert xr is None
886
887 def h(n):
888 x3 = g(3)
889 x4 = g(3)
890 x1 = g(n)
891 build(x1, n) # can collect!
892 check(x1, n, 1)
893 build(x3, 3)
894 x2 = g(n // 2) # allocate more and try again
895 build(x2, n // 2)
896 check(x1, n, 11)
897 check(x2, n // 2, 12)
898 build(x4, 3)
899 check(x3, 3, 13) # check these old objects too
900 check(x4, 3, 14) # check these old objects too
901 rgc.collect()
902 check(x1, n, 21)
903 check(x2, n // 2, 22)
904 check(x3, 3, 23)
905 check(x4, 3, 24)
906
907 def f():
908 # numbers optimized for a 8MB space
909 for n in [100000, 225000, 250000, 300000, 380000,
910 460000, 570000, 800000]:
911 os.write(2, 'case %d\n' % n)
912 rgc.collect()
913 h(n)
914 return -42
915
916 return f
917
918 def test_hash_overflow(self):
919 res = self.run('hash_overflow')
920 assert res == -42
921
922 def define_hash_varsized(self):
923 S = lltype.GcStruct('S', ('abc', lltype.Signed),
924 ('def', lltype.Array(lltype.Signed)))
925 s = lltype.malloc(S, 3, zero=True)
926 h_s = lltype.identityhash(s)
927 def f():
928 return lltype.identityhash(s) - h_s # != 0 (so far),
929 # because S is a varsized structure.
930 return f
931
932 def test_hash_varsized(self):
933 res = self.run('hash_varsized')
934 assert res != 0
935
936 def define_arraycopy_writebarrier_int(cls):
937 TP = lltype.GcArray(lltype.Signed)
938 S = lltype.GcStruct('S')
939 def fn():
940 l = lltype.malloc(TP, 100)
941 for i in range(100):
942 l[i] = i * 3
943 l2 = lltype.malloc(TP, 50)
944 rgc.ll_arraycopy(l, l2, 40, 0, 50)
945 # force a nursery collect
946 x = []
947 for i in range(20):
948 x.append((1, lltype.malloc(S)))
949 for i in range(50):
950 assert l2[i] == (40 + i) * 3
951 return 0
952
953 return fn
954
955 def test_arraycopy_writebarrier_int(self):
956 self.run("arraycopy_writebarrier_int")
957
958 def define_arraycopy_writebarrier_ptr(cls):
959 TP = lltype.GcArray(lltype.Ptr(lltype.GcArray(lltype.Signed)))
960 def fn():
961 l = lltype.malloc(TP, 100)
962 for i in range(100):
963 l[i] = lltype.malloc(TP.OF.TO, i)
964 l2 = lltype.malloc(TP, 50)
965 rgc.ll_arraycopy(l, l2, 40, 0, 50)
966 rgc.collect()
967 for i in range(50):
968 assert l2[i] == l[40 + i]
969 return 0
970
971 return fn
972
973 def test_arraycopy_writebarrier_ptr(self):
974 self.run("arraycopy_writebarrier_ptr")
975
976 def define_get_rpy_roots(self):
977 U = lltype.GcStruct('U', ('x', lltype.Signed))
978 S = lltype.GcStruct('S', ('u', lltype.Ptr(U)))
979
980 def g(s):
981 lst = rgc.get_rpy_roots()
982 found = False
983 for x in lst:
984 if x == lltype.cast_opaque_ptr(llmemory.GCREF, s):
985 found = True
986 if x == lltype.cast_opaque_ptr(llmemory.GCREF, s.u):
987 os.write(2, "s.u should not be found!\n")
988 assert False
989 return found == 1
990
991 def fn():
992 s = lltype.malloc(S)
993 s.u = lltype.malloc(U)
994 found = g(s)
995 if not found:
996 os.write(2, "not found!\n")
997 assert False
998 s.u.x = 42
999 return 0
1000
1001 return fn
1002
1003 def test_get_rpy_roots(self):
1004 self.run("get_rpy_roots")
1005
1006 def define_get_rpy_referents(self):
1007 U = lltype.GcStruct('U', ('x', lltype.Signed))
1008 S = lltype.GcStruct('S', ('u', lltype.Ptr(U)))
1009
1010 def fn():
1011 s = lltype.malloc(S)
1012 s.u = lltype.malloc(U)
1013 gcref1 = lltype.cast_opaque_ptr(llmemory.GCREF, s)
1014 gcref2 = lltype.cast_opaque_ptr(llmemory.GCREF, s.u)
1015 lst = rgc.get_rpy_referents(gcref1)
1016 assert gcref2 in lst
1017 assert gcref1 not in lst
1018 s.u.x = 42
1019 return 0
1020
1021 return fn
1022
1023 def test_get_rpy_referents(self):
1024 self.run("get_rpy_referents")
1025
1026 def define_is_rpy_instance(self):
1027 class Foo:
1028 pass
1029 S = lltype.GcStruct('S', ('x', lltype.Signed))
1030
1031 def check(gcref, expected):
1032 result = rgc._is_rpy_instance(gcref)
1033 assert result == expected
1034
1035 def fn():
1036 s = lltype.malloc(S)
1037 gcref1 = lltype.cast_opaque_ptr(llmemory.GCREF, s)
1038 check(gcref1, False)
1039
1040 f = Foo()
1041 gcref3 = rgc.cast_instance_to_gcref(f)
1042 check(gcref3, True)
1043
1044 return 0
1045
1046 return fn
1047
1048 def test_is_rpy_instance(self):
1049 self.run("is_rpy_instance")
1050
1051 def define_try_cast_gcref_to_instance(self):
1052 class Foo:
1053 pass
1054 class FooBar(Foo):
1055 pass
1056 class Biz(object):
1057 pass
1058 S = lltype.GcStruct('S', ('x', lltype.Signed))
1059
1060 def fn():
1061 foo = Foo()
1062 gcref1 = rgc.cast_instance_to_gcref(foo)
1063 assert rgc.try_cast_gcref_to_instance(Foo, gcref1) is foo
1064 assert rgc.try_cast_gcref_to_instance(FooBar, gcref1) is None
1065 assert rgc.try_cast_gcref_to_instance(Biz, gcref1) is None
1066
1067 foobar = FooBar()
1068 gcref2 = rgc.cast_instance_to_gcref(foobar)
1069 assert rgc.try_cast_gcref_to_instance(Foo, gcref2) is foobar
1070 assert rgc.try_cast_gcref_to_instance(FooBar, gcref2) is foobar
1071 assert rgc.try_cast_gcref_to_instance(Biz, gcref2) is None
1072
1073 s = lltype.malloc(S)
1074 gcref3 = lltype.cast_opaque_ptr(llmemory.GCREF, s)
1075 assert rgc.try_cast_gcref_to_instance(Foo, gcref3) is None
1076 assert rgc.try_cast_gcref_to_instance(FooBar, gcref3) is None
1077 assert rgc.try_cast_gcref_to_instance(Biz, gcref3) is None
1078
1079 return 0
1080
1081 return fn
1082
1083 def test_try_cast_gcref_to_instance(self):
1084 self.run("try_cast_gcref_to_instance")
1085
1086 def define_get_rpy_memory_usage(self):
1087 U = lltype.GcStruct('U', ('x1', lltype.Signed),
1088 ('x2', lltype.Signed),
1089 ('x3', lltype.Signed),
1090 ('x4', lltype.Signed),
1091 ('x5', lltype.Signed),
1092 ('x6', lltype.Signed),
1093 ('x7', lltype.Signed),
1094 ('x8', lltype.Signed))
1095 S = lltype.GcStruct('S', ('u', lltype.Ptr(U)))
1096 A = lltype.GcArray(lltype.Ptr(S))
1097
1098 def fn():
1099 s = lltype.malloc(S)
1100 s.u = lltype.malloc(U)
1101 a = lltype.malloc(A, 1000)
1102 gcref1 = lltype.cast_opaque_ptr(llmemory.GCREF, s)
1103 int1 = rgc.get_rpy_memory_usage(gcref1)
1104 assert 8 <= int1 <= 32
1105 gcref2 = lltype.cast_opaque_ptr(llmemory.GCREF, s.u)
1106 int2 = rgc.get_rpy_memory_usage(gcref2)
1107 assert 4 * 9 <= int2 <= 8 * 12
1108 gcref3 = lltype.cast_opaque_ptr(llmemory.GCREF, a)
1109 int3 = rgc.get_rpy_memory_usage(gcref3)
1110 assert 4 * 1001 <= int3 <= 8 * 1010
1111 return 0
1112
1113 return fn
1114
1115 def test_get_rpy_memory_usage(self):
1116 self.run("get_rpy_memory_usage")
1117
1118 def define_get_rpy_type_index(self):
1119 U = lltype.GcStruct('U', ('x', lltype.Signed))
1120 S = lltype.GcStruct('S', ('u', lltype.Ptr(U)))
1121 A = lltype.GcArray(lltype.Ptr(S))
1122
1123 def fn():
1124 s = lltype.malloc(S)
1125 s.u = lltype.malloc(U)
1126 a = lltype.malloc(A, 1000)
1127 s2 = lltype.malloc(S)
1128 gcref1 = lltype.cast_opaque_ptr(llmemory.GCREF, s)
1129 int1 = rgc.get_rpy_type_index(gcref1)
1130 gcref2 = lltype.cast_opaque_ptr(llmemory.GCREF, s.u)
1131 int2 = rgc.get_rpy_type_index(gcref2)
1132 gcref3 = lltype.cast_opaque_ptr(llmemory.GCREF, a)
1133 int3 = rgc.get_rpy_type_index(gcref3)
1134 gcref4 = lltype.cast_opaque_ptr(llmemory.GCREF, s2)
1135 int4 = rgc.get_rpy_type_index(gcref4)
1136 assert int1 != int2
1137 assert int1 != int3
1138 assert int2 != int3
1139 assert int1 == int4
1140 return 0
1141
1142 return fn
1143
1144 def test_get_rpy_type_index(self):
1145 self.run("get_rpy_type_index")
1146
1147 filename1_dump = str(udir.join('test_dump_rpy_heap.1'))
1148 filename2_dump = str(udir.join('test_dump_rpy_heap.2'))
1149 def define_dump_rpy_heap(self):
1150 U = lltype.GcForwardReference()
1151 U.become(lltype.GcStruct('U', ('next', lltype.Ptr(U)),
1152 ('x', lltype.Signed)))
1153 S = lltype.GcStruct('S', ('u', lltype.Ptr(U)))
1154 A = lltype.GcArray(lltype.Ptr(S))
1155 filename1 = self.filename1_dump
1156 filename2 = self.filename2_dump
1157
1158 def fn():
1159 s = lltype.malloc(S)
1160 s.u = lltype.malloc(U)
1161 s.u.next = lltype.malloc(U)
1162 s.u.next.next = lltype.malloc(U)
1163 a = lltype.malloc(A, 1000)
1164 s2 = lltype.malloc(S)
1165 #
1166 fd1 = os.open(filename1, os.O_WRONLY | os.O_CREAT, 0666)
1167 fd2 = os.open(filename2, os.O_WRONLY | os.O_CREAT, 0666)
1168 # try to ensure we get twice the exact same output below
1169 gc.collect(); gc.collect(); gc.collect()
1170 rgc.dump_rpy_heap(fd1)
1171 rgc.dump_rpy_heap(fd2) # try twice in a row
1172 keepalive_until_here(s2)
1173 keepalive_until_here(s)
1174 keepalive_until_here(a)
1175 os.close(fd1)
1176 os.close(fd2)
1177 return 0
1178
1179 return fn
1180
1181 def test_dump_rpy_heap(self):
1182 self.run("dump_rpy_heap")
1183 for fn in [self.filename1_dump, self.filename2_dump]:
1184 assert os.path.exists(fn)
1185 assert os.path.getsize(fn) > 64
1186 f = open(self.filename1_dump)
1187 data1 = f.read()
1188 f.close()
1189 f = open(self.filename2_dump)
1190 data2 = f.read()
1191 f.close()
1192 assert data1 == data2
1193
1194 filename_dump_typeids_z = str(udir.join('test_typeids_z'))
1195 def define_write_typeids_z(self):
1196 U = lltype.GcForwardReference()
1197 U.become(lltype.GcStruct('U', ('next', lltype.Ptr(U)),
1198 ('x', lltype.Signed)))
1199 S = lltype.GcStruct('S', ('u', lltype.Ptr(U)))
1200 A = lltype.GcArray(lltype.Ptr(S))
1201 filename = self.filename_dump_typeids_z
1202 open_flags = os.O_WRONLY | os.O_CREAT | getattr(os, 'O_BINARY', 0)
1203
1204 def fn():
1205 s = lltype.malloc(S)
1206 s.u = lltype.malloc(U)
1207 s.u.next = lltype.malloc(U)
1208 s.u.next.next = lltype.malloc(U)
1209 a = lltype.malloc(A, 1000)
1210 s2 = lltype.malloc(S)
1211 #
1212 p = rgc.get_typeids_z()
1213 s = ''.join([p[i] for i in range(len(p))])
1214 fd = os.open(filename, open_flags, 0666)
1215 os.write(fd, s)
1216 os.close(fd)
1217 #
1218 a = rgc.get_typeids_list()
1219 assert len(a) > 1
1220 assert 0 < rffi.cast(lltype.Signed, a[1]) < 10000
1221 return 0
1222
1223 return fn
1224
1225 def test_write_typeids_z(self):
1226 self.run("write_typeids_z")
1227 f = open(self.filename_dump_typeids_z, 'rb')
1228 data_z = f.read()
1229 f.close()
1230 import zlib
1231 data = zlib.decompress(data_z)
1232 assert data.startswith('member0')
1233 assert 'GcArray of * GcStruct S {' in data
1234
1235 def define_gcflag_extra(self):
1236 class A:
1237 pass
1238 a1 = A()
1239 def fn():
1240 a2 = A()
1241 if not rgc.has_gcflag_extra():
1242 return 0 # cannot test it then
1243 assert rgc.get_gcflag_extra(a1) == False
1244 assert rgc.get_gcflag_extra(a2) == False
1245 rgc.toggle_gcflag_extra(a1)
1246 assert rgc.get_gcflag_extra(a1) == True
1247 assert rgc.get_gcflag_extra(a2) == False
1248 rgc.toggle_gcflag_extra(a2)
1249 assert rgc.get_gcflag_extra(a1) == True
1250 assert rgc.get_gcflag_extra(a2) == True
1251 rgc.toggle_gcflag_extra(a1)
1252 assert rgc.get_gcflag_extra(a1) == False
1253 assert rgc.get_gcflag_extra(a2) == True
1254 rgc.toggle_gcflag_extra(a2)
1255 assert rgc.get_gcflag_extra(a1) == False
1256 assert rgc.get_gcflag_extra(a2) == False
1257 return 0
1258 return fn
1259
1260 def test_gcflag_extra(self):
1261 self.run("gcflag_extra")
1262
1263 def define_check_zero_works(self):
1264 S = lltype.GcStruct("s", ('x', lltype.Signed))
1265 S2 = lltype.GcStruct("s2", ('parent',
1266 lltype.Struct("s1", ("x", lltype.Signed))),
1267 ('y', lltype.Signed))
1268 A = lltype.GcArray(lltype.Signed)
1269 B = lltype.GcStruct("b", ('x', lltype.Signed),
1270 ('y', lltype.Array(lltype.Signed)))
1271
1272 def fn():
1273 s = lltype.malloc(S, zero=True)
1274 assert s.x == 0
1275 s2 = lltype.malloc(S2, zero=True)
1276 assert s2.parent.x == 0
1277 a = lltype.malloc(A, 3, zero=True)
1278 assert a[2] == 0
1279 # XXX not supported right now in gctransform/framework.py:
1280 #b = lltype.malloc(B, 3, zero=True)
1281 #assert len(b.y) == 3
1282 #assert b.x == 0
1283 #assert b.y[0] == b.y[1] == b.y[2] == 0
1284 return 0
1285 return fn
1286
1287 def test_check_zero_works(self):
1288 self.run("check_zero_works")
1289
1290 def define_long_chain_of_instances(self):
1291 class A(object):
1292 def __init__(self, next):
1293 self.next = next
1294 a = None
1295 for i in range(1500):
1296 a = A(a)
1297
1298 def fn():
1299 i = 0
1300 x = a
1301 while x is not None:
1302 i += 1
1303 x = x.next
1304 return i
1305 return fn
1306
1307 def test_long_chain_of_instances(self):
1308 res = self.run("long_chain_of_instances")
1309 assert res == 1500
1310
1311
1312 class TestSemiSpaceGC(UsingFrameworkTest, snippet.SemiSpaceGCTestDefines):
1313 gcpolicy = "semispace"
1314 should_be_moving = True
1315 GC_CAN_MOVE = True
1316 GC_CAN_SHRINK_ARRAY = True
1317
1318 # for snippets
1319 large_tests_ok = True
1320
1321 def define_many_ids(cls):
1322 from rpython.rlib.objectmodel import compute_unique_id
1323 class A(object):
1324 pass
1325 def f():
1326 from rpython.rtyper.lltypesystem import lltype, rffi
1327 alist = [A() for i in range(50000)]
1328 idarray = lltype.malloc(rffi.SIGNEDP.TO, len(alist), flavor='raw')
1329 # Compute the id of all elements of the list. The goal is
1330 # to not allocate memory, so that if the GC needs memory to
1331 # remember the ids, it will trigger some collections itself
1332 i = 0
1333 while i < len(alist):
1334 idarray[i] = compute_unique_id(alist[i])
1335 i += 1
1336 j = 0
1337 while j < 2:
1338 if j == 1: # allocate some stuff between the two iterations
1339 [A() for i in range(20000)]
1340 i = 0
1341 while i < len(alist):
1342 if idarray[i] != compute_unique_id(alist[i]):
1343 return j * 1000000 + i
1344 i += 1
1345 j += 1
1346 lltype.free(idarray, flavor='raw')
1347 return -2
1348 return f
1349
1350 def test_many_ids(self):
1351 res = self.run('many_ids')
1352 assert res == -2
1353
1354 def define_gc_set_max_heap_size(cls):
1355 def g(n):
1356 return 'x' * n
1357 def fn():
1358 # the semispace size starts at 8MB for now, so setting a
1359 # smaller limit has no effect
1360 # set to more than 32MB -- which should be rounded down to 32MB
1361 rgc.set_max_heap_size(32 * 1024 * 1024 + 20000)
1362 s1 = s2 = s3 = None
1363 try:
1364 s1 = g(400000) # ~ 400 KB
1365 s2 = g(4000000) # ~ 4 MB
1366 s3 = g(40000000) # ~ 40 MB
1367 except MemoryError:
1368 pass
1369 return (s1 is not None) + (s2 is not None) + (s3 is not None)
1370 return fn
1371
1372 def test_gc_set_max_heap_size(self):
1373 res = self.run('gc_set_max_heap_size')
1374 assert res == 2
1375
1376 def define_gc_heap_stats(cls):
1377 S = lltype.GcStruct('S', ('x', lltype.Signed))
1378 l1 = []
1379 l2 = []
1380 l3 = []
1381
1382 def f():
1383 typeid_S = -1
1384 for i in range(10):
1385 s = lltype.malloc(S)
1386 gcref = lltype.cast_opaque_ptr(llmemory.GCREF, s)
1387 typeid_S = rgc.get_rpy_type_index(gcref)
1388 l1.append(s)
1389 l2.append(s)
1390 l3.append(s)
1391 assert typeid_S > 0
1392 gc.collect()
1393 tb = rgc._heap_stats()
1394 assert tb[typeid_S].count == 10
1395 # find the lists
1396 lcount = -1
1397 for i in range(len(tb)):
1398 if tb[i].count >= 3 and tb[i].links[typeid_S] == 30:
1399 assert lcount == -1
1400 lcount = tb[i].count
1401 return lcount
1402 return f
1403
1404 def test_gc_heap_stats(self):
1405 res = self.run("gc_heap_stats")
1406 assert res >= 3
1407
1408 def definestr_string_builder(cls):
1409 def fn(_):
1410 s = StringBuilder()
1411 s.append("a")
1412 s.append("abc")
1413 s.append_slice("abc", 1, 2)
1414 s.append_multiple_char('d', 4)
1415 return s.build()
1416 return fn
1417
1418 def test_string_builder(self):
1419 res = self.run('string_builder')
1420 assert res == "aabcbdddd"
1421
1422 def definestr_string_builder_over_allocation(cls):
1423 def fn(_):
1424 s = StringBuilder(4)
1425 s.append("abcd")
1426 s.append("defg")
1427 s.append("rty")
1428 s.append_multiple_char('y', 1000)
1429 gc.collect()
1430 s.append_multiple_char('y', 1000)
1431 res = s.build()
1432 gc.collect()
1433 return res
1434 return fn
1435
1436 def test_string_builder_over_allocation(self):
1437 res = self.run('string_builder_over_allocation')
1438 assert res[1000] == 'y'
1439
1440 def definestr_string_builder_multiple_builds(cls):
1441 def fn(_):
1442 s = StringBuilder(4)
1443 got = []
1444 for i in range(50):
1445 s.append(chr(33+i))
1446 got.append(s.build())
1447 gc.collect()
1448 return ' '.join(got)
1449 return fn
1450
1451 def test_string_builder_multiple_builds(self):
1452 res = self.run('string_builder_multiple_builds')
1453 assert res == ' '.join([''.join(map(chr, range(33, 33+length)))
1454 for length in range(1, 51)])
1455
1456 def definestr_string_builder_multiple_builds_2(cls):
1457 def fn(_):
1458 got = []
1459 for j in range(3, 76, 5):
1460 s = StringBuilder()
1461 for i in range(j):
1462 s.append(chr(33+i))
1463 gc.collect()
1464 got.append(s.build())
1465 return ' '.join(got)
1466 return fn
1467
1468 def test_string_builder_multiple_builds_2(self):
1469 res = self.run('string_builder_multiple_builds_2')
1470 assert res == ' '.join([''.join(map(chr, range(33, 33+length)))
1471 for length in range(3, 76, 5)])
1472
1473 def define_nursery_hash_base(cls):
1474 from rpython.rlib.debug import debug_print
1475
1476 class A:
1477 pass
1478 def fn():
1479 objects = []
1480 hashes = []
1481 for i in range(200):
1482 debug_print("starting nursery collection", i)
1483 rgc.collect(0) # nursery-only collection, if possible
1484 debug_print("finishing nursery collection", i)
1485 obj = A()
1486 objects.append(obj)
1487 hashes.append(compute_identity_hash(obj))
1488 unique = {}
1489 debug_print("objects", len(objects))
1490 for i in range(len(objects)):
1491 debug_print(i)
1492 assert compute_identity_hash(objects[i]) == hashes[i]
1493 debug_print("storing in dict")
1494 unique[hashes[i]] = None
1495 debug_print("done")
1496 debug_print("finished")
1497 return len(unique)
1498 return fn
1499
1500 def test_nursery_hash_base(self):
1501 res = self.run('nursery_hash_base')
1502 assert res >= 195
1503
1504 def define_extra_item_after_alloc(cls):
1505 from rpython.rtyper.lltypesystem import rstr
1506 # all STR objects should be allocated with enough space for
1507 # one extra char. Check this with our GCs. Use strings of 8,
1508 # 16 and 24 chars because if the extra char is missing,
1509 # writing to it is likely to cause corruption in nearby
1510 # structures.
1511 sizes = [random.choice([8, 16, 24]) for i in range(100)]
1512 A = lltype.Struct('A', ('x', lltype.Signed))
1513 prebuilt = [(rstr.mallocstr(sz),
1514 lltype.malloc(A, flavor='raw', immortal=True))
1515 for sz in sizes]
1516 k = 0
1517 for i, (s, a) in enumerate(prebuilt):
1518 a.x = i
1519 for i in range(len(s.chars)):
1520 k += 1
1521 if k == 256:
1522 k = 1
1523 s.chars[i] = chr(k)
1524
1525 def check(lst):
1526 hashes = []
1527 for i, (s, a) in enumerate(lst):
1528 assert a.x == i
1529 rgc.ll_write_final_null_char(s)
1530 for i, (s, a) in enumerate(lst):
1531 assert a.x == i # check it was not overwritten
1532 def fn():
1533 check(prebuilt)
1534 lst1 = []
1535 for i, sz in enumerate(sizes):
1536 s = rstr.mallocstr(sz)
1537 a = lltype.malloc(A, flavor='raw')
1538 a.x = i
1539 lst1.append((s, a))
1540 check(lst1)
1541 for _, a in lst1:
1542 lltype.free(a, flavor='raw')
1543 return 42
1544 return fn
1545
1546 def test_extra_item_after_alloc(self):
1547 res = self.run('extra_item_after_alloc')
1548 assert res == 42
1549
1550 def define_rerased(cls):
1551 from rpython.rlib.rerased import new_erasing_pair, try_cast_erased
1552 erase_obj, unerase_obj = new_erasing_pair("test obj")
1553 erase_str, unerase_str = new_erasing_pair("test str")
1554 class X:
1555 pass
1556 def f():
1557 x = X()
1558 for i in range(2):
1559 if i:
1560 erased = erase_str('abc')
1561 else:
1562 erased = erase_obj(x)
1563 obj = try_cast_erased(X, erased)
1564 if obj is not None:
1565 assert i == 0
1566 assert obj is x
1567 else:
1568 assert unerase_str(erased) == 'abc'
1569 return 0
1570 return f
1571
1572 def test_rerased(self):
1573 res = self.run('rerased')
1574 assert res == 0
1575
1576
1577 class TestGenerationalGC(TestSemiSpaceGC):
1578 gcpolicy = "generation"
1579 should_be_moving = True
1580
1581
1582 class TestHybridGC(TestGenerationalGC):
1583 gcpolicy = "hybrid"
1584 should_be_moving = True
1585
1586 def test_gc_set_max_heap_size(self):
1587 py.test.skip("not implemented")
1588
1589
1590 class TestHybridGCRemoveTypePtr(TestHybridGC):
1591 removetypeptr = True
1592
1593
1594 class TestMiniMarkGC(TestSemiSpaceGC):
1595 gcpolicy = "minimark"
1596 should_be_moving = True
1597 GC_CAN_SHRINK_ARRAY = True
1598
1599 def test_gc_heap_stats(self):
1600 py.test.skip("not implemented")
1601
1602 def define_nongc_attached_to_gc(cls):
1603 from rpython.rtyper.lltypesystem import rffi
1604 ARRAY = rffi.CArray(rffi.INT)
1605 class A:
1606 def __init__(self, n):
1607 self.buf = lltype.malloc(ARRAY, n, flavor='raw',
1608 add_memory_pressure=True)
1609 def __del__(self):
1610 lltype.free(self.buf, flavor='raw')
1611 A(6)
1612 def f():
1613 # allocate a total of ~77GB, but if the automatic gc'ing works,
1614 # it should never need more than a few MBs at once
1615 am1 = am2 = am3 = None
1616 res = 0
1617 for i in range(1, 100001):
1618 if am3 is not None:
1619 res += rffi.cast(lltype.Signed, am3.buf[0])
1620 am3 = am2
1621 am2 = am1
1622 am1 = A(i * 4)
1623 am1.buf[0] = rffi.cast(rffi.INT, i - 50000)
1624 return res
1625 return f
1626
1627 def test_nongc_attached_to_gc(self):
1628 res = self.run("nongc_attached_to_gc")
1629 assert res == -99997
1630
1631 def define_nongc_opaque_attached_to_gc(cls):
1632 from rpython.rlib import rgc, ropenssl
1633
1634 class A:
1635 def __init__(self):
1636 digest = ropenssl.EVP_get_digestbyname('sha1')
1637 self.ctx = ropenssl.EVP_MD_CTX_new()
1638 ropenssl.EVP_DigestInit(self.ctx, digest)
1639 rgc.add_memory_pressure(ropenssl.HASH_MALLOC_SIZE + 64, self)
1640
1641 def __del__(self):
1642 ropenssl.EVP_MD_CTX_free(self.ctx)
1643 #A() --- can't call it here?? get glibc crashes on tannit64
1644 def f():
1645 am1 = am2 = am3 = None
1646 for i in range(100000):
1647 am3 = am2
1648 am2 = am1
1649 am1 = A()
1650 am1 = am2 = am3 = None
1651 # what can we use for the res?
1652 for i in range(10):
1653 gc.collect()
1654 return rgc.get_stats(rgc.TOTAL_MEMORY_PRESSURE)
1655 return f
1656
1657 def test_nongc_opaque_attached_to_gc(self):
1658 res = self.run("nongc_opaque_attached_to_gc")
1659 # the res is 0 for non-memory-pressure-accounting GC
1660 assert res == 0
1661
1662 def define_limited_memory(self):
1663 class A(object):
1664 def __init__(self, next):
1665 self.next = next
1666 def g(i):
1667 a = None
1668 while i != 0:
1669 a = A(a)
1670 i -= 1
1671 return 0
1672 def f(i):
1673 try:
1674 return g(i)
1675 except MemoryError:
1676 g(20) # allocate some more stuff, but exit
1677 return 42
1678 return f
1679
1680 def test_limited_memory(self):
1681 import random
1682 #
1683 def myrunner(args):
1684 env = os.environ.copy()
1685 env['PYPY_GC_MAX'] = '%dKB' % gcmax
1686 return subprocess.check_output(args, env=env)
1687 #
1688 for i in range(10):
1689 gcmax = random.randrange(50000, 100000)
1690 print gcmax
1691 res = self.run("limited_memory", -1, runner=myrunner)
1692 assert res == 42
1693
1694
1695 class TestIncrementalMiniMarkGC(TestMiniMarkGC):
1696 gcpolicy = "incminimark"
1697
1698 def define_total_memory_pressure(cls):
1699 class A(object):
1700 def __init__(self):
1701 rgc.add_memory_pressure(10, self)
1702
1703 def __del__(self):
1704 pass
1705
1706 class B(A):
1707 def __init__(self):
1708 rgc.add_memory_pressure(10, self)
1709
1710 class C(A):
1711 pass
1712
1713 class Glob(object):
1714 pass
1715 glob = Glob()
1716
1717 def f():
1718 glob.l = [None] * 3
1719 for i in range(10000):
1720 glob.l[i % 3] = A()
1721 glob.l[(i + 1) % 3] = B()
1722 glob.l[(i + 2) % 3] = C()
1723 return rgc.get_stats(rgc.TOTAL_MEMORY_PRESSURE)
1724 return f
1725
1726 def test_total_memory_pressure(self):
1727 res = self.run("total_memory_pressure")
1728 assert res == 30 # total reachable is 3
1729
1730 def define_random_pin(self):
1731 class A:
1732 foo = None
1733 bar = '..'
1734 def f():
1735 alist = [A()]
1736 slist = ['..']
1737 i = 0
1738 j = 0
1739 k = 0
1740 while i < 400000:
1741 k = (k * 1291 + i) % 4603
1742 a = A()
1743 if k < 1000:
1744 alist.append(a)
1745 elif k < 2000:
1746 j = (i * k)
1747 alist[j % len(alist)].foo = alist[(j+i) % len(alist)]
1748 elif k < 3000:
1749 alist[i % len(alist)].bar = slist[(j+i) % len(slist)]
1750 elif k < 4000:
1751 slist.append(chr(i & 255) + chr(k & 255))
1752 elif k < 4100 and len(alist) > 1:
1753 drop = alist.pop()
1754 alist[i % len(alist)] = drop
1755 elif k < 4200 and len(slist) > 1:
1756 drop = slist.pop()
1757 slist[i % len(slist)] = drop
1758 elif k < 4300:
1759 rgc.pin(slist[i % len(slist)]) # <------ pin!
1760 keepalive_until_here(a)
1761 i += 1
1762 n = 0
1763 m = 0
1764 for i in range(len(alist)):
1765 a = alist[i]
1766 if a.foo is None:
1767 n -= 1
1768 else:
1769 n += ord(a.foo.bar[0])
1770 m += ord(a.foo.bar[1])
1771 return m - n
1772 assert f() == 28495
1773 return f
1774
1775 def test_random_pin(self):
1776 res = self.run("random_pin")
1777 assert res == 28495
1778
1779 define_limited_memory_linux = TestMiniMarkGC.define_limited_memory.im_func
1780
1781 def test_limited_memory_linux(self):
1782 if not sys.platform.startswith('linux'):
1783 py.test.skip("linux only")
1784 #
1785 import random
1786 #
1787 def myrunner(args):
1788 args1 = ['/bin/bash', '-c', 'ulimit -v %d && %s' %
1789 (ulimitv, ' '.join(args),)]
1790 popen = subprocess.Popen(args1, stderr=subprocess.PIPE)
1791 _, child_stderr = popen.communicate()
1792 assert popen.wait() in (-6, 134) # aborted
1793 # note: it seems that on some systems we get 134 and on
1794 # others we get -6. Bash is supposed to translate the
1795 # SIGABRT (signal 6) from the subprocess into the exit
1796 # code 128+6, but I guess it may not always do so.
1797 assert 'out of memory:' in child_stderr
1798 return '42'
1799 #
1800 for i in range(10):
1801 ulimitv = random.randrange(50000, 100000)
1802 print ulimitv
1803 res = self.run("limited_memory_linux", -1, runner=myrunner)
1804 assert res == 42
1805
1806 def define_ignore_finalizer(cls):
1807 class X(object):
1808 pass
1809 class FQ(rgc.FinalizerQueue):
1810 Class = X
1811 def finalizer_trigger(self):
1812 pass
1813 queue = FQ()
1814 def g():
1815 x1 = X()
1816 x2 = X()
1817 queue.register_finalizer(x1)
1818 queue.register_finalizer(x2)
1819 rgc.may_ignore_finalizer(x1)
1820 g._dont_inline_ = True
1821 def f():
1822 g()
1823 rgc.collect()
1824 seen = 0
1825 while True:
1826 obj = queue.next_dead()
1827 if obj is None:
1828 break
1829 seen += 1
1830 return seen
1831 assert f() == 2 # untranslated: may_ignore_finalizer() is ignored
1832 return f
1833
1834 def test_ignore_finalizer(self):
1835 res = self.run("ignore_finalizer")
1836 assert res == 1 # translated: x1 is removed from the list
1837
1838 def define_enable_disable(self):
1839 class Counter(object):
1840 val = 0
1841 counter = Counter()
1842 class X(object):
1843 def __del__(self):
1844 counter.val += 1
1845 def f(should_disable):
1846 x1 = X()
1847 rgc.collect() # make x1 old
1848 assert not rgc.can_move(x1)
1849 x1 = None
1850 #
1851 if should_disable:
1852 gc.disable()
1853 assert not gc.isenabled()
1854 # try to trigger a major collection
1855 N = 500 # this should be enough, increase if not
1856 lst = []
1857 for i in range(N):
1858 lst.append(chr(i%256) * (1024*1024))
1859 #print i, counter.val
1860 #
1861 gc.enable()
1862 assert gc.isenabled()
1863 return counter.val
1864 return f
1865
1866 def test_enable_disable(self):
1867 # first, run with normal gc. If the assert fails it means that in the
1868 # loop we don't allocate enough mem to trigger a major collection. Try
1869 # to increase N
1870 deleted = self.run("enable_disable", 0)
1871 assert deleted == 1, 'This should not fail, try to increment N'
1872 #
1873 # now, run with gc.disable: this should NOT free x1
1874 deleted = self.run("enable_disable", 1)
1875 assert deleted == 0
1876
1877 def define_collect_step(self):
1878 class Counter(object):
1879 val = 0
1880 counter = Counter()
1881 class X(object):
1882 def __del__(self):
1883 counter.val += 1
1884 def f():
1885 x1 = X()
1886 rgc.collect() # make x1 old
1887 assert not rgc.can_move(x1)
1888 x1 = None
1889 #
1890 gc.disable()
1891 n = 0
1892 states = []
1893 while True:
1894 n += 1
1895 val = rgc.collect_step()
1896 states.append((rgc.old_state(val), rgc.new_state(val)))
1897 if rgc.is_done(val):
1898 break
1899 if n == 100:
1900 print 'Endless loop!'
1901 assert False, 'this looks like an endless loop'
1902
1903 if n < 4: # we expect at least 4 steps
1904 print 'Too few steps! n =', n
1905 assert False
1906
1907 # check that the state transitions are reasonable
1908 first_state, _ = states[0]
1909 for i, (old_state, new_state) in enumerate(states):
1910 is_last = (i == len(states) - 1)
1911 is_valid = False
1912 if is_last:
1913 assert old_state != new_state == first_state
1914 else:
1915 assert new_state == old_state or new_state == old_state+1
1916
1917 return counter.val
1918 return f
1919
1920 def test_collect_step(self):
1921 deleted = self.run("collect_step")
1922 assert deleted == 1
1923
1924 def define_total_gc_time(cls):
1925 def f():
1926 l = []
1927 for i in range(1000000):
1928 l.append(str(i))
1929 l = []
1930 for i in range(10):
1931 rgc.collect()
1932 return rgc.get_stats(rgc.TOTAL_GC_TIME)
1933 return f
1934
1935 def test_total_gc_time(self):
1936 res = self.run("total_gc_time")
1937 assert res > 0 # should take a few microseconds
1938
1939 def define_increase_root_stack_depth(cls):
1940 class X:
1941 pass
1942 def g(n):
1943 if n <= 0:
1944 return None
1945 x = X()
1946 x.n = n
1947 x.next = g(n - 1)
1948 return x
1949 def f(depth):
1950 from rpython.rlib.rstack import _stack_set_length_fraction
1951 _stack_set_length_fraction(50.0)
1952 # ^^^ the default is enough for at least 10'000 (but less than
1953 # 100'000) recursions of the simple function g(). We multiply
1954 # it by 50.0 to make sure that 200'000 works. The default
1955 # shadowstack depth is 163'840 entries, so 200'000 overflows
1956 # that default shadowstack depth, and gives a segfault unless
1957 # the following line works too.
1958 from rpython.rlib.rgc import increase_root_stack_depth
1959 increase_root_stack_depth(depth + 100)
1960 #
1961 g(depth)
1962 return 42
1963 return f
1964
1965 def test_increase_root_stack_depth(self):
1966 if not sys.platform.startswith('linux'):
1967 py.test.skip("linux only")
1968 #
1969 def myrunner(args):
1970 args1 = ['/bin/bash', '-c', 'ulimit -s unlimited && %s' %
1971 (' '.join(args),)]
1972 return subprocess.check_output(args1)
1973 res = self.run("increase_root_stack_depth", 200000, runner=myrunner)
1974 assert res == 42
1975
1976
1977 # ____________________________________________________________________
1978
1979 class TaggedPointersTest(object):
1980 taggedpointers = True
1981
1982 def define_tagged(cls):
1983 class Unrelated(object):
1984 pass
1985
1986 u = Unrelated()
1987 u.x = UnboxedObject(47)
1988 def fn(n):
1989 rgc.collect() # check that a prebuilt tagged pointer doesn't explode
1990 if n > 0:
1991 x = BoxedObject(n)
1992 else:
1993 x = UnboxedObject(n)
1994 u.x = x # invoke write barrier
1995 rgc.collect()
1996 return x.meth(100)
1997 def func():
1998 return fn(1000) + fn(-1000)
1999 return func
2000
2001 def test_tagged(self):
2002 expected = self.run_orig("tagged")
2003 res = self.run("tagged")
2004 assert res == expected
2005
2006 def define_erased(cls):
2007 from rpython.rlib import rerased
2008 erase, unerase = rerased.new_erasing_pair("test")
2009 class Unrelated(object):
2010 pass
2011
2012 u = Unrelated()
2013 u.tagged = True
2014 u.x = rerased.erase_int(41)
2015 class A(object):
2016 pass
2017 def fn():
2018 n = 1
2019 while n >= 0:
2020 if u.tagged:
2021 n = rerased.unerase_int(u.x)
2022 a = A()
2023 a.n = n - 1
2024 u.x = erase(a)
2025 u.tagged = False
2026 else:
2027 n = unerase(u.x).n
2028 u.x = rerased.erase_int(n - 1)
2029 u.tagged = True
2030 def func():
2031 rgc.collect() # check that a prebuilt erased integer doesn't explode
2032 u.x = rerased.erase_int(1000)
2033 u.tagged = True
2034 fn()
2035 return 1
2036 return func
2037
2038 def test_erased(self):
2039 expected = self.run_orig("erased")
2040 res = self.run("erased")
2041 assert res == expected
2042
2043 from rpython.rlib.objectmodel import UnboxedValue
2044
2045 class TaggedBase(object):
2046 __slots__ = ()
2047 def meth(self, x):
2048 raise NotImplementedError
2049
2050 class BoxedObject(TaggedBase):
2051 attrvalue = 66
2052 def __init__(self, normalint):
2053 self.normalint = normalint
2054 def meth(self, x):
2055 return self.normalint + x + 2
2056
2057 class UnboxedObject(TaggedBase, UnboxedValue):
2058 __slots__ = 'smallint'
2059 def meth(self, x):
2060 return self.smallint + x + 3
2061
2062
2063 class TestHybridTaggedPointers(TaggedPointersTest, TestHybridGC):
2064 pass
2065
2066
2067 class TestMiniMarkGCMostCompact(TaggedPointersTest, TestMiniMarkGC):
2068 removetypeptr = True
2069
2070 class TestIncrementalMiniMarkGCMostCompact(TaggedPointersTest, TestIncrementalMiniMarkGC):
2071 removetypeptr = True