msan.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737
  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 = new (GetGlobalLowLevelAllocator())
  113. 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; \
  288. if (UNLIKELY(s)) { \
  289. PrintWarningWithOrigin(pc, bp, o); \
  290. if (__msan::flags()->halt_on_error) { \
  291. Printf("Exiting\n"); \
  292. Die(); \
  293. } \
  294. } \
  295. }
  296. MSAN_MAYBE_WARNING(u8, 1)
  297. MSAN_MAYBE_WARNING(u16, 2)
  298. MSAN_MAYBE_WARNING(u32, 4)
  299. MSAN_MAYBE_WARNING(u64, 8)
  300. #define MSAN_MAYBE_STORE_ORIGIN(type, size) \
  301. void __msan_maybe_store_origin_##size(type s, void *p, u32 o) { \
  302. if (UNLIKELY(s)) { \
  303. if (__msan_get_track_origins() > 1) { \
  304. GET_CALLER_PC_BP; \
  305. GET_STORE_STACK_TRACE_PC_BP(pc, bp); \
  306. o = ChainOrigin(o, &stack); \
  307. } \
  308. *(u32 *)MEM_TO_ORIGIN((uptr)p & ~3UL) = o; \
  309. } \
  310. }
  311. MSAN_MAYBE_STORE_ORIGIN(u8, 1)
  312. MSAN_MAYBE_STORE_ORIGIN(u16, 2)
  313. MSAN_MAYBE_STORE_ORIGIN(u32, 4)
  314. MSAN_MAYBE_STORE_ORIGIN(u64, 8)
  315. void __msan_warning() {
  316. GET_CALLER_PC_BP;
  317. PrintWarningWithOrigin(pc, bp, 0);
  318. if (__msan::flags()->halt_on_error) {
  319. if (__msan::flags()->print_stats)
  320. ReportStats();
  321. Printf("Exiting\n");
  322. Die();
  323. }
  324. }
  325. void __msan_warning_noreturn() {
  326. GET_CALLER_PC_BP;
  327. PrintWarningWithOrigin(pc, bp, 0);
  328. if (__msan::flags()->print_stats)
  329. ReportStats();
  330. Printf("Exiting\n");
  331. Die();
  332. }
  333. void __msan_warning_with_origin(u32 origin) {
  334. GET_CALLER_PC_BP;
  335. PrintWarningWithOrigin(pc, bp, origin);
  336. if (__msan::flags()->halt_on_error) {
  337. if (__msan::flags()->print_stats)
  338. ReportStats();
  339. Printf("Exiting\n");
  340. Die();
  341. }
  342. }
  343. void __msan_warning_with_origin_noreturn(u32 origin) {
  344. GET_CALLER_PC_BP;
  345. PrintWarningWithOrigin(pc, bp, origin);
  346. if (__msan::flags()->print_stats)
  347. ReportStats();
  348. Printf("Exiting\n");
  349. Die();
  350. }
  351. static void OnStackUnwind(const SignalContext &sig, const void *,
  352. BufferedStackTrace *stack) {
  353. stack->Unwind(StackTrace::GetNextInstructionPc(sig.pc), sig.bp, sig.context,
  354. common_flags()->fast_unwind_on_fatal);
  355. }
  356. static void MsanOnDeadlySignal(int signo, void *siginfo, void *context) {
  357. HandleDeadlySignal(siginfo, context, GetTid(), &OnStackUnwind, nullptr);
  358. }
  359. static void CheckUnwind() {
  360. GET_FATAL_STACK_TRACE_PC_BP(StackTrace::GetCurrentPc(), GET_CURRENT_FRAME());
  361. stack.Print();
  362. }
  363. void __msan_init() {
  364. CHECK(!msan_init_is_running);
  365. if (msan_inited) return;
  366. msan_init_is_running = 1;
  367. SanitizerToolName = "MemorySanitizer";
  368. AvoidCVE_2016_2143();
  369. CacheBinaryName();
  370. InitializeFlags();
  371. // Install tool-specific callbacks in sanitizer_common.
  372. SetCheckUnwindCallback(CheckUnwind);
  373. __sanitizer_set_report_path(common_flags()->log_path);
  374. InitializeInterceptors();
  375. InstallAtForkHandler();
  376. CheckASLR();
  377. InitTlsSize();
  378. InstallDeadlySignalHandlers(MsanOnDeadlySignal);
  379. InstallAtExitHandler(); // Needs __cxa_atexit interceptor.
  380. DisableCoreDumperIfNecessary();
  381. if (StackSizeIsUnlimited()) {
  382. VPrintf(1, "Unlimited stack, doing reexec\n");
  383. // A reasonably large stack size. It is bigger than the usual 8Mb, because,
  384. // well, the program could have been run with unlimited stack for a reason.
  385. SetStackSizeLimitInBytes(32 * 1024 * 1024);
  386. ReExec();
  387. }
  388. __msan_clear_on_return();
  389. if (__msan_get_track_origins())
  390. VPrintf(1, "msan_track_origins\n");
  391. if (!InitShadowWithReExec(__msan_get_track_origins())) {
  392. Printf("FATAL: MemorySanitizer can not mmap the shadow memory.\n");
  393. Printf("FATAL: Make sure to compile with -fPIE and to link with -pie.\n");
  394. Printf("FATAL: Disabling ASLR is known to cause this error.\n");
  395. Printf("FATAL: If running under GDB, try "
  396. "'set disable-randomization off'.\n");
  397. DumpProcessMap();
  398. Die();
  399. }
  400. Symbolizer::GetOrInit()->AddHooks(EnterSymbolizerOrUnwider,
  401. ExitSymbolizerOrUnwider);
  402. InitializeCoverage(common_flags()->coverage, common_flags()->coverage_dir);
  403. MsanTSDInit(MsanTSDDtor);
  404. MsanAllocatorInit();
  405. MsanThread *main_thread = MsanThread::Create(nullptr, nullptr);
  406. SetCurrentThread(main_thread);
  407. main_thread->Init();
  408. #if MSAN_CONTAINS_UBSAN
  409. __ubsan::InitAsPlugin();
  410. #endif
  411. VPrintf(1, "MemorySanitizer init done\n");
  412. msan_init_is_running = 0;
  413. msan_inited = 1;
  414. }
  415. void __msan_set_keep_going(int keep_going) {
  416. flags()->halt_on_error = !keep_going;
  417. }
  418. void __msan_set_expect_umr(int expect_umr) {
  419. if (expect_umr) {
  420. msan_expected_umr_found = 0;
  421. } else if (!msan_expected_umr_found) {
  422. GET_CALLER_PC_BP;
  423. GET_FATAL_STACK_TRACE_PC_BP(pc, bp);
  424. ReportExpectedUMRNotFound(&stack);
  425. Die();
  426. }
  427. msan_expect_umr = expect_umr;
  428. }
  429. void __msan_print_shadow(const void *x, uptr size) {
  430. if (!MEM_IS_APP(x)) {
  431. Printf("Not a valid application address: %p\n", x);
  432. return;
  433. }
  434. DescribeMemoryRange(x, size);
  435. }
  436. void __msan_dump_shadow(const void *x, uptr size) {
  437. if (!MEM_IS_APP(x)) {
  438. Printf("Not a valid application address: %p\n", x);
  439. return;
  440. }
  441. unsigned char *s = (unsigned char*)MEM_TO_SHADOW(x);
  442. Printf("%p[%p] ", (void *)s, x);
  443. for (uptr i = 0; i < size; i++)
  444. Printf("%x%x ", s[i] >> 4, s[i] & 0xf);
  445. Printf("\n");
  446. }
  447. sptr __msan_test_shadow(const void *x, uptr size) {
  448. if (!MEM_IS_APP(x)) return -1;
  449. unsigned char *s = (unsigned char *)MEM_TO_SHADOW((uptr)x);
  450. if (__sanitizer::mem_is_zero((const char *)s, size))
  451. return -1;
  452. // Slow path: loop through again to find the location.
  453. for (uptr i = 0; i < size; ++i)
  454. if (s[i])
  455. return i;
  456. return -1;
  457. }
  458. void __msan_check_mem_is_initialized(const void *x, uptr size) {
  459. if (!__msan::flags()->report_umrs) return;
  460. sptr offset = __msan_test_shadow(x, size);
  461. if (offset < 0)
  462. return;
  463. GET_CALLER_PC_BP;
  464. ReportUMRInsideAddressRange(__func__, x, size, offset);
  465. __msan::PrintWarningWithOrigin(pc, bp,
  466. __msan_get_origin(((const char *)x) + offset));
  467. if (__msan::flags()->halt_on_error) {
  468. Printf("Exiting\n");
  469. Die();
  470. }
  471. }
  472. int __msan_set_poison_in_malloc(int do_poison) {
  473. int old = flags()->poison_in_malloc;
  474. flags()->poison_in_malloc = do_poison;
  475. return old;
  476. }
  477. int __msan_has_dynamic_component() { return false; }
  478. NOINLINE
  479. void __msan_clear_on_return() {
  480. __msan_param_tls[0] = 0;
  481. }
  482. void __msan_partial_poison(const void* data, void* shadow, uptr size) {
  483. internal_memcpy((void*)MEM_TO_SHADOW((uptr)data), shadow, size);
  484. }
  485. void __msan_load_unpoisoned(const void *src, uptr size, void *dst) {
  486. internal_memcpy(dst, src, size);
  487. __msan_unpoison(dst, size);
  488. }
  489. void __msan_set_origin(const void *a, uptr size, u32 origin) {
  490. if (__msan_get_track_origins()) SetOrigin(a, size, origin);
  491. }
  492. void __msan_set_alloca_origin(void *a, uptr size, char *descr) {
  493. SetAllocaOrigin(a, size, reinterpret_cast<u32 *>(descr), descr + 4,
  494. GET_CALLER_PC());
  495. }
  496. void __msan_set_alloca_origin4(void *a, uptr size, char *descr, uptr pc) {
  497. // Intentionally ignore pc and use return address. This function is here for
  498. // compatibility, in case program is linked with library instrumented by
  499. // older clang.
  500. SetAllocaOrigin(a, size, reinterpret_cast<u32 *>(descr), descr + 4,
  501. GET_CALLER_PC());
  502. }
  503. void __msan_set_alloca_origin_with_descr(void *a, uptr size, u32 *id_ptr,
  504. char *descr) {
  505. SetAllocaOrigin(a, size, id_ptr, descr, GET_CALLER_PC());
  506. }
  507. void __msan_set_alloca_origin_no_descr(void *a, uptr size, u32 *id_ptr) {
  508. SetAllocaOrigin(a, size, id_ptr, nullptr, GET_CALLER_PC());
  509. }
  510. u32 __msan_chain_origin(u32 id) {
  511. GET_CALLER_PC_BP;
  512. GET_STORE_STACK_TRACE_PC_BP(pc, bp);
  513. return ChainOrigin(id, &stack);
  514. }
  515. u32 __msan_get_origin(const void *a) {
  516. if (!__msan_get_track_origins()) return 0;
  517. uptr x = (uptr)a;
  518. uptr aligned = x & ~3ULL;
  519. uptr origin_ptr = MEM_TO_ORIGIN(aligned);
  520. return *(u32*)origin_ptr;
  521. }
  522. int __msan_origin_is_descendant_or_same(u32 this_id, u32 prev_id) {
  523. Origin o = Origin::FromRawId(this_id);
  524. while (o.raw_id() != prev_id && o.isChainedOrigin())
  525. o = o.getNextChainedOrigin(nullptr);
  526. return o.raw_id() == prev_id;
  527. }
  528. u32 __msan_get_umr_origin() {
  529. return __msan_origin_tls;
  530. }
  531. u16 __sanitizer_unaligned_load16(const uu16 *p) {
  532. internal_memcpy(&__msan_retval_tls[0], (void *)MEM_TO_SHADOW((uptr)p),
  533. sizeof(uu16));
  534. if (__msan_get_track_origins())
  535. __msan_retval_origin_tls = GetOriginIfPoisoned((uptr)p, sizeof(*p));
  536. return *p;
  537. }
  538. u32 __sanitizer_unaligned_load32(const uu32 *p) {
  539. internal_memcpy(&__msan_retval_tls[0], (void *)MEM_TO_SHADOW((uptr)p),
  540. sizeof(uu32));
  541. if (__msan_get_track_origins())
  542. __msan_retval_origin_tls = GetOriginIfPoisoned((uptr)p, sizeof(*p));
  543. return *p;
  544. }
  545. u64 __sanitizer_unaligned_load64(const uu64 *p) {
  546. internal_memcpy(&__msan_retval_tls[0], (void *)MEM_TO_SHADOW((uptr)p),
  547. sizeof(uu64));
  548. if (__msan_get_track_origins())
  549. __msan_retval_origin_tls = GetOriginIfPoisoned((uptr)p, sizeof(*p));
  550. return *p;
  551. }
  552. void __sanitizer_unaligned_store16(uu16 *p, u16 x) {
  553. static_assert(sizeof(uu16) == sizeof(u16), "incompatible types");
  554. u16 s;
  555. internal_memcpy(&s, &__msan_param_tls[1], sizeof(uu16));
  556. internal_memcpy((void *)MEM_TO_SHADOW((uptr)p), &s, sizeof(uu16));
  557. if (s && __msan_get_track_origins())
  558. if (uu32 o = __msan_param_origin_tls[2])
  559. SetOriginIfPoisoned((uptr)p, (uptr)&s, sizeof(s), o);
  560. *p = x;
  561. }
  562. void __sanitizer_unaligned_store32(uu32 *p, u32 x) {
  563. static_assert(sizeof(uu32) == sizeof(u32), "incompatible types");
  564. u32 s;
  565. internal_memcpy(&s, &__msan_param_tls[1], sizeof(uu32));
  566. internal_memcpy((void *)MEM_TO_SHADOW((uptr)p), &s, sizeof(uu32));
  567. if (s && __msan_get_track_origins())
  568. if (uu32 o = __msan_param_origin_tls[2])
  569. SetOriginIfPoisoned((uptr)p, (uptr)&s, sizeof(s), o);
  570. *p = x;
  571. }
  572. void __sanitizer_unaligned_store64(uu64 *p, u64 x) {
  573. u64 s = __msan_param_tls[1];
  574. *(uu64 *)MEM_TO_SHADOW((uptr)p) = s;
  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 __msan_set_death_callback(void (*callback)(void)) {
  581. SetUserDieCallback(callback);
  582. }
  583. void __msan_start_switch_fiber(const void *bottom, uptr size) {
  584. MsanThread *t = GetCurrentThread();
  585. if (!t) {
  586. VReport(1, "__msan_start_switch_fiber called from unknown thread\n");
  587. return;
  588. }
  589. t->StartSwitchFiber((uptr)bottom, size);
  590. }
  591. void __msan_finish_switch_fiber(const void **bottom_old, uptr *size_old) {
  592. MsanThread *t = GetCurrentThread();
  593. if (!t) {
  594. VReport(1, "__msan_finish_switch_fiber called from unknown thread\n");
  595. return;
  596. }
  597. t->FinishSwitchFiber((uptr *)bottom_old, (uptr *)size_old);
  598. internal_memset(__msan_param_tls, 0, sizeof(__msan_param_tls));
  599. internal_memset(__msan_retval_tls, 0, sizeof(__msan_retval_tls));
  600. internal_memset(__msan_va_arg_tls, 0, sizeof(__msan_va_arg_tls));
  601. if (__msan_get_track_origins()) {
  602. internal_memset(__msan_param_origin_tls, 0,
  603. sizeof(__msan_param_origin_tls));
  604. internal_memset(&__msan_retval_origin_tls, 0,
  605. sizeof(__msan_retval_origin_tls));
  606. internal_memset(__msan_va_arg_origin_tls, 0,
  607. sizeof(__msan_va_arg_origin_tls));
  608. }
  609. }
  610. SANITIZER_INTERFACE_WEAK_DEF(const char *, __msan_default_options, void) {
  611. return "";
  612. }
  613. extern "C" {
  614. SANITIZER_INTERFACE_ATTRIBUTE
  615. void __sanitizer_print_stack_trace() {
  616. GET_FATAL_STACK_TRACE_PC_BP(StackTrace::GetCurrentPc(), GET_CURRENT_FRAME());
  617. stack.Print();
  618. }
  619. } // extern "C"