xref: /freebsd-src/contrib/llvm-project/compiler-rt/lib/memprof/memprof_allocator.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
1e8d8bef9SDimitry Andric //===-- memprof_allocator.cpp --------------------------------------------===//
2e8d8bef9SDimitry Andric //
3e8d8bef9SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e8d8bef9SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e8d8bef9SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6e8d8bef9SDimitry Andric //
7e8d8bef9SDimitry Andric //===----------------------------------------------------------------------===//
8e8d8bef9SDimitry Andric //
9e8d8bef9SDimitry Andric // This file is a part of MemProfiler, a memory profiler.
10e8d8bef9SDimitry Andric //
11e8d8bef9SDimitry Andric // Implementation of MemProf's memory allocator, which uses the allocator
12e8d8bef9SDimitry Andric // from sanitizer_common.
13e8d8bef9SDimitry Andric //
14e8d8bef9SDimitry Andric //===----------------------------------------------------------------------===//
15e8d8bef9SDimitry Andric 
16e8d8bef9SDimitry Andric #include "memprof_allocator.h"
17e8d8bef9SDimitry Andric #include "memprof_mapping.h"
18349cc55cSDimitry Andric #include "memprof_mibmap.h"
19349cc55cSDimitry Andric #include "memprof_rawprofile.h"
20e8d8bef9SDimitry Andric #include "memprof_stack.h"
21e8d8bef9SDimitry Andric #include "memprof_thread.h"
221fd87a68SDimitry Andric #include "profile/MemProfData.inc"
23e8d8bef9SDimitry Andric #include "sanitizer_common/sanitizer_allocator_checks.h"
24e8d8bef9SDimitry Andric #include "sanitizer_common/sanitizer_allocator_interface.h"
25e8d8bef9SDimitry Andric #include "sanitizer_common/sanitizer_allocator_report.h"
2606c3fb27SDimitry Andric #include "sanitizer_common/sanitizer_array_ref.h"
2706c3fb27SDimitry Andric #include "sanitizer_common/sanitizer_common.h"
28e8d8bef9SDimitry Andric #include "sanitizer_common/sanitizer_errno.h"
29e8d8bef9SDimitry Andric #include "sanitizer_common/sanitizer_file.h"
30e8d8bef9SDimitry Andric #include "sanitizer_common/sanitizer_flags.h"
31e8d8bef9SDimitry Andric #include "sanitizer_common/sanitizer_internal_defs.h"
32e8d8bef9SDimitry Andric #include "sanitizer_common/sanitizer_stackdepot.h"
33e8d8bef9SDimitry Andric 
34e8d8bef9SDimitry Andric #include <sched.h>
35e8d8bef9SDimitry Andric #include <time.h>
36e8d8bef9SDimitry Andric 
37*0fca6ea1SDimitry Andric #define MAX_HISTOGRAM_PRINT_SIZE 32U
38*0fca6ea1SDimitry Andric 
39*0fca6ea1SDimitry Andric extern bool __memprof_histogram;
40*0fca6ea1SDimitry Andric 
41e8d8bef9SDimitry Andric namespace __memprof {
421fd87a68SDimitry Andric namespace {
431fd87a68SDimitry Andric using ::llvm::memprof::MemInfoBlock;
441fd87a68SDimitry Andric 
451fd87a68SDimitry Andric void Print(const MemInfoBlock &M, const u64 id, bool print_terse) {
461fd87a68SDimitry Andric   u64 p;
471fd87a68SDimitry Andric 
481fd87a68SDimitry Andric   if (print_terse) {
4981ad6265SDimitry Andric     p = M.TotalSize * 100 / M.AllocCount;
5081ad6265SDimitry Andric     Printf("MIB:%llu/%u/%llu.%02llu/%u/%u/", id, M.AllocCount, p / 100, p % 100,
5181ad6265SDimitry Andric            M.MinSize, M.MaxSize);
5281ad6265SDimitry Andric     p = M.TotalAccessCount * 100 / M.AllocCount;
5381ad6265SDimitry Andric     Printf("%llu.%02llu/%llu/%llu/", p / 100, p % 100, M.MinAccessCount,
5481ad6265SDimitry Andric            M.MaxAccessCount);
5581ad6265SDimitry Andric     p = M.TotalLifetime * 100 / M.AllocCount;
5681ad6265SDimitry Andric     Printf("%llu.%02llu/%u/%u/", p / 100, p % 100, M.MinLifetime,
5781ad6265SDimitry Andric            M.MaxLifetime);
5881ad6265SDimitry Andric     Printf("%u/%u/%u/%u\n", M.NumMigratedCpu, M.NumLifetimeOverlaps,
5981ad6265SDimitry Andric            M.NumSameAllocCpu, M.NumSameDeallocCpu);
601fd87a68SDimitry Andric   } else {
6181ad6265SDimitry Andric     p = M.TotalSize * 100 / M.AllocCount;
621fd87a68SDimitry Andric     Printf("Memory allocation stack id = %llu\n", id);
631fd87a68SDimitry Andric     Printf("\talloc_count %u, size (ave/min/max) %llu.%02llu / %u / %u\n",
6481ad6265SDimitry Andric            M.AllocCount, p / 100, p % 100, M.MinSize, M.MaxSize);
6581ad6265SDimitry Andric     p = M.TotalAccessCount * 100 / M.AllocCount;
661fd87a68SDimitry Andric     Printf("\taccess_count (ave/min/max): %llu.%02llu / %llu / %llu\n", p / 100,
6781ad6265SDimitry Andric            p % 100, M.MinAccessCount, M.MaxAccessCount);
6881ad6265SDimitry Andric     p = M.TotalLifetime * 100 / M.AllocCount;
691fd87a68SDimitry Andric     Printf("\tlifetime (ave/min/max): %llu.%02llu / %u / %u\n", p / 100,
7081ad6265SDimitry Andric            p % 100, M.MinLifetime, M.MaxLifetime);
711fd87a68SDimitry Andric     Printf("\tnum migrated: %u, num lifetime overlaps: %u, num same alloc "
721fd87a68SDimitry Andric            "cpu: %u, num same dealloc_cpu: %u\n",
7381ad6265SDimitry Andric            M.NumMigratedCpu, M.NumLifetimeOverlaps, M.NumSameAllocCpu,
7481ad6265SDimitry Andric            M.NumSameDeallocCpu);
75*0fca6ea1SDimitry Andric     Printf("AccessCountHistogram[%u]: ", M.AccessHistogramSize);
76*0fca6ea1SDimitry Andric     uint32_t PrintSize = M.AccessHistogramSize > MAX_HISTOGRAM_PRINT_SIZE
77*0fca6ea1SDimitry Andric                              ? MAX_HISTOGRAM_PRINT_SIZE
78*0fca6ea1SDimitry Andric                              : M.AccessHistogramSize;
79*0fca6ea1SDimitry Andric     for (size_t i = 0; i < PrintSize; ++i) {
80*0fca6ea1SDimitry Andric       Printf("%llu ", ((uint64_t *)M.AccessHistogram)[i]);
81*0fca6ea1SDimitry Andric     }
82*0fca6ea1SDimitry Andric     Printf("\n");
831fd87a68SDimitry Andric   }
841fd87a68SDimitry Andric }
851fd87a68SDimitry Andric } // namespace
86e8d8bef9SDimitry Andric 
87e8d8bef9SDimitry Andric static int GetCpuId(void) {
88e8d8bef9SDimitry Andric   // _memprof_preinit is called via the preinit_array, which subsequently calls
89e8d8bef9SDimitry Andric   // malloc. Since this is before _dl_init calls VDSO_SETUP, sched_getcpu
90e8d8bef9SDimitry Andric   // will seg fault as the address of __vdso_getcpu will be null.
9106c3fb27SDimitry Andric   if (!memprof_inited)
92e8d8bef9SDimitry Andric     return -1;
93e8d8bef9SDimitry Andric   return sched_getcpu();
94e8d8bef9SDimitry Andric }
95e8d8bef9SDimitry Andric 
96e8d8bef9SDimitry Andric // Compute the timestamp in ms.
97e8d8bef9SDimitry Andric static int GetTimestamp(void) {
98e8d8bef9SDimitry Andric   // timespec_get will segfault if called from dl_init
99e8d8bef9SDimitry Andric   if (!memprof_timestamp_inited) {
100e8d8bef9SDimitry Andric     // By returning 0, this will be effectively treated as being
101e8d8bef9SDimitry Andric     // timestamped at memprof init time (when memprof_init_timestamp_s
102e8d8bef9SDimitry Andric     // is initialized).
103e8d8bef9SDimitry Andric     return 0;
104e8d8bef9SDimitry Andric   }
105e8d8bef9SDimitry Andric   timespec ts;
106e8d8bef9SDimitry Andric   clock_gettime(CLOCK_REALTIME, &ts);
107e8d8bef9SDimitry Andric   return (ts.tv_sec - memprof_init_timestamp_s) * 1000 + ts.tv_nsec / 1000000;
108e8d8bef9SDimitry Andric }
109e8d8bef9SDimitry Andric 
110e8d8bef9SDimitry Andric static MemprofAllocator &get_allocator();
111e8d8bef9SDimitry Andric 
112e8d8bef9SDimitry Andric // The memory chunk allocated from the underlying allocator looks like this:
113e8d8bef9SDimitry Andric // H H U U U U U U
114e8d8bef9SDimitry Andric //   H -- ChunkHeader (32 bytes)
115e8d8bef9SDimitry Andric //   U -- user memory.
116e8d8bef9SDimitry Andric 
117e8d8bef9SDimitry Andric // If there is left padding before the ChunkHeader (due to use of memalign),
118e8d8bef9SDimitry Andric // we store a magic value in the first uptr word of the memory block and
119e8d8bef9SDimitry Andric // store the address of ChunkHeader in the next uptr.
120e8d8bef9SDimitry Andric // M B L L L L L L L L L  H H U U U U U U
121e8d8bef9SDimitry Andric //   |                    ^
122e8d8bef9SDimitry Andric //   ---------------------|
123e8d8bef9SDimitry Andric //   M -- magic value kAllocBegMagic
124e8d8bef9SDimitry Andric //   B -- address of ChunkHeader pointing to the first 'H'
125e8d8bef9SDimitry Andric 
126e8d8bef9SDimitry Andric constexpr uptr kMaxAllowedMallocBits = 40;
127e8d8bef9SDimitry Andric 
128e8d8bef9SDimitry Andric // Should be no more than 32-bytes
129e8d8bef9SDimitry Andric struct ChunkHeader {
130e8d8bef9SDimitry Andric   // 1-st 4 bytes.
131e8d8bef9SDimitry Andric   u32 alloc_context_id;
132e8d8bef9SDimitry Andric   // 2-nd 4 bytes
133e8d8bef9SDimitry Andric   u32 cpu_id;
134e8d8bef9SDimitry Andric   // 3-rd 4 bytes
135e8d8bef9SDimitry Andric   u32 timestamp_ms;
136e8d8bef9SDimitry Andric   // 4-th 4 bytes
137e8d8bef9SDimitry Andric   // Note only 1 bit is needed for this flag if we need space in the future for
138e8d8bef9SDimitry Andric   // more fields.
139e8d8bef9SDimitry Andric   u32 from_memalign;
140e8d8bef9SDimitry Andric   // 5-th and 6-th 4 bytes
141e8d8bef9SDimitry Andric   // The max size of an allocation is 2^40 (kMaxAllowedMallocSize), so this
142e8d8bef9SDimitry Andric   // could be shrunk to kMaxAllowedMallocBits if we need space in the future for
143e8d8bef9SDimitry Andric   // more fields.
144e8d8bef9SDimitry Andric   atomic_uint64_t user_requested_size;
145e8d8bef9SDimitry Andric   // 23 bits available
146e8d8bef9SDimitry Andric   // 7-th and 8-th 4 bytes
147e8d8bef9SDimitry Andric   u64 data_type_id; // TODO: hash of type name
148e8d8bef9SDimitry Andric };
149e8d8bef9SDimitry Andric 
150e8d8bef9SDimitry Andric static const uptr kChunkHeaderSize = sizeof(ChunkHeader);
151e8d8bef9SDimitry Andric COMPILER_CHECK(kChunkHeaderSize == 32);
152e8d8bef9SDimitry Andric 
153e8d8bef9SDimitry Andric struct MemprofChunk : ChunkHeader {
154e8d8bef9SDimitry Andric   uptr Beg() { return reinterpret_cast<uptr>(this) + kChunkHeaderSize; }
155e8d8bef9SDimitry Andric   uptr UsedSize() {
156e8d8bef9SDimitry Andric     return atomic_load(&user_requested_size, memory_order_relaxed);
157e8d8bef9SDimitry Andric   }
158e8d8bef9SDimitry Andric   void *AllocBeg() {
159e8d8bef9SDimitry Andric     if (from_memalign)
160e8d8bef9SDimitry Andric       return get_allocator().GetBlockBegin(reinterpret_cast<void *>(this));
161e8d8bef9SDimitry Andric     return reinterpret_cast<void *>(this);
162e8d8bef9SDimitry Andric   }
163e8d8bef9SDimitry Andric };
164e8d8bef9SDimitry Andric 
165e8d8bef9SDimitry Andric class LargeChunkHeader {
166e8d8bef9SDimitry Andric   static constexpr uptr kAllocBegMagic =
167e8d8bef9SDimitry Andric       FIRST_32_SECOND_64(0xCC6E96B9, 0xCC6E96B9CC6E96B9ULL);
168e8d8bef9SDimitry Andric   atomic_uintptr_t magic;
169e8d8bef9SDimitry Andric   MemprofChunk *chunk_header;
170e8d8bef9SDimitry Andric 
171e8d8bef9SDimitry Andric public:
172e8d8bef9SDimitry Andric   MemprofChunk *Get() const {
173e8d8bef9SDimitry Andric     return atomic_load(&magic, memory_order_acquire) == kAllocBegMagic
174e8d8bef9SDimitry Andric                ? chunk_header
175e8d8bef9SDimitry Andric                : nullptr;
176e8d8bef9SDimitry Andric   }
177e8d8bef9SDimitry Andric 
178e8d8bef9SDimitry Andric   void Set(MemprofChunk *p) {
179e8d8bef9SDimitry Andric     if (p) {
180e8d8bef9SDimitry Andric       chunk_header = p;
181e8d8bef9SDimitry Andric       atomic_store(&magic, kAllocBegMagic, memory_order_release);
182e8d8bef9SDimitry Andric       return;
183e8d8bef9SDimitry Andric     }
184e8d8bef9SDimitry Andric 
185e8d8bef9SDimitry Andric     uptr old = kAllocBegMagic;
186e8d8bef9SDimitry Andric     if (!atomic_compare_exchange_strong(&magic, &old, 0,
187e8d8bef9SDimitry Andric                                         memory_order_release)) {
188e8d8bef9SDimitry Andric       CHECK_EQ(old, kAllocBegMagic);
189e8d8bef9SDimitry Andric     }
190e8d8bef9SDimitry Andric   }
191e8d8bef9SDimitry Andric };
192e8d8bef9SDimitry Andric 
193e8d8bef9SDimitry Andric void FlushUnneededMemProfShadowMemory(uptr p, uptr size) {
194e8d8bef9SDimitry Andric   // Since memprof's mapping is compacting, the shadow chunk may be
195e8d8bef9SDimitry Andric   // not page-aligned, so we only flush the page-aligned portion.
196e8d8bef9SDimitry Andric   ReleaseMemoryPagesToOS(MemToShadow(p), MemToShadow(p + size));
197e8d8bef9SDimitry Andric }
198e8d8bef9SDimitry Andric 
199e8d8bef9SDimitry Andric void MemprofMapUnmapCallback::OnMap(uptr p, uptr size) const {
200e8d8bef9SDimitry Andric   // Statistics.
201e8d8bef9SDimitry Andric   MemprofStats &thread_stats = GetCurrentThreadStats();
202e8d8bef9SDimitry Andric   thread_stats.mmaps++;
203e8d8bef9SDimitry Andric   thread_stats.mmaped += size;
204e8d8bef9SDimitry Andric }
20506c3fb27SDimitry Andric 
206e8d8bef9SDimitry Andric void MemprofMapUnmapCallback::OnUnmap(uptr p, uptr size) const {
207e8d8bef9SDimitry Andric   // We are about to unmap a chunk of user memory.
208e8d8bef9SDimitry Andric   // Mark the corresponding shadow memory as not needed.
209e8d8bef9SDimitry Andric   FlushUnneededMemProfShadowMemory(p, size);
210e8d8bef9SDimitry Andric   // Statistics.
211e8d8bef9SDimitry Andric   MemprofStats &thread_stats = GetCurrentThreadStats();
212e8d8bef9SDimitry Andric   thread_stats.munmaps++;
213e8d8bef9SDimitry Andric   thread_stats.munmaped += size;
214e8d8bef9SDimitry Andric }
215e8d8bef9SDimitry Andric 
216e8d8bef9SDimitry Andric AllocatorCache *GetAllocatorCache(MemprofThreadLocalMallocStorage *ms) {
217e8d8bef9SDimitry Andric   CHECK(ms);
218e8d8bef9SDimitry Andric   return &ms->allocator_cache;
219e8d8bef9SDimitry Andric }
220e8d8bef9SDimitry Andric 
221e8d8bef9SDimitry Andric // Accumulates the access count from the shadow for the given pointer and size.
222e8d8bef9SDimitry Andric u64 GetShadowCount(uptr p, u32 size) {
223e8d8bef9SDimitry Andric   u64 *shadow = (u64 *)MEM_TO_SHADOW(p);
224e8d8bef9SDimitry Andric   u64 *shadow_end = (u64 *)MEM_TO_SHADOW(p + size);
225e8d8bef9SDimitry Andric   u64 count = 0;
226e8d8bef9SDimitry Andric   for (; shadow <= shadow_end; shadow++)
227e8d8bef9SDimitry Andric     count += *shadow;
228e8d8bef9SDimitry Andric   return count;
229e8d8bef9SDimitry Andric }
230e8d8bef9SDimitry Andric 
231*0fca6ea1SDimitry Andric // Accumulates the access count from the shadow for the given pointer and size.
232*0fca6ea1SDimitry Andric // See memprof_mapping.h for an overview on histogram counters.
233*0fca6ea1SDimitry Andric u64 GetShadowCountHistogram(uptr p, u32 size) {
234*0fca6ea1SDimitry Andric   u8 *shadow = (u8 *)HISTOGRAM_MEM_TO_SHADOW(p);
235*0fca6ea1SDimitry Andric   u8 *shadow_end = (u8 *)HISTOGRAM_MEM_TO_SHADOW(p + size);
236*0fca6ea1SDimitry Andric   u64 count = 0;
237*0fca6ea1SDimitry Andric   for (; shadow <= shadow_end; shadow++)
238*0fca6ea1SDimitry Andric     count += *shadow;
239*0fca6ea1SDimitry Andric   return count;
240*0fca6ea1SDimitry Andric }
241*0fca6ea1SDimitry Andric 
242e8d8bef9SDimitry Andric // Clears the shadow counters (when memory is allocated).
243e8d8bef9SDimitry Andric void ClearShadow(uptr addr, uptr size) {
244e8d8bef9SDimitry Andric   CHECK(AddrIsAlignedByGranularity(addr));
245e8d8bef9SDimitry Andric   CHECK(AddrIsInMem(addr));
246e8d8bef9SDimitry Andric   CHECK(AddrIsAlignedByGranularity(addr + size));
247e8d8bef9SDimitry Andric   CHECK(AddrIsInMem(addr + size - SHADOW_GRANULARITY));
248e8d8bef9SDimitry Andric   CHECK(REAL(memset));
249*0fca6ea1SDimitry Andric   uptr shadow_beg;
250*0fca6ea1SDimitry Andric   uptr shadow_end;
251*0fca6ea1SDimitry Andric   if (__memprof_histogram) {
252*0fca6ea1SDimitry Andric     shadow_beg = HISTOGRAM_MEM_TO_SHADOW(addr);
253*0fca6ea1SDimitry Andric     shadow_end = HISTOGRAM_MEM_TO_SHADOW(addr + size);
254*0fca6ea1SDimitry Andric   } else {
255*0fca6ea1SDimitry Andric     shadow_beg = MEM_TO_SHADOW(addr);
256*0fca6ea1SDimitry Andric     shadow_end = MEM_TO_SHADOW(addr + size - SHADOW_GRANULARITY) + 1;
257*0fca6ea1SDimitry Andric   }
258*0fca6ea1SDimitry Andric 
259e8d8bef9SDimitry Andric   if (shadow_end - shadow_beg < common_flags()->clear_shadow_mmap_threshold) {
260e8d8bef9SDimitry Andric     REAL(memset)((void *)shadow_beg, 0, shadow_end - shadow_beg);
261e8d8bef9SDimitry Andric   } else {
262e8d8bef9SDimitry Andric     uptr page_size = GetPageSizeCached();
263e8d8bef9SDimitry Andric     uptr page_beg = RoundUpTo(shadow_beg, page_size);
264e8d8bef9SDimitry Andric     uptr page_end = RoundDownTo(shadow_end, page_size);
265e8d8bef9SDimitry Andric 
266e8d8bef9SDimitry Andric     if (page_beg >= page_end) {
267e8d8bef9SDimitry Andric       REAL(memset)((void *)shadow_beg, 0, shadow_end - shadow_beg);
268e8d8bef9SDimitry Andric     } else {
269e8d8bef9SDimitry Andric       if (page_beg != shadow_beg) {
270e8d8bef9SDimitry Andric         REAL(memset)((void *)shadow_beg, 0, page_beg - shadow_beg);
271e8d8bef9SDimitry Andric       }
272e8d8bef9SDimitry Andric       if (page_end != shadow_end) {
273e8d8bef9SDimitry Andric         REAL(memset)((void *)page_end, 0, shadow_end - page_end);
274e8d8bef9SDimitry Andric       }
275e8d8bef9SDimitry Andric       ReserveShadowMemoryRange(page_beg, page_end - 1, nullptr);
276e8d8bef9SDimitry Andric     }
277e8d8bef9SDimitry Andric   }
278e8d8bef9SDimitry Andric }
279e8d8bef9SDimitry Andric 
280e8d8bef9SDimitry Andric struct Allocator {
281e8d8bef9SDimitry Andric   static const uptr kMaxAllowedMallocSize = 1ULL << kMaxAllowedMallocBits;
282e8d8bef9SDimitry Andric 
283e8d8bef9SDimitry Andric   MemprofAllocator allocator;
284e8d8bef9SDimitry Andric   StaticSpinMutex fallback_mutex;
285e8d8bef9SDimitry Andric   AllocatorCache fallback_allocator_cache;
286e8d8bef9SDimitry Andric 
287e8d8bef9SDimitry Andric   uptr max_user_defined_malloc_size;
288e8d8bef9SDimitry Andric 
289349cc55cSDimitry Andric   // Holds the mapping of stack ids to MemInfoBlocks.
290349cc55cSDimitry Andric   MIBMapTy MIBMap;
291349cc55cSDimitry Andric 
292349cc55cSDimitry Andric   atomic_uint8_t destructing;
293349cc55cSDimitry Andric   atomic_uint8_t constructed;
294349cc55cSDimitry Andric   bool print_text;
295e8d8bef9SDimitry Andric 
296e8d8bef9SDimitry Andric   // ------------------- Initialization ------------------------
297349cc55cSDimitry Andric   explicit Allocator(LinkerInitialized) : print_text(flags()->print_text) {
298349cc55cSDimitry Andric     atomic_store_relaxed(&destructing, 0);
299349cc55cSDimitry Andric     atomic_store_relaxed(&constructed, 1);
300349cc55cSDimitry Andric   }
301e8d8bef9SDimitry Andric 
302349cc55cSDimitry Andric   ~Allocator() {
303349cc55cSDimitry Andric     atomic_store_relaxed(&destructing, 1);
304349cc55cSDimitry Andric     FinishAndWrite();
305349cc55cSDimitry Andric   }
306e8d8bef9SDimitry Andric 
307349cc55cSDimitry Andric   static void PrintCallback(const uptr Key, LockedMemInfoBlock *const &Value,
308349cc55cSDimitry Andric                             void *Arg) {
309bdd1243dSDimitry Andric     SpinMutexLock l(&Value->mutex);
3101fd87a68SDimitry Andric     Print(Value->mib, Key, bool(Arg));
311349cc55cSDimitry Andric   }
312349cc55cSDimitry Andric 
313*0fca6ea1SDimitry Andric   // See memprof_mapping.h for an overview on histogram counters.
314*0fca6ea1SDimitry Andric   static MemInfoBlock CreateNewMIB(uptr p, MemprofChunk *m, u64 user_size) {
315*0fca6ea1SDimitry Andric     if (__memprof_histogram) {
316*0fca6ea1SDimitry Andric       return CreateNewMIBWithHistogram(p, m, user_size);
317*0fca6ea1SDimitry Andric     } else {
318*0fca6ea1SDimitry Andric       return CreateNewMIBWithoutHistogram(p, m, user_size);
319*0fca6ea1SDimitry Andric     }
320*0fca6ea1SDimitry Andric   }
321*0fca6ea1SDimitry Andric 
322*0fca6ea1SDimitry Andric   static MemInfoBlock CreateNewMIBWithHistogram(uptr p, MemprofChunk *m,
323*0fca6ea1SDimitry Andric                                                 u64 user_size) {
324*0fca6ea1SDimitry Andric 
325*0fca6ea1SDimitry Andric     u64 c = GetShadowCountHistogram(p, user_size);
326*0fca6ea1SDimitry Andric     long curtime = GetTimestamp();
327*0fca6ea1SDimitry Andric     uint32_t HistogramSize =
328*0fca6ea1SDimitry Andric         RoundUpTo(user_size, HISTOGRAM_GRANULARITY) / HISTOGRAM_GRANULARITY;
329*0fca6ea1SDimitry Andric     uintptr_t Histogram =
330*0fca6ea1SDimitry Andric         (uintptr_t)InternalAlloc(HistogramSize * sizeof(uint64_t));
331*0fca6ea1SDimitry Andric     memset((void *)Histogram, 0, HistogramSize * sizeof(uint64_t));
332*0fca6ea1SDimitry Andric     for (size_t i = 0; i < HistogramSize; ++i) {
333*0fca6ea1SDimitry Andric       u8 Counter =
334*0fca6ea1SDimitry Andric           *((u8 *)HISTOGRAM_MEM_TO_SHADOW(p + HISTOGRAM_GRANULARITY * i));
335*0fca6ea1SDimitry Andric       ((uint64_t *)Histogram)[i] = (uint64_t)Counter;
336*0fca6ea1SDimitry Andric     }
337*0fca6ea1SDimitry Andric     MemInfoBlock newMIB(user_size, c, m->timestamp_ms, curtime, m->cpu_id,
338*0fca6ea1SDimitry Andric                         GetCpuId(), Histogram, HistogramSize);
339*0fca6ea1SDimitry Andric     return newMIB;
340*0fca6ea1SDimitry Andric   }
341*0fca6ea1SDimitry Andric 
342*0fca6ea1SDimitry Andric   static MemInfoBlock CreateNewMIBWithoutHistogram(uptr p, MemprofChunk *m,
343*0fca6ea1SDimitry Andric                                                    u64 user_size) {
344*0fca6ea1SDimitry Andric     u64 c = GetShadowCount(p, user_size);
345*0fca6ea1SDimitry Andric     long curtime = GetTimestamp();
346*0fca6ea1SDimitry Andric     MemInfoBlock newMIB(user_size, c, m->timestamp_ms, curtime, m->cpu_id,
347*0fca6ea1SDimitry Andric                         GetCpuId(), 0, 0);
348*0fca6ea1SDimitry Andric     return newMIB;
349*0fca6ea1SDimitry Andric   }
350*0fca6ea1SDimitry Andric 
351349cc55cSDimitry Andric   void FinishAndWrite() {
352349cc55cSDimitry Andric     if (print_text && common_flags()->print_module_map)
353349cc55cSDimitry Andric       DumpProcessMap();
354349cc55cSDimitry Andric 
355e8d8bef9SDimitry Andric     allocator.ForceLock();
356349cc55cSDimitry Andric 
357349cc55cSDimitry Andric     InsertLiveBlocks();
358349cc55cSDimitry Andric     if (print_text) {
3594824e7fdSDimitry Andric       if (!flags()->print_terse)
3604824e7fdSDimitry Andric         Printf("Recorded MIBs (incl. live on exit):\n");
361349cc55cSDimitry Andric       MIBMap.ForEach(PrintCallback,
362349cc55cSDimitry Andric                      reinterpret_cast<void *>(flags()->print_terse));
363349cc55cSDimitry Andric       StackDepotPrintAll();
364349cc55cSDimitry Andric     } else {
365349cc55cSDimitry Andric       // Serialize the contents to a raw profile. Format documented in
366349cc55cSDimitry Andric       // memprof_rawprofile.h.
367349cc55cSDimitry Andric       char *Buffer = nullptr;
368349cc55cSDimitry Andric 
36906c3fb27SDimitry Andric       __sanitizer::ListOfModules List;
37006c3fb27SDimitry Andric       List.init();
37106c3fb27SDimitry Andric       ArrayRef<LoadedModule> Modules(List.begin(), List.end());
37206c3fb27SDimitry Andric       u64 BytesSerialized = SerializeToRawProfile(MIBMap, Modules, Buffer);
373349cc55cSDimitry Andric       CHECK(Buffer && BytesSerialized && "could not serialize to buffer");
374349cc55cSDimitry Andric       report_file.Write(Buffer, BytesSerialized);
375349cc55cSDimitry Andric     }
376349cc55cSDimitry Andric 
377349cc55cSDimitry Andric     allocator.ForceUnlock();
378349cc55cSDimitry Andric   }
379349cc55cSDimitry Andric 
380349cc55cSDimitry Andric   // Inserts any blocks which have been allocated but not yet deallocated.
381349cc55cSDimitry Andric   void InsertLiveBlocks() {
382e8d8bef9SDimitry Andric     allocator.ForEachChunk(
383e8d8bef9SDimitry Andric         [](uptr chunk, void *alloc) {
384e8d8bef9SDimitry Andric           u64 user_requested_size;
385349cc55cSDimitry Andric           Allocator *A = (Allocator *)alloc;
386e8d8bef9SDimitry Andric           MemprofChunk *m =
387349cc55cSDimitry Andric               A->GetMemprofChunk((void *)chunk, user_requested_size);
388e8d8bef9SDimitry Andric           if (!m)
389e8d8bef9SDimitry Andric             return;
390e8d8bef9SDimitry Andric           uptr user_beg = ((uptr)m) + kChunkHeaderSize;
391*0fca6ea1SDimitry Andric           MemInfoBlock newMIB = CreateNewMIB(user_beg, m, user_requested_size);
392349cc55cSDimitry Andric           InsertOrMerge(m->alloc_context_id, newMIB, A->MIBMap);
393e8d8bef9SDimitry Andric         },
394e8d8bef9SDimitry Andric         this);
395e8d8bef9SDimitry Andric   }
396e8d8bef9SDimitry Andric 
397e8d8bef9SDimitry Andric   void InitLinkerInitialized() {
398e8d8bef9SDimitry Andric     SetAllocatorMayReturnNull(common_flags()->allocator_may_return_null);
399e8d8bef9SDimitry Andric     allocator.InitLinkerInitialized(
400e8d8bef9SDimitry Andric         common_flags()->allocator_release_to_os_interval_ms);
401e8d8bef9SDimitry Andric     max_user_defined_malloc_size = common_flags()->max_allocation_size_mb
402e8d8bef9SDimitry Andric                                        ? common_flags()->max_allocation_size_mb
403e8d8bef9SDimitry Andric                                              << 20
404e8d8bef9SDimitry Andric                                        : kMaxAllowedMallocSize;
405e8d8bef9SDimitry Andric   }
406e8d8bef9SDimitry Andric 
407e8d8bef9SDimitry Andric   // -------------------- Allocation/Deallocation routines ---------------
408e8d8bef9SDimitry Andric   void *Allocate(uptr size, uptr alignment, BufferedStackTrace *stack,
409e8d8bef9SDimitry Andric                  AllocType alloc_type) {
410e8d8bef9SDimitry Andric     if (UNLIKELY(!memprof_inited))
411e8d8bef9SDimitry Andric       MemprofInitFromRtl();
4120eae32dcSDimitry Andric     if (UNLIKELY(IsRssLimitExceeded())) {
413e8d8bef9SDimitry Andric       if (AllocatorMayReturnNull())
414e8d8bef9SDimitry Andric         return nullptr;
415e8d8bef9SDimitry Andric       ReportRssLimitExceeded(stack);
416e8d8bef9SDimitry Andric     }
417e8d8bef9SDimitry Andric     CHECK(stack);
418e8d8bef9SDimitry Andric     const uptr min_alignment = MEMPROF_ALIGNMENT;
419e8d8bef9SDimitry Andric     if (alignment < min_alignment)
420e8d8bef9SDimitry Andric       alignment = min_alignment;
421e8d8bef9SDimitry Andric     if (size == 0) {
422e8d8bef9SDimitry Andric       // We'd be happy to avoid allocating memory for zero-size requests, but
423e8d8bef9SDimitry Andric       // some programs/tests depend on this behavior and assume that malloc
424e8d8bef9SDimitry Andric       // would not return NULL even for zero-size allocations. Moreover, it
425e8d8bef9SDimitry Andric       // looks like operator new should never return NULL, and results of
426e8d8bef9SDimitry Andric       // consecutive "new" calls must be different even if the allocated size
427e8d8bef9SDimitry Andric       // is zero.
428e8d8bef9SDimitry Andric       size = 1;
429e8d8bef9SDimitry Andric     }
430e8d8bef9SDimitry Andric     CHECK(IsPowerOfTwo(alignment));
431e8d8bef9SDimitry Andric     uptr rounded_size = RoundUpTo(size, alignment);
432e8d8bef9SDimitry Andric     uptr needed_size = rounded_size + kChunkHeaderSize;
433e8d8bef9SDimitry Andric     if (alignment > min_alignment)
434e8d8bef9SDimitry Andric       needed_size += alignment;
435e8d8bef9SDimitry Andric     CHECK(IsAligned(needed_size, min_alignment));
436e8d8bef9SDimitry Andric     if (size > kMaxAllowedMallocSize || needed_size > kMaxAllowedMallocSize ||
437e8d8bef9SDimitry Andric         size > max_user_defined_malloc_size) {
438e8d8bef9SDimitry Andric       if (AllocatorMayReturnNull()) {
439349cc55cSDimitry Andric         Report("WARNING: MemProfiler failed to allocate 0x%zx bytes\n", size);
440e8d8bef9SDimitry Andric         return nullptr;
441e8d8bef9SDimitry Andric       }
442e8d8bef9SDimitry Andric       uptr malloc_limit =
443e8d8bef9SDimitry Andric           Min(kMaxAllowedMallocSize, max_user_defined_malloc_size);
444e8d8bef9SDimitry Andric       ReportAllocationSizeTooBig(size, malloc_limit, stack);
445e8d8bef9SDimitry Andric     }
446e8d8bef9SDimitry Andric 
447e8d8bef9SDimitry Andric     MemprofThread *t = GetCurrentThread();
448e8d8bef9SDimitry Andric     void *allocated;
449e8d8bef9SDimitry Andric     if (t) {
450e8d8bef9SDimitry Andric       AllocatorCache *cache = GetAllocatorCache(&t->malloc_storage());
451e8d8bef9SDimitry Andric       allocated = allocator.Allocate(cache, needed_size, 8);
452e8d8bef9SDimitry Andric     } else {
453e8d8bef9SDimitry Andric       SpinMutexLock l(&fallback_mutex);
454e8d8bef9SDimitry Andric       AllocatorCache *cache = &fallback_allocator_cache;
455e8d8bef9SDimitry Andric       allocated = allocator.Allocate(cache, needed_size, 8);
456e8d8bef9SDimitry Andric     }
457e8d8bef9SDimitry Andric     if (UNLIKELY(!allocated)) {
458e8d8bef9SDimitry Andric       SetAllocatorOutOfMemory();
459e8d8bef9SDimitry Andric       if (AllocatorMayReturnNull())
460e8d8bef9SDimitry Andric         return nullptr;
461e8d8bef9SDimitry Andric       ReportOutOfMemory(size, stack);
462e8d8bef9SDimitry Andric     }
463e8d8bef9SDimitry Andric 
464e8d8bef9SDimitry Andric     uptr alloc_beg = reinterpret_cast<uptr>(allocated);
465e8d8bef9SDimitry Andric     uptr alloc_end = alloc_beg + needed_size;
466e8d8bef9SDimitry Andric     uptr beg_plus_header = alloc_beg + kChunkHeaderSize;
467e8d8bef9SDimitry Andric     uptr user_beg = beg_plus_header;
468e8d8bef9SDimitry Andric     if (!IsAligned(user_beg, alignment))
469e8d8bef9SDimitry Andric       user_beg = RoundUpTo(user_beg, alignment);
470e8d8bef9SDimitry Andric     uptr user_end = user_beg + size;
471e8d8bef9SDimitry Andric     CHECK_LE(user_end, alloc_end);
472e8d8bef9SDimitry Andric     uptr chunk_beg = user_beg - kChunkHeaderSize;
473e8d8bef9SDimitry Andric     MemprofChunk *m = reinterpret_cast<MemprofChunk *>(chunk_beg);
474e8d8bef9SDimitry Andric     m->from_memalign = alloc_beg != chunk_beg;
475e8d8bef9SDimitry Andric     CHECK(size);
476e8d8bef9SDimitry Andric 
477e8d8bef9SDimitry Andric     m->cpu_id = GetCpuId();
478e8d8bef9SDimitry Andric     m->timestamp_ms = GetTimestamp();
479e8d8bef9SDimitry Andric     m->alloc_context_id = StackDepotPut(*stack);
480e8d8bef9SDimitry Andric 
481e8d8bef9SDimitry Andric     uptr size_rounded_down_to_granularity =
482e8d8bef9SDimitry Andric         RoundDownTo(size, SHADOW_GRANULARITY);
483e8d8bef9SDimitry Andric     if (size_rounded_down_to_granularity)
484e8d8bef9SDimitry Andric       ClearShadow(user_beg, size_rounded_down_to_granularity);
485e8d8bef9SDimitry Andric 
486e8d8bef9SDimitry Andric     MemprofStats &thread_stats = GetCurrentThreadStats();
487e8d8bef9SDimitry Andric     thread_stats.mallocs++;
488e8d8bef9SDimitry Andric     thread_stats.malloced += size;
489e8d8bef9SDimitry Andric     thread_stats.malloced_overhead += needed_size - size;
490e8d8bef9SDimitry Andric     if (needed_size > SizeClassMap::kMaxSize)
491e8d8bef9SDimitry Andric       thread_stats.malloc_large++;
492e8d8bef9SDimitry Andric     else
493e8d8bef9SDimitry Andric       thread_stats.malloced_by_size[SizeClassMap::ClassID(needed_size)]++;
494e8d8bef9SDimitry Andric 
495e8d8bef9SDimitry Andric     void *res = reinterpret_cast<void *>(user_beg);
496e8d8bef9SDimitry Andric     atomic_store(&m->user_requested_size, size, memory_order_release);
497e8d8bef9SDimitry Andric     if (alloc_beg != chunk_beg) {
498e8d8bef9SDimitry Andric       CHECK_LE(alloc_beg + sizeof(LargeChunkHeader), chunk_beg);
499e8d8bef9SDimitry Andric       reinterpret_cast<LargeChunkHeader *>(alloc_beg)->Set(m);
500e8d8bef9SDimitry Andric     }
50181ad6265SDimitry Andric     RunMallocHooks(res, size);
502e8d8bef9SDimitry Andric     return res;
503e8d8bef9SDimitry Andric   }
504e8d8bef9SDimitry Andric 
505e8d8bef9SDimitry Andric   void Deallocate(void *ptr, uptr delete_size, uptr delete_alignment,
506e8d8bef9SDimitry Andric                   BufferedStackTrace *stack, AllocType alloc_type) {
507e8d8bef9SDimitry Andric     uptr p = reinterpret_cast<uptr>(ptr);
508e8d8bef9SDimitry Andric     if (p == 0)
509e8d8bef9SDimitry Andric       return;
510e8d8bef9SDimitry Andric 
51181ad6265SDimitry Andric     RunFreeHooks(ptr);
512e8d8bef9SDimitry Andric 
513e8d8bef9SDimitry Andric     uptr chunk_beg = p - kChunkHeaderSize;
514e8d8bef9SDimitry Andric     MemprofChunk *m = reinterpret_cast<MemprofChunk *>(chunk_beg);
515e8d8bef9SDimitry Andric 
516e8d8bef9SDimitry Andric     u64 user_requested_size =
517e8d8bef9SDimitry Andric         atomic_exchange(&m->user_requested_size, 0, memory_order_acquire);
51806c3fb27SDimitry Andric     if (memprof_inited && atomic_load_relaxed(&constructed) &&
519349cc55cSDimitry Andric         !atomic_load_relaxed(&destructing)) {
520*0fca6ea1SDimitry Andric       MemInfoBlock newMIB = this->CreateNewMIB(p, m, user_requested_size);
521349cc55cSDimitry Andric       InsertOrMerge(m->alloc_context_id, newMIB, MIBMap);
522e8d8bef9SDimitry Andric     }
523e8d8bef9SDimitry Andric 
524e8d8bef9SDimitry Andric     MemprofStats &thread_stats = GetCurrentThreadStats();
525e8d8bef9SDimitry Andric     thread_stats.frees++;
526e8d8bef9SDimitry Andric     thread_stats.freed += user_requested_size;
527e8d8bef9SDimitry Andric 
528e8d8bef9SDimitry Andric     void *alloc_beg = m->AllocBeg();
529e8d8bef9SDimitry Andric     if (alloc_beg != m) {
530e8d8bef9SDimitry Andric       // Clear the magic value, as allocator internals may overwrite the
531e8d8bef9SDimitry Andric       // contents of deallocated chunk, confusing GetMemprofChunk lookup.
532e8d8bef9SDimitry Andric       reinterpret_cast<LargeChunkHeader *>(alloc_beg)->Set(nullptr);
533e8d8bef9SDimitry Andric     }
534e8d8bef9SDimitry Andric 
535e8d8bef9SDimitry Andric     MemprofThread *t = GetCurrentThread();
536e8d8bef9SDimitry Andric     if (t) {
537e8d8bef9SDimitry Andric       AllocatorCache *cache = GetAllocatorCache(&t->malloc_storage());
538e8d8bef9SDimitry Andric       allocator.Deallocate(cache, alloc_beg);
539e8d8bef9SDimitry Andric     } else {
540e8d8bef9SDimitry Andric       SpinMutexLock l(&fallback_mutex);
541e8d8bef9SDimitry Andric       AllocatorCache *cache = &fallback_allocator_cache;
542e8d8bef9SDimitry Andric       allocator.Deallocate(cache, alloc_beg);
543e8d8bef9SDimitry Andric     }
544e8d8bef9SDimitry Andric   }
545e8d8bef9SDimitry Andric 
546e8d8bef9SDimitry Andric   void *Reallocate(void *old_ptr, uptr new_size, BufferedStackTrace *stack) {
547e8d8bef9SDimitry Andric     CHECK(old_ptr && new_size);
548e8d8bef9SDimitry Andric     uptr p = reinterpret_cast<uptr>(old_ptr);
549e8d8bef9SDimitry Andric     uptr chunk_beg = p - kChunkHeaderSize;
550e8d8bef9SDimitry Andric     MemprofChunk *m = reinterpret_cast<MemprofChunk *>(chunk_beg);
551e8d8bef9SDimitry Andric 
552e8d8bef9SDimitry Andric     MemprofStats &thread_stats = GetCurrentThreadStats();
553e8d8bef9SDimitry Andric     thread_stats.reallocs++;
554e8d8bef9SDimitry Andric     thread_stats.realloced += new_size;
555e8d8bef9SDimitry Andric 
556e8d8bef9SDimitry Andric     void *new_ptr = Allocate(new_size, 8, stack, FROM_MALLOC);
557e8d8bef9SDimitry Andric     if (new_ptr) {
558e8d8bef9SDimitry Andric       CHECK_NE(REAL(memcpy), nullptr);
559e8d8bef9SDimitry Andric       uptr memcpy_size = Min(new_size, m->UsedSize());
560e8d8bef9SDimitry Andric       REAL(memcpy)(new_ptr, old_ptr, memcpy_size);
561e8d8bef9SDimitry Andric       Deallocate(old_ptr, 0, 0, stack, FROM_MALLOC);
562e8d8bef9SDimitry Andric     }
563e8d8bef9SDimitry Andric     return new_ptr;
564e8d8bef9SDimitry Andric   }
565e8d8bef9SDimitry Andric 
566e8d8bef9SDimitry Andric   void *Calloc(uptr nmemb, uptr size, BufferedStackTrace *stack) {
567e8d8bef9SDimitry Andric     if (UNLIKELY(CheckForCallocOverflow(size, nmemb))) {
568e8d8bef9SDimitry Andric       if (AllocatorMayReturnNull())
569e8d8bef9SDimitry Andric         return nullptr;
570e8d8bef9SDimitry Andric       ReportCallocOverflow(nmemb, size, stack);
571e8d8bef9SDimitry Andric     }
572e8d8bef9SDimitry Andric     void *ptr = Allocate(nmemb * size, 8, stack, FROM_MALLOC);
573e8d8bef9SDimitry Andric     // If the memory comes from the secondary allocator no need to clear it
574e8d8bef9SDimitry Andric     // as it comes directly from mmap.
575e8d8bef9SDimitry Andric     if (ptr && allocator.FromPrimary(ptr))
576e8d8bef9SDimitry Andric       REAL(memset)(ptr, 0, nmemb * size);
577e8d8bef9SDimitry Andric     return ptr;
578e8d8bef9SDimitry Andric   }
579e8d8bef9SDimitry Andric 
580*0fca6ea1SDimitry Andric   void CommitBack(MemprofThreadLocalMallocStorage *ms) {
581e8d8bef9SDimitry Andric     AllocatorCache *ac = GetAllocatorCache(ms);
582e8d8bef9SDimitry Andric     allocator.SwallowCache(ac);
583e8d8bef9SDimitry Andric   }
584e8d8bef9SDimitry Andric 
585e8d8bef9SDimitry Andric   // -------------------------- Chunk lookup ----------------------
586e8d8bef9SDimitry Andric 
587e8d8bef9SDimitry Andric   // Assumes alloc_beg == allocator.GetBlockBegin(alloc_beg).
588e8d8bef9SDimitry Andric   MemprofChunk *GetMemprofChunk(void *alloc_beg, u64 &user_requested_size) {
589e8d8bef9SDimitry Andric     if (!alloc_beg)
590e8d8bef9SDimitry Andric       return nullptr;
591e8d8bef9SDimitry Andric     MemprofChunk *p = reinterpret_cast<LargeChunkHeader *>(alloc_beg)->Get();
592e8d8bef9SDimitry Andric     if (!p) {
593e8d8bef9SDimitry Andric       if (!allocator.FromPrimary(alloc_beg))
594e8d8bef9SDimitry Andric         return nullptr;
595e8d8bef9SDimitry Andric       p = reinterpret_cast<MemprofChunk *>(alloc_beg);
596e8d8bef9SDimitry Andric     }
597e8d8bef9SDimitry Andric     // The size is reset to 0 on deallocation (and a min of 1 on
598e8d8bef9SDimitry Andric     // allocation).
599e8d8bef9SDimitry Andric     user_requested_size =
600e8d8bef9SDimitry Andric         atomic_load(&p->user_requested_size, memory_order_acquire);
601e8d8bef9SDimitry Andric     if (user_requested_size)
602e8d8bef9SDimitry Andric       return p;
603e8d8bef9SDimitry Andric     return nullptr;
604e8d8bef9SDimitry Andric   }
605e8d8bef9SDimitry Andric 
606e8d8bef9SDimitry Andric   MemprofChunk *GetMemprofChunkByAddr(uptr p, u64 &user_requested_size) {
607e8d8bef9SDimitry Andric     void *alloc_beg = allocator.GetBlockBegin(reinterpret_cast<void *>(p));
608e8d8bef9SDimitry Andric     return GetMemprofChunk(alloc_beg, user_requested_size);
609e8d8bef9SDimitry Andric   }
610e8d8bef9SDimitry Andric 
611e8d8bef9SDimitry Andric   uptr AllocationSize(uptr p) {
612e8d8bef9SDimitry Andric     u64 user_requested_size;
613e8d8bef9SDimitry Andric     MemprofChunk *m = GetMemprofChunkByAddr(p, user_requested_size);
614e8d8bef9SDimitry Andric     if (!m)
615e8d8bef9SDimitry Andric       return 0;
616e8d8bef9SDimitry Andric     if (m->Beg() != p)
617e8d8bef9SDimitry Andric       return 0;
618e8d8bef9SDimitry Andric     return user_requested_size;
619e8d8bef9SDimitry Andric   }
620e8d8bef9SDimitry Andric 
62106c3fb27SDimitry Andric   uptr AllocationSizeFast(uptr p) {
62206c3fb27SDimitry Andric     return reinterpret_cast<MemprofChunk *>(p - kChunkHeaderSize)->UsedSize();
62306c3fb27SDimitry Andric   }
62406c3fb27SDimitry Andric 
625*0fca6ea1SDimitry Andric   void Purge() { allocator.ForceReleaseToOS(); }
626e8d8bef9SDimitry Andric 
627e8d8bef9SDimitry Andric   void PrintStats() { allocator.PrintStats(); }
628e8d8bef9SDimitry Andric 
62904eeddc0SDimitry Andric   void ForceLock() SANITIZER_NO_THREAD_SAFETY_ANALYSIS {
630e8d8bef9SDimitry Andric     allocator.ForceLock();
631e8d8bef9SDimitry Andric     fallback_mutex.Lock();
632e8d8bef9SDimitry Andric   }
633e8d8bef9SDimitry Andric 
63404eeddc0SDimitry Andric   void ForceUnlock() SANITIZER_NO_THREAD_SAFETY_ANALYSIS {
635e8d8bef9SDimitry Andric     fallback_mutex.Unlock();
636e8d8bef9SDimitry Andric     allocator.ForceUnlock();
637e8d8bef9SDimitry Andric   }
638e8d8bef9SDimitry Andric };
639e8d8bef9SDimitry Andric 
640e8d8bef9SDimitry Andric static Allocator instance(LINKER_INITIALIZED);
641e8d8bef9SDimitry Andric 
642e8d8bef9SDimitry Andric static MemprofAllocator &get_allocator() { return instance.allocator; }
643e8d8bef9SDimitry Andric 
644e8d8bef9SDimitry Andric void InitializeAllocator() { instance.InitLinkerInitialized(); }
645e8d8bef9SDimitry Andric 
646e8d8bef9SDimitry Andric void MemprofThreadLocalMallocStorage::CommitBack() {
647*0fca6ea1SDimitry Andric   instance.CommitBack(this);
648e8d8bef9SDimitry Andric }
649e8d8bef9SDimitry Andric 
650e8d8bef9SDimitry Andric void PrintInternalAllocatorStats() { instance.PrintStats(); }
651e8d8bef9SDimitry Andric 
652e8d8bef9SDimitry Andric void memprof_free(void *ptr, BufferedStackTrace *stack, AllocType alloc_type) {
653e8d8bef9SDimitry Andric   instance.Deallocate(ptr, 0, 0, stack, alloc_type);
654e8d8bef9SDimitry Andric }
655e8d8bef9SDimitry Andric 
656e8d8bef9SDimitry Andric void memprof_delete(void *ptr, uptr size, uptr alignment,
657e8d8bef9SDimitry Andric                     BufferedStackTrace *stack, AllocType alloc_type) {
658e8d8bef9SDimitry Andric   instance.Deallocate(ptr, size, alignment, stack, alloc_type);
659e8d8bef9SDimitry Andric }
660e8d8bef9SDimitry Andric 
661e8d8bef9SDimitry Andric void *memprof_malloc(uptr size, BufferedStackTrace *stack) {
662e8d8bef9SDimitry Andric   return SetErrnoOnNull(instance.Allocate(size, 8, stack, FROM_MALLOC));
663e8d8bef9SDimitry Andric }
664e8d8bef9SDimitry Andric 
665e8d8bef9SDimitry Andric void *memprof_calloc(uptr nmemb, uptr size, BufferedStackTrace *stack) {
666e8d8bef9SDimitry Andric   return SetErrnoOnNull(instance.Calloc(nmemb, size, stack));
667e8d8bef9SDimitry Andric }
668e8d8bef9SDimitry Andric 
669e8d8bef9SDimitry Andric void *memprof_reallocarray(void *p, uptr nmemb, uptr size,
670e8d8bef9SDimitry Andric                            BufferedStackTrace *stack) {
671e8d8bef9SDimitry Andric   if (UNLIKELY(CheckForCallocOverflow(size, nmemb))) {
672e8d8bef9SDimitry Andric     errno = errno_ENOMEM;
673e8d8bef9SDimitry Andric     if (AllocatorMayReturnNull())
674e8d8bef9SDimitry Andric       return nullptr;
675e8d8bef9SDimitry Andric     ReportReallocArrayOverflow(nmemb, size, stack);
676e8d8bef9SDimitry Andric   }
677e8d8bef9SDimitry Andric   return memprof_realloc(p, nmemb * size, stack);
678e8d8bef9SDimitry Andric }
679e8d8bef9SDimitry Andric 
680e8d8bef9SDimitry Andric void *memprof_realloc(void *p, uptr size, BufferedStackTrace *stack) {
681e8d8bef9SDimitry Andric   if (!p)
682e8d8bef9SDimitry Andric     return SetErrnoOnNull(instance.Allocate(size, 8, stack, FROM_MALLOC));
683e8d8bef9SDimitry Andric   if (size == 0) {
684e8d8bef9SDimitry Andric     if (flags()->allocator_frees_and_returns_null_on_realloc_zero) {
685e8d8bef9SDimitry Andric       instance.Deallocate(p, 0, 0, stack, FROM_MALLOC);
686e8d8bef9SDimitry Andric       return nullptr;
687e8d8bef9SDimitry Andric     }
688e8d8bef9SDimitry Andric     // Allocate a size of 1 if we shouldn't free() on Realloc to 0
689e8d8bef9SDimitry Andric     size = 1;
690e8d8bef9SDimitry Andric   }
691e8d8bef9SDimitry Andric   return SetErrnoOnNull(instance.Reallocate(p, size, stack));
692e8d8bef9SDimitry Andric }
693e8d8bef9SDimitry Andric 
694e8d8bef9SDimitry Andric void *memprof_valloc(uptr size, BufferedStackTrace *stack) {
695e8d8bef9SDimitry Andric   return SetErrnoOnNull(
696e8d8bef9SDimitry Andric       instance.Allocate(size, GetPageSizeCached(), stack, FROM_MALLOC));
697e8d8bef9SDimitry Andric }
698e8d8bef9SDimitry Andric 
699e8d8bef9SDimitry Andric void *memprof_pvalloc(uptr size, BufferedStackTrace *stack) {
700e8d8bef9SDimitry Andric   uptr PageSize = GetPageSizeCached();
701e8d8bef9SDimitry Andric   if (UNLIKELY(CheckForPvallocOverflow(size, PageSize))) {
702e8d8bef9SDimitry Andric     errno = errno_ENOMEM;
703e8d8bef9SDimitry Andric     if (AllocatorMayReturnNull())
704e8d8bef9SDimitry Andric       return nullptr;
705e8d8bef9SDimitry Andric     ReportPvallocOverflow(size, stack);
706e8d8bef9SDimitry Andric   }
707e8d8bef9SDimitry Andric   // pvalloc(0) should allocate one page.
708e8d8bef9SDimitry Andric   size = size ? RoundUpTo(size, PageSize) : PageSize;
709e8d8bef9SDimitry Andric   return SetErrnoOnNull(instance.Allocate(size, PageSize, stack, FROM_MALLOC));
710e8d8bef9SDimitry Andric }
711e8d8bef9SDimitry Andric 
712e8d8bef9SDimitry Andric void *memprof_memalign(uptr alignment, uptr size, BufferedStackTrace *stack,
713e8d8bef9SDimitry Andric                        AllocType alloc_type) {
714e8d8bef9SDimitry Andric   if (UNLIKELY(!IsPowerOfTwo(alignment))) {
715e8d8bef9SDimitry Andric     errno = errno_EINVAL;
716e8d8bef9SDimitry Andric     if (AllocatorMayReturnNull())
717e8d8bef9SDimitry Andric       return nullptr;
718e8d8bef9SDimitry Andric     ReportInvalidAllocationAlignment(alignment, stack);
719e8d8bef9SDimitry Andric   }
720e8d8bef9SDimitry Andric   return SetErrnoOnNull(instance.Allocate(size, alignment, stack, alloc_type));
721e8d8bef9SDimitry Andric }
722e8d8bef9SDimitry Andric 
723e8d8bef9SDimitry Andric void *memprof_aligned_alloc(uptr alignment, uptr size,
724e8d8bef9SDimitry Andric                             BufferedStackTrace *stack) {
725e8d8bef9SDimitry Andric   if (UNLIKELY(!CheckAlignedAllocAlignmentAndSize(alignment, size))) {
726e8d8bef9SDimitry Andric     errno = errno_EINVAL;
727e8d8bef9SDimitry Andric     if (AllocatorMayReturnNull())
728e8d8bef9SDimitry Andric       return nullptr;
729e8d8bef9SDimitry Andric     ReportInvalidAlignedAllocAlignment(size, alignment, stack);
730e8d8bef9SDimitry Andric   }
731e8d8bef9SDimitry Andric   return SetErrnoOnNull(instance.Allocate(size, alignment, stack, FROM_MALLOC));
732e8d8bef9SDimitry Andric }
733e8d8bef9SDimitry Andric 
734e8d8bef9SDimitry Andric int memprof_posix_memalign(void **memptr, uptr alignment, uptr size,
735e8d8bef9SDimitry Andric                            BufferedStackTrace *stack) {
736e8d8bef9SDimitry Andric   if (UNLIKELY(!CheckPosixMemalignAlignment(alignment))) {
737e8d8bef9SDimitry Andric     if (AllocatorMayReturnNull())
738e8d8bef9SDimitry Andric       return errno_EINVAL;
739e8d8bef9SDimitry Andric     ReportInvalidPosixMemalignAlignment(alignment, stack);
740e8d8bef9SDimitry Andric   }
741e8d8bef9SDimitry Andric   void *ptr = instance.Allocate(size, alignment, stack, FROM_MALLOC);
742e8d8bef9SDimitry Andric   if (UNLIKELY(!ptr))
743e8d8bef9SDimitry Andric     // OOM error is already taken care of by Allocate.
744e8d8bef9SDimitry Andric     return errno_ENOMEM;
745e8d8bef9SDimitry Andric   CHECK(IsAligned((uptr)ptr, alignment));
746e8d8bef9SDimitry Andric   *memptr = ptr;
747e8d8bef9SDimitry Andric   return 0;
748e8d8bef9SDimitry Andric }
749e8d8bef9SDimitry Andric 
75006c3fb27SDimitry Andric static const void *memprof_malloc_begin(const void *p) {
75106c3fb27SDimitry Andric   u64 user_requested_size;
75206c3fb27SDimitry Andric   MemprofChunk *m =
75306c3fb27SDimitry Andric       instance.GetMemprofChunkByAddr((uptr)p, user_requested_size);
75406c3fb27SDimitry Andric   if (!m)
75506c3fb27SDimitry Andric     return nullptr;
75606c3fb27SDimitry Andric   if (user_requested_size == 0)
75706c3fb27SDimitry Andric     return nullptr;
75806c3fb27SDimitry Andric 
75906c3fb27SDimitry Andric   return (const void *)m->Beg();
76006c3fb27SDimitry Andric }
76106c3fb27SDimitry Andric 
762*0fca6ea1SDimitry Andric uptr memprof_malloc_usable_size(const void *ptr) {
763e8d8bef9SDimitry Andric   if (!ptr)
764e8d8bef9SDimitry Andric     return 0;
765e8d8bef9SDimitry Andric   uptr usable_size = instance.AllocationSize(reinterpret_cast<uptr>(ptr));
766e8d8bef9SDimitry Andric   return usable_size;
767e8d8bef9SDimitry Andric }
768e8d8bef9SDimitry Andric 
769e8d8bef9SDimitry Andric } // namespace __memprof
770e8d8bef9SDimitry Andric 
771e8d8bef9SDimitry Andric // ---------------------- Interface ---------------- {{{1
772e8d8bef9SDimitry Andric using namespace __memprof;
773e8d8bef9SDimitry Andric 
774e8d8bef9SDimitry Andric uptr __sanitizer_get_estimated_allocated_size(uptr size) { return size; }
775e8d8bef9SDimitry Andric 
776e8d8bef9SDimitry Andric int __sanitizer_get_ownership(const void *p) {
777*0fca6ea1SDimitry Andric   return memprof_malloc_usable_size(p) != 0;
778e8d8bef9SDimitry Andric }
779e8d8bef9SDimitry Andric 
78006c3fb27SDimitry Andric const void *__sanitizer_get_allocated_begin(const void *p) {
78106c3fb27SDimitry Andric   return memprof_malloc_begin(p);
78206c3fb27SDimitry Andric }
78306c3fb27SDimitry Andric 
784e8d8bef9SDimitry Andric uptr __sanitizer_get_allocated_size(const void *p) {
785*0fca6ea1SDimitry Andric   return memprof_malloc_usable_size(p);
786e8d8bef9SDimitry Andric }
787e8d8bef9SDimitry Andric 
78806c3fb27SDimitry Andric uptr __sanitizer_get_allocated_size_fast(const void *p) {
78906c3fb27SDimitry Andric   DCHECK_EQ(p, __sanitizer_get_allocated_begin(p));
79006c3fb27SDimitry Andric   uptr ret = instance.AllocationSizeFast(reinterpret_cast<uptr>(p));
79106c3fb27SDimitry Andric   DCHECK_EQ(ret, __sanitizer_get_allocated_size(p));
79206c3fb27SDimitry Andric   return ret;
79306c3fb27SDimitry Andric }
79406c3fb27SDimitry Andric 
795*0fca6ea1SDimitry Andric void __sanitizer_purge_allocator() { instance.Purge(); }
796*0fca6ea1SDimitry Andric 
797e8d8bef9SDimitry Andric int __memprof_profile_dump() {
798349cc55cSDimitry Andric   instance.FinishAndWrite();
799e8d8bef9SDimitry Andric   // In the future we may want to return non-zero if there are any errors
800e8d8bef9SDimitry Andric   // detected during the dumping process.
801e8d8bef9SDimitry Andric   return 0;
802e8d8bef9SDimitry Andric }
8035f757f3fSDimitry Andric 
8045f757f3fSDimitry Andric void __memprof_profile_reset() {
8055f757f3fSDimitry Andric   if (report_file.fd != kInvalidFd && report_file.fd != kStdoutFd &&
8065f757f3fSDimitry Andric       report_file.fd != kStderrFd) {
8075f757f3fSDimitry Andric     CloseFile(report_file.fd);
8085f757f3fSDimitry Andric     // Setting the file descriptor to kInvalidFd ensures that we will reopen the
8095f757f3fSDimitry Andric     // file when invoking Write again.
8105f757f3fSDimitry Andric     report_file.fd = kInvalidFd;
8115f757f3fSDimitry Andric   }
8125f757f3fSDimitry Andric }
813