1 //===-- CrossDSOCFI.cpp - Externalize this module's CFI checks ------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This pass exports all llvm.bitset's found in the module in the form of a
10 // __cfi_check function, which can be used to verify cross-DSO call targets.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Transforms/IPO/CrossDSOCFI.h"
15 #include "llvm/ADT/SetVector.h"
16 #include "llvm/ADT/Statistic.h"
17 #include "llvm/ADT/Triple.h"
18 #include "llvm/IR/Constant.h"
19 #include "llvm/IR/Constants.h"
20 #include "llvm/IR/Function.h"
21 #include "llvm/IR/GlobalObject.h"
22 #include "llvm/IR/GlobalVariable.h"
23 #include "llvm/IR/IRBuilder.h"
24 #include "llvm/IR/Instructions.h"
25 #include "llvm/IR/Intrinsics.h"
26 #include "llvm/IR/MDBuilder.h"
27 #include "llvm/IR/Module.h"
28 #include "llvm/IR/Operator.h"
29 #include "llvm/Pass.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include "llvm/Transforms/IPO.h"
36 #define DEBUG_TYPE "cross-dso-cfi"
38 STATISTIC(NumTypeIds
, "Number of unique type identifiers");
42 struct CrossDSOCFI
: public ModulePass
{
44 CrossDSOCFI() : ModulePass(ID
) {
45 initializeCrossDSOCFIPass(*PassRegistry::getPassRegistry());
48 MDNode
*VeryLikelyWeights
;
50 ConstantInt
*extractNumericTypeId(MDNode
*MD
);
51 void buildCFICheck(Module
&M
);
52 bool runOnModule(Module
&M
) override
;
55 } // anonymous namespace
57 INITIALIZE_PASS_BEGIN(CrossDSOCFI
, "cross-dso-cfi", "Cross-DSO CFI", false,
59 INITIALIZE_PASS_END(CrossDSOCFI
, "cross-dso-cfi", "Cross-DSO CFI", false, false)
60 char CrossDSOCFI::ID
= 0;
62 ModulePass
*llvm::createCrossDSOCFIPass() { return new CrossDSOCFI
; }
64 /// Extracts a numeric type identifier from an MDNode containing type metadata.
65 ConstantInt
*CrossDSOCFI::extractNumericTypeId(MDNode
*MD
) {
66 // This check excludes vtables for classes inside anonymous namespaces.
67 auto TM
= dyn_cast
<ValueAsMetadata
>(MD
->getOperand(1));
70 auto C
= dyn_cast_or_null
<ConstantInt
>(TM
->getValue());
71 if (!C
) return nullptr;
72 // We are looking for i64 constants.
73 if (C
->getBitWidth() != 64) return nullptr;
78 /// buildCFICheck - emits __cfi_check for the current module.
79 void CrossDSOCFI::buildCFICheck(Module
&M
) {
80 // FIXME: verify that __cfi_check ends up near the end of the code section,
81 // but before the jump slots created in LowerTypeTests.
82 SetVector
<uint64_t> TypeIds
;
83 SmallVector
<MDNode
*, 2> Types
;
84 for (GlobalObject
&GO
: M
.global_objects()) {
86 GO
.getMetadata(LLVMContext::MD_type
, Types
);
87 for (MDNode
*Type
: Types
) {
88 // Sanity check. GO must not be a function declaration.
89 assert(!isa
<Function
>(&GO
) || !cast
<Function
>(&GO
)->isDeclaration());
91 if (ConstantInt
*TypeId
= extractNumericTypeId(Type
))
92 TypeIds
.insert(TypeId
->getZExtValue());
96 NamedMDNode
*CfiFunctionsMD
= M
.getNamedMetadata("cfi.functions");
98 for (auto Func
: CfiFunctionsMD
->operands()) {
99 assert(Func
->getNumOperands() >= 2);
100 for (unsigned I
= 2; I
< Func
->getNumOperands(); ++I
)
101 if (ConstantInt
*TypeId
=
102 extractNumericTypeId(cast
<MDNode
>(Func
->getOperand(I
).get())))
103 TypeIds
.insert(TypeId
->getZExtValue());
107 LLVMContext
&Ctx
= M
.getContext();
108 FunctionCallee C
= M
.getOrInsertFunction(
109 "__cfi_check", Type::getVoidTy(Ctx
), Type::getInt64Ty(Ctx
),
110 Type::getInt8PtrTy(Ctx
), Type::getInt8PtrTy(Ctx
));
111 Function
*F
= dyn_cast
<Function
>(C
.getCallee());
112 // Take over the existing function. The frontend emits a weak stub so that the
113 // linker knows about the symbol; this pass replaces the function body.
115 F
->setAlignment(4096);
117 Triple
T(M
.getTargetTriple());
118 if (T
.isARM() || T
.isThumb())
119 F
->addFnAttr("target-features", "+thumb-mode");
121 auto args
= F
->arg_begin();
122 Value
&CallSiteTypeId
= *(args
++);
123 CallSiteTypeId
.setName("CallSiteTypeId");
124 Value
&Addr
= *(args
++);
125 Addr
.setName("Addr");
126 Value
&CFICheckFailData
= *(args
++);
127 CFICheckFailData
.setName("CFICheckFailData");
128 assert(args
== F
->arg_end());
130 BasicBlock
*BB
= BasicBlock::Create(Ctx
, "entry", F
);
131 BasicBlock
*ExitBB
= BasicBlock::Create(Ctx
, "exit", F
);
133 BasicBlock
*TrapBB
= BasicBlock::Create(Ctx
, "fail", F
);
134 IRBuilder
<> IRBFail(TrapBB
);
135 FunctionCallee CFICheckFailFn
=
136 M
.getOrInsertFunction("__cfi_check_fail", Type::getVoidTy(Ctx
),
137 Type::getInt8PtrTy(Ctx
), Type::getInt8PtrTy(Ctx
));
138 IRBFail
.CreateCall(CFICheckFailFn
, {&CFICheckFailData
, &Addr
});
139 IRBFail
.CreateBr(ExitBB
);
141 IRBuilder
<> IRBExit(ExitBB
);
142 IRBExit
.CreateRetVoid();
145 SwitchInst
*SI
= IRB
.CreateSwitch(&CallSiteTypeId
, TrapBB
, TypeIds
.size());
146 for (uint64_t TypeId
: TypeIds
) {
147 ConstantInt
*CaseTypeId
= ConstantInt::get(Type::getInt64Ty(Ctx
), TypeId
);
148 BasicBlock
*TestBB
= BasicBlock::Create(Ctx
, "test", F
);
149 IRBuilder
<> IRBTest(TestBB
);
150 Function
*BitsetTestFn
= Intrinsic::getDeclaration(&M
, Intrinsic::type_test
);
152 Value
*Test
= IRBTest
.CreateCall(
153 BitsetTestFn
, {&Addr
, MetadataAsValue::get(
154 Ctx
, ConstantAsMetadata::get(CaseTypeId
))});
155 BranchInst
*BI
= IRBTest
.CreateCondBr(Test
, ExitBB
, TrapBB
);
156 BI
->setMetadata(LLVMContext::MD_prof
, VeryLikelyWeights
);
158 SI
->addCase(CaseTypeId
, TestBB
);
163 bool CrossDSOCFI::runOnModule(Module
&M
) {
165 MDBuilder(M
.getContext()).createBranchWeights((1U << 20) - 1, 1);
166 if (M
.getModuleFlag("Cross-DSO CFI") == nullptr)
172 PreservedAnalyses
CrossDSOCFIPass::run(Module
&M
, ModuleAnalysisManager
&AM
) {
174 bool Changed
= Impl
.runOnModule(M
);
176 return PreservedAnalyses::all();
177 return PreservedAnalyses::none();