[msan] Early allocator initialization.

Map MSan heap space early (in __msan_init) so that user code can not
accidentally (i.e. w/o MAP_FIXED) create a conflicting mapping.

llvm-svn: 248829
This commit is contained in:
Evgeniy Stepanov 2015-09-29 21:28:54 +00:00
parent 59dbe86325
commit 7aba3960c7
4 changed files with 35 additions and 9 deletions

View File

@ -415,6 +415,8 @@ void __msan_init() {
MsanTSDInit(MsanTSDDtor);
MsanAllocatorInit();
MsanThread *main_thread = MsanThread::Create(0, 0);
SetCurrentThread(main_thread);
main_thread->ThreadStart();

View File

@ -189,6 +189,7 @@ bool InitShadow(bool init_origins);
char *GetProcSelfMaps();
void InitializeInterceptors();
void MsanAllocatorInit();
void MsanAllocatorThreadFinish();
void *MsanCalloc(StackTrace *stack, uptr nmemb, uptr size);
void *MsanReallocate(StackTrace *stack, void *oldp, uptr size,

View File

@ -87,12 +87,7 @@ static Allocator allocator;
static AllocatorCache fallback_allocator_cache;
static SpinMutex fallback_mutex;
static int inited = 0;
static inline void Init() {
if (inited) return;
__msan_init();
inited = true; // this must happen before any threads are created.
void MsanAllocatorInit() {
allocator.Init(common_flags()->allocator_may_return_null);
}
@ -108,7 +103,6 @@ void MsanThreadLocalMallocStorage::CommitBack() {
static void *MsanAllocate(StackTrace *stack, uptr size, uptr alignment,
bool zeroise) {
Init();
if (size > kMaxAllowedMallocSize) {
Report("WARNING: MemorySanitizer failed to allocate %p bytes\n",
(void *)size);
@ -143,7 +137,6 @@ static void *MsanAllocate(StackTrace *stack, uptr size, uptr alignment,
void MsanDeallocate(StackTrace *stack, void *p) {
CHECK(p);
Init();
MSAN_FREE_HOOK(p);
Metadata *meta = reinterpret_cast<Metadata *>(allocator.GetMetaData(p));
uptr size = meta->requested_size;
@ -170,7 +163,6 @@ void MsanDeallocate(StackTrace *stack, void *p) {
}
void *MsanCalloc(StackTrace *stack, uptr nmemb, uptr size) {
Init();
if (CallocShouldReturnNullDueToOverflow(size, nmemb))
return allocator.ReturnNullOrDie();
return MsanReallocate(stack, 0, nmemb * size, sizeof(u64), true);

View File

@ -0,0 +1,31 @@
// Test that a module constructor can not map memory over the MSan heap
// (without MAP_FIXED, of course). Current implementation ensures this by
// mapping the heap early, in __msan_init.
//
// RUN: %clangxx_msan -O0 %s -o %t_1
// RUN: %clangxx_msan -O0 -DHEAP_ADDRESS=$(%run %t_1) %s -o %t_2 && %run %t_2
#include <assert.h>
#include <stdio.h>
#include <sys/mman.h>
#include <stdlib.h>
#ifdef HEAP_ADDRESS
struct A {
A() {
void *const hint = reinterpret_cast<void *>(HEAP_ADDRESS);
void *p = mmap(hint, 4096, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
// This address must be already mapped. Check that mmap() succeeds, but at a
// different address.
assert(p != reinterpret_cast<void *>(-1));
assert(p != hint);
}
} a;
#endif
int main() {
void *p = malloc(10);
printf("0x%zx\n", reinterpret_cast<size_t>(p) & (~0xfff));
free(p);
}