2015-11-15 Paul Thomas <pault@gcc.gnu.org>
[official-gcc.git] / libsanitizer / asan / asan_globals.cc
blob9c3588b8e081f5101dfb0c67ab231338f985437c
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 //===----------------------------------------------------------------------===//
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"
27 namespace __asan {
29 typedef __asan_global Global;
31 struct ListOfGlobals {
32 const Global *g;
33 ListOfGlobals *next;
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 {
42 Global g;
43 bool initialized;
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 {
51 u32 stack_id;
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,
69 SHADOW_GRANULARITY,
70 kAsanGlobalRedzoneMagic);
74 const uptr kMinimalDistanceFromAnotherGlobal = 64;
76 static 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;
79 return true;
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);
86 if (g.location) {
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 u32 FindRegistrationSite(const Global *g) {
94 mu_for_globals.CheckLocked();
95 CHECK(global_registration_site_vector);
96 for (uptr i = 0, n = global_registration_site_vector->size(); i < n; i++) {
97 GlobalRegistrationSite &grs = (*global_registration_site_vector)[i];
98 if (g >= grs.g_first && g <= grs.g_last)
99 return grs.stack_id;
101 return 0;
104 int GetGlobalsForAddress(uptr addr, Global *globals, u32 *reg_sites,
105 int max_globals) {
106 if (!flags()->report_globals) return 0;
107 BlockingMutexLock lock(&mu_for_globals);
108 int res = 0;
109 for (ListOfGlobals *l = list_of_all_globals; l; l = l->next) {
110 const Global &g = *l->g;
111 if (flags()->report_globals >= 2)
112 ReportGlobal(g, "Search");
113 if (IsAddressNearGlobal(addr, g)) {
114 globals[res] = g;
115 if (reg_sites)
116 reg_sites[res] = FindRegistrationSite(&g);
117 res++;
118 if (res == max_globals) break;
121 return res;
124 bool GetInfoForAddressIfGlobal(uptr addr, AddressDescription *descr) {
125 Global g = {};
126 if (GetGlobalsForAddress(addr, &g, nullptr, 1)) {
127 internal_strncpy(descr->name, g.name, descr->name_size);
128 descr->region_address = g.beg;
129 descr->region_size = g.size;
130 descr->region_kind = "global";
131 return true;
133 return false;
136 // Register a global variable.
137 // This function may be called more than once for every global
138 // so we store the globals in a map.
139 static void RegisterGlobal(const Global *g) {
140 CHECK(asan_inited);
141 if (flags()->report_globals >= 2)
142 ReportGlobal(*g, "Added");
143 CHECK(flags()->report_globals);
144 CHECK(AddrIsInMem(g->beg));
145 CHECK(AddrIsAlignedByGranularity(g->beg));
146 CHECK(AddrIsAlignedByGranularity(g->size_with_redzone));
147 // This "ODR violation" detection is fundamentally incompatible with
148 // how GCC registers globals. Disable as useless until rewritten upstream.
149 if (0 && flags()->detect_odr_violation) {
150 // Try detecting ODR (One Definition Rule) violation, i.e. the situation
151 // where two globals with the same name are defined in different modules.
152 if (__asan_region_is_poisoned(g->beg, g->size_with_redzone)) {
153 // This check may not be enough: if the first global is much larger
154 // the entire redzone of the second global may be within the first global.
155 for (ListOfGlobals *l = list_of_all_globals; l; l = l->next) {
156 if (g->beg == l->g->beg &&
157 (flags()->detect_odr_violation >= 2 || g->size != l->g->size) &&
158 !IsODRViolationSuppressed(g->name))
159 ReportODRViolation(g, FindRegistrationSite(g),
160 l->g, FindRegistrationSite(l->g));
164 if (CanPoisonMemory())
165 PoisonRedZones(*g);
166 ListOfGlobals *l = new(allocator_for_globals) ListOfGlobals;
167 l->g = g;
168 l->next = list_of_all_globals;
169 list_of_all_globals = l;
170 if (g->has_dynamic_init) {
171 if (!dynamic_init_globals) {
172 dynamic_init_globals = new(allocator_for_globals)
173 VectorOfGlobals(kDynamicInitGlobalsInitialCapacity);
175 DynInitGlobal dyn_global = { *g, false };
176 dynamic_init_globals->push_back(dyn_global);
180 static void UnregisterGlobal(const Global *g) {
181 CHECK(asan_inited);
182 if (flags()->report_globals >= 2)
183 ReportGlobal(*g, "Removed");
184 CHECK(flags()->report_globals);
185 CHECK(AddrIsInMem(g->beg));
186 CHECK(AddrIsAlignedByGranularity(g->beg));
187 CHECK(AddrIsAlignedByGranularity(g->size_with_redzone));
188 if (CanPoisonMemory())
189 PoisonShadowForGlobal(g, 0);
190 // We unpoison the shadow memory for the global but we do not remove it from
191 // the list because that would require O(n^2) time with the current list
192 // implementation. It might not be worth doing anyway.
195 void StopInitOrderChecking() {
196 BlockingMutexLock lock(&mu_for_globals);
197 if (!flags()->check_initialization_order || !dynamic_init_globals)
198 return;
199 flags()->check_initialization_order = false;
200 for (uptr i = 0, n = dynamic_init_globals->size(); i < n; ++i) {
201 DynInitGlobal &dyn_g = (*dynamic_init_globals)[i];
202 const Global *g = &dyn_g.g;
203 // Unpoison the whole global.
204 PoisonShadowForGlobal(g, 0);
205 // Poison redzones back.
206 PoisonRedZones(*g);
210 } // namespace __asan
212 // ---------------------- Interface ---------------- {{{1
213 using namespace __asan; // NOLINT
215 // Register an array of globals.
216 void __asan_register_globals(__asan_global *globals, uptr n) {
217 if (!flags()->report_globals) return;
218 GET_STACK_TRACE_MALLOC;
219 u32 stack_id = StackDepotPut(stack);
220 BlockingMutexLock lock(&mu_for_globals);
221 if (!global_registration_site_vector)
222 global_registration_site_vector =
223 new(allocator_for_globals) GlobalRegistrationSiteVector(128);
224 GlobalRegistrationSite site = {stack_id, &globals[0], &globals[n - 1]};
225 global_registration_site_vector->push_back(site);
226 if (flags()->report_globals >= 2) {
227 PRINT_CURRENT_STACK();
228 Printf("=== ID %d; %p %p\n", stack_id, &globals[0], &globals[n - 1]);
230 for (uptr i = 0; i < n; i++) {
231 RegisterGlobal(&globals[i]);
235 // Unregister an array of globals.
236 // We must do this when a shared objects gets dlclosed.
237 void __asan_unregister_globals(__asan_global *globals, uptr n) {
238 if (!flags()->report_globals) return;
239 BlockingMutexLock lock(&mu_for_globals);
240 for (uptr i = 0; i < n; i++) {
241 UnregisterGlobal(&globals[i]);
245 // This method runs immediately prior to dynamic initialization in each TU,
246 // when all dynamically initialized globals are unpoisoned. This method
247 // poisons all global variables not defined in this TU, so that a dynamic
248 // initializer can only touch global variables in the same TU.
249 void __asan_before_dynamic_init(const char *module_name) {
250 if (!flags()->check_initialization_order ||
251 !CanPoisonMemory())
252 return;
253 bool strict_init_order = flags()->strict_init_order;
254 CHECK(dynamic_init_globals);
255 CHECK(module_name);
256 CHECK(asan_inited);
257 BlockingMutexLock lock(&mu_for_globals);
258 if (flags()->report_globals >= 3)
259 Printf("DynInitPoison module: %s\n", module_name);
260 for (uptr i = 0, n = dynamic_init_globals->size(); i < n; ++i) {
261 DynInitGlobal &dyn_g = (*dynamic_init_globals)[i];
262 const Global *g = &dyn_g.g;
263 if (dyn_g.initialized)
264 continue;
265 if (g->module_name != module_name)
266 PoisonShadowForGlobal(g, kAsanInitializationOrderMagic);
267 else if (!strict_init_order)
268 dyn_g.initialized = true;
272 // This method runs immediately after dynamic initialization in each TU, when
273 // all dynamically initialized globals except for those defined in the current
274 // TU are poisoned. It simply unpoisons all dynamically initialized globals.
275 void __asan_after_dynamic_init() {
276 if (!flags()->check_initialization_order ||
277 !CanPoisonMemory())
278 return;
279 CHECK(asan_inited);
280 BlockingMutexLock lock(&mu_for_globals);
281 // FIXME: Optionally report that we're unpoisoning globals from a module.
282 for (uptr i = 0, n = dynamic_init_globals->size(); i < n; ++i) {
283 DynInitGlobal &dyn_g = (*dynamic_init_globals)[i];
284 const Global *g = &dyn_g.g;
285 if (!dyn_g.initialized) {
286 // Unpoison the whole global.
287 PoisonShadowForGlobal(g, 0);
288 // Poison redzones back.
289 PoisonRedZones(*g);