blob: 1c2a32050f9381e0a8aab3591a42e191e8401644 [file] [log] [blame]
Tim Peters1221c0a2002-03-23 00:20:15 +00001#include "Python.h"
Victor Stinner621cebe2018-11-12 16:53:38 +01002#include "pycore_pymem.h"
Tim Peters1221c0a2002-03-23 00:20:15 +00003
Benjamin Peterson3924f932016-09-18 19:12:48 -07004#include <stdbool.h>
5
Victor Stinner0611c262016-03-15 22:22:13 +01006
7/* Defined in tracemalloc.c */
8extern void _PyMem_DumpTraceback(int fd, const void *ptr);
9
10
Victor Stinner0507bf52013-07-07 02:05:46 +020011/* Python's malloc wrappers (see pymem.h) */
12
Victor Stinner34be8072016-03-14 12:04:26 +010013#undef uint
14#define uint unsigned int /* assuming >= 16 bits */
15
Victor Stinner0507bf52013-07-07 02:05:46 +020016/* Forward declaration */
Victor Stinnerc4aec362016-03-14 22:26:53 +010017static void* _PyMem_DebugRawMalloc(void *ctx, size_t size);
18static void* _PyMem_DebugRawCalloc(void *ctx, size_t nelem, size_t elsize);
19static void* _PyMem_DebugRawRealloc(void *ctx, void *ptr, size_t size);
Victor Stinner9ed83c42017-10-31 12:18:10 -070020static void _PyMem_DebugRawFree(void *ctx, void *ptr);
Victor Stinnerc4aec362016-03-14 22:26:53 +010021
Victor Stinner0507bf52013-07-07 02:05:46 +020022static void* _PyMem_DebugMalloc(void *ctx, size_t size);
Victor Stinnerdb067af2014-05-02 22:31:14 +020023static void* _PyMem_DebugCalloc(void *ctx, size_t nelem, size_t elsize);
Victor Stinner0507bf52013-07-07 02:05:46 +020024static void* _PyMem_DebugRealloc(void *ctx, void *ptr, size_t size);
Victor Stinnerc4aec362016-03-14 22:26:53 +010025static void _PyMem_DebugFree(void *ctx, void *p);
Victor Stinner0507bf52013-07-07 02:05:46 +020026
27static void _PyObject_DebugDumpAddress(const void *p);
28static void _PyMem_DebugCheckAddress(char api_id, const void *p);
Victor Stinner0507bf52013-07-07 02:05:46 +020029
Victor Stinner5d39e042017-11-29 17:20:38 +010030static void _PyMem_SetupDebugHooksDomain(PyMemAllocatorDomain domain);
31
Nick Coghlan6ba64f42013-09-29 00:28:55 +100032#if defined(__has_feature) /* Clang */
Alexey Izbyshevfd3a91c2018-11-12 02:14:51 +030033# if __has_feature(address_sanitizer) /* is ASAN enabled? */
34# define _Py_NO_ADDRESS_SAFETY_ANALYSIS \
Benjamin Peterson3924f932016-09-18 19:12:48 -070035 __attribute__((no_address_safety_analysis))
Alexey Izbyshevfd3a91c2018-11-12 02:14:51 +030036# endif
37# if __has_feature(thread_sanitizer) /* is TSAN enabled? */
38# define _Py_NO_SANITIZE_THREAD __attribute__((no_sanitize_thread))
39# endif
40# if __has_feature(memory_sanitizer) /* is MSAN enabled? */
41# define _Py_NO_SANITIZE_MEMORY __attribute__((no_sanitize_memory))
42# endif
43#elif defined(__GNUC__)
44# if defined(__SANITIZE_ADDRESS__) /* GCC 4.8+, is ASAN enabled? */
45# define _Py_NO_ADDRESS_SAFETY_ANALYSIS \
Benjamin Peterson3924f932016-09-18 19:12:48 -070046 __attribute__((no_address_safety_analysis))
Alexey Izbyshevfd3a91c2018-11-12 02:14:51 +030047# endif
48 // TSAN is supported since GCC 4.8, but __SANITIZE_THREAD__ macro
49 // is provided only since GCC 7.
50# if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8)
51# define _Py_NO_SANITIZE_THREAD __attribute__((no_sanitize_thread))
52# endif
53#endif
54
55#ifndef _Py_NO_ADDRESS_SAFETY_ANALYSIS
56# define _Py_NO_ADDRESS_SAFETY_ANALYSIS
57#endif
58#ifndef _Py_NO_SANITIZE_THREAD
59# define _Py_NO_SANITIZE_THREAD
60#endif
61#ifndef _Py_NO_SANITIZE_MEMORY
62# define _Py_NO_SANITIZE_MEMORY
Nick Coghlan6ba64f42013-09-29 00:28:55 +100063#endif
64
Tim Peters1221c0a2002-03-23 00:20:15 +000065#ifdef WITH_PYMALLOC
66
Victor Stinner0507bf52013-07-07 02:05:46 +020067#ifdef MS_WINDOWS
68# include <windows.h>
69#elif defined(HAVE_MMAP)
70# include <sys/mman.h>
71# ifdef MAP_ANONYMOUS
72# define ARENAS_USE_MMAP
73# endif
Antoine Pitrou6f26be02011-05-03 18:18:59 +020074#endif
75
Victor Stinner0507bf52013-07-07 02:05:46 +020076/* Forward declaration */
77static void* _PyObject_Malloc(void *ctx, size_t size);
Victor Stinnerdb067af2014-05-02 22:31:14 +020078static void* _PyObject_Calloc(void *ctx, size_t nelem, size_t elsize);
Victor Stinner0507bf52013-07-07 02:05:46 +020079static void _PyObject_Free(void *ctx, void *p);
80static void* _PyObject_Realloc(void *ctx, void *ptr, size_t size);
Martin v. Löwiscd83fa82013-06-27 12:23:29 +020081#endif
82
Victor Stinner0507bf52013-07-07 02:05:46 +020083
Victor Stinner9e00e802018-10-25 13:31:16 +020084/* bpo-35053: Declare tracemalloc configuration here rather than
85 Modules/_tracemalloc.c because _tracemalloc can be compiled as dynamic
86 library, whereas _Py_NewReference() requires it. */
87struct _PyTraceMalloc_Config _Py_tracemalloc_config = _PyTraceMalloc_Config_INIT;
88
89
Victor Stinner0507bf52013-07-07 02:05:46 +020090static void *
91_PyMem_RawMalloc(void *ctx, size_t size)
92{
Victor Stinnerdb067af2014-05-02 22:31:14 +020093 /* PyMem_RawMalloc(0) means malloc(1). Some systems would return NULL
Victor Stinner0507bf52013-07-07 02:05:46 +020094 for malloc(0), which would be treated as an error. Some platforms would
95 return a pointer with no memory behind it, which would break pymalloc.
96 To solve these problems, allocate an extra byte. */
97 if (size == 0)
98 size = 1;
99 return malloc(size);
100}
101
102static void *
Victor Stinnerdb067af2014-05-02 22:31:14 +0200103_PyMem_RawCalloc(void *ctx, size_t nelem, size_t elsize)
104{
105 /* PyMem_RawCalloc(0, 0) means calloc(1, 1). Some systems would return NULL
106 for calloc(0, 0), which would be treated as an error. Some platforms
107 would return a pointer with no memory behind it, which would break
108 pymalloc. To solve these problems, allocate an extra byte. */
109 if (nelem == 0 || elsize == 0) {
110 nelem = 1;
111 elsize = 1;
112 }
113 return calloc(nelem, elsize);
114}
115
116static void *
Victor Stinner0507bf52013-07-07 02:05:46 +0200117_PyMem_RawRealloc(void *ctx, void *ptr, size_t size)
118{
119 if (size == 0)
120 size = 1;
121 return realloc(ptr, size);
122}
123
124static void
125_PyMem_RawFree(void *ctx, void *ptr)
126{
127 free(ptr);
128}
129
130
131#ifdef MS_WINDOWS
132static void *
133_PyObject_ArenaVirtualAlloc(void *ctx, size_t size)
134{
135 return VirtualAlloc(NULL, size,
136 MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
137}
138
139static void
140_PyObject_ArenaVirtualFree(void *ctx, void *ptr, size_t size)
141{
Victor Stinner725e6682013-07-07 03:06:16 +0200142 VirtualFree(ptr, 0, MEM_RELEASE);
Victor Stinner0507bf52013-07-07 02:05:46 +0200143}
144
145#elif defined(ARENAS_USE_MMAP)
146static void *
147_PyObject_ArenaMmap(void *ctx, size_t size)
148{
149 void *ptr;
150 ptr = mmap(NULL, size, PROT_READ|PROT_WRITE,
151 MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
152 if (ptr == MAP_FAILED)
153 return NULL;
154 assert(ptr != NULL);
155 return ptr;
156}
157
158static void
159_PyObject_ArenaMunmap(void *ctx, void *ptr, size_t size)
160{
161 munmap(ptr, size);
162}
163
164#else
165static void *
166_PyObject_ArenaMalloc(void *ctx, size_t size)
167{
168 return malloc(size);
169}
170
171static void
172_PyObject_ArenaFree(void *ctx, void *ptr, size_t size)
173{
174 free(ptr);
175}
176#endif
177
Victor Stinner5d39e042017-11-29 17:20:38 +0100178#define MALLOC_ALLOC {NULL, _PyMem_RawMalloc, _PyMem_RawCalloc, _PyMem_RawRealloc, _PyMem_RawFree}
Victor Stinner0507bf52013-07-07 02:05:46 +0200179#ifdef WITH_PYMALLOC
Victor Stinner5d39e042017-11-29 17:20:38 +0100180# define PYMALLOC_ALLOC {NULL, _PyObject_Malloc, _PyObject_Calloc, _PyObject_Realloc, _PyObject_Free}
Victor Stinner0507bf52013-07-07 02:05:46 +0200181#endif
Victor Stinner5d39e042017-11-29 17:20:38 +0100182
183#define PYRAW_ALLOC MALLOC_ALLOC
184#ifdef WITH_PYMALLOC
185# define PYOBJ_ALLOC PYMALLOC_ALLOC
186#else
187# define PYOBJ_ALLOC MALLOC_ALLOC
188#endif
189#define PYMEM_ALLOC PYOBJ_ALLOC
Victor Stinner0507bf52013-07-07 02:05:46 +0200190
Victor Stinner0507bf52013-07-07 02:05:46 +0200191typedef struct {
192 /* We tag each block with an API ID in order to tag API violations */
193 char api_id;
Victor Stinnerd8f0d922014-06-02 21:57:10 +0200194 PyMemAllocatorEx alloc;
Victor Stinner0507bf52013-07-07 02:05:46 +0200195} debug_alloc_api_t;
196static struct {
197 debug_alloc_api_t raw;
198 debug_alloc_api_t mem;
199 debug_alloc_api_t obj;
200} _PyMem_Debug = {
Victor Stinner5d39e042017-11-29 17:20:38 +0100201 {'r', PYRAW_ALLOC},
202 {'m', PYMEM_ALLOC},
203 {'o', PYOBJ_ALLOC}
Victor Stinner0507bf52013-07-07 02:05:46 +0200204 };
205
Victor Stinner5d39e042017-11-29 17:20:38 +0100206#define PYDBGRAW_ALLOC \
207 {&_PyMem_Debug.raw, _PyMem_DebugRawMalloc, _PyMem_DebugRawCalloc, _PyMem_DebugRawRealloc, _PyMem_DebugRawFree}
208#define PYDBGMEM_ALLOC \
209 {&_PyMem_Debug.mem, _PyMem_DebugMalloc, _PyMem_DebugCalloc, _PyMem_DebugRealloc, _PyMem_DebugFree}
210#define PYDBGOBJ_ALLOC \
211 {&_PyMem_Debug.obj, _PyMem_DebugMalloc, _PyMem_DebugCalloc, _PyMem_DebugRealloc, _PyMem_DebugFree}
Victor Stinner0507bf52013-07-07 02:05:46 +0200212
Victor Stinner9e87e772017-11-24 12:09:24 +0100213#ifdef Py_DEBUG
Victor Stinner5d39e042017-11-29 17:20:38 +0100214static PyMemAllocatorEx _PyMem_Raw = PYDBGRAW_ALLOC;
215static PyMemAllocatorEx _PyMem = PYDBGMEM_ALLOC;
216static PyMemAllocatorEx _PyObject = PYDBGOBJ_ALLOC;
Victor Stinner9e87e772017-11-24 12:09:24 +0100217#else
Victor Stinner5d39e042017-11-29 17:20:38 +0100218static PyMemAllocatorEx _PyMem_Raw = PYRAW_ALLOC;
219static PyMemAllocatorEx _PyMem = PYMEM_ALLOC;
220static PyMemAllocatorEx _PyObject = PYOBJ_ALLOC;
Victor Stinner9e87e772017-11-24 12:09:24 +0100221#endif
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600222
Victor Stinner0507bf52013-07-07 02:05:46 +0200223
Victor Stinner5d39e042017-11-29 17:20:38 +0100224static int
225pymem_set_default_allocator(PyMemAllocatorDomain domain, int debug,
226 PyMemAllocatorEx *old_alloc)
227{
228 if (old_alloc != NULL) {
229 PyMem_GetAllocator(domain, old_alloc);
230 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800231
Victor Stinner5d39e042017-11-29 17:20:38 +0100232
233 PyMemAllocatorEx new_alloc;
234 switch(domain)
235 {
236 case PYMEM_DOMAIN_RAW:
237 new_alloc = (PyMemAllocatorEx)PYRAW_ALLOC;
238 break;
239 case PYMEM_DOMAIN_MEM:
240 new_alloc = (PyMemAllocatorEx)PYMEM_ALLOC;
241 break;
242 case PYMEM_DOMAIN_OBJ:
243 new_alloc = (PyMemAllocatorEx)PYOBJ_ALLOC;
244 break;
245 default:
246 /* unknown domain */
247 return -1;
248 }
249 PyMem_SetAllocator(domain, &new_alloc);
250 if (debug) {
251 _PyMem_SetupDebugHooksDomain(domain);
252 }
253 return 0;
254}
255
256
257int
258_PyMem_SetDefaultAllocator(PyMemAllocatorDomain domain,
259 PyMemAllocatorEx *old_alloc)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800260{
Victor Stinnerccb04422017-11-16 03:20:31 -0800261#ifdef Py_DEBUG
Victor Stinner5d39e042017-11-29 17:20:38 +0100262 const int debug = 1;
Victor Stinnerccb04422017-11-16 03:20:31 -0800263#else
Victor Stinner5d39e042017-11-29 17:20:38 +0100264 const int debug = 0;
Victor Stinnerccb04422017-11-16 03:20:31 -0800265#endif
Victor Stinner5d39e042017-11-29 17:20:38 +0100266 return pymem_set_default_allocator(domain, debug, old_alloc);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800267}
Victor Stinner0507bf52013-07-07 02:05:46 +0200268
Victor Stinner5d39e042017-11-29 17:20:38 +0100269
Victor Stinner34be8072016-03-14 12:04:26 +0100270int
271_PyMem_SetupAllocators(const char *opt)
272{
273 if (opt == NULL || *opt == '\0') {
274 /* PYTHONMALLOC is empty or is not set or ignored (-E/-I command line
Victor Stinner5d39e042017-11-29 17:20:38 +0100275 options): use default memory allocators */
276 opt = "default";
Victor Stinner34be8072016-03-14 12:04:26 +0100277 }
278
Victor Stinner5d39e042017-11-29 17:20:38 +0100279 if (strcmp(opt, "default") == 0) {
280 (void)_PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, NULL);
281 (void)_PyMem_SetDefaultAllocator(PYMEM_DOMAIN_MEM, NULL);
282 (void)_PyMem_SetDefaultAllocator(PYMEM_DOMAIN_OBJ, NULL);
Victor Stinner34be8072016-03-14 12:04:26 +0100283 }
Victor Stinner5d39e042017-11-29 17:20:38 +0100284 else if (strcmp(opt, "debug") == 0) {
285 (void)pymem_set_default_allocator(PYMEM_DOMAIN_RAW, 1, NULL);
286 (void)pymem_set_default_allocator(PYMEM_DOMAIN_MEM, 1, NULL);
287 (void)pymem_set_default_allocator(PYMEM_DOMAIN_OBJ, 1, NULL);
Victor Stinner34be8072016-03-14 12:04:26 +0100288 }
289#ifdef WITH_PYMALLOC
Victor Stinner5d39e042017-11-29 17:20:38 +0100290 else if (strcmp(opt, "pymalloc") == 0 || strcmp(opt, "pymalloc_debug") == 0) {
291 PyMemAllocatorEx malloc_alloc = MALLOC_ALLOC;
292 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &malloc_alloc);
Victor Stinner34be8072016-03-14 12:04:26 +0100293
Victor Stinner5d39e042017-11-29 17:20:38 +0100294 PyMemAllocatorEx pymalloc = PYMALLOC_ALLOC;
295 PyMem_SetAllocator(PYMEM_DOMAIN_MEM, &pymalloc);
296 PyMem_SetAllocator(PYMEM_DOMAIN_OBJ, &pymalloc);
Victor Stinner34be8072016-03-14 12:04:26 +0100297
Victor Stinner5d39e042017-11-29 17:20:38 +0100298 if (strcmp(opt, "pymalloc_debug") == 0) {
Victor Stinner34be8072016-03-14 12:04:26 +0100299 PyMem_SetupDebugHooks();
Victor Stinner5d39e042017-11-29 17:20:38 +0100300 }
Victor Stinner34be8072016-03-14 12:04:26 +0100301 }
302#endif
Victor Stinner5d39e042017-11-29 17:20:38 +0100303 else if (strcmp(opt, "malloc") == 0 || strcmp(opt, "malloc_debug") == 0) {
304 PyMemAllocatorEx malloc_alloc = MALLOC_ALLOC;
305 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &malloc_alloc);
306 PyMem_SetAllocator(PYMEM_DOMAIN_MEM, &malloc_alloc);
307 PyMem_SetAllocator(PYMEM_DOMAIN_OBJ, &malloc_alloc);
308
309 if (strcmp(opt, "malloc_debug") == 0) {
310 PyMem_SetupDebugHooks();
311 }
312 }
Victor Stinner34be8072016-03-14 12:04:26 +0100313 else {
314 /* unknown allocator */
315 return -1;
316 }
317 return 0;
318}
319
Victor Stinner5d39e042017-11-29 17:20:38 +0100320
321static int
322pymemallocator_eq(PyMemAllocatorEx *a, PyMemAllocatorEx *b)
323{
324 return (memcmp(a, b, sizeof(PyMemAllocatorEx)) == 0);
325}
326
327
328const char*
329_PyMem_GetAllocatorsName(void)
330{
331 PyMemAllocatorEx malloc_alloc = MALLOC_ALLOC;
332#ifdef WITH_PYMALLOC
333 PyMemAllocatorEx pymalloc = PYMALLOC_ALLOC;
334#endif
335
336 if (pymemallocator_eq(&_PyMem_Raw, &malloc_alloc) &&
337 pymemallocator_eq(&_PyMem, &malloc_alloc) &&
338 pymemallocator_eq(&_PyObject, &malloc_alloc))
339 {
340 return "malloc";
341 }
342#ifdef WITH_PYMALLOC
343 if (pymemallocator_eq(&_PyMem_Raw, &malloc_alloc) &&
344 pymemallocator_eq(&_PyMem, &pymalloc) &&
345 pymemallocator_eq(&_PyObject, &pymalloc))
346 {
347 return "pymalloc";
348 }
349#endif
350
351 PyMemAllocatorEx dbg_raw = PYDBGRAW_ALLOC;
352 PyMemAllocatorEx dbg_mem = PYDBGMEM_ALLOC;
353 PyMemAllocatorEx dbg_obj = PYDBGOBJ_ALLOC;
354
355 if (pymemallocator_eq(&_PyMem_Raw, &dbg_raw) &&
356 pymemallocator_eq(&_PyMem, &dbg_mem) &&
357 pymemallocator_eq(&_PyObject, &dbg_obj))
358 {
359 /* Debug hooks installed */
360 if (pymemallocator_eq(&_PyMem_Debug.raw.alloc, &malloc_alloc) &&
361 pymemallocator_eq(&_PyMem_Debug.mem.alloc, &malloc_alloc) &&
362 pymemallocator_eq(&_PyMem_Debug.obj.alloc, &malloc_alloc))
363 {
364 return "malloc_debug";
365 }
366#ifdef WITH_PYMALLOC
367 if (pymemallocator_eq(&_PyMem_Debug.raw.alloc, &malloc_alloc) &&
368 pymemallocator_eq(&_PyMem_Debug.mem.alloc, &pymalloc) &&
369 pymemallocator_eq(&_PyMem_Debug.obj.alloc, &pymalloc))
370 {
371 return "pymalloc_debug";
372 }
373#endif
374 }
375 return NULL;
376}
377
378
379#undef MALLOC_ALLOC
380#undef PYMALLOC_ALLOC
381#undef PYRAW_ALLOC
382#undef PYMEM_ALLOC
383#undef PYOBJ_ALLOC
384#undef PYDBGRAW_ALLOC
385#undef PYDBGMEM_ALLOC
386#undef PYDBGOBJ_ALLOC
387
Victor Stinner0507bf52013-07-07 02:05:46 +0200388
Victor Stinner9e87e772017-11-24 12:09:24 +0100389static PyObjectArenaAllocator _PyObject_Arena = {NULL,
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800390#ifdef MS_WINDOWS
Victor Stinner9e87e772017-11-24 12:09:24 +0100391 _PyObject_ArenaVirtualAlloc, _PyObject_ArenaVirtualFree
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800392#elif defined(ARENAS_USE_MMAP)
Victor Stinner9e87e772017-11-24 12:09:24 +0100393 _PyObject_ArenaMmap, _PyObject_ArenaMunmap
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800394#else
Victor Stinner9e87e772017-11-24 12:09:24 +0100395 _PyObject_ArenaMalloc, _PyObject_ArenaFree
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800396#endif
397 };
398
Victor Stinner0621e0e2016-04-19 17:02:55 +0200399#ifdef WITH_PYMALLOC
Victor Stinner34be8072016-03-14 12:04:26 +0100400static int
401_PyMem_DebugEnabled(void)
402{
403 return (_PyObject.malloc == _PyMem_DebugMalloc);
404}
405
Victor Stinner6bf992a2017-12-06 17:26:10 +0100406static int
Victor Stinner34be8072016-03-14 12:04:26 +0100407_PyMem_PymallocEnabled(void)
408{
409 if (_PyMem_DebugEnabled()) {
410 return (_PyMem_Debug.obj.alloc.malloc == _PyObject_Malloc);
411 }
412 else {
413 return (_PyObject.malloc == _PyObject_Malloc);
414 }
415}
416#endif
417
Victor Stinner5d39e042017-11-29 17:20:38 +0100418
419static void
420_PyMem_SetupDebugHooksDomain(PyMemAllocatorDomain domain)
Victor Stinner0507bf52013-07-07 02:05:46 +0200421{
Victor Stinnerd8f0d922014-06-02 21:57:10 +0200422 PyMemAllocatorEx alloc;
Victor Stinner0507bf52013-07-07 02:05:46 +0200423
Victor Stinner5d39e042017-11-29 17:20:38 +0100424 if (domain == PYMEM_DOMAIN_RAW) {
425 if (_PyMem_Raw.malloc == _PyMem_DebugRawMalloc) {
426 return;
427 }
Victor Stinner34be8072016-03-14 12:04:26 +0100428
Victor Stinner0507bf52013-07-07 02:05:46 +0200429 PyMem_GetAllocator(PYMEM_DOMAIN_RAW, &_PyMem_Debug.raw.alloc);
Victor Stinner5d39e042017-11-29 17:20:38 +0100430 alloc.ctx = &_PyMem_Debug.raw;
431 alloc.malloc = _PyMem_DebugRawMalloc;
432 alloc.calloc = _PyMem_DebugRawCalloc;
433 alloc.realloc = _PyMem_DebugRawRealloc;
434 alloc.free = _PyMem_DebugRawFree;
Victor Stinner0507bf52013-07-07 02:05:46 +0200435 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &alloc);
436 }
Victor Stinner5d39e042017-11-29 17:20:38 +0100437 else if (domain == PYMEM_DOMAIN_MEM) {
438 if (_PyMem.malloc == _PyMem_DebugMalloc) {
439 return;
440 }
Victor Stinner0507bf52013-07-07 02:05:46 +0200441
Victor Stinnerad524372016-03-16 12:12:53 +0100442 PyMem_GetAllocator(PYMEM_DOMAIN_MEM, &_PyMem_Debug.mem.alloc);
Victor Stinner5d39e042017-11-29 17:20:38 +0100443 alloc.ctx = &_PyMem_Debug.mem;
444 alloc.malloc = _PyMem_DebugMalloc;
445 alloc.calloc = _PyMem_DebugCalloc;
446 alloc.realloc = _PyMem_DebugRealloc;
447 alloc.free = _PyMem_DebugFree;
Victor Stinnerad524372016-03-16 12:12:53 +0100448 PyMem_SetAllocator(PYMEM_DOMAIN_MEM, &alloc);
449 }
Victor Stinner5d39e042017-11-29 17:20:38 +0100450 else if (domain == PYMEM_DOMAIN_OBJ) {
451 if (_PyObject.malloc == _PyMem_DebugMalloc) {
452 return;
453 }
Victor Stinnerad524372016-03-16 12:12:53 +0100454
Victor Stinner0507bf52013-07-07 02:05:46 +0200455 PyMem_GetAllocator(PYMEM_DOMAIN_OBJ, &_PyMem_Debug.obj.alloc);
Victor Stinner5d39e042017-11-29 17:20:38 +0100456 alloc.ctx = &_PyMem_Debug.obj;
457 alloc.malloc = _PyMem_DebugMalloc;
458 alloc.calloc = _PyMem_DebugCalloc;
459 alloc.realloc = _PyMem_DebugRealloc;
460 alloc.free = _PyMem_DebugFree;
Victor Stinner0507bf52013-07-07 02:05:46 +0200461 PyMem_SetAllocator(PYMEM_DOMAIN_OBJ, &alloc);
462 }
Victor Stinner0507bf52013-07-07 02:05:46 +0200463}
464
Victor Stinner5d39e042017-11-29 17:20:38 +0100465
466void
467PyMem_SetupDebugHooks(void)
468{
469 _PyMem_SetupDebugHooksDomain(PYMEM_DOMAIN_RAW);
470 _PyMem_SetupDebugHooksDomain(PYMEM_DOMAIN_MEM);
471 _PyMem_SetupDebugHooksDomain(PYMEM_DOMAIN_OBJ);
472}
473
Victor Stinner0507bf52013-07-07 02:05:46 +0200474void
Victor Stinnerd8f0d922014-06-02 21:57:10 +0200475PyMem_GetAllocator(PyMemAllocatorDomain domain, PyMemAllocatorEx *allocator)
Victor Stinner0507bf52013-07-07 02:05:46 +0200476{
477 switch(domain)
478 {
479 case PYMEM_DOMAIN_RAW: *allocator = _PyMem_Raw; break;
480 case PYMEM_DOMAIN_MEM: *allocator = _PyMem; break;
481 case PYMEM_DOMAIN_OBJ: *allocator = _PyObject; break;
482 default:
Victor Stinnerdb067af2014-05-02 22:31:14 +0200483 /* unknown domain: set all attributes to NULL */
Victor Stinner0507bf52013-07-07 02:05:46 +0200484 allocator->ctx = NULL;
485 allocator->malloc = NULL;
Victor Stinnerdb067af2014-05-02 22:31:14 +0200486 allocator->calloc = NULL;
Victor Stinner0507bf52013-07-07 02:05:46 +0200487 allocator->realloc = NULL;
488 allocator->free = NULL;
489 }
490}
491
492void
Victor Stinnerd8f0d922014-06-02 21:57:10 +0200493PyMem_SetAllocator(PyMemAllocatorDomain domain, PyMemAllocatorEx *allocator)
Victor Stinner0507bf52013-07-07 02:05:46 +0200494{
495 switch(domain)
496 {
497 case PYMEM_DOMAIN_RAW: _PyMem_Raw = *allocator; break;
498 case PYMEM_DOMAIN_MEM: _PyMem = *allocator; break;
499 case PYMEM_DOMAIN_OBJ: _PyObject = *allocator; break;
500 /* ignore unknown domain */
501 }
Victor Stinner0507bf52013-07-07 02:05:46 +0200502}
503
504void
505PyObject_GetArenaAllocator(PyObjectArenaAllocator *allocator)
506{
Victor Stinner9e87e772017-11-24 12:09:24 +0100507 *allocator = _PyObject_Arena;
Victor Stinner0507bf52013-07-07 02:05:46 +0200508}
509
510void
511PyObject_SetArenaAllocator(PyObjectArenaAllocator *allocator)
512{
Victor Stinner9e87e772017-11-24 12:09:24 +0100513 _PyObject_Arena = *allocator;
Victor Stinner0507bf52013-07-07 02:05:46 +0200514}
515
516void *
517PyMem_RawMalloc(size_t size)
518{
519 /*
520 * Limit ourselves to PY_SSIZE_T_MAX bytes to prevent security holes.
521 * Most python internals blindly use a signed Py_ssize_t to track
522 * things without checking for overflows or negatives.
523 * As size_t is unsigned, checking for size < 0 is not required.
524 */
525 if (size > (size_t)PY_SSIZE_T_MAX)
526 return NULL;
Victor Stinner0507bf52013-07-07 02:05:46 +0200527 return _PyMem_Raw.malloc(_PyMem_Raw.ctx, size);
528}
529
Victor Stinnerdb067af2014-05-02 22:31:14 +0200530void *
531PyMem_RawCalloc(size_t nelem, size_t elsize)
532{
533 /* see PyMem_RawMalloc() */
534 if (elsize != 0 && nelem > (size_t)PY_SSIZE_T_MAX / elsize)
535 return NULL;
536 return _PyMem_Raw.calloc(_PyMem_Raw.ctx, nelem, elsize);
537}
538
Victor Stinner0507bf52013-07-07 02:05:46 +0200539void*
540PyMem_RawRealloc(void *ptr, size_t new_size)
541{
542 /* see PyMem_RawMalloc() */
543 if (new_size > (size_t)PY_SSIZE_T_MAX)
544 return NULL;
545 return _PyMem_Raw.realloc(_PyMem_Raw.ctx, ptr, new_size);
546}
547
Victor Stinner9e87e772017-11-24 12:09:24 +0100548void PyMem_RawFree(void *ptr)
Victor Stinner0507bf52013-07-07 02:05:46 +0200549{
550 _PyMem_Raw.free(_PyMem_Raw.ctx, ptr);
551}
552
Victor Stinner9ed83c42017-10-31 12:18:10 -0700553
Victor Stinner0507bf52013-07-07 02:05:46 +0200554void *
555PyMem_Malloc(size_t size)
556{
557 /* see PyMem_RawMalloc() */
558 if (size > (size_t)PY_SSIZE_T_MAX)
559 return NULL;
560 return _PyMem.malloc(_PyMem.ctx, size);
561}
562
563void *
Victor Stinnerdb067af2014-05-02 22:31:14 +0200564PyMem_Calloc(size_t nelem, size_t elsize)
565{
566 /* see PyMem_RawMalloc() */
567 if (elsize != 0 && nelem > (size_t)PY_SSIZE_T_MAX / elsize)
568 return NULL;
569 return _PyMem.calloc(_PyMem.ctx, nelem, elsize);
570}
571
572void *
Victor Stinner0507bf52013-07-07 02:05:46 +0200573PyMem_Realloc(void *ptr, size_t new_size)
574{
575 /* see PyMem_RawMalloc() */
576 if (new_size > (size_t)PY_SSIZE_T_MAX)
577 return NULL;
578 return _PyMem.realloc(_PyMem.ctx, ptr, new_size);
579}
580
581void
582PyMem_Free(void *ptr)
583{
584 _PyMem.free(_PyMem.ctx, ptr);
585}
586
Victor Stinner9ed83c42017-10-31 12:18:10 -0700587
Victor Stinner46972b72017-11-24 22:55:40 +0100588wchar_t*
589_PyMem_RawWcsdup(const wchar_t *str)
590{
Victor Stinnerb64de462017-12-01 18:27:09 +0100591 assert(str != NULL);
592
Victor Stinner46972b72017-11-24 22:55:40 +0100593 size_t len = wcslen(str);
594 if (len > (size_t)PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
595 return NULL;
596 }
597
598 size_t size = (len + 1) * sizeof(wchar_t);
599 wchar_t *str2 = PyMem_RawMalloc(size);
600 if (str2 == NULL) {
601 return NULL;
602 }
603
604 memcpy(str2, str, size);
605 return str2;
606}
607
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200608char *
609_PyMem_RawStrdup(const char *str)
610{
Victor Stinnerb64de462017-12-01 18:27:09 +0100611 assert(str != NULL);
612 size_t size = strlen(str) + 1;
613 char *copy = PyMem_RawMalloc(size);
614 if (copy == NULL) {
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200615 return NULL;
Victor Stinnerb64de462017-12-01 18:27:09 +0100616 }
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200617 memcpy(copy, str, size);
618 return copy;
619}
620
621char *
622_PyMem_Strdup(const char *str)
623{
Victor Stinnerb64de462017-12-01 18:27:09 +0100624 assert(str != NULL);
625 size_t size = strlen(str) + 1;
626 char *copy = PyMem_Malloc(size);
627 if (copy == NULL) {
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200628 return NULL;
Victor Stinnerb64de462017-12-01 18:27:09 +0100629 }
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200630 memcpy(copy, str, size);
631 return copy;
632}
633
Victor Stinner0507bf52013-07-07 02:05:46 +0200634void *
635PyObject_Malloc(size_t size)
636{
637 /* see PyMem_RawMalloc() */
638 if (size > (size_t)PY_SSIZE_T_MAX)
639 return NULL;
640 return _PyObject.malloc(_PyObject.ctx, size);
641}
642
643void *
Victor Stinnerdb067af2014-05-02 22:31:14 +0200644PyObject_Calloc(size_t nelem, size_t elsize)
645{
646 /* see PyMem_RawMalloc() */
647 if (elsize != 0 && nelem > (size_t)PY_SSIZE_T_MAX / elsize)
648 return NULL;
649 return _PyObject.calloc(_PyObject.ctx, nelem, elsize);
650}
651
652void *
Victor Stinner0507bf52013-07-07 02:05:46 +0200653PyObject_Realloc(void *ptr, size_t new_size)
654{
655 /* see PyMem_RawMalloc() */
656 if (new_size > (size_t)PY_SSIZE_T_MAX)
657 return NULL;
658 return _PyObject.realloc(_PyObject.ctx, ptr, new_size);
659}
660
661void
662PyObject_Free(void *ptr)
663{
664 _PyObject.free(_PyObject.ctx, ptr);
665}
666
667
668#ifdef WITH_PYMALLOC
669
Benjamin Peterson05159c42009-12-03 03:01:27 +0000670#ifdef WITH_VALGRIND
671#include <valgrind/valgrind.h>
672
673/* If we're using GCC, use __builtin_expect() to reduce overhead of
674 the valgrind checks */
675#if defined(__GNUC__) && (__GNUC__ > 2) && defined(__OPTIMIZE__)
676# define UNLIKELY(value) __builtin_expect((value), 0)
677#else
678# define UNLIKELY(value) (value)
679#endif
680
681/* -1 indicates that we haven't checked that we're running on valgrind yet. */
682static int running_on_valgrind = -1;
683#endif
684
Victor Stinner9ed83c42017-10-31 12:18:10 -0700685
Victor Stinner9e87e772017-11-24 12:09:24 +0100686/* An object allocator for Python.
687
688 Here is an introduction to the layers of the Python memory architecture,
689 showing where the object allocator is actually used (layer +2), It is
690 called for every object allocation and deallocation (PyObject_New/Del),
691 unless the object-specific allocators implement a proprietary allocation
692 scheme (ex.: ints use a simple free list). This is also the place where
693 the cyclic garbage collector operates selectively on container objects.
694
695
696 Object-specific allocators
697 _____ ______ ______ ________
698 [ int ] [ dict ] [ list ] ... [ string ] Python core |
699+3 | <----- Object-specific memory -----> | <-- Non-object memory --> |
700 _______________________________ | |
701 [ Python's object allocator ] | |
702+2 | ####### Object memory ####### | <------ Internal buffers ------> |
703 ______________________________________________________________ |
704 [ Python's raw memory allocator (PyMem_ API) ] |
705+1 | <----- Python memory (under PyMem manager's control) ------> | |
706 __________________________________________________________________
707 [ Underlying general-purpose allocator (ex: C library malloc) ]
708 0 | <------ Virtual memory allocated for the python process -------> |
709
710 =========================================================================
711 _______________________________________________________________________
712 [ OS-specific Virtual Memory Manager (VMM) ]
713-1 | <--- Kernel dynamic storage allocation & management (page-based) ---> |
714 __________________________________ __________________________________
715 [ ] [ ]
716-2 | <-- Physical memory: ROM/RAM --> | | <-- Secondary storage (swap) --> |
717
718*/
719/*==========================================================================*/
720
721/* A fast, special-purpose memory allocator for small blocks, to be used
722 on top of a general-purpose malloc -- heavily based on previous art. */
723
724/* Vladimir Marangozov -- August 2000 */
725
726/*
727 * "Memory management is where the rubber meets the road -- if we do the wrong
728 * thing at any level, the results will not be good. And if we don't make the
729 * levels work well together, we are in serious trouble." (1)
730 *
731 * (1) Paul R. Wilson, Mark S. Johnstone, Michael Neely, and David Boles,
732 * "Dynamic Storage Allocation: A Survey and Critical Review",
733 * in Proc. 1995 Int'l. Workshop on Memory Management, September 1995.
734 */
735
736/* #undef WITH_MEMORY_LIMITS */ /* disable mem limit checks */
737
738/*==========================================================================*/
739
740/*
741 * Allocation strategy abstract:
742 *
743 * For small requests, the allocator sub-allocates <Big> blocks of memory.
744 * Requests greater than SMALL_REQUEST_THRESHOLD bytes are routed to the
745 * system's allocator.
746 *
747 * Small requests are grouped in size classes spaced 8 bytes apart, due
748 * to the required valid alignment of the returned address. Requests of
749 * a particular size are serviced from memory pools of 4K (one VMM page).
750 * Pools are fragmented on demand and contain free lists of blocks of one
751 * particular size class. In other words, there is a fixed-size allocator
752 * for each size class. Free pools are shared by the different allocators
753 * thus minimizing the space reserved for a particular size class.
754 *
755 * This allocation strategy is a variant of what is known as "simple
756 * segregated storage based on array of free lists". The main drawback of
757 * simple segregated storage is that we might end up with lot of reserved
758 * memory for the different free lists, which degenerate in time. To avoid
759 * this, we partition each free list in pools and we share dynamically the
760 * reserved space between all free lists. This technique is quite efficient
761 * for memory intensive programs which allocate mainly small-sized blocks.
762 *
763 * For small requests we have the following table:
764 *
765 * Request in bytes Size of allocated block Size class idx
766 * ----------------------------------------------------------------
767 * 1-8 8 0
768 * 9-16 16 1
769 * 17-24 24 2
770 * 25-32 32 3
771 * 33-40 40 4
772 * 41-48 48 5
773 * 49-56 56 6
774 * 57-64 64 7
775 * 65-72 72 8
776 * ... ... ...
777 * 497-504 504 62
778 * 505-512 512 63
779 *
780 * 0, SMALL_REQUEST_THRESHOLD + 1 and up: routed to the underlying
781 * allocator.
782 */
783
784/*==========================================================================*/
785
786/*
787 * -- Main tunable settings section --
788 */
789
790/*
791 * Alignment of addresses returned to the user. 8-bytes alignment works
792 * on most current architectures (with 32-bit or 64-bit address busses).
793 * The alignment value is also used for grouping small requests in size
794 * classes spaced ALIGNMENT bytes apart.
795 *
796 * You shouldn't change this unless you know what you are doing.
797 */
798#define ALIGNMENT 8 /* must be 2^N */
799#define ALIGNMENT_SHIFT 3
800
801/* Return the number of bytes in size class I, as a uint. */
802#define INDEX2SIZE(I) (((uint)(I) + 1) << ALIGNMENT_SHIFT)
803
804/*
805 * Max size threshold below which malloc requests are considered to be
806 * small enough in order to use preallocated memory pools. You can tune
807 * this value according to your application behaviour and memory needs.
808 *
809 * Note: a size threshold of 512 guarantees that newly created dictionaries
810 * will be allocated from preallocated memory pools on 64-bit.
811 *
812 * The following invariants must hold:
813 * 1) ALIGNMENT <= SMALL_REQUEST_THRESHOLD <= 512
814 * 2) SMALL_REQUEST_THRESHOLD is evenly divisible by ALIGNMENT
815 *
816 * Although not required, for better performance and space efficiency,
817 * it is recommended that SMALL_REQUEST_THRESHOLD is set to a power of 2.
818 */
819#define SMALL_REQUEST_THRESHOLD 512
820#define NB_SMALL_SIZE_CLASSES (SMALL_REQUEST_THRESHOLD / ALIGNMENT)
821
822/*
823 * The system's VMM page size can be obtained on most unices with a
824 * getpagesize() call or deduced from various header files. To make
825 * things simpler, we assume that it is 4K, which is OK for most systems.
826 * It is probably better if this is the native page size, but it doesn't
827 * have to be. In theory, if SYSTEM_PAGE_SIZE is larger than the native page
828 * size, then `POOL_ADDR(p)->arenaindex' could rarely cause a segmentation
829 * violation fault. 4K is apparently OK for all the platforms that python
830 * currently targets.
831 */
832#define SYSTEM_PAGE_SIZE (4 * 1024)
833#define SYSTEM_PAGE_SIZE_MASK (SYSTEM_PAGE_SIZE - 1)
834
835/*
836 * Maximum amount of memory managed by the allocator for small requests.
837 */
838#ifdef WITH_MEMORY_LIMITS
839#ifndef SMALL_MEMORY_LIMIT
840#define SMALL_MEMORY_LIMIT (64 * 1024 * 1024) /* 64 MB -- more? */
841#endif
842#endif
843
844/*
845 * The allocator sub-allocates <Big> blocks of memory (called arenas) aligned
846 * on a page boundary. This is a reserved virtual address space for the
847 * current process (obtained through a malloc()/mmap() call). In no way this
848 * means that the memory arenas will be used entirely. A malloc(<Big>) is
849 * usually an address range reservation for <Big> bytes, unless all pages within
850 * this space are referenced subsequently. So malloc'ing big blocks and not
851 * using them does not mean "wasting memory". It's an addressable range
852 * wastage...
853 *
854 * Arenas are allocated with mmap() on systems supporting anonymous memory
855 * mappings to reduce heap fragmentation.
856 */
857#define ARENA_SIZE (256 << 10) /* 256KB */
858
859#ifdef WITH_MEMORY_LIMITS
860#define MAX_ARENAS (SMALL_MEMORY_LIMIT / ARENA_SIZE)
861#endif
862
863/*
864 * Size of the pools used for small blocks. Should be a power of 2,
865 * between 1K and SYSTEM_PAGE_SIZE, that is: 1k, 2k, 4k.
866 */
867#define POOL_SIZE SYSTEM_PAGE_SIZE /* must be 2^N */
868#define POOL_SIZE_MASK SYSTEM_PAGE_SIZE_MASK
869
870/*
871 * -- End of tunable settings section --
872 */
873
874/*==========================================================================*/
875
Victor Stinner9e87e772017-11-24 12:09:24 +0100876/* When you say memory, my mind reasons in terms of (pointers to) blocks */
877typedef uint8_t block;
878
879/* Pool for small blocks. */
880struct pool_header {
881 union { block *_padding;
882 uint count; } ref; /* number of allocated blocks */
883 block *freeblock; /* pool's free list head */
884 struct pool_header *nextpool; /* next pool of this size class */
885 struct pool_header *prevpool; /* previous pool "" */
886 uint arenaindex; /* index into arenas of base adr */
887 uint szidx; /* block size class index */
888 uint nextoffset; /* bytes to virgin block */
889 uint maxnextoffset; /* largest valid nextoffset */
890};
891
892typedef struct pool_header *poolp;
893
894/* Record keeping for arenas. */
895struct arena_object {
896 /* The address of the arena, as returned by malloc. Note that 0
897 * will never be returned by a successful malloc, and is used
898 * here to mark an arena_object that doesn't correspond to an
899 * allocated arena.
900 */
901 uintptr_t address;
902
903 /* Pool-aligned pointer to the next pool to be carved off. */
904 block* pool_address;
905
906 /* The number of available pools in the arena: free pools + never-
907 * allocated pools.
908 */
909 uint nfreepools;
910
911 /* The total number of pools in the arena, whether or not available. */
912 uint ntotalpools;
913
914 /* Singly-linked list of available pools. */
915 struct pool_header* freepools;
916
917 /* Whenever this arena_object is not associated with an allocated
918 * arena, the nextarena member is used to link all unassociated
919 * arena_objects in the singly-linked `unused_arena_objects` list.
920 * The prevarena member is unused in this case.
921 *
922 * When this arena_object is associated with an allocated arena
923 * with at least one available pool, both members are used in the
924 * doubly-linked `usable_arenas` list, which is maintained in
925 * increasing order of `nfreepools` values.
926 *
927 * Else this arena_object is associated with an allocated arena
928 * all of whose pools are in use. `nextarena` and `prevarena`
929 * are both meaningless in this case.
930 */
931 struct arena_object* nextarena;
932 struct arena_object* prevarena;
933};
934
935#define POOL_OVERHEAD _Py_SIZE_ROUND_UP(sizeof(struct pool_header), ALIGNMENT)
936
937#define DUMMY_SIZE_IDX 0xffff /* size class of newly cached pools */
938
939/* Round pointer P down to the closest pool-aligned address <= P, as a poolp */
940#define POOL_ADDR(P) ((poolp)_Py_ALIGN_DOWN((P), POOL_SIZE))
941
942/* Return total number of blocks in pool of size index I, as a uint. */
943#define NUMBLOCKS(I) ((uint)(POOL_SIZE - POOL_OVERHEAD) / INDEX2SIZE(I))
944
945/*==========================================================================*/
946
947/*
Victor Stinner9e87e772017-11-24 12:09:24 +0100948 * Pool table -- headed, circular, doubly-linked lists of partially used pools.
949
950This is involved. For an index i, usedpools[i+i] is the header for a list of
951all partially used pools holding small blocks with "size class idx" i. So
952usedpools[0] corresponds to blocks of size 8, usedpools[2] to blocks of size
95316, and so on: index 2*i <-> blocks of size (i+1)<<ALIGNMENT_SHIFT.
954
955Pools are carved off an arena's highwater mark (an arena_object's pool_address
956member) as needed. Once carved off, a pool is in one of three states forever
957after:
958
959used == partially used, neither empty nor full
960 At least one block in the pool is currently allocated, and at least one
961 block in the pool is not currently allocated (note this implies a pool
962 has room for at least two blocks).
963 This is a pool's initial state, as a pool is created only when malloc
964 needs space.
965 The pool holds blocks of a fixed size, and is in the circular list headed
966 at usedpools[i] (see above). It's linked to the other used pools of the
967 same size class via the pool_header's nextpool and prevpool members.
968 If all but one block is currently allocated, a malloc can cause a
969 transition to the full state. If all but one block is not currently
970 allocated, a free can cause a transition to the empty state.
971
972full == all the pool's blocks are currently allocated
973 On transition to full, a pool is unlinked from its usedpools[] list.
974 It's not linked to from anything then anymore, and its nextpool and
975 prevpool members are meaningless until it transitions back to used.
976 A free of a block in a full pool puts the pool back in the used state.
977 Then it's linked in at the front of the appropriate usedpools[] list, so
978 that the next allocation for its size class will reuse the freed block.
979
980empty == all the pool's blocks are currently available for allocation
981 On transition to empty, a pool is unlinked from its usedpools[] list,
982 and linked to the front of its arena_object's singly-linked freepools list,
983 via its nextpool member. The prevpool member has no meaning in this case.
984 Empty pools have no inherent size class: the next time a malloc finds
985 an empty list in usedpools[], it takes the first pool off of freepools.
986 If the size class needed happens to be the same as the size class the pool
987 last had, some pool initialization can be skipped.
988
989
990Block Management
991
992Blocks within pools are again carved out as needed. pool->freeblock points to
993the start of a singly-linked list of free blocks within the pool. When a
994block is freed, it's inserted at the front of its pool's freeblock list. Note
995that the available blocks in a pool are *not* linked all together when a pool
996is initialized. Instead only "the first two" (lowest addresses) blocks are
997set up, returning the first such block, and setting pool->freeblock to a
998one-block list holding the second such block. This is consistent with that
999pymalloc strives at all levels (arena, pool, and block) never to touch a piece
1000of memory until it's actually needed.
1001
1002So long as a pool is in the used state, we're certain there *is* a block
1003available for allocating, and pool->freeblock is not NULL. If pool->freeblock
1004points to the end of the free list before we've carved the entire pool into
1005blocks, that means we simply haven't yet gotten to one of the higher-address
1006blocks. The offset from the pool_header to the start of "the next" virgin
1007block is stored in the pool_header nextoffset member, and the largest value
1008of nextoffset that makes sense is stored in the maxnextoffset member when a
1009pool is initialized. All the blocks in a pool have been passed out at least
1010once when and only when nextoffset > maxnextoffset.
1011
1012
1013Major obscurity: While the usedpools vector is declared to have poolp
1014entries, it doesn't really. It really contains two pointers per (conceptual)
1015poolp entry, the nextpool and prevpool members of a pool_header. The
1016excruciating initialization code below fools C so that
1017
1018 usedpool[i+i]
1019
1020"acts like" a genuine poolp, but only so long as you only reference its
1021nextpool and prevpool members. The "- 2*sizeof(block *)" gibberish is
1022compensating for that a pool_header's nextpool and prevpool members
1023immediately follow a pool_header's first two members:
1024
1025 union { block *_padding;
1026 uint count; } ref;
1027 block *freeblock;
1028
1029each of which consume sizeof(block *) bytes. So what usedpools[i+i] really
1030contains is a fudged-up pointer p such that *if* C believes it's a poolp
1031pointer, then p->nextpool and p->prevpool are both p (meaning that the headed
1032circular list is empty).
1033
1034It's unclear why the usedpools setup is so convoluted. It could be to
1035minimize the amount of cache required to hold this heavily-referenced table
1036(which only *needs* the two interpool pointer members of a pool_header). OTOH,
1037referencing code has to remember to "double the index" and doing so isn't
1038free, usedpools[0] isn't a strictly legal pointer, and we're crucially relying
1039on that C doesn't insert any padding anywhere in a pool_header at or before
1040the prevpool member.
1041**************************************************************************** */
1042
1043#define PTA(x) ((poolp )((uint8_t *)&(usedpools[2*(x)]) - 2*sizeof(block *)))
1044#define PT(x) PTA(x), PTA(x)
1045
1046static poolp usedpools[2 * ((NB_SMALL_SIZE_CLASSES + 7) / 8) * 8] = {
1047 PT(0), PT(1), PT(2), PT(3), PT(4), PT(5), PT(6), PT(7)
1048#if NB_SMALL_SIZE_CLASSES > 8
1049 , PT(8), PT(9), PT(10), PT(11), PT(12), PT(13), PT(14), PT(15)
1050#if NB_SMALL_SIZE_CLASSES > 16
1051 , PT(16), PT(17), PT(18), PT(19), PT(20), PT(21), PT(22), PT(23)
1052#if NB_SMALL_SIZE_CLASSES > 24
1053 , PT(24), PT(25), PT(26), PT(27), PT(28), PT(29), PT(30), PT(31)
1054#if NB_SMALL_SIZE_CLASSES > 32
1055 , PT(32), PT(33), PT(34), PT(35), PT(36), PT(37), PT(38), PT(39)
1056#if NB_SMALL_SIZE_CLASSES > 40
1057 , PT(40), PT(41), PT(42), PT(43), PT(44), PT(45), PT(46), PT(47)
1058#if NB_SMALL_SIZE_CLASSES > 48
1059 , PT(48), PT(49), PT(50), PT(51), PT(52), PT(53), PT(54), PT(55)
1060#if NB_SMALL_SIZE_CLASSES > 56
1061 , PT(56), PT(57), PT(58), PT(59), PT(60), PT(61), PT(62), PT(63)
1062#if NB_SMALL_SIZE_CLASSES > 64
1063#error "NB_SMALL_SIZE_CLASSES should be less than 64"
1064#endif /* NB_SMALL_SIZE_CLASSES > 64 */
1065#endif /* NB_SMALL_SIZE_CLASSES > 56 */
1066#endif /* NB_SMALL_SIZE_CLASSES > 48 */
1067#endif /* NB_SMALL_SIZE_CLASSES > 40 */
1068#endif /* NB_SMALL_SIZE_CLASSES > 32 */
1069#endif /* NB_SMALL_SIZE_CLASSES > 24 */
1070#endif /* NB_SMALL_SIZE_CLASSES > 16 */
1071#endif /* NB_SMALL_SIZE_CLASSES > 8 */
1072};
1073
1074/*==========================================================================
1075Arena management.
1076
1077`arenas` is a vector of arena_objects. It contains maxarenas entries, some of
1078which may not be currently used (== they're arena_objects that aren't
1079currently associated with an allocated arena). Note that arenas proper are
1080separately malloc'ed.
1081
1082Prior to Python 2.5, arenas were never free()'ed. Starting with Python 2.5,
1083we do try to free() arenas, and use some mild heuristic strategies to increase
1084the likelihood that arenas eventually can be freed.
1085
1086unused_arena_objects
1087
1088 This is a singly-linked list of the arena_objects that are currently not
1089 being used (no arena is associated with them). Objects are taken off the
1090 head of the list in new_arena(), and are pushed on the head of the list in
1091 PyObject_Free() when the arena is empty. Key invariant: an arena_object
1092 is on this list if and only if its .address member is 0.
1093
1094usable_arenas
1095
1096 This is a doubly-linked list of the arena_objects associated with arenas
1097 that have pools available. These pools are either waiting to be reused,
1098 or have not been used before. The list is sorted to have the most-
1099 allocated arenas first (ascending order based on the nfreepools member).
1100 This means that the next allocation will come from a heavily used arena,
1101 which gives the nearly empty arenas a chance to be returned to the system.
1102 In my unscientific tests this dramatically improved the number of arenas
1103 that could be freed.
1104
1105Note that an arena_object associated with an arena all of whose pools are
1106currently in use isn't on either list.
1107*/
1108
1109/* Array of objects used to track chunks of memory (arenas). */
1110static struct arena_object* arenas = NULL;
1111/* Number of slots currently allocated in the `arenas` vector. */
1112static uint maxarenas = 0;
1113
1114/* The head of the singly-linked, NULL-terminated list of available
1115 * arena_objects.
1116 */
1117static struct arena_object* unused_arena_objects = NULL;
1118
1119/* The head of the doubly-linked, NULL-terminated at each end, list of
1120 * arena_objects associated with arenas that have pools available.
1121 */
1122static struct arena_object* usable_arenas = NULL;
1123
1124/* How many arena_objects do we initially allocate?
1125 * 16 = can allocate 16 arenas = 16 * ARENA_SIZE = 4MB before growing the
1126 * `arenas` vector.
1127 */
1128#define INITIAL_ARENA_OBJECTS 16
1129
1130/* Number of arenas allocated that haven't been free()'d. */
1131static size_t narenas_currently_allocated = 0;
1132
1133/* Total number of times malloc() called to allocate an arena. */
1134static size_t ntimes_arena_allocated = 0;
1135/* High water mark (max value ever seen) for narenas_currently_allocated. */
1136static size_t narenas_highwater = 0;
1137
1138static Py_ssize_t _Py_AllocatedBlocks = 0;
1139
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001140Py_ssize_t
1141_Py_GetAllocatedBlocks(void)
1142{
Victor Stinner9e87e772017-11-24 12:09:24 +01001143 return _Py_AllocatedBlocks;
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001144}
1145
1146
Thomas Woutersa9773292006-04-21 09:43:23 +00001147/* Allocate a new arena. If we run out of memory, return NULL. Else
1148 * allocate a new arena, and return the address of an arena_object
1149 * describing the new arena. It's expected that the caller will set
1150 * `usable_arenas` to the return value.
1151 */
1152static struct arena_object*
Tim Petersd97a1c02002-03-30 06:09:22 +00001153new_arena(void)
1154{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001155 struct arena_object* arenaobj;
1156 uint excess; /* number of bytes above pool alignment */
Victor Stinnerba108822012-03-10 00:21:44 +01001157 void *address;
Victor Stinner34be8072016-03-14 12:04:26 +01001158 static int debug_stats = -1;
Tim Petersd97a1c02002-03-30 06:09:22 +00001159
Victor Stinner34be8072016-03-14 12:04:26 +01001160 if (debug_stats == -1) {
Serhiy Storchaka4ae06c52017-12-12 13:55:04 +02001161 const char *opt = Py_GETENV("PYTHONMALLOCSTATS");
Victor Stinner34be8072016-03-14 12:04:26 +01001162 debug_stats = (opt != NULL && *opt != '\0');
1163 }
1164 if (debug_stats)
David Malcolm49526f42012-06-22 14:55:41 -04001165 _PyObject_DebugMallocStats(stderr);
Victor Stinner34be8072016-03-14 12:04:26 +01001166
Victor Stinner9e87e772017-11-24 12:09:24 +01001167 if (unused_arena_objects == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001168 uint i;
1169 uint numarenas;
1170 size_t nbytes;
Tim Peters0e871182002-04-13 08:29:14 +00001171
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001172 /* Double the number of arena objects on each allocation.
1173 * Note that it's possible for `numarenas` to overflow.
1174 */
Victor Stinner9e87e772017-11-24 12:09:24 +01001175 numarenas = maxarenas ? maxarenas << 1 : INITIAL_ARENA_OBJECTS;
1176 if (numarenas <= maxarenas)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001177 return NULL; /* overflow */
Martin v. Löwis5aca8822008-09-11 06:55:48 +00001178#if SIZEOF_SIZE_T <= SIZEOF_INT
Victor Stinner9e87e772017-11-24 12:09:24 +01001179 if (numarenas > SIZE_MAX / sizeof(*arenas))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001180 return NULL; /* overflow */
Martin v. Löwis5aca8822008-09-11 06:55:48 +00001181#endif
Victor Stinner9e87e772017-11-24 12:09:24 +01001182 nbytes = numarenas * sizeof(*arenas);
1183 arenaobj = (struct arena_object *)PyMem_RawRealloc(arenas, nbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001184 if (arenaobj == NULL)
1185 return NULL;
Victor Stinner9e87e772017-11-24 12:09:24 +01001186 arenas = arenaobj;
Thomas Woutersa9773292006-04-21 09:43:23 +00001187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 /* We might need to fix pointers that were copied. However,
1189 * new_arena only gets called when all the pages in the
1190 * previous arenas are full. Thus, there are *no* pointers
1191 * into the old array. Thus, we don't have to worry about
1192 * invalid pointers. Just to be sure, some asserts:
1193 */
Victor Stinner9e87e772017-11-24 12:09:24 +01001194 assert(usable_arenas == NULL);
1195 assert(unused_arena_objects == NULL);
Thomas Woutersa9773292006-04-21 09:43:23 +00001196
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001197 /* Put the new arenas on the unused_arena_objects list. */
Victor Stinner9e87e772017-11-24 12:09:24 +01001198 for (i = maxarenas; i < numarenas; ++i) {
1199 arenas[i].address = 0; /* mark as unassociated */
1200 arenas[i].nextarena = i < numarenas - 1 ?
1201 &arenas[i+1] : NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001202 }
Thomas Woutersa9773292006-04-21 09:43:23 +00001203
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 /* Update globals. */
Victor Stinner9e87e772017-11-24 12:09:24 +01001205 unused_arena_objects = &arenas[maxarenas];
1206 maxarenas = numarenas;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001207 }
Tim Petersd97a1c02002-03-30 06:09:22 +00001208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001209 /* Take the next available arena object off the head of the list. */
Victor Stinner9e87e772017-11-24 12:09:24 +01001210 assert(unused_arena_objects != NULL);
1211 arenaobj = unused_arena_objects;
1212 unused_arena_objects = arenaobj->nextarena;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 assert(arenaobj->address == 0);
Victor Stinner9e87e772017-11-24 12:09:24 +01001214 address = _PyObject_Arena.alloc(_PyObject_Arena.ctx, ARENA_SIZE);
Victor Stinner0507bf52013-07-07 02:05:46 +02001215 if (address == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001216 /* The allocation failed: return NULL after putting the
1217 * arenaobj back.
1218 */
Victor Stinner9e87e772017-11-24 12:09:24 +01001219 arenaobj->nextarena = unused_arena_objects;
1220 unused_arena_objects = arenaobj;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001221 return NULL;
1222 }
Benjamin Peterson5d4b09c2016-09-18 19:24:52 -07001223 arenaobj->address = (uintptr_t)address;
Tim Petersd97a1c02002-03-30 06:09:22 +00001224
Victor Stinner9e87e772017-11-24 12:09:24 +01001225 ++narenas_currently_allocated;
1226 ++ntimes_arena_allocated;
1227 if (narenas_currently_allocated > narenas_highwater)
1228 narenas_highwater = narenas_currently_allocated;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001229 arenaobj->freepools = NULL;
1230 /* pool_address <- first pool-aligned address in the arena
1231 nfreepools <- number of whole pools that fit after alignment */
Victor Stinner9e87e772017-11-24 12:09:24 +01001232 arenaobj->pool_address = (block*)arenaobj->address;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001233 arenaobj->nfreepools = ARENA_SIZE / POOL_SIZE;
1234 assert(POOL_SIZE * arenaobj->nfreepools == ARENA_SIZE);
1235 excess = (uint)(arenaobj->address & POOL_SIZE_MASK);
1236 if (excess != 0) {
1237 --arenaobj->nfreepools;
1238 arenaobj->pool_address += POOL_SIZE - excess;
1239 }
1240 arenaobj->ntotalpools = arenaobj->nfreepools;
Thomas Woutersa9773292006-04-21 09:43:23 +00001241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001242 return arenaobj;
Tim Petersd97a1c02002-03-30 06:09:22 +00001243}
1244
Victor Stinner9ed83c42017-10-31 12:18:10 -07001245
Thomas Woutersa9773292006-04-21 09:43:23 +00001246/*
Benjamin Peterson3924f932016-09-18 19:12:48 -07001247address_in_range(P, POOL)
Thomas Woutersa9773292006-04-21 09:43:23 +00001248
1249Return true if and only if P is an address that was allocated by pymalloc.
1250POOL must be the pool address associated with P, i.e., POOL = POOL_ADDR(P)
1251(the caller is asked to compute this because the macro expands POOL more than
1252once, and for efficiency it's best for the caller to assign POOL_ADDR(P) to a
Benjamin Peterson3924f932016-09-18 19:12:48 -07001253variable and pass the latter to the macro; because address_in_range is
Thomas Woutersa9773292006-04-21 09:43:23 +00001254called on every alloc/realloc/free, micro-efficiency is important here).
1255
1256Tricky: Let B be the arena base address associated with the pool, B =
1257arenas[(POOL)->arenaindex].address. Then P belongs to the arena if and only if
1258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001259 B <= P < B + ARENA_SIZE
Thomas Woutersa9773292006-04-21 09:43:23 +00001260
1261Subtracting B throughout, this is true iff
1262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 0 <= P-B < ARENA_SIZE
Thomas Woutersa9773292006-04-21 09:43:23 +00001264
1265By using unsigned arithmetic, the "0 <=" half of the test can be skipped.
1266
1267Obscure: A PyMem "free memory" function can call the pymalloc free or realloc
1268before the first arena has been allocated. `arenas` is still NULL in that
1269case. We're relying on that maxarenas is also 0 in that case, so that
1270(POOL)->arenaindex < maxarenas must be false, saving us from trying to index
1271into a NULL arenas.
1272
1273Details: given P and POOL, the arena_object corresponding to P is AO =
1274arenas[(POOL)->arenaindex]. Suppose obmalloc controls P. Then (barring wild
1275stores, etc), POOL is the correct address of P's pool, AO.address is the
1276correct base address of the pool's arena, and P must be within ARENA_SIZE of
1277AO.address. In addition, AO.address is not 0 (no arena can start at address 0
Benjamin Peterson3924f932016-09-18 19:12:48 -07001278(NULL)). Therefore address_in_range correctly reports that obmalloc
Thomas Woutersa9773292006-04-21 09:43:23 +00001279controls P.
1280
1281Now suppose obmalloc does not control P (e.g., P was obtained via a direct
1282call to the system malloc() or realloc()). (POOL)->arenaindex may be anything
1283in this case -- it may even be uninitialized trash. If the trash arenaindex
1284is >= maxarenas, the macro correctly concludes at once that obmalloc doesn't
1285control P.
1286
1287Else arenaindex is < maxarena, and AO is read up. If AO corresponds to an
1288allocated arena, obmalloc controls all the memory in slice AO.address :
1289AO.address+ARENA_SIZE. By case assumption, P is not controlled by obmalloc,
1290so P doesn't lie in that slice, so the macro correctly reports that P is not
1291controlled by obmalloc.
1292
1293Finally, if P is not controlled by obmalloc and AO corresponds to an unused
1294arena_object (one not currently associated with an allocated arena),
1295AO.address is 0, and the second test in the macro reduces to:
1296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001297 P < ARENA_SIZE
Thomas Woutersa9773292006-04-21 09:43:23 +00001298
1299If P >= ARENA_SIZE (extremely likely), the macro again correctly concludes
1300that P is not controlled by obmalloc. However, if P < ARENA_SIZE, this part
1301of the test still passes, and the third clause (AO.address != 0) is necessary
1302to get the correct result: AO.address is 0 in this case, so the macro
1303correctly reports that P is not controlled by obmalloc (despite that P lies in
1304slice AO.address : AO.address + ARENA_SIZE).
1305
1306Note: The third (AO.address != 0) clause was added in Python 2.5. Before
13072.5, arenas were never free()'ed, and an arenaindex < maxarena always
1308corresponded to a currently-allocated arena, so the "P is not controlled by
1309obmalloc, AO corresponds to an unused arena_object, and P < ARENA_SIZE" case
1310was impossible.
1311
1312Note that the logic is excruciating, and reading up possibly uninitialized
1313memory when P is not controlled by obmalloc (to get at (POOL)->arenaindex)
1314creates problems for some memory debuggers. The overwhelming advantage is
1315that this test determines whether an arbitrary address is controlled by
1316obmalloc in a small constant time, independent of the number of arenas
1317obmalloc controls. Since this test is needed at every entry point, it's
1318extremely desirable that it be this fast.
1319*/
Thomas Woutersa9773292006-04-21 09:43:23 +00001320
Alexey Izbyshevfd3a91c2018-11-12 02:14:51 +03001321static bool _Py_NO_ADDRESS_SAFETY_ANALYSIS
1322 _Py_NO_SANITIZE_THREAD
1323 _Py_NO_SANITIZE_MEMORY
Benjamin Peterson3924f932016-09-18 19:12:48 -07001324address_in_range(void *p, poolp pool)
1325{
1326 // Since address_in_range may be reading from memory which was not allocated
1327 // by Python, it is important that pool->arenaindex is read only once, as
1328 // another thread may be concurrently modifying the value without holding
1329 // the GIL. The following dance forces the compiler to read pool->arenaindex
1330 // only once.
1331 uint arenaindex = *((volatile uint *)&pool->arenaindex);
Victor Stinner9e87e772017-11-24 12:09:24 +01001332 return arenaindex < maxarenas &&
1333 (uintptr_t)p - arenas[arenaindex].address < ARENA_SIZE &&
1334 arenas[arenaindex].address != 0;
Benjamin Peterson3924f932016-09-18 19:12:48 -07001335}
Tim Peters338e0102002-04-01 19:23:44 +00001336
Victor Stinner9ed83c42017-10-31 12:18:10 -07001337
Neil Schemenauera35c6882001-02-27 04:45:05 +00001338/*==========================================================================*/
1339
Victor Stinner9ed83c42017-10-31 12:18:10 -07001340/* pymalloc allocator
Neil Schemenauera35c6882001-02-27 04:45:05 +00001341
Victor Stinner9ed83c42017-10-31 12:18:10 -07001342 The basic blocks are ordered by decreasing execution frequency,
1343 which minimizes the number of jumps in the most common cases,
1344 improves branching prediction and instruction scheduling (small
1345 block allocations typically result in a couple of instructions).
1346 Unless the optimizer reorders everything, being too smart...
Neil Schemenauera35c6882001-02-27 04:45:05 +00001347
Victor Stinner9ed83c42017-10-31 12:18:10 -07001348 Return 1 if pymalloc allocated memory and wrote the pointer into *ptr_p.
1349
1350 Return 0 if pymalloc failed to allocate the memory block: on bigger
1351 requests, on error in the code below (as a last chance to serve the request)
1352 or when the max memory limit has been reached. */
1353static int
1354pymalloc_alloc(void *ctx, void **ptr_p, size_t nbytes)
Neil Schemenauera35c6882001-02-27 04:45:05 +00001355{
Victor Stinner9e87e772017-11-24 12:09:24 +01001356 block *bp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001357 poolp pool;
1358 poolp next;
1359 uint size;
Neil Schemenauera35c6882001-02-27 04:45:05 +00001360
Benjamin Peterson05159c42009-12-03 03:01:27 +00001361#ifdef WITH_VALGRIND
Victor Stinner9ed83c42017-10-31 12:18:10 -07001362 if (UNLIKELY(running_on_valgrind == -1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001363 running_on_valgrind = RUNNING_ON_VALGRIND;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001364 }
1365 if (UNLIKELY(running_on_valgrind)) {
1366 return 0;
1367 }
Benjamin Peterson05159c42009-12-03 03:01:27 +00001368#endif
1369
Victor Stinner9ed83c42017-10-31 12:18:10 -07001370 if (nbytes == 0) {
1371 return 0;
1372 }
1373 if (nbytes > SMALL_REQUEST_THRESHOLD) {
1374 return 0;
1375 }
T. Wouters06bb4872017-03-31 10:10:19 -07001376
Victor Stinner9ed83c42017-10-31 12:18:10 -07001377 /*
1378 * Most frequent paths first
1379 */
1380 size = (uint)(nbytes - 1) >> ALIGNMENT_SHIFT;
Victor Stinner9e87e772017-11-24 12:09:24 +01001381 pool = usedpools[size + size];
Victor Stinner9ed83c42017-10-31 12:18:10 -07001382 if (pool != pool->nextpool) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001383 /*
Victor Stinner9ed83c42017-10-31 12:18:10 -07001384 * There is a used pool for this size class.
1385 * Pick up the head block of its free list.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001386 */
Victor Stinner9ed83c42017-10-31 12:18:10 -07001387 ++pool->ref.count;
1388 bp = pool->freeblock;
1389 assert(bp != NULL);
Victor Stinner9e87e772017-11-24 12:09:24 +01001390 if ((pool->freeblock = *(block **)bp) != NULL) {
Victor Stinner9ed83c42017-10-31 12:18:10 -07001391 goto success;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001392 }
Thomas Woutersa9773292006-04-21 09:43:23 +00001393
Victor Stinner9ed83c42017-10-31 12:18:10 -07001394 /*
1395 * Reached the end of the free list, try to extend it.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001396 */
Victor Stinner9ed83c42017-10-31 12:18:10 -07001397 if (pool->nextoffset <= pool->maxnextoffset) {
1398 /* There is room for another block. */
Victor Stinner9e87e772017-11-24 12:09:24 +01001399 pool->freeblock = (block*)pool +
Victor Stinner9ed83c42017-10-31 12:18:10 -07001400 pool->nextoffset;
1401 pool->nextoffset += INDEX2SIZE(size);
Victor Stinner9e87e772017-11-24 12:09:24 +01001402 *(block **)(pool->freeblock) = NULL;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001403 goto success;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001404 }
Thomas Woutersa9773292006-04-21 09:43:23 +00001405
Victor Stinner9ed83c42017-10-31 12:18:10 -07001406 /* Pool is full, unlink from used pools. */
1407 next = pool->nextpool;
1408 pool = pool->prevpool;
1409 next->prevpool = pool;
1410 pool->nextpool = next;
1411 goto success;
1412 }
Thomas Woutersa9773292006-04-21 09:43:23 +00001413
Victor Stinner9ed83c42017-10-31 12:18:10 -07001414 /* There isn't a pool of the right size class immediately
1415 * available: use a free pool.
1416 */
Victor Stinner9e87e772017-11-24 12:09:24 +01001417 if (usable_arenas == NULL) {
Victor Stinner9ed83c42017-10-31 12:18:10 -07001418 /* No arena has a free pool: allocate a new arena. */
1419#ifdef WITH_MEMORY_LIMITS
Victor Stinner9e87e772017-11-24 12:09:24 +01001420 if (narenas_currently_allocated >= MAX_ARENAS) {
Victor Stinner9ed83c42017-10-31 12:18:10 -07001421 goto failed;
1422 }
1423#endif
Victor Stinner9e87e772017-11-24 12:09:24 +01001424 usable_arenas = new_arena();
1425 if (usable_arenas == NULL) {
Victor Stinner9ed83c42017-10-31 12:18:10 -07001426 goto failed;
1427 }
Victor Stinner9e87e772017-11-24 12:09:24 +01001428 usable_arenas->nextarena =
1429 usable_arenas->prevarena = NULL;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001430 }
Victor Stinner9e87e772017-11-24 12:09:24 +01001431 assert(usable_arenas->address != 0);
Victor Stinner9ed83c42017-10-31 12:18:10 -07001432
1433 /* Try to get a cached free pool. */
Victor Stinner9e87e772017-11-24 12:09:24 +01001434 pool = usable_arenas->freepools;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001435 if (pool != NULL) {
1436 /* Unlink from cached pools. */
Victor Stinner9e87e772017-11-24 12:09:24 +01001437 usable_arenas->freepools = pool->nextpool;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001438
1439 /* This arena already had the smallest nfreepools
1440 * value, so decreasing nfreepools doesn't change
1441 * that, and we don't need to rearrange the
1442 * usable_arenas list. However, if the arena has
1443 * become wholly allocated, we need to remove its
1444 * arena_object from usable_arenas.
1445 */
Victor Stinner9e87e772017-11-24 12:09:24 +01001446 --usable_arenas->nfreepools;
1447 if (usable_arenas->nfreepools == 0) {
Victor Stinner9ed83c42017-10-31 12:18:10 -07001448 /* Wholly allocated: remove. */
Victor Stinner9e87e772017-11-24 12:09:24 +01001449 assert(usable_arenas->freepools == NULL);
1450 assert(usable_arenas->nextarena == NULL ||
1451 usable_arenas->nextarena->prevarena ==
1452 usable_arenas);
Victor Stinner9ed83c42017-10-31 12:18:10 -07001453
Victor Stinner9e87e772017-11-24 12:09:24 +01001454 usable_arenas = usable_arenas->nextarena;
1455 if (usable_arenas != NULL) {
1456 usable_arenas->prevarena = NULL;
1457 assert(usable_arenas->address != 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001458 }
1459 }
Victor Stinner9ed83c42017-10-31 12:18:10 -07001460 else {
1461 /* nfreepools > 0: it must be that freepools
1462 * isn't NULL, or that we haven't yet carved
1463 * off all the arena's pools for the first
1464 * time.
1465 */
Victor Stinner9e87e772017-11-24 12:09:24 +01001466 assert(usable_arenas->freepools != NULL ||
1467 usable_arenas->pool_address <=
1468 (block*)usable_arenas->address +
Victor Stinner9ed83c42017-10-31 12:18:10 -07001469 ARENA_SIZE - POOL_SIZE);
1470 }
Thomas Woutersa9773292006-04-21 09:43:23 +00001471
Victor Stinner9ed83c42017-10-31 12:18:10 -07001472 init_pool:
1473 /* Frontlink to used pools. */
Victor Stinner9e87e772017-11-24 12:09:24 +01001474 next = usedpools[size + size]; /* == prev */
Victor Stinner9ed83c42017-10-31 12:18:10 -07001475 pool->nextpool = next;
1476 pool->prevpool = next;
1477 next->nextpool = pool;
1478 next->prevpool = pool;
1479 pool->ref.count = 1;
1480 if (pool->szidx == size) {
1481 /* Luckily, this pool last contained blocks
1482 * of the same size class, so its header
1483 * and free list are already initialized.
1484 */
1485 bp = pool->freeblock;
1486 assert(bp != NULL);
Victor Stinner9e87e772017-11-24 12:09:24 +01001487 pool->freeblock = *(block **)bp;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001488 goto success;
1489 }
1490 /*
1491 * Initialize the pool header, set up the free list to
1492 * contain just the second block, and return the first
1493 * block.
1494 */
1495 pool->szidx = size;
1496 size = INDEX2SIZE(size);
Victor Stinner9e87e772017-11-24 12:09:24 +01001497 bp = (block *)pool + POOL_OVERHEAD;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001498 pool->nextoffset = POOL_OVERHEAD + (size << 1);
1499 pool->maxnextoffset = POOL_SIZE - size;
1500 pool->freeblock = bp + size;
Victor Stinner9e87e772017-11-24 12:09:24 +01001501 *(block **)(pool->freeblock) = NULL;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001502 goto success;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001503 }
Neil Schemenauera35c6882001-02-27 04:45:05 +00001504
Victor Stinner9ed83c42017-10-31 12:18:10 -07001505 /* Carve off a new pool. */
Victor Stinner9e87e772017-11-24 12:09:24 +01001506 assert(usable_arenas->nfreepools > 0);
1507 assert(usable_arenas->freepools == NULL);
1508 pool = (poolp)usable_arenas->pool_address;
1509 assert((block*)pool <= (block*)usable_arenas->address +
Victor Stinner9ed83c42017-10-31 12:18:10 -07001510 ARENA_SIZE - POOL_SIZE);
Victor Stinner9e87e772017-11-24 12:09:24 +01001511 pool->arenaindex = (uint)(usable_arenas - arenas);
1512 assert(&arenas[pool->arenaindex] == usable_arenas);
Victor Stinner9ed83c42017-10-31 12:18:10 -07001513 pool->szidx = DUMMY_SIZE_IDX;
Victor Stinner9e87e772017-11-24 12:09:24 +01001514 usable_arenas->pool_address += POOL_SIZE;
1515 --usable_arenas->nfreepools;
Neil Schemenauera35c6882001-02-27 04:45:05 +00001516
Victor Stinner9e87e772017-11-24 12:09:24 +01001517 if (usable_arenas->nfreepools == 0) {
1518 assert(usable_arenas->nextarena == NULL ||
1519 usable_arenas->nextarena->prevarena ==
1520 usable_arenas);
Victor Stinner9ed83c42017-10-31 12:18:10 -07001521 /* Unlink the arena: it is completely allocated. */
Victor Stinner9e87e772017-11-24 12:09:24 +01001522 usable_arenas = usable_arenas->nextarena;
1523 if (usable_arenas != NULL) {
1524 usable_arenas->prevarena = NULL;
1525 assert(usable_arenas->address != 0);
Victor Stinner9ed83c42017-10-31 12:18:10 -07001526 }
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001527 }
Victor Stinner9ed83c42017-10-31 12:18:10 -07001528
1529 goto init_pool;
1530
1531success:
Victor Stinner9ed83c42017-10-31 12:18:10 -07001532 assert(bp != NULL);
1533 *ptr_p = (void *)bp;
1534 return 1;
1535
1536failed:
Victor Stinner9ed83c42017-10-31 12:18:10 -07001537 return 0;
Neil Schemenauera35c6882001-02-27 04:45:05 +00001538}
1539
Victor Stinner9ed83c42017-10-31 12:18:10 -07001540
Victor Stinnerdb067af2014-05-02 22:31:14 +02001541static void *
1542_PyObject_Malloc(void *ctx, size_t nbytes)
1543{
Victor Stinner9ed83c42017-10-31 12:18:10 -07001544 void* ptr;
1545 if (pymalloc_alloc(ctx, &ptr, nbytes)) {
Victor Stinner9e87e772017-11-24 12:09:24 +01001546 _Py_AllocatedBlocks++;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001547 return ptr;
1548 }
1549
1550 ptr = PyMem_RawMalloc(nbytes);
1551 if (ptr != NULL) {
Victor Stinner9e87e772017-11-24 12:09:24 +01001552 _Py_AllocatedBlocks++;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001553 }
1554 return ptr;
Victor Stinnerdb067af2014-05-02 22:31:14 +02001555}
1556
Victor Stinner9ed83c42017-10-31 12:18:10 -07001557
Victor Stinnerdb067af2014-05-02 22:31:14 +02001558static void *
1559_PyObject_Calloc(void *ctx, size_t nelem, size_t elsize)
1560{
Victor Stinner9ed83c42017-10-31 12:18:10 -07001561 void* ptr;
1562
1563 assert(elsize == 0 || nelem <= (size_t)PY_SSIZE_T_MAX / elsize);
1564 size_t nbytes = nelem * elsize;
1565
1566 if (pymalloc_alloc(ctx, &ptr, nbytes)) {
1567 memset(ptr, 0, nbytes);
Victor Stinner9e87e772017-11-24 12:09:24 +01001568 _Py_AllocatedBlocks++;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001569 return ptr;
1570 }
1571
1572 ptr = PyMem_RawCalloc(nelem, elsize);
1573 if (ptr != NULL) {
Victor Stinner9e87e772017-11-24 12:09:24 +01001574 _Py_AllocatedBlocks++;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001575 }
1576 return ptr;
Victor Stinnerdb067af2014-05-02 22:31:14 +02001577}
1578
Neil Schemenauera35c6882001-02-27 04:45:05 +00001579
Victor Stinner9ed83c42017-10-31 12:18:10 -07001580/* Free a memory block allocated by pymalloc_alloc().
1581 Return 1 if it was freed.
1582 Return 0 if the block was not allocated by pymalloc_alloc(). */
1583static int
1584pymalloc_free(void *ctx, void *p)
Neil Schemenauera35c6882001-02-27 04:45:05 +00001585{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001586 poolp pool;
Victor Stinner9e87e772017-11-24 12:09:24 +01001587 block *lastfree;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001588 poolp next, prev;
1589 uint size;
Neil Schemenauera35c6882001-02-27 04:45:05 +00001590
Victor Stinner9ed83c42017-10-31 12:18:10 -07001591 assert(p != NULL);
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001592
Benjamin Peterson05159c42009-12-03 03:01:27 +00001593#ifdef WITH_VALGRIND
Victor Stinner9ed83c42017-10-31 12:18:10 -07001594 if (UNLIKELY(running_on_valgrind > 0)) {
1595 return 0;
1596 }
Benjamin Peterson05159c42009-12-03 03:01:27 +00001597#endif
1598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001599 pool = POOL_ADDR(p);
Victor Stinner9ed83c42017-10-31 12:18:10 -07001600 if (!address_in_range(p, pool)) {
1601 return 0;
1602 }
1603 /* We allocated this address. */
Thomas Woutersa9773292006-04-21 09:43:23 +00001604
Victor Stinner9ed83c42017-10-31 12:18:10 -07001605 /* Link p to the start of the pool's freeblock list. Since
1606 * the pool had at least the p block outstanding, the pool
1607 * wasn't empty (so it's already in a usedpools[] list, or
1608 * was full and is in no list -- it's not in the freeblocks
1609 * list in any case).
1610 */
1611 assert(pool->ref.count > 0); /* else it was empty */
Victor Stinner9e87e772017-11-24 12:09:24 +01001612 *(block **)p = lastfree = pool->freeblock;
1613 pool->freeblock = (block *)p;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001614 if (!lastfree) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001615 /* Pool was full, so doesn't currently live in any list:
1616 * link it to the front of the appropriate usedpools[] list.
1617 * This mimics LRU pool usage for new allocations and
1618 * targets optimal filling when several pools contain
1619 * blocks of the same size class.
1620 */
1621 --pool->ref.count;
1622 assert(pool->ref.count > 0); /* else the pool is empty */
1623 size = pool->szidx;
Victor Stinner9e87e772017-11-24 12:09:24 +01001624 next = usedpools[size + size];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001625 prev = next->prevpool;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001626
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001627 /* insert pool before next: prev <-> pool <-> next */
1628 pool->nextpool = next;
1629 pool->prevpool = prev;
1630 next->prevpool = pool;
1631 prev->nextpool = pool;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001632 goto success;
1633 }
1634
1635 struct arena_object* ao;
1636 uint nf; /* ao->nfreepools */
1637
1638 /* freeblock wasn't NULL, so the pool wasn't full,
1639 * and the pool is in a usedpools[] list.
1640 */
1641 if (--pool->ref.count != 0) {
1642 /* pool isn't empty: leave it in usedpools */
1643 goto success;
1644 }
1645 /* Pool is now empty: unlink from usedpools, and
1646 * link to the front of freepools. This ensures that
1647 * previously freed pools will be allocated later
1648 * (being not referenced, they are perhaps paged out).
1649 */
1650 next = pool->nextpool;
1651 prev = pool->prevpool;
1652 next->prevpool = prev;
1653 prev->nextpool = next;
1654
1655 /* Link the pool to freepools. This is a singly-linked
1656 * list, and pool->prevpool isn't used there.
1657 */
Victor Stinner9e87e772017-11-24 12:09:24 +01001658 ao = &arenas[pool->arenaindex];
Victor Stinner9ed83c42017-10-31 12:18:10 -07001659 pool->nextpool = ao->freepools;
1660 ao->freepools = pool;
1661 nf = ++ao->nfreepools;
1662
1663 /* All the rest is arena management. We just freed
1664 * a pool, and there are 4 cases for arena mgmt:
1665 * 1. If all the pools are free, return the arena to
1666 * the system free().
1667 * 2. If this is the only free pool in the arena,
1668 * add the arena back to the `usable_arenas` list.
1669 * 3. If the "next" arena has a smaller count of free
1670 * pools, we have to "slide this arena right" to
1671 * restore that usable_arenas is sorted in order of
1672 * nfreepools.
1673 * 4. Else there's nothing more to do.
1674 */
1675 if (nf == ao->ntotalpools) {
1676 /* Case 1. First unlink ao from usable_arenas.
1677 */
1678 assert(ao->prevarena == NULL ||
1679 ao->prevarena->address != 0);
1680 assert(ao ->nextarena == NULL ||
1681 ao->nextarena->address != 0);
1682
1683 /* Fix the pointer in the prevarena, or the
1684 * usable_arenas pointer.
1685 */
1686 if (ao->prevarena == NULL) {
Victor Stinner9e87e772017-11-24 12:09:24 +01001687 usable_arenas = ao->nextarena;
1688 assert(usable_arenas == NULL ||
1689 usable_arenas->address != 0);
Victor Stinner9ed83c42017-10-31 12:18:10 -07001690 }
1691 else {
1692 assert(ao->prevarena->nextarena == ao);
1693 ao->prevarena->nextarena =
1694 ao->nextarena;
1695 }
1696 /* Fix the pointer in the nextarena. */
1697 if (ao->nextarena != NULL) {
1698 assert(ao->nextarena->prevarena == ao);
1699 ao->nextarena->prevarena =
1700 ao->prevarena;
1701 }
1702 /* Record that this arena_object slot is
1703 * available to be reused.
1704 */
Victor Stinner9e87e772017-11-24 12:09:24 +01001705 ao->nextarena = unused_arena_objects;
1706 unused_arena_objects = ao;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001707
1708 /* Free the entire arena. */
Victor Stinner9e87e772017-11-24 12:09:24 +01001709 _PyObject_Arena.free(_PyObject_Arena.ctx,
Victor Stinner9ed83c42017-10-31 12:18:10 -07001710 (void *)ao->address, ARENA_SIZE);
1711 ao->address = 0; /* mark unassociated */
Victor Stinner9e87e772017-11-24 12:09:24 +01001712 --narenas_currently_allocated;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001713
1714 goto success;
1715 }
1716
1717 if (nf == 1) {
1718 /* Case 2. Put ao at the head of
1719 * usable_arenas. Note that because
1720 * ao->nfreepools was 0 before, ao isn't
1721 * currently on the usable_arenas list.
1722 */
Victor Stinner9e87e772017-11-24 12:09:24 +01001723 ao->nextarena = usable_arenas;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001724 ao->prevarena = NULL;
Victor Stinner9e87e772017-11-24 12:09:24 +01001725 if (usable_arenas)
1726 usable_arenas->prevarena = ao;
1727 usable_arenas = ao;
1728 assert(usable_arenas->address != 0);
Victor Stinner9ed83c42017-10-31 12:18:10 -07001729
1730 goto success;
1731 }
1732
1733 /* If this arena is now out of order, we need to keep
1734 * the list sorted. The list is kept sorted so that
1735 * the "most full" arenas are used first, which allows
1736 * the nearly empty arenas to be completely freed. In
1737 * a few un-scientific tests, it seems like this
1738 * approach allowed a lot more memory to be freed.
1739 */
1740 if (ao->nextarena == NULL ||
1741 nf <= ao->nextarena->nfreepools) {
1742 /* Case 4. Nothing to do. */
1743 goto success;
1744 }
1745 /* Case 3: We have to move the arena towards the end
1746 * of the list, because it has more free pools than
1747 * the arena to its right.
1748 * First unlink ao from usable_arenas.
1749 */
1750 if (ao->prevarena != NULL) {
1751 /* ao isn't at the head of the list */
1752 assert(ao->prevarena->nextarena == ao);
1753 ao->prevarena->nextarena = ao->nextarena;
1754 }
1755 else {
1756 /* ao is at the head of the list */
Victor Stinner9e87e772017-11-24 12:09:24 +01001757 assert(usable_arenas == ao);
1758 usable_arenas = ao->nextarena;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001759 }
1760 ao->nextarena->prevarena = ao->prevarena;
1761
1762 /* Locate the new insertion point by iterating over
1763 * the list, using our nextarena pointer.
1764 */
1765 while (ao->nextarena != NULL && nf > ao->nextarena->nfreepools) {
1766 ao->prevarena = ao->nextarena;
1767 ao->nextarena = ao->nextarena->nextarena;
1768 }
1769
1770 /* Insert ao at this point. */
1771 assert(ao->nextarena == NULL || ao->prevarena == ao->nextarena->prevarena);
1772 assert(ao->prevarena->nextarena == ao->nextarena);
1773
1774 ao->prevarena->nextarena = ao;
1775 if (ao->nextarena != NULL) {
1776 ao->nextarena->prevarena = ao;
1777 }
1778
1779 /* Verify that the swaps worked. */
1780 assert(ao->nextarena == NULL || nf <= ao->nextarena->nfreepools);
1781 assert(ao->prevarena == NULL || nf > ao->prevarena->nfreepools);
1782 assert(ao->nextarena == NULL || ao->nextarena->prevarena == ao);
Victor Stinner9e87e772017-11-24 12:09:24 +01001783 assert((usable_arenas == ao && ao->prevarena == NULL)
Victor Stinner9ed83c42017-10-31 12:18:10 -07001784 || ao->prevarena->nextarena == ao);
1785
1786 goto success;
1787
1788success:
Victor Stinner9ed83c42017-10-31 12:18:10 -07001789 return 1;
1790}
1791
1792
1793static void
1794_PyObject_Free(void *ctx, void *p)
1795{
1796 /* PyObject_Free(NULL) has no effect */
1797 if (p == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001798 return;
1799 }
Neil Schemenauera35c6882001-02-27 04:45:05 +00001800
Victor Stinner9e87e772017-11-24 12:09:24 +01001801 _Py_AllocatedBlocks--;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001802 if (!pymalloc_free(ctx, p)) {
1803 /* pymalloc didn't allocate this address */
1804 PyMem_RawFree(p);
1805 }
Neil Schemenauera35c6882001-02-27 04:45:05 +00001806}
1807
Neil Schemenauera35c6882001-02-27 04:45:05 +00001808
Victor Stinner9ed83c42017-10-31 12:18:10 -07001809/* pymalloc realloc.
1810
1811 If nbytes==0, then as the Python docs promise, we do not treat this like
1812 free(p), and return a non-NULL result.
1813
1814 Return 1 if pymalloc reallocated memory and wrote the new pointer into
1815 newptr_p.
1816
1817 Return 0 if pymalloc didn't allocated p. */
1818static int
1819pymalloc_realloc(void *ctx, void **newptr_p, void *p, size_t nbytes)
Neil Schemenauera35c6882001-02-27 04:45:05 +00001820{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001821 void *bp;
1822 poolp pool;
1823 size_t size;
Neil Schemenauera35c6882001-02-27 04:45:05 +00001824
Victor Stinner9ed83c42017-10-31 12:18:10 -07001825 assert(p != NULL);
Georg Brandld492ad82008-07-23 16:13:07 +00001826
Benjamin Peterson05159c42009-12-03 03:01:27 +00001827#ifdef WITH_VALGRIND
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001828 /* Treat running_on_valgrind == -1 the same as 0 */
Victor Stinner9ed83c42017-10-31 12:18:10 -07001829 if (UNLIKELY(running_on_valgrind > 0)) {
1830 return 0;
1831 }
Benjamin Peterson05159c42009-12-03 03:01:27 +00001832#endif
1833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001834 pool = POOL_ADDR(p);
Victor Stinner9ed83c42017-10-31 12:18:10 -07001835 if (!address_in_range(p, pool)) {
1836 /* pymalloc is not managing this block.
1837
1838 If nbytes <= SMALL_REQUEST_THRESHOLD, it's tempting to try to take
1839 over this block. However, if we do, we need to copy the valid data
1840 from the C-managed block to one of our blocks, and there's no
1841 portable way to know how much of the memory space starting at p is
1842 valid.
1843
1844 As bug 1185883 pointed out the hard way, it's possible that the
1845 C-managed block is "at the end" of allocated VM space, so that a
1846 memory fault can occur if we try to copy nbytes bytes starting at p.
1847 Instead we punt: let C continue to manage this block. */
1848 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001849 }
Victor Stinner9ed83c42017-10-31 12:18:10 -07001850
1851 /* pymalloc is in charge of this block */
1852 size = INDEX2SIZE(pool->szidx);
1853 if (nbytes <= size) {
1854 /* The block is staying the same or shrinking.
1855
1856 If it's shrinking, there's a tradeoff: it costs cycles to copy the
1857 block to a smaller size class, but it wastes memory not to copy it.
1858
1859 The compromise here is to copy on shrink only if at least 25% of
1860 size can be shaved off. */
1861 if (4 * nbytes > 3 * size) {
1862 /* It's the same, or shrinking and new/old > 3/4. */
1863 *newptr_p = p;
1864 return 1;
1865 }
1866 size = nbytes;
1867 }
1868
1869 bp = _PyObject_Malloc(ctx, nbytes);
1870 if (bp != NULL) {
1871 memcpy(bp, p, size);
1872 _PyObject_Free(ctx, p);
1873 }
1874 *newptr_p = bp;
1875 return 1;
1876}
1877
1878
1879static void *
1880_PyObject_Realloc(void *ctx, void *ptr, size_t nbytes)
1881{
1882 void *ptr2;
1883
1884 if (ptr == NULL) {
1885 return _PyObject_Malloc(ctx, nbytes);
1886 }
1887
1888 if (pymalloc_realloc(ctx, &ptr2, ptr, nbytes)) {
1889 return ptr2;
1890 }
1891
1892 return PyMem_RawRealloc(ptr, nbytes);
Neil Schemenauera35c6882001-02-27 04:45:05 +00001893}
1894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001895#else /* ! WITH_PYMALLOC */
Tim Petersddea2082002-03-23 10:03:50 +00001896
1897/*==========================================================================*/
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00001898/* pymalloc not enabled: Redirect the entry points to malloc. These will
1899 * only be used by extensions that are compiled with pymalloc enabled. */
Tim Peters62c06ba2002-03-23 22:28:18 +00001900
Antoine Pitrou92840532012-12-17 23:05:59 +01001901Py_ssize_t
1902_Py_GetAllocatedBlocks(void)
1903{
1904 return 0;
1905}
1906
Tim Peters1221c0a2002-03-23 00:20:15 +00001907#endif /* WITH_PYMALLOC */
1908
Victor Stinner34be8072016-03-14 12:04:26 +01001909
Tim Petersddea2082002-03-23 10:03:50 +00001910/*==========================================================================*/
Tim Peters62c06ba2002-03-23 22:28:18 +00001911/* A x-platform debugging allocator. This doesn't manage memory directly,
1912 * it wraps a real allocator, adding extra debugging info to the memory blocks.
1913 */
Tim Petersddea2082002-03-23 10:03:50 +00001914
Tim Petersf6fb5012002-04-12 07:38:53 +00001915/* Special bytes broadcast into debug memory blocks at appropriate times.
1916 * Strings of these are unlikely to be valid addresses, floats, ints or
1917 * 7-bit ASCII.
1918 */
1919#undef CLEANBYTE
1920#undef DEADBYTE
1921#undef FORBIDDENBYTE
1922#define CLEANBYTE 0xCB /* clean (newly allocated) memory */
Tim Peters889f61d2002-07-10 19:29:49 +00001923#define DEADBYTE 0xDB /* dead (newly freed) memory */
Tim Petersf6fb5012002-04-12 07:38:53 +00001924#define FORBIDDENBYTE 0xFB /* untouchable bytes at each end of a block */
Tim Petersddea2082002-03-23 10:03:50 +00001925
Victor Stinner9e87e772017-11-24 12:09:24 +01001926static size_t serialno = 0; /* incremented on each debug {m,re}alloc */
1927
Tim Peterse0850172002-03-24 00:34:21 +00001928/* serialno is always incremented via calling this routine. The point is
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001929 * to supply a single place to set a breakpoint.
1930 */
Tim Peterse0850172002-03-24 00:34:21 +00001931static void
Neil Schemenauerbd02b142002-03-28 21:05:38 +00001932bumpserialno(void)
Tim Peterse0850172002-03-24 00:34:21 +00001933{
Victor Stinner9e87e772017-11-24 12:09:24 +01001934 ++serialno;
Tim Peterse0850172002-03-24 00:34:21 +00001935}
1936
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001937#define SST SIZEOF_SIZE_T
Tim Peterse0850172002-03-24 00:34:21 +00001938
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001939/* Read sizeof(size_t) bytes at p as a big-endian size_t. */
1940static size_t
1941read_size_t(const void *p)
Tim Petersddea2082002-03-23 10:03:50 +00001942{
Benjamin Peterson19517e42016-09-18 19:22:22 -07001943 const uint8_t *q = (const uint8_t *)p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001944 size_t result = *q++;
1945 int i;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001947 for (i = SST; --i > 0; ++q)
1948 result = (result << 8) | *q;
1949 return result;
Tim Petersddea2082002-03-23 10:03:50 +00001950}
1951
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001952/* Write n as a big-endian size_t, MSB at address p, LSB at
1953 * p + sizeof(size_t) - 1.
1954 */
Tim Petersddea2082002-03-23 10:03:50 +00001955static void
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001956write_size_t(void *p, size_t n)
Tim Petersddea2082002-03-23 10:03:50 +00001957{
Benjamin Peterson19517e42016-09-18 19:22:22 -07001958 uint8_t *q = (uint8_t *)p + SST - 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001959 int i;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001961 for (i = SST; --i >= 0; --q) {
Benjamin Peterson19517e42016-09-18 19:22:22 -07001962 *q = (uint8_t)(n & 0xff);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001963 n >>= 8;
1964 }
Tim Petersddea2082002-03-23 10:03:50 +00001965}
1966
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001967/* Let S = sizeof(size_t). The debug malloc asks for 4*S extra bytes and
1968 fills them with useful stuff, here calling the underlying malloc's result p:
Tim Petersddea2082002-03-23 10:03:50 +00001969
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001970p[0: S]
1971 Number of bytes originally asked for. This is a size_t, big-endian (easier
1972 to read in a memory dump).
Georg Brandl7cba5fd2013-09-25 09:04:23 +02001973p[S]
Tim Petersdf099f52013-09-19 21:06:37 -05001974 API ID. See PEP 445. This is a character, but seems undocumented.
1975p[S+1: 2*S]
Tim Petersf6fb5012002-04-12 07:38:53 +00001976 Copies of FORBIDDENBYTE. Used to catch under- writes and reads.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001977p[2*S: 2*S+n]
Tim Petersf6fb5012002-04-12 07:38:53 +00001978 The requested memory, filled with copies of CLEANBYTE.
Tim Petersddea2082002-03-23 10:03:50 +00001979 Used to catch reference to uninitialized memory.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001980 &p[2*S] is returned. Note that this is 8-byte aligned if pymalloc
Tim Petersddea2082002-03-23 10:03:50 +00001981 handled the request itself.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001982p[2*S+n: 2*S+n+S]
Tim Petersf6fb5012002-04-12 07:38:53 +00001983 Copies of FORBIDDENBYTE. Used to catch over- writes and reads.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001984p[2*S+n+S: 2*S+n+2*S]
Victor Stinner0507bf52013-07-07 02:05:46 +02001985 A serial number, incremented by 1 on each call to _PyMem_DebugMalloc
1986 and _PyMem_DebugRealloc.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001987 This is a big-endian size_t.
Tim Petersddea2082002-03-23 10:03:50 +00001988 If "bad memory" is detected later, the serial number gives an
1989 excellent way to set a breakpoint on the next run, to capture the
1990 instant at which this block was passed out.
1991*/
1992
Victor Stinner0507bf52013-07-07 02:05:46 +02001993static void *
Victor Stinnerc4aec362016-03-14 22:26:53 +01001994_PyMem_DebugRawAlloc(int use_calloc, void *ctx, size_t nbytes)
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00001995{
Victor Stinner0507bf52013-07-07 02:05:46 +02001996 debug_alloc_api_t *api = (debug_alloc_api_t *)ctx;
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02001997 uint8_t *p; /* base address of malloc'ed pad block */
Victor Stinner9ed83c42017-10-31 12:18:10 -07001998 uint8_t *data; /* p + 2*SST == pointer to data bytes */
1999 uint8_t *tail; /* data + nbytes == pointer to tail pad bytes */
2000 size_t total; /* 2 * SST + nbytes + 2 * SST */
2001
2002 if (nbytes > (size_t)PY_SSIZE_T_MAX - 4 * SST) {
2003 /* integer overflow: can't represent total as a Py_ssize_t */
2004 return NULL;
2005 }
2006 total = nbytes + 4 * SST;
2007
2008 /* Layout: [SSSS IFFF CCCC...CCCC FFFF NNNN]
2009 * ^--- p ^--- data ^--- tail
2010 S: nbytes stored as size_t
2011 I: API identifier (1 byte)
2012 F: Forbidden bytes (size_t - 1 bytes before, size_t bytes after)
2013 C: Clean bytes used later to store actual data
2014 N: Serial number stored as size_t */
2015
2016 if (use_calloc) {
2017 p = (uint8_t *)api->alloc.calloc(api->alloc.ctx, 1, total);
2018 }
2019 else {
2020 p = (uint8_t *)api->alloc.malloc(api->alloc.ctx, total);
2021 }
2022 if (p == NULL) {
2023 return NULL;
2024 }
2025 data = p + 2*SST;
Tim Petersddea2082002-03-23 10:03:50 +00002026
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002027 bumpserialno();
Tim Petersddea2082002-03-23 10:03:50 +00002028
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002029 /* at p, write size (SST bytes), id (1 byte), pad (SST-1 bytes) */
2030 write_size_t(p, nbytes);
Benjamin Peterson19517e42016-09-18 19:22:22 -07002031 p[SST] = (uint8_t)api->api_id;
Victor Stinner0507bf52013-07-07 02:05:46 +02002032 memset(p + SST + 1, FORBIDDENBYTE, SST-1);
Tim Petersddea2082002-03-23 10:03:50 +00002033
Victor Stinner9ed83c42017-10-31 12:18:10 -07002034 if (nbytes > 0 && !use_calloc) {
2035 memset(data, CLEANBYTE, nbytes);
2036 }
Tim Petersddea2082002-03-23 10:03:50 +00002037
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002038 /* at tail, write pad (SST bytes) and serialno (SST bytes) */
Victor Stinner9ed83c42017-10-31 12:18:10 -07002039 tail = data + nbytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002040 memset(tail, FORBIDDENBYTE, SST);
Victor Stinner9e87e772017-11-24 12:09:24 +01002041 write_size_t(tail + SST, serialno);
Tim Petersddea2082002-03-23 10:03:50 +00002042
Victor Stinner9ed83c42017-10-31 12:18:10 -07002043 return data;
Tim Petersddea2082002-03-23 10:03:50 +00002044}
2045
Victor Stinnerdb067af2014-05-02 22:31:14 +02002046static void *
Victor Stinnerc4aec362016-03-14 22:26:53 +01002047_PyMem_DebugRawMalloc(void *ctx, size_t nbytes)
Victor Stinnerdb067af2014-05-02 22:31:14 +02002048{
Victor Stinnerc4aec362016-03-14 22:26:53 +01002049 return _PyMem_DebugRawAlloc(0, ctx, nbytes);
Victor Stinnerdb067af2014-05-02 22:31:14 +02002050}
2051
2052static void *
Victor Stinnerc4aec362016-03-14 22:26:53 +01002053_PyMem_DebugRawCalloc(void *ctx, size_t nelem, size_t elsize)
Victor Stinnerdb067af2014-05-02 22:31:14 +02002054{
2055 size_t nbytes;
Victor Stinner9ed83c42017-10-31 12:18:10 -07002056 assert(elsize == 0 || nelem <= (size_t)PY_SSIZE_T_MAX / elsize);
Victor Stinnerdb067af2014-05-02 22:31:14 +02002057 nbytes = nelem * elsize;
Victor Stinnerc4aec362016-03-14 22:26:53 +01002058 return _PyMem_DebugRawAlloc(1, ctx, nbytes);
Victor Stinnerdb067af2014-05-02 22:31:14 +02002059}
2060
Victor Stinner9ed83c42017-10-31 12:18:10 -07002061
Victor Stinner82af0b62018-10-23 17:39:40 +02002062/* Heuristic checking if the memory has been freed. Rely on the debug hooks on
2063 Python memory allocators which fills the memory with DEADBYTE (0xDB) when
2064 memory is deallocated. */
2065int
2066_PyMem_IsFreed(void *ptr, size_t size)
2067{
2068 unsigned char *bytes = ptr;
2069 for (size_t i=0; i < size; i++) {
2070 if (bytes[i] != DEADBYTE) {
2071 return 0;
2072 }
2073 }
2074 return 1;
2075}
2076
2077
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00002078/* 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 +00002079 particular, that the FORBIDDENBYTEs with the api ID are still intact).
Tim Petersf6fb5012002-04-12 07:38:53 +00002080 Then fills the original bytes with DEADBYTE.
Tim Petersddea2082002-03-23 10:03:50 +00002081 Then calls the underlying free.
2082*/
Victor Stinner0507bf52013-07-07 02:05:46 +02002083static void
Victor Stinnerc4aec362016-03-14 22:26:53 +01002084_PyMem_DebugRawFree(void *ctx, void *p)
Tim Petersddea2082002-03-23 10:03:50 +00002085{
Victor Stinner9ed83c42017-10-31 12:18:10 -07002086 /* PyMem_Free(NULL) has no effect */
2087 if (p == NULL) {
2088 return;
2089 }
2090
Victor Stinner0507bf52013-07-07 02:05:46 +02002091 debug_alloc_api_t *api = (debug_alloc_api_t *)ctx;
Benjamin Peterson19517e42016-09-18 19:22:22 -07002092 uint8_t *q = (uint8_t *)p - 2*SST; /* address returned from malloc */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002093 size_t nbytes;
Tim Petersddea2082002-03-23 10:03:50 +00002094
Victor Stinner0507bf52013-07-07 02:05:46 +02002095 _PyMem_DebugCheckAddress(api->api_id, p);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002096 nbytes = read_size_t(q);
Victor Stinner9ed83c42017-10-31 12:18:10 -07002097 nbytes += 4 * SST;
2098 memset(q, DEADBYTE, nbytes);
Victor Stinner0507bf52013-07-07 02:05:46 +02002099 api->alloc.free(api->alloc.ctx, q);
Tim Petersddea2082002-03-23 10:03:50 +00002100}
2101
Victor Stinner9ed83c42017-10-31 12:18:10 -07002102
Victor Stinner0507bf52013-07-07 02:05:46 +02002103static void *
Victor Stinnerc4aec362016-03-14 22:26:53 +01002104_PyMem_DebugRawRealloc(void *ctx, void *p, size_t nbytes)
Tim Petersddea2082002-03-23 10:03:50 +00002105{
Victor Stinner9ed83c42017-10-31 12:18:10 -07002106 if (p == NULL) {
2107 return _PyMem_DebugRawAlloc(0, ctx, nbytes);
2108 }
2109
Victor Stinner0507bf52013-07-07 02:05:46 +02002110 debug_alloc_api_t *api = (debug_alloc_api_t *)ctx;
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002111 uint8_t *head; /* base address of malloc'ed pad block */
2112 uint8_t *data; /* pointer to data bytes */
2113 uint8_t *r;
Victor Stinner9ed83c42017-10-31 12:18:10 -07002114 uint8_t *tail; /* data + nbytes == pointer to tail pad bytes */
2115 size_t total; /* 2 * SST + nbytes + 2 * SST */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002116 size_t original_nbytes;
Victor Stinner9e87e772017-11-24 12:09:24 +01002117 size_t block_serialno;
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002118#define ERASED_SIZE 64
2119 uint8_t save[2*ERASED_SIZE]; /* A copy of erased bytes. */
Tim Petersddea2082002-03-23 10:03:50 +00002120
Victor Stinner0507bf52013-07-07 02:05:46 +02002121 _PyMem_DebugCheckAddress(api->api_id, p);
Victor Stinner9ed83c42017-10-31 12:18:10 -07002122
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002123 data = (uint8_t *)p;
2124 head = data - 2*SST;
2125 original_nbytes = read_size_t(head);
Victor Stinner9ed83c42017-10-31 12:18:10 -07002126 if (nbytes > (size_t)PY_SSIZE_T_MAX - 4*SST) {
2127 /* integer overflow: can't represent total as a Py_ssize_t */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002128 return NULL;
Victor Stinner9ed83c42017-10-31 12:18:10 -07002129 }
2130 total = nbytes + 4*SST;
Tim Petersddea2082002-03-23 10:03:50 +00002131
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002132 tail = data + original_nbytes;
Victor Stinner9e87e772017-11-24 12:09:24 +01002133 block_serialno = read_size_t(tail + SST);
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002134 /* Mark the header, the trailer, ERASED_SIZE bytes at the begin and
2135 ERASED_SIZE bytes at the end as dead and save the copy of erased bytes.
2136 */
2137 if (original_nbytes <= sizeof(save)) {
2138 memcpy(save, data, original_nbytes);
2139 memset(data - 2*SST, DEADBYTE, original_nbytes + 4*SST);
2140 }
2141 else {
2142 memcpy(save, data, ERASED_SIZE);
2143 memset(head, DEADBYTE, ERASED_SIZE + 2*SST);
2144 memcpy(&save[ERASED_SIZE], tail - ERASED_SIZE, ERASED_SIZE);
2145 memset(tail - ERASED_SIZE, DEADBYTE, ERASED_SIZE + 2*SST);
Victor Stinner9ed83c42017-10-31 12:18:10 -07002146 }
Tim Peters85cc1c42002-04-12 08:52:50 +00002147
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002148 /* Resize and add decorations. */
2149 r = (uint8_t *)api->alloc.realloc(api->alloc.ctx, head, total);
2150 if (r == NULL) {
2151 nbytes = original_nbytes;
Victor Stinner9ed83c42017-10-31 12:18:10 -07002152 }
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002153 else {
2154 head = r;
2155 bumpserialno();
Victor Stinner9e87e772017-11-24 12:09:24 +01002156 block_serialno = serialno;
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002157 }
2158
2159 write_size_t(head, nbytes);
2160 head[SST] = (uint8_t)api->api_id;
2161 memset(head + SST + 1, FORBIDDENBYTE, SST-1);
2162 data = head + 2*SST;
Victor Stinnerc4266362013-07-09 00:44:43 +02002163
Victor Stinner9ed83c42017-10-31 12:18:10 -07002164 tail = data + nbytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002165 memset(tail, FORBIDDENBYTE, SST);
Victor Stinner9e87e772017-11-24 12:09:24 +01002166 write_size_t(tail + SST, block_serialno);
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002167
2168 /* Restore saved bytes. */
2169 if (original_nbytes <= sizeof(save)) {
2170 memcpy(data, save, Py_MIN(nbytes, original_nbytes));
2171 }
2172 else {
2173 size_t i = original_nbytes - ERASED_SIZE;
2174 memcpy(data, save, Py_MIN(nbytes, ERASED_SIZE));
2175 if (nbytes > i) {
2176 memcpy(data + i, &save[ERASED_SIZE],
2177 Py_MIN(nbytes - i, ERASED_SIZE));
2178 }
2179 }
2180
2181 if (r == NULL) {
2182 return NULL;
2183 }
Tim Peters85cc1c42002-04-12 08:52:50 +00002184
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002185 if (nbytes > original_nbytes) {
2186 /* growing: mark new extra memory clean */
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002187 memset(data + original_nbytes, CLEANBYTE, nbytes - original_nbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002188 }
Tim Peters85cc1c42002-04-12 08:52:50 +00002189
Victor Stinner9ed83c42017-10-31 12:18:10 -07002190 return data;
Tim Petersddea2082002-03-23 10:03:50 +00002191}
2192
Victor Stinnerc4aec362016-03-14 22:26:53 +01002193static void
2194_PyMem_DebugCheckGIL(void)
2195{
Victor Stinnerc4aec362016-03-14 22:26:53 +01002196 if (!PyGILState_Check())
2197 Py_FatalError("Python memory allocator called "
2198 "without holding the GIL");
Victor Stinnerc4aec362016-03-14 22:26:53 +01002199}
2200
2201static void *
2202_PyMem_DebugMalloc(void *ctx, size_t nbytes)
2203{
2204 _PyMem_DebugCheckGIL();
2205 return _PyMem_DebugRawMalloc(ctx, nbytes);
2206}
2207
2208static void *
2209_PyMem_DebugCalloc(void *ctx, size_t nelem, size_t elsize)
2210{
2211 _PyMem_DebugCheckGIL();
2212 return _PyMem_DebugRawCalloc(ctx, nelem, elsize);
2213}
2214
Victor Stinner9ed83c42017-10-31 12:18:10 -07002215
Victor Stinnerc4aec362016-03-14 22:26:53 +01002216static void
2217_PyMem_DebugFree(void *ctx, void *ptr)
2218{
2219 _PyMem_DebugCheckGIL();
Victor Stinner0aed3a42016-03-23 11:30:43 +01002220 _PyMem_DebugRawFree(ctx, ptr);
Victor Stinnerc4aec362016-03-14 22:26:53 +01002221}
2222
Victor Stinner9ed83c42017-10-31 12:18:10 -07002223
Victor Stinnerc4aec362016-03-14 22:26:53 +01002224static void *
2225_PyMem_DebugRealloc(void *ctx, void *ptr, size_t nbytes)
2226{
2227 _PyMem_DebugCheckGIL();
2228 return _PyMem_DebugRawRealloc(ctx, ptr, nbytes);
2229}
2230
Tim Peters7ccfadf2002-04-01 06:04:21 +00002231/* Check the forbidden bytes on both ends of the memory allocated for p.
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00002232 * If anything is wrong, print info to stderr via _PyObject_DebugDumpAddress,
Tim Peters7ccfadf2002-04-01 06:04:21 +00002233 * and call Py_FatalError to kill the program.
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00002234 * The API id, is also checked.
Tim Peters7ccfadf2002-04-01 06:04:21 +00002235 */
Victor Stinner0507bf52013-07-07 02:05:46 +02002236static void
2237_PyMem_DebugCheckAddress(char api, const void *p)
Tim Petersddea2082002-03-23 10:03:50 +00002238{
Benjamin Peterson19517e42016-09-18 19:22:22 -07002239 const uint8_t *q = (const uint8_t *)p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002240 char msgbuf[64];
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02002241 const char *msg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002242 size_t nbytes;
Benjamin Peterson19517e42016-09-18 19:22:22 -07002243 const uint8_t *tail;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002244 int i;
2245 char id;
Tim Petersddea2082002-03-23 10:03:50 +00002246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002247 if (p == NULL) {
2248 msg = "didn't expect a NULL pointer";
2249 goto error;
2250 }
Tim Petersddea2082002-03-23 10:03:50 +00002251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002252 /* Check the API id */
2253 id = (char)q[-SST];
2254 if (id != api) {
2255 msg = msgbuf;
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02002256 snprintf(msgbuf, sizeof(msgbuf), "bad ID: Allocated using API '%c', verified using API '%c'", id, api);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002257 msgbuf[sizeof(msgbuf)-1] = 0;
2258 goto error;
2259 }
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00002260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002261 /* Check the stuff at the start of p first: if there's underwrite
2262 * corruption, the number-of-bytes field may be nuts, and checking
2263 * the tail could lead to a segfault then.
2264 */
2265 for (i = SST-1; i >= 1; --i) {
2266 if (*(q-i) != FORBIDDENBYTE) {
2267 msg = "bad leading pad byte";
2268 goto error;
2269 }
2270 }
Tim Petersddea2082002-03-23 10:03:50 +00002271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002272 nbytes = read_size_t(q - 2*SST);
2273 tail = q + nbytes;
2274 for (i = 0; i < SST; ++i) {
2275 if (tail[i] != FORBIDDENBYTE) {
2276 msg = "bad trailing pad byte";
2277 goto error;
2278 }
2279 }
Tim Petersddea2082002-03-23 10:03:50 +00002280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002281 return;
Tim Petersd1139e02002-03-28 07:32:11 +00002282
2283error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002284 _PyObject_DebugDumpAddress(p);
2285 Py_FatalError(msg);
Tim Petersddea2082002-03-23 10:03:50 +00002286}
2287
Tim Peters7ccfadf2002-04-01 06:04:21 +00002288/* Display info to stderr about the memory block at p. */
Victor Stinner0507bf52013-07-07 02:05:46 +02002289static void
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00002290_PyObject_DebugDumpAddress(const void *p)
Tim Petersddea2082002-03-23 10:03:50 +00002291{
Benjamin Peterson19517e42016-09-18 19:22:22 -07002292 const uint8_t *q = (const uint8_t *)p;
2293 const uint8_t *tail;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002294 size_t nbytes, serial;
2295 int i;
2296 int ok;
2297 char id;
Tim Petersddea2082002-03-23 10:03:50 +00002298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002299 fprintf(stderr, "Debug memory block at address p=%p:", p);
2300 if (p == NULL) {
2301 fprintf(stderr, "\n");
2302 return;
2303 }
2304 id = (char)q[-SST];
2305 fprintf(stderr, " API '%c'\n", id);
Tim Petersddea2082002-03-23 10:03:50 +00002306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002307 nbytes = read_size_t(q - 2*SST);
2308 fprintf(stderr, " %" PY_FORMAT_SIZE_T "u bytes originally "
2309 "requested\n", nbytes);
Tim Petersddea2082002-03-23 10:03:50 +00002310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002311 /* In case this is nuts, check the leading pad bytes first. */
2312 fprintf(stderr, " The %d pad bytes at p-%d are ", SST-1, SST-1);
2313 ok = 1;
2314 for (i = 1; i <= SST-1; ++i) {
2315 if (*(q-i) != FORBIDDENBYTE) {
2316 ok = 0;
2317 break;
2318 }
2319 }
2320 if (ok)
2321 fputs("FORBIDDENBYTE, as expected.\n", stderr);
2322 else {
2323 fprintf(stderr, "not all FORBIDDENBYTE (0x%02x):\n",
2324 FORBIDDENBYTE);
2325 for (i = SST-1; i >= 1; --i) {
Benjamin Peterson19517e42016-09-18 19:22:22 -07002326 const uint8_t byte = *(q-i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002327 fprintf(stderr, " at p-%d: 0x%02x", i, byte);
2328 if (byte != FORBIDDENBYTE)
2329 fputs(" *** OUCH", stderr);
2330 fputc('\n', stderr);
2331 }
Tim Peters449b5a82002-04-28 06:14:45 +00002332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002333 fputs(" Because memory is corrupted at the start, the "
2334 "count of bytes requested\n"
2335 " may be bogus, and checking the trailing pad "
2336 "bytes may segfault.\n", stderr);
2337 }
Tim Petersddea2082002-03-23 10:03:50 +00002338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002339 tail = q + nbytes;
2340 fprintf(stderr, " The %d pad bytes at tail=%p are ", SST, tail);
2341 ok = 1;
2342 for (i = 0; i < SST; ++i) {
2343 if (tail[i] != FORBIDDENBYTE) {
2344 ok = 0;
2345 break;
2346 }
2347 }
2348 if (ok)
2349 fputs("FORBIDDENBYTE, as expected.\n", stderr);
2350 else {
2351 fprintf(stderr, "not all FORBIDDENBYTE (0x%02x):\n",
Stefan Krah735bb122010-11-26 10:54:09 +00002352 FORBIDDENBYTE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002353 for (i = 0; i < SST; ++i) {
Benjamin Peterson19517e42016-09-18 19:22:22 -07002354 const uint8_t byte = tail[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002355 fprintf(stderr, " at tail+%d: 0x%02x",
Stefan Krah735bb122010-11-26 10:54:09 +00002356 i, byte);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002357 if (byte != FORBIDDENBYTE)
2358 fputs(" *** OUCH", stderr);
2359 fputc('\n', stderr);
2360 }
2361 }
Tim Petersddea2082002-03-23 10:03:50 +00002362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002363 serial = read_size_t(tail + SST);
2364 fprintf(stderr, " The block was made by call #%" PY_FORMAT_SIZE_T
2365 "u to debug malloc/realloc.\n", serial);
Tim Petersddea2082002-03-23 10:03:50 +00002366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002367 if (nbytes > 0) {
2368 i = 0;
2369 fputs(" Data at p:", stderr);
2370 /* print up to 8 bytes at the start */
2371 while (q < tail && i < 8) {
2372 fprintf(stderr, " %02x", *q);
2373 ++i;
2374 ++q;
2375 }
2376 /* and up to 8 at the end */
2377 if (q < tail) {
2378 if (tail - q > 8) {
2379 fputs(" ...", stderr);
2380 q = tail - 8;
2381 }
2382 while (q < tail) {
2383 fprintf(stderr, " %02x", *q);
2384 ++q;
2385 }
2386 }
2387 fputc('\n', stderr);
2388 }
Victor Stinner0611c262016-03-15 22:22:13 +01002389 fputc('\n', stderr);
2390
2391 fflush(stderr);
2392 _PyMem_DumpTraceback(fileno(stderr), p);
Tim Petersddea2082002-03-23 10:03:50 +00002393}
2394
David Malcolm49526f42012-06-22 14:55:41 -04002395
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00002396static size_t
David Malcolm49526f42012-06-22 14:55:41 -04002397printone(FILE *out, const char* msg, size_t value)
Tim Peters16bcb6b2002-04-05 05:45:31 +00002398{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002399 int i, k;
2400 char buf[100];
2401 size_t origvalue = value;
Tim Peters16bcb6b2002-04-05 05:45:31 +00002402
David Malcolm49526f42012-06-22 14:55:41 -04002403 fputs(msg, out);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002404 for (i = (int)strlen(msg); i < 35; ++i)
David Malcolm49526f42012-06-22 14:55:41 -04002405 fputc(' ', out);
2406 fputc('=', out);
Tim Peters49f26812002-04-06 01:45:35 +00002407
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002408 /* Write the value with commas. */
2409 i = 22;
2410 buf[i--] = '\0';
2411 buf[i--] = '\n';
2412 k = 3;
2413 do {
2414 size_t nextvalue = value / 10;
Benjamin Peterson2dba1ee2013-02-20 16:54:30 -05002415 unsigned int digit = (unsigned int)(value - nextvalue * 10);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002416 value = nextvalue;
2417 buf[i--] = (char)(digit + '0');
2418 --k;
2419 if (k == 0 && value && i >= 0) {
2420 k = 3;
2421 buf[i--] = ',';
2422 }
2423 } while (value && i >= 0);
Tim Peters49f26812002-04-06 01:45:35 +00002424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002425 while (i >= 0)
2426 buf[i--] = ' ';
David Malcolm49526f42012-06-22 14:55:41 -04002427 fputs(buf, out);
Tim Peters49f26812002-04-06 01:45:35 +00002428
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002429 return origvalue;
Tim Peters16bcb6b2002-04-05 05:45:31 +00002430}
2431
David Malcolm49526f42012-06-22 14:55:41 -04002432void
2433_PyDebugAllocatorStats(FILE *out,
2434 const char *block_name, int num_blocks, size_t sizeof_block)
2435{
2436 char buf1[128];
2437 char buf2[128];
2438 PyOS_snprintf(buf1, sizeof(buf1),
Tim Peterseaa3bcc2013-09-05 22:57:04 -05002439 "%d %ss * %" PY_FORMAT_SIZE_T "d bytes each",
David Malcolm49526f42012-06-22 14:55:41 -04002440 num_blocks, block_name, sizeof_block);
2441 PyOS_snprintf(buf2, sizeof(buf2),
2442 "%48s ", buf1);
2443 (void)printone(out, buf2, num_blocks * sizeof_block);
2444}
2445
Victor Stinner34be8072016-03-14 12:04:26 +01002446
David Malcolm49526f42012-06-22 14:55:41 -04002447#ifdef WITH_PYMALLOC
2448
Victor Stinner34be8072016-03-14 12:04:26 +01002449#ifdef Py_DEBUG
2450/* Is target in the list? The list is traversed via the nextpool pointers.
2451 * The list may be NULL-terminated, or circular. Return 1 if target is in
2452 * list, else 0.
2453 */
2454static int
2455pool_is_in_list(const poolp target, poolp list)
2456{
2457 poolp origlist = list;
2458 assert(target != NULL);
2459 if (list == NULL)
2460 return 0;
2461 do {
2462 if (target == list)
2463 return 1;
2464 list = list->nextpool;
2465 } while (list != NULL && list != origlist);
2466 return 0;
2467}
2468#endif
2469
David Malcolm49526f42012-06-22 14:55:41 -04002470/* Print summary info to "out" about the state of pymalloc's structures.
Tim Peters08d82152002-04-18 22:25:03 +00002471 * In Py_DEBUG mode, also perform some expensive internal consistency
2472 * checks.
Victor Stinner6bf992a2017-12-06 17:26:10 +01002473 *
2474 * Return 0 if the memory debug hooks are not installed or no statistics was
Leo Ariasc3d95082018-02-03 18:36:10 -06002475 * written into out, return 1 otherwise.
Tim Peters08d82152002-04-18 22:25:03 +00002476 */
Victor Stinner6bf992a2017-12-06 17:26:10 +01002477int
David Malcolm49526f42012-06-22 14:55:41 -04002478_PyObject_DebugMallocStats(FILE *out)
Tim Peters7ccfadf2002-04-01 06:04:21 +00002479{
Victor Stinner6bf992a2017-12-06 17:26:10 +01002480 if (!_PyMem_PymallocEnabled()) {
2481 return 0;
2482 }
2483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002484 uint i;
2485 const uint numclasses = SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT;
2486 /* # of pools, allocated blocks, and free blocks per class index */
2487 size_t numpools[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT];
2488 size_t numblocks[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT];
2489 size_t numfreeblocks[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT];
2490 /* total # of allocated bytes in used and full pools */
2491 size_t allocated_bytes = 0;
2492 /* total # of available bytes in used pools */
2493 size_t available_bytes = 0;
2494 /* # of free pools + pools not yet carved out of current arena */
2495 uint numfreepools = 0;
2496 /* # of bytes for arena alignment padding */
2497 size_t arena_alignment = 0;
2498 /* # of bytes in used and full pools used for pool_headers */
2499 size_t pool_header_bytes = 0;
2500 /* # of bytes in used and full pools wasted due to quantization,
2501 * i.e. the necessarily leftover space at the ends of used and
2502 * full pools.
2503 */
2504 size_t quantization = 0;
2505 /* # of arenas actually allocated. */
2506 size_t narenas = 0;
2507 /* running total -- should equal narenas * ARENA_SIZE */
2508 size_t total;
2509 char buf[128];
Tim Peters7ccfadf2002-04-01 06:04:21 +00002510
David Malcolm49526f42012-06-22 14:55:41 -04002511 fprintf(out, "Small block threshold = %d, in %u size classes.\n",
Stefan Krah735bb122010-11-26 10:54:09 +00002512 SMALL_REQUEST_THRESHOLD, numclasses);
Tim Peters7ccfadf2002-04-01 06:04:21 +00002513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002514 for (i = 0; i < numclasses; ++i)
2515 numpools[i] = numblocks[i] = numfreeblocks[i] = 0;
Tim Peters7ccfadf2002-04-01 06:04:21 +00002516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002517 /* Because full pools aren't linked to from anything, it's easiest
2518 * to march over all the arenas. If we're lucky, most of the memory
2519 * will be living in full pools -- would be a shame to miss them.
2520 */
Victor Stinner9e87e772017-11-24 12:09:24 +01002521 for (i = 0; i < maxarenas; ++i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002522 uint j;
Victor Stinner9e87e772017-11-24 12:09:24 +01002523 uintptr_t base = arenas[i].address;
Thomas Woutersa9773292006-04-21 09:43:23 +00002524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002525 /* Skip arenas which are not allocated. */
Victor Stinner9e87e772017-11-24 12:09:24 +01002526 if (arenas[i].address == (uintptr_t)NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002527 continue;
2528 narenas += 1;
Thomas Woutersa9773292006-04-21 09:43:23 +00002529
Victor Stinner9e87e772017-11-24 12:09:24 +01002530 numfreepools += arenas[i].nfreepools;
Tim Peters7ccfadf2002-04-01 06:04:21 +00002531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002532 /* round up to pool alignment */
Benjamin Peterson5d4b09c2016-09-18 19:24:52 -07002533 if (base & (uintptr_t)POOL_SIZE_MASK) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002534 arena_alignment += POOL_SIZE;
Benjamin Peterson5d4b09c2016-09-18 19:24:52 -07002535 base &= ~(uintptr_t)POOL_SIZE_MASK;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002536 base += POOL_SIZE;
2537 }
Tim Peters7ccfadf2002-04-01 06:04:21 +00002538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002539 /* visit every pool in the arena */
Victor Stinner9e87e772017-11-24 12:09:24 +01002540 assert(base <= (uintptr_t) arenas[i].pool_address);
2541 for (j = 0; base < (uintptr_t) arenas[i].pool_address;
Benjamin Peterson19517e42016-09-18 19:22:22 -07002542 ++j, base += POOL_SIZE) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002543 poolp p = (poolp)base;
2544 const uint sz = p->szidx;
2545 uint freeblocks;
Tim Peters08d82152002-04-18 22:25:03 +00002546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002547 if (p->ref.count == 0) {
2548 /* currently unused */
Victor Stinner34be8072016-03-14 12:04:26 +01002549#ifdef Py_DEBUG
Victor Stinner9e87e772017-11-24 12:09:24 +01002550 assert(pool_is_in_list(p, arenas[i].freepools));
Victor Stinner34be8072016-03-14 12:04:26 +01002551#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002552 continue;
2553 }
2554 ++numpools[sz];
2555 numblocks[sz] += p->ref.count;
2556 freeblocks = NUMBLOCKS(sz) - p->ref.count;
2557 numfreeblocks[sz] += freeblocks;
Tim Peters08d82152002-04-18 22:25:03 +00002558#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002559 if (freeblocks > 0)
Victor Stinner9e87e772017-11-24 12:09:24 +01002560 assert(pool_is_in_list(p, usedpools[sz + sz]));
Tim Peters08d82152002-04-18 22:25:03 +00002561#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002562 }
2563 }
Victor Stinner9e87e772017-11-24 12:09:24 +01002564 assert(narenas == narenas_currently_allocated);
Tim Peters7ccfadf2002-04-01 06:04:21 +00002565
David Malcolm49526f42012-06-22 14:55:41 -04002566 fputc('\n', out);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002567 fputs("class size num pools blocks in use avail blocks\n"
2568 "----- ---- --------- ------------- ------------\n",
David Malcolm49526f42012-06-22 14:55:41 -04002569 out);
Tim Peters7ccfadf2002-04-01 06:04:21 +00002570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002571 for (i = 0; i < numclasses; ++i) {
2572 size_t p = numpools[i];
2573 size_t b = numblocks[i];
2574 size_t f = numfreeblocks[i];
2575 uint size = INDEX2SIZE(i);
2576 if (p == 0) {
2577 assert(b == 0 && f == 0);
2578 continue;
2579 }
David Malcolm49526f42012-06-22 14:55:41 -04002580 fprintf(out, "%5u %6u "
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002581 "%11" PY_FORMAT_SIZE_T "u "
2582 "%15" PY_FORMAT_SIZE_T "u "
2583 "%13" PY_FORMAT_SIZE_T "u\n",
Stefan Krah735bb122010-11-26 10:54:09 +00002584 i, size, p, b, f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002585 allocated_bytes += b * size;
2586 available_bytes += f * size;
2587 pool_header_bytes += p * POOL_OVERHEAD;
2588 quantization += p * ((POOL_SIZE - POOL_OVERHEAD) % size);
2589 }
David Malcolm49526f42012-06-22 14:55:41 -04002590 fputc('\n', out);
Victor Stinner34be8072016-03-14 12:04:26 +01002591 if (_PyMem_DebugEnabled())
Victor Stinner9e87e772017-11-24 12:09:24 +01002592 (void)printone(out, "# times object malloc called", serialno);
2593 (void)printone(out, "# arenas allocated total", ntimes_arena_allocated);
2594 (void)printone(out, "# arenas reclaimed", ntimes_arena_allocated - narenas);
2595 (void)printone(out, "# arenas highwater mark", narenas_highwater);
David Malcolm49526f42012-06-22 14:55:41 -04002596 (void)printone(out, "# arenas allocated current", narenas);
Thomas Woutersa9773292006-04-21 09:43:23 +00002597
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002598 PyOS_snprintf(buf, sizeof(buf),
2599 "%" PY_FORMAT_SIZE_T "u arenas * %d bytes/arena",
2600 narenas, ARENA_SIZE);
David Malcolm49526f42012-06-22 14:55:41 -04002601 (void)printone(out, buf, narenas * ARENA_SIZE);
Tim Peters16bcb6b2002-04-05 05:45:31 +00002602
David Malcolm49526f42012-06-22 14:55:41 -04002603 fputc('\n', out);
Tim Peters16bcb6b2002-04-05 05:45:31 +00002604
David Malcolm49526f42012-06-22 14:55:41 -04002605 total = printone(out, "# bytes in allocated blocks", allocated_bytes);
2606 total += printone(out, "# bytes in available blocks", available_bytes);
Tim Peters49f26812002-04-06 01:45:35 +00002607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002608 PyOS_snprintf(buf, sizeof(buf),
2609 "%u unused pools * %d bytes", numfreepools, POOL_SIZE);
David Malcolm49526f42012-06-22 14:55:41 -04002610 total += printone(out, buf, (size_t)numfreepools * POOL_SIZE);
Tim Peters16bcb6b2002-04-05 05:45:31 +00002611
David Malcolm49526f42012-06-22 14:55:41 -04002612 total += printone(out, "# bytes lost to pool headers", pool_header_bytes);
2613 total += printone(out, "# bytes lost to quantization", quantization);
2614 total += printone(out, "# bytes lost to arena alignment", arena_alignment);
2615 (void)printone(out, "Total", total);
Victor Stinner6bf992a2017-12-06 17:26:10 +01002616 return 1;
Tim Peters7ccfadf2002-04-01 06:04:21 +00002617}
2618
David Malcolm49526f42012-06-22 14:55:41 -04002619#endif /* #ifdef WITH_PYMALLOC */