1//===- DXContainerPDB.cpp - DirectX PDB writer pass -----------------------===//
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#include "DirectX.h"
10#include "MCTargetDesc/DirectXContainerObjectWriter.h"
11#include "llvm/ADT/ScopeExit.h"
12#include "llvm/ADT/StringSet.h"
13#include "llvm/BinaryFormat/DXContainer.h"
14#include "llvm/DebugInfo/CodeView/GUID.h"
15#include "llvm/DebugInfo/MSF/MSFBuilder.h"
16#include "llvm/DebugInfo/PDB/Native/InfoStreamBuilder.h"
17#include "llvm/DebugInfo/PDB/Native/PDBFileBuilder.h"
18#include "llvm/IR/Constants.h"
19#include "llvm/IR/Module.h"
20#include "llvm/MC/MCDXContainerWriter.h"
21#include "llvm/Pass.h"
22#include "llvm/Support/CommandLine.h"
23#include "llvm/Support/FileSystem.h"
24#include "llvm/Support/IOSandbox.h"
25#include "llvm/Transforms/Utils/ModuleUtils.h"
26
27using namespace llvm;
28
29namespace {
30
31class DXContainerPDB : public ModulePass, MCDXContainerBaseWriter {
32 Module *M = nullptr;
33 SmallVector<MCDXContainerPart> Parts;
34
35 void reset() {
36 M = nullptr;
37 Parts.clear();
38 }
39
40public:
41 static char ID;
42 DXContainerPDB() : ModulePass(ID) {}
43
44 StringRef getPassName() const override { return "DirectX PDB Emitter"; }
45
46 bool runOnModule(Module &M) override;
47
48 void getAnalysisUsage(AnalysisUsage &AU) const override {
49 AU.setPreservesAll();
50 }
51
52 bool shouldSkipSection(StringRef SectionName, size_t SectionSize) override;
53 ArrayRef<MCDXContainerPart> collectParts() override;
54};
55
56} // namespace
57
58bool DXContainerPDB::shouldSkipSection(StringRef SectionName,
59 size_t SectionSize) {
60 if (MCDXContainerBaseWriter::shouldSkipSection(SectionName, SectionSize))
61 return true;
62 if (dxil::SlimDebug && SectionName == "ILDB")
63 return true;
64
65 // Skip sections that are irrelevant for debug info.
66 static const StringSet<> DebugSections{"ILDB", "ILDN", "HASH", "PDBI",
67 "SRCI", "STAT", "RDAT", "VERS"};
68 return !DebugSections.contains(key: SectionName);
69}
70
71static StringRef getGlobalData(const GlobalVariable &GV) {
72 if (GV.hasInitializer())
73 if (const auto *Data =
74 dyn_cast<ConstantDataSequential>(Val: GV.getInitializer()))
75 return Data->getRawDataValues();
76 return {};
77}
78
79ArrayRef<MCDXContainerPart> DXContainerPDB::collectParts() {
80 Parts.clear();
81 for (const GlobalVariable &GV : M->globals()) {
82 StringRef Name = GV.getSection();
83 StringRef Data = getGlobalData(GV);
84
85 if (Data.empty())
86 continue;
87 if (shouldSkipSection(SectionName: Name, SectionSize: Data.size()))
88 continue;
89
90 Parts.push_back(Elt: {.Name: Name, .Data: Data});
91 }
92 return Parts;
93}
94
95static GlobalVariable *createPrivateDataGlobal(Module &M, StringRef Data) {
96 Constant *Content =
97 ConstantDataArray::getString(Context&: M.getContext(), Initializer: Data, /*AddNull*/ false);
98 auto *GV =
99 new GlobalVariable(M, Content->getType(), true,
100 GlobalValue::PrivateLinkage, Content, "dx.priv");
101 GV->setSection("PRIV");
102 GV->setAlignment(Align(1));
103 return GV;
104}
105
106bool DXContainerPDB::runOnModule(Module &M) {
107 llvm::scope_exit Cleanup([&]() { reset(); });
108 this->M = &M;
109
110 SmallString<128> DebugFileName;
111 ArrayRef<char> ModuleHash;
112 for (const GlobalVariable &GV : M.globals()) {
113 if (GV.getSection() == PdbFileNameSectionName) {
114 assert(DebugFileName.empty() && "Duplicate PDBNAME section");
115 DebugFileName = getGlobalData(GV);
116 } else if (GV.getSection() == ModuleHashSectionName) {
117 assert(ModuleHash.empty() && "Duplicate PBDHASH section");
118 StringRef Data = getGlobalData(GV);
119 ModuleHash = ArrayRef(Data.data(), Data.size());
120 }
121 }
122
123 // PDB emission was not requested.
124 if (DebugFileName.empty() && !dxil::PdbInPrivate)
125 return false;
126 if (ModuleHash.empty())
127 report_fatal_error(reason: "Module hash for PDB not found");
128
129 bool DeleteAfterRead = false;
130 if (DebugFileName.empty()) {
131 if (std::error_code EC =
132 sys::fs::createTemporaryFile(Prefix: "dxil", Suffix: "pdb", ResultPath&: DebugFileName))
133 reportFatalInternalError(reason: "Failed to create temporary PDB file");
134 DeleteAfterRead = true;
135 }
136 llvm::scope_exit FileCleanup([&]() {
137 if (DeleteAfterRead)
138 sys::fs::remove(path: DebugFileName);
139 });
140
141 BumpPtrAllocator Allocator;
142 pdb::PDBFileBuilder Builder(Allocator);
143
144 // DirectXShaderCompiler uses block size 512.
145 if (Error Err = Builder.initialize(BlockSize: 512))
146 reportFatalInternalError(Err: std::move(Err));
147
148 // Reserved streams that should be empty.
149 static_assert(pdb::kSpecialStreamCount == 5 &&
150 "First 5 streams should be empty in DirectX PDB file");
151 for (uint32_t I = 0; I < pdb::kSpecialStreamCount; ++I) {
152 if (auto Err = Builder.getMsfBuilder().addStream(Size: 0).takeError())
153 reportFatalInternalError(Err: std::move(Err));
154 }
155
156 // Add DXContainer stream.
157 if (auto Err = Builder.getMsfBuilder().addStream(Size: 0).takeError())
158 reportFatalInternalError(Err: std::move(Err));
159
160 // InfoStream must be filled. Bitcode hash from HASH part is used for PDB
161 // GUID.
162 codeview::GUID PdbGuid;
163 assert(ModuleHash.size() == std::size(PdbGuid.Guid) &&
164 "Module hash length must be match GUID length");
165 std::copy_n(first: ModuleHash.begin(), n: std::size(PdbGuid.Guid), result: PdbGuid.Guid);
166
167 auto &InfoBuilder = Builder.getInfoBuilder();
168 InfoBuilder.setAge(1);
169 InfoBuilder.setGuid(PdbGuid);
170 InfoBuilder.setSignature(0);
171 InfoBuilder.setVersion(pdb::PdbRaw_ImplVer::PdbImplVC70);
172
173 // Write DXContainer.
174 raw_svector_ostream OS(*Builder.getDXContainerData());
175 write(OS, TT: M.getTargetTriple());
176
177 // Write PDB file.
178 // FIXME(sandboxing): Remove this by routing PDB output through the VFS.
179 auto BypassSandbox = sys::sandbox::scopedDisable();
180 codeview::GUID IgnoredOutGuid;
181 if (Error Err = Builder.commit(Filename: DebugFileName, Guid: &IgnoredOutGuid))
182 reportFatalUsageError(reason: "Couldn't write to PDB file: " +
183 Twine(toString(E: std::move(Err))));
184
185 if (!dxil::PdbInPrivate)
186 return false;
187
188 ErrorOr<std::unique_ptr<MemoryBuffer>> Buf = MemoryBuffer::getFile(
189 Filename: DebugFileName, /*IsText=*/false, /*RequiresNullTerminator=*/false);
190 if (!Buf)
191 reportFatalInternalError(reason: "Failed to read PDB for PRIV embedding");
192
193 appendToCompilerUsed(M, Values: createPrivateDataGlobal(M, Data: (*Buf)->getBuffer()));
194
195 return true;
196}
197
198char DXContainerPDB::ID = 0;
199INITIALIZE_PASS(DXContainerPDB, "dxil-pdb", "DirectX PDB Emitter", false, true)
200
201ModulePass *llvm::createDXContainerPDBPass() { return new DXContainerPDB(); }
202