Skip to content

Commit 5b519cf

Browse files
scottconstabletopperc
authored andcommitted
[X86] Add Indirect Thunk Support to X86 to mitigate Load Value Injection (LVI)
This pass replaces each indirect call/jump with a direct call to a thunk that looks like: lfence jmpq *%r11 This ensures that if the value in register %r11 was loaded from memory, then the value in %r11 is (architecturally) correct prior to the jump. Also adds a new target feature to X86: +lvi-cfi ("cfi" meaning control-flow integrity) The feature can be added via clang CLI using -mlvi-cfi. This is an alternate implementation to https://reviews.llvm.org/D75934 That merges the thunk insertion functionality with the existing X86 retpoline code. Differential Revision: https://reviews.llvm.org/D76812
1 parent 0a3845b commit 5b519cf

File tree

9 files changed

+379
-8
lines changed

9 files changed

+379
-8
lines changed

clang/docs/ClangCommandLineReference.rst

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2625,6 +2625,10 @@ Use Intel MCU ABI
26252625

26262626
Generate branches with extended addressability, usually via indirect jumps.
26272627

2628+
.. option:: -mlvi-cfi, -mno-lvi-cfi
2629+
2630+
Enable only control-flow mitigations for Load Value Injection (LVI)
2631+
26282632
.. option:: -mmacosx-version-min=<arg>, -mmacos-version-min=<arg>
26292633

26302634
Set Mac OS X deployment target

clang/include/clang/Driver/Options.td

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2309,6 +2309,10 @@ def mspeculative_load_hardening : Flag<["-"], "mspeculative-load-hardening">,
23092309
Group<m_Group>, Flags<[CoreOption,CC1Option]>;
23102310
def mno_speculative_load_hardening : Flag<["-"], "mno-speculative-load-hardening">,
23112311
Group<m_Group>, Flags<[CoreOption]>;
2312+
def mlvi_cfi : Flag<["-"], "mlvi-cfi">, Group<m_Group>, Flags<[CoreOption,DriverOption]>,
2313+
HelpText<"Enable only control-flow mitigations for Load Value Injection (LVI)">;
2314+
def mno_lvi_cfi : Flag<["-"], "mno-lvi-cfi">, Group<m_Group>, Flags<[CoreOption,DriverOption]>,
2315+
HelpText<"Disable control-flow mitigations for Load Value Injection (LVI)">;
23122316

23132317
def mrelax : Flag<["-"], "mrelax">, Group<m_riscv_Features_Group>,
23142318
HelpText<"Enable linker relaxation">;

