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