coff2yaml.cpp 14 KB

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