1 //===-- memprof_allocator.cpp --------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file is a part of MemProfiler, a memory profiler.
10 //
11 // Implementation of MemProf's memory allocator, which uses the allocator
12 // from sanitizer_common.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "memprof_allocator.h"
17 #include "memprof_mapping.h"
18 #include "memprof_meminfoblock.h"
19 #include "memprof_mibmap.h"
20 #include "memprof_rawprofile.h"
21 #include "memprof_stack.h"
22 #include "memprof_thread.h"
23 #include "sanitizer_common/sanitizer_allocator_checks.h"
24 #include "sanitizer_common/sanitizer_allocator_interface.h"
25 #include "sanitizer_common/sanitizer_allocator_report.h"
26 #include "sanitizer_common/sanitizer_errno.h"
27 #include "sanitizer_common/sanitizer_file.h"
28 #include "sanitizer_common/sanitizer_flags.h"
29 #include "sanitizer_common/sanitizer_internal_defs.h"
30 #include "sanitizer_common/sanitizer_list.h"
31 #include "sanitizer_common/sanitizer_procmaps.h"
32 #include "sanitizer_common/sanitizer_stackdepot.h"
33 #include "sanitizer_common/sanitizer_vector.h"
34 
35 #include <sched.h>
36 #include <time.h>
37 
38 namespace __memprof {
39 
40 static int GetCpuId(void) {
41   // _memprof_preinit is called via the preinit_array, which subsequently calls
42   // malloc. Since this is before _dl_init calls VDSO_SETUP, sched_getcpu
43   // will seg fault as the address of __vdso_getcpu will be null.
44   if (!memprof_init_done)
45     return -1;
46   return sched_getcpu();
47 }
48 
49 // Compute the timestamp in ms.
50 static int GetTimestamp(void) {
51   // timespec_get will segfault if called from dl_init
52   if (!memprof_timestamp_inited) {
53     // By returning 0, this will be effectively treated as being
54     // timestamped at memprof init time (when memprof_init_timestamp_s
55     // is initialized).
56     return 0;
57   }
58   timespec ts;
59   clock_gettime(CLOCK_REALTIME, &ts);
60   return (ts.tv_sec - memprof_init_timestamp_s) * 1000 + ts.tv_nsec / 1000000;
61 }
62 
63 static MemprofAllocator &get_allocator();
64 
65 // The memory chunk allocated from the underlying allocator looks like this:
66 // H H U U U U U U
67 //   H -- ChunkHeader (32 bytes)
68 //   U -- user memory.
69 
70 // If there is left padding before the ChunkHeader (due to use of memalign),
71 // we store a magic value in the first uptr word of the memory block and
72 // store the address of ChunkHeader in the next uptr.
73 // M B L L L L L L L L L  H H U U U U U U
74 //   |                    ^
75 //   ---------------------|
76 //   M -- magic value kAllocBegMagic
77 //   B -- address of ChunkHeader pointing to the first 'H'
78 
79 constexpr uptr kMaxAllowedMallocBits = 40;
80 
81 // Should be no more than 32-bytes
82 struct ChunkHeader {
83   // 1-st 4 bytes.
84   u32 alloc_context_id;
85   // 2-nd 4 bytes
86   u32 cpu_id;
87   // 3-rd 4 bytes
88   u32 timestamp_ms;
89   // 4-th 4 bytes
90   // Note only 1 bit is needed for this flag if we need space in the future for
91   // more fields.
92   u32 from_memalign;
93   // 5-th and 6-th 4 bytes
94   // The max size of an allocation is 2^40 (kMaxAllowedMallocSize), so this
95   // could be shrunk to kMaxAllowedMallocBits if we need space in the future for
96   // more fields.
97   atomic_uint64_t user_requested_size;
98   // 23 bits available
99   // 7-th and 8-th 4 bytes
100   u64 data_type_id; // TODO: hash of type name
101 };
102 
103 static const uptr kChunkHeaderSize = sizeof(ChunkHeader);
104 COMPILER_CHECK(kChunkHeaderSize == 32);
105 
106 struct MemprofChunk : ChunkHeader {
107   uptr Beg() { return reinterpret_cast<uptr>(this) + kChunkHeaderSize; }
108   uptr UsedSize() {
109     return atomic_load(&user_requested_size, memory_order_relaxed);
110   }
111   void *AllocBeg() {
112     if (from_memalign)
113       return get_allocator().GetBlockBegin(reinterpret_cast<void *>(this));
114     return reinterpret_cast<void *>(this);
115   }
116 };
117 
118 class LargeChunkHeader {
119   static constexpr uptr kAllocBegMagic =
120       FIRST_32_SECOND_64(0xCC6E96B9, 0xCC6E96B9CC6E96B9ULL);
121   atomic_uintptr_t magic;
122   MemprofChunk *chunk_header;
123 
124 public:
125   MemprofChunk *Get() const {
126     return atomic_load(&magic, memory_order_acquire) == kAllocBegMagic
127                ? chunk_header
128                : nullptr;
129   }
130 
131   void Set(MemprofChunk *p) {
132     if (p) {
133       chunk_header = p;
134       atomic_store(&magic, kAllocBegMagic, memory_order_release);
135       return;
136     }
137 
138     uptr old = kAllocBegMagic;
139     if (!atomic_compare_exchange_strong(&magic, &old, 0,
140                                         memory_order_release)) {
141       CHECK_EQ(old, kAllocBegMagic);
142     }
143   }
144 };
145 
146 void FlushUnneededMemProfShadowMemory(uptr p, uptr size) {
147   // Since memprof's mapping is compacting, the shadow chunk may be
148   // not page-aligned, so we only flush the page-aligned portion.
149   ReleaseMemoryPagesToOS(MemToShadow(p), MemToShadow(p + size));
150 }
151 
152 void MemprofMapUnmapCallback::OnMap(uptr p, uptr size) const {
153   // Statistics.
154   MemprofStats &thread_stats = GetCurrentThreadStats();
155   thread_stats.mmaps++;
156   thread_stats.mmaped += size;
157 }
158 void MemprofMapUnmapCallback::OnUnmap(uptr p, uptr size) const {
159   // We are about to unmap a chunk of user memory.
160   // Mark the corresponding shadow memory as not needed.
161   FlushUnneededMemProfShadowMemory(p, size);
162   // Statistics.
163   MemprofStats &thread_stats = GetCurrentThreadStats();
164   thread_stats.munmaps++;
165   thread_stats.munmaped += size;
166 }
167 
168 AllocatorCache *GetAllocatorCache(MemprofThreadLocalMallocStorage *ms) {
169   CHECK(ms);
170   return &ms->allocator_cache;
171 }
172 
173 // Accumulates the access count from the shadow for the given pointer and size.
174 u64 GetShadowCount(uptr p, u32 size) {
175   u64 *shadow = (u64 *)MEM_TO_SHADOW(p);
176   u64 *shadow_end = (u64 *)MEM_TO_SHADOW(p + size);
177   u64 count = 0;
178   for (; shadow <= shadow_end; shadow++)
179     count += *shadow;
180   return count;
181 }
182 
183 // Clears the shadow counters (when memory is allocated).
184 void ClearShadow(uptr addr, uptr size) {
185   CHECK(AddrIsAlignedByGranularity(addr));
186   CHECK(AddrIsInMem(addr));
187   CHECK(AddrIsAlignedByGranularity(addr + size));
188   CHECK(AddrIsInMem(addr + size - SHADOW_GRANULARITY));
189   CHECK(REAL(memset));
190   uptr shadow_beg = MEM_TO_SHADOW(addr);
191   uptr shadow_end = MEM_TO_SHADOW(addr + size - SHADOW_GRANULARITY) + 1;
192   if (shadow_end - shadow_beg < common_flags()->clear_shadow_mmap_threshold) {
193     REAL(memset)((void *)shadow_beg, 0, shadow_end - shadow_beg);
194   } else {
195     uptr page_size = GetPageSizeCached();
196     uptr page_beg = RoundUpTo(shadow_beg, page_size);
197     uptr page_end = RoundDownTo(shadow_end, page_size);
198 
199     if (page_beg >= page_end) {
200       REAL(memset)((void *)shadow_beg, 0, shadow_end - shadow_beg);
201     } else {
202       if (page_beg != shadow_beg) {
203         REAL(memset)((void *)shadow_beg, 0, page_beg - shadow_beg);
204       }
205       if (page_end != shadow_end) {
206         REAL(memset)((void *)page_end, 0, shadow_end - page_end);
207       }
208       ReserveShadowMemoryRange(page_beg, page_end - 1, nullptr);
209     }
210   }
211 }
212 
213 struct Allocator {
214   static const uptr kMaxAllowedMallocSize = 1ULL << kMaxAllowedMallocBits;
215 
216   MemprofAllocator allocator;
217   StaticSpinMutex fallback_mutex;
218   AllocatorCache fallback_allocator_cache;
219 
220   uptr max_user_defined_malloc_size;
221 
222   // Holds the mapping of stack ids to MemInfoBlocks.
223   MIBMapTy MIBMap;
224 
225   atomic_uint8_t destructing;
226   atomic_uint8_t constructed;
227   bool print_text;
228 
229   // ------------------- Initialization ------------------------
230   explicit Allocator(LinkerInitialized) : print_text(flags()->print_text) {
231     atomic_store_relaxed(&destructing, 0);
232     atomic_store_relaxed(&constructed, 1);
233   }
234 
235   ~Allocator() {
236     atomic_store_relaxed(&destructing, 1);
237     FinishAndWrite();
238   }
239 
240   static void PrintCallback(const uptr Key, LockedMemInfoBlock *const &Value,
241                             void *Arg) {
242     SpinMutexLock(&Value->mutex);
243     Value->mib.Print(Key, bool(Arg));
244   }
245 
246   void FinishAndWrite() {
247     if (print_text && common_flags()->print_module_map)
248       DumpProcessMap();
249 
250     allocator.ForceLock();
251 
252     InsertLiveBlocks();
253     if (print_text) {
254       if (!flags()->print_terse)
255         Printf("Recorded MIBs (incl. live on exit):\n");
256       MIBMap.ForEach(PrintCallback,
257                      reinterpret_cast<void *>(flags()->print_terse));
258       StackDepotPrintAll();
259     } else {
260       // Serialize the contents to a raw profile. Format documented in
261       // memprof_rawprofile.h.
262       char *Buffer = nullptr;
263 
264       MemoryMappingLayout Layout(/*cache_enabled=*/true);
265       u64 BytesSerialized = SerializeToRawProfile(MIBMap, Layout, Buffer);
266       CHECK(Buffer && BytesSerialized && "could not serialize to buffer");
267       report_file.Write(Buffer, BytesSerialized);
268     }
269 
270     allocator.ForceUnlock();
271   }
272 
273   // Inserts any blocks which have been allocated but not yet deallocated.
274   void InsertLiveBlocks() {
275     allocator.ForEachChunk(
276         [](uptr chunk, void *alloc) {
277           u64 user_requested_size;
278           Allocator *A = (Allocator *)alloc;
279           MemprofChunk *m =
280               A->GetMemprofChunk((void *)chunk, user_requested_size);
281           if (!m)
282             return;
283           uptr user_beg = ((uptr)m) + kChunkHeaderSize;
284           u64 c = GetShadowCount(user_beg, user_requested_size);
285           long curtime = GetTimestamp();
286           MemInfoBlock newMIB(user_requested_size, c, m->timestamp_ms, curtime,
287                               m->cpu_id, GetCpuId());
288           InsertOrMerge(m->alloc_context_id, newMIB, A->MIBMap);
289         },
290         this);
291   }
292 
293   void InitLinkerInitialized() {
294     SetAllocatorMayReturnNull(common_flags()->allocator_may_return_null);
295     allocator.InitLinkerInitialized(
296         common_flags()->allocator_release_to_os_interval_ms);
297     max_user_defined_malloc_size = common_flags()->max_allocation_size_mb
298                                        ? common_flags()->max_allocation_size_mb
299                                              << 20
300                                        : kMaxAllowedMallocSize;
301   }
302 
303   // -------------------- Allocation/Deallocation routines ---------------
304   void *Allocate(uptr size, uptr alignment, BufferedStackTrace *stack,
305                  AllocType alloc_type) {
306     if (UNLIKELY(!memprof_inited))
307       MemprofInitFromRtl();
308     if (UNLIKELY(IsRssLimitExceeded())) {
309       if (AllocatorMayReturnNull())
310         return nullptr;
311       ReportRssLimitExceeded(stack);
312     }
313     CHECK(stack);
314     const uptr min_alignment = MEMPROF_ALIGNMENT;
315     if (alignment < min_alignment)
316       alignment = min_alignment;
317     if (size == 0) {
318       // We'd be happy to avoid allocating memory for zero-size requests, but
319       // some programs/tests depend on this behavior and assume that malloc
320       // would not return NULL even for zero-size allocations. Moreover, it
321       // looks like operator new should never return NULL, and results of
322       // consecutive "new" calls must be different even if the allocated size
323       // is zero.
324       size = 1;
325     }
326     CHECK(IsPowerOfTwo(alignment));
327     uptr rounded_size = RoundUpTo(size, alignment);
328     uptr needed_size = rounded_size + kChunkHeaderSize;
329     if (alignment > min_alignment)
330       needed_size += alignment;
331     CHECK(IsAligned(needed_size, min_alignment));
332     if (size > kMaxAllowedMallocSize || needed_size > kMaxAllowedMallocSize ||
333         size > max_user_defined_malloc_size) {
334       if (AllocatorMayReturnNull()) {
335         Report("WARNING: MemProfiler failed to allocate 0x%zx bytes\n", size);
336         return nullptr;
337       }
338       uptr malloc_limit =
339           Min(kMaxAllowedMallocSize, max_user_defined_malloc_size);
340       ReportAllocationSizeTooBig(size, malloc_limit, stack);
341     }
342 
343     MemprofThread *t = GetCurrentThread();
344     void *allocated;
345     if (t) {
346       AllocatorCache *cache = GetAllocatorCache(&t->malloc_storage());
347       allocated = allocator.Allocate(cache, needed_size, 8);
348     } else {
349       SpinMutexLock l(&fallback_mutex);
350       AllocatorCache *cache = &fallback_allocator_cache;
351       allocated = allocator.Allocate(cache, needed_size, 8);
352     }
353     if (UNLIKELY(!allocated)) {
354       SetAllocatorOutOfMemory();
355       if (AllocatorMayReturnNull())
356         return nullptr;
357       ReportOutOfMemory(size, stack);
358     }
359 
360     uptr alloc_beg = reinterpret_cast<uptr>(allocated);
361     uptr alloc_end = alloc_beg + needed_size;
362     uptr beg_plus_header = alloc_beg + kChunkHeaderSize;
363     uptr user_beg = beg_plus_header;
364     if (!IsAligned(user_beg, alignment))
365       user_beg = RoundUpTo(user_beg, alignment);
366     uptr user_end = user_beg + size;
367     CHECK_LE(user_end, alloc_end);
368     uptr chunk_beg = user_beg - kChunkHeaderSize;
369     MemprofChunk *m = reinterpret_cast<MemprofChunk *>(chunk_beg);
370     m->from_memalign = alloc_beg != chunk_beg;
371     CHECK(size);
372 
373     m->cpu_id = GetCpuId();
374     m->timestamp_ms = GetTimestamp();
375     m->alloc_context_id = StackDepotPut(*stack);
376 
377     uptr size_rounded_down_to_granularity =
378         RoundDownTo(size, SHADOW_GRANULARITY);
379     if (size_rounded_down_to_granularity)
380       ClearShadow(user_beg, size_rounded_down_to_granularity);
381 
382     MemprofStats &thread_stats = GetCurrentThreadStats();
383     thread_stats.mallocs++;
384     thread_stats.malloced += size;
385     thread_stats.malloced_overhead += needed_size - size;
386     if (needed_size > SizeClassMap::kMaxSize)
387       thread_stats.malloc_large++;
388     else
389       thread_stats.malloced_by_size[SizeClassMap::ClassID(needed_size)]++;
390 
391     void *res = reinterpret_cast<void *>(user_beg);
392     atomic_store(&m->user_requested_size, size, memory_order_release);
393     if (alloc_beg != chunk_beg) {
394       CHECK_LE(alloc_beg + sizeof(LargeChunkHeader), chunk_beg);
395       reinterpret_cast<LargeChunkHeader *>(alloc_beg)->Set(m);
396     }
397     MEMPROF_MALLOC_HOOK(res, size);
398     return res;
399   }
400 
401   void Deallocate(void *ptr, uptr delete_size, uptr delete_alignment,
402                   BufferedStackTrace *stack, AllocType alloc_type) {
403     uptr p = reinterpret_cast<uptr>(ptr);
404     if (p == 0)
405       return;
406 
407     MEMPROF_FREE_HOOK(ptr);
408 
409     uptr chunk_beg = p - kChunkHeaderSize;
410     MemprofChunk *m = reinterpret_cast<MemprofChunk *>(chunk_beg);
411 
412     u64 user_requested_size =
413         atomic_exchange(&m->user_requested_size, 0, memory_order_acquire);
414     if (memprof_inited && memprof_init_done &&
415         atomic_load_relaxed(&constructed) &&
416         !atomic_load_relaxed(&destructing)) {
417       u64 c = GetShadowCount(p, user_requested_size);
418       long curtime = GetTimestamp();
419 
420       MemInfoBlock newMIB(user_requested_size, c, m->timestamp_ms, curtime,
421                           m->cpu_id, GetCpuId());
422       InsertOrMerge(m->alloc_context_id, newMIB, MIBMap);
423     }
424 
425     MemprofStats &thread_stats = GetCurrentThreadStats();
426     thread_stats.frees++;
427     thread_stats.freed += user_requested_size;
428 
429     void *alloc_beg = m->AllocBeg();
430     if (alloc_beg != m) {
431       // Clear the magic value, as allocator internals may overwrite the
432       // contents of deallocated chunk, confusing GetMemprofChunk lookup.
433       reinterpret_cast<LargeChunkHeader *>(alloc_beg)->Set(nullptr);
434     }
435 
436     MemprofThread *t = GetCurrentThread();
437     if (t) {
438       AllocatorCache *cache = GetAllocatorCache(&t->malloc_storage());
439       allocator.Deallocate(cache, alloc_beg);
440     } else {
441       SpinMutexLock l(&fallback_mutex);
442       AllocatorCache *cache = &fallback_allocator_cache;
443       allocator.Deallocate(cache, alloc_beg);
444     }
445   }
446 
447   void *Reallocate(void *old_ptr, uptr new_size, BufferedStackTrace *stack) {
448     CHECK(old_ptr && new_size);
449     uptr p = reinterpret_cast<uptr>(old_ptr);
450     uptr chunk_beg = p - kChunkHeaderSize;
451     MemprofChunk *m = reinterpret_cast<MemprofChunk *>(chunk_beg);
452 
453     MemprofStats &thread_stats = GetCurrentThreadStats();
454     thread_stats.reallocs++;
455     thread_stats.realloced += new_size;
456 
457     void *new_ptr = Allocate(new_size, 8, stack, FROM_MALLOC);
458     if (new_ptr) {
459       CHECK_NE(REAL(memcpy), nullptr);
460       uptr memcpy_size = Min(new_size, m->UsedSize());
461       REAL(memcpy)(new_ptr, old_ptr, memcpy_size);
462       Deallocate(old_ptr, 0, 0, stack, FROM_MALLOC);
463     }
464     return new_ptr;
465   }
466 
467   void *Calloc(uptr nmemb, uptr size, BufferedStackTrace *stack) {
468     if (UNLIKELY(CheckForCallocOverflow(size, nmemb))) {
469       if (AllocatorMayReturnNull())
470         return nullptr;
471       ReportCallocOverflow(nmemb, size, stack);
472     }
473     void *ptr = Allocate(nmemb * size, 8, stack, FROM_MALLOC);
474     // If the memory comes from the secondary allocator no need to clear it
475     // as it comes directly from mmap.
476     if (ptr && allocator.FromPrimary(ptr))
477       REAL(memset)(ptr, 0, nmemb * size);
478     return ptr;
479   }
480 
481   void CommitBack(MemprofThreadLocalMallocStorage *ms,
482                   BufferedStackTrace *stack) {
483     AllocatorCache *ac = GetAllocatorCache(ms);
484     allocator.SwallowCache(ac);
485   }
486 
487   // -------------------------- Chunk lookup ----------------------
488 
489   // Assumes alloc_beg == allocator.GetBlockBegin(alloc_beg).
490   MemprofChunk *GetMemprofChunk(void *alloc_beg, u64 &user_requested_size) {
491     if (!alloc_beg)
492       return nullptr;
493     MemprofChunk *p = reinterpret_cast<LargeChunkHeader *>(alloc_beg)->Get();
494     if (!p) {
495       if (!allocator.FromPrimary(alloc_beg))
496         return nullptr;
497       p = reinterpret_cast<MemprofChunk *>(alloc_beg);
498     }
499     // The size is reset to 0 on deallocation (and a min of 1 on
500     // allocation).
501     user_requested_size =
502         atomic_load(&p->user_requested_size, memory_order_acquire);
503     if (user_requested_size)
504       return p;
505     return nullptr;
506   }
507 
508   MemprofChunk *GetMemprofChunkByAddr(uptr p, u64 &user_requested_size) {
509     void *alloc_beg = allocator.GetBlockBegin(reinterpret_cast<void *>(p));
510     return GetMemprofChunk(alloc_beg, user_requested_size);
511   }
512 
513   uptr AllocationSize(uptr p) {
514     u64 user_requested_size;
515     MemprofChunk *m = GetMemprofChunkByAddr(p, user_requested_size);
516     if (!m)
517       return 0;
518     if (m->Beg() != p)
519       return 0;
520     return user_requested_size;
521   }
522 
523   void Purge(BufferedStackTrace *stack) { allocator.ForceReleaseToOS(); }
524 
525   void PrintStats() { allocator.PrintStats(); }
526 
527   void ForceLock() NO_THREAD_SAFETY_ANALYSIS {
528     allocator.ForceLock();
529     fallback_mutex.Lock();
530   }
531 
532   void ForceUnlock() NO_THREAD_SAFETY_ANALYSIS {
533     fallback_mutex.Unlock();
534     allocator.ForceUnlock();
535   }
536 };
537 
538 static Allocator instance(LINKER_INITIALIZED);
539 
540 static MemprofAllocator &get_allocator() { return instance.allocator; }
541 
542 void InitializeAllocator() { instance.InitLinkerInitialized(); }
543 
544 void MemprofThreadLocalMallocStorage::CommitBack() {
545   GET_STACK_TRACE_MALLOC;
546   instance.CommitBack(this, &stack);
547 }
548 
549 void PrintInternalAllocatorStats() { instance.PrintStats(); }
550 
551 void memprof_free(void *ptr, BufferedStackTrace *stack, AllocType alloc_type) {
552   instance.Deallocate(ptr, 0, 0, stack, alloc_type);
553 }
554 
555 void memprof_delete(void *ptr, uptr size, uptr alignment,
556                     BufferedStackTrace *stack, AllocType alloc_type) {
557   instance.Deallocate(ptr, size, alignment, stack, alloc_type);
558 }
559 
560 void *memprof_malloc(uptr size, BufferedStackTrace *stack) {
561   return SetErrnoOnNull(instance.Allocate(size, 8, stack, FROM_MALLOC));
562 }
563 
564 void *memprof_calloc(uptr nmemb, uptr size, BufferedStackTrace *stack) {
565   return SetErrnoOnNull(instance.Calloc(nmemb, size, stack));
566 }
567 
568 void *memprof_reallocarray(void *p, uptr nmemb, uptr size,
569                            BufferedStackTrace *stack) {
570   if (UNLIKELY(CheckForCallocOverflow(size, nmemb))) {
571     errno = errno_ENOMEM;
572     if (AllocatorMayReturnNull())
573       return nullptr;
574     ReportReallocArrayOverflow(nmemb, size, stack);
575   }
576   return memprof_realloc(p, nmemb * size, stack);
577 }
578 
579 void *memprof_realloc(void *p, uptr size, BufferedStackTrace *stack) {
580   if (!p)
581     return SetErrnoOnNull(instance.Allocate(size, 8, stack, FROM_MALLOC));
582   if (size == 0) {
583     if (flags()->allocator_frees_and_returns_null_on_realloc_zero) {
584       instance.Deallocate(p, 0, 0, stack, FROM_MALLOC);
585       return nullptr;
586     }
587     // Allocate a size of 1 if we shouldn't free() on Realloc to 0
588     size = 1;
589   }
590   return SetErrnoOnNull(instance.Reallocate(p, size, stack));
591 }
592 
593 void *memprof_valloc(uptr size, BufferedStackTrace *stack) {
594   return SetErrnoOnNull(
595       instance.Allocate(size, GetPageSizeCached(), stack, FROM_MALLOC));
596 }
597 
598 void *memprof_pvalloc(uptr size, BufferedStackTrace *stack) {
599   uptr PageSize = GetPageSizeCached();
600   if (UNLIKELY(CheckForPvallocOverflow(size, PageSize))) {
601     errno = errno_ENOMEM;
602     if (AllocatorMayReturnNull())
603       return nullptr;
604     ReportPvallocOverflow(size, stack);
605   }
606   // pvalloc(0) should allocate one page.
607   size = size ? RoundUpTo(size, PageSize) : PageSize;
608   return SetErrnoOnNull(instance.Allocate(size, PageSize, stack, FROM_MALLOC));
609 }
610 
611 void *memprof_memalign(uptr alignment, uptr size, BufferedStackTrace *stack,
612                        AllocType alloc_type) {
613   if (UNLIKELY(!IsPowerOfTwo(alignment))) {
614     errno = errno_EINVAL;
615     if (AllocatorMayReturnNull())
616       return nullptr;
617     ReportInvalidAllocationAlignment(alignment, stack);
618   }
619   return SetErrnoOnNull(instance.Allocate(size, alignment, stack, alloc_type));
620 }
621 
622 void *memprof_aligned_alloc(uptr alignment, uptr size,
623                             BufferedStackTrace *stack) {
624   if (UNLIKELY(!CheckAlignedAllocAlignmentAndSize(alignment, size))) {
625     errno = errno_EINVAL;
626     if (AllocatorMayReturnNull())
627       return nullptr;
628     ReportInvalidAlignedAllocAlignment(size, alignment, stack);
629   }
630   return SetErrnoOnNull(instance.Allocate(size, alignment, stack, FROM_MALLOC));
631 }
632 
633 int memprof_posix_memalign(void **memptr, uptr alignment, uptr size,
634                            BufferedStackTrace *stack) {
635   if (UNLIKELY(!CheckPosixMemalignAlignment(alignment))) {
636     if (AllocatorMayReturnNull())
637       return errno_EINVAL;
638     ReportInvalidPosixMemalignAlignment(alignment, stack);
639   }
640   void *ptr = instance.Allocate(size, alignment, stack, FROM_MALLOC);
641   if (UNLIKELY(!ptr))
642     // OOM error is already taken care of by Allocate.
643     return errno_ENOMEM;
644   CHECK(IsAligned((uptr)ptr, alignment));
645   *memptr = ptr;
646   return 0;
647 }
648 
649 uptr memprof_malloc_usable_size(const void *ptr, uptr pc, uptr bp) {
650   if (!ptr)
651     return 0;
652   uptr usable_size = instance.AllocationSize(reinterpret_cast<uptr>(ptr));
653   return usable_size;
654 }
655 
656 } // namespace __memprof
657 
658 // ---------------------- Interface ---------------- {{{1
659 using namespace __memprof;
660 
661 #if !SANITIZER_SUPPORTS_WEAK_HOOKS
662 // Provide default (no-op) implementation of malloc hooks.
663 SANITIZER_INTERFACE_WEAK_DEF(void, __sanitizer_malloc_hook, void *ptr,
664                              uptr size) {
665   (void)ptr;
666   (void)size;
667 }
668 
669 SANITIZER_INTERFACE_WEAK_DEF(void, __sanitizer_free_hook, void *ptr) {
670   (void)ptr;
671 }
672 #endif
673 
674 uptr __sanitizer_get_estimated_allocated_size(uptr size) { return size; }
675 
676 int __sanitizer_get_ownership(const void *p) {
677   return memprof_malloc_usable_size(p, 0, 0) != 0;
678 }
679 
680 uptr __sanitizer_get_allocated_size(const void *p) {
681   return memprof_malloc_usable_size(p, 0, 0);
682 }
683 
684 int __memprof_profile_dump() {
685   instance.FinishAndWrite();
686   // In the future we may want to return non-zero if there are any errors
687   // detected during the dumping process.
688   return 0;
689 }
690