blob: 9cd6a50466c359c6f5e90ffbb7b6888cdb195554 [file] [log] [blame]
Tim Peters1221c0a2002-03-23 00:20:15 +00001#include "Python.h"
2
3#ifdef WITH_PYMALLOC
4
Antoine Pitrouf0effe62011-11-26 01:11:02 +01005#ifdef HAVE_MMAP
6 #include <sys/mman.h>
7 #ifdef MAP_ANONYMOUS
8 #define ARENAS_USE_MMAP
9 #endif
Antoine Pitrou6f26be02011-05-03 18:18:59 +020010#endif
11
Benjamin Peterson05159c42009-12-03 03:01:27 +000012#ifdef WITH_VALGRIND
13#include <valgrind/valgrind.h>
14
15/* If we're using GCC, use __builtin_expect() to reduce overhead of
16 the valgrind checks */
17#if defined(__GNUC__) && (__GNUC__ > 2) && defined(__OPTIMIZE__)
18# define UNLIKELY(value) __builtin_expect((value), 0)
19#else
20# define UNLIKELY(value) (value)
21#endif
22
23/* -1 indicates that we haven't checked that we're running on valgrind yet. */
24static int running_on_valgrind = -1;
25#endif
26
Neil Schemenauera35c6882001-02-27 04:45:05 +000027/* An object allocator for Python.
28
29 Here is an introduction to the layers of the Python memory architecture,
30 showing where the object allocator is actually used (layer +2), It is
31 called for every object allocation and deallocation (PyObject_New/Del),
32 unless the object-specific allocators implement a proprietary allocation
33 scheme (ex.: ints use a simple free list). This is also the place where
34 the cyclic garbage collector operates selectively on container objects.
35
36
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000037 Object-specific allocators
Neil Schemenauera35c6882001-02-27 04:45:05 +000038 _____ ______ ______ ________
39 [ int ] [ dict ] [ list ] ... [ string ] Python core |
40+3 | <----- Object-specific memory -----> | <-- Non-object memory --> |
41 _______________________________ | |
42 [ Python's object allocator ] | |
43+2 | ####### Object memory ####### | <------ Internal buffers ------> |
44 ______________________________________________________________ |
45 [ Python's raw memory allocator (PyMem_ API) ] |
46+1 | <----- Python memory (under PyMem manager's control) ------> | |
47 __________________________________________________________________
48 [ Underlying general-purpose allocator (ex: C library malloc) ]
49 0 | <------ Virtual memory allocated for the python process -------> |
50
51 =========================================================================
52 _______________________________________________________________________
53 [ OS-specific Virtual Memory Manager (VMM) ]
54-1 | <--- Kernel dynamic storage allocation & management (page-based) ---> |
55 __________________________________ __________________________________
56 [ ] [ ]
57-2 | <-- Physical memory: ROM/RAM --> | | <-- Secondary storage (swap) --> |
58
59*/
60/*==========================================================================*/
61
62/* A fast, special-purpose memory allocator for small blocks, to be used
63 on top of a general-purpose malloc -- heavily based on previous art. */
64
65/* Vladimir Marangozov -- August 2000 */
66
67/*
68 * "Memory management is where the rubber meets the road -- if we do the wrong
69 * thing at any level, the results will not be good. And if we don't make the
70 * levels work well together, we are in serious trouble." (1)
71 *
72 * (1) Paul R. Wilson, Mark S. Johnstone, Michael Neely, and David Boles,
73 * "Dynamic Storage Allocation: A Survey and Critical Review",
74 * in Proc. 1995 Int'l. Workshop on Memory Management, September 1995.
75 */
76
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000077/* #undef WITH_MEMORY_LIMITS */ /* disable mem limit checks */
Neil Schemenauera35c6882001-02-27 04:45:05 +000078
79/*==========================================================================*/
80
81/*
Neil Schemenauera35c6882001-02-27 04:45:05 +000082 * Allocation strategy abstract:
83 *
84 * For small requests, the allocator sub-allocates <Big> blocks of memory.
Antoine Pitrou6f26be02011-05-03 18:18:59 +020085 * Requests greater than SMALL_REQUEST_THRESHOLD bytes are routed to the
86 * system's allocator.
Tim Petersce7fb9b2002-03-23 00:28:57 +000087 *
Neil Schemenauera35c6882001-02-27 04:45:05 +000088 * Small requests are grouped in size classes spaced 8 bytes apart, due
89 * to the required valid alignment of the returned address. Requests of
90 * a particular size are serviced from memory pools of 4K (one VMM page).
91 * Pools are fragmented on demand and contain free lists of blocks of one
92 * particular size class. In other words, there is a fixed-size allocator
93 * for each size class. Free pools are shared by the different allocators
94 * thus minimizing the space reserved for a particular size class.
95 *
96 * This allocation strategy is a variant of what is known as "simple
97 * segregated storage based on array of free lists". The main drawback of
98 * simple segregated storage is that we might end up with lot of reserved
99 * memory for the different free lists, which degenerate in time. To avoid
100 * this, we partition each free list in pools and we share dynamically the
101 * reserved space between all free lists. This technique is quite efficient
102 * for memory intensive programs which allocate mainly small-sized blocks.
103 *
104 * For small requests we have the following table:
105 *
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000106 * Request in bytes Size of allocated block Size class idx
Neil Schemenauera35c6882001-02-27 04:45:05 +0000107 * ----------------------------------------------------------------
108 * 1-8 8 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000109 * 9-16 16 1
110 * 17-24 24 2
111 * 25-32 32 3
112 * 33-40 40 4
113 * 41-48 48 5
114 * 49-56 56 6
115 * 57-64 64 7
116 * 65-72 72 8
117 * ... ... ...
Antoine Pitrou6f26be02011-05-03 18:18:59 +0200118 * 497-504 504 62
119 * 505-512 512 63
Tim Petersce7fb9b2002-03-23 00:28:57 +0000120 *
Antoine Pitrou6f26be02011-05-03 18:18:59 +0200121 * 0, SMALL_REQUEST_THRESHOLD + 1 and up: routed to the underlying
122 * allocator.
Neil Schemenauera35c6882001-02-27 04:45:05 +0000123 */
124
125/*==========================================================================*/
126
127/*
128 * -- Main tunable settings section --
129 */
130
131/*
132 * Alignment of addresses returned to the user. 8-bytes alignment works
133 * on most current architectures (with 32-bit or 64-bit address busses).
134 * The alignment value is also used for grouping small requests in size
135 * classes spaced ALIGNMENT bytes apart.
136 *
137 * You shouldn't change this unless you know what you are doing.
138 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000139#define ALIGNMENT 8 /* must be 2^N */
140#define ALIGNMENT_SHIFT 3
141#define ALIGNMENT_MASK (ALIGNMENT - 1)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000142
Tim Peterse70ddf32002-04-05 04:32:29 +0000143/* Return the number of bytes in size class I, as a uint. */
144#define INDEX2SIZE(I) (((uint)(I) + 1) << ALIGNMENT_SHIFT)
145
Neil Schemenauera35c6882001-02-27 04:45:05 +0000146/*
147 * Max size threshold below which malloc requests are considered to be
148 * small enough in order to use preallocated memory pools. You can tune
149 * this value according to your application behaviour and memory needs.
150 *
Antoine Pitrou6f26be02011-05-03 18:18:59 +0200151 * Note: a size threshold of 512 guarantees that newly created dictionaries
152 * will be allocated from preallocated memory pools on 64-bit.
153 *
Neil Schemenauera35c6882001-02-27 04:45:05 +0000154 * The following invariants must hold:
Antoine Pitrou6f26be02011-05-03 18:18:59 +0200155 * 1) ALIGNMENT <= SMALL_REQUEST_THRESHOLD <= 512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000156 * 2) SMALL_REQUEST_THRESHOLD is evenly divisible by ALIGNMENT
Neil Schemenauera35c6882001-02-27 04:45:05 +0000157 *
158 * Although not required, for better performance and space efficiency,
159 * it is recommended that SMALL_REQUEST_THRESHOLD is set to a power of 2.
160 */
Antoine Pitrou6f26be02011-05-03 18:18:59 +0200161#define SMALL_REQUEST_THRESHOLD 512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000162#define NB_SMALL_SIZE_CLASSES (SMALL_REQUEST_THRESHOLD / ALIGNMENT)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000163
164/*
165 * The system's VMM page size can be obtained on most unices with a
166 * getpagesize() call or deduced from various header files. To make
167 * things simpler, we assume that it is 4K, which is OK for most systems.
168 * It is probably better if this is the native page size, but it doesn't
Tim Petersecc6e6a2005-07-10 22:30:55 +0000169 * have to be. In theory, if SYSTEM_PAGE_SIZE is larger than the native page
170 * size, then `POOL_ADDR(p)->arenaindex' could rarely cause a segmentation
171 * violation fault. 4K is apparently OK for all the platforms that python
Martin v. Löwis8c140282002-10-26 15:01:53 +0000172 * currently targets.
Neil Schemenauera35c6882001-02-27 04:45:05 +0000173 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000174#define SYSTEM_PAGE_SIZE (4 * 1024)
175#define SYSTEM_PAGE_SIZE_MASK (SYSTEM_PAGE_SIZE - 1)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000176
177/*
178 * Maximum amount of memory managed by the allocator for small requests.
179 */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000180#ifdef WITH_MEMORY_LIMITS
181#ifndef SMALL_MEMORY_LIMIT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000182#define SMALL_MEMORY_LIMIT (64 * 1024 * 1024) /* 64 MB -- more? */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000183#endif
184#endif
185
186/*
187 * The allocator sub-allocates <Big> blocks of memory (called arenas) aligned
188 * on a page boundary. This is a reserved virtual address space for the
Antoine Pitrouf0effe62011-11-26 01:11:02 +0100189 * current process (obtained through a malloc()/mmap() call). In no way this
190 * means that the memory arenas will be used entirely. A malloc(<Big>) is
191 * usually an address range reservation for <Big> bytes, unless all pages within
192 * this space are referenced subsequently. So malloc'ing big blocks and not
193 * using them does not mean "wasting memory". It's an addressable range
194 * wastage...
Neil Schemenauera35c6882001-02-27 04:45:05 +0000195 *
Antoine Pitrouf0effe62011-11-26 01:11:02 +0100196 * Arenas are allocated with mmap() on systems supporting anonymous memory
197 * mappings to reduce heap fragmentation.
Neil Schemenauera35c6882001-02-27 04:45:05 +0000198 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000199#define ARENA_SIZE (256 << 10) /* 256KB */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000200
201#ifdef WITH_MEMORY_LIMITS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000202#define MAX_ARENAS (SMALL_MEMORY_LIMIT / ARENA_SIZE)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000203#endif
204
205/*
206 * Size of the pools used for small blocks. Should be a power of 2,
Tim Petersc2ce91a2002-03-30 21:36:04 +0000207 * between 1K and SYSTEM_PAGE_SIZE, that is: 1k, 2k, 4k.
Neil Schemenauera35c6882001-02-27 04:45:05 +0000208 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000209#define POOL_SIZE SYSTEM_PAGE_SIZE /* must be 2^N */
210#define POOL_SIZE_MASK SYSTEM_PAGE_SIZE_MASK
Neil Schemenauera35c6882001-02-27 04:45:05 +0000211
212/*
213 * -- End of tunable settings section --
214 */
215
216/*==========================================================================*/
217
218/*
219 * Locking
220 *
221 * To reduce lock contention, it would probably be better to refine the
222 * crude function locking with per size class locking. I'm not positive
223 * however, whether it's worth switching to such locking policy because
224 * of the performance penalty it might introduce.
225 *
226 * The following macros describe the simplest (should also be the fastest)
227 * lock object on a particular platform and the init/fini/lock/unlock
228 * operations on it. The locks defined here are not expected to be recursive
229 * because it is assumed that they will always be called in the order:
230 * INIT, [LOCK, UNLOCK]*, FINI.
231 */
232
233/*
234 * Python's threads are serialized, so object malloc locking is disabled.
235 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000236#define SIMPLELOCK_DECL(lock) /* simple lock declaration */
237#define SIMPLELOCK_INIT(lock) /* allocate (if needed) and initialize */
238#define SIMPLELOCK_FINI(lock) /* free/destroy an existing lock */
239#define SIMPLELOCK_LOCK(lock) /* acquire released lock */
240#define SIMPLELOCK_UNLOCK(lock) /* release acquired lock */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000241
242/*
243 * Basic types
244 * I don't care if these are defined in <sys/types.h> or elsewhere. Axiom.
245 */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000246#undef uchar
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000247#define uchar unsigned char /* assuming == 8 bits */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000248
Neil Schemenauera35c6882001-02-27 04:45:05 +0000249#undef uint
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000250#define uint unsigned int /* assuming >= 16 bits */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000251
252#undef ulong
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000253#define ulong unsigned long /* assuming >= 32 bits */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000254
Tim Petersd97a1c02002-03-30 06:09:22 +0000255#undef uptr
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000256#define uptr Py_uintptr_t
Tim Petersd97a1c02002-03-30 06:09:22 +0000257
Neil Schemenauera35c6882001-02-27 04:45:05 +0000258/* When you say memory, my mind reasons in terms of (pointers to) blocks */
259typedef uchar block;
260
Tim Peterse70ddf32002-04-05 04:32:29 +0000261/* Pool for small blocks. */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000262struct pool_header {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000263 union { block *_padding;
Stefan Krah735bb122010-11-26 10:54:09 +0000264 uint count; } ref; /* number of allocated blocks */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000265 block *freeblock; /* pool's free list head */
266 struct pool_header *nextpool; /* next pool of this size class */
267 struct pool_header *prevpool; /* previous pool "" */
268 uint arenaindex; /* index into arenas of base adr */
269 uint szidx; /* block size class index */
270 uint nextoffset; /* bytes to virgin block */
271 uint maxnextoffset; /* largest valid nextoffset */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000272};
273
274typedef struct pool_header *poolp;
275
Thomas Woutersa9773292006-04-21 09:43:23 +0000276/* Record keeping for arenas. */
277struct arena_object {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000278 /* The address of the arena, as returned by malloc. Note that 0
279 * will never be returned by a successful malloc, and is used
280 * here to mark an arena_object that doesn't correspond to an
281 * allocated arena.
282 */
283 uptr address;
Thomas Woutersa9773292006-04-21 09:43:23 +0000284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000285 /* Pool-aligned pointer to the next pool to be carved off. */
286 block* pool_address;
Thomas Woutersa9773292006-04-21 09:43:23 +0000287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000288 /* The number of available pools in the arena: free pools + never-
289 * allocated pools.
290 */
291 uint nfreepools;
Thomas Woutersa9773292006-04-21 09:43:23 +0000292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000293 /* The total number of pools in the arena, whether or not available. */
294 uint ntotalpools;
Thomas Woutersa9773292006-04-21 09:43:23 +0000295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000296 /* Singly-linked list of available pools. */
297 struct pool_header* freepools;
Thomas Woutersa9773292006-04-21 09:43:23 +0000298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000299 /* Whenever this arena_object is not associated with an allocated
300 * arena, the nextarena member is used to link all unassociated
301 * arena_objects in the singly-linked `unused_arena_objects` list.
302 * The prevarena member is unused in this case.
303 *
304 * When this arena_object is associated with an allocated arena
305 * with at least one available pool, both members are used in the
306 * doubly-linked `usable_arenas` list, which is maintained in
307 * increasing order of `nfreepools` values.
308 *
309 * Else this arena_object is associated with an allocated arena
310 * all of whose pools are in use. `nextarena` and `prevarena`
311 * are both meaningless in this case.
312 */
313 struct arena_object* nextarena;
314 struct arena_object* prevarena;
Thomas Woutersa9773292006-04-21 09:43:23 +0000315};
316
Neil Schemenauera35c6882001-02-27 04:45:05 +0000317#undef ROUNDUP
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000318#define ROUNDUP(x) (((x) + ALIGNMENT_MASK) & ~ALIGNMENT_MASK)
319#define POOL_OVERHEAD ROUNDUP(sizeof(struct pool_header))
Neil Schemenauera35c6882001-02-27 04:45:05 +0000320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000321#define DUMMY_SIZE_IDX 0xffff /* size class of newly cached pools */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000322
Tim Petersd97a1c02002-03-30 06:09:22 +0000323/* Round pointer P down to the closest pool-aligned address <= P, as a poolp */
Tim Peterse70ddf32002-04-05 04:32:29 +0000324#define POOL_ADDR(P) ((poolp)((uptr)(P) & ~(uptr)POOL_SIZE_MASK))
325
Tim Peters16bcb6b2002-04-05 05:45:31 +0000326/* Return total number of blocks in pool of size index I, as a uint. */
327#define NUMBLOCKS(I) ((uint)(POOL_SIZE - POOL_OVERHEAD) / INDEX2SIZE(I))
Tim Petersd97a1c02002-03-30 06:09:22 +0000328
Neil Schemenauera35c6882001-02-27 04:45:05 +0000329/*==========================================================================*/
330
331/*
332 * This malloc lock
333 */
Jeremy Hyltond1fedb62002-07-18 18:49:52 +0000334SIMPLELOCK_DECL(_malloc_lock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000335#define LOCK() SIMPLELOCK_LOCK(_malloc_lock)
336#define UNLOCK() SIMPLELOCK_UNLOCK(_malloc_lock)
337#define LOCK_INIT() SIMPLELOCK_INIT(_malloc_lock)
338#define LOCK_FINI() SIMPLELOCK_FINI(_malloc_lock)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000339
340/*
Tim Peters1e16db62002-03-31 01:05:22 +0000341 * Pool table -- headed, circular, doubly-linked lists of partially used pools.
342
343This is involved. For an index i, usedpools[i+i] is the header for a list of
344all partially used pools holding small blocks with "size class idx" i. So
345usedpools[0] corresponds to blocks of size 8, usedpools[2] to blocks of size
34616, and so on: index 2*i <-> blocks of size (i+1)<<ALIGNMENT_SHIFT.
347
Thomas Woutersa9773292006-04-21 09:43:23 +0000348Pools are carved off an arena's highwater mark (an arena_object's pool_address
349member) as needed. Once carved off, a pool is in one of three states forever
350after:
Tim Peters1e16db62002-03-31 01:05:22 +0000351
Tim Peters338e0102002-04-01 19:23:44 +0000352used == partially used, neither empty nor full
353 At least one block in the pool is currently allocated, and at least one
354 block in the pool is not currently allocated (note this implies a pool
355 has room for at least two blocks).
356 This is a pool's initial state, as a pool is created only when malloc
357 needs space.
358 The pool holds blocks of a fixed size, and is in the circular list headed
359 at usedpools[i] (see above). It's linked to the other used pools of the
360 same size class via the pool_header's nextpool and prevpool members.
361 If all but one block is currently allocated, a malloc can cause a
362 transition to the full state. If all but one block is not currently
363 allocated, a free can cause a transition to the empty state.
Tim Peters1e16db62002-03-31 01:05:22 +0000364
Tim Peters338e0102002-04-01 19:23:44 +0000365full == all the pool's blocks are currently allocated
366 On transition to full, a pool is unlinked from its usedpools[] list.
367 It's not linked to from anything then anymore, and its nextpool and
368 prevpool members are meaningless until it transitions back to used.
369 A free of a block in a full pool puts the pool back in the used state.
370 Then it's linked in at the front of the appropriate usedpools[] list, so
371 that the next allocation for its size class will reuse the freed block.
372
373empty == all the pool's blocks are currently available for allocation
374 On transition to empty, a pool is unlinked from its usedpools[] list,
Thomas Woutersa9773292006-04-21 09:43:23 +0000375 and linked to the front of its arena_object's singly-linked freepools list,
Tim Peters338e0102002-04-01 19:23:44 +0000376 via its nextpool member. The prevpool member has no meaning in this case.
377 Empty pools have no inherent size class: the next time a malloc finds
378 an empty list in usedpools[], it takes the first pool off of freepools.
379 If the size class needed happens to be the same as the size class the pool
Tim Peterse70ddf32002-04-05 04:32:29 +0000380 last had, some pool initialization can be skipped.
Tim Peters338e0102002-04-01 19:23:44 +0000381
382
383Block Management
384
385Blocks within pools are again carved out as needed. pool->freeblock points to
386the start of a singly-linked list of free blocks within the pool. When a
387block is freed, it's inserted at the front of its pool's freeblock list. Note
388that the available blocks in a pool are *not* linked all together when a pool
Tim Peterse70ddf32002-04-05 04:32:29 +0000389is initialized. Instead only "the first two" (lowest addresses) blocks are
390set up, returning the first such block, and setting pool->freeblock to a
391one-block list holding the second such block. This is consistent with that
392pymalloc strives at all levels (arena, pool, and block) never to touch a piece
393of memory until it's actually needed.
394
395So long as a pool is in the used state, we're certain there *is* a block
Tim Peters52aefc82002-04-11 06:36:45 +0000396available for allocating, and pool->freeblock is not NULL. If pool->freeblock
397points to the end of the free list before we've carved the entire pool into
398blocks, that means we simply haven't yet gotten to one of the higher-address
399blocks. The offset from the pool_header to the start of "the next" virgin
400block is stored in the pool_header nextoffset member, and the largest value
401of nextoffset that makes sense is stored in the maxnextoffset member when a
402pool is initialized. All the blocks in a pool have been passed out at least
403once when and only when nextoffset > maxnextoffset.
Tim Peters338e0102002-04-01 19:23:44 +0000404
Tim Peters1e16db62002-03-31 01:05:22 +0000405
406Major obscurity: While the usedpools vector is declared to have poolp
407entries, it doesn't really. It really contains two pointers per (conceptual)
408poolp entry, the nextpool and prevpool members of a pool_header. The
409excruciating initialization code below fools C so that
410
411 usedpool[i+i]
412
413"acts like" a genuine poolp, but only so long as you only reference its
414nextpool and prevpool members. The "- 2*sizeof(block *)" gibberish is
415compensating for that a pool_header's nextpool and prevpool members
416immediately follow a pool_header's first two members:
417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000418 union { block *_padding;
Stefan Krah735bb122010-11-26 10:54:09 +0000419 uint count; } ref;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 block *freeblock;
Tim Peters1e16db62002-03-31 01:05:22 +0000421
422each of which consume sizeof(block *) bytes. So what usedpools[i+i] really
423contains is a fudged-up pointer p such that *if* C believes it's a poolp
424pointer, then p->nextpool and p->prevpool are both p (meaning that the headed
425circular list is empty).
426
427It's unclear why the usedpools setup is so convoluted. It could be to
428minimize the amount of cache required to hold this heavily-referenced table
429(which only *needs* the two interpool pointer members of a pool_header). OTOH,
430referencing code has to remember to "double the index" and doing so isn't
431free, usedpools[0] isn't a strictly legal pointer, and we're crucially relying
432on that C doesn't insert any padding anywhere in a pool_header at or before
433the prevpool member.
434**************************************************************************** */
435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000436#define PTA(x) ((poolp )((uchar *)&(usedpools[2*(x)]) - 2*sizeof(block *)))
437#define PT(x) PTA(x), PTA(x)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000438
439static poolp usedpools[2 * ((NB_SMALL_SIZE_CLASSES + 7) / 8) * 8] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000440 PT(0), PT(1), PT(2), PT(3), PT(4), PT(5), PT(6), PT(7)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000441#if NB_SMALL_SIZE_CLASSES > 8
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000442 , PT(8), PT(9), PT(10), PT(11), PT(12), PT(13), PT(14), PT(15)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000443#if NB_SMALL_SIZE_CLASSES > 16
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000444 , PT(16), PT(17), PT(18), PT(19), PT(20), PT(21), PT(22), PT(23)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000445#if NB_SMALL_SIZE_CLASSES > 24
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000446 , PT(24), PT(25), PT(26), PT(27), PT(28), PT(29), PT(30), PT(31)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000447#if NB_SMALL_SIZE_CLASSES > 32
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000448 , PT(32), PT(33), PT(34), PT(35), PT(36), PT(37), PT(38), PT(39)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000449#if NB_SMALL_SIZE_CLASSES > 40
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000450 , PT(40), PT(41), PT(42), PT(43), PT(44), PT(45), PT(46), PT(47)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000451#if NB_SMALL_SIZE_CLASSES > 48
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000452 , PT(48), PT(49), PT(50), PT(51), PT(52), PT(53), PT(54), PT(55)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000453#if NB_SMALL_SIZE_CLASSES > 56
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000454 , PT(56), PT(57), PT(58), PT(59), PT(60), PT(61), PT(62), PT(63)
Antoine Pitrou6f26be02011-05-03 18:18:59 +0200455#if NB_SMALL_SIZE_CLASSES > 64
456#error "NB_SMALL_SIZE_CLASSES should be less than 64"
457#endif /* NB_SMALL_SIZE_CLASSES > 64 */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000458#endif /* NB_SMALL_SIZE_CLASSES > 56 */
459#endif /* NB_SMALL_SIZE_CLASSES > 48 */
460#endif /* NB_SMALL_SIZE_CLASSES > 40 */
461#endif /* NB_SMALL_SIZE_CLASSES > 32 */
462#endif /* NB_SMALL_SIZE_CLASSES > 24 */
463#endif /* NB_SMALL_SIZE_CLASSES > 16 */
464#endif /* NB_SMALL_SIZE_CLASSES > 8 */
465};
466
Thomas Woutersa9773292006-04-21 09:43:23 +0000467/*==========================================================================
468Arena management.
Neil Schemenauera35c6882001-02-27 04:45:05 +0000469
Thomas Woutersa9773292006-04-21 09:43:23 +0000470`arenas` is a vector of arena_objects. It contains maxarenas entries, some of
471which may not be currently used (== they're arena_objects that aren't
472currently associated with an allocated arena). Note that arenas proper are
473separately malloc'ed.
Neil Schemenauera35c6882001-02-27 04:45:05 +0000474
Thomas Woutersa9773292006-04-21 09:43:23 +0000475Prior to Python 2.5, arenas were never free()'ed. Starting with Python 2.5,
476we do try to free() arenas, and use some mild heuristic strategies to increase
477the likelihood that arenas eventually can be freed.
478
479unused_arena_objects
480
481 This is a singly-linked list of the arena_objects that are currently not
482 being used (no arena is associated with them). Objects are taken off the
483 head of the list in new_arena(), and are pushed on the head of the list in
484 PyObject_Free() when the arena is empty. Key invariant: an arena_object
485 is on this list if and only if its .address member is 0.
486
487usable_arenas
488
489 This is a doubly-linked list of the arena_objects associated with arenas
490 that have pools available. These pools are either waiting to be reused,
491 or have not been used before. The list is sorted to have the most-
492 allocated arenas first (ascending order based on the nfreepools member).
493 This means that the next allocation will come from a heavily used arena,
494 which gives the nearly empty arenas a chance to be returned to the system.
495 In my unscientific tests this dramatically improved the number of arenas
496 that could be freed.
497
498Note that an arena_object associated with an arena all of whose pools are
499currently in use isn't on either list.
500*/
501
502/* Array of objects used to track chunks of memory (arenas). */
503static struct arena_object* arenas = NULL;
504/* Number of slots currently allocated in the `arenas` vector. */
Tim Peters1d99af82002-03-30 10:35:09 +0000505static uint maxarenas = 0;
Tim Petersd97a1c02002-03-30 06:09:22 +0000506
Thomas Woutersa9773292006-04-21 09:43:23 +0000507/* The head of the singly-linked, NULL-terminated list of available
508 * arena_objects.
Tim Petersd97a1c02002-03-30 06:09:22 +0000509 */
Thomas Woutersa9773292006-04-21 09:43:23 +0000510static struct arena_object* unused_arena_objects = NULL;
511
512/* The head of the doubly-linked, NULL-terminated at each end, list of
513 * arena_objects associated with arenas that have pools available.
514 */
515static struct arena_object* usable_arenas = NULL;
516
517/* How many arena_objects do we initially allocate?
518 * 16 = can allocate 16 arenas = 16 * ARENA_SIZE = 4MB before growing the
519 * `arenas` vector.
520 */
521#define INITIAL_ARENA_OBJECTS 16
522
523/* Number of arenas allocated that haven't been free()'d. */
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000524static size_t narenas_currently_allocated = 0;
Thomas Woutersa9773292006-04-21 09:43:23 +0000525
526#ifdef PYMALLOC_DEBUG
527/* Total number of times malloc() called to allocate an arena. */
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000528static size_t ntimes_arena_allocated = 0;
Thomas Woutersa9773292006-04-21 09:43:23 +0000529/* High water mark (max value ever seen) for narenas_currently_allocated. */
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000530static size_t narenas_highwater = 0;
Thomas Woutersa9773292006-04-21 09:43:23 +0000531#endif
532
533/* Allocate a new arena. If we run out of memory, return NULL. Else
534 * allocate a new arena, and return the address of an arena_object
535 * describing the new arena. It's expected that the caller will set
536 * `usable_arenas` to the return value.
537 */
538static struct arena_object*
Tim Petersd97a1c02002-03-30 06:09:22 +0000539new_arena(void)
540{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000541 struct arena_object* arenaobj;
542 uint excess; /* number of bytes above pool alignment */
Victor Stinnerba108822012-03-10 00:21:44 +0100543 void *address;
544 int err;
Tim Petersd97a1c02002-03-30 06:09:22 +0000545
Tim Peters0e871182002-04-13 08:29:14 +0000546#ifdef PYMALLOC_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000547 if (Py_GETENV("PYTHONMALLOCSTATS"))
548 _PyObject_DebugMallocStats();
Tim Peters0e871182002-04-13 08:29:14 +0000549#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000550 if (unused_arena_objects == NULL) {
551 uint i;
552 uint numarenas;
553 size_t nbytes;
Tim Peters0e871182002-04-13 08:29:14 +0000554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 /* Double the number of arena objects on each allocation.
556 * Note that it's possible for `numarenas` to overflow.
557 */
558 numarenas = maxarenas ? maxarenas << 1 : INITIAL_ARENA_OBJECTS;
559 if (numarenas <= maxarenas)
560 return NULL; /* overflow */
Martin v. Löwis5aca8822008-09-11 06:55:48 +0000561#if SIZEOF_SIZE_T <= SIZEOF_INT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000562 if (numarenas > PY_SIZE_MAX / sizeof(*arenas))
563 return NULL; /* overflow */
Martin v. Löwis5aca8822008-09-11 06:55:48 +0000564#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000565 nbytes = numarenas * sizeof(*arenas);
566 arenaobj = (struct arena_object *)realloc(arenas, nbytes);
567 if (arenaobj == NULL)
568 return NULL;
569 arenas = arenaobj;
Thomas Woutersa9773292006-04-21 09:43:23 +0000570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000571 /* We might need to fix pointers that were copied. However,
572 * new_arena only gets called when all the pages in the
573 * previous arenas are full. Thus, there are *no* pointers
574 * into the old array. Thus, we don't have to worry about
575 * invalid pointers. Just to be sure, some asserts:
576 */
577 assert(usable_arenas == NULL);
578 assert(unused_arena_objects == NULL);
Thomas Woutersa9773292006-04-21 09:43:23 +0000579
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000580 /* Put the new arenas on the unused_arena_objects list. */
581 for (i = maxarenas; i < numarenas; ++i) {
582 arenas[i].address = 0; /* mark as unassociated */
583 arenas[i].nextarena = i < numarenas - 1 ?
584 &arenas[i+1] : NULL;
585 }
Thomas Woutersa9773292006-04-21 09:43:23 +0000586
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000587 /* Update globals. */
588 unused_arena_objects = &arenas[maxarenas];
589 maxarenas = numarenas;
590 }
Tim Petersd97a1c02002-03-30 06:09:22 +0000591
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000592 /* Take the next available arena object off the head of the list. */
593 assert(unused_arena_objects != NULL);
594 arenaobj = unused_arena_objects;
595 unused_arena_objects = arenaobj->nextarena;
596 assert(arenaobj->address == 0);
Antoine Pitrouf0effe62011-11-26 01:11:02 +0100597#ifdef ARENAS_USE_MMAP
Victor Stinnerba108822012-03-10 00:21:44 +0100598 address = mmap(NULL, ARENA_SIZE, PROT_READ|PROT_WRITE,
Antoine Pitrouf0effe62011-11-26 01:11:02 +0100599 MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
Victor Stinnerba108822012-03-10 00:21:44 +0100600 err = (address == MAP_FAILED);
Antoine Pitrouf0effe62011-11-26 01:11:02 +0100601#else
Victor Stinnerba108822012-03-10 00:21:44 +0100602 address = malloc(ARENA_SIZE);
603 err = (address == 0);
Antoine Pitrouf0effe62011-11-26 01:11:02 +0100604#endif
Victor Stinnerba108822012-03-10 00:21:44 +0100605 if (err) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 /* The allocation failed: return NULL after putting the
607 * arenaobj back.
608 */
609 arenaobj->nextarena = unused_arena_objects;
610 unused_arena_objects = arenaobj;
611 return NULL;
612 }
Victor Stinnerba108822012-03-10 00:21:44 +0100613 arenaobj->address = (uptr)address;
Tim Petersd97a1c02002-03-30 06:09:22 +0000614
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000615 ++narenas_currently_allocated;
Thomas Woutersa9773292006-04-21 09:43:23 +0000616#ifdef PYMALLOC_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000617 ++ntimes_arena_allocated;
618 if (narenas_currently_allocated > narenas_highwater)
619 narenas_highwater = narenas_currently_allocated;
Thomas Woutersa9773292006-04-21 09:43:23 +0000620#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000621 arenaobj->freepools = NULL;
622 /* pool_address <- first pool-aligned address in the arena
623 nfreepools <- number of whole pools that fit after alignment */
624 arenaobj->pool_address = (block*)arenaobj->address;
625 arenaobj->nfreepools = ARENA_SIZE / POOL_SIZE;
626 assert(POOL_SIZE * arenaobj->nfreepools == ARENA_SIZE);
627 excess = (uint)(arenaobj->address & POOL_SIZE_MASK);
628 if (excess != 0) {
629 --arenaobj->nfreepools;
630 arenaobj->pool_address += POOL_SIZE - excess;
631 }
632 arenaobj->ntotalpools = arenaobj->nfreepools;
Thomas Woutersa9773292006-04-21 09:43:23 +0000633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 return arenaobj;
Tim Petersd97a1c02002-03-30 06:09:22 +0000635}
636
Thomas Woutersa9773292006-04-21 09:43:23 +0000637/*
638Py_ADDRESS_IN_RANGE(P, POOL)
639
640Return true if and only if P is an address that was allocated by pymalloc.
641POOL must be the pool address associated with P, i.e., POOL = POOL_ADDR(P)
642(the caller is asked to compute this because the macro expands POOL more than
643once, and for efficiency it's best for the caller to assign POOL_ADDR(P) to a
644variable and pass the latter to the macro; because Py_ADDRESS_IN_RANGE is
645called on every alloc/realloc/free, micro-efficiency is important here).
646
647Tricky: Let B be the arena base address associated with the pool, B =
648arenas[(POOL)->arenaindex].address. Then P belongs to the arena if and only if
649
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650 B <= P < B + ARENA_SIZE
Thomas Woutersa9773292006-04-21 09:43:23 +0000651
652Subtracting B throughout, this is true iff
653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000654 0 <= P-B < ARENA_SIZE
Thomas Woutersa9773292006-04-21 09:43:23 +0000655
656By using unsigned arithmetic, the "0 <=" half of the test can be skipped.
657
658Obscure: A PyMem "free memory" function can call the pymalloc free or realloc
659before the first arena has been allocated. `arenas` is still NULL in that
660case. We're relying on that maxarenas is also 0 in that case, so that
661(POOL)->arenaindex < maxarenas must be false, saving us from trying to index
662into a NULL arenas.
663
664Details: given P and POOL, the arena_object corresponding to P is AO =
665arenas[(POOL)->arenaindex]. Suppose obmalloc controls P. Then (barring wild
666stores, etc), POOL is the correct address of P's pool, AO.address is the
667correct base address of the pool's arena, and P must be within ARENA_SIZE of
668AO.address. In addition, AO.address is not 0 (no arena can start at address 0
669(NULL)). Therefore Py_ADDRESS_IN_RANGE correctly reports that obmalloc
670controls P.
671
672Now suppose obmalloc does not control P (e.g., P was obtained via a direct
673call to the system malloc() or realloc()). (POOL)->arenaindex may be anything
674in this case -- it may even be uninitialized trash. If the trash arenaindex
675is >= maxarenas, the macro correctly concludes at once that obmalloc doesn't
676control P.
677
678Else arenaindex is < maxarena, and AO is read up. If AO corresponds to an
679allocated arena, obmalloc controls all the memory in slice AO.address :
680AO.address+ARENA_SIZE. By case assumption, P is not controlled by obmalloc,
681so P doesn't lie in that slice, so the macro correctly reports that P is not
682controlled by obmalloc.
683
684Finally, if P is not controlled by obmalloc and AO corresponds to an unused
685arena_object (one not currently associated with an allocated arena),
686AO.address is 0, and the second test in the macro reduces to:
687
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000688 P < ARENA_SIZE
Thomas Woutersa9773292006-04-21 09:43:23 +0000689
690If P >= ARENA_SIZE (extremely likely), the macro again correctly concludes
691that P is not controlled by obmalloc. However, if P < ARENA_SIZE, this part
692of the test still passes, and the third clause (AO.address != 0) is necessary
693to get the correct result: AO.address is 0 in this case, so the macro
694correctly reports that P is not controlled by obmalloc (despite that P lies in
695slice AO.address : AO.address + ARENA_SIZE).
696
697Note: The third (AO.address != 0) clause was added in Python 2.5. Before
6982.5, arenas were never free()'ed, and an arenaindex < maxarena always
699corresponded to a currently-allocated arena, so the "P is not controlled by
700obmalloc, AO corresponds to an unused arena_object, and P < ARENA_SIZE" case
701was impossible.
702
703Note that the logic is excruciating, and reading up possibly uninitialized
704memory when P is not controlled by obmalloc (to get at (POOL)->arenaindex)
705creates problems for some memory debuggers. The overwhelming advantage is
706that this test determines whether an arbitrary address is controlled by
707obmalloc in a small constant time, independent of the number of arenas
708obmalloc controls. Since this test is needed at every entry point, it's
709extremely desirable that it be this fast.
Antoine Pitroub7fb2e22011-01-07 21:43:59 +0000710
711Since Py_ADDRESS_IN_RANGE may be reading from memory which was not allocated
712by Python, it is important that (POOL)->arenaindex is read only once, as
713another thread may be concurrently modifying the value without holding the
714GIL. To accomplish this, the arenaindex_temp variable is used to store
715(POOL)->arenaindex for the duration of the Py_ADDRESS_IN_RANGE macro's
716execution. The caller of the macro is responsible for declaring this
717variable.
Thomas Woutersa9773292006-04-21 09:43:23 +0000718*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000719#define Py_ADDRESS_IN_RANGE(P, POOL) \
Antoine Pitroub7fb2e22011-01-07 21:43:59 +0000720 ((arenaindex_temp = (POOL)->arenaindex) < maxarenas && \
721 (uptr)(P) - arenas[arenaindex_temp].address < (uptr)ARENA_SIZE && \
722 arenas[arenaindex_temp].address != 0)
Thomas Woutersa9773292006-04-21 09:43:23 +0000723
Neal Norwitz7eb3c912004-06-06 19:20:22 +0000724
725/* This is only useful when running memory debuggers such as
726 * Purify or Valgrind. Uncomment to use.
727 *
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000728#define Py_USING_MEMORY_DEBUGGER
Martin v. Löwis6fea2332008-09-25 04:15:27 +0000729 */
Neal Norwitz7eb3c912004-06-06 19:20:22 +0000730
731#ifdef Py_USING_MEMORY_DEBUGGER
732
733/* Py_ADDRESS_IN_RANGE may access uninitialized memory by design
734 * This leads to thousands of spurious warnings when using
735 * Purify or Valgrind. By making a function, we can easily
736 * suppress the uninitialized memory reads in this one function.
737 * So we won't ignore real errors elsewhere.
738 *
739 * Disable the macro and use a function.
740 */
741
742#undef Py_ADDRESS_IN_RANGE
743
Thomas Wouters89f507f2006-12-13 04:49:30 +0000744#if defined(__GNUC__) && ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 1) || \
Stefan Krah735bb122010-11-26 10:54:09 +0000745 (__GNUC__ >= 4))
Neal Norwitze5e5aa42005-11-13 18:55:39 +0000746#define Py_NO_INLINE __attribute__((__noinline__))
747#else
748#define Py_NO_INLINE
749#endif
750
751/* Don't make static, to try to ensure this isn't inlined. */
752int Py_ADDRESS_IN_RANGE(void *P, poolp pool) Py_NO_INLINE;
753#undef Py_NO_INLINE
Neal Norwitz7eb3c912004-06-06 19:20:22 +0000754#endif
Tim Peters338e0102002-04-01 19:23:44 +0000755
Neil Schemenauera35c6882001-02-27 04:45:05 +0000756/*==========================================================================*/
757
Tim Peters84c1b972002-04-04 04:44:32 +0000758/* malloc. Note that nbytes==0 tries to return a non-NULL pointer, distinct
759 * from all other currently live pointers. This may not be possible.
760 */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000761
762/*
763 * The basic blocks are ordered by decreasing execution frequency,
764 * which minimizes the number of jumps in the most common cases,
765 * improves branching prediction and instruction scheduling (small
766 * block allocations typically result in a couple of instructions).
767 * Unless the optimizer reorders everything, being too smart...
768 */
769
Neil Schemenauerd2560cd2002-04-12 03:10:20 +0000770#undef PyObject_Malloc
Neil Schemenauera35c6882001-02-27 04:45:05 +0000771void *
Neil Schemenauerd2560cd2002-04-12 03:10:20 +0000772PyObject_Malloc(size_t nbytes)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000773{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000774 block *bp;
775 poolp pool;
776 poolp next;
777 uint size;
Neil Schemenauera35c6882001-02-27 04:45:05 +0000778
Benjamin Peterson05159c42009-12-03 03:01:27 +0000779#ifdef WITH_VALGRIND
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000780 if (UNLIKELY(running_on_valgrind == -1))
781 running_on_valgrind = RUNNING_ON_VALGRIND;
782 if (UNLIKELY(running_on_valgrind))
783 goto redirect;
Benjamin Peterson05159c42009-12-03 03:01:27 +0000784#endif
785
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000786 /*
787 * Limit ourselves to PY_SSIZE_T_MAX bytes to prevent security holes.
788 * Most python internals blindly use a signed Py_ssize_t to track
789 * things without checking for overflows or negatives.
790 * As size_t is unsigned, checking for nbytes < 0 is not required.
791 */
792 if (nbytes > PY_SSIZE_T_MAX)
793 return NULL;
Georg Brandld492ad82008-07-23 16:13:07 +0000794
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000795 /*
796 * This implicitly redirects malloc(0).
797 */
798 if ((nbytes - 1) < SMALL_REQUEST_THRESHOLD) {
799 LOCK();
800 /*
801 * Most frequent paths first
802 */
803 size = (uint)(nbytes - 1) >> ALIGNMENT_SHIFT;
804 pool = usedpools[size + size];
805 if (pool != pool->nextpool) {
806 /*
807 * There is a used pool for this size class.
808 * Pick up the head block of its free list.
809 */
810 ++pool->ref.count;
811 bp = pool->freeblock;
812 assert(bp != NULL);
813 if ((pool->freeblock = *(block **)bp) != NULL) {
814 UNLOCK();
815 return (void *)bp;
816 }
817 /*
818 * Reached the end of the free list, try to extend it.
819 */
820 if (pool->nextoffset <= pool->maxnextoffset) {
821 /* There is room for another block. */
822 pool->freeblock = (block*)pool +
823 pool->nextoffset;
824 pool->nextoffset += INDEX2SIZE(size);
825 *(block **)(pool->freeblock) = NULL;
826 UNLOCK();
827 return (void *)bp;
828 }
829 /* Pool is full, unlink from used pools. */
830 next = pool->nextpool;
831 pool = pool->prevpool;
832 next->prevpool = pool;
833 pool->nextpool = next;
834 UNLOCK();
835 return (void *)bp;
836 }
Thomas Woutersa9773292006-04-21 09:43:23 +0000837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 /* There isn't a pool of the right size class immediately
839 * available: use a free pool.
840 */
841 if (usable_arenas == NULL) {
842 /* No arena has a free pool: allocate a new arena. */
Thomas Woutersa9773292006-04-21 09:43:23 +0000843#ifdef WITH_MEMORY_LIMITS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000844 if (narenas_currently_allocated >= MAX_ARENAS) {
845 UNLOCK();
846 goto redirect;
847 }
Thomas Woutersa9773292006-04-21 09:43:23 +0000848#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 usable_arenas = new_arena();
850 if (usable_arenas == NULL) {
851 UNLOCK();
852 goto redirect;
853 }
854 usable_arenas->nextarena =
855 usable_arenas->prevarena = NULL;
856 }
857 assert(usable_arenas->address != 0);
Thomas Woutersa9773292006-04-21 09:43:23 +0000858
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 /* Try to get a cached free pool. */
860 pool = usable_arenas->freepools;
861 if (pool != NULL) {
862 /* Unlink from cached pools. */
863 usable_arenas->freepools = pool->nextpool;
Thomas Woutersa9773292006-04-21 09:43:23 +0000864
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000865 /* This arena already had the smallest nfreepools
866 * value, so decreasing nfreepools doesn't change
867 * that, and we don't need to rearrange the
868 * usable_arenas list. However, if the arena has
869 * become wholly allocated, we need to remove its
870 * arena_object from usable_arenas.
871 */
872 --usable_arenas->nfreepools;
873 if (usable_arenas->nfreepools == 0) {
874 /* Wholly allocated: remove. */
875 assert(usable_arenas->freepools == NULL);
876 assert(usable_arenas->nextarena == NULL ||
877 usable_arenas->nextarena->prevarena ==
878 usable_arenas);
Thomas Woutersa9773292006-04-21 09:43:23 +0000879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 usable_arenas = usable_arenas->nextarena;
881 if (usable_arenas != NULL) {
882 usable_arenas->prevarena = NULL;
883 assert(usable_arenas->address != 0);
884 }
885 }
886 else {
887 /* nfreepools > 0: it must be that freepools
888 * isn't NULL, or that we haven't yet carved
889 * off all the arena's pools for the first
890 * time.
891 */
892 assert(usable_arenas->freepools != NULL ||
893 usable_arenas->pool_address <=
894 (block*)usable_arenas->address +
895 ARENA_SIZE - POOL_SIZE);
896 }
897 init_pool:
898 /* Frontlink to used pools. */
899 next = usedpools[size + size]; /* == prev */
900 pool->nextpool = next;
901 pool->prevpool = next;
902 next->nextpool = pool;
903 next->prevpool = pool;
904 pool->ref.count = 1;
905 if (pool->szidx == size) {
906 /* Luckily, this pool last contained blocks
907 * of the same size class, so its header
908 * and free list are already initialized.
909 */
910 bp = pool->freeblock;
911 pool->freeblock = *(block **)bp;
912 UNLOCK();
913 return (void *)bp;
914 }
915 /*
916 * Initialize the pool header, set up the free list to
917 * contain just the second block, and return the first
918 * block.
919 */
920 pool->szidx = size;
921 size = INDEX2SIZE(size);
922 bp = (block *)pool + POOL_OVERHEAD;
923 pool->nextoffset = POOL_OVERHEAD + (size << 1);
924 pool->maxnextoffset = POOL_SIZE - size;
925 pool->freeblock = bp + size;
926 *(block **)(pool->freeblock) = NULL;
927 UNLOCK();
928 return (void *)bp;
929 }
Thomas Woutersa9773292006-04-21 09:43:23 +0000930
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 /* Carve off a new pool. */
932 assert(usable_arenas->nfreepools > 0);
933 assert(usable_arenas->freepools == NULL);
934 pool = (poolp)usable_arenas->pool_address;
935 assert((block*)pool <= (block*)usable_arenas->address +
936 ARENA_SIZE - POOL_SIZE);
937 pool->arenaindex = usable_arenas - arenas;
938 assert(&arenas[pool->arenaindex] == usable_arenas);
939 pool->szidx = DUMMY_SIZE_IDX;
940 usable_arenas->pool_address += POOL_SIZE;
941 --usable_arenas->nfreepools;
Thomas Woutersa9773292006-04-21 09:43:23 +0000942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000943 if (usable_arenas->nfreepools == 0) {
944 assert(usable_arenas->nextarena == NULL ||
945 usable_arenas->nextarena->prevarena ==
946 usable_arenas);
947 /* Unlink the arena: it is completely allocated. */
948 usable_arenas = usable_arenas->nextarena;
949 if (usable_arenas != NULL) {
950 usable_arenas->prevarena = NULL;
951 assert(usable_arenas->address != 0);
952 }
953 }
Thomas Woutersa9773292006-04-21 09:43:23 +0000954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 goto init_pool;
956 }
Neil Schemenauera35c6882001-02-27 04:45:05 +0000957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000958 /* The small block allocator ends here. */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000959
Tim Petersd97a1c02002-03-30 06:09:22 +0000960redirect:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000961 /* Redirect the original request to the underlying (libc) allocator.
962 * We jump here on bigger requests, on error in the code above (as a
963 * last chance to serve the request) or when the max memory limit
964 * has been reached.
965 */
966 if (nbytes == 0)
967 nbytes = 1;
968 return (void *)malloc(nbytes);
Neil Schemenauera35c6882001-02-27 04:45:05 +0000969}
970
971/* free */
972
Neil Schemenauerd2560cd2002-04-12 03:10:20 +0000973#undef PyObject_Free
Neil Schemenauera35c6882001-02-27 04:45:05 +0000974void
Neil Schemenauerd2560cd2002-04-12 03:10:20 +0000975PyObject_Free(void *p)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000976{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000977 poolp pool;
978 block *lastfree;
979 poolp next, prev;
980 uint size;
Antoine Pitroub7fb2e22011-01-07 21:43:59 +0000981#ifndef Py_USING_MEMORY_DEBUGGER
982 uint arenaindex_temp;
983#endif
Neil Schemenauera35c6882001-02-27 04:45:05 +0000984
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000985 if (p == NULL) /* free(NULL) has no effect */
986 return;
Neil Schemenauera35c6882001-02-27 04:45:05 +0000987
Benjamin Peterson05159c42009-12-03 03:01:27 +0000988#ifdef WITH_VALGRIND
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000989 if (UNLIKELY(running_on_valgrind > 0))
990 goto redirect;
Benjamin Peterson05159c42009-12-03 03:01:27 +0000991#endif
992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 pool = POOL_ADDR(p);
994 if (Py_ADDRESS_IN_RANGE(p, pool)) {
995 /* We allocated this address. */
996 LOCK();
997 /* Link p to the start of the pool's freeblock list. Since
998 * the pool had at least the p block outstanding, the pool
999 * wasn't empty (so it's already in a usedpools[] list, or
1000 * was full and is in no list -- it's not in the freeblocks
1001 * list in any case).
1002 */
1003 assert(pool->ref.count > 0); /* else it was empty */
1004 *(block **)p = lastfree = pool->freeblock;
1005 pool->freeblock = (block *)p;
1006 if (lastfree) {
1007 struct arena_object* ao;
1008 uint nf; /* ao->nfreepools */
Thomas Woutersa9773292006-04-21 09:43:23 +00001009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001010 /* freeblock wasn't NULL, so the pool wasn't full,
1011 * and the pool is in a usedpools[] list.
1012 */
1013 if (--pool->ref.count != 0) {
1014 /* pool isn't empty: leave it in usedpools */
1015 UNLOCK();
1016 return;
1017 }
1018 /* Pool is now empty: unlink from usedpools, and
1019 * link to the front of freepools. This ensures that
1020 * previously freed pools will be allocated later
1021 * (being not referenced, they are perhaps paged out).
1022 */
1023 next = pool->nextpool;
1024 prev = pool->prevpool;
1025 next->prevpool = prev;
1026 prev->nextpool = next;
Thomas Woutersa9773292006-04-21 09:43:23 +00001027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 /* Link the pool to freepools. This is a singly-linked
1029 * list, and pool->prevpool isn't used there.
1030 */
1031 ao = &arenas[pool->arenaindex];
1032 pool->nextpool = ao->freepools;
1033 ao->freepools = pool;
1034 nf = ++ao->nfreepools;
Thomas Woutersa9773292006-04-21 09:43:23 +00001035
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001036 /* All the rest is arena management. We just freed
1037 * a pool, and there are 4 cases for arena mgmt:
1038 * 1. If all the pools are free, return the arena to
1039 * the system free().
1040 * 2. If this is the only free pool in the arena,
1041 * add the arena back to the `usable_arenas` list.
1042 * 3. If the "next" arena has a smaller count of free
1043 * pools, we have to "slide this arena right" to
1044 * restore that usable_arenas is sorted in order of
1045 * nfreepools.
1046 * 4. Else there's nothing more to do.
1047 */
1048 if (nf == ao->ntotalpools) {
1049 /* Case 1. First unlink ao from usable_arenas.
1050 */
1051 assert(ao->prevarena == NULL ||
1052 ao->prevarena->address != 0);
1053 assert(ao ->nextarena == NULL ||
1054 ao->nextarena->address != 0);
Thomas Woutersa9773292006-04-21 09:43:23 +00001055
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001056 /* Fix the pointer in the prevarena, or the
1057 * usable_arenas pointer.
1058 */
1059 if (ao->prevarena == NULL) {
1060 usable_arenas = ao->nextarena;
1061 assert(usable_arenas == NULL ||
1062 usable_arenas->address != 0);
1063 }
1064 else {
1065 assert(ao->prevarena->nextarena == ao);
1066 ao->prevarena->nextarena =
1067 ao->nextarena;
1068 }
1069 /* Fix the pointer in the nextarena. */
1070 if (ao->nextarena != NULL) {
1071 assert(ao->nextarena->prevarena == ao);
1072 ao->nextarena->prevarena =
1073 ao->prevarena;
1074 }
1075 /* Record that this arena_object slot is
1076 * available to be reused.
1077 */
1078 ao->nextarena = unused_arena_objects;
1079 unused_arena_objects = ao;
Thomas Woutersa9773292006-04-21 09:43:23 +00001080
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001081 /* Free the entire arena. */
Antoine Pitrouf0effe62011-11-26 01:11:02 +01001082#ifdef ARENAS_USE_MMAP
1083 munmap((void *)ao->address, ARENA_SIZE);
1084#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001085 free((void *)ao->address);
Antoine Pitrouf0effe62011-11-26 01:11:02 +01001086#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001087 ao->address = 0; /* mark unassociated */
1088 --narenas_currently_allocated;
Thomas Woutersa9773292006-04-21 09:43:23 +00001089
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001090 UNLOCK();
1091 return;
1092 }
1093 if (nf == 1) {
1094 /* Case 2. Put ao at the head of
1095 * usable_arenas. Note that because
1096 * ao->nfreepools was 0 before, ao isn't
1097 * currently on the usable_arenas list.
1098 */
1099 ao->nextarena = usable_arenas;
1100 ao->prevarena = NULL;
1101 if (usable_arenas)
1102 usable_arenas->prevarena = ao;
1103 usable_arenas = ao;
1104 assert(usable_arenas->address != 0);
Thomas Woutersa9773292006-04-21 09:43:23 +00001105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 UNLOCK();
1107 return;
1108 }
1109 /* If this arena is now out of order, we need to keep
1110 * the list sorted. The list is kept sorted so that
1111 * the "most full" arenas are used first, which allows
1112 * the nearly empty arenas to be completely freed. In
1113 * a few un-scientific tests, it seems like this
1114 * approach allowed a lot more memory to be freed.
1115 */
1116 if (ao->nextarena == NULL ||
1117 nf <= ao->nextarena->nfreepools) {
1118 /* Case 4. Nothing to do. */
1119 UNLOCK();
1120 return;
1121 }
1122 /* Case 3: We have to move the arena towards the end
1123 * of the list, because it has more free pools than
1124 * the arena to its right.
1125 * First unlink ao from usable_arenas.
1126 */
1127 if (ao->prevarena != NULL) {
1128 /* ao isn't at the head of the list */
1129 assert(ao->prevarena->nextarena == ao);
1130 ao->prevarena->nextarena = ao->nextarena;
1131 }
1132 else {
1133 /* ao is at the head of the list */
1134 assert(usable_arenas == ao);
1135 usable_arenas = ao->nextarena;
1136 }
1137 ao->nextarena->prevarena = ao->prevarena;
Thomas Woutersa9773292006-04-21 09:43:23 +00001138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001139 /* Locate the new insertion point by iterating over
1140 * the list, using our nextarena pointer.
1141 */
1142 while (ao->nextarena != NULL &&
1143 nf > ao->nextarena->nfreepools) {
1144 ao->prevarena = ao->nextarena;
1145 ao->nextarena = ao->nextarena->nextarena;
1146 }
Thomas Woutersa9773292006-04-21 09:43:23 +00001147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001148 /* Insert ao at this point. */
1149 assert(ao->nextarena == NULL ||
1150 ao->prevarena == ao->nextarena->prevarena);
1151 assert(ao->prevarena->nextarena == ao->nextarena);
Thomas Woutersa9773292006-04-21 09:43:23 +00001152
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001153 ao->prevarena->nextarena = ao;
1154 if (ao->nextarena != NULL)
1155 ao->nextarena->prevarena = ao;
Thomas Woutersa9773292006-04-21 09:43:23 +00001156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001157 /* Verify that the swaps worked. */
1158 assert(ao->nextarena == NULL ||
1159 nf <= ao->nextarena->nfreepools);
1160 assert(ao->prevarena == NULL ||
1161 nf > ao->prevarena->nfreepools);
1162 assert(ao->nextarena == NULL ||
1163 ao->nextarena->prevarena == ao);
1164 assert((usable_arenas == ao &&
1165 ao->prevarena == NULL) ||
1166 ao->prevarena->nextarena == ao);
Thomas Woutersa9773292006-04-21 09:43:23 +00001167
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001168 UNLOCK();
1169 return;
1170 }
1171 /* Pool was full, so doesn't currently live in any list:
1172 * link it to the front of the appropriate usedpools[] list.
1173 * This mimics LRU pool usage for new allocations and
1174 * targets optimal filling when several pools contain
1175 * blocks of the same size class.
1176 */
1177 --pool->ref.count;
1178 assert(pool->ref.count > 0); /* else the pool is empty */
1179 size = pool->szidx;
1180 next = usedpools[size + size];
1181 prev = next->prevpool;
1182 /* insert pool before next: prev <-> pool <-> next */
1183 pool->nextpool = next;
1184 pool->prevpool = prev;
1185 next->prevpool = pool;
1186 prev->nextpool = pool;
1187 UNLOCK();
1188 return;
1189 }
Neil Schemenauera35c6882001-02-27 04:45:05 +00001190
Benjamin Peterson05159c42009-12-03 03:01:27 +00001191#ifdef WITH_VALGRIND
1192redirect:
1193#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 /* We didn't allocate this address. */
1195 free(p);
Neil Schemenauera35c6882001-02-27 04:45:05 +00001196}
1197
Tim Peters84c1b972002-04-04 04:44:32 +00001198/* realloc. If p is NULL, this acts like malloc(nbytes). Else if nbytes==0,
1199 * then as the Python docs promise, we do not treat this like free(p), and
1200 * return a non-NULL result.
1201 */
Neil Schemenauera35c6882001-02-27 04:45:05 +00001202
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00001203#undef PyObject_Realloc
Neil Schemenauera35c6882001-02-27 04:45:05 +00001204void *
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00001205PyObject_Realloc(void *p, size_t nbytes)
Neil Schemenauera35c6882001-02-27 04:45:05 +00001206{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001207 void *bp;
1208 poolp pool;
1209 size_t size;
Antoine Pitroub7fb2e22011-01-07 21:43:59 +00001210#ifndef Py_USING_MEMORY_DEBUGGER
1211 uint arenaindex_temp;
1212#endif
Neil Schemenauera35c6882001-02-27 04:45:05 +00001213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001214 if (p == NULL)
1215 return PyObject_Malloc(nbytes);
Neil Schemenauera35c6882001-02-27 04:45:05 +00001216
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001217 /*
1218 * Limit ourselves to PY_SSIZE_T_MAX bytes to prevent security holes.
1219 * Most python internals blindly use a signed Py_ssize_t to track
1220 * things without checking for overflows or negatives.
1221 * As size_t is unsigned, checking for nbytes < 0 is not required.
1222 */
1223 if (nbytes > PY_SSIZE_T_MAX)
1224 return NULL;
Georg Brandld492ad82008-07-23 16:13:07 +00001225
Benjamin Peterson05159c42009-12-03 03:01:27 +00001226#ifdef WITH_VALGRIND
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001227 /* Treat running_on_valgrind == -1 the same as 0 */
1228 if (UNLIKELY(running_on_valgrind > 0))
1229 goto redirect;
Benjamin Peterson05159c42009-12-03 03:01:27 +00001230#endif
1231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001232 pool = POOL_ADDR(p);
1233 if (Py_ADDRESS_IN_RANGE(p, pool)) {
1234 /* We're in charge of this block */
1235 size = INDEX2SIZE(pool->szidx);
1236 if (nbytes <= size) {
1237 /* The block is staying the same or shrinking. If
1238 * it's shrinking, there's a tradeoff: it costs
1239 * cycles to copy the block to a smaller size class,
1240 * but it wastes memory not to copy it. The
1241 * compromise here is to copy on shrink only if at
1242 * least 25% of size can be shaved off.
1243 */
1244 if (4 * nbytes > 3 * size) {
1245 /* It's the same,
1246 * or shrinking and new/old > 3/4.
1247 */
1248 return p;
1249 }
1250 size = nbytes;
1251 }
1252 bp = PyObject_Malloc(nbytes);
1253 if (bp != NULL) {
1254 memcpy(bp, p, size);
1255 PyObject_Free(p);
1256 }
1257 return bp;
1258 }
Benjamin Peterson05159c42009-12-03 03:01:27 +00001259#ifdef WITH_VALGRIND
1260 redirect:
1261#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001262 /* We're not managing this block. If nbytes <=
1263 * SMALL_REQUEST_THRESHOLD, it's tempting to try to take over this
1264 * block. However, if we do, we need to copy the valid data from
1265 * the C-managed block to one of our blocks, and there's no portable
1266 * way to know how much of the memory space starting at p is valid.
1267 * As bug 1185883 pointed out the hard way, it's possible that the
1268 * C-managed block is "at the end" of allocated VM space, so that
1269 * a memory fault can occur if we try to copy nbytes bytes starting
1270 * at p. Instead we punt: let C continue to manage this block.
1271 */
1272 if (nbytes)
1273 return realloc(p, nbytes);
1274 /* C doesn't define the result of realloc(p, 0) (it may or may not
1275 * return NULL then), but Python's docs promise that nbytes==0 never
1276 * returns NULL. We don't pass 0 to realloc(), to avoid that endcase
1277 * to begin with. Even then, we can't be sure that realloc() won't
1278 * return NULL.
1279 */
1280 bp = realloc(p, 1);
1281 return bp ? bp : p;
Neil Schemenauera35c6882001-02-27 04:45:05 +00001282}
1283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001284#else /* ! WITH_PYMALLOC */
Tim Petersddea2082002-03-23 10:03:50 +00001285
1286/*==========================================================================*/
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00001287/* pymalloc not enabled: Redirect the entry points to malloc. These will
1288 * only be used by extensions that are compiled with pymalloc enabled. */
Tim Peters62c06ba2002-03-23 22:28:18 +00001289
Tim Petersce7fb9b2002-03-23 00:28:57 +00001290void *
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00001291PyObject_Malloc(size_t n)
Tim Peters1221c0a2002-03-23 00:20:15 +00001292{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001293 return PyMem_MALLOC(n);
Tim Peters1221c0a2002-03-23 00:20:15 +00001294}
1295
Tim Petersce7fb9b2002-03-23 00:28:57 +00001296void *
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00001297PyObject_Realloc(void *p, size_t n)
Tim Peters1221c0a2002-03-23 00:20:15 +00001298{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001299 return PyMem_REALLOC(p, n);
Tim Peters1221c0a2002-03-23 00:20:15 +00001300}
1301
1302void
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00001303PyObject_Free(void *p)
Tim Peters1221c0a2002-03-23 00:20:15 +00001304{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001305 PyMem_FREE(p);
Tim Peters1221c0a2002-03-23 00:20:15 +00001306}
1307#endif /* WITH_PYMALLOC */
1308
Tim Petersddea2082002-03-23 10:03:50 +00001309#ifdef PYMALLOC_DEBUG
1310/*==========================================================================*/
Tim Peters62c06ba2002-03-23 22:28:18 +00001311/* A x-platform debugging allocator. This doesn't manage memory directly,
1312 * it wraps a real allocator, adding extra debugging info to the memory blocks.
1313 */
Tim Petersddea2082002-03-23 10:03:50 +00001314
Tim Petersf6fb5012002-04-12 07:38:53 +00001315/* Special bytes broadcast into debug memory blocks at appropriate times.
1316 * Strings of these are unlikely to be valid addresses, floats, ints or
1317 * 7-bit ASCII.
1318 */
1319#undef CLEANBYTE
1320#undef DEADBYTE
1321#undef FORBIDDENBYTE
1322#define CLEANBYTE 0xCB /* clean (newly allocated) memory */
Tim Peters889f61d2002-07-10 19:29:49 +00001323#define DEADBYTE 0xDB /* dead (newly freed) memory */
Tim Petersf6fb5012002-04-12 07:38:53 +00001324#define FORBIDDENBYTE 0xFB /* untouchable bytes at each end of a block */
Tim Petersddea2082002-03-23 10:03:50 +00001325
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00001326/* We tag each block with an API ID in order to tag API violations */
1327#define _PYMALLOC_MEM_ID 'm' /* the PyMem_Malloc() API */
1328#define _PYMALLOC_OBJ_ID 'o' /* The PyObject_Malloc() API */
1329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001330static size_t serialno = 0; /* incremented on each debug {m,re}alloc */
Tim Petersddea2082002-03-23 10:03:50 +00001331
Tim Peterse0850172002-03-24 00:34:21 +00001332/* serialno is always incremented via calling this routine. The point is
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001333 * to supply a single place to set a breakpoint.
1334 */
Tim Peterse0850172002-03-24 00:34:21 +00001335static void
Neil Schemenauerbd02b142002-03-28 21:05:38 +00001336bumpserialno(void)
Tim Peterse0850172002-03-24 00:34:21 +00001337{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001338 ++serialno;
Tim Peterse0850172002-03-24 00:34:21 +00001339}
1340
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001341#define SST SIZEOF_SIZE_T
Tim Peterse0850172002-03-24 00:34:21 +00001342
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001343/* Read sizeof(size_t) bytes at p as a big-endian size_t. */
1344static size_t
1345read_size_t(const void *p)
Tim Petersddea2082002-03-23 10:03:50 +00001346{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001347 const uchar *q = (const uchar *)p;
1348 size_t result = *q++;
1349 int i;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001351 for (i = SST; --i > 0; ++q)
1352 result = (result << 8) | *q;
1353 return result;
Tim Petersddea2082002-03-23 10:03:50 +00001354}
1355
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001356/* Write n as a big-endian size_t, MSB at address p, LSB at
1357 * p + sizeof(size_t) - 1.
1358 */
Tim Petersddea2082002-03-23 10:03:50 +00001359static void
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001360write_size_t(void *p, size_t n)
Tim Petersddea2082002-03-23 10:03:50 +00001361{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001362 uchar *q = (uchar *)p + SST - 1;
1363 int i;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001365 for (i = SST; --i >= 0; --q) {
1366 *q = (uchar)(n & 0xff);
1367 n >>= 8;
1368 }
Tim Petersddea2082002-03-23 10:03:50 +00001369}
1370
Tim Peters08d82152002-04-18 22:25:03 +00001371#ifdef Py_DEBUG
1372/* Is target in the list? The list is traversed via the nextpool pointers.
1373 * The list may be NULL-terminated, or circular. Return 1 if target is in
1374 * list, else 0.
1375 */
1376static int
1377pool_is_in_list(const poolp target, poolp list)
1378{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001379 poolp origlist = list;
1380 assert(target != NULL);
1381 if (list == NULL)
1382 return 0;
1383 do {
1384 if (target == list)
1385 return 1;
1386 list = list->nextpool;
1387 } while (list != NULL && list != origlist);
1388 return 0;
Tim Peters08d82152002-04-18 22:25:03 +00001389}
1390
1391#else
1392#define pool_is_in_list(X, Y) 1
1393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001394#endif /* Py_DEBUG */
Tim Peters08d82152002-04-18 22:25:03 +00001395
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001396/* Let S = sizeof(size_t). The debug malloc asks for 4*S extra bytes and
1397 fills them with useful stuff, here calling the underlying malloc's result p:
Tim Petersddea2082002-03-23 10:03:50 +00001398
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001399p[0: S]
1400 Number of bytes originally asked for. This is a size_t, big-endian (easier
1401 to read in a memory dump).
1402p[S: 2*S]
Tim Petersf6fb5012002-04-12 07:38:53 +00001403 Copies of FORBIDDENBYTE. Used to catch under- writes and reads.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001404p[2*S: 2*S+n]
Tim Petersf6fb5012002-04-12 07:38:53 +00001405 The requested memory, filled with copies of CLEANBYTE.
Tim Petersddea2082002-03-23 10:03:50 +00001406 Used to catch reference to uninitialized memory.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001407 &p[2*S] is returned. Note that this is 8-byte aligned if pymalloc
Tim Petersddea2082002-03-23 10:03:50 +00001408 handled the request itself.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001409p[2*S+n: 2*S+n+S]
Tim Petersf6fb5012002-04-12 07:38:53 +00001410 Copies of FORBIDDENBYTE. Used to catch over- writes and reads.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001411p[2*S+n+S: 2*S+n+2*S]
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00001412 A serial number, incremented by 1 on each call to _PyObject_DebugMalloc
1413 and _PyObject_DebugRealloc.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001414 This is a big-endian size_t.
Tim Petersddea2082002-03-23 10:03:50 +00001415 If "bad memory" is detected later, the serial number gives an
1416 excellent way to set a breakpoint on the next run, to capture the
1417 instant at which this block was passed out.
1418*/
1419
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00001420/* debug replacements for the PyMem_* memory API */
1421void *
1422_PyMem_DebugMalloc(size_t nbytes)
1423{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001424 return _PyObject_DebugMallocApi(_PYMALLOC_MEM_ID, nbytes);
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00001425}
1426void *
1427_PyMem_DebugRealloc(void *p, size_t nbytes)
1428{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001429 return _PyObject_DebugReallocApi(_PYMALLOC_MEM_ID, p, nbytes);
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00001430}
1431void
1432_PyMem_DebugFree(void *p)
1433{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001434 _PyObject_DebugFreeApi(_PYMALLOC_MEM_ID, p);
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00001435}
1436
1437/* debug replacements for the PyObject_* memory API */
Tim Petersddea2082002-03-23 10:03:50 +00001438void *
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00001439_PyObject_DebugMalloc(size_t nbytes)
Tim Petersddea2082002-03-23 10:03:50 +00001440{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001441 return _PyObject_DebugMallocApi(_PYMALLOC_OBJ_ID, nbytes);
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00001442}
1443void *
1444_PyObject_DebugRealloc(void *p, size_t nbytes)
1445{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001446 return _PyObject_DebugReallocApi(_PYMALLOC_OBJ_ID, p, nbytes);
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00001447}
1448void
1449_PyObject_DebugFree(void *p)
1450{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001451 _PyObject_DebugFreeApi(_PYMALLOC_OBJ_ID, p);
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00001452}
1453void
Kristján Valur Jónsson34369002009-09-28 15:57:53 +00001454_PyObject_DebugCheckAddress(const void *p)
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00001455{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001456 _PyObject_DebugCheckAddressApi(_PYMALLOC_OBJ_ID, p);
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00001457}
1458
1459
1460/* generic debug memory api, with an "id" to identify the API in use */
1461void *
1462_PyObject_DebugMallocApi(char id, size_t nbytes)
1463{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001464 uchar *p; /* base address of malloc'ed block */
1465 uchar *tail; /* p + 2*SST + nbytes == pointer to tail pad bytes */
1466 size_t total; /* nbytes + 4*SST */
Tim Petersddea2082002-03-23 10:03:50 +00001467
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001468 bumpserialno();
1469 total = nbytes + 4*SST;
1470 if (total < nbytes)
1471 /* overflow: can't represent total as a size_t */
1472 return NULL;
Tim Petersddea2082002-03-23 10:03:50 +00001473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001474 p = (uchar *)PyObject_Malloc(total);
1475 if (p == NULL)
1476 return NULL;
Tim Petersddea2082002-03-23 10:03:50 +00001477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001478 /* at p, write size (SST bytes), id (1 byte), pad (SST-1 bytes) */
1479 write_size_t(p, nbytes);
1480 p[SST] = (uchar)id;
1481 memset(p + SST + 1 , FORBIDDENBYTE, SST-1);
Tim Petersddea2082002-03-23 10:03:50 +00001482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001483 if (nbytes > 0)
1484 memset(p + 2*SST, CLEANBYTE, nbytes);
Tim Petersddea2082002-03-23 10:03:50 +00001485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001486 /* at tail, write pad (SST bytes) and serialno (SST bytes) */
1487 tail = p + 2*SST + nbytes;
1488 memset(tail, FORBIDDENBYTE, SST);
1489 write_size_t(tail + SST, serialno);
Tim Petersddea2082002-03-23 10:03:50 +00001490
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001491 return p + 2*SST;
Tim Petersddea2082002-03-23 10:03:50 +00001492}
1493
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001494/* The debug free first checks the 2*SST bytes on each end for sanity (in
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00001495 particular, that the FORBIDDENBYTEs with the api ID are still intact).
Tim Petersf6fb5012002-04-12 07:38:53 +00001496 Then fills the original bytes with DEADBYTE.
Tim Petersddea2082002-03-23 10:03:50 +00001497 Then calls the underlying free.
1498*/
1499void
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00001500_PyObject_DebugFreeApi(char api, void *p)
Tim Petersddea2082002-03-23 10:03:50 +00001501{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001502 uchar *q = (uchar *)p - 2*SST; /* address returned from malloc */
1503 size_t nbytes;
Tim Petersddea2082002-03-23 10:03:50 +00001504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001505 if (p == NULL)
1506 return;
1507 _PyObject_DebugCheckAddressApi(api, p);
1508 nbytes = read_size_t(q);
1509 nbytes += 4*SST;
1510 if (nbytes > 0)
1511 memset(q, DEADBYTE, nbytes);
1512 PyObject_Free(q);
Tim Petersddea2082002-03-23 10:03:50 +00001513}
1514
1515void *
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00001516_PyObject_DebugReallocApi(char api, void *p, size_t nbytes)
Tim Petersddea2082002-03-23 10:03:50 +00001517{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001518 uchar *q = (uchar *)p;
1519 uchar *tail;
1520 size_t total; /* nbytes + 4*SST */
1521 size_t original_nbytes;
1522 int i;
Tim Petersddea2082002-03-23 10:03:50 +00001523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001524 if (p == NULL)
1525 return _PyObject_DebugMallocApi(api, nbytes);
Tim Petersddea2082002-03-23 10:03:50 +00001526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001527 _PyObject_DebugCheckAddressApi(api, p);
1528 bumpserialno();
1529 original_nbytes = read_size_t(q - 2*SST);
1530 total = nbytes + 4*SST;
1531 if (total < nbytes)
1532 /* overflow: can't represent total as a size_t */
1533 return NULL;
Tim Petersddea2082002-03-23 10:03:50 +00001534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001535 if (nbytes < original_nbytes) {
1536 /* shrinking: mark old extra memory dead */
1537 memset(q + nbytes, DEADBYTE, original_nbytes - nbytes + 2*SST);
1538 }
Tim Petersddea2082002-03-23 10:03:50 +00001539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001540 /* Resize and add decorations. We may get a new pointer here, in which
1541 * case we didn't get the chance to mark the old memory with DEADBYTE,
1542 * but we live with that.
1543 */
1544 q = (uchar *)PyObject_Realloc(q - 2*SST, total);
1545 if (q == NULL)
1546 return NULL;
Tim Peters85cc1c42002-04-12 08:52:50 +00001547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001548 write_size_t(q, nbytes);
1549 assert(q[SST] == (uchar)api);
1550 for (i = 1; i < SST; ++i)
1551 assert(q[SST + i] == FORBIDDENBYTE);
1552 q += 2*SST;
1553 tail = q + nbytes;
1554 memset(tail, FORBIDDENBYTE, SST);
1555 write_size_t(tail + SST, serialno);
Tim Peters85cc1c42002-04-12 08:52:50 +00001556
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001557 if (nbytes > original_nbytes) {
1558 /* growing: mark new extra memory clean */
1559 memset(q + original_nbytes, CLEANBYTE,
Stefan Krah735bb122010-11-26 10:54:09 +00001560 nbytes - original_nbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001561 }
Tim Peters85cc1c42002-04-12 08:52:50 +00001562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001563 return q;
Tim Petersddea2082002-03-23 10:03:50 +00001564}
1565
Tim Peters7ccfadf2002-04-01 06:04:21 +00001566/* Check the forbidden bytes on both ends of the memory allocated for p.
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00001567 * If anything is wrong, print info to stderr via _PyObject_DebugDumpAddress,
Tim Peters7ccfadf2002-04-01 06:04:21 +00001568 * and call Py_FatalError to kill the program.
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00001569 * The API id, is also checked.
Tim Peters7ccfadf2002-04-01 06:04:21 +00001570 */
1571 void
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00001572_PyObject_DebugCheckAddressApi(char api, const void *p)
Tim Petersddea2082002-03-23 10:03:50 +00001573{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001574 const uchar *q = (const uchar *)p;
1575 char msgbuf[64];
1576 char *msg;
1577 size_t nbytes;
1578 const uchar *tail;
1579 int i;
1580 char id;
Tim Petersddea2082002-03-23 10:03:50 +00001581
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001582 if (p == NULL) {
1583 msg = "didn't expect a NULL pointer";
1584 goto error;
1585 }
Tim Petersddea2082002-03-23 10:03:50 +00001586
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001587 /* Check the API id */
1588 id = (char)q[-SST];
1589 if (id != api) {
1590 msg = msgbuf;
1591 snprintf(msg, sizeof(msgbuf), "bad ID: Allocated using API '%c', verified using API '%c'", id, api);
1592 msgbuf[sizeof(msgbuf)-1] = 0;
1593 goto error;
1594 }
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00001595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001596 /* Check the stuff at the start of p first: if there's underwrite
1597 * corruption, the number-of-bytes field may be nuts, and checking
1598 * the tail could lead to a segfault then.
1599 */
1600 for (i = SST-1; i >= 1; --i) {
1601 if (*(q-i) != FORBIDDENBYTE) {
1602 msg = "bad leading pad byte";
1603 goto error;
1604 }
1605 }
Tim Petersddea2082002-03-23 10:03:50 +00001606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001607 nbytes = read_size_t(q - 2*SST);
1608 tail = q + nbytes;
1609 for (i = 0; i < SST; ++i) {
1610 if (tail[i] != FORBIDDENBYTE) {
1611 msg = "bad trailing pad byte";
1612 goto error;
1613 }
1614 }
Tim Petersddea2082002-03-23 10:03:50 +00001615
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001616 return;
Tim Petersd1139e02002-03-28 07:32:11 +00001617
1618error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001619 _PyObject_DebugDumpAddress(p);
1620 Py_FatalError(msg);
Tim Petersddea2082002-03-23 10:03:50 +00001621}
1622
Tim Peters7ccfadf2002-04-01 06:04:21 +00001623/* Display info to stderr about the memory block at p. */
Tim Petersddea2082002-03-23 10:03:50 +00001624void
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00001625_PyObject_DebugDumpAddress(const void *p)
Tim Petersddea2082002-03-23 10:03:50 +00001626{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001627 const uchar *q = (const uchar *)p;
1628 const uchar *tail;
1629 size_t nbytes, serial;
1630 int i;
1631 int ok;
1632 char id;
Tim Petersddea2082002-03-23 10:03:50 +00001633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001634 fprintf(stderr, "Debug memory block at address p=%p:", p);
1635 if (p == NULL) {
1636 fprintf(stderr, "\n");
1637 return;
1638 }
1639 id = (char)q[-SST];
1640 fprintf(stderr, " API '%c'\n", id);
Tim Petersddea2082002-03-23 10:03:50 +00001641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001642 nbytes = read_size_t(q - 2*SST);
1643 fprintf(stderr, " %" PY_FORMAT_SIZE_T "u bytes originally "
1644 "requested\n", nbytes);
Tim Petersddea2082002-03-23 10:03:50 +00001645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001646 /* In case this is nuts, check the leading pad bytes first. */
1647 fprintf(stderr, " The %d pad bytes at p-%d are ", SST-1, SST-1);
1648 ok = 1;
1649 for (i = 1; i <= SST-1; ++i) {
1650 if (*(q-i) != FORBIDDENBYTE) {
1651 ok = 0;
1652 break;
1653 }
1654 }
1655 if (ok)
1656 fputs("FORBIDDENBYTE, as expected.\n", stderr);
1657 else {
1658 fprintf(stderr, "not all FORBIDDENBYTE (0x%02x):\n",
1659 FORBIDDENBYTE);
1660 for (i = SST-1; i >= 1; --i) {
1661 const uchar byte = *(q-i);
1662 fprintf(stderr, " at p-%d: 0x%02x", i, byte);
1663 if (byte != FORBIDDENBYTE)
1664 fputs(" *** OUCH", stderr);
1665 fputc('\n', stderr);
1666 }
Tim Peters449b5a82002-04-28 06:14:45 +00001667
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001668 fputs(" Because memory is corrupted at the start, the "
1669 "count of bytes requested\n"
1670 " may be bogus, and checking the trailing pad "
1671 "bytes may segfault.\n", stderr);
1672 }
Tim Petersddea2082002-03-23 10:03:50 +00001673
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001674 tail = q + nbytes;
1675 fprintf(stderr, " The %d pad bytes at tail=%p are ", SST, tail);
1676 ok = 1;
1677 for (i = 0; i < SST; ++i) {
1678 if (tail[i] != FORBIDDENBYTE) {
1679 ok = 0;
1680 break;
1681 }
1682 }
1683 if (ok)
1684 fputs("FORBIDDENBYTE, as expected.\n", stderr);
1685 else {
1686 fprintf(stderr, "not all FORBIDDENBYTE (0x%02x):\n",
Stefan Krah735bb122010-11-26 10:54:09 +00001687 FORBIDDENBYTE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001688 for (i = 0; i < SST; ++i) {
1689 const uchar byte = tail[i];
1690 fprintf(stderr, " at tail+%d: 0x%02x",
Stefan Krah735bb122010-11-26 10:54:09 +00001691 i, byte);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001692 if (byte != FORBIDDENBYTE)
1693 fputs(" *** OUCH", stderr);
1694 fputc('\n', stderr);
1695 }
1696 }
Tim Petersddea2082002-03-23 10:03:50 +00001697
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001698 serial = read_size_t(tail + SST);
1699 fprintf(stderr, " The block was made by call #%" PY_FORMAT_SIZE_T
1700 "u to debug malloc/realloc.\n", serial);
Tim Petersddea2082002-03-23 10:03:50 +00001701
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001702 if (nbytes > 0) {
1703 i = 0;
1704 fputs(" Data at p:", stderr);
1705 /* print up to 8 bytes at the start */
1706 while (q < tail && i < 8) {
1707 fprintf(stderr, " %02x", *q);
1708 ++i;
1709 ++q;
1710 }
1711 /* and up to 8 at the end */
1712 if (q < tail) {
1713 if (tail - q > 8) {
1714 fputs(" ...", stderr);
1715 q = tail - 8;
1716 }
1717 while (q < tail) {
1718 fprintf(stderr, " %02x", *q);
1719 ++q;
1720 }
1721 }
1722 fputc('\n', stderr);
1723 }
Tim Petersddea2082002-03-23 10:03:50 +00001724}
1725
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001726static size_t
1727printone(const char* msg, size_t value)
Tim Peters16bcb6b2002-04-05 05:45:31 +00001728{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001729 int i, k;
1730 char buf[100];
1731 size_t origvalue = value;
Tim Peters16bcb6b2002-04-05 05:45:31 +00001732
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001733 fputs(msg, stderr);
1734 for (i = (int)strlen(msg); i < 35; ++i)
1735 fputc(' ', stderr);
1736 fputc('=', stderr);
Tim Peters49f26812002-04-06 01:45:35 +00001737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001738 /* Write the value with commas. */
1739 i = 22;
1740 buf[i--] = '\0';
1741 buf[i--] = '\n';
1742 k = 3;
1743 do {
1744 size_t nextvalue = value / 10;
1745 uint digit = (uint)(value - nextvalue * 10);
1746 value = nextvalue;
1747 buf[i--] = (char)(digit + '0');
1748 --k;
1749 if (k == 0 && value && i >= 0) {
1750 k = 3;
1751 buf[i--] = ',';
1752 }
1753 } while (value && i >= 0);
Tim Peters49f26812002-04-06 01:45:35 +00001754
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001755 while (i >= 0)
1756 buf[i--] = ' ';
1757 fputs(buf, stderr);
Tim Peters49f26812002-04-06 01:45:35 +00001758
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001759 return origvalue;
Tim Peters16bcb6b2002-04-05 05:45:31 +00001760}
1761
Tim Peters08d82152002-04-18 22:25:03 +00001762/* Print summary info to stderr about the state of pymalloc's structures.
1763 * In Py_DEBUG mode, also perform some expensive internal consistency
1764 * checks.
1765 */
Tim Peters7ccfadf2002-04-01 06:04:21 +00001766void
Tim Peters0e871182002-04-13 08:29:14 +00001767_PyObject_DebugMallocStats(void)
Tim Peters7ccfadf2002-04-01 06:04:21 +00001768{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001769 uint i;
1770 const uint numclasses = SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT;
1771 /* # of pools, allocated blocks, and free blocks per class index */
1772 size_t numpools[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT];
1773 size_t numblocks[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT];
1774 size_t numfreeblocks[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT];
1775 /* total # of allocated bytes in used and full pools */
1776 size_t allocated_bytes = 0;
1777 /* total # of available bytes in used pools */
1778 size_t available_bytes = 0;
1779 /* # of free pools + pools not yet carved out of current arena */
1780 uint numfreepools = 0;
1781 /* # of bytes for arena alignment padding */
1782 size_t arena_alignment = 0;
1783 /* # of bytes in used and full pools used for pool_headers */
1784 size_t pool_header_bytes = 0;
1785 /* # of bytes in used and full pools wasted due to quantization,
1786 * i.e. the necessarily leftover space at the ends of used and
1787 * full pools.
1788 */
1789 size_t quantization = 0;
1790 /* # of arenas actually allocated. */
1791 size_t narenas = 0;
1792 /* running total -- should equal narenas * ARENA_SIZE */
1793 size_t total;
1794 char buf[128];
Tim Peters7ccfadf2002-04-01 06:04:21 +00001795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001796 fprintf(stderr, "Small block threshold = %d, in %u size classes.\n",
Stefan Krah735bb122010-11-26 10:54:09 +00001797 SMALL_REQUEST_THRESHOLD, numclasses);
Tim Peters7ccfadf2002-04-01 06:04:21 +00001798
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001799 for (i = 0; i < numclasses; ++i)
1800 numpools[i] = numblocks[i] = numfreeblocks[i] = 0;
Tim Peters7ccfadf2002-04-01 06:04:21 +00001801
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001802 /* Because full pools aren't linked to from anything, it's easiest
1803 * to march over all the arenas. If we're lucky, most of the memory
1804 * will be living in full pools -- would be a shame to miss them.
1805 */
1806 for (i = 0; i < maxarenas; ++i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001807 uint j;
1808 uptr base = arenas[i].address;
Thomas Woutersa9773292006-04-21 09:43:23 +00001809
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001810 /* Skip arenas which are not allocated. */
1811 if (arenas[i].address == (uptr)NULL)
1812 continue;
1813 narenas += 1;
Thomas Woutersa9773292006-04-21 09:43:23 +00001814
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001815 numfreepools += arenas[i].nfreepools;
Tim Peters7ccfadf2002-04-01 06:04:21 +00001816
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001817 /* round up to pool alignment */
1818 if (base & (uptr)POOL_SIZE_MASK) {
1819 arena_alignment += POOL_SIZE;
1820 base &= ~(uptr)POOL_SIZE_MASK;
1821 base += POOL_SIZE;
1822 }
Tim Peters7ccfadf2002-04-01 06:04:21 +00001823
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001824 /* visit every pool in the arena */
1825 assert(base <= (uptr) arenas[i].pool_address);
1826 for (j = 0;
1827 base < (uptr) arenas[i].pool_address;
1828 ++j, base += POOL_SIZE) {
1829 poolp p = (poolp)base;
1830 const uint sz = p->szidx;
1831 uint freeblocks;
Tim Peters08d82152002-04-18 22:25:03 +00001832
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001833 if (p->ref.count == 0) {
1834 /* currently unused */
1835 assert(pool_is_in_list(p, arenas[i].freepools));
1836 continue;
1837 }
1838 ++numpools[sz];
1839 numblocks[sz] += p->ref.count;
1840 freeblocks = NUMBLOCKS(sz) - p->ref.count;
1841 numfreeblocks[sz] += freeblocks;
Tim Peters08d82152002-04-18 22:25:03 +00001842#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001843 if (freeblocks > 0)
1844 assert(pool_is_in_list(p, usedpools[sz + sz]));
Tim Peters08d82152002-04-18 22:25:03 +00001845#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001846 }
1847 }
1848 assert(narenas == narenas_currently_allocated);
Tim Peters7ccfadf2002-04-01 06:04:21 +00001849
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001850 fputc('\n', stderr);
1851 fputs("class size num pools blocks in use avail blocks\n"
1852 "----- ---- --------- ------------- ------------\n",
Stefan Krah735bb122010-11-26 10:54:09 +00001853 stderr);
Tim Peters7ccfadf2002-04-01 06:04:21 +00001854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001855 for (i = 0; i < numclasses; ++i) {
1856 size_t p = numpools[i];
1857 size_t b = numblocks[i];
1858 size_t f = numfreeblocks[i];
1859 uint size = INDEX2SIZE(i);
1860 if (p == 0) {
1861 assert(b == 0 && f == 0);
1862 continue;
1863 }
1864 fprintf(stderr, "%5u %6u "
1865 "%11" PY_FORMAT_SIZE_T "u "
1866 "%15" PY_FORMAT_SIZE_T "u "
1867 "%13" PY_FORMAT_SIZE_T "u\n",
Stefan Krah735bb122010-11-26 10:54:09 +00001868 i, size, p, b, f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001869 allocated_bytes += b * size;
1870 available_bytes += f * size;
1871 pool_header_bytes += p * POOL_OVERHEAD;
1872 quantization += p * ((POOL_SIZE - POOL_OVERHEAD) % size);
1873 }
1874 fputc('\n', stderr);
1875 (void)printone("# times object malloc called", serialno);
Tim Peters16bcb6b2002-04-05 05:45:31 +00001876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001877 (void)printone("# arenas allocated total", ntimes_arena_allocated);
1878 (void)printone("# arenas reclaimed", ntimes_arena_allocated - narenas);
1879 (void)printone("# arenas highwater mark", narenas_highwater);
1880 (void)printone("# arenas allocated current", narenas);
Thomas Woutersa9773292006-04-21 09:43:23 +00001881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001882 PyOS_snprintf(buf, sizeof(buf),
1883 "%" PY_FORMAT_SIZE_T "u arenas * %d bytes/arena",
1884 narenas, ARENA_SIZE);
1885 (void)printone(buf, narenas * ARENA_SIZE);
Tim Peters16bcb6b2002-04-05 05:45:31 +00001886
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001887 fputc('\n', stderr);
Tim Peters16bcb6b2002-04-05 05:45:31 +00001888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001889 total = printone("# bytes in allocated blocks", allocated_bytes);
1890 total += printone("# bytes in available blocks", available_bytes);
Tim Peters49f26812002-04-06 01:45:35 +00001891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001892 PyOS_snprintf(buf, sizeof(buf),
1893 "%u unused pools * %d bytes", numfreepools, POOL_SIZE);
1894 total += printone(buf, (size_t)numfreepools * POOL_SIZE);
Tim Peters16bcb6b2002-04-05 05:45:31 +00001895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001896 total += printone("# bytes lost to pool headers", pool_header_bytes);
1897 total += printone("# bytes lost to quantization", quantization);
1898 total += printone("# bytes lost to arena alignment", arena_alignment);
1899 (void)printone("Total", total);
Tim Peters7ccfadf2002-04-01 06:04:21 +00001900}
1901
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001902#endif /* PYMALLOC_DEBUG */
Neal Norwitz7eb3c912004-06-06 19:20:22 +00001903
1904#ifdef Py_USING_MEMORY_DEBUGGER
Thomas Woutersa9773292006-04-21 09:43:23 +00001905/* Make this function last so gcc won't inline it since the definition is
1906 * after the reference.
1907 */
Neal Norwitz7eb3c912004-06-06 19:20:22 +00001908int
1909Py_ADDRESS_IN_RANGE(void *P, poolp pool)
1910{
Antoine Pitroub7fb2e22011-01-07 21:43:59 +00001911 uint arenaindex_temp = pool->arenaindex;
1912
1913 return arenaindex_temp < maxarenas &&
1914 (uptr)P - arenas[arenaindex_temp].address < (uptr)ARENA_SIZE &&
1915 arenas[arenaindex_temp].address != 0;
Neal Norwitz7eb3c912004-06-06 19:20:22 +00001916}
1917#endif