blob: 1bb1866dc6f9ac2cfdc838f2c434154a0a443d96 [file] [log] [blame]
Tim Peters1221c0a2002-03-23 00:20:15 +00001#include "Python.h"
2
Benjamin Petersonb529c242015-04-26 20:33:38 -04003#if defined(__has_feature) /* Clang */
4 #if __has_feature(address_sanitizer) /* is ASAN enabled? */
5 #define ATTRIBUTE_NO_ADDRESS_SAFETY_ANALYSIS \
6 __attribute__((no_address_safety_analysis)) \
7 __attribute__ ((noinline))
8 #else
9 #define ATTRIBUTE_NO_ADDRESS_SAFETY_ANALYSIS
10 #endif
11#else
12 #if defined(__SANITIZE_ADDRESS__) /* GCC 4.8.x, is ASAN enabled? */
13 #define ATTRIBUTE_NO_ADDRESS_SAFETY_ANALYSIS \
14 __attribute__((no_address_safety_analysis)) \
15 __attribute__ ((noinline))
16 #else
17 #define ATTRIBUTE_NO_ADDRESS_SAFETY_ANALYSIS
18 #endif
19#endif
20
Tim Peters1221c0a2002-03-23 00:20:15 +000021#ifdef WITH_PYMALLOC
22
Benjamin Petersond16e01c2014-02-04 10:20:26 -050023#ifdef HAVE_MMAP
24 #include <sys/mman.h>
25 #ifdef MAP_ANONYMOUS
26 #define ARENAS_USE_MMAP
27 #endif
28#endif
29
Benjamin Peterson91c12eb2009-12-03 02:52:39 +000030#ifdef WITH_VALGRIND
31#include <valgrind/valgrind.h>
32
33/* If we're using GCC, use __builtin_expect() to reduce overhead of
34 the valgrind checks */
35#if defined(__GNUC__) && (__GNUC__ > 2) && defined(__OPTIMIZE__)
36# define UNLIKELY(value) __builtin_expect((value), 0)
37#else
38# define UNLIKELY(value) (value)
39#endif
40
41/* -1 indicates that we haven't checked that we're running on valgrind yet. */
42static int running_on_valgrind = -1;
43#endif
44
Neil Schemenauera35c6882001-02-27 04:45:05 +000045/* An object allocator for Python.
46
47 Here is an introduction to the layers of the Python memory architecture,
48 showing where the object allocator is actually used (layer +2), It is
49 called for every object allocation and deallocation (PyObject_New/Del),
50 unless the object-specific allocators implement a proprietary allocation
51 scheme (ex.: ints use a simple free list). This is also the place where
52 the cyclic garbage collector operates selectively on container objects.
53
54
Antoine Pitrouc83ea132010-05-09 14:46:46 +000055 Object-specific allocators
Neil Schemenauera35c6882001-02-27 04:45:05 +000056 _____ ______ ______ ________
57 [ int ] [ dict ] [ list ] ... [ string ] Python core |
58+3 | <----- Object-specific memory -----> | <-- Non-object memory --> |
59 _______________________________ | |
60 [ Python's object allocator ] | |
61+2 | ####### Object memory ####### | <------ Internal buffers ------> |
62 ______________________________________________________________ |
63 [ Python's raw memory allocator (PyMem_ API) ] |
64+1 | <----- Python memory (under PyMem manager's control) ------> | |
65 __________________________________________________________________
66 [ Underlying general-purpose allocator (ex: C library malloc) ]
67 0 | <------ Virtual memory allocated for the python process -------> |
68
69 =========================================================================
70 _______________________________________________________________________
71 [ OS-specific Virtual Memory Manager (VMM) ]
72-1 | <--- Kernel dynamic storage allocation & management (page-based) ---> |
73 __________________________________ __________________________________
74 [ ] [ ]
75-2 | <-- Physical memory: ROM/RAM --> | | <-- Secondary storage (swap) --> |
76
77*/
78/*==========================================================================*/
79
80/* A fast, special-purpose memory allocator for small blocks, to be used
81 on top of a general-purpose malloc -- heavily based on previous art. */
82
83/* Vladimir Marangozov -- August 2000 */
84
85/*
86 * "Memory management is where the rubber meets the road -- if we do the wrong
87 * thing at any level, the results will not be good. And if we don't make the
88 * levels work well together, we are in serious trouble." (1)
89 *
90 * (1) Paul R. Wilson, Mark S. Johnstone, Michael Neely, and David Boles,
91 * "Dynamic Storage Allocation: A Survey and Critical Review",
92 * in Proc. 1995 Int'l. Workshop on Memory Management, September 1995.
93 */
94
Antoine Pitrouc83ea132010-05-09 14:46:46 +000095/* #undef WITH_MEMORY_LIMITS */ /* disable mem limit checks */
Neil Schemenauera35c6882001-02-27 04:45:05 +000096
97/*==========================================================================*/
98
99/*
Neil Schemenauera35c6882001-02-27 04:45:05 +0000100 * Allocation strategy abstract:
101 *
102 * For small requests, the allocator sub-allocates <Big> blocks of memory.
Benjamin Petersond16e01c2014-02-04 10:20:26 -0500103 * Requests greater than SMALL_REQUEST_THRESHOLD bytes are routed to the
104 * system's allocator.
Tim Petersce7fb9b2002-03-23 00:28:57 +0000105 *
Neil Schemenauera35c6882001-02-27 04:45:05 +0000106 * Small requests are grouped in size classes spaced 8 bytes apart, due
107 * to the required valid alignment of the returned address. Requests of
108 * a particular size are serviced from memory pools of 4K (one VMM page).
109 * Pools are fragmented on demand and contain free lists of blocks of one
110 * particular size class. In other words, there is a fixed-size allocator
111 * for each size class. Free pools are shared by the different allocators
112 * thus minimizing the space reserved for a particular size class.
113 *
114 * This allocation strategy is a variant of what is known as "simple
115 * segregated storage based on array of free lists". The main drawback of
116 * simple segregated storage is that we might end up with lot of reserved
117 * memory for the different free lists, which degenerate in time. To avoid
118 * this, we partition each free list in pools and we share dynamically the
119 * reserved space between all free lists. This technique is quite efficient
120 * for memory intensive programs which allocate mainly small-sized blocks.
121 *
122 * For small requests we have the following table:
123 *
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000124 * Request in bytes Size of allocated block Size class idx
Neil Schemenauera35c6882001-02-27 04:45:05 +0000125 * ----------------------------------------------------------------
126 * 1-8 8 0
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000127 * 9-16 16 1
128 * 17-24 24 2
129 * 25-32 32 3
130 * 33-40 40 4
131 * 41-48 48 5
132 * 49-56 56 6
133 * 57-64 64 7
134 * 65-72 72 8
135 * ... ... ...
Benjamin Petersond16e01c2014-02-04 10:20:26 -0500136 * 497-504 504 62
137 * 505-512 512 63
Tim Petersce7fb9b2002-03-23 00:28:57 +0000138 *
Benjamin Petersond16e01c2014-02-04 10:20:26 -0500139 * 0, SMALL_REQUEST_THRESHOLD + 1 and up: routed to the underlying
140 * allocator.
Neil Schemenauera35c6882001-02-27 04:45:05 +0000141 */
142
143/*==========================================================================*/
144
145/*
146 * -- Main tunable settings section --
147 */
148
149/*
150 * Alignment of addresses returned to the user. 8-bytes alignment works
151 * on most current architectures (with 32-bit or 64-bit address busses).
152 * The alignment value is also used for grouping small requests in size
153 * classes spaced ALIGNMENT bytes apart.
154 *
155 * You shouldn't change this unless you know what you are doing.
156 */
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000157#define ALIGNMENT 8 /* must be 2^N */
158#define ALIGNMENT_SHIFT 3
159#define ALIGNMENT_MASK (ALIGNMENT - 1)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000160
Tim Peterse70ddf32002-04-05 04:32:29 +0000161/* Return the number of bytes in size class I, as a uint. */
162#define INDEX2SIZE(I) (((uint)(I) + 1) << ALIGNMENT_SHIFT)
163
Neil Schemenauera35c6882001-02-27 04:45:05 +0000164/*
165 * Max size threshold below which malloc requests are considered to be
166 * small enough in order to use preallocated memory pools. You can tune
167 * this value according to your application behaviour and memory needs.
168 *
169 * The following invariants must hold:
Benjamin Peterson1edd2f62015-07-29 22:18:16 -0700170 * 1) ALIGNMENT <= SMALL_REQUEST_THRESHOLD <= 512
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000171 * 2) SMALL_REQUEST_THRESHOLD is evenly divisible by ALIGNMENT
Neil Schemenauera35c6882001-02-27 04:45:05 +0000172 *
Benjamin Petersond16e01c2014-02-04 10:20:26 -0500173 * Note: a size threshold of 512 guarantees that newly created dictionaries
174 * will be allocated from preallocated memory pools on 64-bit.
175 *
Neil Schemenauera35c6882001-02-27 04:45:05 +0000176 * Although not required, for better performance and space efficiency,
177 * it is recommended that SMALL_REQUEST_THRESHOLD is set to a power of 2.
178 */
Benjamin Petersond16e01c2014-02-04 10:20:26 -0500179#define SMALL_REQUEST_THRESHOLD 512
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000180#define NB_SMALL_SIZE_CLASSES (SMALL_REQUEST_THRESHOLD / ALIGNMENT)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000181
182/*
183 * The system's VMM page size can be obtained on most unices with a
184 * getpagesize() call or deduced from various header files. To make
185 * things simpler, we assume that it is 4K, which is OK for most systems.
186 * It is probably better if this is the native page size, but it doesn't
Tim Petersecc6e6a2005-07-10 22:30:55 +0000187 * have to be. In theory, if SYSTEM_PAGE_SIZE is larger than the native page
188 * size, then `POOL_ADDR(p)->arenaindex' could rarely cause a segmentation
189 * violation fault. 4K is apparently OK for all the platforms that python
Martin v. Löwis8c140282002-10-26 15:01:53 +0000190 * currently targets.
Neil Schemenauera35c6882001-02-27 04:45:05 +0000191 */
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000192#define SYSTEM_PAGE_SIZE (4 * 1024)
193#define SYSTEM_PAGE_SIZE_MASK (SYSTEM_PAGE_SIZE - 1)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000194
195/*
196 * Maximum amount of memory managed by the allocator for small requests.
197 */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000198#ifdef WITH_MEMORY_LIMITS
199#ifndef SMALL_MEMORY_LIMIT
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000200#define SMALL_MEMORY_LIMIT (64 * 1024 * 1024) /* 64 MB -- more? */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000201#endif
202#endif
203
204/*
205 * The allocator sub-allocates <Big> blocks of memory (called arenas) aligned
206 * on a page boundary. This is a reserved virtual address space for the
Benjamin Petersond16e01c2014-02-04 10:20:26 -0500207 * current process (obtained through a malloc()/mmap() call). In no way this
208 * means that the memory arenas will be used entirely. A malloc(<Big>) is
209 * usually an address range reservation for <Big> bytes, unless all pages within
210 * this space are referenced subsequently. So malloc'ing big blocks and not
211 * using them does not mean "wasting memory". It's an addressable range
212 * wastage...
Neil Schemenauera35c6882001-02-27 04:45:05 +0000213 *
Benjamin Petersond16e01c2014-02-04 10:20:26 -0500214 * Arenas are allocated with mmap() on systems supporting anonymous memory
215 * mappings to reduce heap fragmentation.
Neil Schemenauera35c6882001-02-27 04:45:05 +0000216 */
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000217#define ARENA_SIZE (256 << 10) /* 256KB */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000218
219#ifdef WITH_MEMORY_LIMITS
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000220#define MAX_ARENAS (SMALL_MEMORY_LIMIT / ARENA_SIZE)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000221#endif
222
223/*
224 * Size of the pools used for small blocks. Should be a power of 2,
Tim Petersc2ce91a2002-03-30 21:36:04 +0000225 * between 1K and SYSTEM_PAGE_SIZE, that is: 1k, 2k, 4k.
Neil Schemenauera35c6882001-02-27 04:45:05 +0000226 */
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000227#define POOL_SIZE SYSTEM_PAGE_SIZE /* must be 2^N */
228#define POOL_SIZE_MASK SYSTEM_PAGE_SIZE_MASK
Neil Schemenauera35c6882001-02-27 04:45:05 +0000229
230/*
231 * -- End of tunable settings section --
232 */
233
234/*==========================================================================*/
235
236/*
237 * Locking
238 *
239 * To reduce lock contention, it would probably be better to refine the
240 * crude function locking with per size class locking. I'm not positive
241 * however, whether it's worth switching to such locking policy because
242 * of the performance penalty it might introduce.
243 *
244 * The following macros describe the simplest (should also be the fastest)
245 * lock object on a particular platform and the init/fini/lock/unlock
246 * operations on it. The locks defined here are not expected to be recursive
247 * because it is assumed that they will always be called in the order:
248 * INIT, [LOCK, UNLOCK]*, FINI.
249 */
250
251/*
252 * Python's threads are serialized, so object malloc locking is disabled.
253 */
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000254#define SIMPLELOCK_DECL(lock) /* simple lock declaration */
255#define SIMPLELOCK_INIT(lock) /* allocate (if needed) and initialize */
256#define SIMPLELOCK_FINI(lock) /* free/destroy an existing lock */
257#define SIMPLELOCK_LOCK(lock) /* acquire released lock */
258#define SIMPLELOCK_UNLOCK(lock) /* release acquired lock */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000259
260/*
261 * Basic types
262 * I don't care if these are defined in <sys/types.h> or elsewhere. Axiom.
263 */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000264#undef uchar
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000265#define uchar unsigned char /* assuming == 8 bits */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000266
Neil Schemenauera35c6882001-02-27 04:45:05 +0000267#undef uint
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000268#define uint unsigned int /* assuming >= 16 bits */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000269
270#undef ulong
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000271#define ulong unsigned long /* assuming >= 32 bits */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000272
Tim Petersd97a1c02002-03-30 06:09:22 +0000273#undef uptr
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000274#define uptr Py_uintptr_t
Tim Petersd97a1c02002-03-30 06:09:22 +0000275
Neil Schemenauera35c6882001-02-27 04:45:05 +0000276/* When you say memory, my mind reasons in terms of (pointers to) blocks */
277typedef uchar block;
278
Tim Peterse70ddf32002-04-05 04:32:29 +0000279/* Pool for small blocks. */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000280struct pool_header {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000281 union { block *_padding;
Stefan Krah918c90c2010-11-26 11:03:55 +0000282 uint count; } ref; /* number of allocated blocks */
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000283 block *freeblock; /* pool's free list head */
284 struct pool_header *nextpool; /* next pool of this size class */
285 struct pool_header *prevpool; /* previous pool "" */
286 uint arenaindex; /* index into arenas of base adr */
287 uint szidx; /* block size class index */
288 uint nextoffset; /* bytes to virgin block */
289 uint maxnextoffset; /* largest valid nextoffset */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000290};
291
292typedef struct pool_header *poolp;
293
Tim Peterscf79aac2006-03-16 01:14:46 +0000294/* Record keeping for arenas. */
295struct arena_object {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000296 /* The address of the arena, as returned by malloc. Note that 0
297 * will never be returned by a successful malloc, and is used
298 * here to mark an arena_object that doesn't correspond to an
299 * allocated arena.
300 */
301 uptr address;
Tim Peterscf79aac2006-03-16 01:14:46 +0000302
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000303 /* Pool-aligned pointer to the next pool to be carved off. */
304 block* pool_address;
Tim Peterscf79aac2006-03-16 01:14:46 +0000305
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000306 /* The number of available pools in the arena: free pools + never-
307 * allocated pools.
308 */
309 uint nfreepools;
Tim Peterscf79aac2006-03-16 01:14:46 +0000310
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000311 /* The total number of pools in the arena, whether or not available. */
312 uint ntotalpools;
Tim Peterscf79aac2006-03-16 01:14:46 +0000313
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000314 /* Singly-linked list of available pools. */
315 struct pool_header* freepools;
Tim Peterscf79aac2006-03-16 01:14:46 +0000316
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000317 /* Whenever this arena_object is not associated with an allocated
318 * arena, the nextarena member is used to link all unassociated
319 * arena_objects in the singly-linked `unused_arena_objects` list.
320 * The prevarena member is unused in this case.
321 *
322 * When this arena_object is associated with an allocated arena
323 * with at least one available pool, both members are used in the
324 * doubly-linked `usable_arenas` list, which is maintained in
325 * increasing order of `nfreepools` values.
326 *
327 * Else this arena_object is associated with an allocated arena
328 * all of whose pools are in use. `nextarena` and `prevarena`
329 * are both meaningless in this case.
330 */
331 struct arena_object* nextarena;
332 struct arena_object* prevarena;
Tim Peterscf79aac2006-03-16 01:14:46 +0000333};
334
Neil Schemenauera35c6882001-02-27 04:45:05 +0000335#undef ROUNDUP
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000336#define ROUNDUP(x) (((x) + ALIGNMENT_MASK) & ~ALIGNMENT_MASK)
337#define POOL_OVERHEAD ROUNDUP(sizeof(struct pool_header))
Neil Schemenauera35c6882001-02-27 04:45:05 +0000338
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000339#define DUMMY_SIZE_IDX 0xffff /* size class of newly cached pools */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000340
Tim Petersd97a1c02002-03-30 06:09:22 +0000341/* Round pointer P down to the closest pool-aligned address <= P, as a poolp */
Tim Peterse70ddf32002-04-05 04:32:29 +0000342#define POOL_ADDR(P) ((poolp)((uptr)(P) & ~(uptr)POOL_SIZE_MASK))
343
Tim Peters16bcb6b2002-04-05 05:45:31 +0000344/* Return total number of blocks in pool of size index I, as a uint. */
345#define NUMBLOCKS(I) ((uint)(POOL_SIZE - POOL_OVERHEAD) / INDEX2SIZE(I))
Tim Petersd97a1c02002-03-30 06:09:22 +0000346
Neil Schemenauera35c6882001-02-27 04:45:05 +0000347/*==========================================================================*/
348
349/*
350 * This malloc lock
351 */
Jeremy Hyltond1fedb62002-07-18 18:49:52 +0000352SIMPLELOCK_DECL(_malloc_lock)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000353#define LOCK() SIMPLELOCK_LOCK(_malloc_lock)
354#define UNLOCK() SIMPLELOCK_UNLOCK(_malloc_lock)
355#define LOCK_INIT() SIMPLELOCK_INIT(_malloc_lock)
356#define LOCK_FINI() SIMPLELOCK_FINI(_malloc_lock)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000357
358/*
Tim Peters1e16db62002-03-31 01:05:22 +0000359 * Pool table -- headed, circular, doubly-linked lists of partially used pools.
360
361This is involved. For an index i, usedpools[i+i] is the header for a list of
362all partially used pools holding small blocks with "size class idx" i. So
363usedpools[0] corresponds to blocks of size 8, usedpools[2] to blocks of size
36416, and so on: index 2*i <-> blocks of size (i+1)<<ALIGNMENT_SHIFT.
365
Tim Peterscf79aac2006-03-16 01:14:46 +0000366Pools are carved off an arena's highwater mark (an arena_object's pool_address
367member) as needed. Once carved off, a pool is in one of three states forever
368after:
Tim Peters1e16db62002-03-31 01:05:22 +0000369
Tim Peters338e0102002-04-01 19:23:44 +0000370used == partially used, neither empty nor full
371 At least one block in the pool is currently allocated, and at least one
372 block in the pool is not currently allocated (note this implies a pool
373 has room for at least two blocks).
374 This is a pool's initial state, as a pool is created only when malloc
375 needs space.
376 The pool holds blocks of a fixed size, and is in the circular list headed
377 at usedpools[i] (see above). It's linked to the other used pools of the
378 same size class via the pool_header's nextpool and prevpool members.
379 If all but one block is currently allocated, a malloc can cause a
380 transition to the full state. If all but one block is not currently
381 allocated, a free can cause a transition to the empty state.
Tim Peters1e16db62002-03-31 01:05:22 +0000382
Tim Peters338e0102002-04-01 19:23:44 +0000383full == all the pool's blocks are currently allocated
384 On transition to full, a pool is unlinked from its usedpools[] list.
385 It's not linked to from anything then anymore, and its nextpool and
386 prevpool members are meaningless until it transitions back to used.
387 A free of a block in a full pool puts the pool back in the used state.
388 Then it's linked in at the front of the appropriate usedpools[] list, so
389 that the next allocation for its size class will reuse the freed block.
390
391empty == all the pool's blocks are currently available for allocation
392 On transition to empty, a pool is unlinked from its usedpools[] list,
Tim Peterscf79aac2006-03-16 01:14:46 +0000393 and linked to the front of its arena_object's singly-linked freepools list,
Tim Peters338e0102002-04-01 19:23:44 +0000394 via its nextpool member. The prevpool member has no meaning in this case.
395 Empty pools have no inherent size class: the next time a malloc finds
396 an empty list in usedpools[], it takes the first pool off of freepools.
397 If the size class needed happens to be the same as the size class the pool
Tim Peterse70ddf32002-04-05 04:32:29 +0000398 last had, some pool initialization can be skipped.
Tim Peters338e0102002-04-01 19:23:44 +0000399
400
401Block Management
402
403Blocks within pools are again carved out as needed. pool->freeblock points to
404the start of a singly-linked list of free blocks within the pool. When a
405block is freed, it's inserted at the front of its pool's freeblock list. Note
406that the available blocks in a pool are *not* linked all together when a pool
Tim Peterse70ddf32002-04-05 04:32:29 +0000407is initialized. Instead only "the first two" (lowest addresses) blocks are
408set up, returning the first such block, and setting pool->freeblock to a
409one-block list holding the second such block. This is consistent with that
410pymalloc strives at all levels (arena, pool, and block) never to touch a piece
411of memory until it's actually needed.
412
413So long as a pool is in the used state, we're certain there *is* a block
Tim Peters52aefc82002-04-11 06:36:45 +0000414available for allocating, and pool->freeblock is not NULL. If pool->freeblock
415points to the end of the free list before we've carved the entire pool into
416blocks, that means we simply haven't yet gotten to one of the higher-address
417blocks. The offset from the pool_header to the start of "the next" virgin
418block is stored in the pool_header nextoffset member, and the largest value
419of nextoffset that makes sense is stored in the maxnextoffset member when a
420pool is initialized. All the blocks in a pool have been passed out at least
421once when and only when nextoffset > maxnextoffset.
Tim Peters338e0102002-04-01 19:23:44 +0000422
Tim Peters1e16db62002-03-31 01:05:22 +0000423
424Major obscurity: While the usedpools vector is declared to have poolp
425entries, it doesn't really. It really contains two pointers per (conceptual)
426poolp entry, the nextpool and prevpool members of a pool_header. The
427excruciating initialization code below fools C so that
428
429 usedpool[i+i]
430
431"acts like" a genuine poolp, but only so long as you only reference its
432nextpool and prevpool members. The "- 2*sizeof(block *)" gibberish is
433compensating for that a pool_header's nextpool and prevpool members
434immediately follow a pool_header's first two members:
435
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000436 union { block *_padding;
Stefan Krah918c90c2010-11-26 11:03:55 +0000437 uint count; } ref;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000438 block *freeblock;
Tim Peters1e16db62002-03-31 01:05:22 +0000439
440each of which consume sizeof(block *) bytes. So what usedpools[i+i] really
441contains is a fudged-up pointer p such that *if* C believes it's a poolp
442pointer, then p->nextpool and p->prevpool are both p (meaning that the headed
443circular list is empty).
444
445It's unclear why the usedpools setup is so convoluted. It could be to
446minimize the amount of cache required to hold this heavily-referenced table
447(which only *needs* the two interpool pointer members of a pool_header). OTOH,
448referencing code has to remember to "double the index" and doing so isn't
449free, usedpools[0] isn't a strictly legal pointer, and we're crucially relying
450on that C doesn't insert any padding anywhere in a pool_header at or before
451the prevpool member.
452**************************************************************************** */
453
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000454#define PTA(x) ((poolp )((uchar *)&(usedpools[2*(x)]) - 2*sizeof(block *)))
455#define PT(x) PTA(x), PTA(x)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000456
457static poolp usedpools[2 * ((NB_SMALL_SIZE_CLASSES + 7) / 8) * 8] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000458 PT(0), PT(1), PT(2), PT(3), PT(4), PT(5), PT(6), PT(7)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000459#if NB_SMALL_SIZE_CLASSES > 8
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000460 , PT(8), PT(9), PT(10), PT(11), PT(12), PT(13), PT(14), PT(15)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000461#if NB_SMALL_SIZE_CLASSES > 16
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000462 , PT(16), PT(17), PT(18), PT(19), PT(20), PT(21), PT(22), PT(23)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000463#if NB_SMALL_SIZE_CLASSES > 24
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000464 , PT(24), PT(25), PT(26), PT(27), PT(28), PT(29), PT(30), PT(31)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000465#if NB_SMALL_SIZE_CLASSES > 32
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000466 , PT(32), PT(33), PT(34), PT(35), PT(36), PT(37), PT(38), PT(39)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000467#if NB_SMALL_SIZE_CLASSES > 40
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000468 , PT(40), PT(41), PT(42), PT(43), PT(44), PT(45), PT(46), PT(47)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000469#if NB_SMALL_SIZE_CLASSES > 48
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000470 , PT(48), PT(49), PT(50), PT(51), PT(52), PT(53), PT(54), PT(55)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000471#if NB_SMALL_SIZE_CLASSES > 56
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000472 , PT(56), PT(57), PT(58), PT(59), PT(60), PT(61), PT(62), PT(63)
Benjamin Petersond16e01c2014-02-04 10:20:26 -0500473#if NB_SMALL_SIZE_CLASSES > 64
474#error "NB_SMALL_SIZE_CLASSES should be less than 64"
475#endif /* NB_SMALL_SIZE_CLASSES > 64 */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000476#endif /* NB_SMALL_SIZE_CLASSES > 56 */
477#endif /* NB_SMALL_SIZE_CLASSES > 48 */
478#endif /* NB_SMALL_SIZE_CLASSES > 40 */
479#endif /* NB_SMALL_SIZE_CLASSES > 32 */
480#endif /* NB_SMALL_SIZE_CLASSES > 24 */
481#endif /* NB_SMALL_SIZE_CLASSES > 16 */
482#endif /* NB_SMALL_SIZE_CLASSES > 8 */
483};
484
Tim Peterscf79aac2006-03-16 01:14:46 +0000485/*==========================================================================
486Arena management.
Neil Schemenauera35c6882001-02-27 04:45:05 +0000487
Tim Peterscf79aac2006-03-16 01:14:46 +0000488`arenas` is a vector of arena_objects. It contains maxarenas entries, some of
489which may not be currently used (== they're arena_objects that aren't
490currently associated with an allocated arena). Note that arenas proper are
491separately malloc'ed.
Neil Schemenauera35c6882001-02-27 04:45:05 +0000492
Tim Peterscf79aac2006-03-16 01:14:46 +0000493Prior to Python 2.5, arenas were never free()'ed. Starting with Python 2.5,
494we do try to free() arenas, and use some mild heuristic strategies to increase
495the likelihood that arenas eventually can be freed.
496
497unused_arena_objects
498
499 This is a singly-linked list of the arena_objects that are currently not
500 being used (no arena is associated with them). Objects are taken off the
501 head of the list in new_arena(), and are pushed on the head of the list in
502 PyObject_Free() when the arena is empty. Key invariant: an arena_object
503 is on this list if and only if its .address member is 0.
504
505usable_arenas
506
507 This is a doubly-linked list of the arena_objects associated with arenas
508 that have pools available. These pools are either waiting to be reused,
509 or have not been used before. The list is sorted to have the most-
510 allocated arenas first (ascending order based on the nfreepools member).
511 This means that the next allocation will come from a heavily used arena,
512 which gives the nearly empty arenas a chance to be returned to the system.
513 In my unscientific tests this dramatically improved the number of arenas
514 that could be freed.
515
516Note that an arena_object associated with an arena all of whose pools are
517currently in use isn't on either list.
518*/
519
520/* Array of objects used to track chunks of memory (arenas). */
521static struct arena_object* arenas = NULL;
522/* Number of slots currently allocated in the `arenas` vector. */
Tim Peters1d99af82002-03-30 10:35:09 +0000523static uint maxarenas = 0;
Tim Petersd97a1c02002-03-30 06:09:22 +0000524
Tim Peterscf79aac2006-03-16 01:14:46 +0000525/* The head of the singly-linked, NULL-terminated list of available
526 * arena_objects.
Tim Petersd97a1c02002-03-30 06:09:22 +0000527 */
Tim Peterscf79aac2006-03-16 01:14:46 +0000528static struct arena_object* unused_arena_objects = NULL;
529
530/* The head of the doubly-linked, NULL-terminated at each end, list of
531 * arena_objects associated with arenas that have pools available.
532 */
533static struct arena_object* usable_arenas = NULL;
534
535/* How many arena_objects do we initially allocate?
536 * 16 = can allocate 16 arenas = 16 * ARENA_SIZE = 4MB before growing the
537 * `arenas` vector.
538 */
539#define INITIAL_ARENA_OBJECTS 16
540
541/* Number of arenas allocated that haven't been free()'d. */
Tim Peters9ea89d22006-06-04 03:26:02 +0000542static size_t narenas_currently_allocated = 0;
Tim Peterscf79aac2006-03-16 01:14:46 +0000543
544#ifdef PYMALLOC_DEBUG
545/* Total number of times malloc() called to allocate an arena. */
Tim Peters9ea89d22006-06-04 03:26:02 +0000546static size_t ntimes_arena_allocated = 0;
Tim Peterscf79aac2006-03-16 01:14:46 +0000547/* High water mark (max value ever seen) for narenas_currently_allocated. */
Tim Peters9ea89d22006-06-04 03:26:02 +0000548static size_t narenas_highwater = 0;
Tim Peterscf79aac2006-03-16 01:14:46 +0000549#endif
550
551/* Allocate a new arena. If we run out of memory, return NULL. Else
552 * allocate a new arena, and return the address of an arena_object
553 * describing the new arena. It's expected that the caller will set
554 * `usable_arenas` to the return value.
555 */
556static struct arena_object*
Tim Petersd97a1c02002-03-30 06:09:22 +0000557new_arena(void)
558{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000559 struct arena_object* arenaobj;
560 uint excess; /* number of bytes above pool alignment */
Charles-François Natalicee4f032014-06-19 22:42:51 +0100561 void *address;
562 int err;
Tim Petersd97a1c02002-03-30 06:09:22 +0000563
Tim Peters0e871182002-04-13 08:29:14 +0000564#ifdef PYMALLOC_DEBUG
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000565 if (Py_GETENV("PYTHONMALLOCSTATS"))
566 _PyObject_DebugMallocStats();
Tim Peters0e871182002-04-13 08:29:14 +0000567#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000568 if (unused_arena_objects == NULL) {
569 uint i;
570 uint numarenas;
571 size_t nbytes;
Tim Peters0e871182002-04-13 08:29:14 +0000572
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000573 /* Double the number of arena objects on each allocation.
574 * Note that it's possible for `numarenas` to overflow.
575 */
576 numarenas = maxarenas ? maxarenas << 1 : INITIAL_ARENA_OBJECTS;
577 if (numarenas <= maxarenas)
578 return NULL; /* overflow */
Martin v. Löwis9fa5a282008-09-11 06:53:30 +0000579#if SIZEOF_SIZE_T <= SIZEOF_INT
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000580 if (numarenas > PY_SIZE_MAX / sizeof(*arenas))
581 return NULL; /* overflow */
Martin v. Löwis9fa5a282008-09-11 06:53:30 +0000582#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000583 nbytes = numarenas * sizeof(*arenas);
584 arenaobj = (struct arena_object *)realloc(arenas, nbytes);
585 if (arenaobj == NULL)
586 return NULL;
587 arenas = arenaobj;
Tim Peterscf79aac2006-03-16 01:14:46 +0000588
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000589 /* We might need to fix pointers that were copied. However,
590 * new_arena only gets called when all the pages in the
591 * previous arenas are full. Thus, there are *no* pointers
592 * into the old array. Thus, we don't have to worry about
593 * invalid pointers. Just to be sure, some asserts:
594 */
595 assert(usable_arenas == NULL);
596 assert(unused_arena_objects == NULL);
Tim Peterscf79aac2006-03-16 01:14:46 +0000597
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000598 /* Put the new arenas on the unused_arena_objects list. */
599 for (i = maxarenas; i < numarenas; ++i) {
600 arenas[i].address = 0; /* mark as unassociated */
601 arenas[i].nextarena = i < numarenas - 1 ?
602 &arenas[i+1] : NULL;
603 }
Tim Peterscf79aac2006-03-16 01:14:46 +0000604
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000605 /* Update globals. */
606 unused_arena_objects = &arenas[maxarenas];
607 maxarenas = numarenas;
608 }
Tim Petersd97a1c02002-03-30 06:09:22 +0000609
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000610 /* Take the next available arena object off the head of the list. */
611 assert(unused_arena_objects != NULL);
612 arenaobj = unused_arena_objects;
613 unused_arena_objects = arenaobj->nextarena;
614 assert(arenaobj->address == 0);
Benjamin Petersond16e01c2014-02-04 10:20:26 -0500615#ifdef ARENAS_USE_MMAP
Charles-François Natalicee4f032014-06-19 22:42:51 +0100616 address = mmap(NULL, ARENA_SIZE, PROT_READ|PROT_WRITE,
617 MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
618 err = (address == MAP_FAILED);
Benjamin Petersond16e01c2014-02-04 10:20:26 -0500619#else
Charles-François Natalicee4f032014-06-19 22:42:51 +0100620 address = malloc(ARENA_SIZE);
621 err = (address == 0);
Benjamin Petersond16e01c2014-02-04 10:20:26 -0500622#endif
Charles-François Natalicee4f032014-06-19 22:42:51 +0100623 if (err) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000624 /* The allocation failed: return NULL after putting the
625 * arenaobj back.
626 */
627 arenaobj->nextarena = unused_arena_objects;
628 unused_arena_objects = arenaobj;
629 return NULL;
630 }
Charles-François Natalicee4f032014-06-19 22:42:51 +0100631 arenaobj->address = (uptr)address;
Tim Petersd97a1c02002-03-30 06:09:22 +0000632
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000633 ++narenas_currently_allocated;
Tim Peterscf79aac2006-03-16 01:14:46 +0000634#ifdef PYMALLOC_DEBUG
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000635 ++ntimes_arena_allocated;
636 if (narenas_currently_allocated > narenas_highwater)
637 narenas_highwater = narenas_currently_allocated;
Tim Peterscf79aac2006-03-16 01:14:46 +0000638#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000639 arenaobj->freepools = NULL;
640 /* pool_address <- first pool-aligned address in the arena
641 nfreepools <- number of whole pools that fit after alignment */
642 arenaobj->pool_address = (block*)arenaobj->address;
643 arenaobj->nfreepools = ARENA_SIZE / POOL_SIZE;
644 assert(POOL_SIZE * arenaobj->nfreepools == ARENA_SIZE);
645 excess = (uint)(arenaobj->address & POOL_SIZE_MASK);
646 if (excess != 0) {
647 --arenaobj->nfreepools;
648 arenaobj->pool_address += POOL_SIZE - excess;
649 }
650 arenaobj->ntotalpools = arenaobj->nfreepools;
Tim Peterscf79aac2006-03-16 01:14:46 +0000651
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000652 return arenaobj;
Tim Petersd97a1c02002-03-30 06:09:22 +0000653}
654
Tim Peterscf79aac2006-03-16 01:14:46 +0000655/*
656Py_ADDRESS_IN_RANGE(P, POOL)
657
658Return true if and only if P is an address that was allocated by pymalloc.
659POOL must be the pool address associated with P, i.e., POOL = POOL_ADDR(P)
660(the caller is asked to compute this because the macro expands POOL more than
661once, and for efficiency it's best for the caller to assign POOL_ADDR(P) to a
662variable and pass the latter to the macro; because Py_ADDRESS_IN_RANGE is
663called on every alloc/realloc/free, micro-efficiency is important here).
664
665Tricky: Let B be the arena base address associated with the pool, B =
666arenas[(POOL)->arenaindex].address. Then P belongs to the arena if and only if
667
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000668 B <= P < B + ARENA_SIZE
Tim Peterscf79aac2006-03-16 01:14:46 +0000669
670Subtracting B throughout, this is true iff
671
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000672 0 <= P-B < ARENA_SIZE
Tim Peterscf79aac2006-03-16 01:14:46 +0000673
674By using unsigned arithmetic, the "0 <=" half of the test can be skipped.
675
676Obscure: A PyMem "free memory" function can call the pymalloc free or realloc
677before the first arena has been allocated. `arenas` is still NULL in that
678case. We're relying on that maxarenas is also 0 in that case, so that
679(POOL)->arenaindex < maxarenas must be false, saving us from trying to index
680into a NULL arenas.
681
682Details: given P and POOL, the arena_object corresponding to P is AO =
683arenas[(POOL)->arenaindex]. Suppose obmalloc controls P. Then (barring wild
684stores, etc), POOL is the correct address of P's pool, AO.address is the
685correct base address of the pool's arena, and P must be within ARENA_SIZE of
686AO.address. In addition, AO.address is not 0 (no arena can start at address 0
687(NULL)). Therefore Py_ADDRESS_IN_RANGE correctly reports that obmalloc
688controls P.
689
690Now suppose obmalloc does not control P (e.g., P was obtained via a direct
691call to the system malloc() or realloc()). (POOL)->arenaindex may be anything
692in this case -- it may even be uninitialized trash. If the trash arenaindex
693is >= maxarenas, the macro correctly concludes at once that obmalloc doesn't
694control P.
695
696Else arenaindex is < maxarena, and AO is read up. If AO corresponds to an
697allocated arena, obmalloc controls all the memory in slice AO.address :
698AO.address+ARENA_SIZE. By case assumption, P is not controlled by obmalloc,
699so P doesn't lie in that slice, so the macro correctly reports that P is not
700controlled by obmalloc.
701
702Finally, if P is not controlled by obmalloc and AO corresponds to an unused
703arena_object (one not currently associated with an allocated arena),
704AO.address is 0, and the second test in the macro reduces to:
705
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000706 P < ARENA_SIZE
Tim Peterscf79aac2006-03-16 01:14:46 +0000707
708If P >= ARENA_SIZE (extremely likely), the macro again correctly concludes
709that P is not controlled by obmalloc. However, if P < ARENA_SIZE, this part
710of the test still passes, and the third clause (AO.address != 0) is necessary
711to get the correct result: AO.address is 0 in this case, so the macro
712correctly reports that P is not controlled by obmalloc (despite that P lies in
713slice AO.address : AO.address + ARENA_SIZE).
714
715Note: The third (AO.address != 0) clause was added in Python 2.5. Before
7162.5, arenas were never free()'ed, and an arenaindex < maxarena always
717corresponded to a currently-allocated arena, so the "P is not controlled by
718obmalloc, AO corresponds to an unused arena_object, and P < ARENA_SIZE" case
719was impossible.
720
721Note that the logic is excruciating, and reading up possibly uninitialized
722memory when P is not controlled by obmalloc (to get at (POOL)->arenaindex)
723creates problems for some memory debuggers. The overwhelming advantage is
724that this test determines whether an arbitrary address is controlled by
725obmalloc in a small constant time, independent of the number of arenas
726obmalloc controls. Since this test is needed at every entry point, it's
727extremely desirable that it be this fast.
Antoine Pitrou5a72e762011-01-07 21:49:44 +0000728
729Since Py_ADDRESS_IN_RANGE may be reading from memory which was not allocated
730by Python, it is important that (POOL)->arenaindex is read only once, as
731another thread may be concurrently modifying the value without holding the
732GIL. To accomplish this, the arenaindex_temp variable is used to store
733(POOL)->arenaindex for the duration of the Py_ADDRESS_IN_RANGE macro's
734execution. The caller of the macro is responsible for declaring this
735variable.
Tim Peterscf79aac2006-03-16 01:14:46 +0000736*/
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000737#define Py_ADDRESS_IN_RANGE(P, POOL) \
Antoine Pitrou5a72e762011-01-07 21:49:44 +0000738 ((arenaindex_temp = (POOL)->arenaindex) < maxarenas && \
739 (uptr)(P) - arenas[arenaindex_temp].address < (uptr)ARENA_SIZE && \
740 arenas[arenaindex_temp].address != 0)
Tim Peterscf79aac2006-03-16 01:14:46 +0000741
Neal Norwitz7eb3c912004-06-06 19:20:22 +0000742
743/* This is only useful when running memory debuggers such as
744 * Purify or Valgrind. Uncomment to use.
745 *
Martin v. Löwis68192102007-07-21 06:55:02 +0000746#define Py_USING_MEMORY_DEBUGGER
Martin v. Löwise86b07c2008-09-25 04:12:50 +0000747 */
Neal Norwitz7eb3c912004-06-06 19:20:22 +0000748
749#ifdef Py_USING_MEMORY_DEBUGGER
750
751/* Py_ADDRESS_IN_RANGE may access uninitialized memory by design
752 * This leads to thousands of spurious warnings when using
753 * Purify or Valgrind. By making a function, we can easily
754 * suppress the uninitialized memory reads in this one function.
755 * So we won't ignore real errors elsewhere.
756 *
757 * Disable the macro and use a function.
758 */
759
760#undef Py_ADDRESS_IN_RANGE
761
Neal Norwitzab772272006-10-28 21:21:00 +0000762#if defined(__GNUC__) && ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 1) || \
Stefan Krah918c90c2010-11-26 11:03:55 +0000763 (__GNUC__ >= 4))
Neal Norwitze5e5aa42005-11-13 18:55:39 +0000764#define Py_NO_INLINE __attribute__((__noinline__))
765#else
766#define Py_NO_INLINE
767#endif
768
769/* Don't make static, to try to ensure this isn't inlined. */
770int Py_ADDRESS_IN_RANGE(void *P, poolp pool) Py_NO_INLINE;
771#undef Py_NO_INLINE
Neal Norwitz7eb3c912004-06-06 19:20:22 +0000772#endif
Tim Peters338e0102002-04-01 19:23:44 +0000773
Neil Schemenauera35c6882001-02-27 04:45:05 +0000774/*==========================================================================*/
775
Tim Peters84c1b972002-04-04 04:44:32 +0000776/* malloc. Note that nbytes==0 tries to return a non-NULL pointer, distinct
777 * from all other currently live pointers. This may not be possible.
778 */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000779
780/*
781 * The basic blocks are ordered by decreasing execution frequency,
782 * which minimizes the number of jumps in the most common cases,
783 * improves branching prediction and instruction scheduling (small
784 * block allocations typically result in a couple of instructions).
785 * Unless the optimizer reorders everything, being too smart...
786 */
787
Neil Schemenauerd2560cd2002-04-12 03:10:20 +0000788#undef PyObject_Malloc
Neil Schemenauera35c6882001-02-27 04:45:05 +0000789void *
Neil Schemenauerd2560cd2002-04-12 03:10:20 +0000790PyObject_Malloc(size_t nbytes)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000791{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000792 block *bp;
793 poolp pool;
794 poolp next;
795 uint size;
Neil Schemenauera35c6882001-02-27 04:45:05 +0000796
Benjamin Peterson91c12eb2009-12-03 02:52:39 +0000797#ifdef WITH_VALGRIND
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000798 if (UNLIKELY(running_on_valgrind == -1))
799 running_on_valgrind = RUNNING_ON_VALGRIND;
800 if (UNLIKELY(running_on_valgrind))
801 goto redirect;
Benjamin Peterson91c12eb2009-12-03 02:52:39 +0000802#endif
803
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000804 /*
805 * Limit ourselves to PY_SSIZE_T_MAX bytes to prevent security holes.
806 * Most python internals blindly use a signed Py_ssize_t to track
807 * things without checking for overflows or negatives.
808 * As size_t is unsigned, checking for nbytes < 0 is not required.
809 */
810 if (nbytes > PY_SSIZE_T_MAX)
811 return NULL;
Gregory P. Smith0470bab2008-07-22 04:46:32 +0000812
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000813 /*
814 * This implicitly redirects malloc(0).
815 */
816 if ((nbytes - 1) < SMALL_REQUEST_THRESHOLD) {
817 LOCK();
818 /*
819 * Most frequent paths first
820 */
821 size = (uint)(nbytes - 1) >> ALIGNMENT_SHIFT;
822 pool = usedpools[size + size];
823 if (pool != pool->nextpool) {
824 /*
825 * There is a used pool for this size class.
826 * Pick up the head block of its free list.
827 */
828 ++pool->ref.count;
829 bp = pool->freeblock;
830 assert(bp != NULL);
831 if ((pool->freeblock = *(block **)bp) != NULL) {
832 UNLOCK();
833 return (void *)bp;
834 }
835 /*
836 * Reached the end of the free list, try to extend it.
837 */
838 if (pool->nextoffset <= pool->maxnextoffset) {
839 /* There is room for another block. */
840 pool->freeblock = (block*)pool +
841 pool->nextoffset;
842 pool->nextoffset += INDEX2SIZE(size);
843 *(block **)(pool->freeblock) = NULL;
844 UNLOCK();
845 return (void *)bp;
846 }
847 /* Pool is full, unlink from used pools. */
848 next = pool->nextpool;
849 pool = pool->prevpool;
850 next->prevpool = pool;
851 pool->nextpool = next;
852 UNLOCK();
853 return (void *)bp;
854 }
Tim Peterscf79aac2006-03-16 01:14:46 +0000855
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000856 /* There isn't a pool of the right size class immediately
857 * available: use a free pool.
858 */
859 if (usable_arenas == NULL) {
860 /* No arena has a free pool: allocate a new arena. */
Tim Peterscf79aac2006-03-16 01:14:46 +0000861#ifdef WITH_MEMORY_LIMITS
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000862 if (narenas_currently_allocated >= MAX_ARENAS) {
863 UNLOCK();
864 goto redirect;
865 }
Tim Peterscf79aac2006-03-16 01:14:46 +0000866#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000867 usable_arenas = new_arena();
868 if (usable_arenas == NULL) {
869 UNLOCK();
870 goto redirect;
871 }
872 usable_arenas->nextarena =
873 usable_arenas->prevarena = NULL;
874 }
875 assert(usable_arenas->address != 0);
Tim Peterscf79aac2006-03-16 01:14:46 +0000876
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000877 /* Try to get a cached free pool. */
878 pool = usable_arenas->freepools;
879 if (pool != NULL) {
880 /* Unlink from cached pools. */
881 usable_arenas->freepools = pool->nextpool;
Tim Peterscf79aac2006-03-16 01:14:46 +0000882
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000883 /* This arena already had the smallest nfreepools
884 * value, so decreasing nfreepools doesn't change
885 * that, and we don't need to rearrange the
886 * usable_arenas list. However, if the arena has
887 * become wholly allocated, we need to remove its
888 * arena_object from usable_arenas.
889 */
890 --usable_arenas->nfreepools;
891 if (usable_arenas->nfreepools == 0) {
892 /* Wholly allocated: remove. */
893 assert(usable_arenas->freepools == NULL);
894 assert(usable_arenas->nextarena == NULL ||
895 usable_arenas->nextarena->prevarena ==
896 usable_arenas);
Tim Peterscf79aac2006-03-16 01:14:46 +0000897
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000898 usable_arenas = usable_arenas->nextarena;
899 if (usable_arenas != NULL) {
900 usable_arenas->prevarena = NULL;
901 assert(usable_arenas->address != 0);
902 }
903 }
904 else {
905 /* nfreepools > 0: it must be that freepools
906 * isn't NULL, or that we haven't yet carved
907 * off all the arena's pools for the first
908 * time.
909 */
910 assert(usable_arenas->freepools != NULL ||
911 usable_arenas->pool_address <=
912 (block*)usable_arenas->address +
913 ARENA_SIZE - POOL_SIZE);
914 }
915 init_pool:
916 /* Frontlink to used pools. */
917 next = usedpools[size + size]; /* == prev */
918 pool->nextpool = next;
919 pool->prevpool = next;
920 next->nextpool = pool;
921 next->prevpool = pool;
922 pool->ref.count = 1;
923 if (pool->szidx == size) {
924 /* Luckily, this pool last contained blocks
925 * of the same size class, so its header
926 * and free list are already initialized.
927 */
928 bp = pool->freeblock;
929 pool->freeblock = *(block **)bp;
930 UNLOCK();
931 return (void *)bp;
932 }
933 /*
934 * Initialize the pool header, set up the free list to
935 * contain just the second block, and return the first
936 * block.
937 */
938 pool->szidx = size;
939 size = INDEX2SIZE(size);
940 bp = (block *)pool + POOL_OVERHEAD;
941 pool->nextoffset = POOL_OVERHEAD + (size << 1);
942 pool->maxnextoffset = POOL_SIZE - size;
943 pool->freeblock = bp + size;
944 *(block **)(pool->freeblock) = NULL;
945 UNLOCK();
946 return (void *)bp;
947 }
Tim Peterscf79aac2006-03-16 01:14:46 +0000948
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000949 /* Carve off a new pool. */
950 assert(usable_arenas->nfreepools > 0);
951 assert(usable_arenas->freepools == NULL);
952 pool = (poolp)usable_arenas->pool_address;
953 assert((block*)pool <= (block*)usable_arenas->address +
954 ARENA_SIZE - POOL_SIZE);
955 pool->arenaindex = usable_arenas - arenas;
956 assert(&arenas[pool->arenaindex] == usable_arenas);
957 pool->szidx = DUMMY_SIZE_IDX;
958 usable_arenas->pool_address += POOL_SIZE;
959 --usable_arenas->nfreepools;
Tim Peterscf79aac2006-03-16 01:14:46 +0000960
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000961 if (usable_arenas->nfreepools == 0) {
962 assert(usable_arenas->nextarena == NULL ||
963 usable_arenas->nextarena->prevarena ==
964 usable_arenas);
965 /* Unlink the arena: it is completely allocated. */
966 usable_arenas = usable_arenas->nextarena;
967 if (usable_arenas != NULL) {
968 usable_arenas->prevarena = NULL;
969 assert(usable_arenas->address != 0);
970 }
971 }
Tim Peterscf79aac2006-03-16 01:14:46 +0000972
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000973 goto init_pool;
974 }
Neil Schemenauera35c6882001-02-27 04:45:05 +0000975
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000976 /* The small block allocator ends here. */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000977
Tim Petersd97a1c02002-03-30 06:09:22 +0000978redirect:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000979 /* Redirect the original request to the underlying (libc) allocator.
980 * We jump here on bigger requests, on error in the code above (as a
981 * last chance to serve the request) or when the max memory limit
982 * has been reached.
983 */
984 if (nbytes == 0)
985 nbytes = 1;
986 return (void *)malloc(nbytes);
Neil Schemenauera35c6882001-02-27 04:45:05 +0000987}
988
989/* free */
990
Neil Schemenauerd2560cd2002-04-12 03:10:20 +0000991#undef PyObject_Free
Benjamin Petersonb529c242015-04-26 20:33:38 -0400992ATTRIBUTE_NO_ADDRESS_SAFETY_ANALYSIS
Neil Schemenauera35c6882001-02-27 04:45:05 +0000993void
Neil Schemenauerd2560cd2002-04-12 03:10:20 +0000994PyObject_Free(void *p)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000995{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000996 poolp pool;
997 block *lastfree;
998 poolp next, prev;
999 uint size;
Antoine Pitrou5a72e762011-01-07 21:49:44 +00001000#ifndef Py_USING_MEMORY_DEBUGGER
1001 uint arenaindex_temp;
1002#endif
Neil Schemenauera35c6882001-02-27 04:45:05 +00001003
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001004 if (p == NULL) /* free(NULL) has no effect */
1005 return;
Neil Schemenauera35c6882001-02-27 04:45:05 +00001006
Benjamin Peterson91c12eb2009-12-03 02:52:39 +00001007#ifdef WITH_VALGRIND
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001008 if (UNLIKELY(running_on_valgrind > 0))
1009 goto redirect;
Benjamin Peterson91c12eb2009-12-03 02:52:39 +00001010#endif
1011
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001012 pool = POOL_ADDR(p);
1013 if (Py_ADDRESS_IN_RANGE(p, pool)) {
1014 /* We allocated this address. */
1015 LOCK();
1016 /* Link p to the start of the pool's freeblock list. Since
1017 * the pool had at least the p block outstanding, the pool
1018 * wasn't empty (so it's already in a usedpools[] list, or
1019 * was full and is in no list -- it's not in the freeblocks
1020 * list in any case).
1021 */
1022 assert(pool->ref.count > 0); /* else it was empty */
1023 *(block **)p = lastfree = pool->freeblock;
1024 pool->freeblock = (block *)p;
1025 if (lastfree) {
1026 struct arena_object* ao;
1027 uint nf; /* ao->nfreepools */
Tim Peterscf79aac2006-03-16 01:14:46 +00001028
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001029 /* freeblock wasn't NULL, so the pool wasn't full,
1030 * and the pool is in a usedpools[] list.
1031 */
1032 if (--pool->ref.count != 0) {
1033 /* pool isn't empty: leave it in usedpools */
1034 UNLOCK();
1035 return;
1036 }
1037 /* Pool is now empty: unlink from usedpools, and
1038 * link to the front of freepools. This ensures that
1039 * previously freed pools will be allocated later
1040 * (being not referenced, they are perhaps paged out).
1041 */
1042 next = pool->nextpool;
1043 prev = pool->prevpool;
1044 next->prevpool = prev;
1045 prev->nextpool = next;
Tim Peterscf79aac2006-03-16 01:14:46 +00001046
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001047 /* Link the pool to freepools. This is a singly-linked
1048 * list, and pool->prevpool isn't used there.
1049 */
1050 ao = &arenas[pool->arenaindex];
1051 pool->nextpool = ao->freepools;
1052 ao->freepools = pool;
1053 nf = ++ao->nfreepools;
Tim Peterscf79aac2006-03-16 01:14:46 +00001054
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001055 /* All the rest is arena management. We just freed
1056 * a pool, and there are 4 cases for arena mgmt:
1057 * 1. If all the pools are free, return the arena to
1058 * the system free().
1059 * 2. If this is the only free pool in the arena,
1060 * add the arena back to the `usable_arenas` list.
1061 * 3. If the "next" arena has a smaller count of free
1062 * pools, we have to "slide this arena right" to
1063 * restore that usable_arenas is sorted in order of
1064 * nfreepools.
1065 * 4. Else there's nothing more to do.
1066 */
1067 if (nf == ao->ntotalpools) {
1068 /* Case 1. First unlink ao from usable_arenas.
1069 */
1070 assert(ao->prevarena == NULL ||
1071 ao->prevarena->address != 0);
1072 assert(ao ->nextarena == NULL ||
1073 ao->nextarena->address != 0);
Tim Peterscf79aac2006-03-16 01:14:46 +00001074
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001075 /* Fix the pointer in the prevarena, or the
1076 * usable_arenas pointer.
1077 */
1078 if (ao->prevarena == NULL) {
1079 usable_arenas = ao->nextarena;
1080 assert(usable_arenas == NULL ||
1081 usable_arenas->address != 0);
1082 }
1083 else {
1084 assert(ao->prevarena->nextarena == ao);
1085 ao->prevarena->nextarena =
1086 ao->nextarena;
1087 }
1088 /* Fix the pointer in the nextarena. */
1089 if (ao->nextarena != NULL) {
1090 assert(ao->nextarena->prevarena == ao);
1091 ao->nextarena->prevarena =
1092 ao->prevarena;
1093 }
1094 /* Record that this arena_object slot is
1095 * available to be reused.
1096 */
1097 ao->nextarena = unused_arena_objects;
1098 unused_arena_objects = ao;
Tim Peterscf79aac2006-03-16 01:14:46 +00001099
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001100 /* Free the entire arena. */
Benjamin Petersond16e01c2014-02-04 10:20:26 -05001101#ifdef ARENAS_USE_MMAP
1102 munmap((void *)ao->address, ARENA_SIZE);
1103#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001104 free((void *)ao->address);
Benjamin Petersond16e01c2014-02-04 10:20:26 -05001105#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001106 ao->address = 0; /* mark unassociated */
1107 --narenas_currently_allocated;
Tim Peterscf79aac2006-03-16 01:14:46 +00001108
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001109 UNLOCK();
1110 return;
1111 }
1112 if (nf == 1) {
1113 /* Case 2. Put ao at the head of
1114 * usable_arenas. Note that because
1115 * ao->nfreepools was 0 before, ao isn't
1116 * currently on the usable_arenas list.
1117 */
1118 ao->nextarena = usable_arenas;
1119 ao->prevarena = NULL;
1120 if (usable_arenas)
1121 usable_arenas->prevarena = ao;
1122 usable_arenas = ao;
1123 assert(usable_arenas->address != 0);
Tim Peterscf79aac2006-03-16 01:14:46 +00001124
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001125 UNLOCK();
1126 return;
1127 }
1128 /* If this arena is now out of order, we need to keep
1129 * the list sorted. The list is kept sorted so that
1130 * the "most full" arenas are used first, which allows
1131 * the nearly empty arenas to be completely freed. In
1132 * a few un-scientific tests, it seems like this
1133 * approach allowed a lot more memory to be freed.
1134 */
1135 if (ao->nextarena == NULL ||
1136 nf <= ao->nextarena->nfreepools) {
1137 /* Case 4. Nothing to do. */
1138 UNLOCK();
1139 return;
1140 }
1141 /* Case 3: We have to move the arena towards the end
1142 * of the list, because it has more free pools than
1143 * the arena to its right.
1144 * First unlink ao from usable_arenas.
1145 */
1146 if (ao->prevarena != NULL) {
1147 /* ao isn't at the head of the list */
1148 assert(ao->prevarena->nextarena == ao);
1149 ao->prevarena->nextarena = ao->nextarena;
1150 }
1151 else {
1152 /* ao is at the head of the list */
1153 assert(usable_arenas == ao);
1154 usable_arenas = ao->nextarena;
1155 }
1156 ao->nextarena->prevarena = ao->prevarena;
Tim Peterscf79aac2006-03-16 01:14:46 +00001157
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001158 /* Locate the new insertion point by iterating over
1159 * the list, using our nextarena pointer.
1160 */
1161 while (ao->nextarena != NULL &&
1162 nf > ao->nextarena->nfreepools) {
1163 ao->prevarena = ao->nextarena;
1164 ao->nextarena = ao->nextarena->nextarena;
1165 }
Tim Peterscf79aac2006-03-16 01:14:46 +00001166
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001167 /* Insert ao at this point. */
1168 assert(ao->nextarena == NULL ||
1169 ao->prevarena == ao->nextarena->prevarena);
1170 assert(ao->prevarena->nextarena == ao->nextarena);
Tim Peterscf79aac2006-03-16 01:14:46 +00001171
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001172 ao->prevarena->nextarena = ao;
1173 if (ao->nextarena != NULL)
1174 ao->nextarena->prevarena = ao;
Tim Peterscf79aac2006-03-16 01:14:46 +00001175
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001176 /* Verify that the swaps worked. */
1177 assert(ao->nextarena == NULL ||
1178 nf <= ao->nextarena->nfreepools);
1179 assert(ao->prevarena == NULL ||
1180 nf > ao->prevarena->nfreepools);
1181 assert(ao->nextarena == NULL ||
1182 ao->nextarena->prevarena == ao);
1183 assert((usable_arenas == ao &&
1184 ao->prevarena == NULL) ||
1185 ao->prevarena->nextarena == ao);
Tim Peterscf79aac2006-03-16 01:14:46 +00001186
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001187 UNLOCK();
1188 return;
1189 }
1190 /* Pool was full, so doesn't currently live in any list:
1191 * link it to the front of the appropriate usedpools[] list.
1192 * This mimics LRU pool usage for new allocations and
1193 * targets optimal filling when several pools contain
1194 * blocks of the same size class.
1195 */
1196 --pool->ref.count;
1197 assert(pool->ref.count > 0); /* else the pool is empty */
1198 size = pool->szidx;
1199 next = usedpools[size + size];
1200 prev = next->prevpool;
1201 /* insert pool before next: prev <-> pool <-> next */
1202 pool->nextpool = next;
1203 pool->prevpool = prev;
1204 next->prevpool = pool;
1205 prev->nextpool = pool;
1206 UNLOCK();
1207 return;
1208 }
Neil Schemenauera35c6882001-02-27 04:45:05 +00001209
Benjamin Peterson91c12eb2009-12-03 02:52:39 +00001210#ifdef WITH_VALGRIND
1211redirect:
1212#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001213 /* We didn't allocate this address. */
1214 free(p);
Neil Schemenauera35c6882001-02-27 04:45:05 +00001215}
1216
Tim Peters84c1b972002-04-04 04:44:32 +00001217/* realloc. If p is NULL, this acts like malloc(nbytes). Else if nbytes==0,
1218 * then as the Python docs promise, we do not treat this like free(p), and
1219 * return a non-NULL result.
1220 */
Neil Schemenauera35c6882001-02-27 04:45:05 +00001221
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00001222#undef PyObject_Realloc
Benjamin Petersonb529c242015-04-26 20:33:38 -04001223ATTRIBUTE_NO_ADDRESS_SAFETY_ANALYSIS
Neil Schemenauera35c6882001-02-27 04:45:05 +00001224void *
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00001225PyObject_Realloc(void *p, size_t nbytes)
Neil Schemenauera35c6882001-02-27 04:45:05 +00001226{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001227 void *bp;
1228 poolp pool;
1229 size_t size;
Antoine Pitrou5a72e762011-01-07 21:49:44 +00001230#ifndef Py_USING_MEMORY_DEBUGGER
1231 uint arenaindex_temp;
1232#endif
Neil Schemenauera35c6882001-02-27 04:45:05 +00001233
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001234 if (p == NULL)
1235 return PyObject_Malloc(nbytes);
Neil Schemenauera35c6882001-02-27 04:45:05 +00001236
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001237 /*
1238 * Limit ourselves to PY_SSIZE_T_MAX bytes to prevent security holes.
1239 * Most python internals blindly use a signed Py_ssize_t to track
1240 * things without checking for overflows or negatives.
1241 * As size_t is unsigned, checking for nbytes < 0 is not required.
1242 */
1243 if (nbytes > PY_SSIZE_T_MAX)
1244 return NULL;
Gregory P. Smith0470bab2008-07-22 04:46:32 +00001245
Benjamin Peterson91c12eb2009-12-03 02:52:39 +00001246#ifdef WITH_VALGRIND
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001247 /* Treat running_on_valgrind == -1 the same as 0 */
1248 if (UNLIKELY(running_on_valgrind > 0))
1249 goto redirect;
Benjamin Peterson91c12eb2009-12-03 02:52:39 +00001250#endif
1251
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001252 pool = POOL_ADDR(p);
1253 if (Py_ADDRESS_IN_RANGE(p, pool)) {
1254 /* We're in charge of this block */
1255 size = INDEX2SIZE(pool->szidx);
1256 if (nbytes <= size) {
1257 /* The block is staying the same or shrinking. If
1258 * it's shrinking, there's a tradeoff: it costs
1259 * cycles to copy the block to a smaller size class,
1260 * but it wastes memory not to copy it. The
1261 * compromise here is to copy on shrink only if at
1262 * least 25% of size can be shaved off.
1263 */
1264 if (4 * nbytes > 3 * size) {
1265 /* It's the same,
1266 * or shrinking and new/old > 3/4.
1267 */
1268 return p;
1269 }
1270 size = nbytes;
1271 }
1272 bp = PyObject_Malloc(nbytes);
1273 if (bp != NULL) {
1274 memcpy(bp, p, size);
1275 PyObject_Free(p);
1276 }
1277 return bp;
1278 }
Benjamin Peterson91c12eb2009-12-03 02:52:39 +00001279#ifdef WITH_VALGRIND
1280 redirect:
1281#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001282 /* We're not managing this block. If nbytes <=
1283 * SMALL_REQUEST_THRESHOLD, it's tempting to try to take over this
1284 * block. However, if we do, we need to copy the valid data from
1285 * the C-managed block to one of our blocks, and there's no portable
1286 * way to know how much of the memory space starting at p is valid.
1287 * As bug 1185883 pointed out the hard way, it's possible that the
1288 * C-managed block is "at the end" of allocated VM space, so that
1289 * a memory fault can occur if we try to copy nbytes bytes starting
1290 * at p. Instead we punt: let C continue to manage this block.
1291 */
1292 if (nbytes)
1293 return realloc(p, nbytes);
1294 /* C doesn't define the result of realloc(p, 0) (it may or may not
1295 * return NULL then), but Python's docs promise that nbytes==0 never
1296 * returns NULL. We don't pass 0 to realloc(), to avoid that endcase
1297 * to begin with. Even then, we can't be sure that realloc() won't
1298 * return NULL.
1299 */
1300 bp = realloc(p, 1);
1301 return bp ? bp : p;
Neil Schemenauera35c6882001-02-27 04:45:05 +00001302}
1303
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001304#else /* ! WITH_PYMALLOC */
Tim Petersddea2082002-03-23 10:03:50 +00001305
1306/*==========================================================================*/
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00001307/* pymalloc not enabled: Redirect the entry points to malloc. These will
1308 * only be used by extensions that are compiled with pymalloc enabled. */
Tim Peters62c06ba2002-03-23 22:28:18 +00001309
Tim Petersce7fb9b2002-03-23 00:28:57 +00001310void *
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00001311PyObject_Malloc(size_t n)
Tim Peters1221c0a2002-03-23 00:20:15 +00001312{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001313 return PyMem_MALLOC(n);
Tim Peters1221c0a2002-03-23 00:20:15 +00001314}
1315
Tim Petersce7fb9b2002-03-23 00:28:57 +00001316void *
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00001317PyObject_Realloc(void *p, size_t n)
Tim Peters1221c0a2002-03-23 00:20:15 +00001318{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001319 return PyMem_REALLOC(p, n);
Tim Peters1221c0a2002-03-23 00:20:15 +00001320}
1321
1322void
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00001323PyObject_Free(void *p)
Tim Peters1221c0a2002-03-23 00:20:15 +00001324{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001325 PyMem_FREE(p);
Tim Peters1221c0a2002-03-23 00:20:15 +00001326}
1327#endif /* WITH_PYMALLOC */
1328
Tim Petersddea2082002-03-23 10:03:50 +00001329#ifdef PYMALLOC_DEBUG
1330/*==========================================================================*/
Tim Peters62c06ba2002-03-23 22:28:18 +00001331/* A x-platform debugging allocator. This doesn't manage memory directly,
1332 * it wraps a real allocator, adding extra debugging info to the memory blocks.
1333 */
Tim Petersddea2082002-03-23 10:03:50 +00001334
Tim Petersf6fb5012002-04-12 07:38:53 +00001335/* Special bytes broadcast into debug memory blocks at appropriate times.
1336 * Strings of these are unlikely to be valid addresses, floats, ints or
1337 * 7-bit ASCII.
1338 */
1339#undef CLEANBYTE
1340#undef DEADBYTE
1341#undef FORBIDDENBYTE
1342#define CLEANBYTE 0xCB /* clean (newly allocated) memory */
Tim Peters889f61d2002-07-10 19:29:49 +00001343#define DEADBYTE 0xDB /* dead (newly freed) memory */
Tim Petersf6fb5012002-04-12 07:38:53 +00001344#define FORBIDDENBYTE 0xFB /* untouchable bytes at each end of a block */
Tim Petersddea2082002-03-23 10:03:50 +00001345
Kristján Valur Jónsson02ca57c2009-09-28 13:12:38 +00001346/* We tag each block with an API ID in order to tag API violations */
1347#define _PYMALLOC_MEM_ID 'm' /* the PyMem_Malloc() API */
1348#define _PYMALLOC_OBJ_ID 'o' /* The PyObject_Malloc() API */
1349
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001350static size_t serialno = 0; /* incremented on each debug {m,re}alloc */
Tim Petersddea2082002-03-23 10:03:50 +00001351
Tim Peterse0850172002-03-24 00:34:21 +00001352/* serialno is always incremented via calling this routine. The point is
Tim Peters9ea89d22006-06-04 03:26:02 +00001353 * to supply a single place to set a breakpoint.
1354 */
Tim Peterse0850172002-03-24 00:34:21 +00001355static void
Neil Schemenauerbd02b142002-03-28 21:05:38 +00001356bumpserialno(void)
Tim Peterse0850172002-03-24 00:34:21 +00001357{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001358 ++serialno;
Tim Peterse0850172002-03-24 00:34:21 +00001359}
1360
Tim Peters9ea89d22006-06-04 03:26:02 +00001361#define SST SIZEOF_SIZE_T
Tim Peterse0850172002-03-24 00:34:21 +00001362
Tim Peters9ea89d22006-06-04 03:26:02 +00001363/* Read sizeof(size_t) bytes at p as a big-endian size_t. */
1364static size_t
1365read_size_t(const void *p)
Tim Petersddea2082002-03-23 10:03:50 +00001366{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001367 const uchar *q = (const uchar *)p;
1368 size_t result = *q++;
1369 int i;
Tim Peters9ea89d22006-06-04 03:26:02 +00001370
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001371 for (i = SST; --i > 0; ++q)
1372 result = (result << 8) | *q;
1373 return result;
Tim Petersddea2082002-03-23 10:03:50 +00001374}
1375
Tim Peters9ea89d22006-06-04 03:26:02 +00001376/* Write n as a big-endian size_t, MSB at address p, LSB at
1377 * p + sizeof(size_t) - 1.
1378 */
Tim Petersddea2082002-03-23 10:03:50 +00001379static void
Tim Peters9ea89d22006-06-04 03:26:02 +00001380write_size_t(void *p, size_t n)
Tim Petersddea2082002-03-23 10:03:50 +00001381{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001382 uchar *q = (uchar *)p + SST - 1;
1383 int i;
Tim Peters9ea89d22006-06-04 03:26:02 +00001384
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001385 for (i = SST; --i >= 0; --q) {
1386 *q = (uchar)(n & 0xff);
1387 n >>= 8;
1388 }
Tim Petersddea2082002-03-23 10:03:50 +00001389}
1390
Tim Peters08d82152002-04-18 22:25:03 +00001391#ifdef Py_DEBUG
1392/* Is target in the list? The list is traversed via the nextpool pointers.
1393 * The list may be NULL-terminated, or circular. Return 1 if target is in
1394 * list, else 0.
1395 */
1396static int
1397pool_is_in_list(const poolp target, poolp list)
1398{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001399 poolp origlist = list;
1400 assert(target != NULL);
1401 if (list == NULL)
1402 return 0;
1403 do {
1404 if (target == list)
1405 return 1;
1406 list = list->nextpool;
1407 } while (list != NULL && list != origlist);
1408 return 0;
Tim Peters08d82152002-04-18 22:25:03 +00001409}
1410
1411#else
1412#define pool_is_in_list(X, Y) 1
1413
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001414#endif /* Py_DEBUG */
Tim Peters08d82152002-04-18 22:25:03 +00001415
Tim Peters9ea89d22006-06-04 03:26:02 +00001416/* Let S = sizeof(size_t). The debug malloc asks for 4*S extra bytes and
1417 fills them with useful stuff, here calling the underlying malloc's result p:
Tim Petersddea2082002-03-23 10:03:50 +00001418
Tim Peters9ea89d22006-06-04 03:26:02 +00001419p[0: S]
1420 Number of bytes originally asked for. This is a size_t, big-endian (easier
1421 to read in a memory dump).
1422p[S: 2*S]
Tim Petersf6fb5012002-04-12 07:38:53 +00001423 Copies of FORBIDDENBYTE. Used to catch under- writes and reads.
Tim Peters9ea89d22006-06-04 03:26:02 +00001424p[2*S: 2*S+n]
Tim Petersf6fb5012002-04-12 07:38:53 +00001425 The requested memory, filled with copies of CLEANBYTE.
Tim Petersddea2082002-03-23 10:03:50 +00001426 Used to catch reference to uninitialized memory.
Tim Peters9ea89d22006-06-04 03:26:02 +00001427 &p[2*S] is returned. Note that this is 8-byte aligned if pymalloc
Tim Petersddea2082002-03-23 10:03:50 +00001428 handled the request itself.
Tim Peters9ea89d22006-06-04 03:26:02 +00001429p[2*S+n: 2*S+n+S]
Tim Petersf6fb5012002-04-12 07:38:53 +00001430 Copies of FORBIDDENBYTE. Used to catch over- writes and reads.
Tim Peters9ea89d22006-06-04 03:26:02 +00001431p[2*S+n+S: 2*S+n+2*S]
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00001432 A serial number, incremented by 1 on each call to _PyObject_DebugMalloc
1433 and _PyObject_DebugRealloc.
Tim Peters9ea89d22006-06-04 03:26:02 +00001434 This is a big-endian size_t.
Tim Petersddea2082002-03-23 10:03:50 +00001435 If "bad memory" is detected later, the serial number gives an
1436 excellent way to set a breakpoint on the next run, to capture the
1437 instant at which this block was passed out.
1438*/
1439
Kristján Valur Jónsson02ca57c2009-09-28 13:12:38 +00001440/* debug replacements for the PyMem_* memory API */
1441void *
1442_PyMem_DebugMalloc(size_t nbytes)
1443{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001444 return _PyObject_DebugMallocApi(_PYMALLOC_MEM_ID, nbytes);
Kristján Valur Jónsson02ca57c2009-09-28 13:12:38 +00001445}
1446void *
1447_PyMem_DebugRealloc(void *p, size_t nbytes)
1448{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001449 return _PyObject_DebugReallocApi(_PYMALLOC_MEM_ID, p, nbytes);
Kristján Valur Jónsson02ca57c2009-09-28 13:12:38 +00001450}
1451void
1452_PyMem_DebugFree(void *p)
1453{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001454 _PyObject_DebugFreeApi(_PYMALLOC_MEM_ID, p);
Kristján Valur Jónsson02ca57c2009-09-28 13:12:38 +00001455}
1456
1457/* debug replacements for the PyObject_* memory API */
Tim Petersddea2082002-03-23 10:03:50 +00001458void *
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00001459_PyObject_DebugMalloc(size_t nbytes)
Tim Petersddea2082002-03-23 10:03:50 +00001460{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001461 return _PyObject_DebugMallocApi(_PYMALLOC_OBJ_ID, nbytes);
Kristján Valur Jónsson02ca57c2009-09-28 13:12:38 +00001462}
1463void *
1464_PyObject_DebugRealloc(void *p, size_t nbytes)
1465{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001466 return _PyObject_DebugReallocApi(_PYMALLOC_OBJ_ID, p, nbytes);
Kristján Valur Jónsson02ca57c2009-09-28 13:12:38 +00001467}
1468void
1469_PyObject_DebugFree(void *p)
1470{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001471 _PyObject_DebugFreeApi(_PYMALLOC_OBJ_ID, p);
Kristján Valur Jónsson02ca57c2009-09-28 13:12:38 +00001472}
1473void
Kristján Valur Jónssonb3318022009-09-28 15:56:25 +00001474_PyObject_DebugCheckAddress(const void *p)
Kristján Valur Jónsson02ca57c2009-09-28 13:12:38 +00001475{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001476 _PyObject_DebugCheckAddressApi(_PYMALLOC_OBJ_ID, p);
Kristján Valur Jónsson02ca57c2009-09-28 13:12:38 +00001477}
1478
1479
1480/* generic debug memory api, with an "id" to identify the API in use */
1481void *
1482_PyObject_DebugMallocApi(char id, size_t nbytes)
1483{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001484 uchar *p; /* base address of malloc'ed block */
1485 uchar *tail; /* p + 2*SST + nbytes == pointer to tail pad bytes */
1486 size_t total; /* nbytes + 4*SST */
Tim Petersddea2082002-03-23 10:03:50 +00001487
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001488 bumpserialno();
1489 total = nbytes + 4*SST;
1490 if (total < nbytes)
1491 /* overflow: can't represent total as a size_t */
1492 return NULL;
Tim Petersddea2082002-03-23 10:03:50 +00001493
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001494 p = (uchar *)PyObject_Malloc(total);
1495 if (p == NULL)
1496 return NULL;
Tim Petersddea2082002-03-23 10:03:50 +00001497
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001498 /* at p, write size (SST bytes), id (1 byte), pad (SST-1 bytes) */
1499 write_size_t(p, nbytes);
1500 p[SST] = (uchar)id;
1501 memset(p + SST + 1 , FORBIDDENBYTE, SST-1);
Tim Petersddea2082002-03-23 10:03:50 +00001502
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001503 if (nbytes > 0)
1504 memset(p + 2*SST, CLEANBYTE, nbytes);
Tim Petersddea2082002-03-23 10:03:50 +00001505
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001506 /* at tail, write pad (SST bytes) and serialno (SST bytes) */
1507 tail = p + 2*SST + nbytes;
1508 memset(tail, FORBIDDENBYTE, SST);
1509 write_size_t(tail + SST, serialno);
Tim Petersddea2082002-03-23 10:03:50 +00001510
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001511 return p + 2*SST;
Tim Petersddea2082002-03-23 10:03:50 +00001512}
1513
Tim Peters9ea89d22006-06-04 03:26:02 +00001514/* The debug free first checks the 2*SST bytes on each end for sanity (in
Kristján Valur Jónsson02ca57c2009-09-28 13:12:38 +00001515 particular, that the FORBIDDENBYTEs with the api ID are still intact).
Tim Petersf6fb5012002-04-12 07:38:53 +00001516 Then fills the original bytes with DEADBYTE.
Tim Petersddea2082002-03-23 10:03:50 +00001517 Then calls the underlying free.
1518*/
1519void
Kristján Valur Jónsson02ca57c2009-09-28 13:12:38 +00001520_PyObject_DebugFreeApi(char api, void *p)
Tim Petersddea2082002-03-23 10:03:50 +00001521{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001522 uchar *q = (uchar *)p - 2*SST; /* address returned from malloc */
1523 size_t nbytes;
Tim Petersddea2082002-03-23 10:03:50 +00001524
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001525 if (p == NULL)
1526 return;
1527 _PyObject_DebugCheckAddressApi(api, p);
1528 nbytes = read_size_t(q);
1529 nbytes += 4*SST;
1530 if (nbytes > 0)
1531 memset(q, DEADBYTE, nbytes);
1532 PyObject_Free(q);
Tim Petersddea2082002-03-23 10:03:50 +00001533}
1534
1535void *
Kristján Valur Jónsson02ca57c2009-09-28 13:12:38 +00001536_PyObject_DebugReallocApi(char api, void *p, size_t nbytes)
Tim Petersddea2082002-03-23 10:03:50 +00001537{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001538 uchar *q = (uchar *)p;
1539 uchar *tail;
1540 size_t total; /* nbytes + 4*SST */
1541 size_t original_nbytes;
1542 int i;
Tim Petersddea2082002-03-23 10:03:50 +00001543
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001544 if (p == NULL)
1545 return _PyObject_DebugMallocApi(api, nbytes);
Tim Petersddea2082002-03-23 10:03:50 +00001546
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001547 _PyObject_DebugCheckAddressApi(api, p);
1548 bumpserialno();
1549 original_nbytes = read_size_t(q - 2*SST);
1550 total = nbytes + 4*SST;
1551 if (total < nbytes)
1552 /* overflow: can't represent total as a size_t */
1553 return NULL;
Tim Petersddea2082002-03-23 10:03:50 +00001554
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001555 if (nbytes < original_nbytes) {
1556 /* shrinking: mark old extra memory dead */
1557 memset(q + nbytes, DEADBYTE, original_nbytes - nbytes + 2*SST);
1558 }
Tim Petersddea2082002-03-23 10:03:50 +00001559
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001560 /* Resize and add decorations. We may get a new pointer here, in which
1561 * case we didn't get the chance to mark the old memory with DEADBYTE,
1562 * but we live with that.
1563 */
1564 q = (uchar *)PyObject_Realloc(q - 2*SST, total);
1565 if (q == NULL)
1566 return NULL;
Tim Peters85cc1c42002-04-12 08:52:50 +00001567
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001568 write_size_t(q, nbytes);
1569 assert(q[SST] == (uchar)api);
1570 for (i = 1; i < SST; ++i)
1571 assert(q[SST + i] == FORBIDDENBYTE);
1572 q += 2*SST;
1573 tail = q + nbytes;
1574 memset(tail, FORBIDDENBYTE, SST);
1575 write_size_t(tail + SST, serialno);
Tim Peters85cc1c42002-04-12 08:52:50 +00001576
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001577 if (nbytes > original_nbytes) {
1578 /* growing: mark new extra memory clean */
1579 memset(q + original_nbytes, CLEANBYTE,
Stefan Krah918c90c2010-11-26 11:03:55 +00001580 nbytes - original_nbytes);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001581 }
Tim Peters85cc1c42002-04-12 08:52:50 +00001582
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001583 return q;
Tim Petersddea2082002-03-23 10:03:50 +00001584}
1585
Tim Peters7ccfadf2002-04-01 06:04:21 +00001586/* Check the forbidden bytes on both ends of the memory allocated for p.
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00001587 * If anything is wrong, print info to stderr via _PyObject_DebugDumpAddress,
Tim Peters7ccfadf2002-04-01 06:04:21 +00001588 * and call Py_FatalError to kill the program.
Kristján Valur Jónsson02ca57c2009-09-28 13:12:38 +00001589 * The API id, is also checked.
Tim Peters7ccfadf2002-04-01 06:04:21 +00001590 */
1591 void
Kristján Valur Jónsson02ca57c2009-09-28 13:12:38 +00001592_PyObject_DebugCheckAddressApi(char api, const void *p)
Tim Petersddea2082002-03-23 10:03:50 +00001593{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001594 const uchar *q = (const uchar *)p;
1595 char msgbuf[64];
1596 char *msg;
1597 size_t nbytes;
1598 const uchar *tail;
1599 int i;
1600 char id;
Tim Petersddea2082002-03-23 10:03:50 +00001601
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001602 if (p == NULL) {
1603 msg = "didn't expect a NULL pointer";
1604 goto error;
1605 }
Tim Petersddea2082002-03-23 10:03:50 +00001606
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001607 /* Check the API id */
1608 id = (char)q[-SST];
1609 if (id != api) {
1610 msg = msgbuf;
1611 snprintf(msg, sizeof(msgbuf), "bad ID: Allocated using API '%c', verified using API '%c'", id, api);
1612 msgbuf[sizeof(msgbuf)-1] = 0;
1613 goto error;
1614 }
Kristján Valur Jónsson02ca57c2009-09-28 13:12:38 +00001615
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001616 /* Check the stuff at the start of p first: if there's underwrite
1617 * corruption, the number-of-bytes field may be nuts, and checking
1618 * the tail could lead to a segfault then.
1619 */
1620 for (i = SST-1; i >= 1; --i) {
1621 if (*(q-i) != FORBIDDENBYTE) {
1622 msg = "bad leading pad byte";
1623 goto error;
1624 }
1625 }
Tim Petersddea2082002-03-23 10:03:50 +00001626
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001627 nbytes = read_size_t(q - 2*SST);
1628 tail = q + nbytes;
1629 for (i = 0; i < SST; ++i) {
1630 if (tail[i] != FORBIDDENBYTE) {
1631 msg = "bad trailing pad byte";
1632 goto error;
1633 }
1634 }
Tim Petersddea2082002-03-23 10:03:50 +00001635
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001636 return;
Tim Petersd1139e02002-03-28 07:32:11 +00001637
1638error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001639 _PyObject_DebugDumpAddress(p);
1640 Py_FatalError(msg);
Tim Petersddea2082002-03-23 10:03:50 +00001641}
1642
Tim Peters7ccfadf2002-04-01 06:04:21 +00001643/* Display info to stderr about the memory block at p. */
Tim Petersddea2082002-03-23 10:03:50 +00001644void
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00001645_PyObject_DebugDumpAddress(const void *p)
Tim Petersddea2082002-03-23 10:03:50 +00001646{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001647 const uchar *q = (const uchar *)p;
1648 const uchar *tail;
1649 size_t nbytes, serial;
1650 int i;
1651 int ok;
1652 char id;
Tim Petersddea2082002-03-23 10:03:50 +00001653
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001654 fprintf(stderr, "Debug memory block at address p=%p:", p);
1655 if (p == NULL) {
1656 fprintf(stderr, "\n");
1657 return;
1658 }
1659 id = (char)q[-SST];
1660 fprintf(stderr, " API '%c'\n", id);
Tim Petersddea2082002-03-23 10:03:50 +00001661
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001662 nbytes = read_size_t(q - 2*SST);
1663 fprintf(stderr, " %" PY_FORMAT_SIZE_T "u bytes originally "
1664 "requested\n", nbytes);
Tim Petersddea2082002-03-23 10:03:50 +00001665
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001666 /* In case this is nuts, check the leading pad bytes first. */
1667 fprintf(stderr, " The %d pad bytes at p-%d are ", SST-1, SST-1);
1668 ok = 1;
1669 for (i = 1; i <= SST-1; ++i) {
1670 if (*(q-i) != FORBIDDENBYTE) {
1671 ok = 0;
1672 break;
1673 }
1674 }
1675 if (ok)
1676 fputs("FORBIDDENBYTE, as expected.\n", stderr);
1677 else {
1678 fprintf(stderr, "not all FORBIDDENBYTE (0x%02x):\n",
1679 FORBIDDENBYTE);
1680 for (i = SST-1; i >= 1; --i) {
1681 const uchar byte = *(q-i);
1682 fprintf(stderr, " at p-%d: 0x%02x", i, byte);
1683 if (byte != FORBIDDENBYTE)
1684 fputs(" *** OUCH", stderr);
1685 fputc('\n', stderr);
1686 }
Tim Peters449b5a82002-04-28 06:14:45 +00001687
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001688 fputs(" Because memory is corrupted at the start, the "
1689 "count of bytes requested\n"
1690 " may be bogus, and checking the trailing pad "
1691 "bytes may segfault.\n", stderr);
1692 }
Tim Petersddea2082002-03-23 10:03:50 +00001693
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001694 tail = q + nbytes;
1695 fprintf(stderr, " The %d pad bytes at tail=%p are ", SST, tail);
1696 ok = 1;
1697 for (i = 0; i < SST; ++i) {
1698 if (tail[i] != FORBIDDENBYTE) {
1699 ok = 0;
1700 break;
1701 }
1702 }
1703 if (ok)
1704 fputs("FORBIDDENBYTE, as expected.\n", stderr);
1705 else {
1706 fprintf(stderr, "not all FORBIDDENBYTE (0x%02x):\n",
Stefan Krah918c90c2010-11-26 11:03:55 +00001707 FORBIDDENBYTE);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001708 for (i = 0; i < SST; ++i) {
1709 const uchar byte = tail[i];
1710 fprintf(stderr, " at tail+%d: 0x%02x",
Stefan Krah918c90c2010-11-26 11:03:55 +00001711 i, byte);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001712 if (byte != FORBIDDENBYTE)
1713 fputs(" *** OUCH", stderr);
1714 fputc('\n', stderr);
1715 }
1716 }
Tim Petersddea2082002-03-23 10:03:50 +00001717
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001718 serial = read_size_t(tail + SST);
1719 fprintf(stderr, " The block was made by call #%" PY_FORMAT_SIZE_T
1720 "u to debug malloc/realloc.\n", serial);
Tim Petersddea2082002-03-23 10:03:50 +00001721
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001722 if (nbytes > 0) {
1723 i = 0;
1724 fputs(" Data at p:", stderr);
1725 /* print up to 8 bytes at the start */
1726 while (q < tail && i < 8) {
1727 fprintf(stderr, " %02x", *q);
1728 ++i;
1729 ++q;
1730 }
1731 /* and up to 8 at the end */
1732 if (q < tail) {
1733 if (tail - q > 8) {
1734 fputs(" ...", stderr);
1735 q = tail - 8;
1736 }
1737 while (q < tail) {
1738 fprintf(stderr, " %02x", *q);
1739 ++q;
1740 }
1741 }
1742 fputc('\n', stderr);
1743 }
Tim Petersddea2082002-03-23 10:03:50 +00001744}
1745
Tim Peters9ea89d22006-06-04 03:26:02 +00001746static size_t
1747printone(const char* msg, size_t value)
Tim Peters16bcb6b2002-04-05 05:45:31 +00001748{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001749 int i, k;
1750 char buf[100];
1751 size_t origvalue = value;
Tim Peters16bcb6b2002-04-05 05:45:31 +00001752
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001753 fputs(msg, stderr);
1754 for (i = (int)strlen(msg); i < 35; ++i)
1755 fputc(' ', stderr);
1756 fputc('=', stderr);
Tim Peters49f26812002-04-06 01:45:35 +00001757
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001758 /* Write the value with commas. */
1759 i = 22;
1760 buf[i--] = '\0';
1761 buf[i--] = '\n';
1762 k = 3;
1763 do {
1764 size_t nextvalue = value / 10;
Benjamin Peterson8e830a02013-02-20 16:54:30 -05001765 unsigned int digit = (unsigned int)(value - nextvalue * 10);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001766 value = nextvalue;
1767 buf[i--] = (char)(digit + '0');
1768 --k;
1769 if (k == 0 && value && i >= 0) {
1770 k = 3;
1771 buf[i--] = ',';
1772 }
1773 } while (value && i >= 0);
Tim Peters49f26812002-04-06 01:45:35 +00001774
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001775 while (i >= 0)
1776 buf[i--] = ' ';
1777 fputs(buf, stderr);
Tim Peters49f26812002-04-06 01:45:35 +00001778
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001779 return origvalue;
Tim Peters16bcb6b2002-04-05 05:45:31 +00001780}
1781
Tim Peters08d82152002-04-18 22:25:03 +00001782/* Print summary info to stderr about the state of pymalloc's structures.
1783 * In Py_DEBUG mode, also perform some expensive internal consistency
1784 * checks.
1785 */
Tim Peters7ccfadf2002-04-01 06:04:21 +00001786void
Tim Peters0e871182002-04-13 08:29:14 +00001787_PyObject_DebugMallocStats(void)
Tim Peters7ccfadf2002-04-01 06:04:21 +00001788{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001789 uint i;
1790 const uint numclasses = SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT;
1791 /* # of pools, allocated blocks, and free blocks per class index */
1792 size_t numpools[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT];
1793 size_t numblocks[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT];
1794 size_t numfreeblocks[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT];
1795 /* total # of allocated bytes in used and full pools */
1796 size_t allocated_bytes = 0;
1797 /* total # of available bytes in used pools */
1798 size_t available_bytes = 0;
1799 /* # of free pools + pools not yet carved out of current arena */
1800 uint numfreepools = 0;
1801 /* # of bytes for arena alignment padding */
1802 size_t arena_alignment = 0;
1803 /* # of bytes in used and full pools used for pool_headers */
1804 size_t pool_header_bytes = 0;
1805 /* # of bytes in used and full pools wasted due to quantization,
1806 * i.e. the necessarily leftover space at the ends of used and
1807 * full pools.
1808 */
1809 size_t quantization = 0;
1810 /* # of arenas actually allocated. */
1811 size_t narenas = 0;
1812 /* running total -- should equal narenas * ARENA_SIZE */
1813 size_t total;
1814 char buf[128];
Tim Peters7ccfadf2002-04-01 06:04:21 +00001815
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001816 fprintf(stderr, "Small block threshold = %d, in %u size classes.\n",
Stefan Krah918c90c2010-11-26 11:03:55 +00001817 SMALL_REQUEST_THRESHOLD, numclasses);
Tim Peters7ccfadf2002-04-01 06:04:21 +00001818
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001819 for (i = 0; i < numclasses; ++i)
1820 numpools[i] = numblocks[i] = numfreeblocks[i] = 0;
Tim Peters7ccfadf2002-04-01 06:04:21 +00001821
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001822 /* Because full pools aren't linked to from anything, it's easiest
1823 * to march over all the arenas. If we're lucky, most of the memory
1824 * will be living in full pools -- would be a shame to miss them.
1825 */
1826 for (i = 0; i < maxarenas; ++i) {
1827 uint j;
1828 uptr base = arenas[i].address;
Tim Peterscf79aac2006-03-16 01:14:46 +00001829
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001830 /* Skip arenas which are not allocated. */
1831 if (arenas[i].address == (uptr)NULL)
1832 continue;
1833 narenas += 1;
Tim Peterscf79aac2006-03-16 01:14:46 +00001834
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001835 numfreepools += arenas[i].nfreepools;
Tim Peters7ccfadf2002-04-01 06:04:21 +00001836
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001837 /* round up to pool alignment */
1838 if (base & (uptr)POOL_SIZE_MASK) {
1839 arena_alignment += POOL_SIZE;
1840 base &= ~(uptr)POOL_SIZE_MASK;
1841 base += POOL_SIZE;
1842 }
Tim Peters7ccfadf2002-04-01 06:04:21 +00001843
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001844 /* visit every pool in the arena */
1845 assert(base <= (uptr) arenas[i].pool_address);
1846 for (j = 0;
1847 base < (uptr) arenas[i].pool_address;
1848 ++j, base += POOL_SIZE) {
1849 poolp p = (poolp)base;
1850 const uint sz = p->szidx;
1851 uint freeblocks;
Tim Peters08d82152002-04-18 22:25:03 +00001852
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001853 if (p->ref.count == 0) {
1854 /* currently unused */
1855 assert(pool_is_in_list(p, arenas[i].freepools));
1856 continue;
1857 }
1858 ++numpools[sz];
1859 numblocks[sz] += p->ref.count;
1860 freeblocks = NUMBLOCKS(sz) - p->ref.count;
1861 numfreeblocks[sz] += freeblocks;
Tim Peters08d82152002-04-18 22:25:03 +00001862#ifdef Py_DEBUG
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001863 if (freeblocks > 0)
1864 assert(pool_is_in_list(p, usedpools[sz + sz]));
Tim Peters08d82152002-04-18 22:25:03 +00001865#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001866 }
1867 }
1868 assert(narenas == narenas_currently_allocated);
Tim Peters7ccfadf2002-04-01 06:04:21 +00001869
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001870 fputc('\n', stderr);
1871 fputs("class size num pools blocks in use avail blocks\n"
1872 "----- ---- --------- ------------- ------------\n",
Stefan Krah918c90c2010-11-26 11:03:55 +00001873 stderr);
Tim Peters7ccfadf2002-04-01 06:04:21 +00001874
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001875 for (i = 0; i < numclasses; ++i) {
1876 size_t p = numpools[i];
1877 size_t b = numblocks[i];
1878 size_t f = numfreeblocks[i];
1879 uint size = INDEX2SIZE(i);
1880 if (p == 0) {
1881 assert(b == 0 && f == 0);
1882 continue;
1883 }
1884 fprintf(stderr, "%5u %6u "
1885 "%11" PY_FORMAT_SIZE_T "u "
1886 "%15" PY_FORMAT_SIZE_T "u "
1887 "%13" PY_FORMAT_SIZE_T "u\n",
Stefan Krah918c90c2010-11-26 11:03:55 +00001888 i, size, p, b, f);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001889 allocated_bytes += b * size;
1890 available_bytes += f * size;
1891 pool_header_bytes += p * POOL_OVERHEAD;
1892 quantization += p * ((POOL_SIZE - POOL_OVERHEAD) % size);
1893 }
1894 fputc('\n', stderr);
1895 (void)printone("# times object malloc called", serialno);
Tim Peters16bcb6b2002-04-05 05:45:31 +00001896
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001897 (void)printone("# arenas allocated total", ntimes_arena_allocated);
1898 (void)printone("# arenas reclaimed", ntimes_arena_allocated - narenas);
1899 (void)printone("# arenas highwater mark", narenas_highwater);
1900 (void)printone("# arenas allocated current", narenas);
Tim Peterscf79aac2006-03-16 01:14:46 +00001901
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001902 PyOS_snprintf(buf, sizeof(buf),
1903 "%" PY_FORMAT_SIZE_T "u arenas * %d bytes/arena",
1904 narenas, ARENA_SIZE);
1905 (void)printone(buf, narenas * ARENA_SIZE);
Tim Peters16bcb6b2002-04-05 05:45:31 +00001906
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001907 fputc('\n', stderr);
Tim Peters16bcb6b2002-04-05 05:45:31 +00001908
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001909 total = printone("# bytes in allocated blocks", allocated_bytes);
1910 total += printone("# bytes in available blocks", available_bytes);
Tim Peters49f26812002-04-06 01:45:35 +00001911
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001912 PyOS_snprintf(buf, sizeof(buf),
1913 "%u unused pools * %d bytes", numfreepools, POOL_SIZE);
1914 total += printone(buf, (size_t)numfreepools * POOL_SIZE);
Tim Peters16bcb6b2002-04-05 05:45:31 +00001915
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001916 total += printone("# bytes lost to pool headers", pool_header_bytes);
1917 total += printone("# bytes lost to quantization", quantization);
1918 total += printone("# bytes lost to arena alignment", arena_alignment);
1919 (void)printone("Total", total);
Tim Peters7ccfadf2002-04-01 06:04:21 +00001920}
1921
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001922#endif /* PYMALLOC_DEBUG */
Neal Norwitz7eb3c912004-06-06 19:20:22 +00001923
1924#ifdef Py_USING_MEMORY_DEBUGGER
Tim Peterscf79aac2006-03-16 01:14:46 +00001925/* Make this function last so gcc won't inline it since the definition is
1926 * after the reference.
1927 */
Neal Norwitz7eb3c912004-06-06 19:20:22 +00001928int
1929Py_ADDRESS_IN_RANGE(void *P, poolp pool)
1930{
Antoine Pitrou5a72e762011-01-07 21:49:44 +00001931 uint arenaindex_temp = pool->arenaindex;
1932
1933 return arenaindex_temp < maxarenas &&
1934 (uptr)P - arenas[arenaindex_temp].address < (uptr)ARENA_SIZE &&
1935 arenas[arenaindex_temp].address != 0;
Neal Norwitz7eb3c912004-06-06 19:20:22 +00001936}
1937#endif