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 
__msan_get_track_origins()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 
EnterSymbolizer()82 void EnterSymbolizer() { ++is_in_symbolizer; }
ExitSymbolizer()83 void ExitSymbolizer()  { --is_in_symbolizer; }
IsInSymbolizer()84 bool IsInSymbolizer() { return is_in_symbolizer; }
85 
86 static Flags msan_flags;
87 
flags()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 
SetDefaults()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:
FlagHandlerKeepGoing(bool * halt_on_error)116   explicit FlagHandlerKeepGoing(bool *halt_on_error)
117       : halt_on_error_(halt_on_error) {}
Parse(const char * value)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   }
Format(char * buffer,uptr size)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 
RegisterMsanFlags(FlagParser * parser,Flags * f)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 
InitializeFlags()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     cf.exitcode = 77;
155     OverrideCommonFlags(cf);
156   }
157 
158   Flags *f = flags();
159   f->SetDefaults();
160 
161   FlagParser parser;
162   RegisterMsanFlags(&parser, f);
163   RegisterCommonFlags(&parser);
164 
165 #if MSAN_CONTAINS_UBSAN
166   __ubsan::Flags *uf = __ubsan::flags();
167   uf->SetDefaults();
168 
169   FlagParser ubsan_parser;
170   __ubsan::RegisterUbsanFlags(&ubsan_parser, uf);
171   RegisterCommonFlags(&ubsan_parser);
172 #endif
173 
174   // Override from user-specified string.
175   parser.ParseString(__msan_default_options());
176 #if MSAN_CONTAINS_UBSAN
177   const char *ubsan_default_options = __ubsan_default_options();
178   ubsan_parser.ParseString(ubsan_default_options);
179 #endif
180 
181   parser.ParseStringFromEnv("MSAN_OPTIONS");
182 #if MSAN_CONTAINS_UBSAN
183   ubsan_parser.ParseStringFromEnv("UBSAN_OPTIONS");
184 #endif
185 
186   InitializeCommonFlags();
187 
188   if (Verbosity()) ReportUnrecognizedFlags();
189 
190   if (common_flags()->help) parser.PrintFlagDescriptions();
191 
192   // Check if deprecated exit_code MSan flag is set.
193   if (f->exit_code != -1) {
194     if (Verbosity())
195       Printf("MSAN_OPTIONS=exit_code is deprecated! "
196              "Please use MSAN_OPTIONS=exitcode instead.\n");
197     CommonFlags cf;
198     cf.CopyFrom(*common_flags());
199     cf.exitcode = f->exit_code;
200     OverrideCommonFlags(cf);
201   }
202 
203   // Check flag values:
204   if (f->origin_history_size < 0 ||
205       f->origin_history_size > Origin::kMaxDepth) {
206     Printf(
207         "Origin history size invalid: %d. Must be 0 (unlimited) or in [1, %d] "
208         "range.\n",
209         f->origin_history_size, Origin::kMaxDepth);
210     Die();
211   }
212   // Limiting to kStackDepotMaxUseCount / 2 to avoid overflow in
213   // StackDepotHandle::inc_use_count_unsafe.
214   if (f->origin_history_per_stack_limit < 0 ||
215       f->origin_history_per_stack_limit > kStackDepotMaxUseCount / 2) {
216     Printf(
217         "Origin per-stack limit invalid: %d. Must be 0 (unlimited) or in [1, "
218         "%d] range.\n",
219         f->origin_history_per_stack_limit, kStackDepotMaxUseCount / 2);
220     Die();
221   }
222   if (f->store_context_size < 1) f->store_context_size = 1;
223 }
224 
PrintWarning(uptr pc,uptr bp)225 void PrintWarning(uptr pc, uptr bp) {
226   PrintWarningWithOrigin(pc, bp, __msan_origin_tls);
227 }
228 
PrintWarningWithOrigin(uptr pc,uptr bp,u32 origin)229 void PrintWarningWithOrigin(uptr pc, uptr bp, u32 origin) {
230   if (msan_expect_umr) {
231     // Printf("Expected UMR\n");
232     __msan_origin_tls = origin;
233     msan_expected_umr_found = 1;
234     return;
235   }
236 
237   ++msan_report_count;
238 
239   GET_FATAL_STACK_TRACE_PC_BP(pc, bp);
240 
241   u32 report_origin =
242     (__msan_get_track_origins() && Origin::isValidId(origin)) ? origin : 0;
243   ReportUMR(&stack, report_origin);
244 
245   if (__msan_get_track_origins() && !Origin::isValidId(origin)) {
246     Printf(
247         "  ORIGIN: invalid (%x). Might be a bug in MemorySanitizer origin "
248         "tracking.\n    This could still be a bug in your code, too!\n",
249         origin);
250   }
251 }
252 
UnpoisonParam(uptr n)253 void UnpoisonParam(uptr n) {
254   internal_memset(__msan_param_tls, 0, n * sizeof(*__msan_param_tls));
255 }
256 
257 // Backup MSan runtime TLS state.
258 // Implementation must be async-signal-safe.
259 // Instances of this class may live on the signal handler stack, and data size
260 // may be an issue.
Backup()261 void ScopedThreadLocalStateBackup::Backup() {
262   va_arg_overflow_size_tls = __msan_va_arg_overflow_size_tls;
263 }
264 
Restore()265 void ScopedThreadLocalStateBackup::Restore() {
266   // A lame implementation that only keeps essential state and resets the rest.
267   __msan_va_arg_overflow_size_tls = va_arg_overflow_size_tls;
268 
269   internal_memset(__msan_param_tls, 0, sizeof(__msan_param_tls));
270   internal_memset(__msan_retval_tls, 0, sizeof(__msan_retval_tls));
271   internal_memset(__msan_va_arg_tls, 0, sizeof(__msan_va_arg_tls));
272   internal_memset(__msan_va_arg_origin_tls, 0,
273                   sizeof(__msan_va_arg_origin_tls));
274 
275   if (__msan_get_track_origins()) {
276     internal_memset(&__msan_retval_origin_tls, 0,
277                     sizeof(__msan_retval_origin_tls));
278     internal_memset(__msan_param_origin_tls, 0,
279                     sizeof(__msan_param_origin_tls));
280   }
281 }
282 
UnpoisonThreadLocalState()283 void UnpoisonThreadLocalState() {
284 }
285 
GetStackOriginDescr(u32 id,uptr * pc)286 const char *GetStackOriginDescr(u32 id, uptr *pc) {
287   CHECK_LT(id, kNumStackOriginDescrs);
288   if (pc) *pc = StackOriginPC[id];
289   return StackOriginDescr[id];
290 }
291 
ChainOrigin(u32 id,StackTrace * stack)292 u32 ChainOrigin(u32 id, StackTrace *stack) {
293   MsanThread *t = GetCurrentThread();
294   if (t && t->InSignalHandler())
295     return id;
296 
297   Origin o = Origin::FromRawId(id);
298   stack->tag = StackTrace::TAG_UNKNOWN;
299   Origin chained = Origin::CreateChainedOrigin(o, stack);
300   return chained.raw_id();
301 }
302 
303 } // namespace __msan
304 
UnwindImpl(uptr pc,uptr bp,void * context,bool request_fast,u32 max_depth)305 void __sanitizer::BufferedStackTrace::UnwindImpl(
306     uptr pc, uptr bp, void *context, bool request_fast, u32 max_depth) {
307   using namespace __msan;
308   MsanThread *t = GetCurrentThread();
309   if (!t || !StackTrace::WillUseFastUnwind(request_fast)) {
310     // Block reports from our interceptors during _Unwind_Backtrace.
311     SymbolizerScope sym_scope;
312     return Unwind(max_depth, pc, bp, context, 0, 0, false);
313   }
314   if (StackTrace::WillUseFastUnwind(request_fast))
315     Unwind(max_depth, pc, bp, nullptr, t->stack_top(), t->stack_bottom(), true);
316   else
317     Unwind(max_depth, pc, 0, context, 0, 0, false);
318 }
319 
320 // Interface.
321 
322 using namespace __msan;
323 
324 #define MSAN_MAYBE_WARNING(type, size)              \
325   void __msan_maybe_warning_##size(type s, u32 o) { \
326     GET_CALLER_PC_BP_SP;                            \
327     (void) sp;                                      \
328     if (UNLIKELY(s)) {                              \
329       PrintWarningWithOrigin(pc, bp, o);            \
330       if (__msan::flags()->halt_on_error) {         \
331         Printf("Exiting\n");                        \
332         Die();                                      \
333       }                                             \
334     }                                               \
335   }
336 
337 MSAN_MAYBE_WARNING(u8, 1)
338 MSAN_MAYBE_WARNING(u16, 2)
339 MSAN_MAYBE_WARNING(u32, 4)
340 MSAN_MAYBE_WARNING(u64, 8)
341 
342 #define MSAN_MAYBE_STORE_ORIGIN(type, size)                       \
343   void __msan_maybe_store_origin_##size(type s, void *p, u32 o) { \
344     if (UNLIKELY(s)) {                                            \
345       if (__msan_get_track_origins() > 1) {                       \
346         GET_CALLER_PC_BP_SP;                                      \
347         (void) sp;                                                \
348         GET_STORE_STACK_TRACE_PC_BP(pc, bp);                      \
349         o = ChainOrigin(o, &stack);                               \
350       }                                                           \
351       *(u32 *)MEM_TO_ORIGIN((uptr)p & ~3UL) = o;                  \
352     }                                                             \
353   }
354 
355 MSAN_MAYBE_STORE_ORIGIN(u8, 1)
356 MSAN_MAYBE_STORE_ORIGIN(u16, 2)
357 MSAN_MAYBE_STORE_ORIGIN(u32, 4)
358 MSAN_MAYBE_STORE_ORIGIN(u64, 8)
359 
__msan_warning()360 void __msan_warning() {
361   GET_CALLER_PC_BP_SP;
362   (void)sp;
363   PrintWarning(pc, bp);
364   if (__msan::flags()->halt_on_error) {
365     if (__msan::flags()->print_stats)
366       ReportStats();
367     Printf("Exiting\n");
368     Die();
369   }
370 }
371 
__msan_warning_noreturn()372 void __msan_warning_noreturn() {
373   GET_CALLER_PC_BP_SP;
374   (void)sp;
375   PrintWarning(pc, bp);
376   if (__msan::flags()->print_stats)
377     ReportStats();
378   Printf("Exiting\n");
379   Die();
380 }
381 
__msan_warning_with_origin(u32 origin)382 void __msan_warning_with_origin(u32 origin) {
383   GET_CALLER_PC_BP_SP;
384   (void)sp;
385   PrintWarningWithOrigin(pc, bp, origin);
386   if (__msan::flags()->halt_on_error) {
387     if (__msan::flags()->print_stats)
388       ReportStats();
389     Printf("Exiting\n");
390     Die();
391   }
392 }
393 
__msan_warning_with_origin_noreturn(u32 origin)394 void __msan_warning_with_origin_noreturn(u32 origin) {
395   GET_CALLER_PC_BP_SP;
396   (void)sp;
397   PrintWarningWithOrigin(pc, bp, origin);
398   if (__msan::flags()->print_stats)
399     ReportStats();
400   Printf("Exiting\n");
401   Die();
402 }
403 
OnStackUnwind(const SignalContext & sig,const void *,BufferedStackTrace * stack)404 static void OnStackUnwind(const SignalContext &sig, const void *,
405                           BufferedStackTrace *stack) {
406   stack->Unwind(StackTrace::GetNextInstructionPc(sig.pc), sig.bp, sig.context,
407                 common_flags()->fast_unwind_on_fatal);
408 }
409 
MsanOnDeadlySignal(int signo,void * siginfo,void * context)410 static void MsanOnDeadlySignal(int signo, void *siginfo, void *context) {
411   HandleDeadlySignal(siginfo, context, GetTid(), &OnStackUnwind, nullptr);
412 }
413 
MsanCheckFailed(const char * file,int line,const char * cond,u64 v1,u64 v2)414 static void MsanCheckFailed(const char *file, int line, const char *cond,
415                             u64 v1, u64 v2) {
416   Report("MemorySanitizer CHECK failed: %s:%d \"%s\" (0x%zx, 0x%zx)\n", file,
417          line, cond, (uptr)v1, (uptr)v2);
418   PRINT_CURRENT_STACK_CHECK();
419   Die();
420 }
421 
__msan_init()422 void __msan_init() {
423   CHECK(!msan_init_is_running);
424   if (msan_inited) return;
425   msan_init_is_running = 1;
426   SanitizerToolName = "MemorySanitizer";
427 
428   AvoidCVE_2016_2143();
429 
430   CacheBinaryName();
431   InitializeFlags();
432 
433   // Install tool-specific callbacks in sanitizer_common.
434   SetCheckFailedCallback(MsanCheckFailed);
435 
436   __sanitizer_set_report_path(common_flags()->log_path);
437 
438   InitializeInterceptors();
439   CheckASLR();
440   InitTlsSize();
441   InstallDeadlySignalHandlers(MsanOnDeadlySignal);
442   InstallAtExitHandler(); // Needs __cxa_atexit interceptor.
443 
444   DisableCoreDumperIfNecessary();
445   if (StackSizeIsUnlimited()) {
446     VPrintf(1, "Unlimited stack, doing reexec\n");
447     // A reasonably large stack size. It is bigger than the usual 8Mb, because,
448     // well, the program could have been run with unlimited stack for a reason.
449     SetStackSizeLimitInBytes(32 * 1024 * 1024);
450     ReExec();
451   }
452 
453   __msan_clear_on_return();
454   if (__msan_get_track_origins())
455     VPrintf(1, "msan_track_origins\n");
456   if (!InitShadow(__msan_get_track_origins())) {
457     Printf("FATAL: MemorySanitizer can not mmap the shadow memory.\n");
458     Printf("FATAL: Make sure to compile with -fPIE and to link with -pie.\n");
459     Printf("FATAL: Disabling ASLR is known to cause this error.\n");
460     Printf("FATAL: If running under GDB, try "
461            "'set disable-randomization off'.\n");
462     DumpProcessMap();
463     Die();
464   }
465 
466   Symbolizer::GetOrInit()->AddHooks(EnterSymbolizer, ExitSymbolizer);
467 
468   InitializeCoverage(common_flags()->coverage, common_flags()->coverage_dir);
469 
470   MsanTSDInit(MsanTSDDtor);
471 
472   MsanAllocatorInit();
473 
474   MsanThread *main_thread = MsanThread::Create(nullptr, nullptr);
475   SetCurrentThread(main_thread);
476   main_thread->ThreadStart();
477 
478 #if MSAN_CONTAINS_UBSAN
479   __ubsan::InitAsPlugin();
480 #endif
481 
482   VPrintf(1, "MemorySanitizer init done\n");
483 
484   msan_init_is_running = 0;
485   msan_inited = 1;
486 }
487 
__msan_set_keep_going(int keep_going)488 void __msan_set_keep_going(int keep_going) {
489   flags()->halt_on_error = !keep_going;
490 }
491 
__msan_set_expect_umr(int expect_umr)492 void __msan_set_expect_umr(int expect_umr) {
493   if (expect_umr) {
494     msan_expected_umr_found = 0;
495   } else if (!msan_expected_umr_found) {
496     GET_CALLER_PC_BP_SP;
497     (void)sp;
498     GET_FATAL_STACK_TRACE_PC_BP(pc, bp);
499     ReportExpectedUMRNotFound(&stack);
500     Die();
501   }
502   msan_expect_umr = expect_umr;
503 }
504 
__msan_print_shadow(const void * x,uptr size)505 void __msan_print_shadow(const void *x, uptr size) {
506   if (!MEM_IS_APP(x)) {
507     Printf("Not a valid application address: %p\n", x);
508     return;
509   }
510 
511   DescribeMemoryRange(x, size);
512 }
513 
__msan_dump_shadow(const void * x,uptr size)514 void __msan_dump_shadow(const void *x, uptr size) {
515   if (!MEM_IS_APP(x)) {
516     Printf("Not a valid application address: %p\n", x);
517     return;
518   }
519 
520   unsigned char *s = (unsigned char*)MEM_TO_SHADOW(x);
521   for (uptr i = 0; i < size; i++)
522     Printf("%x%x ", s[i] >> 4, s[i] & 0xf);
523   Printf("\n");
524 }
525 
__msan_test_shadow(const void * x,uptr size)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 
__msan_check_mem_is_initialized(const void * x,uptr size)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 
__msan_set_poison_in_malloc(int do_poison)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 
__msan_has_dynamic_component()561 int __msan_has_dynamic_component() { return false; }
562 
563 NOINLINE
__msan_clear_on_return()564 void __msan_clear_on_return() {
565   __msan_param_tls[0] = 0;
566 }
567 
__msan_partial_poison(const void * data,void * shadow,uptr size)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 
__msan_load_unpoisoned(const void * src,uptr size,void * dst)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 
__msan_set_origin(const void * a,uptr size,u32 origin)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)).
__msan_set_alloca_origin(void * a,uptr size,char * descr)584 void __msan_set_alloca_origin(void *a, uptr size, char *descr) {
585   __msan_set_alloca_origin4(a, size, descr, 0);
586 }
587 
__msan_set_alloca_origin4(void * a,uptr size,char * descr,uptr pc)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 %p \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 
__msan_chain_origin(u32 id)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 
__msan_get_origin(const void * a)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 
__msan_origin_is_descendant_or_same(u32 this_id,u32 prev_id)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 
__msan_get_umr_origin()639 u32 __msan_get_umr_origin() {
640   return __msan_origin_tls;
641 }
642 
__sanitizer_unaligned_load16(const uu16 * p)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 }
__sanitizer_unaligned_load32(const uu32 * p)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 }
__sanitizer_unaligned_load64(const uu64 * p)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 }
__sanitizer_unaligned_store16(uu16 * p,u16 x)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 }
__sanitizer_unaligned_store32(uu32 * p,u32 x)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 }
__sanitizer_unaligned_store64(uu64 * p,u64 x)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 
__msan_set_death_callback(void (* callback)(void))693 void __msan_set_death_callback(void (*callback)(void)) {
694   SetUserDieCallback(callback);
695 }
696 
__msan_start_switch_fiber(const void * bottom,uptr size)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 
__msan_finish_switch_fiber(const void ** bottom_old,uptr * size_old)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 
SANITIZER_INTERFACE_WEAK_DEF(const char *,__msan_default_options,void)728 SANITIZER_INTERFACE_WEAK_DEF(const char *, __msan_default_options, void) {
729   return "";
730 }
731 
732 extern "C" {
733 SANITIZER_INTERFACE_ATTRIBUTE
__sanitizer_print_stack_trace()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