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