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
36using namespace __sanitizer;
37
38// Globals.
39static THREADLOCAL int msan_expect_umr = 0;
40static THREADLOCAL int msan_expected_umr_found = 0;
41
42// Function argument shadow. Each argument starts at the next available 8-byte
43// aligned address.
44SANITIZER_INTERFACE_ATTRIBUTE
45THREADLOCAL 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.
50SANITIZER_INTERFACE_ATTRIBUTE
51THREADLOCAL u32 __msan_param_origin_tls[kMsanParamTlsSize / sizeof(u32)];
52
53SANITIZER_INTERFACE_ATTRIBUTE
54THREADLOCAL u64 __msan_retval_tls[kMsanRetvalTlsSize / sizeof(u64)];
55
56SANITIZER_INTERFACE_ATTRIBUTE
57THREADLOCAL u32 __msan_retval_origin_tls;
58
59alignas(16) SANITIZER_INTERFACE_ATTRIBUTE THREADLOCAL u64
60 __msan_va_arg_tls[kMsanParamTlsSize / sizeof(u64)];
61
62alignas(16) SANITIZER_INTERFACE_ATTRIBUTE THREADLOCAL u32
63 __msan_va_arg_origin_tls[kMsanParamTlsSize / sizeof(u32)];
64
65SANITIZER_INTERFACE_ATTRIBUTE
66THREADLOCAL uptr __msan_va_arg_overflow_size_tls;
67
68SANITIZER_INTERFACE_ATTRIBUTE
69THREADLOCAL u32 __msan_origin_tls;
70
71extern "C" SANITIZER_WEAK_ATTRIBUTE const int __msan_track_origins;
72
73int __msan_get_track_origins() {
74 return &__msan_track_origins ? __msan_track_origins : 0;
75}
76
77extern "C" SANITIZER_WEAK_ATTRIBUTE const int __msan_keep_going;
78
79namespace __msan {
80
81static THREADLOCAL int is_in_symbolizer_or_unwinder;
82static void EnterSymbolizerOrUnwider() { ++is_in_symbolizer_or_unwinder; }
83static void ExitSymbolizerOrUnwider() { --is_in_symbolizer_or_unwinder; }
84bool IsInSymbolizerOrUnwider() { return is_in_symbolizer_or_unwinder; }
85
86struct UnwinderScope {
87 UnwinderScope() { EnterSymbolizerOrUnwider(); }
88 ~UnwinderScope() { ExitSymbolizerOrUnwider(); }
89};
90
91static Flags msan_flags;
92
93Flags *flags() { return &msan_flags; }
94
95int msan_inited = 0;
96bool msan_init_is_running;
97
98int 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
109static const uptr kNumStackOriginDescrs = 1 * 1024 * 1024;
110#else
111static const uptr kNumStackOriginDescrs = 4 * 1024 * 1024;
112#endif // SANITIZER_PPC
113static const char *StackOriginDescr[kNumStackOriginDescrs];
114static uptr StackOriginPC[kNumStackOriginDescrs];
115static atomic_uint32_t NumStackOriginDescrs;
116
117void 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.
125class 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, str_to_use: keep_going_str);
141 }
142};
143
144static 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(name: "keep_going", handler: fh_keep_going,
153 desc: "deprecated, use halt_on_error");
154}
155
156static void InitializeFlags() {
157 SetCommonFlagsDefaults();
158 {
159 CommonFlags cf;
160 cf.CopyFrom(other: *common_flags());
161 cf.external_symbolizer_path = GetEnv(name: "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: &parser, f);
175 RegisterCommonFlags(parser: &parser);
176
177#if MSAN_CONTAINS_UBSAN
178 __ubsan::Flags *uf = __ubsan::flags();
179 uf->SetDefaults();
180
181 FlagParser ubsan_parser;
182 __ubsan::RegisterUbsanFlags(parser: &ubsan_parser, f: uf);
183 RegisterCommonFlags(parser: &ubsan_parser);
184#endif
185
186 // Override from user-specified string.
187 parser.ParseString(s: __msan_default_options());
188#if MSAN_CONTAINS_UBSAN
189 const char *ubsan_default_options = __ubsan_default_options();
190 ubsan_parser.ParseString(s: ubsan_default_options);
191#endif
192
193 parser.ParseStringFromEnv(env_name: "MSAN_OPTIONS");
194#if MSAN_CONTAINS_UBSAN
195 ubsan_parser.ParseStringFromEnv(env_name: "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(format: "MSAN_OPTIONS=exit_code is deprecated! "
208 "Please use MSAN_OPTIONS=exitcode instead.\n");
209 CommonFlags cf;
210 cf.CopyFrom(other: *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 format: "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 format: "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
237void 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(id: origin)) ? origin : 0;
251 ReportUMR(stack: &stack, origin: report_origin);
252
253 if (__msan_get_track_origins() && !Origin::isValidId(id: origin)) {
254 Printf(
255 format: " 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
261void UnpoisonParam(uptr n) {
262 internal_memset(s: __msan_param_tls, c: 0, n: 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.
269void ScopedThreadLocalStateBackup::Backup() {
270 va_arg_overflow_size_tls = __msan_va_arg_overflow_size_tls;
271}
272
273void 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(s: __msan_param_tls, c: 0, n: sizeof(__msan_param_tls));
278 internal_memset(s: __msan_retval_tls, c: 0, n: sizeof(__msan_retval_tls));
279 internal_memset(s: __msan_va_arg_tls, c: 0, n: sizeof(__msan_va_arg_tls));
280 internal_memset(s: __msan_va_arg_origin_tls, c: 0,
281 n: sizeof(__msan_va_arg_origin_tls));
282
283 if (__msan_get_track_origins()) {
284 internal_memset(s: &__msan_retval_origin_tls, c: 0,
285 n: sizeof(__msan_retval_origin_tls));
286 internal_memset(s: __msan_param_origin_tls, c: 0,
287 n: sizeof(__msan_param_origin_tls));
288 }
289}
290
291void UnpoisonThreadLocalState() {
292}
293
294const char *GetStackOriginDescr(u32 id, uptr *pc) {
295 CHECK_LT(id, kNumStackOriginDescrs);
296 if (pc) *pc = StackOriginPC[id];
297 return StackOriginDescr[id];
298}
299
300u32 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(prev: 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)).
316static 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(a: &NumStackOriginDescrs, v: 1, mo: memory_order_relaxed);
324 CHECK_LT(idx, kNumStackOriginDescrs);
325 StackOriginDescr[idx] = descr;
326 StackOriginPC[idx] = pc;
327 id = Origin::CreateStackOrigin(id: idx).raw_id();
328 *id_ptr = id;
329 }
330 __msan_set_origin(a, size, origin: id);
331}
332
333} // namespace __msan
334
335void __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_unwind: request_fast)) {
340 // Block reports from our interceptors during _Unwind_Backtrace.
341 UnwinderScope sym_scope;
342 return Unwind(max_depth, pc, bp, context, stack_top: t ? t->stack_top() : 0,
343 stack_bottom: t ? t->stack_bottom() : 0, request_fast_unwind: false);
344 }
345 if (StackTrace::WillUseFastUnwind(request_fast_unwind: request_fast))
346 Unwind(max_depth, pc, bp, context: nullptr, stack_top: t->stack_top(), stack_bottom: t->stack_bottom(), request_fast_unwind: true);
347 else
348 Unwind(max_depth, pc, bp: 0, context, stack_top: 0, stack_bottom: 0, request_fast_unwind: false);
349}
350
351// Interface.
352
353using namespace __msan;
354
355// N.B. Only [shadow, shadow+size) is defined. shadow is *not* a pointer into
356// an MSan shadow region.
357static void print_shadow_value(void *shadow, u64 size) {
358 Printf(format: "Shadow value (%llu byte%s):", size, size == 1 ? "" : "s");
359 for (unsigned int i = 0; i < size; i++) {
360 if (i % 4 == 0)
361 Printf(format: " ");
362
363 unsigned char x = ((unsigned char *)shadow)[i];
364 Printf(format: "%x%x", x >> 4, x & 0xf);
365 }
366 Printf(format: "\n");
367 Printf(
368 format: "Caveat: the shadow value does not necessarily directly correspond to a "
369 "single user variable. The correspondence is stronger, but not always "
370 "perfect, when origin tracking is enabled.\n");
371 Printf(format: "\n");
372}
373
374#define MSAN_MAYBE_WARNING(type, size) \
375 void __msan_maybe_warning_##size(type s, u32 o) { \
376 GET_CALLER_PC_BP; \
377 \
378 if (UNLIKELY(s)) { \
379 if (Verbosity() >= 1) \
380 print_shadow_value((void *)(&s), sizeof(s)); \
381 PrintWarningWithOrigin(pc, bp, o); \
382 if (__msan::flags()->halt_on_error) { \
383 Printf("Exiting\n"); \
384 Die(); \
385 } \
386 } \
387 }
388
389MSAN_MAYBE_WARNING(u8, 1)
390MSAN_MAYBE_WARNING(u16, 2)
391MSAN_MAYBE_WARNING(u32, 4)
392MSAN_MAYBE_WARNING(u64, 8)
393
394// N.B. Only [shadow, shadow+size) is defined. shadow is *not* a pointer into
395// an MSan shadow region.
396void __msan_maybe_warning_N(void *shadow, u64 size, u32 o) {
397 GET_CALLER_PC_BP;
398
399 bool allZero = true;
400 for (unsigned int i = 0; i < size; i++) {
401 if (((char *)shadow)[i]) {
402 allZero = false;
403 break;
404 }
405 }
406
407 if (UNLIKELY(!allZero)) {
408 if (Verbosity() >= 1)
409 print_shadow_value(shadow, size);
410 PrintWarningWithOrigin(pc, bp, origin: o);
411 if (__msan::flags()->halt_on_error) {
412 Printf(format: "Exiting\n");
413 Die();
414 }
415 }
416}
417
418#define MSAN_MAYBE_STORE_ORIGIN(type, size) \
419 void __msan_maybe_store_origin_##size(type s, void *p, u32 o) { \
420 if (UNLIKELY(s)) { \
421 if (__msan_get_track_origins() > 1) { \
422 GET_CALLER_PC_BP; \
423 GET_STORE_STACK_TRACE_PC_BP(pc, bp); \
424 o = ChainOrigin(o, &stack); \
425 } \
426 *(u32 *)MEM_TO_ORIGIN((uptr)p & ~3UL) = o; \
427 } \
428 }
429
430MSAN_MAYBE_STORE_ORIGIN(u8, 1)
431MSAN_MAYBE_STORE_ORIGIN(u16, 2)
432MSAN_MAYBE_STORE_ORIGIN(u32, 4)
433MSAN_MAYBE_STORE_ORIGIN(u64, 8)
434
435void __msan_warning() {
436 GET_CALLER_PC_BP;
437 PrintWarningWithOrigin(pc, bp, origin: 0);
438 if (__msan::flags()->halt_on_error) {
439 if (__msan::flags()->print_stats)
440 ReportStats();
441 Printf(format: "Exiting\n");
442 Die();
443 }
444}
445
446void __msan_warning_noreturn() {
447 GET_CALLER_PC_BP;
448 PrintWarningWithOrigin(pc, bp, origin: 0);
449 if (__msan::flags()->print_stats)
450 ReportStats();
451 Printf(format: "Exiting\n");
452 Die();
453}
454
455void __msan_warning_with_origin(u32 origin) {
456 GET_CALLER_PC_BP;
457 PrintWarningWithOrigin(pc, bp, origin);
458 if (__msan::flags()->halt_on_error) {
459 if (__msan::flags()->print_stats)
460 ReportStats();
461 Printf(format: "Exiting\n");
462 Die();
463 }
464}
465
466void __msan_warning_with_origin_noreturn(u32 origin) {
467 GET_CALLER_PC_BP;
468 PrintWarningWithOrigin(pc, bp, origin);
469 if (__msan::flags()->print_stats)
470 ReportStats();
471 Printf(format: "Exiting\n");
472 Die();
473}
474
475static void OnStackUnwind(const SignalContext &sig, const void *,
476 BufferedStackTrace *stack) {
477 stack->Unwind(pc: StackTrace::GetNextInstructionPc(pc: sig.pc), bp: sig.bp, context: sig.context,
478 request_fast: common_flags()->fast_unwind_on_fatal);
479}
480
481static void MsanOnDeadlySignal(int signo, void *siginfo, void *context) {
482 HandleDeadlySignal(siginfo, context, tid: GetTid(), unwind: &OnStackUnwind, unwind_context: nullptr);
483}
484
485static void CheckUnwind() {
486 GET_FATAL_STACK_TRACE_PC_BP(StackTrace::GetCurrentPc(), GET_CURRENT_FRAME());
487 stack.Print();
488}
489
490void __msan_init() {
491 CHECK(!msan_init_is_running);
492 if (msan_inited) return;
493 msan_init_is_running = 1;
494 SanitizerToolName = "MemorySanitizer";
495
496 AvoidCVE_2016_2143();
497
498 CacheBinaryName();
499 InitializeFlags();
500
501 // Install tool-specific callbacks in sanitizer_common.
502 SetCheckUnwindCallback(CheckUnwind);
503
504 __sanitizer_set_report_path(path: common_flags()->log_path);
505
506 InitializePlatformEarly();
507
508 InitializeInterceptors();
509 InstallAtForkHandler();
510 CheckASLR();
511 InstallDeadlySignalHandlers(handler: MsanOnDeadlySignal);
512 InstallAtExitHandler(); // Needs __cxa_atexit interceptor.
513
514 DisableCoreDumperIfNecessary();
515 if (StackSizeIsUnlimited()) {
516 VPrintf(1, "Unlimited stack, doing reexec\n");
517 // A reasonably large stack size. It is bigger than the usual 8Mb, because,
518 // well, the program could have been run with unlimited stack for a reason.
519 SetStackSizeLimitInBytes(32 * 1024 * 1024);
520 ReExec();
521 }
522
523 __msan_clear_on_return();
524 if (__msan_get_track_origins())
525 VPrintf(1, "msan_track_origins\n");
526 if (!InitShadowWithReExec(init_origins: __msan_get_track_origins())) {
527 Printf(format: "FATAL: MemorySanitizer can not mmap the shadow memory.\n");
528 Printf(format: "FATAL: Make sure to compile with -fPIE and to link with -pie.\n");
529 Printf(format: "FATAL: Disabling ASLR is known to cause this error.\n");
530 Printf(format: "FATAL: If running under GDB, try "
531 "'set disable-randomization off'.\n");
532 DumpProcessMap();
533 Die();
534 }
535
536 Symbolizer::GetOrInit()->AddHooks(start_hook: EnterSymbolizerOrUnwider,
537 end_hook: ExitSymbolizerOrUnwider);
538
539 InitializeCoverage(enabled: common_flags()->coverage, coverage_dir: common_flags()->coverage_dir);
540
541 MsanTSDInit(destructor: MsanTSDDtor);
542
543 MsanAllocatorInit();
544
545 MsanThread *main_thread = MsanThread::Create(start_routine: nullptr, arg: nullptr);
546 SetCurrentThread(main_thread);
547 main_thread->Init();
548
549#if MSAN_CONTAINS_UBSAN
550 __ubsan::InitAsPlugin();
551#endif
552
553 VPrintf(1, "MemorySanitizer init done\n");
554
555 msan_init_is_running = 0;
556 msan_inited = 1;
557}
558
559void __msan_set_keep_going(int keep_going) {
560 flags()->halt_on_error = !keep_going;
561}
562
563void __msan_set_expect_umr(int expect_umr) {
564 if (expect_umr) {
565 msan_expected_umr_found = 0;
566 } else if (!msan_expected_umr_found) {
567 GET_CALLER_PC_BP;
568 GET_FATAL_STACK_TRACE_PC_BP(pc, bp);
569 ReportExpectedUMRNotFound(stack: &stack);
570 Die();
571 }
572 msan_expect_umr = expect_umr;
573}
574
575void __msan_print_shadow(const void *x, uptr size) {
576 if (!MEM_IS_APP(x)) {
577 Printf(format: "Not a valid application address: %p\n", x);
578 return;
579 }
580
581 DescribeMemoryRange(x, size);
582}
583
584void __msan_dump_shadow(const void *x, uptr size) {
585 if (!MEM_IS_APP(x)) {
586 Printf(format: "Not a valid application address: %p\n", x);
587 return;
588 }
589
590 unsigned char *s = (unsigned char*)MEM_TO_SHADOW(x);
591 Printf(format: "%p[%p] ", (void *)s, x);
592 for (uptr i = 0; i < size; i++)
593 Printf(format: "%x%x ", s[i] >> 4, s[i] & 0xf);
594 Printf(format: "\n");
595}
596
597sptr __msan_test_shadow(const void *x, uptr size) {
598 if (!MEM_IS_APP(x)) return -1;
599 unsigned char *s = (unsigned char *)MEM_TO_SHADOW((uptr)x);
600 if (__sanitizer::mem_is_zero(mem: (const char *)s, size))
601 return -1;
602 // Slow path: loop through again to find the location.
603 for (uptr i = 0; i < size; ++i)
604 if (s[i])
605 return i;
606 return -1;
607}
608
609void __msan_check_mem_is_initialized(const void *x, uptr size) {
610 if (!__msan::flags()->report_umrs) return;
611 sptr offset = __msan_test_shadow(x, size);
612 if (offset < 0)
613 return;
614
615 GET_CALLER_PC_BP;
616 ReportUMRInsideAddressRange(function: __func__, start: x, size, offset);
617 __msan::PrintWarningWithOrigin(pc, bp,
618 origin: __msan_get_origin(a: ((const char *)x) + offset));
619 if (__msan::flags()->halt_on_error) {
620 Printf(format: "Exiting\n");
621 Die();
622 }
623}
624
625int __msan_set_poison_in_malloc(int do_poison) {
626 int old = flags()->poison_in_malloc;
627 flags()->poison_in_malloc = do_poison;
628 return old;
629}
630
631int __msan_has_dynamic_component() { return false; }
632
633NOINLINE
634void __msan_clear_on_return() {
635 __msan_param_tls[0] = 0;
636}
637
638void __msan_partial_poison(const void* data, void* shadow, uptr size) {
639 internal_memcpy(dest: (void*)MEM_TO_SHADOW((uptr)data), src: shadow, n: size);
640}
641
642void __msan_load_unpoisoned(const void *src, uptr size, void *dst) {
643 internal_memcpy(dest: dst, src, n: size);
644 __msan_unpoison(a: dst, size);
645}
646
647void __msan_set_origin(const void *a, uptr size, u32 origin) {
648 if (__msan_get_track_origins()) SetOrigin(dst: a, size, origin);
649}
650
651void __msan_set_alloca_origin(void *a, uptr size, char *descr) {
652 SetAllocaOrigin(a, size, id_ptr: reinterpret_cast<u32 *>(descr), descr: descr + 4,
653 GET_CALLER_PC());
654}
655
656void __msan_set_alloca_origin4(void *a, uptr size, char *descr, uptr pc) {
657 // Intentionally ignore pc and use return address. This function is here for
658 // compatibility, in case program is linked with library instrumented by
659 // older clang.
660 SetAllocaOrigin(a, size, id_ptr: reinterpret_cast<u32 *>(descr), descr: descr + 4,
661 GET_CALLER_PC());
662}
663
664void __msan_set_alloca_origin_with_descr(void *a, uptr size, u32 *id_ptr,
665 char *descr) {
666 SetAllocaOrigin(a, size, id_ptr, descr, GET_CALLER_PC());
667}
668
669void __msan_set_alloca_origin_no_descr(void *a, uptr size, u32 *id_ptr) {
670 SetAllocaOrigin(a, size, id_ptr, descr: nullptr, GET_CALLER_PC());
671}
672
673u32 __msan_chain_origin(u32 id) {
674 GET_CALLER_PC_BP;
675 GET_STORE_STACK_TRACE_PC_BP(pc, bp);
676 return ChainOrigin(id, stack: &stack);
677}
678
679u32 __msan_get_origin(const void *a) {
680 if (!__msan_get_track_origins()) return 0;
681 uptr x = (uptr)a;
682 uptr aligned = x & ~3ULL;
683 uptr origin_ptr = MEM_TO_ORIGIN(aligned);
684 return *(u32*)origin_ptr;
685}
686
687int __msan_origin_is_descendant_or_same(u32 this_id, u32 prev_id) {
688 Origin o = Origin::FromRawId(id: this_id);
689 while (o.raw_id() != prev_id && o.isChainedOrigin())
690 o = o.getNextChainedOrigin(stack: nullptr);
691 return o.raw_id() == prev_id;
692}
693
694u32 __msan_get_umr_origin() {
695 return __msan_origin_tls;
696}
697
698u16 __sanitizer_unaligned_load16(const uu16 *p) {
699 internal_memcpy(dest: &__msan_retval_tls[0], src: (void *)MEM_TO_SHADOW((uptr)p),
700 n: sizeof(uu16));
701 if (__msan_get_track_origins())
702 __msan_retval_origin_tls = GetOriginIfPoisoned(addr: (uptr)p, size: sizeof(*p));
703 return *p;
704}
705u32 __sanitizer_unaligned_load32(const uu32 *p) {
706 internal_memcpy(dest: &__msan_retval_tls[0], src: (void *)MEM_TO_SHADOW((uptr)p),
707 n: sizeof(uu32));
708 if (__msan_get_track_origins())
709 __msan_retval_origin_tls = GetOriginIfPoisoned(addr: (uptr)p, size: sizeof(*p));
710 return *p;
711}
712u64 __sanitizer_unaligned_load64(const uu64 *p) {
713 internal_memcpy(dest: &__msan_retval_tls[0], src: (void *)MEM_TO_SHADOW((uptr)p),
714 n: sizeof(uu64));
715 if (__msan_get_track_origins())
716 __msan_retval_origin_tls = GetOriginIfPoisoned(addr: (uptr)p, size: sizeof(*p));
717 return *p;
718}
719void __sanitizer_unaligned_store16(uu16 *p, u16 x) {
720 static_assert(sizeof(uu16) == sizeof(u16), "incompatible types");
721 u16 s;
722 internal_memcpy(dest: &s, src: &__msan_param_tls[1], n: sizeof(uu16));
723 internal_memcpy(dest: (void *)MEM_TO_SHADOW((uptr)p), src: &s, n: sizeof(uu16));
724 if (s && __msan_get_track_origins())
725 if (uu32 o = __msan_param_origin_tls[2])
726 SetOriginIfPoisoned(addr: (uptr)p, src_shadow: (uptr)&s, size: sizeof(s), src_origin: o);
727 *p = x;
728}
729void __sanitizer_unaligned_store32(uu32 *p, u32 x) {
730 static_assert(sizeof(uu32) == sizeof(u32), "incompatible types");
731 u32 s;
732 internal_memcpy(dest: &s, src: &__msan_param_tls[1], n: sizeof(uu32));
733 internal_memcpy(dest: (void *)MEM_TO_SHADOW((uptr)p), src: &s, n: sizeof(uu32));
734 if (s && __msan_get_track_origins())
735 if (uu32 o = __msan_param_origin_tls[2])
736 SetOriginIfPoisoned(addr: (uptr)p, src_shadow: (uptr)&s, size: sizeof(s), src_origin: o);
737 *p = x;
738}
739void __sanitizer_unaligned_store64(uu64 *p, u64 x) {
740 u64 s = __msan_param_tls[1];
741 *(uu64 *)MEM_TO_SHADOW((uptr)p) = s;
742 if (s && __msan_get_track_origins())
743 if (uu32 o = __msan_param_origin_tls[2])
744 SetOriginIfPoisoned(addr: (uptr)p, src_shadow: (uptr)&s, size: sizeof(s), src_origin: o);
745 *p = x;
746}
747
748void __msan_set_death_callback(void (*callback)(void)) {
749 SetUserDieCallback(callback);
750}
751
752void __msan_start_switch_fiber(const void *bottom, uptr size) {
753 MsanThread *t = GetCurrentThread();
754 if (!t) {
755 VReport(1, "__msan_start_switch_fiber called from unknown thread\n");
756 return;
757 }
758 t->StartSwitchFiber(bottom: (uptr)bottom, size);
759}
760
761void __msan_finish_switch_fiber(const void **bottom_old, uptr *size_old) {
762 MsanThread *t = GetCurrentThread();
763 if (!t) {
764 VReport(1, "__msan_finish_switch_fiber called from unknown thread\n");
765 return;
766 }
767 t->FinishSwitchFiber(bottom_old: (uptr *)bottom_old, size_old: (uptr *)size_old);
768
769 internal_memset(s: __msan_param_tls, c: 0, n: sizeof(__msan_param_tls));
770 internal_memset(s: __msan_retval_tls, c: 0, n: sizeof(__msan_retval_tls));
771 internal_memset(s: __msan_va_arg_tls, c: 0, n: sizeof(__msan_va_arg_tls));
772
773 if (__msan_get_track_origins()) {
774 internal_memset(s: __msan_param_origin_tls, c: 0,
775 n: sizeof(__msan_param_origin_tls));
776 internal_memset(s: &__msan_retval_origin_tls, c: 0,
777 n: sizeof(__msan_retval_origin_tls));
778 internal_memset(s: __msan_va_arg_origin_tls, c: 0,
779 n: sizeof(__msan_va_arg_origin_tls));
780 }
781}
782
783SANITIZER_INTERFACE_WEAK_DEF(const char *, __msan_default_options, void) {
784 return "";
785}
786
787extern "C" {
788SANITIZER_INTERFACE_ATTRIBUTE
789void __sanitizer_print_stack_trace() {
790 GET_FATAL_STACK_TRACE_PC_BP(StackTrace::GetCurrentPc(), GET_CURRENT_FRAME());
791 stack.Print();
792}
793} // extern "C"
794