llvm-project
473 строки · 17.4 Кб
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
29namespace __asan {30
31typedef __asan_global Global;32
33struct ListOfGlobals {34const Global *g;35ListOfGlobals *next;36};37
38static Mutex mu_for_globals;39static ListOfGlobals *list_of_all_globals;40
41static const int kDynamicInitGlobalsInitialCapacity = 512;42struct DynInitGlobal {43Global g;44bool initialized;45};46typedef InternalMmapVector<DynInitGlobal> VectorOfGlobals;47// Lazy-initialized and never deleted.
48static VectorOfGlobals *dynamic_init_globals;49
50// We want to remember where a certain range of globals was registered.
51struct GlobalRegistrationSite {52u32 stack_id;53Global *g_first, *g_last;54};55typedef InternalMmapVector<GlobalRegistrationSite> GlobalRegistrationSiteVector;56static GlobalRegistrationSiteVector *global_registration_site_vector;57
58ALWAYS_INLINE void PoisonShadowForGlobal(const Global *g, u8 value) {59FastPoisonShadow(g->beg, g->size_with_redzone, value);60}
61
62ALWAYS_INLINE void PoisonRedZones(const Global &g) {63uptr aligned_size = RoundUpTo(g.size, ASAN_SHADOW_GRANULARITY);64FastPoisonShadow(g.beg + aligned_size, g.size_with_redzone - aligned_size,65kAsanGlobalRedzoneMagic);66if (g.size != aligned_size) {67FastPoisonShadowPartialRightRedzone(68g.beg + RoundDownTo(g.size, ASAN_SHADOW_GRANULARITY),69g.size % ASAN_SHADOW_GRANULARITY, ASAN_SHADOW_GRANULARITY,70kAsanGlobalRedzoneMagic);71}72}
73
74const uptr kMinimalDistanceFromAnotherGlobal = 64;75
76static bool IsAddressNearGlobal(uptr addr, const __asan_global &g) {77if (addr <= g.beg - kMinimalDistanceFromAnotherGlobal) return false;78if (addr >= g.beg + g.size_with_redzone) return false;79return true;80}
81
82static void ReportGlobal(const Global &g, const char *prefix) {83DataInfo info;84bool symbolized = Symbolizer::GetOrInit()->SymbolizeData(g.beg, &info);85Report(86"%s Global[%p]: beg=%p size=%zu/%zu name=%s source=%s module=%s "87"dyn_init=%zu "88"odr_indicator=%p\n",89prefix, (void *)&g, (void *)g.beg, g.size, g.size_with_redzone, g.name,90g.module_name, (symbolized ? info.module : "?"), g.has_dynamic_init,91(void *)g.odr_indicator);92
93if (symbolized && info.line != 0) {94Report(" location: name=%s, %d\n", info.file, static_cast<int>(info.line));95} else if (g.gcc_location != 0) {96// Fallback to Global::gcc_location97Report(" location: name=%s, %d\n", g.gcc_location->filename, g.gcc_location->line_no);98}99}
100
101static u32 FindRegistrationSite(const Global *g) {102mu_for_globals.CheckLocked();103CHECK(global_registration_site_vector);104for (uptr i = 0, n = global_registration_site_vector->size(); i < n; i++) {105GlobalRegistrationSite &grs = (*global_registration_site_vector)[i];106if (g >= grs.g_first && g <= grs.g_last)107return grs.stack_id;108}109return 0;110}
111
112int GetGlobalsForAddress(uptr addr, Global *globals, u32 *reg_sites,113int max_globals) {114if (!flags()->report_globals) return 0;115Lock lock(&mu_for_globals);116int res = 0;117for (ListOfGlobals *l = list_of_all_globals; l; l = l->next) {118const Global &g = *l->g;119if (flags()->report_globals >= 2)120ReportGlobal(g, "Search");121if (IsAddressNearGlobal(addr, g)) {122internal_memcpy(&globals[res], &g, sizeof(g));123if (reg_sites)124reg_sites[res] = FindRegistrationSite(&g);125res++;126if (res == max_globals)127break;128}129}130return res;131}
132
133enum GlobalSymbolState {134UNREGISTERED = 0,135REGISTERED = 1136};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.
141static void CheckODRViolationViaIndicator(const Global *g) {142// Instrumentation requests to skip ODR check.143if (g->odr_indicator == UINTPTR_MAX)144return;145u8 *odr_indicator = reinterpret_cast<u8 *>(g->odr_indicator);146if (*odr_indicator == UNREGISTERED) {147*odr_indicator = REGISTERED;148return;149}150// If *odr_indicator is DEFINED, some module have already registered151// externally visible symbol with the same name. This is an ODR violation.152for (ListOfGlobals *l = list_of_all_globals; l; l = l->next) {153if (g->odr_indicator == l->g->odr_indicator &&154(flags()->detect_odr_violation >= 2 || g->size != l->g->size) &&155!IsODRViolationSuppressed(g->name))156ReportODRViolation(g, FindRegistrationSite(g),157l->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.
164static void CheckODRViolationViaPoisoning(const Global *g) {165if (__asan_region_is_poisoned(g->beg, g->size_with_redzone)) {166// This check may not be enough: if the first global is much larger167// the entire redzone of the second global may be within the first global.168for (ListOfGlobals *l = list_of_all_globals; l; l = l->next) {169if (g->beg == l->g->beg &&170(flags()->detect_odr_violation >= 2 || g->size != l->g->size) &&171!IsODRViolationSuppressed(g->name))172ReportODRViolation(g, FindRegistrationSite(g),173l->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.
194static inline bool UseODRIndicator(const Global *g) {195return 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.
201static void RegisterGlobal(const Global *g) {202CHECK(AsanInited());203if (flags()->report_globals >= 2)204ReportGlobal(*g, "Added");205CHECK(flags()->report_globals);206CHECK(AddrIsInMem(g->beg));207if (!AddrIsAlignedByGranularity(g->beg)) {208Report("The following global variable is not properly aligned.\n");209Report("This may happen if another global with the same name\n");210Report("resides in another non-instrumented module.\n");211Report("Or the global comes from a C file built w/o -fno-common.\n");212Report("In either case this is likely an ODR violation bug,\n");213Report("but AddressSanitizer can not provide more details.\n");214ReportODRViolation(g, FindRegistrationSite(g), g, FindRegistrationSite(g));215CHECK(AddrIsAlignedByGranularity(g->beg));216}217CHECK(AddrIsAlignedByGranularity(g->size_with_redzone));218if (flags()->detect_odr_violation) {219// Try detecting ODR (One Definition Rule) violation, i.e. the situation220// where two globals with the same name are defined in different modules.221if (UseODRIndicator(g))222CheckODRViolationViaIndicator(g);223else224CheckODRViolationViaPoisoning(g);225}226if (CanPoisonMemory())227PoisonRedZones(*g);228ListOfGlobals *l = new (GetGlobalLowLevelAllocator()) ListOfGlobals;229l->g = g;230l->next = list_of_all_globals;231list_of_all_globals = l;232if (g->has_dynamic_init) {233if (!dynamic_init_globals) {234dynamic_init_globals = new (GetGlobalLowLevelAllocator()) VectorOfGlobals;235dynamic_init_globals->reserve(kDynamicInitGlobalsInitialCapacity);236}237DynInitGlobal dyn_global = { *g, false };238dynamic_init_globals->push_back(dyn_global);239}240}
241
242static void UnregisterGlobal(const Global *g) {243CHECK(AsanInited());244if (flags()->report_globals >= 2)245ReportGlobal(*g, "Removed");246CHECK(flags()->report_globals);247CHECK(AddrIsInMem(g->beg));248CHECK(AddrIsAlignedByGranularity(g->beg));249CHECK(AddrIsAlignedByGranularity(g->size_with_redzone));250if (CanPoisonMemory())251PoisonShadowForGlobal(g, 0);252// We unpoison the shadow memory for the global but we do not remove it from253// the list because that would require O(n^2) time with the current list254// implementation. It might not be worth doing anyway.255
256// Release ODR indicator.257if (UseODRIndicator(g) && g->odr_indicator != UINTPTR_MAX) {258u8 *odr_indicator = reinterpret_cast<u8 *>(g->odr_indicator);259*odr_indicator = UNREGISTERED;260}261}
262
263void StopInitOrderChecking() {264Lock lock(&mu_for_globals);265if (!flags()->check_initialization_order || !dynamic_init_globals)266return;267flags()->check_initialization_order = false;268for (uptr i = 0, n = dynamic_init_globals->size(); i < n; ++i) {269DynInitGlobal &dyn_g = (*dynamic_init_globals)[i];270const Global *g = &dyn_g.g;271// Unpoison the whole global.272PoisonShadowForGlobal(g, 0);273// Poison redzones back.274PoisonRedZones(*g);275}276}
277
278static bool IsASCII(unsigned char c) { return /*0x00 <= c &&*/ c <= 0x7F; }279
280const char *MaybeDemangleGlobalName(const char *name) {281// We can spoil names of globals with C linkage, so use an heuristic282// approach to check if the name should be demangled.283bool should_demangle = false;284if (name[0] == '_' && name[1] == 'Z')285should_demangle = true;286else if (SANITIZER_WINDOWS && name[0] == '\01' && name[1] == '?')287should_demangle = true;288
289return should_demangle ? Symbolizer::GetOrInit()->Demangle(name) : name;290}
291
292// Check if the global is a zero-terminated ASCII string. If so, print it.
293void PrintGlobalNameIfASCII(InternalScopedString *str, const __asan_global &g) {294for (uptr p = g.beg; p < g.beg + g.size - 1; p++) {295unsigned char c = *(unsigned char *)p;296if (c == '\0' || !IsASCII(c)) return;297}298if (*(char *)(g.beg + g.size - 1) != '\0') return;299str->AppendF(" '%s' is ascii string '%s'\n", MaybeDemangleGlobalName(g.name),300(char *)g.beg);301}
302
303void PrintGlobalLocation(InternalScopedString *str, const __asan_global &g,304bool print_module_name) {305DataInfo info;306if (Symbolizer::GetOrInit()->SymbolizeData(g.beg, &info) && info.line != 0) {307str->AppendF("%s:%d", info.file, static_cast<int>(info.line));308} else if (g.gcc_location != 0) {309// Fallback to Global::gcc_location310str->AppendF("%s", g.gcc_location->filename ? g.gcc_location->filename311: g.module_name);312if (g.gcc_location->line_no)313str->AppendF(":%d", g.gcc_location->line_no);314if (g.gcc_location->column_no)315str->AppendF(":%d", g.gcc_location->column_no);316} else {317str->AppendF("%s", g.module_name);318}319if (print_module_name && info.module)320str->AppendF(" in %s", info.module);321}
322
323} // namespace __asan324
325// ---------------------- Interface ---------------- {{{1
326using namespace __asan;327
328// Apply __asan_register_globals to all globals found in the same loaded
329// executable or shared library as `flag'. The flag tracks whether globals have
330// already been registered or not for this image.
331void __asan_register_image_globals(uptr *flag) {332if (*flag)333return;334AsanApplyToGlobals(__asan_register_globals, flag);335*flag = 1;336}
337
338// This mirrors __asan_register_image_globals.
339void __asan_unregister_image_globals(uptr *flag) {340if (!*flag)341return;342AsanApplyToGlobals(__asan_unregister_globals, flag);343*flag = 0;344}
345
346void __asan_register_elf_globals(uptr *flag, void *start, void *stop) {347if (*flag || start == stop)348return;349CHECK_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_register_globals(globals_start, globals_stop - globals_start);353*flag = 1;354}
355
356void __asan_unregister_elf_globals(uptr *flag, void *start, void *stop) {357if (!*flag || start == stop)358return;359CHECK_EQ(0, ((uptr)stop - (uptr)start) % sizeof(__asan_global));360__asan_global *globals_start = (__asan_global*)start;361__asan_global *globals_stop = (__asan_global*)stop;362__asan_unregister_globals(globals_start, globals_stop - globals_start);363*flag = 0;364}
365
366// Register an array of globals.
367void __asan_register_globals(__asan_global *globals, uptr n) {368if (!flags()->report_globals) return;369GET_STACK_TRACE_MALLOC;370u32 stack_id = StackDepotPut(stack);371Lock lock(&mu_for_globals);372if (!global_registration_site_vector) {373global_registration_site_vector =374new (GetGlobalLowLevelAllocator()) GlobalRegistrationSiteVector;375global_registration_site_vector->reserve(128);376}377GlobalRegistrationSite site = {stack_id, &globals[0], &globals[n - 1]};378global_registration_site_vector->push_back(site);379if (flags()->report_globals >= 2) {380PRINT_CURRENT_STACK();381Printf("=== ID %d; %p %p\n", stack_id, (void *)&globals[0],382(void *)&globals[n - 1]);383}384for (uptr i = 0; i < n; i++) {385if (SANITIZER_WINDOWS && globals[i].beg == 0) {386// The MSVC incremental linker may pad globals out to 256 bytes. As long387// as __asan_global is less than 256 bytes large and its size is a power388// of two, we can skip over the padding.389static_assert(390sizeof(__asan_global) < 256 &&391(sizeof(__asan_global) & (sizeof(__asan_global) - 1)) == 0,392"sizeof(__asan_global) incompatible with incremental linker padding");393// If these are padding bytes, the rest of the global should be zero.394CHECK(globals[i].size == 0 && globals[i].size_with_redzone == 0 &&395globals[i].name == nullptr && globals[i].module_name == nullptr &&396globals[i].odr_indicator == 0);397continue;398}399RegisterGlobal(&globals[i]);400}401
402// Poison the metadata. It should not be accessible to user code.403PoisonShadow(reinterpret_cast<uptr>(globals), n * sizeof(__asan_global),404kAsanGlobalRedzoneMagic);405}
406
407// Unregister an array of globals.
408// We must do this when a shared objects gets dlclosed.
409void __asan_unregister_globals(__asan_global *globals, uptr n) {410if (!flags()->report_globals) return;411Lock lock(&mu_for_globals);412for (uptr i = 0; i < n; i++) {413if (SANITIZER_WINDOWS && globals[i].beg == 0) {414// Skip globals that look like padding from the MSVC incremental linker.415// See comment in __asan_register_globals.416continue;417}418UnregisterGlobal(&globals[i]);419}420
421// Unpoison the metadata.422PoisonShadow(reinterpret_cast<uptr>(globals), n * sizeof(__asan_global), 0);423}
424
425// This method runs immediately prior to dynamic initialization in each TU,
426// when all dynamically initialized globals are unpoisoned. This method
427// poisons all global variables not defined in this TU, so that a dynamic
428// initializer can only touch global variables in the same TU.
429void __asan_before_dynamic_init(const char *module_name) {430if (!flags()->check_initialization_order ||431!CanPoisonMemory() ||432!dynamic_init_globals)433return;434bool strict_init_order = flags()->strict_init_order;435CHECK(module_name);436CHECK(AsanInited());437Lock lock(&mu_for_globals);438if (flags()->report_globals >= 3)439Printf("DynInitPoison module: %s\n", module_name);440for (uptr i = 0, n = dynamic_init_globals->size(); i < n; ++i) {441DynInitGlobal &dyn_g = (*dynamic_init_globals)[i];442const Global *g = &dyn_g.g;443if (dyn_g.initialized)444continue;445if (g->module_name != module_name)446PoisonShadowForGlobal(g, kAsanInitializationOrderMagic);447else if (!strict_init_order)448dyn_g.initialized = true;449}450}
451
452// This method runs immediately after dynamic initialization in each TU, when
453// all dynamically initialized globals except for those defined in the current
454// TU are poisoned. It simply unpoisons all dynamically initialized globals.
455void __asan_after_dynamic_init() {456if (!flags()->check_initialization_order ||457!CanPoisonMemory() ||458!dynamic_init_globals)459return;460CHECK(AsanInited());461Lock lock(&mu_for_globals);462// FIXME: Optionally report that we're unpoisoning globals from a module.463for (uptr i = 0, n = dynamic_init_globals->size(); i < n; ++i) {464DynInitGlobal &dyn_g = (*dynamic_init_globals)[i];465const Global *g = &dyn_g.g;466if (!dyn_g.initialized) {467// Unpoison the whole global.468PoisonShadowForGlobal(g, 0);469// Poison redzones back.470PoisonRedZones(*g);471}472}473}
474