Debian Codegraph @

rpython/memory/gc/test/test_direct.py

raw symbols SCIP
1 """ The tests below don't use translation at all. They run the GCs by
2 instantiating them and asking them to allocate memory by calling their
3 methods directly. The tests need to maintain by hand what the GC should
4 see as the list of roots (stack and prebuilt objects).
5 """
6
7 # XXX VERY INCOMPLETE, low coverage
8
9 import py
10
11 from hypothesis import strategies, given, assume, example, settings, HealthCheck
12
13 from rpython.rtyper.lltypesystem import lltype, llmemory
14 from rpython.memory.gctypelayout import TypeLayoutBuilder, FIN_HANDLER_ARRAY
15 from rpython.memory.gctypelayout import WEAKREF, WEAKREFPTR
16 from rpython.rlib.rarithmetic import LONG_BIT, is_valid_int
17 from rpython.memory.gc import minimark, incminimark
18 from rpython.memory.gctypelayout import zero_gc_pointers_inside, zero_gc_pointers
19 from rpython.rlib.debug import debug_print
20 from rpython.rlib.test.test_debug import debuglog
21 from rpython.rlib import rgc
22 import pdb
23 WORD = LONG_BIT // 8
24
25 ADDR_ARRAY = lltype.Array(llmemory.Address)
26 S = lltype.GcForwardReference()
27 S.become(lltype.GcStruct('S',
28 ('x', lltype.Signed),
29 ('prev', lltype.Ptr(S)),
30 ('next', lltype.Ptr(S))))
31 RAW = lltype.Struct('RAW', ('p', lltype.Ptr(S)), ('q', lltype.Ptr(S)))
32 VAR = lltype.GcArray(lltype.Ptr(S))
33 VARNODE = lltype.GcStruct('VARNODE', ('a', lltype.Ptr(VAR)))
34
35 STR = lltype.GcStruct('rpy_string',
36 ('hash', lltype.Signed),
37 ('chars', lltype.Array(lltype.Char, hints={'immutable': True, 'extra_item_after_alloc': 1})))
38
39 class DirectRootWalker(object):
40
41 def __init__(self, tester):
42 self.tester = tester
43
44 def walk_roots(self, collect_stack_root,
45 collect_static_in_prebuilt_nongc,
46 collect_static_in_prebuilt_gc,
47 is_minor=False):
48 gc = self.tester.gc
49 layoutbuilder = self.tester.layoutbuilder
50 if collect_static_in_prebuilt_gc:
51 for addrofaddr in layoutbuilder.addresses_of_static_ptrs:
52 if addrofaddr.address[0]:
53 collect_static_in_prebuilt_gc(gc, addrofaddr)
54 if collect_static_in_prebuilt_nongc:
55 for addrofaddr in layoutbuilder.addresses_of_static_ptrs_in_nongc:
56 if addrofaddr.address[0]:
57 collect_static_in_prebuilt_nongc(gc, addrofaddr)
58 if collect_stack_root:
59 stackroots = self.tester.stackroots
60 a = lltype.malloc(ADDR_ARRAY, len(stackroots), flavor='raw')
61 for i in range(len(a)):
62 a[i] = llmemory.cast_ptr_to_adr(stackroots[i])
63 a_base = lltype.direct_arrayitems(a)
64 for i in range(len(a)):
65 ai = lltype.direct_ptradd(a_base, i)
66 collect_stack_root(gc, llmemory.cast_ptr_to_adr(ai))
67 for i in range(len(a)):
68 PTRTYPE = lltype.typeOf(stackroots[i])
69 stackroots[i] = llmemory.cast_adr_to_ptr(a[i], PTRTYPE)
70 lltype.free(a, flavor='raw')
71
72 def _walk_prebuilt_gc(self, callback):
73 pass
74
75 def finished_minor_collection(self):
76 pass
77
78
79 class BaseDirectGCTest(object):
80 GC_PARAMS = {}
81
82 def get_extra_gc_params(self):
83 return {}
84
85 def setup_method(self, meth):
86 from rpython.config.translationoption import get_combined_translation_config
87 config = get_combined_translation_config(translating=True).translation
88 self.stackroots = []
89 GC_PARAMS = self.GC_PARAMS.copy()
90 if hasattr(meth, 'GC_PARAMS'):
91 GC_PARAMS.update(meth.GC_PARAMS)
92 GC_PARAMS['translated_to_c'] = False
93 GC_PARAMS.update(self.get_extra_gc_params())
94 self.gc = self.GCClass(config, **GC_PARAMS)
95 self.gc.DEBUG = True
96 self.rootwalker = DirectRootWalker(self)
97 self.gc.set_root_walker(self.rootwalker)
98 self.layoutbuilder = TypeLayoutBuilder(self.GCClass)
99 self.get_type_id = self.layoutbuilder.get_type_id
100 gcdata = self.layoutbuilder.initialize_gc_query_function(self.gc)
101 ll_handlers = lltype.malloc(FIN_HANDLER_ARRAY, 0, immortal=True)
102 gcdata.finalizer_handlers = llmemory.cast_ptr_to_adr(ll_handlers)
103 self.gc.setup()
104
105 def consider_constant(self, p):
106 obj = p._obj
107 TYPE = lltype.typeOf(obj)
108 self.layoutbuilder.consider_constant(TYPE, obj, self.gc)
109
110 def write(self, p, fieldname, newvalue):
111 if self.gc.needs_write_barrier:
112 addr_struct = llmemory.cast_ptr_to_adr(p)
113 self.gc.write_barrier(addr_struct)
114 setattr(p, fieldname, newvalue)
115
116 def writearray(self, p, index, newvalue):
117 if self.gc.needs_write_barrier:
118 addr_struct = llmemory.cast_ptr_to_adr(p)
119 if hasattr(self.gc, 'write_barrier_from_array'):
120 self.gc.write_barrier_from_array(addr_struct, index)
121 else:
122 self.gc.write_barrier(addr_struct)
123 p[index] = newvalue
124
125 def malloc(self, TYPE, n=None):
126 addr = self.gc.malloc(self.get_type_id(TYPE), n)
127 obj_ptr = llmemory.cast_adr_to_ptr(addr, lltype.Ptr(TYPE))
128 if not self.gc.malloc_zero_filled:
129 zero_gc_pointers_inside(obj_ptr, TYPE)
130 return obj_ptr
131
132
133 class DirectGCTest(BaseDirectGCTest):
134
135 def test_simple(self):
136 p = self.malloc(S)
137 p.x = 5
138 self.stackroots.append(p)
139 self.gc.collect()
140 p = self.stackroots[0]
141 assert p.x == 5
142
143 def test_missing_stack_root(self):
144 p = self.malloc(S)
145 p.x = 5
146 self.gc.collect() # 'p' should go away
147 py.test.raises(RuntimeError, 'p.x')
148
149 def test_prebuilt_gc(self):
150 k = lltype.malloc(S, immortal=True)
151 k.x = 42
152 self.consider_constant(k)
153 self.write(k, 'next', self.malloc(S))
154 k.next.x = 43
155 self.write(k.next, 'next', self.malloc(S))
156 k.next.next.x = 44
157 self.gc.collect()
158 assert k.x == 42
159 assert k.next.x == 43
160 assert k.next.next.x == 44
161
162 def test_prebuilt_nongc(self):
163 raw = lltype.malloc(RAW, immortal=True)
164 self.consider_constant(raw)
165 raw.p = self.malloc(S)
166 raw.p.x = 43
167 raw.q = self.malloc(S)
168 raw.q.x = 44
169 self.gc.collect()
170 assert raw.p.x == 43
171 assert raw.q.x == 44
172
173 def test_many_objects(self):
174
175 def alloc2(i):
176 a1 = self.malloc(S)
177 a1.x = i
178 self.stackroots.append(a1)
179 a2 = self.malloc(S)
180 a1 = self.stackroots.pop()
181 a2.x = i + 1000
182 return a1, a2
183
184 def growloop(loop, a1, a2):
185 self.write(a1, 'prev', loop.prev)
186 self.write(a1.prev, 'next', a1)
187 self.write(a1, 'next', loop)
188 self.write(loop, 'prev', a1)
189 self.write(a2, 'prev', loop)
190 self.write(a2, 'next', loop.next)
191 self.write(a2.next, 'prev', a2)
192 self.write(loop, 'next', a2)
193
194 def newloop():
195 p = self.malloc(S)
196 p.next = p # initializing stores, no write barrier
197 p.prev = p
198 return p
199
200 # a loop attached to a stack root
201 self.stackroots.append(newloop())
202
203 # another loop attached to a prebuilt gc node
204 k = lltype.malloc(S, immortal=True)
205 k.next = k
206 k.prev = k
207 self.consider_constant(k)
208
209 # a third loop attached to a prebuilt nongc
210 raw = lltype.malloc(RAW, immortal=True)
211 self.consider_constant(raw)
212 raw.p = newloop()
213
214 # run!
215 for i in range(100):
216 a1, a2 = alloc2(i)
217 growloop(self.stackroots[0], a1, a2)
218 a1, a2 = alloc2(i)
219 growloop(k, a1, a2)
220 a1, a2 = alloc2(i)
221 growloop(raw.p, a1, a2)
222
223 def test_varsized_from_stack(self):
224 expected = {}
225 def verify():
226 for (index, index2), value in expected.items():
227 assert self.stackroots[index][index2].x == value
228 x = 0
229 for i in range(40):
230 assert 'DEAD' not in repr(self.stackroots)
231 a = self.malloc(VAR, i)
232 assert 'DEAD' not in repr(a)
233 self.stackroots.append(a)
234 print 'ADDED TO STACKROOTS:', llmemory.cast_adr_to_int(
235 llmemory.cast_ptr_to_adr(a))
236 assert 'DEAD' not in repr(self.stackroots)
237 for j in range(5):
238 assert 'DEAD' not in repr(self.stackroots)
239 p = self.malloc(S)
240 assert 'DEAD' not in repr(self.stackroots)
241 p.x = x
242 index = x % len(self.stackroots)
243 if index > 0:
244 index2 = (x / len(self.stackroots)) % index
245 a = self.stackroots[index]
246 assert len(a) == index
247 self.writearray(a, index2, p)
248 expected[index, index2] = x
249 x += 1291
250 verify()
251 self.gc.collect()
252 verify()
253 self.gc.collect()
254 verify()
255
256 def test_varsized_from_prebuilt_gc(self):
257 expected = {}
258 def verify():
259 for (index, index2), value in expected.items():
260 assert prebuilt[index].a[index2].x == value
261 x = 0
262 prebuilt = [lltype.malloc(VARNODE, immortal=True, zero=True)
263 for i in range(40)]
264 for node in prebuilt:
265 self.consider_constant(node)
266 for i in range(len(prebuilt)):
267 self.write(prebuilt[i], 'a', self.malloc(VAR, i))
268 for j in range(20):
269 p = self.malloc(S)
270 p.x = x
271 index = x % (i+1)
272 if index > 0:
273 index2 = (x / (i+1)) % index
274 a = prebuilt[index].a
275 assert len(a) == index
276 self.writearray(a, index2, p)
277 expected[index, index2] = x
278 x += 1291
279 verify()
280 self.gc.collect()
281 verify()
282 self.gc.collect()
283 verify()
284
285 def test_id(self):
286 ids = {}
287 def allocate_bunch(count=50):
288 base = len(self.stackroots)
289 for i in range(count):
290 p = self.malloc(S)
291 self.stackroots.append(p)
292 for i in range(count):
293 j = base + (i*1291) % count
294 pid = self.gc.id(self.stackroots[j])
295 assert isinstance(pid, int)
296 ids[j] = pid
297 def verify():
298 for j, expected in ids.items():
299 assert self.gc.id(self.stackroots[j]) == expected
300 allocate_bunch(5)
301 verify()
302 allocate_bunch(75)
303 verify()
304 allocate_bunch(5)
305 verify()
306 self.gc.collect()
307 verify()
308 self.gc.collect()
309 verify()
310
311 def test_identityhash(self):
312 # a "does not crash" kind of test
313 p_const = lltype.malloc(S, immortal=True)
314 self.consider_constant(p_const)
315 # (1) p is in the nursery
316 self.gc.collect()
317 p = self.malloc(S)
318 hash = self.gc.identityhash(p)
319 print hash
320 assert is_valid_int(hash)
321 assert hash == self.gc.identityhash(p)
322 self.stackroots.append(p)
323 for i in range(6):
324 self.gc.collect()
325 assert hash == self.gc.identityhash(self.stackroots[-1])
326 self.stackroots.pop()
327 # (2) p is an older object
328 p = self.malloc(S)
329 self.stackroots.append(p)
330 self.gc.collect()
331 hash = self.gc.identityhash(self.stackroots[-1])
332 print hash
333 assert is_valid_int(hash)
334 for i in range(6):
335 self.gc.collect()
336 assert hash == self.gc.identityhash(self.stackroots[-1])
337 self.stackroots.pop()
338 # (3) p is a gen3 object (for hybrid)
339 p = self.malloc(S)
340 self.stackroots.append(p)
341 for i in range(6):
342 self.gc.collect()
343 hash = self.gc.identityhash(self.stackroots[-1])
344 print hash
345 assert is_valid_int(hash)
346 for i in range(2):
347 self.gc.collect()
348 assert hash == self.gc.identityhash(self.stackroots[-1])
349 self.stackroots.pop()
350 # (4) p is a prebuilt object
351 hash = self.gc.identityhash(p_const)
352 print hash
353 assert is_valid_int(hash)
354 assert hash == self.gc.identityhash(p_const)
355 # (5) p is actually moving (for the markcompact gc only?)
356 p0 = self.malloc(S)
357 self.stackroots.append(p0)
358 p = self.malloc(S)
359 self.stackroots.append(p)
360 hash = self.gc.identityhash(p)
361 self.stackroots.pop(-2)
362 self.gc.collect() # p0 goes away, p shifts left
363 assert hash == self.gc.identityhash(self.stackroots[-1])
364 self.gc.collect()
365 assert hash == self.gc.identityhash(self.stackroots[-1])
366 self.stackroots.pop()
367 # (6) ask for the hash of varsized objects, larger and larger
368 for i in range(10):
369 self.gc.collect()
370 p = self.malloc(VAR, i)
371 self.stackroots.append(p)
372 hash = self.gc.identityhash(p)
373 self.gc.collect()
374 assert hash == self.gc.identityhash(self.stackroots[-1])
375 self.stackroots.pop()
376 # (7) the same, but the objects are dying young
377 for i in range(10):
378 self.gc.collect()
379 p = self.malloc(VAR, i)
380 self.stackroots.append(p)
381 hash1 = self.gc.identityhash(p)
382 hash2 = self.gc.identityhash(p)
383 assert hash1 == hash2
384 self.stackroots.pop()
385
386 def test_memory_alignment(self):
387 A1 = lltype.GcArray(lltype.Char)
388 for i in range(50):
389 p1 = self.malloc(A1, i)
390 if i:
391 p1[i-1] = chr(i)
392 self.stackroots.append(p1)
393 self.gc.collect()
394 for i in range(1, 50):
395 p = self.stackroots[-50+i]
396 assert p[i-1] == chr(i)
397
398 class TestSemiSpaceGC(DirectGCTest):
399 from rpython.memory.gc.semispace import SemiSpaceGC as GCClass
400
401 def test_shrink_array(self):
402 S1 = lltype.GcStruct('S1', ('h', lltype.Char),
403 ('v', lltype.Array(lltype.Char)))
404 p1 = self.malloc(S1, 2)
405 p1.h = '?'
406 for i in range(2):
407 p1.v[i] = chr(50 + i)
408 addr = llmemory.cast_ptr_to_adr(p1)
409 ok = self.gc.shrink_array(addr, 1)
410 assert ok
411 assert p1.h == '?'
412 assert len(p1.v) == 1
413 for i in range(1):
414 assert p1.v[i] == chr(50 + i)
415
416
417 class TestGenerationGC(TestSemiSpaceGC):
418 from rpython.memory.gc.generation import GenerationGC as GCClass
419
420 def test_collect_gen(self):
421 gc = self.gc
422 old_semispace_collect = gc.semispace_collect
423 old_collect_nursery = gc.collect_nursery
424 calls = []
425 def semispace_collect():
426 calls.append('semispace_collect')
427 return old_semispace_collect()
428 def collect_nursery():
429 calls.append('collect_nursery')
430 return old_collect_nursery()
431 gc.collect_nursery = collect_nursery
432 gc.semispace_collect = semispace_collect
433
434 gc.collect()
435 assert calls == ['semispace_collect']
436 calls = []
437
438 gc.collect(0)
439 assert calls == ['collect_nursery']
440 calls = []
441
442 gc.collect(1)
443 assert calls == ['semispace_collect']
444 calls = []
445
446 gc.collect(9)
447 assert calls == ['semispace_collect']
448 calls = []
449
450 def test_write_barrier_direct(self):
451 s0 = lltype.malloc(S, immortal=True)
452 self.consider_constant(s0)
453 s = self.malloc(S)
454 s.x = 1
455 s0.next = s
456 self.gc.write_barrier(llmemory.cast_ptr_to_adr(s0))
457
458 self.gc.collect(0)
459
460 assert s0.next.x == 1
461
462
463 class TestHybridGC(TestGenerationGC):
464 from rpython.memory.gc.hybrid import HybridGC as GCClass
465
466 GC_PARAMS = {'space_size': 48*WORD,
467 'min_nursery_size': 12*WORD,
468 'nursery_size': 12*WORD,
469 'large_object': 3*WORD,
470 'large_object_gcptrs': 3*WORD,
471 'generation3_collect_threshold': 5,
472 }
473
474 def test_collect_gen(self):
475 gc = self.gc
476 old_semispace_collect = gc.semispace_collect
477 old_collect_nursery = gc.collect_nursery
478 calls = []
479 def semispace_collect():
480 gen3 = gc.is_collecting_gen3()
481 calls.append(('semispace_collect', gen3))
482 return old_semispace_collect()
483 def collect_nursery():
484 calls.append('collect_nursery')
485 return old_collect_nursery()
486 gc.collect_nursery = collect_nursery
487 gc.semispace_collect = semispace_collect
488
489 gc.collect()
490 assert calls == [('semispace_collect', True)]
491 calls = []
492
493 gc.collect(0)
494 assert calls == ['collect_nursery']
495 calls = []
496
497 gc.collect(1)
498 assert calls == [('semispace_collect', False)]
499 calls = []
500
501 gc.collect(2)
502 assert calls == [('semispace_collect', True)]
503 calls = []
504
505 gc.collect(9)
506 assert calls == [('semispace_collect', True)]
507 calls = []
508
509 def test_identityhash(self):
510 py.test.skip("does not support raw_mallocs(sizeof(S)+sizeof(hash))")
511
512
513 class TestMiniMarkGCSimple(DirectGCTest):
514 from rpython.memory.gc.minimark import MiniMarkGC as GCClass
515 from rpython.memory.gc.minimarktest import SimpleArenaCollection
516 # test the GC itself, providing a simple class for ArenaCollection
517 GC_PARAMS = {'ArenaCollectionClass': SimpleArenaCollection}
518
519 def test_card_marker(self):
520 for arraylength in (range(4, 17)
521 + [69] # 3 bytes
522 + [300]): # 10 bytes
523 print 'array length:', arraylength
524 nums = {}
525 a = self.malloc(VAR, arraylength)
526 self.stackroots.append(a)
527 for i in range(50):
528 p = self.malloc(S)
529 p.x = -i
530 a = self.stackroots[-1]
531 index = (i*i) % arraylength
532 self.writearray(a, index, p)
533 nums[index] = p.x
534 #
535 for index, expected_x in nums.items():
536 assert a[index].x == expected_x
537 self.stackroots.pop()
538 test_card_marker.GC_PARAMS = {"card_page_indices": 4}
539
540 def test_writebarrier_before_copy(self):
541 largeobj_size = self.gc.nonlarge_max + 1
542 self.gc.next_major_collection_threshold = 99999.0
543 p_src = self.malloc(VAR, largeobj_size)
544 p_dst = self.malloc(VAR, largeobj_size)
545 # make them old
546 self.stackroots.append(p_src)
547 self.stackroots.append(p_dst)
548 self.gc.collect()
549 p_dst = self.stackroots.pop()
550 p_src = self.stackroots.pop()
551 #
552 addr_src = llmemory.cast_ptr_to_adr(p_src)
553 addr_dst = llmemory.cast_ptr_to_adr(p_dst)
554 hdr_src = self.gc.header(addr_src)
555 hdr_dst = self.gc.header(addr_dst)
556 #
557 assert hdr_src.tid & minimark.GCFLAG_TRACK_YOUNG_PTRS
558 assert hdr_dst.tid & minimark.GCFLAG_TRACK_YOUNG_PTRS
559 #
560 res = self.gc.writebarrier_before_copy(addr_src, addr_dst, 0, 0, 10)
561 assert res
562 assert hdr_dst.tid & minimark.GCFLAG_TRACK_YOUNG_PTRS
563 #
564 hdr_src.tid &= ~minimark.GCFLAG_TRACK_YOUNG_PTRS # pretend we have young ptrs
565 res = self.gc.writebarrier_before_copy(addr_src, addr_dst, 0, 0, 10)
566 assert res # we optimized it
567 assert hdr_dst.tid & minimark.GCFLAG_TRACK_YOUNG_PTRS == 0 # and we copied the flag
568 #
569 self.gc.card_page_indices = 128 # force > 0
570 hdr_src.tid |= minimark.GCFLAG_TRACK_YOUNG_PTRS
571 hdr_dst.tid |= minimark.GCFLAG_TRACK_YOUNG_PTRS
572 hdr_src.tid |= minimark.GCFLAG_HAS_CARDS
573 hdr_src.tid |= minimark.GCFLAG_CARDS_SET
574 # hdr_dst.tid does not have minimark.GCFLAG_HAS_CARDS
575 res = self.gc.writebarrier_before_copy(addr_src, addr_dst, 0, 0, 10)
576 assert not res # there might be young ptrs, let ll_arraycopy to find them
577
578 def test_writebarrier_before_copy_preserving_cards(self):
579 from rpython.rtyper.lltypesystem import llarena
580 tid = self.get_type_id(VAR)
581 largeobj_size = self.gc.nonlarge_max + 1
582 self.gc.next_major_collection_threshold = 99999.0
583 addr_src = self.gc.external_malloc(tid, largeobj_size, alloc_young=True)
584 addr_dst = self.gc.external_malloc(tid, largeobj_size, alloc_young=True)
585 hdr_src = self.gc.header(addr_src)
586 hdr_dst = self.gc.header(addr_dst)
587 #
588 assert hdr_src.tid & minimark.GCFLAG_HAS_CARDS
589 assert hdr_dst.tid & minimark.GCFLAG_HAS_CARDS
590 #
591 self.gc.write_barrier_from_array(addr_src, 0)
592 index_in_third_page = int(2.5 * self.gc.card_page_indices)
593 assert index_in_third_page < largeobj_size
594 self.gc.write_barrier_from_array(addr_src, index_in_third_page)
595 #
596 assert hdr_src.tid & minimark.GCFLAG_CARDS_SET
597 addr_byte = self.gc.get_card(addr_src, 0)
598 assert ord(addr_byte.char[0]) == 0x01 | 0x04 # bits 0 and 2
599 #
600 res = self.gc.writebarrier_before_copy(addr_src, addr_dst,
601 0, 0, 2*self.gc.card_page_indices)
602 assert res
603 #
604 assert hdr_dst.tid & minimark.GCFLAG_CARDS_SET
605 addr_byte = self.gc.get_card(addr_dst, 0)
606 assert ord(addr_byte.char[0]) == 0x01 | 0x04 # bits 0 and 2
607
608 test_writebarrier_before_copy_preserving_cards.GC_PARAMS = {
609 "card_page_indices": 4}
610
611
612 class TestMiniMarkGCFull(DirectGCTest):
613 from rpython.memory.gc.minimark import MiniMarkGC as GCClass
614
615 class TestIncrementalMiniMarkGCSimple(TestMiniMarkGCSimple):
616 from rpython.memory.gc.incminimark import IncrementalMiniMarkGC as GCClass
617
618 def test_write_barrier_marking_simple(self):
619 for i in range(2):
620 curobj = self.malloc(S)
621 curobj.x = i
622 self.stackroots.append(curobj)
623
624
625 oldobj = self.stackroots[-1]
626 oldhdr = self.gc.header(llmemory.cast_ptr_to_adr(oldobj))
627
628 assert oldhdr.tid & incminimark.GCFLAG_VISITED == 0
629 self.gc.debug_gc_step_until(incminimark.STATE_MARKING)
630 oldobj = self.stackroots[-1]
631 # object shifted by minor collect
632 oldhdr = self.gc.header(llmemory.cast_ptr_to_adr(oldobj))
633 assert oldhdr.tid & incminimark.GCFLAG_VISITED == 0
634
635 self.gc._minor_collection()
636 self.gc.visit_all_objects_step(1)
637
638 assert oldhdr.tid & incminimark.GCFLAG_VISITED
639
640 #at this point the first object should have been processed
641 newobj = self.malloc(S)
642 self.write(oldobj,'next',newobj)
643
644 assert self.gc.header(self.gc.old_objects_pointing_to_young.tolist()[0]) == oldhdr
645
646 self.gc._minor_collection()
647 self.gc.debug_check_consistency()
648
649 def test_sweeping_simple(self):
650 assert self.gc.gc_state == incminimark.STATE_SCANNING
651
652 for i in range(2):
653 curobj = self.malloc(S)
654 curobj.x = i
655 self.stackroots.append(curobj)
656
657 self.gc.debug_gc_step_until(incminimark.STATE_SWEEPING)
658 oldobj = self.stackroots[-1]
659 oldhdr = self.gc.header(llmemory.cast_ptr_to_adr(oldobj))
660 assert oldhdr.tid & incminimark.GCFLAG_VISITED
661
662 newobj1 = self.malloc(S)
663 newobj2 = self.malloc(S)
664 newobj1.x = 1337
665 newobj2.x = 1338
666 self.write(oldobj,'next',newobj1)
667 self.gc.debug_gc_step_until(incminimark.STATE_SCANNING)
668 #should not be cleared even though it was allocated while sweeping
669 newobj1 = oldobj.next
670 assert newobj1.x == 1337
671
672 def test_obj_on_escapes_on_stack(self):
673 obj0 = self.malloc(S)
674
675 self.stackroots.append(obj0)
676 obj0.next = self.malloc(S)
677 self.gc.debug_gc_step_until(incminimark.STATE_MARKING)
678 obj0 = self.stackroots[-1]
679 obj1 = obj0.next
680 obj1.x = 13
681 obj0.next = lltype.nullptr(S)
682 self.stackroots.append(obj1)
683 self.gc.debug_gc_step_until(incminimark.STATE_SCANNING)
684 assert self.stackroots[1].x == 13
685
686 def test_move_out_of_nursery(self):
687 obj0 = self.malloc(S)
688 obj0.x = 123
689 adr1 = self.gc.move_out_of_nursery(llmemory.cast_ptr_to_adr(obj0))
690 obj1 = llmemory.cast_adr_to_ptr(adr1, lltype.Ptr(S))
691 assert obj1.x == 123
692 #
693 import pytest
694 obj2 = self.malloc(S)
695 obj2.x = 456
696 adr3 = self.gc._find_shadow(llmemory.cast_ptr_to_adr(obj2))
697 obj3 = llmemory.cast_adr_to_ptr(adr3, lltype.Ptr(S))
698 with pytest.raises(lltype.UninitializedMemoryAccess):
699 obj3.x # the shadow is not populated yet
700 adr4 = self.gc.move_out_of_nursery(llmemory.cast_ptr_to_adr(obj2))
701 assert adr4 == adr3
702 assert obj3.x == 456 # it is populated now
703
704
705 class TestIncrementalMiniMarkGCFull(DirectGCTest):
706 from rpython.memory.gc.incminimark import IncrementalMiniMarkGC as GCClass
707
708 def flags(self, obj):
709 return self.gc.header(llmemory.cast_ptr_to_adr(obj)).tid.rest
710
711 def test_malloc_fixedsize_no_cleanup(self):
712 p = self.malloc(S)
713 import pytest
714 #ensure the memory is uninitialized
715 with pytest.raises(lltype.UninitializedMemoryAccess):
716 x1 = p.x
717 #ensure all the ptr fields are zeroed
718 assert p.prev == lltype.nullptr(S)
719 assert p.next == lltype.nullptr(S)
720
721 def test_malloc_varsize_no_cleanup(self):
722 x = lltype.Signed
723 VAR1 = lltype.GcArray(x)
724 p = self.malloc(VAR1,5)
725 import pytest
726 with pytest.raises(lltype.UninitializedMemoryAccess):
727 assert isinstance(p[0], lltype._uninitialized)
728 x1 = p[0]
729
730 def test_malloc_varsize_no_cleanup2(self):
731 #as VAR is GcArray so the ptr will don't need to be zeroed
732 p = self.malloc(VAR, 100)
733 for i in range(100):
734 assert p[i] == lltype.nullptr(S)
735
736 def test_malloc_varsize_no_cleanup3(self):
737 VAR1 = lltype.Array(lltype.Ptr(S))
738 p1 = lltype.malloc(VAR1, 10, flavor='raw', track_allocation=False)
739 import pytest
740 with pytest.raises(lltype.UninitializedMemoryAccess):
741 for i in range(10):
742 assert p1[i] == lltype.nullptr(S)
743 p1[i]._free()
744 p1._free()
745
746 def test_malloc_struct_of_ptr_struct(self):
747 S3 = lltype.GcForwardReference()
748 S3.become(lltype.GcStruct('S3',
749 ('gcptr_struct', S),
750 ('prev', lltype.Ptr(S)),
751 ('next', lltype.Ptr(S))))
752 s3 = self.malloc(S3)
753 assert s3.gcptr_struct.prev == lltype.nullptr(S)
754 assert s3.gcptr_struct.next == lltype.nullptr(S)
755
756 def test_malloc_array_of_ptr_struct(self):
757 ARR_OF_PTR_STRUCT = lltype.GcArray(lltype.Ptr(S))
758 arr_of_ptr_struct = self.malloc(ARR_OF_PTR_STRUCT,5)
759 for i in range(5):
760 assert arr_of_ptr_struct[i] == lltype.nullptr(S)
761 assert arr_of_ptr_struct[i] == lltype.nullptr(S)
762 arr_of_ptr_struct[i] = self.malloc(S)
763 assert arr_of_ptr_struct[i].prev == lltype.nullptr(S)
764 assert arr_of_ptr_struct[i].next == lltype.nullptr(S)
765
766 #fail for now
767 def xxx_test_malloc_array_of_ptr_arr(self):
768 ARR_OF_PTR_ARR = lltype.GcArray(lltype.Ptr(lltype.GcArray(lltype.Ptr(S))))
769 arr_of_ptr_arr = self.malloc(ARR_OF_PTR_ARR, 10)
770 self.stackroots.append(arr_of_ptr_arr)
771 for i in range(10):
772 assert arr_of_ptr_arr[i] == lltype.nullptr(lltype.GcArray(lltype.Ptr(S)))
773 for i in range(10):
774 self.writearray(arr_of_ptr_arr, i,
775 self.malloc(lltype.GcArray(lltype.Ptr(S)), i))
776 #self.stackroots.append(arr_of_ptr_arr[i])
777 #debug_print(arr_of_ptr_arr[i])
778 for elem in arr_of_ptr_arr[i]:
779 #self.stackroots.append(elem)
780 assert elem == lltype.nullptr(S)
781 elem = self.malloc(S)
782 assert elem.prev == lltype.nullptr(S)
783 assert elem.next == lltype.nullptr(S)
784
785 def test_collect_0(self, debuglog):
786 self.gc.collect(1) # start a major
787 debuglog.reset()
788 self.gc.collect(-1) # do ONLY a minor
789 assert debuglog.summary() == {'gc-minor': 1}
790
791 def test_enable_disable(self, debuglog):
792 def large_malloc():
793 # malloc an object which is large enough to trigger a major collection
794 threshold = self.gc.next_major_collection_threshold
795 self.malloc(VAR, int(threshold/4))
796 summary = debuglog.summary()
797 debuglog.reset()
798 return summary
799 #
800 summary = large_malloc()
801 assert sorted(summary.keys()) == ['gc-collect-step', 'gc-minor']
802 #
803 self.gc.disable()
804 summary = large_malloc()
805 assert sorted(summary.keys()) == ['gc-minor']
806 #
807 self.gc.enable()
808 summary = large_malloc()
809 assert sorted(summary.keys()) == ['gc-collect-step', 'gc-minor']
810
811 def test_call_collect_when_disabled(self, debuglog):
812 # malloc an object and put it the old generation
813 s = self.malloc(S)
814 s.x = 42
815 self.stackroots.append(s)
816 self.gc.collect()
817 s = self.stackroots.pop()
818 #
819 self.gc.disable()
820 self.gc.collect(1) # start a major collect
821 assert sorted(debuglog.summary()) == ['gc-collect-step', 'gc-minor']
822 assert s.x == 42 # s is not freed yet
823 #
824 debuglog.reset()
825 self.gc.collect(1) # run one more step
826 assert sorted(debuglog.summary()) == ['gc-collect-step', 'gc-minor']
827 assert s.x == 42 # s is not freed yet
828 #
829 debuglog.reset()
830 self.gc.collect() # finish the major collection
831 summary = debuglog.summary()
832 assert sorted(debuglog.summary()) == ['gc-collect-step', 'gc-minor']
833 # s is freed
834 py.test.raises(RuntimeError, 's.x')
835
836 def test_collect_step(self, debuglog):
837 n = 0
838 states = []
839 while True:
840 debuglog.reset()
841 val = self.gc.collect_step()
842 states.append((rgc.old_state(val), rgc.new_state(val)))
843 summary = debuglog.summary()
844 assert summary == {'gc-minor': 1, 'gc-collect-step': 1}
845 if rgc.is_done(val):
846 break
847 n += 1
848 if n == 100:
849 assert False, 'this looks like an endless loop'
850 #
851 assert states == [
852 (incminimark.STATE_SCANNING, incminimark.STATE_MARKING),
853 (incminimark.STATE_MARKING, incminimark.STATE_SWEEPING),
854 (incminimark.STATE_SWEEPING, incminimark.STATE_FINALIZING),
855 (incminimark.STATE_FINALIZING, incminimark.STATE_SCANNING)
856 ]
857
858 def test_gc_debug_crash_with_prebuilt_objects(self):
859 from rpython.rlib import rgc
860 flags = self.flags
861
862 prebuilt = lltype.malloc(S, immortal=True)
863 prebuilt.x = 42
864 self.consider_constant(prebuilt)
865
866 self.gc.DEBUG = 2
867
868 old2 = self.malloc(S)
869 old2.x = 45
870 self.stackroots.append(old2)
871 old = self.malloc(S)
872 old.x = 43
873 self.write(old, 'next', prebuilt)
874 self.stackroots.append(old)
875 val = self.gc.collect_step()
876 assert rgc.old_state(val) == incminimark.STATE_SCANNING
877 assert rgc.new_state(val) == incminimark.STATE_MARKING
878 old2 = self.stackroots[0] # reload
879 old = self.stackroots[1]
880
881 # now a major next collection starts
882 # run things with TEST_VISIT_SINGLE_STEP = True so we can control
883 # the timing correctly
884 self.gc.TEST_VISIT_SINGLE_STEP = True
885 # run two marking steps, the first one marks obj, the second one
886 # prebuilt (which does nothing), but obj2 is left so we aren't done
887 # with marking
888 val = self.gc.collect_step()
889 val = self.gc.collect_step()
890 assert rgc.old_state(val) == incminimark.STATE_MARKING
891 assert rgc.new_state(val) == incminimark.STATE_MARKING
892 assert flags(old) & incminimark.GCFLAG_VISITED
893 assert (flags(old2) & incminimark.GCFLAG_VISITED) == 0
894 # prebuilt counts as grey but for prebuilt reasons
895 assert (flags(prebuilt) & incminimark.GCFLAG_VISITED) == 0
896 assert flags(prebuilt) & incminimark.GCFLAG_NO_HEAP_PTRS
897 # its write barrier is active
898 assert flags(prebuilt) & incminimark.GCFLAG_TRACK_YOUNG_PTRS
899
900 # now lets write a newly allocated object into prebuilt
901 new = self.malloc(S)
902 new.x = -10
903 # write barrier of prebuilt triggers
904 self.write(prebuilt, 'next', new)
905 # prebuilt got added both to old_objects_pointing_to_young and
906 # prebuilt_root_objects, so those flags get cleared
907 assert (flags(prebuilt) & incminimark.GCFLAG_NO_HEAP_PTRS) == 0
908 assert (flags(prebuilt) & incminimark.GCFLAG_TRACK_YOUNG_PTRS) == 0
909 # thus the prebuilt object now counts as white!
910 assert (flags(prebuilt) & incminimark.GCFLAG_VISITED) == 0
911
912 # this triggers the assertion black -> white pointer
913 # for the reference obj -> prebuilt
914 self.gc.collect_step()
915
916 def test_incrementality_bug_arraycopy(self, size1=8, size2=8):
917 from rpython.rlib import rgc
918 flags = self.flags
919 self.gc.DEBUG = 0
920
921 source = self.malloc(VAR, size1)
922 self.stackroots.append(source)
923 target = self.malloc(VAR, size2)
924 self.stackroots.append(target)
925 node = self.malloc(S)
926 node.x = 5
927 self.writearray(source, 0, node)
928 val = self.gc.collect_step()
929 assert rgc.old_state(val) == incminimark.STATE_SCANNING
930 assert rgc.new_state(val) == incminimark.STATE_MARKING
931 source = self.stackroots[0] # reload
932 target = self.stackroots[1]
933 assert (flags(source) & incminimark.GCFLAG_VISITED) == 0
934 assert flags(source) & incminimark.GCFLAG_TRACK_YOUNG_PTRS
935 assert (flags(target) & incminimark.GCFLAG_VISITED) == 0
936 assert flags(target) & incminimark.GCFLAG_TRACK_YOUNG_PTRS
937 self.gc.TEST_VISIT_SINGLE_STEP = True
938 # this traces target
939 val = self.gc.collect_step()
940 assert (flags(source) & incminimark.GCFLAG_VISITED) == 0
941 assert flags(source) & incminimark.GCFLAG_TRACK_YOUNG_PTRS
942 assert flags(target) & incminimark.GCFLAG_VISITED
943 assert flags(target) & incminimark.GCFLAG_TRACK_YOUNG_PTRS
944
945 addr_src = llmemory.cast_ptr_to_adr(source)
946 addr_dst = llmemory.cast_ptr_to_adr(target)
947 res = self.gc.writebarrier_before_copy(addr_src, addr_dst, 0, 0, 2)
948 if res:
949 # manually do the copy
950 target[0] = source[0]
951 target[1] = source[1]
952 else:
953 self.writearray(target, 0, source[0])
954 self.writearray(target, 1, source[1])
955 self.writearray(source, 0, lltype.nullptr(S))
956 # this traces source
957 self.gc.collect_step()
958 # going through more_objects_to_trace (only the arrays are there)
959 self.gc.collect_step()
960 # sweeping 1
961 self.gc.collect_step()
962 # sweeping 2
963 self.gc.collect_step()
964 # used to crash, node got collected
965 assert target[0].x == 5
966
967 def test_incrementality_bug_arraycopy2(self):
968 # same test as before, but with card marking *on* for the arrays
969 # in the previous one they are too small for card marking
970 self.test_incrementality_bug_arraycopy()
971 test_incrementality_bug_arraycopy2.GC_PARAMS = {
972 "card_page_indices": 4}
973
974 def test_incrementality_bug_arraycopy3(self):
975 # same test as before, but with card marking *on* for the arrays
976 # in the previous one they are too small for card marking
977 self.test_incrementality_bug_arraycopy(size2=2)
978 test_incrementality_bug_arraycopy3.GC_PARAMS = {
979 "card_page_indices": 4}
980
981 def test_pin_id_bug(self):
982 from rpython.rlib import rgc
983
984 flags = self.flags
985
986 self.gc.DEBUG = 2
987 self.gc.TEST_VISIT_SINGLE_STEP = True
988 self.gc.gc_step_until(incminimark.STATE_MARKING)
989
990 s = self.malloc(STR, 1)
991 self.stackroots.append(s)
992 assert self.gc.gc_state == incminimark.STATE_MARKING
993 sid = self.gc.id(s)
994 assert self.gc.gc_state == incminimark.STATE_MARKING
995 pinned = self.gc.pin(llmemory.cast_ptr_to_adr(s))
996 assert pinned
997 self.gc.collect_step()
998 assert self.gc.gc_state == incminimark.STATE_SWEEPING
999 self.gc.unpin(llmemory.cast_ptr_to_adr(s))
1000 self.gc.collect()
1001
1002 def test_pin_id_bug2(self):
1003 flags = self.flags
1004 self.gc.DEBUG = 2
1005 self.gc.TEST_VISIT_SINGLE_STEP = True
1006
1007 s = self.malloc(STR, 1)
1008 self.stackroots.append(s)
1009 sid = self.gc.id(s)
1010 pinned = self.gc.pin(llmemory.cast_ptr_to_adr(s))
1011 assert pinned
1012 self.gc.gc_step_until(incminimark.STATE_FINALIZING)
1013 assert self.gc.gc_state == incminimark.STATE_FINALIZING
1014 self.gc.collect_step()
1015 self.gc.unpin(llmemory.cast_ptr_to_adr(s))
1016 assert self.gc.gc_state == incminimark.STATE_SCANNING
1017 # this used to crash, with unexpected GCFLAG_VISITED in
1018 # _debug_check_object_scanning, called on the shadow
1019 self.gc.collect()
1020
1021
1022 class Node(object):
1023 def __init__(self, x, prev, next):
1024 self.x = x
1025 self.prev = prev # an identity
1026 self.next = next # an identity
1027
1028 def __repr__(self):
1029 return "Node(%s, %s, %s)" % (self.x, self.prev, self.next)
1030
1031 class Weakref(object):
1032 def __init__(self, identity):
1033 self.identity = identity
1034
1035 def __repr__(self):
1036 return "Weakref(%s)" % self.identity
1037
1038 @strategies.composite
1039 def random_action_sequences(draw):
1040 import itertools
1041
1042 result = {}
1043 # make sure that drawing "False" leads to the "simpler" choice
1044 result['use_card_marking'] = draw(strategies.booleans())
1045 result['use_simple_arena'] = not draw(strategies.booleans())
1046 result['visit_single_step'] = not draw(strategies.booleans())
1047 result['debug_level'] = draw(strategies.integers(0, 2))
1048
1049 # identity: object
1050 model = {}
1051 stackroots = []
1052 prebuilts = []
1053 pinned_indexes = []
1054 ids_taken = {} # identity -> index in ids list
1055
1056 current_identity = itertools.count(1)
1057 def next_identity():
1058 return next(current_identity)
1059
1060 def filter_objects(typ):
1061 indexes = []
1062 for index, identity in enumerate(prebuilts):
1063 if isinstance(model[identity], typ):
1064 indexes.append(~index)
1065 for index, identity in enumerate(stackroots):
1066 if isinstance(model[identity], typ):
1067 indexes.append(index)
1068 return indexes
1069
1070 def random_object_index():
1071 indexes = filter_objects(object)
1072 return draw(strategies.sampled_from(indexes))
1073
1074 def random_node_index():
1075 indexes = filter_objects(Node)
1076 return draw(strategies.sampled_from(indexes))
1077
1078 def random_array_index():
1079 indexes = filter_objects(list)
1080 return draw(strategies.sampled_from(indexes))
1081
1082 def get_obj_identity(index):
1083 if index < 0:
1084 return prebuilts[~index]
1085 return stackroots[index]
1086
1087 def create_array():
1088 length = draw(strategies.integers(1, 20))
1089 identity = next_identity()
1090 indexes = [random_node_index() for _ in range(length)]
1091 model[identity] = [get_obj_identity(index) for index in indexes]
1092 return identity, indexes
1093
1094 def create_string():
1095 identity = next_identity()
1096 data = draw(strategies.binary(1, 20))
1097 model[identity] = data
1098 return identity, data
1099
1100 # make some prebuilt nodes
1101 prebuilts_result = []
1102 num_prebuilts = draw(strategies.integers(1, 10))
1103 for prebuilt in range(num_prebuilts):
1104 identity = next_identity()
1105 prebuilts.append(identity)
1106 model[identity] = Node(None, None, None)
1107 previndex = random_node_index()
1108 nextindex = random_node_index()
1109 model[identity] = Node(identity, get_obj_identity(previndex), get_obj_identity(nextindex))
1110 prebuilts_result.append((identity, previndex, nextindex))
1111 result['prebuilts'] = prebuilts_result
1112 prebuilts = [el[0] for el in prebuilts_result]
1113
1114 # prebuilt arrays
1115 prebuilt_arrays_result = []
1116 for i in range(draw(strategies.integers(1, 10))):
1117 identity, indexes = create_array()
1118 prebuilt_arrays_result.append(indexes)
1119 prebuilts.append(identity)
1120 result['prebuilt_arrays'] = prebuilt_arrays_result
1121
1122 # now create actions
1123 actions = []
1124 result['actions'] = actions
1125 def add_action(*args):
1126 # compute a heap checking action
1127 checking_actions = []
1128 reachable_model = {}
1129 seen = {} # identity: path
1130 todo = [(identity, ("prebuilt", i)) for i, identity in enumerate(prebuilts)]
1131 todo += [(identity, ("stackroots", i)) for i, identity in enumerate(stackroots)]
1132 while todo:
1133 identity, path = todo.pop()
1134 if identity in seen:
1135 checking_actions.append(("seen", path))
1136 continue
1137 seen[identity] = path
1138 obj = model[identity]
1139 if isinstance(obj, Node):
1140 checking_actions.append(("node", obj.x, path))
1141
1142 for field in ['prev', 'next']:
1143 res = getattr(obj, field)
1144 todo.append((res, path + (field, )))
1145 elif isinstance(obj, list):
1146 checking_actions.append(("array", len(obj), path))
1147 for index, res in enumerate(model[identity]):
1148 todo.append((res, path + (index, )))
1149 elif isinstance(obj, Weakref):
1150 if obj.identity in seen:
1151 checking_actions.append(("weakref", "seen", seen[obj.identity], path))
1152 else:
1153 checking_actions.append((obj, path))
1154 else:
1155 assert isinstance(obj, str)
1156 checking_actions.append(("str", obj, path))
1157 # deal with the weakrefs
1158 for index, tup in enumerate(checking_actions):
1159 obj = tup[0]
1160 if not isinstance(obj, Weakref):
1161 continue
1162 if obj.identity in seen:
1163 checking_actions[index] = ("weakref", "alive", seen[obj.identity], tup[1])
1164 else:
1165 checking_actions[index] = ("weakref", "dead", None, tup[1])
1166 args += (checking_actions, )
1167 assert "weakref" not in checking_actions
1168 actions.append(args)
1169
1170 all_actions = []
1171 def gen_action(name, precond=None):
1172 def wrap(func):
1173 if precond is None:
1174 precond1 = lambda: True
1175 elif isinstance(precond, type):
1176 # passing a type means "do we have an object of that type
1177 # available currently"
1178 typ = precond
1179 precond1 = lambda: len(filter_objects(typ)) != 0
1180 else:
1181 precond1 = precond
1182 all_actions.append((func, precond1))
1183 return func
1184 return wrap
1185
1186 @gen_action("drop", lambda: len(stackroots) != 0)
1187 def drop():
1188 index = draw(strategies.integers(0, len(stackroots)-1))
1189 if index in pinned_indexes:
1190 indexindex = pinned_indexes.index(index)
1191 add_action("unpin", indexindex)
1192 del pinned_indexes[indexindex]
1193 del stackroots[index]
1194 # ugh, annoying
1195 pinned_indexes[:] = [(pinned_index if pinned_index < index else pinned_index - 1)
1196 for pinned_index in pinned_indexes]
1197 add_action("drop", index)
1198
1199 @gen_action("malloc", object)
1200 def malloc():
1201 nextindex = random_object_index()
1202 previndex = random_object_index()
1203 identity = next_identity()
1204 model[identity] = Node(identity, get_obj_identity(previndex), get_obj_identity(nextindex))
1205 stackroots.append(identity)
1206 add_action('malloc', identity, previndex, nextindex)
1207
1208 @gen_action("read", Node)
1209 def read():
1210 index = random_node_index()
1211 identity = get_obj_identity(index)
1212 if draw(strategies.booleans()):
1213 field = 'prev'
1214 else:
1215 field = 'next'
1216 res = getattr(model[identity], field)
1217 stackroots.append(res)
1218 add_action("read", index, field)
1219
1220 @gen_action("write", Node)
1221 def write():
1222 index1 = random_node_index()
1223 index2 = random_object_index()
1224 if draw(strategies.booleans()):
1225 field = 'prev'
1226 else:
1227 field = 'next'
1228 identity1 = get_obj_identity(index1)
1229 identity2 = get_obj_identity(index2)
1230 setattr(model[identity1], field, identity2)
1231 add_action('write', index1, field, index2)
1232
1233 @gen_action("collect")
1234 def collect():
1235 add_action('collect')
1236
1237 @gen_action("readarray", list)
1238 def readarray():
1239 arrayindex = random_array_index()
1240 identity = get_obj_identity(arrayindex)
1241 l = model[identity]
1242 index = draw(strategies.integers(0, len(l) - 1))
1243 res = model[identity][index]
1244 stackroots.append(res)
1245 add_action('readarray', arrayindex, index)
1246
1247 @gen_action("writearray", list)
1248 def writearray():
1249 arrayindex = random_array_index()
1250 objindex = random_object_index()
1251 identity = get_obj_identity(arrayindex)
1252 l = model[identity]
1253 length = len(l)
1254 index = draw(strategies.integers(0, length - 1))
1255 l[index] = get_obj_identity(objindex)
1256 add_action('writearray', arrayindex, index, objindex)
1257
1258 @gen_action("copy_array", list)
1259 def copy_array():
1260 array1index = random_array_index()
1261 array2index = random_array_index()
1262 array1identity = get_obj_identity(array1index)
1263 array2identity = get_obj_identity(array2index)
1264 assume(array1identity != array2identity)
1265 array1 = model[array1identity]
1266 array2 = model[array2identity]
1267 array1length = len(array1)
1268 array2length = len(array2)
1269 if not draw(strategies.booleans()):
1270 source_start = dest_start = 0
1271 length = draw(strategies.integers(1, min(array1length, array2length)))
1272 else:
1273 source_start = draw(strategies.integers(0, array1length-1))
1274 dest_start = draw(strategies.integers(0, array2length-1))
1275 length = draw(strategies.integers(1, min(array1length - source_start, array2length - dest_start)))
1276 for i in range(length):
1277 array2[dest_start + i] = array1[source_start + i]
1278 add_action('copy_array', array1index, array2index, source_start, dest_start, length)
1279
1280 @gen_action("malloc_array")
1281 def malloc_array():
1282 identity, indexes = create_array()
1283 stackroots.append(identity)
1284 add_action('malloc_array', indexes)
1285
1286 @gen_action("malloc_string")
1287 def malloc_string():
1288 identity, value = create_string()
1289 stackroots.append(identity)
1290 add_action('malloc_string', value)
1291
1292 @gen_action("pin", str)
1293 def pin():
1294 indexes = [index for index, identity in enumerate(stackroots) if isinstance(model[identity], str) and index not in pinned_indexes]
1295 index = draw(strategies.sampled_from(indexes))
1296 pinned_indexes.append(index)
1297 add_action('pin', index)
1298
1299 @gen_action("unpin", lambda: len(pinned_indexes) != 0)
1300 def unpin():
1301 index = draw(strategies.integers(0, len(pinned_indexes) - 1))
1302 del pinned_indexes[index]
1303 add_action('unpin', index)
1304
1305 @gen_action("take_id", object)
1306 def take_id():
1307 index = random_object_index()
1308 identity = get_obj_identity(index)
1309 if identity in ids_taken:
1310 add_action('take_id', index, ids_taken[identity])
1311 else:
1312 ids_taken[identity] = len(ids_taken)
1313 add_action('take_id', index, -1)
1314
1315 @gen_action("create_weakref", lambda: len(filter_objects((Node, list))) != 0)
1316 def create_weakref():
1317 indexes = filter_objects((Node, list))
1318 index = draw(strategies.sampled_from(indexes))
1319 identity = get_obj_identity(index)
1320 new_identity = next_identity()
1321 ref = Weakref(identity)
1322 model[new_identity] = ref
1323 stackroots.append(new_identity)
1324 add_action("create_weakref", index)
1325
1326 for i in range(draw(strategies.integers(2, 100))):
1327 # generate steps
1328
1329 # sample from the actions where preconditions are met:
1330 active_actions = [action for action, precond in all_actions if precond()]
1331 action = draw(strategies.sampled_from(active_actions))
1332 action()
1333 return result
1334
1335 class TestIncrementalMiniMarkGCFullRandom(DirectGCTest):
1336 from rpython.memory.gc.incminimark import IncrementalMiniMarkGC as GCClass
1337
1338 NODE = lltype.GcStruct('NODE',
1339 ('x', lltype.Signed),
1340 ('prev', llmemory.GCREF),
1341 ('next', llmemory.GCREF))
1342
1343 VAR = lltype.GcArray(llmemory.GCREF)
1344
1345 def state_setup(self, random_data):
1346 from rpython.memory.gc.minimarktest import SimpleArenaCollection
1347 if random_data['use_card_marking']:
1348 # enable card marking
1349 GC_PARAMS = {"card_page_indices": 4}
1350 else:
1351 GC_PARAMS = {}
1352 if random_data['use_simple_arena']:
1353 GC_PARAMS['ArenaCollectionClass'] = SimpleArenaCollection
1354 self.test_random.im_func.GC_PARAMS = GC_PARAMS
1355 self.setup_method(self.test_random.im_func)
1356 self.gc.TEST_VISIT_SINGLE_STEP = random_data['visit_single_step']
1357 self.gc.DEBUG = random_data['debug_level']
1358 self.make_prebuilts(random_data)
1359 self.pinned_strings = []
1360 self.computed_ids = []
1361
1362 def erase(self, obj):
1363 return lltype.cast_opaque_ptr(llmemory.GCREF, obj)
1364
1365 def unerase_array(self, gcref):
1366 return lltype.cast_opaque_ptr(lltype.Ptr(self.VAR), gcref)
1367
1368 def unerase_node(self, gcref):
1369 return lltype.cast_opaque_ptr(lltype.Ptr(self.NODE), gcref)
1370
1371 def unerase_str(self, gcref):
1372 return lltype.cast_opaque_ptr(lltype.Ptr(STR), gcref)
1373
1374 def unerase_weakref(self, gcref):
1375 return lltype.cast_opaque_ptr(WEAKREFPTR, gcref)
1376
1377 def make_prebuilts(self, random_data):
1378 prebuilts = self.prebuilts = []
1379 # construct the prebuilt nodes
1380 for identity, _, _ in random_data['prebuilts']:
1381 prebuilt = lltype.malloc(self.NODE, immortal=True)
1382 prebuilt.x = identity
1383 prebuilts.append(prebuilt)
1384 # initialize next and prev fields
1385 for node, (_, previd, nextid) in zip(prebuilts, random_data['prebuilts']):
1386 self.consider_constant(node)
1387 node.prev = self.erase(self.get_node(previd))
1388 node.next = self.erase(self.get_node(nextid))
1389
1390 # prebuilt arrays
1391 for content in random_data['prebuilt_arrays']:
1392 array = self.create_array(content, immortal=True)
1393 self.prebuilts.append(array)
1394 self.consider_constant(array)
1395
1396 def get_obj(self, index):
1397 if index < 0:
1398 return self.prebuilts[~index]
1399 else:
1400 return self.stackroots[index]
1401
1402 def get_node(self, index):
1403 res = self.get_obj(index)
1404 return self.unerase_node(res)
1405
1406 def get_array(self, index):
1407 res = self.get_obj(index)
1408 return self.unerase_array(res)
1409
1410 def create_array(self, content, immortal=False):
1411 if immortal:
1412 array = lltype.malloc(self.VAR, len(content), immortal=True)
1413 else:
1414 array = self.malloc(self.VAR, len(content))
1415 for index, objindex in enumerate(content):
1416 obj = self.erase(self.get_node(objindex))
1417 if immortal:
1418 array[index] = obj
1419 else:
1420 self.writearray(array, index, obj)
1421 return array
1422
1423 def create_string(self, content):
1424 string = self.malloc(STR, len(content))
1425 for index, c in enumerate(content):
1426 string.chars[index] = c
1427 return string
1428
1429 def check(self, checking_actions, must_be_dead=False):
1430 # check that all the successfully pinned strings can be accessed
1431 # without going via stackroots
1432 for s in self.pinned_strings:
1433 if s is not None:
1434 len(self.unerase_str(s).chars) # would crash
1435 todo = self.prebuilts + self.stackroots
1436 # walk the reachable heap and compare against model
1437 iterator = iter(checking_actions)
1438 while todo:
1439 obj = todo.pop()
1440 action = next(iterator)
1441 path = action[-1]
1442 actiondata = action[:-1]
1443 if actiondata[0] == "seen":
1444 continue
1445 elif actiondata[0] == "array":
1446 obj = self.unerase_array(obj)
1447 assert actiondata == ("array", len(obj))
1448 for i in range(len(obj)):
1449 todo.append(obj[i])
1450 elif actiondata[0] == "node":
1451 obj = self.unerase_node(obj)
1452 assert actiondata == ("node", obj.x)
1453 todo.append(obj.prev)
1454 todo.append(obj.next)
1455 elif actiondata[0] == "weakref":
1456 obj = self.unerase_weakref(obj)
1457 ptr = llmemory.cast_adr_to_ptr(obj.weakptr, llmemory.GCREF)
1458 _, status, objpath = actiondata
1459 if status == "seen" or status == "alive":
1460 # treat seen and alive the same for now
1461 # just check that it's a valid object, in a somewhat
1462 # annoying way
1463 assert ptr
1464 assert "DEAD" not in str(ptr._obj.container)
1465 else:
1466 assert status == "dead"
1467 if must_be_dead:
1468 assert not ptr
1469 else:
1470 if ptr:
1471 # it can point to an object, but that must be a
1472 # still alive one
1473 assert "DEAD" not in str(ptr._obj.container)
1474 else:
1475 assert actiondata[0] == "str"
1476 obj = self.unerase_str(obj)
1477 assert "".join(obj.chars) == actiondata[1]
1478
1479 @given(random_action_sequences())
1480 @settings(deadline=None, suppress_health_check=[HealthCheck.too_slow])
1481 def test_random(self, random_data):
1482 from rpython.rlib import rgc
1483 self.state_setup(random_data)
1484 for action in random_data['actions']:
1485 kind = action[0]
1486 actiondata = action[1:-1]
1487 print kind, actiondata
1488 if kind == "drop": # drop
1489 index, = actiondata
1490 del self.stackroots[index]
1491 elif kind == "malloc": # alloc
1492 identity, previd, nextid = actiondata
1493 p = self.malloc(self.NODE)
1494 p.x = identity
1495 self.write(p, 'prev', self.erase(self.get_obj(previd)))
1496 self.write(p, 'next', self.erase(self.get_obj(nextid)))
1497 self.stackroots.append(p)
1498 elif kind == "read": # read field
1499 objindex, field = actiondata
1500 obj = self.get_node(objindex)
1501 res = getattr(obj, field)
1502 self.stackroots.append(res)
1503 elif kind == "write":
1504 obj1index, field, obj2index = actiondata
1505 obj1 = self.get_node(obj1index)
1506 obj2 = self.get_obj(obj2index)
1507 self.write(obj1, field, self.erase(obj2))
1508 elif kind == "collect":
1509 assert actiondata == ()
1510 self.gc.collect_step()
1511 elif kind == "readarray":
1512 arrayindex, index = actiondata
1513 array = self.get_array(arrayindex)
1514 self.stackroots.append(array[index])
1515 elif kind == "writearray":
1516 arrayindex, index, objindex = actiondata
1517 array = self.get_array(arrayindex)
1518 node = self.get_obj(objindex)
1519 self.writearray(array, index, self.erase(node))
1520 elif kind == "copy_array":
1521 array1index, array2index, source_start, dest_start, length = actiondata
1522 array1 = self.get_array(array1index)
1523 array2 = self.get_array(array2index)
1524 slowpath = not self.gc.writebarrier_before_copy(llmemory.cast_ptr_to_adr(array1), llmemory.cast_ptr_to_adr(array2),
1525 source_start, dest_start,
1526 length)
1527 for i in range(length):
1528 if slowpath:
1529 self.writearray(array2, dest_start, array1[source_start])
1530 else:
1531 # don't call the write barrier
1532 array2[dest_start] = array1[source_start]
1533 dest_start += 1
1534 source_start += 1
1535 elif kind == "malloc_array":
1536 content, = actiondata
1537 array = self.create_array(content)
1538 self.stackroots.append(array)
1539 elif kind == "malloc_string":
1540 content, = actiondata
1541 array = self.create_string(content)
1542 self.stackroots.append(array)
1543 elif kind == "pin":
1544 index, = actiondata
1545 ptr = self.stackroots[index]
1546 flag = self.gc.pin(llmemory.cast_ptr_to_adr(ptr))
1547 if flag:
1548 self.pinned_strings.append(ptr)
1549 else:
1550 self.pinned_strings.append(None)
1551 elif kind == "unpin":
1552 index, = actiondata
1553 ptr = self.pinned_strings[index]
1554 if ptr is None:
1555 # pinning had failed, do nothing
1556 pass
1557 else:
1558 self.gc.unpin(llmemory.cast_ptr_to_adr(ptr))
1559 del self.pinned_strings[index]
1560 elif kind == "take_id":
1561 index, compare_with = actiondata
1562 node = self.get_obj(index)
1563 int_id = self.gc.id(node)
1564 if compare_with == -1:
1565 self.computed_ids.append(int_id)
1566 else:
1567 assert self.computed_ids[compare_with] == int_id
1568 elif kind == "create_weakref":
1569 index, = actiondata
1570 ref = self.malloc(WEAKREF)
1571 # must read node *after* malloc, in case malloc collects and moves
1572 node = self.get_obj(index)
1573 ref.weakptr = llmemory.cast_ptr_to_adr(node)
1574 self.stackroots.append(ref)
1575 else:
1576 assert 0, "unreachable"
1577 checking_actions = action[-1]
1578 self.check(checking_actions)
1579 self.gc.TEST_VISIT_SINGLE_STEP = False # otherwise the collection might not finish
1580 self.gc.collect()
1581 self.check(checking_actions, must_be_dead=True)