lsan_allocator.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. //=-- lsan_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 LeakSanitizer.
  10. // See lsan_allocator.h for details.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "lsan_allocator.h"
  14. #include "sanitizer_common/sanitizer_allocator.h"
  15. #include "sanitizer_common/sanitizer_allocator_checks.h"
  16. #include "sanitizer_common/sanitizer_allocator_interface.h"
  17. #include "sanitizer_common/sanitizer_allocator_report.h"
  18. #include "sanitizer_common/sanitizer_errno.h"
  19. #include "sanitizer_common/sanitizer_internal_defs.h"
  20. #include "sanitizer_common/sanitizer_stackdepot.h"
  21. #include "sanitizer_common/sanitizer_stacktrace.h"
  22. #include "lsan_common.h"
  23. extern "C" void *memset(void *ptr, int value, uptr num);
  24. namespace __lsan {
  25. #if defined(__i386__) || defined(__arm__)
  26. static const uptr kMaxAllowedMallocSize = 1ULL << 30;
  27. #elif defined(__mips64) || defined(__aarch64__)
  28. static const uptr kMaxAllowedMallocSize = 4ULL << 30;
  29. #else
  30. static const uptr kMaxAllowedMallocSize = 8ULL << 30;
  31. #endif
  32. static Allocator allocator;
  33. static uptr max_malloc_size;
  34. void InitializeAllocator() {
  35. SetAllocatorMayReturnNull(common_flags()->allocator_may_return_null);
  36. allocator.InitLinkerInitialized(
  37. common_flags()->allocator_release_to_os_interval_ms);
  38. if (common_flags()->max_allocation_size_mb)
  39. max_malloc_size = Min(common_flags()->max_allocation_size_mb << 20,
  40. kMaxAllowedMallocSize);
  41. else
  42. max_malloc_size = kMaxAllowedMallocSize;
  43. }
  44. void AllocatorThreadFinish() {
  45. allocator.SwallowCache(GetAllocatorCache());
  46. }
  47. static ChunkMetadata *Metadata(const void *p) {
  48. return reinterpret_cast<ChunkMetadata *>(allocator.GetMetaData(p));
  49. }
  50. static void RegisterAllocation(const StackTrace &stack, void *p, uptr size) {
  51. if (!p) return;
  52. ChunkMetadata *m = Metadata(p);
  53. CHECK(m);
  54. m->tag = DisabledInThisThread() ? kIgnored : kDirectlyLeaked;
  55. m->stack_trace_id = StackDepotPut(stack);
  56. m->requested_size = size;
  57. atomic_store(reinterpret_cast<atomic_uint8_t *>(m), 1, memory_order_relaxed);
  58. }
  59. static void RegisterDeallocation(void *p) {
  60. if (!p) return;
  61. ChunkMetadata *m = Metadata(p);
  62. CHECK(m);
  63. atomic_store(reinterpret_cast<atomic_uint8_t *>(m), 0, memory_order_relaxed);
  64. }
  65. static void *ReportAllocationSizeTooBig(uptr size, const StackTrace &stack) {
  66. if (AllocatorMayReturnNull()) {
  67. Report("WARNING: LeakSanitizer failed to allocate 0x%zx bytes\n", size);
  68. return nullptr;
  69. }
  70. ReportAllocationSizeTooBig(size, max_malloc_size, &stack);
  71. }
  72. void *Allocate(const StackTrace &stack, uptr size, uptr alignment,
  73. bool cleared) {
  74. if (size == 0)
  75. size = 1;
  76. if (size > max_malloc_size)
  77. return ReportAllocationSizeTooBig(size, stack);
  78. if (UNLIKELY(IsRssLimitExceeded())) {
  79. if (AllocatorMayReturnNull())
  80. return nullptr;
  81. ReportRssLimitExceeded(&stack);
  82. }
  83. void *p = allocator.Allocate(GetAllocatorCache(), size, alignment);
  84. if (UNLIKELY(!p)) {
  85. SetAllocatorOutOfMemory();
  86. if (AllocatorMayReturnNull())
  87. return nullptr;
  88. ReportOutOfMemory(size, &stack);
  89. }
  90. // Do not rely on the allocator to clear the memory (it's slow).
  91. if (cleared && allocator.FromPrimary(p))
  92. memset(p, 0, size);
  93. RegisterAllocation(stack, p, size);
  94. if (&__sanitizer_malloc_hook) __sanitizer_malloc_hook(p, size);
  95. RunMallocHooks(p, size);
  96. return p;
  97. }
  98. static void *Calloc(uptr nmemb, uptr size, const StackTrace &stack) {
  99. if (UNLIKELY(CheckForCallocOverflow(size, nmemb))) {
  100. if (AllocatorMayReturnNull())
  101. return nullptr;
  102. ReportCallocOverflow(nmemb, size, &stack);
  103. }
  104. size *= nmemb;
  105. return Allocate(stack, size, 1, true);
  106. }
  107. void Deallocate(void *p) {
  108. if (&__sanitizer_free_hook) __sanitizer_free_hook(p);
  109. RunFreeHooks(p);
  110. RegisterDeallocation(p);
  111. allocator.Deallocate(GetAllocatorCache(), p);
  112. }
  113. void *Reallocate(const StackTrace &stack, void *p, uptr new_size,
  114. uptr alignment) {
  115. if (new_size > max_malloc_size) {
  116. ReportAllocationSizeTooBig(new_size, stack);
  117. return nullptr;
  118. }
  119. RegisterDeallocation(p);
  120. void *new_p =
  121. allocator.Reallocate(GetAllocatorCache(), p, new_size, alignment);
  122. if (new_p)
  123. RegisterAllocation(stack, new_p, new_size);
  124. else if (new_size != 0)
  125. RegisterAllocation(stack, p, new_size);
  126. return new_p;
  127. }
  128. void GetAllocatorCacheRange(uptr *begin, uptr *end) {
  129. *begin = (uptr)GetAllocatorCache();
  130. *end = *begin + sizeof(AllocatorCache);
  131. }
  132. uptr GetMallocUsableSize(const void *p) {
  133. ChunkMetadata *m = Metadata(p);
  134. if (!m) return 0;
  135. return m->requested_size;
  136. }
  137. int lsan_posix_memalign(void **memptr, uptr alignment, uptr size,
  138. const StackTrace &stack) {
  139. if (UNLIKELY(!CheckPosixMemalignAlignment(alignment))) {
  140. if (AllocatorMayReturnNull())
  141. return errno_EINVAL;
  142. ReportInvalidPosixMemalignAlignment(alignment, &stack);
  143. }
  144. void *ptr = Allocate(stack, size, alignment, kAlwaysClearMemory);
  145. if (UNLIKELY(!ptr))
  146. // OOM error is already taken care of by Allocate.
  147. return errno_ENOMEM;
  148. CHECK(IsAligned((uptr)ptr, alignment));
  149. *memptr = ptr;
  150. return 0;
  151. }
  152. void *lsan_aligned_alloc(uptr alignment, uptr size, const StackTrace &stack) {
  153. if (UNLIKELY(!CheckAlignedAllocAlignmentAndSize(alignment, size))) {
  154. errno = errno_EINVAL;
  155. if (AllocatorMayReturnNull())
  156. return nullptr;
  157. ReportInvalidAlignedAllocAlignment(size, alignment, &stack);
  158. }
  159. return SetErrnoOnNull(Allocate(stack, size, alignment, kAlwaysClearMemory));
  160. }
  161. void *lsan_memalign(uptr alignment, uptr size, const StackTrace &stack) {
  162. if (UNLIKELY(!IsPowerOfTwo(alignment))) {
  163. errno = errno_EINVAL;
  164. if (AllocatorMayReturnNull())
  165. return nullptr;
  166. ReportInvalidAllocationAlignment(alignment, &stack);
  167. }
  168. return SetErrnoOnNull(Allocate(stack, size, alignment, kAlwaysClearMemory));
  169. }
  170. void *lsan_malloc(uptr size, const StackTrace &stack) {
  171. return SetErrnoOnNull(Allocate(stack, size, 1, kAlwaysClearMemory));
  172. }
  173. void lsan_free(void *p) {
  174. Deallocate(p);
  175. }
  176. void *lsan_realloc(void *p, uptr size, const StackTrace &stack) {
  177. return SetErrnoOnNull(Reallocate(stack, p, size, 1));
  178. }
  179. void *lsan_reallocarray(void *ptr, uptr nmemb, uptr size,
  180. const StackTrace &stack) {
  181. if (UNLIKELY(CheckForCallocOverflow(size, nmemb))) {
  182. errno = errno_ENOMEM;
  183. if (AllocatorMayReturnNull())
  184. return nullptr;
  185. ReportReallocArrayOverflow(nmemb, size, &stack);
  186. }
  187. return lsan_realloc(ptr, nmemb * size, stack);
  188. }
  189. void *lsan_calloc(uptr nmemb, uptr size, const StackTrace &stack) {
  190. return SetErrnoOnNull(Calloc(nmemb, size, stack));
  191. }
  192. void *lsan_valloc(uptr size, const StackTrace &stack) {
  193. return SetErrnoOnNull(
  194. Allocate(stack, size, GetPageSizeCached(), kAlwaysClearMemory));
  195. }
  196. void *lsan_pvalloc(uptr size, const StackTrace &stack) {
  197. uptr PageSize = GetPageSizeCached();
  198. if (UNLIKELY(CheckForPvallocOverflow(size, PageSize))) {
  199. errno = errno_ENOMEM;
  200. if (AllocatorMayReturnNull())
  201. return nullptr;
  202. ReportPvallocOverflow(size, &stack);
  203. }
  204. // pvalloc(0) should allocate one page.
  205. size = size ? RoundUpTo(size, PageSize) : PageSize;
  206. return SetErrnoOnNull(Allocate(stack, size, PageSize, kAlwaysClearMemory));
  207. }
  208. uptr lsan_mz_size(const void *p) {
  209. return GetMallocUsableSize(p);
  210. }
  211. ///// Interface to the common LSan module. /////
  212. void LockAllocator() {
  213. allocator.ForceLock();
  214. }
  215. void UnlockAllocator() {
  216. allocator.ForceUnlock();
  217. }
  218. void GetAllocatorGlobalRange(uptr *begin, uptr *end) {
  219. *begin = (uptr)&allocator;
  220. *end = *begin + sizeof(allocator);
  221. }
  222. uptr PointsIntoChunk(void* p) {
  223. uptr addr = reinterpret_cast<uptr>(p);
  224. uptr chunk = reinterpret_cast<uptr>(allocator.GetBlockBeginFastLocked(p));
  225. if (!chunk) return 0;
  226. // LargeMmapAllocator considers pointers to the meta-region of a chunk to be
  227. // valid, but we don't want that.
  228. if (addr < chunk) return 0;
  229. ChunkMetadata *m = Metadata(reinterpret_cast<void *>(chunk));
  230. CHECK(m);
  231. if (!m->allocated)
  232. return 0;
  233. if (addr < chunk + m->requested_size)
  234. return chunk;
  235. if (IsSpecialCaseOfOperatorNew0(chunk, m->requested_size, addr))
  236. return chunk;
  237. return 0;
  238. }
  239. uptr GetUserBegin(uptr chunk) {
  240. return chunk;
  241. }
  242. LsanMetadata::LsanMetadata(uptr chunk) {
  243. metadata_ = Metadata(reinterpret_cast<void *>(chunk));
  244. CHECK(metadata_);
  245. }
  246. bool LsanMetadata::allocated() const {
  247. return reinterpret_cast<ChunkMetadata *>(metadata_)->allocated;
  248. }
  249. ChunkTag LsanMetadata::tag() const {
  250. return reinterpret_cast<ChunkMetadata *>(metadata_)->tag;
  251. }
  252. void LsanMetadata::set_tag(ChunkTag value) {
  253. reinterpret_cast<ChunkMetadata *>(metadata_)->tag = value;
  254. }
  255. uptr LsanMetadata::requested_size() const {
  256. return reinterpret_cast<ChunkMetadata *>(metadata_)->requested_size;
  257. }
  258. u32 LsanMetadata::stack_trace_id() const {
  259. return reinterpret_cast<ChunkMetadata *>(metadata_)->stack_trace_id;
  260. }
  261. void ForEachChunk(ForEachChunkCallback callback, void *arg) {
  262. allocator.ForEachChunk(callback, arg);
  263. }
  264. IgnoreObjectResult IgnoreObjectLocked(const void *p) {
  265. void *chunk = allocator.GetBlockBegin(p);
  266. if (!chunk || p < chunk) return kIgnoreObjectInvalid;
  267. ChunkMetadata *m = Metadata(chunk);
  268. CHECK(m);
  269. if (m->allocated && (uptr)p < (uptr)chunk + m->requested_size) {
  270. if (m->tag == kIgnored)
  271. return kIgnoreObjectAlreadyIgnored;
  272. m->tag = kIgnored;
  273. return kIgnoreObjectSuccess;
  274. } else {
  275. return kIgnoreObjectInvalid;
  276. }
  277. }
  278. void GetAdditionalThreadContextPtrs(ThreadContextBase *tctx, void *ptrs) {
  279. // This function can be used to treat memory reachable from `tctx` as live.
  280. // This is useful for threads that have been created but not yet started.
  281. // This is currently a no-op because the LSan `pthread_create()` interceptor
  282. // blocks until the child thread starts which keeps the thread's `arg` pointer
  283. // live.
  284. }
  285. } // namespace __lsan
  286. using namespace __lsan;
  287. extern "C" {
  288. SANITIZER_INTERFACE_ATTRIBUTE
  289. uptr __sanitizer_get_current_allocated_bytes() {
  290. uptr stats[AllocatorStatCount];
  291. allocator.GetStats(stats);
  292. return stats[AllocatorStatAllocated];
  293. }
  294. SANITIZER_INTERFACE_ATTRIBUTE
  295. uptr __sanitizer_get_heap_size() {
  296. uptr stats[AllocatorStatCount];
  297. allocator.GetStats(stats);
  298. return stats[AllocatorStatMapped];
  299. }
  300. SANITIZER_INTERFACE_ATTRIBUTE
  301. uptr __sanitizer_get_free_bytes() { return 0; }
  302. SANITIZER_INTERFACE_ATTRIBUTE
  303. uptr __sanitizer_get_unmapped_bytes() { return 0; }
  304. SANITIZER_INTERFACE_ATTRIBUTE
  305. uptr __sanitizer_get_estimated_allocated_size(uptr size) { return size; }
  306. SANITIZER_INTERFACE_ATTRIBUTE
  307. int __sanitizer_get_ownership(const void *p) { return Metadata(p) != nullptr; }
  308. SANITIZER_INTERFACE_ATTRIBUTE
  309. uptr __sanitizer_get_allocated_size(const void *p) {
  310. return GetMallocUsableSize(p);
  311. }
  312. #if !SANITIZER_SUPPORTS_WEAK_HOOKS
  313. // Provide default (no-op) implementation of malloc hooks.
  314. SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
  315. void __sanitizer_malloc_hook(void *ptr, uptr size) {
  316. (void)ptr;
  317. (void)size;
  318. }
  319. SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
  320. void __sanitizer_free_hook(void *ptr) {
  321. (void)ptr;
  322. }
  323. #endif
  324. } // extern "C"