COFFEmitter.cpp 23 KB

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