1 //===-- msan.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 MemorySanitizer.
10 //
11 // MemorySanitizer runtime.
12 //===----------------------------------------------------------------------===//
13
14 #include "msan.h"
15
16 #include "msan_chained_origin_depot.h"
17 #include "msan_origin.h"
18 #include "msan_poisoning.h"
19 #include "msan_report.h"
20 #include "msan_thread.h"
21 #include "sanitizer_common/sanitizer_atomic.h"
22 #include "sanitizer_common/sanitizer_common.h"
23 #include "sanitizer_common/sanitizer_flag_parser.h"
24 #include "sanitizer_common/sanitizer_flags.h"
25 #include "sanitizer_common/sanitizer_interface_internal.h"
26 #include "sanitizer_common/sanitizer_libc.h"
27 #include "sanitizer_common/sanitizer_procmaps.h"
28 #include "sanitizer_common/sanitizer_stackdepot.h"
29 #include "sanitizer_common/sanitizer_stacktrace.h"
30 #include "sanitizer_common/sanitizer_symbolizer.h"
31 #include "ubsan/ubsan_flags.h"
32 #include "ubsan/ubsan_init.h"
33
34 // ACHTUNG! No system header includes in this file.
35
36 using namespace __sanitizer;
37
38 // Globals.
39 static THREADLOCAL int msan_expect_umr = 0;
40 static THREADLOCAL int msan_expected_umr_found = 0;
41
42 // Function argument shadow. Each argument starts at the next available 8-byte
43 // aligned address.
44 SANITIZER_INTERFACE_ATTRIBUTE
45 THREADLOCAL u64 __msan_param_tls[kMsanParamTlsSize / sizeof(u64)];
46
47 // Function argument origin. Each argument starts at the same offset as the
48 // corresponding shadow in (__msan_param_tls). Slightly weird, but changing this
49 // would break compatibility with older prebuilt binaries.
50 SANITIZER_INTERFACE_ATTRIBUTE
51 THREADLOCAL u32 __msan_param_origin_tls[kMsanParamTlsSize / sizeof(u32)];
52
53 SANITIZER_INTERFACE_ATTRIBUTE
54 THREADLOCAL u64 __msan_retval_tls[kMsanRetvalTlsSize / sizeof(u64)];
55
56 SANITIZER_INTERFACE_ATTRIBUTE
57 THREADLOCAL u32 __msan_retval_origin_tls;
58
59 alignas(16) SANITIZER_INTERFACE_ATTRIBUTE THREADLOCAL u64
60 __msan_va_arg_tls[kMsanParamTlsSize / sizeof(u64)];
61
62 alignas(16) SANITIZER_INTERFACE_ATTRIBUTE THREADLOCAL u32
63 __msan_va_arg_origin_tls[kMsanParamTlsSize / sizeof(u32)];
64
65 SANITIZER_INTERFACE_ATTRIBUTE
66 THREADLOCAL uptr __msan_va_arg_overflow_size_tls;
67
68 SANITIZER_INTERFACE_ATTRIBUTE
69 THREADLOCAL u32 __msan_origin_tls;
70
71 extern "C" SANITIZER_WEAK_ATTRIBUTE const int __msan_track_origins;
72
__msan_get_track_origins()73 int __msan_get_track_origins() {
74 return &__msan_track_origins ? __msan_track_origins : 0;
75 }
76
77 extern "C" SANITIZER_WEAK_ATTRIBUTE const int __msan_keep_going;
78
79 namespace __msan {
80
81 static THREADLOCAL int is_in_symbolizer_or_unwinder;
EnterSymbolizerOrUnwider()82 static void EnterSymbolizerOrUnwider() { ++is_in_symbolizer_or_unwinder; }
ExitSymbolizerOrUnwider()83 static void ExitSymbolizerOrUnwider() { --is_in_symbolizer_or_unwinder; }
IsInSymbolizerOrUnwider()84 bool IsInSymbolizerOrUnwider() { return is_in_symbolizer_or_unwinder; }
85
86 struct UnwinderScope {
UnwinderScope__msan::UnwinderScope87 UnwinderScope() { EnterSymbolizerOrUnwider(); }
~UnwinderScope__msan::UnwinderScope88 ~UnwinderScope() { ExitSymbolizerOrUnwider(); }
89 };
90
91 static Flags msan_flags;
92
flags()93 Flags *flags() { return &msan_flags; }
94
95 int msan_inited = 0;
96 bool msan_init_is_running;
97
98 int msan_report_count = 0;
99
100 // Array of stack origins.
101 // FIXME: make it resizable.
102 // Although BSS memory doesn't cost anything until used, it is limited to 2GB
103 // in some configurations (e.g., "relocation R_X86_64_PC32 out of range:
104 // ... is not in [-2147483648, 2147483647]; references section '.bss'").
105 // We use kNumStackOriginDescrs * (sizeof(char*) + sizeof(uptr)) == 64MB.
106 #if SANITIZER_PPC
107 // soft_rss_limit test (release_origin.c) fails on PPC if kNumStackOriginDescrs
108 // is too high
109 static const uptr kNumStackOriginDescrs = 1 * 1024 * 1024;
110 #else
111 static const uptr kNumStackOriginDescrs = 4 * 1024 * 1024;
112 #endif // SANITIZER_PPC
113 static const char *StackOriginDescr[kNumStackOriginDescrs];
114 static uptr StackOriginPC[kNumStackOriginDescrs];
115 static atomic_uint32_t NumStackOriginDescrs;
116
SetDefaults()117 void Flags::SetDefaults() {
118 #define MSAN_FLAG(Type, Name, DefaultValue, Description) Name = DefaultValue;
119 #include "msan_flags.inc"
120 #undef MSAN_FLAG
121 }
122
123 // keep_going is an old name for halt_on_error,
124 // and it has inverse meaning.
125 class FlagHandlerKeepGoing final : public FlagHandlerBase {
126 bool *halt_on_error_;
127
128 public:
FlagHandlerKeepGoing(bool * halt_on_error)129 explicit FlagHandlerKeepGoing(bool *halt_on_error)
130 : halt_on_error_(halt_on_error) {}
Parse(const char * value)131 bool Parse(const char *value) final {
132 bool tmp;
133 FlagHandler<bool> h(&tmp);
134 if (!h.Parse(value)) return false;
135 *halt_on_error_ = !tmp;
136 return true;
137 }
Format(char * buffer,uptr size)138 bool Format(char *buffer, uptr size) final {
139 const char *keep_going_str = (*halt_on_error_) ? "false" : "true";
140 return FormatString(buffer, size, keep_going_str);
141 }
142 };
143
RegisterMsanFlags(FlagParser * parser,Flags * f)144 static void RegisterMsanFlags(FlagParser *parser, Flags *f) {
145 #define MSAN_FLAG(Type, Name, DefaultValue, Description) \
146 RegisterFlag(parser, #Name, Description, &f->Name);
147 #include "msan_flags.inc"
148 #undef MSAN_FLAG
149
150 FlagHandlerKeepGoing *fh_keep_going = new (GetGlobalLowLevelAllocator())
151 FlagHandlerKeepGoing(&f->halt_on_error);
152 parser->RegisterHandler("keep_going", fh_keep_going,
153 "deprecated, use halt_on_error");
154 }
155
InitializeFlags()156 static void InitializeFlags() {
157 SetCommonFlagsDefaults();
158 {
159 CommonFlags cf;
160 cf.CopyFrom(*common_flags());
161 cf.external_symbolizer_path = GetEnv("MSAN_SYMBOLIZER_PATH");
162 cf.malloc_context_size = 20;
163 cf.handle_ioctl = true;
164 // FIXME: test and enable.
165 cf.check_printf = false;
166 cf.intercept_tls_get_addr = true;
167 OverrideCommonFlags(cf);
168 }
169
170 Flags *f = flags();
171 f->SetDefaults();
172
173 FlagParser parser;
174 RegisterMsanFlags(&parser, f);
175 RegisterCommonFlags(&parser);
176
177 #if MSAN_CONTAINS_UBSAN
178 __ubsan::Flags *uf = __ubsan::flags();
179 uf->SetDefaults();
180
181 FlagParser ubsan_parser;
182 __ubsan::RegisterUbsanFlags(&ubsan_parser, uf);
183 RegisterCommonFlags(&ubsan_parser);
184 #endif
185
186 // Override from user-specified string.
187 parser.ParseString(__msan_default_options());
188 #if MSAN_CONTAINS_UBSAN
189 const char *ubsan_default_options = __ubsan_default_options();
190 ubsan_parser.ParseString(ubsan_default_options);
191 #endif
192
193 parser.ParseStringFromEnv("MSAN_OPTIONS");
194 #if MSAN_CONTAINS_UBSAN
195 ubsan_parser.ParseStringFromEnv("UBSAN_OPTIONS");
196 #endif
197
198 InitializeCommonFlags();
199
200 if (Verbosity()) ReportUnrecognizedFlags();
201
202 if (common_flags()->help) parser.PrintFlagDescriptions();
203
204 // Check if deprecated exit_code MSan flag is set.
205 if (f->exit_code != -1) {
206 if (Verbosity())
207 Printf("MSAN_OPTIONS=exit_code is deprecated! "
208 "Please use MSAN_OPTIONS=exitcode instead.\n");
209 CommonFlags cf;
210 cf.CopyFrom(*common_flags());
211 cf.exitcode = f->exit_code;
212 OverrideCommonFlags(cf);
213 }
214
215 // Check flag values:
216 if (f->origin_history_size < 0 ||
217 f->origin_history_size > Origin::kMaxDepth) {
218 Printf(
219 "Origin history size invalid: %d. Must be 0 (unlimited) or in [1, %d] "
220 "range.\n",
221 f->origin_history_size, Origin::kMaxDepth);
222 Die();
223 }
224 // Limiting to kStackDepotMaxUseCount / 2 to avoid overflow in
225 // StackDepotHandle::inc_use_count_unsafe.
226 if (f->origin_history_per_stack_limit < 0 ||
227 f->origin_history_per_stack_limit > kStackDepotMaxUseCount / 2) {
228 Printf(
229 "Origin per-stack limit invalid: %d. Must be 0 (unlimited) or in [1, "
230 "%d] range.\n",
231 f->origin_history_per_stack_limit, kStackDepotMaxUseCount / 2);
232 Die();
233 }
234 if (f->store_context_size < 1) f->store_context_size = 1;
235 }
236
PrintWarningWithOrigin(uptr pc,uptr bp,u32 origin)237 void PrintWarningWithOrigin(uptr pc, uptr bp, u32 origin) {
238 if (msan_expect_umr) {
239 // Printf("Expected UMR\n");
240 __msan_origin_tls = origin;
241 msan_expected_umr_found = 1;
242 return;
243 }
244
245 ++msan_report_count;
246
247 GET_FATAL_STACK_TRACE_PC_BP(pc, bp);
248
249 u32 report_origin =
250 (__msan_get_track_origins() && Origin::isValidId(origin)) ? origin : 0;
251 ReportUMR(&stack, report_origin);
252
253 if (__msan_get_track_origins() && !Origin::isValidId(origin)) {
254 Printf(
255 " ORIGIN: invalid (%x). Might be a bug in MemorySanitizer origin "
256 "tracking.\n This could still be a bug in your code, too!\n",
257 origin);
258 }
259 }
260
UnpoisonParam(uptr n)261 void UnpoisonParam(uptr n) {
262 internal_memset(__msan_param_tls, 0, n * sizeof(*__msan_param_tls));
263 }
264
265 // Backup MSan runtime TLS state.
266 // Implementation must be async-signal-safe.
267 // Instances of this class may live on the signal handler stack, and data size
268 // may be an issue.
Backup()269 void ScopedThreadLocalStateBackup::Backup() {
270 va_arg_overflow_size_tls = __msan_va_arg_overflow_size_tls;
271 }
272
Restore()273 void ScopedThreadLocalStateBackup::Restore() {
274 // A lame implementation that only keeps essential state and resets the rest.
275 __msan_va_arg_overflow_size_tls = va_arg_overflow_size_tls;
276
277 internal_memset(__msan_param_tls, 0, sizeof(__msan_param_tls));
278 internal_memset(__msan_retval_tls, 0, sizeof(__msan_retval_tls));
279 internal_memset(__msan_va_arg_tls, 0, sizeof(__msan_va_arg_tls));
280 internal_memset(__msan_va_arg_origin_tls, 0,
281 sizeof(__msan_va_arg_origin_tls));
282
283 if (__msan_get_track_origins()) {
284 internal_memset(&__msan_retval_origin_tls, 0,
285 sizeof(__msan_retval_origin_tls));
286 internal_memset(__msan_param_origin_tls, 0,
287 sizeof(__msan_param_origin_tls));
288 }
289 }
290
UnpoisonThreadLocalState()291 void UnpoisonThreadLocalState() {
292 }
293
GetStackOriginDescr(u32 id,uptr * pc)294 const char *GetStackOriginDescr(u32 id, uptr *pc) {
295 CHECK_LT(id, kNumStackOriginDescrs);
296 if (pc) *pc = StackOriginPC[id];
297 return StackOriginDescr[id];
298 }
299
ChainOrigin(u32 id,StackTrace * stack)300 u32 ChainOrigin(u32 id, StackTrace *stack) {
301 MsanThread *t = GetCurrentThread();
302 if (t && t->InSignalHandler())
303 return id;
304
305 Origin o = Origin::FromRawId(id);
306 stack->tag = StackTrace::TAG_UNKNOWN;
307 Origin chained = Origin::CreateChainedOrigin(o, stack);
308 return chained.raw_id();
309 }
310
311 // Current implementation separates the 'id_ptr' from the 'descr' and makes
312 // 'descr' constant.
313 // Previous implementation 'descr' is created at compile time and contains
314 // '----' in the beginning. When we see descr for the first time we replace
315 // '----' with a uniq id and set the origin to (id | (31-th bit)).
SetAllocaOrigin(void * a,uptr size,u32 * id_ptr,char * descr,uptr pc)316 static inline void SetAllocaOrigin(void *a, uptr size, u32 *id_ptr, char *descr,
317 uptr pc) {
318 static const u32 dash = '-';
319 static const u32 first_timer =
320 dash + (dash << 8) + (dash << 16) + (dash << 24);
321 u32 id = *id_ptr;
322 if (id == 0 || id == first_timer) {
323 u32 idx = atomic_fetch_add(&NumStackOriginDescrs, 1, memory_order_relaxed);
324 CHECK_LT(idx, kNumStackOriginDescrs);
325 StackOriginDescr[idx] = descr;
326 StackOriginPC[idx] = pc;
327 id = Origin::CreateStackOrigin(idx).raw_id();
328 *id_ptr = id;
329 }
330 __msan_set_origin(a, size, id);
331 }
332
333 } // namespace __msan
334
UnwindImpl(uptr pc,uptr bp,void * context,bool request_fast,u32 max_depth)335 void __sanitizer::BufferedStackTrace::UnwindImpl(
336 uptr pc, uptr bp, void *context, bool request_fast, u32 max_depth) {
337 using namespace __msan;
338 MsanThread *t = GetCurrentThread();
339 if (!t || !StackTrace::WillUseFastUnwind(request_fast)) {
340 // Block reports from our interceptors during _Unwind_Backtrace.
341 UnwinderScope sym_scope;
342 return Unwind(max_depth, pc, bp, context, t ? t->stack_top() : 0,
343 t ? t->stack_bottom() : 0, false);
344 }
345 if (StackTrace::WillUseFastUnwind(request_fast))
346 Unwind(max_depth, pc, bp, nullptr, t->stack_top(), t->stack_bottom(), true);
347 else
348 Unwind(max_depth, pc, 0, context, 0, 0, false);
349 }
350
351 // Interface.
352
353 using namespace __msan;
354
355 // N.B. Only [shadow, shadow+size) is defined. shadow is *not* a pointer into
356 // an MSan shadow region.
print_shadow_value(void * shadow,u64 size)357 static void print_shadow_value(void *shadow, u64 size) {
358 Printf("Shadow value (%llu byte%s):", size, size == 1 ? "" : "s");
359 for (unsigned int i = 0; i < size; i++) {
360 if (i % 4 == 0)
361 Printf(" ");
362
363 unsigned char x = ((unsigned char *)shadow)[i];
364 Printf("%x%x", x >> 4, x & 0xf);
365 }
366 Printf("\n");
367 Printf(
368 "Caveat: the shadow value does not necessarily directly correspond to a "
369 "single user variable. The correspondence is stronger, but not always "
370 "perfect, when origin tracking is enabled.\n");
371 Printf("\n");
372 }
373
374 #define MSAN_MAYBE_WARNING(type, size) \
375 void __msan_maybe_warning_##size(type s, u32 o) { \
376 GET_CALLER_PC_BP; \
377 \
378 if (UNLIKELY(s)) { \
379 if (Verbosity() >= 1) \
380 print_shadow_value((void *)(&s), sizeof(s)); \
381 PrintWarningWithOrigin(pc, bp, o); \
382 if (__msan::flags()->halt_on_error) { \
383 Printf("Exiting\n"); \
384 Die(); \
385 } \
386 } \
387 }
388
389 MSAN_MAYBE_WARNING(u8, 1)
390 MSAN_MAYBE_WARNING(u16, 2)
391 MSAN_MAYBE_WARNING(u32, 4)
392 MSAN_MAYBE_WARNING(u64, 8)
393
394 // N.B. Only [shadow, shadow+size) is defined. shadow is *not* a pointer into
395 // an MSan shadow region.
__msan_maybe_warning_N(void * shadow,u64 size,u32 o)396 void __msan_maybe_warning_N(void *shadow, u64 size, u32 o) {
397 GET_CALLER_PC_BP;
398
399 bool allZero = true;
400 for (unsigned int i = 0; i < size; i++) {
401 if (((char *)shadow)[i]) {
402 allZero = false;
403 break;
404 }
405 }
406
407 if (UNLIKELY(!allZero)) {
408 if (Verbosity() >= 1)
409 print_shadow_value(shadow, size);
410 PrintWarningWithOrigin(pc, bp, o);
411 if (__msan::flags()->halt_on_error) {
412 Printf("Exiting\n");
413 Die();
414 }
415 }
416 }
417
418 #define MSAN_MAYBE_STORE_ORIGIN(type, size) \
419 void __msan_maybe_store_origin_##size(type s, void *p, u32 o) { \
420 if (UNLIKELY(s)) { \
421 if (__msan_get_track_origins() > 1) { \
422 GET_CALLER_PC_BP; \
423 GET_STORE_STACK_TRACE_PC_BP(pc, bp); \
424 o = ChainOrigin(o, &stack); \
425 } \
426 *(u32 *)MEM_TO_ORIGIN((uptr)p & ~3UL) = o; \
427 } \
428 }
429
430 MSAN_MAYBE_STORE_ORIGIN(u8, 1)
431 MSAN_MAYBE_STORE_ORIGIN(u16, 2)
432 MSAN_MAYBE_STORE_ORIGIN(u32, 4)
433 MSAN_MAYBE_STORE_ORIGIN(u64, 8)
434
__msan_warning()435 void __msan_warning() {
436 GET_CALLER_PC_BP;
437 PrintWarningWithOrigin(pc, bp, 0);
438 if (__msan::flags()->halt_on_error) {
439 if (__msan::flags()->print_stats)
440 ReportStats();
441 Printf("Exiting\n");
442 Die();
443 }
444 }
445
__msan_warning_noreturn()446 void __msan_warning_noreturn() {
447 GET_CALLER_PC_BP;
448 PrintWarningWithOrigin(pc, bp, 0);
449 if (__msan::flags()->print_stats)
450 ReportStats();
451 Printf("Exiting\n");
452 Die();
453 }
454
__msan_warning_with_origin(u32 origin)455 void __msan_warning_with_origin(u32 origin) {
456 GET_CALLER_PC_BP;
457 PrintWarningWithOrigin(pc, bp, origin);
458 if (__msan::flags()->halt_on_error) {
459 if (__msan::flags()->print_stats)
460 ReportStats();
461 Printf("Exiting\n");
462 Die();
463 }
464 }
465
__msan_warning_with_origin_noreturn(u32 origin)466 void __msan_warning_with_origin_noreturn(u32 origin) {
467 GET_CALLER_PC_BP;
468 PrintWarningWithOrigin(pc, bp, origin);
469 if (__msan::flags()->print_stats)
470 ReportStats();
471 Printf("Exiting\n");
472 Die();
473 }
474
OnStackUnwind(const SignalContext & sig,const void *,BufferedStackTrace * stack)475 static void OnStackUnwind(const SignalContext &sig, const void *,
476 BufferedStackTrace *stack) {
477 stack->Unwind(StackTrace::GetNextInstructionPc(sig.pc), sig.bp, sig.context,
478 common_flags()->fast_unwind_on_fatal);
479 }
480
MsanOnDeadlySignal(int signo,void * siginfo,void * context)481 static void MsanOnDeadlySignal(int signo, void *siginfo, void *context) {
482 HandleDeadlySignal(siginfo, context, GetTid(), &OnStackUnwind, nullptr);
483 }
484
CheckUnwind()485 static void CheckUnwind() {
486 GET_FATAL_STACK_TRACE_PC_BP(StackTrace::GetCurrentPc(), GET_CURRENT_FRAME());
487 stack.Print();
488 }
489
__msan_init()490 void __msan_init() {
491 CHECK(!msan_init_is_running);
492 if (msan_inited) return;
493 msan_init_is_running = 1;
494 SanitizerToolName = "MemorySanitizer";
495
496 AvoidCVE_2016_2143();
497
498 CacheBinaryName();
499 InitializeFlags();
500
501 // Install tool-specific callbacks in sanitizer_common.
502 SetCheckUnwindCallback(CheckUnwind);
503
504 __sanitizer_set_report_path(common_flags()->log_path);
505
506 InitializePlatformEarly();
507
508 InitializeInterceptors();
509 InstallAtForkHandler();
510 CheckASLR();
511 InstallDeadlySignalHandlers(MsanOnDeadlySignal);
512 InstallAtExitHandler(); // Needs __cxa_atexit interceptor.
513
514 DisableCoreDumperIfNecessary();
515 if (StackSizeIsUnlimited()) {
516 VPrintf(1, "Unlimited stack, doing reexec\n");
517 // A reasonably large stack size. It is bigger than the usual 8Mb, because,
518 // well, the program could have been run with unlimited stack for a reason.
519 SetStackSizeLimitInBytes(32 * 1024 * 1024);
520 ReExec();
521 }
522
523 __msan_clear_on_return();
524 if (__msan_get_track_origins())
525 VPrintf(1, "msan_track_origins\n");
526 if (!InitShadowWithReExec(__msan_get_track_origins())) {
527 Printf("FATAL: MemorySanitizer can not mmap the shadow memory.\n");
528 Printf("FATAL: Make sure to compile with -fPIE and to link with -pie.\n");
529 Printf("FATAL: Disabling ASLR is known to cause this error.\n");
530 Printf("FATAL: If running under GDB, try "
531 "'set disable-randomization off'.\n");
532 DumpProcessMap();
533 Die();
534 }
535
536 Symbolizer::GetOrInit()->AddHooks(EnterSymbolizerOrUnwider,
537 ExitSymbolizerOrUnwider);
538
539 InitializeCoverage(common_flags()->coverage, common_flags()->coverage_dir);
540
541 MsanTSDInit(MsanTSDDtor);
542
543 MsanAllocatorInit();
544
545 MsanThread *main_thread = MsanThread::Create(nullptr, nullptr);
546 SetCurrentThread(main_thread);
547 main_thread->Init();
548
549 #if MSAN_CONTAINS_UBSAN
550 __ubsan::InitAsPlugin();
551 #endif
552
553 VPrintf(1, "MemorySanitizer init done\n");
554
555 msan_init_is_running = 0;
556 msan_inited = 1;
557 }
558
__msan_set_keep_going(int keep_going)559 void __msan_set_keep_going(int keep_going) {
560 flags()->halt_on_error = !keep_going;
561 }
562
__msan_set_expect_umr(int expect_umr)563 void __msan_set_expect_umr(int expect_umr) {
564 if (expect_umr) {
565 msan_expected_umr_found = 0;
566 } else if (!msan_expected_umr_found) {
567 GET_CALLER_PC_BP;
568 GET_FATAL_STACK_TRACE_PC_BP(pc, bp);
569 ReportExpectedUMRNotFound(&stack);
570 Die();
571 }
572 msan_expect_umr = expect_umr;
573 }
574
__msan_print_shadow(const void * x,uptr size)575 void __msan_print_shadow(const void *x, uptr size) {
576 if (!MEM_IS_APP(x)) {
577 Printf("Not a valid application address: %p\n", x);
578 return;
579 }
580
581 DescribeMemoryRange(x, size);
582 }
583
__msan_dump_shadow(const void * x,uptr size)584 void __msan_dump_shadow(const void *x, uptr size) {
585 if (!MEM_IS_APP(x)) {
586 Printf("Not a valid application address: %p\n", x);
587 return;
588 }
589
590 unsigned char *s = (unsigned char*)MEM_TO_SHADOW(x);
591 Printf("%p[%p] ", (void *)s, x);
592 for (uptr i = 0; i < size; i++)
593 Printf("%x%x ", s[i] >> 4, s[i] & 0xf);
594 Printf("\n");
595 }
596
__msan_test_shadow(const void * x,uptr size)597 sptr __msan_test_shadow(const void *x, uptr size) {
598 if (!MEM_IS_APP(x)) return -1;
599 unsigned char *s = (unsigned char *)MEM_TO_SHADOW((uptr)x);
600 if (__sanitizer::mem_is_zero((const char *)s, size))
601 return -1;
602 // Slow path: loop through again to find the location.
603 for (uptr i = 0; i < size; ++i)
604 if (s[i])
605 return i;
606 return -1;
607 }
608
__msan_check_mem_is_initialized(const void * x,uptr size)609 void __msan_check_mem_is_initialized(const void *x, uptr size) {
610 if (!__msan::flags()->report_umrs) return;
611 sptr offset = __msan_test_shadow(x, size);
612 if (offset < 0)
613 return;
614
615 GET_CALLER_PC_BP;
616 ReportUMRInsideAddressRange(__func__, x, size, offset);
617 __msan::PrintWarningWithOrigin(pc, bp,
618 __msan_get_origin(((const char *)x) + offset));
619 if (__msan::flags()->halt_on_error) {
620 Printf("Exiting\n");
621 Die();
622 }
623 }
624
__msan_set_poison_in_malloc(int do_poison)625 int __msan_set_poison_in_malloc(int do_poison) {
626 int old = flags()->poison_in_malloc;
627 flags()->poison_in_malloc = do_poison;
628 return old;
629 }
630
__msan_has_dynamic_component()631 int __msan_has_dynamic_component() { return false; }
632
633 NOINLINE
__msan_clear_on_return()634 void __msan_clear_on_return() {
635 __msan_param_tls[0] = 0;
636 }
637
__msan_partial_poison(const void * data,void * shadow,uptr size)638 void __msan_partial_poison(const void* data, void* shadow, uptr size) {
639 internal_memcpy((void*)MEM_TO_SHADOW((uptr)data), shadow, size);
640 }
641
__msan_load_unpoisoned(const void * src,uptr size,void * dst)642 void __msan_load_unpoisoned(const void *src, uptr size, void *dst) {
643 internal_memcpy(dst, src, size);
644 __msan_unpoison(dst, size);
645 }
646
__msan_set_origin(const void * a,uptr size,u32 origin)647 void __msan_set_origin(const void *a, uptr size, u32 origin) {
648 if (__msan_get_track_origins()) SetOrigin(a, size, origin);
649 }
650
__msan_set_alloca_origin(void * a,uptr size,char * descr)651 void __msan_set_alloca_origin(void *a, uptr size, char *descr) {
652 SetAllocaOrigin(a, size, reinterpret_cast<u32 *>(descr), descr + 4,
653 GET_CALLER_PC());
654 }
655
__msan_set_alloca_origin4(void * a,uptr size,char * descr,uptr pc)656 void __msan_set_alloca_origin4(void *a, uptr size, char *descr, uptr pc) {
657 // Intentionally ignore pc and use return address. This function is here for
658 // compatibility, in case program is linked with library instrumented by
659 // older clang.
660 SetAllocaOrigin(a, size, reinterpret_cast<u32 *>(descr), descr + 4,
661 GET_CALLER_PC());
662 }
663
__msan_set_alloca_origin_with_descr(void * a,uptr size,u32 * id_ptr,char * descr)664 void __msan_set_alloca_origin_with_descr(void *a, uptr size, u32 *id_ptr,
665 char *descr) {
666 SetAllocaOrigin(a, size, id_ptr, descr, GET_CALLER_PC());
667 }
668
__msan_set_alloca_origin_no_descr(void * a,uptr size,u32 * id_ptr)669 void __msan_set_alloca_origin_no_descr(void *a, uptr size, u32 *id_ptr) {
670 SetAllocaOrigin(a, size, id_ptr, nullptr, GET_CALLER_PC());
671 }
672
__msan_chain_origin(u32 id)673 u32 __msan_chain_origin(u32 id) {
674 GET_CALLER_PC_BP;
675 GET_STORE_STACK_TRACE_PC_BP(pc, bp);
676 return ChainOrigin(id, &stack);
677 }
678
__msan_get_origin(const void * a)679 u32 __msan_get_origin(const void *a) {
680 if (!__msan_get_track_origins()) return 0;
681 uptr x = (uptr)a;
682 uptr aligned = x & ~3ULL;
683 uptr origin_ptr = MEM_TO_ORIGIN(aligned);
684 return *(u32*)origin_ptr;
685 }
686
__msan_origin_is_descendant_or_same(u32 this_id,u32 prev_id)687 int __msan_origin_is_descendant_or_same(u32 this_id, u32 prev_id) {
688 Origin o = Origin::FromRawId(this_id);
689 while (o.raw_id() != prev_id && o.isChainedOrigin())
690 o = o.getNextChainedOrigin(nullptr);
691 return o.raw_id() == prev_id;
692 }
693
__msan_get_umr_origin()694 u32 __msan_get_umr_origin() {
695 return __msan_origin_tls;
696 }
697
__sanitizer_unaligned_load16(const uu16 * p)698 u16 __sanitizer_unaligned_load16(const uu16 *p) {
699 internal_memcpy(&__msan_retval_tls[0], (void *)MEM_TO_SHADOW((uptr)p),
700 sizeof(uu16));
701 if (__msan_get_track_origins())
702 __msan_retval_origin_tls = GetOriginIfPoisoned((uptr)p, sizeof(*p));
703 return *p;
704 }
__sanitizer_unaligned_load32(const uu32 * p)705 u32 __sanitizer_unaligned_load32(const uu32 *p) {
706 internal_memcpy(&__msan_retval_tls[0], (void *)MEM_TO_SHADOW((uptr)p),
707 sizeof(uu32));
708 if (__msan_get_track_origins())
709 __msan_retval_origin_tls = GetOriginIfPoisoned((uptr)p, sizeof(*p));
710 return *p;
711 }
__sanitizer_unaligned_load64(const uu64 * p)712 u64 __sanitizer_unaligned_load64(const uu64 *p) {
713 internal_memcpy(&__msan_retval_tls[0], (void *)MEM_TO_SHADOW((uptr)p),
714 sizeof(uu64));
715 if (__msan_get_track_origins())
716 __msan_retval_origin_tls = GetOriginIfPoisoned((uptr)p, sizeof(*p));
717 return *p;
718 }
__sanitizer_unaligned_store16(uu16 * p,u16 x)719 void __sanitizer_unaligned_store16(uu16 *p, u16 x) {
720 static_assert(sizeof(uu16) == sizeof(u16), "incompatible types");
721 u16 s;
722 internal_memcpy(&s, &__msan_param_tls[1], sizeof(uu16));
723 internal_memcpy((void *)MEM_TO_SHADOW((uptr)p), &s, sizeof(uu16));
724 if (s && __msan_get_track_origins())
725 if (uu32 o = __msan_param_origin_tls[2])
726 SetOriginIfPoisoned((uptr)p, (uptr)&s, sizeof(s), o);
727 *p = x;
728 }
__sanitizer_unaligned_store32(uu32 * p,u32 x)729 void __sanitizer_unaligned_store32(uu32 *p, u32 x) {
730 static_assert(sizeof(uu32) == sizeof(u32), "incompatible types");
731 u32 s;
732 internal_memcpy(&s, &__msan_param_tls[1], sizeof(uu32));
733 internal_memcpy((void *)MEM_TO_SHADOW((uptr)p), &s, sizeof(uu32));
734 if (s && __msan_get_track_origins())
735 if (uu32 o = __msan_param_origin_tls[2])
736 SetOriginIfPoisoned((uptr)p, (uptr)&s, sizeof(s), o);
737 *p = x;
738 }
__sanitizer_unaligned_store64(uu64 * p,u64 x)739 void __sanitizer_unaligned_store64(uu64 *p, u64 x) {
740 u64 s = __msan_param_tls[1];
741 *(uu64 *)MEM_TO_SHADOW((uptr)p) = s;
742 if (s && __msan_get_track_origins())
743 if (uu32 o = __msan_param_origin_tls[2])
744 SetOriginIfPoisoned((uptr)p, (uptr)&s, sizeof(s), o);
745 *p = x;
746 }
747
__msan_set_death_callback(void (* callback)(void))748 void __msan_set_death_callback(void (*callback)(void)) {
749 SetUserDieCallback(callback);
750 }
751
__msan_start_switch_fiber(const void * bottom,uptr size)752 void __msan_start_switch_fiber(const void *bottom, uptr size) {
753 MsanThread *t = GetCurrentThread();
754 if (!t) {
755 VReport(1, "__msan_start_switch_fiber called from unknown thread\n");
756 return;
757 }
758 t->StartSwitchFiber((uptr)bottom, size);
759 }
760
__msan_finish_switch_fiber(const void ** bottom_old,uptr * size_old)761 void __msan_finish_switch_fiber(const void **bottom_old, uptr *size_old) {
762 MsanThread *t = GetCurrentThread();
763 if (!t) {
764 VReport(1, "__msan_finish_switch_fiber called from unknown thread\n");
765 return;
766 }
767 t->FinishSwitchFiber((uptr *)bottom_old, (uptr *)size_old);
768
769 internal_memset(__msan_param_tls, 0, sizeof(__msan_param_tls));
770 internal_memset(__msan_retval_tls, 0, sizeof(__msan_retval_tls));
771 internal_memset(__msan_va_arg_tls, 0, sizeof(__msan_va_arg_tls));
772
773 if (__msan_get_track_origins()) {
774 internal_memset(__msan_param_origin_tls, 0,
775 sizeof(__msan_param_origin_tls));
776 internal_memset(&__msan_retval_origin_tls, 0,
777 sizeof(__msan_retval_origin_tls));
778 internal_memset(__msan_va_arg_origin_tls, 0,
779 sizeof(__msan_va_arg_origin_tls));
780 }
781 }
782
SANITIZER_INTERFACE_WEAK_DEF(const char *,__msan_default_options,void)783 SANITIZER_INTERFACE_WEAK_DEF(const char *, __msan_default_options, void) {
784 return "";
785 }
786
787 extern "C" {
788 SANITIZER_INTERFACE_ATTRIBUTE
__sanitizer_print_stack_trace()789 void __sanitizer_print_stack_trace() {
790 GET_FATAL_STACK_TRACE_PC_BP(StackTrace::GetCurrentPc(), GET_CURRENT_FRAME());
791 stack.Print();
792 }
793 } // extern "C"
794