asan_globals.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. //===-- asan_globals.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 AddressSanitizer, an address sanity checker.
  10. //
  11. // Handle globals.
  12. //===----------------------------------------------------------------------===//
  13. #include "asan_interceptors.h"
  14. #include "asan_internal.h"
  15. #include "asan_mapping.h"
  16. #include "asan_poisoning.h"
  17. #include "asan_report.h"
  18. #include "asan_stack.h"
  19. #include "asan_stats.h"
  20. #include "asan_suppressions.h"
  21. #include "asan_thread.h"
  22. #include "sanitizer_common/sanitizer_common.h"
  23. #include "sanitizer_common/sanitizer_mutex.h"
  24. #include "sanitizer_common/sanitizer_placement_new.h"
  25. #include "sanitizer_common/sanitizer_stackdepot.h"
  26. #include "sanitizer_common/sanitizer_symbolizer.h"
  27. namespace __asan {
  28. typedef __asan_global Global;
  29. struct ListOfGlobals {
  30. const Global *g;
  31. ListOfGlobals *next;
  32. };
  33. static Mutex mu_for_globals;
  34. static LowLevelAllocator allocator_for_globals;
  35. static ListOfGlobals *list_of_all_globals;
  36. static const int kDynamicInitGlobalsInitialCapacity = 512;
  37. struct DynInitGlobal {
  38. Global g;
  39. bool initialized;
  40. };
  41. typedef InternalMmapVector<DynInitGlobal> VectorOfGlobals;
  42. // Lazy-initialized and never deleted.
  43. static VectorOfGlobals *dynamic_init_globals;
  44. // We want to remember where a certain range of globals was registered.
  45. struct GlobalRegistrationSite {
  46. u32 stack_id;
  47. Global *g_first, *g_last;
  48. };
  49. typedef InternalMmapVector<GlobalRegistrationSite> GlobalRegistrationSiteVector;
  50. static GlobalRegistrationSiteVector *global_registration_site_vector;
  51. ALWAYS_INLINE void PoisonShadowForGlobal(const Global *g, u8 value) {
  52. FastPoisonShadow(g->beg, g->size_with_redzone, value);
  53. }
  54. ALWAYS_INLINE void PoisonRedZones(const Global &g) {
  55. uptr aligned_size = RoundUpTo(g.size, ASAN_SHADOW_GRANULARITY);
  56. FastPoisonShadow(g.beg + aligned_size, g.size_with_redzone - aligned_size,
  57. kAsanGlobalRedzoneMagic);
  58. if (g.size != aligned_size) {
  59. FastPoisonShadowPartialRightRedzone(
  60. g.beg + RoundDownTo(g.size, ASAN_SHADOW_GRANULARITY),
  61. g.size % ASAN_SHADOW_GRANULARITY, ASAN_SHADOW_GRANULARITY,
  62. kAsanGlobalRedzoneMagic);
  63. }
  64. }
  65. const uptr kMinimalDistanceFromAnotherGlobal = 64;
  66. static bool IsAddressNearGlobal(uptr addr, const __asan_global &g) {
  67. if (addr <= g.beg - kMinimalDistanceFromAnotherGlobal) return false;
  68. if (addr >= g.beg + g.size_with_redzone) return false;
  69. return true;
  70. }
  71. static void ReportGlobal(const Global &g, const char *prefix) {
  72. Report(
  73. "%s Global[%p]: beg=%p size=%zu/%zu name=%s module=%s dyn_init=%zu "
  74. "odr_indicator=%p\n",
  75. prefix, (void *)&g, (void *)g.beg, g.size, g.size_with_redzone, g.name,
  76. g.module_name, g.has_dynamic_init, (void *)g.odr_indicator);
  77. DataInfo info;
  78. Symbolizer::GetOrInit()->SymbolizeData(g.beg, &info);
  79. if (info.line != 0) {
  80. Report(" location: name=%s, %d\n", info.file, static_cast<int>(info.line));
  81. }
  82. }
  83. static u32 FindRegistrationSite(const Global *g) {
  84. mu_for_globals.CheckLocked();
  85. CHECK(global_registration_site_vector);
  86. for (uptr i = 0, n = global_registration_site_vector->size(); i < n; i++) {
  87. GlobalRegistrationSite &grs = (*global_registration_site_vector)[i];
  88. if (g >= grs.g_first && g <= grs.g_last)
  89. return grs.stack_id;
  90. }
  91. return 0;
  92. }
  93. int GetGlobalsForAddress(uptr addr, Global *globals, u32 *reg_sites,
  94. int max_globals) {
  95. if (!flags()->report_globals) return 0;
  96. Lock lock(&mu_for_globals);
  97. int res = 0;
  98. for (ListOfGlobals *l = list_of_all_globals; l; l = l->next) {
  99. const Global &g = *l->g;
  100. if (flags()->report_globals >= 2)
  101. ReportGlobal(g, "Search");
  102. if (IsAddressNearGlobal(addr, g)) {
  103. internal_memcpy(&globals[res], &g, sizeof(g));
  104. if (reg_sites)
  105. reg_sites[res] = FindRegistrationSite(&g);
  106. res++;
  107. if (res == max_globals)
  108. break;
  109. }
  110. }
  111. return res;
  112. }
  113. enum GlobalSymbolState {
  114. UNREGISTERED = 0,
  115. REGISTERED = 1
  116. };
  117. // Check ODR violation for given global G via special ODR indicator. We use
  118. // this method in case compiler instruments global variables through their
  119. // local aliases.
  120. static void CheckODRViolationViaIndicator(const Global *g) {
  121. // Instrumentation requests to skip ODR check.
  122. if (g->odr_indicator == UINTPTR_MAX)
  123. return;
  124. u8 *odr_indicator = reinterpret_cast<u8 *>(g->odr_indicator);
  125. if (*odr_indicator == UNREGISTERED) {
  126. *odr_indicator = REGISTERED;
  127. return;
  128. }
  129. // If *odr_indicator is DEFINED, some module have already registered
  130. // externally visible symbol with the same name. This is an ODR violation.
  131. for (ListOfGlobals *l = list_of_all_globals; l; l = l->next) {
  132. if (g->odr_indicator == l->g->odr_indicator &&
  133. (flags()->detect_odr_violation >= 2 || g->size != l->g->size) &&
  134. !IsODRViolationSuppressed(g->name))
  135. ReportODRViolation(g, FindRegistrationSite(g),
  136. l->g, FindRegistrationSite(l->g));
  137. }
  138. }
  139. // Check ODR violation for given global G by checking if it's already poisoned.
  140. // We use this method in case compiler doesn't use private aliases for global
  141. // variables.
  142. static void CheckODRViolationViaPoisoning(const Global *g) {
  143. if (__asan_region_is_poisoned(g->beg, g->size_with_redzone)) {
  144. // This check may not be enough: if the first global is much larger
  145. // the entire redzone of the second global may be within the first global.
  146. for (ListOfGlobals *l = list_of_all_globals; l; l = l->next) {
  147. if (g->beg == l->g->beg &&
  148. (flags()->detect_odr_violation >= 2 || g->size != l->g->size) &&
  149. !IsODRViolationSuppressed(g->name))
  150. ReportODRViolation(g, FindRegistrationSite(g),
  151. l->g, FindRegistrationSite(l->g));
  152. }
  153. }
  154. }
  155. // Clang provides two different ways for global variables protection:
  156. // it can poison the global itself or its private alias. In former
  157. // case we may poison same symbol multiple times, that can help us to
  158. // cheaply detect ODR violation: if we try to poison an already poisoned
  159. // global, we have ODR violation error.
  160. // In latter case, we poison each symbol exactly once, so we use special
  161. // indicator symbol to perform similar check.
  162. // In either case, compiler provides a special odr_indicator field to Global
  163. // structure, that can contain two kinds of values:
  164. // 1) Non-zero value. In this case, odr_indicator is an address of
  165. // corresponding indicator variable for given global.
  166. // 2) Zero. This means that we don't use private aliases for global variables
  167. // and can freely check ODR violation with the first method.
  168. //
  169. // This routine chooses between two different methods of ODR violation
  170. // detection.
  171. static inline bool UseODRIndicator(const Global *g) {
  172. return g->odr_indicator > 0;
  173. }
  174. // Register a global variable.
  175. // This function may be called more than once for every global
  176. // so we store the globals in a map.
  177. static void RegisterGlobal(const Global *g) {
  178. CHECK(asan_inited);
  179. if (flags()->report_globals >= 2)
  180. ReportGlobal(*g, "Added");
  181. CHECK(flags()->report_globals);
  182. CHECK(AddrIsInMem(g->beg));
  183. if (!AddrIsAlignedByGranularity(g->beg)) {
  184. Report("The following global variable is not properly aligned.\n");
  185. Report("This may happen if another global with the same name\n");
  186. Report("resides in another non-instrumented module.\n");
  187. Report("Or the global comes from a C file built w/o -fno-common.\n");
  188. Report("In either case this is likely an ODR violation bug,\n");
  189. Report("but AddressSanitizer can not provide more details.\n");
  190. ReportODRViolation(g, FindRegistrationSite(g), g, FindRegistrationSite(g));
  191. CHECK(AddrIsAlignedByGranularity(g->beg));
  192. }
  193. CHECK(AddrIsAlignedByGranularity(g->size_with_redzone));
  194. if (flags()->detect_odr_violation) {
  195. // Try detecting ODR (One Definition Rule) violation, i.e. the situation
  196. // where two globals with the same name are defined in different modules.
  197. if (UseODRIndicator(g))
  198. CheckODRViolationViaIndicator(g);
  199. else
  200. CheckODRViolationViaPoisoning(g);
  201. }
  202. if (CanPoisonMemory())
  203. PoisonRedZones(*g);
  204. ListOfGlobals *l = new(allocator_for_globals) ListOfGlobals;
  205. l->g = g;
  206. l->next = list_of_all_globals;
  207. list_of_all_globals = l;
  208. if (g->has_dynamic_init) {
  209. if (!dynamic_init_globals) {
  210. dynamic_init_globals = new (allocator_for_globals) VectorOfGlobals;
  211. dynamic_init_globals->reserve(kDynamicInitGlobalsInitialCapacity);
  212. }
  213. DynInitGlobal dyn_global = { *g, false };
  214. dynamic_init_globals->push_back(dyn_global);
  215. }
  216. }
  217. static void UnregisterGlobal(const Global *g) {
  218. CHECK(asan_inited);
  219. if (flags()->report_globals >= 2)
  220. ReportGlobal(*g, "Removed");
  221. CHECK(flags()->report_globals);
  222. CHECK(AddrIsInMem(g->beg));
  223. CHECK(AddrIsAlignedByGranularity(g->beg));
  224. CHECK(AddrIsAlignedByGranularity(g->size_with_redzone));
  225. if (CanPoisonMemory())
  226. PoisonShadowForGlobal(g, 0);
  227. // We unpoison the shadow memory for the global but we do not remove it from
  228. // the list because that would require O(n^2) time with the current list
  229. // implementation. It might not be worth doing anyway.
  230. // Release ODR indicator.
  231. if (UseODRIndicator(g) && g->odr_indicator != UINTPTR_MAX) {
  232. u8 *odr_indicator = reinterpret_cast<u8 *>(g->odr_indicator);
  233. *odr_indicator = UNREGISTERED;
  234. }
  235. }
  236. void StopInitOrderChecking() {
  237. Lock lock(&mu_for_globals);
  238. if (!flags()->check_initialization_order || !dynamic_init_globals)
  239. return;
  240. flags()->check_initialization_order = false;
  241. for (uptr i = 0, n = dynamic_init_globals->size(); i < n; ++i) {
  242. DynInitGlobal &dyn_g = (*dynamic_init_globals)[i];
  243. const Global *g = &dyn_g.g;
  244. // Unpoison the whole global.
  245. PoisonShadowForGlobal(g, 0);
  246. // Poison redzones back.
  247. PoisonRedZones(*g);
  248. }
  249. }
  250. static bool IsASCII(unsigned char c) { return /*0x00 <= c &&*/ c <= 0x7F; }
  251. const char *MaybeDemangleGlobalName(const char *name) {
  252. // We can spoil names of globals with C linkage, so use an heuristic
  253. // approach to check if the name should be demangled.
  254. bool should_demangle = false;
  255. if (name[0] == '_' && name[1] == 'Z')
  256. should_demangle = true;
  257. else if (SANITIZER_WINDOWS && name[0] == '\01' && name[1] == '?')
  258. should_demangle = true;
  259. return should_demangle ? Symbolizer::GetOrInit()->Demangle(name) : name;
  260. }
  261. // Check if the global is a zero-terminated ASCII string. If so, print it.
  262. void PrintGlobalNameIfASCII(InternalScopedString *str, const __asan_global &g) {
  263. for (uptr p = g.beg; p < g.beg + g.size - 1; p++) {
  264. unsigned char c = *(unsigned char *)p;
  265. if (c == '\0' || !IsASCII(c)) return;
  266. }
  267. if (*(char *)(g.beg + g.size - 1) != '\0') return;
  268. str->append(" '%s' is ascii string '%s'\n", MaybeDemangleGlobalName(g.name),
  269. (char *)g.beg);
  270. }
  271. void PrintGlobalLocation(InternalScopedString *str, const __asan_global &g) {
  272. DataInfo info;
  273. Symbolizer::GetOrInit()->SymbolizeData(g.beg, &info);
  274. if (info.line != 0) {
  275. str->append("%s:%d", info.file, static_cast<int>(info.line));
  276. } else {
  277. str->append("%s", g.module_name);
  278. }
  279. }
  280. } // namespace __asan
  281. // ---------------------- Interface ---------------- {{{1
  282. using namespace __asan;
  283. // Apply __asan_register_globals to all globals found in the same loaded
  284. // executable or shared library as `flag'. The flag tracks whether globals have
  285. // already been registered or not for this image.
  286. void __asan_register_image_globals(uptr *flag) {
  287. if (*flag)
  288. return;
  289. AsanApplyToGlobals(__asan_register_globals, flag);
  290. *flag = 1;
  291. }
  292. // This mirrors __asan_register_image_globals.
  293. void __asan_unregister_image_globals(uptr *flag) {
  294. if (!*flag)
  295. return;
  296. AsanApplyToGlobals(__asan_unregister_globals, flag);
  297. *flag = 0;
  298. }
  299. void __asan_register_elf_globals(uptr *flag, void *start, void *stop) {
  300. if (*flag) return;
  301. if (!start) return;
  302. CHECK_EQ(0, ((uptr)stop - (uptr)start) % sizeof(__asan_global));
  303. __asan_global *globals_start = (__asan_global*)start;
  304. __asan_global *globals_stop = (__asan_global*)stop;
  305. __asan_register_globals(globals_start, globals_stop - globals_start);
  306. *flag = 1;
  307. }
  308. void __asan_unregister_elf_globals(uptr *flag, void *start, void *stop) {
  309. if (!*flag) return;
  310. if (!start) return;
  311. CHECK_EQ(0, ((uptr)stop - (uptr)start) % sizeof(__asan_global));
  312. __asan_global *globals_start = (__asan_global*)start;
  313. __asan_global *globals_stop = (__asan_global*)stop;
  314. __asan_unregister_globals(globals_start, globals_stop - globals_start);
  315. *flag = 0;
  316. }
  317. // Register an array of globals.
  318. void __asan_register_globals(__asan_global *globals, uptr n) {
  319. if (!flags()->report_globals) return;
  320. GET_STACK_TRACE_MALLOC;
  321. u32 stack_id = StackDepotPut(stack);
  322. Lock lock(&mu_for_globals);
  323. if (!global_registration_site_vector) {
  324. global_registration_site_vector =
  325. new (allocator_for_globals) GlobalRegistrationSiteVector;
  326. global_registration_site_vector->reserve(128);
  327. }
  328. GlobalRegistrationSite site = {stack_id, &globals[0], &globals[n - 1]};
  329. global_registration_site_vector->push_back(site);
  330. if (flags()->report_globals >= 2) {
  331. PRINT_CURRENT_STACK();
  332. Printf("=== ID %d; %p %p\n", stack_id, (void *)&globals[0],
  333. (void *)&globals[n - 1]);
  334. }
  335. for (uptr i = 0; i < n; i++) {
  336. if (SANITIZER_WINDOWS && globals[i].beg == 0) {
  337. // The MSVC incremental linker may pad globals out to 256 bytes. As long
  338. // as __asan_global is less than 256 bytes large and its size is a power
  339. // of two, we can skip over the padding.
  340. static_assert(
  341. sizeof(__asan_global) < 256 &&
  342. (sizeof(__asan_global) & (sizeof(__asan_global) - 1)) == 0,
  343. "sizeof(__asan_global) incompatible with incremental linker padding");
  344. // If these are padding bytes, the rest of the global should be zero.
  345. CHECK(globals[i].size == 0 && globals[i].size_with_redzone == 0 &&
  346. globals[i].name == nullptr && globals[i].module_name == nullptr &&
  347. globals[i].odr_indicator == 0);
  348. continue;
  349. }
  350. RegisterGlobal(&globals[i]);
  351. }
  352. // Poison the metadata. It should not be accessible to user code.
  353. PoisonShadow(reinterpret_cast<uptr>(globals), n * sizeof(__asan_global),
  354. kAsanGlobalRedzoneMagic);
  355. }
  356. // Unregister an array of globals.
  357. // We must do this when a shared objects gets dlclosed.
  358. void __asan_unregister_globals(__asan_global *globals, uptr n) {
  359. if (!flags()->report_globals) return;
  360. Lock lock(&mu_for_globals);
  361. for (uptr i = 0; i < n; i++) {
  362. if (SANITIZER_WINDOWS && globals[i].beg == 0) {
  363. // Skip globals that look like padding from the MSVC incremental linker.
  364. // See comment in __asan_register_globals.
  365. continue;
  366. }
  367. UnregisterGlobal(&globals[i]);
  368. }
  369. // Unpoison the metadata.
  370. PoisonShadow(reinterpret_cast<uptr>(globals), n * sizeof(__asan_global), 0);
  371. }
  372. // This method runs immediately prior to dynamic initialization in each TU,
  373. // when all dynamically initialized globals are unpoisoned. This method
  374. // poisons all global variables not defined in this TU, so that a dynamic
  375. // initializer can only touch global variables in the same TU.
  376. void __asan_before_dynamic_init(const char *module_name) {
  377. if (!flags()->check_initialization_order ||
  378. !CanPoisonMemory() ||
  379. !dynamic_init_globals)
  380. return;
  381. bool strict_init_order = flags()->strict_init_order;
  382. CHECK(module_name);
  383. CHECK(asan_inited);
  384. Lock lock(&mu_for_globals);
  385. if (flags()->report_globals >= 3)
  386. Printf("DynInitPoison module: %s\n", module_name);
  387. for (uptr i = 0, n = dynamic_init_globals->size(); i < n; ++i) {
  388. DynInitGlobal &dyn_g = (*dynamic_init_globals)[i];
  389. const Global *g = &dyn_g.g;
  390. if (dyn_g.initialized)
  391. continue;
  392. if (g->module_name != module_name)
  393. PoisonShadowForGlobal(g, kAsanInitializationOrderMagic);
  394. else if (!strict_init_order)
  395. dyn_g.initialized = true;
  396. }
  397. }
  398. // This method runs immediately after dynamic initialization in each TU, when
  399. // all dynamically initialized globals except for those defined in the current
  400. // TU are poisoned. It simply unpoisons all dynamically initialized globals.
  401. void __asan_after_dynamic_init() {
  402. if (!flags()->check_initialization_order ||
  403. !CanPoisonMemory() ||
  404. !dynamic_init_globals)
  405. return;
  406. CHECK(asan_inited);
  407. Lock lock(&mu_for_globals);
  408. // FIXME: Optionally report that we're unpoisoning globals from a module.
  409. for (uptr i = 0, n = dynamic_init_globals->size(); i < n; ++i) {
  410. DynInitGlobal &dyn_g = (*dynamic_init_globals)[i];
  411. const Global *g = &dyn_g.g;
  412. if (!dyn_g.initialized) {
  413. // Unpoison the whole global.
  414. PoisonShadowForGlobal(g, 0);
  415. // Poison redzones back.
  416. PoisonRedZones(*g);
  417. }
  418. }
  419. }