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 = new(allocator_for_globals)
228 VectorOfGlobals(kDynamicInitGlobalsInitialCapacity);
230 DynInitGlobal dyn_global = { *g, false };
231 dynamic_init_globals->push_back(dyn_global);
235 static void UnregisterGlobal(const Global *g) {
237 if (flags()->report_globals >= 2)
238 ReportGlobal(*g, "Removed");
239 CHECK(flags()->report_globals);
240 CHECK(AddrIsInMem(g->beg));
241 CHECK(AddrIsAlignedByGranularity(g->beg));
242 CHECK(AddrIsAlignedByGranularity(g->size_with_redzone));
243 if (CanPoisonMemory())
244 PoisonShadowForGlobal(g, 0);
245 // We unpoison the shadow memory for the global but we do not remove it from
246 // the list because that would require O(n^2) time with the current list
247 // implementation. It might not be worth doing anyway.
249 // Release ODR indicator.
250 if (UseODRIndicator(g)) {
251 u8 *odr_indicator = reinterpret_cast<u8 *>(g->odr_indicator);
252 *odr_indicator = UNREGISTERED;
256 void StopInitOrderChecking() {
257 BlockingMutexLock lock(&mu_for_globals);
258 if (!flags()->check_initialization_order || !dynamic_init_globals)
260 flags()->check_initialization_order = false;
261 for (uptr i = 0, n = dynamic_init_globals->size(); i < n; ++i) {
262 DynInitGlobal &dyn_g = (*dynamic_init_globals)[i];
263 const Global *g = &dyn_g.g;
264 // Unpoison the whole global.
265 PoisonShadowForGlobal(g, 0);
266 // Poison redzones back.
271 static bool IsASCII(unsigned char c) { return /*0x00 <= c &&*/ c <= 0x7F; }
273 const char *MaybeDemangleGlobalName(const char *name) {
274 // We can spoil names of globals with C linkage, so use an heuristic
275 // approach to check if the name should be demangled.
276 bool should_demangle = false;
277 if (name[0] == '_' && name[1] == 'Z')
278 should_demangle = true;
279 else if (SANITIZER_WINDOWS && name[0] == '\01' && name[1] == '?')
280 should_demangle = true;
282 return should_demangle ? Symbolizer::GetOrInit()->Demangle(name) : name;
285 // Check if the global is a zero-terminated ASCII string. If so, print it.
286 void PrintGlobalNameIfASCII(InternalScopedString *str, const __asan_global &g) {
287 for (uptr p = g.beg; p < g.beg + g.size - 1; p++) {
288 unsigned char c = *(unsigned char *)p;
289 if (c == '\0' || !IsASCII(c)) return;
291 if (*(char *)(g.beg + g.size - 1) != '\0') return;
292 str->append(" '%s' is ascii string '%s'\n", MaybeDemangleGlobalName(g.name),
296 static const char *GlobalFilename(const __asan_global &g) {
297 const char *res = g.module_name;
298 // Prefer the filename from source location, if is available.
299 if (g.location) res = g.location->filename;
304 void PrintGlobalLocation(InternalScopedString *str, const __asan_global &g) {
305 str->append("%s", GlobalFilename(g));
306 if (!g.location) return;
307 if (g.location->line_no) str->append(":%d", g.location->line_no);
308 if (g.location->column_no) str->append(":%d", g.location->column_no);
311 } // namespace __asan
313 // ---------------------- Interface ---------------- {{{1
314 using namespace __asan; // NOLINT
317 // Apply __asan_register_globals to all globals found in the same loaded
318 // executable or shared library as `flag'. The flag tracks whether globals have
319 // already been registered or not for this image.
320 void __asan_register_image_globals(uptr *flag) {
323 AsanApplyToGlobals(__asan_register_globals, flag);
327 // This mirrors __asan_register_image_globals.
328 void __asan_unregister_image_globals(uptr *flag) {
331 AsanApplyToGlobals(__asan_unregister_globals, flag);
335 void __asan_register_elf_globals(uptr *flag, void *start, void *stop) {
338 CHECK_EQ(0, ((uptr)stop - (uptr)start) % sizeof(__asan_global));
339 __asan_global *globals_start = (__asan_global*)start;
340 __asan_global *globals_stop = (__asan_global*)stop;
341 __asan_register_globals(globals_start, globals_stop - globals_start);
345 void __asan_unregister_elf_globals(uptr *flag, void *start, void *stop) {
348 CHECK_EQ(0, ((uptr)stop - (uptr)start) % sizeof(__asan_global));
349 __asan_global *globals_start = (__asan_global*)start;
350 __asan_global *globals_stop = (__asan_global*)stop;
351 __asan_unregister_globals(globals_start, globals_stop - globals_start);
355 // Register an array of globals.
356 void __asan_register_globals(__asan_global *globals, uptr n) {
357 if (!flags()->report_globals) return;
358 GET_STACK_TRACE_MALLOC;
359 u32 stack_id = StackDepotPut(stack);
360 BlockingMutexLock lock(&mu_for_globals);
361 if (!global_registration_site_vector)
362 global_registration_site_vector =
363 new(allocator_for_globals) GlobalRegistrationSiteVector(128);
364 GlobalRegistrationSite site = {stack_id, &globals[0], &globals[n - 1]};
365 global_registration_site_vector->push_back(site);
366 if (flags()->report_globals >= 2) {
367 PRINT_CURRENT_STACK();
368 Printf("=== ID %d; %p %p\n", stack_id, &globals[0], &globals[n - 1]);
370 for (uptr i = 0; i < n; i++) {
371 if (SANITIZER_WINDOWS && globals[i].beg == 0) {
372 // The MSVC incremental linker may pad globals out to 256 bytes. As long
373 // as __asan_global is less than 256 bytes large and its size is a power
374 // of two, we can skip over the padding.
376 sizeof(__asan_global) < 256 &&
377 (sizeof(__asan_global) & (sizeof(__asan_global) - 1)) == 0,
378 "sizeof(__asan_global) incompatible with incremental linker padding");
379 // If these are padding bytes, the rest of the global should be zero.
380 CHECK(globals[i].size == 0 && globals[i].size_with_redzone == 0 &&
381 globals[i].name == nullptr && globals[i].module_name == nullptr &&
382 globals[i].odr_indicator == 0);
385 RegisterGlobal(&globals[i]);
388 // Poison the metadata. It should not be accessible to user code.
389 PoisonShadow(reinterpret_cast<uptr>(globals), n * sizeof(__asan_global),
390 kAsanGlobalRedzoneMagic);
393 // Unregister an array of globals.
394 // We must do this when a shared objects gets dlclosed.
395 void __asan_unregister_globals(__asan_global *globals, uptr n) {
396 if (!flags()->report_globals) return;
397 BlockingMutexLock lock(&mu_for_globals);
398 for (uptr i = 0; i < n; i++) {
399 if (SANITIZER_WINDOWS && globals[i].beg == 0) {
400 // Skip globals that look like padding from the MSVC incremental linker.
401 // See comment in __asan_register_globals.
404 UnregisterGlobal(&globals[i]);
407 // Unpoison the metadata.
408 PoisonShadow(reinterpret_cast<uptr>(globals), n * sizeof(__asan_global), 0);
411 // This method runs immediately prior to dynamic initialization in each TU,
412 // when all dynamically initialized globals are unpoisoned. This method
413 // poisons all global variables not defined in this TU, so that a dynamic
414 // initializer can only touch global variables in the same TU.
415 void __asan_before_dynamic_init(const char *module_name) {
416 if (!flags()->check_initialization_order ||
417 !CanPoisonMemory() ||
418 !dynamic_init_globals)
420 bool strict_init_order = flags()->strict_init_order;
423 BlockingMutexLock lock(&mu_for_globals);
424 if (flags()->report_globals >= 3)
425 Printf("DynInitPoison module: %s\n", module_name);
426 for (uptr i = 0, n = dynamic_init_globals->size(); i < n; ++i) {
427 DynInitGlobal &dyn_g = (*dynamic_init_globals)[i];
428 const Global *g = &dyn_g.g;
429 if (dyn_g.initialized)
431 if (g->module_name != module_name)
432 PoisonShadowForGlobal(g, kAsanInitializationOrderMagic);
433 else if (!strict_init_order)
434 dyn_g.initialized = true;
438 // This method runs immediately after dynamic initialization in each TU, when
439 // all dynamically initialized globals except for those defined in the current
440 // TU are poisoned. It simply unpoisons all dynamically initialized globals.
441 void __asan_after_dynamic_init() {
442 if (!flags()->check_initialization_order ||
443 !CanPoisonMemory() ||
444 !dynamic_init_globals)
447 BlockingMutexLock lock(&mu_for_globals);
448 // FIXME: Optionally report that we're unpoisoning globals from a module.
449 for (uptr i = 0, n = dynamic_init_globals->size(); i < n; ++i) {
450 DynInitGlobal &dyn_g = (*dynamic_init_globals)[i];
451 const Global *g = &dyn_g.g;
452 if (!dyn_g.initialized) {
453 // Unpoison the whole global.
454 PoisonShadowForGlobal(g, 0);
455 // Poison redzones back.