1 //===-- asan_globals.cc ---------------------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file is a part of AddressSanitizer, an address sanity checker.
11 //
12 // Handle globals.
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_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 
28 namespace __asan {
29 
30 typedef __asan_global Global;
31 
32 struct ListOfGlobals {
33   const Global *g;
34   ListOfGlobals *next;
35 };
36 
37 static BlockingMutex mu_for_globals(LINKER_INITIALIZED);
38 static LowLevelAllocator allocator_for_globals;
39 static ListOfGlobals *list_of_all_globals;
40 
41 static const int kDynamicInitGlobalsInitialCapacity = 512;
42 struct DynInitGlobal {
43   Global g;
44   bool initialized;
45 };
46 typedef InternalMmapVector<DynInitGlobal> VectorOfGlobals;
47 // Lazy-initialized and never deleted.
48 static VectorOfGlobals *dynamic_init_globals;
49 
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;
54 };
55 typedef InternalMmapVector<GlobalRegistrationSite> GlobalRegistrationSiteVector;
56 static GlobalRegistrationSiteVector *global_registration_site_vector;
57 
PoisonShadowForGlobal(const Global * g,u8 value)58 ALWAYS_INLINE void PoisonShadowForGlobal(const Global *g, u8 value) {
59   FastPoisonShadow(g->beg, g->size_with_redzone, value);
60 }
61 
PoisonRedZones(const Global & g)62 ALWAYS_INLINE void PoisonRedZones(const Global &g) {
63   uptr aligned_size = RoundUpTo(g.size, 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, SHADOW_GRANULARITY),
69         g.size % SHADOW_GRANULARITY,
70         SHADOW_GRANULARITY,
71         kAsanGlobalRedzoneMagic);
72   }
73 }
74 
75 const uptr kMinimalDistanceFromAnotherGlobal = 64;
76 
IsAddressNearGlobal(uptr addr,const __asan_global & g)77 bool IsAddressNearGlobal(uptr addr, const __asan_global &g) {
78   if (addr <= g.beg - kMinimalDistanceFromAnotherGlobal) return false;
79   if (addr >= g.beg + g.size_with_redzone) return false;
80   return true;
81 }
82 
ReportGlobal(const Global & g,const char * prefix)83 static void ReportGlobal(const Global &g, const char *prefix) {
84   Report("%s Global[%p]: beg=%p size=%zu/%zu name=%s module=%s dyn_init=%zu\n",
85          prefix, &g, (void *)g.beg, g.size, g.size_with_redzone, g.name,
86          g.module_name, g.has_dynamic_init);
87   if (g.location) {
88     Report("  location (%p): name=%s[%p], %d %d\n", g.location,
89            g.location->filename, g.location->filename, g.location->line_no,
90            g.location->column_no);
91   }
92 }
93 
DescribeOrGetInfoIfGlobal(uptr addr,uptr size,bool print,Global * output_global)94 static bool DescribeOrGetInfoIfGlobal(uptr addr, uptr size, bool print,
95                                       Global *output_global) {
96   if (!flags()->report_globals) return false;
97   BlockingMutexLock lock(&mu_for_globals);
98   bool res = false;
99   for (ListOfGlobals *l = list_of_all_globals; l; l = l->next) {
100     const Global &g = *l->g;
101     if (print) {
102       if (flags()->report_globals >= 2)
103         ReportGlobal(g, "Search");
104       res |= DescribeAddressRelativeToGlobal(addr, size, g);
105     } else {
106       if (IsAddressNearGlobal(addr, g)) {
107         CHECK(output_global);
108         *output_global = g;
109         return true;
110       }
111     }
112   }
113   return res;
114 }
115 
DescribeAddressIfGlobal(uptr addr,uptr size)116 bool DescribeAddressIfGlobal(uptr addr, uptr size) {
117   return DescribeOrGetInfoIfGlobal(addr, size, /* print */ true,
118                                    /* output_global */ nullptr);
119 }
120 
GetInfoForAddressIfGlobal(uptr addr,AddressDescription * descr)121 bool GetInfoForAddressIfGlobal(uptr addr, AddressDescription *descr) {
122   Global g = {};
123   if (DescribeOrGetInfoIfGlobal(addr, /* size */ 1, /* print */ false, &g)) {
124     internal_strncpy(descr->name, g.name, descr->name_size);
125     descr->region_address = g.beg;
126     descr->region_size = g.size;
127     descr->region_kind = "global";
128     return true;
129   }
130   return false;
131 }
132 
FindRegistrationSite(const Global * g)133 u32 FindRegistrationSite(const Global *g) {
134   CHECK(global_registration_site_vector);
135   for (uptr i = 0, n = global_registration_site_vector->size(); i < n; i++) {
136     GlobalRegistrationSite &grs = (*global_registration_site_vector)[i];
137     if (g >= grs.g_first && g <= grs.g_last)
138       return grs.stack_id;
139   }
140   return 0;
141 }
142 
143 // Register a global variable.
144 // This function may be called more than once for every global
145 // so we store the globals in a map.
RegisterGlobal(const Global * g)146 static void RegisterGlobal(const Global *g) {
147   CHECK(asan_inited);
148   if (flags()->report_globals >= 2)
149     ReportGlobal(*g, "Added");
150   CHECK(flags()->report_globals);
151   CHECK(AddrIsInMem(g->beg));
152   CHECK(AddrIsAlignedByGranularity(g->beg));
153   CHECK(AddrIsAlignedByGranularity(g->size_with_redzone));
154   if (flags()->detect_odr_violation) {
155     // Try detecting ODR (One Definition Rule) violation, i.e. the situation
156     // where two globals with the same name are defined in different modules.
157     if (__asan_region_is_poisoned(g->beg, g->size_with_redzone)) {
158       // This check may not be enough: if the first global is much larger
159       // the entire redzone of the second global may be within the first global.
160       for (ListOfGlobals *l = list_of_all_globals; l; l = l->next) {
161         if (g->beg == l->g->beg &&
162             (flags()->detect_odr_violation >= 2 || g->size != l->g->size) &&
163             !IsODRViolationSuppressed(g->name))
164           ReportODRViolation(g, FindRegistrationSite(g),
165                              l->g, FindRegistrationSite(l->g));
166       }
167     }
168   }
169   if (CanPoisonMemory())
170     PoisonRedZones(*g);
171   ListOfGlobals *l = new(allocator_for_globals) ListOfGlobals;
172   l->g = g;
173   l->next = list_of_all_globals;
174   list_of_all_globals = l;
175   if (g->has_dynamic_init) {
176     if (dynamic_init_globals == 0) {
177       dynamic_init_globals = new(allocator_for_globals)
178           VectorOfGlobals(kDynamicInitGlobalsInitialCapacity);
179     }
180     DynInitGlobal dyn_global = { *g, false };
181     dynamic_init_globals->push_back(dyn_global);
182   }
183 }
184 
UnregisterGlobal(const Global * g)185 static void UnregisterGlobal(const Global *g) {
186   CHECK(asan_inited);
187   if (flags()->report_globals >= 2)
188     ReportGlobal(*g, "Removed");
189   CHECK(flags()->report_globals);
190   CHECK(AddrIsInMem(g->beg));
191   CHECK(AddrIsAlignedByGranularity(g->beg));
192   CHECK(AddrIsAlignedByGranularity(g->size_with_redzone));
193   if (CanPoisonMemory())
194     PoisonShadowForGlobal(g, 0);
195   // We unpoison the shadow memory for the global but we do not remove it from
196   // the list because that would require O(n^2) time with the current list
197   // implementation. It might not be worth doing anyway.
198 }
199 
StopInitOrderChecking()200 void StopInitOrderChecking() {
201   BlockingMutexLock lock(&mu_for_globals);
202   if (!flags()->check_initialization_order || !dynamic_init_globals)
203     return;
204   flags()->check_initialization_order = false;
205   for (uptr i = 0, n = dynamic_init_globals->size(); i < n; ++i) {
206     DynInitGlobal &dyn_g = (*dynamic_init_globals)[i];
207     const Global *g = &dyn_g.g;
208     // Unpoison the whole global.
209     PoisonShadowForGlobal(g, 0);
210     // Poison redzones back.
211     PoisonRedZones(*g);
212   }
213 }
214 
215 }  // namespace __asan
216 
217 // ---------------------- Interface ---------------- {{{1
218 using namespace __asan;  // NOLINT
219 
220 // Register an array of globals.
__asan_register_globals(__asan_global * globals,uptr n)221 void __asan_register_globals(__asan_global *globals, uptr n) {
222   if (!flags()->report_globals) return;
223   GET_STACK_TRACE_MALLOC;
224   u32 stack_id = StackDepotPut(stack);
225   BlockingMutexLock lock(&mu_for_globals);
226   if (!global_registration_site_vector)
227     global_registration_site_vector =
228         new(allocator_for_globals) GlobalRegistrationSiteVector(128);
229   GlobalRegistrationSite site = {stack_id, &globals[0], &globals[n - 1]};
230   global_registration_site_vector->push_back(site);
231   if (flags()->report_globals >= 2) {
232     PRINT_CURRENT_STACK();
233     Printf("=== ID %d; %p %p\n", stack_id, &globals[0], &globals[n - 1]);
234   }
235   for (uptr i = 0; i < n; i++) {
236     RegisterGlobal(&globals[i]);
237   }
238 }
239 
240 // Unregister an array of globals.
241 // We must do this when a shared objects gets dlclosed.
__asan_unregister_globals(__asan_global * globals,uptr n)242 void __asan_unregister_globals(__asan_global *globals, uptr n) {
243   if (!flags()->report_globals) return;
244   BlockingMutexLock lock(&mu_for_globals);
245   for (uptr i = 0; i < n; i++) {
246     UnregisterGlobal(&globals[i]);
247   }
248 }
249 
250 // This method runs immediately prior to dynamic initialization in each TU,
251 // when all dynamically initialized globals are unpoisoned.  This method
252 // poisons all global variables not defined in this TU, so that a dynamic
253 // initializer can only touch global variables in the same TU.
__asan_before_dynamic_init(const char * module_name)254 void __asan_before_dynamic_init(const char *module_name) {
255   if (!flags()->check_initialization_order ||
256       !CanPoisonMemory())
257     return;
258   bool strict_init_order = flags()->strict_init_order;
259   CHECK(dynamic_init_globals);
260   CHECK(module_name);
261   CHECK(asan_inited);
262   BlockingMutexLock lock(&mu_for_globals);
263   if (flags()->report_globals >= 3)
264     Printf("DynInitPoison module: %s\n", module_name);
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     if (dyn_g.initialized)
269       continue;
270     if (g->module_name != module_name)
271       PoisonShadowForGlobal(g, kAsanInitializationOrderMagic);
272     else if (!strict_init_order)
273       dyn_g.initialized = true;
274   }
275 }
276 
277 // This method runs immediately after dynamic initialization in each TU, when
278 // all dynamically initialized globals except for those defined in the current
279 // TU are poisoned.  It simply unpoisons all dynamically initialized globals.
__asan_after_dynamic_init()280 void __asan_after_dynamic_init() {
281   if (!flags()->check_initialization_order ||
282       !CanPoisonMemory())
283     return;
284   CHECK(asan_inited);
285   BlockingMutexLock lock(&mu_for_globals);
286   // FIXME: Optionally report that we're unpoisoning globals from a module.
287   for (uptr i = 0, n = dynamic_init_globals->size(); i < n; ++i) {
288     DynInitGlobal &dyn_g = (*dynamic_init_globals)[i];
289     const Global *g = &dyn_g.g;
290     if (!dyn_g.initialized) {
291       // Unpoison the whole global.
292       PoisonShadowForGlobal(g, 0);
293       // Poison redzones back.
294       PoisonRedZones(*g);
295     }
296   }
297 }
298