COFFEmitter.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620
  1. //===- yaml2coff - Convert YAML to a COFF object file ---------------------===//
  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. /// \file
  10. /// The COFF component of yaml2obj.
  11. ///
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/ADT/STLExtras.h"
  14. #include "llvm/ADT/StringExtras.h"
  15. #include "llvm/ADT/StringMap.h"
  16. #include "llvm/DebugInfo/CodeView/DebugStringTableSubsection.h"
  17. #include "llvm/DebugInfo/CodeView/StringsAndChecksums.h"
  18. #include "llvm/Object/COFF.h"
  19. #include "llvm/ObjectYAML/ObjectYAML.h"
  20. #include "llvm/ObjectYAML/yaml2obj.h"
  21. #include "llvm/Support/BinaryStreamWriter.h"
  22. #include "llvm/Support/Endian.h"
  23. #include "llvm/Support/MemoryBuffer.h"
  24. #include "llvm/Support/SourceMgr.h"
  25. #include "llvm/Support/WithColor.h"
  26. #include "llvm/Support/raw_ostream.h"
  27. #include <optional>
  28. #include <vector>
  29. using namespace llvm;
  30. namespace {
  31. /// This parses a yaml stream that represents a COFF object file.
  32. /// See docs/yaml2obj for the yaml scheema.
  33. struct COFFParser {
  34. COFFParser(COFFYAML::Object &Obj, yaml::ErrorHandler EH)
  35. : Obj(Obj), SectionTableStart(0), SectionTableSize(0), ErrHandler(EH) {
  36. // A COFF string table always starts with a 4 byte size field. Offsets into
  37. // it include this size, so allocate it now.
  38. StringTable.append(4, char(0));
  39. }
  40. bool useBigObj() const {
  41. return static_cast<int32_t>(Obj.Sections.size()) >
  42. COFF::MaxNumberOfSections16;
  43. }
  44. bool isPE() const { return Obj.OptionalHeader.has_value(); }
  45. bool is64Bit() const {
  46. return Obj.Header.Machine == COFF::IMAGE_FILE_MACHINE_AMD64 ||
  47. Obj.Header.Machine == COFF::IMAGE_FILE_MACHINE_ARM64 ||
  48. Obj.Header.Machine == COFF::IMAGE_FILE_MACHINE_ARM64EC;
  49. }
  50. uint32_t getFileAlignment() const {
  51. return Obj.OptionalHeader->Header.FileAlignment;
  52. }
  53. unsigned getHeaderSize() const {
  54. return useBigObj() ? COFF::Header32Size : COFF::Header16Size;
  55. }
  56. unsigned getSymbolSize() const {
  57. return useBigObj() ? COFF::Symbol32Size : COFF::Symbol16Size;
  58. }
  59. bool parseSections() {
  60. for (COFFYAML::Section &Sec : Obj.Sections) {
  61. // If the name is less than 8 bytes, store it in place, otherwise
  62. // store it in the string table.
  63. StringRef Name = Sec.Name;
  64. if (Name.size() <= COFF::NameSize) {
  65. std::copy(Name.begin(), Name.end(), Sec.Header.Name);
  66. } else {
  67. // Add string to the string table and format the index for output.
  68. unsigned Index = getStringIndex(Name);
  69. std::string str = utostr(Index);
  70. if (str.size() > 7) {
  71. ErrHandler("string table got too large");
  72. return false;
  73. }
  74. Sec.Header.Name[0] = '/';
  75. std::copy(str.begin(), str.end(), Sec.Header.Name + 1);
  76. }
  77. if (Sec.Alignment) {
  78. if (Sec.Alignment > 8192) {
  79. ErrHandler("section alignment is too large");
  80. return false;
  81. }
  82. if (!isPowerOf2_32(Sec.Alignment)) {
  83. ErrHandler("section alignment is not a power of 2");
  84. return false;
  85. }
  86. Sec.Header.Characteristics |= (Log2_32(Sec.Alignment) + 1) << 20;
  87. }
  88. }
  89. return true;
  90. }
  91. bool parseSymbols() {
  92. for (COFFYAML::Symbol &Sym : Obj.Symbols) {
  93. // If the name is less than 8 bytes, store it in place, otherwise
  94. // store it in the string table.
  95. StringRef Name = Sym.Name;
  96. if (Name.size() <= COFF::NameSize) {
  97. std::copy(Name.begin(), Name.end(), Sym.Header.Name);
  98. } else {
  99. // Add string to the string table and format the index for output.
  100. unsigned Index = getStringIndex(Name);
  101. *reinterpret_cast<support::aligned_ulittle32_t *>(Sym.Header.Name + 4) =
  102. Index;
  103. }
  104. Sym.Header.Type = Sym.SimpleType;
  105. Sym.Header.Type |= Sym.ComplexType << COFF::SCT_COMPLEX_TYPE_SHIFT;
  106. }
  107. return true;
  108. }
  109. bool parse() {
  110. if (!parseSections())
  111. return false;
  112. if (!parseSymbols())
  113. return false;
  114. return true;
  115. }
  116. unsigned getStringIndex(StringRef Str) {
  117. StringMap<unsigned>::iterator i = StringTableMap.find(Str);
  118. if (i == StringTableMap.end()) {
  119. unsigned Index = StringTable.size();
  120. StringTable.append(Str.begin(), Str.end());
  121. StringTable.push_back(0);
  122. StringTableMap[Str] = Index;
  123. return Index;
  124. }
  125. return i->second;
  126. }
  127. COFFYAML::Object &Obj;
  128. codeview::StringsAndChecksums StringsAndChecksums;
  129. BumpPtrAllocator Allocator;
  130. StringMap<unsigned> StringTableMap;
  131. std::string StringTable;
  132. uint32_t SectionTableStart;
  133. uint32_t SectionTableSize;
  134. yaml::ErrorHandler ErrHandler;
  135. };
  136. enum { DOSStubSize = 128 };
  137. } // end anonymous namespace
  138. // Take a CP and assign addresses and sizes to everything. Returns false if the
  139. // layout is not valid to do.
  140. static bool layoutOptionalHeader(COFFParser &CP) {
  141. if (!CP.isPE())
  142. return true;
  143. unsigned PEHeaderSize = CP.is64Bit() ? sizeof(object::pe32plus_header)
  144. : sizeof(object::pe32_header);
  145. CP.Obj.Header.SizeOfOptionalHeader =
  146. PEHeaderSize + sizeof(object::data_directory) *
  147. CP.Obj.OptionalHeader->Header.NumberOfRvaAndSize;
  148. return true;
  149. }
  150. static yaml::BinaryRef
  151. toDebugS(ArrayRef<CodeViewYAML::YAMLDebugSubsection> Subsections,
  152. const codeview::StringsAndChecksums &SC, BumpPtrAllocator &Allocator) {
  153. using namespace codeview;
  154. ExitOnError Err("Error occurred writing .debug$S section");
  155. auto CVSS =
  156. Err(CodeViewYAML::toCodeViewSubsectionList(Allocator, Subsections, SC));
  157. std::vector<DebugSubsectionRecordBuilder> Builders;
  158. uint32_t Size = sizeof(uint32_t);
  159. for (auto &SS : CVSS) {
  160. DebugSubsectionRecordBuilder B(SS);
  161. Size += B.calculateSerializedLength();
  162. Builders.push_back(std::move(B));
  163. }
  164. uint8_t *Buffer = Allocator.Allocate<uint8_t>(Size);
  165. MutableArrayRef<uint8_t> Output(Buffer, Size);
  166. BinaryStreamWriter Writer(Output, support::little);
  167. Err(Writer.writeInteger<uint32_t>(COFF::DEBUG_SECTION_MAGIC));
  168. for (const auto &B : Builders) {
  169. Err(B.commit(Writer, CodeViewContainer::ObjectFile));
  170. }
  171. return {Output};
  172. }
  173. // Take a CP and assign addresses and sizes to everything. Returns false if the
  174. // layout is not valid to do.
  175. static bool layoutCOFF(COFFParser &CP) {
  176. // The section table starts immediately after the header, including the
  177. // optional header.
  178. CP.SectionTableStart =
  179. CP.getHeaderSize() + CP.Obj.Header.SizeOfOptionalHeader;
  180. if (CP.isPE())
  181. CP.SectionTableStart += DOSStubSize + sizeof(COFF::PEMagic);
  182. CP.SectionTableSize = COFF::SectionSize * CP.Obj.Sections.size();
  183. uint32_t CurrentSectionDataOffset =
  184. CP.SectionTableStart + CP.SectionTableSize;
  185. for (COFFYAML::Section &S : CP.Obj.Sections) {
  186. // We support specifying exactly one of SectionData or Subsections. So if
  187. // there is already some SectionData, then we don't need to do any of this.
  188. if (S.Name == ".debug$S" && S.SectionData.binary_size() == 0) {
  189. CodeViewYAML::initializeStringsAndChecksums(S.DebugS,
  190. CP.StringsAndChecksums);
  191. if (CP.StringsAndChecksums.hasChecksums() &&
  192. CP.StringsAndChecksums.hasStrings())
  193. break;
  194. }
  195. }
  196. // Assign each section data address consecutively.
  197. for (COFFYAML::Section &S : CP.Obj.Sections) {
  198. if (S.Name == ".debug$S") {
  199. if (S.SectionData.binary_size() == 0) {
  200. assert(CP.StringsAndChecksums.hasStrings() &&
  201. "Object file does not have debug string table!");
  202. S.SectionData =
  203. toDebugS(S.DebugS, CP.StringsAndChecksums, CP.Allocator);
  204. }
  205. } else if (S.Name == ".debug$T") {
  206. if (S.SectionData.binary_size() == 0)
  207. S.SectionData = CodeViewYAML::toDebugT(S.DebugT, CP.Allocator, S.Name);
  208. } else if (S.Name == ".debug$P") {
  209. if (S.SectionData.binary_size() == 0)
  210. S.SectionData = CodeViewYAML::toDebugT(S.DebugP, CP.Allocator, S.Name);
  211. } else if (S.Name == ".debug$H") {
  212. if (S.DebugH && S.SectionData.binary_size() == 0)
  213. S.SectionData = CodeViewYAML::toDebugH(*S.DebugH, CP.Allocator);
  214. }
  215. if (S.SectionData.binary_size() > 0) {
  216. CurrentSectionDataOffset = alignTo(CurrentSectionDataOffset,
  217. CP.isPE() ? CP.getFileAlignment() : 4);
  218. S.Header.SizeOfRawData = S.SectionData.binary_size();
  219. if (CP.isPE())
  220. S.Header.SizeOfRawData =
  221. alignTo(S.Header.SizeOfRawData, CP.getFileAlignment());
  222. S.Header.PointerToRawData = CurrentSectionDataOffset;
  223. CurrentSectionDataOffset += S.Header.SizeOfRawData;
  224. if (!S.Relocations.empty()) {
  225. S.Header.PointerToRelocations = CurrentSectionDataOffset;
  226. if (S.Header.Characteristics & COFF::IMAGE_SCN_LNK_NRELOC_OVFL) {
  227. S.Header.NumberOfRelocations = 0xffff;
  228. CurrentSectionDataOffset += COFF::RelocationSize;
  229. } else
  230. S.Header.NumberOfRelocations = S.Relocations.size();
  231. CurrentSectionDataOffset += S.Relocations.size() * COFF::RelocationSize;
  232. }
  233. } else {
  234. // Leave SizeOfRawData unaltered. For .bss sections in object files, it
  235. // carries the section size.
  236. S.Header.PointerToRawData = 0;
  237. }
  238. }
  239. uint32_t SymbolTableStart = CurrentSectionDataOffset;
  240. // Calculate number of symbols.
  241. uint32_t NumberOfSymbols = 0;
  242. for (std::vector<COFFYAML::Symbol>::iterator i = CP.Obj.Symbols.begin(),
  243. e = CP.Obj.Symbols.end();
  244. i != e; ++i) {
  245. uint32_t NumberOfAuxSymbols = 0;
  246. if (i->FunctionDefinition)
  247. NumberOfAuxSymbols += 1;
  248. if (i->bfAndefSymbol)
  249. NumberOfAuxSymbols += 1;
  250. if (i->WeakExternal)
  251. NumberOfAuxSymbols += 1;
  252. if (!i->File.empty())
  253. NumberOfAuxSymbols +=
  254. (i->File.size() + CP.getSymbolSize() - 1) / CP.getSymbolSize();
  255. if (i->SectionDefinition)
  256. NumberOfAuxSymbols += 1;
  257. if (i->CLRToken)
  258. NumberOfAuxSymbols += 1;
  259. i->Header.NumberOfAuxSymbols = NumberOfAuxSymbols;
  260. NumberOfSymbols += 1 + NumberOfAuxSymbols;
  261. }
  262. // Store all the allocated start addresses in the header.
  263. CP.Obj.Header.NumberOfSections = CP.Obj.Sections.size();
  264. CP.Obj.Header.NumberOfSymbols = NumberOfSymbols;
  265. if (NumberOfSymbols > 0 || CP.StringTable.size() > 4)
  266. CP.Obj.Header.PointerToSymbolTable = SymbolTableStart;
  267. else
  268. CP.Obj.Header.PointerToSymbolTable = 0;
  269. *reinterpret_cast<support::ulittle32_t *>(&CP.StringTable[0]) =
  270. CP.StringTable.size();
  271. return true;
  272. }
  273. template <typename value_type> struct binary_le_impl {
  274. value_type Value;
  275. binary_le_impl(value_type V) : Value(V) {}
  276. };
  277. template <typename value_type>
  278. raw_ostream &operator<<(raw_ostream &OS,
  279. const binary_le_impl<value_type> &BLE) {
  280. char Buffer[sizeof(BLE.Value)];
  281. support::endian::write<value_type, support::little, support::unaligned>(
  282. Buffer, BLE.Value);
  283. OS.write(Buffer, sizeof(BLE.Value));
  284. return OS;
  285. }
  286. template <typename value_type>
  287. binary_le_impl<value_type> binary_le(value_type V) {
  288. return binary_le_impl<value_type>(V);
  289. }
  290. template <size_t NumBytes> struct zeros_impl {};
  291. template <size_t NumBytes>
  292. raw_ostream &operator<<(raw_ostream &OS, const zeros_impl<NumBytes> &) {
  293. char Buffer[NumBytes];
  294. memset(Buffer, 0, sizeof(Buffer));
  295. OS.write(Buffer, sizeof(Buffer));
  296. return OS;
  297. }
  298. template <typename T> zeros_impl<sizeof(T)> zeros(const T &) {
  299. return zeros_impl<sizeof(T)>();
  300. }
  301. template <typename T>
  302. static uint32_t initializeOptionalHeader(COFFParser &CP, uint16_t Magic,
  303. T Header) {
  304. memset(Header, 0, sizeof(*Header));
  305. Header->Magic = Magic;
  306. Header->SectionAlignment = CP.Obj.OptionalHeader->Header.SectionAlignment;
  307. Header->FileAlignment = CP.Obj.OptionalHeader->Header.FileAlignment;
  308. uint32_t SizeOfCode = 0, SizeOfInitializedData = 0,
  309. SizeOfUninitializedData = 0;
  310. uint32_t SizeOfHeaders = alignTo(CP.SectionTableStart + CP.SectionTableSize,
  311. Header->FileAlignment);
  312. uint32_t SizeOfImage = alignTo(SizeOfHeaders, Header->SectionAlignment);
  313. uint32_t BaseOfData = 0;
  314. for (const COFFYAML::Section &S : CP.Obj.Sections) {
  315. if (S.Header.Characteristics & COFF::IMAGE_SCN_CNT_CODE)
  316. SizeOfCode += S.Header.SizeOfRawData;
  317. if (S.Header.Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA)
  318. SizeOfInitializedData += S.Header.SizeOfRawData;
  319. if (S.Header.Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA)
  320. SizeOfUninitializedData += S.Header.SizeOfRawData;
  321. if (S.Name.equals(".text"))
  322. Header->BaseOfCode = S.Header.VirtualAddress; // RVA
  323. else if (S.Name.equals(".data"))
  324. BaseOfData = S.Header.VirtualAddress; // RVA
  325. if (S.Header.VirtualAddress)
  326. SizeOfImage += alignTo(S.Header.VirtualSize, Header->SectionAlignment);
  327. }
  328. Header->SizeOfCode = SizeOfCode;
  329. Header->SizeOfInitializedData = SizeOfInitializedData;
  330. Header->SizeOfUninitializedData = SizeOfUninitializedData;
  331. Header->AddressOfEntryPoint =
  332. CP.Obj.OptionalHeader->Header.AddressOfEntryPoint; // RVA
  333. Header->ImageBase = CP.Obj.OptionalHeader->Header.ImageBase;
  334. Header->MajorOperatingSystemVersion =
  335. CP.Obj.OptionalHeader->Header.MajorOperatingSystemVersion;
  336. Header->MinorOperatingSystemVersion =
  337. CP.Obj.OptionalHeader->Header.MinorOperatingSystemVersion;
  338. Header->MajorImageVersion = CP.Obj.OptionalHeader->Header.MajorImageVersion;
  339. Header->MinorImageVersion = CP.Obj.OptionalHeader->Header.MinorImageVersion;
  340. Header->MajorSubsystemVersion =
  341. CP.Obj.OptionalHeader->Header.MajorSubsystemVersion;
  342. Header->MinorSubsystemVersion =
  343. CP.Obj.OptionalHeader->Header.MinorSubsystemVersion;
  344. Header->SizeOfImage = SizeOfImage;
  345. Header->SizeOfHeaders = SizeOfHeaders;
  346. Header->Subsystem = CP.Obj.OptionalHeader->Header.Subsystem;
  347. Header->DLLCharacteristics = CP.Obj.OptionalHeader->Header.DLLCharacteristics;
  348. Header->SizeOfStackReserve = CP.Obj.OptionalHeader->Header.SizeOfStackReserve;
  349. Header->SizeOfStackCommit = CP.Obj.OptionalHeader->Header.SizeOfStackCommit;
  350. Header->SizeOfHeapReserve = CP.Obj.OptionalHeader->Header.SizeOfHeapReserve;
  351. Header->SizeOfHeapCommit = CP.Obj.OptionalHeader->Header.SizeOfHeapCommit;
  352. Header->NumberOfRvaAndSize = CP.Obj.OptionalHeader->Header.NumberOfRvaAndSize;
  353. return BaseOfData;
  354. }
  355. static bool writeCOFF(COFFParser &CP, raw_ostream &OS) {
  356. if (CP.isPE()) {
  357. // PE files start with a DOS stub.
  358. object::dos_header DH;
  359. memset(&DH, 0, sizeof(DH));
  360. // DOS EXEs start with "MZ" magic.
  361. DH.Magic[0] = 'M';
  362. DH.Magic[1] = 'Z';
  363. // Initializing the AddressOfRelocationTable is strictly optional but
  364. // mollifies certain tools which expect it to have a value greater than
  365. // 0x40.
  366. DH.AddressOfRelocationTable = sizeof(DH);
  367. // This is the address of the PE signature.
  368. DH.AddressOfNewExeHeader = DOSStubSize;
  369. // Write out our DOS stub.
  370. OS.write(reinterpret_cast<char *>(&DH), sizeof(DH));
  371. // Write padding until we reach the position of where our PE signature
  372. // should live.
  373. OS.write_zeros(DOSStubSize - sizeof(DH));
  374. // Write out the PE signature.
  375. OS.write(COFF::PEMagic, sizeof(COFF::PEMagic));
  376. }
  377. if (CP.useBigObj()) {
  378. OS << binary_le(static_cast<uint16_t>(COFF::IMAGE_FILE_MACHINE_UNKNOWN))
  379. << binary_le(static_cast<uint16_t>(0xffff))
  380. << binary_le(
  381. static_cast<uint16_t>(COFF::BigObjHeader::MinBigObjectVersion))
  382. << binary_le(CP.Obj.Header.Machine)
  383. << binary_le(CP.Obj.Header.TimeDateStamp);
  384. OS.write(COFF::BigObjMagic, sizeof(COFF::BigObjMagic));
  385. OS << zeros(uint32_t(0)) << zeros(uint32_t(0)) << zeros(uint32_t(0))
  386. << zeros(uint32_t(0)) << binary_le(CP.Obj.Header.NumberOfSections)
  387. << binary_le(CP.Obj.Header.PointerToSymbolTable)
  388. << binary_le(CP.Obj.Header.NumberOfSymbols);
  389. } else {
  390. OS << binary_le(CP.Obj.Header.Machine)
  391. << binary_le(static_cast<int16_t>(CP.Obj.Header.NumberOfSections))
  392. << binary_le(CP.Obj.Header.TimeDateStamp)
  393. << binary_le(CP.Obj.Header.PointerToSymbolTable)
  394. << binary_le(CP.Obj.Header.NumberOfSymbols)
  395. << binary_le(CP.Obj.Header.SizeOfOptionalHeader)
  396. << binary_le(CP.Obj.Header.Characteristics);
  397. }
  398. if (CP.isPE()) {
  399. if (CP.is64Bit()) {
  400. object::pe32plus_header PEH;
  401. initializeOptionalHeader(CP, COFF::PE32Header::PE32_PLUS, &PEH);
  402. OS.write(reinterpret_cast<char *>(&PEH), sizeof(PEH));
  403. } else {
  404. object::pe32_header PEH;
  405. uint32_t BaseOfData =
  406. initializeOptionalHeader(CP, COFF::PE32Header::PE32, &PEH);
  407. PEH.BaseOfData = BaseOfData;
  408. OS.write(reinterpret_cast<char *>(&PEH), sizeof(PEH));
  409. }
  410. for (uint32_t I = 0; I < CP.Obj.OptionalHeader->Header.NumberOfRvaAndSize;
  411. ++I) {
  412. const std::optional<COFF::DataDirectory> *DataDirectories =
  413. CP.Obj.OptionalHeader->DataDirectories;
  414. uint32_t NumDataDir = std::size(CP.Obj.OptionalHeader->DataDirectories);
  415. if (I >= NumDataDir || !DataDirectories[I]) {
  416. OS << zeros(uint32_t(0));
  417. OS << zeros(uint32_t(0));
  418. } else {
  419. OS << binary_le(DataDirectories[I]->RelativeVirtualAddress);
  420. OS << binary_le(DataDirectories[I]->Size);
  421. }
  422. }
  423. }
  424. assert(OS.tell() == CP.SectionTableStart);
  425. // Output section table.
  426. for (const COFFYAML::Section &S : CP.Obj.Sections) {
  427. OS.write(S.Header.Name, COFF::NameSize);
  428. OS << binary_le(S.Header.VirtualSize)
  429. << binary_le(S.Header.VirtualAddress)
  430. << binary_le(S.Header.SizeOfRawData)
  431. << binary_le(S.Header.PointerToRawData)
  432. << binary_le(S.Header.PointerToRelocations)
  433. << binary_le(S.Header.PointerToLineNumbers)
  434. << binary_le(S.Header.NumberOfRelocations)
  435. << binary_le(S.Header.NumberOfLineNumbers)
  436. << binary_le(S.Header.Characteristics);
  437. }
  438. assert(OS.tell() == CP.SectionTableStart + CP.SectionTableSize);
  439. unsigned CurSymbol = 0;
  440. StringMap<unsigned> SymbolTableIndexMap;
  441. for (const COFFYAML::Symbol &Sym : CP.Obj.Symbols) {
  442. SymbolTableIndexMap[Sym.Name] = CurSymbol;
  443. CurSymbol += 1 + Sym.Header.NumberOfAuxSymbols;
  444. }
  445. // Output section data.
  446. for (const COFFYAML::Section &S : CP.Obj.Sections) {
  447. if (S.Header.SizeOfRawData == 0 || S.Header.PointerToRawData == 0)
  448. continue;
  449. assert(S.Header.PointerToRawData >= OS.tell());
  450. OS.write_zeros(S.Header.PointerToRawData - OS.tell());
  451. S.SectionData.writeAsBinary(OS);
  452. assert(S.Header.SizeOfRawData >= S.SectionData.binary_size());
  453. OS.write_zeros(S.Header.SizeOfRawData - S.SectionData.binary_size());
  454. if (S.Header.Characteristics & COFF::IMAGE_SCN_LNK_NRELOC_OVFL)
  455. OS << binary_le<uint32_t>(/*VirtualAddress=*/ S.Relocations.size() + 1)
  456. << binary_le<uint32_t>(/*SymbolTableIndex=*/ 0)
  457. << binary_le<uint16_t>(/*Type=*/ 0);
  458. for (const COFFYAML::Relocation &R : S.Relocations) {
  459. uint32_t SymbolTableIndex;
  460. if (R.SymbolTableIndex) {
  461. if (!R.SymbolName.empty())
  462. WithColor::error()
  463. << "Both SymbolName and SymbolTableIndex specified\n";
  464. SymbolTableIndex = *R.SymbolTableIndex;
  465. } else {
  466. SymbolTableIndex = SymbolTableIndexMap[R.SymbolName];
  467. }
  468. OS << binary_le(R.VirtualAddress) << binary_le(SymbolTableIndex)
  469. << binary_le(R.Type);
  470. }
  471. }
  472. // Output symbol table.
  473. for (std::vector<COFFYAML::Symbol>::const_iterator i = CP.Obj.Symbols.begin(),
  474. e = CP.Obj.Symbols.end();
  475. i != e; ++i) {
  476. OS.write(i->Header.Name, COFF::NameSize);
  477. OS << binary_le(i->Header.Value);
  478. if (CP.useBigObj())
  479. OS << binary_le(i->Header.SectionNumber);
  480. else
  481. OS << binary_le(static_cast<int16_t>(i->Header.SectionNumber));
  482. OS << binary_le(i->Header.Type) << binary_le(i->Header.StorageClass)
  483. << binary_le(i->Header.NumberOfAuxSymbols);
  484. if (i->FunctionDefinition) {
  485. OS << binary_le(i->FunctionDefinition->TagIndex)
  486. << binary_le(i->FunctionDefinition->TotalSize)
  487. << binary_le(i->FunctionDefinition->PointerToLinenumber)
  488. << binary_le(i->FunctionDefinition->PointerToNextFunction)
  489. << zeros(i->FunctionDefinition->unused);
  490. OS.write_zeros(CP.getSymbolSize() - COFF::Symbol16Size);
  491. }
  492. if (i->bfAndefSymbol) {
  493. OS << zeros(i->bfAndefSymbol->unused1)
  494. << binary_le(i->bfAndefSymbol->Linenumber)
  495. << zeros(i->bfAndefSymbol->unused2)
  496. << binary_le(i->bfAndefSymbol->PointerToNextFunction)
  497. << zeros(i->bfAndefSymbol->unused3);
  498. OS.write_zeros(CP.getSymbolSize() - COFF::Symbol16Size);
  499. }
  500. if (i->WeakExternal) {
  501. OS << binary_le(i->WeakExternal->TagIndex)
  502. << binary_le(i->WeakExternal->Characteristics)
  503. << zeros(i->WeakExternal->unused);
  504. OS.write_zeros(CP.getSymbolSize() - COFF::Symbol16Size);
  505. }
  506. if (!i->File.empty()) {
  507. unsigned SymbolSize = CP.getSymbolSize();
  508. uint32_t NumberOfAuxRecords =
  509. (i->File.size() + SymbolSize - 1) / SymbolSize;
  510. uint32_t NumberOfAuxBytes = NumberOfAuxRecords * SymbolSize;
  511. uint32_t NumZeros = NumberOfAuxBytes - i->File.size();
  512. OS.write(i->File.data(), i->File.size());
  513. OS.write_zeros(NumZeros);
  514. }
  515. if (i->SectionDefinition) {
  516. OS << binary_le(i->SectionDefinition->Length)
  517. << binary_le(i->SectionDefinition->NumberOfRelocations)
  518. << binary_le(i->SectionDefinition->NumberOfLinenumbers)
  519. << binary_le(i->SectionDefinition->CheckSum)
  520. << binary_le(static_cast<int16_t>(i->SectionDefinition->Number))
  521. << binary_le(i->SectionDefinition->Selection)
  522. << zeros(i->SectionDefinition->unused)
  523. << binary_le(static_cast<int16_t>(i->SectionDefinition->Number >> 16));
  524. OS.write_zeros(CP.getSymbolSize() - COFF::Symbol16Size);
  525. }
  526. if (i->CLRToken) {
  527. OS << binary_le(i->CLRToken->AuxType) << zeros(i->CLRToken->unused1)
  528. << binary_le(i->CLRToken->SymbolTableIndex)
  529. << zeros(i->CLRToken->unused2);
  530. OS.write_zeros(CP.getSymbolSize() - COFF::Symbol16Size);
  531. }
  532. }
  533. // Output string table.
  534. if (CP.Obj.Header.PointerToSymbolTable)
  535. OS.write(&CP.StringTable[0], CP.StringTable.size());
  536. return true;
  537. }
  538. namespace llvm {
  539. namespace yaml {
  540. bool yaml2coff(llvm::COFFYAML::Object &Doc, raw_ostream &Out,
  541. ErrorHandler ErrHandler) {
  542. COFFParser CP(Doc, ErrHandler);
  543. if (!CP.parse()) {
  544. ErrHandler("failed to parse YAML file");
  545. return false;
  546. }
  547. if (!layoutOptionalHeader(CP)) {
  548. ErrHandler("failed to layout optional header for COFF file");
  549. return false;
  550. }
  551. if (!layoutCOFF(CP)) {
  552. ErrHandler("failed to layout COFF file");
  553. return false;
  554. }
  555. if (!writeCOFF(CP, Out)) {
  556. ErrHandler("failed to write COFF file");
  557. return false;
  558. }
  559. return true;
  560. }
  561. } // namespace yaml
  562. } // namespace llvm