blob: 7cc889f817b62859acc7f1aae997de744ca87da0 [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);
Victor Stinnerdb067af2014-05-02 22:31:14 +02008static void* _PyMem_DebugCalloc(void *ctx, size_t nelem, size_t elsize);
Victor Stinner0507bf52013-07-07 02:05:46 +02009static void _PyMem_DebugFree(void *ctx, void *p);
10static void* _PyMem_DebugRealloc(void *ctx, void *ptr, size_t size);
11
12static void _PyObject_DebugDumpAddress(const void *p);
13static void _PyMem_DebugCheckAddress(char api_id, const void *p);
14#endif
15
Nick Coghlan6ba64f42013-09-29 00:28:55 +100016#if defined(__has_feature) /* Clang */
17 #if __has_feature(address_sanitizer) /* is ASAN enabled? */
18 #define ATTRIBUTE_NO_ADDRESS_SAFETY_ANALYSIS \
19 __attribute__((no_address_safety_analysis)) \
20 __attribute__ ((noinline))
21 #else
22 #define ATTRIBUTE_NO_ADDRESS_SAFETY_ANALYSIS
23 #endif
24#else
25 #if defined(__SANITIZE_ADDRESS__) /* GCC 4.8.x, is ASAN enabled? */
26 #define ATTRIBUTE_NO_ADDRESS_SAFETY_ANALYSIS \
27 __attribute__((no_address_safety_analysis)) \
28 __attribute__ ((noinline))
29 #else
30 #define ATTRIBUTE_NO_ADDRESS_SAFETY_ANALYSIS
31 #endif
32#endif
33
Tim Peters1221c0a2002-03-23 00:20:15 +000034#ifdef WITH_PYMALLOC
35
Victor Stinner0507bf52013-07-07 02:05:46 +020036#ifdef MS_WINDOWS
37# include <windows.h>
38#elif defined(HAVE_MMAP)
39# include <sys/mman.h>
40# ifdef MAP_ANONYMOUS
41# define ARENAS_USE_MMAP
42# endif
Antoine Pitrou6f26be02011-05-03 18:18:59 +020043#endif
44
Victor Stinner0507bf52013-07-07 02:05:46 +020045/* Forward declaration */
46static void* _PyObject_Malloc(void *ctx, size_t size);
Victor Stinnerdb067af2014-05-02 22:31:14 +020047static void* _PyObject_Calloc(void *ctx, size_t nelem, size_t elsize);
Victor Stinner0507bf52013-07-07 02:05:46 +020048static void _PyObject_Free(void *ctx, void *p);
49static void* _PyObject_Realloc(void *ctx, void *ptr, size_t size);
Martin v. Löwiscd83fa82013-06-27 12:23:29 +020050#endif
51
Victor Stinner0507bf52013-07-07 02:05:46 +020052
53static void *
54_PyMem_RawMalloc(void *ctx, size_t size)
55{
Victor Stinnerdb067af2014-05-02 22:31:14 +020056 /* PyMem_RawMalloc(0) means malloc(1). Some systems would return NULL
Victor Stinner0507bf52013-07-07 02:05:46 +020057 for malloc(0), which would be treated as an error. Some platforms would
58 return a pointer with no memory behind it, which would break pymalloc.
59 To solve these problems, allocate an extra byte. */
60 if (size == 0)
61 size = 1;
62 return malloc(size);
63}
64
65static void *
Victor Stinnerdb067af2014-05-02 22:31:14 +020066_PyMem_RawCalloc(void *ctx, size_t nelem, size_t elsize)
67{
68 /* PyMem_RawCalloc(0, 0) means calloc(1, 1). Some systems would return NULL
69 for calloc(0, 0), which would be treated as an error. Some platforms
70 would return a pointer with no memory behind it, which would break
71 pymalloc. To solve these problems, allocate an extra byte. */
72 if (nelem == 0 || elsize == 0) {
73 nelem = 1;
74 elsize = 1;
75 }
76 return calloc(nelem, elsize);
77}
78
79static void *
Victor Stinner0507bf52013-07-07 02:05:46 +020080_PyMem_RawRealloc(void *ctx, void *ptr, size_t size)
81{
82 if (size == 0)
83 size = 1;
84 return realloc(ptr, size);
85}
86
87static void
88_PyMem_RawFree(void *ctx, void *ptr)
89{
90 free(ptr);
91}
92
93
94#ifdef MS_WINDOWS
95static void *
96_PyObject_ArenaVirtualAlloc(void *ctx, size_t size)
97{
98 return VirtualAlloc(NULL, size,
99 MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
100}
101
102static void
103_PyObject_ArenaVirtualFree(void *ctx, void *ptr, size_t size)
104{
Victor Stinner725e6682013-07-07 03:06:16 +0200105 VirtualFree(ptr, 0, MEM_RELEASE);
Victor Stinner0507bf52013-07-07 02:05:46 +0200106}
107
108#elif defined(ARENAS_USE_MMAP)
109static void *
110_PyObject_ArenaMmap(void *ctx, size_t size)
111{
112 void *ptr;
113 ptr = mmap(NULL, size, PROT_READ|PROT_WRITE,
114 MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
115 if (ptr == MAP_FAILED)
116 return NULL;
117 assert(ptr != NULL);
118 return ptr;
119}
120
121static void
122_PyObject_ArenaMunmap(void *ctx, void *ptr, size_t size)
123{
124 munmap(ptr, size);
125}
126
127#else
128static void *
129_PyObject_ArenaMalloc(void *ctx, size_t size)
130{
131 return malloc(size);
132}
133
134static void
135_PyObject_ArenaFree(void *ctx, void *ptr, size_t size)
136{
137 free(ptr);
138}
139#endif
140
141
Victor Stinnerdb067af2014-05-02 22:31:14 +0200142#define PYRAW_FUNCS _PyMem_RawMalloc, _PyMem_RawCalloc, _PyMem_RawRealloc, _PyMem_RawFree
Victor Stinner0507bf52013-07-07 02:05:46 +0200143#ifdef WITH_PYMALLOC
Victor Stinnerdb067af2014-05-02 22:31:14 +0200144# define PYOBJ_FUNCS _PyObject_Malloc, _PyObject_Calloc, _PyObject_Realloc, _PyObject_Free
Victor Stinner0507bf52013-07-07 02:05:46 +0200145#else
Victor Stinner6cf185d2013-10-10 15:58:42 +0200146# define PYOBJ_FUNCS PYRAW_FUNCS
Victor Stinner0507bf52013-07-07 02:05:46 +0200147#endif
Victor Stinner6cf185d2013-10-10 15:58:42 +0200148#define PYMEM_FUNCS PYRAW_FUNCS
Victor Stinner0507bf52013-07-07 02:05:46 +0200149
150#ifdef PYMALLOC_DEBUG
151typedef struct {
152 /* We tag each block with an API ID in order to tag API violations */
153 char api_id;
Victor Stinnerd8f0d922014-06-02 21:57:10 +0200154 PyMemAllocatorEx alloc;
Victor Stinner0507bf52013-07-07 02:05:46 +0200155} debug_alloc_api_t;
156static struct {
157 debug_alloc_api_t raw;
158 debug_alloc_api_t mem;
159 debug_alloc_api_t obj;
160} _PyMem_Debug = {
161 {'r', {NULL, PYRAW_FUNCS}},
Victor Stinner6cf185d2013-10-10 15:58:42 +0200162 {'m', {NULL, PYMEM_FUNCS}},
163 {'o', {NULL, PYOBJ_FUNCS}}
Victor Stinner0507bf52013-07-07 02:05:46 +0200164 };
165
Victor Stinnerdb067af2014-05-02 22:31:14 +0200166#define PYDBG_FUNCS _PyMem_DebugMalloc, _PyMem_DebugCalloc, _PyMem_DebugRealloc, _PyMem_DebugFree
Victor Stinner0507bf52013-07-07 02:05:46 +0200167#endif
168
Victor Stinnerd8f0d922014-06-02 21:57:10 +0200169static PyMemAllocatorEx _PyMem_Raw = {
Victor Stinner0507bf52013-07-07 02:05:46 +0200170#ifdef PYMALLOC_DEBUG
Victor Stinner6cf185d2013-10-10 15:58:42 +0200171 &_PyMem_Debug.raw, PYDBG_FUNCS
Victor Stinner0507bf52013-07-07 02:05:46 +0200172#else
173 NULL, PYRAW_FUNCS
174#endif
175 };
176
Victor Stinnerd8f0d922014-06-02 21:57:10 +0200177static PyMemAllocatorEx _PyMem = {
Victor Stinner0507bf52013-07-07 02:05:46 +0200178#ifdef PYMALLOC_DEBUG
Victor Stinner6cf185d2013-10-10 15:58:42 +0200179 &_PyMem_Debug.mem, PYDBG_FUNCS
Victor Stinner0507bf52013-07-07 02:05:46 +0200180#else
Victor Stinner6cf185d2013-10-10 15:58:42 +0200181 NULL, PYMEM_FUNCS
Victor Stinner0507bf52013-07-07 02:05:46 +0200182#endif
183 };
184
Victor Stinnerd8f0d922014-06-02 21:57:10 +0200185static PyMemAllocatorEx _PyObject = {
Victor Stinner0507bf52013-07-07 02:05:46 +0200186#ifdef PYMALLOC_DEBUG
Victor Stinner6cf185d2013-10-10 15:58:42 +0200187 &_PyMem_Debug.obj, PYDBG_FUNCS
Victor Stinner0507bf52013-07-07 02:05:46 +0200188#else
Victor Stinner6cf185d2013-10-10 15:58:42 +0200189 NULL, PYOBJ_FUNCS
Victor Stinner0507bf52013-07-07 02:05:46 +0200190#endif
191 };
192
193#undef PYRAW_FUNCS
Victor Stinner6cf185d2013-10-10 15:58:42 +0200194#undef PYMEM_FUNCS
195#undef PYOBJ_FUNCS
196#undef PYDBG_FUNCS
Victor Stinner0507bf52013-07-07 02:05:46 +0200197
198static PyObjectArenaAllocator _PyObject_Arena = {NULL,
199#ifdef MS_WINDOWS
200 _PyObject_ArenaVirtualAlloc, _PyObject_ArenaVirtualFree
201#elif defined(ARENAS_USE_MMAP)
202 _PyObject_ArenaMmap, _PyObject_ArenaMunmap
203#else
204 _PyObject_ArenaMalloc, _PyObject_ArenaFree
205#endif
206 };
207
208void
209PyMem_SetupDebugHooks(void)
210{
211#ifdef PYMALLOC_DEBUG
Victor Stinnerd8f0d922014-06-02 21:57:10 +0200212 PyMemAllocatorEx alloc;
Victor Stinner0507bf52013-07-07 02:05:46 +0200213
214 alloc.malloc = _PyMem_DebugMalloc;
Victor Stinnerdb067af2014-05-02 22:31:14 +0200215 alloc.calloc = _PyMem_DebugCalloc;
Victor Stinner0507bf52013-07-07 02:05:46 +0200216 alloc.realloc = _PyMem_DebugRealloc;
217 alloc.free = _PyMem_DebugFree;
218
219 if (_PyMem_Raw.malloc != _PyMem_DebugMalloc) {
220 alloc.ctx = &_PyMem_Debug.raw;
221 PyMem_GetAllocator(PYMEM_DOMAIN_RAW, &_PyMem_Debug.raw.alloc);
222 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &alloc);
223 }
224
225 if (_PyMem.malloc != _PyMem_DebugMalloc) {
226 alloc.ctx = &_PyMem_Debug.mem;
227 PyMem_GetAllocator(PYMEM_DOMAIN_MEM, &_PyMem_Debug.mem.alloc);
228 PyMem_SetAllocator(PYMEM_DOMAIN_MEM, &alloc);
229 }
230
231 if (_PyObject.malloc != _PyMem_DebugMalloc) {
232 alloc.ctx = &_PyMem_Debug.obj;
233 PyMem_GetAllocator(PYMEM_DOMAIN_OBJ, &_PyMem_Debug.obj.alloc);
234 PyMem_SetAllocator(PYMEM_DOMAIN_OBJ, &alloc);
235 }
236#endif
237}
238
239void
Victor Stinnerd8f0d922014-06-02 21:57:10 +0200240PyMem_GetAllocator(PyMemAllocatorDomain domain, PyMemAllocatorEx *allocator)
Victor Stinner0507bf52013-07-07 02:05:46 +0200241{
242 switch(domain)
243 {
244 case PYMEM_DOMAIN_RAW: *allocator = _PyMem_Raw; break;
245 case PYMEM_DOMAIN_MEM: *allocator = _PyMem; break;
246 case PYMEM_DOMAIN_OBJ: *allocator = _PyObject; break;
247 default:
Victor Stinnerdb067af2014-05-02 22:31:14 +0200248 /* unknown domain: set all attributes to NULL */
Victor Stinner0507bf52013-07-07 02:05:46 +0200249 allocator->ctx = NULL;
250 allocator->malloc = NULL;
Victor Stinnerdb067af2014-05-02 22:31:14 +0200251 allocator->calloc = NULL;
Victor Stinner0507bf52013-07-07 02:05:46 +0200252 allocator->realloc = NULL;
253 allocator->free = NULL;
254 }
255}
256
257void
Victor Stinnerd8f0d922014-06-02 21:57:10 +0200258PyMem_SetAllocator(PyMemAllocatorDomain domain, PyMemAllocatorEx *allocator)
Victor Stinner0507bf52013-07-07 02:05:46 +0200259{
260 switch(domain)
261 {
262 case PYMEM_DOMAIN_RAW: _PyMem_Raw = *allocator; break;
263 case PYMEM_DOMAIN_MEM: _PyMem = *allocator; break;
264 case PYMEM_DOMAIN_OBJ: _PyObject = *allocator; break;
265 /* ignore unknown domain */
266 }
267
268}
269
270void
271PyObject_GetArenaAllocator(PyObjectArenaAllocator *allocator)
272{
273 *allocator = _PyObject_Arena;
274}
275
276void
277PyObject_SetArenaAllocator(PyObjectArenaAllocator *allocator)
278{
279 _PyObject_Arena = *allocator;
280}
281
282void *
283PyMem_RawMalloc(size_t size)
284{
285 /*
286 * Limit ourselves to PY_SSIZE_T_MAX bytes to prevent security holes.
287 * Most python internals blindly use a signed Py_ssize_t to track
288 * things without checking for overflows or negatives.
289 * As size_t is unsigned, checking for size < 0 is not required.
290 */
291 if (size > (size_t)PY_SSIZE_T_MAX)
292 return NULL;
Victor Stinner0507bf52013-07-07 02:05:46 +0200293 return _PyMem_Raw.malloc(_PyMem_Raw.ctx, size);
294}
295
Victor Stinnerdb067af2014-05-02 22:31:14 +0200296void *
297PyMem_RawCalloc(size_t nelem, size_t elsize)
298{
299 /* see PyMem_RawMalloc() */
300 if (elsize != 0 && nelem > (size_t)PY_SSIZE_T_MAX / elsize)
301 return NULL;
302 return _PyMem_Raw.calloc(_PyMem_Raw.ctx, nelem, elsize);
303}
304
Victor Stinner0507bf52013-07-07 02:05:46 +0200305void*
306PyMem_RawRealloc(void *ptr, size_t new_size)
307{
308 /* see PyMem_RawMalloc() */
309 if (new_size > (size_t)PY_SSIZE_T_MAX)
310 return NULL;
311 return _PyMem_Raw.realloc(_PyMem_Raw.ctx, ptr, new_size);
312}
313
314void PyMem_RawFree(void *ptr)
315{
316 _PyMem_Raw.free(_PyMem_Raw.ctx, ptr);
317}
318
319void *
320PyMem_Malloc(size_t size)
321{
322 /* see PyMem_RawMalloc() */
323 if (size > (size_t)PY_SSIZE_T_MAX)
324 return NULL;
325 return _PyMem.malloc(_PyMem.ctx, size);
326}
327
328void *
Victor Stinnerdb067af2014-05-02 22:31:14 +0200329PyMem_Calloc(size_t nelem, size_t elsize)
330{
331 /* see PyMem_RawMalloc() */
332 if (elsize != 0 && nelem > (size_t)PY_SSIZE_T_MAX / elsize)
333 return NULL;
334 return _PyMem.calloc(_PyMem.ctx, nelem, elsize);
335}
336
337void *
Victor Stinner0507bf52013-07-07 02:05:46 +0200338PyMem_Realloc(void *ptr, size_t new_size)
339{
340 /* see PyMem_RawMalloc() */
341 if (new_size > (size_t)PY_SSIZE_T_MAX)
342 return NULL;
343 return _PyMem.realloc(_PyMem.ctx, ptr, new_size);
344}
345
346void
347PyMem_Free(void *ptr)
348{
349 _PyMem.free(_PyMem.ctx, ptr);
350}
351
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200352char *
353_PyMem_RawStrdup(const char *str)
354{
355 size_t size;
356 char *copy;
357
358 size = strlen(str) + 1;
359 copy = PyMem_RawMalloc(size);
360 if (copy == NULL)
361 return NULL;
362 memcpy(copy, str, size);
363 return copy;
364}
365
366char *
367_PyMem_Strdup(const char *str)
368{
369 size_t size;
370 char *copy;
371
372 size = strlen(str) + 1;
373 copy = PyMem_Malloc(size);
374 if (copy == NULL)
375 return NULL;
376 memcpy(copy, str, size);
377 return copy;
378}
379
Victor Stinner0507bf52013-07-07 02:05:46 +0200380void *
381PyObject_Malloc(size_t size)
382{
383 /* see PyMem_RawMalloc() */
384 if (size > (size_t)PY_SSIZE_T_MAX)
385 return NULL;
386 return _PyObject.malloc(_PyObject.ctx, size);
387}
388
389void *
Victor Stinnerdb067af2014-05-02 22:31:14 +0200390PyObject_Calloc(size_t nelem, size_t elsize)
391{
392 /* see PyMem_RawMalloc() */
393 if (elsize != 0 && nelem > (size_t)PY_SSIZE_T_MAX / elsize)
394 return NULL;
395 return _PyObject.calloc(_PyObject.ctx, nelem, elsize);
396}
397
398void *
Victor Stinner0507bf52013-07-07 02:05:46 +0200399PyObject_Realloc(void *ptr, size_t new_size)
400{
401 /* see PyMem_RawMalloc() */
402 if (new_size > (size_t)PY_SSIZE_T_MAX)
403 return NULL;
404 return _PyObject.realloc(_PyObject.ctx, ptr, new_size);
405}
406
407void
408PyObject_Free(void *ptr)
409{
410 _PyObject.free(_PyObject.ctx, ptr);
411}
412
413
414#ifdef WITH_PYMALLOC
415
Benjamin Peterson05159c42009-12-03 03:01:27 +0000416#ifdef WITH_VALGRIND
417#include <valgrind/valgrind.h>
418
419/* If we're using GCC, use __builtin_expect() to reduce overhead of
420 the valgrind checks */
421#if defined(__GNUC__) && (__GNUC__ > 2) && defined(__OPTIMIZE__)
422# define UNLIKELY(value) __builtin_expect((value), 0)
423#else
424# define UNLIKELY(value) (value)
425#endif
426
427/* -1 indicates that we haven't checked that we're running on valgrind yet. */
428static int running_on_valgrind = -1;
429#endif
430
Neil Schemenauera35c6882001-02-27 04:45:05 +0000431/* An object allocator for Python.
432
433 Here is an introduction to the layers of the Python memory architecture,
434 showing where the object allocator is actually used (layer +2), It is
435 called for every object allocation and deallocation (PyObject_New/Del),
436 unless the object-specific allocators implement a proprietary allocation
437 scheme (ex.: ints use a simple free list). This is also the place where
438 the cyclic garbage collector operates selectively on container objects.
439
440
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000441 Object-specific allocators
Neil Schemenauera35c6882001-02-27 04:45:05 +0000442 _____ ______ ______ ________
443 [ int ] [ dict ] [ list ] ... [ string ] Python core |
444+3 | <----- Object-specific memory -----> | <-- Non-object memory --> |
445 _______________________________ | |
446 [ Python's object allocator ] | |
447+2 | ####### Object memory ####### | <------ Internal buffers ------> |
448 ______________________________________________________________ |
449 [ Python's raw memory allocator (PyMem_ API) ] |
450+1 | <----- Python memory (under PyMem manager's control) ------> | |
451 __________________________________________________________________
452 [ Underlying general-purpose allocator (ex: C library malloc) ]
453 0 | <------ Virtual memory allocated for the python process -------> |
454
455 =========================================================================
456 _______________________________________________________________________
457 [ OS-specific Virtual Memory Manager (VMM) ]
458-1 | <--- Kernel dynamic storage allocation & management (page-based) ---> |
459 __________________________________ __________________________________
460 [ ] [ ]
461-2 | <-- Physical memory: ROM/RAM --> | | <-- Secondary storage (swap) --> |
462
463*/
464/*==========================================================================*/
465
466/* A fast, special-purpose memory allocator for small blocks, to be used
467 on top of a general-purpose malloc -- heavily based on previous art. */
468
469/* Vladimir Marangozov -- August 2000 */
470
471/*
472 * "Memory management is where the rubber meets the road -- if we do the wrong
473 * thing at any level, the results will not be good. And if we don't make the
474 * levels work well together, we are in serious trouble." (1)
475 *
476 * (1) Paul R. Wilson, Mark S. Johnstone, Michael Neely, and David Boles,
477 * "Dynamic Storage Allocation: A Survey and Critical Review",
478 * in Proc. 1995 Int'l. Workshop on Memory Management, September 1995.
479 */
480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000481/* #undef WITH_MEMORY_LIMITS */ /* disable mem limit checks */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000482
483/*==========================================================================*/
484
485/*
Neil Schemenauera35c6882001-02-27 04:45:05 +0000486 * Allocation strategy abstract:
487 *
488 * For small requests, the allocator sub-allocates <Big> blocks of memory.
Antoine Pitrou6f26be02011-05-03 18:18:59 +0200489 * Requests greater than SMALL_REQUEST_THRESHOLD bytes are routed to the
490 * system's allocator.
Tim Petersce7fb9b2002-03-23 00:28:57 +0000491 *
Neil Schemenauera35c6882001-02-27 04:45:05 +0000492 * Small requests are grouped in size classes spaced 8 bytes apart, due
493 * to the required valid alignment of the returned address. Requests of
494 * a particular size are serviced from memory pools of 4K (one VMM page).
495 * Pools are fragmented on demand and contain free lists of blocks of one
496 * particular size class. In other words, there is a fixed-size allocator
497 * for each size class. Free pools are shared by the different allocators
498 * thus minimizing the space reserved for a particular size class.
499 *
500 * This allocation strategy is a variant of what is known as "simple
501 * segregated storage based on array of free lists". The main drawback of
502 * simple segregated storage is that we might end up with lot of reserved
503 * memory for the different free lists, which degenerate in time. To avoid
504 * this, we partition each free list in pools and we share dynamically the
505 * reserved space between all free lists. This technique is quite efficient
506 * for memory intensive programs which allocate mainly small-sized blocks.
507 *
508 * For small requests we have the following table:
509 *
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 * Request in bytes Size of allocated block Size class idx
Neil Schemenauera35c6882001-02-27 04:45:05 +0000511 * ----------------------------------------------------------------
512 * 1-8 8 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000513 * 9-16 16 1
514 * 17-24 24 2
515 * 25-32 32 3
516 * 33-40 40 4
517 * 41-48 48 5
518 * 49-56 56 6
519 * 57-64 64 7
520 * 65-72 72 8
521 * ... ... ...
Antoine Pitrou6f26be02011-05-03 18:18:59 +0200522 * 497-504 504 62
523 * 505-512 512 63
Tim Petersce7fb9b2002-03-23 00:28:57 +0000524 *
Antoine Pitrou6f26be02011-05-03 18:18:59 +0200525 * 0, SMALL_REQUEST_THRESHOLD + 1 and up: routed to the underlying
526 * allocator.
Neil Schemenauera35c6882001-02-27 04:45:05 +0000527 */
528
529/*==========================================================================*/
530
531/*
532 * -- Main tunable settings section --
533 */
534
535/*
536 * Alignment of addresses returned to the user. 8-bytes alignment works
537 * on most current architectures (with 32-bit or 64-bit address busses).
538 * The alignment value is also used for grouping small requests in size
539 * classes spaced ALIGNMENT bytes apart.
540 *
541 * You shouldn't change this unless you know what you are doing.
542 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000543#define ALIGNMENT 8 /* must be 2^N */
544#define ALIGNMENT_SHIFT 3
Neil Schemenauera35c6882001-02-27 04:45:05 +0000545
Tim Peterse70ddf32002-04-05 04:32:29 +0000546/* Return the number of bytes in size class I, as a uint. */
547#define INDEX2SIZE(I) (((uint)(I) + 1) << ALIGNMENT_SHIFT)
548
Neil Schemenauera35c6882001-02-27 04:45:05 +0000549/*
550 * Max size threshold below which malloc requests are considered to be
551 * small enough in order to use preallocated memory pools. You can tune
552 * this value according to your application behaviour and memory needs.
553 *
Antoine Pitrou6f26be02011-05-03 18:18:59 +0200554 * Note: a size threshold of 512 guarantees that newly created dictionaries
555 * will be allocated from preallocated memory pools on 64-bit.
556 *
Neil Schemenauera35c6882001-02-27 04:45:05 +0000557 * The following invariants must hold:
Antoine Pitrou6f26be02011-05-03 18:18:59 +0200558 * 1) ALIGNMENT <= SMALL_REQUEST_THRESHOLD <= 512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 * 2) SMALL_REQUEST_THRESHOLD is evenly divisible by ALIGNMENT
Neil Schemenauera35c6882001-02-27 04:45:05 +0000560 *
561 * Although not required, for better performance and space efficiency,
562 * it is recommended that SMALL_REQUEST_THRESHOLD is set to a power of 2.
563 */
Antoine Pitrou6f26be02011-05-03 18:18:59 +0200564#define SMALL_REQUEST_THRESHOLD 512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000565#define NB_SMALL_SIZE_CLASSES (SMALL_REQUEST_THRESHOLD / ALIGNMENT)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000566
567/*
568 * The system's VMM page size can be obtained on most unices with a
569 * getpagesize() call or deduced from various header files. To make
570 * things simpler, we assume that it is 4K, which is OK for most systems.
571 * It is probably better if this is the native page size, but it doesn't
Tim Petersecc6e6a2005-07-10 22:30:55 +0000572 * have to be. In theory, if SYSTEM_PAGE_SIZE is larger than the native page
573 * size, then `POOL_ADDR(p)->arenaindex' could rarely cause a segmentation
574 * violation fault. 4K is apparently OK for all the platforms that python
Martin v. Löwis8c140282002-10-26 15:01:53 +0000575 * currently targets.
Neil Schemenauera35c6882001-02-27 04:45:05 +0000576 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577#define SYSTEM_PAGE_SIZE (4 * 1024)
578#define SYSTEM_PAGE_SIZE_MASK (SYSTEM_PAGE_SIZE - 1)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000579
580/*
581 * Maximum amount of memory managed by the allocator for small requests.
582 */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000583#ifdef WITH_MEMORY_LIMITS
584#ifndef SMALL_MEMORY_LIMIT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000585#define SMALL_MEMORY_LIMIT (64 * 1024 * 1024) /* 64 MB -- more? */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000586#endif
587#endif
588
589/*
590 * The allocator sub-allocates <Big> blocks of memory (called arenas) aligned
591 * on a page boundary. This is a reserved virtual address space for the
Antoine Pitrouf0effe62011-11-26 01:11:02 +0100592 * current process (obtained through a malloc()/mmap() call). In no way this
593 * means that the memory arenas will be used entirely. A malloc(<Big>) is
594 * usually an address range reservation for <Big> bytes, unless all pages within
595 * this space are referenced subsequently. So malloc'ing big blocks and not
596 * using them does not mean "wasting memory". It's an addressable range
597 * wastage...
Neil Schemenauera35c6882001-02-27 04:45:05 +0000598 *
Antoine Pitrouf0effe62011-11-26 01:11:02 +0100599 * Arenas are allocated with mmap() on systems supporting anonymous memory
600 * mappings to reduce heap fragmentation.
Neil Schemenauera35c6882001-02-27 04:45:05 +0000601 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000602#define ARENA_SIZE (256 << 10) /* 256KB */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000603
604#ifdef WITH_MEMORY_LIMITS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000605#define MAX_ARENAS (SMALL_MEMORY_LIMIT / ARENA_SIZE)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000606#endif
607
608/*
609 * Size of the pools used for small blocks. Should be a power of 2,
Tim Petersc2ce91a2002-03-30 21:36:04 +0000610 * between 1K and SYSTEM_PAGE_SIZE, that is: 1k, 2k, 4k.
Neil Schemenauera35c6882001-02-27 04:45:05 +0000611 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612#define POOL_SIZE SYSTEM_PAGE_SIZE /* must be 2^N */
613#define POOL_SIZE_MASK SYSTEM_PAGE_SIZE_MASK
Neil Schemenauera35c6882001-02-27 04:45:05 +0000614
615/*
616 * -- End of tunable settings section --
617 */
618
619/*==========================================================================*/
620
621/*
622 * Locking
623 *
624 * To reduce lock contention, it would probably be better to refine the
625 * crude function locking with per size class locking. I'm not positive
626 * however, whether it's worth switching to such locking policy because
627 * of the performance penalty it might introduce.
628 *
629 * The following macros describe the simplest (should also be the fastest)
630 * lock object on a particular platform and the init/fini/lock/unlock
631 * operations on it. The locks defined here are not expected to be recursive
632 * because it is assumed that they will always be called in the order:
633 * INIT, [LOCK, UNLOCK]*, FINI.
634 */
635
636/*
637 * Python's threads are serialized, so object malloc locking is disabled.
638 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000639#define SIMPLELOCK_DECL(lock) /* simple lock declaration */
640#define SIMPLELOCK_INIT(lock) /* allocate (if needed) and initialize */
641#define SIMPLELOCK_FINI(lock) /* free/destroy an existing lock */
642#define SIMPLELOCK_LOCK(lock) /* acquire released lock */
643#define SIMPLELOCK_UNLOCK(lock) /* release acquired lock */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000644
645/*
646 * Basic types
647 * I don't care if these are defined in <sys/types.h> or elsewhere. Axiom.
648 */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000649#undef uchar
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650#define uchar unsigned char /* assuming == 8 bits */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000651
Neil Schemenauera35c6882001-02-27 04:45:05 +0000652#undef uint
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000653#define uint unsigned int /* assuming >= 16 bits */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000654
655#undef ulong
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000656#define ulong unsigned long /* assuming >= 32 bits */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000657
Tim Petersd97a1c02002-03-30 06:09:22 +0000658#undef uptr
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000659#define uptr Py_uintptr_t
Tim Petersd97a1c02002-03-30 06:09:22 +0000660
Neil Schemenauera35c6882001-02-27 04:45:05 +0000661/* When you say memory, my mind reasons in terms of (pointers to) blocks */
662typedef uchar block;
663
Tim Peterse70ddf32002-04-05 04:32:29 +0000664/* Pool for small blocks. */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000665struct pool_header {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000666 union { block *_padding;
Stefan Krah735bb122010-11-26 10:54:09 +0000667 uint count; } ref; /* number of allocated blocks */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668 block *freeblock; /* pool's free list head */
669 struct pool_header *nextpool; /* next pool of this size class */
670 struct pool_header *prevpool; /* previous pool "" */
671 uint arenaindex; /* index into arenas of base adr */
672 uint szidx; /* block size class index */
673 uint nextoffset; /* bytes to virgin block */
674 uint maxnextoffset; /* largest valid nextoffset */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000675};
676
677typedef struct pool_header *poolp;
678
Thomas Woutersa9773292006-04-21 09:43:23 +0000679/* Record keeping for arenas. */
680struct arena_object {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000681 /* The address of the arena, as returned by malloc. Note that 0
682 * will never be returned by a successful malloc, and is used
683 * here to mark an arena_object that doesn't correspond to an
684 * allocated arena.
685 */
686 uptr address;
Thomas Woutersa9773292006-04-21 09:43:23 +0000687
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000688 /* Pool-aligned pointer to the next pool to be carved off. */
689 block* pool_address;
Thomas Woutersa9773292006-04-21 09:43:23 +0000690
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000691 /* The number of available pools in the arena: free pools + never-
692 * allocated pools.
693 */
694 uint nfreepools;
Thomas Woutersa9773292006-04-21 09:43:23 +0000695
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000696 /* The total number of pools in the arena, whether or not available. */
697 uint ntotalpools;
Thomas Woutersa9773292006-04-21 09:43:23 +0000698
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000699 /* Singly-linked list of available pools. */
700 struct pool_header* freepools;
Thomas Woutersa9773292006-04-21 09:43:23 +0000701
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000702 /* Whenever this arena_object is not associated with an allocated
703 * arena, the nextarena member is used to link all unassociated
704 * arena_objects in the singly-linked `unused_arena_objects` list.
705 * The prevarena member is unused in this case.
706 *
707 * When this arena_object is associated with an allocated arena
708 * with at least one available pool, both members are used in the
709 * doubly-linked `usable_arenas` list, which is maintained in
710 * increasing order of `nfreepools` values.
711 *
712 * Else this arena_object is associated with an allocated arena
713 * all of whose pools are in use. `nextarena` and `prevarena`
714 * are both meaningless in this case.
715 */
716 struct arena_object* nextarena;
717 struct arena_object* prevarena;
Thomas Woutersa9773292006-04-21 09:43:23 +0000718};
719
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +0200720#define POOL_OVERHEAD _Py_SIZE_ROUND_UP(sizeof(struct pool_header), ALIGNMENT)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000721
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000722#define DUMMY_SIZE_IDX 0xffff /* size class of newly cached pools */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000723
Tim Petersd97a1c02002-03-30 06:09:22 +0000724/* Round pointer P down to the closest pool-aligned address <= P, as a poolp */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +0200725#define POOL_ADDR(P) ((poolp)_Py_ALIGN_DOWN((P), POOL_SIZE))
Tim Peterse70ddf32002-04-05 04:32:29 +0000726
Tim Peters16bcb6b2002-04-05 05:45:31 +0000727/* Return total number of blocks in pool of size index I, as a uint. */
728#define NUMBLOCKS(I) ((uint)(POOL_SIZE - POOL_OVERHEAD) / INDEX2SIZE(I))
Tim Petersd97a1c02002-03-30 06:09:22 +0000729
Neil Schemenauera35c6882001-02-27 04:45:05 +0000730/*==========================================================================*/
731
732/*
733 * This malloc lock
734 */
Jeremy Hyltond1fedb62002-07-18 18:49:52 +0000735SIMPLELOCK_DECL(_malloc_lock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736#define LOCK() SIMPLELOCK_LOCK(_malloc_lock)
737#define UNLOCK() SIMPLELOCK_UNLOCK(_malloc_lock)
738#define LOCK_INIT() SIMPLELOCK_INIT(_malloc_lock)
739#define LOCK_FINI() SIMPLELOCK_FINI(_malloc_lock)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000740
741/*
Tim Peters1e16db62002-03-31 01:05:22 +0000742 * Pool table -- headed, circular, doubly-linked lists of partially used pools.
743
744This is involved. For an index i, usedpools[i+i] is the header for a list of
745all partially used pools holding small blocks with "size class idx" i. So
746usedpools[0] corresponds to blocks of size 8, usedpools[2] to blocks of size
74716, and so on: index 2*i <-> blocks of size (i+1)<<ALIGNMENT_SHIFT.
748
Thomas Woutersa9773292006-04-21 09:43:23 +0000749Pools are carved off an arena's highwater mark (an arena_object's pool_address
750member) as needed. Once carved off, a pool is in one of three states forever
751after:
Tim Peters1e16db62002-03-31 01:05:22 +0000752
Tim Peters338e0102002-04-01 19:23:44 +0000753used == partially used, neither empty nor full
754 At least one block in the pool is currently allocated, and at least one
755 block in the pool is not currently allocated (note this implies a pool
756 has room for at least two blocks).
757 This is a pool's initial state, as a pool is created only when malloc
758 needs space.
759 The pool holds blocks of a fixed size, and is in the circular list headed
760 at usedpools[i] (see above). It's linked to the other used pools of the
761 same size class via the pool_header's nextpool and prevpool members.
762 If all but one block is currently allocated, a malloc can cause a
763 transition to the full state. If all but one block is not currently
764 allocated, a free can cause a transition to the empty state.
Tim Peters1e16db62002-03-31 01:05:22 +0000765
Tim Peters338e0102002-04-01 19:23:44 +0000766full == all the pool's blocks are currently allocated
767 On transition to full, a pool is unlinked from its usedpools[] list.
768 It's not linked to from anything then anymore, and its nextpool and
769 prevpool members are meaningless until it transitions back to used.
770 A free of a block in a full pool puts the pool back in the used state.
771 Then it's linked in at the front of the appropriate usedpools[] list, so
772 that the next allocation for its size class will reuse the freed block.
773
774empty == all the pool's blocks are currently available for allocation
775 On transition to empty, a pool is unlinked from its usedpools[] list,
Thomas Woutersa9773292006-04-21 09:43:23 +0000776 and linked to the front of its arena_object's singly-linked freepools list,
Tim Peters338e0102002-04-01 19:23:44 +0000777 via its nextpool member. The prevpool member has no meaning in this case.
778 Empty pools have no inherent size class: the next time a malloc finds
779 an empty list in usedpools[], it takes the first pool off of freepools.
780 If the size class needed happens to be the same as the size class the pool
Tim Peterse70ddf32002-04-05 04:32:29 +0000781 last had, some pool initialization can be skipped.
Tim Peters338e0102002-04-01 19:23:44 +0000782
783
784Block Management
785
786Blocks within pools are again carved out as needed. pool->freeblock points to
787the start of a singly-linked list of free blocks within the pool. When a
788block is freed, it's inserted at the front of its pool's freeblock list. Note
789that the available blocks in a pool are *not* linked all together when a pool
Tim Peterse70ddf32002-04-05 04:32:29 +0000790is initialized. Instead only "the first two" (lowest addresses) blocks are
791set up, returning the first such block, and setting pool->freeblock to a
792one-block list holding the second such block. This is consistent with that
793pymalloc strives at all levels (arena, pool, and block) never to touch a piece
794of memory until it's actually needed.
795
796So long as a pool is in the used state, we're certain there *is* a block
Tim Peters52aefc82002-04-11 06:36:45 +0000797available for allocating, and pool->freeblock is not NULL. If pool->freeblock
798points to the end of the free list before we've carved the entire pool into
799blocks, that means we simply haven't yet gotten to one of the higher-address
800blocks. The offset from the pool_header to the start of "the next" virgin
801block is stored in the pool_header nextoffset member, and the largest value
802of nextoffset that makes sense is stored in the maxnextoffset member when a
803pool is initialized. All the blocks in a pool have been passed out at least
804once when and only when nextoffset > maxnextoffset.
Tim Peters338e0102002-04-01 19:23:44 +0000805
Tim Peters1e16db62002-03-31 01:05:22 +0000806
807Major obscurity: While the usedpools vector is declared to have poolp
808entries, it doesn't really. It really contains two pointers per (conceptual)
809poolp entry, the nextpool and prevpool members of a pool_header. The
810excruciating initialization code below fools C so that
811
812 usedpool[i+i]
813
814"acts like" a genuine poolp, but only so long as you only reference its
815nextpool and prevpool members. The "- 2*sizeof(block *)" gibberish is
816compensating for that a pool_header's nextpool and prevpool members
817immediately follow a pool_header's first two members:
818
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000819 union { block *_padding;
Stefan Krah735bb122010-11-26 10:54:09 +0000820 uint count; } ref;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000821 block *freeblock;
Tim Peters1e16db62002-03-31 01:05:22 +0000822
823each of which consume sizeof(block *) bytes. So what usedpools[i+i] really
824contains is a fudged-up pointer p such that *if* C believes it's a poolp
825pointer, then p->nextpool and p->prevpool are both p (meaning that the headed
826circular list is empty).
827
828It's unclear why the usedpools setup is so convoluted. It could be to
829minimize the amount of cache required to hold this heavily-referenced table
830(which only *needs* the two interpool pointer members of a pool_header). OTOH,
831referencing code has to remember to "double the index" and doing so isn't
832free, usedpools[0] isn't a strictly legal pointer, and we're crucially relying
833on that C doesn't insert any padding anywhere in a pool_header at or before
834the prevpool member.
835**************************************************************************** */
836
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000837#define PTA(x) ((poolp )((uchar *)&(usedpools[2*(x)]) - 2*sizeof(block *)))
838#define PT(x) PTA(x), PTA(x)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000839
840static poolp usedpools[2 * ((NB_SMALL_SIZE_CLASSES + 7) / 8) * 8] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000841 PT(0), PT(1), PT(2), PT(3), PT(4), PT(5), PT(6), PT(7)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000842#if NB_SMALL_SIZE_CLASSES > 8
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000843 , PT(8), PT(9), PT(10), PT(11), PT(12), PT(13), PT(14), PT(15)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000844#if NB_SMALL_SIZE_CLASSES > 16
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000845 , PT(16), PT(17), PT(18), PT(19), PT(20), PT(21), PT(22), PT(23)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000846#if NB_SMALL_SIZE_CLASSES > 24
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000847 , PT(24), PT(25), PT(26), PT(27), PT(28), PT(29), PT(30), PT(31)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000848#if NB_SMALL_SIZE_CLASSES > 32
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 , PT(32), PT(33), PT(34), PT(35), PT(36), PT(37), PT(38), PT(39)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000850#if NB_SMALL_SIZE_CLASSES > 40
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000851 , PT(40), PT(41), PT(42), PT(43), PT(44), PT(45), PT(46), PT(47)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000852#if NB_SMALL_SIZE_CLASSES > 48
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000853 , PT(48), PT(49), PT(50), PT(51), PT(52), PT(53), PT(54), PT(55)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000854#if NB_SMALL_SIZE_CLASSES > 56
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 , PT(56), PT(57), PT(58), PT(59), PT(60), PT(61), PT(62), PT(63)
Antoine Pitrou6f26be02011-05-03 18:18:59 +0200856#if NB_SMALL_SIZE_CLASSES > 64
857#error "NB_SMALL_SIZE_CLASSES should be less than 64"
858#endif /* NB_SMALL_SIZE_CLASSES > 64 */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000859#endif /* NB_SMALL_SIZE_CLASSES > 56 */
860#endif /* NB_SMALL_SIZE_CLASSES > 48 */
861#endif /* NB_SMALL_SIZE_CLASSES > 40 */
862#endif /* NB_SMALL_SIZE_CLASSES > 32 */
863#endif /* NB_SMALL_SIZE_CLASSES > 24 */
864#endif /* NB_SMALL_SIZE_CLASSES > 16 */
865#endif /* NB_SMALL_SIZE_CLASSES > 8 */
866};
867
Thomas Woutersa9773292006-04-21 09:43:23 +0000868/*==========================================================================
869Arena management.
Neil Schemenauera35c6882001-02-27 04:45:05 +0000870
Thomas Woutersa9773292006-04-21 09:43:23 +0000871`arenas` is a vector of arena_objects. It contains maxarenas entries, some of
872which may not be currently used (== they're arena_objects that aren't
873currently associated with an allocated arena). Note that arenas proper are
874separately malloc'ed.
Neil Schemenauera35c6882001-02-27 04:45:05 +0000875
Thomas Woutersa9773292006-04-21 09:43:23 +0000876Prior to Python 2.5, arenas were never free()'ed. Starting with Python 2.5,
877we do try to free() arenas, and use some mild heuristic strategies to increase
878the likelihood that arenas eventually can be freed.
879
880unused_arena_objects
881
882 This is a singly-linked list of the arena_objects that are currently not
883 being used (no arena is associated with them). Objects are taken off the
884 head of the list in new_arena(), and are pushed on the head of the list in
885 PyObject_Free() when the arena is empty. Key invariant: an arena_object
886 is on this list if and only if its .address member is 0.
887
888usable_arenas
889
890 This is a doubly-linked list of the arena_objects associated with arenas
891 that have pools available. These pools are either waiting to be reused,
892 or have not been used before. The list is sorted to have the most-
893 allocated arenas first (ascending order based on the nfreepools member).
894 This means that the next allocation will come from a heavily used arena,
895 which gives the nearly empty arenas a chance to be returned to the system.
896 In my unscientific tests this dramatically improved the number of arenas
897 that could be freed.
898
899Note that an arena_object associated with an arena all of whose pools are
900currently in use isn't on either list.
901*/
902
903/* Array of objects used to track chunks of memory (arenas). */
904static struct arena_object* arenas = NULL;
905/* Number of slots currently allocated in the `arenas` vector. */
Tim Peters1d99af82002-03-30 10:35:09 +0000906static uint maxarenas = 0;
Tim Petersd97a1c02002-03-30 06:09:22 +0000907
Thomas Woutersa9773292006-04-21 09:43:23 +0000908/* The head of the singly-linked, NULL-terminated list of available
909 * arena_objects.
Tim Petersd97a1c02002-03-30 06:09:22 +0000910 */
Thomas Woutersa9773292006-04-21 09:43:23 +0000911static struct arena_object* unused_arena_objects = NULL;
912
913/* The head of the doubly-linked, NULL-terminated at each end, list of
914 * arena_objects associated with arenas that have pools available.
915 */
916static struct arena_object* usable_arenas = NULL;
917
918/* How many arena_objects do we initially allocate?
919 * 16 = can allocate 16 arenas = 16 * ARENA_SIZE = 4MB before growing the
920 * `arenas` vector.
921 */
922#define INITIAL_ARENA_OBJECTS 16
923
924/* Number of arenas allocated that haven't been free()'d. */
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000925static size_t narenas_currently_allocated = 0;
Thomas Woutersa9773292006-04-21 09:43:23 +0000926
Thomas Woutersa9773292006-04-21 09:43:23 +0000927/* Total number of times malloc() called to allocate an arena. */
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000928static size_t ntimes_arena_allocated = 0;
Thomas Woutersa9773292006-04-21 09:43:23 +0000929/* High water mark (max value ever seen) for narenas_currently_allocated. */
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000930static size_t narenas_highwater = 0;
Thomas Woutersa9773292006-04-21 09:43:23 +0000931
Antoine Pitrouf9d0b122012-12-09 14:28:26 +0100932static Py_ssize_t _Py_AllocatedBlocks = 0;
933
934Py_ssize_t
935_Py_GetAllocatedBlocks(void)
936{
937 return _Py_AllocatedBlocks;
938}
939
940
Thomas Woutersa9773292006-04-21 09:43:23 +0000941/* Allocate a new arena. If we run out of memory, return NULL. Else
942 * allocate a new arena, and return the address of an arena_object
943 * describing the new arena. It's expected that the caller will set
944 * `usable_arenas` to the return value.
945 */
946static struct arena_object*
Tim Petersd97a1c02002-03-30 06:09:22 +0000947new_arena(void)
948{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 struct arena_object* arenaobj;
950 uint excess; /* number of bytes above pool alignment */
Victor Stinnerba108822012-03-10 00:21:44 +0100951 void *address;
Tim Petersd97a1c02002-03-30 06:09:22 +0000952
Tim Peters0e871182002-04-13 08:29:14 +0000953#ifdef PYMALLOC_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000954 if (Py_GETENV("PYTHONMALLOCSTATS"))
David Malcolm49526f42012-06-22 14:55:41 -0400955 _PyObject_DebugMallocStats(stderr);
Tim Peters0e871182002-04-13 08:29:14 +0000956#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000957 if (unused_arena_objects == NULL) {
958 uint i;
959 uint numarenas;
960 size_t nbytes;
Tim Peters0e871182002-04-13 08:29:14 +0000961
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000962 /* Double the number of arena objects on each allocation.
963 * Note that it's possible for `numarenas` to overflow.
964 */
965 numarenas = maxarenas ? maxarenas << 1 : INITIAL_ARENA_OBJECTS;
966 if (numarenas <= maxarenas)
967 return NULL; /* overflow */
Martin v. Löwis5aca8822008-09-11 06:55:48 +0000968#if SIZEOF_SIZE_T <= SIZEOF_INT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 if (numarenas > PY_SIZE_MAX / sizeof(*arenas))
970 return NULL; /* overflow */
Martin v. Löwis5aca8822008-09-11 06:55:48 +0000971#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 nbytes = numarenas * sizeof(*arenas);
Victor Stinner6cf185d2013-10-10 15:58:42 +0200973 arenaobj = (struct arena_object *)PyMem_RawRealloc(arenas, nbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 if (arenaobj == NULL)
975 return NULL;
976 arenas = arenaobj;
Thomas Woutersa9773292006-04-21 09:43:23 +0000977
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 /* We might need to fix pointers that were copied. However,
979 * new_arena only gets called when all the pages in the
980 * previous arenas are full. Thus, there are *no* pointers
981 * into the old array. Thus, we don't have to worry about
982 * invalid pointers. Just to be sure, some asserts:
983 */
984 assert(usable_arenas == NULL);
985 assert(unused_arena_objects == NULL);
Thomas Woutersa9773292006-04-21 09:43:23 +0000986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987 /* Put the new arenas on the unused_arena_objects list. */
988 for (i = maxarenas; i < numarenas; ++i) {
989 arenas[i].address = 0; /* mark as unassociated */
990 arenas[i].nextarena = i < numarenas - 1 ?
991 &arenas[i+1] : NULL;
992 }
Thomas Woutersa9773292006-04-21 09:43:23 +0000993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000994 /* Update globals. */
995 unused_arena_objects = &arenas[maxarenas];
996 maxarenas = numarenas;
997 }
Tim Petersd97a1c02002-03-30 06:09:22 +0000998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 /* Take the next available arena object off the head of the list. */
1000 assert(unused_arena_objects != NULL);
1001 arenaobj = unused_arena_objects;
1002 unused_arena_objects = arenaobj->nextarena;
1003 assert(arenaobj->address == 0);
Victor Stinner0507bf52013-07-07 02:05:46 +02001004 address = _PyObject_Arena.alloc(_PyObject_Arena.ctx, ARENA_SIZE);
1005 if (address == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001006 /* The allocation failed: return NULL after putting the
1007 * arenaobj back.
1008 */
1009 arenaobj->nextarena = unused_arena_objects;
1010 unused_arena_objects = arenaobj;
1011 return NULL;
1012 }
Victor Stinnerba108822012-03-10 00:21:44 +01001013 arenaobj->address = (uptr)address;
Tim Petersd97a1c02002-03-30 06:09:22 +00001014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 ++narenas_currently_allocated;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 ++ntimes_arena_allocated;
1017 if (narenas_currently_allocated > narenas_highwater)
1018 narenas_highwater = narenas_currently_allocated;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 arenaobj->freepools = NULL;
1020 /* pool_address <- first pool-aligned address in the arena
1021 nfreepools <- number of whole pools that fit after alignment */
1022 arenaobj->pool_address = (block*)arenaobj->address;
1023 arenaobj->nfreepools = ARENA_SIZE / POOL_SIZE;
1024 assert(POOL_SIZE * arenaobj->nfreepools == ARENA_SIZE);
1025 excess = (uint)(arenaobj->address & POOL_SIZE_MASK);
1026 if (excess != 0) {
1027 --arenaobj->nfreepools;
1028 arenaobj->pool_address += POOL_SIZE - excess;
1029 }
1030 arenaobj->ntotalpools = arenaobj->nfreepools;
Thomas Woutersa9773292006-04-21 09:43:23 +00001031
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001032 return arenaobj;
Tim Petersd97a1c02002-03-30 06:09:22 +00001033}
1034
Thomas Woutersa9773292006-04-21 09:43:23 +00001035/*
1036Py_ADDRESS_IN_RANGE(P, POOL)
1037
1038Return true if and only if P is an address that was allocated by pymalloc.
1039POOL must be the pool address associated with P, i.e., POOL = POOL_ADDR(P)
1040(the caller is asked to compute this because the macro expands POOL more than
1041once, and for efficiency it's best for the caller to assign POOL_ADDR(P) to a
1042variable and pass the latter to the macro; because Py_ADDRESS_IN_RANGE is
1043called on every alloc/realloc/free, micro-efficiency is important here).
1044
1045Tricky: Let B be the arena base address associated with the pool, B =
1046arenas[(POOL)->arenaindex].address. Then P belongs to the arena if and only if
1047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 B <= P < B + ARENA_SIZE
Thomas Woutersa9773292006-04-21 09:43:23 +00001049
1050Subtracting B throughout, this is true iff
1051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 0 <= P-B < ARENA_SIZE
Thomas Woutersa9773292006-04-21 09:43:23 +00001053
1054By using unsigned arithmetic, the "0 <=" half of the test can be skipped.
1055
1056Obscure: A PyMem "free memory" function can call the pymalloc free or realloc
1057before the first arena has been allocated. `arenas` is still NULL in that
1058case. We're relying on that maxarenas is also 0 in that case, so that
1059(POOL)->arenaindex < maxarenas must be false, saving us from trying to index
1060into a NULL arenas.
1061
1062Details: given P and POOL, the arena_object corresponding to P is AO =
1063arenas[(POOL)->arenaindex]. Suppose obmalloc controls P. Then (barring wild
1064stores, etc), POOL is the correct address of P's pool, AO.address is the
1065correct base address of the pool's arena, and P must be within ARENA_SIZE of
1066AO.address. In addition, AO.address is not 0 (no arena can start at address 0
1067(NULL)). Therefore Py_ADDRESS_IN_RANGE correctly reports that obmalloc
1068controls P.
1069
1070Now suppose obmalloc does not control P (e.g., P was obtained via a direct
1071call to the system malloc() or realloc()). (POOL)->arenaindex may be anything
1072in this case -- it may even be uninitialized trash. If the trash arenaindex
1073is >= maxarenas, the macro correctly concludes at once that obmalloc doesn't
1074control P.
1075
1076Else arenaindex is < maxarena, and AO is read up. If AO corresponds to an
1077allocated arena, obmalloc controls all the memory in slice AO.address :
1078AO.address+ARENA_SIZE. By case assumption, P is not controlled by obmalloc,
1079so P doesn't lie in that slice, so the macro correctly reports that P is not
1080controlled by obmalloc.
1081
1082Finally, if P is not controlled by obmalloc and AO corresponds to an unused
1083arena_object (one not currently associated with an allocated arena),
1084AO.address is 0, and the second test in the macro reduces to:
1085
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001086 P < ARENA_SIZE
Thomas Woutersa9773292006-04-21 09:43:23 +00001087
1088If P >= ARENA_SIZE (extremely likely), the macro again correctly concludes
1089that P is not controlled by obmalloc. However, if P < ARENA_SIZE, this part
1090of the test still passes, and the third clause (AO.address != 0) is necessary
1091to get the correct result: AO.address is 0 in this case, so the macro
1092correctly reports that P is not controlled by obmalloc (despite that P lies in
1093slice AO.address : AO.address + ARENA_SIZE).
1094
1095Note: The third (AO.address != 0) clause was added in Python 2.5. Before
10962.5, arenas were never free()'ed, and an arenaindex < maxarena always
1097corresponded to a currently-allocated arena, so the "P is not controlled by
1098obmalloc, AO corresponds to an unused arena_object, and P < ARENA_SIZE" case
1099was impossible.
1100
1101Note that the logic is excruciating, and reading up possibly uninitialized
1102memory when P is not controlled by obmalloc (to get at (POOL)->arenaindex)
1103creates problems for some memory debuggers. The overwhelming advantage is
1104that this test determines whether an arbitrary address is controlled by
1105obmalloc in a small constant time, independent of the number of arenas
1106obmalloc controls. Since this test is needed at every entry point, it's
1107extremely desirable that it be this fast.
Antoine Pitroub7fb2e22011-01-07 21:43:59 +00001108
1109Since Py_ADDRESS_IN_RANGE may be reading from memory which was not allocated
1110by Python, it is important that (POOL)->arenaindex is read only once, as
1111another thread may be concurrently modifying the value without holding the
1112GIL. To accomplish this, the arenaindex_temp variable is used to store
1113(POOL)->arenaindex for the duration of the Py_ADDRESS_IN_RANGE macro's
1114execution. The caller of the macro is responsible for declaring this
1115variable.
Thomas Woutersa9773292006-04-21 09:43:23 +00001116*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001117#define Py_ADDRESS_IN_RANGE(P, POOL) \
Antoine Pitroub7fb2e22011-01-07 21:43:59 +00001118 ((arenaindex_temp = (POOL)->arenaindex) < maxarenas && \
1119 (uptr)(P) - arenas[arenaindex_temp].address < (uptr)ARENA_SIZE && \
1120 arenas[arenaindex_temp].address != 0)
Thomas Woutersa9773292006-04-21 09:43:23 +00001121
Neal Norwitz7eb3c912004-06-06 19:20:22 +00001122
1123/* This is only useful when running memory debuggers such as
1124 * Purify or Valgrind. Uncomment to use.
1125 *
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001126#define Py_USING_MEMORY_DEBUGGER
Martin v. Löwis6fea2332008-09-25 04:15:27 +00001127 */
Neal Norwitz7eb3c912004-06-06 19:20:22 +00001128
1129#ifdef Py_USING_MEMORY_DEBUGGER
1130
1131/* Py_ADDRESS_IN_RANGE may access uninitialized memory by design
1132 * This leads to thousands of spurious warnings when using
1133 * Purify or Valgrind. By making a function, we can easily
1134 * suppress the uninitialized memory reads in this one function.
1135 * So we won't ignore real errors elsewhere.
1136 *
1137 * Disable the macro and use a function.
1138 */
1139
1140#undef Py_ADDRESS_IN_RANGE
1141
Thomas Wouters89f507f2006-12-13 04:49:30 +00001142#if defined(__GNUC__) && ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 1) || \
Stefan Krah735bb122010-11-26 10:54:09 +00001143 (__GNUC__ >= 4))
Neal Norwitze5e5aa42005-11-13 18:55:39 +00001144#define Py_NO_INLINE __attribute__((__noinline__))
1145#else
1146#define Py_NO_INLINE
1147#endif
1148
1149/* Don't make static, to try to ensure this isn't inlined. */
1150int Py_ADDRESS_IN_RANGE(void *P, poolp pool) Py_NO_INLINE;
1151#undef Py_NO_INLINE
Neal Norwitz7eb3c912004-06-06 19:20:22 +00001152#endif
Tim Peters338e0102002-04-01 19:23:44 +00001153
Neil Schemenauera35c6882001-02-27 04:45:05 +00001154/*==========================================================================*/
1155
Tim Peters84c1b972002-04-04 04:44:32 +00001156/* malloc. Note that nbytes==0 tries to return a non-NULL pointer, distinct
1157 * from all other currently live pointers. This may not be possible.
1158 */
Neil Schemenauera35c6882001-02-27 04:45:05 +00001159
1160/*
1161 * The basic blocks are ordered by decreasing execution frequency,
1162 * which minimizes the number of jumps in the most common cases,
1163 * improves branching prediction and instruction scheduling (small
1164 * block allocations typically result in a couple of instructions).
1165 * Unless the optimizer reorders everything, being too smart...
1166 */
1167
Victor Stinner0507bf52013-07-07 02:05:46 +02001168static void *
Victor Stinnerdb067af2014-05-02 22:31:14 +02001169_PyObject_Alloc(int use_calloc, void *ctx, size_t nelem, size_t elsize)
Neil Schemenauera35c6882001-02-27 04:45:05 +00001170{
Victor Stinnerdb067af2014-05-02 22:31:14 +02001171 size_t nbytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001172 block *bp;
1173 poolp pool;
1174 poolp next;
1175 uint size;
Neil Schemenauera35c6882001-02-27 04:45:05 +00001176
Antoine Pitrou0aaaa622013-04-06 01:15:30 +02001177 _Py_AllocatedBlocks++;
1178
Victor Stinner3080d922014-05-06 11:32:29 +02001179 assert(nelem <= PY_SSIZE_T_MAX / elsize);
1180 nbytes = nelem * elsize;
1181
Benjamin Peterson05159c42009-12-03 03:01:27 +00001182#ifdef WITH_VALGRIND
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 if (UNLIKELY(running_on_valgrind == -1))
1184 running_on_valgrind = RUNNING_ON_VALGRIND;
1185 if (UNLIKELY(running_on_valgrind))
1186 goto redirect;
Benjamin Peterson05159c42009-12-03 03:01:27 +00001187#endif
1188
Victor Stinneraf8fc642014-05-02 23:26:03 +02001189 if (nelem == 0 || elsize == 0)
1190 goto redirect;
1191
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001192 if ((nbytes - 1) < SMALL_REQUEST_THRESHOLD) {
1193 LOCK();
1194 /*
1195 * Most frequent paths first
1196 */
1197 size = (uint)(nbytes - 1) >> ALIGNMENT_SHIFT;
1198 pool = usedpools[size + size];
1199 if (pool != pool->nextpool) {
1200 /*
1201 * There is a used pool for this size class.
1202 * Pick up the head block of its free list.
1203 */
1204 ++pool->ref.count;
1205 bp = pool->freeblock;
1206 assert(bp != NULL);
1207 if ((pool->freeblock = *(block **)bp) != NULL) {
1208 UNLOCK();
Victor Stinnerdb067af2014-05-02 22:31:14 +02001209 if (use_calloc)
1210 memset(bp, 0, nbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001211 return (void *)bp;
1212 }
1213 /*
1214 * Reached the end of the free list, try to extend it.
1215 */
1216 if (pool->nextoffset <= pool->maxnextoffset) {
1217 /* There is room for another block. */
1218 pool->freeblock = (block*)pool +
1219 pool->nextoffset;
1220 pool->nextoffset += INDEX2SIZE(size);
1221 *(block **)(pool->freeblock) = NULL;
1222 UNLOCK();
Victor Stinnerdb067af2014-05-02 22:31:14 +02001223 if (use_calloc)
1224 memset(bp, 0, nbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 return (void *)bp;
1226 }
1227 /* Pool is full, unlink from used pools. */
1228 next = pool->nextpool;
1229 pool = pool->prevpool;
1230 next->prevpool = pool;
1231 pool->nextpool = next;
1232 UNLOCK();
Victor Stinnerdb067af2014-05-02 22:31:14 +02001233 if (use_calloc)
1234 memset(bp, 0, nbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001235 return (void *)bp;
1236 }
Thomas Woutersa9773292006-04-21 09:43:23 +00001237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001238 /* There isn't a pool of the right size class immediately
1239 * available: use a free pool.
1240 */
1241 if (usable_arenas == NULL) {
1242 /* No arena has a free pool: allocate a new arena. */
Thomas Woutersa9773292006-04-21 09:43:23 +00001243#ifdef WITH_MEMORY_LIMITS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001244 if (narenas_currently_allocated >= MAX_ARENAS) {
1245 UNLOCK();
1246 goto redirect;
1247 }
Thomas Woutersa9773292006-04-21 09:43:23 +00001248#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001249 usable_arenas = new_arena();
1250 if (usable_arenas == NULL) {
1251 UNLOCK();
1252 goto redirect;
1253 }
1254 usable_arenas->nextarena =
1255 usable_arenas->prevarena = NULL;
1256 }
1257 assert(usable_arenas->address != 0);
Thomas Woutersa9773292006-04-21 09:43:23 +00001258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001259 /* Try to get a cached free pool. */
1260 pool = usable_arenas->freepools;
1261 if (pool != NULL) {
1262 /* Unlink from cached pools. */
1263 usable_arenas->freepools = pool->nextpool;
Thomas Woutersa9773292006-04-21 09:43:23 +00001264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001265 /* This arena already had the smallest nfreepools
1266 * value, so decreasing nfreepools doesn't change
1267 * that, and we don't need to rearrange the
1268 * usable_arenas list. However, if the arena has
1269 * become wholly allocated, we need to remove its
1270 * arena_object from usable_arenas.
1271 */
1272 --usable_arenas->nfreepools;
1273 if (usable_arenas->nfreepools == 0) {
1274 /* Wholly allocated: remove. */
1275 assert(usable_arenas->freepools == NULL);
1276 assert(usable_arenas->nextarena == NULL ||
1277 usable_arenas->nextarena->prevarena ==
1278 usable_arenas);
Thomas Woutersa9773292006-04-21 09:43:23 +00001279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001280 usable_arenas = usable_arenas->nextarena;
1281 if (usable_arenas != NULL) {
1282 usable_arenas->prevarena = NULL;
1283 assert(usable_arenas->address != 0);
1284 }
1285 }
1286 else {
1287 /* nfreepools > 0: it must be that freepools
1288 * isn't NULL, or that we haven't yet carved
1289 * off all the arena's pools for the first
1290 * time.
1291 */
1292 assert(usable_arenas->freepools != NULL ||
1293 usable_arenas->pool_address <=
1294 (block*)usable_arenas->address +
1295 ARENA_SIZE - POOL_SIZE);
1296 }
1297 init_pool:
1298 /* Frontlink to used pools. */
1299 next = usedpools[size + size]; /* == prev */
1300 pool->nextpool = next;
1301 pool->prevpool = next;
1302 next->nextpool = pool;
1303 next->prevpool = pool;
1304 pool->ref.count = 1;
1305 if (pool->szidx == size) {
1306 /* Luckily, this pool last contained blocks
1307 * of the same size class, so its header
1308 * and free list are already initialized.
1309 */
1310 bp = pool->freeblock;
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001311 assert(bp != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001312 pool->freeblock = *(block **)bp;
1313 UNLOCK();
Victor Stinnerdb067af2014-05-02 22:31:14 +02001314 if (use_calloc)
1315 memset(bp, 0, nbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001316 return (void *)bp;
1317 }
1318 /*
1319 * Initialize the pool header, set up the free list to
1320 * contain just the second block, and return the first
1321 * block.
1322 */
1323 pool->szidx = size;
1324 size = INDEX2SIZE(size);
1325 bp = (block *)pool + POOL_OVERHEAD;
1326 pool->nextoffset = POOL_OVERHEAD + (size << 1);
1327 pool->maxnextoffset = POOL_SIZE - size;
1328 pool->freeblock = bp + size;
1329 *(block **)(pool->freeblock) = NULL;
1330 UNLOCK();
Victor Stinnerdb067af2014-05-02 22:31:14 +02001331 if (use_calloc)
1332 memset(bp, 0, nbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001333 return (void *)bp;
1334 }
Thomas Woutersa9773292006-04-21 09:43:23 +00001335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001336 /* Carve off a new pool. */
1337 assert(usable_arenas->nfreepools > 0);
1338 assert(usable_arenas->freepools == NULL);
1339 pool = (poolp)usable_arenas->pool_address;
1340 assert((block*)pool <= (block*)usable_arenas->address +
1341 ARENA_SIZE - POOL_SIZE);
Serhiy Storchaka26861b02015-02-16 20:52:17 +02001342 pool->arenaindex = (uint)(usable_arenas - arenas);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001343 assert(&arenas[pool->arenaindex] == usable_arenas);
1344 pool->szidx = DUMMY_SIZE_IDX;
1345 usable_arenas->pool_address += POOL_SIZE;
1346 --usable_arenas->nfreepools;
Thomas Woutersa9773292006-04-21 09:43:23 +00001347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001348 if (usable_arenas->nfreepools == 0) {
1349 assert(usable_arenas->nextarena == NULL ||
1350 usable_arenas->nextarena->prevarena ==
1351 usable_arenas);
1352 /* Unlink the arena: it is completely allocated. */
1353 usable_arenas = usable_arenas->nextarena;
1354 if (usable_arenas != NULL) {
1355 usable_arenas->prevarena = NULL;
1356 assert(usable_arenas->address != 0);
1357 }
1358 }
Thomas Woutersa9773292006-04-21 09:43:23 +00001359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001360 goto init_pool;
1361 }
Neil Schemenauera35c6882001-02-27 04:45:05 +00001362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001363 /* The small block allocator ends here. */
Neil Schemenauera35c6882001-02-27 04:45:05 +00001364
Tim Petersd97a1c02002-03-30 06:09:22 +00001365redirect:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001366 /* Redirect the original request to the underlying (libc) allocator.
1367 * We jump here on bigger requests, on error in the code above (as a
1368 * last chance to serve the request) or when the max memory limit
1369 * has been reached.
1370 */
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001371 {
Victor Stinnerdb067af2014-05-02 22:31:14 +02001372 void *result;
1373 if (use_calloc)
1374 result = PyMem_RawCalloc(nelem, elsize);
1375 else
1376 result = PyMem_RawMalloc(nbytes);
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001377 if (!result)
1378 _Py_AllocatedBlocks--;
1379 return result;
1380 }
Neil Schemenauera35c6882001-02-27 04:45:05 +00001381}
1382
Victor Stinnerdb067af2014-05-02 22:31:14 +02001383static void *
1384_PyObject_Malloc(void *ctx, size_t nbytes)
1385{
1386 return _PyObject_Alloc(0, ctx, 1, nbytes);
1387}
1388
1389static void *
1390_PyObject_Calloc(void *ctx, size_t nelem, size_t elsize)
1391{
1392 return _PyObject_Alloc(1, ctx, nelem, elsize);
1393}
1394
Neil Schemenauera35c6882001-02-27 04:45:05 +00001395/* free */
1396
Nick Coghlan6ba64f42013-09-29 00:28:55 +10001397ATTRIBUTE_NO_ADDRESS_SAFETY_ANALYSIS
Victor Stinner0507bf52013-07-07 02:05:46 +02001398static void
1399_PyObject_Free(void *ctx, void *p)
Neil Schemenauera35c6882001-02-27 04:45:05 +00001400{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001401 poolp pool;
1402 block *lastfree;
1403 poolp next, prev;
1404 uint size;
Antoine Pitroub7fb2e22011-01-07 21:43:59 +00001405#ifndef Py_USING_MEMORY_DEBUGGER
1406 uint arenaindex_temp;
1407#endif
Neil Schemenauera35c6882001-02-27 04:45:05 +00001408
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001409 if (p == NULL) /* free(NULL) has no effect */
1410 return;
Neil Schemenauera35c6882001-02-27 04:45:05 +00001411
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001412 _Py_AllocatedBlocks--;
1413
Benjamin Peterson05159c42009-12-03 03:01:27 +00001414#ifdef WITH_VALGRIND
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001415 if (UNLIKELY(running_on_valgrind > 0))
1416 goto redirect;
Benjamin Peterson05159c42009-12-03 03:01:27 +00001417#endif
1418
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001419 pool = POOL_ADDR(p);
1420 if (Py_ADDRESS_IN_RANGE(p, pool)) {
1421 /* We allocated this address. */
1422 LOCK();
1423 /* Link p to the start of the pool's freeblock list. Since
1424 * the pool had at least the p block outstanding, the pool
1425 * wasn't empty (so it's already in a usedpools[] list, or
1426 * was full and is in no list -- it's not in the freeblocks
1427 * list in any case).
1428 */
1429 assert(pool->ref.count > 0); /* else it was empty */
1430 *(block **)p = lastfree = pool->freeblock;
1431 pool->freeblock = (block *)p;
1432 if (lastfree) {
1433 struct arena_object* ao;
1434 uint nf; /* ao->nfreepools */
Thomas Woutersa9773292006-04-21 09:43:23 +00001435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001436 /* freeblock wasn't NULL, so the pool wasn't full,
1437 * and the pool is in a usedpools[] list.
1438 */
1439 if (--pool->ref.count != 0) {
1440 /* pool isn't empty: leave it in usedpools */
1441 UNLOCK();
1442 return;
1443 }
1444 /* Pool is now empty: unlink from usedpools, and
1445 * link to the front of freepools. This ensures that
1446 * previously freed pools will be allocated later
1447 * (being not referenced, they are perhaps paged out).
1448 */
1449 next = pool->nextpool;
1450 prev = pool->prevpool;
1451 next->prevpool = prev;
1452 prev->nextpool = next;
Thomas Woutersa9773292006-04-21 09:43:23 +00001453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001454 /* Link the pool to freepools. This is a singly-linked
1455 * list, and pool->prevpool isn't used there.
1456 */
1457 ao = &arenas[pool->arenaindex];
1458 pool->nextpool = ao->freepools;
1459 ao->freepools = pool;
1460 nf = ++ao->nfreepools;
Thomas Woutersa9773292006-04-21 09:43:23 +00001461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001462 /* All the rest is arena management. We just freed
1463 * a pool, and there are 4 cases for arena mgmt:
1464 * 1. If all the pools are free, return the arena to
1465 * the system free().
1466 * 2. If this is the only free pool in the arena,
1467 * add the arena back to the `usable_arenas` list.
1468 * 3. If the "next" arena has a smaller count of free
1469 * pools, we have to "slide this arena right" to
1470 * restore that usable_arenas is sorted in order of
1471 * nfreepools.
1472 * 4. Else there's nothing more to do.
1473 */
1474 if (nf == ao->ntotalpools) {
1475 /* Case 1. First unlink ao from usable_arenas.
1476 */
1477 assert(ao->prevarena == NULL ||
1478 ao->prevarena->address != 0);
1479 assert(ao ->nextarena == NULL ||
1480 ao->nextarena->address != 0);
Thomas Woutersa9773292006-04-21 09:43:23 +00001481
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001482 /* Fix the pointer in the prevarena, or the
1483 * usable_arenas pointer.
1484 */
1485 if (ao->prevarena == NULL) {
1486 usable_arenas = ao->nextarena;
1487 assert(usable_arenas == NULL ||
1488 usable_arenas->address != 0);
1489 }
1490 else {
1491 assert(ao->prevarena->nextarena == ao);
1492 ao->prevarena->nextarena =
1493 ao->nextarena;
1494 }
1495 /* Fix the pointer in the nextarena. */
1496 if (ao->nextarena != NULL) {
1497 assert(ao->nextarena->prevarena == ao);
1498 ao->nextarena->prevarena =
1499 ao->prevarena;
1500 }
1501 /* Record that this arena_object slot is
1502 * available to be reused.
1503 */
1504 ao->nextarena = unused_arena_objects;
1505 unused_arena_objects = ao;
Thomas Woutersa9773292006-04-21 09:43:23 +00001506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001507 /* Free the entire arena. */
Victor Stinner0507bf52013-07-07 02:05:46 +02001508 _PyObject_Arena.free(_PyObject_Arena.ctx,
1509 (void *)ao->address, ARENA_SIZE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001510 ao->address = 0; /* mark unassociated */
1511 --narenas_currently_allocated;
Thomas Woutersa9773292006-04-21 09:43:23 +00001512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001513 UNLOCK();
1514 return;
1515 }
1516 if (nf == 1) {
1517 /* Case 2. Put ao at the head of
1518 * usable_arenas. Note that because
1519 * ao->nfreepools was 0 before, ao isn't
1520 * currently on the usable_arenas list.
1521 */
1522 ao->nextarena = usable_arenas;
1523 ao->prevarena = NULL;
1524 if (usable_arenas)
1525 usable_arenas->prevarena = ao;
1526 usable_arenas = ao;
1527 assert(usable_arenas->address != 0);
Thomas Woutersa9773292006-04-21 09:43:23 +00001528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001529 UNLOCK();
1530 return;
1531 }
1532 /* If this arena is now out of order, we need to keep
1533 * the list sorted. The list is kept sorted so that
1534 * the "most full" arenas are used first, which allows
1535 * the nearly empty arenas to be completely freed. In
1536 * a few un-scientific tests, it seems like this
1537 * approach allowed a lot more memory to be freed.
1538 */
1539 if (ao->nextarena == NULL ||
1540 nf <= ao->nextarena->nfreepools) {
1541 /* Case 4. Nothing to do. */
1542 UNLOCK();
1543 return;
1544 }
1545 /* Case 3: We have to move the arena towards the end
1546 * of the list, because it has more free pools than
1547 * the arena to its right.
1548 * First unlink ao from usable_arenas.
1549 */
1550 if (ao->prevarena != NULL) {
1551 /* ao isn't at the head of the list */
1552 assert(ao->prevarena->nextarena == ao);
1553 ao->prevarena->nextarena = ao->nextarena;
1554 }
1555 else {
1556 /* ao is at the head of the list */
1557 assert(usable_arenas == ao);
1558 usable_arenas = ao->nextarena;
1559 }
1560 ao->nextarena->prevarena = ao->prevarena;
Thomas Woutersa9773292006-04-21 09:43:23 +00001561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001562 /* Locate the new insertion point by iterating over
1563 * the list, using our nextarena pointer.
1564 */
1565 while (ao->nextarena != NULL &&
1566 nf > ao->nextarena->nfreepools) {
1567 ao->prevarena = ao->nextarena;
1568 ao->nextarena = ao->nextarena->nextarena;
1569 }
Thomas Woutersa9773292006-04-21 09:43:23 +00001570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001571 /* Insert ao at this point. */
1572 assert(ao->nextarena == NULL ||
1573 ao->prevarena == ao->nextarena->prevarena);
1574 assert(ao->prevarena->nextarena == ao->nextarena);
Thomas Woutersa9773292006-04-21 09:43:23 +00001575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001576 ao->prevarena->nextarena = ao;
1577 if (ao->nextarena != NULL)
1578 ao->nextarena->prevarena = ao;
Thomas Woutersa9773292006-04-21 09:43:23 +00001579
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001580 /* Verify that the swaps worked. */
1581 assert(ao->nextarena == NULL ||
1582 nf <= ao->nextarena->nfreepools);
1583 assert(ao->prevarena == NULL ||
1584 nf > ao->prevarena->nfreepools);
1585 assert(ao->nextarena == NULL ||
1586 ao->nextarena->prevarena == ao);
1587 assert((usable_arenas == ao &&
1588 ao->prevarena == NULL) ||
1589 ao->prevarena->nextarena == ao);
Thomas Woutersa9773292006-04-21 09:43:23 +00001590
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001591 UNLOCK();
1592 return;
1593 }
1594 /* Pool was full, so doesn't currently live in any list:
1595 * link it to the front of the appropriate usedpools[] list.
1596 * This mimics LRU pool usage for new allocations and
1597 * targets optimal filling when several pools contain
1598 * blocks of the same size class.
1599 */
1600 --pool->ref.count;
1601 assert(pool->ref.count > 0); /* else the pool is empty */
1602 size = pool->szidx;
1603 next = usedpools[size + size];
1604 prev = next->prevpool;
1605 /* insert pool before next: prev <-> pool <-> next */
1606 pool->nextpool = next;
1607 pool->prevpool = prev;
1608 next->prevpool = pool;
1609 prev->nextpool = pool;
1610 UNLOCK();
1611 return;
1612 }
Neil Schemenauera35c6882001-02-27 04:45:05 +00001613
Benjamin Peterson05159c42009-12-03 03:01:27 +00001614#ifdef WITH_VALGRIND
1615redirect:
1616#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001617 /* We didn't allocate this address. */
Victor Stinner6cf185d2013-10-10 15:58:42 +02001618 PyMem_RawFree(p);
Neil Schemenauera35c6882001-02-27 04:45:05 +00001619}
1620
Tim Peters84c1b972002-04-04 04:44:32 +00001621/* realloc. If p is NULL, this acts like malloc(nbytes). Else if nbytes==0,
1622 * then as the Python docs promise, we do not treat this like free(p), and
1623 * return a non-NULL result.
1624 */
Neil Schemenauera35c6882001-02-27 04:45:05 +00001625
Nick Coghlan6ba64f42013-09-29 00:28:55 +10001626ATTRIBUTE_NO_ADDRESS_SAFETY_ANALYSIS
Victor Stinner0507bf52013-07-07 02:05:46 +02001627static void *
1628_PyObject_Realloc(void *ctx, void *p, size_t nbytes)
Neil Schemenauera35c6882001-02-27 04:45:05 +00001629{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001630 void *bp;
1631 poolp pool;
1632 size_t size;
Antoine Pitroub7fb2e22011-01-07 21:43:59 +00001633#ifndef Py_USING_MEMORY_DEBUGGER
1634 uint arenaindex_temp;
1635#endif
Neil Schemenauera35c6882001-02-27 04:45:05 +00001636
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001637 if (p == NULL)
Victor Stinnerdb067af2014-05-02 22:31:14 +02001638 return _PyObject_Alloc(0, ctx, 1, nbytes);
Georg Brandld492ad82008-07-23 16:13:07 +00001639
Benjamin Peterson05159c42009-12-03 03:01:27 +00001640#ifdef WITH_VALGRIND
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001641 /* Treat running_on_valgrind == -1 the same as 0 */
1642 if (UNLIKELY(running_on_valgrind > 0))
1643 goto redirect;
Benjamin Peterson05159c42009-12-03 03:01:27 +00001644#endif
1645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001646 pool = POOL_ADDR(p);
1647 if (Py_ADDRESS_IN_RANGE(p, pool)) {
1648 /* We're in charge of this block */
1649 size = INDEX2SIZE(pool->szidx);
1650 if (nbytes <= size) {
1651 /* The block is staying the same or shrinking. If
1652 * it's shrinking, there's a tradeoff: it costs
1653 * cycles to copy the block to a smaller size class,
1654 * but it wastes memory not to copy it. The
1655 * compromise here is to copy on shrink only if at
1656 * least 25% of size can be shaved off.
1657 */
1658 if (4 * nbytes > 3 * size) {
1659 /* It's the same,
1660 * or shrinking and new/old > 3/4.
1661 */
1662 return p;
1663 }
1664 size = nbytes;
1665 }
Victor Stinnerdb067af2014-05-02 22:31:14 +02001666 bp = _PyObject_Alloc(0, ctx, 1, nbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001667 if (bp != NULL) {
1668 memcpy(bp, p, size);
Victor Stinner0507bf52013-07-07 02:05:46 +02001669 _PyObject_Free(ctx, p);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001670 }
1671 return bp;
1672 }
Benjamin Peterson05159c42009-12-03 03:01:27 +00001673#ifdef WITH_VALGRIND
1674 redirect:
1675#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001676 /* We're not managing this block. If nbytes <=
1677 * SMALL_REQUEST_THRESHOLD, it's tempting to try to take over this
1678 * block. However, if we do, we need to copy the valid data from
1679 * the C-managed block to one of our blocks, and there's no portable
1680 * way to know how much of the memory space starting at p is valid.
1681 * As bug 1185883 pointed out the hard way, it's possible that the
1682 * C-managed block is "at the end" of allocated VM space, so that
1683 * a memory fault can occur if we try to copy nbytes bytes starting
1684 * at p. Instead we punt: let C continue to manage this block.
1685 */
1686 if (nbytes)
Victor Stinner6cf185d2013-10-10 15:58:42 +02001687 return PyMem_RawRealloc(p, nbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001688 /* C doesn't define the result of realloc(p, 0) (it may or may not
1689 * return NULL then), but Python's docs promise that nbytes==0 never
1690 * returns NULL. We don't pass 0 to realloc(), to avoid that endcase
1691 * to begin with. Even then, we can't be sure that realloc() won't
1692 * return NULL.
1693 */
Victor Stinner6cf185d2013-10-10 15:58:42 +02001694 bp = PyMem_RawRealloc(p, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001695 return bp ? bp : p;
Neil Schemenauera35c6882001-02-27 04:45:05 +00001696}
1697
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001698#else /* ! WITH_PYMALLOC */
Tim Petersddea2082002-03-23 10:03:50 +00001699
1700/*==========================================================================*/
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00001701/* pymalloc not enabled: Redirect the entry points to malloc. These will
1702 * only be used by extensions that are compiled with pymalloc enabled. */
Tim Peters62c06ba2002-03-23 22:28:18 +00001703
Antoine Pitrou92840532012-12-17 23:05:59 +01001704Py_ssize_t
1705_Py_GetAllocatedBlocks(void)
1706{
1707 return 0;
1708}
1709
Tim Peters1221c0a2002-03-23 00:20:15 +00001710#endif /* WITH_PYMALLOC */
1711
Tim Petersddea2082002-03-23 10:03:50 +00001712#ifdef PYMALLOC_DEBUG
1713/*==========================================================================*/
Tim Peters62c06ba2002-03-23 22:28:18 +00001714/* A x-platform debugging allocator. This doesn't manage memory directly,
1715 * it wraps a real allocator, adding extra debugging info to the memory blocks.
1716 */
Tim Petersddea2082002-03-23 10:03:50 +00001717
Tim Petersf6fb5012002-04-12 07:38:53 +00001718/* Special bytes broadcast into debug memory blocks at appropriate times.
1719 * Strings of these are unlikely to be valid addresses, floats, ints or
1720 * 7-bit ASCII.
1721 */
1722#undef CLEANBYTE
1723#undef DEADBYTE
1724#undef FORBIDDENBYTE
1725#define CLEANBYTE 0xCB /* clean (newly allocated) memory */
Tim Peters889f61d2002-07-10 19:29:49 +00001726#define DEADBYTE 0xDB /* dead (newly freed) memory */
Tim Petersf6fb5012002-04-12 07:38:53 +00001727#define FORBIDDENBYTE 0xFB /* untouchable bytes at each end of a block */
Tim Petersddea2082002-03-23 10:03:50 +00001728
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001729static size_t serialno = 0; /* incremented on each debug {m,re}alloc */
Tim Petersddea2082002-03-23 10:03:50 +00001730
Tim Peterse0850172002-03-24 00:34:21 +00001731/* serialno is always incremented via calling this routine. The point is
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001732 * to supply a single place to set a breakpoint.
1733 */
Tim Peterse0850172002-03-24 00:34:21 +00001734static void
Neil Schemenauerbd02b142002-03-28 21:05:38 +00001735bumpserialno(void)
Tim Peterse0850172002-03-24 00:34:21 +00001736{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001737 ++serialno;
Tim Peterse0850172002-03-24 00:34:21 +00001738}
1739
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001740#define SST SIZEOF_SIZE_T
Tim Peterse0850172002-03-24 00:34:21 +00001741
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001742/* Read sizeof(size_t) bytes at p as a big-endian size_t. */
1743static size_t
1744read_size_t(const void *p)
Tim Petersddea2082002-03-23 10:03:50 +00001745{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001746 const uchar *q = (const uchar *)p;
1747 size_t result = *q++;
1748 int i;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001749
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001750 for (i = SST; --i > 0; ++q)
1751 result = (result << 8) | *q;
1752 return result;
Tim Petersddea2082002-03-23 10:03:50 +00001753}
1754
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001755/* Write n as a big-endian size_t, MSB at address p, LSB at
1756 * p + sizeof(size_t) - 1.
1757 */
Tim Petersddea2082002-03-23 10:03:50 +00001758static void
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001759write_size_t(void *p, size_t n)
Tim Petersddea2082002-03-23 10:03:50 +00001760{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001761 uchar *q = (uchar *)p + SST - 1;
1762 int i;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001763
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001764 for (i = SST; --i >= 0; --q) {
1765 *q = (uchar)(n & 0xff);
1766 n >>= 8;
1767 }
Tim Petersddea2082002-03-23 10:03:50 +00001768}
1769
Tim Peters08d82152002-04-18 22:25:03 +00001770#ifdef Py_DEBUG
1771/* Is target in the list? The list is traversed via the nextpool pointers.
1772 * The list may be NULL-terminated, or circular. Return 1 if target is in
1773 * list, else 0.
1774 */
1775static int
1776pool_is_in_list(const poolp target, poolp list)
1777{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001778 poolp origlist = list;
1779 assert(target != NULL);
1780 if (list == NULL)
1781 return 0;
1782 do {
1783 if (target == list)
1784 return 1;
1785 list = list->nextpool;
1786 } while (list != NULL && list != origlist);
1787 return 0;
Tim Peters08d82152002-04-18 22:25:03 +00001788}
1789
1790#else
1791#define pool_is_in_list(X, Y) 1
1792
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001793#endif /* Py_DEBUG */
Tim Peters08d82152002-04-18 22:25:03 +00001794
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001795/* Let S = sizeof(size_t). The debug malloc asks for 4*S extra bytes and
1796 fills them with useful stuff, here calling the underlying malloc's result p:
Tim Petersddea2082002-03-23 10:03:50 +00001797
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001798p[0: S]
1799 Number of bytes originally asked for. This is a size_t, big-endian (easier
1800 to read in a memory dump).
Georg Brandl7cba5fd2013-09-25 09:04:23 +02001801p[S]
Tim Petersdf099f52013-09-19 21:06:37 -05001802 API ID. See PEP 445. This is a character, but seems undocumented.
1803p[S+1: 2*S]
Tim Petersf6fb5012002-04-12 07:38:53 +00001804 Copies of FORBIDDENBYTE. Used to catch under- writes and reads.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001805p[2*S: 2*S+n]
Tim Petersf6fb5012002-04-12 07:38:53 +00001806 The requested memory, filled with copies of CLEANBYTE.
Tim Petersddea2082002-03-23 10:03:50 +00001807 Used to catch reference to uninitialized memory.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001808 &p[2*S] is returned. Note that this is 8-byte aligned if pymalloc
Tim Petersddea2082002-03-23 10:03:50 +00001809 handled the request itself.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001810p[2*S+n: 2*S+n+S]
Tim Petersf6fb5012002-04-12 07:38:53 +00001811 Copies of FORBIDDENBYTE. Used to catch over- writes and reads.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001812p[2*S+n+S: 2*S+n+2*S]
Victor Stinner0507bf52013-07-07 02:05:46 +02001813 A serial number, incremented by 1 on each call to _PyMem_DebugMalloc
1814 and _PyMem_DebugRealloc.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001815 This is a big-endian size_t.
Tim Petersddea2082002-03-23 10:03:50 +00001816 If "bad memory" is detected later, the serial number gives an
1817 excellent way to set a breakpoint on the next run, to capture the
1818 instant at which this block was passed out.
1819*/
1820
Victor Stinner0507bf52013-07-07 02:05:46 +02001821static void *
Victor Stinnerdb067af2014-05-02 22:31:14 +02001822_PyMem_DebugAlloc(int use_calloc, void *ctx, size_t nbytes)
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00001823{
Victor Stinner0507bf52013-07-07 02:05:46 +02001824 debug_alloc_api_t *api = (debug_alloc_api_t *)ctx;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001825 uchar *p; /* base address of malloc'ed block */
1826 uchar *tail; /* p + 2*SST + nbytes == pointer to tail pad bytes */
1827 size_t total; /* nbytes + 4*SST */
Tim Petersddea2082002-03-23 10:03:50 +00001828
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001829 bumpserialno();
1830 total = nbytes + 4*SST;
Antoine Pitroucc231542014-11-02 18:40:09 +01001831 if (nbytes > PY_SSIZE_T_MAX - 4*SST)
1832 /* overflow: can't represent total as a Py_ssize_t */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001833 return NULL;
Tim Petersddea2082002-03-23 10:03:50 +00001834
Victor Stinnerdb067af2014-05-02 22:31:14 +02001835 if (use_calloc)
1836 p = (uchar *)api->alloc.calloc(api->alloc.ctx, 1, total);
1837 else
1838 p = (uchar *)api->alloc.malloc(api->alloc.ctx, total);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001839 if (p == NULL)
1840 return NULL;
Tim Petersddea2082002-03-23 10:03:50 +00001841
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001842 /* at p, write size (SST bytes), id (1 byte), pad (SST-1 bytes) */
1843 write_size_t(p, nbytes);
Victor Stinner0507bf52013-07-07 02:05:46 +02001844 p[SST] = (uchar)api->api_id;
1845 memset(p + SST + 1, FORBIDDENBYTE, SST-1);
Tim Petersddea2082002-03-23 10:03:50 +00001846
Victor Stinnerdb067af2014-05-02 22:31:14 +02001847 if (nbytes > 0 && !use_calloc)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001848 memset(p + 2*SST, CLEANBYTE, nbytes);
Tim Petersddea2082002-03-23 10:03:50 +00001849
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001850 /* at tail, write pad (SST bytes) and serialno (SST bytes) */
1851 tail = p + 2*SST + nbytes;
1852 memset(tail, FORBIDDENBYTE, SST);
1853 write_size_t(tail + SST, serialno);
Tim Petersddea2082002-03-23 10:03:50 +00001854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001855 return p + 2*SST;
Tim Petersddea2082002-03-23 10:03:50 +00001856}
1857
Victor Stinnerdb067af2014-05-02 22:31:14 +02001858static void *
1859_PyMem_DebugMalloc(void *ctx, size_t nbytes)
1860{
1861 return _PyMem_DebugAlloc(0, ctx, nbytes);
1862}
1863
1864static void *
1865_PyMem_DebugCalloc(void *ctx, size_t nelem, size_t elsize)
1866{
1867 size_t nbytes;
1868 assert(elsize == 0 || nelem <= PY_SSIZE_T_MAX / elsize);
1869 nbytes = nelem * elsize;
1870 return _PyMem_DebugAlloc(1, ctx, nbytes);
1871}
1872
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001873/* 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 +00001874 particular, that the FORBIDDENBYTEs with the api ID are still intact).
Tim Petersf6fb5012002-04-12 07:38:53 +00001875 Then fills the original bytes with DEADBYTE.
Tim Petersddea2082002-03-23 10:03:50 +00001876 Then calls the underlying free.
1877*/
Victor Stinner0507bf52013-07-07 02:05:46 +02001878static void
1879_PyMem_DebugFree(void *ctx, void *p)
Tim Petersddea2082002-03-23 10:03:50 +00001880{
Victor Stinner0507bf52013-07-07 02:05:46 +02001881 debug_alloc_api_t *api = (debug_alloc_api_t *)ctx;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001882 uchar *q = (uchar *)p - 2*SST; /* address returned from malloc */
1883 size_t nbytes;
Tim Petersddea2082002-03-23 10:03:50 +00001884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001885 if (p == NULL)
1886 return;
Victor Stinner0507bf52013-07-07 02:05:46 +02001887 _PyMem_DebugCheckAddress(api->api_id, p);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001888 nbytes = read_size_t(q);
1889 nbytes += 4*SST;
1890 if (nbytes > 0)
1891 memset(q, DEADBYTE, nbytes);
Victor Stinner0507bf52013-07-07 02:05:46 +02001892 api->alloc.free(api->alloc.ctx, q);
Tim Petersddea2082002-03-23 10:03:50 +00001893}
1894
Victor Stinner0507bf52013-07-07 02:05:46 +02001895static void *
1896_PyMem_DebugRealloc(void *ctx, void *p, size_t nbytes)
Tim Petersddea2082002-03-23 10:03:50 +00001897{
Victor Stinner0507bf52013-07-07 02:05:46 +02001898 debug_alloc_api_t *api = (debug_alloc_api_t *)ctx;
Victor Stinnerc4266362013-07-09 00:44:43 +02001899 uchar *q = (uchar *)p, *oldq;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001900 uchar *tail;
1901 size_t total; /* nbytes + 4*SST */
1902 size_t original_nbytes;
1903 int i;
Tim Petersddea2082002-03-23 10:03:50 +00001904
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001905 if (p == NULL)
Victor Stinnerdb067af2014-05-02 22:31:14 +02001906 return _PyMem_DebugAlloc(0, ctx, nbytes);
Tim Petersddea2082002-03-23 10:03:50 +00001907
Victor Stinner0507bf52013-07-07 02:05:46 +02001908 _PyMem_DebugCheckAddress(api->api_id, p);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001909 bumpserialno();
1910 original_nbytes = read_size_t(q - 2*SST);
1911 total = nbytes + 4*SST;
Antoine Pitroucc231542014-11-02 18:40:09 +01001912 if (nbytes > PY_SSIZE_T_MAX - 4*SST)
1913 /* overflow: can't represent total as a Py_ssize_t */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001914 return NULL;
Tim Petersddea2082002-03-23 10:03:50 +00001915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001916 /* Resize and add decorations. We may get a new pointer here, in which
1917 * case we didn't get the chance to mark the old memory with DEADBYTE,
1918 * but we live with that.
1919 */
Victor Stinnerc4266362013-07-09 00:44:43 +02001920 oldq = q;
Victor Stinner0507bf52013-07-07 02:05:46 +02001921 q = (uchar *)api->alloc.realloc(api->alloc.ctx, q - 2*SST, total);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001922 if (q == NULL)
1923 return NULL;
Tim Peters85cc1c42002-04-12 08:52:50 +00001924
Victor Stinnerc4266362013-07-09 00:44:43 +02001925 if (q == oldq && nbytes < original_nbytes) {
1926 /* shrinking: mark old extra memory dead */
1927 memset(q + nbytes, DEADBYTE, original_nbytes - nbytes);
1928 }
1929
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001930 write_size_t(q, nbytes);
Victor Stinner0507bf52013-07-07 02:05:46 +02001931 assert(q[SST] == (uchar)api->api_id);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001932 for (i = 1; i < SST; ++i)
1933 assert(q[SST + i] == FORBIDDENBYTE);
1934 q += 2*SST;
Victor Stinnerc4266362013-07-09 00:44:43 +02001935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001936 tail = q + nbytes;
1937 memset(tail, FORBIDDENBYTE, SST);
1938 write_size_t(tail + SST, serialno);
Tim Peters85cc1c42002-04-12 08:52:50 +00001939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001940 if (nbytes > original_nbytes) {
1941 /* growing: mark new extra memory clean */
1942 memset(q + original_nbytes, CLEANBYTE,
Stefan Krah735bb122010-11-26 10:54:09 +00001943 nbytes - original_nbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001944 }
Tim Peters85cc1c42002-04-12 08:52:50 +00001945
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001946 return q;
Tim Petersddea2082002-03-23 10:03:50 +00001947}
1948
Tim Peters7ccfadf2002-04-01 06:04:21 +00001949/* Check the forbidden bytes on both ends of the memory allocated for p.
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00001950 * If anything is wrong, print info to stderr via _PyObject_DebugDumpAddress,
Tim Peters7ccfadf2002-04-01 06:04:21 +00001951 * and call Py_FatalError to kill the program.
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00001952 * The API id, is also checked.
Tim Peters7ccfadf2002-04-01 06:04:21 +00001953 */
Victor Stinner0507bf52013-07-07 02:05:46 +02001954static void
1955_PyMem_DebugCheckAddress(char api, const void *p)
Tim Petersddea2082002-03-23 10:03:50 +00001956{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001957 const uchar *q = (const uchar *)p;
1958 char msgbuf[64];
1959 char *msg;
1960 size_t nbytes;
1961 const uchar *tail;
1962 int i;
1963 char id;
Tim Petersddea2082002-03-23 10:03:50 +00001964
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001965 if (p == NULL) {
1966 msg = "didn't expect a NULL pointer";
1967 goto error;
1968 }
Tim Petersddea2082002-03-23 10:03:50 +00001969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001970 /* Check the API id */
1971 id = (char)q[-SST];
1972 if (id != api) {
1973 msg = msgbuf;
1974 snprintf(msg, sizeof(msgbuf), "bad ID: Allocated using API '%c', verified using API '%c'", id, api);
1975 msgbuf[sizeof(msgbuf)-1] = 0;
1976 goto error;
1977 }
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00001978
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001979 /* Check the stuff at the start of p first: if there's underwrite
1980 * corruption, the number-of-bytes field may be nuts, and checking
1981 * the tail could lead to a segfault then.
1982 */
1983 for (i = SST-1; i >= 1; --i) {
1984 if (*(q-i) != FORBIDDENBYTE) {
1985 msg = "bad leading pad byte";
1986 goto error;
1987 }
1988 }
Tim Petersddea2082002-03-23 10:03:50 +00001989
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001990 nbytes = read_size_t(q - 2*SST);
1991 tail = q + nbytes;
1992 for (i = 0; i < SST; ++i) {
1993 if (tail[i] != FORBIDDENBYTE) {
1994 msg = "bad trailing pad byte";
1995 goto error;
1996 }
1997 }
Tim Petersddea2082002-03-23 10:03:50 +00001998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001999 return;
Tim Petersd1139e02002-03-28 07:32:11 +00002000
2001error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002002 _PyObject_DebugDumpAddress(p);
2003 Py_FatalError(msg);
Tim Petersddea2082002-03-23 10:03:50 +00002004}
2005
Tim Peters7ccfadf2002-04-01 06:04:21 +00002006/* Display info to stderr about the memory block at p. */
Victor Stinner0507bf52013-07-07 02:05:46 +02002007static void
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00002008_PyObject_DebugDumpAddress(const void *p)
Tim Petersddea2082002-03-23 10:03:50 +00002009{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002010 const uchar *q = (const uchar *)p;
2011 const uchar *tail;
2012 size_t nbytes, serial;
2013 int i;
2014 int ok;
2015 char id;
Tim Petersddea2082002-03-23 10:03:50 +00002016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002017 fprintf(stderr, "Debug memory block at address p=%p:", p);
2018 if (p == NULL) {
2019 fprintf(stderr, "\n");
2020 return;
2021 }
2022 id = (char)q[-SST];
2023 fprintf(stderr, " API '%c'\n", id);
Tim Petersddea2082002-03-23 10:03:50 +00002024
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002025 nbytes = read_size_t(q - 2*SST);
2026 fprintf(stderr, " %" PY_FORMAT_SIZE_T "u bytes originally "
2027 "requested\n", nbytes);
Tim Petersddea2082002-03-23 10:03:50 +00002028
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002029 /* In case this is nuts, check the leading pad bytes first. */
2030 fprintf(stderr, " The %d pad bytes at p-%d are ", SST-1, SST-1);
2031 ok = 1;
2032 for (i = 1; i <= SST-1; ++i) {
2033 if (*(q-i) != FORBIDDENBYTE) {
2034 ok = 0;
2035 break;
2036 }
2037 }
2038 if (ok)
2039 fputs("FORBIDDENBYTE, as expected.\n", stderr);
2040 else {
2041 fprintf(stderr, "not all FORBIDDENBYTE (0x%02x):\n",
2042 FORBIDDENBYTE);
2043 for (i = SST-1; i >= 1; --i) {
2044 const uchar byte = *(q-i);
2045 fprintf(stderr, " at p-%d: 0x%02x", i, byte);
2046 if (byte != FORBIDDENBYTE)
2047 fputs(" *** OUCH", stderr);
2048 fputc('\n', stderr);
2049 }
Tim Peters449b5a82002-04-28 06:14:45 +00002050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002051 fputs(" Because memory is corrupted at the start, the "
2052 "count of bytes requested\n"
2053 " may be bogus, and checking the trailing pad "
2054 "bytes may segfault.\n", stderr);
2055 }
Tim Petersddea2082002-03-23 10:03:50 +00002056
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002057 tail = q + nbytes;
2058 fprintf(stderr, " The %d pad bytes at tail=%p are ", SST, tail);
2059 ok = 1;
2060 for (i = 0; i < SST; ++i) {
2061 if (tail[i] != FORBIDDENBYTE) {
2062 ok = 0;
2063 break;
2064 }
2065 }
2066 if (ok)
2067 fputs("FORBIDDENBYTE, as expected.\n", stderr);
2068 else {
2069 fprintf(stderr, "not all FORBIDDENBYTE (0x%02x):\n",
Stefan Krah735bb122010-11-26 10:54:09 +00002070 FORBIDDENBYTE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002071 for (i = 0; i < SST; ++i) {
2072 const uchar byte = tail[i];
2073 fprintf(stderr, " at tail+%d: 0x%02x",
Stefan Krah735bb122010-11-26 10:54:09 +00002074 i, byte);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002075 if (byte != FORBIDDENBYTE)
2076 fputs(" *** OUCH", stderr);
2077 fputc('\n', stderr);
2078 }
2079 }
Tim Petersddea2082002-03-23 10:03:50 +00002080
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002081 serial = read_size_t(tail + SST);
2082 fprintf(stderr, " The block was made by call #%" PY_FORMAT_SIZE_T
2083 "u to debug malloc/realloc.\n", serial);
Tim Petersddea2082002-03-23 10:03:50 +00002084
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002085 if (nbytes > 0) {
2086 i = 0;
2087 fputs(" Data at p:", stderr);
2088 /* print up to 8 bytes at the start */
2089 while (q < tail && i < 8) {
2090 fprintf(stderr, " %02x", *q);
2091 ++i;
2092 ++q;
2093 }
2094 /* and up to 8 at the end */
2095 if (q < tail) {
2096 if (tail - q > 8) {
2097 fputs(" ...", stderr);
2098 q = tail - 8;
2099 }
2100 while (q < tail) {
2101 fprintf(stderr, " %02x", *q);
2102 ++q;
2103 }
2104 }
2105 fputc('\n', stderr);
2106 }
Tim Petersddea2082002-03-23 10:03:50 +00002107}
2108
David Malcolm49526f42012-06-22 14:55:41 -04002109#endif /* PYMALLOC_DEBUG */
2110
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00002111static size_t
David Malcolm49526f42012-06-22 14:55:41 -04002112printone(FILE *out, const char* msg, size_t value)
Tim Peters16bcb6b2002-04-05 05:45:31 +00002113{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002114 int i, k;
2115 char buf[100];
2116 size_t origvalue = value;
Tim Peters16bcb6b2002-04-05 05:45:31 +00002117
David Malcolm49526f42012-06-22 14:55:41 -04002118 fputs(msg, out);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002119 for (i = (int)strlen(msg); i < 35; ++i)
David Malcolm49526f42012-06-22 14:55:41 -04002120 fputc(' ', out);
2121 fputc('=', out);
Tim Peters49f26812002-04-06 01:45:35 +00002122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002123 /* Write the value with commas. */
2124 i = 22;
2125 buf[i--] = '\0';
2126 buf[i--] = '\n';
2127 k = 3;
2128 do {
2129 size_t nextvalue = value / 10;
Benjamin Peterson2dba1ee2013-02-20 16:54:30 -05002130 unsigned int digit = (unsigned int)(value - nextvalue * 10);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002131 value = nextvalue;
2132 buf[i--] = (char)(digit + '0');
2133 --k;
2134 if (k == 0 && value && i >= 0) {
2135 k = 3;
2136 buf[i--] = ',';
2137 }
2138 } while (value && i >= 0);
Tim Peters49f26812002-04-06 01:45:35 +00002139
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002140 while (i >= 0)
2141 buf[i--] = ' ';
David Malcolm49526f42012-06-22 14:55:41 -04002142 fputs(buf, out);
Tim Peters49f26812002-04-06 01:45:35 +00002143
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002144 return origvalue;
Tim Peters16bcb6b2002-04-05 05:45:31 +00002145}
2146
David Malcolm49526f42012-06-22 14:55:41 -04002147void
2148_PyDebugAllocatorStats(FILE *out,
2149 const char *block_name, int num_blocks, size_t sizeof_block)
2150{
2151 char buf1[128];
2152 char buf2[128];
2153 PyOS_snprintf(buf1, sizeof(buf1),
Tim Peterseaa3bcc2013-09-05 22:57:04 -05002154 "%d %ss * %" PY_FORMAT_SIZE_T "d bytes each",
David Malcolm49526f42012-06-22 14:55:41 -04002155 num_blocks, block_name, sizeof_block);
2156 PyOS_snprintf(buf2, sizeof(buf2),
2157 "%48s ", buf1);
2158 (void)printone(out, buf2, num_blocks * sizeof_block);
2159}
2160
2161#ifdef WITH_PYMALLOC
2162
2163/* Print summary info to "out" about the state of pymalloc's structures.
Tim Peters08d82152002-04-18 22:25:03 +00002164 * In Py_DEBUG mode, also perform some expensive internal consistency
2165 * checks.
2166 */
Tim Peters7ccfadf2002-04-01 06:04:21 +00002167void
David Malcolm49526f42012-06-22 14:55:41 -04002168_PyObject_DebugMallocStats(FILE *out)
Tim Peters7ccfadf2002-04-01 06:04:21 +00002169{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002170 uint i;
2171 const uint numclasses = SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT;
2172 /* # of pools, allocated blocks, and free blocks per class index */
2173 size_t numpools[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT];
2174 size_t numblocks[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT];
2175 size_t numfreeblocks[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT];
2176 /* total # of allocated bytes in used and full pools */
2177 size_t allocated_bytes = 0;
2178 /* total # of available bytes in used pools */
2179 size_t available_bytes = 0;
2180 /* # of free pools + pools not yet carved out of current arena */
2181 uint numfreepools = 0;
2182 /* # of bytes for arena alignment padding */
2183 size_t arena_alignment = 0;
2184 /* # of bytes in used and full pools used for pool_headers */
2185 size_t pool_header_bytes = 0;
2186 /* # of bytes in used and full pools wasted due to quantization,
2187 * i.e. the necessarily leftover space at the ends of used and
2188 * full pools.
2189 */
2190 size_t quantization = 0;
2191 /* # of arenas actually allocated. */
2192 size_t narenas = 0;
2193 /* running total -- should equal narenas * ARENA_SIZE */
2194 size_t total;
2195 char buf[128];
Tim Peters7ccfadf2002-04-01 06:04:21 +00002196
David Malcolm49526f42012-06-22 14:55:41 -04002197 fprintf(out, "Small block threshold = %d, in %u size classes.\n",
Stefan Krah735bb122010-11-26 10:54:09 +00002198 SMALL_REQUEST_THRESHOLD, numclasses);
Tim Peters7ccfadf2002-04-01 06:04:21 +00002199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002200 for (i = 0; i < numclasses; ++i)
2201 numpools[i] = numblocks[i] = numfreeblocks[i] = 0;
Tim Peters7ccfadf2002-04-01 06:04:21 +00002202
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002203 /* Because full pools aren't linked to from anything, it's easiest
2204 * to march over all the arenas. If we're lucky, most of the memory
2205 * will be living in full pools -- would be a shame to miss them.
2206 */
2207 for (i = 0; i < maxarenas; ++i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002208 uint j;
2209 uptr base = arenas[i].address;
Thomas Woutersa9773292006-04-21 09:43:23 +00002210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002211 /* Skip arenas which are not allocated. */
2212 if (arenas[i].address == (uptr)NULL)
2213 continue;
2214 narenas += 1;
Thomas Woutersa9773292006-04-21 09:43:23 +00002215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002216 numfreepools += arenas[i].nfreepools;
Tim Peters7ccfadf2002-04-01 06:04:21 +00002217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002218 /* round up to pool alignment */
2219 if (base & (uptr)POOL_SIZE_MASK) {
2220 arena_alignment += POOL_SIZE;
2221 base &= ~(uptr)POOL_SIZE_MASK;
2222 base += POOL_SIZE;
2223 }
Tim Peters7ccfadf2002-04-01 06:04:21 +00002224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002225 /* visit every pool in the arena */
2226 assert(base <= (uptr) arenas[i].pool_address);
2227 for (j = 0;
2228 base < (uptr) arenas[i].pool_address;
2229 ++j, base += POOL_SIZE) {
2230 poolp p = (poolp)base;
2231 const uint sz = p->szidx;
2232 uint freeblocks;
Tim Peters08d82152002-04-18 22:25:03 +00002233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002234 if (p->ref.count == 0) {
2235 /* currently unused */
2236 assert(pool_is_in_list(p, arenas[i].freepools));
2237 continue;
2238 }
2239 ++numpools[sz];
2240 numblocks[sz] += p->ref.count;
2241 freeblocks = NUMBLOCKS(sz) - p->ref.count;
2242 numfreeblocks[sz] += freeblocks;
Tim Peters08d82152002-04-18 22:25:03 +00002243#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002244 if (freeblocks > 0)
2245 assert(pool_is_in_list(p, usedpools[sz + sz]));
Tim Peters08d82152002-04-18 22:25:03 +00002246#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002247 }
2248 }
2249 assert(narenas == narenas_currently_allocated);
Tim Peters7ccfadf2002-04-01 06:04:21 +00002250
David Malcolm49526f42012-06-22 14:55:41 -04002251 fputc('\n', out);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002252 fputs("class size num pools blocks in use avail blocks\n"
2253 "----- ---- --------- ------------- ------------\n",
David Malcolm49526f42012-06-22 14:55:41 -04002254 out);
Tim Peters7ccfadf2002-04-01 06:04:21 +00002255
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002256 for (i = 0; i < numclasses; ++i) {
2257 size_t p = numpools[i];
2258 size_t b = numblocks[i];
2259 size_t f = numfreeblocks[i];
2260 uint size = INDEX2SIZE(i);
2261 if (p == 0) {
2262 assert(b == 0 && f == 0);
2263 continue;
2264 }
David Malcolm49526f42012-06-22 14:55:41 -04002265 fprintf(out, "%5u %6u "
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002266 "%11" PY_FORMAT_SIZE_T "u "
2267 "%15" PY_FORMAT_SIZE_T "u "
2268 "%13" PY_FORMAT_SIZE_T "u\n",
Stefan Krah735bb122010-11-26 10:54:09 +00002269 i, size, p, b, f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002270 allocated_bytes += b * size;
2271 available_bytes += f * size;
2272 pool_header_bytes += p * POOL_OVERHEAD;
2273 quantization += p * ((POOL_SIZE - POOL_OVERHEAD) % size);
2274 }
David Malcolm49526f42012-06-22 14:55:41 -04002275 fputc('\n', out);
2276#ifdef PYMALLOC_DEBUG
2277 (void)printone(out, "# times object malloc called", serialno);
2278#endif
2279 (void)printone(out, "# arenas allocated total", ntimes_arena_allocated);
2280 (void)printone(out, "# arenas reclaimed", ntimes_arena_allocated - narenas);
2281 (void)printone(out, "# arenas highwater mark", narenas_highwater);
2282 (void)printone(out, "# arenas allocated current", narenas);
Thomas Woutersa9773292006-04-21 09:43:23 +00002283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002284 PyOS_snprintf(buf, sizeof(buf),
2285 "%" PY_FORMAT_SIZE_T "u arenas * %d bytes/arena",
2286 narenas, ARENA_SIZE);
David Malcolm49526f42012-06-22 14:55:41 -04002287 (void)printone(out, buf, narenas * ARENA_SIZE);
Tim Peters16bcb6b2002-04-05 05:45:31 +00002288
David Malcolm49526f42012-06-22 14:55:41 -04002289 fputc('\n', out);
Tim Peters16bcb6b2002-04-05 05:45:31 +00002290
David Malcolm49526f42012-06-22 14:55:41 -04002291 total = printone(out, "# bytes in allocated blocks", allocated_bytes);
2292 total += printone(out, "# bytes in available blocks", available_bytes);
Tim Peters49f26812002-04-06 01:45:35 +00002293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002294 PyOS_snprintf(buf, sizeof(buf),
2295 "%u unused pools * %d bytes", numfreepools, POOL_SIZE);
David Malcolm49526f42012-06-22 14:55:41 -04002296 total += printone(out, buf, (size_t)numfreepools * POOL_SIZE);
Tim Peters16bcb6b2002-04-05 05:45:31 +00002297
David Malcolm49526f42012-06-22 14:55:41 -04002298 total += printone(out, "# bytes lost to pool headers", pool_header_bytes);
2299 total += printone(out, "# bytes lost to quantization", quantization);
2300 total += printone(out, "# bytes lost to arena alignment", arena_alignment);
2301 (void)printone(out, "Total", total);
Tim Peters7ccfadf2002-04-01 06:04:21 +00002302}
2303
David Malcolm49526f42012-06-22 14:55:41 -04002304#endif /* #ifdef WITH_PYMALLOC */
Neal Norwitz7eb3c912004-06-06 19:20:22 +00002305
2306#ifdef Py_USING_MEMORY_DEBUGGER
Thomas Woutersa9773292006-04-21 09:43:23 +00002307/* Make this function last so gcc won't inline it since the definition is
2308 * after the reference.
2309 */
Neal Norwitz7eb3c912004-06-06 19:20:22 +00002310int
2311Py_ADDRESS_IN_RANGE(void *P, poolp pool)
2312{
Antoine Pitroub7fb2e22011-01-07 21:43:59 +00002313 uint arenaindex_temp = pool->arenaindex;
2314
2315 return arenaindex_temp < maxarenas &&
2316 (uptr)P - arenas[arenaindex_temp].address < (uptr)ARENA_SIZE &&
2317 arenas[arenaindex_temp].address != 0;
Neal Norwitz7eb3c912004-06-06 19:20:22 +00002318}
2319#endif