Coverage Report

Created: 2026-10-31 06:21

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython/Objects/mimalloc/heap.c
Line
Count
Source
1
/*----------------------------------------------------------------------------
2
Copyright (c) 2018-2021, Microsoft Research, Daan Leijen
3
This is free software; you can redistribute it and/or modify it under the
4
terms of the MIT license. A copy of the license can be found in the file
5
"LICENSE" at the root of this distribution.
6
-----------------------------------------------------------------------------*/
7
8
#include "mimalloc.h"
9
#include "mimalloc/internal.h"
10
#include "mimalloc/atomic.h"
11
#include "mimalloc/prim.h"  // mi_prim_get_default_heap
12
13
#include <string.h>  // memset, memcpy
14
15
#if defined(_MSC_VER) && (_MSC_VER < 1920)
16
#pragma warning(disable:4204)  // non-constant aggregate initializer
17
#endif
18
19
/* -----------------------------------------------------------
20
  Helpers
21
----------------------------------------------------------- */
22
23
// return `true` if ok, `false` to break
24
typedef bool (heap_page_visitor_fun)(mi_heap_t* heap, mi_page_queue_t* pq, mi_page_t* page, void* arg1, void* arg2);
25
26
// Visit all pages in a heap; returns `false` if break was called.
27
static bool mi_heap_visit_pages(mi_heap_t* heap, heap_page_visitor_fun* fn, bool include_full, void* arg1, void* arg2)
28
0
{
29
0
  if (heap==NULL || heap->page_count==0) return true;
30
31
  // visit all pages
32
  #if MI_DEBUG>1
33
  size_t total = heap->page_count;
34
  size_t count = 0;
35
  #endif
36
37
0
  const size_t max_bin = (include_full ? MI_BIN_FULL : MI_BIN_FULL - 1);
38
0
  for (size_t i = 0; i <= max_bin; i++) {
39
0
    mi_page_queue_t* pq = &heap->pages[i];
40
0
    mi_page_t* page = pq->first;
41
0
    while(page != NULL) {
42
0
      mi_page_t* next = page->next; // save next in case the page gets removed from the queue
43
0
      mi_assert_internal(mi_page_heap(page) == heap);
44
      #if MI_DEBUG>1
45
      count++;
46
      #endif
47
0
      if (!fn(heap, pq, page, arg1, arg2)) return false;
48
0
      page = next; // and continue
49
0
    }
50
0
  }
51
0
  mi_assert_internal(!include_full || count == total);
52
0
  return true;
53
0
}
54
55
56
#if MI_DEBUG>=2
57
static bool mi_heap_page_is_valid(mi_heap_t* heap, mi_page_queue_t* pq, mi_page_t* page, void* arg1, void* arg2) {
58
  MI_UNUSED(arg1);
59
  MI_UNUSED(arg2);
60
  MI_UNUSED(pq);
61
  mi_assert_internal(mi_page_heap(page) == heap);
62
  mi_segment_t* segment = _mi_page_segment(page);
63
  mi_assert_internal(mi_atomic_load_relaxed(&segment->thread_id) == heap->thread_id);
64
  mi_assert_expensive(_mi_page_is_valid(page));
65
  return true;
66
}
67
#endif
68
#if MI_DEBUG>=3
69
static bool mi_heap_is_valid(mi_heap_t* heap) {
70
  mi_assert_internal(heap!=NULL);
71
  mi_heap_visit_pages(heap, &mi_heap_page_is_valid, true, NULL, NULL);
72
  return true;
73
}
74
#endif
75
76
77
78
79
/* -----------------------------------------------------------
80
  "Collect" pages by migrating `local_free` and `thread_free`
81
  lists and freeing empty pages. This is done when a thread
82
  stops (and in that case abandons pages if there are still
83
  blocks alive)
84
----------------------------------------------------------- */
85
86
typedef enum mi_collect_e {
87
  MI_NORMAL,
88
  MI_FORCE,
89
  MI_ABANDON
90
} mi_collect_t;
91
92
93
0
static bool mi_heap_page_collect(mi_heap_t* heap, mi_page_queue_t* pq, mi_page_t* page, void* arg_collect, void* arg2 ) {
94
0
  MI_UNUSED(arg2);
95
0
  MI_UNUSED(heap);
96
0
  mi_assert_internal(mi_heap_page_is_valid(heap, pq, page, NULL, NULL));
97
0
  mi_collect_t collect = *((mi_collect_t*)arg_collect);
98
0
  _mi_page_free_collect(page, collect >= MI_FORCE);
99
0
  if (collect == MI_FORCE) {
100
    // note: call before a potential `_mi_page_free` as the segment may be freed if this was the last used page in that segment.
101
0
    mi_segment_t* segment = _mi_page_segment(page);
102
0
    _mi_segment_collect(segment, true /* force? */);
103
0
  }
104
0
  if (mi_page_all_free(page)) {
105
    // no more used blocks, free the page.
106
    // note: this will free retired pages as well.
107
0
    bool freed = _PyMem_mi_page_maybe_free(page, pq, collect >= MI_FORCE);
108
0
    if (!freed && collect == MI_ABANDON) {
109
      // CPython: _PyMem_mi_page_maybe_free may have moved the page to a different
110
      // page queue, so we need to re-fetch the correct queue.
111
0
      size_t bin = (mi_page_is_in_full(page) ? MI_BIN_FULL : _mi_bin(mi_page_block_size(page)));
112
0
      _mi_page_abandon(page, &heap->pages[bin]);
113
0
    }
114
0
  }
115
0
  else if (collect == MI_ABANDON) {
116
    // still used blocks but the thread is done; abandon the page
117
0
    _mi_page_abandon(page, pq);
118
0
  }
119
0
  return true; // don't break
120
0
}
121
122
0
static bool mi_heap_page_never_delayed_free(mi_heap_t* heap, mi_page_queue_t* pq, mi_page_t* page, void* arg1, void* arg2) {
123
0
  MI_UNUSED(arg1);
124
0
  MI_UNUSED(arg2);
125
0
  MI_UNUSED(heap);
126
0
  MI_UNUSED(pq);
127
0
  _mi_page_use_delayed_free(page, MI_NEVER_DELAYED_FREE, false);
128
0
  return true; // don't break
129
0
}
130
131
static void mi_heap_collect_ex(mi_heap_t* heap, mi_collect_t collect)
132
0
{
133
0
  if (heap==NULL || !mi_heap_is_initialized(heap)) return;
134
135
0
  const bool force = (collect >= MI_FORCE);
136
0
  _mi_deferred_free(heap, force);
137
138
  // python/cpython#112532: we may be called from a thread that is not the owner of the heap
139
0
  const bool is_main_thread = (_mi_is_main_thread() && heap->thread_id == _mi_thread_id());
140
141
  // note: never reclaim on collect but leave it to threads that need storage to reclaim
142
0
  const bool force_main =
143
0
    #ifdef NDEBUG
144
0
      collect == MI_FORCE
145
    #else
146
      collect >= MI_FORCE
147
    #endif
148
0
      && is_main_thread && mi_heap_is_backing(heap) && !heap->no_reclaim;
149
150
0
  if (force_main) {
151
    // the main thread is abandoned (end-of-program), try to reclaim all abandoned segments.
152
    // if all memory is freed by now, all segments should be freed.
153
    // note: this only collects in the current subprocess
154
0
    _mi_abandoned_reclaim_all(heap, &heap->tld->segments);
155
0
  }
156
157
  // if abandoning, mark all pages to no longer add to delayed_free
158
0
  if (collect == MI_ABANDON) {
159
0
    mi_heap_visit_pages(heap, &mi_heap_page_never_delayed_free, true, NULL, NULL);
160
0
  }
161
162
  // free all current thread delayed blocks.
163
  // (if abandoning, after this there are no more thread-delayed references into the pages.)
164
0
  if (collect >= MI_ABANDON) {
165
0
    _mi_heap_delayed_free_all(heap);      // free all
166
0
  } else {
167
0
    _mi_heap_delayed_free_partial(heap);  // best-effort; contended blocks are retried next time
168
0
  }
169
170
  // collect retired pages
171
0
  _mi_heap_collect_retired(heap, force);
172
173
  // CPython: free pages that were delayed with QSBR
174
0
  _PyMem_mi_heap_collect_qsbr(heap);
175
176
  // collect all pages owned by this thread
177
0
  mi_heap_visit_pages(heap, &mi_heap_page_collect, (collect!=MI_NORMAL), &collect, NULL); // normally don't visit full pages, issue #1220
178
0
  mi_assert_internal( collect != MI_ABANDON || mi_atomic_load_ptr_acquire(mi_block_t,&heap->thread_delayed_free) == NULL );
179
180
  // collect abandoned segments (in particular, purge expired parts of segments in the abandoned segment list)
181
  // note: forced purge can be quite expensive if many threads are created/destroyed so we do not force on abandonment
182
0
  _mi_abandoned_collect(heap, collect == MI_FORCE /* force? */, &heap->tld->segments);
183
184
  // if forced, collect thread data cache on program-exit (or shared library unload)
185
0
  if (force && is_main_thread && mi_heap_is_backing(heap)) {
186
0
    _mi_thread_data_collect();  // collect thread data cache
187
0
  }
188
189
  // collect arenas (this is program wide so don't force purges on abandonment of threads)
190
0
  _mi_arenas_collect(collect == MI_FORCE /* force purge? */);
191
192
  // merge statistics
193
0
  if (collect <= MI_FORCE) { _mi_stats_merge_thread(heap->tld); }
194
0
}
195
196
0
void _mi_heap_collect_abandon(mi_heap_t* heap) {
197
0
  mi_heap_collect_ex(heap, MI_ABANDON);
198
0
}
199
200
0
void mi_heap_collect(mi_heap_t* heap, bool force) mi_attr_noexcept {
201
0
  mi_heap_collect_ex(heap, (force ? MI_FORCE : MI_NORMAL));
202
0
}
203
204
0
void mi_collect(bool force) mi_attr_noexcept {
205
0
  mi_heap_collect(mi_prim_get_default_heap(), force);
206
0
}
207
208
209
/* -----------------------------------------------------------
210
  Heap new
211
----------------------------------------------------------- */
212
213
37
mi_heap_t* mi_heap_get_default(void) {
214
37
  mi_thread_init();
215
37
  return mi_prim_get_default_heap();
216
37
}
217
218
0
static bool mi_heap_is_default(const mi_heap_t* heap) {
219
0
  return (heap == mi_prim_get_default_heap());
220
0
}
221
222
223
0
mi_heap_t* mi_heap_get_backing(void) {
224
0
  mi_heap_t* heap = mi_heap_get_default();
225
0
  mi_assert_internal(heap!=NULL);
226
0
  mi_heap_t* bheap = heap->tld->heap_backing;
227
0
  mi_assert_internal(bheap!=NULL);
228
0
  mi_assert_internal(bheap->thread_id == _mi_thread_id());
229
0
  return bheap;
230
0
}
231
232
0
void _mi_heap_init(mi_heap_t* heap, mi_tld_t* tld, mi_arena_id_t arena_id, bool noreclaim, uint8_t tag) {
233
0
  _mi_memcpy_aligned(heap, &_mi_heap_empty, sizeof(mi_heap_t));
234
0
  heap->tld = tld;
235
0
  heap->thread_id  = _mi_thread_id();
236
0
  heap->arena_id   = arena_id;
237
0
  heap->no_reclaim = noreclaim;
238
0
  heap->tag        = tag;
239
0
  if (heap == tld->heap_backing) {
240
    #if defined(_WIN32) && !defined(MI_SHARED_LIB)
241
      _mi_random_init_weak(&heap->random);    // prevent allocation failure during bcrypt dll initialization with static linking (issue #1185)
242
    #else
243
0
      _mi_random_init(&heap->random);
244
0
    #endif
245
0
  }
246
0
  else {
247
0
    _mi_random_split(&tld->heap_backing->random, &heap->random);
248
0
  }
249
0
  heap->cookie  = _mi_heap_random_next(heap) | 1;
250
0
  heap->keys[0] = _mi_heap_random_next(heap);
251
0
  heap->keys[1] = _mi_heap_random_next(heap);
252
0
  _mi_heap_guarded_init(heap);
253
  // push on the thread local heaps list
254
0
  heap->next = heap->tld->heaps;
255
0
  heap->tld->heaps = heap;
256
0
}
257
258
0
mi_decl_nodiscard mi_heap_t* mi_heap_new_ex(int heap_tag, bool allow_destroy, mi_arena_id_t arena_id) {
259
0
  mi_heap_t* bheap = mi_heap_get_backing();
260
0
  mi_heap_t* heap = mi_heap_malloc_tp(bheap, mi_heap_t);  // todo: OS allocate in secure mode?
261
0
  if (heap == NULL) return NULL;
262
0
  mi_assert(heap_tag >= 0 && heap_tag < 256);
263
0
  _mi_heap_init(heap, bheap->tld, arena_id, allow_destroy /* no reclaim? */, (uint8_t)heap_tag /* heap tag */);
264
0
  return heap;
265
0
}
266
267
0
mi_decl_nodiscard mi_heap_t* mi_heap_new_in_arena(mi_arena_id_t arena_id) {
268
0
  return mi_heap_new_ex(0 /* default heap tag */, false /* don't allow `mi_heap_destroy` */, arena_id);
269
0
}
270
271
0
mi_decl_nodiscard mi_heap_t* mi_heap_new(void) {
272
  // don't reclaim abandoned memory or otherwise destroy is unsafe
273
0
  return mi_heap_new_ex(0 /* default heap tag */, true /* no reclaim */, _mi_arena_id_none());
274
0
}
275
276
0
bool _mi_heap_memid_is_suitable(mi_heap_t* heap, mi_memid_t memid) {
277
0
  return _mi_arena_memid_is_suitable(memid, heap->arena_id);
278
0
}
279
280
111
uintptr_t _mi_heap_random_next(mi_heap_t* heap) {
281
111
  return _mi_random_next(&heap->random);
282
111
}
283
284
// zero out the page queues
285
0
static void mi_heap_reset_pages(mi_heap_t* heap) {
286
0
  mi_assert_internal(heap != NULL);
287
0
  mi_assert_internal(mi_heap_is_initialized(heap));
288
  // TODO: copy full empty heap instead?
289
0
  memset(&heap->pages_free_direct, 0, sizeof(heap->pages_free_direct));
290
0
  _mi_memcpy_aligned(&heap->pages, &_mi_heap_empty.pages, sizeof(heap->pages));
291
0
  heap->thread_delayed_free = NULL;
292
0
  heap->page_count = 0;
293
0
}
294
295
// called from `mi_heap_destroy` and `mi_heap_delete` to free the internal heap resources.
296
0
static void mi_heap_free(mi_heap_t* heap) {
297
0
  mi_assert(heap != NULL);
298
0
  mi_assert_internal(mi_heap_is_initialized(heap));
299
0
  if (heap==NULL || !mi_heap_is_initialized(heap)) return;
300
0
  if (mi_heap_is_backing(heap)) return; // dont free the backing heap
301
302
  // reset default
303
0
  if (mi_heap_is_default(heap)) {
304
0
    _mi_heap_set_default_direct(heap->tld->heap_backing);
305
0
  }
306
307
  // remove ourselves from the thread local heaps list
308
  // linear search but we expect the number of heaps to be relatively small
309
0
  mi_heap_t* prev = NULL;
310
0
  mi_heap_t* curr = heap->tld->heaps;
311
0
  while (curr != heap && curr != NULL) {
312
0
    prev = curr;
313
0
    curr = curr->next;
314
0
  }
315
0
  mi_assert_internal(curr == heap);
316
0
  if (curr == heap) {
317
0
    if (prev != NULL) { prev->next = heap->next; }
318
0
                 else { heap->tld->heaps = heap->next; }
319
0
  }
320
0
  mi_assert_internal(heap->tld->heaps != NULL);
321
322
  // and free the used memory
323
0
  mi_free(heap);
324
0
}
325
326
// return a heap on the same thread as `heap` specialized for the specified tag (if it exists)
327
0
mi_heap_t* _mi_heap_by_tag(mi_heap_t* heap, uint8_t tag) {
328
0
  if (heap->tag == tag) {
329
0
    return heap;
330
0
  }
331
0
  for (mi_heap_t *curr = heap->tld->heaps; curr != NULL; curr = curr->next) {
332
0
    if (curr->tag == tag) {
333
0
      return curr;
334
0
    }
335
0
  }
336
0
  return NULL;
337
0
}
338
339
/* -----------------------------------------------------------
340
  Heap destroy
341
----------------------------------------------------------- */
342
343
0
static bool _mi_heap_page_destroy(mi_heap_t* heap, mi_page_queue_t* pq, mi_page_t* page, void* arg1, void* arg2) {
344
0
  MI_UNUSED(arg1);
345
0
  MI_UNUSED(arg2);
346
0
  MI_UNUSED(heap);
347
0
  MI_UNUSED(pq);
348
349
  // ensure no more thread_delayed_free will be added
350
0
  _mi_page_use_delayed_free(page, MI_NEVER_DELAYED_FREE, false);
351
352
  // stats
353
0
  const size_t bsize = mi_page_block_size(page);
354
0
  if (bsize > MI_MEDIUM_OBJ_SIZE_MAX) {
355
    //if (bsize <= MI_LARGE_OBJ_SIZE_MAX) {
356
    //  mi_heap_stat_decrease(heap, malloc_large, bsize);
357
    //}
358
    //else
359
0
    {
360
0
      mi_heap_stat_decrease(heap, malloc_huge, bsize);
361
0
    }
362
0
  }
363
  #if (MI_STAT>0)
364
  _mi_page_free_collect(page, false);  // update used count
365
  const size_t inuse = page->used;
366
  if (bsize <= MI_LARGE_OBJ_SIZE_MAX) {
367
    mi_heap_stat_decrease(heap, malloc_normal, bsize * inuse);
368
    #if (MI_STAT>1)
369
    mi_heap_stat_decrease(heap, malloc_bins[_mi_bin(bsize)], inuse);
370
    #endif
371
  }
372
  // mi_heap_stat_decrease(heap, malloc_requested, bsize * inuse);  // todo: off for aligned blocks...
373
  #endif
374
375
  /// pretend it is all free now
376
0
  mi_assert_internal(mi_page_thread_free(page) == NULL);
377
0
  page->used = 0;
378
379
  // and free the page
380
  // mi_page_free(page,false);
381
0
  page->next = NULL;
382
0
  page->prev = NULL;
383
0
  _mi_segment_page_free(page,false /* no force? */, &heap->tld->segments);
384
385
0
  return true; // keep going
386
0
}
387
388
0
void _mi_heap_destroy_pages(mi_heap_t* heap) {
389
0
  mi_heap_visit_pages(heap, &_mi_heap_page_destroy, true, NULL, NULL);
390
0
  mi_heap_reset_pages(heap);
391
0
}
392
393
#if MI_TRACK_HEAP_DESTROY
394
static bool mi_cdecl mi_heap_track_block_free(const mi_heap_t* heap, const mi_heap_area_t* area, void* block, size_t block_size, void* arg) {
395
  MI_UNUSED(heap); MI_UNUSED(area);  MI_UNUSED(arg); MI_UNUSED(block_size);
396
  mi_track_free_size(block,mi_usable_size(block));
397
  return true;
398
}
399
#endif
400
401
0
void mi_heap_destroy(mi_heap_t* heap) {
402
0
  mi_assert(heap != NULL);
403
0
  mi_assert(mi_heap_is_initialized(heap));
404
0
  mi_assert(heap->no_reclaim);
405
0
  mi_assert_expensive(mi_heap_is_valid(heap));
406
0
  if (heap==NULL || !mi_heap_is_initialized(heap)) return;
407
  #if MI_GUARDED
408
  // _mi_warning_message("'mi_heap_destroy' called but MI_GUARDED is enabled -- using `mi_heap_delete` instead (heap at %p)\n", heap);
409
  mi_heap_delete(heap);
410
  return;
411
  #else
412
0
  if (!heap->no_reclaim) {
413
0
    _mi_warning_message("'mi_heap_destroy' called but ignored as the heap was not created with 'allow_destroy' (heap at %p)\n", heap);
414
    // don't free in case it may contain reclaimed pages
415
0
    mi_heap_delete(heap);
416
0
  }
417
0
  else {
418
    // track all blocks as freed
419
    #if MI_TRACK_HEAP_DESTROY
420
    mi_heap_visit_blocks(heap, true, mi_heap_track_block_free, NULL);
421
    #endif
422
    // free all pages
423
0
    _mi_heap_destroy_pages(heap);
424
0
    mi_heap_free(heap);
425
0
  }
426
0
  #endif
427
0
}
428
429
// forcefully destroy all heaps in the current thread
430
0
void _mi_heap_unsafe_destroy_all(mi_heap_t* heap) {
431
0
  mi_assert_internal(heap != NULL);
432
0
  if (heap == NULL) return;
433
0
  mi_heap_t* curr = heap->tld->heaps;
434
0
  while (curr != NULL) {
435
0
    mi_heap_t* next = curr->next;
436
0
    if (curr->no_reclaim) {
437
0
      mi_heap_destroy(curr);
438
0
    }
439
0
    else {
440
0
      _mi_heap_destroy_pages(curr);
441
0
    }
442
0
    curr = next;
443
0
  }
444
0
}
445
446
/* -----------------------------------------------------------
447
  Safe Heap delete
448
----------------------------------------------------------- */
449
450
// Transfer the pages from one heap to the other
451
0
static void mi_heap_absorb(mi_heap_t* heap, mi_heap_t* from) {
452
0
  mi_assert_internal(heap!=NULL);
453
0
  if (from==NULL || from->page_count == 0) return;
454
455
  // reduce the size of the delayed frees
456
0
  _mi_heap_delayed_free_partial(from);
457
458
  // transfer all pages by appending the queues; this will set a new heap field
459
  // so threads may do delayed frees in either heap for a while.
460
  // note: appending waits for each page to not be in the `MI_DELAYED_FREEING` state
461
  // so after this only the new heap will get delayed frees
462
0
  for (size_t i = 0; i <= MI_BIN_FULL; i++) {
463
0
    mi_page_queue_t* pq = &heap->pages[i];
464
0
    mi_page_queue_t* append = &from->pages[i];
465
0
    size_t pcount = _mi_page_queue_append(heap, pq, append);
466
0
    heap->page_count += pcount;
467
0
    from->page_count -= pcount;
468
0
  }
469
0
  mi_assert_internal(from->page_count == 0);
470
471
  // and do outstanding delayed frees in the `from` heap
472
  // note: be careful here as the `heap` field in all those pages no longer point to `from`,
473
  // turns out to be ok as `_mi_heap_delayed_free` only visits the list and calls a
474
  // the regular `_mi_free_delayed_block` which is safe.
475
0
  _mi_heap_delayed_free_all(from);
476
0
  #if !defined(_MSC_VER) || (_MSC_VER > 1900) // somehow the following line gives an error in VS2015, issue #353
477
0
  mi_assert_internal(mi_atomic_load_ptr_relaxed(mi_block_t,&from->thread_delayed_free) == NULL);
478
0
  #endif
479
480
  // and reset the `from` heap
481
0
  mi_heap_reset_pages(from);
482
0
}
483
484
// are two heaps compatible with respect to heap-tag, exclusive arena etc.
485
0
static bool mi_heaps_are_compatible(mi_heap_t* heap1, mi_heap_t* heap2) {
486
0
  return (heap1->tag == heap2->tag &&                   // store same kind of objects
487
0
          heap1->arena_id == heap2->arena_id);          // same arena preference
488
0
}
489
490
// Safe delete a heap without freeing any still allocated blocks in that heap.
491
void mi_heap_delete(mi_heap_t* heap)
492
0
{
493
0
  mi_assert(heap != NULL);
494
0
  mi_assert(mi_heap_is_initialized(heap));
495
0
  mi_assert_expensive(mi_heap_is_valid(heap));
496
0
  if (heap==NULL || !mi_heap_is_initialized(heap)) return;
497
498
0
  mi_heap_t* bheap = heap->tld->heap_backing;
499
0
  if (bheap != heap && mi_heaps_are_compatible(bheap,heap)) {
500
    // transfer still used pages to the backing heap
501
0
    mi_heap_absorb(bheap, heap);
502
0
  }
503
0
  else {
504
    // the backing heap abandons its pages
505
0
    _mi_heap_collect_abandon(heap);
506
0
  }
507
0
  mi_assert_internal(heap->page_count==0);
508
0
  mi_heap_free(heap);
509
0
}
510
511
0
mi_heap_t* mi_heap_set_default(mi_heap_t* heap) {
512
0
  mi_assert(heap != NULL);
513
0
  mi_assert(mi_heap_is_initialized(heap));
514
0
  if (heap==NULL || !mi_heap_is_initialized(heap)) return NULL;
515
0
  mi_assert_expensive(mi_heap_is_valid(heap));
516
0
  mi_heap_t* old = mi_prim_get_default_heap();
517
0
  _mi_heap_set_default_direct(heap);
518
0
  return old;
519
0
}
520
521
522
523
524
/* -----------------------------------------------------------
525
  Analysis
526
----------------------------------------------------------- */
527
528
// static since it is not thread safe to access heaps from other threads.
529
0
static mi_heap_t* mi_heap_of_block(const void* p) {
530
0
  if (p == NULL) return NULL;
531
0
  mi_segment_t* segment = _mi_ptr_segment(p);
532
0
  bool valid = (_mi_ptr_cookie(segment) == segment->cookie);
533
0
  mi_assert_internal(valid);
534
0
  if mi_unlikely(!valid) return NULL;
535
0
  return mi_page_heap(_mi_segment_page_of(segment,p));
536
0
}
537
538
0
bool mi_heap_contains_block(mi_heap_t* heap, const void* p) {
539
0
  mi_assert(heap != NULL);
540
0
  if (heap==NULL || !mi_heap_is_initialized(heap)) return false;
541
0
  return (heap == mi_heap_of_block(p));
542
0
}
543
544
545
0
static bool mi_heap_page_check_owned(mi_heap_t* heap, mi_page_queue_t* pq, mi_page_t* page, void* p, void* vfound) {
546
0
  MI_UNUSED(heap);
547
0
  MI_UNUSED(pq);
548
0
  bool* found = (bool*)vfound;
549
0
  void* start = mi_page_start(page);
550
0
  void* end   = (uint8_t*)start + (page->capacity * mi_page_block_size(page));
551
0
  *found = (p >= start && p < end);
552
0
  return (!*found); // continue if not found
553
0
}
554
555
0
bool mi_heap_check_owned(mi_heap_t* heap, const void* p) {
556
0
  mi_assert(heap != NULL);
557
0
  if (heap==NULL || !mi_heap_is_initialized(heap)) return false;
558
0
  if (((uintptr_t)p & (MI_INTPTR_SIZE - 1)) != 0) return false;  // only aligned pointers
559
0
  bool found = false;
560
0
  mi_heap_visit_pages(heap, &mi_heap_page_check_owned, true, (void*)p, &found);
561
0
  return found;
562
0
}
563
564
0
bool mi_check_owned(const void* p) {
565
0
  return mi_heap_check_owned(mi_prim_get_default_heap(), p);
566
0
}
567
568
/* -----------------------------------------------------------
569
  Visit all heap blocks and areas
570
  Todo: enable visiting abandoned pages, and
571
        enable visiting all blocks of all heaps across threads
572
----------------------------------------------------------- */
573
574
0
void _mi_heap_area_init(mi_heap_area_t* area, mi_page_t* page) {
575
0
  const size_t bsize = mi_page_block_size(page);
576
0
  const size_t ubsize = mi_page_usable_block_size(page);
577
0
  area->reserved = page->reserved * bsize;
578
0
  area->committed = page->capacity * bsize;
579
0
  area->blocks = mi_page_start(page);
580
0
  area->used = page->used;   // number of blocks in use (#553)
581
0
  area->block_size = ubsize;
582
0
  area->full_block_size = bsize;
583
0
  area->heap_tag = page->heap_tag;
584
0
}
585
586
587
0
static void mi_get_fast_divisor(size_t divisor, uint64_t* magic, size_t* shift) {
588
0
  mi_assert_internal(divisor > 0 && divisor <= UINT32_MAX);
589
0
  *shift = MI_SIZE_BITS - mi_clz(divisor - 1);
590
0
  *magic = ((((uint64_t)1 << 32) * (((uint64_t)1 << *shift) - divisor)) / divisor + 1);
591
0
}
592
593
0
static size_t mi_fast_divide(size_t n, uint64_t magic, size_t shift) {
594
0
  mi_assert_internal(n <= UINT32_MAX);
595
0
  const uint64_t hi = ((uint64_t)n * magic) >> 32;
596
0
  return (size_t)((hi + n) >> shift);
597
0
}
598
599
0
bool _mi_heap_area_visit_blocks(const mi_heap_area_t* area, mi_page_t* page, mi_block_visit_fun* visitor, void* arg) {
600
0
  mi_assert(area != NULL);
601
0
  if (area==NULL) return true;
602
0
  mi_assert(page != NULL);
603
0
  if (page == NULL) return true;
604
605
  // collect early so the page used count is reported correctly
606
  // _mi_page_free_collect(page,true);              // collect both thread_delayed and local_free
607
0
  mi_assert_internal(page->local_free == NULL);
608
0
  if (page->used == 0) return true;
609
610
0
  size_t psize;
611
0
  uint8_t* const pstart = _mi_segment_page_start(_mi_page_segment(page), page, &psize);
612
0
  mi_heap_t* const heap = mi_page_heap(page);
613
0
  const size_t bsize    = mi_page_block_size(page);
614
0
  const size_t ubsize   = mi_page_usable_block_size(page); // without padding
615
616
  // optimize page with one block
617
0
  if (page->capacity == 1) {
618
0
    mi_assert_internal(page->used == 1 && page->free == NULL);
619
0
    return visitor(mi_page_heap(page), area, pstart, ubsize, arg);
620
0
  }
621
0
  mi_assert(bsize <= UINT32_MAX);
622
623
  // optimize full pages
624
0
  if (page->used == page->capacity) {
625
0
    uint8_t* block = pstart;
626
0
    for (size_t i = 0; i < page->capacity; i++) {
627
0
      if (!visitor(heap, area, block, ubsize, arg)) return false;
628
0
      block += bsize;
629
0
    }
630
0
    return true;
631
0
  }
632
633
  // create a bitmap of free blocks.
634
0
  #define MI_MAX_BLOCKS   (MI_SMALL_PAGE_SIZE / sizeof(void*))
635
0
  uintptr_t free_map[MI_MAX_BLOCKS / MI_INTPTR_BITS];
636
0
  const uintptr_t bmapsize = _mi_divide_up(page->capacity, MI_INTPTR_BITS);
637
0
  memset(free_map, 0, bmapsize * sizeof(intptr_t));
638
0
  if (page->capacity % MI_INTPTR_BITS != 0) {
639
    // mark left-over bits at the end as free
640
0
    size_t shift   = (page->capacity % MI_INTPTR_BITS);
641
0
    uintptr_t mask = (UINTPTR_MAX << shift);
642
0
    free_map[bmapsize - 1] = mask;
643
0
  }
644
645
  // fast repeated division by the block size
646
0
  uint64_t magic;
647
0
  size_t   shift;
648
0
  mi_get_fast_divisor(bsize, &magic, &shift);
649
650
  #if MI_DEBUG>1
651
  size_t free_count = 0;
652
  #endif
653
0
  for (mi_block_t* block = page->free; block != NULL; block = mi_block_next(page, block)) {
654
    #if MI_DEBUG>1
655
    free_count++;
656
    #endif
657
0
    mi_assert_internal((uint8_t*)block >= pstart && (uint8_t*)block < (pstart + psize));
658
0
    size_t offset = (uint8_t*)block - pstart;
659
0
    mi_assert_internal(offset % bsize == 0);
660
0
    mi_assert_internal(offset <= UINT32_MAX);
661
0
    size_t blockidx = mi_fast_divide(offset, magic, shift);
662
0
    mi_assert_internal(blockidx == offset / bsize);
663
0
    mi_assert_internal(blockidx < MI_MAX_BLOCKS);
664
0
    size_t bitidx = (blockidx / MI_INTPTR_BITS);
665
0
    size_t bit = blockidx - (bitidx * MI_INTPTR_BITS);
666
0
    free_map[bitidx] |= ((uintptr_t)1 << bit);
667
0
  }
668
0
  mi_assert_internal(page->capacity == (free_count + page->used));
669
670
  // walk through all blocks skipping the free ones
671
  #if MI_DEBUG>1
672
  size_t used_count = 0;
673
  #endif
674
0
  uint8_t* block = pstart;
675
0
  for (size_t i = 0; i < bmapsize; i++) {
676
0
    if (free_map[i] == 0) {
677
      // every block is in use
678
0
      for (size_t j = 0; j < MI_INTPTR_BITS; j++) {
679
        #if MI_DEBUG>1
680
        used_count++;
681
        #endif
682
0
        if (!visitor(heap, area, block, ubsize, arg)) return false;
683
0
        block += bsize;
684
0
      }
685
0
    }
686
0
    else {
687
      // visit the used blocks in the mask
688
0
      uintptr_t m = ~free_map[i];
689
0
      while (m != 0) {
690
        #if MI_DEBUG>1
691
        used_count++;
692
        #endif
693
0
        size_t bitidx = mi_ctz(m);
694
0
        if (!visitor(heap, area, block + (bitidx * bsize), ubsize, arg)) return false;
695
0
        m &= m - 1;  // clear least significant bit
696
0
      }
697
0
      block += bsize * MI_INTPTR_BITS;
698
0
    }
699
0
  }
700
0
  mi_assert_internal(page->used == used_count);
701
0
  return true;
702
0
}
703
704
705
706
// Separate struct to keep `mi_page_t` out of the public interface
707
typedef struct mi_heap_area_ex_s {
708
  mi_heap_area_t area;
709
  mi_page_t* page;
710
} mi_heap_area_ex_t;
711
712
typedef bool (mi_heap_area_visit_fun)(const mi_heap_t* heap, const mi_heap_area_ex_t* area, void* arg);
713
714
0
static bool mi_heap_visit_areas_page(mi_heap_t* heap, mi_page_queue_t* pq, mi_page_t* page, void* vfun, void* arg) {
715
0
  MI_UNUSED(heap);
716
0
  MI_UNUSED(pq);
717
0
  if (page==NULL) return true;
718
0
  mi_heap_area_visit_fun* fun = (mi_heap_area_visit_fun*)vfun;
719
0
  mi_heap_area_ex_t xarea;
720
0
  xarea.page = page;
721
0
  _mi_page_free_collect(page,true); // collect early so the page->used is accurate
722
0
  _mi_heap_area_init(&xarea.area, page);
723
0
  return fun(heap, &xarea, arg);
724
0
}
725
726
// Visit all heap pages as areas
727
0
static bool mi_heap_visit_areas(const mi_heap_t* heap, mi_heap_area_visit_fun* visitor, void* arg) {
728
0
  if (visitor == NULL) return false;
729
0
  return mi_heap_visit_pages((mi_heap_t*)heap, &mi_heap_visit_areas_page, true, (void*)(visitor), arg); // note: function pointer to void* :-{
730
0
}
731
732
// Just to pass arguments
733
typedef struct mi_visit_blocks_args_s {
734
  bool  visit_blocks;
735
  mi_block_visit_fun* visitor;
736
  void* arg;
737
} mi_visit_blocks_args_t;
738
739
0
static bool mi_heap_area_visitor(const mi_heap_t* heap, const mi_heap_area_ex_t* xarea, void* arg) {
740
0
  mi_visit_blocks_args_t* args = (mi_visit_blocks_args_t*)arg;
741
0
  if (!args->visitor(heap, &xarea->area, NULL, xarea->area.block_size, args->arg)) return false;
742
0
  if (args->visit_blocks) {
743
0
    return _mi_heap_area_visit_blocks(&xarea->area, xarea->page, args->visitor, args->arg);
744
0
  }
745
0
  else {
746
0
    return true;
747
0
  }
748
0
}
749
750
// Visit all blocks in a heap
751
0
bool mi_heap_visit_blocks(const mi_heap_t* heap, bool visit_blocks, mi_block_visit_fun* visitor, void* arg) {
752
0
  mi_visit_blocks_args_t args = { visit_blocks, visitor, arg };
753
0
  _mi_heap_delayed_free_partial((mi_heap_t *)heap);  // CPython: gh-112532
754
0
  return mi_heap_visit_areas(heap, &mi_heap_area_visitor, &args);
755
0
}
756
757
758
759
0
static const mi_page_t* mi_safe_ptr_page(void* p) {
760
0
  const mi_segment_t* const segment = _mi_ptr_segment(p);
761
0
  if mi_unlikely(segment==NULL) return NULL;
762
  #ifndef NDEBUG
763
  if mi_unlikely(!mi_is_in_heap_region(p)) return NULL;
764
  #endif
765
0
  if mi_unlikely(_mi_ptr_cookie(segment) != segment->cookie) return NULL;
766
0
  return _mi_segment_page_of(segment, p);
767
0
}
768
769
// unsafe heap utilization function for DragonFly (see issue #1258)
770
// If the page of pointer `p` belongs to `heap` (or `heap==NULL`) and has less than `perc_threshold` used blocks in its used area return `true`.
771
// This function is unsafe in general as it assumes we are the only thread accessing the page of `p`.
772
0
bool mi_unsafe_heap_page_is_under_utilized(mi_heap_t* heap, void* p, size_t perc_threshold) mi_attr_noexcept {
773
0
  if (p==NULL) return false;
774
0
  const mi_page_t* const page = mi_safe_ptr_page(p);   // Get the page containing this pointer
775
0
  if (page==NULL || page->used==page->capacity || page->capacity < page->reserved) return false;
776
  // If the page is the head of the queue, it is currently being used for
777
  // allocations; we skip it to avoid immediate thrashing.
778
0
  if (page->prev == NULL)  return false;
779
780
  // match heap?
781
0
  const mi_heap_t* const page_heap = mi_page_heap(page);
782
0
  if (page_heap==NULL) return false;
783
0
  if (heap!=NULL && page_heap!=heap) return false;
784
785
  // check utilization
786
0
  if (page->capacity==0)   return false;
787
0
  if (perc_threshold>=100) return true;
788
0
  return (perc_threshold >= ((100UL*page->used) / page->capacity));
789
0
}