1 //===-- CodeGen/AsmPrinter/WinCFGuard.cpp - Control Flow Guard Impl ------===//
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 // This file contains support for writing the metadata for Windows Control Flow
10 // Guard, including address-taken functions, and valid longjmp targets.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "WinCFGuard.h"
15 #include "llvm/CodeGen/AsmPrinter.h"
16 #include "llvm/CodeGen/MachineFunction.h"
17 #include "llvm/CodeGen/MachineModuleInfo.h"
18 #include "llvm/CodeGen/MachineOperand.h"
19 #include "llvm/IR/Constants.h"
20 #include "llvm/IR/Metadata.h"
21 #include "llvm/MC/MCAsmInfo.h"
22 #include "llvm/MC/MCObjectFileInfo.h"
23 #include "llvm/MC/MCStreamer.h"
24 
25 #include <vector>
26 
27 using namespace llvm;
28 
29 WinCFGuard::WinCFGuard(AsmPrinter *A) : AsmPrinterHandler(), Asm(A) {}
30 
31 WinCFGuard::~WinCFGuard() {}
32 
33 void WinCFGuard::endFunction(const MachineFunction *MF) {
34 
35   // Skip functions without any longjmp targets.
36   if (MF->getLongjmpTargets().empty())
37     return;
38 
39   // Copy the function's longjmp targets to a module-level list.
40   LongjmpTargets.insert(LongjmpTargets.end(), MF->getLongjmpTargets().begin(),
41                         MF->getLongjmpTargets().end());
42 }
43 
44 void WinCFGuard::endModule() {
45   const Module *M = Asm->MMI->getModule();
46   std::vector<const Function *> Functions;
47   for (const Function &F : *M)
48     if (F.hasAddressTaken())
49       Functions.push_back(&F);
50   if (Functions.empty() && LongjmpTargets.empty())
51     return;
52   auto &OS = *Asm->OutStreamer;
53   OS.SwitchSection(Asm->OutContext.getObjectFileInfo()->getGFIDsSection());
54   for (const Function *F : Functions)
55     OS.EmitCOFFSymbolIndex(Asm->getSymbol(F));
56 
57   // Emit the symbol index of each longjmp target.
58   OS.SwitchSection(Asm->OutContext.getObjectFileInfo()->getGLJMPSection());
59   for (const MCSymbol *S : LongjmpTargets) {
60     OS.EmitCOFFSymbolIndex(S);
61   }
62 }
63