LLVM 24.0.0git
KCFI.cpp
Go to the documentation of this file.
1//===-- KCFI.cpp - Generic KCFI operand bundle lowering ---------*- C++ -*-===//
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 emits generic KCFI indirect call checks for targets that don't
10// support lowering KCFI operand bundles in the back-end.
11//
12//===----------------------------------------------------------------------===//
13
15#include "llvm/ADT/Statistic.h"
16#include "llvm/IR/Constants.h"
19#include "llvm/IR/Function.h"
20#include "llvm/IR/IRBuilder.h"
23#include "llvm/IR/Intrinsics.h"
24#include "llvm/IR/MDBuilder.h"
25#include "llvm/IR/Module.h"
28
29using namespace llvm;
30
31#define DEBUG_TYPE "kcfi"
32
33STATISTIC(NumKCFIChecks, "Number of kcfi operands transformed into checks");
34
35namespace {
36class DiagnosticInfoKCFI : public DiagnosticInfo {
37 const Twine &Msg;
38
39public:
40 DiagnosticInfoKCFI(const Twine &DiagMsg LLVM_LIFETIME_BOUND,
42 : DiagnosticInfo(DK_Linker, Severity), Msg(DiagMsg) {}
43 void print(DiagnosticPrinter &DP) const override { DP << Msg; }
44};
45} // namespace
46
47static void lowerTrapCheck(CallInst *CI, const Triple &T, IntegerType *Int32Ty,
48 MDNode *VeryUnlikelyWeights) {
49 // Get the expected hash value.
50 const uint32_t ExpectedHash =
52 ->getZExtValue();
53
54 // Drop the KCFI operand bundle.
56 CI->getIterator());
57 assert(Call != CI);
58 Call->copyMetadata(*CI);
60 CI->eraseFromParent();
61
62 if (!Call->isIndirectCall())
63 return;
64
65 // Emit a check and trap if the target hash doesn't match.
66 IRBuilder<> Builder(Call);
67 Builder.disableGEPCanonicalization();
68 Value *FuncPtr = Call->getCalledOperand();
69 // ARM uses the least significant bit of the function pointer to select
70 // between ARM and Thumb modes for the callee. Instructions are always
71 // at least 16-bit aligned, so clear the LSB before we compute the hash
72 // location.
73 if (T.isARM() || T.isThumb()) {
74 FuncPtr = Builder.CreateIntToPtr(
75 Builder.CreateAnd(Builder.CreatePtrToInt(FuncPtr, Int32Ty),
76 ConstantInt::getSigned(Int32Ty, -2)),
77 FuncPtr->getType());
78 }
79 Value *HashPtr = Builder.CreateConstInBoundsGEP1_32(Int32Ty, FuncPtr, -1);
80 Value *Test = Builder.CreateICmpNE(Builder.CreateLoad(Int32Ty, HashPtr),
81 ConstantInt::get(Int32Ty, ExpectedHash));
82 Instruction *ThenTerm =
83 SplitBlockAndInsertIfThen(Test, Call, false, VeryUnlikelyWeights);
84 Builder.SetInsertPoint(ThenTerm);
85 Builder.CreateIntrinsic(Intrinsic::debugtrap, {});
86 ++NumKCFIChecks;
87}
88
90 // Find call instructions with KCFI operand bundles.
92 for (Instruction &I : instructions(F)) {
93 if (auto *CI = dyn_cast<CallInst>(&I))
94 if (CI->getOperandBundle(LLVMContext::OB_kcfi))
95 TrapCalls.push_back(CI);
96 }
97
98 if (TrapCalls.empty())
99 return false;
100
101 Module &M = *F.getParent();
102 LLVMContext &Ctx = M.getContext();
103 // patchable-function-prefix emits nops between the KCFI type identifier
104 // and the function start. As we don't know the size of the emitted nops,
105 // don't allow this attribute with generic lowering.
106 if (F.hasFnAttribute("patchable-function-prefix"))
107 Ctx.diagnose(
108 DiagnosticInfoKCFI("-fpatchable-function-entry=N,M, where M>0 is not "
109 "compatible with -fsanitize=kcfi on this target"));
110
111 IntegerType *Int32Ty = Type::getInt32Ty(Ctx);
112 MDNode *VeryUnlikelyWeights = MDBuilder(Ctx).createUnlikelyBranchWeights();
113 Triple T(M.getTargetTriple());
114
115 for (CallInst *CI : TrapCalls)
116 lowerTrapCheck(CI, T, Int32Ty, VeryUnlikelyWeights);
117 return true;
118}
119
121 if (!F.getParent()->getModuleFlag("kcfi"))
122 return PreservedAnalyses::all();
123
124 if (!lowerTrapBundles(F))
125 return PreservedAnalyses::all();
127}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Expand Atomic instructions
#define LLVM_LIFETIME_BOUND
Definition Compiler.h:464
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Module.h This file contains the declarations for the Module class.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define T
const char * Msg
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
static bool lowerTrapBundles(Function &F)
Definition KCFI.cpp:89
static void lowerTrapCheck(CallInst *CI, const Triple &T, IntegerType *Int32Ty, MDNode *VeryUnlikelyWeights)
Definition KCFI.cpp:47
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
std::optional< OperandBundleUse > getOperandBundle(StringRef Name) const
Return an operand bundle by name, if present.
static LLVM_ABI CallBase * removeOperandBundle(CallBase *CB, uint32_t ID, InsertPosition InsertPt=nullptr)
Create a clone of CB with operand bundle ID removed.
This class represents a function call, abstracting a target machine's calling convention.
static ConstantInt * getSigned(IntegerType *Ty, int64_t V, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
Definition Constants.h:135
This is the base abstract class for diagnostic reporting in the backend.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2990
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
Class to represent integer types.
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Definition KCFI.cpp:120
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
LLVM_ABI void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
LLVM_ABI MDNode * createUnlikelyBranchWeights()
Return metadata containing two branch weights, with significant bias towards false destination.
Definition MDBuilder.cpp:48
Metadata node.
Definition Metadata.h:1087
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition Analysis.h:115
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:48
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:294
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:548
self_iterator getIterator()
Definition ilist_node.h:123
CallInst * Call
This is an optimization pass for GlobalISel generic memory operations.
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
DiagnosticSeverity
Defines the different supported severity of a diagnostic.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI Instruction * SplitBlockAndInsertIfThen(Value *Cond, BasicBlock::iterator SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, BasicBlock *ThenBlock=nullptr)
Split the containing block at the specified instruction - everything before SplitBefore stays in the ...
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.