blob: 3f95133a74e5b81567f27196bf0fe2fb7f7b7350 [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 Stinner15932592016-04-22 18:52:22 +0200169#define PYMEM_FUNCS PYOBJ_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 Stinner15932592016-04-22 18:52:22 +0200201 &_PyMem_Debug.mem, PYDBG_FUNCS
Victor Stinner0507bf52013-07-07 02:05:46 +0200202#else
Victor Stinner15932592016-04-22 18:52:22 +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 {
Victor Stinner15932592016-04-22 18:52:22 +0200255 PyMemAllocatorEx raw_alloc = {NULL, PYRAW_FUNCS};
256 PyMemAllocatorEx mem_alloc = {NULL, PYMEM_FUNCS};
Victor Stinner34be8072016-03-14 12:04:26 +0100257 PyMemAllocatorEx obj_alloc = {NULL, PYOBJ_FUNCS};
258
Victor Stinner15932592016-04-22 18:52:22 +0200259 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &raw_alloc);
260 PyMem_SetAllocator(PYMEM_DOMAIN_MEM, &mem_alloc);
Victor Stinner34be8072016-03-14 12:04:26 +0100261 PyMem_SetAllocator(PYMEM_DOMAIN_OBJ, &obj_alloc);
262
263 if (strcmp(opt, "pymalloc_debug") == 0)
264 PyMem_SetupDebugHooks();
265 }
266#endif
267 else {
268 /* unknown allocator */
269 return -1;
270 }
271 return 0;
272}
273
Victor Stinner0507bf52013-07-07 02:05:46 +0200274#undef PYRAW_FUNCS
Victor Stinner6cf185d2013-10-10 15:58:42 +0200275#undef PYMEM_FUNCS
276#undef PYOBJ_FUNCS
Victor Stinnerc4aec362016-03-14 22:26:53 +0100277#undef PYRAWDBG_FUNCS
Victor Stinner6cf185d2013-10-10 15:58:42 +0200278#undef PYDBG_FUNCS
Victor Stinner0507bf52013-07-07 02:05:46 +0200279
280static PyObjectArenaAllocator _PyObject_Arena = {NULL,
281#ifdef MS_WINDOWS
282 _PyObject_ArenaVirtualAlloc, _PyObject_ArenaVirtualFree
283#elif defined(ARENAS_USE_MMAP)
284 _PyObject_ArenaMmap, _PyObject_ArenaMunmap
285#else
286 _PyObject_ArenaMalloc, _PyObject_ArenaFree
287#endif
288 };
289
Victor Stinner0621e0e2016-04-19 17:02:55 +0200290#ifdef WITH_PYMALLOC
Victor Stinner34be8072016-03-14 12:04:26 +0100291static int
292_PyMem_DebugEnabled(void)
293{
294 return (_PyObject.malloc == _PyMem_DebugMalloc);
295}
296
Victor Stinner34be8072016-03-14 12:04:26 +0100297int
298_PyMem_PymallocEnabled(void)
299{
300 if (_PyMem_DebugEnabled()) {
301 return (_PyMem_Debug.obj.alloc.malloc == _PyObject_Malloc);
302 }
303 else {
304 return (_PyObject.malloc == _PyObject_Malloc);
305 }
306}
307#endif
308
Victor Stinner0507bf52013-07-07 02:05:46 +0200309void
310PyMem_SetupDebugHooks(void)
311{
Victor Stinnerd8f0d922014-06-02 21:57:10 +0200312 PyMemAllocatorEx alloc;
Victor Stinner0507bf52013-07-07 02:05:46 +0200313
Victor Stinnerc4aec362016-03-14 22:26:53 +0100314 alloc.malloc = _PyMem_DebugRawMalloc;
315 alloc.calloc = _PyMem_DebugRawCalloc;
316 alloc.realloc = _PyMem_DebugRawRealloc;
317 alloc.free = _PyMem_DebugRawFree;
Victor Stinner34be8072016-03-14 12:04:26 +0100318
Victor Stinnerc4aec362016-03-14 22:26:53 +0100319 if (_PyMem_Raw.malloc != _PyMem_DebugRawMalloc) {
Victor Stinner0507bf52013-07-07 02:05:46 +0200320 alloc.ctx = &_PyMem_Debug.raw;
321 PyMem_GetAllocator(PYMEM_DOMAIN_RAW, &_PyMem_Debug.raw.alloc);
322 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &alloc);
323 }
324
Victor Stinnerc4aec362016-03-14 22:26:53 +0100325 alloc.malloc = _PyMem_DebugMalloc;
326 alloc.calloc = _PyMem_DebugCalloc;
327 alloc.realloc = _PyMem_DebugRealloc;
328 alloc.free = _PyMem_DebugFree;
329
Victor Stinnerad524372016-03-16 12:12:53 +0100330 if (_PyMem.malloc != _PyMem_DebugMalloc) {
331 alloc.ctx = &_PyMem_Debug.mem;
332 PyMem_GetAllocator(PYMEM_DOMAIN_MEM, &_PyMem_Debug.mem.alloc);
333 PyMem_SetAllocator(PYMEM_DOMAIN_MEM, &alloc);
334 }
335
Victor Stinner0507bf52013-07-07 02:05:46 +0200336 if (_PyObject.malloc != _PyMem_DebugMalloc) {
337 alloc.ctx = &_PyMem_Debug.obj;
338 PyMem_GetAllocator(PYMEM_DOMAIN_OBJ, &_PyMem_Debug.obj.alloc);
339 PyMem_SetAllocator(PYMEM_DOMAIN_OBJ, &alloc);
340 }
Victor Stinner0507bf52013-07-07 02:05:46 +0200341}
342
343void
Victor Stinnerd8f0d922014-06-02 21:57:10 +0200344PyMem_GetAllocator(PyMemAllocatorDomain domain, PyMemAllocatorEx *allocator)
Victor Stinner0507bf52013-07-07 02:05:46 +0200345{
346 switch(domain)
347 {
348 case PYMEM_DOMAIN_RAW: *allocator = _PyMem_Raw; break;
349 case PYMEM_DOMAIN_MEM: *allocator = _PyMem; break;
350 case PYMEM_DOMAIN_OBJ: *allocator = _PyObject; break;
351 default:
Victor Stinnerdb067af2014-05-02 22:31:14 +0200352 /* unknown domain: set all attributes to NULL */
Victor Stinner0507bf52013-07-07 02:05:46 +0200353 allocator->ctx = NULL;
354 allocator->malloc = NULL;
Victor Stinnerdb067af2014-05-02 22:31:14 +0200355 allocator->calloc = NULL;
Victor Stinner0507bf52013-07-07 02:05:46 +0200356 allocator->realloc = NULL;
357 allocator->free = NULL;
358 }
359}
360
361void
Victor Stinnerd8f0d922014-06-02 21:57:10 +0200362PyMem_SetAllocator(PyMemAllocatorDomain domain, PyMemAllocatorEx *allocator)
Victor Stinner0507bf52013-07-07 02:05:46 +0200363{
364 switch(domain)
365 {
366 case PYMEM_DOMAIN_RAW: _PyMem_Raw = *allocator; break;
367 case PYMEM_DOMAIN_MEM: _PyMem = *allocator; break;
368 case PYMEM_DOMAIN_OBJ: _PyObject = *allocator; break;
369 /* ignore unknown domain */
370 }
Victor Stinner0507bf52013-07-07 02:05:46 +0200371}
372
373void
374PyObject_GetArenaAllocator(PyObjectArenaAllocator *allocator)
375{
376 *allocator = _PyObject_Arena;
377}
378
379void
380PyObject_SetArenaAllocator(PyObjectArenaAllocator *allocator)
381{
382 _PyObject_Arena = *allocator;
383}
384
385void *
386PyMem_RawMalloc(size_t size)
387{
388 /*
389 * Limit ourselves to PY_SSIZE_T_MAX bytes to prevent security holes.
390 * Most python internals blindly use a signed Py_ssize_t to track
391 * things without checking for overflows or negatives.
392 * As size_t is unsigned, checking for size < 0 is not required.
393 */
394 if (size > (size_t)PY_SSIZE_T_MAX)
395 return NULL;
Victor Stinner0507bf52013-07-07 02:05:46 +0200396 return _PyMem_Raw.malloc(_PyMem_Raw.ctx, size);
397}
398
Victor Stinnerdb067af2014-05-02 22:31:14 +0200399void *
400PyMem_RawCalloc(size_t nelem, size_t elsize)
401{
402 /* see PyMem_RawMalloc() */
403 if (elsize != 0 && nelem > (size_t)PY_SSIZE_T_MAX / elsize)
404 return NULL;
405 return _PyMem_Raw.calloc(_PyMem_Raw.ctx, nelem, elsize);
406}
407
Victor Stinner0507bf52013-07-07 02:05:46 +0200408void*
409PyMem_RawRealloc(void *ptr, size_t new_size)
410{
411 /* see PyMem_RawMalloc() */
412 if (new_size > (size_t)PY_SSIZE_T_MAX)
413 return NULL;
414 return _PyMem_Raw.realloc(_PyMem_Raw.ctx, ptr, new_size);
415}
416
417void PyMem_RawFree(void *ptr)
418{
419 _PyMem_Raw.free(_PyMem_Raw.ctx, ptr);
420}
421
422void *
423PyMem_Malloc(size_t size)
424{
425 /* see PyMem_RawMalloc() */
426 if (size > (size_t)PY_SSIZE_T_MAX)
427 return NULL;
428 return _PyMem.malloc(_PyMem.ctx, size);
429}
430
431void *
Victor Stinnerdb067af2014-05-02 22:31:14 +0200432PyMem_Calloc(size_t nelem, size_t elsize)
433{
434 /* see PyMem_RawMalloc() */
435 if (elsize != 0 && nelem > (size_t)PY_SSIZE_T_MAX / elsize)
436 return NULL;
437 return _PyMem.calloc(_PyMem.ctx, nelem, elsize);
438}
439
440void *
Victor Stinner0507bf52013-07-07 02:05:46 +0200441PyMem_Realloc(void *ptr, size_t new_size)
442{
443 /* see PyMem_RawMalloc() */
444 if (new_size > (size_t)PY_SSIZE_T_MAX)
445 return NULL;
446 return _PyMem.realloc(_PyMem.ctx, ptr, new_size);
447}
448
449void
450PyMem_Free(void *ptr)
451{
452 _PyMem.free(_PyMem.ctx, ptr);
453}
454
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200455char *
456_PyMem_RawStrdup(const char *str)
457{
458 size_t size;
459 char *copy;
460
461 size = strlen(str) + 1;
462 copy = PyMem_RawMalloc(size);
463 if (copy == NULL)
464 return NULL;
465 memcpy(copy, str, size);
466 return copy;
467}
468
469char *
470_PyMem_Strdup(const char *str)
471{
472 size_t size;
473 char *copy;
474
475 size = strlen(str) + 1;
476 copy = PyMem_Malloc(size);
477 if (copy == NULL)
478 return NULL;
479 memcpy(copy, str, size);
480 return copy;
481}
482
Victor Stinner0507bf52013-07-07 02:05:46 +0200483void *
484PyObject_Malloc(size_t size)
485{
486 /* see PyMem_RawMalloc() */
487 if (size > (size_t)PY_SSIZE_T_MAX)
488 return NULL;
489 return _PyObject.malloc(_PyObject.ctx, size);
490}
491
492void *
Victor Stinnerdb067af2014-05-02 22:31:14 +0200493PyObject_Calloc(size_t nelem, size_t elsize)
494{
495 /* see PyMem_RawMalloc() */
496 if (elsize != 0 && nelem > (size_t)PY_SSIZE_T_MAX / elsize)
497 return NULL;
498 return _PyObject.calloc(_PyObject.ctx, nelem, elsize);
499}
500
501void *
Victor Stinner0507bf52013-07-07 02:05:46 +0200502PyObject_Realloc(void *ptr, size_t new_size)
503{
504 /* see PyMem_RawMalloc() */
505 if (new_size > (size_t)PY_SSIZE_T_MAX)
506 return NULL;
507 return _PyObject.realloc(_PyObject.ctx, ptr, new_size);
508}
509
510void
511PyObject_Free(void *ptr)
512{
513 _PyObject.free(_PyObject.ctx, ptr);
514}
515
516
517#ifdef WITH_PYMALLOC
518
Benjamin Peterson05159c42009-12-03 03:01:27 +0000519#ifdef WITH_VALGRIND
520#include <valgrind/valgrind.h>
521
522/* If we're using GCC, use __builtin_expect() to reduce overhead of
523 the valgrind checks */
524#if defined(__GNUC__) && (__GNUC__ > 2) && defined(__OPTIMIZE__)
525# define UNLIKELY(value) __builtin_expect((value), 0)
526#else
527# define UNLIKELY(value) (value)
528#endif
529
530/* -1 indicates that we haven't checked that we're running on valgrind yet. */
531static int running_on_valgrind = -1;
532#endif
533
Neil Schemenauera35c6882001-02-27 04:45:05 +0000534/* An object allocator for Python.
535
536 Here is an introduction to the layers of the Python memory architecture,
537 showing where the object allocator is actually used (layer +2), It is
538 called for every object allocation and deallocation (PyObject_New/Del),
539 unless the object-specific allocators implement a proprietary allocation
540 scheme (ex.: ints use a simple free list). This is also the place where
541 the cyclic garbage collector operates selectively on container objects.
542
543
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000544 Object-specific allocators
Neil Schemenauera35c6882001-02-27 04:45:05 +0000545 _____ ______ ______ ________
546 [ int ] [ dict ] [ list ] ... [ string ] Python core |
547+3 | <----- Object-specific memory -----> | <-- Non-object memory --> |
548 _______________________________ | |
549 [ Python's object allocator ] | |
550+2 | ####### Object memory ####### | <------ Internal buffers ------> |
551 ______________________________________________________________ |
552 [ Python's raw memory allocator (PyMem_ API) ] |
553+1 | <----- Python memory (under PyMem manager's control) ------> | |
554 __________________________________________________________________
555 [ Underlying general-purpose allocator (ex: C library malloc) ]
556 0 | <------ Virtual memory allocated for the python process -------> |
557
558 =========================================================================
559 _______________________________________________________________________
560 [ OS-specific Virtual Memory Manager (VMM) ]
561-1 | <--- Kernel dynamic storage allocation & management (page-based) ---> |
562 __________________________________ __________________________________
563 [ ] [ ]
564-2 | <-- Physical memory: ROM/RAM --> | | <-- Secondary storage (swap) --> |
565
566*/
567/*==========================================================================*/
568
569/* A fast, special-purpose memory allocator for small blocks, to be used
570 on top of a general-purpose malloc -- heavily based on previous art. */
571
572/* Vladimir Marangozov -- August 2000 */
573
574/*
575 * "Memory management is where the rubber meets the road -- if we do the wrong
576 * thing at any level, the results will not be good. And if we don't make the
577 * levels work well together, we are in serious trouble." (1)
578 *
579 * (1) Paul R. Wilson, Mark S. Johnstone, Michael Neely, and David Boles,
580 * "Dynamic Storage Allocation: A Survey and Critical Review",
581 * in Proc. 1995 Int'l. Workshop on Memory Management, September 1995.
582 */
583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000584/* #undef WITH_MEMORY_LIMITS */ /* disable mem limit checks */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000585
586/*==========================================================================*/
587
588/*
Neil Schemenauera35c6882001-02-27 04:45:05 +0000589 * Allocation strategy abstract:
590 *
591 * For small requests, the allocator sub-allocates <Big> blocks of memory.
Antoine Pitrou6f26be02011-05-03 18:18:59 +0200592 * Requests greater than SMALL_REQUEST_THRESHOLD bytes are routed to the
593 * system's allocator.
Tim Petersce7fb9b2002-03-23 00:28:57 +0000594 *
Neil Schemenauera35c6882001-02-27 04:45:05 +0000595 * Small requests are grouped in size classes spaced 8 bytes apart, due
596 * to the required valid alignment of the returned address. Requests of
597 * a particular size are serviced from memory pools of 4K (one VMM page).
598 * Pools are fragmented on demand and contain free lists of blocks of one
599 * particular size class. In other words, there is a fixed-size allocator
600 * for each size class. Free pools are shared by the different allocators
601 * thus minimizing the space reserved for a particular size class.
602 *
603 * This allocation strategy is a variant of what is known as "simple
604 * segregated storage based on array of free lists". The main drawback of
605 * simple segregated storage is that we might end up with lot of reserved
606 * memory for the different free lists, which degenerate in time. To avoid
607 * this, we partition each free list in pools and we share dynamically the
608 * reserved space between all free lists. This technique is quite efficient
609 * for memory intensive programs which allocate mainly small-sized blocks.
610 *
611 * For small requests we have the following table:
612 *
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000613 * Request in bytes Size of allocated block Size class idx
Neil Schemenauera35c6882001-02-27 04:45:05 +0000614 * ----------------------------------------------------------------
615 * 1-8 8 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000616 * 9-16 16 1
617 * 17-24 24 2
618 * 25-32 32 3
619 * 33-40 40 4
620 * 41-48 48 5
621 * 49-56 56 6
622 * 57-64 64 7
623 * 65-72 72 8
624 * ... ... ...
Antoine Pitrou6f26be02011-05-03 18:18:59 +0200625 * 497-504 504 62
626 * 505-512 512 63
Tim Petersce7fb9b2002-03-23 00:28:57 +0000627 *
Antoine Pitrou6f26be02011-05-03 18:18:59 +0200628 * 0, SMALL_REQUEST_THRESHOLD + 1 and up: routed to the underlying
629 * allocator.
Neil Schemenauera35c6882001-02-27 04:45:05 +0000630 */
631
632/*==========================================================================*/
633
634/*
635 * -- Main tunable settings section --
636 */
637
638/*
639 * Alignment of addresses returned to the user. 8-bytes alignment works
640 * on most current architectures (with 32-bit or 64-bit address busses).
641 * The alignment value is also used for grouping small requests in size
642 * classes spaced ALIGNMENT bytes apart.
643 *
644 * You shouldn't change this unless you know what you are doing.
645 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646#define ALIGNMENT 8 /* must be 2^N */
647#define ALIGNMENT_SHIFT 3
Neil Schemenauera35c6882001-02-27 04:45:05 +0000648
Tim Peterse70ddf32002-04-05 04:32:29 +0000649/* Return the number of bytes in size class I, as a uint. */
650#define INDEX2SIZE(I) (((uint)(I) + 1) << ALIGNMENT_SHIFT)
651
Neil Schemenauera35c6882001-02-27 04:45:05 +0000652/*
653 * Max size threshold below which malloc requests are considered to be
654 * small enough in order to use preallocated memory pools. You can tune
655 * this value according to your application behaviour and memory needs.
656 *
Antoine Pitrou6f26be02011-05-03 18:18:59 +0200657 * Note: a size threshold of 512 guarantees that newly created dictionaries
658 * will be allocated from preallocated memory pools on 64-bit.
659 *
Neil Schemenauera35c6882001-02-27 04:45:05 +0000660 * The following invariants must hold:
Antoine Pitrou6f26be02011-05-03 18:18:59 +0200661 * 1) ALIGNMENT <= SMALL_REQUEST_THRESHOLD <= 512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000662 * 2) SMALL_REQUEST_THRESHOLD is evenly divisible by ALIGNMENT
Neil Schemenauera35c6882001-02-27 04:45:05 +0000663 *
664 * Although not required, for better performance and space efficiency,
665 * it is recommended that SMALL_REQUEST_THRESHOLD is set to a power of 2.
666 */
Antoine Pitrou6f26be02011-05-03 18:18:59 +0200667#define SMALL_REQUEST_THRESHOLD 512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668#define NB_SMALL_SIZE_CLASSES (SMALL_REQUEST_THRESHOLD / ALIGNMENT)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000669
670/*
671 * The system's VMM page size can be obtained on most unices with a
672 * getpagesize() call or deduced from various header files. To make
673 * things simpler, we assume that it is 4K, which is OK for most systems.
674 * It is probably better if this is the native page size, but it doesn't
Tim Petersecc6e6a2005-07-10 22:30:55 +0000675 * have to be. In theory, if SYSTEM_PAGE_SIZE is larger than the native page
676 * size, then `POOL_ADDR(p)->arenaindex' could rarely cause a segmentation
677 * violation fault. 4K is apparently OK for all the platforms that python
Martin v. Löwis8c140282002-10-26 15:01:53 +0000678 * currently targets.
Neil Schemenauera35c6882001-02-27 04:45:05 +0000679 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000680#define SYSTEM_PAGE_SIZE (4 * 1024)
681#define SYSTEM_PAGE_SIZE_MASK (SYSTEM_PAGE_SIZE - 1)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000682
683/*
684 * Maximum amount of memory managed by the allocator for small requests.
685 */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000686#ifdef WITH_MEMORY_LIMITS
687#ifndef SMALL_MEMORY_LIMIT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000688#define SMALL_MEMORY_LIMIT (64 * 1024 * 1024) /* 64 MB -- more? */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000689#endif
690#endif
691
692/*
693 * The allocator sub-allocates <Big> blocks of memory (called arenas) aligned
694 * on a page boundary. This is a reserved virtual address space for the
Antoine Pitrouf0effe62011-11-26 01:11:02 +0100695 * current process (obtained through a malloc()/mmap() call). In no way this
696 * means that the memory arenas will be used entirely. A malloc(<Big>) is
697 * usually an address range reservation for <Big> bytes, unless all pages within
698 * this space are referenced subsequently. So malloc'ing big blocks and not
699 * using them does not mean "wasting memory". It's an addressable range
700 * wastage...
Neil Schemenauera35c6882001-02-27 04:45:05 +0000701 *
Antoine Pitrouf0effe62011-11-26 01:11:02 +0100702 * Arenas are allocated with mmap() on systems supporting anonymous memory
703 * mappings to reduce heap fragmentation.
Neil Schemenauera35c6882001-02-27 04:45:05 +0000704 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000705#define ARENA_SIZE (256 << 10) /* 256KB */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000706
707#ifdef WITH_MEMORY_LIMITS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000708#define MAX_ARENAS (SMALL_MEMORY_LIMIT / ARENA_SIZE)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000709#endif
710
711/*
712 * Size of the pools used for small blocks. Should be a power of 2,
Tim Petersc2ce91a2002-03-30 21:36:04 +0000713 * between 1K and SYSTEM_PAGE_SIZE, that is: 1k, 2k, 4k.
Neil Schemenauera35c6882001-02-27 04:45:05 +0000714 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715#define POOL_SIZE SYSTEM_PAGE_SIZE /* must be 2^N */
716#define POOL_SIZE_MASK SYSTEM_PAGE_SIZE_MASK
Neil Schemenauera35c6882001-02-27 04:45:05 +0000717
718/*
719 * -- End of tunable settings section --
720 */
721
722/*==========================================================================*/
723
724/*
725 * Locking
726 *
727 * To reduce lock contention, it would probably be better to refine the
728 * crude function locking with per size class locking. I'm not positive
729 * however, whether it's worth switching to such locking policy because
730 * of the performance penalty it might introduce.
731 *
732 * The following macros describe the simplest (should also be the fastest)
733 * lock object on a particular platform and the init/fini/lock/unlock
734 * operations on it. The locks defined here are not expected to be recursive
735 * because it is assumed that they will always be called in the order:
736 * INIT, [LOCK, UNLOCK]*, FINI.
737 */
738
739/*
740 * Python's threads are serialized, so object malloc locking is disabled.
741 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000742#define SIMPLELOCK_DECL(lock) /* simple lock declaration */
743#define SIMPLELOCK_INIT(lock) /* allocate (if needed) and initialize */
744#define SIMPLELOCK_FINI(lock) /* free/destroy an existing lock */
745#define SIMPLELOCK_LOCK(lock) /* acquire released lock */
746#define SIMPLELOCK_UNLOCK(lock) /* release acquired lock */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000747
Neil Schemenauera35c6882001-02-27 04:45:05 +0000748/* When you say memory, my mind reasons in terms of (pointers to) blocks */
749typedef uchar block;
750
Tim Peterse70ddf32002-04-05 04:32:29 +0000751/* Pool for small blocks. */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000752struct pool_header {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000753 union { block *_padding;
Stefan Krah735bb122010-11-26 10:54:09 +0000754 uint count; } ref; /* number of allocated blocks */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000755 block *freeblock; /* pool's free list head */
756 struct pool_header *nextpool; /* next pool of this size class */
757 struct pool_header *prevpool; /* previous pool "" */
758 uint arenaindex; /* index into arenas of base adr */
759 uint szidx; /* block size class index */
760 uint nextoffset; /* bytes to virgin block */
761 uint maxnextoffset; /* largest valid nextoffset */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000762};
763
764typedef struct pool_header *poolp;
765
Thomas Woutersa9773292006-04-21 09:43:23 +0000766/* Record keeping for arenas. */
767struct arena_object {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000768 /* The address of the arena, as returned by malloc. Note that 0
769 * will never be returned by a successful malloc, and is used
770 * here to mark an arena_object that doesn't correspond to an
771 * allocated arena.
772 */
773 uptr address;
Thomas Woutersa9773292006-04-21 09:43:23 +0000774
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000775 /* Pool-aligned pointer to the next pool to be carved off. */
776 block* pool_address;
Thomas Woutersa9773292006-04-21 09:43:23 +0000777
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 /* The number of available pools in the arena: free pools + never-
779 * allocated pools.
780 */
781 uint nfreepools;
Thomas Woutersa9773292006-04-21 09:43:23 +0000782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000783 /* The total number of pools in the arena, whether or not available. */
784 uint ntotalpools;
Thomas Woutersa9773292006-04-21 09:43:23 +0000785
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000786 /* Singly-linked list of available pools. */
787 struct pool_header* freepools;
Thomas Woutersa9773292006-04-21 09:43:23 +0000788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 /* Whenever this arena_object is not associated with an allocated
790 * arena, the nextarena member is used to link all unassociated
791 * arena_objects in the singly-linked `unused_arena_objects` list.
792 * The prevarena member is unused in this case.
793 *
794 * When this arena_object is associated with an allocated arena
795 * with at least one available pool, both members are used in the
796 * doubly-linked `usable_arenas` list, which is maintained in
797 * increasing order of `nfreepools` values.
798 *
799 * Else this arena_object is associated with an allocated arena
800 * all of whose pools are in use. `nextarena` and `prevarena`
801 * are both meaningless in this case.
802 */
803 struct arena_object* nextarena;
804 struct arena_object* prevarena;
Thomas Woutersa9773292006-04-21 09:43:23 +0000805};
806
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +0200807#define POOL_OVERHEAD _Py_SIZE_ROUND_UP(sizeof(struct pool_header), ALIGNMENT)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000808
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000809#define DUMMY_SIZE_IDX 0xffff /* size class of newly cached pools */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000810
Tim Petersd97a1c02002-03-30 06:09:22 +0000811/* Round pointer P down to the closest pool-aligned address <= P, as a poolp */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +0200812#define POOL_ADDR(P) ((poolp)_Py_ALIGN_DOWN((P), POOL_SIZE))
Tim Peterse70ddf32002-04-05 04:32:29 +0000813
Tim Peters16bcb6b2002-04-05 05:45:31 +0000814/* Return total number of blocks in pool of size index I, as a uint. */
815#define NUMBLOCKS(I) ((uint)(POOL_SIZE - POOL_OVERHEAD) / INDEX2SIZE(I))
Tim Petersd97a1c02002-03-30 06:09:22 +0000816
Neil Schemenauera35c6882001-02-27 04:45:05 +0000817/*==========================================================================*/
818
819/*
820 * This malloc lock
821 */
Jeremy Hyltond1fedb62002-07-18 18:49:52 +0000822SIMPLELOCK_DECL(_malloc_lock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823#define LOCK() SIMPLELOCK_LOCK(_malloc_lock)
824#define UNLOCK() SIMPLELOCK_UNLOCK(_malloc_lock)
825#define LOCK_INIT() SIMPLELOCK_INIT(_malloc_lock)
826#define LOCK_FINI() SIMPLELOCK_FINI(_malloc_lock)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000827
828/*
Tim Peters1e16db62002-03-31 01:05:22 +0000829 * Pool table -- headed, circular, doubly-linked lists of partially used pools.
830
831This is involved. For an index i, usedpools[i+i] is the header for a list of
832all partially used pools holding small blocks with "size class idx" i. So
833usedpools[0] corresponds to blocks of size 8, usedpools[2] to blocks of size
83416, and so on: index 2*i <-> blocks of size (i+1)<<ALIGNMENT_SHIFT.
835
Thomas Woutersa9773292006-04-21 09:43:23 +0000836Pools are carved off an arena's highwater mark (an arena_object's pool_address
837member) as needed. Once carved off, a pool is in one of three states forever
838after:
Tim Peters1e16db62002-03-31 01:05:22 +0000839
Tim Peters338e0102002-04-01 19:23:44 +0000840used == partially used, neither empty nor full
841 At least one block in the pool is currently allocated, and at least one
842 block in the pool is not currently allocated (note this implies a pool
843 has room for at least two blocks).
844 This is a pool's initial state, as a pool is created only when malloc
845 needs space.
846 The pool holds blocks of a fixed size, and is in the circular list headed
847 at usedpools[i] (see above). It's linked to the other used pools of the
848 same size class via the pool_header's nextpool and prevpool members.
849 If all but one block is currently allocated, a malloc can cause a
850 transition to the full state. If all but one block is not currently
851 allocated, a free can cause a transition to the empty state.
Tim Peters1e16db62002-03-31 01:05:22 +0000852
Tim Peters338e0102002-04-01 19:23:44 +0000853full == all the pool's blocks are currently allocated
854 On transition to full, a pool is unlinked from its usedpools[] list.
855 It's not linked to from anything then anymore, and its nextpool and
856 prevpool members are meaningless until it transitions back to used.
857 A free of a block in a full pool puts the pool back in the used state.
858 Then it's linked in at the front of the appropriate usedpools[] list, so
859 that the next allocation for its size class will reuse the freed block.
860
861empty == all the pool's blocks are currently available for allocation
862 On transition to empty, a pool is unlinked from its usedpools[] list,
Thomas Woutersa9773292006-04-21 09:43:23 +0000863 and linked to the front of its arena_object's singly-linked freepools list,
Tim Peters338e0102002-04-01 19:23:44 +0000864 via its nextpool member. The prevpool member has no meaning in this case.
865 Empty pools have no inherent size class: the next time a malloc finds
866 an empty list in usedpools[], it takes the first pool off of freepools.
867 If the size class needed happens to be the same as the size class the pool
Tim Peterse70ddf32002-04-05 04:32:29 +0000868 last had, some pool initialization can be skipped.
Tim Peters338e0102002-04-01 19:23:44 +0000869
870
871Block Management
872
873Blocks within pools are again carved out as needed. pool->freeblock points to
874the start of a singly-linked list of free blocks within the pool. When a
875block is freed, it's inserted at the front of its pool's freeblock list. Note
876that the available blocks in a pool are *not* linked all together when a pool
Tim Peterse70ddf32002-04-05 04:32:29 +0000877is initialized. Instead only "the first two" (lowest addresses) blocks are
878set up, returning the first such block, and setting pool->freeblock to a
879one-block list holding the second such block. This is consistent with that
880pymalloc strives at all levels (arena, pool, and block) never to touch a piece
881of memory until it's actually needed.
882
883So long as a pool is in the used state, we're certain there *is* a block
Tim Peters52aefc82002-04-11 06:36:45 +0000884available for allocating, and pool->freeblock is not NULL. If pool->freeblock
885points to the end of the free list before we've carved the entire pool into
886blocks, that means we simply haven't yet gotten to one of the higher-address
887blocks. The offset from the pool_header to the start of "the next" virgin
888block is stored in the pool_header nextoffset member, and the largest value
889of nextoffset that makes sense is stored in the maxnextoffset member when a
890pool is initialized. All the blocks in a pool have been passed out at least
891once when and only when nextoffset > maxnextoffset.
Tim Peters338e0102002-04-01 19:23:44 +0000892
Tim Peters1e16db62002-03-31 01:05:22 +0000893
894Major obscurity: While the usedpools vector is declared to have poolp
895entries, it doesn't really. It really contains two pointers per (conceptual)
896poolp entry, the nextpool and prevpool members of a pool_header. The
897excruciating initialization code below fools C so that
898
899 usedpool[i+i]
900
901"acts like" a genuine poolp, but only so long as you only reference its
902nextpool and prevpool members. The "- 2*sizeof(block *)" gibberish is
903compensating for that a pool_header's nextpool and prevpool members
904immediately follow a pool_header's first two members:
905
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 union { block *_padding;
Stefan Krah735bb122010-11-26 10:54:09 +0000907 uint count; } ref;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000908 block *freeblock;
Tim Peters1e16db62002-03-31 01:05:22 +0000909
910each of which consume sizeof(block *) bytes. So what usedpools[i+i] really
911contains is a fudged-up pointer p such that *if* C believes it's a poolp
912pointer, then p->nextpool and p->prevpool are both p (meaning that the headed
913circular list is empty).
914
915It's unclear why the usedpools setup is so convoluted. It could be to
916minimize the amount of cache required to hold this heavily-referenced table
917(which only *needs* the two interpool pointer members of a pool_header). OTOH,
918referencing code has to remember to "double the index" and doing so isn't
919free, usedpools[0] isn't a strictly legal pointer, and we're crucially relying
920on that C doesn't insert any padding anywhere in a pool_header at or before
921the prevpool member.
922**************************************************************************** */
923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924#define PTA(x) ((poolp )((uchar *)&(usedpools[2*(x)]) - 2*sizeof(block *)))
925#define PT(x) PTA(x), PTA(x)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000926
927static poolp usedpools[2 * ((NB_SMALL_SIZE_CLASSES + 7) / 8) * 8] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 PT(0), PT(1), PT(2), PT(3), PT(4), PT(5), PT(6), PT(7)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000929#if NB_SMALL_SIZE_CLASSES > 8
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000930 , PT(8), PT(9), PT(10), PT(11), PT(12), PT(13), PT(14), PT(15)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000931#if NB_SMALL_SIZE_CLASSES > 16
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 , PT(16), PT(17), PT(18), PT(19), PT(20), PT(21), PT(22), PT(23)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000933#if NB_SMALL_SIZE_CLASSES > 24
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 , PT(24), PT(25), PT(26), PT(27), PT(28), PT(29), PT(30), PT(31)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000935#if NB_SMALL_SIZE_CLASSES > 32
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 , PT(32), PT(33), PT(34), PT(35), PT(36), PT(37), PT(38), PT(39)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000937#if NB_SMALL_SIZE_CLASSES > 40
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 , PT(40), PT(41), PT(42), PT(43), PT(44), PT(45), PT(46), PT(47)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000939#if NB_SMALL_SIZE_CLASSES > 48
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 , PT(48), PT(49), PT(50), PT(51), PT(52), PT(53), PT(54), PT(55)
Neil Schemenauera35c6882001-02-27 04:45:05 +0000941#if NB_SMALL_SIZE_CLASSES > 56
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 , PT(56), PT(57), PT(58), PT(59), PT(60), PT(61), PT(62), PT(63)
Antoine Pitrou6f26be02011-05-03 18:18:59 +0200943#if NB_SMALL_SIZE_CLASSES > 64
944#error "NB_SMALL_SIZE_CLASSES should be less than 64"
945#endif /* NB_SMALL_SIZE_CLASSES > 64 */
Neil Schemenauera35c6882001-02-27 04:45:05 +0000946#endif /* NB_SMALL_SIZE_CLASSES > 56 */
947#endif /* NB_SMALL_SIZE_CLASSES > 48 */
948#endif /* NB_SMALL_SIZE_CLASSES > 40 */
949#endif /* NB_SMALL_SIZE_CLASSES > 32 */
950#endif /* NB_SMALL_SIZE_CLASSES > 24 */
951#endif /* NB_SMALL_SIZE_CLASSES > 16 */
952#endif /* NB_SMALL_SIZE_CLASSES > 8 */
953};
954
Thomas Woutersa9773292006-04-21 09:43:23 +0000955/*==========================================================================
956Arena management.
Neil Schemenauera35c6882001-02-27 04:45:05 +0000957
Thomas Woutersa9773292006-04-21 09:43:23 +0000958`arenas` is a vector of arena_objects. It contains maxarenas entries, some of
959which may not be currently used (== they're arena_objects that aren't
960currently associated with an allocated arena). Note that arenas proper are
961separately malloc'ed.
Neil Schemenauera35c6882001-02-27 04:45:05 +0000962
Thomas Woutersa9773292006-04-21 09:43:23 +0000963Prior to Python 2.5, arenas were never free()'ed. Starting with Python 2.5,
964we do try to free() arenas, and use some mild heuristic strategies to increase
965the likelihood that arenas eventually can be freed.
966
967unused_arena_objects
968
969 This is a singly-linked list of the arena_objects that are currently not
970 being used (no arena is associated with them). Objects are taken off the
971 head of the list in new_arena(), and are pushed on the head of the list in
972 PyObject_Free() when the arena is empty. Key invariant: an arena_object
973 is on this list if and only if its .address member is 0.
974
975usable_arenas
976
977 This is a doubly-linked list of the arena_objects associated with arenas
978 that have pools available. These pools are either waiting to be reused,
979 or have not been used before. The list is sorted to have the most-
980 allocated arenas first (ascending order based on the nfreepools member).
981 This means that the next allocation will come from a heavily used arena,
982 which gives the nearly empty arenas a chance to be returned to the system.
983 In my unscientific tests this dramatically improved the number of arenas
984 that could be freed.
985
986Note that an arena_object associated with an arena all of whose pools are
987currently in use isn't on either list.
988*/
989
990/* Array of objects used to track chunks of memory (arenas). */
991static struct arena_object* arenas = NULL;
992/* Number of slots currently allocated in the `arenas` vector. */
Tim Peters1d99af82002-03-30 10:35:09 +0000993static uint maxarenas = 0;
Tim Petersd97a1c02002-03-30 06:09:22 +0000994
Thomas Woutersa9773292006-04-21 09:43:23 +0000995/* The head of the singly-linked, NULL-terminated list of available
996 * arena_objects.
Tim Petersd97a1c02002-03-30 06:09:22 +0000997 */
Thomas Woutersa9773292006-04-21 09:43:23 +0000998static struct arena_object* unused_arena_objects = NULL;
999
1000/* The head of the doubly-linked, NULL-terminated at each end, list of
1001 * arena_objects associated with arenas that have pools available.
1002 */
1003static struct arena_object* usable_arenas = NULL;
1004
1005/* How many arena_objects do we initially allocate?
1006 * 16 = can allocate 16 arenas = 16 * ARENA_SIZE = 4MB before growing the
1007 * `arenas` vector.
1008 */
1009#define INITIAL_ARENA_OBJECTS 16
1010
1011/* Number of arenas allocated that haven't been free()'d. */
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001012static size_t narenas_currently_allocated = 0;
Thomas Woutersa9773292006-04-21 09:43:23 +00001013
Thomas Woutersa9773292006-04-21 09:43:23 +00001014/* Total number of times malloc() called to allocate an arena. */
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001015static size_t ntimes_arena_allocated = 0;
Thomas Woutersa9773292006-04-21 09:43:23 +00001016/* High water mark (max value ever seen) for narenas_currently_allocated. */
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001017static size_t narenas_highwater = 0;
Thomas Woutersa9773292006-04-21 09:43:23 +00001018
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001019static Py_ssize_t _Py_AllocatedBlocks = 0;
1020
1021Py_ssize_t
1022_Py_GetAllocatedBlocks(void)
1023{
1024 return _Py_AllocatedBlocks;
1025}
1026
1027
Thomas Woutersa9773292006-04-21 09:43:23 +00001028/* Allocate a new arena. If we run out of memory, return NULL. Else
1029 * allocate a new arena, and return the address of an arena_object
1030 * describing the new arena. It's expected that the caller will set
1031 * `usable_arenas` to the return value.
1032 */
1033static struct arena_object*
Tim Petersd97a1c02002-03-30 06:09:22 +00001034new_arena(void)
1035{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001036 struct arena_object* arenaobj;
1037 uint excess; /* number of bytes above pool alignment */
Victor Stinnerba108822012-03-10 00:21:44 +01001038 void *address;
Victor Stinner34be8072016-03-14 12:04:26 +01001039 static int debug_stats = -1;
Tim Petersd97a1c02002-03-30 06:09:22 +00001040
Victor Stinner34be8072016-03-14 12:04:26 +01001041 if (debug_stats == -1) {
1042 char *opt = Py_GETENV("PYTHONMALLOCSTATS");
1043 debug_stats = (opt != NULL && *opt != '\0');
1044 }
1045 if (debug_stats)
David Malcolm49526f42012-06-22 14:55:41 -04001046 _PyObject_DebugMallocStats(stderr);
Victor Stinner34be8072016-03-14 12:04:26 +01001047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 if (unused_arena_objects == NULL) {
1049 uint i;
1050 uint numarenas;
1051 size_t nbytes;
Tim Peters0e871182002-04-13 08:29:14 +00001052
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 /* Double the number of arena objects on each allocation.
1054 * Note that it's possible for `numarenas` to overflow.
1055 */
1056 numarenas = maxarenas ? maxarenas << 1 : INITIAL_ARENA_OBJECTS;
1057 if (numarenas <= maxarenas)
1058 return NULL; /* overflow */
Martin v. Löwis5aca8822008-09-11 06:55:48 +00001059#if SIZEOF_SIZE_T <= SIZEOF_INT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001060 if (numarenas > PY_SIZE_MAX / sizeof(*arenas))
1061 return NULL; /* overflow */
Martin v. Löwis5aca8822008-09-11 06:55:48 +00001062#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001063 nbytes = numarenas * sizeof(*arenas);
Victor Stinner6cf185d2013-10-10 15:58:42 +02001064 arenaobj = (struct arena_object *)PyMem_RawRealloc(arenas, nbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001065 if (arenaobj == NULL)
1066 return NULL;
1067 arenas = arenaobj;
Thomas Woutersa9773292006-04-21 09:43:23 +00001068
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001069 /* We might need to fix pointers that were copied. However,
1070 * new_arena only gets called when all the pages in the
1071 * previous arenas are full. Thus, there are *no* pointers
1072 * into the old array. Thus, we don't have to worry about
1073 * invalid pointers. Just to be sure, some asserts:
1074 */
1075 assert(usable_arenas == NULL);
1076 assert(unused_arena_objects == NULL);
Thomas Woutersa9773292006-04-21 09:43:23 +00001077
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 /* Put the new arenas on the unused_arena_objects list. */
1079 for (i = maxarenas; i < numarenas; ++i) {
1080 arenas[i].address = 0; /* mark as unassociated */
1081 arenas[i].nextarena = i < numarenas - 1 ?
1082 &arenas[i+1] : NULL;
1083 }
Thomas Woutersa9773292006-04-21 09:43:23 +00001084
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001085 /* Update globals. */
1086 unused_arena_objects = &arenas[maxarenas];
1087 maxarenas = numarenas;
1088 }
Tim Petersd97a1c02002-03-30 06:09:22 +00001089
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001090 /* Take the next available arena object off the head of the list. */
1091 assert(unused_arena_objects != NULL);
1092 arenaobj = unused_arena_objects;
1093 unused_arena_objects = arenaobj->nextarena;
1094 assert(arenaobj->address == 0);
Victor Stinner0507bf52013-07-07 02:05:46 +02001095 address = _PyObject_Arena.alloc(_PyObject_Arena.ctx, ARENA_SIZE);
1096 if (address == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001097 /* The allocation failed: return NULL after putting the
1098 * arenaobj back.
1099 */
1100 arenaobj->nextarena = unused_arena_objects;
1101 unused_arena_objects = arenaobj;
1102 return NULL;
1103 }
Victor Stinnerba108822012-03-10 00:21:44 +01001104 arenaobj->address = (uptr)address;
Tim Petersd97a1c02002-03-30 06:09:22 +00001105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 ++narenas_currently_allocated;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001107 ++ntimes_arena_allocated;
1108 if (narenas_currently_allocated > narenas_highwater)
1109 narenas_highwater = narenas_currently_allocated;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001110 arenaobj->freepools = NULL;
1111 /* pool_address <- first pool-aligned address in the arena
1112 nfreepools <- number of whole pools that fit after alignment */
1113 arenaobj->pool_address = (block*)arenaobj->address;
1114 arenaobj->nfreepools = ARENA_SIZE / POOL_SIZE;
1115 assert(POOL_SIZE * arenaobj->nfreepools == ARENA_SIZE);
1116 excess = (uint)(arenaobj->address & POOL_SIZE_MASK);
1117 if (excess != 0) {
1118 --arenaobj->nfreepools;
1119 arenaobj->pool_address += POOL_SIZE - excess;
1120 }
1121 arenaobj->ntotalpools = arenaobj->nfreepools;
Thomas Woutersa9773292006-04-21 09:43:23 +00001122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001123 return arenaobj;
Tim Petersd97a1c02002-03-30 06:09:22 +00001124}
1125
Thomas Woutersa9773292006-04-21 09:43:23 +00001126/*
1127Py_ADDRESS_IN_RANGE(P, POOL)
1128
1129Return true if and only if P is an address that was allocated by pymalloc.
1130POOL must be the pool address associated with P, i.e., POOL = POOL_ADDR(P)
1131(the caller is asked to compute this because the macro expands POOL more than
1132once, and for efficiency it's best for the caller to assign POOL_ADDR(P) to a
1133variable and pass the latter to the macro; because Py_ADDRESS_IN_RANGE is
1134called on every alloc/realloc/free, micro-efficiency is important here).
1135
1136Tricky: Let B be the arena base address associated with the pool, B =
1137arenas[(POOL)->arenaindex].address. Then P belongs to the arena if and only if
1138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001139 B <= P < B + ARENA_SIZE
Thomas Woutersa9773292006-04-21 09:43:23 +00001140
1141Subtracting B throughout, this is true iff
1142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001143 0 <= P-B < ARENA_SIZE
Thomas Woutersa9773292006-04-21 09:43:23 +00001144
1145By using unsigned arithmetic, the "0 <=" half of the test can be skipped.
1146
1147Obscure: A PyMem "free memory" function can call the pymalloc free or realloc
1148before the first arena has been allocated. `arenas` is still NULL in that
1149case. We're relying on that maxarenas is also 0 in that case, so that
1150(POOL)->arenaindex < maxarenas must be false, saving us from trying to index
1151into a NULL arenas.
1152
1153Details: given P and POOL, the arena_object corresponding to P is AO =
1154arenas[(POOL)->arenaindex]. Suppose obmalloc controls P. Then (barring wild
1155stores, etc), POOL is the correct address of P's pool, AO.address is the
1156correct base address of the pool's arena, and P must be within ARENA_SIZE of
1157AO.address. In addition, AO.address is not 0 (no arena can start at address 0
1158(NULL)). Therefore Py_ADDRESS_IN_RANGE correctly reports that obmalloc
1159controls P.
1160
1161Now suppose obmalloc does not control P (e.g., P was obtained via a direct
1162call to the system malloc() or realloc()). (POOL)->arenaindex may be anything
1163in this case -- it may even be uninitialized trash. If the trash arenaindex
1164is >= maxarenas, the macro correctly concludes at once that obmalloc doesn't
1165control P.
1166
1167Else arenaindex is < maxarena, and AO is read up. If AO corresponds to an
1168allocated arena, obmalloc controls all the memory in slice AO.address :
1169AO.address+ARENA_SIZE. By case assumption, P is not controlled by obmalloc,
1170so P doesn't lie in that slice, so the macro correctly reports that P is not
1171controlled by obmalloc.
1172
1173Finally, if P is not controlled by obmalloc and AO corresponds to an unused
1174arena_object (one not currently associated with an allocated arena),
1175AO.address is 0, and the second test in the macro reduces to:
1176
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001177 P < ARENA_SIZE
Thomas Woutersa9773292006-04-21 09:43:23 +00001178
1179If P >= ARENA_SIZE (extremely likely), the macro again correctly concludes
1180that P is not controlled by obmalloc. However, if P < ARENA_SIZE, this part
1181of the test still passes, and the third clause (AO.address != 0) is necessary
1182to get the correct result: AO.address is 0 in this case, so the macro
1183correctly reports that P is not controlled by obmalloc (despite that P lies in
1184slice AO.address : AO.address + ARENA_SIZE).
1185
1186Note: The third (AO.address != 0) clause was added in Python 2.5. Before
11872.5, arenas were never free()'ed, and an arenaindex < maxarena always
1188corresponded to a currently-allocated arena, so the "P is not controlled by
1189obmalloc, AO corresponds to an unused arena_object, and P < ARENA_SIZE" case
1190was impossible.
1191
1192Note that the logic is excruciating, and reading up possibly uninitialized
1193memory when P is not controlled by obmalloc (to get at (POOL)->arenaindex)
1194creates problems for some memory debuggers. The overwhelming advantage is
1195that this test determines whether an arbitrary address is controlled by
1196obmalloc in a small constant time, independent of the number of arenas
1197obmalloc controls. Since this test is needed at every entry point, it's
1198extremely desirable that it be this fast.
Antoine Pitroub7fb2e22011-01-07 21:43:59 +00001199
1200Since Py_ADDRESS_IN_RANGE may be reading from memory which was not allocated
1201by Python, it is important that (POOL)->arenaindex is read only once, as
1202another thread may be concurrently modifying the value without holding the
1203GIL. To accomplish this, the arenaindex_temp variable is used to store
1204(POOL)->arenaindex for the duration of the Py_ADDRESS_IN_RANGE macro's
1205execution. The caller of the macro is responsible for declaring this
1206variable.
Thomas Woutersa9773292006-04-21 09:43:23 +00001207*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001208#define Py_ADDRESS_IN_RANGE(P, POOL) \
Antoine Pitroub7fb2e22011-01-07 21:43:59 +00001209 ((arenaindex_temp = (POOL)->arenaindex) < maxarenas && \
1210 (uptr)(P) - arenas[arenaindex_temp].address < (uptr)ARENA_SIZE && \
1211 arenas[arenaindex_temp].address != 0)
Thomas Woutersa9773292006-04-21 09:43:23 +00001212
Neal Norwitz7eb3c912004-06-06 19:20:22 +00001213
1214/* This is only useful when running memory debuggers such as
1215 * Purify or Valgrind. Uncomment to use.
1216 *
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001217#define Py_USING_MEMORY_DEBUGGER
Martin v. Löwis6fea2332008-09-25 04:15:27 +00001218 */
Neal Norwitz7eb3c912004-06-06 19:20:22 +00001219
1220#ifdef Py_USING_MEMORY_DEBUGGER
1221
1222/* Py_ADDRESS_IN_RANGE may access uninitialized memory by design
1223 * This leads to thousands of spurious warnings when using
1224 * Purify or Valgrind. By making a function, we can easily
1225 * suppress the uninitialized memory reads in this one function.
1226 * So we won't ignore real errors elsewhere.
1227 *
1228 * Disable the macro and use a function.
1229 */
1230
1231#undef Py_ADDRESS_IN_RANGE
1232
Thomas Wouters89f507f2006-12-13 04:49:30 +00001233#if defined(__GNUC__) && ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 1) || \
Stefan Krah735bb122010-11-26 10:54:09 +00001234 (__GNUC__ >= 4))
Neal Norwitze5e5aa42005-11-13 18:55:39 +00001235#define Py_NO_INLINE __attribute__((__noinline__))
1236#else
1237#define Py_NO_INLINE
1238#endif
1239
1240/* Don't make static, to try to ensure this isn't inlined. */
1241int Py_ADDRESS_IN_RANGE(void *P, poolp pool) Py_NO_INLINE;
1242#undef Py_NO_INLINE
Neal Norwitz7eb3c912004-06-06 19:20:22 +00001243#endif
Tim Peters338e0102002-04-01 19:23:44 +00001244
Neil Schemenauera35c6882001-02-27 04:45:05 +00001245/*==========================================================================*/
1246
Tim Peters84c1b972002-04-04 04:44:32 +00001247/* malloc. Note that nbytes==0 tries to return a non-NULL pointer, distinct
1248 * from all other currently live pointers. This may not be possible.
1249 */
Neil Schemenauera35c6882001-02-27 04:45:05 +00001250
1251/*
1252 * The basic blocks are ordered by decreasing execution frequency,
1253 * which minimizes the number of jumps in the most common cases,
1254 * improves branching prediction and instruction scheduling (small
1255 * block allocations typically result in a couple of instructions).
1256 * Unless the optimizer reorders everything, being too smart...
1257 */
1258
Victor Stinner0507bf52013-07-07 02:05:46 +02001259static void *
Victor Stinnerdb067af2014-05-02 22:31:14 +02001260_PyObject_Alloc(int use_calloc, void *ctx, size_t nelem, size_t elsize)
Neil Schemenauera35c6882001-02-27 04:45:05 +00001261{
Victor Stinnerdb067af2014-05-02 22:31:14 +02001262 size_t nbytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 block *bp;
1264 poolp pool;
1265 poolp next;
1266 uint size;
Neil Schemenauera35c6882001-02-27 04:45:05 +00001267
Antoine Pitrou0aaaa622013-04-06 01:15:30 +02001268 _Py_AllocatedBlocks++;
1269
Victor Stinner3080d922014-05-06 11:32:29 +02001270 assert(nelem <= PY_SSIZE_T_MAX / elsize);
1271 nbytes = nelem * elsize;
1272
Benjamin Peterson05159c42009-12-03 03:01:27 +00001273#ifdef WITH_VALGRIND
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001274 if (UNLIKELY(running_on_valgrind == -1))
1275 running_on_valgrind = RUNNING_ON_VALGRIND;
1276 if (UNLIKELY(running_on_valgrind))
1277 goto redirect;
Benjamin Peterson05159c42009-12-03 03:01:27 +00001278#endif
1279
Victor Stinneraf8fc642014-05-02 23:26:03 +02001280 if (nelem == 0 || elsize == 0)
1281 goto redirect;
1282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001283 if ((nbytes - 1) < SMALL_REQUEST_THRESHOLD) {
1284 LOCK();
1285 /*
1286 * Most frequent paths first
1287 */
1288 size = (uint)(nbytes - 1) >> ALIGNMENT_SHIFT;
1289 pool = usedpools[size + size];
1290 if (pool != pool->nextpool) {
1291 /*
1292 * There is a used pool for this size class.
1293 * Pick up the head block of its free list.
1294 */
1295 ++pool->ref.count;
1296 bp = pool->freeblock;
1297 assert(bp != NULL);
1298 if ((pool->freeblock = *(block **)bp) != NULL) {
1299 UNLOCK();
Victor Stinnerdb067af2014-05-02 22:31:14 +02001300 if (use_calloc)
1301 memset(bp, 0, nbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001302 return (void *)bp;
1303 }
1304 /*
1305 * Reached the end of the free list, try to extend it.
1306 */
1307 if (pool->nextoffset <= pool->maxnextoffset) {
1308 /* There is room for another block. */
1309 pool->freeblock = (block*)pool +
1310 pool->nextoffset;
1311 pool->nextoffset += INDEX2SIZE(size);
1312 *(block **)(pool->freeblock) = NULL;
1313 UNLOCK();
Victor Stinnerdb067af2014-05-02 22:31:14 +02001314 if (use_calloc)
1315 memset(bp, 0, nbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001316 return (void *)bp;
1317 }
1318 /* Pool is full, unlink from used pools. */
1319 next = pool->nextpool;
1320 pool = pool->prevpool;
1321 next->prevpool = pool;
1322 pool->nextpool = next;
1323 UNLOCK();
Victor Stinnerdb067af2014-05-02 22:31:14 +02001324 if (use_calloc)
1325 memset(bp, 0, nbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001326 return (void *)bp;
1327 }
Thomas Woutersa9773292006-04-21 09:43:23 +00001328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001329 /* There isn't a pool of the right size class immediately
1330 * available: use a free pool.
1331 */
1332 if (usable_arenas == NULL) {
1333 /* No arena has a free pool: allocate a new arena. */
Thomas Woutersa9773292006-04-21 09:43:23 +00001334#ifdef WITH_MEMORY_LIMITS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001335 if (narenas_currently_allocated >= MAX_ARENAS) {
1336 UNLOCK();
1337 goto redirect;
1338 }
Thomas Woutersa9773292006-04-21 09:43:23 +00001339#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001340 usable_arenas = new_arena();
1341 if (usable_arenas == NULL) {
1342 UNLOCK();
1343 goto redirect;
1344 }
1345 usable_arenas->nextarena =
1346 usable_arenas->prevarena = NULL;
1347 }
1348 assert(usable_arenas->address != 0);
Thomas Woutersa9773292006-04-21 09:43:23 +00001349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001350 /* Try to get a cached free pool. */
1351 pool = usable_arenas->freepools;
1352 if (pool != NULL) {
1353 /* Unlink from cached pools. */
1354 usable_arenas->freepools = pool->nextpool;
Thomas Woutersa9773292006-04-21 09:43:23 +00001355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001356 /* This arena already had the smallest nfreepools
1357 * value, so decreasing nfreepools doesn't change
1358 * that, and we don't need to rearrange the
1359 * usable_arenas list. However, if the arena has
1360 * become wholly allocated, we need to remove its
1361 * arena_object from usable_arenas.
1362 */
1363 --usable_arenas->nfreepools;
1364 if (usable_arenas->nfreepools == 0) {
1365 /* Wholly allocated: remove. */
1366 assert(usable_arenas->freepools == NULL);
1367 assert(usable_arenas->nextarena == NULL ||
1368 usable_arenas->nextarena->prevarena ==
1369 usable_arenas);
Thomas Woutersa9773292006-04-21 09:43:23 +00001370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001371 usable_arenas = usable_arenas->nextarena;
1372 if (usable_arenas != NULL) {
1373 usable_arenas->prevarena = NULL;
1374 assert(usable_arenas->address != 0);
1375 }
1376 }
1377 else {
1378 /* nfreepools > 0: it must be that freepools
1379 * isn't NULL, or that we haven't yet carved
1380 * off all the arena's pools for the first
1381 * time.
1382 */
1383 assert(usable_arenas->freepools != NULL ||
1384 usable_arenas->pool_address <=
1385 (block*)usable_arenas->address +
1386 ARENA_SIZE - POOL_SIZE);
1387 }
1388 init_pool:
1389 /* Frontlink to used pools. */
1390 next = usedpools[size + size]; /* == prev */
1391 pool->nextpool = next;
1392 pool->prevpool = next;
1393 next->nextpool = pool;
1394 next->prevpool = pool;
1395 pool->ref.count = 1;
1396 if (pool->szidx == size) {
1397 /* Luckily, this pool last contained blocks
1398 * of the same size class, so its header
1399 * and free list are already initialized.
1400 */
1401 bp = pool->freeblock;
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001402 assert(bp != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001403 pool->freeblock = *(block **)bp;
1404 UNLOCK();
Victor Stinnerdb067af2014-05-02 22:31:14 +02001405 if (use_calloc)
1406 memset(bp, 0, nbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001407 return (void *)bp;
1408 }
1409 /*
1410 * Initialize the pool header, set up the free list to
1411 * contain just the second block, and return the first
1412 * block.
1413 */
1414 pool->szidx = size;
1415 size = INDEX2SIZE(size);
1416 bp = (block *)pool + POOL_OVERHEAD;
1417 pool->nextoffset = POOL_OVERHEAD + (size << 1);
1418 pool->maxnextoffset = POOL_SIZE - size;
1419 pool->freeblock = bp + size;
1420 *(block **)(pool->freeblock) = NULL;
1421 UNLOCK();
Victor Stinnerdb067af2014-05-02 22:31:14 +02001422 if (use_calloc)
1423 memset(bp, 0, nbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001424 return (void *)bp;
1425 }
Thomas Woutersa9773292006-04-21 09:43:23 +00001426
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001427 /* Carve off a new pool. */
1428 assert(usable_arenas->nfreepools > 0);
1429 assert(usable_arenas->freepools == NULL);
1430 pool = (poolp)usable_arenas->pool_address;
1431 assert((block*)pool <= (block*)usable_arenas->address +
1432 ARENA_SIZE - POOL_SIZE);
Serhiy Storchaka26861b02015-02-16 20:52:17 +02001433 pool->arenaindex = (uint)(usable_arenas - arenas);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001434 assert(&arenas[pool->arenaindex] == usable_arenas);
1435 pool->szidx = DUMMY_SIZE_IDX;
1436 usable_arenas->pool_address += POOL_SIZE;
1437 --usable_arenas->nfreepools;
Thomas Woutersa9773292006-04-21 09:43:23 +00001438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001439 if (usable_arenas->nfreepools == 0) {
1440 assert(usable_arenas->nextarena == NULL ||
1441 usable_arenas->nextarena->prevarena ==
1442 usable_arenas);
1443 /* Unlink the arena: it is completely allocated. */
1444 usable_arenas = usable_arenas->nextarena;
1445 if (usable_arenas != NULL) {
1446 usable_arenas->prevarena = NULL;
1447 assert(usable_arenas->address != 0);
1448 }
1449 }
Thomas Woutersa9773292006-04-21 09:43:23 +00001450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001451 goto init_pool;
1452 }
Neil Schemenauera35c6882001-02-27 04:45:05 +00001453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001454 /* The small block allocator ends here. */
Neil Schemenauera35c6882001-02-27 04:45:05 +00001455
Tim Petersd97a1c02002-03-30 06:09:22 +00001456redirect:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001457 /* Redirect the original request to the underlying (libc) allocator.
1458 * We jump here on bigger requests, on error in the code above (as a
1459 * last chance to serve the request) or when the max memory limit
1460 * has been reached.
1461 */
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001462 {
Victor Stinnerdb067af2014-05-02 22:31:14 +02001463 void *result;
1464 if (use_calloc)
1465 result = PyMem_RawCalloc(nelem, elsize);
1466 else
1467 result = PyMem_RawMalloc(nbytes);
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001468 if (!result)
1469 _Py_AllocatedBlocks--;
1470 return result;
1471 }
Neil Schemenauera35c6882001-02-27 04:45:05 +00001472}
1473
Victor Stinnerdb067af2014-05-02 22:31:14 +02001474static void *
1475_PyObject_Malloc(void *ctx, size_t nbytes)
1476{
1477 return _PyObject_Alloc(0, ctx, 1, nbytes);
1478}
1479
1480static void *
1481_PyObject_Calloc(void *ctx, size_t nelem, size_t elsize)
1482{
1483 return _PyObject_Alloc(1, ctx, nelem, elsize);
1484}
1485
Neil Schemenauera35c6882001-02-27 04:45:05 +00001486/* free */
1487
Nick Coghlan6ba64f42013-09-29 00:28:55 +10001488ATTRIBUTE_NO_ADDRESS_SAFETY_ANALYSIS
Victor Stinner0507bf52013-07-07 02:05:46 +02001489static void
1490_PyObject_Free(void *ctx, void *p)
Neil Schemenauera35c6882001-02-27 04:45:05 +00001491{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001492 poolp pool;
1493 block *lastfree;
1494 poolp next, prev;
1495 uint size;
Antoine Pitroub7fb2e22011-01-07 21:43:59 +00001496#ifndef Py_USING_MEMORY_DEBUGGER
1497 uint arenaindex_temp;
1498#endif
Neil Schemenauera35c6882001-02-27 04:45:05 +00001499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001500 if (p == NULL) /* free(NULL) has no effect */
1501 return;
Neil Schemenauera35c6882001-02-27 04:45:05 +00001502
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001503 _Py_AllocatedBlocks--;
1504
Benjamin Peterson05159c42009-12-03 03:01:27 +00001505#ifdef WITH_VALGRIND
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001506 if (UNLIKELY(running_on_valgrind > 0))
1507 goto redirect;
Benjamin Peterson05159c42009-12-03 03:01:27 +00001508#endif
1509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001510 pool = POOL_ADDR(p);
1511 if (Py_ADDRESS_IN_RANGE(p, pool)) {
1512 /* We allocated this address. */
1513 LOCK();
1514 /* Link p to the start of the pool's freeblock list. Since
1515 * the pool had at least the p block outstanding, the pool
1516 * wasn't empty (so it's already in a usedpools[] list, or
1517 * was full and is in no list -- it's not in the freeblocks
1518 * list in any case).
1519 */
1520 assert(pool->ref.count > 0); /* else it was empty */
1521 *(block **)p = lastfree = pool->freeblock;
1522 pool->freeblock = (block *)p;
1523 if (lastfree) {
1524 struct arena_object* ao;
1525 uint nf; /* ao->nfreepools */
Thomas Woutersa9773292006-04-21 09:43:23 +00001526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001527 /* freeblock wasn't NULL, so the pool wasn't full,
1528 * and the pool is in a usedpools[] list.
1529 */
1530 if (--pool->ref.count != 0) {
1531 /* pool isn't empty: leave it in usedpools */
1532 UNLOCK();
1533 return;
1534 }
1535 /* Pool is now empty: unlink from usedpools, and
1536 * link to the front of freepools. This ensures that
1537 * previously freed pools will be allocated later
1538 * (being not referenced, they are perhaps paged out).
1539 */
1540 next = pool->nextpool;
1541 prev = pool->prevpool;
1542 next->prevpool = prev;
1543 prev->nextpool = next;
Thomas Woutersa9773292006-04-21 09:43:23 +00001544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001545 /* Link the pool to freepools. This is a singly-linked
1546 * list, and pool->prevpool isn't used there.
1547 */
1548 ao = &arenas[pool->arenaindex];
1549 pool->nextpool = ao->freepools;
1550 ao->freepools = pool;
1551 nf = ++ao->nfreepools;
Thomas Woutersa9773292006-04-21 09:43:23 +00001552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001553 /* All the rest is arena management. We just freed
1554 * a pool, and there are 4 cases for arena mgmt:
1555 * 1. If all the pools are free, return the arena to
1556 * the system free().
1557 * 2. If this is the only free pool in the arena,
1558 * add the arena back to the `usable_arenas` list.
1559 * 3. If the "next" arena has a smaller count of free
1560 * pools, we have to "slide this arena right" to
1561 * restore that usable_arenas is sorted in order of
1562 * nfreepools.
1563 * 4. Else there's nothing more to do.
1564 */
1565 if (nf == ao->ntotalpools) {
1566 /* Case 1. First unlink ao from usable_arenas.
1567 */
1568 assert(ao->prevarena == NULL ||
1569 ao->prevarena->address != 0);
1570 assert(ao ->nextarena == NULL ||
1571 ao->nextarena->address != 0);
Thomas Woutersa9773292006-04-21 09:43:23 +00001572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001573 /* Fix the pointer in the prevarena, or the
1574 * usable_arenas pointer.
1575 */
1576 if (ao->prevarena == NULL) {
1577 usable_arenas = ao->nextarena;
1578 assert(usable_arenas == NULL ||
1579 usable_arenas->address != 0);
1580 }
1581 else {
1582 assert(ao->prevarena->nextarena == ao);
1583 ao->prevarena->nextarena =
1584 ao->nextarena;
1585 }
1586 /* Fix the pointer in the nextarena. */
1587 if (ao->nextarena != NULL) {
1588 assert(ao->nextarena->prevarena == ao);
1589 ao->nextarena->prevarena =
1590 ao->prevarena;
1591 }
1592 /* Record that this arena_object slot is
1593 * available to be reused.
1594 */
1595 ao->nextarena = unused_arena_objects;
1596 unused_arena_objects = ao;
Thomas Woutersa9773292006-04-21 09:43:23 +00001597
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001598 /* Free the entire arena. */
Victor Stinner0507bf52013-07-07 02:05:46 +02001599 _PyObject_Arena.free(_PyObject_Arena.ctx,
1600 (void *)ao->address, ARENA_SIZE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001601 ao->address = 0; /* mark unassociated */
1602 --narenas_currently_allocated;
Thomas Woutersa9773292006-04-21 09:43:23 +00001603
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001604 UNLOCK();
1605 return;
1606 }
1607 if (nf == 1) {
1608 /* Case 2. Put ao at the head of
1609 * usable_arenas. Note that because
1610 * ao->nfreepools was 0 before, ao isn't
1611 * currently on the usable_arenas list.
1612 */
1613 ao->nextarena = usable_arenas;
1614 ao->prevarena = NULL;
1615 if (usable_arenas)
1616 usable_arenas->prevarena = ao;
1617 usable_arenas = ao;
1618 assert(usable_arenas->address != 0);
Thomas Woutersa9773292006-04-21 09:43:23 +00001619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001620 UNLOCK();
1621 return;
1622 }
1623 /* If this arena is now out of order, we need to keep
1624 * the list sorted. The list is kept sorted so that
1625 * the "most full" arenas are used first, which allows
1626 * the nearly empty arenas to be completely freed. In
1627 * a few un-scientific tests, it seems like this
1628 * approach allowed a lot more memory to be freed.
1629 */
1630 if (ao->nextarena == NULL ||
1631 nf <= ao->nextarena->nfreepools) {
1632 /* Case 4. Nothing to do. */
1633 UNLOCK();
1634 return;
1635 }
1636 /* Case 3: We have to move the arena towards the end
1637 * of the list, because it has more free pools than
1638 * the arena to its right.
1639 * First unlink ao from usable_arenas.
1640 */
1641 if (ao->prevarena != NULL) {
1642 /* ao isn't at the head of the list */
1643 assert(ao->prevarena->nextarena == ao);
1644 ao->prevarena->nextarena = ao->nextarena;
1645 }
1646 else {
1647 /* ao is at the head of the list */
1648 assert(usable_arenas == ao);
1649 usable_arenas = ao->nextarena;
1650 }
1651 ao->nextarena->prevarena = ao->prevarena;
Thomas Woutersa9773292006-04-21 09:43:23 +00001652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001653 /* Locate the new insertion point by iterating over
1654 * the list, using our nextarena pointer.
1655 */
1656 while (ao->nextarena != NULL &&
1657 nf > ao->nextarena->nfreepools) {
1658 ao->prevarena = ao->nextarena;
1659 ao->nextarena = ao->nextarena->nextarena;
1660 }
Thomas Woutersa9773292006-04-21 09:43:23 +00001661
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001662 /* Insert ao at this point. */
1663 assert(ao->nextarena == NULL ||
1664 ao->prevarena == ao->nextarena->prevarena);
1665 assert(ao->prevarena->nextarena == ao->nextarena);
Thomas Woutersa9773292006-04-21 09:43:23 +00001666
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001667 ao->prevarena->nextarena = ao;
1668 if (ao->nextarena != NULL)
1669 ao->nextarena->prevarena = ao;
Thomas Woutersa9773292006-04-21 09:43:23 +00001670
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001671 /* Verify that the swaps worked. */
1672 assert(ao->nextarena == NULL ||
1673 nf <= ao->nextarena->nfreepools);
1674 assert(ao->prevarena == NULL ||
1675 nf > ao->prevarena->nfreepools);
1676 assert(ao->nextarena == NULL ||
1677 ao->nextarena->prevarena == ao);
1678 assert((usable_arenas == ao &&
1679 ao->prevarena == NULL) ||
1680 ao->prevarena->nextarena == ao);
Thomas Woutersa9773292006-04-21 09:43:23 +00001681
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001682 UNLOCK();
1683 return;
1684 }
1685 /* Pool was full, so doesn't currently live in any list:
1686 * link it to the front of the appropriate usedpools[] list.
1687 * This mimics LRU pool usage for new allocations and
1688 * targets optimal filling when several pools contain
1689 * blocks of the same size class.
1690 */
1691 --pool->ref.count;
1692 assert(pool->ref.count > 0); /* else the pool is empty */
1693 size = pool->szidx;
1694 next = usedpools[size + size];
1695 prev = next->prevpool;
1696 /* insert pool before next: prev <-> pool <-> next */
1697 pool->nextpool = next;
1698 pool->prevpool = prev;
1699 next->prevpool = pool;
1700 prev->nextpool = pool;
1701 UNLOCK();
1702 return;
1703 }
Neil Schemenauera35c6882001-02-27 04:45:05 +00001704
Benjamin Peterson05159c42009-12-03 03:01:27 +00001705#ifdef WITH_VALGRIND
1706redirect:
1707#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001708 /* We didn't allocate this address. */
Victor Stinner6cf185d2013-10-10 15:58:42 +02001709 PyMem_RawFree(p);
Neil Schemenauera35c6882001-02-27 04:45:05 +00001710}
1711
Tim Peters84c1b972002-04-04 04:44:32 +00001712/* realloc. If p is NULL, this acts like malloc(nbytes). Else if nbytes==0,
1713 * then as the Python docs promise, we do not treat this like free(p), and
1714 * return a non-NULL result.
1715 */
Neil Schemenauera35c6882001-02-27 04:45:05 +00001716
Nick Coghlan6ba64f42013-09-29 00:28:55 +10001717ATTRIBUTE_NO_ADDRESS_SAFETY_ANALYSIS
Victor Stinner0507bf52013-07-07 02:05:46 +02001718static void *
1719_PyObject_Realloc(void *ctx, void *p, size_t nbytes)
Neil Schemenauera35c6882001-02-27 04:45:05 +00001720{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001721 void *bp;
1722 poolp pool;
1723 size_t size;
Antoine Pitroub7fb2e22011-01-07 21:43:59 +00001724#ifndef Py_USING_MEMORY_DEBUGGER
1725 uint arenaindex_temp;
1726#endif
Neil Schemenauera35c6882001-02-27 04:45:05 +00001727
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001728 if (p == NULL)
Victor Stinnerdb067af2014-05-02 22:31:14 +02001729 return _PyObject_Alloc(0, ctx, 1, nbytes);
Georg Brandld492ad82008-07-23 16:13:07 +00001730
Benjamin Peterson05159c42009-12-03 03:01:27 +00001731#ifdef WITH_VALGRIND
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001732 /* Treat running_on_valgrind == -1 the same as 0 */
1733 if (UNLIKELY(running_on_valgrind > 0))
1734 goto redirect;
Benjamin Peterson05159c42009-12-03 03:01:27 +00001735#endif
1736
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001737 pool = POOL_ADDR(p);
1738 if (Py_ADDRESS_IN_RANGE(p, pool)) {
1739 /* We're in charge of this block */
1740 size = INDEX2SIZE(pool->szidx);
1741 if (nbytes <= size) {
1742 /* The block is staying the same or shrinking. If
1743 * it's shrinking, there's a tradeoff: it costs
1744 * cycles to copy the block to a smaller size class,
1745 * but it wastes memory not to copy it. The
1746 * compromise here is to copy on shrink only if at
1747 * least 25% of size can be shaved off.
1748 */
1749 if (4 * nbytes > 3 * size) {
1750 /* It's the same,
1751 * or shrinking and new/old > 3/4.
1752 */
1753 return p;
1754 }
1755 size = nbytes;
1756 }
Victor Stinnerdb067af2014-05-02 22:31:14 +02001757 bp = _PyObject_Alloc(0, ctx, 1, nbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001758 if (bp != NULL) {
1759 memcpy(bp, p, size);
Victor Stinner0507bf52013-07-07 02:05:46 +02001760 _PyObject_Free(ctx, p);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001761 }
1762 return bp;
1763 }
Benjamin Peterson05159c42009-12-03 03:01:27 +00001764#ifdef WITH_VALGRIND
1765 redirect:
1766#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001767 /* We're not managing this block. If nbytes <=
1768 * SMALL_REQUEST_THRESHOLD, it's tempting to try to take over this
1769 * block. However, if we do, we need to copy the valid data from
1770 * the C-managed block to one of our blocks, and there's no portable
1771 * way to know how much of the memory space starting at p is valid.
1772 * As bug 1185883 pointed out the hard way, it's possible that the
1773 * C-managed block is "at the end" of allocated VM space, so that
1774 * a memory fault can occur if we try to copy nbytes bytes starting
1775 * at p. Instead we punt: let C continue to manage this block.
1776 */
1777 if (nbytes)
Victor Stinner6cf185d2013-10-10 15:58:42 +02001778 return PyMem_RawRealloc(p, nbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001779 /* C doesn't define the result of realloc(p, 0) (it may or may not
1780 * return NULL then), but Python's docs promise that nbytes==0 never
1781 * returns NULL. We don't pass 0 to realloc(), to avoid that endcase
1782 * to begin with. Even then, we can't be sure that realloc() won't
1783 * return NULL.
1784 */
Victor Stinner6cf185d2013-10-10 15:58:42 +02001785 bp = PyMem_RawRealloc(p, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001786 return bp ? bp : p;
Neil Schemenauera35c6882001-02-27 04:45:05 +00001787}
1788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001789#else /* ! WITH_PYMALLOC */
Tim Petersddea2082002-03-23 10:03:50 +00001790
1791/*==========================================================================*/
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00001792/* pymalloc not enabled: Redirect the entry points to malloc. These will
1793 * only be used by extensions that are compiled with pymalloc enabled. */
Tim Peters62c06ba2002-03-23 22:28:18 +00001794
Antoine Pitrou92840532012-12-17 23:05:59 +01001795Py_ssize_t
1796_Py_GetAllocatedBlocks(void)
1797{
1798 return 0;
1799}
1800
Tim Peters1221c0a2002-03-23 00:20:15 +00001801#endif /* WITH_PYMALLOC */
1802
Victor Stinner34be8072016-03-14 12:04:26 +01001803
Tim Petersddea2082002-03-23 10:03:50 +00001804/*==========================================================================*/
Tim Peters62c06ba2002-03-23 22:28:18 +00001805/* A x-platform debugging allocator. This doesn't manage memory directly,
1806 * it wraps a real allocator, adding extra debugging info to the memory blocks.
1807 */
Tim Petersddea2082002-03-23 10:03:50 +00001808
Tim Petersf6fb5012002-04-12 07:38:53 +00001809/* Special bytes broadcast into debug memory blocks at appropriate times.
1810 * Strings of these are unlikely to be valid addresses, floats, ints or
1811 * 7-bit ASCII.
1812 */
1813#undef CLEANBYTE
1814#undef DEADBYTE
1815#undef FORBIDDENBYTE
1816#define CLEANBYTE 0xCB /* clean (newly allocated) memory */
Tim Peters889f61d2002-07-10 19:29:49 +00001817#define DEADBYTE 0xDB /* dead (newly freed) memory */
Tim Petersf6fb5012002-04-12 07:38:53 +00001818#define FORBIDDENBYTE 0xFB /* untouchable bytes at each end of a block */
Tim Petersddea2082002-03-23 10:03:50 +00001819
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001820static size_t serialno = 0; /* incremented on each debug {m,re}alloc */
Tim Petersddea2082002-03-23 10:03:50 +00001821
Tim Peterse0850172002-03-24 00:34:21 +00001822/* serialno is always incremented via calling this routine. The point is
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001823 * to supply a single place to set a breakpoint.
1824 */
Tim Peterse0850172002-03-24 00:34:21 +00001825static void
Neil Schemenauerbd02b142002-03-28 21:05:38 +00001826bumpserialno(void)
Tim Peterse0850172002-03-24 00:34:21 +00001827{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001828 ++serialno;
Tim Peterse0850172002-03-24 00:34:21 +00001829}
1830
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001831#define SST SIZEOF_SIZE_T
Tim Peterse0850172002-03-24 00:34:21 +00001832
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001833/* Read sizeof(size_t) bytes at p as a big-endian size_t. */
1834static size_t
1835read_size_t(const void *p)
Tim Petersddea2082002-03-23 10:03:50 +00001836{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001837 const uchar *q = (const uchar *)p;
1838 size_t result = *q++;
1839 int i;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001840
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001841 for (i = SST; --i > 0; ++q)
1842 result = (result << 8) | *q;
1843 return result;
Tim Petersddea2082002-03-23 10:03:50 +00001844}
1845
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001846/* Write n as a big-endian size_t, MSB at address p, LSB at
1847 * p + sizeof(size_t) - 1.
1848 */
Tim Petersddea2082002-03-23 10:03:50 +00001849static void
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001850write_size_t(void *p, size_t n)
Tim Petersddea2082002-03-23 10:03:50 +00001851{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001852 uchar *q = (uchar *)p + SST - 1;
1853 int i;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001855 for (i = SST; --i >= 0; --q) {
1856 *q = (uchar)(n & 0xff);
1857 n >>= 8;
1858 }
Tim Petersddea2082002-03-23 10:03:50 +00001859}
1860
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001861/* Let S = sizeof(size_t). The debug malloc asks for 4*S extra bytes and
1862 fills them with useful stuff, here calling the underlying malloc's result p:
Tim Petersddea2082002-03-23 10:03:50 +00001863
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001864p[0: S]
1865 Number of bytes originally asked for. This is a size_t, big-endian (easier
1866 to read in a memory dump).
Georg Brandl7cba5fd2013-09-25 09:04:23 +02001867p[S]
Tim Petersdf099f52013-09-19 21:06:37 -05001868 API ID. See PEP 445. This is a character, but seems undocumented.
1869p[S+1: 2*S]
Tim Petersf6fb5012002-04-12 07:38:53 +00001870 Copies of FORBIDDENBYTE. Used to catch under- writes and reads.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001871p[2*S: 2*S+n]
Tim Petersf6fb5012002-04-12 07:38:53 +00001872 The requested memory, filled with copies of CLEANBYTE.
Tim Petersddea2082002-03-23 10:03:50 +00001873 Used to catch reference to uninitialized memory.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001874 &p[2*S] is returned. Note that this is 8-byte aligned if pymalloc
Tim Petersddea2082002-03-23 10:03:50 +00001875 handled the request itself.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001876p[2*S+n: 2*S+n+S]
Tim Petersf6fb5012002-04-12 07:38:53 +00001877 Copies of FORBIDDENBYTE. Used to catch over- writes and reads.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001878p[2*S+n+S: 2*S+n+2*S]
Victor Stinner0507bf52013-07-07 02:05:46 +02001879 A serial number, incremented by 1 on each call to _PyMem_DebugMalloc
1880 and _PyMem_DebugRealloc.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001881 This is a big-endian size_t.
Tim Petersddea2082002-03-23 10:03:50 +00001882 If "bad memory" is detected later, the serial number gives an
1883 excellent way to set a breakpoint on the next run, to capture the
1884 instant at which this block was passed out.
1885*/
1886
Victor Stinner0507bf52013-07-07 02:05:46 +02001887static void *
Victor Stinnerc4aec362016-03-14 22:26:53 +01001888_PyMem_DebugRawAlloc(int use_calloc, void *ctx, size_t nbytes)
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00001889{
Victor Stinner0507bf52013-07-07 02:05:46 +02001890 debug_alloc_api_t *api = (debug_alloc_api_t *)ctx;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001891 uchar *p; /* base address of malloc'ed block */
1892 uchar *tail; /* p + 2*SST + nbytes == pointer to tail pad bytes */
1893 size_t total; /* nbytes + 4*SST */
Tim Petersddea2082002-03-23 10:03:50 +00001894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001895 bumpserialno();
1896 total = nbytes + 4*SST;
Antoine Pitroucc231542014-11-02 18:40:09 +01001897 if (nbytes > PY_SSIZE_T_MAX - 4*SST)
1898 /* overflow: can't represent total as a Py_ssize_t */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001899 return NULL;
Tim Petersddea2082002-03-23 10:03:50 +00001900
Victor Stinnerdb067af2014-05-02 22:31:14 +02001901 if (use_calloc)
1902 p = (uchar *)api->alloc.calloc(api->alloc.ctx, 1, total);
1903 else
1904 p = (uchar *)api->alloc.malloc(api->alloc.ctx, total);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001905 if (p == NULL)
1906 return NULL;
Tim Petersddea2082002-03-23 10:03:50 +00001907
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001908 /* at p, write size (SST bytes), id (1 byte), pad (SST-1 bytes) */
1909 write_size_t(p, nbytes);
Victor Stinner0507bf52013-07-07 02:05:46 +02001910 p[SST] = (uchar)api->api_id;
1911 memset(p + SST + 1, FORBIDDENBYTE, SST-1);
Tim Petersddea2082002-03-23 10:03:50 +00001912
Victor Stinnerdb067af2014-05-02 22:31:14 +02001913 if (nbytes > 0 && !use_calloc)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001914 memset(p + 2*SST, CLEANBYTE, nbytes);
Tim Petersddea2082002-03-23 10:03:50 +00001915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001916 /* at tail, write pad (SST bytes) and serialno (SST bytes) */
1917 tail = p + 2*SST + nbytes;
1918 memset(tail, FORBIDDENBYTE, SST);
1919 write_size_t(tail + SST, serialno);
Tim Petersddea2082002-03-23 10:03:50 +00001920
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001921 return p + 2*SST;
Tim Petersddea2082002-03-23 10:03:50 +00001922}
1923
Victor Stinnerdb067af2014-05-02 22:31:14 +02001924static void *
Victor Stinnerc4aec362016-03-14 22:26:53 +01001925_PyMem_DebugRawMalloc(void *ctx, size_t nbytes)
Victor Stinnerdb067af2014-05-02 22:31:14 +02001926{
Victor Stinnerc4aec362016-03-14 22:26:53 +01001927 return _PyMem_DebugRawAlloc(0, ctx, nbytes);
Victor Stinnerdb067af2014-05-02 22:31:14 +02001928}
1929
1930static void *
Victor Stinnerc4aec362016-03-14 22:26:53 +01001931_PyMem_DebugRawCalloc(void *ctx, size_t nelem, size_t elsize)
Victor Stinnerdb067af2014-05-02 22:31:14 +02001932{
1933 size_t nbytes;
1934 assert(elsize == 0 || nelem <= PY_SSIZE_T_MAX / elsize);
1935 nbytes = nelem * elsize;
Victor Stinnerc4aec362016-03-14 22:26:53 +01001936 return _PyMem_DebugRawAlloc(1, ctx, nbytes);
Victor Stinnerdb067af2014-05-02 22:31:14 +02001937}
1938
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001939/* 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 +00001940 particular, that the FORBIDDENBYTEs with the api ID are still intact).
Tim Petersf6fb5012002-04-12 07:38:53 +00001941 Then fills the original bytes with DEADBYTE.
Tim Petersddea2082002-03-23 10:03:50 +00001942 Then calls the underlying free.
1943*/
Victor Stinner0507bf52013-07-07 02:05:46 +02001944static void
Victor Stinnerc4aec362016-03-14 22:26:53 +01001945_PyMem_DebugRawFree(void *ctx, void *p)
Tim Petersddea2082002-03-23 10:03:50 +00001946{
Victor Stinner0507bf52013-07-07 02:05:46 +02001947 debug_alloc_api_t *api = (debug_alloc_api_t *)ctx;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001948 uchar *q = (uchar *)p - 2*SST; /* address returned from malloc */
1949 size_t nbytes;
Tim Petersddea2082002-03-23 10:03:50 +00001950
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001951 if (p == NULL)
1952 return;
Victor Stinner0507bf52013-07-07 02:05:46 +02001953 _PyMem_DebugCheckAddress(api->api_id, p);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001954 nbytes = read_size_t(q);
1955 nbytes += 4*SST;
1956 if (nbytes > 0)
1957 memset(q, DEADBYTE, nbytes);
Victor Stinner0507bf52013-07-07 02:05:46 +02001958 api->alloc.free(api->alloc.ctx, q);
Tim Petersddea2082002-03-23 10:03:50 +00001959}
1960
Victor Stinner0507bf52013-07-07 02:05:46 +02001961static void *
Victor Stinnerc4aec362016-03-14 22:26:53 +01001962_PyMem_DebugRawRealloc(void *ctx, void *p, size_t nbytes)
Tim Petersddea2082002-03-23 10:03:50 +00001963{
Victor Stinner0507bf52013-07-07 02:05:46 +02001964 debug_alloc_api_t *api = (debug_alloc_api_t *)ctx;
Victor Stinnerc4266362013-07-09 00:44:43 +02001965 uchar *q = (uchar *)p, *oldq;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001966 uchar *tail;
1967 size_t total; /* nbytes + 4*SST */
1968 size_t original_nbytes;
1969 int i;
Tim Petersddea2082002-03-23 10:03:50 +00001970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001971 if (p == NULL)
Victor Stinnerc4aec362016-03-14 22:26:53 +01001972 return _PyMem_DebugRawAlloc(0, ctx, nbytes);
Tim Petersddea2082002-03-23 10:03:50 +00001973
Victor Stinner0507bf52013-07-07 02:05:46 +02001974 _PyMem_DebugCheckAddress(api->api_id, p);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001975 bumpserialno();
1976 original_nbytes = read_size_t(q - 2*SST);
1977 total = nbytes + 4*SST;
Antoine Pitroucc231542014-11-02 18:40:09 +01001978 if (nbytes > PY_SSIZE_T_MAX - 4*SST)
1979 /* overflow: can't represent total as a Py_ssize_t */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001980 return NULL;
Tim Petersddea2082002-03-23 10:03:50 +00001981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001982 /* Resize and add decorations. We may get a new pointer here, in which
1983 * case we didn't get the chance to mark the old memory with DEADBYTE,
1984 * but we live with that.
1985 */
Victor Stinnerc4266362013-07-09 00:44:43 +02001986 oldq = q;
Victor Stinner0507bf52013-07-07 02:05:46 +02001987 q = (uchar *)api->alloc.realloc(api->alloc.ctx, q - 2*SST, total);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001988 if (q == NULL)
1989 return NULL;
Tim Peters85cc1c42002-04-12 08:52:50 +00001990
Victor Stinnerc4266362013-07-09 00:44:43 +02001991 if (q == oldq && nbytes < original_nbytes) {
1992 /* shrinking: mark old extra memory dead */
1993 memset(q + nbytes, DEADBYTE, original_nbytes - nbytes);
1994 }
1995
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001996 write_size_t(q, nbytes);
Victor Stinner0507bf52013-07-07 02:05:46 +02001997 assert(q[SST] == (uchar)api->api_id);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001998 for (i = 1; i < SST; ++i)
1999 assert(q[SST + i] == FORBIDDENBYTE);
2000 q += 2*SST;
Victor Stinnerc4266362013-07-09 00:44:43 +02002001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002002 tail = q + nbytes;
2003 memset(tail, FORBIDDENBYTE, SST);
2004 write_size_t(tail + SST, serialno);
Tim Peters85cc1c42002-04-12 08:52:50 +00002005
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002006 if (nbytes > original_nbytes) {
2007 /* growing: mark new extra memory clean */
2008 memset(q + original_nbytes, CLEANBYTE,
Stefan Krah735bb122010-11-26 10:54:09 +00002009 nbytes - original_nbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002010 }
Tim Peters85cc1c42002-04-12 08:52:50 +00002011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002012 return q;
Tim Petersddea2082002-03-23 10:03:50 +00002013}
2014
Victor Stinnerc4aec362016-03-14 22:26:53 +01002015static void
2016_PyMem_DebugCheckGIL(void)
2017{
2018#ifdef WITH_THREAD
2019 if (!PyGILState_Check())
2020 Py_FatalError("Python memory allocator called "
2021 "without holding the GIL");
2022#endif
2023}
2024
2025static void *
2026_PyMem_DebugMalloc(void *ctx, size_t nbytes)
2027{
2028 _PyMem_DebugCheckGIL();
2029 return _PyMem_DebugRawMalloc(ctx, nbytes);
2030}
2031
2032static void *
2033_PyMem_DebugCalloc(void *ctx, size_t nelem, size_t elsize)
2034{
2035 _PyMem_DebugCheckGIL();
2036 return _PyMem_DebugRawCalloc(ctx, nelem, elsize);
2037}
2038
2039static void
2040_PyMem_DebugFree(void *ctx, void *ptr)
2041{
2042 _PyMem_DebugCheckGIL();
Victor Stinner0aed3a42016-03-23 11:30:43 +01002043 _PyMem_DebugRawFree(ctx, ptr);
Victor Stinnerc4aec362016-03-14 22:26:53 +01002044}
2045
2046static void *
2047_PyMem_DebugRealloc(void *ctx, void *ptr, size_t nbytes)
2048{
2049 _PyMem_DebugCheckGIL();
2050 return _PyMem_DebugRawRealloc(ctx, ptr, nbytes);
2051}
2052
Tim Peters7ccfadf2002-04-01 06:04:21 +00002053/* Check the forbidden bytes on both ends of the memory allocated for p.
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00002054 * If anything is wrong, print info to stderr via _PyObject_DebugDumpAddress,
Tim Peters7ccfadf2002-04-01 06:04:21 +00002055 * and call Py_FatalError to kill the program.
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00002056 * The API id, is also checked.
Tim Peters7ccfadf2002-04-01 06:04:21 +00002057 */
Victor Stinner0507bf52013-07-07 02:05:46 +02002058static void
2059_PyMem_DebugCheckAddress(char api, const void *p)
Tim Petersddea2082002-03-23 10:03:50 +00002060{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002061 const uchar *q = (const uchar *)p;
2062 char msgbuf[64];
2063 char *msg;
2064 size_t nbytes;
2065 const uchar *tail;
2066 int i;
2067 char id;
Tim Petersddea2082002-03-23 10:03:50 +00002068
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002069 if (p == NULL) {
2070 msg = "didn't expect a NULL pointer";
2071 goto error;
2072 }
Tim Petersddea2082002-03-23 10:03:50 +00002073
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002074 /* Check the API id */
2075 id = (char)q[-SST];
2076 if (id != api) {
2077 msg = msgbuf;
2078 snprintf(msg, sizeof(msgbuf), "bad ID: Allocated using API '%c', verified using API '%c'", id, api);
2079 msgbuf[sizeof(msgbuf)-1] = 0;
2080 goto error;
2081 }
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00002082
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002083 /* Check the stuff at the start of p first: if there's underwrite
2084 * corruption, the number-of-bytes field may be nuts, and checking
2085 * the tail could lead to a segfault then.
2086 */
2087 for (i = SST-1; i >= 1; --i) {
2088 if (*(q-i) != FORBIDDENBYTE) {
2089 msg = "bad leading pad byte";
2090 goto error;
2091 }
2092 }
Tim Petersddea2082002-03-23 10:03:50 +00002093
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002094 nbytes = read_size_t(q - 2*SST);
2095 tail = q + nbytes;
2096 for (i = 0; i < SST; ++i) {
2097 if (tail[i] != FORBIDDENBYTE) {
2098 msg = "bad trailing pad byte";
2099 goto error;
2100 }
2101 }
Tim Petersddea2082002-03-23 10:03:50 +00002102
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002103 return;
Tim Petersd1139e02002-03-28 07:32:11 +00002104
2105error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002106 _PyObject_DebugDumpAddress(p);
2107 Py_FatalError(msg);
Tim Petersddea2082002-03-23 10:03:50 +00002108}
2109
Tim Peters7ccfadf2002-04-01 06:04:21 +00002110/* Display info to stderr about the memory block at p. */
Victor Stinner0507bf52013-07-07 02:05:46 +02002111static void
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00002112_PyObject_DebugDumpAddress(const void *p)
Tim Petersddea2082002-03-23 10:03:50 +00002113{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002114 const uchar *q = (const uchar *)p;
2115 const uchar *tail;
2116 size_t nbytes, serial;
2117 int i;
2118 int ok;
2119 char id;
Tim Petersddea2082002-03-23 10:03:50 +00002120
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002121 fprintf(stderr, "Debug memory block at address p=%p:", p);
2122 if (p == NULL) {
2123 fprintf(stderr, "\n");
2124 return;
2125 }
2126 id = (char)q[-SST];
2127 fprintf(stderr, " API '%c'\n", id);
Tim Petersddea2082002-03-23 10:03:50 +00002128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002129 nbytes = read_size_t(q - 2*SST);
2130 fprintf(stderr, " %" PY_FORMAT_SIZE_T "u bytes originally "
2131 "requested\n", nbytes);
Tim Petersddea2082002-03-23 10:03:50 +00002132
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002133 /* In case this is nuts, check the leading pad bytes first. */
2134 fprintf(stderr, " The %d pad bytes at p-%d are ", SST-1, SST-1);
2135 ok = 1;
2136 for (i = 1; i <= SST-1; ++i) {
2137 if (*(q-i) != FORBIDDENBYTE) {
2138 ok = 0;
2139 break;
2140 }
2141 }
2142 if (ok)
2143 fputs("FORBIDDENBYTE, as expected.\n", stderr);
2144 else {
2145 fprintf(stderr, "not all FORBIDDENBYTE (0x%02x):\n",
2146 FORBIDDENBYTE);
2147 for (i = SST-1; i >= 1; --i) {
2148 const uchar byte = *(q-i);
2149 fprintf(stderr, " at p-%d: 0x%02x", i, byte);
2150 if (byte != FORBIDDENBYTE)
2151 fputs(" *** OUCH", stderr);
2152 fputc('\n', stderr);
2153 }
Tim Peters449b5a82002-04-28 06:14:45 +00002154
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002155 fputs(" Because memory is corrupted at the start, the "
2156 "count of bytes requested\n"
2157 " may be bogus, and checking the trailing pad "
2158 "bytes may segfault.\n", stderr);
2159 }
Tim Petersddea2082002-03-23 10:03:50 +00002160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002161 tail = q + nbytes;
2162 fprintf(stderr, " The %d pad bytes at tail=%p are ", SST, tail);
2163 ok = 1;
2164 for (i = 0; i < SST; ++i) {
2165 if (tail[i] != FORBIDDENBYTE) {
2166 ok = 0;
2167 break;
2168 }
2169 }
2170 if (ok)
2171 fputs("FORBIDDENBYTE, as expected.\n", stderr);
2172 else {
2173 fprintf(stderr, "not all FORBIDDENBYTE (0x%02x):\n",
Stefan Krah735bb122010-11-26 10:54:09 +00002174 FORBIDDENBYTE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002175 for (i = 0; i < SST; ++i) {
2176 const uchar byte = tail[i];
2177 fprintf(stderr, " at tail+%d: 0x%02x",
Stefan Krah735bb122010-11-26 10:54:09 +00002178 i, byte);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002179 if (byte != FORBIDDENBYTE)
2180 fputs(" *** OUCH", stderr);
2181 fputc('\n', stderr);
2182 }
2183 }
Tim Petersddea2082002-03-23 10:03:50 +00002184
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002185 serial = read_size_t(tail + SST);
2186 fprintf(stderr, " The block was made by call #%" PY_FORMAT_SIZE_T
2187 "u to debug malloc/realloc.\n", serial);
Tim Petersddea2082002-03-23 10:03:50 +00002188
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002189 if (nbytes > 0) {
2190 i = 0;
2191 fputs(" Data at p:", stderr);
2192 /* print up to 8 bytes at the start */
2193 while (q < tail && i < 8) {
2194 fprintf(stderr, " %02x", *q);
2195 ++i;
2196 ++q;
2197 }
2198 /* and up to 8 at the end */
2199 if (q < tail) {
2200 if (tail - q > 8) {
2201 fputs(" ...", stderr);
2202 q = tail - 8;
2203 }
2204 while (q < tail) {
2205 fprintf(stderr, " %02x", *q);
2206 ++q;
2207 }
2208 }
2209 fputc('\n', stderr);
2210 }
Victor Stinner0611c262016-03-15 22:22:13 +01002211 fputc('\n', stderr);
2212
2213 fflush(stderr);
2214 _PyMem_DumpTraceback(fileno(stderr), p);
Tim Petersddea2082002-03-23 10:03:50 +00002215}
2216
David Malcolm49526f42012-06-22 14:55:41 -04002217
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00002218static size_t
David Malcolm49526f42012-06-22 14:55:41 -04002219printone(FILE *out, const char* msg, size_t value)
Tim Peters16bcb6b2002-04-05 05:45:31 +00002220{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002221 int i, k;
2222 char buf[100];
2223 size_t origvalue = value;
Tim Peters16bcb6b2002-04-05 05:45:31 +00002224
David Malcolm49526f42012-06-22 14:55:41 -04002225 fputs(msg, out);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002226 for (i = (int)strlen(msg); i < 35; ++i)
David Malcolm49526f42012-06-22 14:55:41 -04002227 fputc(' ', out);
2228 fputc('=', out);
Tim Peters49f26812002-04-06 01:45:35 +00002229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002230 /* Write the value with commas. */
2231 i = 22;
2232 buf[i--] = '\0';
2233 buf[i--] = '\n';
2234 k = 3;
2235 do {
2236 size_t nextvalue = value / 10;
Benjamin Peterson2dba1ee2013-02-20 16:54:30 -05002237 unsigned int digit = (unsigned int)(value - nextvalue * 10);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002238 value = nextvalue;
2239 buf[i--] = (char)(digit + '0');
2240 --k;
2241 if (k == 0 && value && i >= 0) {
2242 k = 3;
2243 buf[i--] = ',';
2244 }
2245 } while (value && i >= 0);
Tim Peters49f26812002-04-06 01:45:35 +00002246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002247 while (i >= 0)
2248 buf[i--] = ' ';
David Malcolm49526f42012-06-22 14:55:41 -04002249 fputs(buf, out);
Tim Peters49f26812002-04-06 01:45:35 +00002250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002251 return origvalue;
Tim Peters16bcb6b2002-04-05 05:45:31 +00002252}
2253
David Malcolm49526f42012-06-22 14:55:41 -04002254void
2255_PyDebugAllocatorStats(FILE *out,
2256 const char *block_name, int num_blocks, size_t sizeof_block)
2257{
2258 char buf1[128];
2259 char buf2[128];
2260 PyOS_snprintf(buf1, sizeof(buf1),
Tim Peterseaa3bcc2013-09-05 22:57:04 -05002261 "%d %ss * %" PY_FORMAT_SIZE_T "d bytes each",
David Malcolm49526f42012-06-22 14:55:41 -04002262 num_blocks, block_name, sizeof_block);
2263 PyOS_snprintf(buf2, sizeof(buf2),
2264 "%48s ", buf1);
2265 (void)printone(out, buf2, num_blocks * sizeof_block);
2266}
2267
Victor Stinner34be8072016-03-14 12:04:26 +01002268
David Malcolm49526f42012-06-22 14:55:41 -04002269#ifdef WITH_PYMALLOC
2270
Victor Stinner34be8072016-03-14 12:04:26 +01002271#ifdef Py_DEBUG
2272/* Is target in the list? The list is traversed via the nextpool pointers.
2273 * The list may be NULL-terminated, or circular. Return 1 if target is in
2274 * list, else 0.
2275 */
2276static int
2277pool_is_in_list(const poolp target, poolp list)
2278{
2279 poolp origlist = list;
2280 assert(target != NULL);
2281 if (list == NULL)
2282 return 0;
2283 do {
2284 if (target == list)
2285 return 1;
2286 list = list->nextpool;
2287 } while (list != NULL && list != origlist);
2288 return 0;
2289}
2290#endif
2291
David Malcolm49526f42012-06-22 14:55:41 -04002292/* Print summary info to "out" about the state of pymalloc's structures.
Tim Peters08d82152002-04-18 22:25:03 +00002293 * In Py_DEBUG mode, also perform some expensive internal consistency
2294 * checks.
2295 */
Tim Peters7ccfadf2002-04-01 06:04:21 +00002296void
David Malcolm49526f42012-06-22 14:55:41 -04002297_PyObject_DebugMallocStats(FILE *out)
Tim Peters7ccfadf2002-04-01 06:04:21 +00002298{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002299 uint i;
2300 const uint numclasses = SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT;
2301 /* # of pools, allocated blocks, and free blocks per class index */
2302 size_t numpools[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT];
2303 size_t numblocks[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT];
2304 size_t numfreeblocks[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT];
2305 /* total # of allocated bytes in used and full pools */
2306 size_t allocated_bytes = 0;
2307 /* total # of available bytes in used pools */
2308 size_t available_bytes = 0;
2309 /* # of free pools + pools not yet carved out of current arena */
2310 uint numfreepools = 0;
2311 /* # of bytes for arena alignment padding */
2312 size_t arena_alignment = 0;
2313 /* # of bytes in used and full pools used for pool_headers */
2314 size_t pool_header_bytes = 0;
2315 /* # of bytes in used and full pools wasted due to quantization,
2316 * i.e. the necessarily leftover space at the ends of used and
2317 * full pools.
2318 */
2319 size_t quantization = 0;
2320 /* # of arenas actually allocated. */
2321 size_t narenas = 0;
2322 /* running total -- should equal narenas * ARENA_SIZE */
2323 size_t total;
2324 char buf[128];
Tim Peters7ccfadf2002-04-01 06:04:21 +00002325
David Malcolm49526f42012-06-22 14:55:41 -04002326 fprintf(out, "Small block threshold = %d, in %u size classes.\n",
Stefan Krah735bb122010-11-26 10:54:09 +00002327 SMALL_REQUEST_THRESHOLD, numclasses);
Tim Peters7ccfadf2002-04-01 06:04:21 +00002328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002329 for (i = 0; i < numclasses; ++i)
2330 numpools[i] = numblocks[i] = numfreeblocks[i] = 0;
Tim Peters7ccfadf2002-04-01 06:04:21 +00002331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002332 /* Because full pools aren't linked to from anything, it's easiest
2333 * to march over all the arenas. If we're lucky, most of the memory
2334 * will be living in full pools -- would be a shame to miss them.
2335 */
2336 for (i = 0; i < maxarenas; ++i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002337 uint j;
2338 uptr base = arenas[i].address;
Thomas Woutersa9773292006-04-21 09:43:23 +00002339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002340 /* Skip arenas which are not allocated. */
2341 if (arenas[i].address == (uptr)NULL)
2342 continue;
2343 narenas += 1;
Thomas Woutersa9773292006-04-21 09:43:23 +00002344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002345 numfreepools += arenas[i].nfreepools;
Tim Peters7ccfadf2002-04-01 06:04:21 +00002346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002347 /* round up to pool alignment */
2348 if (base & (uptr)POOL_SIZE_MASK) {
2349 arena_alignment += POOL_SIZE;
2350 base &= ~(uptr)POOL_SIZE_MASK;
2351 base += POOL_SIZE;
2352 }
Tim Peters7ccfadf2002-04-01 06:04:21 +00002353
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002354 /* visit every pool in the arena */
2355 assert(base <= (uptr) arenas[i].pool_address);
2356 for (j = 0;
2357 base < (uptr) arenas[i].pool_address;
2358 ++j, base += POOL_SIZE) {
2359 poolp p = (poolp)base;
2360 const uint sz = p->szidx;
2361 uint freeblocks;
Tim Peters08d82152002-04-18 22:25:03 +00002362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002363 if (p->ref.count == 0) {
2364 /* currently unused */
Victor Stinner34be8072016-03-14 12:04:26 +01002365#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002366 assert(pool_is_in_list(p, arenas[i].freepools));
Victor Stinner34be8072016-03-14 12:04:26 +01002367#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002368 continue;
2369 }
2370 ++numpools[sz];
2371 numblocks[sz] += p->ref.count;
2372 freeblocks = NUMBLOCKS(sz) - p->ref.count;
2373 numfreeblocks[sz] += freeblocks;
Tim Peters08d82152002-04-18 22:25:03 +00002374#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002375 if (freeblocks > 0)
2376 assert(pool_is_in_list(p, usedpools[sz + sz]));
Tim Peters08d82152002-04-18 22:25:03 +00002377#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002378 }
2379 }
2380 assert(narenas == narenas_currently_allocated);
Tim Peters7ccfadf2002-04-01 06:04:21 +00002381
David Malcolm49526f42012-06-22 14:55:41 -04002382 fputc('\n', out);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002383 fputs("class size num pools blocks in use avail blocks\n"
2384 "----- ---- --------- ------------- ------------\n",
David Malcolm49526f42012-06-22 14:55:41 -04002385 out);
Tim Peters7ccfadf2002-04-01 06:04:21 +00002386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002387 for (i = 0; i < numclasses; ++i) {
2388 size_t p = numpools[i];
2389 size_t b = numblocks[i];
2390 size_t f = numfreeblocks[i];
2391 uint size = INDEX2SIZE(i);
2392 if (p == 0) {
2393 assert(b == 0 && f == 0);
2394 continue;
2395 }
David Malcolm49526f42012-06-22 14:55:41 -04002396 fprintf(out, "%5u %6u "
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002397 "%11" PY_FORMAT_SIZE_T "u "
2398 "%15" PY_FORMAT_SIZE_T "u "
2399 "%13" PY_FORMAT_SIZE_T "u\n",
Stefan Krah735bb122010-11-26 10:54:09 +00002400 i, size, p, b, f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002401 allocated_bytes += b * size;
2402 available_bytes += f * size;
2403 pool_header_bytes += p * POOL_OVERHEAD;
2404 quantization += p * ((POOL_SIZE - POOL_OVERHEAD) % size);
2405 }
David Malcolm49526f42012-06-22 14:55:41 -04002406 fputc('\n', out);
Victor Stinner34be8072016-03-14 12:04:26 +01002407 if (_PyMem_DebugEnabled())
2408 (void)printone(out, "# times object malloc called", serialno);
David Malcolm49526f42012-06-22 14:55:41 -04002409 (void)printone(out, "# arenas allocated total", ntimes_arena_allocated);
2410 (void)printone(out, "# arenas reclaimed", ntimes_arena_allocated - narenas);
2411 (void)printone(out, "# arenas highwater mark", narenas_highwater);
2412 (void)printone(out, "# arenas allocated current", narenas);
Thomas Woutersa9773292006-04-21 09:43:23 +00002413
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002414 PyOS_snprintf(buf, sizeof(buf),
2415 "%" PY_FORMAT_SIZE_T "u arenas * %d bytes/arena",
2416 narenas, ARENA_SIZE);
David Malcolm49526f42012-06-22 14:55:41 -04002417 (void)printone(out, buf, narenas * ARENA_SIZE);
Tim Peters16bcb6b2002-04-05 05:45:31 +00002418
David Malcolm49526f42012-06-22 14:55:41 -04002419 fputc('\n', out);
Tim Peters16bcb6b2002-04-05 05:45:31 +00002420
David Malcolm49526f42012-06-22 14:55:41 -04002421 total = printone(out, "# bytes in allocated blocks", allocated_bytes);
2422 total += printone(out, "# bytes in available blocks", available_bytes);
Tim Peters49f26812002-04-06 01:45:35 +00002423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002424 PyOS_snprintf(buf, sizeof(buf),
2425 "%u unused pools * %d bytes", numfreepools, POOL_SIZE);
David Malcolm49526f42012-06-22 14:55:41 -04002426 total += printone(out, buf, (size_t)numfreepools * POOL_SIZE);
Tim Peters16bcb6b2002-04-05 05:45:31 +00002427
David Malcolm49526f42012-06-22 14:55:41 -04002428 total += printone(out, "# bytes lost to pool headers", pool_header_bytes);
2429 total += printone(out, "# bytes lost to quantization", quantization);
2430 total += printone(out, "# bytes lost to arena alignment", arena_alignment);
2431 (void)printone(out, "Total", total);
Tim Peters7ccfadf2002-04-01 06:04:21 +00002432}
2433
David Malcolm49526f42012-06-22 14:55:41 -04002434#endif /* #ifdef WITH_PYMALLOC */
Neal Norwitz7eb3c912004-06-06 19:20:22 +00002435
Victor Stinner34be8072016-03-14 12:04:26 +01002436
Neal Norwitz7eb3c912004-06-06 19:20:22 +00002437#ifdef Py_USING_MEMORY_DEBUGGER
Thomas Woutersa9773292006-04-21 09:43:23 +00002438/* Make this function last so gcc won't inline it since the definition is
2439 * after the reference.
2440 */
Neal Norwitz7eb3c912004-06-06 19:20:22 +00002441int
2442Py_ADDRESS_IN_RANGE(void *P, poolp pool)
2443{
Antoine Pitroub7fb2e22011-01-07 21:43:59 +00002444 uint arenaindex_temp = pool->arenaindex;
2445
2446 return arenaindex_temp < maxarenas &&
2447 (uptr)P - arenas[arenaindex_temp].address < (uptr)ARENA_SIZE &&
2448 arenas[arenaindex_temp].address != 0;
Neal Norwitz7eb3c912004-06-06 19:20:22 +00002449}
2450#endif