Debian Codegraph @

libsanitizer/asan/asan_globals.cpp

raw
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_dense_map.h"
25 #include "sanitizer_common/sanitizer_list.h"
26 #include "sanitizer_common/sanitizer_mutex.h"
27 #include "sanitizer_common/sanitizer_placement_new.h"
28 #include "sanitizer_common/sanitizer_stackdepot.h"
29 #include "sanitizer_common/sanitizer_symbolizer.h"
30 #include "sanitizer_common/sanitizer_thread_safety.h"
31
32 namespace __asan {
33
34 typedef __asan_global Global;
35
36 struct GlobalListNode {
37 const Global *g = nullptr;
38 GlobalListNode *next = nullptr;
39 };
40 typedef IntrusiveList<GlobalListNode> ListOfGlobals;
41
42 static Mutex mu_for_globals;
43 static ListOfGlobals list_of_all_globals SANITIZER_GUARDED_BY(mu_for_globals);
44
45 struct DynInitGlobal {
46 Global g = {};
47 bool initialized = false;
48 DynInitGlobal *next = nullptr;
49 };
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 static ListOfGlobals &GlobalsByIndicator(uptr odr_indicator)
60 SANITIZER_REQUIRES(mu_for_globals) {
61 using MapOfGlobals = DenseMap<uptr, ListOfGlobals>;
62
63 static MapOfGlobals *globals_by_indicator = nullptr;
64 if (!globals_by_indicator) {
65 alignas(
66 alignof(MapOfGlobals)) static char placeholder[sizeof(MapOfGlobals)];
67 globals_by_indicator = new (placeholder) MapOfGlobals();
68 }
69
70 return (*globals_by_indicator)[odr_indicator];
71 }
72
73 static const char *current_dynamic_init_module_name
74 SANITIZER_GUARDED_BY(mu_for_globals) = nullptr;
75
76 using DynInitGlobalsByModule =
77 DenseMap<const char *, IntrusiveList<DynInitGlobal>>;
78
79 // TODO: Add a NoDestroy helper, this patter is very common in sanitizers.
80 static DynInitGlobalsByModule &DynInitGlobals()
81 SANITIZER_REQUIRES(mu_for_globals) {
82 static DynInitGlobalsByModule *globals_by_module = nullptr;
83 if (!globals_by_module) {
84 alignas(alignof(DynInitGlobalsByModule)) static char
85 placeholder[sizeof(DynInitGlobalsByModule)];
86 globals_by_module = new (placeholder) DynInitGlobalsByModule();
87 }
88
89 return *globals_by_module;
90 }
91
92 ALWAYS_INLINE void PoisonShadowForGlobal(const Global *g, u8 value) {
93 FastPoisonShadow(g->beg, g->size_with_redzone, value);
94 }
95
96 ALWAYS_INLINE void PoisonRedZones(const Global &g) {
97 uptr aligned_size = RoundUpTo(g.size, ASAN_SHADOW_GRANULARITY);
98 FastPoisonShadow(g.beg + aligned_size, g.size_with_redzone - aligned_size,
99 kAsanGlobalRedzoneMagic);
100 if (g.size != aligned_size) {
101 FastPoisonShadowPartialRightRedzone(
102 g.beg + RoundDownTo(g.size, ASAN_SHADOW_GRANULARITY),
103 g.size % ASAN_SHADOW_GRANULARITY, ASAN_SHADOW_GRANULARITY,
104 kAsanGlobalRedzoneMagic);
105 }
106 }
107
108 const uptr kMinimalDistanceFromAnotherGlobal = 64;
109
110 static void AddGlobalToList(ListOfGlobals &list, const Global *g) {
111 list.push_front(new (GetGlobalLowLevelAllocator()) GlobalListNode{g});
112 }
113
114 static void UnpoisonDynamicGlobals(IntrusiveList<DynInitGlobal> &dyn_globals,
115 bool mark_initialized) {
116 for (auto &dyn_g : dyn_globals) {
117 const Global *g = &dyn_g.g;
118 if (dyn_g.initialized)
119 continue;
120 // Unpoison the whole global.
121 PoisonShadowForGlobal(g, 0);
122 // Poison redzones back.
123 PoisonRedZones(*g);
124 if (mark_initialized)
125 dyn_g.initialized = true;
126 }
127 }
128
129 static void PoisonDynamicGlobals(
130 const IntrusiveList<DynInitGlobal> &dyn_globals) {
131 for (auto &dyn_g : dyn_globals) {
132 const Global *g = &dyn_g.g;
133 if (dyn_g.initialized)
134 continue;
135 PoisonShadowForGlobal(g, kAsanInitializationOrderMagic);
136 }
137 }
138
139 static bool IsAddressNearGlobal(uptr addr, const __asan_global &g) {
140 if (addr <= g.beg - kMinimalDistanceFromAnotherGlobal) return false;
141 if (addr >= g.beg + g.size_with_redzone) return false;
142 return true;
143 }
144
145 static void ReportGlobal(const Global &g, const char *prefix) {
146 DataInfo info;
147 bool symbolized = Symbolizer::GetOrInit()->SymbolizeData(g.beg, &info);
148 Report(
149 "%s Global[%p]: beg=%p size=%zu/%zu name=%s source=%s module=%s "
150 "dyn_init=%zu "
151 "odr_indicator=%p\n",
152 prefix, (void *)&g, (void *)g.beg, g.size, g.size_with_redzone, g.name,
153 g.module_name, (symbolized ? info.module : "?"), g.has_dynamic_init,
154 (void *)g.odr_indicator);
155
156 if (symbolized && info.line != 0) {
157 Report(" location: name=%s, %d\n", info.file, static_cast<int>(info.line));
158 } else if (g.gcc_location != 0) {
159 // Fallback to Global::gcc_location
160 Report(" location: name=%s, %d\n", g.gcc_location->filename, g.gcc_location->line_no);
161 }
162 }
163
164 static u32 FindRegistrationSite(const Global *g) {
165 mu_for_globals.CheckLocked();
166 CHECK(global_registration_site_vector);
167 for (uptr i = 0, n = global_registration_site_vector->size(); i < n; i++) {
168 GlobalRegistrationSite &grs = (*global_registration_site_vector)[i];
169 if (g >= grs.g_first && g <= grs.g_last)
170 return grs.stack_id;
171 }
172 return 0;
173 }
174
175 int GetGlobalsForAddress(uptr addr, Global *globals, u32 *reg_sites,
176 int max_globals) {
177 if (!flags()->report_globals) return 0;
178 Lock lock(&mu_for_globals);
179 int res = 0;
180 for (const auto &l : list_of_all_globals) {
181 const Global &g = *l.g;
182 if (flags()->report_globals >= 2)
183 ReportGlobal(g, "Search");
184 if (IsAddressNearGlobal(addr, g)) {
185 internal_memcpy(&globals[res], &g, sizeof(g));
186 if (reg_sites)
187 reg_sites[res] = FindRegistrationSite(&g);
188 res++;
189 if (res == max_globals)
190 break;
191 }
192 }
193 return res;
194 }
195
196 enum GlobalSymbolState {
197 UNREGISTERED = 0,
198 REGISTERED = 1
199 };
200
201 // Check ODR violation for given global G via special ODR indicator. We use
202 // this method in case compiler instruments global variables through their
203 // local aliases.
204 static void CheckODRViolationViaIndicator(const Global *g)
205 SANITIZER_REQUIRES(mu_for_globals) {
206 // Instrumentation requests to skip ODR check.
207 if (g->odr_indicator == UINTPTR_MAX)
208 return;
209
210 ListOfGlobals &relevant_globals = GlobalsByIndicator(g->odr_indicator);
211
212 u8 *odr_indicator = reinterpret_cast<u8 *>(g->odr_indicator);
213 if (*odr_indicator == REGISTERED) {
214 // If *odr_indicator is REGISTERED, some module have already registered
215 // externally visible symbol with the same name. This is an ODR violation.
216 for (const auto &l : relevant_globals) {
217 if ((flags()->detect_odr_violation >= 2 || g->size != l.g->size) &&
218 !IsODRViolationSuppressed(g->name))
219 ReportODRViolation(g, FindRegistrationSite(g), l.g,
220 FindRegistrationSite(l.g));
221 }
222 } else { // UNREGISTERED
223 *odr_indicator = REGISTERED;
224 }
225
226 AddGlobalToList(relevant_globals, g);
227 }
228
229 // Clang provides two different ways for global variables protection:
230 // it can poison the global itself or its private alias. In former
231 // case we may poison same symbol multiple times, that can help us to
232 // cheaply detect ODR violation: if we try to poison an already poisoned
233 // global, we have ODR violation error.
234 // In latter case, we poison each symbol exactly once, so we use special
235 // indicator symbol to perform similar check.
236 // In either case, compiler provides a special odr_indicator field to Global
237 // structure, that can contain two kinds of values:
238 // 1) Non-zero value. In this case, odr_indicator is an address of
239 // corresponding indicator variable for given global.
240 // 2) Zero. This means that we don't use private aliases for global variables
241 // and can freely check ODR violation with the first method.
242 //
243 // This routine chooses between two different methods of ODR violation
244 // detection.
245 static inline bool UseODRIndicator(const Global *g) {
246 return g->odr_indicator > 0;
247 }
248
249 // Register a global variable.
250 // This function may be called more than once for every global
251 // so we store the globals in a map.
252 static void RegisterGlobal(const Global *g) SANITIZER_REQUIRES(mu_for_globals) {
253 CHECK(AsanInited());
254 if (flags()->report_globals >= 2)
255 ReportGlobal(*g, "Added");
256 CHECK(flags()->report_globals);
257 CHECK(AddrIsInMem(g->beg));
258 if (!AddrIsAlignedByGranularity(g->beg)) {
259 Report("The following global variable is not properly aligned.\n");
260 Report("This may happen if another global with the same name\n");
261 Report("resides in another non-instrumented module.\n");
262 Report("Or the global comes from a C file built w/o -fno-common.\n");
263 Report("In either case this is likely an ODR violation bug,\n");
264 Report("but AddressSanitizer can not provide more details.\n");
265 ReportODRViolation(g, FindRegistrationSite(g), g, FindRegistrationSite(g));
266 CHECK(AddrIsAlignedByGranularity(g->beg));
267 }
268 CHECK(AddrIsAlignedByGranularity(g->size_with_redzone));
269 if (flags()->detect_odr_violation) {
270 // Try detecting ODR (One Definition Rule) violation, i.e. the situation
271 // where two globals with the same name are defined in different modules.
272 if (UseODRIndicator(g))
273 CheckODRViolationViaIndicator(g);
274 }
275 if (CanPoisonMemory())
276 PoisonRedZones(*g);
277
278 AddGlobalToList(list_of_all_globals, g);
279
280 if (g->has_dynamic_init) {
281 DynInitGlobals()[g->module_name].push_back(
282 new (GetGlobalLowLevelAllocator()) DynInitGlobal{*g, false});
283 }
284 }
285
286 static void UnregisterGlobal(const Global *g)
287 SANITIZER_REQUIRES(mu_for_globals) {
288 CHECK(AsanInited());
289 if (flags()->report_globals >= 2)
290 ReportGlobal(*g, "Removed");
291 CHECK(flags()->report_globals);
292 CHECK(AddrIsInMem(g->beg));
293 CHECK(AddrIsAlignedByGranularity(g->beg));
294 CHECK(AddrIsAlignedByGranularity(g->size_with_redzone));
295 if (CanPoisonMemory())
296 PoisonShadowForGlobal(g, 0);
297 // We unpoison the shadow memory for the global but we do not remove it from
298 // the list because that would require O(n^2) time with the current list
299 // implementation. It might not be worth doing anyway.
300
301 // Release ODR indicator.
302 if (UseODRIndicator(g) && g->odr_indicator != UINTPTR_MAX) {
303 u8 *odr_indicator = reinterpret_cast<u8 *>(g->odr_indicator);
304 *odr_indicator = UNREGISTERED;
305 }
306 }
307
308 void StopInitOrderChecking() {
309 if (!flags()->check_initialization_order)
310 return;
311 Lock lock(&mu_for_globals);
312 flags()->check_initialization_order = false;
313 DynInitGlobals().forEach([&](auto &kv) {
314 UnpoisonDynamicGlobals(kv.second, /*mark_initialized=*/false);
315 return true;
316 });
317 }
318
319 static bool IsASCII(unsigned char c) { return /*0x00 <= c &&*/ c <= 0x7F; }
320
321 const char *MaybeDemangleGlobalName(const char *name) {
322 // We can spoil names of globals with C linkage, so use an heuristic
323 // approach to check if the name should be demangled.
324 bool should_demangle = false;
325 if (name[0] == '_' && name[1] == 'Z')
326 should_demangle = true;
327 else if (SANITIZER_WINDOWS && name[0] == '\01' && name[1] == '?')
328 should_demangle = true;
329
330 return should_demangle ? Symbolizer::GetOrInit()->Demangle(name) : name;
331 }
332
333 // Check if the global is a zero-terminated ASCII string. If so, print it.
334 void PrintGlobalNameIfASCII(InternalScopedString *str, const __asan_global &g) {
335 for (uptr p = g.beg; p < g.beg + g.size - 1; p++) {
336 unsigned char c = *(unsigned char *)p;
337 if (c == '\0' || !IsASCII(c)) return;
338 }
339 if (*(char *)(g.beg + g.size - 1) != '\0') return;
340 str->AppendF(" '%s' is ascii string '%s'\n", MaybeDemangleGlobalName(g.name),
341 (char *)g.beg);
342 }
343
344 void PrintGlobalLocation(InternalScopedString *str, const __asan_global &g,
345 bool print_module_name) {
346 DataInfo info;
347 if (Symbolizer::GetOrInit()->SymbolizeData(g.beg, &info) && info.line != 0) {
348 str->AppendF("%s:%d", info.file, static_cast<int>(info.line));
349 } else if (g.gcc_location != 0) {
350 // Fallback to Global::gcc_location
351 str->AppendF("%s", g.gcc_location->filename ? g.gcc_location->filename
352 : g.module_name);
353 if (g.gcc_location->line_no)
354 str->AppendF(":%d", g.gcc_location->line_no);
355 if (g.gcc_location->column_no)
356 str->AppendF(":%d", g.gcc_location->column_no);
357 } else {
358 str->AppendF("%s", g.module_name);
359 }
360 if (print_module_name && info.module)
361 str->AppendF(" in %s", info.module);
362 }
363
364 } // namespace __asan
365
366 // ---------------------- Interface ---------------- {{{1
367 using namespace __asan;
368
369 // Apply __asan_register_globals to all globals found in the same loaded
370 // executable or shared library as `flag'. The flag tracks whether globals have
371 // already been registered or not for this image.
372 void __asan_register_image_globals(uptr *flag) {
373 if (*flag)
374 return;
375 AsanApplyToGlobals(__asan_register_globals, flag);
376 *flag = 1;
377 }
378
379 // This mirrors __asan_register_image_globals.
380 void __asan_unregister_image_globals(uptr *flag) {
381 if (!*flag)
382 return;
383 AsanApplyToGlobals(__asan_unregister_globals, flag);
384 *flag = 0;
385 }
386
387 void __asan_register_elf_globals(uptr *flag, void *start, void *stop) {
388 if (*flag || start == stop)
389 return;
390 CHECK_EQ(0, ((uptr)stop - (uptr)start) % sizeof(__asan_global));
391 __asan_global *globals_start = (__asan_global*)start;
392 __asan_global *globals_stop = (__asan_global*)stop;
393 __asan_register_globals(globals_start, globals_stop - globals_start);
394 *flag = 1;
395 }
396
397 void __asan_unregister_elf_globals(uptr *flag, void *start, void *stop) {
398 if (!*flag || start == stop)
399 return;
400 CHECK_EQ(0, ((uptr)stop - (uptr)start) % sizeof(__asan_global));
401 __asan_global *globals_start = (__asan_global*)start;
402 __asan_global *globals_stop = (__asan_global*)stop;
403 __asan_unregister_globals(globals_start, globals_stop - globals_start);
404 *flag = 0;
405 }
406
407 // Register an array of globals.
408 void __asan_register_globals(__asan_global *globals, uptr n) {
409 if (!flags()->report_globals) return;
410 GET_STACK_TRACE_MALLOC;
411 u32 stack_id = StackDepotPut(stack);
412 Lock lock(&mu_for_globals);
413 if (!global_registration_site_vector) {
414 global_registration_site_vector =
415 new (GetGlobalLowLevelAllocator()) GlobalRegistrationSiteVector;
416 global_registration_site_vector->reserve(128);
417 }
418 GlobalRegistrationSite site = {stack_id, &globals[0], &globals[n - 1]};
419 global_registration_site_vector->push_back(site);
420 if (flags()->report_globals >= 2) {
421 PRINT_CURRENT_STACK();
422 Printf("=== ID %d; %p %p\n", stack_id, (void *)&globals[0],
423 (void *)&globals[n - 1]);
424 }
425 for (uptr i = 0; i < n; i++) {
426 if (SANITIZER_WINDOWS && globals[i].beg == 0) {
427 // The MSVC incremental linker may pad globals out to 256 bytes. As long
428 // as __asan_global is less than 256 bytes large and its size is a power
429 // of two, we can skip over the padding.
430 static_assert(
431 sizeof(__asan_global) < 256 &&
432 (sizeof(__asan_global) & (sizeof(__asan_global) - 1)) == 0,
433 "sizeof(__asan_global) incompatible with incremental linker padding");
434 // If these are padding bytes, the rest of the global should be zero.
435 CHECK(globals[i].size == 0 && globals[i].size_with_redzone == 0 &&
436 globals[i].name == nullptr && globals[i].module_name == nullptr &&
437 globals[i].odr_indicator == 0);
438 continue;
439 }
440 RegisterGlobal(&globals[i]);
441 }
442
443 // Poison the metadata. It should not be accessible to user code.
444 PoisonShadow(reinterpret_cast<uptr>(globals), n * sizeof(__asan_global),
445 kAsanGlobalRedzoneMagic);
446 }
447
448 // Unregister an array of globals.
449 // We must do this when a shared objects gets dlclosed.
450 void __asan_unregister_globals(__asan_global *globals, uptr n) {
451 if (!flags()->report_globals) return;
452 Lock lock(&mu_for_globals);
453 for (uptr i = 0; i < n; i++) {
454 if (SANITIZER_WINDOWS && globals[i].beg == 0) {
455 // Skip globals that look like padding from the MSVC incremental linker.
456 // See comment in __asan_register_globals.
457 continue;
458 }
459 UnregisterGlobal(&globals[i]);
460 }
461
462 // Unpoison the metadata.
463 PoisonShadow(reinterpret_cast<uptr>(globals), n * sizeof(__asan_global), 0);
464 }
465
466 // This method runs immediately prior to dynamic initialization in each TU,
467 // when all dynamically initialized globals are unpoisoned. This method
468 // poisons all global variables not defined in this TU, so that a dynamic
469 // initializer can only touch global variables in the same TU.
470 void __asan_before_dynamic_init(const char *module_name) {
471 if (!flags()->check_initialization_order || !CanPoisonMemory())
472 return;
473 bool strict_init_order = flags()->strict_init_order;
474 CHECK(module_name);
475 CHECK(AsanInited());
476 Lock lock(&mu_for_globals);
477 if (current_dynamic_init_module_name == module_name)
478 return;
479 if (flags()->report_globals >= 3)
480 Printf("DynInitPoison module: %s\n", module_name);
481
482 if (current_dynamic_init_module_name == nullptr) {
483 // First call, poison all globals from other modules.
484 DynInitGlobals().forEach([&](auto &kv) {
485 if (kv.first != module_name) {
486 PoisonDynamicGlobals(kv.second);
487 } else {
488 UnpoisonDynamicGlobals(kv.second,
489 /*mark_initialized=*/!strict_init_order);
490 }
491 return true;
492 });
493 } else {
494 // Module changed.
495 PoisonDynamicGlobals(DynInitGlobals()[current_dynamic_init_module_name]);
496 UnpoisonDynamicGlobals(DynInitGlobals()[module_name],
497 /*mark_initialized=*/!strict_init_order);
498 }
499 current_dynamic_init_module_name = module_name;
500 }
501
502 // Maybe SANITIZER_CAN_USE_PREINIT_ARRAY is to conservative for `.init_array`,
503 // however we should not make mistake here. If `UnpoisonBeforeMain` was not
504 // executed at all we will have false reports on globals.
505 #if SANITIZER_CAN_USE_PREINIT_ARRAY
506 // This optimization aims to reduce the overhead of `__asan_after_dynamic_init`
507 // calls by leveraging incremental unpoisoning/poisoning in
508 // `__asan_before_dynamic_init`. We expect most `__asan_after_dynamic_init
509 // calls` to be no-ops. However, to ensure all globals are unpoisoned before the
510 // `main`, we force `UnpoisonBeforeMain` to fully execute
511 // `__asan_after_dynamic_init`.
512
513 // With lld, `UnpoisonBeforeMain` runs after standard `.init_array`, making it
514 // the final `__asan_after_dynamic_init` call for the static runtime. In
515 // contrast, GNU ld executes it earlier, causing subsequent
516 // `__asan_after_dynamic_init` calls to perform full unpoisoning, losing the
517 // optimization.
518 bool allow_after_dynamic_init SANITIZER_GUARDED_BY(mu_for_globals) = false;
519
520 static void UnpoisonBeforeMain(void) {
521 {
522 Lock lock(&mu_for_globals);
523 if (allow_after_dynamic_init)
524 return;
525 allow_after_dynamic_init = true;
526 }
527 if (flags()->report_globals >= 3)
528 Printf("UnpoisonBeforeMain\n");
529 __asan_after_dynamic_init();
530 }
531
532 __attribute__((section(".init_array.65537"), used)) static void (
533 *asan_after_init_array)(void) = UnpoisonBeforeMain;
534 #else
535 // Incremental poisoning is disabled, unpoison globals immediately.
536 static constexpr bool allow_after_dynamic_init = true;
537 #endif // SANITIZER_CAN_USE_PREINIT_ARRAY
538
539 // This method runs immediately after dynamic initialization in each TU, when
540 // all dynamically initialized globals except for those defined in the current
541 // TU are poisoned. It simply unpoisons all dynamically initialized globals.
542 void __asan_after_dynamic_init() {
543 if (!flags()->check_initialization_order || !CanPoisonMemory())
544 return;
545 CHECK(AsanInited());
546 Lock lock(&mu_for_globals);
547 if (!allow_after_dynamic_init)
548 return;
549 if (!current_dynamic_init_module_name)
550 return;
551
552 if (flags()->report_globals >= 3)
553 Printf("DynInitUnpoison\n");
554
555 DynInitGlobals().forEach([&](auto &kv) {
556 UnpoisonDynamicGlobals(kv.second, /*mark_initialized=*/false);
557 return true;
558 });
559
560 current_dynamic_init_module_name = nullptr;
561 }