Coverage Report

Created: 2026-11-30 07:19

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython3/Objects/obmalloc.c
Line
Count
Source
1
/* Python's malloc wrappers (see pymem.h) */
2
3
#include "Python.h"
4
#include "pycore_ceval.h"
5
#include "pycore_interp.h"        // _PyInterpreterState_HasFeature
6
#include "pycore_mmap.h"          // _PyAnnotateMemoryMap()
7
#include "pycore_object.h"        // _PyDebugAllocatorStats() definition
8
#include "pycore_obmalloc.h"
9
#include "pycore_obmalloc_init.h"
10
#include "pycore_pyerrors.h"      // _Py_FatalErrorFormat()
11
#include "pycore_pymem.h"
12
#include "pycore_pystate.h"       // _PyInterpreterState_GET
13
#include "pycore_stats.h"         // OBJECT_STAT_INC_COND()
14
15
#include <stdlib.h>               // malloc()
16
#include <stdbool.h>
17
#include <stdio.h>                // fopen(), fgets(), sscanf()
18
#include <errno.h>                // errno
19
#ifdef WITH_MIMALLOC
20
// Forward declarations of functions used in our mimalloc modifications
21
static void _PyMem_mi_page_clear_qsbr(mi_page_t *page);
22
static bool _PyMem_mi_page_is_safe_to_free(mi_page_t *page);
23
static bool _PyMem_mi_page_maybe_free(mi_page_t *page, mi_page_queue_t *pq, bool force);
24
static void _PyMem_mi_page_reclaimed(mi_page_t *page);
25
static void _PyMem_mi_heap_collect_qsbr(mi_heap_t *heap);
26
#  include "pycore_mimalloc.h"
27
#  include "mimalloc/static.c"
28
#  include "mimalloc/internal.h"  // for stats
29
#endif
30
31
#if defined(Py_GIL_DISABLED) && !defined(WITH_MIMALLOC)
32
#  error "Py_GIL_DISABLED requires WITH_MIMALLOC"
33
#endif
34
35
#undef  uint
36
363M
#define uint pymem_uint
37
38
39
/* Defined in tracemalloc.c */
40
extern void _PyMem_DumpTraceback(int fd, const void *ptr);
41
42
static void _PyObject_DebugDumpAddress(const void *p);
43
static void _PyMem_DebugCheckAddress(const char *func, char api_id, const void *p);
44
45
46
static void set_up_debug_hooks_domain_unlocked(PyMemAllocatorDomain domain);
47
static void set_up_debug_hooks_unlocked(void);
48
static void get_allocator_unlocked(PyMemAllocatorDomain, PyMemAllocatorEx *);
49
static void set_allocator_unlocked(PyMemAllocatorDomain, PyMemAllocatorEx *);
50
51
52
/***************************************/
53
/* low-level allocator implementations */
54
/***************************************/
55
56
/* the default raw allocator (wraps malloc) */
57
58
void *
59
_PyMem_RawMalloc(void *Py_UNUSED(ctx), size_t size)
60
3.31M
{
61
    /* PyMem_RawMalloc(0) means malloc(1). Some systems would return NULL
62
       for malloc(0), which would be treated as an error. Some platforms would
63
       return a pointer with no memory behind it, which would break pymalloc.
64
       To solve these problems, allocate an extra byte. */
65
3.31M
    if (size == 0)
66
99.7k
        size = 1;
67
3.31M
    return malloc(size);
68
3.31M
}
69
70
void *
71
_PyMem_RawCalloc(void *Py_UNUSED(ctx), size_t nelem, size_t elsize)
72
957k
{
73
    /* PyMem_RawCalloc(0, 0) means calloc(1, 1). Some systems would return NULL
74
       for calloc(0, 0), which would be treated as an error. Some platforms
75
       would return a pointer with no memory behind it, which would break
76
       pymalloc.  To solve these problems, allocate an extra byte. */
77
957k
    if (nelem == 0 || elsize == 0) {
78
0
        nelem = 1;
79
0
        elsize = 1;
80
0
    }
81
957k
    return calloc(nelem, elsize);
82
957k
}
83
84
void *
85
_PyMem_RawRealloc(void *Py_UNUSED(ctx), void *ptr, size_t size)
86
6.65M
{
87
6.65M
    if (size == 0)
88
0
        size = 1;
89
6.65M
    return realloc(ptr, size);
90
6.65M
}
91
92
void
93
_PyMem_RawFree(void *Py_UNUSED(ctx), void *ptr)
94
4.22M
{
95
4.22M
    free(ptr);
96
4.22M
}
97
98
#ifdef WITH_MIMALLOC
99
100
static void
101
_PyMem_mi_page_clear_qsbr(mi_page_t *page)
102
0
{
103
#ifdef Py_GIL_DISABLED
104
    // Clear the QSBR goal and remove the page from the QSBR linked list.
105
    page->qsbr_goal = 0;
106
    if (page->qsbr_node.next != NULL) {
107
        llist_remove(&page->qsbr_node);
108
    }
109
#endif
110
0
}
111
112
// Check if an empty, newly reclaimed page is safe to free now.
113
static bool
114
_PyMem_mi_page_is_safe_to_free(mi_page_t *page)
115
0
{
116
0
    assert(mi_page_all_free(page));
117
#ifdef Py_GIL_DISABLED
118
    assert(page->qsbr_node.next == NULL);
119
    if (page->use_qsbr && page->qsbr_goal != 0) {
120
        _PyThreadStateImpl *tstate = (_PyThreadStateImpl *)_PyThreadState_GET();
121
        if (tstate == NULL) {
122
            return false;
123
        }
124
        return _Py_qbsr_goal_reached(tstate->qsbr, page->qsbr_goal);
125
    }
126
#endif
127
0
    return true;
128
129
0
}
130
131
#ifdef Py_GIL_DISABLED
132
133
// If we are deferring collection of more than this amount of memory for
134
// mimalloc pages, advance the write sequence.  Advancing allows these
135
// pages to be re-used in a different thread or for a different size class.
136
#define QSBR_PAGE_MEM_LIMIT 4096*20
137
138
// Return true if the global write sequence should be advanced for a mimalloc
139
// page that is deferred from collection.
140
static bool
141
should_advance_qsbr_for_page(struct _qsbr_thread_state *qsbr, mi_page_t *page)
142
{
143
    size_t bsize = mi_page_block_size(page);
144
    size_t page_size = page->capacity*bsize;
145
    if (page_size > QSBR_PAGE_MEM_LIMIT) {
146
        qsbr->deferred_page_memory = 0;
147
        return true;
148
    }
149
    qsbr->deferred_page_memory += page_size;
150
    if (qsbr->deferred_page_memory > QSBR_PAGE_MEM_LIMIT) {
151
        qsbr->deferred_page_memory = 0;
152
        return true;
153
    }
154
    return false;
155
}
156
157
static _PyThreadStateImpl *
158
tstate_from_heap(mi_heap_t *heap)
159
{
160
    return _Py_CONTAINER_OF(heap->tld, _PyThreadStateImpl, mimalloc.tld);
161
}
162
#endif
163
164
static bool
165
_PyMem_mi_page_maybe_free(mi_page_t *page, mi_page_queue_t *pq, bool force)
166
0
{
167
#ifdef Py_GIL_DISABLED
168
    assert(mi_page_all_free(page));
169
    if (page->use_qsbr) {
170
        struct _qsbr_thread_state *qsbr = ((_PyThreadStateImpl *)PyThreadState_GET())->qsbr;
171
        if (page->qsbr_goal != 0 && _Py_qbsr_goal_reached(qsbr, page->qsbr_goal)) {
172
            _PyMem_mi_page_clear_qsbr(page);
173
            _mi_page_free(page, pq, force);
174
            return true;
175
        }
176
177
        // gh-145615: since we are not freeing this page yet, we want to
178
        // make it available for allocations. Note that the QSBR goal and
179
        // linked list node remain set even if the page is later used for
180
        // an allocation. We only detect and clear the QSBR goal when the
181
        // page becomes empty again (used == 0).
182
        if (mi_page_is_in_full(page)) {
183
            _mi_page_unfull(page);
184
        }
185
186
        _PyMem_mi_page_clear_qsbr(page);
187
        page->retire_expire = 0;
188
189
        if (should_advance_qsbr_for_page(qsbr, page)) {
190
            page->qsbr_goal = _Py_qsbr_advance(qsbr->shared);
191
        }
192
        else {
193
            page->qsbr_goal = _Py_qsbr_shared_next(qsbr->shared);
194
        }
195
196
        // We may be freeing a page belonging to a different thread during a
197
        // stop-the-world event. Find the _PyThreadStateImpl for the page.
198
        _PyThreadStateImpl *tstate = tstate_from_heap(mi_page_heap(page));
199
        llist_insert_tail(&tstate->mimalloc.page_list, &page->qsbr_node);
200
        return false;
201
    }
202
#endif
203
0
    _mi_page_free(page, pq, force);
204
0
    return true;
205
0
}
206
207
static void
208
_PyMem_mi_page_reclaimed(mi_page_t *page)
209
0
{
210
#ifdef Py_GIL_DISABLED
211
    assert(page->qsbr_node.next == NULL);
212
    if (page->qsbr_goal != 0) {
213
        if (mi_page_all_free(page)) {
214
            assert(page->qsbr_node.next == NULL);
215
            _PyThreadStateImpl *tstate = tstate_from_heap(mi_page_heap(page));
216
            // gh-159462: the owning tstate may differ from the current
217
            // one, but the heap is always owned by the current OS thread,
218
            // so the page list is not shared with other OS threads.
219
            assert(mi_page_heap(page)->thread_id == _Py_ThreadId());
220
            page->retire_expire = 0;
221
            llist_insert_tail(&tstate->mimalloc.page_list, &page->qsbr_node);
222
        }
223
        else {
224
            page->qsbr_goal = 0;
225
        }
226
    }
227
#endif
228
0
}
229
230
static void
231
_PyMem_mi_heap_collect_qsbr(mi_heap_t *heap)
232
0
{
233
#ifdef Py_GIL_DISABLED
234
    if (!heap->page_use_qsbr) {
235
        return;
236
    }
237
238
    _PyThreadStateImpl *tstate = (_PyThreadStateImpl *)_PyThreadState_GET();
239
    struct llist_node *head = &tstate->mimalloc.page_list;
240
    if (llist_empty(head)) {
241
        return;
242
    }
243
244
    struct llist_node *node;
245
    llist_for_each_safe(node, head) {
246
        mi_page_t *page = llist_data(node, mi_page_t, qsbr_node);
247
        if (!mi_page_all_free(page)) {
248
            // We allocated from this page some point after the delayed free
249
            _PyMem_mi_page_clear_qsbr(page);
250
            continue;
251
        }
252
253
        if (!_Py_qsbr_poll(tstate->qsbr, page->qsbr_goal)) {
254
            return;
255
        }
256
257
        _PyMem_mi_page_clear_qsbr(page);
258
        _mi_page_free(page, mi_page_queue_of(page), false);
259
    }
260
#endif
261
0
}
262
263
void *
264
_PyMem_MiMalloc(void *ctx, size_t size)
265
0
{
266
#ifdef Py_GIL_DISABLED
267
    _PyThreadStateImpl *tstate = (_PyThreadStateImpl *)_PyThreadState_GET();
268
    mi_heap_t *heap = &tstate->mimalloc.heaps[_Py_MIMALLOC_HEAP_MEM];
269
    return mi_heap_malloc(heap, size);
270
#else
271
0
    return mi_malloc(size);
272
0
#endif
273
0
}
274
275
void *
276
_PyMem_MiCalloc(void *ctx, size_t nelem, size_t elsize)
277
0
{
278
#ifdef Py_GIL_DISABLED
279
    _PyThreadStateImpl *tstate = (_PyThreadStateImpl *)_PyThreadState_GET();
280
    mi_heap_t *heap = &tstate->mimalloc.heaps[_Py_MIMALLOC_HEAP_MEM];
281
    return mi_heap_calloc(heap, nelem, elsize);
282
#else
283
0
    return mi_calloc(nelem, elsize);
284
0
#endif
285
0
}
286
287
void *
288
_PyMem_MiRealloc(void *ctx, void *ptr, size_t size)
289
0
{
290
#ifdef Py_GIL_DISABLED
291
    _PyThreadStateImpl *tstate = (_PyThreadStateImpl *)_PyThreadState_GET();
292
    mi_heap_t *heap = &tstate->mimalloc.heaps[_Py_MIMALLOC_HEAP_MEM];
293
    return mi_heap_realloc(heap, ptr, size);
294
#else
295
0
    return mi_realloc(ptr, size);
296
0
#endif
297
0
}
298
299
void
300
_PyMem_MiFree(void *ctx, void *ptr)
301
0
{
302
0
    mi_free(ptr);
303
0
}
304
305
void *
306
_PyObject_MiMalloc(void *ctx, size_t nbytes)
307
0
{
308
#ifdef Py_GIL_DISABLED
309
    _PyThreadStateImpl *tstate = (_PyThreadStateImpl *)_PyThreadState_GET();
310
    mi_heap_t *heap = tstate->mimalloc.current_object_heap;
311
    return mi_heap_malloc(heap, nbytes);
312
#else
313
0
    return mi_malloc(nbytes);
314
0
#endif
315
0
}
316
317
void *
318
_PyObject_MiCalloc(void *ctx, size_t nelem, size_t elsize)
319
0
{
320
#ifdef Py_GIL_DISABLED
321
    _PyThreadStateImpl *tstate = (_PyThreadStateImpl *)_PyThreadState_GET();
322
    mi_heap_t *heap = tstate->mimalloc.current_object_heap;
323
    return mi_heap_calloc(heap, nelem, elsize);
324
#else
325
0
    return mi_calloc(nelem, elsize);
326
0
#endif
327
0
}
328
329
330
void *
331
_PyObject_MiRealloc(void *ctx, void *ptr, size_t nbytes)
332
0
{
333
#ifdef Py_GIL_DISABLED
334
    _PyThreadStateImpl *tstate = (_PyThreadStateImpl *)_PyThreadState_GET();
335
    // Implement our own realloc logic so that we can copy PyObject header
336
    // in a thread-safe way.
337
    size_t size = mi_usable_size(ptr);
338
    if (nbytes <= size && nbytes >= (size / 2) && nbytes > 0) {
339
        return ptr;
340
    }
341
342
    mi_heap_t *heap = tstate->mimalloc.current_object_heap;
343
    void* newp = mi_heap_malloc(heap, nbytes);
344
    if (newp == NULL) {
345
        return NULL;
346
    }
347
348
    // Free threaded Python allows access from other threads to the PyObject reference count
349
    // fields for a period of time after the object is freed (see InternalDocs/qsbr.md).
350
    // These fields are typically initialized by PyObject_Init() using relaxed
351
    // atomic stores. We need to copy these fields in a thread-safe way here.
352
    // We use the "debug_offset" to determine how many bytes to copy -- it
353
    // includes the PyObject header and plus any extra pre-headers.
354
    size_t offset = heap->debug_offset;
355
    assert(offset % sizeof(void*) == 0);
356
357
    size_t copy_size = (size < nbytes ? size : nbytes);
358
    if (copy_size >= offset) {
359
        for (size_t i = 0; i != offset; i += sizeof(void*)) {
360
            // Use memcpy to avoid strict-aliasing issues. However, we probably
361
            // still have unavoidable strict-aliasing issues with
362
            // _Py_atomic_store_ptr_relaxed here.
363
            void *word;
364
            memcpy(&word, (char*)ptr + i, sizeof(void*));
365
            _Py_atomic_store_ptr_relaxed((void**)((char*)newp + i), word);
366
        }
367
        _mi_memcpy((char*)newp + offset, (char*)ptr + offset, copy_size - offset);
368
    }
369
    else {
370
        // memcpy(dst, NULL, 0) is undefined behavior. See gh-151297.
371
        if mi_likely(ptr) {
372
            _mi_memcpy(newp, ptr, copy_size);
373
        }
374
    }
375
    mi_free(ptr);
376
    return newp;
377
#else
378
0
    return mi_realloc(ptr, nbytes);
379
0
#endif
380
0
}
381
382
void
383
_PyObject_MiFree(void *ctx, void *ptr)
384
0
{
385
0
    mi_free(ptr);
386
0
}
387
388
void *
389
_PyMem_MiRawMalloc(void *ctx, size_t size)
390
0
{
391
0
    return mi_malloc(size);
392
0
}
393
394
void *
395
_PyMem_MiRawCalloc(void *ctx, size_t nelem, size_t elsize)
396
0
{
397
0
    return mi_calloc(nelem, elsize);
398
0
}
399
400
void *
401
_PyMem_MiRawRealloc(void *ctx, void *ptr, size_t size)
402
0
{
403
0
    return mi_realloc(ptr, size);
404
0
}
405
406
void
407
_PyMem_MiRawFree(void *ctx, void *ptr)
408
0
{
409
0
    mi_free(ptr);
410
0
}
411
#endif // WITH_MIMALLOC
412
413
414
0
#define MALLOC_ALLOC {NULL, _PyMem_RawMalloc, _PyMem_RawCalloc, _PyMem_RawRealloc, _PyMem_RawFree}
415
416
417
#ifdef WITH_MIMALLOC
418
0
#  define MIMALLOC_ALLOC    {NULL, _PyMem_MiMalloc, _PyMem_MiCalloc, _PyMem_MiRealloc, _PyMem_MiFree}
419
0
#  define MIMALLOC_RAWALLOC {NULL, _PyMem_MiRawMalloc, _PyMem_MiRawCalloc, _PyMem_MiRawRealloc, _PyMem_MiRawFree}
420
0
#  define MIMALLOC_OBJALLOC {NULL, _PyObject_MiMalloc, _PyObject_MiCalloc, _PyObject_MiRealloc, _PyObject_MiFree}
421
#endif
422
423
/* the pymalloc allocator */
424
425
// The actual implementation is further down.
426
427
#if defined(WITH_PYMALLOC)
428
void* _PyObject_Malloc(void *ctx, size_t size);
429
void* _PyObject_Calloc(void *ctx, size_t nelem, size_t elsize);
430
void _PyObject_Free(void *ctx, void *p);
431
void* _PyObject_Realloc(void *ctx, void *ptr, size_t size);
432
0
#  define PYMALLOC_ALLOC {NULL, _PyObject_Malloc, _PyObject_Calloc, _PyObject_Realloc, _PyObject_Free}
433
#endif  // WITH_PYMALLOC
434
435
#if defined(Py_GIL_DISABLED)
436
// Py_GIL_DISABLED requires using mimalloc for "mem" and "obj" domains.
437
#  define PYRAW_ALLOC MIMALLOC_RAWALLOC
438
#  define PYMEM_ALLOC MIMALLOC_ALLOC
439
#  define PYOBJ_ALLOC MIMALLOC_OBJALLOC
440
#elif defined(_Py_ADDRESS_SANITIZER) || defined(_Py_MEMORY_SANITIZER)
441
// ASan and MSan do not track pymalloc blocks, so use malloc by default.
442
// pymalloc can still be selected at runtime.
443
#  define PYRAW_ALLOC MALLOC_ALLOC
444
#  define PYMEM_ALLOC MALLOC_ALLOC
445
#  define PYOBJ_ALLOC MALLOC_ALLOC
446
#elif defined(WITH_PYMALLOC)
447
0
#  define PYRAW_ALLOC MALLOC_ALLOC
448
0
#  define PYMEM_ALLOC PYMALLOC_ALLOC
449
0
#  define PYOBJ_ALLOC PYMALLOC_ALLOC
450
#else
451
#  define PYRAW_ALLOC MALLOC_ALLOC
452
#  define PYMEM_ALLOC MALLOC_ALLOC
453
#  define PYOBJ_ALLOC MALLOC_ALLOC
454
#endif
455
456
457
/* the default debug allocators */
458
459
// The actual implementation is further down.
460
461
void* _PyMem_DebugRawMalloc(void *ctx, size_t size);
462
void* _PyMem_DebugRawCalloc(void *ctx, size_t nelem, size_t elsize);
463
void* _PyMem_DebugRawRealloc(void *ctx, void *ptr, size_t size);
464
void _PyMem_DebugRawFree(void *ctx, void *ptr);
465
466
void* _PyMem_DebugMalloc(void *ctx, size_t size);
467
void* _PyMem_DebugCalloc(void *ctx, size_t nelem, size_t elsize);
468
void* _PyMem_DebugRealloc(void *ctx, void *ptr, size_t size);
469
void _PyMem_DebugFree(void *ctx, void *p);
470
471
#define PYDBGRAW_ALLOC \
472
0
    {&_PyRuntime.allocators.debug.raw, _PyMem_DebugRawMalloc, _PyMem_DebugRawCalloc, _PyMem_DebugRawRealloc, _PyMem_DebugRawFree}
473
#define PYDBGMEM_ALLOC \
474
0
    {&_PyRuntime.allocators.debug.mem, _PyMem_DebugMalloc, _PyMem_DebugCalloc, _PyMem_DebugRealloc, _PyMem_DebugFree}
475
#define PYDBGOBJ_ALLOC \
476
0
    {&_PyRuntime.allocators.debug.obj, _PyMem_DebugMalloc, _PyMem_DebugCalloc, _PyMem_DebugRealloc, _PyMem_DebugFree}
