CFGuard.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. //===-- CFGuard.cpp - Control Flow Guard checks -----------------*- C++ -*-===//
  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. ///
  9. /// \file
  10. /// This file contains the IR transform to add Microsoft's Control Flow Guard
  11. /// checks on Windows targets.
  12. ///
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/Transforms/CFGuard.h"
  15. #include "llvm/ADT/SmallVector.h"
  16. #include "llvm/ADT/Statistic.h"
  17. #include "llvm/ADT/Triple.h"
  18. #include "llvm/IR/CallingConv.h"
  19. #include "llvm/IR/IRBuilder.h"
  20. #include "llvm/IR/Instruction.h"
  21. #include "llvm/InitializePasses.h"
  22. #include "llvm/Pass.h"
  23. using namespace llvm;
  24. using OperandBundleDef = OperandBundleDefT<Value *>;
  25. #define DEBUG_TYPE "cfguard"
  26. STATISTIC(CFGuardCounter, "Number of Control Flow Guard checks added");
  27. namespace {
  28. /// Adds Control Flow Guard (CFG) checks on indirect function calls/invokes.
  29. /// These checks ensure that the target address corresponds to the start of an
  30. /// address-taken function. X86_64 targets use the CF_Dispatch mechanism. X86,
  31. /// ARM, and AArch64 targets use the CF_Check machanism.
  32. class CFGuard : public FunctionPass {
  33. public:
  34. static char ID;
  35. enum Mechanism { CF_Check, CF_Dispatch };
  36. // Default constructor required for the INITIALIZE_PASS macro.
  37. CFGuard() : FunctionPass(ID) {
  38. initializeCFGuardPass(*PassRegistry::getPassRegistry());
  39. // By default, use the guard check mechanism.
  40. GuardMechanism = CF_Check;
  41. }
  42. // Recommended constructor used to specify the type of guard mechanism.
  43. CFGuard(Mechanism Var) : FunctionPass(ID) {
  44. initializeCFGuardPass(*PassRegistry::getPassRegistry());
  45. GuardMechanism = Var;
  46. }
  47. /// Inserts a Control Flow Guard (CFG) check on an indirect call using the CFG
  48. /// check mechanism. When the image is loaded, the loader puts the appropriate
  49. /// guard check function pointer in the __guard_check_icall_fptr global
  50. /// symbol. This checks that the target address is a valid address-taken
  51. /// function. The address of the target function is passed to the guard check
  52. /// function in an architecture-specific register (e.g. ECX on 32-bit X86,
  53. /// X15 on Aarch64, and R0 on ARM). The guard check function has no return
  54. /// value (if the target is invalid, the guard check funtion will raise an
  55. /// error).
  56. ///
  57. /// For example, the following LLVM IR:
  58. /// \code
  59. /// %func_ptr = alloca i32 ()*, align 8
  60. /// store i32 ()* @target_func, i32 ()** %func_ptr, align 8
  61. /// %0 = load i32 ()*, i32 ()** %func_ptr, align 8
  62. /// %1 = call i32 %0()
  63. /// \endcode
  64. ///
  65. /// is transformed to:
  66. /// \code
  67. /// %func_ptr = alloca i32 ()*, align 8
  68. /// store i32 ()* @target_func, i32 ()** %func_ptr, align 8
  69. /// %0 = load i32 ()*, i32 ()** %func_ptr, align 8
  70. /// %1 = load void (i8*)*, void (i8*)** @__guard_check_icall_fptr
  71. /// %2 = bitcast i32 ()* %0 to i8*
  72. /// call cfguard_checkcc void %1(i8* %2)
  73. /// %3 = call i32 %0()
  74. /// \endcode
  75. ///
  76. /// For example, the following X86 assembly code:
  77. /// \code
  78. /// movl $_target_func, %eax
  79. /// calll *%eax
  80. /// \endcode
  81. ///
  82. /// is transformed to:
  83. /// \code
  84. /// movl $_target_func, %ecx
  85. /// calll *___guard_check_icall_fptr
  86. /// calll *%ecx
  87. /// \endcode
  88. ///
  89. /// \param CB indirect call to instrument.
  90. void insertCFGuardCheck(CallBase *CB);
  91. /// Inserts a Control Flow Guard (CFG) check on an indirect call using the CFG
  92. /// dispatch mechanism. When the image is loaded, the loader puts the
  93. /// appropriate guard check function pointer in the
  94. /// __guard_dispatch_icall_fptr global symbol. This checks that the target
  95. /// address is a valid address-taken function and, if so, tail calls the
  96. /// target. The target address is passed in an architecture-specific register
  97. /// (e.g. RAX on X86_64), with all other arguments for the target function
  98. /// passed as usual.
  99. ///
  100. /// For example, the following LLVM IR:
  101. /// \code
  102. /// %func_ptr = alloca i32 ()*, align 8
  103. /// store i32 ()* @target_func, i32 ()** %func_ptr, align 8
  104. /// %0 = load i32 ()*, i32 ()** %func_ptr, align 8
  105. /// %1 = call i32 %0()
  106. /// \endcode
  107. ///
  108. /// is transformed to:
  109. /// \code
  110. /// %func_ptr = alloca i32 ()*, align 8
  111. /// store i32 ()* @target_func, i32 ()** %func_ptr, align 8
  112. /// %0 = load i32 ()*, i32 ()** %func_ptr, align 8
  113. /// %1 = load i32 ()*, i32 ()** @__guard_dispatch_icall_fptr
  114. /// %2 = call i32 %1() [ "cfguardtarget"(i32 ()* %0) ]
  115. /// \endcode
  116. ///
  117. /// For example, the following X86_64 assembly code:
  118. /// \code
  119. /// leaq target_func(%rip), %rax
  120. /// callq *%rax
  121. /// \endcode
  122. ///
  123. /// is transformed to:
  124. /// \code
  125. /// leaq target_func(%rip), %rax
  126. /// callq *__guard_dispatch_icall_fptr(%rip)
  127. /// \endcode
  128. ///
  129. /// \param CB indirect call to instrument.
  130. void insertCFGuardDispatch(CallBase *CB);
  131. bool doInitialization(Module &M) override;
  132. bool runOnFunction(Function &F) override;
  133. private:
  134. // Only add checks if the module has the cfguard=2 flag.
  135. int cfguard_module_flag = 0;
  136. Mechanism GuardMechanism = CF_Check;
  137. FunctionType *GuardFnType = nullptr;
  138. PointerType *GuardFnPtrType = nullptr;
  139. Constant *GuardFnGlobal = nullptr;
  140. };
  141. } // end anonymous namespace
  142. void CFGuard::insertCFGuardCheck(CallBase *CB) {
  143. assert(Triple(CB->getModule()->getTargetTriple()).isOSWindows() &&
  144. "Only applicable for Windows targets");
  145. assert(CB->isIndirectCall() &&
  146. "Control Flow Guard checks can only be added to indirect calls");
  147. IRBuilder<> B(CB);
  148. Value *CalledOperand = CB->getCalledOperand();
  149. // If the indirect call is called within catchpad or cleanuppad,
  150. // we need to copy "funclet" bundle of the call.
  151. SmallVector<llvm::OperandBundleDef, 1> Bundles;
  152. if (auto Bundle = CB->getOperandBundle(LLVMContext::OB_funclet))
  153. Bundles.push_back(OperandBundleDef(*Bundle));
  154. // Load the global symbol as a pointer to the check function.
  155. LoadInst *GuardCheckLoad = B.CreateLoad(GuardFnPtrType, GuardFnGlobal);
  156. // Create new call instruction. The CFGuard check should always be a call,
  157. // even if the original CallBase is an Invoke or CallBr instruction.
  158. CallInst *GuardCheck =
  159. B.CreateCall(GuardFnType, GuardCheckLoad,
  160. {B.CreateBitCast(CalledOperand, B.getInt8PtrTy())}, Bundles);
  161. // Ensure that the first argument is passed in the correct register
  162. // (e.g. ECX on 32-bit X86 targets).
  163. GuardCheck->setCallingConv(CallingConv::CFGuard_Check);
  164. }
  165. void CFGuard::insertCFGuardDispatch(CallBase *CB) {
  166. assert(Triple(CB->getModule()->getTargetTriple()).isOSWindows() &&
  167. "Only applicable for Windows targets");
  168. assert(CB->isIndirectCall() &&
  169. "Control Flow Guard checks can only be added to indirect calls");
  170. IRBuilder<> B(CB);
  171. Value *CalledOperand = CB->getCalledOperand();
  172. Type *CalledOperandType = CalledOperand->getType();
  173. // Cast the guard dispatch global to the type of the called operand.
  174. PointerType *PTy = PointerType::get(CalledOperandType, 0);
  175. if (GuardFnGlobal->getType() != PTy)
  176. GuardFnGlobal = ConstantExpr::getBitCast(GuardFnGlobal, PTy);
  177. // Load the global as a pointer to a function of the same type.
  178. LoadInst *GuardDispatchLoad = B.CreateLoad(CalledOperandType, GuardFnGlobal);
  179. // Add the original call target as a cfguardtarget operand bundle.
  180. SmallVector<llvm::OperandBundleDef, 1> Bundles;
  181. CB->getOperandBundlesAsDefs(Bundles);
  182. Bundles.emplace_back("cfguardtarget", CalledOperand);
  183. // Create a copy of the call/invoke instruction and add the new bundle.
  184. assert((isa<CallInst>(CB) || isa<InvokeInst>(CB)) &&
  185. "Unknown indirect call type");
  186. CallBase *NewCB = CallBase::Create(CB, Bundles, CB);
  187. // Change the target of the call to be the guard dispatch function.
  188. NewCB->setCalledOperand(GuardDispatchLoad);
  189. // Replace the original call/invoke with the new instruction.
  190. CB->replaceAllUsesWith(NewCB);
  191. // Delete the original call/invoke.
  192. CB->eraseFromParent();
  193. }
  194. bool CFGuard::doInitialization(Module &M) {
  195. // Check if this module has the cfguard flag and read its value.
  196. if (auto *MD =
  197. mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("cfguard")))
  198. cfguard_module_flag = MD->getZExtValue();
  199. // Skip modules for which CFGuard checks have been disabled.
  200. if (cfguard_module_flag != 2)
  201. return false;
  202. // Set up prototypes for the guard check and dispatch functions.
  203. GuardFnType = FunctionType::get(Type::getVoidTy(M.getContext()),
  204. {Type::getInt8PtrTy(M.getContext())}, false);
  205. GuardFnPtrType = PointerType::get(GuardFnType, 0);
  206. // Get or insert the guard check or dispatch global symbols.
  207. llvm::StringRef GuardFnName;
  208. if (GuardMechanism == CF_Check) {
  209. GuardFnName = "__guard_check_icall_fptr";
  210. } else if (GuardMechanism == CF_Dispatch) {
  211. GuardFnName = "__guard_dispatch_icall_fptr";
  212. } else {
  213. assert(false && "Invalid CFGuard mechanism");
  214. }
  215. GuardFnGlobal = M.getOrInsertGlobal(GuardFnName, GuardFnPtrType, [&] {
  216. auto *Var = new GlobalVariable(M, GuardFnPtrType, false,
  217. GlobalVariable::ExternalLinkage, nullptr,
  218. GuardFnName);
  219. Var->setDSOLocal(true);
  220. return Var;
  221. });
  222. return true;
  223. }
  224. bool CFGuard::runOnFunction(Function &F) {
  225. // Skip modules for which CFGuard checks have been disabled.
  226. if (cfguard_module_flag != 2)
  227. return false;
  228. SmallVector<CallBase *, 8> IndirectCalls;
  229. // Iterate over the instructions to find all indirect call/invoke/callbr
  230. // instructions. Make a separate list of pointers to indirect
  231. // call/invoke/callbr instructions because the original instructions will be
  232. // deleted as the checks are added.
  233. for (BasicBlock &BB : F) {
  234. for (Instruction &I : BB) {
  235. auto *CB = dyn_cast<CallBase>(&I);
  236. if (CB && CB->isIndirectCall() && !CB->hasFnAttr("guard_nocf")) {
  237. IndirectCalls.push_back(CB);
  238. CFGuardCounter++;
  239. }
  240. }
  241. }
  242. // If no checks are needed, return early.
  243. if (IndirectCalls.empty()) {
  244. return false;
  245. }
  246. // For each indirect call/invoke, add the appropriate dispatch or check.
  247. if (GuardMechanism == CF_Dispatch) {
  248. for (CallBase *CB : IndirectCalls) {
  249. insertCFGuardDispatch(CB);
  250. }
  251. } else {
  252. for (CallBase *CB : IndirectCalls) {
  253. insertCFGuardCheck(CB);
  254. }
  255. }
  256. return true;
  257. }
  258. char CFGuard::ID = 0;
  259. INITIALIZE_PASS(CFGuard, "CFGuard", "CFGuard", false, false)
  260. FunctionPass *llvm::createCFGuardCheckPass() {
  261. return new CFGuard(CFGuard::CF_Check);
  262. }
  263. FunctionPass *llvm::createCFGuardDispatchPass() {
  264. return new CFGuard(CFGuard::CF_Dispatch);
  265. }