blob: 1b8b5eefe2119000d5230b11e9eeebacda432c39 [file] [log] [blame]
Tim Peters1221c0a2002-03-23 00:20:15 +00001#include "Python.h"
2
Benjamin Peterson3924f932016-09-18 19:12:48 -07003#include <stdbool.h>
4
Victor Stinner0611c262016-03-15 22:22:13 +01005
6/* Defined in tracemalloc.c */
7extern void _PyMem_DumpTraceback(int fd, const void *ptr);
8
9
Victor Stinner0507bf52013-07-07 02:05:46 +020010/* Python's malloc wrappers (see pymem.h) */
11
Victor Stinner34be807c2016-03-14 12:04:26 +010012#undef uint
13#define uint unsigned int /* assuming >= 16 bits */
14
Victor Stinner0507bf52013-07-07 02:05:46 +020015/* Forward declaration */
Victor Stinnerc4aec362016-03-14 22:26:53 +010016static void* _PyMem_DebugRawMalloc(void *ctx, size_t size);
17static void* _PyMem_DebugRawCalloc(void *ctx, size_t nelem, size_t elsize);
18static void* _PyMem_DebugRawRealloc(void *ctx, void *ptr, size_t size);
Victor Stinner9ed83c42017-10-31 12:18:10 -070019static void _PyMem_DebugRawFree(void *ctx, void *ptr);
Victor Stinnerc4aec362016-03-14 22:26:53 +010020
Victor Stinner0507bf52013-07-07 02:05:46 +020021static void* _PyMem_DebugMalloc(void *ctx, size_t size);
Victor Stinnerdb067af2014-05-02 22:31:14 +020022static void* _PyMem_DebugCalloc(void *ctx, size_t nelem, size_t elsize);
Victor Stinner0507bf52013-07-07 02:05:46 +020023static void* _PyMem_DebugRealloc(void *ctx, void *ptr, size_t size);
Victor Stinnerc4aec362016-03-14 22:26:53 +010024static void _PyMem_DebugFree(void *ctx, void *p);
Victor Stinner0507bf52013-07-07 02:05:46 +020025
26static void _PyObject_DebugDumpAddress(const void *p);
27static void _PyMem_DebugCheckAddress(char api_id, const void *p);
Victor Stinner0507bf52013-07-07 02:05:46 +020028
Victor Stinner5d39e042017-11-29 17:20:38 +010029static void _PyMem_SetupDebugHooksDomain(PyMemAllocatorDomain domain);
30
Nick Coghlan6ba64f42013-09-29 00:28:55 +100031#if defined(__has_feature) /* Clang */
Miss Islington (bot)1ec57812018-11-11 15:44:34 -080032# if __has_feature(address_sanitizer) /* is ASAN enabled? */
33# define _Py_NO_ADDRESS_SAFETY_ANALYSIS \
Benjamin Peterson3924f932016-09-18 19:12:48 -070034 __attribute__((no_address_safety_analysis))
Miss Islington (bot)1ec57812018-11-11 15:44:34 -080035# endif
36# if __has_feature(thread_sanitizer) /* is TSAN enabled? */
37# define _Py_NO_SANITIZE_THREAD __attribute__((no_sanitize_thread))
38# endif
39# if __has_feature(memory_sanitizer) /* is MSAN enabled? */
40# define _Py_NO_SANITIZE_MEMORY __attribute__((no_sanitize_memory))
41# endif
42#elif defined(__GNUC__)
43# if defined(__SANITIZE_ADDRESS__) /* GCC 4.8+, is ASAN enabled? */
44# define _Py_NO_ADDRESS_SAFETY_ANALYSIS \
Benjamin Peterson3924f932016-09-18 19:12:48 -070045 __attribute__((no_address_safety_analysis))
Miss Islington (bot)1ec57812018-11-11 15:44:34 -080046# endif
47 // TSAN is supported since GCC 4.8, but __SANITIZE_THREAD__ macro
48 // is provided only since GCC 7.
49# if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8)
50# define _Py_NO_SANITIZE_THREAD __attribute__((no_sanitize_thread))
51# endif
52#endif
53
54#ifndef _Py_NO_ADDRESS_SAFETY_ANALYSIS
55# define _Py_NO_ADDRESS_SAFETY_ANALYSIS
56#endif
57#ifndef _Py_NO_SANITIZE_THREAD
58# define _Py_NO_SANITIZE_THREAD
59#endif
60#ifndef _Py_NO_SANITIZE_MEMORY
61# define _Py_NO_SANITIZE_MEMORY
Nick Coghlan6ba64f42013-09-29 00:28:55 +100062#endif
63
Tim Peters1221c0a2002-03-23 00:20:15 +000064#ifdef WITH_PYMALLOC
65
Victor Stinner0507bf52013-07-07 02:05:46 +020066#ifdef MS_WINDOWS
67# include <windows.h>
68#elif defined(HAVE_MMAP)
69# include <sys/mman.h>
70# ifdef MAP_ANONYMOUS
71# define ARENAS_USE_MMAP
72# endif
Antoine Pitrou6f26be02011-05-03 18:18:59 +020073#endif
74
Victor Stinner0507bf52013-07-07 02:05:46 +020075/* Forward declaration */
76static void* _PyObject_Malloc(void *ctx, size_t size);
Victor Stinnerdb067af2014-05-02 22:31:14 +020077static void* _PyObject_Calloc(void *ctx, size_t nelem, size_t elsize);
Victor Stinner0507bf52013-07-07 02:05:46 +020078static void _PyObject_Free(void *ctx, void *p);
79static void* _PyObject_Realloc(void *ctx, void *ptr, size_t size);
Martin v. Löwiscd83fa82013-06-27 12:23:29 +020080#endif
81
Victor Stinner0507bf52013-07-07 02:05:46 +020082
83static void *
84_PyMem_RawMalloc(void *ctx, size_t size)
85{
Victor Stinnerdb067af2014-05-02 22:31:14 +020086 /* PyMem_RawMalloc(0) means malloc(1). Some systems would return NULL
Victor Stinner0507bf52013-07-07 02:05:46 +020087 for malloc(0), which would be treated as an error. Some platforms would
88 return a pointer with no memory behind it, which would break pymalloc.
89 To solve these problems, allocate an extra byte. */
90 if (size == 0)
91 size = 1;
92 return malloc(size);
93}
94
95static void *
Victor Stinnerdb067af2014-05-02 22:31:14 +020096_PyMem_RawCalloc(void *ctx, size_t nelem, size_t elsize)
97{
98 /* PyMem_RawCalloc(0, 0) means calloc(1, 1). Some systems would return NULL
99 for calloc(0, 0), which would be treated as an error. Some platforms
100 would return a pointer with no memory behind it, which would break
101 pymalloc. To solve these problems, allocate an extra byte. */
102 if (nelem == 0 || elsize == 0) {
103 nelem = 1;
104 elsize = 1;
105 }
106 return calloc(nelem, elsize);
107}
108
109static void *
Victor Stinner0507bf52013-07-07 02:05:46 +0200110_PyMem_RawRealloc(void *ctx, void *ptr, size_t size)
111{
112 if (size == 0)
113 size = 1;
114 return realloc(ptr, size);
115}
116
117static void
118_PyMem_RawFree(void *ctx, void *ptr)
119{
120 free(ptr);
121}
122
123
124#ifdef MS_WINDOWS
125static void *
126_PyObject_ArenaVirtualAlloc(void *ctx, size_t size)
127{
128 return VirtualAlloc(NULL, size,
129 MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
130}
131
132static void
133_PyObject_ArenaVirtualFree(void *ctx, void *ptr, size_t size)
134{
Victor Stinner725e6682013-07-07 03:06:16 +0200135 VirtualFree(ptr, 0, MEM_RELEASE);
Victor Stinner0507bf52013-07-07 02:05:46 +0200136}
137
138#elif defined(ARENAS_USE_MMAP)
139static void *
140_PyObject_ArenaMmap(void *ctx, size_t size)
141{
142 void *ptr;
143 ptr = mmap(NULL, size, PROT_READ|PROT_WRITE,
144 MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
145 if (ptr == MAP_FAILED)
146 return NULL;
147 assert(ptr != NULL);
148 return ptr;
149}
150
151static void
152_PyObject_ArenaMunmap(void *ctx, void *ptr, size_t size)
153{
154 munmap(ptr, size);
155}
156
157#else
158static void *
159_PyObject_ArenaMalloc(void *ctx, size_t size)
160{
161 return malloc(size);
162}
163
164static void
165_PyObject_ArenaFree(void *ctx, void *ptr, size_t size)
166{
167 free(ptr);
168}
169#endif
170
Victor Stinner5d39e042017-11-29 17:20:38 +0100171#define MALLOC_ALLOC {NULL, _PyMem_RawMalloc, _PyMem_RawCalloc, _PyMem_RawRealloc, _PyMem_RawFree}
Victor Stinner0507bf52013-07-07 02:05:46 +0200172#ifdef WITH_PYMALLOC
Victor Stinner5d39e042017-11-29 17:20:38 +0100173# define PYMALLOC_ALLOC {NULL, _PyObject_Malloc, _PyObject_Calloc, _PyObject_Realloc, _PyObject_Free}
Victor Stinner0507bf52013-07-07 02:05:46 +0200174#endif
Victor Stinner5d39e042017-11-29 17:20:38 +0100175
176#define PYRAW_ALLOC MALLOC_ALLOC
177#ifdef WITH_PYMALLOC
178# define PYOBJ_ALLOC PYMALLOC_ALLOC
179#else
180# define PYOBJ_ALLOC MALLOC_ALLOC
181#endif
182#define PYMEM_ALLOC PYOBJ_ALLOC
Victor Stinner0507bf52013-07-07 02:05:46 +0200183
Victor Stinner0507bf52013-07-07 02:05:46 +0200184typedef struct {
185 /* We tag each block with an API ID in order to tag API violations */
186 char api_id;
Victor Stinnerd8f0d922014-06-02 21:57:10 +0200187 PyMemAllocatorEx alloc;
Victor Stinner0507bf52013-07-07 02:05:46 +0200188} debug_alloc_api_t;
189static struct {
190 debug_alloc_api_t raw;
191 debug_alloc_api_t mem;
192 debug_alloc_api_t obj;
193} _PyMem_Debug = {
Victor Stinner5d39e042017-11-29 17:20:38 +0100194 {'r', PYRAW_ALLOC},
195 {'m', PYMEM_ALLOC},
196 {'o', PYOBJ_ALLOC}
Victor Stinner0507bf52013-07-07 02:05:46 +0200197 };
198
Victor Stinner5d39e042017-11-29 17:20:38 +0100199#define PYDBGRAW_ALLOC \
200 {&_PyMem_Debug.raw, _PyMem_DebugRawMalloc, _PyMem_DebugRawCalloc, _PyMem_DebugRawRealloc, _PyMem_DebugRawFree}
201#define PYDBGMEM_ALLOC \
202 {&_PyMem_Debug.mem, _PyMem_DebugMalloc, _PyMem_DebugCalloc, _PyMem_DebugRealloc, _PyMem_DebugFree}
203#define PYDBGOBJ_ALLOC \
204 {&_PyMem_Debug.obj, _PyMem_DebugMalloc, _PyMem_DebugCalloc, _PyMem_DebugRealloc, _PyMem_DebugFree}
Victor Stinner0507bf52013-07-07 02:05:46 +0200205
Victor Stinner9e87e772017-11-24 12:09:24 +0100206#ifdef Py_DEBUG
Victor Stinner5d39e042017-11-29 17:20:38 +0100207static PyMemAllocatorEx _PyMem_Raw = PYDBGRAW_ALLOC;
208static PyMemAllocatorEx _PyMem = PYDBGMEM_ALLOC;
209static PyMemAllocatorEx _PyObject = PYDBGOBJ_ALLOC;
Victor Stinner9e87e772017-11-24 12:09:24 +0100210#else
Victor Stinner5d39e042017-11-29 17:20:38 +0100211static PyMemAllocatorEx _PyMem_Raw = PYRAW_ALLOC;
212static PyMemAllocatorEx _PyMem = PYMEM_ALLOC;
213static PyMemAllocatorEx _PyObject = PYOBJ_ALLOC;
Victor Stinner9e87e772017-11-24 12:09:24 +0100214#endif
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600215
Victor Stinner0507bf52013-07-07 02:05:46 +0200216
Victor Stinner5d39e042017-11-29 17:20:38 +0100217static int
218pymem_set_default_allocator(PyMemAllocatorDomain domain, int debug,
219 PyMemAllocatorEx *old_alloc)
220{
221 if (old_alloc != NULL) {
222 PyMem_GetAllocator(domain, old_alloc);
223 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800224
Victor Stinner5d39e042017-11-29 17:20:38 +0100225
226 PyMemAllocatorEx new_alloc;
227 switch(domain)
228 {
229 case PYMEM_DOMAIN_RAW:
230 new_alloc = (PyMemAllocatorEx)PYRAW_ALLOC;
231 break;
232 case PYMEM_DOMAIN_MEM:
233 new_alloc = (PyMemAllocatorEx)PYMEM_ALLOC;
234 break;
235 case PYMEM_DOMAIN_OBJ:
236 new_alloc = (PyMemAllocatorEx)PYOBJ_ALLOC;
237 break;
238 default:
239 /* unknown domain */
240 return -1;
241 }
242 PyMem_SetAllocator(domain, &new_alloc);
243 if (debug) {
244 _PyMem_SetupDebugHooksDomain(domain);
245 }
246 return 0;
247}
248
249
250int
251_PyMem_SetDefaultAllocator(PyMemAllocatorDomain domain,
252 PyMemAllocatorEx *old_alloc)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800253{
Victor Stinnerccb04422017-11-16 03:20:31 -0800254#ifdef Py_DEBUG
Victor Stinner5d39e042017-11-29 17:20:38 +0100255 const int debug = 1;
Victor Stinnerccb04422017-11-16 03:20:31 -0800256#else
Victor Stinner5d39e042017-11-29 17:20:38 +0100257 const int debug = 0;
Victor Stinnerccb04422017-11-16 03:20:31 -0800258#endif
Victor Stinner5d39e042017-11-29 17:20:38 +0100259 return pymem_set_default_allocator(domain, debug, old_alloc);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800260}
Victor Stinner0507bf52013-07-07 02:05:46 +0200261
Victor Stinner5d39e042017-11-29 17:20:38 +0100262
Victor Stinner34be807c2016-03-14 12:04:26 +0100263int
264_PyMem_SetupAllocators(const char *opt)
265{
266 if (opt == NULL || *opt == '\0') {
267 /* PYTHONMALLOC is empty or is not set or ignored (-E/-I command line
Victor Stinner5d39e042017-11-29 17:20:38 +0100268 options): use default memory allocators */
269 opt = "default";
Victor Stinner34be807c2016-03-14 12:04:26 +0100270 }
271
Victor Stinner5d39e042017-11-29 17:20:38 +0100272 if (strcmp(opt, "default") == 0) {
273 (void)_PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, NULL);
274 (void)_PyMem_SetDefaultAllocator(PYMEM_DOMAIN_MEM, NULL);
275 (void)_PyMem_SetDefaultAllocator(PYMEM_DOMAIN_OBJ, NULL);
Victor Stinner34be807c2016-03-14 12:04:26 +0100276 }
Victor Stinner5d39e042017-11-29 17:20:38 +0100277 else if (strcmp(opt, "debug") == 0) {
278 (void)pymem_set_default_allocator(PYMEM_DOMAIN_RAW, 1, NULL);
279 (void)pymem_set_default_allocator(PYMEM_DOMAIN_MEM, 1, NULL);
280 (void)pymem_set_default_allocator(PYMEM_DOMAIN_OBJ, 1, NULL);
Victor Stinner34be807c2016-03-14 12:04:26 +0100281 }
282#ifdef WITH_PYMALLOC
Victor Stinner5d39e042017-11-29 17:20:38 +0100283 else if (strcmp(opt, "pymalloc") == 0 || strcmp(opt, "pymalloc_debug") == 0) {
284 PyMemAllocatorEx malloc_alloc = MALLOC_ALLOC;
285 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &malloc_alloc);
Victor Stinner34be807c2016-03-14 12:04:26 +0100286
Victor Stinner5d39e042017-11-29 17:20:38 +0100287 PyMemAllocatorEx pymalloc = PYMALLOC_ALLOC;
288 PyMem_SetAllocator(PYMEM_DOMAIN_MEM, &pymalloc);
289 PyMem_SetAllocator(PYMEM_DOMAIN_OBJ, &pymalloc);
Victor Stinner34be807c2016-03-14 12:04:26 +0100290
Victor Stinner5d39e042017-11-29 17:20:38 +0100291 if (strcmp(opt, "pymalloc_debug") == 0) {
Victor Stinner34be807c2016-03-14 12:04:26 +0100292 PyMem_SetupDebugHooks();
Victor Stinner5d39e042017-11-29 17:20:38 +0100293 }
Victor Stinner34be807c2016-03-14 12:04:26 +0100294 }
295#endif
Victor Stinner5d39e042017-11-29 17:20:38 +0100296 else if (strcmp(opt, "malloc") == 0 || strcmp(opt, "malloc_debug") == 0) {
297 PyMemAllocatorEx malloc_alloc = MALLOC_ALLOC;
298 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &malloc_alloc);
299 PyMem_SetAllocator(PYMEM_DOMAIN_MEM, &malloc_alloc);
300 PyMem_SetAllocator(PYMEM_DOMAIN_OBJ, &malloc_alloc);
301
302 if (strcmp(opt, "malloc_debug") == 0) {
303 PyMem_SetupDebugHooks();
304 }
305 }
Victor Stinner34be807c2016-03-14 12:04:26 +0100306 else {
307 /* unknown allocator */
308 return -1;
309 }
310 return 0;
311}
312
Victor Stinner5d39e042017-11-29 17:20:38 +0100313
314static int
315pymemallocator_eq(PyMemAllocatorEx *a, PyMemAllocatorEx *b)
316{
317 return (memcmp(a, b, sizeof(PyMemAllocatorEx)) == 0);
318}
319
320
321const char*
322_PyMem_GetAllocatorsName(void)
323{
324 PyMemAllocatorEx malloc_alloc = MALLOC_ALLOC;
325#ifdef WITH_PYMALLOC
326 PyMemAllocatorEx pymalloc = PYMALLOC_ALLOC;
327#endif
328
329 if (pymemallocator_eq(&_PyMem_Raw, &malloc_alloc) &&
330 pymemallocator_eq(&_PyMem, &malloc_alloc) &&
331 pymemallocator_eq(&_PyObject, &malloc_alloc))
332 {
333 return "malloc";
334 }
335#ifdef WITH_PYMALLOC
336 if (pymemallocator_eq(&_PyMem_Raw, &malloc_alloc) &&
337 pymemallocator_eq(&_PyMem, &pymalloc) &&
338 pymemallocator_eq(&_PyObject, &pymalloc))
339 {
340 return "pymalloc";
341 }
342#endif
343
344 PyMemAllocatorEx dbg_raw = PYDBGRAW_ALLOC;
345 PyMemAllocatorEx dbg_mem = PYDBGMEM_ALLOC;
346 PyMemAllocatorEx dbg_obj = PYDBGOBJ_ALLOC;
347
348 if (pymemallocator_eq(&_PyMem_Raw, &dbg_raw) &&
349 pymemallocator_eq(&_PyMem, &dbg_mem) &&
350 pymemallocator_eq(&_PyObject, &dbg_obj))
351 {
352 /* Debug hooks installed */
353 if (pymemallocator_eq(&_PyMem_Debug.raw.alloc, &malloc_alloc) &&
354 pymemallocator_eq(&_PyMem_Debug.mem.alloc, &malloc_alloc) &&
355 pymemallocator_eq(&_PyMem_Debug.obj.alloc, &malloc_alloc))
356 {
357 return "malloc_debug";
358 }
359#ifdef WITH_PYMALLOC
360 if (pymemallocator_eq(&_PyMem_Debug.raw.alloc, &malloc_alloc) &&
361 pymemallocator_eq(&_PyMem_Debug.mem.alloc, &pymalloc) &&
362 pymemallocator_eq(&_PyMem_Debug.obj.alloc, &pymalloc))
363 {
364 return "pymalloc_debug";
365 }
366#endif
367 }
368 return NULL;
369}
370
371
372#undef MALLOC_ALLOC
373#undef PYMALLOC_ALLOC
374#undef PYRAW_ALLOC
375#undef PYMEM_ALLOC
376#undef PYOBJ_ALLOC
377#undef PYDBGRAW_ALLOC
378#undef PYDBGMEM_ALLOC
379#undef PYDBGOBJ_ALLOC
380
Victor Stinner0507bf52013-07-07 02:05:46 +0200381
Victor Stinner9e87e772017-11-24 12:09:24 +0100382static PyObjectArenaAllocator _PyObject_Arena = {NULL,
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800383#ifdef MS_WINDOWS
Victor Stinner9e87e772017-11-24 12:09:24 +0100384 _PyObject_ArenaVirtualAlloc, _PyObject_ArenaVirtualFree
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800385#elif defined(ARENAS_USE_MMAP)
Victor Stinner9e87e772017-11-24 12:09:24 +0100386 _PyObject_ArenaMmap, _PyObject_ArenaMunmap
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800387#else
Victor Stinner9e87e772017-11-24 12:09:24 +0100388 _PyObject_ArenaMalloc, _PyObject_ArenaFree
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800389#endif
390 };
391
Victor Stinner0621e0e2016-04-19 17:02:55 +0200392#ifdef WITH_PYMALLOC
Victor Stinner34be807c2016-03-14 12:04:26 +0100393static int
394_PyMem_DebugEnabled(void)
395{
396 return (_PyObject.malloc == _PyMem_DebugMalloc);
397}
398
Victor Stinner6bf992a2017-12-06 17:26:10 +0100399static int
Victor Stinner34be807c2016-03-14 12:04:26 +0100400_PyMem_PymallocEnabled(void)
401{
402 if (_PyMem_DebugEnabled()) {
403 return (_PyMem_Debug.obj.alloc.malloc == _PyObject_Malloc);
404 }
405 else {
406 return (_PyObject.malloc == _PyObject_Malloc);
407 }
408}
409#endif
410
Victor Stinner5d39e042017-11-29 17:20:38 +0100411
412static void
413_PyMem_SetupDebugHooksDomain(PyMemAllocatorDomain domain)
Victor Stinner0507bf52013-07-07 02:05:46 +0200414{
Victor Stinnerd8f0d922014-06-02 21:57:10 +0200415 PyMemAllocatorEx alloc;
Victor Stinner0507bf52013-07-07 02:05:46 +0200416
Victor Stinner5d39e042017-11-29 17:20:38 +0100417 if (domain == PYMEM_DOMAIN_RAW) {
418 if (_PyMem_Raw.malloc == _PyMem_DebugRawMalloc) {
419 return;
420 }
Victor Stinner34be807c2016-03-14 12:04:26 +0100421
Victor Stinner0507bf52013-07-07 02:05:46 +0200422 PyMem_GetAllocator(PYMEM_DOMAIN_RAW, &_PyMem_Debug.raw.alloc);
Victor Stinner5d39e042017-11-29 17:20:38 +0100423 alloc.ctx = &_PyMem_Debug.raw;
424 alloc.malloc = _PyMem_DebugRawMalloc;
425 alloc.calloc = _PyMem_DebugRawCalloc;
426 alloc.realloc = _PyMem_DebugRawRealloc;
427 alloc.free = _PyMem_DebugRawFree;
Victor Stinner0507bf52013-07-07 02:05:46 +0200428 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &alloc);
429 }
Victor Stinner5d39e042017-11-29 17:20:38 +0100430 else if (domain == PYMEM_DOMAIN_MEM) {
431 if (_PyMem.malloc == _PyMem_DebugMalloc) {
432 return;
433 }
Victor Stinner0507bf52013-07-07 02:05:46 +0200434
Victor Stinnerad524372016-03-16 12:12:53 +0100435 PyMem_GetAllocator(PYMEM_DOMAIN_MEM, &_PyMem_Debug.mem.alloc);
Victor Stinner5d39e042017-11-29 17:20:38 +0100436 alloc.ctx = &_PyMem_Debug.mem;
437 alloc.malloc = _PyMem_DebugMalloc;
438 alloc.calloc = _PyMem_DebugCalloc;
439 alloc.realloc = _PyMem_DebugRealloc;
440 alloc.free = _PyMem_DebugFree;
Victor Stinnerad524372016-03-16 12:12:53 +0100441 PyMem_SetAllocator(PYMEM_DOMAIN_MEM, &alloc);
442 }
Victor Stinner5d39e042017-11-29 17:20:38 +0100443 else if (domain == PYMEM_DOMAIN_OBJ) {
444 if (_PyObject.malloc == _PyMem_DebugMalloc) {
445 return;
446 }
Victor Stinnerad524372016-03-16 12:12:53 +0100447
Victor Stinner0507bf52013-07-07 02:05:46 +0200448 PyMem_GetAllocator(PYMEM_DOMAIN_OBJ, &_PyMem_Debug.obj.alloc);
Victor Stinner5d39e042017-11-29 17:20:38 +0100449 alloc.ctx = &_PyMem_Debug.obj;
450 alloc.malloc = _PyMem_DebugMalloc;
451 alloc.calloc = _PyMem_DebugCalloc;
452 alloc.realloc = _PyMem_DebugRealloc;
453 alloc.free = _PyMem_DebugFree;
Victor Stinner0507bf52013-07-07 02:05:46 +0200454 PyMem_SetAllocator(PYMEM_DOMAIN_OBJ, &alloc);
455 }
Victor Stinner0507bf52013-07-07 02:05:46 +0200456}
457
Victor Stinner5d39e042017-11-29 17:20:38 +0100458
459void
460PyMem_SetupDebugHooks(void)
461{
462 _PyMem_SetupDebugHooksDomain(PYMEM_DOMAIN_RAW);
463 _PyMem_SetupDebugHooksDomain(PYMEM_DOMAIN_MEM);
464 _PyMem_SetupDebugHooksDomain(PYMEM_DOMAIN_OBJ);
465}
466
Victor Stinner0507bf52013-07-07 02:05:46 +0200467void
Victor Stinnerd8f0d922014-06-02 21:57:10 +0200468PyMem_GetAllocator(PyMemAllocatorDomain domain, PyMemAllocatorEx *allocator)
Victor Stinner0507bf52013-07-07 02:05:46 +0200469{
470 switch(domain)
471 {
472 case PYMEM_DOMAIN_RAW: *allocator = _PyMem_Raw; break;
473 case PYMEM_DOMAIN_MEM: *allocator = _PyMem; break;
474 case PYMEM_DOMAIN_OBJ: *allocator = _PyObject; break;
475 default:
Victor Stinnerdb067af2014-05-02 22:31:14 +0200476 /* unknown domain: set all attributes to NULL */
Victor Stinner0507bf52013-07-07 02:05:46 +0200477 allocator->ctx = NULL;
478 allocator->malloc = NULL;
Victor Stinnerdb067af2014-05-02 22:31:14 +0200479 allocator->calloc = NULL;
Victor Stinner0507bf52013-07-07 02:05:46 +0200480 allocator->realloc = NULL;
481 allocator->free = NULL;
482 }
483}
484
485void
Victor Stinnerd8f0d922014-06-02 21:57:10 +0200486PyMem_SetAllocator(PyMemAllocatorDomain domain, PyMemAllocatorEx *allocator)
Victor Stinner0507bf52013-07-07 02:05:46 +0200487{
488 switch(domain)
489 {
490 case PYMEM_DOMAIN_RAW: _PyMem_Raw = *allocator; break;
491 case PYMEM_DOMAIN_MEM: _PyMem = *allocator; break;
492 case PYMEM_DOMAIN_OBJ: _PyObject = *allocator; break;
493 /* ignore unknown domain */
494 }
Victor Stinner0507bf52013-07-07 02:05:46 +0200495}
496
497void
498PyObject_GetArenaAllocator(PyObjectArenaAllocator *allocator)
499{
Victor Stinner9e87e772017-11-24 12:09:24 +0100500 *allocator = _PyObject_Arena;
Victor Stinner0507bf52013-07-07 02:05:46 +0200501}
502
503void
504PyObject_SetArenaAllocator(PyObjectArenaAllocator *allocator)
505{
Victor Stinner9e87e772017-11-24 12:09:24 +0100506 _PyObject_Arena = *allocator;
Victor Stinner0507bf52013-07-07 02:05:46 +0200507}
508
509void *
510PyMem_RawMalloc(size_t size)
511{
512 /*
513 * Limit ourselves to PY_SSIZE_T_MAX bytes to prevent security holes.
514 * Most python internals blindly use a signed Py_ssize_t to track
515 * things without checking for overflows or negatives.
516 * As size_t is unsigned, checking for size < 0 is not required.
517 */
518 if (size > (size_t)PY_SSIZE_T_MAX)
519 return NULL;
Victor Stinner0507bf52013-07-07 02:05:46 +0200520 return _PyMem_Raw.malloc(_PyMem_Raw.ctx, size);
521}
522
Victor Stinnerdb067af2014-05-02 22:31:14 +0200523void *
524PyMem_RawCalloc(size_t nelem, size_t elsize)
525{
526 /* see PyMem_RawMalloc() */
527 if (elsize != 0 && nelem > (size_t)PY_SSIZE_T_MAX / elsize)
528 return NULL;
529 return _PyMem_Raw.calloc(_PyMem_Raw.ctx, nelem, elsize);
530}
531
Victor Stinner0507bf52013-07-07 02:05:46 +0200532void*
533PyMem_RawRealloc(void *ptr, size_t new_size)
534{
535 /* see PyMem_RawMalloc() */
536 if (new_size > (size_t)PY_SSIZE_T_MAX)
537 return NULL;
538 return _PyMem_Raw.realloc(_PyMem_Raw.ctx, ptr, new_size);
539}
540
Victor Stinner9e87e772017-11-24 12:09:24 +0100541void PyMem_RawFree(void *ptr)
Victor Stinner0507bf52013-07-07 02:05:46 +0200542{
543 _PyMem_Raw.free(_PyMem_Raw.ctx, ptr);
544}
545
Victor Stinner9ed83c42017-10-31 12:18:10 -0700546
Victor Stinner0507bf52013-07-07 02:05:46 +0200547void *
548PyMem_Malloc(size_t size)
549{
550 /* see PyMem_RawMalloc() */
551 if (size > (size_t)PY_SSIZE_T_MAX)
552 return NULL;
553 return _PyMem.malloc(_PyMem.ctx, size);
554}
555
556void *
Victor Stinnerdb067af2014-05-02 22:31:14 +0200557PyMem_Calloc(size_t nelem, size_t elsize)
558{
559 /* see PyMem_RawMalloc() */
560 if (elsize != 0 && nelem > (size_t)PY_SSIZE_T_MAX / elsize)
561 return NULL;
562 return _PyMem.calloc(_PyMem.ctx, nelem, elsize);
563}
564
565void *
Victor Stinner0507bf52013-07-07 02:05:46 +0200566PyMem_Realloc(void *ptr, size_t new_size)
567{
568 /* see PyMem_RawMalloc() */
569 if (new_size > (size_t)PY_SSIZE_T_MAX)
570 return NULL;
571 return _PyMem.realloc(_PyMem.ctx, ptr, new_size);
572}
573
574void
575PyMem_Free(void *ptr)
576{
577 _PyMem.free(_PyMem.ctx, ptr);
578}
579
Victor Stinner9ed83c42017-10-31 12:18:10 -0700580
Victor Stinner46972b72017-11-24 22:55:40 +0100581wchar_t*
582_PyMem_RawWcsdup(const wchar_t *str)
583{
Victor Stinnerb64de462017-12-01 18:27:09 +0100584 assert(str != NULL);
585
Victor Stinner46972b72017-11-24 22:55:40 +0100586 size_t len = wcslen(str);
587 if (len > (size_t)PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
588 return NULL;
589 }
590
591 size_t size = (len + 1) * sizeof(wchar_t);
592 wchar_t *str2 = PyMem_RawMalloc(size);
593 if (str2 == NULL) {
594 return NULL;
595 }
596
597 memcpy(str2, str, size);
598 return str2;
599}
600
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200601char *
602_PyMem_RawStrdup(const char *str)
603{
Victor Stinnerb64de462017-12-01 18:27:09 +0100604 assert(str != NULL);
605 size_t size = strlen(str) + 1;
606 char *copy = PyMem_RawMalloc(size);
607 if (copy == NULL) {
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200608 return NULL;
Victor Stinnerb64de462017-12-01 18:27:09 +0100609 }
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200610 memcpy(copy, str, size);
611 return copy;
612}
613
614char *
615_PyMem_Strdup(const char *str)
616{
Victor Stinnerb64de462017-12-01 18:27:09 +0100617 assert(str != NULL);
618 size_t size = strlen(str) + 1;
619 char *copy = PyMem_Malloc(size);
620 if (copy == NULL) {
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200621 return NULL;
Victor Stinnerb64de462017-12-01 18:27:09 +0100622 }
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200623 memcpy(copy, str, size);
624 return copy;
625}
626
Victor Stinner0507bf52013-07-07 02:05:46 +0200627void *
628PyObject_Malloc(size_t size)
629{
630 /* see PyMem_RawMalloc() */
631 if (size > (size_t)PY_SSIZE_T_MAX)
632 return NULL;
633 return _PyObject.malloc(_PyObject.ctx, size);
634}
635
636void *
Victor Stinnerdb067af2014-05-02 22:31:14 +0200637PyObject_Calloc(size_t nelem, size_t elsize)
638{
639 /* see PyMem_RawMalloc() */
640 if (elsize != 0 && nelem > (size_t)PY_SSIZE_T_MAX / elsize)
641 return NULL;
642 return _PyObject.calloc(_PyObject.ctx, nelem, elsize);
643}
644
645void *
Victor Stinner0507bf52013-07-07 02:05:46 +0200646PyObject_Realloc(void *ptr, size_t new_size)
647{
648 /* see PyMem_RawMalloc() */
649 if (new_size > (size_t)PY_SSIZE_T_MAX)
650 return NULL;
651 return _PyObject.realloc(_PyObject.ctx, ptr, new_size);
652}
653
654void
655PyObject_Free(void *ptr)
656{
657 _PyObject.free(_PyObject.ctx, ptr);
658}
659
660
661#ifdef WITH_PYMALLOC
662
Benjamin Peterson05159c42009-12-03 03:01:27 +0000663#ifdef WITH_VALGRIND
664#include <valgrind/valgrind.h>
665
666/* If we're using GCC, use __builtin_expect() to reduce overhead of
667 the valgrind checks */
668#if defined(__GNUC__) && (__GNUC__ > 2) && defined(__OPTIMIZE__)
669# define UNLIKELY(value) __builtin_expect((value), 0)
670#else
671# define UNLIKELY(value) (value)
672#endif
673
674/* -1 indicates that we haven't checked that we're running on valgrind yet. */
675static int running_on_valgrind = -1;
676#endif
677
Victor Stinner9ed83c42017-10-31 12:18:10 -0700678
Victor Stinner9e87e772017-11-24 12:09:24 +0100679/* An object allocator for Python.
680
681 Here is an introduction to the layers of the Python memory architecture,
682 showing where the object allocator is actually used (layer +2), It is
683 called for every object allocation and deallocation (PyObject_New/Del),
684 unless the object-specific allocators implement a proprietary allocation
685 scheme (ex.: ints use a simple free list). This is also the place where
686 the cyclic garbage collector operates selectively on container objects.
687
688
689 Object-specific allocators
690 _____ ______ ______ ________
691 [ int ] [ dict ] [ list ] ... [ string ] Python core |
692+3 | <----- Object-specific memory -----> | <-- Non-object memory --> |
693 _______________________________ | |
694 [ Python's object allocator ] | |
695+2 | ####### Object memory ####### | <------ Internal buffers ------> |
696 ______________________________________________________________ |
697 [ Python's raw memory allocator (PyMem_ API) ] |
698+1 | <----- Python memory (under PyMem manager's control) ------> | |
699 __________________________________________________________________
700 [ Underlying general-purpose allocator (ex: C library malloc) ]
701 0 | <------ Virtual memory allocated for the python process -------> |
702
703 =========================================================================
704 _______________________________________________________________________
705 [ OS-specific Virtual Memory Manager (VMM) ]
706-1 | <--- Kernel dynamic storage allocation & management (page-based) ---> |
707 __________________________________ __________________________________
708 [ ] [ ]
709-2 | <-- Physical memory: ROM/RAM --> | | <-- Secondary storage (swap) --> |
710
711*/
712/*==========================================================================*/
713
714/* A fast, special-purpose memory allocator for small blocks, to be used
715 on top of a general-purpose malloc -- heavily based on previous art. */
716
717/* Vladimir Marangozov -- August 2000 */
718
719/*
720 * "Memory management is where the rubber meets the road -- if we do the wrong
721 * thing at any level, the results will not be good. And if we don't make the
722 * levels work well together, we are in serious trouble." (1)
723 *
724 * (1) Paul R. Wilson, Mark S. Johnstone, Michael Neely, and David Boles,
725 * "Dynamic Storage Allocation: A Survey and Critical Review",
726 * in Proc. 1995 Int'l. Workshop on Memory Management, September 1995.
727 */
728
729/* #undef WITH_MEMORY_LIMITS */ /* disable mem limit checks */
730
731/*==========================================================================*/
732
733/*
734 * Allocation strategy abstract:
735 *
736 * For small requests, the allocator sub-allocates <Big> blocks of memory.
737 * Requests greater than SMALL_REQUEST_THRESHOLD bytes are routed to the
738 * system's allocator.
739 *
740 * Small requests are grouped in size classes spaced 8 bytes apart, due
741 * to the required valid alignment of the returned address. Requests of
742 * a particular size are serviced from memory pools of 4K (one VMM page).
743 * Pools are fragmented on demand and contain free lists of blocks of one
744 * particular size class. In other words, there is a fixed-size allocator
745 * for each size class. Free pools are shared by the different allocators
746 * thus minimizing the space reserved for a particular size class.
747 *
748 * This allocation strategy is a variant of what is known as "simple
749 * segregated storage based on array of free lists". The main drawback of
750 * simple segregated storage is that we might end up with lot of reserved
751 * memory for the different free lists, which degenerate in time. To avoid
752 * this, we partition each free list in pools and we share dynamically the
753 * reserved space between all free lists. This technique is quite efficient
754 * for memory intensive programs which allocate mainly small-sized blocks.
755 *
756 * For small requests we have the following table:
757 *
758 * Request in bytes Size of allocated block Size class idx
759 * ----------------------------------------------------------------
760 * 1-8 8 0
761 * 9-16 16 1
762 * 17-24 24 2
763 * 25-32 32 3
764 * 33-40 40 4
765 * 41-48 48 5
766 * 49-56 56 6
767 * 57-64 64 7
768 * 65-72 72 8
769 * ... ... ...
770 * 497-504 504 62
771 * 505-512 512 63
772 *
773 * 0, SMALL_REQUEST_THRESHOLD + 1 and up: routed to the underlying
774 * allocator.
775 */
776
777/*==========================================================================*/
778
779/*
780 * -- Main tunable settings section --
781 */
782
783/*
784 * Alignment of addresses returned to the user. 8-bytes alignment works
785 * on most current architectures (with 32-bit or 64-bit address busses).
786 * The alignment value is also used for grouping small requests in size
787 * classes spaced ALIGNMENT bytes apart.
788 *
789 * You shouldn't change this unless you know what you are doing.
790 */
791#define ALIGNMENT 8 /* must be 2^N */
792#define ALIGNMENT_SHIFT 3
793
794/* Return the number of bytes in size class I, as a uint. */
795#define INDEX2SIZE(I) (((uint)(I) + 1) << ALIGNMENT_SHIFT)
796
797/*
798 * Max size threshold below which malloc requests are considered to be
799 * small enough in order to use preallocated memory pools. You can tune
800 * this value according to your application behaviour and memory needs.
801 *
802 * Note: a size threshold of 512 guarantees that newly created dictionaries
803 * will be allocated from preallocated memory pools on 64-bit.
804 *
805 * The following invariants must hold:
806 * 1) ALIGNMENT <= SMALL_REQUEST_THRESHOLD <= 512
807 * 2) SMALL_REQUEST_THRESHOLD is evenly divisible by ALIGNMENT
808 *
809 * Although not required, for better performance and space efficiency,
810 * it is recommended that SMALL_REQUEST_THRESHOLD is set to a power of 2.
811 */
812#define SMALL_REQUEST_THRESHOLD 512
813#define NB_SMALL_SIZE_CLASSES (SMALL_REQUEST_THRESHOLD / ALIGNMENT)
814
815/*
816 * The system's VMM page size can be obtained on most unices with a
817 * getpagesize() call or deduced from various header files. To make
818 * things simpler, we assume that it is 4K, which is OK for most systems.
819 * It is probably better if this is the native page size, but it doesn't
820 * have to be. In theory, if SYSTEM_PAGE_SIZE is larger than the native page
821 * size, then `POOL_ADDR(p)->arenaindex' could rarely cause a segmentation
822 * violation fault. 4K is apparently OK for all the platforms that python
823 * currently targets.
824 */
825#define SYSTEM_PAGE_SIZE (4 * 1024)
826#define SYSTEM_PAGE_SIZE_MASK (SYSTEM_PAGE_SIZE - 1)
827
828/*
829 * Maximum amount of memory managed by the allocator for small requests.
830 */
831#ifdef WITH_MEMORY_LIMITS
832#ifndef SMALL_MEMORY_LIMIT
833#define SMALL_MEMORY_LIMIT (64 * 1024 * 1024) /* 64 MB -- more? */
834#endif
835#endif
836
837/*
838 * The allocator sub-allocates <Big> blocks of memory (called arenas) aligned
839 * on a page boundary. This is a reserved virtual address space for the
840 * current process (obtained through a malloc()/mmap() call). In no way this
841 * means that the memory arenas will be used entirely. A malloc(<Big>) is
842 * usually an address range reservation for <Big> bytes, unless all pages within
843 * this space are referenced subsequently. So malloc'ing big blocks and not
844 * using them does not mean "wasting memory". It's an addressable range
845 * wastage...
846 *
847 * Arenas are allocated with mmap() on systems supporting anonymous memory
848 * mappings to reduce heap fragmentation.
849 */
850#define ARENA_SIZE (256 << 10) /* 256KB */
851
852#ifdef WITH_MEMORY_LIMITS
853#define MAX_ARENAS (SMALL_MEMORY_LIMIT / ARENA_SIZE)
854#endif
855
856/*
857 * Size of the pools used for small blocks. Should be a power of 2,
858 * between 1K and SYSTEM_PAGE_SIZE, that is: 1k, 2k, 4k.
859 */
860#define POOL_SIZE SYSTEM_PAGE_SIZE /* must be 2^N */
861#define POOL_SIZE_MASK SYSTEM_PAGE_SIZE_MASK
862
863/*
864 * -- End of tunable settings section --
865 */
866
867/*==========================================================================*/
868
869/*
870 * Locking
871 *
872 * To reduce lock contention, it would probably be better to refine the
873 * crude function locking with per size class locking. I'm not positive
874 * however, whether it's worth switching to such locking policy because
875 * of the performance penalty it might introduce.
876 *
877 * The following macros describe the simplest (should also be the fastest)
878 * lock object on a particular platform and the init/fini/lock/unlock
879 * operations on it. The locks defined here are not expected to be recursive
880 * because it is assumed that they will always be called in the order:
881 * INIT, [LOCK, UNLOCK]*, FINI.
882 */
883
884/*
885 * Python's threads are serialized, so object malloc locking is disabled.
886 */
887#define SIMPLELOCK_DECL(lock) /* simple lock declaration */
888#define SIMPLELOCK_INIT(lock) /* allocate (if needed) and initialize */
889#define SIMPLELOCK_FINI(lock) /* free/destroy an existing lock */
890#define SIMPLELOCK_LOCK(lock) /* acquire released lock */
891#define SIMPLELOCK_UNLOCK(lock) /* release acquired lock */
892
893/* When you say memory, my mind reasons in terms of (pointers to) blocks */
894typedef uint8_t block;
895
896/* Pool for small blocks. */
897struct pool_header {
898 union { block *_padding;
899 uint count; } ref; /* number of allocated blocks */
900 block *freeblock; /* pool's free list head */
901 struct pool_header *nextpool; /* next pool of this size class */
902 struct pool_header *prevpool; /* previous pool "" */
903 uint arenaindex; /* index into arenas of base adr */
904 uint szidx; /* block size class index */
905 uint nextoffset; /* bytes to virgin block */
906 uint maxnextoffset; /* largest valid nextoffset */
907};
908
909typedef struct pool_header *poolp;
910
911/* Record keeping for arenas. */
912struct arena_object {
913 /* The address of the arena, as returned by malloc. Note that 0
914 * will never be returned by a successful malloc, and is used
915 * here to mark an arena_object that doesn't correspond to an
916 * allocated arena.
917 */
918 uintptr_t address;
919
920 /* Pool-aligned pointer to the next pool to be carved off. */
921 block* pool_address;
922
923 /* The number of available pools in the arena: free pools + never-
924 * allocated pools.
925 */
926 uint nfreepools;
927
928 /* The total number of pools in the arena, whether or not available. */
929 uint ntotalpools;
930
931 /* Singly-linked list of available pools. */
932 struct pool_header* freepools;
933
934 /* Whenever this arena_object is not associated with an allocated
935 * arena, the nextarena member is used to link all unassociated
936 * arena_objects in the singly-linked `unused_arena_objects` list.
937 * The prevarena member is unused in this case.
938 *
939 * When this arena_object is associated with an allocated arena
940 * with at least one available pool, both members are used in the
941 * doubly-linked `usable_arenas` list, which is maintained in
942 * increasing order of `nfreepools` values.
943 *
944 * Else this arena_object is associated with an allocated arena
945 * all of whose pools are in use. `nextarena` and `prevarena`
946 * are both meaningless in this case.
947 */
948 struct arena_object* nextarena;
949 struct arena_object* prevarena;
950};
951
952#define POOL_OVERHEAD _Py_SIZE_ROUND_UP(sizeof(struct pool_header), ALIGNMENT)
953
954#define DUMMY_SIZE_IDX 0xffff /* size class of newly cached pools */
955
956/* Round pointer P down to the closest pool-aligned address <= P, as a poolp */
957#define POOL_ADDR(P) ((poolp)_Py_ALIGN_DOWN((P), POOL_SIZE))
958
959/* Return total number of blocks in pool of size index I, as a uint. */
960#define NUMBLOCKS(I) ((uint)(POOL_SIZE - POOL_OVERHEAD) / INDEX2SIZE(I))
961
962/*==========================================================================*/
963
964/*
965 * This malloc lock
966 */
967SIMPLELOCK_DECL(_malloc_lock)
968#define LOCK() SIMPLELOCK_LOCK(_malloc_lock)
969#define UNLOCK() SIMPLELOCK_UNLOCK(_malloc_lock)
970#define LOCK_INIT() SIMPLELOCK_INIT(_malloc_lock)
971#define LOCK_FINI() SIMPLELOCK_FINI(_malloc_lock)
972
973/*
974 * Pool table -- headed, circular, doubly-linked lists of partially used pools.
975
976This is involved. For an index i, usedpools[i+i] is the header for a list of
977all partially used pools holding small blocks with "size class idx" i. So
978usedpools[0] corresponds to blocks of size 8, usedpools[2] to blocks of size
97916, and so on: index 2*i <-> blocks of size (i+1)<<ALIGNMENT_SHIFT.
980
981Pools are carved off an arena's highwater mark (an arena_object's pool_address
982member) as needed. Once carved off, a pool is in one of three states forever
983after:
984
985used == partially used, neither empty nor full
986 At least one block in the pool is currently allocated, and at least one
987 block in the pool is not currently allocated (note this implies a pool
988 has room for at least two blocks).
989 This is a pool's initial state, as a pool is created only when malloc
990 needs space.
991 The pool holds blocks of a fixed size, and is in the circular list headed
992 at usedpools[i] (see above). It's linked to the other used pools of the
993 same size class via the pool_header's nextpool and prevpool members.
994 If all but one block is currently allocated, a malloc can cause a
995 transition to the full state. If all but one block is not currently
996 allocated, a free can cause a transition to the empty state.
997
998full == all the pool's blocks are currently allocated
999 On transition to full, a pool is unlinked from its usedpools[] list.
1000 It's not linked to from anything then anymore, and its nextpool and
1001 prevpool members are meaningless until it transitions back to used.
1002 A free of a block in a full pool puts the pool back in the used state.
1003 Then it's linked in at the front of the appropriate usedpools[] list, so
1004 that the next allocation for its size class will reuse the freed block.
1005
1006empty == all the pool's blocks are currently available for allocation
1007 On transition to empty, a pool is unlinked from its usedpools[] list,
1008 and linked to the front of its arena_object's singly-linked freepools list,
1009 via its nextpool member. The prevpool member has no meaning in this case.
1010 Empty pools have no inherent size class: the next time a malloc finds
1011 an empty list in usedpools[], it takes the first pool off of freepools.
1012 If the size class needed happens to be the same as the size class the pool
1013 last had, some pool initialization can be skipped.
1014
1015
1016Block Management
1017
1018Blocks within pools are again carved out as needed. pool->freeblock points to
1019the start of a singly-linked list of free blocks within the pool. When a
1020block is freed, it's inserted at the front of its pool's freeblock list. Note
1021that the available blocks in a pool are *not* linked all together when a pool
1022is initialized. Instead only "the first two" (lowest addresses) blocks are
1023set up, returning the first such block, and setting pool->freeblock to a
1024one-block list holding the second such block. This is consistent with that
1025pymalloc strives at all levels (arena, pool, and block) never to touch a piece
1026of memory until it's actually needed.
1027
1028So long as a pool is in the used state, we're certain there *is* a block
1029available for allocating, and pool->freeblock is not NULL. If pool->freeblock
1030points to the end of the free list before we've carved the entire pool into
1031blocks, that means we simply haven't yet gotten to one of the higher-address
1032blocks. The offset from the pool_header to the start of "the next" virgin
1033block is stored in the pool_header nextoffset member, and the largest value
1034of nextoffset that makes sense is stored in the maxnextoffset member when a
1035pool is initialized. All the blocks in a pool have been passed out at least
1036once when and only when nextoffset > maxnextoffset.
1037
1038
1039Major obscurity: While the usedpools vector is declared to have poolp
1040entries, it doesn't really. It really contains two pointers per (conceptual)
1041poolp entry, the nextpool and prevpool members of a pool_header. The
1042excruciating initialization code below fools C so that
1043
1044 usedpool[i+i]
1045
1046"acts like" a genuine poolp, but only so long as you only reference its
1047nextpool and prevpool members. The "- 2*sizeof(block *)" gibberish is
1048compensating for that a pool_header's nextpool and prevpool members
1049immediately follow a pool_header's first two members:
1050
1051 union { block *_padding;
1052 uint count; } ref;
1053 block *freeblock;
1054
1055each of which consume sizeof(block *) bytes. So what usedpools[i+i] really
1056contains is a fudged-up pointer p such that *if* C believes it's a poolp
1057pointer, then p->nextpool and p->prevpool are both p (meaning that the headed
1058circular list is empty).
1059
1060It's unclear why the usedpools setup is so convoluted. It could be to
1061minimize the amount of cache required to hold this heavily-referenced table
1062(which only *needs* the two interpool pointer members of a pool_header). OTOH,
1063referencing code has to remember to "double the index" and doing so isn't
1064free, usedpools[0] isn't a strictly legal pointer, and we're crucially relying
1065on that C doesn't insert any padding anywhere in a pool_header at or before
1066the prevpool member.
1067**************************************************************************** */
1068
1069#define PTA(x) ((poolp )((uint8_t *)&(usedpools[2*(x)]) - 2*sizeof(block *)))
1070#define PT(x) PTA(x), PTA(x)
1071
1072static poolp usedpools[2 * ((NB_SMALL_SIZE_CLASSES + 7) / 8) * 8] = {
1073 PT(0), PT(1), PT(2), PT(3), PT(4), PT(5), PT(6), PT(7)
1074#if NB_SMALL_SIZE_CLASSES > 8
1075 , PT(8), PT(9), PT(10), PT(11), PT(12), PT(13), PT(14), PT(15)
1076#if NB_SMALL_SIZE_CLASSES > 16
1077 , PT(16), PT(17), PT(18), PT(19), PT(20), PT(21), PT(22), PT(23)
1078#if NB_SMALL_SIZE_CLASSES > 24
1079 , PT(24), PT(25), PT(26), PT(27), PT(28), PT(29), PT(30), PT(31)
1080#if NB_SMALL_SIZE_CLASSES > 32
1081 , PT(32), PT(33), PT(34), PT(35), PT(36), PT(37), PT(38), PT(39)
1082#if NB_SMALL_SIZE_CLASSES > 40
1083 , PT(40), PT(41), PT(42), PT(43), PT(44), PT(45), PT(46), PT(47)
1084#if NB_SMALL_SIZE_CLASSES > 48
1085 , PT(48), PT(49), PT(50), PT(51), PT(52), PT(53), PT(54), PT(55)
1086#if NB_SMALL_SIZE_CLASSES > 56
1087 , PT(56), PT(57), PT(58), PT(59), PT(60), PT(61), PT(62), PT(63)
1088#if NB_SMALL_SIZE_CLASSES > 64
1089#error "NB_SMALL_SIZE_CLASSES should be less than 64"
1090#endif /* NB_SMALL_SIZE_CLASSES > 64 */
1091#endif /* NB_SMALL_SIZE_CLASSES > 56 */
1092#endif /* NB_SMALL_SIZE_CLASSES > 48 */
1093#endif /* NB_SMALL_SIZE_CLASSES > 40 */
1094#endif /* NB_SMALL_SIZE_CLASSES > 32 */
1095#endif /* NB_SMALL_SIZE_CLASSES > 24 */
1096#endif /* NB_SMALL_SIZE_CLASSES > 16 */
1097#endif /* NB_SMALL_SIZE_CLASSES > 8 */
1098};
1099
1100/*==========================================================================
1101Arena management.
1102
1103`arenas` is a vector of arena_objects. It contains maxarenas entries, some of
1104which may not be currently used (== they're arena_objects that aren't
1105currently associated with an allocated arena). Note that arenas proper are
1106separately malloc'ed.
1107
1108Prior to Python 2.5, arenas were never free()'ed. Starting with Python 2.5,
1109we do try to free() arenas, and use some mild heuristic strategies to increase
1110the likelihood that arenas eventually can be freed.
1111
1112unused_arena_objects
1113
1114 This is a singly-linked list of the arena_objects that are currently not
1115 being used (no arena is associated with them). Objects are taken off the
1116 head of the list in new_arena(), and are pushed on the head of the list in
1117 PyObject_Free() when the arena is empty. Key invariant: an arena_object
1118 is on this list if and only if its .address member is 0.
1119
1120usable_arenas
1121
1122 This is a doubly-linked list of the arena_objects associated with arenas
1123 that have pools available. These pools are either waiting to be reused,
1124 or have not been used before. The list is sorted to have the most-
1125 allocated arenas first (ascending order based on the nfreepools member).
1126 This means that the next allocation will come from a heavily used arena,
1127 which gives the nearly empty arenas a chance to be returned to the system.
1128 In my unscientific tests this dramatically improved the number of arenas
1129 that could be freed.
1130
1131Note that an arena_object associated with an arena all of whose pools are
1132currently in use isn't on either list.
1133*/
1134
1135/* Array of objects used to track chunks of memory (arenas). */
1136static struct arena_object* arenas = NULL;
1137/* Number of slots currently allocated in the `arenas` vector. */
1138static uint maxarenas = 0;
1139
1140/* The head of the singly-linked, NULL-terminated list of available
1141 * arena_objects.
1142 */
1143static struct arena_object* unused_arena_objects = NULL;
1144
1145/* The head of the doubly-linked, NULL-terminated at each end, list of
1146 * arena_objects associated with arenas that have pools available.
1147 */
1148static struct arena_object* usable_arenas = NULL;
1149
1150/* How many arena_objects do we initially allocate?
1151 * 16 = can allocate 16 arenas = 16 * ARENA_SIZE = 4MB before growing the
1152 * `arenas` vector.
1153 */
1154#define INITIAL_ARENA_OBJECTS 16
1155
1156/* Number of arenas allocated that haven't been free()'d. */
1157static size_t narenas_currently_allocated = 0;
1158
1159/* Total number of times malloc() called to allocate an arena. */
1160static size_t ntimes_arena_allocated = 0;
1161/* High water mark (max value ever seen) for narenas_currently_allocated. */
1162static size_t narenas_highwater = 0;
1163
1164static Py_ssize_t _Py_AllocatedBlocks = 0;
1165
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001166Py_ssize_t
1167_Py_GetAllocatedBlocks(void)
1168{
Victor Stinner9e87e772017-11-24 12:09:24 +01001169 return _Py_AllocatedBlocks;
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001170}
1171
1172
Thomas Woutersa9773292006-04-21 09:43:23 +00001173/* Allocate a new arena. If we run out of memory, return NULL. Else
1174 * allocate a new arena, and return the address of an arena_object
1175 * describing the new arena. It's expected that the caller will set
1176 * `usable_arenas` to the return value.
1177 */
1178static struct arena_object*
Tim Petersd97a1c02002-03-30 06:09:22 +00001179new_arena(void)
1180{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001181 struct arena_object* arenaobj;
1182 uint excess; /* number of bytes above pool alignment */
Victor Stinnerba108822012-03-10 00:21:44 +01001183 void *address;
Victor Stinner34be807c2016-03-14 12:04:26 +01001184 static int debug_stats = -1;
Tim Petersd97a1c02002-03-30 06:09:22 +00001185
Victor Stinner34be807c2016-03-14 12:04:26 +01001186 if (debug_stats == -1) {
Serhiy Storchaka4ae06c52017-12-12 13:55:04 +02001187 const char *opt = Py_GETENV("PYTHONMALLOCSTATS");
Victor Stinner34be807c2016-03-14 12:04:26 +01001188 debug_stats = (opt != NULL && *opt != '\0');
1189 }
1190 if (debug_stats)
David Malcolm49526f42012-06-22 14:55:41 -04001191 _PyObject_DebugMallocStats(stderr);
Victor Stinner34be807c2016-03-14 12:04:26 +01001192
Victor Stinner9e87e772017-11-24 12:09:24 +01001193 if (unused_arena_objects == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 uint i;
1195 uint numarenas;
1196 size_t nbytes;
Tim Peters0e871182002-04-13 08:29:14 +00001197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001198 /* Double the number of arena objects on each allocation.
1199 * Note that it's possible for `numarenas` to overflow.
1200 */
Victor Stinner9e87e772017-11-24 12:09:24 +01001201 numarenas = maxarenas ? maxarenas << 1 : INITIAL_ARENA_OBJECTS;
1202 if (numarenas <= maxarenas)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001203 return NULL; /* overflow */
Martin v. Löwis5aca8822008-09-11 06:55:48 +00001204#if SIZEOF_SIZE_T <= SIZEOF_INT
Victor Stinner9e87e772017-11-24 12:09:24 +01001205 if (numarenas > SIZE_MAX / sizeof(*arenas))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001206 return NULL; /* overflow */
Martin v. Löwis5aca8822008-09-11 06:55:48 +00001207#endif
Victor Stinner9e87e772017-11-24 12:09:24 +01001208 nbytes = numarenas * sizeof(*arenas);
1209 arenaobj = (struct arena_object *)PyMem_RawRealloc(arenas, nbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001210 if (arenaobj == NULL)
1211 return NULL;
Victor Stinner9e87e772017-11-24 12:09:24 +01001212 arenas = arenaobj;
Thomas Woutersa9773292006-04-21 09:43:23 +00001213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001214 /* We might need to fix pointers that were copied. However,
1215 * new_arena only gets called when all the pages in the
1216 * previous arenas are full. Thus, there are *no* pointers
1217 * into the old array. Thus, we don't have to worry about
1218 * invalid pointers. Just to be sure, some asserts:
1219 */
Victor Stinner9e87e772017-11-24 12:09:24 +01001220 assert(usable_arenas == NULL);
1221 assert(unused_arena_objects == NULL);
Thomas Woutersa9773292006-04-21 09:43:23 +00001222
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001223 /* Put the new arenas on the unused_arena_objects list. */
Victor Stinner9e87e772017-11-24 12:09:24 +01001224 for (i = maxarenas; i < numarenas; ++i) {
1225 arenas[i].address = 0; /* mark as unassociated */
1226 arenas[i].nextarena = i < numarenas - 1 ?
1227 &arenas[i+1] : NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001228 }
Thomas Woutersa9773292006-04-21 09:43:23 +00001229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001230 /* Update globals. */
Victor Stinner9e87e772017-11-24 12:09:24 +01001231 unused_arena_objects = &arenas[maxarenas];
1232 maxarenas = numarenas;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001233 }
Tim Petersd97a1c02002-03-30 06:09:22 +00001234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001235 /* Take the next available arena object off the head of the list. */
Victor Stinner9e87e772017-11-24 12:09:24 +01001236 assert(unused_arena_objects != NULL);
1237 arenaobj = unused_arena_objects;
1238 unused_arena_objects = arenaobj->nextarena;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001239 assert(arenaobj->address == 0);
Victor Stinner9e87e772017-11-24 12:09:24 +01001240 address = _PyObject_Arena.alloc(_PyObject_Arena.ctx, ARENA_SIZE);
Victor Stinner0507bf52013-07-07 02:05:46 +02001241 if (address == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001242 /* The allocation failed: return NULL after putting the
1243 * arenaobj back.
1244 */
Victor Stinner9e87e772017-11-24 12:09:24 +01001245 arenaobj->nextarena = unused_arena_objects;
1246 unused_arena_objects = arenaobj;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001247 return NULL;
1248 }
Benjamin Peterson5d4b09c2016-09-18 19:24:52 -07001249 arenaobj->address = (uintptr_t)address;
Tim Petersd97a1c02002-03-30 06:09:22 +00001250
Victor Stinner9e87e772017-11-24 12:09:24 +01001251 ++narenas_currently_allocated;
1252 ++ntimes_arena_allocated;
1253 if (narenas_currently_allocated > narenas_highwater)
1254 narenas_highwater = narenas_currently_allocated;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001255 arenaobj->freepools = NULL;
1256 /* pool_address <- first pool-aligned address in the arena
1257 nfreepools <- number of whole pools that fit after alignment */
Victor Stinner9e87e772017-11-24 12:09:24 +01001258 arenaobj->pool_address = (block*)arenaobj->address;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001259 arenaobj->nfreepools = ARENA_SIZE / POOL_SIZE;
1260 assert(POOL_SIZE * arenaobj->nfreepools == ARENA_SIZE);
1261 excess = (uint)(arenaobj->address & POOL_SIZE_MASK);
1262 if (excess != 0) {
1263 --arenaobj->nfreepools;
1264 arenaobj->pool_address += POOL_SIZE - excess;
1265 }
1266 arenaobj->ntotalpools = arenaobj->nfreepools;
Thomas Woutersa9773292006-04-21 09:43:23 +00001267
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001268 return arenaobj;
Tim Petersd97a1c02002-03-30 06:09:22 +00001269}
1270
Victor Stinner9ed83c42017-10-31 12:18:10 -07001271
Thomas Woutersa9773292006-04-21 09:43:23 +00001272/*
Benjamin Peterson3924f932016-09-18 19:12:48 -07001273address_in_range(P, POOL)
Thomas Woutersa9773292006-04-21 09:43:23 +00001274
1275Return true if and only if P is an address that was allocated by pymalloc.
1276POOL must be the pool address associated with P, i.e., POOL = POOL_ADDR(P)
1277(the caller is asked to compute this because the macro expands POOL more than
1278once, and for efficiency it's best for the caller to assign POOL_ADDR(P) to a
Benjamin Peterson3924f932016-09-18 19:12:48 -07001279variable and pass the latter to the macro; because address_in_range is
Thomas Woutersa9773292006-04-21 09:43:23 +00001280called on every alloc/realloc/free, micro-efficiency is important here).
1281
1282Tricky: Let B be the arena base address associated with the pool, B =
1283arenas[(POOL)->arenaindex].address. Then P belongs to the arena if and only if
1284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001285 B <= P < B + ARENA_SIZE
Thomas Woutersa9773292006-04-21 09:43:23 +00001286
1287Subtracting B throughout, this is true iff
1288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001289 0 <= P-B < ARENA_SIZE
Thomas Woutersa9773292006-04-21 09:43:23 +00001290
1291By using unsigned arithmetic, the "0 <=" half of the test can be skipped.
1292
1293Obscure: A PyMem "free memory" function can call the pymalloc free or realloc
1294before the first arena has been allocated. `arenas` is still NULL in that
1295case. We're relying on that maxarenas is also 0 in that case, so that
1296(POOL)->arenaindex < maxarenas must be false, saving us from trying to index
1297into a NULL arenas.
1298
1299Details: given P and POOL, the arena_object corresponding to P is AO =
1300arenas[(POOL)->arenaindex]. Suppose obmalloc controls P. Then (barring wild
1301stores, etc), POOL is the correct address of P's pool, AO.address is the
1302correct base address of the pool's arena, and P must be within ARENA_SIZE of
1303AO.address. In addition, AO.address is not 0 (no arena can start at address 0
Benjamin Peterson3924f932016-09-18 19:12:48 -07001304(NULL)). Therefore address_in_range correctly reports that obmalloc
Thomas Woutersa9773292006-04-21 09:43:23 +00001305controls P.
1306
1307Now suppose obmalloc does not control P (e.g., P was obtained via a direct
1308call to the system malloc() or realloc()). (POOL)->arenaindex may be anything
1309in this case -- it may even be uninitialized trash. If the trash arenaindex
1310is >= maxarenas, the macro correctly concludes at once that obmalloc doesn't
1311control P.
1312
1313Else arenaindex is < maxarena, and AO is read up. If AO corresponds to an
1314allocated arena, obmalloc controls all the memory in slice AO.address :
1315AO.address+ARENA_SIZE. By case assumption, P is not controlled by obmalloc,
1316so P doesn't lie in that slice, so the macro correctly reports that P is not
1317controlled by obmalloc.
1318
1319Finally, if P is not controlled by obmalloc and AO corresponds to an unused
1320arena_object (one not currently associated with an allocated arena),
1321AO.address is 0, and the second test in the macro reduces to:
1322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001323 P < ARENA_SIZE
Thomas Woutersa9773292006-04-21 09:43:23 +00001324
1325If P >= ARENA_SIZE (extremely likely), the macro again correctly concludes
1326that P is not controlled by obmalloc. However, if P < ARENA_SIZE, this part
1327of the test still passes, and the third clause (AO.address != 0) is necessary
1328to get the correct result: AO.address is 0 in this case, so the macro
1329correctly reports that P is not controlled by obmalloc (despite that P lies in
1330slice AO.address : AO.address + ARENA_SIZE).
1331
1332Note: The third (AO.address != 0) clause was added in Python 2.5. Before
13332.5, arenas were never free()'ed, and an arenaindex < maxarena always
1334corresponded to a currently-allocated arena, so the "P is not controlled by
1335obmalloc, AO corresponds to an unused arena_object, and P < ARENA_SIZE" case
1336was impossible.
1337
1338Note that the logic is excruciating, and reading up possibly uninitialized
1339memory when P is not controlled by obmalloc (to get at (POOL)->arenaindex)
1340creates problems for some memory debuggers. The overwhelming advantage is
1341that this test determines whether an arbitrary address is controlled by
1342obmalloc in a small constant time, independent of the number of arenas
1343obmalloc controls. Since this test is needed at every entry point, it's
1344extremely desirable that it be this fast.
1345*/
Thomas Woutersa9773292006-04-21 09:43:23 +00001346
Miss Islington (bot)1ec57812018-11-11 15:44:34 -08001347static bool _Py_NO_ADDRESS_SAFETY_ANALYSIS
1348 _Py_NO_SANITIZE_THREAD
1349 _Py_NO_SANITIZE_MEMORY
Benjamin Peterson3924f932016-09-18 19:12:48 -07001350address_in_range(void *p, poolp pool)
1351{
1352 // Since address_in_range may be reading from memory which was not allocated
1353 // by Python, it is important that pool->arenaindex is read only once, as
1354 // another thread may be concurrently modifying the value without holding
1355 // the GIL. The following dance forces the compiler to read pool->arenaindex
1356 // only once.
1357 uint arenaindex = *((volatile uint *)&pool->arenaindex);
Victor Stinner9e87e772017-11-24 12:09:24 +01001358 return arenaindex < maxarenas &&
1359 (uintptr_t)p - arenas[arenaindex].address < ARENA_SIZE &&
1360 arenas[arenaindex].address != 0;
Benjamin Peterson3924f932016-09-18 19:12:48 -07001361}
Tim Peters338e0102002-04-01 19:23:44 +00001362
Victor Stinner9ed83c42017-10-31 12:18:10 -07001363
Neil Schemenauera35c6882001-02-27 04:45:05 +00001364/*==========================================================================*/
1365
Victor Stinner9ed83c42017-10-31 12:18:10 -07001366/* pymalloc allocator
Neil Schemenauera35c6882001-02-27 04:45:05 +00001367
Victor Stinner9ed83c42017-10-31 12:18:10 -07001368 The basic blocks are ordered by decreasing execution frequency,
1369 which minimizes the number of jumps in the most common cases,
1370 improves branching prediction and instruction scheduling (small
1371 block allocations typically result in a couple of instructions).
1372 Unless the optimizer reorders everything, being too smart...
Neil Schemenauera35c6882001-02-27 04:45:05 +00001373
Victor Stinner9ed83c42017-10-31 12:18:10 -07001374 Return 1 if pymalloc allocated memory and wrote the pointer into *ptr_p.
1375
1376 Return 0 if pymalloc failed to allocate the memory block: on bigger
1377 requests, on error in the code below (as a last chance to serve the request)
1378 or when the max memory limit has been reached. */
1379static int
1380pymalloc_alloc(void *ctx, void **ptr_p, size_t nbytes)
Neil Schemenauera35c6882001-02-27 04:45:05 +00001381{
Victor Stinner9e87e772017-11-24 12:09:24 +01001382 block *bp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001383 poolp pool;
1384 poolp next;
1385 uint size;
Neil Schemenauera35c6882001-02-27 04:45:05 +00001386
Benjamin Peterson05159c42009-12-03 03:01:27 +00001387#ifdef WITH_VALGRIND
Victor Stinner9ed83c42017-10-31 12:18:10 -07001388 if (UNLIKELY(running_on_valgrind == -1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001389 running_on_valgrind = RUNNING_ON_VALGRIND;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001390 }
1391 if (UNLIKELY(running_on_valgrind)) {
1392 return 0;
1393 }
Benjamin Peterson05159c42009-12-03 03:01:27 +00001394#endif
1395
Victor Stinner9ed83c42017-10-31 12:18:10 -07001396 if (nbytes == 0) {
1397 return 0;
1398 }
1399 if (nbytes > SMALL_REQUEST_THRESHOLD) {
1400 return 0;
1401 }
T. Wouters06bb4872017-03-31 10:10:19 -07001402
Victor Stinner9ed83c42017-10-31 12:18:10 -07001403 LOCK();
1404 /*
1405 * Most frequent paths first
1406 */
1407 size = (uint)(nbytes - 1) >> ALIGNMENT_SHIFT;
Victor Stinner9e87e772017-11-24 12:09:24 +01001408 pool = usedpools[size + size];
Victor Stinner9ed83c42017-10-31 12:18:10 -07001409 if (pool != pool->nextpool) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 /*
Victor Stinner9ed83c42017-10-31 12:18:10 -07001411 * There is a used pool for this size class.
1412 * Pick up the head block of its free list.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001413 */
Victor Stinner9ed83c42017-10-31 12:18:10 -07001414 ++pool->ref.count;
1415 bp = pool->freeblock;
1416 assert(bp != NULL);
Victor Stinner9e87e772017-11-24 12:09:24 +01001417 if ((pool->freeblock = *(block **)bp) != NULL) {
Victor Stinner9ed83c42017-10-31 12:18:10 -07001418 goto success;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001419 }
Thomas Woutersa9773292006-04-21 09:43:23 +00001420
Victor Stinner9ed83c42017-10-31 12:18:10 -07001421 /*
1422 * Reached the end of the free list, try to extend it.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001423 */
Victor Stinner9ed83c42017-10-31 12:18:10 -07001424 if (pool->nextoffset <= pool->maxnextoffset) {
1425 /* There is room for another block. */
Victor Stinner9e87e772017-11-24 12:09:24 +01001426 pool->freeblock = (block*)pool +
Victor Stinner9ed83c42017-10-31 12:18:10 -07001427 pool->nextoffset;
1428 pool->nextoffset += INDEX2SIZE(size);
Victor Stinner9e87e772017-11-24 12:09:24 +01001429 *(block **)(pool->freeblock) = NULL;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001430 goto success;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001431 }
Thomas Woutersa9773292006-04-21 09:43:23 +00001432
Victor Stinner9ed83c42017-10-31 12:18:10 -07001433 /* Pool is full, unlink from used pools. */
1434 next = pool->nextpool;
1435 pool = pool->prevpool;
1436 next->prevpool = pool;
1437 pool->nextpool = next;
1438 goto success;
1439 }
Thomas Woutersa9773292006-04-21 09:43:23 +00001440
Victor Stinner9ed83c42017-10-31 12:18:10 -07001441 /* There isn't a pool of the right size class immediately
1442 * available: use a free pool.
1443 */
Victor Stinner9e87e772017-11-24 12:09:24 +01001444 if (usable_arenas == NULL) {
Victor Stinner9ed83c42017-10-31 12:18:10 -07001445 /* No arena has a free pool: allocate a new arena. */
1446#ifdef WITH_MEMORY_LIMITS
Victor Stinner9e87e772017-11-24 12:09:24 +01001447 if (narenas_currently_allocated >= MAX_ARENAS) {
Victor Stinner9ed83c42017-10-31 12:18:10 -07001448 goto failed;
1449 }
1450#endif
Victor Stinner9e87e772017-11-24 12:09:24 +01001451 usable_arenas = new_arena();
1452 if (usable_arenas == NULL) {
Victor Stinner9ed83c42017-10-31 12:18:10 -07001453 goto failed;
1454 }
Victor Stinner9e87e772017-11-24 12:09:24 +01001455 usable_arenas->nextarena =
1456 usable_arenas->prevarena = NULL;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001457 }
Victor Stinner9e87e772017-11-24 12:09:24 +01001458 assert(usable_arenas->address != 0);
Victor Stinner9ed83c42017-10-31 12:18:10 -07001459
1460 /* Try to get a cached free pool. */
Victor Stinner9e87e772017-11-24 12:09:24 +01001461 pool = usable_arenas->freepools;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001462 if (pool != NULL) {
1463 /* Unlink from cached pools. */
Victor Stinner9e87e772017-11-24 12:09:24 +01001464 usable_arenas->freepools = pool->nextpool;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001465
1466 /* This arena already had the smallest nfreepools
1467 * value, so decreasing nfreepools doesn't change
1468 * that, and we don't need to rearrange the
1469 * usable_arenas list. However, if the arena has
1470 * become wholly allocated, we need to remove its
1471 * arena_object from usable_arenas.
1472 */
Victor Stinner9e87e772017-11-24 12:09:24 +01001473 --usable_arenas->nfreepools;
1474 if (usable_arenas->nfreepools == 0) {
Victor Stinner9ed83c42017-10-31 12:18:10 -07001475 /* Wholly allocated: remove. */
Victor Stinner9e87e772017-11-24 12:09:24 +01001476 assert(usable_arenas->freepools == NULL);
1477 assert(usable_arenas->nextarena == NULL ||
1478 usable_arenas->nextarena->prevarena ==
1479 usable_arenas);
Victor Stinner9ed83c42017-10-31 12:18:10 -07001480
Victor Stinner9e87e772017-11-24 12:09:24 +01001481 usable_arenas = usable_arenas->nextarena;
1482 if (usable_arenas != NULL) {
1483 usable_arenas->prevarena = NULL;
1484 assert(usable_arenas->address != 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001485 }
1486 }
Victor Stinner9ed83c42017-10-31 12:18:10 -07001487 else {
1488 /* nfreepools > 0: it must be that freepools
1489 * isn't NULL, or that we haven't yet carved
1490 * off all the arena's pools for the first
1491 * time.
1492 */
Victor Stinner9e87e772017-11-24 12:09:24 +01001493 assert(usable_arenas->freepools != NULL ||
1494 usable_arenas->pool_address <=
1495 (block*)usable_arenas->address +
Victor Stinner9ed83c42017-10-31 12:18:10 -07001496 ARENA_SIZE - POOL_SIZE);
1497 }
Thomas Woutersa9773292006-04-21 09:43:23 +00001498
Victor Stinner9ed83c42017-10-31 12:18:10 -07001499 init_pool:
1500 /* Frontlink to used pools. */
Victor Stinner9e87e772017-11-24 12:09:24 +01001501 next = usedpools[size + size]; /* == prev */
Victor Stinner9ed83c42017-10-31 12:18:10 -07001502 pool->nextpool = next;
1503 pool->prevpool = next;
1504 next->nextpool = pool;
1505 next->prevpool = pool;
1506 pool->ref.count = 1;
1507 if (pool->szidx == size) {
1508 /* Luckily, this pool last contained blocks
1509 * of the same size class, so its header
1510 * and free list are already initialized.
1511 */
1512 bp = pool->freeblock;
1513 assert(bp != NULL);
Victor Stinner9e87e772017-11-24 12:09:24 +01001514 pool->freeblock = *(block **)bp;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001515 goto success;
1516 }
1517 /*
1518 * Initialize the pool header, set up the free list to
1519 * contain just the second block, and return the first
1520 * block.
1521 */
1522 pool->szidx = size;
1523 size = INDEX2SIZE(size);
Victor Stinner9e87e772017-11-24 12:09:24 +01001524 bp = (block *)pool + POOL_OVERHEAD;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001525 pool->nextoffset = POOL_OVERHEAD + (size << 1);
1526 pool->maxnextoffset = POOL_SIZE - size;
1527 pool->freeblock = bp + size;
Victor Stinner9e87e772017-11-24 12:09:24 +01001528 *(block **)(pool->freeblock) = NULL;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001529 goto success;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001530 }
Neil Schemenauera35c6882001-02-27 04:45:05 +00001531
Victor Stinner9ed83c42017-10-31 12:18:10 -07001532 /* Carve off a new pool. */
Victor Stinner9e87e772017-11-24 12:09:24 +01001533 assert(usable_arenas->nfreepools > 0);
1534 assert(usable_arenas->freepools == NULL);
1535 pool = (poolp)usable_arenas->pool_address;
1536 assert((block*)pool <= (block*)usable_arenas->address +
Victor Stinner9ed83c42017-10-31 12:18:10 -07001537 ARENA_SIZE - POOL_SIZE);
Victor Stinner9e87e772017-11-24 12:09:24 +01001538 pool->arenaindex = (uint)(usable_arenas - arenas);
1539 assert(&arenas[pool->arenaindex] == usable_arenas);
Victor Stinner9ed83c42017-10-31 12:18:10 -07001540 pool->szidx = DUMMY_SIZE_IDX;
Victor Stinner9e87e772017-11-24 12:09:24 +01001541 usable_arenas->pool_address += POOL_SIZE;
1542 --usable_arenas->nfreepools;
Neil Schemenauera35c6882001-02-27 04:45:05 +00001543
Victor Stinner9e87e772017-11-24 12:09:24 +01001544 if (usable_arenas->nfreepools == 0) {
1545 assert(usable_arenas->nextarena == NULL ||
1546 usable_arenas->nextarena->prevarena ==
1547 usable_arenas);
Victor Stinner9ed83c42017-10-31 12:18:10 -07001548 /* Unlink the arena: it is completely allocated. */
Victor Stinner9e87e772017-11-24 12:09:24 +01001549 usable_arenas = usable_arenas->nextarena;
1550 if (usable_arenas != NULL) {
1551 usable_arenas->prevarena = NULL;
1552 assert(usable_arenas->address != 0);
Victor Stinner9ed83c42017-10-31 12:18:10 -07001553 }
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001554 }
Victor Stinner9ed83c42017-10-31 12:18:10 -07001555
1556 goto init_pool;
1557
1558success:
1559 UNLOCK();
1560 assert(bp != NULL);
1561 *ptr_p = (void *)bp;
1562 return 1;
1563
1564failed:
1565 UNLOCK();
1566 return 0;
Neil Schemenauera35c6882001-02-27 04:45:05 +00001567}
1568
Victor Stinner9ed83c42017-10-31 12:18:10 -07001569
Victor Stinnerdb067af2014-05-02 22:31:14 +02001570static void *
1571_PyObject_Malloc(void *ctx, size_t nbytes)
1572{
Victor Stinner9ed83c42017-10-31 12:18:10 -07001573 void* ptr;
1574 if (pymalloc_alloc(ctx, &ptr, nbytes)) {
Victor Stinner9e87e772017-11-24 12:09:24 +01001575 _Py_AllocatedBlocks++;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001576 return ptr;
1577 }
1578
1579 ptr = PyMem_RawMalloc(nbytes);
1580 if (ptr != NULL) {
Victor Stinner9e87e772017-11-24 12:09:24 +01001581 _Py_AllocatedBlocks++;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001582 }
1583 return ptr;
Victor Stinnerdb067af2014-05-02 22:31:14 +02001584}
1585
Victor Stinner9ed83c42017-10-31 12:18:10 -07001586
Victor Stinnerdb067af2014-05-02 22:31:14 +02001587static void *
1588_PyObject_Calloc(void *ctx, size_t nelem, size_t elsize)
1589{
Victor Stinner9ed83c42017-10-31 12:18:10 -07001590 void* ptr;
1591
1592 assert(elsize == 0 || nelem <= (size_t)PY_SSIZE_T_MAX / elsize);
1593 size_t nbytes = nelem * elsize;
1594
1595 if (pymalloc_alloc(ctx, &ptr, nbytes)) {
1596 memset(ptr, 0, nbytes);
Victor Stinner9e87e772017-11-24 12:09:24 +01001597 _Py_AllocatedBlocks++;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001598 return ptr;
1599 }
1600
1601 ptr = PyMem_RawCalloc(nelem, elsize);
1602 if (ptr != NULL) {
Victor Stinner9e87e772017-11-24 12:09:24 +01001603 _Py_AllocatedBlocks++;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001604 }
1605 return ptr;
Victor Stinnerdb067af2014-05-02 22:31:14 +02001606}
1607
Neil Schemenauera35c6882001-02-27 04:45:05 +00001608
Victor Stinner9ed83c42017-10-31 12:18:10 -07001609/* Free a memory block allocated by pymalloc_alloc().
1610 Return 1 if it was freed.
1611 Return 0 if the block was not allocated by pymalloc_alloc(). */
1612static int
1613pymalloc_free(void *ctx, void *p)
Neil Schemenauera35c6882001-02-27 04:45:05 +00001614{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001615 poolp pool;
Victor Stinner9e87e772017-11-24 12:09:24 +01001616 block *lastfree;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001617 poolp next, prev;
1618 uint size;
Neil Schemenauera35c6882001-02-27 04:45:05 +00001619
Victor Stinner9ed83c42017-10-31 12:18:10 -07001620 assert(p != NULL);
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001621
Benjamin Peterson05159c42009-12-03 03:01:27 +00001622#ifdef WITH_VALGRIND
Victor Stinner9ed83c42017-10-31 12:18:10 -07001623 if (UNLIKELY(running_on_valgrind > 0)) {
1624 return 0;
1625 }
Benjamin Peterson05159c42009-12-03 03:01:27 +00001626#endif
1627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001628 pool = POOL_ADDR(p);
Victor Stinner9ed83c42017-10-31 12:18:10 -07001629 if (!address_in_range(p, pool)) {
1630 return 0;
1631 }
1632 /* We allocated this address. */
Thomas Woutersa9773292006-04-21 09:43:23 +00001633
Victor Stinner9ed83c42017-10-31 12:18:10 -07001634 LOCK();
Thomas Woutersa9773292006-04-21 09:43:23 +00001635
Victor Stinner9ed83c42017-10-31 12:18:10 -07001636 /* Link p to the start of the pool's freeblock list. Since
1637 * the pool had at least the p block outstanding, the pool
1638 * wasn't empty (so it's already in a usedpools[] list, or
1639 * was full and is in no list -- it's not in the freeblocks
1640 * list in any case).
1641 */
1642 assert(pool->ref.count > 0); /* else it was empty */
Victor Stinner9e87e772017-11-24 12:09:24 +01001643 *(block **)p = lastfree = pool->freeblock;
1644 pool->freeblock = (block *)p;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001645 if (!lastfree) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001646 /* Pool was full, so doesn't currently live in any list:
1647 * link it to the front of the appropriate usedpools[] list.
1648 * This mimics LRU pool usage for new allocations and
1649 * targets optimal filling when several pools contain
1650 * blocks of the same size class.
1651 */
1652 --pool->ref.count;
1653 assert(pool->ref.count > 0); /* else the pool is empty */
1654 size = pool->szidx;
Victor Stinner9e87e772017-11-24 12:09:24 +01001655 next = usedpools[size + size];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001656 prev = next->prevpool;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001657
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001658 /* insert pool before next: prev <-> pool <-> next */
1659 pool->nextpool = next;
1660 pool->prevpool = prev;
1661 next->prevpool = pool;
1662 prev->nextpool = pool;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001663 goto success;
1664 }
1665
1666 struct arena_object* ao;
1667 uint nf; /* ao->nfreepools */
1668
1669 /* freeblock wasn't NULL, so the pool wasn't full,
1670 * and the pool is in a usedpools[] list.
1671 */
1672 if (--pool->ref.count != 0) {
1673 /* pool isn't empty: leave it in usedpools */
1674 goto success;
1675 }
1676 /* Pool is now empty: unlink from usedpools, and
1677 * link to the front of freepools. This ensures that
1678 * previously freed pools will be allocated later
1679 * (being not referenced, they are perhaps paged out).
1680 */
1681 next = pool->nextpool;
1682 prev = pool->prevpool;
1683 next->prevpool = prev;
1684 prev->nextpool = next;
1685
1686 /* Link the pool to freepools. This is a singly-linked
1687 * list, and pool->prevpool isn't used there.
1688 */
Victor Stinner9e87e772017-11-24 12:09:24 +01001689 ao = &arenas[pool->arenaindex];
Victor Stinner9ed83c42017-10-31 12:18:10 -07001690 pool->nextpool = ao->freepools;
1691 ao->freepools = pool;
1692 nf = ++ao->nfreepools;
1693
1694 /* All the rest is arena management. We just freed
1695 * a pool, and there are 4 cases for arena mgmt:
1696 * 1. If all the pools are free, return the arena to
1697 * the system free().
1698 * 2. If this is the only free pool in the arena,
1699 * add the arena back to the `usable_arenas` list.
1700 * 3. If the "next" arena has a smaller count of free
1701 * pools, we have to "slide this arena right" to
1702 * restore that usable_arenas is sorted in order of
1703 * nfreepools.
1704 * 4. Else there's nothing more to do.
1705 */
1706 if (nf == ao->ntotalpools) {
1707 /* Case 1. First unlink ao from usable_arenas.
1708 */
1709 assert(ao->prevarena == NULL ||
1710 ao->prevarena->address != 0);
1711 assert(ao ->nextarena == NULL ||
1712 ao->nextarena->address != 0);
1713
1714 /* Fix the pointer in the prevarena, or the
1715 * usable_arenas pointer.
1716 */
1717 if (ao->prevarena == NULL) {
Victor Stinner9e87e772017-11-24 12:09:24 +01001718 usable_arenas = ao->nextarena;
1719 assert(usable_arenas == NULL ||
1720 usable_arenas->address != 0);
Victor Stinner9ed83c42017-10-31 12:18:10 -07001721 }
1722 else {
1723 assert(ao->prevarena->nextarena == ao);
1724 ao->prevarena->nextarena =
1725 ao->nextarena;
1726 }
1727 /* Fix the pointer in the nextarena. */
1728 if (ao->nextarena != NULL) {
1729 assert(ao->nextarena->prevarena == ao);
1730 ao->nextarena->prevarena =
1731 ao->prevarena;
1732 }
1733 /* Record that this arena_object slot is
1734 * available to be reused.
1735 */
Victor Stinner9e87e772017-11-24 12:09:24 +01001736 ao->nextarena = unused_arena_objects;
1737 unused_arena_objects = ao;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001738
1739 /* Free the entire arena. */
Victor Stinner9e87e772017-11-24 12:09:24 +01001740 _PyObject_Arena.free(_PyObject_Arena.ctx,
Victor Stinner9ed83c42017-10-31 12:18:10 -07001741 (void *)ao->address, ARENA_SIZE);
1742 ao->address = 0; /* mark unassociated */
Victor Stinner9e87e772017-11-24 12:09:24 +01001743 --narenas_currently_allocated;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001744
1745 goto success;
1746 }
1747
1748 if (nf == 1) {
1749 /* Case 2. Put ao at the head of
1750 * usable_arenas. Note that because
1751 * ao->nfreepools was 0 before, ao isn't
1752 * currently on the usable_arenas list.
1753 */
Victor Stinner9e87e772017-11-24 12:09:24 +01001754 ao->nextarena = usable_arenas;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001755 ao->prevarena = NULL;
Victor Stinner9e87e772017-11-24 12:09:24 +01001756 if (usable_arenas)
1757 usable_arenas->prevarena = ao;
1758 usable_arenas = ao;
1759 assert(usable_arenas->address != 0);
Victor Stinner9ed83c42017-10-31 12:18:10 -07001760
1761 goto success;
1762 }
1763
1764 /* If this arena is now out of order, we need to keep
1765 * the list sorted. The list is kept sorted so that
1766 * the "most full" arenas are used first, which allows
1767 * the nearly empty arenas to be completely freed. In
1768 * a few un-scientific tests, it seems like this
1769 * approach allowed a lot more memory to be freed.
1770 */
1771 if (ao->nextarena == NULL ||
1772 nf <= ao->nextarena->nfreepools) {
1773 /* Case 4. Nothing to do. */
1774 goto success;
1775 }
1776 /* Case 3: We have to move the arena towards the end
1777 * of the list, because it has more free pools than
1778 * the arena to its right.
1779 * First unlink ao from usable_arenas.
1780 */
1781 if (ao->prevarena != NULL) {
1782 /* ao isn't at the head of the list */
1783 assert(ao->prevarena->nextarena == ao);
1784 ao->prevarena->nextarena = ao->nextarena;
1785 }
1786 else {
1787 /* ao is at the head of the list */
Victor Stinner9e87e772017-11-24 12:09:24 +01001788 assert(usable_arenas == ao);
1789 usable_arenas = ao->nextarena;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001790 }
1791 ao->nextarena->prevarena = ao->prevarena;
1792
1793 /* Locate the new insertion point by iterating over
1794 * the list, using our nextarena pointer.
1795 */
1796 while (ao->nextarena != NULL && nf > ao->nextarena->nfreepools) {
1797 ao->prevarena = ao->nextarena;
1798 ao->nextarena = ao->nextarena->nextarena;
1799 }
1800
1801 /* Insert ao at this point. */
1802 assert(ao->nextarena == NULL || ao->prevarena == ao->nextarena->prevarena);
1803 assert(ao->prevarena->nextarena == ao->nextarena);
1804
1805 ao->prevarena->nextarena = ao;
1806 if (ao->nextarena != NULL) {
1807 ao->nextarena->prevarena = ao;
1808 }
1809
1810 /* Verify that the swaps worked. */
1811 assert(ao->nextarena == NULL || nf <= ao->nextarena->nfreepools);
1812 assert(ao->prevarena == NULL || nf > ao->prevarena->nfreepools);
1813 assert(ao->nextarena == NULL || ao->nextarena->prevarena == ao);
Victor Stinner9e87e772017-11-24 12:09:24 +01001814 assert((usable_arenas == ao && ao->prevarena == NULL)
Victor Stinner9ed83c42017-10-31 12:18:10 -07001815 || ao->prevarena->nextarena == ao);
1816
1817 goto success;
1818
1819success:
1820 UNLOCK();
1821 return 1;
1822}
1823
1824
1825static void
1826_PyObject_Free(void *ctx, void *p)
1827{
1828 /* PyObject_Free(NULL) has no effect */
1829 if (p == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001830 return;
1831 }
Neil Schemenauera35c6882001-02-27 04:45:05 +00001832
Victor Stinner9e87e772017-11-24 12:09:24 +01001833 _Py_AllocatedBlocks--;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001834 if (!pymalloc_free(ctx, p)) {
1835 /* pymalloc didn't allocate this address */
1836 PyMem_RawFree(p);
1837 }
Neil Schemenauera35c6882001-02-27 04:45:05 +00001838}
1839
Neil Schemenauera35c6882001-02-27 04:45:05 +00001840
Victor Stinner9ed83c42017-10-31 12:18:10 -07001841/* pymalloc realloc.
1842
1843 If nbytes==0, then as the Python docs promise, we do not treat this like
1844 free(p), and return a non-NULL result.
1845
1846 Return 1 if pymalloc reallocated memory and wrote the new pointer into
1847 newptr_p.
1848
1849 Return 0 if pymalloc didn't allocated p. */
1850static int
1851pymalloc_realloc(void *ctx, void **newptr_p, void *p, size_t nbytes)
Neil Schemenauera35c6882001-02-27 04:45:05 +00001852{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001853 void *bp;
1854 poolp pool;
1855 size_t size;
Neil Schemenauera35c6882001-02-27 04:45:05 +00001856
Victor Stinner9ed83c42017-10-31 12:18:10 -07001857 assert(p != NULL);
Georg Brandld492ad82008-07-23 16:13:07 +00001858
Benjamin Peterson05159c42009-12-03 03:01:27 +00001859#ifdef WITH_VALGRIND
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001860 /* Treat running_on_valgrind == -1 the same as 0 */
Victor Stinner9ed83c42017-10-31 12:18:10 -07001861 if (UNLIKELY(running_on_valgrind > 0)) {
1862 return 0;
1863 }
Benjamin Peterson05159c42009-12-03 03:01:27 +00001864#endif
1865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001866 pool = POOL_ADDR(p);
Victor Stinner9ed83c42017-10-31 12:18:10 -07001867 if (!address_in_range(p, pool)) {
1868 /* pymalloc is not managing this block.
1869
1870 If nbytes <= SMALL_REQUEST_THRESHOLD, it's tempting to try to take
1871 over this block. However, if we do, we need to copy the valid data
1872 from the C-managed block to one of our blocks, and there's no
1873 portable way to know how much of the memory space starting at p is
1874 valid.
1875
1876 As bug 1185883 pointed out the hard way, it's possible that the
1877 C-managed block is "at the end" of allocated VM space, so that a
1878 memory fault can occur if we try to copy nbytes bytes starting at p.
1879 Instead we punt: let C continue to manage this block. */
1880 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001881 }
Victor Stinner9ed83c42017-10-31 12:18:10 -07001882
1883 /* pymalloc is in charge of this block */
1884 size = INDEX2SIZE(pool->szidx);
1885 if (nbytes <= size) {
1886 /* The block is staying the same or shrinking.
1887
1888 If it's shrinking, there's a tradeoff: it costs cycles to copy the
1889 block to a smaller size class, but it wastes memory not to copy it.
1890
1891 The compromise here is to copy on shrink only if at least 25% of
1892 size can be shaved off. */
1893 if (4 * nbytes > 3 * size) {
1894 /* It's the same, or shrinking and new/old > 3/4. */
1895 *newptr_p = p;
1896 return 1;
1897 }
1898 size = nbytes;
1899 }
1900
1901 bp = _PyObject_Malloc(ctx, nbytes);
1902 if (bp != NULL) {
1903 memcpy(bp, p, size);
1904 _PyObject_Free(ctx, p);
1905 }
1906 *newptr_p = bp;
1907 return 1;
1908}
1909
1910
1911static void *
1912_PyObject_Realloc(void *ctx, void *ptr, size_t nbytes)
1913{
1914 void *ptr2;
1915
1916 if (ptr == NULL) {
1917 return _PyObject_Malloc(ctx, nbytes);
1918 }
1919
1920 if (pymalloc_realloc(ctx, &ptr2, ptr, nbytes)) {
1921 return ptr2;
1922 }
1923
1924 return PyMem_RawRealloc(ptr, nbytes);
Neil Schemenauera35c6882001-02-27 04:45:05 +00001925}
1926
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001927#else /* ! WITH_PYMALLOC */
Tim Petersddea2082002-03-23 10:03:50 +00001928
1929/*==========================================================================*/
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00001930/* pymalloc not enabled: Redirect the entry points to malloc. These will
1931 * only be used by extensions that are compiled with pymalloc enabled. */
Tim Peters62c06ba2002-03-23 22:28:18 +00001932
Antoine Pitrou92840532012-12-17 23:05:59 +01001933Py_ssize_t
1934_Py_GetAllocatedBlocks(void)
1935{
1936 return 0;
1937}
1938
Tim Peters1221c0a2002-03-23 00:20:15 +00001939#endif /* WITH_PYMALLOC */
1940
Victor Stinner34be807c2016-03-14 12:04:26 +01001941
Tim Petersddea2082002-03-23 10:03:50 +00001942/*==========================================================================*/
Tim Peters62c06ba2002-03-23 22:28:18 +00001943/* A x-platform debugging allocator. This doesn't manage memory directly,
1944 * it wraps a real allocator, adding extra debugging info to the memory blocks.
1945 */
Tim Petersddea2082002-03-23 10:03:50 +00001946
Tim Petersf6fb5012002-04-12 07:38:53 +00001947/* Special bytes broadcast into debug memory blocks at appropriate times.
1948 * Strings of these are unlikely to be valid addresses, floats, ints or
1949 * 7-bit ASCII.
1950 */
1951#undef CLEANBYTE
1952#undef DEADBYTE
1953#undef FORBIDDENBYTE
1954#define CLEANBYTE 0xCB /* clean (newly allocated) memory */
Tim Peters889f61d2002-07-10 19:29:49 +00001955#define DEADBYTE 0xDB /* dead (newly freed) memory */
Tim Petersf6fb5012002-04-12 07:38:53 +00001956#define FORBIDDENBYTE 0xFB /* untouchable bytes at each end of a block */
Tim Petersddea2082002-03-23 10:03:50 +00001957
Victor Stinner9e87e772017-11-24 12:09:24 +01001958static size_t serialno = 0; /* incremented on each debug {m,re}alloc */
1959
Tim Peterse0850172002-03-24 00:34:21 +00001960/* serialno is always incremented via calling this routine. The point is
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001961 * to supply a single place to set a breakpoint.
1962 */
Tim Peterse0850172002-03-24 00:34:21 +00001963static void
Neil Schemenauerbd02b142002-03-28 21:05:38 +00001964bumpserialno(void)
Tim Peterse0850172002-03-24 00:34:21 +00001965{
Victor Stinner9e87e772017-11-24 12:09:24 +01001966 ++serialno;
Tim Peterse0850172002-03-24 00:34:21 +00001967}
1968
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001969#define SST SIZEOF_SIZE_T
Tim Peterse0850172002-03-24 00:34:21 +00001970
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001971/* Read sizeof(size_t) bytes at p as a big-endian size_t. */
1972static size_t
1973read_size_t(const void *p)
Tim Petersddea2082002-03-23 10:03:50 +00001974{
Benjamin Peterson19517e42016-09-18 19:22:22 -07001975 const uint8_t *q = (const uint8_t *)p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001976 size_t result = *q++;
1977 int i;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001978
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001979 for (i = SST; --i > 0; ++q)
1980 result = (result << 8) | *q;
1981 return result;
Tim Petersddea2082002-03-23 10:03:50 +00001982}
1983
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001984/* Write n as a big-endian size_t, MSB at address p, LSB at
1985 * p + sizeof(size_t) - 1.
1986 */
Tim Petersddea2082002-03-23 10:03:50 +00001987static void
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001988write_size_t(void *p, size_t n)
Tim Petersddea2082002-03-23 10:03:50 +00001989{
Benjamin Peterson19517e42016-09-18 19:22:22 -07001990 uint8_t *q = (uint8_t *)p + SST - 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001991 int i;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001993 for (i = SST; --i >= 0; --q) {
Benjamin Peterson19517e42016-09-18 19:22:22 -07001994 *q = (uint8_t)(n & 0xff);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001995 n >>= 8;
1996 }
Tim Petersddea2082002-03-23 10:03:50 +00001997}
1998
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001999/* Let S = sizeof(size_t). The debug malloc asks for 4*S extra bytes and
2000 fills them with useful stuff, here calling the underlying malloc's result p:
Tim Petersddea2082002-03-23 10:03:50 +00002001
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00002002p[0: S]
2003 Number of bytes originally asked for. This is a size_t, big-endian (easier
2004 to read in a memory dump).
Georg Brandl7cba5fd2013-09-25 09:04:23 +02002005p[S]
Tim Petersdf099f52013-09-19 21:06:37 -05002006 API ID. See PEP 445. This is a character, but seems undocumented.
2007p[S+1: 2*S]
Tim Petersf6fb5012002-04-12 07:38:53 +00002008 Copies of FORBIDDENBYTE. Used to catch under- writes and reads.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00002009p[2*S: 2*S+n]
Tim Petersf6fb5012002-04-12 07:38:53 +00002010 The requested memory, filled with copies of CLEANBYTE.
Tim Petersddea2082002-03-23 10:03:50 +00002011 Used to catch reference to uninitialized memory.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00002012 &p[2*S] is returned. Note that this is 8-byte aligned if pymalloc
Tim Petersddea2082002-03-23 10:03:50 +00002013 handled the request itself.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00002014p[2*S+n: 2*S+n+S]
Tim Petersf6fb5012002-04-12 07:38:53 +00002015 Copies of FORBIDDENBYTE. Used to catch over- writes and reads.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00002016p[2*S+n+S: 2*S+n+2*S]
Victor Stinner0507bf52013-07-07 02:05:46 +02002017 A serial number, incremented by 1 on each call to _PyMem_DebugMalloc
2018 and _PyMem_DebugRealloc.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00002019 This is a big-endian size_t.
Tim Petersddea2082002-03-23 10:03:50 +00002020 If "bad memory" is detected later, the serial number gives an
2021 excellent way to set a breakpoint on the next run, to capture the
2022 instant at which this block was passed out.
2023*/
2024
Victor Stinner0507bf52013-07-07 02:05:46 +02002025static void *
Victor Stinnerc4aec362016-03-14 22:26:53 +01002026_PyMem_DebugRawAlloc(int use_calloc, void *ctx, size_t nbytes)
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00002027{
Victor Stinner0507bf52013-07-07 02:05:46 +02002028 debug_alloc_api_t *api = (debug_alloc_api_t *)ctx;
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002029 uint8_t *p; /* base address of malloc'ed pad block */
Victor Stinner9ed83c42017-10-31 12:18:10 -07002030 uint8_t *data; /* p + 2*SST == pointer to data bytes */
2031 uint8_t *tail; /* data + nbytes == pointer to tail pad bytes */
2032 size_t total; /* 2 * SST + nbytes + 2 * SST */
2033
2034 if (nbytes > (size_t)PY_SSIZE_T_MAX - 4 * SST) {
2035 /* integer overflow: can't represent total as a Py_ssize_t */
2036 return NULL;
2037 }
2038 total = nbytes + 4 * SST;
2039
2040 /* Layout: [SSSS IFFF CCCC...CCCC FFFF NNNN]
2041 * ^--- p ^--- data ^--- tail
2042 S: nbytes stored as size_t
2043 I: API identifier (1 byte)
2044 F: Forbidden bytes (size_t - 1 bytes before, size_t bytes after)
2045 C: Clean bytes used later to store actual data
2046 N: Serial number stored as size_t */
2047
2048 if (use_calloc) {
2049 p = (uint8_t *)api->alloc.calloc(api->alloc.ctx, 1, total);
2050 }
2051 else {
2052 p = (uint8_t *)api->alloc.malloc(api->alloc.ctx, total);
2053 }
2054 if (p == NULL) {
2055 return NULL;
2056 }
2057 data = p + 2*SST;
Tim Petersddea2082002-03-23 10:03:50 +00002058
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002059 bumpserialno();
Tim Petersddea2082002-03-23 10:03:50 +00002060
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002061 /* at p, write size (SST bytes), id (1 byte), pad (SST-1 bytes) */
2062 write_size_t(p, nbytes);
Benjamin Peterson19517e42016-09-18 19:22:22 -07002063 p[SST] = (uint8_t)api->api_id;
Victor Stinner0507bf52013-07-07 02:05:46 +02002064 memset(p + SST + 1, FORBIDDENBYTE, SST-1);
Tim Petersddea2082002-03-23 10:03:50 +00002065
Victor Stinner9ed83c42017-10-31 12:18:10 -07002066 if (nbytes > 0 && !use_calloc) {
2067 memset(data, CLEANBYTE, nbytes);
2068 }
Tim Petersddea2082002-03-23 10:03:50 +00002069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002070 /* at tail, write pad (SST bytes) and serialno (SST bytes) */
Victor Stinner9ed83c42017-10-31 12:18:10 -07002071 tail = data + nbytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002072 memset(tail, FORBIDDENBYTE, SST);
Victor Stinner9e87e772017-11-24 12:09:24 +01002073 write_size_t(tail + SST, serialno);
Tim Petersddea2082002-03-23 10:03:50 +00002074
Victor Stinner9ed83c42017-10-31 12:18:10 -07002075 return data;
Tim Petersddea2082002-03-23 10:03:50 +00002076}
2077
Victor Stinnerdb067af2014-05-02 22:31:14 +02002078static void *
Victor Stinnerc4aec362016-03-14 22:26:53 +01002079_PyMem_DebugRawMalloc(void *ctx, size_t nbytes)
Victor Stinnerdb067af2014-05-02 22:31:14 +02002080{
Victor Stinnerc4aec362016-03-14 22:26:53 +01002081 return _PyMem_DebugRawAlloc(0, ctx, nbytes);
Victor Stinnerdb067af2014-05-02 22:31:14 +02002082}
2083
2084static void *
Victor Stinnerc4aec362016-03-14 22:26:53 +01002085_PyMem_DebugRawCalloc(void *ctx, size_t nelem, size_t elsize)
Victor Stinnerdb067af2014-05-02 22:31:14 +02002086{
2087 size_t nbytes;
Victor Stinner9ed83c42017-10-31 12:18:10 -07002088 assert(elsize == 0 || nelem <= (size_t)PY_SSIZE_T_MAX / elsize);
Victor Stinnerdb067af2014-05-02 22:31:14 +02002089 nbytes = nelem * elsize;
Victor Stinnerc4aec362016-03-14 22:26:53 +01002090 return _PyMem_DebugRawAlloc(1, ctx, nbytes);
Victor Stinnerdb067af2014-05-02 22:31:14 +02002091}
2092
Victor Stinner9ed83c42017-10-31 12:18:10 -07002093
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00002094/* 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 +00002095 particular, that the FORBIDDENBYTEs with the api ID are still intact).
Tim Petersf6fb5012002-04-12 07:38:53 +00002096 Then fills the original bytes with DEADBYTE.
Tim Petersddea2082002-03-23 10:03:50 +00002097 Then calls the underlying free.
2098*/
Victor Stinner0507bf52013-07-07 02:05:46 +02002099static void
Victor Stinnerc4aec362016-03-14 22:26:53 +01002100_PyMem_DebugRawFree(void *ctx, void *p)
Tim Petersddea2082002-03-23 10:03:50 +00002101{
Victor Stinner9ed83c42017-10-31 12:18:10 -07002102 /* PyMem_Free(NULL) has no effect */
2103 if (p == NULL) {
2104 return;
2105 }
2106
Victor Stinner0507bf52013-07-07 02:05:46 +02002107 debug_alloc_api_t *api = (debug_alloc_api_t *)ctx;
Benjamin Peterson19517e42016-09-18 19:22:22 -07002108 uint8_t *q = (uint8_t *)p - 2*SST; /* address returned from malloc */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002109 size_t nbytes;
Tim Petersddea2082002-03-23 10:03:50 +00002110
Victor Stinner0507bf52013-07-07 02:05:46 +02002111 _PyMem_DebugCheckAddress(api->api_id, p);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002112 nbytes = read_size_t(q);
Victor Stinner9ed83c42017-10-31 12:18:10 -07002113 nbytes += 4 * SST;
2114 memset(q, DEADBYTE, nbytes);
Victor Stinner0507bf52013-07-07 02:05:46 +02002115 api->alloc.free(api->alloc.ctx, q);
Tim Petersddea2082002-03-23 10:03:50 +00002116}
2117
Victor Stinner9ed83c42017-10-31 12:18:10 -07002118
Victor Stinner0507bf52013-07-07 02:05:46 +02002119static void *
Victor Stinnerc4aec362016-03-14 22:26:53 +01002120_PyMem_DebugRawRealloc(void *ctx, void *p, size_t nbytes)
Tim Petersddea2082002-03-23 10:03:50 +00002121{
Victor Stinner9ed83c42017-10-31 12:18:10 -07002122 if (p == NULL) {
2123 return _PyMem_DebugRawAlloc(0, ctx, nbytes);
2124 }
2125
Victor Stinner0507bf52013-07-07 02:05:46 +02002126 debug_alloc_api_t *api = (debug_alloc_api_t *)ctx;
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002127 uint8_t *head; /* base address of malloc'ed pad block */
2128 uint8_t *data; /* pointer to data bytes */
2129 uint8_t *r;
Victor Stinner9ed83c42017-10-31 12:18:10 -07002130 uint8_t *tail; /* data + nbytes == pointer to tail pad bytes */
2131 size_t total; /* 2 * SST + nbytes + 2 * SST */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002132 size_t original_nbytes;
Victor Stinner9e87e772017-11-24 12:09:24 +01002133 size_t block_serialno;
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002134#define ERASED_SIZE 64
2135 uint8_t save[2*ERASED_SIZE]; /* A copy of erased bytes. */
Tim Petersddea2082002-03-23 10:03:50 +00002136
Victor Stinner0507bf52013-07-07 02:05:46 +02002137 _PyMem_DebugCheckAddress(api->api_id, p);
Victor Stinner9ed83c42017-10-31 12:18:10 -07002138
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002139 data = (uint8_t *)p;
2140 head = data - 2*SST;
2141 original_nbytes = read_size_t(head);
Victor Stinner9ed83c42017-10-31 12:18:10 -07002142 if (nbytes > (size_t)PY_SSIZE_T_MAX - 4*SST) {
2143 /* integer overflow: can't represent total as a Py_ssize_t */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002144 return NULL;
Victor Stinner9ed83c42017-10-31 12:18:10 -07002145 }
2146 total = nbytes + 4*SST;
Tim Petersddea2082002-03-23 10:03:50 +00002147
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002148 tail = data + original_nbytes;
Victor Stinner9e87e772017-11-24 12:09:24 +01002149 block_serialno = read_size_t(tail + SST);
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002150 /* Mark the header, the trailer, ERASED_SIZE bytes at the begin and
2151 ERASED_SIZE bytes at the end as dead and save the copy of erased bytes.
2152 */
2153 if (original_nbytes <= sizeof(save)) {
2154 memcpy(save, data, original_nbytes);
2155 memset(data - 2*SST, DEADBYTE, original_nbytes + 4*SST);
2156 }
2157 else {
2158 memcpy(save, data, ERASED_SIZE);
2159 memset(head, DEADBYTE, ERASED_SIZE + 2*SST);
2160 memcpy(&save[ERASED_SIZE], tail - ERASED_SIZE, ERASED_SIZE);
2161 memset(tail - ERASED_SIZE, DEADBYTE, ERASED_SIZE + 2*SST);
Victor Stinner9ed83c42017-10-31 12:18:10 -07002162 }
Tim Peters85cc1c42002-04-12 08:52:50 +00002163
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002164 /* Resize and add decorations. */
2165 r = (uint8_t *)api->alloc.realloc(api->alloc.ctx, head, total);
2166 if (r == NULL) {
2167 nbytes = original_nbytes;
Victor Stinner9ed83c42017-10-31 12:18:10 -07002168 }
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002169 else {
2170 head = r;
2171 bumpserialno();
Victor Stinner9e87e772017-11-24 12:09:24 +01002172 block_serialno = serialno;
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002173 }
2174
2175 write_size_t(head, nbytes);
2176 head[SST] = (uint8_t)api->api_id;
2177 memset(head + SST + 1, FORBIDDENBYTE, SST-1);
2178 data = head + 2*SST;
Victor Stinnerc4266362013-07-09 00:44:43 +02002179
Victor Stinner9ed83c42017-10-31 12:18:10 -07002180 tail = data + nbytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002181 memset(tail, FORBIDDENBYTE, SST);
Victor Stinner9e87e772017-11-24 12:09:24 +01002182 write_size_t(tail + SST, block_serialno);
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002183
2184 /* Restore saved bytes. */
2185 if (original_nbytes <= sizeof(save)) {
2186 memcpy(data, save, Py_MIN(nbytes, original_nbytes));
2187 }
2188 else {
2189 size_t i = original_nbytes - ERASED_SIZE;
2190 memcpy(data, save, Py_MIN(nbytes, ERASED_SIZE));
2191 if (nbytes > i) {
2192 memcpy(data + i, &save[ERASED_SIZE],
2193 Py_MIN(nbytes - i, ERASED_SIZE));
2194 }
2195 }
2196
2197 if (r == NULL) {
2198 return NULL;
2199 }
Tim Peters85cc1c42002-04-12 08:52:50 +00002200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002201 if (nbytes > original_nbytes) {
2202 /* growing: mark new extra memory clean */
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002203 memset(data + original_nbytes, CLEANBYTE, nbytes - original_nbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002204 }
Tim Peters85cc1c42002-04-12 08:52:50 +00002205
Victor Stinner9ed83c42017-10-31 12:18:10 -07002206 return data;
Tim Petersddea2082002-03-23 10:03:50 +00002207}
2208
Victor Stinnerc4aec362016-03-14 22:26:53 +01002209static void
2210_PyMem_DebugCheckGIL(void)
2211{
Victor Stinnerc4aec362016-03-14 22:26:53 +01002212 if (!PyGILState_Check())
2213 Py_FatalError("Python memory allocator called "
2214 "without holding the GIL");
Victor Stinnerc4aec362016-03-14 22:26:53 +01002215}
2216
2217static void *
2218_PyMem_DebugMalloc(void *ctx, size_t nbytes)
2219{
2220 _PyMem_DebugCheckGIL();
2221 return _PyMem_DebugRawMalloc(ctx, nbytes);
2222}
2223
2224static void *
2225_PyMem_DebugCalloc(void *ctx, size_t nelem, size_t elsize)
2226{
2227 _PyMem_DebugCheckGIL();
2228 return _PyMem_DebugRawCalloc(ctx, nelem, elsize);
2229}
2230
Victor Stinner9ed83c42017-10-31 12:18:10 -07002231
Victor Stinnerc4aec362016-03-14 22:26:53 +01002232static void
2233_PyMem_DebugFree(void *ctx, void *ptr)
2234{
2235 _PyMem_DebugCheckGIL();
Victor Stinner0aed3a42016-03-23 11:30:43 +01002236 _PyMem_DebugRawFree(ctx, ptr);
Victor Stinnerc4aec362016-03-14 22:26:53 +01002237}
2238
Victor Stinner9ed83c42017-10-31 12:18:10 -07002239
Victor Stinnerc4aec362016-03-14 22:26:53 +01002240static void *
2241_PyMem_DebugRealloc(void *ctx, void *ptr, size_t nbytes)
2242{
2243 _PyMem_DebugCheckGIL();
2244 return _PyMem_DebugRawRealloc(ctx, ptr, nbytes);
2245}
2246
Tim Peters7ccfadf2002-04-01 06:04:21 +00002247/* Check the forbidden bytes on both ends of the memory allocated for p.
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00002248 * If anything is wrong, print info to stderr via _PyObject_DebugDumpAddress,
Tim Peters7ccfadf2002-04-01 06:04:21 +00002249 * and call Py_FatalError to kill the program.
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00002250 * The API id, is also checked.
Tim Peters7ccfadf2002-04-01 06:04:21 +00002251 */
Victor Stinner0507bf52013-07-07 02:05:46 +02002252static void
2253_PyMem_DebugCheckAddress(char api, const void *p)
Tim Petersddea2082002-03-23 10:03:50 +00002254{
Benjamin Peterson19517e42016-09-18 19:22:22 -07002255 const uint8_t *q = (const uint8_t *)p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002256 char msgbuf[64];
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02002257 const char *msg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002258 size_t nbytes;
Benjamin Peterson19517e42016-09-18 19:22:22 -07002259 const uint8_t *tail;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002260 int i;
2261 char id;
Tim Petersddea2082002-03-23 10:03:50 +00002262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002263 if (p == NULL) {
2264 msg = "didn't expect a NULL pointer";
2265 goto error;
2266 }
Tim Petersddea2082002-03-23 10:03:50 +00002267
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002268 /* Check the API id */
2269 id = (char)q[-SST];
2270 if (id != api) {
2271 msg = msgbuf;
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02002272 snprintf(msgbuf, sizeof(msgbuf), "bad ID: Allocated using API '%c', verified using API '%c'", id, api);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002273 msgbuf[sizeof(msgbuf)-1] = 0;
2274 goto error;
2275 }
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00002276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002277 /* Check the stuff at the start of p first: if there's underwrite
2278 * corruption, the number-of-bytes field may be nuts, and checking
2279 * the tail could lead to a segfault then.
2280 */
2281 for (i = SST-1; i >= 1; --i) {
2282 if (*(q-i) != FORBIDDENBYTE) {
2283 msg = "bad leading pad byte";
2284 goto error;
2285 }
2286 }
Tim Petersddea2082002-03-23 10:03:50 +00002287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002288 nbytes = read_size_t(q - 2*SST);
2289 tail = q + nbytes;
2290 for (i = 0; i < SST; ++i) {
2291 if (tail[i] != FORBIDDENBYTE) {
2292 msg = "bad trailing pad byte";
2293 goto error;
2294 }
2295 }
Tim Petersddea2082002-03-23 10:03:50 +00002296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002297 return;
Tim Petersd1139e02002-03-28 07:32:11 +00002298
2299error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002300 _PyObject_DebugDumpAddress(p);
2301 Py_FatalError(msg);
Tim Petersddea2082002-03-23 10:03:50 +00002302}
2303
Tim Peters7ccfadf2002-04-01 06:04:21 +00002304/* Display info to stderr about the memory block at p. */
Victor Stinner0507bf52013-07-07 02:05:46 +02002305static void
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00002306_PyObject_DebugDumpAddress(const void *p)
Tim Petersddea2082002-03-23 10:03:50 +00002307{
Benjamin Peterson19517e42016-09-18 19:22:22 -07002308 const uint8_t *q = (const uint8_t *)p;
2309 const uint8_t *tail;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002310 size_t nbytes, serial;
2311 int i;
2312 int ok;
2313 char id;
Tim Petersddea2082002-03-23 10:03:50 +00002314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002315 fprintf(stderr, "Debug memory block at address p=%p:", p);
2316 if (p == NULL) {
2317 fprintf(stderr, "\n");
2318 return;
2319 }
2320 id = (char)q[-SST];
2321 fprintf(stderr, " API '%c'\n", id);
Tim Petersddea2082002-03-23 10:03:50 +00002322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002323 nbytes = read_size_t(q - 2*SST);
2324 fprintf(stderr, " %" PY_FORMAT_SIZE_T "u bytes originally "
2325 "requested\n", nbytes);
Tim Petersddea2082002-03-23 10:03:50 +00002326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002327 /* In case this is nuts, check the leading pad bytes first. */
2328 fprintf(stderr, " The %d pad bytes at p-%d are ", SST-1, SST-1);
2329 ok = 1;
2330 for (i = 1; i <= SST-1; ++i) {
2331 if (*(q-i) != FORBIDDENBYTE) {
2332 ok = 0;
2333 break;
2334 }
2335 }
2336 if (ok)
2337 fputs("FORBIDDENBYTE, as expected.\n", stderr);
2338 else {
2339 fprintf(stderr, "not all FORBIDDENBYTE (0x%02x):\n",
2340 FORBIDDENBYTE);
2341 for (i = SST-1; i >= 1; --i) {
Benjamin Peterson19517e42016-09-18 19:22:22 -07002342 const uint8_t byte = *(q-i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002343 fprintf(stderr, " at p-%d: 0x%02x", i, byte);
2344 if (byte != FORBIDDENBYTE)
2345 fputs(" *** OUCH", stderr);
2346 fputc('\n', stderr);
2347 }
Tim Peters449b5a82002-04-28 06:14:45 +00002348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002349 fputs(" Because memory is corrupted at the start, the "
2350 "count of bytes requested\n"
2351 " may be bogus, and checking the trailing pad "
2352 "bytes may segfault.\n", stderr);
2353 }
Tim Petersddea2082002-03-23 10:03:50 +00002354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002355 tail = q + nbytes;
2356 fprintf(stderr, " The %d pad bytes at tail=%p are ", SST, tail);
2357 ok = 1;
2358 for (i = 0; i < SST; ++i) {
2359 if (tail[i] != FORBIDDENBYTE) {
2360 ok = 0;
2361 break;
2362 }
2363 }
2364 if (ok)
2365 fputs("FORBIDDENBYTE, as expected.\n", stderr);
2366 else {
2367 fprintf(stderr, "not all FORBIDDENBYTE (0x%02x):\n",
Stefan Krah735bb122010-11-26 10:54:09 +00002368 FORBIDDENBYTE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002369 for (i = 0; i < SST; ++i) {
Benjamin Peterson19517e42016-09-18 19:22:22 -07002370 const uint8_t byte = tail[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002371 fprintf(stderr, " at tail+%d: 0x%02x",
Stefan Krah735bb122010-11-26 10:54:09 +00002372 i, byte);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002373 if (byte != FORBIDDENBYTE)
2374 fputs(" *** OUCH", stderr);
2375 fputc('\n', stderr);
2376 }
2377 }
Tim Petersddea2082002-03-23 10:03:50 +00002378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002379 serial = read_size_t(tail + SST);
2380 fprintf(stderr, " The block was made by call #%" PY_FORMAT_SIZE_T
2381 "u to debug malloc/realloc.\n", serial);
Tim Petersddea2082002-03-23 10:03:50 +00002382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002383 if (nbytes > 0) {
2384 i = 0;
2385 fputs(" Data at p:", stderr);
2386 /* print up to 8 bytes at the start */
2387 while (q < tail && i < 8) {
2388 fprintf(stderr, " %02x", *q);
2389 ++i;
2390 ++q;
2391 }
2392 /* and up to 8 at the end */
2393 if (q < tail) {
2394 if (tail - q > 8) {
2395 fputs(" ...", stderr);
2396 q = tail - 8;
2397 }
2398 while (q < tail) {
2399 fprintf(stderr, " %02x", *q);
2400 ++q;
2401 }
2402 }
2403 fputc('\n', stderr);
2404 }
Victor Stinner0611c262016-03-15 22:22:13 +01002405 fputc('\n', stderr);
2406
2407 fflush(stderr);
2408 _PyMem_DumpTraceback(fileno(stderr), p);
Tim Petersddea2082002-03-23 10:03:50 +00002409}
2410
David Malcolm49526f42012-06-22 14:55:41 -04002411
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00002412static size_t
David Malcolm49526f42012-06-22 14:55:41 -04002413printone(FILE *out, const char* msg, size_t value)
Tim Peters16bcb6b2002-04-05 05:45:31 +00002414{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002415 int i, k;
2416 char buf[100];
2417 size_t origvalue = value;
Tim Peters16bcb6b2002-04-05 05:45:31 +00002418
David Malcolm49526f42012-06-22 14:55:41 -04002419 fputs(msg, out);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002420 for (i = (int)strlen(msg); i < 35; ++i)
David Malcolm49526f42012-06-22 14:55:41 -04002421 fputc(' ', out);
2422 fputc('=', out);
Tim Peters49f26812002-04-06 01:45:35 +00002423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002424 /* Write the value with commas. */
2425 i = 22;
2426 buf[i--] = '\0';
2427 buf[i--] = '\n';
2428 k = 3;
2429 do {
2430 size_t nextvalue = value / 10;
Benjamin Peterson2dba1ee2013-02-20 16:54:30 -05002431 unsigned int digit = (unsigned int)(value - nextvalue * 10);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002432 value = nextvalue;
2433 buf[i--] = (char)(digit + '0');
2434 --k;
2435 if (k == 0 && value && i >= 0) {
2436 k = 3;
2437 buf[i--] = ',';
2438 }
2439 } while (value && i >= 0);
Tim Peters49f26812002-04-06 01:45:35 +00002440
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002441 while (i >= 0)
2442 buf[i--] = ' ';
David Malcolm49526f42012-06-22 14:55:41 -04002443 fputs(buf, out);
Tim Peters49f26812002-04-06 01:45:35 +00002444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002445 return origvalue;
Tim Peters16bcb6b2002-04-05 05:45:31 +00002446}
2447
David Malcolm49526f42012-06-22 14:55:41 -04002448void
2449_PyDebugAllocatorStats(FILE *out,
2450 const char *block_name, int num_blocks, size_t sizeof_block)
2451{
2452 char buf1[128];
2453 char buf2[128];
2454 PyOS_snprintf(buf1, sizeof(buf1),
Tim Peterseaa3bcc2013-09-05 22:57:04 -05002455 "%d %ss * %" PY_FORMAT_SIZE_T "d bytes each",
David Malcolm49526f42012-06-22 14:55:41 -04002456 num_blocks, block_name, sizeof_block);
2457 PyOS_snprintf(buf2, sizeof(buf2),
2458 "%48s ", buf1);
2459 (void)printone(out, buf2, num_blocks * sizeof_block);
2460}
2461
Victor Stinner34be807c2016-03-14 12:04:26 +01002462
David Malcolm49526f42012-06-22 14:55:41 -04002463#ifdef WITH_PYMALLOC
2464
Victor Stinner34be807c2016-03-14 12:04:26 +01002465#ifdef Py_DEBUG
2466/* Is target in the list? The list is traversed via the nextpool pointers.
2467 * The list may be NULL-terminated, or circular. Return 1 if target is in
2468 * list, else 0.
2469 */
2470static int
2471pool_is_in_list(const poolp target, poolp list)
2472{
2473 poolp origlist = list;
2474 assert(target != NULL);
2475 if (list == NULL)
2476 return 0;
2477 do {
2478 if (target == list)
2479 return 1;
2480 list = list->nextpool;
2481 } while (list != NULL && list != origlist);
2482 return 0;
2483}
2484#endif
2485
David Malcolm49526f42012-06-22 14:55:41 -04002486/* Print summary info to "out" about the state of pymalloc's structures.
Tim Peters08d82152002-04-18 22:25:03 +00002487 * In Py_DEBUG mode, also perform some expensive internal consistency
2488 * checks.
Victor Stinner6bf992a2017-12-06 17:26:10 +01002489 *
2490 * Return 0 if the memory debug hooks are not installed or no statistics was
Miss Islington (bot)e86db342018-02-03 17:41:43 -08002491 * written into out, return 1 otherwise.
Tim Peters08d82152002-04-18 22:25:03 +00002492 */
Victor Stinner6bf992a2017-12-06 17:26:10 +01002493int
David Malcolm49526f42012-06-22 14:55:41 -04002494_PyObject_DebugMallocStats(FILE *out)
Tim Peters7ccfadf2002-04-01 06:04:21 +00002495{
Victor Stinner6bf992a2017-12-06 17:26:10 +01002496 if (!_PyMem_PymallocEnabled()) {
2497 return 0;
2498 }
2499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002500 uint i;
2501 const uint numclasses = SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT;
2502 /* # of pools, allocated blocks, and free blocks per class index */
2503 size_t numpools[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT];
2504 size_t numblocks[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT];
2505 size_t numfreeblocks[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT];
2506 /* total # of allocated bytes in used and full pools */
2507 size_t allocated_bytes = 0;
2508 /* total # of available bytes in used pools */
2509 size_t available_bytes = 0;
2510 /* # of free pools + pools not yet carved out of current arena */
2511 uint numfreepools = 0;
2512 /* # of bytes for arena alignment padding */
2513 size_t arena_alignment = 0;
2514 /* # of bytes in used and full pools used for pool_headers */
2515 size_t pool_header_bytes = 0;
2516 /* # of bytes in used and full pools wasted due to quantization,
2517 * i.e. the necessarily leftover space at the ends of used and
2518 * full pools.
2519 */
2520 size_t quantization = 0;
2521 /* # of arenas actually allocated. */
2522 size_t narenas = 0;
2523 /* running total -- should equal narenas * ARENA_SIZE */
2524 size_t total;
2525 char buf[128];
Tim Peters7ccfadf2002-04-01 06:04:21 +00002526
David Malcolm49526f42012-06-22 14:55:41 -04002527 fprintf(out, "Small block threshold = %d, in %u size classes.\n",
Stefan Krah735bb122010-11-26 10:54:09 +00002528 SMALL_REQUEST_THRESHOLD, numclasses);
Tim Peters7ccfadf2002-04-01 06:04:21 +00002529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002530 for (i = 0; i < numclasses; ++i)
2531 numpools[i] = numblocks[i] = numfreeblocks[i] = 0;
Tim Peters7ccfadf2002-04-01 06:04:21 +00002532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002533 /* Because full pools aren't linked to from anything, it's easiest
2534 * to march over all the arenas. If we're lucky, most of the memory
2535 * will be living in full pools -- would be a shame to miss them.
2536 */
Victor Stinner9e87e772017-11-24 12:09:24 +01002537 for (i = 0; i < maxarenas; ++i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002538 uint j;
Victor Stinner9e87e772017-11-24 12:09:24 +01002539 uintptr_t base = arenas[i].address;
Thomas Woutersa9773292006-04-21 09:43:23 +00002540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002541 /* Skip arenas which are not allocated. */
Victor Stinner9e87e772017-11-24 12:09:24 +01002542 if (arenas[i].address == (uintptr_t)NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002543 continue;
2544 narenas += 1;
Thomas Woutersa9773292006-04-21 09:43:23 +00002545
Victor Stinner9e87e772017-11-24 12:09:24 +01002546 numfreepools += arenas[i].nfreepools;
Tim Peters7ccfadf2002-04-01 06:04:21 +00002547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002548 /* round up to pool alignment */
Benjamin Peterson5d4b09c2016-09-18 19:24:52 -07002549 if (base & (uintptr_t)POOL_SIZE_MASK) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002550 arena_alignment += POOL_SIZE;
Benjamin Peterson5d4b09c2016-09-18 19:24:52 -07002551 base &= ~(uintptr_t)POOL_SIZE_MASK;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002552 base += POOL_SIZE;
2553 }
Tim Peters7ccfadf2002-04-01 06:04:21 +00002554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002555 /* visit every pool in the arena */
Victor Stinner9e87e772017-11-24 12:09:24 +01002556 assert(base <= (uintptr_t) arenas[i].pool_address);
2557 for (j = 0; base < (uintptr_t) arenas[i].pool_address;
Benjamin Peterson19517e42016-09-18 19:22:22 -07002558 ++j, base += POOL_SIZE) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002559 poolp p = (poolp)base;
2560 const uint sz = p->szidx;
2561 uint freeblocks;
Tim Peters08d82152002-04-18 22:25:03 +00002562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002563 if (p->ref.count == 0) {
2564 /* currently unused */
Victor Stinner34be807c2016-03-14 12:04:26 +01002565#ifdef Py_DEBUG
Victor Stinner9e87e772017-11-24 12:09:24 +01002566 assert(pool_is_in_list(p, arenas[i].freepools));
Victor Stinner34be807c2016-03-14 12:04:26 +01002567#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002568 continue;
2569 }
2570 ++numpools[sz];
2571 numblocks[sz] += p->ref.count;
2572 freeblocks = NUMBLOCKS(sz) - p->ref.count;
2573 numfreeblocks[sz] += freeblocks;
Tim Peters08d82152002-04-18 22:25:03 +00002574#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002575 if (freeblocks > 0)
Victor Stinner9e87e772017-11-24 12:09:24 +01002576 assert(pool_is_in_list(p, usedpools[sz + sz]));
Tim Peters08d82152002-04-18 22:25:03 +00002577#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002578 }
2579 }
Victor Stinner9e87e772017-11-24 12:09:24 +01002580 assert(narenas == narenas_currently_allocated);
Tim Peters7ccfadf2002-04-01 06:04:21 +00002581
David Malcolm49526f42012-06-22 14:55:41 -04002582 fputc('\n', out);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002583 fputs("class size num pools blocks in use avail blocks\n"
2584 "----- ---- --------- ------------- ------------\n",
David Malcolm49526f42012-06-22 14:55:41 -04002585 out);
Tim Peters7ccfadf2002-04-01 06:04:21 +00002586
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002587 for (i = 0; i < numclasses; ++i) {
2588 size_t p = numpools[i];
2589 size_t b = numblocks[i];
2590 size_t f = numfreeblocks[i];
2591 uint size = INDEX2SIZE(i);
2592 if (p == 0) {
2593 assert(b == 0 && f == 0);
2594 continue;
2595 }
David Malcolm49526f42012-06-22 14:55:41 -04002596 fprintf(out, "%5u %6u "
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002597 "%11" PY_FORMAT_SIZE_T "u "
2598 "%15" PY_FORMAT_SIZE_T "u "
2599 "%13" PY_FORMAT_SIZE_T "u\n",
Stefan Krah735bb122010-11-26 10:54:09 +00002600 i, size, p, b, f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002601 allocated_bytes += b * size;
2602 available_bytes += f * size;
2603 pool_header_bytes += p * POOL_OVERHEAD;
2604 quantization += p * ((POOL_SIZE - POOL_OVERHEAD) % size);
2605 }
David Malcolm49526f42012-06-22 14:55:41 -04002606 fputc('\n', out);
Victor Stinner34be807c2016-03-14 12:04:26 +01002607 if (_PyMem_DebugEnabled())
Victor Stinner9e87e772017-11-24 12:09:24 +01002608 (void)printone(out, "# times object malloc called", serialno);
2609 (void)printone(out, "# arenas allocated total", ntimes_arena_allocated);
2610 (void)printone(out, "# arenas reclaimed", ntimes_arena_allocated - narenas);
2611 (void)printone(out, "# arenas highwater mark", narenas_highwater);
David Malcolm49526f42012-06-22 14:55:41 -04002612 (void)printone(out, "# arenas allocated current", narenas);
Thomas Woutersa9773292006-04-21 09:43:23 +00002613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002614 PyOS_snprintf(buf, sizeof(buf),
2615 "%" PY_FORMAT_SIZE_T "u arenas * %d bytes/arena",
2616 narenas, ARENA_SIZE);
David Malcolm49526f42012-06-22 14:55:41 -04002617 (void)printone(out, buf, narenas * ARENA_SIZE);
Tim Peters16bcb6b2002-04-05 05:45:31 +00002618
David Malcolm49526f42012-06-22 14:55:41 -04002619 fputc('\n', out);
Tim Peters16bcb6b2002-04-05 05:45:31 +00002620
David Malcolm49526f42012-06-22 14:55:41 -04002621 total = printone(out, "# bytes in allocated blocks", allocated_bytes);
2622 total += printone(out, "# bytes in available blocks", available_bytes);
Tim Peters49f26812002-04-06 01:45:35 +00002623
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002624 PyOS_snprintf(buf, sizeof(buf),
2625 "%u unused pools * %d bytes", numfreepools, POOL_SIZE);
David Malcolm49526f42012-06-22 14:55:41 -04002626 total += printone(out, buf, (size_t)numfreepools * POOL_SIZE);
Tim Peters16bcb6b2002-04-05 05:45:31 +00002627
David Malcolm49526f42012-06-22 14:55:41 -04002628 total += printone(out, "# bytes lost to pool headers", pool_header_bytes);
2629 total += printone(out, "# bytes lost to quantization", quantization);
2630 total += printone(out, "# bytes lost to arena alignment", arena_alignment);
2631 (void)printone(out, "Total", total);
Victor Stinner6bf992a2017-12-06 17:26:10 +01002632 return 1;
Tim Peters7ccfadf2002-04-01 06:04:21 +00002633}
2634
David Malcolm49526f42012-06-22 14:55:41 -04002635#endif /* #ifdef WITH_PYMALLOC */