msan.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745
  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. #include "msan.h"
  14. #include "msan_chained_origin_depot.h"
  15. #include "msan_origin.h"
  16. #include "msan_poisoning.h"
  17. #include "msan_report.h"
  18. #include "msan_thread.h"
  19. #include "sanitizer_common/sanitizer_atomic.h"
  20. #include "sanitizer_common/sanitizer_common.h"
  21. #include "sanitizer_common/sanitizer_flag_parser.h"
  22. #include "sanitizer_common/sanitizer_flags.h"
  23. #include "sanitizer_common/sanitizer_interface_internal.h"
  24. #include "sanitizer_common/sanitizer_libc.h"
  25. #include "sanitizer_common/sanitizer_procmaps.h"
  26. #include "sanitizer_common/sanitizer_stackdepot.h"
  27. #include "sanitizer_common/sanitizer_stacktrace.h"
  28. #include "sanitizer_common/sanitizer_symbolizer.h"
  29. #include "ubsan/ubsan_flags.h"
  30. #include "ubsan/ubsan_init.h"
  31. // ACHTUNG! No system header includes in this file.
  32. using namespace __sanitizer;
  33. // Globals.
  34. static THREADLOCAL int msan_expect_umr = 0;
  35. static THREADLOCAL int msan_expected_umr_found = 0;
  36. // Function argument shadow. Each argument starts at the next available 8-byte
  37. // aligned address.
  38. SANITIZER_INTERFACE_ATTRIBUTE
  39. THREADLOCAL u64 __msan_param_tls[kMsanParamTlsSize / sizeof(u64)];
  40. // Function argument origin. Each argument starts at the same offset as the
  41. // corresponding shadow in (__msan_param_tls). Slightly weird, but changing this
  42. // would break compatibility with older prebuilt binaries.
  43. SANITIZER_INTERFACE_ATTRIBUTE
  44. THREADLOCAL u32 __msan_param_origin_tls[kMsanParamTlsSize / sizeof(u32)];
  45. SANITIZER_INTERFACE_ATTRIBUTE
  46. THREADLOCAL u64 __msan_retval_tls[kMsanRetvalTlsSize / sizeof(u64)];
  47. SANITIZER_INTERFACE_ATTRIBUTE
  48. THREADLOCAL u32 __msan_retval_origin_tls;
  49. SANITIZER_INTERFACE_ATTRIBUTE
  50. ALIGNED(16) THREADLOCAL u64 __msan_va_arg_tls[kMsanParamTlsSize / sizeof(u64)];
  51. SANITIZER_INTERFACE_ATTRIBUTE
  52. ALIGNED(16)
  53. THREADLOCAL u32 __msan_va_arg_origin_tls[kMsanParamTlsSize / sizeof(u32)];
  54. SANITIZER_INTERFACE_ATTRIBUTE
  55. THREADLOCAL u64 __msan_va_arg_overflow_size_tls;
  56. SANITIZER_INTERFACE_ATTRIBUTE
  57. THREADLOCAL u32 __msan_origin_tls;
  58. extern "C" SANITIZER_WEAK_ATTRIBUTE const int __msan_track_origins;
  59. int __msan_get_track_origins() {
  60. return &__msan_track_origins ? __msan_track_origins : 0;
  61. }
  62. extern "C" SANITIZER_WEAK_ATTRIBUTE const int __msan_keep_going;
  63. namespace __msan {
  64. static THREADLOCAL int is_in_symbolizer_or_unwinder;
  65. static void EnterSymbolizerOrUnwider() { ++is_in_symbolizer_or_unwinder; }
  66. static void ExitSymbolizerOrUnwider() { --is_in_symbolizer_or_unwinder; }
  67. bool IsInSymbolizerOrUnwider() { return is_in_symbolizer_or_unwinder; }
  68. struct UnwinderScope {
  69. UnwinderScope() { EnterSymbolizerOrUnwider(); }
  70. ~UnwinderScope() { ExitSymbolizerOrUnwider(); }
  71. };
  72. static Flags msan_flags;
  73. Flags *flags() { return &msan_flags; }
  74. int msan_inited = 0;
  75. bool msan_init_is_running;
  76. int msan_report_count = 0;
  77. // Array of stack origins.
  78. // FIXME: make it resizable.
  79. static const uptr kNumStackOriginDescrs = 1024 * 1024;
  80. static const char *StackOriginDescr[kNumStackOriginDescrs];
  81. static uptr StackOriginPC[kNumStackOriginDescrs];
  82. static atomic_uint32_t NumStackOriginDescrs;
  83. void Flags::SetDefaults() {
  84. #define MSAN_FLAG(Type, Name, DefaultValue, Description) Name = DefaultValue;
  85. #include "msan_flags.inc"
  86. #undef MSAN_FLAG
  87. }
  88. // keep_going is an old name for halt_on_error,
  89. // and it has inverse meaning.
  90. class FlagHandlerKeepGoing final : public FlagHandlerBase {
  91. bool *halt_on_error_;
  92. public:
  93. explicit FlagHandlerKeepGoing(bool *halt_on_error)
  94. : halt_on_error_(halt_on_error) {}
  95. bool Parse(const char *value) final {
  96. bool tmp;
  97. FlagHandler<bool> h(&tmp);
  98. if (!h.Parse(value)) return false;
  99. *halt_on_error_ = !tmp;
  100. return true;
  101. }
  102. bool Format(char *buffer, uptr size) final {
  103. const char *keep_going_str = (*halt_on_error_) ? "false" : "true";
  104. return FormatString(buffer, size, keep_going_str);
  105. }
  106. };
  107. static void RegisterMsanFlags(FlagParser *parser, Flags *f) {
  108. #define MSAN_FLAG(Type, Name, DefaultValue, Description) \
  109. RegisterFlag(parser, #Name, Description, &f->Name);
  110. #include "msan_flags.inc"
  111. #undef MSAN_FLAG
  112. FlagHandlerKeepGoing *fh_keep_going =
  113. new (FlagParser::Alloc) FlagHandlerKeepGoing(&f->halt_on_error);
  114. parser->RegisterHandler("keep_going", fh_keep_going,
  115. "deprecated, use halt_on_error");
  116. }
  117. static void InitializeFlags() {
  118. SetCommonFlagsDefaults();
  119. {
  120. CommonFlags cf;
  121. cf.CopyFrom(*common_flags());
  122. cf.external_symbolizer_path = GetEnv("MSAN_SYMBOLIZER_PATH");
  123. cf.malloc_context_size = 20;
  124. cf.handle_ioctl = true;
  125. // FIXME: test and enable.
  126. cf.check_printf = false;
  127. cf.intercept_tls_get_addr = true;
  128. OverrideCommonFlags(cf);
  129. }
  130. Flags *f = flags();
  131. f->SetDefaults();
  132. FlagParser parser;
  133. RegisterMsanFlags(&parser, f);
  134. RegisterCommonFlags(&parser);
  135. #if MSAN_CONTAINS_UBSAN
  136. __ubsan::Flags *uf = __ubsan::flags();
  137. uf->SetDefaults();
  138. FlagParser ubsan_parser;
  139. __ubsan::RegisterUbsanFlags(&ubsan_parser, uf);
  140. RegisterCommonFlags(&ubsan_parser);
  141. #endif
  142. // Override from user-specified string.
  143. parser.ParseString(__msan_default_options());
  144. #if MSAN_CONTAINS_UBSAN
  145. const char *ubsan_default_options = __ubsan_default_options();
  146. ubsan_parser.ParseString(ubsan_default_options);
  147. #endif
  148. parser.ParseStringFromEnv("MSAN_OPTIONS");
  149. #if MSAN_CONTAINS_UBSAN
  150. ubsan_parser.ParseStringFromEnv("UBSAN_OPTIONS");
  151. #endif
  152. InitializeCommonFlags();
  153. if (Verbosity()) ReportUnrecognizedFlags();
  154. if (common_flags()->help) parser.PrintFlagDescriptions();
  155. // Check if deprecated exit_code MSan flag is set.
  156. if (f->exit_code != -1) {
  157. if (Verbosity())
  158. Printf("MSAN_OPTIONS=exit_code is deprecated! "
  159. "Please use MSAN_OPTIONS=exitcode instead.\n");
  160. CommonFlags cf;
  161. cf.CopyFrom(*common_flags());
  162. cf.exitcode = f->exit_code;
  163. OverrideCommonFlags(cf);
  164. }
  165. // Check flag values:
  166. if (f->origin_history_size < 0 ||
  167. f->origin_history_size > Origin::kMaxDepth) {
  168. Printf(
  169. "Origin history size invalid: %d. Must be 0 (unlimited) or in [1, %d] "
  170. "range.\n",
  171. f->origin_history_size, Origin::kMaxDepth);
  172. Die();
  173. }
  174. // Limiting to kStackDepotMaxUseCount / 2 to avoid overflow in
  175. // StackDepotHandle::inc_use_count_unsafe.
  176. if (f->origin_history_per_stack_limit < 0 ||
  177. f->origin_history_per_stack_limit > kStackDepotMaxUseCount / 2) {
  178. Printf(
  179. "Origin per-stack limit invalid: %d. Must be 0 (unlimited) or in [1, "
  180. "%d] range.\n",
  181. f->origin_history_per_stack_limit, kStackDepotMaxUseCount / 2);
  182. Die();
  183. }
  184. if (f->store_context_size < 1) f->store_context_size = 1;
  185. }
  186. void PrintWarningWithOrigin(uptr pc, uptr bp, u32 origin) {
  187. if (msan_expect_umr) {
  188. // Printf("Expected UMR\n");
  189. __msan_origin_tls = origin;
  190. msan_expected_umr_found = 1;
  191. return;
  192. }
  193. ++msan_report_count;
  194. GET_FATAL_STACK_TRACE_PC_BP(pc, bp);
  195. u32 report_origin =
  196. (__msan_get_track_origins() && Origin::isValidId(origin)) ? origin : 0;
  197. ReportUMR(&stack, report_origin);
  198. if (__msan_get_track_origins() && !Origin::isValidId(origin)) {
  199. Printf(
  200. " ORIGIN: invalid (%x). Might be a bug in MemorySanitizer origin "
  201. "tracking.\n This could still be a bug in your code, too!\n",
  202. origin);
  203. }
  204. }
  205. void UnpoisonParam(uptr n) {
  206. internal_memset(__msan_param_tls, 0, n * sizeof(*__msan_param_tls));
  207. }
  208. // Backup MSan runtime TLS state.
  209. // Implementation must be async-signal-safe.
  210. // Instances of this class may live on the signal handler stack, and data size
  211. // may be an issue.
  212. void ScopedThreadLocalStateBackup::Backup() {
  213. va_arg_overflow_size_tls = __msan_va_arg_overflow_size_tls;
  214. }
  215. void ScopedThreadLocalStateBackup::Restore() {
  216. // A lame implementation that only keeps essential state and resets the rest.
  217. __msan_va_arg_overflow_size_tls = va_arg_overflow_size_tls;
  218. internal_memset(__msan_param_tls, 0, sizeof(__msan_param_tls));
  219. internal_memset(__msan_retval_tls, 0, sizeof(__msan_retval_tls));
  220. internal_memset(__msan_va_arg_tls, 0, sizeof(__msan_va_arg_tls));
  221. internal_memset(__msan_va_arg_origin_tls, 0,
  222. sizeof(__msan_va_arg_origin_tls));
  223. if (__msan_get_track_origins()) {
  224. internal_memset(&__msan_retval_origin_tls, 0,
  225. sizeof(__msan_retval_origin_tls));
  226. internal_memset(__msan_param_origin_tls, 0,
  227. sizeof(__msan_param_origin_tls));
  228. }
  229. }
  230. void UnpoisonThreadLocalState() {
  231. }
  232. const char *GetStackOriginDescr(u32 id, uptr *pc) {
  233. CHECK_LT(id, kNumStackOriginDescrs);
  234. if (pc) *pc = StackOriginPC[id];
  235. return StackOriginDescr[id];
  236. }
  237. u32 ChainOrigin(u32 id, StackTrace *stack) {
  238. MsanThread *t = GetCurrentThread();
  239. if (t && t->InSignalHandler())
  240. return id;
  241. Origin o = Origin::FromRawId(id);
  242. stack->tag = StackTrace::TAG_UNKNOWN;
  243. Origin chained = Origin::CreateChainedOrigin(o, stack);
  244. return chained.raw_id();
  245. }
  246. // Current implementation separates the 'id_ptr' from the 'descr' and makes
  247. // 'descr' constant.
  248. // Previous implementation 'descr' is created at compile time and contains
  249. // '----' in the beginning. When we see descr for the first time we replace
  250. // '----' with a uniq id and set the origin to (id | (31-th bit)).
  251. static inline void SetAllocaOrigin(void *a, uptr size, u32 *id_ptr, char *descr,
  252. uptr pc) {
  253. static const u32 dash = '-';
  254. static const u32 first_timer =
  255. dash + (dash << 8) + (dash << 16) + (dash << 24);
  256. u32 id = *id_ptr;
  257. if (id == 0 || id == first_timer) {
  258. u32 idx = atomic_fetch_add(&NumStackOriginDescrs, 1, memory_order_relaxed);
  259. CHECK_LT(idx, kNumStackOriginDescrs);
  260. StackOriginDescr[idx] = descr;
  261. StackOriginPC[idx] = pc;
  262. id = Origin::CreateStackOrigin(idx).raw_id();
  263. *id_ptr = id;
  264. }
  265. __msan_set_origin(a, size, id);
  266. }
  267. } // namespace __msan
  268. void __sanitizer::BufferedStackTrace::UnwindImpl(
  269. uptr pc, uptr bp, void *context, bool request_fast, u32 max_depth) {
  270. using namespace __msan;
  271. MsanThread *t = GetCurrentThread();
  272. if (!t || !StackTrace::WillUseFastUnwind(request_fast)) {
  273. // Block reports from our interceptors during _Unwind_Backtrace.
  274. UnwinderScope sym_scope;
  275. return Unwind(max_depth, pc, bp, context, t ? t->stack_top() : 0,
  276. t ? t->stack_bottom() : 0, false);
  277. }
  278. if (StackTrace::WillUseFastUnwind(request_fast))
  279. Unwind(max_depth, pc, bp, nullptr, t->stack_top(), t->stack_bottom(), true);
  280. else
  281. Unwind(max_depth, pc, 0, context, 0, 0, false);
  282. }
  283. // Interface.
  284. using namespace __msan;
  285. #define MSAN_MAYBE_WARNING(type, size) \
  286. void __msan_maybe_warning_##size(type s, u32 o) { \
  287. GET_CALLER_PC_BP_SP; \
  288. (void) sp; \
  289. if (UNLIKELY(s)) { \
  290. PrintWarningWithOrigin(pc, bp, o); \
  291. if (__msan::flags()->halt_on_error) { \
  292. Printf("Exiting\n"); \
  293. Die(); \
  294. } \
  295. } \
  296. }
  297. MSAN_MAYBE_WARNING(u8, 1)
  298. MSAN_MAYBE_WARNING(u16, 2)
  299. MSAN_MAYBE_WARNING(u32, 4)
  300. MSAN_MAYBE_WARNING(u64, 8)
  301. #define MSAN_MAYBE_STORE_ORIGIN(type, size) \
  302. void __msan_maybe_store_origin_##size(type s, void *p, u32 o) { \
  303. if (UNLIKELY(s)) { \
  304. if (__msan_get_track_origins() > 1) { \
  305. GET_CALLER_PC_BP_SP; \
  306. (void) sp; \
  307. GET_STORE_STACK_TRACE_PC_BP(pc, bp); \
  308. o = ChainOrigin(o, &stack); \
  309. } \
  310. *(u32 *)MEM_TO_ORIGIN((uptr)p & ~3UL) = o; \
  311. } \
  312. }
  313. MSAN_MAYBE_STORE_ORIGIN(u8, 1)
  314. MSAN_MAYBE_STORE_ORIGIN(u16, 2)
  315. MSAN_MAYBE_STORE_ORIGIN(u32, 4)
  316. MSAN_MAYBE_STORE_ORIGIN(u64, 8)
  317. void __msan_warning() {
  318. GET_CALLER_PC_BP_SP;
  319. (void)sp;
  320. PrintWarningWithOrigin(pc, bp, 0);
  321. if (__msan::flags()->halt_on_error) {
  322. if (__msan::flags()->print_stats)
  323. ReportStats();
  324. Printf("Exiting\n");
  325. Die();
  326. }
  327. }
  328. void __msan_warning_noreturn() {
  329. GET_CALLER_PC_BP_SP;
  330. (void)sp;
  331. PrintWarningWithOrigin(pc, bp, 0);
  332. if (__msan::flags()->print_stats)
  333. ReportStats();
  334. Printf("Exiting\n");
  335. Die();
  336. }
  337. void __msan_warning_with_origin(u32 origin) {
  338. GET_CALLER_PC_BP_SP;
  339. (void)sp;
  340. PrintWarningWithOrigin(pc, bp, origin);
  341. if (__msan::flags()->halt_on_error) {
  342. if (__msan::flags()->print_stats)
  343. ReportStats();
  344. Printf("Exiting\n");
  345. Die();
  346. }
  347. }
  348. void __msan_warning_with_origin_noreturn(u32 origin) {
  349. GET_CALLER_PC_BP_SP;
  350. (void)sp;
  351. PrintWarningWithOrigin(pc, bp, origin);
  352. if (__msan::flags()->print_stats)
  353. ReportStats();
  354. Printf("Exiting\n");
  355. Die();
  356. }
  357. static void OnStackUnwind(const SignalContext &sig, const void *,
  358. BufferedStackTrace *stack) {
  359. stack->Unwind(StackTrace::GetNextInstructionPc(sig.pc), sig.bp, sig.context,
  360. common_flags()->fast_unwind_on_fatal);
  361. }
  362. static void MsanOnDeadlySignal(int signo, void *siginfo, void *context) {
  363. HandleDeadlySignal(siginfo, context, GetTid(), &OnStackUnwind, nullptr);
  364. }
  365. static void CheckUnwind() {
  366. GET_FATAL_STACK_TRACE_PC_BP(StackTrace::GetCurrentPc(), GET_CURRENT_FRAME());
  367. stack.Print();
  368. }
  369. void __msan_init() {
  370. CHECK(!msan_init_is_running);
  371. if (msan_inited) return;
  372. msan_init_is_running = 1;
  373. SanitizerToolName = "MemorySanitizer";
  374. AvoidCVE_2016_2143();
  375. CacheBinaryName();
  376. InitializeFlags();
  377. // Install tool-specific callbacks in sanitizer_common.
  378. SetCheckUnwindCallback(CheckUnwind);
  379. __sanitizer_set_report_path(common_flags()->log_path);
  380. InitializeInterceptors();
  381. CheckASLR();
  382. InitTlsSize();
  383. InstallDeadlySignalHandlers(MsanOnDeadlySignal);
  384. InstallAtExitHandler(); // Needs __cxa_atexit interceptor.
  385. DisableCoreDumperIfNecessary();
  386. if (StackSizeIsUnlimited()) {
  387. VPrintf(1, "Unlimited stack, doing reexec\n");
  388. // A reasonably large stack size. It is bigger than the usual 8Mb, because,
  389. // well, the program could have been run with unlimited stack for a reason.
  390. SetStackSizeLimitInBytes(32 * 1024 * 1024);
  391. ReExec();
  392. }
  393. __msan_clear_on_return();
  394. if (__msan_get_track_origins())
  395. VPrintf(1, "msan_track_origins\n");
  396. if (!InitShadow(__msan_get_track_origins())) {
  397. Printf("FATAL: MemorySanitizer can not mmap the shadow memory.\n");
  398. Printf("FATAL: Make sure to compile with -fPIE and to link with -pie.\n");
  399. Printf("FATAL: Disabling ASLR is known to cause this error.\n");
  400. Printf("FATAL: If running under GDB, try "
  401. "'set disable-randomization off'.\n");
  402. DumpProcessMap();
  403. Die();
  404. }
  405. Symbolizer::GetOrInit()->AddHooks(EnterSymbolizerOrUnwider,
  406. ExitSymbolizerOrUnwider);
  407. InitializeCoverage(common_flags()->coverage, common_flags()->coverage_dir);
  408. MsanTSDInit(MsanTSDDtor);
  409. MsanAllocatorInit();
  410. MsanThread *main_thread = MsanThread::Create(nullptr, nullptr);
  411. SetCurrentThread(main_thread);
  412. main_thread->Init();
  413. #if MSAN_CONTAINS_UBSAN
  414. __ubsan::InitAsPlugin();
  415. #endif
  416. VPrintf(1, "MemorySanitizer init done\n");
  417. msan_init_is_running = 0;
  418. msan_inited = 1;
  419. }
  420. void __msan_set_keep_going(int keep_going) {
  421. flags()->halt_on_error = !keep_going;
  422. }
  423. void __msan_set_expect_umr(int expect_umr) {
  424. if (expect_umr) {
  425. msan_expected_umr_found = 0;
  426. } else if (!msan_expected_umr_found) {
  427. GET_CALLER_PC_BP_SP;
  428. (void)sp;
  429. GET_FATAL_STACK_TRACE_PC_BP(pc, bp);
  430. ReportExpectedUMRNotFound(&stack);
  431. Die();
  432. }
  433. msan_expect_umr = expect_umr;
  434. }
  435. void __msan_print_shadow(const void *x, uptr size) {
  436. if (!MEM_IS_APP(x)) {
  437. Printf("Not a valid application address: %p\n", x);
  438. return;
  439. }
  440. DescribeMemoryRange(x, size);
  441. }
  442. void __msan_dump_shadow(const void *x, uptr size) {
  443. if (!MEM_IS_APP(x)) {
  444. Printf("Not a valid application address: %p\n", x);
  445. return;
  446. }
  447. unsigned char *s = (unsigned char*)MEM_TO_SHADOW(x);
  448. Printf("%p[%p] ", (void *)s, x);
  449. for (uptr i = 0; i < size; i++)
  450. Printf("%x%x ", s[i] >> 4, s[i] & 0xf);
  451. Printf("\n");
  452. }
  453. sptr __msan_test_shadow(const void *x, uptr size) {
  454. if (!MEM_IS_APP(x)) return -1;
  455. unsigned char *s = (unsigned char *)MEM_TO_SHADOW((uptr)x);
  456. if (__sanitizer::mem_is_zero((const char *)s, size))
  457. return -1;
  458. // Slow path: loop through again to find the location.
  459. for (uptr i = 0; i < size; ++i)
  460. if (s[i])
  461. return i;
  462. return -1;
  463. }
  464. void __msan_check_mem_is_initialized(const void *x, uptr size) {
  465. if (!__msan::flags()->report_umrs) return;
  466. sptr offset = __msan_test_shadow(x, size);
  467. if (offset < 0)
  468. return;
  469. GET_CALLER_PC_BP_SP;
  470. (void)sp;
  471. ReportUMRInsideAddressRange(__func__, x, size, offset);
  472. __msan::PrintWarningWithOrigin(pc, bp,
  473. __msan_get_origin(((const char *)x) + offset));
  474. if (__msan::flags()->halt_on_error) {
  475. Printf("Exiting\n");
  476. Die();
  477. }
  478. }
  479. int __msan_set_poison_in_malloc(int do_poison) {
  480. int old = flags()->poison_in_malloc;
  481. flags()->poison_in_malloc = do_poison;
  482. return old;
  483. }
  484. int __msan_has_dynamic_component() { return false; }
  485. NOINLINE
  486. void __msan_clear_on_return() {
  487. __msan_param_tls[0] = 0;
  488. }
  489. void __msan_partial_poison(const void* data, void* shadow, uptr size) {
  490. internal_memcpy((void*)MEM_TO_SHADOW((uptr)data), shadow, size);
  491. }
  492. void __msan_load_unpoisoned(const void *src, uptr size, void *dst) {
  493. internal_memcpy(dst, src, size);
  494. __msan_unpoison(dst, size);
  495. }
  496. void __msan_set_origin(const void *a, uptr size, u32 origin) {
  497. if (__msan_get_track_origins()) SetOrigin(a, size, origin);
  498. }
  499. void __msan_set_alloca_origin(void *a, uptr size, char *descr) {
  500. SetAllocaOrigin(a, size, reinterpret_cast<u32 *>(descr), descr + 4,
  501. GET_CALLER_PC());
  502. }
  503. void __msan_set_alloca_origin4(void *a, uptr size, char *descr, uptr pc) {
  504. // Intentionally ignore pc and use return address. This function is here for
  505. // compatibility, in case program is linked with library instrumented by
  506. // older clang.
  507. SetAllocaOrigin(a, size, reinterpret_cast<u32 *>(descr), descr + 4,
  508. GET_CALLER_PC());
  509. }
  510. void __msan_set_alloca_origin_with_descr(void *a, uptr size, u32 *id_ptr,
  511. char *descr) {
  512. SetAllocaOrigin(a, size, id_ptr, descr, GET_CALLER_PC());
  513. }
  514. void __msan_set_alloca_origin_no_descr(void *a, uptr size, u32 *id_ptr) {
  515. SetAllocaOrigin(a, size, id_ptr, nullptr, GET_CALLER_PC());
  516. }
  517. u32 __msan_chain_origin(u32 id) {
  518. GET_CALLER_PC_BP_SP;
  519. (void)sp;
  520. GET_STORE_STACK_TRACE_PC_BP(pc, bp);
  521. return ChainOrigin(id, &stack);
  522. }
  523. u32 __msan_get_origin(const void *a) {
  524. if (!__msan_get_track_origins()) return 0;
  525. uptr x = (uptr)a;
  526. uptr aligned = x & ~3ULL;
  527. uptr origin_ptr = MEM_TO_ORIGIN(aligned);
  528. return *(u32*)origin_ptr;
  529. }
  530. int __msan_origin_is_descendant_or_same(u32 this_id, u32 prev_id) {
  531. Origin o = Origin::FromRawId(this_id);
  532. while (o.raw_id() != prev_id && o.isChainedOrigin())
  533. o = o.getNextChainedOrigin(nullptr);
  534. return o.raw_id() == prev_id;
  535. }
  536. u32 __msan_get_umr_origin() {
  537. return __msan_origin_tls;
  538. }
  539. u16 __sanitizer_unaligned_load16(const uu16 *p) {
  540. internal_memcpy(&__msan_retval_tls[0], (void *)MEM_TO_SHADOW((uptr)p),
  541. sizeof(uu16));
  542. if (__msan_get_track_origins())
  543. __msan_retval_origin_tls = GetOriginIfPoisoned((uptr)p, sizeof(*p));
  544. return *p;
  545. }
  546. u32 __sanitizer_unaligned_load32(const uu32 *p) {
  547. internal_memcpy(&__msan_retval_tls[0], (void *)MEM_TO_SHADOW((uptr)p),
  548. sizeof(uu32));
  549. if (__msan_get_track_origins())
  550. __msan_retval_origin_tls = GetOriginIfPoisoned((uptr)p, sizeof(*p));
  551. return *p;
  552. }
  553. u64 __sanitizer_unaligned_load64(const uu64 *p) {
  554. internal_memcpy(&__msan_retval_tls[0], (void *)MEM_TO_SHADOW((uptr)p),
  555. sizeof(uu64));
  556. if (__msan_get_track_origins())
  557. __msan_retval_origin_tls = GetOriginIfPoisoned((uptr)p, sizeof(*p));
  558. return *p;
  559. }
  560. void __sanitizer_unaligned_store16(uu16 *p, u16 x) {
  561. static_assert(sizeof(uu16) == sizeof(u16), "incompatible types");
  562. u16 s;
  563. internal_memcpy(&s, &__msan_param_tls[1], sizeof(uu16));
  564. internal_memcpy((void *)MEM_TO_SHADOW((uptr)p), &s, sizeof(uu16));
  565. if (s && __msan_get_track_origins())
  566. if (uu32 o = __msan_param_origin_tls[2])
  567. SetOriginIfPoisoned((uptr)p, (uptr)&s, sizeof(s), o);
  568. *p = x;
  569. }
  570. void __sanitizer_unaligned_store32(uu32 *p, u32 x) {
  571. static_assert(sizeof(uu32) == sizeof(u32), "incompatible types");
  572. u32 s;
  573. internal_memcpy(&s, &__msan_param_tls[1], sizeof(uu32));
  574. internal_memcpy((void *)MEM_TO_SHADOW((uptr)p), &s, sizeof(uu32));
  575. if (s && __msan_get_track_origins())
  576. if (uu32 o = __msan_param_origin_tls[2])
  577. SetOriginIfPoisoned((uptr)p, (uptr)&s, sizeof(s), o);
  578. *p = x;
  579. }
  580. void __sanitizer_unaligned_store64(uu64 *p, u64 x) {
  581. u64 s = __msan_param_tls[1];
  582. *(uu64 *)MEM_TO_SHADOW((uptr)p) = s;
  583. if (s && __msan_get_track_origins())
  584. if (uu32 o = __msan_param_origin_tls[2])
  585. SetOriginIfPoisoned((uptr)p, (uptr)&s, sizeof(s), o);
  586. *p = x;
  587. }
  588. void __msan_set_death_callback(void (*callback)(void)) {
  589. SetUserDieCallback(callback);
  590. }
  591. void __msan_start_switch_fiber(const void *bottom, uptr size) {
  592. MsanThread *t = GetCurrentThread();
  593. if (!t) {
  594. VReport(1, "__msan_start_switch_fiber called from unknown thread\n");
  595. return;
  596. }
  597. t->StartSwitchFiber((uptr)bottom, size);
  598. }
  599. void __msan_finish_switch_fiber(const void **bottom_old, uptr *size_old) {
  600. MsanThread *t = GetCurrentThread();
  601. if (!t) {
  602. VReport(1, "__msan_finish_switch_fiber called from unknown thread\n");
  603. return;
  604. }
  605. t->FinishSwitchFiber((uptr *)bottom_old, (uptr *)size_old);
  606. internal_memset(__msan_param_tls, 0, sizeof(__msan_param_tls));
  607. internal_memset(__msan_retval_tls, 0, sizeof(__msan_retval_tls));
  608. internal_memset(__msan_va_arg_tls, 0, sizeof(__msan_va_arg_tls));
  609. if (__msan_get_track_origins()) {
  610. internal_memset(__msan_param_origin_tls, 0,
  611. sizeof(__msan_param_origin_tls));
  612. internal_memset(&__msan_retval_origin_tls, 0,
  613. sizeof(__msan_retval_origin_tls));
  614. internal_memset(__msan_va_arg_origin_tls, 0,
  615. sizeof(__msan_va_arg_origin_tls));
  616. }
  617. }
  618. SANITIZER_INTERFACE_WEAK_DEF(const char *, __msan_default_options, void) {
  619. return "";
  620. }
  621. extern "C" {
  622. SANITIZER_INTERFACE_ATTRIBUTE
  623. void __sanitizer_print_stack_trace() {
  624. GET_FATAL_STACK_TRACE_PC_BP(StackTrace::GetCurrentPc(), GET_CURRENT_FRAME());
  625. stack.Print();
  626. }
  627. } // extern "C"