blob: f7b3e491ca468001039cbcd9f57433f920fae683 [file] [log] [blame]
Tim Peters1221c0a2002-03-23 00:20:15 +00001#include "Python.h"
2
Victor Stinner0507bf52013-07-07 02:05:46 +02003/* Python's malloc wrappers (see pymem.h) */
4
5#ifdef PYMALLOC_DEBUG /* WITH_PYMALLOC && PYMALLOC_DEBUG */
6/* Forward declaration */
7static void* _PyMem_DebugMalloc(void *ctx, size_t size);
8static void _PyMem_DebugFree(void *ctx, void *p);
9static void* _PyMem_DebugRealloc(void *ctx, void *ptr, size_t size);
10
11static void _PyObject_DebugDumpAddress(const void *p);
12static void _PyMem_DebugCheckAddress(char api_id, const void *p);
13#endif
14
Nick Coghlan6ba64f42013-09-29 00:28:55 +100015#if defined(__has_feature) /* Clang */
16 #if __has_feature(address_sanitizer) /* is ASAN enabled? */
17 #define ATTRIBUTE_NO_ADDRESS_SAFETY_ANALYSIS \
18 __attribute__((no_address_safety_analysis)) \
19 __attribute__ ((noinline))
20 #else
21 #define ATTRIBUTE_NO_ADDRESS_SAFETY_ANALYSIS
22 #endif
23#else
24 #if defined(__SANITIZE_ADDRESS__) /* GCC 4.8.x, is ASAN enabled? */
25 #define ATTRIBUTE_NO_ADDRESS_SAFETY_ANALYSIS \
26 __attribute__((no_address_safety_analysis)) \
27 __attribute__ ((noinline))
28 #else
29 #define ATTRIBUTE_NO_ADDRESS_SAFETY_ANALYSIS
30 #endif
31#endif
32
Tim Peters1221c0a2002-03-23 00:20:15 +000033#ifdef WITH_PYMALLOC
34
Victor Stinner0507bf52013-07-07 02:05:46 +020035#ifdef MS_WINDOWS
36# include <windows.h>
37#elif defined(HAVE_MMAP)
38# include <sys/mman.h>
39# ifdef MAP_ANONYMOUS
40# define ARENAS_USE_MMAP
41# endif
Antoine Pitrou6f26be02011-05-03 18:18:59 +020042#endif
43
Victor Stinner0507bf52013-07-07 02:05:46 +020044/* Forward declaration */
45static void* _PyObject_Malloc(void *ctx, size_t size);
46static void _PyObject_Free(void *ctx, void *p);
47static void* _PyObject_Realloc(void *ctx, void *ptr, size_t size);
Martin v. Löwiscd83fa82013-06-27 12:23:29 +020048#endif
49
Victor Stinner0507bf52013-07-07 02:05:46 +020050
51static void *
52_PyMem_RawMalloc(void *ctx, size_t size)
53{
54 /* PyMem_Malloc(0) means malloc(1). Some systems would return NULL
55 for malloc(0), which would be treated as an error. Some platforms would
56 return a pointer with no memory behind it, which would break pymalloc.
57 To solve these problems, allocate an extra byte. */
58 if (size == 0)
59 size = 1;
60 return malloc(size);
61}
62
63static void *
64_PyMem_RawRealloc(void *ctx, void *ptr, size_t size)
65{
66 if (size == 0)
67 size = 1;
68 return realloc(ptr, size);
69}
70
71static void
72_PyMem_RawFree(void *ctx, void *ptr)
73{
74 free(ptr);
75}
76
77
78#ifdef MS_WINDOWS
79static void *
80_PyObject_ArenaVirtualAlloc(void *ctx, size_t size)
81{
82 return VirtualAlloc(NULL, size,
83 MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
84}
85
86static void
87_PyObject_ArenaVirtualFree(void *ctx, void *ptr, size_t size)
88{
Victor Stinner725e6682013-07-07 03:06:16 +020089 VirtualFree(ptr, 0, MEM_RELEASE);
Victor Stinner0507bf52013-07-07 02:05:46 +020090}
91
92#elif defined(ARENAS_USE_MMAP)
93static void *
94_PyObject_ArenaMmap(void *ctx, size_t size)
95{
96 void *ptr;
97 ptr = mmap(NULL, size, PROT_READ|PROT_WRITE,
98 MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
99 if (ptr == MAP_FAILED)
100 return NULL;
101 assert(ptr != NULL);
102 return ptr;
103}
104
105static void
106_PyObject_ArenaMunmap(void *ctx, void *ptr, size_t size)
107{
108 munmap(ptr, size);
109}
110
111#else
112static void *
113_PyObject_ArenaMalloc(void *ctx, size_t size)
114{
115 return malloc(size);
116}
117
118static void
119_PyObject_ArenaFree(void *ctx, void *ptr, size_t size)
120{
121 free(ptr);
122}
123#endif
124
125
126#define PYRAW_FUNCS _PyMem_RawMalloc, _PyMem_RawRealloc, _PyMem_RawFree
127#ifdef WITH_PYMALLOC
128#define PYOBJECT_FUNCS _PyObject_Malloc, _PyObject_Realloc, _PyObject_Free
129#else
130#define PYOBJECT_FUNCS PYRAW_FUNCS
131#endif
132
133#ifdef PYMALLOC_DEBUG
134typedef struct {
135 /* We tag each block with an API ID in order to tag API violations */
136 char api_id;
137 PyMemAllocator alloc;
138} debug_alloc_api_t;
139static struct {
140 debug_alloc_api_t raw;
141 debug_alloc_api_t mem;
142 debug_alloc_api_t obj;
143} _PyMem_Debug = {
144 {'r', {NULL, PYRAW_FUNCS}},
145 {'m', {NULL, PYRAW_FUNCS}},
146 {'o', {NULL, PYOBJECT_FUNCS}}
147 };
148
149#define PYDEBUG_FUNCS _PyMem_DebugMalloc, _PyMem_DebugRealloc, _PyMem_DebugFree
150#endif
151
152static PyMemAllocator _PyMem_Raw = {
153#ifdef PYMALLOC_DEBUG
154 &_PyMem_Debug.raw, PYDEBUG_FUNCS
155#else
156 NULL, PYRAW_FUNCS
157#endif
158 };
159
160static PyMemAllocator _PyMem = {
161#ifdef PYMALLOC_DEBUG
162 &_PyMem_Debug.mem, PYDEBUG_FUNCS
163#else
164 NULL, PYRAW_FUNCS
165#endif
166 };
167
168static PyMemAllocator _PyObject = {
169#ifdef PYMALLOC_DEBUG
170 &_PyMem_Debug.obj, PYDEBUG_FUNCS
171#else
172 NULL, PYOBJECT_FUNCS
173#endif
174 };
175
176#undef PYRAW_FUNCS
177#undef PYOBJECT_FUNCS
178#undef PYDEBUG_FUNCS
179
180static PyObjectArenaAllocator _PyObject_Arena = {NULL,
181#ifdef MS_WINDOWS
182 _PyObject_ArenaVirtualAlloc, _PyObject_ArenaVirtualFree
183#elif defined(ARENAS_USE_MMAP)
184 _PyObject_ArenaMmap, _PyObject_ArenaMunmap
185#else
186 _PyObject_ArenaMalloc, _PyObject_ArenaFree
187#endif
188 };
189
190void
191PyMem_SetupDebugHooks(void)
192{
193#ifdef PYMALLOC_DEBUG
194 PyMemAllocator alloc;
195
196 alloc.malloc = _PyMem_DebugMalloc;
197 alloc.realloc = _PyMem_DebugRealloc;
198 alloc.free = _PyMem_DebugFree;
199
200 if (_PyMem_Raw.malloc != _PyMem_DebugMalloc) {
201 alloc.ctx = &_PyMem_Debug.raw;
202 PyMem_GetAllocator(PYMEM_DOMAIN_RAW, &_PyMem_Debug.raw.alloc);
203 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &alloc);
204 }
205
206 if (_PyMem.malloc != _PyMem_DebugMalloc) {
207 alloc.ctx = &_PyMem_Debug.mem;
208 PyMem_GetAllocator(PYMEM_DOMAIN_MEM, &_PyMem_Debug.mem.alloc);
209 PyMem_SetAllocator(PYMEM_DOMAIN_MEM, &alloc);
210 }
211
212 if (_PyObject.malloc != _PyMem_DebugMalloc) {
213 alloc.ctx = &_PyMem_Debug.obj;
214 PyMem_GetAllocator(PYMEM_DOMAIN_OBJ, &_PyMem_Debug.obj.alloc);
215 PyMem_SetAllocator(PYMEM_DOMAIN_OBJ, &alloc);
216 }
217#endif
218}
219
220void
221PyMem_GetAllocator(PyMemAllocatorDomain domain, PyMemAllocator *allocator)
222{
223 switch(domain)
224 {
225 case PYMEM_DOMAIN_RAW: *allocator = _PyMem_Raw; break;
226 case PYMEM_DOMAIN_MEM: *allocator = _PyMem; break;
227 case PYMEM_DOMAIN_OBJ: *allocator = _PyObject; break;
228 default:
229 /* unknown domain */
230 allocator->ctx = NULL;
231 allocator->malloc = NULL;
232 allocator->realloc = NULL;
233 allocator->free = NULL;
234 }
235}
236
237void
238PyMem_SetAllocator(PyMemAllocatorDomain domain, PyMemAllocator *allocator)
239{
240 switch(domain)
241 {
242 case PYMEM_DOMAIN_RAW: _PyMem_Raw = *allocator; break;
243 case PYMEM_DOMAIN_MEM: _PyMem = *allocator; break;
244 case PYMEM_DOMAIN_OBJ: _PyObject = *allocator; break;
245 /* ignore unknown domain */
246 }
247
248}
249
250void
251PyObject_GetArenaAllocator(PyObjectArenaAllocator *allocator)
252{
253 *allocator = _PyObject_Arena;
254}
255
256void
257PyObject_SetArenaAllocator(PyObjectArenaAllocator *allocator)
258{
259 _PyObject_Arena = *allocator;
260}
261
262void *
263PyMem_RawMalloc(size_t size)
264{
265 /*
266 * Limit ourselves to PY_SSIZE_T_MAX bytes to prevent security holes.
267 * Most python internals blindly use a signed Py_ssize_t to track
268 * things without checking for overflows or negatives.
269 * As size_t is unsigned, checking for size < 0 is not required.
270 */
271 if (size > (size_t)PY_SSIZE_T_MAX)
272 return NULL;
273
274 return _PyMem_Raw.malloc(_PyMem_Raw.ctx, size);
275}
276
277void*
278PyMem_RawRealloc(void *ptr, size_t new_size)
279{
280 /* see PyMem_RawMalloc() */
281 if (new_size > (size_t)PY_SSIZE_T_MAX)
282 return NULL;
283 return _PyMem_Raw.realloc(_PyMem_Raw.ctx, ptr, new_size);
284}
285
286void PyMem_RawFree(void *ptr)
287{
288 _PyMem_Raw.free(_PyMem_Raw.ctx, ptr);
289}
290
291void *
292PyMem_Malloc(size_t size)
293{
294 /* see PyMem_RawMalloc() */
295 if (size > (size_t)PY_SSIZE_T_MAX)
296 return NULL;
297 return _PyMem.malloc(_PyMem.ctx, size);
298}
299
300void *
301PyMem_Realloc(void *ptr, size_t new_size)
302{
303 /* see PyMem_RawMalloc() */
304 if (new_size > (size_t)PY_SSIZE_T_MAX)
305 return NULL;
306 return _PyMem.realloc(_PyMem.ctx, ptr, new_size);
307}
308
309void
310PyMem_Free(void *ptr)
311{
312 _PyMem.free(_PyMem.ctx, ptr);
313}
314
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200315char *
316_PyMem_RawStrdup(const char *str)
317{
318 size_t size;
319 char *copy;
320
321 size = strlen(str) + 1;
322 copy = PyMem_RawMalloc(size);
323 if (copy == NULL)
324 return NULL;
325 memcpy(copy, str, size);
326 return copy;
327}
328
329char *
330_PyMem_Strdup(const char *str)
331{
332 size_t size;
333 char *copy;
334
335 size = strlen(str) + 1;
336 copy = PyMem_Malloc(size);
337 if (copy == NULL)
338 return NULL;
339 memcpy(copy, str, size);
340 return copy;
341}
342
Victor Stinner0507bf52013-07-07 02:05:46 +0200343void *
344PyObject_Malloc(size_t size)
345{
346 /* see PyMem_RawMalloc() */
347 if (size > (size_t)PY_SSIZE_T_MAX)
348 return NULL;
349 return _PyObject.malloc(_PyObject.ctx, size);
350}
351
352void *
353PyObject_Realloc(void *ptr, size_t new_size)
354{
355 /* see PyMem_RawMalloc() */
356 if (new_size > (size_t)PY_SSIZE_T_MAX)
357 return NULL;
358 return _PyObject.realloc(_PyObject.ctx, ptr, new_size);
359}
360
361void
362PyObject_Free(void *ptr)
363{
364 _PyObject.free(_PyObject.ctx, ptr);
365}
366
367
368#ifdef WITH_PYMALLOC
369
Benjamin Peterson05159c42009-12-03 03:01:27 +0000370#ifdef WITH_VALGRIND
371#include <valgrind/valgrind.h>
372
373/* If we're using GCC, use __builtin_expect() to reduce overhead of
374 the valgrind checks */
375#if defined(__GNUC__) && (__GNUC__ > 2) && defined(__OPTIMIZE__)
376# define UNLIKELY(value) __builtin_expect((value), 0)
377#else
378# define UNLIKELY(value) (value)
379#endif
380
381/* -1 indicates that we haven't checked that we're running on valgrind yet. */
382static int running_on_valgrind = -1;
383#endif
384
Neil Schemenauera35c6882001-02-27 04:45:05 +0000385/* An object allocator for Python.
386
387 Here is an introduction to the layers of the Python memory architecture,
388 showing where the object allocator is actually used (layer +2), It is
389 called for every object allocation and deallocation (PyObject_New/Del),
390 unless the object-specific allocators implement a proprietary allocation
391 scheme (ex.: ints use a simple free list). This is also the place where
392 the cyclic garbage collector operates selectively on container objects.
393
394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000395 Object-specific allocators
Neil Schemenauera35c6882001-02-27 04:45:05 +0000396 _____ ______ ______ ________
397 [ int ] [ dict ] [ list ] ... [ string ] Python core |
398+3 | <----- Object-specific memory -----> | <-- Non-object memory --> |
399 _______________________________ | |
400 [ Python's object allocator ] | |
401+2 | ####### Object memory ####### | <------ Internal buffers ------> |
402 ______________________________________________________________ |
403 [ Python's raw memory allocator (PyMem_ API) ] |
404+1 | <----- Python memory (under PyMem manager's control) ------> | |
405 __________________________________________________________________
406 [ Underlying general-purpose allocator (ex: C library malloc) ]
407 0 | <------ Virtual memory allocated for the python process -------> |
408
409 =========================================================================
410 _______________________________________________________________________
411 [ OS-specific Virtual Memory Manager (VMM) ]
412-1 | <--- Kernel dynamic storage allocation & management (page-based) ---> |
413 __________________________________ __________________________________
414 [ ] [ ]
415-2 | <-- Physical memory: ROM/RAM --> | | <-- Secondary storage (swap) --> |
416
417*/
418/*==========================================================================*/
419
420/* A fast, special-purpose memory allocator for small blocks, to be used
421 on top of a general-purpose malloc -- heavily based on previous art. */
422
423/* Vladimir Marangozov -- August 2000 */
424
425/*
426 * "Memory management is where the rubber meets the road -- if we do the wrong
427 * thing at any level, the results will not be good. And if we don't make the
428 * levels work well together, we are in serious trouble." (1)
429 *
430 * (1) Paul R. Wilson, Mark S. Johnstone, Michael Neely, and David Boles,
431 * "Dynamic Storage Allocation: A Survey and Critical Review",
432 * in Proc. 1995 Int'l. Workshop on Memory Management, September 1995.
433 */
434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000435/* #undef WITH_MEMORY_LIMITS */ /* disable mem limit checks */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000436
437/*==========================================================================*/
438
439/*
Neil Schemenauera35c6882001-02-27 04:45:05 +0000440 * Allocation strategy abstract:
441 *
442 * For small requests, the allocator sub-allocates <Big> blocks of memory.
Antoine Pitrou6f26be02011-05-03 18:18:59 +0200443 * Requests greater than SMALL_REQUEST_THRESHOLD bytes are routed to the
444 * system's allocator.
Tim Petersce7fb9b2002-03-23 00:28:57 +0000445 *
Neil Schemenauera35c6882001-02-27 04:45:05 +0000446 * Small requests are grouped in size classes spaced 8 bytes apart, due
447 * to the required valid alignment of the returned address. Requests of
448 * a particular size are serviced from memory pools of 4K (one VMM page).
449 * Pools are fragmented on demand and contain free lists of blocks of one
450 * particular size class. In other words, there is a fixed-size allocator
451 * for each size class. Free pools are shared by the different allocators
452 * thus minimizing the space reserved for a particular size class.
453 *
454 * This allocation strategy is a variant of what is known as "simple
455 * segregated storage based on array of free lists". The main drawback of
456 * simple segregated storage is that we might end up with lot of reserved
457 * memory for the different free lists, which degenerate in time. To avoid
458 * this, we partition each free list in pools and we share dynamically the
459 * reserved space between all free lists. This technique is quite efficient
460 * for memory intensive programs which allocate mainly small-sized blocks.
461 *
462 * For small requests we have the following table:
463 *
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000464 * Request in bytes Size of allocated block Size class idx
Neil Schemenauera35c6882001-02-27 04:45:05 +0000465 * ----------------------------------------------------------------
466 * 1-8 8 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000467 * 9-16 16 1
468 * 17-24 24 2
469 * 25-32 32 3
470 * 33-40 40 4
471 * 41-48 48 5
472 * 49-56 56 6
473 * 57-64 64 7
474 * 65-72 72 8
475 * ... ... ...
Antoine Pitrou6f26be02011-05-03 18:18:59 +0200476 * 497-504 504 62
477 * 505-512 512 63
Tim Petersce7fb9b2002-03-23 00:28:57 +0000478 *
Antoine Pitrou6f26be02011-05-03 18:18:59 +0200479 * 0, SMALL_REQUEST_THRESHOLD + 1 and up: routed to the underlying
480 * allocator.
Neil Schemenauera35c6882001-02-27 04:45:05 +0000481 */
482
483/*==========================================================================*/
484
485/*
486 * -- Main tunable settings section --
487 */
488
489/*
490 * Alignment of addresses returned to the user. 8-bytes alignment works
491 * on most current architectures (with 32-bit or 64-bit address busses).
492 * The alignment value is also used for grouping small requests in size
493 * classes spaced ALIGNMENT bytes apart.
494 *
495 * You shouldn't change this unless you know what you are doing.
496 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497#define ALIGNMENT 8 /* must be 2^N */
498#define ALIGNMENT_SHIFT 3
Neil Schemenauera35c6882001-02-27 04:45:05 +0000499
Tim Peterse70ddf32002-04-05 04:32:29 +0000500/* Return the number of bytes in size class I, as a uint. */
501#define INDEX2SIZE(I) (((uint)(I) + 1) << ALIGNMENT_SHIFT)
502
Neil Schemenauera35c6882001-02-27 04:45:05 +0000503/*
504 * Max size threshold below which malloc requests are considered to be
505 * small enough in order to use preallocated memory pools. You can tune
506 * this value according to your application behaviour and memory needs.
507 *
Antoine Pitrou6f26be02011-05-03 18:18:59 +0200508 * Note: a size threshold of 512 guarantees that newly created dictionaries
509 * will be allocated from preallocated memory pools on 64-bit.
510 *
Neil Schemenauera35c6882001-02-27 04:45:05 +0000511 * The following invariants must hold:
Antoine Pitrou6f26be02011-05-03 18:18:59 +0200512 * 1) ALIGNMENT <= SMALL_REQUEST_THRESHOLD <= 512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000513 * 2) SMALL_REQUEST_THRESHOLD is evenly divisible by ALIGNMENT
Neil Schemenauera35c6882001-02-27 04:45:05 +0000514 *
515 * Although not required, for better performance and space efficiency,
516 * it is recommended that SMALL_REQUEST_THRESHOLD is set to a power of 2.
517 */
Antoine Pitrou6f26be02011-05-03 18:18:59 +0200518#define SMALL_REQUEST_THRESHOLD 512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519#define NB_SMALL_SIZE_CLASSES (SMALL_REQUEST_THRESHOLD / ALIGNMENT)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000520
521/*
522 * The system's VMM page size can be obtained on most unices with a
523 * getpagesize() call or deduced from various header files. To make
524 * things simpler, we assume that it is 4K, which is OK for most systems.
525 * It is probably better if this is the native page size, but it doesn't
Tim Petersecc6e6a2005-07-10 22:30:55 +0000526 * have to be. In theory, if SYSTEM_PAGE_SIZE is larger than the native page
527 * size, then `POOL_ADDR(p)->arenaindex' could rarely cause a segmentation
528 * violation fault. 4K is apparently OK for all the platforms that python
Martin v. Löwis8c140282002-10-26 15:01:53 +0000529 * currently targets.
Neil Schemenauera35c6882001-02-27 04:45:05 +0000530 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000531#define SYSTEM_PAGE_SIZE (4 * 1024)
532#define SYSTEM_PAGE_SIZE_MASK (SYSTEM_PAGE_SIZE - 1)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000533
534/*
535 * Maximum amount of memory managed by the allocator for small requests.
536 */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000537#ifdef WITH_MEMORY_LIMITS
538#ifndef SMALL_MEMORY_LIMIT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000539#define SMALL_MEMORY_LIMIT (64 * 1024 * 1024) /* 64 MB -- more? */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000540#endif
541#endif
542
543/*
544 * The allocator sub-allocates <Big> blocks of memory (called arenas) aligned
545 * on a page boundary. This is a reserved virtual address space for the
Antoine Pitrouf0effe62011-11-26 01:11:02 +0100546 * current process (obtained through a malloc()/mmap() call). In no way this
547 * means that the memory arenas will be used entirely. A malloc(<Big>) is
548 * usually an address range reservation for <Big> bytes, unless all pages within
549 * this space are referenced subsequently. So malloc'ing big blocks and not
550 * using them does not mean "wasting memory". It's an addressable range
551 * wastage...
Neil Schemenauera35c6882001-02-27 04:45:05 +0000552 *
Antoine Pitrouf0effe62011-11-26 01:11:02 +0100553 * Arenas are allocated with mmap() on systems supporting anonymous memory
554 * mappings to reduce heap fragmentation.
Neil Schemenauera35c6882001-02-27 04:45:05 +0000555 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000556#define ARENA_SIZE (256 << 10) /* 256KB */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000557
558#ifdef WITH_MEMORY_LIMITS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559#define MAX_ARENAS (SMALL_MEMORY_LIMIT / ARENA_SIZE)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000560#endif
561
562/*
563 * Size of the pools used for small blocks. Should be a power of 2,
Tim Petersc2ce91a2002-03-30 21:36:04 +0000564 * between 1K and SYSTEM_PAGE_SIZE, that is: 1k, 2k, 4k.
Neil Schemenauera35c6882001-02-27 04:45:05 +0000565 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000566#define POOL_SIZE SYSTEM_PAGE_SIZE /* must be 2^N */
567#define POOL_SIZE_MASK SYSTEM_PAGE_SIZE_MASK
Neil Schemenauera35c6882001-02-27 04:45:05 +0000568
569/*
570 * -- End of tunable settings section --
571 */
572
573/*==========================================================================*/
574
575/*
576 * Locking
577 *
578 * To reduce lock contention, it would probably be better to refine the
579 * crude function locking with per size class locking. I'm not positive
580 * however, whether it's worth switching to such locking policy because
581 * of the performance penalty it might introduce.
582 *
583 * The following macros describe the simplest (should also be the fastest)
584 * lock object on a particular platform and the init/fini/lock/unlock
585 * operations on it. The locks defined here are not expected to be recursive
586 * because it is assumed that they will always be called in the order:
587 * INIT, [LOCK, UNLOCK]*, FINI.
588 */
589
590/*
591 * Python's threads are serialized, so object malloc locking is disabled.
592 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000593#define SIMPLELOCK_DECL(lock) /* simple lock declaration */
594#define SIMPLELOCK_INIT(lock) /* allocate (if needed) and initialize */
595#define SIMPLELOCK_FINI(lock) /* free/destroy an existing lock */
596#define SIMPLELOCK_LOCK(lock) /* acquire released lock */
597#define SIMPLELOCK_UNLOCK(lock) /* release acquired lock */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000598
599/*
600 * Basic types
601 * I don't care if these are defined in <sys/types.h> or elsewhere. Axiom.
602 */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000603#undef uchar
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000604#define uchar unsigned char /* assuming == 8 bits */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000605
Neil Schemenauera35c6882001-02-27 04:45:05 +0000606#undef uint
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000607#define uint unsigned int /* assuming >= 16 bits */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000608
609#undef ulong
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000610#define ulong unsigned long /* assuming >= 32 bits */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000611
Tim Petersd97a1c02002-03-30 06:09:22 +0000612#undef uptr
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000613#define uptr Py_uintptr_t
Tim Petersd97a1c02002-03-30 06:09:22 +0000614
Neil Schemenauera35c6882001-02-27 04:45:05 +0000615/* When you say memory, my mind reasons in terms of (pointers to) blocks */
616typedef uchar block;
617
Tim Peterse70ddf32002-04-05 04:32:29 +0000618/* Pool for small blocks. */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000619struct pool_header {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000620 union { block *_padding;
Stefan Krah735bb122010-11-26 10:54:09 +0000621 uint count; } ref; /* number of allocated blocks */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 block *freeblock; /* pool's free list head */
623 struct pool_header *nextpool; /* next pool of this size class */
624 struct pool_header *prevpool; /* previous pool "" */
625 uint arenaindex; /* index into arenas of base adr */
626 uint szidx; /* block size class index */
627 uint nextoffset; /* bytes to virgin block */
628 uint maxnextoffset; /* largest valid nextoffset */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000629};
630
631typedef struct pool_header *poolp;
632
Thomas Woutersa9773292006-04-21 09:43:23 +0000633/* Record keeping for arenas. */
634struct arena_object {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000635 /* The address of the arena, as returned by malloc. Note that 0
636 * will never be returned by a successful malloc, and is used
637 * here to mark an arena_object that doesn't correspond to an
638 * allocated arena.
639 */
640 uptr address;
Thomas Woutersa9773292006-04-21 09:43:23 +0000641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 /* Pool-aligned pointer to the next pool to be carved off. */
643 block* pool_address;
Thomas Woutersa9773292006-04-21 09:43:23 +0000644
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000645 /* The number of available pools in the arena: free pools + never-
646 * allocated pools.
647 */
648 uint nfreepools;
Thomas Woutersa9773292006-04-21 09:43:23 +0000649
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650 /* The total number of pools in the arena, whether or not available. */
651 uint ntotalpools;
Thomas Woutersa9773292006-04-21 09:43:23 +0000652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000653 /* Singly-linked list of available pools. */
654 struct pool_header* freepools;
Thomas Woutersa9773292006-04-21 09:43:23 +0000655
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000656 /* Whenever this arena_object is not associated with an allocated
657 * arena, the nextarena member is used to link all unassociated
658 * arena_objects in the singly-linked `unused_arena_objects` list.
659 * The prevarena member is unused in this case.
660 *
661 * When this arena_object is associated with an allocated arena
662 * with at least one available pool, both members are used in the
663 * doubly-linked `usable_arenas` list, which is maintained in
664 * increasing order of `nfreepools` values.
665 *
666 * Else this arena_object is associated with an allocated arena
667 * all of whose pools are in use. `nextarena` and `prevarena`
668 * are both meaningless in this case.
669 */
670 struct arena_object* nextarena;
671 struct arena_object* prevarena;
Thomas Woutersa9773292006-04-21 09:43:23 +0000672};
673
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +0200674#define POOL_OVERHEAD _Py_SIZE_ROUND_UP(sizeof(struct pool_header), ALIGNMENT)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000675
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676#define DUMMY_SIZE_IDX 0xffff /* size class of newly cached pools */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000677
Tim Petersd97a1c02002-03-30 06:09:22 +0000678/* Round pointer P down to the closest pool-aligned address <= P, as a poolp */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +0200679#define POOL_ADDR(P) ((poolp)_Py_ALIGN_DOWN((P), POOL_SIZE))
Tim Peterse70ddf32002-04-05 04:32:29 +0000680
Tim Peters16bcb6b2002-04-05 05:45:31 +0000681/* Return total number of blocks in pool of size index I, as a uint. */
682#define NUMBLOCKS(I) ((uint)(POOL_SIZE - POOL_OVERHEAD) / INDEX2SIZE(I))
Tim Petersd97a1c02002-03-30 06:09:22 +0000683
Neil Schemenauera35c6882001-02-27 04:45:05 +0000684/*==========================================================================*/
685
686/*
687 * This malloc lock
688 */
Jeremy Hyltond1fedb62002-07-18 18:49:52 +0000689SIMPLELOCK_DECL(_malloc_lock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000690#define LOCK() SIMPLELOCK_LOCK(_malloc_lock)
691#define UNLOCK() SIMPLELOCK_UNLOCK(_malloc_lock)
692#define LOCK_INIT() SIMPLELOCK_INIT(_malloc_lock)
693#define LOCK_FINI() SIMPLELOCK_FINI(_malloc_lock)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000694
695/*
Tim Peters1e16db62002-03-31 01:05:22 +0000696 * Pool table -- headed, circular, doubly-linked lists of partially used pools.
697
698This is involved. For an index i, usedpools[i+i] is the header for a list of
699all partially used pools holding small blocks with "size class idx" i. So
700usedpools[0] corresponds to blocks of size 8, usedpools[2] to blocks of size
70116, and so on: index 2*i <-> blocks of size (i+1)<<ALIGNMENT_SHIFT.
702
Thomas Woutersa9773292006-04-21 09:43:23 +0000703Pools are carved off an arena's highwater mark (an arena_object's pool_address
704member) as needed. Once carved off, a pool is in one of three states forever
705after:
Tim Peters1e16db62002-03-31 01:05:22 +0000706
Tim Peters338e0102002-04-01 19:23:44 +0000707used == partially used, neither empty nor full
708 At least one block in the pool is currently allocated, and at least one
709 block in the pool is not currently allocated (note this implies a pool
710 has room for at least two blocks).
711 This is a pool's initial state, as a pool is created only when malloc
712 needs space.
713 The pool holds blocks of a fixed size, and is in the circular list headed
714 at usedpools[i] (see above). It's linked to the other used pools of the
715 same size class via the pool_header's nextpool and prevpool members.
716 If all but one block is currently allocated, a malloc can cause a
717 transition to the full state. If all but one block is not currently
718 allocated, a free can cause a transition to the empty state.
Tim Peters1e16db62002-03-31 01:05:22 +0000719
Tim Peters338e0102002-04-01 19:23:44 +0000720full == all the pool's blocks are currently allocated
721 On transition to full, a pool is unlinked from its usedpools[] list.
722 It's not linked to from anything then anymore, and its nextpool and
723 prevpool members are meaningless until it transitions back to used.
724 A free of a block in a full pool puts the pool back in the used state.
725 Then it's linked in at the front of the appropriate usedpools[] list, so
726 that the next allocation for its size class will reuse the freed block.
727
728empty == all the pool's blocks are currently available for allocation
729 On transition to empty, a pool is unlinked from its usedpools[] list,
Thomas Woutersa9773292006-04-21 09:43:23 +0000730 and linked to the front of its arena_object's singly-linked freepools list,
Tim Peters338e0102002-04-01 19:23:44 +0000731 via its nextpool member. The prevpool member has no meaning in this case.
732 Empty pools have no inherent size class: the next time a malloc finds
733 an empty list in usedpools[], it takes the first pool off of freepools.
734 If the size class needed happens to be the same as the size class the pool
Tim Peterse70ddf32002-04-05 04:32:29 +0000735 last had, some pool initialization can be skipped.
Tim Peters338e0102002-04-01 19:23:44 +0000736
737
738Block Management
739
740Blocks within pools are again carved out as needed. pool->freeblock points to
741the start of a singly-linked list of free blocks within the pool. When a
742block is freed, it's inserted at the front of its pool's freeblock list. Note
743that the available blocks in a pool are *not* linked all together when a pool
Tim Peterse70ddf32002-04-05 04:32:29 +0000744is initialized. Instead only "the first two" (lowest addresses) blocks are
745set up, returning the first such block, and setting pool->freeblock to a
746one-block list holding the second such block. This is consistent with that
747pymalloc strives at all levels (arena, pool, and block) never to touch a piece
748of memory until it's actually needed.
749
750So long as a pool is in the used state, we're certain there *is* a block
Tim Peters52aefc82002-04-11 06:36:45 +0000751available for allocating, and pool->freeblock is not NULL. If pool->freeblock
752points to the end of the free list before we've carved the entire pool into
753blocks, that means we simply haven't yet gotten to one of the higher-address
754blocks. The offset from the pool_header to the start of "the next" virgin
755block is stored in the pool_header nextoffset member, and the largest value
756of nextoffset that makes sense is stored in the maxnextoffset member when a
757pool is initialized. All the blocks in a pool have been passed out at least
758once when and only when nextoffset > maxnextoffset.
Tim Peters338e0102002-04-01 19:23:44 +0000759
Tim Peters1e16db62002-03-31 01:05:22 +0000760
761Major obscurity: While the usedpools vector is declared to have poolp
762entries, it doesn't really. It really contains two pointers per (conceptual)
763poolp entry, the nextpool and prevpool members of a pool_header. The
764excruciating initialization code below fools C so that
765
766 usedpool[i+i]
767
768"acts like" a genuine poolp, but only so long as you only reference its
769nextpool and prevpool members. The "- 2*sizeof(block *)" gibberish is
770compensating for that a pool_header's nextpool and prevpool members
771immediately follow a pool_header's first two members:
772
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000773 union { block *_padding;
Stefan Krah735bb122010-11-26 10:54:09 +0000774 uint count; } ref;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000775 block *freeblock;
Tim Peters1e16db62002-03-31 01:05:22 +0000776
777each of which consume sizeof(block *) bytes. So what usedpools[i+i] really
778contains is a fudged-up pointer p such that *if* C believes it's a poolp
779pointer, then p->nextpool and p->prevpool are both p (meaning that the headed
780circular list is empty).
781
782It's unclear why the usedpools setup is so convoluted. It could be to
783minimize the amount of cache required to hold this heavily-referenced table
784(which only *needs* the two interpool pointer members of a pool_header). OTOH,
785referencing code has to remember to "double the index" and doing so isn't
786free, usedpools[0] isn't a strictly legal pointer, and we're crucially relying
787on that C doesn't insert any padding anywhere in a pool_header at or before
788the prevpool member.
789**************************************************************************** */
790
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000791#define PTA(x) ((poolp )((uchar *)&(usedpools[2*(x)]) - 2*sizeof(block *)))
792#define PT(x) PTA(x), PTA(x)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000793
794static poolp usedpools[2 * ((NB_SMALL_SIZE_CLASSES + 7) / 8) * 8] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000795 PT(0), PT(1), PT(2), PT(3), PT(4), PT(5), PT(6), PT(7)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000796#if NB_SMALL_SIZE_CLASSES > 8
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000797 , PT(8), PT(9), PT(10), PT(11), PT(12), PT(13), PT(14), PT(15)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000798#if NB_SMALL_SIZE_CLASSES > 16
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000799 , PT(16), PT(17), PT(18), PT(19), PT(20), PT(21), PT(22), PT(23)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000800#if NB_SMALL_SIZE_CLASSES > 24
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000801 , PT(24), PT(25), PT(26), PT(27), PT(28), PT(29), PT(30), PT(31)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000802#if NB_SMALL_SIZE_CLASSES > 32
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 , PT(32), PT(33), PT(34), PT(35), PT(36), PT(37), PT(38), PT(39)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000804#if NB_SMALL_SIZE_CLASSES > 40
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000805 , PT(40), PT(41), PT(42), PT(43), PT(44), PT(45), PT(46), PT(47)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000806#if NB_SMALL_SIZE_CLASSES > 48
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000807 , PT(48), PT(49), PT(50), PT(51), PT(52), PT(53), PT(54), PT(55)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000808#if NB_SMALL_SIZE_CLASSES > 56
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000809 , PT(56), PT(57), PT(58), PT(59), PT(60), PT(61), PT(62), PT(63)
Antoine Pitrou6f26be02011-05-03 18:18:59 +0200810#if NB_SMALL_SIZE_CLASSES > 64
811#error "NB_SMALL_SIZE_CLASSES should be less than 64"
812#endif /* NB_SMALL_SIZE_CLASSES > 64 */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000813#endif /* NB_SMALL_SIZE_CLASSES > 56 */
814#endif /* NB_SMALL_SIZE_CLASSES > 48 */
815#endif /* NB_SMALL_SIZE_CLASSES > 40 */
816#endif /* NB_SMALL_SIZE_CLASSES > 32 */
817#endif /* NB_SMALL_SIZE_CLASSES > 24 */
818#endif /* NB_SMALL_SIZE_CLASSES > 16 */
819#endif /* NB_SMALL_SIZE_CLASSES > 8 */
820};
821
Thomas Woutersa9773292006-04-21 09:43:23 +0000822/*==========================================================================
823Arena management.
Neil Schemenauera35c6882001-02-27 04:45:05 +0000824
Thomas Woutersa9773292006-04-21 09:43:23 +0000825`arenas` is a vector of arena_objects. It contains maxarenas entries, some of
826which may not be currently used (== they're arena_objects that aren't
827currently associated with an allocated arena). Note that arenas proper are
828separately malloc'ed.
Neil Schemenauera35c6882001-02-27 04:45:05 +0000829
Thomas Woutersa9773292006-04-21 09:43:23 +0000830Prior to Python 2.5, arenas were never free()'ed. Starting with Python 2.5,
831we do try to free() arenas, and use some mild heuristic strategies to increase
832the likelihood that arenas eventually can be freed.
833
834unused_arena_objects
835
836 This is a singly-linked list of the arena_objects that are currently not
837 being used (no arena is associated with them). Objects are taken off the
838 head of the list in new_arena(), and are pushed on the head of the list in
839 PyObject_Free() when the arena is empty. Key invariant: an arena_object
840 is on this list if and only if its .address member is 0.
841
842usable_arenas
843
844 This is a doubly-linked list of the arena_objects associated with arenas
845 that have pools available. These pools are either waiting to be reused,
846 or have not been used before. The list is sorted to have the most-
847 allocated arenas first (ascending order based on the nfreepools member).
848 This means that the next allocation will come from a heavily used arena,
849 which gives the nearly empty arenas a chance to be returned to the system.
850 In my unscientific tests this dramatically improved the number of arenas
851 that could be freed.
852
853Note that an arena_object associated with an arena all of whose pools are
854currently in use isn't on either list.
855*/
856
857/* Array of objects used to track chunks of memory (arenas). */
858static struct arena_object* arenas = NULL;
859/* Number of slots currently allocated in the `arenas` vector. */
Tim Peters1d99af82002-03-30 10:35:09 +0000860static uint maxarenas = 0;
Tim Petersd97a1c02002-03-30 06:09:22 +0000861
Thomas Woutersa9773292006-04-21 09:43:23 +0000862/* The head of the singly-linked, NULL-terminated list of available
863 * arena_objects.
Tim Petersd97a1c02002-03-30 06:09:22 +0000864 */
Thomas Woutersa9773292006-04-21 09:43:23 +0000865static struct arena_object* unused_arena_objects = NULL;
866
867/* The head of the doubly-linked, NULL-terminated at each end, list of
868 * arena_objects associated with arenas that have pools available.
869 */
870static struct arena_object* usable_arenas = NULL;
871
872/* How many arena_objects do we initially allocate?
873 * 16 = can allocate 16 arenas = 16 * ARENA_SIZE = 4MB before growing the
874 * `arenas` vector.
875 */
876#define INITIAL_ARENA_OBJECTS 16
877
878/* Number of arenas allocated that haven't been free()'d. */
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000879static size_t narenas_currently_allocated = 0;
Thomas Woutersa9773292006-04-21 09:43:23 +0000880
Thomas Woutersa9773292006-04-21 09:43:23 +0000881/* Total number of times malloc() called to allocate an arena. */
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000882static size_t ntimes_arena_allocated = 0;
Thomas Woutersa9773292006-04-21 09:43:23 +0000883/* High water mark (max value ever seen) for narenas_currently_allocated. */
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000884static size_t narenas_highwater = 0;
Thomas Woutersa9773292006-04-21 09:43:23 +0000885
Antoine Pitrouf9d0b122012-12-09 14:28:26 +0100886static Py_ssize_t _Py_AllocatedBlocks = 0;
887
888Py_ssize_t
889_Py_GetAllocatedBlocks(void)
890{
891 return _Py_AllocatedBlocks;
892}
893
894
Thomas Woutersa9773292006-04-21 09:43:23 +0000895/* Allocate a new arena. If we run out of memory, return NULL. Else
896 * allocate a new arena, and return the address of an arena_object
897 * describing the new arena. It's expected that the caller will set
898 * `usable_arenas` to the return value.
899 */
900static struct arena_object*
Tim Petersd97a1c02002-03-30 06:09:22 +0000901new_arena(void)
902{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000903 struct arena_object* arenaobj;
904 uint excess; /* number of bytes above pool alignment */
Victor Stinnerba108822012-03-10 00:21:44 +0100905 void *address;
Tim Petersd97a1c02002-03-30 06:09:22 +0000906
Tim Peters0e871182002-04-13 08:29:14 +0000907#ifdef PYMALLOC_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000908 if (Py_GETENV("PYTHONMALLOCSTATS"))
David Malcolm49526f42012-06-22 14:55:41 -0400909 _PyObject_DebugMallocStats(stderr);
Tim Peters0e871182002-04-13 08:29:14 +0000910#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000911 if (unused_arena_objects == NULL) {
912 uint i;
913 uint numarenas;
914 size_t nbytes;
Tim Peters0e871182002-04-13 08:29:14 +0000915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 /* Double the number of arena objects on each allocation.
917 * Note that it's possible for `numarenas` to overflow.
918 */
919 numarenas = maxarenas ? maxarenas << 1 : INITIAL_ARENA_OBJECTS;
920 if (numarenas <= maxarenas)
921 return NULL; /* overflow */
Martin v. Löwis5aca8822008-09-11 06:55:48 +0000922#if SIZEOF_SIZE_T <= SIZEOF_INT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000923 if (numarenas > PY_SIZE_MAX / sizeof(*arenas))
924 return NULL; /* overflow */
Martin v. Löwis5aca8822008-09-11 06:55:48 +0000925#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 nbytes = numarenas * sizeof(*arenas);
Victor Stinner0507bf52013-07-07 02:05:46 +0200927 arenaobj = (struct arena_object *)PyMem_Realloc(arenas, nbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 if (arenaobj == NULL)
929 return NULL;
930 arenas = arenaobj;
Thomas Woutersa9773292006-04-21 09:43:23 +0000931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 /* We might need to fix pointers that were copied. However,
933 * new_arena only gets called when all the pages in the
934 * previous arenas are full. Thus, there are *no* pointers
935 * into the old array. Thus, we don't have to worry about
936 * invalid pointers. Just to be sure, some asserts:
937 */
938 assert(usable_arenas == NULL);
939 assert(unused_arena_objects == NULL);
Thomas Woutersa9773292006-04-21 09:43:23 +0000940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 /* Put the new arenas on the unused_arena_objects list. */
942 for (i = maxarenas; i < numarenas; ++i) {
943 arenas[i].address = 0; /* mark as unassociated */
944 arenas[i].nextarena = i < numarenas - 1 ?
945 &arenas[i+1] : NULL;
946 }
Thomas Woutersa9773292006-04-21 09:43:23 +0000947
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000948 /* Update globals. */
949 unused_arena_objects = &arenas[maxarenas];
950 maxarenas = numarenas;
951 }
Tim Petersd97a1c02002-03-30 06:09:22 +0000952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 /* Take the next available arena object off the head of the list. */
954 assert(unused_arena_objects != NULL);
955 arenaobj = unused_arena_objects;
956 unused_arena_objects = arenaobj->nextarena;
957 assert(arenaobj->address == 0);
Victor Stinner0507bf52013-07-07 02:05:46 +0200958 address = _PyObject_Arena.alloc(_PyObject_Arena.ctx, ARENA_SIZE);
959 if (address == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 /* The allocation failed: return NULL after putting the
961 * arenaobj back.
962 */
963 arenaobj->nextarena = unused_arena_objects;
964 unused_arena_objects = arenaobj;
965 return NULL;
966 }
Victor Stinnerba108822012-03-10 00:21:44 +0100967 arenaobj->address = (uptr)address;
Tim Petersd97a1c02002-03-30 06:09:22 +0000968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 ++narenas_currently_allocated;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000970 ++ntimes_arena_allocated;
971 if (narenas_currently_allocated > narenas_highwater)
972 narenas_highwater = narenas_currently_allocated;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000973 arenaobj->freepools = NULL;
974 /* pool_address <- first pool-aligned address in the arena
975 nfreepools <- number of whole pools that fit after alignment */
976 arenaobj->pool_address = (block*)arenaobj->address;
977 arenaobj->nfreepools = ARENA_SIZE / POOL_SIZE;
978 assert(POOL_SIZE * arenaobj->nfreepools == ARENA_SIZE);
979 excess = (uint)(arenaobj->address & POOL_SIZE_MASK);
980 if (excess != 0) {
981 --arenaobj->nfreepools;
982 arenaobj->pool_address += POOL_SIZE - excess;
983 }
984 arenaobj->ntotalpools = arenaobj->nfreepools;
Thomas Woutersa9773292006-04-21 09:43:23 +0000985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 return arenaobj;
Tim Petersd97a1c02002-03-30 06:09:22 +0000987}
988
Thomas Woutersa9773292006-04-21 09:43:23 +0000989/*
990Py_ADDRESS_IN_RANGE(P, POOL)
991
992Return true if and only if P is an address that was allocated by pymalloc.
993POOL must be the pool address associated with P, i.e., POOL = POOL_ADDR(P)
994(the caller is asked to compute this because the macro expands POOL more than
995once, and for efficiency it's best for the caller to assign POOL_ADDR(P) to a
996variable and pass the latter to the macro; because Py_ADDRESS_IN_RANGE is
997called on every alloc/realloc/free, micro-efficiency is important here).
998
999Tricky: Let B be the arena base address associated with the pool, B =
1000arenas[(POOL)->arenaindex].address. Then P belongs to the arena if and only if
1001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 B <= P < B + ARENA_SIZE
Thomas Woutersa9773292006-04-21 09:43:23 +00001003
1004Subtracting B throughout, this is true iff
1005
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001006 0 <= P-B < ARENA_SIZE
Thomas Woutersa9773292006-04-21 09:43:23 +00001007
1008By using unsigned arithmetic, the "0 <=" half of the test can be skipped.
1009
1010Obscure: A PyMem "free memory" function can call the pymalloc free or realloc
1011before the first arena has been allocated. `arenas` is still NULL in that
1012case. We're relying on that maxarenas is also 0 in that case, so that
1013(POOL)->arenaindex < maxarenas must be false, saving us from trying to index
1014into a NULL arenas.
1015
1016Details: given P and POOL, the arena_object corresponding to P is AO =
1017arenas[(POOL)->arenaindex]. Suppose obmalloc controls P. Then (barring wild
1018stores, etc), POOL is the correct address of P's pool, AO.address is the
1019correct base address of the pool's arena, and P must be within ARENA_SIZE of
1020AO.address. In addition, AO.address is not 0 (no arena can start at address 0
1021(NULL)). Therefore Py_ADDRESS_IN_RANGE correctly reports that obmalloc
1022controls P.
1023
1024Now suppose obmalloc does not control P (e.g., P was obtained via a direct
1025call to the system malloc() or realloc()). (POOL)->arenaindex may be anything
1026in this case -- it may even be uninitialized trash. If the trash arenaindex
1027is >= maxarenas, the macro correctly concludes at once that obmalloc doesn't
1028control P.
1029
1030Else arenaindex is < maxarena, and AO is read up. If AO corresponds to an
1031allocated arena, obmalloc controls all the memory in slice AO.address :
1032AO.address+ARENA_SIZE. By case assumption, P is not controlled by obmalloc,
1033so P doesn't lie in that slice, so the macro correctly reports that P is not
1034controlled by obmalloc.
1035
1036Finally, if P is not controlled by obmalloc and AO corresponds to an unused
1037arena_object (one not currently associated with an allocated arena),
1038AO.address is 0, and the second test in the macro reduces to:
1039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 P < ARENA_SIZE
Thomas Woutersa9773292006-04-21 09:43:23 +00001041
1042If P >= ARENA_SIZE (extremely likely), the macro again correctly concludes
1043that P is not controlled by obmalloc. However, if P < ARENA_SIZE, this part
1044of the test still passes, and the third clause (AO.address != 0) is necessary
1045to get the correct result: AO.address is 0 in this case, so the macro
1046correctly reports that P is not controlled by obmalloc (despite that P lies in
1047slice AO.address : AO.address + ARENA_SIZE).
1048
1049Note: The third (AO.address != 0) clause was added in Python 2.5. Before
10502.5, arenas were never free()'ed, and an arenaindex < maxarena always
1051corresponded to a currently-allocated arena, so the "P is not controlled by
1052obmalloc, AO corresponds to an unused arena_object, and P < ARENA_SIZE" case
1053was impossible.
1054
1055Note that the logic is excruciating, and reading up possibly uninitialized
1056memory when P is not controlled by obmalloc (to get at (POOL)->arenaindex)
1057creates problems for some memory debuggers. The overwhelming advantage is
1058that this test determines whether an arbitrary address is controlled by
1059obmalloc in a small constant time, independent of the number of arenas
1060obmalloc controls. Since this test is needed at every entry point, it's
1061extremely desirable that it be this fast.
Antoine Pitroub7fb2e22011-01-07 21:43:59 +00001062
1063Since Py_ADDRESS_IN_RANGE may be reading from memory which was not allocated
1064by Python, it is important that (POOL)->arenaindex is read only once, as
1065another thread may be concurrently modifying the value without holding the
1066GIL. To accomplish this, the arenaindex_temp variable is used to store
1067(POOL)->arenaindex for the duration of the Py_ADDRESS_IN_RANGE macro's
1068execution. The caller of the macro is responsible for declaring this
1069variable.
Thomas Woutersa9773292006-04-21 09:43:23 +00001070*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071#define Py_ADDRESS_IN_RANGE(P, POOL) \
Antoine Pitroub7fb2e22011-01-07 21:43:59 +00001072 ((arenaindex_temp = (POOL)->arenaindex) < maxarenas && \
1073 (uptr)(P) - arenas[arenaindex_temp].address < (uptr)ARENA_SIZE && \
1074 arenas[arenaindex_temp].address != 0)
Thomas Woutersa9773292006-04-21 09:43:23 +00001075
Neal Norwitz7eb3c912004-06-06 19:20:22 +00001076
1077/* This is only useful when running memory debuggers such as
1078 * Purify or Valgrind. Uncomment to use.
1079 *
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001080#define Py_USING_MEMORY_DEBUGGER
Martin v. Löwis6fea2332008-09-25 04:15:27 +00001081 */
Neal Norwitz7eb3c912004-06-06 19:20:22 +00001082
1083#ifdef Py_USING_MEMORY_DEBUGGER
1084
1085/* Py_ADDRESS_IN_RANGE may access uninitialized memory by design
1086 * This leads to thousands of spurious warnings when using
1087 * Purify or Valgrind. By making a function, we can easily
1088 * suppress the uninitialized memory reads in this one function.
1089 * So we won't ignore real errors elsewhere.
1090 *
1091 * Disable the macro and use a function.
1092 */
1093
1094#undef Py_ADDRESS_IN_RANGE
1095
Thomas Wouters89f507f2006-12-13 04:49:30 +00001096#if defined(__GNUC__) && ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 1) || \
Stefan Krah735bb122010-11-26 10:54:09 +00001097 (__GNUC__ >= 4))
Neal Norwitze5e5aa42005-11-13 18:55:39 +00001098#define Py_NO_INLINE __attribute__((__noinline__))
1099#else
1100#define Py_NO_INLINE
1101#endif
1102
1103/* Don't make static, to try to ensure this isn't inlined. */
1104int Py_ADDRESS_IN_RANGE(void *P, poolp pool) Py_NO_INLINE;
1105#undef Py_NO_INLINE
Neal Norwitz7eb3c912004-06-06 19:20:22 +00001106#endif
Tim Peters338e0102002-04-01 19:23:44 +00001107
Neil Schemenauera35c6882001-02-27 04:45:05 +00001108/*==========================================================================*/
1109
Tim Peters84c1b972002-04-04 04:44:32 +00001110/* malloc. Note that nbytes==0 tries to return a non-NULL pointer, distinct
1111 * from all other currently live pointers. This may not be possible.
1112 */
Neil Schemenauera35c6882001-02-27 04:45:05 +00001113
1114/*
1115 * The basic blocks are ordered by decreasing execution frequency,
1116 * which minimizes the number of jumps in the most common cases,
1117 * improves branching prediction and instruction scheduling (small
1118 * block allocations typically result in a couple of instructions).
1119 * Unless the optimizer reorders everything, being too smart...
1120 */
1121
Victor Stinner0507bf52013-07-07 02:05:46 +02001122static void *
1123_PyObject_Malloc(void *ctx, size_t nbytes)
Neil Schemenauera35c6882001-02-27 04:45:05 +00001124{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001125 block *bp;
1126 poolp pool;
1127 poolp next;
1128 uint size;
Neil Schemenauera35c6882001-02-27 04:45:05 +00001129
Antoine Pitrou0aaaa622013-04-06 01:15:30 +02001130 _Py_AllocatedBlocks++;
1131
Benjamin Peterson05159c42009-12-03 03:01:27 +00001132#ifdef WITH_VALGRIND
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001133 if (UNLIKELY(running_on_valgrind == -1))
1134 running_on_valgrind = RUNNING_ON_VALGRIND;
1135 if (UNLIKELY(running_on_valgrind))
1136 goto redirect;
Benjamin Peterson05159c42009-12-03 03:01:27 +00001137#endif
1138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001139 /*
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001140 * This implicitly redirects malloc(0).
1141 */
1142 if ((nbytes - 1) < SMALL_REQUEST_THRESHOLD) {
1143 LOCK();
1144 /*
1145 * Most frequent paths first
1146 */
1147 size = (uint)(nbytes - 1) >> ALIGNMENT_SHIFT;
1148 pool = usedpools[size + size];
1149 if (pool != pool->nextpool) {
1150 /*
1151 * There is a used pool for this size class.
1152 * Pick up the head block of its free list.
1153 */
1154 ++pool->ref.count;
1155 bp = pool->freeblock;
1156 assert(bp != NULL);
1157 if ((pool->freeblock = *(block **)bp) != NULL) {
1158 UNLOCK();
1159 return (void *)bp;
1160 }
1161 /*
1162 * Reached the end of the free list, try to extend it.
1163 */
1164 if (pool->nextoffset <= pool->maxnextoffset) {
1165 /* There is room for another block. */
1166 pool->freeblock = (block*)pool +
1167 pool->nextoffset;
1168 pool->nextoffset += INDEX2SIZE(size);
1169 *(block **)(pool->freeblock) = NULL;
1170 UNLOCK();
1171 return (void *)bp;
1172 }
1173 /* Pool is full, unlink from used pools. */
1174 next = pool->nextpool;
1175 pool = pool->prevpool;
1176 next->prevpool = pool;
1177 pool->nextpool = next;
1178 UNLOCK();
1179 return (void *)bp;
1180 }
Thomas Woutersa9773292006-04-21 09:43:23 +00001181
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 /* There isn't a pool of the right size class immediately
1183 * available: use a free pool.
1184 */
1185 if (usable_arenas == NULL) {
1186 /* No arena has a free pool: allocate a new arena. */
Thomas Woutersa9773292006-04-21 09:43:23 +00001187#ifdef WITH_MEMORY_LIMITS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 if (narenas_currently_allocated >= MAX_ARENAS) {
1189 UNLOCK();
1190 goto redirect;
1191 }
Thomas Woutersa9773292006-04-21 09:43:23 +00001192#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001193 usable_arenas = new_arena();
1194 if (usable_arenas == NULL) {
1195 UNLOCK();
1196 goto redirect;
1197 }
1198 usable_arenas->nextarena =
1199 usable_arenas->prevarena = NULL;
1200 }
1201 assert(usable_arenas->address != 0);
Thomas Woutersa9773292006-04-21 09:43:23 +00001202
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001203 /* Try to get a cached free pool. */
1204 pool = usable_arenas->freepools;
1205 if (pool != NULL) {
1206 /* Unlink from cached pools. */
1207 usable_arenas->freepools = pool->nextpool;
Thomas Woutersa9773292006-04-21 09:43:23 +00001208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001209 /* This arena already had the smallest nfreepools
1210 * value, so decreasing nfreepools doesn't change
1211 * that, and we don't need to rearrange the
1212 * usable_arenas list. However, if the arena has
1213 * become wholly allocated, we need to remove its
1214 * arena_object from usable_arenas.
1215 */
1216 --usable_arenas->nfreepools;
1217 if (usable_arenas->nfreepools == 0) {
1218 /* Wholly allocated: remove. */
1219 assert(usable_arenas->freepools == NULL);
1220 assert(usable_arenas->nextarena == NULL ||
1221 usable_arenas->nextarena->prevarena ==
1222 usable_arenas);
Thomas Woutersa9773292006-04-21 09:43:23 +00001223
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001224 usable_arenas = usable_arenas->nextarena;
1225 if (usable_arenas != NULL) {
1226 usable_arenas->prevarena = NULL;
1227 assert(usable_arenas->address != 0);
1228 }
1229 }
1230 else {
1231 /* nfreepools > 0: it must be that freepools
1232 * isn't NULL, or that we haven't yet carved
1233 * off all the arena's pools for the first
1234 * time.
1235 */
1236 assert(usable_arenas->freepools != NULL ||
1237 usable_arenas->pool_address <=
1238 (block*)usable_arenas->address +
1239 ARENA_SIZE - POOL_SIZE);
1240 }
1241 init_pool:
1242 /* Frontlink to used pools. */
1243 next = usedpools[size + size]; /* == prev */
1244 pool->nextpool = next;
1245 pool->prevpool = next;
1246 next->nextpool = pool;
1247 next->prevpool = pool;
1248 pool->ref.count = 1;
1249 if (pool->szidx == size) {
1250 /* Luckily, this pool last contained blocks
1251 * of the same size class, so its header
1252 * and free list are already initialized.
1253 */
1254 bp = pool->freeblock;
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001255 assert(bp != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001256 pool->freeblock = *(block **)bp;
1257 UNLOCK();
1258 return (void *)bp;
1259 }
1260 /*
1261 * Initialize the pool header, set up the free list to
1262 * contain just the second block, and return the first
1263 * block.
1264 */
1265 pool->szidx = size;
1266 size = INDEX2SIZE(size);
1267 bp = (block *)pool + POOL_OVERHEAD;
1268 pool->nextoffset = POOL_OVERHEAD + (size << 1);
1269 pool->maxnextoffset = POOL_SIZE - size;
1270 pool->freeblock = bp + size;
1271 *(block **)(pool->freeblock) = NULL;
1272 UNLOCK();
1273 return (void *)bp;
1274 }
Thomas Woutersa9773292006-04-21 09:43:23 +00001275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001276 /* Carve off a new pool. */
1277 assert(usable_arenas->nfreepools > 0);
1278 assert(usable_arenas->freepools == NULL);
1279 pool = (poolp)usable_arenas->pool_address;
1280 assert((block*)pool <= (block*)usable_arenas->address +
1281 ARENA_SIZE - POOL_SIZE);
1282 pool->arenaindex = usable_arenas - arenas;
1283 assert(&arenas[pool->arenaindex] == usable_arenas);
1284 pool->szidx = DUMMY_SIZE_IDX;
1285 usable_arenas->pool_address += POOL_SIZE;
1286 --usable_arenas->nfreepools;
Thomas Woutersa9773292006-04-21 09:43:23 +00001287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001288 if (usable_arenas->nfreepools == 0) {
1289 assert(usable_arenas->nextarena == NULL ||
1290 usable_arenas->nextarena->prevarena ==
1291 usable_arenas);
1292 /* Unlink the arena: it is completely allocated. */
1293 usable_arenas = usable_arenas->nextarena;
1294 if (usable_arenas != NULL) {
1295 usable_arenas->prevarena = NULL;
1296 assert(usable_arenas->address != 0);
1297 }
1298 }
Thomas Woutersa9773292006-04-21 09:43:23 +00001299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001300 goto init_pool;
1301 }
Neil Schemenauera35c6882001-02-27 04:45:05 +00001302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001303 /* The small block allocator ends here. */
Neil Schemenauera35c6882001-02-27 04:45:05 +00001304
Tim Petersd97a1c02002-03-30 06:09:22 +00001305redirect:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001306 /* Redirect the original request to the underlying (libc) allocator.
1307 * We jump here on bigger requests, on error in the code above (as a
1308 * last chance to serve the request) or when the max memory limit
1309 * has been reached.
1310 */
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001311 {
Victor Stinner0507bf52013-07-07 02:05:46 +02001312 void *result = PyMem_Malloc(nbytes);
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001313 if (!result)
1314 _Py_AllocatedBlocks--;
1315 return result;
1316 }
Neil Schemenauera35c6882001-02-27 04:45:05 +00001317}
1318
1319/* free */
1320
Nick Coghlan6ba64f42013-09-29 00:28:55 +10001321ATTRIBUTE_NO_ADDRESS_SAFETY_ANALYSIS
Victor Stinner0507bf52013-07-07 02:05:46 +02001322static void
1323_PyObject_Free(void *ctx, void *p)
Neil Schemenauera35c6882001-02-27 04:45:05 +00001324{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001325 poolp pool;
1326 block *lastfree;
1327 poolp next, prev;
1328 uint size;
Antoine Pitroub7fb2e22011-01-07 21:43:59 +00001329#ifndef Py_USING_MEMORY_DEBUGGER
1330 uint arenaindex_temp;
1331#endif
Neil Schemenauera35c6882001-02-27 04:45:05 +00001332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001333 if (p == NULL) /* free(NULL) has no effect */
1334 return;
Neil Schemenauera35c6882001-02-27 04:45:05 +00001335
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001336 _Py_AllocatedBlocks--;
1337
Benjamin Peterson05159c42009-12-03 03:01:27 +00001338#ifdef WITH_VALGRIND
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001339 if (UNLIKELY(running_on_valgrind > 0))
1340 goto redirect;
Benjamin Peterson05159c42009-12-03 03:01:27 +00001341#endif
1342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001343 pool = POOL_ADDR(p);
1344 if (Py_ADDRESS_IN_RANGE(p, pool)) {
1345 /* We allocated this address. */
1346 LOCK();
1347 /* Link p to the start of the pool's freeblock list. Since
1348 * the pool had at least the p block outstanding, the pool
1349 * wasn't empty (so it's already in a usedpools[] list, or
1350 * was full and is in no list -- it's not in the freeblocks
1351 * list in any case).
1352 */
1353 assert(pool->ref.count > 0); /* else it was empty */
1354 *(block **)p = lastfree = pool->freeblock;
1355 pool->freeblock = (block *)p;
1356 if (lastfree) {
1357 struct arena_object* ao;
1358 uint nf; /* ao->nfreepools */
Thomas Woutersa9773292006-04-21 09:43:23 +00001359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001360 /* freeblock wasn't NULL, so the pool wasn't full,
1361 * and the pool is in a usedpools[] list.
1362 */
1363 if (--pool->ref.count != 0) {
1364 /* pool isn't empty: leave it in usedpools */
1365 UNLOCK();
1366 return;
1367 }
1368 /* Pool is now empty: unlink from usedpools, and
1369 * link to the front of freepools. This ensures that
1370 * previously freed pools will be allocated later
1371 * (being not referenced, they are perhaps paged out).
1372 */
1373 next = pool->nextpool;
1374 prev = pool->prevpool;
1375 next->prevpool = prev;
1376 prev->nextpool = next;
Thomas Woutersa9773292006-04-21 09:43:23 +00001377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001378 /* Link the pool to freepools. This is a singly-linked
1379 * list, and pool->prevpool isn't used there.
1380 */
1381 ao = &arenas[pool->arenaindex];
1382 pool->nextpool = ao->freepools;
1383 ao->freepools = pool;
1384 nf = ++ao->nfreepools;
Thomas Woutersa9773292006-04-21 09:43:23 +00001385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001386 /* All the rest is arena management. We just freed
1387 * a pool, and there are 4 cases for arena mgmt:
1388 * 1. If all the pools are free, return the arena to
1389 * the system free().
1390 * 2. If this is the only free pool in the arena,
1391 * add the arena back to the `usable_arenas` list.
1392 * 3. If the "next" arena has a smaller count of free
1393 * pools, we have to "slide this arena right" to
1394 * restore that usable_arenas is sorted in order of
1395 * nfreepools.
1396 * 4. Else there's nothing more to do.
1397 */
1398 if (nf == ao->ntotalpools) {
1399 /* Case 1. First unlink ao from usable_arenas.
1400 */
1401 assert(ao->prevarena == NULL ||
1402 ao->prevarena->address != 0);
1403 assert(ao ->nextarena == NULL ||
1404 ao->nextarena->address != 0);
Thomas Woutersa9773292006-04-21 09:43:23 +00001405
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001406 /* Fix the pointer in the prevarena, or the
1407 * usable_arenas pointer.
1408 */
1409 if (ao->prevarena == NULL) {
1410 usable_arenas = ao->nextarena;
1411 assert(usable_arenas == NULL ||
1412 usable_arenas->address != 0);
1413 }
1414 else {
1415 assert(ao->prevarena->nextarena == ao);
1416 ao->prevarena->nextarena =
1417 ao->nextarena;
1418 }
1419 /* Fix the pointer in the nextarena. */
1420 if (ao->nextarena != NULL) {
1421 assert(ao->nextarena->prevarena == ao);
1422 ao->nextarena->prevarena =
1423 ao->prevarena;
1424 }
1425 /* Record that this arena_object slot is
1426 * available to be reused.
1427 */
1428 ao->nextarena = unused_arena_objects;
1429 unused_arena_objects = ao;
Thomas Woutersa9773292006-04-21 09:43:23 +00001430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001431 /* Free the entire arena. */
Victor Stinner0507bf52013-07-07 02:05:46 +02001432 _PyObject_Arena.free(_PyObject_Arena.ctx,
1433 (void *)ao->address, ARENA_SIZE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001434 ao->address = 0; /* mark unassociated */
1435 --narenas_currently_allocated;
Thomas Woutersa9773292006-04-21 09:43:23 +00001436
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001437 UNLOCK();
1438 return;
1439 }
1440 if (nf == 1) {
1441 /* Case 2. Put ao at the head of
1442 * usable_arenas. Note that because
1443 * ao->nfreepools was 0 before, ao isn't
1444 * currently on the usable_arenas list.
1445 */
1446 ao->nextarena = usable_arenas;
1447 ao->prevarena = NULL;
1448 if (usable_arenas)
1449 usable_arenas->prevarena = ao;
1450 usable_arenas = ao;
1451 assert(usable_arenas->address != 0);
Thomas Woutersa9773292006-04-21 09:43:23 +00001452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001453 UNLOCK();
1454 return;
1455 }
1456 /* If this arena is now out of order, we need to keep
1457 * the list sorted. The list is kept sorted so that
1458 * the "most full" arenas are used first, which allows
1459 * the nearly empty arenas to be completely freed. In
1460 * a few un-scientific tests, it seems like this
1461 * approach allowed a lot more memory to be freed.
1462 */
1463 if (ao->nextarena == NULL ||
1464 nf <= ao->nextarena->nfreepools) {
1465 /* Case 4. Nothing to do. */
1466 UNLOCK();
1467 return;
1468 }
1469 /* Case 3: We have to move the arena towards the end
1470 * of the list, because it has more free pools than
1471 * the arena to its right.
1472 * First unlink ao from usable_arenas.
1473 */
1474 if (ao->prevarena != NULL) {
1475 /* ao isn't at the head of the list */
1476 assert(ao->prevarena->nextarena == ao);
1477 ao->prevarena->nextarena = ao->nextarena;
1478 }
1479 else {
1480 /* ao is at the head of the list */
1481 assert(usable_arenas == ao);
1482 usable_arenas = ao->nextarena;
1483 }
1484 ao->nextarena->prevarena = ao->prevarena;
Thomas Woutersa9773292006-04-21 09:43:23 +00001485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001486 /* Locate the new insertion point by iterating over
1487 * the list, using our nextarena pointer.
1488 */
1489 while (ao->nextarena != NULL &&
1490 nf > ao->nextarena->nfreepools) {
1491 ao->prevarena = ao->nextarena;
1492 ao->nextarena = ao->nextarena->nextarena;
1493 }
Thomas Woutersa9773292006-04-21 09:43:23 +00001494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001495 /* Insert ao at this point. */
1496 assert(ao->nextarena == NULL ||
1497 ao->prevarena == ao->nextarena->prevarena);
1498 assert(ao->prevarena->nextarena == ao->nextarena);
Thomas Woutersa9773292006-04-21 09:43:23 +00001499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001500 ao->prevarena->nextarena = ao;
1501 if (ao->nextarena != NULL)
1502 ao->nextarena->prevarena = ao;
Thomas Woutersa9773292006-04-21 09:43:23 +00001503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001504 /* Verify that the swaps worked. */
1505 assert(ao->nextarena == NULL ||
1506 nf <= ao->nextarena->nfreepools);
1507 assert(ao->prevarena == NULL ||
1508 nf > ao->prevarena->nfreepools);
1509 assert(ao->nextarena == NULL ||
1510 ao->nextarena->prevarena == ao);
1511 assert((usable_arenas == ao &&
1512 ao->prevarena == NULL) ||
1513 ao->prevarena->nextarena == ao);
Thomas Woutersa9773292006-04-21 09:43:23 +00001514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001515 UNLOCK();
1516 return;
1517 }
1518 /* Pool was full, so doesn't currently live in any list:
1519 * link it to the front of the appropriate usedpools[] list.
1520 * This mimics LRU pool usage for new allocations and
1521 * targets optimal filling when several pools contain
1522 * blocks of the same size class.
1523 */
1524 --pool->ref.count;
1525 assert(pool->ref.count > 0); /* else the pool is empty */
1526 size = pool->szidx;
1527 next = usedpools[size + size];
1528 prev = next->prevpool;
1529 /* insert pool before next: prev <-> pool <-> next */
1530 pool->nextpool = next;
1531 pool->prevpool = prev;
1532 next->prevpool = pool;
1533 prev->nextpool = pool;
1534 UNLOCK();
1535 return;
1536 }
Neil Schemenauera35c6882001-02-27 04:45:05 +00001537
Benjamin Peterson05159c42009-12-03 03:01:27 +00001538#ifdef WITH_VALGRIND
1539redirect:
1540#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001541 /* We didn't allocate this address. */
Victor Stinner0507bf52013-07-07 02:05:46 +02001542 PyMem_Free(p);
Neil Schemenauera35c6882001-02-27 04:45:05 +00001543}
1544
Tim Peters84c1b972002-04-04 04:44:32 +00001545/* realloc. If p is NULL, this acts like malloc(nbytes). Else if nbytes==0,
1546 * then as the Python docs promise, we do not treat this like free(p), and
1547 * return a non-NULL result.
1548 */
Neil Schemenauera35c6882001-02-27 04:45:05 +00001549
Nick Coghlan6ba64f42013-09-29 00:28:55 +10001550ATTRIBUTE_NO_ADDRESS_SAFETY_ANALYSIS
Victor Stinner0507bf52013-07-07 02:05:46 +02001551static void *
1552_PyObject_Realloc(void *ctx, void *p, size_t nbytes)
Neil Schemenauera35c6882001-02-27 04:45:05 +00001553{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001554 void *bp;
1555 poolp pool;
1556 size_t size;
Antoine Pitroub7fb2e22011-01-07 21:43:59 +00001557#ifndef Py_USING_MEMORY_DEBUGGER
1558 uint arenaindex_temp;
1559#endif
Neil Schemenauera35c6882001-02-27 04:45:05 +00001560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001561 if (p == NULL)
Victor Stinner0507bf52013-07-07 02:05:46 +02001562 return _PyObject_Malloc(ctx, nbytes);
Georg Brandld492ad82008-07-23 16:13:07 +00001563
Benjamin Peterson05159c42009-12-03 03:01:27 +00001564#ifdef WITH_VALGRIND
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001565 /* Treat running_on_valgrind == -1 the same as 0 */
1566 if (UNLIKELY(running_on_valgrind > 0))
1567 goto redirect;
Benjamin Peterson05159c42009-12-03 03:01:27 +00001568#endif
1569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001570 pool = POOL_ADDR(p);
1571 if (Py_ADDRESS_IN_RANGE(p, pool)) {
1572 /* We're in charge of this block */
1573 size = INDEX2SIZE(pool->szidx);
1574 if (nbytes <= size) {
1575 /* The block is staying the same or shrinking. If
1576 * it's shrinking, there's a tradeoff: it costs
1577 * cycles to copy the block to a smaller size class,
1578 * but it wastes memory not to copy it. The
1579 * compromise here is to copy on shrink only if at
1580 * least 25% of size can be shaved off.
1581 */
1582 if (4 * nbytes > 3 * size) {
1583 /* It's the same,
1584 * or shrinking and new/old > 3/4.
1585 */
1586 return p;
1587 }
1588 size = nbytes;
1589 }
Victor Stinner0507bf52013-07-07 02:05:46 +02001590 bp = _PyObject_Malloc(ctx, nbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001591 if (bp != NULL) {
1592 memcpy(bp, p, size);
Victor Stinner0507bf52013-07-07 02:05:46 +02001593 _PyObject_Free(ctx, p);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001594 }
1595 return bp;
1596 }
Benjamin Peterson05159c42009-12-03 03:01:27 +00001597#ifdef WITH_VALGRIND
1598 redirect:
1599#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001600 /* We're not managing this block. If nbytes <=
1601 * SMALL_REQUEST_THRESHOLD, it's tempting to try to take over this
1602 * block. However, if we do, we need to copy the valid data from
1603 * the C-managed block to one of our blocks, and there's no portable
1604 * way to know how much of the memory space starting at p is valid.
1605 * As bug 1185883 pointed out the hard way, it's possible that the
1606 * C-managed block is "at the end" of allocated VM space, so that
1607 * a memory fault can occur if we try to copy nbytes bytes starting
1608 * at p. Instead we punt: let C continue to manage this block.
1609 */
1610 if (nbytes)
Victor Stinner0507bf52013-07-07 02:05:46 +02001611 return PyMem_Realloc(p, nbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001612 /* C doesn't define the result of realloc(p, 0) (it may or may not
1613 * return NULL then), but Python's docs promise that nbytes==0 never
1614 * returns NULL. We don't pass 0 to realloc(), to avoid that endcase
1615 * to begin with. Even then, we can't be sure that realloc() won't
1616 * return NULL.
1617 */
Victor Stinner0507bf52013-07-07 02:05:46 +02001618 bp = PyMem_Realloc(p, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001619 return bp ? bp : p;
Neil Schemenauera35c6882001-02-27 04:45:05 +00001620}
1621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001622#else /* ! WITH_PYMALLOC */
Tim Petersddea2082002-03-23 10:03:50 +00001623
1624/*==========================================================================*/
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00001625/* pymalloc not enabled: Redirect the entry points to malloc. These will
1626 * only be used by extensions that are compiled with pymalloc enabled. */
Tim Peters62c06ba2002-03-23 22:28:18 +00001627
Antoine Pitrou92840532012-12-17 23:05:59 +01001628Py_ssize_t
1629_Py_GetAllocatedBlocks(void)
1630{
1631 return 0;
1632}
1633
Tim Peters1221c0a2002-03-23 00:20:15 +00001634#endif /* WITH_PYMALLOC */
1635
Tim Petersddea2082002-03-23 10:03:50 +00001636#ifdef PYMALLOC_DEBUG
1637/*==========================================================================*/
Tim Peters62c06ba2002-03-23 22:28:18 +00001638/* A x-platform debugging allocator. This doesn't manage memory directly,
1639 * it wraps a real allocator, adding extra debugging info to the memory blocks.
1640 */
Tim Petersddea2082002-03-23 10:03:50 +00001641
Tim Petersf6fb5012002-04-12 07:38:53 +00001642/* Special bytes broadcast into debug memory blocks at appropriate times.
1643 * Strings of these are unlikely to be valid addresses, floats, ints or
1644 * 7-bit ASCII.
1645 */
1646#undef CLEANBYTE
1647#undef DEADBYTE
1648#undef FORBIDDENBYTE
1649#define CLEANBYTE 0xCB /* clean (newly allocated) memory */
Tim Peters889f61d2002-07-10 19:29:49 +00001650#define DEADBYTE 0xDB /* dead (newly freed) memory */
Tim Petersf6fb5012002-04-12 07:38:53 +00001651#define FORBIDDENBYTE 0xFB /* untouchable bytes at each end of a block */
Tim Petersddea2082002-03-23 10:03:50 +00001652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001653static size_t serialno = 0; /* incremented on each debug {m,re}alloc */
Tim Petersddea2082002-03-23 10:03:50 +00001654
Tim Peterse0850172002-03-24 00:34:21 +00001655/* serialno is always incremented via calling this routine. The point is
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001656 * to supply a single place to set a breakpoint.
1657 */
Tim Peterse0850172002-03-24 00:34:21 +00001658static void
Neil Schemenauerbd02b142002-03-28 21:05:38 +00001659bumpserialno(void)
Tim Peterse0850172002-03-24 00:34:21 +00001660{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001661 ++serialno;
Tim Peterse0850172002-03-24 00:34:21 +00001662}
1663
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001664#define SST SIZEOF_SIZE_T
Tim Peterse0850172002-03-24 00:34:21 +00001665
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001666/* Read sizeof(size_t) bytes at p as a big-endian size_t. */
1667static size_t
1668read_size_t(const void *p)
Tim Petersddea2082002-03-23 10:03:50 +00001669{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001670 const uchar *q = (const uchar *)p;
1671 size_t result = *q++;
1672 int i;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001673
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001674 for (i = SST; --i > 0; ++q)
1675 result = (result << 8) | *q;
1676 return result;
Tim Petersddea2082002-03-23 10:03:50 +00001677}
1678
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001679/* Write n as a big-endian size_t, MSB at address p, LSB at
1680 * p + sizeof(size_t) - 1.
1681 */
Tim Petersddea2082002-03-23 10:03:50 +00001682static void
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001683write_size_t(void *p, size_t n)
Tim Petersddea2082002-03-23 10:03:50 +00001684{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001685 uchar *q = (uchar *)p + SST - 1;
1686 int i;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001687
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001688 for (i = SST; --i >= 0; --q) {
1689 *q = (uchar)(n & 0xff);
1690 n >>= 8;
1691 }
Tim Petersddea2082002-03-23 10:03:50 +00001692}
1693
Tim Peters08d82152002-04-18 22:25:03 +00001694#ifdef Py_DEBUG
1695/* Is target in the list? The list is traversed via the nextpool pointers.
1696 * The list may be NULL-terminated, or circular. Return 1 if target is in
1697 * list, else 0.
1698 */
1699static int
1700pool_is_in_list(const poolp target, poolp list)
1701{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001702 poolp origlist = list;
1703 assert(target != NULL);
1704 if (list == NULL)
1705 return 0;
1706 do {
1707 if (target == list)
1708 return 1;
1709 list = list->nextpool;
1710 } while (list != NULL && list != origlist);
1711 return 0;
Tim Peters08d82152002-04-18 22:25:03 +00001712}
1713
1714#else
1715#define pool_is_in_list(X, Y) 1
1716
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001717#endif /* Py_DEBUG */
Tim Peters08d82152002-04-18 22:25:03 +00001718
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001719/* Let S = sizeof(size_t). The debug malloc asks for 4*S extra bytes and
1720 fills them with useful stuff, here calling the underlying malloc's result p:
Tim Petersddea2082002-03-23 10:03:50 +00001721
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001722p[0: S]
1723 Number of bytes originally asked for. This is a size_t, big-endian (easier
1724 to read in a memory dump).
Georg Brandl7cba5fd2013-09-25 09:04:23 +02001725p[S]
Tim Petersdf099f52013-09-19 21:06:37 -05001726 API ID. See PEP 445. This is a character, but seems undocumented.
1727p[S+1: 2*S]
Tim Petersf6fb5012002-04-12 07:38:53 +00001728 Copies of FORBIDDENBYTE. Used to catch under- writes and reads.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001729p[2*S: 2*S+n]
Tim Petersf6fb5012002-04-12 07:38:53 +00001730 The requested memory, filled with copies of CLEANBYTE.
Tim Petersddea2082002-03-23 10:03:50 +00001731 Used to catch reference to uninitialized memory.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001732 &p[2*S] is returned. Note that this is 8-byte aligned if pymalloc
Tim Petersddea2082002-03-23 10:03:50 +00001733 handled the request itself.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001734p[2*S+n: 2*S+n+S]
Tim Petersf6fb5012002-04-12 07:38:53 +00001735 Copies of FORBIDDENBYTE. Used to catch over- writes and reads.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001736p[2*S+n+S: 2*S+n+2*S]
Victor Stinner0507bf52013-07-07 02:05:46 +02001737 A serial number, incremented by 1 on each call to _PyMem_DebugMalloc
1738 and _PyMem_DebugRealloc.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001739 This is a big-endian size_t.
Tim Petersddea2082002-03-23 10:03:50 +00001740 If "bad memory" is detected later, the serial number gives an
1741 excellent way to set a breakpoint on the next run, to capture the
1742 instant at which this block was passed out.
1743*/
1744
Victor Stinner0507bf52013-07-07 02:05:46 +02001745static void *
1746_PyMem_DebugMalloc(void *ctx, size_t nbytes)
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00001747{
Victor Stinner0507bf52013-07-07 02:05:46 +02001748 debug_alloc_api_t *api = (debug_alloc_api_t *)ctx;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001749 uchar *p; /* base address of malloc'ed block */
1750 uchar *tail; /* p + 2*SST + nbytes == pointer to tail pad bytes */
1751 size_t total; /* nbytes + 4*SST */
Tim Petersddea2082002-03-23 10:03:50 +00001752
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001753 bumpserialno();
1754 total = nbytes + 4*SST;
1755 if (total < nbytes)
1756 /* overflow: can't represent total as a size_t */
1757 return NULL;
Tim Petersddea2082002-03-23 10:03:50 +00001758
Victor Stinner0507bf52013-07-07 02:05:46 +02001759 p = (uchar *)api->alloc.malloc(api->alloc.ctx, total);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001760 if (p == NULL)
1761 return NULL;
Tim Petersddea2082002-03-23 10:03:50 +00001762
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001763 /* at p, write size (SST bytes), id (1 byte), pad (SST-1 bytes) */
1764 write_size_t(p, nbytes);
Victor Stinner0507bf52013-07-07 02:05:46 +02001765 p[SST] = (uchar)api->api_id;
1766 memset(p + SST + 1, FORBIDDENBYTE, SST-1);
Tim Petersddea2082002-03-23 10:03:50 +00001767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001768 if (nbytes > 0)
1769 memset(p + 2*SST, CLEANBYTE, nbytes);
Tim Petersddea2082002-03-23 10:03:50 +00001770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001771 /* at tail, write pad (SST bytes) and serialno (SST bytes) */
1772 tail = p + 2*SST + nbytes;
1773 memset(tail, FORBIDDENBYTE, SST);
1774 write_size_t(tail + SST, serialno);
Tim Petersddea2082002-03-23 10:03:50 +00001775
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001776 return p + 2*SST;
Tim Petersddea2082002-03-23 10:03:50 +00001777}
1778
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001779/* 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 +00001780 particular, that the FORBIDDENBYTEs with the api ID are still intact).
Tim Petersf6fb5012002-04-12 07:38:53 +00001781 Then fills the original bytes with DEADBYTE.
Tim Petersddea2082002-03-23 10:03:50 +00001782 Then calls the underlying free.
1783*/
Victor Stinner0507bf52013-07-07 02:05:46 +02001784static void
1785_PyMem_DebugFree(void *ctx, void *p)
Tim Petersddea2082002-03-23 10:03:50 +00001786{
Victor Stinner0507bf52013-07-07 02:05:46 +02001787 debug_alloc_api_t *api = (debug_alloc_api_t *)ctx;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001788 uchar *q = (uchar *)p - 2*SST; /* address returned from malloc */
1789 size_t nbytes;
Tim Petersddea2082002-03-23 10:03:50 +00001790
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001791 if (p == NULL)
1792 return;
Victor Stinner0507bf52013-07-07 02:05:46 +02001793 _PyMem_DebugCheckAddress(api->api_id, p);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001794 nbytes = read_size_t(q);
1795 nbytes += 4*SST;
1796 if (nbytes > 0)
1797 memset(q, DEADBYTE, nbytes);
Victor Stinner0507bf52013-07-07 02:05:46 +02001798 api->alloc.free(api->alloc.ctx, q);
Tim Petersddea2082002-03-23 10:03:50 +00001799}
1800
Victor Stinner0507bf52013-07-07 02:05:46 +02001801static void *
1802_PyMem_DebugRealloc(void *ctx, void *p, size_t nbytes)
Tim Petersddea2082002-03-23 10:03:50 +00001803{
Victor Stinner0507bf52013-07-07 02:05:46 +02001804 debug_alloc_api_t *api = (debug_alloc_api_t *)ctx;
Victor Stinnerc4266362013-07-09 00:44:43 +02001805 uchar *q = (uchar *)p, *oldq;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001806 uchar *tail;
1807 size_t total; /* nbytes + 4*SST */
1808 size_t original_nbytes;
1809 int i;
Tim Petersddea2082002-03-23 10:03:50 +00001810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001811 if (p == NULL)
Victor Stinner0507bf52013-07-07 02:05:46 +02001812 return _PyMem_DebugMalloc(ctx, nbytes);
Tim Petersddea2082002-03-23 10:03:50 +00001813
Victor Stinner0507bf52013-07-07 02:05:46 +02001814 _PyMem_DebugCheckAddress(api->api_id, p);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001815 bumpserialno();
1816 original_nbytes = read_size_t(q - 2*SST);
1817 total = nbytes + 4*SST;
1818 if (total < nbytes)
1819 /* overflow: can't represent total as a size_t */
1820 return NULL;
Tim Petersddea2082002-03-23 10:03:50 +00001821
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001822 /* Resize and add decorations. We may get a new pointer here, in which
1823 * case we didn't get the chance to mark the old memory with DEADBYTE,
1824 * but we live with that.
1825 */
Victor Stinnerc4266362013-07-09 00:44:43 +02001826 oldq = q;
Victor Stinner0507bf52013-07-07 02:05:46 +02001827 q = (uchar *)api->alloc.realloc(api->alloc.ctx, q - 2*SST, total);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001828 if (q == NULL)
1829 return NULL;
Tim Peters85cc1c42002-04-12 08:52:50 +00001830
Victor Stinnerc4266362013-07-09 00:44:43 +02001831 if (q == oldq && nbytes < original_nbytes) {
1832 /* shrinking: mark old extra memory dead */
1833 memset(q + nbytes, DEADBYTE, original_nbytes - nbytes);
1834 }
1835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001836 write_size_t(q, nbytes);
Victor Stinner0507bf52013-07-07 02:05:46 +02001837 assert(q[SST] == (uchar)api->api_id);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001838 for (i = 1; i < SST; ++i)
1839 assert(q[SST + i] == FORBIDDENBYTE);
1840 q += 2*SST;
Victor Stinnerc4266362013-07-09 00:44:43 +02001841
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001842 tail = q + nbytes;
1843 memset(tail, FORBIDDENBYTE, SST);
1844 write_size_t(tail + SST, serialno);
Tim Peters85cc1c42002-04-12 08:52:50 +00001845
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001846 if (nbytes > original_nbytes) {
1847 /* growing: mark new extra memory clean */
1848 memset(q + original_nbytes, CLEANBYTE,
Stefan Krah735bb122010-11-26 10:54:09 +00001849 nbytes - original_nbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001850 }
Tim Peters85cc1c42002-04-12 08:52:50 +00001851
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001852 return q;
Tim Petersddea2082002-03-23 10:03:50 +00001853}
1854
Tim Peters7ccfadf2002-04-01 06:04:21 +00001855/* Check the forbidden bytes on both ends of the memory allocated for p.
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00001856 * If anything is wrong, print info to stderr via _PyObject_DebugDumpAddress,
Tim Peters7ccfadf2002-04-01 06:04:21 +00001857 * and call Py_FatalError to kill the program.
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00001858 * The API id, is also checked.
Tim Peters7ccfadf2002-04-01 06:04:21 +00001859 */
Victor Stinner0507bf52013-07-07 02:05:46 +02001860static void
1861_PyMem_DebugCheckAddress(char api, const void *p)
Tim Petersddea2082002-03-23 10:03:50 +00001862{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001863 const uchar *q = (const uchar *)p;
1864 char msgbuf[64];
1865 char *msg;
1866 size_t nbytes;
1867 const uchar *tail;
1868 int i;
1869 char id;
Tim Petersddea2082002-03-23 10:03:50 +00001870
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001871 if (p == NULL) {
1872 msg = "didn't expect a NULL pointer";
1873 goto error;
1874 }
Tim Petersddea2082002-03-23 10:03:50 +00001875
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001876 /* Check the API id */
1877 id = (char)q[-SST];
1878 if (id != api) {
1879 msg = msgbuf;
1880 snprintf(msg, sizeof(msgbuf), "bad ID: Allocated using API '%c', verified using API '%c'", id, api);
1881 msgbuf[sizeof(msgbuf)-1] = 0;
1882 goto error;
1883 }
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00001884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001885 /* Check the stuff at the start of p first: if there's underwrite
1886 * corruption, the number-of-bytes field may be nuts, and checking
1887 * the tail could lead to a segfault then.
1888 */
1889 for (i = SST-1; i >= 1; --i) {
1890 if (*(q-i) != FORBIDDENBYTE) {
1891 msg = "bad leading pad byte";
1892 goto error;
1893 }
1894 }
Tim Petersddea2082002-03-23 10:03:50 +00001895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001896 nbytes = read_size_t(q - 2*SST);
1897 tail = q + nbytes;
1898 for (i = 0; i < SST; ++i) {
1899 if (tail[i] != FORBIDDENBYTE) {
1900 msg = "bad trailing pad byte";
1901 goto error;
1902 }
1903 }
Tim Petersddea2082002-03-23 10:03:50 +00001904
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001905 return;
Tim Petersd1139e02002-03-28 07:32:11 +00001906
1907error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001908 _PyObject_DebugDumpAddress(p);
1909 Py_FatalError(msg);
Tim Petersddea2082002-03-23 10:03:50 +00001910}
1911
Tim Peters7ccfadf2002-04-01 06:04:21 +00001912/* Display info to stderr about the memory block at p. */
Victor Stinner0507bf52013-07-07 02:05:46 +02001913static void
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00001914_PyObject_DebugDumpAddress(const void *p)
Tim Petersddea2082002-03-23 10:03:50 +00001915{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001916 const uchar *q = (const uchar *)p;
1917 const uchar *tail;
1918 size_t nbytes, serial;
1919 int i;
1920 int ok;
1921 char id;
Tim Petersddea2082002-03-23 10:03:50 +00001922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001923 fprintf(stderr, "Debug memory block at address p=%p:", p);
1924 if (p == NULL) {
1925 fprintf(stderr, "\n");
1926 return;
1927 }
1928 id = (char)q[-SST];
1929 fprintf(stderr, " API '%c'\n", id);
Tim Petersddea2082002-03-23 10:03:50 +00001930
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001931 nbytes = read_size_t(q - 2*SST);
1932 fprintf(stderr, " %" PY_FORMAT_SIZE_T "u bytes originally "
1933 "requested\n", nbytes);
Tim Petersddea2082002-03-23 10:03:50 +00001934
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001935 /* In case this is nuts, check the leading pad bytes first. */
1936 fprintf(stderr, " The %d pad bytes at p-%d are ", SST-1, SST-1);
1937 ok = 1;
1938 for (i = 1; i <= SST-1; ++i) {
1939 if (*(q-i) != FORBIDDENBYTE) {
1940 ok = 0;
1941 break;
1942 }
1943 }
1944 if (ok)
1945 fputs("FORBIDDENBYTE, as expected.\n", stderr);
1946 else {
1947 fprintf(stderr, "not all FORBIDDENBYTE (0x%02x):\n",
1948 FORBIDDENBYTE);
1949 for (i = SST-1; i >= 1; --i) {
1950 const uchar byte = *(q-i);
1951 fprintf(stderr, " at p-%d: 0x%02x", i, byte);
1952 if (byte != FORBIDDENBYTE)
1953 fputs(" *** OUCH", stderr);
1954 fputc('\n', stderr);
1955 }
Tim Peters449b5a82002-04-28 06:14:45 +00001956
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001957 fputs(" Because memory is corrupted at the start, the "
1958 "count of bytes requested\n"
1959 " may be bogus, and checking the trailing pad "
1960 "bytes may segfault.\n", stderr);
1961 }
Tim Petersddea2082002-03-23 10:03:50 +00001962
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001963 tail = q + nbytes;
1964 fprintf(stderr, " The %d pad bytes at tail=%p are ", SST, tail);
1965 ok = 1;
1966 for (i = 0; i < SST; ++i) {
1967 if (tail[i] != FORBIDDENBYTE) {
1968 ok = 0;
1969 break;
1970 }
1971 }
1972 if (ok)
1973 fputs("FORBIDDENBYTE, as expected.\n", stderr);
1974 else {
1975 fprintf(stderr, "not all FORBIDDENBYTE (0x%02x):\n",
Stefan Krah735bb122010-11-26 10:54:09 +00001976 FORBIDDENBYTE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001977 for (i = 0; i < SST; ++i) {
1978 const uchar byte = tail[i];
1979 fprintf(stderr, " at tail+%d: 0x%02x",
Stefan Krah735bb122010-11-26 10:54:09 +00001980 i, byte);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001981 if (byte != FORBIDDENBYTE)
1982 fputs(" *** OUCH", stderr);
1983 fputc('\n', stderr);
1984 }
1985 }
Tim Petersddea2082002-03-23 10:03:50 +00001986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001987 serial = read_size_t(tail + SST);
1988 fprintf(stderr, " The block was made by call #%" PY_FORMAT_SIZE_T
1989 "u to debug malloc/realloc.\n", serial);
Tim Petersddea2082002-03-23 10:03:50 +00001990
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001991 if (nbytes > 0) {
1992 i = 0;
1993 fputs(" Data at p:", stderr);
1994 /* print up to 8 bytes at the start */
1995 while (q < tail && i < 8) {
1996 fprintf(stderr, " %02x", *q);
1997 ++i;
1998 ++q;
1999 }
2000 /* and up to 8 at the end */
2001 if (q < tail) {
2002 if (tail - q > 8) {
2003 fputs(" ...", stderr);
2004 q = tail - 8;
2005 }
2006 while (q < tail) {
2007 fprintf(stderr, " %02x", *q);
2008 ++q;
2009 }
2010 }
2011 fputc('\n', stderr);
2012 }
Tim Petersddea2082002-03-23 10:03:50 +00002013}
2014
David Malcolm49526f42012-06-22 14:55:41 -04002015#endif /* PYMALLOC_DEBUG */
2016
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00002017static size_t
David Malcolm49526f42012-06-22 14:55:41 -04002018printone(FILE *out, const char* msg, size_t value)
Tim Peters16bcb6b2002-04-05 05:45:31 +00002019{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002020 int i, k;
2021 char buf[100];
2022 size_t origvalue = value;
Tim Peters16bcb6b2002-04-05 05:45:31 +00002023
David Malcolm49526f42012-06-22 14:55:41 -04002024 fputs(msg, out);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002025 for (i = (int)strlen(msg); i < 35; ++i)
David Malcolm49526f42012-06-22 14:55:41 -04002026 fputc(' ', out);
2027 fputc('=', out);
Tim Peters49f26812002-04-06 01:45:35 +00002028
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002029 /* Write the value with commas. */
2030 i = 22;
2031 buf[i--] = '\0';
2032 buf[i--] = '\n';
2033 k = 3;
2034 do {
2035 size_t nextvalue = value / 10;
Benjamin Peterson2dba1ee2013-02-20 16:54:30 -05002036 unsigned int digit = (unsigned int)(value - nextvalue * 10);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002037 value = nextvalue;
2038 buf[i--] = (char)(digit + '0');
2039 --k;
2040 if (k == 0 && value && i >= 0) {
2041 k = 3;
2042 buf[i--] = ',';
2043 }
2044 } while (value && i >= 0);
Tim Peters49f26812002-04-06 01:45:35 +00002045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002046 while (i >= 0)
2047 buf[i--] = ' ';
David Malcolm49526f42012-06-22 14:55:41 -04002048 fputs(buf, out);
Tim Peters49f26812002-04-06 01:45:35 +00002049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002050 return origvalue;
Tim Peters16bcb6b2002-04-05 05:45:31 +00002051}
2052
David Malcolm49526f42012-06-22 14:55:41 -04002053void
2054_PyDebugAllocatorStats(FILE *out,
2055 const char *block_name, int num_blocks, size_t sizeof_block)
2056{
2057 char buf1[128];
2058 char buf2[128];
2059 PyOS_snprintf(buf1, sizeof(buf1),
Tim Peterseaa3bcc2013-09-05 22:57:04 -05002060 "%d %ss * %" PY_FORMAT_SIZE_T "d bytes each",
David Malcolm49526f42012-06-22 14:55:41 -04002061 num_blocks, block_name, sizeof_block);
2062 PyOS_snprintf(buf2, sizeof(buf2),
2063 "%48s ", buf1);
2064 (void)printone(out, buf2, num_blocks * sizeof_block);
2065}
2066
2067#ifdef WITH_PYMALLOC
2068
2069/* Print summary info to "out" about the state of pymalloc's structures.
Tim Peters08d82152002-04-18 22:25:03 +00002070 * In Py_DEBUG mode, also perform some expensive internal consistency
2071 * checks.
2072 */
Tim Peters7ccfadf2002-04-01 06:04:21 +00002073void
David Malcolm49526f42012-06-22 14:55:41 -04002074_PyObject_DebugMallocStats(FILE *out)
Tim Peters7ccfadf2002-04-01 06:04:21 +00002075{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002076 uint i;
2077 const uint numclasses = SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT;
2078 /* # of pools, allocated blocks, and free blocks per class index */
2079 size_t numpools[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT];
2080 size_t numblocks[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT];
2081 size_t numfreeblocks[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT];
2082 /* total # of allocated bytes in used and full pools */
2083 size_t allocated_bytes = 0;
2084 /* total # of available bytes in used pools */
2085 size_t available_bytes = 0;
2086 /* # of free pools + pools not yet carved out of current arena */
2087 uint numfreepools = 0;
2088 /* # of bytes for arena alignment padding */
2089 size_t arena_alignment = 0;
2090 /* # of bytes in used and full pools used for pool_headers */
2091 size_t pool_header_bytes = 0;
2092 /* # of bytes in used and full pools wasted due to quantization,
2093 * i.e. the necessarily leftover space at the ends of used and
2094 * full pools.
2095 */
2096 size_t quantization = 0;
2097 /* # of arenas actually allocated. */
2098 size_t narenas = 0;
2099 /* running total -- should equal narenas * ARENA_SIZE */
2100 size_t total;
2101 char buf[128];
Tim Peters7ccfadf2002-04-01 06:04:21 +00002102
David Malcolm49526f42012-06-22 14:55:41 -04002103 fprintf(out, "Small block threshold = %d, in %u size classes.\n",
Stefan Krah735bb122010-11-26 10:54:09 +00002104 SMALL_REQUEST_THRESHOLD, numclasses);
Tim Peters7ccfadf2002-04-01 06:04:21 +00002105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002106 for (i = 0; i < numclasses; ++i)
2107 numpools[i] = numblocks[i] = numfreeblocks[i] = 0;
Tim Peters7ccfadf2002-04-01 06:04:21 +00002108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002109 /* Because full pools aren't linked to from anything, it's easiest
2110 * to march over all the arenas. If we're lucky, most of the memory
2111 * will be living in full pools -- would be a shame to miss them.
2112 */
2113 for (i = 0; i < maxarenas; ++i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002114 uint j;
2115 uptr base = arenas[i].address;
Thomas Woutersa9773292006-04-21 09:43:23 +00002116
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002117 /* Skip arenas which are not allocated. */
2118 if (arenas[i].address == (uptr)NULL)
2119 continue;
2120 narenas += 1;
Thomas Woutersa9773292006-04-21 09:43:23 +00002121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002122 numfreepools += arenas[i].nfreepools;
Tim Peters7ccfadf2002-04-01 06:04:21 +00002123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002124 /* round up to pool alignment */
2125 if (base & (uptr)POOL_SIZE_MASK) {
2126 arena_alignment += POOL_SIZE;
2127 base &= ~(uptr)POOL_SIZE_MASK;
2128 base += POOL_SIZE;
2129 }
Tim Peters7ccfadf2002-04-01 06:04:21 +00002130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002131 /* visit every pool in the arena */
2132 assert(base <= (uptr) arenas[i].pool_address);
2133 for (j = 0;
2134 base < (uptr) arenas[i].pool_address;
2135 ++j, base += POOL_SIZE) {
2136 poolp p = (poolp)base;
2137 const uint sz = p->szidx;
2138 uint freeblocks;
Tim Peters08d82152002-04-18 22:25:03 +00002139
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002140 if (p->ref.count == 0) {
2141 /* currently unused */
2142 assert(pool_is_in_list(p, arenas[i].freepools));
2143 continue;
2144 }
2145 ++numpools[sz];
2146 numblocks[sz] += p->ref.count;
2147 freeblocks = NUMBLOCKS(sz) - p->ref.count;
2148 numfreeblocks[sz] += freeblocks;
Tim Peters08d82152002-04-18 22:25:03 +00002149#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002150 if (freeblocks > 0)
2151 assert(pool_is_in_list(p, usedpools[sz + sz]));
Tim Peters08d82152002-04-18 22:25:03 +00002152#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002153 }
2154 }
2155 assert(narenas == narenas_currently_allocated);
Tim Peters7ccfadf2002-04-01 06:04:21 +00002156
David Malcolm49526f42012-06-22 14:55:41 -04002157 fputc('\n', out);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002158 fputs("class size num pools blocks in use avail blocks\n"
2159 "----- ---- --------- ------------- ------------\n",
David Malcolm49526f42012-06-22 14:55:41 -04002160 out);
Tim Peters7ccfadf2002-04-01 06:04:21 +00002161
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002162 for (i = 0; i < numclasses; ++i) {
2163 size_t p = numpools[i];
2164 size_t b = numblocks[i];
2165 size_t f = numfreeblocks[i];
2166 uint size = INDEX2SIZE(i);
2167 if (p == 0) {
2168 assert(b == 0 && f == 0);
2169 continue;
2170 }
David Malcolm49526f42012-06-22 14:55:41 -04002171 fprintf(out, "%5u %6u "
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002172 "%11" PY_FORMAT_SIZE_T "u "
2173 "%15" PY_FORMAT_SIZE_T "u "
2174 "%13" PY_FORMAT_SIZE_T "u\n",
Stefan Krah735bb122010-11-26 10:54:09 +00002175 i, size, p, b, f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002176 allocated_bytes += b * size;
2177 available_bytes += f * size;
2178 pool_header_bytes += p * POOL_OVERHEAD;
2179 quantization += p * ((POOL_SIZE - POOL_OVERHEAD) % size);
2180 }
David Malcolm49526f42012-06-22 14:55:41 -04002181 fputc('\n', out);
2182#ifdef PYMALLOC_DEBUG
2183 (void)printone(out, "# times object malloc called", serialno);
2184#endif
2185 (void)printone(out, "# arenas allocated total", ntimes_arena_allocated);
2186 (void)printone(out, "# arenas reclaimed", ntimes_arena_allocated - narenas);
2187 (void)printone(out, "# arenas highwater mark", narenas_highwater);
2188 (void)printone(out, "# arenas allocated current", narenas);
Thomas Woutersa9773292006-04-21 09:43:23 +00002189
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002190 PyOS_snprintf(buf, sizeof(buf),
2191 "%" PY_FORMAT_SIZE_T "u arenas * %d bytes/arena",
2192 narenas, ARENA_SIZE);
David Malcolm49526f42012-06-22 14:55:41 -04002193 (void)printone(out, buf, narenas * ARENA_SIZE);
Tim Peters16bcb6b2002-04-05 05:45:31 +00002194
David Malcolm49526f42012-06-22 14:55:41 -04002195 fputc('\n', out);
Tim Peters16bcb6b2002-04-05 05:45:31 +00002196
David Malcolm49526f42012-06-22 14:55:41 -04002197 total = printone(out, "# bytes in allocated blocks", allocated_bytes);
2198 total += printone(out, "# bytes in available blocks", available_bytes);
Tim Peters49f26812002-04-06 01:45:35 +00002199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002200 PyOS_snprintf(buf, sizeof(buf),
2201 "%u unused pools * %d bytes", numfreepools, POOL_SIZE);
David Malcolm49526f42012-06-22 14:55:41 -04002202 total += printone(out, buf, (size_t)numfreepools * POOL_SIZE);
Tim Peters16bcb6b2002-04-05 05:45:31 +00002203
David Malcolm49526f42012-06-22 14:55:41 -04002204 total += printone(out, "# bytes lost to pool headers", pool_header_bytes);
2205 total += printone(out, "# bytes lost to quantization", quantization);
2206 total += printone(out, "# bytes lost to arena alignment", arena_alignment);
2207 (void)printone(out, "Total", total);
Tim Peters7ccfadf2002-04-01 06:04:21 +00002208}
2209
David Malcolm49526f42012-06-22 14:55:41 -04002210#endif /* #ifdef WITH_PYMALLOC */
Neal Norwitz7eb3c912004-06-06 19:20:22 +00002211
2212#ifdef Py_USING_MEMORY_DEBUGGER
Thomas Woutersa9773292006-04-21 09:43:23 +00002213/* Make this function last so gcc won't inline it since the definition is
2214 * after the reference.
2215 */
Neal Norwitz7eb3c912004-06-06 19:20:22 +00002216int
2217Py_ADDRESS_IN_RANGE(void *P, poolp pool)
2218{
Antoine Pitroub7fb2e22011-01-07 21:43:59 +00002219 uint arenaindex_temp = pool->arenaindex;
2220
2221 return arenaindex_temp < maxarenas &&
2222 (uptr)P - arenas[arenaindex_temp].address < (uptr)ARENA_SIZE &&
2223 arenas[arenaindex_temp].address != 0;
Neal Norwitz7eb3c912004-06-06 19:20:22 +00002224}
2225#endif