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