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