1 //===-- asan_globals.cc ---------------------------------------------------===//
2 //
3 // This file is distributed under the University of Illinois Open Source
4 // License. See LICENSE.TXT for details.
5 //
6 //===----------------------------------------------------------------------===//
7 //
8 // This file is a part of AddressSanitizer, an address sanity checker.
9 //
10 // Handle globals.
11 //===----------------------------------------------------------------------===//
12 
13 #include "asan_interceptors.h"
14 #include "asan_internal.h"
15 #include "asan_mapping.h"
16 #include "asan_poisoning.h"
17 #include "asan_report.h"
18 #include "asan_stack.h"
19 #include "asan_stats.h"
20 #include "asan_suppressions.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"
26 #include "sanitizer_common/sanitizer_symbolizer.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 static 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 
FindRegistrationSite(const Global * g)94 static u32 FindRegistrationSite(const Global *g) {
95   mu_for_globals.CheckLocked();
96   CHECK(global_registration_site_vector);
97   for (uptr i = 0, n = global_registration_site_vector->size(); i < n; i++) {
98     GlobalRegistrationSite &grs = (*global_registration_site_vector)[i];
99     if (g >= grs.g_first && g <= grs.g_last)
100       return grs.stack_id;
101   }
102   return 0;
103 }
104 
GetGlobalsForAddress(uptr addr,Global * globals,u32 * reg_sites,int max_globals)105 int GetGlobalsForAddress(uptr addr, Global *globals, u32 *reg_sites,
106                          int max_globals) {
107   if (!flags()->report_globals) return 0;
108   BlockingMutexLock lock(&mu_for_globals);
109   int res = 0;
110   for (ListOfGlobals *l = list_of_all_globals; l; l = l->next) {
111     const Global &g = *l->g;
112     if (flags()->report_globals >= 2)
113       ReportGlobal(g, "Search");
114     if (IsAddressNearGlobal(addr, g)) {
115 #if defined(__GNUC__) && defined(__sparc__)
116       internal_memcpy(&globals[res], &g, sizeof(g));
117 #else
118       globals[res] = g;
119 #endif
120       if (reg_sites)
121         reg_sites[res] = FindRegistrationSite(&g);
122       res++;
123       if (res == max_globals) break;
124     }
125   }
126   return res;
127 }
128 
129 enum GlobalSymbolState {
130   UNREGISTERED = 0,
131   REGISTERED = 1
132 };
133 
134 // Check ODR violation for given global G via special ODR indicator. We use
135 // this method in case compiler instruments global variables through their
136 // local aliases.
CheckODRViolationViaIndicator(const Global * g)137 static void CheckODRViolationViaIndicator(const Global *g) {
138   u8 *odr_indicator = reinterpret_cast<u8 *>(g->odr_indicator);
139   if (*odr_indicator == UNREGISTERED) {
140     *odr_indicator = REGISTERED;
141     return;
142   }
143   // If *odr_indicator is DEFINED, some module have already registered
144   // externally visible symbol with the same name. This is an ODR violation.
145   for (ListOfGlobals *l = list_of_all_globals; l; l = l->next) {
146     if (g->odr_indicator == l->g->odr_indicator &&
147         (flags()->detect_odr_violation >= 2 || g->size != l->g->size) &&
148         !IsODRViolationSuppressed(g->name))
149       ReportODRViolation(g, FindRegistrationSite(g),
150                          l->g, FindRegistrationSite(l->g));
151   }
152 }
153 
154 // Clang provides two different ways for global variables protection:
155 // it can poison the global itself or its private alias. In former
156 // case we may poison same symbol multiple times, that can help us to
157 // cheaply detect ODR violation: if we try to poison an already poisoned
158 // global, we have ODR violation error.
159 // In latter case, we poison each symbol exactly once, so we use special
160 // indicator symbol to perform similar check.
161 // In either case, compiler provides a special odr_indicator field to Global
162 // structure, that can contain two kinds of values:
163 //   1) Non-zero value. In this case, odr_indicator is an address of
164 //      corresponding indicator variable for given global.
165 //   2) Zero. This means that we don't use private aliases for global variables
166 //      and can freely check ODR violation with the first method.
167 //
168 // This routine chooses between two different methods of ODR violation
169 // detection.
UseODRIndicator(const Global * g)170 static inline bool UseODRIndicator(const Global *g) {
171   // Use ODR indicator method iff use_odr_indicator flag is set and
172   // indicator symbol address is not 0.
173   return flags()->use_odr_indicator && g->odr_indicator > 0;
174 }
175 
176 // Register a global variable.
177 // This function may be called more than once for every global
178 // so we store the globals in a map.
RegisterGlobal(const Global * g)179 static void RegisterGlobal(const Global *g) {
180   CHECK(asan_inited);
181   if (flags()->report_globals >= 2)
182     ReportGlobal(*g, "Added");
183   CHECK(flags()->report_globals);
184   CHECK(AddrIsInMem(g->beg));
185   if (!AddrIsAlignedByGranularity(g->beg)) {
186     Report("The following global variable is not properly aligned.\n");
187     Report("This may happen if another global with the same name\n");
188     Report("resides in another non-instrumented module.\n");
189     Report("Or the global comes from a C file built w/o -fno-common.\n");
190     Report("In either case this is likely an ODR violation bug,\n");
191     Report("but AddressSanitizer can not provide more details.\n");
192     ReportODRViolation(g, FindRegistrationSite(g), g, FindRegistrationSite(g));
193     CHECK(AddrIsAlignedByGranularity(g->beg));
194   }
195   CHECK(AddrIsAlignedByGranularity(g->size_with_redzone));
196   if (flags()->detect_odr_violation) {
197     // Try detecting ODR (One Definition Rule) violation, i.e. the situation
198     // where two globals with the same name are defined in different modules.
199     if (UseODRIndicator(g))
200       CheckODRViolationViaIndicator(g);
201   }
202   if (CanPoisonMemory())
203     PoisonRedZones(*g);
204   ListOfGlobals *l = new(allocator_for_globals) ListOfGlobals;
205   l->g = g;
206   l->next = list_of_all_globals;
207   list_of_all_globals = l;
208   if (g->has_dynamic_init) {
209     if (!dynamic_init_globals) {
210       dynamic_init_globals =
211           new (allocator_for_globals) VectorOfGlobals;  // NOLINT
212       dynamic_init_globals->reserve(kDynamicInitGlobalsInitialCapacity);
213     }
214     DynInitGlobal dyn_global = { *g, false };
215     dynamic_init_globals->push_back(dyn_global);
216   }
217 }
218 
UnregisterGlobal(const Global * g)219 static void UnregisterGlobal(const Global *g) {
220   CHECK(asan_inited);
221   if (flags()->report_globals >= 2)
222     ReportGlobal(*g, "Removed");
223   CHECK(flags()->report_globals);
224   CHECK(AddrIsInMem(g->beg));
225   CHECK(AddrIsAlignedByGranularity(g->beg));
226   CHECK(AddrIsAlignedByGranularity(g->size_with_redzone));
227   if (CanPoisonMemory())
228     PoisonShadowForGlobal(g, 0);
229   // We unpoison the shadow memory for the global but we do not remove it from
230   // the list because that would require O(n^2) time with the current list
231   // implementation. It might not be worth doing anyway.
232 
233   // Release ODR indicator.
234   if (UseODRIndicator(g)) {
235     u8 *odr_indicator = reinterpret_cast<u8 *>(g->odr_indicator);
236     *odr_indicator = UNREGISTERED;
237   }
238 }
239 
StopInitOrderChecking()240 void StopInitOrderChecking() {
241   BlockingMutexLock lock(&mu_for_globals);
242   if (!flags()->check_initialization_order || !dynamic_init_globals)
243     return;
244   flags()->check_initialization_order = false;
245   for (uptr i = 0, n = dynamic_init_globals->size(); i < n; ++i) {
246     DynInitGlobal &dyn_g = (*dynamic_init_globals)[i];
247     const Global *g = &dyn_g.g;
248     // Unpoison the whole global.
249     PoisonShadowForGlobal(g, 0);
250     // Poison redzones back.
251     PoisonRedZones(*g);
252   }
253 }
254 
IsASCII(unsigned char c)255 static bool IsASCII(unsigned char c) { return /*0x00 <= c &&*/ c <= 0x7F; }
256 
MaybeDemangleGlobalName(const char * name)257 const char *MaybeDemangleGlobalName(const char *name) {
258   // We can spoil names of globals with C linkage, so use an heuristic
259   // approach to check if the name should be demangled.
260   bool should_demangle = false;
261   if (name[0] == '_' && name[1] == 'Z')
262     should_demangle = true;
263   else if (SANITIZER_WINDOWS && name[0] == '\01' && name[1] == '?')
264     should_demangle = true;
265 
266   return should_demangle ? Symbolizer::GetOrInit()->Demangle(name) : name;
267 }
268 
269 // Check if the global is a zero-terminated ASCII string. If so, print it.
PrintGlobalNameIfASCII(InternalScopedString * str,const __asan_global & g)270 void PrintGlobalNameIfASCII(InternalScopedString *str, const __asan_global &g) {
271   for (uptr p = g.beg; p < g.beg + g.size - 1; p++) {
272     unsigned char c = *(unsigned char *)p;
273     if (c == '\0' || !IsASCII(c)) return;
274   }
275   if (*(char *)(g.beg + g.size - 1) != '\0') return;
276   str->append("  '%s' is ascii string '%s'\n", MaybeDemangleGlobalName(g.name),
277               (char *)g.beg);
278 }
279 
GlobalFilename(const __asan_global & g)280 static const char *GlobalFilename(const __asan_global &g) {
281   const char *res = g.module_name;
282   // Prefer the filename from source location, if is available.
283   if (g.location) res = g.location->filename;
284   CHECK(res);
285   return res;
286 }
287 
PrintGlobalLocation(InternalScopedString * str,const __asan_global & g)288 void PrintGlobalLocation(InternalScopedString *str, const __asan_global &g) {
289   str->append("%s", GlobalFilename(g));
290   if (!g.location) return;
291   if (g.location->line_no) str->append(":%d", g.location->line_no);
292   if (g.location->column_no) str->append(":%d", g.location->column_no);
293 }
294 
295 } // namespace __asan
296 
297 // ---------------------- Interface ---------------- {{{1
298 using namespace __asan;  // NOLINT
299 
300 
301 // Apply __asan_register_globals to all globals found in the same loaded
302 // executable or shared library as `flag'. The flag tracks whether globals have
303 // already been registered or not for this image.
__asan_register_image_globals(uptr * flag)304 void __asan_register_image_globals(uptr *flag) {
305   if (*flag)
306     return;
307   AsanApplyToGlobals(__asan_register_globals, flag);
308   *flag = 1;
309 }
310 
311 // This mirrors __asan_register_image_globals.
__asan_unregister_image_globals(uptr * flag)312 void __asan_unregister_image_globals(uptr *flag) {
313   if (!*flag)
314     return;
315   AsanApplyToGlobals(__asan_unregister_globals, flag);
316   *flag = 0;
317 }
318 
__asan_register_elf_globals(uptr * flag,void * start,void * stop)319 void __asan_register_elf_globals(uptr *flag, void *start, void *stop) {
320   if (*flag) return;
321   if (!start) return;
322   CHECK_EQ(0, ((uptr)stop - (uptr)start) % sizeof(__asan_global));
323   __asan_global *globals_start = (__asan_global*)start;
324   __asan_global *globals_stop = (__asan_global*)stop;
325   __asan_register_globals(globals_start, globals_stop - globals_start);
326   *flag = 1;
327 }
328 
__asan_unregister_elf_globals(uptr * flag,void * start,void * stop)329 void __asan_unregister_elf_globals(uptr *flag, void *start, void *stop) {
330   if (!*flag) return;
331   if (!start) return;
332   CHECK_EQ(0, ((uptr)stop - (uptr)start) % sizeof(__asan_global));
333   __asan_global *globals_start = (__asan_global*)start;
334   __asan_global *globals_stop = (__asan_global*)stop;
335   __asan_unregister_globals(globals_start, globals_stop - globals_start);
336   *flag = 0;
337 }
338 
339 // Register an array of globals.
__asan_register_globals(__asan_global * globals,uptr n)340 void __asan_register_globals(__asan_global *globals, uptr n) {
341   if (!flags()->report_globals) return;
342   GET_STACK_TRACE_MALLOC;
343   u32 stack_id = StackDepotPut(stack);
344   BlockingMutexLock lock(&mu_for_globals);
345   if (!global_registration_site_vector) {
346     global_registration_site_vector =
347         new (allocator_for_globals) GlobalRegistrationSiteVector;  // NOLINT
348     global_registration_site_vector->reserve(128);
349   }
350   GlobalRegistrationSite site = {stack_id, &globals[0], &globals[n - 1]};
351   global_registration_site_vector->push_back(site);
352   if (flags()->report_globals >= 2) {
353     PRINT_CURRENT_STACK();
354     Printf("=== ID %d; %p %p\n", stack_id, &globals[0], &globals[n - 1]);
355   }
356   for (uptr i = 0; i < n; i++) {
357     if (SANITIZER_WINDOWS && globals[i].beg == 0) {
358       // The MSVC incremental linker may pad globals out to 256 bytes. As long
359       // as __asan_global is less than 256 bytes large and its size is a power
360       // of two, we can skip over the padding.
361       static_assert(
362           sizeof(__asan_global) < 256 &&
363               (sizeof(__asan_global) & (sizeof(__asan_global) - 1)) == 0,
364           "sizeof(__asan_global) incompatible with incremental linker padding");
365       // If these are padding bytes, the rest of the global should be zero.
366       CHECK(globals[i].size == 0 && globals[i].size_with_redzone == 0 &&
367             globals[i].name == nullptr && globals[i].module_name == nullptr &&
368             globals[i].odr_indicator == 0);
369       continue;
370     }
371     RegisterGlobal(&globals[i]);
372   }
373 
374   // Poison the metadata. It should not be accessible to user code.
375   PoisonShadow(reinterpret_cast<uptr>(globals), n * sizeof(__asan_global),
376                kAsanGlobalRedzoneMagic);
377 }
378 
379 // Unregister an array of globals.
380 // We must do this when a shared objects gets dlclosed.
__asan_unregister_globals(__asan_global * globals,uptr n)381 void __asan_unregister_globals(__asan_global *globals, uptr n) {
382   if (!flags()->report_globals) return;
383   BlockingMutexLock lock(&mu_for_globals);
384   for (uptr i = 0; i < n; i++) {
385     if (SANITIZER_WINDOWS && globals[i].beg == 0) {
386       // Skip globals that look like padding from the MSVC incremental linker.
387       // See comment in __asan_register_globals.
388       continue;
389     }
390     UnregisterGlobal(&globals[i]);
391   }
392 
393   // Unpoison the metadata.
394   PoisonShadow(reinterpret_cast<uptr>(globals), n * sizeof(__asan_global), 0);
395 }
396 
397 // This method runs immediately prior to dynamic initialization in each TU,
398 // when all dynamically initialized globals are unpoisoned.  This method
399 // poisons all global variables not defined in this TU, so that a dynamic
400 // initializer can only touch global variables in the same TU.
__asan_before_dynamic_init(const char * module_name)401 void __asan_before_dynamic_init(const char *module_name) {
402   if (!flags()->check_initialization_order ||
403       !CanPoisonMemory() ||
404       !dynamic_init_globals)
405     return;
406   bool strict_init_order = flags()->strict_init_order;
407   CHECK(module_name);
408   CHECK(asan_inited);
409   BlockingMutexLock lock(&mu_for_globals);
410   if (flags()->report_globals >= 3)
411     Printf("DynInitPoison module: %s\n", module_name);
412   for (uptr i = 0, n = dynamic_init_globals->size(); i < n; ++i) {
413     DynInitGlobal &dyn_g = (*dynamic_init_globals)[i];
414     const Global *g = &dyn_g.g;
415     if (dyn_g.initialized)
416       continue;
417     if (g->module_name != module_name)
418       PoisonShadowForGlobal(g, kAsanInitializationOrderMagic);
419     else if (!strict_init_order)
420       dyn_g.initialized = true;
421   }
422 }
423 
424 // This method runs immediately after dynamic initialization in each TU, when
425 // all dynamically initialized globals except for those defined in the current
426 // TU are poisoned.  It simply unpoisons all dynamically initialized globals.
__asan_after_dynamic_init()427 void __asan_after_dynamic_init() {
428   if (!flags()->check_initialization_order ||
429       !CanPoisonMemory() ||
430       !dynamic_init_globals)
431     return;
432   CHECK(asan_inited);
433   BlockingMutexLock lock(&mu_for_globals);
434   // FIXME: Optionally report that we're unpoisoning globals from a module.
435   for (uptr i = 0, n = dynamic_init_globals->size(); i < n; ++i) {
436     DynInitGlobal &dyn_g = (*dynamic_init_globals)[i];
437     const Global *g = &dyn_g.g;
438     if (!dyn_g.initialized) {
439       // Unpoison the whole global.
440       PoisonShadowForGlobal(g, 0);
441       // Poison redzones back.
442       PoisonRedZones(*g);
443     }
444   }
445 }
446