Edit File by line
/home/barbar84/www/wp-conte.../plugins/sujqvwi/AnonR/smanonr..../usr/lib64/python3..../multipro...
File: heap.py
#
[0] Fix | Delete
# Module which supports allocation of memory from an mmap
[1] Fix | Delete
#
[2] Fix | Delete
# multiprocessing/heap.py
[3] Fix | Delete
#
[4] Fix | Delete
# Copyright (c) 2006-2008, R Oudkerk
[5] Fix | Delete
# Licensed to PSF under a Contributor Agreement.
[6] Fix | Delete
#
[7] Fix | Delete
[8] Fix | Delete
import bisect
[9] Fix | Delete
from collections import defaultdict
[10] Fix | Delete
import mmap
[11] Fix | Delete
import os
[12] Fix | Delete
import sys
[13] Fix | Delete
import tempfile
[14] Fix | Delete
import threading
[15] Fix | Delete
[16] Fix | Delete
from .context import reduction, assert_spawning
[17] Fix | Delete
from . import util
[18] Fix | Delete
[19] Fix | Delete
__all__ = ['BufferWrapper']
[20] Fix | Delete
[21] Fix | Delete
#
[22] Fix | Delete
# Inheritable class which wraps an mmap, and from which blocks can be allocated
[23] Fix | Delete
#
[24] Fix | Delete
[25] Fix | Delete
if sys.platform == 'win32':
[26] Fix | Delete
[27] Fix | Delete
import _winapi
[28] Fix | Delete
[29] Fix | Delete
class Arena(object):
[30] Fix | Delete
"""
[31] Fix | Delete
A shared memory area backed by anonymous memory (Windows).
[32] Fix | Delete
"""
[33] Fix | Delete
[34] Fix | Delete
_rand = tempfile._RandomNameSequence()
[35] Fix | Delete
[36] Fix | Delete
def __init__(self, size):
[37] Fix | Delete
self.size = size
[38] Fix | Delete
for i in range(100):
[39] Fix | Delete
name = 'pym-%d-%s' % (os.getpid(), next(self._rand))
[40] Fix | Delete
buf = mmap.mmap(-1, size, tagname=name)
[41] Fix | Delete
if _winapi.GetLastError() == 0:
[42] Fix | Delete
break
[43] Fix | Delete
# We have reopened a preexisting mmap.
[44] Fix | Delete
buf.close()
[45] Fix | Delete
else:
[46] Fix | Delete
raise FileExistsError('Cannot find name for new mmap')
[47] Fix | Delete
self.name = name
[48] Fix | Delete
self.buffer = buf
[49] Fix | Delete
self._state = (self.size, self.name)
[50] Fix | Delete
[51] Fix | Delete
def __getstate__(self):
[52] Fix | Delete
assert_spawning(self)
[53] Fix | Delete
return self._state
[54] Fix | Delete
[55] Fix | Delete
def __setstate__(self, state):
[56] Fix | Delete
self.size, self.name = self._state = state
[57] Fix | Delete
# Reopen existing mmap
[58] Fix | Delete
self.buffer = mmap.mmap(-1, self.size, tagname=self.name)
[59] Fix | Delete
# XXX Temporarily preventing buildbot failures while determining
[60] Fix | Delete
# XXX the correct long-term fix. See issue 23060
[61] Fix | Delete
#assert _winapi.GetLastError() == _winapi.ERROR_ALREADY_EXISTS
[62] Fix | Delete
[63] Fix | Delete
else:
[64] Fix | Delete
[65] Fix | Delete
class Arena(object):
[66] Fix | Delete
"""
[67] Fix | Delete
A shared memory area backed by a temporary file (POSIX).
[68] Fix | Delete
"""
[69] Fix | Delete
[70] Fix | Delete
if sys.platform == 'linux':
[71] Fix | Delete
_dir_candidates = ['/dev/shm']
[72] Fix | Delete
else:
[73] Fix | Delete
_dir_candidates = []
[74] Fix | Delete
[75] Fix | Delete
def __init__(self, size, fd=-1):
[76] Fix | Delete
self.size = size
[77] Fix | Delete
self.fd = fd
[78] Fix | Delete
if fd == -1:
[79] Fix | Delete
# Arena is created anew (if fd != -1, it means we're coming
[80] Fix | Delete
# from rebuild_arena() below)
[81] Fix | Delete
self.fd, name = tempfile.mkstemp(
[82] Fix | Delete
prefix='pym-%d-'%os.getpid(),
[83] Fix | Delete
dir=self._choose_dir(size))
[84] Fix | Delete
os.unlink(name)
[85] Fix | Delete
util.Finalize(self, os.close, (self.fd,))
[86] Fix | Delete
os.ftruncate(self.fd, size)
[87] Fix | Delete
self.buffer = mmap.mmap(self.fd, self.size)
[88] Fix | Delete
[89] Fix | Delete
def _choose_dir(self, size):
[90] Fix | Delete
# Choose a non-storage backed directory if possible,
[91] Fix | Delete
# to improve performance
[92] Fix | Delete
for d in self._dir_candidates:
[93] Fix | Delete
st = os.statvfs(d)
[94] Fix | Delete
if st.f_bavail * st.f_frsize >= size: # enough free space?
[95] Fix | Delete
return d
[96] Fix | Delete
return util.get_temp_dir()
[97] Fix | Delete
[98] Fix | Delete
def reduce_arena(a):
[99] Fix | Delete
if a.fd == -1:
[100] Fix | Delete
raise ValueError('Arena is unpicklable because '
[101] Fix | Delete
'forking was enabled when it was created')
[102] Fix | Delete
return rebuild_arena, (a.size, reduction.DupFd(a.fd))
[103] Fix | Delete
[104] Fix | Delete
def rebuild_arena(size, dupfd):
[105] Fix | Delete
return Arena(size, dupfd.detach())
[106] Fix | Delete
[107] Fix | Delete
reduction.register(Arena, reduce_arena)
[108] Fix | Delete
[109] Fix | Delete
#
[110] Fix | Delete
# Class allowing allocation of chunks of memory from arenas
[111] Fix | Delete
#
[112] Fix | Delete
[113] Fix | Delete
class Heap(object):
[114] Fix | Delete
[115] Fix | Delete
# Minimum malloc() alignment
[116] Fix | Delete
_alignment = 8
[117] Fix | Delete
[118] Fix | Delete
_DISCARD_FREE_SPACE_LARGER_THAN = 4 * 1024 ** 2 # 4 MB
[119] Fix | Delete
_DOUBLE_ARENA_SIZE_UNTIL = 4 * 1024 ** 2
[120] Fix | Delete
[121] Fix | Delete
def __init__(self, size=mmap.PAGESIZE):
[122] Fix | Delete
self._lastpid = os.getpid()
[123] Fix | Delete
self._lock = threading.Lock()
[124] Fix | Delete
# Current arena allocation size
[125] Fix | Delete
self._size = size
[126] Fix | Delete
# A sorted list of available block sizes in arenas
[127] Fix | Delete
self._lengths = []
[128] Fix | Delete
[129] Fix | Delete
# Free block management:
[130] Fix | Delete
# - map each block size to a list of `(Arena, start, stop)` blocks
[131] Fix | Delete
self._len_to_seq = {}
[132] Fix | Delete
# - map `(Arena, start)` tuple to the `(Arena, start, stop)` block
[133] Fix | Delete
# starting at that offset
[134] Fix | Delete
self._start_to_block = {}
[135] Fix | Delete
# - map `(Arena, stop)` tuple to the `(Arena, start, stop)` block
[136] Fix | Delete
# ending at that offset
[137] Fix | Delete
self._stop_to_block = {}
[138] Fix | Delete
[139] Fix | Delete
# Map arenas to their `(Arena, start, stop)` blocks in use
[140] Fix | Delete
self._allocated_blocks = defaultdict(set)
[141] Fix | Delete
self._arenas = []
[142] Fix | Delete
[143] Fix | Delete
# List of pending blocks to free - see comment in free() below
[144] Fix | Delete
self._pending_free_blocks = []
[145] Fix | Delete
[146] Fix | Delete
# Statistics
[147] Fix | Delete
self._n_mallocs = 0
[148] Fix | Delete
self._n_frees = 0
[149] Fix | Delete
[150] Fix | Delete
@staticmethod
[151] Fix | Delete
def _roundup(n, alignment):
[152] Fix | Delete
# alignment must be a power of 2
[153] Fix | Delete
mask = alignment - 1
[154] Fix | Delete
return (n + mask) & ~mask
[155] Fix | Delete
[156] Fix | Delete
def _new_arena(self, size):
[157] Fix | Delete
# Create a new arena with at least the given *size*
[158] Fix | Delete
length = self._roundup(max(self._size, size), mmap.PAGESIZE)
[159] Fix | Delete
# We carve larger and larger arenas, for efficiency, until we
[160] Fix | Delete
# reach a large-ish size (roughly L3 cache-sized)
[161] Fix | Delete
if self._size < self._DOUBLE_ARENA_SIZE_UNTIL:
[162] Fix | Delete
self._size *= 2
[163] Fix | Delete
util.info('allocating a new mmap of length %d', length)
[164] Fix | Delete
arena = Arena(length)
[165] Fix | Delete
self._arenas.append(arena)
[166] Fix | Delete
return (arena, 0, length)
[167] Fix | Delete
[168] Fix | Delete
def _discard_arena(self, arena):
[169] Fix | Delete
# Possibly delete the given (unused) arena
[170] Fix | Delete
length = arena.size
[171] Fix | Delete
# Reusing an existing arena is faster than creating a new one, so
[172] Fix | Delete
# we only reclaim space if it's large enough.
[173] Fix | Delete
if length < self._DISCARD_FREE_SPACE_LARGER_THAN:
[174] Fix | Delete
return
[175] Fix | Delete
blocks = self._allocated_blocks.pop(arena)
[176] Fix | Delete
assert not blocks
[177] Fix | Delete
del self._start_to_block[(arena, 0)]
[178] Fix | Delete
del self._stop_to_block[(arena, length)]
[179] Fix | Delete
self._arenas.remove(arena)
[180] Fix | Delete
seq = self._len_to_seq[length]
[181] Fix | Delete
seq.remove((arena, 0, length))
[182] Fix | Delete
if not seq:
[183] Fix | Delete
del self._len_to_seq[length]
[184] Fix | Delete
self._lengths.remove(length)
[185] Fix | Delete
[186] Fix | Delete
def _malloc(self, size):
[187] Fix | Delete
# returns a large enough block -- it might be much larger
[188] Fix | Delete
i = bisect.bisect_left(self._lengths, size)
[189] Fix | Delete
if i == len(self._lengths):
[190] Fix | Delete
return self._new_arena(size)
[191] Fix | Delete
else:
[192] Fix | Delete
length = self._lengths[i]
[193] Fix | Delete
seq = self._len_to_seq[length]
[194] Fix | Delete
block = seq.pop()
[195] Fix | Delete
if not seq:
[196] Fix | Delete
del self._len_to_seq[length], self._lengths[i]
[197] Fix | Delete
[198] Fix | Delete
(arena, start, stop) = block
[199] Fix | Delete
del self._start_to_block[(arena, start)]
[200] Fix | Delete
del self._stop_to_block[(arena, stop)]
[201] Fix | Delete
return block
[202] Fix | Delete
[203] Fix | Delete
def _add_free_block(self, block):
[204] Fix | Delete
# make block available and try to merge with its neighbours in the arena
[205] Fix | Delete
(arena, start, stop) = block
[206] Fix | Delete
[207] Fix | Delete
try:
[208] Fix | Delete
prev_block = self._stop_to_block[(arena, start)]
[209] Fix | Delete
except KeyError:
[210] Fix | Delete
pass
[211] Fix | Delete
else:
[212] Fix | Delete
start, _ = self._absorb(prev_block)
[213] Fix | Delete
[214] Fix | Delete
try:
[215] Fix | Delete
next_block = self._start_to_block[(arena, stop)]
[216] Fix | Delete
except KeyError:
[217] Fix | Delete
pass
[218] Fix | Delete
else:
[219] Fix | Delete
_, stop = self._absorb(next_block)
[220] Fix | Delete
[221] Fix | Delete
block = (arena, start, stop)
[222] Fix | Delete
length = stop - start
[223] Fix | Delete
[224] Fix | Delete
try:
[225] Fix | Delete
self._len_to_seq[length].append(block)
[226] Fix | Delete
except KeyError:
[227] Fix | Delete
self._len_to_seq[length] = [block]
[228] Fix | Delete
bisect.insort(self._lengths, length)
[229] Fix | Delete
[230] Fix | Delete
self._start_to_block[(arena, start)] = block
[231] Fix | Delete
self._stop_to_block[(arena, stop)] = block
[232] Fix | Delete
[233] Fix | Delete
def _absorb(self, block):
[234] Fix | Delete
# deregister this block so it can be merged with a neighbour
[235] Fix | Delete
(arena, start, stop) = block
[236] Fix | Delete
del self._start_to_block[(arena, start)]
[237] Fix | Delete
del self._stop_to_block[(arena, stop)]
[238] Fix | Delete
[239] Fix | Delete
length = stop - start
[240] Fix | Delete
seq = self._len_to_seq[length]
[241] Fix | Delete
seq.remove(block)
[242] Fix | Delete
if not seq:
[243] Fix | Delete
del self._len_to_seq[length]
[244] Fix | Delete
self._lengths.remove(length)
[245] Fix | Delete
[246] Fix | Delete
return start, stop
[247] Fix | Delete
[248] Fix | Delete
def _remove_allocated_block(self, block):
[249] Fix | Delete
arena, start, stop = block
[250] Fix | Delete
blocks = self._allocated_blocks[arena]
[251] Fix | Delete
blocks.remove((start, stop))
[252] Fix | Delete
if not blocks:
[253] Fix | Delete
# Arena is entirely free, discard it from this process
[254] Fix | Delete
self._discard_arena(arena)
[255] Fix | Delete
[256] Fix | Delete
def _free_pending_blocks(self):
[257] Fix | Delete
# Free all the blocks in the pending list - called with the lock held.
[258] Fix | Delete
while True:
[259] Fix | Delete
try:
[260] Fix | Delete
block = self._pending_free_blocks.pop()
[261] Fix | Delete
except IndexError:
[262] Fix | Delete
break
[263] Fix | Delete
self._add_free_block(block)
[264] Fix | Delete
self._remove_allocated_block(block)
[265] Fix | Delete
[266] Fix | Delete
def free(self, block):
[267] Fix | Delete
# free a block returned by malloc()
[268] Fix | Delete
# Since free() can be called asynchronously by the GC, it could happen
[269] Fix | Delete
# that it's called while self._lock is held: in that case,
[270] Fix | Delete
# self._lock.acquire() would deadlock (issue #12352). To avoid that, a
[271] Fix | Delete
# trylock is used instead, and if the lock can't be acquired
[272] Fix | Delete
# immediately, the block is added to a list of blocks to be freed
[273] Fix | Delete
# synchronously sometimes later from malloc() or free(), by calling
[274] Fix | Delete
# _free_pending_blocks() (appending and retrieving from a list is not
[275] Fix | Delete
# strictly thread-safe but under CPython it's atomic thanks to the GIL).
[276] Fix | Delete
if os.getpid() != self._lastpid:
[277] Fix | Delete
raise ValueError(
[278] Fix | Delete
"My pid ({0:n}) is not last pid {1:n}".format(
[279] Fix | Delete
os.getpid(),self._lastpid))
[280] Fix | Delete
if not self._lock.acquire(False):
[281] Fix | Delete
# can't acquire the lock right now, add the block to the list of
[282] Fix | Delete
# pending blocks to free
[283] Fix | Delete
self._pending_free_blocks.append(block)
[284] Fix | Delete
else:
[285] Fix | Delete
# we hold the lock
[286] Fix | Delete
try:
[287] Fix | Delete
self._n_frees += 1
[288] Fix | Delete
self._free_pending_blocks()
[289] Fix | Delete
self._add_free_block(block)
[290] Fix | Delete
self._remove_allocated_block(block)
[291] Fix | Delete
finally:
[292] Fix | Delete
self._lock.release()
[293] Fix | Delete
[294] Fix | Delete
def malloc(self, size):
[295] Fix | Delete
# return a block of right size (possibly rounded up)
[296] Fix | Delete
if size < 0:
[297] Fix | Delete
raise ValueError("Size {0:n} out of range".format(size))
[298] Fix | Delete
if sys.maxsize <= size:
[299] Fix | Delete
raise OverflowError("Size {0:n} too large".format(size))
[300] Fix | Delete
if os.getpid() != self._lastpid:
[301] Fix | Delete
self.__init__() # reinitialize after fork
[302] Fix | Delete
with self._lock:
[303] Fix | Delete
self._n_mallocs += 1
[304] Fix | Delete
# allow pending blocks to be marked available
[305] Fix | Delete
self._free_pending_blocks()
[306] Fix | Delete
size = self._roundup(max(size, 1), self._alignment)
[307] Fix | Delete
(arena, start, stop) = self._malloc(size)
[308] Fix | Delete
real_stop = start + size
[309] Fix | Delete
if real_stop < stop:
[310] Fix | Delete
# if the returned block is larger than necessary, mark
[311] Fix | Delete
# the remainder available
[312] Fix | Delete
self._add_free_block((arena, real_stop, stop))
[313] Fix | Delete
self._allocated_blocks[arena].add((start, real_stop))
[314] Fix | Delete
return (arena, start, real_stop)
[315] Fix | Delete
[316] Fix | Delete
#
[317] Fix | Delete
# Class wrapping a block allocated out of a Heap -- can be inherited by child process
[318] Fix | Delete
#
[319] Fix | Delete
[320] Fix | Delete
class BufferWrapper(object):
[321] Fix | Delete
[322] Fix | Delete
_heap = Heap()
[323] Fix | Delete
[324] Fix | Delete
def __init__(self, size):
[325] Fix | Delete
if size < 0:
[326] Fix | Delete
raise ValueError("Size {0:n} out of range".format(size))
[327] Fix | Delete
if sys.maxsize <= size:
[328] Fix | Delete
raise OverflowError("Size {0:n} too large".format(size))
[329] Fix | Delete
block = BufferWrapper._heap.malloc(size)
[330] Fix | Delete
self._state = (block, size)
[331] Fix | Delete
util.Finalize(self, BufferWrapper._heap.free, args=(block,))
[332] Fix | Delete
[333] Fix | Delete
def create_memoryview(self):
[334] Fix | Delete
(arena, start, stop), size = self._state
[335] Fix | Delete
return memoryview(arena.buffer)[start:start+size]
[336] Fix | Delete
[337] Fix | Delete
It is recommended that you Edit text format, this type of Fix handles quite a lot in one request
Function