hwasan_allocator.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  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. alignment = Max(alignment, kShadowAlignment);
  116. uptr size = TaggedSize(orig_size);
  117. Thread *t = GetCurrentThread();
  118. void *allocated;
  119. if (t) {
  120. allocated = allocator.Allocate(t->allocator_cache(), size, alignment);
  121. } else {
  122. SpinMutexLock l(&fallback_mutex);
  123. AllocatorCache *cache = &fallback_allocator_cache;
  124. allocated = allocator.Allocate(cache, size, alignment);
  125. }
  126. if (UNLIKELY(!allocated)) {
  127. SetAllocatorOutOfMemory();
  128. if (AllocatorMayReturnNull())
  129. return nullptr;
  130. ReportOutOfMemory(size, stack);
  131. }
  132. Metadata *meta =
  133. reinterpret_cast<Metadata *>(allocator.GetMetaData(allocated));
  134. meta->set_requested_size(orig_size);
  135. meta->alloc_context_id = StackDepotPut(*stack);
  136. meta->right_aligned = false;
  137. if (zeroise) {
  138. internal_memset(allocated, 0, size);
  139. } else if (flags()->max_malloc_fill_size > 0) {
  140. uptr fill_size = Min(size, (uptr)flags()->max_malloc_fill_size);
  141. internal_memset(allocated, flags()->malloc_fill_byte, fill_size);
  142. }
  143. if (size != orig_size) {
  144. u8 *tail = reinterpret_cast<u8 *>(allocated) + orig_size;
  145. uptr tail_length = size - orig_size;
  146. internal_memcpy(tail, tail_magic, tail_length - 1);
  147. // Short granule is excluded from magic tail, so we explicitly untag.
  148. tail[tail_length - 1] = 0;
  149. }
  150. void *user_ptr = allocated;
  151. // Tagging can only be skipped when both tag_in_malloc and tag_in_free are
  152. // false. When tag_in_malloc = false and tag_in_free = true malloc needs to
  153. // retag to 0.
  154. if (InTaggableRegion(reinterpret_cast<uptr>(user_ptr)) &&
  155. (flags()->tag_in_malloc || flags()->tag_in_free) &&
  156. atomic_load_relaxed(&hwasan_allocator_tagging_enabled)) {
  157. if (flags()->tag_in_malloc && malloc_bisect(stack, orig_size)) {
  158. tag_t tag = t ? t->GenerateRandomTag() : kFallbackAllocTag;
  159. uptr tag_size = orig_size ? orig_size : 1;
  160. uptr full_granule_size = RoundDownTo(tag_size, kShadowAlignment);
  161. user_ptr =
  162. (void *)TagMemoryAligned((uptr)user_ptr, full_granule_size, tag);
  163. if (full_granule_size != tag_size) {
  164. u8 *short_granule =
  165. reinterpret_cast<u8 *>(allocated) + full_granule_size;
  166. TagMemoryAligned((uptr)short_granule, kShadowAlignment,
  167. tag_size % kShadowAlignment);
  168. short_granule[kShadowAlignment - 1] = tag;
  169. }
  170. } else {
  171. user_ptr = (void *)TagMemoryAligned((uptr)user_ptr, size, 0);
  172. }
  173. }
  174. HWASAN_MALLOC_HOOK(user_ptr, size);
  175. return user_ptr;
  176. }
  177. static bool PointerAndMemoryTagsMatch(void *tagged_ptr) {
  178. CHECK(tagged_ptr);
  179. uptr tagged_uptr = reinterpret_cast<uptr>(tagged_ptr);
  180. if (!InTaggableRegion(tagged_uptr))
  181. return true;
  182. tag_t mem_tag = *reinterpret_cast<tag_t *>(
  183. MemToShadow(reinterpret_cast<uptr>(UntagPtr(tagged_ptr))));
  184. return PossiblyShortTagMatches(mem_tag, tagged_uptr, 1);
  185. }
  186. static bool CheckInvalidFree(StackTrace *stack, void *untagged_ptr,
  187. void *tagged_ptr) {
  188. // This function can return true if halt_on_error is false.
  189. if (!MemIsApp(reinterpret_cast<uptr>(untagged_ptr)) ||
  190. !PointerAndMemoryTagsMatch(tagged_ptr)) {
  191. ReportInvalidFree(stack, reinterpret_cast<uptr>(tagged_ptr));
  192. return true;
  193. }
  194. return false;
  195. }
  196. static void HwasanDeallocate(StackTrace *stack, void *tagged_ptr) {
  197. CHECK(tagged_ptr);
  198. HWASAN_FREE_HOOK(tagged_ptr);
  199. bool in_taggable_region =
  200. InTaggableRegion(reinterpret_cast<uptr>(tagged_ptr));
  201. void *untagged_ptr = in_taggable_region ? UntagPtr(tagged_ptr) : tagged_ptr;
  202. if (CheckInvalidFree(stack, untagged_ptr, tagged_ptr))
  203. return;
  204. void *aligned_ptr = reinterpret_cast<void *>(
  205. RoundDownTo(reinterpret_cast<uptr>(untagged_ptr), kShadowAlignment));
  206. tag_t pointer_tag = GetTagFromPointer(reinterpret_cast<uptr>(tagged_ptr));
  207. Metadata *meta =
  208. reinterpret_cast<Metadata *>(allocator.GetMetaData(aligned_ptr));
  209. if (!meta) {
  210. ReportInvalidFree(stack, reinterpret_cast<uptr>(tagged_ptr));
  211. return;
  212. }
  213. uptr orig_size = meta->get_requested_size();
  214. u32 free_context_id = StackDepotPut(*stack);
  215. u32 alloc_context_id = meta->alloc_context_id;
  216. // Check tail magic.
  217. uptr tagged_size = TaggedSize(orig_size);
  218. if (flags()->free_checks_tail_magic && orig_size &&
  219. tagged_size != orig_size) {
  220. uptr tail_size = tagged_size - orig_size - 1;
  221. CHECK_LT(tail_size, kShadowAlignment);
  222. void *tail_beg = reinterpret_cast<void *>(
  223. reinterpret_cast<uptr>(aligned_ptr) + orig_size);
  224. tag_t short_granule_memtag = *(reinterpret_cast<tag_t *>(
  225. reinterpret_cast<uptr>(tail_beg) + tail_size));
  226. if (tail_size &&
  227. (internal_memcmp(tail_beg, tail_magic, tail_size) ||
  228. (in_taggable_region && pointer_tag != short_granule_memtag)))
  229. ReportTailOverwritten(stack, reinterpret_cast<uptr>(tagged_ptr),
  230. orig_size, tail_magic);
  231. }
  232. meta->set_requested_size(0);
  233. meta->alloc_context_id = 0;
  234. // This memory will not be reused by anyone else, so we are free to keep it
  235. // poisoned.
  236. Thread *t = GetCurrentThread();
  237. if (flags()->max_free_fill_size > 0) {
  238. uptr fill_size =
  239. Min(TaggedSize(orig_size), (uptr)flags()->max_free_fill_size);
  240. internal_memset(aligned_ptr, flags()->free_fill_byte, fill_size);
  241. }
  242. if (in_taggable_region && flags()->tag_in_free && malloc_bisect(stack, 0) &&
  243. atomic_load_relaxed(&hwasan_allocator_tagging_enabled)) {
  244. // Always store full 8-bit tags on free to maximize UAF detection.
  245. tag_t tag;
  246. if (t) {
  247. // Make sure we are not using a short granule tag as a poison tag. This
  248. // would make us attempt to read the memory on a UaF.
  249. // The tag can be zero if tagging is disabled on this thread.
  250. do {
  251. tag = t->GenerateRandomTag(/*num_bits=*/8);
  252. } while (
  253. UNLIKELY((tag < kShadowAlignment || tag == pointer_tag) && tag != 0));
  254. } else {
  255. static_assert(kFallbackFreeTag >= kShadowAlignment,
  256. "fallback tag must not be a short granule tag.");
  257. tag = kFallbackFreeTag;
  258. }
  259. TagMemoryAligned(reinterpret_cast<uptr>(aligned_ptr), TaggedSize(orig_size),
  260. tag);
  261. }
  262. if (t) {
  263. allocator.Deallocate(t->allocator_cache(), aligned_ptr);
  264. if (auto *ha = t->heap_allocations())
  265. ha->push({reinterpret_cast<uptr>(tagged_ptr), alloc_context_id,
  266. free_context_id, static_cast<u32>(orig_size)});
  267. } else {
  268. SpinMutexLock l(&fallback_mutex);
  269. AllocatorCache *cache = &fallback_allocator_cache;
  270. allocator.Deallocate(cache, aligned_ptr);
  271. }
  272. }
  273. static void *HwasanReallocate(StackTrace *stack, void *tagged_ptr_old,
  274. uptr new_size, uptr alignment) {
  275. void *untagged_ptr_old =
  276. InTaggableRegion(reinterpret_cast<uptr>(tagged_ptr_old))
  277. ? UntagPtr(tagged_ptr_old)
  278. : tagged_ptr_old;
  279. if (CheckInvalidFree(stack, untagged_ptr_old, tagged_ptr_old))
  280. return nullptr;
  281. void *tagged_ptr_new =
  282. HwasanAllocate(stack, new_size, alignment, false /*zeroise*/);
  283. if (tagged_ptr_old && tagged_ptr_new) {
  284. Metadata *meta =
  285. reinterpret_cast<Metadata *>(allocator.GetMetaData(untagged_ptr_old));
  286. internal_memcpy(
  287. UntagPtr(tagged_ptr_new), untagged_ptr_old,
  288. Min(new_size, static_cast<uptr>(meta->get_requested_size())));
  289. HwasanDeallocate(stack, tagged_ptr_old);
  290. }
  291. return tagged_ptr_new;
  292. }
  293. static void *HwasanCalloc(StackTrace *stack, uptr nmemb, uptr size) {
  294. if (UNLIKELY(CheckForCallocOverflow(size, nmemb))) {
  295. if (AllocatorMayReturnNull())
  296. return nullptr;
  297. ReportCallocOverflow(nmemb, size, stack);
  298. }
  299. return HwasanAllocate(stack, nmemb * size, sizeof(u64), true);
  300. }
  301. HwasanChunkView FindHeapChunkByAddress(uptr address) {
  302. if (!allocator.PointerIsMine(reinterpret_cast<void *>(address)))
  303. return HwasanChunkView();
  304. void *block = allocator.GetBlockBegin(reinterpret_cast<void*>(address));
  305. if (!block)
  306. return HwasanChunkView();
  307. Metadata *metadata =
  308. reinterpret_cast<Metadata*>(allocator.GetMetaData(block));
  309. return HwasanChunkView(reinterpret_cast<uptr>(block), metadata);
  310. }
  311. static uptr AllocationSize(const void *tagged_ptr) {
  312. const void *untagged_ptr = UntagPtr(tagged_ptr);
  313. if (!untagged_ptr) return 0;
  314. const void *beg = allocator.GetBlockBegin(untagged_ptr);
  315. Metadata *b = (Metadata *)allocator.GetMetaData(untagged_ptr);
  316. if (b->right_aligned) {
  317. if (beg != reinterpret_cast<void *>(RoundDownTo(
  318. reinterpret_cast<uptr>(untagged_ptr), kShadowAlignment)))
  319. return 0;
  320. } else {
  321. if (beg != untagged_ptr) return 0;
  322. }
  323. return b->get_requested_size();
  324. }
  325. void *hwasan_malloc(uptr size, StackTrace *stack) {
  326. return SetErrnoOnNull(HwasanAllocate(stack, size, sizeof(u64), false));
  327. }
  328. void *hwasan_calloc(uptr nmemb, uptr size, StackTrace *stack) {
  329. return SetErrnoOnNull(HwasanCalloc(stack, nmemb, size));
  330. }
  331. void *hwasan_realloc(void *ptr, uptr size, StackTrace *stack) {
  332. if (!ptr)
  333. return SetErrnoOnNull(HwasanAllocate(stack, size, sizeof(u64), false));
  334. if (size == 0) {
  335. HwasanDeallocate(stack, ptr);
  336. return nullptr;
  337. }
  338. return SetErrnoOnNull(HwasanReallocate(stack, ptr, size, sizeof(u64)));
  339. }
  340. void *hwasan_reallocarray(void *ptr, uptr nmemb, uptr size, StackTrace *stack) {
  341. if (UNLIKELY(CheckForCallocOverflow(size, nmemb))) {
  342. errno = errno_ENOMEM;
  343. if (AllocatorMayReturnNull())
  344. return nullptr;
  345. ReportReallocArrayOverflow(nmemb, size, stack);
  346. }
  347. return hwasan_realloc(ptr, nmemb * size, stack);
  348. }
  349. void *hwasan_valloc(uptr size, StackTrace *stack) {
  350. return SetErrnoOnNull(
  351. HwasanAllocate(stack, size, GetPageSizeCached(), false));
  352. }
  353. void *hwasan_pvalloc(uptr size, StackTrace *stack) {
  354. uptr PageSize = GetPageSizeCached();
  355. if (UNLIKELY(CheckForPvallocOverflow(size, PageSize))) {
  356. errno = errno_ENOMEM;
  357. if (AllocatorMayReturnNull())
  358. return nullptr;
  359. ReportPvallocOverflow(size, stack);
  360. }
  361. // pvalloc(0) should allocate one page.
  362. size = size ? RoundUpTo(size, PageSize) : PageSize;
  363. return SetErrnoOnNull(HwasanAllocate(stack, size, PageSize, false));
  364. }
  365. void *hwasan_aligned_alloc(uptr alignment, uptr size, StackTrace *stack) {
  366. if (UNLIKELY(!CheckAlignedAllocAlignmentAndSize(alignment, size))) {
  367. errno = errno_EINVAL;
  368. if (AllocatorMayReturnNull())
  369. return nullptr;
  370. ReportInvalidAlignedAllocAlignment(size, alignment, stack);
  371. }
  372. return SetErrnoOnNull(HwasanAllocate(stack, size, alignment, false));
  373. }
  374. void *hwasan_memalign(uptr alignment, uptr size, StackTrace *stack) {
  375. if (UNLIKELY(!IsPowerOfTwo(alignment))) {
  376. errno = errno_EINVAL;
  377. if (AllocatorMayReturnNull())
  378. return nullptr;
  379. ReportInvalidAllocationAlignment(alignment, stack);
  380. }
  381. return SetErrnoOnNull(HwasanAllocate(stack, size, alignment, false));
  382. }
  383. int hwasan_posix_memalign(void **memptr, uptr alignment, uptr size,
  384. StackTrace *stack) {
  385. if (UNLIKELY(!CheckPosixMemalignAlignment(alignment))) {
  386. if (AllocatorMayReturnNull())
  387. return errno_EINVAL;
  388. ReportInvalidPosixMemalignAlignment(alignment, stack);
  389. }
  390. void *ptr = HwasanAllocate(stack, size, alignment, false);
  391. if (UNLIKELY(!ptr))
  392. // OOM error is already taken care of by HwasanAllocate.
  393. return errno_ENOMEM;
  394. CHECK(IsAligned((uptr)ptr, alignment));
  395. *memptr = ptr;
  396. return 0;
  397. }
  398. void hwasan_free(void *ptr, StackTrace *stack) {
  399. return HwasanDeallocate(stack, ptr);
  400. }
  401. } // namespace __hwasan
  402. using namespace __hwasan;
  403. void __hwasan_enable_allocator_tagging() {
  404. atomic_store_relaxed(&hwasan_allocator_tagging_enabled, 1);
  405. }
  406. void __hwasan_disable_allocator_tagging() {
  407. atomic_store_relaxed(&hwasan_allocator_tagging_enabled, 0);
  408. }
  409. uptr __sanitizer_get_current_allocated_bytes() {
  410. uptr stats[AllocatorStatCount];
  411. allocator.GetStats(stats);
  412. return stats[AllocatorStatAllocated];
  413. }
  414. uptr __sanitizer_get_heap_size() {
  415. uptr stats[AllocatorStatCount];
  416. allocator.GetStats(stats);
  417. return stats[AllocatorStatMapped];
  418. }
  419. uptr __sanitizer_get_free_bytes() { return 1; }
  420. uptr __sanitizer_get_unmapped_bytes() { return 1; }
  421. uptr __sanitizer_get_estimated_allocated_size(uptr size) { return size; }
  422. int __sanitizer_get_ownership(const void *p) { return AllocationSize(p) != 0; }
  423. uptr __sanitizer_get_allocated_size(const void *p) { return AllocationSize(p); }