blob: 885ad537ad959d11fc64e4264c1c49aa3b6b3765 [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 */
Miss Islington (bot)1b85f4e2019-05-25 10:18:34 -0700791
792#if SIZEOF_VOID_P > 4
793#define ALIGNMENT 16 /* must be 2^N */
794#define ALIGNMENT_SHIFT 4
795#else
Victor Stinner9e87e772017-11-24 12:09:24 +0100796#define ALIGNMENT 8 /* must be 2^N */
797#define ALIGNMENT_SHIFT 3
Miss Islington (bot)1b85f4e2019-05-25 10:18:34 -0700798#endif
Victor Stinner9e87e772017-11-24 12:09:24 +0100799
800/* Return the number of bytes in size class I, as a uint. */
801#define INDEX2SIZE(I) (((uint)(I) + 1) << ALIGNMENT_SHIFT)
802
803/*
804 * Max size threshold below which malloc requests are considered to be
805 * small enough in order to use preallocated memory pools. You can tune
806 * this value according to your application behaviour and memory needs.
807 *
808 * Note: a size threshold of 512 guarantees that newly created dictionaries
809 * will be allocated from preallocated memory pools on 64-bit.
810 *
811 * The following invariants must hold:
812 * 1) ALIGNMENT <= SMALL_REQUEST_THRESHOLD <= 512
813 * 2) SMALL_REQUEST_THRESHOLD is evenly divisible by ALIGNMENT
814 *
815 * Although not required, for better performance and space efficiency,
816 * it is recommended that SMALL_REQUEST_THRESHOLD is set to a power of 2.
817 */
818#define SMALL_REQUEST_THRESHOLD 512
819#define NB_SMALL_SIZE_CLASSES (SMALL_REQUEST_THRESHOLD / ALIGNMENT)
820
821/*
822 * The system's VMM page size can be obtained on most unices with a
823 * getpagesize() call or deduced from various header files. To make
824 * things simpler, we assume that it is 4K, which is OK for most systems.
825 * It is probably better if this is the native page size, but it doesn't
826 * have to be. In theory, if SYSTEM_PAGE_SIZE is larger than the native page
827 * size, then `POOL_ADDR(p)->arenaindex' could rarely cause a segmentation
828 * violation fault. 4K is apparently OK for all the platforms that python
829 * currently targets.
830 */
831#define SYSTEM_PAGE_SIZE (4 * 1024)
832#define SYSTEM_PAGE_SIZE_MASK (SYSTEM_PAGE_SIZE - 1)
833
834/*
835 * Maximum amount of memory managed by the allocator for small requests.
836 */
837#ifdef WITH_MEMORY_LIMITS
838#ifndef SMALL_MEMORY_LIMIT
839#define SMALL_MEMORY_LIMIT (64 * 1024 * 1024) /* 64 MB -- more? */
840#endif
841#endif
842
843/*
844 * The allocator sub-allocates <Big> blocks of memory (called arenas) aligned
845 * on a page boundary. This is a reserved virtual address space for the
846 * current process (obtained through a malloc()/mmap() call). In no way this
847 * means that the memory arenas will be used entirely. A malloc(<Big>) is
848 * usually an address range reservation for <Big> bytes, unless all pages within
849 * this space are referenced subsequently. So malloc'ing big blocks and not
850 * using them does not mean "wasting memory". It's an addressable range
851 * wastage...
852 *
853 * Arenas are allocated with mmap() on systems supporting anonymous memory
854 * mappings to reduce heap fragmentation.
855 */
856#define ARENA_SIZE (256 << 10) /* 256KB */
857
858#ifdef WITH_MEMORY_LIMITS
859#define MAX_ARENAS (SMALL_MEMORY_LIMIT / ARENA_SIZE)
860#endif
861
862/*
863 * Size of the pools used for small blocks. Should be a power of 2,
864 * between 1K and SYSTEM_PAGE_SIZE, that is: 1k, 2k, 4k.
865 */
866#define POOL_SIZE SYSTEM_PAGE_SIZE /* must be 2^N */
867#define POOL_SIZE_MASK SYSTEM_PAGE_SIZE_MASK
868
869/*
870 * -- End of tunable settings section --
871 */
872
873/*==========================================================================*/
874
875/*
876 * Locking
877 *
878 * To reduce lock contention, it would probably be better to refine the
879 * crude function locking with per size class locking. I'm not positive
880 * however, whether it's worth switching to such locking policy because
881 * of the performance penalty it might introduce.
882 *
883 * The following macros describe the simplest (should also be the fastest)
884 * lock object on a particular platform and the init/fini/lock/unlock
885 * operations on it. The locks defined here are not expected to be recursive
886 * because it is assumed that they will always be called in the order:
887 * INIT, [LOCK, UNLOCK]*, FINI.
888 */
889
890/*
891 * Python's threads are serialized, so object malloc locking is disabled.
892 */
893#define SIMPLELOCK_DECL(lock) /* simple lock declaration */
894#define SIMPLELOCK_INIT(lock) /* allocate (if needed) and initialize */
895#define SIMPLELOCK_FINI(lock) /* free/destroy an existing lock */
896#define SIMPLELOCK_LOCK(lock) /* acquire released lock */
897#define SIMPLELOCK_UNLOCK(lock) /* release acquired lock */
898
899/* When you say memory, my mind reasons in terms of (pointers to) blocks */
900typedef uint8_t block;
901
902/* Pool for small blocks. */
903struct pool_header {
904 union { block *_padding;
905 uint count; } ref; /* number of allocated blocks */
906 block *freeblock; /* pool's free list head */
907 struct pool_header *nextpool; /* next pool of this size class */
908 struct pool_header *prevpool; /* previous pool "" */
909 uint arenaindex; /* index into arenas of base adr */
910 uint szidx; /* block size class index */
911 uint nextoffset; /* bytes to virgin block */
912 uint maxnextoffset; /* largest valid nextoffset */
913};
914
915typedef struct pool_header *poolp;
916
917/* Record keeping for arenas. */
918struct arena_object {
919 /* The address of the arena, as returned by malloc. Note that 0
920 * will never be returned by a successful malloc, and is used
921 * here to mark an arena_object that doesn't correspond to an
922 * allocated arena.
923 */
924 uintptr_t address;
925
926 /* Pool-aligned pointer to the next pool to be carved off. */
927 block* pool_address;
928
929 /* The number of available pools in the arena: free pools + never-
930 * allocated pools.
931 */
932 uint nfreepools;
933
934 /* The total number of pools in the arena, whether or not available. */
935 uint ntotalpools;
936
937 /* Singly-linked list of available pools. */
938 struct pool_header* freepools;
939
940 /* Whenever this arena_object is not associated with an allocated
941 * arena, the nextarena member is used to link all unassociated
942 * arena_objects in the singly-linked `unused_arena_objects` list.
943 * The prevarena member is unused in this case.
944 *
945 * When this arena_object is associated with an allocated arena
946 * with at least one available pool, both members are used in the
947 * doubly-linked `usable_arenas` list, which is maintained in
948 * increasing order of `nfreepools` values.
949 *
950 * Else this arena_object is associated with an allocated arena
951 * all of whose pools are in use. `nextarena` and `prevarena`
952 * are both meaningless in this case.
953 */
954 struct arena_object* nextarena;
955 struct arena_object* prevarena;
956};
957
958#define POOL_OVERHEAD _Py_SIZE_ROUND_UP(sizeof(struct pool_header), ALIGNMENT)
959
960#define DUMMY_SIZE_IDX 0xffff /* size class of newly cached pools */
961
962/* Round pointer P down to the closest pool-aligned address <= P, as a poolp */
963#define POOL_ADDR(P) ((poolp)_Py_ALIGN_DOWN((P), POOL_SIZE))
964
965/* Return total number of blocks in pool of size index I, as a uint. */
966#define NUMBLOCKS(I) ((uint)(POOL_SIZE - POOL_OVERHEAD) / INDEX2SIZE(I))
967
968/*==========================================================================*/
969
970/*
971 * This malloc lock
972 */
973SIMPLELOCK_DECL(_malloc_lock)
974#define LOCK() SIMPLELOCK_LOCK(_malloc_lock)
975#define UNLOCK() SIMPLELOCK_UNLOCK(_malloc_lock)
976#define LOCK_INIT() SIMPLELOCK_INIT(_malloc_lock)
977#define LOCK_FINI() SIMPLELOCK_FINI(_malloc_lock)
978
979/*
980 * Pool table -- headed, circular, doubly-linked lists of partially used pools.
981
982This is involved. For an index i, usedpools[i+i] is the header for a list of
983all partially used pools holding small blocks with "size class idx" i. So
984usedpools[0] corresponds to blocks of size 8, usedpools[2] to blocks of size
98516, and so on: index 2*i <-> blocks of size (i+1)<<ALIGNMENT_SHIFT.
986
987Pools are carved off an arena's highwater mark (an arena_object's pool_address
988member) as needed. Once carved off, a pool is in one of three states forever
989after:
990
991used == partially used, neither empty nor full
992 At least one block in the pool is currently allocated, and at least one
993 block in the pool is not currently allocated (note this implies a pool
994 has room for at least two blocks).
995 This is a pool's initial state, as a pool is created only when malloc
996 needs space.
997 The pool holds blocks of a fixed size, and is in the circular list headed
998 at usedpools[i] (see above). It's linked to the other used pools of the
999 same size class via the pool_header's nextpool and prevpool members.
1000 If all but one block is currently allocated, a malloc can cause a
1001 transition to the full state. If all but one block is not currently
1002 allocated, a free can cause a transition to the empty state.
1003
1004full == all the pool's blocks are currently allocated
1005 On transition to full, a pool is unlinked from its usedpools[] list.
1006 It's not linked to from anything then anymore, and its nextpool and
1007 prevpool members are meaningless until it transitions back to used.
1008 A free of a block in a full pool puts the pool back in the used state.
1009 Then it's linked in at the front of the appropriate usedpools[] list, so
1010 that the next allocation for its size class will reuse the freed block.
1011
1012empty == all the pool's blocks are currently available for allocation
1013 On transition to empty, a pool is unlinked from its usedpools[] list,
1014 and linked to the front of its arena_object's singly-linked freepools list,
1015 via its nextpool member. The prevpool member has no meaning in this case.
1016 Empty pools have no inherent size class: the next time a malloc finds
1017 an empty list in usedpools[], it takes the first pool off of freepools.
1018 If the size class needed happens to be the same as the size class the pool
1019 last had, some pool initialization can be skipped.
1020
1021
1022Block Management
1023
1024Blocks within pools are again carved out as needed. pool->freeblock points to
1025the start of a singly-linked list of free blocks within the pool. When a
1026block is freed, it's inserted at the front of its pool's freeblock list. Note
1027that the available blocks in a pool are *not* linked all together when a pool
1028is initialized. Instead only "the first two" (lowest addresses) blocks are
1029set up, returning the first such block, and setting pool->freeblock to a
1030one-block list holding the second such block. This is consistent with that
1031pymalloc strives at all levels (arena, pool, and block) never to touch a piece
1032of memory until it's actually needed.
1033
1034So long as a pool is in the used state, we're certain there *is* a block
1035available for allocating, and pool->freeblock is not NULL. If pool->freeblock
1036points to the end of the free list before we've carved the entire pool into
1037blocks, that means we simply haven't yet gotten to one of the higher-address
1038blocks. The offset from the pool_header to the start of "the next" virgin
1039block is stored in the pool_header nextoffset member, and the largest value
1040of nextoffset that makes sense is stored in the maxnextoffset member when a
1041pool is initialized. All the blocks in a pool have been passed out at least
1042once when and only when nextoffset > maxnextoffset.
1043
1044
1045Major obscurity: While the usedpools vector is declared to have poolp
1046entries, it doesn't really. It really contains two pointers per (conceptual)
1047poolp entry, the nextpool and prevpool members of a pool_header. The
1048excruciating initialization code below fools C so that
1049
1050 usedpool[i+i]
1051
1052"acts like" a genuine poolp, but only so long as you only reference its
1053nextpool and prevpool members. The "- 2*sizeof(block *)" gibberish is
1054compensating for that a pool_header's nextpool and prevpool members
1055immediately follow a pool_header's first two members:
1056
1057 union { block *_padding;
1058 uint count; } ref;
1059 block *freeblock;
1060
1061each of which consume sizeof(block *) bytes. So what usedpools[i+i] really
1062contains is a fudged-up pointer p such that *if* C believes it's a poolp
1063pointer, then p->nextpool and p->prevpool are both p (meaning that the headed
1064circular list is empty).
1065
1066It's unclear why the usedpools setup is so convoluted. It could be to
1067minimize the amount of cache required to hold this heavily-referenced table
1068(which only *needs* the two interpool pointer members of a pool_header). OTOH,
1069referencing code has to remember to "double the index" and doing so isn't
1070free, usedpools[0] isn't a strictly legal pointer, and we're crucially relying
1071on that C doesn't insert any padding anywhere in a pool_header at or before
1072the prevpool member.
1073**************************************************************************** */
1074
1075#define PTA(x) ((poolp )((uint8_t *)&(usedpools[2*(x)]) - 2*sizeof(block *)))
1076#define PT(x) PTA(x), PTA(x)
1077
1078static poolp usedpools[2 * ((NB_SMALL_SIZE_CLASSES + 7) / 8) * 8] = {
1079 PT(0), PT(1), PT(2), PT(3), PT(4), PT(5), PT(6), PT(7)
1080#if NB_SMALL_SIZE_CLASSES > 8
1081 , PT(8), PT(9), PT(10), PT(11), PT(12), PT(13), PT(14), PT(15)
1082#if NB_SMALL_SIZE_CLASSES > 16
1083 , PT(16), PT(17), PT(18), PT(19), PT(20), PT(21), PT(22), PT(23)
1084#if NB_SMALL_SIZE_CLASSES > 24
1085 , PT(24), PT(25), PT(26), PT(27), PT(28), PT(29), PT(30), PT(31)
1086#if NB_SMALL_SIZE_CLASSES > 32
1087 , PT(32), PT(33), PT(34), PT(35), PT(36), PT(37), PT(38), PT(39)
1088#if NB_SMALL_SIZE_CLASSES > 40
1089 , PT(40), PT(41), PT(42), PT(43), PT(44), PT(45), PT(46), PT(47)
1090#if NB_SMALL_SIZE_CLASSES > 48
1091 , PT(48), PT(49), PT(50), PT(51), PT(52), PT(53), PT(54), PT(55)
1092#if NB_SMALL_SIZE_CLASSES > 56
1093 , PT(56), PT(57), PT(58), PT(59), PT(60), PT(61), PT(62), PT(63)
1094#if NB_SMALL_SIZE_CLASSES > 64
1095#error "NB_SMALL_SIZE_CLASSES should be less than 64"
1096#endif /* NB_SMALL_SIZE_CLASSES > 64 */
1097#endif /* NB_SMALL_SIZE_CLASSES > 56 */
1098#endif /* NB_SMALL_SIZE_CLASSES > 48 */
1099#endif /* NB_SMALL_SIZE_CLASSES > 40 */
1100#endif /* NB_SMALL_SIZE_CLASSES > 32 */
1101#endif /* NB_SMALL_SIZE_CLASSES > 24 */
1102#endif /* NB_SMALL_SIZE_CLASSES > 16 */
1103#endif /* NB_SMALL_SIZE_CLASSES > 8 */
1104};
1105
1106/*==========================================================================
1107Arena management.
1108
1109`arenas` is a vector of arena_objects. It contains maxarenas entries, some of
1110which may not be currently used (== they're arena_objects that aren't
1111currently associated with an allocated arena). Note that arenas proper are
1112separately malloc'ed.
1113
1114Prior to Python 2.5, arenas were never free()'ed. Starting with Python 2.5,
1115we do try to free() arenas, and use some mild heuristic strategies to increase
1116the likelihood that arenas eventually can be freed.
1117
1118unused_arena_objects
1119
1120 This is a singly-linked list of the arena_objects that are currently not
1121 being used (no arena is associated with them). Objects are taken off the
1122 head of the list in new_arena(), and are pushed on the head of the list in
1123 PyObject_Free() when the arena is empty. Key invariant: an arena_object
1124 is on this list if and only if its .address member is 0.
1125
1126usable_arenas
1127
1128 This is a doubly-linked list of the arena_objects associated with arenas
1129 that have pools available. These pools are either waiting to be reused,
1130 or have not been used before. The list is sorted to have the most-
1131 allocated arenas first (ascending order based on the nfreepools member).
1132 This means that the next allocation will come from a heavily used arena,
1133 which gives the nearly empty arenas a chance to be returned to the system.
1134 In my unscientific tests this dramatically improved the number of arenas
1135 that could be freed.
1136
1137Note that an arena_object associated with an arena all of whose pools are
1138currently in use isn't on either list.
1139*/
1140
1141/* Array of objects used to track chunks of memory (arenas). */
1142static struct arena_object* arenas = NULL;
1143/* Number of slots currently allocated in the `arenas` vector. */
1144static uint maxarenas = 0;
1145
1146/* The head of the singly-linked, NULL-terminated list of available
1147 * arena_objects.
1148 */
1149static struct arena_object* unused_arena_objects = NULL;
1150
1151/* The head of the doubly-linked, NULL-terminated at each end, list of
1152 * arena_objects associated with arenas that have pools available.
1153 */
1154static struct arena_object* usable_arenas = NULL;
1155
1156/* How many arena_objects do we initially allocate?
1157 * 16 = can allocate 16 arenas = 16 * ARENA_SIZE = 4MB before growing the
1158 * `arenas` vector.
1159 */
1160#define INITIAL_ARENA_OBJECTS 16
1161
1162/* Number of arenas allocated that haven't been free()'d. */
1163static size_t narenas_currently_allocated = 0;
1164
1165/* Total number of times malloc() called to allocate an arena. */
1166static size_t ntimes_arena_allocated = 0;
1167/* High water mark (max value ever seen) for narenas_currently_allocated. */
1168static size_t narenas_highwater = 0;
1169
1170static Py_ssize_t _Py_AllocatedBlocks = 0;
1171
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001172Py_ssize_t
1173_Py_GetAllocatedBlocks(void)
1174{
Victor Stinner9e87e772017-11-24 12:09:24 +01001175 return _Py_AllocatedBlocks;
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001176}
1177
1178
Thomas Woutersa9773292006-04-21 09:43:23 +00001179/* Allocate a new arena. If we run out of memory, return NULL. Else
1180 * allocate a new arena, and return the address of an arena_object
1181 * describing the new arena. It's expected that the caller will set
1182 * `usable_arenas` to the return value.
1183 */
1184static struct arena_object*
Tim Petersd97a1c02002-03-30 06:09:22 +00001185new_arena(void)
1186{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001187 struct arena_object* arenaobj;
1188 uint excess; /* number of bytes above pool alignment */
Victor Stinnerba108822012-03-10 00:21:44 +01001189 void *address;
Victor Stinner34be807c2016-03-14 12:04:26 +01001190 static int debug_stats = -1;
Tim Petersd97a1c02002-03-30 06:09:22 +00001191
Victor Stinner34be807c2016-03-14 12:04:26 +01001192 if (debug_stats == -1) {
Serhiy Storchaka4ae06c52017-12-12 13:55:04 +02001193 const char *opt = Py_GETENV("PYTHONMALLOCSTATS");
Victor Stinner34be807c2016-03-14 12:04:26 +01001194 debug_stats = (opt != NULL && *opt != '\0');
1195 }
1196 if (debug_stats)
David Malcolm49526f42012-06-22 14:55:41 -04001197 _PyObject_DebugMallocStats(stderr);
Victor Stinner34be807c2016-03-14 12:04:26 +01001198
Victor Stinner9e87e772017-11-24 12:09:24 +01001199 if (unused_arena_objects == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001200 uint i;
1201 uint numarenas;
1202 size_t nbytes;
Tim Peters0e871182002-04-13 08:29:14 +00001203
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 /* Double the number of arena objects on each allocation.
1205 * Note that it's possible for `numarenas` to overflow.
1206 */
Victor Stinner9e87e772017-11-24 12:09:24 +01001207 numarenas = maxarenas ? maxarenas << 1 : INITIAL_ARENA_OBJECTS;
1208 if (numarenas <= maxarenas)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001209 return NULL; /* overflow */
Martin v. Löwis5aca8822008-09-11 06:55:48 +00001210#if SIZEOF_SIZE_T <= SIZEOF_INT
Victor Stinner9e87e772017-11-24 12:09:24 +01001211 if (numarenas > SIZE_MAX / sizeof(*arenas))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001212 return NULL; /* overflow */
Martin v. Löwis5aca8822008-09-11 06:55:48 +00001213#endif
Victor Stinner9e87e772017-11-24 12:09:24 +01001214 nbytes = numarenas * sizeof(*arenas);
1215 arenaobj = (struct arena_object *)PyMem_RawRealloc(arenas, nbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001216 if (arenaobj == NULL)
1217 return NULL;
Victor Stinner9e87e772017-11-24 12:09:24 +01001218 arenas = arenaobj;
Thomas Woutersa9773292006-04-21 09:43:23 +00001219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001220 /* We might need to fix pointers that were copied. However,
1221 * new_arena only gets called when all the pages in the
1222 * previous arenas are full. Thus, there are *no* pointers
1223 * into the old array. Thus, we don't have to worry about
1224 * invalid pointers. Just to be sure, some asserts:
1225 */
Victor Stinner9e87e772017-11-24 12:09:24 +01001226 assert(usable_arenas == NULL);
1227 assert(unused_arena_objects == NULL);
Thomas Woutersa9773292006-04-21 09:43:23 +00001228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001229 /* Put the new arenas on the unused_arena_objects list. */
Victor Stinner9e87e772017-11-24 12:09:24 +01001230 for (i = maxarenas; i < numarenas; ++i) {
1231 arenas[i].address = 0; /* mark as unassociated */
1232 arenas[i].nextarena = i < numarenas - 1 ?
1233 &arenas[i+1] : NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 }
Thomas Woutersa9773292006-04-21 09:43:23 +00001235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001236 /* Update globals. */
Victor Stinner9e87e772017-11-24 12:09:24 +01001237 unused_arena_objects = &arenas[maxarenas];
1238 maxarenas = numarenas;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001239 }
Tim Petersd97a1c02002-03-30 06:09:22 +00001240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001241 /* Take the next available arena object off the head of the list. */
Victor Stinner9e87e772017-11-24 12:09:24 +01001242 assert(unused_arena_objects != NULL);
1243 arenaobj = unused_arena_objects;
1244 unused_arena_objects = arenaobj->nextarena;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001245 assert(arenaobj->address == 0);
Victor Stinner9e87e772017-11-24 12:09:24 +01001246 address = _PyObject_Arena.alloc(_PyObject_Arena.ctx, ARENA_SIZE);
Victor Stinner0507bf52013-07-07 02:05:46 +02001247 if (address == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001248 /* The allocation failed: return NULL after putting the
1249 * arenaobj back.
1250 */
Victor Stinner9e87e772017-11-24 12:09:24 +01001251 arenaobj->nextarena = unused_arena_objects;
1252 unused_arena_objects = arenaobj;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001253 return NULL;
1254 }
Benjamin Peterson5d4b09c2016-09-18 19:24:52 -07001255 arenaobj->address = (uintptr_t)address;
Tim Petersd97a1c02002-03-30 06:09:22 +00001256
Victor Stinner9e87e772017-11-24 12:09:24 +01001257 ++narenas_currently_allocated;
1258 ++ntimes_arena_allocated;
1259 if (narenas_currently_allocated > narenas_highwater)
1260 narenas_highwater = narenas_currently_allocated;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001261 arenaobj->freepools = NULL;
1262 /* pool_address <- first pool-aligned address in the arena
1263 nfreepools <- number of whole pools that fit after alignment */
Victor Stinner9e87e772017-11-24 12:09:24 +01001264 arenaobj->pool_address = (block*)arenaobj->address;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001265 arenaobj->nfreepools = ARENA_SIZE / POOL_SIZE;
1266 assert(POOL_SIZE * arenaobj->nfreepools == ARENA_SIZE);
1267 excess = (uint)(arenaobj->address & POOL_SIZE_MASK);
1268 if (excess != 0) {
1269 --arenaobj->nfreepools;
1270 arenaobj->pool_address += POOL_SIZE - excess;
1271 }
1272 arenaobj->ntotalpools = arenaobj->nfreepools;
Thomas Woutersa9773292006-04-21 09:43:23 +00001273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001274 return arenaobj;
Tim Petersd97a1c02002-03-30 06:09:22 +00001275}
1276
Victor Stinner9ed83c42017-10-31 12:18:10 -07001277
Thomas Woutersa9773292006-04-21 09:43:23 +00001278/*
Benjamin Peterson3924f932016-09-18 19:12:48 -07001279address_in_range(P, POOL)
Thomas Woutersa9773292006-04-21 09:43:23 +00001280
1281Return true if and only if P is an address that was allocated by pymalloc.
1282POOL must be the pool address associated with P, i.e., POOL = POOL_ADDR(P)
1283(the caller is asked to compute this because the macro expands POOL more than
1284once, and for efficiency it's best for the caller to assign POOL_ADDR(P) to a
Benjamin Peterson3924f932016-09-18 19:12:48 -07001285variable and pass the latter to the macro; because address_in_range is
Thomas Woutersa9773292006-04-21 09:43:23 +00001286called on every alloc/realloc/free, micro-efficiency is important here).
1287
1288Tricky: Let B be the arena base address associated with the pool, B =
1289arenas[(POOL)->arenaindex].address. Then P belongs to the arena if and only if
1290
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001291 B <= P < B + ARENA_SIZE
Thomas Woutersa9773292006-04-21 09:43:23 +00001292
1293Subtracting B throughout, this is true iff
1294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001295 0 <= P-B < ARENA_SIZE
Thomas Woutersa9773292006-04-21 09:43:23 +00001296
1297By using unsigned arithmetic, the "0 <=" half of the test can be skipped.
1298
1299Obscure: A PyMem "free memory" function can call the pymalloc free or realloc
1300before the first arena has been allocated. `arenas` is still NULL in that
1301case. We're relying on that maxarenas is also 0 in that case, so that
1302(POOL)->arenaindex < maxarenas must be false, saving us from trying to index
1303into a NULL arenas.
1304
1305Details: given P and POOL, the arena_object corresponding to P is AO =
1306arenas[(POOL)->arenaindex]. Suppose obmalloc controls P. Then (barring wild
1307stores, etc), POOL is the correct address of P's pool, AO.address is the
1308correct base address of the pool's arena, and P must be within ARENA_SIZE of
1309AO.address. In addition, AO.address is not 0 (no arena can start at address 0
Benjamin Peterson3924f932016-09-18 19:12:48 -07001310(NULL)). Therefore address_in_range correctly reports that obmalloc
Thomas Woutersa9773292006-04-21 09:43:23 +00001311controls P.
1312
1313Now suppose obmalloc does not control P (e.g., P was obtained via a direct
1314call to the system malloc() or realloc()). (POOL)->arenaindex may be anything
1315in this case -- it may even be uninitialized trash. If the trash arenaindex
1316is >= maxarenas, the macro correctly concludes at once that obmalloc doesn't
1317control P.
1318
1319Else arenaindex is < maxarena, and AO is read up. If AO corresponds to an
1320allocated arena, obmalloc controls all the memory in slice AO.address :
1321AO.address+ARENA_SIZE. By case assumption, P is not controlled by obmalloc,
1322so P doesn't lie in that slice, so the macro correctly reports that P is not
1323controlled by obmalloc.
1324
1325Finally, if P is not controlled by obmalloc and AO corresponds to an unused
1326arena_object (one not currently associated with an allocated arena),
1327AO.address is 0, and the second test in the macro reduces to:
1328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001329 P < ARENA_SIZE
Thomas Woutersa9773292006-04-21 09:43:23 +00001330
1331If P >= ARENA_SIZE (extremely likely), the macro again correctly concludes
1332that P is not controlled by obmalloc. However, if P < ARENA_SIZE, this part
1333of the test still passes, and the third clause (AO.address != 0) is necessary
1334to get the correct result: AO.address is 0 in this case, so the macro
1335correctly reports that P is not controlled by obmalloc (despite that P lies in
1336slice AO.address : AO.address + ARENA_SIZE).
1337
1338Note: The third (AO.address != 0) clause was added in Python 2.5. Before
13392.5, arenas were never free()'ed, and an arenaindex < maxarena always
1340corresponded to a currently-allocated arena, so the "P is not controlled by
1341obmalloc, AO corresponds to an unused arena_object, and P < ARENA_SIZE" case
1342was impossible.
1343
1344Note that the logic is excruciating, and reading up possibly uninitialized
1345memory when P is not controlled by obmalloc (to get at (POOL)->arenaindex)
1346creates problems for some memory debuggers. The overwhelming advantage is
1347that this test determines whether an arbitrary address is controlled by
1348obmalloc in a small constant time, independent of the number of arenas
1349obmalloc controls. Since this test is needed at every entry point, it's
1350extremely desirable that it be this fast.
1351*/
Thomas Woutersa9773292006-04-21 09:43:23 +00001352
Miss Islington (bot)1ec57812018-11-11 15:44:34 -08001353static bool _Py_NO_ADDRESS_SAFETY_ANALYSIS
1354 _Py_NO_SANITIZE_THREAD
1355 _Py_NO_SANITIZE_MEMORY
Benjamin Peterson3924f932016-09-18 19:12:48 -07001356address_in_range(void *p, poolp pool)
1357{
1358 // Since address_in_range may be reading from memory which was not allocated
1359 // by Python, it is important that pool->arenaindex is read only once, as
1360 // another thread may be concurrently modifying the value without holding
1361 // the GIL. The following dance forces the compiler to read pool->arenaindex
1362 // only once.
1363 uint arenaindex = *((volatile uint *)&pool->arenaindex);
Victor Stinner9e87e772017-11-24 12:09:24 +01001364 return arenaindex < maxarenas &&
1365 (uintptr_t)p - arenas[arenaindex].address < ARENA_SIZE &&
1366 arenas[arenaindex].address != 0;
Benjamin Peterson3924f932016-09-18 19:12:48 -07001367}
Tim Peters338e0102002-04-01 19:23:44 +00001368
Victor Stinner9ed83c42017-10-31 12:18:10 -07001369
Neil Schemenauera35c6882001-02-27 04:45:05 +00001370/*==========================================================================*/
1371
Victor Stinner9ed83c42017-10-31 12:18:10 -07001372/* pymalloc allocator
Neil Schemenauera35c6882001-02-27 04:45:05 +00001373
Victor Stinner9ed83c42017-10-31 12:18:10 -07001374 The basic blocks are ordered by decreasing execution frequency,
1375 which minimizes the number of jumps in the most common cases,
1376 improves branching prediction and instruction scheduling (small
1377 block allocations typically result in a couple of instructions).
1378 Unless the optimizer reorders everything, being too smart...
Neil Schemenauera35c6882001-02-27 04:45:05 +00001379
Victor Stinner9ed83c42017-10-31 12:18:10 -07001380 Return 1 if pymalloc allocated memory and wrote the pointer into *ptr_p.
1381
1382 Return 0 if pymalloc failed to allocate the memory block: on bigger
1383 requests, on error in the code below (as a last chance to serve the request)
1384 or when the max memory limit has been reached. */
1385static int
1386pymalloc_alloc(void *ctx, void **ptr_p, size_t nbytes)
Neil Schemenauera35c6882001-02-27 04:45:05 +00001387{
Victor Stinner9e87e772017-11-24 12:09:24 +01001388 block *bp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001389 poolp pool;
1390 poolp next;
1391 uint size;
Neil Schemenauera35c6882001-02-27 04:45:05 +00001392
Benjamin Peterson05159c42009-12-03 03:01:27 +00001393#ifdef WITH_VALGRIND
Victor Stinner9ed83c42017-10-31 12:18:10 -07001394 if (UNLIKELY(running_on_valgrind == -1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001395 running_on_valgrind = RUNNING_ON_VALGRIND;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001396 }
1397 if (UNLIKELY(running_on_valgrind)) {
1398 return 0;
1399 }
Benjamin Peterson05159c42009-12-03 03:01:27 +00001400#endif
1401
Victor Stinner9ed83c42017-10-31 12:18:10 -07001402 if (nbytes == 0) {
1403 return 0;
1404 }
1405 if (nbytes > SMALL_REQUEST_THRESHOLD) {
1406 return 0;
1407 }
T. Wouters06bb4872017-03-31 10:10:19 -07001408
Victor Stinner9ed83c42017-10-31 12:18:10 -07001409 LOCK();
1410 /*
1411 * Most frequent paths first
1412 */
1413 size = (uint)(nbytes - 1) >> ALIGNMENT_SHIFT;
Victor Stinner9e87e772017-11-24 12:09:24 +01001414 pool = usedpools[size + size];
Victor Stinner9ed83c42017-10-31 12:18:10 -07001415 if (pool != pool->nextpool) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001416 /*
Victor Stinner9ed83c42017-10-31 12:18:10 -07001417 * There is a used pool for this size class.
1418 * Pick up the head block of its free list.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001419 */
Victor Stinner9ed83c42017-10-31 12:18:10 -07001420 ++pool->ref.count;
1421 bp = pool->freeblock;
1422 assert(bp != NULL);
Victor Stinner9e87e772017-11-24 12:09:24 +01001423 if ((pool->freeblock = *(block **)bp) != NULL) {
Victor Stinner9ed83c42017-10-31 12:18:10 -07001424 goto success;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001425 }
Thomas Woutersa9773292006-04-21 09:43:23 +00001426
Victor Stinner9ed83c42017-10-31 12:18:10 -07001427 /*
1428 * Reached the end of the free list, try to extend it.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001429 */
Victor Stinner9ed83c42017-10-31 12:18:10 -07001430 if (pool->nextoffset <= pool->maxnextoffset) {
1431 /* There is room for another block. */
Victor Stinner9e87e772017-11-24 12:09:24 +01001432 pool->freeblock = (block*)pool +
Victor Stinner9ed83c42017-10-31 12:18:10 -07001433 pool->nextoffset;
1434 pool->nextoffset += INDEX2SIZE(size);
Victor Stinner9e87e772017-11-24 12:09:24 +01001435 *(block **)(pool->freeblock) = NULL;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001436 goto success;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001437 }
Thomas Woutersa9773292006-04-21 09:43:23 +00001438
Victor Stinner9ed83c42017-10-31 12:18:10 -07001439 /* Pool is full, unlink from used pools. */
1440 next = pool->nextpool;
1441 pool = pool->prevpool;
1442 next->prevpool = pool;
1443 pool->nextpool = next;
1444 goto success;
1445 }
Thomas Woutersa9773292006-04-21 09:43:23 +00001446
Victor Stinner9ed83c42017-10-31 12:18:10 -07001447 /* There isn't a pool of the right size class immediately
1448 * available: use a free pool.
1449 */
Victor Stinner9e87e772017-11-24 12:09:24 +01001450 if (usable_arenas == NULL) {
Victor Stinner9ed83c42017-10-31 12:18:10 -07001451 /* No arena has a free pool: allocate a new arena. */
1452#ifdef WITH_MEMORY_LIMITS
Victor Stinner9e87e772017-11-24 12:09:24 +01001453 if (narenas_currently_allocated >= MAX_ARENAS) {
Victor Stinner9ed83c42017-10-31 12:18:10 -07001454 goto failed;
1455 }
1456#endif
Victor Stinner9e87e772017-11-24 12:09:24 +01001457 usable_arenas = new_arena();
1458 if (usable_arenas == NULL) {
Victor Stinner9ed83c42017-10-31 12:18:10 -07001459 goto failed;
1460 }
Victor Stinner9e87e772017-11-24 12:09:24 +01001461 usable_arenas->nextarena =
1462 usable_arenas->prevarena = NULL;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001463 }
Victor Stinner9e87e772017-11-24 12:09:24 +01001464 assert(usable_arenas->address != 0);
Victor Stinner9ed83c42017-10-31 12:18:10 -07001465
1466 /* Try to get a cached free pool. */
Victor Stinner9e87e772017-11-24 12:09:24 +01001467 pool = usable_arenas->freepools;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001468 if (pool != NULL) {
1469 /* Unlink from cached pools. */
Victor Stinner9e87e772017-11-24 12:09:24 +01001470 usable_arenas->freepools = pool->nextpool;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001471
1472 /* This arena already had the smallest nfreepools
1473 * value, so decreasing nfreepools doesn't change
1474 * that, and we don't need to rearrange the
1475 * usable_arenas list. However, if the arena has
1476 * become wholly allocated, we need to remove its
1477 * arena_object from usable_arenas.
1478 */
Victor Stinner9e87e772017-11-24 12:09:24 +01001479 --usable_arenas->nfreepools;
1480 if (usable_arenas->nfreepools == 0) {
Victor Stinner9ed83c42017-10-31 12:18:10 -07001481 /* Wholly allocated: remove. */
Victor Stinner9e87e772017-11-24 12:09:24 +01001482 assert(usable_arenas->freepools == NULL);
1483 assert(usable_arenas->nextarena == NULL ||
1484 usable_arenas->nextarena->prevarena ==
1485 usable_arenas);
Victor Stinner9ed83c42017-10-31 12:18:10 -07001486
Victor Stinner9e87e772017-11-24 12:09:24 +01001487 usable_arenas = usable_arenas->nextarena;
1488 if (usable_arenas != NULL) {
1489 usable_arenas->prevarena = NULL;
1490 assert(usable_arenas->address != 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001491 }
1492 }
Victor Stinner9ed83c42017-10-31 12:18:10 -07001493 else {
1494 /* nfreepools > 0: it must be that freepools
1495 * isn't NULL, or that we haven't yet carved
1496 * off all the arena's pools for the first
1497 * time.
1498 */
Victor Stinner9e87e772017-11-24 12:09:24 +01001499 assert(usable_arenas->freepools != NULL ||
1500 usable_arenas->pool_address <=
1501 (block*)usable_arenas->address +
Victor Stinner9ed83c42017-10-31 12:18:10 -07001502 ARENA_SIZE - POOL_SIZE);
1503 }
Thomas Woutersa9773292006-04-21 09:43:23 +00001504
Victor Stinner9ed83c42017-10-31 12:18:10 -07001505 init_pool:
1506 /* Frontlink to used pools. */
Victor Stinner9e87e772017-11-24 12:09:24 +01001507 next = usedpools[size + size]; /* == prev */
Victor Stinner9ed83c42017-10-31 12:18:10 -07001508 pool->nextpool = next;
1509 pool->prevpool = next;
1510 next->nextpool = pool;
1511 next->prevpool = pool;
1512 pool->ref.count = 1;
1513 if (pool->szidx == size) {
1514 /* Luckily, this pool last contained blocks
1515 * of the same size class, so its header
1516 * and free list are already initialized.
1517 */
1518 bp = pool->freeblock;
1519 assert(bp != NULL);
Victor Stinner9e87e772017-11-24 12:09:24 +01001520 pool->freeblock = *(block **)bp;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001521 goto success;
1522 }
1523 /*
1524 * Initialize the pool header, set up the free list to
1525 * contain just the second block, and return the first
1526 * block.
1527 */
1528 pool->szidx = size;
1529 size = INDEX2SIZE(size);
Victor Stinner9e87e772017-11-24 12:09:24 +01001530 bp = (block *)pool + POOL_OVERHEAD;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001531 pool->nextoffset = POOL_OVERHEAD + (size << 1);
1532 pool->maxnextoffset = POOL_SIZE - size;
1533 pool->freeblock = bp + size;
Victor Stinner9e87e772017-11-24 12:09:24 +01001534 *(block **)(pool->freeblock) = NULL;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001535 goto success;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001536 }
Neil Schemenauera35c6882001-02-27 04:45:05 +00001537
Victor Stinner9ed83c42017-10-31 12:18:10 -07001538 /* Carve off a new pool. */
Victor Stinner9e87e772017-11-24 12:09:24 +01001539 assert(usable_arenas->nfreepools > 0);
1540 assert(usable_arenas->freepools == NULL);
1541 pool = (poolp)usable_arenas->pool_address;
1542 assert((block*)pool <= (block*)usable_arenas->address +
Victor Stinner9ed83c42017-10-31 12:18:10 -07001543 ARENA_SIZE - POOL_SIZE);
Victor Stinner9e87e772017-11-24 12:09:24 +01001544 pool->arenaindex = (uint)(usable_arenas - arenas);
1545 assert(&arenas[pool->arenaindex] == usable_arenas);
Victor Stinner9ed83c42017-10-31 12:18:10 -07001546 pool->szidx = DUMMY_SIZE_IDX;
Victor Stinner9e87e772017-11-24 12:09:24 +01001547 usable_arenas->pool_address += POOL_SIZE;
1548 --usable_arenas->nfreepools;
Neil Schemenauera35c6882001-02-27 04:45:05 +00001549
Victor Stinner9e87e772017-11-24 12:09:24 +01001550 if (usable_arenas->nfreepools == 0) {
1551 assert(usable_arenas->nextarena == NULL ||
1552 usable_arenas->nextarena->prevarena ==
1553 usable_arenas);
Victor Stinner9ed83c42017-10-31 12:18:10 -07001554 /* Unlink the arena: it is completely allocated. */
Victor Stinner9e87e772017-11-24 12:09:24 +01001555 usable_arenas = usable_arenas->nextarena;
1556 if (usable_arenas != NULL) {
1557 usable_arenas->prevarena = NULL;
1558 assert(usable_arenas->address != 0);
Victor Stinner9ed83c42017-10-31 12:18:10 -07001559 }
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001560 }
Victor Stinner9ed83c42017-10-31 12:18:10 -07001561
1562 goto init_pool;
1563
1564success:
1565 UNLOCK();
1566 assert(bp != NULL);
1567 *ptr_p = (void *)bp;
1568 return 1;
1569
1570failed:
1571 UNLOCK();
1572 return 0;
Neil Schemenauera35c6882001-02-27 04:45:05 +00001573}
1574
Victor Stinner9ed83c42017-10-31 12:18:10 -07001575
Victor Stinnerdb067af2014-05-02 22:31:14 +02001576static void *
1577_PyObject_Malloc(void *ctx, size_t nbytes)
1578{
Victor Stinner9ed83c42017-10-31 12:18:10 -07001579 void* ptr;
1580 if (pymalloc_alloc(ctx, &ptr, nbytes)) {
Victor Stinner9e87e772017-11-24 12:09:24 +01001581 _Py_AllocatedBlocks++;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001582 return ptr;
1583 }
1584
1585 ptr = PyMem_RawMalloc(nbytes);
1586 if (ptr != NULL) {
Victor Stinner9e87e772017-11-24 12:09:24 +01001587 _Py_AllocatedBlocks++;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001588 }
1589 return ptr;
Victor Stinnerdb067af2014-05-02 22:31:14 +02001590}
1591
Victor Stinner9ed83c42017-10-31 12:18:10 -07001592
Victor Stinnerdb067af2014-05-02 22:31:14 +02001593static void *
1594_PyObject_Calloc(void *ctx, size_t nelem, size_t elsize)
1595{
Victor Stinner9ed83c42017-10-31 12:18:10 -07001596 void* ptr;
1597
1598 assert(elsize == 0 || nelem <= (size_t)PY_SSIZE_T_MAX / elsize);
1599 size_t nbytes = nelem * elsize;
1600
1601 if (pymalloc_alloc(ctx, &ptr, nbytes)) {
1602 memset(ptr, 0, nbytes);
Victor Stinner9e87e772017-11-24 12:09:24 +01001603 _Py_AllocatedBlocks++;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001604 return ptr;
1605 }
1606
1607 ptr = PyMem_RawCalloc(nelem, elsize);
1608 if (ptr != NULL) {
Victor Stinner9e87e772017-11-24 12:09:24 +01001609 _Py_AllocatedBlocks++;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001610 }
1611 return ptr;
Victor Stinnerdb067af2014-05-02 22:31:14 +02001612}
1613
Neil Schemenauera35c6882001-02-27 04:45:05 +00001614
Victor Stinner9ed83c42017-10-31 12:18:10 -07001615/* Free a memory block allocated by pymalloc_alloc().
1616 Return 1 if it was freed.
1617 Return 0 if the block was not allocated by pymalloc_alloc(). */
1618static int
1619pymalloc_free(void *ctx, void *p)
Neil Schemenauera35c6882001-02-27 04:45:05 +00001620{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001621 poolp pool;
Victor Stinner9e87e772017-11-24 12:09:24 +01001622 block *lastfree;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001623 poolp next, prev;
1624 uint size;
Neil Schemenauera35c6882001-02-27 04:45:05 +00001625
Victor Stinner9ed83c42017-10-31 12:18:10 -07001626 assert(p != NULL);
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001627
Benjamin Peterson05159c42009-12-03 03:01:27 +00001628#ifdef WITH_VALGRIND
Victor Stinner9ed83c42017-10-31 12:18:10 -07001629 if (UNLIKELY(running_on_valgrind > 0)) {
1630 return 0;
1631 }
Benjamin Peterson05159c42009-12-03 03:01:27 +00001632#endif
1633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001634 pool = POOL_ADDR(p);
Victor Stinner9ed83c42017-10-31 12:18:10 -07001635 if (!address_in_range(p, pool)) {
1636 return 0;
1637 }
1638 /* We allocated this address. */
Thomas Woutersa9773292006-04-21 09:43:23 +00001639
Victor Stinner9ed83c42017-10-31 12:18:10 -07001640 LOCK();
Thomas Woutersa9773292006-04-21 09:43:23 +00001641
Victor Stinner9ed83c42017-10-31 12:18:10 -07001642 /* Link p to the start of the pool's freeblock list. Since
1643 * the pool had at least the p block outstanding, the pool
1644 * wasn't empty (so it's already in a usedpools[] list, or
1645 * was full and is in no list -- it's not in the freeblocks
1646 * list in any case).
1647 */
1648 assert(pool->ref.count > 0); /* else it was empty */
Victor Stinner9e87e772017-11-24 12:09:24 +01001649 *(block **)p = lastfree = pool->freeblock;
1650 pool->freeblock = (block *)p;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001651 if (!lastfree) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001652 /* Pool was full, so doesn't currently live in any list:
1653 * link it to the front of the appropriate usedpools[] list.
1654 * This mimics LRU pool usage for new allocations and
1655 * targets optimal filling when several pools contain
1656 * blocks of the same size class.
1657 */
1658 --pool->ref.count;
1659 assert(pool->ref.count > 0); /* else the pool is empty */
1660 size = pool->szidx;
Victor Stinner9e87e772017-11-24 12:09:24 +01001661 next = usedpools[size + size];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001662 prev = next->prevpool;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001663
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001664 /* insert pool before next: prev <-> pool <-> next */
1665 pool->nextpool = next;
1666 pool->prevpool = prev;
1667 next->prevpool = pool;
1668 prev->nextpool = pool;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001669 goto success;
1670 }
1671
1672 struct arena_object* ao;
1673 uint nf; /* ao->nfreepools */
1674
1675 /* freeblock wasn't NULL, so the pool wasn't full,
1676 * and the pool is in a usedpools[] list.
1677 */
1678 if (--pool->ref.count != 0) {
1679 /* pool isn't empty: leave it in usedpools */
1680 goto success;
1681 }
1682 /* Pool is now empty: unlink from usedpools, and
1683 * link to the front of freepools. This ensures that
1684 * previously freed pools will be allocated later
1685 * (being not referenced, they are perhaps paged out).
1686 */
1687 next = pool->nextpool;
1688 prev = pool->prevpool;
1689 next->prevpool = prev;
1690 prev->nextpool = next;
1691
1692 /* Link the pool to freepools. This is a singly-linked
1693 * list, and pool->prevpool isn't used there.
1694 */
Victor Stinner9e87e772017-11-24 12:09:24 +01001695 ao = &arenas[pool->arenaindex];
Victor Stinner9ed83c42017-10-31 12:18:10 -07001696 pool->nextpool = ao->freepools;
1697 ao->freepools = pool;
1698 nf = ++ao->nfreepools;
1699
1700 /* All the rest is arena management. We just freed
1701 * a pool, and there are 4 cases for arena mgmt:
1702 * 1. If all the pools are free, return the arena to
1703 * the system free().
1704 * 2. If this is the only free pool in the arena,
1705 * add the arena back to the `usable_arenas` list.
1706 * 3. If the "next" arena has a smaller count of free
1707 * pools, we have to "slide this arena right" to
1708 * restore that usable_arenas is sorted in order of
1709 * nfreepools.
1710 * 4. Else there's nothing more to do.
1711 */
1712 if (nf == ao->ntotalpools) {
1713 /* Case 1. First unlink ao from usable_arenas.
1714 */
1715 assert(ao->prevarena == NULL ||
1716 ao->prevarena->address != 0);
1717 assert(ao ->nextarena == NULL ||
1718 ao->nextarena->address != 0);
1719
1720 /* Fix the pointer in the prevarena, or the
1721 * usable_arenas pointer.
1722 */
1723 if (ao->prevarena == NULL) {
Victor Stinner9e87e772017-11-24 12:09:24 +01001724 usable_arenas = ao->nextarena;
1725 assert(usable_arenas == NULL ||
1726 usable_arenas->address != 0);
Victor Stinner9ed83c42017-10-31 12:18:10 -07001727 }
1728 else {
1729 assert(ao->prevarena->nextarena == ao);
1730 ao->prevarena->nextarena =
1731 ao->nextarena;
1732 }
1733 /* Fix the pointer in the nextarena. */
1734 if (ao->nextarena != NULL) {
1735 assert(ao->nextarena->prevarena == ao);
1736 ao->nextarena->prevarena =
1737 ao->prevarena;
1738 }
1739 /* Record that this arena_object slot is
1740 * available to be reused.
1741 */
Victor Stinner9e87e772017-11-24 12:09:24 +01001742 ao->nextarena = unused_arena_objects;
1743 unused_arena_objects = ao;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001744
1745 /* Free the entire arena. */
Victor Stinner9e87e772017-11-24 12:09:24 +01001746 _PyObject_Arena.free(_PyObject_Arena.ctx,
Victor Stinner9ed83c42017-10-31 12:18:10 -07001747 (void *)ao->address, ARENA_SIZE);
1748 ao->address = 0; /* mark unassociated */
Victor Stinner9e87e772017-11-24 12:09:24 +01001749 --narenas_currently_allocated;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001750
1751 goto success;
1752 }
1753
1754 if (nf == 1) {
1755 /* Case 2. Put ao at the head of
1756 * usable_arenas. Note that because
1757 * ao->nfreepools was 0 before, ao isn't
1758 * currently on the usable_arenas list.
1759 */
Victor Stinner9e87e772017-11-24 12:09:24 +01001760 ao->nextarena = usable_arenas;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001761 ao->prevarena = NULL;
Victor Stinner9e87e772017-11-24 12:09:24 +01001762 if (usable_arenas)
1763 usable_arenas->prevarena = ao;
1764 usable_arenas = ao;
1765 assert(usable_arenas->address != 0);
Victor Stinner9ed83c42017-10-31 12:18:10 -07001766
1767 goto success;
1768 }
1769
1770 /* If this arena is now out of order, we need to keep
1771 * the list sorted. The list is kept sorted so that
1772 * the "most full" arenas are used first, which allows
1773 * the nearly empty arenas to be completely freed. In
1774 * a few un-scientific tests, it seems like this
1775 * approach allowed a lot more memory to be freed.
1776 */
1777 if (ao->nextarena == NULL ||
1778 nf <= ao->nextarena->nfreepools) {
1779 /* Case 4. Nothing to do. */
1780 goto success;
1781 }
1782 /* Case 3: We have to move the arena towards the end
1783 * of the list, because it has more free pools than
1784 * the arena to its right.
1785 * First unlink ao from usable_arenas.
1786 */
1787 if (ao->prevarena != NULL) {
1788 /* ao isn't at the head of the list */
1789 assert(ao->prevarena->nextarena == ao);
1790 ao->prevarena->nextarena = ao->nextarena;
1791 }
1792 else {
1793 /* ao is at the head of the list */
Victor Stinner9e87e772017-11-24 12:09:24 +01001794 assert(usable_arenas == ao);
1795 usable_arenas = ao->nextarena;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001796 }
1797 ao->nextarena->prevarena = ao->prevarena;
1798
1799 /* Locate the new insertion point by iterating over
1800 * the list, using our nextarena pointer.
1801 */
1802 while (ao->nextarena != NULL && nf > ao->nextarena->nfreepools) {
1803 ao->prevarena = ao->nextarena;
1804 ao->nextarena = ao->nextarena->nextarena;
1805 }
1806
1807 /* Insert ao at this point. */
1808 assert(ao->nextarena == NULL || ao->prevarena == ao->nextarena->prevarena);
1809 assert(ao->prevarena->nextarena == ao->nextarena);
1810
1811 ao->prevarena->nextarena = ao;
1812 if (ao->nextarena != NULL) {
1813 ao->nextarena->prevarena = ao;
1814 }
1815
1816 /* Verify that the swaps worked. */
1817 assert(ao->nextarena == NULL || nf <= ao->nextarena->nfreepools);
1818 assert(ao->prevarena == NULL || nf > ao->prevarena->nfreepools);
1819 assert(ao->nextarena == NULL || ao->nextarena->prevarena == ao);
Victor Stinner9e87e772017-11-24 12:09:24 +01001820 assert((usable_arenas == ao && ao->prevarena == NULL)
Victor Stinner9ed83c42017-10-31 12:18:10 -07001821 || ao->prevarena->nextarena == ao);
1822
1823 goto success;
1824
1825success:
1826 UNLOCK();
1827 return 1;
1828}
1829
1830
1831static void
1832_PyObject_Free(void *ctx, void *p)
1833{
1834 /* PyObject_Free(NULL) has no effect */
1835 if (p == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001836 return;
1837 }
Neil Schemenauera35c6882001-02-27 04:45:05 +00001838
Victor Stinner9e87e772017-11-24 12:09:24 +01001839 _Py_AllocatedBlocks--;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001840 if (!pymalloc_free(ctx, p)) {
1841 /* pymalloc didn't allocate this address */
1842 PyMem_RawFree(p);
1843 }
Neil Schemenauera35c6882001-02-27 04:45:05 +00001844}
1845
Neil Schemenauera35c6882001-02-27 04:45:05 +00001846
Victor Stinner9ed83c42017-10-31 12:18:10 -07001847/* pymalloc realloc.
1848
1849 If nbytes==0, then as the Python docs promise, we do not treat this like
1850 free(p), and return a non-NULL result.
1851
1852 Return 1 if pymalloc reallocated memory and wrote the new pointer into
1853 newptr_p.
1854
1855 Return 0 if pymalloc didn't allocated p. */
1856static int
1857pymalloc_realloc(void *ctx, void **newptr_p, void *p, size_t nbytes)
Neil Schemenauera35c6882001-02-27 04:45:05 +00001858{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001859 void *bp;
1860 poolp pool;
1861 size_t size;
Neil Schemenauera35c6882001-02-27 04:45:05 +00001862
Victor Stinner9ed83c42017-10-31 12:18:10 -07001863 assert(p != NULL);
Georg Brandld492ad82008-07-23 16:13:07 +00001864
Benjamin Peterson05159c42009-12-03 03:01:27 +00001865#ifdef WITH_VALGRIND
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001866 /* Treat running_on_valgrind == -1 the same as 0 */
Victor Stinner9ed83c42017-10-31 12:18:10 -07001867 if (UNLIKELY(running_on_valgrind > 0)) {
1868 return 0;
1869 }
Benjamin Peterson05159c42009-12-03 03:01:27 +00001870#endif
1871
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001872 pool = POOL_ADDR(p);
Victor Stinner9ed83c42017-10-31 12:18:10 -07001873 if (!address_in_range(p, pool)) {
1874 /* pymalloc is not managing this block.
1875
1876 If nbytes <= SMALL_REQUEST_THRESHOLD, it's tempting to try to take
1877 over this block. However, if we do, we need to copy the valid data
1878 from the C-managed block to one of our blocks, and there's no
1879 portable way to know how much of the memory space starting at p is
1880 valid.
1881
1882 As bug 1185883 pointed out the hard way, it's possible that the
1883 C-managed block is "at the end" of allocated VM space, so that a
1884 memory fault can occur if we try to copy nbytes bytes starting at p.
1885 Instead we punt: let C continue to manage this block. */
1886 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001887 }
Victor Stinner9ed83c42017-10-31 12:18:10 -07001888
1889 /* pymalloc is in charge of this block */
1890 size = INDEX2SIZE(pool->szidx);
1891 if (nbytes <= size) {
1892 /* The block is staying the same or shrinking.
1893
1894 If it's shrinking, there's a tradeoff: it costs cycles to copy the
1895 block to a smaller size class, but it wastes memory not to copy it.
1896
1897 The compromise here is to copy on shrink only if at least 25% of
1898 size can be shaved off. */
1899 if (4 * nbytes > 3 * size) {
1900 /* It's the same, or shrinking and new/old > 3/4. */
1901 *newptr_p = p;
1902 return 1;
1903 }
1904 size = nbytes;
1905 }
1906
1907 bp = _PyObject_Malloc(ctx, nbytes);
1908 if (bp != NULL) {
1909 memcpy(bp, p, size);
1910 _PyObject_Free(ctx, p);
1911 }
1912 *newptr_p = bp;
1913 return 1;
1914}
1915
1916
1917static void *
1918_PyObject_Realloc(void *ctx, void *ptr, size_t nbytes)
1919{
1920 void *ptr2;
1921
1922 if (ptr == NULL) {
1923 return _PyObject_Malloc(ctx, nbytes);
1924 }
1925
1926 if (pymalloc_realloc(ctx, &ptr2, ptr, nbytes)) {
1927 return ptr2;
1928 }
1929
1930 return PyMem_RawRealloc(ptr, nbytes);
Neil Schemenauera35c6882001-02-27 04:45:05 +00001931}
1932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001933#else /* ! WITH_PYMALLOC */
Tim Petersddea2082002-03-23 10:03:50 +00001934
1935/*==========================================================================*/
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00001936/* pymalloc not enabled: Redirect the entry points to malloc. These will
1937 * only be used by extensions that are compiled with pymalloc enabled. */
Tim Peters62c06ba2002-03-23 22:28:18 +00001938
Antoine Pitrou92840532012-12-17 23:05:59 +01001939Py_ssize_t
1940_Py_GetAllocatedBlocks(void)
1941{
1942 return 0;
1943}
1944
Tim Peters1221c0a2002-03-23 00:20:15 +00001945#endif /* WITH_PYMALLOC */
1946
Victor Stinner34be807c2016-03-14 12:04:26 +01001947
Tim Petersddea2082002-03-23 10:03:50 +00001948/*==========================================================================*/
Tim Peters62c06ba2002-03-23 22:28:18 +00001949/* A x-platform debugging allocator. This doesn't manage memory directly,
1950 * it wraps a real allocator, adding extra debugging info to the memory blocks.
1951 */
Tim Petersddea2082002-03-23 10:03:50 +00001952
Tim Petersf6fb5012002-04-12 07:38:53 +00001953/* Special bytes broadcast into debug memory blocks at appropriate times.
1954 * Strings of these are unlikely to be valid addresses, floats, ints or
Victor Stinner9e23f0a2019-04-11 22:30:31 +02001955 * 7-bit ASCII. If modified, _PyMem_IsPtrFreed() should be updated as well.
1956 *
1957 * Byte patterns 0xCB, 0xBB and 0xFB have been replaced with 0xCD, 0xDD and
1958 * 0xFD to use the same values than Windows CRT debug malloc() and free().
Tim Petersf6fb5012002-04-12 07:38:53 +00001959 */
1960#undef CLEANBYTE
1961#undef DEADBYTE
1962#undef FORBIDDENBYTE
Victor Stinner9e23f0a2019-04-11 22:30:31 +02001963#define CLEANBYTE 0xCD /* clean (newly allocated) memory */
1964#define DEADBYTE 0xDD /* dead (newly freed) memory */
1965#define FORBIDDENBYTE 0xFD /* untouchable bytes at each end of a block */
Tim Petersddea2082002-03-23 10:03:50 +00001966
Victor Stinner9e87e772017-11-24 12:09:24 +01001967static size_t serialno = 0; /* incremented on each debug {m,re}alloc */
1968
Tim Peterse0850172002-03-24 00:34:21 +00001969/* serialno is always incremented via calling this routine. The point is
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001970 * to supply a single place to set a breakpoint.
1971 */
Tim Peterse0850172002-03-24 00:34:21 +00001972static void
Neil Schemenauerbd02b142002-03-28 21:05:38 +00001973bumpserialno(void)
Tim Peterse0850172002-03-24 00:34:21 +00001974{
Victor Stinner9e87e772017-11-24 12:09:24 +01001975 ++serialno;
Tim Peterse0850172002-03-24 00:34:21 +00001976}
1977
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001978#define SST SIZEOF_SIZE_T
Tim Peterse0850172002-03-24 00:34:21 +00001979
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001980/* Read sizeof(size_t) bytes at p as a big-endian size_t. */
1981static size_t
1982read_size_t(const void *p)
Tim Petersddea2082002-03-23 10:03:50 +00001983{
Benjamin Peterson19517e42016-09-18 19:22:22 -07001984 const uint8_t *q = (const uint8_t *)p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001985 size_t result = *q++;
1986 int i;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001987
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001988 for (i = SST; --i > 0; ++q)
1989 result = (result << 8) | *q;
1990 return result;
Tim Petersddea2082002-03-23 10:03:50 +00001991}
1992
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001993/* Write n as a big-endian size_t, MSB at address p, LSB at
1994 * p + sizeof(size_t) - 1.
1995 */
Tim Petersddea2082002-03-23 10:03:50 +00001996static void
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001997write_size_t(void *p, size_t n)
Tim Petersddea2082002-03-23 10:03:50 +00001998{
Benjamin Peterson19517e42016-09-18 19:22:22 -07001999 uint8_t *q = (uint8_t *)p + SST - 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002000 int i;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00002001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002002 for (i = SST; --i >= 0; --q) {
Benjamin Peterson19517e42016-09-18 19:22:22 -07002003 *q = (uint8_t)(n & 0xff);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002004 n >>= 8;
2005 }
Tim Petersddea2082002-03-23 10:03:50 +00002006}
2007
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00002008/* Let S = sizeof(size_t). The debug malloc asks for 4*S extra bytes and
2009 fills them with useful stuff, here calling the underlying malloc's result p:
Tim Petersddea2082002-03-23 10:03:50 +00002010
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00002011p[0: S]
2012 Number of bytes originally asked for. This is a size_t, big-endian (easier
2013 to read in a memory dump).
Georg Brandl7cba5fd2013-09-25 09:04:23 +02002014p[S]
Tim Petersdf099f52013-09-19 21:06:37 -05002015 API ID. See PEP 445. This is a character, but seems undocumented.
2016p[S+1: 2*S]
Tim Petersf6fb5012002-04-12 07:38:53 +00002017 Copies of FORBIDDENBYTE. Used to catch under- writes and reads.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00002018p[2*S: 2*S+n]
Tim Petersf6fb5012002-04-12 07:38:53 +00002019 The requested memory, filled with copies of CLEANBYTE.
Tim Petersddea2082002-03-23 10:03:50 +00002020 Used to catch reference to uninitialized memory.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00002021 &p[2*S] is returned. Note that this is 8-byte aligned if pymalloc
Tim Petersddea2082002-03-23 10:03:50 +00002022 handled the request itself.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00002023p[2*S+n: 2*S+n+S]
Tim Petersf6fb5012002-04-12 07:38:53 +00002024 Copies of FORBIDDENBYTE. Used to catch over- writes and reads.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00002025p[2*S+n+S: 2*S+n+2*S]
Victor Stinner0507bf52013-07-07 02:05:46 +02002026 A serial number, incremented by 1 on each call to _PyMem_DebugMalloc
2027 and _PyMem_DebugRealloc.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00002028 This is a big-endian size_t.
Tim Petersddea2082002-03-23 10:03:50 +00002029 If "bad memory" is detected later, the serial number gives an
2030 excellent way to set a breakpoint on the next run, to capture the
2031 instant at which this block was passed out.
2032*/
2033
Victor Stinner0507bf52013-07-07 02:05:46 +02002034static void *
Victor Stinnerc4aec362016-03-14 22:26:53 +01002035_PyMem_DebugRawAlloc(int use_calloc, void *ctx, size_t nbytes)
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00002036{
Victor Stinner0507bf52013-07-07 02:05:46 +02002037 debug_alloc_api_t *api = (debug_alloc_api_t *)ctx;
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002038 uint8_t *p; /* base address of malloc'ed pad block */
Victor Stinner9ed83c42017-10-31 12:18:10 -07002039 uint8_t *data; /* p + 2*SST == pointer to data bytes */
2040 uint8_t *tail; /* data + nbytes == pointer to tail pad bytes */
2041 size_t total; /* 2 * SST + nbytes + 2 * SST */
2042
2043 if (nbytes > (size_t)PY_SSIZE_T_MAX - 4 * SST) {
2044 /* integer overflow: can't represent total as a Py_ssize_t */
2045 return NULL;
2046 }
2047 total = nbytes + 4 * SST;
2048
2049 /* Layout: [SSSS IFFF CCCC...CCCC FFFF NNNN]
2050 * ^--- p ^--- data ^--- tail
2051 S: nbytes stored as size_t
2052 I: API identifier (1 byte)
2053 F: Forbidden bytes (size_t - 1 bytes before, size_t bytes after)
2054 C: Clean bytes used later to store actual data
2055 N: Serial number stored as size_t */
2056
2057 if (use_calloc) {
2058 p = (uint8_t *)api->alloc.calloc(api->alloc.ctx, 1, total);
2059 }
2060 else {
2061 p = (uint8_t *)api->alloc.malloc(api->alloc.ctx, total);
2062 }
2063 if (p == NULL) {
2064 return NULL;
2065 }
2066 data = p + 2*SST;
Tim Petersddea2082002-03-23 10:03:50 +00002067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002068 bumpserialno();
Tim Petersddea2082002-03-23 10:03:50 +00002069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002070 /* at p, write size (SST bytes), id (1 byte), pad (SST-1 bytes) */
2071 write_size_t(p, nbytes);
Benjamin Peterson19517e42016-09-18 19:22:22 -07002072 p[SST] = (uint8_t)api->api_id;
Victor Stinner0507bf52013-07-07 02:05:46 +02002073 memset(p + SST + 1, FORBIDDENBYTE, SST-1);
Tim Petersddea2082002-03-23 10:03:50 +00002074
Victor Stinner9ed83c42017-10-31 12:18:10 -07002075 if (nbytes > 0 && !use_calloc) {
2076 memset(data, CLEANBYTE, nbytes);
2077 }
Tim Petersddea2082002-03-23 10:03:50 +00002078
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002079 /* at tail, write pad (SST bytes) and serialno (SST bytes) */
Victor Stinner9ed83c42017-10-31 12:18:10 -07002080 tail = data + nbytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002081 memset(tail, FORBIDDENBYTE, SST);
Victor Stinner9e87e772017-11-24 12:09:24 +01002082 write_size_t(tail + SST, serialno);
Tim Petersddea2082002-03-23 10:03:50 +00002083
Victor Stinner9ed83c42017-10-31 12:18:10 -07002084 return data;
Tim Petersddea2082002-03-23 10:03:50 +00002085}
2086
Victor Stinnerdb067af2014-05-02 22:31:14 +02002087static void *
Victor Stinnerc4aec362016-03-14 22:26:53 +01002088_PyMem_DebugRawMalloc(void *ctx, size_t nbytes)
Victor Stinnerdb067af2014-05-02 22:31:14 +02002089{
Victor Stinnerc4aec362016-03-14 22:26:53 +01002090 return _PyMem_DebugRawAlloc(0, ctx, nbytes);
Victor Stinnerdb067af2014-05-02 22:31:14 +02002091}
2092
2093static void *
Victor Stinnerc4aec362016-03-14 22:26:53 +01002094_PyMem_DebugRawCalloc(void *ctx, size_t nelem, size_t elsize)
Victor Stinnerdb067af2014-05-02 22:31:14 +02002095{
2096 size_t nbytes;
Victor Stinner9ed83c42017-10-31 12:18:10 -07002097 assert(elsize == 0 || nelem <= (size_t)PY_SSIZE_T_MAX / elsize);
Victor Stinnerdb067af2014-05-02 22:31:14 +02002098 nbytes = nelem * elsize;
Victor Stinnerc4aec362016-03-14 22:26:53 +01002099 return _PyMem_DebugRawAlloc(1, ctx, nbytes);
Victor Stinnerdb067af2014-05-02 22:31:14 +02002100}
2101
Victor Stinner9ed83c42017-10-31 12:18:10 -07002102
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00002103/* 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 +00002104 particular, that the FORBIDDENBYTEs with the api ID are still intact).
Tim Petersf6fb5012002-04-12 07:38:53 +00002105 Then fills the original bytes with DEADBYTE.
Tim Petersddea2082002-03-23 10:03:50 +00002106 Then calls the underlying free.
2107*/
Victor Stinner0507bf52013-07-07 02:05:46 +02002108static void
Victor Stinnerc4aec362016-03-14 22:26:53 +01002109_PyMem_DebugRawFree(void *ctx, void *p)
Tim Petersddea2082002-03-23 10:03:50 +00002110{
Victor Stinner9ed83c42017-10-31 12:18:10 -07002111 /* PyMem_Free(NULL) has no effect */
2112 if (p == NULL) {
2113 return;
2114 }
2115
Victor Stinner0507bf52013-07-07 02:05:46 +02002116 debug_alloc_api_t *api = (debug_alloc_api_t *)ctx;
Benjamin Peterson19517e42016-09-18 19:22:22 -07002117 uint8_t *q = (uint8_t *)p - 2*SST; /* address returned from malloc */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002118 size_t nbytes;
Tim Petersddea2082002-03-23 10:03:50 +00002119
Victor Stinner0507bf52013-07-07 02:05:46 +02002120 _PyMem_DebugCheckAddress(api->api_id, p);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002121 nbytes = read_size_t(q);
Victor Stinner9ed83c42017-10-31 12:18:10 -07002122 nbytes += 4 * SST;
2123 memset(q, DEADBYTE, nbytes);
Victor Stinner0507bf52013-07-07 02:05:46 +02002124 api->alloc.free(api->alloc.ctx, q);
Tim Petersddea2082002-03-23 10:03:50 +00002125}
2126
Victor Stinner9ed83c42017-10-31 12:18:10 -07002127
Victor Stinner0507bf52013-07-07 02:05:46 +02002128static void *
Victor Stinnerc4aec362016-03-14 22:26:53 +01002129_PyMem_DebugRawRealloc(void *ctx, void *p, size_t nbytes)
Tim Petersddea2082002-03-23 10:03:50 +00002130{
Victor Stinner9ed83c42017-10-31 12:18:10 -07002131 if (p == NULL) {
2132 return _PyMem_DebugRawAlloc(0, ctx, nbytes);
2133 }
2134
Victor Stinner0507bf52013-07-07 02:05:46 +02002135 debug_alloc_api_t *api = (debug_alloc_api_t *)ctx;
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002136 uint8_t *head; /* base address of malloc'ed pad block */
2137 uint8_t *data; /* pointer to data bytes */
2138 uint8_t *r;
Victor Stinner9ed83c42017-10-31 12:18:10 -07002139 uint8_t *tail; /* data + nbytes == pointer to tail pad bytes */
2140 size_t total; /* 2 * SST + nbytes + 2 * SST */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 size_t original_nbytes;
Victor Stinner9e87e772017-11-24 12:09:24 +01002142 size_t block_serialno;
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002143#define ERASED_SIZE 64
2144 uint8_t save[2*ERASED_SIZE]; /* A copy of erased bytes. */
Tim Petersddea2082002-03-23 10:03:50 +00002145
Victor Stinner0507bf52013-07-07 02:05:46 +02002146 _PyMem_DebugCheckAddress(api->api_id, p);
Victor Stinner9ed83c42017-10-31 12:18:10 -07002147
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002148 data = (uint8_t *)p;
2149 head = data - 2*SST;
2150 original_nbytes = read_size_t(head);
Victor Stinner9ed83c42017-10-31 12:18:10 -07002151 if (nbytes > (size_t)PY_SSIZE_T_MAX - 4*SST) {
2152 /* integer overflow: can't represent total as a Py_ssize_t */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002153 return NULL;
Victor Stinner9ed83c42017-10-31 12:18:10 -07002154 }
2155 total = nbytes + 4*SST;
Tim Petersddea2082002-03-23 10:03:50 +00002156
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002157 tail = data + original_nbytes;
Victor Stinner9e87e772017-11-24 12:09:24 +01002158 block_serialno = read_size_t(tail + SST);
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002159 /* Mark the header, the trailer, ERASED_SIZE bytes at the begin and
2160 ERASED_SIZE bytes at the end as dead and save the copy of erased bytes.
2161 */
2162 if (original_nbytes <= sizeof(save)) {
2163 memcpy(save, data, original_nbytes);
2164 memset(data - 2*SST, DEADBYTE, original_nbytes + 4*SST);
2165 }
2166 else {
2167 memcpy(save, data, ERASED_SIZE);
2168 memset(head, DEADBYTE, ERASED_SIZE + 2*SST);
2169 memcpy(&save[ERASED_SIZE], tail - ERASED_SIZE, ERASED_SIZE);
2170 memset(tail - ERASED_SIZE, DEADBYTE, ERASED_SIZE + 2*SST);
Victor Stinner9ed83c42017-10-31 12:18:10 -07002171 }
Tim Peters85cc1c42002-04-12 08:52:50 +00002172
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002173 /* Resize and add decorations. */
2174 r = (uint8_t *)api->alloc.realloc(api->alloc.ctx, head, total);
2175 if (r == NULL) {
2176 nbytes = original_nbytes;
Victor Stinner9ed83c42017-10-31 12:18:10 -07002177 }
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002178 else {
2179 head = r;
2180 bumpserialno();
Victor Stinner9e87e772017-11-24 12:09:24 +01002181 block_serialno = serialno;
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002182 }
2183
2184 write_size_t(head, nbytes);
2185 head[SST] = (uint8_t)api->api_id;
2186 memset(head + SST + 1, FORBIDDENBYTE, SST-1);
2187 data = head + 2*SST;
Victor Stinnerc4266362013-07-09 00:44:43 +02002188
Victor Stinner9ed83c42017-10-31 12:18:10 -07002189 tail = data + nbytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002190 memset(tail, FORBIDDENBYTE, SST);
Victor Stinner9e87e772017-11-24 12:09:24 +01002191 write_size_t(tail + SST, block_serialno);
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002192
2193 /* Restore saved bytes. */
2194 if (original_nbytes <= sizeof(save)) {
2195 memcpy(data, save, Py_MIN(nbytes, original_nbytes));
2196 }
2197 else {
2198 size_t i = original_nbytes - ERASED_SIZE;
2199 memcpy(data, save, Py_MIN(nbytes, ERASED_SIZE));
2200 if (nbytes > i) {
2201 memcpy(data + i, &save[ERASED_SIZE],
2202 Py_MIN(nbytes - i, ERASED_SIZE));
2203 }
2204 }
2205
2206 if (r == NULL) {
2207 return NULL;
2208 }
Tim Peters85cc1c42002-04-12 08:52:50 +00002209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002210 if (nbytes > original_nbytes) {
2211 /* growing: mark new extra memory clean */
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002212 memset(data + original_nbytes, CLEANBYTE, nbytes - original_nbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002213 }
Tim Peters85cc1c42002-04-12 08:52:50 +00002214
Victor Stinner9ed83c42017-10-31 12:18:10 -07002215 return data;
Tim Petersddea2082002-03-23 10:03:50 +00002216}
2217
Victor Stinnerc4aec362016-03-14 22:26:53 +01002218static void
2219_PyMem_DebugCheckGIL(void)
2220{
Victor Stinnerc4aec362016-03-14 22:26:53 +01002221 if (!PyGILState_Check())
2222 Py_FatalError("Python memory allocator called "
2223 "without holding the GIL");
Victor Stinnerc4aec362016-03-14 22:26:53 +01002224}
2225
2226static void *
2227_PyMem_DebugMalloc(void *ctx, size_t nbytes)
2228{
2229 _PyMem_DebugCheckGIL();
2230 return _PyMem_DebugRawMalloc(ctx, nbytes);
2231}
2232
2233static void *
2234_PyMem_DebugCalloc(void *ctx, size_t nelem, size_t elsize)
2235{
2236 _PyMem_DebugCheckGIL();
2237 return _PyMem_DebugRawCalloc(ctx, nelem, elsize);
2238}
2239
Victor Stinner9ed83c42017-10-31 12:18:10 -07002240
Victor Stinnerc4aec362016-03-14 22:26:53 +01002241static void
2242_PyMem_DebugFree(void *ctx, void *ptr)
2243{
2244 _PyMem_DebugCheckGIL();
Victor Stinner0aed3a42016-03-23 11:30:43 +01002245 _PyMem_DebugRawFree(ctx, ptr);
Victor Stinnerc4aec362016-03-14 22:26:53 +01002246}
2247
Victor Stinner9ed83c42017-10-31 12:18:10 -07002248
Victor Stinnerc4aec362016-03-14 22:26:53 +01002249static void *
2250_PyMem_DebugRealloc(void *ctx, void *ptr, size_t nbytes)
2251{
2252 _PyMem_DebugCheckGIL();
2253 return _PyMem_DebugRawRealloc(ctx, ptr, nbytes);
2254}
2255
Tim Peters7ccfadf2002-04-01 06:04:21 +00002256/* Check the forbidden bytes on both ends of the memory allocated for p.
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00002257 * If anything is wrong, print info to stderr via _PyObject_DebugDumpAddress,
Tim Peters7ccfadf2002-04-01 06:04:21 +00002258 * and call Py_FatalError to kill the program.
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00002259 * The API id, is also checked.
Tim Peters7ccfadf2002-04-01 06:04:21 +00002260 */
Victor Stinner0507bf52013-07-07 02:05:46 +02002261static void
2262_PyMem_DebugCheckAddress(char api, const void *p)
Tim Petersddea2082002-03-23 10:03:50 +00002263{
Benjamin Peterson19517e42016-09-18 19:22:22 -07002264 const uint8_t *q = (const uint8_t *)p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002265 char msgbuf[64];
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02002266 const char *msg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002267 size_t nbytes;
Benjamin Peterson19517e42016-09-18 19:22:22 -07002268 const uint8_t *tail;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002269 int i;
2270 char id;
Tim Petersddea2082002-03-23 10:03:50 +00002271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002272 if (p == NULL) {
2273 msg = "didn't expect a NULL pointer";
2274 goto error;
2275 }
Tim Petersddea2082002-03-23 10:03:50 +00002276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002277 /* Check the API id */
2278 id = (char)q[-SST];
2279 if (id != api) {
2280 msg = msgbuf;
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02002281 snprintf(msgbuf, sizeof(msgbuf), "bad ID: Allocated using API '%c', verified using API '%c'", id, api);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002282 msgbuf[sizeof(msgbuf)-1] = 0;
2283 goto error;
2284 }
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00002285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002286 /* Check the stuff at the start of p first: if there's underwrite
2287 * corruption, the number-of-bytes field may be nuts, and checking
2288 * the tail could lead to a segfault then.
2289 */
2290 for (i = SST-1; i >= 1; --i) {
2291 if (*(q-i) != FORBIDDENBYTE) {
2292 msg = "bad leading pad byte";
2293 goto error;
2294 }
2295 }
Tim Petersddea2082002-03-23 10:03:50 +00002296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002297 nbytes = read_size_t(q - 2*SST);
2298 tail = q + nbytes;
2299 for (i = 0; i < SST; ++i) {
2300 if (tail[i] != FORBIDDENBYTE) {
2301 msg = "bad trailing pad byte";
2302 goto error;
2303 }
2304 }
Tim Petersddea2082002-03-23 10:03:50 +00002305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002306 return;
Tim Petersd1139e02002-03-28 07:32:11 +00002307
2308error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002309 _PyObject_DebugDumpAddress(p);
2310 Py_FatalError(msg);
Tim Petersddea2082002-03-23 10:03:50 +00002311}
2312
Tim Peters7ccfadf2002-04-01 06:04:21 +00002313/* Display info to stderr about the memory block at p. */
Victor Stinner0507bf52013-07-07 02:05:46 +02002314static void
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00002315_PyObject_DebugDumpAddress(const void *p)
Tim Petersddea2082002-03-23 10:03:50 +00002316{
Benjamin Peterson19517e42016-09-18 19:22:22 -07002317 const uint8_t *q = (const uint8_t *)p;
2318 const uint8_t *tail;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002319 size_t nbytes, serial;
2320 int i;
2321 int ok;
2322 char id;
Tim Petersddea2082002-03-23 10:03:50 +00002323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002324 fprintf(stderr, "Debug memory block at address p=%p:", p);
2325 if (p == NULL) {
2326 fprintf(stderr, "\n");
2327 return;
2328 }
2329 id = (char)q[-SST];
2330 fprintf(stderr, " API '%c'\n", id);
Tim Petersddea2082002-03-23 10:03:50 +00002331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002332 nbytes = read_size_t(q - 2*SST);
2333 fprintf(stderr, " %" PY_FORMAT_SIZE_T "u bytes originally "
2334 "requested\n", nbytes);
Tim Petersddea2082002-03-23 10:03:50 +00002335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002336 /* In case this is nuts, check the leading pad bytes first. */
2337 fprintf(stderr, " The %d pad bytes at p-%d are ", SST-1, SST-1);
2338 ok = 1;
2339 for (i = 1; i <= SST-1; ++i) {
2340 if (*(q-i) != FORBIDDENBYTE) {
2341 ok = 0;
2342 break;
2343 }
2344 }
2345 if (ok)
2346 fputs("FORBIDDENBYTE, as expected.\n", stderr);
2347 else {
2348 fprintf(stderr, "not all FORBIDDENBYTE (0x%02x):\n",
2349 FORBIDDENBYTE);
2350 for (i = SST-1; i >= 1; --i) {
Benjamin Peterson19517e42016-09-18 19:22:22 -07002351 const uint8_t byte = *(q-i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002352 fprintf(stderr, " at p-%d: 0x%02x", i, byte);
2353 if (byte != FORBIDDENBYTE)
2354 fputs(" *** OUCH", stderr);
2355 fputc('\n', stderr);
2356 }
Tim Peters449b5a82002-04-28 06:14:45 +00002357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002358 fputs(" Because memory is corrupted at the start, the "
2359 "count of bytes requested\n"
2360 " may be bogus, and checking the trailing pad "
2361 "bytes may segfault.\n", stderr);
2362 }
Tim Petersddea2082002-03-23 10:03:50 +00002363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002364 tail = q + nbytes;
2365 fprintf(stderr, " The %d pad bytes at tail=%p are ", SST, tail);
2366 ok = 1;
2367 for (i = 0; i < SST; ++i) {
2368 if (tail[i] != FORBIDDENBYTE) {
2369 ok = 0;
2370 break;
2371 }
2372 }
2373 if (ok)
2374 fputs("FORBIDDENBYTE, as expected.\n", stderr);
2375 else {
2376 fprintf(stderr, "not all FORBIDDENBYTE (0x%02x):\n",
Stefan Krah735bb122010-11-26 10:54:09 +00002377 FORBIDDENBYTE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002378 for (i = 0; i < SST; ++i) {
Benjamin Peterson19517e42016-09-18 19:22:22 -07002379 const uint8_t byte = tail[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002380 fprintf(stderr, " at tail+%d: 0x%02x",
Stefan Krah735bb122010-11-26 10:54:09 +00002381 i, byte);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002382 if (byte != FORBIDDENBYTE)
2383 fputs(" *** OUCH", stderr);
2384 fputc('\n', stderr);
2385 }
2386 }
Tim Petersddea2082002-03-23 10:03:50 +00002387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002388 serial = read_size_t(tail + SST);
2389 fprintf(stderr, " The block was made by call #%" PY_FORMAT_SIZE_T
2390 "u to debug malloc/realloc.\n", serial);
Tim Petersddea2082002-03-23 10:03:50 +00002391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002392 if (nbytes > 0) {
2393 i = 0;
2394 fputs(" Data at p:", stderr);
2395 /* print up to 8 bytes at the start */
2396 while (q < tail && i < 8) {
2397 fprintf(stderr, " %02x", *q);
2398 ++i;
2399 ++q;
2400 }
2401 /* and up to 8 at the end */
2402 if (q < tail) {
2403 if (tail - q > 8) {
2404 fputs(" ...", stderr);
2405 q = tail - 8;
2406 }
2407 while (q < tail) {
2408 fprintf(stderr, " %02x", *q);
2409 ++q;
2410 }
2411 }
2412 fputc('\n', stderr);
2413 }
Victor Stinner0611c262016-03-15 22:22:13 +01002414 fputc('\n', stderr);
2415
2416 fflush(stderr);
2417 _PyMem_DumpTraceback(fileno(stderr), p);
Tim Petersddea2082002-03-23 10:03:50 +00002418}
2419
David Malcolm49526f42012-06-22 14:55:41 -04002420
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00002421static size_t
David Malcolm49526f42012-06-22 14:55:41 -04002422printone(FILE *out, const char* msg, size_t value)
Tim Peters16bcb6b2002-04-05 05:45:31 +00002423{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002424 int i, k;
2425 char buf[100];
2426 size_t origvalue = value;
Tim Peters16bcb6b2002-04-05 05:45:31 +00002427
David Malcolm49526f42012-06-22 14:55:41 -04002428 fputs(msg, out);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002429 for (i = (int)strlen(msg); i < 35; ++i)
David Malcolm49526f42012-06-22 14:55:41 -04002430 fputc(' ', out);
2431 fputc('=', out);
Tim Peters49f26812002-04-06 01:45:35 +00002432
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002433 /* Write the value with commas. */
2434 i = 22;
2435 buf[i--] = '\0';
2436 buf[i--] = '\n';
2437 k = 3;
2438 do {
2439 size_t nextvalue = value / 10;
Benjamin Peterson2dba1ee2013-02-20 16:54:30 -05002440 unsigned int digit = (unsigned int)(value - nextvalue * 10);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002441 value = nextvalue;
2442 buf[i--] = (char)(digit + '0');
2443 --k;
2444 if (k == 0 && value && i >= 0) {
2445 k = 3;
2446 buf[i--] = ',';
2447 }
2448 } while (value && i >= 0);
Tim Peters49f26812002-04-06 01:45:35 +00002449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002450 while (i >= 0)
2451 buf[i--] = ' ';
David Malcolm49526f42012-06-22 14:55:41 -04002452 fputs(buf, out);
Tim Peters49f26812002-04-06 01:45:35 +00002453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002454 return origvalue;
Tim Peters16bcb6b2002-04-05 05:45:31 +00002455}
2456
David Malcolm49526f42012-06-22 14:55:41 -04002457void
2458_PyDebugAllocatorStats(FILE *out,
2459 const char *block_name, int num_blocks, size_t sizeof_block)
2460{
2461 char buf1[128];
2462 char buf2[128];
2463 PyOS_snprintf(buf1, sizeof(buf1),
Tim Peterseaa3bcc2013-09-05 22:57:04 -05002464 "%d %ss * %" PY_FORMAT_SIZE_T "d bytes each",
David Malcolm49526f42012-06-22 14:55:41 -04002465 num_blocks, block_name, sizeof_block);
2466 PyOS_snprintf(buf2, sizeof(buf2),
2467 "%48s ", buf1);
2468 (void)printone(out, buf2, num_blocks * sizeof_block);
2469}
2470
Victor Stinner34be807c2016-03-14 12:04:26 +01002471
David Malcolm49526f42012-06-22 14:55:41 -04002472#ifdef WITH_PYMALLOC
2473
Victor Stinner34be807c2016-03-14 12:04:26 +01002474#ifdef Py_DEBUG
2475/* Is target in the list? The list is traversed via the nextpool pointers.
2476 * The list may be NULL-terminated, or circular. Return 1 if target is in
2477 * list, else 0.
2478 */
2479static int
2480pool_is_in_list(const poolp target, poolp list)
2481{
2482 poolp origlist = list;
2483 assert(target != NULL);
2484 if (list == NULL)
2485 return 0;
2486 do {
2487 if (target == list)
2488 return 1;
2489 list = list->nextpool;
2490 } while (list != NULL && list != origlist);
2491 return 0;
2492}
2493#endif
2494
David Malcolm49526f42012-06-22 14:55:41 -04002495/* Print summary info to "out" about the state of pymalloc's structures.
Tim Peters08d82152002-04-18 22:25:03 +00002496 * In Py_DEBUG mode, also perform some expensive internal consistency
2497 * checks.
Victor Stinner6bf992a2017-12-06 17:26:10 +01002498 *
2499 * Return 0 if the memory debug hooks are not installed or no statistics was
Miss Islington (bot)e86db342018-02-03 17:41:43 -08002500 * written into out, return 1 otherwise.
Tim Peters08d82152002-04-18 22:25:03 +00002501 */
Victor Stinner6bf992a2017-12-06 17:26:10 +01002502int
David Malcolm49526f42012-06-22 14:55:41 -04002503_PyObject_DebugMallocStats(FILE *out)
Tim Peters7ccfadf2002-04-01 06:04:21 +00002504{
Victor Stinner6bf992a2017-12-06 17:26:10 +01002505 if (!_PyMem_PymallocEnabled()) {
2506 return 0;
2507 }
2508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002509 uint i;
2510 const uint numclasses = SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT;
2511 /* # of pools, allocated blocks, and free blocks per class index */
2512 size_t numpools[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT];
2513 size_t numblocks[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT];
2514 size_t numfreeblocks[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT];
2515 /* total # of allocated bytes in used and full pools */
2516 size_t allocated_bytes = 0;
2517 /* total # of available bytes in used pools */
2518 size_t available_bytes = 0;
2519 /* # of free pools + pools not yet carved out of current arena */
2520 uint numfreepools = 0;
2521 /* # of bytes for arena alignment padding */
2522 size_t arena_alignment = 0;
2523 /* # of bytes in used and full pools used for pool_headers */
2524 size_t pool_header_bytes = 0;
2525 /* # of bytes in used and full pools wasted due to quantization,
2526 * i.e. the necessarily leftover space at the ends of used and
2527 * full pools.
2528 */
2529 size_t quantization = 0;
2530 /* # of arenas actually allocated. */
2531 size_t narenas = 0;
2532 /* running total -- should equal narenas * ARENA_SIZE */
2533 size_t total;
2534 char buf[128];
Tim Peters7ccfadf2002-04-01 06:04:21 +00002535
David Malcolm49526f42012-06-22 14:55:41 -04002536 fprintf(out, "Small block threshold = %d, in %u size classes.\n",
Stefan Krah735bb122010-11-26 10:54:09 +00002537 SMALL_REQUEST_THRESHOLD, numclasses);
Tim Peters7ccfadf2002-04-01 06:04:21 +00002538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002539 for (i = 0; i < numclasses; ++i)
2540 numpools[i] = numblocks[i] = numfreeblocks[i] = 0;
Tim Peters7ccfadf2002-04-01 06:04:21 +00002541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002542 /* Because full pools aren't linked to from anything, it's easiest
2543 * to march over all the arenas. If we're lucky, most of the memory
2544 * will be living in full pools -- would be a shame to miss them.
2545 */
Victor Stinner9e87e772017-11-24 12:09:24 +01002546 for (i = 0; i < maxarenas; ++i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002547 uint j;
Victor Stinner9e87e772017-11-24 12:09:24 +01002548 uintptr_t base = arenas[i].address;
Thomas Woutersa9773292006-04-21 09:43:23 +00002549
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002550 /* Skip arenas which are not allocated. */
Victor Stinner9e87e772017-11-24 12:09:24 +01002551 if (arenas[i].address == (uintptr_t)NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002552 continue;
2553 narenas += 1;
Thomas Woutersa9773292006-04-21 09:43:23 +00002554
Victor Stinner9e87e772017-11-24 12:09:24 +01002555 numfreepools += arenas[i].nfreepools;
Tim Peters7ccfadf2002-04-01 06:04:21 +00002556
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002557 /* round up to pool alignment */
Benjamin Peterson5d4b09c2016-09-18 19:24:52 -07002558 if (base & (uintptr_t)POOL_SIZE_MASK) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002559 arena_alignment += POOL_SIZE;
Benjamin Peterson5d4b09c2016-09-18 19:24:52 -07002560 base &= ~(uintptr_t)POOL_SIZE_MASK;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002561 base += POOL_SIZE;
2562 }
Tim Peters7ccfadf2002-04-01 06:04:21 +00002563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002564 /* visit every pool in the arena */
Victor Stinner9e87e772017-11-24 12:09:24 +01002565 assert(base <= (uintptr_t) arenas[i].pool_address);
2566 for (j = 0; base < (uintptr_t) arenas[i].pool_address;
Benjamin Peterson19517e42016-09-18 19:22:22 -07002567 ++j, base += POOL_SIZE) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002568 poolp p = (poolp)base;
2569 const uint sz = p->szidx;
2570 uint freeblocks;
Tim Peters08d82152002-04-18 22:25:03 +00002571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002572 if (p->ref.count == 0) {
2573 /* currently unused */
Victor Stinner34be807c2016-03-14 12:04:26 +01002574#ifdef Py_DEBUG
Victor Stinner9e87e772017-11-24 12:09:24 +01002575 assert(pool_is_in_list(p, arenas[i].freepools));
Victor Stinner34be807c2016-03-14 12:04:26 +01002576#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002577 continue;
2578 }
2579 ++numpools[sz];
2580 numblocks[sz] += p->ref.count;
2581 freeblocks = NUMBLOCKS(sz) - p->ref.count;
2582 numfreeblocks[sz] += freeblocks;
Tim Peters08d82152002-04-18 22:25:03 +00002583#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002584 if (freeblocks > 0)
Victor Stinner9e87e772017-11-24 12:09:24 +01002585 assert(pool_is_in_list(p, usedpools[sz + sz]));
Tim Peters08d82152002-04-18 22:25:03 +00002586#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002587 }
2588 }
Victor Stinner9e87e772017-11-24 12:09:24 +01002589 assert(narenas == narenas_currently_allocated);
Tim Peters7ccfadf2002-04-01 06:04:21 +00002590
David Malcolm49526f42012-06-22 14:55:41 -04002591 fputc('\n', out);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002592 fputs("class size num pools blocks in use avail blocks\n"
2593 "----- ---- --------- ------------- ------------\n",
David Malcolm49526f42012-06-22 14:55:41 -04002594 out);
Tim Peters7ccfadf2002-04-01 06:04:21 +00002595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002596 for (i = 0; i < numclasses; ++i) {
2597 size_t p = numpools[i];
2598 size_t b = numblocks[i];
2599 size_t f = numfreeblocks[i];
2600 uint size = INDEX2SIZE(i);
2601 if (p == 0) {
2602 assert(b == 0 && f == 0);
2603 continue;
2604 }
David Malcolm49526f42012-06-22 14:55:41 -04002605 fprintf(out, "%5u %6u "
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002606 "%11" PY_FORMAT_SIZE_T "u "
2607 "%15" PY_FORMAT_SIZE_T "u "
2608 "%13" PY_FORMAT_SIZE_T "u\n",
Stefan Krah735bb122010-11-26 10:54:09 +00002609 i, size, p, b, f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002610 allocated_bytes += b * size;
2611 available_bytes += f * size;
2612 pool_header_bytes += p * POOL_OVERHEAD;
2613 quantization += p * ((POOL_SIZE - POOL_OVERHEAD) % size);
2614 }
David Malcolm49526f42012-06-22 14:55:41 -04002615 fputc('\n', out);
Victor Stinner34be807c2016-03-14 12:04:26 +01002616 if (_PyMem_DebugEnabled())
Victor Stinner9e87e772017-11-24 12:09:24 +01002617 (void)printone(out, "# times object malloc called", serialno);
2618 (void)printone(out, "# arenas allocated total", ntimes_arena_allocated);
2619 (void)printone(out, "# arenas reclaimed", ntimes_arena_allocated - narenas);
2620 (void)printone(out, "# arenas highwater mark", narenas_highwater);
David Malcolm49526f42012-06-22 14:55:41 -04002621 (void)printone(out, "# arenas allocated current", narenas);
Thomas Woutersa9773292006-04-21 09:43:23 +00002622
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002623 PyOS_snprintf(buf, sizeof(buf),
2624 "%" PY_FORMAT_SIZE_T "u arenas * %d bytes/arena",
2625 narenas, ARENA_SIZE);
David Malcolm49526f42012-06-22 14:55:41 -04002626 (void)printone(out, buf, narenas * ARENA_SIZE);
Tim Peters16bcb6b2002-04-05 05:45:31 +00002627
David Malcolm49526f42012-06-22 14:55:41 -04002628 fputc('\n', out);
Tim Peters16bcb6b2002-04-05 05:45:31 +00002629
David Malcolm49526f42012-06-22 14:55:41 -04002630 total = printone(out, "# bytes in allocated blocks", allocated_bytes);
2631 total += printone(out, "# bytes in available blocks", available_bytes);
Tim Peters49f26812002-04-06 01:45:35 +00002632
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002633 PyOS_snprintf(buf, sizeof(buf),
2634 "%u unused pools * %d bytes", numfreepools, POOL_SIZE);
David Malcolm49526f42012-06-22 14:55:41 -04002635 total += printone(out, buf, (size_t)numfreepools * POOL_SIZE);
Tim Peters16bcb6b2002-04-05 05:45:31 +00002636
David Malcolm49526f42012-06-22 14:55:41 -04002637 total += printone(out, "# bytes lost to pool headers", pool_header_bytes);
2638 total += printone(out, "# bytes lost to quantization", quantization);
2639 total += printone(out, "# bytes lost to arena alignment", arena_alignment);
2640 (void)printone(out, "Total", total);
Victor Stinner6bf992a2017-12-06 17:26:10 +01002641 return 1;
Tim Peters7ccfadf2002-04-01 06:04:21 +00002642}
2643
David Malcolm49526f42012-06-22 14:55:41 -04002644#endif /* #ifdef WITH_PYMALLOC */