xref: /llvm-project/compiler-rt/lib/msan/msan.cpp (revision a0bb2e21c10bebcdb6bc6b8bc18f74dcf7c4b8b2)
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 u64 __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 
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;
82 static void EnterSymbolizerOrUnwider() { ++is_in_symbolizer_or_unwinder; }
83 static void ExitSymbolizerOrUnwider() { --is_in_symbolizer_or_unwinder; }
84 bool IsInSymbolizerOrUnwider() { return is_in_symbolizer_or_unwinder; }
85 
86 struct UnwinderScope {
87   UnwinderScope() { EnterSymbolizerOrUnwider(); }
88   ~UnwinderScope() { ExitSymbolizerOrUnwider(); }
89 };
90 
91 static Flags msan_flags;
92 
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 
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:
129   explicit FlagHandlerKeepGoing(bool *halt_on_error)
130       : halt_on_error_(halt_on_error) {}
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   }
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 
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 
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 
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 
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.
269 void ScopedThreadLocalStateBackup::Backup() {
270   va_arg_overflow_size_tls = __msan_va_arg_overflow_size_tls;
271 }
272 
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 
291 void UnpoisonThreadLocalState() {
292 }
293 
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 
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)).
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 
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 #define MSAN_MAYBE_WARNING(type, size)              \
356   void __msan_maybe_warning_##size(type s, u32 o) { \
357     GET_CALLER_PC_BP;                               \
358     if (UNLIKELY(s)) {                              \
359       PrintWarningWithOrigin(pc, bp, o);            \
360       if (__msan::flags()->halt_on_error) {         \
361         Printf("Exiting\n");                        \
362         Die();                                      \
363       }                                             \
364     }                                               \
365   }
366 
367 MSAN_MAYBE_WARNING(u8, 1)
368 MSAN_MAYBE_WARNING(u16, 2)
369 MSAN_MAYBE_WARNING(u32, 4)
370 MSAN_MAYBE_WARNING(u64, 8)
371 
372 #define MSAN_MAYBE_STORE_ORIGIN(type, size)                       \
373   void __msan_maybe_store_origin_##size(type s, void *p, u32 o) { \
374     if (UNLIKELY(s)) {                                            \
375       if (__msan_get_track_origins() > 1) {                       \
376         GET_CALLER_PC_BP;                                         \
377         GET_STORE_STACK_TRACE_PC_BP(pc, bp);                      \
378         o = ChainOrigin(o, &stack);                               \
379       }                                                           \
380       *(u32 *)MEM_TO_ORIGIN((uptr)p & ~3UL) = o;                  \
381     }                                                             \
382   }
383 
384 MSAN_MAYBE_STORE_ORIGIN(u8, 1)
385 MSAN_MAYBE_STORE_ORIGIN(u16, 2)
386 MSAN_MAYBE_STORE_ORIGIN(u32, 4)
387 MSAN_MAYBE_STORE_ORIGIN(u64, 8)
388 
389 void __msan_warning() {
390   GET_CALLER_PC_BP;
391   PrintWarningWithOrigin(pc, bp, 0);
392   if (__msan::flags()->halt_on_error) {
393     if (__msan::flags()->print_stats)
394       ReportStats();
395     Printf("Exiting\n");
396     Die();
397   }
398 }
399 
400 void __msan_warning_noreturn() {
401   GET_CALLER_PC_BP;
402   PrintWarningWithOrigin(pc, bp, 0);
403   if (__msan::flags()->print_stats)
404     ReportStats();
405   Printf("Exiting\n");
406   Die();
407 }
408 
409 void __msan_warning_with_origin(u32 origin) {
410   GET_CALLER_PC_BP;
411   PrintWarningWithOrigin(pc, bp, origin);
412   if (__msan::flags()->halt_on_error) {
413     if (__msan::flags()->print_stats)
414       ReportStats();
415     Printf("Exiting\n");
416     Die();
417   }
418 }
419 
420 void __msan_warning_with_origin_noreturn(u32 origin) {
421   GET_CALLER_PC_BP;
422   PrintWarningWithOrigin(pc, bp, origin);
423   if (__msan::flags()->print_stats)
424     ReportStats();
425   Printf("Exiting\n");
426   Die();
427 }
428 
429 static void OnStackUnwind(const SignalContext &sig, const void *,
430                           BufferedStackTrace *stack) {
431   stack->Unwind(StackTrace::GetNextInstructionPc(sig.pc), sig.bp, sig.context,
432                 common_flags()->fast_unwind_on_fatal);
433 }
434 
435 static void MsanOnDeadlySignal(int signo, void *siginfo, void *context) {
436   HandleDeadlySignal(siginfo, context, GetTid(), &OnStackUnwind, nullptr);
437 }
438 
439 static void CheckUnwind() {
440   GET_FATAL_STACK_TRACE_PC_BP(StackTrace::GetCurrentPc(), GET_CURRENT_FRAME());
441   stack.Print();
442 }
443 
444 void __msan_init() {
445   CHECK(!msan_init_is_running);
446   if (msan_inited) return;
447   msan_init_is_running = 1;
448   SanitizerToolName = "MemorySanitizer";
449 
450   AvoidCVE_2016_2143();
451 
452   CacheBinaryName();
453   InitializeFlags();
454 
455   // Install tool-specific callbacks in sanitizer_common.
456   SetCheckUnwindCallback(CheckUnwind);
457 
458   __sanitizer_set_report_path(common_flags()->log_path);
459 
460   InitializePlatformEarly();
461 
462   InitializeInterceptors();
463   InstallAtForkHandler();
464   CheckASLR();
465   InstallDeadlySignalHandlers(MsanOnDeadlySignal);
466   InstallAtExitHandler(); // Needs __cxa_atexit interceptor.
467 
468   DisableCoreDumperIfNecessary();
469   if (StackSizeIsUnlimited()) {
470     VPrintf(1, "Unlimited stack, doing reexec\n");
471     // A reasonably large stack size. It is bigger than the usual 8Mb, because,
472     // well, the program could have been run with unlimited stack for a reason.
473     SetStackSizeLimitInBytes(32 * 1024 * 1024);
474     ReExec();
475   }
476 
477   __msan_clear_on_return();
478   if (__msan_get_track_origins())
479     VPrintf(1, "msan_track_origins\n");
480   if (!InitShadowWithReExec(__msan_get_track_origins())) {
481     Printf("FATAL: MemorySanitizer can not mmap the shadow memory.\n");
482     Printf("FATAL: Make sure to compile with -fPIE and to link with -pie.\n");
483     Printf("FATAL: Disabling ASLR is known to cause this error.\n");
484     Printf("FATAL: If running under GDB, try "
485            "'set disable-randomization off'.\n");
486     DumpProcessMap();
487     Die();
488   }
489 
490   Symbolizer::GetOrInit()->AddHooks(EnterSymbolizerOrUnwider,
491                                     ExitSymbolizerOrUnwider);
492 
493   InitializeCoverage(common_flags()->coverage, common_flags()->coverage_dir);
494 
495   MsanTSDInit(MsanTSDDtor);
496 
497   MsanAllocatorInit();
498 
499   MsanThread *main_thread = MsanThread::Create(nullptr, nullptr);
500   SetCurrentThread(main_thread);
501   main_thread->Init();
502 
503 #if MSAN_CONTAINS_UBSAN
504   __ubsan::InitAsPlugin();
505 #endif
506 
507   VPrintf(1, "MemorySanitizer init done\n");
508 
509   msan_init_is_running = 0;
510   msan_inited = 1;
511 }
512 
513 void __msan_set_keep_going(int keep_going) {
514   flags()->halt_on_error = !keep_going;
515 }
516 
517 void __msan_set_expect_umr(int expect_umr) {
518   if (expect_umr) {
519     msan_expected_umr_found = 0;
520   } else if (!msan_expected_umr_found) {
521     GET_CALLER_PC_BP;
522     GET_FATAL_STACK_TRACE_PC_BP(pc, bp);
523     ReportExpectedUMRNotFound(&stack);
524     Die();
525   }
526   msan_expect_umr = expect_umr;
527 }
528 
529 void __msan_print_shadow(const void *x, uptr size) {
530   if (!MEM_IS_APP(x)) {
531     Printf("Not a valid application address: %p\n", x);
532     return;
533   }
534 
535   DescribeMemoryRange(x, size);
536 }
537 
538 void __msan_dump_shadow(const void *x, uptr size) {
539   if (!MEM_IS_APP(x)) {
540     Printf("Not a valid application address: %p\n", x);
541     return;
542   }
543 
544   unsigned char *s = (unsigned char*)MEM_TO_SHADOW(x);
545   Printf("%p[%p]  ", (void *)s, x);
546   for (uptr i = 0; i < size; i++)
547     Printf("%x%x ", s[i] >> 4, s[i] & 0xf);
548   Printf("\n");
549 }
550 
551 sptr __msan_test_shadow(const void *x, uptr size) {
552   if (!MEM_IS_APP(x)) return -1;
553   unsigned char *s = (unsigned char *)MEM_TO_SHADOW((uptr)x);
554   if (__sanitizer::mem_is_zero((const char *)s, size))
555     return -1;
556   // Slow path: loop through again to find the location.
557   for (uptr i = 0; i < size; ++i)
558     if (s[i])
559       return i;
560   return -1;
561 }
562 
563 void __msan_check_mem_is_initialized(const void *x, uptr size) {
564   if (!__msan::flags()->report_umrs) return;
565   sptr offset = __msan_test_shadow(x, size);
566   if (offset < 0)
567     return;
568 
569   GET_CALLER_PC_BP;
570   ReportUMRInsideAddressRange(__func__, x, size, offset);
571   __msan::PrintWarningWithOrigin(pc, bp,
572                                  __msan_get_origin(((const char *)x) + offset));
573   if (__msan::flags()->halt_on_error) {
574     Printf("Exiting\n");
575     Die();
576   }
577 }
578 
579 int __msan_set_poison_in_malloc(int do_poison) {
580   int old = flags()->poison_in_malloc;
581   flags()->poison_in_malloc = do_poison;
582   return old;
583 }
584 
585 int __msan_has_dynamic_component() { return false; }
586 
587 NOINLINE
588 void __msan_clear_on_return() {
589   __msan_param_tls[0] = 0;
590 }
591 
592 void __msan_partial_poison(const void* data, void* shadow, uptr size) {
593   internal_memcpy((void*)MEM_TO_SHADOW((uptr)data), shadow, size);
594 }
595 
596 void __msan_load_unpoisoned(const void *src, uptr size, void *dst) {
597   internal_memcpy(dst, src, size);
598   __msan_unpoison(dst, size);
599 }
600 
601 void __msan_set_origin(const void *a, uptr size, u32 origin) {
602   if (__msan_get_track_origins()) SetOrigin(a, size, origin);
603 }
604 
605 void __msan_set_alloca_origin(void *a, uptr size, char *descr) {
606   SetAllocaOrigin(a, size, reinterpret_cast<u32 *>(descr), descr + 4,
607                   GET_CALLER_PC());
608 }
609 
610 void __msan_set_alloca_origin4(void *a, uptr size, char *descr, uptr pc) {
611   // Intentionally ignore pc and use return address. This function is here for
612   // compatibility, in case program is linked with library instrumented by
613   // older clang.
614   SetAllocaOrigin(a, size, reinterpret_cast<u32 *>(descr), descr + 4,
615                   GET_CALLER_PC());
616 }
617 
618 void __msan_set_alloca_origin_with_descr(void *a, uptr size, u32 *id_ptr,
619                                          char *descr) {
620   SetAllocaOrigin(a, size, id_ptr, descr, GET_CALLER_PC());
621 }
622 
623 void __msan_set_alloca_origin_no_descr(void *a, uptr size, u32 *id_ptr) {
624   SetAllocaOrigin(a, size, id_ptr, nullptr, GET_CALLER_PC());
625 }
626 
627 u32 __msan_chain_origin(u32 id) {
628   GET_CALLER_PC_BP;
629   GET_STORE_STACK_TRACE_PC_BP(pc, bp);
630   return ChainOrigin(id, &stack);
631 }
632 
633 u32 __msan_get_origin(const void *a) {
634   if (!__msan_get_track_origins()) return 0;
635   uptr x = (uptr)a;
636   uptr aligned = x & ~3ULL;
637   uptr origin_ptr = MEM_TO_ORIGIN(aligned);
638   return *(u32*)origin_ptr;
639 }
640 
641 int __msan_origin_is_descendant_or_same(u32 this_id, u32 prev_id) {
642   Origin o = Origin::FromRawId(this_id);
643   while (o.raw_id() != prev_id && o.isChainedOrigin())
644     o = o.getNextChainedOrigin(nullptr);
645   return o.raw_id() == prev_id;
646 }
647 
648 u32 __msan_get_umr_origin() {
649   return __msan_origin_tls;
650 }
651 
652 u16 __sanitizer_unaligned_load16(const uu16 *p) {
653   internal_memcpy(&__msan_retval_tls[0], (void *)MEM_TO_SHADOW((uptr)p),
654                   sizeof(uu16));
655   if (__msan_get_track_origins())
656     __msan_retval_origin_tls = GetOriginIfPoisoned((uptr)p, sizeof(*p));
657   return *p;
658 }
659 u32 __sanitizer_unaligned_load32(const uu32 *p) {
660   internal_memcpy(&__msan_retval_tls[0], (void *)MEM_TO_SHADOW((uptr)p),
661                   sizeof(uu32));
662   if (__msan_get_track_origins())
663     __msan_retval_origin_tls = GetOriginIfPoisoned((uptr)p, sizeof(*p));
664   return *p;
665 }
666 u64 __sanitizer_unaligned_load64(const uu64 *p) {
667   internal_memcpy(&__msan_retval_tls[0], (void *)MEM_TO_SHADOW((uptr)p),
668                   sizeof(uu64));
669   if (__msan_get_track_origins())
670     __msan_retval_origin_tls = GetOriginIfPoisoned((uptr)p, sizeof(*p));
671   return *p;
672 }
673 void __sanitizer_unaligned_store16(uu16 *p, u16 x) {
674   static_assert(sizeof(uu16) == sizeof(u16), "incompatible types");
675   u16 s;
676   internal_memcpy(&s, &__msan_param_tls[1], sizeof(uu16));
677   internal_memcpy((void *)MEM_TO_SHADOW((uptr)p), &s, sizeof(uu16));
678   if (s && __msan_get_track_origins())
679     if (uu32 o = __msan_param_origin_tls[2])
680       SetOriginIfPoisoned((uptr)p, (uptr)&s, sizeof(s), o);
681   *p = x;
682 }
683 void __sanitizer_unaligned_store32(uu32 *p, u32 x) {
684   static_assert(sizeof(uu32) == sizeof(u32), "incompatible types");
685   u32 s;
686   internal_memcpy(&s, &__msan_param_tls[1], sizeof(uu32));
687   internal_memcpy((void *)MEM_TO_SHADOW((uptr)p), &s, sizeof(uu32));
688   if (s && __msan_get_track_origins())
689     if (uu32 o = __msan_param_origin_tls[2])
690       SetOriginIfPoisoned((uptr)p, (uptr)&s, sizeof(s), o);
691   *p = x;
692 }
693 void __sanitizer_unaligned_store64(uu64 *p, u64 x) {
694   u64 s = __msan_param_tls[1];
695   *(uu64 *)MEM_TO_SHADOW((uptr)p) = s;
696   if (s && __msan_get_track_origins())
697     if (uu32 o = __msan_param_origin_tls[2])
698       SetOriginIfPoisoned((uptr)p, (uptr)&s, sizeof(s), o);
699   *p = x;
700 }
701 
702 void __msan_set_death_callback(void (*callback)(void)) {
703   SetUserDieCallback(callback);
704 }
705 
706 void __msan_start_switch_fiber(const void *bottom, uptr size) {
707   MsanThread *t = GetCurrentThread();
708   if (!t) {
709     VReport(1, "__msan_start_switch_fiber called from unknown thread\n");
710     return;
711   }
712   t->StartSwitchFiber((uptr)bottom, size);
713 }
714 
715 void __msan_finish_switch_fiber(const void **bottom_old, uptr *size_old) {
716   MsanThread *t = GetCurrentThread();
717   if (!t) {
718     VReport(1, "__msan_finish_switch_fiber called from unknown thread\n");
719     return;
720   }
721   t->FinishSwitchFiber((uptr *)bottom_old, (uptr *)size_old);
722 
723   internal_memset(__msan_param_tls, 0, sizeof(__msan_param_tls));
724   internal_memset(__msan_retval_tls, 0, sizeof(__msan_retval_tls));
725   internal_memset(__msan_va_arg_tls, 0, sizeof(__msan_va_arg_tls));
726 
727   if (__msan_get_track_origins()) {
728     internal_memset(__msan_param_origin_tls, 0,
729                     sizeof(__msan_param_origin_tls));
730     internal_memset(&__msan_retval_origin_tls, 0,
731                     sizeof(__msan_retval_origin_tls));
732     internal_memset(__msan_va_arg_origin_tls, 0,
733                     sizeof(__msan_va_arg_origin_tls));
734   }
735 }
736 
737 SANITIZER_INTERFACE_WEAK_DEF(const char *, __msan_default_options, void) {
738   return "";
739 }
740 
741 extern "C" {
742 SANITIZER_INTERFACE_ATTRIBUTE
743 void __sanitizer_print_stack_trace() {
744   GET_FATAL_STACK_TRACE_PC_BP(StackTrace::GetCurrentPc(), GET_CURRENT_FRAME());
745   stack.Print();
746 }
747 } // extern "C"
748