blob: bd15bcf1363bdecf7cd05e65dc6316830003511e [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 */
Inada Naokif0be4bb2019-05-14 18:51:15 +0900798
799#if SIZEOF_VOID_P > 4
800#define ALIGNMENT 16 /* must be 2^N */
801#define ALIGNMENT_SHIFT 4
802#else
Victor Stinner9e87e772017-11-24 12:09:24 +0100803#define ALIGNMENT 8 /* must be 2^N */
804#define ALIGNMENT_SHIFT 3
Inada Naokif0be4bb2019-05-14 18:51:15 +0900805#endif
Victor Stinner9e87e772017-11-24 12:09:24 +0100806
807/* Return the number of bytes in size class I, as a uint. */
808#define INDEX2SIZE(I) (((uint)(I) + 1) << ALIGNMENT_SHIFT)
809
810/*
811 * Max size threshold below which malloc requests are considered to be
812 * small enough in order to use preallocated memory pools. You can tune
813 * this value according to your application behaviour and memory needs.
814 *
815 * Note: a size threshold of 512 guarantees that newly created dictionaries
816 * will be allocated from preallocated memory pools on 64-bit.
817 *
818 * The following invariants must hold:
819 * 1) ALIGNMENT <= SMALL_REQUEST_THRESHOLD <= 512
820 * 2) SMALL_REQUEST_THRESHOLD is evenly divisible by ALIGNMENT
821 *
822 * Although not required, for better performance and space efficiency,
823 * it is recommended that SMALL_REQUEST_THRESHOLD is set to a power of 2.
824 */
825#define SMALL_REQUEST_THRESHOLD 512
826#define NB_SMALL_SIZE_CLASSES (SMALL_REQUEST_THRESHOLD / ALIGNMENT)
827
828/*
829 * The system's VMM page size can be obtained on most unices with a
830 * getpagesize() call or deduced from various header files. To make
831 * things simpler, we assume that it is 4K, which is OK for most systems.
832 * It is probably better if this is the native page size, but it doesn't
833 * have to be. In theory, if SYSTEM_PAGE_SIZE is larger than the native page
834 * size, then `POOL_ADDR(p)->arenaindex' could rarely cause a segmentation
835 * violation fault. 4K is apparently OK for all the platforms that python
836 * currently targets.
837 */
838#define SYSTEM_PAGE_SIZE (4 * 1024)
839#define SYSTEM_PAGE_SIZE_MASK (SYSTEM_PAGE_SIZE - 1)
840
841/*
842 * Maximum amount of memory managed by the allocator for small requests.
843 */
844#ifdef WITH_MEMORY_LIMITS
845#ifndef SMALL_MEMORY_LIMIT
846#define SMALL_MEMORY_LIMIT (64 * 1024 * 1024) /* 64 MB -- more? */
847#endif
848#endif
849
850/*
851 * The allocator sub-allocates <Big> blocks of memory (called arenas) aligned
852 * on a page boundary. This is a reserved virtual address space for the
853 * current process (obtained through a malloc()/mmap() call). In no way this
854 * means that the memory arenas will be used entirely. A malloc(<Big>) is
855 * usually an address range reservation for <Big> bytes, unless all pages within
856 * this space are referenced subsequently. So malloc'ing big blocks and not
857 * using them does not mean "wasting memory". It's an addressable range
858 * wastage...
859 *
860 * Arenas are allocated with mmap() on systems supporting anonymous memory
861 * mappings to reduce heap fragmentation.
862 */
863#define ARENA_SIZE (256 << 10) /* 256KB */
864
865#ifdef WITH_MEMORY_LIMITS
866#define MAX_ARENAS (SMALL_MEMORY_LIMIT / ARENA_SIZE)
867#endif
868
869/*
870 * Size of the pools used for small blocks. Should be a power of 2,
871 * between 1K and SYSTEM_PAGE_SIZE, that is: 1k, 2k, 4k.
872 */
873#define POOL_SIZE SYSTEM_PAGE_SIZE /* must be 2^N */
874#define POOL_SIZE_MASK SYSTEM_PAGE_SIZE_MASK
875
876/*
877 * -- End of tunable settings section --
878 */
879
880/*==========================================================================*/
881
Victor Stinner9e87e772017-11-24 12:09:24 +0100882/* When you say memory, my mind reasons in terms of (pointers to) blocks */
883typedef uint8_t block;
884
885/* Pool for small blocks. */
886struct pool_header {
887 union { block *_padding;
888 uint count; } ref; /* number of allocated blocks */
889 block *freeblock; /* pool's free list head */
890 struct pool_header *nextpool; /* next pool of this size class */
891 struct pool_header *prevpool; /* previous pool "" */
892 uint arenaindex; /* index into arenas of base adr */
893 uint szidx; /* block size class index */
894 uint nextoffset; /* bytes to virgin block */
895 uint maxnextoffset; /* largest valid nextoffset */
896};
897
898typedef struct pool_header *poolp;
899
900/* Record keeping for arenas. */
901struct arena_object {
902 /* The address of the arena, as returned by malloc. Note that 0
903 * will never be returned by a successful malloc, and is used
904 * here to mark an arena_object that doesn't correspond to an
905 * allocated arena.
906 */
907 uintptr_t address;
908
909 /* Pool-aligned pointer to the next pool to be carved off. */
910 block* pool_address;
911
912 /* The number of available pools in the arena: free pools + never-
913 * allocated pools.
914 */
915 uint nfreepools;
916
917 /* The total number of pools in the arena, whether or not available. */
918 uint ntotalpools;
919
920 /* Singly-linked list of available pools. */
921 struct pool_header* freepools;
922
923 /* Whenever this arena_object is not associated with an allocated
924 * arena, the nextarena member is used to link all unassociated
925 * arena_objects in the singly-linked `unused_arena_objects` list.
926 * The prevarena member is unused in this case.
927 *
928 * When this arena_object is associated with an allocated arena
929 * with at least one available pool, both members are used in the
930 * doubly-linked `usable_arenas` list, which is maintained in
931 * increasing order of `nfreepools` values.
932 *
933 * Else this arena_object is associated with an allocated arena
934 * all of whose pools are in use. `nextarena` and `prevarena`
935 * are both meaningless in this case.
936 */
937 struct arena_object* nextarena;
938 struct arena_object* prevarena;
939};
940
941#define POOL_OVERHEAD _Py_SIZE_ROUND_UP(sizeof(struct pool_header), ALIGNMENT)
942
943#define DUMMY_SIZE_IDX 0xffff /* size class of newly cached pools */
944
945/* Round pointer P down to the closest pool-aligned address <= P, as a poolp */
946#define POOL_ADDR(P) ((poolp)_Py_ALIGN_DOWN((P), POOL_SIZE))
947
948/* Return total number of blocks in pool of size index I, as a uint. */
949#define NUMBLOCKS(I) ((uint)(POOL_SIZE - POOL_OVERHEAD) / INDEX2SIZE(I))
950
951/*==========================================================================*/
952
953/*
Victor Stinner9e87e772017-11-24 12:09:24 +0100954 * Pool table -- headed, circular, doubly-linked lists of partially used pools.
955
956This is involved. For an index i, usedpools[i+i] is the header for a list of
957all partially used pools holding small blocks with "size class idx" i. So
958usedpools[0] corresponds to blocks of size 8, usedpools[2] to blocks of size
95916, and so on: index 2*i <-> blocks of size (i+1)<<ALIGNMENT_SHIFT.
960
961Pools are carved off an arena's highwater mark (an arena_object's pool_address
962member) as needed. Once carved off, a pool is in one of three states forever
963after:
964
965used == partially used, neither empty nor full
966 At least one block in the pool is currently allocated, and at least one
967 block in the pool is not currently allocated (note this implies a pool
968 has room for at least two blocks).
969 This is a pool's initial state, as a pool is created only when malloc
970 needs space.
971 The pool holds blocks of a fixed size, and is in the circular list headed
972 at usedpools[i] (see above). It's linked to the other used pools of the
973 same size class via the pool_header's nextpool and prevpool members.
974 If all but one block is currently allocated, a malloc can cause a
975 transition to the full state. If all but one block is not currently
976 allocated, a free can cause a transition to the empty state.
977
978full == all the pool's blocks are currently allocated
979 On transition to full, a pool is unlinked from its usedpools[] list.
980 It's not linked to from anything then anymore, and its nextpool and
981 prevpool members are meaningless until it transitions back to used.
982 A free of a block in a full pool puts the pool back in the used state.
983 Then it's linked in at the front of the appropriate usedpools[] list, so
984 that the next allocation for its size class will reuse the freed block.
985
986empty == all the pool's blocks are currently available for allocation
987 On transition to empty, a pool is unlinked from its usedpools[] list,
988 and linked to the front of its arena_object's singly-linked freepools list,
989 via its nextpool member. The prevpool member has no meaning in this case.
990 Empty pools have no inherent size class: the next time a malloc finds
991 an empty list in usedpools[], it takes the first pool off of freepools.
992 If the size class needed happens to be the same as the size class the pool
993 last had, some pool initialization can be skipped.
994
995
996Block Management
997
998Blocks within pools are again carved out as needed. pool->freeblock points to
999the start of a singly-linked list of free blocks within the pool. When a
1000block is freed, it's inserted at the front of its pool's freeblock list. Note
1001that the available blocks in a pool are *not* linked all together when a pool
1002is initialized. Instead only "the first two" (lowest addresses) blocks are
1003set up, returning the first such block, and setting pool->freeblock to a
1004one-block list holding the second such block. This is consistent with that
1005pymalloc strives at all levels (arena, pool, and block) never to touch a piece
1006of memory until it's actually needed.
1007
1008So long as a pool is in the used state, we're certain there *is* a block
1009available for allocating, and pool->freeblock is not NULL. If pool->freeblock
1010points to the end of the free list before we've carved the entire pool into
1011blocks, that means we simply haven't yet gotten to one of the higher-address
1012blocks. The offset from the pool_header to the start of "the next" virgin
1013block is stored in the pool_header nextoffset member, and the largest value
1014of nextoffset that makes sense is stored in the maxnextoffset member when a
1015pool is initialized. All the blocks in a pool have been passed out at least
1016once when and only when nextoffset > maxnextoffset.
1017
1018
1019Major obscurity: While the usedpools vector is declared to have poolp
1020entries, it doesn't really. It really contains two pointers per (conceptual)
1021poolp entry, the nextpool and prevpool members of a pool_header. The
1022excruciating initialization code below fools C so that
1023
1024 usedpool[i+i]
1025
1026"acts like" a genuine poolp, but only so long as you only reference its
1027nextpool and prevpool members. The "- 2*sizeof(block *)" gibberish is
1028compensating for that a pool_header's nextpool and prevpool members
1029immediately follow a pool_header's first two members:
1030
1031 union { block *_padding;
1032 uint count; } ref;
1033 block *freeblock;
1034
1035each of which consume sizeof(block *) bytes. So what usedpools[i+i] really
1036contains is a fudged-up pointer p such that *if* C believes it's a poolp
1037pointer, then p->nextpool and p->prevpool are both p (meaning that the headed
1038circular list is empty).
1039
1040It's unclear why the usedpools setup is so convoluted. It could be to
1041minimize the amount of cache required to hold this heavily-referenced table
1042(which only *needs* the two interpool pointer members of a pool_header). OTOH,
1043referencing code has to remember to "double the index" and doing so isn't
1044free, usedpools[0] isn't a strictly legal pointer, and we're crucially relying
1045on that C doesn't insert any padding anywhere in a pool_header at or before
1046the prevpool member.
1047**************************************************************************** */
1048
1049#define PTA(x) ((poolp )((uint8_t *)&(usedpools[2*(x)]) - 2*sizeof(block *)))
1050#define PT(x) PTA(x), PTA(x)
1051
1052static poolp usedpools[2 * ((NB_SMALL_SIZE_CLASSES + 7) / 8) * 8] = {
1053 PT(0), PT(1), PT(2), PT(3), PT(4), PT(5), PT(6), PT(7)
1054#if NB_SMALL_SIZE_CLASSES > 8
1055 , PT(8), PT(9), PT(10), PT(11), PT(12), PT(13), PT(14), PT(15)
1056#if NB_SMALL_SIZE_CLASSES > 16
1057 , PT(16), PT(17), PT(18), PT(19), PT(20), PT(21), PT(22), PT(23)
1058#if NB_SMALL_SIZE_CLASSES > 24
1059 , PT(24), PT(25), PT(26), PT(27), PT(28), PT(29), PT(30), PT(31)
1060#if NB_SMALL_SIZE_CLASSES > 32
1061 , PT(32), PT(33), PT(34), PT(35), PT(36), PT(37), PT(38), PT(39)
1062#if NB_SMALL_SIZE_CLASSES > 40
1063 , PT(40), PT(41), PT(42), PT(43), PT(44), PT(45), PT(46), PT(47)
1064#if NB_SMALL_SIZE_CLASSES > 48
1065 , PT(48), PT(49), PT(50), PT(51), PT(52), PT(53), PT(54), PT(55)
1066#if NB_SMALL_SIZE_CLASSES > 56
1067 , PT(56), PT(57), PT(58), PT(59), PT(60), PT(61), PT(62), PT(63)
1068#if NB_SMALL_SIZE_CLASSES > 64
1069#error "NB_SMALL_SIZE_CLASSES should be less than 64"
1070#endif /* NB_SMALL_SIZE_CLASSES > 64 */
1071#endif /* NB_SMALL_SIZE_CLASSES > 56 */
1072#endif /* NB_SMALL_SIZE_CLASSES > 48 */
1073#endif /* NB_SMALL_SIZE_CLASSES > 40 */
1074#endif /* NB_SMALL_SIZE_CLASSES > 32 */
1075#endif /* NB_SMALL_SIZE_CLASSES > 24 */
1076#endif /* NB_SMALL_SIZE_CLASSES > 16 */
1077#endif /* NB_SMALL_SIZE_CLASSES > 8 */
1078};
1079
1080/*==========================================================================
1081Arena management.
1082
1083`arenas` is a vector of arena_objects. It contains maxarenas entries, some of
1084which may not be currently used (== they're arena_objects that aren't
1085currently associated with an allocated arena). Note that arenas proper are
1086separately malloc'ed.
1087
1088Prior to Python 2.5, arenas were never free()'ed. Starting with Python 2.5,
1089we do try to free() arenas, and use some mild heuristic strategies to increase
1090the likelihood that arenas eventually can be freed.
1091
1092unused_arena_objects
1093
1094 This is a singly-linked list of the arena_objects that are currently not
1095 being used (no arena is associated with them). Objects are taken off the
1096 head of the list in new_arena(), and are pushed on the head of the list in
1097 PyObject_Free() when the arena is empty. Key invariant: an arena_object
1098 is on this list if and only if its .address member is 0.
1099
1100usable_arenas
1101
1102 This is a doubly-linked list of the arena_objects associated with arenas
1103 that have pools available. These pools are either waiting to be reused,
1104 or have not been used before. The list is sorted to have the most-
1105 allocated arenas first (ascending order based on the nfreepools member).
1106 This means that the next allocation will come from a heavily used arena,
1107 which gives the nearly empty arenas a chance to be returned to the system.
1108 In my unscientific tests this dramatically improved the number of arenas
1109 that could be freed.
1110
1111Note that an arena_object associated with an arena all of whose pools are
1112currently in use isn't on either list.
1113*/
1114
1115/* Array of objects used to track chunks of memory (arenas). */
1116static struct arena_object* arenas = NULL;
1117/* Number of slots currently allocated in the `arenas` vector. */
1118static uint maxarenas = 0;
1119
1120/* The head of the singly-linked, NULL-terminated list of available
1121 * arena_objects.
1122 */
1123static struct arena_object* unused_arena_objects = NULL;
1124
1125/* The head of the doubly-linked, NULL-terminated at each end, list of
1126 * arena_objects associated with arenas that have pools available.
1127 */
1128static struct arena_object* usable_arenas = NULL;
1129
1130/* How many arena_objects do we initially allocate?
1131 * 16 = can allocate 16 arenas = 16 * ARENA_SIZE = 4MB before growing the
1132 * `arenas` vector.
1133 */
1134#define INITIAL_ARENA_OBJECTS 16
1135
1136/* Number of arenas allocated that haven't been free()'d. */
1137static size_t narenas_currently_allocated = 0;
1138
1139/* Total number of times malloc() called to allocate an arena. */
1140static size_t ntimes_arena_allocated = 0;
1141/* High water mark (max value ever seen) for narenas_currently_allocated. */
1142static size_t narenas_highwater = 0;
1143
1144static Py_ssize_t _Py_AllocatedBlocks = 0;
1145
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001146Py_ssize_t
1147_Py_GetAllocatedBlocks(void)
1148{
Victor Stinner9e87e772017-11-24 12:09:24 +01001149 return _Py_AllocatedBlocks;
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001150}
1151
1152
Thomas Woutersa9773292006-04-21 09:43:23 +00001153/* Allocate a new arena. If we run out of memory, return NULL. Else
1154 * allocate a new arena, and return the address of an arena_object
1155 * describing the new arena. It's expected that the caller will set
1156 * `usable_arenas` to the return value.
1157 */
1158static struct arena_object*
Tim Petersd97a1c02002-03-30 06:09:22 +00001159new_arena(void)
1160{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001161 struct arena_object* arenaobj;
1162 uint excess; /* number of bytes above pool alignment */
Victor Stinnerba108822012-03-10 00:21:44 +01001163 void *address;
Victor Stinner34be807c2016-03-14 12:04:26 +01001164 static int debug_stats = -1;
Tim Petersd97a1c02002-03-30 06:09:22 +00001165
Victor Stinner34be807c2016-03-14 12:04:26 +01001166 if (debug_stats == -1) {
Serhiy Storchaka4ae06c52017-12-12 13:55:04 +02001167 const char *opt = Py_GETENV("PYTHONMALLOCSTATS");
Victor Stinner34be807c2016-03-14 12:04:26 +01001168 debug_stats = (opt != NULL && *opt != '\0');
1169 }
1170 if (debug_stats)
David Malcolm49526f42012-06-22 14:55:41 -04001171 _PyObject_DebugMallocStats(stderr);
Victor Stinner34be807c2016-03-14 12:04:26 +01001172
Victor Stinner9e87e772017-11-24 12:09:24 +01001173 if (unused_arena_objects == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001174 uint i;
1175 uint numarenas;
1176 size_t nbytes;
Tim Peters0e871182002-04-13 08:29:14 +00001177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001178 /* Double the number of arena objects on each allocation.
1179 * Note that it's possible for `numarenas` to overflow.
1180 */
Victor Stinner9e87e772017-11-24 12:09:24 +01001181 numarenas = maxarenas ? maxarenas << 1 : INITIAL_ARENA_OBJECTS;
1182 if (numarenas <= maxarenas)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 return NULL; /* overflow */
Martin v. Löwis5aca8822008-09-11 06:55:48 +00001184#if SIZEOF_SIZE_T <= SIZEOF_INT
Victor Stinner9e87e772017-11-24 12:09:24 +01001185 if (numarenas > SIZE_MAX / sizeof(*arenas))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001186 return NULL; /* overflow */
Martin v. Löwis5aca8822008-09-11 06:55:48 +00001187#endif
Victor Stinner9e87e772017-11-24 12:09:24 +01001188 nbytes = numarenas * sizeof(*arenas);
1189 arenaobj = (struct arena_object *)PyMem_RawRealloc(arenas, nbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001190 if (arenaobj == NULL)
1191 return NULL;
Victor Stinner9e87e772017-11-24 12:09:24 +01001192 arenas = arenaobj;
Thomas Woutersa9773292006-04-21 09:43:23 +00001193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 /* We might need to fix pointers that were copied. However,
1195 * new_arena only gets called when all the pages in the
1196 * previous arenas are full. Thus, there are *no* pointers
1197 * into the old array. Thus, we don't have to worry about
1198 * invalid pointers. Just to be sure, some asserts:
1199 */
Victor Stinner9e87e772017-11-24 12:09:24 +01001200 assert(usable_arenas == NULL);
1201 assert(unused_arena_objects == NULL);
Thomas Woutersa9773292006-04-21 09:43:23 +00001202
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001203 /* Put the new arenas on the unused_arena_objects list. */
Victor Stinner9e87e772017-11-24 12:09:24 +01001204 for (i = maxarenas; i < numarenas; ++i) {
1205 arenas[i].address = 0; /* mark as unassociated */
1206 arenas[i].nextarena = i < numarenas - 1 ?
1207 &arenas[i+1] : NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001208 }
Thomas Woutersa9773292006-04-21 09:43:23 +00001209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001210 /* Update globals. */
Victor Stinner9e87e772017-11-24 12:09:24 +01001211 unused_arena_objects = &arenas[maxarenas];
1212 maxarenas = numarenas;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 }
Tim Petersd97a1c02002-03-30 06:09:22 +00001214
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001215 /* Take the next available arena object off the head of the list. */
Victor Stinner9e87e772017-11-24 12:09:24 +01001216 assert(unused_arena_objects != NULL);
1217 arenaobj = unused_arena_objects;
1218 unused_arena_objects = arenaobj->nextarena;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001219 assert(arenaobj->address == 0);
Victor Stinner9e87e772017-11-24 12:09:24 +01001220 address = _PyObject_Arena.alloc(_PyObject_Arena.ctx, ARENA_SIZE);
Victor Stinner0507bf52013-07-07 02:05:46 +02001221 if (address == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001222 /* The allocation failed: return NULL after putting the
1223 * arenaobj back.
1224 */
Victor Stinner9e87e772017-11-24 12:09:24 +01001225 arenaobj->nextarena = unused_arena_objects;
1226 unused_arena_objects = arenaobj;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001227 return NULL;
1228 }
Benjamin Peterson5d4b09c2016-09-18 19:24:52 -07001229 arenaobj->address = (uintptr_t)address;
Tim Petersd97a1c02002-03-30 06:09:22 +00001230
Victor Stinner9e87e772017-11-24 12:09:24 +01001231 ++narenas_currently_allocated;
1232 ++ntimes_arena_allocated;
1233 if (narenas_currently_allocated > narenas_highwater)
1234 narenas_highwater = narenas_currently_allocated;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001235 arenaobj->freepools = NULL;
1236 /* pool_address <- first pool-aligned address in the arena
1237 nfreepools <- number of whole pools that fit after alignment */
Victor Stinner9e87e772017-11-24 12:09:24 +01001238 arenaobj->pool_address = (block*)arenaobj->address;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001239 arenaobj->nfreepools = ARENA_SIZE / POOL_SIZE;
1240 assert(POOL_SIZE * arenaobj->nfreepools == ARENA_SIZE);
1241 excess = (uint)(arenaobj->address & POOL_SIZE_MASK);
1242 if (excess != 0) {
1243 --arenaobj->nfreepools;
1244 arenaobj->pool_address += POOL_SIZE - excess;
1245 }
1246 arenaobj->ntotalpools = arenaobj->nfreepools;
Thomas Woutersa9773292006-04-21 09:43:23 +00001247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001248 return arenaobj;
Tim Petersd97a1c02002-03-30 06:09:22 +00001249}
1250
Victor Stinner9ed83c42017-10-31 12:18:10 -07001251
Thomas Woutersa9773292006-04-21 09:43:23 +00001252/*
Benjamin Peterson3924f932016-09-18 19:12:48 -07001253address_in_range(P, POOL)
Thomas Woutersa9773292006-04-21 09:43:23 +00001254
1255Return true if and only if P is an address that was allocated by pymalloc.
1256POOL must be the pool address associated with P, i.e., POOL = POOL_ADDR(P)
1257(the caller is asked to compute this because the macro expands POOL more than
1258once, and for efficiency it's best for the caller to assign POOL_ADDR(P) to a
Benjamin Peterson3924f932016-09-18 19:12:48 -07001259variable and pass the latter to the macro; because address_in_range is
Thomas Woutersa9773292006-04-21 09:43:23 +00001260called on every alloc/realloc/free, micro-efficiency is important here).
1261
1262Tricky: Let B be the arena base address associated with the pool, B =
1263arenas[(POOL)->arenaindex].address. Then P belongs to the arena if and only if
1264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001265 B <= P < B + ARENA_SIZE
Thomas Woutersa9773292006-04-21 09:43:23 +00001266
1267Subtracting B throughout, this is true iff
1268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001269 0 <= P-B < ARENA_SIZE
Thomas Woutersa9773292006-04-21 09:43:23 +00001270
1271By using unsigned arithmetic, the "0 <=" half of the test can be skipped.
1272
1273Obscure: A PyMem "free memory" function can call the pymalloc free or realloc
1274before the first arena has been allocated. `arenas` is still NULL in that
1275case. We're relying on that maxarenas is also 0 in that case, so that
1276(POOL)->arenaindex < maxarenas must be false, saving us from trying to index
1277into a NULL arenas.
1278
1279Details: given P and POOL, the arena_object corresponding to P is AO =
1280arenas[(POOL)->arenaindex]. Suppose obmalloc controls P. Then (barring wild
1281stores, etc), POOL is the correct address of P's pool, AO.address is the
1282correct base address of the pool's arena, and P must be within ARENA_SIZE of
1283AO.address. In addition, AO.address is not 0 (no arena can start at address 0
Benjamin Peterson3924f932016-09-18 19:12:48 -07001284(NULL)). Therefore address_in_range correctly reports that obmalloc
Thomas Woutersa9773292006-04-21 09:43:23 +00001285controls P.
1286
1287Now suppose obmalloc does not control P (e.g., P was obtained via a direct
1288call to the system malloc() or realloc()). (POOL)->arenaindex may be anything
1289in this case -- it may even be uninitialized trash. If the trash arenaindex
1290is >= maxarenas, the macro correctly concludes at once that obmalloc doesn't
1291control P.
1292
1293Else arenaindex is < maxarena, and AO is read up. If AO corresponds to an
1294allocated arena, obmalloc controls all the memory in slice AO.address :
1295AO.address+ARENA_SIZE. By case assumption, P is not controlled by obmalloc,
1296so P doesn't lie in that slice, so the macro correctly reports that P is not
1297controlled by obmalloc.
1298
1299Finally, if P is not controlled by obmalloc and AO corresponds to an unused
1300arena_object (one not currently associated with an allocated arena),
1301AO.address is 0, and the second test in the macro reduces to:
1302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001303 P < ARENA_SIZE
Thomas Woutersa9773292006-04-21 09:43:23 +00001304
1305If P >= ARENA_SIZE (extremely likely), the macro again correctly concludes
1306that P is not controlled by obmalloc. However, if P < ARENA_SIZE, this part
1307of the test still passes, and the third clause (AO.address != 0) is necessary
1308to get the correct result: AO.address is 0 in this case, so the macro
1309correctly reports that P is not controlled by obmalloc (despite that P lies in
1310slice AO.address : AO.address + ARENA_SIZE).
1311
1312Note: The third (AO.address != 0) clause was added in Python 2.5. Before
13132.5, arenas were never free()'ed, and an arenaindex < maxarena always
1314corresponded to a currently-allocated arena, so the "P is not controlled by
1315obmalloc, AO corresponds to an unused arena_object, and P < ARENA_SIZE" case
1316was impossible.
1317
1318Note that the logic is excruciating, and reading up possibly uninitialized
1319memory when P is not controlled by obmalloc (to get at (POOL)->arenaindex)
1320creates problems for some memory debuggers. The overwhelming advantage is
1321that this test determines whether an arbitrary address is controlled by
1322obmalloc in a small constant time, independent of the number of arenas
1323obmalloc controls. Since this test is needed at every entry point, it's
1324extremely desirable that it be this fast.
1325*/
Thomas Woutersa9773292006-04-21 09:43:23 +00001326
Alexey Izbyshevfd3a91c2018-11-12 02:14:51 +03001327static bool _Py_NO_ADDRESS_SAFETY_ANALYSIS
1328 _Py_NO_SANITIZE_THREAD
1329 _Py_NO_SANITIZE_MEMORY
Benjamin Peterson3924f932016-09-18 19:12:48 -07001330address_in_range(void *p, poolp pool)
1331{
1332 // Since address_in_range may be reading from memory which was not allocated
1333 // by Python, it is important that pool->arenaindex is read only once, as
1334 // another thread may be concurrently modifying the value without holding
1335 // the GIL. The following dance forces the compiler to read pool->arenaindex
1336 // only once.
1337 uint arenaindex = *((volatile uint *)&pool->arenaindex);
Victor Stinner9e87e772017-11-24 12:09:24 +01001338 return arenaindex < maxarenas &&
1339 (uintptr_t)p - arenas[arenaindex].address < ARENA_SIZE &&
1340 arenas[arenaindex].address != 0;
Benjamin Peterson3924f932016-09-18 19:12:48 -07001341}
Tim Peters338e0102002-04-01 19:23:44 +00001342
Victor Stinner9ed83c42017-10-31 12:18:10 -07001343
Neil Schemenauera35c6882001-02-27 04:45:05 +00001344/*==========================================================================*/
1345
Victor Stinner9ed83c42017-10-31 12:18:10 -07001346/* pymalloc allocator
Neil Schemenauera35c6882001-02-27 04:45:05 +00001347
Victor Stinner9ed83c42017-10-31 12:18:10 -07001348 The basic blocks are ordered by decreasing execution frequency,
1349 which minimizes the number of jumps in the most common cases,
1350 improves branching prediction and instruction scheduling (small
1351 block allocations typically result in a couple of instructions).
1352 Unless the optimizer reorders everything, being too smart...
Neil Schemenauera35c6882001-02-27 04:45:05 +00001353
Victor Stinner9ed83c42017-10-31 12:18:10 -07001354 Return 1 if pymalloc allocated memory and wrote the pointer into *ptr_p.
1355
1356 Return 0 if pymalloc failed to allocate the memory block: on bigger
1357 requests, on error in the code below (as a last chance to serve the request)
1358 or when the max memory limit has been reached. */
1359static int
1360pymalloc_alloc(void *ctx, void **ptr_p, size_t nbytes)
Neil Schemenauera35c6882001-02-27 04:45:05 +00001361{
Victor Stinner9e87e772017-11-24 12:09:24 +01001362 block *bp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001363 poolp pool;
1364 poolp next;
1365 uint size;
Neil Schemenauera35c6882001-02-27 04:45:05 +00001366
Benjamin Peterson05159c42009-12-03 03:01:27 +00001367#ifdef WITH_VALGRIND
Victor Stinner9ed83c42017-10-31 12:18:10 -07001368 if (UNLIKELY(running_on_valgrind == -1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001369 running_on_valgrind = RUNNING_ON_VALGRIND;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001370 }
1371 if (UNLIKELY(running_on_valgrind)) {
1372 return 0;
1373 }
Benjamin Peterson05159c42009-12-03 03:01:27 +00001374#endif
1375
Victor Stinner9ed83c42017-10-31 12:18:10 -07001376 if (nbytes == 0) {
1377 return 0;
1378 }
1379 if (nbytes > SMALL_REQUEST_THRESHOLD) {
1380 return 0;
1381 }
T. Wouters06bb4872017-03-31 10:10:19 -07001382
Victor Stinner9ed83c42017-10-31 12:18:10 -07001383 /*
1384 * Most frequent paths first
1385 */
1386 size = (uint)(nbytes - 1) >> ALIGNMENT_SHIFT;
Victor Stinner9e87e772017-11-24 12:09:24 +01001387 pool = usedpools[size + size];
Victor Stinner9ed83c42017-10-31 12:18:10 -07001388 if (pool != pool->nextpool) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001389 /*
Victor Stinner9ed83c42017-10-31 12:18:10 -07001390 * There is a used pool for this size class.
1391 * Pick up the head block of its free list.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001392 */
Victor Stinner9ed83c42017-10-31 12:18:10 -07001393 ++pool->ref.count;
1394 bp = pool->freeblock;
1395 assert(bp != NULL);
Victor Stinner9e87e772017-11-24 12:09:24 +01001396 if ((pool->freeblock = *(block **)bp) != NULL) {
Victor Stinner9ed83c42017-10-31 12:18:10 -07001397 goto success;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001398 }
Thomas Woutersa9773292006-04-21 09:43:23 +00001399
Victor Stinner9ed83c42017-10-31 12:18:10 -07001400 /*
1401 * Reached the end of the free list, try to extend it.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001402 */
Victor Stinner9ed83c42017-10-31 12:18:10 -07001403 if (pool->nextoffset <= pool->maxnextoffset) {
1404 /* There is room for another block. */
Victor Stinner9e87e772017-11-24 12:09:24 +01001405 pool->freeblock = (block*)pool +
Victor Stinner9ed83c42017-10-31 12:18:10 -07001406 pool->nextoffset;
1407 pool->nextoffset += INDEX2SIZE(size);
Victor Stinner9e87e772017-11-24 12:09:24 +01001408 *(block **)(pool->freeblock) = NULL;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001409 goto success;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 }
Thomas Woutersa9773292006-04-21 09:43:23 +00001411
Victor Stinner9ed83c42017-10-31 12:18:10 -07001412 /* Pool is full, unlink from used pools. */
1413 next = pool->nextpool;
1414 pool = pool->prevpool;
1415 next->prevpool = pool;
1416 pool->nextpool = next;
1417 goto success;
1418 }
Thomas Woutersa9773292006-04-21 09:43:23 +00001419
Victor Stinner9ed83c42017-10-31 12:18:10 -07001420 /* There isn't a pool of the right size class immediately
1421 * available: use a free pool.
1422 */
Victor Stinner9e87e772017-11-24 12:09:24 +01001423 if (usable_arenas == NULL) {
Victor Stinner9ed83c42017-10-31 12:18:10 -07001424 /* No arena has a free pool: allocate a new arena. */
1425#ifdef WITH_MEMORY_LIMITS
Victor Stinner9e87e772017-11-24 12:09:24 +01001426 if (narenas_currently_allocated >= MAX_ARENAS) {
Victor Stinner9ed83c42017-10-31 12:18:10 -07001427 goto failed;
1428 }
1429#endif
Victor Stinner9e87e772017-11-24 12:09:24 +01001430 usable_arenas = new_arena();
1431 if (usable_arenas == NULL) {
Victor Stinner9ed83c42017-10-31 12:18:10 -07001432 goto failed;
1433 }
Victor Stinner9e87e772017-11-24 12:09:24 +01001434 usable_arenas->nextarena =
1435 usable_arenas->prevarena = NULL;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001436 }
Victor Stinner9e87e772017-11-24 12:09:24 +01001437 assert(usable_arenas->address != 0);
Victor Stinner9ed83c42017-10-31 12:18:10 -07001438
1439 /* Try to get a cached free pool. */
Victor Stinner9e87e772017-11-24 12:09:24 +01001440 pool = usable_arenas->freepools;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001441 if (pool != NULL) {
1442 /* Unlink from cached pools. */
Victor Stinner9e87e772017-11-24 12:09:24 +01001443 usable_arenas->freepools = pool->nextpool;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001444
1445 /* This arena already had the smallest nfreepools
1446 * value, so decreasing nfreepools doesn't change
1447 * that, and we don't need to rearrange the
1448 * usable_arenas list. However, if the arena has
1449 * become wholly allocated, we need to remove its
1450 * arena_object from usable_arenas.
1451 */
Victor Stinner9e87e772017-11-24 12:09:24 +01001452 --usable_arenas->nfreepools;
1453 if (usable_arenas->nfreepools == 0) {
Victor Stinner9ed83c42017-10-31 12:18:10 -07001454 /* Wholly allocated: remove. */
Victor Stinner9e87e772017-11-24 12:09:24 +01001455 assert(usable_arenas->freepools == NULL);
1456 assert(usable_arenas->nextarena == NULL ||
1457 usable_arenas->nextarena->prevarena ==
1458 usable_arenas);
Victor Stinner9ed83c42017-10-31 12:18:10 -07001459
Victor Stinner9e87e772017-11-24 12:09:24 +01001460 usable_arenas = usable_arenas->nextarena;
1461 if (usable_arenas != NULL) {
1462 usable_arenas->prevarena = NULL;
1463 assert(usable_arenas->address != 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001464 }
1465 }
Victor Stinner9ed83c42017-10-31 12:18:10 -07001466 else {
1467 /* nfreepools > 0: it must be that freepools
1468 * isn't NULL, or that we haven't yet carved
1469 * off all the arena's pools for the first
1470 * time.
1471 */
Victor Stinner9e87e772017-11-24 12:09:24 +01001472 assert(usable_arenas->freepools != NULL ||
1473 usable_arenas->pool_address <=
1474 (block*)usable_arenas->address +
Victor Stinner9ed83c42017-10-31 12:18:10 -07001475 ARENA_SIZE - POOL_SIZE);
1476 }
Thomas Woutersa9773292006-04-21 09:43:23 +00001477
Victor Stinner9ed83c42017-10-31 12:18:10 -07001478 init_pool:
1479 /* Frontlink to used pools. */
Victor Stinner9e87e772017-11-24 12:09:24 +01001480 next = usedpools[size + size]; /* == prev */
Victor Stinner9ed83c42017-10-31 12:18:10 -07001481 pool->nextpool = next;
1482 pool->prevpool = next;
1483 next->nextpool = pool;
1484 next->prevpool = pool;
1485 pool->ref.count = 1;
1486 if (pool->szidx == size) {
1487 /* Luckily, this pool last contained blocks
1488 * of the same size class, so its header
1489 * and free list are already initialized.
1490 */
1491 bp = pool->freeblock;
1492 assert(bp != NULL);
Victor Stinner9e87e772017-11-24 12:09:24 +01001493 pool->freeblock = *(block **)bp;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001494 goto success;
1495 }
1496 /*
1497 * Initialize the pool header, set up the free list to
1498 * contain just the second block, and return the first
1499 * block.
1500 */
1501 pool->szidx = size;
1502 size = INDEX2SIZE(size);
Victor Stinner9e87e772017-11-24 12:09:24 +01001503 bp = (block *)pool + POOL_OVERHEAD;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001504 pool->nextoffset = POOL_OVERHEAD + (size << 1);
1505 pool->maxnextoffset = POOL_SIZE - size;
1506 pool->freeblock = bp + size;
Victor Stinner9e87e772017-11-24 12:09:24 +01001507 *(block **)(pool->freeblock) = NULL;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001508 goto success;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001509 }
Neil Schemenauera35c6882001-02-27 04:45:05 +00001510
Victor Stinner9ed83c42017-10-31 12:18:10 -07001511 /* Carve off a new pool. */
Victor Stinner9e87e772017-11-24 12:09:24 +01001512 assert(usable_arenas->nfreepools > 0);
1513 assert(usable_arenas->freepools == NULL);
1514 pool = (poolp)usable_arenas->pool_address;
1515 assert((block*)pool <= (block*)usable_arenas->address +
Victor Stinner9ed83c42017-10-31 12:18:10 -07001516 ARENA_SIZE - POOL_SIZE);
Victor Stinner9e87e772017-11-24 12:09:24 +01001517 pool->arenaindex = (uint)(usable_arenas - arenas);
1518 assert(&arenas[pool->arenaindex] == usable_arenas);
Victor Stinner9ed83c42017-10-31 12:18:10 -07001519 pool->szidx = DUMMY_SIZE_IDX;
Victor Stinner9e87e772017-11-24 12:09:24 +01001520 usable_arenas->pool_address += POOL_SIZE;
1521 --usable_arenas->nfreepools;
Neil Schemenauera35c6882001-02-27 04:45:05 +00001522
Victor Stinner9e87e772017-11-24 12:09:24 +01001523 if (usable_arenas->nfreepools == 0) {
1524 assert(usable_arenas->nextarena == NULL ||
1525 usable_arenas->nextarena->prevarena ==
1526 usable_arenas);
Victor Stinner9ed83c42017-10-31 12:18:10 -07001527 /* Unlink the arena: it is completely allocated. */
Victor Stinner9e87e772017-11-24 12:09:24 +01001528 usable_arenas = usable_arenas->nextarena;
1529 if (usable_arenas != NULL) {
1530 usable_arenas->prevarena = NULL;
1531 assert(usable_arenas->address != 0);
Victor Stinner9ed83c42017-10-31 12:18:10 -07001532 }
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001533 }
Victor Stinner9ed83c42017-10-31 12:18:10 -07001534
1535 goto init_pool;
1536
1537success:
Victor Stinner9ed83c42017-10-31 12:18:10 -07001538 assert(bp != NULL);
1539 *ptr_p = (void *)bp;
1540 return 1;
1541
1542failed:
Victor Stinner9ed83c42017-10-31 12:18:10 -07001543 return 0;
Neil Schemenauera35c6882001-02-27 04:45:05 +00001544}
1545
Victor Stinner9ed83c42017-10-31 12:18:10 -07001546
Victor Stinnerdb067af2014-05-02 22:31:14 +02001547static void *
1548_PyObject_Malloc(void *ctx, size_t nbytes)
1549{
Victor Stinner9ed83c42017-10-31 12:18:10 -07001550 void* ptr;
1551 if (pymalloc_alloc(ctx, &ptr, nbytes)) {
Victor Stinner9e87e772017-11-24 12:09:24 +01001552 _Py_AllocatedBlocks++;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001553 return ptr;
1554 }
1555
1556 ptr = PyMem_RawMalloc(nbytes);
1557 if (ptr != NULL) {
Victor Stinner9e87e772017-11-24 12:09:24 +01001558 _Py_AllocatedBlocks++;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001559 }
1560 return ptr;
Victor Stinnerdb067af2014-05-02 22:31:14 +02001561}
1562
Victor Stinner9ed83c42017-10-31 12:18:10 -07001563
Victor Stinnerdb067af2014-05-02 22:31:14 +02001564static void *
1565_PyObject_Calloc(void *ctx, size_t nelem, size_t elsize)
1566{
Victor Stinner9ed83c42017-10-31 12:18:10 -07001567 void* ptr;
1568
1569 assert(elsize == 0 || nelem <= (size_t)PY_SSIZE_T_MAX / elsize);
1570 size_t nbytes = nelem * elsize;
1571
1572 if (pymalloc_alloc(ctx, &ptr, nbytes)) {
1573 memset(ptr, 0, nbytes);
Victor Stinner9e87e772017-11-24 12:09:24 +01001574 _Py_AllocatedBlocks++;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001575 return ptr;
1576 }
1577
1578 ptr = PyMem_RawCalloc(nelem, elsize);
1579 if (ptr != NULL) {
Victor Stinner9e87e772017-11-24 12:09:24 +01001580 _Py_AllocatedBlocks++;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001581 }
1582 return ptr;
Victor Stinnerdb067af2014-05-02 22:31:14 +02001583}
1584
Neil Schemenauera35c6882001-02-27 04:45:05 +00001585
Victor Stinner9ed83c42017-10-31 12:18:10 -07001586/* Free a memory block allocated by pymalloc_alloc().
1587 Return 1 if it was freed.
1588 Return 0 if the block was not allocated by pymalloc_alloc(). */
1589static int
1590pymalloc_free(void *ctx, void *p)
Neil Schemenauera35c6882001-02-27 04:45:05 +00001591{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001592 poolp pool;
Victor Stinner9e87e772017-11-24 12:09:24 +01001593 block *lastfree;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001594 poolp next, prev;
1595 uint size;
Neil Schemenauera35c6882001-02-27 04:45:05 +00001596
Victor Stinner9ed83c42017-10-31 12:18:10 -07001597 assert(p != NULL);
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001598
Benjamin Peterson05159c42009-12-03 03:01:27 +00001599#ifdef WITH_VALGRIND
Victor Stinner9ed83c42017-10-31 12:18:10 -07001600 if (UNLIKELY(running_on_valgrind > 0)) {
1601 return 0;
1602 }
Benjamin Peterson05159c42009-12-03 03:01:27 +00001603#endif
1604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001605 pool = POOL_ADDR(p);
Victor Stinner9ed83c42017-10-31 12:18:10 -07001606 if (!address_in_range(p, pool)) {
1607 return 0;
1608 }
1609 /* We allocated this address. */
Thomas Woutersa9773292006-04-21 09:43:23 +00001610
Victor Stinner9ed83c42017-10-31 12:18:10 -07001611 /* Link p to the start of the pool's freeblock list. Since
1612 * the pool had at least the p block outstanding, the pool
1613 * wasn't empty (so it's already in a usedpools[] list, or
1614 * was full and is in no list -- it's not in the freeblocks
1615 * list in any case).
1616 */
1617 assert(pool->ref.count > 0); /* else it was empty */
Victor Stinner9e87e772017-11-24 12:09:24 +01001618 *(block **)p = lastfree = pool->freeblock;
1619 pool->freeblock = (block *)p;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001620 if (!lastfree) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001621 /* Pool was full, so doesn't currently live in any list:
1622 * link it to the front of the appropriate usedpools[] list.
1623 * This mimics LRU pool usage for new allocations and
1624 * targets optimal filling when several pools contain
1625 * blocks of the same size class.
1626 */
1627 --pool->ref.count;
1628 assert(pool->ref.count > 0); /* else the pool is empty */
1629 size = pool->szidx;
Victor Stinner9e87e772017-11-24 12:09:24 +01001630 next = usedpools[size + size];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001631 prev = next->prevpool;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001632
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001633 /* insert pool before next: prev <-> pool <-> next */
1634 pool->nextpool = next;
1635 pool->prevpool = prev;
1636 next->prevpool = pool;
1637 prev->nextpool = pool;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001638 goto success;
1639 }
1640
1641 struct arena_object* ao;
1642 uint nf; /* ao->nfreepools */
1643
1644 /* freeblock wasn't NULL, so the pool wasn't full,
1645 * and the pool is in a usedpools[] list.
1646 */
1647 if (--pool->ref.count != 0) {
1648 /* pool isn't empty: leave it in usedpools */
1649 goto success;
1650 }
1651 /* Pool is now empty: unlink from usedpools, and
1652 * link to the front of freepools. This ensures that
1653 * previously freed pools will be allocated later
1654 * (being not referenced, they are perhaps paged out).
1655 */
1656 next = pool->nextpool;
1657 prev = pool->prevpool;
1658 next->prevpool = prev;
1659 prev->nextpool = next;
1660
1661 /* Link the pool to freepools. This is a singly-linked
1662 * list, and pool->prevpool isn't used there.
1663 */
Victor Stinner9e87e772017-11-24 12:09:24 +01001664 ao = &arenas[pool->arenaindex];
Victor Stinner9ed83c42017-10-31 12:18:10 -07001665 pool->nextpool = ao->freepools;
1666 ao->freepools = pool;
1667 nf = ++ao->nfreepools;
1668
1669 /* All the rest is arena management. We just freed
1670 * a pool, and there are 4 cases for arena mgmt:
1671 * 1. If all the pools are free, return the arena to
1672 * the system free().
1673 * 2. If this is the only free pool in the arena,
1674 * add the arena back to the `usable_arenas` list.
1675 * 3. If the "next" arena has a smaller count of free
1676 * pools, we have to "slide this arena right" to
1677 * restore that usable_arenas is sorted in order of
1678 * nfreepools.
1679 * 4. Else there's nothing more to do.
1680 */
1681 if (nf == ao->ntotalpools) {
1682 /* Case 1. First unlink ao from usable_arenas.
1683 */
1684 assert(ao->prevarena == NULL ||
1685 ao->prevarena->address != 0);
1686 assert(ao ->nextarena == NULL ||
1687 ao->nextarena->address != 0);
1688
1689 /* Fix the pointer in the prevarena, or the
1690 * usable_arenas pointer.
1691 */
1692 if (ao->prevarena == NULL) {
Victor Stinner9e87e772017-11-24 12:09:24 +01001693 usable_arenas = ao->nextarena;
1694 assert(usable_arenas == NULL ||
1695 usable_arenas->address != 0);
Victor Stinner9ed83c42017-10-31 12:18:10 -07001696 }
1697 else {
1698 assert(ao->prevarena->nextarena == ao);
1699 ao->prevarena->nextarena =
1700 ao->nextarena;
1701 }
1702 /* Fix the pointer in the nextarena. */
1703 if (ao->nextarena != NULL) {
1704 assert(ao->nextarena->prevarena == ao);
1705 ao->nextarena->prevarena =
1706 ao->prevarena;
1707 }
1708 /* Record that this arena_object slot is
1709 * available to be reused.
1710 */
Victor Stinner9e87e772017-11-24 12:09:24 +01001711 ao->nextarena = unused_arena_objects;
1712 unused_arena_objects = ao;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001713
1714 /* Free the entire arena. */
Victor Stinner9e87e772017-11-24 12:09:24 +01001715 _PyObject_Arena.free(_PyObject_Arena.ctx,
Victor Stinner9ed83c42017-10-31 12:18:10 -07001716 (void *)ao->address, ARENA_SIZE);
1717 ao->address = 0; /* mark unassociated */
Victor Stinner9e87e772017-11-24 12:09:24 +01001718 --narenas_currently_allocated;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001719
1720 goto success;
1721 }
1722
1723 if (nf == 1) {
1724 /* Case 2. Put ao at the head of
1725 * usable_arenas. Note that because
1726 * ao->nfreepools was 0 before, ao isn't
1727 * currently on the usable_arenas list.
1728 */
Victor Stinner9e87e772017-11-24 12:09:24 +01001729 ao->nextarena = usable_arenas;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001730 ao->prevarena = NULL;
Victor Stinner9e87e772017-11-24 12:09:24 +01001731 if (usable_arenas)
1732 usable_arenas->prevarena = ao;
1733 usable_arenas = ao;
1734 assert(usable_arenas->address != 0);
Victor Stinner9ed83c42017-10-31 12:18:10 -07001735
1736 goto success;
1737 }
1738
1739 /* If this arena is now out of order, we need to keep
1740 * the list sorted. The list is kept sorted so that
1741 * the "most full" arenas are used first, which allows
1742 * the nearly empty arenas to be completely freed. In
1743 * a few un-scientific tests, it seems like this
1744 * approach allowed a lot more memory to be freed.
1745 */
1746 if (ao->nextarena == NULL ||
1747 nf <= ao->nextarena->nfreepools) {
1748 /* Case 4. Nothing to do. */
1749 goto success;
1750 }
1751 /* Case 3: We have to move the arena towards the end
1752 * of the list, because it has more free pools than
1753 * the arena to its right.
1754 * First unlink ao from usable_arenas.
1755 */
1756 if (ao->prevarena != NULL) {
1757 /* ao isn't at the head of the list */
1758 assert(ao->prevarena->nextarena == ao);
1759 ao->prevarena->nextarena = ao->nextarena;
1760 }
1761 else {
1762 /* ao is at the head of the list */
Victor Stinner9e87e772017-11-24 12:09:24 +01001763 assert(usable_arenas == ao);
1764 usable_arenas = ao->nextarena;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001765 }
1766 ao->nextarena->prevarena = ao->prevarena;
1767
1768 /* Locate the new insertion point by iterating over
1769 * the list, using our nextarena pointer.
1770 */
1771 while (ao->nextarena != NULL && nf > ao->nextarena->nfreepools) {
1772 ao->prevarena = ao->nextarena;
1773 ao->nextarena = ao->nextarena->nextarena;
1774 }
1775
1776 /* Insert ao at this point. */
1777 assert(ao->nextarena == NULL || ao->prevarena == ao->nextarena->prevarena);
1778 assert(ao->prevarena->nextarena == ao->nextarena);
1779
1780 ao->prevarena->nextarena = ao;
1781 if (ao->nextarena != NULL) {
1782 ao->nextarena->prevarena = ao;
1783 }
1784
1785 /* Verify that the swaps worked. */
1786 assert(ao->nextarena == NULL || nf <= ao->nextarena->nfreepools);
1787 assert(ao->prevarena == NULL || nf > ao->prevarena->nfreepools);
1788 assert(ao->nextarena == NULL || ao->nextarena->prevarena == ao);
Victor Stinner9e87e772017-11-24 12:09:24 +01001789 assert((usable_arenas == ao && ao->prevarena == NULL)
Victor Stinner9ed83c42017-10-31 12:18:10 -07001790 || ao->prevarena->nextarena == ao);
1791
1792 goto success;
1793
1794success:
Victor Stinner9ed83c42017-10-31 12:18:10 -07001795 return 1;
1796}
1797
1798
1799static void
1800_PyObject_Free(void *ctx, void *p)
1801{
1802 /* PyObject_Free(NULL) has no effect */
1803 if (p == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001804 return;
1805 }
Neil Schemenauera35c6882001-02-27 04:45:05 +00001806
Victor Stinner9e87e772017-11-24 12:09:24 +01001807 _Py_AllocatedBlocks--;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001808 if (!pymalloc_free(ctx, p)) {
1809 /* pymalloc didn't allocate this address */
1810 PyMem_RawFree(p);
1811 }
Neil Schemenauera35c6882001-02-27 04:45:05 +00001812}
1813
Neil Schemenauera35c6882001-02-27 04:45:05 +00001814
Victor Stinner9ed83c42017-10-31 12:18:10 -07001815/* pymalloc realloc.
1816
1817 If nbytes==0, then as the Python docs promise, we do not treat this like
1818 free(p), and return a non-NULL result.
1819
1820 Return 1 if pymalloc reallocated memory and wrote the new pointer into
1821 newptr_p.
1822
1823 Return 0 if pymalloc didn't allocated p. */
1824static int
1825pymalloc_realloc(void *ctx, void **newptr_p, void *p, size_t nbytes)
Neil Schemenauera35c6882001-02-27 04:45:05 +00001826{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001827 void *bp;
1828 poolp pool;
1829 size_t size;
Neil Schemenauera35c6882001-02-27 04:45:05 +00001830
Victor Stinner9ed83c42017-10-31 12:18:10 -07001831 assert(p != NULL);
Georg Brandld492ad82008-07-23 16:13:07 +00001832
Benjamin Peterson05159c42009-12-03 03:01:27 +00001833#ifdef WITH_VALGRIND
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001834 /* Treat running_on_valgrind == -1 the same as 0 */
Victor Stinner9ed83c42017-10-31 12:18:10 -07001835 if (UNLIKELY(running_on_valgrind > 0)) {
1836 return 0;
1837 }
Benjamin Peterson05159c42009-12-03 03:01:27 +00001838#endif
1839
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001840 pool = POOL_ADDR(p);
Victor Stinner9ed83c42017-10-31 12:18:10 -07001841 if (!address_in_range(p, pool)) {
1842 /* pymalloc is not managing this block.
1843
1844 If nbytes <= SMALL_REQUEST_THRESHOLD, it's tempting to try to take
1845 over this block. However, if we do, we need to copy the valid data
1846 from the C-managed block to one of our blocks, and there's no
1847 portable way to know how much of the memory space starting at p is
1848 valid.
1849
1850 As bug 1185883 pointed out the hard way, it's possible that the
1851 C-managed block is "at the end" of allocated VM space, so that a
1852 memory fault can occur if we try to copy nbytes bytes starting at p.
1853 Instead we punt: let C continue to manage this block. */
1854 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001855 }
Victor Stinner9ed83c42017-10-31 12:18:10 -07001856
1857 /* pymalloc is in charge of this block */
1858 size = INDEX2SIZE(pool->szidx);
1859 if (nbytes <= size) {
1860 /* The block is staying the same or shrinking.
1861
1862 If it's shrinking, there's a tradeoff: it costs cycles to copy the
1863 block to a smaller size class, but it wastes memory not to copy it.
1864
1865 The compromise here is to copy on shrink only if at least 25% of
1866 size can be shaved off. */
1867 if (4 * nbytes > 3 * size) {
1868 /* It's the same, or shrinking and new/old > 3/4. */
1869 *newptr_p = p;
1870 return 1;
1871 }
1872 size = nbytes;
1873 }
1874
1875 bp = _PyObject_Malloc(ctx, nbytes);
1876 if (bp != NULL) {
1877 memcpy(bp, p, size);
1878 _PyObject_Free(ctx, p);
1879 }
1880 *newptr_p = bp;
1881 return 1;
1882}
1883
1884
1885static void *
1886_PyObject_Realloc(void *ctx, void *ptr, size_t nbytes)
1887{
1888 void *ptr2;
1889
1890 if (ptr == NULL) {
1891 return _PyObject_Malloc(ctx, nbytes);
1892 }
1893
1894 if (pymalloc_realloc(ctx, &ptr2, ptr, nbytes)) {
1895 return ptr2;
1896 }
1897
1898 return PyMem_RawRealloc(ptr, nbytes);
Neil Schemenauera35c6882001-02-27 04:45:05 +00001899}
1900
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001901#else /* ! WITH_PYMALLOC */
Tim Petersddea2082002-03-23 10:03:50 +00001902
1903/*==========================================================================*/
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00001904/* pymalloc not enabled: Redirect the entry points to malloc. These will
1905 * only be used by extensions that are compiled with pymalloc enabled. */
Tim Peters62c06ba2002-03-23 22:28:18 +00001906
Antoine Pitrou92840532012-12-17 23:05:59 +01001907Py_ssize_t
1908_Py_GetAllocatedBlocks(void)
1909{
1910 return 0;
1911}
1912
Tim Peters1221c0a2002-03-23 00:20:15 +00001913#endif /* WITH_PYMALLOC */
1914
Victor Stinner34be807c2016-03-14 12:04:26 +01001915
Tim Petersddea2082002-03-23 10:03:50 +00001916/*==========================================================================*/
Tim Peters62c06ba2002-03-23 22:28:18 +00001917/* A x-platform debugging allocator. This doesn't manage memory directly,
1918 * it wraps a real allocator, adding extra debugging info to the memory blocks.
1919 */
Tim Petersddea2082002-03-23 10:03:50 +00001920
Tim Petersf6fb5012002-04-12 07:38:53 +00001921/* Special bytes broadcast into debug memory blocks at appropriate times.
1922 * Strings of these are unlikely to be valid addresses, floats, ints or
Victor Stinner2b00db62019-04-11 11:33:27 +02001923 * 7-bit ASCII. If modified, _PyMem_IsPtrFreed() should be updated as well.
Victor Stinner4c409be2019-04-11 13:01:15 +02001924 *
1925 * Byte patterns 0xCB, 0xBB and 0xFB have been replaced with 0xCD, 0xDD and
1926 * 0xFD to use the same values than Windows CRT debug malloc() and free().
Tim Petersf6fb5012002-04-12 07:38:53 +00001927 */
1928#undef CLEANBYTE
1929#undef DEADBYTE
1930#undef FORBIDDENBYTE
Victor Stinner4c409be2019-04-11 13:01:15 +02001931#define CLEANBYTE 0xCD /* clean (newly allocated) memory */
1932#define DEADBYTE 0xDD /* dead (newly freed) memory */
1933#define FORBIDDENBYTE 0xFD /* untouchable bytes at each end of a block */
Tim Petersddea2082002-03-23 10:03:50 +00001934
Victor Stinnere8f9acf2019-04-12 21:54:06 +02001935/* Uncomment this define to add the "serialno" field */
1936/* #define PYMEM_DEBUG_SERIALNO */
1937
1938#ifdef PYMEM_DEBUG_SERIALNO
Victor Stinner9e87e772017-11-24 12:09:24 +01001939static size_t serialno = 0; /* incremented on each debug {m,re}alloc */
1940
Tim Peterse0850172002-03-24 00:34:21 +00001941/* serialno is always incremented via calling this routine. The point is
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001942 * to supply a single place to set a breakpoint.
1943 */
Tim Peterse0850172002-03-24 00:34:21 +00001944static void
Neil Schemenauerbd02b142002-03-28 21:05:38 +00001945bumpserialno(void)
Tim Peterse0850172002-03-24 00:34:21 +00001946{
Victor Stinner9e87e772017-11-24 12:09:24 +01001947 ++serialno;
Tim Peterse0850172002-03-24 00:34:21 +00001948}
Victor Stinnere8f9acf2019-04-12 21:54:06 +02001949#endif
Tim Peterse0850172002-03-24 00:34:21 +00001950
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001951#define SST SIZEOF_SIZE_T
Tim Peterse0850172002-03-24 00:34:21 +00001952
Victor Stinnere8f9acf2019-04-12 21:54:06 +02001953#ifdef PYMEM_DEBUG_SERIALNO
1954# define PYMEM_DEBUG_EXTRA_BYTES 4 * SST
1955#else
1956# define PYMEM_DEBUG_EXTRA_BYTES 3 * SST
1957#endif
1958
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001959/* Read sizeof(size_t) bytes at p as a big-endian size_t. */
1960static size_t
1961read_size_t(const void *p)
Tim Petersddea2082002-03-23 10:03:50 +00001962{
Benjamin Peterson19517e42016-09-18 19:22:22 -07001963 const uint8_t *q = (const uint8_t *)p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001964 size_t result = *q++;
1965 int i;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001966
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001967 for (i = SST; --i > 0; ++q)
1968 result = (result << 8) | *q;
1969 return result;
Tim Petersddea2082002-03-23 10:03:50 +00001970}
1971
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001972/* Write n as a big-endian size_t, MSB at address p, LSB at
1973 * p + sizeof(size_t) - 1.
1974 */
Tim Petersddea2082002-03-23 10:03:50 +00001975static void
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001976write_size_t(void *p, size_t n)
Tim Petersddea2082002-03-23 10:03:50 +00001977{
Benjamin Peterson19517e42016-09-18 19:22:22 -07001978 uint8_t *q = (uint8_t *)p + SST - 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001979 int i;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001980
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001981 for (i = SST; --i >= 0; --q) {
Benjamin Peterson19517e42016-09-18 19:22:22 -07001982 *q = (uint8_t)(n & 0xff);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001983 n >>= 8;
1984 }
Tim Petersddea2082002-03-23 10:03:50 +00001985}
1986
Victor Stinnere8f9acf2019-04-12 21:54:06 +02001987/* Let S = sizeof(size_t). The debug malloc asks for 4 * S extra bytes and
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001988 fills them with useful stuff, here calling the underlying malloc's result p:
Tim Petersddea2082002-03-23 10:03:50 +00001989
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001990p[0: S]
1991 Number of bytes originally asked for. This is a size_t, big-endian (easier
1992 to read in a memory dump).
Georg Brandl7cba5fd2013-09-25 09:04:23 +02001993p[S]
Tim Petersdf099f52013-09-19 21:06:37 -05001994 API ID. See PEP 445. This is a character, but seems undocumented.
1995p[S+1: 2*S]
Tim Petersf6fb5012002-04-12 07:38:53 +00001996 Copies of FORBIDDENBYTE. Used to catch under- writes and reads.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001997p[2*S: 2*S+n]
Tim Petersf6fb5012002-04-12 07:38:53 +00001998 The requested memory, filled with copies of CLEANBYTE.
Tim Petersddea2082002-03-23 10:03:50 +00001999 Used to catch reference to uninitialized memory.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00002000 &p[2*S] is returned. Note that this is 8-byte aligned if pymalloc
Tim Petersddea2082002-03-23 10:03:50 +00002001 handled the request itself.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00002002p[2*S+n: 2*S+n+S]
Tim Petersf6fb5012002-04-12 07:38:53 +00002003 Copies of FORBIDDENBYTE. Used to catch over- writes and reads.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00002004p[2*S+n+S: 2*S+n+2*S]
Victor Stinner0507bf52013-07-07 02:05:46 +02002005 A serial number, incremented by 1 on each call to _PyMem_DebugMalloc
2006 and _PyMem_DebugRealloc.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00002007 This is a big-endian size_t.
Tim Petersddea2082002-03-23 10:03:50 +00002008 If "bad memory" is detected later, the serial number gives an
2009 excellent way to set a breakpoint on the next run, to capture the
2010 instant at which this block was passed out.
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002011
2012If PYMEM_DEBUG_SERIALNO is not defined (default), the debug malloc only asks
2013for 3 * S extra bytes, and omits the last serialno field.
Tim Petersddea2082002-03-23 10:03:50 +00002014*/
2015
Victor Stinner0507bf52013-07-07 02:05:46 +02002016static void *
Victor Stinnerc4aec362016-03-14 22:26:53 +01002017_PyMem_DebugRawAlloc(int use_calloc, void *ctx, size_t nbytes)
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00002018{
Victor Stinner0507bf52013-07-07 02:05:46 +02002019 debug_alloc_api_t *api = (debug_alloc_api_t *)ctx;
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002020 uint8_t *p; /* base address of malloc'ed pad block */
Victor Stinner9ed83c42017-10-31 12:18:10 -07002021 uint8_t *data; /* p + 2*SST == pointer to data bytes */
2022 uint8_t *tail; /* data + nbytes == pointer to tail pad bytes */
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002023 size_t total; /* nbytes + PYMEM_DEBUG_EXTRA_BYTES */
Victor Stinner9ed83c42017-10-31 12:18:10 -07002024
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002025 if (nbytes > (size_t)PY_SSIZE_T_MAX - PYMEM_DEBUG_EXTRA_BYTES) {
Victor Stinner9ed83c42017-10-31 12:18:10 -07002026 /* integer overflow: can't represent total as a Py_ssize_t */
2027 return NULL;
2028 }
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002029 total = nbytes + PYMEM_DEBUG_EXTRA_BYTES;
Victor Stinner9ed83c42017-10-31 12:18:10 -07002030
2031 /* Layout: [SSSS IFFF CCCC...CCCC FFFF NNNN]
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002032 ^--- p ^--- data ^--- tail
Victor Stinner9ed83c42017-10-31 12:18:10 -07002033 S: nbytes stored as size_t
2034 I: API identifier (1 byte)
2035 F: Forbidden bytes (size_t - 1 bytes before, size_t bytes after)
2036 C: Clean bytes used later to store actual data
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002037 N: Serial number stored as size_t
2038
2039 If PYMEM_DEBUG_SERIALNO is not defined (default), the last NNNN field
2040 is omitted. */
Victor Stinner9ed83c42017-10-31 12:18:10 -07002041
2042 if (use_calloc) {
2043 p = (uint8_t *)api->alloc.calloc(api->alloc.ctx, 1, total);
2044 }
2045 else {
2046 p = (uint8_t *)api->alloc.malloc(api->alloc.ctx, total);
2047 }
2048 if (p == NULL) {
2049 return NULL;
2050 }
2051 data = p + 2*SST;
Tim Petersddea2082002-03-23 10:03:50 +00002052
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002053#ifdef PYMEM_DEBUG_SERIALNO
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002054 bumpserialno();
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002055#endif
Tim Petersddea2082002-03-23 10:03:50 +00002056
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002057 /* at p, write size (SST bytes), id (1 byte), pad (SST-1 bytes) */
2058 write_size_t(p, nbytes);
Benjamin Peterson19517e42016-09-18 19:22:22 -07002059 p[SST] = (uint8_t)api->api_id;
Victor Stinner0507bf52013-07-07 02:05:46 +02002060 memset(p + SST + 1, FORBIDDENBYTE, SST-1);
Tim Petersddea2082002-03-23 10:03:50 +00002061
Victor Stinner9ed83c42017-10-31 12:18:10 -07002062 if (nbytes > 0 && !use_calloc) {
2063 memset(data, CLEANBYTE, nbytes);
2064 }
Tim Petersddea2082002-03-23 10:03:50 +00002065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002066 /* at tail, write pad (SST bytes) and serialno (SST bytes) */
Victor Stinner9ed83c42017-10-31 12:18:10 -07002067 tail = data + nbytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002068 memset(tail, FORBIDDENBYTE, SST);
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002069#ifdef PYMEM_DEBUG_SERIALNO
Victor Stinner9e87e772017-11-24 12:09:24 +01002070 write_size_t(tail + SST, serialno);
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002071#endif
Tim Petersddea2082002-03-23 10:03:50 +00002072
Victor Stinner9ed83c42017-10-31 12:18:10 -07002073 return data;
Tim Petersddea2082002-03-23 10:03:50 +00002074}
2075
Victor Stinnerdb067af2014-05-02 22:31:14 +02002076static void *
Victor Stinnerc4aec362016-03-14 22:26:53 +01002077_PyMem_DebugRawMalloc(void *ctx, size_t nbytes)
Victor Stinnerdb067af2014-05-02 22:31:14 +02002078{
Victor Stinnerc4aec362016-03-14 22:26:53 +01002079 return _PyMem_DebugRawAlloc(0, ctx, nbytes);
Victor Stinnerdb067af2014-05-02 22:31:14 +02002080}
2081
2082static void *
Victor Stinnerc4aec362016-03-14 22:26:53 +01002083_PyMem_DebugRawCalloc(void *ctx, size_t nelem, size_t elsize)
Victor Stinnerdb067af2014-05-02 22:31:14 +02002084{
2085 size_t nbytes;
Victor Stinner9ed83c42017-10-31 12:18:10 -07002086 assert(elsize == 0 || nelem <= (size_t)PY_SSIZE_T_MAX / elsize);
Victor Stinnerdb067af2014-05-02 22:31:14 +02002087 nbytes = nelem * elsize;
Victor Stinnerc4aec362016-03-14 22:26:53 +01002088 return _PyMem_DebugRawAlloc(1, ctx, nbytes);
Victor Stinnerdb067af2014-05-02 22:31:14 +02002089}
2090
Victor Stinner9ed83c42017-10-31 12:18:10 -07002091
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00002092/* 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 +00002093 particular, that the FORBIDDENBYTEs with the api ID are still intact).
Tim Petersf6fb5012002-04-12 07:38:53 +00002094 Then fills the original bytes with DEADBYTE.
Tim Petersddea2082002-03-23 10:03:50 +00002095 Then calls the underlying free.
2096*/
Victor Stinner0507bf52013-07-07 02:05:46 +02002097static void
Victor Stinnerc4aec362016-03-14 22:26:53 +01002098_PyMem_DebugRawFree(void *ctx, void *p)
Tim Petersddea2082002-03-23 10:03:50 +00002099{
Victor Stinner9ed83c42017-10-31 12:18:10 -07002100 /* PyMem_Free(NULL) has no effect */
2101 if (p == NULL) {
2102 return;
2103 }
2104
Victor Stinner0507bf52013-07-07 02:05:46 +02002105 debug_alloc_api_t *api = (debug_alloc_api_t *)ctx;
Benjamin Peterson19517e42016-09-18 19:22:22 -07002106 uint8_t *q = (uint8_t *)p - 2*SST; /* address returned from malloc */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002107 size_t nbytes;
Tim Petersddea2082002-03-23 10:03:50 +00002108
Victor Stinner0507bf52013-07-07 02:05:46 +02002109 _PyMem_DebugCheckAddress(api->api_id, p);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002110 nbytes = read_size_t(q);
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002111 nbytes += PYMEM_DEBUG_EXTRA_BYTES;
Victor Stinner9ed83c42017-10-31 12:18:10 -07002112 memset(q, DEADBYTE, nbytes);
Victor Stinner0507bf52013-07-07 02:05:46 +02002113 api->alloc.free(api->alloc.ctx, q);
Tim Petersddea2082002-03-23 10:03:50 +00002114}
2115
Victor Stinner9ed83c42017-10-31 12:18:10 -07002116
Victor Stinner0507bf52013-07-07 02:05:46 +02002117static void *
Victor Stinnerc4aec362016-03-14 22:26:53 +01002118_PyMem_DebugRawRealloc(void *ctx, void *p, size_t nbytes)
Tim Petersddea2082002-03-23 10:03:50 +00002119{
Victor Stinner9ed83c42017-10-31 12:18:10 -07002120 if (p == NULL) {
2121 return _PyMem_DebugRawAlloc(0, ctx, nbytes);
2122 }
2123
Victor Stinner0507bf52013-07-07 02:05:46 +02002124 debug_alloc_api_t *api = (debug_alloc_api_t *)ctx;
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002125 uint8_t *head; /* base address of malloc'ed pad block */
2126 uint8_t *data; /* pointer to data bytes */
2127 uint8_t *r;
Victor Stinner9ed83c42017-10-31 12:18:10 -07002128 uint8_t *tail; /* data + nbytes == pointer to tail pad bytes */
2129 size_t total; /* 2 * SST + nbytes + 2 * SST */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002130 size_t original_nbytes;
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002131#define ERASED_SIZE 64
2132 uint8_t save[2*ERASED_SIZE]; /* A copy of erased bytes. */
Tim Petersddea2082002-03-23 10:03:50 +00002133
Victor Stinner0507bf52013-07-07 02:05:46 +02002134 _PyMem_DebugCheckAddress(api->api_id, p);
Victor Stinner9ed83c42017-10-31 12:18:10 -07002135
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002136 data = (uint8_t *)p;
2137 head = data - 2*SST;
2138 original_nbytes = read_size_t(head);
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002139 if (nbytes > (size_t)PY_SSIZE_T_MAX - PYMEM_DEBUG_EXTRA_BYTES) {
Victor Stinner9ed83c42017-10-31 12:18:10 -07002140 /* integer overflow: can't represent total as a Py_ssize_t */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 return NULL;
Victor Stinner9ed83c42017-10-31 12:18:10 -07002142 }
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002143 total = nbytes + PYMEM_DEBUG_EXTRA_BYTES;
Tim Petersddea2082002-03-23 10:03:50 +00002144
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002145 tail = data + original_nbytes;
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002146#ifdef PYMEM_DEBUG_SERIALNO
2147 size_t block_serialno = read_size_t(tail + SST);
2148#endif
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002149 /* Mark the header, the trailer, ERASED_SIZE bytes at the begin and
2150 ERASED_SIZE bytes at the end as dead and save the copy of erased bytes.
2151 */
2152 if (original_nbytes <= sizeof(save)) {
2153 memcpy(save, data, original_nbytes);
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002154 memset(data - 2 * SST, DEADBYTE,
2155 original_nbytes + PYMEM_DEBUG_EXTRA_BYTES);
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002156 }
2157 else {
2158 memcpy(save, data, ERASED_SIZE);
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002159 memset(head, DEADBYTE, ERASED_SIZE + 2 * SST);
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002160 memcpy(&save[ERASED_SIZE], tail - ERASED_SIZE, ERASED_SIZE);
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002161 memset(tail - ERASED_SIZE, DEADBYTE,
2162 ERASED_SIZE + PYMEM_DEBUG_EXTRA_BYTES - 2 * SST);
Victor Stinner9ed83c42017-10-31 12:18:10 -07002163 }
Tim Peters85cc1c42002-04-12 08:52:50 +00002164
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002165 /* Resize and add decorations. */
2166 r = (uint8_t *)api->alloc.realloc(api->alloc.ctx, head, total);
2167 if (r == NULL) {
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002168 /* if realloc() failed: rewrite header and footer which have
2169 just been erased */
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002170 nbytes = original_nbytes;
Victor Stinner9ed83c42017-10-31 12:18:10 -07002171 }
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002172 else {
2173 head = r;
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002174#ifdef PYMEM_DEBUG_SERIALNO
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002175 bumpserialno();
Victor Stinner9e87e772017-11-24 12:09:24 +01002176 block_serialno = serialno;
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002177#endif
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002178 }
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002179 data = head + 2*SST;
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002180
2181 write_size_t(head, nbytes);
2182 head[SST] = (uint8_t)api->api_id;
2183 memset(head + SST + 1, FORBIDDENBYTE, SST-1);
Victor Stinnerc4266362013-07-09 00:44:43 +02002184
Victor Stinner9ed83c42017-10-31 12:18:10 -07002185 tail = data + nbytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002186 memset(tail, FORBIDDENBYTE, SST);
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002187#ifdef PYMEM_DEBUG_SERIALNO
Victor Stinner9e87e772017-11-24 12:09:24 +01002188 write_size_t(tail + SST, block_serialno);
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002189#endif
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002190
2191 /* Restore saved bytes. */
2192 if (original_nbytes <= sizeof(save)) {
2193 memcpy(data, save, Py_MIN(nbytes, original_nbytes));
2194 }
2195 else {
2196 size_t i = original_nbytes - ERASED_SIZE;
2197 memcpy(data, save, Py_MIN(nbytes, ERASED_SIZE));
2198 if (nbytes > i) {
2199 memcpy(data + i, &save[ERASED_SIZE],
2200 Py_MIN(nbytes - i, ERASED_SIZE));
2201 }
2202 }
2203
2204 if (r == NULL) {
2205 return NULL;
2206 }
Tim Peters85cc1c42002-04-12 08:52:50 +00002207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002208 if (nbytes > original_nbytes) {
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002209 /* growing: mark new extra memory clean */
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002210 memset(data + original_nbytes, CLEANBYTE, nbytes - original_nbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002211 }
Tim Peters85cc1c42002-04-12 08:52:50 +00002212
Victor Stinner9ed83c42017-10-31 12:18:10 -07002213 return data;
Tim Petersddea2082002-03-23 10:03:50 +00002214}
2215
Victor Stinnerc4aec362016-03-14 22:26:53 +01002216static void
2217_PyMem_DebugCheckGIL(void)
2218{
Victor Stinnerc4aec362016-03-14 22:26:53 +01002219 if (!PyGILState_Check())
2220 Py_FatalError("Python memory allocator called "
2221 "without holding the GIL");
Victor Stinnerc4aec362016-03-14 22:26:53 +01002222}
2223
2224static void *
2225_PyMem_DebugMalloc(void *ctx, size_t nbytes)
2226{
2227 _PyMem_DebugCheckGIL();
2228 return _PyMem_DebugRawMalloc(ctx, nbytes);
2229}
2230
2231static void *
2232_PyMem_DebugCalloc(void *ctx, size_t nelem, size_t elsize)
2233{
2234 _PyMem_DebugCheckGIL();
2235 return _PyMem_DebugRawCalloc(ctx, nelem, elsize);
2236}
2237
Victor Stinner9ed83c42017-10-31 12:18:10 -07002238
Victor Stinnerc4aec362016-03-14 22:26:53 +01002239static void
2240_PyMem_DebugFree(void *ctx, void *ptr)
2241{
2242 _PyMem_DebugCheckGIL();
Victor Stinner0aed3a42016-03-23 11:30:43 +01002243 _PyMem_DebugRawFree(ctx, ptr);
Victor Stinnerc4aec362016-03-14 22:26:53 +01002244}
2245
Victor Stinner9ed83c42017-10-31 12:18:10 -07002246
Victor Stinnerc4aec362016-03-14 22:26:53 +01002247static void *
2248_PyMem_DebugRealloc(void *ctx, void *ptr, size_t nbytes)
2249{
2250 _PyMem_DebugCheckGIL();
2251 return _PyMem_DebugRawRealloc(ctx, ptr, nbytes);
2252}
2253
Tim Peters7ccfadf2002-04-01 06:04:21 +00002254/* Check the forbidden bytes on both ends of the memory allocated for p.
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00002255 * If anything is wrong, print info to stderr via _PyObject_DebugDumpAddress,
Tim Peters7ccfadf2002-04-01 06:04:21 +00002256 * and call Py_FatalError to kill the program.
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00002257 * The API id, is also checked.
Tim Peters7ccfadf2002-04-01 06:04:21 +00002258 */
Victor Stinner0507bf52013-07-07 02:05:46 +02002259static void
2260_PyMem_DebugCheckAddress(char api, const void *p)
Tim Petersddea2082002-03-23 10:03:50 +00002261{
Benjamin Peterson19517e42016-09-18 19:22:22 -07002262 const uint8_t *q = (const uint8_t *)p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002263 char msgbuf[64];
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02002264 const char *msg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002265 size_t nbytes;
Benjamin Peterson19517e42016-09-18 19:22:22 -07002266 const uint8_t *tail;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002267 int i;
2268 char id;
Tim Petersddea2082002-03-23 10:03:50 +00002269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002270 if (p == NULL) {
2271 msg = "didn't expect a NULL pointer";
2272 goto error;
2273 }
Tim Petersddea2082002-03-23 10:03:50 +00002274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002275 /* Check the API id */
2276 id = (char)q[-SST];
2277 if (id != api) {
2278 msg = msgbuf;
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02002279 snprintf(msgbuf, sizeof(msgbuf), "bad ID: Allocated using API '%c', verified using API '%c'", id, api);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002280 msgbuf[sizeof(msgbuf)-1] = 0;
2281 goto error;
2282 }
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00002283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002284 /* Check the stuff at the start of p first: if there's underwrite
2285 * corruption, the number-of-bytes field may be nuts, and checking
2286 * the tail could lead to a segfault then.
2287 */
2288 for (i = SST-1; i >= 1; --i) {
2289 if (*(q-i) != FORBIDDENBYTE) {
2290 msg = "bad leading pad byte";
2291 goto error;
2292 }
2293 }
Tim Petersddea2082002-03-23 10:03:50 +00002294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002295 nbytes = read_size_t(q - 2*SST);
2296 tail = q + nbytes;
2297 for (i = 0; i < SST; ++i) {
2298 if (tail[i] != FORBIDDENBYTE) {
2299 msg = "bad trailing pad byte";
2300 goto error;
2301 }
2302 }
Tim Petersddea2082002-03-23 10:03:50 +00002303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002304 return;
Tim Petersd1139e02002-03-28 07:32:11 +00002305
2306error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002307 _PyObject_DebugDumpAddress(p);
2308 Py_FatalError(msg);
Tim Petersddea2082002-03-23 10:03:50 +00002309}
2310
Tim Peters7ccfadf2002-04-01 06:04:21 +00002311/* Display info to stderr about the memory block at p. */
Victor Stinner0507bf52013-07-07 02:05:46 +02002312static void
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00002313_PyObject_DebugDumpAddress(const void *p)
Tim Petersddea2082002-03-23 10:03:50 +00002314{
Benjamin Peterson19517e42016-09-18 19:22:22 -07002315 const uint8_t *q = (const uint8_t *)p;
2316 const uint8_t *tail;
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002317 size_t nbytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002318 int i;
2319 int ok;
2320 char id;
Tim Petersddea2082002-03-23 10:03:50 +00002321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002322 fprintf(stderr, "Debug memory block at address p=%p:", p);
2323 if (p == NULL) {
2324 fprintf(stderr, "\n");
2325 return;
2326 }
2327 id = (char)q[-SST];
2328 fprintf(stderr, " API '%c'\n", id);
Tim Petersddea2082002-03-23 10:03:50 +00002329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002330 nbytes = read_size_t(q - 2*SST);
2331 fprintf(stderr, " %" PY_FORMAT_SIZE_T "u bytes originally "
2332 "requested\n", nbytes);
Tim Petersddea2082002-03-23 10:03:50 +00002333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002334 /* In case this is nuts, check the leading pad bytes first. */
2335 fprintf(stderr, " The %d pad bytes at p-%d are ", SST-1, SST-1);
2336 ok = 1;
2337 for (i = 1; i <= SST-1; ++i) {
2338 if (*(q-i) != FORBIDDENBYTE) {
2339 ok = 0;
2340 break;
2341 }
2342 }
2343 if (ok)
2344 fputs("FORBIDDENBYTE, as expected.\n", stderr);
2345 else {
2346 fprintf(stderr, "not all FORBIDDENBYTE (0x%02x):\n",
2347 FORBIDDENBYTE);
2348 for (i = SST-1; i >= 1; --i) {
Benjamin Peterson19517e42016-09-18 19:22:22 -07002349 const uint8_t byte = *(q-i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002350 fprintf(stderr, " at p-%d: 0x%02x", i, byte);
2351 if (byte != FORBIDDENBYTE)
2352 fputs(" *** OUCH", stderr);
2353 fputc('\n', stderr);
2354 }
Tim Peters449b5a82002-04-28 06:14:45 +00002355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002356 fputs(" Because memory is corrupted at the start, the "
2357 "count of bytes requested\n"
2358 " may be bogus, and checking the trailing pad "
2359 "bytes may segfault.\n", stderr);
2360 }
Tim Petersddea2082002-03-23 10:03:50 +00002361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002362 tail = q + nbytes;
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002363 fprintf(stderr, " The %d pad bytes at tail=%p are ", SST, (void *)tail);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002364 ok = 1;
2365 for (i = 0; i < SST; ++i) {
2366 if (tail[i] != FORBIDDENBYTE) {
2367 ok = 0;
2368 break;
2369 }
2370 }
2371 if (ok)
2372 fputs("FORBIDDENBYTE, as expected.\n", stderr);
2373 else {
2374 fprintf(stderr, "not all FORBIDDENBYTE (0x%02x):\n",
Stefan Krah735bb122010-11-26 10:54:09 +00002375 FORBIDDENBYTE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002376 for (i = 0; i < SST; ++i) {
Benjamin Peterson19517e42016-09-18 19:22:22 -07002377 const uint8_t byte = tail[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002378 fprintf(stderr, " at tail+%d: 0x%02x",
Stefan Krah735bb122010-11-26 10:54:09 +00002379 i, byte);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002380 if (byte != FORBIDDENBYTE)
2381 fputs(" *** OUCH", stderr);
2382 fputc('\n', stderr);
2383 }
2384 }
Tim Petersddea2082002-03-23 10:03:50 +00002385
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002386#ifdef PYMEM_DEBUG_SERIALNO
2387 size_t serial = read_size_t(tail + SST);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002388 fprintf(stderr, " The block was made by call #%" PY_FORMAT_SIZE_T
2389 "u to debug malloc/realloc.\n", serial);
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002390#endif
Tim Petersddea2082002-03-23 10:03:50 +00002391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002392 if (nbytes > 0) {
2393 i = 0;
2394 fputs(" Data at p:", stderr);
2395 /* print up to 8 bytes at the start */
2396 while (q < tail && i < 8) {
2397 fprintf(stderr, " %02x", *q);
2398 ++i;
2399 ++q;
2400 }
2401 /* and up to 8 at the end */
2402 if (q < tail) {
2403 if (tail - q > 8) {
2404 fputs(" ...", stderr);
2405 q = tail - 8;
2406 }
2407 while (q < tail) {
2408 fprintf(stderr, " %02x", *q);
2409 ++q;
2410 }
2411 }
2412 fputc('\n', stderr);
2413 }
Victor Stinner0611c262016-03-15 22:22:13 +01002414 fputc('\n', stderr);
2415
2416 fflush(stderr);
2417 _PyMem_DumpTraceback(fileno(stderr), p);
Tim Petersddea2082002-03-23 10:03:50 +00002418}
2419
David Malcolm49526f42012-06-22 14:55:41 -04002420
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00002421static size_t
David Malcolm49526f42012-06-22 14:55:41 -04002422printone(FILE *out, const char* msg, size_t value)
Tim Peters16bcb6b2002-04-05 05:45:31 +00002423{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002424 int i, k;
2425 char buf[100];
2426 size_t origvalue = value;
Tim Peters16bcb6b2002-04-05 05:45:31 +00002427
David Malcolm49526f42012-06-22 14:55:41 -04002428 fputs(msg, out);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002429 for (i = (int)strlen(msg); i < 35; ++i)
David Malcolm49526f42012-06-22 14:55:41 -04002430 fputc(' ', out);
2431 fputc('=', out);
Tim Peters49f26812002-04-06 01:45:35 +00002432
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002433 /* Write the value with commas. */
2434 i = 22;
2435 buf[i--] = '\0';
2436 buf[i--] = '\n';
2437 k = 3;
2438 do {
2439 size_t nextvalue = value / 10;
Benjamin Peterson2dba1ee2013-02-20 16:54:30 -05002440 unsigned int digit = (unsigned int)(value - nextvalue * 10);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002441 value = nextvalue;
2442 buf[i--] = (char)(digit + '0');
2443 --k;
2444 if (k == 0 && value && i >= 0) {
2445 k = 3;
2446 buf[i--] = ',';
2447 }
2448 } while (value && i >= 0);
Tim Peters49f26812002-04-06 01:45:35 +00002449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002450 while (i >= 0)
2451 buf[i--] = ' ';
David Malcolm49526f42012-06-22 14:55:41 -04002452 fputs(buf, out);
Tim Peters49f26812002-04-06 01:45:35 +00002453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002454 return origvalue;
Tim Peters16bcb6b2002-04-05 05:45:31 +00002455}
2456
David Malcolm49526f42012-06-22 14:55:41 -04002457void
2458_PyDebugAllocatorStats(FILE *out,
2459 const char *block_name, int num_blocks, size_t sizeof_block)
2460{
2461 char buf1[128];
2462 char buf2[128];
2463 PyOS_snprintf(buf1, sizeof(buf1),
Tim Peterseaa3bcc2013-09-05 22:57:04 -05002464 "%d %ss * %" PY_FORMAT_SIZE_T "d bytes each",
David Malcolm49526f42012-06-22 14:55:41 -04002465 num_blocks, block_name, sizeof_block);
2466 PyOS_snprintf(buf2, sizeof(buf2),
2467 "%48s ", buf1);
2468 (void)printone(out, buf2, num_blocks * sizeof_block);
2469}
2470
Victor Stinner34be807c2016-03-14 12:04:26 +01002471
David Malcolm49526f42012-06-22 14:55:41 -04002472#ifdef WITH_PYMALLOC
2473
Victor Stinner34be807c2016-03-14 12:04:26 +01002474#ifdef Py_DEBUG
2475/* Is target in the list? The list is traversed via the nextpool pointers.
2476 * The list may be NULL-terminated, or circular. Return 1 if target is in
2477 * list, else 0.
2478 */
2479static int
2480pool_is_in_list(const poolp target, poolp list)
2481{
2482 poolp origlist = list;
2483 assert(target != NULL);
2484 if (list == NULL)
2485 return 0;
2486 do {
2487 if (target == list)
2488 return 1;
2489 list = list->nextpool;
2490 } while (list != NULL && list != origlist);
2491 return 0;
2492}
2493#endif
2494
David Malcolm49526f42012-06-22 14:55:41 -04002495/* Print summary info to "out" about the state of pymalloc's structures.
Tim Peters08d82152002-04-18 22:25:03 +00002496 * In Py_DEBUG mode, also perform some expensive internal consistency
2497 * checks.
Victor Stinner6bf992a2017-12-06 17:26:10 +01002498 *
2499 * Return 0 if the memory debug hooks are not installed or no statistics was
Leo Ariasc3d95082018-02-03 18:36:10 -06002500 * written into out, return 1 otherwise.
Tim Peters08d82152002-04-18 22:25:03 +00002501 */
Victor Stinner6bf992a2017-12-06 17:26:10 +01002502int
David Malcolm49526f42012-06-22 14:55:41 -04002503_PyObject_DebugMallocStats(FILE *out)
Tim Peters7ccfadf2002-04-01 06:04:21 +00002504{
Victor Stinner6bf992a2017-12-06 17:26:10 +01002505 if (!_PyMem_PymallocEnabled()) {
2506 return 0;
2507 }
2508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002509 uint i;
2510 const uint numclasses = SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT;
2511 /* # of pools, allocated blocks, and free blocks per class index */
2512 size_t numpools[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT];
2513 size_t numblocks[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT];
2514 size_t numfreeblocks[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT];
2515 /* total # of allocated bytes in used and full pools */
2516 size_t allocated_bytes = 0;
2517 /* total # of available bytes in used pools */
2518 size_t available_bytes = 0;
2519 /* # of free pools + pools not yet carved out of current arena */
2520 uint numfreepools = 0;
2521 /* # of bytes for arena alignment padding */
2522 size_t arena_alignment = 0;
2523 /* # of bytes in used and full pools used for pool_headers */
2524 size_t pool_header_bytes = 0;
2525 /* # of bytes in used and full pools wasted due to quantization,
2526 * i.e. the necessarily leftover space at the ends of used and
2527 * full pools.
2528 */
2529 size_t quantization = 0;
2530 /* # of arenas actually allocated. */
2531 size_t narenas = 0;
2532 /* running total -- should equal narenas * ARENA_SIZE */
2533 size_t total;
2534 char buf[128];
Tim Peters7ccfadf2002-04-01 06:04:21 +00002535
David Malcolm49526f42012-06-22 14:55:41 -04002536 fprintf(out, "Small block threshold = %d, in %u size classes.\n",
Stefan Krah735bb122010-11-26 10:54:09 +00002537 SMALL_REQUEST_THRESHOLD, numclasses);
Tim Peters7ccfadf2002-04-01 06:04:21 +00002538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002539 for (i = 0; i < numclasses; ++i)
2540 numpools[i] = numblocks[i] = numfreeblocks[i] = 0;
Tim Peters7ccfadf2002-04-01 06:04:21 +00002541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002542 /* Because full pools aren't linked to from anything, it's easiest
2543 * to march over all the arenas. If we're lucky, most of the memory
2544 * will be living in full pools -- would be a shame to miss them.
2545 */
Victor Stinner9e87e772017-11-24 12:09:24 +01002546 for (i = 0; i < maxarenas; ++i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002547 uint j;
Victor Stinner9e87e772017-11-24 12:09:24 +01002548 uintptr_t base = arenas[i].address;
Thomas Woutersa9773292006-04-21 09:43:23 +00002549
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002550 /* Skip arenas which are not allocated. */
Victor Stinner9e87e772017-11-24 12:09:24 +01002551 if (arenas[i].address == (uintptr_t)NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002552 continue;
2553 narenas += 1;
Thomas Woutersa9773292006-04-21 09:43:23 +00002554
Victor Stinner9e87e772017-11-24 12:09:24 +01002555 numfreepools += arenas[i].nfreepools;
Tim Peters7ccfadf2002-04-01 06:04:21 +00002556
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002557 /* round up to pool alignment */
Benjamin Peterson5d4b09c2016-09-18 19:24:52 -07002558 if (base & (uintptr_t)POOL_SIZE_MASK) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002559 arena_alignment += POOL_SIZE;
Benjamin Peterson5d4b09c2016-09-18 19:24:52 -07002560 base &= ~(uintptr_t)POOL_SIZE_MASK;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002561 base += POOL_SIZE;
2562 }
Tim Peters7ccfadf2002-04-01 06:04:21 +00002563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002564 /* visit every pool in the arena */
Victor Stinner9e87e772017-11-24 12:09:24 +01002565 assert(base <= (uintptr_t) arenas[i].pool_address);
2566 for (j = 0; base < (uintptr_t) arenas[i].pool_address;
Benjamin Peterson19517e42016-09-18 19:22:22 -07002567 ++j, base += POOL_SIZE) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002568 poolp p = (poolp)base;
2569 const uint sz = p->szidx;
2570 uint freeblocks;
Tim Peters08d82152002-04-18 22:25:03 +00002571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002572 if (p->ref.count == 0) {
2573 /* currently unused */
Victor Stinner34be807c2016-03-14 12:04:26 +01002574#ifdef Py_DEBUG
Victor Stinner9e87e772017-11-24 12:09:24 +01002575 assert(pool_is_in_list(p, arenas[i].freepools));
Victor Stinner34be807c2016-03-14 12:04:26 +01002576#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002577 continue;
2578 }
2579 ++numpools[sz];
2580 numblocks[sz] += p->ref.count;
2581 freeblocks = NUMBLOCKS(sz) - p->ref.count;
2582 numfreeblocks[sz] += freeblocks;
Tim Peters08d82152002-04-18 22:25:03 +00002583#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002584 if (freeblocks > 0)
Victor Stinner9e87e772017-11-24 12:09:24 +01002585 assert(pool_is_in_list(p, usedpools[sz + sz]));
Tim Peters08d82152002-04-18 22:25:03 +00002586#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002587 }
2588 }
Victor Stinner9e87e772017-11-24 12:09:24 +01002589 assert(narenas == narenas_currently_allocated);
Tim Peters7ccfadf2002-04-01 06:04:21 +00002590
David Malcolm49526f42012-06-22 14:55:41 -04002591 fputc('\n', out);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002592 fputs("class size num pools blocks in use avail blocks\n"
2593 "----- ---- --------- ------------- ------------\n",
David Malcolm49526f42012-06-22 14:55:41 -04002594 out);
Tim Peters7ccfadf2002-04-01 06:04:21 +00002595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002596 for (i = 0; i < numclasses; ++i) {
2597 size_t p = numpools[i];
2598 size_t b = numblocks[i];
2599 size_t f = numfreeblocks[i];
2600 uint size = INDEX2SIZE(i);
2601 if (p == 0) {
2602 assert(b == 0 && f == 0);
2603 continue;
2604 }
David Malcolm49526f42012-06-22 14:55:41 -04002605 fprintf(out, "%5u %6u "
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002606 "%11" PY_FORMAT_SIZE_T "u "
2607 "%15" PY_FORMAT_SIZE_T "u "
2608 "%13" PY_FORMAT_SIZE_T "u\n",
Stefan Krah735bb122010-11-26 10:54:09 +00002609 i, size, p, b, f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002610 allocated_bytes += b * size;
2611 available_bytes += f * size;
2612 pool_header_bytes += p * POOL_OVERHEAD;
2613 quantization += p * ((POOL_SIZE - POOL_OVERHEAD) % size);
2614 }
David Malcolm49526f42012-06-22 14:55:41 -04002615 fputc('\n', out);
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002616#ifdef PYMEM_DEBUG_SERIALNO
2617 if (_PyMem_DebugEnabled()) {
Victor Stinner9e87e772017-11-24 12:09:24 +01002618 (void)printone(out, "# times object malloc called", serialno);
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002619 }
2620#endif
Victor Stinner9e87e772017-11-24 12:09:24 +01002621 (void)printone(out, "# arenas allocated total", ntimes_arena_allocated);
2622 (void)printone(out, "# arenas reclaimed", ntimes_arena_allocated - narenas);
2623 (void)printone(out, "# arenas highwater mark", narenas_highwater);
David Malcolm49526f42012-06-22 14:55:41 -04002624 (void)printone(out, "# arenas allocated current", narenas);
Thomas Woutersa9773292006-04-21 09:43:23 +00002625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002626 PyOS_snprintf(buf, sizeof(buf),
2627 "%" PY_FORMAT_SIZE_T "u arenas * %d bytes/arena",
2628 narenas, ARENA_SIZE);
David Malcolm49526f42012-06-22 14:55:41 -04002629 (void)printone(out, buf, narenas * ARENA_SIZE);
Tim Peters16bcb6b2002-04-05 05:45:31 +00002630
David Malcolm49526f42012-06-22 14:55:41 -04002631 fputc('\n', out);
Tim Peters16bcb6b2002-04-05 05:45:31 +00002632
David Malcolm49526f42012-06-22 14:55:41 -04002633 total = printone(out, "# bytes in allocated blocks", allocated_bytes);
2634 total += printone(out, "# bytes in available blocks", available_bytes);
Tim Peters49f26812002-04-06 01:45:35 +00002635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002636 PyOS_snprintf(buf, sizeof(buf),
2637 "%u unused pools * %d bytes", numfreepools, POOL_SIZE);
David Malcolm49526f42012-06-22 14:55:41 -04002638 total += printone(out, buf, (size_t)numfreepools * POOL_SIZE);
Tim Peters16bcb6b2002-04-05 05:45:31 +00002639
David Malcolm49526f42012-06-22 14:55:41 -04002640 total += printone(out, "# bytes lost to pool headers", pool_header_bytes);
2641 total += printone(out, "# bytes lost to quantization", quantization);
2642 total += printone(out, "# bytes lost to arena alignment", arena_alignment);
2643 (void)printone(out, "Total", total);
Victor Stinner6bf992a2017-12-06 17:26:10 +01002644 return 1;
Tim Peters7ccfadf2002-04-01 06:04:21 +00002645}
2646
David Malcolm49526f42012-06-22 14:55:41 -04002647#endif /* #ifdef WITH_PYMALLOC */