asan_globals.cpp 17 KB

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