llvm.org GIT mirror llvm / 7bfedca
[asan] Fix dead stripping of globals on Linux. Use a combination of !associated, comdat, @llvm.compiler.used and custom sections to allow dead stripping of globals and their asan metadata. Sometimes. Currently this works on LLD, which supports SHF_LINK_ORDER with sh_link pointing to the associated section. This also works on BFD, which seems to treat comdats as all-or-nothing with respect to linker GC. There is a weird quirk where the "first" global in each link is never GC-ed because of the section symbols. At this moment it does not work on Gold (as in the globals are never stripped). This is a re-land of r298158 rebased on D31358. This time, asan.module_ctor is put in a comdat as well to avoid quadratic behavior in Gold. git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@299697 91177308-0d34-0410-b5e6-96231b3b80d8 Evgeniy Stepanov 2 years ago
7 changed file(s) with 164 addition(s) and 49 deletion(s). Raw diff Collapse all Expand all
8383 void filterDeadComdatFunctions(
8484 Module &M, SmallVectorImpl &DeadComdatFunctions);
8585
86 /// \brief Produce a unique identifier for this module by taking the MD5 sum of
87 /// the names of the module's strong external symbols.
88 ///
89 /// This identifier is normally guaranteed to be unique, or the program would
90 /// fail to link due to multiply defined symbols.
91 ///
92 /// If the module has no strong external symbols (such a module may still have a
93 /// semantic effect if it performs global initialization), we cannot produce a
94 /// unique identifier for this module, so we return the empty string.
95 std::string getUniqueModuleId(Module *M);
96
8697 } // End llvm namespace
8798
8899 #endif // LLVM_TRANSFORMS_UTILS_MODULEUTILS_H
2929 #include "llvm/Transforms/IPO.h"
3030 #include "llvm/Transforms/IPO/FunctionAttrs.h"
3131 #include "llvm/Transforms/Utils/Cloning.h"
32 #include "llvm/Transforms/Utils/ModuleUtils.h"
3233 using namespace llvm;
3334
3435 namespace {
35
36 // Produce a unique identifier for this module by taking the MD5 sum of the
37 // names of the module's strong external symbols. This identifier is
38 // normally guaranteed to be unique, or the program would fail to link due to
39 // multiply defined symbols.
40 //
41 // If the module has no strong external symbols (such a module may still have a
42 // semantic effect if it performs global initialization), we cannot produce a
43 // unique identifier for this module, so we return the empty string, which
44 // causes the entire module to be written as a regular LTO module.
45 std::string getModuleId(Module *M) {
46 MD5 Md5;
47 bool ExportsSymbols = false;
48 for (auto &GV : M->global_values()) {
49 if (GV.isDeclaration() || GV.getName().startswith("llvm.") ||
50 !GV.hasExternalLinkage())
51 continue;
52 ExportsSymbols = true;
53 Md5.update(GV.getName());
54 Md5.update(ArrayRef{0});
55 }
56
57 if (!ExportsSymbols)
58 return "";
59
60 MD5::MD5Result R;
61 Md5.final(R);
62
63 SmallString<32> Str;
64 MD5::stringifyResult(R, Str);
65 return ("$" + Str).str();
66 }
6736
6837 // Promote each local-linkage entity defined by ExportM and used by ImportM by
6938 // changing visibility and appending the given ModuleId.
236205 void splitAndWriteThinLTOBitcode(
237206 raw_ostream &OS, raw_ostream *ThinLinkOS,
238207 function_ref AARGetter, Module &M) {
239 std::string ModuleId = getModuleId(&M);
208 std::string ModuleId = getUniqueModuleId(&M);
240209 if (ModuleId.empty()) {
241210 // We couldn't generate a module ID for this module, just write it out as a
242211 // regular LTO module.
100100 "__asan_register_image_globals";
101101 static const char *const kAsanUnregisterImageGlobalsName =
102102 "__asan_unregister_image_globals";
103 static const char *const kAsanRegisterElfGlobalsName =
104 "__asan_register_elf_globals";
105 static const char *const kAsanUnregisterElfGlobalsName =
106 "__asan_unregister_elf_globals";
103107 static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
104108 static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
105109 static const char *const kAsanInitName = "__asan_init";
119123 "__asan_poison_stack_memory";
120124 static const char *const kAsanUnpoisonStackMemoryName =
121125 "__asan_unpoison_stack_memory";
126
127 // ASan version script has __asan_* wildcard. Triple underscore prevents a
128 // linker (gold) warning about attempting to export a local symbol.
122129 static const char *const kAsanGlobalsRegisteredFlagName =
123 "__asan_globals_registered";
130 "___asan_globals_registered";
124131
125132 static const char *const kAsanOptionDetectUseAfterReturn =
126133 "__asan_option_detect_stack_use_after_return";
609616 void InstrumentGlobalsCOFF(IRBuilder<> &IRB, Module &M,
610617 ArrayRef ExtendedGlobals,
611618 ArrayRef MetadataInitializers);
619 void InstrumentGlobalsELF(IRBuilder<> &IRB, Module &M,
620 ArrayRef ExtendedGlobals,
621 ArrayRef MetadataInitializers,
622 const std::string &UniqueModuleId);
612623 void InstrumentGlobalsMachO(IRBuilder<> &IRB, Module &M,
613624 ArrayRef ExtendedGlobals,
614625 ArrayRef MetadataInitializers);
619630
620631 GlobalVariable *CreateMetadataGlobal(Module &M, Constant *Initializer,
621632 StringRef OriginalName);
622 void SetComdatForGlobalMetadata(GlobalVariable *G, GlobalVariable *Metadata);
633 void SetComdatForGlobalMetadata(GlobalVariable *G, GlobalVariable *Metadata,
634 StringRef InternalSuffix);
623635 IRBuilder<> CreateAsanModuleDtor(Module &M);
624636
625637 bool ShouldInstrumentGlobal(GlobalVariable *G);
644656 Function *AsanUnregisterGlobals;
645657 Function *AsanRegisterImageGlobals;
646658 Function *AsanUnregisterImageGlobals;
659 Function *AsanRegisterElfGlobals;
660 Function *AsanUnregisterElfGlobals;
647661
648662 Function *AsanCtorFunction = nullptr;
649663 Function *AsanDtorFunction = nullptr;
16011615 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
16021616 kAsanUnregisterImageGlobalsName, IRB.getVoidTy(), IntptrTy, nullptr));
16031617 AsanUnregisterImageGlobals->setLinkage(Function::ExternalLinkage);
1618
1619 AsanRegisterElfGlobals = checkSanitizerInterfaceFunction(
1620 M.getOrInsertFunction(kAsanRegisterElfGlobalsName, IRB.getVoidTy(),
1621 IntptrTy, IntptrTy, IntptrTy, nullptr));
1622 AsanRegisterElfGlobals->setLinkage(Function::ExternalLinkage);
1623
1624 AsanUnregisterElfGlobals = checkSanitizerInterfaceFunction(
1625 M.getOrInsertFunction(kAsanUnregisterElfGlobalsName, IRB.getVoidTy(),
1626 IntptrTy, IntptrTy, IntptrTy, nullptr));
1627 AsanUnregisterElfGlobals->setLinkage(Function::ExternalLinkage);
16041628 }
16051629
16061630 // Put the metadata and the instrumented global in the same group. This ensures
16071631 // that the metadata is discarded if the instrumented global is discarded.
16081632 void AddressSanitizerModule::SetComdatForGlobalMetadata(
1609 GlobalVariable *G, GlobalVariable *Metadata) {
1633 GlobalVariable *G, GlobalVariable *Metadata, StringRef InternalSuffix) {
16101634 Module &M = *G->getParent();
16111635 Comdat *C = G->getComdat();
16121636 if (!C) {
16161640 assert(G->hasLocalLinkage());
16171641 G->setName(Twine(kAsanGenPrefix) + "_anon_global");
16181642 }
1619 C = M.getOrInsertComdat(G->getName());
1643
1644 if (!InternalSuffix.empty() && G->hasLocalLinkage()) {
1645 std::string Name = G->getName();
1646 Name += InternalSuffix;
1647 C = M.getOrInsertComdat(Name);
1648 } else {
1649 C = M.getOrInsertComdat(G->getName());
1650 }
1651
16201652 // Make this IMAGE_COMDAT_SELECT_NODUPLICATES on COFF.
16211653 if (TargetTriple.isOSBinFormatCOFF())
16221654 C->setSelectionKind(Comdat::NoDuplicates);
16701702 "global metadata will not be padded appropriately");
16711703 Metadata->setAlignment(SizeOfGlobalStruct);
16721704
1673 SetComdatForGlobalMetadata(G, Metadata);
1674 }
1705 SetComdatForGlobalMetadata(G, Metadata, "");
1706 }
1707 }
1708
1709 void AddressSanitizerModule::InstrumentGlobalsELF(
1710 IRBuilder<> &IRB, Module &M, ArrayRef ExtendedGlobals,
1711 ArrayRef MetadataInitializers,
1712 const std::string &UniqueModuleId) {
1713 assert(ExtendedGlobals.size() == MetadataInitializers.size());
1714
1715 SmallVector MetadataGlobals(ExtendedGlobals.size());
1716 for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
1717 GlobalVariable *G = ExtendedGlobals[i];
1718 GlobalVariable *Metadata =
1719 CreateMetadataGlobal(M, MetadataInitializers[i], G->getName());
1720 MDNode *MD = MDNode::get(M.getContext(), ValueAsMetadata::get(G));
1721 Metadata->setMetadata(LLVMContext::MD_associated, MD);
1722 MetadataGlobals[i] = Metadata;
1723
1724 SetComdatForGlobalMetadata(G, Metadata, UniqueModuleId);
1725 }
1726
1727 // Update llvm.compiler.used, adding the new metadata globals. This is
1728 // needed so that during LTO these variables stay alive.
1729 if (!MetadataGlobals.empty())
1730 appendToCompilerUsed(M, MetadataGlobals);
1731
1732 // RegisteredFlag serves two purposes. First, we can pass it to dladdr()
1733 // to look up the loaded image that contains it. Second, we can store in it
1734 // whether registration has already occurred, to prevent duplicate
1735 // registration.
1736 //
1737 // Common linkage ensures that there is only one global per shared library.
1738 GlobalVariable *RegisteredFlag = new GlobalVariable(
1739 M, IntptrTy, false, GlobalVariable::CommonLinkage,
1740 ConstantInt::get(IntptrTy, 0), kAsanGlobalsRegisteredFlagName);
1741 RegisteredFlag->setVisibility(GlobalVariable::HiddenVisibility);
1742
1743 // Create start and stop symbols.
1744 GlobalVariable *StartELFMetadata = new GlobalVariable(
1745 M, IntptrTy, false, GlobalVariable::ExternalWeakLinkage, nullptr,
1746 "__start_" + getGlobalMetadataSection());
1747 StartELFMetadata->setVisibility(GlobalVariable::HiddenVisibility);
1748 GlobalVariable *StopELFMetadata = new GlobalVariable(
1749 M, IntptrTy, false, GlobalVariable::ExternalWeakLinkage, nullptr,
1750 "__stop_" + getGlobalMetadataSection());
1751 StopELFMetadata->setVisibility(GlobalVariable::HiddenVisibility);
1752
1753 // Create a call to register the globals with the runtime.
1754 IRB.CreateCall(AsanRegisterElfGlobals,
1755 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy),
1756 IRB.CreatePointerCast(StartELFMetadata, IntptrTy),
1757 IRB.CreatePointerCast(StopELFMetadata, IntptrTy)});
1758
1759 // We also need to unregister globals at the end, e.g., when a shared library
1760 // gets closed.
1761 IRBuilder<> IRB_Dtor = CreateAsanModuleDtor(M);
1762 IRB_Dtor.CreateCall(AsanUnregisterElfGlobals,
1763 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy),
1764 IRB.CreatePointerCast(StartELFMetadata, IntptrTy),
1765 IRB.CreatePointerCast(StopELFMetadata, IntptrTy)});
16751766 }
16761767
16771768 void AddressSanitizerModule::InstrumentGlobalsMachO(
19222013 Initializers[i] = Initializer;
19232014 }
19242015
1925 if (TargetTriple.isOSBinFormatCOFF()) {
2016 std::string ELFUniqueModuleId =
2017 TargetTriple.isOSBinFormatELF() ? getUniqueModuleId(&M) : "";
2018
2019 if (!ELFUniqueModuleId.empty()) {
2020 InstrumentGlobalsELF(IRB, M, NewGlobals, Initializers, ELFUniqueModuleId);
2021 *CtorComdat = true;
2022 } else if (TargetTriple.isOSBinFormatCOFF()) {
19262023 InstrumentGlobalsCOFF(IRB, M, NewGlobals, Initializers);
19272024 } else if (ShouldUseMachOGlobalsSection()) {
19282025 InstrumentGlobalsMachO(IRB, M, NewGlobals, Initializers);
236236 ComdatEntriesCovered.end();
237237 });
238238 }
239
240 std::string llvm::getUniqueModuleId(Module *M) {
241 MD5 Md5;
242 bool ExportsSymbols = false;
243 auto AddGlobal = [&](GlobalValue &GV) {
244 if (GV.isDeclaration() || GV.getName().startswith("llvm.") ||
245 !GV.hasExternalLinkage())
246 return;
247 ExportsSymbols = true;
248 Md5.update(GV.getName());
249 Md5.update(ArrayRef{0});
250 };
251
252 for (auto &F : *M)
253 AddGlobal(F);
254 for (auto &GV : M->globals())
255 AddGlobal(GV);
256 for (auto &GA : M->aliases())
257 AddGlobal(GA);
258 for (auto &IF : M->ifuncs())
259 AddGlobal(IF);
260
261 if (!ExportsSymbols)
262 return "";
263
264 MD5::MD5Result R;
265 Md5.final(R);
266
267 SmallString<32> Str;
268 MD5::stringifyResult(R, Str);
269 return ("$" + Str).str();
270 }
1111 @llvm.global_ctors = appending global [1 x { i32, void ()*, i8* }] [{ i32, void ()*, i8* } { i32 65535, void ()* @_GLOBAL__sub_I_asan_globals.cpp, i8* null }]
1212
1313 ; Check that globals were instrumented:
14 ; CHECK: @global = global { i32, [60 x i8] } zeroinitializer, align 32
15 ; CHECK: @.str = internal unnamed_addr constant { [14 x i8], [50 x i8] } { [14 x i8] c"Hello, world!\00", [50 x i8] zeroinitializer }, align 32
14
15 ; CHECK: @global = global { i32, [60 x i8] } zeroinitializer, comdat, align 32
16 ; CHECK: @.str = internal unnamed_addr constant { [14 x i8], [50 x i8] } { [14 x i8] c"Hello, world!\00", [50 x i8] zeroinitializer }, comdat($".str${{[01-9a-f]+}}"), align 32
1617
1718 ; Check emitted location descriptions:
1819 ; CHECK: [[VARNAME:@__asan_gen_.[0-9]+]] = private unnamed_addr constant [7 x i8] c"global\00", align 1
1920 ; CHECK: [[FILENAME:@__asan_gen_.[0-9]+]] = private unnamed_addr constant [22 x i8] c"/tmp/asan-globals.cpp\00", align 1
2021 ; CHECK: [[LOCDESCR:@__asan_gen_.[0-9]+]] = private unnamed_addr constant { [22 x i8]*, i32, i32 } { [22 x i8]* [[FILENAME]], i32 5, i32 5 }
22 ; CHECK: @__asan_global_global = {{.*}}i64 ptrtoint ({ i32, [60 x i8] }* @global to i64){{.*}} section "asan_globals"{{.*}}, !associated
23 ; CHECK: @__asan_global_.str = {{.*}}i64 ptrtoint ({ [14 x i8], [50 x i8] }* @.str to i64){{.*}} section "asan_globals"{{.*}}, !associated
24
25 ; The metadata has to be inserted to llvm.compiler.used to avoid being stripped
26 ; during LTO.
27 ; CHECK: @llvm.compiler.used {{.*}} @__asan_global_global {{.*}} section "llvm.metadata"
2128
2229 ; Check that location descriptors and global names were passed into __asan_register_globals:
23 ; CHECK: i64 ptrtoint ([7 x i8]* [[VARNAME]] to i64)
24 ; CHECK: i64 ptrtoint ({ [22 x i8]*, i32, i32 }* [[LOCDESCR]] to i64)
30 ; CHECK: call void @__asan_register_elf_globals(i64 ptrtoint (i64* @___asan_globals_registered to i64), i64 ptrtoint (i64* @__start_asan_globals to i64), i64 ptrtoint (i64* @__stop_asan_globals to i64))
2531
2632 ; Function Attrs: nounwind sanitize_address
2733 define internal void @__cxx_global_var_init() #0 section ".text.startup" {
2525 ; CHECK: @llvm.compiler.used {{.*}} @__asan_binder_global {{.*}} section "llvm.metadata"
2626
2727 ; Test that there is the flag global variable:
28 ; CHECK: @__asan_globals_registered = common hidden global i64 0
28 ; CHECK: @___asan_globals_registered = common hidden global i64 0
2929
3030 ; Test that __asan_register_image_globals is invoked from the constructor:
3131 ; CHECK-LABEL: define internal void @asan.module_ctor
3232 ; CHECK-NOT: ret
33 ; CHECK: call void @__asan_register_image_globals(i64 ptrtoint (i64* @__asan_globals_registered to i64))
33 ; CHECK: call void @__asan_register_image_globals(i64 ptrtoint (i64* @___asan_globals_registered to i64))
3434 ; CHECK: ret
3535
3636 ; Test that __asan_unregister_image_globals is invoked from the destructor:
3737 ; CHECK-LABEL: define internal void @asan.module_dtor
3838 ; CHECK-NOT: ret
39 ; CHECK: call void @__asan_unregister_image_globals(i64 ptrtoint (i64* @__asan_globals_registered to i64))
39 ; CHECK: call void @__asan_unregister_image_globals(i64 ptrtoint (i64* @___asan_globals_registered to i64))
4040 ; CHECK: ret
7272
7373 ; CHECK-LABEL: define internal void @asan.module_ctor
7474 ; CHECK-NOT: ret
75 ; CHECK: call void @__asan_register_globals
75 ; CHECK: call void @__asan_register_elf_globals
7676 ; CHECK: ret
7777
7878 ; CHECK-LABEL: define internal void @asan.module_dtor
7979 ; CHECK-NOT: ret
80 ; CHECK: call void @__asan_unregister_globals
80 ; CHECK: call void @__asan_unregister_elf_globals
8181 ; CHECK: ret