| 775 | } |
| 776 | |
| 777 | static bool mem_map_collect_impl(cbm_mem_map_t *out, bool walk_allocator) { |
| 778 | if (!out) { |
| 779 | return false; |
| 780 | } |
| 781 | memset(out, 0, sizeof(*out)); |
| 782 | |
| 783 | size_t elapsed_ms = 0; |
| 784 | size_t user_ms = 0; |
| 785 | size_t sys_ms = 0; |
| 786 | size_t current_rss = 0; |
| 787 | size_t peak_rss = 0; |
| 788 | size_t current_commit = 0; |
| 789 | size_t peak_commit = 0; |
| 790 | size_t page_faults = 0; |
| 791 | mi_process_info(&elapsed_ms, &user_ms, &sys_ms, ¤t_rss, &peak_rss, ¤t_commit, |
| 792 | &peak_commit, &page_faults); |
| 793 | out->os_rss_bytes = current_rss ? current_rss : cbm_mem_rss(); |
| 794 | out->os_committed_bytes = current_commit; |
| 795 | |
| 796 | /* Does plain malloc actually land in the allocator's regions? This single |
| 797 | * bit distinguishes "nothing is live" from "the allocator does not own |
| 798 | * this build's allocations", which are opposite conclusions from the same |
| 799 | * zero. Probe with a real malloc/free pair rather than inferring from |
| 800 | * build flags, because the Windows static-CRT override is defined at |
| 801 | * compile time yet can still fail to take effect at link time. */ |
| 802 | void *probe = malloc(CBM_SZ_64); |
| 803 | if (probe) { |
| 804 | out->malloc_is_allocator_owned = mi_is_in_heap_region(probe); |
| 805 | free(probe); |
| 806 | } |
| 807 | |
| 808 | /* Walk only heaps this thread may safely read. |
| 809 | * |
| 810 | * mi_heap_main() is the process-wide aggregate: any other thread can be |
| 811 | * allocating into it while the walk runs, which is a data race by |
| 812 | * construction and TSan reports it as one (init.c:452 in mi_heap_main). |
| 813 | * A diagnostic must not introduce a race into the code it measures, so the |
| 814 | * aggregate walk is gone. What remains is safe by ownership: this thread's |
| 815 | * own theap, plus abandoned pages, which by definition have no owning |
| 816 | * thread left to race with. |
| 817 | * |
| 818 | * That includes mi_heap_main() itself: merely CALLING it reads the |
| 819 | * allocator's main-heap pointer, which a thread exiting concurrently |
| 820 | * rewrites from _mi_thread_done -> _mi_theap_default_set. TSan caught |
| 821 | * exactly that pairing on macOS, so the abandoned-page walk goes too -- |
| 822 | * it could only be reached through mi_heap_main(). |
| 823 | * |
| 824 | * The cost is coverage -- other threads' live blocks and abandoned pages |
| 825 | * are not attributed -- and that is exactly what the residual in mem.h |
| 826 | * exists to carry. An unmeasured map must never read as an empty one. */ |
| 827 | if (walk_allocator) { |
| 828 | (void)mi_theap_visit_blocks(mi_theap_get_default(), false, mem_map_visit_area, out); |
| 829 | } |
| 830 | return true; |
| 831 | } |
| 832 | |
| 833 | /* ── Allocator ownership audit (see mem.h) ─────────────────────────── */ |
| 834 |
no test coverage detected