COFFEmitter.cpp 23 KB

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