xref: /freebsd-src/contrib/llvm-project/compiler-rt/lib/memprof/memprof_allocator.cpp (revision 5e801ac66d24704442eba426ed13c3effb8a34e7)
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   atomic_uint8_t rss_limit_exceeded;
222 
223   // Holds the mapping of stack ids to MemInfoBlocks.
224   MIBMapTy MIBMap;
225 
226   atomic_uint8_t destructing;
227   atomic_uint8_t constructed;
228   bool print_text;
229 
230   // ------------------- Initialization ------------------------
231   explicit Allocator(LinkerInitialized) : print_text(flags()->print_text) {
232     atomic_store_relaxed(&destructing, 0);
233     atomic_store_relaxed(&constructed, 1);
234   }
235 
236   ~Allocator() {
237     atomic_store_relaxed(&destructing, 1);
238     FinishAndWrite();
239   }
240 
241   static void PrintCallback(const uptr Key, LockedMemInfoBlock *const &Value,
242                             void *Arg) {
243     SpinMutexLock(&Value->mutex);
244     Value->mib.Print(Key, bool(Arg));
245   }
246 
247   void FinishAndWrite() {
248     if (print_text && common_flags()->print_module_map)
249       DumpProcessMap();
250 
251     allocator.ForceLock();
252 
253     InsertLiveBlocks();
254     if (print_text) {
255       MIBMap.ForEach(PrintCallback,
256                      reinterpret_cast<void *>(flags()->print_terse));
257       StackDepotPrintAll();
258     } else {
259       // Serialize the contents to a raw profile. Format documented in
260       // memprof_rawprofile.h.
261       char *Buffer = nullptr;
262 
263       MemoryMappingLayout Layout(/*cache_enabled=*/true);
264       u64 BytesSerialized = SerializeToRawProfile(MIBMap, Layout, Buffer);
265       CHECK(Buffer && BytesSerialized && "could not serialize to buffer");
266       report_file.Write(Buffer, BytesSerialized);
267     }
268 
269     allocator.ForceUnlock();
270   }
271 
272   // Inserts any blocks which have been allocated but not yet deallocated.
273   void InsertLiveBlocks() {
274     if (print_text && !flags()->print_terse)
275       Printf("Live on exit:\n");
276 
277     allocator.ForEachChunk(
278         [](uptr chunk, void *alloc) {
279           u64 user_requested_size;
280           Allocator *A = (Allocator *)alloc;
281           MemprofChunk *m =
282               A->GetMemprofChunk((void *)chunk, user_requested_size);
283           if (!m)
284             return;
285           uptr user_beg = ((uptr)m) + kChunkHeaderSize;
286           u64 c = GetShadowCount(user_beg, user_requested_size);
287           long curtime = GetTimestamp();
288           MemInfoBlock newMIB(user_requested_size, c, m->timestamp_ms, curtime,
289                               m->cpu_id, GetCpuId());
290           InsertOrMerge(m->alloc_context_id, newMIB, A->MIBMap);
291         },
292         this);
293   }
294 
295   void InitLinkerInitialized() {
296     SetAllocatorMayReturnNull(common_flags()->allocator_may_return_null);
297     allocator.InitLinkerInitialized(
298         common_flags()->allocator_release_to_os_interval_ms);
299     max_user_defined_malloc_size = common_flags()->max_allocation_size_mb
300                                        ? common_flags()->max_allocation_size_mb
301                                              << 20
302                                        : kMaxAllowedMallocSize;
303   }
304 
305   bool RssLimitExceeded() {
306     return atomic_load(&rss_limit_exceeded, memory_order_relaxed);
307   }
308 
309   void SetRssLimitExceeded(bool limit_exceeded) {
310     atomic_store(&rss_limit_exceeded, limit_exceeded, memory_order_relaxed);
311   }
312 
313   // -------------------- Allocation/Deallocation routines ---------------
314   void *Allocate(uptr size, uptr alignment, BufferedStackTrace *stack,
315                  AllocType alloc_type) {
316     if (UNLIKELY(!memprof_inited))
317       MemprofInitFromRtl();
318     if (RssLimitExceeded()) {
319       if (AllocatorMayReturnNull())
320         return nullptr;
321       ReportRssLimitExceeded(stack);
322     }
323     CHECK(stack);
324     const uptr min_alignment = MEMPROF_ALIGNMENT;
325     if (alignment < min_alignment)
326       alignment = min_alignment;
327     if (size == 0) {
328       // We'd be happy to avoid allocating memory for zero-size requests, but
329       // some programs/tests depend on this behavior and assume that malloc
330       // would not return NULL even for zero-size allocations. Moreover, it
331       // looks like operator new should never return NULL, and results of
332       // consecutive "new" calls must be different even if the allocated size
333       // is zero.
334       size = 1;
335     }
336     CHECK(IsPowerOfTwo(alignment));
337     uptr rounded_size = RoundUpTo(size, alignment);
338     uptr needed_size = rounded_size + kChunkHeaderSize;
339     if (alignment > min_alignment)
340       needed_size += alignment;
341     CHECK(IsAligned(needed_size, min_alignment));
342     if (size > kMaxAllowedMallocSize || needed_size > kMaxAllowedMallocSize ||
343         size > max_user_defined_malloc_size) {
344       if (AllocatorMayReturnNull()) {
345         Report("WARNING: MemProfiler failed to allocate 0x%zx bytes\n", size);
346         return nullptr;
347       }
348       uptr malloc_limit =
349           Min(kMaxAllowedMallocSize, max_user_defined_malloc_size);
350       ReportAllocationSizeTooBig(size, malloc_limit, stack);
351     }
352 
353     MemprofThread *t = GetCurrentThread();
354     void *allocated;
355     if (t) {
356       AllocatorCache *cache = GetAllocatorCache(&t->malloc_storage());
357       allocated = allocator.Allocate(cache, needed_size, 8);
358     } else {
359       SpinMutexLock l(&fallback_mutex);
360       AllocatorCache *cache = &fallback_allocator_cache;
361       allocated = allocator.Allocate(cache, needed_size, 8);
362     }
363     if (UNLIKELY(!allocated)) {
364       SetAllocatorOutOfMemory();
365       if (AllocatorMayReturnNull())
366         return nullptr;
367       ReportOutOfMemory(size, stack);
368     }
369 
370     uptr alloc_beg = reinterpret_cast<uptr>(allocated);
371     uptr alloc_end = alloc_beg + needed_size;
372     uptr beg_plus_header = alloc_beg + kChunkHeaderSize;
373     uptr user_beg = beg_plus_header;
374     if (!IsAligned(user_beg, alignment))
375       user_beg = RoundUpTo(user_beg, alignment);
376     uptr user_end = user_beg + size;
377     CHECK_LE(user_end, alloc_end);
378     uptr chunk_beg = user_beg - kChunkHeaderSize;
379     MemprofChunk *m = reinterpret_cast<MemprofChunk *>(chunk_beg);
380     m->from_memalign = alloc_beg != chunk_beg;
381     CHECK(size);
382 
383     m->cpu_id = GetCpuId();
384     m->timestamp_ms = GetTimestamp();
385     m->alloc_context_id = StackDepotPut(*stack);
386 
387     uptr size_rounded_down_to_granularity =
388         RoundDownTo(size, SHADOW_GRANULARITY);
389     if (size_rounded_down_to_granularity)
390       ClearShadow(user_beg, size_rounded_down_to_granularity);
391 
392     MemprofStats &thread_stats = GetCurrentThreadStats();
393     thread_stats.mallocs++;
394     thread_stats.malloced += size;
395     thread_stats.malloced_overhead += needed_size - size;
396     if (needed_size > SizeClassMap::kMaxSize)
397       thread_stats.malloc_large++;
398     else
399       thread_stats.malloced_by_size[SizeClassMap::ClassID(needed_size)]++;
400 
401     void *res = reinterpret_cast<void *>(user_beg);
402     atomic_store(&m->user_requested_size, size, memory_order_release);
403     if (alloc_beg != chunk_beg) {
404       CHECK_LE(alloc_beg + sizeof(LargeChunkHeader), chunk_beg);
405       reinterpret_cast<LargeChunkHeader *>(alloc_beg)->Set(m);
406     }
407     MEMPROF_MALLOC_HOOK(res, size);
408     return res;
409   }
410 
411   void Deallocate(void *ptr, uptr delete_size, uptr delete_alignment,
412                   BufferedStackTrace *stack, AllocType alloc_type) {
413     uptr p = reinterpret_cast<uptr>(ptr);
414     if (p == 0)
415       return;
416 
417     MEMPROF_FREE_HOOK(ptr);
418 
419     uptr chunk_beg = p - kChunkHeaderSize;
420     MemprofChunk *m = reinterpret_cast<MemprofChunk *>(chunk_beg);
421 
422     u64 user_requested_size =
423         atomic_exchange(&m->user_requested_size, 0, memory_order_acquire);
424     if (memprof_inited && memprof_init_done &&
425         atomic_load_relaxed(&constructed) &&
426         !atomic_load_relaxed(&destructing)) {
427       u64 c = GetShadowCount(p, user_requested_size);
428       long curtime = GetTimestamp();
429 
430       MemInfoBlock newMIB(user_requested_size, c, m->timestamp_ms, curtime,
431                           m->cpu_id, GetCpuId());
432       InsertOrMerge(m->alloc_context_id, newMIB, MIBMap);
433     }
434 
435     MemprofStats &thread_stats = GetCurrentThreadStats();
436     thread_stats.frees++;
437     thread_stats.freed += user_requested_size;
438 
439     void *alloc_beg = m->AllocBeg();
440     if (alloc_beg != m) {
441       // Clear the magic value, as allocator internals may overwrite the
442       // contents of deallocated chunk, confusing GetMemprofChunk lookup.
443       reinterpret_cast<LargeChunkHeader *>(alloc_beg)->Set(nullptr);
444     }
445 
446     MemprofThread *t = GetCurrentThread();
447     if (t) {
448       AllocatorCache *cache = GetAllocatorCache(&t->malloc_storage());
449       allocator.Deallocate(cache, alloc_beg);
450     } else {
451       SpinMutexLock l(&fallback_mutex);
452       AllocatorCache *cache = &fallback_allocator_cache;
453       allocator.Deallocate(cache, alloc_beg);
454     }
455   }
456 
457   void *Reallocate(void *old_ptr, uptr new_size, BufferedStackTrace *stack) {
458     CHECK(old_ptr && new_size);
459     uptr p = reinterpret_cast<uptr>(old_ptr);
460     uptr chunk_beg = p - kChunkHeaderSize;
461     MemprofChunk *m = reinterpret_cast<MemprofChunk *>(chunk_beg);
462 
463     MemprofStats &thread_stats = GetCurrentThreadStats();
464     thread_stats.reallocs++;
465     thread_stats.realloced += new_size;
466 
467     void *new_ptr = Allocate(new_size, 8, stack, FROM_MALLOC);
468     if (new_ptr) {
469       CHECK_NE(REAL(memcpy), nullptr);
470       uptr memcpy_size = Min(new_size, m->UsedSize());
471       REAL(memcpy)(new_ptr, old_ptr, memcpy_size);
472       Deallocate(old_ptr, 0, 0, stack, FROM_MALLOC);
473     }
474     return new_ptr;
475   }
476 
477   void *Calloc(uptr nmemb, uptr size, BufferedStackTrace *stack) {
478     if (UNLIKELY(CheckForCallocOverflow(size, nmemb))) {
479       if (AllocatorMayReturnNull())
480         return nullptr;
481       ReportCallocOverflow(nmemb, size, stack);
482     }
483     void *ptr = Allocate(nmemb * size, 8, stack, FROM_MALLOC);
484     // If the memory comes from the secondary allocator no need to clear it
485     // as it comes directly from mmap.
486     if (ptr && allocator.FromPrimary(ptr))
487       REAL(memset)(ptr, 0, nmemb * size);
488     return ptr;
489   }
490 
491   void CommitBack(MemprofThreadLocalMallocStorage *ms,
492                   BufferedStackTrace *stack) {
493     AllocatorCache *ac = GetAllocatorCache(ms);
494     allocator.SwallowCache(ac);
495   }
496 
497   // -------------------------- Chunk lookup ----------------------
498 
499   // Assumes alloc_beg == allocator.GetBlockBegin(alloc_beg).
500   MemprofChunk *GetMemprofChunk(void *alloc_beg, u64 &user_requested_size) {
501     if (!alloc_beg)
502       return nullptr;
503     MemprofChunk *p = reinterpret_cast<LargeChunkHeader *>(alloc_beg)->Get();
504     if (!p) {
505       if (!allocator.FromPrimary(alloc_beg))
506         return nullptr;
507       p = reinterpret_cast<MemprofChunk *>(alloc_beg);
508     }
509     // The size is reset to 0 on deallocation (and a min of 1 on
510     // allocation).
511     user_requested_size =
512         atomic_load(&p->user_requested_size, memory_order_acquire);
513     if (user_requested_size)
514       return p;
515     return nullptr;
516   }
517 
518   MemprofChunk *GetMemprofChunkByAddr(uptr p, u64 &user_requested_size) {
519     void *alloc_beg = allocator.GetBlockBegin(reinterpret_cast<void *>(p));
520     return GetMemprofChunk(alloc_beg, user_requested_size);
521   }
522 
523   uptr AllocationSize(uptr p) {
524     u64 user_requested_size;
525     MemprofChunk *m = GetMemprofChunkByAddr(p, user_requested_size);
526     if (!m)
527       return 0;
528     if (m->Beg() != p)
529       return 0;
530     return user_requested_size;
531   }
532 
533   void Purge(BufferedStackTrace *stack) { allocator.ForceReleaseToOS(); }
534 
535   void PrintStats() { allocator.PrintStats(); }
536 
537   void ForceLock() NO_THREAD_SAFETY_ANALYSIS {
538     allocator.ForceLock();
539     fallback_mutex.Lock();
540   }
541 
542   void ForceUnlock() NO_THREAD_SAFETY_ANALYSIS {
543     fallback_mutex.Unlock();
544     allocator.ForceUnlock();
545   }
546 };
547 
548 static Allocator instance(LINKER_INITIALIZED);
549 
550 static MemprofAllocator &get_allocator() { return instance.allocator; }
551 
552 void InitializeAllocator() { instance.InitLinkerInitialized(); }
553 
554 void MemprofThreadLocalMallocStorage::CommitBack() {
555   GET_STACK_TRACE_MALLOC;
556   instance.CommitBack(this, &stack);
557 }
558 
559 void PrintInternalAllocatorStats() { instance.PrintStats(); }
560 
561 void memprof_free(void *ptr, BufferedStackTrace *stack, AllocType alloc_type) {
562   instance.Deallocate(ptr, 0, 0, stack, alloc_type);
563 }
564 
565 void memprof_delete(void *ptr, uptr size, uptr alignment,
566                     BufferedStackTrace *stack, AllocType alloc_type) {
567   instance.Deallocate(ptr, size, alignment, stack, alloc_type);
568 }
569 
570 void *memprof_malloc(uptr size, BufferedStackTrace *stack) {
571   return SetErrnoOnNull(instance.Allocate(size, 8, stack, FROM_MALLOC));
572 }
573 
574 void *memprof_calloc(uptr nmemb, uptr size, BufferedStackTrace *stack) {
575   return SetErrnoOnNull(instance.Calloc(nmemb, size, stack));
576 }
577 
578 void *memprof_reallocarray(void *p, uptr nmemb, uptr size,
579                            BufferedStackTrace *stack) {
580   if (UNLIKELY(CheckForCallocOverflow(size, nmemb))) {
581     errno = errno_ENOMEM;
582     if (AllocatorMayReturnNull())
583       return nullptr;
584     ReportReallocArrayOverflow(nmemb, size, stack);
585   }
586   return memprof_realloc(p, nmemb * size, stack);
587 }
588 
589 void *memprof_realloc(void *p, uptr size, BufferedStackTrace *stack) {
590   if (!p)
591     return SetErrnoOnNull(instance.Allocate(size, 8, stack, FROM_MALLOC));
592   if (size == 0) {
593     if (flags()->allocator_frees_and_returns_null_on_realloc_zero) {
594       instance.Deallocate(p, 0, 0, stack, FROM_MALLOC);
595       return nullptr;
596     }
597     // Allocate a size of 1 if we shouldn't free() on Realloc to 0
598     size = 1;
599   }
600   return SetErrnoOnNull(instance.Reallocate(p, size, stack));
601 }
602 
603 void *memprof_valloc(uptr size, BufferedStackTrace *stack) {
604   return SetErrnoOnNull(
605       instance.Allocate(size, GetPageSizeCached(), stack, FROM_MALLOC));
606 }
607 
608 void *memprof_pvalloc(uptr size, BufferedStackTrace *stack) {
609   uptr PageSize = GetPageSizeCached();
610   if (UNLIKELY(CheckForPvallocOverflow(size, PageSize))) {
611     errno = errno_ENOMEM;
612     if (AllocatorMayReturnNull())
613       return nullptr;
614     ReportPvallocOverflow(size, stack);
615   }
616   // pvalloc(0) should allocate one page.
617   size = size ? RoundUpTo(size, PageSize) : PageSize;
618   return SetErrnoOnNull(instance.Allocate(size, PageSize, stack, FROM_MALLOC));
619 }
620 
621 void *memprof_memalign(uptr alignment, uptr size, BufferedStackTrace *stack,
622                        AllocType alloc_type) {
623   if (UNLIKELY(!IsPowerOfTwo(alignment))) {
624     errno = errno_EINVAL;
625     if (AllocatorMayReturnNull())
626       return nullptr;
627     ReportInvalidAllocationAlignment(alignment, stack);
628   }
629   return SetErrnoOnNull(instance.Allocate(size, alignment, stack, alloc_type));
630 }
631 
632 void *memprof_aligned_alloc(uptr alignment, uptr size,
633                             BufferedStackTrace *stack) {
634   if (UNLIKELY(!CheckAlignedAllocAlignmentAndSize(alignment, size))) {
635     errno = errno_EINVAL;
636     if (AllocatorMayReturnNull())
637       return nullptr;
638     ReportInvalidAlignedAllocAlignment(size, alignment, stack);
639   }
640   return SetErrnoOnNull(instance.Allocate(size, alignment, stack, FROM_MALLOC));
641 }
642 
643 int memprof_posix_memalign(void **memptr, uptr alignment, uptr size,
644                            BufferedStackTrace *stack) {
645   if (UNLIKELY(!CheckPosixMemalignAlignment(alignment))) {
646     if (AllocatorMayReturnNull())
647       return errno_EINVAL;
648     ReportInvalidPosixMemalignAlignment(alignment, stack);
649   }
650   void *ptr = instance.Allocate(size, alignment, stack, FROM_MALLOC);
651   if (UNLIKELY(!ptr))
652     // OOM error is already taken care of by Allocate.
653     return errno_ENOMEM;
654   CHECK(IsAligned((uptr)ptr, alignment));
655   *memptr = ptr;
656   return 0;
657 }
658 
659 uptr memprof_malloc_usable_size(const void *ptr, uptr pc, uptr bp) {
660   if (!ptr)
661     return 0;
662   uptr usable_size = instance.AllocationSize(reinterpret_cast<uptr>(ptr));
663   return usable_size;
664 }
665 
666 void MemprofSoftRssLimitExceededCallback(bool limit_exceeded) {
667   instance.SetRssLimitExceeded(limit_exceeded);
668 }
669 
670 } // namespace __memprof
671 
672 // ---------------------- Interface ---------------- {{{1
673 using namespace __memprof;
674 
675 #if !SANITIZER_SUPPORTS_WEAK_HOOKS
676 // Provide default (no-op) implementation of malloc hooks.
677 SANITIZER_INTERFACE_WEAK_DEF(void, __sanitizer_malloc_hook, void *ptr,
678                              uptr size) {
679   (void)ptr;
680   (void)size;
681 }
682 
683 SANITIZER_INTERFACE_WEAK_DEF(void, __sanitizer_free_hook, void *ptr) {
684   (void)ptr;
685 }
686 #endif
687 
688 uptr __sanitizer_get_estimated_allocated_size(uptr size) { return size; }
689 
690 int __sanitizer_get_ownership(const void *p) {
691   return memprof_malloc_usable_size(p, 0, 0) != 0;
692 }
693 
694 uptr __sanitizer_get_allocated_size(const void *p) {
695   return memprof_malloc_usable_size(p, 0, 0);
696 }
697 
698 int __memprof_profile_dump() {
699   instance.FinishAndWrite();
700   // In the future we may want to return non-zero if there are any errors
701   // detected during the dumping process.
702   return 0;
703 }
704