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