| 1 | #include "Python.h" |
| 2 | |
| 3 | #if defined(__has_feature) /* Clang */ |
| 4 | #if __has_feature(address_sanitizer) /* is ASAN enabled? */ |
| 5 | #define ATTRIBUTE_NO_ADDRESS_SAFETY_ANALYSIS \ |
| 6 | __attribute__((no_address_safety_analysis)) \ |
| 7 | __attribute__ ((noinline)) |
| 8 | #else |
| 9 | #define ATTRIBUTE_NO_ADDRESS_SAFETY_ANALYSIS |
| 10 | #endif |
| 11 | #else |
| 12 | #if defined(__SANITIZE_ADDRESS__) /* GCC 4.8.x, is ASAN enabled? */ |
| 13 | #define ATTRIBUTE_NO_ADDRESS_SAFETY_ANALYSIS \ |
| 14 | __attribute__((no_address_safety_analysis)) \ |
| 15 | __attribute__ ((noinline)) |
| 16 | #else |
| 17 | #define ATTRIBUTE_NO_ADDRESS_SAFETY_ANALYSIS |
| 18 | #endif |
| 19 | #endif |
| 20 | |
| 21 | #ifdef WITH_PYMALLOC |
| 22 | |
| 23 | #ifdef HAVE_MMAP |
| 24 | #include <sys/mman.h> |
| 25 | #ifdef MAP_ANONYMOUS |
| 26 | #define ARENAS_USE_MMAP |
| 27 | #endif |
| 28 | #endif |
| 29 | |
| 30 | #ifdef WITH_VALGRIND |
| 31 | #include <valgrind/valgrind.h> |
| 32 | |
| 33 | /* If we're using GCC, use __builtin_expect() to reduce overhead of |
| 34 | the valgrind checks */ |
| 35 | #if defined(__GNUC__) && (__GNUC__ > 2) && defined(__OPTIMIZE__) |
| 36 | # define UNLIKELY(value) __builtin_expect((value), 0) |
| 37 | #else |
| 38 | # define UNLIKELY(value) (value) |
| 39 | #endif |
| 40 | |
| 41 | /* -1 indicates that we haven't checked that we're running on valgrind yet. */ |
| 42 | static int running_on_valgrind = -1; |
| 43 | #endif |
| 44 | |
| 45 | /* An object allocator for Python. |
| 46 | |
| 47 | Here is an introduction to the layers of the Python memory architecture, |
| 48 | showing where the object allocator is actually used (layer +2), It is |
| 49 | called for every object allocation and deallocation (PyObject_New/Del), |
| 50 | unless the object-specific allocators implement a proprietary allocation |
| 51 | scheme (ex.: ints use a simple free list). This is also the place where |
| 52 | the cyclic garbage collector operates selectively on container objects. |
| 53 | |
| 54 | |
| 55 | Object-specific allocators |
| 56 | _____ ______ ______ ________ |
| 57 | [ int ] [ dict ] [ list ] ... [ string ] Python core | |
| 58 | +3 | <----- Object-specific memory -----> | <-- Non-object memory --> | |
| 59 | _______________________________ | | |
| 60 | [ Python's object allocator ] | | |
| 61 | +2 | ####### Object memory ####### | <------ Internal buffers ------> | |
| 62 | ______________________________________________________________ | |
| 63 | [ Python's raw memory allocator (PyMem_ API) ] | |
| 64 | +1 | <----- Python memory (under PyMem manager's control) ------> | | |
| 65 | __________________________________________________________________ |
| 66 | [ Underlying general-purpose allocator (ex: C library malloc) ] |
| 67 | 0 | <------ Virtual memory allocated for the python process -------> | |
| 68 | |
| 69 | ========================================================================= |
| 70 | _______________________________________________________________________ |
| 71 | [ OS-specific Virtual Memory Manager (VMM) ] |
| 72 | -1 | <--- Kernel dynamic storage allocation & management (page-based) ---> | |
| 73 | __________________________________ __________________________________ |
| 74 | [ ] [ ] |
| 75 | -2 | <-- Physical memory: ROM/RAM --> | | <-- Secondary storage (swap) --> | |
| 76 | |
| 77 | */ |
| 78 | /*==========================================================================*/ |
| 79 | |
| 80 | /* A fast, special-purpose memory allocator for small blocks, to be used |
| 81 | on top of a general-purpose malloc -- heavily based on previous art. */ |
| 82 | |
| 83 | /* Vladimir Marangozov -- August 2000 */ |
| 84 | |
| 85 | /* |
| 86 | * "Memory management is where the rubber meets the road -- if we do the wrong |
| 87 | * thing at any level, the results will not be good. And if we don't make the |
| 88 | * levels work well together, we are in serious trouble." (1) |
| 89 | * |
| 90 | * (1) Paul R. Wilson, Mark S. Johnstone, Michael Neely, and David Boles, |
| 91 | * "Dynamic Storage Allocation: A Survey and Critical Review", |
| 92 | * in Proc. 1995 Int'l. Workshop on Memory Management, September 1995. |
| 93 | */ |
| 94 | |
| 95 | /* #undef WITH_MEMORY_LIMITS */ /* disable mem limit checks */ |
| 96 | |
| 97 | /*==========================================================================*/ |
| 98 | |
| 99 | /* |
| 100 | * Allocation strategy abstract: |
| 101 | * |
| 102 | * For small requests, the allocator sub-allocates <Big> blocks of memory. |
| 103 | * Requests greater than SMALL_REQUEST_THRESHOLD bytes are routed to the |
| 104 | * system's allocator. |
| 105 | * |
| 106 | * Small requests are grouped in size classes spaced 8 bytes apart, due |
| 107 | * to the required valid alignment of the returned address. Requests of |
| 108 | * a particular size are serviced from memory pools of 4K (one VMM page). |
| 109 | * Pools are fragmented on demand and contain free lists of blocks of one |
| 110 | * particular size class. In other words, there is a fixed-size allocator |
| 111 | * for each size class. Free pools are shared by the different allocators |
| 112 | * thus minimizing the space reserved for a particular size class. |
| 113 | * |
| 114 | * This allocation strategy is a variant of what is known as "simple |
| 115 | * segregated storage based on array of free lists". The main drawback of |
| 116 | * simple segregated storage is that we might end up with lot of reserved |
| 117 | * memory for the different free lists, which degenerate in time. To avoid |
| 118 | * this, we partition each free list in pools and we share dynamically the |
| 119 | * reserved space between all free lists. This technique is quite efficient |
| 120 | * for memory intensive programs which allocate mainly small-sized blocks. |
| 121 | * |
| 122 | * For small requests we have the following table: |
| 123 | * |
| 124 | * Request in bytes Size of allocated block Size class idx |
| 125 | * ---------------------------------------------------------------- |
| 126 | * 1-8 8 0 |
| 127 | * 9-16 16 1 |
| 128 | * 17-24 24 2 |
| 129 | * 25-32 32 3 |
| 130 | * 33-40 40 4 |
| 131 | * 41-48 48 5 |
| 132 | * 49-56 56 6 |
| 133 | * 57-64 64 7 |
| 134 | * 65-72 72 8 |
| 135 | * ... ... ... |
| 136 | * 497-504 504 62 |
| 137 | * 505-512 512 63 |
| 138 | * |
| 139 | * 0, SMALL_REQUEST_THRESHOLD + 1 and up: routed to the underlying |
| 140 | * allocator. |
| 141 | */ |
| 142 | |
| 143 | /*==========================================================================*/ |
| 144 | |
| 145 | /* |
| 146 | * -- Main tunable settings section -- |
| 147 | */ |
| 148 | |
| 149 | /* |
| 150 | * Alignment of addresses returned to the user. 8-bytes alignment works |
| 151 | * on most current architectures (with 32-bit or 64-bit address busses). |
| 152 | * The alignment value is also used for grouping small requests in size |
| 153 | * classes spaced ALIGNMENT bytes apart. |
| 154 | * |
| 155 | * You shouldn't change this unless you know what you are doing. |
| 156 | */ |
| 157 | |
| 158 | #if SIZEOF_VOID_P > 4 |
| 159 | #define ALIGNMENT 16 /* must be 2^N */ |
| 160 | #define ALIGNMENT_SHIFT 4 |
| 161 | #else |
| 162 | #define ALIGNMENT 8 /* must be 2^N */ |
| 163 | #define ALIGNMENT_SHIFT 3 |
| 164 | #endif |
| 165 | #define ALIGNMENT_MASK (ALIGNMENT - 1) |
| 166 | |
| 167 | /* Return the number of bytes in size class I, as a uint. */ |
| 168 | #define INDEX2SIZE(I) (((uint)(I) + 1) << ALIGNMENT_SHIFT) |
| 169 | |
| 170 | /* |
| 171 | * Max size threshold below which malloc requests are considered to be |
| 172 | * small enough in order to use preallocated memory pools. You can tune |
| 173 | * this value according to your application behaviour and memory needs. |
| 174 | * |
| 175 | * The following invariants must hold: |
| 176 | * 1) ALIGNMENT <= SMALL_REQUEST_THRESHOLD <= 512 |
| 177 | * 2) SMALL_REQUEST_THRESHOLD is evenly divisible by ALIGNMENT |
| 178 | * |
| 179 | * Note: a size threshold of 512 guarantees that newly created dictionaries |
| 180 | * will be allocated from preallocated memory pools on 64-bit. |
| 181 | * |
| 182 | * Although not required, for better performance and space efficiency, |
| 183 | * it is recommended that SMALL_REQUEST_THRESHOLD is set to a power of 2. |
| 184 | */ |
| 185 | #define SMALL_REQUEST_THRESHOLD 512 |
| 186 | #define NB_SMALL_SIZE_CLASSES (SMALL_REQUEST_THRESHOLD / ALIGNMENT) |
| 187 | |
| 188 | /* |
| 189 | * The system's VMM page size can be obtained on most unices with a |
| 190 | * getpagesize() call or deduced from various header files. To make |
| 191 | * things simpler, we assume that it is 4K, which is OK for most systems. |
| 192 | * It is probably better if this is the native page size, but it doesn't |
| 193 | * have to be. In theory, if SYSTEM_PAGE_SIZE is larger than the native page |
| 194 | * size, then `POOL_ADDR(p)->arenaindex' could rarely cause a segmentation |
| 195 | * violation fault. 4K is apparently OK for all the platforms that python |
| 196 | * currently targets. |
| 197 | */ |
| 198 | #define SYSTEM_PAGE_SIZE (4 * 1024) |
| 199 | #define SYSTEM_PAGE_SIZE_MASK (SYSTEM_PAGE_SIZE - 1) |
| 200 | |
| 201 | /* |
| 202 | * Maximum amount of memory managed by the allocator for small requests. |
| 203 | */ |
| 204 | #ifdef WITH_MEMORY_LIMITS |
| 205 | #ifndef SMALL_MEMORY_LIMIT |
| 206 | #define SMALL_MEMORY_LIMIT (64 * 1024 * 1024) /* 64 MB -- more? */ |
| 207 | #endif |
| 208 | #endif |
| 209 | |
| 210 | /* |
| 211 | * The allocator sub-allocates <Big> blocks of memory (called arenas) aligned |
| 212 | * on a page boundary. This is a reserved virtual address space for the |
| 213 | * current process (obtained through a malloc()/mmap() call). In no way this |
| 214 | * means that the memory arenas will be used entirely. A malloc(<Big>) is |
| 215 | * usually an address range reservation for <Big> bytes, unless all pages within |
| 216 | * this space are referenced subsequently. So malloc'ing big blocks and not |
| 217 | * using them does not mean "wasting memory". It's an addressable range |
| 218 | * wastage... |
| 219 | * |
| 220 | * Arenas are allocated with mmap() on systems supporting anonymous memory |
| 221 | * mappings to reduce heap fragmentation. |
| 222 | */ |
| 223 | #define ARENA_SIZE (256 << 10) /* 256KiB */ |
| 224 | |
| 225 | #ifdef WITH_MEMORY_LIMITS |
| 226 | #define MAX_ARENAS (SMALL_MEMORY_LIMIT / ARENA_SIZE) |
| 227 | #endif |
| 228 | |
| 229 | /* |
| 230 | * Size of the pools used for small blocks. Should be a power of 2, |
| 231 | * between 1K and SYSTEM_PAGE_SIZE, that is: 1k, 2k, 4k. |
| 232 | */ |
| 233 | #define POOL_SIZE SYSTEM_PAGE_SIZE /* must be 2^N */ |
| 234 | #define POOL_SIZE_MASK SYSTEM_PAGE_SIZE_MASK |
| 235 | |
| 236 | /* |
| 237 | * -- End of tunable settings section -- |
| 238 | */ |
| 239 | |
| 240 | /*==========================================================================*/ |
| 241 | |
| 242 | /* |
| 243 | * Locking |
| 244 | * |
| 245 | * To reduce lock contention, it would probably be better to refine the |
| 246 | * crude function locking with per size class locking. I'm not positive |
| 247 | * however, whether it's worth switching to such locking policy because |
| 248 | * of the performance penalty it might introduce. |
| 249 | * |
| 250 | * The following macros describe the simplest (should also be the fastest) |
| 251 | * lock object on a particular platform and the init/fini/lock/unlock |
| 252 | * operations on it. The locks defined here are not expected to be recursive |
| 253 | * because it is assumed that they will always be called in the order: |
| 254 | * INIT, [LOCK, UNLOCK]*, FINI. |
| 255 | */ |
| 256 | |
| 257 | /* |
| 258 | * Python's threads are serialized, so object malloc locking is disabled. |
| 259 | */ |
| 260 | #define SIMPLELOCK_DECL(lock) /* simple lock declaration */ |
| 261 | #define SIMPLELOCK_INIT(lock) /* allocate (if needed) and initialize */ |
| 262 | #define SIMPLELOCK_FINI(lock) /* free/destroy an existing lock */ |
| 263 | #define SIMPLELOCK_LOCK(lock) /* acquire released lock */ |
| 264 | #define SIMPLELOCK_UNLOCK(lock) /* release acquired lock */ |
| 265 | |
| 266 | /* |
| 267 | * Basic types |
| 268 | * I don't care if these are defined in <sys/types.h> or elsewhere. Axiom. |
| 269 | */ |
| 270 | #undef uchar |
| 271 | #define uchar unsigned char /* assuming == 8 bits */ |
| 272 | |
| 273 | #undef uint |
| 274 | #define uint unsigned int /* assuming >= 16 bits */ |
| 275 | |
| 276 | #undef ulong |
| 277 | #define ulong unsigned long /* assuming >= 32 bits */ |
| 278 | |
| 279 | #undef uptr |
| 280 | #define uptr Py_uintptr_t |
| 281 | |
| 282 | /* When you say memory, my mind reasons in terms of (pointers to) blocks */ |
| 283 | typedef uchar block; |
| 284 | |
| 285 | /* Pool for small blocks. */ |
| 286 | struct pool_header { |
| 287 | union { block *_padding; |
| 288 | uint count; } ref; /* number of allocated blocks */ |
| 289 | block *freeblock; /* pool's free list head */ |
| 290 | struct pool_header *nextpool; /* next pool of this size class */ |
| 291 | struct pool_header *prevpool; /* previous pool "" */ |
| 292 | uint arenaindex; /* index into arenas of base adr */ |
| 293 | uint szidx; /* block size class index */ |
| 294 | uint nextoffset; /* bytes to virgin block */ |
| 295 | uint maxnextoffset; /* largest valid nextoffset */ |
| 296 | }; |
| 297 | |
| 298 | typedef struct pool_header *poolp; |
| 299 | |
| 300 | /* Record keeping for arenas. */ |
| 301 | struct arena_object { |
| 302 | /* The address of the arena, as returned by malloc. Note that 0 |
| 303 | * will never be returned by a successful malloc, and is used |
| 304 | * here to mark an arena_object that doesn't correspond to an |
| 305 | * allocated arena. |
| 306 | */ |
| 307 | uptr address; |
| 308 | |
| 309 | /* Pool-aligned pointer to the next pool to be carved off. */ |
| 310 | block* pool_address; |
| 311 | |
| 312 | /* The number of available pools in the arena: free pools + never- |
| 313 | * allocated pools. |
| 314 | */ |
| 315 | uint nfreepools; |
| 316 | |
| 317 | /* The total number of pools in the arena, whether or not available. */ |
| 318 | uint ntotalpools; |
| 319 | |
| 320 | /* Singly-linked list of available pools. */ |
| 321 | struct pool_header* freepools; |
| 322 | |
| 323 | /* Whenever this arena_object is not associated with an allocated |
| 324 | * arena, the nextarena member is used to link all unassociated |
| 325 | * arena_objects in the singly-linked `unused_arena_objects` list. |
| 326 | * The prevarena member is unused in this case. |
| 327 | * |
| 328 | * When this arena_object is associated with an allocated arena |
| 329 | * with at least one available pool, both members are used in the |
| 330 | * doubly-linked `usable_arenas` list, which is maintained in |
| 331 | * increasing order of `nfreepools` values. |
| 332 | * |
| 333 | * Else this arena_object is associated with an allocated arena |
| 334 | * all of whose pools are in use. `nextarena` and `prevarena` |
| 335 | * are both meaningless in this case. |
| 336 | */ |
| 337 | struct arena_object* nextarena; |
| 338 | struct arena_object* prevarena; |
| 339 | }; |
| 340 | |
| 341 | #undef ROUNDUP |
| 342 | #define ROUNDUP(x) (((x) + ALIGNMENT_MASK) & ~ALIGNMENT_MASK) |
| 343 | #define POOL_OVERHEAD ROUNDUP(sizeof(struct pool_header)) |
| 344 | |
| 345 | #define DUMMY_SIZE_IDX 0xffff /* size class of newly cached pools */ |
| 346 | |
| 347 | /* Round pointer P down to the closest pool-aligned address <= P, as a poolp */ |
| 348 | #define POOL_ADDR(P) ((poolp)((uptr)(P) & ~(uptr)POOL_SIZE_MASK)) |
| 349 | |
| 350 | /* Return total number of blocks in pool of size index I, as a uint. */ |
| 351 | #define NUMBLOCKS(I) ((uint)(POOL_SIZE - POOL_OVERHEAD) / INDEX2SIZE(I)) |
| 352 | |
| 353 | /*==========================================================================*/ |
| 354 | |
| 355 | /* |
| 356 | * This malloc lock |
| 357 | */ |
| 358 | SIMPLELOCK_DECL(_malloc_lock) |
| 359 | #define LOCK() SIMPLELOCK_LOCK(_malloc_lock) |
| 360 | #define UNLOCK() SIMPLELOCK_UNLOCK(_malloc_lock) |
| 361 | #define LOCK_INIT() SIMPLELOCK_INIT(_malloc_lock) |
| 362 | #define LOCK_FINI() SIMPLELOCK_FINI(_malloc_lock) |
| 363 | |
| 364 | /* |
| 365 | * Pool table -- headed, circular, doubly-linked lists of partially used pools. |
| 366 | |
| 367 | This is involved. For an index i, usedpools[i+i] is the header for a list of |
| 368 | all partially used pools holding small blocks with "size class idx" i. So |
| 369 | usedpools[0] corresponds to blocks of size 8, usedpools[2] to blocks of size |
| 370 | 16, and so on: index 2*i <-> blocks of size (i+1)<<ALIGNMENT_SHIFT. |
| 371 | |
| 372 | Pools are carved off an arena's highwater mark (an arena_object's pool_address |
| 373 | member) as needed. Once carved off, a pool is in one of three states forever |
| 374 | after: |
| 375 | |
| 376 | used == partially used, neither empty nor full |
| 377 | At least one block in the pool is currently allocated, and at least one |
| 378 | block in the pool is not currently allocated (note this implies a pool |
| 379 | has room for at least two blocks). |
| 380 | This is a pool's initial state, as a pool is created only when malloc |
| 381 | needs space. |
| 382 | The pool holds blocks of a fixed size, and is in the circular list headed |
| 383 | at usedpools[i] (see above). It's linked to the other used pools of the |
| 384 | same size class via the pool_header's nextpool and prevpool members. |
| 385 | If all but one block is currently allocated, a malloc can cause a |
| 386 | transition to the full state. If all but one block is not currently |
| 387 | allocated, a free can cause a transition to the empty state. |
| 388 | |
| 389 | full == all the pool's blocks are currently allocated |
| 390 | On transition to full, a pool is unlinked from its usedpools[] list. |
| 391 | It's not linked to from anything then anymore, and its nextpool and |
| 392 | prevpool members are meaningless until it transitions back to used. |
| 393 | A free of a block in a full pool puts the pool back in the used state. |
| 394 | Then it's linked in at the front of the appropriate usedpools[] list, so |
| 395 | that the next allocation for its size class will reuse the freed block. |
| 396 | |
| 397 | empty == all the pool's blocks are currently available for allocation |
| 398 | On transition to empty, a pool is unlinked from its usedpools[] list, |
| 399 | and linked to the front of its arena_object's singly-linked freepools list, |
| 400 | via its nextpool member. The prevpool member has no meaning in this case. |
| 401 | Empty pools have no inherent size class: the next time a malloc finds |
| 402 | an empty list in usedpools[], it takes the first pool off of freepools. |
| 403 | If the size class needed happens to be the same as the size class the pool |
| 404 | last had, some pool initialization can be skipped. |
| 405 | |
| 406 | |
| 407 | Block Management |
| 408 | |
| 409 | Blocks within pools are again carved out as needed. pool->freeblock points to |
| 410 | the start of a singly-linked list of free blocks within the pool. When a |
| 411 | block is freed, it's inserted at the front of its pool's freeblock list. Note |
| 412 | that the available blocks in a pool are *not* linked all together when a pool |
| 413 | is initialized. Instead only "the first two" (lowest addresses) blocks are |
| 414 | set up, returning the first such block, and setting pool->freeblock to a |
| 415 | one-block list holding the second such block. This is consistent with that |
| 416 | pymalloc strives at all levels (arena, pool, and block) never to touch a piece |
| 417 | of memory until it's actually needed. |
| 418 | |
| 419 | So long as a pool is in the used state, we're certain there *is* a block |
| 420 | available for allocating, and pool->freeblock is not NULL. If pool->freeblock |
| 421 | points to the end of the free list before we've carved the entire pool into |
| 422 | blocks, that means we simply haven't yet gotten to one of the higher-address |
| 423 | blocks. The offset from the pool_header to the start of "the next" virgin |
| 424 | block is stored in the pool_header nextoffset member, and the largest value |
| 425 | of nextoffset that makes sense is stored in the maxnextoffset member when a |
| 426 | pool is initialized. All the blocks in a pool have been passed out at least |
| 427 | once when and only when nextoffset > maxnextoffset. |
| 428 | |
| 429 | |
| 430 | Major obscurity: While the usedpools vector is declared to have poolp |
| 431 | entries, it doesn't really. It really contains two pointers per (conceptual) |
| 432 | poolp entry, the nextpool and prevpool members of a pool_header. The |
| 433 | excruciating initialization code below fools C so that |
| 434 | |
| 435 | usedpool[i+i] |
| 436 | |
| 437 | "acts like" a genuine poolp, but only so long as you only reference its |
| 438 | nextpool and prevpool members. The "- 2*sizeof(block *)" gibberish is |
| 439 | compensating for that a pool_header's nextpool and prevpool members |
| 440 | immediately follow a pool_header's first two members: |
| 441 | |
| 442 | union { block *_padding; |
| 443 | uint count; } ref; |
| 444 | block *freeblock; |
| 445 | |
| 446 | each of which consume sizeof(block *) bytes. So what usedpools[i+i] really |
| 447 | contains is a fudged-up pointer p such that *if* C believes it's a poolp |
| 448 | pointer, then p->nextpool and p->prevpool are both p (meaning that the headed |
| 449 | circular list is empty). |
| 450 | |
| 451 | It's unclear why the usedpools setup is so convoluted. It could be to |
| 452 | minimize the amount of cache required to hold this heavily-referenced table |
| 453 | (which only *needs* the two interpool pointer members of a pool_header). OTOH, |
| 454 | referencing code has to remember to "double the index" and doing so isn't |
| 455 | free, usedpools[0] isn't a strictly legal pointer, and we're crucially relying |
| 456 | on that C doesn't insert any padding anywhere in a pool_header at or before |
| 457 | the prevpool member. |
| 458 | **************************************************************************** */ |
| 459 | |
| 460 | #define PTA(x) ((poolp )((uchar *)&(usedpools[2*(x)]) - 2*sizeof(block *))) |
| 461 | #define PT(x) PTA(x), PTA(x) |
| 462 | |
| 463 | static poolp usedpools[2 * ((NB_SMALL_SIZE_CLASSES + 7) / 8) * 8] = { |
| 464 | PT(0), PT(1), PT(2), PT(3), PT(4), PT(5), PT(6), PT(7) |
| 465 | #if NB_SMALL_SIZE_CLASSES > 8 |
| 466 | , PT(8), PT(9), PT(10), PT(11), PT(12), PT(13), PT(14), PT(15) |
| 467 | #if NB_SMALL_SIZE_CLASSES > 16 |
| 468 | , PT(16), PT(17), PT(18), PT(19), PT(20), PT(21), PT(22), PT(23) |
| 469 | #if NB_SMALL_SIZE_CLASSES > 24 |
| 470 | , PT(24), PT(25), PT(26), PT(27), PT(28), PT(29), PT(30), PT(31) |
| 471 | #if NB_SMALL_SIZE_CLASSES > 32 |
| 472 | , PT(32), PT(33), PT(34), PT(35), PT(36), PT(37), PT(38), PT(39) |
| 473 | #if NB_SMALL_SIZE_CLASSES > 40 |
| 474 | , PT(40), PT(41), PT(42), PT(43), PT(44), PT(45), PT(46), PT(47) |
| 475 | #if NB_SMALL_SIZE_CLASSES > 48 |
| 476 | , PT(48), PT(49), PT(50), PT(51), PT(52), PT(53), PT(54), PT(55) |
| 477 | #if NB_SMALL_SIZE_CLASSES > 56 |
| 478 | , PT(56), PT(57), PT(58), PT(59), PT(60), PT(61), PT(62), PT(63) |
| 479 | #if NB_SMALL_SIZE_CLASSES > 64 |
| 480 | #error "NB_SMALL_SIZE_CLASSES should be less than 64" |
| 481 | #endif /* NB_SMALL_SIZE_CLASSES > 64 */ |
| 482 | #endif /* NB_SMALL_SIZE_CLASSES > 56 */ |
| 483 | #endif /* NB_SMALL_SIZE_CLASSES > 48 */ |
| 484 | #endif /* NB_SMALL_SIZE_CLASSES > 40 */ |
| 485 | #endif /* NB_SMALL_SIZE_CLASSES > 32 */ |
| 486 | #endif /* NB_SMALL_SIZE_CLASSES > 24 */ |
| 487 | #endif /* NB_SMALL_SIZE_CLASSES > 16 */ |
| 488 | #endif /* NB_SMALL_SIZE_CLASSES > 8 */ |
| 489 | }; |
| 490 | |
| 491 | /*========================================================================== |
| 492 | Arena management. |
| 493 | |
| 494 | `arenas` is a vector of arena_objects. It contains maxarenas entries, some of |
| 495 | which may not be currently used (== they're arena_objects that aren't |
| 496 | currently associated with an allocated arena). Note that arenas proper are |
| 497 | separately malloc'ed. |
| 498 | |
| 499 | Prior to Python 2.5, arenas were never free()'ed. Starting with Python 2.5, |
| 500 | we do try to free() arenas, and use some mild heuristic strategies to increase |
| 501 | the likelihood that arenas eventually can be freed. |
| 502 | |
| 503 | unused_arena_objects |
| 504 | |
| 505 | This is a singly-linked list of the arena_objects that are currently not |
| 506 | being used (no arena is associated with them). Objects are taken off the |
| 507 | head of the list in new_arena(), and are pushed on the head of the list in |
| 508 | PyObject_Free() when the arena is empty. Key invariant: an arena_object |
| 509 | is on this list if and only if its .address member is 0. |
| 510 | |
| 511 | usable_arenas |
| 512 | |
| 513 | This is a doubly-linked list of the arena_objects associated with arenas |
| 514 | that have pools available. These pools are either waiting to be reused, |
| 515 | or have not been used before. The list is sorted to have the most- |
| 516 | allocated arenas first (ascending order based on the nfreepools member). |
| 517 | This means that the next allocation will come from a heavily used arena, |
| 518 | which gives the nearly empty arenas a chance to be returned to the system. |
| 519 | In my unscientific tests this dramatically improved the number of arenas |
| 520 | that could be freed. |
| 521 | |
| 522 | Note that an arena_object associated with an arena all of whose pools are |
| 523 | currently in use isn't on either list. |
| 524 | */ |
| 525 | |
| 526 | /* Array of objects used to track chunks of memory (arenas). */ |
| 527 | static struct arena_object* arenas = NULL; |
| 528 | /* Number of slots currently allocated in the `arenas` vector. */ |
| 529 | static uint maxarenas = 0; |
| 530 | |
| 531 | /* The head of the singly-linked, NULL-terminated list of available |
| 532 | * arena_objects. |
| 533 | */ |
| 534 | static struct arena_object* unused_arena_objects = NULL; |
| 535 | |
| 536 | /* The head of the doubly-linked, NULL-terminated at each end, list of |
| 537 | * arena_objects associated with arenas that have pools available. |
| 538 | */ |
| 539 | static struct arena_object* usable_arenas = NULL; |
| 540 | |
| 541 | /* How many arena_objects do we initially allocate? |
| 542 | * 16 = can allocate 16 arenas = 16 * ARENA_SIZE = 4MB before growing the |
| 543 | * `arenas` vector. |
| 544 | */ |
| 545 | #define INITIAL_ARENA_OBJECTS 16 |
| 546 | |
| 547 | /* Number of arenas allocated that haven't been free()'d. */ |
| 548 | static size_t narenas_currently_allocated = 0; |
| 549 | |
| 550 | #ifdef PYMALLOC_DEBUG |
| 551 | /* Total number of times malloc() called to allocate an arena. */ |
| 552 | static size_t ntimes_arena_allocated = 0; |
| 553 | /* High water mark (max value ever seen) for narenas_currently_allocated. */ |
| 554 | static size_t narenas_highwater = 0; |
| 555 | #endif |
| 556 | |
| 557 | /* Allocate a new arena. If we run out of memory, return NULL. Else |
| 558 | * allocate a new arena, and return the address of an arena_object |
| 559 | * describing the new arena. It's expected that the caller will set |
| 560 | * `usable_arenas` to the return value. |
| 561 | */ |
| 562 | static struct arena_object* |
| 563 | new_arena(void) |
| 564 | { |
| 565 | struct arena_object* arenaobj; |
| 566 | uint excess; /* number of bytes above pool alignment */ |
| 567 | void *address; |
| 568 | int err; |
| 569 | |
| 570 | #ifdef PYMALLOC_DEBUG |
| 571 | if (Py_GETENV("PYTHONMALLOCSTATS")) |
| 572 | _PyObject_DebugMallocStats(); |
| 573 | #endif |
| 574 | if (unused_arena_objects == NULL) { |
| 575 | uint i; |
| 576 | uint numarenas; |
| 577 | size_t nbytes; |
| 578 | |
| 579 | /* Double the number of arena objects on each allocation. |
| 580 | * Note that it's possible for `numarenas` to overflow. |
| 581 | */ |
| 582 | numarenas = maxarenas ? maxarenas << 1 : INITIAL_ARENA_OBJECTS; |
| 583 | if (numarenas <= maxarenas) |
| 584 | return NULL; /* overflow */ |
| 585 | #if SIZEOF_SIZE_T <= SIZEOF_INT |
| 586 | if (numarenas > PY_SIZE_MAX / sizeof(*arenas)) |
| 587 | return NULL; /* overflow */ |
| 588 | #endif |
| 589 | nbytes = numarenas * sizeof(*arenas); |
| 590 | arenaobj = (struct arena_object *)realloc(arenas, nbytes); |
| 591 | if (arenaobj == NULL) |
| 592 | return NULL; |
| 593 | arenas = arenaobj; |
| 594 | |
| 595 | /* We might need to fix pointers that were copied. However, |
| 596 | * new_arena only gets called when all the pages in the |
| 597 | * previous arenas are full. Thus, there are *no* pointers |
| 598 | * into the old array. Thus, we don't have to worry about |
| 599 | * invalid pointers. Just to be sure, some asserts: |
| 600 | */ |
| 601 | assert(usable_arenas == NULL); |
| 602 | assert(unused_arena_objects == NULL); |
| 603 | |
| 604 | /* Put the new arenas on the unused_arena_objects list. */ |
| 605 | for (i = maxarenas; i < numarenas; ++i) { |
| 606 | arenas[i].address = 0; /* mark as unassociated */ |
| 607 | arenas[i].nextarena = i < numarenas - 1 ? |
| 608 | &arenas[i+1] : NULL; |
| 609 | } |
| 610 | |
| 611 | /* Update globals. */ |
| 612 | unused_arena_objects = &arenas[maxarenas]; |
| 613 | maxarenas = numarenas; |
| 614 | } |
| 615 | |
| 616 | /* Take the next available arena object off the head of the list. */ |
| 617 | assert(unused_arena_objects != NULL); |
| 618 | arenaobj = unused_arena_objects; |
| 619 | unused_arena_objects = arenaobj->nextarena; |
| 620 | assert(arenaobj->address == 0); |
| 621 | #ifdef ARENAS_USE_MMAP |
| 622 | address = mmap(NULL, ARENA_SIZE, PROT_READ|PROT_WRITE, |
| 623 | MAP_PRIVATE|MAP_ANONYMOUS, -1, 0); |
| 624 | err = (address == MAP_FAILED); |
| 625 | #else |
| 626 | address = malloc(ARENA_SIZE); |
| 627 | err = (address == 0); |
| 628 | #endif |
| 629 | if (err) { |
| 630 | /* The allocation failed: return NULL after putting the |
| 631 | * arenaobj back. |
| 632 | */ |
| 633 | arenaobj->nextarena = unused_arena_objects; |
| 634 | unused_arena_objects = arenaobj; |
| 635 | return NULL; |
| 636 | } |
| 637 | arenaobj->address = (uptr)address; |
| 638 | |
| 639 | ++narenas_currently_allocated; |
| 640 | #ifdef PYMALLOC_DEBUG |
| 641 | ++ntimes_arena_allocated; |
| 642 | if (narenas_currently_allocated > narenas_highwater) |
| 643 | narenas_highwater = narenas_currently_allocated; |
| 644 | #endif |
| 645 | arenaobj->freepools = NULL; |
| 646 | /* pool_address <- first pool-aligned address in the arena |
| 647 | nfreepools <- number of whole pools that fit after alignment */ |
| 648 | arenaobj->pool_address = (block*)arenaobj->address; |
| 649 | arenaobj->nfreepools = ARENA_SIZE / POOL_SIZE; |
| 650 | assert(POOL_SIZE * arenaobj->nfreepools == ARENA_SIZE); |
| 651 | excess = (uint)(arenaobj->address & POOL_SIZE_MASK); |
| 652 | if (excess != 0) { |
| 653 | --arenaobj->nfreepools; |
| 654 | arenaobj->pool_address += POOL_SIZE - excess; |
| 655 | } |
| 656 | arenaobj->ntotalpools = arenaobj->nfreepools; |
| 657 | |
| 658 | return arenaobj; |
| 659 | } |
| 660 | |
| 661 | /* |
| 662 | Py_ADDRESS_IN_RANGE(P, POOL) |
| 663 | |
| 664 | Return true if and only if P is an address that was allocated by pymalloc. |
| 665 | POOL must be the pool address associated with P, i.e., POOL = POOL_ADDR(P) |
| 666 | (the caller is asked to compute this because the macro expands POOL more than |
| 667 | once, and for efficiency it's best for the caller to assign POOL_ADDR(P) to a |
| 668 | variable and pass the latter to the macro; because Py_ADDRESS_IN_RANGE is |
| 669 | called on every alloc/realloc/free, micro-efficiency is important here). |
| 670 | |
| 671 | Tricky: Let B be the arena base address associated with the pool, B = |
| 672 | arenas[(POOL)->arenaindex].address. Then P belongs to the arena if and only if |
| 673 | |
| 674 | B <= P < B + ARENA_SIZE |
| 675 | |
| 676 | Subtracting B throughout, this is true iff |
| 677 | |
| 678 | 0 <= P-B < ARENA_SIZE |
| 679 | |
| 680 | By using unsigned arithmetic, the "0 <=" half of the test can be skipped. |
| 681 | |
| 682 | Obscure: A PyMem "free memory" function can call the pymalloc free or realloc |
| 683 | before the first arena has been allocated. `arenas` is still NULL in that |
| 684 | case. We're relying on that maxarenas is also 0 in that case, so that |
| 685 | (POOL)->arenaindex < maxarenas must be false, saving us from trying to index |
| 686 | into a NULL arenas. |
| 687 | |
| 688 | Details: given P and POOL, the arena_object corresponding to P is AO = |
| 689 | arenas[(POOL)->arenaindex]. Suppose obmalloc controls P. Then (barring wild |
| 690 | stores, etc), POOL is the correct address of P's pool, AO.address is the |
| 691 | correct base address of the pool's arena, and P must be within ARENA_SIZE of |
| 692 | AO.address. In addition, AO.address is not 0 (no arena can start at address 0 |
| 693 | (NULL)). Therefore Py_ADDRESS_IN_RANGE correctly reports that obmalloc |
| 694 | controls P. |
| 695 | |
| 696 | Now suppose obmalloc does not control P (e.g., P was obtained via a direct |
| 697 | call to the system malloc() or realloc()). (POOL)->arenaindex may be anything |
| 698 | in this case -- it may even be uninitialized trash. If the trash arenaindex |
| 699 | is >= maxarenas, the macro correctly concludes at once that obmalloc doesn't |
| 700 | control P. |
| 701 | |
| 702 | Else arenaindex is < maxarena, and AO is read up. If AO corresponds to an |
| 703 | allocated arena, obmalloc controls all the memory in slice AO.address : |
| 704 | AO.address+ARENA_SIZE. By case assumption, P is not controlled by obmalloc, |
| 705 | so P doesn't lie in that slice, so the macro correctly reports that P is not |
| 706 | controlled by obmalloc. |
| 707 | |
| 708 | Finally, if P is not controlled by obmalloc and AO corresponds to an unused |
| 709 | arena_object (one not currently associated with an allocated arena), |
| 710 | AO.address is 0, and the second test in the macro reduces to: |
| 711 | |
| 712 | P < ARENA_SIZE |
| 713 | |
| 714 | If P >= ARENA_SIZE (extremely likely), the macro again correctly concludes |
| 715 | that P is not controlled by obmalloc. However, if P < ARENA_SIZE, this part |
| 716 | of the test still passes, and the third clause (AO.address != 0) is necessary |
| 717 | to get the correct result: AO.address is 0 in this case, so the macro |
| 718 | correctly reports that P is not controlled by obmalloc (despite that P lies in |
| 719 | slice AO.address : AO.address + ARENA_SIZE). |
| 720 | |
| 721 | Note: The third (AO.address != 0) clause was added in Python 2.5. Before |
| 722 | 2.5, arenas were never free()'ed, and an arenaindex < maxarena always |
| 723 | corresponded to a currently-allocated arena, so the "P is not controlled by |
| 724 | obmalloc, AO corresponds to an unused arena_object, and P < ARENA_SIZE" case |
| 725 | was impossible. |
| 726 | |
| 727 | Note that the logic is excruciating, and reading up possibly uninitialized |
| 728 | memory when P is not controlled by obmalloc (to get at (POOL)->arenaindex) |
| 729 | creates problems for some memory debuggers. The overwhelming advantage is |
| 730 | that this test determines whether an arbitrary address is controlled by |
| 731 | obmalloc in a small constant time, independent of the number of arenas |
| 732 | obmalloc controls. Since this test is needed at every entry point, it's |
| 733 | extremely desirable that it be this fast. |
| 734 | |
| 735 | Since Py_ADDRESS_IN_RANGE may be reading from memory which was not allocated |
| 736 | by Python, it is important that (POOL)->arenaindex is read only once, as |
| 737 | another thread may be concurrently modifying the value without holding the |
| 738 | GIL. To accomplish this, the arenaindex_temp variable is used to store |
| 739 | (POOL)->arenaindex for the duration of the Py_ADDRESS_IN_RANGE macro's |
| 740 | execution. The caller of the macro is responsible for declaring this |
| 741 | variable. |
| 742 | */ |
| 743 | #define Py_ADDRESS_IN_RANGE(P, POOL) \ |
| 744 | ((arenaindex_temp = (POOL)->arenaindex) < maxarenas && \ |
| 745 | (uptr)(P) - arenas[arenaindex_temp].address < (uptr)ARENA_SIZE && \ |
| 746 | arenas[arenaindex_temp].address != 0) |
| 747 | |
| 748 | |
| 749 | /* This is only useful when running memory debuggers such as |
| 750 | * Purify or Valgrind. Uncomment to use. |
| 751 | * |
| 752 | #define Py_USING_MEMORY_DEBUGGER |
| 753 | */ |
| 754 | |
| 755 | #ifdef Py_USING_MEMORY_DEBUGGER |
| 756 | |
| 757 | /* Py_ADDRESS_IN_RANGE may access uninitialized memory by design |
| 758 | * This leads to thousands of spurious warnings when using |
| 759 | * Purify or Valgrind. By making a function, we can easily |
| 760 | * suppress the uninitialized memory reads in this one function. |
| 761 | * So we won't ignore real errors elsewhere. |
| 762 | * |
| 763 | * Disable the macro and use a function. |
| 764 | */ |
| 765 | |
| 766 | #undef Py_ADDRESS_IN_RANGE |
| 767 | |
| 768 | #if defined(__GNUC__) && ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 1) || \ |
| 769 | (__GNUC__ >= 4)) |
| 770 | #define Py_NO_INLINE __attribute__((__noinline__)) |
| 771 | #else |
| 772 | #define Py_NO_INLINE |
| 773 | #endif |
| 774 | |
| 775 | /* Don't make static, to try to ensure this isn't inlined. */ |
| 776 | int Py_ADDRESS_IN_RANGE(void *P, poolp pool) Py_NO_INLINE; |
| 777 | #undef Py_NO_INLINE |
| 778 | #endif |
| 779 | |
| 780 | /*==========================================================================*/ |
| 781 | |
| 782 | /* malloc. Note that nbytes==0 tries to return a non-NULL pointer, distinct |
| 783 | * from all other currently live pointers. This may not be possible. |
| 784 | */ |
| 785 | |
| 786 | /* |
| 787 | * The basic blocks are ordered by decreasing execution frequency, |
| 788 | * which minimizes the number of jumps in the most common cases, |
| 789 | * improves branching prediction and instruction scheduling (small |
| 790 | * block allocations typically result in a couple of instructions). |
| 791 | * Unless the optimizer reorders everything, being too smart... |
| 792 | */ |
| 793 | |
| 794 | #undef PyObject_Malloc |
| 795 | void * |
| 796 | PyObject_Malloc(size_t nbytes) |
| 797 | { |
| 798 | block *bp; |
| 799 | poolp pool; |
| 800 | poolp next; |
| 801 | uint size; |
| 802 | |
| 803 | #ifdef WITH_VALGRIND |
| 804 | if (UNLIKELY(running_on_valgrind == -1)) |
| 805 | running_on_valgrind = RUNNING_ON_VALGRIND; |
| 806 | if (UNLIKELY(running_on_valgrind)) |
| 807 | goto redirect; |
| 808 | #endif |
| 809 | |
| 810 | /* |
| 811 | * Limit ourselves to PY_SSIZE_T_MAX bytes to prevent security holes. |
| 812 | * Most python internals blindly use a signed Py_ssize_t to track |
| 813 | * things without checking for overflows or negatives. |
| 814 | * As size_t is unsigned, checking for nbytes < 0 is not required. |
| 815 | */ |
| 816 | if (nbytes > PY_SSIZE_T_MAX) |
| 817 | return NULL; |
| 818 | |
| 819 | /* |
| 820 | * This implicitly redirects malloc(0). |
| 821 | */ |
| 822 | if ((nbytes - 1) < SMALL_REQUEST_THRESHOLD) { |
| 823 | LOCK(); |
| 824 | /* |
| 825 | * Most frequent paths first |
| 826 | */ |
| 827 | size = (uint)(nbytes - 1) >> ALIGNMENT_SHIFT; |
| 828 | pool = usedpools[size + size]; |
| 829 | if (pool != pool->nextpool) { |
| 830 | /* |
| 831 | * There is a used pool for this size class. |
| 832 | * Pick up the head block of its free list. |
| 833 | */ |
| 834 | ++pool->ref.count; |
| 835 | bp = pool->freeblock; |
| 836 | assert(bp != NULL); |
| 837 | if ((pool->freeblock = *(block **)bp) != NULL) { |
| 838 | UNLOCK(); |
| 839 | return (void *)bp; |
| 840 | } |
| 841 | /* |
| 842 | * Reached the end of the free list, try to extend it. |
| 843 | */ |
| 844 | if (pool->nextoffset <= pool->maxnextoffset) { |
| 845 | /* There is room for another block. */ |
| 846 | pool->freeblock = (block*)pool + |
| 847 | pool->nextoffset; |
| 848 | pool->nextoffset += INDEX2SIZE(size); |
| 849 | *(block **)(pool->freeblock) = NULL; |
| 850 | UNLOCK(); |
| 851 | return (void *)bp; |
| 852 | } |
| 853 | /* Pool is full, unlink from used pools. */ |
| 854 | next = pool->nextpool; |
| 855 | pool = pool->prevpool; |
| 856 | next->prevpool = pool; |
| 857 | pool->nextpool = next; |
| 858 | UNLOCK(); |
| 859 | return (void *)bp; |
| 860 | } |
| 861 | |
| 862 | /* There isn't a pool of the right size class immediately |
| 863 | * available: use a free pool. |
| 864 | */ |
| 865 | if (usable_arenas == NULL) { |
| 866 | /* No arena has a free pool: allocate a new arena. */ |
| 867 | #ifdef WITH_MEMORY_LIMITS |
| 868 | if (narenas_currently_allocated >= MAX_ARENAS) { |
| 869 | UNLOCK(); |
| 870 | goto redirect; |
| 871 | } |
| 872 | #endif |
| 873 | usable_arenas = new_arena(); |
| 874 | if (usable_arenas == NULL) { |
| 875 | UNLOCK(); |
| 876 | goto redirect; |
| 877 | } |
| 878 | usable_arenas->nextarena = |
| 879 | usable_arenas->prevarena = NULL; |
| 880 | } |
| 881 | assert(usable_arenas->address != 0); |
| 882 | |
| 883 | /* Try to get a cached free pool. */ |
| 884 | pool = usable_arenas->freepools; |
| 885 | if (pool != NULL) { |
| 886 | /* Unlink from cached pools. */ |
| 887 | usable_arenas->freepools = pool->nextpool; |
| 888 | |
| 889 | /* This arena already had the smallest nfreepools |
| 890 | * value, so decreasing nfreepools doesn't change |
| 891 | * that, and we don't need to rearrange the |
| 892 | * usable_arenas list. However, if the arena has |
| 893 | * become wholly allocated, we need to remove its |
| 894 | * arena_object from usable_arenas. |
| 895 | */ |
| 896 | --usable_arenas->nfreepools; |
| 897 | if (usable_arenas->nfreepools == 0) { |
| 898 | /* Wholly allocated: remove. */ |
| 899 | assert(usable_arenas->freepools == NULL); |
| 900 | assert(usable_arenas->nextarena == NULL || |
| 901 | usable_arenas->nextarena->prevarena == |
| 902 | usable_arenas); |
| 903 | |
| 904 | usable_arenas = usable_arenas->nextarena; |
| 905 | if (usable_arenas != NULL) { |
| 906 | usable_arenas->prevarena = NULL; |
| 907 | assert(usable_arenas->address != 0); |
| 908 | } |
| 909 | } |
| 910 | else { |
| 911 | /* nfreepools > 0: it must be that freepools |
| 912 | * isn't NULL, or that we haven't yet carved |
| 913 | * off all the arena's pools for the first |
| 914 | * time. |
| 915 | */ |
| 916 | assert(usable_arenas->freepools != NULL || |
| 917 | usable_arenas->pool_address <= |
| 918 | (block*)usable_arenas->address + |
| 919 | ARENA_SIZE - POOL_SIZE); |
| 920 | } |
| 921 | init_pool: |
| 922 | /* Frontlink to used pools. */ |
| 923 | next = usedpools[size + size]; /* == prev */ |
| 924 | pool->nextpool = next; |
| 925 | pool->prevpool = next; |
| 926 | next->nextpool = pool; |
| 927 | next->prevpool = pool; |
| 928 | pool->ref.count = 1; |
| 929 | if (pool->szidx == size) { |
| 930 | /* Luckily, this pool last contained blocks |
| 931 | * of the same size class, so its header |
| 932 | * and free list are already initialized. |
| 933 | */ |
| 934 | bp = pool->freeblock; |
| 935 | pool->freeblock = *(block **)bp; |
| 936 | UNLOCK(); |
| 937 | return (void *)bp; |
| 938 | } |
| 939 | /* |
| 940 | * Initialize the pool header, set up the free list to |
| 941 | * contain just the second block, and return the first |
| 942 | * block. |
| 943 | */ |
| 944 | pool->szidx = size; |
| 945 | size = INDEX2SIZE(size); |
| 946 | bp = (block *)pool + POOL_OVERHEAD; |
| 947 | pool->nextoffset = POOL_OVERHEAD + (size << 1); |
| 948 | pool->maxnextoffset = POOL_SIZE - size; |
| 949 | pool->freeblock = bp + size; |
| 950 | *(block **)(pool->freeblock) = NULL; |
| 951 | UNLOCK(); |
| 952 | return (void *)bp; |
| 953 | } |
| 954 | |
| 955 | /* Carve off a new pool. */ |
| 956 | assert(usable_arenas->nfreepools > 0); |
| 957 | assert(usable_arenas->freepools == NULL); |
| 958 | pool = (poolp)usable_arenas->pool_address; |
| 959 | assert((block*)pool <= (block*)usable_arenas->address + |
| 960 | ARENA_SIZE - POOL_SIZE); |
| 961 | pool->arenaindex = usable_arenas - arenas; |
| 962 | assert(&arenas[pool->arenaindex] == usable_arenas); |
| 963 | pool->szidx = DUMMY_SIZE_IDX; |
| 964 | usable_arenas->pool_address += POOL_SIZE; |
| 965 | --usable_arenas->nfreepools; |
| 966 | |
| 967 | if (usable_arenas->nfreepools == 0) { |
| 968 | assert(usable_arenas->nextarena == NULL || |
| 969 | usable_arenas->nextarena->prevarena == |
| 970 | usable_arenas); |
| 971 | /* Unlink the arena: it is completely allocated. */ |
| 972 | usable_arenas = usable_arenas->nextarena; |
| 973 | if (usable_arenas != NULL) { |
| 974 | usable_arenas->prevarena = NULL; |
| 975 | assert(usable_arenas->address != 0); |
| 976 | } |
| 977 | } |
| 978 | |
| 979 | goto init_pool; |
| 980 | } |
| 981 | |
| 982 | /* The small block allocator ends here. */ |
| 983 | |
| 984 | redirect: |
| 985 | /* Redirect the original request to the underlying (libc) allocator. |
| 986 | * We jump here on bigger requests, on error in the code above (as a |
| 987 | * last chance to serve the request) or when the max memory limit |
| 988 | * has been reached. |
| 989 | */ |
| 990 | if (nbytes == 0) |
| 991 | nbytes = 1; |
| 992 | return (void *)malloc(nbytes); |
| 993 | } |
| 994 | |
| 995 | /* free */ |
| 996 | |
| 997 | #undef PyObject_Free |
| 998 | ATTRIBUTE_NO_ADDRESS_SAFETY_ANALYSIS |
| 999 | void |
| 1000 | PyObject_Free(void *p) |
| 1001 | { |
| 1002 | poolp pool; |
| 1003 | block *lastfree; |
| 1004 | poolp next, prev; |
| 1005 | uint size; |
| 1006 | #ifndef Py_USING_MEMORY_DEBUGGER |
| 1007 | uint arenaindex_temp; |
| 1008 | #endif |
| 1009 | |
| 1010 | if (p == NULL) /* free(NULL) has no effect */ |
| 1011 | return; |
| 1012 | |
| 1013 | #ifdef WITH_VALGRIND |
| 1014 | if (UNLIKELY(running_on_valgrind > 0)) |
| 1015 | goto redirect; |
| 1016 | #endif |
| 1017 | |
| 1018 | pool = POOL_ADDR(p); |
| 1019 | if (Py_ADDRESS_IN_RANGE(p, pool)) { |
| 1020 | /* We allocated this address. */ |
| 1021 | LOCK(); |
| 1022 | /* Link p to the start of the pool's freeblock list. Since |
| 1023 | * the pool had at least the p block outstanding, the pool |
| 1024 | * wasn't empty (so it's already in a usedpools[] list, or |
| 1025 | * was full and is in no list -- it's not in the freeblocks |
| 1026 | * list in any case). |
| 1027 | */ |
| 1028 | assert(pool->ref.count > 0); /* else it was empty */ |
| 1029 | *(block **)p = lastfree = pool->freeblock; |
| 1030 | pool->freeblock = (block *)p; |
| 1031 | if (lastfree) { |
| 1032 | struct arena_object* ao; |
| 1033 | uint nf; /* ao->nfreepools */ |
| 1034 | |
| 1035 | /* freeblock wasn't NULL, so the pool wasn't full, |
| 1036 | * and the pool is in a usedpools[] list. |
| 1037 | */ |
| 1038 | if (--pool->ref.count != 0) { |
| 1039 | /* pool isn't empty: leave it in usedpools */ |
| 1040 | UNLOCK(); |
| 1041 | return; |
| 1042 | } |
| 1043 | /* Pool is now empty: unlink from usedpools, and |
| 1044 | * link to the front of freepools. This ensures that |
| 1045 | * previously freed pools will be allocated later |
| 1046 | * (being not referenced, they are perhaps paged out). |
| 1047 | */ |
| 1048 | next = pool->nextpool; |
| 1049 | prev = pool->prevpool; |
| 1050 | next->prevpool = prev; |
| 1051 | prev->nextpool = next; |
| 1052 | |
| 1053 | /* Link the pool to freepools. This is a singly-linked |
| 1054 | * list, and pool->prevpool isn't used there. |
| 1055 | */ |
| 1056 | ao = &arenas[pool->arenaindex]; |
| 1057 | pool->nextpool = ao->freepools; |
| 1058 | ao->freepools = pool; |
| 1059 | nf = ++ao->nfreepools; |
| 1060 | |
| 1061 | /* All the rest is arena management. We just freed |
| 1062 | * a pool, and there are 4 cases for arena mgmt: |
| 1063 | * 1. If all the pools are free, return the arena to |
| 1064 | * the system free(). |
| 1065 | * 2. If this is the only free pool in the arena, |
| 1066 | * add the arena back to the `usable_arenas` list. |
| 1067 | * 3. If the "next" arena has a smaller count of free |
| 1068 | * pools, we have to "slide this arena right" to |
| 1069 | * restore that usable_arenas is sorted in order of |
| 1070 | * nfreepools. |
| 1071 | * 4. Else there's nothing more to do. |
| 1072 | */ |
| 1073 | if (nf == ao->ntotalpools) { |
| 1074 | /* Case 1. First unlink ao from usable_arenas. |
| 1075 | */ |
| 1076 | assert(ao->prevarena == NULL || |
| 1077 | ao->prevarena->address != 0); |
| 1078 | assert(ao ->nextarena == NULL || |
| 1079 | ao->nextarena->address != 0); |
| 1080 | |
| 1081 | /* Fix the pointer in the prevarena, or the |
| 1082 | * usable_arenas pointer. |
| 1083 | */ |
| 1084 | if (ao->prevarena == NULL) { |
| 1085 | usable_arenas = ao->nextarena; |
| 1086 | assert(usable_arenas == NULL || |
| 1087 | usable_arenas->address != 0); |
| 1088 | } |
| 1089 | else { |
| 1090 | assert(ao->prevarena->nextarena == ao); |
| 1091 | ao->prevarena->nextarena = |
| 1092 | ao->nextarena; |
| 1093 | } |
| 1094 | /* Fix the pointer in the nextarena. */ |
| 1095 | if (ao->nextarena != NULL) { |
| 1096 | assert(ao->nextarena->prevarena == ao); |
| 1097 | ao->nextarena->prevarena = |
| 1098 | ao->prevarena; |
| 1099 | } |
| 1100 | /* Record that this arena_object slot is |
| 1101 | * available to be reused. |
| 1102 | */ |
| 1103 | ao->nextarena = unused_arena_objects; |
| 1104 | unused_arena_objects = ao; |
| 1105 | |
| 1106 | /* Free the entire arena. */ |
| 1107 | #ifdef ARENAS_USE_MMAP |
| 1108 | munmap((void *)ao->address, ARENA_SIZE); |
| 1109 | #else |
| 1110 | free((void *)ao->address); |
| 1111 | #endif |
| 1112 | ao->address = 0; /* mark unassociated */ |
| 1113 | --narenas_currently_allocated; |
| 1114 | |
| 1115 | UNLOCK(); |
| 1116 | return; |
| 1117 | } |
| 1118 | if (nf == 1) { |
| 1119 | /* Case 2. Put ao at the head of |
| 1120 | * usable_arenas. Note that because |
| 1121 | * ao->nfreepools was 0 before, ao isn't |
| 1122 | * currently on the usable_arenas list. |
| 1123 | */ |
| 1124 | ao->nextarena = usable_arenas; |
| 1125 | ao->prevarena = NULL; |
| 1126 | if (usable_arenas) |
| 1127 | usable_arenas->prevarena = ao; |
| 1128 | usable_arenas = ao; |
| 1129 | assert(usable_arenas->address != 0); |
| 1130 | |
| 1131 | UNLOCK(); |
| 1132 | return; |
| 1133 | } |
| 1134 | /* If this arena is now out of order, we need to keep |
| 1135 | * the list sorted. The list is kept sorted so that |
| 1136 | * the "most full" arenas are used first, which allows |
| 1137 | * the nearly empty arenas to be completely freed. In |
| 1138 | * a few un-scientific tests, it seems like this |
| 1139 | * approach allowed a lot more memory to be freed. |
| 1140 | */ |
| 1141 | if (ao->nextarena == NULL || |
| 1142 | nf <= ao->nextarena->nfreepools) { |
| 1143 | /* Case 4. Nothing to do. */ |
| 1144 | UNLOCK(); |
| 1145 | return; |
| 1146 | } |
| 1147 | /* Case 3: We have to move the arena towards the end |
| 1148 | * of the list, because it has more free pools than |
| 1149 | * the arena to its right. |
| 1150 | * First unlink ao from usable_arenas. |
| 1151 | */ |
| 1152 | if (ao->prevarena != NULL) { |
| 1153 | /* ao isn't at the head of the list */ |
| 1154 | assert(ao->prevarena->nextarena == ao); |
| 1155 | ao->prevarena->nextarena = ao->nextarena; |
| 1156 | } |
| 1157 | else { |
| 1158 | /* ao is at the head of the list */ |
| 1159 | assert(usable_arenas == ao); |
| 1160 | usable_arenas = ao->nextarena; |
| 1161 | } |
| 1162 | ao->nextarena->prevarena = ao->prevarena; |
| 1163 | |
| 1164 | /* Locate the new insertion point by iterating over |
| 1165 | * the list, using our nextarena pointer. |
| 1166 | */ |
| 1167 | while (ao->nextarena != NULL && |
| 1168 | nf > ao->nextarena->nfreepools) { |
| 1169 | ao->prevarena = ao->nextarena; |
| 1170 | ao->nextarena = ao->nextarena->nextarena; |
| 1171 | } |
| 1172 | |
| 1173 | /* Insert ao at this point. */ |
| 1174 | assert(ao->nextarena == NULL || |
| 1175 | ao->prevarena == ao->nextarena->prevarena); |
| 1176 | assert(ao->prevarena->nextarena == ao->nextarena); |
| 1177 | |
| 1178 | ao->prevarena->nextarena = ao; |
| 1179 | if (ao->nextarena != NULL) |
| 1180 | ao->nextarena->prevarena = ao; |
| 1181 | |
| 1182 | /* Verify that the swaps worked. */ |
| 1183 | assert(ao->nextarena == NULL || |
| 1184 | nf <= ao->nextarena->nfreepools); |
| 1185 | assert(ao->prevarena == NULL || |
| 1186 | nf > ao->prevarena->nfreepools); |
| 1187 | assert(ao->nextarena == NULL || |
| 1188 | ao->nextarena->prevarena == ao); |
| 1189 | assert((usable_arenas == ao && |
| 1190 | ao->prevarena == NULL) || |
| 1191 | ao->prevarena->nextarena == ao); |
| 1192 | |
| 1193 | UNLOCK(); |
| 1194 | return; |
| 1195 | } |
| 1196 | /* Pool was full, so doesn't currently live in any list: |
| 1197 | * link it to the front of the appropriate usedpools[] list. |
| 1198 | * This mimics LRU pool usage for new allocations and |
| 1199 | * targets optimal filling when several pools contain |
| 1200 | * blocks of the same size class. |
| 1201 | */ |
| 1202 | --pool->ref.count; |
| 1203 | assert(pool->ref.count > 0); /* else the pool is empty */ |
| 1204 | size = pool->szidx; |
| 1205 | next = usedpools[size + size]; |
| 1206 | prev = next->prevpool; |
| 1207 | /* insert pool before next: prev <-> pool <-> next */ |
| 1208 | pool->nextpool = next; |
| 1209 | pool->prevpool = prev; |
| 1210 | next->prevpool = pool; |
| 1211 | prev->nextpool = pool; |
| 1212 | UNLOCK(); |
| 1213 | return; |
| 1214 | } |
| 1215 | |
| 1216 | #ifdef WITH_VALGRIND |
| 1217 | redirect: |
| 1218 | #endif |
| 1219 | /* We didn't allocate this address. */ |
| 1220 | free(p); |
| 1221 | } |
| 1222 | |
| 1223 | /* realloc. If p is NULL, this acts like malloc(nbytes). Else if nbytes==0, |
| 1224 | * then as the Python docs promise, we do not treat this like free(p), and |
| 1225 | * return a non-NULL result. |
| 1226 | */ |
| 1227 | |
| 1228 | #undef PyObject_Realloc |
| 1229 | ATTRIBUTE_NO_ADDRESS_SAFETY_ANALYSIS |
| 1230 | void * |
| 1231 | PyObject_Realloc(void *p, size_t nbytes) |
| 1232 | { |
| 1233 | void *bp; |
| 1234 | poolp pool; |
| 1235 | size_t size; |
| 1236 | #ifndef Py_USING_MEMORY_DEBUGGER |
| 1237 | uint arenaindex_temp; |
| 1238 | #endif |
| 1239 | |
| 1240 | if (p == NULL) |
| 1241 | return PyObject_Malloc(nbytes); |
| 1242 | |
| 1243 | /* |
| 1244 | * Limit ourselves to PY_SSIZE_T_MAX bytes to prevent security holes. |
| 1245 | * Most python internals blindly use a signed Py_ssize_t to track |
| 1246 | * things without checking for overflows or negatives. |
| 1247 | * As size_t is unsigned, checking for nbytes < 0 is not required. |
| 1248 | */ |
| 1249 | if (nbytes > PY_SSIZE_T_MAX) |
| 1250 | return NULL; |
| 1251 | |
| 1252 | #ifdef WITH_VALGRIND |
| 1253 | /* Treat running_on_valgrind == -1 the same as 0 */ |
| 1254 | if (UNLIKELY(running_on_valgrind > 0)) |
| 1255 | goto redirect; |
| 1256 | #endif |
| 1257 | |
| 1258 | pool = POOL_ADDR(p); |
| 1259 | if (Py_ADDRESS_IN_RANGE(p, pool)) { |
| 1260 | /* We're in charge of this block */ |
| 1261 | size = INDEX2SIZE(pool->szidx); |
| 1262 | if (nbytes <= size) { |
| 1263 | /* The block is staying the same or shrinking. If |
| 1264 | * it's shrinking, there's a tradeoff: it costs |
| 1265 | * cycles to copy the block to a smaller size class, |
| 1266 | * but it wastes memory not to copy it. The |
| 1267 | * compromise here is to copy on shrink only if at |
| 1268 | * least 25% of size can be shaved off. |
| 1269 | */ |
| 1270 | if (4 * nbytes > 3 * size) { |
| 1271 | /* It's the same, |
| 1272 | * or shrinking and new/old > 3/4. |
| 1273 | */ |
| 1274 | return p; |
| 1275 | } |
| 1276 | size = nbytes; |
| 1277 | } |
| 1278 | bp = PyObject_Malloc(nbytes); |
| 1279 | if (bp != NULL) { |
| 1280 | memcpy(bp, p, size); |
| 1281 | PyObject_Free(p); |
| 1282 | } |
| 1283 | return bp; |
| 1284 | } |
| 1285 | #ifdef WITH_VALGRIND |
| 1286 | redirect: |
| 1287 | #endif |
| 1288 | /* We're not managing this block. If nbytes <= |
| 1289 | * SMALL_REQUEST_THRESHOLD, it's tempting to try to take over this |
| 1290 | * block. However, if we do, we need to copy the valid data from |
| 1291 | * the C-managed block to one of our blocks, and there's no portable |
| 1292 | * way to know how much of the memory space starting at p is valid. |
| 1293 | * As bug 1185883 pointed out the hard way, it's possible that the |
| 1294 | * C-managed block is "at the end" of allocated VM space, so that |
| 1295 | * a memory fault can occur if we try to copy nbytes bytes starting |
| 1296 | * at p. Instead we punt: let C continue to manage this block. |
| 1297 | */ |
| 1298 | if (nbytes) |
| 1299 | return realloc(p, nbytes); |
| 1300 | /* C doesn't define the result of realloc(p, 0) (it may or may not |
| 1301 | * return NULL then), but Python's docs promise that nbytes==0 never |
| 1302 | * returns NULL. We don't pass 0 to realloc(), to avoid that endcase |
| 1303 | * to begin with. Even then, we can't be sure that realloc() won't |
| 1304 | * return NULL. |
| 1305 | */ |
| 1306 | bp = realloc(p, 1); |
| 1307 | return bp ? bp : p; |
| 1308 | } |
| 1309 | |
| 1310 | #else /* ! WITH_PYMALLOC */ |
| 1311 | |
| 1312 | /*==========================================================================*/ |
| 1313 | /* pymalloc not enabled: Redirect the entry points to malloc. These will |
| 1314 | * only be used by extensions that are compiled with pymalloc enabled. */ |
| 1315 | |
| 1316 | void * |
| 1317 | PyObject_Malloc(size_t n) |
| 1318 | { |
| 1319 | return PyMem_MALLOC(n); |
| 1320 | } |
| 1321 | |
| 1322 | void * |
| 1323 | PyObject_Realloc(void *p, size_t n) |
| 1324 | { |
| 1325 | return PyMem_REALLOC(p, n); |
| 1326 | } |
| 1327 | |
| 1328 | void |
| 1329 | PyObject_Free(void *p) |
| 1330 | { |
| 1331 | PyMem_FREE(p); |
| 1332 | } |
| 1333 | #endif /* WITH_PYMALLOC */ |
| 1334 | |
| 1335 | #ifdef PYMALLOC_DEBUG |
| 1336 | /*==========================================================================*/ |
| 1337 | /* A x-platform debugging allocator. This doesn't manage memory directly, |
| 1338 | * it wraps a real allocator, adding extra debugging info to the memory blocks. |
| 1339 | */ |
| 1340 | |
| 1341 | /* Special bytes broadcast into debug memory blocks at appropriate times. |
| 1342 | * Strings of these are unlikely to be valid addresses, floats, ints or |
| 1343 | * 7-bit ASCII. |
| 1344 | */ |
| 1345 | #undef CLEANBYTE |
| 1346 | #undef DEADBYTE |
| 1347 | #undef FORBIDDENBYTE |
| 1348 | #define CLEANBYTE 0xCB /* clean (newly allocated) memory */ |
| 1349 | #define DEADBYTE 0xDB /* dead (newly freed) memory */ |
| 1350 | #define FORBIDDENBYTE 0xFB /* untouchable bytes at each end of a block */ |
| 1351 | |
| 1352 | /* We tag each block with an API ID in order to tag API violations */ |
| 1353 | #define _PYMALLOC_MEM_ID 'm' /* the PyMem_Malloc() API */ |
| 1354 | #define _PYMALLOC_OBJ_ID 'o' /* The PyObject_Malloc() API */ |
| 1355 | |
| 1356 | static size_t serialno = 0; /* incremented on each debug {m,re}alloc */ |
| 1357 | |
| 1358 | /* serialno is always incremented via calling this routine. The point is |
| 1359 | * to supply a single place to set a breakpoint. |
| 1360 | */ |
| 1361 | static void |
| 1362 | bumpserialno(void) |
| 1363 | { |
| 1364 | ++serialno; |
| 1365 | } |
| 1366 | |
| 1367 | #define SST SIZEOF_SIZE_T |
| 1368 | |
| 1369 | /* Read sizeof(size_t) bytes at p as a big-endian size_t. */ |
| 1370 | static size_t |
| 1371 | read_size_t(const void *p) |
| 1372 | { |
| 1373 | const uchar *q = (const uchar *)p; |
| 1374 | size_t result = *q++; |
| 1375 | int i; |
| 1376 | |
| 1377 | for (i = SST; --i > 0; ++q) |
| 1378 | result = (result << 8) | *q; |
| 1379 | return result; |
| 1380 | } |
| 1381 | |
| 1382 | /* Write n as a big-endian size_t, MSB at address p, LSB at |
| 1383 | * p + sizeof(size_t) - 1. |
| 1384 | */ |
| 1385 | static void |
| 1386 | write_size_t(void *p, size_t n) |
| 1387 | { |
| 1388 | uchar *q = (uchar *)p + SST - 1; |
| 1389 | int i; |
| 1390 | |
| 1391 | for (i = SST; --i >= 0; --q) { |
| 1392 | *q = (uchar)(n & 0xff); |
| 1393 | n >>= 8; |
| 1394 | } |
| 1395 | } |
| 1396 | |
| 1397 | #ifdef Py_DEBUG |
| 1398 | /* Is target in the list? The list is traversed via the nextpool pointers. |
| 1399 | * The list may be NULL-terminated, or circular. Return 1 if target is in |
| 1400 | * list, else 0. |
| 1401 | */ |
| 1402 | static int |
| 1403 | pool_is_in_list(const poolp target, poolp list) |
| 1404 | { |
| 1405 | poolp origlist = list; |
| 1406 | assert(target != NULL); |
| 1407 | if (list == NULL) |
| 1408 | return 0; |
| 1409 | do { |
| 1410 | if (target == list) |
| 1411 | return 1; |
| 1412 | list = list->nextpool; |
| 1413 | } while (list != NULL && list != origlist); |
| 1414 | return 0; |
| 1415 | } |
| 1416 | |
| 1417 | #else |
| 1418 | #define pool_is_in_list(X, Y) 1 |
| 1419 | |
| 1420 | #endif /* Py_DEBUG */ |
| 1421 | |
| 1422 | static void * |
| 1423 | _PyMem_Malloc(size_t nbytes) |
| 1424 | { |
| 1425 | if (nbytes > (size_t)PY_SSIZE_T_MAX) { |
| 1426 | return NULL; |
| 1427 | } |
| 1428 | if (nbytes == 0) { |
| 1429 | nbytes = 1; |
| 1430 | } |
| 1431 | return malloc(nbytes); |
| 1432 | } |
| 1433 | |
| 1434 | static void * |
| 1435 | _PyMem_Realloc(void *p, size_t nbytes) |
| 1436 | { |
| 1437 | if (nbytes > (size_t)PY_SSIZE_T_MAX) { |
| 1438 | return NULL; |
| 1439 | } |
| 1440 | if (nbytes == 0) { |
| 1441 | nbytes = 1; |
| 1442 | } |
| 1443 | return realloc(p, nbytes); |
| 1444 | } |
| 1445 | |
| 1446 | |
| 1447 | static void |
| 1448 | _PyMem_Free(void *p) |
| 1449 | { |
| 1450 | free(p); |
| 1451 | } |
| 1452 | |
| 1453 | |
| 1454 | /* Let S = sizeof(size_t). The debug malloc asks for 4*S extra bytes and |
| 1455 | fills them with useful stuff, here calling the underlying malloc's result p: |
| 1456 | |
| 1457 | p[0: S] |
| 1458 | Number of bytes originally asked for. This is a size_t, big-endian (easier |
| 1459 | to read in a memory dump). |
| 1460 | p[S: 2*S] |
| 1461 | Copies of FORBIDDENBYTE. Used to catch under- writes and reads. |
| 1462 | p[2*S: 2*S+n] |
| 1463 | The requested memory, filled with copies of CLEANBYTE. |
| 1464 | Used to catch reference to uninitialized memory. |
| 1465 | &p[2*S] is returned. Note that this is 8-byte aligned if pymalloc |
| 1466 | handled the request itself. |
| 1467 | p[2*S+n: 2*S+n+S] |
| 1468 | Copies of FORBIDDENBYTE. Used to catch over- writes and reads. |
| 1469 | p[2*S+n+S: 2*S+n+2*S] |
| 1470 | A serial number, incremented by 1 on each call to _PyObject_DebugMalloc |
| 1471 | and _PyObject_DebugRealloc. |
| 1472 | This is a big-endian size_t. |
| 1473 | If "bad memory" is detected later, the serial number gives an |
| 1474 | excellent way to set a breakpoint on the next run, to capture the |
| 1475 | instant at which this block was passed out. |
| 1476 | */ |
| 1477 | |
| 1478 | /* debug replacements for the PyMem_* memory API */ |
| 1479 | void * |
| 1480 | _PyMem_DebugMalloc(size_t nbytes) |
| 1481 | { |
| 1482 | return _PyObject_DebugMallocApi(_PYMALLOC_MEM_ID, nbytes); |
| 1483 | } |
| 1484 | void * |
| 1485 | _PyMem_DebugRealloc(void *p, size_t nbytes) |
| 1486 | { |
| 1487 | return _PyObject_DebugReallocApi(_PYMALLOC_MEM_ID, p, nbytes); |
| 1488 | } |
| 1489 | void |
| 1490 | _PyMem_DebugFree(void *p) |
| 1491 | { |
| 1492 | _PyObject_DebugFreeApi(_PYMALLOC_MEM_ID, p); |
| 1493 | } |
| 1494 | |
| 1495 | /* debug replacements for the PyObject_* memory API */ |
| 1496 | void * |
| 1497 | _PyObject_DebugMalloc(size_t nbytes) |
| 1498 | { |
| 1499 | return _PyObject_DebugMallocApi(_PYMALLOC_OBJ_ID, nbytes); |
| 1500 | } |
| 1501 | void * |
| 1502 | _PyObject_DebugRealloc(void *p, size_t nbytes) |
| 1503 | { |
| 1504 | return _PyObject_DebugReallocApi(_PYMALLOC_OBJ_ID, p, nbytes); |
| 1505 | } |
| 1506 | void |
| 1507 | _PyObject_DebugFree(void *p) |
| 1508 | { |
| 1509 | _PyObject_DebugFreeApi(_PYMALLOC_OBJ_ID, p); |
| 1510 | } |
| 1511 | void |
| 1512 | _PyObject_DebugCheckAddress(const void *p) |
| 1513 | { |
| 1514 | _PyObject_DebugCheckAddressApi(_PYMALLOC_OBJ_ID, p); |
| 1515 | } |
| 1516 | |
| 1517 | |
| 1518 | /* generic debug memory api, with an "id" to identify the API in use */ |
| 1519 | void * |
| 1520 | _PyObject_DebugMallocApi(char api, size_t nbytes) |
| 1521 | { |
| 1522 | uchar *p; /* base address of malloc'ed block */ |
| 1523 | uchar *tail; /* p + 2*SST + nbytes == pointer to tail pad bytes */ |
| 1524 | size_t total; /* nbytes + 4*SST */ |
| 1525 | |
| 1526 | bumpserialno(); |
| 1527 | total = nbytes + 4*SST; |
| 1528 | if (total < nbytes) |
| 1529 | /* overflow: can't represent total as a size_t */ |
| 1530 | return NULL; |
| 1531 | |
| 1532 | if (api == _PYMALLOC_OBJ_ID) { |
| 1533 | p = (uchar *)PyObject_Malloc(total); |
| 1534 | } |
| 1535 | else { |
| 1536 | p = (uchar *)_PyMem_Malloc(total); |
| 1537 | } |
| 1538 | if (p == NULL) |
| 1539 | return NULL; |
| 1540 | |
| 1541 | /* at p, write size (SST bytes), api (1 byte), pad (SST-1 bytes) */ |
| 1542 | write_size_t(p, nbytes); |
| 1543 | p[SST] = (uchar)api; |
| 1544 | memset(p + SST + 1 , FORBIDDENBYTE, SST-1); |
| 1545 | |
| 1546 | if (nbytes > 0) |
| 1547 | memset(p + 2*SST, CLEANBYTE, nbytes); |
| 1548 | |
| 1549 | /* at tail, write pad (SST bytes) and serialno (SST bytes) */ |
| 1550 | tail = p + 2*SST + nbytes; |
| 1551 | memset(tail, FORBIDDENBYTE, SST); |
| 1552 | write_size_t(tail + SST, serialno); |
| 1553 | |
| 1554 | return p + 2*SST; |
| 1555 | } |
| 1556 | |
| 1557 | /* The debug free first checks the 2*SST bytes on each end for sanity (in |
| 1558 | particular, that the FORBIDDENBYTEs with the api ID are still intact). |
| 1559 | Then fills the original bytes with DEADBYTE. |
| 1560 | Then calls the underlying free. |
| 1561 | */ |
| 1562 | void |
| 1563 | _PyObject_DebugFreeApi(char api, void *p) |
| 1564 | { |
| 1565 | uchar *q = (uchar *)p - 2*SST; /* address returned from malloc */ |
| 1566 | size_t nbytes; |
| 1567 | |
| 1568 | if (p == NULL) |
| 1569 | return; |
| 1570 | _PyObject_DebugCheckAddressApi(api, p); |
| 1571 | nbytes = read_size_t(q); |
| 1572 | nbytes += 4*SST; |
| 1573 | if (nbytes > 0) |
| 1574 | memset(q, DEADBYTE, nbytes); |
| 1575 | if (api == _PYMALLOC_OBJ_ID) { |
| 1576 | PyObject_Free(q); |
| 1577 | } |
| 1578 | else { |
| 1579 | _PyMem_Free(q); |
| 1580 | } |
| 1581 | } |
| 1582 | |
| 1583 | void * |
| 1584 | _PyObject_DebugReallocApi(char api, void *p, size_t nbytes) |
| 1585 | { |
| 1586 | uchar *q = (uchar *)p; |
| 1587 | uchar *tail; |
| 1588 | size_t total; /* nbytes + 4*SST */ |
| 1589 | size_t original_nbytes; |
| 1590 | int i; |
| 1591 | |
| 1592 | if (p == NULL) |
| 1593 | return _PyObject_DebugMallocApi(api, nbytes); |
| 1594 | |
| 1595 | _PyObject_DebugCheckAddressApi(api, p); |
| 1596 | bumpserialno(); |
| 1597 | original_nbytes = read_size_t(q - 2*SST); |
| 1598 | total = nbytes + 4*SST; |
| 1599 | if (total < nbytes) |
| 1600 | /* overflow: can't represent total as a size_t */ |
| 1601 | return NULL; |
| 1602 | |
| 1603 | if (nbytes <= original_nbytes) { |
| 1604 | /* shrinking: mark old extra memory dead */ |
| 1605 | memset(q + nbytes, DEADBYTE, original_nbytes - nbytes + 2*SST); |
| 1606 | } |
| 1607 | |
| 1608 | /* Resize and add decorations. We may get a new pointer here, in which |
| 1609 | * case we didn't get the chance to mark the old memory with DEADBYTE, |
| 1610 | * but we live with that. |
| 1611 | */ |
| 1612 | if (api == _PYMALLOC_OBJ_ID) { |
| 1613 | q = (uchar *)PyObject_Realloc(q - 2*SST, total); |
| 1614 | } |
| 1615 | else { |
| 1616 | q = (uchar *)_PyMem_Realloc(q - 2*SST, total); |
| 1617 | } |
| 1618 | if (q == NULL) { |
| 1619 | if (nbytes <= original_nbytes) { |
| 1620 | /* bpo-31626: the memset() above expects that realloc never fails |
| 1621 | on shrinking a memory block. */ |
| 1622 | Py_FatalError("Shrinking reallocation failed"); |
| 1623 | } |
| 1624 | return NULL; |
| 1625 | } |
| 1626 | |
| 1627 | write_size_t(q, nbytes); |
| 1628 | assert(q[SST] == (uchar)api); |
| 1629 | for (i = 1; i < SST; ++i) |
| 1630 | assert(q[SST + i] == FORBIDDENBYTE); |
| 1631 | q += 2*SST; |
| 1632 | tail = q + nbytes; |
| 1633 | memset(tail, FORBIDDENBYTE, SST); |
| 1634 | write_size_t(tail + SST, serialno); |
| 1635 | |
| 1636 | if (nbytes > original_nbytes) { |
| 1637 | /* growing: mark new extra memory clean */ |
| 1638 | memset(q + original_nbytes, CLEANBYTE, |
| 1639 | nbytes - original_nbytes); |
| 1640 | } |
| 1641 | |
| 1642 | return q; |
| 1643 | } |
| 1644 | |
| 1645 | /* Check the forbidden bytes on both ends of the memory allocated for p. |
| 1646 | * If anything is wrong, print info to stderr via _PyObject_DebugDumpAddress, |
| 1647 | * and call Py_FatalError to kill the program. |
| 1648 | * The API id, is also checked. |
| 1649 | */ |
| 1650 | void |
| 1651 | _PyObject_DebugCheckAddressApi(char api, const void *p) |
| 1652 | { |
| 1653 | const uchar *q = (const uchar *)p; |
| 1654 | char msgbuf[64]; |
| 1655 | char *msg; |
| 1656 | size_t nbytes; |
| 1657 | const uchar *tail; |
| 1658 | int i; |
| 1659 | char id; |
| 1660 | |
| 1661 | if (p == NULL) { |
| 1662 | msg = "didn't expect a NULL pointer"; |
| 1663 | goto error; |
| 1664 | } |
| 1665 | |
| 1666 | /* Check the API id */ |
| 1667 | id = (char)q[-SST]; |
| 1668 | if (id != api) { |
| 1669 | msg = msgbuf; |
| 1670 | snprintf(msg, sizeof(msgbuf), "bad ID: Allocated using API '%c', verified using API '%c'", id, api); |
| 1671 | msgbuf[sizeof(msgbuf)-1] = 0; |
| 1672 | goto error; |
| 1673 | } |
| 1674 | |
| 1675 | /* Check the stuff at the start of p first: if there's underwrite |
| 1676 | * corruption, the number-of-bytes field may be nuts, and checking |
| 1677 | * the tail could lead to a segfault then. |
| 1678 | */ |
| 1679 | for (i = SST-1; i >= 1; --i) { |
| 1680 | if (*(q-i) != FORBIDDENBYTE) { |
| 1681 | msg = "bad leading pad byte"; |
| 1682 | goto error; |
| 1683 | } |
| 1684 | } |
| 1685 | |
| 1686 | nbytes = read_size_t(q - 2*SST); |
| 1687 | tail = q + nbytes; |
| 1688 | for (i = 0; i < SST; ++i) { |
| 1689 | if (tail[i] != FORBIDDENBYTE) { |
| 1690 | msg = "bad trailing pad byte"; |
| 1691 | goto error; |
| 1692 | } |
| 1693 | } |
| 1694 | |
| 1695 | return; |
| 1696 | |
| 1697 | error: |
| 1698 | _PyObject_DebugDumpAddress(p); |
| 1699 | Py_FatalError(msg); |
| 1700 | } |
| 1701 | |
| 1702 | /* Display info to stderr about the memory block at p. */ |
| 1703 | void |
| 1704 | _PyObject_DebugDumpAddress(const void *p) |
| 1705 | { |
| 1706 | const uchar *q = (const uchar *)p; |
| 1707 | const uchar *tail; |
| 1708 | size_t nbytes, serial; |
| 1709 | int i; |
| 1710 | int ok; |
| 1711 | char id; |
| 1712 | |
| 1713 | fprintf(stderr, "Debug memory block at address p=%p:", p); |
| 1714 | if (p == NULL) { |
| 1715 | fprintf(stderr, "\n"); |
| 1716 | return; |
| 1717 | } |
| 1718 | id = (char)q[-SST]; |
| 1719 | fprintf(stderr, " API '%c'\n", id); |
| 1720 | |
| 1721 | nbytes = read_size_t(q - 2*SST); |
| 1722 | fprintf(stderr, " %" PY_FORMAT_SIZE_T "u bytes originally " |
| 1723 | "requested\n", nbytes); |
| 1724 | |
| 1725 | /* In case this is nuts, check the leading pad bytes first. */ |
| 1726 | fprintf(stderr, " The %d pad bytes at p-%d are ", SST-1, SST-1); |
| 1727 | ok = 1; |
| 1728 | for (i = 1; i <= SST-1; ++i) { |
| 1729 | if (*(q-i) != FORBIDDENBYTE) { |
| 1730 | ok = 0; |
| 1731 | break; |
| 1732 | } |
| 1733 | } |
| 1734 | if (ok) |
| 1735 | fputs("FORBIDDENBYTE, as expected.\n", stderr); |
| 1736 | else { |
| 1737 | fprintf(stderr, "not all FORBIDDENBYTE (0x%02x):\n", |
| 1738 | FORBIDDENBYTE); |
| 1739 | for (i = SST-1; i >= 1; --i) { |
| 1740 | const uchar byte = *(q-i); |
| 1741 | fprintf(stderr, " at p-%d: 0x%02x", i, byte); |
| 1742 | if (byte != FORBIDDENBYTE) |
| 1743 | fputs(" *** OUCH", stderr); |
| 1744 | fputc('\n', stderr); |
| 1745 | } |
| 1746 | |
| 1747 | fputs(" Because memory is corrupted at the start, the " |
| 1748 | "count of bytes requested\n" |
| 1749 | " may be bogus, and checking the trailing pad " |
| 1750 | "bytes may segfault.\n", stderr); |
| 1751 | } |
| 1752 | |
| 1753 | tail = q + nbytes; |
| 1754 | fprintf(stderr, " The %d pad bytes at tail=%p are ", SST, tail); |
| 1755 | ok = 1; |
| 1756 | for (i = 0; i < SST; ++i) { |
| 1757 | if (tail[i] != FORBIDDENBYTE) { |
| 1758 | ok = 0; |
| 1759 | break; |
| 1760 | } |
| 1761 | } |
| 1762 | if (ok) |
| 1763 | fputs("FORBIDDENBYTE, as expected.\n", stderr); |
| 1764 | else { |
| 1765 | fprintf(stderr, "not all FORBIDDENBYTE (0x%02x):\n", |
| 1766 | FORBIDDENBYTE); |
| 1767 | for (i = 0; i < SST; ++i) { |
| 1768 | const uchar byte = tail[i]; |
| 1769 | fprintf(stderr, " at tail+%d: 0x%02x", |
| 1770 | i, byte); |
| 1771 | if (byte != FORBIDDENBYTE) |
| 1772 | fputs(" *** OUCH", stderr); |
| 1773 | fputc('\n', stderr); |
| 1774 | } |
| 1775 | } |
| 1776 | |
| 1777 | serial = read_size_t(tail + SST); |
| 1778 | fprintf(stderr, " The block was made by call #%" PY_FORMAT_SIZE_T |
| 1779 | "u to debug malloc/realloc.\n", serial); |
| 1780 | |
| 1781 | if (nbytes > 0) { |
| 1782 | i = 0; |
| 1783 | fputs(" Data at p:", stderr); |
| 1784 | /* print up to 8 bytes at the start */ |
| 1785 | while (q < tail && i < 8) { |
| 1786 | fprintf(stderr, " %02x", *q); |
| 1787 | ++i; |
| 1788 | ++q; |
| 1789 | } |
| 1790 | /* and up to 8 at the end */ |
| 1791 | if (q < tail) { |
| 1792 | if (tail - q > 8) { |
| 1793 | fputs(" ...", stderr); |
| 1794 | q = tail - 8; |
| 1795 | } |
| 1796 | while (q < tail) { |
| 1797 | fprintf(stderr, " %02x", *q); |
| 1798 | ++q; |
| 1799 | } |
| 1800 | } |
| 1801 | fputc('\n', stderr); |
| 1802 | } |
| 1803 | } |
| 1804 | |
| 1805 | static size_t |
| 1806 | printone(const char* msg, size_t value) |
| 1807 | { |
| 1808 | int i, k; |
| 1809 | char buf[100]; |
| 1810 | size_t origvalue = value; |
| 1811 | |
| 1812 | fputs(msg, stderr); |
| 1813 | for (i = (int)strlen(msg); i < 35; ++i) |
| 1814 | fputc(' ', stderr); |
| 1815 | fputc('=', stderr); |
| 1816 | |
| 1817 | /* Write the value with commas. */ |
| 1818 | i = 22; |
| 1819 | buf[i--] = '\0'; |
| 1820 | buf[i--] = '\n'; |
| 1821 | k = 3; |
| 1822 | do { |
| 1823 | size_t nextvalue = value / 10; |
| 1824 | unsigned int digit = (unsigned int)(value - nextvalue * 10); |
| 1825 | value = nextvalue; |
| 1826 | buf[i--] = (char)(digit + '0'); |
| 1827 | --k; |
| 1828 | if (k == 0 && value && i >= 0) { |
| 1829 | k = 3; |
| 1830 | buf[i--] = ','; |
| 1831 | } |
| 1832 | } while (value && i >= 0); |
| 1833 | |
| 1834 | while (i >= 0) |
| 1835 | buf[i--] = ' '; |
| 1836 | fputs(buf, stderr); |
| 1837 | |
| 1838 | return origvalue; |
| 1839 | } |
| 1840 | |
| 1841 | /* Print summary info to stderr about the state of pymalloc's structures. |
| 1842 | * In Py_DEBUG mode, also perform some expensive internal consistency |
| 1843 | * checks. |
| 1844 | */ |
| 1845 | void |
| 1846 | _PyObject_DebugMallocStats(void) |
| 1847 | { |
| 1848 | uint i; |
| 1849 | const uint numclasses = SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT; |
| 1850 | /* # of pools, allocated blocks, and free blocks per class index */ |
| 1851 | size_t numpools[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT]; |
| 1852 | size_t numblocks[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT]; |
| 1853 | size_t numfreeblocks[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT]; |
| 1854 | /* total # of allocated bytes in used and full pools */ |
| 1855 | size_t allocated_bytes = 0; |
| 1856 | /* total # of available bytes in used pools */ |
| 1857 | size_t available_bytes = 0; |
| 1858 | /* # of free pools + pools not yet carved out of current arena */ |
| 1859 | uint numfreepools = 0; |
| 1860 | /* # of bytes for arena alignment padding */ |
| 1861 | size_t arena_alignment = 0; |
| 1862 | /* # of bytes in used and full pools used for pool_headers */ |
| 1863 | size_t pool_header_bytes = 0; |
| 1864 | /* # of bytes in used and full pools wasted due to quantization, |
| 1865 | * i.e. the necessarily leftover space at the ends of used and |
| 1866 | * full pools. |
| 1867 | */ |
| 1868 | size_t quantization = 0; |
| 1869 | /* # of arenas actually allocated. */ |
| 1870 | size_t narenas = 0; |
| 1871 | /* running total -- should equal narenas * ARENA_SIZE */ |
| 1872 | size_t total; |
| 1873 | char buf[128]; |
| 1874 | |
| 1875 | fprintf(stderr, "Small block threshold = %d, in %u size classes.\n", |
| 1876 | SMALL_REQUEST_THRESHOLD, numclasses); |
| 1877 | |
| 1878 | for (i = 0; i < numclasses; ++i) |
| 1879 | numpools[i] = numblocks[i] = numfreeblocks[i] = 0; |
| 1880 | |
| 1881 | /* Because full pools aren't linked to from anything, it's easiest |
| 1882 | * to march over all the arenas. If we're lucky, most of the memory |
| 1883 | * will be living in full pools -- would be a shame to miss them. |
| 1884 | */ |
| 1885 | for (i = 0; i < maxarenas; ++i) { |
| 1886 | uint j; |
| 1887 | uptr base = arenas[i].address; |
| 1888 | |
| 1889 | /* Skip arenas which are not allocated. */ |
| 1890 | if (arenas[i].address == (uptr)NULL) |
| 1891 | continue; |
| 1892 | narenas += 1; |
| 1893 | |
| 1894 | numfreepools += arenas[i].nfreepools; |
| 1895 | |
| 1896 | /* round up to pool alignment */ |
| 1897 | if (base & (uptr)POOL_SIZE_MASK) { |
| 1898 | arena_alignment += POOL_SIZE; |
| 1899 | base &= ~(uptr)POOL_SIZE_MASK; |
| 1900 | base += POOL_SIZE; |
| 1901 | } |
| 1902 | |
| 1903 | /* visit every pool in the arena */ |
| 1904 | assert(base <= (uptr) arenas[i].pool_address); |
| 1905 | for (j = 0; |
| 1906 | base < (uptr) arenas[i].pool_address; |
| 1907 | ++j, base += POOL_SIZE) { |
| 1908 | poolp p = (poolp)base; |
| 1909 | const uint sz = p->szidx; |
| 1910 | uint freeblocks; |
| 1911 | |
| 1912 | if (p->ref.count == 0) { |
| 1913 | /* currently unused */ |
| 1914 | assert(pool_is_in_list(p, arenas[i].freepools)); |
| 1915 | continue; |
| 1916 | } |
| 1917 | ++numpools[sz]; |
| 1918 | numblocks[sz] += p->ref.count; |
| 1919 | freeblocks = NUMBLOCKS(sz) - p->ref.count; |
| 1920 | numfreeblocks[sz] += freeblocks; |
| 1921 | #ifdef Py_DEBUG |
| 1922 | if (freeblocks > 0) |
| 1923 | assert(pool_is_in_list(p, usedpools[sz + sz])); |
| 1924 | #endif |
| 1925 | } |
| 1926 | } |
| 1927 | assert(narenas == narenas_currently_allocated); |
| 1928 | |
| 1929 | fputc('\n', stderr); |
| 1930 | fputs("class size num pools blocks in use avail blocks\n" |
| 1931 | "----- ---- --------- ------------- ------------\n", |
| 1932 | stderr); |
| 1933 | |
| 1934 | for (i = 0; i < numclasses; ++i) { |
| 1935 | size_t p = numpools[i]; |
| 1936 | size_t b = numblocks[i]; |
| 1937 | size_t f = numfreeblocks[i]; |
| 1938 | uint size = INDEX2SIZE(i); |
| 1939 | if (p == 0) { |
| 1940 | assert(b == 0 && f == 0); |
| 1941 | continue; |
| 1942 | } |
| 1943 | fprintf(stderr, "%5u %6u " |
| 1944 | "%11" PY_FORMAT_SIZE_T "u " |
| 1945 | "%15" PY_FORMAT_SIZE_T "u " |
| 1946 | "%13" PY_FORMAT_SIZE_T "u\n", |
| 1947 | i, size, p, b, f); |
| 1948 | allocated_bytes += b * size; |
| 1949 | available_bytes += f * size; |
| 1950 | pool_header_bytes += p * POOL_OVERHEAD; |
| 1951 | quantization += p * ((POOL_SIZE - POOL_OVERHEAD) % size); |
| 1952 | } |
| 1953 | fputc('\n', stderr); |
| 1954 | (void)printone("# times object malloc called", serialno); |
| 1955 | |
| 1956 | (void)printone("# arenas allocated total", ntimes_arena_allocated); |
| 1957 | (void)printone("# arenas reclaimed", ntimes_arena_allocated - narenas); |
| 1958 | (void)printone("# arenas highwater mark", narenas_highwater); |
| 1959 | (void)printone("# arenas allocated current", narenas); |
| 1960 | |
| 1961 | PyOS_snprintf(buf, sizeof(buf), |
| 1962 | "%" PY_FORMAT_SIZE_T "u arenas * %d bytes/arena", |
| 1963 | narenas, ARENA_SIZE); |
| 1964 | (void)printone(buf, narenas * ARENA_SIZE); |
| 1965 | |
| 1966 | fputc('\n', stderr); |
| 1967 | |
| 1968 | total = printone("# bytes in allocated blocks", allocated_bytes); |
| 1969 | total += printone("# bytes in available blocks", available_bytes); |
| 1970 | |
| 1971 | PyOS_snprintf(buf, sizeof(buf), |
| 1972 | "%u unused pools * %d bytes", numfreepools, POOL_SIZE); |
| 1973 | total += printone(buf, (size_t)numfreepools * POOL_SIZE); |
| 1974 | |
| 1975 | total += printone("# bytes lost to pool headers", pool_header_bytes); |
| 1976 | total += printone("# bytes lost to quantization", quantization); |
| 1977 | total += printone("# bytes lost to arena alignment", arena_alignment); |
| 1978 | (void)printone("Total", total); |
| 1979 | } |
| 1980 | |
| 1981 | #endif /* PYMALLOC_DEBUG */ |
| 1982 | |
| 1983 | #ifdef Py_USING_MEMORY_DEBUGGER |
| 1984 | /* Make this function last so gcc won't inline it since the definition is |
| 1985 | * after the reference. |
| 1986 | */ |
| 1987 | int |
| 1988 | Py_ADDRESS_IN_RANGE(void *P, poolp pool) |
| 1989 | { |
| 1990 | uint arenaindex_temp = pool->arenaindex; |
| 1991 | |
| 1992 | return arenaindex_temp < maxarenas && |
| 1993 | (uptr)P - arenas[arenaindex_temp].address < (uptr)ARENA_SIZE && |
| 1994 | arenas[arenaindex_temp].address != 0; |
| 1995 | } |
| 1996 | #endif |