Debian Codegraph @

rpython/rtyper/lltypesystem/llmemory.py

raw symbols SCIP
1 # this file contains the definitions and most extremely faked
2 # implementations of things relating to the description of the layout
3 # of objects in memeory.
4
5 # sizeof, offsetof
6
7 import weakref
8 from rpython.annotator.bookkeeper import analyzer_for
9 from rpython.annotator.model import SomeInteger, SomeObject, SomeString, s_Bool
10 from rpython.annotator.model import SomeBool
11 from rpython.rlib.objectmodel import Symbolic, specialize
12 from rpython.rtyper.lltypesystem import lltype
13 from rpython.rtyper.lltypesystem.lltype import SomePtr
14 from rpython.tool.uid import uid
15 from rpython.rlib.rarithmetic import is_valid_int
16 from rpython.rtyper.extregistry import ExtRegistryEntry
17
18
19 class AddressOffset(Symbolic):
20
21 def annotation(self):
22 from rpython.annotator import model
23 return model.SomeInteger()
24
25 def lltype(self):
26 return lltype.Signed
27
28 def __add__(self, other):
29 if not isinstance(other, AddressOffset):
30 return NotImplemented
31 return CompositeOffset(self, other)
32
33 # special-casing: only for '>= 0' and '< 0' and only when the
34 # symbolic offset is known to be non-negative
35 def __ge__(self, other):
36 if self is other:
37 return True
38 elif (is_valid_int(other) and other == 0 and
39 self.known_nonneg()):
40 return True
41 else:
42 raise TypeError("Symbolics cannot be compared! (%r, %r)"
43 % (self, other))
44
45 def __lt__(self, other):
46 return not self.__ge__(other)
47
48 def known_nonneg(self):
49 return False
50
51 def _raw_malloc(self, rest, zero):
52 raise NotImplementedError("_raw_malloc(%r, %r)" % (self, rest))
53
54 def raw_memcopy(self, srcadr, dstadr):
55 raise NotImplementedError("raw_memcopy(%r)" % (self,))
56
57
58 class ItemOffset(AddressOffset):
59
60 def __init__(self, TYPE, repeat=1):
61 self.TYPE = TYPE
62 self.repeat = repeat
63
64 def __repr__(self):
65 return "<ItemOffset %r %r>" % (self.TYPE, self.repeat)
66
67 def __mul__(self, other):
68 if not is_valid_int(other):
69 return NotImplemented
70 return ItemOffset(self.TYPE, self.repeat * other)
71
72 __rmul__ = __mul__
73
74 def __neg__(self):
75 return ItemOffset(self.TYPE, -self.repeat)
76
77 def known_nonneg(self):
78 return self.repeat >= 0
79
80 def ref(self, firstitemptr):
81 A = lltype.typeOf(firstitemptr).TO
82 if A == self.TYPE:
83 # for array of containers
84 parent, index = lltype.parentlink(firstitemptr._obj)
85 assert parent, "%r is not within a container" % (firstitemptr,)
86 assert isinstance(lltype.typeOf(parent),
87 (lltype.Array, lltype.FixedSizeArray)), (
88 "%r is not within an array" % (firstitemptr,))
89 if isinstance(index, str):
90 assert index.startswith('item') # itemN => N
91 index = int(index[4:])
92 index += self.repeat
93 if index == parent.getlength():
94 # for references exactly to the end of the array
95 try:
96 endmarker = _end_markers[parent]
97 except KeyError:
98 endmarker = _endmarker_struct(A, parent=parent,
99 parentindex=index)
100 _end_markers[parent] = endmarker
101 return endmarker._as_ptr()
102 else:
103 return parent.getitem(index)._as_ptr()
104 elif ((isinstance(A, lltype.FixedSizeArray)
105 or (isinstance(A, lltype.Array) and A._hints.get('nolength',
106 False)))
107 and array_item_type_match(A.OF, self.TYPE)):
108 # for array of primitives or pointers
109 return lltype.direct_ptradd(firstitemptr, self.repeat)
110 else:
111 raise TypeError('got %r, expected %r' % (A, self.TYPE))
112
113 def _raw_malloc(self, rest, zero):
114 assert not rest
115 if (isinstance(self.TYPE, lltype.ContainerType)
116 and self.TYPE._gckind == 'gc'):
117 assert self.repeat == 1
118 p = lltype.malloc(self.TYPE, flavor='raw', zero=zero,
119 track_allocation=False)
120 return cast_ptr_to_adr(p)
121 else:
122 T = lltype.FixedSizeArray(self.TYPE, self.repeat)
123 p = lltype.malloc(T, flavor='raw', zero=zero,
124 track_allocation=False)
125 array_adr = cast_ptr_to_adr(p)
126 return array_adr + ArrayItemsOffset(T)
127
128 def raw_memcopy(self, srcadr, dstadr):
129 repeat = self.repeat
130 if repeat == 0:
131 return
132 if isinstance(self.TYPE, lltype.ContainerType):
133 PTR = lltype.Ptr(self.TYPE)
134 elif self.TYPE == GCREF:
135 self._raw_memcopy_gcrefs(srcadr, dstadr)
136 return
137 else:
138 PTR = lltype.Ptr(lltype.FixedSizeArray(self.TYPE, 1))
139 steps = []
140 while True:
141 src = cast_adr_to_ptr(srcadr, PTR)
142 dst = cast_adr_to_ptr(dstadr, PTR)
143 _reccopy_lazy(src, dst, steps)
144 repeat -= 1
145 if repeat <= 0:
146 break
147 srcadr += ItemOffset(self.TYPE)
148 dstadr += ItemOffset(self.TYPE)
149 for step in steps:
150 step()
151
152 def _raw_memcopy_gcrefs(self, srcadr, dstadr):
153 # special case to handle arrays of any GC pointers
154 repeat = self.repeat
155 data_list = []
156 while True:
157 data_list.append(srcadr.address[0])
158 repeat -= 1
159 if repeat <= 0:
160 break
161 srcadr += ItemOffset(self.TYPE)
162 for i, data in enumerate(data_list):
163 if i > 0:
164 dstadr += ItemOffset(self.TYPE)
165 dstadr.address[0] = data
166
167 _end_markers = weakref.WeakKeyDictionary() # <array of STRUCT> -> _endmarker
168 class _endmarker_struct(lltype._struct):
169 __slots__ = ()
170 def __new__(self, *args, **kwds):
171 return object.__new__(self)
172 def __init__(self, *args, **kwds):
173 lltype._struct.__init__(self, *args, **kwds)
174 self._storage = False
175 def __getattr__(self, name):
176 raise AttributeError("cannot access fields in the endmarker "
177 "structure at the end of the array")
178 def __setattr__(self, name, value):
179 if name.startswith('_'):
180 object.__setattr__(self, name, value) # '_xxx' attributes
181 elif self._storage is False:
182 raise AttributeError("cannot access fields in the endmarker "
183 "structure at the end of the array")
184
185
186 class FieldOffset(AddressOffset):
187
188 def __init__(self, TYPE, fldname):
189 self.TYPE = TYPE
190 self.fldname = fldname
191
192 def __repr__(self):
193 return "<FieldOffset %r %r>" % (self.TYPE, self.fldname)
194
195 def known_nonneg(self):
196 return True
197
198 def ref(self, struct):
199 if lltype.typeOf(struct).TO != self.TYPE:
200 struct = lltype.cast_pointer(lltype.Ptr(self.TYPE), struct)
201 FIELD = getattr(self.TYPE, self.fldname)
202 if isinstance(FIELD, lltype.ContainerType):
203 substruct = struct._obj._getattr(self.fldname)
204 return substruct._as_ptr()
205 else:
206 return lltype.direct_fieldptr(struct, self.fldname)
207
208 def _raw_malloc(self, rest, parenttype=None, zero=False):
209 if self.fldname != self.TYPE._arrayfld:
210 # for the error msg
211 return AddressOffset._raw_malloc(self, rest, zero=zero)
212 assert rest
213 return rest[0]._raw_malloc(rest[1:], parenttype=parenttype or self.TYPE,
214 zero=zero)
215
216 def raw_memcopy(self, srcadr, dstadr):
217 if self.fldname != self.TYPE._arrayfld:
218 return AddressOffset.raw_memcopy(srcadr, dstadr) #for the error msg
219 PTR = lltype.Ptr(self.TYPE)
220 src = cast_adr_to_ptr(srcadr, PTR)
221 dst = cast_adr_to_ptr(dstadr, PTR)
222 _reccopy(src, dst)
223
224
225 class CompositeOffset(AddressOffset):
226
227 def __new__(cls, *offsets):
228 lst = []
229 for item in offsets:
230 if isinstance(item, CompositeOffset):
231 lst.extend(item.offsets)
232 else:
233 lst.append(item)
234 for i in range(len(lst)-2, -1, -1):
235 if (isinstance(lst[i], ItemOffset) and
236 isinstance(lst[i+1], ItemOffset) and
237 lst[i].TYPE == lst[i+1].TYPE):
238 lst[i:i+2] = [ItemOffset(lst[i].TYPE,
239 lst[i].repeat + lst[i+1].repeat)]
240 if len(lst) == 1:
241 return lst[0]
242 else:
243 self = object.__new__(cls)
244 self.offsets = lst
245 return self
246
247 def __repr__(self):
248 return '< %s >' % (' + '.join([repr(item) for item in self.offsets]),)
249
250 def __neg__(self):
251 ofs = [-item for item in self.offsets]
252 ofs.reverse()
253 return CompositeOffset(*ofs)
254
255 def known_nonneg(self):
256 for item in self.offsets:
257 if not item.known_nonneg():
258 return False
259 return True
260
261 def ref(self, ptr):
262 for item in self.offsets:
263 ptr = item.ref(ptr)
264 return ptr
265
266 def _raw_malloc(self, rest, zero):
267 return self.offsets[0]._raw_malloc(self.offsets[1:] + rest, zero=zero)
268
269 def raw_memcopy(self, srcadr, dstadr):
270 for o in self.offsets[:-1]:
271 o.raw_memcopy(srcadr, dstadr)
272 srcadr += o
273 dstadr += o
274 o = self.offsets[-1]
275 o.raw_memcopy(srcadr, dstadr)
276
277
278 class ArrayItemsOffset(AddressOffset):
279
280 def __init__(self, TYPE):
281 self.TYPE = TYPE
282
283 def __repr__(self):
284 return '< ArrayItemsOffset %r >' % (self.TYPE,)
285
286 def known_nonneg(self):
287 return True
288
289 def ref(self, arrayptr):
290 assert array_type_match(lltype.typeOf(arrayptr).TO, self.TYPE)
291 if isinstance(self.TYPE.OF, lltype.ContainerType):
292 # XXX this doesn't support empty arrays
293 # XXX it's also missing 'solid' support, probably
294 o = arrayptr._obj.getitem(0)
295 return o._as_ptr()
296 else:
297 return lltype.direct_arrayitems(arrayptr)
298
299 def _raw_malloc(self, rest, parenttype=None, zero=False):
300 if rest:
301 assert len(rest) == 1
302 assert isinstance(rest[0], ItemOffset)
303 assert self.TYPE.OF == rest[0].TYPE
304 count = rest[0].repeat
305 else:
306 count = 0
307 p = lltype.malloc(parenttype or self.TYPE, count,
308 immortal = self.TYPE._gckind == 'raw',
309 zero = zero,
310 track_allocation = False)
311 return cast_ptr_to_adr(p)
312
313 def raw_memcopy(self, srcadr, dstadr):
314 # copy the length field, if we can
315 srclen = srcadr.ptr._obj.getlength()
316 dstlen = dstadr.ptr._obj.getlength()
317 if dstlen != srclen:
318 assert dstlen > srclen, "can't increase the length"
319 # a decrease in length occurs in the GC tests when copying a STR:
320 # the copy is initially allocated with really one extra char,
321 # the 'extra_item_after_alloc', and must be fixed.
322 dstadr.ptr._obj.shrinklength(srclen)
323
324
325 class ArrayLengthOffset(AddressOffset):
326
327 def __init__(self, TYPE):
328 self.TYPE = TYPE
329
330 def __repr__(self):
331 return '< ArrayLengthOffset %r >' % (self.TYPE,)
332
333 def known_nonneg(self):
334 return True
335
336 def ref(self, arrayptr):
337 assert array_type_match(lltype.typeOf(arrayptr).TO, self.TYPE)
338 return lltype._arraylenref._makeptr(arrayptr._obj, arrayptr._solid)
339
340
341 class GCHeaderOffset(AddressOffset):
342 def __init__(self, gcheaderbuilder):
343 self.gcheaderbuilder = gcheaderbuilder
344
345 def __repr__(self):
346 return '< GCHeaderOffset >'
347
348 def __neg__(self):
349 return GCHeaderAntiOffset(self.gcheaderbuilder)
350
351 def known_nonneg(self):
352 return True
353
354 def ref(self, headerptr):
355 gcptr = self.gcheaderbuilder.object_from_header(headerptr)
356 return gcptr
357
358 def _raw_malloc(self, rest, zero):
359 assert rest
360 if isinstance(rest[0], GCHeaderAntiOffset):
361 return rest[1]._raw_malloc(rest[2:], zero=zero) # just for fun
362 gcobjadr = rest[0]._raw_malloc(rest[1:], zero=zero)
363 headerptr = self.gcheaderbuilder.new_header(gcobjadr.ptr)
364 return cast_ptr_to_adr(headerptr)
365
366 def raw_memcopy(self, srcadr, dstadr):
367 _reccopy(srcadr.ptr, dstadr.ptr)
368
369 class GCHeaderAntiOffset(AddressOffset):
370 def __init__(self, gcheaderbuilder):
371 self.gcheaderbuilder = gcheaderbuilder
372
373 def __repr__(self):
374 return '< GCHeaderAntiOffset >'
375
376 def __neg__(self):
377 return GCHeaderOffset(self.gcheaderbuilder)
378
379 def ref(self, gcptr):
380 headerptr = self.gcheaderbuilder.header_of_object(gcptr)
381 return headerptr
382
383 def _raw_malloc(self, rest, zero):
384 assert len(rest) >= 2
385 assert isinstance(rest[0], GCHeaderOffset)
386 return rest[1]._raw_malloc(rest[2:], zero=zero)
387
388 # ____________________________________________________________
389
390 @specialize.memo()
391 def _sizeof_none(TYPE):
392 assert not TYPE._is_varsize()
393 return ItemOffset(TYPE)
394
395 @specialize.memo()
396 def _internal_array_field(TYPE):
397 return TYPE._arrayfld, TYPE._flds[TYPE._arrayfld]
398
399 def _sizeof_int(TYPE, n):
400 if isinstance(TYPE, lltype.Struct):
401 fldname, ARRAY = _internal_array_field(TYPE)
402 return offsetof(TYPE, fldname) + sizeof(ARRAY, n)
403 else:
404 raise Exception("don't know how to take the size of a %r"%TYPE)
405
406 @specialize.memo()
407 def extra_item_after_alloc(ARRAY):
408 assert isinstance(ARRAY, lltype.Array)
409 return ARRAY._hints.get('extra_item_after_alloc', 0)
410
411 @specialize.arg(0)
412 def sizeof(TYPE, n=None):
413 """Return the symbolic size of TYPE.
414 For a Struct with no varsized part, it must be called with n=None.
415 For an Array or a Struct with a varsized part, it is the number of items.
416 There is a special case to return 1 more than requested if the array
417 has the hint 'extra_item_after_alloc' set to 1.
418 """
419 if n is None:
420 return _sizeof_none(TYPE)
421 elif isinstance(TYPE, lltype.Array):
422 n += extra_item_after_alloc(TYPE)
423 return itemoffsetof(TYPE) + _sizeof_none(TYPE.OF) * n
424 else:
425 return _sizeof_int(TYPE, n)
426
427 @specialize.memo()
428 def offsetof(TYPE, fldname):
429 assert fldname in TYPE._flds
430 return FieldOffset(TYPE, fldname)
431
432 @analyzer_for(offsetof)
433 def ann_offsetof(TYPE, fldname):
434 return SomeInteger()
435
436
437 @specialize.memo()
438 def itemoffsetof(TYPE, n=0):
439 result = ArrayItemsOffset(TYPE)
440 if n != 0:
441 result += ItemOffset(TYPE.OF) * n
442 return result
443
444 @specialize.memo()
445 def arraylengthoffset(TYPE):
446 return ArrayLengthOffset(TYPE)
447
448 # -------------------------------------------------------------
449
450 class fakeaddress(object):
451 __slots__ = ['ptr']
452 # NOTE: the 'ptr' in the addresses must be normalized.
453 # Use cast_ptr_to_adr() instead of directly fakeaddress() if unsure.
454 def __init__(self, ptr):
455 if ptr is not None and ptr._obj0 is None:
456 ptr = None # null ptr => None
457 self.ptr = ptr
458
459 def __repr__(self):
460 if self.ptr is None:
461 s = 'NULL'
462 else:
463 #try:
464 # s = hex(self.ptr._cast_to_int())
465 #except:
466 s = str(self.ptr)
467 return '<fakeaddr %s>' % (s,)
468
469 def __add__(self, other):
470 if isinstance(other, AddressOffset):
471 if self.ptr is None:
472 raise NullAddressError("offset from NULL address")
473 return fakeaddress(other.ref(self.ptr))
474 if other == 0:
475 return self
476 return NotImplemented
477
478 def __sub__(self, other):
479 if isinstance(other, AddressOffset):
480 return self + (-other)
481 if isinstance(other, fakeaddress):
482 if self == other:
483 return 0
484 else:
485 raise TypeError("cannot subtract fakeaddresses in general")
486 if other == 0:
487 return self
488 return NotImplemented
489
490 def __nonzero__(self):
491 return self.ptr is not None
492
493 #def __hash__(self):
494 # raise TypeError("don't put addresses in a prebuilt dictionary")
495
496 def __eq__(self, other):
497 if isinstance(other, fakeaddress):
498 try:
499 obj1 = self._fixup().ptr
500 obj2 = other._fixup().ptr
501 if obj1 is not None: obj1 = obj1._obj
502 if obj2 is not None: obj2 = obj2._obj
503 return obj1 == obj2
504 except lltype.DelayedPointer:
505 return self.ptr is other.ptr
506 else:
507 return NotImplemented
508
509 def __ne__(self, other):
510 if isinstance(other, fakeaddress):
511 return not (self == other)
512 else:
513 return NotImplemented
514
515 def __lt__(self, other):
516 # for the convenience of debugging the GCs, NULL compares as the
517 # smallest address even when compared with a non-fakearenaaddress
518 if not isinstance(other, fakeaddress):
519 raise TypeError("cannot compare fakeaddress and %r" % (
520 other.__class__.__name__,))
521 if not other:
522 return False # self < NULL => False
523 if not self:
524 return True # NULL < non-null-other => True
525 raise TypeError("cannot compare non-NULL fakeaddresses with '<'")
526 def __le__(self, other):
527 return self == other or self < other
528 def __gt__(self, other):
529 return not (self == other or self < other)
530 def __ge__(self, other):
531 return not (self < other)
532
533 def ref(self):
534 if not self:
535 raise NullAddressError
536 return self.ptr
537
538 def _cast_to_ptr(self, EXPECTED_TYPE):
539 addr = self._fixup()
540 if addr:
541 return cast_any_ptr(EXPECTED_TYPE, addr.ptr)
542 else:
543 return lltype.nullptr(EXPECTED_TYPE.TO)
544
545 def _cast_to_int(self, symbolic=False):
546 if self:
547 if isinstance(self.ptr._obj0, int): # tagged integer
548 return self.ptr._obj0
549 if symbolic:
550 return AddressAsInt(self)
551 else:
552 # This is a bit annoying. We want this method to still work
553 # when the pointed-to object is dead
554 return self.ptr._cast_to_int(False)
555 else:
556 return 0
557
558 def _fixup(self):
559 if self.ptr is not None and self.ptr._was_freed():
560 # hack to support llarena.test_replace_object_with_stub()
561 from rpython.rtyper.lltypesystem import llarena
562 return llarena.getfakearenaaddress(self)
563 else:
564 return self
565
566 class fakeaddressEntry(ExtRegistryEntry):
567 _type_ = fakeaddress
568
569 def compute_annotation(self):
570 from rpython.rtyper.llannotation import SomeAddress
571 return SomeAddress()
572
573 class SomeAddress(SomeObject):
574 immutable = True
575
576 def can_be_none(self):
577 return False
578
579 def is_null_address(self):
580 return self.is_immutable_constant() and not self.const
581
582 def getattr(self, s_attr):
583 assert s_attr.is_constant()
584 assert isinstance(s_attr, SomeString)
585 assert s_attr.const in supported_access_types
586 return SomeTypedAddressAccess(supported_access_types[s_attr.const])
587 getattr.can_only_throw = []
588
589 def bool(self):
590 return s_Bool
591
592 class SomeTypedAddressAccess(SomeObject):
593 """This class is used to annotate the intermediate value that
594 appears in expressions of the form:
595 addr.signed[offset] and addr.signed[offset] = value
596 """
597
598 def __init__(self, type):
599 self.type = type
600
601 def can_be_none(self):
602 return False
603
604 # ____________________________________________________________
605
606 class AddressAsInt(Symbolic):
607 # a symbolic, rendered as an address cast to an integer.
608 def __init__(self, adr):
609 self.adr = adr
610 def annotation(self):
611 from rpython.annotator import model
612 return model.SomeInteger()
613 def lltype(self):
614 return lltype.Signed
615 def __eq__(self, other):
616 return self.adr == cast_int_to_adr(other)
617 def __ne__(self, other):
618 return self.adr != cast_int_to_adr(other)
619 def __nonzero__(self):
620 return bool(self.adr)
621 def __add__(self, ofs):
622 if (isinstance(ofs, int) and
623 getattr(self.adr.ptr._TYPE.TO, 'OF', None) == lltype.Char):
624 return AddressAsInt(self.adr + ItemOffset(lltype.Char, ofs))
625 if isinstance(ofs, FieldOffset) and ofs.TYPE is self.adr.ptr._TYPE.TO:
626 fieldadr = getattr(self.adr.ptr, ofs.fldname)
627 return AddressAsInt(cast_ptr_to_adr(fieldadr))
628 if (isinstance(ofs, ItemOffset) and
629 isinstance(self.adr.ptr._TYPE.TO, lltype.Array) and
630 self.adr.ptr._TYPE.TO._hints.get('nolength') is True and
631 ofs.TYPE is self.adr.ptr._TYPE.TO.OF):
632 itemadr = self.adr.ptr[ofs.repeat]
633 return AddressAsInt(cast_ptr_to_adr(itemadr))
634 return NotImplemented
635 def __repr__(self):
636 try:
637 return '<AddressAsInt %s>' % (self.adr.ptr,)
638 except AttributeError:
639 return '<AddressAsInt at 0x%x>' % (uid(self),)
640
641 # ____________________________________________________________
642
643 class NullAddressError(Exception):
644 pass
645
646 class DanglingPointerError(Exception):
647 pass
648
649 NULL = fakeaddress(None)
650 Address = lltype.Primitive("Address", NULL)
651
652 # GCREF is similar to Address but it is GC-aware
653 GCREF = lltype.Ptr(lltype.GcOpaqueType('GCREF'))
654
655 # A placeholder for any type that is a GcArray of pointers.
656 # This can be used in the symbolic offsets above to access such arrays
657 # in a generic way.
658 GCARRAY_OF_PTR = lltype.GcArray(GCREF, hints={'placeholder': True})
659 gcarrayofptr_lengthoffset = ArrayLengthOffset(GCARRAY_OF_PTR)
660 gcarrayofptr_itemsoffset = ArrayItemsOffset(GCARRAY_OF_PTR)
661 gcarrayofptr_singleitemoffset = ItemOffset(GCARRAY_OF_PTR.OF)
662 def array_type_match(A1, A2):
663 return A1 == A2 or (A2 == GCARRAY_OF_PTR and
664 isinstance(A1, lltype.GcArray) and
665 isinstance(A1.OF, lltype.Ptr) and
666 not A1._hints.get('nolength'))
667 def array_item_type_match(T1, T2):
668 return T1 == T2 or (T2 == GCREF and isinstance(T1, lltype.Ptr))
669
670
671 class _fakeaccessor(object):
672 def __init__(self, addr):
673 self.addr = addr
674 def __getitem__(self, index):
675 ptr = self.addr.ref()
676 if index != 0:
677 ptr = lltype.direct_ptradd(ptr, index)
678 return self.read_from_ptr(ptr)
679
680 def __setitem__(self, index, value):
681 assert lltype.typeOf(value) == self.TYPE
682 ptr = self.addr.ref()
683 if index != 0:
684 ptr = lltype.direct_ptradd(ptr, index)
685 self.write_into_ptr(ptr, value)
686
687 def read_from_ptr(self, ptr):
688 value = ptr[0]
689 assert lltype.typeOf(value) == self.TYPE
690 return value
691
692 def write_into_ptr(self, ptr, value):
693 ptr[0] = value
694
695
696 class _signed_fakeaccessor(_fakeaccessor):
697 TYPE = lltype.Signed
698
699 class _unsigned_fakeaccessor(_fakeaccessor):
700 TYPE = lltype.Unsigned
701
702 class _float_fakeaccessor(_fakeaccessor):
703 TYPE = lltype.Float
704
705 class _char_fakeaccessor(_fakeaccessor):
706 TYPE = lltype.Char
707
708 class _address_fakeaccessor(_fakeaccessor):
709 TYPE = Address
710
711 def read_from_ptr(self, ptr):
712 value = ptr[0]
713 if isinstance(value, lltype._ptr):
714 return value._cast_to_adr()
715 elif lltype.typeOf(value) == Address:
716 return value
717 else:
718 raise TypeError(value)
719
720 def write_into_ptr(self, ptr, value):
721 TARGETTYPE = lltype.typeOf(ptr).TO.OF
722 if TARGETTYPE == Address:
723 pass
724 elif isinstance(TARGETTYPE, lltype.Ptr):
725 value = cast_adr_to_ptr(value, TARGETTYPE)
726 else:
727 raise TypeError(TARGETTYPE)
728 ptr[0] = value
729
730 supported_access_types = {"signed": lltype.Signed,
731 "unsigned": lltype.Unsigned,
732 "char": lltype.Char,
733 "address": Address,
734 "float": lltype.Float,
735 }
736
737 fakeaddress.signed = property(_signed_fakeaccessor)
738 fakeaddress.unsigned = property(_unsigned_fakeaccessor)
739 fakeaddress.float = property(_float_fakeaccessor)
740 fakeaddress.char = property(_char_fakeaccessor)
741 fakeaddress.address = property(_address_fakeaccessor)
742 fakeaddress._TYPE = Address
743
744 # the obtained address will not keep the object alive. e.g. if the object is
745 # only reachable through an address, it might get collected
746 def cast_ptr_to_adr(obj):
747 assert isinstance(lltype.typeOf(obj), lltype.Ptr)
748 return obj._cast_to_adr()
749
750 @analyzer_for(cast_ptr_to_adr)
751 def ann_cast_ptr_to_adr(s):
752 from rpython.rtyper.llannotation import SomeInteriorPtr
753 assert not isinstance(s, SomeInteriorPtr)
754 return SomeAddress()
755
756
757 def cast_adr_to_ptr(adr, EXPECTED_TYPE):
758 return adr._cast_to_ptr(EXPECTED_TYPE)
759
760 @analyzer_for(cast_adr_to_ptr)
761 def ann_cast_adr_to_ptr(s, s_type):
762 assert s_type.is_constant()
763 return SomePtr(s_type.const)
764
765
766 def cast_adr_to_int(adr, mode="emulated"):
767 # The following modes are supported before translation (after
768 # translation, it's all just a cast):
769 # * mode="emulated": goes via lltype.cast_ptr_to_int(), which returns some
770 # number based on id(). The difference is that it works even if the
771 # address is that of a dead object.
772 # * mode="symbolic": returns an AddressAsInt instance, which can only be
773 # cast back to an address later.
774 # * mode="forced": uses rffi.cast() to return a real number.
775 assert mode in ("emulated", "symbolic", "forced")
776 res = adr._cast_to_int(symbolic = (mode != "emulated"))
777 if mode == "forced":
778 from rpython.rtyper.lltypesystem.rffi import cast
779 res = cast(lltype.Signed, res)
780 return res
781
782 @analyzer_for(cast_adr_to_int)
783 def ann_cast_adr_to_int(s, s_mode=None):
784 return SomeInteger() # xxx
785
786
787 _NONGCREF = lltype.Ptr(lltype.OpaqueType('NONGCREF'))
788 def cast_int_to_adr(int):
789 if isinstance(int, AddressAsInt):
790 return int.adr
791 try:
792 ptr = lltype.cast_int_to_ptr(_NONGCREF, int)
793 except ValueError:
794 from rpython.rtyper.lltypesystem import ll2ctypes
795 ptr = ll2ctypes._int2obj[int]._as_ptr()
796 return cast_ptr_to_adr(ptr)
797
798 @analyzer_for(cast_int_to_adr)
799 def ann_cast_int_to_adr(s):
800 return SomeAddress()
801
802 # ____________________________________________________________
803 # Weakrefs.
804 #
805 # An object of type WeakRef is a small GC-managed object that contains
806 # a weak reference to another GC-managed object, as in regular Python.
807 #
808
809 class _WeakRefType(lltype.ContainerType):
810 _gckind = 'gc'
811
812 def __str__(self):
813 return "WeakRef"
814
815 WeakRef = _WeakRefType()
816 WeakRefPtr = lltype.Ptr(WeakRef)
817
818 def weakref_create(ptarget):
819 # ptarget should not be a nullptr
820 PTRTYPE = lltype.typeOf(ptarget)
821 assert isinstance(PTRTYPE, lltype.Ptr)
822 assert PTRTYPE.TO._gckind == 'gc'
823 assert ptarget
824 return _wref(ptarget)._as_ptr()
825
826 @analyzer_for(weakref_create)
827 def ann_weakref_create(s_obj):
828 if (not isinstance(s_obj, SomePtr) or
829 s_obj.ll_ptrtype.TO._gckind != 'gc'):
830 raise Exception("bad type for argument to weakref_create(): %r" % (
831 s_obj,))
832 return SomePtr(WeakRefPtr)
833
834
835 def weakref_deref(PTRTYPE, pwref):
836 # pwref should not be a nullptr
837 assert isinstance(PTRTYPE, lltype.Ptr)
838 assert PTRTYPE.TO._gckind == 'gc'
839 assert lltype.typeOf(pwref) == WeakRefPtr
840 p = pwref._obj._dereference()
841 if p is None:
842 return lltype.nullptr(PTRTYPE.TO)
843 else:
844 return cast_any_ptr(PTRTYPE, p)
845
846 @analyzer_for(weakref_deref)
847 def ann_weakref_deref(s_ptrtype, s_wref):
848 if not (s_ptrtype.is_constant() and
849 isinstance(s_ptrtype.const, lltype.Ptr) and
850 s_ptrtype.const.TO._gckind == 'gc'):
851 raise Exception("weakref_deref() arg 1 must be a constant "
852 "ptr type, got %s" % (s_ptrtype,))
853 if not (isinstance(s_wref, SomePtr) and
854 s_wref.ll_ptrtype == WeakRefPtr):
855 raise Exception("weakref_deref() arg 2 must be a WeakRefPtr, "
856 "got %s" % (s_wref,))
857 return SomePtr(s_ptrtype.const)
858
859
860 class _wref(lltype._container):
861 _gckind = 'gc'
862 _TYPE = WeakRef
863
864 def __init__(self, ptarget):
865 if ptarget is None:
866 self._obref = lambda: None
867 else:
868 obj = lltype.normalizeptr(ptarget)._obj
869 self._obref = weakref.ref(obj)
870
871 def _dereference(self):
872 obj = self._obref()
873 # in combination with a GC like the SemiSpace, the 'obj' can be
874 # still alive in the CPython sense but freed by the arena logic.
875 if obj is None or obj._was_freed():
876 return None
877 else:
878 return obj._as_ptr()
879
880 def __repr__(self):
881 return '<%s>' % (self,)
882
883 def __str__(self):
884 return 'wref -> %s' % (self._obref(),)
885
886 # a prebuilt pointer to a dead low-level weakref
887 dead_wref = _wref(None)._as_ptr()
888
889 # The rest is to support the GC transformers: they can use it to build
890 # an explicit weakref object with some structure and then "hide" the
891 # result by casting it to a WeakRefPtr, and "reveal" it again. In other
892 # words, weakref_create and weakref_deref are operations that exist only
893 # before the GC transformation, whereas the two cast operations below
894 # exist only after. They are implemented here only to allow GC
895 # transformers to be tested on top of the llinterpreter.
896 def cast_ptr_to_weakrefptr(ptr):
897 if ptr:
898 return _gctransformed_wref(ptr)._as_ptr()
899 else:
900 return lltype.nullptr(WeakRef)
901
902 @analyzer_for(cast_ptr_to_weakrefptr)
903 def llcast_ptr_to_weakrefptr(s_ptr):
904 assert isinstance(s_ptr, SomePtr)
905 return SomePtr(WeakRefPtr)
906
907
908 def cast_weakrefptr_to_ptr(PTRTYPE, pwref):
909 assert lltype.typeOf(pwref) == WeakRefPtr
910 if pwref:
911 assert isinstance(pwref._obj, _gctransformed_wref)
912 if PTRTYPE is not None:
913 assert PTRTYPE == lltype.typeOf(pwref._obj._ptr)
914 return pwref._obj._ptr
915 else:
916 return lltype.nullptr(PTRTYPE.TO)
917
918 @analyzer_for(cast_weakrefptr_to_ptr)
919 def llcast_weakrefptr_to_ptr(s_ptrtype, s_wref):
920 if not (s_ptrtype.is_constant() and
921 isinstance(s_ptrtype.const, lltype.Ptr)):
922 raise Exception("cast_weakrefptr_to_ptr() arg 1 must be a constant "
923 "ptr type, got %s" % (s_ptrtype,))
924 if not (isinstance(s_wref, SomePtr) and s_wref.ll_ptrtype == WeakRefPtr):
925 raise Exception("cast_weakrefptr_to_ptr() arg 2 must be a WeakRefPtr, "
926 "got %s" % (s_wref,))
927 return SomePtr(s_ptrtype.const)
928
929
930 class _gctransformed_wref(lltype._container):
931 _gckind = 'gc'
932 _TYPE = WeakRef
933 def __init__(self, ptr):
934 self._ptr = ptr
935 def __repr__(self):
936 return '<%s>' % (self,)
937 def __str__(self):
938 return 'gctransformed_wref(%s)' % (self._ptr,)
939 def _normalizedcontainer(self, check=True):
940 return self._ptr._getobj(check=check)._normalizedcontainer(check=check)
941 def _was_freed(self):
942 return self._ptr._was_freed()
943
944 # ____________________________________________________________
945
946 def raw_malloc(size, zero=False):
947 if not isinstance(size, AddressOffset):
948 raise NotImplementedError(size)
949 return size._raw_malloc([], zero=zero)
950
951 @analyzer_for(raw_malloc)
952 def ann_raw_malloc(s_size, s_zero=None):
953 assert isinstance(s_size, SomeInteger) # XXX add noneg...?
954 assert s_zero is None or isinstance(s_zero, SomeBool)
955 return SomeAddress()
956
957
958 def raw_free(adr):
959 # try to free the whole object if 'adr' is the address of the header
960 from rpython.memory.gcheader import GCHeaderBuilder
961 try:
962 objectptr = GCHeaderBuilder.object_from_header(adr.ptr)
963 except KeyError:
964 pass
965 else:
966 raw_free(cast_ptr_to_adr(objectptr))
967 assert isinstance(adr.ref()._obj, lltype._parentable)
968 adr.ptr._as_obj()._free()
969
970 @analyzer_for(raw_free)
971 def ann_raw_free(s_addr):
972 assert isinstance(s_addr, SomeAddress)
973
974 def raw_malloc_usage(size):
975 if isinstance(size, AddressOffset):
976 # ouah
977 from rpython.memory.lltypelayout import convert_offset_to_int
978 size = convert_offset_to_int(size)
979 return size
980
981 @analyzer_for(raw_malloc_usage)
982 def ann_raw_malloc_usage(s_size):
983 assert isinstance(s_size, SomeInteger) # XXX add noneg...?
984 return SomeInteger(nonneg=True)
985
986
987 def raw_memclear(adr, size):
988 if not isinstance(size, AddressOffset):
989 raise NotImplementedError(size)
990 assert lltype.typeOf(adr) == Address
991 zeroadr = size._raw_malloc([], zero=True)
992 size.raw_memcopy(zeroadr, adr)
993
994 @analyzer_for(raw_memclear)
995 def ann_raw_memclear(s_addr, s_int):
996 assert isinstance(s_addr, SomeAddress)
997 assert isinstance(s_int, SomeInteger)
998
999
1000 def raw_memcopy(source, dest, size):
1001 assert lltype.typeOf(source) == Address
1002 assert lltype.typeOf(dest) == Address
1003 size.raw_memcopy(source, dest)
1004
1005 @analyzer_for(raw_memcopy)
1006 def ann_raw_memcopy(s_addr1, s_addr2, s_int):
1007 assert isinstance(s_addr1, SomeAddress)
1008 assert isinstance(s_addr2, SomeAddress)
1009 assert isinstance(s_int, SomeInteger) # XXX add noneg...?
1010
1011
1012 def raw_memmove(source, dest, size):
1013 # for now let's assume that raw_memmove is the same as raw_memcopy,
1014 # when run on top of fake addresses, but we _free the source object
1015 raw_memcopy(source, dest, size)
1016 source.ptr._as_obj()._free()
1017
1018 def raw_memmove_no_free(source, dest, size):
1019 # same as raw_memmove(), but we can't _free the source object when
1020 # running on top of fake addresses. This is meant to be used when
1021 # source and dest are subarrays of the same array.
1022 raw_memcopy(source, dest, size)
1023
1024 class RawMemmoveEntry(ExtRegistryEntry):
1025 _about_ = (raw_memmove, raw_memmove_no_free)
1026
1027 def compute_result_annotation(self, s_from, s_to, s_size):
1028 assert isinstance(s_from, SomeAddress)
1029 assert isinstance(s_to, SomeAddress)
1030 assert isinstance(s_size, SomeInteger)
1031
1032 def specialize_call(self, hop):
1033 hop.exception_cannot_occur()
1034 v_list = hop.inputargs(Address, Address, lltype.Signed)
1035 return hop.genop('raw_memmove', v_list)
1036
1037 def cast_any_ptr(EXPECTED_TYPE, ptr):
1038 # this is a generalization of the various cast_xxx_ptr() functions.
1039 PTRTYPE = lltype.typeOf(ptr)
1040 if PTRTYPE == EXPECTED_TYPE:
1041 return ptr
1042 elif EXPECTED_TYPE == WeakRefPtr:
1043 return cast_ptr_to_weakrefptr(ptr)
1044 elif PTRTYPE == WeakRefPtr:
1045 ptr = cast_weakrefptr_to_ptr(None, ptr)
1046 return cast_any_ptr(EXPECTED_TYPE, ptr)
1047 elif (isinstance(EXPECTED_TYPE.TO, lltype.OpaqueType) or
1048 isinstance(PTRTYPE.TO, lltype.OpaqueType)):
1049 return lltype.cast_opaque_ptr(EXPECTED_TYPE, ptr)
1050 else:
1051 # regular case
1052 return lltype.cast_pointer(EXPECTED_TYPE, ptr)
1053
1054
1055 def _reccopy_lazy(source, dest, steps):
1056 # copy recursively a structure or array onto another.
1057 # This does all the reading and then fills 'steps' with a list of callables.
1058 # Only when these callables are invoked does all the writing take place.
1059 T = lltype.typeOf(source).TO
1060 assert T == lltype.typeOf(dest).TO
1061 if isinstance(T, (lltype.Array, lltype.FixedSizeArray)):
1062 sourcelgt = source._obj.getlength()
1063 destlgt = dest._obj.getlength()
1064 lgt = min(sourcelgt, destlgt)
1065 ITEMTYPE = T.OF
1066 for i in range(lgt):
1067 if isinstance(ITEMTYPE, lltype.ContainerType):
1068 subsrc = source._obj.getitem(i)._as_ptr()
1069 subdst = dest._obj.getitem(i)._as_ptr()
1070 _reccopy_lazy(subsrc, subdst, steps)
1071 else:
1072 # this is a hack XXX de-hack this
1073 llvalue = source._obj.getitem(i, uninitialized_ok=2)
1074 if not isinstance(llvalue, lltype._uninitialized):
1075 steps.append(lambda i=i, llvalue=llvalue:
1076 dest._obj.setitem(i, llvalue))
1077 elif isinstance(T, lltype.Struct):
1078 for name in T._names:
1079 FIELDTYPE = getattr(T, name)
1080 if isinstance(FIELDTYPE, lltype.ContainerType):
1081 subsrc = source._obj._getattr(name)._as_ptr()
1082 subdst = dest._obj._getattr(name)._as_ptr()
1083 _reccopy_lazy(subsrc, subdst, steps)
1084 else:
1085 # this is a hack XXX de-hack this
1086 llvalue = source._obj._getattr(name, uninitialized_ok=True)
1087 steps.append(lambda name=name, llvalue=llvalue:
1088 setattr(dest._obj, name, llvalue))
1089 else:
1090 raise TypeError(T)
1091
1092 def _reccopy(source, dest):
1093 # copy recursively a structure or array onto another.
1094 steps = []
1095 _reccopy_lazy(source, dest, steps)
1096 for step in steps:
1097 step()