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
20using namespace llvm;
21
22namespace {
23
24class 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
33public:
34 COFFDumper(const object::COFFObjectFile &Obj);
35 COFFYAML::Object &getYAMLObj();
36};
37
38}
39
40COFFDumper::COFFDumper(const object::COFFObjectFile &Obj) : Obj(Obj) {
41 if (const object::pe32_header *PE32Header = Obj.getPE32Header())
42 dumpOptionalHeader(OptionalHeader: PE32Header);
43 else if (const object::pe32plus_header *PE32PlusHeader =
44 Obj.getPE32PlusHeader())
45 dumpOptionalHeader(OptionalHeader: PE32PlusHeader);
46
47 dumpHeader();
48 dumpSections(numSections: Obj.getNumberOfSections());
49 dumpSymbols(numSymbols: Obj.getNumberOfSymbols());
50}
51
52template <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(index: I++);
88 if (!DD)
89 continue;
90 DestDD = COFF::DataDirectory();
91 DestDD->RelativeVirtualAddress = DD->RelativeVirtualAddress;
92 DestDD->Size = DD->Size;
93 }
94}
95
96void COFFDumper::dumpHeader() {
97 YAMLObj.Header.Machine = Obj.getMachine();
98 YAMLObj.Header.TimeDateStamp = Obj.getTimeDateStamp();
99 YAMLObj.Header.Characteristics = Obj.getCharacteristics();
100}
101
102static void
103initializeFileAndStringTable(const llvm::object::COFFObjectFile &Obj,
104 codeview::StringsAndChecksumsRef &SC) {
105
106 ExitOnError Err("invalid .debug$S section");
107 // Iterate all .debug$S sections looking for the checksums and string table.
108 // Exit as soon as both sections are found.
109 for (const auto &S : Obj.sections()) {
110 if (SC.hasStrings() && SC.hasChecksums())
111 break;
112
113 Expected<StringRef> SectionNameOrErr = S.getName();
114 if (!SectionNameOrErr) {
115 consumeError(Err: SectionNameOrErr.takeError());
116 continue;
117 }
118
119 ArrayRef<uint8_t> sectionData;
120 if ((*SectionNameOrErr) != ".debug$S")
121 continue;
122
123 const object::coff_section *COFFSection = Obj.getCOFFSection(Section: S);
124
125 cantFail(Err: Obj.getSectionContents(Sec: COFFSection, Res&: sectionData));
126
127 BinaryStreamReader Reader(sectionData, llvm::endianness::little);
128 uint32_t Magic;
129
130 Err(Reader.readInteger(Dest&: Magic));
131 assert(Magic == COFF::DEBUG_SECTION_MAGIC && "Invalid .debug$S section!");
132
133 codeview::DebugSubsectionArray Subsections;
134 Err(Reader.readArray(Array&: Subsections, Size: Reader.bytesRemaining()));
135
136 SC.initialize(FragmentRange&: Subsections);
137 }
138}
139
140static void dumpBBAddrMap(COFFYAML::Section &Sec, ArrayRef<uint8_t> Content,
141 unsigned AddressSize) {
142 if (Content.empty()) {
143 Sec.SectionData.reset();
144 return;
145 }
146
147 ExitOnError Err("invalid .llvm_bb_addr_map section: ");
148 Err(BBAddrMapYAML::decodePayload(Content, Endian: llvm::endianness::little,
149 AddressSize, Entries&: Sec.BBAddrMapEntries,
150 PGOAnalyses&: Sec.PGOAnalyses));
151
152 // COFFYAML rejects Entries with SectionData or SizeOfRawData, since yaml2obj
153 // derives both from Entries.
154 if (Sec.BBAddrMapEntries) {
155 Sec.SectionData.reset();
156 Sec.Header.SizeOfRawData = 0;
157 }
158}
159
160void COFFDumper::dumpSections(unsigned NumSections) {
161 std::vector<COFFYAML::Section> &YAMLSections = YAMLObj.Sections;
162 codeview::StringsAndChecksumsRef SC;
163 initializeFileAndStringTable(Obj, SC);
164
165 ExitOnError Err("invalid section table");
166 StringMap<bool> SymbolUnique;
167 for (const auto &S : Obj.symbols()) {
168 StringRef Name = Err(Obj.getSymbolName(Symbol: Obj.getCOFFSymbol(Symbol: S)));
169 StringMap<bool>::iterator It;
170 bool Inserted;
171 std::tie(args&: It, args&: Inserted) = SymbolUnique.insert(KV: std::make_pair(x&: Name, y: true));
172 if (!Inserted)
173 It->second = false;
174 }
175
176 for (const auto &ObjSection : Obj.sections()) {
177 const object::coff_section *COFFSection = Obj.getCOFFSection(Section: ObjSection);
178 COFFYAML::Section NewYAMLSection;
179
180 if (Expected<StringRef> NameOrErr = ObjSection.getName())
181 NewYAMLSection.Name = *NameOrErr;
182 else
183 consumeError(Err: NameOrErr.takeError());
184
185 NewYAMLSection.Header.Characteristics = COFFSection->Characteristics;
186 NewYAMLSection.Header.VirtualAddress = COFFSection->VirtualAddress;
187 NewYAMLSection.Header.VirtualSize = COFFSection->VirtualSize;
188 NewYAMLSection.Header.NumberOfLineNumbers =
189 COFFSection->NumberOfLinenumbers;
190 NewYAMLSection.Header.NumberOfRelocations =
191 COFFSection->NumberOfRelocations;
192 NewYAMLSection.Header.PointerToLineNumbers =
193 COFFSection->PointerToLinenumbers;
194 NewYAMLSection.Header.PointerToRawData = COFFSection->PointerToRawData;
195 NewYAMLSection.Header.PointerToRelocations =
196 COFFSection->PointerToRelocations;
197 NewYAMLSection.Header.SizeOfRawData = COFFSection->SizeOfRawData;
198 uint32_t Shift = (COFFSection->Characteristics >> 20) & 0xF;
199 NewYAMLSection.Alignment = (1U << Shift) >> 1;
200 assert(NewYAMLSection.Alignment <= 8192);
201
202 ArrayRef<uint8_t> sectionData;
203 if (!ObjSection.isBSS())
204 cantFail(Err: Obj.getSectionContents(Sec: COFFSection, Res&: sectionData));
205 NewYAMLSection.SectionData = yaml::BinaryRef(sectionData);
206
207 if (NewYAMLSection.Name == ".debug$S")
208 NewYAMLSection.DebugS = CodeViewYAML::fromDebugS(Data: sectionData, SC);
209 else if (NewYAMLSection.Name == ".debug$T")
210 NewYAMLSection.DebugT = CodeViewYAML::fromDebugT(DebugTorP: sectionData,
211 SectionName: NewYAMLSection.Name);
212 else if (NewYAMLSection.Name == ".debug$P")
213 NewYAMLSection.DebugP = CodeViewYAML::fromDebugT(DebugTorP: sectionData,
214 SectionName: NewYAMLSection.Name);
215 else if (NewYAMLSection.Name == ".debug$H")
216 NewYAMLSection.DebugH = CodeViewYAML::fromDebugH(DebugH: sectionData);
217 else if (NewYAMLSection.Name == ".llvm_bb_addr_map")
218 dumpBBAddrMap(Sec&: NewYAMLSection, Content: sectionData,
219 AddressSize: COFF::is64Bit(Machine: Obj.getMachine()) ? 8 : 4);
220
221 std::vector<COFFYAML::Relocation> Relocations;
222 for (const auto &Reloc : ObjSection.relocations()) {
223 const object::coff_relocation *reloc = Obj.getCOFFRelocation(Reloc);
224 COFFYAML::Relocation Rel;
225 object::symbol_iterator Sym = Reloc.getSymbol();
226 Expected<StringRef> SymbolNameOrErr = Sym->getName();
227 if (!SymbolNameOrErr) {
228 std::string Buf;
229 raw_string_ostream OS(Buf);
230 logAllUnhandledErrors(E: SymbolNameOrErr.takeError(), OS);
231 report_fatal_error(reason: Twine(OS.str()));
232 }
233 if (SymbolUnique.lookup(Key: *SymbolNameOrErr))
234 Rel.SymbolName = *SymbolNameOrErr;
235 else
236 Rel.SymbolTableIndex = reloc->SymbolTableIndex;
237 Rel.VirtualAddress = reloc->VirtualAddress;
238 Rel.Type = reloc->Type;
239 Relocations.push_back(x: Rel);
240 }
241 NewYAMLSection.Relocations = Relocations;
242 YAMLSections.push_back(x: NewYAMLSection);
243 }
244}
245
246static void
247dumpFunctionDefinition(COFFYAML::Symbol *Sym,
248 const object::coff_aux_function_definition *ObjFD) {
249 COFF::AuxiliaryFunctionDefinition YAMLFD;
250 YAMLFD.TagIndex = ObjFD->TagIndex;
251 YAMLFD.TotalSize = ObjFD->TotalSize;
252 YAMLFD.PointerToLinenumber = ObjFD->PointerToLinenumber;
253 YAMLFD.PointerToNextFunction = ObjFD->PointerToNextFunction;
254
255 Sym->FunctionDefinition = YAMLFD;
256}
257
258static void
259dumpbfAndEfLineInfo(COFFYAML::Symbol *Sym,
260 const object::coff_aux_bf_and_ef_symbol *ObjBES) {
261 COFF::AuxiliarybfAndefSymbol YAMLAAS;
262 YAMLAAS.Linenumber = ObjBES->Linenumber;
263 YAMLAAS.PointerToNextFunction = ObjBES->PointerToNextFunction;
264
265 Sym->bfAndefSymbol = YAMLAAS;
266}
267
268static void dumpWeakExternal(COFFYAML::Symbol *Sym,
269 const object::coff_aux_weak_external *ObjWE) {
270 COFF::AuxiliaryWeakExternal YAMLWE;
271 YAMLWE.TagIndex = ObjWE->TagIndex;
272 YAMLWE.Characteristics = ObjWE->Characteristics;
273
274 Sym->WeakExternal = YAMLWE;
275}
276
277static void
278dumpSectionDefinition(COFFYAML::Symbol *Sym,
279 const object::coff_aux_section_definition *ObjSD,
280 bool IsBigObj) {
281 COFF::AuxiliarySectionDefinition YAMLASD;
282 int32_t AuxNumber = ObjSD->getNumber(IsBigObj);
283 YAMLASD.Length = ObjSD->Length;
284 YAMLASD.NumberOfRelocations = ObjSD->NumberOfRelocations;
285 YAMLASD.NumberOfLinenumbers = ObjSD->NumberOfLinenumbers;
286 YAMLASD.CheckSum = ObjSD->CheckSum;
287 YAMLASD.Number = AuxNumber;
288 YAMLASD.Selection = ObjSD->Selection;
289
290 Sym->SectionDefinition = YAMLASD;
291}
292
293static void
294dumpCLRTokenDefinition(COFFYAML::Symbol *Sym,
295 const object::coff_aux_clr_token *ObjCLRToken) {
296 COFF::AuxiliaryCLRToken YAMLCLRToken;
297 YAMLCLRToken.AuxType = ObjCLRToken->AuxType;
298 YAMLCLRToken.SymbolTableIndex = ObjCLRToken->SymbolTableIndex;
299
300 Sym->CLRToken = YAMLCLRToken;
301}
302
303void COFFDumper::dumpSymbols(unsigned NumSymbols) {
304 ExitOnError Err("invalid symbol table");
305
306 std::vector<COFFYAML::Symbol> &Symbols = YAMLObj.Symbols;
307 for (const auto &S : Obj.symbols()) {
308 object::COFFSymbolRef Symbol = Obj.getCOFFSymbol(Symbol: S);
309 COFFYAML::Symbol Sym;
310 Sym.Name = Err(Obj.getSymbolName(Symbol));
311 Sym.SimpleType = COFF::SymbolBaseType(Symbol.getBaseType());
312 Sym.ComplexType = COFF::SymbolComplexType(Symbol.getComplexType());
313 Sym.Header.StorageClass = Symbol.getStorageClass();
314 Sym.Header.Value = Symbol.getValue();
315 Sym.Header.SectionNumber = Symbol.getSectionNumber();
316 Sym.Header.NumberOfAuxSymbols = Symbol.getNumberOfAuxSymbols();
317
318 if (Symbol.getNumberOfAuxSymbols() > 0) {
319 ArrayRef<uint8_t> AuxData = Obj.getSymbolAuxData(Symbol);
320 if (Symbol.isFunctionDefinition()) {
321 // This symbol represents a function definition.
322 assert(Symbol.getNumberOfAuxSymbols() == 1 &&
323 "Expected a single aux symbol to describe this function!");
324
325 const object::coff_aux_function_definition *ObjFD =
326 reinterpret_cast<const object::coff_aux_function_definition *>(
327 AuxData.data());
328 dumpFunctionDefinition(Sym: &Sym, ObjFD);
329 } else if (Symbol.isFunctionLineInfo()) {
330 // This symbol describes function line number information.
331 assert(Symbol.getNumberOfAuxSymbols() == 1 &&
332 "Expected a single aux symbol to describe this function!");
333
334 const object::coff_aux_bf_and_ef_symbol *ObjBES =
335 reinterpret_cast<const object::coff_aux_bf_and_ef_symbol *>(
336 AuxData.data());
337 dumpbfAndEfLineInfo(Sym: &Sym, ObjBES);
338 } else if (Symbol.isAnyUndefined()) {
339 // This symbol represents a weak external definition.
340 assert(Symbol.getNumberOfAuxSymbols() == 1 &&
341 "Expected a single aux symbol to describe this weak symbol!");
342
343 const object::coff_aux_weak_external *ObjWE =
344 reinterpret_cast<const object::coff_aux_weak_external *>(
345 AuxData.data());
346 dumpWeakExternal(Sym: &Sym, ObjWE);
347 } else if (Symbol.isFileRecord()) {
348 // This symbol represents a file record.
349 Sym.File = StringRef(reinterpret_cast<const char *>(AuxData.data()),
350 Symbol.getNumberOfAuxSymbols() *
351 Obj.getSymbolTableEntrySize())
352 .rtrim(Chars: StringRef("\0", /*length=*/1));
353 } else if (Symbol.isSectionDefinition()) {
354 // This symbol represents a section definition.
355 assert(Symbol.getNumberOfAuxSymbols() == 1 &&
356 "Expected a single aux symbol to describe this section!");
357
358 const object::coff_aux_section_definition *ObjSD =
359 reinterpret_cast<const object::coff_aux_section_definition *>(
360 AuxData.data());
361 dumpSectionDefinition(Sym: &Sym, ObjSD, IsBigObj: Symbol.isBigObj());
362 } else if (Symbol.isCLRToken()) {
363 // This symbol represents a CLR token definition.
364 assert(Symbol.getNumberOfAuxSymbols() == 1 &&
365 "Expected a single aux symbol to describe this CLR Token!");
366
367 const object::coff_aux_clr_token *ObjCLRToken =
368 reinterpret_cast<const object::coff_aux_clr_token *>(
369 AuxData.data());
370 dumpCLRTokenDefinition(Sym: &Sym, ObjCLRToken);
371 } else {
372 llvm_unreachable("Unhandled auxiliary symbol!");
373 }
374 }
375 Symbols.push_back(x: Sym);
376 }
377}
378
379COFFYAML::Object &COFFDumper::getYAMLObj() {
380 return YAMLObj;
381}
382
383std::error_code coff2yaml(raw_ostream &Out, const object::COFFObjectFile &Obj) {
384 COFFDumper Dumper(Obj);
385
386 yaml::Output Yout(Out);
387 Yout << Dumper.getYAMLObj();
388
389 return std::error_code();
390}
391