clang/lib/Driver/ToolChains/Arch/X86.cpp

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -146,26 +146,43 @@ void x86::getX86TargetFeatures(const Driver &D, const llvm::Triple &Triple,
146146
// flags). This is a bit hacky but keeps existing usages working. We should
147147
// consider deprecating this and instead warn if the user requests external
148148
// retpoline thunks and *doesn't* request some form of retpolines.
149+
auto SpectreOpt = clang::driver::options::ID::OPT_INVALID;
149150
if (Args.hasArgNoClaim(options::OPT_mretpoline, options::OPT_mno_retpoline,
150151
options::OPT_mspeculative_load_hardening,
151152
options::OPT_mno_speculative_load_hardening)) {
152153
if (Args.hasFlag(options::OPT_mretpoline, options::OPT_mno_retpoline,
153154
false)) {
154155
Features.push_back("+retpoline-indirect-calls");
155156
Features.push_back("+retpoline-indirect-branches");
157+
SpectreOpt = options::OPT_mretpoline;
156158
} else if (Args.hasFlag(options::OPT_mspeculative_load_hardening,
157159
options::OPT_mno_speculative_load_hardening,
158160
false)) {
159161
// On x86, speculative load hardening relies on at least using retpolines
160162
// for indirect calls.
161163
Features.push_back("+retpoline-indirect-calls");
164+
SpectreOpt = options::OPT_mspeculative_load_hardening;
162165
}
163166
} else if (Args.hasFlag(options::OPT_mretpoline_external_thunk,
164167
options::OPT_mno_retpoline_external_thunk, false)) {
165168
// FIXME: Add a warning about failing to specify `-mretpoline` and
166169
// eventually switch to an error here.
167170
Features.push_back("+retpoline-indirect-calls");
168171
Features.push_back("+retpoline-indirect-branches");
172+
SpectreOpt = options::OPT_mretpoline_external_thunk;
173+
}
174+
175+
auto LVIOpt = clang::driver::options::ID::OPT_INVALID;
176+
if (Args.hasFlag(options::OPT_mlvi_cfi, options::OPT_mno_lvi_cfi, false)) {
177+
Features.push_back("+lvi-cfi");
178+
LVIOpt = options::OPT_mlvi_cfi;
179+
}
180+
181+
if (SpectreOpt != clang::driver::options::ID::OPT_INVALID &&
182+
LVIOpt != clang::driver::options::ID::OPT_INVALID) {
183+
D.Diag(diag::err_drv_argument_not_allowed_with)
184+
<< D.getOpts().getOptionName(SpectreOpt)
185+
<< D.getOpts().getOptionName(LVIOpt);
169186
}
170187

171188
// Now add any that the user explicitly requested on the command line,

clang/test/Driver/x86-target-features.c

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,11 @@
154154
// SLH: "-mspeculative-load-hardening"
155155
// NO-SLH-NOT: retpoline
156156

157+
// RUN: %clang -target i386-linux-gnu -mlvi-cfi %s -### -o %t.o 2>&1 | FileCheck -check-prefix=LVICFI %s
158+
// RUN: %clang -target i386-linux-gnu -mno-lvi-cfi %s -### -o %t.o 2>&1 | FileCheck -check-prefix=NO-LVICFI %s
159+
// LVICFI: "-target-feature" "+lvi-cfi"
160+
// NO-LVICFI-NOT: lvi-cfi
161+
157162
// RUN: %clang -target i386-linux-gnu -mwaitpkg %s -### -o %t.o 2>&1 | FileCheck -check-prefix=WAITPKG %s
158163
// RUN: %clang -target i386-linux-gnu -mno-waitpkg %s -### -o %t.o 2>&1 | FileCheck -check-prefix=NO-WAITPKG %s
159164
// WAITPKG: "-target-feature" "+waitpkg"

llvm/lib/Target/X86/X86.td

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -433,6 +433,15 @@ def FeatureRetpolineExternalThunk
433433
"ourselves. Only has effect when combined with some other retpoline "
434434
"feature", [FeatureRetpolineIndirectCalls]>;
435435

436+
// Mitigate LVI attacks against indirect calls/branches and call returns
437+
def FeatureLVIControlFlowIntegrity
438+
: SubtargetFeature<
439+
"lvi-cfi", "UseLVIControlFlowIntegrity", "true",
440+
"Prevent indirect calls/branches from using a memory operand, and "
441+
"precede all indirect calls/branches from a register with an "
442+
"LFENCE instruction to serialize control flow. Also decompose RET "
443+
"instructions into a POP+LFENCE+JMP sequence.">;
444+
436445
// Direct Move instructions.
437446
def FeatureMOVDIRI : SubtargetFeature<"movdiri", "HasMOVDIRI", "true",
438447
"Support movdiri instruction">;

llvm/lib/Target/X86/X86ISelLowering.cpp

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31972,6 +31972,11 @@ static const char *getIndirectThunkSymbol(const X86Subtarget &Subtarget,
3197231972
}
3197331973
llvm_unreachable("unexpected reg for retpoline");
3197431974
}
31975+
31976+
if (Subtarget.useLVIControlFlowIntegrity()) {
31977+
assert(Subtarget.is64Bit() && "Should not be using a 64-bit thunk!");
31978+
return "__llvm_lvi_thunk_r11";
31979+
}
3197531980
llvm_unreachable("getIndirectThunkSymbol() invoked without thunk feature");
3197631981
}
3197731982

llvm/lib/Target/X86/X86IndirectThunks.cpp

Lines changed: 43 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@
1414
///
1515
/// Currently supported thunks include:
1616
/// - Retpoline -- A RET-implemented trampoline that lowers indirect calls
17+
/// - LVI Thunk -- A CALL/JMP-implemented thunk that forces load serialization
18+
/// before making an indirect call/jump
1719
///
1820
/// Note that the reason that this is implemented as a MachineFunctionPass and
1921
/// not a ModulePass is that ModulePasses at this point in the LLVM X86 pipeline
@@ -44,11 +46,14 @@ using namespace llvm;
4446
#define DEBUG_TYPE "x86-retpoline-thunks"
4547

4648
static const char RetpolineNamePrefix[] = "__llvm_retpoline_";
47-
static const char R11RetpolineName[] = "__llvm_retpoline_r11";
48-
static const char EAXRetpolineName[] = "__llvm_retpoline_eax";
49-
static const char ECXRetpolineName[] = "__llvm_retpoline_ecx";
50-
static const char EDXRetpolineName[] = "__llvm_retpoline_edx";
51-
static const char EDIRetpolineName[] = "__llvm_retpoline_edi";
49+
static const char R11RetpolineName[] = "__llvm_retpoline_r11";
50+
static const char EAXRetpolineName[] = "__llvm_retpoline_eax";
51+
static const char ECXRetpolineName[] = "__llvm_retpoline_ecx";
52+
static const char EDXRetpolineName[] = "__llvm_retpoline_edx";
53+
static const char EDIRetpolineName[] = "__llvm_retpoline_edi";
54+
55+
static const char LVIThunkNamePrefix[] = "__llvm_lvi_thunk_";
56+
static const char R11LVIThunkName[] = "__llvm_lvi_thunk_r11";
5257

