blob: 3028f225ae709f8957826322b476dc3e83ac4abe [file] [log] [blame]
Tim Peters1221c0a2002-03-23 00:20:15 +00001#include "Python.h"
2
3#ifdef WITH_PYMALLOC
4
Antoine Pitrouf0effe62011-11-26 01:11:02 +01005#ifdef HAVE_MMAP
6 #include <sys/mman.h>
7 #ifdef MAP_ANONYMOUS
8 #define ARENAS_USE_MMAP
9 #endif
Antoine Pitrou6f26be02011-05-03 18:18:59 +020010#endif
11
Benjamin Peterson05159c42009-12-03 03:01:27 +000012#ifdef WITH_VALGRIND
13#include <valgrind/valgrind.h>
14
15/* If we're using GCC, use __builtin_expect() to reduce overhead of
16 the valgrind checks */
17#if defined(__GNUC__) && (__GNUC__ > 2) && defined(__OPTIMIZE__)
18# define UNLIKELY(value) __builtin_expect((value), 0)
19#else
20# define UNLIKELY(value) (value)
21#endif
22
23/* -1 indicates that we haven't checked that we're running on valgrind yet. */
24static int running_on_valgrind = -1;
25#endif
26
Neil Schemenauera35c6882001-02-27 04:45:05 +000027/* An object allocator for Python.
28
29 Here is an introduction to the layers of the Python memory architecture,
30 showing where the object allocator is actually used (layer +2), It is
31 called for every object allocation and deallocation (PyObject_New/Del),
32 unless the object-specific allocators implement a proprietary allocation
33 scheme (ex.: ints use a simple free list). This is also the place where
34 the cyclic garbage collector operates selectively on container objects.
35
36
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000037 Object-specific allocators
Neil Schemenauera35c6882001-02-27 04:45:05 +000038 _____ ______ ______ ________
39 [ int ] [ dict ] [ list ] ... [ string ] Python core |
40+3 | <----- Object-specific memory -----> | <-- Non-object memory --> |
41 _______________________________ | |
42 [ Python's object allocator ] | |
43+2 | ####### Object memory ####### | <------ Internal buffers ------> |
44 ______________________________________________________________ |
45 [ Python's raw memory allocator (PyMem_ API) ] |
46+1 | <----- Python memory (under PyMem manager's control) ------> | |
47 __________________________________________________________________
48 [ Underlying general-purpose allocator (ex: C library malloc) ]
49 0 | <------ Virtual memory allocated for the python process -------> |
50
51 =========================================================================
52 _______________________________________________________________________
53 [ OS-specific Virtual Memory Manager (VMM) ]
54-1 | <--- Kernel dynamic storage allocation & management (page-based) ---> |
55 __________________________________ __________________________________
56 [ ] [ ]
57-2 | <-- Physical memory: ROM/RAM --> | | <-- Secondary storage (swap) --> |
58
59*/
60/*==========================================================================*/
61
62/* A fast, special-purpose memory allocator for small blocks, to be used
63 on top of a general-purpose malloc -- heavily based on previous art. */
64
65/* Vladimir Marangozov -- August 2000 */
66
67/*
68 * "Memory management is where the rubber meets the road -- if we do the wrong
69 * thing at any level, the results will not be good. And if we don't make the
70 * levels work well together, we are in serious trouble." (1)
71 *
72 * (1) Paul R. Wilson, Mark S. Johnstone, Michael Neely, and David Boles,
73 * "Dynamic Storage Allocation: A Survey and Critical Review",
74 * in Proc. 1995 Int'l. Workshop on Memory Management, September 1995.
75 */
76
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000077/* #undef WITH_MEMORY_LIMITS */ /* disable mem limit checks */
Neil Schemenauera35c6882001-02-27 04:45:05 +000078
79/*==========================================================================*/
80
81/*
Neil Schemenauera35c6882001-02-27 04:45:05 +000082 * Allocation strategy abstract:
83 *
84 * For small requests, the allocator sub-allocates <Big> blocks of memory.
Antoine Pitrou6f26be02011-05-03 18:18:59 +020085 * Requests greater than SMALL_REQUEST_THRESHOLD bytes are routed to the
86 * system's allocator.
Tim Petersce7fb9b2002-03-23 00:28:57 +000087 *
Neil Schemenauera35c6882001-02-27 04:45:05 +000088 * Small requests are grouped in size classes spaced 8 bytes apart, due
89 * to the required valid alignment of the returned address. Requests of
90 * a particular size are serviced from memory pools of 4K (one VMM page).
91 * Pools are fragmented on demand and contain free lists of blocks of one
92 * particular size class. In other words, there is a fixed-size allocator
93 * for each size class. Free pools are shared by the different allocators
94 * thus minimizing the space reserved for a particular size class.
95 *
96 * This allocation strategy is a variant of what is known as "simple
97 * segregated storage based on array of free lists". The main drawback of
98 * simple segregated storage is that we might end up with lot of reserved
99 * memory for the different free lists, which degenerate in time. To avoid
100 * this, we partition each free list in pools and we share dynamically the
101 * reserved space between all free lists. This technique is quite efficient
102 * for memory intensive programs which allocate mainly small-sized blocks.
103 *
104 * For small requests we have the following table:
105 *
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000106 * Request in bytes Size of allocated block Size class idx
Neil Schemenauera35c6882001-02-27 04:45:05 +0000107 * ----------------------------------------------------------------
108 * 1-8 8 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000109 * 9-16 16 1
110 * 17-24 24 2
111 * 25-32 32 3
112 * 33-40 40 4
113 * 41-48 48 5
114 * 49-56 56 6
115 * 57-64 64 7
116 * 65-72 72 8
117 * ... ... ...
Antoine Pitrou6f26be02011-05-03 18:18:59 +0200118 * 497-504 504 62
119 * 505-512 512 63
Tim Petersce7fb9b2002-03-23 00:28:57 +0000120 *
Antoine Pitrou6f26be02011-05-03 18:18:59 +0200121 * 0, SMALL_REQUEST_THRESHOLD + 1 and up: routed to the underlying
122 * allocator.
Neil Schemenauera35c6882001-02-27 04:45:05 +0000123 */
124
125/*==========================================================================*/
126
127/*
128 * -- Main tunable settings section --
129 */
130
131/*
132 * Alignment of addresses returned to the user. 8-bytes alignment works
133 * on most current architectures (with 32-bit or 64-bit address busses).
134 * The alignment value is also used for grouping small requests in size
135 * classes spaced ALIGNMENT bytes apart.
136 *
137 * You shouldn't change this unless you know what you are doing.
138 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000139#define ALIGNMENT 8 /* must be 2^N */
140#define ALIGNMENT_SHIFT 3
Neil Schemenauera35c6882001-02-27 04:45:05 +0000141
Tim Peterse70ddf32002-04-05 04:32:29 +0000142/* Return the number of bytes in size class I, as a uint. */
143#define INDEX2SIZE(I) (((uint)(I) + 1) << ALIGNMENT_SHIFT)
144
Neil Schemenauera35c6882001-02-27 04:45:05 +0000145/*
146 * Max size threshold below which malloc requests are considered to be
147 * small enough in order to use preallocated memory pools. You can tune
148 * this value according to your application behaviour and memory needs.
149 *
Antoine Pitrou6f26be02011-05-03 18:18:59 +0200150 * Note: a size threshold of 512 guarantees that newly created dictionaries
151 * will be allocated from preallocated memory pools on 64-bit.
152 *
Neil Schemenauera35c6882001-02-27 04:45:05 +0000153 * The following invariants must hold:
Antoine Pitrou6f26be02011-05-03 18:18:59 +0200154 * 1) ALIGNMENT <= SMALL_REQUEST_THRESHOLD <= 512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000155 * 2) SMALL_REQUEST_THRESHOLD is evenly divisible by ALIGNMENT
Neil Schemenauera35c6882001-02-27 04:45:05 +0000156 *
157 * Although not required, for better performance and space efficiency,
158 * it is recommended that SMALL_REQUEST_THRESHOLD is set to a power of 2.
159 */
Antoine Pitrou6f26be02011-05-03 18:18:59 +0200160#define SMALL_REQUEST_THRESHOLD 512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000161#define NB_SMALL_SIZE_CLASSES (SMALL_REQUEST_THRESHOLD / ALIGNMENT)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000162
163/*
164 * The system's VMM page size can be obtained on most unices with a
165 * getpagesize() call or deduced from various header files. To make
166 * things simpler, we assume that it is 4K, which is OK for most systems.
167 * It is probably better if this is the native page size, but it doesn't
Tim Petersecc6e6a2005-07-10 22:30:55 +0000168 * have to be. In theory, if SYSTEM_PAGE_SIZE is larger than the native page
169 * size, then `POOL_ADDR(p)->arenaindex' could rarely cause a segmentation
170 * violation fault. 4K is apparently OK for all the platforms that python
Martin v. Löwis8c140282002-10-26 15:01:53 +0000171 * currently targets.
Neil Schemenauera35c6882001-02-27 04:45:05 +0000172 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000173#define SYSTEM_PAGE_SIZE (4 * 1024)
174#define SYSTEM_PAGE_SIZE_MASK (SYSTEM_PAGE_SIZE - 1)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000175
176/*
177 * Maximum amount of memory managed by the allocator for small requests.
178 */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000179#ifdef WITH_MEMORY_LIMITS
180#ifndef SMALL_MEMORY_LIMIT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000181#define SMALL_MEMORY_LIMIT (64 * 1024 * 1024) /* 64 MB -- more? */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000182#endif
183#endif
184
185/*
186 * The allocator sub-allocates <Big> blocks of memory (called arenas) aligned
187 * on a page boundary. This is a reserved virtual address space for the
Antoine Pitrouf0effe62011-11-26 01:11:02 +0100188 * current process (obtained through a malloc()/mmap() call). In no way this
189 * means that the memory arenas will be used entirely. A malloc(<Big>) is
190 * usually an address range reservation for <Big> bytes, unless all pages within
191 * this space are referenced subsequently. So malloc'ing big blocks and not
192 * using them does not mean "wasting memory". It's an addressable range
193 * wastage...
Neil Schemenauera35c6882001-02-27 04:45:05 +0000194 *
Antoine Pitrouf0effe62011-11-26 01:11:02 +0100195 * Arenas are allocated with mmap() on systems supporting anonymous memory
196 * mappings to reduce heap fragmentation.
Neil Schemenauera35c6882001-02-27 04:45:05 +0000197 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000198#define ARENA_SIZE (256 << 10) /* 256KB */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000199
200#ifdef WITH_MEMORY_LIMITS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000201#define MAX_ARENAS (SMALL_MEMORY_LIMIT / ARENA_SIZE)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000202#endif
203
204/*
205 * Size of the pools used for small blocks. Should be a power of 2,
Tim Petersc2ce91a2002-03-30 21:36:04 +0000206 * between 1K and SYSTEM_PAGE_SIZE, that is: 1k, 2k, 4k.
Neil Schemenauera35c6882001-02-27 04:45:05 +0000207 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000208#define POOL_SIZE SYSTEM_PAGE_SIZE /* must be 2^N */
209#define POOL_SIZE_MASK SYSTEM_PAGE_SIZE_MASK
Neil Schemenauera35c6882001-02-27 04:45:05 +0000210
211/*
212 * -- End of tunable settings section --
213 */
214
215/*==========================================================================*/
216
217/*
218 * Locking
219 *
220 * To reduce lock contention, it would probably be better to refine the
221 * crude function locking with per size class locking. I'm not positive
222 * however, whether it's worth switching to such locking policy because
223 * of the performance penalty it might introduce.
224 *
225 * The following macros describe the simplest (should also be the fastest)
226 * lock object on a particular platform and the init/fini/lock/unlock
227 * operations on it. The locks defined here are not expected to be recursive
228 * because it is assumed that they will always be called in the order:
229 * INIT, [LOCK, UNLOCK]*, FINI.
230 */
231
232/*
233 * Python's threads are serialized, so object malloc locking is disabled.
234 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000235#define SIMPLELOCK_DECL(lock) /* simple lock declaration */
236#define SIMPLELOCK_INIT(lock) /* allocate (if needed) and initialize */
237#define SIMPLELOCK_FINI(lock) /* free/destroy an existing lock */
238#define SIMPLELOCK_LOCK(lock) /* acquire released lock */
239#define SIMPLELOCK_UNLOCK(lock) /* release acquired lock */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000240
241/*
242 * Basic types
243 * I don't care if these are defined in <sys/types.h> or elsewhere. Axiom.
244 */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000245#undef uchar
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000246#define uchar unsigned char /* assuming == 8 bits */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000247
Neil Schemenauera35c6882001-02-27 04:45:05 +0000248#undef uint
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000249#define uint unsigned int /* assuming >= 16 bits */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000250
251#undef ulong
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000252#define ulong unsigned long /* assuming >= 32 bits */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000253
Tim Petersd97a1c02002-03-30 06:09:22 +0000254#undef uptr
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000255#define uptr Py_uintptr_t
Tim Petersd97a1c02002-03-30 06:09:22 +0000256
Neil Schemenauera35c6882001-02-27 04:45:05 +0000257/* When you say memory, my mind reasons in terms of (pointers to) blocks */
258typedef uchar block;
259
Tim Peterse70ddf32002-04-05 04:32:29 +0000260/* Pool for small blocks. */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000261struct pool_header {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000262 union { block *_padding;
Stefan Krah735bb122010-11-26 10:54:09 +0000263 uint count; } ref; /* number of allocated blocks */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000264 block *freeblock; /* pool's free list head */
265 struct pool_header *nextpool; /* next pool of this size class */
266 struct pool_header *prevpool; /* previous pool "" */
267 uint arenaindex; /* index into arenas of base adr */
268 uint szidx; /* block size class index */
269 uint nextoffset; /* bytes to virgin block */
270 uint maxnextoffset; /* largest valid nextoffset */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000271};
272
273typedef struct pool_header *poolp;
274
Thomas Woutersa9773292006-04-21 09:43:23 +0000275/* Record keeping for arenas. */
276struct arena_object {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000277 /* The address of the arena, as returned by malloc. Note that 0
278 * will never be returned by a successful malloc, and is used
279 * here to mark an arena_object that doesn't correspond to an
280 * allocated arena.
281 */
282 uptr address;
Thomas Woutersa9773292006-04-21 09:43:23 +0000283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000284 /* Pool-aligned pointer to the next pool to be carved off. */
285 block* pool_address;
Thomas Woutersa9773292006-04-21 09:43:23 +0000286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000287 /* The number of available pools in the arena: free pools + never-
288 * allocated pools.
289 */
290 uint nfreepools;
Thomas Woutersa9773292006-04-21 09:43:23 +0000291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000292 /* The total number of pools in the arena, whether or not available. */
293 uint ntotalpools;
Thomas Woutersa9773292006-04-21 09:43:23 +0000294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000295 /* Singly-linked list of available pools. */
296 struct pool_header* freepools;
Thomas Woutersa9773292006-04-21 09:43:23 +0000297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000298 /* Whenever this arena_object is not associated with an allocated
299 * arena, the nextarena member is used to link all unassociated
300 * arena_objects in the singly-linked `unused_arena_objects` list.
301 * The prevarena member is unused in this case.
302 *
303 * When this arena_object is associated with an allocated arena
304 * with at least one available pool, both members are used in the
305 * doubly-linked `usable_arenas` list, which is maintained in
306 * increasing order of `nfreepools` values.
307 *
308 * Else this arena_object is associated with an allocated arena
309 * all of whose pools are in use. `nextarena` and `prevarena`
310 * are both meaningless in this case.
311 */
312 struct arena_object* nextarena;
313 struct arena_object* prevarena;
Thomas Woutersa9773292006-04-21 09:43:23 +0000314};
315
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +0200316#define POOL_OVERHEAD _Py_SIZE_ROUND_UP(sizeof(struct pool_header), ALIGNMENT)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000318#define DUMMY_SIZE_IDX 0xffff /* size class of newly cached pools */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000319
Tim Petersd97a1c02002-03-30 06:09:22 +0000320/* Round pointer P down to the closest pool-aligned address <= P, as a poolp */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +0200321#define POOL_ADDR(P) ((poolp)_Py_ALIGN_DOWN((P), POOL_SIZE))
Tim Peterse70ddf32002-04-05 04:32:29 +0000322
Tim Peters16bcb6b2002-04-05 05:45:31 +0000323/* Return total number of blocks in pool of size index I, as a uint. */
324#define NUMBLOCKS(I) ((uint)(POOL_SIZE - POOL_OVERHEAD) / INDEX2SIZE(I))
Tim Petersd97a1c02002-03-30 06:09:22 +0000325
Neil Schemenauera35c6882001-02-27 04:45:05 +0000326/*==========================================================================*/
327
328/*
329 * This malloc lock
330 */
Jeremy Hyltond1fedb62002-07-18 18:49:52 +0000331SIMPLELOCK_DECL(_malloc_lock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000332#define LOCK() SIMPLELOCK_LOCK(_malloc_lock)
333#define UNLOCK() SIMPLELOCK_UNLOCK(_malloc_lock)
334#define LOCK_INIT() SIMPLELOCK_INIT(_malloc_lock)
335#define LOCK_FINI() SIMPLELOCK_FINI(_malloc_lock)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000336
337/*
Tim Peters1e16db62002-03-31 01:05:22 +0000338 * Pool table -- headed, circular, doubly-linked lists of partially used pools.
339
340This is involved. For an index i, usedpools[i+i] is the header for a list of
341all partially used pools holding small blocks with "size class idx" i. So
342usedpools[0] corresponds to blocks of size 8, usedpools[2] to blocks of size
34316, and so on: index 2*i <-> blocks of size (i+1)<<ALIGNMENT_SHIFT.
344
Thomas Woutersa9773292006-04-21 09:43:23 +0000345Pools are carved off an arena's highwater mark (an arena_object's pool_address
346member) as needed. Once carved off, a pool is in one of three states forever
347after:
Tim Peters1e16db62002-03-31 01:05:22 +0000348
Tim Peters338e0102002-04-01 19:23:44 +0000349used == partially used, neither empty nor full
350 At least one block in the pool is currently allocated, and at least one
351 block in the pool is not currently allocated (note this implies a pool
352 has room for at least two blocks).
353 This is a pool's initial state, as a pool is created only when malloc
354 needs space.
355 The pool holds blocks of a fixed size, and is in the circular list headed
356 at usedpools[i] (see above). It's linked to the other used pools of the
357 same size class via the pool_header's nextpool and prevpool members.
358 If all but one block is currently allocated, a malloc can cause a
359 transition to the full state. If all but one block is not currently
360 allocated, a free can cause a transition to the empty state.
Tim Peters1e16db62002-03-31 01:05:22 +0000361
Tim Peters338e0102002-04-01 19:23:44 +0000362full == all the pool's blocks are currently allocated
363 On transition to full, a pool is unlinked from its usedpools[] list.
364 It's not linked to from anything then anymore, and its nextpool and
365 prevpool members are meaningless until it transitions back to used.
366 A free of a block in a full pool puts the pool back in the used state.
367 Then it's linked in at the front of the appropriate usedpools[] list, so
368 that the next allocation for its size class will reuse the freed block.
369
370empty == all the pool's blocks are currently available for allocation
371 On transition to empty, a pool is unlinked from its usedpools[] list,
Thomas Woutersa9773292006-04-21 09:43:23 +0000372 and linked to the front of its arena_object's singly-linked freepools list,
Tim Peters338e0102002-04-01 19:23:44 +0000373 via its nextpool member. The prevpool member has no meaning in this case.
374 Empty pools have no inherent size class: the next time a malloc finds
375 an empty list in usedpools[], it takes the first pool off of freepools.
376 If the size class needed happens to be the same as the size class the pool
Tim Peterse70ddf32002-04-05 04:32:29 +0000377 last had, some pool initialization can be skipped.
Tim Peters338e0102002-04-01 19:23:44 +0000378
379
380Block Management
381
382Blocks within pools are again carved out as needed. pool->freeblock points to
383the start of a singly-linked list of free blocks within the pool. When a
384block is freed, it's inserted at the front of its pool's freeblock list. Note
385that the available blocks in a pool are *not* linked all together when a pool
Tim Peterse70ddf32002-04-05 04:32:29 +0000386is initialized. Instead only "the first two" (lowest addresses) blocks are
387set up, returning the first such block, and setting pool->freeblock to a
388one-block list holding the second such block. This is consistent with that
389pymalloc strives at all levels (arena, pool, and block) never to touch a piece
390of memory until it's actually needed.
391
392So long as a pool is in the used state, we're certain there *is* a block
Tim Peters52aefc82002-04-11 06:36:45 +0000393available for allocating, and pool->freeblock is not NULL. If pool->freeblock
394points to the end of the free list before we've carved the entire pool into
395blocks, that means we simply haven't yet gotten to one of the higher-address
396blocks. The offset from the pool_header to the start of "the next" virgin
397block is stored in the pool_header nextoffset member, and the largest value
398of nextoffset that makes sense is stored in the maxnextoffset member when a
399pool is initialized. All the blocks in a pool have been passed out at least
400once when and only when nextoffset > maxnextoffset.
Tim Peters338e0102002-04-01 19:23:44 +0000401
Tim Peters1e16db62002-03-31 01:05:22 +0000402
403Major obscurity: While the usedpools vector is declared to have poolp
404entries, it doesn't really. It really contains two pointers per (conceptual)
405poolp entry, the nextpool and prevpool members of a pool_header. The
406excruciating initialization code below fools C so that
407
408 usedpool[i+i]
409
410"acts like" a genuine poolp, but only so long as you only reference its
411nextpool and prevpool members. The "- 2*sizeof(block *)" gibberish is
412compensating for that a pool_header's nextpool and prevpool members
413immediately follow a pool_header's first two members:
414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000415 union { block *_padding;
Stefan Krah735bb122010-11-26 10:54:09 +0000416 uint count; } ref;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417 block *freeblock;
Tim Peters1e16db62002-03-31 01:05:22 +0000418
419each of which consume sizeof(block *) bytes. So what usedpools[i+i] really
420contains is a fudged-up pointer p such that *if* C believes it's a poolp
421pointer, then p->nextpool and p->prevpool are both p (meaning that the headed
422circular list is empty).
423
424It's unclear why the usedpools setup is so convoluted. It could be to
425minimize the amount of cache required to hold this heavily-referenced table
426(which only *needs* the two interpool pointer members of a pool_header). OTOH,
427referencing code has to remember to "double the index" and doing so isn't
428free, usedpools[0] isn't a strictly legal pointer, and we're crucially relying
429on that C doesn't insert any padding anywhere in a pool_header at or before
430the prevpool member.
431**************************************************************************** */
432
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000433#define PTA(x) ((poolp )((uchar *)&(usedpools[2*(x)]) - 2*sizeof(block *)))
434#define PT(x) PTA(x), PTA(x)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000435
436static poolp usedpools[2 * ((NB_SMALL_SIZE_CLASSES + 7) / 8) * 8] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000437 PT(0), PT(1), PT(2), PT(3), PT(4), PT(5), PT(6), PT(7)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000438#if NB_SMALL_SIZE_CLASSES > 8
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000439 , PT(8), PT(9), PT(10), PT(11), PT(12), PT(13), PT(14), PT(15)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000440#if NB_SMALL_SIZE_CLASSES > 16
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000441 , PT(16), PT(17), PT(18), PT(19), PT(20), PT(21), PT(22), PT(23)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000442#if NB_SMALL_SIZE_CLASSES > 24
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000443 , PT(24), PT(25), PT(26), PT(27), PT(28), PT(29), PT(30), PT(31)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000444#if NB_SMALL_SIZE_CLASSES > 32
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000445 , PT(32), PT(33), PT(34), PT(35), PT(36), PT(37), PT(38), PT(39)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000446#if NB_SMALL_SIZE_CLASSES > 40
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000447 , PT(40), PT(41), PT(42), PT(43), PT(44), PT(45), PT(46), PT(47)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000448#if NB_SMALL_SIZE_CLASSES > 48
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000449 , PT(48), PT(49), PT(50), PT(51), PT(52), PT(53), PT(54), PT(55)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000450#if NB_SMALL_SIZE_CLASSES > 56
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000451 , PT(56), PT(57), PT(58), PT(59), PT(60), PT(61), PT(62), PT(63)
Antoine Pitrou6f26be02011-05-03 18:18:59 +0200452#if NB_SMALL_SIZE_CLASSES > 64
453#error "NB_SMALL_SIZE_CLASSES should be less than 64"
454#endif /* NB_SMALL_SIZE_CLASSES > 64 */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000455#endif /* NB_SMALL_SIZE_CLASSES > 56 */
456#endif /* NB_SMALL_SIZE_CLASSES > 48 */
457#endif /* NB_SMALL_SIZE_CLASSES > 40 */
458#endif /* NB_SMALL_SIZE_CLASSES > 32 */
459#endif /* NB_SMALL_SIZE_CLASSES > 24 */
460#endif /* NB_SMALL_SIZE_CLASSES > 16 */
461#endif /* NB_SMALL_SIZE_CLASSES > 8 */
462};
463
Thomas Woutersa9773292006-04-21 09:43:23 +0000464/*==========================================================================
465Arena management.
Neil Schemenauera35c6882001-02-27 04:45:05 +0000466
Thomas Woutersa9773292006-04-21 09:43:23 +0000467`arenas` is a vector of arena_objects. It contains maxarenas entries, some of
468which may not be currently used (== they're arena_objects that aren't
469currently associated with an allocated arena). Note that arenas proper are
470separately malloc'ed.
Neil Schemenauera35c6882001-02-27 04:45:05 +0000471
Thomas Woutersa9773292006-04-21 09:43:23 +0000472Prior to Python 2.5, arenas were never free()'ed. Starting with Python 2.5,
473we do try to free() arenas, and use some mild heuristic strategies to increase
474the likelihood that arenas eventually can be freed.
475
476unused_arena_objects
477
478 This is a singly-linked list of the arena_objects that are currently not
479 being used (no arena is associated with them). Objects are taken off the
480 head of the list in new_arena(), and are pushed on the head of the list in
481 PyObject_Free() when the arena is empty. Key invariant: an arena_object
482 is on this list if and only if its .address member is 0.
483
484usable_arenas
485
486 This is a doubly-linked list of the arena_objects associated with arenas
487 that have pools available. These pools are either waiting to be reused,
488 or have not been used before. The list is sorted to have the most-
489 allocated arenas first (ascending order based on the nfreepools member).
490 This means that the next allocation will come from a heavily used arena,
491 which gives the nearly empty arenas a chance to be returned to the system.
492 In my unscientific tests this dramatically improved the number of arenas
493 that could be freed.
494
495Note that an arena_object associated with an arena all of whose pools are
496currently in use isn't on either list.
497*/
498
499/* Array of objects used to track chunks of memory (arenas). */
500static struct arena_object* arenas = NULL;
501/* Number of slots currently allocated in the `arenas` vector. */
Tim Peters1d99af82002-03-30 10:35:09 +0000502static uint maxarenas = 0;
Tim Petersd97a1c02002-03-30 06:09:22 +0000503
Thomas Woutersa9773292006-04-21 09:43:23 +0000504/* The head of the singly-linked, NULL-terminated list of available
505 * arena_objects.
Tim Petersd97a1c02002-03-30 06:09:22 +0000506 */
Thomas Woutersa9773292006-04-21 09:43:23 +0000507static struct arena_object* unused_arena_objects = NULL;
508
509/* The head of the doubly-linked, NULL-terminated at each end, list of
510 * arena_objects associated with arenas that have pools available.
511 */
512static struct arena_object* usable_arenas = NULL;
513
514/* How many arena_objects do we initially allocate?
515 * 16 = can allocate 16 arenas = 16 * ARENA_SIZE = 4MB before growing the
516 * `arenas` vector.
517 */
518#define INITIAL_ARENA_OBJECTS 16
519
520/* Number of arenas allocated that haven't been free()'d. */
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000521static size_t narenas_currently_allocated = 0;
Thomas Woutersa9773292006-04-21 09:43:23 +0000522
Thomas Woutersa9773292006-04-21 09:43:23 +0000523/* Total number of times malloc() called to allocate an arena. */
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000524static size_t ntimes_arena_allocated = 0;
Thomas Woutersa9773292006-04-21 09:43:23 +0000525/* High water mark (max value ever seen) for narenas_currently_allocated. */
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000526static size_t narenas_highwater = 0;
Thomas Woutersa9773292006-04-21 09:43:23 +0000527
Antoine Pitrouf9d0b122012-12-09 14:28:26 +0100528static Py_ssize_t _Py_AllocatedBlocks = 0;
529
530Py_ssize_t
531_Py_GetAllocatedBlocks(void)
532{
533 return _Py_AllocatedBlocks;
534}
535
536
Thomas Woutersa9773292006-04-21 09:43:23 +0000537/* Allocate a new arena. If we run out of memory, return NULL. Else
538 * allocate a new arena, and return the address of an arena_object
539 * describing the new arena. It's expected that the caller will set
540 * `usable_arenas` to the return value.
541 */
542static struct arena_object*
Tim Petersd97a1c02002-03-30 06:09:22 +0000543new_arena(void)
544{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000545 struct arena_object* arenaobj;
546 uint excess; /* number of bytes above pool alignment */
Victor Stinnerba108822012-03-10 00:21:44 +0100547 void *address;
548 int err;
Tim Petersd97a1c02002-03-30 06:09:22 +0000549
Tim Peters0e871182002-04-13 08:29:14 +0000550#ifdef PYMALLOC_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 if (Py_GETENV("PYTHONMALLOCSTATS"))
David Malcolm49526f42012-06-22 14:55:41 -0400552 _PyObject_DebugMallocStats(stderr);
Tim Peters0e871182002-04-13 08:29:14 +0000553#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000554 if (unused_arena_objects == NULL) {
555 uint i;
556 uint numarenas;
557 size_t nbytes;
Tim Peters0e871182002-04-13 08:29:14 +0000558
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 /* Double the number of arena objects on each allocation.
560 * Note that it's possible for `numarenas` to overflow.
561 */
562 numarenas = maxarenas ? maxarenas << 1 : INITIAL_ARENA_OBJECTS;
563 if (numarenas <= maxarenas)
564 return NULL; /* overflow */
Martin v. Löwis5aca8822008-09-11 06:55:48 +0000565#if SIZEOF_SIZE_T <= SIZEOF_INT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000566 if (numarenas > PY_SIZE_MAX / sizeof(*arenas))
567 return NULL; /* overflow */
Martin v. Löwis5aca8822008-09-11 06:55:48 +0000568#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000569 nbytes = numarenas * sizeof(*arenas);
570 arenaobj = (struct arena_object *)realloc(arenas, nbytes);
571 if (arenaobj == NULL)
572 return NULL;
573 arenas = arenaobj;
Thomas Woutersa9773292006-04-21 09:43:23 +0000574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000575 /* We might need to fix pointers that were copied. However,
576 * new_arena only gets called when all the pages in the
577 * previous arenas are full. Thus, there are *no* pointers
578 * into the old array. Thus, we don't have to worry about
579 * invalid pointers. Just to be sure, some asserts:
580 */
581 assert(usable_arenas == NULL);
582 assert(unused_arena_objects == NULL);
Thomas Woutersa9773292006-04-21 09:43:23 +0000583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000584 /* Put the new arenas on the unused_arena_objects list. */
585 for (i = maxarenas; i < numarenas; ++i) {
586 arenas[i].address = 0; /* mark as unassociated */
587 arenas[i].nextarena = i < numarenas - 1 ?
588 &arenas[i+1] : NULL;
589 }
Thomas Woutersa9773292006-04-21 09:43:23 +0000590
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000591 /* Update globals. */
592 unused_arena_objects = &arenas[maxarenas];
593 maxarenas = numarenas;
594 }
Tim Petersd97a1c02002-03-30 06:09:22 +0000595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596 /* Take the next available arena object off the head of the list. */
597 assert(unused_arena_objects != NULL);
598 arenaobj = unused_arena_objects;
599 unused_arena_objects = arenaobj->nextarena;
600 assert(arenaobj->address == 0);
Antoine Pitrouf0effe62011-11-26 01:11:02 +0100601#ifdef ARENAS_USE_MMAP
Victor Stinnerba108822012-03-10 00:21:44 +0100602 address = mmap(NULL, ARENA_SIZE, PROT_READ|PROT_WRITE,
Antoine Pitrouf0effe62011-11-26 01:11:02 +0100603 MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
Victor Stinnerba108822012-03-10 00:21:44 +0100604 err = (address == MAP_FAILED);
Antoine Pitrouf0effe62011-11-26 01:11:02 +0100605#else
Victor Stinnerba108822012-03-10 00:21:44 +0100606 address = malloc(ARENA_SIZE);
607 err = (address == 0);
Antoine Pitrouf0effe62011-11-26 01:11:02 +0100608#endif
Victor Stinnerba108822012-03-10 00:21:44 +0100609 if (err) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000610 /* The allocation failed: return NULL after putting the
611 * arenaobj back.
612 */
613 arenaobj->nextarena = unused_arena_objects;
614 unused_arena_objects = arenaobj;
615 return NULL;
616 }
Victor Stinnerba108822012-03-10 00:21:44 +0100617 arenaobj->address = (uptr)address;
Tim Petersd97a1c02002-03-30 06:09:22 +0000618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 ++narenas_currently_allocated;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000620 ++ntimes_arena_allocated;
621 if (narenas_currently_allocated > narenas_highwater)
622 narenas_highwater = narenas_currently_allocated;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000623 arenaobj->freepools = NULL;
624 /* pool_address <- first pool-aligned address in the arena
625 nfreepools <- number of whole pools that fit after alignment */
626 arenaobj->pool_address = (block*)arenaobj->address;
627 arenaobj->nfreepools = ARENA_SIZE / POOL_SIZE;
628 assert(POOL_SIZE * arenaobj->nfreepools == ARENA_SIZE);
629 excess = (uint)(arenaobj->address & POOL_SIZE_MASK);
630 if (excess != 0) {
631 --arenaobj->nfreepools;
632 arenaobj->pool_address += POOL_SIZE - excess;
633 }
634 arenaobj->ntotalpools = arenaobj->nfreepools;
Thomas Woutersa9773292006-04-21 09:43:23 +0000635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 return arenaobj;
Tim Petersd97a1c02002-03-30 06:09:22 +0000637}
638
Thomas Woutersa9773292006-04-21 09:43:23 +0000639/*
640Py_ADDRESS_IN_RANGE(P, POOL)
641
642Return true if and only if P is an address that was allocated by pymalloc.
643POOL must be the pool address associated with P, i.e., POOL = POOL_ADDR(P)
644(the caller is asked to compute this because the macro expands POOL more than
645once, and for efficiency it's best for the caller to assign POOL_ADDR(P) to a
646variable and pass the latter to the macro; because Py_ADDRESS_IN_RANGE is
647called on every alloc/realloc/free, micro-efficiency is important here).
648
649Tricky: Let B be the arena base address associated with the pool, B =
650arenas[(POOL)->arenaindex].address. Then P belongs to the arena if and only if
651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000652 B <= P < B + ARENA_SIZE
Thomas Woutersa9773292006-04-21 09:43:23 +0000653
654Subtracting B throughout, this is true iff
655
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000656 0 <= P-B < ARENA_SIZE
Thomas Woutersa9773292006-04-21 09:43:23 +0000657
658By using unsigned arithmetic, the "0 <=" half of the test can be skipped.
659
660Obscure: A PyMem "free memory" function can call the pymalloc free or realloc
661before the first arena has been allocated. `arenas` is still NULL in that
662case. We're relying on that maxarenas is also 0 in that case, so that
663(POOL)->arenaindex < maxarenas must be false, saving us from trying to index
664into a NULL arenas.
665
666Details: given P and POOL, the arena_object corresponding to P is AO =
667arenas[(POOL)->arenaindex]. Suppose obmalloc controls P. Then (barring wild
668stores, etc), POOL is the correct address of P's pool, AO.address is the
669correct base address of the pool's arena, and P must be within ARENA_SIZE of
670AO.address. In addition, AO.address is not 0 (no arena can start at address 0
671(NULL)). Therefore Py_ADDRESS_IN_RANGE correctly reports that obmalloc
672controls P.
673
674Now suppose obmalloc does not control P (e.g., P was obtained via a direct
675call to the system malloc() or realloc()). (POOL)->arenaindex may be anything
676in this case -- it may even be uninitialized trash. If the trash arenaindex
677is >= maxarenas, the macro correctly concludes at once that obmalloc doesn't
678control P.
679
680Else arenaindex is < maxarena, and AO is read up. If AO corresponds to an
681allocated arena, obmalloc controls all the memory in slice AO.address :
682AO.address+ARENA_SIZE. By case assumption, P is not controlled by obmalloc,
683so P doesn't lie in that slice, so the macro correctly reports that P is not
684controlled by obmalloc.
685
686Finally, if P is not controlled by obmalloc and AO corresponds to an unused
687arena_object (one not currently associated with an allocated arena),
688AO.address is 0, and the second test in the macro reduces to:
689
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000690 P < ARENA_SIZE
Thomas Woutersa9773292006-04-21 09:43:23 +0000691
692If P >= ARENA_SIZE (extremely likely), the macro again correctly concludes
693that P is not controlled by obmalloc. However, if P < ARENA_SIZE, this part
694of the test still passes, and the third clause (AO.address != 0) is necessary
695to get the correct result: AO.address is 0 in this case, so the macro
696correctly reports that P is not controlled by obmalloc (despite that P lies in
697slice AO.address : AO.address + ARENA_SIZE).
698
699Note: The third (AO.address != 0) clause was added in Python 2.5. Before
7002.5, arenas were never free()'ed, and an arenaindex < maxarena always
701corresponded to a currently-allocated arena, so the "P is not controlled by
702obmalloc, AO corresponds to an unused arena_object, and P < ARENA_SIZE" case
703was impossible.
704
705Note that the logic is excruciating, and reading up possibly uninitialized
706memory when P is not controlled by obmalloc (to get at (POOL)->arenaindex)
707creates problems for some memory debuggers. The overwhelming advantage is
708that this test determines whether an arbitrary address is controlled by
709obmalloc in a small constant time, independent of the number of arenas
710obmalloc controls. Since this test is needed at every entry point, it's
711extremely desirable that it be this fast.
Antoine Pitroub7fb2e22011-01-07 21:43:59 +0000712
713Since Py_ADDRESS_IN_RANGE may be reading from memory which was not allocated
714by Python, it is important that (POOL)->arenaindex is read only once, as
715another thread may be concurrently modifying the value without holding the
716GIL. To accomplish this, the arenaindex_temp variable is used to store
717(POOL)->arenaindex for the duration of the Py_ADDRESS_IN_RANGE macro's
718execution. The caller of the macro is responsible for declaring this
719variable.
Thomas Woutersa9773292006-04-21 09:43:23 +0000720*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000721#define Py_ADDRESS_IN_RANGE(P, POOL) \
Antoine Pitroub7fb2e22011-01-07 21:43:59 +0000722 ((arenaindex_temp = (POOL)->arenaindex) < maxarenas && \
723 (uptr)(P) - arenas[arenaindex_temp].address < (uptr)ARENA_SIZE && \
724 arenas[arenaindex_temp].address != 0)
Thomas Woutersa9773292006-04-21 09:43:23 +0000725
Neal Norwitz7eb3c912004-06-06 19:20:22 +0000726
727/* This is only useful when running memory debuggers such as
728 * Purify or Valgrind. Uncomment to use.
729 *
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000730#define Py_USING_MEMORY_DEBUGGER
Martin v. Löwis6fea2332008-09-25 04:15:27 +0000731 */
Neal Norwitz7eb3c912004-06-06 19:20:22 +0000732
733#ifdef Py_USING_MEMORY_DEBUGGER
734
735/* Py_ADDRESS_IN_RANGE may access uninitialized memory by design
736 * This leads to thousands of spurious warnings when using
737 * Purify or Valgrind. By making a function, we can easily
738 * suppress the uninitialized memory reads in this one function.
739 * So we won't ignore real errors elsewhere.
740 *
741 * Disable the macro and use a function.
742 */
743
744#undef Py_ADDRESS_IN_RANGE
745
Thomas Wouters89f507f2006-12-13 04:49:30 +0000746#if defined(__GNUC__) && ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 1) || \
Stefan Krah735bb122010-11-26 10:54:09 +0000747 (__GNUC__ >= 4))
Neal Norwitze5e5aa42005-11-13 18:55:39 +0000748#define Py_NO_INLINE __attribute__((__noinline__))
749#else
750#define Py_NO_INLINE
751#endif
752
753/* Don't make static, to try to ensure this isn't inlined. */
754int Py_ADDRESS_IN_RANGE(void *P, poolp pool) Py_NO_INLINE;
755#undef Py_NO_INLINE
Neal Norwitz7eb3c912004-06-06 19:20:22 +0000756#endif
Tim Peters338e0102002-04-01 19:23:44 +0000757
Neil Schemenauera35c6882001-02-27 04:45:05 +0000758/*==========================================================================*/
759
Tim Peters84c1b972002-04-04 04:44:32 +0000760/* malloc. Note that nbytes==0 tries to return a non-NULL pointer, distinct
761 * from all other currently live pointers. This may not be possible.
762 */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000763
764/*
765 * The basic blocks are ordered by decreasing execution frequency,
766 * which minimizes the number of jumps in the most common cases,
767 * improves branching prediction and instruction scheduling (small
768 * block allocations typically result in a couple of instructions).
769 * Unless the optimizer reorders everything, being too smart...
770 */
771
Neil Schemenauerd2560cd2002-04-12 03:10:20 +0000772#undef PyObject_Malloc
Neil Schemenauera35c6882001-02-27 04:45:05 +0000773void *
Neil Schemenauerd2560cd2002-04-12 03:10:20 +0000774PyObject_Malloc(size_t nbytes)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000775{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000776 block *bp;
777 poolp pool;
778 poolp next;
779 uint size;
Neil Schemenauera35c6882001-02-27 04:45:05 +0000780
Antoine Pitrou0aaaa622013-04-06 01:15:30 +0200781 _Py_AllocatedBlocks++;
782
Benjamin Peterson05159c42009-12-03 03:01:27 +0000783#ifdef WITH_VALGRIND
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 if (UNLIKELY(running_on_valgrind == -1))
785 running_on_valgrind = RUNNING_ON_VALGRIND;
786 if (UNLIKELY(running_on_valgrind))
787 goto redirect;
Benjamin Peterson05159c42009-12-03 03:01:27 +0000788#endif
789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 /*
791 * Limit ourselves to PY_SSIZE_T_MAX bytes to prevent security holes.
792 * Most python internals blindly use a signed Py_ssize_t to track
793 * things without checking for overflows or negatives.
794 * As size_t is unsigned, checking for nbytes < 0 is not required.
795 */
Antoine Pitrou0aaaa622013-04-06 01:15:30 +0200796 if (nbytes > PY_SSIZE_T_MAX) {
797 _Py_AllocatedBlocks--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000798 return NULL;
Antoine Pitrou0aaaa622013-04-06 01:15:30 +0200799 }
Antoine Pitrouf9d0b122012-12-09 14:28:26 +0100800
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000801 /*
802 * This implicitly redirects malloc(0).
803 */
804 if ((nbytes - 1) < SMALL_REQUEST_THRESHOLD) {
805 LOCK();
806 /*
807 * Most frequent paths first
808 */
809 size = (uint)(nbytes - 1) >> ALIGNMENT_SHIFT;
810 pool = usedpools[size + size];
811 if (pool != pool->nextpool) {
812 /*
813 * There is a used pool for this size class.
814 * Pick up the head block of its free list.
815 */
816 ++pool->ref.count;
817 bp = pool->freeblock;
818 assert(bp != NULL);
819 if ((pool->freeblock = *(block **)bp) != NULL) {
820 UNLOCK();
821 return (void *)bp;
822 }
823 /*
824 * Reached the end of the free list, try to extend it.
825 */
826 if (pool->nextoffset <= pool->maxnextoffset) {
827 /* There is room for another block. */
828 pool->freeblock = (block*)pool +
829 pool->nextoffset;
830 pool->nextoffset += INDEX2SIZE(size);
831 *(block **)(pool->freeblock) = NULL;
832 UNLOCK();
833 return (void *)bp;
834 }
835 /* Pool is full, unlink from used pools. */
836 next = pool->nextpool;
837 pool = pool->prevpool;
838 next->prevpool = pool;
839 pool->nextpool = next;
840 UNLOCK();
841 return (void *)bp;
842 }
Thomas Woutersa9773292006-04-21 09:43:23 +0000843
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000844 /* There isn't a pool of the right size class immediately
845 * available: use a free pool.
846 */
847 if (usable_arenas == NULL) {
848 /* No arena has a free pool: allocate a new arena. */
Thomas Woutersa9773292006-04-21 09:43:23 +0000849#ifdef WITH_MEMORY_LIMITS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000850 if (narenas_currently_allocated >= MAX_ARENAS) {
851 UNLOCK();
852 goto redirect;
853 }
Thomas Woutersa9773292006-04-21 09:43:23 +0000854#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 usable_arenas = new_arena();
856 if (usable_arenas == NULL) {
857 UNLOCK();
858 goto redirect;
859 }
860 usable_arenas->nextarena =
861 usable_arenas->prevarena = NULL;
862 }
863 assert(usable_arenas->address != 0);
Thomas Woutersa9773292006-04-21 09:43:23 +0000864
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000865 /* Try to get a cached free pool. */
866 pool = usable_arenas->freepools;
867 if (pool != NULL) {
868 /* Unlink from cached pools. */
869 usable_arenas->freepools = pool->nextpool;
Thomas Woutersa9773292006-04-21 09:43:23 +0000870
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000871 /* This arena already had the smallest nfreepools
872 * value, so decreasing nfreepools doesn't change
873 * that, and we don't need to rearrange the
874 * usable_arenas list. However, if the arena has
875 * become wholly allocated, we need to remove its
876 * arena_object from usable_arenas.
877 */
878 --usable_arenas->nfreepools;
879 if (usable_arenas->nfreepools == 0) {
880 /* Wholly allocated: remove. */
881 assert(usable_arenas->freepools == NULL);
882 assert(usable_arenas->nextarena == NULL ||
883 usable_arenas->nextarena->prevarena ==
884 usable_arenas);
Thomas Woutersa9773292006-04-21 09:43:23 +0000885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 usable_arenas = usable_arenas->nextarena;
887 if (usable_arenas != NULL) {
888 usable_arenas->prevarena = NULL;
889 assert(usable_arenas->address != 0);
890 }
891 }
892 else {
893 /* nfreepools > 0: it must be that freepools
894 * isn't NULL, or that we haven't yet carved
895 * off all the arena's pools for the first
896 * time.
897 */
898 assert(usable_arenas->freepools != NULL ||
899 usable_arenas->pool_address <=
900 (block*)usable_arenas->address +
901 ARENA_SIZE - POOL_SIZE);
902 }
903 init_pool:
904 /* Frontlink to used pools. */
905 next = usedpools[size + size]; /* == prev */
906 pool->nextpool = next;
907 pool->prevpool = next;
908 next->nextpool = pool;
909 next->prevpool = pool;
910 pool->ref.count = 1;
911 if (pool->szidx == size) {
912 /* Luckily, this pool last contained blocks
913 * of the same size class, so its header
914 * and free list are already initialized.
915 */
916 bp = pool->freeblock;
Antoine Pitrouf9d0b122012-12-09 14:28:26 +0100917 assert(bp != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 pool->freeblock = *(block **)bp;
919 UNLOCK();
920 return (void *)bp;
921 }
922 /*
923 * Initialize the pool header, set up the free list to
924 * contain just the second block, and return the first
925 * block.
926 */
927 pool->szidx = size;
928 size = INDEX2SIZE(size);
929 bp = (block *)pool + POOL_OVERHEAD;
930 pool->nextoffset = POOL_OVERHEAD + (size << 1);
931 pool->maxnextoffset = POOL_SIZE - size;
932 pool->freeblock = bp + size;
933 *(block **)(pool->freeblock) = NULL;
934 UNLOCK();
935 return (void *)bp;
936 }
Thomas Woutersa9773292006-04-21 09:43:23 +0000937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 /* Carve off a new pool. */
939 assert(usable_arenas->nfreepools > 0);
940 assert(usable_arenas->freepools == NULL);
941 pool = (poolp)usable_arenas->pool_address;
942 assert((block*)pool <= (block*)usable_arenas->address +
943 ARENA_SIZE - POOL_SIZE);
944 pool->arenaindex = usable_arenas - arenas;
945 assert(&arenas[pool->arenaindex] == usable_arenas);
946 pool->szidx = DUMMY_SIZE_IDX;
947 usable_arenas->pool_address += POOL_SIZE;
948 --usable_arenas->nfreepools;
Thomas Woutersa9773292006-04-21 09:43:23 +0000949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 if (usable_arenas->nfreepools == 0) {
951 assert(usable_arenas->nextarena == NULL ||
952 usable_arenas->nextarena->prevarena ==
953 usable_arenas);
954 /* Unlink the arena: it is completely allocated. */
955 usable_arenas = usable_arenas->nextarena;
956 if (usable_arenas != NULL) {
957 usable_arenas->prevarena = NULL;
958 assert(usable_arenas->address != 0);
959 }
960 }
Thomas Woutersa9773292006-04-21 09:43:23 +0000961
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000962 goto init_pool;
963 }
Neil Schemenauera35c6882001-02-27 04:45:05 +0000964
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000965 /* The small block allocator ends here. */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000966
Tim Petersd97a1c02002-03-30 06:09:22 +0000967redirect:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000968 /* Redirect the original request to the underlying (libc) allocator.
969 * We jump here on bigger requests, on error in the code above (as a
970 * last chance to serve the request) or when the max memory limit
971 * has been reached.
972 */
973 if (nbytes == 0)
974 nbytes = 1;
Antoine Pitrouf9d0b122012-12-09 14:28:26 +0100975 {
976 void *result = malloc(nbytes);
977 if (!result)
978 _Py_AllocatedBlocks--;
979 return result;
980 }
Neil Schemenauera35c6882001-02-27 04:45:05 +0000981}
982
983/* free */
984
Neil Schemenauerd2560cd2002-04-12 03:10:20 +0000985#undef PyObject_Free
Neil Schemenauera35c6882001-02-27 04:45:05 +0000986void
Neil Schemenauerd2560cd2002-04-12 03:10:20 +0000987PyObject_Free(void *p)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000988{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000989 poolp pool;
990 block *lastfree;
991 poolp next, prev;
992 uint size;
Antoine Pitroub7fb2e22011-01-07 21:43:59 +0000993#ifndef Py_USING_MEMORY_DEBUGGER
994 uint arenaindex_temp;
995#endif
Neil Schemenauera35c6882001-02-27 04:45:05 +0000996
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 if (p == NULL) /* free(NULL) has no effect */
998 return;
Neil Schemenauera35c6882001-02-27 04:45:05 +0000999
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001000 _Py_AllocatedBlocks--;
1001
Benjamin Peterson05159c42009-12-03 03:01:27 +00001002#ifdef WITH_VALGRIND
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001003 if (UNLIKELY(running_on_valgrind > 0))
1004 goto redirect;
Benjamin Peterson05159c42009-12-03 03:01:27 +00001005#endif
1006
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001007 pool = POOL_ADDR(p);
1008 if (Py_ADDRESS_IN_RANGE(p, pool)) {
1009 /* We allocated this address. */
1010 LOCK();
1011 /* Link p to the start of the pool's freeblock list. Since
1012 * the pool had at least the p block outstanding, the pool
1013 * wasn't empty (so it's already in a usedpools[] list, or
1014 * was full and is in no list -- it's not in the freeblocks
1015 * list in any case).
1016 */
1017 assert(pool->ref.count > 0); /* else it was empty */
1018 *(block **)p = lastfree = pool->freeblock;
1019 pool->freeblock = (block *)p;
1020 if (lastfree) {
1021 struct arena_object* ao;
1022 uint nf; /* ao->nfreepools */
Thomas Woutersa9773292006-04-21 09:43:23 +00001023
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001024 /* freeblock wasn't NULL, so the pool wasn't full,
1025 * and the pool is in a usedpools[] list.
1026 */
1027 if (--pool->ref.count != 0) {
1028 /* pool isn't empty: leave it in usedpools */
1029 UNLOCK();
1030 return;
1031 }
1032 /* Pool is now empty: unlink from usedpools, and
1033 * link to the front of freepools. This ensures that
1034 * previously freed pools will be allocated later
1035 * (being not referenced, they are perhaps paged out).
1036 */
1037 next = pool->nextpool;
1038 prev = pool->prevpool;
1039 next->prevpool = prev;
1040 prev->nextpool = next;
Thomas Woutersa9773292006-04-21 09:43:23 +00001041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 /* Link the pool to freepools. This is a singly-linked
1043 * list, and pool->prevpool isn't used there.
1044 */
1045 ao = &arenas[pool->arenaindex];
1046 pool->nextpool = ao->freepools;
1047 ao->freepools = pool;
1048 nf = ++ao->nfreepools;
Thomas Woutersa9773292006-04-21 09:43:23 +00001049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 /* All the rest is arena management. We just freed
1051 * a pool, and there are 4 cases for arena mgmt:
1052 * 1. If all the pools are free, return the arena to
1053 * the system free().
1054 * 2. If this is the only free pool in the arena,
1055 * add the arena back to the `usable_arenas` list.
1056 * 3. If the "next" arena has a smaller count of free
1057 * pools, we have to "slide this arena right" to
1058 * restore that usable_arenas is sorted in order of
1059 * nfreepools.
1060 * 4. Else there's nothing more to do.
1061 */
1062 if (nf == ao->ntotalpools) {
1063 /* Case 1. First unlink ao from usable_arenas.
1064 */
1065 assert(ao->prevarena == NULL ||
1066 ao->prevarena->address != 0);
1067 assert(ao ->nextarena == NULL ||
1068 ao->nextarena->address != 0);
Thomas Woutersa9773292006-04-21 09:43:23 +00001069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 /* Fix the pointer in the prevarena, or the
1071 * usable_arenas pointer.
1072 */
1073 if (ao->prevarena == NULL) {
1074 usable_arenas = ao->nextarena;
1075 assert(usable_arenas == NULL ||
1076 usable_arenas->address != 0);
1077 }
1078 else {
1079 assert(ao->prevarena->nextarena == ao);
1080 ao->prevarena->nextarena =
1081 ao->nextarena;
1082 }
1083 /* Fix the pointer in the nextarena. */
1084 if (ao->nextarena != NULL) {
1085 assert(ao->nextarena->prevarena == ao);
1086 ao->nextarena->prevarena =
1087 ao->prevarena;
1088 }
1089 /* Record that this arena_object slot is
1090 * available to be reused.
1091 */
1092 ao->nextarena = unused_arena_objects;
1093 unused_arena_objects = ao;
Thomas Woutersa9773292006-04-21 09:43:23 +00001094
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001095 /* Free the entire arena. */
Antoine Pitrouf0effe62011-11-26 01:11:02 +01001096#ifdef ARENAS_USE_MMAP
1097 munmap((void *)ao->address, ARENA_SIZE);
1098#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001099 free((void *)ao->address);
Antoine Pitrouf0effe62011-11-26 01:11:02 +01001100#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001101 ao->address = 0; /* mark unassociated */
1102 --narenas_currently_allocated;
Thomas Woutersa9773292006-04-21 09:43:23 +00001103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001104 UNLOCK();
1105 return;
1106 }
1107 if (nf == 1) {
1108 /* Case 2. Put ao at the head of
1109 * usable_arenas. Note that because
1110 * ao->nfreepools was 0 before, ao isn't
1111 * currently on the usable_arenas list.
1112 */
1113 ao->nextarena = usable_arenas;
1114 ao->prevarena = NULL;
1115 if (usable_arenas)
1116 usable_arenas->prevarena = ao;
1117 usable_arenas = ao;
1118 assert(usable_arenas->address != 0);
Thomas Woutersa9773292006-04-21 09:43:23 +00001119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001120 UNLOCK();
1121 return;
1122 }
1123 /* If this arena is now out of order, we need to keep
1124 * the list sorted. The list is kept sorted so that
1125 * the "most full" arenas are used first, which allows
1126 * the nearly empty arenas to be completely freed. In
1127 * a few un-scientific tests, it seems like this
1128 * approach allowed a lot more memory to be freed.
1129 */
1130 if (ao->nextarena == NULL ||
1131 nf <= ao->nextarena->nfreepools) {
1132 /* Case 4. Nothing to do. */
1133 UNLOCK();
1134 return;
1135 }
1136 /* Case 3: We have to move the arena towards the end
1137 * of the list, because it has more free pools than
1138 * the arena to its right.
1139 * First unlink ao from usable_arenas.
1140 */
1141 if (ao->prevarena != NULL) {
1142 /* ao isn't at the head of the list */
1143 assert(ao->prevarena->nextarena == ao);
1144 ao->prevarena->nextarena = ao->nextarena;
1145 }
1146 else {
1147 /* ao is at the head of the list */
1148 assert(usable_arenas == ao);
1149 usable_arenas = ao->nextarena;
1150 }
1151 ao->nextarena->prevarena = ao->prevarena;
Thomas Woutersa9773292006-04-21 09:43:23 +00001152
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001153 /* Locate the new insertion point by iterating over
1154 * the list, using our nextarena pointer.
1155 */
1156 while (ao->nextarena != NULL &&
1157 nf > ao->nextarena->nfreepools) {
1158 ao->prevarena = ao->nextarena;
1159 ao->nextarena = ao->nextarena->nextarena;
1160 }
Thomas Woutersa9773292006-04-21 09:43:23 +00001161
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001162 /* Insert ao at this point. */
1163 assert(ao->nextarena == NULL ||
1164 ao->prevarena == ao->nextarena->prevarena);
1165 assert(ao->prevarena->nextarena == ao->nextarena);
Thomas Woutersa9773292006-04-21 09:43:23 +00001166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001167 ao->prevarena->nextarena = ao;
1168 if (ao->nextarena != NULL)
1169 ao->nextarena->prevarena = ao;
Thomas Woutersa9773292006-04-21 09:43:23 +00001170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001171 /* Verify that the swaps worked. */
1172 assert(ao->nextarena == NULL ||
1173 nf <= ao->nextarena->nfreepools);
1174 assert(ao->prevarena == NULL ||
1175 nf > ao->prevarena->nfreepools);
1176 assert(ao->nextarena == NULL ||
1177 ao->nextarena->prevarena == ao);
1178 assert((usable_arenas == ao &&
1179 ao->prevarena == NULL) ||
1180 ao->prevarena->nextarena == ao);
Thomas Woutersa9773292006-04-21 09:43:23 +00001181
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 UNLOCK();
1183 return;
1184 }
1185 /* Pool was full, so doesn't currently live in any list:
1186 * link it to the front of the appropriate usedpools[] list.
1187 * This mimics LRU pool usage for new allocations and
1188 * targets optimal filling when several pools contain
1189 * blocks of the same size class.
1190 */
1191 --pool->ref.count;
1192 assert(pool->ref.count > 0); /* else the pool is empty */
1193 size = pool->szidx;
1194 next = usedpools[size + size];
1195 prev = next->prevpool;
1196 /* insert pool before next: prev <-> pool <-> next */
1197 pool->nextpool = next;
1198 pool->prevpool = prev;
1199 next->prevpool = pool;
1200 prev->nextpool = pool;
1201 UNLOCK();
1202 return;
1203 }
Neil Schemenauera35c6882001-02-27 04:45:05 +00001204
Benjamin Peterson05159c42009-12-03 03:01:27 +00001205#ifdef WITH_VALGRIND
1206redirect:
1207#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001208 /* We didn't allocate this address. */
1209 free(p);
Neil Schemenauera35c6882001-02-27 04:45:05 +00001210}
1211
Tim Peters84c1b972002-04-04 04:44:32 +00001212/* realloc. If p is NULL, this acts like malloc(nbytes). Else if nbytes==0,
1213 * then as the Python docs promise, we do not treat this like free(p), and
1214 * return a non-NULL result.
1215 */
Neil Schemenauera35c6882001-02-27 04:45:05 +00001216
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00001217#undef PyObject_Realloc
Neil Schemenauera35c6882001-02-27 04:45:05 +00001218void *
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00001219PyObject_Realloc(void *p, size_t nbytes)
Neil Schemenauera35c6882001-02-27 04:45:05 +00001220{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001221 void *bp;
1222 poolp pool;
1223 size_t size;
Antoine Pitroub7fb2e22011-01-07 21:43:59 +00001224#ifndef Py_USING_MEMORY_DEBUGGER
1225 uint arenaindex_temp;
1226#endif
Neil Schemenauera35c6882001-02-27 04:45:05 +00001227
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001228 if (p == NULL)
1229 return PyObject_Malloc(nbytes);
Neil Schemenauera35c6882001-02-27 04:45:05 +00001230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001231 /*
1232 * Limit ourselves to PY_SSIZE_T_MAX bytes to prevent security holes.
1233 * Most python internals blindly use a signed Py_ssize_t to track
1234 * things without checking for overflows or negatives.
1235 * As size_t is unsigned, checking for nbytes < 0 is not required.
1236 */
1237 if (nbytes > PY_SSIZE_T_MAX)
1238 return NULL;
Georg Brandld492ad82008-07-23 16:13:07 +00001239
Benjamin Peterson05159c42009-12-03 03:01:27 +00001240#ifdef WITH_VALGRIND
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001241 /* Treat running_on_valgrind == -1 the same as 0 */
1242 if (UNLIKELY(running_on_valgrind > 0))
1243 goto redirect;
Benjamin Peterson05159c42009-12-03 03:01:27 +00001244#endif
1245
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001246 pool = POOL_ADDR(p);
1247 if (Py_ADDRESS_IN_RANGE(p, pool)) {
1248 /* We're in charge of this block */
1249 size = INDEX2SIZE(pool->szidx);
1250 if (nbytes <= size) {
1251 /* The block is staying the same or shrinking. If
1252 * it's shrinking, there's a tradeoff: it costs
1253 * cycles to copy the block to a smaller size class,
1254 * but it wastes memory not to copy it. The
1255 * compromise here is to copy on shrink only if at
1256 * least 25% of size can be shaved off.
1257 */
1258 if (4 * nbytes > 3 * size) {
1259 /* It's the same,
1260 * or shrinking and new/old > 3/4.
1261 */
1262 return p;
1263 }
1264 size = nbytes;
1265 }
1266 bp = PyObject_Malloc(nbytes);
1267 if (bp != NULL) {
1268 memcpy(bp, p, size);
1269 PyObject_Free(p);
1270 }
1271 return bp;
1272 }
Benjamin Peterson05159c42009-12-03 03:01:27 +00001273#ifdef WITH_VALGRIND
1274 redirect:
1275#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001276 /* We're not managing this block. If nbytes <=
1277 * SMALL_REQUEST_THRESHOLD, it's tempting to try to take over this
1278 * block. However, if we do, we need to copy the valid data from
1279 * the C-managed block to one of our blocks, and there's no portable
1280 * way to know how much of the memory space starting at p is valid.
1281 * As bug 1185883 pointed out the hard way, it's possible that the
1282 * C-managed block is "at the end" of allocated VM space, so that
1283 * a memory fault can occur if we try to copy nbytes bytes starting
1284 * at p. Instead we punt: let C continue to manage this block.
1285 */
1286 if (nbytes)
1287 return realloc(p, nbytes);
1288 /* C doesn't define the result of realloc(p, 0) (it may or may not
1289 * return NULL then), but Python's docs promise that nbytes==0 never
1290 * returns NULL. We don't pass 0 to realloc(), to avoid that endcase
1291 * to begin with. Even then, we can't be sure that realloc() won't
1292 * return NULL.
1293 */
1294 bp = realloc(p, 1);
1295 return bp ? bp : p;
Neil Schemenauera35c6882001-02-27 04:45:05 +00001296}
1297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001298#else /* ! WITH_PYMALLOC */
Tim Petersddea2082002-03-23 10:03:50 +00001299
1300/*==========================================================================*/
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00001301/* pymalloc not enabled: Redirect the entry points to malloc. These will
1302 * only be used by extensions that are compiled with pymalloc enabled. */
Tim Peters62c06ba2002-03-23 22:28:18 +00001303
Tim Petersce7fb9b2002-03-23 00:28:57 +00001304void *
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00001305PyObject_Malloc(size_t n)
Tim Peters1221c0a2002-03-23 00:20:15 +00001306{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001307 return PyMem_MALLOC(n);
Tim Peters1221c0a2002-03-23 00:20:15 +00001308}
1309
Tim Petersce7fb9b2002-03-23 00:28:57 +00001310void *
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00001311PyObject_Realloc(void *p, size_t n)
Tim Peters1221c0a2002-03-23 00:20:15 +00001312{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001313 return PyMem_REALLOC(p, n);
Tim Peters1221c0a2002-03-23 00:20:15 +00001314}
1315
1316void
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00001317PyObject_Free(void *p)
Tim Peters1221c0a2002-03-23 00:20:15 +00001318{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001319 PyMem_FREE(p);
Tim Peters1221c0a2002-03-23 00:20:15 +00001320}
Antoine Pitrou92840532012-12-17 23:05:59 +01001321
1322Py_ssize_t
1323_Py_GetAllocatedBlocks(void)
1324{
1325 return 0;
1326}
1327
Tim Peters1221c0a2002-03-23 00:20:15 +00001328#endif /* WITH_PYMALLOC */
1329
Tim Petersddea2082002-03-23 10:03:50 +00001330#ifdef PYMALLOC_DEBUG
1331/*==========================================================================*/
Tim Peters62c06ba2002-03-23 22:28:18 +00001332/* A x-platform debugging allocator. This doesn't manage memory directly,
1333 * it wraps a real allocator, adding extra debugging info to the memory blocks.
1334 */
Tim Petersddea2082002-03-23 10:03:50 +00001335
Tim Petersf6fb5012002-04-12 07:38:53 +00001336/* Special bytes broadcast into debug memory blocks at appropriate times.
1337 * Strings of these are unlikely to be valid addresses, floats, ints or
1338 * 7-bit ASCII.
1339 */
1340#undef CLEANBYTE
1341#undef DEADBYTE
1342#undef FORBIDDENBYTE
1343#define CLEANBYTE 0xCB /* clean (newly allocated) memory */
Tim Peters889f61d2002-07-10 19:29:49 +00001344#define DEADBYTE 0xDB /* dead (newly freed) memory */
Tim Petersf6fb5012002-04-12 07:38:53 +00001345#define FORBIDDENBYTE 0xFB /* untouchable bytes at each end of a block */
Tim Petersddea2082002-03-23 10:03:50 +00001346
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00001347/* We tag each block with an API ID in order to tag API violations */
1348#define _PYMALLOC_MEM_ID 'm' /* the PyMem_Malloc() API */
1349#define _PYMALLOC_OBJ_ID 'o' /* The PyObject_Malloc() API */
1350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001351static size_t serialno = 0; /* incremented on each debug {m,re}alloc */
Tim Petersddea2082002-03-23 10:03:50 +00001352
Tim Peterse0850172002-03-24 00:34:21 +00001353/* serialno is always incremented via calling this routine. The point is
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001354 * to supply a single place to set a breakpoint.
1355 */
Tim Peterse0850172002-03-24 00:34:21 +00001356static void
Neil Schemenauerbd02b142002-03-28 21:05:38 +00001357bumpserialno(void)
Tim Peterse0850172002-03-24 00:34:21 +00001358{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001359 ++serialno;
Tim Peterse0850172002-03-24 00:34:21 +00001360}
1361
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001362#define SST SIZEOF_SIZE_T
Tim Peterse0850172002-03-24 00:34:21 +00001363
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001364/* Read sizeof(size_t) bytes at p as a big-endian size_t. */
1365static size_t
1366read_size_t(const void *p)
Tim Petersddea2082002-03-23 10:03:50 +00001367{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001368 const uchar *q = (const uchar *)p;
1369 size_t result = *q++;
1370 int i;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001371
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001372 for (i = SST; --i > 0; ++q)
1373 result = (result << 8) | *q;
1374 return result;
Tim Petersddea2082002-03-23 10:03:50 +00001375}
1376
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001377/* Write n as a big-endian size_t, MSB at address p, LSB at
1378 * p + sizeof(size_t) - 1.
1379 */
Tim Petersddea2082002-03-23 10:03:50 +00001380static void
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001381write_size_t(void *p, size_t n)
Tim Petersddea2082002-03-23 10:03:50 +00001382{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001383 uchar *q = (uchar *)p + SST - 1;
1384 int i;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001386 for (i = SST; --i >= 0; --q) {
1387 *q = (uchar)(n & 0xff);
1388 n >>= 8;
1389 }
Tim Petersddea2082002-03-23 10:03:50 +00001390}
1391
Tim Peters08d82152002-04-18 22:25:03 +00001392#ifdef Py_DEBUG
1393/* Is target in the list? The list is traversed via the nextpool pointers.
1394 * The list may be NULL-terminated, or circular. Return 1 if target is in
1395 * list, else 0.
1396 */
1397static int
1398pool_is_in_list(const poolp target, poolp list)
1399{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001400 poolp origlist = list;
1401 assert(target != NULL);
1402 if (list == NULL)
1403 return 0;
1404 do {
1405 if (target == list)
1406 return 1;
1407 list = list->nextpool;
1408 } while (list != NULL && list != origlist);
1409 return 0;
Tim Peters08d82152002-04-18 22:25:03 +00001410}
1411
1412#else
1413#define pool_is_in_list(X, Y) 1
1414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001415#endif /* Py_DEBUG */
Tim Peters08d82152002-04-18 22:25:03 +00001416
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001417/* Let S = sizeof(size_t). The debug malloc asks for 4*S extra bytes and
1418 fills them with useful stuff, here calling the underlying malloc's result p:
Tim Petersddea2082002-03-23 10:03:50 +00001419
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001420p[0: S]
1421 Number of bytes originally asked for. This is a size_t, big-endian (easier
1422 to read in a memory dump).
1423p[S: 2*S]
Tim Petersf6fb5012002-04-12 07:38:53 +00001424 Copies of FORBIDDENBYTE. Used to catch under- writes and reads.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001425p[2*S: 2*S+n]
Tim Petersf6fb5012002-04-12 07:38:53 +00001426 The requested memory, filled with copies of CLEANBYTE.
Tim Petersddea2082002-03-23 10:03:50 +00001427 Used to catch reference to uninitialized memory.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001428 &p[2*S] is returned. Note that this is 8-byte aligned if pymalloc
Tim Petersddea2082002-03-23 10:03:50 +00001429 handled the request itself.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001430p[2*S+n: 2*S+n+S]
Tim Petersf6fb5012002-04-12 07:38:53 +00001431 Copies of FORBIDDENBYTE. Used to catch over- writes and reads.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001432p[2*S+n+S: 2*S+n+2*S]
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00001433 A serial number, incremented by 1 on each call to _PyObject_DebugMalloc
1434 and _PyObject_DebugRealloc.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001435 This is a big-endian size_t.
Tim Petersddea2082002-03-23 10:03:50 +00001436 If "bad memory" is detected later, the serial number gives an
1437 excellent way to set a breakpoint on the next run, to capture the
1438 instant at which this block was passed out.
1439*/
1440
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00001441/* debug replacements for the PyMem_* memory API */
1442void *
1443_PyMem_DebugMalloc(size_t nbytes)
1444{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001445 return _PyObject_DebugMallocApi(_PYMALLOC_MEM_ID, nbytes);
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00001446}
1447void *
1448_PyMem_DebugRealloc(void *p, size_t nbytes)
1449{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001450 return _PyObject_DebugReallocApi(_PYMALLOC_MEM_ID, p, nbytes);
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00001451}
1452void
1453_PyMem_DebugFree(void *p)
1454{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001455 _PyObject_DebugFreeApi(_PYMALLOC_MEM_ID, p);
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00001456}
1457
1458/* debug replacements for the PyObject_* memory API */
Tim Petersddea2082002-03-23 10:03:50 +00001459void *
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00001460_PyObject_DebugMalloc(size_t nbytes)
Tim Petersddea2082002-03-23 10:03:50 +00001461{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001462 return _PyObject_DebugMallocApi(_PYMALLOC_OBJ_ID, nbytes);
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00001463}
1464void *
1465_PyObject_DebugRealloc(void *p, size_t nbytes)
1466{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001467 return _PyObject_DebugReallocApi(_PYMALLOC_OBJ_ID, p, nbytes);
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00001468}
1469void
1470_PyObject_DebugFree(void *p)
1471{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001472 _PyObject_DebugFreeApi(_PYMALLOC_OBJ_ID, p);
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00001473}
1474void
Kristján Valur Jónsson34369002009-09-28 15:57:53 +00001475_PyObject_DebugCheckAddress(const void *p)
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00001476{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001477 _PyObject_DebugCheckAddressApi(_PYMALLOC_OBJ_ID, p);
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00001478}
1479
1480
1481/* generic debug memory api, with an "id" to identify the API in use */
1482void *
1483_PyObject_DebugMallocApi(char id, size_t nbytes)
1484{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001485 uchar *p; /* base address of malloc'ed block */
1486 uchar *tail; /* p + 2*SST + nbytes == pointer to tail pad bytes */
1487 size_t total; /* nbytes + 4*SST */
Tim Petersddea2082002-03-23 10:03:50 +00001488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001489 bumpserialno();
1490 total = nbytes + 4*SST;
1491 if (total < nbytes)
1492 /* overflow: can't represent total as a size_t */
1493 return NULL;
Tim Petersddea2082002-03-23 10:03:50 +00001494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001495 p = (uchar *)PyObject_Malloc(total);
1496 if (p == NULL)
1497 return NULL;
Tim Petersddea2082002-03-23 10:03:50 +00001498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001499 /* at p, write size (SST bytes), id (1 byte), pad (SST-1 bytes) */
1500 write_size_t(p, nbytes);
1501 p[SST] = (uchar)id;
1502 memset(p + SST + 1 , FORBIDDENBYTE, SST-1);
Tim Petersddea2082002-03-23 10:03:50 +00001503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001504 if (nbytes > 0)
1505 memset(p + 2*SST, CLEANBYTE, nbytes);
Tim Petersddea2082002-03-23 10:03:50 +00001506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001507 /* at tail, write pad (SST bytes) and serialno (SST bytes) */
1508 tail = p + 2*SST + nbytes;
1509 memset(tail, FORBIDDENBYTE, SST);
1510 write_size_t(tail + SST, serialno);
Tim Petersddea2082002-03-23 10:03:50 +00001511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001512 return p + 2*SST;
Tim Petersddea2082002-03-23 10:03:50 +00001513}
1514
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001515/* The debug free first checks the 2*SST bytes on each end for sanity (in
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00001516 particular, that the FORBIDDENBYTEs with the api ID are still intact).
Tim Petersf6fb5012002-04-12 07:38:53 +00001517 Then fills the original bytes with DEADBYTE.
Tim Petersddea2082002-03-23 10:03:50 +00001518 Then calls the underlying free.
1519*/
1520void
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00001521_PyObject_DebugFreeApi(char api, void *p)
Tim Petersddea2082002-03-23 10:03:50 +00001522{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001523 uchar *q = (uchar *)p - 2*SST; /* address returned from malloc */
1524 size_t nbytes;
Tim Petersddea2082002-03-23 10:03:50 +00001525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001526 if (p == NULL)
1527 return;
1528 _PyObject_DebugCheckAddressApi(api, p);
1529 nbytes = read_size_t(q);
1530 nbytes += 4*SST;
1531 if (nbytes > 0)
1532 memset(q, DEADBYTE, nbytes);
1533 PyObject_Free(q);
Tim Petersddea2082002-03-23 10:03:50 +00001534}
1535
1536void *
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00001537_PyObject_DebugReallocApi(char api, void *p, size_t nbytes)
Tim Petersddea2082002-03-23 10:03:50 +00001538{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001539 uchar *q = (uchar *)p;
1540 uchar *tail;
1541 size_t total; /* nbytes + 4*SST */
1542 size_t original_nbytes;
1543 int i;
Tim Petersddea2082002-03-23 10:03:50 +00001544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001545 if (p == NULL)
1546 return _PyObject_DebugMallocApi(api, nbytes);
Tim Petersddea2082002-03-23 10:03:50 +00001547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001548 _PyObject_DebugCheckAddressApi(api, p);
1549 bumpserialno();
1550 original_nbytes = read_size_t(q - 2*SST);
1551 total = nbytes + 4*SST;
1552 if (total < nbytes)
1553 /* overflow: can't represent total as a size_t */
1554 return NULL;
Tim Petersddea2082002-03-23 10:03:50 +00001555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001556 if (nbytes < original_nbytes) {
1557 /* shrinking: mark old extra memory dead */
1558 memset(q + nbytes, DEADBYTE, original_nbytes - nbytes + 2*SST);
1559 }
Tim Petersddea2082002-03-23 10:03:50 +00001560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001561 /* Resize and add decorations. We may get a new pointer here, in which
1562 * case we didn't get the chance to mark the old memory with DEADBYTE,
1563 * but we live with that.
1564 */
1565 q = (uchar *)PyObject_Realloc(q - 2*SST, total);
1566 if (q == NULL)
1567 return NULL;
Tim Peters85cc1c42002-04-12 08:52:50 +00001568
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001569 write_size_t(q, nbytes);
1570 assert(q[SST] == (uchar)api);
1571 for (i = 1; i < SST; ++i)
1572 assert(q[SST + i] == FORBIDDENBYTE);
1573 q += 2*SST;
1574 tail = q + nbytes;
1575 memset(tail, FORBIDDENBYTE, SST);
1576 write_size_t(tail + SST, serialno);
Tim Peters85cc1c42002-04-12 08:52:50 +00001577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001578 if (nbytes > original_nbytes) {
1579 /* growing: mark new extra memory clean */
1580 memset(q + original_nbytes, CLEANBYTE,
Stefan Krah735bb122010-11-26 10:54:09 +00001581 nbytes - original_nbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001582 }
Tim Peters85cc1c42002-04-12 08:52:50 +00001583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001584 return q;
Tim Petersddea2082002-03-23 10:03:50 +00001585}
1586
Tim Peters7ccfadf2002-04-01 06:04:21 +00001587/* Check the forbidden bytes on both ends of the memory allocated for p.
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00001588 * If anything is wrong, print info to stderr via _PyObject_DebugDumpAddress,
Tim Peters7ccfadf2002-04-01 06:04:21 +00001589 * and call Py_FatalError to kill the program.
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00001590 * The API id, is also checked.
Tim Peters7ccfadf2002-04-01 06:04:21 +00001591 */
1592 void
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00001593_PyObject_DebugCheckAddressApi(char api, const void *p)
Tim Petersddea2082002-03-23 10:03:50 +00001594{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001595 const uchar *q = (const uchar *)p;
1596 char msgbuf[64];
1597 char *msg;
1598 size_t nbytes;
1599 const uchar *tail;
1600 int i;
1601 char id;
Tim Petersddea2082002-03-23 10:03:50 +00001602
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001603 if (p == NULL) {
1604 msg = "didn't expect a NULL pointer";
1605 goto error;
1606 }
Tim Petersddea2082002-03-23 10:03:50 +00001607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001608 /* Check the API id */
1609 id = (char)q[-SST];
1610 if (id != api) {
1611 msg = msgbuf;
1612 snprintf(msg, sizeof(msgbuf), "bad ID: Allocated using API '%c', verified using API '%c'", id, api);
1613 msgbuf[sizeof(msgbuf)-1] = 0;
1614 goto error;
1615 }
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00001616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001617 /* Check the stuff at the start of p first: if there's underwrite
1618 * corruption, the number-of-bytes field may be nuts, and checking
1619 * the tail could lead to a segfault then.
1620 */
1621 for (i = SST-1; i >= 1; --i) {
1622 if (*(q-i) != FORBIDDENBYTE) {
1623 msg = "bad leading pad byte";
1624 goto error;
1625 }
1626 }
Tim Petersddea2082002-03-23 10:03:50 +00001627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001628 nbytes = read_size_t(q - 2*SST);
1629 tail = q + nbytes;
1630 for (i = 0; i < SST; ++i) {
1631 if (tail[i] != FORBIDDENBYTE) {
1632 msg = "bad trailing pad byte";
1633 goto error;
1634 }
1635 }
Tim Petersddea2082002-03-23 10:03:50 +00001636
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001637 return;
Tim Petersd1139e02002-03-28 07:32:11 +00001638
1639error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001640 _PyObject_DebugDumpAddress(p);
1641 Py_FatalError(msg);
Tim Petersddea2082002-03-23 10:03:50 +00001642}
1643
Tim Peters7ccfadf2002-04-01 06:04:21 +00001644/* Display info to stderr about the memory block at p. */
Tim Petersddea2082002-03-23 10:03:50 +00001645void
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00001646_PyObject_DebugDumpAddress(const void *p)
Tim Petersddea2082002-03-23 10:03:50 +00001647{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001648 const uchar *q = (const uchar *)p;
1649 const uchar *tail;
1650 size_t nbytes, serial;
1651 int i;
1652 int ok;
1653 char id;
Tim Petersddea2082002-03-23 10:03:50 +00001654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001655 fprintf(stderr, "Debug memory block at address p=%p:", p);
1656 if (p == NULL) {
1657 fprintf(stderr, "\n");
1658 return;
1659 }
1660 id = (char)q[-SST];
1661 fprintf(stderr, " API '%c'\n", id);
Tim Petersddea2082002-03-23 10:03:50 +00001662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001663 nbytes = read_size_t(q - 2*SST);
1664 fprintf(stderr, " %" PY_FORMAT_SIZE_T "u bytes originally "
1665 "requested\n", nbytes);
Tim Petersddea2082002-03-23 10:03:50 +00001666
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001667 /* In case this is nuts, check the leading pad bytes first. */
1668 fprintf(stderr, " The %d pad bytes at p-%d are ", SST-1, SST-1);
1669 ok = 1;
1670 for (i = 1; i <= SST-1; ++i) {
1671 if (*(q-i) != FORBIDDENBYTE) {
1672 ok = 0;
1673 break;
1674 }
1675 }
1676 if (ok)
1677 fputs("FORBIDDENBYTE, as expected.\n", stderr);
1678 else {
1679 fprintf(stderr, "not all FORBIDDENBYTE (0x%02x):\n",
1680 FORBIDDENBYTE);
1681 for (i = SST-1; i >= 1; --i) {
1682 const uchar byte = *(q-i);
1683 fprintf(stderr, " at p-%d: 0x%02x", i, byte);
1684 if (byte != FORBIDDENBYTE)
1685 fputs(" *** OUCH", stderr);
1686 fputc('\n', stderr);
1687 }
Tim Peters449b5a82002-04-28 06:14:45 +00001688
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001689 fputs(" Because memory is corrupted at the start, the "
1690 "count of bytes requested\n"
1691 " may be bogus, and checking the trailing pad "
1692 "bytes may segfault.\n", stderr);
1693 }
Tim Petersddea2082002-03-23 10:03:50 +00001694
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001695 tail = q + nbytes;
1696 fprintf(stderr, " The %d pad bytes at tail=%p are ", SST, tail);
1697 ok = 1;
1698 for (i = 0; i < SST; ++i) {
1699 if (tail[i] != FORBIDDENBYTE) {
1700 ok = 0;
1701 break;
1702 }
1703 }
1704 if (ok)
1705 fputs("FORBIDDENBYTE, as expected.\n", stderr);
1706 else {
1707 fprintf(stderr, "not all FORBIDDENBYTE (0x%02x):\n",
Stefan Krah735bb122010-11-26 10:54:09 +00001708 FORBIDDENBYTE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001709 for (i = 0; i < SST; ++i) {
1710 const uchar byte = tail[i];
1711 fprintf(stderr, " at tail+%d: 0x%02x",
Stefan Krah735bb122010-11-26 10:54:09 +00001712 i, byte);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001713 if (byte != FORBIDDENBYTE)
1714 fputs(" *** OUCH", stderr);
1715 fputc('\n', stderr);
1716 }
1717 }
Tim Petersddea2082002-03-23 10:03:50 +00001718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001719 serial = read_size_t(tail + SST);
1720 fprintf(stderr, " The block was made by call #%" PY_FORMAT_SIZE_T
1721 "u to debug malloc/realloc.\n", serial);
Tim Petersddea2082002-03-23 10:03:50 +00001722
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001723 if (nbytes > 0) {
1724 i = 0;
1725 fputs(" Data at p:", stderr);
1726 /* print up to 8 bytes at the start */
1727 while (q < tail && i < 8) {
1728 fprintf(stderr, " %02x", *q);
1729 ++i;
1730 ++q;
1731 }
1732 /* and up to 8 at the end */
1733 if (q < tail) {
1734 if (tail - q > 8) {
1735 fputs(" ...", stderr);
1736 q = tail - 8;
1737 }
1738 while (q < tail) {
1739 fprintf(stderr, " %02x", *q);
1740 ++q;
1741 }
1742 }
1743 fputc('\n', stderr);
1744 }
Tim Petersddea2082002-03-23 10:03:50 +00001745}
1746
David Malcolm49526f42012-06-22 14:55:41 -04001747#endif /* PYMALLOC_DEBUG */
1748
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001749static size_t
David Malcolm49526f42012-06-22 14:55:41 -04001750printone(FILE *out, const char* msg, size_t value)
Tim Peters16bcb6b2002-04-05 05:45:31 +00001751{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001752 int i, k;
1753 char buf[100];
1754 size_t origvalue = value;
Tim Peters16bcb6b2002-04-05 05:45:31 +00001755
David Malcolm49526f42012-06-22 14:55:41 -04001756 fputs(msg, out);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001757 for (i = (int)strlen(msg); i < 35; ++i)
David Malcolm49526f42012-06-22 14:55:41 -04001758 fputc(' ', out);
1759 fputc('=', out);
Tim Peters49f26812002-04-06 01:45:35 +00001760
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001761 /* Write the value with commas. */
1762 i = 22;
1763 buf[i--] = '\0';
1764 buf[i--] = '\n';
1765 k = 3;
1766 do {
1767 size_t nextvalue = value / 10;
Benjamin Peterson2dba1ee2013-02-20 16:54:30 -05001768 unsigned int digit = (unsigned int)(value - nextvalue * 10);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001769 value = nextvalue;
1770 buf[i--] = (char)(digit + '0');
1771 --k;
1772 if (k == 0 && value && i >= 0) {
1773 k = 3;
1774 buf[i--] = ',';
1775 }
1776 } while (value && i >= 0);
Tim Peters49f26812002-04-06 01:45:35 +00001777
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001778 while (i >= 0)
1779 buf[i--] = ' ';
David Malcolm49526f42012-06-22 14:55:41 -04001780 fputs(buf, out);
Tim Peters49f26812002-04-06 01:45:35 +00001781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001782 return origvalue;
Tim Peters16bcb6b2002-04-05 05:45:31 +00001783}
1784
David Malcolm49526f42012-06-22 14:55:41 -04001785void
1786_PyDebugAllocatorStats(FILE *out,
1787 const char *block_name, int num_blocks, size_t sizeof_block)
1788{
1789 char buf1[128];
1790 char buf2[128];
1791 PyOS_snprintf(buf1, sizeof(buf1),
1792 "%d %ss * %zd bytes each",
1793 num_blocks, block_name, sizeof_block);
1794 PyOS_snprintf(buf2, sizeof(buf2),
1795 "%48s ", buf1);
1796 (void)printone(out, buf2, num_blocks * sizeof_block);
1797}
1798
1799#ifdef WITH_PYMALLOC
1800
1801/* Print summary info to "out" about the state of pymalloc's structures.
Tim Peters08d82152002-04-18 22:25:03 +00001802 * In Py_DEBUG mode, also perform some expensive internal consistency
1803 * checks.
1804 */
Tim Peters7ccfadf2002-04-01 06:04:21 +00001805void
David Malcolm49526f42012-06-22 14:55:41 -04001806_PyObject_DebugMallocStats(FILE *out)
Tim Peters7ccfadf2002-04-01 06:04:21 +00001807{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001808 uint i;
1809 const uint numclasses = SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT;
1810 /* # of pools, allocated blocks, and free blocks per class index */
1811 size_t numpools[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT];
1812 size_t numblocks[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT];
1813 size_t numfreeblocks[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT];
1814 /* total # of allocated bytes in used and full pools */
1815 size_t allocated_bytes = 0;
1816 /* total # of available bytes in used pools */
1817 size_t available_bytes = 0;
1818 /* # of free pools + pools not yet carved out of current arena */
1819 uint numfreepools = 0;
1820 /* # of bytes for arena alignment padding */
1821 size_t arena_alignment = 0;
1822 /* # of bytes in used and full pools used for pool_headers */
1823 size_t pool_header_bytes = 0;
1824 /* # of bytes in used and full pools wasted due to quantization,
1825 * i.e. the necessarily leftover space at the ends of used and
1826 * full pools.
1827 */
1828 size_t quantization = 0;
1829 /* # of arenas actually allocated. */
1830 size_t narenas = 0;
1831 /* running total -- should equal narenas * ARENA_SIZE */
1832 size_t total;
1833 char buf[128];
Tim Peters7ccfadf2002-04-01 06:04:21 +00001834
David Malcolm49526f42012-06-22 14:55:41 -04001835 fprintf(out, "Small block threshold = %d, in %u size classes.\n",
Stefan Krah735bb122010-11-26 10:54:09 +00001836 SMALL_REQUEST_THRESHOLD, numclasses);
Tim Peters7ccfadf2002-04-01 06:04:21 +00001837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001838 for (i = 0; i < numclasses; ++i)
1839 numpools[i] = numblocks[i] = numfreeblocks[i] = 0;
Tim Peters7ccfadf2002-04-01 06:04:21 +00001840
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001841 /* Because full pools aren't linked to from anything, it's easiest
1842 * to march over all the arenas. If we're lucky, most of the memory
1843 * will be living in full pools -- would be a shame to miss them.
1844 */
1845 for (i = 0; i < maxarenas; ++i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001846 uint j;
1847 uptr base = arenas[i].address;
Thomas Woutersa9773292006-04-21 09:43:23 +00001848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001849 /* Skip arenas which are not allocated. */
1850 if (arenas[i].address == (uptr)NULL)
1851 continue;
1852 narenas += 1;
Thomas Woutersa9773292006-04-21 09:43:23 +00001853
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001854 numfreepools += arenas[i].nfreepools;
Tim Peters7ccfadf2002-04-01 06:04:21 +00001855
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001856 /* round up to pool alignment */
1857 if (base & (uptr)POOL_SIZE_MASK) {
1858 arena_alignment += POOL_SIZE;
1859 base &= ~(uptr)POOL_SIZE_MASK;
1860 base += POOL_SIZE;
1861 }
Tim Peters7ccfadf2002-04-01 06:04:21 +00001862
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001863 /* visit every pool in the arena */
1864 assert(base <= (uptr) arenas[i].pool_address);
1865 for (j = 0;
1866 base < (uptr) arenas[i].pool_address;
1867 ++j, base += POOL_SIZE) {
1868 poolp p = (poolp)base;
1869 const uint sz = p->szidx;
1870 uint freeblocks;
Tim Peters08d82152002-04-18 22:25:03 +00001871
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001872 if (p->ref.count == 0) {
1873 /* currently unused */
1874 assert(pool_is_in_list(p, arenas[i].freepools));
1875 continue;
1876 }
1877 ++numpools[sz];
1878 numblocks[sz] += p->ref.count;
1879 freeblocks = NUMBLOCKS(sz) - p->ref.count;
1880 numfreeblocks[sz] += freeblocks;
Tim Peters08d82152002-04-18 22:25:03 +00001881#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001882 if (freeblocks > 0)
1883 assert(pool_is_in_list(p, usedpools[sz + sz]));
Tim Peters08d82152002-04-18 22:25:03 +00001884#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001885 }
1886 }
1887 assert(narenas == narenas_currently_allocated);
Tim Peters7ccfadf2002-04-01 06:04:21 +00001888
David Malcolm49526f42012-06-22 14:55:41 -04001889 fputc('\n', out);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001890 fputs("class size num pools blocks in use avail blocks\n"
1891 "----- ---- --------- ------------- ------------\n",
David Malcolm49526f42012-06-22 14:55:41 -04001892 out);
Tim Peters7ccfadf2002-04-01 06:04:21 +00001893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001894 for (i = 0; i < numclasses; ++i) {
1895 size_t p = numpools[i];
1896 size_t b = numblocks[i];
1897 size_t f = numfreeblocks[i];
1898 uint size = INDEX2SIZE(i);
1899 if (p == 0) {
1900 assert(b == 0 && f == 0);
1901 continue;
1902 }
David Malcolm49526f42012-06-22 14:55:41 -04001903 fprintf(out, "%5u %6u "
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001904 "%11" PY_FORMAT_SIZE_T "u "
1905 "%15" PY_FORMAT_SIZE_T "u "
1906 "%13" PY_FORMAT_SIZE_T "u\n",
Stefan Krah735bb122010-11-26 10:54:09 +00001907 i, size, p, b, f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001908 allocated_bytes += b * size;
1909 available_bytes += f * size;
1910 pool_header_bytes += p * POOL_OVERHEAD;
1911 quantization += p * ((POOL_SIZE - POOL_OVERHEAD) % size);
1912 }
David Malcolm49526f42012-06-22 14:55:41 -04001913 fputc('\n', out);
1914#ifdef PYMALLOC_DEBUG
1915 (void)printone(out, "# times object malloc called", serialno);
1916#endif
1917 (void)printone(out, "# arenas allocated total", ntimes_arena_allocated);
1918 (void)printone(out, "# arenas reclaimed", ntimes_arena_allocated - narenas);
1919 (void)printone(out, "# arenas highwater mark", narenas_highwater);
1920 (void)printone(out, "# arenas allocated current", narenas);
Thomas Woutersa9773292006-04-21 09:43:23 +00001921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001922 PyOS_snprintf(buf, sizeof(buf),
1923 "%" PY_FORMAT_SIZE_T "u arenas * %d bytes/arena",
1924 narenas, ARENA_SIZE);
David Malcolm49526f42012-06-22 14:55:41 -04001925 (void)printone(out, buf, narenas * ARENA_SIZE);
Tim Peters16bcb6b2002-04-05 05:45:31 +00001926
David Malcolm49526f42012-06-22 14:55:41 -04001927 fputc('\n', out);
Tim Peters16bcb6b2002-04-05 05:45:31 +00001928
David Malcolm49526f42012-06-22 14:55:41 -04001929 total = printone(out, "# bytes in allocated blocks", allocated_bytes);
1930 total += printone(out, "# bytes in available blocks", available_bytes);
Tim Peters49f26812002-04-06 01:45:35 +00001931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001932 PyOS_snprintf(buf, sizeof(buf),
1933 "%u unused pools * %d bytes", numfreepools, POOL_SIZE);
David Malcolm49526f42012-06-22 14:55:41 -04001934 total += printone(out, buf, (size_t)numfreepools * POOL_SIZE);
Tim Peters16bcb6b2002-04-05 05:45:31 +00001935
David Malcolm49526f42012-06-22 14:55:41 -04001936 total += printone(out, "# bytes lost to pool headers", pool_header_bytes);
1937 total += printone(out, "# bytes lost to quantization", quantization);
1938 total += printone(out, "# bytes lost to arena alignment", arena_alignment);
1939 (void)printone(out, "Total", total);
Tim Peters7ccfadf2002-04-01 06:04:21 +00001940}
1941
David Malcolm49526f42012-06-22 14:55:41 -04001942#endif /* #ifdef WITH_PYMALLOC */
Neal Norwitz7eb3c912004-06-06 19:20:22 +00001943
1944#ifdef Py_USING_MEMORY_DEBUGGER
Thomas Woutersa9773292006-04-21 09:43:23 +00001945/* Make this function last so gcc won't inline it since the definition is
1946 * after the reference.
1947 */
Neal Norwitz7eb3c912004-06-06 19:20:22 +00001948int
1949Py_ADDRESS_IN_RANGE(void *P, poolp pool)
1950{
Antoine Pitroub7fb2e22011-01-07 21:43:59 +00001951 uint arenaindex_temp = pool->arenaindex;
1952
1953 return arenaindex_temp < maxarenas &&
1954 (uptr)P - arenas[arenaindex_temp].address < (uptr)ARENA_SIZE &&
1955 arenas[arenaindex_temp].address != 0;
Neal Norwitz7eb3c912004-06-06 19:20:22 +00001956}
1957#endif