blob: 59ace3f19fc6b538babc394620c520a342e2652f [file] [log] [blame]
Chandler Carruthc58f2162018-01-22 22:05:25 +00001//======- X86RetpolineThunks.cpp - Construct retpoline thunks for x86 --=====//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9/// \file
10///
11/// Pass that injects an MI thunk implementing a "retpoline". This is
12/// a RET-implemented trampoline that is used to lower indirect calls in a way
13/// that prevents speculation on some x86 processors and can be used to mitigate
14/// security vulnerabilities due to targeted speculative execution and side
15/// channels such as CVE-2017-5715.
16///
17/// TODO(chandlerc): All of this code could use better comments and
18/// documentation.
19///
20//===----------------------------------------------------------------------===//
21
22#include "X86.h"
23#include "X86InstrBuilder.h"
24#include "X86Subtarget.h"
25#include "llvm/CodeGen/MachineFunction.h"
26#include "llvm/CodeGen/MachineInstrBuilder.h"
27#include "llvm/CodeGen/MachineModuleInfo.h"
28#include "llvm/CodeGen/Passes.h"
29#include "llvm/CodeGen/TargetPassConfig.h"
30#include "llvm/IR/IRBuilder.h"
31#include "llvm/IR/Instructions.h"
32#include "llvm/IR/Module.h"
33#include "llvm/Support/CommandLine.h"
34#include "llvm/Support/Debug.h"
35#include "llvm/Support/raw_ostream.h"
36
37using namespace llvm;
38
39#define DEBUG_TYPE "x86-retpoline-thunks"
40
Chandler Carruth0dcee4f2018-01-31 20:56:37 +000041static const char ThunkNamePrefix[] = "__llvm_retpoline_";
42static const char R11ThunkName[] = "__llvm_retpoline_r11";
43static const char EAXThunkName[] = "__llvm_retpoline_eax";
44static const char ECXThunkName[] = "__llvm_retpoline_ecx";
45static const char EDXThunkName[] = "__llvm_retpoline_edx";
Reid Kleckner91e11a82018-02-13 20:47:49 +000046static const char EDIThunkName[] = "__llvm_retpoline_edi";
Chandler Carruth0dcee4f2018-01-31 20:56:37 +000047
Chandler Carruthc58f2162018-01-22 22:05:25 +000048namespace {
Chandler Carruth0dcee4f2018-01-31 20:56:37 +000049class X86RetpolineThunks : public MachineFunctionPass {
Chandler Carruthc58f2162018-01-22 22:05:25 +000050public:
51 static char ID;
52
Chandler Carruth0dcee4f2018-01-31 20:56:37 +000053 X86RetpolineThunks() : MachineFunctionPass(ID) {}
Chandler Carruthc58f2162018-01-22 22:05:25 +000054
55 StringRef getPassName() const override { return "X86 Retpoline Thunks"; }
56
Chandler Carruth0dcee4f2018-01-31 20:56:37 +000057 bool doInitialization(Module &M) override;
58 bool runOnMachineFunction(MachineFunction &F) override;
Chandler Carruthc58f2162018-01-22 22:05:25 +000059
60 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth0dcee4f2018-01-31 20:56:37 +000061 MachineFunctionPass::getAnalysisUsage(AU);
Chandler Carruthc58f2162018-01-22 22:05:25 +000062 AU.addRequired<MachineModuleInfo>();
63 AU.addPreserved<MachineModuleInfo>();
64 }
65
66private:
67 MachineModuleInfo *MMI;
68 const TargetMachine *TM;
69 bool Is64Bit;
70 const X86Subtarget *STI;
71 const X86InstrInfo *TII;
72
Chandler Carruth0dcee4f2018-01-31 20:56:37 +000073 bool InsertedThunks;
74
75 void createThunkFunction(Module &M, StringRef Name);
Chandler Carruthc58f2162018-01-22 22:05:25 +000076 void insertRegReturnAddrClobber(MachineBasicBlock &MBB, unsigned Reg);
77 void insert32BitPushReturnAddrClobber(MachineBasicBlock &MBB);
Chandler Carruth0dcee4f2018-01-31 20:56:37 +000078 void populateThunk(MachineFunction &MF, Optional<unsigned> Reg = None);
Chandler Carruthc58f2162018-01-22 22:05:25 +000079};
80
81} // end anonymous namespace
82
Chandler Carruth0dcee4f2018-01-31 20:56:37 +000083FunctionPass *llvm::createX86RetpolineThunksPass() {
Chandler Carruthc58f2162018-01-22 22:05:25 +000084 return new X86RetpolineThunks();
85}
86
87char X86RetpolineThunks::ID = 0;
88
Chandler Carruth0dcee4f2018-01-31 20:56:37 +000089bool X86RetpolineThunks::doInitialization(Module &M) {
90 InsertedThunks = false;
91 return false;
92}
93
94bool X86RetpolineThunks::runOnMachineFunction(MachineFunction &MF) {
Chandler Carruthc58f2162018-01-22 22:05:25 +000095 DEBUG(dbgs() << getPassName() << '\n');
96
Chandler Carruth0dcee4f2018-01-31 20:56:37 +000097 TM = &MF.getTarget();;
98 STI = &MF.getSubtarget<X86Subtarget>();
99 TII = STI->getInstrInfo();
Chandler Carruthc58f2162018-01-22 22:05:25 +0000100 Is64Bit = TM->getTargetTriple().getArch() == Triple::x86_64;
101
Chandler Carruth0dcee4f2018-01-31 20:56:37 +0000102 MMI = &getAnalysis<MachineModuleInfo>();
103 Module &M = const_cast<Module &>(*MMI->getModule());
Chandler Carruthc58f2162018-01-22 22:05:25 +0000104
Chandler Carruth0dcee4f2018-01-31 20:56:37 +0000105 // If this function is not a thunk, check to see if we need to insert
106 // a thunk.
107 if (!MF.getName().startswith(ThunkNamePrefix)) {
108 // If we've already inserted a thunk, nothing else to do.
109 if (InsertedThunks)
110 return false;
Chandler Carruthc58f2162018-01-22 22:05:25 +0000111
Chandler Carruth0dcee4f2018-01-31 20:56:37 +0000112 // Only add a thunk if one of the functions has the retpoline feature
113 // enabled in its subtarget, and doesn't enable external thunks.
114 // FIXME: Conditionalize on indirect calls so we don't emit a thunk when
115 // nothing will end up calling it.
116 // FIXME: It's a little silly to look at every function just to enumerate
117 // the subtargets, but eventually we'll want to look at them for indirect
118 // calls, so maybe this is OK.
119 if (!STI->useRetpoline() || STI->useRetpolineExternalThunk())
120 return false;
121
122 // Otherwise, we need to insert the thunk.
123 // WARNING: This is not really a well behaving thing to do in a function
124 // pass. We extract the module and insert a new function (and machine
125 // function) directly into the module.
126 if (Is64Bit)
127 createThunkFunction(M, R11ThunkName);
128 else
129 for (StringRef Name :
Reid Kleckner91e11a82018-02-13 20:47:49 +0000130 {EAXThunkName, ECXThunkName, EDXThunkName, EDIThunkName})
Chandler Carruth0dcee4f2018-01-31 20:56:37 +0000131 createThunkFunction(M, Name);
132 InsertedThunks = true;
133 return true;
134 }
135
136 // If this *is* a thunk function, we need to populate it with the correct MI.
Chandler Carruthc58f2162018-01-22 22:05:25 +0000137 if (Is64Bit) {
Chandler Carruth0dcee4f2018-01-31 20:56:37 +0000138 assert(MF.getName() == "__llvm_retpoline_r11" &&
139 "Should only have an r11 thunk on 64-bit targets");
140
Chandler Carruthc58f2162018-01-22 22:05:25 +0000141 // __llvm_retpoline_r11:
142 // callq .Lr11_call_target
143 // .Lr11_capture_spec:
144 // pause
145 // lfence
146 // jmp .Lr11_capture_spec
147 // .align 16
148 // .Lr11_call_target:
149 // movq %r11, (%rsp)
150 // retq
Chandler Carruth0dcee4f2018-01-31 20:56:37 +0000151 populateThunk(MF, X86::R11);
Chandler Carruthc58f2162018-01-22 22:05:25 +0000152 } else {
153 // For 32-bit targets we need to emit a collection of thunks for various
Reid Kleckner91e11a82018-02-13 20:47:49 +0000154 // possible scratch registers as well as a fallback that uses EDI, which is
155 // normally callee saved.
Chandler Carruthc58f2162018-01-22 22:05:25 +0000156 // __llvm_retpoline_eax:
157 // calll .Leax_call_target
158 // .Leax_capture_spec:
159 // pause
160 // jmp .Leax_capture_spec
161 // .align 16
162 // .Leax_call_target:
163 // movl %eax, (%esp) # Clobber return addr
164 // retl
165 //
166 // __llvm_retpoline_ecx:
167 // ... # Same setup
168 // movl %ecx, (%esp)
169 // retl
170 //
171 // __llvm_retpoline_edx:
172 // ... # Same setup
173 // movl %edx, (%esp)
174 // retl
175 //
Reid Kleckner91e11a82018-02-13 20:47:49 +0000176 // __llvm_retpoline_edi:
177 // ... # Same setup
178 // movl %edi, (%esp)
179 // retl
Chandler Carruth0dcee4f2018-01-31 20:56:37 +0000180 if (MF.getName() == EAXThunkName)
181 populateThunk(MF, X86::EAX);
182 else if (MF.getName() == ECXThunkName)
183 populateThunk(MF, X86::ECX);
184 else if (MF.getName() == EDXThunkName)
185 populateThunk(MF, X86::EDX);
Reid Kleckner91e11a82018-02-13 20:47:49 +0000186 else if (MF.getName() == EDIThunkName)
187 populateThunk(MF, X86::EDI);
Chandler Carruth0dcee4f2018-01-31 20:56:37 +0000188 else
189 llvm_unreachable("Invalid thunk name on x86-32!");
Chandler Carruthc58f2162018-01-22 22:05:25 +0000190 }
191
192 return true;
193}
194
Chandler Carruth0dcee4f2018-01-31 20:56:37 +0000195void X86RetpolineThunks::createThunkFunction(Module &M, StringRef Name) {
196 assert(Name.startswith(ThunkNamePrefix) &&
197 "Created a thunk with an unexpected prefix!");
198
Chandler Carruthc58f2162018-01-22 22:05:25 +0000199 LLVMContext &Ctx = M.getContext();
200 auto Type = FunctionType::get(Type::getVoidTy(Ctx), false);
201 Function *F =
202 Function::Create(Type, GlobalValue::LinkOnceODRLinkage, Name, &M);
203 F->setVisibility(GlobalValue::HiddenVisibility);
204 F->setComdat(M.getOrInsertComdat(Name));
205
206 // Add Attributes so that we don't create a frame, unwind information, or
207 // inline.
208 AttrBuilder B;
209 B.addAttribute(llvm::Attribute::NoUnwind);
210 B.addAttribute(llvm::Attribute::Naked);
211 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
212
213 // Populate our function a bit so that we can verify.
214 BasicBlock *Entry = BasicBlock::Create(Ctx, "entry", F);
215 IRBuilder<> Builder(Entry);
216
217 Builder.CreateRetVoid();
Chandler Carruthc58f2162018-01-22 22:05:25 +0000218}
219
220void X86RetpolineThunks::insertRegReturnAddrClobber(MachineBasicBlock &MBB,
221 unsigned Reg) {
222 const unsigned MovOpc = Is64Bit ? X86::MOV64mr : X86::MOV32mr;
223 const unsigned SPReg = Is64Bit ? X86::RSP : X86::ESP;
224 addRegOffset(BuildMI(&MBB, DebugLoc(), TII->get(MovOpc)), SPReg, false, 0)
225 .addReg(Reg);
226}
Chandler Carruth0dcee4f2018-01-31 20:56:37 +0000227
Chandler Carruthc58f2162018-01-22 22:05:25 +0000228void X86RetpolineThunks::insert32BitPushReturnAddrClobber(
229 MachineBasicBlock &MBB) {
230 // The instruction sequence we use to replace the return address without
231 // a scratch register is somewhat complicated:
232 // # Clear capture_spec from return address.
233 // addl $4, %esp
234 // # Top of stack words are: Callee, RA. Exchange Callee and RA.
235 // pushl 4(%esp) # Push callee
236 // pushl 4(%esp) # Push RA
237 // popl 8(%esp) # Pop RA to final RA
238 // popl (%esp) # Pop callee to next top of stack
239 // retl # Ret to callee
240 BuildMI(&MBB, DebugLoc(), TII->get(X86::ADD32ri), X86::ESP)
241 .addReg(X86::ESP)
242 .addImm(4);
243 addRegOffset(BuildMI(&MBB, DebugLoc(), TII->get(X86::PUSH32rmm)), X86::ESP,
244 false, 4);
245 addRegOffset(BuildMI(&MBB, DebugLoc(), TII->get(X86::PUSH32rmm)), X86::ESP,
246 false, 4);
247 addRegOffset(BuildMI(&MBB, DebugLoc(), TII->get(X86::POP32rmm)), X86::ESP,
248 false, 8);
249 addRegOffset(BuildMI(&MBB, DebugLoc(), TII->get(X86::POP32rmm)), X86::ESP,
250 false, 0);
251}
252
Chandler Carruth0dcee4f2018-01-31 20:56:37 +0000253void X86RetpolineThunks::populateThunk(MachineFunction &MF,
254 Optional<unsigned> Reg) {
Chandler Carruthc58f2162018-01-22 22:05:25 +0000255 // Set MF properties. We never use vregs...
256 MF.getProperties().set(MachineFunctionProperties::Property::NoVRegs);
257
Chandler Carruth0dcee4f2018-01-31 20:56:37 +0000258 MachineBasicBlock *Entry = &MF.front();
259 Entry->clear();
Chandler Carruthc58f2162018-01-22 22:05:25 +0000260
Chandler Carruth0dcee4f2018-01-31 20:56:37 +0000261 MachineBasicBlock *CaptureSpec = MF.CreateMachineBasicBlock(Entry->getBasicBlock());
262 MachineBasicBlock *CallTarget = MF.CreateMachineBasicBlock(Entry->getBasicBlock());
Chandler Carruthc58f2162018-01-22 22:05:25 +0000263 MF.push_back(CaptureSpec);
264 MF.push_back(CallTarget);
265
266 const unsigned CallOpc = Is64Bit ? X86::CALL64pcrel32 : X86::CALLpcrel32;
267 const unsigned RetOpc = Is64Bit ? X86::RETQ : X86::RETL;
268
269 BuildMI(Entry, DebugLoc(), TII->get(CallOpc)).addMBB(CallTarget);
270 Entry->addSuccessor(CallTarget);
271 Entry->addSuccessor(CaptureSpec);
272 CallTarget->setHasAddressTaken();
273
274 // In the capture loop for speculation, we want to stop the processor from
275 // speculating as fast as possible. On Intel processors, the PAUSE instruction
276 // will block speculation without consuming any execution resources. On AMD
277 // processors, the PAUSE instruction is (essentially) a nop, so we also use an
278 // LFENCE instruction which they have advised will stop speculation as well
279 // with minimal resource utilization. We still end the capture with a jump to
280 // form an infinite loop to fully guarantee that no matter what implementation
281 // of the x86 ISA, speculating this code path never escapes.
282 BuildMI(CaptureSpec, DebugLoc(), TII->get(X86::PAUSE));
283 BuildMI(CaptureSpec, DebugLoc(), TII->get(X86::LFENCE));
284 BuildMI(CaptureSpec, DebugLoc(), TII->get(X86::JMP_1)).addMBB(CaptureSpec);
285 CaptureSpec->setHasAddressTaken();
286 CaptureSpec->addSuccessor(CaptureSpec);
287
288 CallTarget->setAlignment(4);
Reid Kleckner91e11a82018-02-13 20:47:49 +0000289 insertRegReturnAddrClobber(*CallTarget, *Reg);
Chandler Carruthc58f2162018-01-22 22:05:25 +0000290 BuildMI(CallTarget, DebugLoc(), TII->get(RetOpc));
291}