5358
namespace {
5459
template <typename Derived> class ThunkInserter {
@@ -80,6 +85,38 @@ struct RetpolineThunkInserter : ThunkInserter<RetpolineThunkInserter> {
8085
void populateThunk(MachineFunction &MF);
8186
};
8287

88+
struct LVIThunkInserter : ThunkInserter<LVIThunkInserter> {
89+
const char *getThunkPrefix() { return LVIThunkNamePrefix; }
90+
bool mayUseThunk(const MachineFunction &MF) {
91+
return MF.getSubtarget<X86Subtarget>().useLVIControlFlowIntegrity();
92+
}
93+
void insertThunks(MachineModuleInfo &MMI) {
94+
createThunkFunction(MMI, R11LVIThunkName);
95+
}
96+
void populateThunk(MachineFunction &MF) {
97+
// Grab the entry MBB and erase any other blocks. O0 codegen appears to
98+
// generate two bbs for the entry block.
99+
MachineBasicBlock *Entry = &MF.front();
100+
Entry->clear();
101+
while (MF.size() > 1)
102+
MF.erase(std::next(MF.begin()));
103+
104+
// This code mitigates LVI by replacing each indirect call/jump with a
105+
// direct call/jump to a thunk that looks like:
106+
// ```
107+
// lfence
108+
// jmpq *%r11
109+
// ```
110+
// This ensures that if the value in register %r11 was loaded from memory,
111+
// then the value in %r11 is (architecturally) correct prior to the jump.
112+
const TargetInstrInfo *TII = MF.getSubtarget<X86Subtarget>().getInstrInfo();
113+
BuildMI(&MF.front(), DebugLoc(), TII->get(X86::LFENCE));
114+
BuildMI(&MF.front(), DebugLoc(), TII->get(X86::JMP64r)).addReg(X86::R11);
115+
MF.front().addLiveIn(X86::R11);
116+
return;
117+
}
118+
};
119+
83120
class X86IndirectThunks : public MachineFunctionPass {
84121
public:
85122
static char ID;
@@ -98,7 +135,7 @@ class X86IndirectThunks : public MachineFunctionPass {
98135
}
99136

100137
private:
101-
std::tuple<RetpolineThunkInserter> TIs;
138+
std::tuple<RetpolineThunkInserter, LVIThunkInserter> TIs;
102139

103140
// FIXME: When LLVM moves to C++17, these can become folds
104141
template <typename... ThunkInserterT>

llvm/lib/Target/X86/X86Subtarget.h

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -428,6 +428,12 @@ class X86Subtarget final : public X86GenSubtargetInfo {
428428
/// than emitting one inside the compiler.
429429
bool UseRetpolineExternalThunk = false;
430430

431+
/// Prevent generation of indirect call/branch instructions from memory,
432+
/// and force all indirect call/branch instructions from a register to be
433+
/// preceded by an LFENCE. Also decompose RET instructions into a
434+
/// POP+LFENCE+JMP sequence.
435+
bool UseLVIControlFlowIntegrity = false;
436+
431437
/// Use software floating point for code generation.
432438
bool UseSoftFloat = false;
433439

@@ -719,13 +725,16 @@ class X86Subtarget final : public X86GenSubtargetInfo {
719725
// These are generic getters that OR together all of the thunk types
720726
// supported by the subtarget. Therefore useIndirectThunk*() will return true
721727
// if any respective thunk feature is enabled.
722-
bool useIndirectThunkCalls() const { return useRetpolineIndirectCalls(); }
728+
bool useIndirectThunkCalls() const {
729+
return useRetpolineIndirectCalls() || useLVIControlFlowIntegrity();
730+
}
723731
bool useIndirectThunkBranches() const {
724-
return useRetpolineIndirectBranches();
732+
return useRetpolineIndirectBranches() || useLVIControlFlowIntegrity();
725733
}
726734

727735
bool preferMaskRegisters() const { return PreferMaskRegisters; }
728736
bool useGLMDivSqrtCosts() const { return UseGLMDivSqrtCosts; }
737+
bool useLVIControlFlowIntegrity() const { return UseLVIControlFlowIntegrity; }
729738

730739
unsigned getPreferVectorWidth() const { return PreferVectorWidth; }
731740
unsigned getRequiredVectorWidth() const { return RequiredVectorWidth; }

0 commit comments

Comments
 (0)