LLVM 23.0.0git
X86LoadValueInjectionRetHardening.cpp
Go to the documentation of this file.
1//===-- X86LoadValueInjectionRetHardening.cpp - LVI RET hardening for x86 --==//
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/// Description: Replaces every `ret` instruction with the sequence:
10/// ```
11/// pop <scratch-reg>
12/// lfence
13/// jmp *<scratch-reg>
14/// ```
15/// where `<scratch-reg>` is some available scratch register, according to the
16/// calling convention of the function being mitigated.
17///
18//===----------------------------------------------------------------------===//
19
20#include "X86.h"
21#include "X86InstrBuilder.h"
22#include "X86Subtarget.h"
23#include "llvm/ADT/Statistic.h"
28#include "llvm/IR/Function.h"
29#include "llvm/Support/Debug.h"
30
31using namespace llvm;
32
33#define PASS_KEY "x86-lvi-ret"
34#define DEBUG_TYPE PASS_KEY
35
36STATISTIC(NumFences, "Number of LFENCEs inserted for LVI mitigation");
37STATISTIC(NumFunctionsConsidered, "Number of functions analyzed");
38STATISTIC(NumFunctionsMitigated, "Number of functions for which mitigations "
39 "were deployed");
40
41namespace {
42
43constexpr StringRef X86LVIRetPassName =
44 "X86 Load Value Injection (LVI) Ret-Hardening";
45
46class X86LoadValueInjectionRetHardeningLegacy : public MachineFunctionPass {
47public:
48 X86LoadValueInjectionRetHardeningLegacy() : MachineFunctionPass(ID) {}
49 StringRef getPassName() const override { return X86LVIRetPassName; }
50 bool runOnMachineFunction(MachineFunction &MF) override;
51
52 static char ID;
53};
54
55} // end anonymous namespace
56
57char X86LoadValueInjectionRetHardeningLegacy::ID = 0;
58
60 const X86Subtarget *Subtarget = &MF.getSubtarget<X86Subtarget>();
61 if (!Subtarget->useLVIControlFlowIntegrity() || !Subtarget->is64Bit())
62 return false; // FIXME: support 32-bit
63
64 LLVM_DEBUG(dbgs() << "***** " << X86LVIRetPassName << " : " << MF.getName()
65 << " *****\n");
66 ++NumFunctionsConsidered;
67 const X86RegisterInfo *TRI = Subtarget->getRegisterInfo();
68 const X86InstrInfo *TII = Subtarget->getInstrInfo();
69
70 bool Modified = false;
71 for (auto &MBB : MF) {
72 for (auto MBBI = MBB.begin(); MBBI != MBB.end(); ++MBBI) {
73 if (MBBI->getOpcode() != X86::RET64)
74 continue;
75
76 unsigned ClobberReg = TRI->findDeadCallerSavedReg(MBB, MBBI);
77 if (ClobberReg != X86::NoRegister) {
78 BuildMI(MBB, MBBI, DebugLoc(), TII->get(X86::POP64r))
79 .addReg(ClobberReg, RegState::Define)
81 BuildMI(MBB, MBBI, DebugLoc(), TII->get(X86::LFENCE));
82 BuildMI(MBB, MBBI, DebugLoc(), TII->get(X86::JMP64r))
83 .addReg(ClobberReg);
84 MBB.erase(MBBI);
85 } else {
86 // In case there is no available scratch register, we can still read
87 // from RSP to assert that RSP points to a valid page. The write to RSP
88 // is also helpful because it verifies that the stack's write
89 // permissions are intact.
90 MachineInstr *Fence =
91 BuildMI(MBB, MBBI, DebugLoc(), TII->get(X86::LFENCE));
92 addRegOffset(BuildMI(MBB, Fence, DebugLoc(), TII->get(X86::SHL64mi)),
93 X86::RSP, false, 0)
94 .addImm(0)
95 ->addRegisterDead(X86::EFLAGS, TRI);
96 }
97
98 ++NumFences;
99 Modified = true;
100 break;
101 }
102 }
103
104 if (Modified)
105 ++NumFunctionsMitigated;
106 return Modified;
107}
108
109bool X86LoadValueInjectionRetHardeningLegacy::runOnMachineFunction(
110 MachineFunction &MF) {
111 // Don't skip functions with the "optnone" attr but participate in opt-bisect.
112 // Note: NewPM implements this behavior by default.
113 const Function &F = MF.getFunction();
114 if (!F.hasOptNone() && skipFunction(F))
115 return false;
116
118}
119
127
128INITIALIZE_PASS(X86LoadValueInjectionRetHardeningLegacy, PASS_KEY,
129 "X86 LVI ret hardener", false, false)
130
132 return new X86LoadValueInjectionRetHardeningLegacy();
133}
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator MBBI
const HexagonInstrInfo * TII
#define F(x, y, z)
Definition MD5.cpp:54
Register const TargetRegisterInfo * TRI
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
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
#define LLVM_DEBUG(...)
Definition Debug.h:114
#define PASS_KEY
static bool runX86LoadValueInjectionRetHardening(MachineFunction &MF)
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
Function & getFunction()
Return the LLVM function that this machine code represents.
const MachineInstrBuilder & setMIFlag(MachineInstr::MIFlag Flag) const
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & addReg(Register RegNo, unsigned Flags=0, unsigned SubReg=0) const
Add a new virtual register operand.
Representation of each machine instruction.
LLVM_ABI bool addRegisterDead(Register Reg, const TargetRegisterInfo *RegInfo, bool AddIfNotFound=false)
We have determined MI defined a register without a use.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:151
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
const X86InstrInfo * getInstrInfo() const override
const X86RegisterInfo * getRegisterInfo() const override
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ Define
Register definition.
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
FunctionPass * createX86LoadValueInjectionRetHardeningLegacyPass()
static const MachineInstrBuilder & addRegOffset(const MachineInstrBuilder &MIB, Register Reg, bool isKill, int Offset)
addRegOffset - This function is used to add a memory reference of the form [Reg + Offset],...