1 //===-- asan_globals.cc ---------------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file is a part of AddressSanitizer, an address sanity checker.
13 //===----------------------------------------------------------------------===//
15 #include "asan_interceptors.h"
16 #include "asan_internal.h"
17 #include "asan_mapping.h"
18 #include "asan_poisoning.h"
19 #include "asan_report.h"
20 #include "asan_stack.h"
21 #include "asan_stats.h"
22 #include "asan_suppressions.h"
23 #include "asan_thread.h"
24 #include "sanitizer_common/sanitizer_common.h"
25 #include "sanitizer_common/sanitizer_mutex.h"
26 #include "sanitizer_common/sanitizer_placement_new.h"
27 #include "sanitizer_common/sanitizer_stackdepot.h"
28 #include "sanitizer_common/sanitizer_symbolizer.h"
32 typedef __asan_global Global;
34 struct ListOfGlobals {
39 static BlockingMutex mu_for_globals(LINKER_INITIALIZED);
40 static LowLevelAllocator allocator_for_globals;
41 static ListOfGlobals *list_of_all_globals;
43 static const int kDynamicInitGlobalsInitialCapacity = 512;
44 struct DynInitGlobal {
48 typedef InternalMmapVector<DynInitGlobal> VectorOfGlobals;
49 // Lazy-initialized and never deleted.
50 static VectorOfGlobals *dynamic_init_globals;
52 // We want to remember where a certain range of globals was registered.
53 struct GlobalRegistrationSite {
55 Global *g_first, *g_last;
57 typedef InternalMmapVector<GlobalRegistrationSite> GlobalRegistrationSiteVector;
58 static GlobalRegistrationSiteVector *global_registration_site_vector;
60 ALWAYS_INLINE void PoisonShadowForGlobal(const Global *g, u8 value) {
61 FastPoisonShadow(g->beg, g->size_with_redzone, value);
64 ALWAYS_INLINE void PoisonRedZones(const Global &g) {
65 uptr aligned_size = RoundUpTo(g.size, SHADOW_GRANULARITY);
66 FastPoisonShadow(g.beg + aligned_size, g.size_with_redzone - aligned_size,
67 kAsanGlobalRedzoneMagic);
68 if (g.size != aligned_size) {
69 FastPoisonShadowPartialRightRedzone(
70 g.beg + RoundDownTo(g.size, SHADOW_GRANULARITY),
71 g.size % SHADOW_GRANULARITY,
73 kAsanGlobalRedzoneMagic);
77 const uptr kMinimalDistanceFromAnotherGlobal = 64;
79 static bool IsAddressNearGlobal(uptr addr, const __asan_global &g) {
80 if (addr <= g.beg - kMinimalDistanceFromAnotherGlobal) return false;
81 if (addr >= g.beg + g.size_with_redzone) return false;
85 static void ReportGlobal(const Global &g, const char *prefix) {
86 Report("%s Global[%p]: beg=%p size=%zu/%zu name=%s module=%s dyn_init=%zu\n",
87 prefix, &g, (void *)g.beg, g.size, g.size_with_redzone, g.name,
88 g.module_name, g.has_dynamic_init);
90 Report(" location (%p): name=%s[%p], %d %d\n", g.location,
91 g.location->filename, g.location->filename, g.location->line_no,
92 g.location->column_no);
96 static u32 FindRegistrationSite(const Global *g) {
97 mu_for_globals.CheckLocked();
98 CHECK(global_registration_site_vector);
99 for (uptr i = 0, n = global_registration_site_vector->size(); i < n; i++) {
100 GlobalRegistrationSite &grs = (*global_registration_site_vector)[i];
101 if (g >= grs.g_first && g <= grs.g_last)
107 int GetGlobalsForAddress(uptr addr, Global *globals, u32 *reg_sites,
109 if (!flags()->report_globals) return 0;
110 BlockingMutexLock lock(&mu_for_globals);
112 for (ListOfGlobals *l = list_of_all_globals; l; l = l->next) {
113 const Global &g = *l->g;
114 if (flags()->report_globals >= 2)
115 ReportGlobal(g, "Search");
116 if (IsAddressNearGlobal(addr, g)) {
119 reg_sites[res] = FindRegistrationSite(&g);
121 if (res == max_globals) break;
127 enum GlobalSymbolState {
132 // Check ODR violation for given global G via special ODR indicator. We use
133 // this method in case compiler instruments global variables through their
135 static void CheckODRViolationViaIndicator(const Global *g) {
136 u8 *odr_indicator = reinterpret_cast<u8 *>(g->odr_indicator);
137 if (*odr_indicator == UNREGISTERED) {
138 *odr_indicator = REGISTERED;
141 // If *odr_indicator is DEFINED, some module have already registered
142 // externally visible symbol with the same name. This is an ODR violation.
143 for (ListOfGlobals *l = list_of_all_globals; l; l = l->next) {
144 if (g->odr_indicator == l->g->odr_indicator &&
145 (flags()->detect_odr_violation >= 2 || g->size != l->g->size) &&
146 !IsODRViolationSuppressed(g->name))
147 ReportODRViolation(g, FindRegistrationSite(g),
148 l->g, FindRegistrationSite(l->g));
152 // Check ODR violation for given global G by checking if it's already poisoned.
153 // We use this method in case compiler doesn't use private aliases for global
155 static void CheckODRViolationViaPoisoning(const Global *g) {
156 if (__asan_region_is_poisoned(g->beg, g->size_with_redzone)) {
157 // This check may not be enough: if the first global is much larger
158 // the entire redzone of the second global may be within the first global.
159 for (ListOfGlobals *l = list_of_all_globals; l; l = l->next) {
160 if (g->beg == l->g->beg &&
161 (flags()->detect_odr_violation >= 2 || g->size != l->g->size) &&
162 !IsODRViolationSuppressed(g->name))
163 ReportODRViolation(g, FindRegistrationSite(g),
164 l->g, FindRegistrationSite(l->g));
169 // Clang provides two different ways for global variables protection:
170 // it can poison the global itself or its private alias. In former
171 // case we may poison same symbol multiple times, that can help us to
172 // cheaply detect ODR violation: if we try to poison an already poisoned
173 // global, we have ODR violation error.
174 // In latter case, we poison each symbol exactly once, so we use special
175 // indicator symbol to perform similar check.
176 // In either case, compiler provides a special odr_indicator field to Global
177 // structure, that can contain two kinds of values:
178 // 1) Non-zero value. In this case, odr_indicator is an address of
179 // corresponding indicator variable for given global.
180 // 2) Zero. This means that we don't use private aliases for global variables
181 // and can freely check ODR violation with the first method.
183 // This routine chooses between two different methods of ODR violation
185 static inline bool UseODRIndicator(const Global *g) {
186 // Use ODR indicator method iff use_odr_indicator flag is set and
187 // indicator symbol address is not 0.
188 return flags()->use_odr_indicator && g->odr_indicator > 0;
191 // Register a global variable.
192 // This function may be called more than once for every global
193 // so we store the globals in a map.
194 static void RegisterGlobal(const Global *g) {
196 if (flags()->report_globals >= 2)
197 ReportGlobal(*g, "Added");
198 CHECK(flags()->report_globals);
199 CHECK(AddrIsInMem(g->beg));
200 if (!AddrIsAlignedByGranularity(g->beg)) {
201 Report("The following global variable is not properly aligned.\n");
202 Report("This may happen if another global with the same name\n");
203 Report("resides in another non-instrumented module.\n");
204 Report("Or the global comes from a C file built w/o -fno-common.\n");
205 Report("In either case this is likely an ODR violation bug,\n");
206 Report("but AddressSanitizer can not provide more details.\n");
207 ReportODRViolation(g, FindRegistrationSite(g), g, FindRegistrationSite(g));
208 CHECK(AddrIsAlignedByGranularity(g->beg));
210 CHECK(AddrIsAlignedByGranularity(g->size_with_redzone));
211 if (flags()->detect_odr_violation) {
212 // Try detecting ODR (One Definition Rule) violation, i.e. the situation
213 // where two globals with the same name are defined in different modules.
214 if (UseODRIndicator(g))
215 CheckODRViolationViaIndicator(g);
217 CheckODRViolationViaPoisoning(g);
219 if (CanPoisonMemory())
221 ListOfGlobals *l = new(allocator_for_globals) ListOfGlobals;
223 l->next = list_of_all_globals;
224 list_of_all_globals = l;
225 if (g->has_dynamic_init) {
226 if (!dynamic_init_globals) {
227 dynamic_init_globals =
228 new (allocator_for_globals) VectorOfGlobals; // NOLINT
229 dynamic_init_globals->reserve(kDynamicInitGlobalsInitialCapacity);
231 DynInitGlobal dyn_global = { *g, false };
232 dynamic_init_globals->push_back(dyn_global);
236 static void UnregisterGlobal(const Global *g) {
238 if (flags()->report_globals >= 2)
239 ReportGlobal(*g, "Removed");
240 CHECK(flags()->report_globals);
241 CHECK(AddrIsInMem(g->beg));
242 CHECK(AddrIsAlignedByGranularity(g->beg));
243 CHECK(AddrIsAlignedByGranularity(g->size_with_redzone));
244 if (CanPoisonMemory())
245 PoisonShadowForGlobal(g, 0);
246 // We unpoison the shadow memory for the global but we do not remove it from
247 // the list because that would require O(n^2) time with the current list
248 // implementation. It might not be worth doing anyway.
250 // Release ODR indicator.
251 if (UseODRIndicator(g)) {
252 u8 *odr_indicator = reinterpret_cast<u8 *>(g->odr_indicator);
253 *odr_indicator = UNREGISTERED;
257 void StopInitOrderChecking() {
258 BlockingMutexLock lock(&mu_for_globals);
259 if (!flags()->check_initialization_order || !dynamic_init_globals)
261 flags()->check_initialization_order = false;
262 for (uptr i = 0, n = dynamic_init_globals->size(); i < n; ++i) {
263 DynInitGlobal &dyn_g = (*dynamic_init_globals)[i];
264 const Global *g = &dyn_g.g;
265 // Unpoison the whole global.
266 PoisonShadowForGlobal(g, 0);
267 // Poison redzones back.
272 static bool IsASCII(unsigned char c) { return /*0x00 <= c &&*/ c <= 0x7F; }
274 const char *MaybeDemangleGlobalName(const char *name) {
275 // We can spoil names of globals with C linkage, so use an heuristic
276 // approach to check if the name should be demangled.
277 bool should_demangle = false;
278 if (name[0] == '_' && name[1] == 'Z')
279 should_demangle = true;
280 else if (SANITIZER_WINDOWS && name[0] == '\01' && name[1] == '?')
281 should_demangle = true;
283 return should_demangle ? Symbolizer::GetOrInit()->Demangle(name) : name;
286 // Check if the global is a zero-terminated ASCII string. If so, print it.
287 void PrintGlobalNameIfASCII(InternalScopedString *str, const __asan_global &g) {
288 for (uptr p = g.beg; p < g.beg + g.size - 1; p++) {
289 unsigned char c = *(unsigned char *)p;
290 if (c == '\0' || !IsASCII(c)) return;
292 if (*(char *)(g.beg + g.size - 1) != '\0') return;
293 str->append(" '%s' is ascii string '%s'\n", MaybeDemangleGlobalName(g.name),
297 static const char *GlobalFilename(const __asan_global &g) {
298 const char *res = g.module_name;
299 // Prefer the filename from source location, if is available.
300 if (g.location) res = g.location->filename;
305 void PrintGlobalLocation(InternalScopedString *str, const __asan_global &g) {
306 str->append("%s", GlobalFilename(g));
307 if (!g.location) return;
308 if (g.location->line_no) str->append(":%d", g.location->line_no);
309 if (g.location->column_no) str->append(":%d", g.location->column_no);
312 } // namespace __asan
314 // ---------------------- Interface ---------------- {{{1
315 using namespace __asan; // NOLINT
318 // Apply __asan_register_globals to all globals found in the same loaded
319 // executable or shared library as `flag'. The flag tracks whether globals have
320 // already been registered or not for this image.
321 void __asan_register_image_globals(uptr *flag) {
324 AsanApplyToGlobals(__asan_register_globals, flag);
328 // This mirrors __asan_register_image_globals.
329 void __asan_unregister_image_globals(uptr *flag) {
332 AsanApplyToGlobals(__asan_unregister_globals, flag);
336 void __asan_register_elf_globals(uptr *flag, void *start, void *stop) {
339 CHECK_EQ(0, ((uptr)stop - (uptr)start) % sizeof(__asan_global));
340 __asan_global *globals_start = (__asan_global*)start;
341 __asan_global *globals_stop = (__asan_global*)stop;
342 __asan_register_globals(globals_start, globals_stop - globals_start);
346 void __asan_unregister_elf_globals(uptr *flag, void *start, void *stop) {
349 CHECK_EQ(0, ((uptr)stop - (uptr)start) % sizeof(__asan_global));
350 __asan_global *globals_start = (__asan_global*)start;
351 __asan_global *globals_stop = (__asan_global*)stop;
352 __asan_unregister_globals(globals_start, globals_stop - globals_start);
356 // Register an array of globals.
357 void __asan_register_globals(__asan_global *globals, uptr n) {
358 if (!flags()->report_globals) return;
359 GET_STACK_TRACE_MALLOC;
360 u32 stack_id = StackDepotPut(stack);
361 BlockingMutexLock lock(&mu_for_globals);
362 if (!global_registration_site_vector) {
363 global_registration_site_vector =
364 new (allocator_for_globals) GlobalRegistrationSiteVector; // NOLINT
365 global_registration_site_vector->reserve(128);
367 GlobalRegistrationSite site = {stack_id, &globals[0], &globals[n - 1]};
368 global_registration_site_vector->push_back(site);
369 if (flags()->report_globals >= 2) {
370 PRINT_CURRENT_STACK();
371 Printf("=== ID %d; %p %p\n", stack_id, &globals[0], &globals[n - 1]);
373 for (uptr i = 0; i < n; i++) {
374 if (SANITIZER_WINDOWS && globals[i].beg == 0) {
375 // The MSVC incremental linker may pad globals out to 256 bytes. As long
376 // as __asan_global is less than 256 bytes large and its size is a power
377 // of two, we can skip over the padding.
379 sizeof(__asan_global) < 256 &&
380 (sizeof(__asan_global) & (sizeof(__asan_global) - 1)) == 0,
381 "sizeof(__asan_global) incompatible with incremental linker padding");
382 // If these are padding bytes, the rest of the global should be zero.
383 CHECK(globals[i].size == 0 && globals[i].size_with_redzone == 0 &&
384 globals[i].name == nullptr && globals[i].module_name == nullptr &&
385 globals[i].odr_indicator == 0);
388 RegisterGlobal(&globals[i]);
391 // Poison the metadata. It should not be accessible to user code.
392 PoisonShadow(reinterpret_cast<uptr>(globals), n * sizeof(__asan_global),
393 kAsanGlobalRedzoneMagic);
396 // Unregister an array of globals.
397 // We must do this when a shared objects gets dlclosed.
398 void __asan_unregister_globals(__asan_global *globals, uptr n) {
399 if (!flags()->report_globals) return;
400 BlockingMutexLock lock(&mu_for_globals);
401 for (uptr i = 0; i < n; i++) {
402 if (SANITIZER_WINDOWS && globals[i].beg == 0) {
403 // Skip globals that look like padding from the MSVC incremental linker.
404 // See comment in __asan_register_globals.
407 UnregisterGlobal(&globals[i]);
410 // Unpoison the metadata.
411 PoisonShadow(reinterpret_cast<uptr>(globals), n * sizeof(__asan_global), 0);
414 // This method runs immediately prior to dynamic initialization in each TU,
415 // when all dynamically initialized globals are unpoisoned. This method
416 // poisons all global variables not defined in this TU, so that a dynamic
417 // initializer can only touch global variables in the same TU.
418 void __asan_before_dynamic_init(const char *module_name) {
419 if (!flags()->check_initialization_order ||
420 !CanPoisonMemory() ||
421 !dynamic_init_globals)
423 bool strict_init_order = flags()->strict_init_order;
426 BlockingMutexLock lock(&mu_for_globals);
427 if (flags()->report_globals >= 3)
428 Printf("DynInitPoison module: %s\n", module_name);
429 for (uptr i = 0, n = dynamic_init_globals->size(); i < n; ++i) {
430 DynInitGlobal &dyn_g = (*dynamic_init_globals)[i];
431 const Global *g = &dyn_g.g;
432 if (dyn_g.initialized)
434 if (g->module_name != module_name)
435 PoisonShadowForGlobal(g, kAsanInitializationOrderMagic);
436 else if (!strict_init_order)
437 dyn_g.initialized = true;
441 // This method runs immediately after dynamic initialization in each TU, when
442 // all dynamically initialized globals except for those defined in the current
443 // TU are poisoned. It simply unpoisons all dynamically initialized globals.
444 void __asan_after_dynamic_init() {
445 if (!flags()->check_initialization_order ||
446 !CanPoisonMemory() ||
447 !dynamic_init_globals)
450 BlockingMutexLock lock(&mu_for_globals);
451 // FIXME: Optionally report that we're unpoisoning globals from a module.
452 for (uptr i = 0, n = dynamic_init_globals->size(); i < n; ++i) {
453 DynInitGlobal &dyn_g = (*dynamic_init_globals)[i];
454 const Global *g = &dyn_g.g;
455 if (!dyn_g.initialized) {
456 // Unpoison the whole global.
457 PoisonShadowForGlobal(g, 0);
458 // Poison redzones back.