LLVM 19.0.0git
Go to the documentation of this file.
1//===-- KCFI.cpp - Generic KCFI operand bundle lowering ---------*- C++ -*-===//
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
9// This pass emits generic KCFI indirect call checks for targets that don't
10// support lowering KCFI operand bundles in the back-end.
15#include "llvm/ADT/Statistic.h"
16#include "llvm/IR/Constants.h"
19#include "llvm/IR/Function.h"
21#include "llvm/IR/IRBuilder.h"
24#include "llvm/IR/Intrinsics.h"
25#include "llvm/IR/MDBuilder.h"
26#include "llvm/IR/Module.h"
30using namespace llvm;
32#define DEBUG_TYPE "kcfi"
34STATISTIC(NumKCFIChecks, "Number of kcfi operands transformed into checks");
36namespace {
37class DiagnosticInfoKCFI : public DiagnosticInfo {
38 const Twine &Msg;
41 DiagnosticInfoKCFI(const Twine &DiagMsg,
43 : DiagnosticInfo(DK_Linker, Severity), Msg(DiagMsg) {}
44 void print(DiagnosticPrinter &DP) const override { DP << Msg; }
46} // namespace
49 Module &M = *F.getParent();
50 if (!M.getModuleFlag("kcfi"))
53 // Find call instructions with KCFI operand bundles.
55 for (Instruction &I : instructions(F)) {
56 if (auto *CI = dyn_cast<CallInst>(&I))
57 if (CI->getOperandBundle(LLVMContext::OB_kcfi))
58 KCFICalls.push_back(CI);
59 }
61 if (KCFICalls.empty())
64 LLVMContext &Ctx = M.getContext();
65 // patchable-function-prefix emits nops between the KCFI type identifier
66 // and the function start. As we don't know the size of the emitted nops,
67 // don't allow this attribute with generic lowering.
68 if (F.hasFnAttribute("patchable-function-prefix"))
69 Ctx.diagnose(
70 DiagnosticInfoKCFI("-fpatchable-function-entry=N,M, where M>0 is not "
71 "compatible with -fsanitize=kcfi on this target"));
73 IntegerType *Int32Ty = Type::getInt32Ty(Ctx);
74 MDNode *VeryUnlikelyWeights = MDBuilder(Ctx).createUnlikelyBranchWeights();
75 Triple T(M.getTargetTriple());
77 for (CallInst *CI : KCFICalls) {
78 // Get the expected hash value.
79 const uint32_t ExpectedHash =
80 cast<ConstantInt>(CI->getOperandBundle(LLVMContext::OB_kcfi)->Inputs[0])
81 ->getZExtValue();
83 // Drop the KCFI operand bundle.
85 CI->getIterator());
86 assert(Call != CI);
87 Call->copyMetadata(*CI);
88 CI->replaceAllUsesWith(Call);
89 CI->eraseFromParent();
91 if (!Call->isIndirectCall())
92 continue;
94 // Emit a check and trap if the target hash doesn't match.
95 IRBuilder<> Builder(Call);
96 Value *FuncPtr = Call->getCalledOperand();
97 // ARM uses the least significant bit of the function pointer to select
98 // between ARM and Thumb modes for the callee. Instructions are always
99 // at least 16-bit aligned, so clear the LSB before we compute the hash
100 // location.
101 if (T.isARM() || T.isThumb()) {
102 FuncPtr = Builder.CreateIntToPtr(
103 Builder.CreateAnd(Builder.CreatePtrToInt(FuncPtr, Int32Ty),
104 ConstantInt::get(Int32Ty, -2)),
105 FuncPtr->getType());
106 }
107 Value *HashPtr = Builder.CreateConstInBoundsGEP1_32(Int32Ty, FuncPtr, -1);
108 Value *Test = Builder.CreateICmpNE(Builder.CreateLoad(Int32Ty, HashPtr),
109 ConstantInt::get(Int32Ty, ExpectedHash));
110 Instruction *ThenTerm =
111 SplitBlockAndInsertIfThen(Test, Call, false, VeryUnlikelyWeights);
112 Builder.SetInsertPoint(ThenTerm);
113 Builder.CreateCall(Intrinsic::getDeclaration(&M, Intrinsic::debugtrap));
114 ++NumKCFIChecks;
115 }
Expand Atomic instructions
This file contains the declarations for the subclasses of Constant, which represent the different fla...
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
Module.h This file contains the declarations for the Module class.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
Definition: Statistic.h:167
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:253
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Definition: InstrTypes.h:1236
static 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.
This is the base abstract class for diagnostic reporting in the backend.
virtual void print(DiagnosticPrinter &DP) const =0
Print using the given DP a user-friendly message.
Interface for custom diagnostic printing.
Value * CreateIntToPtr(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2127
Value * CreateConstInBoundsGEP1_32(Type *Ty, Value *Ptr, unsigned Idx0, const Twine &Name="")
Definition: IRBuilder.h:1894
Value * CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:2250
LoadInst * CreateLoad(Type *Ty, Value *Ptr, const char *Name)
Provided to resolve 'CreateLoad(Ty, Ptr, "...")' correctly, instead of converting the string to 'bool...
Definition: IRBuilder.h:1795
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1480
Value * CreatePtrToInt(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2122
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition: IRBuilder.h:177
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value * > Args=std::nullopt, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:2417
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:2671
Class to represent integer types.
Definition: DerivedTypes.h:40
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Definition: KCFI.cpp:48
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:67
void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
MDNode * createUnlikelyBranchWeights()
Return metadata containing two branch weights, with significant bias towards false destination.
Definition: MDBuilder.cpp:47
Metadata node.
Definition: Metadata.h:1067
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
A set of analyses that are preserved following a run of a transformation pass.
Definition: Analysis.h:111
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition: Analysis.h:114
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: Analysis.h:117
bool empty() const
Definition: SmallVector.h:94
void push_back(const T &Elt)
Definition: SmallVector.h:426
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
static IntegerType * getInt32Ty(LLVMContext &C)
LLVM Value Representation.
Definition: Value.h:74
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
Function * getDeclaration(Module *M, ID id, ArrayRef< Type * > Tys=std::nullopt)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
Definition: Function.cpp:1513
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
@ DK_Linker
Defines the different supported severity of a diagnostic.
@ DS_Error
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 ...