msan.cc revision 12c46937db2a5ab9237ce314c3f3a83636e8a575
1//===-- msan.cc -----------------------------------------------------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file is a part of MemorySanitizer. 11// 12// MemorySanitizer runtime. 13//===----------------------------------------------------------------------===// 14 15#include "msan.h" 16#include "sanitizer_common/sanitizer_atomic.h" 17#include "sanitizer_common/sanitizer_common.h" 18#include "sanitizer_common/sanitizer_flags.h" 19#include "sanitizer_common/sanitizer_libc.h" 20#include "sanitizer_common/sanitizer_procmaps.h" 21#include "sanitizer_common/sanitizer_stacktrace.h" 22#include "sanitizer_common/sanitizer_symbolizer.h" 23 24#include "interception/interception.h" 25 26// ACHTUNG! No system header includes in this file. 27 28using namespace __sanitizer; 29 30// Globals. 31static THREADLOCAL int msan_expect_umr = 0; 32static THREADLOCAL int msan_expected_umr_found = 0; 33 34static int msan_running_under_dr = 0; 35 36SANITIZER_INTERFACE_ATTRIBUTE 37THREADLOCAL u64 __msan_param_tls[kMsanParamTlsSizeInWords]; 38 39SANITIZER_INTERFACE_ATTRIBUTE 40THREADLOCAL u32 __msan_param_origin_tls[kMsanParamTlsSizeInWords]; 41 42SANITIZER_INTERFACE_ATTRIBUTE 43THREADLOCAL u64 __msan_retval_tls[kMsanRetvalTlsSizeInWords]; 44 45SANITIZER_INTERFACE_ATTRIBUTE 46THREADLOCAL u32 __msan_retval_origin_tls; 47 48SANITIZER_INTERFACE_ATTRIBUTE 49THREADLOCAL u64 __msan_va_arg_tls[kMsanParamTlsSizeInWords]; 50 51SANITIZER_INTERFACE_ATTRIBUTE 52THREADLOCAL u64 __msan_va_arg_overflow_size_tls; 53 54SANITIZER_INTERFACE_ATTRIBUTE 55THREADLOCAL u32 __msan_origin_tls; 56 57static THREADLOCAL struct { 58 uptr stack_top, stack_bottom; 59} __msan_stack_bounds; 60 61extern "C" const int __msan_track_origins; 62int __msan_get_track_origins() { 63 return __msan_track_origins; 64} 65 66namespace __msan { 67 68static bool IsRunningUnderDr() { 69 bool result = false; 70 MemoryMappingLayout proc_maps; 71 const sptr kBufSize = 4095; 72 char *filename = (char*)MmapOrDie(kBufSize, __FUNCTION__); 73 while (proc_maps.Next(/* start */0, /* end */0, /* file_offset */0, 74 filename, kBufSize)) { 75 if (internal_strstr(filename, "libdynamorio") != 0) { 76 result = true; 77 break; 78 } 79 } 80 UnmapOrDie(filename, kBufSize); 81 return result; 82} 83 84static Flags msan_flags; 85 86Flags *flags() { 87 return &msan_flags; 88} 89 90int msan_inited = 0; 91bool msan_init_is_running; 92 93int msan_report_count = 0; 94 95// Array of stack origins. 96// FIXME: make it resizable. 97static const uptr kNumStackOriginDescrs = 1024 * 1024; 98static const char *StackOriginDescr[kNumStackOriginDescrs]; 99static atomic_uint32_t NumStackOriginDescrs; 100 101static void ParseFlagsFromString(Flags *f, const char *str) { 102 ParseFlag(str, &f->poison_heap_with_zeroes, "poison_heap_with_zeroes"); 103 ParseFlag(str, &f->poison_stack_with_zeroes, "poison_stack_with_zeroes"); 104 ParseFlag(str, &f->poison_in_malloc, "poison_in_malloc"); 105 ParseFlag(str, &f->exit_code, "exit_code"); 106 if (f->exit_code < 0 || f->exit_code > 127) { 107 Printf("Exit code not in [0, 128) range: %d\n", f->exit_code); 108 f->exit_code = 1; 109 Die(); 110 } 111 ParseFlag(str, &f->num_callers, "num_callers"); 112 ParseFlag(str, &f->report_umrs, "report_umrs"); 113 ParseFlag(str, &f->verbosity, "verbosity"); 114} 115 116static void InitializeFlags(Flags *f, const char *options) { 117 internal_memset(f, 0, sizeof(*f)); 118 119 f->poison_heap_with_zeroes = false; 120 f->poison_stack_with_zeroes = false; 121 f->poison_in_malloc = true; 122 f->exit_code = 77; 123 f->num_callers = 20; 124 f->report_umrs = true; 125 f->verbosity = 0; 126 127 ParseFlagsFromString(f, options); 128} 129 130static void GetCurrentStackBounds(uptr *stack_top, uptr *stack_bottom) { 131 if (__msan_stack_bounds.stack_top == 0) { 132 // Break recursion (GetStackTrace -> GetThreadStackTopAndBottom -> 133 // realloc -> GetStackTrace). 134 __msan_stack_bounds.stack_top = __msan_stack_bounds.stack_bottom = 1; 135 GetThreadStackTopAndBottom(/* at_initialization */false, 136 &__msan_stack_bounds.stack_top, 137 &__msan_stack_bounds.stack_bottom); 138 } 139 *stack_top = __msan_stack_bounds.stack_top; 140 *stack_bottom = __msan_stack_bounds.stack_bottom; 141} 142 143void GetStackTrace(StackTrace *stack, uptr max_s, uptr pc, uptr bp) { 144 uptr stack_top, stack_bottom; 145 GetCurrentStackBounds(&stack_top, &stack_bottom); 146 stack->size = 0; 147 stack->trace[0] = pc; 148 stack->max_size = max_s; 149 stack->FastUnwindStack(pc, bp, stack_top, stack_bottom); 150} 151 152void PrintWarning(uptr pc, uptr bp) { 153 PrintWarningWithOrigin(pc, bp, __msan_origin_tls); 154} 155 156bool OriginIsValid(u32 origin) { 157 return origin != 0 && origin != (u32)-1; 158} 159 160void PrintWarningWithOrigin(uptr pc, uptr bp, u32 origin) { 161 if (msan_expect_umr) { 162 // Printf("Expected UMR\n"); 163 __msan_origin_tls = origin; 164 msan_expected_umr_found = 1; 165 return; 166 } 167 168 ++msan_report_count; 169 170 StackTrace stack; 171 GetStackTrace(&stack, kStackTraceMax, pc, bp); 172 173 u32 report_origin = 174 (__msan_track_origins && OriginIsValid(origin)) ? origin : 0; 175 ReportUMR(&stack, report_origin); 176 177 if (__msan_track_origins && !OriginIsValid(origin)) { 178 Printf(" ORIGIN: invalid (%x). Might be a bug in MemorySanitizer, " 179 "please report to MemorySanitizer developers.\n", 180 origin); 181 } 182} 183 184} // namespace __msan 185 186// Interface. 187 188using namespace __msan; 189 190void __msan_warning() { 191 GET_CALLER_PC_BP_SP; 192 (void)sp; 193 PrintWarning(pc, bp); 194} 195 196void __msan_warning_noreturn() { 197 GET_CALLER_PC_BP_SP; 198 (void)sp; 199 PrintWarning(pc, bp); 200 Printf("Exiting\n"); 201 Die(); 202} 203 204void __msan_init() { 205 if (msan_inited) return; 206 msan_init_is_running = 1; 207 208 InstallAtExitHandler(); 209 SetDieCallback(MsanDie); 210 InitializeInterceptors(); 211 212 ReplaceOperatorsNewAndDelete(); 213 if (StackSizeIsUnlimited()) { 214 if (flags()->verbosity) 215 Printf("Unlimited stack, doing reexec\n"); 216 // A reasonably large stack size. It is bigger than the usual 8Mb, because, 217 // well, the program could have been run with unlimited stack for a reason. 218 SetStackSizeLimitInBytes(32 * 1024 * 1024); 219 ReExec(); 220 } 221 const char *msan_options = GetEnv("MSAN_OPTIONS"); 222 InitializeFlags(&msan_flags, msan_options); 223 if (flags()->verbosity) 224 Printf("MSAN_OPTIONS: %s\n", msan_options ? msan_options : "<empty>"); 225 msan_running_under_dr = IsRunningUnderDr(); 226 __msan_clear_on_return(); 227 if (__msan_track_origins && flags()->verbosity > 0) 228 Printf("msan_track_origins\n"); 229 if (!InitShadow(/* prot1 */false, /* prot2 */true, /* map_shadow */true, 230 __msan_track_origins)) { 231 // FIXME: prot1 = false is only required when running under DR. 232 Printf("FATAL: MemorySanitizer can not mmap the shadow memory.\n"); 233 Printf("FATAL: Make sure to compile with -fPIE and to link with -pie.\n"); 234 Printf("FATAL: Disabling ASLR is known to cause this error.\n"); 235 Printf("FATAL: If running under GDB, try " 236 "'set disable-randomization off'.\n"); 237 DumpProcessMap(); 238 Die(); 239 } 240 241 const char *external_symbolizer = GetEnv("MSAN_SYMBOLIZER_PATH"); 242 if (external_symbolizer && external_symbolizer[0]) { 243 CHECK(InitializeExternalSymbolizer(external_symbolizer)); 244 } 245 246 GetThreadStackTopAndBottom(/* at_initialization */true, 247 &__msan_stack_bounds.stack_top, 248 &__msan_stack_bounds.stack_bottom); 249 if (flags()->verbosity) 250 Printf("MemorySanitizer init done\n"); 251 msan_init_is_running = 0; 252 msan_inited = 1; 253} 254 255void __msan_set_exit_code(int exit_code) { 256 flags()->exit_code = exit_code; 257} 258 259void __msan_set_expect_umr(int expect_umr) { 260 if (expect_umr) { 261 msan_expected_umr_found = 0; 262 } else if (!msan_expected_umr_found) { 263 GET_CALLER_PC_BP_SP; 264 (void)sp; 265 StackTrace stack; 266 GetStackTrace(&stack, kStackTraceMax, pc, bp); 267 ReportExpectedUMRNotFound(&stack); 268 Die(); 269 } 270 msan_expect_umr = expect_umr; 271} 272 273void __msan_print_shadow(const void *x, uptr size) { 274 unsigned char *s = (unsigned char*)MEM_TO_SHADOW(x); 275 u32 *o = (u32*)MEM_TO_ORIGIN(x); 276 for (uptr i = 0; i < size; i++) { 277 Printf("%x%x ", s[i] >> 4, s[i] & 0xf); 278 } 279 Printf("\n"); 280 if (__msan_track_origins) { 281 for (uptr i = 0; i < size / 4; i++) { 282 Printf(" o: %x ", o[i]); 283 } 284 Printf("\n"); 285 } 286} 287 288void __msan_print_param_shadow() { 289 for (int i = 0; i < 16; i++) { 290 Printf("#%d:%zx ", i, __msan_param_tls[i]); 291 } 292 Printf("\n"); 293} 294 295sptr __msan_test_shadow(const void *x, uptr size) { 296 unsigned char *s = (unsigned char*)MEM_TO_SHADOW((uptr)x); 297 for (uptr i = 0; i < size; ++i) 298 if (s[i]) 299 return i; 300 return -1; 301} 302 303int __msan_set_poison_in_malloc(int do_poison) { 304 int old = flags()->poison_in_malloc; 305 flags()->poison_in_malloc = do_poison; 306 return old; 307} 308 309int __msan_has_dynamic_component() { 310 return msan_running_under_dr; 311} 312 313NOINLINE 314void __msan_clear_on_return() { 315 __msan_param_tls[0] = 0; 316} 317 318static void* get_tls_base() { 319 u64 p; 320 asm("mov %%fs:0, %0" 321 : "=r"(p) ::); 322 return (void*)p; 323} 324 325int __msan_get_retval_tls_offset() { 326 // volatile here is needed to avoid UB, because the compiler thinks that we 327 // are doing address arithmetics on unrelated pointers, and takes some 328 // shortcuts 329 volatile sptr retval_tls_p = (sptr)&__msan_retval_tls; 330 volatile sptr tls_base_p = (sptr)get_tls_base(); 331 return retval_tls_p - tls_base_p; 332} 333 334int __msan_get_param_tls_offset() { 335 // volatile here is needed to avoid UB, because the compiler thinks that we 336 // are doing address arithmetics on unrelated pointers, and takes some 337 // shortcuts 338 volatile sptr param_tls_p = (sptr)&__msan_param_tls; 339 volatile sptr tls_base_p = (sptr)get_tls_base(); 340 return param_tls_p - tls_base_p; 341} 342 343void __msan_partial_poison(void* data, void* shadow, uptr size) { 344 internal_memcpy((void*)MEM_TO_SHADOW((uptr)data), shadow, size); 345} 346 347void __msan_load_unpoisoned(void *src, uptr size, void *dst) { 348 internal_memcpy(dst, src, size); 349 __msan_unpoison(dst, size); 350} 351 352void __msan_set_origin(void *a, uptr size, u32 origin) { 353 // Origin mapping is 4 bytes per 4 bytes of application memory. 354 // Here we extend the range such that its left and right bounds are both 355 // 4 byte aligned. 356 if (!__msan_track_origins) return; 357 uptr x = MEM_TO_ORIGIN((uptr)a); 358 uptr beg = x & ~3UL; // align down. 359 uptr end = (x + size + 3) & ~3UL; // align up. 360 u64 origin64 = ((u64)origin << 32) | origin; 361 // This is like memset, but the value is 32-bit. We unroll by 2 two write 362 // 64-bits at once. May want to unroll further to get 128-bit stores. 363 if (beg & 7ULL) { 364 *(u32*)beg = origin; 365 beg += 4; 366 } 367 for (uptr addr = beg; addr < (end & ~7UL); addr += 8) 368 *(u64*)addr = origin64; 369 if (end & 7ULL) 370 *(u32*)(end - 4) = origin; 371} 372 373// 'descr' is created at compile time and contains '----' in the beginning. 374// When we see descr for the first time we replace '----' with a uniq id 375// and set the origin to (id | (31-th bit)). 376void __msan_set_alloca_origin(void *a, uptr size, const char *descr) { 377 static const u32 dash = '-'; 378 static const u32 first_timer = 379 dash + (dash << 8) + (dash << 16) + (dash << 24); 380 u32 *id_ptr = (u32*)descr; 381 bool print = false; // internal_strstr(descr + 4, "AllocaTOTest") != 0; 382 u32 id = *id_ptr; 383 if (id == first_timer) { 384 id = atomic_fetch_add(&NumStackOriginDescrs, 385 1, memory_order_relaxed); 386 *id_ptr = id; 387 CHECK_LT(id, kNumStackOriginDescrs); 388 StackOriginDescr[id] = descr + 4; 389 if (print) 390 Printf("First time: id=%d %s \n", id, descr + 4); 391 } 392 id |= 1U << 31; 393 if (print) 394 Printf("__msan_set_alloca_origin: descr=%s id=%x\n", descr + 4, id); 395 __msan_set_origin(a, size, id); 396} 397 398const char *__msan_get_origin_descr_if_stack(u32 id) { 399 if ((id >> 31) == 0) return 0; 400 id &= (1U << 31) - 1; 401 CHECK_LT(id, kNumStackOriginDescrs); 402 return StackOriginDescr[id]; 403} 404 405 406u32 __msan_get_origin(void *a) { 407 if (!__msan_track_origins) return 0; 408 uptr x = (uptr)a; 409 uptr aligned = x & ~3ULL; 410 uptr origin_ptr = MEM_TO_ORIGIN(aligned); 411 return *(u32*)origin_ptr; 412} 413 414u32 __msan_get_umr_origin() { 415 return __msan_origin_tls; 416} 417