blob: 3fac6d4bceed56ef376897580246b7854f09c5a7 [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
Martin v. Löwiscd83fa82013-06-27 12:23:29 +020012#ifdef MS_WINDOWS
13#include <windows.h>
14#endif
15
Benjamin Peterson05159c42009-12-03 03:01:27 +000016#ifdef WITH_VALGRIND
17#include <valgrind/valgrind.h>
18
19/* If we're using GCC, use __builtin_expect() to reduce overhead of
20 the valgrind checks */
21#if defined(__GNUC__) && (__GNUC__ > 2) && defined(__OPTIMIZE__)
22# define UNLIKELY(value) __builtin_expect((value), 0)
23#else
24# define UNLIKELY(value) (value)
25#endif
26
27/* -1 indicates that we haven't checked that we're running on valgrind yet. */
28static int running_on_valgrind = -1;
29#endif
30
Neil Schemenauera35c6882001-02-27 04:45:05 +000031/* An object allocator for Python.
32
33 Here is an introduction to the layers of the Python memory architecture,
34 showing where the object allocator is actually used (layer +2), It is
35 called for every object allocation and deallocation (PyObject_New/Del),
36 unless the object-specific allocators implement a proprietary allocation
37 scheme (ex.: ints use a simple free list). This is also the place where
38 the cyclic garbage collector operates selectively on container objects.
39
40
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000041 Object-specific allocators
Neil Schemenauera35c6882001-02-27 04:45:05 +000042 _____ ______ ______ ________
43 [ int ] [ dict ] [ list ] ... [ string ] Python core |
44+3 | <----- Object-specific memory -----> | <-- Non-object memory --> |
45 _______________________________ | |
46 [ Python's object allocator ] | |
47+2 | ####### Object memory ####### | <------ Internal buffers ------> |
48 ______________________________________________________________ |
49 [ Python's raw memory allocator (PyMem_ API) ] |
50+1 | <----- Python memory (under PyMem manager's control) ------> | |
51 __________________________________________________________________
52 [ Underlying general-purpose allocator (ex: C library malloc) ]
53 0 | <------ Virtual memory allocated for the python process -------> |
54
55 =========================================================================
56 _______________________________________________________________________
57 [ OS-specific Virtual Memory Manager (VMM) ]
58-1 | <--- Kernel dynamic storage allocation & management (page-based) ---> |
59 __________________________________ __________________________________
60 [ ] [ ]
61-2 | <-- Physical memory: ROM/RAM --> | | <-- Secondary storage (swap) --> |
62
63*/
64/*==========================================================================*/
65
66/* A fast, special-purpose memory allocator for small blocks, to be used
67 on top of a general-purpose malloc -- heavily based on previous art. */
68
69/* Vladimir Marangozov -- August 2000 */
70
71/*
72 * "Memory management is where the rubber meets the road -- if we do the wrong
73 * thing at any level, the results will not be good. And if we don't make the
74 * levels work well together, we are in serious trouble." (1)
75 *
76 * (1) Paul R. Wilson, Mark S. Johnstone, Michael Neely, and David Boles,
77 * "Dynamic Storage Allocation: A Survey and Critical Review",
78 * in Proc. 1995 Int'l. Workshop on Memory Management, September 1995.
79 */
80
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000081/* #undef WITH_MEMORY_LIMITS */ /* disable mem limit checks */
Neil Schemenauera35c6882001-02-27 04:45:05 +000082
83/*==========================================================================*/
84
85/*
Neil Schemenauera35c6882001-02-27 04:45:05 +000086 * Allocation strategy abstract:
87 *
88 * For small requests, the allocator sub-allocates <Big> blocks of memory.
Antoine Pitrou6f26be02011-05-03 18:18:59 +020089 * Requests greater than SMALL_REQUEST_THRESHOLD bytes are routed to the
90 * system's allocator.
Tim Petersce7fb9b2002-03-23 00:28:57 +000091 *
Neil Schemenauera35c6882001-02-27 04:45:05 +000092 * Small requests are grouped in size classes spaced 8 bytes apart, due
93 * to the required valid alignment of the returned address. Requests of
94 * a particular size are serviced from memory pools of 4K (one VMM page).
95 * Pools are fragmented on demand and contain free lists of blocks of one
96 * particular size class. In other words, there is a fixed-size allocator
97 * for each size class. Free pools are shared by the different allocators
98 * thus minimizing the space reserved for a particular size class.
99 *
100 * This allocation strategy is a variant of what is known as "simple
101 * segregated storage based on array of free lists". The main drawback of
102 * simple segregated storage is that we might end up with lot of reserved
103 * memory for the different free lists, which degenerate in time. To avoid
104 * this, we partition each free list in pools and we share dynamically the
105 * reserved space between all free lists. This technique is quite efficient
106 * for memory intensive programs which allocate mainly small-sized blocks.
107 *
108 * For small requests we have the following table:
109 *
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000110 * Request in bytes Size of allocated block Size class idx
Neil Schemenauera35c6882001-02-27 04:45:05 +0000111 * ----------------------------------------------------------------
112 * 1-8 8 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000113 * 9-16 16 1
114 * 17-24 24 2
115 * 25-32 32 3
116 * 33-40 40 4
117 * 41-48 48 5
118 * 49-56 56 6
119 * 57-64 64 7
120 * 65-72 72 8
121 * ... ... ...
Antoine Pitrou6f26be02011-05-03 18:18:59 +0200122 * 497-504 504 62
123 * 505-512 512 63
Tim Petersce7fb9b2002-03-23 00:28:57 +0000124 *
Antoine Pitrou6f26be02011-05-03 18:18:59 +0200125 * 0, SMALL_REQUEST_THRESHOLD + 1 and up: routed to the underlying
126 * allocator.
Neil Schemenauera35c6882001-02-27 04:45:05 +0000127 */
128
129/*==========================================================================*/
130
131/*
132 * -- Main tunable settings section --
133 */
134
135/*
136 * Alignment of addresses returned to the user. 8-bytes alignment works
137 * on most current architectures (with 32-bit or 64-bit address busses).
138 * The alignment value is also used for grouping small requests in size
139 * classes spaced ALIGNMENT bytes apart.
140 *
141 * You shouldn't change this unless you know what you are doing.
142 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000143#define ALIGNMENT 8 /* must be 2^N */
144#define ALIGNMENT_SHIFT 3
Neil Schemenauera35c6882001-02-27 04:45:05 +0000145
Tim Peterse70ddf32002-04-05 04:32:29 +0000146/* Return the number of bytes in size class I, as a uint. */
147#define INDEX2SIZE(I) (((uint)(I) + 1) << ALIGNMENT_SHIFT)
148
Neil Schemenauera35c6882001-02-27 04:45:05 +0000149/*
150 * Max size threshold below which malloc requests are considered to be
151 * small enough in order to use preallocated memory pools. You can tune
152 * this value according to your application behaviour and memory needs.
153 *
Antoine Pitrou6f26be02011-05-03 18:18:59 +0200154 * Note: a size threshold of 512 guarantees that newly created dictionaries
155 * will be allocated from preallocated memory pools on 64-bit.
156 *
Neil Schemenauera35c6882001-02-27 04:45:05 +0000157 * The following invariants must hold:
Antoine Pitrou6f26be02011-05-03 18:18:59 +0200158 * 1) ALIGNMENT <= SMALL_REQUEST_THRESHOLD <= 512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000159 * 2) SMALL_REQUEST_THRESHOLD is evenly divisible by ALIGNMENT
Neil Schemenauera35c6882001-02-27 04:45:05 +0000160 *
161 * Although not required, for better performance and space efficiency,
162 * it is recommended that SMALL_REQUEST_THRESHOLD is set to a power of 2.
163 */
Antoine Pitrou6f26be02011-05-03 18:18:59 +0200164#define SMALL_REQUEST_THRESHOLD 512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000165#define NB_SMALL_SIZE_CLASSES (SMALL_REQUEST_THRESHOLD / ALIGNMENT)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000166
167/*
168 * The system's VMM page size can be obtained on most unices with a
169 * getpagesize() call or deduced from various header files. To make
170 * things simpler, we assume that it is 4K, which is OK for most systems.
171 * It is probably better if this is the native page size, but it doesn't
Tim Petersecc6e6a2005-07-10 22:30:55 +0000172 * have to be. In theory, if SYSTEM_PAGE_SIZE is larger than the native page
173 * size, then `POOL_ADDR(p)->arenaindex' could rarely cause a segmentation
174 * violation fault. 4K is apparently OK for all the platforms that python
Martin v. Löwis8c140282002-10-26 15:01:53 +0000175 * currently targets.
Neil Schemenauera35c6882001-02-27 04:45:05 +0000176 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000177#define SYSTEM_PAGE_SIZE (4 * 1024)
178#define SYSTEM_PAGE_SIZE_MASK (SYSTEM_PAGE_SIZE - 1)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000179
180/*
181 * Maximum amount of memory managed by the allocator for small requests.
182 */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000183#ifdef WITH_MEMORY_LIMITS
184#ifndef SMALL_MEMORY_LIMIT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000185#define SMALL_MEMORY_LIMIT (64 * 1024 * 1024) /* 64 MB -- more? */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000186#endif
187#endif
188
189/*
190 * The allocator sub-allocates <Big> blocks of memory (called arenas) aligned
191 * on a page boundary. This is a reserved virtual address space for the
Antoine Pitrouf0effe62011-11-26 01:11:02 +0100192 * current process (obtained through a malloc()/mmap() call). In no way this
193 * means that the memory arenas will be used entirely. A malloc(<Big>) is
194 * usually an address range reservation for <Big> bytes, unless all pages within
195 * this space are referenced subsequently. So malloc'ing big blocks and not
196 * using them does not mean "wasting memory". It's an addressable range
197 * wastage...
Neil Schemenauera35c6882001-02-27 04:45:05 +0000198 *
Antoine Pitrouf0effe62011-11-26 01:11:02 +0100199 * Arenas are allocated with mmap() on systems supporting anonymous memory
200 * mappings to reduce heap fragmentation.
Neil Schemenauera35c6882001-02-27 04:45:05 +0000201 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000202#define ARENA_SIZE (256 << 10) /* 256KB */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000203
204#ifdef WITH_MEMORY_LIMITS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000205#define MAX_ARENAS (SMALL_MEMORY_LIMIT / ARENA_SIZE)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000206#endif
207
208/*
209 * Size of the pools used for small blocks. Should be a power of 2,
Tim Petersc2ce91a2002-03-30 21:36:04 +0000210 * between 1K and SYSTEM_PAGE_SIZE, that is: 1k, 2k, 4k.
Neil Schemenauera35c6882001-02-27 04:45:05 +0000211 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000212#define POOL_SIZE SYSTEM_PAGE_SIZE /* must be 2^N */
213#define POOL_SIZE_MASK SYSTEM_PAGE_SIZE_MASK
Neil Schemenauera35c6882001-02-27 04:45:05 +0000214
215/*
216 * -- End of tunable settings section --
217 */
218
219/*==========================================================================*/
220
221/*
222 * Locking
223 *
224 * To reduce lock contention, it would probably be better to refine the
225 * crude function locking with per size class locking. I'm not positive
226 * however, whether it's worth switching to such locking policy because
227 * of the performance penalty it might introduce.
228 *
229 * The following macros describe the simplest (should also be the fastest)
230 * lock object on a particular platform and the init/fini/lock/unlock
231 * operations on it. The locks defined here are not expected to be recursive
232 * because it is assumed that they will always be called in the order:
233 * INIT, [LOCK, UNLOCK]*, FINI.
234 */
235
236/*
237 * Python's threads are serialized, so object malloc locking is disabled.
238 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000239#define SIMPLELOCK_DECL(lock) /* simple lock declaration */
240#define SIMPLELOCK_INIT(lock) /* allocate (if needed) and initialize */
241#define SIMPLELOCK_FINI(lock) /* free/destroy an existing lock */
242#define SIMPLELOCK_LOCK(lock) /* acquire released lock */
243#define SIMPLELOCK_UNLOCK(lock) /* release acquired lock */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000244
245/*
246 * Basic types
247 * I don't care if these are defined in <sys/types.h> or elsewhere. Axiom.
248 */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000249#undef uchar
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000250#define uchar unsigned char /* assuming == 8 bits */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000251
Neil Schemenauera35c6882001-02-27 04:45:05 +0000252#undef uint
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000253#define uint unsigned int /* assuming >= 16 bits */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000254
255#undef ulong
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000256#define ulong unsigned long /* assuming >= 32 bits */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000257
Tim Petersd97a1c02002-03-30 06:09:22 +0000258#undef uptr
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000259#define uptr Py_uintptr_t
Tim Petersd97a1c02002-03-30 06:09:22 +0000260
Neil Schemenauera35c6882001-02-27 04:45:05 +0000261/* When you say memory, my mind reasons in terms of (pointers to) blocks */
262typedef uchar block;
263
Tim Peterse70ddf32002-04-05 04:32:29 +0000264/* Pool for small blocks. */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000265struct pool_header {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000266 union { block *_padding;
Stefan Krah735bb122010-11-26 10:54:09 +0000267 uint count; } ref; /* number of allocated blocks */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000268 block *freeblock; /* pool's free list head */
269 struct pool_header *nextpool; /* next pool of this size class */
270 struct pool_header *prevpool; /* previous pool "" */
271 uint arenaindex; /* index into arenas of base adr */
272 uint szidx; /* block size class index */
273 uint nextoffset; /* bytes to virgin block */
274 uint maxnextoffset; /* largest valid nextoffset */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000275};
276
277typedef struct pool_header *poolp;
278
Thomas Woutersa9773292006-04-21 09:43:23 +0000279/* Record keeping for arenas. */
280struct arena_object {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000281 /* The address of the arena, as returned by malloc. Note that 0
282 * will never be returned by a successful malloc, and is used
283 * here to mark an arena_object that doesn't correspond to an
284 * allocated arena.
285 */
286 uptr address;
Thomas Woutersa9773292006-04-21 09:43:23 +0000287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000288 /* Pool-aligned pointer to the next pool to be carved off. */
289 block* pool_address;
Thomas Woutersa9773292006-04-21 09:43:23 +0000290
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000291 /* The number of available pools in the arena: free pools + never-
292 * allocated pools.
293 */
294 uint nfreepools;
Thomas Woutersa9773292006-04-21 09:43:23 +0000295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000296 /* The total number of pools in the arena, whether or not available. */
297 uint ntotalpools;
Thomas Woutersa9773292006-04-21 09:43:23 +0000298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000299 /* Singly-linked list of available pools. */
300 struct pool_header* freepools;
Thomas Woutersa9773292006-04-21 09:43:23 +0000301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000302 /* Whenever this arena_object is not associated with an allocated
303 * arena, the nextarena member is used to link all unassociated
304 * arena_objects in the singly-linked `unused_arena_objects` list.
305 * The prevarena member is unused in this case.
306 *
307 * When this arena_object is associated with an allocated arena
308 * with at least one available pool, both members are used in the
309 * doubly-linked `usable_arenas` list, which is maintained in
310 * increasing order of `nfreepools` values.
311 *
312 * Else this arena_object is associated with an allocated arena
313 * all of whose pools are in use. `nextarena` and `prevarena`
314 * are both meaningless in this case.
315 */
316 struct arena_object* nextarena;
317 struct arena_object* prevarena;
Thomas Woutersa9773292006-04-21 09:43:23 +0000318};
319
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +0200320#define POOL_OVERHEAD _Py_SIZE_ROUND_UP(sizeof(struct pool_header), ALIGNMENT)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000322#define DUMMY_SIZE_IDX 0xffff /* size class of newly cached pools */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000323
Tim Petersd97a1c02002-03-30 06:09:22 +0000324/* Round pointer P down to the closest pool-aligned address <= P, as a poolp */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +0200325#define POOL_ADDR(P) ((poolp)_Py_ALIGN_DOWN((P), POOL_SIZE))
Tim Peterse70ddf32002-04-05 04:32:29 +0000326
Tim Peters16bcb6b2002-04-05 05:45:31 +0000327/* Return total number of blocks in pool of size index I, as a uint. */
328#define NUMBLOCKS(I) ((uint)(POOL_SIZE - POOL_OVERHEAD) / INDEX2SIZE(I))
Tim Petersd97a1c02002-03-30 06:09:22 +0000329
Neil Schemenauera35c6882001-02-27 04:45:05 +0000330/*==========================================================================*/
331
332/*
333 * This malloc lock
334 */
Jeremy Hyltond1fedb62002-07-18 18:49:52 +0000335SIMPLELOCK_DECL(_malloc_lock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000336#define LOCK() SIMPLELOCK_LOCK(_malloc_lock)
337#define UNLOCK() SIMPLELOCK_UNLOCK(_malloc_lock)
338#define LOCK_INIT() SIMPLELOCK_INIT(_malloc_lock)
339#define LOCK_FINI() SIMPLELOCK_FINI(_malloc_lock)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000340
341/*
Tim Peters1e16db62002-03-31 01:05:22 +0000342 * Pool table -- headed, circular, doubly-linked lists of partially used pools.
343
344This is involved. For an index i, usedpools[i+i] is the header for a list of
345all partially used pools holding small blocks with "size class idx" i. So
346usedpools[0] corresponds to blocks of size 8, usedpools[2] to blocks of size
34716, and so on: index 2*i <-> blocks of size (i+1)<<ALIGNMENT_SHIFT.
348
Thomas Woutersa9773292006-04-21 09:43:23 +0000349Pools are carved off an arena's highwater mark (an arena_object's pool_address
350member) as needed. Once carved off, a pool is in one of three states forever
351after:
Tim Peters1e16db62002-03-31 01:05:22 +0000352
Tim Peters338e0102002-04-01 19:23:44 +0000353used == partially used, neither empty nor full
354 At least one block in the pool is currently allocated, and at least one
355 block in the pool is not currently allocated (note this implies a pool
356 has room for at least two blocks).
357 This is a pool's initial state, as a pool is created only when malloc
358 needs space.
359 The pool holds blocks of a fixed size, and is in the circular list headed
360 at usedpools[i] (see above). It's linked to the other used pools of the
361 same size class via the pool_header's nextpool and prevpool members.
362 If all but one block is currently allocated, a malloc can cause a
363 transition to the full state. If all but one block is not currently
364 allocated, a free can cause a transition to the empty state.
Tim Peters1e16db62002-03-31 01:05:22 +0000365
Tim Peters338e0102002-04-01 19:23:44 +0000366full == all the pool's blocks are currently allocated
367 On transition to full, a pool is unlinked from its usedpools[] list.
368 It's not linked to from anything then anymore, and its nextpool and
369 prevpool members are meaningless until it transitions back to used.
370 A free of a block in a full pool puts the pool back in the used state.
371 Then it's linked in at the front of the appropriate usedpools[] list, so
372 that the next allocation for its size class will reuse the freed block.
373
374empty == all the pool's blocks are currently available for allocation
375 On transition to empty, a pool is unlinked from its usedpools[] list,
Thomas Woutersa9773292006-04-21 09:43:23 +0000376 and linked to the front of its arena_object's singly-linked freepools list,
Tim Peters338e0102002-04-01 19:23:44 +0000377 via its nextpool member. The prevpool member has no meaning in this case.
378 Empty pools have no inherent size class: the next time a malloc finds
379 an empty list in usedpools[], it takes the first pool off of freepools.
380 If the size class needed happens to be the same as the size class the pool
Tim Peterse70ddf32002-04-05 04:32:29 +0000381 last had, some pool initialization can be skipped.
Tim Peters338e0102002-04-01 19:23:44 +0000382
383
384Block Management
385
386Blocks within pools are again carved out as needed. pool->freeblock points to
387the start of a singly-linked list of free blocks within the pool. When a
388block is freed, it's inserted at the front of its pool's freeblock list. Note
389that the available blocks in a pool are *not* linked all together when a pool
Tim Peterse70ddf32002-04-05 04:32:29 +0000390is initialized. Instead only "the first two" (lowest addresses) blocks are
391set up, returning the first such block, and setting pool->freeblock to a
392one-block list holding the second such block. This is consistent with that
393pymalloc strives at all levels (arena, pool, and block) never to touch a piece
394of memory until it's actually needed.
395
396So long as a pool is in the used state, we're certain there *is* a block
Tim Peters52aefc82002-04-11 06:36:45 +0000397available for allocating, and pool->freeblock is not NULL. If pool->freeblock
398points to the end of the free list before we've carved the entire pool into
399blocks, that means we simply haven't yet gotten to one of the higher-address
400blocks. The offset from the pool_header to the start of "the next" virgin
401block is stored in the pool_header nextoffset member, and the largest value
402of nextoffset that makes sense is stored in the maxnextoffset member when a
403pool is initialized. All the blocks in a pool have been passed out at least
404once when and only when nextoffset > maxnextoffset.
Tim Peters338e0102002-04-01 19:23:44 +0000405
Tim Peters1e16db62002-03-31 01:05:22 +0000406
407Major obscurity: While the usedpools vector is declared to have poolp
408entries, it doesn't really. It really contains two pointers per (conceptual)
409poolp entry, the nextpool and prevpool members of a pool_header. The
410excruciating initialization code below fools C so that
411
412 usedpool[i+i]
413
414"acts like" a genuine poolp, but only so long as you only reference its
415nextpool and prevpool members. The "- 2*sizeof(block *)" gibberish is
416compensating for that a pool_header's nextpool and prevpool members
417immediately follow a pool_header's first two members:
418
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000419 union { block *_padding;
Stefan Krah735bb122010-11-26 10:54:09 +0000420 uint count; } ref;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 block *freeblock;
Tim Peters1e16db62002-03-31 01:05:22 +0000422
423each of which consume sizeof(block *) bytes. So what usedpools[i+i] really
424contains is a fudged-up pointer p such that *if* C believes it's a poolp
425pointer, then p->nextpool and p->prevpool are both p (meaning that the headed
426circular list is empty).
427
428It's unclear why the usedpools setup is so convoluted. It could be to
429minimize the amount of cache required to hold this heavily-referenced table
430(which only *needs* the two interpool pointer members of a pool_header). OTOH,
431referencing code has to remember to "double the index" and doing so isn't
432free, usedpools[0] isn't a strictly legal pointer, and we're crucially relying
433on that C doesn't insert any padding anywhere in a pool_header at or before
434the prevpool member.
435**************************************************************************** */
436
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000437#define PTA(x) ((poolp )((uchar *)&(usedpools[2*(x)]) - 2*sizeof(block *)))
438#define PT(x) PTA(x), PTA(x)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000439
440static poolp usedpools[2 * ((NB_SMALL_SIZE_CLASSES + 7) / 8) * 8] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000441 PT(0), PT(1), PT(2), PT(3), PT(4), PT(5), PT(6), PT(7)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000442#if NB_SMALL_SIZE_CLASSES > 8
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000443 , PT(8), PT(9), PT(10), PT(11), PT(12), PT(13), PT(14), PT(15)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000444#if NB_SMALL_SIZE_CLASSES > 16
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000445 , PT(16), PT(17), PT(18), PT(19), PT(20), PT(21), PT(22), PT(23)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000446#if NB_SMALL_SIZE_CLASSES > 24
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000447 , PT(24), PT(25), PT(26), PT(27), PT(28), PT(29), PT(30), PT(31)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000448#if NB_SMALL_SIZE_CLASSES > 32
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000449 , PT(32), PT(33), PT(34), PT(35), PT(36), PT(37), PT(38), PT(39)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000450#if NB_SMALL_SIZE_CLASSES > 40
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000451 , PT(40), PT(41), PT(42), PT(43), PT(44), PT(45), PT(46), PT(47)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000452#if NB_SMALL_SIZE_CLASSES > 48
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000453 , PT(48), PT(49), PT(50), PT(51), PT(52), PT(53), PT(54), PT(55)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000454#if NB_SMALL_SIZE_CLASSES > 56
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000455 , PT(56), PT(57), PT(58), PT(59), PT(60), PT(61), PT(62), PT(63)
Antoine Pitrou6f26be02011-05-03 18:18:59 +0200456#if NB_SMALL_SIZE_CLASSES > 64
457#error "NB_SMALL_SIZE_CLASSES should be less than 64"
458#endif /* NB_SMALL_SIZE_CLASSES > 64 */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000459#endif /* NB_SMALL_SIZE_CLASSES > 56 */
460#endif /* NB_SMALL_SIZE_CLASSES > 48 */
461#endif /* NB_SMALL_SIZE_CLASSES > 40 */
462#endif /* NB_SMALL_SIZE_CLASSES > 32 */
463#endif /* NB_SMALL_SIZE_CLASSES > 24 */
464#endif /* NB_SMALL_SIZE_CLASSES > 16 */
465#endif /* NB_SMALL_SIZE_CLASSES > 8 */
466};
467
Thomas Woutersa9773292006-04-21 09:43:23 +0000468/*==========================================================================
469Arena management.
Neil Schemenauera35c6882001-02-27 04:45:05 +0000470
Thomas Woutersa9773292006-04-21 09:43:23 +0000471`arenas` is a vector of arena_objects. It contains maxarenas entries, some of
472which may not be currently used (== they're arena_objects that aren't
473currently associated with an allocated arena). Note that arenas proper are
474separately malloc'ed.
Neil Schemenauera35c6882001-02-27 04:45:05 +0000475
Thomas Woutersa9773292006-04-21 09:43:23 +0000476Prior to Python 2.5, arenas were never free()'ed. Starting with Python 2.5,
477we do try to free() arenas, and use some mild heuristic strategies to increase
478the likelihood that arenas eventually can be freed.
479
480unused_arena_objects
481
482 This is a singly-linked list of the arena_objects that are currently not
483 being used (no arena is associated with them). Objects are taken off the
484 head of the list in new_arena(), and are pushed on the head of the list in
485 PyObject_Free() when the arena is empty. Key invariant: an arena_object
486 is on this list if and only if its .address member is 0.
487
488usable_arenas
489
490 This is a doubly-linked list of the arena_objects associated with arenas
491 that have pools available. These pools are either waiting to be reused,
492 or have not been used before. The list is sorted to have the most-
493 allocated arenas first (ascending order based on the nfreepools member).
494 This means that the next allocation will come from a heavily used arena,
495 which gives the nearly empty arenas a chance to be returned to the system.
496 In my unscientific tests this dramatically improved the number of arenas
497 that could be freed.
498
499Note that an arena_object associated with an arena all of whose pools are
500currently in use isn't on either list.
501*/
502
503/* Array of objects used to track chunks of memory (arenas). */
504static struct arena_object* arenas = NULL;
505/* Number of slots currently allocated in the `arenas` vector. */
Tim Peters1d99af82002-03-30 10:35:09 +0000506static uint maxarenas = 0;
Tim Petersd97a1c02002-03-30 06:09:22 +0000507
Thomas Woutersa9773292006-04-21 09:43:23 +0000508/* The head of the singly-linked, NULL-terminated list of available
509 * arena_objects.
Tim Petersd97a1c02002-03-30 06:09:22 +0000510 */
Thomas Woutersa9773292006-04-21 09:43:23 +0000511static struct arena_object* unused_arena_objects = NULL;
512
513/* The head of the doubly-linked, NULL-terminated at each end, list of
514 * arena_objects associated with arenas that have pools available.
515 */
516static struct arena_object* usable_arenas = NULL;
517
518/* How many arena_objects do we initially allocate?
519 * 16 = can allocate 16 arenas = 16 * ARENA_SIZE = 4MB before growing the
520 * `arenas` vector.
521 */
522#define INITIAL_ARENA_OBJECTS 16
523
524/* Number of arenas allocated that haven't been free()'d. */
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000525static size_t narenas_currently_allocated = 0;
Thomas Woutersa9773292006-04-21 09:43:23 +0000526
Thomas Woutersa9773292006-04-21 09:43:23 +0000527/* 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
Antoine Pitrouf9d0b122012-12-09 14:28:26 +0100532static Py_ssize_t _Py_AllocatedBlocks = 0;
533
534Py_ssize_t
535_Py_GetAllocatedBlocks(void)
536{
537 return _Py_AllocatedBlocks;
538}
539
540
Thomas Woutersa9773292006-04-21 09:43:23 +0000541/* Allocate a new arena. If we run out of memory, return NULL. Else
542 * allocate a new arena, and return the address of an arena_object
543 * describing the new arena. It's expected that the caller will set
544 * `usable_arenas` to the return value.
545 */
546static struct arena_object*
Tim Petersd97a1c02002-03-30 06:09:22 +0000547new_arena(void)
548{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000549 struct arena_object* arenaobj;
550 uint excess; /* number of bytes above pool alignment */
Victor Stinnerba108822012-03-10 00:21:44 +0100551 void *address;
Victor Stinner36f01ad2013-06-15 03:37:01 +0200552 int err;
Tim Petersd97a1c02002-03-30 06:09:22 +0000553
Tim Peters0e871182002-04-13 08:29:14 +0000554#ifdef PYMALLOC_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 if (Py_GETENV("PYTHONMALLOCSTATS"))
David Malcolm49526f42012-06-22 14:55:41 -0400556 _PyObject_DebugMallocStats(stderr);
Tim Peters0e871182002-04-13 08:29:14 +0000557#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000558 if (unused_arena_objects == NULL) {
559 uint i;
560 uint numarenas;
561 size_t nbytes;
Tim Peters0e871182002-04-13 08:29:14 +0000562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563 /* Double the number of arena objects on each allocation.
564 * Note that it's possible for `numarenas` to overflow.
565 */
566 numarenas = maxarenas ? maxarenas << 1 : INITIAL_ARENA_OBJECTS;
567 if (numarenas <= maxarenas)
568 return NULL; /* overflow */
Martin v. Löwis5aca8822008-09-11 06:55:48 +0000569#if SIZEOF_SIZE_T <= SIZEOF_INT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000570 if (numarenas > PY_SIZE_MAX / sizeof(*arenas))
571 return NULL; /* overflow */
Martin v. Löwis5aca8822008-09-11 06:55:48 +0000572#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000573 nbytes = numarenas * sizeof(*arenas);
Victor Stinner36f01ad2013-06-15 03:37:01 +0200574 arenaobj = (struct arena_object *)realloc(arenas, nbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000575 if (arenaobj == NULL)
576 return NULL;
577 arenas = arenaobj;
Thomas Woutersa9773292006-04-21 09:43:23 +0000578
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000579 /* We might need to fix pointers that were copied. However,
580 * new_arena only gets called when all the pages in the
581 * previous arenas are full. Thus, there are *no* pointers
582 * into the old array. Thus, we don't have to worry about
583 * invalid pointers. Just to be sure, some asserts:
584 */
585 assert(usable_arenas == NULL);
586 assert(unused_arena_objects == NULL);
Thomas Woutersa9773292006-04-21 09:43:23 +0000587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000588 /* Put the new arenas on the unused_arena_objects list. */
589 for (i = maxarenas; i < numarenas; ++i) {
590 arenas[i].address = 0; /* mark as unassociated */
591 arenas[i].nextarena = i < numarenas - 1 ?
592 &arenas[i+1] : NULL;
593 }
Thomas Woutersa9773292006-04-21 09:43:23 +0000594
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 /* Update globals. */
596 unused_arena_objects = &arenas[maxarenas];
597 maxarenas = numarenas;
598 }
Tim Petersd97a1c02002-03-30 06:09:22 +0000599
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000600 /* Take the next available arena object off the head of the list. */
601 assert(unused_arena_objects != NULL);
602 arenaobj = unused_arena_objects;
603 unused_arena_objects = arenaobj->nextarena;
604 assert(arenaobj->address == 0);
Martin v. Löwiscd83fa82013-06-27 12:23:29 +0200605#ifdef MS_WINDOWS
606 address = (void*)VirtualAlloc(NULL, ARENA_SIZE,
607 MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
608 err = (address == NULL);
609#elif defined(ARENAS_USE_MMAP)
Victor Stinner36f01ad2013-06-15 03:37:01 +0200610 address = mmap(NULL, ARENA_SIZE, PROT_READ|PROT_WRITE,
611 MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
612 err = (address == MAP_FAILED);
613#else
614 address = malloc(ARENA_SIZE);
615 err = (address == 0);
616#endif
617 if (err) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000618 /* The allocation failed: return NULL after putting the
619 * arenaobj back.
620 */
621 arenaobj->nextarena = unused_arena_objects;
622 unused_arena_objects = arenaobj;
623 return NULL;
624 }
Victor Stinnerba108822012-03-10 00:21:44 +0100625 arenaobj->address = (uptr)address;
Tim Petersd97a1c02002-03-30 06:09:22 +0000626
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 ++narenas_currently_allocated;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000628 ++ntimes_arena_allocated;
629 if (narenas_currently_allocated > narenas_highwater)
630 narenas_highwater = narenas_currently_allocated;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000631 arenaobj->freepools = NULL;
632 /* pool_address <- first pool-aligned address in the arena
633 nfreepools <- number of whole pools that fit after alignment */
634 arenaobj->pool_address = (block*)arenaobj->address;
635 arenaobj->nfreepools = ARENA_SIZE / POOL_SIZE;
636 assert(POOL_SIZE * arenaobj->nfreepools == ARENA_SIZE);
637 excess = (uint)(arenaobj->address & POOL_SIZE_MASK);
638 if (excess != 0) {
639 --arenaobj->nfreepools;
640 arenaobj->pool_address += POOL_SIZE - excess;
641 }
642 arenaobj->ntotalpools = arenaobj->nfreepools;
Thomas Woutersa9773292006-04-21 09:43:23 +0000643
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 return arenaobj;
Tim Petersd97a1c02002-03-30 06:09:22 +0000645}
646
Thomas Woutersa9773292006-04-21 09:43:23 +0000647/*
648Py_ADDRESS_IN_RANGE(P, POOL)
649
650Return true if and only if P is an address that was allocated by pymalloc.
651POOL must be the pool address associated with P, i.e., POOL = POOL_ADDR(P)
652(the caller is asked to compute this because the macro expands POOL more than
653once, and for efficiency it's best for the caller to assign POOL_ADDR(P) to a
654variable and pass the latter to the macro; because Py_ADDRESS_IN_RANGE is
655called on every alloc/realloc/free, micro-efficiency is important here).
656
657Tricky: Let B be the arena base address associated with the pool, B =
658arenas[(POOL)->arenaindex].address. Then P belongs to the arena if and only if
659
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000660 B <= P < B + ARENA_SIZE
Thomas Woutersa9773292006-04-21 09:43:23 +0000661
662Subtracting B throughout, this is true iff
663
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000664 0 <= P-B < ARENA_SIZE
Thomas Woutersa9773292006-04-21 09:43:23 +0000665
666By using unsigned arithmetic, the "0 <=" half of the test can be skipped.
667
668Obscure: A PyMem "free memory" function can call the pymalloc free or realloc
669before the first arena has been allocated. `arenas` is still NULL in that
670case. We're relying on that maxarenas is also 0 in that case, so that
671(POOL)->arenaindex < maxarenas must be false, saving us from trying to index
672into a NULL arenas.
673
674Details: given P and POOL, the arena_object corresponding to P is AO =
675arenas[(POOL)->arenaindex]. Suppose obmalloc controls P. Then (barring wild
676stores, etc), POOL is the correct address of P's pool, AO.address is the
677correct base address of the pool's arena, and P must be within ARENA_SIZE of
678AO.address. In addition, AO.address is not 0 (no arena can start at address 0
679(NULL)). Therefore Py_ADDRESS_IN_RANGE correctly reports that obmalloc
680controls P.
681
682Now suppose obmalloc does not control P (e.g., P was obtained via a direct
683call to the system malloc() or realloc()). (POOL)->arenaindex may be anything
684in this case -- it may even be uninitialized trash. If the trash arenaindex
685is >= maxarenas, the macro correctly concludes at once that obmalloc doesn't
686control P.
687
688Else arenaindex is < maxarena, and AO is read up. If AO corresponds to an
689allocated arena, obmalloc controls all the memory in slice AO.address :
690AO.address+ARENA_SIZE. By case assumption, P is not controlled by obmalloc,
691so P doesn't lie in that slice, so the macro correctly reports that P is not
692controlled by obmalloc.
693
694Finally, if P is not controlled by obmalloc and AO corresponds to an unused
695arena_object (one not currently associated with an allocated arena),
696AO.address is 0, and the second test in the macro reduces to:
697
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000698 P < ARENA_SIZE
Thomas Woutersa9773292006-04-21 09:43:23 +0000699
700If P >= ARENA_SIZE (extremely likely), the macro again correctly concludes
701that P is not controlled by obmalloc. However, if P < ARENA_SIZE, this part
702of the test still passes, and the third clause (AO.address != 0) is necessary
703to get the correct result: AO.address is 0 in this case, so the macro
704correctly reports that P is not controlled by obmalloc (despite that P lies in
705slice AO.address : AO.address + ARENA_SIZE).
706
707Note: The third (AO.address != 0) clause was added in Python 2.5. Before
7082.5, arenas were never free()'ed, and an arenaindex < maxarena always
709corresponded to a currently-allocated arena, so the "P is not controlled by
710obmalloc, AO corresponds to an unused arena_object, and P < ARENA_SIZE" case
711was impossible.
712
713Note that the logic is excruciating, and reading up possibly uninitialized
714memory when P is not controlled by obmalloc (to get at (POOL)->arenaindex)
715creates problems for some memory debuggers. The overwhelming advantage is
716that this test determines whether an arbitrary address is controlled by
717obmalloc in a small constant time, independent of the number of arenas
718obmalloc controls. Since this test is needed at every entry point, it's
719extremely desirable that it be this fast.
Antoine Pitroub7fb2e22011-01-07 21:43:59 +0000720
721Since Py_ADDRESS_IN_RANGE may be reading from memory which was not allocated
722by Python, it is important that (POOL)->arenaindex is read only once, as
723another thread may be concurrently modifying the value without holding the
724GIL. To accomplish this, the arenaindex_temp variable is used to store
725(POOL)->arenaindex for the duration of the Py_ADDRESS_IN_RANGE macro's
726execution. The caller of the macro is responsible for declaring this
727variable.
Thomas Woutersa9773292006-04-21 09:43:23 +0000728*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000729#define Py_ADDRESS_IN_RANGE(P, POOL) \
Antoine Pitroub7fb2e22011-01-07 21:43:59 +0000730 ((arenaindex_temp = (POOL)->arenaindex) < maxarenas && \
731 (uptr)(P) - arenas[arenaindex_temp].address < (uptr)ARENA_SIZE && \
732 arenas[arenaindex_temp].address != 0)
Thomas Woutersa9773292006-04-21 09:43:23 +0000733
Neal Norwitz7eb3c912004-06-06 19:20:22 +0000734
735/* This is only useful when running memory debuggers such as
736 * Purify or Valgrind. Uncomment to use.
737 *
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000738#define Py_USING_MEMORY_DEBUGGER
Martin v. Löwis6fea2332008-09-25 04:15:27 +0000739 */
Neal Norwitz7eb3c912004-06-06 19:20:22 +0000740
741#ifdef Py_USING_MEMORY_DEBUGGER
742
743/* Py_ADDRESS_IN_RANGE may access uninitialized memory by design
744 * This leads to thousands of spurious warnings when using
745 * Purify or Valgrind. By making a function, we can easily
746 * suppress the uninitialized memory reads in this one function.
747 * So we won't ignore real errors elsewhere.
748 *
749 * Disable the macro and use a function.
750 */
751
752#undef Py_ADDRESS_IN_RANGE
753
Thomas Wouters89f507f2006-12-13 04:49:30 +0000754#if defined(__GNUC__) && ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 1) || \
Stefan Krah735bb122010-11-26 10:54:09 +0000755 (__GNUC__ >= 4))
Neal Norwitze5e5aa42005-11-13 18:55:39 +0000756#define Py_NO_INLINE __attribute__((__noinline__))
757#else
758#define Py_NO_INLINE
759#endif
760
761/* Don't make static, to try to ensure this isn't inlined. */
762int Py_ADDRESS_IN_RANGE(void *P, poolp pool) Py_NO_INLINE;
763#undef Py_NO_INLINE
Neal Norwitz7eb3c912004-06-06 19:20:22 +0000764#endif
Tim Peters338e0102002-04-01 19:23:44 +0000765
Neil Schemenauera35c6882001-02-27 04:45:05 +0000766/*==========================================================================*/
767
Tim Peters84c1b972002-04-04 04:44:32 +0000768/* malloc. Note that nbytes==0 tries to return a non-NULL pointer, distinct
769 * from all other currently live pointers. This may not be possible.
770 */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000771
772/*
773 * The basic blocks are ordered by decreasing execution frequency,
774 * which minimizes the number of jumps in the most common cases,
775 * improves branching prediction and instruction scheduling (small
776 * block allocations typically result in a couple of instructions).
777 * Unless the optimizer reorders everything, being too smart...
778 */
779
Victor Stinner36f01ad2013-06-15 03:37:01 +0200780#undef PyObject_Malloc
781void *
782PyObject_Malloc(size_t nbytes)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000783{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 block *bp;
785 poolp pool;
786 poolp next;
787 uint size;
Neil Schemenauera35c6882001-02-27 04:45:05 +0000788
Antoine Pitrou0aaaa622013-04-06 01:15:30 +0200789 _Py_AllocatedBlocks++;
790
Benjamin Peterson05159c42009-12-03 03:01:27 +0000791#ifdef WITH_VALGRIND
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000792 if (UNLIKELY(running_on_valgrind == -1))
793 running_on_valgrind = RUNNING_ON_VALGRIND;
794 if (UNLIKELY(running_on_valgrind))
795 goto redirect;
Benjamin Peterson05159c42009-12-03 03:01:27 +0000796#endif
797
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000798 /*
Victor Stinner36f01ad2013-06-15 03:37:01 +0200799 * Limit ourselves to PY_SSIZE_T_MAX bytes to prevent security holes.
800 * Most python internals blindly use a signed Py_ssize_t to track
801 * things without checking for overflows or negatives.
802 * As size_t is unsigned, checking for nbytes < 0 is not required.
803 */
804 if (nbytes > PY_SSIZE_T_MAX) {
805 _Py_AllocatedBlocks--;
806 return NULL;
807 }
808
809 /*
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000810 * This implicitly redirects malloc(0).
811 */
812 if ((nbytes - 1) < SMALL_REQUEST_THRESHOLD) {
813 LOCK();
814 /*
815 * Most frequent paths first
816 */
817 size = (uint)(nbytes - 1) >> ALIGNMENT_SHIFT;
818 pool = usedpools[size + size];
819 if (pool != pool->nextpool) {
820 /*
821 * There is a used pool for this size class.
822 * Pick up the head block of its free list.
823 */
824 ++pool->ref.count;
825 bp = pool->freeblock;
826 assert(bp != NULL);
827 if ((pool->freeblock = *(block **)bp) != NULL) {
828 UNLOCK();
829 return (void *)bp;
830 }
831 /*
832 * Reached the end of the free list, try to extend it.
833 */
834 if (pool->nextoffset <= pool->maxnextoffset) {
835 /* There is room for another block. */
836 pool->freeblock = (block*)pool +
837 pool->nextoffset;
838 pool->nextoffset += INDEX2SIZE(size);
839 *(block **)(pool->freeblock) = NULL;
840 UNLOCK();
841 return (void *)bp;
842 }
843 /* Pool is full, unlink from used pools. */
844 next = pool->nextpool;
845 pool = pool->prevpool;
846 next->prevpool = pool;
847 pool->nextpool = next;
848 UNLOCK();
849 return (void *)bp;
850 }
Thomas Woutersa9773292006-04-21 09:43:23 +0000851
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000852 /* There isn't a pool of the right size class immediately
853 * available: use a free pool.
854 */
855 if (usable_arenas == NULL) {
856 /* No arena has a free pool: allocate a new arena. */
Thomas Woutersa9773292006-04-21 09:43:23 +0000857#ifdef WITH_MEMORY_LIMITS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 if (narenas_currently_allocated >= MAX_ARENAS) {
859 UNLOCK();
860 goto redirect;
861 }
Thomas Woutersa9773292006-04-21 09:43:23 +0000862#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000863 usable_arenas = new_arena();
864 if (usable_arenas == NULL) {
865 UNLOCK();
866 goto redirect;
867 }
868 usable_arenas->nextarena =
869 usable_arenas->prevarena = NULL;
870 }
871 assert(usable_arenas->address != 0);
Thomas Woutersa9773292006-04-21 09:43:23 +0000872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000873 /* Try to get a cached free pool. */
874 pool = usable_arenas->freepools;
875 if (pool != NULL) {
876 /* Unlink from cached pools. */
877 usable_arenas->freepools = pool->nextpool;
Thomas Woutersa9773292006-04-21 09:43:23 +0000878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000879 /* This arena already had the smallest nfreepools
880 * value, so decreasing nfreepools doesn't change
881 * that, and we don't need to rearrange the
882 * usable_arenas list. However, if the arena has
883 * become wholly allocated, we need to remove its
884 * arena_object from usable_arenas.
885 */
886 --usable_arenas->nfreepools;
887 if (usable_arenas->nfreepools == 0) {
888 /* Wholly allocated: remove. */
889 assert(usable_arenas->freepools == NULL);
890 assert(usable_arenas->nextarena == NULL ||
891 usable_arenas->nextarena->prevarena ==
892 usable_arenas);
Thomas Woutersa9773292006-04-21 09:43:23 +0000893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 usable_arenas = usable_arenas->nextarena;
895 if (usable_arenas != NULL) {
896 usable_arenas->prevarena = NULL;
897 assert(usable_arenas->address != 0);
898 }
899 }
900 else {
901 /* nfreepools > 0: it must be that freepools
902 * isn't NULL, or that we haven't yet carved
903 * off all the arena's pools for the first
904 * time.
905 */
906 assert(usable_arenas->freepools != NULL ||
907 usable_arenas->pool_address <=
908 (block*)usable_arenas->address +
909 ARENA_SIZE - POOL_SIZE);
910 }
911 init_pool:
912 /* Frontlink to used pools. */
913 next = usedpools[size + size]; /* == prev */
914 pool->nextpool = next;
915 pool->prevpool = next;
916 next->nextpool = pool;
917 next->prevpool = pool;
918 pool->ref.count = 1;
919 if (pool->szidx == size) {
920 /* Luckily, this pool last contained blocks
921 * of the same size class, so its header
922 * and free list are already initialized.
923 */
924 bp = pool->freeblock;
Antoine Pitrouf9d0b122012-12-09 14:28:26 +0100925 assert(bp != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 pool->freeblock = *(block **)bp;
927 UNLOCK();
928 return (void *)bp;
929 }
930 /*
931 * Initialize the pool header, set up the free list to
932 * contain just the second block, and return the first
933 * block.
934 */
935 pool->szidx = size;
936 size = INDEX2SIZE(size);
937 bp = (block *)pool + POOL_OVERHEAD;
938 pool->nextoffset = POOL_OVERHEAD + (size << 1);
939 pool->maxnextoffset = POOL_SIZE - size;
940 pool->freeblock = bp + size;
941 *(block **)(pool->freeblock) = NULL;
942 UNLOCK();
943 return (void *)bp;
944 }
Thomas Woutersa9773292006-04-21 09:43:23 +0000945
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 /* Carve off a new pool. */
947 assert(usable_arenas->nfreepools > 0);
948 assert(usable_arenas->freepools == NULL);
949 pool = (poolp)usable_arenas->pool_address;
950 assert((block*)pool <= (block*)usable_arenas->address +
951 ARENA_SIZE - POOL_SIZE);
952 pool->arenaindex = usable_arenas - arenas;
953 assert(&arenas[pool->arenaindex] == usable_arenas);
954 pool->szidx = DUMMY_SIZE_IDX;
955 usable_arenas->pool_address += POOL_SIZE;
956 --usable_arenas->nfreepools;
Thomas Woutersa9773292006-04-21 09:43:23 +0000957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000958 if (usable_arenas->nfreepools == 0) {
959 assert(usable_arenas->nextarena == NULL ||
960 usable_arenas->nextarena->prevarena ==
961 usable_arenas);
962 /* Unlink the arena: it is completely allocated. */
963 usable_arenas = usable_arenas->nextarena;
964 if (usable_arenas != NULL) {
965 usable_arenas->prevarena = NULL;
966 assert(usable_arenas->address != 0);
967 }
968 }
Thomas Woutersa9773292006-04-21 09:43:23 +0000969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000970 goto init_pool;
971 }
Neil Schemenauera35c6882001-02-27 04:45:05 +0000972
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000973 /* The small block allocator ends here. */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000974
Tim Petersd97a1c02002-03-30 06:09:22 +0000975redirect:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000976 /* Redirect the original request to the underlying (libc) allocator.
977 * We jump here on bigger requests, on error in the code above (as a
978 * last chance to serve the request) or when the max memory limit
979 * has been reached.
980 */
Victor Stinner36f01ad2013-06-15 03:37:01 +0200981 if (nbytes == 0)
982 nbytes = 1;
Antoine Pitrouf9d0b122012-12-09 14:28:26 +0100983 {
Victor Stinner36f01ad2013-06-15 03:37:01 +0200984 void *result = malloc(nbytes);
Antoine Pitrouf9d0b122012-12-09 14:28:26 +0100985 if (!result)
986 _Py_AllocatedBlocks--;
987 return result;
988 }
Neil Schemenauera35c6882001-02-27 04:45:05 +0000989}
990
991/* free */
992
Victor Stinner36f01ad2013-06-15 03:37:01 +0200993#undef PyObject_Free
994void
995PyObject_Free(void *p)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000996{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 poolp pool;
998 block *lastfree;
999 poolp next, prev;
1000 uint size;
Antoine Pitroub7fb2e22011-01-07 21:43:59 +00001001#ifndef Py_USING_MEMORY_DEBUGGER
1002 uint arenaindex_temp;
1003#endif
Neil Schemenauera35c6882001-02-27 04:45:05 +00001004
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 if (p == NULL) /* free(NULL) has no effect */
1006 return;
Neil Schemenauera35c6882001-02-27 04:45:05 +00001007
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001008 _Py_AllocatedBlocks--;
1009
Benjamin Peterson05159c42009-12-03 03:01:27 +00001010#ifdef WITH_VALGRIND
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001011 if (UNLIKELY(running_on_valgrind > 0))
1012 goto redirect;
Benjamin Peterson05159c42009-12-03 03:01:27 +00001013#endif
1014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 pool = POOL_ADDR(p);
1016 if (Py_ADDRESS_IN_RANGE(p, pool)) {
1017 /* We allocated this address. */
1018 LOCK();
1019 /* Link p to the start of the pool's freeblock list. Since
1020 * the pool had at least the p block outstanding, the pool
1021 * wasn't empty (so it's already in a usedpools[] list, or
1022 * was full and is in no list -- it's not in the freeblocks
1023 * list in any case).
1024 */
1025 assert(pool->ref.count > 0); /* else it was empty */
1026 *(block **)p = lastfree = pool->freeblock;
1027 pool->freeblock = (block *)p;
1028 if (lastfree) {
1029 struct arena_object* ao;
1030 uint nf; /* ao->nfreepools */
Thomas Woutersa9773292006-04-21 09:43:23 +00001031
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001032 /* freeblock wasn't NULL, so the pool wasn't full,
1033 * and the pool is in a usedpools[] list.
1034 */
1035 if (--pool->ref.count != 0) {
1036 /* pool isn't empty: leave it in usedpools */
1037 UNLOCK();
1038 return;
1039 }
1040 /* Pool is now empty: unlink from usedpools, and
1041 * link to the front of freepools. This ensures that
1042 * previously freed pools will be allocated later
1043 * (being not referenced, they are perhaps paged out).
1044 */
1045 next = pool->nextpool;
1046 prev = pool->prevpool;
1047 next->prevpool = prev;
1048 prev->nextpool = next;
Thomas Woutersa9773292006-04-21 09:43:23 +00001049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 /* Link the pool to freepools. This is a singly-linked
1051 * list, and pool->prevpool isn't used there.
1052 */
1053 ao = &arenas[pool->arenaindex];
1054 pool->nextpool = ao->freepools;
1055 ao->freepools = pool;
1056 nf = ++ao->nfreepools;
Thomas Woutersa9773292006-04-21 09:43:23 +00001057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001058 /* All the rest is arena management. We just freed
1059 * a pool, and there are 4 cases for arena mgmt:
1060 * 1. If all the pools are free, return the arena to
1061 * the system free().
1062 * 2. If this is the only free pool in the arena,
1063 * add the arena back to the `usable_arenas` list.
1064 * 3. If the "next" arena has a smaller count of free
1065 * pools, we have to "slide this arena right" to
1066 * restore that usable_arenas is sorted in order of
1067 * nfreepools.
1068 * 4. Else there's nothing more to do.
1069 */
1070 if (nf == ao->ntotalpools) {
1071 /* Case 1. First unlink ao from usable_arenas.
1072 */
1073 assert(ao->prevarena == NULL ||
1074 ao->prevarena->address != 0);
1075 assert(ao ->nextarena == NULL ||
1076 ao->nextarena->address != 0);
Thomas Woutersa9773292006-04-21 09:43:23 +00001077
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 /* Fix the pointer in the prevarena, or the
1079 * usable_arenas pointer.
1080 */
1081 if (ao->prevarena == NULL) {
1082 usable_arenas = ao->nextarena;
1083 assert(usable_arenas == NULL ||
1084 usable_arenas->address != 0);
1085 }
1086 else {
1087 assert(ao->prevarena->nextarena == ao);
1088 ao->prevarena->nextarena =
1089 ao->nextarena;
1090 }
1091 /* Fix the pointer in the nextarena. */
1092 if (ao->nextarena != NULL) {
1093 assert(ao->nextarena->prevarena == ao);
1094 ao->nextarena->prevarena =
1095 ao->prevarena;
1096 }
1097 /* Record that this arena_object slot is
1098 * available to be reused.
1099 */
1100 ao->nextarena = unused_arena_objects;
1101 unused_arena_objects = ao;
Thomas Woutersa9773292006-04-21 09:43:23 +00001102
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001103 /* Free the entire arena. */
Martin v. Löwiscd83fa82013-06-27 12:23:29 +02001104#ifdef MS_WINDOWS
1105 VirtualFree((void *)ao->address, 0, MEM_RELEASE);
1106#elif defined(ARENAS_USE_MMAP)
Victor Stinner36f01ad2013-06-15 03:37:01 +02001107 munmap((void *)ao->address, ARENA_SIZE);
1108#else
1109 free((void *)ao->address);
1110#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001111 ao->address = 0; /* mark unassociated */
1112 --narenas_currently_allocated;
Thomas Woutersa9773292006-04-21 09:43:23 +00001113
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001114 UNLOCK();
1115 return;
1116 }
1117 if (nf == 1) {
1118 /* Case 2. Put ao at the head of
1119 * usable_arenas. Note that because
1120 * ao->nfreepools was 0 before, ao isn't
1121 * currently on the usable_arenas list.
1122 */
1123 ao->nextarena = usable_arenas;
1124 ao->prevarena = NULL;
1125 if (usable_arenas)
1126 usable_arenas->prevarena = ao;
1127 usable_arenas = ao;
1128 assert(usable_arenas->address != 0);
Thomas Woutersa9773292006-04-21 09:43:23 +00001129
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001130 UNLOCK();
1131 return;
1132 }
1133 /* If this arena is now out of order, we need to keep
1134 * the list sorted. The list is kept sorted so that
1135 * the "most full" arenas are used first, which allows
1136 * the nearly empty arenas to be completely freed. In
1137 * a few un-scientific tests, it seems like this
1138 * approach allowed a lot more memory to be freed.
1139 */
1140 if (ao->nextarena == NULL ||
1141 nf <= ao->nextarena->nfreepools) {
1142 /* Case 4. Nothing to do. */
1143 UNLOCK();
1144 return;
1145 }
1146 /* Case 3: We have to move the arena towards the end
1147 * of the list, because it has more free pools than
1148 * the arena to its right.
1149 * First unlink ao from usable_arenas.
1150 */
1151 if (ao->prevarena != NULL) {
1152 /* ao isn't at the head of the list */
1153 assert(ao->prevarena->nextarena == ao);
1154 ao->prevarena->nextarena = ao->nextarena;
1155 }
1156 else {
1157 /* ao is at the head of the list */
1158 assert(usable_arenas == ao);
1159 usable_arenas = ao->nextarena;
1160 }
1161 ao->nextarena->prevarena = ao->prevarena;
Thomas Woutersa9773292006-04-21 09:43:23 +00001162
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001163 /* Locate the new insertion point by iterating over
1164 * the list, using our nextarena pointer.
1165 */
1166 while (ao->nextarena != NULL &&
1167 nf > ao->nextarena->nfreepools) {
1168 ao->prevarena = ao->nextarena;
1169 ao->nextarena = ao->nextarena->nextarena;
1170 }
Thomas Woutersa9773292006-04-21 09:43:23 +00001171
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001172 /* Insert ao at this point. */
1173 assert(ao->nextarena == NULL ||
1174 ao->prevarena == ao->nextarena->prevarena);
1175 assert(ao->prevarena->nextarena == ao->nextarena);
Thomas Woutersa9773292006-04-21 09:43:23 +00001176
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001177 ao->prevarena->nextarena = ao;
1178 if (ao->nextarena != NULL)
1179 ao->nextarena->prevarena = ao;
Thomas Woutersa9773292006-04-21 09:43:23 +00001180
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001181 /* Verify that the swaps worked. */
1182 assert(ao->nextarena == NULL ||
1183 nf <= ao->nextarena->nfreepools);
1184 assert(ao->prevarena == NULL ||
1185 nf > ao->prevarena->nfreepools);
1186 assert(ao->nextarena == NULL ||
1187 ao->nextarena->prevarena == ao);
1188 assert((usable_arenas == ao &&
1189 ao->prevarena == NULL) ||
1190 ao->prevarena->nextarena == ao);
Thomas Woutersa9773292006-04-21 09:43:23 +00001191
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001192 UNLOCK();
1193 return;
1194 }
1195 /* Pool was full, so doesn't currently live in any list:
1196 * link it to the front of the appropriate usedpools[] list.
1197 * This mimics LRU pool usage for new allocations and
1198 * targets optimal filling when several pools contain
1199 * blocks of the same size class.
1200 */
1201 --pool->ref.count;
1202 assert(pool->ref.count > 0); /* else the pool is empty */
1203 size = pool->szidx;
1204 next = usedpools[size + size];
1205 prev = next->prevpool;
1206 /* insert pool before next: prev <-> pool <-> next */
1207 pool->nextpool = next;
1208 pool->prevpool = prev;
1209 next->prevpool = pool;
1210 prev->nextpool = pool;
1211 UNLOCK();
1212 return;
1213 }
Neil Schemenauera35c6882001-02-27 04:45:05 +00001214
Benjamin Peterson05159c42009-12-03 03:01:27 +00001215#ifdef WITH_VALGRIND
1216redirect:
1217#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001218 /* We didn't allocate this address. */
Victor Stinner36f01ad2013-06-15 03:37:01 +02001219 free(p);
Neil Schemenauera35c6882001-02-27 04:45:05 +00001220}
1221
Tim Peters84c1b972002-04-04 04:44:32 +00001222/* realloc. If p is NULL, this acts like malloc(nbytes). Else if nbytes==0,
1223 * then as the Python docs promise, we do not treat this like free(p), and
1224 * return a non-NULL result.
1225 */
Neil Schemenauera35c6882001-02-27 04:45:05 +00001226
Victor Stinner36f01ad2013-06-15 03:37:01 +02001227#undef PyObject_Realloc
1228void *
1229PyObject_Realloc(void *p, size_t nbytes)
Neil Schemenauera35c6882001-02-27 04:45:05 +00001230{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001231 void *bp;
1232 poolp pool;
1233 size_t size;
Antoine Pitroub7fb2e22011-01-07 21:43:59 +00001234#ifndef Py_USING_MEMORY_DEBUGGER
1235 uint arenaindex_temp;
1236#endif
Neil Schemenauera35c6882001-02-27 04:45:05 +00001237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001238 if (p == NULL)
Victor Stinner36f01ad2013-06-15 03:37:01 +02001239 return PyObject_Malloc(nbytes);
1240
1241 /*
1242 * Limit ourselves to PY_SSIZE_T_MAX bytes to prevent security holes.
1243 * Most python internals blindly use a signed Py_ssize_t to track
1244 * things without checking for overflows or negatives.
1245 * As size_t is unsigned, checking for nbytes < 0 is not required.
1246 */
1247 if (nbytes > PY_SSIZE_T_MAX)
1248 return NULL;
Georg Brandld492ad82008-07-23 16:13:07 +00001249
Benjamin Peterson05159c42009-12-03 03:01:27 +00001250#ifdef WITH_VALGRIND
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001251 /* Treat running_on_valgrind == -1 the same as 0 */
1252 if (UNLIKELY(running_on_valgrind > 0))
1253 goto redirect;
Benjamin Peterson05159c42009-12-03 03:01:27 +00001254#endif
1255
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001256 pool = POOL_ADDR(p);
1257 if (Py_ADDRESS_IN_RANGE(p, pool)) {
1258 /* We're in charge of this block */
1259 size = INDEX2SIZE(pool->szidx);
1260 if (nbytes <= size) {
1261 /* The block is staying the same or shrinking. If
1262 * it's shrinking, there's a tradeoff: it costs
1263 * cycles to copy the block to a smaller size class,
1264 * but it wastes memory not to copy it. The
1265 * compromise here is to copy on shrink only if at
1266 * least 25% of size can be shaved off.
1267 */
1268 if (4 * nbytes > 3 * size) {
1269 /* It's the same,
1270 * or shrinking and new/old > 3/4.
1271 */
1272 return p;
1273 }
1274 size = nbytes;
1275 }
Victor Stinner36f01ad2013-06-15 03:37:01 +02001276 bp = PyObject_Malloc(nbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001277 if (bp != NULL) {
1278 memcpy(bp, p, size);
Victor Stinner36f01ad2013-06-15 03:37:01 +02001279 PyObject_Free(p);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001280 }
1281 return bp;
1282 }
Benjamin Peterson05159c42009-12-03 03:01:27 +00001283#ifdef WITH_VALGRIND
1284 redirect:
1285#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001286 /* We're not managing this block. If nbytes <=
1287 * SMALL_REQUEST_THRESHOLD, it's tempting to try to take over this
1288 * block. However, if we do, we need to copy the valid data from
1289 * the C-managed block to one of our blocks, and there's no portable
1290 * way to know how much of the memory space starting at p is valid.
1291 * As bug 1185883 pointed out the hard way, it's possible that the
1292 * C-managed block is "at the end" of allocated VM space, so that
1293 * a memory fault can occur if we try to copy nbytes bytes starting
1294 * at p. Instead we punt: let C continue to manage this block.
1295 */
1296 if (nbytes)
Victor Stinner36f01ad2013-06-15 03:37:01 +02001297 return realloc(p, nbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001298 /* C doesn't define the result of realloc(p, 0) (it may or may not
1299 * return NULL then), but Python's docs promise that nbytes==0 never
1300 * returns NULL. We don't pass 0 to realloc(), to avoid that endcase
1301 * to begin with. Even then, we can't be sure that realloc() won't
1302 * return NULL.
1303 */
Victor Stinner36f01ad2013-06-15 03:37:01 +02001304 bp = realloc(p, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001305 return bp ? bp : p;
Neil Schemenauera35c6882001-02-27 04:45:05 +00001306}
1307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001308#else /* ! WITH_PYMALLOC */
Tim Petersddea2082002-03-23 10:03:50 +00001309
1310/*==========================================================================*/
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00001311/* pymalloc not enabled: Redirect the entry points to malloc. These will
1312 * only be used by extensions that are compiled with pymalloc enabled. */
Tim Peters62c06ba2002-03-23 22:28:18 +00001313
Victor Stinner36f01ad2013-06-15 03:37:01 +02001314void *
1315PyObject_Malloc(size_t n)
1316{
1317 return PyMem_MALLOC(n);
1318}
1319
1320void *
1321PyObject_Realloc(void *p, size_t n)
1322{
1323 return PyMem_REALLOC(p, n);
1324}
1325
1326void
1327PyObject_Free(void *p)
1328{
1329 PyMem_FREE(p);
1330}
1331
Antoine Pitrou92840532012-12-17 23:05:59 +01001332Py_ssize_t
1333_Py_GetAllocatedBlocks(void)
1334{
1335 return 0;
1336}
1337
Tim Peters1221c0a2002-03-23 00:20:15 +00001338#endif /* WITH_PYMALLOC */
1339
Tim Petersddea2082002-03-23 10:03:50 +00001340#ifdef PYMALLOC_DEBUG
1341/*==========================================================================*/
Tim Peters62c06ba2002-03-23 22:28:18 +00001342/* A x-platform debugging allocator. This doesn't manage memory directly,
1343 * it wraps a real allocator, adding extra debugging info to the memory blocks.
1344 */
Tim Petersddea2082002-03-23 10:03:50 +00001345
Tim Petersf6fb5012002-04-12 07:38:53 +00001346/* Special bytes broadcast into debug memory blocks at appropriate times.
1347 * Strings of these are unlikely to be valid addresses, floats, ints or
1348 * 7-bit ASCII.
1349 */
1350#undef CLEANBYTE
1351#undef DEADBYTE
1352#undef FORBIDDENBYTE
1353#define CLEANBYTE 0xCB /* clean (newly allocated) memory */
Tim Peters889f61d2002-07-10 19:29:49 +00001354#define DEADBYTE 0xDB /* dead (newly freed) memory */
Tim Petersf6fb5012002-04-12 07:38:53 +00001355#define FORBIDDENBYTE 0xFB /* untouchable bytes at each end of a block */
Tim Petersddea2082002-03-23 10:03:50 +00001356
Victor Stinner36f01ad2013-06-15 03:37:01 +02001357/* We tag each block with an API ID in order to tag API violations */
1358#define _PYMALLOC_MEM_ID 'm' /* the PyMem_Malloc() API */
1359#define _PYMALLOC_OBJ_ID 'o' /* The PyObject_Malloc() API */
1360
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001361static size_t serialno = 0; /* incremented on each debug {m,re}alloc */
Tim Petersddea2082002-03-23 10:03:50 +00001362
Tim Peterse0850172002-03-24 00:34:21 +00001363/* serialno is always incremented via calling this routine. The point is
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001364 * to supply a single place to set a breakpoint.
1365 */
Tim Peterse0850172002-03-24 00:34:21 +00001366static void
Neil Schemenauerbd02b142002-03-28 21:05:38 +00001367bumpserialno(void)
Tim Peterse0850172002-03-24 00:34:21 +00001368{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001369 ++serialno;
Tim Peterse0850172002-03-24 00:34:21 +00001370}
1371
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001372#define SST SIZEOF_SIZE_T
Tim Peterse0850172002-03-24 00:34:21 +00001373
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001374/* Read sizeof(size_t) bytes at p as a big-endian size_t. */
1375static size_t
1376read_size_t(const void *p)
Tim Petersddea2082002-03-23 10:03:50 +00001377{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001378 const uchar *q = (const uchar *)p;
1379 size_t result = *q++;
1380 int i;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001382 for (i = SST; --i > 0; ++q)
1383 result = (result << 8) | *q;
1384 return result;
Tim Petersddea2082002-03-23 10:03:50 +00001385}
1386
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001387/* Write n as a big-endian size_t, MSB at address p, LSB at
1388 * p + sizeof(size_t) - 1.
1389 */
Tim Petersddea2082002-03-23 10:03:50 +00001390static void
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001391write_size_t(void *p, size_t n)
Tim Petersddea2082002-03-23 10:03:50 +00001392{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001393 uchar *q = (uchar *)p + SST - 1;
1394 int i;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001396 for (i = SST; --i >= 0; --q) {
1397 *q = (uchar)(n & 0xff);
1398 n >>= 8;
1399 }
Tim Petersddea2082002-03-23 10:03:50 +00001400}
1401
Tim Peters08d82152002-04-18 22:25:03 +00001402#ifdef Py_DEBUG
1403/* Is target in the list? The list is traversed via the nextpool pointers.
1404 * The list may be NULL-terminated, or circular. Return 1 if target is in
1405 * list, else 0.
1406 */
1407static int
1408pool_is_in_list(const poolp target, poolp list)
1409{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 poolp origlist = list;
1411 assert(target != NULL);
1412 if (list == NULL)
1413 return 0;
1414 do {
1415 if (target == list)
1416 return 1;
1417 list = list->nextpool;
1418 } while (list != NULL && list != origlist);
1419 return 0;
Tim Peters08d82152002-04-18 22:25:03 +00001420}
1421
1422#else
1423#define pool_is_in_list(X, Y) 1
1424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001425#endif /* Py_DEBUG */
Tim Peters08d82152002-04-18 22:25:03 +00001426
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001427/* Let S = sizeof(size_t). The debug malloc asks for 4*S extra bytes and
1428 fills them with useful stuff, here calling the underlying malloc's result p:
Tim Petersddea2082002-03-23 10:03:50 +00001429
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001430p[0: S]
1431 Number of bytes originally asked for. This is a size_t, big-endian (easier
1432 to read in a memory dump).
1433p[S: 2*S]
Tim Petersf6fb5012002-04-12 07:38:53 +00001434 Copies of FORBIDDENBYTE. Used to catch under- writes and reads.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001435p[2*S: 2*S+n]
Tim Petersf6fb5012002-04-12 07:38:53 +00001436 The requested memory, filled with copies of CLEANBYTE.
Tim Petersddea2082002-03-23 10:03:50 +00001437 Used to catch reference to uninitialized memory.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001438 &p[2*S] is returned. Note that this is 8-byte aligned if pymalloc
Tim Petersddea2082002-03-23 10:03:50 +00001439 handled the request itself.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001440p[2*S+n: 2*S+n+S]
Tim Petersf6fb5012002-04-12 07:38:53 +00001441 Copies of FORBIDDENBYTE. Used to catch over- writes and reads.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001442p[2*S+n+S: 2*S+n+2*S]
Victor Stinner36f01ad2013-06-15 03:37:01 +02001443 A serial number, incremented by 1 on each call to _PyObject_DebugMalloc
1444 and _PyObject_DebugRealloc.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001445 This is a big-endian size_t.
Tim Petersddea2082002-03-23 10:03:50 +00001446 If "bad memory" is detected later, the serial number gives an
1447 excellent way to set a breakpoint on the next run, to capture the
1448 instant at which this block was passed out.
1449*/
1450
Victor Stinner36f01ad2013-06-15 03:37:01 +02001451/* debug replacements for the PyMem_* memory API */
1452void *
1453_PyMem_DebugMalloc(size_t nbytes)
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00001454{
Victor Stinner36f01ad2013-06-15 03:37:01 +02001455 return _PyObject_DebugMallocApi(_PYMALLOC_MEM_ID, nbytes);
1456}
1457void *
1458_PyMem_DebugRealloc(void *p, size_t nbytes)
1459{
1460 return _PyObject_DebugReallocApi(_PYMALLOC_MEM_ID, p, nbytes);
1461}
1462void
1463_PyMem_DebugFree(void *p)
1464{
1465 _PyObject_DebugFreeApi(_PYMALLOC_MEM_ID, p);
1466}
1467
1468/* debug replacements for the PyObject_* memory API */
1469void *
1470_PyObject_DebugMalloc(size_t nbytes)
1471{
1472 return _PyObject_DebugMallocApi(_PYMALLOC_OBJ_ID, nbytes);
1473}
1474void *
1475_PyObject_DebugRealloc(void *p, size_t nbytes)
1476{
1477 return _PyObject_DebugReallocApi(_PYMALLOC_OBJ_ID, p, nbytes);
1478}
1479void
1480_PyObject_DebugFree(void *p)
1481{
1482 _PyObject_DebugFreeApi(_PYMALLOC_OBJ_ID, p);
1483}
1484void
1485_PyObject_DebugCheckAddress(const void *p)
1486{
1487 _PyObject_DebugCheckAddressApi(_PYMALLOC_OBJ_ID, p);
1488}
1489
1490
1491/* generic debug memory api, with an "id" to identify the API in use */
1492void *
1493_PyObject_DebugMallocApi(char id, size_t nbytes)
1494{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001495 uchar *p; /* base address of malloc'ed block */
1496 uchar *tail; /* p + 2*SST + nbytes == pointer to tail pad bytes */
1497 size_t total; /* nbytes + 4*SST */
Tim Petersddea2082002-03-23 10:03:50 +00001498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001499 bumpserialno();
1500 total = nbytes + 4*SST;
1501 if (total < nbytes)
1502 /* overflow: can't represent total as a size_t */
1503 return NULL;
Tim Petersddea2082002-03-23 10:03:50 +00001504
Victor Stinner36f01ad2013-06-15 03:37:01 +02001505 p = (uchar *)PyObject_Malloc(total);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001506 if (p == NULL)
1507 return NULL;
Tim Petersddea2082002-03-23 10:03:50 +00001508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001509 /* at p, write size (SST bytes), id (1 byte), pad (SST-1 bytes) */
1510 write_size_t(p, nbytes);
Victor Stinner36f01ad2013-06-15 03:37:01 +02001511 p[SST] = (uchar)id;
1512 memset(p + SST + 1 , FORBIDDENBYTE, SST-1);
Tim Petersddea2082002-03-23 10:03:50 +00001513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001514 if (nbytes > 0)
1515 memset(p + 2*SST, CLEANBYTE, nbytes);
Tim Petersddea2082002-03-23 10:03:50 +00001516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001517 /* at tail, write pad (SST bytes) and serialno (SST bytes) */
1518 tail = p + 2*SST + nbytes;
1519 memset(tail, FORBIDDENBYTE, SST);
1520 write_size_t(tail + SST, serialno);
Tim Petersddea2082002-03-23 10:03:50 +00001521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001522 return p + 2*SST;
Tim Petersddea2082002-03-23 10:03:50 +00001523}
1524
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001525/* 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 +00001526 particular, that the FORBIDDENBYTEs with the api ID are still intact).
Tim Petersf6fb5012002-04-12 07:38:53 +00001527 Then fills the original bytes with DEADBYTE.
Tim Petersddea2082002-03-23 10:03:50 +00001528 Then calls the underlying free.
1529*/
Victor Stinner36f01ad2013-06-15 03:37:01 +02001530void
1531_PyObject_DebugFreeApi(char api, void *p)
Tim Petersddea2082002-03-23 10:03:50 +00001532{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001533 uchar *q = (uchar *)p - 2*SST; /* address returned from malloc */
1534 size_t nbytes;
Tim Petersddea2082002-03-23 10:03:50 +00001535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001536 if (p == NULL)
1537 return;
Victor Stinner36f01ad2013-06-15 03:37:01 +02001538 _PyObject_DebugCheckAddressApi(api, p);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001539 nbytes = read_size_t(q);
1540 nbytes += 4*SST;
1541 if (nbytes > 0)
1542 memset(q, DEADBYTE, nbytes);
Victor Stinner36f01ad2013-06-15 03:37:01 +02001543 PyObject_Free(q);
Tim Petersddea2082002-03-23 10:03:50 +00001544}
1545
Victor Stinner36f01ad2013-06-15 03:37:01 +02001546void *
1547_PyObject_DebugReallocApi(char api, void *p, size_t nbytes)
Tim Petersddea2082002-03-23 10:03:50 +00001548{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001549 uchar *q = (uchar *)p;
1550 uchar *tail;
1551 size_t total; /* nbytes + 4*SST */
1552 size_t original_nbytes;
1553 int i;
Tim Petersddea2082002-03-23 10:03:50 +00001554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001555 if (p == NULL)
Victor Stinner36f01ad2013-06-15 03:37:01 +02001556 return _PyObject_DebugMallocApi(api, nbytes);
Tim Petersddea2082002-03-23 10:03:50 +00001557
Victor Stinner36f01ad2013-06-15 03:37:01 +02001558 _PyObject_DebugCheckAddressApi(api, p);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001559 bumpserialno();
1560 original_nbytes = read_size_t(q - 2*SST);
1561 total = nbytes + 4*SST;
1562 if (total < nbytes)
1563 /* overflow: can't represent total as a size_t */
1564 return NULL;
Tim Petersddea2082002-03-23 10:03:50 +00001565
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001566 if (nbytes < original_nbytes) {
1567 /* shrinking: mark old extra memory dead */
1568 memset(q + nbytes, DEADBYTE, original_nbytes - nbytes + 2*SST);
1569 }
Tim Petersddea2082002-03-23 10:03:50 +00001570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001571 /* Resize and add decorations. We may get a new pointer here, in which
1572 * case we didn't get the chance to mark the old memory with DEADBYTE,
1573 * but we live with that.
1574 */
Victor Stinner36f01ad2013-06-15 03:37:01 +02001575 q = (uchar *)PyObject_Realloc(q - 2*SST, total);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001576 if (q == NULL)
1577 return NULL;
Tim Peters85cc1c42002-04-12 08:52:50 +00001578
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001579 write_size_t(q, nbytes);
Victor Stinner36f01ad2013-06-15 03:37:01 +02001580 assert(q[SST] == (uchar)api);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001581 for (i = 1; i < SST; ++i)
1582 assert(q[SST + i] == FORBIDDENBYTE);
1583 q += 2*SST;
1584 tail = q + nbytes;
1585 memset(tail, FORBIDDENBYTE, SST);
1586 write_size_t(tail + SST, serialno);
Tim Peters85cc1c42002-04-12 08:52:50 +00001587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001588 if (nbytes > original_nbytes) {
1589 /* growing: mark new extra memory clean */
1590 memset(q + original_nbytes, CLEANBYTE,
Stefan Krah735bb122010-11-26 10:54:09 +00001591 nbytes - original_nbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001592 }
Tim Peters85cc1c42002-04-12 08:52:50 +00001593
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001594 return q;
Tim Petersddea2082002-03-23 10:03:50 +00001595}
1596
Tim Peters7ccfadf2002-04-01 06:04:21 +00001597/* Check the forbidden bytes on both ends of the memory allocated for p.
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00001598 * If anything is wrong, print info to stderr via _PyObject_DebugDumpAddress,
Tim Peters7ccfadf2002-04-01 06:04:21 +00001599 * and call Py_FatalError to kill the program.
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00001600 * The API id, is also checked.
Tim Peters7ccfadf2002-04-01 06:04:21 +00001601 */
Victor Stinner36f01ad2013-06-15 03:37:01 +02001602 void
1603_PyObject_DebugCheckAddressApi(char api, const void *p)
Tim Petersddea2082002-03-23 10:03:50 +00001604{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001605 const uchar *q = (const uchar *)p;
1606 char msgbuf[64];
1607 char *msg;
1608 size_t nbytes;
1609 const uchar *tail;
1610 int i;
1611 char id;
Tim Petersddea2082002-03-23 10:03:50 +00001612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001613 if (p == NULL) {
1614 msg = "didn't expect a NULL pointer";
1615 goto error;
1616 }
Tim Petersddea2082002-03-23 10:03:50 +00001617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001618 /* Check the API id */
1619 id = (char)q[-SST];
1620 if (id != api) {
1621 msg = msgbuf;
1622 snprintf(msg, sizeof(msgbuf), "bad ID: Allocated using API '%c', verified using API '%c'", id, api);
1623 msgbuf[sizeof(msgbuf)-1] = 0;
1624 goto error;
1625 }
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00001626
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001627 /* Check the stuff at the start of p first: if there's underwrite
1628 * corruption, the number-of-bytes field may be nuts, and checking
1629 * the tail could lead to a segfault then.
1630 */
1631 for (i = SST-1; i >= 1; --i) {
1632 if (*(q-i) != FORBIDDENBYTE) {
1633 msg = "bad leading pad byte";
1634 goto error;
1635 }
1636 }
Tim Petersddea2082002-03-23 10:03:50 +00001637
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001638 nbytes = read_size_t(q - 2*SST);
1639 tail = q + nbytes;
1640 for (i = 0; i < SST; ++i) {
1641 if (tail[i] != FORBIDDENBYTE) {
1642 msg = "bad trailing pad byte";
1643 goto error;
1644 }
1645 }
Tim Petersddea2082002-03-23 10:03:50 +00001646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001647 return;
Tim Petersd1139e02002-03-28 07:32:11 +00001648
1649error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001650 _PyObject_DebugDumpAddress(p);
1651 Py_FatalError(msg);
Tim Petersddea2082002-03-23 10:03:50 +00001652}
1653
Tim Peters7ccfadf2002-04-01 06:04:21 +00001654/* Display info to stderr about the memory block at p. */
Victor Stinner36f01ad2013-06-15 03:37:01 +02001655void
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00001656_PyObject_DebugDumpAddress(const void *p)
Tim Petersddea2082002-03-23 10:03:50 +00001657{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001658 const uchar *q = (const uchar *)p;
1659 const uchar *tail;
1660 size_t nbytes, serial;
1661 int i;
1662 int ok;
1663 char id;
Tim Petersddea2082002-03-23 10:03:50 +00001664
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001665 fprintf(stderr, "Debug memory block at address p=%p:", p);
1666 if (p == NULL) {
1667 fprintf(stderr, "\n");
1668 return;
1669 }
1670 id = (char)q[-SST];
1671 fprintf(stderr, " API '%c'\n", id);
Tim Petersddea2082002-03-23 10:03:50 +00001672
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001673 nbytes = read_size_t(q - 2*SST);
1674 fprintf(stderr, " %" PY_FORMAT_SIZE_T "u bytes originally "
1675 "requested\n", nbytes);
Tim Petersddea2082002-03-23 10:03:50 +00001676
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001677 /* In case this is nuts, check the leading pad bytes first. */
1678 fprintf(stderr, " The %d pad bytes at p-%d are ", SST-1, SST-1);
1679 ok = 1;
1680 for (i = 1; i <= SST-1; ++i) {
1681 if (*(q-i) != FORBIDDENBYTE) {
1682 ok = 0;
1683 break;
1684 }
1685 }
1686 if (ok)
1687 fputs("FORBIDDENBYTE, as expected.\n", stderr);
1688 else {
1689 fprintf(stderr, "not all FORBIDDENBYTE (0x%02x):\n",
1690 FORBIDDENBYTE);
1691 for (i = SST-1; i >= 1; --i) {
1692 const uchar byte = *(q-i);
1693 fprintf(stderr, " at p-%d: 0x%02x", i, byte);
1694 if (byte != FORBIDDENBYTE)
1695 fputs(" *** OUCH", stderr);
1696 fputc('\n', stderr);
1697 }
Tim Peters449b5a82002-04-28 06:14:45 +00001698
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001699 fputs(" Because memory is corrupted at the start, the "
1700 "count of bytes requested\n"
1701 " may be bogus, and checking the trailing pad "
1702 "bytes may segfault.\n", stderr);
1703 }
Tim Petersddea2082002-03-23 10:03:50 +00001704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001705 tail = q + nbytes;
1706 fprintf(stderr, " The %d pad bytes at tail=%p are ", SST, tail);
1707 ok = 1;
1708 for (i = 0; i < SST; ++i) {
1709 if (tail[i] != FORBIDDENBYTE) {
1710 ok = 0;
1711 break;
1712 }
1713 }
1714 if (ok)
1715 fputs("FORBIDDENBYTE, as expected.\n", stderr);
1716 else {
1717 fprintf(stderr, "not all FORBIDDENBYTE (0x%02x):\n",
Stefan Krah735bb122010-11-26 10:54:09 +00001718 FORBIDDENBYTE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001719 for (i = 0; i < SST; ++i) {
1720 const uchar byte = tail[i];
1721 fprintf(stderr, " at tail+%d: 0x%02x",
Stefan Krah735bb122010-11-26 10:54:09 +00001722 i, byte);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001723 if (byte != FORBIDDENBYTE)
1724 fputs(" *** OUCH", stderr);
1725 fputc('\n', stderr);
1726 }
1727 }
Tim Petersddea2082002-03-23 10:03:50 +00001728
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001729 serial = read_size_t(tail + SST);
1730 fprintf(stderr, " The block was made by call #%" PY_FORMAT_SIZE_T
1731 "u to debug malloc/realloc.\n", serial);
Tim Petersddea2082002-03-23 10:03:50 +00001732
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001733 if (nbytes > 0) {
1734 i = 0;
1735 fputs(" Data at p:", stderr);
1736 /* print up to 8 bytes at the start */
1737 while (q < tail && i < 8) {
1738 fprintf(stderr, " %02x", *q);
1739 ++i;
1740 ++q;
1741 }
1742 /* and up to 8 at the end */
1743 if (q < tail) {
1744 if (tail - q > 8) {
1745 fputs(" ...", stderr);
1746 q = tail - 8;
1747 }
1748 while (q < tail) {
1749 fprintf(stderr, " %02x", *q);
1750 ++q;
1751 }
1752 }
1753 fputc('\n', stderr);
1754 }
Tim Petersddea2082002-03-23 10:03:50 +00001755}
1756
David Malcolm49526f42012-06-22 14:55:41 -04001757#endif /* PYMALLOC_DEBUG */
1758
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001759static size_t
David Malcolm49526f42012-06-22 14:55:41 -04001760printone(FILE *out, const char* msg, size_t value)
Tim Peters16bcb6b2002-04-05 05:45:31 +00001761{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001762 int i, k;
1763 char buf[100];
1764 size_t origvalue = value;
Tim Peters16bcb6b2002-04-05 05:45:31 +00001765
David Malcolm49526f42012-06-22 14:55:41 -04001766 fputs(msg, out);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001767 for (i = (int)strlen(msg); i < 35; ++i)
David Malcolm49526f42012-06-22 14:55:41 -04001768 fputc(' ', out);
1769 fputc('=', out);
Tim Peters49f26812002-04-06 01:45:35 +00001770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001771 /* Write the value with commas. */
1772 i = 22;
1773 buf[i--] = '\0';
1774 buf[i--] = '\n';
1775 k = 3;
1776 do {
1777 size_t nextvalue = value / 10;
Benjamin Peterson2dba1ee2013-02-20 16:54:30 -05001778 unsigned int digit = (unsigned int)(value - nextvalue * 10);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001779 value = nextvalue;
1780 buf[i--] = (char)(digit + '0');
1781 --k;
1782 if (k == 0 && value && i >= 0) {
1783 k = 3;
1784 buf[i--] = ',';
1785 }
1786 } while (value && i >= 0);
Tim Peters49f26812002-04-06 01:45:35 +00001787
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001788 while (i >= 0)
1789 buf[i--] = ' ';
David Malcolm49526f42012-06-22 14:55:41 -04001790 fputs(buf, out);
Tim Peters49f26812002-04-06 01:45:35 +00001791
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001792 return origvalue;
Tim Peters16bcb6b2002-04-05 05:45:31 +00001793}
1794
David Malcolm49526f42012-06-22 14:55:41 -04001795void
1796_PyDebugAllocatorStats(FILE *out,
1797 const char *block_name, int num_blocks, size_t sizeof_block)
1798{
1799 char buf1[128];
1800 char buf2[128];
1801 PyOS_snprintf(buf1, sizeof(buf1),
1802 "%d %ss * %zd bytes each",
1803 num_blocks, block_name, sizeof_block);
1804 PyOS_snprintf(buf2, sizeof(buf2),
1805 "%48s ", buf1);
1806 (void)printone(out, buf2, num_blocks * sizeof_block);
1807}
1808
1809#ifdef WITH_PYMALLOC
1810
1811/* Print summary info to "out" about the state of pymalloc's structures.
Tim Peters08d82152002-04-18 22:25:03 +00001812 * In Py_DEBUG mode, also perform some expensive internal consistency
1813 * checks.
1814 */
Tim Peters7ccfadf2002-04-01 06:04:21 +00001815void
David Malcolm49526f42012-06-22 14:55:41 -04001816_PyObject_DebugMallocStats(FILE *out)
Tim Peters7ccfadf2002-04-01 06:04:21 +00001817{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001818 uint i;
1819 const uint numclasses = SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT;
1820 /* # of pools, allocated blocks, and free blocks per class index */
1821 size_t numpools[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT];
1822 size_t numblocks[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT];
1823 size_t numfreeblocks[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT];
1824 /* total # of allocated bytes in used and full pools */
1825 size_t allocated_bytes = 0;
1826 /* total # of available bytes in used pools */
1827 size_t available_bytes = 0;
1828 /* # of free pools + pools not yet carved out of current arena */
1829 uint numfreepools = 0;
1830 /* # of bytes for arena alignment padding */
1831 size_t arena_alignment = 0;
1832 /* # of bytes in used and full pools used for pool_headers */
1833 size_t pool_header_bytes = 0;
1834 /* # of bytes in used and full pools wasted due to quantization,
1835 * i.e. the necessarily leftover space at the ends of used and
1836 * full pools.
1837 */
1838 size_t quantization = 0;
1839 /* # of arenas actually allocated. */
1840 size_t narenas = 0;
1841 /* running total -- should equal narenas * ARENA_SIZE */
1842 size_t total;
1843 char buf[128];
Tim Peters7ccfadf2002-04-01 06:04:21 +00001844
David Malcolm49526f42012-06-22 14:55:41 -04001845 fprintf(out, "Small block threshold = %d, in %u size classes.\n",
Stefan Krah735bb122010-11-26 10:54:09 +00001846 SMALL_REQUEST_THRESHOLD, numclasses);
Tim Peters7ccfadf2002-04-01 06:04:21 +00001847
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001848 for (i = 0; i < numclasses; ++i)
1849 numpools[i] = numblocks[i] = numfreeblocks[i] = 0;
Tim Peters7ccfadf2002-04-01 06:04:21 +00001850
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001851 /* Because full pools aren't linked to from anything, it's easiest
1852 * to march over all the arenas. If we're lucky, most of the memory
1853 * will be living in full pools -- would be a shame to miss them.
1854 */
1855 for (i = 0; i < maxarenas; ++i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001856 uint j;
1857 uptr base = arenas[i].address;
Thomas Woutersa9773292006-04-21 09:43:23 +00001858
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001859 /* Skip arenas which are not allocated. */
1860 if (arenas[i].address == (uptr)NULL)
1861 continue;
1862 narenas += 1;
Thomas Woutersa9773292006-04-21 09:43:23 +00001863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001864 numfreepools += arenas[i].nfreepools;
Tim Peters7ccfadf2002-04-01 06:04:21 +00001865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001866 /* round up to pool alignment */
1867 if (base & (uptr)POOL_SIZE_MASK) {
1868 arena_alignment += POOL_SIZE;
1869 base &= ~(uptr)POOL_SIZE_MASK;
1870 base += POOL_SIZE;
1871 }
Tim Peters7ccfadf2002-04-01 06:04:21 +00001872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001873 /* visit every pool in the arena */
1874 assert(base <= (uptr) arenas[i].pool_address);
1875 for (j = 0;
1876 base < (uptr) arenas[i].pool_address;
1877 ++j, base += POOL_SIZE) {
1878 poolp p = (poolp)base;
1879 const uint sz = p->szidx;
1880 uint freeblocks;
Tim Peters08d82152002-04-18 22:25:03 +00001881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001882 if (p->ref.count == 0) {
1883 /* currently unused */
1884 assert(pool_is_in_list(p, arenas[i].freepools));
1885 continue;
1886 }
1887 ++numpools[sz];
1888 numblocks[sz] += p->ref.count;
1889 freeblocks = NUMBLOCKS(sz) - p->ref.count;
1890 numfreeblocks[sz] += freeblocks;
Tim Peters08d82152002-04-18 22:25:03 +00001891#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001892 if (freeblocks > 0)
1893 assert(pool_is_in_list(p, usedpools[sz + sz]));
Tim Peters08d82152002-04-18 22:25:03 +00001894#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001895 }
1896 }
1897 assert(narenas == narenas_currently_allocated);
Tim Peters7ccfadf2002-04-01 06:04:21 +00001898
David Malcolm49526f42012-06-22 14:55:41 -04001899 fputc('\n', out);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001900 fputs("class size num pools blocks in use avail blocks\n"
1901 "----- ---- --------- ------------- ------------\n",
David Malcolm49526f42012-06-22 14:55:41 -04001902 out);
Tim Peters7ccfadf2002-04-01 06:04:21 +00001903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001904 for (i = 0; i < numclasses; ++i) {
1905 size_t p = numpools[i];
1906 size_t b = numblocks[i];
1907 size_t f = numfreeblocks[i];
1908 uint size = INDEX2SIZE(i);
1909 if (p == 0) {
1910 assert(b == 0 && f == 0);
1911 continue;
1912 }
David Malcolm49526f42012-06-22 14:55:41 -04001913 fprintf(out, "%5u %6u "
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001914 "%11" PY_FORMAT_SIZE_T "u "
1915 "%15" PY_FORMAT_SIZE_T "u "
1916 "%13" PY_FORMAT_SIZE_T "u\n",
Stefan Krah735bb122010-11-26 10:54:09 +00001917 i, size, p, b, f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001918 allocated_bytes += b * size;
1919 available_bytes += f * size;
1920 pool_header_bytes += p * POOL_OVERHEAD;
1921 quantization += p * ((POOL_SIZE - POOL_OVERHEAD) % size);
1922 }
David Malcolm49526f42012-06-22 14:55:41 -04001923 fputc('\n', out);
1924#ifdef PYMALLOC_DEBUG
1925 (void)printone(out, "# times object malloc called", serialno);
1926#endif
1927 (void)printone(out, "# arenas allocated total", ntimes_arena_allocated);
1928 (void)printone(out, "# arenas reclaimed", ntimes_arena_allocated - narenas);
1929 (void)printone(out, "# arenas highwater mark", narenas_highwater);
1930 (void)printone(out, "# arenas allocated current", narenas);
Thomas Woutersa9773292006-04-21 09:43:23 +00001931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001932 PyOS_snprintf(buf, sizeof(buf),
1933 "%" PY_FORMAT_SIZE_T "u arenas * %d bytes/arena",
1934 narenas, ARENA_SIZE);
David Malcolm49526f42012-06-22 14:55:41 -04001935 (void)printone(out, buf, narenas * ARENA_SIZE);
Tim Peters16bcb6b2002-04-05 05:45:31 +00001936
David Malcolm49526f42012-06-22 14:55:41 -04001937 fputc('\n', out);
Tim Peters16bcb6b2002-04-05 05:45:31 +00001938
David Malcolm49526f42012-06-22 14:55:41 -04001939 total = printone(out, "# bytes in allocated blocks", allocated_bytes);
1940 total += printone(out, "# bytes in available blocks", available_bytes);
Tim Peters49f26812002-04-06 01:45:35 +00001941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001942 PyOS_snprintf(buf, sizeof(buf),
1943 "%u unused pools * %d bytes", numfreepools, POOL_SIZE);
David Malcolm49526f42012-06-22 14:55:41 -04001944 total += printone(out, buf, (size_t)numfreepools * POOL_SIZE);
Tim Peters16bcb6b2002-04-05 05:45:31 +00001945
David Malcolm49526f42012-06-22 14:55:41 -04001946 total += printone(out, "# bytes lost to pool headers", pool_header_bytes);
1947 total += printone(out, "# bytes lost to quantization", quantization);
1948 total += printone(out, "# bytes lost to arena alignment", arena_alignment);
1949 (void)printone(out, "Total", total);
Tim Peters7ccfadf2002-04-01 06:04:21 +00001950}
1951
David Malcolm49526f42012-06-22 14:55:41 -04001952#endif /* #ifdef WITH_PYMALLOC */
Neal Norwitz7eb3c912004-06-06 19:20:22 +00001953
1954#ifdef Py_USING_MEMORY_DEBUGGER
Thomas Woutersa9773292006-04-21 09:43:23 +00001955/* Make this function last so gcc won't inline it since the definition is
1956 * after the reference.
1957 */
Neal Norwitz7eb3c912004-06-06 19:20:22 +00001958int
1959Py_ADDRESS_IN_RANGE(void *P, poolp pool)
1960{
Antoine Pitroub7fb2e22011-01-07 21:43:59 +00001961 uint arenaindex_temp = pool->arenaindex;
1962
1963 return arenaindex_temp < maxarenas &&
1964 (uptr)P - arenas[arenaindex_temp].address < (uptr)ARENA_SIZE &&
1965 arenas[arenaindex_temp].address != 0;
Neal Norwitz7eb3c912004-06-06 19:20:22 +00001966}
1967#endif