Debian Codegraph @

rpython/memory/gcheader.py

raw symbols SCIP
1 import weakref
2 from rpython.rtyper.lltypesystem import lltype, llmemory
3
4
5 # this is global because a header cannot be a header of more than one GcObj
6 header2obj = weakref.WeakKeyDictionary()
7
8
9 class GCHeaderBuilder(object):
10
11 def __init__(self, HDR):
12 """NOT_RPYTHON"""
13 self.HDR = HDR
14 #
15 # The following used to be a weakref.WeakKeyDictionary(), but
16 # the problem is that if you have a gcobj which has already a
17 # weakref cached on it and the hash already cached in that
18 # weakref, and later the hash of the gcobj changes (because it
19 # is ll2ctypes-ified), then that gcobj cannot be used as a key
20 # in a WeakKeyDictionary any more: from this point on,
21 # 'ref(gcobj)' and 'ref(gcobj, callback)' return two objects
22 # with different hashes... and so e.g. the sequence of
23 # operations 'obj2header[x]=y; assert x in obj2header' fails.
24 #
25 # Instead, just use a regular dictionary and hope that not too
26 # many objects would be reclaimed in a given GCHeaderBuilder
27 # instance.
28 self.obj2header = {}
29 self.size_gc_header = llmemory.GCHeaderOffset(self)
30
31 def header_of_object(self, gcptr):
32 # XXX hackhackhack
33 gcptr = gcptr._as_obj(check=False)
34 if isinstance(gcptr, llmemory._gctransformed_wref):
35 return self.obj2header[gcptr._ptr._as_obj(check=False)]
36 return self.obj2header[gcptr]
37
38 def object_from_header(headerptr):
39 return header2obj[headerptr._as_obj(check=False)]
40 object_from_header = staticmethod(object_from_header)
41
42 def get_header(self, gcptr):
43 return self.obj2header.get(gcptr._as_obj(check=False), None)
44
45 def attach_header(self, gcptr, headerptr):
46 gcobj = gcptr._as_obj()
47 assert gcobj not in self.obj2header
48 # sanity checks
49 assert gcobj._TYPE._gckind == 'gc'
50 assert not isinstance(gcobj._TYPE, lltype.GcOpaqueType)
51 assert not gcobj._parentstructure()
52 self.obj2header[gcobj] = headerptr
53 header2obj[headerptr._obj] = gcptr._as_ptr()
54
55 def new_header(self, gcptr):
56 headerptr = lltype.malloc(self.HDR, immortal=True)
57 self.attach_header(gcptr, headerptr)
58 return headerptr
59
60 def _freeze_(self):
61 return True # for reads of size_gc_header