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