LLVM 23.0.0git
AArch64PointerAuth.cpp
Go to the documentation of this file.
1//===-- AArch64PointerAuth.cpp -- Harden code using PAuth ------------------==//
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
10
11#include "AArch64.h"
13#include "AArch64InstrInfo.h"
15#include "AArch64Subtarget.h"
20
21using namespace llvm;
22using namespace llvm::AArch64PAuth;
23
24#define AARCH64_POINTER_AUTH_NAME "AArch64 Pointer Authentication"
25
26namespace {
27
28class AArch64PointerAuthImpl {
29public:
30 bool run(MachineFunction &MF);
31
32private:
33 const AArch64Subtarget *Subtarget = nullptr;
34 const AArch64InstrInfo *TII = nullptr;
35
36 void signLR(MachineFunction &MF, MachineBasicBlock::iterator MBBI) const;
37
38 void authenticateLR(MachineFunction &MF,
40};
41
42class AArch64PointerAuthLegacy : public MachineFunctionPass {
43public:
44 static char ID;
45
46 AArch64PointerAuthLegacy() : MachineFunctionPass(ID) {}
47
48 bool runOnMachineFunction(MachineFunction &MF) override;
49
50 StringRef getPassName() const override { return AARCH64_POINTER_AUTH_NAME; }
51};
52
53} // end anonymous namespace
54
55INITIALIZE_PASS(AArch64PointerAuthLegacy, "aarch64-ptrauth",
56 AARCH64_POINTER_AUTH_NAME, false, false)
57
59 return new AArch64PointerAuthLegacy();
60}
61
62char AArch64PointerAuthLegacy::ID = 0;
63
78
80 MachineInstr::MIFlag Flags, bool EmitCFI) {
81 if (!EmitCFI)
82 return;
83
84 auto &MF = *MBB.getParent();
85 auto &MFnI = *MF.getInfo<AArch64FunctionInfo>();
86
87 CFIInstBuilder CFIBuilder(MBB, MBBI, Flags);
88 if (MFnI.branchProtectionPAuthLR()) {
89 CFIBuilder.buildNegateRAStateWithPC();
90 } else if (!MF.getTarget().getTargetTriple().isOSBinFormatMachO()) {
91 CFIBuilder.buildNegateRAState();
92 }
93}
94
95void AArch64PointerAuthImpl::signLR(MachineFunction &MF,
97 auto &MFnI = *MF.getInfo<AArch64FunctionInfo>();
98 bool UseBKey = MFnI.shouldSignWithBKey();
99 bool EmitCFI = MFnI.needsDwarfUnwindInfo(MF);
100 bool NeedsWinCFI = MF.hasWinCFI();
101
102 MachineBasicBlock &MBB = *MBBI->getParent();
103
104 // Debug location must be unknown, see AArch64FrameLowering::emitPrologue.
105 DebugLoc DL;
106
107 if (UseBKey && !MF.getTarget().getTargetTriple().isOSBinFormatMachO()) {
108 BuildMI(MBB, MBBI, DL, TII->get(AArch64::EMITBKEY))
110 }
111
112 // PAuthLR authentication instructions need to know the value of PC at the
113 // point of signing (PACI*).
114 if (MFnI.branchProtectionPAuthLR()) {
115 MCSymbol *PACSym = MF.getContext().createTempSymbol();
116 MFnI.setSigningInstrLabel(PACSym);
117 }
118
119 // No SEH opcode for this one; it doesn't materialize into an
120 // instruction on Windows.
121 if (MFnI.branchProtectionPAuthLR() && Subtarget->hasPAuthLR()) {
123 BuildMI(MBB, MBBI, DL,
124 TII->get(UseBKey ? AArch64::PACIBSPPC : AArch64::PACIASPPC))
126 ->setPreInstrSymbol(MF, MFnI.getSigningInstrLabel());
127 } else {
128 if (MFnI.branchProtectionPAuthLR()) {
129 BuildMI(MBB, MBBI, DL, TII->get(AArch64::PACM))
132 }
133 BuildMI(MBB, MBBI, DL,
134 TII->get(UseBKey ? AArch64::PACIBSP : AArch64::PACIASP))
136 ->setPreInstrSymbol(MF, MFnI.getSigningInstrLabel());
137 if (!MFnI.branchProtectionPAuthLR())
139 }
140
141 if (!EmitCFI && NeedsWinCFI) {
142 BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_PACSignLR))
144 }
145}
146
147void AArch64PointerAuthImpl::authenticateLR(
148 MachineFunction &MF, MachineBasicBlock::iterator MBBI) const {
149 const AArch64FunctionInfo *MFnI = MF.getInfo<AArch64FunctionInfo>();
150 bool UseBKey = MFnI->shouldSignWithBKey();
151 bool EmitAsyncCFI = MFnI->needsAsyncDwarfUnwindInfo(MF);
152 bool NeedsWinCFI = MF.hasWinCFI();
153
154 MachineBasicBlock &MBB = *MBBI->getParent();
155 DebugLoc DL = MBBI->getDebugLoc();
156 // MBBI points to a PAUTH_EPILOGUE instruction to be replaced and
157 // TI points to a terminator instruction that may or may not be combined.
158 // Note that inserting new instructions "before MBBI" and "before TI" is
159 // not the same because if ShadowCallStack is enabled, its instructions
160 // are placed between MBBI and TI.
162
163 // The AUTIASP instruction assembles to a hint instruction before v8.3a so
164 // this instruction can safely used for any v8a architecture.
165 // From v8.3a onwards there are optimised authenticate LR and return
166 // instructions, namely RETA{A,B}, that can be used instead. In this case the
167 // DW_CFA_AARCH64_negate_ra_state can't be emitted.
168 bool TerminatorIsCombinable =
169 TI != MBB.end() && TI->getOpcode() == AArch64::RET;
170 MCSymbol *PACSym = MFnI->getSigningInstrLabel();
171
172 if (Subtarget->hasPAuth() && TerminatorIsCombinable && !NeedsWinCFI &&
173 !MF.getFunction().hasFnAttribute(Attribute::ShadowCallStack)) {
174 if (MFnI->branchProtectionPAuthLR() && Subtarget->hasPAuthLR()) {
175 assert(PACSym && "No PAC instruction to refer to");
176 BuildMI(MBB, TI, DL,
177 TII->get(UseBKey ? AArch64::RETABSPPCi : AArch64::RETAASPPCi))
178 .addSym(PACSym)
181 } else {
182 if (MFnI->branchProtectionPAuthLR()) {
184 AArch64::X16);
185 BuildMI(MBB, MBBI, DL, TII->get(AArch64::PACM))
187 }
188 BuildMI(MBB, TI, DL, TII->get(UseBKey ? AArch64::RETAB : AArch64::RETAA))
191 }
192 MBB.erase(TI);
193 return;
194 }
195
196 auto &AFL = *static_cast<const AArch64FrameLowering *>(
197 MF.getSubtarget().getFrameLowering());
198 int64_t ArgumentStackToRestore = AFL.getArgumentStackToRestore(MF, MBB);
199
200 // When ArgumentStackToRestore < 0, the tail callee pops more argument space
201 // than this function received, so after the frame teardown SP is below the
202 // entry SP used as the signing modifier. Reconstruct entry SP in x16 and
203 // authenticate using AUTI[AB]1716 (x17=LR, x16=entry_SP).
204 if (ArgumentStackToRestore < 0) {
205 emitFrameOffset(MBB, MBBI, DL, AArch64::X16, AArch64::SP,
206 StackOffset::getFixed(-ArgumentStackToRestore), TII,
208
209 BuildMI(MBB, MBBI, DL, TII->get(AArch64::ORRXrs), AArch64::X17)
210 .addReg(AArch64::XZR)
211 .addReg(AArch64::LR)
212 .addImm(0)
214
215 if (MFnI->branchProtectionPAuthLR() && Subtarget->hasPAuthLR()) {
216 assert(PACSym && "No PAC instruction to refer to");
218 AArch64::X15);
219
221 unsigned AutOpc = UseBKey ? AArch64::AUTIB171615 : AArch64::AUTIA171615;
222 BuildMI(MBB, MBBI, DL, TII->get(AutOpc))
224 } else if (MFnI->branchProtectionPAuthLR()) {
225 assert(PACSym && "No PAC instruction to refer to");
227 AArch64::X15);
228
229 // The PACM hint-space instruction modifies the following AUTI[AB]1716
230 // to optionally take x15 as an extra operand depending on the
231 // presence of +pauth-lr at runtime. On machines without +pauth-lr, it
232 // behaves as a nop, and the address of the PACI[AB]SP in x15 is
233 // ignored.
234 BuildMI(MBB, MBBI, DL, TII->get(AArch64::PACM))
236
238 unsigned AutOpc = UseBKey ? AArch64::AUTIB1716 : AArch64::AUTIA1716;
239 BuildMI(MBB, MBBI, DL, TII->get(AutOpc))
241 } else {
242 unsigned AutOpc = UseBKey ? AArch64::AUTIB1716 : AArch64::AUTIA1716;
243 BuildMI(MBB, MBBI, DL, TII->get(AutOpc))
246 }
247
248 BuildMI(MBB, MBBI, DL, TII->get(AArch64::ORRXrs), AArch64::LR)
249 .addReg(AArch64::XZR)
250 .addReg(AArch64::X17)
251 .addImm(0)
253 return;
254 }
255
256 // When ArgumentStackToRestore > 0, this function received more argument
257 // space than the tail callee pops. The epilogue contains an SP adjustment
258 // (e.g. "add sp, sp, #N") to discard the leftover argument space. We must
259 // authenticate *before* that adjustment so that AUTI[AB]SP sees the entry
260 // SP discriminator. Move any such SP-adjusting instructions to after the
261 // authentication instruction.
262 //
263 // We cannot simply bump SP first and then use AUTI[AB]SP with the bumped
264 // value, because the live arguments would fall below SP and potentially
265 // outside the red-zone.
266 SmallVector<MachineInstr *, 2> SPMods;
267 if (ArgumentStackToRestore > 0) {
268 for (auto I = MBBI; I->getFlag(MachineInstr::FrameDestroy); --I) {
269 if ((I->getOpcode() == AArch64::ADDXri ||
270 I->getOpcode() == AArch64::SUBXri) &&
271 I->getOperand(0).getReg() == AArch64::SP &&
272 I->getOperand(1).getReg() == AArch64::SP)
273 SPMods.push_back(&*I);
274 }
275 }
276 for (auto *MI : SPMods)
277 MI->removeFromParent();
278
279 if (MFnI->branchProtectionPAuthLR() && Subtarget->hasPAuthLR()) {
280 assert(PACSym && "No PAC instruction to refer to");
282 BuildMI(MBB, MBBI, DL,
283 TII->get(UseBKey ? AArch64::AUTIBSPPCi : AArch64::AUTIASPPCi))
284 .addSym(PACSym)
286 } else {
287 if (MFnI->branchProtectionPAuthLR()) {
289 AArch64::X16);
290
291 BuildMI(MBB, MBBI, DL, TII->get(AArch64::PACM))
294 }
295 BuildMI(MBB, MBBI, DL,
296 TII->get(UseBKey ? AArch64::AUTIBSP : AArch64::AUTIASP))
298 if (!MFnI->branchProtectionPAuthLR())
300 }
301
302 if (NeedsWinCFI) {
303 BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_PACSignLR))
305 }
306
307 for (auto *MI : SPMods)
308 MBB.insert(MBBI, MI);
309}
310
312 switch (Method) {
314 return 0;
316 return 4;
318 return 12;
321 return 20;
322 }
323 llvm_unreachable("Unknown AuthCheckMethod enum");
324}
325
326bool AArch64PointerAuthImpl::run(MachineFunction &MF) {
327 Subtarget = &MF.getSubtarget<AArch64Subtarget>();
328 TII = Subtarget->getInstrInfo();
329
331
332 bool Modified = false;
333
334 for (auto &MBB : MF) {
335 for (auto &MI : MBB) {
336 switch (MI.getOpcode()) {
337 default:
338 break;
339 case AArch64::PAUTH_PROLOGUE:
340 case AArch64::PAUTH_EPILOGUE:
341 PAuthPseudoInstrs.push_back(MI.getIterator());
342 break;
343 }
344 }
345 }
346
347 for (auto It : PAuthPseudoInstrs) {
348 switch (It->getOpcode()) {
349 case AArch64::PAUTH_PROLOGUE:
350 signLR(MF, It);
351 break;
352 case AArch64::PAUTH_EPILOGUE:
353 authenticateLR(MF, It);
354 break;
355 default:
356 llvm_unreachable("Unhandled opcode");
357 }
358 It->eraseFromParent();
359 Modified = true;
360 }
361
362 return Modified;
363}
364
365bool AArch64PointerAuthLegacy::runOnMachineFunction(MachineFunction &MF) {
366 return AArch64PointerAuthImpl().run(MF);
367}
368
369PreservedAnalyses
372 const bool Changed = AArch64PointerAuthImpl().run(MF);
373 if (!Changed)
374 return PreservedAnalyses::all();
377 return PA;
378}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
#define AARCH64_POINTER_AUTH_NAME
static void emitEpiloguePACSymOffsetIntoReg(const TargetInstrInfo &TII, MachineBasicBlock &MBB, MachineBasicBlock::iterator I, DebugLoc DL, MCSymbol *PACSym, Register Reg)
static void emitPACCFI(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, MachineInstr::MIFlag Flags, bool EmitCFI)
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
MachineBasicBlock MachineBasicBlock::iterator MBBI
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
AArch64FunctionInfo - This class is derived from MachineFunctionInfo and contains private AArch64-spe...
bool needsAsyncDwarfUnwindInfo(const MachineFunction &MF) const
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
const AArch64InstrInfo * getInstrInfo() const override
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
Helper class for creating CFI instructions and inserting them into MIR.
A debug info location.
Definition DebugLoc.h:124
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition Function.cpp:724
LLVM_ABI MCSymbol * createTempSymbol()
Create a temporary symbol with a unique name.
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition MCSymbol.h:42
LLVM_ABI instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
LLVM_ABI instr_iterator erase(instr_iterator I)
Remove an instruction from the instruction list and delete it.
LLVM_ABI instr_iterator getFirstInstrTerminator()
Same getFirstTerminator but it ignores bundles and return an instr_iterator instead.
MachineInstrBundleIterator< MachineInstr > iterator
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MCContext & getContext() const
Function & getFunction()
Return the LLVM function that this machine code represents.
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & setMIFlag(MachineInstr::MIFlag Flag) const
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & addSym(MCSymbol *Sym, unsigned char TargetFlags=0) const
const MachineInstrBuilder & copyImplicitOps(const MachineInstr &OtherMI) const
Copy all the implicit operands from OtherMI onto this one.
LLVM_ABI void setPreInstrSymbol(MachineFunction &MF, MCSymbol *Symbol)
Set a symbol that will be emitted just prior to the instruction itself.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:151
Wrapper class representing virtual and physical registers.
Definition Register.h:20
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
int64_t getFixed() const
Returns the fixed component of the stack.
Definition TypeSize.h:46
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
TargetInstrInfo - Interface to description of machine instruction set.
const Triple & getTargetTriple() const
bool isOSBinFormatMachO() const
Tests whether the environment is MachO.
Definition Triple.h:791
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ MO_NC
MO_NC - Indicates whether the linker is expected to check the symbol reference for overflow.
@ MO_PAGEOFF
MO_PAGEOFF - A symbol operand with this flag represents the offset of that symbol within a 4K page.
@ MO_PAGE
MO_PAGE - A symbol operand with this flag represents the pc-relative offset of the 4K page containing...
unsigned getCheckerSizeInBytes(AuthCheckMethod Method)
Returns the number of bytes added by checkAuthenticatedRegister.
AuthCheckMethod
Variants of check performed on an authenticated pointer.
@ XPACHint
Check by comparing the authenticated value with an XPAC-ed one without using PAuth instructions not e...
@ DummyLoad
Perform a load to a temporary register.
@ HighBitsNoTBI
Check by comparing bits 62 and 61 of the authenticated address.
@ None
Do not check the value at all.
@ XPAC
Similar to XPACHint but using Armv8.3-only XPAC instruction, thus not restricted to LR:
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
This is an optimization pass for GlobalISel generic memory operations.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
FunctionPass * createAArch64PointerAuthPass()
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
void emitFrameOffset(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, const DebugLoc &DL, unsigned DestReg, unsigned SrcReg, StackOffset Offset, const TargetInstrInfo *TII, MachineInstr::MIFlag=MachineInstr::NoFlags, bool SetNZCV=false, bool NeedsWinCFI=false, bool *HasWinCFI=nullptr, bool EmitCFAOffset=false, StackOffset InitialOffset={}, unsigned FrameReg=AArch64::SP)
emitFrameOffset - Emit instructions as needed to set DestReg to SrcReg plus Offset.