blob: f54856dcfe7166afa33fdc12400afeac09cd4ee1 [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
Victor Stinnerb16b4e42019-05-17 15:20:52 +0200271_PyMem_GetAllocatorName(const char *name, PyMemAllocatorName *allocator)
Victor Stinner34be807c2016-03-14 12:04:26 +0100272{
Victor Stinnerb16b4e42019-05-17 15:20:52 +0200273 if (name == NULL || *name == '\0') {
Victor Stinner34be807c2016-03-14 12:04:26 +0100274 /* PYTHONMALLOC is empty or is not set or ignored (-E/-I command line
Victor Stinnerb16b4e42019-05-17 15:20:52 +0200275 nameions): use default memory allocators */
276 *allocator = PYMEM_ALLOCATOR_DEFAULT;
Victor Stinner34be807c2016-03-14 12:04:26 +0100277 }
Victor Stinnerb16b4e42019-05-17 15:20:52 +0200278 else if (strcmp(name, "default") == 0) {
279 *allocator = PYMEM_ALLOCATOR_DEFAULT;
280 }
281 else if (strcmp(name, "debug") == 0) {
282 *allocator = PYMEM_ALLOCATOR_DEBUG;
283 }
284#ifdef WITH_PYMALLOC
285 else if (strcmp(name, "pymalloc") == 0) {
286 *allocator = PYMEM_ALLOCATOR_PYMALLOC;
287 }
288 else if (strcmp(name, "pymalloc_debug") == 0) {
289 *allocator = PYMEM_ALLOCATOR_PYMALLOC_DEBUG;
290 }
291#endif
292 else if (strcmp(name, "malloc") == 0) {
293 *allocator = PYMEM_ALLOCATOR_MALLOC;
294 }
295 else if (strcmp(name, "malloc_debug") == 0) {
296 *allocator = PYMEM_ALLOCATOR_MALLOC_DEBUG;
297 }
298 else {
299 /* unknown allocator */
300 return -1;
301 }
302 return 0;
303}
Victor Stinner34be807c2016-03-14 12:04:26 +0100304
Victor Stinnerb16b4e42019-05-17 15:20:52 +0200305
306int
307_PyMem_SetupAllocators(PyMemAllocatorName allocator)
308{
309 switch (allocator) {
310 case PYMEM_ALLOCATOR_NOT_SET:
311 /* do nothing */
312 break;
313
314 case PYMEM_ALLOCATOR_DEFAULT:
Victor Stinner5d39e042017-11-29 17:20:38 +0100315 (void)_PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, NULL);
316 (void)_PyMem_SetDefaultAllocator(PYMEM_DOMAIN_MEM, NULL);
317 (void)_PyMem_SetDefaultAllocator(PYMEM_DOMAIN_OBJ, NULL);
Victor Stinnerb16b4e42019-05-17 15:20:52 +0200318 break;
319
320 case PYMEM_ALLOCATOR_DEBUG:
Victor Stinner5d39e042017-11-29 17:20:38 +0100321 (void)pymem_set_default_allocator(PYMEM_DOMAIN_RAW, 1, NULL);
322 (void)pymem_set_default_allocator(PYMEM_DOMAIN_MEM, 1, NULL);
323 (void)pymem_set_default_allocator(PYMEM_DOMAIN_OBJ, 1, NULL);
Victor Stinnerb16b4e42019-05-17 15:20:52 +0200324 break;
325
Victor Stinner34be807c2016-03-14 12:04:26 +0100326#ifdef WITH_PYMALLOC
Victor Stinnerb16b4e42019-05-17 15:20:52 +0200327 case PYMEM_ALLOCATOR_PYMALLOC:
328 case PYMEM_ALLOCATOR_PYMALLOC_DEBUG:
329 {
Victor Stinner5d39e042017-11-29 17:20:38 +0100330 PyMemAllocatorEx malloc_alloc = MALLOC_ALLOC;
331 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &malloc_alloc);
Victor Stinner34be807c2016-03-14 12:04:26 +0100332
Victor Stinner5d39e042017-11-29 17:20:38 +0100333 PyMemAllocatorEx pymalloc = PYMALLOC_ALLOC;
334 PyMem_SetAllocator(PYMEM_DOMAIN_MEM, &pymalloc);
335 PyMem_SetAllocator(PYMEM_DOMAIN_OBJ, &pymalloc);
Victor Stinner34be807c2016-03-14 12:04:26 +0100336
Victor Stinnerb16b4e42019-05-17 15:20:52 +0200337 if (allocator == PYMEM_ALLOCATOR_PYMALLOC_DEBUG) {
Victor Stinner34be807c2016-03-14 12:04:26 +0100338 PyMem_SetupDebugHooks();
Victor Stinner5d39e042017-11-29 17:20:38 +0100339 }
Victor Stinnerb16b4e42019-05-17 15:20:52 +0200340 break;
Victor Stinner34be807c2016-03-14 12:04:26 +0100341 }
342#endif
Victor Stinnerb16b4e42019-05-17 15:20:52 +0200343
344 case PYMEM_ALLOCATOR_MALLOC:
345 case PYMEM_ALLOCATOR_MALLOC_DEBUG:
346 {
Victor Stinner5d39e042017-11-29 17:20:38 +0100347 PyMemAllocatorEx malloc_alloc = MALLOC_ALLOC;
348 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &malloc_alloc);
349 PyMem_SetAllocator(PYMEM_DOMAIN_MEM, &malloc_alloc);
350 PyMem_SetAllocator(PYMEM_DOMAIN_OBJ, &malloc_alloc);
351
Victor Stinnerb16b4e42019-05-17 15:20:52 +0200352 if (allocator == PYMEM_ALLOCATOR_MALLOC_DEBUG) {
Victor Stinner5d39e042017-11-29 17:20:38 +0100353 PyMem_SetupDebugHooks();
354 }
Victor Stinnerb16b4e42019-05-17 15:20:52 +0200355 break;
Victor Stinner5d39e042017-11-29 17:20:38 +0100356 }
Victor Stinnerb16b4e42019-05-17 15:20:52 +0200357
358 default:
Victor Stinner34be807c2016-03-14 12:04:26 +0100359 /* unknown allocator */
360 return -1;
361 }
362 return 0;
363}
364
Victor Stinner5d39e042017-11-29 17:20:38 +0100365
366static int
367pymemallocator_eq(PyMemAllocatorEx *a, PyMemAllocatorEx *b)
368{
369 return (memcmp(a, b, sizeof(PyMemAllocatorEx)) == 0);
370}
371
372
373const char*
Victor Stinnerb16b4e42019-05-17 15:20:52 +0200374_PyMem_GetCurrentAllocatorName(void)
Victor Stinner5d39e042017-11-29 17:20:38 +0100375{
376 PyMemAllocatorEx malloc_alloc = MALLOC_ALLOC;
377#ifdef WITH_PYMALLOC
378 PyMemAllocatorEx pymalloc = PYMALLOC_ALLOC;
379#endif
380
381 if (pymemallocator_eq(&_PyMem_Raw, &malloc_alloc) &&
382 pymemallocator_eq(&_PyMem, &malloc_alloc) &&
383 pymemallocator_eq(&_PyObject, &malloc_alloc))
384 {
385 return "malloc";
386 }
387#ifdef WITH_PYMALLOC
388 if (pymemallocator_eq(&_PyMem_Raw, &malloc_alloc) &&
389 pymemallocator_eq(&_PyMem, &pymalloc) &&
390 pymemallocator_eq(&_PyObject, &pymalloc))
391 {
392 return "pymalloc";
393 }
394#endif
395
396 PyMemAllocatorEx dbg_raw = PYDBGRAW_ALLOC;
397 PyMemAllocatorEx dbg_mem = PYDBGMEM_ALLOC;
398 PyMemAllocatorEx dbg_obj = PYDBGOBJ_ALLOC;
399
400 if (pymemallocator_eq(&_PyMem_Raw, &dbg_raw) &&
401 pymemallocator_eq(&_PyMem, &dbg_mem) &&
402 pymemallocator_eq(&_PyObject, &dbg_obj))
403 {
404 /* Debug hooks installed */
405 if (pymemallocator_eq(&_PyMem_Debug.raw.alloc, &malloc_alloc) &&
406 pymemallocator_eq(&_PyMem_Debug.mem.alloc, &malloc_alloc) &&
407 pymemallocator_eq(&_PyMem_Debug.obj.alloc, &malloc_alloc))
408 {
409 return "malloc_debug";
410 }
411#ifdef WITH_PYMALLOC
412 if (pymemallocator_eq(&_PyMem_Debug.raw.alloc, &malloc_alloc) &&
413 pymemallocator_eq(&_PyMem_Debug.mem.alloc, &pymalloc) &&
414 pymemallocator_eq(&_PyMem_Debug.obj.alloc, &pymalloc))
415 {
416 return "pymalloc_debug";
417 }
418#endif
419 }
420 return NULL;
421}
422
423
424#undef MALLOC_ALLOC
425#undef PYMALLOC_ALLOC
426#undef PYRAW_ALLOC
427#undef PYMEM_ALLOC
428#undef PYOBJ_ALLOC
429#undef PYDBGRAW_ALLOC
430#undef PYDBGMEM_ALLOC
431#undef PYDBGOBJ_ALLOC
432
Victor Stinner0507bf52013-07-07 02:05:46 +0200433
Victor Stinner9e87e772017-11-24 12:09:24 +0100434static PyObjectArenaAllocator _PyObject_Arena = {NULL,
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800435#ifdef MS_WINDOWS
Victor Stinner9e87e772017-11-24 12:09:24 +0100436 _PyObject_ArenaVirtualAlloc, _PyObject_ArenaVirtualFree
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800437#elif defined(ARENAS_USE_MMAP)
Victor Stinner9e87e772017-11-24 12:09:24 +0100438 _PyObject_ArenaMmap, _PyObject_ArenaMunmap
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800439#else
Victor Stinner9e87e772017-11-24 12:09:24 +0100440 _PyObject_ArenaMalloc, _PyObject_ArenaFree
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800441#endif
442 };
443
Victor Stinner0621e0e2016-04-19 17:02:55 +0200444#ifdef WITH_PYMALLOC
Victor Stinner34be807c2016-03-14 12:04:26 +0100445static int
446_PyMem_DebugEnabled(void)
447{
448 return (_PyObject.malloc == _PyMem_DebugMalloc);
449}
450
Victor Stinner6bf992a2017-12-06 17:26:10 +0100451static int
Victor Stinner34be807c2016-03-14 12:04:26 +0100452_PyMem_PymallocEnabled(void)
453{
454 if (_PyMem_DebugEnabled()) {
455 return (_PyMem_Debug.obj.alloc.malloc == _PyObject_Malloc);
456 }
457 else {
458 return (_PyObject.malloc == _PyObject_Malloc);
459 }
460}
461#endif
462
Victor Stinner5d39e042017-11-29 17:20:38 +0100463
464static void
465_PyMem_SetupDebugHooksDomain(PyMemAllocatorDomain domain)
Victor Stinner0507bf52013-07-07 02:05:46 +0200466{
Victor Stinnerd8f0d922014-06-02 21:57:10 +0200467 PyMemAllocatorEx alloc;
Victor Stinner0507bf52013-07-07 02:05:46 +0200468
Victor Stinner5d39e042017-11-29 17:20:38 +0100469 if (domain == PYMEM_DOMAIN_RAW) {
470 if (_PyMem_Raw.malloc == _PyMem_DebugRawMalloc) {
471 return;
472 }
Victor Stinner34be807c2016-03-14 12:04:26 +0100473
Victor Stinner0507bf52013-07-07 02:05:46 +0200474 PyMem_GetAllocator(PYMEM_DOMAIN_RAW, &_PyMem_Debug.raw.alloc);
Victor Stinner5d39e042017-11-29 17:20:38 +0100475 alloc.ctx = &_PyMem_Debug.raw;
476 alloc.malloc = _PyMem_DebugRawMalloc;
477 alloc.calloc = _PyMem_DebugRawCalloc;
478 alloc.realloc = _PyMem_DebugRawRealloc;
479 alloc.free = _PyMem_DebugRawFree;
Victor Stinner0507bf52013-07-07 02:05:46 +0200480 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &alloc);
481 }
Victor Stinner5d39e042017-11-29 17:20:38 +0100482 else if (domain == PYMEM_DOMAIN_MEM) {
483 if (_PyMem.malloc == _PyMem_DebugMalloc) {
484 return;
485 }
Victor Stinner0507bf52013-07-07 02:05:46 +0200486
Victor Stinnerad524372016-03-16 12:12:53 +0100487 PyMem_GetAllocator(PYMEM_DOMAIN_MEM, &_PyMem_Debug.mem.alloc);
Victor Stinner5d39e042017-11-29 17:20:38 +0100488 alloc.ctx = &_PyMem_Debug.mem;
489 alloc.malloc = _PyMem_DebugMalloc;
490 alloc.calloc = _PyMem_DebugCalloc;
491 alloc.realloc = _PyMem_DebugRealloc;
492 alloc.free = _PyMem_DebugFree;
Victor Stinnerad524372016-03-16 12:12:53 +0100493 PyMem_SetAllocator(PYMEM_DOMAIN_MEM, &alloc);
494 }
Victor Stinner5d39e042017-11-29 17:20:38 +0100495 else if (domain == PYMEM_DOMAIN_OBJ) {
496 if (_PyObject.malloc == _PyMem_DebugMalloc) {
497 return;
498 }
Victor Stinnerad524372016-03-16 12:12:53 +0100499
Victor Stinner0507bf52013-07-07 02:05:46 +0200500 PyMem_GetAllocator(PYMEM_DOMAIN_OBJ, &_PyMem_Debug.obj.alloc);
Victor Stinner5d39e042017-11-29 17:20:38 +0100501 alloc.ctx = &_PyMem_Debug.obj;
502 alloc.malloc = _PyMem_DebugMalloc;
503 alloc.calloc = _PyMem_DebugCalloc;
504 alloc.realloc = _PyMem_DebugRealloc;
505 alloc.free = _PyMem_DebugFree;
Victor Stinner0507bf52013-07-07 02:05:46 +0200506 PyMem_SetAllocator(PYMEM_DOMAIN_OBJ, &alloc);
507 }
Victor Stinner0507bf52013-07-07 02:05:46 +0200508}
509
Victor Stinner5d39e042017-11-29 17:20:38 +0100510
511void
512PyMem_SetupDebugHooks(void)
513{
514 _PyMem_SetupDebugHooksDomain(PYMEM_DOMAIN_RAW);
515 _PyMem_SetupDebugHooksDomain(PYMEM_DOMAIN_MEM);
516 _PyMem_SetupDebugHooksDomain(PYMEM_DOMAIN_OBJ);
517}
518
Victor Stinner0507bf52013-07-07 02:05:46 +0200519void
Victor Stinnerd8f0d922014-06-02 21:57:10 +0200520PyMem_GetAllocator(PyMemAllocatorDomain domain, PyMemAllocatorEx *allocator)
Victor Stinner0507bf52013-07-07 02:05:46 +0200521{
522 switch(domain)
523 {
524 case PYMEM_DOMAIN_RAW: *allocator = _PyMem_Raw; break;
525 case PYMEM_DOMAIN_MEM: *allocator = _PyMem; break;
526 case PYMEM_DOMAIN_OBJ: *allocator = _PyObject; break;
527 default:
Victor Stinnerdb067af2014-05-02 22:31:14 +0200528 /* unknown domain: set all attributes to NULL */
Victor Stinner0507bf52013-07-07 02:05:46 +0200529 allocator->ctx = NULL;
530 allocator->malloc = NULL;
Victor Stinnerdb067af2014-05-02 22:31:14 +0200531 allocator->calloc = NULL;
Victor Stinner0507bf52013-07-07 02:05:46 +0200532 allocator->realloc = NULL;
533 allocator->free = NULL;
534 }
535}
536
537void
Victor Stinnerd8f0d922014-06-02 21:57:10 +0200538PyMem_SetAllocator(PyMemAllocatorDomain domain, PyMemAllocatorEx *allocator)
Victor Stinner0507bf52013-07-07 02:05:46 +0200539{
540 switch(domain)
541 {
542 case PYMEM_DOMAIN_RAW: _PyMem_Raw = *allocator; break;
543 case PYMEM_DOMAIN_MEM: _PyMem = *allocator; break;
544 case PYMEM_DOMAIN_OBJ: _PyObject = *allocator; break;
545 /* ignore unknown domain */
546 }
Victor Stinner0507bf52013-07-07 02:05:46 +0200547}
548
549void
550PyObject_GetArenaAllocator(PyObjectArenaAllocator *allocator)
551{
Victor Stinner9e87e772017-11-24 12:09:24 +0100552 *allocator = _PyObject_Arena;
Victor Stinner0507bf52013-07-07 02:05:46 +0200553}
554
555void
556PyObject_SetArenaAllocator(PyObjectArenaAllocator *allocator)
557{
Victor Stinner9e87e772017-11-24 12:09:24 +0100558 _PyObject_Arena = *allocator;
Victor Stinner0507bf52013-07-07 02:05:46 +0200559}
560
561void *
562PyMem_RawMalloc(size_t size)
563{
564 /*
565 * Limit ourselves to PY_SSIZE_T_MAX bytes to prevent security holes.
566 * Most python internals blindly use a signed Py_ssize_t to track
567 * things without checking for overflows or negatives.
568 * As size_t is unsigned, checking for size < 0 is not required.
569 */
570 if (size > (size_t)PY_SSIZE_T_MAX)
571 return NULL;
Victor Stinner0507bf52013-07-07 02:05:46 +0200572 return _PyMem_Raw.malloc(_PyMem_Raw.ctx, size);
573}
574
Victor Stinnerdb067af2014-05-02 22:31:14 +0200575void *
576PyMem_RawCalloc(size_t nelem, size_t elsize)
577{
578 /* see PyMem_RawMalloc() */
579 if (elsize != 0 && nelem > (size_t)PY_SSIZE_T_MAX / elsize)
580 return NULL;
581 return _PyMem_Raw.calloc(_PyMem_Raw.ctx, nelem, elsize);
582}
583
Victor Stinner0507bf52013-07-07 02:05:46 +0200584void*
585PyMem_RawRealloc(void *ptr, size_t new_size)
586{
587 /* see PyMem_RawMalloc() */
588 if (new_size > (size_t)PY_SSIZE_T_MAX)
589 return NULL;
590 return _PyMem_Raw.realloc(_PyMem_Raw.ctx, ptr, new_size);
591}
592
Victor Stinner9e87e772017-11-24 12:09:24 +0100593void PyMem_RawFree(void *ptr)
Victor Stinner0507bf52013-07-07 02:05:46 +0200594{
595 _PyMem_Raw.free(_PyMem_Raw.ctx, ptr);
596}
597
Victor Stinner9ed83c42017-10-31 12:18:10 -0700598
Victor Stinner0507bf52013-07-07 02:05:46 +0200599void *
600PyMem_Malloc(size_t size)
601{
602 /* see PyMem_RawMalloc() */
603 if (size > (size_t)PY_SSIZE_T_MAX)
604 return NULL;
605 return _PyMem.malloc(_PyMem.ctx, size);
606}
607
608void *
Victor Stinnerdb067af2014-05-02 22:31:14 +0200609PyMem_Calloc(size_t nelem, size_t elsize)
610{
611 /* see PyMem_RawMalloc() */
612 if (elsize != 0 && nelem > (size_t)PY_SSIZE_T_MAX / elsize)
613 return NULL;
614 return _PyMem.calloc(_PyMem.ctx, nelem, elsize);
615}
616
617void *
Victor Stinner0507bf52013-07-07 02:05:46 +0200618PyMem_Realloc(void *ptr, size_t new_size)
619{
620 /* see PyMem_RawMalloc() */
621 if (new_size > (size_t)PY_SSIZE_T_MAX)
622 return NULL;
623 return _PyMem.realloc(_PyMem.ctx, ptr, new_size);
624}
625
626void
627PyMem_Free(void *ptr)
628{
629 _PyMem.free(_PyMem.ctx, ptr);
630}
631
Victor Stinner9ed83c42017-10-31 12:18:10 -0700632
Victor Stinner46972b72017-11-24 22:55:40 +0100633wchar_t*
634_PyMem_RawWcsdup(const wchar_t *str)
635{
Victor Stinnerb64de462017-12-01 18:27:09 +0100636 assert(str != NULL);
637
Victor Stinner46972b72017-11-24 22:55:40 +0100638 size_t len = wcslen(str);
639 if (len > (size_t)PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
640 return NULL;
641 }
642
643 size_t size = (len + 1) * sizeof(wchar_t);
644 wchar_t *str2 = PyMem_RawMalloc(size);
645 if (str2 == NULL) {
646 return NULL;
647 }
648
649 memcpy(str2, str, size);
650 return str2;
651}
652
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200653char *
654_PyMem_RawStrdup(const char *str)
655{
Victor Stinnerb64de462017-12-01 18:27:09 +0100656 assert(str != NULL);
657 size_t size = strlen(str) + 1;
658 char *copy = PyMem_RawMalloc(size);
659 if (copy == NULL) {
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200660 return NULL;
Victor Stinnerb64de462017-12-01 18:27:09 +0100661 }
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200662 memcpy(copy, str, size);
663 return copy;
664}
665
666char *
667_PyMem_Strdup(const char *str)
668{
Victor Stinnerb64de462017-12-01 18:27:09 +0100669 assert(str != NULL);
670 size_t size = strlen(str) + 1;
671 char *copy = PyMem_Malloc(size);
672 if (copy == NULL) {
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200673 return NULL;
Victor Stinnerb64de462017-12-01 18:27:09 +0100674 }
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200675 memcpy(copy, str, size);
676 return copy;
677}
678
Victor Stinner0507bf52013-07-07 02:05:46 +0200679void *
680PyObject_Malloc(size_t size)
681{
682 /* see PyMem_RawMalloc() */
683 if (size > (size_t)PY_SSIZE_T_MAX)
684 return NULL;
685 return _PyObject.malloc(_PyObject.ctx, size);
686}
687
688void *
Victor Stinnerdb067af2014-05-02 22:31:14 +0200689PyObject_Calloc(size_t nelem, size_t elsize)
690{
691 /* see PyMem_RawMalloc() */
692 if (elsize != 0 && nelem > (size_t)PY_SSIZE_T_MAX / elsize)
693 return NULL;
694 return _PyObject.calloc(_PyObject.ctx, nelem, elsize);
695}
696
697void *
Victor Stinner0507bf52013-07-07 02:05:46 +0200698PyObject_Realloc(void *ptr, size_t new_size)
699{
700 /* see PyMem_RawMalloc() */
701 if (new_size > (size_t)PY_SSIZE_T_MAX)
702 return NULL;
703 return _PyObject.realloc(_PyObject.ctx, ptr, new_size);
704}
705
706void
707PyObject_Free(void *ptr)
708{
709 _PyObject.free(_PyObject.ctx, ptr);
710}
711
712
713#ifdef WITH_PYMALLOC
714
Benjamin Peterson05159c42009-12-03 03:01:27 +0000715#ifdef WITH_VALGRIND
716#include <valgrind/valgrind.h>
717
718/* If we're using GCC, use __builtin_expect() to reduce overhead of
719 the valgrind checks */
720#if defined(__GNUC__) && (__GNUC__ > 2) && defined(__OPTIMIZE__)
721# define UNLIKELY(value) __builtin_expect((value), 0)
722#else
723# define UNLIKELY(value) (value)
724#endif
725
726/* -1 indicates that we haven't checked that we're running on valgrind yet. */
727static int running_on_valgrind = -1;
728#endif
729
Victor Stinner9ed83c42017-10-31 12:18:10 -0700730
Victor Stinner9e87e772017-11-24 12:09:24 +0100731/* An object allocator for Python.
732
733 Here is an introduction to the layers of the Python memory architecture,
734 showing where the object allocator is actually used (layer +2), It is
735 called for every object allocation and deallocation (PyObject_New/Del),
736 unless the object-specific allocators implement a proprietary allocation
737 scheme (ex.: ints use a simple free list). This is also the place where
738 the cyclic garbage collector operates selectively on container objects.
739
740
741 Object-specific allocators
742 _____ ______ ______ ________
743 [ int ] [ dict ] [ list ] ... [ string ] Python core |
744+3 | <----- Object-specific memory -----> | <-- Non-object memory --> |
745 _______________________________ | |
746 [ Python's object allocator ] | |
747+2 | ####### Object memory ####### | <------ Internal buffers ------> |
748 ______________________________________________________________ |
749 [ Python's raw memory allocator (PyMem_ API) ] |
750+1 | <----- Python memory (under PyMem manager's control) ------> | |
751 __________________________________________________________________
752 [ Underlying general-purpose allocator (ex: C library malloc) ]
753 0 | <------ Virtual memory allocated for the python process -------> |
754
755 =========================================================================
756 _______________________________________________________________________
757 [ OS-specific Virtual Memory Manager (VMM) ]
758-1 | <--- Kernel dynamic storage allocation & management (page-based) ---> |
759 __________________________________ __________________________________
760 [ ] [ ]
761-2 | <-- Physical memory: ROM/RAM --> | | <-- Secondary storage (swap) --> |
762
763*/
764/*==========================================================================*/
765
766/* A fast, special-purpose memory allocator for small blocks, to be used
767 on top of a general-purpose malloc -- heavily based on previous art. */
768
769/* Vladimir Marangozov -- August 2000 */
770
771/*
772 * "Memory management is where the rubber meets the road -- if we do the wrong
773 * thing at any level, the results will not be good. And if we don't make the
774 * levels work well together, we are in serious trouble." (1)
775 *
776 * (1) Paul R. Wilson, Mark S. Johnstone, Michael Neely, and David Boles,
777 * "Dynamic Storage Allocation: A Survey and Critical Review",
778 * in Proc. 1995 Int'l. Workshop on Memory Management, September 1995.
779 */
780
781/* #undef WITH_MEMORY_LIMITS */ /* disable mem limit checks */
782
783/*==========================================================================*/
784
785/*
786 * Allocation strategy abstract:
787 *
788 * For small requests, the allocator sub-allocates <Big> blocks of memory.
789 * Requests greater than SMALL_REQUEST_THRESHOLD bytes are routed to the
790 * system's allocator.
791 *
792 * Small requests are grouped in size classes spaced 8 bytes apart, due
793 * to the required valid alignment of the returned address. Requests of
794 * a particular size are serviced from memory pools of 4K (one VMM page).
795 * Pools are fragmented on demand and contain free lists of blocks of one
796 * particular size class. In other words, there is a fixed-size allocator
797 * for each size class. Free pools are shared by the different allocators
798 * thus minimizing the space reserved for a particular size class.
799 *
800 * This allocation strategy is a variant of what is known as "simple
801 * segregated storage based on array of free lists". The main drawback of
802 * simple segregated storage is that we might end up with lot of reserved
803 * memory for the different free lists, which degenerate in time. To avoid
804 * this, we partition each free list in pools and we share dynamically the
805 * reserved space between all free lists. This technique is quite efficient
806 * for memory intensive programs which allocate mainly small-sized blocks.
807 *
808 * For small requests we have the following table:
809 *
810 * Request in bytes Size of allocated block Size class idx
811 * ----------------------------------------------------------------
812 * 1-8 8 0
813 * 9-16 16 1
814 * 17-24 24 2
815 * 25-32 32 3
816 * 33-40 40 4
817 * 41-48 48 5
818 * 49-56 56 6
819 * 57-64 64 7
820 * 65-72 72 8
821 * ... ... ...
822 * 497-504 504 62
823 * 505-512 512 63
824 *
825 * 0, SMALL_REQUEST_THRESHOLD + 1 and up: routed to the underlying
826 * allocator.
827 */
828
829/*==========================================================================*/
830
831/*
832 * -- Main tunable settings section --
833 */
834
835/*
836 * Alignment of addresses returned to the user. 8-bytes alignment works
837 * on most current architectures (with 32-bit or 64-bit address busses).
838 * The alignment value is also used for grouping small requests in size
839 * classes spaced ALIGNMENT bytes apart.
840 *
841 * You shouldn't change this unless you know what you are doing.
842 */
Inada Naokif0be4bb2019-05-14 18:51:15 +0900843
844#if SIZEOF_VOID_P > 4
845#define ALIGNMENT 16 /* must be 2^N */
846#define ALIGNMENT_SHIFT 4
847#else
Victor Stinner9e87e772017-11-24 12:09:24 +0100848#define ALIGNMENT 8 /* must be 2^N */
849#define ALIGNMENT_SHIFT 3
Inada Naokif0be4bb2019-05-14 18:51:15 +0900850#endif
Victor Stinner9e87e772017-11-24 12:09:24 +0100851
852/* Return the number of bytes in size class I, as a uint. */
853#define INDEX2SIZE(I) (((uint)(I) + 1) << ALIGNMENT_SHIFT)
854
855/*
856 * Max size threshold below which malloc requests are considered to be
857 * small enough in order to use preallocated memory pools. You can tune
858 * this value according to your application behaviour and memory needs.
859 *
860 * Note: a size threshold of 512 guarantees that newly created dictionaries
861 * will be allocated from preallocated memory pools on 64-bit.
862 *
863 * The following invariants must hold:
864 * 1) ALIGNMENT <= SMALL_REQUEST_THRESHOLD <= 512
865 * 2) SMALL_REQUEST_THRESHOLD is evenly divisible by ALIGNMENT
866 *
867 * Although not required, for better performance and space efficiency,
868 * it is recommended that SMALL_REQUEST_THRESHOLD is set to a power of 2.
869 */
870#define SMALL_REQUEST_THRESHOLD 512
871#define NB_SMALL_SIZE_CLASSES (SMALL_REQUEST_THRESHOLD / ALIGNMENT)
872
873/*
874 * The system's VMM page size can be obtained on most unices with a
875 * getpagesize() call or deduced from various header files. To make
876 * things simpler, we assume that it is 4K, which is OK for most systems.
877 * It is probably better if this is the native page size, but it doesn't
878 * have to be. In theory, if SYSTEM_PAGE_SIZE is larger than the native page
879 * size, then `POOL_ADDR(p)->arenaindex' could rarely cause a segmentation
880 * violation fault. 4K is apparently OK for all the platforms that python
881 * currently targets.
882 */
883#define SYSTEM_PAGE_SIZE (4 * 1024)
884#define SYSTEM_PAGE_SIZE_MASK (SYSTEM_PAGE_SIZE - 1)
885
886/*
887 * Maximum amount of memory managed by the allocator for small requests.
888 */
889#ifdef WITH_MEMORY_LIMITS
890#ifndef SMALL_MEMORY_LIMIT
891#define SMALL_MEMORY_LIMIT (64 * 1024 * 1024) /* 64 MB -- more? */
892#endif
893#endif
894
895/*
896 * The allocator sub-allocates <Big> blocks of memory (called arenas) aligned
897 * on a page boundary. This is a reserved virtual address space for the
898 * current process (obtained through a malloc()/mmap() call). In no way this
899 * means that the memory arenas will be used entirely. A malloc(<Big>) is
900 * usually an address range reservation for <Big> bytes, unless all pages within
901 * this space are referenced subsequently. So malloc'ing big blocks and not
902 * using them does not mean "wasting memory". It's an addressable range
903 * wastage...
904 *
905 * Arenas are allocated with mmap() on systems supporting anonymous memory
906 * mappings to reduce heap fragmentation.
907 */
908#define ARENA_SIZE (256 << 10) /* 256KB */
909
910#ifdef WITH_MEMORY_LIMITS
911#define MAX_ARENAS (SMALL_MEMORY_LIMIT / ARENA_SIZE)
912#endif
913
914/*
915 * Size of the pools used for small blocks. Should be a power of 2,
916 * between 1K and SYSTEM_PAGE_SIZE, that is: 1k, 2k, 4k.
917 */
918#define POOL_SIZE SYSTEM_PAGE_SIZE /* must be 2^N */
919#define POOL_SIZE_MASK SYSTEM_PAGE_SIZE_MASK
920
921/*
922 * -- End of tunable settings section --
923 */
924
925/*==========================================================================*/
926
Victor Stinner9e87e772017-11-24 12:09:24 +0100927/* When you say memory, my mind reasons in terms of (pointers to) blocks */
928typedef uint8_t block;
929
930/* Pool for small blocks. */
931struct pool_header {
932 union { block *_padding;
933 uint count; } ref; /* number of allocated blocks */
934 block *freeblock; /* pool's free list head */
935 struct pool_header *nextpool; /* next pool of this size class */
936 struct pool_header *prevpool; /* previous pool "" */
937 uint arenaindex; /* index into arenas of base adr */
938 uint szidx; /* block size class index */
939 uint nextoffset; /* bytes to virgin block */
940 uint maxnextoffset; /* largest valid nextoffset */
941};
942
943typedef struct pool_header *poolp;
944
945/* Record keeping for arenas. */
946struct arena_object {
947 /* The address of the arena, as returned by malloc. Note that 0
948 * will never be returned by a successful malloc, and is used
949 * here to mark an arena_object that doesn't correspond to an
950 * allocated arena.
951 */
952 uintptr_t address;
953
954 /* Pool-aligned pointer to the next pool to be carved off. */
955 block* pool_address;
956
957 /* The number of available pools in the arena: free pools + never-
958 * allocated pools.
959 */
960 uint nfreepools;
961
962 /* The total number of pools in the arena, whether or not available. */
963 uint ntotalpools;
964
965 /* Singly-linked list of available pools. */
966 struct pool_header* freepools;
967
968 /* Whenever this arena_object is not associated with an allocated
969 * arena, the nextarena member is used to link all unassociated
970 * arena_objects in the singly-linked `unused_arena_objects` list.
971 * The prevarena member is unused in this case.
972 *
973 * When this arena_object is associated with an allocated arena
974 * with at least one available pool, both members are used in the
975 * doubly-linked `usable_arenas` list, which is maintained in
976 * increasing order of `nfreepools` values.
977 *
978 * Else this arena_object is associated with an allocated arena
979 * all of whose pools are in use. `nextarena` and `prevarena`
980 * are both meaningless in this case.
981 */
982 struct arena_object* nextarena;
983 struct arena_object* prevarena;
984};
985
986#define POOL_OVERHEAD _Py_SIZE_ROUND_UP(sizeof(struct pool_header), ALIGNMENT)
987
988#define DUMMY_SIZE_IDX 0xffff /* size class of newly cached pools */
989
990/* Round pointer P down to the closest pool-aligned address <= P, as a poolp */
991#define POOL_ADDR(P) ((poolp)_Py_ALIGN_DOWN((P), POOL_SIZE))
992
993/* Return total number of blocks in pool of size index I, as a uint. */
994#define NUMBLOCKS(I) ((uint)(POOL_SIZE - POOL_OVERHEAD) / INDEX2SIZE(I))
995
996/*==========================================================================*/
997
998/*
Victor Stinner9e87e772017-11-24 12:09:24 +0100999 * Pool table -- headed, circular, doubly-linked lists of partially used pools.
1000
1001This is involved. For an index i, usedpools[i+i] is the header for a list of
1002all partially used pools holding small blocks with "size class idx" i. So
1003usedpools[0] corresponds to blocks of size 8, usedpools[2] to blocks of size
100416, and so on: index 2*i <-> blocks of size (i+1)<<ALIGNMENT_SHIFT.
1005
1006Pools are carved off an arena's highwater mark (an arena_object's pool_address
1007member) as needed. Once carved off, a pool is in one of three states forever
1008after:
1009
1010used == partially used, neither empty nor full
1011 At least one block in the pool is currently allocated, and at least one
1012 block in the pool is not currently allocated (note this implies a pool
1013 has room for at least two blocks).
1014 This is a pool's initial state, as a pool is created only when malloc
1015 needs space.
1016 The pool holds blocks of a fixed size, and is in the circular list headed
1017 at usedpools[i] (see above). It's linked to the other used pools of the
1018 same size class via the pool_header's nextpool and prevpool members.
1019 If all but one block is currently allocated, a malloc can cause a
1020 transition to the full state. If all but one block is not currently
1021 allocated, a free can cause a transition to the empty state.
1022
1023full == all the pool's blocks are currently allocated
1024 On transition to full, a pool is unlinked from its usedpools[] list.
1025 It's not linked to from anything then anymore, and its nextpool and
1026 prevpool members are meaningless until it transitions back to used.
1027 A free of a block in a full pool puts the pool back in the used state.
1028 Then it's linked in at the front of the appropriate usedpools[] list, so
1029 that the next allocation for its size class will reuse the freed block.
1030
1031empty == all the pool's blocks are currently available for allocation
1032 On transition to empty, a pool is unlinked from its usedpools[] list,
1033 and linked to the front of its arena_object's singly-linked freepools list,
1034 via its nextpool member. The prevpool member has no meaning in this case.
1035 Empty pools have no inherent size class: the next time a malloc finds
1036 an empty list in usedpools[], it takes the first pool off of freepools.
1037 If the size class needed happens to be the same as the size class the pool
1038 last had, some pool initialization can be skipped.
1039
1040
1041Block Management
1042
1043Blocks within pools are again carved out as needed. pool->freeblock points to
1044the start of a singly-linked list of free blocks within the pool. When a
1045block is freed, it's inserted at the front of its pool's freeblock list. Note
1046that the available blocks in a pool are *not* linked all together when a pool
1047is initialized. Instead only "the first two" (lowest addresses) blocks are
1048set up, returning the first such block, and setting pool->freeblock to a
1049one-block list holding the second such block. This is consistent with that
1050pymalloc strives at all levels (arena, pool, and block) never to touch a piece
1051of memory until it's actually needed.
1052
1053So long as a pool is in the used state, we're certain there *is* a block
1054available for allocating, and pool->freeblock is not NULL. If pool->freeblock
1055points to the end of the free list before we've carved the entire pool into
1056blocks, that means we simply haven't yet gotten to one of the higher-address
1057blocks. The offset from the pool_header to the start of "the next" virgin
1058block is stored in the pool_header nextoffset member, and the largest value
1059of nextoffset that makes sense is stored in the maxnextoffset member when a
1060pool is initialized. All the blocks in a pool have been passed out at least
1061once when and only when nextoffset > maxnextoffset.
1062
1063
1064Major obscurity: While the usedpools vector is declared to have poolp
1065entries, it doesn't really. It really contains two pointers per (conceptual)
1066poolp entry, the nextpool and prevpool members of a pool_header. The
1067excruciating initialization code below fools C so that
1068
1069 usedpool[i+i]
1070
1071"acts like" a genuine poolp, but only so long as you only reference its
1072nextpool and prevpool members. The "- 2*sizeof(block *)" gibberish is
1073compensating for that a pool_header's nextpool and prevpool members
1074immediately follow a pool_header's first two members:
1075
1076 union { block *_padding;
1077 uint count; } ref;
1078 block *freeblock;
1079
1080each of which consume sizeof(block *) bytes. So what usedpools[i+i] really
1081contains is a fudged-up pointer p such that *if* C believes it's a poolp
1082pointer, then p->nextpool and p->prevpool are both p (meaning that the headed
1083circular list is empty).
1084
1085It's unclear why the usedpools setup is so convoluted. It could be to
1086minimize the amount of cache required to hold this heavily-referenced table
1087(which only *needs* the two interpool pointer members of a pool_header). OTOH,
1088referencing code has to remember to "double the index" and doing so isn't
1089free, usedpools[0] isn't a strictly legal pointer, and we're crucially relying
1090on that C doesn't insert any padding anywhere in a pool_header at or before
1091the prevpool member.
1092**************************************************************************** */
1093
1094#define PTA(x) ((poolp )((uint8_t *)&(usedpools[2*(x)]) - 2*sizeof(block *)))
1095#define PT(x) PTA(x), PTA(x)
1096
1097static poolp usedpools[2 * ((NB_SMALL_SIZE_CLASSES + 7) / 8) * 8] = {
1098 PT(0), PT(1), PT(2), PT(3), PT(4), PT(5), PT(6), PT(7)
1099#if NB_SMALL_SIZE_CLASSES > 8
1100 , PT(8), PT(9), PT(10), PT(11), PT(12), PT(13), PT(14), PT(15)
1101#if NB_SMALL_SIZE_CLASSES > 16
1102 , PT(16), PT(17), PT(18), PT(19), PT(20), PT(21), PT(22), PT(23)
1103#if NB_SMALL_SIZE_CLASSES > 24
1104 , PT(24), PT(25), PT(26), PT(27), PT(28), PT(29), PT(30), PT(31)
1105#if NB_SMALL_SIZE_CLASSES > 32
1106 , PT(32), PT(33), PT(34), PT(35), PT(36), PT(37), PT(38), PT(39)
1107#if NB_SMALL_SIZE_CLASSES > 40
1108 , PT(40), PT(41), PT(42), PT(43), PT(44), PT(45), PT(46), PT(47)
1109#if NB_SMALL_SIZE_CLASSES > 48
1110 , PT(48), PT(49), PT(50), PT(51), PT(52), PT(53), PT(54), PT(55)
1111#if NB_SMALL_SIZE_CLASSES > 56
1112 , PT(56), PT(57), PT(58), PT(59), PT(60), PT(61), PT(62), PT(63)
1113#if NB_SMALL_SIZE_CLASSES > 64
1114#error "NB_SMALL_SIZE_CLASSES should be less than 64"
1115#endif /* NB_SMALL_SIZE_CLASSES > 64 */
1116#endif /* NB_SMALL_SIZE_CLASSES > 56 */
1117#endif /* NB_SMALL_SIZE_CLASSES > 48 */
1118#endif /* NB_SMALL_SIZE_CLASSES > 40 */
1119#endif /* NB_SMALL_SIZE_CLASSES > 32 */
1120#endif /* NB_SMALL_SIZE_CLASSES > 24 */
1121#endif /* NB_SMALL_SIZE_CLASSES > 16 */
1122#endif /* NB_SMALL_SIZE_CLASSES > 8 */
1123};
1124
1125/*==========================================================================
1126Arena management.
1127
1128`arenas` is a vector of arena_objects. It contains maxarenas entries, some of
1129which may not be currently used (== they're arena_objects that aren't
1130currently associated with an allocated arena). Note that arenas proper are
1131separately malloc'ed.
1132
1133Prior to Python 2.5, arenas were never free()'ed. Starting with Python 2.5,
1134we do try to free() arenas, and use some mild heuristic strategies to increase
1135the likelihood that arenas eventually can be freed.
1136
1137unused_arena_objects
1138
1139 This is a singly-linked list of the arena_objects that are currently not
1140 being used (no arena is associated with them). Objects are taken off the
1141 head of the list in new_arena(), and are pushed on the head of the list in
1142 PyObject_Free() when the arena is empty. Key invariant: an arena_object
1143 is on this list if and only if its .address member is 0.
1144
1145usable_arenas
1146
1147 This is a doubly-linked list of the arena_objects associated with arenas
1148 that have pools available. These pools are either waiting to be reused,
1149 or have not been used before. The list is sorted to have the most-
1150 allocated arenas first (ascending order based on the nfreepools member).
1151 This means that the next allocation will come from a heavily used arena,
1152 which gives the nearly empty arenas a chance to be returned to the system.
1153 In my unscientific tests this dramatically improved the number of arenas
1154 that could be freed.
1155
1156Note that an arena_object associated with an arena all of whose pools are
1157currently in use isn't on either list.
1158*/
1159
1160/* Array of objects used to track chunks of memory (arenas). */
1161static struct arena_object* arenas = NULL;
1162/* Number of slots currently allocated in the `arenas` vector. */
1163static uint maxarenas = 0;
1164
1165/* The head of the singly-linked, NULL-terminated list of available
1166 * arena_objects.
1167 */
1168static struct arena_object* unused_arena_objects = NULL;
1169
1170/* The head of the doubly-linked, NULL-terminated at each end, list of
1171 * arena_objects associated with arenas that have pools available.
1172 */
1173static struct arena_object* usable_arenas = NULL;
1174
1175/* How many arena_objects do we initially allocate?
1176 * 16 = can allocate 16 arenas = 16 * ARENA_SIZE = 4MB before growing the
1177 * `arenas` vector.
1178 */
1179#define INITIAL_ARENA_OBJECTS 16
1180
1181/* Number of arenas allocated that haven't been free()'d. */
1182static size_t narenas_currently_allocated = 0;
1183
1184/* Total number of times malloc() called to allocate an arena. */
1185static size_t ntimes_arena_allocated = 0;
1186/* High water mark (max value ever seen) for narenas_currently_allocated. */
1187static size_t narenas_highwater = 0;
1188
1189static Py_ssize_t _Py_AllocatedBlocks = 0;
1190
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001191Py_ssize_t
1192_Py_GetAllocatedBlocks(void)
1193{
Victor Stinner9e87e772017-11-24 12:09:24 +01001194 return _Py_AllocatedBlocks;
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001195}
1196
1197
Thomas Woutersa9773292006-04-21 09:43:23 +00001198/* Allocate a new arena. If we run out of memory, return NULL. Else
1199 * allocate a new arena, and return the address of an arena_object
1200 * describing the new arena. It's expected that the caller will set
1201 * `usable_arenas` to the return value.
1202 */
1203static struct arena_object*
Tim Petersd97a1c02002-03-30 06:09:22 +00001204new_arena(void)
1205{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001206 struct arena_object* arenaobj;
1207 uint excess; /* number of bytes above pool alignment */
Victor Stinnerba108822012-03-10 00:21:44 +01001208 void *address;
Victor Stinner34be807c2016-03-14 12:04:26 +01001209 static int debug_stats = -1;
Tim Petersd97a1c02002-03-30 06:09:22 +00001210
Victor Stinner34be807c2016-03-14 12:04:26 +01001211 if (debug_stats == -1) {
Serhiy Storchaka4ae06c52017-12-12 13:55:04 +02001212 const char *opt = Py_GETENV("PYTHONMALLOCSTATS");
Victor Stinner34be807c2016-03-14 12:04:26 +01001213 debug_stats = (opt != NULL && *opt != '\0');
1214 }
1215 if (debug_stats)
David Malcolm49526f42012-06-22 14:55:41 -04001216 _PyObject_DebugMallocStats(stderr);
Victor Stinner34be807c2016-03-14 12:04:26 +01001217
Victor Stinner9e87e772017-11-24 12:09:24 +01001218 if (unused_arena_objects == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001219 uint i;
1220 uint numarenas;
1221 size_t nbytes;
Tim Peters0e871182002-04-13 08:29:14 +00001222
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001223 /* Double the number of arena objects on each allocation.
1224 * Note that it's possible for `numarenas` to overflow.
1225 */
Victor Stinner9e87e772017-11-24 12:09:24 +01001226 numarenas = maxarenas ? maxarenas << 1 : INITIAL_ARENA_OBJECTS;
1227 if (numarenas <= maxarenas)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001228 return NULL; /* overflow */
Martin v. Löwis5aca8822008-09-11 06:55:48 +00001229#if SIZEOF_SIZE_T <= SIZEOF_INT
Victor Stinner9e87e772017-11-24 12:09:24 +01001230 if (numarenas > SIZE_MAX / sizeof(*arenas))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001231 return NULL; /* overflow */
Martin v. Löwis5aca8822008-09-11 06:55:48 +00001232#endif
Victor Stinner9e87e772017-11-24 12:09:24 +01001233 nbytes = numarenas * sizeof(*arenas);
1234 arenaobj = (struct arena_object *)PyMem_RawRealloc(arenas, nbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001235 if (arenaobj == NULL)
1236 return NULL;
Victor Stinner9e87e772017-11-24 12:09:24 +01001237 arenas = arenaobj;
Thomas Woutersa9773292006-04-21 09:43:23 +00001238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001239 /* We might need to fix pointers that were copied. However,
1240 * new_arena only gets called when all the pages in the
1241 * previous arenas are full. Thus, there are *no* pointers
1242 * into the old array. Thus, we don't have to worry about
1243 * invalid pointers. Just to be sure, some asserts:
1244 */
Victor Stinner9e87e772017-11-24 12:09:24 +01001245 assert(usable_arenas == NULL);
1246 assert(unused_arena_objects == NULL);
Thomas Woutersa9773292006-04-21 09:43:23 +00001247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001248 /* Put the new arenas on the unused_arena_objects list. */
Victor Stinner9e87e772017-11-24 12:09:24 +01001249 for (i = maxarenas; i < numarenas; ++i) {
1250 arenas[i].address = 0; /* mark as unassociated */
1251 arenas[i].nextarena = i < numarenas - 1 ?
1252 &arenas[i+1] : NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001253 }
Thomas Woutersa9773292006-04-21 09:43:23 +00001254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001255 /* Update globals. */
Victor Stinner9e87e772017-11-24 12:09:24 +01001256 unused_arena_objects = &arenas[maxarenas];
1257 maxarenas = numarenas;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001258 }
Tim Petersd97a1c02002-03-30 06:09:22 +00001259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001260 /* Take the next available arena object off the head of the list. */
Victor Stinner9e87e772017-11-24 12:09:24 +01001261 assert(unused_arena_objects != NULL);
1262 arenaobj = unused_arena_objects;
1263 unused_arena_objects = arenaobj->nextarena;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001264 assert(arenaobj->address == 0);
Victor Stinner9e87e772017-11-24 12:09:24 +01001265 address = _PyObject_Arena.alloc(_PyObject_Arena.ctx, ARENA_SIZE);
Victor Stinner0507bf52013-07-07 02:05:46 +02001266 if (address == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001267 /* The allocation failed: return NULL after putting the
1268 * arenaobj back.
1269 */
Victor Stinner9e87e772017-11-24 12:09:24 +01001270 arenaobj->nextarena = unused_arena_objects;
1271 unused_arena_objects = arenaobj;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 return NULL;
1273 }
Benjamin Peterson5d4b09c2016-09-18 19:24:52 -07001274 arenaobj->address = (uintptr_t)address;
Tim Petersd97a1c02002-03-30 06:09:22 +00001275
Victor Stinner9e87e772017-11-24 12:09:24 +01001276 ++narenas_currently_allocated;
1277 ++ntimes_arena_allocated;
1278 if (narenas_currently_allocated > narenas_highwater)
1279 narenas_highwater = narenas_currently_allocated;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001280 arenaobj->freepools = NULL;
1281 /* pool_address <- first pool-aligned address in the arena
1282 nfreepools <- number of whole pools that fit after alignment */
Victor Stinner9e87e772017-11-24 12:09:24 +01001283 arenaobj->pool_address = (block*)arenaobj->address;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001284 arenaobj->nfreepools = ARENA_SIZE / POOL_SIZE;
1285 assert(POOL_SIZE * arenaobj->nfreepools == ARENA_SIZE);
1286 excess = (uint)(arenaobj->address & POOL_SIZE_MASK);
1287 if (excess != 0) {
1288 --arenaobj->nfreepools;
1289 arenaobj->pool_address += POOL_SIZE - excess;
1290 }
1291 arenaobj->ntotalpools = arenaobj->nfreepools;
Thomas Woutersa9773292006-04-21 09:43:23 +00001292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001293 return arenaobj;
Tim Petersd97a1c02002-03-30 06:09:22 +00001294}
1295
Victor Stinner9ed83c42017-10-31 12:18:10 -07001296
Thomas Woutersa9773292006-04-21 09:43:23 +00001297/*
Benjamin Peterson3924f932016-09-18 19:12:48 -07001298address_in_range(P, POOL)
Thomas Woutersa9773292006-04-21 09:43:23 +00001299
1300Return true if and only if P is an address that was allocated by pymalloc.
1301POOL must be the pool address associated with P, i.e., POOL = POOL_ADDR(P)
1302(the caller is asked to compute this because the macro expands POOL more than
1303once, and for efficiency it's best for the caller to assign POOL_ADDR(P) to a
Benjamin Peterson3924f932016-09-18 19:12:48 -07001304variable and pass the latter to the macro; because address_in_range is
Thomas Woutersa9773292006-04-21 09:43:23 +00001305called on every alloc/realloc/free, micro-efficiency is important here).
1306
1307Tricky: Let B be the arena base address associated with the pool, B =
1308arenas[(POOL)->arenaindex].address. Then P belongs to the arena if and only if
1309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001310 B <= P < B + ARENA_SIZE
Thomas Woutersa9773292006-04-21 09:43:23 +00001311
1312Subtracting B throughout, this is true iff
1313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001314 0 <= P-B < ARENA_SIZE
Thomas Woutersa9773292006-04-21 09:43:23 +00001315
1316By using unsigned arithmetic, the "0 <=" half of the test can be skipped.
1317
1318Obscure: A PyMem "free memory" function can call the pymalloc free or realloc
1319before the first arena has been allocated. `arenas` is still NULL in that
1320case. We're relying on that maxarenas is also 0 in that case, so that
1321(POOL)->arenaindex < maxarenas must be false, saving us from trying to index
1322into a NULL arenas.
1323
1324Details: given P and POOL, the arena_object corresponding to P is AO =
1325arenas[(POOL)->arenaindex]. Suppose obmalloc controls P. Then (barring wild
1326stores, etc), POOL is the correct address of P's pool, AO.address is the
1327correct base address of the pool's arena, and P must be within ARENA_SIZE of
1328AO.address. In addition, AO.address is not 0 (no arena can start at address 0
Benjamin Peterson3924f932016-09-18 19:12:48 -07001329(NULL)). Therefore address_in_range correctly reports that obmalloc
Thomas Woutersa9773292006-04-21 09:43:23 +00001330controls P.
1331
1332Now suppose obmalloc does not control P (e.g., P was obtained via a direct
1333call to the system malloc() or realloc()). (POOL)->arenaindex may be anything
1334in this case -- it may even be uninitialized trash. If the trash arenaindex
1335is >= maxarenas, the macro correctly concludes at once that obmalloc doesn't
1336control P.
1337
1338Else arenaindex is < maxarena, and AO is read up. If AO corresponds to an
1339allocated arena, obmalloc controls all the memory in slice AO.address :
1340AO.address+ARENA_SIZE. By case assumption, P is not controlled by obmalloc,
1341so P doesn't lie in that slice, so the macro correctly reports that P is not
1342controlled by obmalloc.
1343
1344Finally, if P is not controlled by obmalloc and AO corresponds to an unused
1345arena_object (one not currently associated with an allocated arena),
1346AO.address is 0, and the second test in the macro reduces to:
1347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001348 P < ARENA_SIZE
Thomas Woutersa9773292006-04-21 09:43:23 +00001349
1350If P >= ARENA_SIZE (extremely likely), the macro again correctly concludes
1351that P is not controlled by obmalloc. However, if P < ARENA_SIZE, this part
1352of the test still passes, and the third clause (AO.address != 0) is necessary
1353to get the correct result: AO.address is 0 in this case, so the macro
1354correctly reports that P is not controlled by obmalloc (despite that P lies in
1355slice AO.address : AO.address + ARENA_SIZE).
1356
1357Note: The third (AO.address != 0) clause was added in Python 2.5. Before
13582.5, arenas were never free()'ed, and an arenaindex < maxarena always
1359corresponded to a currently-allocated arena, so the "P is not controlled by
1360obmalloc, AO corresponds to an unused arena_object, and P < ARENA_SIZE" case
1361was impossible.
1362
1363Note that the logic is excruciating, and reading up possibly uninitialized
1364memory when P is not controlled by obmalloc (to get at (POOL)->arenaindex)
1365creates problems for some memory debuggers. The overwhelming advantage is
1366that this test determines whether an arbitrary address is controlled by
1367obmalloc in a small constant time, independent of the number of arenas
1368obmalloc controls. Since this test is needed at every entry point, it's
1369extremely desirable that it be this fast.
1370*/
Thomas Woutersa9773292006-04-21 09:43:23 +00001371
Alexey Izbyshevfd3a91c2018-11-12 02:14:51 +03001372static bool _Py_NO_ADDRESS_SAFETY_ANALYSIS
1373 _Py_NO_SANITIZE_THREAD
1374 _Py_NO_SANITIZE_MEMORY
Benjamin Peterson3924f932016-09-18 19:12:48 -07001375address_in_range(void *p, poolp pool)
1376{
1377 // Since address_in_range may be reading from memory which was not allocated
1378 // by Python, it is important that pool->arenaindex is read only once, as
1379 // another thread may be concurrently modifying the value without holding
1380 // the GIL. The following dance forces the compiler to read pool->arenaindex
1381 // only once.
1382 uint arenaindex = *((volatile uint *)&pool->arenaindex);
Victor Stinner9e87e772017-11-24 12:09:24 +01001383 return arenaindex < maxarenas &&
1384 (uintptr_t)p - arenas[arenaindex].address < ARENA_SIZE &&
1385 arenas[arenaindex].address != 0;
Benjamin Peterson3924f932016-09-18 19:12:48 -07001386}
Tim Peters338e0102002-04-01 19:23:44 +00001387
Victor Stinner9ed83c42017-10-31 12:18:10 -07001388
Neil Schemenauera35c6882001-02-27 04:45:05 +00001389/*==========================================================================*/
1390
Victor Stinner9ed83c42017-10-31 12:18:10 -07001391/* pymalloc allocator
Neil Schemenauera35c6882001-02-27 04:45:05 +00001392
Victor Stinner9ed83c42017-10-31 12:18:10 -07001393 The basic blocks are ordered by decreasing execution frequency,
1394 which minimizes the number of jumps in the most common cases,
1395 improves branching prediction and instruction scheduling (small
1396 block allocations typically result in a couple of instructions).
1397 Unless the optimizer reorders everything, being too smart...
Neil Schemenauera35c6882001-02-27 04:45:05 +00001398
Victor Stinner9ed83c42017-10-31 12:18:10 -07001399 Return 1 if pymalloc allocated memory and wrote the pointer into *ptr_p.
1400
1401 Return 0 if pymalloc failed to allocate the memory block: on bigger
1402 requests, on error in the code below (as a last chance to serve the request)
1403 or when the max memory limit has been reached. */
1404static int
1405pymalloc_alloc(void *ctx, void **ptr_p, size_t nbytes)
Neil Schemenauera35c6882001-02-27 04:45:05 +00001406{
Victor Stinner9e87e772017-11-24 12:09:24 +01001407 block *bp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001408 poolp pool;
1409 poolp next;
1410 uint size;
Neil Schemenauera35c6882001-02-27 04:45:05 +00001411
Benjamin Peterson05159c42009-12-03 03:01:27 +00001412#ifdef WITH_VALGRIND
Victor Stinner9ed83c42017-10-31 12:18:10 -07001413 if (UNLIKELY(running_on_valgrind == -1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001414 running_on_valgrind = RUNNING_ON_VALGRIND;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001415 }
1416 if (UNLIKELY(running_on_valgrind)) {
1417 return 0;
1418 }
Benjamin Peterson05159c42009-12-03 03:01:27 +00001419#endif
1420
Victor Stinner9ed83c42017-10-31 12:18:10 -07001421 if (nbytes == 0) {
1422 return 0;
1423 }
1424 if (nbytes > SMALL_REQUEST_THRESHOLD) {
1425 return 0;
1426 }
T. Wouters06bb4872017-03-31 10:10:19 -07001427
Victor Stinner9ed83c42017-10-31 12:18:10 -07001428 /*
1429 * Most frequent paths first
1430 */
1431 size = (uint)(nbytes - 1) >> ALIGNMENT_SHIFT;
Victor Stinner9e87e772017-11-24 12:09:24 +01001432 pool = usedpools[size + size];
Victor Stinner9ed83c42017-10-31 12:18:10 -07001433 if (pool != pool->nextpool) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001434 /*
Victor Stinner9ed83c42017-10-31 12:18:10 -07001435 * There is a used pool for this size class.
1436 * Pick up the head block of its free list.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001437 */
Victor Stinner9ed83c42017-10-31 12:18:10 -07001438 ++pool->ref.count;
1439 bp = pool->freeblock;
1440 assert(bp != NULL);
Victor Stinner9e87e772017-11-24 12:09:24 +01001441 if ((pool->freeblock = *(block **)bp) != NULL) {
Victor Stinner9ed83c42017-10-31 12:18:10 -07001442 goto success;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001443 }
Thomas Woutersa9773292006-04-21 09:43:23 +00001444
Victor Stinner9ed83c42017-10-31 12:18:10 -07001445 /*
1446 * Reached the end of the free list, try to extend it.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001447 */
Victor Stinner9ed83c42017-10-31 12:18:10 -07001448 if (pool->nextoffset <= pool->maxnextoffset) {
1449 /* There is room for another block. */
Victor Stinner9e87e772017-11-24 12:09:24 +01001450 pool->freeblock = (block*)pool +
Victor Stinner9ed83c42017-10-31 12:18:10 -07001451 pool->nextoffset;
1452 pool->nextoffset += INDEX2SIZE(size);
Victor Stinner9e87e772017-11-24 12:09:24 +01001453 *(block **)(pool->freeblock) = NULL;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001454 goto success;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001455 }
Thomas Woutersa9773292006-04-21 09:43:23 +00001456
Victor Stinner9ed83c42017-10-31 12:18:10 -07001457 /* Pool is full, unlink from used pools. */
1458 next = pool->nextpool;
1459 pool = pool->prevpool;
1460 next->prevpool = pool;
1461 pool->nextpool = next;
1462 goto success;
1463 }
Thomas Woutersa9773292006-04-21 09:43:23 +00001464
Victor Stinner9ed83c42017-10-31 12:18:10 -07001465 /* There isn't a pool of the right size class immediately
1466 * available: use a free pool.
1467 */
Victor Stinner9e87e772017-11-24 12:09:24 +01001468 if (usable_arenas == NULL) {
Victor Stinner9ed83c42017-10-31 12:18:10 -07001469 /* No arena has a free pool: allocate a new arena. */
1470#ifdef WITH_MEMORY_LIMITS
Victor Stinner9e87e772017-11-24 12:09:24 +01001471 if (narenas_currently_allocated >= MAX_ARENAS) {
Victor Stinner9ed83c42017-10-31 12:18:10 -07001472 goto failed;
1473 }
1474#endif
Victor Stinner9e87e772017-11-24 12:09:24 +01001475 usable_arenas = new_arena();
1476 if (usable_arenas == NULL) {
Victor Stinner9ed83c42017-10-31 12:18:10 -07001477 goto failed;
1478 }
Victor Stinner9e87e772017-11-24 12:09:24 +01001479 usable_arenas->nextarena =
1480 usable_arenas->prevarena = NULL;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001481 }
Victor Stinner9e87e772017-11-24 12:09:24 +01001482 assert(usable_arenas->address != 0);
Victor Stinner9ed83c42017-10-31 12:18:10 -07001483
1484 /* Try to get a cached free pool. */
Victor Stinner9e87e772017-11-24 12:09:24 +01001485 pool = usable_arenas->freepools;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001486 if (pool != NULL) {
1487 /* Unlink from cached pools. */
Victor Stinner9e87e772017-11-24 12:09:24 +01001488 usable_arenas->freepools = pool->nextpool;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001489
1490 /* This arena already had the smallest nfreepools
1491 * value, so decreasing nfreepools doesn't change
1492 * that, and we don't need to rearrange the
1493 * usable_arenas list. However, if the arena has
1494 * become wholly allocated, we need to remove its
1495 * arena_object from usable_arenas.
1496 */
Victor Stinner9e87e772017-11-24 12:09:24 +01001497 --usable_arenas->nfreepools;
1498 if (usable_arenas->nfreepools == 0) {
Victor Stinner9ed83c42017-10-31 12:18:10 -07001499 /* Wholly allocated: remove. */
Victor Stinner9e87e772017-11-24 12:09:24 +01001500 assert(usable_arenas->freepools == NULL);
1501 assert(usable_arenas->nextarena == NULL ||
1502 usable_arenas->nextarena->prevarena ==
1503 usable_arenas);
Victor Stinner9ed83c42017-10-31 12:18:10 -07001504
Victor Stinner9e87e772017-11-24 12:09:24 +01001505 usable_arenas = usable_arenas->nextarena;
1506 if (usable_arenas != NULL) {
1507 usable_arenas->prevarena = NULL;
1508 assert(usable_arenas->address != 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001509 }
1510 }
Victor Stinner9ed83c42017-10-31 12:18:10 -07001511 else {
1512 /* nfreepools > 0: it must be that freepools
1513 * isn't NULL, or that we haven't yet carved
1514 * off all the arena's pools for the first
1515 * time.
1516 */
Victor Stinner9e87e772017-11-24 12:09:24 +01001517 assert(usable_arenas->freepools != NULL ||
1518 usable_arenas->pool_address <=
1519 (block*)usable_arenas->address +
Victor Stinner9ed83c42017-10-31 12:18:10 -07001520 ARENA_SIZE - POOL_SIZE);
1521 }
Thomas Woutersa9773292006-04-21 09:43:23 +00001522
Victor Stinner9ed83c42017-10-31 12:18:10 -07001523 init_pool:
1524 /* Frontlink to used pools. */
Victor Stinner9e87e772017-11-24 12:09:24 +01001525 next = usedpools[size + size]; /* == prev */
Victor Stinner9ed83c42017-10-31 12:18:10 -07001526 pool->nextpool = next;
1527 pool->prevpool = next;
1528 next->nextpool = pool;
1529 next->prevpool = pool;
1530 pool->ref.count = 1;
1531 if (pool->szidx == size) {
1532 /* Luckily, this pool last contained blocks
1533 * of the same size class, so its header
1534 * and free list are already initialized.
1535 */
1536 bp = pool->freeblock;
1537 assert(bp != NULL);
Victor Stinner9e87e772017-11-24 12:09:24 +01001538 pool->freeblock = *(block **)bp;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001539 goto success;
1540 }
1541 /*
1542 * Initialize the pool header, set up the free list to
1543 * contain just the second block, and return the first
1544 * block.
1545 */
1546 pool->szidx = size;
1547 size = INDEX2SIZE(size);
Victor Stinner9e87e772017-11-24 12:09:24 +01001548 bp = (block *)pool + POOL_OVERHEAD;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001549 pool->nextoffset = POOL_OVERHEAD + (size << 1);
1550 pool->maxnextoffset = POOL_SIZE - size;
1551 pool->freeblock = bp + size;
Victor Stinner9e87e772017-11-24 12:09:24 +01001552 *(block **)(pool->freeblock) = NULL;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001553 goto success;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001554 }
Neil Schemenauera35c6882001-02-27 04:45:05 +00001555
Victor Stinner9ed83c42017-10-31 12:18:10 -07001556 /* Carve off a new pool. */
Victor Stinner9e87e772017-11-24 12:09:24 +01001557 assert(usable_arenas->nfreepools > 0);
1558 assert(usable_arenas->freepools == NULL);
1559 pool = (poolp)usable_arenas->pool_address;
1560 assert((block*)pool <= (block*)usable_arenas->address +
Victor Stinner9ed83c42017-10-31 12:18:10 -07001561 ARENA_SIZE - POOL_SIZE);
Victor Stinner9e87e772017-11-24 12:09:24 +01001562 pool->arenaindex = (uint)(usable_arenas - arenas);
1563 assert(&arenas[pool->arenaindex] == usable_arenas);
Victor Stinner9ed83c42017-10-31 12:18:10 -07001564 pool->szidx = DUMMY_SIZE_IDX;
Victor Stinner9e87e772017-11-24 12:09:24 +01001565 usable_arenas->pool_address += POOL_SIZE;
1566 --usable_arenas->nfreepools;
Neil Schemenauera35c6882001-02-27 04:45:05 +00001567
Victor Stinner9e87e772017-11-24 12:09:24 +01001568 if (usable_arenas->nfreepools == 0) {
1569 assert(usable_arenas->nextarena == NULL ||
1570 usable_arenas->nextarena->prevarena ==
1571 usable_arenas);
Victor Stinner9ed83c42017-10-31 12:18:10 -07001572 /* Unlink the arena: it is completely allocated. */
Victor Stinner9e87e772017-11-24 12:09:24 +01001573 usable_arenas = usable_arenas->nextarena;
1574 if (usable_arenas != NULL) {
1575 usable_arenas->prevarena = NULL;
1576 assert(usable_arenas->address != 0);
Victor Stinner9ed83c42017-10-31 12:18:10 -07001577 }
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001578 }
Victor Stinner9ed83c42017-10-31 12:18:10 -07001579
1580 goto init_pool;
1581
1582success:
Victor Stinner9ed83c42017-10-31 12:18:10 -07001583 assert(bp != NULL);
1584 *ptr_p = (void *)bp;
1585 return 1;
1586
1587failed:
Victor Stinner9ed83c42017-10-31 12:18:10 -07001588 return 0;
Neil Schemenauera35c6882001-02-27 04:45:05 +00001589}
1590
Victor Stinner9ed83c42017-10-31 12:18:10 -07001591
Victor Stinnerdb067af2014-05-02 22:31:14 +02001592static void *
1593_PyObject_Malloc(void *ctx, size_t nbytes)
1594{
Victor Stinner9ed83c42017-10-31 12:18:10 -07001595 void* ptr;
1596 if (pymalloc_alloc(ctx, &ptr, nbytes)) {
Victor Stinner9e87e772017-11-24 12:09:24 +01001597 _Py_AllocatedBlocks++;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001598 return ptr;
1599 }
1600
1601 ptr = PyMem_RawMalloc(nbytes);
1602 if (ptr != NULL) {
Victor Stinner9e87e772017-11-24 12:09:24 +01001603 _Py_AllocatedBlocks++;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001604 }
1605 return ptr;
Victor Stinnerdb067af2014-05-02 22:31:14 +02001606}
1607
Victor Stinner9ed83c42017-10-31 12:18:10 -07001608
Victor Stinnerdb067af2014-05-02 22:31:14 +02001609static void *
1610_PyObject_Calloc(void *ctx, size_t nelem, size_t elsize)
1611{
Victor Stinner9ed83c42017-10-31 12:18:10 -07001612 void* ptr;
1613
1614 assert(elsize == 0 || nelem <= (size_t)PY_SSIZE_T_MAX / elsize);
1615 size_t nbytes = nelem * elsize;
1616
1617 if (pymalloc_alloc(ctx, &ptr, nbytes)) {
1618 memset(ptr, 0, nbytes);
Victor Stinner9e87e772017-11-24 12:09:24 +01001619 _Py_AllocatedBlocks++;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001620 return ptr;
1621 }
1622
1623 ptr = PyMem_RawCalloc(nelem, elsize);
1624 if (ptr != NULL) {
Victor Stinner9e87e772017-11-24 12:09:24 +01001625 _Py_AllocatedBlocks++;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001626 }
1627 return ptr;
Victor Stinnerdb067af2014-05-02 22:31:14 +02001628}
1629
Neil Schemenauera35c6882001-02-27 04:45:05 +00001630
Victor Stinner9ed83c42017-10-31 12:18:10 -07001631/* Free a memory block allocated by pymalloc_alloc().
1632 Return 1 if it was freed.
1633 Return 0 if the block was not allocated by pymalloc_alloc(). */
1634static int
1635pymalloc_free(void *ctx, void *p)
Neil Schemenauera35c6882001-02-27 04:45:05 +00001636{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001637 poolp pool;
Victor Stinner9e87e772017-11-24 12:09:24 +01001638 block *lastfree;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001639 poolp next, prev;
1640 uint size;
Neil Schemenauera35c6882001-02-27 04:45:05 +00001641
Victor Stinner9ed83c42017-10-31 12:18:10 -07001642 assert(p != NULL);
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001643
Benjamin Peterson05159c42009-12-03 03:01:27 +00001644#ifdef WITH_VALGRIND
Victor Stinner9ed83c42017-10-31 12:18:10 -07001645 if (UNLIKELY(running_on_valgrind > 0)) {
1646 return 0;
1647 }
Benjamin Peterson05159c42009-12-03 03:01:27 +00001648#endif
1649
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001650 pool = POOL_ADDR(p);
Victor Stinner9ed83c42017-10-31 12:18:10 -07001651 if (!address_in_range(p, pool)) {
1652 return 0;
1653 }
1654 /* We allocated this address. */
Thomas Woutersa9773292006-04-21 09:43:23 +00001655
Victor Stinner9ed83c42017-10-31 12:18:10 -07001656 /* Link p to the start of the pool's freeblock list. Since
1657 * the pool had at least the p block outstanding, the pool
1658 * wasn't empty (so it's already in a usedpools[] list, or
1659 * was full and is in no list -- it's not in the freeblocks
1660 * list in any case).
1661 */
1662 assert(pool->ref.count > 0); /* else it was empty */
Victor Stinner9e87e772017-11-24 12:09:24 +01001663 *(block **)p = lastfree = pool->freeblock;
1664 pool->freeblock = (block *)p;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001665 if (!lastfree) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001666 /* Pool was full, so doesn't currently live in any list:
1667 * link it to the front of the appropriate usedpools[] list.
1668 * This mimics LRU pool usage for new allocations and
1669 * targets optimal filling when several pools contain
1670 * blocks of the same size class.
1671 */
1672 --pool->ref.count;
1673 assert(pool->ref.count > 0); /* else the pool is empty */
1674 size = pool->szidx;
Victor Stinner9e87e772017-11-24 12:09:24 +01001675 next = usedpools[size + size];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001676 prev = next->prevpool;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001678 /* insert pool before next: prev <-> pool <-> next */
1679 pool->nextpool = next;
1680 pool->prevpool = prev;
1681 next->prevpool = pool;
1682 prev->nextpool = pool;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001683 goto success;
1684 }
1685
1686 struct arena_object* ao;
1687 uint nf; /* ao->nfreepools */
1688
1689 /* freeblock wasn't NULL, so the pool wasn't full,
1690 * and the pool is in a usedpools[] list.
1691 */
1692 if (--pool->ref.count != 0) {
1693 /* pool isn't empty: leave it in usedpools */
1694 goto success;
1695 }
1696 /* Pool is now empty: unlink from usedpools, and
1697 * link to the front of freepools. This ensures that
1698 * previously freed pools will be allocated later
1699 * (being not referenced, they are perhaps paged out).
1700 */
1701 next = pool->nextpool;
1702 prev = pool->prevpool;
1703 next->prevpool = prev;
1704 prev->nextpool = next;
1705
1706 /* Link the pool to freepools. This is a singly-linked
1707 * list, and pool->prevpool isn't used there.
1708 */
Victor Stinner9e87e772017-11-24 12:09:24 +01001709 ao = &arenas[pool->arenaindex];
Victor Stinner9ed83c42017-10-31 12:18:10 -07001710 pool->nextpool = ao->freepools;
1711 ao->freepools = pool;
1712 nf = ++ao->nfreepools;
1713
1714 /* All the rest is arena management. We just freed
1715 * a pool, and there are 4 cases for arena mgmt:
1716 * 1. If all the pools are free, return the arena to
1717 * the system free().
1718 * 2. If this is the only free pool in the arena,
1719 * add the arena back to the `usable_arenas` list.
1720 * 3. If the "next" arena has a smaller count of free
1721 * pools, we have to "slide this arena right" to
1722 * restore that usable_arenas is sorted in order of
1723 * nfreepools.
1724 * 4. Else there's nothing more to do.
1725 */
1726 if (nf == ao->ntotalpools) {
1727 /* Case 1. First unlink ao from usable_arenas.
1728 */
1729 assert(ao->prevarena == NULL ||
1730 ao->prevarena->address != 0);
1731 assert(ao ->nextarena == NULL ||
1732 ao->nextarena->address != 0);
1733
1734 /* Fix the pointer in the prevarena, or the
1735 * usable_arenas pointer.
1736 */
1737 if (ao->prevarena == NULL) {
Victor Stinner9e87e772017-11-24 12:09:24 +01001738 usable_arenas = ao->nextarena;
1739 assert(usable_arenas == NULL ||
1740 usable_arenas->address != 0);
Victor Stinner9ed83c42017-10-31 12:18:10 -07001741 }
1742 else {
1743 assert(ao->prevarena->nextarena == ao);
1744 ao->prevarena->nextarena =
1745 ao->nextarena;
1746 }
1747 /* Fix the pointer in the nextarena. */
1748 if (ao->nextarena != NULL) {
1749 assert(ao->nextarena->prevarena == ao);
1750 ao->nextarena->prevarena =
1751 ao->prevarena;
1752 }
1753 /* Record that this arena_object slot is
1754 * available to be reused.
1755 */
Victor Stinner9e87e772017-11-24 12:09:24 +01001756 ao->nextarena = unused_arena_objects;
1757 unused_arena_objects = ao;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001758
1759 /* Free the entire arena. */
Victor Stinner9e87e772017-11-24 12:09:24 +01001760 _PyObject_Arena.free(_PyObject_Arena.ctx,
Victor Stinner9ed83c42017-10-31 12:18:10 -07001761 (void *)ao->address, ARENA_SIZE);
1762 ao->address = 0; /* mark unassociated */
Victor Stinner9e87e772017-11-24 12:09:24 +01001763 --narenas_currently_allocated;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001764
1765 goto success;
1766 }
1767
1768 if (nf == 1) {
1769 /* Case 2. Put ao at the head of
1770 * usable_arenas. Note that because
1771 * ao->nfreepools was 0 before, ao isn't
1772 * currently on the usable_arenas list.
1773 */
Victor Stinner9e87e772017-11-24 12:09:24 +01001774 ao->nextarena = usable_arenas;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001775 ao->prevarena = NULL;
Victor Stinner9e87e772017-11-24 12:09:24 +01001776 if (usable_arenas)
1777 usable_arenas->prevarena = ao;
1778 usable_arenas = ao;
1779 assert(usable_arenas->address != 0);
Victor Stinner9ed83c42017-10-31 12:18:10 -07001780
1781 goto success;
1782 }
1783
1784 /* If this arena is now out of order, we need to keep
1785 * the list sorted. The list is kept sorted so that
1786 * the "most full" arenas are used first, which allows
1787 * the nearly empty arenas to be completely freed. In
1788 * a few un-scientific tests, it seems like this
1789 * approach allowed a lot more memory to be freed.
1790 */
1791 if (ao->nextarena == NULL ||
1792 nf <= ao->nextarena->nfreepools) {
1793 /* Case 4. Nothing to do. */
1794 goto success;
1795 }
1796 /* Case 3: We have to move the arena towards the end
1797 * of the list, because it has more free pools than
1798 * the arena to its right.
1799 * First unlink ao from usable_arenas.
1800 */
1801 if (ao->prevarena != NULL) {
1802 /* ao isn't at the head of the list */
1803 assert(ao->prevarena->nextarena == ao);
1804 ao->prevarena->nextarena = ao->nextarena;
1805 }
1806 else {
1807 /* ao is at the head of the list */
Victor Stinner9e87e772017-11-24 12:09:24 +01001808 assert(usable_arenas == ao);
1809 usable_arenas = ao->nextarena;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001810 }
1811 ao->nextarena->prevarena = ao->prevarena;
1812
1813 /* Locate the new insertion point by iterating over
1814 * the list, using our nextarena pointer.
1815 */
1816 while (ao->nextarena != NULL && nf > ao->nextarena->nfreepools) {
1817 ao->prevarena = ao->nextarena;
1818 ao->nextarena = ao->nextarena->nextarena;
1819 }
1820
1821 /* Insert ao at this point. */
1822 assert(ao->nextarena == NULL || ao->prevarena == ao->nextarena->prevarena);
1823 assert(ao->prevarena->nextarena == ao->nextarena);
1824
1825 ao->prevarena->nextarena = ao;
1826 if (ao->nextarena != NULL) {
1827 ao->nextarena->prevarena = ao;
1828 }
1829
1830 /* Verify that the swaps worked. */
1831 assert(ao->nextarena == NULL || nf <= ao->nextarena->nfreepools);
1832 assert(ao->prevarena == NULL || nf > ao->prevarena->nfreepools);
1833 assert(ao->nextarena == NULL || ao->nextarena->prevarena == ao);
Victor Stinner9e87e772017-11-24 12:09:24 +01001834 assert((usable_arenas == ao && ao->prevarena == NULL)
Victor Stinner9ed83c42017-10-31 12:18:10 -07001835 || ao->prevarena->nextarena == ao);
1836
1837 goto success;
1838
1839success:
Victor Stinner9ed83c42017-10-31 12:18:10 -07001840 return 1;
1841}
1842
1843
1844static void
1845_PyObject_Free(void *ctx, void *p)
1846{
1847 /* PyObject_Free(NULL) has no effect */
1848 if (p == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001849 return;
1850 }
Neil Schemenauera35c6882001-02-27 04:45:05 +00001851
Victor Stinner9e87e772017-11-24 12:09:24 +01001852 _Py_AllocatedBlocks--;
Victor Stinner9ed83c42017-10-31 12:18:10 -07001853 if (!pymalloc_free(ctx, p)) {
1854 /* pymalloc didn't allocate this address */
1855 PyMem_RawFree(p);
1856 }
Neil Schemenauera35c6882001-02-27 04:45:05 +00001857}
1858
Neil Schemenauera35c6882001-02-27 04:45:05 +00001859
Victor Stinner9ed83c42017-10-31 12:18:10 -07001860/* pymalloc realloc.
1861
1862 If nbytes==0, then as the Python docs promise, we do not treat this like
1863 free(p), and return a non-NULL result.
1864
1865 Return 1 if pymalloc reallocated memory and wrote the new pointer into
1866 newptr_p.
1867
1868 Return 0 if pymalloc didn't allocated p. */
1869static int
1870pymalloc_realloc(void *ctx, void **newptr_p, void *p, size_t nbytes)
Neil Schemenauera35c6882001-02-27 04:45:05 +00001871{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001872 void *bp;
1873 poolp pool;
1874 size_t size;
Neil Schemenauera35c6882001-02-27 04:45:05 +00001875
Victor Stinner9ed83c42017-10-31 12:18:10 -07001876 assert(p != NULL);
Georg Brandld492ad82008-07-23 16:13:07 +00001877
Benjamin Peterson05159c42009-12-03 03:01:27 +00001878#ifdef WITH_VALGRIND
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001879 /* Treat running_on_valgrind == -1 the same as 0 */
Victor Stinner9ed83c42017-10-31 12:18:10 -07001880 if (UNLIKELY(running_on_valgrind > 0)) {
1881 return 0;
1882 }
Benjamin Peterson05159c42009-12-03 03:01:27 +00001883#endif
1884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001885 pool = POOL_ADDR(p);
Victor Stinner9ed83c42017-10-31 12:18:10 -07001886 if (!address_in_range(p, pool)) {
1887 /* pymalloc is not managing this block.
1888
1889 If nbytes <= SMALL_REQUEST_THRESHOLD, it's tempting to try to take
1890 over this block. However, if we do, we need to copy the valid data
1891 from the C-managed block to one of our blocks, and there's no
1892 portable way to know how much of the memory space starting at p is
1893 valid.
1894
1895 As bug 1185883 pointed out the hard way, it's possible that the
1896 C-managed block is "at the end" of allocated VM space, so that a
1897 memory fault can occur if we try to copy nbytes bytes starting at p.
1898 Instead we punt: let C continue to manage this block. */
1899 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001900 }
Victor Stinner9ed83c42017-10-31 12:18:10 -07001901
1902 /* pymalloc is in charge of this block */
1903 size = INDEX2SIZE(pool->szidx);
1904 if (nbytes <= size) {
1905 /* The block is staying the same or shrinking.
1906
1907 If it's shrinking, there's a tradeoff: it costs cycles to copy the
1908 block to a smaller size class, but it wastes memory not to copy it.
1909
1910 The compromise here is to copy on shrink only if at least 25% of
1911 size can be shaved off. */
1912 if (4 * nbytes > 3 * size) {
1913 /* It's the same, or shrinking and new/old > 3/4. */
1914 *newptr_p = p;
1915 return 1;
1916 }
1917 size = nbytes;
1918 }
1919
1920 bp = _PyObject_Malloc(ctx, nbytes);
1921 if (bp != NULL) {
1922 memcpy(bp, p, size);
1923 _PyObject_Free(ctx, p);
1924 }
1925 *newptr_p = bp;
1926 return 1;
1927}
1928
1929
1930static void *
1931_PyObject_Realloc(void *ctx, void *ptr, size_t nbytes)
1932{
1933 void *ptr2;
1934
1935 if (ptr == NULL) {
1936 return _PyObject_Malloc(ctx, nbytes);
1937 }
1938
1939 if (pymalloc_realloc(ctx, &ptr2, ptr, nbytes)) {
1940 return ptr2;
1941 }
1942
1943 return PyMem_RawRealloc(ptr, nbytes);
Neil Schemenauera35c6882001-02-27 04:45:05 +00001944}
1945
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001946#else /* ! WITH_PYMALLOC */
Tim Petersddea2082002-03-23 10:03:50 +00001947
1948/*==========================================================================*/
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00001949/* pymalloc not enabled: Redirect the entry points to malloc. These will
1950 * only be used by extensions that are compiled with pymalloc enabled. */
Tim Peters62c06ba2002-03-23 22:28:18 +00001951
Antoine Pitrou92840532012-12-17 23:05:59 +01001952Py_ssize_t
1953_Py_GetAllocatedBlocks(void)
1954{
1955 return 0;
1956}
1957
Tim Peters1221c0a2002-03-23 00:20:15 +00001958#endif /* WITH_PYMALLOC */
1959
Victor Stinner34be807c2016-03-14 12:04:26 +01001960
Tim Petersddea2082002-03-23 10:03:50 +00001961/*==========================================================================*/
Tim Peters62c06ba2002-03-23 22:28:18 +00001962/* A x-platform debugging allocator. This doesn't manage memory directly,
1963 * it wraps a real allocator, adding extra debugging info to the memory blocks.
1964 */
Tim Petersddea2082002-03-23 10:03:50 +00001965
Tim Petersf6fb5012002-04-12 07:38:53 +00001966/* Special bytes broadcast into debug memory blocks at appropriate times.
1967 * Strings of these are unlikely to be valid addresses, floats, ints or
Victor Stinner2b00db62019-04-11 11:33:27 +02001968 * 7-bit ASCII. If modified, _PyMem_IsPtrFreed() should be updated as well.
Victor Stinner4c409be2019-04-11 13:01:15 +02001969 *
1970 * Byte patterns 0xCB, 0xBB and 0xFB have been replaced with 0xCD, 0xDD and
1971 * 0xFD to use the same values than Windows CRT debug malloc() and free().
Tim Petersf6fb5012002-04-12 07:38:53 +00001972 */
1973#undef CLEANBYTE
1974#undef DEADBYTE
1975#undef FORBIDDENBYTE
Victor Stinner4c409be2019-04-11 13:01:15 +02001976#define CLEANBYTE 0xCD /* clean (newly allocated) memory */
1977#define DEADBYTE 0xDD /* dead (newly freed) memory */
1978#define FORBIDDENBYTE 0xFD /* untouchable bytes at each end of a block */
Tim Petersddea2082002-03-23 10:03:50 +00001979
Victor Stinnere8f9acf2019-04-12 21:54:06 +02001980/* Uncomment this define to add the "serialno" field */
1981/* #define PYMEM_DEBUG_SERIALNO */
1982
1983#ifdef PYMEM_DEBUG_SERIALNO
Victor Stinner9e87e772017-11-24 12:09:24 +01001984static size_t serialno = 0; /* incremented on each debug {m,re}alloc */
1985
Tim Peterse0850172002-03-24 00:34:21 +00001986/* serialno is always incremented via calling this routine. The point is
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001987 * to supply a single place to set a breakpoint.
1988 */
Tim Peterse0850172002-03-24 00:34:21 +00001989static void
Neil Schemenauerbd02b142002-03-28 21:05:38 +00001990bumpserialno(void)
Tim Peterse0850172002-03-24 00:34:21 +00001991{
Victor Stinner9e87e772017-11-24 12:09:24 +01001992 ++serialno;
Tim Peterse0850172002-03-24 00:34:21 +00001993}
Victor Stinnere8f9acf2019-04-12 21:54:06 +02001994#endif
Tim Peterse0850172002-03-24 00:34:21 +00001995
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001996#define SST SIZEOF_SIZE_T
Tim Peterse0850172002-03-24 00:34:21 +00001997
Victor Stinnere8f9acf2019-04-12 21:54:06 +02001998#ifdef PYMEM_DEBUG_SERIALNO
1999# define PYMEM_DEBUG_EXTRA_BYTES 4 * SST
2000#else
2001# define PYMEM_DEBUG_EXTRA_BYTES 3 * SST
2002#endif
2003
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00002004/* Read sizeof(size_t) bytes at p as a big-endian size_t. */
2005static size_t
2006read_size_t(const void *p)
Tim Petersddea2082002-03-23 10:03:50 +00002007{
Benjamin Peterson19517e42016-09-18 19:22:22 -07002008 const uint8_t *q = (const uint8_t *)p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002009 size_t result = *q++;
2010 int i;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00002011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002012 for (i = SST; --i > 0; ++q)
2013 result = (result << 8) | *q;
2014 return result;
Tim Petersddea2082002-03-23 10:03:50 +00002015}
2016
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00002017/* Write n as a big-endian size_t, MSB at address p, LSB at
2018 * p + sizeof(size_t) - 1.
2019 */
Tim Petersddea2082002-03-23 10:03:50 +00002020static void
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00002021write_size_t(void *p, size_t n)
Tim Petersddea2082002-03-23 10:03:50 +00002022{
Benjamin Peterson19517e42016-09-18 19:22:22 -07002023 uint8_t *q = (uint8_t *)p + SST - 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002024 int i;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00002025
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002026 for (i = SST; --i >= 0; --q) {
Benjamin Peterson19517e42016-09-18 19:22:22 -07002027 *q = (uint8_t)(n & 0xff);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002028 n >>= 8;
2029 }
Tim Petersddea2082002-03-23 10:03:50 +00002030}
2031
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002032/* Let S = sizeof(size_t). The debug malloc asks for 4 * S extra bytes and
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00002033 fills them with useful stuff, here calling the underlying malloc's result p:
Tim Petersddea2082002-03-23 10:03:50 +00002034
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00002035p[0: S]
2036 Number of bytes originally asked for. This is a size_t, big-endian (easier
2037 to read in a memory dump).
Georg Brandl7cba5fd2013-09-25 09:04:23 +02002038p[S]
Tim Petersdf099f52013-09-19 21:06:37 -05002039 API ID. See PEP 445. This is a character, but seems undocumented.
2040p[S+1: 2*S]
Tim Petersf6fb5012002-04-12 07:38:53 +00002041 Copies of FORBIDDENBYTE. Used to catch under- writes and reads.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00002042p[2*S: 2*S+n]
Tim Petersf6fb5012002-04-12 07:38:53 +00002043 The requested memory, filled with copies of CLEANBYTE.
Tim Petersddea2082002-03-23 10:03:50 +00002044 Used to catch reference to uninitialized memory.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00002045 &p[2*S] is returned. Note that this is 8-byte aligned if pymalloc
Tim Petersddea2082002-03-23 10:03:50 +00002046 handled the request itself.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00002047p[2*S+n: 2*S+n+S]
Tim Petersf6fb5012002-04-12 07:38:53 +00002048 Copies of FORBIDDENBYTE. Used to catch over- writes and reads.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00002049p[2*S+n+S: 2*S+n+2*S]
Victor Stinner0507bf52013-07-07 02:05:46 +02002050 A serial number, incremented by 1 on each call to _PyMem_DebugMalloc
2051 and _PyMem_DebugRealloc.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00002052 This is a big-endian size_t.
Tim Petersddea2082002-03-23 10:03:50 +00002053 If "bad memory" is detected later, the serial number gives an
2054 excellent way to set a breakpoint on the next run, to capture the
2055 instant at which this block was passed out.
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002056
2057If PYMEM_DEBUG_SERIALNO is not defined (default), the debug malloc only asks
2058for 3 * S extra bytes, and omits the last serialno field.
Tim Petersddea2082002-03-23 10:03:50 +00002059*/
2060
Victor Stinner0507bf52013-07-07 02:05:46 +02002061static void *
Victor Stinnerc4aec362016-03-14 22:26:53 +01002062_PyMem_DebugRawAlloc(int use_calloc, void *ctx, size_t nbytes)
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00002063{
Victor Stinner0507bf52013-07-07 02:05:46 +02002064 debug_alloc_api_t *api = (debug_alloc_api_t *)ctx;
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002065 uint8_t *p; /* base address of malloc'ed pad block */
Victor Stinner9ed83c42017-10-31 12:18:10 -07002066 uint8_t *data; /* p + 2*SST == pointer to data bytes */
2067 uint8_t *tail; /* data + nbytes == pointer to tail pad bytes */
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002068 size_t total; /* nbytes + PYMEM_DEBUG_EXTRA_BYTES */
Victor Stinner9ed83c42017-10-31 12:18:10 -07002069
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002070 if (nbytes > (size_t)PY_SSIZE_T_MAX - PYMEM_DEBUG_EXTRA_BYTES) {
Victor Stinner9ed83c42017-10-31 12:18:10 -07002071 /* integer overflow: can't represent total as a Py_ssize_t */
2072 return NULL;
2073 }
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002074 total = nbytes + PYMEM_DEBUG_EXTRA_BYTES;
Victor Stinner9ed83c42017-10-31 12:18:10 -07002075
2076 /* Layout: [SSSS IFFF CCCC...CCCC FFFF NNNN]
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002077 ^--- p ^--- data ^--- tail
Victor Stinner9ed83c42017-10-31 12:18:10 -07002078 S: nbytes stored as size_t
2079 I: API identifier (1 byte)
2080 F: Forbidden bytes (size_t - 1 bytes before, size_t bytes after)
2081 C: Clean bytes used later to store actual data
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002082 N: Serial number stored as size_t
2083
2084 If PYMEM_DEBUG_SERIALNO is not defined (default), the last NNNN field
2085 is omitted. */
Victor Stinner9ed83c42017-10-31 12:18:10 -07002086
2087 if (use_calloc) {
2088 p = (uint8_t *)api->alloc.calloc(api->alloc.ctx, 1, total);
2089 }
2090 else {
2091 p = (uint8_t *)api->alloc.malloc(api->alloc.ctx, total);
2092 }
2093 if (p == NULL) {
2094 return NULL;
2095 }
2096 data = p + 2*SST;
Tim Petersddea2082002-03-23 10:03:50 +00002097
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002098#ifdef PYMEM_DEBUG_SERIALNO
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002099 bumpserialno();
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002100#endif
Tim Petersddea2082002-03-23 10:03:50 +00002101
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002102 /* at p, write size (SST bytes), id (1 byte), pad (SST-1 bytes) */
2103 write_size_t(p, nbytes);
Benjamin Peterson19517e42016-09-18 19:22:22 -07002104 p[SST] = (uint8_t)api->api_id;
Victor Stinner0507bf52013-07-07 02:05:46 +02002105 memset(p + SST + 1, FORBIDDENBYTE, SST-1);
Tim Petersddea2082002-03-23 10:03:50 +00002106
Victor Stinner9ed83c42017-10-31 12:18:10 -07002107 if (nbytes > 0 && !use_calloc) {
2108 memset(data, CLEANBYTE, nbytes);
2109 }
Tim Petersddea2082002-03-23 10:03:50 +00002110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002111 /* at tail, write pad (SST bytes) and serialno (SST bytes) */
Victor Stinner9ed83c42017-10-31 12:18:10 -07002112 tail = data + nbytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002113 memset(tail, FORBIDDENBYTE, SST);
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002114#ifdef PYMEM_DEBUG_SERIALNO
Victor Stinner9e87e772017-11-24 12:09:24 +01002115 write_size_t(tail + SST, serialno);
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002116#endif
Tim Petersddea2082002-03-23 10:03:50 +00002117
Victor Stinner9ed83c42017-10-31 12:18:10 -07002118 return data;
Tim Petersddea2082002-03-23 10:03:50 +00002119}
2120
Victor Stinnerdb067af2014-05-02 22:31:14 +02002121static void *
Victor Stinnerc4aec362016-03-14 22:26:53 +01002122_PyMem_DebugRawMalloc(void *ctx, size_t nbytes)
Victor Stinnerdb067af2014-05-02 22:31:14 +02002123{
Victor Stinnerc4aec362016-03-14 22:26:53 +01002124 return _PyMem_DebugRawAlloc(0, ctx, nbytes);
Victor Stinnerdb067af2014-05-02 22:31:14 +02002125}
2126
2127static void *
Victor Stinnerc4aec362016-03-14 22:26:53 +01002128_PyMem_DebugRawCalloc(void *ctx, size_t nelem, size_t elsize)
Victor Stinnerdb067af2014-05-02 22:31:14 +02002129{
2130 size_t nbytes;
Victor Stinner9ed83c42017-10-31 12:18:10 -07002131 assert(elsize == 0 || nelem <= (size_t)PY_SSIZE_T_MAX / elsize);
Victor Stinnerdb067af2014-05-02 22:31:14 +02002132 nbytes = nelem * elsize;
Victor Stinnerc4aec362016-03-14 22:26:53 +01002133 return _PyMem_DebugRawAlloc(1, ctx, nbytes);
Victor Stinnerdb067af2014-05-02 22:31:14 +02002134}
2135
Victor Stinner9ed83c42017-10-31 12:18:10 -07002136
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00002137/* 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 +00002138 particular, that the FORBIDDENBYTEs with the api ID are still intact).
Tim Petersf6fb5012002-04-12 07:38:53 +00002139 Then fills the original bytes with DEADBYTE.
Tim Petersddea2082002-03-23 10:03:50 +00002140 Then calls the underlying free.
2141*/
Victor Stinner0507bf52013-07-07 02:05:46 +02002142static void
Victor Stinnerc4aec362016-03-14 22:26:53 +01002143_PyMem_DebugRawFree(void *ctx, void *p)
Tim Petersddea2082002-03-23 10:03:50 +00002144{
Victor Stinner9ed83c42017-10-31 12:18:10 -07002145 /* PyMem_Free(NULL) has no effect */
2146 if (p == NULL) {
2147 return;
2148 }
2149
Victor Stinner0507bf52013-07-07 02:05:46 +02002150 debug_alloc_api_t *api = (debug_alloc_api_t *)ctx;
Benjamin Peterson19517e42016-09-18 19:22:22 -07002151 uint8_t *q = (uint8_t *)p - 2*SST; /* address returned from malloc */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002152 size_t nbytes;
Tim Petersddea2082002-03-23 10:03:50 +00002153
Victor Stinner0507bf52013-07-07 02:05:46 +02002154 _PyMem_DebugCheckAddress(api->api_id, p);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002155 nbytes = read_size_t(q);
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002156 nbytes += PYMEM_DEBUG_EXTRA_BYTES;
Victor Stinner9ed83c42017-10-31 12:18:10 -07002157 memset(q, DEADBYTE, nbytes);
Victor Stinner0507bf52013-07-07 02:05:46 +02002158 api->alloc.free(api->alloc.ctx, q);
Tim Petersddea2082002-03-23 10:03:50 +00002159}
2160
Victor Stinner9ed83c42017-10-31 12:18:10 -07002161
Victor Stinner0507bf52013-07-07 02:05:46 +02002162static void *
Victor Stinnerc4aec362016-03-14 22:26:53 +01002163_PyMem_DebugRawRealloc(void *ctx, void *p, size_t nbytes)
Tim Petersddea2082002-03-23 10:03:50 +00002164{
Victor Stinner9ed83c42017-10-31 12:18:10 -07002165 if (p == NULL) {
2166 return _PyMem_DebugRawAlloc(0, ctx, nbytes);
2167 }
2168
Victor Stinner0507bf52013-07-07 02:05:46 +02002169 debug_alloc_api_t *api = (debug_alloc_api_t *)ctx;
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002170 uint8_t *head; /* base address of malloc'ed pad block */
2171 uint8_t *data; /* pointer to data bytes */
2172 uint8_t *r;
Victor Stinner9ed83c42017-10-31 12:18:10 -07002173 uint8_t *tail; /* data + nbytes == pointer to tail pad bytes */
2174 size_t total; /* 2 * SST + nbytes + 2 * SST */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002175 size_t original_nbytes;
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002176#define ERASED_SIZE 64
2177 uint8_t save[2*ERASED_SIZE]; /* A copy of erased bytes. */
Tim Petersddea2082002-03-23 10:03:50 +00002178
Victor Stinner0507bf52013-07-07 02:05:46 +02002179 _PyMem_DebugCheckAddress(api->api_id, p);
Victor Stinner9ed83c42017-10-31 12:18:10 -07002180
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002181 data = (uint8_t *)p;
2182 head = data - 2*SST;
2183 original_nbytes = read_size_t(head);
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002184 if (nbytes > (size_t)PY_SSIZE_T_MAX - PYMEM_DEBUG_EXTRA_BYTES) {
Victor Stinner9ed83c42017-10-31 12:18:10 -07002185 /* integer overflow: can't represent total as a Py_ssize_t */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002186 return NULL;
Victor Stinner9ed83c42017-10-31 12:18:10 -07002187 }
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002188 total = nbytes + PYMEM_DEBUG_EXTRA_BYTES;
Tim Petersddea2082002-03-23 10:03:50 +00002189
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002190 tail = data + original_nbytes;
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002191#ifdef PYMEM_DEBUG_SERIALNO
2192 size_t block_serialno = read_size_t(tail + SST);
2193#endif
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002194 /* Mark the header, the trailer, ERASED_SIZE bytes at the begin and
2195 ERASED_SIZE bytes at the end as dead and save the copy of erased bytes.
2196 */
2197 if (original_nbytes <= sizeof(save)) {
2198 memcpy(save, data, original_nbytes);
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002199 memset(data - 2 * SST, DEADBYTE,
2200 original_nbytes + PYMEM_DEBUG_EXTRA_BYTES);
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002201 }
2202 else {
2203 memcpy(save, data, ERASED_SIZE);
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002204 memset(head, DEADBYTE, ERASED_SIZE + 2 * SST);
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002205 memcpy(&save[ERASED_SIZE], tail - ERASED_SIZE, ERASED_SIZE);
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002206 memset(tail - ERASED_SIZE, DEADBYTE,
2207 ERASED_SIZE + PYMEM_DEBUG_EXTRA_BYTES - 2 * SST);
Victor Stinner9ed83c42017-10-31 12:18:10 -07002208 }
Tim Peters85cc1c42002-04-12 08:52:50 +00002209
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002210 /* Resize and add decorations. */
2211 r = (uint8_t *)api->alloc.realloc(api->alloc.ctx, head, total);
2212 if (r == NULL) {
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002213 /* if realloc() failed: rewrite header and footer which have
2214 just been erased */
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002215 nbytes = original_nbytes;
Victor Stinner9ed83c42017-10-31 12:18:10 -07002216 }
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002217 else {
2218 head = r;
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002219#ifdef PYMEM_DEBUG_SERIALNO
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002220 bumpserialno();
Victor Stinner9e87e772017-11-24 12:09:24 +01002221 block_serialno = serialno;
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002222#endif
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002223 }
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002224 data = head + 2*SST;
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002225
2226 write_size_t(head, nbytes);
2227 head[SST] = (uint8_t)api->api_id;
2228 memset(head + SST + 1, FORBIDDENBYTE, SST-1);
Victor Stinnerc4266362013-07-09 00:44:43 +02002229
Victor Stinner9ed83c42017-10-31 12:18:10 -07002230 tail = data + nbytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002231 memset(tail, FORBIDDENBYTE, SST);
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002232#ifdef PYMEM_DEBUG_SERIALNO
Victor Stinner9e87e772017-11-24 12:09:24 +01002233 write_size_t(tail + SST, block_serialno);
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002234#endif
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002235
2236 /* Restore saved bytes. */
2237 if (original_nbytes <= sizeof(save)) {
2238 memcpy(data, save, Py_MIN(nbytes, original_nbytes));
2239 }
2240 else {
2241 size_t i = original_nbytes - ERASED_SIZE;
2242 memcpy(data, save, Py_MIN(nbytes, ERASED_SIZE));
2243 if (nbytes > i) {
2244 memcpy(data + i, &save[ERASED_SIZE],
2245 Py_MIN(nbytes - i, ERASED_SIZE));
2246 }
2247 }
2248
2249 if (r == NULL) {
2250 return NULL;
2251 }
Tim Peters85cc1c42002-04-12 08:52:50 +00002252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002253 if (nbytes > original_nbytes) {
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002254 /* growing: mark new extra memory clean */
Serhiy Storchaka3cc4c532017-11-07 12:46:42 +02002255 memset(data + original_nbytes, CLEANBYTE, nbytes - original_nbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002256 }
Tim Peters85cc1c42002-04-12 08:52:50 +00002257
Victor Stinner9ed83c42017-10-31 12:18:10 -07002258 return data;
Tim Petersddea2082002-03-23 10:03:50 +00002259}
2260
Victor Stinnerc4aec362016-03-14 22:26:53 +01002261static void
2262_PyMem_DebugCheckGIL(void)
2263{
Victor Stinnerc4aec362016-03-14 22:26:53 +01002264 if (!PyGILState_Check())
2265 Py_FatalError("Python memory allocator called "
2266 "without holding the GIL");
Victor Stinnerc4aec362016-03-14 22:26:53 +01002267}
2268
2269static void *
2270_PyMem_DebugMalloc(void *ctx, size_t nbytes)
2271{
2272 _PyMem_DebugCheckGIL();
2273 return _PyMem_DebugRawMalloc(ctx, nbytes);
2274}
2275
2276static void *
2277_PyMem_DebugCalloc(void *ctx, size_t nelem, size_t elsize)
2278{
2279 _PyMem_DebugCheckGIL();
2280 return _PyMem_DebugRawCalloc(ctx, nelem, elsize);
2281}
2282
Victor Stinner9ed83c42017-10-31 12:18:10 -07002283
Victor Stinnerc4aec362016-03-14 22:26:53 +01002284static void
2285_PyMem_DebugFree(void *ctx, void *ptr)
2286{
2287 _PyMem_DebugCheckGIL();
Victor Stinner0aed3a42016-03-23 11:30:43 +01002288 _PyMem_DebugRawFree(ctx, ptr);
Victor Stinnerc4aec362016-03-14 22:26:53 +01002289}
2290
Victor Stinner9ed83c42017-10-31 12:18:10 -07002291
Victor Stinnerc4aec362016-03-14 22:26:53 +01002292static void *
2293_PyMem_DebugRealloc(void *ctx, void *ptr, size_t nbytes)
2294{
2295 _PyMem_DebugCheckGIL();
2296 return _PyMem_DebugRawRealloc(ctx, ptr, nbytes);
2297}
2298
Tim Peters7ccfadf2002-04-01 06:04:21 +00002299/* Check the forbidden bytes on both ends of the memory allocated for p.
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00002300 * If anything is wrong, print info to stderr via _PyObject_DebugDumpAddress,
Tim Peters7ccfadf2002-04-01 06:04:21 +00002301 * and call Py_FatalError to kill the program.
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00002302 * The API id, is also checked.
Tim Peters7ccfadf2002-04-01 06:04:21 +00002303 */
Victor Stinner0507bf52013-07-07 02:05:46 +02002304static void
2305_PyMem_DebugCheckAddress(char api, const void *p)
Tim Petersddea2082002-03-23 10:03:50 +00002306{
Benjamin Peterson19517e42016-09-18 19:22:22 -07002307 const uint8_t *q = (const uint8_t *)p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002308 char msgbuf[64];
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02002309 const char *msg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002310 size_t nbytes;
Benjamin Peterson19517e42016-09-18 19:22:22 -07002311 const uint8_t *tail;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002312 int i;
2313 char id;
Tim Petersddea2082002-03-23 10:03:50 +00002314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002315 if (p == NULL) {
2316 msg = "didn't expect a NULL pointer";
2317 goto error;
2318 }
Tim Petersddea2082002-03-23 10:03:50 +00002319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002320 /* Check the API id */
2321 id = (char)q[-SST];
2322 if (id != api) {
2323 msg = msgbuf;
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02002324 snprintf(msgbuf, sizeof(msgbuf), "bad ID: Allocated using API '%c', verified using API '%c'", id, api);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002325 msgbuf[sizeof(msgbuf)-1] = 0;
2326 goto error;
2327 }
Kristján Valur Jónssonae4cfb12009-09-28 13:45:02 +00002328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002329 /* Check the stuff at the start of p first: if there's underwrite
2330 * corruption, the number-of-bytes field may be nuts, and checking
2331 * the tail could lead to a segfault then.
2332 */
2333 for (i = SST-1; i >= 1; --i) {
2334 if (*(q-i) != FORBIDDENBYTE) {
2335 msg = "bad leading pad byte";
2336 goto error;
2337 }
2338 }
Tim Petersddea2082002-03-23 10:03:50 +00002339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002340 nbytes = read_size_t(q - 2*SST);
2341 tail = q + nbytes;
2342 for (i = 0; i < SST; ++i) {
2343 if (tail[i] != FORBIDDENBYTE) {
2344 msg = "bad trailing pad byte";
2345 goto error;
2346 }
2347 }
Tim Petersddea2082002-03-23 10:03:50 +00002348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002349 return;
Tim Petersd1139e02002-03-28 07:32:11 +00002350
2351error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002352 _PyObject_DebugDumpAddress(p);
2353 Py_FatalError(msg);
Tim Petersddea2082002-03-23 10:03:50 +00002354}
2355
Tim Peters7ccfadf2002-04-01 06:04:21 +00002356/* Display info to stderr about the memory block at p. */
Victor Stinner0507bf52013-07-07 02:05:46 +02002357static void
Neil Schemenauerd2560cd2002-04-12 03:10:20 +00002358_PyObject_DebugDumpAddress(const void *p)
Tim Petersddea2082002-03-23 10:03:50 +00002359{
Benjamin Peterson19517e42016-09-18 19:22:22 -07002360 const uint8_t *q = (const uint8_t *)p;
2361 const uint8_t *tail;
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002362 size_t nbytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002363 int i;
2364 int ok;
2365 char id;
Tim Petersddea2082002-03-23 10:03:50 +00002366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002367 fprintf(stderr, "Debug memory block at address p=%p:", p);
2368 if (p == NULL) {
2369 fprintf(stderr, "\n");
2370 return;
2371 }
2372 id = (char)q[-SST];
2373 fprintf(stderr, " API '%c'\n", id);
Tim Petersddea2082002-03-23 10:03:50 +00002374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002375 nbytes = read_size_t(q - 2*SST);
2376 fprintf(stderr, " %" PY_FORMAT_SIZE_T "u bytes originally "
2377 "requested\n", nbytes);
Tim Petersddea2082002-03-23 10:03:50 +00002378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002379 /* In case this is nuts, check the leading pad bytes first. */
2380 fprintf(stderr, " The %d pad bytes at p-%d are ", SST-1, SST-1);
2381 ok = 1;
2382 for (i = 1; i <= SST-1; ++i) {
2383 if (*(q-i) != FORBIDDENBYTE) {
2384 ok = 0;
2385 break;
2386 }
2387 }
2388 if (ok)
2389 fputs("FORBIDDENBYTE, as expected.\n", stderr);
2390 else {
2391 fprintf(stderr, "not all FORBIDDENBYTE (0x%02x):\n",
2392 FORBIDDENBYTE);
2393 for (i = SST-1; i >= 1; --i) {
Benjamin Peterson19517e42016-09-18 19:22:22 -07002394 const uint8_t byte = *(q-i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002395 fprintf(stderr, " at p-%d: 0x%02x", i, byte);
2396 if (byte != FORBIDDENBYTE)
2397 fputs(" *** OUCH", stderr);
2398 fputc('\n', stderr);
2399 }
Tim Peters449b5a82002-04-28 06:14:45 +00002400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002401 fputs(" Because memory is corrupted at the start, the "
2402 "count of bytes requested\n"
2403 " may be bogus, and checking the trailing pad "
2404 "bytes may segfault.\n", stderr);
2405 }
Tim Petersddea2082002-03-23 10:03:50 +00002406
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002407 tail = q + nbytes;
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002408 fprintf(stderr, " The %d pad bytes at tail=%p are ", SST, (void *)tail);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002409 ok = 1;
2410 for (i = 0; i < SST; ++i) {
2411 if (tail[i] != FORBIDDENBYTE) {
2412 ok = 0;
2413 break;
2414 }
2415 }
2416 if (ok)
2417 fputs("FORBIDDENBYTE, as expected.\n", stderr);
2418 else {
2419 fprintf(stderr, "not all FORBIDDENBYTE (0x%02x):\n",
Stefan Krah735bb122010-11-26 10:54:09 +00002420 FORBIDDENBYTE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002421 for (i = 0; i < SST; ++i) {
Benjamin Peterson19517e42016-09-18 19:22:22 -07002422 const uint8_t byte = tail[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002423 fprintf(stderr, " at tail+%d: 0x%02x",
Stefan Krah735bb122010-11-26 10:54:09 +00002424 i, byte);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002425 if (byte != FORBIDDENBYTE)
2426 fputs(" *** OUCH", stderr);
2427 fputc('\n', stderr);
2428 }
2429 }
Tim Petersddea2082002-03-23 10:03:50 +00002430
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002431#ifdef PYMEM_DEBUG_SERIALNO
2432 size_t serial = read_size_t(tail + SST);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002433 fprintf(stderr, " The block was made by call #%" PY_FORMAT_SIZE_T
2434 "u to debug malloc/realloc.\n", serial);
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002435#endif
Tim Petersddea2082002-03-23 10:03:50 +00002436
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002437 if (nbytes > 0) {
2438 i = 0;
2439 fputs(" Data at p:", stderr);
2440 /* print up to 8 bytes at the start */
2441 while (q < tail && i < 8) {
2442 fprintf(stderr, " %02x", *q);
2443 ++i;
2444 ++q;
2445 }
2446 /* and up to 8 at the end */
2447 if (q < tail) {
2448 if (tail - q > 8) {
2449 fputs(" ...", stderr);
2450 q = tail - 8;
2451 }
2452 while (q < tail) {
2453 fprintf(stderr, " %02x", *q);
2454 ++q;
2455 }
2456 }
2457 fputc('\n', stderr);
2458 }
Victor Stinner0611c262016-03-15 22:22:13 +01002459 fputc('\n', stderr);
2460
2461 fflush(stderr);
2462 _PyMem_DumpTraceback(fileno(stderr), p);
Tim Petersddea2082002-03-23 10:03:50 +00002463}
2464
David Malcolm49526f42012-06-22 14:55:41 -04002465
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00002466static size_t
David Malcolm49526f42012-06-22 14:55:41 -04002467printone(FILE *out, const char* msg, size_t value)
Tim Peters16bcb6b2002-04-05 05:45:31 +00002468{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002469 int i, k;
2470 char buf[100];
2471 size_t origvalue = value;
Tim Peters16bcb6b2002-04-05 05:45:31 +00002472
David Malcolm49526f42012-06-22 14:55:41 -04002473 fputs(msg, out);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002474 for (i = (int)strlen(msg); i < 35; ++i)
David Malcolm49526f42012-06-22 14:55:41 -04002475 fputc(' ', out);
2476 fputc('=', out);
Tim Peters49f26812002-04-06 01:45:35 +00002477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002478 /* Write the value with commas. */
2479 i = 22;
2480 buf[i--] = '\0';
2481 buf[i--] = '\n';
2482 k = 3;
2483 do {
2484 size_t nextvalue = value / 10;
Benjamin Peterson2dba1ee2013-02-20 16:54:30 -05002485 unsigned int digit = (unsigned int)(value - nextvalue * 10);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002486 value = nextvalue;
2487 buf[i--] = (char)(digit + '0');
2488 --k;
2489 if (k == 0 && value && i >= 0) {
2490 k = 3;
2491 buf[i--] = ',';
2492 }
2493 } while (value && i >= 0);
Tim Peters49f26812002-04-06 01:45:35 +00002494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002495 while (i >= 0)
2496 buf[i--] = ' ';
David Malcolm49526f42012-06-22 14:55:41 -04002497 fputs(buf, out);
Tim Peters49f26812002-04-06 01:45:35 +00002498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002499 return origvalue;
Tim Peters16bcb6b2002-04-05 05:45:31 +00002500}
2501
David Malcolm49526f42012-06-22 14:55:41 -04002502void
2503_PyDebugAllocatorStats(FILE *out,
2504 const char *block_name, int num_blocks, size_t sizeof_block)
2505{
2506 char buf1[128];
2507 char buf2[128];
2508 PyOS_snprintf(buf1, sizeof(buf1),
Tim Peterseaa3bcc2013-09-05 22:57:04 -05002509 "%d %ss * %" PY_FORMAT_SIZE_T "d bytes each",
David Malcolm49526f42012-06-22 14:55:41 -04002510 num_blocks, block_name, sizeof_block);
2511 PyOS_snprintf(buf2, sizeof(buf2),
2512 "%48s ", buf1);
2513 (void)printone(out, buf2, num_blocks * sizeof_block);
2514}
2515
Victor Stinner34be807c2016-03-14 12:04:26 +01002516
David Malcolm49526f42012-06-22 14:55:41 -04002517#ifdef WITH_PYMALLOC
2518
Victor Stinner34be807c2016-03-14 12:04:26 +01002519#ifdef Py_DEBUG
2520/* Is target in the list? The list is traversed via the nextpool pointers.
2521 * The list may be NULL-terminated, or circular. Return 1 if target is in
2522 * list, else 0.
2523 */
2524static int
2525pool_is_in_list(const poolp target, poolp list)
2526{
2527 poolp origlist = list;
2528 assert(target != NULL);
2529 if (list == NULL)
2530 return 0;
2531 do {
2532 if (target == list)
2533 return 1;
2534 list = list->nextpool;
2535 } while (list != NULL && list != origlist);
2536 return 0;
2537}
2538#endif
2539
David Malcolm49526f42012-06-22 14:55:41 -04002540/* Print summary info to "out" about the state of pymalloc's structures.
Tim Peters08d82152002-04-18 22:25:03 +00002541 * In Py_DEBUG mode, also perform some expensive internal consistency
2542 * checks.
Victor Stinner6bf992a2017-12-06 17:26:10 +01002543 *
2544 * Return 0 if the memory debug hooks are not installed or no statistics was
Leo Ariasc3d95082018-02-03 18:36:10 -06002545 * written into out, return 1 otherwise.
Tim Peters08d82152002-04-18 22:25:03 +00002546 */
Victor Stinner6bf992a2017-12-06 17:26:10 +01002547int
David Malcolm49526f42012-06-22 14:55:41 -04002548_PyObject_DebugMallocStats(FILE *out)
Tim Peters7ccfadf2002-04-01 06:04:21 +00002549{
Victor Stinner6bf992a2017-12-06 17:26:10 +01002550 if (!_PyMem_PymallocEnabled()) {
2551 return 0;
2552 }
2553
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002554 uint i;
2555 const uint numclasses = SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT;
2556 /* # of pools, allocated blocks, and free blocks per class index */
2557 size_t numpools[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT];
2558 size_t numblocks[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT];
2559 size_t numfreeblocks[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT];
2560 /* total # of allocated bytes in used and full pools */
2561 size_t allocated_bytes = 0;
2562 /* total # of available bytes in used pools */
2563 size_t available_bytes = 0;
2564 /* # of free pools + pools not yet carved out of current arena */
2565 uint numfreepools = 0;
2566 /* # of bytes for arena alignment padding */
2567 size_t arena_alignment = 0;
2568 /* # of bytes in used and full pools used for pool_headers */
2569 size_t pool_header_bytes = 0;
2570 /* # of bytes in used and full pools wasted due to quantization,
2571 * i.e. the necessarily leftover space at the ends of used and
2572 * full pools.
2573 */
2574 size_t quantization = 0;
2575 /* # of arenas actually allocated. */
2576 size_t narenas = 0;
2577 /* running total -- should equal narenas * ARENA_SIZE */
2578 size_t total;
2579 char buf[128];
Tim Peters7ccfadf2002-04-01 06:04:21 +00002580
David Malcolm49526f42012-06-22 14:55:41 -04002581 fprintf(out, "Small block threshold = %d, in %u size classes.\n",
Stefan Krah735bb122010-11-26 10:54:09 +00002582 SMALL_REQUEST_THRESHOLD, numclasses);
Tim Peters7ccfadf2002-04-01 06:04:21 +00002583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002584 for (i = 0; i < numclasses; ++i)
2585 numpools[i] = numblocks[i] = numfreeblocks[i] = 0;
Tim Peters7ccfadf2002-04-01 06:04:21 +00002586
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002587 /* Because full pools aren't linked to from anything, it's easiest
2588 * to march over all the arenas. If we're lucky, most of the memory
2589 * will be living in full pools -- would be a shame to miss them.
2590 */
Victor Stinner9e87e772017-11-24 12:09:24 +01002591 for (i = 0; i < maxarenas; ++i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002592 uint j;
Victor Stinner9e87e772017-11-24 12:09:24 +01002593 uintptr_t base = arenas[i].address;
Thomas Woutersa9773292006-04-21 09:43:23 +00002594
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002595 /* Skip arenas which are not allocated. */
Victor Stinner9e87e772017-11-24 12:09:24 +01002596 if (arenas[i].address == (uintptr_t)NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002597 continue;
2598 narenas += 1;
Thomas Woutersa9773292006-04-21 09:43:23 +00002599
Victor Stinner9e87e772017-11-24 12:09:24 +01002600 numfreepools += arenas[i].nfreepools;
Tim Peters7ccfadf2002-04-01 06:04:21 +00002601
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002602 /* round up to pool alignment */
Benjamin Peterson5d4b09c2016-09-18 19:24:52 -07002603 if (base & (uintptr_t)POOL_SIZE_MASK) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002604 arena_alignment += POOL_SIZE;
Benjamin Peterson5d4b09c2016-09-18 19:24:52 -07002605 base &= ~(uintptr_t)POOL_SIZE_MASK;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002606 base += POOL_SIZE;
2607 }
Tim Peters7ccfadf2002-04-01 06:04:21 +00002608
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002609 /* visit every pool in the arena */
Victor Stinner9e87e772017-11-24 12:09:24 +01002610 assert(base <= (uintptr_t) arenas[i].pool_address);
2611 for (j = 0; base < (uintptr_t) arenas[i].pool_address;
Benjamin Peterson19517e42016-09-18 19:22:22 -07002612 ++j, base += POOL_SIZE) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002613 poolp p = (poolp)base;
2614 const uint sz = p->szidx;
2615 uint freeblocks;
Tim Peters08d82152002-04-18 22:25:03 +00002616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002617 if (p->ref.count == 0) {
2618 /* currently unused */
Victor Stinner34be807c2016-03-14 12:04:26 +01002619#ifdef Py_DEBUG
Victor Stinner9e87e772017-11-24 12:09:24 +01002620 assert(pool_is_in_list(p, arenas[i].freepools));
Victor Stinner34be807c2016-03-14 12:04:26 +01002621#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002622 continue;
2623 }
2624 ++numpools[sz];
2625 numblocks[sz] += p->ref.count;
2626 freeblocks = NUMBLOCKS(sz) - p->ref.count;
2627 numfreeblocks[sz] += freeblocks;
Tim Peters08d82152002-04-18 22:25:03 +00002628#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002629 if (freeblocks > 0)
Victor Stinner9e87e772017-11-24 12:09:24 +01002630 assert(pool_is_in_list(p, usedpools[sz + sz]));
Tim Peters08d82152002-04-18 22:25:03 +00002631#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002632 }
2633 }
Victor Stinner9e87e772017-11-24 12:09:24 +01002634 assert(narenas == narenas_currently_allocated);
Tim Peters7ccfadf2002-04-01 06:04:21 +00002635
David Malcolm49526f42012-06-22 14:55:41 -04002636 fputc('\n', out);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002637 fputs("class size num pools blocks in use avail blocks\n"
2638 "----- ---- --------- ------------- ------------\n",
David Malcolm49526f42012-06-22 14:55:41 -04002639 out);
Tim Peters7ccfadf2002-04-01 06:04:21 +00002640
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002641 for (i = 0; i < numclasses; ++i) {
2642 size_t p = numpools[i];
2643 size_t b = numblocks[i];
2644 size_t f = numfreeblocks[i];
2645 uint size = INDEX2SIZE(i);
2646 if (p == 0) {
2647 assert(b == 0 && f == 0);
2648 continue;
2649 }
David Malcolm49526f42012-06-22 14:55:41 -04002650 fprintf(out, "%5u %6u "
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002651 "%11" PY_FORMAT_SIZE_T "u "
2652 "%15" PY_FORMAT_SIZE_T "u "
2653 "%13" PY_FORMAT_SIZE_T "u\n",
Stefan Krah735bb122010-11-26 10:54:09 +00002654 i, size, p, b, f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002655 allocated_bytes += b * size;
2656 available_bytes += f * size;
2657 pool_header_bytes += p * POOL_OVERHEAD;
2658 quantization += p * ((POOL_SIZE - POOL_OVERHEAD) % size);
2659 }
David Malcolm49526f42012-06-22 14:55:41 -04002660 fputc('\n', out);
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002661#ifdef PYMEM_DEBUG_SERIALNO
2662 if (_PyMem_DebugEnabled()) {
Victor Stinner9e87e772017-11-24 12:09:24 +01002663 (void)printone(out, "# times object malloc called", serialno);
Victor Stinnere8f9acf2019-04-12 21:54:06 +02002664 }
2665#endif
Victor Stinner9e87e772017-11-24 12:09:24 +01002666 (void)printone(out, "# arenas allocated total", ntimes_arena_allocated);
2667 (void)printone(out, "# arenas reclaimed", ntimes_arena_allocated - narenas);
2668 (void)printone(out, "# arenas highwater mark", narenas_highwater);
David Malcolm49526f42012-06-22 14:55:41 -04002669 (void)printone(out, "# arenas allocated current", narenas);
Thomas Woutersa9773292006-04-21 09:43:23 +00002670
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002671 PyOS_snprintf(buf, sizeof(buf),
2672 "%" PY_FORMAT_SIZE_T "u arenas * %d bytes/arena",
2673 narenas, ARENA_SIZE);
David Malcolm49526f42012-06-22 14:55:41 -04002674 (void)printone(out, buf, narenas * ARENA_SIZE);
Tim Peters16bcb6b2002-04-05 05:45:31 +00002675
David Malcolm49526f42012-06-22 14:55:41 -04002676 fputc('\n', out);
Tim Peters16bcb6b2002-04-05 05:45:31 +00002677
David Malcolm49526f42012-06-22 14:55:41 -04002678 total = printone(out, "# bytes in allocated blocks", allocated_bytes);
2679 total += printone(out, "# bytes in available blocks", available_bytes);
Tim Peters49f26812002-04-06 01:45:35 +00002680
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002681 PyOS_snprintf(buf, sizeof(buf),
2682 "%u unused pools * %d bytes", numfreepools, POOL_SIZE);
David Malcolm49526f42012-06-22 14:55:41 -04002683 total += printone(out, buf, (size_t)numfreepools * POOL_SIZE);
Tim Peters16bcb6b2002-04-05 05:45:31 +00002684
David Malcolm49526f42012-06-22 14:55:41 -04002685 total += printone(out, "# bytes lost to pool headers", pool_header_bytes);
2686 total += printone(out, "# bytes lost to quantization", quantization);
2687 total += printone(out, "# bytes lost to arena alignment", arena_alignment);
2688 (void)printone(out, "Total", total);
Victor Stinner6bf992a2017-12-06 17:26:10 +01002689 return 1;
Tim Peters7ccfadf2002-04-01 06:04:21 +00002690}
2691
David Malcolm49526f42012-06-22 14:55:41 -04002692#endif /* #ifdef WITH_PYMALLOC */