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
67 MCSymbol *PACSym, Register Reg) {
68 BuildMI(MBB, I, DL, TII.get(AArch64::ADRP), Reg)
69 .addSym(PACSym, AArch64II::MO_PAGE);
70 BuildMI(MBB, I, DL, TII.get(AArch64::ADDXri), Reg)
71 .addReg(Reg)
73 .addImm(0);
74}
75
77 MachineInstr::MIFlag Flags, bool EmitCFI) {
78 if (!EmitCFI)
79 return;
80
81 auto &MF = *MBB.getParent();
82 auto &MFnI = *MF.getInfo<AArch64FunctionInfo>();
83
84 CFIInstBuilder CFIBuilder(MBB, MBBI, Flags);
85 MFnI.branchProtectionPAuthLR() ? CFIBuilder.buildNegateRAStateWithPC()
86 : CFIBuilder.buildNegateRAState();
87}
88
89void AArch64PointerAuthImpl::signLR(MachineFunction &MF,
91 auto &MFnI = *MF.getInfo<AArch64FunctionInfo>();
92 bool UseBKey = MFnI.shouldSignWithBKey();
93 bool EmitCFI = MFnI.needsDwarfUnwindInfo(MF);
94 bool NeedsWinCFI = MF.hasWinCFI();
95
96 MachineBasicBlock &MBB = *MBBI->getParent();
97
98 // Debug location must be unknown, see AArch64FrameLowering::emitPrologue.
100
101 if (UseBKey && !MF.getTarget().getTargetTriple().isOSBinFormatMachO()) {
102 BuildMI(MBB, MBBI, DL, TII->get(AArch64::EMITBKEY))
104 }
105
106 // PAuthLR authentication instructions need to know the value of PC at the
107 // point of signing (PACI*).
108 if (MFnI.branchProtectionPAuthLR()) {
109 MCSymbol *PACSym = MF.getContext().createTempSymbol();
110 MFnI.setSigningInstrLabel(PACSym);
111 }
112
113 // No SEH opcode for this one; it doesn't materialize into an
114 // instruction on Windows.
115 if (MFnI.branchProtectionPAuthLR() && Subtarget->hasPAuthLR()) {
117 BuildMI(MBB, MBBI, DL,
118 TII->get(UseBKey ? AArch64::PACIBSPPC : AArch64::PACIASPPC))
120 ->setPreInstrSymbol(MF, MFnI.getSigningInstrLabel());
121 } else {
122 if (MFnI.branchProtectionPAuthLR()) {
123 BuildMI(MBB, MBBI, DL, TII->get(AArch64::PACM))
126 }
127 BuildMI(MBB, MBBI, DL,
128 TII->get(UseBKey ? AArch64::PACIBSP : AArch64::PACIASP))
130 ->setPreInstrSymbol(MF, MFnI.getSigningInstrLabel());
131 if (!MFnI.branchProtectionPAuthLR())
133 }
134
135 if (!EmitCFI && NeedsWinCFI) {
136 BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_PACSignLR))
138 }
139}
140
141void AArch64PointerAuthImpl::authenticateLR(
142 MachineFunction &MF, MachineBasicBlock::iterator MBBI) const {
143 const AArch64FunctionInfo *MFnI = MF.getInfo<AArch64FunctionInfo>();
144 bool UseBKey = MFnI->shouldSignWithBKey();
145 bool EmitAsyncCFI = MFnI->needsAsyncDwarfUnwindInfo(MF);
146 bool NeedsWinCFI = MF.hasWinCFI();
147
148 MachineBasicBlock &MBB = *MBBI->getParent();
149 DebugLoc DL = MBBI->getDebugLoc();
150 // MBBI points to a PAUTH_EPILOGUE instruction to be replaced and
151 // TI points to a terminator instruction that may or may not be combined.
152 // Note that inserting new instructions "before MBBI" and "before TI" is
153 // not the same because if ShadowCallStack is enabled, its instructions
154 // are placed between MBBI and TI.
156
157 // The AUTIASP instruction assembles to a hint instruction before v8.3a so
158 // this instruction can safely used for any v8a architecture.
159 // From v8.3a onwards there are optimised authenticate LR and return
160 // instructions, namely RETA{A,B}, that can be used instead. In this case the
161 // DW_CFA_AARCH64_negate_ra_state can't be emitted.
162 bool TerminatorIsCombinable =
163 TI != MBB.end() && TI->getOpcode() == AArch64::RET;
164 MCSymbol *PACSym = MFnI->getSigningInstrLabel();
165
166 if (Subtarget->hasPAuth() && TerminatorIsCombinable && !NeedsWinCFI &&
167 !MF.getFunction().hasFnAttribute(Attribute::ShadowCallStack)) {
168 if (MFnI->branchProtectionPAuthLR() && Subtarget->hasPAuthLR()) {
169 assert(PACSym && "No PAC instruction to refer to");
170 BuildMI(MBB, TI, DL,
171 TII->get(UseBKey ? AArch64::RETABSPPCi : AArch64::RETAASPPCi))
172 .addSym(PACSym)
175 } else {
176 if (MFnI->branchProtectionPAuthLR()) {
177 emitPACSymOffsetIntoReg(*TII, MBB, MBBI, DL, PACSym, AArch64::X16);
178 BuildMI(MBB, MBBI, DL, TII->get(AArch64::PACM))
180 }
181 BuildMI(MBB, TI, DL, TII->get(UseBKey ? AArch64::RETAB : AArch64::RETAA))
184 }
185 MBB.erase(TI);
186 return;
187 }
188
189 // When FPDiff != 0 (tail call with callee-popped stack arg space), SP has
190 // been adjusted and no longer matches the entry SP used as the signing
191 // modifier. We must reconstruct entry SP for authentication.
192 auto &AFL = *static_cast<const AArch64FrameLowering *>(
193 MF.getSubtarget().getFrameLowering());
194 if (int64_t FPDiff = AFL.getArgumentStackToRestore(MF, MBB)) {
195 // Use AUTI[AB]1716 variants: x17=LR, x16=entry_SP.
196 BuildMI(MBB, MBBI, DL, TII->get(AArch64::ORRXrs), AArch64::X17)
197 .addReg(AArch64::XZR)
198 .addReg(AArch64::LR)
199 .addImm(0)
201 emitFrameOffset(MBB, MBBI, DL, AArch64::X16, AArch64::SP,
202 StackOffset::getFixed(-FPDiff), TII,
204
205 if (MFnI->branchProtectionPAuthLR() && Subtarget->hasPAuthLR()) {
206 assert(PACSym && "No PAC instruction to refer to");
207 emitPACSymOffsetIntoReg(*TII, MBB, MBBI, DL, PACSym, AArch64::X15);
208
210 unsigned AutOpc = UseBKey ? AArch64::AUTIB171615 : AArch64::AUTIA171615;
211 BuildMI(MBB, MBBI, DL, TII->get(AutOpc))
213 } else if (MFnI->branchProtectionPAuthLR()) {
214 assert(PACSym && "No PAC instruction to refer to");
215 emitPACSymOffsetIntoReg(*TII, MBB, MBBI, DL, PACSym, AArch64::X15);
216
217 // The PACM hint-space instruction modifies the following AUTI[AB]1716
218 // to optionally take x15 as an extra operand depending on the
219 // presence of +pauth-lr at runtime. On machines without +pauth-lr, it
220 // behaves as a nop, and the address of the PACI[AB]SP in x15 is
221 // ignored.
222 BuildMI(MBB, MBBI, DL, TII->get(AArch64::PACM))
224
226 unsigned AutOpc = UseBKey ? AArch64::AUTIB1716 : AArch64::AUTIA1716;
227 BuildMI(MBB, MBBI, DL, TII->get(AutOpc))
229 } else {
230 unsigned AutOpc = UseBKey ? AArch64::AUTIB1716 : AArch64::AUTIA1716;
231 BuildMI(MBB, MBBI, DL, TII->get(AutOpc))
234 }
235
236 BuildMI(MBB, MBBI, DL, TII->get(AArch64::ORRXrs), AArch64::LR)
237 .addReg(AArch64::XZR)
238 .addReg(AArch64::X17)
239 .addImm(0)
241 return;
242 }
243
244 if (MFnI->branchProtectionPAuthLR() && Subtarget->hasPAuthLR()) {
245 assert(PACSym && "No PAC instruction to refer to");
247 BuildMI(MBB, MBBI, DL,
248 TII->get(UseBKey ? AArch64::AUTIBSPPCi : AArch64::AUTIASPPCi))
249 .addSym(PACSym)
251 } else {
252 if (MFnI->branchProtectionPAuthLR()) {
253 emitPACSymOffsetIntoReg(*TII, MBB, MBBI, DL, PACSym, AArch64::X16);
254 BuildMI(MBB, MBBI, DL, TII->get(AArch64::PACM))
257 }
258 BuildMI(MBB, MBBI, DL,
259 TII->get(UseBKey ? AArch64::AUTIBSP : AArch64::AUTIASP))
261 if (!MFnI->branchProtectionPAuthLR())
263 }
264
265 if (NeedsWinCFI) {
266 BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_PACSignLR))
268 }
269}
270
272 switch (Method) {
274 return 0;
276 return 4;
278 return 12;
281 return 20;
282 }
283 llvm_unreachable("Unknown AuthCheckMethod enum");
284}
285
286bool AArch64PointerAuthImpl::run(MachineFunction &MF) {
287 Subtarget = &MF.getSubtarget<AArch64Subtarget>();
288 TII = Subtarget->getInstrInfo();
289
291
292 bool Modified = false;
293
294 for (auto &MBB : MF) {
295 for (auto &MI : MBB) {
296 switch (MI.getOpcode()) {
297 default:
298 break;
299 case AArch64::PAUTH_PROLOGUE:
300 case AArch64::PAUTH_EPILOGUE:
301 PAuthPseudoInstrs.push_back(MI.getIterator());
302 break;
303 }
304 }
305 }
306
307 for (auto It : PAuthPseudoInstrs) {
308 switch (It->getOpcode()) {
309 case AArch64::PAUTH_PROLOGUE:
310 signLR(MF, It);
311 break;
312 case AArch64::PAUTH_EPILOGUE:
313 authenticateLR(MF, It);
314 break;
315 default:
316 llvm_unreachable("Unhandled opcode");
317 }
318 It->eraseFromParent();
319 Modified = true;
320 }
321
322 return Modified;
323}
324
325bool AArch64PointerAuthLegacy::runOnMachineFunction(MachineFunction &MF) {
326 return AArch64PointerAuthImpl().run(MF);
327}
328
329PreservedAnalyses
332 const bool Changed = AArch64PointerAuthImpl().run(MF);
333 if (!Changed)
334 return PreservedAnalyses::all();
337 return PA;
338}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
#define AARCH64_POINTER_AUTH_NAME
static void emitPACSymOffsetIntoReg(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:123
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:728
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
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.