blob: b4c6f52f5e1badd4752b0cdd57bed7da90757d1d [file] [log] [blame]
Evgeniy Stepanov78c56c32012-12-11 12:27:27 +00001//===-- 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"
Evgeniy Stepanov78c56c32012-12-11 12:27:27 +000020#include "sanitizer_common/sanitizer_procmaps.h"
Evgeniy Stepanov78c56c32012-12-11 12:27:27 +000021#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
Evgeniy Stepanove9c10e22013-01-22 13:34:57 +000061extern "C" const int __msan_track_origins;
Evgeniy Stepanov78c56c32012-12-11 12:27:27 +000062int __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
Evgeniy Stepanov99bf1d72013-01-10 11:17:55 +000093int msan_report_count = 0;
94
Evgeniy Stepanov78c56c32012-12-11 12:27:27 +000095// 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
Evgeniy Stepanov78c56c32012-12-11 12:27:27 +0000152void PrintWarning(uptr pc, uptr bp) {
153 PrintWarningWithOrigin(pc, bp, __msan_origin_tls);
154}
155
Evgeniy Stepanovdb010da2012-12-26 09:32:05 +0000156bool OriginIsValid(u32 origin) {
157 return origin != 0 && origin != (u32)-1;
158}
159
Evgeniy Stepanov78c56c32012-12-11 12:27:27 +0000160void PrintWarningWithOrigin(uptr pc, uptr bp, u32 origin) {
Evgeniy Stepanov78c56c32012-12-11 12:27:27 +0000161 if (msan_expect_umr) {
162 // Printf("Expected UMR\n");
163 __msan_origin_tls = origin;
164 msan_expected_umr_found = 1;
165 return;
166 }
167
Evgeniy Stepanov99bf1d72013-01-10 11:17:55 +0000168 ++msan_report_count;
169
Evgeniy Stepanovdb010da2012-12-26 09:32:05 +0000170 StackTrace stack;
171 GetStackTrace(&stack, kStackTraceMax, pc, bp);
Evgeniy Stepanov78c56c32012-12-11 12:27:27 +0000172
Evgeniy Stepanovdb010da2012-12-26 09:32:05 +0000173 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);
Evgeniy Stepanov78c56c32012-12-11 12:27:27 +0000181 }
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;
Kostya Serebryany859778a2013-01-31 14:11:21 +0000207 SanitizerToolName = "MemorySanitizer";
Evgeniy Stepanov78c56c32012-12-11 12:27:27 +0000208
Evgeniy Stepanov99bf1d72013-01-10 11:17:55 +0000209 InstallAtExitHandler();
Evgeniy Stepanov78c56c32012-12-11 12:27:27 +0000210 SetDieCallback(MsanDie);
211 InitializeInterceptors();
212
213 ReplaceOperatorsNewAndDelete();
214 if (StackSizeIsUnlimited()) {
215 if (flags()->verbosity)
216 Printf("Unlimited stack, doing reexec\n");
217 // A reasonably large stack size. It is bigger than the usual 8Mb, because,
218 // well, the program could have been run with unlimited stack for a reason.
219 SetStackSizeLimitInBytes(32 * 1024 * 1024);
220 ReExec();
221 }
222 const char *msan_options = GetEnv("MSAN_OPTIONS");
223 InitializeFlags(&msan_flags, msan_options);
224 if (flags()->verbosity)
225 Printf("MSAN_OPTIONS: %s\n", msan_options ? msan_options : "<empty>");
226 msan_running_under_dr = IsRunningUnderDr();
227 __msan_clear_on_return();
228 if (__msan_track_origins && flags()->verbosity > 0)
229 Printf("msan_track_origins\n");
230 if (!InitShadow(/* prot1 */false, /* prot2 */true, /* map_shadow */true,
231 __msan_track_origins)) {
232 // FIXME: prot1 = false is only required when running under DR.
Evgeniy Stepanov4c9ddc12012-12-26 06:37:23 +0000233 Printf("FATAL: MemorySanitizer can not mmap the shadow memory.\n");
Evgeniy Stepanov78c56c32012-12-11 12:27:27 +0000234 Printf("FATAL: Make sure to compile with -fPIE and to link with -pie.\n");
Evgeniy Stepanov4c9ddc12012-12-26 06:37:23 +0000235 Printf("FATAL: Disabling ASLR is known to cause this error.\n");
Kostya Serebryany4b48f452012-12-27 14:09:19 +0000236 Printf("FATAL: If running under GDB, try "
237 "'set disable-randomization off'.\n");
Evgeniy Stepanov78c56c32012-12-11 12:27:27 +0000238 DumpProcessMap();
239 Die();
240 }
241
Evgeniy Stepanov78c56c32012-12-11 12:27:27 +0000242 const char *external_symbolizer = GetEnv("MSAN_SYMBOLIZER_PATH");
243 if (external_symbolizer && external_symbolizer[0]) {
244 CHECK(InitializeExternalSymbolizer(external_symbolizer));
245 }
246
247 GetThreadStackTopAndBottom(/* at_initialization */true,
248 &__msan_stack_bounds.stack_top,
249 &__msan_stack_bounds.stack_bottom);
250 if (flags()->verbosity)
251 Printf("MemorySanitizer init done\n");
252 msan_init_is_running = 0;
253 msan_inited = 1;
254}
255
256void __msan_set_exit_code(int exit_code) {
257 flags()->exit_code = exit_code;
258}
259
260void __msan_set_expect_umr(int expect_umr) {
261 if (expect_umr) {
262 msan_expected_umr_found = 0;
263 } else if (!msan_expected_umr_found) {
Evgeniy Stepanov78c56c32012-12-11 12:27:27 +0000264 GET_CALLER_PC_BP_SP;
265 (void)sp;
Evgeniy Stepanovdb010da2012-12-26 09:32:05 +0000266 StackTrace stack;
267 GetStackTrace(&stack, kStackTraceMax, pc, bp);
268 ReportExpectedUMRNotFound(&stack);
Evgeniy Stepanov78c56c32012-12-11 12:27:27 +0000269 Die();
270 }
271 msan_expect_umr = expect_umr;
272}
273
274void __msan_print_shadow(const void *x, uptr size) {
275 unsigned char *s = (unsigned char*)MEM_TO_SHADOW(x);
276 u32 *o = (u32*)MEM_TO_ORIGIN(x);
277 for (uptr i = 0; i < size; i++) {
278 Printf("%x%x ", s[i] >> 4, s[i] & 0xf);
279 }
280 Printf("\n");
281 if (__msan_track_origins) {
282 for (uptr i = 0; i < size / 4; i++) {
283 Printf(" o: %x ", o[i]);
284 }
285 Printf("\n");
286 }
287}
288
289void __msan_print_param_shadow() {
290 for (int i = 0; i < 16; i++) {
291 Printf("#%d:%zx ", i, __msan_param_tls[i]);
292 }
293 Printf("\n");
294}
295
296sptr __msan_test_shadow(const void *x, uptr size) {
297 unsigned char *s = (unsigned char*)MEM_TO_SHADOW((uptr)x);
298 for (uptr i = 0; i < size; ++i)
299 if (s[i])
300 return i;
301 return -1;
302}
303
304int __msan_set_poison_in_malloc(int do_poison) {
305 int old = flags()->poison_in_malloc;
306 flags()->poison_in_malloc = do_poison;
307 return old;
308}
309
Evgeniy Stepanov78c56c32012-12-11 12:27:27 +0000310int __msan_has_dynamic_component() {
311 return msan_running_under_dr;
312}
313
314NOINLINE
315void __msan_clear_on_return() {
316 __msan_param_tls[0] = 0;
317}
318
319static void* get_tls_base() {
320 u64 p;
321 asm("mov %%fs:0, %0"
322 : "=r"(p) ::);
323 return (void*)p;
324}
325
326int __msan_get_retval_tls_offset() {
327 // volatile here is needed to avoid UB, because the compiler thinks that we
328 // are doing address arithmetics on unrelated pointers, and takes some
329 // shortcuts
330 volatile sptr retval_tls_p = (sptr)&__msan_retval_tls;
331 volatile sptr tls_base_p = (sptr)get_tls_base();
332 return retval_tls_p - tls_base_p;
333}
334
335int __msan_get_param_tls_offset() {
336 // volatile here is needed to avoid UB, because the compiler thinks that we
337 // are doing address arithmetics on unrelated pointers, and takes some
338 // shortcuts
339 volatile sptr param_tls_p = (sptr)&__msan_param_tls;
340 volatile sptr tls_base_p = (sptr)get_tls_base();
341 return param_tls_p - tls_base_p;
342}
343
344void __msan_partial_poison(void* data, void* shadow, uptr size) {
345 internal_memcpy((void*)MEM_TO_SHADOW((uptr)data), shadow, size);
346}
347
348void __msan_load_unpoisoned(void *src, uptr size, void *dst) {
349 internal_memcpy(dst, src, size);
350 __msan_unpoison(dst, size);
351}
352
353void __msan_set_origin(void *a, uptr size, u32 origin) {
354 // Origin mapping is 4 bytes per 4 bytes of application memory.
355 // Here we extend the range such that its left and right bounds are both
356 // 4 byte aligned.
357 if (!__msan_track_origins) return;
358 uptr x = MEM_TO_ORIGIN((uptr)a);
359 uptr beg = x & ~3UL; // align down.
360 uptr end = (x + size + 3) & ~3UL; // align up.
361 u64 origin64 = ((u64)origin << 32) | origin;
362 // This is like memset, but the value is 32-bit. We unroll by 2 two write
363 // 64-bits at once. May want to unroll further to get 128-bit stores.
364 if (beg & 7ULL) {
365 *(u32*)beg = origin;
366 beg += 4;
367 }
368 for (uptr addr = beg; addr < (end & ~7UL); addr += 8)
369 *(u64*)addr = origin64;
370 if (end & 7ULL)
371 *(u32*)(end - 4) = origin;
372}
373
374// 'descr' is created at compile time and contains '----' in the beginning.
375// When we see descr for the first time we replace '----' with a uniq id
376// and set the origin to (id | (31-th bit)).
377void __msan_set_alloca_origin(void *a, uptr size, const char *descr) {
378 static const u32 dash = '-';
379 static const u32 first_timer =
380 dash + (dash << 8) + (dash << 16) + (dash << 24);
381 u32 *id_ptr = (u32*)descr;
382 bool print = false; // internal_strstr(descr + 4, "AllocaTOTest") != 0;
383 u32 id = *id_ptr;
384 if (id == first_timer) {
385 id = atomic_fetch_add(&NumStackOriginDescrs,
386 1, memory_order_relaxed);
387 *id_ptr = id;
388 CHECK_LT(id, kNumStackOriginDescrs);
389 StackOriginDescr[id] = descr + 4;
390 if (print)
391 Printf("First time: id=%d %s \n", id, descr + 4);
392 }
393 id |= 1U << 31;
394 if (print)
395 Printf("__msan_set_alloca_origin: descr=%s id=%x\n", descr + 4, id);
396 __msan_set_origin(a, size, id);
397}
398
399const char *__msan_get_origin_descr_if_stack(u32 id) {
400 if ((id >> 31) == 0) return 0;
401 id &= (1U << 31) - 1;
402 CHECK_LT(id, kNumStackOriginDescrs);
403 return StackOriginDescr[id];
404}
405
406
407u32 __msan_get_origin(void *a) {
408 if (!__msan_track_origins) return 0;
409 uptr x = (uptr)a;
410 uptr aligned = x & ~3ULL;
411 uptr origin_ptr = MEM_TO_ORIGIN(aligned);
412 return *(u32*)origin_ptr;
413}
414
Evgeniy Stepanov12c46932013-01-29 14:33:29 +0000415u32 __msan_get_umr_origin() {
Evgeniy Stepanov78c56c32012-12-11 12:27:27 +0000416 return __msan_origin_tls;
417}