1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
|
//===- bolt/Passes/RetpolineInsertion.cpp ---------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file implements RetpolineInsertion class, which replaces indirect
// branches (calls and jumps) with calls to retpolines to protect against branch
// target injection attacks.
// A unique retpoline is created for each register holding the address of the
// callee, if the callee address is in memory %r11 is used if available to
// hold the address of the callee before calling the retpoline, otherwise an
// address pattern specific retpoline is called where the callee address is
// loaded inside the retpoline.
// The user can determine when to assume %r11 available using r11-availability
// option, by default %r11 is assumed not available.
// Adding lfence instruction to the body of the speculate code is enabled by
// default and can be controlled by the user using retpoline-lfence option.
//
//===----------------------------------------------------------------------===//
#include "bolt/Passes/RetpolineInsertion.h"
#include "llvm/MC/MCInstPrinter.h"
#include "llvm/Support/raw_ostream.h"
#define DEBUG_TYPE "bolt-retpoline"
using namespace llvm;
using namespace bolt;
namespace opts {
extern cl::OptionCategory BoltCategory;
llvm::cl::opt<bool> InsertRetpolines("insert-retpolines",
cl::desc("run retpoline insertion pass"),
cl::cat(BoltCategory));
llvm::cl::opt<bool>
RetpolineLfence("retpoline-lfence",
cl::desc("determine if lfence instruction should exist in the retpoline"),
cl::init(true),
cl::ZeroOrMore,
cl::Hidden,
cl::cat(BoltCategory));
cl::opt<RetpolineInsertion::AvailabilityOptions> R11Availability(
"r11-availability",
cl::desc("determine the availability of r11 before indirect branches"),
cl::init(RetpolineInsertion::AvailabilityOptions::NEVER),
cl::values(clEnumValN(RetpolineInsertion::AvailabilityOptions::NEVER,
"never", "r11 not available"),
clEnumValN(RetpolineInsertion::AvailabilityOptions::ALWAYS,
"always", "r11 avaialable before calls and jumps"),
clEnumValN(RetpolineInsertion::AvailabilityOptions::ABI, "abi",
"r11 avaialable before calls but not before jumps")),
cl::ZeroOrMore, cl::cat(BoltCategory));
} // namespace opts
namespace llvm {
namespace bolt {
// Retpoline function structure:
// BB0: call BB2
// BB1: pause
// lfence
// jmp BB1
// BB2: mov %reg, (%rsp)
// ret
// or
// BB2: push %r11
// mov Address, %r11
// mov %r11, 8(%rsp)
// pop %r11
// ret
BinaryFunction *createNewRetpoline(BinaryContext &BC,
const std::string &RetpolineTag,
const IndirectBranchInfo &BrInfo,
bool R11Available) {
auto &MIB = *BC.MIB;
MCContext &Ctx = *BC.Ctx.get();
LLVM_DEBUG(dbgs() << "BOLT-DEBUG: Creating a new retpoline function["
<< RetpolineTag << "]\n");
BinaryFunction *NewRetpoline =
BC.createInjectedBinaryFunction(RetpolineTag, true);
std::vector<std::unique_ptr<BinaryBasicBlock>> NewBlocks(3);
for (int I = 0; I < 3; I++) {
MCSymbol *Symbol =
Ctx.createNamedTempSymbol(Twine(RetpolineTag + "_BB" + to_string(I)));
NewBlocks[I] = NewRetpoline->createBasicBlock(Symbol);
NewBlocks[I].get()->setCFIState(0);
}
BinaryBasicBlock &BB0 = *NewBlocks[0].get();
BinaryBasicBlock &BB1 = *NewBlocks[1].get();
BinaryBasicBlock &BB2 = *NewBlocks[2].get();
BB0.addSuccessor(&BB2, 0, 0);
BB1.addSuccessor(&BB1, 0, 0);
// Build BB0
MCInst DirectCall;
MIB.createDirectCall(DirectCall, BB2.getLabel(), &Ctx, /*IsTailCall*/ false);
BB0.addInstruction(DirectCall);
// Build BB1
MCInst Pause;
MIB.createPause(Pause);
BB1.addInstruction(Pause);
if (opts::RetpolineLfence) {
MCInst Lfence;
MIB.createLfence(Lfence);
BB1.addInstruction(Lfence);
}
InstructionListType Seq;
MIB.createShortJmp(Seq, BB1.getLabel(), &Ctx);
BB1.addInstructions(Seq.begin(), Seq.end());
// Build BB2
if (BrInfo.isMem()) {
if (R11Available) {
MCInst StoreToStack;
MIB.createSaveToStack(StoreToStack, MIB.getStackPointer(), 0,
MIB.getX86R11(), 8);
BB2.addInstruction(StoreToStack);
} else {
MCInst PushR11;
MIB.createPushRegister(PushR11, MIB.getX86R11(), 8);
BB2.addInstruction(PushR11);
MCInst LoadCalleeAddrs;
const IndirectBranchInfo::MemOpInfo &MemRef = BrInfo.Memory;
MIB.createLoad(LoadCalleeAddrs, MemRef.BaseRegNum, MemRef.ScaleImm,
MemRef.IndexRegNum, MemRef.DispImm, MemRef.DispExpr,
MemRef.SegRegNum, MIB.getX86R11(), 8);
BB2.addInstruction(LoadCalleeAddrs);
MCInst StoreToStack;
MIB.createSaveToStack(StoreToStack, MIB.getStackPointer(), 8,
MIB.getX86R11(), 8);
BB2.addInstruction(StoreToStack);
MCInst PopR11;
MIB.createPopRegister(PopR11, MIB.getX86R11(), 8);
BB2.addInstruction(PopR11);
}
} else if (BrInfo.isReg()) {
MCInst StoreToStack;
MIB.createSaveToStack(StoreToStack, MIB.getStackPointer(), 0,
BrInfo.BranchReg, 8);
BB2.addInstruction(StoreToStack);
} else {
llvm_unreachable("not expected");
}
// return
MCInst Return;
MIB.createReturn(Return);
BB2.addInstruction(Return);
NewRetpoline->insertBasicBlocks(nullptr, std::move(NewBlocks),
/* UpdateLayout */ true,
/* UpdateCFIState */ false);
NewRetpoline->updateState(BinaryFunction::State::CFG_Finalized);
return NewRetpoline;
}
std::string createRetpolineFunctionTag(BinaryContext &BC,
const IndirectBranchInfo &BrInfo,
bool R11Available) {
std::string Tag;
llvm::raw_string_ostream TagOS(Tag);
TagOS << "__retpoline_";
if (BrInfo.isReg()) {
BC.InstPrinter->printRegName(TagOS, BrInfo.BranchReg);
TagOS << "_";
TagOS.flush();
return Tag;
}
// Memory Branch
if (R11Available)
return "__retpoline_r11";
const IndirectBranchInfo::MemOpInfo &MemRef = BrInfo.Memory;
TagOS << "mem_";
if (MemRef.BaseRegNum != BC.MIB->getNoRegister())
BC.InstPrinter->printRegName(TagOS, MemRef.BaseRegNum);
TagOS << "+";
if (MemRef.DispExpr)
MemRef.DispExpr->print(TagOS, BC.AsmInfo.get());
else
TagOS << MemRef.DispImm;
if (MemRef.IndexRegNum != BC.MIB->getNoRegister()) {
TagOS << "+" << MemRef.ScaleImm << "*";
BC.InstPrinter->printRegName(TagOS, MemRef.IndexRegNum);
}
if (MemRef.SegRegNum != BC.MIB->getNoRegister()) {
TagOS << "_seg_";
BC.InstPrinter->printRegName(TagOS, MemRef.SegRegNum);
}
TagOS.flush();
return Tag;
}
BinaryFunction *RetpolineInsertion::getOrCreateRetpoline(
BinaryContext &BC, const IndirectBranchInfo &BrInfo, bool R11Available) {
const std::string RetpolineTag =
createRetpolineFunctionTag(BC, BrInfo, R11Available);
if (CreatedRetpolines.count(RetpolineTag))
return CreatedRetpolines[RetpolineTag];
return CreatedRetpolines[RetpolineTag] =
createNewRetpoline(BC, RetpolineTag, BrInfo, R11Available);
}
void createBranchReplacement(BinaryContext &BC,
const IndirectBranchInfo &BrInfo,
bool R11Available,
InstructionListType &Replacement,
const MCSymbol *RetpolineSymbol) {
auto &MIB = *BC.MIB;
// Load the branch address in r11 if available
if (BrInfo.isMem() && R11Available) {
const IndirectBranchInfo::MemOpInfo &MemRef = BrInfo.Memory;
MCInst LoadCalleeAddrs;
MIB.createLoad(LoadCalleeAddrs, MemRef.BaseRegNum, MemRef.ScaleImm,
MemRef.IndexRegNum, MemRef.DispImm, MemRef.DispExpr,
MemRef.SegRegNum, MIB.getX86R11(), 8);
Replacement.push_back(LoadCalleeAddrs);
}
// Call the retpoline
MCInst RetpolineCall;
MIB.createDirectCall(RetpolineCall, RetpolineSymbol, BC.Ctx.get(),
BrInfo.isJump() || BrInfo.isTailCall());
Replacement.push_back(RetpolineCall);
}
IndirectBranchInfo::IndirectBranchInfo(MCInst &Inst, MCPlusBuilder &MIB) {
IsCall = MIB.isCall(Inst);
IsTailCall = MIB.isTailCall(Inst);
if (MIB.isBranchOnMem(Inst)) {
IsMem = true;
std::optional<MCPlusBuilder::X86MemOperand> MO =
MIB.evaluateX86MemoryOperand(Inst);
if (!MO)
llvm_unreachable("not expected");
Memory = MO.value();
} else if (MIB.isBranchOnReg(Inst)) {
assert(MCPlus::getNumPrimeOperands(Inst) == 1 && "expect 1 operand");
BranchReg = Inst.getOperand(0).getReg();
} else {
llvm_unreachable("unexpected instruction");
}
}
void RetpolineInsertion::runOnFunctions(BinaryContext &BC) {
if (!opts::InsertRetpolines)
return;
assert(BC.isX86() &&
"retpoline insertion not supported for target architecture");
assert(BC.HasRelocations && "retpoline mode not supported in non-reloc");
auto &MIB = *BC.MIB;
uint32_t RetpolinedBranches = 0;
for (auto &It : BC.getBinaryFunctions()) {
BinaryFunction &Function = It.second;
for (BinaryBasicBlock &BB : Function) {
for (auto It = BB.begin(); It != BB.end(); ++It) {
MCInst &Inst = *It;
if (!MIB.isIndirectCall(Inst) && !MIB.isIndirectBranch(Inst))
continue;
IndirectBranchInfo BrInfo(Inst, MIB);
bool R11Available = false;
BinaryFunction *TargetRetpoline;
InstructionListType Replacement;
// Determine if r11 is available before this instruction
if (BrInfo.isMem()) {
if (MIB.hasAnnotation(Inst, "PLTCall"))
R11Available = true;
else if (opts::R11Availability == AvailabilityOptions::ALWAYS)
R11Available = true;
else if (opts::R11Availability == AvailabilityOptions::ABI)
R11Available = BrInfo.isCall();
}
// If the instruction addressing pattern uses rsp and the retpoline
// loads the callee address then displacement needs to be updated
if (BrInfo.isMem() && !R11Available) {
IndirectBranchInfo::MemOpInfo &MemRef = BrInfo.Memory;
int Addend = (BrInfo.isJump() || BrInfo.isTailCall()) ? 8 : 16;
if (MemRef.BaseRegNum == MIB.getStackPointer())
MemRef.DispImm += Addend;
if (MemRef.IndexRegNum == MIB.getStackPointer())
MemRef.DispImm += Addend * MemRef.ScaleImm;
}
TargetRetpoline = getOrCreateRetpoline(BC, BrInfo, R11Available);
createBranchReplacement(BC, BrInfo, R11Available, Replacement,
TargetRetpoline->getSymbol());
It = BB.replaceInstruction(It, Replacement.begin(), Replacement.end());
RetpolinedBranches++;
}
}
}
outs() << "BOLT-INFO: The number of created retpoline functions is : "
<< CreatedRetpolines.size()
<< "\nBOLT-INFO: The number of retpolined branches is : "
<< RetpolinedBranches << "\n";
}
} // namespace bolt
} // namespace llvm
|