$OpenBSD: patch-lib_Target_X86_X86FrameLowering_cpp,v 1.2 2018/08/21 06:56:09 ajacoutot Exp $

- Add RETGUARD to clang for amd64. This security mechanism uses per-function
  random cookies to protect access to function return instructions, with the
  effect that the integrity of the return address is protected, and function
  return instructions are harder to use in ROP gadgets.

  On function entry the return address is combined with a per-function random
  cookie and stored in the stack frame. The integrity of this value is verified
  before function return, and if this check fails, the program aborts. In this way
  RETGUARD is an improved stack protector, since the cookies are per-function. The
  verification routine is constructed such that the binary space immediately
  before each ret instruction is padded with int03 instructions, which makes these
  return instructions difficult to use in ROP gadgets. In the kernel, this has the
  effect of removing approximately 50% of total ROP gadgets, and 15% of unique
  ROP gadgets compared to the 6.3 release kernel. Function epilogues are
  essentially gadget free, leaving only the polymorphic gadgets that result from
  jumping into the instruction stream partway through other instructions. Work to
  remove these gadgets will continue through other mechanisms.
- Refactor retguard to make adding additional arches easier.

Index: lib/Target/X86/X86FrameLowering.cpp
--- lib/Target/X86/X86FrameLowering.cpp.orig
+++ lib/Target/X86/X86FrameLowering.cpp
@@ -15,6 +15,7 @@
 #include "X86InstrBuilder.h"
 #include "X86InstrInfo.h"
 #include "X86MachineFunctionInfo.h"
+#include "X86ReturnProtectorLowering.h"
 #include "X86Subtarget.h"
 #include "X86TargetMachine.h"
 #include "llvm/ADT/SmallSet.h"
@@ -39,7 +40,7 @@ X86FrameLowering::X86FrameLowering(const X86Subtarget 
                                    unsigned StackAlignOverride)
     : TargetFrameLowering(StackGrowsDown, StackAlignOverride,
                           STI.is64Bit() ? -8 : -4),
-      STI(STI), TII(*STI.getInstrInfo()), TRI(STI.getRegisterInfo()) {
+      STI(STI), TII(*STI.getInstrInfo()), TRI(STI.getRegisterInfo()), RPL() {
   // Cache a bunch of frame-related predicates for this subtarget.
   SlotSize = TRI->getSlotSize();
   Is64Bit = STI.is64Bit();
@@ -3058,4 +3059,8 @@ void X86FrameLowering::processFunctionBeforeFrameFinal
   addFrameReference(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64mi32)),
                     UnwindHelpFI)
       .addImm(-2);
+}
+
+const ReturnProtectorLowering *X86FrameLowering::getReturnProtector() const {
+  return &RPL;
 }
