blob: af12f41ed3276132b3aadffb7daf2bf3efcd4d8d [file] [log] [blame]
Tim Peters1221c0a2002-03-23 00:20:15 +00001#include "Python.h"
2
3#ifdef WITH_PYMALLOC
4
Neil Schemenauera35c6882001-02-27 04:45:05 +00005/* An object allocator for Python.
6
7 Here is an introduction to the layers of the Python memory architecture,
8 showing where the object allocator is actually used (layer +2), It is
9 called for every object allocation and deallocation (PyObject_New/Del),
10 unless the object-specific allocators implement a proprietary allocation
11 scheme (ex.: ints use a simple free list). This is also the place where
12 the cyclic garbage collector operates selectively on container objects.
13
14
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +000015 Object-specific allocators
Neil Schemenauera35c6882001-02-27 04:45:05 +000016 _____ ______ ______ ________
17 [ int ] [ dict ] [ list ] ... [ string ] Python core |
18+3 | <----- Object-specific memory -----> | <-- Non-object memory --> |
19 _______________________________ | |
20 [ Python's object allocator ] | |
21+2 | ####### Object memory ####### | <------ Internal buffers ------> |
22 ______________________________________________________________ |
23 [ Python's raw memory allocator (PyMem_ API) ] |
24+1 | <----- Python memory (under PyMem manager's control) ------> | |
25 __________________________________________________________________
26 [ Underlying general-purpose allocator (ex: C library malloc) ]
27 0 | <------ Virtual memory allocated for the python process -------> |
28
29 =========================================================================
30 _______________________________________________________________________
31 [ OS-specific Virtual Memory Manager (VMM) ]
32-1 | <--- Kernel dynamic storage allocation & management (page-based) ---> |
33 __________________________________ __________________________________
34 [ ] [ ]
35-2 | <-- Physical memory: ROM/RAM --> | | <-- Secondary storage (swap) --> |
36
37*/
38/*==========================================================================*/
39
40/* A fast, special-purpose memory allocator for small blocks, to be used
41 on top of a general-purpose malloc -- heavily based on previous art. */
42
43/* Vladimir Marangozov -- August 2000 */
44
45/*
46 * "Memory management is where the rubber meets the road -- if we do the wrong
47 * thing at any level, the results will not be good. And if we don't make the
48 * levels work well together, we are in serious trouble." (1)
49 *
50 * (1) Paul R. Wilson, Mark S. Johnstone, Michael Neely, and David Boles,
51 * "Dynamic Storage Allocation: A Survey and Critical Review",
52 * in Proc. 1995 Int'l. Workshop on Memory Management, September 1995.
53 */
54
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +000055/* #undef WITH_MEMORY_LIMITS */ /* disable mem limit checks */
Neil Schemenauera35c6882001-02-27 04:45:05 +000056
57/*==========================================================================*/
58
59/*
Neil Schemenauera35c6882001-02-27 04:45:05 +000060 * Allocation strategy abstract:
61 *
62 * For small requests, the allocator sub-allocates <Big> blocks of memory.
63 * Requests greater than 256 bytes are routed to the system's allocator.
Tim Petersce7fb9b2002-03-23 00:28:57 +000064 *
Neil Schemenauera35c6882001-02-27 04:45:05 +000065 * Small requests are grouped in size classes spaced 8 bytes apart, due
66 * to the required valid alignment of the returned address. Requests of
67 * a particular size are serviced from memory pools of 4K (one VMM page).
68 * Pools are fragmented on demand and contain free lists of blocks of one
69 * particular size class. In other words, there is a fixed-size allocator
70 * for each size class. Free pools are shared by the different allocators
71 * thus minimizing the space reserved for a particular size class.
72 *
73 * This allocation strategy is a variant of what is known as "simple
74 * segregated storage based on array of free lists". The main drawback of
75 * simple segregated storage is that we might end up with lot of reserved
76 * memory for the different free lists, which degenerate in time. To avoid
77 * this, we partition each free list in pools and we share dynamically the
78 * reserved space between all free lists. This technique is quite efficient
79 * for memory intensive programs which allocate mainly small-sized blocks.
80 *
81 * For small requests we have the following table:
82 *
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +000083 * Request in bytes Size of allocated block Size class idx
Neil Schemenauera35c6882001-02-27 04:45:05 +000084 * ----------------------------------------------------------------
85 * 1-8 8 0
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +000086 * 9-16 16 1
87 * 17-24 24 2
88 * 25-32 32 3
89 * 33-40 40 4
90 * 41-48 48 5
91 * 49-56 56 6
92 * 57-64 64 7
93 * 65-72 72 8
94 * ... ... ...
95 * 241-248 248 30
96 * 249-256 256 31
Tim Petersce7fb9b2002-03-23 00:28:57 +000097 *
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +000098 * 0, 257 and up: routed to the underlying allocator.
Neil Schemenauera35c6882001-02-27 04:45:05 +000099 */
100
101/*==========================================================================*/
102
103/*
104 * -- Main tunable settings section --
105 */
106
107/*
108 * Alignment of addresses returned to the user. 8-bytes alignment works
109 * on most current architectures (with 32-bit or 64-bit address busses).
110 * The alignment value is also used for grouping small requests in size
111 * classes spaced ALIGNMENT bytes apart.
112 *
113 * You shouldn't change this unless you know what you are doing.
114 */
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000115#define ALIGNMENT 8 /* must be 2^N */
116#define ALIGNMENT_SHIFT 3
117#define ALIGNMENT_MASK (ALIGNMENT - 1)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000118
Tim Peterse70ddf32002-04-05 04:32:29 +0000119/* Return the number of bytes in size class I, as a uint. */
120#define INDEX2SIZE(I) (((uint)(I) + 1) << ALIGNMENT_SHIFT)
121
Neil Schemenauera35c6882001-02-27 04:45:05 +0000122/*
123 * Max size threshold below which malloc requests are considered to be
124 * small enough in order to use preallocated memory pools. You can tune
125 * this value according to your application behaviour and memory needs.
126 *
127 * The following invariants must hold:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000128 * 1) ALIGNMENT <= SMALL_REQUEST_THRESHOLD <= 256
129 * 2) SMALL_REQUEST_THRESHOLD is evenly divisible by ALIGNMENT
Neil Schemenauera35c6882001-02-27 04:45:05 +0000130 *
131 * Although not required, for better performance and space efficiency,
132 * it is recommended that SMALL_REQUEST_THRESHOLD is set to a power of 2.
133 */
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000134#define SMALL_REQUEST_THRESHOLD 256
135#define NB_SMALL_SIZE_CLASSES (SMALL_REQUEST_THRESHOLD / ALIGNMENT)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000136
137/*
138 * The system's VMM page size can be obtained on most unices with a
139 * getpagesize() call or deduced from various header files. To make
140 * things simpler, we assume that it is 4K, which is OK for most systems.
141 * It is probably better if this is the native page size, but it doesn't
Tim Petersecc6e6a2005-07-10 22:30:55 +0000142 * have to be. In theory, if SYSTEM_PAGE_SIZE is larger than the native page
143 * size, then `POOL_ADDR(p)->arenaindex' could rarely cause a segmentation
144 * violation fault. 4K is apparently OK for all the platforms that python
Martin v. Löwis8c140282002-10-26 15:01:53 +0000145 * currently targets.
Neil Schemenauera35c6882001-02-27 04:45:05 +0000146 */
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000147#define SYSTEM_PAGE_SIZE (4 * 1024)
148#define SYSTEM_PAGE_SIZE_MASK (SYSTEM_PAGE_SIZE - 1)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000149
150/*
151 * Maximum amount of memory managed by the allocator for small requests.
152 */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000153#ifdef WITH_MEMORY_LIMITS
154#ifndef SMALL_MEMORY_LIMIT
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000155#define SMALL_MEMORY_LIMIT (64 * 1024 * 1024) /* 64 MB -- more? */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000156#endif
157#endif
158
159/*
160 * The allocator sub-allocates <Big> blocks of memory (called arenas) aligned
161 * on a page boundary. This is a reserved virtual address space for the
162 * current process (obtained through a malloc call). In no way this means
163 * that the memory arenas will be used entirely. A malloc(<Big>) is usually
164 * an address range reservation for <Big> bytes, unless all pages within this
165 * space are referenced subsequently. So malloc'ing big blocks and not using
166 * them does not mean "wasting memory". It's an addressable range wastage...
167 *
168 * Therefore, allocating arenas with malloc is not optimal, because there is
169 * some address space wastage, but this is the most portable way to request
Tim Petersd97a1c02002-03-30 06:09:22 +0000170 * memory from the system across various platforms.
Neil Schemenauera35c6882001-02-27 04:45:05 +0000171 */
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000172#define ARENA_SIZE (256 << 10) /* 256KB */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000173
174#ifdef WITH_MEMORY_LIMITS
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000175#define MAX_ARENAS (SMALL_MEMORY_LIMIT / ARENA_SIZE)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000176#endif
177
178/*
179 * Size of the pools used for small blocks. Should be a power of 2,
Tim Petersc2ce91a2002-03-30 21:36:04 +0000180 * between 1K and SYSTEM_PAGE_SIZE, that is: 1k, 2k, 4k.
Neil Schemenauera35c6882001-02-27 04:45:05 +0000181 */
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000182#define POOL_SIZE SYSTEM_PAGE_SIZE /* must be 2^N */
183#define POOL_SIZE_MASK SYSTEM_PAGE_SIZE_MASK
Neil Schemenauera35c6882001-02-27 04:45:05 +0000184
185/*
186 * -- End of tunable settings section --
187 */
188
189/*==========================================================================*/
190
191/*
192 * Locking
193 *
194 * To reduce lock contention, it would probably be better to refine the
195 * crude function locking with per size class locking. I'm not positive
196 * however, whether it's worth switching to such locking policy because
197 * of the performance penalty it might introduce.
198 *
199 * The following macros describe the simplest (should also be the fastest)
200 * lock object on a particular platform and the init/fini/lock/unlock
201 * operations on it. The locks defined here are not expected to be recursive
202 * because it is assumed that they will always be called in the order:
203 * INIT, [LOCK, UNLOCK]*, FINI.
204 */
205
206/*
207 * Python's threads are serialized, so object malloc locking is disabled.
208 */
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000209#define SIMPLELOCK_DECL(lock) /* simple lock declaration */
210#define SIMPLELOCK_INIT(lock) /* allocate (if needed) and initialize */
211#define SIMPLELOCK_FINI(lock) /* free/destroy an existing lock */
212#define SIMPLELOCK_LOCK(lock) /* acquire released lock */
213#define SIMPLELOCK_UNLOCK(lock) /* release acquired lock */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000214
215/*
216 * Basic types
217 * I don't care if these are defined in <sys/types.h> or elsewhere. Axiom.
218 */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000219#undef uchar
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000220#define uchar unsigned char /* assuming == 8 bits */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000221
Neil Schemenauera35c6882001-02-27 04:45:05 +0000222#undef uint
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000223#define uint unsigned int /* assuming >= 16 bits */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000224
225#undef ulong
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000226#define ulong unsigned long /* assuming >= 32 bits */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000227
Tim Petersd97a1c02002-03-30 06:09:22 +0000228#undef uptr
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000229#define uptr Py_uintptr_t
Tim Petersd97a1c02002-03-30 06:09:22 +0000230
Neil Schemenauera35c6882001-02-27 04:45:05 +0000231/* When you say memory, my mind reasons in terms of (pointers to) blocks */
232typedef uchar block;
233
Tim Peterse70ddf32002-04-05 04:32:29 +0000234/* Pool for small blocks. */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000235struct pool_header {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000236 union { block *_padding;
Stefan Krah5d744a82010-11-26 11:07:04 +0000237 uint count; } ref; /* number of allocated blocks */
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000238 block *freeblock; /* pool's free list head */
239 struct pool_header *nextpool; /* next pool of this size class */
240 struct pool_header *prevpool; /* previous pool "" */
241 uint arenaindex; /* index into arenas of base adr */
242 uint szidx; /* block size class index */
243 uint nextoffset; /* bytes to virgin block */
244 uint maxnextoffset; /* largest valid nextoffset */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000245};
246
247typedef struct pool_header *poolp;
248
Thomas Woutersa9773292006-04-21 09:43:23 +0000249/* Record keeping for arenas. */
250struct arena_object {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000251 /* The address of the arena, as returned by malloc. Note that 0
252 * will never be returned by a successful malloc, and is used
253 * here to mark an arena_object that doesn't correspond to an
254 * allocated arena.
255 */
256 uptr address;
Thomas Woutersa9773292006-04-21 09:43:23 +0000257
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000258 /* Pool-aligned pointer to the next pool to be carved off. */
259 block* pool_address;
Thomas Woutersa9773292006-04-21 09:43:23 +0000260
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000261 /* The number of available pools in the arena: free pools + never-
262 * allocated pools.
263 */
264 uint nfreepools;
Thomas Woutersa9773292006-04-21 09:43:23 +0000265
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000266 /* The total number of pools in the arena, whether or not available. */
267 uint ntotalpools;
Thomas Woutersa9773292006-04-21 09:43:23 +0000268
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000269 /* Singly-linked list of available pools. */
270 struct pool_header* freepools;
Thomas Woutersa9773292006-04-21 09:43:23 +0000271
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000272 /* Whenever this arena_object is not associated with an allocated
273 * arena, the nextarena member is used to link all unassociated
274 * arena_objects in the singly-linked `unused_arena_objects` list.
275 * The prevarena member is unused in this case.
276 *
277 * When this arena_object is associated with an allocated arena
278 * with at least one available pool, both members are used in the
279 * doubly-linked `usable_arenas` list, which is maintained in
280 * increasing order of `nfreepools` values.
281 *
282 * Else this arena_object is associated with an allocated arena
283 * all of whose pools are in use. `nextarena` and `prevarena`
284 * are both meaningless in this case.
285 */
286 struct arena_object* nextarena;
287 struct arena_object* prevarena;
Thomas Woutersa9773292006-04-21 09:43:23 +0000288};
289
Neil Schemenauera35c6882001-02-27 04:45:05 +0000290#undef ROUNDUP
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000291#define ROUNDUP(x) (((x) + ALIGNMENT_MASK) & ~ALIGNMENT_MASK)
292#define POOL_OVERHEAD ROUNDUP(sizeof(struct pool_header))
Neil Schemenauera35c6882001-02-27 04:45:05 +0000293
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000294#define DUMMY_SIZE_IDX 0xffff /* size class of newly cached pools */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000295
Tim Petersd97a1c02002-03-30 06:09:22 +0000296/* Round pointer P down to the closest pool-aligned address <= P, as a poolp */
Tim Peterse70ddf32002-04-05 04:32:29 +0000297#define POOL_ADDR(P) ((poolp)((uptr)(P) & ~(uptr)POOL_SIZE_MASK))
298
Tim Peters16bcb6b2002-04-05 05:45:31 +0000299/* Return total number of blocks in pool of size index I, as a uint. */
300#define NUMBLOCKS(I) ((uint)(POOL_SIZE - POOL_OVERHEAD) / INDEX2SIZE(I))
Tim Petersd97a1c02002-03-30 06:09:22 +0000301
Neil Schemenauera35c6882001-02-27 04:45:05 +0000302/*==========================================================================*/
303
304/*
305 * This malloc lock
306 */
Jeremy Hyltond1fedb62002-07-18 18:49:52 +0000307SIMPLELOCK_DECL(_malloc_lock)
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000308#define LOCK() SIMPLELOCK_LOCK(_malloc_lock)
309#define UNLOCK() SIMPLELOCK_UNLOCK(_malloc_lock)
310#define LOCK_INIT() SIMPLELOCK_INIT(_malloc_lock)
311#define LOCK_FINI() SIMPLELOCK_FINI(_malloc_lock)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000312
313/*
Tim Peters1e16db62002-03-31 01:05:22 +0000314 * Pool table -- headed, circular, doubly-linked lists of partially used pools.
315
316This is involved. For an index i, usedpools[i+i] is the header for a list of
317all partially used pools holding small blocks with "size class idx" i. So
318usedpools[0] corresponds to blocks of size 8, usedpools[2] to blocks of size
31916, and so on: index 2*i <-> blocks of size (i+1)<<ALIGNMENT_SHIFT.
320
Thomas Woutersa9773292006-04-21 09:43:23 +0000321Pools are carved off an arena's highwater mark (an arena_object's pool_address
322member) as needed. Once carved off, a pool is in one of three states forever
323after:
Tim Peters1e16db62002-03-31 01:05:22 +0000324
Tim Peters338e0102002-04-01 19:23:44 +0000325used == partially used, neither empty nor full
326 At least one block in the pool is currently allocated, and at least one
327 block in the pool is not currently allocated (note this implies a pool
328 has room for at least two blocks).
329 This is a pool's initial state, as a pool is created only when malloc
330 needs space.
331 The pool holds blocks of a fixed size, and is in the circular list headed
332 at usedpools[i] (see above). It's linked to the other used pools of the
333 same size class via the pool_header's nextpool and prevpool members.
334 If all but one block is currently allocated, a malloc can cause a
335 transition to the full state. If all but one block is not currently
336 allocated, a free can cause a transition to the empty state.
Tim Peters1e16db62002-03-31 01:05:22 +0000337
Tim Peters338e0102002-04-01 19:23:44 +0000338full == all the pool's blocks are currently allocated
339 On transition to full, a pool is unlinked from its usedpools[] list.
340 It's not linked to from anything then anymore, and its nextpool and
341 prevpool members are meaningless until it transitions back to used.
342 A free of a block in a full pool puts the pool back in the used state.
343 Then it's linked in at the front of the appropriate usedpools[] list, so
344 that the next allocation for its size class will reuse the freed block.
345
346empty == all the pool's blocks are currently available for allocation
347 On transition to empty, a pool is unlinked from its usedpools[] list,
Thomas Woutersa9773292006-04-21 09:43:23 +0000348 and linked to the front of its arena_object's singly-linked freepools list,
Tim Peters338e0102002-04-01 19:23:44 +0000349 via its nextpool member. The prevpool member has no meaning in this case.
350 Empty pools have no inherent size class: the next time a malloc finds
351 an empty list in usedpools[], it takes the first pool off of freepools.
352 If the size class needed happens to be the same as the size class the pool
Tim Peterse70ddf32002-04-05 04:32:29 +0000353 last had, some pool initialization can be skipped.
Tim Peters338e0102002-04-01 19:23:44 +0000354
355
356Block Management
357
358Blocks within pools are again carved out as needed. pool->freeblock points to
359the start of a singly-linked list of free blocks within the pool. When a
360block is freed, it's inserted at the front of its pool's freeblock list. Note
361that the available blocks in a pool are *not* linked all together when a pool
Tim Peterse70ddf32002-04-05 04:32:29 +0000362is initialized. Instead only "the first two" (lowest addresses) blocks are
363set up, returning the first such block, and setting pool->freeblock to a
364one-block list holding the second such block. This is consistent with that
365pymalloc strives at all levels (arena, pool, and block) never to touch a piece
366of memory until it's actually needed.
367
368So long as a pool is in the used state, we're certain there *is* a block
Tim Peters52aefc82002-04-11 06:36:45 +0000369available for allocating, and pool->freeblock is not NULL. If pool->freeblock
370points to the end of the free list before we've carved the entire pool into
371blocks, that means we simply haven't yet gotten to one of the higher-address
372blocks. The offset from the pool_header to the start of "the next" virgin
373block is stored in the pool_header nextoffset member, and the largest value
374of nextoffset that makes sense is stored in the maxnextoffset member when a
375pool is initialized. All the blocks in a pool have been passed out at least
376once when and only when nextoffset > maxnextoffset.
Tim Peters338e0102002-04-01 19:23:44 +0000377
Tim Peters1e16db62002-03-31 01:05:22 +0000378
379Major obscurity: While the usedpools vector is declared to have poolp
380entries, it doesn't really. It really contains two pointers per (conceptual)
381poolp entry, the nextpool and prevpool members of a pool_header. The
382excruciating initialization code below fools C so that
383
384 usedpool[i+i]
385
386"acts like" a genuine poolp, but only so long as you only reference its
387nextpool and prevpool members. The "- 2*sizeof(block *)" gibberish is
388compensating for that a pool_header's nextpool and prevpool members
389immediately follow a pool_header's first two members:
390
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000391 union { block *_padding;
Stefan Krah5d744a82010-11-26 11:07:04 +0000392 uint count; } ref;
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000393 block *freeblock;
Tim Peters1e16db62002-03-31 01:05:22 +0000394
395each of which consume sizeof(block *) bytes. So what usedpools[i+i] really
396contains is a fudged-up pointer p such that *if* C believes it's a poolp
397pointer, then p->nextpool and p->prevpool are both p (meaning that the headed
398circular list is empty).
399
400It's unclear why the usedpools setup is so convoluted. It could be to
401minimize the amount of cache required to hold this heavily-referenced table
402(which only *needs* the two interpool pointer members of a pool_header). OTOH,
403referencing code has to remember to "double the index" and doing so isn't
404free, usedpools[0] isn't a strictly legal pointer, and we're crucially relying
405on that C doesn't insert any padding anywhere in a pool_header at or before
406the prevpool member.
407**************************************************************************** */
408
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000409#define PTA(x) ((poolp )((uchar *)&(usedpools[2*(x)]) - 2*sizeof(block *)))
410#define PT(x) PTA(x), PTA(x)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000411
412static poolp usedpools[2 * ((NB_SMALL_SIZE_CLASSES + 7) / 8) * 8] = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000413 PT(0), PT(1), PT(2), PT(3), PT(4), PT(5), PT(6), PT(7)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000414#if NB_SMALL_SIZE_CLASSES > 8
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000415 , PT(8), PT(9), PT(10), PT(11), PT(12), PT(13), PT(14), PT(15)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000416#if NB_SMALL_SIZE_CLASSES > 16
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000417 , PT(16), PT(17), PT(18), PT(19), PT(20), PT(21), PT(22), PT(23)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000418#if NB_SMALL_SIZE_CLASSES > 24
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000419 , PT(24), PT(25), PT(26), PT(27), PT(28), PT(29), PT(30), PT(31)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000420#if NB_SMALL_SIZE_CLASSES > 32
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000421 , PT(32), PT(33), PT(34), PT(35), PT(36), PT(37), PT(38), PT(39)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000422#if NB_SMALL_SIZE_CLASSES > 40
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000423 , PT(40), PT(41), PT(42), PT(43), PT(44), PT(45), PT(46), PT(47)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000424#if NB_SMALL_SIZE_CLASSES > 48
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000425 , PT(48), PT(49), PT(50), PT(51), PT(52), PT(53), PT(54), PT(55)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000426#if NB_SMALL_SIZE_CLASSES > 56
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000427 , PT(56), PT(57), PT(58), PT(59), PT(60), PT(61), PT(62), PT(63)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000428#endif /* NB_SMALL_SIZE_CLASSES > 56 */
429#endif /* NB_SMALL_SIZE_CLASSES > 48 */
430#endif /* NB_SMALL_SIZE_CLASSES > 40 */
431#endif /* NB_SMALL_SIZE_CLASSES > 32 */
432#endif /* NB_SMALL_SIZE_CLASSES > 24 */
433#endif /* NB_SMALL_SIZE_CLASSES > 16 */
434#endif /* NB_SMALL_SIZE_CLASSES > 8 */
435};
436
Thomas Woutersa9773292006-04-21 09:43:23 +0000437/*==========================================================================
438Arena management.
Neil Schemenauera35c6882001-02-27 04:45:05 +0000439
Thomas Woutersa9773292006-04-21 09:43:23 +0000440`arenas` is a vector of arena_objects. It contains maxarenas entries, some of
441which may not be currently used (== they're arena_objects that aren't
442currently associated with an allocated arena). Note that arenas proper are
443separately malloc'ed.
Neil Schemenauera35c6882001-02-27 04:45:05 +0000444
Thomas Woutersa9773292006-04-21 09:43:23 +0000445Prior to Python 2.5, arenas were never free()'ed. Starting with Python 2.5,
446we do try to free() arenas, and use some mild heuristic strategies to increase
447the likelihood that arenas eventually can be freed.
448
449unused_arena_objects
450
451 This is a singly-linked list of the arena_objects that are currently not
452 being used (no arena is associated with them). Objects are taken off the
453 head of the list in new_arena(), and are pushed on the head of the list in
454 PyObject_Free() when the arena is empty. Key invariant: an arena_object
455 is on this list if and only if its .address member is 0.
456
457usable_arenas
458
459 This is a doubly-linked list of the arena_objects associated with arenas
460 that have pools available. These pools are either waiting to be reused,
461 or have not been used before. The list is sorted to have the most-
462 allocated arenas first (ascending order based on the nfreepools member).
463 This means that the next allocation will come from a heavily used arena,
464 which gives the nearly empty arenas a chance to be returned to the system.
465 In my unscientific tests this dramatically improved the number of arenas
466 that could be freed.
467
468Note that an arena_object associated with an arena all of whose pools are
469currently in use isn't on either list.
470*/
471
472/* Array of objects used to track chunks of memory (arenas). */
473static struct arena_object* arenas = NULL;
474/* Number of slots currently allocated in the `arenas` vector. */
Tim Peters1d99af82002-03-30 10:35:09 +0000475static uint maxarenas = 0;
Tim Petersd97a1c02002-03-30 06:09:22 +0000476
Thomas Woutersa9773292006-04-21 09:43:23 +0000477/* The head of the singly-linked, NULL-terminated list of available
478 * arena_objects.
Tim Petersd97a1c02002-03-30 06:09:22 +0000479 */
Thomas Woutersa9773292006-04-21 09:43:23 +0000480static struct arena_object* unused_arena_objects = NULL;
481
482/* The head of the doubly-linked, NULL-terminated at each end, list of
483 * arena_objects associated with arenas that have pools available.
484 */
485static struct arena_object* usable_arenas = NULL;
486
487/* How many arena_objects do we initially allocate?
488 * 16 = can allocate 16 arenas = 16 * ARENA_SIZE = 4MB before growing the
489 * `arenas` vector.
490 */
491#define INITIAL_ARENA_OBJECTS 16
492
493/* Number of arenas allocated that haven't been free()'d. */
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000494static size_t narenas_currently_allocated = 0;
Thomas Woutersa9773292006-04-21 09:43:23 +0000495
496#ifdef PYMALLOC_DEBUG
497/* Total number of times malloc() called to allocate an arena. */
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000498static size_t ntimes_arena_allocated = 0;
Thomas Woutersa9773292006-04-21 09:43:23 +0000499/* High water mark (max value ever seen) for narenas_currently_allocated. */
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000500static size_t narenas_highwater = 0;
Thomas Woutersa9773292006-04-21 09:43:23 +0000501#endif
502
503/* Allocate a new arena. If we run out of memory, return NULL. Else
504 * allocate a new arena, and return the address of an arena_object
505 * describing the new arena. It's expected that the caller will set
506 * `usable_arenas` to the return value.
507 */
508static struct arena_object*
Tim Petersd97a1c02002-03-30 06:09:22 +0000509new_arena(void)
510{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000511 struct arena_object* arenaobj;
512 uint excess; /* number of bytes above pool alignment */
Tim Petersd97a1c02002-03-30 06:09:22 +0000513
Tim Peters0e871182002-04-13 08:29:14 +0000514#ifdef PYMALLOC_DEBUG
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000515 if (Py_GETENV("PYTHONMALLOCSTATS"))
516 _PyObject_DebugMallocStats();
Tim Peters0e871182002-04-13 08:29:14 +0000517#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000518 if (unused_arena_objects == NULL) {
519 uint i;
520 uint numarenas;
521 size_t nbytes;
Tim Peters0e871182002-04-13 08:29:14 +0000522
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000523 /* Double the number of arena objects on each allocation.
524 * Note that it's possible for `numarenas` to overflow.
525 */
526 numarenas = maxarenas ? maxarenas << 1 : INITIAL_ARENA_OBJECTS;
527 if (numarenas <= maxarenas)
528 return NULL; /* overflow */
Martin v. Löwis5aca8822008-09-11 06:55:48 +0000529#if SIZEOF_SIZE_T <= SIZEOF_INT
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000530 if (numarenas > PY_SIZE_MAX / sizeof(*arenas))
531 return NULL; /* overflow */
Martin v. Löwis5aca8822008-09-11 06:55:48 +0000532#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000533 nbytes = numarenas * sizeof(*arenas);
534 arenaobj = (struct arena_object *)realloc(arenas, nbytes);
535 if (arenaobj == NULL)
536 return NULL;
537 arenas = arenaobj;
Thomas Woutersa9773292006-04-21 09:43:23 +0000538
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000539 /* We might need to fix pointers that were copied. However,
540 * new_arena only gets called when all the pages in the
541 * previous arenas are full. Thus, there are *no* pointers
542 * into the old array. Thus, we don't have to worry about
543 * invalid pointers. Just to be sure, some asserts:
544 */
545 assert(usable_arenas == NULL);
546 assert(unused_arena_objects == NULL);
Thomas Woutersa9773292006-04-21 09:43:23 +0000547
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000548 /* Put the new arenas on the unused_arena_objects list. */
549 for (i = maxarenas; i < numarenas; ++i) {
550 arenas[i].address = 0; /* mark as unassociated */
551 arenas[i].nextarena = i < numarenas - 1 ?
552 &arenas[i+1] : NULL;
553 }
Thomas Woutersa9773292006-04-21 09:43:23 +0000554
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000555 /* Update globals. */
556 unused_arena_objects = &arenas[maxarenas];
557 maxarenas = numarenas;
558 }
Tim Petersd97a1c02002-03-30 06:09:22 +0000559
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000560 /* Take the next available arena object off the head of the list. */
561 assert(unused_arena_objects != NULL);
562 arenaobj = unused_arena_objects;
563 unused_arena_objects = arenaobj->nextarena;
564 assert(arenaobj->address == 0);
565 arenaobj->address = (uptr)malloc(ARENA_SIZE);
566 if (arenaobj->address == 0) {
567 /* The allocation failed: return NULL after putting the
568 * arenaobj back.
569 */
570 arenaobj->nextarena = unused_arena_objects;
571 unused_arena_objects = arenaobj;
572 return NULL;
573 }
Tim Petersd97a1c02002-03-30 06:09:22 +0000574
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000575 ++narenas_currently_allocated;
Thomas Woutersa9773292006-04-21 09:43:23 +0000576#ifdef PYMALLOC_DEBUG
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000577 ++ntimes_arena_allocated;
578 if (narenas_currently_allocated > narenas_highwater)
579 narenas_highwater = narenas_currently_allocated;
Thomas Woutersa9773292006-04-21 09:43:23 +0000580#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000581 arenaobj->freepools = NULL;
582 /* pool_address <- first pool-aligned address in the arena
583 nfreepools <- number of whole pools that fit after alignment */
584 arenaobj->pool_address = (block*)arenaobj->address;
585 arenaobj->nfreepools = ARENA_SIZE / POOL_SIZE;
586 assert(POOL_SIZE * arenaobj->nfreepools == ARENA_SIZE);
587 excess = (uint)(arenaobj->address & POOL_SIZE_MASK);
588 if (excess != 0) {
589 --arenaobj->nfreepools;
590 arenaobj->pool_address += POOL_SIZE - excess;
591 }
592 arenaobj->ntotalpools = arenaobj->nfreepools;
Thomas Woutersa9773292006-04-21 09:43:23 +0000593
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000594 return arenaobj;
Tim Petersd97a1c02002-03-30 06:09:22 +0000595}
596
Thomas Woutersa9773292006-04-21 09:43:23 +0000597/*
598Py_ADDRESS_IN_RANGE(P, POOL)
599
600Return true if and only if P is an address that was allocated by pymalloc.
601POOL must be the pool address associated with P, i.e., POOL = POOL_ADDR(P)
602(the caller is asked to compute this because the macro expands POOL more than
603once, and for efficiency it's best for the caller to assign POOL_ADDR(P) to a
604variable and pass the latter to the macro; because Py_ADDRESS_IN_RANGE is
605called on every alloc/realloc/free, micro-efficiency is important here).
606
607Tricky: Let B be the arena base address associated with the pool, B =
608arenas[(POOL)->arenaindex].address. Then P belongs to the arena if and only if
609
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000610 B <= P < B + ARENA_SIZE
Thomas Woutersa9773292006-04-21 09:43:23 +0000611
612Subtracting B throughout, this is true iff
613
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000614 0 <= P-B < ARENA_SIZE
Thomas Woutersa9773292006-04-21 09:43:23 +0000615
616By using unsigned arithmetic, the "0 <=" half of the test can be skipped.
617
618Obscure: A PyMem "free memory" function can call the pymalloc free or realloc
619before the first arena has been allocated. `arenas` is still NULL in that
620case. We're relying on that maxarenas is also 0 in that case, so that
621(POOL)->arenaindex < maxarenas must be false, saving us from trying to index
622into a NULL arenas.
623
624Details: given P and POOL, the arena_object corresponding to P is AO =
625arenas[(POOL)->arenaindex]. Suppose obmalloc controls P. Then (barring wild
626stores, etc), POOL is the correct address of P's pool, AO.address is the
627correct base address of the pool's arena, and P must be within ARENA_SIZE of
628AO.address. In addition, AO.address is not 0 (no arena can start at address 0
629(NULL)). Therefore Py_ADDRESS_IN_RANGE correctly reports that obmalloc
630controls P.
631
632Now suppose obmalloc does not control P (e.g., P was obtained via a direct
633call to the system malloc() or realloc()). (POOL)->arenaindex may be anything
634in this case -- it may even be uninitialized trash. If the trash arenaindex
635is >= maxarenas, the macro correctly concludes at once that obmalloc doesn't
636control P.
637
638Else arenaindex is < maxarena, and AO is read up. If AO corresponds to an
639allocated arena, obmalloc controls all the memory in slice AO.address :
640AO.address+ARENA_SIZE. By case assumption, P is not controlled by obmalloc,
641so P doesn't lie in that slice, so the macro correctly reports that P is not
642controlled by obmalloc.
643
644Finally, if P is not controlled by obmalloc and AO corresponds to an unused
645arena_object (one not currently associated with an allocated arena),
646AO.address is 0, and the second test in the macro reduces to:
647
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000648 P < ARENA_SIZE
Thomas Woutersa9773292006-04-21 09:43:23 +0000649
650If P >= ARENA_SIZE (extremely likely), the macro again correctly concludes
651that P is not controlled by obmalloc. However, if P < ARENA_SIZE, this part
652of the test still passes, and the third clause (AO.address != 0) is necessary
653to get the correct result: AO.address is 0 in this case, so the macro
654correctly reports that P is not controlled by obmalloc (despite that P lies in
655slice AO.address : AO.address + ARENA_SIZE).
656
657Note: The third (AO.address != 0) clause was added in Python 2.5. Before
6582.5, arenas were never free()'ed, and an arenaindex < maxarena always
659corresponded to a currently-allocated arena, so the "P is not controlled by
660obmalloc, AO corresponds to an unused arena_object, and P < ARENA_SIZE" case
661was impossible.
662
663Note that the logic is excruciating, and reading up possibly uninitialized
664memory when P is not controlled by obmalloc (to get at (POOL)->arenaindex)
665creates problems for some memory debuggers. The overwhelming advantage is
666that this test determines whether an arbitrary address is controlled by
667obmalloc in a small constant time, independent of the number of arenas
668obmalloc controls. Since this test is needed at every entry point, it's
669extremely desirable that it be this fast.
Antoine Pitrou5b6fc632011-01-07 21:49:25 +0000670
671Since Py_ADDRESS_IN_RANGE may be reading from memory which was not allocated
672by Python, it is important that (POOL)->arenaindex is read only once, as
673another thread may be concurrently modifying the value without holding the
674GIL. To accomplish this, the arenaindex_temp variable is used to store
675(POOL)->arenaindex for the duration of the Py_ADDRESS_IN_RANGE macro's
676execution. The caller of the macro is responsible for declaring this
677variable.
Thomas Woutersa9773292006-04-21 09:43:23 +0000678*/
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000679#define Py_ADDRESS_IN_RANGE(P, POOL) \
Antoine Pitrou5b6fc632011-01-07 21:49:25 +0000680 ((arenaindex_temp = (POOL)->arenaindex) < maxarenas && \
681 (uptr)(P) - arenas[arenaindex_temp].address < (uptr)ARENA_SIZE && \
682 arenas[arenaindex_temp].address != 0)
Thomas Woutersa9773292006-04-21 09:43:23 +0000683
Neal Norwitz7eb3c912004-06-06 19:20:22 +0000684
685/* This is only useful when running memory debuggers such as
686 * Purify or Valgrind. Uncomment to use.
687 *
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000688#define Py_USING_MEMORY_DEBUGGER
Martin v. Löwis6fea2332008-09-25 04:15:27 +0000689 */
Neal Norwitz7eb3c912004-06-06 19:20:22 +0000690
691#ifdef Py_USING_MEMORY_DEBUGGER
692
693/* Py_ADDRESS_IN_RANGE may access uninitialized memory by design
694 * This leads to thousands of spurious warnings when using
695 * Purify or Valgrind. By making a function, we can easily
696 * suppress the uninitialized memory reads in this one function.
697 * So we won't ignore real errors elsewhere.
698 *
699 * Disable the macro and use a function.
700 */
701
702#undef Py_ADDRESS_IN_RANGE
703
Thomas Wouters89f507f2006-12-13 04:49:30 +0000704#if defined(__GNUC__) && ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 1) || \
Stefan Krah5d744a82010-11-26 11:07:04 +0000705 (__GNUC__ >= 4))
Neal Norwitze5e5aa42005-11-13 18:55:39 +0000706#define Py_NO_INLINE __attribute__((__noinline__))
707#else
708#define Py_NO_INLINE
709#endif
710
711/* Don't make static, to try to ensure this isn't inlined. */
712int Py_ADDRESS_IN_RANGE(void *P, poolp pool) Py_NO_INLINE;
713#undef Py_NO_INLINE
Neal Norwitz7eb3c912004-06-06 19:20:22 +0000714#endif
Tim Peters338e0102002-04-01 19:23:44 +0000715
Neil Schemenauera35c6882001-02-27 04:45:05 +0000716/*==========================================================================*/
717
Tim Peters84c1b972002-04-04 04:44:32 +0000718/* malloc. Note that nbytes==0 tries to return a non-NULL pointer, distinct
719 * from all other currently live pointers. This may not be possible.
720 */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000721
722/*
723 * The basic blocks are ordered by decreasing execution frequency,
724 * which minimizes the number of jumps in the most common cases,
725 * improves branching prediction and instruction scheduling (small
726 * block allocations typically result in a couple of instructions).
727 * Unless the optimizer reorders everything, being too smart...
728 */
729
Neil Schemenauerd2560cd2002-04-12 03:10:20 +0000730#undef PyObject_Malloc
Neil Schemenauera35c6882001-02-27 04:45:05 +0000731void *
Neil Schemenauerd2560cd2002-04-12 03:10:20 +0000732PyObject_Malloc(size_t nbytes)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000733{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000734 block *bp;
735 poolp pool;
736 poolp next;
737 uint size;
Neil Schemenauera35c6882001-02-27 04:45:05 +0000738
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000739 /*
740 * Limit ourselves to PY_SSIZE_T_MAX bytes to prevent security holes.
741 * Most python internals blindly use a signed Py_ssize_t to track
742 * things without checking for overflows or negatives.
743 * As size_t is unsigned, checking for nbytes < 0 is not required.
744 */
745 if (nbytes > PY_SSIZE_T_MAX)
746 return NULL;
Georg Brandld492ad82008-07-23 16:13:07 +0000747
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000748 /*
749 * This implicitly redirects malloc(0).
750 */
751 if ((nbytes - 1) < SMALL_REQUEST_THRESHOLD) {
752 LOCK();
753 /*
754 * Most frequent paths first
755 */
756 size = (uint)(nbytes - 1) >> ALIGNMENT_SHIFT;
757 pool = usedpools[size + size];
758 if (pool != pool->nextpool) {
759 /*
760 * There is a used pool for this size class.
761 * Pick up the head block of its free list.
762 */
763 ++pool->ref.count;
764 bp = pool->freeblock;
765 assert(bp != NULL);
766 if ((pool->freeblock = *(block **)bp) != NULL) {
767 UNLOCK();
768 return (void *)bp;
769 }
770 /*
771 * Reached the end of the free list, try to extend it.
772 */
773 if (pool->nextoffset <= pool->maxnextoffset) {
774 /* There is room for another block. */
775 pool->freeblock = (block*)pool +
776 pool->nextoffset;
777 pool->nextoffset += INDEX2SIZE(size);
778 *(block **)(pool->freeblock) = NULL;
779 UNLOCK();
780 return (void *)bp;
781 }
782 /* Pool is full, unlink from used pools. */
783 next = pool->nextpool;
784 pool = pool->prevpool;
785 next->prevpool = pool;
786 pool->nextpool = next;
787 UNLOCK();
788 return (void *)bp;
789 }
Thomas Woutersa9773292006-04-21 09:43:23 +0000790
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000791 /* There isn't a pool of the right size class immediately
792 * available: use a free pool.
793 */
794 if (usable_arenas == NULL) {
795 /* No arena has a free pool: allocate a new arena. */
Thomas Woutersa9773292006-04-21 09:43:23 +0000796#ifdef WITH_MEMORY_LIMITS
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000797 if (narenas_currently_allocated >= MAX_ARENAS) {
798 UNLOCK();
799 goto redirect;
800 }
Thomas Woutersa9773292006-04-21 09:43:23 +0000801#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000802 usable_arenas = new_arena();
803 if (usable_arenas == NULL) {
804 UNLOCK();
805 goto redirect;
806 }
807 usable_arenas->nextarena =
808 usable_arenas->prevarena = NULL;
809 }
810 assert(usable_arenas->address != 0);
Thomas Woutersa9773292006-04-21 09:43:23 +0000811
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000812 /* Try to get a cached free pool. */
813 pool = usable_arenas->freepools;
814 if (pool != NULL) {
815 /* Unlink from cached pools. */
816 usable_arenas->freepools = pool->nextpool;
Thomas Woutersa9773292006-04-21 09:43:23 +0000817
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000818 /* This arena already had the smallest nfreepools
819 * value, so decreasing nfreepools doesn't change
820 * that, and we don't need to rearrange the
821 * usable_arenas list. However, if the arena has
822 * become wholly allocated, we need to remove its
823 * arena_object from usable_arenas.
824 */
825 --usable_arenas->nfreepools;
826 if (usable_arenas->nfreepools == 0) {
827 /* Wholly allocated: remove. */
828 assert(usable_arenas->freepools == NULL);
829 assert(usable_arenas->nextarena == NULL ||
830 usable_arenas->nextarena->prevarena ==
831 usable_arenas);
Thomas Woutersa9773292006-04-21 09:43:23 +0000832
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000833 usable_arenas = usable_arenas->nextarena;
834 if (usable_arenas != NULL) {
835 usable_arenas->prevarena = NULL;
836 assert(usable_arenas->address != 0);
837 }
838 }
839 else {
840 /* nfreepools > 0: it must be that freepools
841 * isn't NULL, or that we haven't yet carved
842 * off all the arena's pools for the first
843 * time.
844 */
845 assert(usable_arenas->freepools != NULL ||
846 usable_arenas->pool_address <=
847 (block*)usable_arenas->address +
848 ARENA_SIZE - POOL_SIZE);
849 }
850 init_pool:
851 /* Frontlink to used pools. */
852 next = usedpools[size + size]; /* == prev */
853 pool->nextpool = next;
854 pool->prevpool = next;
855 next->nextpool = pool;
856 next->prevpool = pool;
857 pool->ref.count = 1;
858 if (pool->szidx == size) {
859 /* Luckily, this pool last contained blocks
860 * of the same size class, so its header
861 * and free list are already initialized.
862 */
863 bp = pool->freeblock;
864 pool->freeblock = *(block **)bp;
865 UNLOCK();
866 return (void *)bp;
867 }
868 /*
869 * Initialize the pool header, set up the free list to
870 * contain just the second block, and return the first
871 * block.
872 */
873 pool->szidx = size;
874 size = INDEX2SIZE(size);
875 bp = (block *)pool + POOL_OVERHEAD;
876 pool->nextoffset = POOL_OVERHEAD + (size << 1);
877 pool->maxnextoffset = POOL_SIZE - size;
878 pool->freeblock = bp + size;
879 *(block **)(pool->freeblock) = NULL;
880 UNLOCK();
881 return (void *)bp;
882 }
Thomas Woutersa9773292006-04-21 09:43:23 +0000883
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000884 /* Carve off a new pool. */
885 assert(usable_arenas->nfreepools > 0);
886 assert(usable_arenas->freepools == NULL);
887 pool = (poolp)usable_arenas->pool_address;
888 assert((block*)pool <= (block*)usable_arenas->address +
889 ARENA_SIZE - POOL_SIZE);
890 pool->arenaindex = usable_arenas - arenas;
891 assert(&arenas[pool->arenaindex] == usable_arenas);
892 pool->szidx = DUMMY_SIZE_IDX;
893 usable_arenas->pool_address += POOL_SIZE;
894 --usable_arenas->nfreepools;
Thomas Woutersa9773292006-04-21 09:43:23 +0000895
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000896 if (usable_arenas->nfreepools == 0) {
897 assert(usable_arenas->nextarena == NULL ||
898 usable_arenas->nextarena->prevarena ==
899 usable_arenas);
900 /* Unlink the arena: it is completely allocated. */
901 usable_arenas = usable_arenas->nextarena;
902 if (usable_arenas != NULL) {
903 usable_arenas->prevarena = NULL;
904 assert(usable_arenas->address != 0);
905 }
906 }
Thomas Woutersa9773292006-04-21 09:43:23 +0000907
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000908 goto init_pool;
909 }
Neil Schemenauera35c6882001-02-27 04:45:05 +0000910
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000911 /* The small block allocator ends here. */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000912
Tim Petersd97a1c02002-03-30 06:09:22 +0000913redirect:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000914 /* Redirect the original request to the underlying (libc) allocator.
915 * We jump here on bigger requests, on error in the code above (as a
916 * last chance to serve the request) or when the max memory limit
917 * has been reached.
918 */
919 if (nbytes == 0)
920 nbytes = 1;
921 return (void *)malloc(nbytes);
Neil Schemenauera35c6882001-02-27 04:45:05 +0000922}
923
924/* free */
925
Neil Schemenauerd2560cd2002-04-12 03:10:20 +0000926#undef PyObject_Free
Neil Schemenauera35c6882001-02-27 04:45:05 +0000927void
Neil Schemenauerd2560cd2002-04-12 03:10:20 +0000928PyObject_Free(void *p)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000929{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000930 poolp pool;
931 block *lastfree;
932 poolp next, prev;
933 uint size;
Antoine Pitrou5b6fc632011-01-07 21:49:25 +0000934#ifndef Py_USING_MEMORY_DEBUGGER
935 uint arenaindex_temp;
936#endif
Neil Schemenauera35c6882001-02-27 04:45:05 +0000937
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000938 if (p == NULL) /* free(NULL) has no effect */
939 return;
Neil Schemenauera35c6882001-02-27 04:45:05 +0000940
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000941 pool = POOL_ADDR(p);
942 if (Py_ADDRESS_IN_RANGE(p, pool)) {
943 /* We allocated this address. */
944 LOCK();
945 /* Link p to the start of the pool's freeblock list. Since
946 * the pool had at least the p block outstanding, the pool
947 * wasn't empty (so it's already in a usedpools[] list, or
948 * was full and is in no list -- it's not in the freeblocks
949 * list in any case).
950 */
951 assert(pool->ref.count > 0); /* else it was empty */
952 *(block **)p = lastfree = pool->freeblock;
953 pool->freeblock = (block *)p;
954 if (lastfree) {
955 struct arena_object* ao;
956 uint nf; /* ao->nfreepools */
Thomas Woutersa9773292006-04-21 09:43:23 +0000957
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000958 /* freeblock wasn't NULL, so the pool wasn't full,
959 * and the pool is in a usedpools[] list.
960 */
961 if (--pool->ref.count != 0) {
962 /* pool isn't empty: leave it in usedpools */
963 UNLOCK();
964 return;
965 }
966 /* Pool is now empty: unlink from usedpools, and
967 * link to the front of freepools. This ensures that
968 * previously freed pools will be allocated later
969 * (being not referenced, they are perhaps paged out).
970 */
971 next = pool->nextpool;
972 prev = pool->prevpool;
973 next->prevpool = prev;
974 prev->nextpool = next;
Thomas Woutersa9773292006-04-21 09:43:23 +0000975
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000976 /* Link the pool to freepools. This is a singly-linked
977 * list, and pool->prevpool isn't used there.
978 */
979 ao = &arenas[pool->arenaindex];
980 pool->nextpool = ao->freepools;
981 ao->freepools = pool;
982 nf = ++ao->nfreepools;
Thomas Woutersa9773292006-04-21 09:43:23 +0000983
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000984 /* All the rest is arena management. We just freed
985 * a pool, and there are 4 cases for arena mgmt:
986 * 1. If all the pools are free, return the arena to
987 * the system free().
988 * 2. If this is the only free pool in the arena,
989 * add the arena back to the `usable_arenas` list.
990 * 3. If the "next" arena has a smaller count of free
991 * pools, we have to "slide this arena right" to
992 * restore that usable_arenas is sorted in order of
993 * nfreepools.
994 * 4. Else there's nothing more to do.
995 */
996 if (nf == ao->ntotalpools) {
997 /* Case 1. First unlink ao from usable_arenas.
998 */
999 assert(ao->prevarena == NULL ||
1000 ao->prevarena->address != 0);
1001 assert(ao ->nextarena == NULL ||
1002 ao->nextarena->address != 0);
Thomas Woutersa9773292006-04-21 09:43:23 +00001003
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001004 /* Fix the pointer in the prevarena, or the
1005 * usable_arenas pointer.
1006 */
1007 if (ao->prevarena == NULL) {
1008 usable_arenas = ao->nextarena;
1009 assert(usable_arenas == NULL ||
1010 usable_arenas->address != 0);
1011 }
1012 else {
1013 assert(ao->prevarena->nextarena == ao);
1014 ao->prevarena->nextarena =
1015 ao->nextarena;
1016 }
1017 /* Fix the pointer in the nextarena. */
1018 if (ao->nextarena != NULL) {
1019 assert(ao->nextarena->prevarena == ao);
1020 ao->nextarena->prevarena =
1021 ao->prevarena;
1022 }
1023 /* Record that this arena_object slot is
1024 * available to be reused.
1025 */
1026 ao->nextarena = unused_arena_objects;
1027 unused_arena_objects = ao;
Thomas Woutersa9773292006-04-21 09:43:23 +00001028
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001029 /* Free the entire arena. */
1030 free((void *)ao->address);
1031 ao->address = 0; /* mark unassociated */
1032 --narenas_currently_allocated;
Thomas Woutersa9773292006-04-21 09:43:23 +00001033
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001034 UNLOCK();
1035 return;
1036 }
1037 if (nf == 1) {
1038 /* Case 2. Put ao at the head of
1039 * usable_arenas. Note that because
1040 * ao->nfreepools was 0 before, ao isn't
1041 * currently on the usable_arenas list.
1042 */
1043 ao->nextarena = usable_arenas;
1044 ao->prevarena = NULL;
1045 if (usable_arenas)
1046 usable_arenas->prevarena = ao;
1047 usable_arenas = ao;
1048 assert(usable_arenas->address != 0);
Thomas Woutersa9773292006-04-21 09:43:23 +00001049
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001050 UNLOCK();
1051 return;
1052 }
1053 /* If this arena is now out of order, we need to keep
1054 * the list sorted. The list is kept sorted so that
1055 * the "most full" arenas are used first, which allows
1056 * the nearly empty arenas to be completely freed. In
1057 * a few un-scientific tests, it seems like this
1058 * approach allowed a lot more memory to be freed.
1059 */
1060 if (ao->nextarena == NULL ||
1061 nf <= ao->nextarena->nfreepools) {
1062 /* Case 4. Nothing to do. */
1063 UNLOCK();
1064 return;
1065 }
1066 /* Case 3: We have to move the arena towards the end
1067 * of the list, because it has more free pools than
1068 * the arena to its right.
1069 * First unlink ao from usable_arenas.
1070 */
1071 if (ao->prevarena != NULL) {
1072 /* ao isn't at the head of the list */
1073 assert(ao->prevarena->nextarena == ao);
1074 ao->prevarena->nextarena = ao->nextarena;
1075 }
1076 else {
1077 /* ao is at the head of the list */
1078 assert(usable_arenas == ao);
1079 usable_arenas = ao->nextarena;
1080 }
1081 ao->nextarena->prevarena = ao->prevarena;
Thomas Woutersa9773292006-04-21 09:43:23 +00001082
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001083 /* Locate the new insertion point by iterating over
1084 * the list, using our nextarena pointer.
1085 */
1086 while (ao->nextarena != NULL &&
1087 nf > ao->nextarena->nfreepools) {
1088 ao->prevarena = ao->nextarena;
1089 ao->nextarena = ao->nextarena->nextarena;
1090 }
Thomas Woutersa9773292006-04-21 09:43:23 +00001091
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001092 /* Insert ao at this point. */
1093 assert(ao->nextarena == NULL ||
1094 ao->prevarena == ao->nextarena->prevarena);
1095 assert(ao->prevarena->nextarena == ao->nextarena);
Thomas Woutersa9773292006-04-21 09:43:23 +00001096
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001097 ao->prevarena->nextarena = ao;
1098 if (ao->nextarena != NULL)
1099 ao->nextarena->prevarena = ao;
Thomas Woutersa9773292006-04-21 09:43:23 +00001100
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001101 /* Verify that the swaps worked. */
1102 assert(ao->nextarena == NULL ||
1103 nf <= ao->nextarena->nfreepools);
1104 assert(ao->prevarena == NULL ||
1105 nf > ao->prevarena->nfreepools);
1106 assert(ao->nextarena == NULL ||
1107 ao->nextarena->prevarena == ao);
1108 assert((usable_arenas == ao &&
1109 ao->prevarena == NULL) ||
1110 ao->prevarena->nextarena == ao);
Thomas Woutersa9773292006-04-21 09:43:23 +00001111
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001112 UNLOCK();
1113 return;
1114 }
1115 /* Pool was full, so doesn't currently live in any list:
1116 * link it to the front of the appropriate usedpools[] list.
1117 * This mimics LRU pool usage for new allocations and
1118 * targets optimal filling when several pools contain
1119 * blocks of the same size class.
1120 */
1121 --pool->ref.count;
1122 assert(pool->ref.count > 0); /* else the pool is empty */
1123 size = pool->szidx;
1124 next = usedpools[size + size];
1125 prev = next->prevpool;
1126 /* insert pool before next: prev <-> pool <-> next */
1127 pool->nextpool = next;
1128 pool->prevpool = prev;
1129 next->prevpool = pool;
1130 prev->nextpool = pool;
1131 UNLOCK();
1132 return;
1133 }
Neil Schemenauera35c6882001-02-27 04:45:05 +00001134
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001135 /* We didn't allocate this address. */
1136 free(p);
Neil Schemenauera35c6882001-02-27 04:45:05 +00001137}
1138
Tim Peters84c1b972002-04-04 04:44:32 +00001139/* realloc. If p is NULL, this acts like malloc(nbytes). Else if nbytes==0,
1140 * then as the Python docs promise, we do not treat this like free(p), and
1141 * return a non-NULL result.
1142 */
Neil Schemenauera35c6882001-02-27 04:45:05 +00001143
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00001144#undef PyObject_Realloc
Neil Schemenauera35c6882001-02-27 04:45:05 +00001145void *
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00001146PyObject_Realloc(void *p, size_t nbytes)
Neil Schemenauera35c6882001-02-27 04:45:05 +00001147{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001148 void *bp;
1149 poolp pool;
1150 size_t size;
Antoine Pitrou5b6fc632011-01-07 21:49:25 +00001151#ifndef Py_USING_MEMORY_DEBUGGER
1152 uint arenaindex_temp;
1153#endif
Neil Schemenauera35c6882001-02-27 04:45:05 +00001154
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001155 if (p == NULL)
1156 return PyObject_Malloc(nbytes);
Neil Schemenauera35c6882001-02-27 04:45:05 +00001157
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001158 /*
1159 * Limit ourselves to PY_SSIZE_T_MAX bytes to prevent security holes.
1160 * Most python internals blindly use a signed Py_ssize_t to track
1161 * things without checking for overflows or negatives.
1162 * As size_t is unsigned, checking for nbytes < 0 is not required.
1163 */
1164 if (nbytes > PY_SSIZE_T_MAX)
1165 return NULL;
Georg Brandld492ad82008-07-23 16:13:07 +00001166
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001167 pool = POOL_ADDR(p);
1168 if (Py_ADDRESS_IN_RANGE(p, pool)) {
1169 /* We're in charge of this block */
1170 size = INDEX2SIZE(pool->szidx);
1171 if (nbytes <= size) {
1172 /* The block is staying the same or shrinking. If
1173 * it's shrinking, there's a tradeoff: it costs
1174 * cycles to copy the block to a smaller size class,
1175 * but it wastes memory not to copy it. The
1176 * compromise here is to copy on shrink only if at
1177 * least 25% of size can be shaved off.
1178 */
1179 if (4 * nbytes > 3 * size) {
1180 /* It's the same,
1181 * or shrinking and new/old > 3/4.
1182 */
1183 return p;
1184 }
1185 size = nbytes;
1186 }
1187 bp = PyObject_Malloc(nbytes);
1188 if (bp != NULL) {
1189 memcpy(bp, p, size);
1190 PyObject_Free(p);
1191 }
1192 return bp;
1193 }
1194 /* We're not managing this block. If nbytes <=
1195 * SMALL_REQUEST_THRESHOLD, it's tempting to try to take over this
1196 * block. However, if we do, we need to copy the valid data from
1197 * the C-managed block to one of our blocks, and there's no portable
1198 * way to know how much of the memory space starting at p is valid.
1199 * As bug 1185883 pointed out the hard way, it's possible that the
1200 * C-managed block is "at the end" of allocated VM space, so that
1201 * a memory fault can occur if we try to copy nbytes bytes starting
1202 * at p. Instead we punt: let C continue to manage this block.
1203 */
1204 if (nbytes)
1205 return realloc(p, nbytes);
1206 /* C doesn't define the result of realloc(p, 0) (it may or may not
1207 * return NULL then), but Python's docs promise that nbytes==0 never
1208 * returns NULL. We don't pass 0 to realloc(), to avoid that endcase
1209 * to begin with. Even then, we can't be sure that realloc() won't
1210 * return NULL.
1211 */
1212 bp = realloc(p, 1);
1213 return bp ? bp : p;
Neil Schemenauera35c6882001-02-27 04:45:05 +00001214}
1215
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001216#else /* ! WITH_PYMALLOC */
Tim Petersddea2082002-03-23 10:03:50 +00001217
1218/*==========================================================================*/
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00001219/* pymalloc not enabled: Redirect the entry points to malloc. These will
1220 * only be used by extensions that are compiled with pymalloc enabled. */
Tim Peters62c06ba2002-03-23 22:28:18 +00001221
Tim Petersce7fb9b2002-03-23 00:28:57 +00001222void *
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00001223PyObject_Malloc(size_t n)
Tim Peters1221c0a2002-03-23 00:20:15 +00001224{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001225 return PyMem_MALLOC(n);
Tim Peters1221c0a2002-03-23 00:20:15 +00001226}
1227
Tim Petersce7fb9b2002-03-23 00:28:57 +00001228void *
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00001229PyObject_Realloc(void *p, size_t n)
Tim Peters1221c0a2002-03-23 00:20:15 +00001230{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001231 return PyMem_REALLOC(p, n);
Tim Peters1221c0a2002-03-23 00:20:15 +00001232}
1233
1234void
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00001235PyObject_Free(void *p)
Tim Peters1221c0a2002-03-23 00:20:15 +00001236{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001237 PyMem_FREE(p);
Tim Peters1221c0a2002-03-23 00:20:15 +00001238}
1239#endif /* WITH_PYMALLOC */
1240
Tim Petersddea2082002-03-23 10:03:50 +00001241#ifdef PYMALLOC_DEBUG
1242/*==========================================================================*/
Tim Peters62c06ba2002-03-23 22:28:18 +00001243/* A x-platform debugging allocator. This doesn't manage memory directly,
1244 * it wraps a real allocator, adding extra debugging info to the memory blocks.
1245 */
Tim Petersddea2082002-03-23 10:03:50 +00001246
Tim Petersf6fb5012002-04-12 07:38:53 +00001247/* Special bytes broadcast into debug memory blocks at appropriate times.
1248 * Strings of these are unlikely to be valid addresses, floats, ints or
1249 * 7-bit ASCII.
1250 */
1251#undef CLEANBYTE
1252#undef DEADBYTE
1253#undef FORBIDDENBYTE
1254#define CLEANBYTE 0xCB /* clean (newly allocated) memory */
Tim Peters889f61d2002-07-10 19:29:49 +00001255#define DEADBYTE 0xDB /* dead (newly freed) memory */
Tim Petersf6fb5012002-04-12 07:38:53 +00001256#define FORBIDDENBYTE 0xFB /* untouchable bytes at each end of a block */
Tim Petersddea2082002-03-23 10:03:50 +00001257
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001258static size_t serialno = 0; /* incremented on each debug {m,re}alloc */
Tim Petersddea2082002-03-23 10:03:50 +00001259
Tim Peterse0850172002-03-24 00:34:21 +00001260/* serialno is always incremented via calling this routine. The point is
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001261 * to supply a single place to set a breakpoint.
1262 */
Tim Peterse0850172002-03-24 00:34:21 +00001263static void
Neil Schemenauerbd02b142002-03-28 21:05:38 +00001264bumpserialno(void)
Tim Peterse0850172002-03-24 00:34:21 +00001265{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001266 ++serialno;
Tim Peterse0850172002-03-24 00:34:21 +00001267}
1268
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001269#define SST SIZEOF_SIZE_T
Tim Peterse0850172002-03-24 00:34:21 +00001270
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001271/* Read sizeof(size_t) bytes at p as a big-endian size_t. */
1272static size_t
1273read_size_t(const void *p)
Tim Petersddea2082002-03-23 10:03:50 +00001274{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001275 const uchar *q = (const uchar *)p;
1276 size_t result = *q++;
1277 int i;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001278
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001279 for (i = SST; --i > 0; ++q)
1280 result = (result << 8) | *q;
1281 return result;
Tim Petersddea2082002-03-23 10:03:50 +00001282}
1283
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001284/* Write n as a big-endian size_t, MSB at address p, LSB at
1285 * p + sizeof(size_t) - 1.
1286 */
Tim Petersddea2082002-03-23 10:03:50 +00001287static void
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001288write_size_t(void *p, size_t n)
Tim Petersddea2082002-03-23 10:03:50 +00001289{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001290 uchar *q = (uchar *)p + SST - 1;
1291 int i;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001292
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001293 for (i = SST; --i >= 0; --q) {
1294 *q = (uchar)(n & 0xff);
1295 n >>= 8;
1296 }
Tim Petersddea2082002-03-23 10:03:50 +00001297}
1298
Tim Peters08d82152002-04-18 22:25:03 +00001299#ifdef Py_DEBUG
1300/* Is target in the list? The list is traversed via the nextpool pointers.
1301 * The list may be NULL-terminated, or circular. Return 1 if target is in
1302 * list, else 0.
1303 */
1304static int
1305pool_is_in_list(const poolp target, poolp list)
1306{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001307 poolp origlist = list;
1308 assert(target != NULL);
1309 if (list == NULL)
1310 return 0;
1311 do {
1312 if (target == list)
1313 return 1;
1314 list = list->nextpool;
1315 } while (list != NULL && list != origlist);
1316 return 0;
Tim Peters08d82152002-04-18 22:25:03 +00001317}
1318
1319#else
1320#define pool_is_in_list(X, Y) 1
1321
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001322#endif /* Py_DEBUG */
Tim Peters08d82152002-04-18 22:25:03 +00001323
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001324/* Let S = sizeof(size_t). The debug malloc asks for 4*S extra bytes and
1325 fills them with useful stuff, here calling the underlying malloc's result p:
Tim Petersddea2082002-03-23 10:03:50 +00001326
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001327p[0: S]
1328 Number of bytes originally asked for. This is a size_t, big-endian (easier
1329 to read in a memory dump).
1330p[S: 2*S]
Tim Petersf6fb5012002-04-12 07:38:53 +00001331 Copies of FORBIDDENBYTE. Used to catch under- writes and reads.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001332p[2*S: 2*S+n]
Tim Petersf6fb5012002-04-12 07:38:53 +00001333 The requested memory, filled with copies of CLEANBYTE.
Tim Petersddea2082002-03-23 10:03:50 +00001334 Used to catch reference to uninitialized memory.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001335 &p[2*S] is returned. Note that this is 8-byte aligned if pymalloc
Tim Petersddea2082002-03-23 10:03:50 +00001336 handled the request itself.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001337p[2*S+n: 2*S+n+S]
Tim Petersf6fb5012002-04-12 07:38:53 +00001338 Copies of FORBIDDENBYTE. Used to catch over- writes and reads.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001339p[2*S+n+S: 2*S+n+2*S]
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00001340 A serial number, incremented by 1 on each call to _PyObject_DebugMalloc
1341 and _PyObject_DebugRealloc.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001342 This is a big-endian size_t.
Tim Petersddea2082002-03-23 10:03:50 +00001343 If "bad memory" is detected later, the serial number gives an
1344 excellent way to set a breakpoint on the next run, to capture the
1345 instant at which this block was passed out.
1346*/
1347
1348void *
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00001349_PyObject_DebugMalloc(size_t nbytes)
Tim Petersddea2082002-03-23 10:03:50 +00001350{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001351 uchar *p; /* base address of malloc'ed block */
1352 uchar *tail; /* p + 2*SST + nbytes == pointer to tail pad bytes */
1353 size_t total; /* nbytes + 4*SST */
Tim Petersddea2082002-03-23 10:03:50 +00001354
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001355 bumpserialno();
1356 total = nbytes + 4*SST;
1357 if (total < nbytes)
1358 /* overflow: can't represent total as a size_t */
1359 return NULL;
Tim Petersddea2082002-03-23 10:03:50 +00001360
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001361 p = (uchar *)PyObject_Malloc(total);
1362 if (p == NULL)
1363 return NULL;
Tim Petersddea2082002-03-23 10:03:50 +00001364
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001365 write_size_t(p, nbytes);
1366 memset(p + SST, FORBIDDENBYTE, SST);
Tim Petersddea2082002-03-23 10:03:50 +00001367
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001368 if (nbytes > 0)
1369 memset(p + 2*SST, CLEANBYTE, nbytes);
Tim Petersddea2082002-03-23 10:03:50 +00001370
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001371 tail = p + 2*SST + nbytes;
1372 memset(tail, FORBIDDENBYTE, SST);
1373 write_size_t(tail + SST, serialno);
Tim Petersddea2082002-03-23 10:03:50 +00001374
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001375 return p + 2*SST;
Tim Petersddea2082002-03-23 10:03:50 +00001376}
1377
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001378/* The debug free first checks the 2*SST bytes on each end for sanity (in
Tim Petersf6fb5012002-04-12 07:38:53 +00001379 particular, that the FORBIDDENBYTEs are still intact).
1380 Then fills the original bytes with DEADBYTE.
Tim Petersddea2082002-03-23 10:03:50 +00001381 Then calls the underlying free.
1382*/
1383void
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00001384_PyObject_DebugFree(void *p)
Tim Petersddea2082002-03-23 10:03:50 +00001385{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001386 uchar *q = (uchar *)p - 2*SST; /* address returned from malloc */
1387 size_t nbytes;
Tim Petersddea2082002-03-23 10:03:50 +00001388
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001389 if (p == NULL)
1390 return;
1391 _PyObject_DebugCheckAddress(p);
1392 nbytes = read_size_t(q);
1393 if (nbytes > 0)
1394 memset(q, DEADBYTE, nbytes);
1395 PyObject_Free(q);
Tim Petersddea2082002-03-23 10:03:50 +00001396}
1397
1398void *
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00001399_PyObject_DebugRealloc(void *p, size_t nbytes)
Tim Petersddea2082002-03-23 10:03:50 +00001400{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001401 uchar *q = (uchar *)p;
1402 uchar *tail;
1403 size_t total; /* nbytes + 4*SST */
1404 size_t original_nbytes;
1405 int i;
Tim Petersddea2082002-03-23 10:03:50 +00001406
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001407 if (p == NULL)
1408 return _PyObject_DebugMalloc(nbytes);
Tim Petersddea2082002-03-23 10:03:50 +00001409
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001410 _PyObject_DebugCheckAddress(p);
1411 bumpserialno();
1412 original_nbytes = read_size_t(q - 2*SST);
1413 total = nbytes + 4*SST;
1414 if (total < nbytes)
1415 /* overflow: can't represent total as a size_t */
1416 return NULL;
Tim Petersddea2082002-03-23 10:03:50 +00001417
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001418 if (nbytes < original_nbytes) {
1419 /* shrinking: mark old extra memory dead */
1420 memset(q + nbytes, DEADBYTE, original_nbytes - nbytes);
1421 }
Tim Petersddea2082002-03-23 10:03:50 +00001422
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001423 /* Resize and add decorations. */
1424 q = (uchar *)PyObject_Realloc(q - 2*SST, total);
1425 if (q == NULL)
1426 return NULL;
Tim Peters85cc1c42002-04-12 08:52:50 +00001427
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001428 write_size_t(q, nbytes);
1429 for (i = 0; i < SST; ++i)
1430 assert(q[SST + i] == FORBIDDENBYTE);
1431 q += 2*SST;
1432 tail = q + nbytes;
1433 memset(tail, FORBIDDENBYTE, SST);
1434 write_size_t(tail + SST, serialno);
Tim Peters85cc1c42002-04-12 08:52:50 +00001435
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001436 if (nbytes > original_nbytes) {
1437 /* growing: mark new extra memory clean */
1438 memset(q + original_nbytes, CLEANBYTE,
Stefan Krah5d744a82010-11-26 11:07:04 +00001439 nbytes - original_nbytes);
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001440 }
Tim Peters85cc1c42002-04-12 08:52:50 +00001441
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001442 return q;
Tim Petersddea2082002-03-23 10:03:50 +00001443}
1444
Tim Peters7ccfadf2002-04-01 06:04:21 +00001445/* Check the forbidden bytes on both ends of the memory allocated for p.
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00001446 * If anything is wrong, print info to stderr via _PyObject_DebugDumpAddress,
Tim Peters7ccfadf2002-04-01 06:04:21 +00001447 * and call Py_FatalError to kill the program.
1448 */
1449 void
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00001450_PyObject_DebugCheckAddress(const void *p)
Tim Petersddea2082002-03-23 10:03:50 +00001451{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001452 const uchar *q = (const uchar *)p;
1453 char *msg;
1454 size_t nbytes;
1455 const uchar *tail;
1456 int i;
Tim Petersddea2082002-03-23 10:03:50 +00001457
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001458 if (p == NULL) {
1459 msg = "didn't expect a NULL pointer";
1460 goto error;
1461 }
Tim Petersddea2082002-03-23 10:03:50 +00001462
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001463 /* Check the stuff at the start of p first: if there's underwrite
1464 * corruption, the number-of-bytes field may be nuts, and checking
1465 * the tail could lead to a segfault then.
1466 */
1467 for (i = SST; i >= 1; --i) {
1468 if (*(q-i) != FORBIDDENBYTE) {
1469 msg = "bad leading pad byte";
1470 goto error;
1471 }
1472 }
Tim Petersddea2082002-03-23 10:03:50 +00001473
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001474 nbytes = read_size_t(q - 2*SST);
1475 tail = q + nbytes;
1476 for (i = 0; i < SST; ++i) {
1477 if (tail[i] != FORBIDDENBYTE) {
1478 msg = "bad trailing pad byte";
1479 goto error;
1480 }
1481 }
Tim Petersddea2082002-03-23 10:03:50 +00001482
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001483 return;
Tim Petersd1139e02002-03-28 07:32:11 +00001484
1485error:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001486 _PyObject_DebugDumpAddress(p);
1487 Py_FatalError(msg);
Tim Petersddea2082002-03-23 10:03:50 +00001488}
1489
Tim Peters7ccfadf2002-04-01 06:04:21 +00001490/* Display info to stderr about the memory block at p. */
Tim Petersddea2082002-03-23 10:03:50 +00001491void
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00001492_PyObject_DebugDumpAddress(const void *p)
Tim Petersddea2082002-03-23 10:03:50 +00001493{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001494 const uchar *q = (const uchar *)p;
1495 const uchar *tail;
1496 size_t nbytes, serial;
1497 int i;
1498 int ok;
Tim Petersddea2082002-03-23 10:03:50 +00001499
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001500 fprintf(stderr, "Debug memory block at address p=%p:\n", p);
1501 if (p == NULL)
1502 return;
Tim Petersddea2082002-03-23 10:03:50 +00001503
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001504 nbytes = read_size_t(q - 2*SST);
1505 fprintf(stderr, " %" PY_FORMAT_SIZE_T "u bytes originally "
1506 "requested\n", nbytes);
Tim Petersddea2082002-03-23 10:03:50 +00001507
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001508 /* In case this is nuts, check the leading pad bytes first. */
1509 fprintf(stderr, " The %d pad bytes at p-%d are ", SST, SST);
1510 ok = 1;
1511 for (i = 1; i <= SST; ++i) {
1512 if (*(q-i) != FORBIDDENBYTE) {
1513 ok = 0;
1514 break;
1515 }
1516 }
1517 if (ok)
1518 fputs("FORBIDDENBYTE, as expected.\n", stderr);
1519 else {
1520 fprintf(stderr, "not all FORBIDDENBYTE (0x%02x):\n",
1521 FORBIDDENBYTE);
1522 for (i = SST; i >= 1; --i) {
1523 const uchar byte = *(q-i);
1524 fprintf(stderr, " at p-%d: 0x%02x", i, byte);
1525 if (byte != FORBIDDENBYTE)
1526 fputs(" *** OUCH", stderr);
1527 fputc('\n', stderr);
1528 }
Tim Peters449b5a82002-04-28 06:14:45 +00001529
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001530 fputs(" Because memory is corrupted at the start, the "
1531 "count of bytes requested\n"
1532 " may be bogus, and checking the trailing pad "
1533 "bytes may segfault.\n", stderr);
1534 }
Tim Petersddea2082002-03-23 10:03:50 +00001535
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001536 tail = q + nbytes;
1537 fprintf(stderr, " The %d pad bytes at tail=%p are ", SST, tail);
1538 ok = 1;
1539 for (i = 0; i < SST; ++i) {
1540 if (tail[i] != FORBIDDENBYTE) {
1541 ok = 0;
1542 break;
1543 }
1544 }
1545 if (ok)
1546 fputs("FORBIDDENBYTE, as expected.\n", stderr);
1547 else {
1548 fprintf(stderr, "not all FORBIDDENBYTE (0x%02x):\n",
Stefan Krah5d744a82010-11-26 11:07:04 +00001549 FORBIDDENBYTE);
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001550 for (i = 0; i < SST; ++i) {
1551 const uchar byte = tail[i];
1552 fprintf(stderr, " at tail+%d: 0x%02x",
Stefan Krah5d744a82010-11-26 11:07:04 +00001553 i, byte);
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001554 if (byte != FORBIDDENBYTE)
1555 fputs(" *** OUCH", stderr);
1556 fputc('\n', stderr);
1557 }
1558 }
Tim Petersddea2082002-03-23 10:03:50 +00001559
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001560 serial = read_size_t(tail + SST);
1561 fprintf(stderr, " The block was made by call #%" PY_FORMAT_SIZE_T
1562 "u to debug malloc/realloc.\n", serial);
Tim Petersddea2082002-03-23 10:03:50 +00001563
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001564 if (nbytes > 0) {
1565 i = 0;
1566 fputs(" Data at p:", stderr);
1567 /* print up to 8 bytes at the start */
1568 while (q < tail && i < 8) {
1569 fprintf(stderr, " %02x", *q);
1570 ++i;
1571 ++q;
1572 }
1573 /* and up to 8 at the end */
1574 if (q < tail) {
1575 if (tail - q > 8) {
1576 fputs(" ...", stderr);
1577 q = tail - 8;
1578 }
1579 while (q < tail) {
1580 fprintf(stderr, " %02x", *q);
1581 ++q;
1582 }
1583 }
1584 fputc('\n', stderr);
1585 }
Tim Petersddea2082002-03-23 10:03:50 +00001586}
1587
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001588static size_t
1589printone(const char* msg, size_t value)
Tim Peters16bcb6b2002-04-05 05:45:31 +00001590{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001591 int i, k;
1592 char buf[100];
1593 size_t origvalue = value;
Tim Peters16bcb6b2002-04-05 05:45:31 +00001594
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001595 fputs(msg, stderr);
1596 for (i = (int)strlen(msg); i < 35; ++i)
1597 fputc(' ', stderr);
1598 fputc('=', stderr);
Tim Peters49f26812002-04-06 01:45:35 +00001599
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001600 /* Write the value with commas. */
1601 i = 22;
1602 buf[i--] = '\0';
1603 buf[i--] = '\n';
1604 k = 3;
1605 do {
1606 size_t nextvalue = value / 10;
1607 uint digit = (uint)(value - nextvalue * 10);
1608 value = nextvalue;
1609 buf[i--] = (char)(digit + '0');
1610 --k;
1611 if (k == 0 && value && i >= 0) {
1612 k = 3;
1613 buf[i--] = ',';
1614 }
1615 } while (value && i >= 0);
Tim Peters49f26812002-04-06 01:45:35 +00001616
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001617 while (i >= 0)
1618 buf[i--] = ' ';
1619 fputs(buf, stderr);
Tim Peters49f26812002-04-06 01:45:35 +00001620
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001621 return origvalue;
Tim Peters16bcb6b2002-04-05 05:45:31 +00001622}
1623
Tim Peters08d82152002-04-18 22:25:03 +00001624/* Print summary info to stderr about the state of pymalloc's structures.
1625 * In Py_DEBUG mode, also perform some expensive internal consistency
1626 * checks.
1627 */
Tim Peters7ccfadf2002-04-01 06:04:21 +00001628void
Tim Peters0e871182002-04-13 08:29:14 +00001629_PyObject_DebugMallocStats(void)
Tim Peters7ccfadf2002-04-01 06:04:21 +00001630{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001631 uint i;
1632 const uint numclasses = SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT;
1633 /* # of pools, allocated blocks, and free blocks per class index */
1634 size_t numpools[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT];
1635 size_t numblocks[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT];
1636 size_t numfreeblocks[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT];
1637 /* total # of allocated bytes in used and full pools */
1638 size_t allocated_bytes = 0;
1639 /* total # of available bytes in used pools */
1640 size_t available_bytes = 0;
1641 /* # of free pools + pools not yet carved out of current arena */
1642 uint numfreepools = 0;
1643 /* # of bytes for arena alignment padding */
1644 size_t arena_alignment = 0;
1645 /* # of bytes in used and full pools used for pool_headers */
1646 size_t pool_header_bytes = 0;
1647 /* # of bytes in used and full pools wasted due to quantization,
1648 * i.e. the necessarily leftover space at the ends of used and
1649 * full pools.
1650 */
1651 size_t quantization = 0;
1652 /* # of arenas actually allocated. */
1653 size_t narenas = 0;
1654 /* running total -- should equal narenas * ARENA_SIZE */
1655 size_t total;
1656 char buf[128];
Tim Peters7ccfadf2002-04-01 06:04:21 +00001657
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001658 fprintf(stderr, "Small block threshold = %d, in %u size classes.\n",
Stefan Krah5d744a82010-11-26 11:07:04 +00001659 SMALL_REQUEST_THRESHOLD, numclasses);
Tim Peters7ccfadf2002-04-01 06:04:21 +00001660
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001661 for (i = 0; i < numclasses; ++i)
1662 numpools[i] = numblocks[i] = numfreeblocks[i] = 0;
Tim Peters7ccfadf2002-04-01 06:04:21 +00001663
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001664 /* Because full pools aren't linked to from anything, it's easiest
1665 * to march over all the arenas. If we're lucky, most of the memory
1666 * will be living in full pools -- would be a shame to miss them.
1667 */
1668 for (i = 0; i < maxarenas; ++i) {
1669 uint poolsinarena;
1670 uint j;
1671 uptr base = arenas[i].address;
Thomas Woutersa9773292006-04-21 09:43:23 +00001672
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001673 /* Skip arenas which are not allocated. */
1674 if (arenas[i].address == (uptr)NULL)
1675 continue;
1676 narenas += 1;
Thomas Woutersa9773292006-04-21 09:43:23 +00001677
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001678 poolsinarena = arenas[i].ntotalpools;
1679 numfreepools += arenas[i].nfreepools;
Tim Peters7ccfadf2002-04-01 06:04:21 +00001680
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001681 /* round up to pool alignment */
1682 if (base & (uptr)POOL_SIZE_MASK) {
1683 arena_alignment += POOL_SIZE;
1684 base &= ~(uptr)POOL_SIZE_MASK;
1685 base += POOL_SIZE;
1686 }
Tim Peters7ccfadf2002-04-01 06:04:21 +00001687
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001688 /* visit every pool in the arena */
1689 assert(base <= (uptr) arenas[i].pool_address);
1690 for (j = 0;
1691 base < (uptr) arenas[i].pool_address;
1692 ++j, base += POOL_SIZE) {
1693 poolp p = (poolp)base;
1694 const uint sz = p->szidx;
1695 uint freeblocks;
Tim Peters08d82152002-04-18 22:25:03 +00001696
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001697 if (p->ref.count == 0) {
1698 /* currently unused */
1699 assert(pool_is_in_list(p, arenas[i].freepools));
1700 continue;
1701 }
1702 ++numpools[sz];
1703 numblocks[sz] += p->ref.count;
1704 freeblocks = NUMBLOCKS(sz) - p->ref.count;
1705 numfreeblocks[sz] += freeblocks;
Tim Peters08d82152002-04-18 22:25:03 +00001706#ifdef Py_DEBUG
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001707 if (freeblocks > 0)
1708 assert(pool_is_in_list(p, usedpools[sz + sz]));
Tim Peters08d82152002-04-18 22:25:03 +00001709#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001710 }
1711 }
1712 assert(narenas == narenas_currently_allocated);
Tim Peters7ccfadf2002-04-01 06:04:21 +00001713
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001714 fputc('\n', stderr);
1715 fputs("class size num pools blocks in use avail blocks\n"
1716 "----- ---- --------- ------------- ------------\n",
Stefan Krah5d744a82010-11-26 11:07:04 +00001717 stderr);
Tim Peters7ccfadf2002-04-01 06:04:21 +00001718
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001719 for (i = 0; i < numclasses; ++i) {
1720 size_t p = numpools[i];
1721 size_t b = numblocks[i];
1722 size_t f = numfreeblocks[i];
1723 uint size = INDEX2SIZE(i);
1724 if (p == 0) {
1725 assert(b == 0 && f == 0);
1726 continue;
1727 }
1728 fprintf(stderr, "%5u %6u "
1729 "%11" PY_FORMAT_SIZE_T "u "
1730 "%15" PY_FORMAT_SIZE_T "u "
1731 "%13" PY_FORMAT_SIZE_T "u\n",
Stefan Krah5d744a82010-11-26 11:07:04 +00001732 i, size, p, b, f);
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001733 allocated_bytes += b * size;
1734 available_bytes += f * size;
1735 pool_header_bytes += p * POOL_OVERHEAD;
1736 quantization += p * ((POOL_SIZE - POOL_OVERHEAD) % size);
1737 }
1738 fputc('\n', stderr);
1739 (void)printone("# times object malloc called", serialno);
Tim Peters16bcb6b2002-04-05 05:45:31 +00001740
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001741 (void)printone("# arenas allocated total", ntimes_arena_allocated);
1742 (void)printone("# arenas reclaimed", ntimes_arena_allocated - narenas);
1743 (void)printone("# arenas highwater mark", narenas_highwater);
1744 (void)printone("# arenas allocated current", narenas);
Thomas Woutersa9773292006-04-21 09:43:23 +00001745
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001746 PyOS_snprintf(buf, sizeof(buf),
1747 "%" PY_FORMAT_SIZE_T "u arenas * %d bytes/arena",
1748 narenas, ARENA_SIZE);
1749 (void)printone(buf, narenas * ARENA_SIZE);
Tim Peters16bcb6b2002-04-05 05:45:31 +00001750
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001751 fputc('\n', stderr);
Tim Peters16bcb6b2002-04-05 05:45:31 +00001752
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001753 total = printone("# bytes in allocated blocks", allocated_bytes);
1754 total += printone("# bytes in available blocks", available_bytes);
Tim Peters49f26812002-04-06 01:45:35 +00001755
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001756 PyOS_snprintf(buf, sizeof(buf),
1757 "%u unused pools * %d bytes", numfreepools, POOL_SIZE);
1758 total += printone(buf, (size_t)numfreepools * POOL_SIZE);
Tim Peters16bcb6b2002-04-05 05:45:31 +00001759
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001760 total += printone("# bytes lost to pool headers", pool_header_bytes);
1761 total += printone("# bytes lost to quantization", quantization);
1762 total += printone("# bytes lost to arena alignment", arena_alignment);
1763 (void)printone("Total", total);
Tim Peters7ccfadf2002-04-01 06:04:21 +00001764}
1765
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001766#endif /* PYMALLOC_DEBUG */
Neal Norwitz7eb3c912004-06-06 19:20:22 +00001767
1768#ifdef Py_USING_MEMORY_DEBUGGER
Thomas Woutersa9773292006-04-21 09:43:23 +00001769/* Make this function last so gcc won't inline it since the definition is
1770 * after the reference.
1771 */
Neal Norwitz7eb3c912004-06-06 19:20:22 +00001772int
1773Py_ADDRESS_IN_RANGE(void *P, poolp pool)
1774{
Antoine Pitrou5b6fc632011-01-07 21:49:25 +00001775 uint arenaindex_temp = pool->arenaindex;
1776
1777 return arenaindex_temp < maxarenas &&
1778 (uptr)P - arenas[arenaindex_temp].address < (uptr)ARENA_SIZE &&
1779 arenas[arenaindex_temp].address != 0;
Neal Norwitz7eb3c912004-06-06 19:20:22 +00001780}
1781#endif