asan_globals.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  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. if (g.location) {
  78. Report(" location (%p): name=%s[%p], %d %d\n", (void *)g.location,
  79. g.location->filename, (void *)g.location->filename,
  80. g.location->line_no, g.location->column_no);
  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. static const char *GlobalFilename(const __asan_global &g) {
  272. const char *res = g.module_name;
  273. // Prefer the filename from source location, if is available.
  274. if (g.location) res = g.location->filename;
  275. CHECK(res);
  276. return res;
  277. }
  278. void PrintGlobalLocation(InternalScopedString *str, const __asan_global &g) {
  279. str->append("%s", GlobalFilename(g));
  280. if (!g.location) return;
  281. if (g.location->line_no) str->append(":%d", g.location->line_no);
  282. if (g.location->column_no) str->append(":%d", g.location->column_no);
  283. }
  284. } // namespace __asan
  285. // ---------------------- Interface ---------------- {{{1
  286. using namespace __asan;
  287. // Apply __asan_register_globals to all globals found in the same loaded
  288. // executable or shared library as `flag'. The flag tracks whether globals have
  289. // already been registered or not for this image.
  290. void __asan_register_image_globals(uptr *flag) {
  291. if (*flag)
  292. return;
  293. AsanApplyToGlobals(__asan_register_globals, flag);
  294. *flag = 1;
  295. }
  296. // This mirrors __asan_register_image_globals.
  297. void __asan_unregister_image_globals(uptr *flag) {
  298. if (!*flag)
  299. return;
  300. AsanApplyToGlobals(__asan_unregister_globals, flag);
  301. *flag = 0;
  302. }
  303. void __asan_register_elf_globals(uptr *flag, void *start, void *stop) {
  304. if (*flag) return;
  305. if (!start) return;
  306. CHECK_EQ(0, ((uptr)stop - (uptr)start) % sizeof(__asan_global));
  307. __asan_global *globals_start = (__asan_global*)start;
  308. __asan_global *globals_stop = (__asan_global*)stop;
  309. __asan_register_globals(globals_start, globals_stop - globals_start);
  310. *flag = 1;
  311. }
  312. void __asan_unregister_elf_globals(uptr *flag, void *start, void *stop) {
  313. if (!*flag) return;
  314. if (!start) return;
  315. CHECK_EQ(0, ((uptr)stop - (uptr)start) % sizeof(__asan_global));
  316. __asan_global *globals_start = (__asan_global*)start;
  317. __asan_global *globals_stop = (__asan_global*)stop;
  318. __asan_unregister_globals(globals_start, globals_stop - globals_start);
  319. *flag = 0;
  320. }
  321. // Register an array of globals.
  322. void __asan_register_globals(__asan_global *globals, uptr n) {
  323. if (!flags()->report_globals) return;
  324. GET_STACK_TRACE_MALLOC;
  325. u32 stack_id = StackDepotPut(stack);
  326. Lock lock(&mu_for_globals);
  327. if (!global_registration_site_vector) {
  328. global_registration_site_vector =
  329. new (allocator_for_globals) GlobalRegistrationSiteVector;
  330. global_registration_site_vector->reserve(128);
  331. }
  332. GlobalRegistrationSite site = {stack_id, &globals[0], &globals[n - 1]};
  333. global_registration_site_vector->push_back(site);
  334. if (flags()->report_globals >= 2) {
  335. PRINT_CURRENT_STACK();
  336. Printf("=== ID %d; %p %p\n", stack_id, (void *)&globals[0],
  337. (void *)&globals[n - 1]);
  338. }
  339. for (uptr i = 0; i < n; i++) {
  340. if (SANITIZER_WINDOWS && globals[i].beg == 0) {
  341. // The MSVC incremental linker may pad globals out to 256 bytes. As long
  342. // as __asan_global is less than 256 bytes large and its size is a power
  343. // of two, we can skip over the padding.
  344. static_assert(
  345. sizeof(__asan_global) < 256 &&
  346. (sizeof(__asan_global) & (sizeof(__asan_global) - 1)) == 0,
  347. "sizeof(__asan_global) incompatible with incremental linker padding");
  348. // If these are padding bytes, the rest of the global should be zero.
  349. CHECK(globals[i].size == 0 && globals[i].size_with_redzone == 0 &&
  350. globals[i].name == nullptr && globals[i].module_name == nullptr &&
  351. globals[i].odr_indicator == 0);
  352. continue;
  353. }
  354. RegisterGlobal(&globals[i]);
  355. }
  356. // Poison the metadata. It should not be accessible to user code.
  357. PoisonShadow(reinterpret_cast<uptr>(globals), n * sizeof(__asan_global),
  358. kAsanGlobalRedzoneMagic);
  359. }
  360. // Unregister an array of globals.
  361. // We must do this when a shared objects gets dlclosed.
  362. void __asan_unregister_globals(__asan_global *globals, uptr n) {
  363. if (!flags()->report_globals) return;
  364. Lock lock(&mu_for_globals);
  365. for (uptr i = 0; i < n; i++) {
  366. if (SANITIZER_WINDOWS && globals[i].beg == 0) {
  367. // Skip globals that look like padding from the MSVC incremental linker.
  368. // See comment in __asan_register_globals.
  369. continue;
  370. }
  371. UnregisterGlobal(&globals[i]);
  372. }
  373. // Unpoison the metadata.
  374. PoisonShadow(reinterpret_cast<uptr>(globals), n * sizeof(__asan_global), 0);
  375. }
  376. // This method runs immediately prior to dynamic initialization in each TU,
  377. // when all dynamically initialized globals are unpoisoned. This method
  378. // poisons all global variables not defined in this TU, so that a dynamic
  379. // initializer can only touch global variables in the same TU.
  380. void __asan_before_dynamic_init(const char *module_name) {
  381. if (!flags()->check_initialization_order ||
  382. !CanPoisonMemory() ||
  383. !dynamic_init_globals)
  384. return;
  385. bool strict_init_order = flags()->strict_init_order;
  386. CHECK(module_name);
  387. CHECK(asan_inited);
  388. Lock lock(&mu_for_globals);
  389. if (flags()->report_globals >= 3)
  390. Printf("DynInitPoison module: %s\n", module_name);
  391. for (uptr i = 0, n = dynamic_init_globals->size(); i < n; ++i) {
  392. DynInitGlobal &dyn_g = (*dynamic_init_globals)[i];
  393. const Global *g = &dyn_g.g;
  394. if (dyn_g.initialized)
  395. continue;
  396. if (g->module_name != module_name)
  397. PoisonShadowForGlobal(g, kAsanInitializationOrderMagic);
  398. else if (!strict_init_order)
  399. dyn_g.initialized = true;
  400. }
  401. }
  402. // This method runs immediately after dynamic initialization in each TU, when
  403. // all dynamically initialized globals except for those defined in the current
  404. // TU are poisoned. It simply unpoisons all dynamically initialized globals.
  405. void __asan_after_dynamic_init() {
  406. if (!flags()->check_initialization_order ||
  407. !CanPoisonMemory() ||
  408. !dynamic_init_globals)
  409. return;
  410. CHECK(asan_inited);
  411. Lock lock(&mu_for_globals);
  412. // FIXME: Optionally report that we're unpoisoning globals from a module.
  413. for (uptr i = 0, n = dynamic_init_globals->size(); i < n; ++i) {
  414. DynInitGlobal &dyn_g = (*dynamic_init_globals)[i];
  415. const Global *g = &dyn_g.g;
  416. if (!dyn_g.initialized) {
  417. // Unpoison the whole global.
  418. PoisonShadowForGlobal(g, 0);
  419. // Poison redzones back.
  420. PoisonRedZones(*g);
  421. }
  422. }
  423. }