mirror of
https://github.com/opnsense/src.git
synced 2026-03-15 07:02:32 -04:00
6.0.0 (branches/release_60 r324090). This introduces retpoline support, with the -mretpoline flag. The upstream initial commit message (r323155 by Chandler Carruth) contains quite a bit of explanation. Quoting: Introduce the "retpoline" x86 mitigation technique for variant #2 of the speculative execution vulnerabilities disclosed today, specifically identified by CVE-2017-5715, "Branch Target Injection", and is one of the two halves to Spectre. Summary: First, we need to explain the core of the vulnerability. Note that this is a very incomplete description, please see the Project Zero blog post for details: https://googleprojectzero.blogspot.com/2018/01/reading-privileged-memory-with-side.html The basis for branch target injection is to direct speculative execution of the processor to some "gadget" of executable code by poisoning the prediction of indirect branches with the address of that gadget. The gadget in turn contains an operation that provides a side channel for reading data. Most commonly, this will look like a load of secret data followed by a branch on the loaded value and then a load of some predictable cache line. The attacker then uses timing of the processors cache to determine which direction the branch took *in the speculative execution*, and in turn what one bit of the loaded value was. Due to the nature of these timing side channels and the branch predictor on Intel processors, this allows an attacker to leak data only accessible to a privileged domain (like the kernel) back into an unprivileged domain. The goal is simple: avoid generating code which contains an indirect branch that could have its prediction poisoned by an attacker. In many cases, the compiler can simply use directed conditional branches and a small search tree. LLVM already has support for lowering switches in this way and the first step of this patch is to disable jump-table lowering of switches and introduce a pass to rewrite explicit indirectbr sequences into a switch over integers. However, there is no fully general alternative to indirect calls. We introduce a new construct we call a "retpoline" to implement indirect calls in a non-speculatable way. It can be thought of loosely as a trampoline for indirect calls which uses the RET instruction on x86. Further, we arrange for a specific call->ret sequence which ensures the processor predicts the return to go to a controlled, known location. The retpoline then "smashes" the return address pushed onto the stack by the call with the desired target of the original indirect call. The result is a predicted return to the next instruction after a call (which can be used to trap speculative execution within an infinite loop) and an actual indirect branch to an arbitrary address. On 64-bit x86 ABIs, this is especially easily done in the compiler by using a guaranteed scratch register to pass the target into this device. For 32-bit ABIs there isn't a guaranteed scratch register and so several different retpoline variants are introduced to use a scratch register if one is available in the calling convention and to otherwise use direct stack push/pop sequences to pass the target address. This "retpoline" mitigation is fully described in the following blog post: https://support.google.com/faqs/answer/7625886 We also support a target feature that disables emission of the retpoline thunk by the compiler to allow for custom thunks if users want them. These are particularly useful in environments like kernels that routinely do hot-patching on boot and want to hot-patch their thunk to different code sequences. They can write this custom thunk and use `-mretpoline-external-thunk` *in addition* to `-mretpoline`. In this case, on x86-64 thu thunk names must be: ``` __llvm_external_retpoline_r11 ``` or on 32-bit: ``` __llvm_external_retpoline_eax __llvm_external_retpoline_ecx __llvm_external_retpoline_edx __llvm_external_retpoline_push ``` And the target of the retpoline is passed in the named register, or in the case of the `push` suffix on the top of the stack via a `pushl` instruction. There is one other important source of indirect branches in x86 ELF binaries: the PLT. These patches also include support for LLD to generate PLT entries that perform a retpoline-style indirection. The only other indirect branches remaining that we are aware of are from precompiled runtimes (such as crt0.o and similar). The ones we have found are not really attackable, and so we have not focused on them here, but eventually these runtimes should also be replicated for retpoline-ed configurations for completeness. For kernels or other freestanding or fully static executables, the compiler switch `-mretpoline` is sufficient to fully mitigate this particular attack. For dynamic executables, you must compile *all* libraries with `-mretpoline` and additionally link the dynamic executable and all shared libraries with LLD and pass `-z retpolineplt` (or use similar functionality from some other linker). We strongly recommend also using `-z now` as non-lazy binding allows the retpoline-mitigated PLT to be substantially smaller. When manually apply similar transformations to `-mretpoline` to the Linux kernel we observed very small performance hits to applications running typic al workloads, and relatively minor hits (approximately 2%) even for extremely syscall-heavy applications. This is largely due to the small number of indirect branches that occur in performance sensitive paths of the kernel. When using these patches on statically linked applications, especially C++ applications, you should expect to see a much more dramatic performance hit. For microbenchmarks that are switch, indirect-, or virtual-call heavy we have seen overheads ranging from 10% to 50%. However, real-world workloads exhibit substantially lower performance impact. Notably, techniques such as PGO and ThinLTO dramatically reduce the impact of hot indirect calls (by speculatively promoting them to direct calls) and allow optimized search trees to be used to lower switches. If you need to deploy these techniques in C++ applications, we *strongly* recommend that you ensure all hot call targets are statically linked (avoiding PLT indirection) and use both PGO and ThinLTO. Well tuned servers using all of these techniques saw 5% - 10% overhead from the use of retpoline. We will add detailed documentation covering these components in subsequent patches, but wanted to make the core functionality available as soon as possible. Happy for more code review, but we'd really like to get these patches landed and backported ASAP for obvious reasons. We're planning to backport this to both 6.0 and 5.0 release streams and get a 5.0 release with just this cherry picked ASAP for distros and vendors. This patch is the work of a number of people over the past month: Eric, Reid, Rui, and myself. I'm mailing it out as a single commit due to the time sensitive nature of landing this and the need to backport it. Huge thanks to everyone who helped out here, and everyone at Intel who helped out in discussions about how to craft this. Also, credit goes to Paul Turner (at Google, but not an LLVM contributor) for much of the underlying retpoline design. Reviewers: echristo, rnk, ruiu, craig.topper, DavidKreitzer Subscribers: sanjoy, emaste, mcrosier, mgorny, mehdi_amini, hiraditya, llvm-commits Differential Revision: https://reviews.llvm.org/D41723 MFC after: 3 months X-MFC-With: r327952 PR: 224669
194 lines
7.2 KiB
C++
194 lines
7.2 KiB
C++
//===-- MipsTargetObjectFile.cpp - Mips Object Files ----------------------===//
|
|
//
|
|
// The LLVM Compiler Infrastructure
|
|
//
|
|
// This file is distributed under the University of Illinois Open Source
|
|
// License. See LICENSE.TXT for details.
|
|
//
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
#include "MipsTargetObjectFile.h"
|
|
#include "MipsSubtarget.h"
|
|
#include "MipsTargetMachine.h"
|
|
#include "llvm/BinaryFormat/ELF.h"
|
|
#include "llvm/IR/DataLayout.h"
|
|
#include "llvm/IR/DerivedTypes.h"
|
|
#include "llvm/IR/GlobalVariable.h"
|
|
#include "llvm/MC/MCContext.h"
|
|
#include "llvm/MC/MCSectionELF.h"
|
|
#include "llvm/Support/CommandLine.h"
|
|
#include "llvm/Target/TargetMachine.h"
|
|
using namespace llvm;
|
|
|
|
static cl::opt<unsigned>
|
|
SSThreshold("mips-ssection-threshold", cl::Hidden,
|
|
cl::desc("Small data and bss section threshold size (default=8)"),
|
|
cl::init(8));
|
|
|
|
static cl::opt<bool>
|
|
LocalSData("mlocal-sdata", cl::Hidden,
|
|
cl::desc("MIPS: Use gp_rel for object-local data."),
|
|
cl::init(true));
|
|
|
|
static cl::opt<bool>
|
|
ExternSData("mextern-sdata", cl::Hidden,
|
|
cl::desc("MIPS: Use gp_rel for data that is not defined by the "
|
|
"current object."),
|
|
cl::init(true));
|
|
|
|
static cl::opt<bool>
|
|
EmbeddedData("membedded-data", cl::Hidden,
|
|
cl::desc("MIPS: Try to allocate variables in the following"
|
|
" sections if possible: .rodata, .sdata, .data ."),
|
|
cl::init(false));
|
|
|
|
void MipsTargetObjectFile::Initialize(MCContext &Ctx, const TargetMachine &TM){
|
|
TargetLoweringObjectFileELF::Initialize(Ctx, TM);
|
|
InitializeELF(TM.Options.UseInitArray);
|
|
|
|
SmallDataSection = getContext().getELFSection(
|
|
".sdata", ELF::SHT_PROGBITS,
|
|
ELF::SHF_WRITE | ELF::SHF_ALLOC | ELF::SHF_MIPS_GPREL);
|
|
|
|
SmallBSSSection = getContext().getELFSection(".sbss", ELF::SHT_NOBITS,
|
|
ELF::SHF_WRITE | ELF::SHF_ALLOC |
|
|
ELF::SHF_MIPS_GPREL);
|
|
this->TM = &static_cast<const MipsTargetMachine &>(TM);
|
|
}
|
|
|
|
// A address must be loaded from a small section if its size is less than the
|
|
// small section size threshold. Data in this section must be addressed using
|
|
// gp_rel operator.
|
|
static bool IsInSmallSection(uint64_t Size) {
|
|
// gcc has traditionally not treated zero-sized objects as small data, so this
|
|
// is effectively part of the ABI.
|
|
return Size > 0 && Size <= SSThreshold;
|
|
}
|
|
|
|
/// Return true if this global address should be placed into small data/bss
|
|
/// section.
|
|
bool MipsTargetObjectFile::IsGlobalInSmallSection(
|
|
const GlobalObject *GO, const TargetMachine &TM) const {
|
|
// We first check the case where global is a declaration, because finding
|
|
// section kind using getKindForGlobal() is only allowed for global
|
|
// definitions.
|
|
if (GO->isDeclaration() || GO->hasAvailableExternallyLinkage())
|
|
return IsGlobalInSmallSectionImpl(GO, TM);
|
|
|
|
return IsGlobalInSmallSection(GO, TM, getKindForGlobal(GO, TM));
|
|
}
|
|
|
|
/// Return true if this global address should be placed into small data/bss
|
|
/// section.
|
|
bool MipsTargetObjectFile::
|
|
IsGlobalInSmallSection(const GlobalObject *GO, const TargetMachine &TM,
|
|
SectionKind Kind) const {
|
|
return IsGlobalInSmallSectionImpl(GO, TM) &&
|
|
(Kind.isData() || Kind.isBSS() || Kind.isCommon() ||
|
|
Kind.isReadOnly());
|
|
}
|
|
|
|
/// Return true if this global address should be placed into small data/bss
|
|
/// section. This method does all the work, except for checking the section
|
|
/// kind.
|
|
bool MipsTargetObjectFile::
|
|
IsGlobalInSmallSectionImpl(const GlobalObject *GO,
|
|
const TargetMachine &TM) const {
|
|
const MipsSubtarget &Subtarget =
|
|
*static_cast<const MipsTargetMachine &>(TM).getSubtargetImpl();
|
|
|
|
// Return if small section is not available.
|
|
if (!Subtarget.useSmallSection())
|
|
return false;
|
|
|
|
// Only global variables, not functions.
|
|
const GlobalVariable *GVA = dyn_cast<GlobalVariable>(GO);
|
|
if (!GVA)
|
|
return false;
|
|
|
|
// If the variable has an explicit section, it is placed in that section but
|
|
// it's addressing mode may change.
|
|
if (GVA->hasSection()) {
|
|
StringRef Section = GVA->getSection();
|
|
|
|
// Explicitly placing any variable in the small data section overrides
|
|
// the global -G value.
|
|
if (Section == ".sdata" || Section == ".sbss")
|
|
return true;
|
|
|
|
// Otherwise reject accessing it through the gp pointer. There are some
|
|
// historic cases which GCC doesn't appear to respect any more. These
|
|
// are .lit4, .lit8 and .srdata. For the moment reject these as well.
|
|
return false;
|
|
}
|
|
|
|
// Enforce -mlocal-sdata.
|
|
if (!LocalSData && GVA->hasLocalLinkage())
|
|
return false;
|
|
|
|
// Enforce -mextern-sdata.
|
|
if (!ExternSData && ((GVA->hasExternalLinkage() && GVA->isDeclaration()) ||
|
|
GVA->hasCommonLinkage()))
|
|
return false;
|
|
|
|
// Enforce -membedded-data.
|
|
if (EmbeddedData && GVA->isConstant())
|
|
return false;
|
|
|
|
Type *Ty = GVA->getValueType();
|
|
|
|
// It is possible that the type of the global is unsized, i.e. a declaration
|
|
// of a extern struct. In this case don't presume it is in the small data
|
|
// section. This happens e.g. when building the FreeBSD kernel.
|
|
if (!Ty->isSized())
|
|
return false;
|
|
|
|
return IsInSmallSection(
|
|
GVA->getParent()->getDataLayout().getTypeAllocSize(Ty));
|
|
}
|
|
|
|
MCSection *MipsTargetObjectFile::SelectSectionForGlobal(
|
|
const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
|
|
// TODO: Could also support "weak" symbols as well with ".gnu.linkonce.s.*"
|
|
// sections?
|
|
|
|
// Handle Small Section classification here.
|
|
if (Kind.isBSS() && IsGlobalInSmallSection(GO, TM, Kind))
|
|
return SmallBSSSection;
|
|
if (Kind.isData() && IsGlobalInSmallSection(GO, TM, Kind))
|
|
return SmallDataSection;
|
|
if (Kind.isReadOnly() && IsGlobalInSmallSection(GO, TM, Kind))
|
|
return SmallDataSection;
|
|
|
|
// Otherwise, we work the same as ELF.
|
|
return TargetLoweringObjectFileELF::SelectSectionForGlobal(GO, Kind, TM);
|
|
}
|
|
|
|
/// Return true if this constant should be placed into small data section.
|
|
bool MipsTargetObjectFile::IsConstantInSmallSection(
|
|
const DataLayout &DL, const Constant *CN, const TargetMachine &TM) const {
|
|
return (static_cast<const MipsTargetMachine &>(TM)
|
|
.getSubtargetImpl()
|
|
->useSmallSection() &&
|
|
LocalSData && IsInSmallSection(DL.getTypeAllocSize(CN->getType())));
|
|
}
|
|
|
|
/// Return true if this constant should be placed into small data section.
|
|
MCSection *MipsTargetObjectFile::getSectionForConstant(const DataLayout &DL,
|
|
SectionKind Kind,
|
|
const Constant *C,
|
|
unsigned &Align) const {
|
|
if (IsConstantInSmallSection(DL, C, *TM))
|
|
return SmallDataSection;
|
|
|
|
// Otherwise, we work the same as ELF.
|
|
return TargetLoweringObjectFileELF::getSectionForConstant(DL, Kind, C, Align);
|
|
}
|
|
|
|
const MCExpr *
|
|
MipsTargetObjectFile::getDebugThreadLocalSymbol(const MCSymbol *Sym) const {
|
|
const MCExpr *Expr =
|
|
MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
|
|
return MCBinaryExpr::createAdd(
|
|
Expr, MCConstantExpr::create(0x8000, getContext()), getContext());
|
|
}
|