dfsan_allocator.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. //===-- dfsan_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 DataflowSanitizer.
  10. //
  11. // DataflowSanitizer allocator.
  12. //===----------------------------------------------------------------------===//
  13. #include "dfsan_allocator.h"
  14. #include "dfsan.h"
  15. #include "dfsan_flags.h"
  16. #include "dfsan_thread.h"
  17. #include "sanitizer_common/sanitizer_allocator.h"
  18. #include "sanitizer_common/sanitizer_allocator_checks.h"
  19. #include "sanitizer_common/sanitizer_allocator_interface.h"
  20. #include "sanitizer_common/sanitizer_allocator_report.h"
  21. #include "sanitizer_common/sanitizer_errno.h"
  22. namespace __dfsan {
  23. struct Metadata {
  24. uptr requested_size;
  25. };
  26. struct DFsanMapUnmapCallback {
  27. void OnMap(uptr p, uptr size) const { dfsan_set_label(0, (void *)p, size); }
  28. void OnMapSecondary(uptr p, uptr size, uptr user_begin,
  29. uptr user_size) const {
  30. OnMap(p, size);
  31. }
  32. void OnUnmap(uptr p, uptr size) const { dfsan_set_label(0, (void *)p, size); }
  33. };
  34. #if defined(__aarch64__)
  35. const uptr kAllocatorSpace = 0xE00000000000ULL;
  36. #else
  37. const uptr kAllocatorSpace = 0x700000000000ULL;
  38. #endif
  39. const uptr kMaxAllowedMallocSize = 8UL << 30;
  40. struct AP64 { // Allocator64 parameters. Deliberately using a short name.
  41. static const uptr kSpaceBeg = kAllocatorSpace;
  42. static const uptr kSpaceSize = 0x40000000000; // 4T.
  43. static const uptr kMetadataSize = sizeof(Metadata);
  44. typedef DefaultSizeClassMap SizeClassMap;
  45. typedef DFsanMapUnmapCallback MapUnmapCallback;
  46. static const uptr kFlags = 0;
  47. using AddressSpaceView = LocalAddressSpaceView;
  48. };
  49. typedef SizeClassAllocator64<AP64> PrimaryAllocator;
  50. typedef CombinedAllocator<PrimaryAllocator> Allocator;
  51. typedef Allocator::AllocatorCache AllocatorCache;
  52. static Allocator allocator;
  53. static AllocatorCache fallback_allocator_cache;
  54. static StaticSpinMutex fallback_mutex;
  55. static uptr max_malloc_size;
  56. void dfsan_allocator_init() {
  57. SetAllocatorMayReturnNull(common_flags()->allocator_may_return_null);
  58. allocator.Init(common_flags()->allocator_release_to_os_interval_ms);
  59. if (common_flags()->max_allocation_size_mb)
  60. max_malloc_size = Min(common_flags()->max_allocation_size_mb << 20,
  61. kMaxAllowedMallocSize);
  62. else
  63. max_malloc_size = kMaxAllowedMallocSize;
  64. }
  65. AllocatorCache *GetAllocatorCache(DFsanThreadLocalMallocStorage *ms) {
  66. CHECK(ms);
  67. CHECK_LE(sizeof(AllocatorCache), sizeof(ms->allocator_cache));
  68. return reinterpret_cast<AllocatorCache *>(ms->allocator_cache);
  69. }
  70. void DFsanThreadLocalMallocStorage::CommitBack() {
  71. allocator.SwallowCache(GetAllocatorCache(this));
  72. }
  73. static void *DFsanAllocate(uptr size, uptr alignment, bool zeroise) {
  74. if (size > max_malloc_size) {
  75. if (AllocatorMayReturnNull()) {
  76. Report("WARNING: DataflowSanitizer failed to allocate 0x%zx bytes\n",
  77. size);
  78. return nullptr;
  79. }
  80. BufferedStackTrace stack;
  81. ReportAllocationSizeTooBig(size, max_malloc_size, &stack);
  82. }
  83. if (UNLIKELY(IsRssLimitExceeded())) {
  84. if (AllocatorMayReturnNull())
  85. return nullptr;
  86. BufferedStackTrace stack;
  87. ReportRssLimitExceeded(&stack);
  88. }
  89. DFsanThread *t = GetCurrentThread();
  90. void *allocated;
  91. if (t) {
  92. AllocatorCache *cache = GetAllocatorCache(&t->malloc_storage());
  93. allocated = allocator.Allocate(cache, size, alignment);
  94. } else {
  95. SpinMutexLock l(&fallback_mutex);
  96. AllocatorCache *cache = &fallback_allocator_cache;
  97. allocated = allocator.Allocate(cache, size, alignment);
  98. }
  99. if (UNLIKELY(!allocated)) {
  100. SetAllocatorOutOfMemory();
  101. if (AllocatorMayReturnNull())
  102. return nullptr;
  103. BufferedStackTrace stack;
  104. ReportOutOfMemory(size, &stack);
  105. }
  106. Metadata *meta =
  107. reinterpret_cast<Metadata *>(allocator.GetMetaData(allocated));
  108. meta->requested_size = size;
  109. if (zeroise) {
  110. internal_memset(allocated, 0, size);
  111. dfsan_set_label(0, allocated, size);
  112. } else if (flags().zero_in_malloc) {
  113. dfsan_set_label(0, allocated, size);
  114. }
  115. return allocated;
  116. }
  117. void dfsan_deallocate(void *p) {
  118. CHECK(p);
  119. Metadata *meta = reinterpret_cast<Metadata *>(allocator.GetMetaData(p));
  120. uptr size = meta->requested_size;
  121. meta->requested_size = 0;
  122. if (flags().zero_in_free)
  123. dfsan_set_label(0, p, size);
  124. DFsanThread *t = GetCurrentThread();
  125. if (t) {
  126. AllocatorCache *cache = GetAllocatorCache(&t->malloc_storage());
  127. allocator.Deallocate(cache, p);
  128. } else {
  129. SpinMutexLock l(&fallback_mutex);
  130. AllocatorCache *cache = &fallback_allocator_cache;
  131. allocator.Deallocate(cache, p);
  132. }
  133. }
  134. void *DFsanReallocate(void *old_p, uptr new_size, uptr alignment) {
  135. Metadata *meta = reinterpret_cast<Metadata *>(allocator.GetMetaData(old_p));
  136. uptr old_size = meta->requested_size;
  137. uptr actually_allocated_size = allocator.GetActuallyAllocatedSize(old_p);
  138. if (new_size <= actually_allocated_size) {
  139. // We are not reallocating here.
  140. meta->requested_size = new_size;
  141. if (new_size > old_size && flags().zero_in_malloc)
  142. dfsan_set_label(0, (char *)old_p + old_size, new_size - old_size);
  143. return old_p;
  144. }
  145. uptr memcpy_size = Min(new_size, old_size);
  146. void *new_p = DFsanAllocate(new_size, alignment, false /*zeroise*/);
  147. if (new_p) {
  148. dfsan_copy_memory(new_p, old_p, memcpy_size);
  149. dfsan_deallocate(old_p);
  150. }
  151. return new_p;
  152. }
  153. void *DFsanCalloc(uptr nmemb, uptr size) {
  154. if (UNLIKELY(CheckForCallocOverflow(size, nmemb))) {
  155. if (AllocatorMayReturnNull())
  156. return nullptr;
  157. BufferedStackTrace stack;
  158. ReportCallocOverflow(nmemb, size, &stack);
  159. }
  160. return DFsanAllocate(nmemb * size, sizeof(u64), true /*zeroise*/);
  161. }
  162. static const void *AllocationBegin(const void *p) {
  163. if (!p)
  164. return nullptr;
  165. void *beg = allocator.GetBlockBegin(p);
  166. if (!beg)
  167. return nullptr;
  168. Metadata *b = (Metadata *)allocator.GetMetaData(beg);
  169. if (!b)
  170. return nullptr;
  171. if (b->requested_size == 0)
  172. return nullptr;
  173. return (const void *)beg;
  174. }
  175. static uptr AllocationSize(const void *p) {
  176. if (!p)
  177. return 0;
  178. const void *beg = allocator.GetBlockBegin(p);
  179. if (beg != p)
  180. return 0;
  181. Metadata *b = (Metadata *)allocator.GetMetaData(p);
  182. return b->requested_size;
  183. }
  184. static uptr AllocationSizeFast(const void *p) {
  185. return reinterpret_cast<Metadata *>(allocator.GetMetaData(p))->requested_size;
  186. }
  187. void *dfsan_malloc(uptr size) {
  188. return SetErrnoOnNull(DFsanAllocate(size, sizeof(u64), false /*zeroise*/));
  189. }
  190. void *dfsan_calloc(uptr nmemb, uptr size) {
  191. return SetErrnoOnNull(DFsanCalloc(nmemb, size));
  192. }
  193. void *dfsan_realloc(void *ptr, uptr size) {
  194. if (!ptr)
  195. return SetErrnoOnNull(DFsanAllocate(size, sizeof(u64), false /*zeroise*/));
  196. if (size == 0) {
  197. dfsan_deallocate(ptr);
  198. return nullptr;
  199. }
  200. return SetErrnoOnNull(DFsanReallocate(ptr, size, sizeof(u64)));
  201. }
  202. void *dfsan_reallocarray(void *ptr, uptr nmemb, uptr size) {
  203. if (UNLIKELY(CheckForCallocOverflow(size, nmemb))) {
  204. errno = errno_ENOMEM;
  205. if (AllocatorMayReturnNull())
  206. return nullptr;
  207. BufferedStackTrace stack;
  208. ReportReallocArrayOverflow(nmemb, size, &stack);
  209. }
  210. return dfsan_realloc(ptr, nmemb * size);
  211. }
  212. void *dfsan_valloc(uptr size) {
  213. return SetErrnoOnNull(
  214. DFsanAllocate(size, GetPageSizeCached(), false /*zeroise*/));
  215. }
  216. void *dfsan_pvalloc(uptr size) {
  217. uptr PageSize = GetPageSizeCached();
  218. if (UNLIKELY(CheckForPvallocOverflow(size, PageSize))) {
  219. errno = errno_ENOMEM;
  220. if (AllocatorMayReturnNull())
  221. return nullptr;
  222. BufferedStackTrace stack;
  223. ReportPvallocOverflow(size, &stack);
  224. }
  225. // pvalloc(0) should allocate one page.
  226. size = size ? RoundUpTo(size, PageSize) : PageSize;
  227. return SetErrnoOnNull(DFsanAllocate(size, PageSize, false /*zeroise*/));
  228. }
  229. void *dfsan_aligned_alloc(uptr alignment, uptr size) {
  230. if (UNLIKELY(!CheckAlignedAllocAlignmentAndSize(alignment, size))) {
  231. errno = errno_EINVAL;
  232. if (AllocatorMayReturnNull())
  233. return nullptr;
  234. BufferedStackTrace stack;
  235. ReportInvalidAlignedAllocAlignment(size, alignment, &stack);
  236. }
  237. return SetErrnoOnNull(DFsanAllocate(size, alignment, false /*zeroise*/));
  238. }
  239. void *dfsan_memalign(uptr alignment, uptr size) {
  240. if (UNLIKELY(!IsPowerOfTwo(alignment))) {
  241. errno = errno_EINVAL;
  242. if (AllocatorMayReturnNull())
  243. return nullptr;
  244. BufferedStackTrace stack;
  245. ReportInvalidAllocationAlignment(alignment, &stack);
  246. }
  247. return SetErrnoOnNull(DFsanAllocate(size, alignment, false /*zeroise*/));
  248. }
  249. int dfsan_posix_memalign(void **memptr, uptr alignment, uptr size) {
  250. if (UNLIKELY(!CheckPosixMemalignAlignment(alignment))) {
  251. if (AllocatorMayReturnNull())
  252. return errno_EINVAL;
  253. BufferedStackTrace stack;
  254. ReportInvalidPosixMemalignAlignment(alignment, &stack);
  255. }
  256. void *ptr = DFsanAllocate(size, alignment, false /*zeroise*/);
  257. if (UNLIKELY(!ptr))
  258. // OOM error is already taken care of by DFsanAllocate.
  259. return errno_ENOMEM;
  260. CHECK(IsAligned((uptr)ptr, alignment));
  261. *memptr = ptr;
  262. return 0;
  263. }
  264. } // namespace __dfsan
  265. using namespace __dfsan;
  266. uptr __sanitizer_get_current_allocated_bytes() {
  267. uptr stats[AllocatorStatCount];
  268. allocator.GetStats(stats);
  269. return stats[AllocatorStatAllocated];
  270. }
  271. uptr __sanitizer_get_heap_size() {
  272. uptr stats[AllocatorStatCount];
  273. allocator.GetStats(stats);
  274. return stats[AllocatorStatMapped];
  275. }
  276. uptr __sanitizer_get_free_bytes() { return 1; }
  277. uptr __sanitizer_get_unmapped_bytes() { return 1; }
  278. uptr __sanitizer_get_estimated_allocated_size(uptr size) { return size; }
  279. int __sanitizer_get_ownership(const void *p) { return AllocationSize(p) != 0; }
  280. const void *__sanitizer_get_allocated_begin(const void *p) {
  281. return AllocationBegin(p);
  282. }
  283. uptr __sanitizer_get_allocated_size(const void *p) { return AllocationSize(p); }
  284. uptr __sanitizer_get_allocated_size_fast(const void *p) {
  285. DCHECK_EQ(p, __sanitizer_get_allocated_begin(p));
  286. uptr ret = AllocationSizeFast(p);
  287. DCHECK_EQ(ret, __sanitizer_get_allocated_size(p));
  288. return ret;
  289. }