Silence the DeprecationWarning raised by importing mimetools in BaseHTTPServer.
[python.git] / Objects / obmalloc.c
blobda8f9c2d37af1277057300aa948ed27e7a813906
1 #include "Python.h"
3 #ifdef WITH_PYMALLOC
5 /* An object allocator for Python.
7 Here is an introduction to the layers of the Python memory architecture,
8 showing where the object allocator is actually used (layer +2), It is
9 called for every object allocation and deallocation (PyObject_New/Del),
10 unless the object-specific allocators implement a proprietary allocation
11 scheme (ex.: ints use a simple free list). This is also the place where
12 the cyclic garbage collector operates selectively on container objects.
15 Object-specific allocators
16 _____ ______ ______ ________
17 [ int ] [ dict ] [ list ] ... [ string ] Python core |
18 +3 | <----- Object-specific memory -----> | <-- Non-object memory --> |
19 _______________________________ | |
20 [ Python's object allocator ] | |
21 +2 | ####### Object memory ####### | <------ Internal buffers ------> |
22 ______________________________________________________________ |
23 [ Python's raw memory allocator (PyMem_ API) ] |
24 +1 | <----- Python memory (under PyMem manager's control) ------> | |
25 __________________________________________________________________
26 [ Underlying general-purpose allocator (ex: C library malloc) ]
27 0 | <------ Virtual memory allocated for the python process -------> |
29 =========================================================================
30 _______________________________________________________________________
31 [ OS-specific Virtual Memory Manager (VMM) ]
32 -1 | <--- Kernel dynamic storage allocation & management (page-based) ---> |
33 __________________________________ __________________________________
34 [ ] [ ]
35 -2 | <-- Physical memory: ROM/RAM --> | | <-- Secondary storage (swap) --> |
38 /*==========================================================================*/
40 /* A fast, special-purpose memory allocator for small blocks, to be used
41 on top of a general-purpose malloc -- heavily based on previous art. */
43 /* Vladimir Marangozov -- August 2000 */
46 * "Memory management is where the rubber meets the road -- if we do the wrong
47 * thing at any level, the results will not be good. And if we don't make the
48 * levels work well together, we are in serious trouble." (1)
50 * (1) Paul R. Wilson, Mark S. Johnstone, Michael Neely, and David Boles,
51 * "Dynamic Storage Allocation: A Survey and Critical Review",
52 * in Proc. 1995 Int'l. Workshop on Memory Management, September 1995.
55 /* #undef WITH_MEMORY_LIMITS */ /* disable mem limit checks */
57 /*==========================================================================*/
60 * Allocation strategy abstract:
62 * For small requests, the allocator sub-allocates <Big> blocks of memory.
63 * Requests greater than 256 bytes are routed to the system's allocator.
65 * Small requests are grouped in size classes spaced 8 bytes apart, due
66 * to the required valid alignment of the returned address. Requests of
67 * a particular size are serviced from memory pools of 4K (one VMM page).
68 * Pools are fragmented on demand and contain free lists of blocks of one
69 * particular size class. In other words, there is a fixed-size allocator
70 * for each size class. Free pools are shared by the different allocators
71 * thus minimizing the space reserved for a particular size class.
73 * This allocation strategy is a variant of what is known as "simple
74 * segregated storage based on array of free lists". The main drawback of
75 * simple segregated storage is that we might end up with lot of reserved
76 * memory for the different free lists, which degenerate in time. To avoid
77 * this, we partition each free list in pools and we share dynamically the
78 * reserved space between all free lists. This technique is quite efficient
79 * for memory intensive programs which allocate mainly small-sized blocks.
81 * For small requests we have the following table:
83 * Request in bytes Size of allocated block Size class idx
84 * ----------------------------------------------------------------
85 * 1-8 8 0
86 * 9-16 16 1
87 * 17-24 24 2
88 * 25-32 32 3
89 * 33-40 40 4
90 * 41-48 48 5
91 * 49-56 56 6
92 * 57-64 64 7
93 * 65-72 72 8
94 * ... ... ...
95 * 241-248 248 30
96 * 249-256 256 31
98 * 0, 257 and up: routed to the underlying allocator.
101 /*==========================================================================*/
104 * -- Main tunable settings section --
108 * Alignment of addresses returned to the user. 8-bytes alignment works
109 * on most current architectures (with 32-bit or 64-bit address busses).
110 * The alignment value is also used for grouping small requests in size
111 * classes spaced ALIGNMENT bytes apart.
113 * You shouldn't change this unless you know what you are doing.
115 #define ALIGNMENT 8 /* must be 2^N */
116 #define ALIGNMENT_SHIFT 3
117 #define ALIGNMENT_MASK (ALIGNMENT - 1)
119 /* Return the number of bytes in size class I, as a uint. */
120 #define INDEX2SIZE(I) (((uint)(I) + 1) << ALIGNMENT_SHIFT)
123 * Max size threshold below which malloc requests are considered to be
124 * small enough in order to use preallocated memory pools. You can tune
125 * this value according to your application behaviour and memory needs.
127 * The following invariants must hold:
128 * 1) ALIGNMENT <= SMALL_REQUEST_THRESHOLD <= 256
129 * 2) SMALL_REQUEST_THRESHOLD is evenly divisible by ALIGNMENT
131 * Although not required, for better performance and space efficiency,
132 * it is recommended that SMALL_REQUEST_THRESHOLD is set to a power of 2.
134 #define SMALL_REQUEST_THRESHOLD 256
135 #define NB_SMALL_SIZE_CLASSES (SMALL_REQUEST_THRESHOLD / ALIGNMENT)
138 * The system's VMM page size can be obtained on most unices with a
139 * getpagesize() call or deduced from various header files. To make
140 * things simpler, we assume that it is 4K, which is OK for most systems.
141 * It is probably better if this is the native page size, but it doesn't
142 * have to be. In theory, if SYSTEM_PAGE_SIZE is larger than the native page
143 * size, then `POOL_ADDR(p)->arenaindex' could rarely cause a segmentation
144 * violation fault. 4K is apparently OK for all the platforms that python
145 * currently targets.
147 #define SYSTEM_PAGE_SIZE (4 * 1024)
148 #define SYSTEM_PAGE_SIZE_MASK (SYSTEM_PAGE_SIZE - 1)
151 * Maximum amount of memory managed by the allocator for small requests.
153 #ifdef WITH_MEMORY_LIMITS
154 #ifndef SMALL_MEMORY_LIMIT
155 #define SMALL_MEMORY_LIMIT (64 * 1024 * 1024) /* 64 MB -- more? */
156 #endif
157 #endif
160 * The allocator sub-allocates <Big> blocks of memory (called arenas) aligned
161 * on a page boundary. This is a reserved virtual address space for the
162 * current process (obtained through a malloc call). In no way this means
163 * that the memory arenas will be used entirely. A malloc(<Big>) is usually
164 * an address range reservation for <Big> bytes, unless all pages within this
165 * space are referenced subsequently. So malloc'ing big blocks and not using
166 * them does not mean "wasting memory". It's an addressable range wastage...
168 * Therefore, allocating arenas with malloc is not optimal, because there is
169 * some address space wastage, but this is the most portable way to request
170 * memory from the system across various platforms.
172 #define ARENA_SIZE (256 << 10) /* 256KB */
174 #ifdef WITH_MEMORY_LIMITS
175 #define MAX_ARENAS (SMALL_MEMORY_LIMIT / ARENA_SIZE)
176 #endif
179 * Size of the pools used for small blocks. Should be a power of 2,
180 * between 1K and SYSTEM_PAGE_SIZE, that is: 1k, 2k, 4k.
182 #define POOL_SIZE SYSTEM_PAGE_SIZE /* must be 2^N */
183 #define POOL_SIZE_MASK SYSTEM_PAGE_SIZE_MASK
186 * -- End of tunable settings section --
189 /*==========================================================================*/
192 * Locking
194 * To reduce lock contention, it would probably be better to refine the
195 * crude function locking with per size class locking. I'm not positive
196 * however, whether it's worth switching to such locking policy because
197 * of the performance penalty it might introduce.
199 * The following macros describe the simplest (should also be the fastest)
200 * lock object on a particular platform and the init/fini/lock/unlock
201 * operations on it. The locks defined here are not expected to be recursive
202 * because it is assumed that they will always be called in the order:
203 * INIT, [LOCK, UNLOCK]*, FINI.
207 * Python's threads are serialized, so object malloc locking is disabled.
209 #define SIMPLELOCK_DECL(lock) /* simple lock declaration */
210 #define SIMPLELOCK_INIT(lock) /* allocate (if needed) and initialize */
211 #define SIMPLELOCK_FINI(lock) /* free/destroy an existing lock */
212 #define SIMPLELOCK_LOCK(lock) /* acquire released lock */
213 #define SIMPLELOCK_UNLOCK(lock) /* release acquired lock */
216 * Basic types
217 * I don't care if these are defined in <sys/types.h> or elsewhere. Axiom.
219 #undef uchar
220 #define uchar unsigned char /* assuming == 8 bits */
222 #undef uint
223 #define uint unsigned int /* assuming >= 16 bits */
225 #undef ulong
226 #define ulong unsigned long /* assuming >= 32 bits */
228 #undef uptr
229 #define uptr Py_uintptr_t
231 /* When you say memory, my mind reasons in terms of (pointers to) blocks */
232 typedef uchar block;
234 /* Pool for small blocks. */
235 struct pool_header {
236 union { block *_padding;
237 uint count; } ref; /* number of allocated blocks */
238 block *freeblock; /* pool's free list head */
239 struct pool_header *nextpool; /* next pool of this size class */
240 struct pool_header *prevpool; /* previous pool "" */
241 uint arenaindex; /* index into arenas of base adr */
242 uint szidx; /* block size class index */
243 uint nextoffset; /* bytes to virgin block */
244 uint maxnextoffset; /* largest valid nextoffset */
247 typedef struct pool_header *poolp;
249 /* Record keeping for arenas. */
250 struct arena_object {
251 /* The address of the arena, as returned by malloc. Note that 0
252 * will never be returned by a successful malloc, and is used
253 * here to mark an arena_object that doesn't correspond to an
254 * allocated arena.
256 uptr address;
258 /* Pool-aligned pointer to the next pool to be carved off. */
259 block* pool_address;
261 /* The number of available pools in the arena: free pools + never-
262 * allocated pools.
264 uint nfreepools;
266 /* The total number of pools in the arena, whether or not available. */
267 uint ntotalpools;
269 /* Singly-linked list of available pools. */
270 struct pool_header* freepools;
272 /* Whenever this arena_object is not associated with an allocated
273 * arena, the nextarena member is used to link all unassociated
274 * arena_objects in the singly-linked `unused_arena_objects` list.
275 * The prevarena member is unused in this case.
277 * When this arena_object is associated with an allocated arena
278 * with at least one available pool, both members are used in the
279 * doubly-linked `usable_arenas` list, which is maintained in
280 * increasing order of `nfreepools` values.
282 * Else this arena_object is associated with an allocated arena
283 * all of whose pools are in use. `nextarena` and `prevarena`
284 * are both meaningless in this case.
286 struct arena_object* nextarena;
287 struct arena_object* prevarena;
290 #undef ROUNDUP
291 #define ROUNDUP(x) (((x) + ALIGNMENT_MASK) & ~ALIGNMENT_MASK)
292 #define POOL_OVERHEAD ROUNDUP(sizeof(struct pool_header))
294 #define DUMMY_SIZE_IDX 0xffff /* size class of newly cached pools */
296 /* Round pointer P down to the closest pool-aligned address <= P, as a poolp */
297 #define POOL_ADDR(P) ((poolp)((uptr)(P) & ~(uptr)POOL_SIZE_MASK))
299 /* Return total number of blocks in pool of size index I, as a uint. */
300 #define NUMBLOCKS(I) ((uint)(POOL_SIZE - POOL_OVERHEAD) / INDEX2SIZE(I))
302 /*==========================================================================*/
305 * This malloc lock
307 SIMPLELOCK_DECL(_malloc_lock)
308 #define LOCK() SIMPLELOCK_LOCK(_malloc_lock)
309 #define UNLOCK() SIMPLELOCK_UNLOCK(_malloc_lock)
310 #define LOCK_INIT() SIMPLELOCK_INIT(_malloc_lock)
311 #define LOCK_FINI() SIMPLELOCK_FINI(_malloc_lock)
314 * Pool table -- headed, circular, doubly-linked lists of partially used pools.
316 This is involved. For an index i, usedpools[i+i] is the header for a list of
317 all partially used pools holding small blocks with "size class idx" i. So
318 usedpools[0] corresponds to blocks of size 8, usedpools[2] to blocks of size
319 16, and so on: index 2*i <-> blocks of size (i+1)<<ALIGNMENT_SHIFT.
321 Pools are carved off an arena's highwater mark (an arena_object's pool_address
322 member) as needed. Once carved off, a pool is in one of three states forever
323 after:
325 used == partially used, neither empty nor full
326 At least one block in the pool is currently allocated, and at least one
327 block in the pool is not currently allocated (note this implies a pool
328 has room for at least two blocks).
329 This is a pool's initial state, as a pool is created only when malloc
330 needs space.
331 The pool holds blocks of a fixed size, and is in the circular list headed
332 at usedpools[i] (see above). It's linked to the other used pools of the
333 same size class via the pool_header's nextpool and prevpool members.
334 If all but one block is currently allocated, a malloc can cause a
335 transition to the full state. If all but one block is not currently
336 allocated, a free can cause a transition to the empty state.
338 full == all the pool's blocks are currently allocated
339 On transition to full, a pool is unlinked from its usedpools[] list.
340 It's not linked to from anything then anymore, and its nextpool and
341 prevpool members are meaningless until it transitions back to used.
342 A free of a block in a full pool puts the pool back in the used state.
343 Then it's linked in at the front of the appropriate usedpools[] list, so
344 that the next allocation for its size class will reuse the freed block.
346 empty == all the pool's blocks are currently available for allocation
347 On transition to empty, a pool is unlinked from its usedpools[] list,
348 and linked to the front of its arena_object's singly-linked freepools list,
349 via its nextpool member. The prevpool member has no meaning in this case.
350 Empty pools have no inherent size class: the next time a malloc finds
351 an empty list in usedpools[], it takes the first pool off of freepools.
352 If the size class needed happens to be the same as the size class the pool
353 last had, some pool initialization can be skipped.
356 Block Management
358 Blocks within pools are again carved out as needed. pool->freeblock points to
359 the start of a singly-linked list of free blocks within the pool. When a
360 block is freed, it's inserted at the front of its pool's freeblock list. Note
361 that the available blocks in a pool are *not* linked all together when a pool
362 is initialized. Instead only "the first two" (lowest addresses) blocks are
363 set up, returning the first such block, and setting pool->freeblock to a
364 one-block list holding the second such block. This is consistent with that
365 pymalloc strives at all levels (arena, pool, and block) never to touch a piece
366 of memory until it's actually needed.
368 So long as a pool is in the used state, we're certain there *is* a block
369 available for allocating, and pool->freeblock is not NULL. If pool->freeblock
370 points to the end of the free list before we've carved the entire pool into
371 blocks, that means we simply haven't yet gotten to one of the higher-address
372 blocks. The offset from the pool_header to the start of "the next" virgin
373 block is stored in the pool_header nextoffset member, and the largest value
374 of nextoffset that makes sense is stored in the maxnextoffset member when a
375 pool is initialized. All the blocks in a pool have been passed out at least
376 once when and only when nextoffset > maxnextoffset.
379 Major obscurity: While the usedpools vector is declared to have poolp
380 entries, it doesn't really. It really contains two pointers per (conceptual)
381 poolp entry, the nextpool and prevpool members of a pool_header. The
382 excruciating initialization code below fools C so that
384 usedpool[i+i]
386 "acts like" a genuine poolp, but only so long as you only reference its
387 nextpool and prevpool members. The "- 2*sizeof(block *)" gibberish is
388 compensating for that a pool_header's nextpool and prevpool members
389 immediately follow a pool_header's first two members:
391 union { block *_padding;
392 uint count; } ref;
393 block *freeblock;
395 each of which consume sizeof(block *) bytes. So what usedpools[i+i] really
396 contains is a fudged-up pointer p such that *if* C believes it's a poolp
397 pointer, then p->nextpool and p->prevpool are both p (meaning that the headed
398 circular list is empty).
400 It's unclear why the usedpools setup is so convoluted. It could be to
401 minimize the amount of cache required to hold this heavily-referenced table
402 (which only *needs* the two interpool pointer members of a pool_header). OTOH,
403 referencing code has to remember to "double the index" and doing so isn't
404 free, usedpools[0] isn't a strictly legal pointer, and we're crucially relying
405 on that C doesn't insert any padding anywhere in a pool_header at or before
406 the prevpool member.
407 **************************************************************************** */
409 #define PTA(x) ((poolp )((uchar *)&(usedpools[2*(x)]) - 2*sizeof(block *)))
410 #define PT(x) PTA(x), PTA(x)
412 static poolp usedpools[2 * ((NB_SMALL_SIZE_CLASSES + 7) / 8) * 8] = {
413 PT(0), PT(1), PT(2), PT(3), PT(4), PT(5), PT(6), PT(7)
414 #if NB_SMALL_SIZE_CLASSES > 8
415 , PT(8), PT(9), PT(10), PT(11), PT(12), PT(13), PT(14), PT(15)
416 #if NB_SMALL_SIZE_CLASSES > 16
417 , PT(16), PT(17), PT(18), PT(19), PT(20), PT(21), PT(22), PT(23)
418 #if NB_SMALL_SIZE_CLASSES > 24
419 , PT(24), PT(25), PT(26), PT(27), PT(28), PT(29), PT(30), PT(31)
420 #if NB_SMALL_SIZE_CLASSES > 32
421 , PT(32), PT(33), PT(34), PT(35), PT(36), PT(37), PT(38), PT(39)
422 #if NB_SMALL_SIZE_CLASSES > 40
423 , PT(40), PT(41), PT(42), PT(43), PT(44), PT(45), PT(46), PT(47)
424 #if NB_SMALL_SIZE_CLASSES > 48
425 , PT(48), PT(49), PT(50), PT(51), PT(52), PT(53), PT(54), PT(55)
426 #if NB_SMALL_SIZE_CLASSES > 56
427 , PT(56), PT(57), PT(58), PT(59), PT(60), PT(61), PT(62), PT(63)
428 #endif /* NB_SMALL_SIZE_CLASSES > 56 */
429 #endif /* NB_SMALL_SIZE_CLASSES > 48 */
430 #endif /* NB_SMALL_SIZE_CLASSES > 40 */
431 #endif /* NB_SMALL_SIZE_CLASSES > 32 */
432 #endif /* NB_SMALL_SIZE_CLASSES > 24 */
433 #endif /* NB_SMALL_SIZE_CLASSES > 16 */
434 #endif /* NB_SMALL_SIZE_CLASSES > 8 */
437 /*==========================================================================
438 Arena management.
440 `arenas` is a vector of arena_objects. It contains maxarenas entries, some of
441 which may not be currently used (== they're arena_objects that aren't
442 currently associated with an allocated arena). Note that arenas proper are
443 separately malloc'ed.
445 Prior to Python 2.5, arenas were never free()'ed. Starting with Python 2.5,
446 we do try to free() arenas, and use some mild heuristic strategies to increase
447 the likelihood that arenas eventually can be freed.
449 unused_arena_objects
451 This is a singly-linked list of the arena_objects that are currently not
452 being used (no arena is associated with them). Objects are taken off the
453 head of the list in new_arena(), and are pushed on the head of the list in
454 PyObject_Free() when the arena is empty. Key invariant: an arena_object
455 is on this list if and only if its .address member is 0.
457 usable_arenas
459 This is a doubly-linked list of the arena_objects associated with arenas
460 that have pools available. These pools are either waiting to be reused,
461 or have not been used before. The list is sorted to have the most-
462 allocated arenas first (ascending order based on the nfreepools member).
463 This means that the next allocation will come from a heavily used arena,
464 which gives the nearly empty arenas a chance to be returned to the system.
465 In my unscientific tests this dramatically improved the number of arenas
466 that could be freed.
468 Note that an arena_object associated with an arena all of whose pools are
469 currently in use isn't on either list.
472 /* Array of objects used to track chunks of memory (arenas). */
473 static struct arena_object* arenas = NULL;
474 /* Number of slots currently allocated in the `arenas` vector. */
475 static uint maxarenas = 0;
477 /* The head of the singly-linked, NULL-terminated list of available
478 * arena_objects.
480 static struct arena_object* unused_arena_objects = NULL;
482 /* The head of the doubly-linked, NULL-terminated at each end, list of
483 * arena_objects associated with arenas that have pools available.
485 static struct arena_object* usable_arenas = NULL;
487 /* How many arena_objects do we initially allocate?
488 * 16 = can allocate 16 arenas = 16 * ARENA_SIZE = 4MB before growing the
489 * `arenas` vector.
491 #define INITIAL_ARENA_OBJECTS 16
493 /* Number of arenas allocated that haven't been free()'d. */
494 static size_t narenas_currently_allocated = 0;
496 #ifdef PYMALLOC_DEBUG
497 /* Total number of times malloc() called to allocate an arena. */
498 static size_t ntimes_arena_allocated = 0;
499 /* High water mark (max value ever seen) for narenas_currently_allocated. */
500 static size_t narenas_highwater = 0;
501 #endif
503 /* Allocate a new arena. If we run out of memory, return NULL. Else
504 * allocate a new arena, and return the address of an arena_object
505 * describing the new arena. It's expected that the caller will set
506 * `usable_arenas` to the return value.
508 static struct arena_object*
509 new_arena(void)
511 struct arena_object* arenaobj;
512 uint excess; /* number of bytes above pool alignment */
514 #ifdef PYMALLOC_DEBUG
515 if (Py_GETENV("PYTHONMALLOCSTATS"))
516 _PyObject_DebugMallocStats();
517 #endif
518 if (unused_arena_objects == NULL) {
519 uint i;
520 uint numarenas;
521 size_t nbytes;
523 /* Double the number of arena objects on each allocation.
524 * Note that it's possible for `numarenas` to overflow.
526 numarenas = maxarenas ? maxarenas << 1 : INITIAL_ARENA_OBJECTS;
527 if (numarenas <= maxarenas)
528 return NULL; /* overflow */
529 if (numarenas > PY_SIZE_MAX / sizeof(*arenas))
530 return NULL; /* overflow */
531 nbytes = numarenas * sizeof(*arenas);
532 arenaobj = (struct arena_object *)realloc(arenas, nbytes);
533 if (arenaobj == NULL)
534 return NULL;
535 arenas = arenaobj;
537 /* We might need to fix pointers that were copied. However,
538 * new_arena only gets called when all the pages in the
539 * previous arenas are full. Thus, there are *no* pointers
540 * into the old array. Thus, we don't have to worry about
541 * invalid pointers. Just to be sure, some asserts:
543 assert(usable_arenas == NULL);
544 assert(unused_arena_objects == NULL);
546 /* Put the new arenas on the unused_arena_objects list. */
547 for (i = maxarenas; i < numarenas; ++i) {
548 arenas[i].address = 0; /* mark as unassociated */
549 arenas[i].nextarena = i < numarenas - 1 ?
550 &arenas[i+1] : NULL;
553 /* Update globals. */
554 unused_arena_objects = &arenas[maxarenas];
555 maxarenas = numarenas;
558 /* Take the next available arena object off the head of the list. */
559 assert(unused_arena_objects != NULL);
560 arenaobj = unused_arena_objects;
561 unused_arena_objects = arenaobj->nextarena;
562 assert(arenaobj->address == 0);
563 arenaobj->address = (uptr)malloc(ARENA_SIZE);
564 if (arenaobj->address == 0) {
565 /* The allocation failed: return NULL after putting the
566 * arenaobj back.
568 arenaobj->nextarena = unused_arena_objects;
569 unused_arena_objects = arenaobj;
570 return NULL;
573 ++narenas_currently_allocated;
574 #ifdef PYMALLOC_DEBUG
575 ++ntimes_arena_allocated;
576 if (narenas_currently_allocated > narenas_highwater)
577 narenas_highwater = narenas_currently_allocated;
578 #endif
579 arenaobj->freepools = NULL;
580 /* pool_address <- first pool-aligned address in the arena
581 nfreepools <- number of whole pools that fit after alignment */
582 arenaobj->pool_address = (block*)arenaobj->address;
583 arenaobj->nfreepools = ARENA_SIZE / POOL_SIZE;
584 assert(POOL_SIZE * arenaobj->nfreepools == ARENA_SIZE);
585 excess = (uint)(arenaobj->address & POOL_SIZE_MASK);
586 if (excess != 0) {
587 --arenaobj->nfreepools;
588 arenaobj->pool_address += POOL_SIZE - excess;
590 arenaobj->ntotalpools = arenaobj->nfreepools;
592 return arenaobj;
596 Py_ADDRESS_IN_RANGE(P, POOL)
598 Return true if and only if P is an address that was allocated by pymalloc.
599 POOL must be the pool address associated with P, i.e., POOL = POOL_ADDR(P)
600 (the caller is asked to compute this because the macro expands POOL more than
601 once, and for efficiency it's best for the caller to assign POOL_ADDR(P) to a
602 variable and pass the latter to the macro; because Py_ADDRESS_IN_RANGE is
603 called on every alloc/realloc/free, micro-efficiency is important here).
605 Tricky: Let B be the arena base address associated with the pool, B =
606 arenas[(POOL)->arenaindex].address. Then P belongs to the arena if and only if
608 B <= P < B + ARENA_SIZE
610 Subtracting B throughout, this is true iff
612 0 <= P-B < ARENA_SIZE
614 By using unsigned arithmetic, the "0 <=" half of the test can be skipped.
616 Obscure: A PyMem "free memory" function can call the pymalloc free or realloc
617 before the first arena has been allocated. `arenas` is still NULL in that
618 case. We're relying on that maxarenas is also 0 in that case, so that
619 (POOL)->arenaindex < maxarenas must be false, saving us from trying to index
620 into a NULL arenas.
622 Details: given P and POOL, the arena_object corresponding to P is AO =
623 arenas[(POOL)->arenaindex]. Suppose obmalloc controls P. Then (barring wild
624 stores, etc), POOL is the correct address of P's pool, AO.address is the
625 correct base address of the pool's arena, and P must be within ARENA_SIZE of
626 AO.address. In addition, AO.address is not 0 (no arena can start at address 0
627 (NULL)). Therefore Py_ADDRESS_IN_RANGE correctly reports that obmalloc
628 controls P.
630 Now suppose obmalloc does not control P (e.g., P was obtained via a direct
631 call to the system malloc() or realloc()). (POOL)->arenaindex may be anything
632 in this case -- it may even be uninitialized trash. If the trash arenaindex
633 is >= maxarenas, the macro correctly concludes at once that obmalloc doesn't
634 control P.
636 Else arenaindex is < maxarena, and AO is read up. If AO corresponds to an
637 allocated arena, obmalloc controls all the memory in slice AO.address :
638 AO.address+ARENA_SIZE. By case assumption, P is not controlled by obmalloc,
639 so P doesn't lie in that slice, so the macro correctly reports that P is not
640 controlled by obmalloc.
642 Finally, if P is not controlled by obmalloc and AO corresponds to an unused
643 arena_object (one not currently associated with an allocated arena),
644 AO.address is 0, and the second test in the macro reduces to:
646 P < ARENA_SIZE
648 If P >= ARENA_SIZE (extremely likely), the macro again correctly concludes
649 that P is not controlled by obmalloc. However, if P < ARENA_SIZE, this part
650 of the test still passes, and the third clause (AO.address != 0) is necessary
651 to get the correct result: AO.address is 0 in this case, so the macro
652 correctly reports that P is not controlled by obmalloc (despite that P lies in
653 slice AO.address : AO.address + ARENA_SIZE).
655 Note: The third (AO.address != 0) clause was added in Python 2.5. Before
656 2.5, arenas were never free()'ed, and an arenaindex < maxarena always
657 corresponded to a currently-allocated arena, so the "P is not controlled by
658 obmalloc, AO corresponds to an unused arena_object, and P < ARENA_SIZE" case
659 was impossible.
661 Note that the logic is excruciating, and reading up possibly uninitialized
662 memory when P is not controlled by obmalloc (to get at (POOL)->arenaindex)
663 creates problems for some memory debuggers. The overwhelming advantage is
664 that this test determines whether an arbitrary address is controlled by
665 obmalloc in a small constant time, independent of the number of arenas
666 obmalloc controls. Since this test is needed at every entry point, it's
667 extremely desirable that it be this fast.
669 #define Py_ADDRESS_IN_RANGE(P, POOL) \
670 ((POOL)->arenaindex < maxarenas && \
671 (uptr)(P) - arenas[(POOL)->arenaindex].address < (uptr)ARENA_SIZE && \
672 arenas[(POOL)->arenaindex].address != 0)
675 /* This is only useful when running memory debuggers such as
676 * Purify or Valgrind. Uncomment to use.
679 #define Py_USING_MEMORY_DEBUGGER
681 #ifdef Py_USING_MEMORY_DEBUGGER
683 /* Py_ADDRESS_IN_RANGE may access uninitialized memory by design
684 * This leads to thousands of spurious warnings when using
685 * Purify or Valgrind. By making a function, we can easily
686 * suppress the uninitialized memory reads in this one function.
687 * So we won't ignore real errors elsewhere.
689 * Disable the macro and use a function.
692 #undef Py_ADDRESS_IN_RANGE
694 #if defined(__GNUC__) && ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 1) || \
695 (__GNUC__ >= 4))
696 #define Py_NO_INLINE __attribute__((__noinline__))
697 #else
698 #define Py_NO_INLINE
699 #endif
701 /* Don't make static, to try to ensure this isn't inlined. */
702 int Py_ADDRESS_IN_RANGE(void *P, poolp pool) Py_NO_INLINE;
703 #undef Py_NO_INLINE
704 #endif
706 /*==========================================================================*/
708 /* malloc. Note that nbytes==0 tries to return a non-NULL pointer, distinct
709 * from all other currently live pointers. This may not be possible.
713 * The basic blocks are ordered by decreasing execution frequency,
714 * which minimizes the number of jumps in the most common cases,
715 * improves branching prediction and instruction scheduling (small
716 * block allocations typically result in a couple of instructions).
717 * Unless the optimizer reorders everything, being too smart...
720 #undef PyObject_Malloc
721 void *
722 PyObject_Malloc(size_t nbytes)
724 block *bp;
725 poolp pool;
726 poolp next;
727 uint size;
730 * Limit ourselves to PY_SSIZE_T_MAX bytes to prevent security holes.
731 * Most python internals blindly use a signed Py_ssize_t to track
732 * things without checking for overflows or negatives.
733 * As size_t is unsigned, checking for nbytes < 0 is not required.
735 if (nbytes > PY_SSIZE_T_MAX)
736 return NULL;
739 * This implicitly redirects malloc(0).
741 if ((nbytes - 1) < SMALL_REQUEST_THRESHOLD) {
742 LOCK();
744 * Most frequent paths first
746 size = (uint)(nbytes - 1) >> ALIGNMENT_SHIFT;
747 pool = usedpools[size + size];
748 if (pool != pool->nextpool) {
750 * There is a used pool for this size class.
751 * Pick up the head block of its free list.
753 ++pool->ref.count;
754 bp = pool->freeblock;
755 assert(bp != NULL);
756 if ((pool->freeblock = *(block **)bp) != NULL) {
757 UNLOCK();
758 return (void *)bp;
761 * Reached the end of the free list, try to extend it.
763 if (pool->nextoffset <= pool->maxnextoffset) {
764 /* There is room for another block. */
765 pool->freeblock = (block*)pool +
766 pool->nextoffset;
767 pool->nextoffset += INDEX2SIZE(size);
768 *(block **)(pool->freeblock) = NULL;
769 UNLOCK();
770 return (void *)bp;
772 /* Pool is full, unlink from used pools. */
773 next = pool->nextpool;
774 pool = pool->prevpool;
775 next->prevpool = pool;
776 pool->nextpool = next;
777 UNLOCK();
778 return (void *)bp;
781 /* There isn't a pool of the right size class immediately
782 * available: use a free pool.
784 if (usable_arenas == NULL) {
785 /* No arena has a free pool: allocate a new arena. */
786 #ifdef WITH_MEMORY_LIMITS
787 if (narenas_currently_allocated >= MAX_ARENAS) {
788 UNLOCK();
789 goto redirect;
791 #endif
792 usable_arenas = new_arena();
793 if (usable_arenas == NULL) {
794 UNLOCK();
795 goto redirect;
797 usable_arenas->nextarena =
798 usable_arenas->prevarena = NULL;
800 assert(usable_arenas->address != 0);
802 /* Try to get a cached free pool. */
803 pool = usable_arenas->freepools;
804 if (pool != NULL) {
805 /* Unlink from cached pools. */
806 usable_arenas->freepools = pool->nextpool;
808 /* This arena already had the smallest nfreepools
809 * value, so decreasing nfreepools doesn't change
810 * that, and we don't need to rearrange the
811 * usable_arenas list. However, if the arena has
812 * become wholly allocated, we need to remove its
813 * arena_object from usable_arenas.
815 --usable_arenas->nfreepools;
816 if (usable_arenas->nfreepools == 0) {
817 /* Wholly allocated: remove. */
818 assert(usable_arenas->freepools == NULL);
819 assert(usable_arenas->nextarena == NULL ||
820 usable_arenas->nextarena->prevarena ==
821 usable_arenas);
823 usable_arenas = usable_arenas->nextarena;
824 if (usable_arenas != NULL) {
825 usable_arenas->prevarena = NULL;
826 assert(usable_arenas->address != 0);
829 else {
830 /* nfreepools > 0: it must be that freepools
831 * isn't NULL, or that we haven't yet carved
832 * off all the arena's pools for the first
833 * time.
835 assert(usable_arenas->freepools != NULL ||
836 usable_arenas->pool_address <=
837 (block*)usable_arenas->address +
838 ARENA_SIZE - POOL_SIZE);
840 init_pool:
841 /* Frontlink to used pools. */
842 next = usedpools[size + size]; /* == prev */
843 pool->nextpool = next;
844 pool->prevpool = next;
845 next->nextpool = pool;
846 next->prevpool = pool;
847 pool->ref.count = 1;
848 if (pool->szidx == size) {
849 /* Luckily, this pool last contained blocks
850 * of the same size class, so its header
851 * and free list are already initialized.
853 bp = pool->freeblock;
854 pool->freeblock = *(block **)bp;
855 UNLOCK();
856 return (void *)bp;
859 * Initialize the pool header, set up the free list to
860 * contain just the second block, and return the first
861 * block.
863 pool->szidx = size;
864 size = INDEX2SIZE(size);
865 bp = (block *)pool + POOL_OVERHEAD;
866 pool->nextoffset = POOL_OVERHEAD + (size << 1);
867 pool->maxnextoffset = POOL_SIZE - size;
868 pool->freeblock = bp + size;
869 *(block **)(pool->freeblock) = NULL;
870 UNLOCK();
871 return (void *)bp;
874 /* Carve off a new pool. */
875 assert(usable_arenas->nfreepools > 0);
876 assert(usable_arenas->freepools == NULL);
877 pool = (poolp)usable_arenas->pool_address;
878 assert((block*)pool <= (block*)usable_arenas->address +
879 ARENA_SIZE - POOL_SIZE);
880 pool->arenaindex = usable_arenas - arenas;
881 assert(&arenas[pool->arenaindex] == usable_arenas);
882 pool->szidx = DUMMY_SIZE_IDX;
883 usable_arenas->pool_address += POOL_SIZE;
884 --usable_arenas->nfreepools;
886 if (usable_arenas->nfreepools == 0) {
887 assert(usable_arenas->nextarena == NULL ||
888 usable_arenas->nextarena->prevarena ==
889 usable_arenas);
890 /* Unlink the arena: it is completely allocated. */
891 usable_arenas = usable_arenas->nextarena;
892 if (usable_arenas != NULL) {
893 usable_arenas->prevarena = NULL;
894 assert(usable_arenas->address != 0);
898 goto init_pool;
901 /* The small block allocator ends here. */
903 redirect:
904 /* Redirect the original request to the underlying (libc) allocator.
905 * We jump here on bigger requests, on error in the code above (as a
906 * last chance to serve the request) or when the max memory limit
907 * has been reached.
909 if (nbytes == 0)
910 nbytes = 1;
911 return (void *)malloc(nbytes);
914 /* free */
916 #undef PyObject_Free
917 void
918 PyObject_Free(void *p)
920 poolp pool;
921 block *lastfree;
922 poolp next, prev;
923 uint size;
925 if (p == NULL) /* free(NULL) has no effect */
926 return;
928 pool = POOL_ADDR(p);
929 if (Py_ADDRESS_IN_RANGE(p, pool)) {
930 /* We allocated this address. */
931 LOCK();
932 /* Link p to the start of the pool's freeblock list. Since
933 * the pool had at least the p block outstanding, the pool
934 * wasn't empty (so it's already in a usedpools[] list, or
935 * was full and is in no list -- it's not in the freeblocks
936 * list in any case).
938 assert(pool->ref.count > 0); /* else it was empty */
939 *(block **)p = lastfree = pool->freeblock;
940 pool->freeblock = (block *)p;
941 if (lastfree) {
942 struct arena_object* ao;
943 uint nf; /* ao->nfreepools */
945 /* freeblock wasn't NULL, so the pool wasn't full,
946 * and the pool is in a usedpools[] list.
948 if (--pool->ref.count != 0) {
949 /* pool isn't empty: leave it in usedpools */
950 UNLOCK();
951 return;
953 /* Pool is now empty: unlink from usedpools, and
954 * link to the front of freepools. This ensures that
955 * previously freed pools will be allocated later
956 * (being not referenced, they are perhaps paged out).
958 next = pool->nextpool;
959 prev = pool->prevpool;
960 next->prevpool = prev;
961 prev->nextpool = next;
963 /* Link the pool to freepools. This is a singly-linked
964 * list, and pool->prevpool isn't used there.
966 ao = &arenas[pool->arenaindex];
967 pool->nextpool = ao->freepools;
968 ao->freepools = pool;
969 nf = ++ao->nfreepools;
971 /* All the rest is arena management. We just freed
972 * a pool, and there are 4 cases for arena mgmt:
973 * 1. If all the pools are free, return the arena to
974 * the system free().
975 * 2. If this is the only free pool in the arena,
976 * add the arena back to the `usable_arenas` list.
977 * 3. If the "next" arena has a smaller count of free
978 * pools, we have to "slide this arena right" to
979 * restore that usable_arenas is sorted in order of
980 * nfreepools.
981 * 4. Else there's nothing more to do.
983 if (nf == ao->ntotalpools) {
984 /* Case 1. First unlink ao from usable_arenas.
986 assert(ao->prevarena == NULL ||
987 ao->prevarena->address != 0);
988 assert(ao ->nextarena == NULL ||
989 ao->nextarena->address != 0);
991 /* Fix the pointer in the prevarena, or the
992 * usable_arenas pointer.
994 if (ao->prevarena == NULL) {
995 usable_arenas = ao->nextarena;
996 assert(usable_arenas == NULL ||
997 usable_arenas->address != 0);
999 else {
1000 assert(ao->prevarena->nextarena == ao);
1001 ao->prevarena->nextarena =
1002 ao->nextarena;
1004 /* Fix the pointer in the nextarena. */
1005 if (ao->nextarena != NULL) {
1006 assert(ao->nextarena->prevarena == ao);
1007 ao->nextarena->prevarena =
1008 ao->prevarena;
1010 /* Record that this arena_object slot is
1011 * available to be reused.
1013 ao->nextarena = unused_arena_objects;
1014 unused_arena_objects = ao;
1016 /* Free the entire arena. */
1017 free((void *)ao->address);
1018 ao->address = 0; /* mark unassociated */
1019 --narenas_currently_allocated;
1021 UNLOCK();
1022 return;
1024 if (nf == 1) {
1025 /* Case 2. Put ao at the head of
1026 * usable_arenas. Note that because
1027 * ao->nfreepools was 0 before, ao isn't
1028 * currently on the usable_arenas list.
1030 ao->nextarena = usable_arenas;
1031 ao->prevarena = NULL;
1032 if (usable_arenas)
1033 usable_arenas->prevarena = ao;
1034 usable_arenas = ao;
1035 assert(usable_arenas->address != 0);
1037 UNLOCK();
1038 return;
1040 /* If this arena is now out of order, we need to keep
1041 * the list sorted. The list is kept sorted so that
1042 * the "most full" arenas are used first, which allows
1043 * the nearly empty arenas to be completely freed. In
1044 * a few un-scientific tests, it seems like this
1045 * approach allowed a lot more memory to be freed.
1047 if (ao->nextarena == NULL ||
1048 nf <= ao->nextarena->nfreepools) {
1049 /* Case 4. Nothing to do. */
1050 UNLOCK();
1051 return;
1053 /* Case 3: We have to move the arena towards the end
1054 * of the list, because it has more free pools than
1055 * the arena to its right.
1056 * First unlink ao from usable_arenas.
1058 if (ao->prevarena != NULL) {
1059 /* ao isn't at the head of the list */
1060 assert(ao->prevarena->nextarena == ao);
1061 ao->prevarena->nextarena = ao->nextarena;
1063 else {
1064 /* ao is at the head of the list */
1065 assert(usable_arenas == ao);
1066 usable_arenas = ao->nextarena;
1068 ao->nextarena->prevarena = ao->prevarena;
1070 /* Locate the new insertion point by iterating over
1071 * the list, using our nextarena pointer.
1073 while (ao->nextarena != NULL &&
1074 nf > ao->nextarena->nfreepools) {
1075 ao->prevarena = ao->nextarena;
1076 ao->nextarena = ao->nextarena->nextarena;
1079 /* Insert ao at this point. */
1080 assert(ao->nextarena == NULL ||
1081 ao->prevarena == ao->nextarena->prevarena);
1082 assert(ao->prevarena->nextarena == ao->nextarena);
1084 ao->prevarena->nextarena = ao;
1085 if (ao->nextarena != NULL)
1086 ao->nextarena->prevarena = ao;
1088 /* Verify that the swaps worked. */
1089 assert(ao->nextarena == NULL ||
1090 nf <= ao->nextarena->nfreepools);
1091 assert(ao->prevarena == NULL ||
1092 nf > ao->prevarena->nfreepools);
1093 assert(ao->nextarena == NULL ||
1094 ao->nextarena->prevarena == ao);
1095 assert((usable_arenas == ao &&
1096 ao->prevarena == NULL) ||
1097 ao->prevarena->nextarena == ao);
1099 UNLOCK();
1100 return;
1102 /* Pool was full, so doesn't currently live in any list:
1103 * link it to the front of the appropriate usedpools[] list.
1104 * This mimics LRU pool usage for new allocations and
1105 * targets optimal filling when several pools contain
1106 * blocks of the same size class.
1108 --pool->ref.count;
1109 assert(pool->ref.count > 0); /* else the pool is empty */
1110 size = pool->szidx;
1111 next = usedpools[size + size];
1112 prev = next->prevpool;
1113 /* insert pool before next: prev <-> pool <-> next */
1114 pool->nextpool = next;
1115 pool->prevpool = prev;
1116 next->prevpool = pool;
1117 prev->nextpool = pool;
1118 UNLOCK();
1119 return;
1122 /* We didn't allocate this address. */
1123 free(p);
1126 /* realloc. If p is NULL, this acts like malloc(nbytes). Else if nbytes==0,
1127 * then as the Python docs promise, we do not treat this like free(p), and
1128 * return a non-NULL result.
1131 #undef PyObject_Realloc
1132 void *
1133 PyObject_Realloc(void *p, size_t nbytes)
1135 void *bp;
1136 poolp pool;
1137 size_t size;
1139 if (p == NULL)
1140 return PyObject_Malloc(nbytes);
1143 * Limit ourselves to PY_SSIZE_T_MAX bytes to prevent security holes.
1144 * Most python internals blindly use a signed Py_ssize_t to track
1145 * things without checking for overflows or negatives.
1146 * As size_t is unsigned, checking for nbytes < 0 is not required.
1148 if (nbytes > PY_SSIZE_T_MAX)
1149 return NULL;
1151 pool = POOL_ADDR(p);
1152 if (Py_ADDRESS_IN_RANGE(p, pool)) {
1153 /* We're in charge of this block */
1154 size = INDEX2SIZE(pool->szidx);
1155 if (nbytes <= size) {
1156 /* The block is staying the same or shrinking. If
1157 * it's shrinking, there's a tradeoff: it costs
1158 * cycles to copy the block to a smaller size class,
1159 * but it wastes memory not to copy it. The
1160 * compromise here is to copy on shrink only if at
1161 * least 25% of size can be shaved off.
1163 if (4 * nbytes > 3 * size) {
1164 /* It's the same,
1165 * or shrinking and new/old > 3/4.
1167 return p;
1169 size = nbytes;
1171 bp = PyObject_Malloc(nbytes);
1172 if (bp != NULL) {
1173 memcpy(bp, p, size);
1174 PyObject_Free(p);
1176 return bp;
1178 /* We're not managing this block. If nbytes <=
1179 * SMALL_REQUEST_THRESHOLD, it's tempting to try to take over this
1180 * block. However, if we do, we need to copy the valid data from
1181 * the C-managed block to one of our blocks, and there's no portable
1182 * way to know how much of the memory space starting at p is valid.
1183 * As bug 1185883 pointed out the hard way, it's possible that the
1184 * C-managed block is "at the end" of allocated VM space, so that
1185 * a memory fault can occur if we try to copy nbytes bytes starting
1186 * at p. Instead we punt: let C continue to manage this block.
1188 if (nbytes)
1189 return realloc(p, nbytes);
1190 /* C doesn't define the result of realloc(p, 0) (it may or may not
1191 * return NULL then), but Python's docs promise that nbytes==0 never
1192 * returns NULL. We don't pass 0 to realloc(), to avoid that endcase
1193 * to begin with. Even then, we can't be sure that realloc() won't
1194 * return NULL.
1196 bp = realloc(p, 1);
1197 return bp ? bp : p;
1200 #else /* ! WITH_PYMALLOC */
1202 /*==========================================================================*/
1203 /* pymalloc not enabled: Redirect the entry points to malloc. These will
1204 * only be used by extensions that are compiled with pymalloc enabled. */
1206 void *
1207 PyObject_Malloc(size_t n)
1209 return PyMem_MALLOC(n);
1212 void *
1213 PyObject_Realloc(void *p, size_t n)
1215 return PyMem_REALLOC(p, n);
1218 void
1219 PyObject_Free(void *p)
1221 PyMem_FREE(p);
1223 #endif /* WITH_PYMALLOC */
1225 #ifdef PYMALLOC_DEBUG
1226 /*==========================================================================*/
1227 /* A x-platform debugging allocator. This doesn't manage memory directly,
1228 * it wraps a real allocator, adding extra debugging info to the memory blocks.
1231 /* Special bytes broadcast into debug memory blocks at appropriate times.
1232 * Strings of these are unlikely to be valid addresses, floats, ints or
1233 * 7-bit ASCII.
1235 #undef CLEANBYTE
1236 #undef DEADBYTE
1237 #undef FORBIDDENBYTE
1238 #define CLEANBYTE 0xCB /* clean (newly allocated) memory */
1239 #define DEADBYTE 0xDB /* dead (newly freed) memory */
1240 #define FORBIDDENBYTE 0xFB /* untouchable bytes at each end of a block */
1242 static size_t serialno = 0; /* incremented on each debug {m,re}alloc */
1244 /* serialno is always incremented via calling this routine. The point is
1245 * to supply a single place to set a breakpoint.
1247 static void
1248 bumpserialno(void)
1250 ++serialno;
1253 #define SST SIZEOF_SIZE_T
1255 /* Read sizeof(size_t) bytes at p as a big-endian size_t. */
1256 static size_t
1257 read_size_t(const void *p)
1259 const uchar *q = (const uchar *)p;
1260 size_t result = *q++;
1261 int i;
1263 for (i = SST; --i > 0; ++q)
1264 result = (result << 8) | *q;
1265 return result;
1268 /* Write n as a big-endian size_t, MSB at address p, LSB at
1269 * p + sizeof(size_t) - 1.
1271 static void
1272 write_size_t(void *p, size_t n)
1274 uchar *q = (uchar *)p + SST - 1;
1275 int i;
1277 for (i = SST; --i >= 0; --q) {
1278 *q = (uchar)(n & 0xff);
1279 n >>= 8;
1283 #ifdef Py_DEBUG
1284 /* Is target in the list? The list is traversed via the nextpool pointers.
1285 * The list may be NULL-terminated, or circular. Return 1 if target is in
1286 * list, else 0.
1288 static int
1289 pool_is_in_list(const poolp target, poolp list)
1291 poolp origlist = list;
1292 assert(target != NULL);
1293 if (list == NULL)
1294 return 0;
1295 do {
1296 if (target == list)
1297 return 1;
1298 list = list->nextpool;
1299 } while (list != NULL && list != origlist);
1300 return 0;
1303 #else
1304 #define pool_is_in_list(X, Y) 1
1306 #endif /* Py_DEBUG */
1308 /* Let S = sizeof(size_t). The debug malloc asks for 4*S extra bytes and
1309 fills them with useful stuff, here calling the underlying malloc's result p:
1311 p[0: S]
1312 Number of bytes originally asked for. This is a size_t, big-endian (easier
1313 to read in a memory dump).
1314 p[S: 2*S]
1315 Copies of FORBIDDENBYTE. Used to catch under- writes and reads.
1316 p[2*S: 2*S+n]
1317 The requested memory, filled with copies of CLEANBYTE.
1318 Used to catch reference to uninitialized memory.
1319 &p[2*S] is returned. Note that this is 8-byte aligned if pymalloc
1320 handled the request itself.
1321 p[2*S+n: 2*S+n+S]
1322 Copies of FORBIDDENBYTE. Used to catch over- writes and reads.
1323 p[2*S+n+S: 2*S+n+2*S]
1324 A serial number, incremented by 1 on each call to _PyObject_DebugMalloc
1325 and _PyObject_DebugRealloc.
1326 This is a big-endian size_t.
1327 If "bad memory" is detected later, the serial number gives an
1328 excellent way to set a breakpoint on the next run, to capture the
1329 instant at which this block was passed out.
1332 void *
1333 _PyObject_DebugMalloc(size_t nbytes)
1335 uchar *p; /* base address of malloc'ed block */
1336 uchar *tail; /* p + 2*SST + nbytes == pointer to tail pad bytes */
1337 size_t total; /* nbytes + 4*SST */
1339 bumpserialno();
1340 total = nbytes + 4*SST;
1341 if (total < nbytes)
1342 /* overflow: can't represent total as a size_t */
1343 return NULL;
1345 p = (uchar *)PyObject_Malloc(total);
1346 if (p == NULL)
1347 return NULL;
1349 write_size_t(p, nbytes);
1350 memset(p + SST, FORBIDDENBYTE, SST);
1352 if (nbytes > 0)
1353 memset(p + 2*SST, CLEANBYTE, nbytes);
1355 tail = p + 2*SST + nbytes;
1356 memset(tail, FORBIDDENBYTE, SST);
1357 write_size_t(tail + SST, serialno);
1359 return p + 2*SST;
1362 /* The debug free first checks the 2*SST bytes on each end for sanity (in
1363 particular, that the FORBIDDENBYTEs are still intact).
1364 Then fills the original bytes with DEADBYTE.
1365 Then calls the underlying free.
1367 void
1368 _PyObject_DebugFree(void *p)
1370 uchar *q = (uchar *)p - 2*SST; /* address returned from malloc */
1371 size_t nbytes;
1373 if (p == NULL)
1374 return;
1375 _PyObject_DebugCheckAddress(p);
1376 nbytes = read_size_t(q);
1377 if (nbytes > 0)
1378 memset(q, DEADBYTE, nbytes);
1379 PyObject_Free(q);
1382 void *
1383 _PyObject_DebugRealloc(void *p, size_t nbytes)
1385 uchar *q = (uchar *)p;
1386 uchar *tail;
1387 size_t total; /* nbytes + 4*SST */
1388 size_t original_nbytes;
1389 int i;
1391 if (p == NULL)
1392 return _PyObject_DebugMalloc(nbytes);
1394 _PyObject_DebugCheckAddress(p);
1395 bumpserialno();
1396 original_nbytes = read_size_t(q - 2*SST);
1397 total = nbytes + 4*SST;
1398 if (total < nbytes)
1399 /* overflow: can't represent total as a size_t */
1400 return NULL;
1402 if (nbytes < original_nbytes) {
1403 /* shrinking: mark old extra memory dead */
1404 memset(q + nbytes, DEADBYTE, original_nbytes - nbytes);
1407 /* Resize and add decorations. */
1408 q = (uchar *)PyObject_Realloc(q - 2*SST, total);
1409 if (q == NULL)
1410 return NULL;
1412 write_size_t(q, nbytes);
1413 for (i = 0; i < SST; ++i)
1414 assert(q[SST + i] == FORBIDDENBYTE);
1415 q += 2*SST;
1416 tail = q + nbytes;
1417 memset(tail, FORBIDDENBYTE, SST);
1418 write_size_t(tail + SST, serialno);
1420 if (nbytes > original_nbytes) {
1421 /* growing: mark new extra memory clean */
1422 memset(q + original_nbytes, CLEANBYTE,
1423 nbytes - original_nbytes);
1426 return q;
1429 /* Check the forbidden bytes on both ends of the memory allocated for p.
1430 * If anything is wrong, print info to stderr via _PyObject_DebugDumpAddress,
1431 * and call Py_FatalError to kill the program.
1433 void
1434 _PyObject_DebugCheckAddress(const void *p)
1436 const uchar *q = (const uchar *)p;
1437 char *msg;
1438 size_t nbytes;
1439 const uchar *tail;
1440 int i;
1442 if (p == NULL) {
1443 msg = "didn't expect a NULL pointer";
1444 goto error;
1447 /* Check the stuff at the start of p first: if there's underwrite
1448 * corruption, the number-of-bytes field may be nuts, and checking
1449 * the tail could lead to a segfault then.
1451 for (i = SST; i >= 1; --i) {
1452 if (*(q-i) != FORBIDDENBYTE) {
1453 msg = "bad leading pad byte";
1454 goto error;
1458 nbytes = read_size_t(q - 2*SST);
1459 tail = q + nbytes;
1460 for (i = 0; i < SST; ++i) {
1461 if (tail[i] != FORBIDDENBYTE) {
1462 msg = "bad trailing pad byte";
1463 goto error;
1467 return;
1469 error:
1470 _PyObject_DebugDumpAddress(p);
1471 Py_FatalError(msg);
1474 /* Display info to stderr about the memory block at p. */
1475 void
1476 _PyObject_DebugDumpAddress(const void *p)
1478 const uchar *q = (const uchar *)p;
1479 const uchar *tail;
1480 size_t nbytes, serial;
1481 int i;
1482 int ok;
1484 fprintf(stderr, "Debug memory block at address p=%p:\n", p);
1485 if (p == NULL)
1486 return;
1488 nbytes = read_size_t(q - 2*SST);
1489 fprintf(stderr, " %" PY_FORMAT_SIZE_T "u bytes originally "
1490 "requested\n", nbytes);
1492 /* In case this is nuts, check the leading pad bytes first. */
1493 fprintf(stderr, " The %d pad bytes at p-%d are ", SST, SST);
1494 ok = 1;
1495 for (i = 1; i <= SST; ++i) {
1496 if (*(q-i) != FORBIDDENBYTE) {
1497 ok = 0;
1498 break;
1501 if (ok)
1502 fputs("FORBIDDENBYTE, as expected.\n", stderr);
1503 else {
1504 fprintf(stderr, "not all FORBIDDENBYTE (0x%02x):\n",
1505 FORBIDDENBYTE);
1506 for (i = SST; i >= 1; --i) {
1507 const uchar byte = *(q-i);
1508 fprintf(stderr, " at p-%d: 0x%02x", i, byte);
1509 if (byte != FORBIDDENBYTE)
1510 fputs(" *** OUCH", stderr);
1511 fputc('\n', stderr);
1514 fputs(" Because memory is corrupted at the start, the "
1515 "count of bytes requested\n"
1516 " may be bogus, and checking the trailing pad "
1517 "bytes may segfault.\n", stderr);
1520 tail = q + nbytes;
1521 fprintf(stderr, " The %d pad bytes at tail=%p are ", SST, tail);
1522 ok = 1;
1523 for (i = 0; i < SST; ++i) {
1524 if (tail[i] != FORBIDDENBYTE) {
1525 ok = 0;
1526 break;
1529 if (ok)
1530 fputs("FORBIDDENBYTE, as expected.\n", stderr);
1531 else {
1532 fprintf(stderr, "not all FORBIDDENBYTE (0x%02x):\n",
1533 FORBIDDENBYTE);
1534 for (i = 0; i < SST; ++i) {
1535 const uchar byte = tail[i];
1536 fprintf(stderr, " at tail+%d: 0x%02x",
1537 i, byte);
1538 if (byte != FORBIDDENBYTE)
1539 fputs(" *** OUCH", stderr);
1540 fputc('\n', stderr);
1544 serial = read_size_t(tail + SST);
1545 fprintf(stderr, " The block was made by call #%" PY_FORMAT_SIZE_T
1546 "u to debug malloc/realloc.\n", serial);
1548 if (nbytes > 0) {
1549 i = 0;
1550 fputs(" Data at p:", stderr);
1551 /* print up to 8 bytes at the start */
1552 while (q < tail && i < 8) {
1553 fprintf(stderr, " %02x", *q);
1554 ++i;
1555 ++q;
1557 /* and up to 8 at the end */
1558 if (q < tail) {
1559 if (tail - q > 8) {
1560 fputs(" ...", stderr);
1561 q = tail - 8;
1563 while (q < tail) {
1564 fprintf(stderr, " %02x", *q);
1565 ++q;
1568 fputc('\n', stderr);
1572 static size_t
1573 printone(const char* msg, size_t value)
1575 int i, k;
1576 char buf[100];
1577 size_t origvalue = value;
1579 fputs(msg, stderr);
1580 for (i = (int)strlen(msg); i < 35; ++i)
1581 fputc(' ', stderr);
1582 fputc('=', stderr);
1584 /* Write the value with commas. */
1585 i = 22;
1586 buf[i--] = '\0';
1587 buf[i--] = '\n';
1588 k = 3;
1589 do {
1590 size_t nextvalue = value / 10;
1591 uint digit = (uint)(value - nextvalue * 10);
1592 value = nextvalue;
1593 buf[i--] = (char)(digit + '0');
1594 --k;
1595 if (k == 0 && value && i >= 0) {
1596 k = 3;
1597 buf[i--] = ',';
1599 } while (value && i >= 0);
1601 while (i >= 0)
1602 buf[i--] = ' ';
1603 fputs(buf, stderr);
1605 return origvalue;
1608 /* Print summary info to stderr about the state of pymalloc's structures.
1609 * In Py_DEBUG mode, also perform some expensive internal consistency
1610 * checks.
1612 void
1613 _PyObject_DebugMallocStats(void)
1615 uint i;
1616 const uint numclasses = SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT;
1617 /* # of pools, allocated blocks, and free blocks per class index */
1618 size_t numpools[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT];
1619 size_t numblocks[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT];
1620 size_t numfreeblocks[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT];
1621 /* total # of allocated bytes in used and full pools */
1622 size_t allocated_bytes = 0;
1623 /* total # of available bytes in used pools */
1624 size_t available_bytes = 0;
1625 /* # of free pools + pools not yet carved out of current arena */
1626 uint numfreepools = 0;
1627 /* # of bytes for arena alignment padding */
1628 size_t arena_alignment = 0;
1629 /* # of bytes in used and full pools used for pool_headers */
1630 size_t pool_header_bytes = 0;
1631 /* # of bytes in used and full pools wasted due to quantization,
1632 * i.e. the necessarily leftover space at the ends of used and
1633 * full pools.
1635 size_t quantization = 0;
1636 /* # of arenas actually allocated. */
1637 size_t narenas = 0;
1638 /* running total -- should equal narenas * ARENA_SIZE */
1639 size_t total;
1640 char buf[128];
1642 fprintf(stderr, "Small block threshold = %d, in %u size classes.\n",
1643 SMALL_REQUEST_THRESHOLD, numclasses);
1645 for (i = 0; i < numclasses; ++i)
1646 numpools[i] = numblocks[i] = numfreeblocks[i] = 0;
1648 /* Because full pools aren't linked to from anything, it's easiest
1649 * to march over all the arenas. If we're lucky, most of the memory
1650 * will be living in full pools -- would be a shame to miss them.
1652 for (i = 0; i < maxarenas; ++i) {
1653 uint poolsinarena;
1654 uint j;
1655 uptr base = arenas[i].address;
1657 /* Skip arenas which are not allocated. */
1658 if (arenas[i].address == (uptr)NULL)
1659 continue;
1660 narenas += 1;
1662 poolsinarena = arenas[i].ntotalpools;
1663 numfreepools += arenas[i].nfreepools;
1665 /* round up to pool alignment */
1666 if (base & (uptr)POOL_SIZE_MASK) {
1667 arena_alignment += POOL_SIZE;
1668 base &= ~(uptr)POOL_SIZE_MASK;
1669 base += POOL_SIZE;
1672 /* visit every pool in the arena */
1673 assert(base <= (uptr) arenas[i].pool_address);
1674 for (j = 0;
1675 base < (uptr) arenas[i].pool_address;
1676 ++j, base += POOL_SIZE) {
1677 poolp p = (poolp)base;
1678 const uint sz = p->szidx;
1679 uint freeblocks;
1681 if (p->ref.count == 0) {
1682 /* currently unused */
1683 assert(pool_is_in_list(p, arenas[i].freepools));
1684 continue;
1686 ++numpools[sz];
1687 numblocks[sz] += p->ref.count;
1688 freeblocks = NUMBLOCKS(sz) - p->ref.count;
1689 numfreeblocks[sz] += freeblocks;
1690 #ifdef Py_DEBUG
1691 if (freeblocks > 0)
1692 assert(pool_is_in_list(p, usedpools[sz + sz]));
1693 #endif
1696 assert(narenas == narenas_currently_allocated);
1698 fputc('\n', stderr);
1699 fputs("class size num pools blocks in use avail blocks\n"
1700 "----- ---- --------- ------------- ------------\n",
1701 stderr);
1703 for (i = 0; i < numclasses; ++i) {
1704 size_t p = numpools[i];
1705 size_t b = numblocks[i];
1706 size_t f = numfreeblocks[i];
1707 uint size = INDEX2SIZE(i);
1708 if (p == 0) {
1709 assert(b == 0 && f == 0);
1710 continue;
1712 fprintf(stderr, "%5u %6u "
1713 "%11" PY_FORMAT_SIZE_T "u "
1714 "%15" PY_FORMAT_SIZE_T "u "
1715 "%13" PY_FORMAT_SIZE_T "u\n",
1716 i, size, p, b, f);
1717 allocated_bytes += b * size;
1718 available_bytes += f * size;
1719 pool_header_bytes += p * POOL_OVERHEAD;
1720 quantization += p * ((POOL_SIZE - POOL_OVERHEAD) % size);
1722 fputc('\n', stderr);
1723 (void)printone("# times object malloc called", serialno);
1725 (void)printone("# arenas allocated total", ntimes_arena_allocated);
1726 (void)printone("# arenas reclaimed", ntimes_arena_allocated - narenas);
1727 (void)printone("# arenas highwater mark", narenas_highwater);
1728 (void)printone("# arenas allocated current", narenas);
1730 PyOS_snprintf(buf, sizeof(buf),
1731 "%" PY_FORMAT_SIZE_T "u arenas * %d bytes/arena",
1732 narenas, ARENA_SIZE);
1733 (void)printone(buf, narenas * ARENA_SIZE);
1735 fputc('\n', stderr);
1737 total = printone("# bytes in allocated blocks", allocated_bytes);
1738 total += printone("# bytes in available blocks", available_bytes);
1740 PyOS_snprintf(buf, sizeof(buf),
1741 "%u unused pools * %d bytes", numfreepools, POOL_SIZE);
1742 total += printone(buf, (size_t)numfreepools * POOL_SIZE);
1744 total += printone("# bytes lost to pool headers", pool_header_bytes);
1745 total += printone("# bytes lost to quantization", quantization);
1746 total += printone("# bytes lost to arena alignment", arena_alignment);
1747 (void)printone("Total", total);
1750 #endif /* PYMALLOC_DEBUG */
1752 #ifdef Py_USING_MEMORY_DEBUGGER
1753 /* Make this function last so gcc won't inline it since the definition is
1754 * after the reference.
1757 Py_ADDRESS_IN_RANGE(void *P, poolp pool)
1759 return pool->arenaindex < maxarenas &&
1760 (uptr)P - arenas[pool->arenaindex].address < (uptr)ARENA_SIZE &&
1761 arenas[pool->arenaindex].address != 0;
1763 #endif