hwasan_allocator.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. //===-- hwasan_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 HWAddressSanitizer.
  10. //
  11. // HWAddressSanitizer allocator.
  12. //===----------------------------------------------------------------------===//
  13. #include "sanitizer_common/sanitizer_atomic.h"
  14. #include "sanitizer_common/sanitizer_errno.h"
  15. #include "sanitizer_common/sanitizer_stackdepot.h"
  16. #include "hwasan.h"
  17. #include "hwasan_allocator.h"
  18. #include "hwasan_checks.h"
  19. #include "hwasan_mapping.h"
  20. #include "hwasan_malloc_bisect.h"
  21. #include "hwasan_thread.h"
  22. #include "hwasan_report.h"
  23. namespace __hwasan {
  24. static Allocator allocator;
  25. static AllocatorCache fallback_allocator_cache;
  26. static SpinMutex fallback_mutex;
  27. static atomic_uint8_t hwasan_allocator_tagging_enabled;
  28. static constexpr tag_t kFallbackAllocTag = 0xBB & kTagMask;
  29. static constexpr tag_t kFallbackFreeTag = 0xBC;
  30. enum RightAlignMode {
  31. kRightAlignNever,
  32. kRightAlignSometimes,
  33. kRightAlignAlways
  34. };
  35. // Initialized in HwasanAllocatorInit, an never changed.
  36. static ALIGNED(16) u8 tail_magic[kShadowAlignment - 1];
  37. bool HwasanChunkView::IsAllocated() const {
  38. return metadata_ && metadata_->alloc_context_id &&
  39. metadata_->get_requested_size();
  40. }
  41. // Aligns the 'addr' right to the granule boundary.
  42. static uptr AlignRight(uptr addr, uptr requested_size) {
  43. uptr tail_size = requested_size % kShadowAlignment;
  44. if (!tail_size) return addr;
  45. return addr + kShadowAlignment - tail_size;
  46. }
  47. uptr HwasanChunkView::Beg() const {
  48. if (metadata_ && metadata_->right_aligned)
  49. return AlignRight(block_, metadata_->get_requested_size());
  50. return block_;
  51. }
  52. uptr HwasanChunkView::End() const {
  53. return Beg() + UsedSize();
  54. }
  55. uptr HwasanChunkView::UsedSize() const {
  56. return metadata_->get_requested_size();
  57. }
  58. u32 HwasanChunkView::GetAllocStackId() const {
  59. return metadata_->alloc_context_id;
  60. }
  61. uptr HwasanChunkView::ActualSize() const {
  62. return allocator.GetActuallyAllocatedSize(reinterpret_cast<void *>(block_));
  63. }
  64. bool HwasanChunkView::FromSmallHeap() const {
  65. return allocator.FromPrimary(reinterpret_cast<void *>(block_));
  66. }
  67. void GetAllocatorStats(AllocatorStatCounters s) {
  68. allocator.GetStats(s);
  69. }
  70. uptr GetAliasRegionStart() {
  71. #if defined(HWASAN_ALIASING_MODE)
  72. constexpr uptr kAliasRegionOffset = 1ULL << (kTaggableRegionCheckShift - 1);
  73. uptr AliasRegionStart =
  74. __hwasan_shadow_memory_dynamic_address + kAliasRegionOffset;
  75. CHECK_EQ(AliasRegionStart >> kTaggableRegionCheckShift,
  76. __hwasan_shadow_memory_dynamic_address >> kTaggableRegionCheckShift);
  77. CHECK_EQ(
  78. (AliasRegionStart + kAliasRegionOffset - 1) >> kTaggableRegionCheckShift,
  79. __hwasan_shadow_memory_dynamic_address >> kTaggableRegionCheckShift);
  80. return AliasRegionStart;
  81. #else
  82. return 0;
  83. #endif
  84. }
  85. void HwasanAllocatorInit() {
  86. atomic_store_relaxed(&hwasan_allocator_tagging_enabled,
  87. !flags()->disable_allocator_tagging);
  88. SetAllocatorMayReturnNull(common_flags()->allocator_may_return_null);
  89. allocator.Init(common_flags()->allocator_release_to_os_interval_ms,
  90. GetAliasRegionStart());
  91. for (uptr i = 0; i < sizeof(tail_magic); i++)
  92. tail_magic[i] = GetCurrentThread()->GenerateRandomTag();
  93. }
  94. void HwasanAllocatorLock() { allocator.ForceLock(); }
  95. void HwasanAllocatorUnlock() { allocator.ForceUnlock(); }
  96. void AllocatorSwallowThreadLocalCache(AllocatorCache *cache) {
  97. allocator.SwallowCache(cache);
  98. }
  99. static uptr TaggedSize(uptr size) {
  100. if (!size) size = 1;
  101. uptr new_size = RoundUpTo(size, kShadowAlignment);
  102. CHECK_GE(new_size, size);
  103. return new_size;
  104. }
  105. static void *HwasanAllocate(StackTrace *stack, uptr orig_size, uptr alignment,
  106. bool zeroise) {
  107. if (orig_size > kMaxAllowedMallocSize) {
  108. if (AllocatorMayReturnNull()) {
  109. Report("WARNING: HWAddressSanitizer failed to allocate 0x%zx bytes\n",
  110. orig_size);
  111. return nullptr;
  112. }
  113. ReportAllocationSizeTooBig(orig_size, kMaxAllowedMallocSize, stack);
  114. }
  115. if (UNLIKELY(IsRssLimitExceeded())) {
  116. if (AllocatorMayReturnNull())
  117. return nullptr;
  118. ReportRssLimitExceeded(stack);
  119. }
  120. alignment = Max(alignment, kShadowAlignment);
  121. uptr size = TaggedSize(orig_size);
  122. Thread *t = GetCurrentThread();
  123. void *allocated;
  124. if (t) {
  125. allocated = allocator.Allocate(t->allocator_cache(), size, alignment);
  126. } else {
  127. SpinMutexLock l(&fallback_mutex);
  128. AllocatorCache *cache = &fallback_allocator_cache;
  129. allocated = allocator.Allocate(cache, size, alignment);
  130. }
  131. if (UNLIKELY(!allocated)) {
  132. SetAllocatorOutOfMemory();
  133. if (AllocatorMayReturnNull())
  134. return nullptr;
  135. ReportOutOfMemory(size, stack);
  136. }
  137. Metadata *meta =
  138. reinterpret_cast<Metadata *>(allocator.GetMetaData(allocated));
  139. meta->set_requested_size(orig_size);
  140. meta->alloc_context_id = StackDepotPut(*stack);
  141. meta->right_aligned = false;
  142. if (zeroise) {
  143. internal_memset(allocated, 0, size);
  144. } else if (flags()->max_malloc_fill_size > 0) {
  145. uptr fill_size = Min(size, (uptr)flags()->max_malloc_fill_size);
  146. internal_memset(allocated, flags()->malloc_fill_byte, fill_size);
  147. }
  148. if (size != orig_size) {
  149. u8 *tail = reinterpret_cast<u8 *>(allocated) + orig_size;
  150. uptr tail_length = size - orig_size;
  151. internal_memcpy(tail, tail_magic, tail_length - 1);
  152. // Short granule is excluded from magic tail, so we explicitly untag.
  153. tail[tail_length - 1] = 0;
  154. }
  155. void *user_ptr = allocated;
  156. // Tagging can only be skipped when both tag_in_malloc and tag_in_free are
  157. // false. When tag_in_malloc = false and tag_in_free = true malloc needs to
  158. // retag to 0.
  159. if (InTaggableRegion(reinterpret_cast<uptr>(user_ptr)) &&
  160. (flags()->tag_in_malloc || flags()->tag_in_free) &&
  161. atomic_load_relaxed(&hwasan_allocator_tagging_enabled)) {
  162. if (flags()->tag_in_malloc && malloc_bisect(stack, orig_size)) {
  163. tag_t tag = t ? t->GenerateRandomTag() : kFallbackAllocTag;
  164. uptr tag_size = orig_size ? orig_size : 1;
  165. uptr full_granule_size = RoundDownTo(tag_size, kShadowAlignment);
  166. user_ptr =
  167. (void *)TagMemoryAligned((uptr)user_ptr, full_granule_size, tag);
  168. if (full_granule_size != tag_size) {
  169. u8 *short_granule =
  170. reinterpret_cast<u8 *>(allocated) + full_granule_size;
  171. TagMemoryAligned((uptr)short_granule, kShadowAlignment,
  172. tag_size % kShadowAlignment);
  173. short_granule[kShadowAlignment - 1] = tag;
  174. }
  175. } else {
  176. user_ptr = (void *)TagMemoryAligned((uptr)user_ptr, size, 0);
  177. }
  178. }
  179. HWASAN_MALLOC_HOOK(user_ptr, size);
  180. return user_ptr;
  181. }
  182. static bool PointerAndMemoryTagsMatch(void *tagged_ptr) {
  183. CHECK(tagged_ptr);
  184. uptr tagged_uptr = reinterpret_cast<uptr>(tagged_ptr);
  185. if (!InTaggableRegion(tagged_uptr))
  186. return true;
  187. tag_t mem_tag = *reinterpret_cast<tag_t *>(
  188. MemToShadow(reinterpret_cast<uptr>(UntagPtr(tagged_ptr))));
  189. return PossiblyShortTagMatches(mem_tag, tagged_uptr, 1);
  190. }
  191. static bool CheckInvalidFree(StackTrace *stack, void *untagged_ptr,
  192. void *tagged_ptr) {
  193. // This function can return true if halt_on_error is false.
  194. if (!MemIsApp(reinterpret_cast<uptr>(untagged_ptr)) ||
  195. !PointerAndMemoryTagsMatch(tagged_ptr)) {
  196. ReportInvalidFree(stack, reinterpret_cast<uptr>(tagged_ptr));
  197. return true;
  198. }
  199. return false;
  200. }
  201. static void HwasanDeallocate(StackTrace *stack, void *tagged_ptr) {
  202. CHECK(tagged_ptr);
  203. HWASAN_FREE_HOOK(tagged_ptr);
  204. bool in_taggable_region =
  205. InTaggableRegion(reinterpret_cast<uptr>(tagged_ptr));
  206. void *untagged_ptr = in_taggable_region ? UntagPtr(tagged_ptr) : tagged_ptr;
  207. if (CheckInvalidFree(stack, untagged_ptr, tagged_ptr))
  208. return;
  209. void *aligned_ptr = reinterpret_cast<void *>(
  210. RoundDownTo(reinterpret_cast<uptr>(untagged_ptr), kShadowAlignment));
  211. tag_t pointer_tag = GetTagFromPointer(reinterpret_cast<uptr>(tagged_ptr));
  212. Metadata *meta =
  213. reinterpret_cast<Metadata *>(allocator.GetMetaData(aligned_ptr));
  214. if (!meta) {
  215. ReportInvalidFree(stack, reinterpret_cast<uptr>(tagged_ptr));
  216. return;
  217. }
  218. uptr orig_size = meta->get_requested_size();
  219. u32 free_context_id = StackDepotPut(*stack);
  220. u32 alloc_context_id = meta->alloc_context_id;
  221. // Check tail magic.
  222. uptr tagged_size = TaggedSize(orig_size);
  223. if (flags()->free_checks_tail_magic && orig_size &&
  224. tagged_size != orig_size) {
  225. uptr tail_size = tagged_size - orig_size - 1;
  226. CHECK_LT(tail_size, kShadowAlignment);
  227. void *tail_beg = reinterpret_cast<void *>(
  228. reinterpret_cast<uptr>(aligned_ptr) + orig_size);
  229. tag_t short_granule_memtag = *(reinterpret_cast<tag_t *>(
  230. reinterpret_cast<uptr>(tail_beg) + tail_size));
  231. if (tail_size &&
  232. (internal_memcmp(tail_beg, tail_magic, tail_size) ||
  233. (in_taggable_region && pointer_tag != short_granule_memtag)))
  234. ReportTailOverwritten(stack, reinterpret_cast<uptr>(tagged_ptr),
  235. orig_size, tail_magic);
  236. }
  237. meta->set_requested_size(0);
  238. meta->alloc_context_id = 0;
  239. // This memory will not be reused by anyone else, so we are free to keep it
  240. // poisoned.
  241. Thread *t = GetCurrentThread();
  242. if (flags()->max_free_fill_size > 0) {
  243. uptr fill_size =
  244. Min(TaggedSize(orig_size), (uptr)flags()->max_free_fill_size);
  245. internal_memset(aligned_ptr, flags()->free_fill_byte, fill_size);
  246. }
  247. if (in_taggable_region && flags()->tag_in_free && malloc_bisect(stack, 0) &&
  248. atomic_load_relaxed(&hwasan_allocator_tagging_enabled)) {
  249. // Always store full 8-bit tags on free to maximize UAF detection.
  250. tag_t tag;
  251. if (t) {
  252. // Make sure we are not using a short granule tag as a poison tag. This
  253. // would make us attempt to read the memory on a UaF.
  254. // The tag can be zero if tagging is disabled on this thread.
  255. do {
  256. tag = t->GenerateRandomTag(/*num_bits=*/8);
  257. } while (
  258. UNLIKELY((tag < kShadowAlignment || tag == pointer_tag) && tag != 0));
  259. } else {
  260. static_assert(kFallbackFreeTag >= kShadowAlignment,
  261. "fallback tag must not be a short granule tag.");
  262. tag = kFallbackFreeTag;
  263. }
  264. TagMemoryAligned(reinterpret_cast<uptr>(aligned_ptr), TaggedSize(orig_size),
  265. tag);
  266. }
  267. if (t) {
  268. allocator.Deallocate(t->allocator_cache(), aligned_ptr);
  269. if (auto *ha = t->heap_allocations())
  270. ha->push({reinterpret_cast<uptr>(tagged_ptr), alloc_context_id,
  271. free_context_id, static_cast<u32>(orig_size)});
  272. } else {
  273. SpinMutexLock l(&fallback_mutex);
  274. AllocatorCache *cache = &fallback_allocator_cache;
  275. allocator.Deallocate(cache, aligned_ptr);
  276. }
  277. }
  278. static void *HwasanReallocate(StackTrace *stack, void *tagged_ptr_old,
  279. uptr new_size, uptr alignment) {
  280. void *untagged_ptr_old =
  281. InTaggableRegion(reinterpret_cast<uptr>(tagged_ptr_old))
  282. ? UntagPtr(tagged_ptr_old)
  283. : tagged_ptr_old;
  284. if (CheckInvalidFree(stack, untagged_ptr_old, tagged_ptr_old))
  285. return nullptr;
  286. void *tagged_ptr_new =
  287. HwasanAllocate(stack, new_size, alignment, false /*zeroise*/);
  288. if (tagged_ptr_old && tagged_ptr_new) {
  289. Metadata *meta =
  290. reinterpret_cast<Metadata *>(allocator.GetMetaData(untagged_ptr_old));
  291. internal_memcpy(
  292. UntagPtr(tagged_ptr_new), untagged_ptr_old,
  293. Min(new_size, static_cast<uptr>(meta->get_requested_size())));
  294. HwasanDeallocate(stack, tagged_ptr_old);
  295. }
  296. return tagged_ptr_new;
  297. }
  298. static void *HwasanCalloc(StackTrace *stack, uptr nmemb, uptr size) {
  299. if (UNLIKELY(CheckForCallocOverflow(size, nmemb))) {
  300. if (AllocatorMayReturnNull())
  301. return nullptr;
  302. ReportCallocOverflow(nmemb, size, stack);
  303. }
  304. return HwasanAllocate(stack, nmemb * size, sizeof(u64), true);
  305. }
  306. HwasanChunkView FindHeapChunkByAddress(uptr address) {
  307. if (!allocator.PointerIsMine(reinterpret_cast<void *>(address)))
  308. return HwasanChunkView();
  309. void *block = allocator.GetBlockBegin(reinterpret_cast<void*>(address));
  310. if (!block)
  311. return HwasanChunkView();
  312. Metadata *metadata =
  313. reinterpret_cast<Metadata*>(allocator.GetMetaData(block));
  314. return HwasanChunkView(reinterpret_cast<uptr>(block), metadata);
  315. }
  316. static uptr AllocationSize(const void *tagged_ptr) {
  317. const void *untagged_ptr = UntagPtr(tagged_ptr);
  318. if (!untagged_ptr) return 0;
  319. const void *beg = allocator.GetBlockBegin(untagged_ptr);
  320. Metadata *b = (Metadata *)allocator.GetMetaData(untagged_ptr);
  321. if (b->right_aligned) {
  322. if (beg != reinterpret_cast<void *>(RoundDownTo(
  323. reinterpret_cast<uptr>(untagged_ptr), kShadowAlignment)))
  324. return 0;
  325. } else {
  326. if (beg != untagged_ptr) return 0;
  327. }
  328. return b->get_requested_size();
  329. }
  330. void *hwasan_malloc(uptr size, StackTrace *stack) {
  331. return SetErrnoOnNull(HwasanAllocate(stack, size, sizeof(u64), false));
  332. }
  333. void *hwasan_calloc(uptr nmemb, uptr size, StackTrace *stack) {
  334. return SetErrnoOnNull(HwasanCalloc(stack, nmemb, size));
  335. }
  336. void *hwasan_realloc(void *ptr, uptr size, StackTrace *stack) {
  337. if (!ptr)
  338. return SetErrnoOnNull(HwasanAllocate(stack, size, sizeof(u64), false));
  339. if (size == 0) {
  340. HwasanDeallocate(stack, ptr);
  341. return nullptr;
  342. }
  343. return SetErrnoOnNull(HwasanReallocate(stack, ptr, size, sizeof(u64)));
  344. }
  345. void *hwasan_reallocarray(void *ptr, uptr nmemb, uptr size, StackTrace *stack) {
  346. if (UNLIKELY(CheckForCallocOverflow(size, nmemb))) {
  347. errno = errno_ENOMEM;
  348. if (AllocatorMayReturnNull())
  349. return nullptr;
  350. ReportReallocArrayOverflow(nmemb, size, stack);
  351. }
  352. return hwasan_realloc(ptr, nmemb * size, stack);
  353. }
  354. void *hwasan_valloc(uptr size, StackTrace *stack) {
  355. return SetErrnoOnNull(
  356. HwasanAllocate(stack, size, GetPageSizeCached(), false));
  357. }
  358. void *hwasan_pvalloc(uptr size, StackTrace *stack) {
  359. uptr PageSize = GetPageSizeCached();
  360. if (UNLIKELY(CheckForPvallocOverflow(size, PageSize))) {
  361. errno = errno_ENOMEM;
  362. if (AllocatorMayReturnNull())
  363. return nullptr;
  364. ReportPvallocOverflow(size, stack);
  365. }
  366. // pvalloc(0) should allocate one page.
  367. size = size ? RoundUpTo(size, PageSize) : PageSize;
  368. return SetErrnoOnNull(HwasanAllocate(stack, size, PageSize, false));
  369. }
  370. void *hwasan_aligned_alloc(uptr alignment, uptr size, StackTrace *stack) {
  371. if (UNLIKELY(!CheckAlignedAllocAlignmentAndSize(alignment, size))) {
  372. errno = errno_EINVAL;
  373. if (AllocatorMayReturnNull())
  374. return nullptr;
  375. ReportInvalidAlignedAllocAlignment(size, alignment, stack);
  376. }
  377. return SetErrnoOnNull(HwasanAllocate(stack, size, alignment, false));
  378. }
  379. void *hwasan_memalign(uptr alignment, uptr size, StackTrace *stack) {
  380. if (UNLIKELY(!IsPowerOfTwo(alignment))) {
  381. errno = errno_EINVAL;
  382. if (AllocatorMayReturnNull())
  383. return nullptr;
  384. ReportInvalidAllocationAlignment(alignment, stack);
  385. }
  386. return SetErrnoOnNull(HwasanAllocate(stack, size, alignment, false));
  387. }
  388. int hwasan_posix_memalign(void **memptr, uptr alignment, uptr size,
  389. StackTrace *stack) {
  390. if (UNLIKELY(!CheckPosixMemalignAlignment(alignment))) {
  391. if (AllocatorMayReturnNull())
  392. return errno_EINVAL;
  393. ReportInvalidPosixMemalignAlignment(alignment, stack);
  394. }
  395. void *ptr = HwasanAllocate(stack, size, alignment, false);
  396. if (UNLIKELY(!ptr))
  397. // OOM error is already taken care of by HwasanAllocate.
  398. return errno_ENOMEM;
  399. CHECK(IsAligned((uptr)ptr, alignment));
  400. *memptr = ptr;
  401. return 0;
  402. }
  403. void hwasan_free(void *ptr, StackTrace *stack) {
  404. return HwasanDeallocate(stack, ptr);
  405. }
  406. } // namespace __hwasan
  407. using namespace __hwasan;
  408. void __hwasan_enable_allocator_tagging() {
  409. atomic_store_relaxed(&hwasan_allocator_tagging_enabled, 1);
  410. }
  411. void __hwasan_disable_allocator_tagging() {
  412. atomic_store_relaxed(&hwasan_allocator_tagging_enabled, 0);
  413. }
  414. uptr __sanitizer_get_current_allocated_bytes() {
  415. uptr stats[AllocatorStatCount];
  416. allocator.GetStats(stats);
  417. return stats[AllocatorStatAllocated];
  418. }
  419. uptr __sanitizer_get_heap_size() {
  420. uptr stats[AllocatorStatCount];
  421. allocator.GetStats(stats);
  422. return stats[AllocatorStatMapped];
  423. }
  424. uptr __sanitizer_get_free_bytes() { return 1; }
  425. uptr __sanitizer_get_unmapped_bytes() { return 1; }
  426. uptr __sanitizer_get_estimated_allocated_size(uptr size) { return size; }
  427. int __sanitizer_get_ownership(const void *p) { return AllocationSize(p) != 0; }
  428. uptr __sanitizer_get_allocated_size(const void *p) { return AllocationSize(p); }