Debian Codegraph @

rpython/rlib/rgc.py

raw symbols SCIP
1 from __future__ import absolute_import
2
3 import gc
4 import types
5
6 from rpython.rlib import jit
7 from rpython.rlib.objectmodel import we_are_translated, enforceargs, specialize
8 from rpython.rlib.objectmodel import CDefinedIntSymbolic, not_rpython
9 from rpython.rtyper.extregistry import ExtRegistryEntry
10 from rpython.rtyper.lltypesystem import lltype, llmemory
11
12 # ____________________________________________________________
13 # General GC features
14
15 collect = gc.collect
16 enable = gc.enable
17 disable = gc.disable
18 isenabled = gc.isenabled
19
20 def collect_step():
21 """
22 If the GC is incremental, run a single gc-collect-step.
23
24 Return an integer which encodes the starting and ending GC state. Use
25 rgc.{old_state,new_state,is_done} to decode it.
26
27 If the GC is not incremental, do a full collection and return a value on
28 which rgc.is_done() return True.
29 """
30 gc.collect()
31 return _encode_states(1, 0)
32
33 def _encode_states(oldstate, newstate):
34 return oldstate << 8 | newstate
35
36 def old_state(states):
37 return (states & 0xFF00) >> 8
38
39 def new_state(states):
40 return states & 0xFF
41
42 def is_done(states):
43 """
44 Return True if the return value of collect_step signals the end of a major
45 collection
46 """
47 old = old_state(states)
48 new = new_state(states)
49 return is_done__states(old, new)
50
51 def is_done__states(oldstate, newstate):
52 "Like is_done, but takes oldstate and newstate explicitly"
53 # a collection is considered done when it ends up in the starting state
54 # (which is usually represented as 0). This logic works for incminimark,
55 # which is currently the only gc actually used and for which collect_step
56 # is implemented. In case we add more GC in the future, we might want to
57 # delegate this logic to the GC itself, but for now it is MUCH simpler to
58 # just write it in plain RPython.
59 return oldstate != 0 and newstate == 0
60
61 def set_max_heap_size(nbytes):
62 """Limit the heap size to n bytes.
63 """
64 pass
65
66 def must_split_gc_address_space():
67 """Returns True if we have a "split GC address space", i.e. if
68 we are translating with an option that doesn't support taking raw
69 addresses inside GC objects and "hacking" at them. This is
70 notably the case with --revdb."""
71 return False
72
73 # for test purposes we allow objects to be pinned and use
74 # the following list to keep track of the pinned objects
75 _pinned_objects = []
76
77 def pin(obj):
78 """If 'obj' can move, then attempt to temporarily fix it. This
79 function returns True if and only if 'obj' could be pinned; this is
80 a special state in the GC. Note that can_move(obj) still returns
81 True even on pinned objects, because once unpinned it will indeed be
82 able to move again. In other words, the code that succeeded in
83 pinning 'obj' can assume that it won't move until the corresponding
84 call to unpin(obj), despite can_move(obj) still being True. (This
85 is important if multiple threads try to os.write() the same string:
86 only one of them will succeed in pinning the string.)
87
88 It is expected that the time between pinning and unpinning an object
89 is short. Therefore the expected use case is a single function
90 invoking pin(obj) and unpin(obj) only a few lines of code apart.
91
92 Note that this can return False for any reason, e.g. if the 'obj' is
93 already non-movable or already pinned, if the GC doesn't support
94 pinning, or if there are too many pinned objects.
95
96 Note further that pinning an object does not prevent it from being
97 collected if it is not used anymore.
98 """
99 _pinned_objects.append(obj)
100 return True
101
102
103 class PinEntry(ExtRegistryEntry):
104 _about_ = pin
105
106 def compute_result_annotation(self, s_obj):
107 from rpython.annotator import model as annmodel
108 return annmodel.SomeBool()
109
110 def specialize_call(self, hop):
111 hop.exception_cannot_occur()
112 return hop.genop('gc_pin', hop.args_v, resulttype=hop.r_result)
113
114 def unpin(obj):
115 """Unpin 'obj', allowing it to move again.
116 Must only be called after a call to pin(obj) returned True.
117 """
118 for i in range(len(_pinned_objects)):
119 try:
120 if _pinned_objects[i] == obj:
121 del _pinned_objects[i]
122 return
123 except TypeError:
124 pass
125
126
127 class UnpinEntry(ExtRegistryEntry):
128 _about_ = unpin
129
130 def compute_result_annotation(self, s_obj):
131 pass
132
133 def specialize_call(self, hop):
134 hop.exception_cannot_occur()
135 hop.genop('gc_unpin', hop.args_v)
136
137 def _is_pinned(obj):
138 """Method to check if 'obj' is pinned."""
139 for i in range(len(_pinned_objects)):
140 try:
141 if _pinned_objects[i] == obj:
142 return True
143 except TypeError:
144 pass
145 return False
146
147
148 class IsPinnedEntry(ExtRegistryEntry):
149 _about_ = _is_pinned
150
151 def compute_result_annotation(self, s_obj):
152 from rpython.annotator import model as annmodel
153 return annmodel.SomeBool()
154
155 def specialize_call(self, hop):
156 hop.exception_cannot_occur()
157 return hop.genop('gc__is_pinned', hop.args_v, resulttype=hop.r_result)
158
159 # ____________________________________________________________
160 # Annotation and specialization
161
162 # Support for collection.
163
164 class CollectEntry(ExtRegistryEntry):
165 _about_ = gc.collect
166
167 def compute_result_annotation(self, s_gen=None):
168 from rpython.annotator import model as annmodel
169 return annmodel.s_None
170
171 def specialize_call(self, hop):
172 hop.exception_cannot_occur()
173 args_v = []
174 if len(hop.args_s) == 1:
175 args_v = hop.inputargs(lltype.Signed)
176 return hop.genop('gc__collect', args_v, resulttype=hop.r_result)
177
178
179 class EnableDisableEntry(ExtRegistryEntry):
180 _about_ = (gc.enable, gc.disable)
181
182 def compute_result_annotation(self):
183 from rpython.annotator import model as annmodel
184 return annmodel.s_None
185
186 def specialize_call(self, hop):
187 hop.exception_cannot_occur()
188 opname = self.instance.__name__
189 return hop.genop('gc__%s' % opname, hop.args_v, resulttype=hop.r_result)
190
191
192 class IsEnabledEntry(ExtRegistryEntry):
193 _about_ = gc.isenabled
194
195 def compute_result_annotation(self):
196 from rpython.annotator import model as annmodel
197 return annmodel.s_Bool
198
199 def specialize_call(self, hop):
200 hop.exception_cannot_occur()
201 return hop.genop('gc__isenabled', hop.args_v, resulttype=hop.r_result)
202
203
204 class CollectStepEntry(ExtRegistryEntry):
205 _about_ = collect_step
206
207 def compute_result_annotation(self):
208 from rpython.annotator import model as annmodel
209 return annmodel.SomeInteger()
210
211 def specialize_call(self, hop):
212 hop.exception_cannot_occur()
213 return hop.genop('gc__collect_step', hop.args_v, resulttype=hop.r_result)
214
215
216 class SetMaxHeapSizeEntry(ExtRegistryEntry):
217 _about_ = set_max_heap_size
218
219 def compute_result_annotation(self, s_nbytes):
220 from rpython.annotator import model as annmodel
221 return annmodel.s_None
222
223 def specialize_call(self, hop):
224 [v_nbytes] = hop.inputargs(lltype.Signed)
225 hop.exception_cannot_occur()
226 return hop.genop('gc_set_max_heap_size', [v_nbytes],
227 resulttype=lltype.Void)
228
229 def can_move(p):
230 """Check if the GC object 'p' is at an address that can move.
231 Must not be called with None. With non-moving GCs, it is always False.
232 With some moving GCs like the SemiSpace GC, it is always True.
233 With other moving GCs like the MiniMark GC, it can be True for some
234 time, then False for the same object, when we are sure that it won't
235 move any more.
236 """
237 return True
238
239 class SplitAddrSpaceEntry(ExtRegistryEntry):
240 _about_ = must_split_gc_address_space
241
242 def compute_result_annotation(self):
243 config = self.bookkeeper.annotator.translator.config
244 result = config.translation.split_gc_address_space
245 return self.bookkeeper.immutablevalue(result)
246
247 def specialize_call(self, hop):
248 hop.exception_cannot_occur()
249 return hop.inputconst(lltype.Bool, hop.s_result.const)
250
251 class CanMoveEntry(ExtRegistryEntry):
252 _about_ = can_move
253
254 def compute_result_annotation(self, s_p):
255 from rpython.annotator import model as annmodel
256 return annmodel.SomeBool()
257
258 def specialize_call(self, hop):
259 hop.exception_cannot_occur()
260 return hop.genop('gc_can_move', hop.args_v, resulttype=hop.r_result)
261
262 def _make_sure_does_not_move(p):
263 """'p' is a non-null GC object. This (tries to) make sure that the
264 object does not move any more, by forcing collections if needed.
265 Warning: should ideally only be used with the minimark GC, and only
266 on objects that are already a bit old, so have a chance to be
267 already non-movable."""
268 assert p
269 if not we_are_translated():
270 # for testing purpose
271 return not _is_pinned(p)
272 #
273 if _is_pinned(p):
274 # although a pinned object can't move we must return 'False'. A pinned
275 # object can be unpinned any time and becomes movable.
276 return False
277 i = -1
278 while can_move(p):
279 if i > 6:
280 raise NotImplementedError("can't make object non-movable!")
281 collect(i)
282 i += 1
283 return True
284
285 def needs_write_barrier(obj):
286 """ We need to emit write barrier if the right hand of assignment
287 is in nursery, used by the JIT for handling set*_gc(Const)
288 """
289 if not obj:
290 return False
291 # XXX returning can_move() here might acidentally work for the use
292 # cases (see issue #2212), but this is not really safe. Now we
293 # just return True for any non-NULL pointer, and too bad for the
294 # few extra 'cond_call_gc_wb'. It could be improved e.g. to return
295 # False if 'obj' is a static prebuilt constant, or if we're not
296 # running incminimark...
297 return True #can_move(obj)
298
299 def _heap_stats():
300 raise NotImplementedError # can't be run directly
301
302 class DumpHeapEntry(ExtRegistryEntry):
303 _about_ = _heap_stats
304
305 def compute_result_annotation(self):
306 from rpython.rtyper.llannotation import SomePtr
307 from rpython.memory.gc.base import ARRAY_TYPEID_MAP
308 return SomePtr(lltype.Ptr(ARRAY_TYPEID_MAP))
309
310 def specialize_call(self, hop):
311 hop.exception_is_here()
312 return hop.genop('gc_heap_stats', [], resulttype=hop.r_result)
313
314
315 def copy_struct_item(source, dest, si, di):
316 TP = lltype.typeOf(source).TO.OF
317 i = 0
318 while i < len(TP._names):
319 setattr(dest[di], TP._names[i], getattr(source[si], TP._names[i]))
320 i += 1
321
322 class CopyStructEntry(ExtRegistryEntry):
323 _about_ = copy_struct_item
324
325 def compute_result_annotation(self, s_source, s_dest, si, di):
326 pass
327
328 def specialize_call(self, hop):
329 v_source, v_dest, v_si, v_di = hop.inputargs(hop.args_r[0],
330 hop.args_r[1],
331 lltype.Signed,
332 lltype.Signed)
333 hop.exception_cannot_occur()
334 TP = v_source.concretetype.TO.OF
335 for name, TP in TP._flds.iteritems():
336 c_name = hop.inputconst(lltype.Void, name)
337 v_fld = hop.genop('getinteriorfield', [v_source, v_si, c_name],
338 resulttype=TP)
339 hop.genop('setinteriorfield', [v_dest, v_di, c_name, v_fld])
340
341
342 @specialize.ll()
343 def copy_item(source, dest, si, di):
344 TP = lltype.typeOf(source)
345 if isinstance(TP.TO.OF, lltype.Struct):
346 copy_struct_item(source, dest, si, di)
347 else:
348 dest[di] = source[si]
349
350 @specialize.memo()
351 def _contains_gcptr(TP):
352 if not isinstance(TP, lltype.Struct):
353 if isinstance(TP, lltype.Ptr) and TP.TO._gckind == 'gc':
354 return True
355 return False
356 for TP in TP._flds.itervalues():
357 if _contains_gcptr(TP):
358 return True
359 return False
360
361
362 @jit.oopspec('list.ll_arraycopy(source, dest, source_start, dest_start, length)')
363 @enforceargs(None, None, int, int, int)
364 @specialize.ll()
365 def ll_arraycopy(source, dest, source_start, dest_start, length):
366 from rpython.rtyper.lltypesystem.lloperation import llop
367 from rpython.rlib.objectmodel import keepalive_until_here
368
369 # XXX: Hack to ensure that we get a proper effectinfo.write_descrs_arrays
370 # and also, maybe, speed up very small cases
371 if length <= 1:
372 if length == 1:
373 copy_item(source, dest, source_start, dest_start)
374 return
375
376 # supports non-overlapping copies only
377 if not we_are_translated():
378 if source == dest:
379 assert (source_start + length <= dest_start or
380 dest_start + length <= source_start)
381
382 TP = lltype.typeOf(source).TO
383 assert TP == lltype.typeOf(dest).TO
384
385 slowpath = False
386 if must_split_gc_address_space():
387 slowpath = True
388 elif _contains_gcptr(TP.OF):
389 # perform a write barrier that copies necessary flags from
390 # source to dest
391 if not llop.gc_writebarrier_before_copy(lltype.Bool, source, dest,
392 source_start, dest_start,
393 length):
394 slowpath = True
395 if slowpath:
396 # if the write barrier is not supported, or if we translate with
397 # the option 'split_gc_address_space', then copy by hand
398 i = 0
399 while i < length:
400 copy_item(source, dest, i + source_start, i + dest_start)
401 i += 1
402 return
403 source_addr = llmemory.cast_ptr_to_adr(source)
404 dest_addr = llmemory.cast_ptr_to_adr(dest)
405 cp_source_addr = (source_addr + llmemory.itemoffsetof(TP, 0) +
406 llmemory.sizeof(TP.OF) * source_start)
407 cp_dest_addr = (dest_addr + llmemory.itemoffsetof(TP, 0) +
408 llmemory.sizeof(TP.OF) * dest_start)
409
410 llmemory.raw_memcopy(cp_source_addr, cp_dest_addr,
411 llmemory.sizeof(TP.OF) * length)
412 keepalive_until_here(source)
413 keepalive_until_here(dest)
414
415 @jit.oopspec('list.ll_arraymove(array, source_start, dest_start, length)')
416 @enforceargs(None, int, int, int)
417 @specialize.ll()
418 def ll_arraymove(array, source_start, dest_start, length):
419 from rpython.rtyper.lltypesystem.lloperation import llop
420 from rpython.rlib.objectmodel import keepalive_until_here
421
422 # XXX: Hack to ensure that we get a proper effectinfo.write_descrs_arrays
423 # and also, maybe, speed up very small cases
424 if length <= 1:
425 if length == 1:
426 copy_item(array, array, source_start, dest_start)
427 return
428
429 TP = lltype.typeOf(array).TO
430
431 slowpath = False
432 if must_split_gc_address_space():
433 slowpath = True
434 elif _contains_gcptr(TP.OF):
435 # if the array has card marks set, then this will perform a
436 # general (card-less) write barrier on it, because the marked cards
437 # are no longer necessarily the right ones after the move.
438 # Otherwise, if the GC doesn't support cards, this is a no-op,
439 # because we're not writing any new GC pointer into the array:
440 # we're just moving existing ones around.
441 llop.gc_writebarrier_before_move(lltype.Void, array)
442 if slowpath:
443 # if we translate with the option 'split_gc_address_space',
444 # then move by hand
445 delta = dest_start - source_start
446 if delta < 0:
447 i = source_start
448 stop = source_start + length
449 while i < stop:
450 copy_item(array, array, i, i + delta)
451 i += 1
452 elif delta > 0:
453 i = source_start + length
454 while i > source_start:
455 i -= 1
456 copy_item(array, array, i, i + delta)
457 return
458 array_addr = llmemory.cast_ptr_to_adr(array)
459 mv_source_addr = (array_addr + llmemory.itemoffsetof(TP, 0) +
460 llmemory.sizeof(TP.OF) * source_start)
461 mv_dest_addr = (array_addr + llmemory.itemoffsetof(TP, 0) +
462 llmemory.sizeof(TP.OF) * dest_start)
463
464 llmemory.raw_memmove_no_free(mv_source_addr, mv_dest_addr,
465 llmemory.sizeof(TP.OF) * length)
466 keepalive_until_here(array)
467
468 @jit.oopspec('rgc.ll_shrink_array(p, smallerlength)')
469 @enforceargs(None, int)
470 @specialize.ll()
471 def ll_shrink_array(p, smallerlength):
472 from rpython.rtyper.lltypesystem.lloperation import llop
473 from rpython.rlib.objectmodel import keepalive_until_here
474
475 if llop.shrink_array(lltype.Bool, p, smallerlength):
476 return p # done by the GC
477 # XXX we assume for now that the type of p is GcStruct containing a
478 # variable array, with no further pointers anywhere, and exactly one
479 # field in the fixed part -- like STR and UNICODE.
480
481 TP = lltype.typeOf(p).TO
482 newp = lltype.malloc(TP, smallerlength)
483
484 assert len(TP._names) == 2
485 field = getattr(p, TP._names[0])
486 setattr(newp, TP._names[0], field)
487
488 if must_split_gc_address_space():
489 # do the copying element by element
490 i = 0
491 while i < smallerlength:
492 newp.chars[i] = p.chars[i]
493 i += 1
494 return newp
495
496 ARRAY = getattr(TP, TP._arrayfld)
497 offset = (llmemory.offsetof(TP, TP._arrayfld) +
498 llmemory.itemoffsetof(ARRAY, 0))
499 source_addr = llmemory.cast_ptr_to_adr(p) + offset
500 dest_addr = llmemory.cast_ptr_to_adr(newp) + offset
501 llmemory.raw_memcopy(source_addr, dest_addr,
502 llmemory.sizeof(ARRAY.OF) * smallerlength)
503
504 keepalive_until_here(p)
505 keepalive_until_here(newp)
506 return newp
507
508 @jit.dont_look_inside
509 @specialize.ll()
510 def ll_arrayclear(p):
511 # Equivalent to memset(array, 0). Only for GcArray(primitive-type) for now.
512 from rpython.rlib.objectmodel import keepalive_until_here
513
514 length = len(p)
515 ARRAY = lltype.typeOf(p).TO
516 if must_split_gc_address_space():
517 # do the clearing element by element
518 from rpython.rtyper.lltypesystem import rffi
519 ZERO = rffi.cast(ARRAY.OF, 0)
520 i = 0
521 while i < length:
522 p[i] = ZERO
523 i += 1
524 else:
525 offset = llmemory.itemoffsetof(ARRAY, 0)
526 dest_addr = llmemory.cast_ptr_to_adr(p) + offset
527 llmemory.raw_memclear(dest_addr, llmemory.sizeof(ARRAY.OF) * length)
528 keepalive_until_here(p)
529
530
531 def no_release_gil(func):
532 func._dont_inline_ = True
533 func._no_release_gil_ = True
534 return func
535
536 def no_collect(func):
537 func._dont_inline_ = True
538 func._gc_no_collect_ = True
539 return func
540
541 def must_be_light_finalizer(func):
542 """Mark a __del__ method as being a destructor, calling only a limited
543 set of operations. See pypy/doc/discussion/finalizer-order.rst.
544
545 If you use the same decorator on a class, this class and all its
546 subclasses are only allowed to have __del__ methods which are
547 similarly decorated (or no __del__ at all). It prevents a class
548 hierarchy from having destructors in some parent classes, which are
549 overridden in subclasses with (non-light, old-style) finalizers.
550 (This case is the original motivation for FinalizerQueue.)
551 """
552 func._must_be_light_finalizer_ = True
553 return func
554
555
556 class FinalizerQueue(object):
557 """A finalizer queue. See pypy/doc/discussion/finalizer-order.rst.
558 """
559 # Must be subclassed, and the subclass needs these attributes:
560 #
561 # Class:
562 # the class (or base class) of finalized objects
563 # --or-- None to handle low-level GCREFs directly
564 #
565 # def finalizer_trigger(self):
566 # called to notify that new items have been put in the queue
567
568 def _freeze_(self):
569 return True
570
571 @specialize.arg(0)
572 @jit.dont_look_inside
573 def next_dead(self):
574 if we_are_translated():
575 from rpython.rtyper.lltypesystem.lloperation import llop
576 from rpython.rtyper.lltypesystem.llmemory import GCREF
577 from rpython.rtyper.annlowlevel import cast_gcref_to_instance
578 tag = FinalizerQueue._get_tag(self)
579 ptr = llop.gc_fq_next_dead(GCREF, tag)
580 if self.Class is not None:
581 ptr = cast_gcref_to_instance(self.Class, ptr)
582 return ptr
583 try:
584 return self._queue.popleft()
585 except (AttributeError, IndexError):
586 return None
587
588 @specialize.arg(0)
589 @jit.dont_look_inside
590 def register_finalizer(self, obj):
591 from rpython.rtyper.lltypesystem.llmemory import GCREF
592 if self.Class is None:
593 assert lltype.typeOf(obj) == GCREF
594 else:
595 assert isinstance(obj, self.Class)
596 if we_are_translated():
597 from rpython.rtyper.lltypesystem.lloperation import llop
598 from rpython.rtyper.annlowlevel import cast_instance_to_gcref
599 tag = FinalizerQueue._get_tag(self)
600 if self.Class is not None:
601 obj = cast_instance_to_gcref(obj)
602 llop.gc_fq_register(lltype.Void, tag, obj)
603 return
604 else:
605 self._untranslated_register_finalizer(obj)
606
607 @not_rpython
608 def _get_tag(self):
609 "special-cased below"
610
611 def _reset(self):
612 import collections
613 self._weakrefs = set()
614 self._queue = collections.deque()
615
616 def _already_registered(self, obj):
617 return hasattr(obj, '__enable_del_for_id')
618
619 def _untranslated_register_finalizer(self, obj):
620 assert not self._already_registered(obj)
621
622 if not hasattr(self, '_queue'):
623 self._reset()
624
625 # Fetch and check the type of 'obj'
626 objtyp = obj.__class__
627 assert isinstance(objtyp, type), (
628 "%r: to run register_finalizer() untranslated, "
629 "the object's class must be new-style" % (obj,))
630 assert hasattr(obj, '__dict__'), (
631 "%r: to run register_finalizer() untranslated, "
632 "the object must have a __dict__" % (obj,))
633 assert (not hasattr(obj, '__slots__') or
634 type(obj).__slots__ == () or
635 type(obj).__slots__ == ('__weakref__',)), (
636 "%r: to run register_finalizer() untranslated, "
637 "the object must not have __slots__" % (obj,))
638
639 # The first time, patch the method __del__ of the class, if
640 # any, so that we can disable it on the original 'obj' and
641 # enable it only on the 'newobj'
642 _fq_patch_class(objtyp)
643
644 # Build a new shadow object with the same class and dict
645 newobj = object.__new__(objtyp)
646 obj.__dict__ = obj.__dict__.copy() #PyPy: break the dict->obj dependency
647 newobj.__dict__ = obj.__dict__
648
649 # A callback that is invoked when (or after) 'obj' is deleted;
650 # 'newobj' is still kept alive here
651 def callback(wr):
652 self._weakrefs.discard(wr)
653 self._queue.append(newobj)
654 self.finalizer_trigger()
655
656 import weakref
657 wr = weakref.ref(obj, callback)
658 self._weakrefs.add(wr)
659
660 # Disable __del__ on the original 'obj' and enable it only on
661 # the 'newobj'. Use id() and not a regular reference, because
662 # that would make a cycle between 'newobj' and 'obj.__dict__'
663 # (which is 'newobj.__dict__' too).
664 setattr(obj, '__enable_del_for_id', id(newobj))
665
666
667 def _fq_patch_class(Cls):
668 if Cls in _fq_patched_classes:
669 return
670 if '__del__' in Cls.__dict__:
671 def __del__(self):
672 if not we_are_translated():
673 try:
674 if getattr(self, '__enable_del_for_id') != id(self):
675 return
676 except AttributeError:
677 pass
678 original_del(self)
679 original_del = Cls.__del__
680 Cls.__del__ = __del__
681 _fq_patched_classes.add(Cls)
682 for BaseCls in Cls.__bases__:
683 _fq_patch_class(BaseCls)
684
685 _fq_patched_classes = set()
686
687 class FqTagEntry(ExtRegistryEntry):
688 _about_ = FinalizerQueue._get_tag.im_func
689
690 def compute_result_annotation(self, s_fq):
691 assert s_fq.is_constant()
692 fq = s_fq.const
693 s_func = self.bookkeeper.immutablevalue(fq.finalizer_trigger)
694 self.bookkeeper.emulate_pbc_call(self.bookkeeper.position_key,
695 s_func, [])
696 if not hasattr(fq, '_fq_tag'):
697 fq._fq_tag = CDefinedIntSymbolic(
698 '0 /*FinalizerQueue TAG for %s*/' % fq.__class__.__name__,
699 default=fq)
700 return self.bookkeeper.immutablevalue(fq._fq_tag)
701
702 def specialize_call(self, hop):
703 from rpython.rtyper.rclass import InstanceRepr
704 translator = hop.rtyper.annotator.translator
705 fq = hop.args_s[0].const
706 graph = translator._graphof(fq.finalizer_trigger.im_func)
707 InstanceRepr.check_graph_of_del_does_not_call_too_much(hop.rtyper,
708 graph)
709 hop.exception_cannot_occur()
710 return hop.inputconst(lltype.Signed, hop.s_result.const)
711
712 @jit.dont_look_inside
713 @specialize.argtype(0)
714 def may_ignore_finalizer(obj):
715 """Optimization hint: says that it is valid for any finalizer
716 for 'obj' to be ignored, depending on the GC."""
717 from rpython.rtyper.lltypesystem.lloperation import llop
718 llop.gc_ignore_finalizer(lltype.Void, obj)
719
720 @jit.dont_look_inside
721 def move_out_of_nursery(obj):
722 """ Returns another object which is a copy of obj; but at any point
723 (either now or in the future) the returned object might suddenly
724 become identical to the one returned.
725
726 NOTE: Only use for immutable objects!
727
728 NOTE: Might fail on some GCs! You have to check again
729 can_move() afterwards. It should always work with the default
730 GC. With Boehm, can_move() is always False so
731 move_out_of_nursery() should never be called in the first place.
732 """
733 return obj
734
735 class MoveOutOfNurseryEntry(ExtRegistryEntry):
736 _about_ = move_out_of_nursery
737
738 def compute_result_annotation(self, s_obj):
739 return s_obj
740
741 def specialize_call(self, hop):
742 hop.exception_cannot_occur()
743 return hop.genop('gc_move_out_of_nursery', hop.args_v, resulttype=hop.r_result)
744
745 @jit.dont_look_inside
746 def increase_root_stack_depth(new_depth):
747 """Shadowstack: make sure the size of the shadowstack is at least
748 'new_depth' pointers."""
749 from rpython.rtyper.lltypesystem.lloperation import llop
750 llop.gc_increase_root_stack_depth(lltype.Void, new_depth)
751
752 # ____________________________________________________________
753
754
755 @not_rpython
756 def get_rpy_roots():
757 # Return the 'roots' from the GC.
758 # The gc typically returns a list that ends with a few NULL_GCREFs.
759 return [_GcRef(x) for x in gc.get_objects()]
760
761 @not_rpython
762 def get_rpy_referents(gcref):
763 x = gcref._x
764 if isinstance(x, list):
765 d = x
766 elif isinstance(x, dict):
767 d = x.keys() + x.values()
768 else:
769 d = []
770 if hasattr(x, '__dict__'):
771 d = x.__dict__.values()
772 if hasattr(type(x), '__slots__'):
773 for slot in type(x).__slots__:
774 try:
775 d.append(getattr(x, slot))
776 except AttributeError:
777 pass
778 # discard objects that are too random or that are _freeze_=True
779 return [_GcRef(x) for x in d if _keep_object(x)]
780
781 def _keep_object(x):
782 if isinstance(x, type) or type(x) is types.ClassType:
783 return False # don't keep any type
784 if isinstance(x, (list, dict, str)):
785 return True # keep lists and dicts and strings
786 if hasattr(x, '_freeze_'):
787 return False
788 return type(x).__module__ != '__builtin__' # keep non-builtins
789
790 def add_memory_pressure(estimate, object=None):
791 """Add memory pressure for OpaquePtrs."""
792 pass
793
794 class AddMemoryPressureEntry(ExtRegistryEntry):
795 _about_ = add_memory_pressure
796
797 def compute_result_annotation(self, s_nbytes, s_object=None):
798 from rpython.annotator import model as annmodel
799 if s_object is not None:
800 if not isinstance(s_object, annmodel.SomeInstance):
801 raise Exception("Wrong kind of object passed to "
802 "add memory pressure")
803 self.bookkeeper.memory_pressure_types.add(s_object.classdef)
804 return annmodel.s_None
805
806 def specialize_call(self, hop):
807 v_size = hop.inputarg(lltype.Signed, 0)
808 if len(hop.args_v) == 2:
809 v_obj = hop.inputarg(hop.args_r[1], 1)
810 args = [v_size, v_obj]
811 else:
812 args = [v_size]
813 hop.exception_cannot_occur()
814 return hop.genop('gc_add_memory_pressure', args,
815 resulttype=lltype.Void)
816
817
818 @not_rpython
819 def get_rpy_memory_usage(gcref):
820 # approximate implementation using CPython's type info
821 Class = type(gcref._x)
822 size = Class.__basicsize__
823 if Class.__itemsize__ > 0:
824 size += Class.__itemsize__ * len(gcref._x)
825 return size
826
827 @not_rpython
828 def get_rpy_type_index(gcref):
829 from rpython.rlib.rarithmetic import intmask
830 Class = gcref._x.__class__
831 i = intmask(id(Class))
832 if i < 0:
833 i = ~i # always return a positive number, at least
834 return i
835
836 def cast_gcref_to_int(gcref):
837 # This is meant to be used on cast_instance_to_gcref results.
838 # Don't use this on regular gcrefs obtained e.g. with
839 # lltype.cast_opaque_ptr().
840 if we_are_translated():
841 return lltype.cast_ptr_to_int(gcref)
842 else:
843 return id(gcref._x)
844
845 (TOTAL_MEMORY, TOTAL_ALLOCATED_MEMORY, TOTAL_MEMORY_PRESSURE,
846 PEAK_MEMORY, PEAK_ALLOCATED_MEMORY, TOTAL_ARENA_MEMORY,
847 TOTAL_RAWMALLOCED_MEMORY, PEAK_ARENA_MEMORY, PEAK_RAWMALLOCED_MEMORY,
848 NURSERY_SIZE, TOTAL_GC_TIME) = range(11)
849
850 @not_rpython
851 def get_stats(stat_no):
852 """ Long docstring goes here
853 """
854 raise NotImplementedError
855
856 @not_rpython
857 def dump_rpy_heap(fd):
858 raise NotImplementedError
859
860 @not_rpython
861 def get_typeids_z():
862 raise NotImplementedError
863
864 @not_rpython
865 def get_typeids_list():
866 raise NotImplementedError
867
868 @not_rpython
869 def has_gcflag_extra():
870 return True
871 has_gcflag_extra._subopnum = 1
872
873 _gcflag_extras = set()
874
875 @not_rpython
876 def get_gcflag_extra(gcref):
877 assert gcref # not NULL!
878 return gcref in _gcflag_extras
879 get_gcflag_extra._subopnum = 2
880
881 @not_rpython
882 def toggle_gcflag_extra(gcref):
883 assert gcref # not NULL!
884 try:
885 _gcflag_extras.remove(gcref)
886 except KeyError:
887 _gcflag_extras.add(gcref)
888 toggle_gcflag_extra._subopnum = 3
889
890 @not_rpython
891 def get_gcflag_dummy(gcref):
892 return False
893 get_gcflag_dummy._subopnum = 4
894
895 def assert_no_more_gcflags():
896 if not we_are_translated():
897 assert not _gcflag_extras
898
899 ARRAY_OF_CHAR = lltype.Array(lltype.Char)
900 NULL_GCREF = lltype.nullptr(llmemory.GCREF.TO)
901
902 class _GcRef(object):
903 # implementation-specific: there should not be any after translation
904 __slots__ = ['_x', '_handle']
905 _TYPE = llmemory.GCREF
906 def __init__(self, x):
907 self._x = x
908 def __hash__(self):
909 return object.__hash__(self._x)
910 def __eq__(self, other):
911 if isinstance(other, lltype._ptr):
912 assert other == NULL_GCREF, (
913 "comparing a _GcRef with a non-NULL lltype ptr")
914 return False
915 assert isinstance(other, _GcRef)
916 return self._x is other._x
917 def __ne__(self, other):
918 return not self.__eq__(other)
919 def __repr__(self):
920 return "_GcRef(%r)" % (self._x, )
921 def _freeze_(self):
922 raise Exception("instances of rlib.rgc._GcRef cannot be translated")
923
924 def cast_instance_to_gcref(x):
925 # Before translation, casts an RPython instance into a _GcRef.
926 # After translation, it is a variant of cast_object_to_ptr(GCREF).
927 if we_are_translated():
928 from rpython.rtyper import annlowlevel
929 x = annlowlevel.cast_instance_to_base_ptr(x)
930 return lltype.cast_opaque_ptr(llmemory.GCREF, x)
931 else:
932 return _GcRef(x)
933 cast_instance_to_gcref._annspecialcase_ = 'specialize:argtype(0)'
934
935 def try_cast_gcref_to_instance(Class, gcref):
936 # Before translation, unwraps the RPython instance contained in a _GcRef.
937 # After translation, it is a type-check performed by the GC.
938 if we_are_translated():
939 from rpython.rtyper.rclass import OBJECTPTR, ll_isinstance
940 from rpython.rtyper.annlowlevel import cast_base_ptr_to_instance
941 if _is_rpy_instance(gcref):
942 objptr = lltype.cast_opaque_ptr(OBJECTPTR, gcref)
943 if objptr.typeptr: # may be NULL, e.g. in rdict's dummykeyobj
944 clsptr = _get_llcls_from_cls(Class)
945 if ll_isinstance(objptr, clsptr):
946 return cast_base_ptr_to_instance(Class, objptr)
947 return None
948 else:
949 if isinstance(gcref._x, Class):
950 return gcref._x
951 return None
952 try_cast_gcref_to_instance._annspecialcase_ = 'specialize:arg(0)'
953
954 _ffi_cache = None
955 def _fetch_ffi():
956 global _ffi_cache
957 if _ffi_cache is None:
958 try:
959 import _cffi_backend
960 _ffi_cache = _cffi_backend.FFI()
961 except (ImportError, AttributeError):
962 import py
963 py.test.skip("need CFFI >= 1.0")
964 return _ffi_cache
965
966 @jit.dont_look_inside
967 def hide_nonmovable_gcref(gcref):
968 from rpython.rtyper.lltypesystem import lltype, llmemory, rffi
969 if we_are_translated():
970 assert lltype.typeOf(gcref) == llmemory.GCREF
971 assert not can_move(gcref)
972 return rffi.cast(llmemory.Address, gcref)
973 else:
974 assert isinstance(gcref, _GcRef)
975 x = gcref._x
976 ffi = _fetch_ffi()
977 if not hasattr(x, '__handle'):
978 x.__handle = ffi.new_handle(x)
979 addr = int(ffi.cast("intptr_t", x.__handle))
980 return rffi.cast(llmemory.Address, addr)
981
982 @jit.dont_look_inside
983 def reveal_gcref(addr):
984 from rpython.rtyper.lltypesystem import lltype, llmemory, rffi
985 assert lltype.typeOf(addr) == llmemory.Address
986 if we_are_translated():
987 return rffi.cast(llmemory.GCREF, addr)
988 else:
989 addr = rffi.cast(lltype.Signed, addr)
990 if addr == 0:
991 return lltype.nullptr(llmemory.GCREF.TO)
992 ffi = _fetch_ffi()
993 x = ffi.from_handle(ffi.cast("void *", addr))
994 return _GcRef(x)
995
996 # ------------------- implementation -------------------
997
998 _cache_s_list_of_gcrefs = None
999
1000 def s_list_of_gcrefs():
1001 global _cache_s_list_of_gcrefs
1002 if _cache_s_list_of_gcrefs is None:
1003 from rpython.annotator import model as annmodel
1004 from rpython.rtyper.llannotation import SomePtr
1005 from rpython.annotator.listdef import ListDef
1006 s_gcref = SomePtr(llmemory.GCREF)
1007 _cache_s_list_of_gcrefs = annmodel.SomeList(
1008 ListDef(None, s_gcref, mutated=True, resized=False))
1009 return _cache_s_list_of_gcrefs
1010
1011 class Entry(ExtRegistryEntry):
1012 _about_ = get_rpy_roots
1013 def compute_result_annotation(self):
1014 return s_list_of_gcrefs()
1015 def specialize_call(self, hop):
1016 hop.exception_cannot_occur()
1017 return hop.genop('gc_get_rpy_roots', [], resulttype = hop.r_result)
1018
1019 class Entry(ExtRegistryEntry):
1020 _about_ = get_rpy_referents
1021
1022 def compute_result_annotation(self, s_gcref):
1023 from rpython.rtyper.llannotation import SomePtr
1024 assert SomePtr(llmemory.GCREF).contains(s_gcref)
1025 return s_list_of_gcrefs()
1026
1027 def specialize_call(self, hop):
1028 vlist = hop.inputargs(hop.args_r[0])
1029 hop.exception_cannot_occur()
1030 return hop.genop('gc_get_rpy_referents', vlist,
1031 resulttype=hop.r_result)
1032
1033 class Entry(ExtRegistryEntry):
1034 _about_ = get_rpy_memory_usage
1035 def compute_result_annotation(self, s_gcref):
1036 from rpython.annotator import model as annmodel
1037 return annmodel.SomeInteger()
1038 def specialize_call(self, hop):
1039 vlist = hop.inputargs(hop.args_r[0])
1040 hop.exception_cannot_occur()
1041 return hop.genop('gc_get_rpy_memory_usage', vlist,
1042 resulttype = hop.r_result)
1043
1044 class Entry(ExtRegistryEntry):
1045 _about_ = get_rpy_type_index
1046 def compute_result_annotation(self, s_gcref):
1047 from rpython.annotator import model as annmodel
1048 return annmodel.SomeInteger()
1049 def specialize_call(self, hop):
1050 vlist = hop.inputargs(hop.args_r[0])
1051 hop.exception_cannot_occur()
1052 return hop.genop('gc_get_rpy_type_index', vlist,
1053 resulttype = hop.r_result)
1054
1055 class Entry(ExtRegistryEntry):
1056 _about_ = get_stats
1057 def compute_result_annotation(self, s_no):
1058 from rpython.annotator.model import SomeInteger
1059 if not isinstance(s_no, SomeInteger):
1060 raise Exception("expecting an integer")
1061 return SomeInteger()
1062 def specialize_call(self, hop):
1063 args = hop.inputargs(lltype.Signed)
1064 hop.exception_cannot_occur()
1065 return hop.genop('gc_get_stats', args, resulttype=lltype.Signed)
1066
1067 @not_rpython
1068 def _is_rpy_instance(gcref):
1069 raise NotImplementedError
1070
1071 @not_rpython
1072 def _get_llcls_from_cls(Class):
1073 raise NotImplementedError
1074
1075 class Entry(ExtRegistryEntry):
1076 _about_ = _is_rpy_instance
1077 def compute_result_annotation(self, s_gcref):
1078 from rpython.annotator import model as annmodel
1079 return annmodel.SomeBool()
1080 def specialize_call(self, hop):
1081 vlist = hop.inputargs(hop.args_r[0])
1082 hop.exception_cannot_occur()
1083 return hop.genop('gc_is_rpy_instance', vlist,
1084 resulttype = hop.r_result)
1085
1086 class Entry(ExtRegistryEntry):
1087 _about_ = _get_llcls_from_cls
1088 def compute_result_annotation(self, s_Class):
1089 from rpython.rtyper.llannotation import SomePtr
1090 from rpython.rtyper.rclass import CLASSTYPE
1091 assert s_Class.is_constant()
1092 return SomePtr(CLASSTYPE)
1093
1094 def specialize_call(self, hop):
1095 from rpython.rtyper.rclass import getclassrepr, CLASSTYPE
1096 from rpython.flowspace.model import Constant
1097 Class = hop.args_s[0].const
1098 classdef = hop.rtyper.annotator.bookkeeper.getuniqueclassdef(Class)
1099 classrepr = getclassrepr(hop.rtyper, classdef)
1100 vtable = classrepr.getvtable()
1101 assert lltype.typeOf(vtable) == CLASSTYPE
1102 hop.exception_cannot_occur()
1103 return Constant(vtable, concretetype=CLASSTYPE)
1104
1105 class Entry(ExtRegistryEntry):
1106 _about_ = dump_rpy_heap
1107 def compute_result_annotation(self, s_fd):
1108 from rpython.annotator.model import s_Bool
1109 return s_Bool
1110 def specialize_call(self, hop):
1111 vlist = hop.inputargs(lltype.Signed)
1112 hop.exception_is_here()
1113 return hop.genop('gc_dump_rpy_heap', vlist, resulttype = hop.r_result)
1114
1115 class Entry(ExtRegistryEntry):
1116 _about_ = get_typeids_z
1117
1118 def compute_result_annotation(self):
1119 from rpython.rtyper.llannotation import SomePtr
1120 return SomePtr(lltype.Ptr(ARRAY_OF_CHAR))
1121
1122 def specialize_call(self, hop):
1123 hop.exception_is_here()
1124 return hop.genop('gc_typeids_z', [], resulttype = hop.r_result)
1125
1126 class Entry(ExtRegistryEntry):
1127 _about_ = get_typeids_list
1128
1129 def compute_result_annotation(self):
1130 from rpython.rtyper.llannotation import SomePtr
1131 from rpython.rtyper.lltypesystem import llgroup
1132 return SomePtr(lltype.Ptr(lltype.Array(llgroup.HALFWORD)))
1133
1134 def specialize_call(self, hop):
1135 hop.exception_is_here()
1136 return hop.genop('gc_typeids_list', [], resulttype = hop.r_result)
1137
1138 class Entry(ExtRegistryEntry):
1139 _about_ = (has_gcflag_extra, get_gcflag_extra, toggle_gcflag_extra,
1140 get_gcflag_dummy)
1141 def compute_result_annotation(self, s_arg=None):
1142 from rpython.annotator.model import s_Bool
1143 return s_Bool
1144 def specialize_call(self, hop):
1145 subopnum = self.instance._subopnum
1146 vlist = [hop.inputconst(lltype.Signed, subopnum)]
1147 vlist += hop.inputargs(*hop.args_r)
1148 hop.exception_cannot_occur()
1149 return hop.genop('gc_gcflag_extra', vlist, resulttype = hop.r_result)
1150
1151 def lltype_is_gc(TP):
1152 return getattr(getattr(TP, "TO", None), "_gckind", "?") == 'gc'
1153
1154 def register_custom_trace_hook(TP, lambda_func):
1155 """ This function does not do anything, but called from any annotated
1156 place, will tell that "func" is used to trace GC roots inside any instance
1157 of the type TP. The func must be specified as "lambda: func" in this
1158 call, for internal reasons. Note that the func will be automatically
1159 specialized on the 'callback' argument value. Example:
1160
1161 def customtrace(gc, obj, callback, arg1, arg2):
1162 gc._trace_callback(callback, arg1, arg2, obj + offset_of_x)
1163 lambda_customtrace = lambda: customtrace
1164 """
1165
1166 @specialize.ll()
1167 def ll_writebarrier(gc_obj):
1168 """Use together with custom tracers. When you update some object pointer
1169 stored in raw memory, you must call this function on 'gc_obj', which must
1170 be the object of type TP with the custom tracer (*not* the value stored!).
1171 This makes sure that the custom hook will be called again."""
1172 from rpython.rtyper.lltypesystem.lloperation import llop
1173 llop.gc_writebarrier(lltype.Void, gc_obj)
1174
1175 class RegisterGcTraceEntry(ExtRegistryEntry):
1176 _about_ = register_custom_trace_hook
1177
1178 def compute_result_annotation(self, s_tp, s_lambda_func):
1179 pass
1180
1181 def specialize_call(self, hop):
1182 TP = hop.args_s[0].const
1183 lambda_func = hop.args_s[1].const
1184 hop.exception_cannot_occur()
1185 hop.rtyper.custom_trace_funcs.append((TP, lambda_func()))
1186
1187 def register_custom_light_finalizer(TP, lambda_func):
1188 """ This function does not do anything, but called from any annotated
1189 place, will tell that "func" is used as a lightweight finalizer for TP.
1190 The func must be specified as "lambda: func" in this call, for internal
1191 reasons.
1192 """
1193
1194 @specialize.arg(0)
1195 def do_get_objects(callback):
1196 """ Get all the objects that satisfy callback(gcref) -> obj
1197 """
1198 roots = get_rpy_roots()
1199 if not roots: # is always None on translations using Boehm or None GCs
1200 return []
1201 roots = [gcref for gcref in roots if gcref]
1202 result_w = []
1203 #
1204 if not we_are_translated(): # fast path before translation
1205 seen = set()
1206 while roots:
1207 gcref = roots.pop()
1208 if gcref not in seen:
1209 seen.add(gcref)
1210 w_obj = callback(gcref)
1211 if w_obj is not None:
1212 result_w.append(w_obj)
1213 roots.extend(get_rpy_referents(gcref))
1214 return result_w
1215 #
1216 pending = roots[:]
1217 while pending:
1218 gcref = pending.pop()
1219 if not get_gcflag_extra(gcref):
1220 toggle_gcflag_extra(gcref)
1221 w_obj = callback(gcref)
1222 if w_obj is not None:
1223 result_w.append(w_obj)
1224 pending.extend(get_rpy_referents(gcref))
1225 clear_gcflag_extra(roots)
1226 assert_no_more_gcflags()
1227 return result_w
1228
1229 class RegisterCustomLightFinalizer(ExtRegistryEntry):
1230 _about_ = register_custom_light_finalizer
1231
1232 def compute_result_annotation(self, s_tp, s_lambda_func):
1233 pass
1234
1235 def specialize_call(self, hop):
1236 from rpython.rtyper.llannotation import SomePtr
1237 TP = hop.args_s[0].const
1238 lambda_func = hop.args_s[1].const
1239 ll_func = lambda_func()
1240 args_s = [SomePtr(lltype.Ptr(TP))]
1241 funcptr = hop.rtyper.annotate_helper_fn(ll_func, args_s)
1242 hop.exception_cannot_occur()
1243 lltype.attachRuntimeTypeInfo(TP, destrptr=funcptr)
1244
1245 def clear_gcflag_extra(fromlist):
1246 pending = fromlist[:]
1247 while pending:
1248 gcref = pending.pop()
1249 if get_gcflag_extra(gcref):
1250 toggle_gcflag_extra(gcref)
1251 pending.extend(get_rpy_referents(gcref))
1252
1253 all_typeids = {}
1254
1255 def get_typeid(obj):
1256 raise Exception("does not work untranslated")
1257
1258 class GetTypeidEntry(ExtRegistryEntry):
1259 _about_ = get_typeid
1260
1261 def compute_result_annotation(self, s_obj):
1262 from rpython.annotator import model as annmodel
1263 return annmodel.SomeInteger()
1264
1265 def specialize_call(self, hop):
1266 hop.exception_cannot_occur()
1267 return hop.genop('gc_gettypeid', hop.args_v, resulttype=lltype.Signed)
1268
1269 # ____________________________________________________________
1270
1271
1272 class _rawptr_missing_item(object):
1273 pass
1274 _rawptr_missing_item = _rawptr_missing_item()
1275
1276
1277 class _ResizableListSupportingRawPtr(list):
1278 """Calling this class is a no-op after translation.
1279
1280 Before translation, it returns a new instance of
1281 _ResizableListSupportingRawPtr, on which
1282 rgc.nonmoving_raw_ptr_for_resizable_list() might be
1283 used if needed. For now, only supports lists of chars.
1284 """
1285 __slots__ = ('_ll_list',) # either None or a struct of TYPE=LIST_OF(Char)
1286
1287 def __init__(self, lst):
1288 self._ll_list = None
1289 self.__from_list(lst)
1290
1291 def __resize(self):
1292 """Called before an operation changes the size of the list"""
1293 if self._ll_list is not None:
1294 list.__init__(self, self.__as_list())
1295 self._ll_list = None
1296
1297 def __from_list(self, lst):
1298 """Initialize the list from a copy of the list 'lst'."""
1299 assert isinstance(lst, list)
1300 for x in lst:
1301 assert isinstance(x, str) and len(x) == 1
1302 if self is lst:
1303 return
1304 if len(self) != len(lst):
1305 self.__resize()
1306 if self._ll_list is None:
1307 list.__init__(self, lst)
1308 else:
1309 assert len(self) == self._ll_list.length == len(lst)
1310 for i in range(len(self)):
1311 self._ll_list.items[i] = lst[i]
1312
1313 def __as_list(self):
1314 """Return a list (the same or a different one) which contains the
1315 items in the regular way."""
1316 if self._ll_list is None:
1317 return self
1318 length = self._ll_list.length
1319 assert length == len(self)
1320 return [self._ll_list.items[i] for i in range(length)]
1321
1322 def __getitem__(self, index):
1323 if self._ll_list is None:
1324 return list.__getitem__(self, index)
1325 if index < 0:
1326 index += len(self)
1327 if not (0 <= index < len(self)):
1328 raise IndexError
1329 return self._ll_list.items[index]
1330
1331 def __setitem__(self, index, new):
1332 if self._ll_list is None:
1333 return list.__setitem__(self, index, new)
1334 if index < 0:
1335 index += len(self)
1336 if not (0 <= index < len(self)):
1337 raise IndexError
1338 self._ll_list.items[index] = new
1339
1340 def __delitem__(self, index):
1341 self.__resize()
1342 list.__delitem__(self, index)
1343
1344 def __getslice__(self, i, j):
1345 return self.__class__(list.__getslice__(self.__as_list(), i, j))
1346
1347 def __setslice__(self, i, j, new):
1348 lst = self.__as_list()
1349 list.__setslice__(lst, i, j, new)
1350 self.__from_list(lst)
1351
1352 def __delslice__(self, i, j):
1353 lst = self.__as_list()
1354 list.__delslice__(lst, i, j)
1355 self.__from_list(lst)
1356
1357 def __iter__(self):
1358 try:
1359 i = 0
1360 while True:
1361 yield self[i]
1362 i += 1
1363 except IndexError:
1364 pass
1365
1366 def __reversed__(self):
1367 i = len(self)
1368 while i > 0:
1369 i -= 1
1370 yield self[i]
1371
1372 def __contains__(self, item):
1373 return list.__contains__(self.__as_list(), item)
1374
1375 def __add__(self, other):
1376 if isinstance(other, _ResizableListSupportingRawPtr):
1377 other = other.__as_list()
1378 return list.__add__(self.__as_list(), other)
1379
1380 def __radd__(self, other):
1381 if isinstance(other, _ResizableListSupportingRawPtr):
1382 other = other.__as_list()
1383 return list.__add__(other, self.__as_list())
1384
1385 def __iadd__(self, other):
1386 self.__resize()
1387 return list.__iadd__(self, other)
1388
1389 def __eq__(self, other):
1390 return list.__eq__(self.__as_list(), other)
1391 def __ne__(self, other):
1392 return list.__ne__(self.__as_list(), other)
1393 def __ge__(self, other):
1394 return list.__ge__(self.__as_list(), other)
1395 def __gt__(self, other):
1396 return list.__gt__(self.__as_list(), other)
1397 def __le__(self, other):
1398 return list.__le__(self.__as_list(), other)
1399 def __lt__(self, other):
1400 return list.__lt__(self.__as_list(), other)
1401
1402 def __mul__(self, other):
1403 return list.__mul__(self.__as_list(), other)
1404
1405 def __rmul__(self, other):
1406 return list.__mul__(self.__as_list(), other)
1407
1408 def __imul__(self, other):
1409 self.__resize()
1410 return list.__imul__(self, other)
1411
1412 def __repr__(self):
1413 return '_ResizableListSupportingRawPtr(%s)' % (
1414 list.__repr__(self.__as_list()),)
1415
1416 def append(self, object):
1417 self.__resize()
1418 return list.append(self, object)
1419
1420 def count(self, value):
1421 return list.count(self.__as_list(), value)
1422
1423 def extend(self, iterable):
1424 self.__resize()
1425 return list.extend(self, iterable)
1426
1427 def index(self, value, *start_stop):
1428 return list.index(self.__as_list(), value, *start_stop)
1429
1430 def insert(self, index, object):
1431 self.__resize()
1432 return list.insert(self, index, object)
1433
1434 def pop(self, *opt_index):
1435 self.__resize()
1436 return list.pop(self, *opt_index)
1437
1438 def remove(self, value):
1439 self.__resize()
1440 return list.remove(self, value)
1441
1442 def reverse(self):
1443 lst = self.__as_list()
1444 list.reverse(lst)
1445 self.__from_list(lst)
1446
1447 def sort(self, *args, **kwds):
1448 lst = self.__as_list()
1449 list.sort(lst, *args, **kwds)
1450 self.__from_list(lst)
1451
1452 def _get_ll_list(self):
1453 from rpython.rtyper.lltypesystem import rffi
1454 from rpython.rtyper.lltypesystem.rlist import LIST_OF
1455 if self._ll_list is None:
1456 LIST = LIST_OF(lltype.Char)
1457 existing_items = list(self)
1458 n = len(self)
1459 self._ll_list = lltype.malloc(LIST, immortal=True)
1460 self._ll_list.length = n
1461 self._ll_list.items = lltype.malloc(LIST.items.TO, n)
1462 self.__from_list(existing_items)
1463 assert self._ll_list is not None
1464 return self._ll_list
1465
1466 def _nonmoving_raw_ptr_for_resizable_list(self):
1467 ll_list = self._get_ll_list()
1468 return ll_nonmovable_raw_ptr_for_resizable_list(ll_list)
1469
1470 def resizable_list_supporting_raw_ptr(lst):
1471 return _ResizableListSupportingRawPtr(lst)
1472
1473 def nonmoving_raw_ptr_for_resizable_list(lst):
1474 if must_split_gc_address_space():
1475 raise ValueError
1476 return _nonmoving_raw_ptr_for_resizable_list(lst)
1477
1478 def _nonmoving_raw_ptr_for_resizable_list(lst):
1479 assert isinstance(lst, _ResizableListSupportingRawPtr)
1480 return lst._nonmoving_raw_ptr_for_resizable_list()
1481
1482 def ll_for_resizable_list(lst):
1483 """
1484 This is the equivalent of llstr(), but for lists. It can be called only if
1485 the list has been created by calling resizable_list_supporting_raw_ptr().
1486
1487 In theory, all the operations on lst are immediately visible also on
1488 ll_list. However, support for that is incomplete in
1489 _ResizableListSupportingRawPtr and as such, the pointer becomes invalid as
1490 soon as you call a resizing operation on lst.
1491 """
1492 assert isinstance(lst, _ResizableListSupportingRawPtr)
1493 return lst._get_ll_list()
1494
1495 def _check_resizable_list_of_chars(s_list):
1496 from rpython.annotator import model as annmodel
1497 from rpython.rlib import debug
1498 if annmodel.s_None.contains(s_list):
1499 return # "None", will likely be generalized later
1500 if not isinstance(s_list, annmodel.SomeList):
1501 raise Exception("not a list, got %r" % (s_list,))
1502 if not isinstance(s_list.listdef.listitem.s_value,
1503 (annmodel.SomeChar, annmodel.SomeImpossibleValue)):
1504 raise debug.NotAListOfChars
1505 s_list.listdef.resize() # must be resizable
1506
1507 class Entry(ExtRegistryEntry):
1508 _about_ = resizable_list_supporting_raw_ptr
1509
1510 def compute_result_annotation(self, s_list):
1511 _check_resizable_list_of_chars(s_list)
1512 return s_list
1513
1514 def specialize_call(self, hop):
1515 from rpython.rtyper.lltypesystem.rlist import LIST_OF
1516 if hop.args_r[0].LIST != LIST_OF(lltype.Char):
1517 raise ValueError('Resizable list of chars does not have the '
1518 'expected low-level type')
1519 hop.exception_cannot_occur()
1520 return hop.inputarg(hop.args_r[0], 0)
1521
1522 class Entry(ExtRegistryEntry):
1523 _about_ = _nonmoving_raw_ptr_for_resizable_list
1524
1525 def compute_result_annotation(self, s_list):
1526 from rpython.rtyper.lltypesystem import lltype, rffi
1527 from rpython.rtyper.llannotation import SomePtr
1528 _check_resizable_list_of_chars(s_list)
1529 return SomePtr(rffi.CCHARP)
1530
1531 def specialize_call(self, hop):
1532 v_list = hop.inputarg(hop.args_r[0], 0)
1533 hop.exception_cannot_occur() # ignoring MemoryError
1534 return hop.gendirectcall(ll_nonmovable_raw_ptr_for_resizable_list,
1535 v_list)
1536
1537 class Entry(ExtRegistryEntry):
1538 _about_ = ll_for_resizable_list
1539
1540 def compute_result_annotation(self, s_list):
1541 from rpython.rtyper.lltypesystem.rlist import LIST_OF
1542 from rpython.rtyper.llannotation import lltype_to_annotation
1543 _check_resizable_list_of_chars(s_list)
1544 LIST = LIST_OF(lltype.Char)
1545 return lltype_to_annotation(lltype.Ptr(LIST))
1546
1547 def specialize_call(self, hop):
1548 hop.exception_cannot_occur()
1549 assert hop.args_r[0].lowleveltype == hop.r_result.lowleveltype
1550 v_ll_list, = hop.inputargs(*hop.args_r)
1551 return hop.genop('same_as', [v_ll_list],
1552 resulttype = hop.r_result.lowleveltype)
1553
1554
1555 @jit.dont_look_inside
1556 def ll_nonmovable_raw_ptr_for_resizable_list(ll_list):
1557 """
1558 WARNING: dragons ahead.
1559 Return the address of the internal char* buffer of 'll_list', which
1560 must be a resizable list of chars.
1561
1562 This makes sure that the list items are non-moving, if necessary by
1563 first copying the GcArray inside 'll_list.items' outside the GC
1564 nursery. The returned 'char *' pointer is guaranteed to be valid
1565 until one of these occurs:
1566
1567 * 'll_list' gets garbage-collected; or
1568 * you do an operation on 'll_list' that changes its size.
1569 """
1570 from rpython.rtyper.lltypesystem import lltype, rffi
1571 array = ll_list.items
1572 if can_move(array):
1573 length = ll_list.length
1574 new_array = lltype.malloc(lltype.typeOf(ll_list).TO.items.TO, length,
1575 nonmovable=True)
1576 ll_arraycopy(array, new_array, 0, 0, length)
1577 ll_list.items = new_array
1578 array = new_array
1579 ptr = lltype.direct_arrayitems(array)
1580 # ptr is a Ptr(FixedSizeArray(Char, 1)). Cast it to a rffi.CCHARP
1581 return rffi.cast(rffi.CCHARP, ptr)
1582
1583 @jit.dont_look_inside
1584 @no_collect
1585 @specialize.ll()
1586 def ll_write_final_null_char(s):
1587 """'s' is a low-level STR; writes a terminating NULL character after
1588 the other characters in 's'. Warning, this only works because of
1589 the 'extra_item_after_alloc' hack inside the definition of STR.
1590 """
1591 from rpython.rtyper.lltypesystem import rffi
1592 PSTR = lltype.typeOf(s)
1593 assert has_final_null_char(PSTR) == 1
1594 n = llmemory.offsetof(PSTR.TO, 'chars')
1595 n += llmemory.itemoffsetof(PSTR.TO.chars, 0)
1596 n = llmemory.raw_malloc_usage(n)
1597 n += len(s.chars)
1598 # no GC operation from here!
1599 ptr = rffi.cast(rffi.CCHARP, s)
1600 ptr[n] = '\x00'
1601
1602 @specialize.memo()
1603 def has_final_null_char(PSTR):
1604 return PSTR.TO.chars._hints.get('extra_item_after_alloc', 0)