477
478
/* default raw allocator (not swappable) */
479
480
void *
481
_PyMem_DefaultRawMalloc(size_t size)
482
154
{
483
#ifdef Py_DEBUG
484
    return _PyMem_DebugRawMalloc(&_PyRuntime.allocators.debug.raw, size);
485
#else
486
154
    return _PyMem_RawMalloc(NULL, size);
487
154
#endif
488
154
}
489
490
void *
491
_PyMem_DefaultRawCalloc(size_t nelem, size_t elsize)
492
0
{
493
#ifdef Py_DEBUG
494
    return _PyMem_DebugRawCalloc(&_PyRuntime.allocators.debug.raw, nelem, elsize);
495
#else
496
0
    return _PyMem_RawCalloc(NULL, nelem, elsize);
497
0
#endif
498
0
}
499
500
void *
501
_PyMem_DefaultRawRealloc(void *ptr, size_t size)
502
0
{
503
#ifdef Py_DEBUG
504
    return _PyMem_DebugRawRealloc(&_PyRuntime.allocators.debug.raw, ptr, size);
505
#else
506
0
    return _PyMem_RawRealloc(NULL, ptr, size);
507
0
#endif
508
0
}
509
510
void
511
_PyMem_DefaultRawFree(void *ptr)
512
176
{
513
#ifdef Py_DEBUG
514
    _PyMem_DebugRawFree(&_PyRuntime.allocators.debug.raw, ptr);
515
#else
516
176
    _PyMem_RawFree(NULL, ptr);
517
176
#endif
518
176
}
519
520
wchar_t*
521
_PyMem_DefaultRawWcsdup(const wchar_t *str)
522
110
{
523
110
    assert(str != NULL);
524
525
110
    size_t len = wcslen(str);
526
110
    if (len > (size_t)PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
527
0
        return NULL;
528
0
    }
529
530
110
    size_t size = (len + 1) * sizeof(wchar_t);
531
110
    wchar_t *str2 = _PyMem_DefaultRawMalloc(size);
532
110
    if (str2 == NULL) {
533
0
        return NULL;
534
0
    }
535
536
110
    memcpy(str2, str, size);
537
110
    return str2;
538
110
}
539
540
/* the low-level virtual memory allocator */
541
542
#ifdef WITH_PYMALLOC
543
#  ifdef MS_WINDOWS
544
#    include <windows.h>
545
#  elif defined(HAVE_MMAP)
546
#    include <sys/mman.h>
547
#    ifdef MAP_ANONYMOUS
548
#      define ARENAS_USE_MMAP
549
#    endif
550
#  endif
551
#endif
552
553
/* Return the system's default huge page size in bytes, or 0 if it
554
 * cannot be determined.  The result is cached after the first call.
555
 *
556
 * This is Linux-only (/proc/meminfo).  On other systems that define
557
 * MAP_HUGETLB the caller should skip huge pages gracefully. */
558
#if defined(PYMALLOC_USE_HUGEPAGES) && defined(ARENAS_USE_MMAP) && defined(MAP_HUGETLB)
559
static size_t
560
_pymalloc_system_hugepage_size(void)
561
{
562
    static size_t hp_size = 0;
563
    static int initialized = 0;
564
565
    if (initialized) {
566
        return hp_size;
567
    }
568
569
#ifdef __linux__
570
    FILE *f = fopen("/proc/meminfo", "r");
571
    if (f != NULL) {
572
        char line[256];
573
        while (fgets(line, sizeof(line), f)) {
574
            unsigned long size_kb;
575
            if (sscanf(line, "Hugepagesize: %lu kB", &size_kb) == 1) {
576
                hp_size = (size_t)size_kb * 1024;
577
                break;
578
            }
579
        }
580
        fclose(f);
581
    }
582
#endif
583
584
    initialized = 1;
585
    return hp_size;
586
}
587
#endif
588
589
#if (defined(MS_WINDOWS) && defined(PYMALLOC_USE_HUGEPAGES)) || \
590
    (defined(PYMALLOC_USE_HUGEPAGES) && defined(ARENAS_USE_MMAP) && defined(MAP_HUGETLB))
