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