]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/lld/COFF/PDB.cpp
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r305575, and update
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / lld / COFF / PDB.cpp
1 //===- PDB.cpp ------------------------------------------------------------===//
2 //
3 //                             The LLVM Linker
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "PDB.h"
11 #include "Chunks.h"
12 #include "Config.h"
13 #include "Error.h"
14 #include "SymbolTable.h"
15 #include "Symbols.h"
16 #include "llvm/DebugInfo/CodeView/CVDebugRecord.h"
17 #include "llvm/DebugInfo/CodeView/CVTypeVisitor.h"
18 #include "llvm/DebugInfo/CodeView/LazyRandomTypeCollection.h"
19 #include "llvm/DebugInfo/CodeView/SymbolDumper.h"
20 #include "llvm/DebugInfo/CodeView/TypeDatabase.h"
21 #include "llvm/DebugInfo/CodeView/TypeDumpVisitor.h"
22 #include "llvm/DebugInfo/CodeView/TypeStreamMerger.h"
23 #include "llvm/DebugInfo/CodeView/TypeTableBuilder.h"
24 #include "llvm/DebugInfo/MSF/MSFBuilder.h"
25 #include "llvm/DebugInfo/MSF/MSFCommon.h"
26 #include "llvm/DebugInfo/PDB/Native/DbiStream.h"
27 #include "llvm/DebugInfo/PDB/Native/DbiStreamBuilder.h"
28 #include "llvm/DebugInfo/PDB/Native/InfoStream.h"
29 #include "llvm/DebugInfo/PDB/Native/InfoStreamBuilder.h"
30 #include "llvm/DebugInfo/PDB/Native/PDBFile.h"
31 #include "llvm/DebugInfo/PDB/Native/PDBFileBuilder.h"
32 #include "llvm/DebugInfo/PDB/Native/DbiModuleDescriptorBuilder.h"
33 #include "llvm/DebugInfo/PDB/Native/PDBStringTableBuilder.h"
34 #include "llvm/DebugInfo/PDB/Native/PDBTypeServerHandler.h"
35 #include "llvm/DebugInfo/PDB/Native/TpiStream.h"
36 #include "llvm/DebugInfo/PDB/Native/TpiStreamBuilder.h"
37 #include "llvm/Object/COFF.h"
38 #include "llvm/Support/BinaryByteStream.h"
39 #include "llvm/Support/Endian.h"
40 #include "llvm/Support/FileOutputBuffer.h"
41 #include "llvm/Support/Path.h"
42 #include "llvm/Support/ScopedPrinter.h"
43 #include <memory>
44
45 using namespace lld;
46 using namespace lld::coff;
47 using namespace llvm;
48 using namespace llvm::codeview;
49 using namespace llvm::support;
50 using namespace llvm::support::endian;
51
52 using llvm::object::coff_section;
53
54 static ExitOnError ExitOnErr;
55
56 // Returns a list of all SectionChunks.
57 static void addSectionContribs(SymbolTable *Symtab, pdb::DbiStreamBuilder &DbiBuilder) {
58   for (Chunk *C : Symtab->getChunks())
59     if (auto *SC = dyn_cast<SectionChunk>(C))
60       DbiBuilder.addSectionContrib(SC->File->ModuleDBI, SC->Header);
61 }
62
63 static SectionChunk *findByName(std::vector<SectionChunk *> &Sections,
64                                 StringRef Name) {
65   for (SectionChunk *C : Sections)
66     if (C->getSectionName() == Name)
67       return C;
68   return nullptr;
69 }
70
71 static ArrayRef<uint8_t> getDebugSection(ObjectFile *File, StringRef SecName) {
72   SectionChunk *Sec = findByName(File->getDebugChunks(), SecName);
73   if (!Sec)
74     return {};
75
76   // First 4 bytes are section magic.
77   ArrayRef<uint8_t> Data = Sec->getContents();
78   if (Data.size() < 4)
79     fatal(SecName + " too short");
80   if (read32le(Data.data()) != COFF::DEBUG_SECTION_MAGIC)
81     fatal(SecName + " has an invalid magic");
82   return Data.slice(4);
83 }
84
85 static void addTypeInfo(pdb::TpiStreamBuilder &TpiBuilder,
86                         codeview::TypeTableBuilder &TypeTable) {
87   // Start the TPI or IPI stream header.
88   TpiBuilder.setVersionHeader(pdb::PdbTpiV80);
89
90   // Flatten the in memory type table.
91   TypeTable.ForEachRecord([&](TypeIndex TI, ArrayRef<uint8_t> Rec) {
92     // FIXME: Hash types.
93     TpiBuilder.addTypeRecord(Rec, None);
94   });
95 }
96
97 // Add all object files to the PDB. Merge .debug$T sections into IpiData and
98 // TpiData.
99 static void addObjectsToPDB(SymbolTable *Symtab, pdb::PDBFileBuilder &Builder,
100                             codeview::TypeTableBuilder &TypeTable,
101                             codeview::TypeTableBuilder &IDTable) {
102   // Follow type servers.  If the same type server is encountered more than
103   // once for this instance of `PDBTypeServerHandler` (for example if many
104   // object files reference the same TypeServer), the types from the
105   // TypeServer will only be visited once.
106   pdb::PDBTypeServerHandler Handler;
107
108   // Visit all .debug$T sections to add them to Builder.
109   for (ObjectFile *File : Symtab->ObjectFiles) {
110     // Add a module descriptor for every object file. We need to put an absolute
111     // path to the object into the PDB. If this is a plain object, we make its
112     // path absolute. If it's an object in an archive, we make the archive path
113     // absolute.
114     bool InArchive = !File->ParentName.empty();
115     SmallString<128> Path = InArchive ? File->ParentName : File->getName();
116     sys::fs::make_absolute(Path);
117     StringRef Name = InArchive ? File->getName() : StringRef(Path);
118     File->ModuleDBI = &ExitOnErr(Builder.getDbiBuilder().addModuleInfo(Name));
119     File->ModuleDBI->setObjFileName(Path);
120
121     // FIXME: Walk the .debug$S sections and add them. Do things like recording
122     // source files.
123
124     ArrayRef<uint8_t> Data = getDebugSection(File, ".debug$T");
125     if (Data.empty())
126       continue;
127
128     BinaryByteStream Stream(Data, support::little);
129     codeview::CVTypeArray Types;
130     BinaryStreamReader Reader(Stream);
131     SmallVector<TypeIndex, 128> SourceToDest;
132     Handler.addSearchPath(llvm::sys::path::parent_path(File->getName()));
133     if (auto EC = Reader.readArray(Types, Reader.getLength()))
134       fatal(EC, "Reader::readArray failed");
135     if (auto Err = codeview::mergeTypeAndIdRecords(
136             IDTable, TypeTable, SourceToDest, &Handler, Types))
137       fatal(Err, "codeview::mergeTypeStreams failed");
138   }
139
140   // Construct TPI stream contents.
141   addTypeInfo(Builder.getTpiBuilder(), TypeTable);
142
143   // Construct IPI stream contents.
144   addTypeInfo(Builder.getIpiBuilder(), IDTable);
145 }
146
147 static void dumpDebugT(ScopedPrinter &W, ObjectFile *File) {
148   ListScope LS(W, "DebugT");
149   ArrayRef<uint8_t> Data = getDebugSection(File, ".debug$T");
150   if (Data.empty())
151     return;
152
153   LazyRandomTypeCollection Types(Data, 100);
154   TypeDumpVisitor TDV(Types, &W, false);
155   // Use a default implementation that does not follow type servers and instead
156   // just dumps the contents of the TypeServer2 record.
157   if (auto EC = codeview::visitTypeStream(Types, TDV))
158     fatal(EC, "CVTypeDumper::dump failed");
159 }
160
161 static void dumpDebugS(ScopedPrinter &W, ObjectFile *File) {
162   ListScope LS(W, "DebugS");
163   ArrayRef<uint8_t> Data = getDebugSection(File, ".debug$S");
164   if (Data.empty())
165     return;
166
167   BinaryByteStream Stream(Data, llvm::support::little);
168   CVSymbolArray Symbols;
169   BinaryStreamReader Reader(Stream);
170   if (auto EC = Reader.readArray(Symbols, Reader.getLength()))
171     fatal(EC, "StreamReader.readArray<CVSymbolArray> failed");
172
173   TypeDatabase TDB(0);
174   CVSymbolDumper SymbolDumper(W, TDB, CodeViewContainer::ObjectFile, nullptr,
175                               false);
176   if (auto EC = SymbolDumper.dump(Symbols))
177     fatal(EC, "CVSymbolDumper::dump failed");
178 }
179
180 // Dump CodeView debug info. This is for debugging.
181 static void dumpCodeView(SymbolTable *Symtab) {
182   ScopedPrinter W(outs());
183
184   for (ObjectFile *File : Symtab->ObjectFiles) {
185     dumpDebugT(W, File);
186     dumpDebugS(W, File);
187   }
188 }
189
190 // Creates a PDB file.
191 void coff::createPDB(StringRef Path, SymbolTable *Symtab,
192                      ArrayRef<uint8_t> SectionTable,
193                      const llvm::codeview::DebugInfo *DI) {
194   if (Config->DumpPdb)
195     dumpCodeView(Symtab);
196
197   BumpPtrAllocator Alloc;
198   pdb::PDBFileBuilder Builder(Alloc);
199   ExitOnErr(Builder.initialize(4096)); // 4096 is blocksize
200
201   // Create streams in MSF for predefined streams, namely
202   // PDB, TPI, DBI and IPI.
203   for (int I = 0; I < (int)pdb::kSpecialStreamCount; ++I)
204     ExitOnErr(Builder.getMsfBuilder().addStream(0));
205
206   // Add an Info stream.
207   auto &InfoBuilder = Builder.getInfoBuilder();
208   InfoBuilder.setAge(DI ? DI->PDB70.Age : 0);
209
210   pdb::PDB_UniqueId uuid{};
211   if (DI)
212     memcpy(&uuid, &DI->PDB70.Signature, sizeof(uuid));
213   InfoBuilder.setGuid(uuid);
214   // Should be the current time, but set 0 for reproducibilty.
215   InfoBuilder.setSignature(0);
216   InfoBuilder.setVersion(pdb::PdbRaw_ImplVer::PdbImplVC70);
217
218   // Add an empty DPI stream.
219   pdb::DbiStreamBuilder &DbiBuilder = Builder.getDbiBuilder();
220   DbiBuilder.setVersionHeader(pdb::PdbDbiV110);
221
222   codeview::TypeTableBuilder TypeTable(BAlloc);
223   codeview::TypeTableBuilder IDTable(BAlloc);
224   addObjectsToPDB(Symtab, Builder, TypeTable, IDTable);
225
226   // Add Section Contributions.
227   addSectionContribs(Symtab, DbiBuilder);
228
229   // Add Section Map stream.
230   ArrayRef<object::coff_section> Sections = {
231       (const object::coff_section *)SectionTable.data(),
232       SectionTable.size() / sizeof(object::coff_section)};
233   std::vector<pdb::SecMapEntry> SectionMap =
234       pdb::DbiStreamBuilder::createSectionMap(Sections);
235   DbiBuilder.setSectionMap(SectionMap);
236
237   ExitOnErr(DbiBuilder.addModuleInfo("* Linker *"));
238
239   // Add COFF section header stream.
240   ExitOnErr(
241       DbiBuilder.addDbgStream(pdb::DbgHeaderType::SectionHdr, SectionTable));
242
243   // Write to a file.
244   ExitOnErr(Builder.commit(Path));
245 }