591
static size_t
592
_pymalloc_round_up_to_multiple(size_t size, size_t multiple)
593
{
594
    if (multiple == 0 || size == 0) {
595
        return size;
596
    }
597
598
    size_t remainder = size % multiple;
599
    if (remainder == 0) {
600
        return size;
601
    }
602
603
    size_t padding = multiple - remainder;
604
    if (size > SIZE_MAX - padding) {
605
        return 0;
606
    }
607
    return size + padding;
608
}
609
#endif
610
611
static size_t
612
_pymalloc_virtual_alloc_size(size_t size)
613
71.8k
{
614
#if defined(MS_WINDOWS) && defined(PYMALLOC_USE_HUGEPAGES)
615
    if (_PyRuntime.allocators.use_hugepages) {
616
        SIZE_T large_page_size = GetLargePageMinimum();
617
        if (large_page_size > 0) {
618
            return _pymalloc_round_up_to_multiple(size, (size_t)large_page_size);
619
        }
620
    }
621
#elif defined(PYMALLOC_USE_HUGEPAGES) && defined(ARENAS_USE_MMAP) && defined(MAP_HUGETLB)
622
    if (_PyRuntime.allocators.use_hugepages) {
623
        size_t hp_size = _pymalloc_system_hugepage_size();
624
        if (hp_size > 0) {
625
            return _pymalloc_round_up_to_multiple(size, hp_size);
626
        }
627
    }
628
#endif
629
71.8k
    return size;
630
71.8k
}
631
632
void *
633
_PyMem_ArenaAlloc(void *Py_UNUSED(ctx), size_t size)
634
43.7k
{
635
#ifdef MS_WINDOWS
636
#  ifdef PYMALLOC_USE_HUGEPAGES
637
    if (_PyRuntime.allocators.use_hugepages) {
638
        SIZE_T lp_size = GetLargePageMinimum();
639
        if (lp_size > 0 && size % lp_size == 0) {
640
            void *ptr = VirtualAlloc(NULL, size,
641
                            MEM_COMMIT | MEM_RESERVE | MEM_LARGE_PAGES,
642
                            PAGE_READWRITE);
643
            if (ptr != NULL)
644
                return ptr;
645
        }
646
    }
647
    /* Fall back to regular pages */
648
#  endif
649
    return VirtualAlloc(NULL, size,
650
                        MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
651
#elif defined(ARENAS_USE_MMAP)
652
    void *ptr;
653
#  ifdef PYMALLOC_USE_HUGEPAGES
654
#    ifdef MAP_HUGETLB
655
    if (_PyRuntime.allocators.use_hugepages) {
656
        size_t hp_size = _pymalloc_system_hugepage_size();
657
        /* Only use huge pages if the arena size is a multiple of the
658
         * system's default huge page size.  When the arena is smaller
659
         * than the huge page, mmap still succeeds but silently
660
         * allocates an entire huge page; the subsequent munmap with
661
         * the smaller arena size then fails with EINVAL, leaking
662
         * all of that memory. */
663
        if (hp_size > 0 && size % hp_size == 0) {
664
            ptr = mmap(NULL, size, PROT_READ|PROT_WRITE,
665
                       MAP_PRIVATE|MAP_ANONYMOUS|MAP_HUGETLB, -1, 0);
666
            if (ptr != MAP_FAILED) {
667
                assert(ptr != NULL);
668
                (void)_PyAnnotateMemoryMap(ptr, size, "cpython:pymalloc:hugepage");
669
                return ptr;
670
            }
671
        }
672
    }
673
    /* Fall back to regular pages */
674
#    endif
675
#  endif
676
43.7k
    ptr = mmap(NULL, size, PROT_READ|PROT_WRITE,
677
43.7k
               MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
678
43.7k
    if (ptr == MAP_FAILED)
679
0
        return NULL;
680
43.7k
    assert(ptr != NULL);
681
43.7k
#ifdef MADV_HUGEPAGE
682
43.7k
    (void)madvise(ptr, size, MADV_HUGEPAGE);
683
43.7k
#endif
684
43.7k
    (void)_PyAnnotateMemoryMap(ptr, size, "cpython:pymalloc");
685
43.7k
    return ptr;
686
#else
687
    return malloc(size);
688
#endif
689
43.7k
}
690
691
void
692
_PyMem_ArenaFree(void *Py_UNUSED(ctx), void *ptr,
693
#if defined(ARENAS_USE_MMAP)
694
    size_t size
695
#else
696
    size_t Py_UNUSED(size)
697
#endif
698
)
699
43.5k
{
700
#ifdef MS_WINDOWS
701
    /* Unlike free(), VirtualFree() does not special-case NULL to noop. */
702
    if (ptr == NULL) {
703
        return;
704
    }
705
    VirtualFree(ptr, 0, MEM_RELEASE);
706
#elif defined(ARENAS_USE_MMAP)
707
    /* Unlike free(), munmap() does not special-case NULL to noop. */
708
43.5k
    if (ptr == NULL) {
709
0
        return;
710
0
    }
711
43.5k
    if (munmap(ptr, size) < 0) {
712
0
        _Py_FatalErrorFormat(__func__,
713
0
                             "munmap(%p, %zu) failed with errno %d",
714
0
                             ptr, size, errno);
715
0
    }
716
#else
717
    free(ptr);
718
#endif
719
43.5k
}
720
721
/*******************************************/
722
/* end low-level allocator implementations */
723
/*******************************************/
724
725
726
44
#define ALLOCATORS_MUTEX (_PyRuntime.allocators.mutex)
727
30.2M
#define _PyMem_Raw (_PyRuntime.allocators.standard.raw)
728
324M
#define _PyMem (_PyRuntime.allocators.standard.mem)
729
1.10G
#define _PyObject (_PyRuntime.allocators.standard.obj)
730
0
#define _PyMem_Debug (_PyRuntime.allocators.debug)
731
174k
#define _PyObject_Arena (_PyRuntime.allocators.obj_arena)
732
733
734
/***************************/
735
/* managing the allocators */
736
/***************************/
737
738
static int
739
set_default_allocator_unlocked(PyMemAllocatorDomain domain, int debug,
740
                               PyMemAllocatorEx *old_alloc)
741
0
{
742
0
    if (old_alloc != NULL) {
743
0
        get_allocator_unlocked(domain, old_alloc);
744
0
    }
745
746
747
0
    PyMemAllocatorEx new_alloc;
748
0
    switch(domain)
749
0
    {
750
0
    case PYMEM_DOMAIN_RAW:
751
0
        new_alloc = (PyMemAllocatorEx)PYRAW_ALLOC;
752
0
        break;
753
0
    case PYMEM_DOMAIN_MEM:
754
0
        new_alloc = (PyMemAllocatorEx)PYMEM_ALLOC;
755
0
        break;
756
0
    case PYMEM_DOMAIN_OBJ:
757
0
        new_alloc = (PyMemAllocatorEx)PYOBJ_ALLOC;
758
0
        break;
759
0
    default:
760
        /* unknown domain */
761
0
        return -1;
762
0
    }
763
0
    set_allocator_unlocked(domain, &new_alloc);
764
0
    if (debug) {
765
0
        set_up_debug_hooks_domain_unlocked(domain);
766
0
    }
767
0
    return 0;
768
0
}
769
770
771
#ifdef Py_DEBUG
772
static const int pydebug = 1;
773
#else
774
static const int pydebug = 0;
775
#endif
776
777
int
778
_PyMem_GetAllocatorName(const char *name, PyMemAllocatorName *allocator)
779
0
{
780
0
    if (name == NULL || *name == '\0') {
781
        /* PYTHONMALLOC is empty or is not set or ignored (-E/-I command line
782
           nameions): use default memory allocators */
783
0
        *allocator = PYMEM_ALLOCATOR_DEFAULT;
784
0
    }
785
0
    else if (strcmp(name, "default") == 0) {
786
0
        *allocator = PYMEM_ALLOCATOR_DEFAULT;
787
0
    }
788
0
    else if (strcmp(name, "debug") == 0) {
789
0
        *allocator = PYMEM_ALLOCATOR_DEBUG;
790
0
    }
791
0
#if defined(WITH_PYMALLOC) && !defined(Py_GIL_DISABLED)
792
0
    else if (strcmp(name, "pymalloc") == 0) {
793
0
        *allocator = PYMEM_ALLOCATOR_PYMALLOC;
794
0
    }
795
0
    else if (strcmp(name, "pymalloc_debug") == 0) {
796
0
        *allocator = PYMEM_ALLOCATOR_PYMALLOC_DEBUG;
797
0
    }
798
0
#endif
799
0
#ifdef WITH_MIMALLOC
800
0
    else if (strcmp(name, "mimalloc") == 0) {
801
0
        *allocator = PYMEM_ALLOCATOR_MIMALLOC;
802
0
    }
803
0
    else if (strcmp(name, "mimalloc_debug") == 0) {
804
0
        *allocator = PYMEM_ALLOCATOR_MIMALLOC_DEBUG;
805
0
    }
806
0
#endif
807
0
#ifndef Py_GIL_DISABLED
808
0
    else if (strcmp(name, "malloc") == 0) {
809
0
        *allocator = PYMEM_ALLOCATOR_MALLOC;
810
0
    }
811
0
    else if (strcmp(name, "malloc_debug") == 0) {
812
0
        *allocator = PYMEM_ALLOCATOR_MALLOC_DEBUG;
813
0
    }
814
0
#endif
815
0
    else {
816
        /* unknown allocator */
817
0
        return -1;
818
0
    }
819
0
    return 0;
820
0
}
821
822
823
static int
824
set_up_allocators_unlocked(PyMemAllocatorName allocator)
825
0
{
826
0
    switch (allocator) {
827
0
    case PYMEM_ALLOCATOR_NOT_SET:
828
        /* do nothing */
829
0
        break;
830
831
0
    case PYMEM_ALLOCATOR_DEFAULT:
832
0
        (void)set_default_allocator_unlocked(PYMEM_DOMAIN_RAW, pydebug, NULL);
833
0
        (void)set_default_allocator_unlocked(PYMEM_DOMAIN_MEM, pydebug, NULL);
834
0
        (void)set_default_allocator_unlocked(PYMEM_DOMAIN_OBJ, pydebug, NULL);
835
0
        _PyRuntime.allocators.is_debug_enabled = pydebug;
836
0
        break;
837
838
0
    case PYMEM_ALLOCATOR_DEBUG:
839
0
        (void)set_default_allocator_unlocked(PYMEM_DOMAIN_RAW, 1, NULL);
840
0
        (void)set_default_allocator_unlocked(PYMEM_DOMAIN_MEM, 1, NULL);
841
0
        (void)set_default_allocator_unlocked(PYMEM_DOMAIN_OBJ, 1, NULL);
842
0
        _PyRuntime.allocators.is_debug_enabled = 1;
843
0
        break;
844
845
0
#ifdef WITH_PYMALLOC
846
0
    case PYMEM_ALLOCATOR_PYMALLOC:
847
0
    case PYMEM_ALLOCATOR_PYMALLOC_DEBUG:
848
0
    {
849
0
        PyMemAllocatorEx malloc_alloc = MALLOC_ALLOC;
850
0
        set_allocator_unlocked(PYMEM_DOMAIN_RAW, &malloc_alloc);
851
852
0
        PyMemAllocatorEx pymalloc = PYMALLOC_ALLOC;
853
0
        set_allocator_unlocked(PYMEM_DOMAIN_MEM, &pymalloc);
854
0
        set_allocator_unlocked(PYMEM_DOMAIN_OBJ, &pymalloc);
855
856
0
        int is_debug = (allocator == PYMEM_ALLOCATOR_PYMALLOC_DEBUG);
857
0
        _PyRuntime.allocators.is_debug_enabled = is_debug;
858
0
        if (is_debug) {
859
0
            set_up_debug_hooks_unlocked();
860
0
        }
861
0
        break;
862
0
    }
863
0
#endif
864
0
#ifdef WITH_MIMALLOC
865
0
    case PYMEM_ALLOCATOR_MIMALLOC:
866
0
    case PYMEM_ALLOCATOR_MIMALLOC_DEBUG:
867
0
    {
868
0
        PyMemAllocatorEx malloc_alloc = MIMALLOC_RAWALLOC;
869
0
        set_allocator_unlocked(PYMEM_DOMAIN_RAW, &malloc_alloc);
870
871
0
        PyMemAllocatorEx pymalloc = MIMALLOC_ALLOC;
872
0
        set_allocator_unlocked(PYMEM_DOMAIN_MEM, &pymalloc);
873
874
0
        PyMemAllocatorEx objmalloc = MIMALLOC_OBJALLOC;
875
0
        set_allocator_unlocked(PYMEM_DOMAIN_OBJ, &objmalloc);
876
877
0
        int is_debug = (allocator == PYMEM_ALLOCATOR_MIMALLOC_DEBUG);
878
0
        _PyRuntime.allocators.is_debug_enabled = is_debug;
879
0
        if (is_debug) {
880
0
            set_up_debug_hooks_unlocked();
881
0
        }
882
883
0
        break;
884
0
    }
885
0
#endif
886
887
0
    case PYMEM_ALLOCATOR_MALLOC:
888
0
    case PYMEM_ALLOCATOR_MALLOC_DEBUG:
889
0
    {
890
0
        PyMemAllocatorEx malloc_alloc = MALLOC_ALLOC;
891
0
        set_allocator_unlocked(PYMEM_DOMAIN_RAW, &malloc_alloc);
892
0
        set_allocator_unlocked(PYMEM_DOMAIN_MEM, &malloc_alloc);
893
0
        set_allocator_unlocked(PYMEM_DOMAIN_OBJ, &malloc_alloc);
894
895
0
        int is_debug = (allocator == PYMEM_ALLOCATOR_MALLOC_DEBUG);
896
0
        _PyRuntime.allocators.is_debug_enabled = is_debug;
897
0
        if (is_debug) {
898
0
            set_up_debug_hooks_unlocked();
899
0
        }
900
0
        break;
901
0
    }
902
903
0
    default:
904
        /* unknown allocator */
905
0
        return -1;
906
0
    }
907
908
0
    return 0;
909
0
}
910
911
int
912
_PyMem_SetupAllocators(PyMemAllocatorName allocator)
913
0
{
914
0
    PyMutex_Lock(&ALLOCATORS_MUTEX);
915
0
    int res = set_up_allocators_unlocked(allocator);
916
0
    PyMutex_Unlock(&ALLOCATORS_MUTEX);
917
0
    return res;
918
0
}
919
920
921
static int
922
pymemallocator_eq(PyMemAllocatorEx *a, PyMemAllocatorEx *b)
923
0
{
924
0
    return (memcmp(a, b, sizeof(PyMemAllocatorEx)) == 0);
925
0
}
926
927
928
static const char*
929
get_current_allocator_name_unlocked(void)
930
0
{
931
0
    PyMemAllocatorEx malloc_alloc = MALLOC_ALLOC;
932
0
#ifdef WITH_PYMALLOC
933
0
    PyMemAllocatorEx pymalloc = PYMALLOC_ALLOC;
934
0
#endif
935
0
#ifdef WITH_MIMALLOC
936
0
    PyMemAllocatorEx mimalloc = MIMALLOC_ALLOC;
937
0
    PyMemAllocatorEx mimalloc_obj = MIMALLOC_OBJALLOC;
938
0
    PyMemAllocatorEx mimalloc_raw = MIMALLOC_RAWALLOC;
939
0
#endif
940
941
0
    if (pymemallocator_eq(&_PyMem_Raw, &malloc_alloc) &&
942
0
        pymemallocator_eq(&_PyMem, &malloc_alloc) &&
943
0
        pymemallocator_eq(&_PyObject, &malloc_alloc))
944
0
    {
945
0
        return "malloc";
946
0
    }
947
0
#ifdef WITH_PYMALLOC
948
0
    if (pymemallocator_eq(&_PyMem_Raw, &malloc_alloc) &&
949
0
        pymemallocator_eq(&_PyMem, &pymalloc) &&
950
0
        pymemallocator_eq(&_PyObject, &pymalloc))
951
0
    {
952
0
        return "pymalloc";
953
0
    }
954
0
#endif
955
0
#ifdef WITH_MIMALLOC
956
0
    if (pymemallocator_eq(&_PyMem_Raw, &mimalloc_raw) &&
957
0
        pymemallocator_eq(&_PyMem, &mimalloc) &&
958
0
        pymemallocator_eq(&_PyObject, &mimalloc_obj))
959
0
    {
960
0
        return "mimalloc";
961
0
    }
962
0
#endif
963
964
0
    PyMemAllocatorEx dbg_raw = PYDBGRAW_ALLOC;
965
0
    PyMemAllocatorEx dbg_mem = PYDBGMEM_ALLOC;
966
0
    PyMemAllocatorEx dbg_obj = PYDBGOBJ_ALLOC;
967
968
0
    if (pymemallocator_eq(&_PyMem_Raw, &dbg_raw) &&
969
0
        pymemallocator_eq(&_PyMem, &dbg_mem) &&
970
0
        pymemallocator_eq(&_PyObject, &dbg_obj))
971
0
    {
972
        /* Debug hooks installed */
973
0
        if (pymemallocator_eq(&_PyMem_Debug.raw.alloc, &malloc_alloc) &&
974
0
            pymemallocator_eq(&_PyMem_Debug.mem.alloc, &malloc_alloc) &&
975
0
            pymemallocator_eq(&_PyMem_Debug.obj.alloc, &malloc_alloc))
976
0
        {
977
0
            return "malloc_debug";
978
0
        }
979
0
#ifdef WITH_PYMALLOC
980
0
        if (pymemallocator_eq(&_PyMem_Debug.raw.alloc, &malloc_alloc) &&
981
0
            pymemallocator_eq(&_PyMem_Debug.mem.alloc, &pymalloc) &&
982
0
            pymemallocator_eq(&_PyMem_Debug.obj.alloc, &pymalloc))
983
0
        {
984
0
            return "pymalloc_debug";
985
0
        }
986
0
#endif
987
0
#ifdef WITH_MIMALLOC
988
0
        if (pymemallocator_eq(&_PyMem_Debug.raw.alloc, &mimalloc_raw) &&
989
0
            pymemallocator_eq(&_PyMem_Debug.mem.alloc, &mimalloc) &&
990
0
            pymemallocator_eq(&_PyMem_Debug.obj.alloc, &mimalloc_obj))
991
0
        {
992
0
            return "mimalloc_debug";
993
0
        }
994
0
#endif
995
0
    }
996
0
    return NULL;
997
0
}
998
999
const char*
1000
_PyMem_GetCurrentAllocatorName(void)
1001
0
{
1002
0
    PyMutex_Lock(&ALLOCATORS_MUTEX);
1003
0
    const char *name = get_current_allocator_name_unlocked();
1004
0
    PyMutex_Unlock(&ALLOCATORS_MUTEX);
1005
0
    return name;
1006
0
}
1007
1008
1009
int
1010
_PyMem_DebugEnabled(void)
1011
0
{
1012
0
    return _PyRuntime.allocators.is_debug_enabled;
1013
0
}
1014
1015
#ifdef WITH_PYMALLOC
1016
static int
1017
_PyMem_PymallocEnabled(void)
1018
0
{
1019
0
    if (_PyMem_DebugEnabled()) {
1020
0
        return (_PyMem_Debug.obj.alloc.malloc == _PyObject_Malloc);
1021
0
    }
1022
0
    else {
1023
0
        return (_PyObject.malloc == _PyObject_Malloc);
1024
0
    }
1025
0
}
1026
1027
#ifdef WITH_MIMALLOC
1028
static int
1029
_PyMem_MimallocEnabled(void)
1030
0
{
1031
#ifdef Py_GIL_DISABLED
1032
    return 1;
1033
#else
1034
0
    if (_PyMem_DebugEnabled()) {
1035
0
        return (_PyMem_Debug.obj.alloc.malloc == _PyObject_MiMalloc);
1036
0
    }
1037
0
    else {
1038
0
        return (_PyObject.malloc == _PyObject_MiMalloc);
1039
0
    }
1040
0
#endif
1041
0
}
1042
#endif  // WITH_MIMALLOC
1043
1044
#endif  // WITH_PYMALLOC
1045
1046
1047
static void
1048
set_up_debug_hooks_domain_unlocked(PyMemAllocatorDomain domain)
1049
0
{
1050
0
    PyMemAllocatorEx alloc;
1051
1052
0
    if (domain == PYMEM_DOMAIN_RAW) {
1053
0
        if (_PyMem_Raw.malloc == _PyMem_DebugRawMalloc) {
1054
0
            return;
1055
0
        }
1056
1057
0
        get_allocator_unlocked(domain, &_PyMem_Debug.raw.alloc);
1058
0
        alloc.ctx = &_PyMem_Debug.raw;
1059
0
        alloc.malloc = _PyMem_DebugRawMalloc;
1060
0
        alloc.calloc = _PyMem_DebugRawCalloc;
1061
0
        alloc.realloc = _PyMem_DebugRawRealloc;
1062
0
        alloc.free = _PyMem_DebugRawFree;
1063
0
        set_allocator_unlocked(domain, &alloc);
1064
0
    }
1065
0
    else if (domain == PYMEM_DOMAIN_MEM) {
1066
0
        if (_PyMem.malloc == _PyMem_DebugMalloc) {
1067
0
            return;
1068
0
        }
1069
1070
0
        get_allocator_unlocked(domain, &_PyMem_Debug.mem.alloc);
1071
0
        alloc.ctx = &_PyMem_Debug.mem;
1072
0
        alloc.malloc = _PyMem_DebugMalloc;
1073
0
        alloc.calloc = _PyMem_DebugCalloc;
1074
0
        alloc.realloc = _PyMem_DebugRealloc;
1075
0
        alloc.free = _PyMem_DebugFree;
1076
0
        set_allocator_unlocked(domain, &alloc);
1077
0
    }
1078
0
    else if (domain == PYMEM_DOMAIN_OBJ)  {
1079
0
        if (_PyObject.malloc == _PyMem_DebugMalloc) {
1080
0
            return;
1081
0
        }
1082
1083
0
        get_allocator_unlocked(domain, &_PyMem_Debug.obj.alloc);
1084
0
        alloc.ctx = &_PyMem_Debug.obj;
1085
0
        alloc.malloc = _PyMem_DebugMalloc;
1086
0
        alloc.calloc = _PyMem_DebugCalloc;
1087
0
        alloc.realloc = _PyMem_DebugRealloc;
1088
0
        alloc.free = _PyMem_DebugFree;
1089
0
        set_allocator_unlocked(domain, &alloc);
1090
0
    }
1091
0
}
1092
1093
1094
static void
1095
set_up_debug_hooks_unlocked(void)
1096
0
{
1097
0
    set_up_debug_hooks_domain_unlocked(PYMEM_DOMAIN_RAW);
1098
0
    set_up_debug_hooks_domain_unlocked(PYMEM_DOMAIN_MEM);
1099
0
    set_up_debug_hooks_domain_unlocked(PYMEM_DOMAIN_OBJ);
1100
0
    _PyRuntime.allocators.is_debug_enabled = 1;
1101
0
}
1102
1103
void
1104
PyMem_SetupDebugHooks(void)
1105
0
{
1106
0
    PyMutex_Lock(&ALLOCATORS_MUTEX);
1107
0
    set_up_debug_hooks_unlocked();
1108
0
    PyMutex_Unlock(&ALLOCATORS_MUTEX);
1109
0
}
1110
1111
static void
1112
get_allocator_unlocked(PyMemAllocatorDomain domain, PyMemAllocatorEx *allocator)
1113
22
{
1114
22
    switch(domain)
1115
22
    {
1116
22
    case PYMEM_DOMAIN_RAW: *allocator = _PyMem_Raw; break;
1117
0
    case PYMEM_DOMAIN_MEM: *allocator = _PyMem; break;
1118
0
    case PYMEM_DOMAIN_OBJ: *allocator = _PyObject; break;
1119
0
    default:
1120
        /* unknown domain: set all attributes to NULL */
1121
0
        allocator->ctx = NULL;
1122
0
        allocator->malloc = NULL;
1123
0
        allocator->calloc = NULL;
1124
0
        allocator->realloc = NULL;
1125
0
        allocator->free = NULL;
1126
22
    }
1127
22
}
1128
1129
static void
1130
set_allocator_unlocked(PyMemAllocatorDomain domain, PyMemAllocatorEx *allocator)
1131
0
{
1132
0
    switch(domain)
1133
0
    {
1134
0
    case PYMEM_DOMAIN_RAW: _PyMem_Raw = *allocator; break;
1135
0
    case PYMEM_DOMAIN_MEM: _PyMem = *allocator; break;
1136
0
    case PYMEM_DOMAIN_OBJ: _PyObject = *allocator; break;
1137
    /* ignore unknown domain */
1138
0
    }
1139
0
}
1140
1141
void
1142
PyMem_GetAllocator(PyMemAllocatorDomain domain, PyMemAllocatorEx *allocator)
1143
22
{
1144
22
    PyMutex_Lock(&ALLOCATORS_MUTEX);
1145
22
    get_allocator_unlocked(domain, allocator);
1146
22
    PyMutex_Unlock(&ALLOCATORS_MUTEX);
1147
22
}
1148
1149
void
1150
PyMem_SetAllocator(PyMemAllocatorDomain domain, PyMemAllocatorEx *allocator)
1151
0
{
1152
0
    PyMutex_Lock(&ALLOCATORS_MUTEX);
1153
0
    set_allocator_unlocked(domain, allocator);
1154
0
    PyMutex_Unlock(&ALLOCATORS_MUTEX);
1155
0
}
1156
1157
void
1158
PyObject_GetArenaAllocator(PyObjectArenaAllocator *allocator)
1159
0
{
1160
0
    PyMutex_Lock(&ALLOCATORS_MUTEX);
1161
0
    *allocator = _PyObject_Arena;
1162
0
    PyMutex_Unlock(&ALLOCATORS_MUTEX);
1163
0
}
1164
1165
void
1166
PyObject_SetArenaAllocator(PyObjectArenaAllocator *allocator)
1167
0
{
1168
0
    PyMutex_Lock(&ALLOCATORS_MUTEX);
1169
0
    _PyObject_Arena = *allocator;
1170
0
    PyMutex_Unlock(&ALLOCATORS_MUTEX);
1171
0
}
1172
1173
1174
/* Note that there is a possible, but very unlikely, race in any place
1175
 * below where we call one of the allocator functions.  We access two
1176
 * fields in each case:  "malloc", etc. and "ctx".
1177
 *
1178
 * It is unlikely that the allocator will be changed while one of those
1179
 * calls is happening, much less in that very narrow window.
1180
 * Furthermore, the likelihood of a race is drastically reduced by the
1181
 * fact that the allocator may not be changed after runtime init
1182
 * (except with a wrapper).
1183
 *
1184
 * With the above in mind, we currently don't worry about locking
1185
 * around these uses of the runtime-global allocators state. */
1186
1187
1188
/*************************/
1189
/* the "arena" allocator */
1190
/*************************/
1191
1192
void *
1193
_PyObject_VirtualAlloc(size_t size)
1194
35.9k
{
1195
35.9k
    size_t alloc_size = _pymalloc_virtual_alloc_size(size);
1196
35.9k
    if (alloc_size == 0 && size != 0) {
1197
0
        return NULL;
1198
0
    }
1199
35.9k
    return _PyObject_Arena.alloc(_PyObject_Arena.ctx, alloc_size);
1200
35.9k
}
1201
1202
void
1203
_PyObject_VirtualFree(void *obj, size_t size)
1204
35.8k
{
1205
35.8k
    size_t alloc_size = _pymalloc_virtual_alloc_size(size);
1206
35.8k
    assert(alloc_size != 0 || size == 0);
1207
35.8k
    _PyObject_Arena.free(_PyObject_Arena.ctx, obj, alloc_size);
1208
35.8k
}
1209
1210
1211
/***********************/
1212
/* the "raw" allocator */
1213
/***********************/
1214
1215
void *
1216
PyMem_RawMalloc(size_t size)
1217
3.30M
{
1218
    /*
1219
     * Limit ourselves to PY_SSIZE_T_MAX bytes to prevent security holes.
1220
     * Most python internals blindly use a signed Py_ssize_t to track
1221
     * things without checking for overflows or negatives.
1222
     * As size_t is unsigned, checking for size < 0 is not required.
1223
     */
1224
3.30M
    if (size > (size_t)PY_SSIZE_T_MAX)
1225
0
        return NULL;
1226
3.30M
    return _PyMem_Raw.malloc(_PyMem_Raw.ctx, size);
1227
3.30M
}
1228
1229
void *
1230
PyMem_RawCalloc(size_t nelem, size_t elsize)
1231
957k
{
1232
    /* see PyMem_RawMalloc() */
1233
957k
    if (elsize != 0 && nelem > (size_t)PY_SSIZE_T_MAX / elsize)
1234
0
        return NULL;
1235
957k
    return _PyMem_Raw.calloc(_PyMem_Raw.ctx, nelem, elsize);
1236
957k
}
1237
1238
void*
1239
PyMem_RawRealloc(void *ptr, size_t new_size)
1240
6.65M
{
1241
    /* see PyMem_RawMalloc() */
1242
6.65M
    if (new_size > (size_t)PY_SSIZE_T_MAX)
1243
0
        return NULL;
1244
6.65M
    return _PyMem_Raw.realloc(_PyMem_Raw.ctx, ptr, new_size);
1245
6.65M
}
1246
1247
void PyMem_RawFree(void *ptr)
1248
4.21M
{
1249
4.21M
    _PyMem_Raw.free(_PyMem_Raw.ctx, ptr);
1250
4.21M
}
1251
1252
1253
/***********************/
1254
/* the "mem" allocator */
1255
/***********************/
1256
1257
void *
1258
PyMem_Malloc(size_t size)
1259
51.1M
{
1260
    /* see PyMem_RawMalloc() */
1261
51.1M
    if (size > (size_t)PY_SSIZE_T_MAX)
1262
0
        return NULL;
1263
51.1M
    OBJECT_STAT_INC_COND(allocations512, size < 512);
1264
51.1M
    OBJECT_STAT_INC_COND(allocations4k, size >= 512 && size < 4094);
1265
51.1M
    OBJECT_STAT_INC_COND(allocations_big, size >= 4094);
1266
51.1M
    OBJECT_STAT_INC(allocations);
1267
51.1M
    return _PyMem.malloc(_PyMem.ctx, size);
1268
51.1M
}
1269
1270
void *
1271
PyMem_Calloc(size_t nelem, size_t elsize)
1272
10.3M
{
1273
    /* see PyMem_RawMalloc() */
1274
10.3M
    if (elsize != 0 && nelem > (size_t)PY_SSIZE_T_MAX / elsize)
1275
0
        return NULL;
1276
10.3M
    OBJECT_STAT_INC_COND(allocations512, elsize < 512);
1277
10.3M
    OBJECT_STAT_INC_COND(allocations4k, elsize >= 512 && elsize < 4094);
1278
10.3M
    OBJECT_STAT_INC_COND(allocations_big, elsize >= 4094);
1279
10.3M
    OBJECT_STAT_INC(allocations);
1280
10.3M
    return _PyMem.calloc(_PyMem.ctx, nelem, elsize);
1281
10.3M
}
1282
1283
void *
1284
PyMem_Realloc(void *ptr, size_t new_size)
1285
19.6M
{
1286
    /* see PyMem_RawMalloc() */
1287
19.6M
    if (new_size > (size_t)PY_SSIZE_T_MAX)
1288
0
        return NULL;
1289
19.6M
    return _PyMem.realloc(_PyMem.ctx, ptr, new_size);
1290
19.6M
}
1291
1292
void
1293
PyMem_Free(void *ptr)
1294
81.0M
{
1295
81.0M
    OBJECT_STAT_INC(frees);
1296
81.0M
    _PyMem.free(_PyMem.ctx, ptr);
1297
81.0M
}
1298
1299
1300
/***************************/
1301
/* pymem utility functions */
1302
/***************************/
1303
1304
wchar_t*
1305
_PyMem_RawWcsdup(const wchar_t *str)
1306
902
{
1307
902
    assert(str != NULL);
1308
1309
902
    size_t len = wcslen(str);
1310
902
    if (len > (size_t)PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
1311
0
        return NULL;
1312
0
    }
1313
1314
902
    size_t size = (len + 1) * sizeof(wchar_t);
1315
902
    wchar_t *str2 = PyMem_RawMalloc(size);
1316
902
    if (str2 == NULL) {
1317
0
        return NULL;
1318
0
    }
1319
1320
902
    memcpy(str2, str, size);
1321
902
    return str2;
1322
902
}
1323
1324
char *
1325
_PyMem_RawStrdup(const char *str)
1326
88
{
1327
88
    assert(str != NULL);
1328
88
    size_t size = strlen(str) + 1;
1329
88
    char *copy = PyMem_RawMalloc(size);
1330
88
    if (copy == NULL) {
1331
0
        return NULL;
1332
0
    }
1333
88
    memcpy(copy, str, size);
1334
88
    return copy;
1335
88
}
1336
1337
char *
1338
_PyMem_Strdup(const char *str)
1339
2
{
1340
2
    assert(str != NULL);
1341
2
    size_t size = strlen(str) + 1;
1342
2
    char *copy = PyMem_Malloc(size);
1343
2
    if (copy == NULL) {
1344
0
        return NULL;
1345
0
    }
1346
2
    memcpy(copy, str, size);
1347
2
    return copy;
1348
2
}
1349
1350
/***********************************************/
1351
/* Delayed freeing support for Py_GIL_DISABLED */
1352
/***********************************************/
1353
1354
// So that sizeof(struct _mem_work_chunk) is 4096 bytes on 64-bit platforms.
1355
#define WORK_ITEMS_PER_CHUNK 254
1356
1357
// A pointer to be freed once the QSBR read sequence reaches qsbr_goal.
1358
struct _mem_work_item {
1359
    uintptr_t ptr; // lowest bit tagged 1 for objects freed with PyObject_Free
1360
    uint64_t qsbr_goal;
1361
};
1362
1363
// A fixed-size buffer of pointers to be freed
1364
struct _mem_work_chunk {
1365
    // Linked list node of chunks in queue
1366
    struct llist_node node;
1367
1368
    Py_ssize_t rd_idx;  // index of next item to read
1369
    Py_ssize_t wr_idx;  // index of next item to write
1370
    struct _mem_work_item array[WORK_ITEMS_PER_CHUNK];
1371
};
1372
1373
static int
1374
work_item_should_decref(uintptr_t ptr)
1375
3.42k
{
1376
3.42k
    return ptr & 0x01;
1377
3.42k
}
1378
1379
static void
1380
free_work_item(uintptr_t ptr, delayed_dealloc_cb cb, void *state)
1381
3.42k
{
1382
3.42k
    if (work_item_should_decref(ptr)) {
1383
0
        PyObject *obj = (PyObject *)(ptr - 1);
1384
#ifdef Py_GIL_DISABLED
1385
        if (cb == NULL) {
1386
            assert(!_PyInterpreterState_GET()->stoptheworld.world_stopped);
1387
            Py_DECREF(obj);
1388
            return;
1389
        }
1390
        assert(_PyInterpreterState_GET()->stoptheworld.world_stopped);
1391
        if (_Py_IsImmortal(obj)) {
1392
            // The object may have become immortal after it was queued.
1393
            return;
1394
        }
1395
        Py_ssize_t refcount = _Py_ExplicitMergeRefcount(obj, -1);
1396
        if (refcount == 0) {
1397
            cb(obj, state);
1398
        }
1399
#else
1400
0
        Py_DECREF(obj);
1401
0
#endif
1402
0
    }
1403
3.42k
    else {
1404
3.42k
        PyMem_Free((void *)ptr);
1405
3.42k
    }
1406
3.42k
}
1407
1408
1409
#ifdef Py_GIL_DISABLED
1410
1411
// For deferred advance on free: the number of deferred items before advancing
1412
// the write sequence.  This is based on WORK_ITEMS_PER_CHUNK.  We ideally
1413
// want to process a chunk before it overflows.
1414
#define QSBR_DEFERRED_LIMIT 127
1415
1416
// If the deferred memory exceeds 1 MiB, advance the write sequence.  This
1417
// helps limit memory usage due to QSBR delaying frees too long.
1418
#define QSBR_FREE_MEM_LIMIT 1024*1024
1419
1420
// Return true if the global write sequence should be advanced for a deferred
1421
// memory free.
1422
static bool
1423
should_advance_qsbr_for_free(struct _qsbr_thread_state *qsbr, size_t size)
1424
{
1425
    if (size > QSBR_FREE_MEM_LIMIT) {
1426
        qsbr->deferred_count = 0;
1427
        qsbr->deferred_memory = 0;
1428
        _Py_set_eval_breaker_bit(qsbr->tstate, _PY_EVAL_PROCESS_DELAYED_BIT);
1429
        return true;
1430
    }
1431
    qsbr->deferred_count++;
1432
    qsbr->deferred_memory += size;
1433
    if (qsbr->deferred_count > QSBR_DEFERRED_LIMIT ||
1434
            qsbr->deferred_memory > QSBR_FREE_MEM_LIMIT) {
1435
        qsbr->deferred_count = 0;
1436
        qsbr->deferred_memory = 0;
1437
        _Py_set_eval_breaker_bit(qsbr->tstate, _PY_EVAL_PROCESS_DELAYED_BIT);
1438
        return true;
1439
    }
1440
    return false;
1441
}
1442
#endif
1443
1444
static void
1445
free_delayed(uintptr_t ptr, size_t size)
1446
3.42k
{
1447
3.42k
#ifndef Py_GIL_DISABLED
1448
3.42k
    free_work_item(ptr, NULL, NULL);
1449
#else
1450
    PyInterpreterState *interp = _PyInterpreterState_GET();
1451
    if (_PyInterpreterState_GetFinalizing(interp) != NULL ||
1452
        interp->stoptheworld.world_stopped)
1453
    {
1454
        // Free immediately during interpreter shutdown or if the world is
1455
        // stopped.
1456
        assert(!interp->stoptheworld.world_stopped || !work_item_should_decref(ptr));
1457
        free_work_item(ptr, NULL, NULL);
1458
        return;
1459
    }
1460
1461
    _PyThreadStateImpl *tstate = (_PyThreadStateImpl *)_PyThreadState_GET();
1462
    struct llist_node *head = &tstate->mem_free_queue;
1463
1464
    struct _mem_work_chunk *buf = NULL;
1465
    if (!llist_empty(head)) {
1466
        // Try to re-use the last buffer
1467
        buf = llist_data(head->prev, struct _mem_work_chunk, node);
1468
        if (buf->wr_idx == WORK_ITEMS_PER_CHUNK) {
1469
            // already full
1470
            buf = NULL;
1471
        }
1472
    }
1473
1474
    if (buf == NULL) {
1475
        buf = PyMem_Calloc(1, sizeof(*buf));
1476
        if (buf != NULL) {
1477
            llist_insert_tail(head, &buf->node);
1478
        }
1479
    }
1480
1481
    if (buf == NULL) {
1482
        // failed to allocate a buffer, free immediately
1483
        PyObject *to_dealloc = NULL;
1484
        _PyEval_StopTheWorld(tstate->base.interp);
1485
        if (work_item_should_decref(ptr)) {
1486
            PyObject *obj = (PyObject *)(ptr - 1);
1487
            if (!_Py_IsImmortal(obj)) {
1488
                Py_ssize_t refcount = _Py_ExplicitMergeRefcount(obj, -1);
1489
                if (refcount == 0) {
1490
                    to_dealloc = obj;
1491
                }
1492
            }
1493
        }
1494
        else {
1495
            PyMem_Free((void *)ptr);
1496
        }
1497
        _PyEval_StartTheWorld(tstate->base.interp);
1498
        if (to_dealloc != NULL) {
1499
            _Py_Dealloc(to_dealloc);
1500
        }
1501
        return;
1502
    }
1503
1504
    assert(buf != NULL && buf->wr_idx < WORK_ITEMS_PER_CHUNK);
1505
    uint64_t seq;
1506
    if (should_advance_qsbr_for_free(tstate->qsbr, size)) {
1507
        seq = _Py_qsbr_advance(tstate->qsbr->shared);
1508
    }
1509
    else {
1510
        seq = _Py_qsbr_shared_next(tstate->qsbr->shared);
1511
    }
1512
    buf->array[buf->wr_idx].ptr = ptr;
1513
    buf->array[buf->wr_idx].qsbr_goal = seq;
1514
    buf->wr_idx++;
1515
#endif
1516
3.42k
}
1517
1518
void
1519
_PyMem_FreeDelayed(void *ptr, size_t size)
1520
3.42k
{
1521
3.42k
    assert(!((uintptr_t)ptr & 0x01));
1522
3.42k
    if (ptr != NULL) {
1523
3.42k
        free_delayed((uintptr_t)ptr, size);
1524
3.42k
    }
1525
3.42k
}
1526
1527
#ifdef Py_GIL_DISABLED
1528
void
1529
_PyObject_XDecRefDelayed(PyObject *ptr)
1530
{
1531
    assert(!((uintptr_t)ptr & 0x01));
1532
    if (ptr != NULL && !_Py_IsImmortal(ptr)) {
1533
        // We use 0 as the size since we don't have an easy way to know the
1534
        // actual size.  If we are freeing many objects, the write sequence
1535
        // will be advanced due to QSBR_DEFERRED_LIMIT.
1536
        free_delayed(((uintptr_t)ptr)|0x01, 0);
1537
    }
1538
}
1539
#endif
1540
1541
#ifdef Py_GIL_DISABLED
1542
void
1543
_PyObject_XSetRefDelayed(PyObject **ptr, PyObject *value)
1544
{
1545
    PyObject *old = *ptr;
1546
    FT_ATOMIC_STORE_PTR_RELEASE(*ptr, value);
1547
    _PyObject_XDecRefDelayed(old);
1548
}
1549
#endif
1550
1551
static struct _mem_work_chunk *
1552
work_queue_first(struct llist_node *head)
1553
0
{
1554
0
    return llist_data(head->next, struct _mem_work_chunk, node);
1555
0
}
1556
1557
static void
1558
process_queue(struct llist_node *head, _PyThreadStateImpl *tstate,
1559
              bool keep_empty, delayed_dealloc_cb cb, void *state)
1560
0
{
1561
0
    while (!llist_empty(head)) {
1562
0
        struct _mem_work_chunk *buf = work_queue_first(head);
1563
1564
0
        if (buf->rd_idx < buf->wr_idx) {
1565
0
            struct _mem_work_item *item = &buf->array[buf->rd_idx];
1566
0
            if (!_Py_qsbr_poll(tstate->qsbr, item->qsbr_goal)) {
1567
0
                return;
1568
0
            }
1569
1570
0
            buf->rd_idx++;
1571
            // NB: free_work_item may re-enter or execute arbitrary code
1572
0
            free_work_item(item->ptr, cb, state);
1573
0
            continue;
1574
0
        }
1575
1576
0
        assert(buf->rd_idx == buf->wr_idx);
1577
0
        if (keep_empty && buf->node.next == head) {
1578
            // Keep the last buffer in the queue to reduce re-allocations
1579
0
            buf->rd_idx = buf->wr_idx = 0;
1580
0
            return;
1581
0
        }
1582
1583
0
        llist_remove(&buf->node);
1584
0
        PyMem_Free(buf);
1585
0
    }
1586
0
}
1587
1588
static void
1589
process_interp_queue(struct _Py_mem_interp_free_queue *queue,
1590
                     _PyThreadStateImpl *tstate, delayed_dealloc_cb cb,
1591
                     void *state)
1592
0
{
1593
0
    assert(PyMutex_IsLocked(&queue->mutex));
1594
0
    process_queue(&queue->head, tstate, false, cb, state);
1595
1596
0
    int more_work = !llist_empty(&queue->head);
1597
0
    _Py_atomic_store_int_relaxed(&queue->has_work, more_work);
1598
0
}
1599
1600
static void
1601
maybe_process_interp_queue(struct _Py_mem_interp_free_queue *queue,
1602
                           _PyThreadStateImpl *tstate, delayed_dealloc_cb cb,
1603
                           void *state)
1604
0
{
1605
0
    if (!_Py_atomic_load_int_relaxed(&queue->has_work)) {
1606
0
        return;
1607
0
    }
1608
1609
    // Try to acquire the lock, but don't block if it's already held.
1610
0
    if (_PyMutex_LockTimed(&queue->mutex, 0, 0) == PY_LOCK_ACQUIRED) {
1611
0
        process_interp_queue(queue, tstate, cb, state);
1612
0
        PyMutex_Unlock(&queue->mutex);
1613
0
    }
1614
0
}
1615
1616
void
1617
_PyMem_ProcessDelayed(PyThreadState *tstate)
1618
0
{
1619
0
    PyInterpreterState *interp = tstate->interp;
1620
0
    _PyThreadStateImpl *tstate_impl = (_PyThreadStateImpl *)tstate;
1621
1622
0
    _Py_unset_eval_breaker_bit(tstate, _PY_EVAL_PROCESS_DELAYED_BIT);
1623
1624
    // Process thread-local work
1625
0
    process_queue(&tstate_impl->mem_free_queue, tstate_impl, true, NULL, NULL);
1626
1627
    // Process shared interpreter work
1628
0
    maybe_process_interp_queue(&interp->mem_free_queue, tstate_impl, NULL, NULL);
1629
0
}
1630
1631
void
1632
_PyMem_ProcessDelayedNoDealloc(PyThreadState *tstate, delayed_dealloc_cb cb, void *state)
1633
0
{
1634
0
    PyInterpreterState *interp = tstate->interp;
1635
0
    _PyThreadStateImpl *tstate_impl = (_PyThreadStateImpl *)tstate;
1636
1637
    // Process thread-local work
1638
0
    process_queue(&tstate_impl->mem_free_queue, tstate_impl, true, cb, state);
1639
1640
    // Process shared interpreter work
1641
0
    maybe_process_interp_queue(&interp->mem_free_queue, tstate_impl, cb, state);
1642
0
}
1643
1644
void
1645
_PyMem_AbandonDelayed(PyThreadState *tstate)
1646
0
{
1647
0
    PyInterpreterState *interp = tstate->interp;
1648
0
    struct llist_node *queue = &((_PyThreadStateImpl *)tstate)->mem_free_queue;
1649
1650
0
    if (llist_empty(queue)) {
1651
0
        return;
1652
0
    }
1653
1654
    // Check if the queue contains one empty buffer
1655
0
    struct _mem_work_chunk *buf = work_queue_first(queue);
1656
0
    if (buf->rd_idx == buf->wr_idx) {
1657
0
        llist_remove(&buf->node);
1658
0
        PyMem_Free(buf);
1659
0
        assert(llist_empty(queue));
1660
0
        return;
1661
0
    }
1662
1663
0
    PyMutex_Lock(&interp->mem_free_queue.mutex);
1664
1665
    // Merge the thread's work queue into the interpreter's work queue.
1666
0
    llist_concat(&interp->mem_free_queue.head, queue);
1667
1668
    // Process the merged queue now (see gh-130794).
1669
0
    _PyThreadStateImpl *this_tstate = (_PyThreadStateImpl *)_PyThreadState_GET();
1670
0
    process_interp_queue(&interp->mem_free_queue, this_tstate, NULL, NULL);
1671
1672
0
    PyMutex_Unlock(&interp->mem_free_queue.mutex);
1673
1674
0
    assert(llist_empty(queue));  // the thread's queue is now empty
1675
0
}
1676
1677
void
1678
_PyMem_FiniDelayed(PyInterpreterState *interp)
1679
0
{
1680
0
    struct llist_node *head = &interp->mem_free_queue.head;
1681
0
    while (!llist_empty(head)) {
1682
0
        struct _mem_work_chunk *buf = work_queue_first(head);
1683
1684
0
        if (buf->rd_idx < buf->wr_idx) {
1685
            // Free the remaining items immediately. There should be no other
1686
            // threads accessing the memory at this point during shutdown.
1687
0
            struct _mem_work_item *item = &buf->array[buf->rd_idx];
1688
0
            buf->rd_idx++;
1689
            // NB: free_work_item may re-enter or execute arbitrary code
1690
0
            free_work_item(item->ptr, NULL, NULL);
1691
0
            continue;
1692
0
        }
1693
1694
0
        llist_remove(&buf->node);
1695
0
        PyMem_Free(buf);
1696
0
    }
1697
0
}
1698
1699
/**************************/
1700
/* the "object" allocator */
1701
/**************************/
1702
1703
void *
1704
PyObject_Malloc(size_t size)
1705
272M
{
1706
    /* see PyMem_RawMalloc() */
1707
272M
    if (size > (size_t)PY_SSIZE_T_MAX)
1708
0
        return NULL;
1709
272M
    OBJECT_STAT_INC_COND(allocations512, size < 512);
1710
272M
    OBJECT_STAT_INC_COND(allocations4k, size >= 512 && size < 4094);
1711
272M
    OBJECT_STAT_INC_COND(allocations_big, size >= 4094);
1712
272M
    OBJECT_STAT_INC(allocations);
1713
272M
    return _PyObject.malloc(_PyObject.ctx, size);
1714
272M
}
1715
1716
void *
1717
PyObject_Calloc(size_t nelem, size_t elsize)
1718
0
{
1719
    /* see PyMem_RawMalloc() */
1720
0
    if (elsize != 0 && nelem > (size_t)PY_SSIZE_T_MAX / elsize)
1721
0
        return NULL;
1722
0
    OBJECT_STAT_INC_COND(allocations512, elsize < 512);
1723
0
    OBJECT_STAT_INC_COND(allocations4k, elsize >= 512 && elsize < 4094);
1724
0
    OBJECT_STAT_INC_COND(allocations_big, elsize >= 4094);
1725
0
    OBJECT_STAT_INC(allocations);
1726
0
    return _PyObject.calloc(_PyObject.ctx, nelem, elsize);
1727
0
}
1728
1729
void *
1730
PyObject_Realloc(void *ptr, size_t new_size)
1731
10.1M
{
1732
    /* see PyMem_RawMalloc() */
1733
10.1M
    if (new_size > (size_t)PY_SSIZE_T_MAX)
1734
0
        return NULL;
1735
10.1M
    return _PyObject.realloc(_PyObject.ctx, ptr, new_size);
1736
10.1M
}
1737
1738
void
1739
PyObject_Free(void *ptr)
1740
271M
{
1741
271M
    OBJECT_STAT_INC(frees);
1742
271M
    _PyObject.free(_PyObject.ctx, ptr);
1743
271M
}
1744
1745
1746
/* Use __builtin_expect() where available to reduce overhead of
1747
   the valgrind checks */
1748
#if (defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 2))) && defined(__OPTIMIZE__)
1749
2.29G
#  define UNLIKELY(value) __builtin_expect((value), 0)
1750
1.04G
#  define LIKELY(value) __builtin_expect((value), 1)
1751
#else
1752
#  define UNLIKELY(value) (value)
1753
#  define LIKELY(value) (value)
1754
#endif
1755
1756
#ifdef WITH_PYMALLOC
1757
1758
#ifdef WITH_VALGRIND
1759
#include <valgrind/valgrind.h>
1760
1761
/* -1 indicates that we haven't checked that we're running on valgrind yet. */
1762
static int running_on_valgrind = -1;
1763
#endif
1764
1765
typedef struct _obmalloc_state OMState;
1766
1767
/* obmalloc state for main interpreter and shared by all interpreters without
1768
 * their own obmalloc state.  By not explicitly initializing this structure, it
1769
 * will be allocated in the BSS which is a small performance win.  The radix
1770
 * tree arrays are fairly large but are sparsely used.  */
1771
static struct _obmalloc_state obmalloc_state_main;
1772
static bool obmalloc_state_initialized;
1773
1774
static inline int
1775
has_own_state(PyInterpreterState *interp)
1776
0
{
1777
0
    return (_Py_IsMainInterpreter(interp) ||
1778
0
            !(interp->feature_flags & Py_RTFLAGS_USE_MAIN_OBMALLOC) ||
1779
0
            _Py_IsMainInterpreterFinalizing(interp));
1780
0
}
1781
1782
static inline OMState *
1783
get_state(void)
1784
722M
{
1785
722M
    PyInterpreterState *interp = _PyInterpreterState_GET();
1786
722M
    assert(interp->obmalloc != NULL); // otherwise not initialized or freed
1787
722M
    return interp->obmalloc;
1788
722M
}
1789
1790
// These macros all rely on a local "state" variable.
1791
363M
#define usedpools (state->pools.used)
1792
1.53M
#define allarenas (state->mgmt.arenas)
1793
182
#define maxarenas (state->mgmt.maxarenas)
1794
38.8k
#define unused_arena_objects (state->mgmt.unused_arena_objects)
1795
11.0M
#define usable_arenas (state->mgmt.usable_arenas)
1796
6.97M
#define nfp2lasta (state->mgmt.nfp2lasta)
1797
23.8k
#define narenas_currently_allocated (state->mgmt.narenas_currently_allocated)
1798
7.82k
#define ntimes_arena_allocated (state->mgmt.ntimes_arena_allocated)
1799
8.33k
#define narenas_highwater (state->mgmt.narenas_highwater)
1800
8.38M
#define raw_allocated_blocks (state->mgmt.raw_allocated_blocks)
1801
1802
#ifdef WITH_MIMALLOC
1803
static bool count_blocks(
1804
    const mi_heap_t* heap, const mi_heap_area_t* area,
1805
    void* block, size_t block_size, void* allocated_blocks)
1806
0
{
1807
0
    *(size_t *)allocated_blocks += area->used;
1808
0
    return 1;
1809
0
}
1810
1811
static Py_ssize_t
1812
get_mimalloc_allocated_blocks(PyInterpreterState *interp)
1813
0
{
1814
0
    size_t allocated_blocks = 0;
1815
#ifdef Py_GIL_DISABLED
1816
    _Py_FOR_EACH_TSTATE_UNLOCKED(interp, t) {
1817
        _PyThreadStateImpl *tstate = (_PyThreadStateImpl *)t;
1818
        for (int i = 0; i < _Py_MIMALLOC_HEAP_COUNT; i++) {
1819
            mi_heap_t *heap = &tstate->mimalloc.heaps[i];
1820
            mi_heap_visit_blocks(heap, false, &count_blocks, &allocated_blocks);
1821
        }
1822
    }
1823
1824
    mi_subproc_t *subproc = interp->mimalloc.subproc;
1825
    for (int tag = 0; tag < _Py_MIMALLOC_HEAP_COUNT; tag++) {
1826
        mi_abandoned_visit_blocks(subproc, tag, false, &count_blocks,
1827
                                  &allocated_blocks);
1828
    }
1829
#else
1830
    // TODO(sgross): this only counts the current thread's blocks.
1831
0
    mi_heap_t *heap = mi_heap_get_default();
1832
0
    mi_heap_visit_blocks(heap, false, &count_blocks, &allocated_blocks);
1833
0
#endif
1834
0
    return allocated_blocks;
1835
0
}
1836
#endif
1837
1838
Py_ssize_t
1839
_PyInterpreterState_GetAllocatedBlocks(PyInterpreterState *interp)
1840
0
{
1841
0
#ifdef WITH_MIMALLOC
1842
0
    if (_PyMem_MimallocEnabled()) {
1843
0
        return get_mimalloc_allocated_blocks(interp);
1844
0
    }
1845
0
#endif
1846
1847
#ifdef Py_DEBUG
1848
    assert(has_own_state(interp));
1849
#else
1850
0
    if (!has_own_state(interp)) {
1851
0
        _Py_FatalErrorFunc(__func__,
1852
0
                           "the interpreter doesn't have its own allocator");
1853
0
    }
1854
0
#endif
1855
0
    OMState *state = interp->obmalloc;
1856
1857
0
    if (state == NULL) {
1858
0
        return 0;
1859
0
    }
1860
1861
0
    Py_ssize_t n = raw_allocated_blocks;
1862
    /* add up allocated blocks for used pools */
1863
0
    for (uint i = 0; i < maxarenas; ++i) {
1864
        /* Skip arenas which are not allocated. */
1865
0
        if (allarenas[i].address == 0) {
1866
0
            continue;
1867
0
        }
1868
1869
0
        uintptr_t base = (uintptr_t)_Py_ALIGN_UP(allarenas[i].address, POOL_SIZE);
1870
1871
        /* visit every pool in the arena */
1872
0
        assert(base <= (uintptr_t) allarenas[i].pool_address);
1873
0
        for (; base < (uintptr_t) allarenas[i].pool_address; base += POOL_SIZE) {
1874
0
            poolp p = (poolp)base;
1875
0
            n += p->ref.count;
1876
0
        }
1877
0
    }
1878
0
    return n;
1879
0
}
1880
1881
static void free_obmalloc_arenas(PyInterpreterState *interp);
1882
1883
void
1884
_PyInterpreterState_FinalizeAllocatedBlocks(PyInterpreterState *interp)
1885
0
{
1886
0
#ifdef WITH_MIMALLOC
1887
0
    if (_PyMem_MimallocEnabled()) {
1888
0
        Py_ssize_t leaked = _PyInterpreterState_GetAllocatedBlocks(interp);
1889
0
        interp->runtime->obmalloc.interpreter_leaks += leaked;
1890
0
        return;
1891
0
    }
1892
0
#endif
1893
0
    if (has_own_state(interp) && interp->obmalloc != NULL) {
1894
0
        Py_ssize_t leaked = _PyInterpreterState_GetAllocatedBlocks(interp);
1895
0
        assert(has_own_state(interp) || leaked == 0);
1896
0
        interp->runtime->obmalloc.interpreter_leaks += leaked;
1897
0
        if (_PyMem_obmalloc_state_on_heap(interp) && leaked == 0) {
1898
            // free the obmalloc arenas and radix tree nodes.  If leaked > 0
1899
            // then some of the memory allocated by obmalloc has not been
1900
            // freed.  It might be safe to free the arenas in that case but
1901
            // it's possible that extension modules are still using that
1902
            // memory.  So, it is safer to not free and to leak.  Perhaps there
1903
            // should be warning when this happens.  It should be possible to
1904
            // use a tool like "-fsanitize=address" to track down these leaks.
1905
0
            free_obmalloc_arenas(interp);
1906
0
        }
1907
0
    }
1908
0
}
1909
1910
static Py_ssize_t get_num_global_allocated_blocks(_PyRuntimeState *);
1911
1912
/* We preserve the number of blocks leaked during runtime finalization,
1913
   so they can be reported if the runtime is initialized again. */
1914
// XXX We don't lose any information by dropping this,
1915
// so we should consider doing so.
1916
static Py_ssize_t last_final_leaks = 0;
1917
1918
void
1919
_Py_FinalizeAllocatedBlocks(_PyRuntimeState *runtime)
1920
0
{
1921
0
    last_final_leaks = get_num_global_allocated_blocks(runtime);
1922
0
    runtime->obmalloc.interpreter_leaks = 0;
1923
0
}
1924
1925
static Py_ssize_t
1926
get_num_global_allocated_blocks(_PyRuntimeState *runtime)
1927
0
{
1928
0
    Py_ssize_t total = 0;
1929
0
    if (_PyRuntimeState_GetFinalizing(runtime) != NULL) {
1930
0
        PyInterpreterState *interp = _PyInterpreterState_Main();
1931
0
        if (interp == NULL) {
1932
            /* We are at the very end of runtime finalization.
1933
               We can't rely on finalizing->interp since that thread
1934
               state is probably already freed, so we don't worry
1935
               about it. */
1936
0
            assert(PyInterpreterState_Head() == NULL);
1937
0
        }
1938
0
        else {
1939
0
            assert(interp != NULL);
1940
            /* It is probably the last interpreter but not necessarily. */
1941
0
            assert(PyInterpreterState_Next(interp) == NULL);
1942
0
            total += _PyInterpreterState_GetAllocatedBlocks(interp);
1943
0
        }
1944
0
    }
1945
0
    else {
1946
0
        _PyEval_StopTheWorldAll(&_PyRuntime);
1947
0
        HEAD_LOCK(runtime);
1948
0
        PyInterpreterState *interp = PyInterpreterState_Head();
1949
0
        assert(interp != NULL);
1950
#ifdef Py_DEBUG
1951
        int got_main = 0;
1952
#endif
1953
0
        for (; interp != NULL; interp = PyInterpreterState_Next(interp)) {
1954
#ifdef Py_DEBUG
1955
            if (_Py_IsMainInterpreter(interp)) {
1956
                assert(!got_main);
1957
                got_main = 1;
1958
                assert(has_own_state(interp));
1959
            }
1960
#endif
1961
0
            if (has_own_state(interp)) {
1962
0
                total += _PyInterpreterState_GetAllocatedBlocks(interp);
1963
0
            }
1964
0
        }
1965
0
        HEAD_UNLOCK(runtime);
1966
0
        _PyEval_StartTheWorldAll(&_PyRuntime);
1967
#ifdef Py_DEBUG
1968
        assert(got_main);
1969
#endif
1970
0
    }
1971
0
    total += runtime->obmalloc.interpreter_leaks;
1972
0
    total += last_final_leaks;
1973
0
    return total;
1974
0
}
1975
1976
Py_ssize_t
1977
_Py_GetGlobalAllocatedBlocks(void)
1978
0
{
1979
0
    return get_num_global_allocated_blocks(&_PyRuntime);
1980
0
}
1981
1982
#if WITH_PYMALLOC_RADIX_TREE
1983
/*==========================================================================*/
1984
/* radix tree for tracking arena usage. */
1985
1986
1.09G
#define arena_map_root (state->usage.arena_map_root)
1987
#ifdef USE_INTERIOR_NODES
1988
22
#define arena_map_mid_count (state->usage.arena_map_mid_count)
1989
22
#define arena_map_bot_count (state->usage.arena_map_bot_count)
1990
#endif
1991
1992
/* Return a pointer to a bottom tree node, return NULL if it doesn't exist or
1993
 * it cannot be created */
1994
static inline Py_ALWAYS_INLINE arena_map_bot_t *
1995
arena_map_get(OMState *state, pymem_block *p, int create)
1996
368M
{
1997
368M
#ifdef USE_INTERIOR_NODES
1998
    /* sanity check that IGNORE_BITS is correct */
1999
368M
    assert(HIGH_BITS(p) == HIGH_BITS(&arena_map_root));
2000
368M
    int i1 = MAP_TOP_INDEX(p);
2001
368M
    if (arena_map_root.ptrs[i1] == NULL) {
2002
22
        if (!create) {
2003
0
            return NULL;
2004
0
        }
2005
22
        arena_map_mid_t *n = PyMem_RawCalloc(1, sizeof(arena_map_mid_t));
2006
22
        if (n == NULL) {
2007
0
            return NULL;
2008
0
        }
2009
22
        arena_map_root.ptrs[i1] = n;
2010
22
        arena_map_mid_count++;
2011
22
    }
2012
368M
    int i2 = MAP_MID_INDEX(p);
2013
368M
    if (arena_map_root.ptrs[i1]->ptrs[i2] == NULL) {
2014
10.8M
        if (!create) {
2015
10.8M
            return NULL;
2016
10.8M
        }
2017
22
        arena_map_bot_t *n = PyMem_RawCalloc(1, sizeof(arena_map_bot_t));
2018
22
        if (n == NULL) {
2019
0
            return NULL;
2020
0
        }
2021
22
        arena_map_root.ptrs[i1]->ptrs[i2] = n;
2022
22
        arena_map_bot_count++;
2023
22
    }
2024
357M
    return arena_map_root.ptrs[i1]->ptrs[i2];
2025
#else
2026
    return &arena_map_root;
2027
#endif
2028
368M
}
2029
2030
2031
/* The radix tree only tracks arenas.  So, for 16 MiB arenas, we throw
2032
 * away 24 bits of the address.  That reduces the space requirement of
2033
 * the tree compared to similar radix tree page-map schemes.  In
2034
 * exchange for slashing the space requirement, it needs more
2035
 * computation to check an address.
2036
 *
2037
 * Tracking coverage is done by "ideal" arena address.  It is easier to
2038
 * explain in decimal so let's say that the arena size is 100 bytes.
2039
 * Then, ideal addresses are 100, 200, 300, etc.  For checking if a
2040
 * pointer address is inside an actual arena, we have to check two ideal
2041
 * arena addresses.  E.g. if pointer is 357, we need to check 200 and
2042
 * 300.  In the rare case that an arena is aligned in the ideal way
2043
 * (e.g. base address of arena is 200) then we only have to check one
2044
 * ideal address.
2045
 *
2046
 * The tree nodes for 200 and 300 both store the address of arena.
2047
 * There are two cases: the arena starts at a lower ideal arena and
2048
 * extends to this one, or the arena starts in this arena and extends to
2049
 * the next ideal arena.  The tail_lo and tail_hi members correspond to
2050
 * these two cases.
2051
 */
2052
2053
2054
/* mark or unmark addresses covered by arena */
2055
static int
2056
arena_map_mark_used(OMState *state, uintptr_t arena_base, int is_used)
2057
15.5k
{
2058
    /* sanity check that IGNORE_BITS is correct */
2059
15.5k
    assert(HIGH_BITS(arena_base) == HIGH_BITS(&arena_map_root));
2060
15.5k
    arena_map_bot_t *n_hi = arena_map_get(
2061
15.5k
            state, (pymem_block *)arena_base, is_used);
2062
15.5k
    if (n_hi == NULL) {
2063
0
        assert(is_used); /* otherwise node should already exist */
2064
0
        return 0; /* failed to allocate space for node */
2065
0
    }
2066
15.5k
    int i3 = MAP_BOT_INDEX((pymem_block *)arena_base);
2067
15.5k
    int32_t tail = (int32_t)(arena_base & ARENA_SIZE_MASK);
2068
15.5k
    if (tail == 0) {
2069
        /* is ideal arena address */
2070
39
        n_hi->arenas[i3].tail_hi = is_used ? -1 : 0;
2071
39
    }
2072
15.4k
    else {
2073
        /* arena_base address is not ideal (aligned to arena size) and
2074
         * so it potentially covers two MAP_BOT nodes.  Get the MAP_BOT node
2075
         * for the next arena.  Note that it might be in different MAP_TOP
2076
         * and MAP_MID nodes as well so we need to call arena_map_get()
2077
         * again (do the full tree traversal).
2078
         */
2079
15.4k
        n_hi->arenas[i3].tail_hi = is_used ? tail : 0;
2080
15.4k
        uintptr_t arena_base_next = arena_base + ARENA_SIZE;
2081
        /* If arena_base is a legit arena address, so is arena_base_next - 1
2082
         * (last address in arena).  If arena_base_next overflows then it
2083
         * must overflow to 0.  However, that would mean arena_base was
2084
         * "ideal" and we should not be in this case. */
2085
15.4k
        assert(arena_base < arena_base_next);
2086
15.4k
        arena_map_bot_t *n_lo = arena_map_get(
2087
15.4k
                state, (pymem_block *)arena_base_next, is_used);
2088
15.4k
        if (n_lo == NULL) {
2089
0
            assert(is_used); /* otherwise should already exist */
2090
0
            n_hi->arenas[i3].tail_hi = 0;
2091
0
            return 0; /* failed to allocate space for node */
2092
0
        }
2093
15.4k
        int i3_next = MAP_BOT_INDEX(arena_base_next);
2094
15.4k
        n_lo->arenas[i3_next].tail_lo = is_used ? tail : 0;
2095
15.4k
    }
2096
15.5k
    return 1;
2097
15.5k
}
2098
2099
/* Return true if 'p' is a pointer inside an obmalloc arena.
2100
 * _PyObject_Free() calls this so it needs to be very fast. */
2101
static int
2102
arena_map_is_used(OMState *state, pymem_block *p)
2103
368M
{
2104
368M
    arena_map_bot_t *n = arena_map_get(state, p, 0);
2105
368M
    if (n == NULL) {
2106
10.8M
        return 0;
2107
10.8M
    }
2108
357M
    int i3 = MAP_BOT_INDEX(p);
2109
    /* ARENA_BITS must be < 32 so that the tail is a non-negative int32_t. */
2110
357M
    int32_t hi = n->arenas[i3].tail_hi;
2111
357M
    int32_t lo = n->arenas[i3].tail_lo;
2112
357M
    int32_t tail = (int32_t)(AS_UINT(p) & ARENA_SIZE_MASK);
2113
357M
    return (tail < lo) || (tail >= hi && hi != 0);
2114
368M
}
2115
2116
/* end of radix tree logic */
2117
/*==========================================================================*/
2118
#endif /* WITH_PYMALLOC_RADIX_TREE */
2119
2120
2121
/* Allocate a new arena.  If we run out of memory, return NULL.  Else
2122
 * allocate a new arena, and return the address of an arena_object
2123
 * describing the new arena.  It's expected that the caller will set
2124
 * `usable_arenas` to the return value.
2125
 */
2126
static struct arena_object*
2127
new_arena(OMState *state)
2128
7.82k
{
2129
7.82k
    struct arena_object* arenaobj;
2130
7.82k
    uint excess;        /* number of bytes above pool alignment */
2131
7.82k
    void *address;
2132
2133
7.82k
    int debug_stats = _PyRuntime.obmalloc.dump_debug_stats;
2134
7.82k
    if (debug_stats == -1) {
2135
22
        const char *opt = Py_GETENV("PYTHONMALLOCSTATS");
2136
22
        debug_stats = (opt != NULL && *opt != '\0');
2137
22
        _PyRuntime.obmalloc.dump_debug_stats = debug_stats;
2138
22
    }
2139
7.82k
    if (debug_stats) {
2140
0
        _PyObject_DebugMallocStats(stderr);
2141
0
    }
2142
2143
7.82k
    if (unused_arena_objects == NULL) {
2144
34
        uint i;
2145
34
        uint numarenas;
2146
34
        size_t nbytes;
2147
2148
        /* Double the number of arena objects on each allocation.
2149
         * Note that it's possible for `numarenas` to overflow.
2150
         */
2151
34
        numarenas = maxarenas ? maxarenas << 1 : INITIAL_ARENA_OBJECTS;
2152
34
        if (numarenas <= maxarenas)
2153
0
            return NULL;                /* overflow */
2154
#if SIZEOF_SIZE_T <= SIZEOF_INT
2155
        if (numarenas > SIZE_MAX / sizeof(*allarenas))
2156
            return NULL;                /* overflow */
2157
#endif
2158
34
        nbytes = numarenas * sizeof(*allarenas);
2159
34
        arenaobj = (struct arena_object *)PyMem_RawRealloc(allarenas, nbytes);
2160
34
        if (arenaobj == NULL)
2161
0
            return NULL;
2162
34
        allarenas = arenaobj;
2163
2164
        /* We might need to fix pointers that were copied.  However,
2165
         * new_arena only gets called when all the pages in the
2166
         * previous arenas are full.  Thus, there are *no* pointers
2167
         * into the old array. Thus, we don't have to worry about
2168
         * invalid pointers.  Just to be sure, some asserts:
2169
         */
2170
34
        assert(usable_arenas == NULL);
2171
34
        assert(unused_arena_objects == NULL);
2172
2173
        /* Put the new arenas on the unused_arena_objects list. */
2174
946
        for (i = maxarenas; i < numarenas; ++i) {
2175
912
            allarenas[i].address = 0;              /* mark as unassociated */
2176
912
            allarenas[i].nextarena = i < numarenas - 1 ?
2177
912
                                        &allarenas[i+1] : NULL;
2178
912
        }
2179
2180
        /* Update globals. */
2181
34
        unused_arena_objects = &allarenas[maxarenas];
2182
34
        maxarenas = numarenas;
2183
34
    }
2184
2185
    /* Take the next available arena object off the head of the list. */
2186
7.82k
    assert(unused_arena_objects != NULL);
2187
7.82k
    arenaobj = unused_arena_objects;
2188
7.82k
    unused_arena_objects = arenaobj->nextarena;
2189
7.82k
    assert(arenaobj->address == 0);
2190
7.82k
    address = _PyObject_Arena.alloc(_PyObject_Arena.ctx, ARENA_SIZE);
2191
7.82k
#if WITH_PYMALLOC_RADIX_TREE
2192
7.82k
    if (address != NULL) {
2193
7.82k
        if (!arena_map_mark_used(state, (uintptr_t)address, 1)) {
2194
            /* marking arena in radix tree failed, abort */
2195
0
            _PyObject_Arena.free(_PyObject_Arena.ctx, address, ARENA_SIZE);
2196
0
            address = NULL;
2197
0
        }
2198
7.82k
    }
2199
7.82k
#endif
2200
7.82k
    if (address == NULL) {
2201
        /* The allocation failed: return NULL after putting the
2202
         * arenaobj back.
2203
         */
2204
0
        arenaobj->nextarena = unused_arena_objects;
2205
0
        unused_arena_objects = arenaobj;
2206
0
        return NULL;
2207
0
    }
2208
7.82k
    arenaobj->address = (uintptr_t)address;
2209
2210
7.82k
    ++narenas_currently_allocated;
2211
7.82k
    ++ntimes_arena_allocated;
2212
7.82k
    if (narenas_currently_allocated > narenas_highwater)
2213
506
        narenas_highwater = narenas_currently_allocated;
2214
7.82k
    arenaobj->freepools = NULL;
2215
    /* pool_address <- first pool-aligned address in the arena
2216
       nfreepools <- number of whole pools that fit after alignment */
2217
7.82k
    arenaobj->pool_address = (pymem_block*)arenaobj->address;
2218
7.82k
    arenaobj->nfreepools = MAX_POOLS_IN_ARENA;
2219
7.82k
    excess = (uint)(arenaobj->address & POOL_SIZE_MASK);
2220
7.82k
    if (excess != 0) {
2221
7.62k
        --arenaobj->nfreepools;
2222
7.62k
        arenaobj->pool_address += POOL_SIZE - excess;
2223
7.62k
    }
2224
7.82k
    arenaobj->ntotalpools = arenaobj->nfreepools;
2225
2226
7.82k
    return arenaobj;
2227
7.82k
}
2228
2229
2230
2231
#if WITH_PYMALLOC_RADIX_TREE
2232
/* Return true if and only if P is an address that was allocated by
2233
   pymalloc.  When the radix tree is used, 'poolp' is unused.
2234
 */
2235
static bool
2236
address_in_range(OMState *state, void *p, poolp Py_UNUSED(pool))
2237
368M
{
2238
368M
    return arena_map_is_used(state, p);
2239
368M
}
2240
#else
2241
/*
2242
address_in_range(P, POOL)
2243
2244
Return true if and only if P is an address that was allocated by pymalloc.
2245
POOL must be the pool address associated with P, i.e., POOL = POOL_ADDR(P)
2246
(the caller is asked to compute this because the macro expands POOL more than
2247
once, and for efficiency it's best for the caller to assign POOL_ADDR(P) to a
2248
variable and pass the latter to the macro; because address_in_range is
2249
called on every alloc/realloc/free, micro-efficiency is important here).
2250
2251
Tricky:  Let B be the arena base address associated with the pool, B =
2252
arenas[(POOL)->arenaindex].address.  Then P belongs to the arena if and only if
2253
2254
    B <= P < B + ARENA_SIZE
2255
2256
Subtracting B throughout, this is true iff
2257
2258
    0 <= P-B < ARENA_SIZE
2259
2260
By using unsigned arithmetic, the "0 <=" half of the test can be skipped.
2261
2262
Obscure:  A PyMem "free memory" function can call the pymalloc free or realloc
2263
before the first arena has been allocated.  `arenas` is still NULL in that
2264
case.  We're relying on that maxarenas is also 0 in that case, so that
2265
(POOL)->arenaindex < maxarenas  must be false, saving us from trying to index
2266
into a NULL arenas.
2267
2268
Details:  given P and POOL, the arena_object corresponding to P is AO =
2269
arenas[(POOL)->arenaindex].  Suppose obmalloc controls P.  Then (barring wild
2270
stores, etc), POOL is the correct address of P's pool, AO.address is the
2271
correct base address of the pool's arena, and P must be within ARENA_SIZE of
2272
AO.address.  In addition, AO.address is not 0 (no arena can start at address 0
2273
(NULL)).  Therefore address_in_range correctly reports that obmalloc
2274
controls P.
2275
2276
Now suppose obmalloc does not control P (e.g., P was obtained via a direct
2277
call to the system malloc() or realloc()).  (POOL)->arenaindex may be anything
2278
in this case -- it may even be uninitialized trash.  If the trash arenaindex
2279
is >= maxarenas, the macro correctly concludes at once that obmalloc doesn't
2280
control P.
2281
2282
Else arenaindex is < maxarena, and AO is read up.  If AO corresponds to an
2283
allocated arena, obmalloc controls all the memory in slice AO.address :
2284
AO.address+ARENA_SIZE.  By case assumption, P is not controlled by obmalloc,
2285
so P doesn't lie in that slice, so the macro correctly reports that P is not
2286
controlled by obmalloc.
2287
2288
Finally, if P is not controlled by obmalloc and AO corresponds to an unused
2289
arena_object (one not currently associated with an allocated arena),
2290
AO.address is 0, and the second test in the macro reduces to:
2291
2292
    P < ARENA_SIZE
2293
2294
If P >= ARENA_SIZE (extremely likely), the macro again correctly concludes
2295
that P is not controlled by obmalloc.  However, if P < ARENA_SIZE, this part
2296
of the test still passes, and the third clause (AO.address != 0) is necessary
2297
to get the correct result:  AO.address is 0 in this case, so the macro
2298
correctly reports that P is not controlled by obmalloc (despite that P lies in
2299
slice AO.address : AO.address + ARENA_SIZE).
2300
2301
Note:  The third (AO.address != 0) clause was added in Python 2.5.  Before
2302
2.5, arenas were never free()'ed, and an arenaindex < maxarena always
2303
corresponded to a currently-allocated arena, so the "P is not controlled by
2304
obmalloc, AO corresponds to an unused arena_object, and P < ARENA_SIZE" case
2305
was impossible.
2306
2307
Note that the logic is excruciating, and reading up possibly uninitialized
2308
memory when P is not controlled by obmalloc (to get at (POOL)->arenaindex)
2309
creates problems for some memory debuggers.  The overwhelming advantage is
2310
that this test determines whether an arbitrary address is controlled by
2311
obmalloc in a small constant time, independent of the number of arenas
2312
obmalloc controls.  Since this test is needed at every entry point, it's
2313
extremely desirable that it be this fast.
2314
*/
2315
2316
static bool _Py_NO_SANITIZE_ADDRESS
2317
            _Py_NO_SANITIZE_THREAD
2318
            _Py_NO_SANITIZE_MEMORY
2319
address_in_range(OMState *state, void *p, poolp pool)
2320
{
2321
    // Since address_in_range may be reading from memory which was not allocated
2322
    // by Python, it is important that pool->arenaindex is read only once, as
2323
    // another thread may be concurrently modifying the value without holding
2324
    // the GIL. The following dance forces the compiler to read pool->arenaindex
2325
    // only once.
2326
    uint arenaindex = *((volatile uint *)&pool->arenaindex);
2327
    return arenaindex < maxarenas &&
2328
        (uintptr_t)p - allarenas[arenaindex].address < ARENA_SIZE &&
2329
        allarenas[arenaindex].address != 0;
2330
}
2331
2332
#endif /* !WITH_PYMALLOC_RADIX_TREE */
2333
2334
/*==========================================================================*/
2335
2336
// Called when freelist is exhausted.  Extend the freelist if there is
2337
// space for a block.  Otherwise, remove this pool from usedpools.
2338
static void
2339
pymalloc_pool_extend(poolp pool, uint size)
2340
174M
{
2341
174M
    if (UNLIKELY(pool->nextoffset <= pool->maxnextoffset)) {
2342
        /* There is room for another block. */
2343
162M
        pool->freeblock = (pymem_block*)pool + pool->nextoffset;
2344
162M
        pool->nextoffset += INDEX2SIZE(size);
2345
162M
        *(pymem_block **)(pool->freeblock) = NULL;
2346
162M
        return;
2347
162M
    }
2348
2349
    /* Pool is full, unlink from used pools. */
2350
11.6M
    poolp next;
2351
11.6M
    next = pool->nextpool;
2352
11.6M
    pool = pool->prevpool;
2353
11.6M
    next->prevpool = pool;
2354
11.6M
    pool->nextpool = next;
2355
11.6M
}
2356
2357
/* called when pymalloc_alloc can not allocate a block from usedpool.
2358
 * This function takes new pool and allocate a block from it.
2359
 */
2360
static void*
2361
allocate_from_new_pool(OMState *state, uint size)
2362
1.04M
{
2363
    /* There isn't a pool of the right size class immediately
2364
     * available:  use a free pool.
2365
     */
2366
1.04M
    if (UNLIKELY(usable_arenas == NULL)) {
2367
        /* No arena has a free pool:  allocate a new arena. */
2368
#ifdef WITH_MEMORY_LIMITS
2369
        if (narenas_currently_allocated >= MAX_ARENAS) {
2370
            return NULL;
2371
        }
2372
#endif
2373
7.82k
        usable_arenas = new_arena(state);
2374
7.82k
        if (usable_arenas == NULL) {
2375
0
            return NULL;
2376
0
        }
2377
7.82k
        usable_arenas->nextarena = usable_arenas->prevarena = NULL;
2378
7.82k
        assert(nfp2lasta[usable_arenas->nfreepools] == NULL);
2379
7.82k
        nfp2lasta[usable_arenas->nfreepools] = usable_arenas;
2380
7.82k
    }
2381
1.04M
    assert(usable_arenas->address != 0);
2382
2383
    /* This arena already had the smallest nfreepools value, so decreasing
2384
     * nfreepools doesn't change that, and we don't need to rearrange the
2385
     * usable_arenas list.  However, if the arena becomes wholly allocated,
2386
     * we need to remove its arena_object from usable_arenas.
2387
     */
2388
1.04M
    assert(usable_arenas->nfreepools > 0);
2389
1.04M
    if (nfp2lasta[usable_arenas->nfreepools] == usable_arenas) {
2390
        /* It's the last of this size, so there won't be any. */
2391
1.03M
        nfp2lasta[usable_arenas->nfreepools] = NULL;
2392
1.03M
    }
2393
    /* If any free pools will remain, it will be the new smallest. */
2394
1.04M
    if (usable_arenas->nfreepools > 1) {
2395
1.01M
        assert(nfp2lasta[usable_arenas->nfreepools - 1] == NULL);
2396
1.01M
        nfp2lasta[usable_arenas->nfreepools - 1] = usable_arenas;
2397
1.01M
    }
2398
2399
    /* Try to get a cached free pool. */
2400
1.04M
    poolp pool = usable_arenas->freepools;
2401
1.04M
    if (LIKELY(pool != NULL)) {
2402
        /* Unlink from cached pools. */
2403
549k
        usable_arenas->freepools = pool->nextpool;
2404
549k
        usable_arenas->nfreepools--;
2405
549k
        if (UNLIKELY(usable_arenas->nfreepools == 0)) {
2406
            /* Wholly allocated:  remove. */
2407
21.6k
            assert(usable_arenas->freepools == NULL);
2408
21.6k
            assert(usable_arenas->nextarena == NULL ||
2409
21.6k
                   usable_arenas->nextarena->prevarena ==
2410
21.6k
                   usable_arenas);
2411
21.6k
            usable_arenas = usable_arenas->nextarena;
2412
21.6k
            if (usable_arenas != NULL) {
2413
21.1k
                usable_arenas->prevarena = NULL;
2414
21.1k
                assert(usable_arenas->address != 0);
2415
21.1k
            }
2416
21.6k
        }
2417
528k
        else {
2418
            /* nfreepools > 0:  it must be that freepools
2419
             * isn't NULL, or that we haven't yet carved
2420
             * off all the arena's pools for the first
2421
             * time.
2422
             */
2423
528k
            assert(usable_arenas->freepools != NULL ||
2424
528k
                   usable_arenas->pool_address <=
2425
528k
                   (pymem_block*)usable_arenas->address +
2426
528k
                       ARENA_SIZE - POOL_SIZE);
2427
528k
        }
2428
549k
    }
2429
491k
    else {
2430
        /* Carve off a new pool. */
2431
491k
        assert(usable_arenas->nfreepools > 0);
2432
491k
        assert(usable_arenas->freepools == NULL);
2433
491k
        pool = (poolp)usable_arenas->pool_address;
2434
491k
        assert((pymem_block*)pool <= (pymem_block*)usable_arenas->address +
2435
491k
                                 ARENA_SIZE - POOL_SIZE);
2436
491k
        pool->arenaindex = (uint)(usable_arenas - allarenas);
2437
491k
        assert(&allarenas[pool->arenaindex] == usable_arenas);
2438
491k
        pool->szidx = DUMMY_SIZE_IDX;
2439
491k
        usable_arenas->pool_address += POOL_SIZE;
2440
491k
        --usable_arenas->nfreepools;
2441
2442
491k
        if (usable_arenas->nfreepools == 0) {
2443
7.75k
            assert(usable_arenas->nextarena == NULL ||
2444
7.75k
                   usable_arenas->nextarena->prevarena ==
2445
7.75k
                   usable_arenas);
2446
            /* Unlink the arena:  it is completely allocated. */
2447
7.75k
            usable_arenas = usable_arenas->nextarena;
2448
7.75k
            if (usable_arenas != NULL) {
2449
149
                usable_arenas->prevarena = NULL;
2450
149
                assert(usable_arenas->address != 0);
2451
149
            }
2452
7.75k
        }
2453
491k
    }
2454
2455
    /* Frontlink to used pools. */
2456
1.04M
    pymem_block *bp;
2457
1.04M
    poolp next = usedpools[size + size]; /* == prev */
2458
1.04M
    pool->nextpool = next;
2459
1.04M
    pool->prevpool = next;
2460
1.04M
    next->nextpool = pool;
2461
1.04M
    next->prevpool = pool;
2462
1.04M
    pool->ref.count = 1;
2463
1.04M
    if (pool->szidx == size) {
2464
        /* Luckily, this pool last contained blocks
2465
         * of the same size class, so its header
2466
         * and free list are already initialized.
2467
         */
2468
357k
        bp = pool->freeblock;
2469
357k
        assert(bp != NULL);
2470
357k
        pool->freeblock = *(pymem_block **)bp;
2471
357k
        return bp;
2472
357k
    }
2473
    /*
2474
     * Initialize the pool header, set up the free list to
2475
     * contain just the second block, and return the first
2476
     * block.
2477
     */
2478
683k
    pool->szidx = size;
2479
683k
    size = INDEX2SIZE(size);
2480
683k
    bp = (pymem_block *)pool + POOL_OVERHEAD;
2481
683k
    pool->nextoffset = POOL_OVERHEAD + (size << 1);
2482
683k
    pool->maxnextoffset = POOL_SIZE - size;
2483
683k
    pool->freeblock = bp + size;
2484
683k
    *(pymem_block **)(pool->freeblock) = NULL;
2485
683k
    return bp;
2486
1.04M
}
2487
2488
/* pymalloc allocator
2489
2490
   Return a pointer to newly allocated memory if pymalloc allocated memory.
2491
2492
   Return NULL if pymalloc failed to allocate the memory block: on bigger
2493
   requests, on error in the code below (as a last chance to serve the request)
2494
   or when the max memory limit has been reached.
2495
*/
2496
static inline void*
2497
pymalloc_alloc(OMState *state, void *Py_UNUSED(ctx), size_t nbytes)
2498
354M
{
2499
#ifdef WITH_VALGRIND
2500
    if (UNLIKELY(running_on_valgrind == -1)) {
2501
        running_on_valgrind = RUNNING_ON_VALGRIND;
2502
    }
2503
    if (UNLIKELY(running_on_valgrind)) {
2504
        return NULL;
2505
    }
2506
#endif
2507
2508
354M
    if (UNLIKELY(nbytes == 0)) {
2509
99.7k
        return NULL;
2510
99.7k
    }
2511
354M
    if (UNLIKELY(nbytes > SMALL_REQUEST_THRESHOLD)) {
2512
4.10M
        return NULL;
2513
4.10M
    }
2514
2515
350M
    uint size = (uint)(nbytes - 1) >> ALIGNMENT_SHIFT;
2516
350M
    poolp pool = usedpools[size + size];
2517
350M
    pymem_block *bp;
2518
2519
350M
    if (LIKELY(pool != pool->nextpool)) {
2520
        /*
2521
         * There is a used pool for this size class.
2522
         * Pick up the head block of its free list.
2523
         */
2524
349M
        ++pool->ref.count;
2525
349M
        bp = pool->freeblock;
2526
349M
        assert(bp != NULL);
2527
2528
349M
        if (UNLIKELY((pool->freeblock = *(pymem_block **)bp) == NULL)) {
2529
            // Reached the end of the free list, try to extend it.
2530
174M
            pymalloc_pool_extend(pool, size);
2531
174M
        }
2532
349M
    }
2533
1.04M
    else {
2534
        /* There isn't a pool of the right size class immediately
2535
         * available:  use a free pool.
2536
         */
2537
1.04M
        bp = allocate_from_new_pool(state, size);
2538
1.04M
    }
2539
2540
350M
    return (void *)bp;
2541
350M
}
2542
2543
2544
void *
2545
_PyObject_Malloc(void *ctx, size_t nbytes)
2546
344M
{
2547
344M
    OMState *state = get_state();
2548
344M
    void* ptr = pymalloc_alloc(state, ctx, nbytes);
2549
344M
    if (LIKELY(ptr != NULL)) {
2550
340M
        return ptr;
2551
340M
    }
2552
2553
3.26M
    ptr = PyMem_RawMalloc(nbytes);
2554
3.26M
    if (ptr != NULL) {
2555
3.26M
        raw_allocated_blocks++;
2556
3.26M
    }
2557
3.26M
    return ptr;
2558
344M
}
2559
2560
2561
void *
2562
_PyObject_Calloc(void *ctx, size_t nelem, size_t elsize)
2563
10.3M
{
2564
10.3M
    assert(elsize == 0 || nelem <= (size_t)PY_SSIZE_T_MAX / elsize);
2565
10.3M
    size_t nbytes = nelem * elsize;
2566
2567
10.3M
    OMState *state = get_state();
2568
10.3M
    void* ptr = pymalloc_alloc(state, ctx, nbytes);
2569
10.3M
    if (LIKELY(ptr != NULL)) {
2570
9.44M
        memset(ptr, 0, nbytes);
2571
9.44M
        return ptr;
2572
9.44M
    }
2573
2574
942k
    ptr = PyMem_RawCalloc(nelem, elsize);
2575
942k
    if (ptr != NULL) {
2576
942k
        raw_allocated_blocks++;
2577
942k
    }
2578
942k
    return ptr;
2579
10.3M
}
2580
2581
2582
static void
2583
insert_to_usedpool(OMState *state, poolp pool)
2584
11.6M
{
2585
11.6M
    assert(pool->ref.count > 0);            /* else the pool is empty */
2586
2587
11.6M
    uint size = pool->szidx;
2588
11.6M
    poolp next = usedpools[size + size];
2589
11.6M
    poolp prev = next->prevpool;
2590
2591
    /* insert pool before next:   prev <-> pool <-> next */
2592
11.6M
    pool->nextpool = next;
2593
11.6M
    pool->prevpool = prev;
2594
11.6M
    next->prevpool = pool;
2595
11.6M
    prev->nextpool = pool;
2596
11.6M
}
2597
2598
static void
2599
insert_to_freepool(OMState *state, poolp pool)
2600
1.03M
{
2601
1.03M
    poolp next = pool->nextpool;
2602
1.03M
    poolp prev = pool->prevpool;
2603
1.03M
    next->prevpool = prev;
2604
1.03M
    prev->nextpool = next;
2605
2606
    /* Link the pool to freepools.  This is a singly-linked
2607
     * list, and pool->prevpool isn't used there.
2608
     */
2609
1.03M
    struct arena_object *ao = &allarenas[pool->arenaindex];
2610
1.03M
    pool->nextpool = ao->freepools;
2611
1.03M
    ao->freepools = pool;
2612
1.03M
    uint nf = ao->nfreepools;
2613
    /* If this is the rightmost arena with this number of free pools,
2614
     * nfp2lasta[nf] needs to change.  Caution:  if nf is 0, there
2615
     * are no arenas in usable_arenas with that value.
2616
     */
2617
1.03M
    struct arena_object* lastnf = nfp2lasta[nf];
2618
1.03M
    assert((nf == 0 && lastnf == NULL) ||
2619
1.03M
           (nf > 0 &&
2620
1.03M
            lastnf != NULL &&
2621
1.03M
            lastnf->nfreepools == nf &&
2622
1.03M
            (lastnf->nextarena == NULL ||
2623
1.03M
             nf < lastnf->nextarena->nfreepools)));
2624
1.03M
    if (lastnf == ao) {  /* it is the rightmost */
2625
899k
        struct arena_object* p = ao->prevarena;
2626
899k
        nfp2lasta[nf] = (p != NULL && p->nfreepools == nf) ? p : NULL;
2627
899k
    }
2628
1.03M
    ao->nfreepools = ++nf;
2629
2630
    /* All the rest is arena management.  We just freed
2631
     * a pool, and there are 4 cases for arena mgmt:
2632
     * 1. If all the pools are free, return the arena to
2633
     *    the system free().  Except if this is the last
2634
     *    arena in the list, keep it to avoid thrashing:
2635
     *    keeping one wholly free arena in the list avoids
2636
     *    pathological cases where a simple loop would
2637
     *    otherwise provoke needing to allocate and free an
2638
     *    arena on every iteration.  See bpo-37257.
2639
     * 2. If this is the only free pool in the arena,
2640
     *    add the arena back to the `usable_arenas` list.
2641
     * 3. If the "next" arena has a smaller count of free
2642
     *    pools, we have to "slide this arena right" to
2643
     *    restore that usable_arenas is sorted in order of
2644
     *    nfreepools.
2645
     * 4. Else there's nothing more to do.
2646
     */
2647
1.03M
    if (nf == ao->ntotalpools && ao->nextarena != NULL) {
2648
        /* Case 1.  First unlink ao from usable_arenas.
2649
         */
2650
7.68k
        assert(ao->prevarena == NULL ||
2651
7.68k
               ao->prevarena->address != 0);
2652
7.68k
        assert(ao ->nextarena == NULL ||
2653
7.68k
               ao->nextarena->address != 0);
2654
2655
        /* Fix the pointer in the prevarena, or the
2656
         * usable_arenas pointer.
2657
         */
2658
7.68k
        if (ao->prevarena == NULL) {
2659
68
            usable_arenas = ao->nextarena;
2660
68
            assert(usable_arenas == NULL ||
2661
68
                   usable_arenas->address != 0);
2662
68
        }
2663
7.61k
        else {
2664
7.61k
            assert(ao->prevarena->nextarena == ao);
2665
7.61k
            ao->prevarena->nextarena =
2666
7.61k
                ao->nextarena;
2667
7.61k
        }
2668
        /* Fix the pointer in the nextarena. */
2669
7.68k
        if (ao->nextarena != NULL) {
2670
7.68k
            assert(ao->nextarena->prevarena == ao);
2671
7.68k
            ao->nextarena->prevarena =
2672
7.68k
                ao->prevarena;
2673
7.68k
        }
2674
        /* Record that this arena_object slot is
2675
         * available to be reused.
2676
         */
2677
7.68k
        ao->nextarena = unused_arena_objects;
2678
7.68k
        unused_arena_objects = ao;
2679
2680
7.68k
#if WITH_PYMALLOC_RADIX_TREE
2681
        /* mark arena region as not under control of obmalloc */
2682
7.68k
        arena_map_mark_used(state, ao->address, 0);
2683
7.68k
#endif
2684
2685
        /* Free the entire arena. */
2686
7.68k
        _PyObject_Arena.free(_PyObject_Arena.ctx,
2687
7.68k
                             (void *)ao->address, ARENA_SIZE);
2688
7.68k
        ao->address = 0;                        /* mark unassociated */
2689
7.68k
        --narenas_currently_allocated;
2690
2691
7.68k
        return;
2692
7.68k
    }
2693
2694
1.02M
    if (nf == 1) {
2695
        /* Case 2.  Put ao at the head of
2696
         * usable_arenas.  Note that because
2697
         * ao->nfreepools was 0 before, ao isn't
2698
         * currently on the usable_arenas list.
2699
         */
2700
29.3k
        ao->nextarena = usable_arenas;
2701
29.3k
        ao->prevarena = NULL;
2702
29.3k
        if (usable_arenas)
2703
29.0k
            usable_arenas->prevarena = ao;
2704
29.3k
        usable_arenas = ao;
2705
29.3k
        assert(usable_arenas->address != 0);
2706
29.3k
        if (nfp2lasta[1] == NULL) {
2707
27.1k
            nfp2lasta[1] = ao;
2708
27.1k
        }
2709
2710
29.3k
        return;
2711
29.3k
    }
2712
2713
    /* If this arena is now out of order, we need to keep
2714
     * the list sorted.  The list is kept sorted so that
2715
     * the "most full" arenas are used first, which allows
2716
     * the nearly empty arenas to be completely freed.  In
2717
     * a few un-scientific tests, it seems like this
2718
     * approach allowed a lot more memory to be freed.
2719
     */
2720
    /* If this is the only arena with nf, record that. */
2721
999k
    if (nfp2lasta[nf] == NULL) {
2722
887k
        nfp2lasta[nf] = ao;
2723
887k
    } /* else the rightmost with nf doesn't change */
2724
    /* If this was the rightmost of the old size, it remains in place. */
2725
999k
    if (ao == lastnf) {
2726
        /* Case 4.  Nothing to do. */
2727
898k
        return;
2728
898k
    }
2729
    /* If ao were the only arena in the list, the last block would have
2730
     * gotten us out.
2731
     */
2732
999k
    assert(ao->nextarena != NULL);
2733
2734
    /* Case 3:  We have to move the arena towards the end of the list,
2735
     * because it has more free pools than the arena to its right.  It needs
2736
     * to move to follow lastnf.
2737
     * First unlink ao from usable_arenas.
2738
     */
2739
100k
    if (ao->prevarena != NULL) {
2740
        /* ao isn't at the head of the list */
2741
87.4k
        assert(ao->prevarena->nextarena == ao);
2742
87.4k
        ao->prevarena->nextarena = ao->nextarena;
2743
87.4k
    }
2744
13.3k
    else {
2745
        /* ao is at the head of the list */
2746
13.3k
        assert(usable_arenas == ao);
2747
13.3k
        usable_arenas = ao->nextarena;
2748
13.3k
    }
2749
100k
    ao->nextarena->prevarena = ao->prevarena;
2750
    /* And insert after lastnf. */
2751
100k
    ao->prevarena = lastnf;
2752
100k
    ao->nextarena = lastnf->nextarena;
2753
100k
    if (ao->nextarena != NULL) {
2754
99.8k
        ao->nextarena->prevarena = ao;
2755
99.8k
    }
2756
100k
    lastnf->nextarena = ao;
2757
    /* Verify that the swaps worked. */
2758
100k
    assert(ao->nextarena == NULL || nf <= ao->nextarena->nfreepools);
2759
100k
    assert(ao->prevarena == NULL || nf > ao->prevarena->nfreepools);
2760
100k
    assert(ao->nextarena == NULL || ao->nextarena->prevarena == ao);
2761
100k
    assert((usable_arenas == ao && ao->prevarena == NULL)
2762
100k
           || ao->prevarena->nextarena == ao);
2763
100k
}
2764
2765
/* Free a memory block allocated by pymalloc_alloc().
2766
   Return 1 if it was freed.
2767
   Return 0 if the block was not allocated by pymalloc_alloc(). */
2768
static inline int
2769
pymalloc_free(OMState *state, void *Py_UNUSED(ctx), void *p)
2770
353M
{
2771
353M
    assert(p != NULL);
2772
2773
#ifdef WITH_VALGRIND
2774
    if (UNLIKELY(running_on_valgrind > 0)) {
2775
        return 0;
2776
    }
2777
#endif
2778
2779
353M
    poolp pool = POOL_ADDR(p);
2780
353M
    if (UNLIKELY(!address_in_range(state, p, pool))) {
2781
4.18M
        return 0;
2782
4.18M
    }
2783
    /* We allocated this address. */
2784
2785
    /* Link p to the start of the pool's freeblock list.  Since
2786
     * the pool had at least the p block outstanding, the pool
2787
     * wasn't empty (so it's already in a usedpools[] list, or
2788
     * was full and is in no list -- it's not in the freeblocks
2789
     * list in any case).
2790
     */
2791
353M
    assert(pool->ref.count > 0);            /* else it was empty */
2792
349M
    pymem_block *lastfree = pool->freeblock;
2793
349M
    *(pymem_block **)p = lastfree;
2794
349M
    pool->freeblock = (pymem_block *)p;
2795
349M
    pool->ref.count--;
2796
2797
349M
    if (UNLIKELY(lastfree == NULL)) {
2798
        /* Pool was full, so doesn't currently live in any list:
2799
         * link it to the front of the appropriate usedpools[] list.
2800
         * This mimics LRU pool usage for new allocations and
2801
         * targets optimal filling when several pools contain
2802
         * blocks of the same size class.
2803
         */
2804
11.6M
        insert_to_usedpool(state, pool);
2805
11.6M
        return 1;
2806
11.6M
    }
2807
2808
    /* freeblock wasn't NULL, so the pool wasn't full,
2809
     * and the pool is in a usedpools[] list.
2810
     */
2811
338M
    if (LIKELY(pool->ref.count != 0)) {
2812
        /* pool isn't empty:  leave it in usedpools */
2813
336M
        return 1;
2814
336M
    }
2815
2816
    /* Pool is now empty:  unlink from usedpools, and
2817
     * link to the front of freepools.  This ensures that
2818
     * previously freed pools will be allocated later
2819
     * (being not referenced, they are perhaps paged out).
2820
     */
2821
1.03M
    insert_to_freepool(state, pool);
2822
1.03M
    return 1;
2823
338M
}
2824
2825
2826
void
2827
_PyObject_Free(void *ctx, void *p)
2828
357M
{
2829
    /* PyObject_Free(NULL) has no effect */
2830
357M
    if (p == NULL) {
2831
3.96M
        return;
2832
3.96M
    }
2833
2834
353M
    OMState *state = get_state();
2835
353M
    if (UNLIKELY(!pymalloc_free(state, ctx, p))) {
2836
        /* pymalloc didn't allocate this address */
2837
4.18M
        PyMem_RawFree(p);
2838
4.18M
        raw_allocated_blocks--;
2839
4.18M
    }
2840
353M
}
2841
2842
2843
/* pymalloc realloc.
2844
2845
   If nbytes==0, then as the Python docs promise, we do not treat this like
2846
   free(p), and return a non-NULL result.
2847
2848
   Return 1 if pymalloc reallocated memory and wrote the new pointer into
2849
   newptr_p.
2850
2851
   Return 0 if pymalloc didn't allocated p. */
2852
static int
2853
pymalloc_realloc(OMState *state, void *ctx,
2854
                 void **newptr_p, void *p, size_t nbytes)
2855
14.3M
{
2856
14.3M
    void *bp;
2857
14.3M
    poolp pool;
2858
14.3M
    size_t size;
2859
2860
14.3M
    assert(p != NULL);
2861
2862
#ifdef WITH_VALGRIND
2863
    /* Treat running_on_valgrind == -1 the same as 0 */
2864
    if (UNLIKELY(running_on_valgrind > 0)) {
2865
        return 0;
2866
    }
2867
#endif
2868
2869
14.3M
    pool = POOL_ADDR(p);
2870
14.3M
    if (!address_in_range(state, p, pool)) {
2871
        /* pymalloc is not managing this block.
2872
2873
           If nbytes <= SMALL_REQUEST_THRESHOLD, it's tempting to try to take
2874
           over this block.  However, if we do, we need to copy the valid data
2875
           from the C-managed block to one of our blocks, and there's no
2876
           portable way to know how much of the memory space starting at p is
2877
           valid.
2878
2879
           As bug 1185883 pointed out the hard way, it's possible that the
2880
           C-managed block is "at the end" of allocated VM space, so that a
2881
           memory fault can occur if we try to copy nbytes bytes starting at p.
2882
           Instead we punt: let C continue to manage this block. */
2883
6.64M
        return 0;
2884
6.64M
    }
2885
2886
    /* pymalloc is in charge of this block */
2887
7.67M
    size = INDEX2SIZE(pool->szidx);
2888
7.67M
    if (nbytes <= size) {
2889
        /* The block is staying the same or shrinking.
2890
2891
           If it's shrinking, there's a tradeoff: it costs cycles to copy the
2892
           block to a smaller size class, but it wastes memory not to copy it.
2893
2894
           The compromise here is to copy on shrink only if at least 25% of
2895
           size can be shaved off. */
2896
4.04M
        if (4 * nbytes > 3 * size) {
2897
            /* It's the same, or shrinking and new/old > 3/4. */
2898
2.21M
            *newptr_p = p;
2899
2.21M
            return 1;
2900
2.21M
        }
2901
1.83M
        size = nbytes;
2902
1.83M
    }
2903
2904
5.45M
    bp = _PyObject_Malloc(ctx, nbytes);
2905
5.45M
    if (bp != NULL) {
2906
5.45M
        memcpy(bp, p, size);
2907
5.45M
        _PyObject_Free(ctx, p);
2908
5.45M
    }
2909
5.45M
    *newptr_p = bp;
2910
5.45M
    return 1;
2911
7.67M
}
2912
2913
2914
void *
2915
_PyObject_Realloc(void *ctx, void *ptr, size_t nbytes)
2916
29.8M
{
2917
29.8M
    void *ptr2;
2918
2919
29.8M
    if (ptr == NULL) {
2920
15.4M
        return _PyObject_Malloc(ctx, nbytes);
2921
15.4M
    }
2922
2923
14.3M
    OMState *state = get_state();
2924
14.3M
    if (pymalloc_realloc(state, ctx, &ptr2, ptr, nbytes)) {
2925
7.67M
        return ptr2;
2926
7.67M
    }
2927
2928
6.64M
    return PyMem_RawRealloc(ptr, nbytes);
2929
14.3M
}
2930
2931
#else   /* ! WITH_PYMALLOC */
2932
2933
/*==========================================================================*/
2934
/* pymalloc not enabled:  Redirect the entry points to malloc.  These will
2935
 * only be used by extensions that are compiled with pymalloc enabled. */
2936
2937
Py_ssize_t
2938
_PyInterpreterState_GetAllocatedBlocks(PyInterpreterState *Py_UNUSED(interp))
2939
{
2940
    return 0;
2941
}
2942
2943
Py_ssize_t
2944
_Py_GetGlobalAllocatedBlocks(void)
2945
{
2946
    return 0;
2947
}
2948
2949
void
2950
_PyInterpreterState_FinalizeAllocatedBlocks(PyInterpreterState *Py_UNUSED(interp))
2951
{
2952
    return;
2953
}
2954
2955
void
2956
_Py_FinalizeAllocatedBlocks(_PyRuntimeState *Py_UNUSED(runtime))
2957
{
2958
    return;
2959
}
2960
2961
#endif /* WITH_PYMALLOC */
2962
2963
2964
/*==========================================================================*/
2965
/* A x-platform debugging allocator.  This doesn't manage memory directly,
2966
 * it wraps a real allocator, adding extra debugging info to the memory blocks.
2967
 */
2968
2969
/* Uncomment this define to add the "serialno" field */
2970
/* #define PYMEM_DEBUG_SERIALNO */
2971
2972
#ifdef PYMEM_DEBUG_SERIALNO
2973
static size_t serialno = 0;     /* incremented on each debug {m,re}alloc */
2974
2975
/* serialno is always incremented via calling this routine.  The point is
2976
 * to supply a single place to set a breakpoint.
2977
 */
2978
static void
2979
bumpserialno(void)
2980
{
2981
    ++serialno;
2982
}
2983
#endif
2984
2985
0
#define SST SIZEOF_SIZE_T
2986
2987
#ifdef PYMEM_DEBUG_SERIALNO
2988
#  define PYMEM_DEBUG_EXTRA_BYTES 4 * SST
2989
#else
2990
0
#  define PYMEM_DEBUG_EXTRA_BYTES 3 * SST
2991
#endif
2992
2993
/* Read sizeof(size_t) bytes at p as a big-endian size_t. */
2994
static size_t
2995
read_size_t(const void *p)
2996
0
{
2997
0
    const uint8_t *q = (const uint8_t *)p;
2998
0
    size_t result = *q++;
2999
0
    int i;
3000
3001
0
    for (i = SST; --i > 0; ++q)
3002
0
        result = (result << 8) | *q;
3003
0
    return result;
3004
0
}
3005
3006
/* Write n as a big-endian size_t, MSB at address p, LSB at
3007
 * p + sizeof(size_t) - 1.
3008
 */
3009
static void
3010
write_size_t(void *p, size_t n)
3011
0
{
3012
0
    uint8_t *q = (uint8_t *)p + SST - 1;
3013
0
    int i;
3014
3015
0
    for (i = SST; --i >= 0; --q) {
3016
0
        *q = (uint8_t)(n & 0xff);
3017
0
        n >>= 8;
3018
0
    }
3019
0
}
3020
3021
static void
3022
fill_mem_debug(debug_alloc_api_t *api, void *data, int c, size_t nbytes,
3023
               bool is_alloc)
3024
0
{
3025
#ifdef Py_GIL_DISABLED
3026
    if (api->api_id == 'o') {
3027
        // Don't overwrite the first few bytes of a PyObject allocation in the
3028
        // free-threaded build
3029
        _PyThreadStateImpl *tstate = (_PyThreadStateImpl *)_PyThreadState_GET();
3030
        size_t debug_offset;
3031
        if (is_alloc) {
3032
            debug_offset = tstate->mimalloc.current_object_heap->debug_offset;
3033
        }
3034
        else {
3035
            char *alloc = (char *)data - 2*SST;  // start of the allocation
3036
            debug_offset = _mi_ptr_page(alloc)->debug_offset;
3037
        }
3038
        debug_offset -= 2*SST;  // account for pymalloc extra bytes
3039
        if (debug_offset < nbytes) {
3040
            memset((char *)data + debug_offset, c, nbytes - debug_offset);
3041
        }
3042
        return;
3043
    }
3044
#endif
3045
0
    memset(data, c, nbytes);
3046
0
}
3047
3048
/* Let S = sizeof(size_t).  The debug malloc asks for 4 * S extra bytes and
3049
   fills them with useful stuff, here calling the underlying malloc's result p:
3050
3051
p[0: S]
3052
    Number of bytes originally asked for.  This is a size_t, big-endian (easier
3053
    to read in a memory dump).
3054
p[S]
3055
    API ID.  See PEP 445.  This is a character, but seems undocumented.
3056
p[S+1: 2*S]
3057
    Copies of PYMEM_FORBIDDENBYTE.  Used to catch under- writes and reads.
3058
p[2*S: 2*S+n]
3059
    The requested memory, filled with copies of PYMEM_CLEANBYTE.
3060
    Used to catch reference to uninitialized memory.
3061
    &p[2*S] is returned.  Note that this is 8-byte aligned if pymalloc
3062
    handled the request itself.
3063
p[2*S+n: 2*S+n+S]
3064
    Copies of PYMEM_FORBIDDENBYTE.  Used to catch over- writes and reads.
3065
p[2*S+n+S: 2*S+n+2*S]
3066
    A serial number, incremented by 1 on each call to _PyMem_DebugMalloc
3067
    and _PyMem_DebugRealloc.
3068
    This is a big-endian size_t.
3069
    If "bad memory" is detected later, the serial number gives an
3070
    excellent way to set a breakpoint on the next run, to capture the
3071
    instant at which this block was passed out.
3072
3073
If PYMEM_DEBUG_SERIALNO is not defined (default), the debug malloc only asks
3074
for 3 * S extra bytes, and omits the last serialno field.
3075
*/
3076
3077
static void *
3078
_PyMem_DebugRawAlloc(int use_calloc, void *ctx, size_t nbytes)
3079
0
{
3080
0
    debug_alloc_api_t *api = (debug_alloc_api_t *)ctx;
3081
0
    uint8_t *p;           /* base address of malloc'ed pad block */
3082
0
    uint8_t *data;        /* p + 2*SST == pointer to data bytes */
3083
0
    uint8_t *tail;        /* data + nbytes == pointer to tail pad bytes */
3084
0
    size_t total;         /* nbytes + PYMEM_DEBUG_EXTRA_BYTES */
3085
3086
0
    if (nbytes > (size_t)PY_SSIZE_T_MAX - PYMEM_DEBUG_EXTRA_BYTES) {
3087
        /* integer overflow: can't represent total as a Py_ssize_t */
3088
0
        return NULL;
3089
0
    }
3090
0
    total = nbytes + PYMEM_DEBUG_EXTRA_BYTES;
3091
3092
    /* Layout: [SSSS IFFF CCCC...CCCC FFFF NNNN]
3093
                ^--- p    ^--- data   ^--- tail
3094
       S: nbytes stored as size_t
3095
       I: API identifier (1 byte)
3096
       F: Forbidden bytes (size_t - 1 bytes before, size_t bytes after)
3097
       C: Clean bytes used later to store actual data
3098
       N: Serial number stored as size_t
3099
3100
       If PYMEM_DEBUG_SERIALNO is not defined (default), the last NNNN field
3101
       is omitted. */
3102
3103
0
    if (use_calloc) {
3104
0
        p = (uint8_t *)api->alloc.calloc(api->alloc.ctx, 1, total);
3105
0
    }
3106
0
    else {
3107
0
        p = (uint8_t *)api->alloc.malloc(api->alloc.ctx, total);
3108
0
    }
3109
0
    if (p == NULL) {
3110
0
        return NULL;
3111
0
    }
3112
0
    data = p + 2*SST;
3113
3114
#ifdef PYMEM_DEBUG_SERIALNO
3115
    bumpserialno();
3116
#endif
3117
3118
    /* at p, write size (SST bytes), id (1 byte), pad (SST-1 bytes) */
3119
0
    write_size_t(p, nbytes);
3120
0
    p[SST] = (uint8_t)api->api_id;
3121
0
    memset(p + SST + 1, PYMEM_FORBIDDENBYTE, SST-1);
3122
3123
0
    if (nbytes > 0 && !use_calloc) {
3124
0
        fill_mem_debug(api, data, PYMEM_CLEANBYTE, nbytes, true);
3125
0
    }
3126
3127
    /* at tail, write pad (SST bytes) and serialno (SST bytes) */
3128
0
    tail = data + nbytes;
3129
0
    memset(tail, PYMEM_FORBIDDENBYTE, SST);
3130
#ifdef PYMEM_DEBUG_SERIALNO
3131
    write_size_t(tail + SST, serialno);
3132
#endif
3133
3134
0
    return data;
3135
0
}
3136
3137
void *
3138
_PyMem_DebugRawMalloc(void *ctx, size_t nbytes)
3139
0
{
3140
0
    return _PyMem_DebugRawAlloc(0, ctx, nbytes);
3141
0
}
3142
3143
void *
3144
_PyMem_DebugRawCalloc(void *ctx, size_t nelem, size_t elsize)
3145
0
{
3146
0
    size_t nbytes;
3147
0
    assert(elsize == 0 || nelem <= (size_t)PY_SSIZE_T_MAX / elsize);
3148
0
    nbytes = nelem * elsize;
3149
0
    return _PyMem_DebugRawAlloc(1, ctx, nbytes);
3150
0
}
3151
3152
3153
/* The debug free first checks the 2*SST bytes on each end for sanity (in
3154
   particular, that the FORBIDDENBYTEs with the api ID are still intact).
3155
   Then fills the original bytes with PYMEM_DEADBYTE.
3156
   Then calls the underlying free.
3157
*/
3158
void
3159
_PyMem_DebugRawFree(void *ctx, void *p)
3160
0
{
3161
    /* PyMem_Free(NULL) has no effect */
3162
0
    if (p == NULL) {
3163
0
        return;
3164
0
    }
3165
3166
0
    debug_alloc_api_t *api = (debug_alloc_api_t *)ctx;
3167
0
    uint8_t *q = (uint8_t *)p - 2*SST;  /* address returned from malloc */
3168
0
    size_t nbytes;
3169
3170
0
    _PyMem_DebugCheckAddress(__func__, api->api_id, p);
3171
0
    nbytes = read_size_t(q);
3172
0
    nbytes += PYMEM_DEBUG_EXTRA_BYTES - 2*SST;
3173
0
    memset(q, PYMEM_DEADBYTE, 2*SST);
3174
0
    fill_mem_debug(api, p, PYMEM_DEADBYTE, nbytes, false);
3175
0
    api->alloc.free(api->alloc.ctx, q);
3176
0
}
3177
3178
3179
void *
3180
_PyMem_DebugRawRealloc(void *ctx, void *p, size_t nbytes)
3181
0
{
3182
0
    if (p == NULL) {
3183
0
        return _PyMem_DebugRawAlloc(0, ctx, nbytes);
3184
0
    }
3185
3186
0
    debug_alloc_api_t *api = (debug_alloc_api_t *)ctx;
3187
0
    uint8_t *head;        /* base address of malloc'ed pad block */
3188
0
    uint8_t *data;        /* pointer to data bytes */
3189
0
    uint8_t *r;
3190
0
    uint8_t *tail;        /* data + nbytes == pointer to tail pad bytes */
3191
0
    size_t total;         /* 2 * SST + nbytes + 2 * SST */
3192
0
    size_t original_nbytes;
3193
0
#define ERASED_SIZE 64
3194
3195
0
    _PyMem_DebugCheckAddress(__func__, api->api_id, p);
3196
3197
0
    data = (uint8_t *)p;
3198
0
    head = data - 2*SST;
3199
0
    original_nbytes = read_size_t(head);
3200
0
    if (nbytes > (size_t)PY_SSIZE_T_MAX - PYMEM_DEBUG_EXTRA_BYTES) {
3201
        /* integer overflow: can't represent total as a Py_ssize_t */
3202
0
        return NULL;
3203
0
    }
3204
0
    total = nbytes + PYMEM_DEBUG_EXTRA_BYTES;
3205
3206
0
    tail = data + original_nbytes;
3207
#ifdef PYMEM_DEBUG_SERIALNO
3208
    size_t block_serialno = read_size_t(tail + SST);
3209
#endif
3210
0
#ifndef Py_GIL_DISABLED
3211
    /* Mark the header, the trailer, ERASED_SIZE bytes at the begin and
3212
       ERASED_SIZE bytes at the end as dead and save the copy of erased bytes.
3213
     */
3214
0
    uint8_t save[2*ERASED_SIZE];  /* A copy of erased bytes. */
3215
0
    if (original_nbytes <= sizeof(save)) {
3216
0
        memcpy(save, data, original_nbytes);
3217
0
        memset(data - 2 * SST, PYMEM_DEADBYTE,
3218
0
               original_nbytes + PYMEM_DEBUG_EXTRA_BYTES);
3219
0
    }
3220
0
    else {
3221
0
        memcpy(save, data, ERASED_SIZE);
3222
0
        memset(head, PYMEM_DEADBYTE, ERASED_SIZE + 2 * SST);
3223
0
        memcpy(&save[ERASED_SIZE], tail - ERASED_SIZE, ERASED_SIZE);
3224
0
        memset(tail - ERASED_SIZE, PYMEM_DEADBYTE,
3225
0
               ERASED_SIZE + PYMEM_DEBUG_EXTRA_BYTES - 2 * SST);
3226
0
    }
3227
0
#endif
3228
3229
    /* Resize and add decorations. */
3230
0
    r = (uint8_t *)api->alloc.realloc(api->alloc.ctx, head, total);
3231
0
    if (r == NULL) {
3232
        /* if realloc() failed: rewrite header and footer which have
3233
           just been erased */
3234
0
        nbytes = original_nbytes;
3235
0
    }
3236
0
    else {
3237
0
        head = r;
3238
#ifdef PYMEM_DEBUG_SERIALNO
3239
        bumpserialno();
3240
        block_serialno = serialno;
3241
#endif
3242
0
    }
3243
0
    data = head + 2*SST;
3244
3245
0
    write_size_t(head, nbytes);
3246
0
    head[SST] = (uint8_t)api->api_id;
3247
0
    memset(head + SST + 1, PYMEM_FORBIDDENBYTE, SST-1);
3248
3249
0
    tail = data + nbytes;
3250
0
    memset(tail, PYMEM_FORBIDDENBYTE, SST);
3251
#ifdef PYMEM_DEBUG_SERIALNO
3252
    write_size_t(tail + SST, block_serialno);
3253
#endif
3254
3255
0
#ifndef Py_GIL_DISABLED
3256
    /* Restore saved bytes. */
3257
0
    if (original_nbytes <= sizeof(save)) {
3258
0
        memcpy(data, save, Py_MIN(nbytes, original_nbytes));
3259
0
    }
3260
0
    else {
3261
0
        size_t i = original_nbytes - ERASED_SIZE;
3262
0
        memcpy(data, save, Py_MIN(nbytes, (size_t)ERASED_SIZE));
3263
0
        if (nbytes > i) {
3264
0
            memcpy(data + i, &save[ERASED_SIZE],
3265
0
                   Py_MIN(nbytes - i, (size_t)ERASED_SIZE));
3266
0
        }
3267
0
    }
3268
0
#endif
3269
3270
0
    if (r == NULL) {
3271
0
        return NULL;
3272
0
    }
3273
3274
0
    if (nbytes > original_nbytes) {
3275
        /* growing: mark new extra memory clean */
3276
0
        memset(data + original_nbytes, PYMEM_CLEANBYTE,
3277
0
               nbytes - original_nbytes);
3278
0
    }
3279
3280
0
    return data;
3281
0
}
3282
3283
static inline void
3284
_PyMem_DebugCheckGIL(const char *func)
3285
0
{
3286
0
    PyThreadState *tstate = _PyThreadState_GET();
3287
0
    if (tstate == NULL) {
3288
0
#ifndef Py_GIL_DISABLED
3289
0
        _Py_FatalErrorFunc(func,
3290
0
                           "Python memory allocator called "
3291
0
                           "without holding the GIL");
3292
#else
3293
        _Py_FatalErrorFunc(func,
3294
                           "Python memory allocator called "
3295
                           "without an active thread state. "
3296
                           "Are you trying to call it inside of a Py_BEGIN_ALLOW_THREADS block?");
3297
#endif
3298
0
    }
3299
0
}
3300
3301
void *
3302
_PyMem_DebugMalloc(void *ctx, size_t nbytes)
3303
0
{
3304
0
    _PyMem_DebugCheckGIL(__func__);
3305
0
    return _PyMem_DebugRawMalloc(ctx, nbytes);
3306
0
}
3307
3308
void *
3309
_PyMem_DebugCalloc(void *ctx, size_t nelem, size_t elsize)
3310
0
{
3311
0
    _PyMem_DebugCheckGIL(__func__);
3312
0
    return _PyMem_DebugRawCalloc(ctx, nelem, elsize);
3313
0
}
3314
3315
3316
void
3317
_PyMem_DebugFree(void *ctx, void *ptr)
3318
0
{
3319
0
    _PyMem_DebugCheckGIL(__func__);
3320
0
    _PyMem_DebugRawFree(ctx, ptr);
3321
0
}
3322
3323
3324
void *
3325
_PyMem_DebugRealloc(void *ctx, void *ptr, size_t nbytes)
3326
0
{
3327
0
    _PyMem_DebugCheckGIL(__func__);
3328
0
    return _PyMem_DebugRawRealloc(ctx, ptr, nbytes);
3329
0
}
3330
3331
/* Check the forbidden bytes on both ends of the memory allocated for p.
3332
 * If anything is wrong, print info to stderr via _PyObject_DebugDumpAddress,
3333
 * and call Py_FatalError to kill the program.
3334
 * The API id, is also checked.
3335
 */
3336
static void
3337
_PyMem_DebugCheckAddress(const char *func, char api, const void *p)
3338
0
{
3339
0
    assert(p != NULL);
3340
3341
0
    const uint8_t *q = (const uint8_t *)p;
3342
0
    size_t nbytes;
3343
0
    const uint8_t *tail;
3344
0
    int i;
3345
0
    char id;
3346
3347
    /* Check the API id */
3348
0
    id = (char)q[-SST];
3349
0
    if (id != api) {
3350
0
        _PyObject_DebugDumpAddress(p);
3351
0
        _Py_FatalErrorFormat(func,
3352
0
                             "bad ID: Allocated using API '%c', "
3353
0
                             "verified using API '%c'",
3354
0
                             id, api);
3355
0
    }
3356
3357
    /* Check the stuff at the start of p first:  if there's underwrite
3358
     * corruption, the number-of-bytes field may be nuts, and checking
3359
     * the tail could lead to a segfault then.
3360
     */
3361
0
    for (i = SST-1; i >= 1; --i) {
3362
0
        if (*(q-i) != PYMEM_FORBIDDENBYTE) {
3363
0
            _PyObject_DebugDumpAddress(p);
3364
0
            _Py_FatalErrorFunc(func, "bad leading pad byte");
3365
0
        }
3366
0
    }
3367
3368
0
    nbytes = read_size_t(q - 2*SST);
3369
0
    tail = q + nbytes;
3370
0
    for (i = 0; i < SST; ++i) {
3371
0
        if (tail[i] != PYMEM_FORBIDDENBYTE) {
3372
0
            _PyObject_DebugDumpAddress(p);
3373
0
            _Py_FatalErrorFunc(func, "bad trailing pad byte");
3374
0
        }
3375
0
    }
3376
0
}
3377
3378
/* Display info to stderr about the memory block at p. */
3379
static void
3380
_PyObject_DebugDumpAddress(const void *p)
3381
0
{
3382
0
    const uint8_t *q = (const uint8_t *)p;
3383
0
    const uint8_t *tail;
3384
0
    size_t nbytes;
3385
0
    int i;
3386
0
    int ok;
3387
0
    char id;
3388
3389
0
    fprintf(stderr, "Debug memory block at address p=%p:", p);
3390
0
    if (p == NULL) {
3391
0
        fprintf(stderr, "\n");
3392
0
        return;
3393
0
    }
3394
0
    id = (char)q[-SST];
3395
0
    fprintf(stderr, " API '%c'\n", id);
3396
3397
0
    nbytes = read_size_t(q - 2*SST);
3398
0
    fprintf(stderr, "    %zu bytes originally requested\n", nbytes);
3399
3400
    /* In case this is nuts, check the leading pad bytes first. */
3401
0
    fprintf(stderr, "    The %d pad bytes at p-%d are ", SST-1, SST-1);
3402
0
    ok = 1;
3403
0
    for (i = 1; i <= SST-1; ++i) {
3404
0
        if (*(q-i) != PYMEM_FORBIDDENBYTE) {
3405
0
            ok = 0;
3406
0
            break;
3407
0
        }
3408
0
    }
3409
0
    if (ok)
3410
0
        fputs("FORBIDDENBYTE, as expected.\n", stderr);
3411
0
    else {
3412
0
        fprintf(stderr, "not all FORBIDDENBYTE (0x%02x):\n",
3413
0
            PYMEM_FORBIDDENBYTE);
3414
0
        for (i = SST-1; i >= 1; --i) {
3415
0
            const uint8_t byte = *(q-i);
3416
0
            fprintf(stderr, "        at p-%d: 0x%02x", i, byte);
3417
0
            if (byte != PYMEM_FORBIDDENBYTE)
3418
0
                fputs(" *** OUCH", stderr);
3419
0
            fputc('\n', stderr);
3420
0
        }
3421
3422
0
        fputs("    Because memory is corrupted at the start, the "
3423
0
              "count of bytes requested\n"
3424
0
              "       may be bogus, and checking the trailing pad "
3425
0
              "bytes may segfault.\n", stderr);
3426
0
    }
3427
3428
0
    tail = q + nbytes;
3429
0
    fprintf(stderr, "    The %d pad bytes at tail=%p are ", SST, (void *)tail);
3430
0
    ok = 1;
3431
0
    for (i = 0; i < SST; ++i) {
3432
0
        if (tail[i] != PYMEM_FORBIDDENBYTE) {
3433
0
            ok = 0;
3434
0
            break;
3435
0
        }
3436
0
    }
3437
0
    if (ok)
3438
0
        fputs("FORBIDDENBYTE, as expected.\n", stderr);
3439
0
    else {
3440
0
        fprintf(stderr, "not all FORBIDDENBYTE (0x%02x):\n",
3441
0
                PYMEM_FORBIDDENBYTE);
3442
0
        for (i = 0; i < SST; ++i) {
3443
0
            const uint8_t byte = tail[i];
3444
0
            fprintf(stderr, "        at tail+%d: 0x%02x",
3445
0
                    i, byte);
3446
0
            if (byte != PYMEM_FORBIDDENBYTE)
3447
0
                fputs(" *** OUCH", stderr);
3448
0
            fputc('\n', stderr);
3449
0
        }
3450
0
    }
3451
3452
#ifdef PYMEM_DEBUG_SERIALNO
3453
    size_t serial = read_size_t(tail + SST);
3454
    fprintf(stderr,
3455
            "    The block was made by call #%zu to debug malloc/realloc.\n",
3456
            serial);
3457
#endif
3458
3459
0
    if (nbytes > 0) {
3460
0
        i = 0;
3461
0
        fputs("    Data at p:", stderr);
3462
        /* print up to 8 bytes at the start */
3463
0
        while (q < tail && i < 8) {
3464
0
            fprintf(stderr, " %02x", *q);
3465
0
            ++i;
3466
0
            ++q;
3467
0
        }
3468
        /* and up to 8 at the end */
3469
0
        if (q < tail) {
3470
0
            if (tail - q > 8) {
3471
0
                fputs(" ...", stderr);
3472
0
                q = tail - 8;
3473
0
            }
3474
0
            while (q < tail) {
3475
0
                fprintf(stderr, " %02x", *q);
3476
0
                ++q;
3477
0
            }
3478
0
        }
3479
0
        fputc('\n', stderr);
3480
0
    }
3481
0
    fputc('\n', stderr);
3482
3483
0
    fflush(stderr);
3484
0
    _PyMem_DumpTraceback(fileno(stderr), p);
3485
0
}
3486
3487
3488
static size_t
3489
printone(FILE *out, const char* msg, size_t value)
3490
0
{
3491
0
    int i, k;
3492
0
    char buf[100];
3493
0
    size_t origvalue = value;
3494
3495
0
    fputs(msg, out);
3496
0
    for (i = (int)strlen(msg); i < 35; ++i)
3497
0
        fputc(' ', out);
3498
0
    fputc('=', out);
3499
3500
    /* Write the value with commas. */
3501
0
    i = 22;
3502
0
    buf[i--] = '\0';
3503
0
    buf[i--] = '\n';
3504
0
    k = 3;
3505
0
    do {
3506
0
        size_t nextvalue = value / 10;
3507
0
        unsigned int digit = (unsigned int)(value - nextvalue * 10);
3508
0
        value = nextvalue;
3509
0
        buf[i--] = (char)(digit + '0');
3510
0
        --k;
3511
0
        if (k == 0 && value && i >= 0) {
3512
0
            k = 3;
3513
0
            buf[i--] = ',';
3514
0
        }
3515
0
    } while (value && i >= 0);
3516
3517
0
    while (i >= 0)
3518
0
        buf[i--] = ' ';
3519
0
    fputs(buf, out);
3520
3521
0
    return origvalue;
3522
0
}
3523
3524
void
3525
_PyDebugAllocatorStats(FILE *out,
3526
                       const char *block_name, int num_blocks, size_t sizeof_block)
3527
0
{
3528
0
    char buf1[128];
3529
0
    char buf2[128];
3530
0
    PyOS_snprintf(buf1, sizeof(buf1),
3531
0
                  "%d %ss * %zd bytes each",
3532
0
                  num_blocks, block_name, sizeof_block);
3533
0
    PyOS_snprintf(buf2, sizeof(buf2),
3534
0
                  "%48s ", buf1);
3535
0
    (void)printone(out, buf2, num_blocks * sizeof_block);
3536
0
}
3537
3538
// Return true if the obmalloc state structure is heap allocated,
3539
// by PyMem_RawCalloc().  For the main interpreter, this structure
3540
// allocated in the BSS.  Allocating that way gives some memory savings
3541
// and a small performance win (at least on a demand paged OS).  On
3542
// 64-bit platforms, the obmalloc structure is 256 kB. Most of that
3543
// memory is for the arena_map_top array.  Since normally only one entry
3544
// of that array is used, only one page of resident memory is actually
3545
// used, rather than the full 256 kB.
3546
bool _PyMem_obmalloc_state_on_heap(PyInterpreterState *interp)
3547
0
{
3548
0
#if WITH_PYMALLOC
3549
0
    return interp->obmalloc && interp->obmalloc != &obmalloc_state_main;
3550
#else
3551
    return false;
3552
#endif
3553
0
}
3554
3555
#ifdef WITH_PYMALLOC
3556
static void
3557
init_obmalloc_pools(PyInterpreterState *interp)
3558
22
{
3559
    // initialize the obmalloc->pools structure.  This must be done
3560
    // before the obmalloc alloc/free functions can be called.
3561
22
    poolp temp[OBMALLOC_USED_POOLS_SIZE] =
3562
22
        _obmalloc_pools_INIT(interp->obmalloc->pools);
3563
22
    memcpy(&interp->obmalloc->pools.used, temp, sizeof(temp));
3564
22
}
3565
#endif /* WITH_PYMALLOC */
3566
3567
int _PyMem_init_obmalloc(PyInterpreterState *interp)
3568
22
{
3569
22
#ifdef WITH_PYMALLOC
3570
    /* Initialize obmalloc, but only for subinterpreters,
3571
       since the main interpreter is initialized statically. */
3572
22
    if (_Py_IsMainInterpreter(interp)
3573
0
            || _PyInterpreterState_HasFeature(interp,
3574
22
                                              Py_RTFLAGS_USE_MAIN_OBMALLOC)) {
3575
22
        interp->obmalloc = &obmalloc_state_main;
3576
22
        if (!obmalloc_state_initialized) {
3577
22
            init_obmalloc_pools(interp);
3578
22
            obmalloc_state_initialized = true;
3579
22
        }
3580
22
    } else {
3581
0
        interp->obmalloc = PyMem_RawCalloc(1, sizeof(struct _obmalloc_state));
3582
0
        if (interp->obmalloc == NULL) {
3583
0
            return -1;
3584
0
        }
3585
0
        init_obmalloc_pools(interp);
3586
0
    }
3587
22
#endif /* WITH_PYMALLOC */
3588
22
    return 0; // success
3589
22
}
3590
3591
3592
#ifdef WITH_PYMALLOC
3593
3594
static void
3595
free_obmalloc_arenas(PyInterpreterState *interp)
3596
0
{
3597
0
    OMState *state = interp->obmalloc;
3598
0
    for (uint i = 0; i < maxarenas; ++i) {
3599
        // free each obmalloc memory arena
3600
0
        struct arena_object *ao = &allarenas[i];
3601
0
        _PyObject_Arena.free(_PyObject_Arena.ctx,
3602
0
                             (void *)ao->address, ARENA_SIZE);
3603
0
    }
3604
    // free the array containing pointers to all arenas
3605
0
    PyMem_RawFree(allarenas);
3606
0
#if WITH_PYMALLOC_RADIX_TREE
3607
0
#ifdef USE_INTERIOR_NODES
3608
    // Free the middle and bottom nodes of the radix tree.  These are allocated
3609
    // by arena_map_mark_used() but not freed when arenas are freed.
3610
0
    for (int i1 = 0; i1 < MAP_TOP_LENGTH; i1++) {
3611
0
         arena_map_mid_t *mid = arena_map_root.ptrs[i1];
3612
0
         if (mid == NULL) {
3613
0
             continue;
3614
0
         }
3615
0
         for (int i2 = 0; i2 < MAP_MID_LENGTH; i2++) {
3616
0
            arena_map_bot_t *bot = arena_map_root.ptrs[i1]->ptrs[i2];
3617
0
            if (bot == NULL) {
3618
0
                continue;
3619
0
            }
3620
0
            PyMem_RawFree(bot);
3621
0
         }
3622
0
         PyMem_RawFree(mid);
3623
0
    }
3624
0
#endif
3625
0
#endif
3626
0
}
3627
3628
#ifdef Py_DEBUG
3629
/* Is target in the list?  The list is traversed via the nextpool pointers.
3630
 * The list may be NULL-terminated, or circular.  Return 1 if target is in
3631
 * list, else 0.
3632
 */
3633
static int
3634
pool_is_in_list(const poolp target, poolp list)
3635
{
3636
    poolp origlist = list;
3637
    assert(target != NULL);
3638
    if (list == NULL)
3639
        return 0;
3640
    do {
3641
        if (target == list)
3642
            return 1;
3643
        list = list->nextpool;
3644
    } while (list != NULL && list != origlist);
3645
    return 0;
3646
}
3647
#endif
3648
3649
#ifdef WITH_MIMALLOC
3650
struct _alloc_stats {
3651
    size_t allocated_blocks;
3652
    size_t allocated_bytes;
3653
    size_t allocated_with_overhead;
3654
    size_t bytes_reserved;
3655
    size_t bytes_committed;
3656
};
3657
3658
static bool _collect_alloc_stats(
3659
    const mi_heap_t* heap, const mi_heap_area_t* area,
3660
    void* block, size_t block_size, void* arg)
3661
0
{
3662
0
    struct _alloc_stats *stats = (struct _alloc_stats *)arg;
3663
0
    stats->allocated_blocks += area->used;
3664
0
    stats->allocated_bytes += area->used * area->block_size;
3665
0
    stats->allocated_with_overhead += area->used * area->full_block_size;
3666
0
    stats->bytes_reserved += area->reserved;
3667
0
    stats->bytes_committed += area->committed;
3668
0
    return 1;
3669
0
}
3670
3671
static void
3672
py_mimalloc_print_stats(FILE *out)
3673
0
{
3674
0
    fprintf(out, "Small block threshold = %zu, in %u size classes.\n",
3675
0
        (size_t)MI_SMALL_OBJ_SIZE_MAX, MI_BIN_HUGE);
3676
0
    fprintf(out, "Medium block threshold = %zu\n",
3677
0
            (size_t)MI_MEDIUM_OBJ_SIZE_MAX);
3678
0
    fprintf(out, "Large object max size = %zu\n",
3679
0
            (size_t)MI_LARGE_OBJ_SIZE_MAX);
3680
3681
0
    mi_heap_t *heap = mi_heap_get_default();
3682
0
    struct _alloc_stats stats;
3683
0
    memset(&stats, 0, sizeof(stats));
3684
0
    mi_heap_visit_blocks(heap, false, &_collect_alloc_stats, &stats);
3685
3686
0
    fprintf(out, "    Allocated Blocks: %zd\n", stats.allocated_blocks);
3687
0
    fprintf(out, "    Allocated Bytes: %zd\n", stats.allocated_bytes);
3688
0
    fprintf(out, "    Allocated Bytes w/ Overhead: %zd\n", stats.allocated_with_overhead);
3689
0
    fprintf(out, "    Bytes Reserved: %zd\n", stats.bytes_reserved);
3690
0
    fprintf(out, "    Bytes Committed: %zd\n", stats.bytes_committed);
3691
0
}
3692
#endif
3693
3694
3695
static void
3696
pymalloc_print_stats(FILE *out)
3697
0
{
3698
0
    OMState *state = get_state();
3699
3700
0
    uint i;
3701
0
    const uint numclasses = SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT;
3702
    /* # of pools, allocated blocks, and free blocks per class index */
3703
0
    size_t numpools[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT];
3704
0
    size_t numblocks[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT];
3705
0
    size_t numfreeblocks[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT];
3706
    /* total # of allocated bytes in used and full pools */
3707
0
    size_t allocated_bytes = 0;
3708
    /* total # of available bytes in used pools */
3709
0
    size_t available_bytes = 0;
3710
    /* # of free pools + pools not yet carved out of current arena */
3711
0
    uint numfreepools = 0;
3712
    /* # of bytes for arena alignment padding */
3713
0
    size_t arena_alignment = 0;
3714
    /* # of bytes in used and full pools used for pool_headers */
3715
0
    size_t pool_header_bytes = 0;
3716
    /* # of bytes in used and full pools wasted due to quantization,
3717
     * i.e. the necessarily leftover space at the ends of used and
3718
     * full pools.
3719
     */
3720
0
    size_t quantization = 0;
3721
    /* # of arenas actually allocated. */
3722
0
    size_t narenas = 0;
3723
    /* running total -- should equal narenas * ARENA_SIZE */
3724
0
    size_t total;
3725
0
    char buf[128];
3726
3727
0
    fprintf(out, "Small block threshold = %d, in %u size classes.\n",
3728
0
            SMALL_REQUEST_THRESHOLD, numclasses);
3729
3730
0
    for (i = 0; i < numclasses; ++i)
3731
0
        numpools[i] = numblocks[i] = numfreeblocks[i] = 0;
3732
3733
    /* Because full pools aren't linked to from anything, it's easiest
3734
     * to march over all the arenas.  If we're lucky, most of the memory
3735
     * will be living in full pools -- would be a shame to miss them.
3736
     */
3737
0
    for (i = 0; i < maxarenas; ++i) {
3738
0
        uintptr_t base = allarenas[i].address;
3739
3740
        /* Skip arenas which are not allocated. */
3741
0
        if (allarenas[i].address == (uintptr_t)NULL)
3742
0
            continue;
3743
0
        narenas += 1;
3744
3745
0
        numfreepools += allarenas[i].nfreepools;
3746
3747
        /* round up to pool alignment */
3748
0
        if (base & (uintptr_t)POOL_SIZE_MASK) {
3749
0
            arena_alignment += POOL_SIZE;
3750
0
            base &= ~(uintptr_t)POOL_SIZE_MASK;
3751
0
            base += POOL_SIZE;
3752
0
        }
3753
3754
        /* visit every pool in the arena */
3755
0
        assert(base <= (uintptr_t) allarenas[i].pool_address);
3756
0
        for (; base < (uintptr_t) allarenas[i].pool_address; base += POOL_SIZE) {
3757
0
            poolp p = (poolp)base;
3758
0
            const uint sz = p->szidx;
3759
0
            uint freeblocks;
3760
3761
0
            if (p->ref.count == 0) {
3762
                /* currently unused */
3763
#ifdef Py_DEBUG
3764
                assert(pool_is_in_list(p, allarenas[i].freepools));
3765
#endif
3766
0
                continue;
3767
0
            }
3768
0
            ++numpools[sz];
3769
0
            numblocks[sz] += p->ref.count;
3770
0
            freeblocks = NUMBLOCKS(sz) - p->ref.count;
3771
0
            numfreeblocks[sz] += freeblocks;
3772
#ifdef Py_DEBUG
3773
            if (freeblocks > 0)
3774
                assert(pool_is_in_list(p, usedpools[sz + sz]));
3775
#endif
3776
0
        }
3777
0
    }
3778
0
    assert(narenas == narenas_currently_allocated);
3779
3780
0
    fputc('\n', out);
3781
0
    fputs("class   size   num pools   blocks in use  avail blocks\n"
3782
0
          "-----   ----   ---------   -------------  ------------\n",
3783
0
          out);
3784
3785
0
    for (i = 0; i < numclasses; ++i) {
3786
0
        size_t p = numpools[i];
3787
0
        size_t b = numblocks[i];
3788
0
        size_t f = numfreeblocks[i];
3789
0
        uint size = INDEX2SIZE(i);
3790
0
        if (p == 0) {
3791
0
            assert(b == 0 && f == 0);
3792
0
            continue;
3793
0
        }
3794
0
        fprintf(out, "%5u %6u %11zu %15zu %13zu\n",
3795
0
                i, size, p, b, f);
3796
0
        allocated_bytes += b * size;
3797
0
        available_bytes += f * size;
3798
0
        pool_header_bytes += p * POOL_OVERHEAD;
3799
0
        quantization += p * ((POOL_SIZE - POOL_OVERHEAD) % size);
3800
0
    }
3801
0
    fputc('\n', out);
3802
#ifdef PYMEM_DEBUG_SERIALNO
3803
    if (_PyMem_DebugEnabled()) {
3804
        (void)printone(out, "# times object malloc called", serialno);
3805
    }
3806
#endif
3807
0
    (void)printone(out, "# arenas allocated total", ntimes_arena_allocated);
3808
0
    (void)printone(out, "# arenas reclaimed", ntimes_arena_allocated - narenas);
3809
0
    (void)printone(out, "# arenas highwater mark", narenas_highwater);
3810
0
    (void)printone(out, "# arenas allocated current", narenas);
3811
3812
0
    PyOS_snprintf(buf, sizeof(buf),
3813
0
                  "%zu arenas * %d bytes/arena",
3814
0
                  narenas, ARENA_SIZE);
3815
0
    (void)printone(out, buf, narenas * ARENA_SIZE);
3816
3817
0
    fputc('\n', out);
3818
3819
    /* Account for what all of those arena bytes are being used for. */
3820
0
    total = printone(out, "# bytes in allocated blocks", allocated_bytes);
3821
0
    total += printone(out, "# bytes in available blocks", available_bytes);
3822
3823
0
    PyOS_snprintf(buf, sizeof(buf),
3824
0
        "%u unused pools * %d bytes", numfreepools, POOL_SIZE);
3825
0
    total += printone(out, buf, (size_t)numfreepools * POOL_SIZE);
3826
3827
0
    total += printone(out, "# bytes lost to pool headers", pool_header_bytes);
3828
0
    total += printone(out, "# bytes lost to quantization", quantization);
3829
0
    total += printone(out, "# bytes lost to arena alignment", arena_alignment);
3830
0
    (void)printone(out, "Total", total);
3831
0
    assert(narenas * ARENA_SIZE == total);
3832
3833
0
#if WITH_PYMALLOC_RADIX_TREE
3834
0
    fputs("\narena map counts\n", out);
3835
0
#ifdef USE_INTERIOR_NODES
3836
0
    (void)printone(out, "# arena map mid nodes", arena_map_mid_count);
3837
0
    (void)printone(out, "# arena map bot nodes", arena_map_bot_count);
3838
0
    fputc('\n', out);
3839
0
#endif
3840
0
    total = printone(out, "# bytes lost to arena map root", sizeof(arena_map_root));
3841
0
#ifdef USE_INTERIOR_NODES
3842
0
    total += printone(out, "# bytes lost to arena map mid",
3843
0
                      sizeof(arena_map_mid_t) * arena_map_mid_count);
3844
0
    total += printone(out, "# bytes lost to arena map bot",
3845
0
                      sizeof(arena_map_bot_t) * arena_map_bot_count);
3846
0
    (void)printone(out, "Total", total);
3847
0
#endif
3848
0
#endif
3849
3850
0
}
3851
3852
/* Print summary info to "out" about the state of pymalloc's structures.
3853
 * In Py_DEBUG mode, also perform some expensive internal consistency
3854
 * checks.
3855
 *
3856
 * Return 0 if the memory debug hooks are not installed or no statistics was
3857
 * written into out, return 1 otherwise.
3858
 */
3859
int
3860
_PyObject_DebugMallocStats(FILE *out)
3861
0
{
3862
0
#ifdef WITH_MIMALLOC
3863
0
    if (_PyMem_MimallocEnabled()) {
3864
0
        py_mimalloc_print_stats(out);
3865
0
        return 1;
3866
0
    }
3867
0
    else
3868
0
#endif
3869
0
    if (_PyMem_PymallocEnabled()) {
3870
0
        pymalloc_print_stats(out);
3871
0
        return 1;
3872
0
    }
3873
0
    else {
3874
0
        return 0;
3875
0
    }
3876
0
}
3877
3878
#endif /* #ifdef WITH_PYMALLOC */