msan.cpp 22 KB

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