Debian Codegraph @

rpython/memory/gc/semispace.py

raw symbols SCIP
1 from rpython.rtyper.lltypesystem.llmemory import raw_malloc, raw_free
2 from rpython.rtyper.lltypesystem.llmemory import raw_memcopy, raw_memclear
3 from rpython.rtyper.lltypesystem.llmemory import NULL, raw_malloc_usage
4 from rpython.memory.support import get_address_stack, get_address_deque
5 from rpython.memory.support import AddressDict
6 from rpython.rtyper.lltypesystem import lltype, llmemory, llarena, rffi, llgroup
7 from rpython.rlib.objectmodel import free_non_gc_object
8 from rpython.rlib.debug import ll_assert, have_debug_prints
9 from rpython.rlib.debug import debug_print, debug_start, debug_stop
10 from rpython.rtyper.lltypesystem.lloperation import llop
11 from rpython.rlib.rarithmetic import ovfcheck, LONG_BIT
12 from rpython.memory.gc.base import MovingGCBase, ARRAY_TYPEID_MAP,\
13 TYPEID_MAP
14
15 import sys, os
16
17 first_gcflag = 1 << (LONG_BIT//2)
18 GCFLAG_FORWARDED = first_gcflag
19 # GCFLAG_EXTERNAL is set on objects not living in the semispace:
20 # either immortal objects or (for HybridGC) externally raw_malloc'ed
21 GCFLAG_EXTERNAL = first_gcflag << 1
22 GCFLAG_FINALIZATION_ORDERING = first_gcflag << 2
23
24 _GCFLAG_HASH_BASE = first_gcflag << 3
25 GCFLAG_HASHMASK = _GCFLAG_HASH_BASE * 0x3 # also consumes 'first_gcflag << 4'
26 # the two bits in GCFLAG_HASHMASK can have one of the following values:
27 # - nobody ever asked for the hash of the object
28 GC_HASH_NOTTAKEN = _GCFLAG_HASH_BASE * 0x0
29 # - someone asked, and we gave the address of the object
30 GC_HASH_TAKEN_ADDR = _GCFLAG_HASH_BASE * 0x1
31 # - someone asked, and we gave the address plus 'nursery_hash_base'
32 GC_HASH_TAKEN_NURS = _GCFLAG_HASH_BASE * 0x2
33 # - we have our own extra field to store the hash
34 GC_HASH_HASFIELD = _GCFLAG_HASH_BASE * 0x3
35
36 GCFLAG_EXTRA = first_gcflag << 5 # for RPython abuse only
37
38 memoryError = MemoryError()
39
40
41 class SemiSpaceGC(MovingGCBase):
42 _alloc_flavor_ = "raw"
43 inline_simple_malloc = True
44 inline_simple_malloc_varsize = True
45 malloc_zero_filled = True
46 first_unused_gcflag = first_gcflag << 6
47 gcflag_extra = GCFLAG_EXTRA
48
49 HDR = lltype.Struct('header', ('tid', lltype.Signed)) # XXX or rffi.INT?
50 typeid_is_in_field = 'tid'
51 FORWARDSTUB = lltype.GcStruct('forwarding_stub',
52 ('forw', llmemory.Address))
53 FORWARDSTUBPTR = lltype.Ptr(FORWARDSTUB)
54
55 object_minimal_size = llmemory.sizeof(FORWARDSTUB)
56
57 # the following values override the default arguments of __init__ when
58 # translating to a real backend.
59 TRANSLATION_PARAMS = {'space_size': 8*1024*1024} # XXX adjust
60
61 def __init__(self, config, space_size=4096, max_space_size=sys.maxint//2+1,
62 **kwds):
63 self.param_space_size = space_size
64 self.param_max_space_size = max_space_size
65 MovingGCBase.__init__(self, config, **kwds)
66
67 def setup(self):
68 #self.total_collection_time = 0.0
69 self.total_collection_count = 0
70
71 self.space_size = self.param_space_size
72 self.max_space_size = self.param_max_space_size
73 self.red_zone = 0
74
75 #self.program_start_time = time.time()
76 self.tospace = llarena.arena_malloc(self.space_size, True)
77 ll_assert(bool(self.tospace), "couldn't allocate tospace")
78 self.top_of_space = self.tospace + self.space_size
79 self.fromspace = llarena.arena_malloc(self.space_size, True)
80 ll_assert(bool(self.fromspace), "couldn't allocate fromspace")
81 self.free = self.tospace
82 MovingGCBase.setup(self)
83 self.objects_with_finalizers = self.AddressDeque()
84 self.objects_with_light_finalizers = self.AddressStack()
85 self.objects_with_weakrefs = self.AddressStack()
86
87 def _teardown(self):
88 debug_print("Teardown")
89 llarena.arena_free(self.fromspace)
90 llarena.arena_free(self.tospace)
91
92 # This class only defines the malloc_{fixed,var}size_clear() methods
93 # because the spaces are filled with zeroes in advance.
94
95 def malloc_fixedsize_clear(self, typeid16, size,
96 has_finalizer=False,
97 is_finalizer_light=False,
98 contains_weakptr=False):
99 size_gc_header = self.gcheaderbuilder.size_gc_header
100 totalsize = size_gc_header + size
101 result = self.free
102 if raw_malloc_usage(totalsize) > self.top_of_space - result:
103 result = self.obtain_free_space(totalsize)
104 llarena.arena_reserve(result, totalsize)
105 self.init_gc_object(result, typeid16)
106 self.free = result + totalsize
107 #if is_finalizer_light:
108 # self.objects_with_light_finalizers.append(result + size_gc_header)
109 #else:
110 if has_finalizer:
111 from rpython.rtyper.lltypesystem import rffi
112 self.objects_with_finalizers.append(result + size_gc_header)
113 self.objects_with_finalizers.append(rffi.cast(llmemory.Address, -1))
114 if contains_weakptr:
115 self.objects_with_weakrefs.append(result + size_gc_header)
116 return llmemory.cast_adr_to_ptr(result+size_gc_header, llmemory.GCREF)
117
118 def malloc_varsize_clear(self, typeid16, length, size, itemsize,
119 offset_to_length):
120 size_gc_header = self.gcheaderbuilder.size_gc_header
121 nonvarsize = size_gc_header + size
122 try:
123 varsize = ovfcheck(itemsize * length)
124 totalsize = ovfcheck(nonvarsize + varsize)
125 except OverflowError:
126 raise memoryError
127 result = self.free
128 if raw_malloc_usage(totalsize) > self.top_of_space - result:
129 result = self.obtain_free_space(totalsize)
130 llarena.arena_reserve(result, totalsize)
131 self.init_gc_object(result, typeid16)
132 (result + size_gc_header + offset_to_length).signed[0] = length
133 self.free = result + llarena.round_up_for_allocation(totalsize)
134 return llmemory.cast_adr_to_ptr(result+size_gc_header, llmemory.GCREF)
135
136 def shrink_array(self, addr, smallerlength):
137 size_gc_header = self.gcheaderbuilder.size_gc_header
138 if self._is_in_the_space(addr - size_gc_header):
139 typeid = self.get_type_id(addr)
140 totalsmallersize = (
141 size_gc_header + self.fixed_size(typeid) +
142 self.varsize_item_sizes(typeid) * smallerlength)
143 llarena.arena_shrink_obj(addr - size_gc_header, totalsmallersize)
144 #
145 offset_to_length = self.varsize_offset_to_length(typeid)
146 (addr + offset_to_length).signed[0] = smallerlength
147 return True
148 else:
149 return False
150
151 def register_finalizer(self, fq_index, gcobj):
152 from rpython.rtyper.lltypesystem import rffi
153 obj = llmemory.cast_ptr_to_adr(gcobj)
154 fq_index = rffi.cast(llmemory.Address, fq_index)
155 self.objects_with_finalizers.append(obj)
156 self.objects_with_finalizers.append(fq_index)
157
158 def obtain_free_space(self, needed):
159 # a bit of tweaking to maximize the performance and minimize the
160 # amount of code in an inlined version of malloc_fixedsize_clear()
161 if not self.try_obtain_free_space(needed):
162 raise memoryError
163 return self.free
164 obtain_free_space._dont_inline_ = True
165
166 def try_obtain_free_space(self, needed):
167 # XXX for bonus points do big objects differently
168 needed = raw_malloc_usage(needed)
169 if (self.red_zone >= 2 and self.space_size < self.max_space_size and
170 self.double_space_size()):
171 pass # collect was done during double_space_size()
172 else:
173 self.semispace_collect()
174 missing = needed - (self.top_of_space - self.free)
175 if missing <= 0:
176 return True # success
177 else:
178 # first check if the object could possibly fit
179 proposed_size = self.space_size
180 while missing > 0:
181 if proposed_size >= self.max_space_size:
182 return False # no way
183 missing -= proposed_size
184 proposed_size *= 2
185 # For address space fragmentation reasons, we double the space
186 # size possibly several times, moving the objects at each step,
187 # instead of going directly for the final size. We assume that
188 # it's a rare case anyway.
189 while self.space_size < proposed_size:
190 if not self.double_space_size():
191 return False
192 ll_assert(needed <= self.top_of_space - self.free,
193 "double_space_size() failed to do its job")
194 return True
195
196 def double_space_size(self):
197 self.red_zone = 0
198 old_fromspace = self.fromspace
199 newsize = self.space_size * 2
200 newspace = llarena.arena_malloc(newsize, True)
201 if not newspace:
202 return False # out of memory
203 llarena.arena_free(old_fromspace)
204 self.fromspace = newspace
205 # now self.tospace contains the existing objects and
206 # self.fromspace is the freshly allocated bigger space
207
208 self.semispace_collect(size_changing=True)
209 self.top_of_space = self.tospace + newsize
210 # now self.tospace is the freshly allocated bigger space,
211 # and self.fromspace is the old smaller space, now empty
212 llarena.arena_free(self.fromspace)
213
214 newspace = llarena.arena_malloc(newsize, True)
215 if not newspace:
216 # Complex failure case: we have in self.tospace a big chunk
217 # of memory, and the two smaller original spaces are already gone.
218 # Unsure if it's worth these efforts, but we can artificially
219 # split self.tospace in two again...
220 self.max_space_size = self.space_size # don't try to grow again,
221 # because doing arena_free(self.fromspace) would crash
222 self.fromspace = self.tospace + self.space_size
223 self.top_of_space = self.fromspace
224 ll_assert(self.free <= self.top_of_space,
225 "unexpected growth of GC space usage during collect")
226 return False # out of memory
227
228 self.fromspace = newspace
229 self.space_size = newsize
230 return True # success
231
232 def set_max_heap_size(self, size):
233 # Set the maximum semispace size.
234 # The size is rounded down to the next power of two. Also, this is
235 # the size of one semispace only, so actual usage can be the double
236 # during a collection. Finally, note that this will never shrink
237 # an already-allocated heap.
238 if size < 1:
239 size = 1 # actually, the minimum is 8MB in default translations
240 self.max_space_size = sys.maxint//2+1
241 while self.max_space_size > size:
242 self.max_space_size >>= 1
243
244 @classmethod
245 def JIT_minimal_size_in_nursery(cls):
246 return cls.object_minimal_size
247
248 def collect(self, gen=0):
249 self.debug_check_consistency()
250 self.semispace_collect()
251 # the indirection is required by the fact that collect() is referred
252 # to by the gc transformer, and the default argument would crash
253 # (this is also a hook for the HybridGC)
254
255 def semispace_collect(self, size_changing=False):
256 debug_start("gc-collect")
257 debug_print()
258 debug_print(".----------- Full collection ------------------")
259 start_usage = self.free - self.tospace
260 debug_print("| used before collection: ",
261 start_usage, "bytes")
262 #start_time = time.time()
263 #llop.debug_print(lltype.Void, 'semispace_collect', int(size_changing))
264
265 # Switch the spaces. We copy everything over to the empty space
266 # (self.fromspace at the beginning of the collection), and clear the old
267 # one (self.tospace at the beginning). Their purposes will be reversed
268 # for the next collection.
269 tospace = self.fromspace
270 fromspace = self.tospace
271 self.fromspace = fromspace
272 self.tospace = tospace
273 self.top_of_space = tospace + self.space_size
274 scan = self.free = tospace
275 self.starting_full_collect()
276 self.collect_roots()
277 self.copy_pending_finalizers(self.copy)
278 scan = self.scan_copied(scan)
279 if self.objects_with_light_finalizers.non_empty():
280 self.deal_with_objects_with_light_finalizers()
281 if self.objects_with_finalizers.non_empty():
282 scan = self.deal_with_objects_with_finalizers(scan)
283 if self.objects_with_weakrefs.non_empty():
284 self.invalidate_weakrefs()
285 self.update_objects_with_id()
286 self.finished_full_collect()
287 self.debug_check_consistency()
288 if not size_changing:
289 llarena.arena_reset(fromspace, self.space_size, True)
290 self.record_red_zone()
291 self.execute_finalizers()
292 #llop.debug_print(lltype.Void, 'collected', self.space_size, size_changing, self.top_of_space - self.free)
293 if have_debug_prints():
294 #end_time = time.time()
295 #elapsed_time = end_time - start_time
296 #self.total_collection_time += elapsed_time
297 self.total_collection_count += 1
298 #total_program_time = end_time - self.program_start_time
299 end_usage = self.free - self.tospace
300 debug_print("| used after collection: ",
301 end_usage, "bytes")
302 debug_print("| freed: ",
303 start_usage - end_usage, "bytes")
304 debug_print("| size of each semispace: ",
305 self.space_size, "bytes")
306 debug_print("| fraction of semispace now used: ",
307 end_usage * 100.0 / self.space_size, "%")
308 #ct = self.total_collection_time
309 cc = self.total_collection_count
310 debug_print("| number of semispace_collects: ",
311 cc)
312 #debug_print("| i.e.: ",
313 # cc / total_program_time, "per second")
314 #debug_print("| total time in semispace_collect: ",
315 # ct, "seconds")
316 #debug_print("| i.e.: ",
317 # ct * 100.0 / total_program_time, "%")
318 debug_print("`----------------------------------------------")
319 debug_stop("gc-collect")
320
321 def starting_full_collect(self):
322 pass # hook for the HybridGC
323
324 def finished_full_collect(self):
325 pass # hook for the HybridGC
326
327 def record_red_zone(self):
328 # red zone: if the space is more than 80% full, the next collection
329 # should double its size. If it is more than 66% full twice in a row,
330 # then it should double its size too. (XXX adjust)
331 # The goal is to avoid many repeated collection that don't free a lot
332 # of memory each, if the size of the live object set is just below the
333 # size of the space.
334 free_after_collection = self.top_of_space - self.free
335 if free_after_collection > self.space_size // 3:
336 self.red_zone = 0
337 else:
338 self.red_zone += 1
339 if free_after_collection < self.space_size // 5:
340 self.red_zone += 1
341
342 def get_size_incl_hash(self, obj):
343 size = self.get_size(obj)
344 hdr = self.header(obj)
345 if (hdr.tid & GCFLAG_HASHMASK) == GC_HASH_HASFIELD:
346 size += llmemory.sizeof(lltype.Signed)
347 return size
348
349 def scan_copied(self, scan):
350 while scan < self.free:
351 curr = scan + self.size_gc_header()
352 self.trace_and_copy(curr)
353 scan += self.size_gc_header() + self.get_size_incl_hash(curr)
354 return scan
355
356 def collect_roots(self):
357 self.root_walker.walk_roots(
358 SemiSpaceGC._collect_root, # stack roots
359 SemiSpaceGC._collect_root, # static in prebuilt non-gc structures
360 SemiSpaceGC._collect_root) # static in prebuilt gc objects
361
362 def _collect_root(self, root):
363 root.address[0] = self.copy(root.address[0])
364
365 def copy(self, obj):
366 if self.DEBUG:
367 self.debug_check_can_copy(obj)
368 if self.is_forwarded(obj):
369 #llop.debug_print(lltype.Void, obj, "already copied to", self.get_forwarding_address(obj))
370 return self.get_forwarding_address(obj)
371 else:
372 objsize = self.get_size(obj)
373 newobj = self.make_a_copy(obj, objsize)
374 #llop.debug_print(lltype.Void, obj, "copied to", newobj,
375 # "tid", self.header(obj).tid,
376 # "size", totalsize)
377 self.set_forwarding_address(obj, newobj, objsize)
378 return newobj
379
380 def _get_object_hash(self, obj, objsize, tid):
381 # Returns the hash of the object, which must not be GC_HASH_NOTTAKEN.
382 gc_hash = tid & GCFLAG_HASHMASK
383 if gc_hash == GC_HASH_HASFIELD:
384 obj = llarena.getfakearenaaddress(obj)
385 return (obj + objsize).signed[0]
386 elif gc_hash == GC_HASH_TAKEN_ADDR:
387 return llmemory.cast_adr_to_int(obj)
388 elif gc_hash == GC_HASH_TAKEN_NURS:
389 return self._compute_current_nursery_hash(obj)
390 else:
391 assert 0, "gc_hash == GC_HASH_NOTTAKEN"
392
393 def _make_a_copy_with_tid(self, obj, objsize, tid):
394 totalsize = self.size_gc_header() + objsize
395 newaddr = self.free
396 llarena.arena_reserve(newaddr, totalsize)
397 raw_memcopy(obj - self.size_gc_header(), newaddr, totalsize)
398 if tid & GCFLAG_HASHMASK:
399 hash = self._get_object_hash(obj, objsize, tid)
400 llarena.arena_reserve(newaddr + totalsize,
401 llmemory.sizeof(lltype.Signed))
402 (newaddr + totalsize).signed[0] = hash
403 tid |= GC_HASH_HASFIELD
404 totalsize += llmemory.sizeof(lltype.Signed)
405 self.free += totalsize
406 newhdr = llmemory.cast_adr_to_ptr(newaddr, lltype.Ptr(self.HDR))
407 newhdr.tid = tid
408 newobj = newaddr + self.size_gc_header()
409 return newobj
410
411 def make_a_copy(self, obj, objsize):
412 tid = self.header(obj).tid
413 return self._make_a_copy_with_tid(obj, objsize, tid)
414
415 def trace_and_copy(self, obj):
416 self.trace(obj, self.make_callback('_trace_copy'), self, None)
417
418 def _trace_copy(self, pointer, ignored):
419 pointer.address[0] = self.copy(pointer.address[0])
420
421 def surviving(self, obj):
422 # To use during a collection. Check if the object is currently
423 # marked as surviving the collection. This is equivalent to
424 # self.is_forwarded() for all objects except the nonmoving objects
425 # created by the HybridGC subclass. In all cases, if an object
426 # survives, self.get_forwarding_address() returns its new address.
427 return self.is_forwarded(obj)
428
429 def is_forwarded(self, obj):
430 return self.header(obj).tid & GCFLAG_FORWARDED != 0
431 # note: all prebuilt objects also have this flag set
432
433 def get_forwarding_address(self, obj):
434 tid = self.header(obj).tid
435 if tid & GCFLAG_EXTERNAL:
436 self.visit_external_object(obj)
437 return obj # external or prebuilt objects are "forwarded"
438 # to themselves
439 else:
440 stub = llmemory.cast_adr_to_ptr(obj, self.FORWARDSTUBPTR)
441 return stub.forw
442
443 def visit_external_object(self, obj):
444 pass # hook for the HybridGC
445
446 def get_possibly_forwarded_type_id(self, obj):
447 tid = self.header(obj).tid
448 if self.is_forwarded(obj) and not (tid & GCFLAG_EXTERNAL):
449 obj = self.get_forwarding_address(obj)
450 return self.get_type_id(obj)
451
452 def set_forwarding_address(self, obj, newobj, objsize):
453 # To mark an object as forwarded, we set the GCFLAG_FORWARDED and
454 # overwrite the object with a FORWARDSTUB. Doing so is a bit
455 # long-winded on llarena, but it all melts down to two memory
456 # writes after translation to C.
457 size_gc_header = self.size_gc_header()
458 stubsize = llmemory.sizeof(self.FORWARDSTUB)
459 tid = self.header(obj).tid
460 ll_assert(tid & GCFLAG_EXTERNAL == 0, "unexpected GCFLAG_EXTERNAL")
461 ll_assert(tid & GCFLAG_FORWARDED == 0, "unexpected GCFLAG_FORWARDED")
462 # replace the object at 'obj' with a FORWARDSTUB.
463 hdraddr = obj - size_gc_header
464 llarena.arena_reset(hdraddr, size_gc_header + objsize, False)
465 llarena.arena_reserve(hdraddr, size_gc_header + stubsize)
466 hdr = llmemory.cast_adr_to_ptr(hdraddr, lltype.Ptr(self.HDR))
467 hdr.tid = tid | GCFLAG_FORWARDED
468 stub = llmemory.cast_adr_to_ptr(obj, self.FORWARDSTUBPTR)
469 stub.forw = newobj
470
471 def combine(self, typeid16, flags):
472 return llop.combine_ushort(lltype.Signed, typeid16, flags)
473
474 def get_type_id(self, addr):
475 tid = self.header(addr).tid
476 ll_assert(tid & (GCFLAG_FORWARDED|GCFLAG_EXTERNAL) != GCFLAG_FORWARDED,
477 "get_type_id on forwarded obj")
478 # Non-prebuilt forwarded objects are overwritten with a FORWARDSTUB.
479 # Although calling get_type_id() on a forwarded object works by itself,
480 # we catch it as an error because it's likely that what is then
481 # done with the typeid is bogus.
482 return llop.extract_ushort(llgroup.HALFWORD, tid)
483
484 def init_gc_object(self, addr, typeid16, flags=0):
485 hdr = llmemory.cast_adr_to_ptr(addr, lltype.Ptr(self.HDR))
486 hdr.tid = self.combine(typeid16, flags)
487
488 def init_gc_object_immortal(self, addr, typeid16, flags=0):
489 hdr = llmemory.cast_adr_to_ptr(addr, lltype.Ptr(self.HDR))
490 flags |= GCFLAG_EXTERNAL | GCFLAG_FORWARDED | GC_HASH_TAKEN_ADDR
491 hdr.tid = self.combine(typeid16, flags)
492 # immortal objects always have GCFLAG_FORWARDED set;
493 # see get_forwarding_address().
494
495 def deal_with_objects_with_light_finalizers(self):
496 """ This is a much simpler version of dealing with finalizers
497 and an optimization - we can reasonably assume that those finalizers
498 don't do anything fancy and *just* call them. Among other things
499 they won't resurrect objects
500 """
501 new_objects = self.AddressStack()
502 while self.objects_with_light_finalizers.non_empty():
503 obj = self.objects_with_light_finalizers.pop()
504 if self.surviving(obj):
505 new_objects.append(self.get_forwarding_address(obj))
506 else:
507 self.call_destructor(obj)
508 self.objects_with_light_finalizers.delete()
509 self.objects_with_light_finalizers = new_objects
510
511 def deal_with_objects_with_finalizers(self, scan):
512 # walk over list of objects with finalizers
513 # if it is not copied, add it to the list of to-be-called finalizers
514 # and copy it, to me make the finalizer runnable
515 # We try to run the finalizers in a "reasonable" order, like
516 # CPython does. The details of this algorithm are in
517 # pypy/doc/discussion/finalizer-order.txt.
518 new_with_finalizer = self.AddressDeque()
519 marked = self.AddressDeque()
520 pending = self.AddressStack()
521 self.tmpstack = self.AddressStack()
522 while self.objects_with_finalizers.non_empty():
523 x = self.objects_with_finalizers.popleft()
524 fq_nr = self.objects_with_finalizers.popleft()
525 ll_assert(self._finalization_state(x) != 1,
526 "bad finalization state 1")
527 if self.surviving(x):
528 new_with_finalizer.append(self.get_forwarding_address(x))
529 new_with_finalizer.append(fq_nr)
530 continue
531 marked.append(x)
532 marked.append(fq_nr)
533 pending.append(x)
534 while pending.non_empty():
535 y = pending.pop()
536 state = self._finalization_state(y)
537 if state == 0:
538 self._bump_finalization_state_from_0_to_1(y)
539 self.trace(y, self._append_if_nonnull, pending, None)
540 elif state == 2:
541 self._recursively_bump_finalization_state_from_2_to_3(y)
542 scan = self._recursively_bump_finalization_state_from_1_to_2(
543 x, scan)
544
545 while marked.non_empty():
546 x = marked.popleft()
547 fq_nr = marked.popleft()
548 state = self._finalization_state(x)
549 ll_assert(state >= 2, "unexpected finalization state < 2")
550 newx = self.get_forwarding_address(x)
551 if state == 2:
552 from rpython.rtyper.lltypesystem import rffi
553 fq_index = rffi.cast(lltype.Signed, fq_nr)
554 self.mark_finalizer_to_run(fq_index, newx)
555 # we must also fix the state from 2 to 3 here, otherwise
556 # we leave the GCFLAG_FINALIZATION_ORDERING bit behind
557 # which will confuse the next collection
558 self._recursively_bump_finalization_state_from_2_to_3(x)
559 else:
560 new_with_finalizer.append(newx)
561 new_with_finalizer.append(fq_nr)
562
563 self.tmpstack.delete()
564 pending.delete()
565 marked.delete()
566 self.objects_with_finalizers.delete()
567 self.objects_with_finalizers = new_with_finalizer
568 return scan
569
570 def _append_if_nonnull(pointer, stack, ignored):
571 stack.append(pointer.address[0])
572 _append_if_nonnull = staticmethod(_append_if_nonnull)
573
574 def _finalization_state(self, obj):
575 if self.surviving(obj):
576 newobj = self.get_forwarding_address(obj)
577 hdr = self.header(newobj)
578 if hdr.tid & GCFLAG_FINALIZATION_ORDERING:
579 return 2
580 else:
581 return 3
582 else:
583 hdr = self.header(obj)
584 if hdr.tid & GCFLAG_FINALIZATION_ORDERING:
585 return 1
586 else:
587 return 0
588
589 def _bump_finalization_state_from_0_to_1(self, obj):
590 ll_assert(self._finalization_state(obj) == 0,
591 "unexpected finalization state != 0")
592 hdr = self.header(obj)
593 hdr.tid |= GCFLAG_FINALIZATION_ORDERING
594
595 def _recursively_bump_finalization_state_from_2_to_3(self, obj):
596 ll_assert(self._finalization_state(obj) == 2,
597 "unexpected finalization state != 2")
598 newobj = self.get_forwarding_address(obj)
599 pending = self.tmpstack
600 ll_assert(not pending.non_empty(), "tmpstack not empty")
601 pending.append(newobj)
602 while pending.non_empty():
603 y = pending.pop()
604 hdr = self.header(y)
605 if hdr.tid & GCFLAG_FINALIZATION_ORDERING: # state 2 ?
606 hdr.tid &= ~GCFLAG_FINALIZATION_ORDERING # change to state 3
607 self.trace(y, self._append_if_nonnull, pending, None)
608
609 def _recursively_bump_finalization_state_from_1_to_2(self, obj, scan):
610 # recursively convert objects from state 1 to state 2.
611 # Note that copy() copies all bits, including the
612 # GCFLAG_FINALIZATION_ORDERING. The mapping between
613 # state numbers and the presence of this bit was designed
614 # for the following to work :-)
615 self.copy(obj)
616 return self.scan_copied(scan)
617
618 def invalidate_weakrefs(self):
619 # walk over list of objects that contain weakrefs
620 # if the object it references survives then update the weakref
621 # otherwise invalidate the weakref
622 new_with_weakref = self.AddressStack()
623 while self.objects_with_weakrefs.non_empty():
624 obj = self.objects_with_weakrefs.pop()
625 if not self.surviving(obj):
626 continue # weakref itself dies
627 obj = self.get_forwarding_address(obj)
628 offset = self.weakpointer_offset(self.get_type_id(obj))
629 pointing_to = (obj + offset).address[0]
630 # XXX I think that pointing_to cannot be NULL here
631 if pointing_to:
632 if self.surviving(pointing_to):
633 (obj + offset).address[0] = self.get_forwarding_address(
634 pointing_to)
635 new_with_weakref.append(obj)
636 else:
637 (obj + offset).address[0] = NULL
638 self.objects_with_weakrefs.delete()
639 self.objects_with_weakrefs = new_with_weakref
640
641 def _is_external(self, obj):
642 return (self.header(obj).tid & GCFLAG_EXTERNAL) != 0
643
644 def _is_in_the_space(self, obj):
645 return self.tospace <= obj < self.free
646
647 def debug_check_object(self, obj):
648 """Check the invariants about 'obj' that should be true
649 between collections."""
650 tid = self.header(obj).tid
651 if tid & GCFLAG_EXTERNAL:
652 ll_assert(tid & GCFLAG_FORWARDED != 0, "bug: external+!forwarded")
653 ll_assert(not (self.tospace <= obj < self.free),
654 "external flag but object inside the semispaces")
655 else:
656 ll_assert(not (tid & GCFLAG_FORWARDED), "bug: !external+forwarded")
657 ll_assert(self.tospace <= obj < self.free,
658 "!external flag but object outside the semispaces")
659 ll_assert(not (tid & GCFLAG_FINALIZATION_ORDERING),
660 "unexpected GCFLAG_FINALIZATION_ORDERING")
661
662 def debug_check_can_copy(self, obj):
663 ll_assert(not (self.tospace <= obj < self.free),
664 "copy() on already-copied object")
665
666 STATISTICS_NUMBERS = 0
667
668 def is_in_nursery(self, addr):
669 # overridden in generation.py.
670 return False
671
672 def _compute_current_nursery_hash(self, obj):
673 # overridden in generation.py.
674 raise AssertionError("should not be called")
675
676 def identityhash(self, gcobj):
677 # The following loop should run at most twice.
678 while 1:
679 obj = llmemory.cast_ptr_to_adr(gcobj)
680 hdr = self.header(obj)
681 if hdr.tid & GCFLAG_HASHMASK:
682 break
683 # It's the first time we ask for a hash, and it's not an
684 # external object. Shrink the top of space by the extra
685 # hash word that will be needed after a collect.
686 shrunk_top = self.top_of_space - llmemory.sizeof(lltype.Signed)
687 if shrunk_top < self.free:
688 # Cannot shrink! Do a collection, asking for at least
689 # one word of free space, and try again. May raise
690 # MemoryError. Obscure: not called directly, but
691 # across an llop, to make sure that there is the
692 # correct push_roots/pop_roots around the call...
693 llop.gc_obtain_free_space(llmemory.Address,
694 llmemory.sizeof(lltype.Signed))
695 continue
696 else:
697 # Now we can have side-effects: lower the top of space
698 # and set one of the GC_HASH_TAKEN_xxx flags.
699 self.top_of_space = shrunk_top
700 if self.is_in_nursery(obj):
701 hdr.tid |= GC_HASH_TAKEN_NURS
702 else:
703 hdr.tid |= GC_HASH_TAKEN_ADDR
704 break
705 # Now we can return the result
706 objsize = self.get_size(obj)
707 return self._get_object_hash(obj, objsize, hdr.tid)
708
709 def track_heap_parent(self, obj, parent):
710 addr = obj.address[0]
711 parent_idx = llop.get_member_index(lltype.Signed,
712 self.get_type_id(parent))
713 idx = llop.get_member_index(lltype.Signed, self.get_type_id(addr))
714 self._ll_typeid_map[parent_idx].links[idx] += 1
715 self.track_heap(addr)
716
717 def track_heap(self, adr):
718 if self._tracked_dict.contains(adr):
719 return
720 self._tracked_dict.add(adr)
721 idx = llop.get_member_index(lltype.Signed, self.get_type_id(adr))
722 self._ll_typeid_map[idx].count += 1
723 totsize = self.get_size(adr) + self.size_gc_header()
724 self._ll_typeid_map[idx].size += llmemory.raw_malloc_usage(totsize)
725 self.trace(adr, self.make_callback('track_heap_parent'), self, adr)
726
727 @staticmethod
728 def _track_heap_root(obj, self):
729 self.track_heap(obj)
730
731 def heap_stats(self):
732 self._tracked_dict = self.AddressDict()
733 max_tid = self.root_walker.gcdata.max_type_id
734 ll_typeid_map = lltype.malloc(ARRAY_TYPEID_MAP, max_tid, zero=True)
735 for i in range(max_tid):
736 ll_typeid_map[i] = lltype.malloc(TYPEID_MAP, max_tid, zero=True)
737 self._ll_typeid_map = ll_typeid_map
738 self._tracked_dict.add(llmemory.cast_ptr_to_adr(ll_typeid_map))
739 i = 0
740 while i < max_tid:
741 self._tracked_dict.add(llmemory.cast_ptr_to_adr(ll_typeid_map[i]))
742 i += 1
743 self.enumerate_all_roots(SemiSpaceGC._track_heap_root, self)
744 self._ll_typeid_map = lltype.nullptr(ARRAY_TYPEID_MAP)
745 self._tracked_dict.delete()
746 return ll_typeid_map