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 //===----------------------------------------------------------------------===//
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_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"
29 typedef __asan_global Global;
31 struct ListOfGlobals {
36 static BlockingMutex mu_for_globals(LINKER_INITIALIZED);
37 static LowLevelAllocator allocator_for_globals;
38 static ListOfGlobals *list_of_all_globals;
40 static const int kDynamicInitGlobalsInitialCapacity = 512;
41 struct DynInitGlobal {
45 typedef InternalMmapVector<DynInitGlobal> VectorOfGlobals;
46 // Lazy-initialized and never deleted.
47 static VectorOfGlobals *dynamic_init_globals;
49 // We want to remember where a certain range of globals was registered.
50 struct GlobalRegistrationSite {
52 Global *g_first, *g_last;
54 typedef InternalMmapVector<GlobalRegistrationSite> GlobalRegistrationSiteVector;
55 static GlobalRegistrationSiteVector *global_registration_site_vector;
57 ALWAYS_INLINE void PoisonShadowForGlobal(const Global *g, u8 value) {
58 FastPoisonShadow(g->beg, g->size_with_redzone, value);
61 ALWAYS_INLINE void PoisonRedZones(const Global &g) {
62 uptr aligned_size = RoundUpTo(g.size, SHADOW_GRANULARITY);
63 FastPoisonShadow(g.beg + aligned_size, g.size_with_redzone - aligned_size,
64 kAsanGlobalRedzoneMagic);
65 if (g.size != aligned_size) {
66 FastPoisonShadowPartialRightRedzone(
67 g.beg + RoundDownTo(g.size, SHADOW_GRANULARITY),
68 g.size % SHADOW_GRANULARITY,
70 kAsanGlobalRedzoneMagic);
74 const uptr kMinimalDistanceFromAnotherGlobal = 64;
76 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;
82 static void ReportGlobal(const Global &g, const char *prefix) {
83 Report("%s Global[%p]: beg=%p size=%zu/%zu name=%s module=%s dyn_init=%zu\n",
84 prefix, &g, (void *)g.beg, g.size, g.size_with_redzone, g.name,
85 g.module_name, g.has_dynamic_init);
87 Report(" location (%p): name=%s[%p], %d %d\n", g.location,
88 g.location->filename, g.location->filename, g.location->line_no,
89 g.location->column_no);
93 static bool DescribeOrGetInfoIfGlobal(uptr addr, uptr size, bool print,
94 Global *output_global) {
95 if (!flags()->report_globals) return false;
96 BlockingMutexLock lock(&mu_for_globals);
98 for (ListOfGlobals *l = list_of_all_globals; l; l = l->next) {
99 const Global &g = *l->g;
101 if (flags()->report_globals >= 2)
102 ReportGlobal(g, "Search");
103 res |= DescribeAddressRelativeToGlobal(addr, size, g);
105 if (IsAddressNearGlobal(addr, g)) {
106 CHECK(output_global);
115 bool DescribeAddressIfGlobal(uptr addr, uptr size) {
116 return DescribeOrGetInfoIfGlobal(addr, size, /* print */ true,
117 /* output_global */ nullptr);
120 bool GetInfoForAddressIfGlobal(uptr addr, AddressDescription *descr) {
122 if (DescribeOrGetInfoIfGlobal(addr, /* size */ 1, /* print */ false, &g)) {
123 internal_strncpy(descr->name, g.name, descr->name_size);
124 descr->region_address = g.beg;
125 descr->region_size = g.size;
126 descr->region_kind = "global";
132 u32 FindRegistrationSite(const Global *g) {
133 CHECK(global_registration_site_vector);
134 for (uptr i = 0, n = global_registration_site_vector->size(); i < n; i++) {
135 GlobalRegistrationSite &grs = (*global_registration_site_vector)[i];
136 if (g >= grs.g_first && g <= grs.g_last)
142 // Register a global variable.
143 // This function may be called more than once for every global
144 // so we store the globals in a map.
145 static void RegisterGlobal(const Global *g) {
147 if (flags()->report_globals >= 2)
148 ReportGlobal(*g, "Added");
149 CHECK(flags()->report_globals);
150 CHECK(AddrIsInMem(g->beg));
151 CHECK(AddrIsAlignedByGranularity(g->beg));
152 CHECK(AddrIsAlignedByGranularity(g->size_with_redzone));
153 if (flags()->detect_odr_violation) {
154 // Try detecting ODR (One Definition Rule) violation, i.e. the situation
155 // where two globals with the same name are defined in different modules.
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 ReportODRViolation(g, FindRegistrationSite(g),
163 l->g, FindRegistrationSite(l->g));
167 if (CanPoisonMemory())
169 ListOfGlobals *l = new(allocator_for_globals) ListOfGlobals;
171 l->next = list_of_all_globals;
172 list_of_all_globals = l;
173 if (g->has_dynamic_init) {
174 if (dynamic_init_globals == 0) {
175 dynamic_init_globals = new(allocator_for_globals)
176 VectorOfGlobals(kDynamicInitGlobalsInitialCapacity);
178 DynInitGlobal dyn_global = { *g, false };
179 dynamic_init_globals->push_back(dyn_global);
183 static void UnregisterGlobal(const Global *g) {
185 if (flags()->report_globals >= 2)
186 ReportGlobal(*g, "Removed");
187 CHECK(flags()->report_globals);
188 CHECK(AddrIsInMem(g->beg));
189 CHECK(AddrIsAlignedByGranularity(g->beg));
190 CHECK(AddrIsAlignedByGranularity(g->size_with_redzone));
191 if (CanPoisonMemory())
192 PoisonShadowForGlobal(g, 0);
193 // We unpoison the shadow memory for the global but we do not remove it from
194 // the list because that would require O(n^2) time with the current list
195 // implementation. It might not be worth doing anyway.
198 void StopInitOrderChecking() {
199 BlockingMutexLock lock(&mu_for_globals);
200 if (!flags()->check_initialization_order || !dynamic_init_globals)
202 flags()->check_initialization_order = false;
203 for (uptr i = 0, n = dynamic_init_globals->size(); i < n; ++i) {
204 DynInitGlobal &dyn_g = (*dynamic_init_globals)[i];
205 const Global *g = &dyn_g.g;
206 // Unpoison the whole global.
207 PoisonShadowForGlobal(g, 0);
208 // Poison redzones back.
213 #if SANITIZER_WINDOWS // Should only be called on Windows.
214 SANITIZER_INTERFACE_ATTRIBUTE
215 void UnregisterGlobalsInRange(void *beg, void *end) {
216 if (!flags()->report_globals)
218 BlockingMutexLock lock(&mu_for_globals);
219 for (ListOfGlobals *l = list_of_all_globals; l; l = l->next) {
220 void *address = (void *)l->g->beg;
221 if (beg <= address && address < end)
222 UnregisterGlobal(l->g);
227 } // namespace __asan
229 // ---------------------- Interface ---------------- {{{1
230 using namespace __asan; // NOLINT
232 // Register an array of globals.
233 void __asan_register_globals(__asan_global *globals, uptr n) {
234 if (!flags()->report_globals) return;
235 GET_STACK_TRACE_FATAL_HERE;
236 u32 stack_id = StackDepotPut(stack);
237 BlockingMutexLock lock(&mu_for_globals);
238 if (!global_registration_site_vector)
239 global_registration_site_vector =
240 new(allocator_for_globals) GlobalRegistrationSiteVector(128);
241 GlobalRegistrationSite site = {stack_id, &globals[0], &globals[n - 1]};
242 global_registration_site_vector->push_back(site);
243 if (flags()->report_globals >= 2) {
244 PRINT_CURRENT_STACK();
245 Printf("=== ID %d; %p %p\n", stack_id, &globals[0], &globals[n - 1]);
247 for (uptr i = 0; i < n; i++) {
248 RegisterGlobal(&globals[i]);
252 // Unregister an array of globals.
253 // We must do this when a shared objects gets dlclosed.
254 void __asan_unregister_globals(__asan_global *globals, uptr n) {
255 if (!flags()->report_globals) return;
256 BlockingMutexLock lock(&mu_for_globals);
257 for (uptr i = 0; i < n; i++) {
258 UnregisterGlobal(&globals[i]);
262 // This method runs immediately prior to dynamic initialization in each TU,
263 // when all dynamically initialized globals are unpoisoned. This method
264 // poisons all global variables not defined in this TU, so that a dynamic
265 // initializer can only touch global variables in the same TU.
266 void __asan_before_dynamic_init(const char *module_name) {
267 if (!flags()->check_initialization_order ||
270 bool strict_init_order = flags()->strict_init_order;
271 CHECK(dynamic_init_globals);
274 BlockingMutexLock lock(&mu_for_globals);
275 if (flags()->report_globals >= 3)
276 Printf("DynInitPoison module: %s\n", module_name);
277 for (uptr i = 0, n = dynamic_init_globals->size(); i < n; ++i) {
278 DynInitGlobal &dyn_g = (*dynamic_init_globals)[i];
279 const Global *g = &dyn_g.g;
280 if (dyn_g.initialized)
282 if (g->module_name != module_name)
283 PoisonShadowForGlobal(g, kAsanInitializationOrderMagic);
284 else if (!strict_init_order)
285 dyn_g.initialized = true;
289 // This method runs immediately after dynamic initialization in each TU, when
290 // all dynamically initialized globals except for those defined in the current
291 // TU are poisoned. It simply unpoisons all dynamically initialized globals.
292 void __asan_after_dynamic_init() {
293 if (!flags()->check_initialization_order ||
297 BlockingMutexLock lock(&mu_for_globals);
298 // FIXME: Optionally report that we're unpoisoning globals from a module.
299 for (uptr i = 0, n = dynamic_init_globals->size(); i < n; ++i) {
300 DynInitGlobal &dyn_g = (*dynamic_init_globals)[i];
301 const Global *g = &dyn_g.g;
302 if (!dyn_g.initialized) {
303 // Unpoison the whole global.
304 PoisonShadowForGlobal(g, 0);
305 // Poison redzones back.