1 //===------ utils/obj2yaml.cpp - obj2yaml conversion tool -------*- C++ -*-===//
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 "obj2yaml.h"
10 #include "llvm/ADT/StringMap.h"
11 #include "llvm/DebugInfo/CodeView/DebugChecksumsSubsection.h"
12 #include "llvm/DebugInfo/CodeView/DebugStringTableSubsection.h"
13 #include "llvm/DebugInfo/CodeView/StringsAndChecksums.h"
14 #include "llvm/Object/COFF.h"
15 #include "llvm/ObjectYAML/COFFYAML.h"
16 #include "llvm/ObjectYAML/CodeViewYAMLTypes.h"
17 #include "llvm/Support/ErrorHandling.h"
18 #include "llvm/Support/YAMLTraits.h"
19 
20 using namespace llvm;
21 
22 namespace {
23 
24 class COFFDumper {
25   const object::COFFObjectFile &Obj;
26   COFFYAML::Object YAMLObj;
27   template <typename T>
28   void dumpOptionalHeader(T OptionalHeader);
29   void dumpHeader();
30   void dumpSections(unsigned numSections);
31   void dumpSymbols(unsigned numSymbols);
32 
33 public:
34   COFFDumper(const object::COFFObjectFile &Obj);
35   COFFYAML::Object &getYAMLObj();
36 };
37 
38 }
39 
40 COFFDumper::COFFDumper(const object::COFFObjectFile &Obj) : Obj(Obj) {
41   if (const object::pe32_header *PE32Header = Obj.getPE32Header())
42     dumpOptionalHeader(PE32Header);
43   else if (const object::pe32plus_header *PE32PlusHeader =
44                Obj.getPE32PlusHeader())
45     dumpOptionalHeader(PE32PlusHeader);
46 
47   dumpHeader();
48   dumpSections(Obj.getNumberOfSections());
49   dumpSymbols(Obj.getNumberOfSymbols());
50 }
51 
52 template <typename T> void COFFDumper::dumpOptionalHeader(T OptionalHeader) {
53   YAMLObj.OptionalHeader = COFFYAML::PEHeader();
54   YAMLObj.OptionalHeader->Header.AddressOfEntryPoint =
55       OptionalHeader->AddressOfEntryPoint;
56   YAMLObj.OptionalHeader->Header.ImageBase = OptionalHeader->ImageBase;
57   YAMLObj.OptionalHeader->Header.SectionAlignment =
58       OptionalHeader->SectionAlignment;
59   YAMLObj.OptionalHeader->Header.FileAlignment = OptionalHeader->FileAlignment;
60   YAMLObj.OptionalHeader->Header.MajorOperatingSystemVersion =
61       OptionalHeader->MajorOperatingSystemVersion;
62   YAMLObj.OptionalHeader->Header.MinorOperatingSystemVersion =
63       OptionalHeader->MinorOperatingSystemVersion;
64   YAMLObj.OptionalHeader->Header.MajorImageVersion =
65       OptionalHeader->MajorImageVersion;
66   YAMLObj.OptionalHeader->Header.MinorImageVersion =
67       OptionalHeader->MinorImageVersion;
68   YAMLObj.OptionalHeader->Header.MajorSubsystemVersion =
69       OptionalHeader->MajorSubsystemVersion;
70   YAMLObj.OptionalHeader->Header.MinorSubsystemVersion =
71       OptionalHeader->MinorSubsystemVersion;
72   YAMLObj.OptionalHeader->Header.Subsystem = OptionalHeader->Subsystem;
73   YAMLObj.OptionalHeader->Header.DLLCharacteristics =
74       OptionalHeader->DLLCharacteristics;
75   YAMLObj.OptionalHeader->Header.SizeOfStackReserve =
76       OptionalHeader->SizeOfStackReserve;
77   YAMLObj.OptionalHeader->Header.SizeOfStackCommit =
78       OptionalHeader->SizeOfStackCommit;
79   YAMLObj.OptionalHeader->Header.SizeOfHeapReserve =
80       OptionalHeader->SizeOfHeapReserve;
81   YAMLObj.OptionalHeader->Header.SizeOfHeapCommit =
82       OptionalHeader->SizeOfHeapCommit;
83   YAMLObj.OptionalHeader->Header.NumberOfRvaAndSize =
84       OptionalHeader->NumberOfRvaAndSize;
85   unsigned I = 0;
86   for (auto &DestDD : YAMLObj.OptionalHeader->DataDirectories) {
87     const object::data_directory *DD = Obj.getDataDirectory(I++);
88     if (!DD)
89       continue;
90     DestDD = COFF::DataDirectory();
91     DestDD->RelativeVirtualAddress = DD->RelativeVirtualAddress;
92     DestDD->Size = DD->Size;
93   }
94 }
95 
96 void COFFDumper::dumpHeader() {
97   YAMLObj.Header.Machine = Obj.getMachine();
98   YAMLObj.Header.Characteristics = Obj.getCharacteristics();
99 }
100 
101 static void
102 initializeFileAndStringTable(const llvm::object::COFFObjectFile &Obj,
103                              codeview::StringsAndChecksumsRef &SC) {
104 
105   ExitOnError Err("invalid .debug$S section");
106   // Iterate all .debug$S sections looking for the checksums and string table.
107   // Exit as soon as both sections are found.
108   for (const auto &S : Obj.sections()) {
109     if (SC.hasStrings() && SC.hasChecksums())
110       break;
111 
112     Expected<StringRef> SectionNameOrErr = S.getName();
113     if (!SectionNameOrErr) {
114       consumeError(SectionNameOrErr.takeError());
115       continue;
116     }
117 
118     ArrayRef<uint8_t> sectionData;
119     if ((*SectionNameOrErr) != ".debug$S")
120       continue;
121 
122     const object::coff_section *COFFSection = Obj.getCOFFSection(S);
123 
124     cantFail(Obj.getSectionContents(COFFSection, sectionData));
125 
126     BinaryStreamReader Reader(sectionData, support::little);
127     uint32_t Magic;
128 
129     Err(Reader.readInteger(Magic));
130     assert(Magic == COFF::DEBUG_SECTION_MAGIC && "Invalid .debug$S section!");
131 
132     codeview::DebugSubsectionArray Subsections;
133     Err(Reader.readArray(Subsections, Reader.bytesRemaining()));
134 
135     SC.initialize(Subsections);
136   }
137 }
138 
139 void COFFDumper::dumpSections(unsigned NumSections) {
140   std::vector<COFFYAML::Section> &YAMLSections = YAMLObj.Sections;
141   codeview::StringsAndChecksumsRef SC;
142   initializeFileAndStringTable(Obj, SC);
143 
144   ExitOnError Err("invalid section table");
145   StringMap<bool> SymbolUnique;
146   for (const auto &S : Obj.symbols()) {
147     StringRef Name = Err(Obj.getSymbolName(Obj.getCOFFSymbol(S)));
148     StringMap<bool>::iterator It;
149     bool Inserted;
150     std::tie(It, Inserted) = SymbolUnique.insert(std::make_pair(Name, true));
151     if (!Inserted)
152       It->second = false;
153   }
154 
155   for (const auto &ObjSection : Obj.sections()) {
156     const object::coff_section *COFFSection = Obj.getCOFFSection(ObjSection);
157     COFFYAML::Section NewYAMLSection;
158 
159     if (Expected<StringRef> NameOrErr = ObjSection.getName())
160       NewYAMLSection.Name = *NameOrErr;
161     else
162       consumeError(NameOrErr.takeError());
163 
164     NewYAMLSection.Header.Characteristics = COFFSection->Characteristics;
165     NewYAMLSection.Header.VirtualAddress = COFFSection->VirtualAddress;
166     NewYAMLSection.Header.VirtualSize = COFFSection->VirtualSize;
167     NewYAMLSection.Header.NumberOfLineNumbers =
168         COFFSection->NumberOfLinenumbers;
169     NewYAMLSection.Header.NumberOfRelocations =
170         COFFSection->NumberOfRelocations;
171     NewYAMLSection.Header.PointerToLineNumbers =
172         COFFSection->PointerToLinenumbers;
173     NewYAMLSection.Header.PointerToRawData = COFFSection->PointerToRawData;
174     NewYAMLSection.Header.PointerToRelocations =
175         COFFSection->PointerToRelocations;
176     NewYAMLSection.Header.SizeOfRawData = COFFSection->SizeOfRawData;
177     uint32_t Shift = (COFFSection->Characteristics >> 20) & 0xF;
178     NewYAMLSection.Alignment = (1U << Shift) >> 1;
179     assert(NewYAMLSection.Alignment <= 8192);
180 
181     ArrayRef<uint8_t> sectionData;
182     if (!ObjSection.isBSS())
183       cantFail(Obj.getSectionContents(COFFSection, sectionData));
184     NewYAMLSection.SectionData = yaml::BinaryRef(sectionData);
185 
186     if (NewYAMLSection.Name == ".debug$S")
187       NewYAMLSection.DebugS = CodeViewYAML::fromDebugS(sectionData, SC);
188     else if (NewYAMLSection.Name == ".debug$T")
189       NewYAMLSection.DebugT = CodeViewYAML::fromDebugT(sectionData,
190                                                        NewYAMLSection.Name);
191     else if (NewYAMLSection.Name == ".debug$P")
192       NewYAMLSection.DebugP = CodeViewYAML::fromDebugT(sectionData,
193                                                        NewYAMLSection.Name);
194     else if (NewYAMLSection.Name == ".debug$H")
195       NewYAMLSection.DebugH = CodeViewYAML::fromDebugH(sectionData);
196 
197     std::vector<COFFYAML::Relocation> Relocations;
198     for (const auto &Reloc : ObjSection.relocations()) {
199       const object::coff_relocation *reloc = Obj.getCOFFRelocation(Reloc);
200       COFFYAML::Relocation Rel;
201       object::symbol_iterator Sym = Reloc.getSymbol();
202       Expected<StringRef> SymbolNameOrErr = Sym->getName();
203       if (!SymbolNameOrErr) {
204        std::string Buf;
205        raw_string_ostream OS(Buf);
206        logAllUnhandledErrors(SymbolNameOrErr.takeError(), OS);
207        OS.flush();
208        report_fatal_error(Buf);
209       }
210       if (SymbolUnique.lookup(*SymbolNameOrErr))
211         Rel.SymbolName = *SymbolNameOrErr;
212       else
213         Rel.SymbolTableIndex = reloc->SymbolTableIndex;
214       Rel.VirtualAddress = reloc->VirtualAddress;
215       Rel.Type = reloc->Type;
216       Relocations.push_back(Rel);
217     }
218     NewYAMLSection.Relocations = Relocations;
219     YAMLSections.push_back(NewYAMLSection);
220   }
221 }
222 
223 static void
224 dumpFunctionDefinition(COFFYAML::Symbol *Sym,
225                        const object::coff_aux_function_definition *ObjFD) {
226   COFF::AuxiliaryFunctionDefinition YAMLFD;
227   YAMLFD.TagIndex = ObjFD->TagIndex;
228   YAMLFD.TotalSize = ObjFD->TotalSize;
229   YAMLFD.PointerToLinenumber = ObjFD->PointerToLinenumber;
230   YAMLFD.PointerToNextFunction = ObjFD->PointerToNextFunction;
231 
232   Sym->FunctionDefinition = YAMLFD;
233 }
234 
235 static void
236 dumpbfAndEfLineInfo(COFFYAML::Symbol *Sym,
237                     const object::coff_aux_bf_and_ef_symbol *ObjBES) {
238   COFF::AuxiliarybfAndefSymbol YAMLAAS;
239   YAMLAAS.Linenumber = ObjBES->Linenumber;
240   YAMLAAS.PointerToNextFunction = ObjBES->PointerToNextFunction;
241 
242   Sym->bfAndefSymbol = YAMLAAS;
243 }
244 
245 static void dumpWeakExternal(COFFYAML::Symbol *Sym,
246                              const object::coff_aux_weak_external *ObjWE) {
247   COFF::AuxiliaryWeakExternal YAMLWE;
248   YAMLWE.TagIndex = ObjWE->TagIndex;
249   YAMLWE.Characteristics = ObjWE->Characteristics;
250 
251   Sym->WeakExternal = YAMLWE;
252 }
253 
254 static void
255 dumpSectionDefinition(COFFYAML::Symbol *Sym,
256                       const object::coff_aux_section_definition *ObjSD,
257                       bool IsBigObj) {
258   COFF::AuxiliarySectionDefinition YAMLASD;
259   int32_t AuxNumber = ObjSD->getNumber(IsBigObj);
260   YAMLASD.Length = ObjSD->Length;
261   YAMLASD.NumberOfRelocations = ObjSD->NumberOfRelocations;
262   YAMLASD.NumberOfLinenumbers = ObjSD->NumberOfLinenumbers;
263   YAMLASD.CheckSum = ObjSD->CheckSum;
264   YAMLASD.Number = AuxNumber;
265   YAMLASD.Selection = ObjSD->Selection;
266 
267   Sym->SectionDefinition = YAMLASD;
268 }
269 
270 static void
271 dumpCLRTokenDefinition(COFFYAML::Symbol *Sym,
272                        const object::coff_aux_clr_token *ObjCLRToken) {
273   COFF::AuxiliaryCLRToken YAMLCLRToken;
274   YAMLCLRToken.AuxType = ObjCLRToken->AuxType;
275   YAMLCLRToken.SymbolTableIndex = ObjCLRToken->SymbolTableIndex;
276 
277   Sym->CLRToken = YAMLCLRToken;
278 }
279 
280 void COFFDumper::dumpSymbols(unsigned NumSymbols) {
281   ExitOnError Err("invalid symbol table");
282 
283   std::vector<COFFYAML::Symbol> &Symbols = YAMLObj.Symbols;
284   for (const auto &S : Obj.symbols()) {
285     object::COFFSymbolRef Symbol = Obj.getCOFFSymbol(S);
286     COFFYAML::Symbol Sym;
287     Sym.Name = Err(Obj.getSymbolName(Symbol));
288     Sym.SimpleType = COFF::SymbolBaseType(Symbol.getBaseType());
289     Sym.ComplexType = COFF::SymbolComplexType(Symbol.getComplexType());
290     Sym.Header.StorageClass = Symbol.getStorageClass();
291     Sym.Header.Value = Symbol.getValue();
292     Sym.Header.SectionNumber = Symbol.getSectionNumber();
293     Sym.Header.NumberOfAuxSymbols = Symbol.getNumberOfAuxSymbols();
294 
295     if (Symbol.getNumberOfAuxSymbols() > 0) {
296       ArrayRef<uint8_t> AuxData = Obj.getSymbolAuxData(Symbol);
297       if (Symbol.isFunctionDefinition()) {
298         // This symbol represents a function definition.
299         assert(Symbol.getNumberOfAuxSymbols() == 1 &&
300                "Expected a single aux symbol to describe this function!");
301 
302         const object::coff_aux_function_definition *ObjFD =
303             reinterpret_cast<const object::coff_aux_function_definition *>(
304                 AuxData.data());
305         dumpFunctionDefinition(&Sym, ObjFD);
306       } else if (Symbol.isFunctionLineInfo()) {
307         // This symbol describes function line number information.
308         assert(Symbol.getNumberOfAuxSymbols() == 1 &&
309                "Expected a single aux symbol to describe this function!");
310 
311         const object::coff_aux_bf_and_ef_symbol *ObjBES =
312             reinterpret_cast<const object::coff_aux_bf_and_ef_symbol *>(
313                 AuxData.data());
314         dumpbfAndEfLineInfo(&Sym, ObjBES);
315       } else if (Symbol.isAnyUndefined()) {
316         // This symbol represents a weak external definition.
317         assert(Symbol.getNumberOfAuxSymbols() == 1 &&
318                "Expected a single aux symbol to describe this weak symbol!");
319 
320         const object::coff_aux_weak_external *ObjWE =
321             reinterpret_cast<const object::coff_aux_weak_external *>(
322                 AuxData.data());
323         dumpWeakExternal(&Sym, ObjWE);
324       } else if (Symbol.isFileRecord()) {
325         // This symbol represents a file record.
326         Sym.File = StringRef(reinterpret_cast<const char *>(AuxData.data()),
327                              Symbol.getNumberOfAuxSymbols() *
328                                  Obj.getSymbolTableEntrySize())
329                        .rtrim(StringRef("\0", /*length=*/1));
330       } else if (Symbol.isSectionDefinition()) {
331         // This symbol represents a section definition.
332         assert(Symbol.getNumberOfAuxSymbols() == 1 &&
333                "Expected a single aux symbol to describe this section!");
334 
335         const object::coff_aux_section_definition *ObjSD =
336             reinterpret_cast<const object::coff_aux_section_definition *>(
337                 AuxData.data());
338         dumpSectionDefinition(&Sym, ObjSD, Symbol.isBigObj());
339       } else if (Symbol.isCLRToken()) {
340         // This symbol represents a CLR token definition.
341         assert(Symbol.getNumberOfAuxSymbols() == 1 &&
342                "Expected a single aux symbol to describe this CLR Token!");
343 
344         const object::coff_aux_clr_token *ObjCLRToken =
345             reinterpret_cast<const object::coff_aux_clr_token *>(
346                 AuxData.data());
347         dumpCLRTokenDefinition(&Sym, ObjCLRToken);
348       } else {
349         llvm_unreachable("Unhandled auxiliary symbol!");
350       }
351     }
352     Symbols.push_back(Sym);
353   }
354 }
355 
356 COFFYAML::Object &COFFDumper::getYAMLObj() {
357   return YAMLObj;
358 }
359 
360 std::error_code coff2yaml(raw_ostream &Out, const object::COFFObjectFile &Obj) {
361   COFFDumper Dumper(Obj);
362 
363   yaml::Output Yout(Out);
364   Yout << Dumper.getYAMLObj();
365 
366   return std::error_code();
367 }
368