1480093f4SDimitry Andric //===-- CFGuard.cpp - Control Flow Guard checks -----------------*- C++ -*-===// 2480093f4SDimitry Andric // 3480093f4SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4480093f4SDimitry Andric // See https://llvm.org/LICENSE.txt for license information. 5480093f4SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6480093f4SDimitry Andric // 7480093f4SDimitry Andric //===----------------------------------------------------------------------===// 8480093f4SDimitry Andric /// 9480093f4SDimitry Andric /// \file 10480093f4SDimitry Andric /// This file contains the IR transform to add Microsoft's Control Flow Guard 11480093f4SDimitry Andric /// checks on Windows targets. 12480093f4SDimitry Andric /// 13480093f4SDimitry Andric //===----------------------------------------------------------------------===// 14480093f4SDimitry Andric 15480093f4SDimitry Andric #include "llvm/Transforms/CFGuard.h" 16480093f4SDimitry Andric #include "llvm/ADT/SmallVector.h" 17480093f4SDimitry Andric #include "llvm/ADT/Statistic.h" 18480093f4SDimitry Andric #include "llvm/ADT/Triple.h" 19480093f4SDimitry Andric #include "llvm/IR/CallingConv.h" 20480093f4SDimitry Andric #include "llvm/IR/IRBuilder.h" 21480093f4SDimitry Andric #include "llvm/IR/Instruction.h" 22480093f4SDimitry Andric #include "llvm/InitializePasses.h" 23480093f4SDimitry Andric #include "llvm/Pass.h" 24480093f4SDimitry Andric 25480093f4SDimitry Andric using namespace llvm; 26480093f4SDimitry Andric 27480093f4SDimitry Andric using OperandBundleDef = OperandBundleDefT<Value *>; 28480093f4SDimitry Andric 29480093f4SDimitry Andric #define DEBUG_TYPE "cfguard" 30480093f4SDimitry Andric 31480093f4SDimitry Andric STATISTIC(CFGuardCounter, "Number of Control Flow Guard checks added"); 32480093f4SDimitry Andric 33480093f4SDimitry Andric namespace { 34480093f4SDimitry Andric 35480093f4SDimitry Andric /// Adds Control Flow Guard (CFG) checks on indirect function calls/invokes. 36480093f4SDimitry Andric /// These checks ensure that the target address corresponds to the start of an 37480093f4SDimitry Andric /// address-taken function. X86_64 targets use the CF_Dispatch mechanism. X86, 38480093f4SDimitry Andric /// ARM, and AArch64 targets use the CF_Check machanism. 39480093f4SDimitry Andric class CFGuard : public FunctionPass { 40480093f4SDimitry Andric public: 41480093f4SDimitry Andric static char ID; 42480093f4SDimitry Andric 43480093f4SDimitry Andric enum Mechanism { CF_Check, CF_Dispatch }; 44480093f4SDimitry Andric 45480093f4SDimitry Andric // Default constructor required for the INITIALIZE_PASS macro. 46480093f4SDimitry Andric CFGuard() : FunctionPass(ID) { 47480093f4SDimitry Andric initializeCFGuardPass(*PassRegistry::getPassRegistry()); 48480093f4SDimitry Andric // By default, use the guard check mechanism. 49480093f4SDimitry Andric GuardMechanism = CF_Check; 50480093f4SDimitry Andric } 51480093f4SDimitry Andric 52480093f4SDimitry Andric // Recommended constructor used to specify the type of guard mechanism. 53480093f4SDimitry Andric CFGuard(Mechanism Var) : FunctionPass(ID) { 54480093f4SDimitry Andric initializeCFGuardPass(*PassRegistry::getPassRegistry()); 55480093f4SDimitry Andric GuardMechanism = Var; 56480093f4SDimitry Andric } 57480093f4SDimitry Andric 58480093f4SDimitry Andric /// Inserts a Control Flow Guard (CFG) check on an indirect call using the CFG 59480093f4SDimitry Andric /// check mechanism. When the image is loaded, the loader puts the appropriate 60480093f4SDimitry Andric /// guard check function pointer in the __guard_check_icall_fptr global 61480093f4SDimitry Andric /// symbol. This checks that the target address is a valid address-taken 62480093f4SDimitry Andric /// function. The address of the target function is passed to the guard check 63480093f4SDimitry Andric /// function in an architecture-specific register (e.g. ECX on 32-bit X86, 64480093f4SDimitry Andric /// X15 on Aarch64, and R0 on ARM). The guard check function has no return 65480093f4SDimitry Andric /// value (if the target is invalid, the guard check funtion will raise an 66480093f4SDimitry Andric /// error). 67480093f4SDimitry Andric /// 68480093f4SDimitry Andric /// For example, the following LLVM IR: 69480093f4SDimitry Andric /// \code 70480093f4SDimitry Andric /// %func_ptr = alloca i32 ()*, align 8 71480093f4SDimitry Andric /// store i32 ()* @target_func, i32 ()** %func_ptr, align 8 72480093f4SDimitry Andric /// %0 = load i32 ()*, i32 ()** %func_ptr, align 8 73480093f4SDimitry Andric /// %1 = call i32 %0() 74480093f4SDimitry Andric /// \endcode 75480093f4SDimitry Andric /// 76480093f4SDimitry Andric /// is transformed to: 77480093f4SDimitry Andric /// \code 78480093f4SDimitry Andric /// %func_ptr = alloca i32 ()*, align 8 79480093f4SDimitry Andric /// store i32 ()* @target_func, i32 ()** %func_ptr, align 8 80480093f4SDimitry Andric /// %0 = load i32 ()*, i32 ()** %func_ptr, align 8 81480093f4SDimitry Andric /// %1 = load void (i8*)*, void (i8*)** @__guard_check_icall_fptr 82480093f4SDimitry Andric /// %2 = bitcast i32 ()* %0 to i8* 83480093f4SDimitry Andric /// call cfguard_checkcc void %1(i8* %2) 84480093f4SDimitry Andric /// %3 = call i32 %0() 85480093f4SDimitry Andric /// \endcode 86480093f4SDimitry Andric /// 87480093f4SDimitry Andric /// For example, the following X86 assembly code: 88480093f4SDimitry Andric /// \code 89480093f4SDimitry Andric /// movl $_target_func, %eax 90480093f4SDimitry Andric /// calll *%eax 91480093f4SDimitry Andric /// \endcode 92480093f4SDimitry Andric /// 93480093f4SDimitry Andric /// is transformed to: 94480093f4SDimitry Andric /// \code 95480093f4SDimitry Andric /// movl $_target_func, %ecx 96480093f4SDimitry Andric /// calll *___guard_check_icall_fptr 97480093f4SDimitry Andric /// calll *%ecx 98480093f4SDimitry Andric /// \endcode 99480093f4SDimitry Andric /// 100480093f4SDimitry Andric /// \param CB indirect call to instrument. 101480093f4SDimitry Andric void insertCFGuardCheck(CallBase *CB); 102480093f4SDimitry Andric 103480093f4SDimitry Andric /// Inserts a Control Flow Guard (CFG) check on an indirect call using the CFG 104480093f4SDimitry Andric /// dispatch mechanism. When the image is loaded, the loader puts the 105480093f4SDimitry Andric /// appropriate guard check function pointer in the 106480093f4SDimitry Andric /// __guard_dispatch_icall_fptr global symbol. This checks that the target 107480093f4SDimitry Andric /// address is a valid address-taken function and, if so, tail calls the 108480093f4SDimitry Andric /// target. The target address is passed in an architecture-specific register 109480093f4SDimitry Andric /// (e.g. RAX on X86_64), with all other arguments for the target function 110480093f4SDimitry Andric /// passed as usual. 111480093f4SDimitry Andric /// 112480093f4SDimitry Andric /// For example, the following LLVM IR: 113480093f4SDimitry Andric /// \code 114480093f4SDimitry Andric /// %func_ptr = alloca i32 ()*, align 8 115480093f4SDimitry Andric /// store i32 ()* @target_func, i32 ()** %func_ptr, align 8 116480093f4SDimitry Andric /// %0 = load i32 ()*, i32 ()** %func_ptr, align 8 117480093f4SDimitry Andric /// %1 = call i32 %0() 118480093f4SDimitry Andric /// \endcode 119480093f4SDimitry Andric /// 120480093f4SDimitry Andric /// is transformed to: 121480093f4SDimitry Andric /// \code 122480093f4SDimitry Andric /// %func_ptr = alloca i32 ()*, align 8 123480093f4SDimitry Andric /// store i32 ()* @target_func, i32 ()** %func_ptr, align 8 124480093f4SDimitry Andric /// %0 = load i32 ()*, i32 ()** %func_ptr, align 8 125480093f4SDimitry Andric /// %1 = load i32 ()*, i32 ()** @__guard_dispatch_icall_fptr 126480093f4SDimitry Andric /// %2 = call i32 %1() [ "cfguardtarget"(i32 ()* %0) ] 127480093f4SDimitry Andric /// \endcode 128480093f4SDimitry Andric /// 129480093f4SDimitry Andric /// For example, the following X86_64 assembly code: 130480093f4SDimitry Andric /// \code 131480093f4SDimitry Andric /// leaq target_func(%rip), %rax 132480093f4SDimitry Andric /// callq *%rax 133480093f4SDimitry Andric /// \endcode 134480093f4SDimitry Andric /// 135480093f4SDimitry Andric /// is transformed to: 136480093f4SDimitry Andric /// \code 137480093f4SDimitry Andric /// leaq target_func(%rip), %rax 138480093f4SDimitry Andric /// callq *__guard_dispatch_icall_fptr(%rip) 139480093f4SDimitry Andric /// \endcode 140480093f4SDimitry Andric /// 141480093f4SDimitry Andric /// \param CB indirect call to instrument. 142480093f4SDimitry Andric void insertCFGuardDispatch(CallBase *CB); 143480093f4SDimitry Andric 144480093f4SDimitry Andric bool doInitialization(Module &M) override; 145480093f4SDimitry Andric bool runOnFunction(Function &F) override; 146480093f4SDimitry Andric 147480093f4SDimitry Andric private: 148480093f4SDimitry Andric // Only add checks if the module has the cfguard=2 flag. 149480093f4SDimitry Andric int cfguard_module_flag = 0; 150480093f4SDimitry Andric Mechanism GuardMechanism = CF_Check; 151480093f4SDimitry Andric FunctionType *GuardFnType = nullptr; 152480093f4SDimitry Andric PointerType *GuardFnPtrType = nullptr; 153480093f4SDimitry Andric Constant *GuardFnGlobal = nullptr; 154480093f4SDimitry Andric }; 155480093f4SDimitry Andric 156480093f4SDimitry Andric } // end anonymous namespace 157480093f4SDimitry Andric 158480093f4SDimitry Andric void CFGuard::insertCFGuardCheck(CallBase *CB) { 159480093f4SDimitry Andric 160480093f4SDimitry Andric assert(Triple(CB->getModule()->getTargetTriple()).isOSWindows() && 161480093f4SDimitry Andric "Only applicable for Windows targets"); 162480093f4SDimitry Andric assert(CB->isIndirectCall() && 163480093f4SDimitry Andric "Control Flow Guard checks can only be added to indirect calls"); 164480093f4SDimitry Andric 165480093f4SDimitry Andric IRBuilder<> B(CB); 166480093f4SDimitry Andric Value *CalledOperand = CB->getCalledOperand(); 167480093f4SDimitry Andric 168480093f4SDimitry Andric // Load the global symbol as a pointer to the check function. 169480093f4SDimitry Andric LoadInst *GuardCheckLoad = B.CreateLoad(GuardFnPtrType, GuardFnGlobal); 170480093f4SDimitry Andric 171480093f4SDimitry Andric // Create new call instruction. The CFGuard check should always be a call, 172480093f4SDimitry Andric // even if the original CallBase is an Invoke or CallBr instruction. 173480093f4SDimitry Andric CallInst *GuardCheck = 174480093f4SDimitry Andric B.CreateCall(GuardFnType, GuardCheckLoad, 175480093f4SDimitry Andric {B.CreateBitCast(CalledOperand, B.getInt8PtrTy())}); 176480093f4SDimitry Andric 177480093f4SDimitry Andric // Ensure that the first argument is passed in the correct register 178480093f4SDimitry Andric // (e.g. ECX on 32-bit X86 targets). 179480093f4SDimitry Andric GuardCheck->setCallingConv(CallingConv::CFGuard_Check); 180480093f4SDimitry Andric } 181480093f4SDimitry Andric 182480093f4SDimitry Andric void CFGuard::insertCFGuardDispatch(CallBase *CB) { 183480093f4SDimitry Andric 184480093f4SDimitry Andric assert(Triple(CB->getModule()->getTargetTriple()).isOSWindows() && 185480093f4SDimitry Andric "Only applicable for Windows targets"); 186480093f4SDimitry Andric assert(CB->isIndirectCall() && 187480093f4SDimitry Andric "Control Flow Guard checks can only be added to indirect calls"); 188480093f4SDimitry Andric 189480093f4SDimitry Andric IRBuilder<> B(CB); 190480093f4SDimitry Andric Value *CalledOperand = CB->getCalledOperand(); 191480093f4SDimitry Andric Type *CalledOperandType = CalledOperand->getType(); 192480093f4SDimitry Andric 193480093f4SDimitry Andric // Cast the guard dispatch global to the type of the called operand. 194480093f4SDimitry Andric PointerType *PTy = PointerType::get(CalledOperandType, 0); 195480093f4SDimitry Andric if (GuardFnGlobal->getType() != PTy) 196480093f4SDimitry Andric GuardFnGlobal = ConstantExpr::getBitCast(GuardFnGlobal, PTy); 197480093f4SDimitry Andric 198480093f4SDimitry Andric // Load the global as a pointer to a function of the same type. 199480093f4SDimitry Andric LoadInst *GuardDispatchLoad = B.CreateLoad(CalledOperandType, GuardFnGlobal); 200480093f4SDimitry Andric 201480093f4SDimitry Andric // Add the original call target as a cfguardtarget operand bundle. 202480093f4SDimitry Andric SmallVector<llvm::OperandBundleDef, 1> Bundles; 203480093f4SDimitry Andric CB->getOperandBundlesAsDefs(Bundles); 204480093f4SDimitry Andric Bundles.emplace_back("cfguardtarget", CalledOperand); 205480093f4SDimitry Andric 206480093f4SDimitry Andric // Create a copy of the call/invoke instruction and add the new bundle. 207*5ffd83dbSDimitry Andric assert((isa<CallInst>(CB) || isa<InvokeInst>(CB)) && 208*5ffd83dbSDimitry Andric "Unknown indirect call type"); 209*5ffd83dbSDimitry Andric CallBase *NewCB = CallBase::Create(CB, Bundles, CB); 210480093f4SDimitry Andric 211480093f4SDimitry Andric // Change the target of the call to be the guard dispatch function. 212480093f4SDimitry Andric NewCB->setCalledOperand(GuardDispatchLoad); 213480093f4SDimitry Andric 214480093f4SDimitry Andric // Replace the original call/invoke with the new instruction. 215480093f4SDimitry Andric CB->replaceAllUsesWith(NewCB); 216480093f4SDimitry Andric 217480093f4SDimitry Andric // Delete the original call/invoke. 218480093f4SDimitry Andric CB->eraseFromParent(); 219480093f4SDimitry Andric } 220480093f4SDimitry Andric 221480093f4SDimitry Andric bool CFGuard::doInitialization(Module &M) { 222480093f4SDimitry Andric 223480093f4SDimitry Andric // Check if this module has the cfguard flag and read its value. 224480093f4SDimitry Andric if (auto *MD = 225480093f4SDimitry Andric mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("cfguard"))) 226480093f4SDimitry Andric cfguard_module_flag = MD->getZExtValue(); 227480093f4SDimitry Andric 228480093f4SDimitry Andric // Skip modules for which CFGuard checks have been disabled. 229480093f4SDimitry Andric if (cfguard_module_flag != 2) 230480093f4SDimitry Andric return false; 231480093f4SDimitry Andric 232480093f4SDimitry Andric // Set up prototypes for the guard check and dispatch functions. 233480093f4SDimitry Andric GuardFnType = FunctionType::get(Type::getVoidTy(M.getContext()), 234480093f4SDimitry Andric {Type::getInt8PtrTy(M.getContext())}, false); 235480093f4SDimitry Andric GuardFnPtrType = PointerType::get(GuardFnType, 0); 236480093f4SDimitry Andric 237480093f4SDimitry Andric // Get or insert the guard check or dispatch global symbols. 238480093f4SDimitry Andric if (GuardMechanism == CF_Check) { 239480093f4SDimitry Andric GuardFnGlobal = 240480093f4SDimitry Andric M.getOrInsertGlobal("__guard_check_icall_fptr", GuardFnPtrType); 241480093f4SDimitry Andric } else { 242480093f4SDimitry Andric assert(GuardMechanism == CF_Dispatch && "Invalid CFGuard mechanism"); 243480093f4SDimitry Andric GuardFnGlobal = 244480093f4SDimitry Andric M.getOrInsertGlobal("__guard_dispatch_icall_fptr", GuardFnPtrType); 245480093f4SDimitry Andric } 246480093f4SDimitry Andric 247480093f4SDimitry Andric return true; 248480093f4SDimitry Andric } 249480093f4SDimitry Andric 250480093f4SDimitry Andric bool CFGuard::runOnFunction(Function &F) { 251480093f4SDimitry Andric 252480093f4SDimitry Andric // Skip modules for which CFGuard checks have been disabled. 253480093f4SDimitry Andric if (cfguard_module_flag != 2) 254480093f4SDimitry Andric return false; 255480093f4SDimitry Andric 256480093f4SDimitry Andric SmallVector<CallBase *, 8> IndirectCalls; 257480093f4SDimitry Andric 258480093f4SDimitry Andric // Iterate over the instructions to find all indirect call/invoke/callbr 259480093f4SDimitry Andric // instructions. Make a separate list of pointers to indirect 260480093f4SDimitry Andric // call/invoke/callbr instructions because the original instructions will be 261480093f4SDimitry Andric // deleted as the checks are added. 262480093f4SDimitry Andric for (BasicBlock &BB : F.getBasicBlockList()) { 263480093f4SDimitry Andric for (Instruction &I : BB.getInstList()) { 264480093f4SDimitry Andric auto *CB = dyn_cast<CallBase>(&I); 265480093f4SDimitry Andric if (CB && CB->isIndirectCall() && !CB->hasFnAttr("guard_nocf")) { 266480093f4SDimitry Andric IndirectCalls.push_back(CB); 267480093f4SDimitry Andric CFGuardCounter++; 268480093f4SDimitry Andric } 269480093f4SDimitry Andric } 270480093f4SDimitry Andric } 271480093f4SDimitry Andric 272480093f4SDimitry Andric // If no checks are needed, return early. 273480093f4SDimitry Andric if (IndirectCalls.empty()) { 274480093f4SDimitry Andric return false; 275480093f4SDimitry Andric } 276480093f4SDimitry Andric 277480093f4SDimitry Andric // For each indirect call/invoke, add the appropriate dispatch or check. 278480093f4SDimitry Andric if (GuardMechanism == CF_Dispatch) { 279480093f4SDimitry Andric for (CallBase *CB : IndirectCalls) { 280480093f4SDimitry Andric insertCFGuardDispatch(CB); 281480093f4SDimitry Andric } 282480093f4SDimitry Andric } else { 283480093f4SDimitry Andric for (CallBase *CB : IndirectCalls) { 284480093f4SDimitry Andric insertCFGuardCheck(CB); 285480093f4SDimitry Andric } 286480093f4SDimitry Andric } 287480093f4SDimitry Andric 288480093f4SDimitry Andric return true; 289480093f4SDimitry Andric } 290480093f4SDimitry Andric 291480093f4SDimitry Andric char CFGuard::ID = 0; 292480093f4SDimitry Andric INITIALIZE_PASS(CFGuard, "CFGuard", "CFGuard", false, false) 293480093f4SDimitry Andric 294480093f4SDimitry Andric FunctionPass *llvm::createCFGuardCheckPass() { 295480093f4SDimitry Andric return new CFGuard(CFGuard::CF_Check); 296480093f4SDimitry Andric } 297480093f4SDimitry Andric 298480093f4SDimitry Andric FunctionPass *llvm::createCFGuardDispatchPass() { 299480093f4SDimitry Andric return new CFGuard(CFGuard::CF_Dispatch); 300480093f4SDimitry Andric } 301