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