blob: 97a137db37300435fa376d58caef369ddcb35d0f [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
Tim Peters1221c0a2002-03-23 00:20:15 +000015#ifdef WITH_PYMALLOC
16
Victor Stinner0507bf52013-07-07 02:05:46 +020017#ifdef MS_WINDOWS
18# include <windows.h>
19#elif defined(HAVE_MMAP)
20# include <sys/mman.h>
21# ifdef MAP_ANONYMOUS
22# define ARENAS_USE_MMAP
23# endif
Antoine Pitrou6f26be02011-05-03 18:18:59 +020024#endif
25
Victor Stinner0507bf52013-07-07 02:05:46 +020026/* Forward declaration */
27static void* _PyObject_Malloc(void *ctx, size_t size);
28static void _PyObject_Free(void *ctx, void *p);
29static void* _PyObject_Realloc(void *ctx, void *ptr, size_t size);
Martin v. Löwiscd83fa82013-06-27 12:23:29 +020030#endif
31
Victor Stinner0507bf52013-07-07 02:05:46 +020032
33static void *
34_PyMem_RawMalloc(void *ctx, size_t size)
35{
36 /* PyMem_Malloc(0) means malloc(1). Some systems would return NULL
37 for malloc(0), which would be treated as an error. Some platforms would
38 return a pointer with no memory behind it, which would break pymalloc.
39 To solve these problems, allocate an extra byte. */
40 if (size == 0)
41 size = 1;
42 return malloc(size);
43}
44
45static void *
46_PyMem_RawRealloc(void *ctx, void *ptr, size_t size)
47{
48 if (size == 0)
49 size = 1;
50 return realloc(ptr, size);
51}
52
53static void
54_PyMem_RawFree(void *ctx, void *ptr)
55{
56 free(ptr);
57}
58
59
60#ifdef MS_WINDOWS
61static void *
62_PyObject_ArenaVirtualAlloc(void *ctx, size_t size)
63{
64 return VirtualAlloc(NULL, size,
65 MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
66}
67
68static void
69_PyObject_ArenaVirtualFree(void *ctx, void *ptr, size_t size)
70{
Victor Stinner725e6682013-07-07 03:06:16 +020071 VirtualFree(ptr, 0, MEM_RELEASE);
Victor Stinner0507bf52013-07-07 02:05:46 +020072}
73
74#elif defined(ARENAS_USE_MMAP)
75static void *
76_PyObject_ArenaMmap(void *ctx, size_t size)
77{
78 void *ptr;
79 ptr = mmap(NULL, size, PROT_READ|PROT_WRITE,
80 MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
81 if (ptr == MAP_FAILED)
82 return NULL;
83 assert(ptr != NULL);
84 return ptr;
85}
86
87static void
88_PyObject_ArenaMunmap(void *ctx, void *ptr, size_t size)
89{
90 munmap(ptr, size);
91}
92
93#else
94static void *
95_PyObject_ArenaMalloc(void *ctx, size_t size)
96{
97 return malloc(size);
98}
99
100static void
101_PyObject_ArenaFree(void *ctx, void *ptr, size_t size)
102{
103 free(ptr);
104}
105#endif
106
107
108#define PYRAW_FUNCS _PyMem_RawMalloc, _PyMem_RawRealloc, _PyMem_RawFree
109#ifdef WITH_PYMALLOC
110#define PYOBJECT_FUNCS _PyObject_Malloc, _PyObject_Realloc, _PyObject_Free
111#else
112#define PYOBJECT_FUNCS PYRAW_FUNCS
113#endif
114
115#ifdef PYMALLOC_DEBUG
116typedef struct {
117 /* We tag each block with an API ID in order to tag API violations */
118 char api_id;
119 PyMemAllocator alloc;
120} debug_alloc_api_t;
121static struct {
122 debug_alloc_api_t raw;
123 debug_alloc_api_t mem;
124 debug_alloc_api_t obj;
125} _PyMem_Debug = {
126 {'r', {NULL, PYRAW_FUNCS}},
127 {'m', {NULL, PYRAW_FUNCS}},
128 {'o', {NULL, PYOBJECT_FUNCS}}
129 };
130
131#define PYDEBUG_FUNCS _PyMem_DebugMalloc, _PyMem_DebugRealloc, _PyMem_DebugFree
132#endif
133
134static PyMemAllocator _PyMem_Raw = {
135#ifdef PYMALLOC_DEBUG
136 &_PyMem_Debug.raw, PYDEBUG_FUNCS
137#else
138 NULL, PYRAW_FUNCS
139#endif
140 };
141
142static PyMemAllocator _PyMem = {
143#ifdef PYMALLOC_DEBUG
144 &_PyMem_Debug.mem, PYDEBUG_FUNCS
145#else
146 NULL, PYRAW_FUNCS
147#endif
148 };
149
150static PyMemAllocator _PyObject = {
151#ifdef PYMALLOC_DEBUG
152 &_PyMem_Debug.obj, PYDEBUG_FUNCS
153#else
154 NULL, PYOBJECT_FUNCS
155#endif
156 };
157
158#undef PYRAW_FUNCS
159#undef PYOBJECT_FUNCS
160#undef PYDEBUG_FUNCS
161
162static PyObjectArenaAllocator _PyObject_Arena = {NULL,
163#ifdef MS_WINDOWS
164 _PyObject_ArenaVirtualAlloc, _PyObject_ArenaVirtualFree
165#elif defined(ARENAS_USE_MMAP)
166 _PyObject_ArenaMmap, _PyObject_ArenaMunmap
167#else
168 _PyObject_ArenaMalloc, _PyObject_ArenaFree
169#endif
170 };
171
172void
173PyMem_SetupDebugHooks(void)
174{
175#ifdef PYMALLOC_DEBUG
176 PyMemAllocator alloc;
177
178 alloc.malloc = _PyMem_DebugMalloc;
179 alloc.realloc = _PyMem_DebugRealloc;
180 alloc.free = _PyMem_DebugFree;
181
182 if (_PyMem_Raw.malloc != _PyMem_DebugMalloc) {
183 alloc.ctx = &_PyMem_Debug.raw;
184 PyMem_GetAllocator(PYMEM_DOMAIN_RAW, &_PyMem_Debug.raw.alloc);
185 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &alloc);
186 }
187
188 if (_PyMem.malloc != _PyMem_DebugMalloc) {
189 alloc.ctx = &_PyMem_Debug.mem;
190 PyMem_GetAllocator(PYMEM_DOMAIN_MEM, &_PyMem_Debug.mem.alloc);
191 PyMem_SetAllocator(PYMEM_DOMAIN_MEM, &alloc);
192 }
193
194 if (_PyObject.malloc != _PyMem_DebugMalloc) {
195 alloc.ctx = &_PyMem_Debug.obj;
196 PyMem_GetAllocator(PYMEM_DOMAIN_OBJ, &_PyMem_Debug.obj.alloc);
197 PyMem_SetAllocator(PYMEM_DOMAIN_OBJ, &alloc);
198 }
199#endif
200}
201
202void
203PyMem_GetAllocator(PyMemAllocatorDomain domain, PyMemAllocator *allocator)
204{
205 switch(domain)
206 {
207 case PYMEM_DOMAIN_RAW: *allocator = _PyMem_Raw; break;
208 case PYMEM_DOMAIN_MEM: *allocator = _PyMem; break;
209 case PYMEM_DOMAIN_OBJ: *allocator = _PyObject; break;
210 default:
211 /* unknown domain */
212 allocator->ctx = NULL;
213 allocator->malloc = NULL;
214 allocator->realloc = NULL;
215 allocator->free = NULL;
216 }
217}
218
219void
220PyMem_SetAllocator(PyMemAllocatorDomain domain, PyMemAllocator *allocator)
221{
222 switch(domain)
223 {
224 case PYMEM_DOMAIN_RAW: _PyMem_Raw = *allocator; break;
225 case PYMEM_DOMAIN_MEM: _PyMem = *allocator; break;
226 case PYMEM_DOMAIN_OBJ: _PyObject = *allocator; break;
227 /* ignore unknown domain */
228 }
229
230}
231
232void
233PyObject_GetArenaAllocator(PyObjectArenaAllocator *allocator)
234{
235 *allocator = _PyObject_Arena;
236}
237
238void
239PyObject_SetArenaAllocator(PyObjectArenaAllocator *allocator)
240{
241 _PyObject_Arena = *allocator;
242}
243
244void *
245PyMem_RawMalloc(size_t size)
246{
247 /*
248 * Limit ourselves to PY_SSIZE_T_MAX bytes to prevent security holes.
249 * Most python internals blindly use a signed Py_ssize_t to track
250 * things without checking for overflows or negatives.
251 * As size_t is unsigned, checking for size < 0 is not required.
252 */
253 if (size > (size_t)PY_SSIZE_T_MAX)
254 return NULL;
255
256 return _PyMem_Raw.malloc(_PyMem_Raw.ctx, size);
257}
258
259void*
260PyMem_RawRealloc(void *ptr, size_t new_size)
261{
262 /* see PyMem_RawMalloc() */
263 if (new_size > (size_t)PY_SSIZE_T_MAX)
264 return NULL;
265 return _PyMem_Raw.realloc(_PyMem_Raw.ctx, ptr, new_size);
266}
267
268void PyMem_RawFree(void *ptr)
269{
270 _PyMem_Raw.free(_PyMem_Raw.ctx, ptr);
271}
272
273void *
274PyMem_Malloc(size_t size)
275{
276 /* see PyMem_RawMalloc() */
277 if (size > (size_t)PY_SSIZE_T_MAX)
278 return NULL;
279 return _PyMem.malloc(_PyMem.ctx, size);
280}
281
282void *
283PyMem_Realloc(void *ptr, size_t new_size)
284{
285 /* see PyMem_RawMalloc() */
286 if (new_size > (size_t)PY_SSIZE_T_MAX)
287 return NULL;
288 return _PyMem.realloc(_PyMem.ctx, ptr, new_size);
289}
290
291void
292PyMem_Free(void *ptr)
293{
294 _PyMem.free(_PyMem.ctx, ptr);
295}
296
297void *
298PyObject_Malloc(size_t size)
299{
300 /* see PyMem_RawMalloc() */
301 if (size > (size_t)PY_SSIZE_T_MAX)
302 return NULL;
303 return _PyObject.malloc(_PyObject.ctx, size);
304}
305
306void *
307PyObject_Realloc(void *ptr, size_t new_size)
308{
309 /* see PyMem_RawMalloc() */
310 if (new_size > (size_t)PY_SSIZE_T_MAX)
311 return NULL;
312 return _PyObject.realloc(_PyObject.ctx, ptr, new_size);
313}
314
315void
316PyObject_Free(void *ptr)
317{
318 _PyObject.free(_PyObject.ctx, ptr);
319}
320
321
322#ifdef WITH_PYMALLOC
323
Benjamin Peterson05159c42009-12-03 03:01:27 +0000324#ifdef WITH_VALGRIND
325#include <valgrind/valgrind.h>
326
327/* If we're using GCC, use __builtin_expect() to reduce overhead of
328 the valgrind checks */
329#if defined(__GNUC__) && (__GNUC__ > 2) && defined(__OPTIMIZE__)
330# define UNLIKELY(value) __builtin_expect((value), 0)
331#else
332# define UNLIKELY(value) (value)
333#endif
334
335/* -1 indicates that we haven't checked that we're running on valgrind yet. */
336static int running_on_valgrind = -1;
337#endif
338
Neil Schemenauera35c6882001-02-27 04:45:05 +0000339/* An object allocator for Python.
340
341 Here is an introduction to the layers of the Python memory architecture,
342 showing where the object allocator is actually used (layer +2), It is
343 called for every object allocation and deallocation (PyObject_New/Del),
344 unless the object-specific allocators implement a proprietary allocation
345 scheme (ex.: ints use a simple free list). This is also the place where
346 the cyclic garbage collector operates selectively on container objects.
347
348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000349 Object-specific allocators
Neil Schemenauera35c6882001-02-27 04:45:05 +0000350 _____ ______ ______ ________
351 [ int ] [ dict ] [ list ] ... [ string ] Python core |
352+3 | <----- Object-specific memory -----> | <-- Non-object memory --> |
353 _______________________________ | |
354 [ Python's object allocator ] | |
355+2 | ####### Object memory ####### | <------ Internal buffers ------> |
356 ______________________________________________________________ |
357 [ Python's raw memory allocator (PyMem_ API) ] |
358+1 | <----- Python memory (under PyMem manager's control) ------> | |
359 __________________________________________________________________
360 [ Underlying general-purpose allocator (ex: C library malloc) ]
361 0 | <------ Virtual memory allocated for the python process -------> |
362
363 =========================================================================
364 _______________________________________________________________________
365 [ OS-specific Virtual Memory Manager (VMM) ]
366-1 | <--- Kernel dynamic storage allocation & management (page-based) ---> |
367 __________________________________ __________________________________
368 [ ] [ ]
369-2 | <-- Physical memory: ROM/RAM --> | | <-- Secondary storage (swap) --> |
370
371*/
372/*==========================================================================*/
373
374/* A fast, special-purpose memory allocator for small blocks, to be used
375 on top of a general-purpose malloc -- heavily based on previous art. */
376
377/* Vladimir Marangozov -- August 2000 */
378
379/*
380 * "Memory management is where the rubber meets the road -- if we do the wrong
381 * thing at any level, the results will not be good. And if we don't make the
382 * levels work well together, we are in serious trouble." (1)
383 *
384 * (1) Paul R. Wilson, Mark S. Johnstone, Michael Neely, and David Boles,
385 * "Dynamic Storage Allocation: A Survey and Critical Review",
386 * in Proc. 1995 Int'l. Workshop on Memory Management, September 1995.
387 */
388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000389/* #undef WITH_MEMORY_LIMITS */ /* disable mem limit checks */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000390
391/*==========================================================================*/
392
393/*
Neil Schemenauera35c6882001-02-27 04:45:05 +0000394 * Allocation strategy abstract:
395 *
396 * For small requests, the allocator sub-allocates <Big> blocks of memory.
Antoine Pitrou6f26be02011-05-03 18:18:59 +0200397 * Requests greater than SMALL_REQUEST_THRESHOLD bytes are routed to the
398 * system's allocator.
Tim Petersce7fb9b2002-03-23 00:28:57 +0000399 *
Neil Schemenauera35c6882001-02-27 04:45:05 +0000400 * Small requests are grouped in size classes spaced 8 bytes apart, due
401 * to the required valid alignment of the returned address. Requests of
402 * a particular size are serviced from memory pools of 4K (one VMM page).
403 * Pools are fragmented on demand and contain free lists of blocks of one
404 * particular size class. In other words, there is a fixed-size allocator
405 * for each size class. Free pools are shared by the different allocators
406 * thus minimizing the space reserved for a particular size class.
407 *
408 * This allocation strategy is a variant of what is known as "simple
409 * segregated storage based on array of free lists". The main drawback of
410 * simple segregated storage is that we might end up with lot of reserved
411 * memory for the different free lists, which degenerate in time. To avoid
412 * this, we partition each free list in pools and we share dynamically the
413 * reserved space between all free lists. This technique is quite efficient
414 * for memory intensive programs which allocate mainly small-sized blocks.
415 *
416 * For small requests we have the following table:
417 *
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000418 * Request in bytes Size of allocated block Size class idx
Neil Schemenauera35c6882001-02-27 04:45:05 +0000419 * ----------------------------------------------------------------
420 * 1-8 8 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 * 9-16 16 1
422 * 17-24 24 2
423 * 25-32 32 3
424 * 33-40 40 4
425 * 41-48 48 5
426 * 49-56 56 6
427 * 57-64 64 7
428 * 65-72 72 8
429 * ... ... ...
Antoine Pitrou6f26be02011-05-03 18:18:59 +0200430 * 497-504 504 62
431 * 505-512 512 63
Tim Petersce7fb9b2002-03-23 00:28:57 +0000432 *
Antoine Pitrou6f26be02011-05-03 18:18:59 +0200433 * 0, SMALL_REQUEST_THRESHOLD + 1 and up: routed to the underlying
434 * allocator.
Neil Schemenauera35c6882001-02-27 04:45:05 +0000435 */
436
437/*==========================================================================*/
438
439/*
440 * -- Main tunable settings section --
441 */
442
443/*
444 * Alignment of addresses returned to the user. 8-bytes alignment works
445 * on most current architectures (with 32-bit or 64-bit address busses).
446 * The alignment value is also used for grouping small requests in size
447 * classes spaced ALIGNMENT bytes apart.
448 *
449 * You shouldn't change this unless you know what you are doing.
450 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000451#define ALIGNMENT 8 /* must be 2^N */
452#define ALIGNMENT_SHIFT 3
Neil Schemenauera35c6882001-02-27 04:45:05 +0000453
Tim Peterse70ddf32002-04-05 04:32:29 +0000454/* Return the number of bytes in size class I, as a uint. */
455#define INDEX2SIZE(I) (((uint)(I) + 1) << ALIGNMENT_SHIFT)
456
Neil Schemenauera35c6882001-02-27 04:45:05 +0000457/*
458 * Max size threshold below which malloc requests are considered to be
459 * small enough in order to use preallocated memory pools. You can tune
460 * this value according to your application behaviour and memory needs.
461 *
Antoine Pitrou6f26be02011-05-03 18:18:59 +0200462 * Note: a size threshold of 512 guarantees that newly created dictionaries
463 * will be allocated from preallocated memory pools on 64-bit.
464 *
Neil Schemenauera35c6882001-02-27 04:45:05 +0000465 * The following invariants must hold:
Antoine Pitrou6f26be02011-05-03 18:18:59 +0200466 * 1) ALIGNMENT <= SMALL_REQUEST_THRESHOLD <= 512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000467 * 2) SMALL_REQUEST_THRESHOLD is evenly divisible by ALIGNMENT
Neil Schemenauera35c6882001-02-27 04:45:05 +0000468 *
469 * Although not required, for better performance and space efficiency,
470 * it is recommended that SMALL_REQUEST_THRESHOLD is set to a power of 2.
471 */
Antoine Pitrou6f26be02011-05-03 18:18:59 +0200472#define SMALL_REQUEST_THRESHOLD 512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000473#define NB_SMALL_SIZE_CLASSES (SMALL_REQUEST_THRESHOLD / ALIGNMENT)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000474
475/*
476 * The system's VMM page size can be obtained on most unices with a
477 * getpagesize() call or deduced from various header files. To make
478 * things simpler, we assume that it is 4K, which is OK for most systems.
479 * It is probably better if this is the native page size, but it doesn't
Tim Petersecc6e6a2005-07-10 22:30:55 +0000480 * have to be. In theory, if SYSTEM_PAGE_SIZE is larger than the native page
481 * size, then `POOL_ADDR(p)->arenaindex' could rarely cause a segmentation
482 * violation fault. 4K is apparently OK for all the platforms that python
Martin v. Löwis8c140282002-10-26 15:01:53 +0000483 * currently targets.
Neil Schemenauera35c6882001-02-27 04:45:05 +0000484 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485#define SYSTEM_PAGE_SIZE (4 * 1024)
486#define SYSTEM_PAGE_SIZE_MASK (SYSTEM_PAGE_SIZE - 1)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000487
488/*
489 * Maximum amount of memory managed by the allocator for small requests.
490 */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000491#ifdef WITH_MEMORY_LIMITS
492#ifndef SMALL_MEMORY_LIMIT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493#define SMALL_MEMORY_LIMIT (64 * 1024 * 1024) /* 64 MB -- more? */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000494#endif
495#endif
496
497/*
498 * The allocator sub-allocates <Big> blocks of memory (called arenas) aligned
499 * on a page boundary. This is a reserved virtual address space for the
Antoine Pitrouf0effe62011-11-26 01:11:02 +0100500 * current process (obtained through a malloc()/mmap() call). In no way this
501 * means that the memory arenas will be used entirely. A malloc(<Big>) is
502 * usually an address range reservation for <Big> bytes, unless all pages within
503 * this space are referenced subsequently. So malloc'ing big blocks and not
504 * using them does not mean "wasting memory". It's an addressable range
505 * wastage...
Neil Schemenauera35c6882001-02-27 04:45:05 +0000506 *
Antoine Pitrouf0effe62011-11-26 01:11:02 +0100507 * Arenas are allocated with mmap() on systems supporting anonymous memory
508 * mappings to reduce heap fragmentation.
Neil Schemenauera35c6882001-02-27 04:45:05 +0000509 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510#define ARENA_SIZE (256 << 10) /* 256KB */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000511
512#ifdef WITH_MEMORY_LIMITS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000513#define MAX_ARENAS (SMALL_MEMORY_LIMIT / ARENA_SIZE)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000514#endif
515
516/*
517 * Size of the pools used for small blocks. Should be a power of 2,
Tim Petersc2ce91a2002-03-30 21:36:04 +0000518 * between 1K and SYSTEM_PAGE_SIZE, that is: 1k, 2k, 4k.
Neil Schemenauera35c6882001-02-27 04:45:05 +0000519 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000520#define POOL_SIZE SYSTEM_PAGE_SIZE /* must be 2^N */
521#define POOL_SIZE_MASK SYSTEM_PAGE_SIZE_MASK
Neil Schemenauera35c6882001-02-27 04:45:05 +0000522
523/*
524 * -- End of tunable settings section --
525 */
526
527/*==========================================================================*/
528
529/*
530 * Locking
531 *
532 * To reduce lock contention, it would probably be better to refine the
533 * crude function locking with per size class locking. I'm not positive
534 * however, whether it's worth switching to such locking policy because
535 * of the performance penalty it might introduce.
536 *
537 * The following macros describe the simplest (should also be the fastest)
538 * lock object on a particular platform and the init/fini/lock/unlock
539 * operations on it. The locks defined here are not expected to be recursive
540 * because it is assumed that they will always be called in the order:
541 * INIT, [LOCK, UNLOCK]*, FINI.
542 */
543
544/*
545 * Python's threads are serialized, so object malloc locking is disabled.
546 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000547#define SIMPLELOCK_DECL(lock) /* simple lock declaration */
548#define SIMPLELOCK_INIT(lock) /* allocate (if needed) and initialize */
549#define SIMPLELOCK_FINI(lock) /* free/destroy an existing lock */
550#define SIMPLELOCK_LOCK(lock) /* acquire released lock */
551#define SIMPLELOCK_UNLOCK(lock) /* release acquired lock */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000552
553/*
554 * Basic types
555 * I don't care if these are defined in <sys/types.h> or elsewhere. Axiom.
556 */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000557#undef uchar
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000558#define uchar unsigned char /* assuming == 8 bits */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000559
Neil Schemenauera35c6882001-02-27 04:45:05 +0000560#undef uint
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561#define uint unsigned int /* assuming >= 16 bits */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000562
563#undef ulong
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000564#define ulong unsigned long /* assuming >= 32 bits */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000565
Tim Petersd97a1c02002-03-30 06:09:22 +0000566#undef uptr
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000567#define uptr Py_uintptr_t
Tim Petersd97a1c02002-03-30 06:09:22 +0000568
Neil Schemenauera35c6882001-02-27 04:45:05 +0000569/* When you say memory, my mind reasons in terms of (pointers to) blocks */
570typedef uchar block;
571
Tim Peterse70ddf32002-04-05 04:32:29 +0000572/* Pool for small blocks. */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000573struct pool_header {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000574 union { block *_padding;
Stefan Krah735bb122010-11-26 10:54:09 +0000575 uint count; } ref; /* number of allocated blocks */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000576 block *freeblock; /* pool's free list head */
577 struct pool_header *nextpool; /* next pool of this size class */
578 struct pool_header *prevpool; /* previous pool "" */
579 uint arenaindex; /* index into arenas of base adr */
580 uint szidx; /* block size class index */
581 uint nextoffset; /* bytes to virgin block */
582 uint maxnextoffset; /* largest valid nextoffset */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000583};
584
585typedef struct pool_header *poolp;
586
Thomas Woutersa9773292006-04-21 09:43:23 +0000587/* Record keeping for arenas. */
588struct arena_object {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 /* The address of the arena, as returned by malloc. Note that 0
590 * will never be returned by a successful malloc, and is used
591 * here to mark an arena_object that doesn't correspond to an
592 * allocated arena.
593 */
594 uptr address;
Thomas Woutersa9773292006-04-21 09:43:23 +0000595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596 /* Pool-aligned pointer to the next pool to be carved off. */
597 block* pool_address;
Thomas Woutersa9773292006-04-21 09:43:23 +0000598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000599 /* The number of available pools in the arena: free pools + never-
600 * allocated pools.
601 */
602 uint nfreepools;
Thomas Woutersa9773292006-04-21 09:43:23 +0000603
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000604 /* The total number of pools in the arena, whether or not available. */
605 uint ntotalpools;
Thomas Woutersa9773292006-04-21 09:43:23 +0000606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000607 /* Singly-linked list of available pools. */
608 struct pool_header* freepools;
Thomas Woutersa9773292006-04-21 09:43:23 +0000609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000610 /* Whenever this arena_object is not associated with an allocated
611 * arena, the nextarena member is used to link all unassociated
612 * arena_objects in the singly-linked `unused_arena_objects` list.
613 * The prevarena member is unused in this case.
614 *
615 * When this arena_object is associated with an allocated arena
616 * with at least one available pool, both members are used in the
617 * doubly-linked `usable_arenas` list, which is maintained in
618 * increasing order of `nfreepools` values.
619 *
620 * Else this arena_object is associated with an allocated arena
621 * all of whose pools are in use. `nextarena` and `prevarena`
622 * are both meaningless in this case.
623 */
624 struct arena_object* nextarena;
625 struct arena_object* prevarena;
Thomas Woutersa9773292006-04-21 09:43:23 +0000626};
627
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +0200628#define POOL_OVERHEAD _Py_SIZE_ROUND_UP(sizeof(struct pool_header), ALIGNMENT)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630#define DUMMY_SIZE_IDX 0xffff /* size class of newly cached pools */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000631
Tim Petersd97a1c02002-03-30 06:09:22 +0000632/* Round pointer P down to the closest pool-aligned address <= P, as a poolp */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +0200633#define POOL_ADDR(P) ((poolp)_Py_ALIGN_DOWN((P), POOL_SIZE))
Tim Peterse70ddf32002-04-05 04:32:29 +0000634
Tim Peters16bcb6b2002-04-05 05:45:31 +0000635/* Return total number of blocks in pool of size index I, as a uint. */
636#define NUMBLOCKS(I) ((uint)(POOL_SIZE - POOL_OVERHEAD) / INDEX2SIZE(I))
Tim Petersd97a1c02002-03-30 06:09:22 +0000637
Neil Schemenauera35c6882001-02-27 04:45:05 +0000638/*==========================================================================*/
639
640/*
641 * This malloc lock
642 */
Jeremy Hyltond1fedb62002-07-18 18:49:52 +0000643SIMPLELOCK_DECL(_malloc_lock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644#define LOCK() SIMPLELOCK_LOCK(_malloc_lock)
645#define UNLOCK() SIMPLELOCK_UNLOCK(_malloc_lock)
646#define LOCK_INIT() SIMPLELOCK_INIT(_malloc_lock)
647#define LOCK_FINI() SIMPLELOCK_FINI(_malloc_lock)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000648
649/*
Tim Peters1e16db62002-03-31 01:05:22 +0000650 * Pool table -- headed, circular, doubly-linked lists of partially used pools.
651
652This is involved. For an index i, usedpools[i+i] is the header for a list of
653all partially used pools holding small blocks with "size class idx" i. So
654usedpools[0] corresponds to blocks of size 8, usedpools[2] to blocks of size
65516, and so on: index 2*i <-> blocks of size (i+1)<<ALIGNMENT_SHIFT.
656
Thomas Woutersa9773292006-04-21 09:43:23 +0000657Pools are carved off an arena's highwater mark (an arena_object's pool_address
658member) as needed. Once carved off, a pool is in one of three states forever
659after:
Tim Peters1e16db62002-03-31 01:05:22 +0000660
Tim Peters338e0102002-04-01 19:23:44 +0000661used == partially used, neither empty nor full
662 At least one block in the pool is currently allocated, and at least one
663 block in the pool is not currently allocated (note this implies a pool
664 has room for at least two blocks).
665 This is a pool's initial state, as a pool is created only when malloc
666 needs space.
667 The pool holds blocks of a fixed size, and is in the circular list headed
668 at usedpools[i] (see above). It's linked to the other used pools of the
669 same size class via the pool_header's nextpool and prevpool members.
670 If all but one block is currently allocated, a malloc can cause a
671 transition to the full state. If all but one block is not currently
672 allocated, a free can cause a transition to the empty state.
Tim Peters1e16db62002-03-31 01:05:22 +0000673
Tim Peters338e0102002-04-01 19:23:44 +0000674full == all the pool's blocks are currently allocated
675 On transition to full, a pool is unlinked from its usedpools[] list.
676 It's not linked to from anything then anymore, and its nextpool and
677 prevpool members are meaningless until it transitions back to used.
678 A free of a block in a full pool puts the pool back in the used state.
679 Then it's linked in at the front of the appropriate usedpools[] list, so
680 that the next allocation for its size class will reuse the freed block.
681
682empty == all the pool's blocks are currently available for allocation
683 On transition to empty, a pool is unlinked from its usedpools[] list,
Thomas Woutersa9773292006-04-21 09:43:23 +0000684 and linked to the front of its arena_object's singly-linked freepools list,
Tim Peters338e0102002-04-01 19:23:44 +0000685 via its nextpool member. The prevpool member has no meaning in this case.
686 Empty pools have no inherent size class: the next time a malloc finds
687 an empty list in usedpools[], it takes the first pool off of freepools.
688 If the size class needed happens to be the same as the size class the pool
Tim Peterse70ddf32002-04-05 04:32:29 +0000689 last had, some pool initialization can be skipped.
Tim Peters338e0102002-04-01 19:23:44 +0000690
691
692Block Management
693
694Blocks within pools are again carved out as needed. pool->freeblock points to
695the start of a singly-linked list of free blocks within the pool. When a
696block is freed, it's inserted at the front of its pool's freeblock list. Note
697that the available blocks in a pool are *not* linked all together when a pool
Tim Peterse70ddf32002-04-05 04:32:29 +0000698is initialized. Instead only "the first two" (lowest addresses) blocks are
699set up, returning the first such block, and setting pool->freeblock to a
700one-block list holding the second such block. This is consistent with that
701pymalloc strives at all levels (arena, pool, and block) never to touch a piece
702of memory until it's actually needed.
703
704So long as a pool is in the used state, we're certain there *is* a block
Tim Peters52aefc82002-04-11 06:36:45 +0000705available for allocating, and pool->freeblock is not NULL. If pool->freeblock
706points to the end of the free list before we've carved the entire pool into
707blocks, that means we simply haven't yet gotten to one of the higher-address
708blocks. The offset from the pool_header to the start of "the next" virgin
709block is stored in the pool_header nextoffset member, and the largest value
710of nextoffset that makes sense is stored in the maxnextoffset member when a
711pool is initialized. All the blocks in a pool have been passed out at least
712once when and only when nextoffset > maxnextoffset.
Tim Peters338e0102002-04-01 19:23:44 +0000713
Tim Peters1e16db62002-03-31 01:05:22 +0000714
715Major obscurity: While the usedpools vector is declared to have poolp
716entries, it doesn't really. It really contains two pointers per (conceptual)
717poolp entry, the nextpool and prevpool members of a pool_header. The
718excruciating initialization code below fools C so that
719
720 usedpool[i+i]
721
722"acts like" a genuine poolp, but only so long as you only reference its
723nextpool and prevpool members. The "- 2*sizeof(block *)" gibberish is
724compensating for that a pool_header's nextpool and prevpool members
725immediately follow a pool_header's first two members:
726
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000727 union { block *_padding;
Stefan Krah735bb122010-11-26 10:54:09 +0000728 uint count; } ref;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000729 block *freeblock;
Tim Peters1e16db62002-03-31 01:05:22 +0000730
731each of which consume sizeof(block *) bytes. So what usedpools[i+i] really
732contains is a fudged-up pointer p such that *if* C believes it's a poolp
733pointer, then p->nextpool and p->prevpool are both p (meaning that the headed
734circular list is empty).
735
736It's unclear why the usedpools setup is so convoluted. It could be to
737minimize the amount of cache required to hold this heavily-referenced table
738(which only *needs* the two interpool pointer members of a pool_header). OTOH,
739referencing code has to remember to "double the index" and doing so isn't
740free, usedpools[0] isn't a strictly legal pointer, and we're crucially relying
741on that C doesn't insert any padding anywhere in a pool_header at or before
742the prevpool member.
743**************************************************************************** */
744
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000745#define PTA(x) ((poolp )((uchar *)&(usedpools[2*(x)]) - 2*sizeof(block *)))
746#define PT(x) PTA(x), PTA(x)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000747
748static poolp usedpools[2 * ((NB_SMALL_SIZE_CLASSES + 7) / 8) * 8] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000749 PT(0), PT(1), PT(2), PT(3), PT(4), PT(5), PT(6), PT(7)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000750#if NB_SMALL_SIZE_CLASSES > 8
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000751 , PT(8), PT(9), PT(10), PT(11), PT(12), PT(13), PT(14), PT(15)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000752#if NB_SMALL_SIZE_CLASSES > 16
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000753 , PT(16), PT(17), PT(18), PT(19), PT(20), PT(21), PT(22), PT(23)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000754#if NB_SMALL_SIZE_CLASSES > 24
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000755 , PT(24), PT(25), PT(26), PT(27), PT(28), PT(29), PT(30), PT(31)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000756#if NB_SMALL_SIZE_CLASSES > 32
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000757 , PT(32), PT(33), PT(34), PT(35), PT(36), PT(37), PT(38), PT(39)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000758#if NB_SMALL_SIZE_CLASSES > 40
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000759 , PT(40), PT(41), PT(42), PT(43), PT(44), PT(45), PT(46), PT(47)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000760#if NB_SMALL_SIZE_CLASSES > 48
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000761 , PT(48), PT(49), PT(50), PT(51), PT(52), PT(53), PT(54), PT(55)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000762#if NB_SMALL_SIZE_CLASSES > 56
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000763 , PT(56), PT(57), PT(58), PT(59), PT(60), PT(61), PT(62), PT(63)
Antoine Pitrou6f26be02011-05-03 18:18:59 +0200764#if NB_SMALL_SIZE_CLASSES > 64
765#error "NB_SMALL_SIZE_CLASSES should be less than 64"
766#endif /* NB_SMALL_SIZE_CLASSES > 64 */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000767#endif /* NB_SMALL_SIZE_CLASSES > 56 */
768#endif /* NB_SMALL_SIZE_CLASSES > 48 */
769#endif /* NB_SMALL_SIZE_CLASSES > 40 */
770#endif /* NB_SMALL_SIZE_CLASSES > 32 */
771#endif /* NB_SMALL_SIZE_CLASSES > 24 */
772#endif /* NB_SMALL_SIZE_CLASSES > 16 */
773#endif /* NB_SMALL_SIZE_CLASSES > 8 */
774};
775
Thomas Woutersa9773292006-04-21 09:43:23 +0000776/*==========================================================================
777Arena management.
Neil Schemenauera35c6882001-02-27 04:45:05 +0000778
Thomas Woutersa9773292006-04-21 09:43:23 +0000779`arenas` is a vector of arena_objects. It contains maxarenas entries, some of
780which may not be currently used (== they're arena_objects that aren't
781currently associated with an allocated arena). Note that arenas proper are
782separately malloc'ed.
Neil Schemenauera35c6882001-02-27 04:45:05 +0000783
Thomas Woutersa9773292006-04-21 09:43:23 +0000784Prior to Python 2.5, arenas were never free()'ed. Starting with Python 2.5,
785we do try to free() arenas, and use some mild heuristic strategies to increase
786the likelihood that arenas eventually can be freed.
787
788unused_arena_objects
789
790 This is a singly-linked list of the arena_objects that are currently not
791 being used (no arena is associated with them). Objects are taken off the
792 head of the list in new_arena(), and are pushed on the head of the list in
793 PyObject_Free() when the arena is empty. Key invariant: an arena_object
794 is on this list if and only if its .address member is 0.
795
796usable_arenas
797
798 This is a doubly-linked list of the arena_objects associated with arenas
799 that have pools available. These pools are either waiting to be reused,
800 or have not been used before. The list is sorted to have the most-
801 allocated arenas first (ascending order based on the nfreepools member).
802 This means that the next allocation will come from a heavily used arena,
803 which gives the nearly empty arenas a chance to be returned to the system.
804 In my unscientific tests this dramatically improved the number of arenas
805 that could be freed.
806
807Note that an arena_object associated with an arena all of whose pools are
808currently in use isn't on either list.
809*/
810
811/* Array of objects used to track chunks of memory (arenas). */
812static struct arena_object* arenas = NULL;
813/* Number of slots currently allocated in the `arenas` vector. */
Tim Peters1d99af82002-03-30 10:35:09 +0000814static uint maxarenas = 0;
Tim Petersd97a1c02002-03-30 06:09:22 +0000815
Thomas Woutersa9773292006-04-21 09:43:23 +0000816/* The head of the singly-linked, NULL-terminated list of available
817 * arena_objects.
Tim Petersd97a1c02002-03-30 06:09:22 +0000818 */
Thomas Woutersa9773292006-04-21 09:43:23 +0000819static struct arena_object* unused_arena_objects = NULL;
820
821/* The head of the doubly-linked, NULL-terminated at each end, list of
822 * arena_objects associated with arenas that have pools available.
823 */
824static struct arena_object* usable_arenas = NULL;
825
826/* How many arena_objects do we initially allocate?
827 * 16 = can allocate 16 arenas = 16 * ARENA_SIZE = 4MB before growing the
828 * `arenas` vector.
829 */
830#define INITIAL_ARENA_OBJECTS 16
831
832/* Number of arenas allocated that haven't been free()'d. */
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000833static size_t narenas_currently_allocated = 0;
Thomas Woutersa9773292006-04-21 09:43:23 +0000834
Thomas Woutersa9773292006-04-21 09:43:23 +0000835/* Total number of times malloc() called to allocate an arena. */
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000836static size_t ntimes_arena_allocated = 0;
Thomas Woutersa9773292006-04-21 09:43:23 +0000837/* High water mark (max value ever seen) for narenas_currently_allocated. */
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000838static size_t narenas_highwater = 0;
Thomas Woutersa9773292006-04-21 09:43:23 +0000839
Antoine Pitrouf9d0b122012-12-09 14:28:26 +0100840static Py_ssize_t _Py_AllocatedBlocks = 0;
841
842Py_ssize_t
843_Py_GetAllocatedBlocks(void)
844{
845 return _Py_AllocatedBlocks;
846}
847
848
Thomas Woutersa9773292006-04-21 09:43:23 +0000849/* Allocate a new arena. If we run out of memory, return NULL. Else
850 * allocate a new arena, and return the address of an arena_object
851 * describing the new arena. It's expected that the caller will set
852 * `usable_arenas` to the return value.
853 */
854static struct arena_object*
Tim Petersd97a1c02002-03-30 06:09:22 +0000855new_arena(void)
856{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000857 struct arena_object* arenaobj;
858 uint excess; /* number of bytes above pool alignment */
Victor Stinnerba108822012-03-10 00:21:44 +0100859 void *address;
Tim Petersd97a1c02002-03-30 06:09:22 +0000860
Tim Peters0e871182002-04-13 08:29:14 +0000861#ifdef PYMALLOC_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 if (Py_GETENV("PYTHONMALLOCSTATS"))
David Malcolm49526f42012-06-22 14:55:41 -0400863 _PyObject_DebugMallocStats(stderr);
Tim Peters0e871182002-04-13 08:29:14 +0000864#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000865 if (unused_arena_objects == NULL) {
866 uint i;
867 uint numarenas;
868 size_t nbytes;
Tim Peters0e871182002-04-13 08:29:14 +0000869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000870 /* Double the number of arena objects on each allocation.
871 * Note that it's possible for `numarenas` to overflow.
872 */
873 numarenas = maxarenas ? maxarenas << 1 : INITIAL_ARENA_OBJECTS;
874 if (numarenas <= maxarenas)
875 return NULL; /* overflow */
Martin v. Löwis5aca8822008-09-11 06:55:48 +0000876#if SIZEOF_SIZE_T <= SIZEOF_INT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000877 if (numarenas > PY_SIZE_MAX / sizeof(*arenas))
878 return NULL; /* overflow */
Martin v. Löwis5aca8822008-09-11 06:55:48 +0000879#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 nbytes = numarenas * sizeof(*arenas);
Victor Stinner0507bf52013-07-07 02:05:46 +0200881 arenaobj = (struct arena_object *)PyMem_Realloc(arenas, nbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 if (arenaobj == NULL)
883 return NULL;
884 arenas = arenaobj;
Thomas Woutersa9773292006-04-21 09:43:23 +0000885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 /* We might need to fix pointers that were copied. However,
887 * new_arena only gets called when all the pages in the
888 * previous arenas are full. Thus, there are *no* pointers
889 * into the old array. Thus, we don't have to worry about
890 * invalid pointers. Just to be sure, some asserts:
891 */
892 assert(usable_arenas == NULL);
893 assert(unused_arena_objects == NULL);
Thomas Woutersa9773292006-04-21 09:43:23 +0000894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000895 /* Put the new arenas on the unused_arena_objects list. */
896 for (i = maxarenas; i < numarenas; ++i) {
897 arenas[i].address = 0; /* mark as unassociated */
898 arenas[i].nextarena = i < numarenas - 1 ?
899 &arenas[i+1] : NULL;
900 }
Thomas Woutersa9773292006-04-21 09:43:23 +0000901
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000902 /* Update globals. */
903 unused_arena_objects = &arenas[maxarenas];
904 maxarenas = numarenas;
905 }
Tim Petersd97a1c02002-03-30 06:09:22 +0000906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 /* Take the next available arena object off the head of the list. */
908 assert(unused_arena_objects != NULL);
909 arenaobj = unused_arena_objects;
910 unused_arena_objects = arenaobj->nextarena;
911 assert(arenaobj->address == 0);
Victor Stinner0507bf52013-07-07 02:05:46 +0200912 address = _PyObject_Arena.alloc(_PyObject_Arena.ctx, ARENA_SIZE);
913 if (address == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 /* The allocation failed: return NULL after putting the
915 * arenaobj back.
916 */
917 arenaobj->nextarena = unused_arena_objects;
918 unused_arena_objects = arenaobj;
919 return NULL;
920 }
Victor Stinnerba108822012-03-10 00:21:44 +0100921 arenaobj->address = (uptr)address;
Tim Petersd97a1c02002-03-30 06:09:22 +0000922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000923 ++narenas_currently_allocated;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 ++ntimes_arena_allocated;
925 if (narenas_currently_allocated > narenas_highwater)
926 narenas_highwater = narenas_currently_allocated;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000927 arenaobj->freepools = NULL;
928 /* pool_address <- first pool-aligned address in the arena
929 nfreepools <- number of whole pools that fit after alignment */
930 arenaobj->pool_address = (block*)arenaobj->address;
931 arenaobj->nfreepools = ARENA_SIZE / POOL_SIZE;
932 assert(POOL_SIZE * arenaobj->nfreepools == ARENA_SIZE);
933 excess = (uint)(arenaobj->address & POOL_SIZE_MASK);
934 if (excess != 0) {
935 --arenaobj->nfreepools;
936 arenaobj->pool_address += POOL_SIZE - excess;
937 }
938 arenaobj->ntotalpools = arenaobj->nfreepools;
Thomas Woutersa9773292006-04-21 09:43:23 +0000939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 return arenaobj;
Tim Petersd97a1c02002-03-30 06:09:22 +0000941}
942
Thomas Woutersa9773292006-04-21 09:43:23 +0000943/*
944Py_ADDRESS_IN_RANGE(P, POOL)
945
946Return true if and only if P is an address that was allocated by pymalloc.
947POOL must be the pool address associated with P, i.e., POOL = POOL_ADDR(P)
948(the caller is asked to compute this because the macro expands POOL more than
949once, and for efficiency it's best for the caller to assign POOL_ADDR(P) to a
950variable and pass the latter to the macro; because Py_ADDRESS_IN_RANGE is
951called on every alloc/realloc/free, micro-efficiency is important here).
952
953Tricky: Let B be the arena base address associated with the pool, B =
954arenas[(POOL)->arenaindex].address. Then P belongs to the arena if and only if
955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000956 B <= P < B + ARENA_SIZE
Thomas Woutersa9773292006-04-21 09:43:23 +0000957
958Subtracting B throughout, this is true iff
959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 0 <= P-B < ARENA_SIZE
Thomas Woutersa9773292006-04-21 09:43:23 +0000961
962By using unsigned arithmetic, the "0 <=" half of the test can be skipped.
963
964Obscure: A PyMem "free memory" function can call the pymalloc free or realloc
965before the first arena has been allocated. `arenas` is still NULL in that
966case. We're relying on that maxarenas is also 0 in that case, so that
967(POOL)->arenaindex < maxarenas must be false, saving us from trying to index
968into a NULL arenas.
969
970Details: given P and POOL, the arena_object corresponding to P is AO =
971arenas[(POOL)->arenaindex]. Suppose obmalloc controls P. Then (barring wild
972stores, etc), POOL is the correct address of P's pool, AO.address is the
973correct base address of the pool's arena, and P must be within ARENA_SIZE of
974AO.address. In addition, AO.address is not 0 (no arena can start at address 0
975(NULL)). Therefore Py_ADDRESS_IN_RANGE correctly reports that obmalloc
976controls P.
977
978Now suppose obmalloc does not control P (e.g., P was obtained via a direct
979call to the system malloc() or realloc()). (POOL)->arenaindex may be anything
980in this case -- it may even be uninitialized trash. If the trash arenaindex
981is >= maxarenas, the macro correctly concludes at once that obmalloc doesn't
982control P.
983
984Else arenaindex is < maxarena, and AO is read up. If AO corresponds to an
985allocated arena, obmalloc controls all the memory in slice AO.address :
986AO.address+ARENA_SIZE. By case assumption, P is not controlled by obmalloc,
987so P doesn't lie in that slice, so the macro correctly reports that P is not
988controlled by obmalloc.
989
990Finally, if P is not controlled by obmalloc and AO corresponds to an unused
991arena_object (one not currently associated with an allocated arena),
992AO.address is 0, and the second test in the macro reduces to:
993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000994 P < ARENA_SIZE
Thomas Woutersa9773292006-04-21 09:43:23 +0000995
996If P >= ARENA_SIZE (extremely likely), the macro again correctly concludes
997that P is not controlled by obmalloc. However, if P < ARENA_SIZE, this part
998of the test still passes, and the third clause (AO.address != 0) is necessary
999to get the correct result: AO.address is 0 in this case, so the macro
1000correctly reports that P is not controlled by obmalloc (despite that P lies in
1001slice AO.address : AO.address + ARENA_SIZE).
1002
1003Note: The third (AO.address != 0) clause was added in Python 2.5. Before
10042.5, arenas were never free()'ed, and an arenaindex < maxarena always
1005corresponded to a currently-allocated arena, so the "P is not controlled by
1006obmalloc, AO corresponds to an unused arena_object, and P < ARENA_SIZE" case
1007was impossible.
1008
1009Note that the logic is excruciating, and reading up possibly uninitialized
1010memory when P is not controlled by obmalloc (to get at (POOL)->arenaindex)
1011creates problems for some memory debuggers. The overwhelming advantage is
1012that this test determines whether an arbitrary address is controlled by
1013obmalloc in a small constant time, independent of the number of arenas
1014obmalloc controls. Since this test is needed at every entry point, it's
1015extremely desirable that it be this fast.
Antoine Pitroub7fb2e22011-01-07 21:43:59 +00001016
1017Since Py_ADDRESS_IN_RANGE may be reading from memory which was not allocated
1018by Python, it is important that (POOL)->arenaindex is read only once, as
1019another thread may be concurrently modifying the value without holding the
1020GIL. To accomplish this, the arenaindex_temp variable is used to store
1021(POOL)->arenaindex for the duration of the Py_ADDRESS_IN_RANGE macro's
1022execution. The caller of the macro is responsible for declaring this
1023variable.
Thomas Woutersa9773292006-04-21 09:43:23 +00001024*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001025#define Py_ADDRESS_IN_RANGE(P, POOL) \
Antoine Pitroub7fb2e22011-01-07 21:43:59 +00001026 ((arenaindex_temp = (POOL)->arenaindex) < maxarenas && \
1027 (uptr)(P) - arenas[arenaindex_temp].address < (uptr)ARENA_SIZE && \
1028 arenas[arenaindex_temp].address != 0)
Thomas Woutersa9773292006-04-21 09:43:23 +00001029
Neal Norwitz7eb3c912004-06-06 19:20:22 +00001030
1031/* This is only useful when running memory debuggers such as
1032 * Purify or Valgrind. Uncomment to use.
1033 *
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001034#define Py_USING_MEMORY_DEBUGGER
Martin v. Löwis6fea2332008-09-25 04:15:27 +00001035 */
Neal Norwitz7eb3c912004-06-06 19:20:22 +00001036
1037#ifdef Py_USING_MEMORY_DEBUGGER
1038
1039/* Py_ADDRESS_IN_RANGE may access uninitialized memory by design
1040 * This leads to thousands of spurious warnings when using
1041 * Purify or Valgrind. By making a function, we can easily
1042 * suppress the uninitialized memory reads in this one function.
1043 * So we won't ignore real errors elsewhere.
1044 *
1045 * Disable the macro and use a function.
1046 */
1047
1048#undef Py_ADDRESS_IN_RANGE
1049
Thomas Wouters89f507f2006-12-13 04:49:30 +00001050#if defined(__GNUC__) && ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 1) || \
Stefan Krah735bb122010-11-26 10:54:09 +00001051 (__GNUC__ >= 4))
Neal Norwitze5e5aa42005-11-13 18:55:39 +00001052#define Py_NO_INLINE __attribute__((__noinline__))
1053#else
1054#define Py_NO_INLINE
1055#endif
1056
1057/* Don't make static, to try to ensure this isn't inlined. */
1058int Py_ADDRESS_IN_RANGE(void *P, poolp pool) Py_NO_INLINE;
1059#undef Py_NO_INLINE
Neal Norwitz7eb3c912004-06-06 19:20:22 +00001060#endif
Tim Peters338e0102002-04-01 19:23:44 +00001061
Neil Schemenauera35c6882001-02-27 04:45:05 +00001062/*==========================================================================*/
1063
Tim Peters84c1b972002-04-04 04:44:32 +00001064/* malloc. Note that nbytes==0 tries to return a non-NULL pointer, distinct
1065 * from all other currently live pointers. This may not be possible.
1066 */
Neil Schemenauera35c6882001-02-27 04:45:05 +00001067
1068/*
1069 * The basic blocks are ordered by decreasing execution frequency,
1070 * which minimizes the number of jumps in the most common cases,
1071 * improves branching prediction and instruction scheduling (small
1072 * block allocations typically result in a couple of instructions).
1073 * Unless the optimizer reorders everything, being too smart...
1074 */
1075
Victor Stinner0507bf52013-07-07 02:05:46 +02001076static void *
1077_PyObject_Malloc(void *ctx, size_t nbytes)
Neil Schemenauera35c6882001-02-27 04:45:05 +00001078{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001079 block *bp;
1080 poolp pool;
1081 poolp next;
1082 uint size;
Neil Schemenauera35c6882001-02-27 04:45:05 +00001083
Antoine Pitrou0aaaa622013-04-06 01:15:30 +02001084 _Py_AllocatedBlocks++;
1085
Benjamin Peterson05159c42009-12-03 03:01:27 +00001086#ifdef WITH_VALGRIND
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001087 if (UNLIKELY(running_on_valgrind == -1))
1088 running_on_valgrind = RUNNING_ON_VALGRIND;
1089 if (UNLIKELY(running_on_valgrind))
1090 goto redirect;
Benjamin Peterson05159c42009-12-03 03:01:27 +00001091#endif
1092
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001093 /*
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001094 * This implicitly redirects malloc(0).
1095 */
1096 if ((nbytes - 1) < SMALL_REQUEST_THRESHOLD) {
1097 LOCK();
1098 /*
1099 * Most frequent paths first
1100 */
1101 size = (uint)(nbytes - 1) >> ALIGNMENT_SHIFT;
1102 pool = usedpools[size + size];
1103 if (pool != pool->nextpool) {
1104 /*
1105 * There is a used pool for this size class.
1106 * Pick up the head block of its free list.
1107 */
1108 ++pool->ref.count;
1109 bp = pool->freeblock;
1110 assert(bp != NULL);
1111 if ((pool->freeblock = *(block **)bp) != NULL) {
1112 UNLOCK();
1113 return (void *)bp;
1114 }
1115 /*
1116 * Reached the end of the free list, try to extend it.
1117 */
1118 if (pool->nextoffset <= pool->maxnextoffset) {
1119 /* There is room for another block. */
1120 pool->freeblock = (block*)pool +
1121 pool->nextoffset;
1122 pool->nextoffset += INDEX2SIZE(size);
1123 *(block **)(pool->freeblock) = NULL;
1124 UNLOCK();
1125 return (void *)bp;
1126 }
1127 /* Pool is full, unlink from used pools. */
1128 next = pool->nextpool;
1129 pool = pool->prevpool;
1130 next->prevpool = pool;
1131 pool->nextpool = next;
1132 UNLOCK();
1133 return (void *)bp;
1134 }
Thomas Woutersa9773292006-04-21 09:43:23 +00001135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136 /* There isn't a pool of the right size class immediately
1137 * available: use a free pool.
1138 */
1139 if (usable_arenas == NULL) {
1140 /* No arena has a free pool: allocate a new arena. */
Thomas Woutersa9773292006-04-21 09:43:23 +00001141#ifdef WITH_MEMORY_LIMITS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142 if (narenas_currently_allocated >= MAX_ARENAS) {
1143 UNLOCK();
1144 goto redirect;
1145 }
Thomas Woutersa9773292006-04-21 09:43:23 +00001146#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001147 usable_arenas = new_arena();
1148 if (usable_arenas == NULL) {
1149 UNLOCK();
1150 goto redirect;
1151 }
1152 usable_arenas->nextarena =
1153 usable_arenas->prevarena = NULL;
1154 }
1155 assert(usable_arenas->address != 0);
Thomas Woutersa9773292006-04-21 09:43:23 +00001156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001157 /* Try to get a cached free pool. */
1158 pool = usable_arenas->freepools;
1159 if (pool != NULL) {
1160 /* Unlink from cached pools. */
1161 usable_arenas->freepools = pool->nextpool;
Thomas Woutersa9773292006-04-21 09:43:23 +00001162
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001163 /* This arena already had the smallest nfreepools
1164 * value, so decreasing nfreepools doesn't change
1165 * that, and we don't need to rearrange the
1166 * usable_arenas list. However, if the arena has
1167 * become wholly allocated, we need to remove its
1168 * arena_object from usable_arenas.
1169 */
1170 --usable_arenas->nfreepools;
1171 if (usable_arenas->nfreepools == 0) {
1172 /* Wholly allocated: remove. */
1173 assert(usable_arenas->freepools == NULL);
1174 assert(usable_arenas->nextarena == NULL ||
1175 usable_arenas->nextarena->prevarena ==
1176 usable_arenas);
Thomas Woutersa9773292006-04-21 09:43:23 +00001177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001178 usable_arenas = usable_arenas->nextarena;
1179 if (usable_arenas != NULL) {
1180 usable_arenas->prevarena = NULL;
1181 assert(usable_arenas->address != 0);
1182 }
1183 }
1184 else {
1185 /* nfreepools > 0: it must be that freepools
1186 * isn't NULL, or that we haven't yet carved
1187 * off all the arena's pools for the first
1188 * time.
1189 */
1190 assert(usable_arenas->freepools != NULL ||
1191 usable_arenas->pool_address <=
1192 (block*)usable_arenas->address +
1193 ARENA_SIZE - POOL_SIZE);
1194 }
1195 init_pool:
1196 /* Frontlink to used pools. */
1197 next = usedpools[size + size]; /* == prev */
1198 pool->nextpool = next;
1199 pool->prevpool = next;
1200 next->nextpool = pool;
1201 next->prevpool = pool;
1202 pool->ref.count = 1;
1203 if (pool->szidx == size) {
1204 /* Luckily, this pool last contained blocks
1205 * of the same size class, so its header
1206 * and free list are already initialized.
1207 */
1208 bp = pool->freeblock;
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001209 assert(bp != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001210 pool->freeblock = *(block **)bp;
1211 UNLOCK();
1212 return (void *)bp;
1213 }
1214 /*
1215 * Initialize the pool header, set up the free list to
1216 * contain just the second block, and return the first
1217 * block.
1218 */
1219 pool->szidx = size;
1220 size = INDEX2SIZE(size);
1221 bp = (block *)pool + POOL_OVERHEAD;
1222 pool->nextoffset = POOL_OVERHEAD + (size << 1);
1223 pool->maxnextoffset = POOL_SIZE - size;
1224 pool->freeblock = bp + size;
1225 *(block **)(pool->freeblock) = NULL;
1226 UNLOCK();
1227 return (void *)bp;
1228 }
Thomas Woutersa9773292006-04-21 09:43:23 +00001229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001230 /* Carve off a new pool. */
1231 assert(usable_arenas->nfreepools > 0);
1232 assert(usable_arenas->freepools == NULL);
1233 pool = (poolp)usable_arenas->pool_address;
1234 assert((block*)pool <= (block*)usable_arenas->address +
1235 ARENA_SIZE - POOL_SIZE);
1236 pool->arenaindex = usable_arenas - arenas;
1237 assert(&arenas[pool->arenaindex] == usable_arenas);
1238 pool->szidx = DUMMY_SIZE_IDX;
1239 usable_arenas->pool_address += POOL_SIZE;
1240 --usable_arenas->nfreepools;
Thomas Woutersa9773292006-04-21 09:43:23 +00001241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001242 if (usable_arenas->nfreepools == 0) {
1243 assert(usable_arenas->nextarena == NULL ||
1244 usable_arenas->nextarena->prevarena ==
1245 usable_arenas);
1246 /* Unlink the arena: it is completely allocated. */
1247 usable_arenas = usable_arenas->nextarena;
1248 if (usable_arenas != NULL) {
1249 usable_arenas->prevarena = NULL;
1250 assert(usable_arenas->address != 0);
1251 }
1252 }
Thomas Woutersa9773292006-04-21 09:43:23 +00001253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001254 goto init_pool;
1255 }
Neil Schemenauera35c6882001-02-27 04:45:05 +00001256
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001257 /* The small block allocator ends here. */
Neil Schemenauera35c6882001-02-27 04:45:05 +00001258
Tim Petersd97a1c02002-03-30 06:09:22 +00001259redirect:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001260 /* Redirect the original request to the underlying (libc) allocator.
1261 * We jump here on bigger requests, on error in the code above (as a
1262 * last chance to serve the request) or when the max memory limit
1263 * has been reached.
1264 */
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001265 {
Victor Stinner0507bf52013-07-07 02:05:46 +02001266 void *result = PyMem_Malloc(nbytes);
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001267 if (!result)
1268 _Py_AllocatedBlocks--;
1269 return result;
1270 }
Neil Schemenauera35c6882001-02-27 04:45:05 +00001271}
1272
1273/* free */
1274
Victor Stinner0507bf52013-07-07 02:05:46 +02001275static void
1276_PyObject_Free(void *ctx, void *p)
Neil Schemenauera35c6882001-02-27 04:45:05 +00001277{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001278 poolp pool;
1279 block *lastfree;
1280 poolp next, prev;
1281 uint size;
Antoine Pitroub7fb2e22011-01-07 21:43:59 +00001282#ifndef Py_USING_MEMORY_DEBUGGER
1283 uint arenaindex_temp;
1284#endif
Neil Schemenauera35c6882001-02-27 04:45:05 +00001285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001286 if (p == NULL) /* free(NULL) has no effect */
1287 return;
Neil Schemenauera35c6882001-02-27 04:45:05 +00001288
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001289 _Py_AllocatedBlocks--;
1290
Benjamin Peterson05159c42009-12-03 03:01:27 +00001291#ifdef WITH_VALGRIND
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001292 if (UNLIKELY(running_on_valgrind > 0))
1293 goto redirect;
Benjamin Peterson05159c42009-12-03 03:01:27 +00001294#endif
1295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001296 pool = POOL_ADDR(p);
1297 if (Py_ADDRESS_IN_RANGE(p, pool)) {
1298 /* We allocated this address. */
1299 LOCK();
1300 /* Link p to the start of the pool's freeblock list. Since
1301 * the pool had at least the p block outstanding, the pool
1302 * wasn't empty (so it's already in a usedpools[] list, or
1303 * was full and is in no list -- it's not in the freeblocks
1304 * list in any case).
1305 */
1306 assert(pool->ref.count > 0); /* else it was empty */
1307 *(block **)p = lastfree = pool->freeblock;
1308 pool->freeblock = (block *)p;
1309 if (lastfree) {
1310 struct arena_object* ao;
1311 uint nf; /* ao->nfreepools */
Thomas Woutersa9773292006-04-21 09:43:23 +00001312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001313 /* freeblock wasn't NULL, so the pool wasn't full,
1314 * and the pool is in a usedpools[] list.
1315 */
1316 if (--pool->ref.count != 0) {
1317 /* pool isn't empty: leave it in usedpools */
1318 UNLOCK();
1319 return;
1320 }
1321 /* Pool is now empty: unlink from usedpools, and
1322 * link to the front of freepools. This ensures that
1323 * previously freed pools will be allocated later
1324 * (being not referenced, they are perhaps paged out).
1325 */
1326 next = pool->nextpool;
1327 prev = pool->prevpool;
1328 next->prevpool = prev;
1329 prev->nextpool = next;
Thomas Woutersa9773292006-04-21 09:43:23 +00001330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001331 /* Link the pool to freepools. This is a singly-linked
1332 * list, and pool->prevpool isn't used there.
1333 */
1334 ao = &arenas[pool->arenaindex];
1335 pool->nextpool = ao->freepools;
1336 ao->freepools = pool;
1337 nf = ++ao->nfreepools;
Thomas Woutersa9773292006-04-21 09:43:23 +00001338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001339 /* All the rest is arena management. We just freed
1340 * a pool, and there are 4 cases for arena mgmt:
1341 * 1. If all the pools are free, return the arena to
1342 * the system free().
1343 * 2. If this is the only free pool in the arena,
1344 * add the arena back to the `usable_arenas` list.
1345 * 3. If the "next" arena has a smaller count of free
1346 * pools, we have to "slide this arena right" to
1347 * restore that usable_arenas is sorted in order of
1348 * nfreepools.
1349 * 4. Else there's nothing more to do.
1350 */
1351 if (nf == ao->ntotalpools) {
1352 /* Case 1. First unlink ao from usable_arenas.
1353 */
1354 assert(ao->prevarena == NULL ||
1355 ao->prevarena->address != 0);
1356 assert(ao ->nextarena == NULL ||
1357 ao->nextarena->address != 0);
Thomas Woutersa9773292006-04-21 09:43:23 +00001358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001359 /* Fix the pointer in the prevarena, or the
1360 * usable_arenas pointer.
1361 */
1362 if (ao->prevarena == NULL) {
1363 usable_arenas = ao->nextarena;
1364 assert(usable_arenas == NULL ||
1365 usable_arenas->address != 0);
1366 }
1367 else {
1368 assert(ao->prevarena->nextarena == ao);
1369 ao->prevarena->nextarena =
1370 ao->nextarena;
1371 }
1372 /* Fix the pointer in the nextarena. */
1373 if (ao->nextarena != NULL) {
1374 assert(ao->nextarena->prevarena == ao);
1375 ao->nextarena->prevarena =
1376 ao->prevarena;
1377 }
1378 /* Record that this arena_object slot is
1379 * available to be reused.
1380 */
1381 ao->nextarena = unused_arena_objects;
1382 unused_arena_objects = ao;
Thomas Woutersa9773292006-04-21 09:43:23 +00001383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001384 /* Free the entire arena. */
Victor Stinner0507bf52013-07-07 02:05:46 +02001385 _PyObject_Arena.free(_PyObject_Arena.ctx,
1386 (void *)ao->address, ARENA_SIZE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001387 ao->address = 0; /* mark unassociated */
1388 --narenas_currently_allocated;
Thomas Woutersa9773292006-04-21 09:43:23 +00001389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001390 UNLOCK();
1391 return;
1392 }
1393 if (nf == 1) {
1394 /* Case 2. Put ao at the head of
1395 * usable_arenas. Note that because
1396 * ao->nfreepools was 0 before, ao isn't
1397 * currently on the usable_arenas list.
1398 */
1399 ao->nextarena = usable_arenas;
1400 ao->prevarena = NULL;
1401 if (usable_arenas)
1402 usable_arenas->prevarena = ao;
1403 usable_arenas = ao;
1404 assert(usable_arenas->address != 0);
Thomas Woutersa9773292006-04-21 09:43:23 +00001405
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001406 UNLOCK();
1407 return;
1408 }
1409 /* If this arena is now out of order, we need to keep
1410 * the list sorted. The list is kept sorted so that
1411 * the "most full" arenas are used first, which allows
1412 * the nearly empty arenas to be completely freed. In
1413 * a few un-scientific tests, it seems like this
1414 * approach allowed a lot more memory to be freed.
1415 */
1416 if (ao->nextarena == NULL ||
1417 nf <= ao->nextarena->nfreepools) {
1418 /* Case 4. Nothing to do. */
1419 UNLOCK();
1420 return;
1421 }
1422 /* Case 3: We have to move the arena towards the end
1423 * of the list, because it has more free pools than
1424 * the arena to its right.
1425 * First unlink ao from usable_arenas.
1426 */
1427 if (ao->prevarena != NULL) {
1428 /* ao isn't at the head of the list */
1429 assert(ao->prevarena->nextarena == ao);
1430 ao->prevarena->nextarena = ao->nextarena;
1431 }
1432 else {
1433 /* ao is at the head of the list */
1434 assert(usable_arenas == ao);
1435 usable_arenas = ao->nextarena;
1436 }
1437 ao->nextarena->prevarena = ao->prevarena;
Thomas Woutersa9773292006-04-21 09:43:23 +00001438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001439 /* Locate the new insertion point by iterating over
1440 * the list, using our nextarena pointer.
1441 */
1442 while (ao->nextarena != NULL &&
1443 nf > ao->nextarena->nfreepools) {
1444 ao->prevarena = ao->nextarena;
1445 ao->nextarena = ao->nextarena->nextarena;
1446 }
Thomas Woutersa9773292006-04-21 09:43:23 +00001447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001448 /* Insert ao at this point. */
1449 assert(ao->nextarena == NULL ||
1450 ao->prevarena == ao->nextarena->prevarena);
1451 assert(ao->prevarena->nextarena == ao->nextarena);
Thomas Woutersa9773292006-04-21 09:43:23 +00001452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001453 ao->prevarena->nextarena = ao;
1454 if (ao->nextarena != NULL)
1455 ao->nextarena->prevarena = ao;
Thomas Woutersa9773292006-04-21 09:43:23 +00001456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001457 /* Verify that the swaps worked. */
1458 assert(ao->nextarena == NULL ||
1459 nf <= ao->nextarena->nfreepools);
1460 assert(ao->prevarena == NULL ||
1461 nf > ao->prevarena->nfreepools);
1462 assert(ao->nextarena == NULL ||
1463 ao->nextarena->prevarena == ao);
1464 assert((usable_arenas == ao &&
1465 ao->prevarena == NULL) ||
1466 ao->prevarena->nextarena == ao);
Thomas Woutersa9773292006-04-21 09:43:23 +00001467
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001468 UNLOCK();
1469 return;
1470 }
1471 /* Pool was full, so doesn't currently live in any list:
1472 * link it to the front of the appropriate usedpools[] list.
1473 * This mimics LRU pool usage for new allocations and
1474 * targets optimal filling when several pools contain
1475 * blocks of the same size class.
1476 */
1477 --pool->ref.count;
1478 assert(pool->ref.count > 0); /* else the pool is empty */
1479 size = pool->szidx;
1480 next = usedpools[size + size];
1481 prev = next->prevpool;
1482 /* insert pool before next: prev <-> pool <-> next */
1483 pool->nextpool = next;
1484 pool->prevpool = prev;
1485 next->prevpool = pool;
1486 prev->nextpool = pool;
1487 UNLOCK();
1488 return;
1489 }
Neil Schemenauera35c6882001-02-27 04:45:05 +00001490
Benjamin Peterson05159c42009-12-03 03:01:27 +00001491#ifdef WITH_VALGRIND
1492redirect:
1493#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001494 /* We didn't allocate this address. */
Victor Stinner0507bf52013-07-07 02:05:46 +02001495 PyMem_Free(p);
Neil Schemenauera35c6882001-02-27 04:45:05 +00001496}
1497
Tim Peters84c1b972002-04-04 04:44:32 +00001498/* realloc. If p is NULL, this acts like malloc(nbytes). Else if nbytes==0,
1499 * then as the Python docs promise, we do not treat this like free(p), and
1500 * return a non-NULL result.
1501 */
Neil Schemenauera35c6882001-02-27 04:45:05 +00001502
Victor Stinner0507bf52013-07-07 02:05:46 +02001503static void *
1504_PyObject_Realloc(void *ctx, void *p, size_t nbytes)
Neil Schemenauera35c6882001-02-27 04:45:05 +00001505{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001506 void *bp;
1507 poolp pool;
1508 size_t size;
Antoine Pitroub7fb2e22011-01-07 21:43:59 +00001509#ifndef Py_USING_MEMORY_DEBUGGER
1510 uint arenaindex_temp;
1511#endif
Neil Schemenauera35c6882001-02-27 04:45:05 +00001512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001513 if (p == NULL)
Victor Stinner0507bf52013-07-07 02:05:46 +02001514 return _PyObject_Malloc(ctx, nbytes);
Georg Brandld492ad82008-07-23 16:13:07 +00001515
Benjamin Peterson05159c42009-12-03 03:01:27 +00001516#ifdef WITH_VALGRIND
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001517 /* Treat running_on_valgrind == -1 the same as 0 */
1518 if (UNLIKELY(running_on_valgrind > 0))
1519 goto redirect;
Benjamin Peterson05159c42009-12-03 03:01:27 +00001520#endif
1521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001522 pool = POOL_ADDR(p);
1523 if (Py_ADDRESS_IN_RANGE(p, pool)) {
1524 /* We're in charge of this block */
1525 size = INDEX2SIZE(pool->szidx);
1526 if (nbytes <= size) {
1527 /* The block is staying the same or shrinking. If
1528 * it's shrinking, there's a tradeoff: it costs
1529 * cycles to copy the block to a smaller size class,
1530 * but it wastes memory not to copy it. The
1531 * compromise here is to copy on shrink only if at
1532 * least 25% of size can be shaved off.
1533 */
1534 if (4 * nbytes > 3 * size) {
1535 /* It's the same,
1536 * or shrinking and new/old > 3/4.
1537 */
1538 return p;
1539 }
1540 size = nbytes;
1541 }
Victor Stinner0507bf52013-07-07 02:05:46 +02001542 bp = _PyObject_Malloc(ctx, nbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001543 if (bp != NULL) {
1544 memcpy(bp, p, size);
Victor Stinner0507bf52013-07-07 02:05:46 +02001545 _PyObject_Free(ctx, p);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001546 }
1547 return bp;
1548 }
Benjamin Peterson05159c42009-12-03 03:01:27 +00001549#ifdef WITH_VALGRIND
1550 redirect:
1551#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001552 /* We're not managing this block. If nbytes <=
1553 * SMALL_REQUEST_THRESHOLD, it's tempting to try to take over this
1554 * block. However, if we do, we need to copy the valid data from
1555 * the C-managed block to one of our blocks, and there's no portable
1556 * way to know how much of the memory space starting at p is valid.
1557 * As bug 1185883 pointed out the hard way, it's possible that the
1558 * C-managed block is "at the end" of allocated VM space, so that
1559 * a memory fault can occur if we try to copy nbytes bytes starting
1560 * at p. Instead we punt: let C continue to manage this block.
1561 */
1562 if (nbytes)
Victor Stinner0507bf52013-07-07 02:05:46 +02001563 return PyMem_Realloc(p, nbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001564 /* C doesn't define the result of realloc(p, 0) (it may or may not
1565 * return NULL then), but Python's docs promise that nbytes==0 never
1566 * returns NULL. We don't pass 0 to realloc(), to avoid that endcase
1567 * to begin with. Even then, we can't be sure that realloc() won't
1568 * return NULL.
1569 */
Victor Stinner0507bf52013-07-07 02:05:46 +02001570 bp = PyMem_Realloc(p, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001571 return bp ? bp : p;
Neil Schemenauera35c6882001-02-27 04:45:05 +00001572}
1573
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001574#else /* ! WITH_PYMALLOC */
Tim Petersddea2082002-03-23 10:03:50 +00001575
1576/*==========================================================================*/
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00001577/* pymalloc not enabled: Redirect the entry points to malloc. These will
1578 * only be used by extensions that are compiled with pymalloc enabled. */
Tim Peters62c06ba2002-03-23 22:28:18 +00001579
Antoine Pitrou92840532012-12-17 23:05:59 +01001580Py_ssize_t
1581_Py_GetAllocatedBlocks(void)
1582{
1583 return 0;
1584}
1585
Tim Peters1221c0a2002-03-23 00:20:15 +00001586#endif /* WITH_PYMALLOC */
1587
Tim Petersddea2082002-03-23 10:03:50 +00001588#ifdef PYMALLOC_DEBUG
1589/*==========================================================================*/
Tim Peters62c06ba2002-03-23 22:28:18 +00001590/* A x-platform debugging allocator. This doesn't manage memory directly,
1591 * it wraps a real allocator, adding extra debugging info to the memory blocks.
1592 */
Tim Petersddea2082002-03-23 10:03:50 +00001593
Tim Petersf6fb5012002-04-12 07:38:53 +00001594/* Special bytes broadcast into debug memory blocks at appropriate times.
1595 * Strings of these are unlikely to be valid addresses, floats, ints or
1596 * 7-bit ASCII.
1597 */
1598#undef CLEANBYTE
1599#undef DEADBYTE
1600#undef FORBIDDENBYTE
1601#define CLEANBYTE 0xCB /* clean (newly allocated) memory */
Tim Peters889f61d2002-07-10 19:29:49 +00001602#define DEADBYTE 0xDB /* dead (newly freed) memory */
Tim Petersf6fb5012002-04-12 07:38:53 +00001603#define FORBIDDENBYTE 0xFB /* untouchable bytes at each end of a block */
Tim Petersddea2082002-03-23 10:03:50 +00001604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001605static size_t serialno = 0; /* incremented on each debug {m,re}alloc */
Tim Petersddea2082002-03-23 10:03:50 +00001606
Tim Peterse0850172002-03-24 00:34:21 +00001607/* serialno is always incremented via calling this routine. The point is
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001608 * to supply a single place to set a breakpoint.
1609 */
Tim Peterse0850172002-03-24 00:34:21 +00001610static void
Neil Schemenauerbd02b142002-03-28 21:05:38 +00001611bumpserialno(void)
Tim Peterse0850172002-03-24 00:34:21 +00001612{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001613 ++serialno;
Tim Peterse0850172002-03-24 00:34:21 +00001614}
1615
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001616#define SST SIZEOF_SIZE_T
Tim Peterse0850172002-03-24 00:34:21 +00001617
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001618/* Read sizeof(size_t) bytes at p as a big-endian size_t. */
1619static size_t
1620read_size_t(const void *p)
Tim Petersddea2082002-03-23 10:03:50 +00001621{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001622 const uchar *q = (const uchar *)p;
1623 size_t result = *q++;
1624 int i;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001626 for (i = SST; --i > 0; ++q)
1627 result = (result << 8) | *q;
1628 return result;
Tim Petersddea2082002-03-23 10:03:50 +00001629}
1630
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001631/* Write n as a big-endian size_t, MSB at address p, LSB at
1632 * p + sizeof(size_t) - 1.
1633 */
Tim Petersddea2082002-03-23 10:03:50 +00001634static void
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001635write_size_t(void *p, size_t n)
Tim Petersddea2082002-03-23 10:03:50 +00001636{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001637 uchar *q = (uchar *)p + SST - 1;
1638 int i;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001640 for (i = SST; --i >= 0; --q) {
1641 *q = (uchar)(n & 0xff);
1642 n >>= 8;
1643 }
Tim Petersddea2082002-03-23 10:03:50 +00001644}
1645
Tim Peters08d82152002-04-18 22:25:03 +00001646#ifdef Py_DEBUG
1647/* Is target in the list? The list is traversed via the nextpool pointers.
1648 * The list may be NULL-terminated, or circular. Return 1 if target is in
1649 * list, else 0.
1650 */
1651static int
1652pool_is_in_list(const poolp target, poolp list)
1653{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001654 poolp origlist = list;
1655 assert(target != NULL);
1656 if (list == NULL)
1657 return 0;
1658 do {
1659 if (target == list)
1660 return 1;
1661 list = list->nextpool;
1662 } while (list != NULL && list != origlist);
1663 return 0;
Tim Peters08d82152002-04-18 22:25:03 +00001664}
1665
1666#else
1667#define pool_is_in_list(X, Y) 1
1668
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001669#endif /* Py_DEBUG */
Tim Peters08d82152002-04-18 22:25:03 +00001670
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001671/* Let S = sizeof(size_t). The debug malloc asks for 4*S extra bytes and
1672 fills them with useful stuff, here calling the underlying malloc's result p:
Tim Petersddea2082002-03-23 10:03:50 +00001673
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001674p[0: S]
1675 Number of bytes originally asked for. This is a size_t, big-endian (easier
1676 to read in a memory dump).
1677p[S: 2*S]
Tim Petersf6fb5012002-04-12 07:38:53 +00001678 Copies of FORBIDDENBYTE. Used to catch under- writes and reads.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001679p[2*S: 2*S+n]
Tim Petersf6fb5012002-04-12 07:38:53 +00001680 The requested memory, filled with copies of CLEANBYTE.
Tim Petersddea2082002-03-23 10:03:50 +00001681 Used to catch reference to uninitialized memory.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001682 &p[2*S] is returned. Note that this is 8-byte aligned if pymalloc
Tim Petersddea2082002-03-23 10:03:50 +00001683 handled the request itself.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001684p[2*S+n: 2*S+n+S]
Tim Petersf6fb5012002-04-12 07:38:53 +00001685 Copies of FORBIDDENBYTE. Used to catch over- writes and reads.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001686p[2*S+n+S: 2*S+n+2*S]
Victor Stinner0507bf52013-07-07 02:05:46 +02001687 A serial number, incremented by 1 on each call to _PyMem_DebugMalloc
1688 and _PyMem_DebugRealloc.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001689 This is a big-endian size_t.
Tim Petersddea2082002-03-23 10:03:50 +00001690 If "bad memory" is detected later, the serial number gives an
1691 excellent way to set a breakpoint on the next run, to capture the
1692 instant at which this block was passed out.
1693*/
1694
Victor Stinner0507bf52013-07-07 02:05:46 +02001695static void *
1696_PyMem_DebugMalloc(void *ctx, size_t nbytes)
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00001697{
Victor Stinner0507bf52013-07-07 02:05:46 +02001698 debug_alloc_api_t *api = (debug_alloc_api_t *)ctx;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001699 uchar *p; /* base address of malloc'ed block */
1700 uchar *tail; /* p + 2*SST + nbytes == pointer to tail pad bytes */
1701 size_t total; /* nbytes + 4*SST */
Tim Petersddea2082002-03-23 10:03:50 +00001702
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001703 bumpserialno();
1704 total = nbytes + 4*SST;
1705 if (total < nbytes)
1706 /* overflow: can't represent total as a size_t */
1707 return NULL;
Tim Petersddea2082002-03-23 10:03:50 +00001708
Victor Stinner0507bf52013-07-07 02:05:46 +02001709 p = (uchar *)api->alloc.malloc(api->alloc.ctx, total);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001710 if (p == NULL)
1711 return NULL;
Tim Petersddea2082002-03-23 10:03:50 +00001712
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001713 /* at p, write size (SST bytes), id (1 byte), pad (SST-1 bytes) */
1714 write_size_t(p, nbytes);
Victor Stinner0507bf52013-07-07 02:05:46 +02001715 p[SST] = (uchar)api->api_id;
1716 memset(p + SST + 1, FORBIDDENBYTE, SST-1);
Tim Petersddea2082002-03-23 10:03:50 +00001717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001718 if (nbytes > 0)
1719 memset(p + 2*SST, CLEANBYTE, nbytes);
Tim Petersddea2082002-03-23 10:03:50 +00001720
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001721 /* at tail, write pad (SST bytes) and serialno (SST bytes) */
1722 tail = p + 2*SST + nbytes;
1723 memset(tail, FORBIDDENBYTE, SST);
1724 write_size_t(tail + SST, serialno);
Tim Petersddea2082002-03-23 10:03:50 +00001725
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001726 return p + 2*SST;
Tim Petersddea2082002-03-23 10:03:50 +00001727}
1728
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001729/* 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 +00001730 particular, that the FORBIDDENBYTEs with the api ID are still intact).
Tim Petersf6fb5012002-04-12 07:38:53 +00001731 Then fills the original bytes with DEADBYTE.
Tim Petersddea2082002-03-23 10:03:50 +00001732 Then calls the underlying free.
1733*/
Victor Stinner0507bf52013-07-07 02:05:46 +02001734static void
1735_PyMem_DebugFree(void *ctx, void *p)
Tim Petersddea2082002-03-23 10:03:50 +00001736{
Victor Stinner0507bf52013-07-07 02:05:46 +02001737 debug_alloc_api_t *api = (debug_alloc_api_t *)ctx;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001738 uchar *q = (uchar *)p - 2*SST; /* address returned from malloc */
1739 size_t nbytes;
Tim Petersddea2082002-03-23 10:03:50 +00001740
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001741 if (p == NULL)
1742 return;
Victor Stinner0507bf52013-07-07 02:05:46 +02001743 _PyMem_DebugCheckAddress(api->api_id, p);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001744 nbytes = read_size_t(q);
1745 nbytes += 4*SST;
1746 if (nbytes > 0)
1747 memset(q, DEADBYTE, nbytes);
Victor Stinner0507bf52013-07-07 02:05:46 +02001748 api->alloc.free(api->alloc.ctx, q);
Tim Petersddea2082002-03-23 10:03:50 +00001749}
1750
Victor Stinner0507bf52013-07-07 02:05:46 +02001751static void *
1752_PyMem_DebugRealloc(void *ctx, void *p, size_t nbytes)
Tim Petersddea2082002-03-23 10:03:50 +00001753{
Victor Stinner0507bf52013-07-07 02:05:46 +02001754 debug_alloc_api_t *api = (debug_alloc_api_t *)ctx;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001755 uchar *q = (uchar *)p;
1756 uchar *tail;
1757 size_t total; /* nbytes + 4*SST */
1758 size_t original_nbytes;
1759 int i;
Tim Petersddea2082002-03-23 10:03:50 +00001760
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001761 if (p == NULL)
Victor Stinner0507bf52013-07-07 02:05:46 +02001762 return _PyMem_DebugMalloc(ctx, nbytes);
Tim Petersddea2082002-03-23 10:03:50 +00001763
Victor Stinner0507bf52013-07-07 02:05:46 +02001764 _PyMem_DebugCheckAddress(api->api_id, p);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001765 bumpserialno();
1766 original_nbytes = read_size_t(q - 2*SST);
1767 total = nbytes + 4*SST;
1768 if (total < nbytes)
1769 /* overflow: can't represent total as a size_t */
1770 return NULL;
Tim Petersddea2082002-03-23 10:03:50 +00001771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001772 if (nbytes < original_nbytes) {
1773 /* shrinking: mark old extra memory dead */
1774 memset(q + nbytes, DEADBYTE, original_nbytes - nbytes + 2*SST);
1775 }
Tim Petersddea2082002-03-23 10:03:50 +00001776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001777 /* Resize and add decorations. We may get a new pointer here, in which
1778 * case we didn't get the chance to mark the old memory with DEADBYTE,
1779 * but we live with that.
1780 */
Victor Stinner0507bf52013-07-07 02:05:46 +02001781 q = (uchar *)api->alloc.realloc(api->alloc.ctx, q - 2*SST, total);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001782 if (q == NULL)
1783 return NULL;
Tim Peters85cc1c42002-04-12 08:52:50 +00001784
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001785 write_size_t(q, nbytes);
Victor Stinner0507bf52013-07-07 02:05:46 +02001786 assert(q[SST] == (uchar)api->api_id);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001787 for (i = 1; i < SST; ++i)
1788 assert(q[SST + i] == FORBIDDENBYTE);
1789 q += 2*SST;
1790 tail = q + nbytes;
1791 memset(tail, FORBIDDENBYTE, SST);
1792 write_size_t(tail + SST, serialno);
Tim Peters85cc1c42002-04-12 08:52:50 +00001793
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001794 if (nbytes > original_nbytes) {
1795 /* growing: mark new extra memory clean */
1796 memset(q + original_nbytes, CLEANBYTE,
Stefan Krah735bb122010-11-26 10:54:09 +00001797 nbytes - original_nbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001798 }
Tim Peters85cc1c42002-04-12 08:52:50 +00001799
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001800 return q;
Tim Petersddea2082002-03-23 10:03:50 +00001801}
1802
Tim Peters7ccfadf2002-04-01 06:04:21 +00001803/* Check the forbidden bytes on both ends of the memory allocated for p.
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00001804 * If anything is wrong, print info to stderr via _PyObject_DebugDumpAddress,
Tim Peters7ccfadf2002-04-01 06:04:21 +00001805 * and call Py_FatalError to kill the program.
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00001806 * The API id, is also checked.
Tim Peters7ccfadf2002-04-01 06:04:21 +00001807 */
Victor Stinner0507bf52013-07-07 02:05:46 +02001808static void
1809_PyMem_DebugCheckAddress(char api, const void *p)
Tim Petersddea2082002-03-23 10:03:50 +00001810{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001811 const uchar *q = (const uchar *)p;
1812 char msgbuf[64];
1813 char *msg;
1814 size_t nbytes;
1815 const uchar *tail;
1816 int i;
1817 char id;
Tim Petersddea2082002-03-23 10:03:50 +00001818
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001819 if (p == NULL) {
1820 msg = "didn't expect a NULL pointer";
1821 goto error;
1822 }
Tim Petersddea2082002-03-23 10:03:50 +00001823
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001824 /* Check the API id */
1825 id = (char)q[-SST];
1826 if (id != api) {
1827 msg = msgbuf;
1828 snprintf(msg, sizeof(msgbuf), "bad ID: Allocated using API '%c', verified using API '%c'", id, api);
1829 msgbuf[sizeof(msgbuf)-1] = 0;
1830 goto error;
1831 }
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00001832
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001833 /* Check the stuff at the start of p first: if there's underwrite
1834 * corruption, the number-of-bytes field may be nuts, and checking
1835 * the tail could lead to a segfault then.
1836 */
1837 for (i = SST-1; i >= 1; --i) {
1838 if (*(q-i) != FORBIDDENBYTE) {
1839 msg = "bad leading pad byte";
1840 goto error;
1841 }
1842 }
Tim Petersddea2082002-03-23 10:03:50 +00001843
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001844 nbytes = read_size_t(q - 2*SST);
1845 tail = q + nbytes;
1846 for (i = 0; i < SST; ++i) {
1847 if (tail[i] != FORBIDDENBYTE) {
1848 msg = "bad trailing pad byte";
1849 goto error;
1850 }
1851 }
Tim Petersddea2082002-03-23 10:03:50 +00001852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001853 return;
Tim Petersd1139e02002-03-28 07:32:11 +00001854
1855error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001856 _PyObject_DebugDumpAddress(p);
1857 Py_FatalError(msg);
Tim Petersddea2082002-03-23 10:03:50 +00001858}
1859
Tim Peters7ccfadf2002-04-01 06:04:21 +00001860/* Display info to stderr about the memory block at p. */
Victor Stinner0507bf52013-07-07 02:05:46 +02001861static void
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00001862_PyObject_DebugDumpAddress(const void *p)
Tim Petersddea2082002-03-23 10:03:50 +00001863{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001864 const uchar *q = (const uchar *)p;
1865 const uchar *tail;
1866 size_t nbytes, serial;
1867 int i;
1868 int ok;
1869 char id;
Tim Petersddea2082002-03-23 10:03:50 +00001870
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001871 fprintf(stderr, "Debug memory block at address p=%p:", p);
1872 if (p == NULL) {
1873 fprintf(stderr, "\n");
1874 return;
1875 }
1876 id = (char)q[-SST];
1877 fprintf(stderr, " API '%c'\n", id);
Tim Petersddea2082002-03-23 10:03:50 +00001878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001879 nbytes = read_size_t(q - 2*SST);
1880 fprintf(stderr, " %" PY_FORMAT_SIZE_T "u bytes originally "
1881 "requested\n", nbytes);
Tim Petersddea2082002-03-23 10:03:50 +00001882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001883 /* In case this is nuts, check the leading pad bytes first. */
1884 fprintf(stderr, " The %d pad bytes at p-%d are ", SST-1, SST-1);
1885 ok = 1;
1886 for (i = 1; i <= SST-1; ++i) {
1887 if (*(q-i) != FORBIDDENBYTE) {
1888 ok = 0;
1889 break;
1890 }
1891 }
1892 if (ok)
1893 fputs("FORBIDDENBYTE, as expected.\n", stderr);
1894 else {
1895 fprintf(stderr, "not all FORBIDDENBYTE (0x%02x):\n",
1896 FORBIDDENBYTE);
1897 for (i = SST-1; i >= 1; --i) {
1898 const uchar byte = *(q-i);
1899 fprintf(stderr, " at p-%d: 0x%02x", i, byte);
1900 if (byte != FORBIDDENBYTE)
1901 fputs(" *** OUCH", stderr);
1902 fputc('\n', stderr);
1903 }
Tim Peters449b5a82002-04-28 06:14:45 +00001904
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001905 fputs(" Because memory is corrupted at the start, the "
1906 "count of bytes requested\n"
1907 " may be bogus, and checking the trailing pad "
1908 "bytes may segfault.\n", stderr);
1909 }
Tim Petersddea2082002-03-23 10:03:50 +00001910
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001911 tail = q + nbytes;
1912 fprintf(stderr, " The %d pad bytes at tail=%p are ", SST, tail);
1913 ok = 1;
1914 for (i = 0; i < SST; ++i) {
1915 if (tail[i] != FORBIDDENBYTE) {
1916 ok = 0;
1917 break;
1918 }
1919 }
1920 if (ok)
1921 fputs("FORBIDDENBYTE, as expected.\n", stderr);
1922 else {
1923 fprintf(stderr, "not all FORBIDDENBYTE (0x%02x):\n",
Stefan Krah735bb122010-11-26 10:54:09 +00001924 FORBIDDENBYTE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001925 for (i = 0; i < SST; ++i) {
1926 const uchar byte = tail[i];
1927 fprintf(stderr, " at tail+%d: 0x%02x",
Stefan Krah735bb122010-11-26 10:54:09 +00001928 i, byte);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001929 if (byte != FORBIDDENBYTE)
1930 fputs(" *** OUCH", stderr);
1931 fputc('\n', stderr);
1932 }
1933 }
Tim Petersddea2082002-03-23 10:03:50 +00001934
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001935 serial = read_size_t(tail + SST);
1936 fprintf(stderr, " The block was made by call #%" PY_FORMAT_SIZE_T
1937 "u to debug malloc/realloc.\n", serial);
Tim Petersddea2082002-03-23 10:03:50 +00001938
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001939 if (nbytes > 0) {
1940 i = 0;
1941 fputs(" Data at p:", stderr);
1942 /* print up to 8 bytes at the start */
1943 while (q < tail && i < 8) {
1944 fprintf(stderr, " %02x", *q);
1945 ++i;
1946 ++q;
1947 }
1948 /* and up to 8 at the end */
1949 if (q < tail) {
1950 if (tail - q > 8) {
1951 fputs(" ...", stderr);
1952 q = tail - 8;
1953 }
1954 while (q < tail) {
1955 fprintf(stderr, " %02x", *q);
1956 ++q;
1957 }
1958 }
1959 fputc('\n', stderr);
1960 }
Tim Petersddea2082002-03-23 10:03:50 +00001961}
1962
David Malcolm49526f42012-06-22 14:55:41 -04001963#endif /* PYMALLOC_DEBUG */
1964
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001965static size_t
David Malcolm49526f42012-06-22 14:55:41 -04001966printone(FILE *out, const char* msg, size_t value)
Tim Peters16bcb6b2002-04-05 05:45:31 +00001967{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001968 int i, k;
1969 char buf[100];
1970 size_t origvalue = value;
Tim Peters16bcb6b2002-04-05 05:45:31 +00001971
David Malcolm49526f42012-06-22 14:55:41 -04001972 fputs(msg, out);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001973 for (i = (int)strlen(msg); i < 35; ++i)
David Malcolm49526f42012-06-22 14:55:41 -04001974 fputc(' ', out);
1975 fputc('=', out);
Tim Peters49f26812002-04-06 01:45:35 +00001976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001977 /* Write the value with commas. */
1978 i = 22;
1979 buf[i--] = '\0';
1980 buf[i--] = '\n';
1981 k = 3;
1982 do {
1983 size_t nextvalue = value / 10;
Benjamin Peterson2dba1ee2013-02-20 16:54:30 -05001984 unsigned int digit = (unsigned int)(value - nextvalue * 10);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001985 value = nextvalue;
1986 buf[i--] = (char)(digit + '0');
1987 --k;
1988 if (k == 0 && value && i >= 0) {
1989 k = 3;
1990 buf[i--] = ',';
1991 }
1992 } while (value && i >= 0);
Tim Peters49f26812002-04-06 01:45:35 +00001993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001994 while (i >= 0)
1995 buf[i--] = ' ';
David Malcolm49526f42012-06-22 14:55:41 -04001996 fputs(buf, out);
Tim Peters49f26812002-04-06 01:45:35 +00001997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001998 return origvalue;
Tim Peters16bcb6b2002-04-05 05:45:31 +00001999}
2000
David Malcolm49526f42012-06-22 14:55:41 -04002001void
2002_PyDebugAllocatorStats(FILE *out,
2003 const char *block_name, int num_blocks, size_t sizeof_block)
2004{
2005 char buf1[128];
2006 char buf2[128];
2007 PyOS_snprintf(buf1, sizeof(buf1),
2008 "%d %ss * %zd bytes each",
2009 num_blocks, block_name, sizeof_block);
2010 PyOS_snprintf(buf2, sizeof(buf2),
2011 "%48s ", buf1);
2012 (void)printone(out, buf2, num_blocks * sizeof_block);
2013}
2014
2015#ifdef WITH_PYMALLOC
2016
2017/* Print summary info to "out" about the state of pymalloc's structures.
Tim Peters08d82152002-04-18 22:25:03 +00002018 * In Py_DEBUG mode, also perform some expensive internal consistency
2019 * checks.
2020 */
Tim Peters7ccfadf2002-04-01 06:04:21 +00002021void
David Malcolm49526f42012-06-22 14:55:41 -04002022_PyObject_DebugMallocStats(FILE *out)
Tim Peters7ccfadf2002-04-01 06:04:21 +00002023{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002024 uint i;
2025 const uint numclasses = SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT;
2026 /* # of pools, allocated blocks, and free blocks per class index */
2027 size_t numpools[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT];
2028 size_t numblocks[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT];
2029 size_t numfreeblocks[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT];
2030 /* total # of allocated bytes in used and full pools */
2031 size_t allocated_bytes = 0;
2032 /* total # of available bytes in used pools */
2033 size_t available_bytes = 0;
2034 /* # of free pools + pools not yet carved out of current arena */
2035 uint numfreepools = 0;
2036 /* # of bytes for arena alignment padding */
2037 size_t arena_alignment = 0;
2038 /* # of bytes in used and full pools used for pool_headers */
2039 size_t pool_header_bytes = 0;
2040 /* # of bytes in used and full pools wasted due to quantization,
2041 * i.e. the necessarily leftover space at the ends of used and
2042 * full pools.
2043 */
2044 size_t quantization = 0;
2045 /* # of arenas actually allocated. */
2046 size_t narenas = 0;
2047 /* running total -- should equal narenas * ARENA_SIZE */
2048 size_t total;
2049 char buf[128];
Tim Peters7ccfadf2002-04-01 06:04:21 +00002050
David Malcolm49526f42012-06-22 14:55:41 -04002051 fprintf(out, "Small block threshold = %d, in %u size classes.\n",
Stefan Krah735bb122010-11-26 10:54:09 +00002052 SMALL_REQUEST_THRESHOLD, numclasses);
Tim Peters7ccfadf2002-04-01 06:04:21 +00002053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002054 for (i = 0; i < numclasses; ++i)
2055 numpools[i] = numblocks[i] = numfreeblocks[i] = 0;
Tim Peters7ccfadf2002-04-01 06:04:21 +00002056
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002057 /* Because full pools aren't linked to from anything, it's easiest
2058 * to march over all the arenas. If we're lucky, most of the memory
2059 * will be living in full pools -- would be a shame to miss them.
2060 */
2061 for (i = 0; i < maxarenas; ++i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002062 uint j;
2063 uptr base = arenas[i].address;
Thomas Woutersa9773292006-04-21 09:43:23 +00002064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002065 /* Skip arenas which are not allocated. */
2066 if (arenas[i].address == (uptr)NULL)
2067 continue;
2068 narenas += 1;
Thomas Woutersa9773292006-04-21 09:43:23 +00002069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002070 numfreepools += arenas[i].nfreepools;
Tim Peters7ccfadf2002-04-01 06:04:21 +00002071
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002072 /* round up to pool alignment */
2073 if (base & (uptr)POOL_SIZE_MASK) {
2074 arena_alignment += POOL_SIZE;
2075 base &= ~(uptr)POOL_SIZE_MASK;
2076 base += POOL_SIZE;
2077 }
Tim Peters7ccfadf2002-04-01 06:04:21 +00002078
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002079 /* visit every pool in the arena */
2080 assert(base <= (uptr) arenas[i].pool_address);
2081 for (j = 0;
2082 base < (uptr) arenas[i].pool_address;
2083 ++j, base += POOL_SIZE) {
2084 poolp p = (poolp)base;
2085 const uint sz = p->szidx;
2086 uint freeblocks;
Tim Peters08d82152002-04-18 22:25:03 +00002087
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002088 if (p->ref.count == 0) {
2089 /* currently unused */
2090 assert(pool_is_in_list(p, arenas[i].freepools));
2091 continue;
2092 }
2093 ++numpools[sz];
2094 numblocks[sz] += p->ref.count;
2095 freeblocks = NUMBLOCKS(sz) - p->ref.count;
2096 numfreeblocks[sz] += freeblocks;
Tim Peters08d82152002-04-18 22:25:03 +00002097#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002098 if (freeblocks > 0)
2099 assert(pool_is_in_list(p, usedpools[sz + sz]));
Tim Peters08d82152002-04-18 22:25:03 +00002100#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002101 }
2102 }
2103 assert(narenas == narenas_currently_allocated);
Tim Peters7ccfadf2002-04-01 06:04:21 +00002104
David Malcolm49526f42012-06-22 14:55:41 -04002105 fputc('\n', out);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002106 fputs("class size num pools blocks in use avail blocks\n"
2107 "----- ---- --------- ------------- ------------\n",
David Malcolm49526f42012-06-22 14:55:41 -04002108 out);
Tim Peters7ccfadf2002-04-01 06:04:21 +00002109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002110 for (i = 0; i < numclasses; ++i) {
2111 size_t p = numpools[i];
2112 size_t b = numblocks[i];
2113 size_t f = numfreeblocks[i];
2114 uint size = INDEX2SIZE(i);
2115 if (p == 0) {
2116 assert(b == 0 && f == 0);
2117 continue;
2118 }
David Malcolm49526f42012-06-22 14:55:41 -04002119 fprintf(out, "%5u %6u "
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002120 "%11" PY_FORMAT_SIZE_T "u "
2121 "%15" PY_FORMAT_SIZE_T "u "
2122 "%13" PY_FORMAT_SIZE_T "u\n",
Stefan Krah735bb122010-11-26 10:54:09 +00002123 i, size, p, b, f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002124 allocated_bytes += b * size;
2125 available_bytes += f * size;
2126 pool_header_bytes += p * POOL_OVERHEAD;
2127 quantization += p * ((POOL_SIZE - POOL_OVERHEAD) % size);
2128 }
David Malcolm49526f42012-06-22 14:55:41 -04002129 fputc('\n', out);
2130#ifdef PYMALLOC_DEBUG
2131 (void)printone(out, "# times object malloc called", serialno);
2132#endif
2133 (void)printone(out, "# arenas allocated total", ntimes_arena_allocated);
2134 (void)printone(out, "# arenas reclaimed", ntimes_arena_allocated - narenas);
2135 (void)printone(out, "# arenas highwater mark", narenas_highwater);
2136 (void)printone(out, "# arenas allocated current", narenas);
Thomas Woutersa9773292006-04-21 09:43:23 +00002137
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002138 PyOS_snprintf(buf, sizeof(buf),
2139 "%" PY_FORMAT_SIZE_T "u arenas * %d bytes/arena",
2140 narenas, ARENA_SIZE);
David Malcolm49526f42012-06-22 14:55:41 -04002141 (void)printone(out, buf, narenas * ARENA_SIZE);
Tim Peters16bcb6b2002-04-05 05:45:31 +00002142
David Malcolm49526f42012-06-22 14:55:41 -04002143 fputc('\n', out);
Tim Peters16bcb6b2002-04-05 05:45:31 +00002144
David Malcolm49526f42012-06-22 14:55:41 -04002145 total = printone(out, "# bytes in allocated blocks", allocated_bytes);
2146 total += printone(out, "# bytes in available blocks", available_bytes);
Tim Peters49f26812002-04-06 01:45:35 +00002147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002148 PyOS_snprintf(buf, sizeof(buf),
2149 "%u unused pools * %d bytes", numfreepools, POOL_SIZE);
David Malcolm49526f42012-06-22 14:55:41 -04002150 total += printone(out, buf, (size_t)numfreepools * POOL_SIZE);
Tim Peters16bcb6b2002-04-05 05:45:31 +00002151
David Malcolm49526f42012-06-22 14:55:41 -04002152 total += printone(out, "# bytes lost to pool headers", pool_header_bytes);
2153 total += printone(out, "# bytes lost to quantization", quantization);
2154 total += printone(out, "# bytes lost to arena alignment", arena_alignment);
2155 (void)printone(out, "Total", total);
Tim Peters7ccfadf2002-04-01 06:04:21 +00002156}
2157
David Malcolm49526f42012-06-22 14:55:41 -04002158#endif /* #ifdef WITH_PYMALLOC */
Neal Norwitz7eb3c912004-06-06 19:20:22 +00002159
2160#ifdef Py_USING_MEMORY_DEBUGGER
Thomas Woutersa9773292006-04-21 09:43:23 +00002161/* Make this function last so gcc won't inline it since the definition is
2162 * after the reference.
2163 */
Neal Norwitz7eb3c912004-06-06 19:20:22 +00002164int
2165Py_ADDRESS_IN_RANGE(void *P, poolp pool)
2166{
Antoine Pitroub7fb2e22011-01-07 21:43:59 +00002167 uint arenaindex_temp = pool->arenaindex;
2168
2169 return arenaindex_temp < maxarenas &&
2170 (uptr)P - arenas[arenaindex_temp].address < (uptr)ARENA_SIZE &&
2171 arenas[arenaindex_temp].address != 0;
Neal Norwitz7eb3c912004-06-06 19:20:22 +00002172}
2173#endif