Debian Codegraph @

rpython/rtyper/lltypesystem/llarena.py

raw symbols SCIP
1 import array
2 from rpython.rtyper.lltypesystem import llmemory
3 from rpython.rlib.rarithmetic import is_valid_int
4 from rpython.rtyper.lltypesystem.lloperation import llop
5 import os, sys
6
7 # An "arena" is a large area of memory which can hold a number of
8 # objects, not necessarily all of the same type or size. It's used by
9 # some of our framework GCs. Addresses that point inside arenas support
10 # direct arithmetic: adding and subtracting integers, and taking the
11 # difference of two addresses. When not translated to C, the arena
12 # keeps track of which bytes are used by what object to detect GC bugs;
13 # it internally uses raw_malloc_usage() to estimate the number of bytes
14 # it needs to reserve.
15
16 class ArenaError(Exception):
17 pass
18
19 class Arena(object):
20 _count_arenas = 0
21
22 def __init__(self, nbytes, zero):
23 Arena._count_arenas += 1
24 self._arena_index = Arena._count_arenas
25 self.nbytes = nbytes
26 self.usagemap = array.array('c')
27 self.objectptrs = {} # {offset: ptr-to-container}
28 self.objectsizes = {} # {offset: size}
29 self.freed = False
30 self.protect_inaccessible = None
31 self.reset(zero)
32
33 def __repr__(self):
34 return '<Arena #%d [%d bytes]>' % (self._arena_index, self.nbytes)
35
36 def reset(self, zero, start=0, size=None):
37 self.check()
38 if size is None:
39 stop = self.nbytes
40 else:
41 stop = start + llmemory.raw_malloc_usage(size)
42 assert 0 <= start <= stop <= self.nbytes
43 for offset, ptr in self.objectptrs.items():
44 size = self.objectsizes[offset]
45 if offset < start: # object is before the cleared area
46 assert offset + size <= start, "object overlaps cleared area"
47 elif offset + size > stop: # object is after the cleared area
48 assert offset >= stop, "object overlaps cleared area"
49 else:
50 obj = ptr._obj
51 obj.__arena_location__[0] = False # no longer valid
52 del self.objectptrs[offset]
53 del self.objectsizes[offset]
54 obj._free()
55 if zero in (1, 2):
56 initialbyte = "0"
57 else:
58 initialbyte = "#"
59 self.usagemap[start:stop] = array.array('c', initialbyte*(stop-start))
60
61 def check(self):
62 if self.freed:
63 raise ArenaError("arena was already freed")
64 if self.protect_inaccessible is not None:
65 raise ArenaError("arena is currently arena_protect()ed")
66
67 def _getid(self):
68 address, length = self.usagemap.buffer_info()
69 return address
70
71 def getaddr(self, offset):
72 if not (0 <= offset <= self.nbytes):
73 raise ArenaError("Address offset is outside the arena")
74 return fakearenaaddress(self, offset)
75
76 def allocate_object(self, offset, size, letter='x'):
77 self.check()
78 bytes = llmemory.raw_malloc_usage(size)
79 if offset + bytes > self.nbytes:
80 raise ArenaError("object overflows beyond the end of the arena")
81 zero = True
82 for c in self.usagemap[offset:offset+bytes]:
83 if c == '0':
84 pass
85 elif c == '#':
86 zero = False
87 else:
88 raise ArenaError("new object overlaps a previous object")
89 assert offset not in self.objectptrs
90 addr2 = size._raw_malloc([], zero=zero)
91 pattern = letter.upper() + letter*(bytes-1)
92 self.usagemap[offset:offset+bytes] = array.array('c', pattern)
93 self.setobject(addr2, offset, bytes)
94 # common case: 'size' starts with a GCHeaderOffset. In this case
95 # we can also remember that the real object starts after the header.
96 while isinstance(size, RoundedUpForAllocation):
97 size = size.basesize
98 if (isinstance(size, llmemory.CompositeOffset) and
99 isinstance(size.offsets[0], llmemory.GCHeaderOffset)):
100 objaddr = addr2 + size.offsets[0]
101 hdrbytes = llmemory.raw_malloc_usage(size.offsets[0])
102 objoffset = offset + hdrbytes
103 self.setobject(objaddr, objoffset, bytes - hdrbytes)
104 return addr2
105
106 def setobject(self, objaddr, offset, bytes):
107 assert bytes > 0, ("llarena does not support GcStructs with no field"
108 " or empty arrays")
109 assert offset not in self.objectptrs
110 self.objectptrs[offset] = objaddr.ptr
111 self.objectsizes[offset] = bytes
112 container = objaddr.ptr._obj
113 container.__arena_location__ = [True, self, offset]
114
115 def shrink_obj(self, offset, newsize):
116 oldbytes = self.objectsizes[offset]
117 newbytes = llmemory.raw_malloc_usage(newsize)
118 assert newbytes <= oldbytes
119 # fix self.objectsizes
120 for i in range(newbytes):
121 adr = offset + i
122 if adr in self.objectsizes:
123 assert self.objectsizes[adr] == oldbytes - i
124 self.objectsizes[adr] = newbytes - i
125 # fix self.usagemap
126 for i in range(offset + newbytes, offset + oldbytes):
127 assert self.usagemap[i] == 'x'
128 self.usagemap[i] = '#'
129
130 def mark_freed(self):
131 self.freed = True # this method is a hook for tests
132
133 def set_protect(self, inaccessible):
134 if inaccessible:
135 assert self.protect_inaccessible is None
136 saved = []
137 for ptr in self.objectptrs.values():
138 obj = ptr._obj
139 saved.append((obj, obj._protect()))
140 self.protect_inaccessible = saved
141 else:
142 assert self.protect_inaccessible is not None
143 saved = self.protect_inaccessible
144 for obj, storage in saved:
145 obj._unprotect(storage)
146 self.protect_inaccessible = None
147
148 class fakearenaaddress(llmemory.fakeaddress):
149
150 def __init__(self, arena, offset):
151 self.arena = arena
152 self.offset = offset
153
154 def _getptr(self):
155 try:
156 return self.arena.objectptrs[self.offset]
157 except KeyError:
158 self.arena.check()
159 raise ArenaError("don't know yet what type of object "
160 "is at offset %d" % (self.offset,))
161 ptr = property(_getptr)
162
163 def __repr__(self):
164 return '<arenaaddr %s + %d>' % (self.arena, self.offset)
165
166 def __add__(self, other):
167 if is_valid_int(other):
168 position = self.offset + other
169 elif isinstance(other, llmemory.AddressOffset):
170 # this is really some Do What I Mean logic. There are two
171 # possible meanings: either we want to go past the current
172 # object in the arena, or we want to take the address inside
173 # the current object. Try to guess...
174 bytes = llmemory.raw_malloc_usage(other)
175 if (self.offset in self.arena.objectsizes and
176 bytes < self.arena.objectsizes[self.offset]):
177 # looks like we mean "inside the object"
178 return llmemory.fakeaddress.__add__(self, other)
179 position = self.offset + bytes
180 else:
181 return NotImplemented
182 return self.arena.getaddr(position)
183
184 def __sub__(self, other):
185 if isinstance(other, llmemory.AddressOffset):
186 other = llmemory.raw_malloc_usage(other)
187 if is_valid_int(other):
188 return self.arena.getaddr(self.offset - other)
189 if isinstance(other, fakearenaaddress):
190 if self.arena is not other.arena:
191 raise ArenaError("The two addresses are from different arenas")
192 return self.offset - other.offset
193 return NotImplemented
194
195 def __nonzero__(self):
196 return True
197
198 def compare_with_fakeaddr(self, other):
199 other = other._fixup()
200 if not other:
201 return None, None
202 obj = other.ptr._obj
203 innerobject = False
204 while not getattr(obj, '__arena_location__', (False,))[0]:
205 obj = obj._parentstructure()
206 if obj is None:
207 return None, None # not found in the arena
208 innerobject = True
209 _, arena, offset = obj.__arena_location__
210 if innerobject:
211 # 'obj' is really inside the object allocated from the arena,
212 # so it's likely that its address "should be" a bit larger than
213 # what 'offset' says.
214 # We could estimate the correct offset but it's a bit messy;
215 # instead, let's check the answer doesn't depend on it
216 if self.arena is arena:
217 objectsize = arena.objectsizes[offset]
218 if offset < self.offset < offset+objectsize:
219 raise AssertionError(
220 "comparing an inner address with a "
221 "fakearenaaddress that points in the "
222 "middle of the same object")
223 offset += objectsize // 2 # arbitrary
224 return arena, offset
225
226 def __eq__(self, other):
227 if isinstance(other, fakearenaaddress):
228 arena = other.arena
229 offset = other.offset
230 elif isinstance(other, llmemory.fakeaddress):
231 arena, offset = self.compare_with_fakeaddr(other)
232 else:
233 return llmemory.fakeaddress.__eq__(self, other)
234 return self.arena is arena and self.offset == offset
235
236 def __lt__(self, other):
237 if isinstance(other, fakearenaaddress):
238 arena = other.arena
239 offset = other.offset
240 elif isinstance(other, llmemory.fakeaddress):
241 arena, offset = self.compare_with_fakeaddr(other)
242 if arena is None:
243 return False # self < other-not-in-any-arena => False
244 # (arbitrarily)
245 else:
246 raise TypeError("comparing a %s and a %s" % (
247 self.__class__.__name__, other.__class__.__name__))
248 if self.arena is arena:
249 return self.offset < offset
250 else:
251 return self.arena._getid() < arena._getid()
252
253 def _cast_to_int(self, symbolic=False):
254 assert not symbolic
255 return rffi.cast(lltype.Signed, self.arena._getid() + self.offset)
256
257
258 def getfakearenaaddress(addr):
259 """Logic to handle test_replace_object_with_stub()."""
260 if isinstance(addr, fakearenaaddress):
261 return addr
262 else:
263 assert isinstance(addr, llmemory.fakeaddress)
264 assert addr, "NULL address"
265 # it must be possible to use the address of an already-freed
266 # arena object
267 obj = addr.ptr._getobj(check=False)
268 return _oldobj_to_address(obj)
269
270 def _oldobj_to_address(obj):
271 obj = obj._normalizedcontainer(check=False)
272 try:
273 _, arena, offset = obj.__arena_location__
274 except AttributeError:
275 if obj._was_freed():
276 msg = "taking address of %r, but it was freed"
277 else:
278 msg = "taking address of %r, but it is not in an arena"
279 raise RuntimeError(msg % (obj,))
280 return arena.getaddr(offset)
281
282 class RoundedUpForAllocation(llmemory.AddressOffset):
283 """A size that is rounded up in order to preserve alignment of objects
284 following it. For arenas containing heterogenous objects.
285 """
286 def __init__(self, basesize, minsize):
287 assert isinstance(basesize, llmemory.AddressOffset)
288 assert isinstance(minsize, llmemory.AddressOffset) or minsize == 0
289 self.basesize = basesize
290 self.minsize = minsize
291
292 def __repr__(self):
293 return '< RoundedUpForAllocation %r %r >' % (self.basesize,
294 self.minsize)
295
296 def known_nonneg(self):
297 return self.basesize.known_nonneg()
298
299 def ref(self, ptr):
300 return self.basesize.ref(ptr)
301
302 def _raw_malloc(self, rest, zero):
303 return self.basesize._raw_malloc(rest, zero=zero)
304
305 def raw_memcopy(self, srcadr, dstadr):
306 self.basesize.raw_memcopy(srcadr, dstadr)
307
308 # ____________________________________________________________
309 #
310 # Public interface: arena_malloc(), arena_free(), arena_reset()
311 # are similar to raw_malloc(), raw_free() and raw_memclear(), but
312 # work with fakearenaaddresses on which arbitrary arithmetic is
313 # possible even on top of the llinterpreter.
314
315 # arena_new_view(ptr) is a no-op when translated, returns fresh view
316 # on previous arena when run on top of llinterp
317
318 def arena_malloc(nbytes, zero):
319 """Allocate and return a new arena, optionally zero-initialized."""
320 return Arena(nbytes, zero).getaddr(0)
321
322 def arena_free(arena_addr):
323 """Release an arena."""
324 assert isinstance(arena_addr, fakearenaaddress)
325 assert arena_addr.offset == 0
326 arena_addr.arena.reset(False)
327 assert not arena_addr.arena.objectptrs
328 arena_addr.arena.mark_freed()
329
330 def arena_reset(arena_addr, size, zero):
331 """Free all objects in the arena, which can then be reused.
332 This can also be used on a subrange of the arena.
333 The value of 'zero' is:
334 * 0: don't fill the area with zeroes
335 * 1: clear, optimized for a very large area of memory
336 * 2: clear, optimized for a small or medium area of memory
337 * 3: fill with garbage
338 * 4: large area of memory that can benefit from MADV_FREE
339 (i.e. contains garbage, may be zero-filled or not)
340 """
341 arena_addr = getfakearenaaddress(arena_addr)
342 arena_addr.arena.reset(zero, arena_addr.offset, size)
343
344 def arena_reserve(addr, size, check_alignment=True):
345 """Mark some bytes in an arena as reserved, and returns addr.
346 For debugging this can check that reserved ranges of bytes don't
347 overlap. The size must be symbolic; in non-translated version
348 this is used to know what type of lltype object to allocate."""
349 from rpython.memory.lltypelayout import memory_alignment
350 addr = getfakearenaaddress(addr)
351 letter = 'x'
352 if llmemory.raw_malloc_usage(size) == 1:
353 letter = 'b' # for Byte-aligned allocations
354 elif check_alignment and (addr.offset & (memory_alignment-1)) != 0:
355 raise ArenaError("object at offset %d would not be correctly aligned"
356 % (addr.offset,))
357 addr.arena.allocate_object(addr.offset, size, letter)
358
359 def arena_shrink_obj(addr, newsize):
360 """ Mark object as shorter than it was
361 """
362 addr = getfakearenaaddress(addr)
363 addr.arena.shrink_obj(addr.offset, newsize)
364
365 def round_up_for_allocation(size, minsize=0):
366 """Round up the size in order to preserve alignment of objects
367 following an object. For arenas containing heterogenous objects.
368 If minsize is specified, it gives a minimum on the resulting size."""
369 return _round_up_for_allocation(size, minsize)
370 round_up_for_allocation._annenforceargs_ = [int, int]
371
372 def _round_up_for_allocation(size, minsize): # internal
373 return RoundedUpForAllocation(size, minsize)
374
375 def arena_new_view(ptr):
376 """Return a fresh memory view on an arena
377 """
378 return Arena(ptr.arena.nbytes, False).getaddr(0)
379
380 def arena_protect(arena_addr, size, inaccessible):
381 """For debugging, set or reset memory protection on an arena.
382 For now, the starting point and size should reference the whole arena.
383 The value of 'inaccessible' is a boolean.
384 """
385 arena_addr = getfakearenaaddress(arena_addr)
386 assert arena_addr.offset == 0
387 assert size == arena_addr.arena.nbytes
388 arena_addr.arena.set_protect(inaccessible)
389
390 # ____________________________________________________________
391 #
392 # Translation support: the functions above turn into the code below.
393 # We can tweak these implementations to be more suited to very large
394 # chunks of memory.
395
396 from rpython.rtyper.lltypesystem import rffi, lltype
397 from rpython.rtyper.extfunc import register_external
398 from rpython.rtyper.tool.rffi_platform import memory_alignment
399
400 MEMORY_ALIGNMENT = memory_alignment()
401
402 if os.name == 'posix':
403 # The general Posix solution to clear a large range of memory that
404 # was obtained with mmap() is to call mmap() again with MAP_FIXED.
405
406 legacy_getpagesize = rffi.llexternal('getpagesize', [], rffi.INT,
407 sandboxsafe=True, _nowrapper=True)
408
409 class PosixPageSize:
410 def __init__(self):
411 self.pagesize = 0
412 def _cleanup_(self):
413 self.pagesize = 0
414 def get(self):
415 pagesize = self.pagesize
416 if pagesize == 0:
417 pagesize = rffi.cast(lltype.Signed, legacy_getpagesize())
418 self.pagesize = pagesize
419 return pagesize
420
421 posixpagesize = PosixPageSize()
422
423 def clear_large_memory_chunk(baseaddr, size):
424 from rpython.rlib import rmmap
425
426 pagesize = posixpagesize.get()
427 if size > 2 * pagesize:
428 lowbits = rffi.cast(lltype.Signed, baseaddr) & (pagesize - 1)
429 if lowbits: # clear the initial misaligned part, if any
430 partpage = pagesize - lowbits
431 llmemory.raw_memclear(baseaddr, partpage)
432 baseaddr += partpage
433 size -= partpage
434 length = size & -pagesize
435 if rmmap.clear_large_memory_chunk_aligned(baseaddr, length):
436 baseaddr += length # clearing worked
437 size -= length
438
439 if size > 0: # clear the final misaligned part, if any
440 llmemory.raw_memclear(baseaddr, size)
441
442 else:
443 # XXX any better implementation on Windows?
444 # Should use VirtualAlloc() to reserve the range of pages,
445 # and commit some pages gradually with support from the GC.
446 # Or it might be enough to decommit the pages and recommit
447 # them immediately.
448 clear_large_memory_chunk = llmemory.raw_memclear
449
450 class PosixPageSize:
451 def get(self):
452 from rpython.rlib import rmmap
453 return rmmap.PAGESIZE
454 posixpagesize = PosixPageSize()
455
456 def madvise_arena_free(baseaddr, size):
457 from rpython.rlib import rmmap
458
459 pagesize = posixpagesize.get()
460 baseaddr = rffi.cast(lltype.Signed, baseaddr)
461 aligned_addr = (baseaddr + pagesize - 1) & ~(pagesize - 1)
462 size -= (aligned_addr - baseaddr)
463 if size >= pagesize:
464 rmmap.madvise_free(rffi.cast(rmmap.PTR, aligned_addr),
465 size & ~(pagesize - 1))
466
467
468 if os.name == "posix":
469 from rpython.translator.tool.cbuild import ExternalCompilationInfo
470 _eci = ExternalCompilationInfo(includes=['sys/mman.h'])
471 raw_mprotect = rffi.llexternal('mprotect',
472 [llmemory.Address, rffi.SIZE_T, rffi.INT],
473 rffi.INT,
474 sandboxsafe=True, _nowrapper=True,
475 compilation_info=_eci)
476 def llimpl_protect(addr, size, inaccessible):
477 if inaccessible:
478 prot = 0
479 else:
480 from rpython.rlib.rmmap import PROT_READ, PROT_WRITE
481 prot = PROT_READ | PROT_WRITE
482 raw_mprotect(addr, rffi.cast(rffi.SIZE_T, size),
483 rffi.cast(rffi.INT, prot))
484 # ignore potential errors
485 has_protect = True
486
487 elif os.name == 'nt':
488 def llimpl_protect(addr, size, inaccessible):
489 from rpython.rlib.rmmap import VirtualProtect, LPDWORD
490 if inaccessible:
491 from rpython.rlib.rmmap import PAGE_NOACCESS as newprotect
492 else:
493 from rpython.rlib.rmmap import PAGE_READWRITE as newprotect
494 arg = lltype.malloc(LPDWORD.TO, 1, zero=True, flavor='raw')
495 #does not release the GIL
496 VirtualProtect(rffi.cast(rffi.VOIDP, addr),
497 size, newprotect, arg)
498 # ignore potential errors
499 lltype.free(arg, flavor='raw')
500 has_protect = True
501
502 else:
503 has_protect = False
504
505
506 llimpl_malloc = rffi.llexternal('malloc', [lltype.Signed], llmemory.Address,
507 sandboxsafe=True, _nowrapper=True)
508 llimpl_calloc = rffi.llexternal('calloc', [lltype.Signed, lltype.Signed],
509 llmemory.Address,
510 sandboxsafe=True, _nowrapper=True)
511 llimpl_free = rffi.llexternal('free', [llmemory.Address], lltype.Void,
512 sandboxsafe=True, _nowrapper=True)
513
514 def llimpl_arena_malloc(nbytes, zero):
515 if zero:
516 addr = llimpl_calloc(nbytes, 1)
517 else:
518 addr = llimpl_malloc(nbytes)
519 return addr
520 llimpl_arena_malloc._always_inline_ = True
521 register_external(arena_malloc, [int, int], llmemory.Address,
522 'll_arena.arena_malloc',
523 llimpl=llimpl_arena_malloc,
524 llfakeimpl=arena_malloc,
525 sandboxsafe=True)
526
527 register_external(arena_free, [llmemory.Address], None, 'll_arena.arena_free',
528 llimpl=llimpl_free,
529 llfakeimpl=arena_free,
530 sandboxsafe=True)
531
532 def llimpl_arena_reset(arena_addr, size, zero):
533 if zero:
534 if zero == 1:
535 clear_large_memory_chunk(arena_addr, size)
536 elif zero == 3:
537 llop.raw_memset(lltype.Void, arena_addr, ord('#'), size)
538 elif zero == 4:
539 madvise_arena_free(arena_addr, size)
540 else:
541 llmemory.raw_memclear(arena_addr, size)
542 llimpl_arena_reset._always_inline_ = True
543 register_external(arena_reset, [llmemory.Address, int, int], None,
544 'll_arena.arena_reset',
545 llimpl=llimpl_arena_reset,
546 llfakeimpl=arena_reset,
547 sandboxsafe=True)
548
549 def llimpl_arena_reserve(addr, size):
550 pass
551 register_external(arena_reserve, [llmemory.Address, int], None,
552 'll_arena.arena_reserve',
553 llimpl=llimpl_arena_reserve,
554 llfakeimpl=arena_reserve,
555 sandboxsafe=True)
556
557 def llimpl_arena_shrink_obj(addr, newsize):
558 pass
559 register_external(arena_shrink_obj, [llmemory.Address, int], None,
560 'll_arena.arena_shrink_obj',
561 llimpl=llimpl_arena_shrink_obj,
562 llfakeimpl=arena_shrink_obj,
563 sandboxsafe=True)
564
565 def llimpl_round_up_for_allocation(size, minsize):
566 return (max(size, minsize) + (MEMORY_ALIGNMENT-1)) & ~(MEMORY_ALIGNMENT-1)
567 register_external(_round_up_for_allocation, [int, int], int,
568 'll_arena.round_up_for_allocation',
569 llimpl=llimpl_round_up_for_allocation,
570 llfakeimpl=round_up_for_allocation,
571 sandboxsafe=True)
572
573 def llimpl_arena_new_view(addr):
574 return addr
575 register_external(arena_new_view, [llmemory.Address], llmemory.Address,
576 'll_arena.arena_new_view', llimpl=llimpl_arena_new_view,
577 llfakeimpl=arena_new_view, sandboxsafe=True)
578
579 def llimpl_arena_protect(addr, size, inaccessible):
580 if has_protect:
581 # do some alignment
582 start = rffi.cast(lltype.Signed, addr)
583 end = start + size
584 start = (start + 4095) & ~ 4095
585 end = end & ~ 4095
586 if end > start:
587 llimpl_protect(rffi.cast(llmemory.Address, start), end-start,
588 inaccessible)
589 register_external(arena_protect, [llmemory.Address, lltype.Signed,
590 lltype.Bool], lltype.Void,
591 'll_arena.arena_protect', llimpl=llimpl_arena_protect,
592 llfakeimpl=arena_protect, sandboxsafe=True)
593
594 def llimpl_getfakearenaaddress(addr):
595 return addr
596 register_external(getfakearenaaddress, [llmemory.Address], llmemory.Address,
597 'll_arena.getfakearenaaddress',
598 llimpl=llimpl_getfakearenaaddress,
599 llfakeimpl=getfakearenaaddress,
600 sandboxsafe=True)