1 //===-- sanitizer_allocator.cc --------------------------------------------===//
3 // This file is distributed under the University of Illinois Open Source
4 // License. See LICENSE.TXT for details.
6 //===----------------------------------------------------------------------===//
8 // This file is shared between AddressSanitizer and ThreadSanitizer
10 // This allocator that is used inside run-times.
11 //===----------------------------------------------------------------------===//
12 #include "sanitizer_common.h"
14 // FIXME: We should probably use more low-level allocator that would
15 // mmap some pages and split them into chunks to fulfill requests.
16 #if defined(__linux__) && !defined(__ANDROID__)
17 extern "C" void *__libc_malloc(__sanitizer::uptr size
);
18 extern "C" void __libc_free(void *ptr
);
19 # define LIBC_MALLOC __libc_malloc
20 # define LIBC_FREE __libc_free
21 #else // __linux__ && !ANDROID
23 # define LIBC_MALLOC malloc
24 # define LIBC_FREE free
25 #endif // __linux__ && !ANDROID
27 namespace __sanitizer
{
29 const u64 kBlockMagic
= 0x6A6CB03ABCEBC041ull
;
31 void *InternalAlloc(uptr size
) {
32 if (size
+ sizeof(u64
) < size
)
34 void *p
= LIBC_MALLOC(size
+ sizeof(u64
));
37 ((u64
*)p
)[0] = kBlockMagic
;
38 return (char*)p
+ sizeof(u64
);
41 void InternalFree(void *addr
) {
44 addr
= (char*)addr
- sizeof(u64
);
45 CHECK_EQ(((u64
*)addr
)[0], kBlockMagic
);
51 static LowLevelAllocateCallback low_level_alloc_callback
;
53 void *LowLevelAllocator::Allocate(uptr size
) {
54 // Align allocation size.
55 size
= RoundUpTo(size
, 8);
56 if (allocated_end_
- allocated_current_
< (sptr
)size
) {
57 uptr size_to_allocate
= Max(size
, GetPageSizeCached());
59 (char*)MmapOrDie(size_to_allocate
, __FUNCTION__
);
60 allocated_end_
= allocated_current_
+ size_to_allocate
;
61 if (low_level_alloc_callback
) {
62 low_level_alloc_callback((uptr
)allocated_current_
,
66 CHECK(allocated_end_
- allocated_current_
>= (sptr
)size
);
67 void *res
= allocated_current_
;
68 allocated_current_
+= size
;
72 void SetLowLevelAllocateCallback(LowLevelAllocateCallback callback
) {
73 low_level_alloc_callback
= callback
;
76 bool CallocShouldReturnNullDueToOverflow(uptr size
, uptr n
) {
77 if (!size
) return false;
79 return (max
/ size
) < n
;
82 } // namespace __sanitizer