yaml2elf.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  1. //===- yaml2elf - Convert YAML to a ELF object file -----------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. ///
  10. /// \file
  11. /// \brief The ELF component of yaml2obj.
  12. ///
  13. //===----------------------------------------------------------------------===//
  14. #include "yaml2obj.h"
  15. #include "llvm/ADT/ArrayRef.h"
  16. #include "llvm/MC/StringTableBuilder.h"
  17. #include "llvm/Object/ELFObjectFile.h"
  18. #include "llvm/Object/ELFYAML.h"
  19. #include "llvm/Support/ELF.h"
  20. #include "llvm/Support/MemoryBuffer.h"
  21. #include "llvm/Support/YAMLTraits.h"
  22. #include "llvm/Support/raw_ostream.h"
  23. using namespace llvm;
  24. // This class is used to build up a contiguous binary blob while keeping
  25. // track of an offset in the output (which notionally begins at
  26. // `InitialOffset`).
  27. namespace {
  28. class ContiguousBlobAccumulator {
  29. const uint64_t InitialOffset;
  30. SmallVector<char, 128> Buf;
  31. raw_svector_ostream OS;
  32. /// \returns The new offset.
  33. uint64_t padToAlignment(unsigned Align) {
  34. if (Align == 0)
  35. Align = 1;
  36. uint64_t CurrentOffset = InitialOffset + OS.tell();
  37. uint64_t AlignedOffset = RoundUpToAlignment(CurrentOffset, Align);
  38. for (; CurrentOffset != AlignedOffset; ++CurrentOffset)
  39. OS.write('\0');
  40. return AlignedOffset; // == CurrentOffset;
  41. }
  42. public:
  43. ContiguousBlobAccumulator(uint64_t InitialOffset_)
  44. : InitialOffset(InitialOffset_), Buf(), OS(Buf) {}
  45. template <class Integer>
  46. raw_ostream &getOSAndAlignedOffset(Integer &Offset, unsigned Align) {
  47. Offset = padToAlignment(Align);
  48. return OS;
  49. }
  50. void writeBlobToStream(raw_ostream &Out) { Out << OS.str(); }
  51. };
  52. } // end anonymous namespace
  53. // Used to keep track of section and symbol names, so that in the YAML file
  54. // sections and symbols can be referenced by name instead of by index.
  55. namespace {
  56. class NameToIdxMap {
  57. StringMap<int> Map;
  58. public:
  59. /// \returns true if name is already present in the map.
  60. bool addName(StringRef Name, unsigned i) {
  61. return !Map.insert(std::make_pair(Name, (int)i)).second;
  62. }
  63. /// \returns true if name is not present in the map
  64. bool lookup(StringRef Name, unsigned &Idx) const {
  65. StringMap<int>::const_iterator I = Map.find(Name);
  66. if (I == Map.end())
  67. return true;
  68. Idx = I->getValue();
  69. return false;
  70. }
  71. };
  72. } // end anonymous namespace
  73. template <class T>
  74. static size_t arrayDataSize(ArrayRef<T> A) {
  75. return A.size() * sizeof(T);
  76. }
  77. template <class T>
  78. static void writeArrayData(raw_ostream &OS, ArrayRef<T> A) {
  79. OS.write((const char *)A.data(), arrayDataSize(A));
  80. }
  81. template <class T>
  82. static void zero(T &Obj) {
  83. memset(&Obj, 0, sizeof(Obj));
  84. }
  85. namespace {
  86. /// \brief "Single point of truth" for the ELF file construction.
  87. /// TODO: This class still has a ways to go before it is truly a "single
  88. /// point of truth".
  89. template <class ELFT>
  90. class ELFState {
  91. typedef typename object::ELFFile<ELFT>::Elf_Ehdr Elf_Ehdr;
  92. typedef typename object::ELFFile<ELFT>::Elf_Shdr Elf_Shdr;
  93. typedef typename object::ELFFile<ELFT>::Elf_Sym Elf_Sym;
  94. typedef typename object::ELFFile<ELFT>::Elf_Rel Elf_Rel;
  95. typedef typename object::ELFFile<ELFT>::Elf_Rela Elf_Rela;
  96. /// \brief The future ".strtab" section.
  97. StringTableBuilder DotStrtab;
  98. /// \brief The future ".shstrtab" section.
  99. StringTableBuilder DotShStrtab;
  100. NameToIdxMap SN2I;
  101. NameToIdxMap SymN2I;
  102. const ELFYAML::Object &Doc;
  103. bool buildSectionIndex();
  104. bool buildSymbolIndex(std::size_t &StartIndex,
  105. const std::vector<ELFYAML::Symbol> &Symbols);
  106. void initELFHeader(Elf_Ehdr &Header);
  107. bool initSectionHeaders(std::vector<Elf_Shdr> &SHeaders,
  108. ContiguousBlobAccumulator &CBA);
  109. void initSymtabSectionHeader(Elf_Shdr &SHeader,
  110. ContiguousBlobAccumulator &CBA);
  111. void initStrtabSectionHeader(Elf_Shdr &SHeader, StringRef Name,
  112. StringTableBuilder &STB,
  113. ContiguousBlobAccumulator &CBA);
  114. void addSymbols(const std::vector<ELFYAML::Symbol> &Symbols,
  115. std::vector<Elf_Sym> &Syms, unsigned SymbolBinding);
  116. void writeSectionContent(Elf_Shdr &SHeader,
  117. const ELFYAML::RawContentSection &Section,
  118. ContiguousBlobAccumulator &CBA);
  119. bool writeSectionContent(Elf_Shdr &SHeader,
  120. const ELFYAML::RelocationSection &Section,
  121. ContiguousBlobAccumulator &CBA);
  122. bool writeSectionContent(Elf_Shdr &SHeader, const ELFYAML::Group &Group,
  123. ContiguousBlobAccumulator &CBA);
  124. bool writeSectionContent(Elf_Shdr &SHeader,
  125. const ELFYAML::MipsABIFlags &Section,
  126. ContiguousBlobAccumulator &CBA);
  127. // - SHT_NULL entry (placed first, i.e. 0'th entry)
  128. // - symbol table (.symtab) (placed third to last)
  129. // - string table (.strtab) (placed second to last)
  130. // - section header string table (.shstrtab) (placed last)
  131. unsigned getDotSymTabSecNo() const { return Doc.Sections.size() + 1; }
  132. unsigned getDotStrTabSecNo() const { return Doc.Sections.size() + 2; }
  133. unsigned getDotShStrTabSecNo() const { return Doc.Sections.size() + 3; }
  134. unsigned getSectionCount() const { return Doc.Sections.size() + 4; }
  135. ELFState(const ELFYAML::Object &D) : Doc(D) {}
  136. public:
  137. static int writeELF(raw_ostream &OS, const ELFYAML::Object &Doc);
  138. };
  139. } // end anonymous namespace
  140. template <class ELFT>
  141. void ELFState<ELFT>::initELFHeader(Elf_Ehdr &Header) {
  142. using namespace llvm::ELF;
  143. zero(Header);
  144. Header.e_ident[EI_MAG0] = 0x7f;
  145. Header.e_ident[EI_MAG1] = 'E';
  146. Header.e_ident[EI_MAG2] = 'L';
  147. Header.e_ident[EI_MAG3] = 'F';
  148. Header.e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;
  149. bool IsLittleEndian = ELFT::TargetEndianness == support::little;
  150. Header.e_ident[EI_DATA] = IsLittleEndian ? ELFDATA2LSB : ELFDATA2MSB;
  151. Header.e_ident[EI_VERSION] = EV_CURRENT;
  152. Header.e_ident[EI_OSABI] = Doc.Header.OSABI;
  153. Header.e_ident[EI_ABIVERSION] = 0;
  154. Header.e_type = Doc.Header.Type;
  155. Header.e_machine = Doc.Header.Machine;
  156. Header.e_version = EV_CURRENT;
  157. Header.e_entry = Doc.Header.Entry;
  158. Header.e_flags = Doc.Header.Flags;
  159. Header.e_ehsize = sizeof(Elf_Ehdr);
  160. Header.e_shentsize = sizeof(Elf_Shdr);
  161. // Immediately following the ELF header.
  162. Header.e_shoff = sizeof(Header);
  163. Header.e_shnum = getSectionCount();
  164. Header.e_shstrndx = getDotShStrTabSecNo();
  165. }
  166. template <class ELFT>
  167. bool ELFState<ELFT>::initSectionHeaders(std::vector<Elf_Shdr> &SHeaders,
  168. ContiguousBlobAccumulator &CBA) {
  169. // Ensure SHN_UNDEF entry is present. An all-zero section header is a
  170. // valid SHN_UNDEF entry since SHT_NULL == 0.
  171. Elf_Shdr SHeader;
  172. zero(SHeader);
  173. SHeaders.push_back(SHeader);
  174. for (const auto &Sec : Doc.Sections)
  175. DotShStrtab.add(Sec->Name);
  176. DotShStrtab.finalize(StringTableBuilder::ELF);
  177. for (const auto &Sec : Doc.Sections) {
  178. zero(SHeader);
  179. SHeader.sh_name = DotShStrtab.getOffset(Sec->Name);
  180. SHeader.sh_type = Sec->Type;
  181. SHeader.sh_flags = Sec->Flags;
  182. SHeader.sh_addr = Sec->Address;
  183. SHeader.sh_addralign = Sec->AddressAlign;
  184. if (!Sec->Link.empty()) {
  185. unsigned Index;
  186. if (SN2I.lookup(Sec->Link, Index)) {
  187. errs() << "error: Unknown section referenced: '" << Sec->Link
  188. << "' at YAML section '" << Sec->Name << "'.\n";
  189. return false;
  190. }
  191. SHeader.sh_link = Index;
  192. }
  193. if (auto S = dyn_cast<ELFYAML::RawContentSection>(Sec.get()))
  194. writeSectionContent(SHeader, *S, CBA);
  195. else if (auto S = dyn_cast<ELFYAML::RelocationSection>(Sec.get())) {
  196. if (S->Link.empty())
  197. // For relocation section set link to .symtab by default.
  198. SHeader.sh_link = getDotSymTabSecNo();
  199. unsigned Index;
  200. if (SN2I.lookup(S->Info, Index)) {
  201. errs() << "error: Unknown section referenced: '" << S->Info
  202. << "' at YAML section '" << S->Name << "'.\n";
  203. return false;
  204. }
  205. SHeader.sh_info = Index;
  206. if (!writeSectionContent(SHeader, *S, CBA))
  207. return false;
  208. } else if (auto S = dyn_cast<ELFYAML::Group>(Sec.get())) {
  209. unsigned SymIdx;
  210. if (SymN2I.lookup(S->Info, SymIdx)) {
  211. errs() << "error: Unknown symbol referenced: '" << S->Info
  212. << "' at YAML section '" << S->Name << "'.\n";
  213. return false;
  214. }
  215. SHeader.sh_info = SymIdx;
  216. if (!writeSectionContent(SHeader, *S, CBA))
  217. return false;
  218. } else if (auto S = dyn_cast<ELFYAML::MipsABIFlags>(Sec.get())) {
  219. if (!writeSectionContent(SHeader, *S, CBA))
  220. return false;
  221. } else if (auto S = dyn_cast<ELFYAML::NoBitsSection>(Sec.get())) {
  222. SHeader.sh_entsize = 0;
  223. SHeader.sh_size = S->Size;
  224. // SHT_NOBITS section does not have content
  225. // so just to setup the section offset.
  226. CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
  227. } else
  228. llvm_unreachable("Unknown section type");
  229. SHeaders.push_back(SHeader);
  230. }
  231. return true;
  232. }
  233. template <class ELFT>
  234. void ELFState<ELFT>::initSymtabSectionHeader(Elf_Shdr &SHeader,
  235. ContiguousBlobAccumulator &CBA) {
  236. zero(SHeader);
  237. SHeader.sh_name = DotShStrtab.getOffset(".symtab");
  238. SHeader.sh_type = ELF::SHT_SYMTAB;
  239. SHeader.sh_link = getDotStrTabSecNo();
  240. // One greater than symbol table index of the last local symbol.
  241. SHeader.sh_info = Doc.Symbols.Local.size() + 1;
  242. SHeader.sh_entsize = sizeof(Elf_Sym);
  243. SHeader.sh_addralign = 8;
  244. std::vector<Elf_Sym> Syms;
  245. {
  246. // Ensure STN_UNDEF is present
  247. Elf_Sym Sym;
  248. zero(Sym);
  249. Syms.push_back(Sym);
  250. }
  251. // Add symbol names to .strtab.
  252. for (const auto &Sym : Doc.Symbols.Local)
  253. DotStrtab.add(Sym.Name);
  254. for (const auto &Sym : Doc.Symbols.Global)
  255. DotStrtab.add(Sym.Name);
  256. for (const auto &Sym : Doc.Symbols.Weak)
  257. DotStrtab.add(Sym.Name);
  258. DotStrtab.finalize(StringTableBuilder::ELF);
  259. addSymbols(Doc.Symbols.Local, Syms, ELF::STB_LOCAL);
  260. addSymbols(Doc.Symbols.Global, Syms, ELF::STB_GLOBAL);
  261. addSymbols(Doc.Symbols.Weak, Syms, ELF::STB_WEAK);
  262. writeArrayData(
  263. CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign),
  264. makeArrayRef(Syms));
  265. SHeader.sh_size = arrayDataSize(makeArrayRef(Syms));
  266. }
  267. template <class ELFT>
  268. void ELFState<ELFT>::initStrtabSectionHeader(Elf_Shdr &SHeader, StringRef Name,
  269. StringTableBuilder &STB,
  270. ContiguousBlobAccumulator &CBA) {
  271. zero(SHeader);
  272. SHeader.sh_name = DotShStrtab.getOffset(Name);
  273. SHeader.sh_type = ELF::SHT_STRTAB;
  274. CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign)
  275. << STB.data();
  276. SHeader.sh_size = STB.data().size();
  277. SHeader.sh_addralign = 1;
  278. }
  279. template <class ELFT>
  280. void ELFState<ELFT>::addSymbols(const std::vector<ELFYAML::Symbol> &Symbols,
  281. std::vector<Elf_Sym> &Syms,
  282. unsigned SymbolBinding) {
  283. for (const auto &Sym : Symbols) {
  284. Elf_Sym Symbol;
  285. zero(Symbol);
  286. if (!Sym.Name.empty())
  287. Symbol.st_name = DotStrtab.getOffset(Sym.Name);
  288. Symbol.setBindingAndType(SymbolBinding, Sym.Type);
  289. if (!Sym.Section.empty()) {
  290. unsigned Index;
  291. if (SN2I.lookup(Sym.Section, Index)) {
  292. errs() << "error: Unknown section referenced: '" << Sym.Section
  293. << "' by YAML symbol " << Sym.Name << ".\n";
  294. exit(1);
  295. }
  296. Symbol.st_shndx = Index;
  297. } // else Symbol.st_shndex == SHN_UNDEF (== 0), since it was zero'd earlier.
  298. Symbol.st_value = Sym.Value;
  299. Symbol.st_other = Sym.Other;
  300. Symbol.st_size = Sym.Size;
  301. Syms.push_back(Symbol);
  302. }
  303. }
  304. template <class ELFT>
  305. void
  306. ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
  307. const ELFYAML::RawContentSection &Section,
  308. ContiguousBlobAccumulator &CBA) {
  309. assert(Section.Size >= Section.Content.binary_size() &&
  310. "Section size and section content are inconsistent");
  311. raw_ostream &OS =
  312. CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
  313. Section.Content.writeAsBinary(OS);
  314. for (auto i = Section.Content.binary_size(); i < Section.Size; ++i)
  315. OS.write(0);
  316. SHeader.sh_entsize = 0;
  317. SHeader.sh_size = Section.Size;
  318. }
  319. static bool isMips64EL(const ELFYAML::Object &Doc) {
  320. return Doc.Header.Machine == ELFYAML::ELF_EM(llvm::ELF::EM_MIPS) &&
  321. Doc.Header.Class == ELFYAML::ELF_ELFCLASS(ELF::ELFCLASS64) &&
  322. Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB);
  323. }
  324. template <class ELFT>
  325. bool
  326. ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
  327. const ELFYAML::RelocationSection &Section,
  328. ContiguousBlobAccumulator &CBA) {
  329. assert((Section.Type == llvm::ELF::SHT_REL ||
  330. Section.Type == llvm::ELF::SHT_RELA) &&
  331. "Section type is not SHT_REL nor SHT_RELA");
  332. bool IsRela = Section.Type == llvm::ELF::SHT_RELA;
  333. SHeader.sh_entsize = IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
  334. SHeader.sh_size = SHeader.sh_entsize * Section.Relocations.size();
  335. auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
  336. for (const auto &Rel : Section.Relocations) {
  337. unsigned SymIdx = 0;
  338. // Some special relocation, R_ARM_v4BX for instance, does not have
  339. // an external reference. So it ignores the return value of lookup()
  340. // here.
  341. SymN2I.lookup(Rel.Symbol, SymIdx);
  342. if (IsRela) {
  343. Elf_Rela REntry;
  344. zero(REntry);
  345. REntry.r_offset = Rel.Offset;
  346. REntry.r_addend = Rel.Addend;
  347. REntry.setSymbolAndType(SymIdx, Rel.Type, isMips64EL(Doc));
  348. OS.write((const char *)&REntry, sizeof(REntry));
  349. } else {
  350. Elf_Rel REntry;
  351. zero(REntry);
  352. REntry.r_offset = Rel.Offset;
  353. REntry.setSymbolAndType(SymIdx, Rel.Type, isMips64EL(Doc));
  354. OS.write((const char *)&REntry, sizeof(REntry));
  355. }
  356. }
  357. return true;
  358. }
  359. template <class ELFT>
  360. bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
  361. const ELFYAML::Group &Section,
  362. ContiguousBlobAccumulator &CBA) {
  363. typedef typename object::ELFFile<ELFT>::Elf_Word Elf_Word;
  364. assert(Section.Type == llvm::ELF::SHT_GROUP &&
  365. "Section type is not SHT_GROUP");
  366. SHeader.sh_entsize = sizeof(Elf_Word);
  367. SHeader.sh_size = SHeader.sh_entsize * Section.Members.size();
  368. auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
  369. for (auto member : Section.Members) {
  370. Elf_Word SIdx;
  371. unsigned int sectionIndex = 0;
  372. if (member.sectionNameOrType == "GRP_COMDAT")
  373. sectionIndex = llvm::ELF::GRP_COMDAT;
  374. else if (SN2I.lookup(member.sectionNameOrType, sectionIndex)) {
  375. errs() << "error: Unknown section referenced: '"
  376. << member.sectionNameOrType << "' at YAML section' "
  377. << Section.Name << "\n";
  378. return false;
  379. }
  380. SIdx = sectionIndex;
  381. OS.write((const char *)&SIdx, sizeof(SIdx));
  382. }
  383. return true;
  384. }
  385. template <class ELFT>
  386. bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
  387. const ELFYAML::MipsABIFlags &Section,
  388. ContiguousBlobAccumulator &CBA) {
  389. assert(Section.Type == llvm::ELF::SHT_MIPS_ABIFLAGS &&
  390. "Section type is not SHT_MIPS_ABIFLAGS");
  391. object::Elf_Mips_ABIFlags<ELFT> Flags;
  392. zero(Flags);
  393. SHeader.sh_entsize = sizeof(Flags);
  394. SHeader.sh_size = SHeader.sh_entsize;
  395. auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
  396. Flags.version = Section.Version;
  397. Flags.isa_level = Section.ISALevel;
  398. Flags.isa_rev = Section.ISARevision;
  399. Flags.gpr_size = Section.GPRSize;
  400. Flags.cpr1_size = Section.CPR1Size;
  401. Flags.cpr2_size = Section.CPR2Size;
  402. Flags.fp_abi = Section.FpABI;
  403. Flags.isa_ext = Section.ISAExtension;
  404. Flags.ases = Section.ASEs;
  405. Flags.flags1 = Section.Flags1;
  406. Flags.flags2 = Section.Flags2;
  407. OS.write((const char *)&Flags, sizeof(Flags));
  408. return true;
  409. }
  410. template <class ELFT> bool ELFState<ELFT>::buildSectionIndex() {
  411. SN2I.addName(".symtab", getDotSymTabSecNo());
  412. SN2I.addName(".strtab", getDotStrTabSecNo());
  413. SN2I.addName(".shstrtab", getDotShStrTabSecNo());
  414. for (unsigned i = 0, e = Doc.Sections.size(); i != e; ++i) {
  415. StringRef Name = Doc.Sections[i]->Name;
  416. if (Name.empty())
  417. continue;
  418. // "+ 1" to take into account the SHT_NULL entry.
  419. if (SN2I.addName(Name, i + 1)) {
  420. errs() << "error: Repeated section name: '" << Name
  421. << "' at YAML section number " << i << ".\n";
  422. return false;
  423. }
  424. }
  425. return true;
  426. }
  427. template <class ELFT>
  428. bool
  429. ELFState<ELFT>::buildSymbolIndex(std::size_t &StartIndex,
  430. const std::vector<ELFYAML::Symbol> &Symbols) {
  431. for (const auto &Sym : Symbols) {
  432. ++StartIndex;
  433. if (Sym.Name.empty())
  434. continue;
  435. if (SymN2I.addName(Sym.Name, StartIndex)) {
  436. errs() << "error: Repeated symbol name: '" << Sym.Name << "'.\n";
  437. return false;
  438. }
  439. }
  440. return true;
  441. }
  442. template <class ELFT>
  443. int ELFState<ELFT>::writeELF(raw_ostream &OS, const ELFYAML::Object &Doc) {
  444. ELFState<ELFT> State(Doc);
  445. if (!State.buildSectionIndex())
  446. return 1;
  447. std::size_t StartSymIndex = 0;
  448. if (!State.buildSymbolIndex(StartSymIndex, Doc.Symbols.Local) ||
  449. !State.buildSymbolIndex(StartSymIndex, Doc.Symbols.Global) ||
  450. !State.buildSymbolIndex(StartSymIndex, Doc.Symbols.Weak))
  451. return 1;
  452. Elf_Ehdr Header;
  453. State.initELFHeader(Header);
  454. // TODO: Flesh out section header support.
  455. // TODO: Program headers.
  456. // XXX: This offset is tightly coupled with the order that we write
  457. // things to `OS`.
  458. const size_t SectionContentBeginOffset =
  459. Header.e_ehsize + Header.e_shentsize * Header.e_shnum;
  460. ContiguousBlobAccumulator CBA(SectionContentBeginOffset);
  461. // Doc might not contain .symtab, .strtab and .shstrtab sections,
  462. // but we will emit them, so make sure to add them to ShStrTabSHeader.
  463. State.DotShStrtab.add(".symtab");
  464. State.DotShStrtab.add(".strtab");
  465. State.DotShStrtab.add(".shstrtab");
  466. std::vector<Elf_Shdr> SHeaders;
  467. if(!State.initSectionHeaders(SHeaders, CBA))
  468. return 1;
  469. // .symtab section.
  470. Elf_Shdr SymtabSHeader;
  471. State.initSymtabSectionHeader(SymtabSHeader, CBA);
  472. SHeaders.push_back(SymtabSHeader);
  473. // .strtab string table header.
  474. Elf_Shdr DotStrTabSHeader;
  475. State.initStrtabSectionHeader(DotStrTabSHeader, ".strtab", State.DotStrtab,
  476. CBA);
  477. SHeaders.push_back(DotStrTabSHeader);
  478. // .shstrtab string table header.
  479. Elf_Shdr ShStrTabSHeader;
  480. State.initStrtabSectionHeader(ShStrTabSHeader, ".shstrtab", State.DotShStrtab,
  481. CBA);
  482. SHeaders.push_back(ShStrTabSHeader);
  483. OS.write((const char *)&Header, sizeof(Header));
  484. writeArrayData(OS, makeArrayRef(SHeaders));
  485. CBA.writeBlobToStream(OS);
  486. return 0;
  487. }
  488. static bool is64Bit(const ELFYAML::Object &Doc) {
  489. return Doc.Header.Class == ELFYAML::ELF_ELFCLASS(ELF::ELFCLASS64);
  490. }
  491. static bool isLittleEndian(const ELFYAML::Object &Doc) {
  492. return Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB);
  493. }
  494. int yaml2elf(yaml::Input &YIn, raw_ostream &Out) {
  495. ELFYAML::Object Doc;
  496. YIn >> Doc;
  497. if (YIn.error()) {
  498. errs() << "yaml2obj: Failed to parse YAML file!\n";
  499. return 1;
  500. }
  501. using object::ELFType;
  502. typedef ELFType<support::little, true> LE64;
  503. typedef ELFType<support::big, true> BE64;
  504. typedef ELFType<support::little, false> LE32;
  505. typedef ELFType<support::big, false> BE32;
  506. if (is64Bit(Doc)) {
  507. if (isLittleEndian(Doc))
  508. return ELFState<LE64>::writeELF(Out, Doc);
  509. else
  510. return ELFState<BE64>::writeELF(Out, Doc);
  511. } else {
  512. if (isLittleEndian(Doc))
  513. return ELFState<LE32>::writeELF(Out, Doc);
  514. else
  515. return ELFState<BE32>::writeELF(Out, Doc);
  516. }
  517. }