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
34using namespace __sanitizer;
35
36// Globals.
37static THREADLOCAL int msan_expect_umr = 0;
38static THREADLOCAL int msan_expected_umr_found = 0;
39
40// Function argument shadow. Each argument starts at the next available 8-byte
41// aligned address.
42SANITIZER_INTERFACE_ATTRIBUTE
43THREADLOCAL 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.
48SANITIZER_INTERFACE_ATTRIBUTE
49THREADLOCAL u32 __msan_param_origin_tls[kMsanParamTlsSize / sizeof(u32)];
50
51SANITIZER_INTERFACE_ATTRIBUTE
52THREADLOCAL u64 __msan_retval_tls[kMsanRetvalTlsSize / sizeof(u64)];
53
54SANITIZER_INTERFACE_ATTRIBUTE
55THREADLOCAL u32 __msan_retval_origin_tls;
56
57SANITIZER_INTERFACE_ATTRIBUTE
58ALIGNED(16) THREADLOCAL u64 __msan_va_arg_tls[kMsanParamTlsSize / sizeof(u64)];
59
60SANITIZER_INTERFACE_ATTRIBUTE
61ALIGNED(16)
62THREADLOCAL u32 __msan_va_arg_origin_tls[kMsanParamTlsSize / sizeof(u32)];
63
64SANITIZER_INTERFACE_ATTRIBUTE
65THREADLOCAL u64 __msan_va_arg_overflow_size_tls;
66
67SANITIZER_INTERFACE_ATTRIBUTE
68THREADLOCAL u32 __msan_origin_tls;
69
70static THREADLOCAL int is_in_symbolizer;
71
72extern "C" SANITIZER_WEAK_ATTRIBUTE const int __msan_track_origins;
73
74int __msan_get_track_origins() {
75  return &__msan_track_origins ? __msan_track_origins : 0;
76}
77
78extern "C" SANITIZER_WEAK_ATTRIBUTE const int __msan_keep_going;
79
80namespace __msan {
81
82void EnterSymbolizer() { ++is_in_symbolizer; }
83void ExitSymbolizer()  { --is_in_symbolizer; }
84bool IsInSymbolizer() { return is_in_symbolizer; }
85
86static Flags msan_flags;
87
88Flags *flags() {
89  return &msan_flags;
90}
91
92int msan_inited = 0;
93bool msan_init_is_running;
94
95int msan_report_count = 0;
96
97// Array of stack origins.
98// FIXME: make it resizable.
99static const uptr kNumStackOriginDescrs = 1024 * 1024;
100static const char *StackOriginDescr[kNumStackOriginDescrs];
101static uptr StackOriginPC[kNumStackOriginDescrs];
102static atomic_uint32_t NumStackOriginDescrs;
103
104void 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.
112class FlagHandlerKeepGoing : 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
131static 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
143static 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  if (__msan_default_options)
176    parser.ParseString(__msan_default_options());
177#if MSAN_CONTAINS_UBSAN
178  const char *ubsan_default_options = __ubsan::MaybeCallUbsanDefaultOptions();
179  ubsan_parser.ParseString(ubsan_default_options);
180#endif
181
182  parser.ParseStringFromEnv("MSAN_OPTIONS");
183#if MSAN_CONTAINS_UBSAN
184  ubsan_parser.ParseStringFromEnv("UBSAN_OPTIONS");
185#endif
186
187  InitializeCommonFlags();
188
189  if (Verbosity()) ReportUnrecognizedFlags();
190
191  if (common_flags()->help) parser.PrintFlagDescriptions();
192
193  // Check if deprecated exit_code MSan flag is set.
194  if (f->exit_code != -1) {
195    if (Verbosity())
196      Printf("MSAN_OPTIONS=exit_code is deprecated! "
197             "Please use MSAN_OPTIONS=exitcode instead.\n");
198    CommonFlags cf;
199    cf.CopyFrom(*common_flags());
200    cf.exitcode = f->exit_code;
201    OverrideCommonFlags(cf);
202  }
203
204  // Check flag values:
205  if (f->origin_history_size < 0 ||
206      f->origin_history_size > Origin::kMaxDepth) {
207    Printf(
208        "Origin history size invalid: %d. Must be 0 (unlimited) or in [1, %d] "
209        "range.\n",
210        f->origin_history_size, Origin::kMaxDepth);
211    Die();
212  }
213  // Limiting to kStackDepotMaxUseCount / 2 to avoid overflow in
214  // StackDepotHandle::inc_use_count_unsafe.
215  if (f->origin_history_per_stack_limit < 0 ||
216      f->origin_history_per_stack_limit > kStackDepotMaxUseCount / 2) {
217    Printf(
218        "Origin per-stack limit invalid: %d. Must be 0 (unlimited) or in [1, "
219        "%d] range.\n",
220        f->origin_history_per_stack_limit, kStackDepotMaxUseCount / 2);
221    Die();
222  }
223  if (f->store_context_size < 1) f->store_context_size = 1;
224}
225
226void PrintWarning(uptr pc, uptr bp) {
227  PrintWarningWithOrigin(pc, bp, __msan_origin_tls);
228}
229
230void PrintWarningWithOrigin(uptr pc, uptr bp, u32 origin) {
231  if (msan_expect_umr) {
232    // Printf("Expected UMR\n");
233    __msan_origin_tls = origin;
234    msan_expected_umr_found = 1;
235    return;
236  }
237
238  ++msan_report_count;
239
240  GET_FATAL_STACK_TRACE_PC_BP(pc, bp);
241
242  u32 report_origin =
243    (__msan_get_track_origins() && Origin::isValidId(origin)) ? origin : 0;
244  ReportUMR(&stack, report_origin);
245
246  if (__msan_get_track_origins() && !Origin::isValidId(origin)) {
247    Printf(
248        "  ORIGIN: invalid (%x). Might be a bug in MemorySanitizer origin "
249        "tracking.\n    This could still be a bug in your code, too!\n",
250        origin);
251  }
252}
253
254void UnpoisonParam(uptr n) {
255  internal_memset(__msan_param_tls, 0, n * sizeof(*__msan_param_tls));
256}
257
258// Backup MSan runtime TLS state.
259// Implementation must be async-signal-safe.
260// Instances of this class may live on the signal handler stack, and data size
261// may be an issue.
262void ScopedThreadLocalStateBackup::Backup() {
263  va_arg_overflow_size_tls = __msan_va_arg_overflow_size_tls;
264}
265
266void ScopedThreadLocalStateBackup::Restore() {
267  // A lame implementation that only keeps essential state and resets the rest.
268  __msan_va_arg_overflow_size_tls = va_arg_overflow_size_tls;
269
270  internal_memset(__msan_param_tls, 0, sizeof(__msan_param_tls));
271  internal_memset(__msan_retval_tls, 0, sizeof(__msan_retval_tls));
272  internal_memset(__msan_va_arg_tls, 0, sizeof(__msan_va_arg_tls));
273  internal_memset(__msan_va_arg_origin_tls, 0,
274                  sizeof(__msan_va_arg_origin_tls));
275
276  if (__msan_get_track_origins()) {
277    internal_memset(&__msan_retval_origin_tls, 0,
278                    sizeof(__msan_retval_origin_tls));
279    internal_memset(__msan_param_origin_tls, 0,
280                    sizeof(__msan_param_origin_tls));
281  }
282}
283
284void UnpoisonThreadLocalState() {
285}
286
287const char *GetStackOriginDescr(u32 id, uptr *pc) {
288  CHECK_LT(id, kNumStackOriginDescrs);
289  if (pc) *pc = StackOriginPC[id];
290  return StackOriginDescr[id];
291}
292
293u32 ChainOrigin(u32 id, StackTrace *stack) {
294  MsanThread *t = GetCurrentThread();
295  if (t && t->InSignalHandler())
296    return id;
297
298  Origin o = Origin::FromRawId(id);
299  stack->tag = StackTrace::TAG_UNKNOWN;
300  Origin chained = Origin::CreateChainedOrigin(o, stack);
301  return chained.raw_id();
302}
303
304} // namespace __msan
305
306void __sanitizer::BufferedStackTrace::UnwindImpl(
307    uptr pc, uptr bp, void *context, bool request_fast, u32 max_depth) {
308  using namespace __msan;
309  MsanThread *t = GetCurrentThread();
310  if (!t || !StackTrace::WillUseFastUnwind(request_fast)) {
311    // Block reports from our interceptors during _Unwind_Backtrace.
312    SymbolizerScope sym_scope;
313    return Unwind(max_depth, pc, bp, context, 0, 0, false);
314  }
315  if (StackTrace::WillUseFastUnwind(request_fast))
316    Unwind(max_depth, pc, bp, nullptr, t->stack_top(), t->stack_bottom(), true);
317  else
318    Unwind(max_depth, pc, 0, context, 0, 0, false);
319}
320
321// Interface.
322
323using namespace __msan;
324
325#define MSAN_MAYBE_WARNING(type, size)              \
326  void __msan_maybe_warning_##size(type s, u32 o) { \
327    GET_CALLER_PC_BP_SP;                            \
328    (void) sp;                                      \
329    if (UNLIKELY(s)) {                              \
330      PrintWarningWithOrigin(pc, bp, o);            \
331      if (__msan::flags()->halt_on_error) {         \
332        Printf("Exiting\n");                        \
333        Die();                                      \
334      }                                             \
335    }                                               \
336  }
337
338MSAN_MAYBE_WARNING(u8, 1)
339MSAN_MAYBE_WARNING(u16, 2)
340MSAN_MAYBE_WARNING(u32, 4)
341MSAN_MAYBE_WARNING(u64, 8)
342
343#define MSAN_MAYBE_STORE_ORIGIN(type, size)                       \
344  void __msan_maybe_store_origin_##size(type s, void *p, u32 o) { \
345    if (UNLIKELY(s)) {                                            \
346      if (__msan_get_track_origins() > 1) {                       \
347        GET_CALLER_PC_BP_SP;                                      \
348        (void) sp;                                                \
349        GET_STORE_STACK_TRACE_PC_BP(pc, bp);                      \
350        o = ChainOrigin(o, &stack);                               \
351      }                                                           \
352      *(u32 *)MEM_TO_ORIGIN((uptr)p & ~3UL) = o;                  \
353    }                                                             \
354  }
355
356MSAN_MAYBE_STORE_ORIGIN(u8, 1)
357MSAN_MAYBE_STORE_ORIGIN(u16, 2)
358MSAN_MAYBE_STORE_ORIGIN(u32, 4)
359MSAN_MAYBE_STORE_ORIGIN(u64, 8)
360
361void __msan_warning() {
362  GET_CALLER_PC_BP_SP;
363  (void)sp;
364  PrintWarning(pc, bp);
365  if (__msan::flags()->halt_on_error) {
366    if (__msan::flags()->print_stats)
367      ReportStats();
368    Printf("Exiting\n");
369    Die();
370  }
371}
372
373void __msan_warning_noreturn() {
374  GET_CALLER_PC_BP_SP;
375  (void)sp;
376  PrintWarning(pc, bp);
377  if (__msan::flags()->print_stats)
378    ReportStats();
379  Printf("Exiting\n");
380  Die();
381}
382
383void __msan_warning_with_origin(u32 origin) {
384  GET_CALLER_PC_BP_SP;
385  (void)sp;
386  PrintWarningWithOrigin(pc, bp, origin);
387  if (__msan::flags()->halt_on_error) {
388    if (__msan::flags()->print_stats)
389      ReportStats();
390    Printf("Exiting\n");
391    Die();
392  }
393}
394
395void __msan_warning_with_origin_noreturn(u32 origin) {
396  GET_CALLER_PC_BP_SP;
397  (void)sp;
398  PrintWarningWithOrigin(pc, bp, origin);
399  if (__msan::flags()->print_stats)
400    ReportStats();
401  Printf("Exiting\n");
402  Die();
403}
404
405static void OnStackUnwind(const SignalContext &sig, const void *,
406                          BufferedStackTrace *stack) {
407  stack->Unwind(StackTrace::GetNextInstructionPc(sig.pc), sig.bp, sig.context,
408                common_flags()->fast_unwind_on_fatal);
409}
410
411static void MsanOnDeadlySignal(int signo, void *siginfo, void *context) {
412  HandleDeadlySignal(siginfo, context, GetTid(), &OnStackUnwind, nullptr);
413}
414
415static void MsanCheckFailed(const char *file, int line, const char *cond,
416                            u64 v1, u64 v2) {
417  Report("MemorySanitizer CHECK failed: %s:%d \"%s\" (0x%zx, 0x%zx)\n", file,
418         line, cond, (uptr)v1, (uptr)v2);
419  PRINT_CURRENT_STACK_CHECK();
420  Die();
421}
422
423void __msan_init() {
424  CHECK(!msan_init_is_running);
425  if (msan_inited) return;
426  msan_init_is_running = 1;
427  SanitizerToolName = "MemorySanitizer";
428
429  AvoidCVE_2016_2143();
430
431  CacheBinaryName();
432  InitializeFlags();
433
434  // Install tool-specific callbacks in sanitizer_common.
435  SetCheckFailedCallback(MsanCheckFailed);
436
437  __sanitizer_set_report_path(common_flags()->log_path);
438
439  InitializeInterceptors();
440  CheckASLR();
441  InitTlsSize();
442  InstallDeadlySignalHandlers(MsanOnDeadlySignal);
443  InstallAtExitHandler(); // Needs __cxa_atexit interceptor.
444
445  DisableCoreDumperIfNecessary();
446  if (StackSizeIsUnlimited()) {
447    VPrintf(1, "Unlimited stack, doing reexec\n");
448    // A reasonably large stack size. It is bigger than the usual 8Mb, because,
449    // well, the program could have been run with unlimited stack for a reason.
450    SetStackSizeLimitInBytes(32 * 1024 * 1024);
451    ReExec();
452  }
453
454  __msan_clear_on_return();
455  if (__msan_get_track_origins())
456    VPrintf(1, "msan_track_origins\n");
457  if (!InitShadow(__msan_get_track_origins())) {
458    Printf("FATAL: MemorySanitizer can not mmap the shadow memory.\n");
459    Printf("FATAL: Make sure to compile with -fPIE and to link with -pie.\n");
460    Printf("FATAL: Disabling ASLR is known to cause this error.\n");
461    Printf("FATAL: If running under GDB, try "
462           "'set disable-randomization off'.\n");
463    DumpProcessMap();
464    Die();
465  }
466
467  Symbolizer::GetOrInit()->AddHooks(EnterSymbolizer, ExitSymbolizer);
468
469  InitializeCoverage(common_flags()->coverage, common_flags()->coverage_dir);
470
471  MsanTSDInit(MsanTSDDtor);
472
473  MsanAllocatorInit();
474
475  MsanThread *main_thread = MsanThread::Create(nullptr, nullptr);
476  SetCurrentThread(main_thread);
477  main_thread->ThreadStart();
478
479#if MSAN_CONTAINS_UBSAN
480  __ubsan::InitAsPlugin();
481#endif
482
483  VPrintf(1, "MemorySanitizer init done\n");
484
485  msan_init_is_running = 0;
486  msan_inited = 1;
487}
488
489void __msan_set_keep_going(int keep_going) {
490  flags()->halt_on_error = !keep_going;
491}
492
493void __msan_set_expect_umr(int expect_umr) {
494  if (expect_umr) {
495    msan_expected_umr_found = 0;
496  } else if (!msan_expected_umr_found) {
497    GET_CALLER_PC_BP_SP;
498    (void)sp;
499    GET_FATAL_STACK_TRACE_PC_BP(pc, bp);
500    ReportExpectedUMRNotFound(&stack);
501    Die();
502  }
503  msan_expect_umr = expect_umr;
504}
505
506void __msan_print_shadow(const void *x, uptr size) {
507  if (!MEM_IS_APP(x)) {
508    Printf("Not a valid application address: %p\n", x);
509    return;
510  }
511
512  DescribeMemoryRange(x, size);
513}
514
515void __msan_dump_shadow(const void *x, uptr size) {
516  if (!MEM_IS_APP(x)) {
517    Printf("Not a valid application address: %p\n", x);
518    return;
519  }
520
521  unsigned char *s = (unsigned char*)MEM_TO_SHADOW(x);
522  for (uptr i = 0; i < size; i++)
523    Printf("%x%x ", s[i] >> 4, s[i] & 0xf);
524  Printf("\n");
525}
526
527sptr __msan_test_shadow(const void *x, uptr size) {
528  if (!MEM_IS_APP(x)) return -1;
529  unsigned char *s = (unsigned char *)MEM_TO_SHADOW((uptr)x);
530  for (uptr i = 0; i < size; ++i)
531    if (s[i])
532      return i;
533  return -1;
534}
535
536void __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
553int __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
559int __msan_has_dynamic_component() { return false; }
560
561NOINLINE
562void __msan_clear_on_return() {
563  __msan_param_tls[0] = 0;
564}
565
566void __msan_partial_poison(const void* data, void* shadow, uptr size) {
567  internal_memcpy((void*)MEM_TO_SHADOW((uptr)data), shadow, size);
568}
569
570void __msan_load_unpoisoned(const void *src, uptr size, void *dst) {
571  internal_memcpy(dst, src, size);
572  __msan_unpoison(dst, size);
573}
574
575void __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)).
582void __msan_set_alloca_origin(void *a, uptr size, char *descr) {
583  __msan_set_alloca_origin4(a, size, descr, 0);
584}
585
586void __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
615u32 __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
622u32 __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
630int __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
637u32 __msan_get_umr_origin() {
638  return __msan_origin_tls;
639}
640
641u16 __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}
648u32 __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}
655u64 __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}
662void __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}
672void __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}
682void __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
691void __msan_set_death_callback(void (*callback)(void)) {
692  SetUserDieCallback(callback);
693}
694
695#if !SANITIZER_SUPPORTS_WEAK_HOOKS
696extern "C" {
697SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
698const char* __msan_default_options() { return ""; }
699}  // extern "C"
700#endif
701
702extern "C" {
703SANITIZER_INTERFACE_ATTRIBUTE
704void __sanitizer_print_stack_trace() {
705  GET_FATAL_STACK_TRACE_PC_BP(StackTrace::GetCurrentPc(), GET_CURRENT_FRAME());
706  stack.Print();
707}
708} // extern "C"
709