blob: 7cfd28965967f9580aeb06a0cef8b20fa234f4ae [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 Stinner34be807c2016-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 Stinner34be807c2016-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 Stinner34be807c2016-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 Stinner34be807c2016-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 Stinner34be807c2016-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 Stinner34be807c2016-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 Stinner34be807c2016-03-14 12:04:26 +0100297
Victor Stinner5d39e042017-11-29 17:20:38 +0100298 if (strcmp(opt, "pymalloc_debug") == 0) {
Victor Stinner34be807c2016-03-14 12:04:26 +0100299 PyMem_SetupDebugHooks();
Victor Stinner5d39e042017-11-29 17:20:38 +0100300 }
Victor Stinner34be807c2016-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 Stinner34be807c2016-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 Stinner34be807c2016-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 Stinner34be807c2016-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 Stinner34be807c2016-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 Stinner34be807c2016-03-14 12:04:26 +01001158 static int debug_stats = -1;
Tim Petersd97a1c02002-03-30 06:09:22 +00001159
Victor Stinner34be807c2016-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 Stinner34be807c2016-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 Stinner34be807c2016-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 Stinner34be807c2016-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
Victor Stinner2b00db62019-04-11 11:33:27 +02001917 * 7-bit ASCII. If modified, _PyMem_IsPtrFreed() should be updated as well.
Victor Stinner4c409be2019-04-11 13:01:15 +02001918 *
1919 * Byte patterns 0xCB, 0xBB and 0xFB have been replaced with 0xCD, 0xDD and
1920 * 0xFD to use the same values than Windows CRT debug malloc() and free().
Tim Petersf6fb5012002-04-12 07:38:53 +00001921 */
1922#undef CLEANBYTE
1923#undef DEADBYTE
1924#undef FORBIDDENBYTE
Victor Stinner4c409be2019-04-11 13:01:15 +02001925#define CLEANBYTE 0xCD /* clean (newly allocated) memory */
1926#define DEADBYTE 0xDD /* dead (newly freed) memory */
1927#define FORBIDDENBYTE 0xFD /* untouchable bytes at each end of a block */
Tim Petersddea2082002-03-23 10:03:50 +00001928
Victor Stinnere8f9acf2019-04-12 21:54:06 +02001929/* Uncomment this define to add the "serialno" field */
1930/* #define PYMEM_DEBUG_SERIALNO */
1931
1932#ifdef PYMEM_DEBUG_SERIALNO
Victor Stinner9e87e772017-11-24 12:09:24 +01001933static size_t serialno = 0; /* incremented on each debug {m,re}alloc */
1934
Tim Peterse0850172002-03-24 00:34:21 +00001935/* serialno is always incremented via calling this routine. The point is
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001936 * to supply a single place to set a breakpoint.
1937 */
Tim Peterse0850172002-03-24 00:34:21 +00001938static void
Neil Schemenauerbd02b142002-03-28 21:05:38 +00001939bumpserialno(void)
Tim Peterse0850172002-03-24 00:34:21 +00001940{
Victor Stinner9e87e772017-11-24 12:09:24 +01001941 ++serialno;
Tim Peterse0850172002-03-24 00:34:21 +00001942}
Victor Stinnere8f9acf2019-04-12 21:54:06 +02001943#endif
Tim Peterse0850172002-03-24 00:34:21 +00001944
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001945#define SST SIZEOF_SIZE_T
Tim Peterse0850172002-03-24 00:34:21 +00001946
Victor Stinnere8f9acf2019-04-12 21:54:06 +02001947#ifdef PYMEM_DEBUG_SERIALNO
1948# define PYMEM_DEBUG_EXTRA_BYTES 4 * SST
1949#else
1950# define PYMEM_DEBUG_EXTRA_BYTES 3 * SST
1951#endif
1952
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001953/* Read sizeof(size_t) bytes at p as a big-endian size_t. */
1954static size_t
1955read_size_t(const void *p)
Tim Petersddea2082002-03-23 10:03:50 +00001956{
Benjamin Peterson19517e42016-09-18 19:22:22 -07001957 const uint8_t *q = (const uint8_t *)p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001958 size_t result = *q++;
1959 int i;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001961 for (i = SST; --i > 0; ++q)
1962 result = (result << 8) | *q;
1963 return result;
Tim Petersddea2082002-03-23 10:03:50 +00001964}
1965
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001966/* Write n as a big-endian size_t, MSB at address p, LSB at
1967 * p + sizeof(size_t) - 1.
1968 */
Tim Petersddea2082002-03-23 10:03:50 +00001969static void
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001970write_size_t(void *p, size_t n)
Tim Petersddea2082002-03-23 10:03:50 +00001971{
Benjamin Peterson19517e42016-09-18 19:22:22 -07001972 uint8_t *q = (uint8_t *)p + SST - 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001973 int i;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001974
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001975 for (i = SST; --i >= 0; --q) {
Benjamin Peterson19517e42016-09-18 19:22:22 -07001976 *q = (uint8_t)(n & 0xff);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001977 n >>= 8;
1978 }
Tim Petersddea2082002-03-23 10:03:50 +00001979}
1980
Victor Stinnere8f9acf2019-04-12 21:54:06 +02001981/* Let S = sizeof(size_t). The debug malloc asks for 4 * S extra bytes and
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001982 fills them with useful stuff, here calling the underlying malloc's result p:
Tim Petersddea2082002-03-23 10:03:50 +00001983
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001984p[0: S]
1985 Number of bytes originally asked for. This is a size_t, big-endian (easier
1986 to read in a memory dump).
Georg Brandl7cba5fd2013-09-25 09:04:23 +02001987p[S]
Tim Petersdf099f52013-09-19 21:06:37 -05001988 API ID. See PEP 445. This is a character, but seems undocumented.
1989p[S+1: 2*S]
Tim Petersf6fb5012002-04-12 07:38:53 +00001990 Copies of FORBIDDENBYTE. Used to catch under- writes and reads.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001991p[2*S: 2*S+n]
Tim Petersf6fb5012002-04-12 07:38:53 +00001992 The requested memory, filled with copies of CLEANBYTE.
Tim Petersddea2082002-03-23 10:03:50 +00001993 Used to catch reference to uninitialized memory.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001994 &p[2*S] is returned. Note that this is 8-byte aligned if pymalloc
Tim Petersddea2082002-03-23 10:03:50 +00001995 handled the request itself.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001996p[2*S+n: 2*S+n+S]
Tim Petersf6fb5012002-04-12 07:38:53 +00001997 Copies of FORBIDDENBYTE. Used to catch over- writes and reads.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001998p[2*S+n+S: 2*S+n+2*S]
Victor Stinner0507bf52013-07-07 02:05:46 +02001999 A serial number, incremented by 1 on each call to _PyMem_DebugMalloc
2000 and _PyMem_DebugRealloc.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00002001 This is a big-endian size_t.
Tim Petersddea2082002-03-23 10:03:50 +00002002 If "bad memory" is detected later, the serial number gives an
2003 excellent way to set a breakpoint on the next run, to capture the
2004 instant at which this block was passed out.
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002005
2006If PYMEM_DEBUG_SERIALNO is not defined (default), the debug malloc only asks
2007for 3 * S extra bytes, and omits the last serialno field.
Tim Petersddea2082002-03-23 10:03:50 +00002008*/
2009
Victor Stinner0507bf52013-07-07 02:05:46 +02002010static void *
Victor Stinnerc4aec362016-03-14 22:26:53 +01002011_PyMem_DebugRawAlloc(int use_calloc, void *ctx, size_t nbytes)
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00002012{
Victor Stinner0507bf52013-07-07 02:05:46 +02002013 debug_alloc_api_t *api = (debug_alloc_api_t *)ctx;
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002014 uint8_t *p; /* base address of malloc'ed pad block */
Victor Stinner9ed83c42017-10-31 12:18:10 -07002015 uint8_t *data; /* p + 2*SST == pointer to data bytes */
2016 uint8_t *tail; /* data + nbytes == pointer to tail pad bytes */
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002017 size_t total; /* nbytes + PYMEM_DEBUG_EXTRA_BYTES */
Victor Stinner9ed83c42017-10-31 12:18:10 -07002018
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002019 if (nbytes > (size_t)PY_SSIZE_T_MAX - PYMEM_DEBUG_EXTRA_BYTES) {
Victor Stinner9ed83c42017-10-31 12:18:10 -07002020 /* integer overflow: can't represent total as a Py_ssize_t */
2021 return NULL;
2022 }
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002023 total = nbytes + PYMEM_DEBUG_EXTRA_BYTES;
Victor Stinner9ed83c42017-10-31 12:18:10 -07002024
2025 /* Layout: [SSSS IFFF CCCC...CCCC FFFF NNNN]
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002026 ^--- p ^--- data ^--- tail
Victor Stinner9ed83c42017-10-31 12:18:10 -07002027 S: nbytes stored as size_t
2028 I: API identifier (1 byte)
2029 F: Forbidden bytes (size_t - 1 bytes before, size_t bytes after)
2030 C: Clean bytes used later to store actual data
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002031 N: Serial number stored as size_t
2032
2033 If PYMEM_DEBUG_SERIALNO is not defined (default), the last NNNN field
2034 is omitted. */
Victor Stinner9ed83c42017-10-31 12:18:10 -07002035
2036 if (use_calloc) {
2037 p = (uint8_t *)api->alloc.calloc(api->alloc.ctx, 1, total);
2038 }
2039 else {
2040 p = (uint8_t *)api->alloc.malloc(api->alloc.ctx, total);
2041 }
2042 if (p == NULL) {
2043 return NULL;
2044 }
2045 data = p + 2*SST;
Tim Petersddea2082002-03-23 10:03:50 +00002046
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002047#ifdef PYMEM_DEBUG_SERIALNO
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002048 bumpserialno();
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002049#endif
Tim Petersddea2082002-03-23 10:03:50 +00002050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002051 /* at p, write size (SST bytes), id (1 byte), pad (SST-1 bytes) */
2052 write_size_t(p, nbytes);
Benjamin Peterson19517e42016-09-18 19:22:22 -07002053 p[SST] = (uint8_t)api->api_id;
Victor Stinner0507bf52013-07-07 02:05:46 +02002054 memset(p + SST + 1, FORBIDDENBYTE, SST-1);
Tim Petersddea2082002-03-23 10:03:50 +00002055
Victor Stinner9ed83c42017-10-31 12:18:10 -07002056 if (nbytes > 0 && !use_calloc) {
2057 memset(data, CLEANBYTE, nbytes);
2058 }
Tim Petersddea2082002-03-23 10:03:50 +00002059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002060 /* at tail, write pad (SST bytes) and serialno (SST bytes) */
Victor Stinner9ed83c42017-10-31 12:18:10 -07002061 tail = data + nbytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002062 memset(tail, FORBIDDENBYTE, SST);
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002063#ifdef PYMEM_DEBUG_SERIALNO
Victor Stinner9e87e772017-11-24 12:09:24 +01002064 write_size_t(tail + SST, serialno);
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002065#endif
Tim Petersddea2082002-03-23 10:03:50 +00002066
Victor Stinner9ed83c42017-10-31 12:18:10 -07002067 return data;
Tim Petersddea2082002-03-23 10:03:50 +00002068}
2069
Victor Stinnerdb067af2014-05-02 22:31:14 +02002070static void *
Victor Stinnerc4aec362016-03-14 22:26:53 +01002071_PyMem_DebugRawMalloc(void *ctx, size_t nbytes)
Victor Stinnerdb067af2014-05-02 22:31:14 +02002072{
Victor Stinnerc4aec362016-03-14 22:26:53 +01002073 return _PyMem_DebugRawAlloc(0, ctx, nbytes);
Victor Stinnerdb067af2014-05-02 22:31:14 +02002074}
2075
2076static void *
Victor Stinnerc4aec362016-03-14 22:26:53 +01002077_PyMem_DebugRawCalloc(void *ctx, size_t nelem, size_t elsize)
Victor Stinnerdb067af2014-05-02 22:31:14 +02002078{
2079 size_t nbytes;
Victor Stinner9ed83c42017-10-31 12:18:10 -07002080 assert(elsize == 0 || nelem <= (size_t)PY_SSIZE_T_MAX / elsize);
Victor Stinnerdb067af2014-05-02 22:31:14 +02002081 nbytes = nelem * elsize;
Victor Stinnerc4aec362016-03-14 22:26:53 +01002082 return _PyMem_DebugRawAlloc(1, ctx, nbytes);
Victor Stinnerdb067af2014-05-02 22:31:14 +02002083}
2084
Victor Stinner9ed83c42017-10-31 12:18:10 -07002085
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00002086/* 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 +00002087 particular, that the FORBIDDENBYTEs with the api ID are still intact).
Tim Petersf6fb5012002-04-12 07:38:53 +00002088 Then fills the original bytes with DEADBYTE.
Tim Petersddea2082002-03-23 10:03:50 +00002089 Then calls the underlying free.
2090*/
Victor Stinner0507bf52013-07-07 02:05:46 +02002091static void
Victor Stinnerc4aec362016-03-14 22:26:53 +01002092_PyMem_DebugRawFree(void *ctx, void *p)
Tim Petersddea2082002-03-23 10:03:50 +00002093{
Victor Stinner9ed83c42017-10-31 12:18:10 -07002094 /* PyMem_Free(NULL) has no effect */
2095 if (p == NULL) {
2096 return;
2097 }
2098
Victor Stinner0507bf52013-07-07 02:05:46 +02002099 debug_alloc_api_t *api = (debug_alloc_api_t *)ctx;
Benjamin Peterson19517e42016-09-18 19:22:22 -07002100 uint8_t *q = (uint8_t *)p - 2*SST; /* address returned from malloc */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002101 size_t nbytes;
Tim Petersddea2082002-03-23 10:03:50 +00002102
Victor Stinner0507bf52013-07-07 02:05:46 +02002103 _PyMem_DebugCheckAddress(api->api_id, p);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002104 nbytes = read_size_t(q);
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002105 nbytes += PYMEM_DEBUG_EXTRA_BYTES;
Victor Stinner9ed83c42017-10-31 12:18:10 -07002106 memset(q, DEADBYTE, nbytes);
Victor Stinner0507bf52013-07-07 02:05:46 +02002107 api->alloc.free(api->alloc.ctx, q);
Tim Petersddea2082002-03-23 10:03:50 +00002108}
2109
Victor Stinner9ed83c42017-10-31 12:18:10 -07002110
Victor Stinner0507bf52013-07-07 02:05:46 +02002111static void *
Victor Stinnerc4aec362016-03-14 22:26:53 +01002112_PyMem_DebugRawRealloc(void *ctx, void *p, size_t nbytes)
Tim Petersddea2082002-03-23 10:03:50 +00002113{
Victor Stinner9ed83c42017-10-31 12:18:10 -07002114 if (p == NULL) {
2115 return _PyMem_DebugRawAlloc(0, ctx, nbytes);
2116 }
2117
Victor Stinner0507bf52013-07-07 02:05:46 +02002118 debug_alloc_api_t *api = (debug_alloc_api_t *)ctx;
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002119 uint8_t *head; /* base address of malloc'ed pad block */
2120 uint8_t *data; /* pointer to data bytes */
2121 uint8_t *r;
Victor Stinner9ed83c42017-10-31 12:18:10 -07002122 uint8_t *tail; /* data + nbytes == pointer to tail pad bytes */
2123 size_t total; /* 2 * SST + nbytes + 2 * SST */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002124 size_t original_nbytes;
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002125#define ERASED_SIZE 64
2126 uint8_t save[2*ERASED_SIZE]; /* A copy of erased bytes. */
Tim Petersddea2082002-03-23 10:03:50 +00002127
Victor Stinner0507bf52013-07-07 02:05:46 +02002128 _PyMem_DebugCheckAddress(api->api_id, p);
Victor Stinner9ed83c42017-10-31 12:18:10 -07002129
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002130 data = (uint8_t *)p;
2131 head = data - 2*SST;
2132 original_nbytes = read_size_t(head);
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002133 if (nbytes > (size_t)PY_SSIZE_T_MAX - PYMEM_DEBUG_EXTRA_BYTES) {
Victor Stinner9ed83c42017-10-31 12:18:10 -07002134 /* integer overflow: can't represent total as a Py_ssize_t */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002135 return NULL;
Victor Stinner9ed83c42017-10-31 12:18:10 -07002136 }
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002137 total = nbytes + PYMEM_DEBUG_EXTRA_BYTES;
Tim Petersddea2082002-03-23 10:03:50 +00002138
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002139 tail = data + original_nbytes;
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002140#ifdef PYMEM_DEBUG_SERIALNO
2141 size_t block_serialno = read_size_t(tail + SST);
2142#endif
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002143 /* Mark the header, the trailer, ERASED_SIZE bytes at the begin and
2144 ERASED_SIZE bytes at the end as dead and save the copy of erased bytes.
2145 */
2146 if (original_nbytes <= sizeof(save)) {
2147 memcpy(save, data, original_nbytes);
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002148 memset(data - 2 * SST, DEADBYTE,
2149 original_nbytes + PYMEM_DEBUG_EXTRA_BYTES);
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002150 }
2151 else {
2152 memcpy(save, data, ERASED_SIZE);
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002153 memset(head, DEADBYTE, ERASED_SIZE + 2 * SST);
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002154 memcpy(&save[ERASED_SIZE], tail - ERASED_SIZE, ERASED_SIZE);
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002155 memset(tail - ERASED_SIZE, DEADBYTE,
2156 ERASED_SIZE + PYMEM_DEBUG_EXTRA_BYTES - 2 * SST);
Victor Stinner9ed83c42017-10-31 12:18:10 -07002157 }
Tim Peters85cc1c42002-04-12 08:52:50 +00002158
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002159 /* Resize and add decorations. */
2160 r = (uint8_t *)api->alloc.realloc(api->alloc.ctx, head, total);
2161 if (r == NULL) {
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002162 /* if realloc() failed: rewrite header and footer which have
2163 just been erased */
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002164 nbytes = original_nbytes;
Victor Stinner9ed83c42017-10-31 12:18:10 -07002165 }
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002166 else {
2167 head = r;
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002168#ifdef PYMEM_DEBUG_SERIALNO
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002169 bumpserialno();
Victor Stinner9e87e772017-11-24 12:09:24 +01002170 block_serialno = serialno;
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002171#endif
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002172 }
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002173 data = head + 2*SST;
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002174
2175 write_size_t(head, nbytes);
2176 head[SST] = (uint8_t)api->api_id;
2177 memset(head + SST + 1, FORBIDDENBYTE, SST-1);
Victor Stinnerc4266362013-07-09 00:44:43 +02002178
Victor Stinner9ed83c42017-10-31 12:18:10 -07002179 tail = data + nbytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002180 memset(tail, FORBIDDENBYTE, SST);
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002181#ifdef PYMEM_DEBUG_SERIALNO
Victor Stinner9e87e772017-11-24 12:09:24 +01002182 write_size_t(tail + SST, block_serialno);
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002183#endif
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002184
2185 /* Restore saved bytes. */
2186 if (original_nbytes <= sizeof(save)) {
2187 memcpy(data, save, Py_MIN(nbytes, original_nbytes));
2188 }
2189 else {
2190 size_t i = original_nbytes - ERASED_SIZE;
2191 memcpy(data, save, Py_MIN(nbytes, ERASED_SIZE));
2192 if (nbytes > i) {
2193 memcpy(data + i, &save[ERASED_SIZE],
2194 Py_MIN(nbytes - i, ERASED_SIZE));
2195 }
2196 }
2197
2198 if (r == NULL) {
2199 return NULL;
2200 }
Tim Peters85cc1c42002-04-12 08:52:50 +00002201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002202 if (nbytes > original_nbytes) {
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002203 /* growing: mark new extra memory clean */
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002204 memset(data + original_nbytes, CLEANBYTE, nbytes - original_nbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002205 }
Tim Peters85cc1c42002-04-12 08:52:50 +00002206
Victor Stinner9ed83c42017-10-31 12:18:10 -07002207 return data;
Tim Petersddea2082002-03-23 10:03:50 +00002208}
2209
Victor Stinnerc4aec362016-03-14 22:26:53 +01002210static void
2211_PyMem_DebugCheckGIL(void)
2212{
Victor Stinnerc4aec362016-03-14 22:26:53 +01002213 if (!PyGILState_Check())
2214 Py_FatalError("Python memory allocator called "
2215 "without holding the GIL");
Victor Stinnerc4aec362016-03-14 22:26:53 +01002216}
2217
2218static void *
2219_PyMem_DebugMalloc(void *ctx, size_t nbytes)
2220{
2221 _PyMem_DebugCheckGIL();
2222 return _PyMem_DebugRawMalloc(ctx, nbytes);
2223}
2224
2225static void *
2226_PyMem_DebugCalloc(void *ctx, size_t nelem, size_t elsize)
2227{
2228 _PyMem_DebugCheckGIL();
2229 return _PyMem_DebugRawCalloc(ctx, nelem, elsize);
2230}
2231
Victor Stinner9ed83c42017-10-31 12:18:10 -07002232
Victor Stinnerc4aec362016-03-14 22:26:53 +01002233static void
2234_PyMem_DebugFree(void *ctx, void *ptr)
2235{
2236 _PyMem_DebugCheckGIL();
Victor Stinner0aed3a42016-03-23 11:30:43 +01002237 _PyMem_DebugRawFree(ctx, ptr);
Victor Stinnerc4aec362016-03-14 22:26:53 +01002238}
2239
Victor Stinner9ed83c42017-10-31 12:18:10 -07002240
Victor Stinnerc4aec362016-03-14 22:26:53 +01002241static void *
2242_PyMem_DebugRealloc(void *ctx, void *ptr, size_t nbytes)
2243{
2244 _PyMem_DebugCheckGIL();
2245 return _PyMem_DebugRawRealloc(ctx, ptr, nbytes);
2246}
2247
Tim Peters7ccfadf2002-04-01 06:04:21 +00002248/* Check the forbidden bytes on both ends of the memory allocated for p.
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00002249 * If anything is wrong, print info to stderr via _PyObject_DebugDumpAddress,
Tim Peters7ccfadf2002-04-01 06:04:21 +00002250 * and call Py_FatalError to kill the program.
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00002251 * The API id, is also checked.
Tim Peters7ccfadf2002-04-01 06:04:21 +00002252 */
Victor Stinner0507bf52013-07-07 02:05:46 +02002253static void
2254_PyMem_DebugCheckAddress(char api, const void *p)
Tim Petersddea2082002-03-23 10:03:50 +00002255{
Benjamin Peterson19517e42016-09-18 19:22:22 -07002256 const uint8_t *q = (const uint8_t *)p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002257 char msgbuf[64];
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02002258 const char *msg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002259 size_t nbytes;
Benjamin Peterson19517e42016-09-18 19:22:22 -07002260 const uint8_t *tail;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002261 int i;
2262 char id;
Tim Petersddea2082002-03-23 10:03:50 +00002263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002264 if (p == NULL) {
2265 msg = "didn't expect a NULL pointer";
2266 goto error;
2267 }
Tim Petersddea2082002-03-23 10:03:50 +00002268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002269 /* Check the API id */
2270 id = (char)q[-SST];
2271 if (id != api) {
2272 msg = msgbuf;
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02002273 snprintf(msgbuf, sizeof(msgbuf), "bad ID: Allocated using API '%c', verified using API '%c'", id, api);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002274 msgbuf[sizeof(msgbuf)-1] = 0;
2275 goto error;
2276 }
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00002277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002278 /* Check the stuff at the start of p first: if there's underwrite
2279 * corruption, the number-of-bytes field may be nuts, and checking
2280 * the tail could lead to a segfault then.
2281 */
2282 for (i = SST-1; i >= 1; --i) {
2283 if (*(q-i) != FORBIDDENBYTE) {
2284 msg = "bad leading pad byte";
2285 goto error;
2286 }
2287 }
Tim Petersddea2082002-03-23 10:03:50 +00002288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002289 nbytes = read_size_t(q - 2*SST);
2290 tail = q + nbytes;
2291 for (i = 0; i < SST; ++i) {
2292 if (tail[i] != FORBIDDENBYTE) {
2293 msg = "bad trailing pad byte";
2294 goto error;
2295 }
2296 }
Tim Petersddea2082002-03-23 10:03:50 +00002297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002298 return;
Tim Petersd1139e02002-03-28 07:32:11 +00002299
2300error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002301 _PyObject_DebugDumpAddress(p);
2302 Py_FatalError(msg);
Tim Petersddea2082002-03-23 10:03:50 +00002303}
2304
Tim Peters7ccfadf2002-04-01 06:04:21 +00002305/* Display info to stderr about the memory block at p. */
Victor Stinner0507bf52013-07-07 02:05:46 +02002306static void
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00002307_PyObject_DebugDumpAddress(const void *p)
Tim Petersddea2082002-03-23 10:03:50 +00002308{
Benjamin Peterson19517e42016-09-18 19:22:22 -07002309 const uint8_t *q = (const uint8_t *)p;
2310 const uint8_t *tail;
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002311 size_t nbytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002312 int i;
2313 int ok;
2314 char id;
Tim Petersddea2082002-03-23 10:03:50 +00002315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002316 fprintf(stderr, "Debug memory block at address p=%p:", p);
2317 if (p == NULL) {
2318 fprintf(stderr, "\n");
2319 return;
2320 }
2321 id = (char)q[-SST];
2322 fprintf(stderr, " API '%c'\n", id);
Tim Petersddea2082002-03-23 10:03:50 +00002323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002324 nbytes = read_size_t(q - 2*SST);
2325 fprintf(stderr, " %" PY_FORMAT_SIZE_T "u bytes originally "
2326 "requested\n", nbytes);
Tim Petersddea2082002-03-23 10:03:50 +00002327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002328 /* In case this is nuts, check the leading pad bytes first. */
2329 fprintf(stderr, " The %d pad bytes at p-%d are ", SST-1, SST-1);
2330 ok = 1;
2331 for (i = 1; i <= SST-1; ++i) {
2332 if (*(q-i) != FORBIDDENBYTE) {
2333 ok = 0;
2334 break;
2335 }
2336 }
2337 if (ok)
2338 fputs("FORBIDDENBYTE, as expected.\n", stderr);
2339 else {
2340 fprintf(stderr, "not all FORBIDDENBYTE (0x%02x):\n",
2341 FORBIDDENBYTE);
2342 for (i = SST-1; i >= 1; --i) {
Benjamin Peterson19517e42016-09-18 19:22:22 -07002343 const uint8_t byte = *(q-i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002344 fprintf(stderr, " at p-%d: 0x%02x", i, byte);
2345 if (byte != FORBIDDENBYTE)
2346 fputs(" *** OUCH", stderr);
2347 fputc('\n', stderr);
2348 }
Tim Peters449b5a82002-04-28 06:14:45 +00002349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002350 fputs(" Because memory is corrupted at the start, the "
2351 "count of bytes requested\n"
2352 " may be bogus, and checking the trailing pad "
2353 "bytes may segfault.\n", stderr);
2354 }
Tim Petersddea2082002-03-23 10:03:50 +00002355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002356 tail = q + nbytes;
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002357 fprintf(stderr, " The %d pad bytes at tail=%p are ", SST, (void *)tail);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002358 ok = 1;
2359 for (i = 0; i < SST; ++i) {
2360 if (tail[i] != FORBIDDENBYTE) {
2361 ok = 0;
2362 break;
2363 }
2364 }
2365 if (ok)
2366 fputs("FORBIDDENBYTE, as expected.\n", stderr);
2367 else {
2368 fprintf(stderr, "not all FORBIDDENBYTE (0x%02x):\n",
Stefan Krah735bb122010-11-26 10:54:09 +00002369 FORBIDDENBYTE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002370 for (i = 0; i < SST; ++i) {
Benjamin Peterson19517e42016-09-18 19:22:22 -07002371 const uint8_t byte = tail[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002372 fprintf(stderr, " at tail+%d: 0x%02x",
Stefan Krah735bb122010-11-26 10:54:09 +00002373 i, byte);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002374 if (byte != FORBIDDENBYTE)
2375 fputs(" *** OUCH", stderr);
2376 fputc('\n', stderr);
2377 }
2378 }
Tim Petersddea2082002-03-23 10:03:50 +00002379
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002380#ifdef PYMEM_DEBUG_SERIALNO
2381 size_t serial = read_size_t(tail + SST);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002382 fprintf(stderr, " The block was made by call #%" PY_FORMAT_SIZE_T
2383 "u to debug malloc/realloc.\n", serial);
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002384#endif
Tim Petersddea2082002-03-23 10:03:50 +00002385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002386 if (nbytes > 0) {
2387 i = 0;
2388 fputs(" Data at p:", stderr);
2389 /* print up to 8 bytes at the start */
2390 while (q < tail && i < 8) {
2391 fprintf(stderr, " %02x", *q);
2392 ++i;
2393 ++q;
2394 }
2395 /* and up to 8 at the end */
2396 if (q < tail) {
2397 if (tail - q > 8) {
2398 fputs(" ...", stderr);
2399 q = tail - 8;
2400 }
2401 while (q < tail) {
2402 fprintf(stderr, " %02x", *q);
2403 ++q;
2404 }
2405 }
2406 fputc('\n', stderr);
2407 }
Victor Stinner0611c262016-03-15 22:22:13 +01002408 fputc('\n', stderr);
2409
2410 fflush(stderr);
2411 _PyMem_DumpTraceback(fileno(stderr), p);
Tim Petersddea2082002-03-23 10:03:50 +00002412}
2413
David Malcolm49526f42012-06-22 14:55:41 -04002414
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00002415static size_t
David Malcolm49526f42012-06-22 14:55:41 -04002416printone(FILE *out, const char* msg, size_t value)
Tim Peters16bcb6b2002-04-05 05:45:31 +00002417{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002418 int i, k;
2419 char buf[100];
2420 size_t origvalue = value;
Tim Peters16bcb6b2002-04-05 05:45:31 +00002421
David Malcolm49526f42012-06-22 14:55:41 -04002422 fputs(msg, out);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002423 for (i = (int)strlen(msg); i < 35; ++i)
David Malcolm49526f42012-06-22 14:55:41 -04002424 fputc(' ', out);
2425 fputc('=', out);
Tim Peters49f26812002-04-06 01:45:35 +00002426
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002427 /* Write the value with commas. */
2428 i = 22;
2429 buf[i--] = '\0';
2430 buf[i--] = '\n';
2431 k = 3;
2432 do {
2433 size_t nextvalue = value / 10;
Benjamin Peterson2dba1ee2013-02-20 16:54:30 -05002434 unsigned int digit = (unsigned int)(value - nextvalue * 10);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002435 value = nextvalue;
2436 buf[i--] = (char)(digit + '0');
2437 --k;
2438 if (k == 0 && value && i >= 0) {
2439 k = 3;
2440 buf[i--] = ',';
2441 }
2442 } while (value && i >= 0);
Tim Peters49f26812002-04-06 01:45:35 +00002443
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002444 while (i >= 0)
2445 buf[i--] = ' ';
David Malcolm49526f42012-06-22 14:55:41 -04002446 fputs(buf, out);
Tim Peters49f26812002-04-06 01:45:35 +00002447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002448 return origvalue;
Tim Peters16bcb6b2002-04-05 05:45:31 +00002449}
2450
David Malcolm49526f42012-06-22 14:55:41 -04002451void
2452_PyDebugAllocatorStats(FILE *out,
2453 const char *block_name, int num_blocks, size_t sizeof_block)
2454{
2455 char buf1[128];
2456 char buf2[128];
2457 PyOS_snprintf(buf1, sizeof(buf1),
Tim Peterseaa3bcc2013-09-05 22:57:04 -05002458 "%d %ss * %" PY_FORMAT_SIZE_T "d bytes each",
David Malcolm49526f42012-06-22 14:55:41 -04002459 num_blocks, block_name, sizeof_block);
2460 PyOS_snprintf(buf2, sizeof(buf2),
2461 "%48s ", buf1);
2462 (void)printone(out, buf2, num_blocks * sizeof_block);
2463}
2464
Victor Stinner34be807c2016-03-14 12:04:26 +01002465
David Malcolm49526f42012-06-22 14:55:41 -04002466#ifdef WITH_PYMALLOC
2467
Victor Stinner34be807c2016-03-14 12:04:26 +01002468#ifdef Py_DEBUG
2469/* Is target in the list? The list is traversed via the nextpool pointers.
2470 * The list may be NULL-terminated, or circular. Return 1 if target is in
2471 * list, else 0.
2472 */
2473static int
2474pool_is_in_list(const poolp target, poolp list)
2475{
2476 poolp origlist = list;
2477 assert(target != NULL);
2478 if (list == NULL)
2479 return 0;
2480 do {
2481 if (target == list)
2482 return 1;
2483 list = list->nextpool;
2484 } while (list != NULL && list != origlist);
2485 return 0;
2486}
2487#endif
2488
David Malcolm49526f42012-06-22 14:55:41 -04002489/* Print summary info to "out" about the state of pymalloc's structures.
Tim Peters08d82152002-04-18 22:25:03 +00002490 * In Py_DEBUG mode, also perform some expensive internal consistency
2491 * checks.
Victor Stinner6bf992a2017-12-06 17:26:10 +01002492 *
2493 * Return 0 if the memory debug hooks are not installed or no statistics was
Leo Ariasc3d95082018-02-03 18:36:10 -06002494 * written into out, return 1 otherwise.
Tim Peters08d82152002-04-18 22:25:03 +00002495 */
Victor Stinner6bf992a2017-12-06 17:26:10 +01002496int
David Malcolm49526f42012-06-22 14:55:41 -04002497_PyObject_DebugMallocStats(FILE *out)
Tim Peters7ccfadf2002-04-01 06:04:21 +00002498{
Victor Stinner6bf992a2017-12-06 17:26:10 +01002499 if (!_PyMem_PymallocEnabled()) {
2500 return 0;
2501 }
2502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002503 uint i;
2504 const uint numclasses = SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT;
2505 /* # of pools, allocated blocks, and free blocks per class index */
2506 size_t numpools[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT];
2507 size_t numblocks[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT];
2508 size_t numfreeblocks[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT];
2509 /* total # of allocated bytes in used and full pools */
2510 size_t allocated_bytes = 0;
2511 /* total # of available bytes in used pools */
2512 size_t available_bytes = 0;
2513 /* # of free pools + pools not yet carved out of current arena */
2514 uint numfreepools = 0;
2515 /* # of bytes for arena alignment padding */
2516 size_t arena_alignment = 0;
2517 /* # of bytes in used and full pools used for pool_headers */
2518 size_t pool_header_bytes = 0;
2519 /* # of bytes in used and full pools wasted due to quantization,
2520 * i.e. the necessarily leftover space at the ends of used and
2521 * full pools.
2522 */
2523 size_t quantization = 0;
2524 /* # of arenas actually allocated. */
2525 size_t narenas = 0;
2526 /* running total -- should equal narenas * ARENA_SIZE */
2527 size_t total;
2528 char buf[128];
Tim Peters7ccfadf2002-04-01 06:04:21 +00002529
David Malcolm49526f42012-06-22 14:55:41 -04002530 fprintf(out, "Small block threshold = %d, in %u size classes.\n",
Stefan Krah735bb122010-11-26 10:54:09 +00002531 SMALL_REQUEST_THRESHOLD, numclasses);
Tim Peters7ccfadf2002-04-01 06:04:21 +00002532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002533 for (i = 0; i < numclasses; ++i)
2534 numpools[i] = numblocks[i] = numfreeblocks[i] = 0;
Tim Peters7ccfadf2002-04-01 06:04:21 +00002535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002536 /* Because full pools aren't linked to from anything, it's easiest
2537 * to march over all the arenas. If we're lucky, most of the memory
2538 * will be living in full pools -- would be a shame to miss them.
2539 */
Victor Stinner9e87e772017-11-24 12:09:24 +01002540 for (i = 0; i < maxarenas; ++i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002541 uint j;
Victor Stinner9e87e772017-11-24 12:09:24 +01002542 uintptr_t base = arenas[i].address;
Thomas Woutersa9773292006-04-21 09:43:23 +00002543
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002544 /* Skip arenas which are not allocated. */
Victor Stinner9e87e772017-11-24 12:09:24 +01002545 if (arenas[i].address == (uintptr_t)NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002546 continue;
2547 narenas += 1;
Thomas Woutersa9773292006-04-21 09:43:23 +00002548
Victor Stinner9e87e772017-11-24 12:09:24 +01002549 numfreepools += arenas[i].nfreepools;
Tim Peters7ccfadf2002-04-01 06:04:21 +00002550
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002551 /* round up to pool alignment */
Benjamin Peterson5d4b09c2016-09-18 19:24:52 -07002552 if (base & (uintptr_t)POOL_SIZE_MASK) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002553 arena_alignment += POOL_SIZE;
Benjamin Peterson5d4b09c2016-09-18 19:24:52 -07002554 base &= ~(uintptr_t)POOL_SIZE_MASK;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002555 base += POOL_SIZE;
2556 }
Tim Peters7ccfadf2002-04-01 06:04:21 +00002557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002558 /* visit every pool in the arena */
Victor Stinner9e87e772017-11-24 12:09:24 +01002559 assert(base <= (uintptr_t) arenas[i].pool_address);
2560 for (j = 0; base < (uintptr_t) arenas[i].pool_address;
Benjamin Peterson19517e42016-09-18 19:22:22 -07002561 ++j, base += POOL_SIZE) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002562 poolp p = (poolp)base;
2563 const uint sz = p->szidx;
2564 uint freeblocks;
Tim Peters08d82152002-04-18 22:25:03 +00002565
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002566 if (p->ref.count == 0) {
2567 /* currently unused */
Victor Stinner34be807c2016-03-14 12:04:26 +01002568#ifdef Py_DEBUG
Victor Stinner9e87e772017-11-24 12:09:24 +01002569 assert(pool_is_in_list(p, arenas[i].freepools));
Victor Stinner34be807c2016-03-14 12:04:26 +01002570#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002571 continue;
2572 }
2573 ++numpools[sz];
2574 numblocks[sz] += p->ref.count;
2575 freeblocks = NUMBLOCKS(sz) - p->ref.count;
2576 numfreeblocks[sz] += freeblocks;
Tim Peters08d82152002-04-18 22:25:03 +00002577#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002578 if (freeblocks > 0)
Victor Stinner9e87e772017-11-24 12:09:24 +01002579 assert(pool_is_in_list(p, usedpools[sz + sz]));
Tim Peters08d82152002-04-18 22:25:03 +00002580#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002581 }
2582 }
Victor Stinner9e87e772017-11-24 12:09:24 +01002583 assert(narenas == narenas_currently_allocated);
Tim Peters7ccfadf2002-04-01 06:04:21 +00002584
David Malcolm49526f42012-06-22 14:55:41 -04002585 fputc('\n', out);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002586 fputs("class size num pools blocks in use avail blocks\n"
2587 "----- ---- --------- ------------- ------------\n",
David Malcolm49526f42012-06-22 14:55:41 -04002588 out);
Tim Peters7ccfadf2002-04-01 06:04:21 +00002589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002590 for (i = 0; i < numclasses; ++i) {
2591 size_t p = numpools[i];
2592 size_t b = numblocks[i];
2593 size_t f = numfreeblocks[i];
2594 uint size = INDEX2SIZE(i);
2595 if (p == 0) {
2596 assert(b == 0 && f == 0);
2597 continue;
2598 }
David Malcolm49526f42012-06-22 14:55:41 -04002599 fprintf(out, "%5u %6u "
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002600 "%11" PY_FORMAT_SIZE_T "u "
2601 "%15" PY_FORMAT_SIZE_T "u "
2602 "%13" PY_FORMAT_SIZE_T "u\n",
Stefan Krah735bb122010-11-26 10:54:09 +00002603 i, size, p, b, f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002604 allocated_bytes += b * size;
2605 available_bytes += f * size;
2606 pool_header_bytes += p * POOL_OVERHEAD;
2607 quantization += p * ((POOL_SIZE - POOL_OVERHEAD) % size);
2608 }
David Malcolm49526f42012-06-22 14:55:41 -04002609 fputc('\n', out);
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002610#ifdef PYMEM_DEBUG_SERIALNO
2611 if (_PyMem_DebugEnabled()) {
Victor Stinner9e87e772017-11-24 12:09:24 +01002612 (void)printone(out, "# times object malloc called", serialno);
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002613 }
2614#endif
Victor Stinner9e87e772017-11-24 12:09:24 +01002615 (void)printone(out, "# arenas allocated total", ntimes_arena_allocated);
2616 (void)printone(out, "# arenas reclaimed", ntimes_arena_allocated - narenas);
2617 (void)printone(out, "# arenas highwater mark", narenas_highwater);
David Malcolm49526f42012-06-22 14:55:41 -04002618 (void)printone(out, "# arenas allocated current", narenas);
Thomas Woutersa9773292006-04-21 09:43:23 +00002619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002620 PyOS_snprintf(buf, sizeof(buf),
2621 "%" PY_FORMAT_SIZE_T "u arenas * %d bytes/arena",
2622 narenas, ARENA_SIZE);
David Malcolm49526f42012-06-22 14:55:41 -04002623 (void)printone(out, buf, narenas * ARENA_SIZE);
Tim Peters16bcb6b2002-04-05 05:45:31 +00002624
David Malcolm49526f42012-06-22 14:55:41 -04002625 fputc('\n', out);
Tim Peters16bcb6b2002-04-05 05:45:31 +00002626
David Malcolm49526f42012-06-22 14:55:41 -04002627 total = printone(out, "# bytes in allocated blocks", allocated_bytes);
2628 total += printone(out, "# bytes in available blocks", available_bytes);
Tim Peters49f26812002-04-06 01:45:35 +00002629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002630 PyOS_snprintf(buf, sizeof(buf),
2631 "%u unused pools * %d bytes", numfreepools, POOL_SIZE);
David Malcolm49526f42012-06-22 14:55:41 -04002632 total += printone(out, buf, (size_t)numfreepools * POOL_SIZE);
Tim Peters16bcb6b2002-04-05 05:45:31 +00002633
David Malcolm49526f42012-06-22 14:55:41 -04002634 total += printone(out, "# bytes lost to pool headers", pool_header_bytes);
2635 total += printone(out, "# bytes lost to quantization", quantization);
2636 total += printone(out, "# bytes lost to arena alignment", arena_alignment);
2637 (void)printone(out, "Total", total);
Victor Stinner6bf992a2017-12-06 17:26:10 +01002638 return 1;
Tim Peters7ccfadf2002-04-01 06:04:21 +00002639}
2640
David Malcolm49526f42012-06-22 14:55:41 -04002641#endif /* #ifdef WITH_PYMALLOC */