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