1//===-- CrossDSOCFI.cpp - Externalize this module's CFI checks ------------===//
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 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.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Transforms/IPO/CrossDSOCFI.h"
15#include "llvm/ADT/SetVector.h"
16#include "llvm/ADT/Statistic.h"
17#include "llvm/IR/Constants.h"
18#include "llvm/IR/Function.h"
19#include "llvm/IR/IRBuilder.h"
20#include "llvm/IR/Instructions.h"
21#include "llvm/IR/Intrinsics.h"
22#include "llvm/IR/MDBuilder.h"
23#include "llvm/IR/Module.h"
24#include "llvm/IR/ProfDataUtils.h"
25#include "llvm/TargetParser/Triple.h"
26#include "llvm/Transforms/IPO/LowerTypeTests.h"
27
28using namespace llvm;
29
30#define DEBUG_TYPE "cross-dso-cfi"
31
32STATISTIC(NumTypeIds, "Number of unique type identifiers");
33
34namespace {
35
36struct CrossDSOCFI {
37 MDNode *VeryLikelyWeights;
38
39 void buildCFICheck(Module &M);
40 bool runOnModule(Module &M);
41};
42
43} // anonymous namespace
44
45/// buildCFICheck - emits __cfi_check for the current module.
46void CrossDSOCFI::buildCFICheck(Module &M) {
47 // FIXME: verify that __cfi_check ends up near the end of the code section,
48 // but before the jump slots created in LowerTypeTests.
49 SetVector<uint64_t> TypeIds = lowertypetests::findCfiTypeIds(M);
50
51 LLVMContext &Ctx = M.getContext();
52 FunctionCallee C = M.getOrInsertFunction(
53 Name: "__cfi_check", RetTy: Type::getVoidTy(C&: Ctx), Args: Type::getInt64Ty(C&: Ctx),
54 Args: PointerType::getUnqual(C&: Ctx), Args: PointerType::getUnqual(C&: Ctx));
55 Function *F = cast<Function>(Val: C.getCallee());
56 // Take over the existing function. The frontend emits a weak stub so that the
57 // linker knows about the symbol; this pass replaces the function body.
58 F->deleteBody();
59 F->setAlignment(Align(4096));
60 // __cfi_check is synthesized by this pass, so there is no profile data for
61 // it.
62 setExplicitlyUnknownFunctionEntryCount(F&: *F, DEBUG_TYPE);
63
64 Triple T(M.getTargetTriple());
65 if (T.isARM() || T.isThumb())
66 F->addFnAttr(Kind: "target-features", Val: "+thumb-mode");
67
68 auto args = F->arg_begin();
69 Value &CallSiteTypeId = *(args++);
70 CallSiteTypeId.setName("CallSiteTypeId");
71 Value &Addr = *(args++);
72 Addr.setName("Addr");
73 Value &CFICheckFailData = *(args++);
74 CFICheckFailData.setName("CFICheckFailData");
75 assert(args == F->arg_end());
76
77 BasicBlock *BB = BasicBlock::Create(Context&: Ctx, Name: "entry", Parent: F);
78 BasicBlock *ExitBB = BasicBlock::Create(Context&: Ctx, Name: "exit", Parent: F);
79
80 BasicBlock *TrapBB = BasicBlock::Create(Context&: Ctx, Name: "fail", Parent: F);
81 IRBuilder<> IRBFail(TrapBB);
82 FunctionCallee CFICheckFailFn = M.getOrInsertFunction(
83 Name: "__cfi_check_fail", RetTy: Type::getVoidTy(C&: Ctx), Args: PointerType::getUnqual(C&: Ctx),
84 Args: PointerType::getUnqual(C&: Ctx));
85 IRBFail.CreateCall(Callee: CFICheckFailFn, Args: {&CFICheckFailData, &Addr});
86 IRBFail.CreateBr(Dest: ExitBB);
87
88 IRBuilder<> IRBExit(ExitBB);
89 IRBExit.CreateRetVoid();
90
91 IRBuilder<> IRB(BB);
92 SwitchInst *SI = IRB.CreateSwitch(V: &CallSiteTypeId, Dest: TrapBB, NumCases: TypeIds.size());
93 // The distribution of type ids at the call sites is not known.
94 setExplicitlyUnknownBranchWeights(I&: *SI, DEBUG_TYPE);
95 for (uint64_t TypeId : TypeIds) {
96 ConstantInt *CaseTypeId = ConstantInt::get(Ty: Type::getInt64Ty(C&: Ctx), V: TypeId);
97 BasicBlock *TestBB = BasicBlock::Create(Context&: Ctx, Name: "test", Parent: F);
98 IRBuilder<> IRBTest(TestBB);
99
100 Value *Test = IRBTest.CreateIntrinsic(
101 ID: Intrinsic::type_test,
102 Args: {&Addr,
103 MetadataAsValue::get(Context&: Ctx, MD: ConstantAsMetadata::get(C: CaseTypeId))});
104 CondBrInst *BI = IRBTest.CreateCondBr(Cond: Test, True: ExitBB, False: TrapBB);
105 BI->setMetadata(KindID: LLVMContext::MD_prof, Node: VeryLikelyWeights);
106
107 SI->addCase(OnVal: CaseTypeId, Dest: TestBB);
108 ++NumTypeIds;
109 }
110}
111
112bool CrossDSOCFI::runOnModule(Module &M) {
113 VeryLikelyWeights = MDBuilder(M.getContext()).createLikelyBranchWeights();
114 if (M.getModuleFlag(Key: "Cross-DSO CFI") == nullptr)
115 return false;
116 buildCFICheck(M);
117 return true;
118}
119
120PreservedAnalyses CrossDSOCFIPass::run(Module &M, ModuleAnalysisManager &AM) {
121 CrossDSOCFI Impl;
122 bool Changed = Impl.runOnModule(M);
123 if (!Changed)
124 return PreservedAnalyses::all();
125 return PreservedAnalyses::none();
126}
127