1 //==- X86IndirectThunks.cpp - Construct indirect call/jump thunks 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 /// \file
9 ///
10 /// Pass that injects an MI thunk that is used to lower indirect calls in a way
11 /// that prevents speculation on some x86 processors and can be used to mitigate
12 /// security vulnerabilities due to targeted speculative execution and side
13 /// channels such as CVE-2017-5715.
14 ///
15 /// Currently supported thunks include:
16 /// - 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
19 ///
20 /// Note that the reason that this is implemented as a MachineFunctionPass and
21 /// not a ModulePass is that ModulePasses at this point in the LLVM X86 pipeline
22 /// serialize all transformations, which can consume lots of memory.
23 ///
24 /// TODO(chandlerc): All of this code could use better comments and
25 /// documentation.
26 ///
27 //===----------------------------------------------------------------------===//
28 
29 #include "X86.h"
30 #include "X86InstrBuilder.h"
31 #include "X86Subtarget.h"
32 #include "llvm/CodeGen/IndirectThunks.h"
33 #include "llvm/CodeGen/MachineFunction.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/CodeGen/MachineModuleInfo.h"
36 #include "llvm/CodeGen/Passes.h"
37 #include "llvm/CodeGen/TargetPassConfig.h"
38 #include "llvm/IR/IRBuilder.h"
39 #include "llvm/IR/Instructions.h"
40 #include "llvm/IR/Module.h"
41 #include "llvm/Support/CommandLine.h"
42 #include "llvm/Support/Debug.h"
43 #include "llvm/Support/raw_ostream.h"
44 #include "llvm/Target/TargetMachine.h"
45 
46 using namespace llvm;
47 
48 #define DEBUG_TYPE "x86-retpoline-thunks"
49 
50 static const char RetpolineNamePrefix[] = "__llvm_retpoline_";
51 static const char R11RetpolineName[] = "__llvm_retpoline_r11";
52 static const char EAXRetpolineName[] = "__llvm_retpoline_eax";
53 static const char ECXRetpolineName[] = "__llvm_retpoline_ecx";
54 static const char EDXRetpolineName[] = "__llvm_retpoline_edx";
55 static const char EDIRetpolineName[] = "__llvm_retpoline_edi";
56 
57 static const char LVIThunkNamePrefix[] = "__llvm_lvi_thunk_";
58 static const char R11LVIThunkName[] = "__llvm_lvi_thunk_r11";
59 
60 namespace {
61 struct RetpolineThunkInserter : ThunkInserter<RetpolineThunkInserter> {
62   const char *getThunkPrefix() { return RetpolineNamePrefix; }
63   bool mayUseThunk(const MachineFunction &MF) {
64     const auto &STI = MF.getSubtarget<X86Subtarget>();
65     return (STI.useRetpolineIndirectCalls() ||
66             STI.useRetpolineIndirectBranches()) &&
67            !STI.useRetpolineExternalThunk();
68   }
69   void insertThunks(MachineModuleInfo &MMI);
70   void populateThunk(MachineFunction &MF);
71 };
72 
73 struct LVIThunkInserter : ThunkInserter<LVIThunkInserter> {
74   const char *getThunkPrefix() { return LVIThunkNamePrefix; }
75   bool mayUseThunk(const MachineFunction &MF) {
76     return MF.getSubtarget<X86Subtarget>().useLVIControlFlowIntegrity();
77   }
78   void insertThunks(MachineModuleInfo &MMI) {
79     createThunkFunction(MMI, R11LVIThunkName);
80   }
81   void populateThunk(MachineFunction &MF) {
82     assert (MF.size() == 1);
83     MachineBasicBlock *Entry = &MF.front();
84     Entry->clear();
85 
86     // This code mitigates LVI by replacing each indirect call/jump with a
87     // direct call/jump to a thunk that looks like:
88     // ```
89     // lfence
90     // jmpq *%r11
91     // ```
92     // This ensures that if the value in register %r11 was loaded from memory,
93     // then the value in %r11 is (architecturally) correct prior to the jump.
94     const TargetInstrInfo *TII = MF.getSubtarget<X86Subtarget>().getInstrInfo();
95     BuildMI(&MF.front(), DebugLoc(), TII->get(X86::LFENCE));
96     BuildMI(&MF.front(), DebugLoc(), TII->get(X86::JMP64r)).addReg(X86::R11);
97     MF.front().addLiveIn(X86::R11);
98     return;
99   }
100 };
101 
102 class X86IndirectThunks : public MachineFunctionPass {
103 public:
104   static char ID;
105 
106   X86IndirectThunks() : MachineFunctionPass(ID) {}
107 
108   StringRef getPassName() const override { return "X86 Indirect Thunks"; }
109 
110   bool doInitialization(Module &M) override;
111   bool runOnMachineFunction(MachineFunction &MF) override;
112 
113   void getAnalysisUsage(AnalysisUsage &AU) const override {
114     MachineFunctionPass::getAnalysisUsage(AU);
115     AU.addRequired<MachineModuleInfoWrapperPass>();
116     AU.addPreserved<MachineModuleInfoWrapperPass>();
117   }
118 
119 private:
120   std::tuple<RetpolineThunkInserter, LVIThunkInserter> TIs;
121 
122   // FIXME: When LLVM moves to C++17, these can become folds
123   template <typename... ThunkInserterT>
124   static void initTIs(Module &M,
125                       std::tuple<ThunkInserterT...> &ThunkInserters) {
126     (void)std::initializer_list<int>{
127         (std::get<ThunkInserterT>(ThunkInserters).init(M), 0)...};
128   }
129   template <typename... ThunkInserterT>
130   static bool runTIs(MachineModuleInfo &MMI, MachineFunction &MF,
131                      std::tuple<ThunkInserterT...> &ThunkInserters) {
132     bool Modified = false;
133     (void)std::initializer_list<int>{
134         Modified |= std::get<ThunkInserterT>(ThunkInserters).run(MMI, MF)...};
135     return Modified;
136   }
137 };
138 
139 } // end anonymous namespace
140 
141 void RetpolineThunkInserter::insertThunks(MachineModuleInfo &MMI) {
142   if (MMI.getTarget().getTargetTriple().getArch() == Triple::x86_64)
143     createThunkFunction(MMI, R11RetpolineName);
144   else
145     for (StringRef Name : {EAXRetpolineName, ECXRetpolineName, EDXRetpolineName,
146                            EDIRetpolineName})
147       createThunkFunction(MMI, Name);
148 }
149 
150 void RetpolineThunkInserter::populateThunk(MachineFunction &MF) {
151   bool Is64Bit = MF.getTarget().getTargetTriple().getArch() == Triple::x86_64;
152   Register ThunkReg;
153   if (Is64Bit) {
154     assert(MF.getName() == "__llvm_retpoline_r11" &&
155            "Should only have an r11 thunk on 64-bit targets");
156 
157     // __llvm_retpoline_r11:
158     //   callq .Lr11_call_target
159     // .Lr11_capture_spec:
160     //   pause
161     //   lfence
162     //   jmp .Lr11_capture_spec
163     // .align 16
164     // .Lr11_call_target:
165     //   movq %r11, (%rsp)
166     //   retq
167     ThunkReg = X86::R11;
168   } else {
169     // For 32-bit targets we need to emit a collection of thunks for various
170     // possible scratch registers as well as a fallback that uses EDI, which is
171     // normally callee saved.
172     //   __llvm_retpoline_eax:
173     //         calll .Leax_call_target
174     //   .Leax_capture_spec:
175     //         pause
176     //         jmp .Leax_capture_spec
177     //   .align 16
178     //   .Leax_call_target:
179     //         movl %eax, (%esp)  # Clobber return addr
180     //         retl
181     //
182     //   __llvm_retpoline_ecx:
183     //   ... # Same setup
184     //         movl %ecx, (%esp)
185     //         retl
186     //
187     //   __llvm_retpoline_edx:
188     //   ... # Same setup
189     //         movl %edx, (%esp)
190     //         retl
191     //
192     //   __llvm_retpoline_edi:
193     //   ... # Same setup
194     //         movl %edi, (%esp)
195     //         retl
196     if (MF.getName() == EAXRetpolineName)
197       ThunkReg = X86::EAX;
198     else if (MF.getName() == ECXRetpolineName)
199       ThunkReg = X86::ECX;
200     else if (MF.getName() == EDXRetpolineName)
201       ThunkReg = X86::EDX;
202     else if (MF.getName() == EDIRetpolineName)
203       ThunkReg = X86::EDI;
204     else
205       llvm_unreachable("Invalid thunk name on x86-32!");
206   }
207 
208   const TargetInstrInfo *TII = MF.getSubtarget<X86Subtarget>().getInstrInfo();
209   assert (MF.size() == 1);
210   MachineBasicBlock *Entry = &MF.front();
211   Entry->clear();
212 
213   MachineBasicBlock *CaptureSpec =
214       MF.CreateMachineBasicBlock(Entry->getBasicBlock());
215   MachineBasicBlock *CallTarget =
216       MF.CreateMachineBasicBlock(Entry->getBasicBlock());
217   MCSymbol *TargetSym = MF.getContext().createTempSymbol();
218   MF.push_back(CaptureSpec);
219   MF.push_back(CallTarget);
220 
221   const unsigned CallOpc = Is64Bit ? X86::CALL64pcrel32 : X86::CALLpcrel32;
222   const unsigned RetOpc = Is64Bit ? X86::RETQ : X86::RETL;
223 
224   Entry->addLiveIn(ThunkReg);
225   BuildMI(Entry, DebugLoc(), TII->get(CallOpc)).addSym(TargetSym);
226 
227   // The MIR verifier thinks that the CALL in the entry block will fall through
228   // to CaptureSpec, so mark it as the successor. Technically, CaptureTarget is
229   // the successor, but the MIR verifier doesn't know how to cope with that.
230   Entry->addSuccessor(CaptureSpec);
231 
232   // In the capture loop for speculation, we want to stop the processor from
233   // speculating as fast as possible. On Intel processors, the PAUSE instruction
234   // will block speculation without consuming any execution resources. On AMD
235   // processors, the PAUSE instruction is (essentially) a nop, so we also use an
236   // LFENCE instruction which they have advised will stop speculation as well
237   // with minimal resource utilization. We still end the capture with a jump to
238   // form an infinite loop to fully guarantee that no matter what implementation
239   // of the x86 ISA, speculating this code path never escapes.
240   BuildMI(CaptureSpec, DebugLoc(), TII->get(X86::PAUSE));
241   BuildMI(CaptureSpec, DebugLoc(), TII->get(X86::LFENCE));
242   BuildMI(CaptureSpec, DebugLoc(), TII->get(X86::JMP_1)).addMBB(CaptureSpec);
243   CaptureSpec->setHasAddressTaken();
244   CaptureSpec->addSuccessor(CaptureSpec);
245 
246   CallTarget->addLiveIn(ThunkReg);
247   CallTarget->setHasAddressTaken();
248   CallTarget->setAlignment(Align(16));
249 
250   // Insert return address clobber
251   const unsigned MovOpc = Is64Bit ? X86::MOV64mr : X86::MOV32mr;
252   const Register SPReg = Is64Bit ? X86::RSP : X86::ESP;
253   addRegOffset(BuildMI(CallTarget, DebugLoc(), TII->get(MovOpc)), SPReg, false,
254                0)
255       .addReg(ThunkReg);
256 
257   CallTarget->back().setPreInstrSymbol(MF, TargetSym);
258   BuildMI(CallTarget, DebugLoc(), TII->get(RetOpc));
259 }
260 
261 FunctionPass *llvm::createX86IndirectThunksPass() {
262   return new X86IndirectThunks();
263 }
264 
265 char X86IndirectThunks::ID = 0;
266 
267 bool X86IndirectThunks::doInitialization(Module &M) {
268   initTIs(M, TIs);
269   return false;
270 }
271 
272 bool X86IndirectThunks::runOnMachineFunction(MachineFunction &MF) {
273   LLVM_DEBUG(dbgs() << getPassName() << '\n');
274   auto &MMI = getAnalysis<MachineModuleInfoWrapperPass>().getMMI();
275   return runTIs(MMI, MF, TIs);
276 }
277