blob: 40c9fcdec9361324a17251e532a86b69d824393f [file] [log] [blame]
Tim Peters1221c0a2002-03-23 00:20:15 +00001#include "Python.h"
2
Victor Stinner0611c262016-03-15 22:22:13 +01003
4/* Defined in tracemalloc.c */
5extern void _PyMem_DumpTraceback(int fd, const void *ptr);
6
7
Victor Stinner0507bf52013-07-07 02:05:46 +02008/* Python's malloc wrappers (see pymem.h) */
9
Victor Stinner34be8072016-03-14 12:04:26 +010010/*
11 * Basic types
12 * I don't care if these are defined in <sys/types.h> or elsewhere. Axiom.
13 */
14#undef uchar
15#define uchar unsigned char /* assuming == 8 bits */
16
17#undef uint
18#define uint unsigned int /* assuming >= 16 bits */
19
20#undef uptr
21#define uptr Py_uintptr_t
22
Victor Stinner0507bf52013-07-07 02:05:46 +020023/* Forward declaration */
Victor Stinnerc4aec362016-03-14 22:26:53 +010024static void* _PyMem_DebugRawMalloc(void *ctx, size_t size);
25static void* _PyMem_DebugRawCalloc(void *ctx, size_t nelem, size_t elsize);
26static void* _PyMem_DebugRawRealloc(void *ctx, void *ptr, size_t size);
27static void _PyMem_DebugRawFree(void *ctx, void *p);
28
Victor Stinner0507bf52013-07-07 02:05:46 +020029static void* _PyMem_DebugMalloc(void *ctx, size_t size);
Victor Stinnerdb067af2014-05-02 22:31:14 +020030static void* _PyMem_DebugCalloc(void *ctx, size_t nelem, size_t elsize);
Victor Stinner0507bf52013-07-07 02:05:46 +020031static void* _PyMem_DebugRealloc(void *ctx, void *ptr, size_t size);
Victor Stinnerc4aec362016-03-14 22:26:53 +010032static void _PyMem_DebugFree(void *ctx, void *p);
Victor Stinner0507bf52013-07-07 02:05:46 +020033
34static void _PyObject_DebugDumpAddress(const void *p);
35static void _PyMem_DebugCheckAddress(char api_id, const void *p);
Victor Stinner0507bf52013-07-07 02:05:46 +020036
Nick Coghlan6ba64f42013-09-29 00:28:55 +100037#if defined(__has_feature) /* Clang */
38 #if __has_feature(address_sanitizer) /* is ASAN enabled? */
39 #define ATTRIBUTE_NO_ADDRESS_SAFETY_ANALYSIS \
40 __attribute__((no_address_safety_analysis)) \
41 __attribute__ ((noinline))
42 #else
43 #define ATTRIBUTE_NO_ADDRESS_SAFETY_ANALYSIS
44 #endif
45#else
46 #if defined(__SANITIZE_ADDRESS__) /* GCC 4.8.x, is ASAN enabled? */
47 #define ATTRIBUTE_NO_ADDRESS_SAFETY_ANALYSIS \
48 __attribute__((no_address_safety_analysis)) \
49 __attribute__ ((noinline))
50 #else
51 #define ATTRIBUTE_NO_ADDRESS_SAFETY_ANALYSIS
52 #endif
53#endif
54
Tim Peters1221c0a2002-03-23 00:20:15 +000055#ifdef WITH_PYMALLOC
56
Victor Stinner0507bf52013-07-07 02:05:46 +020057#ifdef MS_WINDOWS
58# include <windows.h>
59#elif defined(HAVE_MMAP)
60# include <sys/mman.h>
61# ifdef MAP_ANONYMOUS
62# define ARENAS_USE_MMAP
63# endif
Antoine Pitrou6f26be02011-05-03 18:18:59 +020064#endif
65
Victor Stinner0507bf52013-07-07 02:05:46 +020066/* Forward declaration */
67static void* _PyObject_Malloc(void *ctx, size_t size);
Victor Stinnerdb067af2014-05-02 22:31:14 +020068static void* _PyObject_Calloc(void *ctx, size_t nelem, size_t elsize);
Victor Stinner0507bf52013-07-07 02:05:46 +020069static void _PyObject_Free(void *ctx, void *p);
70static void* _PyObject_Realloc(void *ctx, void *ptr, size_t size);
Martin v. Löwiscd83fa82013-06-27 12:23:29 +020071#endif
72
Victor Stinner0507bf52013-07-07 02:05:46 +020073
74static void *
75_PyMem_RawMalloc(void *ctx, size_t size)
76{
Victor Stinnerdb067af2014-05-02 22:31:14 +020077 /* PyMem_RawMalloc(0) means malloc(1). Some systems would return NULL
Victor Stinner0507bf52013-07-07 02:05:46 +020078 for malloc(0), which would be treated as an error. Some platforms would
79 return a pointer with no memory behind it, which would break pymalloc.
80 To solve these problems, allocate an extra byte. */
81 if (size == 0)
82 size = 1;
83 return malloc(size);
84}
85
86static void *
Victor Stinnerdb067af2014-05-02 22:31:14 +020087_PyMem_RawCalloc(void *ctx, size_t nelem, size_t elsize)
88{
89 /* PyMem_RawCalloc(0, 0) means calloc(1, 1). Some systems would return NULL
90 for calloc(0, 0), which would be treated as an error. Some platforms
91 would return a pointer with no memory behind it, which would break
92 pymalloc. To solve these problems, allocate an extra byte. */
93 if (nelem == 0 || elsize == 0) {
94 nelem = 1;
95 elsize = 1;
96 }
97 return calloc(nelem, elsize);
98}
99
100static void *
Victor Stinner0507bf52013-07-07 02:05:46 +0200101_PyMem_RawRealloc(void *ctx, void *ptr, size_t size)
102{
103 if (size == 0)
104 size = 1;
105 return realloc(ptr, size);
106}
107
108static void
109_PyMem_RawFree(void *ctx, void *ptr)
110{
111 free(ptr);
112}
113
114
115#ifdef MS_WINDOWS
116static void *
117_PyObject_ArenaVirtualAlloc(void *ctx, size_t size)
118{
119 return VirtualAlloc(NULL, size,
120 MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
121}
122
123static void
124_PyObject_ArenaVirtualFree(void *ctx, void *ptr, size_t size)
125{
Victor Stinner725e6682013-07-07 03:06:16 +0200126 VirtualFree(ptr, 0, MEM_RELEASE);
Victor Stinner0507bf52013-07-07 02:05:46 +0200127}
128
129#elif defined(ARENAS_USE_MMAP)
130static void *
131_PyObject_ArenaMmap(void *ctx, size_t size)
132{
133 void *ptr;
134 ptr = mmap(NULL, size, PROT_READ|PROT_WRITE,
135 MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
136 if (ptr == MAP_FAILED)
137 return NULL;
138 assert(ptr != NULL);
139 return ptr;
140}
141
142static void
143_PyObject_ArenaMunmap(void *ctx, void *ptr, size_t size)
144{
145 munmap(ptr, size);
146}
147
148#else
149static void *
150_PyObject_ArenaMalloc(void *ctx, size_t size)
151{
152 return malloc(size);
153}
154
155static void
156_PyObject_ArenaFree(void *ctx, void *ptr, size_t size)
157{
158 free(ptr);
159}
160#endif
161
162
Victor Stinnerdb067af2014-05-02 22:31:14 +0200163#define PYRAW_FUNCS _PyMem_RawMalloc, _PyMem_RawCalloc, _PyMem_RawRealloc, _PyMem_RawFree
Victor Stinner0507bf52013-07-07 02:05:46 +0200164#ifdef WITH_PYMALLOC
Victor Stinnerdb067af2014-05-02 22:31:14 +0200165# define PYOBJ_FUNCS _PyObject_Malloc, _PyObject_Calloc, _PyObject_Realloc, _PyObject_Free
Victor Stinner0507bf52013-07-07 02:05:46 +0200166#else
Victor Stinner6cf185d2013-10-10 15:58:42 +0200167# define PYOBJ_FUNCS PYRAW_FUNCS
Victor Stinner0507bf52013-07-07 02:05:46 +0200168#endif
Victor Stinner6cf185d2013-10-10 15:58:42 +0200169#define PYMEM_FUNCS PYRAW_FUNCS
Victor Stinner0507bf52013-07-07 02:05:46 +0200170
Victor Stinner0507bf52013-07-07 02:05:46 +0200171typedef struct {
172 /* We tag each block with an API ID in order to tag API violations */
173 char api_id;
Victor Stinnerd8f0d922014-06-02 21:57:10 +0200174 PyMemAllocatorEx alloc;
Victor Stinner0507bf52013-07-07 02:05:46 +0200175} debug_alloc_api_t;
176static struct {
177 debug_alloc_api_t raw;
178 debug_alloc_api_t mem;
179 debug_alloc_api_t obj;
180} _PyMem_Debug = {
181 {'r', {NULL, PYRAW_FUNCS}},
Victor Stinner6cf185d2013-10-10 15:58:42 +0200182 {'m', {NULL, PYMEM_FUNCS}},
183 {'o', {NULL, PYOBJ_FUNCS}}
Victor Stinner0507bf52013-07-07 02:05:46 +0200184 };
185
Victor Stinnerc4aec362016-03-14 22:26:53 +0100186#define PYRAWDBG_FUNCS \
187 _PyMem_DebugRawMalloc, _PyMem_DebugRawCalloc, _PyMem_DebugRawRealloc, _PyMem_DebugRawFree
188#define PYDBG_FUNCS \
189 _PyMem_DebugMalloc, _PyMem_DebugCalloc, _PyMem_DebugRealloc, _PyMem_DebugFree
Victor Stinner0507bf52013-07-07 02:05:46 +0200190
Victor Stinnerd8f0d922014-06-02 21:57:10 +0200191static PyMemAllocatorEx _PyMem_Raw = {
Victor Stinner34be8072016-03-14 12:04:26 +0100192#ifdef Py_DEBUG
Victor Stinnerc4aec362016-03-14 22:26:53 +0100193 &_PyMem_Debug.raw, PYRAWDBG_FUNCS
Victor Stinner0507bf52013-07-07 02:05:46 +0200194#else
195 NULL, PYRAW_FUNCS
196#endif
197 };
198
Victor Stinnerd8f0d922014-06-02 21:57:10 +0200199static PyMemAllocatorEx _PyMem = {
Victor Stinner34be8072016-03-14 12:04:26 +0100200#ifdef Py_DEBUG
Victor Stinnerad524372016-03-16 12:12:53 +0100201 &_PyMem_Debug.mem, PYDBG_FUNCS
Victor Stinner0507bf52013-07-07 02:05:46 +0200202#else
Victor Stinner6cf185d2013-10-10 15:58:42 +0200203 NULL, PYMEM_FUNCS
Victor Stinner0507bf52013-07-07 02:05:46 +0200204#endif
205 };
206
Victor Stinnerd8f0d922014-06-02 21:57:10 +0200207static PyMemAllocatorEx _PyObject = {
Victor Stinner34be8072016-03-14 12:04:26 +0100208#ifdef Py_DEBUG
Victor Stinner6cf185d2013-10-10 15:58:42 +0200209 &_PyMem_Debug.obj, PYDBG_FUNCS
Victor Stinner0507bf52013-07-07 02:05:46 +0200210#else
Victor Stinner6cf185d2013-10-10 15:58:42 +0200211 NULL, PYOBJ_FUNCS
Victor Stinner0507bf52013-07-07 02:05:46 +0200212#endif
213 };
214
Victor Stinner34be8072016-03-14 12:04:26 +0100215int
216_PyMem_SetupAllocators(const char *opt)
217{
218 if (opt == NULL || *opt == '\0') {
219 /* PYTHONMALLOC is empty or is not set or ignored (-E/-I command line
220 options): use default allocators */
221#ifdef Py_DEBUG
222# ifdef WITH_PYMALLOC
223 opt = "pymalloc_debug";
224# else
225 opt = "malloc_debug";
226# endif
227#else
228 /* !Py_DEBUG */
229# ifdef WITH_PYMALLOC
230 opt = "pymalloc";
231# else
232 opt = "malloc";
233# endif
234#endif
235 }
236
237 if (strcmp(opt, "debug") == 0) {
238 PyMem_SetupDebugHooks();
239 }
240 else if (strcmp(opt, "malloc") == 0 || strcmp(opt, "malloc_debug") == 0)
241 {
242 PyMemAllocatorEx alloc = {NULL, PYRAW_FUNCS};
243
244 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &alloc);
245 PyMem_SetAllocator(PYMEM_DOMAIN_MEM, &alloc);
246 PyMem_SetAllocator(PYMEM_DOMAIN_OBJ, &alloc);
247
248 if (strcmp(opt, "malloc_debug") == 0)
249 PyMem_SetupDebugHooks();
250 }
251#ifdef WITH_PYMALLOC
252 else if (strcmp(opt, "pymalloc") == 0
253 || strcmp(opt, "pymalloc_debug") == 0)
254 {
255 PyMemAllocatorEx mem_alloc = {NULL, PYRAW_FUNCS};
256 PyMemAllocatorEx obj_alloc = {NULL, PYOBJ_FUNCS};
257
258 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &mem_alloc);
259 PyMem_SetAllocator(PYMEM_DOMAIN_MEM, &mem_alloc);
260 PyMem_SetAllocator(PYMEM_DOMAIN_OBJ, &obj_alloc);
261
262 if (strcmp(opt, "pymalloc_debug") == 0)
263 PyMem_SetupDebugHooks();
264 }
265#endif
266 else {
267 /* unknown allocator */
268 return -1;
269 }
270 return 0;
271}
272
Victor Stinner0507bf52013-07-07 02:05:46 +0200273#undef PYRAW_FUNCS
Victor Stinner6cf185d2013-10-10 15:58:42 +0200274#undef PYMEM_FUNCS
275#undef PYOBJ_FUNCS
Victor Stinnerc4aec362016-03-14 22:26:53 +0100276#undef PYRAWDBG_FUNCS
Victor Stinner6cf185d2013-10-10 15:58:42 +0200277#undef PYDBG_FUNCS
Victor Stinner0507bf52013-07-07 02:05:46 +0200278
279static PyObjectArenaAllocator _PyObject_Arena = {NULL,
280#ifdef MS_WINDOWS
281 _PyObject_ArenaVirtualAlloc, _PyObject_ArenaVirtualFree
282#elif defined(ARENAS_USE_MMAP)
283 _PyObject_ArenaMmap, _PyObject_ArenaMunmap
284#else
285 _PyObject_ArenaMalloc, _PyObject_ArenaFree
286#endif
287 };
288
Victor Stinner34be8072016-03-14 12:04:26 +0100289static int
290_PyMem_DebugEnabled(void)
291{
292 return (_PyObject.malloc == _PyMem_DebugMalloc);
293}
294
295#ifdef WITH_PYMALLOC
296int
297_PyMem_PymallocEnabled(void)
298{
299 if (_PyMem_DebugEnabled()) {
300 return (_PyMem_Debug.obj.alloc.malloc == _PyObject_Malloc);
301 }
302 else {
303 return (_PyObject.malloc == _PyObject_Malloc);
304 }
305}
306#endif
307
Victor Stinner0507bf52013-07-07 02:05:46 +0200308void
309PyMem_SetupDebugHooks(void)
310{
Victor Stinnerd8f0d922014-06-02 21:57:10 +0200311 PyMemAllocatorEx alloc;
Victor Stinner0507bf52013-07-07 02:05:46 +0200312
Victor Stinnerc4aec362016-03-14 22:26:53 +0100313 alloc.malloc = _PyMem_DebugRawMalloc;
314 alloc.calloc = _PyMem_DebugRawCalloc;
315 alloc.realloc = _PyMem_DebugRawRealloc;
316 alloc.free = _PyMem_DebugRawFree;
Victor Stinner34be8072016-03-14 12:04:26 +0100317
Victor Stinnerc4aec362016-03-14 22:26:53 +0100318 if (_PyMem_Raw.malloc != _PyMem_DebugRawMalloc) {
Victor Stinner0507bf52013-07-07 02:05:46 +0200319 alloc.ctx = &_PyMem_Debug.raw;
320 PyMem_GetAllocator(PYMEM_DOMAIN_RAW, &_PyMem_Debug.raw.alloc);
321 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &alloc);
322 }
323
Victor Stinnerc4aec362016-03-14 22:26:53 +0100324 alloc.malloc = _PyMem_DebugMalloc;
325 alloc.calloc = _PyMem_DebugCalloc;
326 alloc.realloc = _PyMem_DebugRealloc;
327 alloc.free = _PyMem_DebugFree;
328
Victor Stinnerad524372016-03-16 12:12:53 +0100329 if (_PyMem.malloc != _PyMem_DebugMalloc) {
330 alloc.ctx = &_PyMem_Debug.mem;
331 PyMem_GetAllocator(PYMEM_DOMAIN_MEM, &_PyMem_Debug.mem.alloc);
332 PyMem_SetAllocator(PYMEM_DOMAIN_MEM, &alloc);
333 }
334
Victor Stinner0507bf52013-07-07 02:05:46 +0200335 if (_PyObject.malloc != _PyMem_DebugMalloc) {
336 alloc.ctx = &_PyMem_Debug.obj;
337 PyMem_GetAllocator(PYMEM_DOMAIN_OBJ, &_PyMem_Debug.obj.alloc);
338 PyMem_SetAllocator(PYMEM_DOMAIN_OBJ, &alloc);
339 }
Victor Stinner0507bf52013-07-07 02:05:46 +0200340}
341
342void
Victor Stinnerd8f0d922014-06-02 21:57:10 +0200343PyMem_GetAllocator(PyMemAllocatorDomain domain, PyMemAllocatorEx *allocator)
Victor Stinner0507bf52013-07-07 02:05:46 +0200344{
345 switch(domain)
346 {
347 case PYMEM_DOMAIN_RAW: *allocator = _PyMem_Raw; break;
348 case PYMEM_DOMAIN_MEM: *allocator = _PyMem; break;
349 case PYMEM_DOMAIN_OBJ: *allocator = _PyObject; break;
350 default:
Victor Stinnerdb067af2014-05-02 22:31:14 +0200351 /* unknown domain: set all attributes to NULL */
Victor Stinner0507bf52013-07-07 02:05:46 +0200352 allocator->ctx = NULL;
353 allocator->malloc = NULL;
Victor Stinnerdb067af2014-05-02 22:31:14 +0200354 allocator->calloc = NULL;
Victor Stinner0507bf52013-07-07 02:05:46 +0200355 allocator->realloc = NULL;
356 allocator->free = NULL;
357 }
358}
359
360void
Victor Stinnerd8f0d922014-06-02 21:57:10 +0200361PyMem_SetAllocator(PyMemAllocatorDomain domain, PyMemAllocatorEx *allocator)
Victor Stinner0507bf52013-07-07 02:05:46 +0200362{
363 switch(domain)
364 {
365 case PYMEM_DOMAIN_RAW: _PyMem_Raw = *allocator; break;
366 case PYMEM_DOMAIN_MEM: _PyMem = *allocator; break;
367 case PYMEM_DOMAIN_OBJ: _PyObject = *allocator; break;
368 /* ignore unknown domain */
369 }
Victor Stinner0507bf52013-07-07 02:05:46 +0200370}
371
372void
373PyObject_GetArenaAllocator(PyObjectArenaAllocator *allocator)
374{
375 *allocator = _PyObject_Arena;
376}
377
378void
379PyObject_SetArenaAllocator(PyObjectArenaAllocator *allocator)
380{
381 _PyObject_Arena = *allocator;
382}
383
384void *
385PyMem_RawMalloc(size_t size)
386{
387 /*
388 * Limit ourselves to PY_SSIZE_T_MAX bytes to prevent security holes.
389 * Most python internals blindly use a signed Py_ssize_t to track
390 * things without checking for overflows or negatives.
391 * As size_t is unsigned, checking for size < 0 is not required.
392 */
393 if (size > (size_t)PY_SSIZE_T_MAX)
394 return NULL;
Victor Stinner0507bf52013-07-07 02:05:46 +0200395 return _PyMem_Raw.malloc(_PyMem_Raw.ctx, size);
396}
397
Victor Stinnerdb067af2014-05-02 22:31:14 +0200398void *
399PyMem_RawCalloc(size_t nelem, size_t elsize)
400{
401 /* see PyMem_RawMalloc() */
402 if (elsize != 0 && nelem > (size_t)PY_SSIZE_T_MAX / elsize)
403 return NULL;
404 return _PyMem_Raw.calloc(_PyMem_Raw.ctx, nelem, elsize);
405}
406
Victor Stinner0507bf52013-07-07 02:05:46 +0200407void*
408PyMem_RawRealloc(void *ptr, size_t new_size)
409{
410 /* see PyMem_RawMalloc() */
411 if (new_size > (size_t)PY_SSIZE_T_MAX)
412 return NULL;
413 return _PyMem_Raw.realloc(_PyMem_Raw.ctx, ptr, new_size);
414}
415
416void PyMem_RawFree(void *ptr)
417{
418 _PyMem_Raw.free(_PyMem_Raw.ctx, ptr);
419}
420
421void *
422PyMem_Malloc(size_t size)
423{
424 /* see PyMem_RawMalloc() */
425 if (size > (size_t)PY_SSIZE_T_MAX)
426 return NULL;
427 return _PyMem.malloc(_PyMem.ctx, size);
428}
429
430void *
Victor Stinnerdb067af2014-05-02 22:31:14 +0200431PyMem_Calloc(size_t nelem, size_t elsize)
432{
433 /* see PyMem_RawMalloc() */
434 if (elsize != 0 && nelem > (size_t)PY_SSIZE_T_MAX / elsize)
435 return NULL;
436 return _PyMem.calloc(_PyMem.ctx, nelem, elsize);
437}
438
439void *
Victor Stinner0507bf52013-07-07 02:05:46 +0200440PyMem_Realloc(void *ptr, size_t new_size)
441{
442 /* see PyMem_RawMalloc() */
443 if (new_size > (size_t)PY_SSIZE_T_MAX)
444 return NULL;
445 return _PyMem.realloc(_PyMem.ctx, ptr, new_size);
446}
447
448void
449PyMem_Free(void *ptr)
450{
451 _PyMem.free(_PyMem.ctx, ptr);
452}
453
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200454char *
455_PyMem_RawStrdup(const char *str)
456{
457 size_t size;
458 char *copy;
459
460 size = strlen(str) + 1;
461 copy = PyMem_RawMalloc(size);
462 if (copy == NULL)
463 return NULL;
464 memcpy(copy, str, size);
465 return copy;
466}
467
468char *
469_PyMem_Strdup(const char *str)
470{
471 size_t size;
472 char *copy;
473
474 size = strlen(str) + 1;
475 copy = PyMem_Malloc(size);
476 if (copy == NULL)
477 return NULL;
478 memcpy(copy, str, size);
479 return copy;
480}
481
Victor Stinner0507bf52013-07-07 02:05:46 +0200482void *
483PyObject_Malloc(size_t size)
484{
485 /* see PyMem_RawMalloc() */
486 if (size > (size_t)PY_SSIZE_T_MAX)
487 return NULL;
488 return _PyObject.malloc(_PyObject.ctx, size);
489}
490
491void *
Victor Stinnerdb067af2014-05-02 22:31:14 +0200492PyObject_Calloc(size_t nelem, size_t elsize)
493{
494 /* see PyMem_RawMalloc() */
495 if (elsize != 0 && nelem > (size_t)PY_SSIZE_T_MAX / elsize)
496 return NULL;
497 return _PyObject.calloc(_PyObject.ctx, nelem, elsize);
498}
499
500void *
Victor Stinner0507bf52013-07-07 02:05:46 +0200501PyObject_Realloc(void *ptr, size_t new_size)
502{
503 /* see PyMem_RawMalloc() */
504 if (new_size > (size_t)PY_SSIZE_T_MAX)
505 return NULL;
506 return _PyObject.realloc(_PyObject.ctx, ptr, new_size);
507}
508
509void
510PyObject_Free(void *ptr)
511{
512 _PyObject.free(_PyObject.ctx, ptr);
513}
514
515
516#ifdef WITH_PYMALLOC
517
Benjamin Peterson05159c42009-12-03 03:01:27 +0000518#ifdef WITH_VALGRIND
519#include <valgrind/valgrind.h>
520
521/* If we're using GCC, use __builtin_expect() to reduce overhead of
522 the valgrind checks */
523#if defined(__GNUC__) && (__GNUC__ > 2) && defined(__OPTIMIZE__)
524# define UNLIKELY(value) __builtin_expect((value), 0)
525#else
526# define UNLIKELY(value) (value)
527#endif
528
529/* -1 indicates that we haven't checked that we're running on valgrind yet. */
530static int running_on_valgrind = -1;
531#endif
532
Neil Schemenauera35c6882001-02-27 04:45:05 +0000533/* An object allocator for Python.
534
535 Here is an introduction to the layers of the Python memory architecture,
536 showing where the object allocator is actually used (layer +2), It is
537 called for every object allocation and deallocation (PyObject_New/Del),
538 unless the object-specific allocators implement a proprietary allocation
539 scheme (ex.: ints use a simple free list). This is also the place where
540 the cyclic garbage collector operates selectively on container objects.
541
542
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000543 Object-specific allocators
Neil Schemenauera35c6882001-02-27 04:45:05 +0000544 _____ ______ ______ ________
545 [ int ] [ dict ] [ list ] ... [ string ] Python core |
546+3 | <----- Object-specific memory -----> | <-- Non-object memory --> |
547 _______________________________ | |
548 [ Python's object allocator ] | |
549+2 | ####### Object memory ####### | <------ Internal buffers ------> |
550 ______________________________________________________________ |
551 [ Python's raw memory allocator (PyMem_ API) ] |
552+1 | <----- Python memory (under PyMem manager's control) ------> | |
553 __________________________________________________________________
554 [ Underlying general-purpose allocator (ex: C library malloc) ]
555 0 | <------ Virtual memory allocated for the python process -------> |
556
557 =========================================================================
558 _______________________________________________________________________
559 [ OS-specific Virtual Memory Manager (VMM) ]
560-1 | <--- Kernel dynamic storage allocation & management (page-based) ---> |
561 __________________________________ __________________________________
562 [ ] [ ]
563-2 | <-- Physical memory: ROM/RAM --> | | <-- Secondary storage (swap) --> |
564
565*/
566/*==========================================================================*/
567
568/* A fast, special-purpose memory allocator for small blocks, to be used
569 on top of a general-purpose malloc -- heavily based on previous art. */
570
571/* Vladimir Marangozov -- August 2000 */
572
573/*
574 * "Memory management is where the rubber meets the road -- if we do the wrong
575 * thing at any level, the results will not be good. And if we don't make the
576 * levels work well together, we are in serious trouble." (1)
577 *
578 * (1) Paul R. Wilson, Mark S. Johnstone, Michael Neely, and David Boles,
579 * "Dynamic Storage Allocation: A Survey and Critical Review",
580 * in Proc. 1995 Int'l. Workshop on Memory Management, September 1995.
581 */
582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000583/* #undef WITH_MEMORY_LIMITS */ /* disable mem limit checks */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000584
585/*==========================================================================*/
586
587/*
Neil Schemenauera35c6882001-02-27 04:45:05 +0000588 * Allocation strategy abstract:
589 *
590 * For small requests, the allocator sub-allocates <Big> blocks of memory.
Antoine Pitrou6f26be02011-05-03 18:18:59 +0200591 * Requests greater than SMALL_REQUEST_THRESHOLD bytes are routed to the
592 * system's allocator.
Tim Petersce7fb9b2002-03-23 00:28:57 +0000593 *
Neil Schemenauera35c6882001-02-27 04:45:05 +0000594 * Small requests are grouped in size classes spaced 8 bytes apart, due
595 * to the required valid alignment of the returned address. Requests of
596 * a particular size are serviced from memory pools of 4K (one VMM page).
597 * Pools are fragmented on demand and contain free lists of blocks of one
598 * particular size class. In other words, there is a fixed-size allocator
599 * for each size class. Free pools are shared by the different allocators
600 * thus minimizing the space reserved for a particular size class.
601 *
602 * This allocation strategy is a variant of what is known as "simple
603 * segregated storage based on array of free lists". The main drawback of
604 * simple segregated storage is that we might end up with lot of reserved
605 * memory for the different free lists, which degenerate in time. To avoid
606 * this, we partition each free list in pools and we share dynamically the
607 * reserved space between all free lists. This technique is quite efficient
608 * for memory intensive programs which allocate mainly small-sized blocks.
609 *
610 * For small requests we have the following table:
611 *
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 * Request in bytes Size of allocated block Size class idx
Neil Schemenauera35c6882001-02-27 04:45:05 +0000613 * ----------------------------------------------------------------
614 * 1-8 8 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000615 * 9-16 16 1
616 * 17-24 24 2
617 * 25-32 32 3
618 * 33-40 40 4
619 * 41-48 48 5
620 * 49-56 56 6
621 * 57-64 64 7
622 * 65-72 72 8
623 * ... ... ...
Antoine Pitrou6f26be02011-05-03 18:18:59 +0200624 * 497-504 504 62
625 * 505-512 512 63
Tim Petersce7fb9b2002-03-23 00:28:57 +0000626 *
Antoine Pitrou6f26be02011-05-03 18:18:59 +0200627 * 0, SMALL_REQUEST_THRESHOLD + 1 and up: routed to the underlying
628 * allocator.
Neil Schemenauera35c6882001-02-27 04:45:05 +0000629 */
630
631/*==========================================================================*/
632
633/*
634 * -- Main tunable settings section --
635 */
636
637/*
638 * Alignment of addresses returned to the user. 8-bytes alignment works
639 * on most current architectures (with 32-bit or 64-bit address busses).
640 * The alignment value is also used for grouping small requests in size
641 * classes spaced ALIGNMENT bytes apart.
642 *
643 * You shouldn't change this unless you know what you are doing.
644 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000645#define ALIGNMENT 8 /* must be 2^N */
646#define ALIGNMENT_SHIFT 3
Neil Schemenauera35c6882001-02-27 04:45:05 +0000647
Tim Peterse70ddf32002-04-05 04:32:29 +0000648/* Return the number of bytes in size class I, as a uint. */
649#define INDEX2SIZE(I) (((uint)(I) + 1) << ALIGNMENT_SHIFT)
650
Neil Schemenauera35c6882001-02-27 04:45:05 +0000651/*
652 * Max size threshold below which malloc requests are considered to be
653 * small enough in order to use preallocated memory pools. You can tune
654 * this value according to your application behaviour and memory needs.
655 *
Antoine Pitrou6f26be02011-05-03 18:18:59 +0200656 * Note: a size threshold of 512 guarantees that newly created dictionaries
657 * will be allocated from preallocated memory pools on 64-bit.
658 *
Neil Schemenauera35c6882001-02-27 04:45:05 +0000659 * The following invariants must hold:
Antoine Pitrou6f26be02011-05-03 18:18:59 +0200660 * 1) ALIGNMENT <= SMALL_REQUEST_THRESHOLD <= 512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 * 2) SMALL_REQUEST_THRESHOLD is evenly divisible by ALIGNMENT
Neil Schemenauera35c6882001-02-27 04:45:05 +0000662 *
663 * Although not required, for better performance and space efficiency,
664 * it is recommended that SMALL_REQUEST_THRESHOLD is set to a power of 2.
665 */
Antoine Pitrou6f26be02011-05-03 18:18:59 +0200666#define SMALL_REQUEST_THRESHOLD 512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000667#define NB_SMALL_SIZE_CLASSES (SMALL_REQUEST_THRESHOLD / ALIGNMENT)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000668
669/*
670 * The system's VMM page size can be obtained on most unices with a
671 * getpagesize() call or deduced from various header files. To make
672 * things simpler, we assume that it is 4K, which is OK for most systems.
673 * It is probably better if this is the native page size, but it doesn't
Tim Petersecc6e6a2005-07-10 22:30:55 +0000674 * have to be. In theory, if SYSTEM_PAGE_SIZE is larger than the native page
675 * size, then `POOL_ADDR(p)->arenaindex' could rarely cause a segmentation
676 * violation fault. 4K is apparently OK for all the platforms that python
Martin v. Löwis8c140282002-10-26 15:01:53 +0000677 * currently targets.
Neil Schemenauera35c6882001-02-27 04:45:05 +0000678 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000679#define SYSTEM_PAGE_SIZE (4 * 1024)
680#define SYSTEM_PAGE_SIZE_MASK (SYSTEM_PAGE_SIZE - 1)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000681
682/*
683 * Maximum amount of memory managed by the allocator for small requests.
684 */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000685#ifdef WITH_MEMORY_LIMITS
686#ifndef SMALL_MEMORY_LIMIT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000687#define SMALL_MEMORY_LIMIT (64 * 1024 * 1024) /* 64 MB -- more? */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000688#endif
689#endif
690
691/*
692 * The allocator sub-allocates <Big> blocks of memory (called arenas) aligned
693 * on a page boundary. This is a reserved virtual address space for the
Antoine Pitrouf0effe62011-11-26 01:11:02 +0100694 * current process (obtained through a malloc()/mmap() call). In no way this
695 * means that the memory arenas will be used entirely. A malloc(<Big>) is
696 * usually an address range reservation for <Big> bytes, unless all pages within
697 * this space are referenced subsequently. So malloc'ing big blocks and not
698 * using them does not mean "wasting memory". It's an addressable range
699 * wastage...
Neil Schemenauera35c6882001-02-27 04:45:05 +0000700 *
Antoine Pitrouf0effe62011-11-26 01:11:02 +0100701 * Arenas are allocated with mmap() on systems supporting anonymous memory
702 * mappings to reduce heap fragmentation.
Neil Schemenauera35c6882001-02-27 04:45:05 +0000703 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000704#define ARENA_SIZE (256 << 10) /* 256KB */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000705
706#ifdef WITH_MEMORY_LIMITS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000707#define MAX_ARENAS (SMALL_MEMORY_LIMIT / ARENA_SIZE)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000708#endif
709
710/*
711 * Size of the pools used for small blocks. Should be a power of 2,
Tim Petersc2ce91a2002-03-30 21:36:04 +0000712 * between 1K and SYSTEM_PAGE_SIZE, that is: 1k, 2k, 4k.
Neil Schemenauera35c6882001-02-27 04:45:05 +0000713 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714#define POOL_SIZE SYSTEM_PAGE_SIZE /* must be 2^N */
715#define POOL_SIZE_MASK SYSTEM_PAGE_SIZE_MASK
Neil Schemenauera35c6882001-02-27 04:45:05 +0000716
717/*
718 * -- End of tunable settings section --
719 */
720
721/*==========================================================================*/
722
723/*
724 * Locking
725 *
726 * To reduce lock contention, it would probably be better to refine the
727 * crude function locking with per size class locking. I'm not positive
728 * however, whether it's worth switching to such locking policy because
729 * of the performance penalty it might introduce.
730 *
731 * The following macros describe the simplest (should also be the fastest)
732 * lock object on a particular platform and the init/fini/lock/unlock
733 * operations on it. The locks defined here are not expected to be recursive
734 * because it is assumed that they will always be called in the order:
735 * INIT, [LOCK, UNLOCK]*, FINI.
736 */
737
738/*
739 * Python's threads are serialized, so object malloc locking is disabled.
740 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000741#define SIMPLELOCK_DECL(lock) /* simple lock declaration */
742#define SIMPLELOCK_INIT(lock) /* allocate (if needed) and initialize */
743#define SIMPLELOCK_FINI(lock) /* free/destroy an existing lock */
744#define SIMPLELOCK_LOCK(lock) /* acquire released lock */
745#define SIMPLELOCK_UNLOCK(lock) /* release acquired lock */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000746
Neil Schemenauera35c6882001-02-27 04:45:05 +0000747/* When you say memory, my mind reasons in terms of (pointers to) blocks */
748typedef uchar block;
749
Tim Peterse70ddf32002-04-05 04:32:29 +0000750/* Pool for small blocks. */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000751struct pool_header {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000752 union { block *_padding;
Stefan Krah735bb122010-11-26 10:54:09 +0000753 uint count; } ref; /* number of allocated blocks */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000754 block *freeblock; /* pool's free list head */
755 struct pool_header *nextpool; /* next pool of this size class */
756 struct pool_header *prevpool; /* previous pool "" */
757 uint arenaindex; /* index into arenas of base adr */
758 uint szidx; /* block size class index */
759 uint nextoffset; /* bytes to virgin block */
760 uint maxnextoffset; /* largest valid nextoffset */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000761};
762
763typedef struct pool_header *poolp;
764
Thomas Woutersa9773292006-04-21 09:43:23 +0000765/* Record keeping for arenas. */
766struct arena_object {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000767 /* The address of the arena, as returned by malloc. Note that 0
768 * will never be returned by a successful malloc, and is used
769 * here to mark an arena_object that doesn't correspond to an
770 * allocated arena.
771 */
772 uptr address;
Thomas Woutersa9773292006-04-21 09:43:23 +0000773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000774 /* Pool-aligned pointer to the next pool to be carved off. */
775 block* pool_address;
Thomas Woutersa9773292006-04-21 09:43:23 +0000776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000777 /* The number of available pools in the arena: free pools + never-
778 * allocated pools.
779 */
780 uint nfreepools;
Thomas Woutersa9773292006-04-21 09:43:23 +0000781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 /* The total number of pools in the arena, whether or not available. */
783 uint ntotalpools;
Thomas Woutersa9773292006-04-21 09:43:23 +0000784
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000785 /* Singly-linked list of available pools. */
786 struct pool_header* freepools;
Thomas Woutersa9773292006-04-21 09:43:23 +0000787
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000788 /* Whenever this arena_object is not associated with an allocated
789 * arena, the nextarena member is used to link all unassociated
790 * arena_objects in the singly-linked `unused_arena_objects` list.
791 * The prevarena member is unused in this case.
792 *
793 * When this arena_object is associated with an allocated arena
794 * with at least one available pool, both members are used in the
795 * doubly-linked `usable_arenas` list, which is maintained in
796 * increasing order of `nfreepools` values.
797 *
798 * Else this arena_object is associated with an allocated arena
799 * all of whose pools are in use. `nextarena` and `prevarena`
800 * are both meaningless in this case.
801 */
802 struct arena_object* nextarena;
803 struct arena_object* prevarena;
Thomas Woutersa9773292006-04-21 09:43:23 +0000804};
805
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +0200806#define POOL_OVERHEAD _Py_SIZE_ROUND_UP(sizeof(struct pool_header), ALIGNMENT)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808#define DUMMY_SIZE_IDX 0xffff /* size class of newly cached pools */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000809
Tim Petersd97a1c02002-03-30 06:09:22 +0000810/* Round pointer P down to the closest pool-aligned address <= P, as a poolp */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +0200811#define POOL_ADDR(P) ((poolp)_Py_ALIGN_DOWN((P), POOL_SIZE))
Tim Peterse70ddf32002-04-05 04:32:29 +0000812
Tim Peters16bcb6b2002-04-05 05:45:31 +0000813/* Return total number of blocks in pool of size index I, as a uint. */
814#define NUMBLOCKS(I) ((uint)(POOL_SIZE - POOL_OVERHEAD) / INDEX2SIZE(I))
Tim Petersd97a1c02002-03-30 06:09:22 +0000815
Neil Schemenauera35c6882001-02-27 04:45:05 +0000816/*==========================================================================*/
817
818/*
819 * This malloc lock
820 */
Jeremy Hyltond1fedb62002-07-18 18:49:52 +0000821SIMPLELOCK_DECL(_malloc_lock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000822#define LOCK() SIMPLELOCK_LOCK(_malloc_lock)
823#define UNLOCK() SIMPLELOCK_UNLOCK(_malloc_lock)
824#define LOCK_INIT() SIMPLELOCK_INIT(_malloc_lock)
825#define LOCK_FINI() SIMPLELOCK_FINI(_malloc_lock)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000826
827/*
Tim Peters1e16db62002-03-31 01:05:22 +0000828 * Pool table -- headed, circular, doubly-linked lists of partially used pools.
829
830This is involved. For an index i, usedpools[i+i] is the header for a list of
831all partially used pools holding small blocks with "size class idx" i. So
832usedpools[0] corresponds to blocks of size 8, usedpools[2] to blocks of size
83316, and so on: index 2*i <-> blocks of size (i+1)<<ALIGNMENT_SHIFT.
834
Thomas Woutersa9773292006-04-21 09:43:23 +0000835Pools are carved off an arena's highwater mark (an arena_object's pool_address
836member) as needed. Once carved off, a pool is in one of three states forever
837after:
Tim Peters1e16db62002-03-31 01:05:22 +0000838
Tim Peters338e0102002-04-01 19:23:44 +0000839used == partially used, neither empty nor full
840 At least one block in the pool is currently allocated, and at least one
841 block in the pool is not currently allocated (note this implies a pool
842 has room for at least two blocks).
843 This is a pool's initial state, as a pool is created only when malloc
844 needs space.
845 The pool holds blocks of a fixed size, and is in the circular list headed
846 at usedpools[i] (see above). It's linked to the other used pools of the
847 same size class via the pool_header's nextpool and prevpool members.
848 If all but one block is currently allocated, a malloc can cause a
849 transition to the full state. If all but one block is not currently
850 allocated, a free can cause a transition to the empty state.
Tim Peters1e16db62002-03-31 01:05:22 +0000851
Tim Peters338e0102002-04-01 19:23:44 +0000852full == all the pool's blocks are currently allocated
853 On transition to full, a pool is unlinked from its usedpools[] list.
854 It's not linked to from anything then anymore, and its nextpool and
855 prevpool members are meaningless until it transitions back to used.
856 A free of a block in a full pool puts the pool back in the used state.
857 Then it's linked in at the front of the appropriate usedpools[] list, so
858 that the next allocation for its size class will reuse the freed block.
859
860empty == all the pool's blocks are currently available for allocation
861 On transition to empty, a pool is unlinked from its usedpools[] list,
Thomas Woutersa9773292006-04-21 09:43:23 +0000862 and linked to the front of its arena_object's singly-linked freepools list,
Tim Peters338e0102002-04-01 19:23:44 +0000863 via its nextpool member. The prevpool member has no meaning in this case.
864 Empty pools have no inherent size class: the next time a malloc finds
865 an empty list in usedpools[], it takes the first pool off of freepools.
866 If the size class needed happens to be the same as the size class the pool
Tim Peterse70ddf32002-04-05 04:32:29 +0000867 last had, some pool initialization can be skipped.
Tim Peters338e0102002-04-01 19:23:44 +0000868
869
870Block Management
871
872Blocks within pools are again carved out as needed. pool->freeblock points to
873the start of a singly-linked list of free blocks within the pool. When a
874block is freed, it's inserted at the front of its pool's freeblock list. Note
875that the available blocks in a pool are *not* linked all together when a pool
Tim Peterse70ddf32002-04-05 04:32:29 +0000876is initialized. Instead only "the first two" (lowest addresses) blocks are
877set up, returning the first such block, and setting pool->freeblock to a
878one-block list holding the second such block. This is consistent with that
879pymalloc strives at all levels (arena, pool, and block) never to touch a piece
880of memory until it's actually needed.
881
882So long as a pool is in the used state, we're certain there *is* a block
Tim Peters52aefc82002-04-11 06:36:45 +0000883available for allocating, and pool->freeblock is not NULL. If pool->freeblock
884points to the end of the free list before we've carved the entire pool into
885blocks, that means we simply haven't yet gotten to one of the higher-address
886blocks. The offset from the pool_header to the start of "the next" virgin
887block is stored in the pool_header nextoffset member, and the largest value
888of nextoffset that makes sense is stored in the maxnextoffset member when a
889pool is initialized. All the blocks in a pool have been passed out at least
890once when and only when nextoffset > maxnextoffset.
Tim Peters338e0102002-04-01 19:23:44 +0000891
Tim Peters1e16db62002-03-31 01:05:22 +0000892
893Major obscurity: While the usedpools vector is declared to have poolp
894entries, it doesn't really. It really contains two pointers per (conceptual)
895poolp entry, the nextpool and prevpool members of a pool_header. The
896excruciating initialization code below fools C so that
897
898 usedpool[i+i]
899
900"acts like" a genuine poolp, but only so long as you only reference its
901nextpool and prevpool members. The "- 2*sizeof(block *)" gibberish is
902compensating for that a pool_header's nextpool and prevpool members
903immediately follow a pool_header's first two members:
904
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000905 union { block *_padding;
Stefan Krah735bb122010-11-26 10:54:09 +0000906 uint count; } ref;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 block *freeblock;
Tim Peters1e16db62002-03-31 01:05:22 +0000908
909each of which consume sizeof(block *) bytes. So what usedpools[i+i] really
910contains is a fudged-up pointer p such that *if* C believes it's a poolp
911pointer, then p->nextpool and p->prevpool are both p (meaning that the headed
912circular list is empty).
913
914It's unclear why the usedpools setup is so convoluted. It could be to
915minimize the amount of cache required to hold this heavily-referenced table
916(which only *needs* the two interpool pointer members of a pool_header). OTOH,
917referencing code has to remember to "double the index" and doing so isn't
918free, usedpools[0] isn't a strictly legal pointer, and we're crucially relying
919on that C doesn't insert any padding anywhere in a pool_header at or before
920the prevpool member.
921**************************************************************************** */
922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000923#define PTA(x) ((poolp )((uchar *)&(usedpools[2*(x)]) - 2*sizeof(block *)))
924#define PT(x) PTA(x), PTA(x)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000925
926static poolp usedpools[2 * ((NB_SMALL_SIZE_CLASSES + 7) / 8) * 8] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000927 PT(0), PT(1), PT(2), PT(3), PT(4), PT(5), PT(6), PT(7)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000928#if NB_SMALL_SIZE_CLASSES > 8
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000929 , PT(8), PT(9), PT(10), PT(11), PT(12), PT(13), PT(14), PT(15)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000930#if NB_SMALL_SIZE_CLASSES > 16
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 , PT(16), PT(17), PT(18), PT(19), PT(20), PT(21), PT(22), PT(23)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000932#if NB_SMALL_SIZE_CLASSES > 24
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000933 , PT(24), PT(25), PT(26), PT(27), PT(28), PT(29), PT(30), PT(31)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000934#if NB_SMALL_SIZE_CLASSES > 32
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935 , PT(32), PT(33), PT(34), PT(35), PT(36), PT(37), PT(38), PT(39)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000936#if NB_SMALL_SIZE_CLASSES > 40
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000937 , PT(40), PT(41), PT(42), PT(43), PT(44), PT(45), PT(46), PT(47)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000938#if NB_SMALL_SIZE_CLASSES > 48
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 , PT(48), PT(49), PT(50), PT(51), PT(52), PT(53), PT(54), PT(55)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000940#if NB_SMALL_SIZE_CLASSES > 56
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 , PT(56), PT(57), PT(58), PT(59), PT(60), PT(61), PT(62), PT(63)
Antoine Pitrou6f26be02011-05-03 18:18:59 +0200942#if NB_SMALL_SIZE_CLASSES > 64
943#error "NB_SMALL_SIZE_CLASSES should be less than 64"
944#endif /* NB_SMALL_SIZE_CLASSES > 64 */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000945#endif /* NB_SMALL_SIZE_CLASSES > 56 */
946#endif /* NB_SMALL_SIZE_CLASSES > 48 */
947#endif /* NB_SMALL_SIZE_CLASSES > 40 */
948#endif /* NB_SMALL_SIZE_CLASSES > 32 */
949#endif /* NB_SMALL_SIZE_CLASSES > 24 */
950#endif /* NB_SMALL_SIZE_CLASSES > 16 */
951#endif /* NB_SMALL_SIZE_CLASSES > 8 */
952};
953
Thomas Woutersa9773292006-04-21 09:43:23 +0000954/*==========================================================================
955Arena management.
Neil Schemenauera35c6882001-02-27 04:45:05 +0000956
Thomas Woutersa9773292006-04-21 09:43:23 +0000957`arenas` is a vector of arena_objects. It contains maxarenas entries, some of
958which may not be currently used (== they're arena_objects that aren't
959currently associated with an allocated arena). Note that arenas proper are
960separately malloc'ed.
Neil Schemenauera35c6882001-02-27 04:45:05 +0000961
Thomas Woutersa9773292006-04-21 09:43:23 +0000962Prior to Python 2.5, arenas were never free()'ed. Starting with Python 2.5,
963we do try to free() arenas, and use some mild heuristic strategies to increase
964the likelihood that arenas eventually can be freed.
965
966unused_arena_objects
967
968 This is a singly-linked list of the arena_objects that are currently not
969 being used (no arena is associated with them). Objects are taken off the
970 head of the list in new_arena(), and are pushed on the head of the list in
971 PyObject_Free() when the arena is empty. Key invariant: an arena_object
972 is on this list if and only if its .address member is 0.
973
974usable_arenas
975
976 This is a doubly-linked list of the arena_objects associated with arenas
977 that have pools available. These pools are either waiting to be reused,
978 or have not been used before. The list is sorted to have the most-
979 allocated arenas first (ascending order based on the nfreepools member).
980 This means that the next allocation will come from a heavily used arena,
981 which gives the nearly empty arenas a chance to be returned to the system.
982 In my unscientific tests this dramatically improved the number of arenas
983 that could be freed.
984
985Note that an arena_object associated with an arena all of whose pools are
986currently in use isn't on either list.
987*/
988
989/* Array of objects used to track chunks of memory (arenas). */
990static struct arena_object* arenas = NULL;
991/* Number of slots currently allocated in the `arenas` vector. */
Tim Peters1d99af82002-03-30 10:35:09 +0000992static uint maxarenas = 0;
Tim Petersd97a1c02002-03-30 06:09:22 +0000993
Thomas Woutersa9773292006-04-21 09:43:23 +0000994/* The head of the singly-linked, NULL-terminated list of available
995 * arena_objects.
Tim Petersd97a1c02002-03-30 06:09:22 +0000996 */
Thomas Woutersa9773292006-04-21 09:43:23 +0000997static struct arena_object* unused_arena_objects = NULL;
998
999/* The head of the doubly-linked, NULL-terminated at each end, list of
1000 * arena_objects associated with arenas that have pools available.
1001 */
1002static struct arena_object* usable_arenas = NULL;
1003
1004/* How many arena_objects do we initially allocate?
1005 * 16 = can allocate 16 arenas = 16 * ARENA_SIZE = 4MB before growing the
1006 * `arenas` vector.
1007 */
1008#define INITIAL_ARENA_OBJECTS 16
1009
1010/* Number of arenas allocated that haven't been free()'d. */
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001011static size_t narenas_currently_allocated = 0;
Thomas Woutersa9773292006-04-21 09:43:23 +00001012
Thomas Woutersa9773292006-04-21 09:43:23 +00001013/* Total number of times malloc() called to allocate an arena. */
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001014static size_t ntimes_arena_allocated = 0;
Thomas Woutersa9773292006-04-21 09:43:23 +00001015/* High water mark (max value ever seen) for narenas_currently_allocated. */
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001016static size_t narenas_highwater = 0;
Thomas Woutersa9773292006-04-21 09:43:23 +00001017
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001018static Py_ssize_t _Py_AllocatedBlocks = 0;
1019
1020Py_ssize_t
1021_Py_GetAllocatedBlocks(void)
1022{
1023 return _Py_AllocatedBlocks;
1024}
1025
1026
Thomas Woutersa9773292006-04-21 09:43:23 +00001027/* Allocate a new arena. If we run out of memory, return NULL. Else
1028 * allocate a new arena, and return the address of an arena_object
1029 * describing the new arena. It's expected that the caller will set
1030 * `usable_arenas` to the return value.
1031 */
1032static struct arena_object*
Tim Petersd97a1c02002-03-30 06:09:22 +00001033new_arena(void)
1034{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001035 struct arena_object* arenaobj;
1036 uint excess; /* number of bytes above pool alignment */
Victor Stinnerba108822012-03-10 00:21:44 +01001037 void *address;
Victor Stinner34be8072016-03-14 12:04:26 +01001038 static int debug_stats = -1;
Tim Petersd97a1c02002-03-30 06:09:22 +00001039
Victor Stinner34be8072016-03-14 12:04:26 +01001040 if (debug_stats == -1) {
1041 char *opt = Py_GETENV("PYTHONMALLOCSTATS");
1042 debug_stats = (opt != NULL && *opt != '\0');
1043 }
1044 if (debug_stats)
David Malcolm49526f42012-06-22 14:55:41 -04001045 _PyObject_DebugMallocStats(stderr);
Victor Stinner34be8072016-03-14 12:04:26 +01001046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001047 if (unused_arena_objects == NULL) {
1048 uint i;
1049 uint numarenas;
1050 size_t nbytes;
Tim Peters0e871182002-04-13 08:29:14 +00001051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 /* Double the number of arena objects on each allocation.
1053 * Note that it's possible for `numarenas` to overflow.
1054 */
1055 numarenas = maxarenas ? maxarenas << 1 : INITIAL_ARENA_OBJECTS;
1056 if (numarenas <= maxarenas)
1057 return NULL; /* overflow */
Martin v. Löwis5aca8822008-09-11 06:55:48 +00001058#if SIZEOF_SIZE_T <= SIZEOF_INT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001059 if (numarenas > PY_SIZE_MAX / sizeof(*arenas))
1060 return NULL; /* overflow */
Martin v. Löwis5aca8822008-09-11 06:55:48 +00001061#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001062 nbytes = numarenas * sizeof(*arenas);
Victor Stinner6cf185d2013-10-10 15:58:42 +02001063 arenaobj = (struct arena_object *)PyMem_RawRealloc(arenas, nbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001064 if (arenaobj == NULL)
1065 return NULL;
1066 arenas = arenaobj;
Thomas Woutersa9773292006-04-21 09:43:23 +00001067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001068 /* We might need to fix pointers that were copied. However,
1069 * new_arena only gets called when all the pages in the
1070 * previous arenas are full. Thus, there are *no* pointers
1071 * into the old array. Thus, we don't have to worry about
1072 * invalid pointers. Just to be sure, some asserts:
1073 */
1074 assert(usable_arenas == NULL);
1075 assert(unused_arena_objects == NULL);
Thomas Woutersa9773292006-04-21 09:43:23 +00001076
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001077 /* Put the new arenas on the unused_arena_objects list. */
1078 for (i = maxarenas; i < numarenas; ++i) {
1079 arenas[i].address = 0; /* mark as unassociated */
1080 arenas[i].nextarena = i < numarenas - 1 ?
1081 &arenas[i+1] : NULL;
1082 }
Thomas Woutersa9773292006-04-21 09:43:23 +00001083
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 /* Update globals. */
1085 unused_arena_objects = &arenas[maxarenas];
1086 maxarenas = numarenas;
1087 }
Tim Petersd97a1c02002-03-30 06:09:22 +00001088
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001089 /* Take the next available arena object off the head of the list. */
1090 assert(unused_arena_objects != NULL);
1091 arenaobj = unused_arena_objects;
1092 unused_arena_objects = arenaobj->nextarena;
1093 assert(arenaobj->address == 0);
Victor Stinner0507bf52013-07-07 02:05:46 +02001094 address = _PyObject_Arena.alloc(_PyObject_Arena.ctx, ARENA_SIZE);
1095 if (address == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001096 /* The allocation failed: return NULL after putting the
1097 * arenaobj back.
1098 */
1099 arenaobj->nextarena = unused_arena_objects;
1100 unused_arena_objects = arenaobj;
1101 return NULL;
1102 }
Victor Stinnerba108822012-03-10 00:21:44 +01001103 arenaobj->address = (uptr)address;
Tim Petersd97a1c02002-03-30 06:09:22 +00001104
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001105 ++narenas_currently_allocated;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 ++ntimes_arena_allocated;
1107 if (narenas_currently_allocated > narenas_highwater)
1108 narenas_highwater = narenas_currently_allocated;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001109 arenaobj->freepools = NULL;
1110 /* pool_address <- first pool-aligned address in the arena
1111 nfreepools <- number of whole pools that fit after alignment */
1112 arenaobj->pool_address = (block*)arenaobj->address;
1113 arenaobj->nfreepools = ARENA_SIZE / POOL_SIZE;
1114 assert(POOL_SIZE * arenaobj->nfreepools == ARENA_SIZE);
1115 excess = (uint)(arenaobj->address & POOL_SIZE_MASK);
1116 if (excess != 0) {
1117 --arenaobj->nfreepools;
1118 arenaobj->pool_address += POOL_SIZE - excess;
1119 }
1120 arenaobj->ntotalpools = arenaobj->nfreepools;
Thomas Woutersa9773292006-04-21 09:43:23 +00001121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001122 return arenaobj;
Tim Petersd97a1c02002-03-30 06:09:22 +00001123}
1124
Thomas Woutersa9773292006-04-21 09:43:23 +00001125/*
1126Py_ADDRESS_IN_RANGE(P, POOL)
1127
1128Return true if and only if P is an address that was allocated by pymalloc.
1129POOL must be the pool address associated with P, i.e., POOL = POOL_ADDR(P)
1130(the caller is asked to compute this because the macro expands POOL more than
1131once, and for efficiency it's best for the caller to assign POOL_ADDR(P) to a
1132variable and pass the latter to the macro; because Py_ADDRESS_IN_RANGE is
1133called on every alloc/realloc/free, micro-efficiency is important here).
1134
1135Tricky: Let B be the arena base address associated with the pool, B =
1136arenas[(POOL)->arenaindex].address. Then P belongs to the arena if and only if
1137
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001138 B <= P < B + ARENA_SIZE
Thomas Woutersa9773292006-04-21 09:43:23 +00001139
1140Subtracting B throughout, this is true iff
1141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142 0 <= P-B < ARENA_SIZE
Thomas Woutersa9773292006-04-21 09:43:23 +00001143
1144By using unsigned arithmetic, the "0 <=" half of the test can be skipped.
1145
1146Obscure: A PyMem "free memory" function can call the pymalloc free or realloc
1147before the first arena has been allocated. `arenas` is still NULL in that
1148case. We're relying on that maxarenas is also 0 in that case, so that
1149(POOL)->arenaindex < maxarenas must be false, saving us from trying to index
1150into a NULL arenas.
1151
1152Details: given P and POOL, the arena_object corresponding to P is AO =
1153arenas[(POOL)->arenaindex]. Suppose obmalloc controls P. Then (barring wild
1154stores, etc), POOL is the correct address of P's pool, AO.address is the
1155correct base address of the pool's arena, and P must be within ARENA_SIZE of
1156AO.address. In addition, AO.address is not 0 (no arena can start at address 0
1157(NULL)). Therefore Py_ADDRESS_IN_RANGE correctly reports that obmalloc
1158controls P.
1159
1160Now suppose obmalloc does not control P (e.g., P was obtained via a direct
1161call to the system malloc() or realloc()). (POOL)->arenaindex may be anything
1162in this case -- it may even be uninitialized trash. If the trash arenaindex
1163is >= maxarenas, the macro correctly concludes at once that obmalloc doesn't
1164control P.
1165
1166Else arenaindex is < maxarena, and AO is read up. If AO corresponds to an
1167allocated arena, obmalloc controls all the memory in slice AO.address :
1168AO.address+ARENA_SIZE. By case assumption, P is not controlled by obmalloc,
1169so P doesn't lie in that slice, so the macro correctly reports that P is not
1170controlled by obmalloc.
1171
1172Finally, if P is not controlled by obmalloc and AO corresponds to an unused
1173arena_object (one not currently associated with an allocated arena),
1174AO.address is 0, and the second test in the macro reduces to:
1175
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001176 P < ARENA_SIZE
Thomas Woutersa9773292006-04-21 09:43:23 +00001177
1178If P >= ARENA_SIZE (extremely likely), the macro again correctly concludes
1179that P is not controlled by obmalloc. However, if P < ARENA_SIZE, this part
1180of the test still passes, and the third clause (AO.address != 0) is necessary
1181to get the correct result: AO.address is 0 in this case, so the macro
1182correctly reports that P is not controlled by obmalloc (despite that P lies in
1183slice AO.address : AO.address + ARENA_SIZE).
1184
1185Note: The third (AO.address != 0) clause was added in Python 2.5. Before
11862.5, arenas were never free()'ed, and an arenaindex < maxarena always
1187corresponded to a currently-allocated arena, so the "P is not controlled by
1188obmalloc, AO corresponds to an unused arena_object, and P < ARENA_SIZE" case
1189was impossible.
1190
1191Note that the logic is excruciating, and reading up possibly uninitialized
1192memory when P is not controlled by obmalloc (to get at (POOL)->arenaindex)
1193creates problems for some memory debuggers. The overwhelming advantage is
1194that this test determines whether an arbitrary address is controlled by
1195obmalloc in a small constant time, independent of the number of arenas
1196obmalloc controls. Since this test is needed at every entry point, it's
1197extremely desirable that it be this fast.
Antoine Pitroub7fb2e22011-01-07 21:43:59 +00001198
1199Since Py_ADDRESS_IN_RANGE may be reading from memory which was not allocated
1200by Python, it is important that (POOL)->arenaindex is read only once, as
1201another thread may be concurrently modifying the value without holding the
1202GIL. To accomplish this, the arenaindex_temp variable is used to store
1203(POOL)->arenaindex for the duration of the Py_ADDRESS_IN_RANGE macro's
1204execution. The caller of the macro is responsible for declaring this
1205variable.
Thomas Woutersa9773292006-04-21 09:43:23 +00001206*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001207#define Py_ADDRESS_IN_RANGE(P, POOL) \
Antoine Pitroub7fb2e22011-01-07 21:43:59 +00001208 ((arenaindex_temp = (POOL)->arenaindex) < maxarenas && \
1209 (uptr)(P) - arenas[arenaindex_temp].address < (uptr)ARENA_SIZE && \
1210 arenas[arenaindex_temp].address != 0)
Thomas Woutersa9773292006-04-21 09:43:23 +00001211
Neal Norwitz7eb3c912004-06-06 19:20:22 +00001212
1213/* This is only useful when running memory debuggers such as
1214 * Purify or Valgrind. Uncomment to use.
1215 *
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001216#define Py_USING_MEMORY_DEBUGGER
Martin v. Löwis6fea2332008-09-25 04:15:27 +00001217 */
Neal Norwitz7eb3c912004-06-06 19:20:22 +00001218
1219#ifdef Py_USING_MEMORY_DEBUGGER
1220
1221/* Py_ADDRESS_IN_RANGE may access uninitialized memory by design
1222 * This leads to thousands of spurious warnings when using
1223 * Purify or Valgrind. By making a function, we can easily
1224 * suppress the uninitialized memory reads in this one function.
1225 * So we won't ignore real errors elsewhere.
1226 *
1227 * Disable the macro and use a function.
1228 */
1229
1230#undef Py_ADDRESS_IN_RANGE
1231
Thomas Wouters89f507f2006-12-13 04:49:30 +00001232#if defined(__GNUC__) && ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 1) || \
Stefan Krah735bb122010-11-26 10:54:09 +00001233 (__GNUC__ >= 4))
Neal Norwitze5e5aa42005-11-13 18:55:39 +00001234#define Py_NO_INLINE __attribute__((__noinline__))
1235#else
1236#define Py_NO_INLINE
1237#endif
1238
1239/* Don't make static, to try to ensure this isn't inlined. */
1240int Py_ADDRESS_IN_RANGE(void *P, poolp pool) Py_NO_INLINE;
1241#undef Py_NO_INLINE
Neal Norwitz7eb3c912004-06-06 19:20:22 +00001242#endif
Tim Peters338e0102002-04-01 19:23:44 +00001243
Neil Schemenauera35c6882001-02-27 04:45:05 +00001244/*==========================================================================*/
1245
Tim Peters84c1b972002-04-04 04:44:32 +00001246/* malloc. Note that nbytes==0 tries to return a non-NULL pointer, distinct
1247 * from all other currently live pointers. This may not be possible.
1248 */
Neil Schemenauera35c6882001-02-27 04:45:05 +00001249
1250/*
1251 * The basic blocks are ordered by decreasing execution frequency,
1252 * which minimizes the number of jumps in the most common cases,
1253 * improves branching prediction and instruction scheduling (small
1254 * block allocations typically result in a couple of instructions).
1255 * Unless the optimizer reorders everything, being too smart...
1256 */
1257
Victor Stinner0507bf52013-07-07 02:05:46 +02001258static void *
Victor Stinnerdb067af2014-05-02 22:31:14 +02001259_PyObject_Alloc(int use_calloc, void *ctx, size_t nelem, size_t elsize)
Neil Schemenauera35c6882001-02-27 04:45:05 +00001260{
Victor Stinnerdb067af2014-05-02 22:31:14 +02001261 size_t nbytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001262 block *bp;
1263 poolp pool;
1264 poolp next;
1265 uint size;
Neil Schemenauera35c6882001-02-27 04:45:05 +00001266
Antoine Pitrou0aaaa622013-04-06 01:15:30 +02001267 _Py_AllocatedBlocks++;
1268
Victor Stinner3080d922014-05-06 11:32:29 +02001269 assert(nelem <= PY_SSIZE_T_MAX / elsize);
1270 nbytes = nelem * elsize;
1271
Benjamin Peterson05159c42009-12-03 03:01:27 +00001272#ifdef WITH_VALGRIND
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001273 if (UNLIKELY(running_on_valgrind == -1))
1274 running_on_valgrind = RUNNING_ON_VALGRIND;
1275 if (UNLIKELY(running_on_valgrind))
1276 goto redirect;
Benjamin Peterson05159c42009-12-03 03:01:27 +00001277#endif
1278
Victor Stinneraf8fc642014-05-02 23:26:03 +02001279 if (nelem == 0 || elsize == 0)
1280 goto redirect;
1281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001282 if ((nbytes - 1) < SMALL_REQUEST_THRESHOLD) {
1283 LOCK();
1284 /*
1285 * Most frequent paths first
1286 */
1287 size = (uint)(nbytes - 1) >> ALIGNMENT_SHIFT;
1288 pool = usedpools[size + size];
1289 if (pool != pool->nextpool) {
1290 /*
1291 * There is a used pool for this size class.
1292 * Pick up the head block of its free list.
1293 */
1294 ++pool->ref.count;
1295 bp = pool->freeblock;
1296 assert(bp != NULL);
1297 if ((pool->freeblock = *(block **)bp) != NULL) {
1298 UNLOCK();
Victor Stinnerdb067af2014-05-02 22:31:14 +02001299 if (use_calloc)
1300 memset(bp, 0, nbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001301 return (void *)bp;
1302 }
1303 /*
1304 * Reached the end of the free list, try to extend it.
1305 */
1306 if (pool->nextoffset <= pool->maxnextoffset) {
1307 /* There is room for another block. */
1308 pool->freeblock = (block*)pool +
1309 pool->nextoffset;
1310 pool->nextoffset += INDEX2SIZE(size);
1311 *(block **)(pool->freeblock) = NULL;
1312 UNLOCK();
Victor Stinnerdb067af2014-05-02 22:31:14 +02001313 if (use_calloc)
1314 memset(bp, 0, nbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001315 return (void *)bp;
1316 }
1317 /* Pool is full, unlink from used pools. */
1318 next = pool->nextpool;
1319 pool = pool->prevpool;
1320 next->prevpool = pool;
1321 pool->nextpool = next;
1322 UNLOCK();
Victor Stinnerdb067af2014-05-02 22:31:14 +02001323 if (use_calloc)
1324 memset(bp, 0, nbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001325 return (void *)bp;
1326 }
Thomas Woutersa9773292006-04-21 09:43:23 +00001327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001328 /* There isn't a pool of the right size class immediately
1329 * available: use a free pool.
1330 */
1331 if (usable_arenas == NULL) {
1332 /* No arena has a free pool: allocate a new arena. */
Thomas Woutersa9773292006-04-21 09:43:23 +00001333#ifdef WITH_MEMORY_LIMITS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001334 if (narenas_currently_allocated >= MAX_ARENAS) {
1335 UNLOCK();
1336 goto redirect;
1337 }
Thomas Woutersa9773292006-04-21 09:43:23 +00001338#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001339 usable_arenas = new_arena();
1340 if (usable_arenas == NULL) {
1341 UNLOCK();
1342 goto redirect;
1343 }
1344 usable_arenas->nextarena =
1345 usable_arenas->prevarena = NULL;
1346 }
1347 assert(usable_arenas->address != 0);
Thomas Woutersa9773292006-04-21 09:43:23 +00001348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001349 /* Try to get a cached free pool. */
1350 pool = usable_arenas->freepools;
1351 if (pool != NULL) {
1352 /* Unlink from cached pools. */
1353 usable_arenas->freepools = pool->nextpool;
Thomas Woutersa9773292006-04-21 09:43:23 +00001354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001355 /* This arena already had the smallest nfreepools
1356 * value, so decreasing nfreepools doesn't change
1357 * that, and we don't need to rearrange the
1358 * usable_arenas list. However, if the arena has
1359 * become wholly allocated, we need to remove its
1360 * arena_object from usable_arenas.
1361 */
1362 --usable_arenas->nfreepools;
1363 if (usable_arenas->nfreepools == 0) {
1364 /* Wholly allocated: remove. */
1365 assert(usable_arenas->freepools == NULL);
1366 assert(usable_arenas->nextarena == NULL ||
1367 usable_arenas->nextarena->prevarena ==
1368 usable_arenas);
Thomas Woutersa9773292006-04-21 09:43:23 +00001369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001370 usable_arenas = usable_arenas->nextarena;
1371 if (usable_arenas != NULL) {
1372 usable_arenas->prevarena = NULL;
1373 assert(usable_arenas->address != 0);
1374 }
1375 }
1376 else {
1377 /* nfreepools > 0: it must be that freepools
1378 * isn't NULL, or that we haven't yet carved
1379 * off all the arena's pools for the first
1380 * time.
1381 */
1382 assert(usable_arenas->freepools != NULL ||
1383 usable_arenas->pool_address <=
1384 (block*)usable_arenas->address +
1385 ARENA_SIZE - POOL_SIZE);
1386 }
1387 init_pool:
1388 /* Frontlink to used pools. */
1389 next = usedpools[size + size]; /* == prev */
1390 pool->nextpool = next;
1391 pool->prevpool = next;
1392 next->nextpool = pool;
1393 next->prevpool = pool;
1394 pool->ref.count = 1;
1395 if (pool->szidx == size) {
1396 /* Luckily, this pool last contained blocks
1397 * of the same size class, so its header
1398 * and free list are already initialized.
1399 */
1400 bp = pool->freeblock;
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001401 assert(bp != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001402 pool->freeblock = *(block **)bp;
1403 UNLOCK();
Victor Stinnerdb067af2014-05-02 22:31:14 +02001404 if (use_calloc)
1405 memset(bp, 0, nbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001406 return (void *)bp;
1407 }
1408 /*
1409 * Initialize the pool header, set up the free list to
1410 * contain just the second block, and return the first
1411 * block.
1412 */
1413 pool->szidx = size;
1414 size = INDEX2SIZE(size);
1415 bp = (block *)pool + POOL_OVERHEAD;
1416 pool->nextoffset = POOL_OVERHEAD + (size << 1);
1417 pool->maxnextoffset = POOL_SIZE - size;
1418 pool->freeblock = bp + size;
1419 *(block **)(pool->freeblock) = NULL;
1420 UNLOCK();
Victor Stinnerdb067af2014-05-02 22:31:14 +02001421 if (use_calloc)
1422 memset(bp, 0, nbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001423 return (void *)bp;
1424 }
Thomas Woutersa9773292006-04-21 09:43:23 +00001425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001426 /* Carve off a new pool. */
1427 assert(usable_arenas->nfreepools > 0);
1428 assert(usable_arenas->freepools == NULL);
1429 pool = (poolp)usable_arenas->pool_address;
1430 assert((block*)pool <= (block*)usable_arenas->address +
1431 ARENA_SIZE - POOL_SIZE);
Serhiy Storchaka26861b02015-02-16 20:52:17 +02001432 pool->arenaindex = (uint)(usable_arenas - arenas);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001433 assert(&arenas[pool->arenaindex] == usable_arenas);
1434 pool->szidx = DUMMY_SIZE_IDX;
1435 usable_arenas->pool_address += POOL_SIZE;
1436 --usable_arenas->nfreepools;
Thomas Woutersa9773292006-04-21 09:43:23 +00001437
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001438 if (usable_arenas->nfreepools == 0) {
1439 assert(usable_arenas->nextarena == NULL ||
1440 usable_arenas->nextarena->prevarena ==
1441 usable_arenas);
1442 /* Unlink the arena: it is completely allocated. */
1443 usable_arenas = usable_arenas->nextarena;
1444 if (usable_arenas != NULL) {
1445 usable_arenas->prevarena = NULL;
1446 assert(usable_arenas->address != 0);
1447 }
1448 }
Thomas Woutersa9773292006-04-21 09:43:23 +00001449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001450 goto init_pool;
1451 }
Neil Schemenauera35c6882001-02-27 04:45:05 +00001452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001453 /* The small block allocator ends here. */
Neil Schemenauera35c6882001-02-27 04:45:05 +00001454
Tim Petersd97a1c02002-03-30 06:09:22 +00001455redirect:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001456 /* Redirect the original request to the underlying (libc) allocator.
1457 * We jump here on bigger requests, on error in the code above (as a
1458 * last chance to serve the request) or when the max memory limit
1459 * has been reached.
1460 */
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001461 {
Victor Stinnerdb067af2014-05-02 22:31:14 +02001462 void *result;
1463 if (use_calloc)
1464 result = PyMem_RawCalloc(nelem, elsize);
1465 else
1466 result = PyMem_RawMalloc(nbytes);
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001467 if (!result)
1468 _Py_AllocatedBlocks--;
1469 return result;
1470 }
Neil Schemenauera35c6882001-02-27 04:45:05 +00001471}
1472
Victor Stinnerdb067af2014-05-02 22:31:14 +02001473static void *
1474_PyObject_Malloc(void *ctx, size_t nbytes)
1475{
1476 return _PyObject_Alloc(0, ctx, 1, nbytes);
1477}
1478
1479static void *
1480_PyObject_Calloc(void *ctx, size_t nelem, size_t elsize)
1481{
1482 return _PyObject_Alloc(1, ctx, nelem, elsize);
1483}
1484
Neil Schemenauera35c6882001-02-27 04:45:05 +00001485/* free */
1486
Nick Coghlan6ba64f42013-09-29 00:28:55 +10001487ATTRIBUTE_NO_ADDRESS_SAFETY_ANALYSIS
Victor Stinner0507bf52013-07-07 02:05:46 +02001488static void
1489_PyObject_Free(void *ctx, void *p)
Neil Schemenauera35c6882001-02-27 04:45:05 +00001490{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001491 poolp pool;
1492 block *lastfree;
1493 poolp next, prev;
1494 uint size;
Antoine Pitroub7fb2e22011-01-07 21:43:59 +00001495#ifndef Py_USING_MEMORY_DEBUGGER
1496 uint arenaindex_temp;
1497#endif
Neil Schemenauera35c6882001-02-27 04:45:05 +00001498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001499 if (p == NULL) /* free(NULL) has no effect */
1500 return;
Neil Schemenauera35c6882001-02-27 04:45:05 +00001501
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001502 _Py_AllocatedBlocks--;
1503
Benjamin Peterson05159c42009-12-03 03:01:27 +00001504#ifdef WITH_VALGRIND
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001505 if (UNLIKELY(running_on_valgrind > 0))
1506 goto redirect;
Benjamin Peterson05159c42009-12-03 03:01:27 +00001507#endif
1508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001509 pool = POOL_ADDR(p);
1510 if (Py_ADDRESS_IN_RANGE(p, pool)) {
1511 /* We allocated this address. */
1512 LOCK();
1513 /* Link p to the start of the pool's freeblock list. Since
1514 * the pool had at least the p block outstanding, the pool
1515 * wasn't empty (so it's already in a usedpools[] list, or
1516 * was full and is in no list -- it's not in the freeblocks
1517 * list in any case).
1518 */
1519 assert(pool->ref.count > 0); /* else it was empty */
1520 *(block **)p = lastfree = pool->freeblock;
1521 pool->freeblock = (block *)p;
1522 if (lastfree) {
1523 struct arena_object* ao;
1524 uint nf; /* ao->nfreepools */
Thomas Woutersa9773292006-04-21 09:43:23 +00001525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001526 /* freeblock wasn't NULL, so the pool wasn't full,
1527 * and the pool is in a usedpools[] list.
1528 */
1529 if (--pool->ref.count != 0) {
1530 /* pool isn't empty: leave it in usedpools */
1531 UNLOCK();
1532 return;
1533 }
1534 /* Pool is now empty: unlink from usedpools, and
1535 * link to the front of freepools. This ensures that
1536 * previously freed pools will be allocated later
1537 * (being not referenced, they are perhaps paged out).
1538 */
1539 next = pool->nextpool;
1540 prev = pool->prevpool;
1541 next->prevpool = prev;
1542 prev->nextpool = next;
Thomas Woutersa9773292006-04-21 09:43:23 +00001543
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001544 /* Link the pool to freepools. This is a singly-linked
1545 * list, and pool->prevpool isn't used there.
1546 */
1547 ao = &arenas[pool->arenaindex];
1548 pool->nextpool = ao->freepools;
1549 ao->freepools = pool;
1550 nf = ++ao->nfreepools;
Thomas Woutersa9773292006-04-21 09:43:23 +00001551
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001552 /* All the rest is arena management. We just freed
1553 * a pool, and there are 4 cases for arena mgmt:
1554 * 1. If all the pools are free, return the arena to
1555 * the system free().
1556 * 2. If this is the only free pool in the arena,
1557 * add the arena back to the `usable_arenas` list.
1558 * 3. If the "next" arena has a smaller count of free
1559 * pools, we have to "slide this arena right" to
1560 * restore that usable_arenas is sorted in order of
1561 * nfreepools.
1562 * 4. Else there's nothing more to do.
1563 */
1564 if (nf == ao->ntotalpools) {
1565 /* Case 1. First unlink ao from usable_arenas.
1566 */
1567 assert(ao->prevarena == NULL ||
1568 ao->prevarena->address != 0);
1569 assert(ao ->nextarena == NULL ||
1570 ao->nextarena->address != 0);
Thomas Woutersa9773292006-04-21 09:43:23 +00001571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001572 /* Fix the pointer in the prevarena, or the
1573 * usable_arenas pointer.
1574 */
1575 if (ao->prevarena == NULL) {
1576 usable_arenas = ao->nextarena;
1577 assert(usable_arenas == NULL ||
1578 usable_arenas->address != 0);
1579 }
1580 else {
1581 assert(ao->prevarena->nextarena == ao);
1582 ao->prevarena->nextarena =
1583 ao->nextarena;
1584 }
1585 /* Fix the pointer in the nextarena. */
1586 if (ao->nextarena != NULL) {
1587 assert(ao->nextarena->prevarena == ao);
1588 ao->nextarena->prevarena =
1589 ao->prevarena;
1590 }
1591 /* Record that this arena_object slot is
1592 * available to be reused.
1593 */
1594 ao->nextarena = unused_arena_objects;
1595 unused_arena_objects = ao;
Thomas Woutersa9773292006-04-21 09:43:23 +00001596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001597 /* Free the entire arena. */
Victor Stinner0507bf52013-07-07 02:05:46 +02001598 _PyObject_Arena.free(_PyObject_Arena.ctx,
1599 (void *)ao->address, ARENA_SIZE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001600 ao->address = 0; /* mark unassociated */
1601 --narenas_currently_allocated;
Thomas Woutersa9773292006-04-21 09:43:23 +00001602
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001603 UNLOCK();
1604 return;
1605 }
1606 if (nf == 1) {
1607 /* Case 2. Put ao at the head of
1608 * usable_arenas. Note that because
1609 * ao->nfreepools was 0 before, ao isn't
1610 * currently on the usable_arenas list.
1611 */
1612 ao->nextarena = usable_arenas;
1613 ao->prevarena = NULL;
1614 if (usable_arenas)
1615 usable_arenas->prevarena = ao;
1616 usable_arenas = ao;
1617 assert(usable_arenas->address != 0);
Thomas Woutersa9773292006-04-21 09:43:23 +00001618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001619 UNLOCK();
1620 return;
1621 }
1622 /* If this arena is now out of order, we need to keep
1623 * the list sorted. The list is kept sorted so that
1624 * the "most full" arenas are used first, which allows
1625 * the nearly empty arenas to be completely freed. In
1626 * a few un-scientific tests, it seems like this
1627 * approach allowed a lot more memory to be freed.
1628 */
1629 if (ao->nextarena == NULL ||
1630 nf <= ao->nextarena->nfreepools) {
1631 /* Case 4. Nothing to do. */
1632 UNLOCK();
1633 return;
1634 }
1635 /* Case 3: We have to move the arena towards the end
1636 * of the list, because it has more free pools than
1637 * the arena to its right.
1638 * First unlink ao from usable_arenas.
1639 */
1640 if (ao->prevarena != NULL) {
1641 /* ao isn't at the head of the list */
1642 assert(ao->prevarena->nextarena == ao);
1643 ao->prevarena->nextarena = ao->nextarena;
1644 }
1645 else {
1646 /* ao is at the head of the list */
1647 assert(usable_arenas == ao);
1648 usable_arenas = ao->nextarena;
1649 }
1650 ao->nextarena->prevarena = ao->prevarena;
Thomas Woutersa9773292006-04-21 09:43:23 +00001651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001652 /* Locate the new insertion point by iterating over
1653 * the list, using our nextarena pointer.
1654 */
1655 while (ao->nextarena != NULL &&
1656 nf > ao->nextarena->nfreepools) {
1657 ao->prevarena = ao->nextarena;
1658 ao->nextarena = ao->nextarena->nextarena;
1659 }
Thomas Woutersa9773292006-04-21 09:43:23 +00001660
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001661 /* Insert ao at this point. */
1662 assert(ao->nextarena == NULL ||
1663 ao->prevarena == ao->nextarena->prevarena);
1664 assert(ao->prevarena->nextarena == ao->nextarena);
Thomas Woutersa9773292006-04-21 09:43:23 +00001665
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001666 ao->prevarena->nextarena = ao;
1667 if (ao->nextarena != NULL)
1668 ao->nextarena->prevarena = ao;
Thomas Woutersa9773292006-04-21 09:43:23 +00001669
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001670 /* Verify that the swaps worked. */
1671 assert(ao->nextarena == NULL ||
1672 nf <= ao->nextarena->nfreepools);
1673 assert(ao->prevarena == NULL ||
1674 nf > ao->prevarena->nfreepools);
1675 assert(ao->nextarena == NULL ||
1676 ao->nextarena->prevarena == ao);
1677 assert((usable_arenas == ao &&
1678 ao->prevarena == NULL) ||
1679 ao->prevarena->nextarena == ao);
Thomas Woutersa9773292006-04-21 09:43:23 +00001680
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001681 UNLOCK();
1682 return;
1683 }
1684 /* Pool was full, so doesn't currently live in any list:
1685 * link it to the front of the appropriate usedpools[] list.
1686 * This mimics LRU pool usage for new allocations and
1687 * targets optimal filling when several pools contain
1688 * blocks of the same size class.
1689 */
1690 --pool->ref.count;
1691 assert(pool->ref.count > 0); /* else the pool is empty */
1692 size = pool->szidx;
1693 next = usedpools[size + size];
1694 prev = next->prevpool;
1695 /* insert pool before next: prev <-> pool <-> next */
1696 pool->nextpool = next;
1697 pool->prevpool = prev;
1698 next->prevpool = pool;
1699 prev->nextpool = pool;
1700 UNLOCK();
1701 return;
1702 }
Neil Schemenauera35c6882001-02-27 04:45:05 +00001703
Benjamin Peterson05159c42009-12-03 03:01:27 +00001704#ifdef WITH_VALGRIND
1705redirect:
1706#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001707 /* We didn't allocate this address. */
Victor Stinner6cf185d2013-10-10 15:58:42 +02001708 PyMem_RawFree(p);
Neil Schemenauera35c6882001-02-27 04:45:05 +00001709}
1710
Tim Peters84c1b972002-04-04 04:44:32 +00001711/* realloc. If p is NULL, this acts like malloc(nbytes). Else if nbytes==0,
1712 * then as the Python docs promise, we do not treat this like free(p), and
1713 * return a non-NULL result.
1714 */
Neil Schemenauera35c6882001-02-27 04:45:05 +00001715
Nick Coghlan6ba64f42013-09-29 00:28:55 +10001716ATTRIBUTE_NO_ADDRESS_SAFETY_ANALYSIS
Victor Stinner0507bf52013-07-07 02:05:46 +02001717static void *
1718_PyObject_Realloc(void *ctx, void *p, size_t nbytes)
Neil Schemenauera35c6882001-02-27 04:45:05 +00001719{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001720 void *bp;
1721 poolp pool;
1722 size_t size;
Antoine Pitroub7fb2e22011-01-07 21:43:59 +00001723#ifndef Py_USING_MEMORY_DEBUGGER
1724 uint arenaindex_temp;
1725#endif
Neil Schemenauera35c6882001-02-27 04:45:05 +00001726
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001727 if (p == NULL)
Victor Stinnerdb067af2014-05-02 22:31:14 +02001728 return _PyObject_Alloc(0, ctx, 1, nbytes);
Georg Brandld492ad82008-07-23 16:13:07 +00001729
Benjamin Peterson05159c42009-12-03 03:01:27 +00001730#ifdef WITH_VALGRIND
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001731 /* Treat running_on_valgrind == -1 the same as 0 */
1732 if (UNLIKELY(running_on_valgrind > 0))
1733 goto redirect;
Benjamin Peterson05159c42009-12-03 03:01:27 +00001734#endif
1735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001736 pool = POOL_ADDR(p);
1737 if (Py_ADDRESS_IN_RANGE(p, pool)) {
1738 /* We're in charge of this block */
1739 size = INDEX2SIZE(pool->szidx);
1740 if (nbytes <= size) {
1741 /* The block is staying the same or shrinking. If
1742 * it's shrinking, there's a tradeoff: it costs
1743 * cycles to copy the block to a smaller size class,
1744 * but it wastes memory not to copy it. The
1745 * compromise here is to copy on shrink only if at
1746 * least 25% of size can be shaved off.
1747 */
1748 if (4 * nbytes > 3 * size) {
1749 /* It's the same,
1750 * or shrinking and new/old > 3/4.
1751 */
1752 return p;
1753 }
1754 size = nbytes;
1755 }
Victor Stinnerdb067af2014-05-02 22:31:14 +02001756 bp = _PyObject_Alloc(0, ctx, 1, nbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001757 if (bp != NULL) {
1758 memcpy(bp, p, size);
Victor Stinner0507bf52013-07-07 02:05:46 +02001759 _PyObject_Free(ctx, p);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001760 }
1761 return bp;
1762 }
Benjamin Peterson05159c42009-12-03 03:01:27 +00001763#ifdef WITH_VALGRIND
1764 redirect:
1765#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001766 /* We're not managing this block. If nbytes <=
1767 * SMALL_REQUEST_THRESHOLD, it's tempting to try to take over this
1768 * block. However, if we do, we need to copy the valid data from
1769 * the C-managed block to one of our blocks, and there's no portable
1770 * way to know how much of the memory space starting at p is valid.
1771 * As bug 1185883 pointed out the hard way, it's possible that the
1772 * C-managed block is "at the end" of allocated VM space, so that
1773 * a memory fault can occur if we try to copy nbytes bytes starting
1774 * at p. Instead we punt: let C continue to manage this block.
1775 */
1776 if (nbytes)
Victor Stinner6cf185d2013-10-10 15:58:42 +02001777 return PyMem_RawRealloc(p, nbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001778 /* C doesn't define the result of realloc(p, 0) (it may or may not
1779 * return NULL then), but Python's docs promise that nbytes==0 never
1780 * returns NULL. We don't pass 0 to realloc(), to avoid that endcase
1781 * to begin with. Even then, we can't be sure that realloc() won't
1782 * return NULL.
1783 */
Victor Stinner6cf185d2013-10-10 15:58:42 +02001784 bp = PyMem_RawRealloc(p, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001785 return bp ? bp : p;
Neil Schemenauera35c6882001-02-27 04:45:05 +00001786}
1787
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001788#else /* ! WITH_PYMALLOC */
Tim Petersddea2082002-03-23 10:03:50 +00001789
1790/*==========================================================================*/
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00001791/* pymalloc not enabled: Redirect the entry points to malloc. These will
1792 * only be used by extensions that are compiled with pymalloc enabled. */
Tim Peters62c06ba2002-03-23 22:28:18 +00001793
Antoine Pitrou92840532012-12-17 23:05:59 +01001794Py_ssize_t
1795_Py_GetAllocatedBlocks(void)
1796{
1797 return 0;
1798}
1799
Tim Peters1221c0a2002-03-23 00:20:15 +00001800#endif /* WITH_PYMALLOC */
1801
Victor Stinner34be8072016-03-14 12:04:26 +01001802
Tim Petersddea2082002-03-23 10:03:50 +00001803/*==========================================================================*/
Tim Peters62c06ba2002-03-23 22:28:18 +00001804/* A x-platform debugging allocator. This doesn't manage memory directly,
1805 * it wraps a real allocator, adding extra debugging info to the memory blocks.
1806 */
Tim Petersddea2082002-03-23 10:03:50 +00001807
Tim Petersf6fb5012002-04-12 07:38:53 +00001808/* Special bytes broadcast into debug memory blocks at appropriate times.
1809 * Strings of these are unlikely to be valid addresses, floats, ints or
1810 * 7-bit ASCII.
1811 */
1812#undef CLEANBYTE
1813#undef DEADBYTE
1814#undef FORBIDDENBYTE
1815#define CLEANBYTE 0xCB /* clean (newly allocated) memory */
Tim Peters889f61d2002-07-10 19:29:49 +00001816#define DEADBYTE 0xDB /* dead (newly freed) memory */
Tim Petersf6fb5012002-04-12 07:38:53 +00001817#define FORBIDDENBYTE 0xFB /* untouchable bytes at each end of a block */
Tim Petersddea2082002-03-23 10:03:50 +00001818
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001819static size_t serialno = 0; /* incremented on each debug {m,re}alloc */
Tim Petersddea2082002-03-23 10:03:50 +00001820
Tim Peterse0850172002-03-24 00:34:21 +00001821/* serialno is always incremented via calling this routine. The point is
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001822 * to supply a single place to set a breakpoint.
1823 */
Tim Peterse0850172002-03-24 00:34:21 +00001824static void
Neil Schemenauerbd02b142002-03-28 21:05:38 +00001825bumpserialno(void)
Tim Peterse0850172002-03-24 00:34:21 +00001826{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001827 ++serialno;
Tim Peterse0850172002-03-24 00:34:21 +00001828}
1829
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001830#define SST SIZEOF_SIZE_T
Tim Peterse0850172002-03-24 00:34:21 +00001831
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001832/* Read sizeof(size_t) bytes at p as a big-endian size_t. */
1833static size_t
1834read_size_t(const void *p)
Tim Petersddea2082002-03-23 10:03:50 +00001835{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001836 const uchar *q = (const uchar *)p;
1837 size_t result = *q++;
1838 int i;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001839
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001840 for (i = SST; --i > 0; ++q)
1841 result = (result << 8) | *q;
1842 return result;
Tim Petersddea2082002-03-23 10:03:50 +00001843}
1844
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001845/* Write n as a big-endian size_t, MSB at address p, LSB at
1846 * p + sizeof(size_t) - 1.
1847 */
Tim Petersddea2082002-03-23 10:03:50 +00001848static void
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001849write_size_t(void *p, size_t n)
Tim Petersddea2082002-03-23 10:03:50 +00001850{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001851 uchar *q = (uchar *)p + SST - 1;
1852 int i;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001853
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001854 for (i = SST; --i >= 0; --q) {
1855 *q = (uchar)(n & 0xff);
1856 n >>= 8;
1857 }
Tim Petersddea2082002-03-23 10:03:50 +00001858}
1859
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001860/* Let S = sizeof(size_t). The debug malloc asks for 4*S extra bytes and
1861 fills them with useful stuff, here calling the underlying malloc's result p:
Tim Petersddea2082002-03-23 10:03:50 +00001862
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001863p[0: S]
1864 Number of bytes originally asked for. This is a size_t, big-endian (easier
1865 to read in a memory dump).
Georg Brandl7cba5fd2013-09-25 09:04:23 +02001866p[S]
Tim Petersdf099f52013-09-19 21:06:37 -05001867 API ID. See PEP 445. This is a character, but seems undocumented.
1868p[S+1: 2*S]
Tim Petersf6fb5012002-04-12 07:38:53 +00001869 Copies of FORBIDDENBYTE. Used to catch under- writes and reads.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001870p[2*S: 2*S+n]
Tim Petersf6fb5012002-04-12 07:38:53 +00001871 The requested memory, filled with copies of CLEANBYTE.
Tim Petersddea2082002-03-23 10:03:50 +00001872 Used to catch reference to uninitialized memory.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001873 &p[2*S] is returned. Note that this is 8-byte aligned if pymalloc
Tim Petersddea2082002-03-23 10:03:50 +00001874 handled the request itself.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001875p[2*S+n: 2*S+n+S]
Tim Petersf6fb5012002-04-12 07:38:53 +00001876 Copies of FORBIDDENBYTE. Used to catch over- writes and reads.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001877p[2*S+n+S: 2*S+n+2*S]
Victor Stinner0507bf52013-07-07 02:05:46 +02001878 A serial number, incremented by 1 on each call to _PyMem_DebugMalloc
1879 and _PyMem_DebugRealloc.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001880 This is a big-endian size_t.
Tim Petersddea2082002-03-23 10:03:50 +00001881 If "bad memory" is detected later, the serial number gives an
1882 excellent way to set a breakpoint on the next run, to capture the
1883 instant at which this block was passed out.
1884*/
1885
Victor Stinner0507bf52013-07-07 02:05:46 +02001886static void *
Victor Stinnerc4aec362016-03-14 22:26:53 +01001887_PyMem_DebugRawAlloc(int use_calloc, void *ctx, size_t nbytes)
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00001888{
Victor Stinner0507bf52013-07-07 02:05:46 +02001889 debug_alloc_api_t *api = (debug_alloc_api_t *)ctx;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001890 uchar *p; /* base address of malloc'ed block */
1891 uchar *tail; /* p + 2*SST + nbytes == pointer to tail pad bytes */
1892 size_t total; /* nbytes + 4*SST */
Tim Petersddea2082002-03-23 10:03:50 +00001893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001894 bumpserialno();
1895 total = nbytes + 4*SST;
Antoine Pitroucc231542014-11-02 18:40:09 +01001896 if (nbytes > PY_SSIZE_T_MAX - 4*SST)
1897 /* overflow: can't represent total as a Py_ssize_t */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001898 return NULL;
Tim Petersddea2082002-03-23 10:03:50 +00001899
Victor Stinnerdb067af2014-05-02 22:31:14 +02001900 if (use_calloc)
1901 p = (uchar *)api->alloc.calloc(api->alloc.ctx, 1, total);
1902 else
1903 p = (uchar *)api->alloc.malloc(api->alloc.ctx, total);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001904 if (p == NULL)
1905 return NULL;
Tim Petersddea2082002-03-23 10:03:50 +00001906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001907 /* at p, write size (SST bytes), id (1 byte), pad (SST-1 bytes) */
1908 write_size_t(p, nbytes);
Victor Stinner0507bf52013-07-07 02:05:46 +02001909 p[SST] = (uchar)api->api_id;
1910 memset(p + SST + 1, FORBIDDENBYTE, SST-1);
Tim Petersddea2082002-03-23 10:03:50 +00001911
Victor Stinnerdb067af2014-05-02 22:31:14 +02001912 if (nbytes > 0 && !use_calloc)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001913 memset(p + 2*SST, CLEANBYTE, nbytes);
Tim Petersddea2082002-03-23 10:03:50 +00001914
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001915 /* at tail, write pad (SST bytes) and serialno (SST bytes) */
1916 tail = p + 2*SST + nbytes;
1917 memset(tail, FORBIDDENBYTE, SST);
1918 write_size_t(tail + SST, serialno);
Tim Petersddea2082002-03-23 10:03:50 +00001919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001920 return p + 2*SST;
Tim Petersddea2082002-03-23 10:03:50 +00001921}
1922
Victor Stinnerdb067af2014-05-02 22:31:14 +02001923static void *
Victor Stinnerc4aec362016-03-14 22:26:53 +01001924_PyMem_DebugRawMalloc(void *ctx, size_t nbytes)
Victor Stinnerdb067af2014-05-02 22:31:14 +02001925{
Victor Stinnerc4aec362016-03-14 22:26:53 +01001926 return _PyMem_DebugRawAlloc(0, ctx, nbytes);
Victor Stinnerdb067af2014-05-02 22:31:14 +02001927}
1928
1929static void *
Victor Stinnerc4aec362016-03-14 22:26:53 +01001930_PyMem_DebugRawCalloc(void *ctx, size_t nelem, size_t elsize)
Victor Stinnerdb067af2014-05-02 22:31:14 +02001931{
1932 size_t nbytes;
1933 assert(elsize == 0 || nelem <= PY_SSIZE_T_MAX / elsize);
1934 nbytes = nelem * elsize;
Victor Stinnerc4aec362016-03-14 22:26:53 +01001935 return _PyMem_DebugRawAlloc(1, ctx, nbytes);
Victor Stinnerdb067af2014-05-02 22:31:14 +02001936}
1937
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001938/* 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 +00001939 particular, that the FORBIDDENBYTEs with the api ID are still intact).
Tim Petersf6fb5012002-04-12 07:38:53 +00001940 Then fills the original bytes with DEADBYTE.
Tim Petersddea2082002-03-23 10:03:50 +00001941 Then calls the underlying free.
1942*/
Victor Stinner0507bf52013-07-07 02:05:46 +02001943static void
Victor Stinnerc4aec362016-03-14 22:26:53 +01001944_PyMem_DebugRawFree(void *ctx, void *p)
Tim Petersddea2082002-03-23 10:03:50 +00001945{
Victor Stinner0507bf52013-07-07 02:05:46 +02001946 debug_alloc_api_t *api = (debug_alloc_api_t *)ctx;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001947 uchar *q = (uchar *)p - 2*SST; /* address returned from malloc */
1948 size_t nbytes;
Tim Petersddea2082002-03-23 10:03:50 +00001949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001950 if (p == NULL)
1951 return;
Victor Stinner0507bf52013-07-07 02:05:46 +02001952 _PyMem_DebugCheckAddress(api->api_id, p);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001953 nbytes = read_size_t(q);
1954 nbytes += 4*SST;
1955 if (nbytes > 0)
1956 memset(q, DEADBYTE, nbytes);
Victor Stinner0507bf52013-07-07 02:05:46 +02001957 api->alloc.free(api->alloc.ctx, q);
Tim Petersddea2082002-03-23 10:03:50 +00001958}
1959
Victor Stinner0507bf52013-07-07 02:05:46 +02001960static void *
Victor Stinnerc4aec362016-03-14 22:26:53 +01001961_PyMem_DebugRawRealloc(void *ctx, void *p, size_t nbytes)
Tim Petersddea2082002-03-23 10:03:50 +00001962{
Victor Stinner0507bf52013-07-07 02:05:46 +02001963 debug_alloc_api_t *api = (debug_alloc_api_t *)ctx;
Victor Stinnerc4266362013-07-09 00:44:43 +02001964 uchar *q = (uchar *)p, *oldq;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001965 uchar *tail;
1966 size_t total; /* nbytes + 4*SST */
1967 size_t original_nbytes;
1968 int i;
Tim Petersddea2082002-03-23 10:03:50 +00001969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001970 if (p == NULL)
Victor Stinnerc4aec362016-03-14 22:26:53 +01001971 return _PyMem_DebugRawAlloc(0, ctx, nbytes);
Tim Petersddea2082002-03-23 10:03:50 +00001972
Victor Stinner0507bf52013-07-07 02:05:46 +02001973 _PyMem_DebugCheckAddress(api->api_id, p);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001974 bumpserialno();
1975 original_nbytes = read_size_t(q - 2*SST);
1976 total = nbytes + 4*SST;
Antoine Pitroucc231542014-11-02 18:40:09 +01001977 if (nbytes > PY_SSIZE_T_MAX - 4*SST)
1978 /* overflow: can't represent total as a Py_ssize_t */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001979 return NULL;
Tim Petersddea2082002-03-23 10:03:50 +00001980
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001981 /* Resize and add decorations. We may get a new pointer here, in which
1982 * case we didn't get the chance to mark the old memory with DEADBYTE,
1983 * but we live with that.
1984 */
Victor Stinnerc4266362013-07-09 00:44:43 +02001985 oldq = q;
Victor Stinner0507bf52013-07-07 02:05:46 +02001986 q = (uchar *)api->alloc.realloc(api->alloc.ctx, q - 2*SST, total);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001987 if (q == NULL)
1988 return NULL;
Tim Peters85cc1c42002-04-12 08:52:50 +00001989
Victor Stinnerc4266362013-07-09 00:44:43 +02001990 if (q == oldq && nbytes < original_nbytes) {
1991 /* shrinking: mark old extra memory dead */
1992 memset(q + nbytes, DEADBYTE, original_nbytes - nbytes);
1993 }
1994
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001995 write_size_t(q, nbytes);
Victor Stinner0507bf52013-07-07 02:05:46 +02001996 assert(q[SST] == (uchar)api->api_id);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001997 for (i = 1; i < SST; ++i)
1998 assert(q[SST + i] == FORBIDDENBYTE);
1999 q += 2*SST;
Victor Stinnerc4266362013-07-09 00:44:43 +02002000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002001 tail = q + nbytes;
2002 memset(tail, FORBIDDENBYTE, SST);
2003 write_size_t(tail + SST, serialno);
Tim Peters85cc1c42002-04-12 08:52:50 +00002004
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002005 if (nbytes > original_nbytes) {
2006 /* growing: mark new extra memory clean */
2007 memset(q + original_nbytes, CLEANBYTE,
Stefan Krah735bb122010-11-26 10:54:09 +00002008 nbytes - original_nbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002009 }
Tim Peters85cc1c42002-04-12 08:52:50 +00002010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002011 return q;
Tim Petersddea2082002-03-23 10:03:50 +00002012}
2013
Victor Stinnerc4aec362016-03-14 22:26:53 +01002014static void
2015_PyMem_DebugCheckGIL(void)
2016{
2017#ifdef WITH_THREAD
2018 if (!PyGILState_Check())
2019 Py_FatalError("Python memory allocator called "
2020 "without holding the GIL");
2021#endif
2022}
2023
2024static void *
2025_PyMem_DebugMalloc(void *ctx, size_t nbytes)
2026{
2027 _PyMem_DebugCheckGIL();
2028 return _PyMem_DebugRawMalloc(ctx, nbytes);
2029}
2030
2031static void *
2032_PyMem_DebugCalloc(void *ctx, size_t nelem, size_t elsize)
2033{
2034 _PyMem_DebugCheckGIL();
2035 return _PyMem_DebugRawCalloc(ctx, nelem, elsize);
2036}
2037
2038static void
2039_PyMem_DebugFree(void *ctx, void *ptr)
2040{
2041 _PyMem_DebugCheckGIL();
Victor Stinner0aed3a42016-03-23 11:30:43 +01002042 _PyMem_DebugRawFree(ctx, ptr);
Victor Stinnerc4aec362016-03-14 22:26:53 +01002043}
2044
2045static void *
2046_PyMem_DebugRealloc(void *ctx, void *ptr, size_t nbytes)
2047{
2048 _PyMem_DebugCheckGIL();
2049 return _PyMem_DebugRawRealloc(ctx, ptr, nbytes);
2050}
2051
Tim Peters7ccfadf2002-04-01 06:04:21 +00002052/* Check the forbidden bytes on both ends of the memory allocated for p.
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00002053 * If anything is wrong, print info to stderr via _PyObject_DebugDumpAddress,
Tim Peters7ccfadf2002-04-01 06:04:21 +00002054 * and call Py_FatalError to kill the program.
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00002055 * The API id, is also checked.
Tim Peters7ccfadf2002-04-01 06:04:21 +00002056 */
Victor Stinner0507bf52013-07-07 02:05:46 +02002057static void
2058_PyMem_DebugCheckAddress(char api, const void *p)
Tim Petersddea2082002-03-23 10:03:50 +00002059{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002060 const uchar *q = (const uchar *)p;
2061 char msgbuf[64];
2062 char *msg;
2063 size_t nbytes;
2064 const uchar *tail;
2065 int i;
2066 char id;
Tim Petersddea2082002-03-23 10:03:50 +00002067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002068 if (p == NULL) {
2069 msg = "didn't expect a NULL pointer";
2070 goto error;
2071 }
Tim Petersddea2082002-03-23 10:03:50 +00002072
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002073 /* Check the API id */
2074 id = (char)q[-SST];
2075 if (id != api) {
2076 msg = msgbuf;
2077 snprintf(msg, sizeof(msgbuf), "bad ID: Allocated using API '%c', verified using API '%c'", id, api);
2078 msgbuf[sizeof(msgbuf)-1] = 0;
2079 goto error;
2080 }
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00002081
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002082 /* Check the stuff at the start of p first: if there's underwrite
2083 * corruption, the number-of-bytes field may be nuts, and checking
2084 * the tail could lead to a segfault then.
2085 */
2086 for (i = SST-1; i >= 1; --i) {
2087 if (*(q-i) != FORBIDDENBYTE) {
2088 msg = "bad leading pad byte";
2089 goto error;
2090 }
2091 }
Tim Petersddea2082002-03-23 10:03:50 +00002092
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002093 nbytes = read_size_t(q - 2*SST);
2094 tail = q + nbytes;
2095 for (i = 0; i < SST; ++i) {
2096 if (tail[i] != FORBIDDENBYTE) {
2097 msg = "bad trailing pad byte";
2098 goto error;
2099 }
2100 }
Tim Petersddea2082002-03-23 10:03:50 +00002101
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002102 return;
Tim Petersd1139e02002-03-28 07:32:11 +00002103
2104error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002105 _PyObject_DebugDumpAddress(p);
2106 Py_FatalError(msg);
Tim Petersddea2082002-03-23 10:03:50 +00002107}
2108
Tim Peters7ccfadf2002-04-01 06:04:21 +00002109/* Display info to stderr about the memory block at p. */
Victor Stinner0507bf52013-07-07 02:05:46 +02002110static void
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00002111_PyObject_DebugDumpAddress(const void *p)
Tim Petersddea2082002-03-23 10:03:50 +00002112{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002113 const uchar *q = (const uchar *)p;
2114 const uchar *tail;
2115 size_t nbytes, serial;
2116 int i;
2117 int ok;
2118 char id;
Tim Petersddea2082002-03-23 10:03:50 +00002119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002120 fprintf(stderr, "Debug memory block at address p=%p:", p);
2121 if (p == NULL) {
2122 fprintf(stderr, "\n");
2123 return;
2124 }
2125 id = (char)q[-SST];
2126 fprintf(stderr, " API '%c'\n", id);
Tim Petersddea2082002-03-23 10:03:50 +00002127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002128 nbytes = read_size_t(q - 2*SST);
2129 fprintf(stderr, " %" PY_FORMAT_SIZE_T "u bytes originally "
2130 "requested\n", nbytes);
Tim Petersddea2082002-03-23 10:03:50 +00002131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002132 /* In case this is nuts, check the leading pad bytes first. */
2133 fprintf(stderr, " The %d pad bytes at p-%d are ", SST-1, SST-1);
2134 ok = 1;
2135 for (i = 1; i <= SST-1; ++i) {
2136 if (*(q-i) != FORBIDDENBYTE) {
2137 ok = 0;
2138 break;
2139 }
2140 }
2141 if (ok)
2142 fputs("FORBIDDENBYTE, as expected.\n", stderr);
2143 else {
2144 fprintf(stderr, "not all FORBIDDENBYTE (0x%02x):\n",
2145 FORBIDDENBYTE);
2146 for (i = SST-1; i >= 1; --i) {
2147 const uchar byte = *(q-i);
2148 fprintf(stderr, " at p-%d: 0x%02x", i, byte);
2149 if (byte != FORBIDDENBYTE)
2150 fputs(" *** OUCH", stderr);
2151 fputc('\n', stderr);
2152 }
Tim Peters449b5a82002-04-28 06:14:45 +00002153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002154 fputs(" Because memory is corrupted at the start, the "
2155 "count of bytes requested\n"
2156 " may be bogus, and checking the trailing pad "
2157 "bytes may segfault.\n", stderr);
2158 }
Tim Petersddea2082002-03-23 10:03:50 +00002159
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002160 tail = q + nbytes;
2161 fprintf(stderr, " The %d pad bytes at tail=%p are ", SST, tail);
2162 ok = 1;
2163 for (i = 0; i < SST; ++i) {
2164 if (tail[i] != FORBIDDENBYTE) {
2165 ok = 0;
2166 break;
2167 }
2168 }
2169 if (ok)
2170 fputs("FORBIDDENBYTE, as expected.\n", stderr);
2171 else {
2172 fprintf(stderr, "not all FORBIDDENBYTE (0x%02x):\n",
Stefan Krah735bb122010-11-26 10:54:09 +00002173 FORBIDDENBYTE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002174 for (i = 0; i < SST; ++i) {
2175 const uchar byte = tail[i];
2176 fprintf(stderr, " at tail+%d: 0x%02x",
Stefan Krah735bb122010-11-26 10:54:09 +00002177 i, byte);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002178 if (byte != FORBIDDENBYTE)
2179 fputs(" *** OUCH", stderr);
2180 fputc('\n', stderr);
2181 }
2182 }
Tim Petersddea2082002-03-23 10:03:50 +00002183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002184 serial = read_size_t(tail + SST);
2185 fprintf(stderr, " The block was made by call #%" PY_FORMAT_SIZE_T
2186 "u to debug malloc/realloc.\n", serial);
Tim Petersddea2082002-03-23 10:03:50 +00002187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002188 if (nbytes > 0) {
2189 i = 0;
2190 fputs(" Data at p:", stderr);
2191 /* print up to 8 bytes at the start */
2192 while (q < tail && i < 8) {
2193 fprintf(stderr, " %02x", *q);
2194 ++i;
2195 ++q;
2196 }
2197 /* and up to 8 at the end */
2198 if (q < tail) {
2199 if (tail - q > 8) {
2200 fputs(" ...", stderr);
2201 q = tail - 8;
2202 }
2203 while (q < tail) {
2204 fprintf(stderr, " %02x", *q);
2205 ++q;
2206 }
2207 }
2208 fputc('\n', stderr);
2209 }
Victor Stinner0611c262016-03-15 22:22:13 +01002210 fputc('\n', stderr);
2211
2212 fflush(stderr);
2213 _PyMem_DumpTraceback(fileno(stderr), p);
Tim Petersddea2082002-03-23 10:03:50 +00002214}
2215
David Malcolm49526f42012-06-22 14:55:41 -04002216
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00002217static size_t
David Malcolm49526f42012-06-22 14:55:41 -04002218printone(FILE *out, const char* msg, size_t value)
Tim Peters16bcb6b2002-04-05 05:45:31 +00002219{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002220 int i, k;
2221 char buf[100];
2222 size_t origvalue = value;
Tim Peters16bcb6b2002-04-05 05:45:31 +00002223
David Malcolm49526f42012-06-22 14:55:41 -04002224 fputs(msg, out);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002225 for (i = (int)strlen(msg); i < 35; ++i)
David Malcolm49526f42012-06-22 14:55:41 -04002226 fputc(' ', out);
2227 fputc('=', out);
Tim Peters49f26812002-04-06 01:45:35 +00002228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002229 /* Write the value with commas. */
2230 i = 22;
2231 buf[i--] = '\0';
2232 buf[i--] = '\n';
2233 k = 3;
2234 do {
2235 size_t nextvalue = value / 10;
Benjamin Peterson2dba1ee2013-02-20 16:54:30 -05002236 unsigned int digit = (unsigned int)(value - nextvalue * 10);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002237 value = nextvalue;
2238 buf[i--] = (char)(digit + '0');
2239 --k;
2240 if (k == 0 && value && i >= 0) {
2241 k = 3;
2242 buf[i--] = ',';
2243 }
2244 } while (value && i >= 0);
Tim Peters49f26812002-04-06 01:45:35 +00002245
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002246 while (i >= 0)
2247 buf[i--] = ' ';
David Malcolm49526f42012-06-22 14:55:41 -04002248 fputs(buf, out);
Tim Peters49f26812002-04-06 01:45:35 +00002249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002250 return origvalue;
Tim Peters16bcb6b2002-04-05 05:45:31 +00002251}
2252
David Malcolm49526f42012-06-22 14:55:41 -04002253void
2254_PyDebugAllocatorStats(FILE *out,
2255 const char *block_name, int num_blocks, size_t sizeof_block)
2256{
2257 char buf1[128];
2258 char buf2[128];
2259 PyOS_snprintf(buf1, sizeof(buf1),
Tim Peterseaa3bcc2013-09-05 22:57:04 -05002260 "%d %ss * %" PY_FORMAT_SIZE_T "d bytes each",
David Malcolm49526f42012-06-22 14:55:41 -04002261 num_blocks, block_name, sizeof_block);
2262 PyOS_snprintf(buf2, sizeof(buf2),
2263 "%48s ", buf1);
2264 (void)printone(out, buf2, num_blocks * sizeof_block);
2265}
2266
Victor Stinner34be8072016-03-14 12:04:26 +01002267
David Malcolm49526f42012-06-22 14:55:41 -04002268#ifdef WITH_PYMALLOC
2269
Victor Stinner34be8072016-03-14 12:04:26 +01002270#ifdef Py_DEBUG
2271/* Is target in the list? The list is traversed via the nextpool pointers.
2272 * The list may be NULL-terminated, or circular. Return 1 if target is in
2273 * list, else 0.
2274 */
2275static int
2276pool_is_in_list(const poolp target, poolp list)
2277{
2278 poolp origlist = list;
2279 assert(target != NULL);
2280 if (list == NULL)
2281 return 0;
2282 do {
2283 if (target == list)
2284 return 1;
2285 list = list->nextpool;
2286 } while (list != NULL && list != origlist);
2287 return 0;
2288}
2289#endif
2290
David Malcolm49526f42012-06-22 14:55:41 -04002291/* Print summary info to "out" about the state of pymalloc's structures.
Tim Peters08d82152002-04-18 22:25:03 +00002292 * In Py_DEBUG mode, also perform some expensive internal consistency
2293 * checks.
2294 */
Tim Peters7ccfadf2002-04-01 06:04:21 +00002295void
David Malcolm49526f42012-06-22 14:55:41 -04002296_PyObject_DebugMallocStats(FILE *out)
Tim Peters7ccfadf2002-04-01 06:04:21 +00002297{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002298 uint i;
2299 const uint numclasses = SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT;
2300 /* # of pools, allocated blocks, and free blocks per class index */
2301 size_t numpools[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT];
2302 size_t numblocks[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT];
2303 size_t numfreeblocks[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT];
2304 /* total # of allocated bytes in used and full pools */
2305 size_t allocated_bytes = 0;
2306 /* total # of available bytes in used pools */
2307 size_t available_bytes = 0;
2308 /* # of free pools + pools not yet carved out of current arena */
2309 uint numfreepools = 0;
2310 /* # of bytes for arena alignment padding */
2311 size_t arena_alignment = 0;
2312 /* # of bytes in used and full pools used for pool_headers */
2313 size_t pool_header_bytes = 0;
2314 /* # of bytes in used and full pools wasted due to quantization,
2315 * i.e. the necessarily leftover space at the ends of used and
2316 * full pools.
2317 */
2318 size_t quantization = 0;
2319 /* # of arenas actually allocated. */
2320 size_t narenas = 0;
2321 /* running total -- should equal narenas * ARENA_SIZE */
2322 size_t total;
2323 char buf[128];
Tim Peters7ccfadf2002-04-01 06:04:21 +00002324
David Malcolm49526f42012-06-22 14:55:41 -04002325 fprintf(out, "Small block threshold = %d, in %u size classes.\n",
Stefan Krah735bb122010-11-26 10:54:09 +00002326 SMALL_REQUEST_THRESHOLD, numclasses);
Tim Peters7ccfadf2002-04-01 06:04:21 +00002327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002328 for (i = 0; i < numclasses; ++i)
2329 numpools[i] = numblocks[i] = numfreeblocks[i] = 0;
Tim Peters7ccfadf2002-04-01 06:04:21 +00002330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002331 /* Because full pools aren't linked to from anything, it's easiest
2332 * to march over all the arenas. If we're lucky, most of the memory
2333 * will be living in full pools -- would be a shame to miss them.
2334 */
2335 for (i = 0; i < maxarenas; ++i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002336 uint j;
2337 uptr base = arenas[i].address;
Thomas Woutersa9773292006-04-21 09:43:23 +00002338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002339 /* Skip arenas which are not allocated. */
2340 if (arenas[i].address == (uptr)NULL)
2341 continue;
2342 narenas += 1;
Thomas Woutersa9773292006-04-21 09:43:23 +00002343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002344 numfreepools += arenas[i].nfreepools;
Tim Peters7ccfadf2002-04-01 06:04:21 +00002345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002346 /* round up to pool alignment */
2347 if (base & (uptr)POOL_SIZE_MASK) {
2348 arena_alignment += POOL_SIZE;
2349 base &= ~(uptr)POOL_SIZE_MASK;
2350 base += POOL_SIZE;
2351 }
Tim Peters7ccfadf2002-04-01 06:04:21 +00002352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002353 /* visit every pool in the arena */
2354 assert(base <= (uptr) arenas[i].pool_address);
2355 for (j = 0;
2356 base < (uptr) arenas[i].pool_address;
2357 ++j, base += POOL_SIZE) {
2358 poolp p = (poolp)base;
2359 const uint sz = p->szidx;
2360 uint freeblocks;
Tim Peters08d82152002-04-18 22:25:03 +00002361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002362 if (p->ref.count == 0) {
2363 /* currently unused */
Victor Stinner34be8072016-03-14 12:04:26 +01002364#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002365 assert(pool_is_in_list(p, arenas[i].freepools));
Victor Stinner34be8072016-03-14 12:04:26 +01002366#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002367 continue;
2368 }
2369 ++numpools[sz];
2370 numblocks[sz] += p->ref.count;
2371 freeblocks = NUMBLOCKS(sz) - p->ref.count;
2372 numfreeblocks[sz] += freeblocks;
Tim Peters08d82152002-04-18 22:25:03 +00002373#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002374 if (freeblocks > 0)
2375 assert(pool_is_in_list(p, usedpools[sz + sz]));
Tim Peters08d82152002-04-18 22:25:03 +00002376#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002377 }
2378 }
2379 assert(narenas == narenas_currently_allocated);
Tim Peters7ccfadf2002-04-01 06:04:21 +00002380
David Malcolm49526f42012-06-22 14:55:41 -04002381 fputc('\n', out);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002382 fputs("class size num pools blocks in use avail blocks\n"
2383 "----- ---- --------- ------------- ------------\n",
David Malcolm49526f42012-06-22 14:55:41 -04002384 out);
Tim Peters7ccfadf2002-04-01 06:04:21 +00002385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002386 for (i = 0; i < numclasses; ++i) {
2387 size_t p = numpools[i];
2388 size_t b = numblocks[i];
2389 size_t f = numfreeblocks[i];
2390 uint size = INDEX2SIZE(i);
2391 if (p == 0) {
2392 assert(b == 0 && f == 0);
2393 continue;
2394 }
David Malcolm49526f42012-06-22 14:55:41 -04002395 fprintf(out, "%5u %6u "
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002396 "%11" PY_FORMAT_SIZE_T "u "
2397 "%15" PY_FORMAT_SIZE_T "u "
2398 "%13" PY_FORMAT_SIZE_T "u\n",
Stefan Krah735bb122010-11-26 10:54:09 +00002399 i, size, p, b, f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002400 allocated_bytes += b * size;
2401 available_bytes += f * size;
2402 pool_header_bytes += p * POOL_OVERHEAD;
2403 quantization += p * ((POOL_SIZE - POOL_OVERHEAD) % size);
2404 }
David Malcolm49526f42012-06-22 14:55:41 -04002405 fputc('\n', out);
Victor Stinner34be8072016-03-14 12:04:26 +01002406 if (_PyMem_DebugEnabled())
2407 (void)printone(out, "# times object malloc called", serialno);
David Malcolm49526f42012-06-22 14:55:41 -04002408 (void)printone(out, "# arenas allocated total", ntimes_arena_allocated);
2409 (void)printone(out, "# arenas reclaimed", ntimes_arena_allocated - narenas);
2410 (void)printone(out, "# arenas highwater mark", narenas_highwater);
2411 (void)printone(out, "# arenas allocated current", narenas);
Thomas Woutersa9773292006-04-21 09:43:23 +00002412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002413 PyOS_snprintf(buf, sizeof(buf),
2414 "%" PY_FORMAT_SIZE_T "u arenas * %d bytes/arena",
2415 narenas, ARENA_SIZE);
David Malcolm49526f42012-06-22 14:55:41 -04002416 (void)printone(out, buf, narenas * ARENA_SIZE);
Tim Peters16bcb6b2002-04-05 05:45:31 +00002417
David Malcolm49526f42012-06-22 14:55:41 -04002418 fputc('\n', out);
Tim Peters16bcb6b2002-04-05 05:45:31 +00002419
David Malcolm49526f42012-06-22 14:55:41 -04002420 total = printone(out, "# bytes in allocated blocks", allocated_bytes);
2421 total += printone(out, "# bytes in available blocks", available_bytes);
Tim Peters49f26812002-04-06 01:45:35 +00002422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002423 PyOS_snprintf(buf, sizeof(buf),
2424 "%u unused pools * %d bytes", numfreepools, POOL_SIZE);
David Malcolm49526f42012-06-22 14:55:41 -04002425 total += printone(out, buf, (size_t)numfreepools * POOL_SIZE);
Tim Peters16bcb6b2002-04-05 05:45:31 +00002426
David Malcolm49526f42012-06-22 14:55:41 -04002427 total += printone(out, "# bytes lost to pool headers", pool_header_bytes);
2428 total += printone(out, "# bytes lost to quantization", quantization);
2429 total += printone(out, "# bytes lost to arena alignment", arena_alignment);
2430 (void)printone(out, "Total", total);
Tim Peters7ccfadf2002-04-01 06:04:21 +00002431}
2432
David Malcolm49526f42012-06-22 14:55:41 -04002433#endif /* #ifdef WITH_PYMALLOC */
Neal Norwitz7eb3c912004-06-06 19:20:22 +00002434
Victor Stinner34be8072016-03-14 12:04:26 +01002435
Neal Norwitz7eb3c912004-06-06 19:20:22 +00002436#ifdef Py_USING_MEMORY_DEBUGGER
Thomas Woutersa9773292006-04-21 09:43:23 +00002437/* Make this function last so gcc won't inline it since the definition is
2438 * after the reference.
2439 */
Neal Norwitz7eb3c912004-06-06 19:20:22 +00002440int
2441Py_ADDRESS_IN_RANGE(void *P, poolp pool)
2442{
Antoine Pitroub7fb2e22011-01-07 21:43:59 +00002443 uint arenaindex_temp = pool->arenaindex;
2444
2445 return arenaindex_temp < maxarenas &&
2446 (uptr)P - arenas[arenaindex_temp].address < (uptr)ARENA_SIZE &&
2447 arenas[arenaindex_temp].address != 0;
Neal Norwitz7eb3c912004-06-06 19:20:22 +00002448}
2449#endif