blob: 9a7c7e7ce610dc1a1b74e94390594d17dc9656d7 [file] [log] [blame]
Tim Peters1221c0a2002-03-23 00:20:15 +00001#include "Python.h"
2
3#ifdef WITH_PYMALLOC
4
Antoine Pitrou6f26be02011-05-03 18:18:59 +02005#ifdef HAVE_MALLOPT_MMAP_THRESHOLD
6 #include <malloc.h>
7#endif
8
Benjamin Peterson05159c42009-12-03 03:01:27 +00009#ifdef WITH_VALGRIND
10#include <valgrind/valgrind.h>
11
12/* If we're using GCC, use __builtin_expect() to reduce overhead of
13 the valgrind checks */
14#if defined(__GNUC__) && (__GNUC__ > 2) && defined(__OPTIMIZE__)
15# define UNLIKELY(value) __builtin_expect((value), 0)
16#else
17# define UNLIKELY(value) (value)
18#endif
19
20/* -1 indicates that we haven't checked that we're running on valgrind yet. */
21static int running_on_valgrind = -1;
22#endif
23
Neil Schemenauera35c6882001-02-27 04:45:05 +000024/* An object allocator for Python.
25
26 Here is an introduction to the layers of the Python memory architecture,
27 showing where the object allocator is actually used (layer +2), It is
28 called for every object allocation and deallocation (PyObject_New/Del),
29 unless the object-specific allocators implement a proprietary allocation
30 scheme (ex.: ints use a simple free list). This is also the place where
31 the cyclic garbage collector operates selectively on container objects.
32
33
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000034 Object-specific allocators
Neil Schemenauera35c6882001-02-27 04:45:05 +000035 _____ ______ ______ ________
36 [ int ] [ dict ] [ list ] ... [ string ] Python core |
37+3 | <----- Object-specific memory -----> | <-- Non-object memory --> |
38 _______________________________ | |
39 [ Python's object allocator ] | |
40+2 | ####### Object memory ####### | <------ Internal buffers ------> |
41 ______________________________________________________________ |
42 [ Python's raw memory allocator (PyMem_ API) ] |
43+1 | <----- Python memory (under PyMem manager's control) ------> | |
44 __________________________________________________________________
45 [ Underlying general-purpose allocator (ex: C library malloc) ]
46 0 | <------ Virtual memory allocated for the python process -------> |
47
48 =========================================================================
49 _______________________________________________________________________
50 [ OS-specific Virtual Memory Manager (VMM) ]
51-1 | <--- Kernel dynamic storage allocation & management (page-based) ---> |
52 __________________________________ __________________________________
53 [ ] [ ]
54-2 | <-- Physical memory: ROM/RAM --> | | <-- Secondary storage (swap) --> |
55
56*/
57/*==========================================================================*/
58
59/* A fast, special-purpose memory allocator for small blocks, to be used
60 on top of a general-purpose malloc -- heavily based on previous art. */
61
62/* Vladimir Marangozov -- August 2000 */
63
64/*
65 * "Memory management is where the rubber meets the road -- if we do the wrong
66 * thing at any level, the results will not be good. And if we don't make the
67 * levels work well together, we are in serious trouble." (1)
68 *
69 * (1) Paul R. Wilson, Mark S. Johnstone, Michael Neely, and David Boles,
70 * "Dynamic Storage Allocation: A Survey and Critical Review",
71 * in Proc. 1995 Int'l. Workshop on Memory Management, September 1995.
72 */
73
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000074/* #undef WITH_MEMORY_LIMITS */ /* disable mem limit checks */
Neil Schemenauera35c6882001-02-27 04:45:05 +000075
76/*==========================================================================*/
77
78/*
Neil Schemenauera35c6882001-02-27 04:45:05 +000079 * Allocation strategy abstract:
80 *
81 * For small requests, the allocator sub-allocates <Big> blocks of memory.
Antoine Pitrou6f26be02011-05-03 18:18:59 +020082 * Requests greater than SMALL_REQUEST_THRESHOLD bytes are routed to the
83 * system's allocator.
Tim Petersce7fb9b2002-03-23 00:28:57 +000084 *
Neil Schemenauera35c6882001-02-27 04:45:05 +000085 * Small requests are grouped in size classes spaced 8 bytes apart, due
86 * to the required valid alignment of the returned address. Requests of
87 * a particular size are serviced from memory pools of 4K (one VMM page).
88 * Pools are fragmented on demand and contain free lists of blocks of one
89 * particular size class. In other words, there is a fixed-size allocator
90 * for each size class. Free pools are shared by the different allocators
91 * thus minimizing the space reserved for a particular size class.
92 *
93 * This allocation strategy is a variant of what is known as "simple
94 * segregated storage based on array of free lists". The main drawback of
95 * simple segregated storage is that we might end up with lot of reserved
96 * memory for the different free lists, which degenerate in time. To avoid
97 * this, we partition each free list in pools and we share dynamically the
98 * reserved space between all free lists. This technique is quite efficient
99 * for memory intensive programs which allocate mainly small-sized blocks.
100 *
101 * For small requests we have the following table:
102 *
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000103 * Request in bytes Size of allocated block Size class idx
Neil Schemenauera35c6882001-02-27 04:45:05 +0000104 * ----------------------------------------------------------------
105 * 1-8 8 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000106 * 9-16 16 1
107 * 17-24 24 2
108 * 25-32 32 3
109 * 33-40 40 4
110 * 41-48 48 5
111 * 49-56 56 6
112 * 57-64 64 7
113 * 65-72 72 8
114 * ... ... ...
Antoine Pitrou6f26be02011-05-03 18:18:59 +0200115 * 497-504 504 62
116 * 505-512 512 63
Tim Petersce7fb9b2002-03-23 00:28:57 +0000117 *
Antoine Pitrou6f26be02011-05-03 18:18:59 +0200118 * 0, SMALL_REQUEST_THRESHOLD + 1 and up: routed to the underlying
119 * allocator.
Neil Schemenauera35c6882001-02-27 04:45:05 +0000120 */
121
122/*==========================================================================*/
123
124/*
125 * -- Main tunable settings section --
126 */
127
128/*
129 * Alignment of addresses returned to the user. 8-bytes alignment works
130 * on most current architectures (with 32-bit or 64-bit address busses).
131 * The alignment value is also used for grouping small requests in size
132 * classes spaced ALIGNMENT bytes apart.
133 *
134 * You shouldn't change this unless you know what you are doing.
135 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000136#define ALIGNMENT 8 /* must be 2^N */
137#define ALIGNMENT_SHIFT 3
138#define ALIGNMENT_MASK (ALIGNMENT - 1)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000139
Tim Peterse70ddf32002-04-05 04:32:29 +0000140/* Return the number of bytes in size class I, as a uint. */
141#define INDEX2SIZE(I) (((uint)(I) + 1) << ALIGNMENT_SHIFT)
142
Neil Schemenauera35c6882001-02-27 04:45:05 +0000143/*
144 * Max size threshold below which malloc requests are considered to be
145 * small enough in order to use preallocated memory pools. You can tune
146 * this value according to your application behaviour and memory needs.
147 *
Antoine Pitrou6f26be02011-05-03 18:18:59 +0200148 * Note: a size threshold of 512 guarantees that newly created dictionaries
149 * will be allocated from preallocated memory pools on 64-bit.
150 *
Neil Schemenauera35c6882001-02-27 04:45:05 +0000151 * The following invariants must hold:
Antoine Pitrou6f26be02011-05-03 18:18:59 +0200152 * 1) ALIGNMENT <= SMALL_REQUEST_THRESHOLD <= 512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000153 * 2) SMALL_REQUEST_THRESHOLD is evenly divisible by ALIGNMENT
Neil Schemenauera35c6882001-02-27 04:45:05 +0000154 *
155 * Although not required, for better performance and space efficiency,
156 * it is recommended that SMALL_REQUEST_THRESHOLD is set to a power of 2.
157 */
Antoine Pitrou6f26be02011-05-03 18:18:59 +0200158#define SMALL_REQUEST_THRESHOLD 512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000159#define NB_SMALL_SIZE_CLASSES (SMALL_REQUEST_THRESHOLD / ALIGNMENT)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000160
161/*
162 * The system's VMM page size can be obtained on most unices with a
163 * getpagesize() call or deduced from various header files. To make
164 * things simpler, we assume that it is 4K, which is OK for most systems.
165 * It is probably better if this is the native page size, but it doesn't
Tim Petersecc6e6a2005-07-10 22:30:55 +0000166 * have to be. In theory, if SYSTEM_PAGE_SIZE is larger than the native page
167 * size, then `POOL_ADDR(p)->arenaindex' could rarely cause a segmentation
168 * violation fault. 4K is apparently OK for all the platforms that python
Martin v. Löwis8c140282002-10-26 15:01:53 +0000169 * currently targets.
Neil Schemenauera35c6882001-02-27 04:45:05 +0000170 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000171#define SYSTEM_PAGE_SIZE (4 * 1024)
172#define SYSTEM_PAGE_SIZE_MASK (SYSTEM_PAGE_SIZE - 1)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000173
174/*
175 * Maximum amount of memory managed by the allocator for small requests.
176 */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000177#ifdef WITH_MEMORY_LIMITS
178#ifndef SMALL_MEMORY_LIMIT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000179#define SMALL_MEMORY_LIMIT (64 * 1024 * 1024) /* 64 MB -- more? */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000180#endif
181#endif
182
183/*
184 * The allocator sub-allocates <Big> blocks of memory (called arenas) aligned
185 * on a page boundary. This is a reserved virtual address space for the
186 * current process (obtained through a malloc call). In no way this means
187 * that the memory arenas will be used entirely. A malloc(<Big>) is usually
188 * an address range reservation for <Big> bytes, unless all pages within this
189 * space are referenced subsequently. So malloc'ing big blocks and not using
190 * them does not mean "wasting memory". It's an addressable range wastage...
191 *
192 * Therefore, allocating arenas with malloc is not optimal, because there is
193 * some address space wastage, but this is the most portable way to request
Tim Petersd97a1c02002-03-30 06:09:22 +0000194 * memory from the system across various platforms.
Neil Schemenauera35c6882001-02-27 04:45:05 +0000195 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000196#define ARENA_SIZE (256 << 10) /* 256KB */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000197
198#ifdef WITH_MEMORY_LIMITS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000199#define MAX_ARENAS (SMALL_MEMORY_LIMIT / ARENA_SIZE)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000200#endif
201
202/*
203 * Size of the pools used for small blocks. Should be a power of 2,
Tim Petersc2ce91a2002-03-30 21:36:04 +0000204 * between 1K and SYSTEM_PAGE_SIZE, that is: 1k, 2k, 4k.
Neil Schemenauera35c6882001-02-27 04:45:05 +0000205 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000206#define POOL_SIZE SYSTEM_PAGE_SIZE /* must be 2^N */
207#define POOL_SIZE_MASK SYSTEM_PAGE_SIZE_MASK
Neil Schemenauera35c6882001-02-27 04:45:05 +0000208
209/*
210 * -- End of tunable settings section --
211 */
212
213/*==========================================================================*/
214
215/*
216 * Locking
217 *
218 * To reduce lock contention, it would probably be better to refine the
219 * crude function locking with per size class locking. I'm not positive
220 * however, whether it's worth switching to such locking policy because
221 * of the performance penalty it might introduce.
222 *
223 * The following macros describe the simplest (should also be the fastest)
224 * lock object on a particular platform and the init/fini/lock/unlock
225 * operations on it. The locks defined here are not expected to be recursive
226 * because it is assumed that they will always be called in the order:
227 * INIT, [LOCK, UNLOCK]*, FINI.
228 */
229
230/*
231 * Python's threads are serialized, so object malloc locking is disabled.
232 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000233#define SIMPLELOCK_DECL(lock) /* simple lock declaration */
234#define SIMPLELOCK_INIT(lock) /* allocate (if needed) and initialize */
235#define SIMPLELOCK_FINI(lock) /* free/destroy an existing lock */
236#define SIMPLELOCK_LOCK(lock) /* acquire released lock */
237#define SIMPLELOCK_UNLOCK(lock) /* release acquired lock */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000238
239/*
240 * Basic types
241 * I don't care if these are defined in <sys/types.h> or elsewhere. Axiom.
242 */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000243#undef uchar
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000244#define uchar unsigned char /* assuming == 8 bits */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000245
Neil Schemenauera35c6882001-02-27 04:45:05 +0000246#undef uint
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000247#define uint unsigned int /* assuming >= 16 bits */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000248
249#undef ulong
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000250#define ulong unsigned long /* assuming >= 32 bits */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000251
Tim Petersd97a1c02002-03-30 06:09:22 +0000252#undef uptr
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000253#define uptr Py_uintptr_t
Tim Petersd97a1c02002-03-30 06:09:22 +0000254
Neil Schemenauera35c6882001-02-27 04:45:05 +0000255/* When you say memory, my mind reasons in terms of (pointers to) blocks */
256typedef uchar block;
257
Tim Peterse70ddf32002-04-05 04:32:29 +0000258/* Pool for small blocks. */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000259struct pool_header {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000260 union { block *_padding;
Stefan Krah735bb122010-11-26 10:54:09 +0000261 uint count; } ref; /* number of allocated blocks */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000262 block *freeblock; /* pool's free list head */
263 struct pool_header *nextpool; /* next pool of this size class */
264 struct pool_header *prevpool; /* previous pool "" */
265 uint arenaindex; /* index into arenas of base adr */
266 uint szidx; /* block size class index */
267 uint nextoffset; /* bytes to virgin block */
268 uint maxnextoffset; /* largest valid nextoffset */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000269};
270
271typedef struct pool_header *poolp;
272
Thomas Woutersa9773292006-04-21 09:43:23 +0000273/* Record keeping for arenas. */
274struct arena_object {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000275 /* The address of the arena, as returned by malloc. Note that 0
276 * will never be returned by a successful malloc, and is used
277 * here to mark an arena_object that doesn't correspond to an
278 * allocated arena.
279 */
280 uptr address;
Thomas Woutersa9773292006-04-21 09:43:23 +0000281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000282 /* Pool-aligned pointer to the next pool to be carved off. */
283 block* pool_address;
Thomas Woutersa9773292006-04-21 09:43:23 +0000284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000285 /* The number of available pools in the arena: free pools + never-
286 * allocated pools.
287 */
288 uint nfreepools;
Thomas Woutersa9773292006-04-21 09:43:23 +0000289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000290 /* The total number of pools in the arena, whether or not available. */
291 uint ntotalpools;
Thomas Woutersa9773292006-04-21 09:43:23 +0000292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000293 /* Singly-linked list of available pools. */
294 struct pool_header* freepools;
Thomas Woutersa9773292006-04-21 09:43:23 +0000295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000296 /* Whenever this arena_object is not associated with an allocated
297 * arena, the nextarena member is used to link all unassociated
298 * arena_objects in the singly-linked `unused_arena_objects` list.
299 * The prevarena member is unused in this case.
300 *
301 * When this arena_object is associated with an allocated arena
302 * with at least one available pool, both members are used in the
303 * doubly-linked `usable_arenas` list, which is maintained in
304 * increasing order of `nfreepools` values.
305 *
306 * Else this arena_object is associated with an allocated arena
307 * all of whose pools are in use. `nextarena` and `prevarena`
308 * are both meaningless in this case.
309 */
310 struct arena_object* nextarena;
311 struct arena_object* prevarena;
Thomas Woutersa9773292006-04-21 09:43:23 +0000312};
313
Neil Schemenauera35c6882001-02-27 04:45:05 +0000314#undef ROUNDUP
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000315#define ROUNDUP(x) (((x) + ALIGNMENT_MASK) & ~ALIGNMENT_MASK)
316#define POOL_OVERHEAD ROUNDUP(sizeof(struct pool_header))
Neil Schemenauera35c6882001-02-27 04:45:05 +0000317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000318#define DUMMY_SIZE_IDX 0xffff /* size class of newly cached pools */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000319
Tim Petersd97a1c02002-03-30 06:09:22 +0000320/* Round pointer P down to the closest pool-aligned address <= P, as a poolp */
Tim Peterse70ddf32002-04-05 04:32:29 +0000321#define POOL_ADDR(P) ((poolp)((uptr)(P) & ~(uptr)POOL_SIZE_MASK))
322
Tim Peters16bcb6b2002-04-05 05:45:31 +0000323/* Return total number of blocks in pool of size index I, as a uint. */
324#define NUMBLOCKS(I) ((uint)(POOL_SIZE - POOL_OVERHEAD) / INDEX2SIZE(I))
Tim Petersd97a1c02002-03-30 06:09:22 +0000325
Neil Schemenauera35c6882001-02-27 04:45:05 +0000326/*==========================================================================*/
327
328/*
329 * This malloc lock
330 */
Jeremy Hyltond1fedb62002-07-18 18:49:52 +0000331SIMPLELOCK_DECL(_malloc_lock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000332#define LOCK() SIMPLELOCK_LOCK(_malloc_lock)
333#define UNLOCK() SIMPLELOCK_UNLOCK(_malloc_lock)
334#define LOCK_INIT() SIMPLELOCK_INIT(_malloc_lock)
335#define LOCK_FINI() SIMPLELOCK_FINI(_malloc_lock)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000336
337/*
Tim Peters1e16db62002-03-31 01:05:22 +0000338 * Pool table -- headed, circular, doubly-linked lists of partially used pools.
339
340This is involved. For an index i, usedpools[i+i] is the header for a list of
341all partially used pools holding small blocks with "size class idx" i. So
342usedpools[0] corresponds to blocks of size 8, usedpools[2] to blocks of size
34316, and so on: index 2*i <-> blocks of size (i+1)<<ALIGNMENT_SHIFT.
344
Thomas Woutersa9773292006-04-21 09:43:23 +0000345Pools are carved off an arena's highwater mark (an arena_object's pool_address
346member) as needed. Once carved off, a pool is in one of three states forever
347after:
Tim Peters1e16db62002-03-31 01:05:22 +0000348
Tim Peters338e0102002-04-01 19:23:44 +0000349used == partially used, neither empty nor full
350 At least one block in the pool is currently allocated, and at least one
351 block in the pool is not currently allocated (note this implies a pool
352 has room for at least two blocks).
353 This is a pool's initial state, as a pool is created only when malloc
354 needs space.
355 The pool holds blocks of a fixed size, and is in the circular list headed
356 at usedpools[i] (see above). It's linked to the other used pools of the
357 same size class via the pool_header's nextpool and prevpool members.
358 If all but one block is currently allocated, a malloc can cause a
359 transition to the full state. If all but one block is not currently
360 allocated, a free can cause a transition to the empty state.
Tim Peters1e16db62002-03-31 01:05:22 +0000361
Tim Peters338e0102002-04-01 19:23:44 +0000362full == all the pool's blocks are currently allocated
363 On transition to full, a pool is unlinked from its usedpools[] list.
364 It's not linked to from anything then anymore, and its nextpool and
365 prevpool members are meaningless until it transitions back to used.
366 A free of a block in a full pool puts the pool back in the used state.
367 Then it's linked in at the front of the appropriate usedpools[] list, so
368 that the next allocation for its size class will reuse the freed block.
369
370empty == all the pool's blocks are currently available for allocation
371 On transition to empty, a pool is unlinked from its usedpools[] list,
Thomas Woutersa9773292006-04-21 09:43:23 +0000372 and linked to the front of its arena_object's singly-linked freepools list,
Tim Peters338e0102002-04-01 19:23:44 +0000373 via its nextpool member. The prevpool member has no meaning in this case.
374 Empty pools have no inherent size class: the next time a malloc finds
375 an empty list in usedpools[], it takes the first pool off of freepools.
376 If the size class needed happens to be the same as the size class the pool
Tim Peterse70ddf32002-04-05 04:32:29 +0000377 last had, some pool initialization can be skipped.
Tim Peters338e0102002-04-01 19:23:44 +0000378
379
380Block Management
381
382Blocks within pools are again carved out as needed. pool->freeblock points to
383the start of a singly-linked list of free blocks within the pool. When a
384block is freed, it's inserted at the front of its pool's freeblock list. Note
385that the available blocks in a pool are *not* linked all together when a pool
Tim Peterse70ddf32002-04-05 04:32:29 +0000386is initialized. Instead only "the first two" (lowest addresses) blocks are
387set up, returning the first such block, and setting pool->freeblock to a
388one-block list holding the second such block. This is consistent with that
389pymalloc strives at all levels (arena, pool, and block) never to touch a piece
390of memory until it's actually needed.
391
392So long as a pool is in the used state, we're certain there *is* a block
Tim Peters52aefc82002-04-11 06:36:45 +0000393available for allocating, and pool->freeblock is not NULL. If pool->freeblock
394points to the end of the free list before we've carved the entire pool into
395blocks, that means we simply haven't yet gotten to one of the higher-address
396blocks. The offset from the pool_header to the start of "the next" virgin
397block is stored in the pool_header nextoffset member, and the largest value
398of nextoffset that makes sense is stored in the maxnextoffset member when a
399pool is initialized. All the blocks in a pool have been passed out at least
400once when and only when nextoffset > maxnextoffset.
Tim Peters338e0102002-04-01 19:23:44 +0000401
Tim Peters1e16db62002-03-31 01:05:22 +0000402
403Major obscurity: While the usedpools vector is declared to have poolp
404entries, it doesn't really. It really contains two pointers per (conceptual)
405poolp entry, the nextpool and prevpool members of a pool_header. The
406excruciating initialization code below fools C so that
407
408 usedpool[i+i]
409
410"acts like" a genuine poolp, but only so long as you only reference its
411nextpool and prevpool members. The "- 2*sizeof(block *)" gibberish is
412compensating for that a pool_header's nextpool and prevpool members
413immediately follow a pool_header's first two members:
414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000415 union { block *_padding;
Stefan Krah735bb122010-11-26 10:54:09 +0000416 uint count; } ref;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417 block *freeblock;
Tim Peters1e16db62002-03-31 01:05:22 +0000418
419each of which consume sizeof(block *) bytes. So what usedpools[i+i] really
420contains is a fudged-up pointer p such that *if* C believes it's a poolp
421pointer, then p->nextpool and p->prevpool are both p (meaning that the headed
422circular list is empty).
423
424It's unclear why the usedpools setup is so convoluted. It could be to
425minimize the amount of cache required to hold this heavily-referenced table
426(which only *needs* the two interpool pointer members of a pool_header). OTOH,
427referencing code has to remember to "double the index" and doing so isn't
428free, usedpools[0] isn't a strictly legal pointer, and we're crucially relying
429on that C doesn't insert any padding anywhere in a pool_header at or before
430the prevpool member.
431**************************************************************************** */
432
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000433#define PTA(x) ((poolp )((uchar *)&(usedpools[2*(x)]) - 2*sizeof(block *)))
434#define PT(x) PTA(x), PTA(x)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000435
436static poolp usedpools[2 * ((NB_SMALL_SIZE_CLASSES + 7) / 8) * 8] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000437 PT(0), PT(1), PT(2), PT(3), PT(4), PT(5), PT(6), PT(7)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000438#if NB_SMALL_SIZE_CLASSES > 8
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000439 , PT(8), PT(9), PT(10), PT(11), PT(12), PT(13), PT(14), PT(15)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000440#if NB_SMALL_SIZE_CLASSES > 16
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000441 , PT(16), PT(17), PT(18), PT(19), PT(20), PT(21), PT(22), PT(23)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000442#if NB_SMALL_SIZE_CLASSES > 24
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000443 , PT(24), PT(25), PT(26), PT(27), PT(28), PT(29), PT(30), PT(31)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000444#if NB_SMALL_SIZE_CLASSES > 32
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000445 , PT(32), PT(33), PT(34), PT(35), PT(36), PT(37), PT(38), PT(39)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000446#if NB_SMALL_SIZE_CLASSES > 40
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000447 , PT(40), PT(41), PT(42), PT(43), PT(44), PT(45), PT(46), PT(47)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000448#if NB_SMALL_SIZE_CLASSES > 48
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000449 , PT(48), PT(49), PT(50), PT(51), PT(52), PT(53), PT(54), PT(55)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000450#if NB_SMALL_SIZE_CLASSES > 56
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000451 , PT(56), PT(57), PT(58), PT(59), PT(60), PT(61), PT(62), PT(63)
Antoine Pitrou6f26be02011-05-03 18:18:59 +0200452#if NB_SMALL_SIZE_CLASSES > 64
453#error "NB_SMALL_SIZE_CLASSES should be less than 64"
454#endif /* NB_SMALL_SIZE_CLASSES > 64 */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000455#endif /* NB_SMALL_SIZE_CLASSES > 56 */
456#endif /* NB_SMALL_SIZE_CLASSES > 48 */
457#endif /* NB_SMALL_SIZE_CLASSES > 40 */
458#endif /* NB_SMALL_SIZE_CLASSES > 32 */
459#endif /* NB_SMALL_SIZE_CLASSES > 24 */
460#endif /* NB_SMALL_SIZE_CLASSES > 16 */
461#endif /* NB_SMALL_SIZE_CLASSES > 8 */
462};
463
Thomas Woutersa9773292006-04-21 09:43:23 +0000464/*==========================================================================
465Arena management.
Neil Schemenauera35c6882001-02-27 04:45:05 +0000466
Thomas Woutersa9773292006-04-21 09:43:23 +0000467`arenas` is a vector of arena_objects. It contains maxarenas entries, some of
468which may not be currently used (== they're arena_objects that aren't
469currently associated with an allocated arena). Note that arenas proper are
470separately malloc'ed.
Neil Schemenauera35c6882001-02-27 04:45:05 +0000471
Thomas Woutersa9773292006-04-21 09:43:23 +0000472Prior to Python 2.5, arenas were never free()'ed. Starting with Python 2.5,
473we do try to free() arenas, and use some mild heuristic strategies to increase
474the likelihood that arenas eventually can be freed.
475
476unused_arena_objects
477
478 This is a singly-linked list of the arena_objects that are currently not
479 being used (no arena is associated with them). Objects are taken off the
480 head of the list in new_arena(), and are pushed on the head of the list in
481 PyObject_Free() when the arena is empty. Key invariant: an arena_object
482 is on this list if and only if its .address member is 0.
483
484usable_arenas
485
486 This is a doubly-linked list of the arena_objects associated with arenas
487 that have pools available. These pools are either waiting to be reused,
488 or have not been used before. The list is sorted to have the most-
489 allocated arenas first (ascending order based on the nfreepools member).
490 This means that the next allocation will come from a heavily used arena,
491 which gives the nearly empty arenas a chance to be returned to the system.
492 In my unscientific tests this dramatically improved the number of arenas
493 that could be freed.
494
495Note that an arena_object associated with an arena all of whose pools are
496currently in use isn't on either list.
497*/
498
499/* Array of objects used to track chunks of memory (arenas). */
500static struct arena_object* arenas = NULL;
501/* Number of slots currently allocated in the `arenas` vector. */
Tim Peters1d99af82002-03-30 10:35:09 +0000502static uint maxarenas = 0;
Tim Petersd97a1c02002-03-30 06:09:22 +0000503
Thomas Woutersa9773292006-04-21 09:43:23 +0000504/* The head of the singly-linked, NULL-terminated list of available
505 * arena_objects.
Tim Petersd97a1c02002-03-30 06:09:22 +0000506 */
Thomas Woutersa9773292006-04-21 09:43:23 +0000507static struct arena_object* unused_arena_objects = NULL;
508
509/* The head of the doubly-linked, NULL-terminated at each end, list of
510 * arena_objects associated with arenas that have pools available.
511 */
512static struct arena_object* usable_arenas = NULL;
513
514/* How many arena_objects do we initially allocate?
515 * 16 = can allocate 16 arenas = 16 * ARENA_SIZE = 4MB before growing the
516 * `arenas` vector.
517 */
518#define INITIAL_ARENA_OBJECTS 16
519
520/* Number of arenas allocated that haven't been free()'d. */
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000521static size_t narenas_currently_allocated = 0;
Thomas Woutersa9773292006-04-21 09:43:23 +0000522
523#ifdef PYMALLOC_DEBUG
524/* Total number of times malloc() called to allocate an arena. */
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000525static size_t ntimes_arena_allocated = 0;
Thomas Woutersa9773292006-04-21 09:43:23 +0000526/* High water mark (max value ever seen) for narenas_currently_allocated. */
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000527static size_t narenas_highwater = 0;
Thomas Woutersa9773292006-04-21 09:43:23 +0000528#endif
529
530/* Allocate a new arena. If we run out of memory, return NULL. Else
531 * allocate a new arena, and return the address of an arena_object
532 * describing the new arena. It's expected that the caller will set
533 * `usable_arenas` to the return value.
534 */
535static struct arena_object*
Tim Petersd97a1c02002-03-30 06:09:22 +0000536new_arena(void)
537{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 struct arena_object* arenaobj;
539 uint excess; /* number of bytes above pool alignment */
Tim Petersd97a1c02002-03-30 06:09:22 +0000540
Tim Peters0e871182002-04-13 08:29:14 +0000541#ifdef PYMALLOC_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000542 if (Py_GETENV("PYTHONMALLOCSTATS"))
543 _PyObject_DebugMallocStats();
Tim Peters0e871182002-04-13 08:29:14 +0000544#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000545 if (unused_arena_objects == NULL) {
546 uint i;
547 uint numarenas;
548 size_t nbytes;
Tim Peters0e871182002-04-13 08:29:14 +0000549
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000550 /* Double the number of arena objects on each allocation.
551 * Note that it's possible for `numarenas` to overflow.
552 */
553 numarenas = maxarenas ? maxarenas << 1 : INITIAL_ARENA_OBJECTS;
554 if (numarenas <= maxarenas)
555 return NULL; /* overflow */
Martin v. Löwis5aca8822008-09-11 06:55:48 +0000556#if SIZEOF_SIZE_T <= SIZEOF_INT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000557 if (numarenas > PY_SIZE_MAX / sizeof(*arenas))
558 return NULL; /* overflow */
Martin v. Löwis5aca8822008-09-11 06:55:48 +0000559#endif
Antoine Pitrou6f26be02011-05-03 18:18:59 +0200560#ifdef HAVE_MALLOPT_MMAP_THRESHOLD
561 /* Ensure arenas are allocated by mmap to avoid heap fragmentation. */
562 if (numarenas == INITIAL_ARENA_OBJECTS)
563 mallopt(M_MMAP_THRESHOLD, ARENA_SIZE);
564#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);
597 arenaobj->address = (uptr)malloc(ARENA_SIZE);
598 if (arenaobj->address == 0) {
599 /* The allocation failed: return NULL after putting the
600 * arenaobj back.
601 */
602 arenaobj->nextarena = unused_arena_objects;
603 unused_arena_objects = arenaobj;
604 return NULL;
605 }
Tim Petersd97a1c02002-03-30 06:09:22 +0000606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000607 ++narenas_currently_allocated;
Thomas Woutersa9773292006-04-21 09:43:23 +0000608#ifdef PYMALLOC_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 ++ntimes_arena_allocated;
610 if (narenas_currently_allocated > narenas_highwater)
611 narenas_highwater = narenas_currently_allocated;
Thomas Woutersa9773292006-04-21 09:43:23 +0000612#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000613 arenaobj->freepools = NULL;
614 /* pool_address <- first pool-aligned address in the arena
615 nfreepools <- number of whole pools that fit after alignment */
616 arenaobj->pool_address = (block*)arenaobj->address;
617 arenaobj->nfreepools = ARENA_SIZE / POOL_SIZE;
618 assert(POOL_SIZE * arenaobj->nfreepools == ARENA_SIZE);
619 excess = (uint)(arenaobj->address & POOL_SIZE_MASK);
620 if (excess != 0) {
621 --arenaobj->nfreepools;
622 arenaobj->pool_address += POOL_SIZE - excess;
623 }
624 arenaobj->ntotalpools = arenaobj->nfreepools;
Thomas Woutersa9773292006-04-21 09:43:23 +0000625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000626 return arenaobj;
Tim Petersd97a1c02002-03-30 06:09:22 +0000627}
628
Thomas Woutersa9773292006-04-21 09:43:23 +0000629/*
630Py_ADDRESS_IN_RANGE(P, POOL)
631
632Return true if and only if P is an address that was allocated by pymalloc.
633POOL must be the pool address associated with P, i.e., POOL = POOL_ADDR(P)
634(the caller is asked to compute this because the macro expands POOL more than
635once, and for efficiency it's best for the caller to assign POOL_ADDR(P) to a
636variable and pass the latter to the macro; because Py_ADDRESS_IN_RANGE is
637called on every alloc/realloc/free, micro-efficiency is important here).
638
639Tricky: Let B be the arena base address associated with the pool, B =
640arenas[(POOL)->arenaindex].address. Then P belongs to the arena if and only if
641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 B <= P < B + ARENA_SIZE
Thomas Woutersa9773292006-04-21 09:43:23 +0000643
644Subtracting B throughout, this is true iff
645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 0 <= P-B < ARENA_SIZE
Thomas Woutersa9773292006-04-21 09:43:23 +0000647
648By using unsigned arithmetic, the "0 <=" half of the test can be skipped.
649
650Obscure: A PyMem "free memory" function can call the pymalloc free or realloc
651before the first arena has been allocated. `arenas` is still NULL in that
652case. We're relying on that maxarenas is also 0 in that case, so that
653(POOL)->arenaindex < maxarenas must be false, saving us from trying to index
654into a NULL arenas.
655
656Details: given P and POOL, the arena_object corresponding to P is AO =
657arenas[(POOL)->arenaindex]. Suppose obmalloc controls P. Then (barring wild
658stores, etc), POOL is the correct address of P's pool, AO.address is the
659correct base address of the pool's arena, and P must be within ARENA_SIZE of
660AO.address. In addition, AO.address is not 0 (no arena can start at address 0
661(NULL)). Therefore Py_ADDRESS_IN_RANGE correctly reports that obmalloc
662controls P.
663
664Now suppose obmalloc does not control P (e.g., P was obtained via a direct
665call to the system malloc() or realloc()). (POOL)->arenaindex may be anything
666in this case -- it may even be uninitialized trash. If the trash arenaindex
667is >= maxarenas, the macro correctly concludes at once that obmalloc doesn't
668control P.
669
670Else arenaindex is < maxarena, and AO is read up. If AO corresponds to an
671allocated arena, obmalloc controls all the memory in slice AO.address :
672AO.address+ARENA_SIZE. By case assumption, P is not controlled by obmalloc,
673so P doesn't lie in that slice, so the macro correctly reports that P is not
674controlled by obmalloc.
675
676Finally, if P is not controlled by obmalloc and AO corresponds to an unused
677arena_object (one not currently associated with an allocated arena),
678AO.address is 0, and the second test in the macro reduces to:
679
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000680 P < ARENA_SIZE
Thomas Woutersa9773292006-04-21 09:43:23 +0000681
682If P >= ARENA_SIZE (extremely likely), the macro again correctly concludes
683that P is not controlled by obmalloc. However, if P < ARENA_SIZE, this part
684of the test still passes, and the third clause (AO.address != 0) is necessary
685to get the correct result: AO.address is 0 in this case, so the macro
686correctly reports that P is not controlled by obmalloc (despite that P lies in
687slice AO.address : AO.address + ARENA_SIZE).
688
689Note: The third (AO.address != 0) clause was added in Python 2.5. Before
6902.5, arenas were never free()'ed, and an arenaindex < maxarena always
691corresponded to a currently-allocated arena, so the "P is not controlled by
692obmalloc, AO corresponds to an unused arena_object, and P < ARENA_SIZE" case
693was impossible.
694
695Note that the logic is excruciating, and reading up possibly uninitialized
696memory when P is not controlled by obmalloc (to get at (POOL)->arenaindex)
697creates problems for some memory debuggers. The overwhelming advantage is
698that this test determines whether an arbitrary address is controlled by
699obmalloc in a small constant time, independent of the number of arenas
700obmalloc controls. Since this test is needed at every entry point, it's
701extremely desirable that it be this fast.
Antoine Pitroub7fb2e22011-01-07 21:43:59 +0000702
703Since Py_ADDRESS_IN_RANGE may be reading from memory which was not allocated
704by Python, it is important that (POOL)->arenaindex is read only once, as
705another thread may be concurrently modifying the value without holding the
706GIL. To accomplish this, the arenaindex_temp variable is used to store
707(POOL)->arenaindex for the duration of the Py_ADDRESS_IN_RANGE macro's
708execution. The caller of the macro is responsible for declaring this
709variable.
Thomas Woutersa9773292006-04-21 09:43:23 +0000710*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000711#define Py_ADDRESS_IN_RANGE(P, POOL) \
Antoine Pitroub7fb2e22011-01-07 21:43:59 +0000712 ((arenaindex_temp = (POOL)->arenaindex) < maxarenas && \
713 (uptr)(P) - arenas[arenaindex_temp].address < (uptr)ARENA_SIZE && \
714 arenas[arenaindex_temp].address != 0)
Thomas Woutersa9773292006-04-21 09:43:23 +0000715
Neal Norwitz7eb3c912004-06-06 19:20:22 +0000716
717/* This is only useful when running memory debuggers such as
718 * Purify or Valgrind. Uncomment to use.
719 *
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000720#define Py_USING_MEMORY_DEBUGGER
Martin v. Löwis6fea2332008-09-25 04:15:27 +0000721 */
Neal Norwitz7eb3c912004-06-06 19:20:22 +0000722
723#ifdef Py_USING_MEMORY_DEBUGGER
724
725/* Py_ADDRESS_IN_RANGE may access uninitialized memory by design
726 * This leads to thousands of spurious warnings when using
727 * Purify or Valgrind. By making a function, we can easily
728 * suppress the uninitialized memory reads in this one function.
729 * So we won't ignore real errors elsewhere.
730 *
731 * Disable the macro and use a function.
732 */
733
734#undef Py_ADDRESS_IN_RANGE
735
Thomas Wouters89f507f2006-12-13 04:49:30 +0000736#if defined(__GNUC__) && ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 1) || \
Stefan Krah735bb122010-11-26 10:54:09 +0000737 (__GNUC__ >= 4))
Neal Norwitze5e5aa42005-11-13 18:55:39 +0000738#define Py_NO_INLINE __attribute__((__noinline__))
739#else
740#define Py_NO_INLINE
741#endif
742
743/* Don't make static, to try to ensure this isn't inlined. */
744int Py_ADDRESS_IN_RANGE(void *P, poolp pool) Py_NO_INLINE;
745#undef Py_NO_INLINE
Neal Norwitz7eb3c912004-06-06 19:20:22 +0000746#endif
Tim Peters338e0102002-04-01 19:23:44 +0000747
Neil Schemenauera35c6882001-02-27 04:45:05 +0000748/*==========================================================================*/
749
Tim Peters84c1b972002-04-04 04:44:32 +0000750/* malloc. Note that nbytes==0 tries to return a non-NULL pointer, distinct
751 * from all other currently live pointers. This may not be possible.
752 */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000753
754/*
755 * The basic blocks are ordered by decreasing execution frequency,
756 * which minimizes the number of jumps in the most common cases,
757 * improves branching prediction and instruction scheduling (small
758 * block allocations typically result in a couple of instructions).
759 * Unless the optimizer reorders everything, being too smart...
760 */
761
Neil Schemenauerd2560cd2002-04-12 03:10:20 +0000762#undef PyObject_Malloc
Neil Schemenauera35c6882001-02-27 04:45:05 +0000763void *
Neil Schemenauerd2560cd2002-04-12 03:10:20 +0000764PyObject_Malloc(size_t nbytes)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000765{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000766 block *bp;
767 poolp pool;
768 poolp next;
769 uint size;
Neil Schemenauera35c6882001-02-27 04:45:05 +0000770
Benjamin Peterson05159c42009-12-03 03:01:27 +0000771#ifdef WITH_VALGRIND
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000772 if (UNLIKELY(running_on_valgrind == -1))
773 running_on_valgrind = RUNNING_ON_VALGRIND;
774 if (UNLIKELY(running_on_valgrind))
775 goto redirect;
Benjamin Peterson05159c42009-12-03 03:01:27 +0000776#endif
777
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 /*
779 * Limit ourselves to PY_SSIZE_T_MAX bytes to prevent security holes.
780 * Most python internals blindly use a signed Py_ssize_t to track
781 * things without checking for overflows or negatives.
782 * As size_t is unsigned, checking for nbytes < 0 is not required.
783 */
784 if (nbytes > PY_SSIZE_T_MAX)
785 return NULL;
Georg Brandld492ad82008-07-23 16:13:07 +0000786
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 /*
788 * This implicitly redirects malloc(0).
789 */
790 if ((nbytes - 1) < SMALL_REQUEST_THRESHOLD) {
791 LOCK();
792 /*
793 * Most frequent paths first
794 */
795 size = (uint)(nbytes - 1) >> ALIGNMENT_SHIFT;
796 pool = usedpools[size + size];
797 if (pool != pool->nextpool) {
798 /*
799 * There is a used pool for this size class.
800 * Pick up the head block of its free list.
801 */
802 ++pool->ref.count;
803 bp = pool->freeblock;
804 assert(bp != NULL);
805 if ((pool->freeblock = *(block **)bp) != NULL) {
806 UNLOCK();
807 return (void *)bp;
808 }
809 /*
810 * Reached the end of the free list, try to extend it.
811 */
812 if (pool->nextoffset <= pool->maxnextoffset) {
813 /* There is room for another block. */
814 pool->freeblock = (block*)pool +
815 pool->nextoffset;
816 pool->nextoffset += INDEX2SIZE(size);
817 *(block **)(pool->freeblock) = NULL;
818 UNLOCK();
819 return (void *)bp;
820 }
821 /* Pool is full, unlink from used pools. */
822 next = pool->nextpool;
823 pool = pool->prevpool;
824 next->prevpool = pool;
825 pool->nextpool = next;
826 UNLOCK();
827 return (void *)bp;
828 }
Thomas Woutersa9773292006-04-21 09:43:23 +0000829
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 /* There isn't a pool of the right size class immediately
831 * available: use a free pool.
832 */
833 if (usable_arenas == NULL) {
834 /* No arena has a free pool: allocate a new arena. */
Thomas Woutersa9773292006-04-21 09:43:23 +0000835#ifdef WITH_MEMORY_LIMITS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 if (narenas_currently_allocated >= MAX_ARENAS) {
837 UNLOCK();
838 goto redirect;
839 }
Thomas Woutersa9773292006-04-21 09:43:23 +0000840#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000841 usable_arenas = new_arena();
842 if (usable_arenas == NULL) {
843 UNLOCK();
844 goto redirect;
845 }
846 usable_arenas->nextarena =
847 usable_arenas->prevarena = NULL;
848 }
849 assert(usable_arenas->address != 0);
Thomas Woutersa9773292006-04-21 09:43:23 +0000850
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000851 /* Try to get a cached free pool. */
852 pool = usable_arenas->freepools;
853 if (pool != NULL) {
854 /* Unlink from cached pools. */
855 usable_arenas->freepools = pool->nextpool;
Thomas Woutersa9773292006-04-21 09:43:23 +0000856
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000857 /* This arena already had the smallest nfreepools
858 * value, so decreasing nfreepools doesn't change
859 * that, and we don't need to rearrange the
860 * usable_arenas list. However, if the arena has
861 * become wholly allocated, we need to remove its
862 * arena_object from usable_arenas.
863 */
864 --usable_arenas->nfreepools;
865 if (usable_arenas->nfreepools == 0) {
866 /* Wholly allocated: remove. */
867 assert(usable_arenas->freepools == NULL);
868 assert(usable_arenas->nextarena == NULL ||
869 usable_arenas->nextarena->prevarena ==
870 usable_arenas);
Thomas Woutersa9773292006-04-21 09:43:23 +0000871
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000872 usable_arenas = usable_arenas->nextarena;
873 if (usable_arenas != NULL) {
874 usable_arenas->prevarena = NULL;
875 assert(usable_arenas->address != 0);
876 }
877 }
878 else {
879 /* nfreepools > 0: it must be that freepools
880 * isn't NULL, or that we haven't yet carved
881 * off all the arena's pools for the first
882 * time.
883 */
884 assert(usable_arenas->freepools != NULL ||
885 usable_arenas->pool_address <=
886 (block*)usable_arenas->address +
887 ARENA_SIZE - POOL_SIZE);
888 }
889 init_pool:
890 /* Frontlink to used pools. */
891 next = usedpools[size + size]; /* == prev */
892 pool->nextpool = next;
893 pool->prevpool = next;
894 next->nextpool = pool;
895 next->prevpool = pool;
896 pool->ref.count = 1;
897 if (pool->szidx == size) {
898 /* Luckily, this pool last contained blocks
899 * of the same size class, so its header
900 * and free list are already initialized.
901 */
902 bp = pool->freeblock;
903 pool->freeblock = *(block **)bp;
904 UNLOCK();
905 return (void *)bp;
906 }
907 /*
908 * Initialize the pool header, set up the free list to
909 * contain just the second block, and return the first
910 * block.
911 */
912 pool->szidx = size;
913 size = INDEX2SIZE(size);
914 bp = (block *)pool + POOL_OVERHEAD;
915 pool->nextoffset = POOL_OVERHEAD + (size << 1);
916 pool->maxnextoffset = POOL_SIZE - size;
917 pool->freeblock = bp + size;
918 *(block **)(pool->freeblock) = NULL;
919 UNLOCK();
920 return (void *)bp;
921 }
Thomas Woutersa9773292006-04-21 09:43:23 +0000922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000923 /* Carve off a new pool. */
924 assert(usable_arenas->nfreepools > 0);
925 assert(usable_arenas->freepools == NULL);
926 pool = (poolp)usable_arenas->pool_address;
927 assert((block*)pool <= (block*)usable_arenas->address +
928 ARENA_SIZE - POOL_SIZE);
929 pool->arenaindex = usable_arenas - arenas;
930 assert(&arenas[pool->arenaindex] == usable_arenas);
931 pool->szidx = DUMMY_SIZE_IDX;
932 usable_arenas->pool_address += POOL_SIZE;
933 --usable_arenas->nfreepools;
Thomas Woutersa9773292006-04-21 09:43:23 +0000934
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935 if (usable_arenas->nfreepools == 0) {
936 assert(usable_arenas->nextarena == NULL ||
937 usable_arenas->nextarena->prevarena ==
938 usable_arenas);
939 /* Unlink the arena: it is completely allocated. */
940 usable_arenas = usable_arenas->nextarena;
941 if (usable_arenas != NULL) {
942 usable_arenas->prevarena = NULL;
943 assert(usable_arenas->address != 0);
944 }
945 }
Thomas Woutersa9773292006-04-21 09:43:23 +0000946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 goto init_pool;
948 }
Neil Schemenauera35c6882001-02-27 04:45:05 +0000949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 /* The small block allocator ends here. */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000951
Tim Petersd97a1c02002-03-30 06:09:22 +0000952redirect:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 /* Redirect the original request to the underlying (libc) allocator.
954 * We jump here on bigger requests, on error in the code above (as a
955 * last chance to serve the request) or when the max memory limit
956 * has been reached.
957 */
958 if (nbytes == 0)
959 nbytes = 1;
960 return (void *)malloc(nbytes);
Neil Schemenauera35c6882001-02-27 04:45:05 +0000961}
962
963/* free */
964
Neil Schemenauerd2560cd2002-04-12 03:10:20 +0000965#undef PyObject_Free
Neil Schemenauera35c6882001-02-27 04:45:05 +0000966void
Neil Schemenauerd2560cd2002-04-12 03:10:20 +0000967PyObject_Free(void *p)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000968{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 poolp pool;
970 block *lastfree;
971 poolp next, prev;
972 uint size;
Antoine Pitroub7fb2e22011-01-07 21:43:59 +0000973#ifndef Py_USING_MEMORY_DEBUGGER
974 uint arenaindex_temp;
975#endif
Neil Schemenauera35c6882001-02-27 04:45:05 +0000976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000977 if (p == NULL) /* free(NULL) has no effect */
978 return;
Neil Schemenauera35c6882001-02-27 04:45:05 +0000979
Benjamin Peterson05159c42009-12-03 03:01:27 +0000980#ifdef WITH_VALGRIND
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000981 if (UNLIKELY(running_on_valgrind > 0))
982 goto redirect;
Benjamin Peterson05159c42009-12-03 03:01:27 +0000983#endif
984
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000985 pool = POOL_ADDR(p);
986 if (Py_ADDRESS_IN_RANGE(p, pool)) {
987 /* We allocated this address. */
988 LOCK();
989 /* Link p to the start of the pool's freeblock list. Since
990 * the pool had at least the p block outstanding, the pool
991 * wasn't empty (so it's already in a usedpools[] list, or
992 * was full and is in no list -- it's not in the freeblocks
993 * list in any case).
994 */
995 assert(pool->ref.count > 0); /* else it was empty */
996 *(block **)p = lastfree = pool->freeblock;
997 pool->freeblock = (block *)p;
998 if (lastfree) {
999 struct arena_object* ao;
1000 uint nf; /* ao->nfreepools */
Thomas Woutersa9773292006-04-21 09:43:23 +00001001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 /* freeblock wasn't NULL, so the pool wasn't full,
1003 * and the pool is in a usedpools[] list.
1004 */
1005 if (--pool->ref.count != 0) {
1006 /* pool isn't empty: leave it in usedpools */
1007 UNLOCK();
1008 return;
1009 }
1010 /* Pool is now empty: unlink from usedpools, and
1011 * link to the front of freepools. This ensures that
1012 * previously freed pools will be allocated later
1013 * (being not referenced, they are perhaps paged out).
1014 */
1015 next = pool->nextpool;
1016 prev = pool->prevpool;
1017 next->prevpool = prev;
1018 prev->nextpool = next;
Thomas Woutersa9773292006-04-21 09:43:23 +00001019
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 /* Link the pool to freepools. This is a singly-linked
1021 * list, and pool->prevpool isn't used there.
1022 */
1023 ao = &arenas[pool->arenaindex];
1024 pool->nextpool = ao->freepools;
1025 ao->freepools = pool;
1026 nf = ++ao->nfreepools;
Thomas Woutersa9773292006-04-21 09:43:23 +00001027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 /* All the rest is arena management. We just freed
1029 * a pool, and there are 4 cases for arena mgmt:
1030 * 1. If all the pools are free, return the arena to
1031 * the system free().
1032 * 2. If this is the only free pool in the arena,
1033 * add the arena back to the `usable_arenas` list.
1034 * 3. If the "next" arena has a smaller count of free
1035 * pools, we have to "slide this arena right" to
1036 * restore that usable_arenas is sorted in order of
1037 * nfreepools.
1038 * 4. Else there's nothing more to do.
1039 */
1040 if (nf == ao->ntotalpools) {
1041 /* Case 1. First unlink ao from usable_arenas.
1042 */
1043 assert(ao->prevarena == NULL ||
1044 ao->prevarena->address != 0);
1045 assert(ao ->nextarena == NULL ||
1046 ao->nextarena->address != 0);
Thomas Woutersa9773292006-04-21 09:43:23 +00001047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 /* Fix the pointer in the prevarena, or the
1049 * usable_arenas pointer.
1050 */
1051 if (ao->prevarena == NULL) {
1052 usable_arenas = ao->nextarena;
1053 assert(usable_arenas == NULL ||
1054 usable_arenas->address != 0);
1055 }
1056 else {
1057 assert(ao->prevarena->nextarena == ao);
1058 ao->prevarena->nextarena =
1059 ao->nextarena;
1060 }
1061 /* Fix the pointer in the nextarena. */
1062 if (ao->nextarena != NULL) {
1063 assert(ao->nextarena->prevarena == ao);
1064 ao->nextarena->prevarena =
1065 ao->prevarena;
1066 }
1067 /* Record that this arena_object slot is
1068 * available to be reused.
1069 */
1070 ao->nextarena = unused_arena_objects;
1071 unused_arena_objects = ao;
Thomas Woutersa9773292006-04-21 09:43:23 +00001072
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 /* Free the entire arena. */
1074 free((void *)ao->address);
1075 ao->address = 0; /* mark unassociated */
1076 --narenas_currently_allocated;
Thomas Woutersa9773292006-04-21 09:43:23 +00001077
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 UNLOCK();
1079 return;
1080 }
1081 if (nf == 1) {
1082 /* Case 2. Put ao at the head of
1083 * usable_arenas. Note that because
1084 * ao->nfreepools was 0 before, ao isn't
1085 * currently on the usable_arenas list.
1086 */
1087 ao->nextarena = usable_arenas;
1088 ao->prevarena = NULL;
1089 if (usable_arenas)
1090 usable_arenas->prevarena = ao;
1091 usable_arenas = ao;
1092 assert(usable_arenas->address != 0);
Thomas Woutersa9773292006-04-21 09:43:23 +00001093
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001094 UNLOCK();
1095 return;
1096 }
1097 /* If this arena is now out of order, we need to keep
1098 * the list sorted. The list is kept sorted so that
1099 * the "most full" arenas are used first, which allows
1100 * the nearly empty arenas to be completely freed. In
1101 * a few un-scientific tests, it seems like this
1102 * approach allowed a lot more memory to be freed.
1103 */
1104 if (ao->nextarena == NULL ||
1105 nf <= ao->nextarena->nfreepools) {
1106 /* Case 4. Nothing to do. */
1107 UNLOCK();
1108 return;
1109 }
1110 /* Case 3: We have to move the arena towards the end
1111 * of the list, because it has more free pools than
1112 * the arena to its right.
1113 * First unlink ao from usable_arenas.
1114 */
1115 if (ao->prevarena != NULL) {
1116 /* ao isn't at the head of the list */
1117 assert(ao->prevarena->nextarena == ao);
1118 ao->prevarena->nextarena = ao->nextarena;
1119 }
1120 else {
1121 /* ao is at the head of the list */
1122 assert(usable_arenas == ao);
1123 usable_arenas = ao->nextarena;
1124 }
1125 ao->nextarena->prevarena = ao->prevarena;
Thomas Woutersa9773292006-04-21 09:43:23 +00001126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001127 /* Locate the new insertion point by iterating over
1128 * the list, using our nextarena pointer.
1129 */
1130 while (ao->nextarena != NULL &&
1131 nf > ao->nextarena->nfreepools) {
1132 ao->prevarena = ao->nextarena;
1133 ao->nextarena = ao->nextarena->nextarena;
1134 }
Thomas Woutersa9773292006-04-21 09:43:23 +00001135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136 /* Insert ao at this point. */
1137 assert(ao->nextarena == NULL ||
1138 ao->prevarena == ao->nextarena->prevarena);
1139 assert(ao->prevarena->nextarena == ao->nextarena);
Thomas Woutersa9773292006-04-21 09:43:23 +00001140
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001141 ao->prevarena->nextarena = ao;
1142 if (ao->nextarena != NULL)
1143 ao->nextarena->prevarena = ao;
Thomas Woutersa9773292006-04-21 09:43:23 +00001144
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001145 /* Verify that the swaps worked. */
1146 assert(ao->nextarena == NULL ||
1147 nf <= ao->nextarena->nfreepools);
1148 assert(ao->prevarena == NULL ||
1149 nf > ao->prevarena->nfreepools);
1150 assert(ao->nextarena == NULL ||
1151 ao->nextarena->prevarena == ao);
1152 assert((usable_arenas == ao &&
1153 ao->prevarena == NULL) ||
1154 ao->prevarena->nextarena == ao);
Thomas Woutersa9773292006-04-21 09:43:23 +00001155
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001156 UNLOCK();
1157 return;
1158 }
1159 /* Pool was full, so doesn't currently live in any list:
1160 * link it to the front of the appropriate usedpools[] list.
1161 * This mimics LRU pool usage for new allocations and
1162 * targets optimal filling when several pools contain
1163 * blocks of the same size class.
1164 */
1165 --pool->ref.count;
1166 assert(pool->ref.count > 0); /* else the pool is empty */
1167 size = pool->szidx;
1168 next = usedpools[size + size];
1169 prev = next->prevpool;
1170 /* insert pool before next: prev <-> pool <-> next */
1171 pool->nextpool = next;
1172 pool->prevpool = prev;
1173 next->prevpool = pool;
1174 prev->nextpool = pool;
1175 UNLOCK();
1176 return;
1177 }
Neil Schemenauera35c6882001-02-27 04:45:05 +00001178
Benjamin Peterson05159c42009-12-03 03:01:27 +00001179#ifdef WITH_VALGRIND
1180redirect:
1181#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 /* We didn't allocate this address. */
1183 free(p);
Neil Schemenauera35c6882001-02-27 04:45:05 +00001184}
1185
Tim Peters84c1b972002-04-04 04:44:32 +00001186/* realloc. If p is NULL, this acts like malloc(nbytes). Else if nbytes==0,
1187 * then as the Python docs promise, we do not treat this like free(p), and
1188 * return a non-NULL result.
1189 */
Neil Schemenauera35c6882001-02-27 04:45:05 +00001190
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00001191#undef PyObject_Realloc
Neil Schemenauera35c6882001-02-27 04:45:05 +00001192void *
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00001193PyObject_Realloc(void *p, size_t nbytes)
Neil Schemenauera35c6882001-02-27 04:45:05 +00001194{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195 void *bp;
1196 poolp pool;
1197 size_t size;
Antoine Pitroub7fb2e22011-01-07 21:43:59 +00001198#ifndef Py_USING_MEMORY_DEBUGGER
1199 uint arenaindex_temp;
1200#endif
Neil Schemenauera35c6882001-02-27 04:45:05 +00001201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001202 if (p == NULL)
1203 return PyObject_Malloc(nbytes);
Neil Schemenauera35c6882001-02-27 04:45:05 +00001204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001205 /*
1206 * Limit ourselves to PY_SSIZE_T_MAX bytes to prevent security holes.
1207 * Most python internals blindly use a signed Py_ssize_t to track
1208 * things without checking for overflows or negatives.
1209 * As size_t is unsigned, checking for nbytes < 0 is not required.
1210 */
1211 if (nbytes > PY_SSIZE_T_MAX)
1212 return NULL;
Georg Brandld492ad82008-07-23 16:13:07 +00001213
Benjamin Peterson05159c42009-12-03 03:01:27 +00001214#ifdef WITH_VALGRIND
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001215 /* Treat running_on_valgrind == -1 the same as 0 */
1216 if (UNLIKELY(running_on_valgrind > 0))
1217 goto redirect;
Benjamin Peterson05159c42009-12-03 03:01:27 +00001218#endif
1219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001220 pool = POOL_ADDR(p);
1221 if (Py_ADDRESS_IN_RANGE(p, pool)) {
1222 /* We're in charge of this block */
1223 size = INDEX2SIZE(pool->szidx);
1224 if (nbytes <= size) {
1225 /* The block is staying the same or shrinking. If
1226 * it's shrinking, there's a tradeoff: it costs
1227 * cycles to copy the block to a smaller size class,
1228 * but it wastes memory not to copy it. The
1229 * compromise here is to copy on shrink only if at
1230 * least 25% of size can be shaved off.
1231 */
1232 if (4 * nbytes > 3 * size) {
1233 /* It's the same,
1234 * or shrinking and new/old > 3/4.
1235 */
1236 return p;
1237 }
1238 size = nbytes;
1239 }
1240 bp = PyObject_Malloc(nbytes);
1241 if (bp != NULL) {
1242 memcpy(bp, p, size);
1243 PyObject_Free(p);
1244 }
1245 return bp;
1246 }
Benjamin Peterson05159c42009-12-03 03:01:27 +00001247#ifdef WITH_VALGRIND
1248 redirect:
1249#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001250 /* We're not managing this block. If nbytes <=
1251 * SMALL_REQUEST_THRESHOLD, it's tempting to try to take over this
1252 * block. However, if we do, we need to copy the valid data from
1253 * the C-managed block to one of our blocks, and there's no portable
1254 * way to know how much of the memory space starting at p is valid.
1255 * As bug 1185883 pointed out the hard way, it's possible that the
1256 * C-managed block is "at the end" of allocated VM space, so that
1257 * a memory fault can occur if we try to copy nbytes bytes starting
1258 * at p. Instead we punt: let C continue to manage this block.
1259 */
1260 if (nbytes)
1261 return realloc(p, nbytes);
1262 /* C doesn't define the result of realloc(p, 0) (it may or may not
1263 * return NULL then), but Python's docs promise that nbytes==0 never
1264 * returns NULL. We don't pass 0 to realloc(), to avoid that endcase
1265 * to begin with. Even then, we can't be sure that realloc() won't
1266 * return NULL.
1267 */
1268 bp = realloc(p, 1);
1269 return bp ? bp : p;
Neil Schemenauera35c6882001-02-27 04:45:05 +00001270}
1271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272#else /* ! WITH_PYMALLOC */
Tim Petersddea2082002-03-23 10:03:50 +00001273
1274/*==========================================================================*/
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00001275/* pymalloc not enabled: Redirect the entry points to malloc. These will
1276 * only be used by extensions that are compiled with pymalloc enabled. */
Tim Peters62c06ba2002-03-23 22:28:18 +00001277
Tim Petersce7fb9b2002-03-23 00:28:57 +00001278void *
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00001279PyObject_Malloc(size_t n)
Tim Peters1221c0a2002-03-23 00:20:15 +00001280{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001281 return PyMem_MALLOC(n);
Tim Peters1221c0a2002-03-23 00:20:15 +00001282}
1283
Tim Petersce7fb9b2002-03-23 00:28:57 +00001284void *
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00001285PyObject_Realloc(void *p, size_t n)
Tim Peters1221c0a2002-03-23 00:20:15 +00001286{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001287 return PyMem_REALLOC(p, n);
Tim Peters1221c0a2002-03-23 00:20:15 +00001288}
1289
1290void
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00001291PyObject_Free(void *p)
Tim Peters1221c0a2002-03-23 00:20:15 +00001292{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001293 PyMem_FREE(p);
Tim Peters1221c0a2002-03-23 00:20:15 +00001294}
1295#endif /* WITH_PYMALLOC */
1296
Tim Petersddea2082002-03-23 10:03:50 +00001297#ifdef PYMALLOC_DEBUG
1298/*==========================================================================*/
Tim Peters62c06ba2002-03-23 22:28:18 +00001299/* A x-platform debugging allocator. This doesn't manage memory directly,
1300 * it wraps a real allocator, adding extra debugging info to the memory blocks.
1301 */
Tim Petersddea2082002-03-23 10:03:50 +00001302
Tim Petersf6fb5012002-04-12 07:38:53 +00001303/* Special bytes broadcast into debug memory blocks at appropriate times.
1304 * Strings of these are unlikely to be valid addresses, floats, ints or
1305 * 7-bit ASCII.
1306 */
1307#undef CLEANBYTE
1308#undef DEADBYTE
1309#undef FORBIDDENBYTE
1310#define CLEANBYTE 0xCB /* clean (newly allocated) memory */
Tim Peters889f61d2002-07-10 19:29:49 +00001311#define DEADBYTE 0xDB /* dead (newly freed) memory */
Tim Petersf6fb5012002-04-12 07:38:53 +00001312#define FORBIDDENBYTE 0xFB /* untouchable bytes at each end of a block */
Tim Petersddea2082002-03-23 10:03:50 +00001313
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00001314/* We tag each block with an API ID in order to tag API violations */
1315#define _PYMALLOC_MEM_ID 'm' /* the PyMem_Malloc() API */
1316#define _PYMALLOC_OBJ_ID 'o' /* The PyObject_Malloc() API */
1317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001318static size_t serialno = 0; /* incremented on each debug {m,re}alloc */
Tim Petersddea2082002-03-23 10:03:50 +00001319
Tim Peterse0850172002-03-24 00:34:21 +00001320/* serialno is always incremented via calling this routine. The point is
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001321 * to supply a single place to set a breakpoint.
1322 */
Tim Peterse0850172002-03-24 00:34:21 +00001323static void
Neil Schemenauerbd02b142002-03-28 21:05:38 +00001324bumpserialno(void)
Tim Peterse0850172002-03-24 00:34:21 +00001325{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001326 ++serialno;
Tim Peterse0850172002-03-24 00:34:21 +00001327}
1328
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001329#define SST SIZEOF_SIZE_T
Tim Peterse0850172002-03-24 00:34:21 +00001330
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001331/* Read sizeof(size_t) bytes at p as a big-endian size_t. */
1332static size_t
1333read_size_t(const void *p)
Tim Petersddea2082002-03-23 10:03:50 +00001334{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001335 const uchar *q = (const uchar *)p;
1336 size_t result = *q++;
1337 int i;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001339 for (i = SST; --i > 0; ++q)
1340 result = (result << 8) | *q;
1341 return result;
Tim Petersddea2082002-03-23 10:03:50 +00001342}
1343
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001344/* Write n as a big-endian size_t, MSB at address p, LSB at
1345 * p + sizeof(size_t) - 1.
1346 */
Tim Petersddea2082002-03-23 10:03:50 +00001347static void
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001348write_size_t(void *p, size_t n)
Tim Petersddea2082002-03-23 10:03:50 +00001349{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001350 uchar *q = (uchar *)p + SST - 1;
1351 int i;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001353 for (i = SST; --i >= 0; --q) {
1354 *q = (uchar)(n & 0xff);
1355 n >>= 8;
1356 }
Tim Petersddea2082002-03-23 10:03:50 +00001357}
1358
Tim Peters08d82152002-04-18 22:25:03 +00001359#ifdef Py_DEBUG
1360/* Is target in the list? The list is traversed via the nextpool pointers.
1361 * The list may be NULL-terminated, or circular. Return 1 if target is in
1362 * list, else 0.
1363 */
1364static int
1365pool_is_in_list(const poolp target, poolp list)
1366{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001367 poolp origlist = list;
1368 assert(target != NULL);
1369 if (list == NULL)
1370 return 0;
1371 do {
1372 if (target == list)
1373 return 1;
1374 list = list->nextpool;
1375 } while (list != NULL && list != origlist);
1376 return 0;
Tim Peters08d82152002-04-18 22:25:03 +00001377}
1378
1379#else
1380#define pool_is_in_list(X, Y) 1
1381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001382#endif /* Py_DEBUG */
Tim Peters08d82152002-04-18 22:25:03 +00001383
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001384/* Let S = sizeof(size_t). The debug malloc asks for 4*S extra bytes and
1385 fills them with useful stuff, here calling the underlying malloc's result p:
Tim Petersddea2082002-03-23 10:03:50 +00001386
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001387p[0: S]
1388 Number of bytes originally asked for. This is a size_t, big-endian (easier
1389 to read in a memory dump).
1390p[S: 2*S]
Tim Petersf6fb5012002-04-12 07:38:53 +00001391 Copies of FORBIDDENBYTE. Used to catch under- writes and reads.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001392p[2*S: 2*S+n]
Tim Petersf6fb5012002-04-12 07:38:53 +00001393 The requested memory, filled with copies of CLEANBYTE.
Tim Petersddea2082002-03-23 10:03:50 +00001394 Used to catch reference to uninitialized memory.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001395 &p[2*S] is returned. Note that this is 8-byte aligned if pymalloc
Tim Petersddea2082002-03-23 10:03:50 +00001396 handled the request itself.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001397p[2*S+n: 2*S+n+S]
Tim Petersf6fb5012002-04-12 07:38:53 +00001398 Copies of FORBIDDENBYTE. Used to catch over- writes and reads.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001399p[2*S+n+S: 2*S+n+2*S]
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00001400 A serial number, incremented by 1 on each call to _PyObject_DebugMalloc
1401 and _PyObject_DebugRealloc.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001402 This is a big-endian size_t.
Tim Petersddea2082002-03-23 10:03:50 +00001403 If "bad memory" is detected later, the serial number gives an
1404 excellent way to set a breakpoint on the next run, to capture the
1405 instant at which this block was passed out.
1406*/
1407
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00001408/* debug replacements for the PyMem_* memory API */
1409void *
1410_PyMem_DebugMalloc(size_t nbytes)
1411{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001412 return _PyObject_DebugMallocApi(_PYMALLOC_MEM_ID, nbytes);
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00001413}
1414void *
1415_PyMem_DebugRealloc(void *p, size_t nbytes)
1416{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001417 return _PyObject_DebugReallocApi(_PYMALLOC_MEM_ID, p, nbytes);
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00001418}
1419void
1420_PyMem_DebugFree(void *p)
1421{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001422 _PyObject_DebugFreeApi(_PYMALLOC_MEM_ID, p);
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00001423}
1424
1425/* debug replacements for the PyObject_* memory API */
Tim Petersddea2082002-03-23 10:03:50 +00001426void *
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00001427_PyObject_DebugMalloc(size_t nbytes)
Tim Petersddea2082002-03-23 10:03:50 +00001428{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001429 return _PyObject_DebugMallocApi(_PYMALLOC_OBJ_ID, nbytes);
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00001430}
1431void *
1432_PyObject_DebugRealloc(void *p, size_t nbytes)
1433{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001434 return _PyObject_DebugReallocApi(_PYMALLOC_OBJ_ID, p, nbytes);
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00001435}
1436void
1437_PyObject_DebugFree(void *p)
1438{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001439 _PyObject_DebugFreeApi(_PYMALLOC_OBJ_ID, p);
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00001440}
1441void
Kristján Valur Jónsson34369002009-09-28 15:57:53 +00001442_PyObject_DebugCheckAddress(const void *p)
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00001443{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001444 _PyObject_DebugCheckAddressApi(_PYMALLOC_OBJ_ID, p);
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00001445}
1446
1447
1448/* generic debug memory api, with an "id" to identify the API in use */
1449void *
1450_PyObject_DebugMallocApi(char id, size_t nbytes)
1451{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001452 uchar *p; /* base address of malloc'ed block */
1453 uchar *tail; /* p + 2*SST + nbytes == pointer to tail pad bytes */
1454 size_t total; /* nbytes + 4*SST */
Tim Petersddea2082002-03-23 10:03:50 +00001455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001456 bumpserialno();
1457 total = nbytes + 4*SST;
1458 if (total < nbytes)
1459 /* overflow: can't represent total as a size_t */
1460 return NULL;
Tim Petersddea2082002-03-23 10:03:50 +00001461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001462 p = (uchar *)PyObject_Malloc(total);
1463 if (p == NULL)
1464 return NULL;
Tim Petersddea2082002-03-23 10:03:50 +00001465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001466 /* at p, write size (SST bytes), id (1 byte), pad (SST-1 bytes) */
1467 write_size_t(p, nbytes);
1468 p[SST] = (uchar)id;
1469 memset(p + SST + 1 , FORBIDDENBYTE, SST-1);
Tim Petersddea2082002-03-23 10:03:50 +00001470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001471 if (nbytes > 0)
1472 memset(p + 2*SST, CLEANBYTE, nbytes);
Tim Petersddea2082002-03-23 10:03:50 +00001473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001474 /* at tail, write pad (SST bytes) and serialno (SST bytes) */
1475 tail = p + 2*SST + nbytes;
1476 memset(tail, FORBIDDENBYTE, SST);
1477 write_size_t(tail + SST, serialno);
Tim Petersddea2082002-03-23 10:03:50 +00001478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001479 return p + 2*SST;
Tim Petersddea2082002-03-23 10:03:50 +00001480}
1481
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001482/* 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 +00001483 particular, that the FORBIDDENBYTEs with the api ID are still intact).
Tim Petersf6fb5012002-04-12 07:38:53 +00001484 Then fills the original bytes with DEADBYTE.
Tim Petersddea2082002-03-23 10:03:50 +00001485 Then calls the underlying free.
1486*/
1487void
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00001488_PyObject_DebugFreeApi(char api, void *p)
Tim Petersddea2082002-03-23 10:03:50 +00001489{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001490 uchar *q = (uchar *)p - 2*SST; /* address returned from malloc */
1491 size_t nbytes;
Tim Petersddea2082002-03-23 10:03:50 +00001492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001493 if (p == NULL)
1494 return;
1495 _PyObject_DebugCheckAddressApi(api, p);
1496 nbytes = read_size_t(q);
1497 nbytes += 4*SST;
1498 if (nbytes > 0)
1499 memset(q, DEADBYTE, nbytes);
1500 PyObject_Free(q);
Tim Petersddea2082002-03-23 10:03:50 +00001501}
1502
1503void *
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00001504_PyObject_DebugReallocApi(char api, void *p, size_t nbytes)
Tim Petersddea2082002-03-23 10:03:50 +00001505{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001506 uchar *q = (uchar *)p;
1507 uchar *tail;
1508 size_t total; /* nbytes + 4*SST */
1509 size_t original_nbytes;
1510 int i;
Tim Petersddea2082002-03-23 10:03:50 +00001511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001512 if (p == NULL)
1513 return _PyObject_DebugMallocApi(api, nbytes);
Tim Petersddea2082002-03-23 10:03:50 +00001514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001515 _PyObject_DebugCheckAddressApi(api, p);
1516 bumpserialno();
1517 original_nbytes = read_size_t(q - 2*SST);
1518 total = nbytes + 4*SST;
1519 if (total < nbytes)
1520 /* overflow: can't represent total as a size_t */
1521 return NULL;
Tim Petersddea2082002-03-23 10:03:50 +00001522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001523 if (nbytes < original_nbytes) {
1524 /* shrinking: mark old extra memory dead */
1525 memset(q + nbytes, DEADBYTE, original_nbytes - nbytes + 2*SST);
1526 }
Tim Petersddea2082002-03-23 10:03:50 +00001527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001528 /* Resize and add decorations. We may get a new pointer here, in which
1529 * case we didn't get the chance to mark the old memory with DEADBYTE,
1530 * but we live with that.
1531 */
1532 q = (uchar *)PyObject_Realloc(q - 2*SST, total);
1533 if (q == NULL)
1534 return NULL;
Tim Peters85cc1c42002-04-12 08:52:50 +00001535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001536 write_size_t(q, nbytes);
1537 assert(q[SST] == (uchar)api);
1538 for (i = 1; i < SST; ++i)
1539 assert(q[SST + i] == FORBIDDENBYTE);
1540 q += 2*SST;
1541 tail = q + nbytes;
1542 memset(tail, FORBIDDENBYTE, SST);
1543 write_size_t(tail + SST, serialno);
Tim Peters85cc1c42002-04-12 08:52:50 +00001544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001545 if (nbytes > original_nbytes) {
1546 /* growing: mark new extra memory clean */
1547 memset(q + original_nbytes, CLEANBYTE,
Stefan Krah735bb122010-11-26 10:54:09 +00001548 nbytes - original_nbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001549 }
Tim Peters85cc1c42002-04-12 08:52:50 +00001550
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001551 return q;
Tim Petersddea2082002-03-23 10:03:50 +00001552}
1553
Tim Peters7ccfadf2002-04-01 06:04:21 +00001554/* Check the forbidden bytes on both ends of the memory allocated for p.
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00001555 * If anything is wrong, print info to stderr via _PyObject_DebugDumpAddress,
Tim Peters7ccfadf2002-04-01 06:04:21 +00001556 * and call Py_FatalError to kill the program.
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00001557 * The API id, is also checked.
Tim Peters7ccfadf2002-04-01 06:04:21 +00001558 */
1559 void
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00001560_PyObject_DebugCheckAddressApi(char api, const void *p)
Tim Petersddea2082002-03-23 10:03:50 +00001561{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001562 const uchar *q = (const uchar *)p;
1563 char msgbuf[64];
1564 char *msg;
1565 size_t nbytes;
1566 const uchar *tail;
1567 int i;
1568 char id;
Tim Petersddea2082002-03-23 10:03:50 +00001569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001570 if (p == NULL) {
1571 msg = "didn't expect a NULL pointer";
1572 goto error;
1573 }
Tim Petersddea2082002-03-23 10:03:50 +00001574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001575 /* Check the API id */
1576 id = (char)q[-SST];
1577 if (id != api) {
1578 msg = msgbuf;
1579 snprintf(msg, sizeof(msgbuf), "bad ID: Allocated using API '%c', verified using API '%c'", id, api);
1580 msgbuf[sizeof(msgbuf)-1] = 0;
1581 goto error;
1582 }
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00001583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001584 /* Check the stuff at the start of p first: if there's underwrite
1585 * corruption, the number-of-bytes field may be nuts, and checking
1586 * the tail could lead to a segfault then.
1587 */
1588 for (i = SST-1; i >= 1; --i) {
1589 if (*(q-i) != FORBIDDENBYTE) {
1590 msg = "bad leading pad byte";
1591 goto error;
1592 }
1593 }
Tim Petersddea2082002-03-23 10:03:50 +00001594
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001595 nbytes = read_size_t(q - 2*SST);
1596 tail = q + nbytes;
1597 for (i = 0; i < SST; ++i) {
1598 if (tail[i] != FORBIDDENBYTE) {
1599 msg = "bad trailing pad byte";
1600 goto error;
1601 }
1602 }
Tim Petersddea2082002-03-23 10:03:50 +00001603
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001604 return;
Tim Petersd1139e02002-03-28 07:32:11 +00001605
1606error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001607 _PyObject_DebugDumpAddress(p);
1608 Py_FatalError(msg);
Tim Petersddea2082002-03-23 10:03:50 +00001609}
1610
Tim Peters7ccfadf2002-04-01 06:04:21 +00001611/* Display info to stderr about the memory block at p. */
Tim Petersddea2082002-03-23 10:03:50 +00001612void
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00001613_PyObject_DebugDumpAddress(const void *p)
Tim Petersddea2082002-03-23 10:03:50 +00001614{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001615 const uchar *q = (const uchar *)p;
1616 const uchar *tail;
1617 size_t nbytes, serial;
1618 int i;
1619 int ok;
1620 char id;
Tim Petersddea2082002-03-23 10:03:50 +00001621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001622 fprintf(stderr, "Debug memory block at address p=%p:", p);
1623 if (p == NULL) {
1624 fprintf(stderr, "\n");
1625 return;
1626 }
1627 id = (char)q[-SST];
1628 fprintf(stderr, " API '%c'\n", id);
Tim Petersddea2082002-03-23 10:03:50 +00001629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001630 nbytes = read_size_t(q - 2*SST);
1631 fprintf(stderr, " %" PY_FORMAT_SIZE_T "u bytes originally "
1632 "requested\n", nbytes);
Tim Petersddea2082002-03-23 10:03:50 +00001633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001634 /* In case this is nuts, check the leading pad bytes first. */
1635 fprintf(stderr, " The %d pad bytes at p-%d are ", SST-1, SST-1);
1636 ok = 1;
1637 for (i = 1; i <= SST-1; ++i) {
1638 if (*(q-i) != FORBIDDENBYTE) {
1639 ok = 0;
1640 break;
1641 }
1642 }
1643 if (ok)
1644 fputs("FORBIDDENBYTE, as expected.\n", stderr);
1645 else {
1646 fprintf(stderr, "not all FORBIDDENBYTE (0x%02x):\n",
1647 FORBIDDENBYTE);
1648 for (i = SST-1; i >= 1; --i) {
1649 const uchar byte = *(q-i);
1650 fprintf(stderr, " at p-%d: 0x%02x", i, byte);
1651 if (byte != FORBIDDENBYTE)
1652 fputs(" *** OUCH", stderr);
1653 fputc('\n', stderr);
1654 }
Tim Peters449b5a82002-04-28 06:14:45 +00001655
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001656 fputs(" Because memory is corrupted at the start, the "
1657 "count of bytes requested\n"
1658 " may be bogus, and checking the trailing pad "
1659 "bytes may segfault.\n", stderr);
1660 }
Tim Petersddea2082002-03-23 10:03:50 +00001661
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001662 tail = q + nbytes;
1663 fprintf(stderr, " The %d pad bytes at tail=%p are ", SST, tail);
1664 ok = 1;
1665 for (i = 0; i < SST; ++i) {
1666 if (tail[i] != FORBIDDENBYTE) {
1667 ok = 0;
1668 break;
1669 }
1670 }
1671 if (ok)
1672 fputs("FORBIDDENBYTE, as expected.\n", stderr);
1673 else {
1674 fprintf(stderr, "not all FORBIDDENBYTE (0x%02x):\n",
Stefan Krah735bb122010-11-26 10:54:09 +00001675 FORBIDDENBYTE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001676 for (i = 0; i < SST; ++i) {
1677 const uchar byte = tail[i];
1678 fprintf(stderr, " at tail+%d: 0x%02x",
Stefan Krah735bb122010-11-26 10:54:09 +00001679 i, byte);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001680 if (byte != FORBIDDENBYTE)
1681 fputs(" *** OUCH", stderr);
1682 fputc('\n', stderr);
1683 }
1684 }
Tim Petersddea2082002-03-23 10:03:50 +00001685
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001686 serial = read_size_t(tail + SST);
1687 fprintf(stderr, " The block was made by call #%" PY_FORMAT_SIZE_T
1688 "u to debug malloc/realloc.\n", serial);
Tim Petersddea2082002-03-23 10:03:50 +00001689
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001690 if (nbytes > 0) {
1691 i = 0;
1692 fputs(" Data at p:", stderr);
1693 /* print up to 8 bytes at the start */
1694 while (q < tail && i < 8) {
1695 fprintf(stderr, " %02x", *q);
1696 ++i;
1697 ++q;
1698 }
1699 /* and up to 8 at the end */
1700 if (q < tail) {
1701 if (tail - q > 8) {
1702 fputs(" ...", stderr);
1703 q = tail - 8;
1704 }
1705 while (q < tail) {
1706 fprintf(stderr, " %02x", *q);
1707 ++q;
1708 }
1709 }
1710 fputc('\n', stderr);
1711 }
Tim Petersddea2082002-03-23 10:03:50 +00001712}
1713
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001714static size_t
1715printone(const char* msg, size_t value)
Tim Peters16bcb6b2002-04-05 05:45:31 +00001716{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001717 int i, k;
1718 char buf[100];
1719 size_t origvalue = value;
Tim Peters16bcb6b2002-04-05 05:45:31 +00001720
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001721 fputs(msg, stderr);
1722 for (i = (int)strlen(msg); i < 35; ++i)
1723 fputc(' ', stderr);
1724 fputc('=', stderr);
Tim Peters49f26812002-04-06 01:45:35 +00001725
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001726 /* Write the value with commas. */
1727 i = 22;
1728 buf[i--] = '\0';
1729 buf[i--] = '\n';
1730 k = 3;
1731 do {
1732 size_t nextvalue = value / 10;
1733 uint digit = (uint)(value - nextvalue * 10);
1734 value = nextvalue;
1735 buf[i--] = (char)(digit + '0');
1736 --k;
1737 if (k == 0 && value && i >= 0) {
1738 k = 3;
1739 buf[i--] = ',';
1740 }
1741 } while (value && i >= 0);
Tim Peters49f26812002-04-06 01:45:35 +00001742
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001743 while (i >= 0)
1744 buf[i--] = ' ';
1745 fputs(buf, stderr);
Tim Peters49f26812002-04-06 01:45:35 +00001746
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001747 return origvalue;
Tim Peters16bcb6b2002-04-05 05:45:31 +00001748}
1749
Tim Peters08d82152002-04-18 22:25:03 +00001750/* Print summary info to stderr about the state of pymalloc's structures.
1751 * In Py_DEBUG mode, also perform some expensive internal consistency
1752 * checks.
1753 */
Tim Peters7ccfadf2002-04-01 06:04:21 +00001754void
Tim Peters0e871182002-04-13 08:29:14 +00001755_PyObject_DebugMallocStats(void)
Tim Peters7ccfadf2002-04-01 06:04:21 +00001756{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001757 uint i;
1758 const uint numclasses = SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT;
1759 /* # of pools, allocated blocks, and free blocks per class index */
1760 size_t numpools[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT];
1761 size_t numblocks[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT];
1762 size_t numfreeblocks[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT];
1763 /* total # of allocated bytes in used and full pools */
1764 size_t allocated_bytes = 0;
1765 /* total # of available bytes in used pools */
1766 size_t available_bytes = 0;
1767 /* # of free pools + pools not yet carved out of current arena */
1768 uint numfreepools = 0;
1769 /* # of bytes for arena alignment padding */
1770 size_t arena_alignment = 0;
1771 /* # of bytes in used and full pools used for pool_headers */
1772 size_t pool_header_bytes = 0;
1773 /* # of bytes in used and full pools wasted due to quantization,
1774 * i.e. the necessarily leftover space at the ends of used and
1775 * full pools.
1776 */
1777 size_t quantization = 0;
1778 /* # of arenas actually allocated. */
1779 size_t narenas = 0;
1780 /* running total -- should equal narenas * ARENA_SIZE */
1781 size_t total;
1782 char buf[128];
Tim Peters7ccfadf2002-04-01 06:04:21 +00001783
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001784 fprintf(stderr, "Small block threshold = %d, in %u size classes.\n",
Stefan Krah735bb122010-11-26 10:54:09 +00001785 SMALL_REQUEST_THRESHOLD, numclasses);
Tim Peters7ccfadf2002-04-01 06:04:21 +00001786
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001787 for (i = 0; i < numclasses; ++i)
1788 numpools[i] = numblocks[i] = numfreeblocks[i] = 0;
Tim Peters7ccfadf2002-04-01 06:04:21 +00001789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001790 /* Because full pools aren't linked to from anything, it's easiest
1791 * to march over all the arenas. If we're lucky, most of the memory
1792 * will be living in full pools -- would be a shame to miss them.
1793 */
1794 for (i = 0; i < maxarenas; ++i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001795 uint j;
1796 uptr base = arenas[i].address;
Thomas Woutersa9773292006-04-21 09:43:23 +00001797
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001798 /* Skip arenas which are not allocated. */
1799 if (arenas[i].address == (uptr)NULL)
1800 continue;
1801 narenas += 1;
Thomas Woutersa9773292006-04-21 09:43:23 +00001802
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001803 numfreepools += arenas[i].nfreepools;
Tim Peters7ccfadf2002-04-01 06:04:21 +00001804
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001805 /* round up to pool alignment */
1806 if (base & (uptr)POOL_SIZE_MASK) {
1807 arena_alignment += POOL_SIZE;
1808 base &= ~(uptr)POOL_SIZE_MASK;
1809 base += POOL_SIZE;
1810 }
Tim Peters7ccfadf2002-04-01 06:04:21 +00001811
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001812 /* visit every pool in the arena */
1813 assert(base <= (uptr) arenas[i].pool_address);
1814 for (j = 0;
1815 base < (uptr) arenas[i].pool_address;
1816 ++j, base += POOL_SIZE) {
1817 poolp p = (poolp)base;
1818 const uint sz = p->szidx;
1819 uint freeblocks;
Tim Peters08d82152002-04-18 22:25:03 +00001820
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001821 if (p->ref.count == 0) {
1822 /* currently unused */
1823 assert(pool_is_in_list(p, arenas[i].freepools));
1824 continue;
1825 }
1826 ++numpools[sz];
1827 numblocks[sz] += p->ref.count;
1828 freeblocks = NUMBLOCKS(sz) - p->ref.count;
1829 numfreeblocks[sz] += freeblocks;
Tim Peters08d82152002-04-18 22:25:03 +00001830#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001831 if (freeblocks > 0)
1832 assert(pool_is_in_list(p, usedpools[sz + sz]));
Tim Peters08d82152002-04-18 22:25:03 +00001833#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001834 }
1835 }
1836 assert(narenas == narenas_currently_allocated);
Tim Peters7ccfadf2002-04-01 06:04:21 +00001837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001838 fputc('\n', stderr);
1839 fputs("class size num pools blocks in use avail blocks\n"
1840 "----- ---- --------- ------------- ------------\n",
Stefan Krah735bb122010-11-26 10:54:09 +00001841 stderr);
Tim Peters7ccfadf2002-04-01 06:04:21 +00001842
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001843 for (i = 0; i < numclasses; ++i) {
1844 size_t p = numpools[i];
1845 size_t b = numblocks[i];
1846 size_t f = numfreeblocks[i];
1847 uint size = INDEX2SIZE(i);
1848 if (p == 0) {
1849 assert(b == 0 && f == 0);
1850 continue;
1851 }
1852 fprintf(stderr, "%5u %6u "
1853 "%11" PY_FORMAT_SIZE_T "u "
1854 "%15" PY_FORMAT_SIZE_T "u "
1855 "%13" PY_FORMAT_SIZE_T "u\n",
Stefan Krah735bb122010-11-26 10:54:09 +00001856 i, size, p, b, f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001857 allocated_bytes += b * size;
1858 available_bytes += f * size;
1859 pool_header_bytes += p * POOL_OVERHEAD;
1860 quantization += p * ((POOL_SIZE - POOL_OVERHEAD) % size);
1861 }
1862 fputc('\n', stderr);
1863 (void)printone("# times object malloc called", serialno);
Tim Peters16bcb6b2002-04-05 05:45:31 +00001864
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001865 (void)printone("# arenas allocated total", ntimes_arena_allocated);
1866 (void)printone("# arenas reclaimed", ntimes_arena_allocated - narenas);
1867 (void)printone("# arenas highwater mark", narenas_highwater);
1868 (void)printone("# arenas allocated current", narenas);
Thomas Woutersa9773292006-04-21 09:43:23 +00001869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001870 PyOS_snprintf(buf, sizeof(buf),
1871 "%" PY_FORMAT_SIZE_T "u arenas * %d bytes/arena",
1872 narenas, ARENA_SIZE);
1873 (void)printone(buf, narenas * ARENA_SIZE);
Tim Peters16bcb6b2002-04-05 05:45:31 +00001874
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001875 fputc('\n', stderr);
Tim Peters16bcb6b2002-04-05 05:45:31 +00001876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001877 total = printone("# bytes in allocated blocks", allocated_bytes);
1878 total += printone("# bytes in available blocks", available_bytes);
Tim Peters49f26812002-04-06 01:45:35 +00001879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001880 PyOS_snprintf(buf, sizeof(buf),
1881 "%u unused pools * %d bytes", numfreepools, POOL_SIZE);
1882 total += printone(buf, (size_t)numfreepools * POOL_SIZE);
Tim Peters16bcb6b2002-04-05 05:45:31 +00001883
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001884 total += printone("# bytes lost to pool headers", pool_header_bytes);
1885 total += printone("# bytes lost to quantization", quantization);
1886 total += printone("# bytes lost to arena alignment", arena_alignment);
1887 (void)printone("Total", total);
Tim Peters7ccfadf2002-04-01 06:04:21 +00001888}
1889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001890#endif /* PYMALLOC_DEBUG */
Neal Norwitz7eb3c912004-06-06 19:20:22 +00001891
1892#ifdef Py_USING_MEMORY_DEBUGGER
Thomas Woutersa9773292006-04-21 09:43:23 +00001893/* Make this function last so gcc won't inline it since the definition is
1894 * after the reference.
1895 */
Neal Norwitz7eb3c912004-06-06 19:20:22 +00001896int
1897Py_ADDRESS_IN_RANGE(void *P, poolp pool)
1898{
Antoine Pitroub7fb2e22011-01-07 21:43:59 +00001899 uint arenaindex_temp = pool->arenaindex;
1900
1901 return arenaindex_temp < maxarenas &&
1902 (uptr)P - arenas[arenaindex_temp].address < (uptr)ARENA_SIZE &&
1903 arenas[arenaindex_temp].address != 0;
Neal Norwitz7eb3c912004-06-06 19:20:22 +00001904}
1905#endif