ELFEmitter.cpp 71 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002
  1. //===- yaml2elf - Convert YAML to a ELF 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 ELF component of yaml2obj.
  11. ///
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/ADT/ArrayRef.h"
  14. #include "llvm/ADT/DenseMap.h"
  15. #include "llvm/ADT/SetVector.h"
  16. #include "llvm/ADT/StringSet.h"
  17. #include "llvm/BinaryFormat/ELF.h"
  18. #include "llvm/MC/StringTableBuilder.h"
  19. #include "llvm/Object/ELFObjectFile.h"
  20. #include "llvm/Object/ELFTypes.h"
  21. #include "llvm/ObjectYAML/DWARFEmitter.h"
  22. #include "llvm/ObjectYAML/DWARFYAML.h"
  23. #include "llvm/ObjectYAML/ELFYAML.h"
  24. #include "llvm/ObjectYAML/yaml2obj.h"
  25. #include "llvm/Support/EndianStream.h"
  26. #include "llvm/Support/Errc.h"
  27. #include "llvm/Support/Error.h"
  28. #include "llvm/Support/LEB128.h"
  29. #include "llvm/Support/MemoryBuffer.h"
  30. #include "llvm/Support/WithColor.h"
  31. #include "llvm/Support/YAMLTraits.h"
  32. #include "llvm/Support/raw_ostream.h"
  33. #include <optional>
  34. using namespace llvm;
  35. // This class is used to build up a contiguous binary blob while keeping
  36. // track of an offset in the output (which notionally begins at
  37. // `InitialOffset`).
  38. // The blob might be limited to an arbitrary size. All attempts to write data
  39. // are ignored and the error condition is remembered once the limit is reached.
  40. // Such an approach allows us to simplify the code by delaying error reporting
  41. // and doing it at a convenient time.
  42. namespace {
  43. class ContiguousBlobAccumulator {
  44. const uint64_t InitialOffset;
  45. const uint64_t MaxSize;
  46. SmallVector<char, 128> Buf;
  47. raw_svector_ostream OS;
  48. Error ReachedLimitErr = Error::success();
  49. bool checkLimit(uint64_t Size) {
  50. if (!ReachedLimitErr && getOffset() + Size <= MaxSize)
  51. return true;
  52. if (!ReachedLimitErr)
  53. ReachedLimitErr = createStringError(errc::invalid_argument,
  54. "reached the output size limit");
  55. return false;
  56. }
  57. public:
  58. ContiguousBlobAccumulator(uint64_t BaseOffset, uint64_t SizeLimit)
  59. : InitialOffset(BaseOffset), MaxSize(SizeLimit), OS(Buf) {}
  60. uint64_t tell() const { return OS.tell(); }
  61. uint64_t getOffset() const { return InitialOffset + OS.tell(); }
  62. void writeBlobToStream(raw_ostream &Out) const { Out << OS.str(); }
  63. Error takeLimitError() {
  64. // Request to write 0 bytes to check we did not reach the limit.
  65. checkLimit(0);
  66. return std::move(ReachedLimitErr);
  67. }
  68. /// \returns The new offset.
  69. uint64_t padToAlignment(unsigned Align) {
  70. uint64_t CurrentOffset = getOffset();
  71. if (ReachedLimitErr)
  72. return CurrentOffset;
  73. uint64_t AlignedOffset = alignTo(CurrentOffset, Align == 0 ? 1 : Align);
  74. uint64_t PaddingSize = AlignedOffset - CurrentOffset;
  75. if (!checkLimit(PaddingSize))
  76. return CurrentOffset;
  77. writeZeros(PaddingSize);
  78. return AlignedOffset;
  79. }
  80. raw_ostream *getRawOS(uint64_t Size) {
  81. if (checkLimit(Size))
  82. return &OS;
  83. return nullptr;
  84. }
  85. void writeAsBinary(const yaml::BinaryRef &Bin, uint64_t N = UINT64_MAX) {
  86. if (!checkLimit(Bin.binary_size()))
  87. return;
  88. Bin.writeAsBinary(OS, N);
  89. }
  90. void writeZeros(uint64_t Num) {
  91. if (checkLimit(Num))
  92. OS.write_zeros(Num);
  93. }
  94. void write(const char *Ptr, size_t Size) {
  95. if (checkLimit(Size))
  96. OS.write(Ptr, Size);
  97. }
  98. void write(unsigned char C) {
  99. if (checkLimit(1))
  100. OS.write(C);
  101. }
  102. unsigned writeULEB128(uint64_t Val) {
  103. if (!checkLimit(sizeof(uint64_t)))
  104. return 0;
  105. return encodeULEB128(Val, OS);
  106. }
  107. template <typename T> void write(T Val, support::endianness E) {
  108. if (checkLimit(sizeof(T)))
  109. support::endian::write<T>(OS, Val, E);
  110. }
  111. void updateDataAt(uint64_t Pos, void *Data, size_t Size) {
  112. assert(Pos >= InitialOffset && Pos + Size <= getOffset());
  113. memcpy(&Buf[Pos - InitialOffset], Data, Size);
  114. }
  115. };
  116. // Used to keep track of section and symbol names, so that in the YAML file
  117. // sections and symbols can be referenced by name instead of by index.
  118. class NameToIdxMap {
  119. StringMap<unsigned> Map;
  120. public:
  121. /// \Returns false if name is already present in the map.
  122. bool addName(StringRef Name, unsigned Ndx) {
  123. return Map.insert({Name, Ndx}).second;
  124. }
  125. /// \Returns false if name is not present in the map.
  126. bool lookup(StringRef Name, unsigned &Idx) const {
  127. auto I = Map.find(Name);
  128. if (I == Map.end())
  129. return false;
  130. Idx = I->getValue();
  131. return true;
  132. }
  133. /// Asserts if name is not present in the map.
  134. unsigned get(StringRef Name) const {
  135. unsigned Idx;
  136. if (lookup(Name, Idx))
  137. return Idx;
  138. assert(false && "Expected section not found in index");
  139. return 0;
  140. }
  141. unsigned size() const { return Map.size(); }
  142. };
  143. namespace {
  144. struct Fragment {
  145. uint64_t Offset;
  146. uint64_t Size;
  147. uint32_t Type;
  148. uint64_t AddrAlign;
  149. };
  150. } // namespace
  151. /// "Single point of truth" for the ELF file construction.
  152. /// TODO: This class still has a ways to go before it is truly a "single
  153. /// point of truth".
  154. template <class ELFT> class ELFState {
  155. LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
  156. enum class SymtabType { Static, Dynamic };
  157. /// The future symbol table string section.
  158. StringTableBuilder DotStrtab{StringTableBuilder::ELF};
  159. /// The future section header string table section, if a unique string table
  160. /// is needed. Don't reference this variable direectly: use the
  161. /// ShStrtabStrings member instead.
  162. StringTableBuilder DotShStrtab{StringTableBuilder::ELF};
  163. /// The future dynamic symbol string section.
  164. StringTableBuilder DotDynstr{StringTableBuilder::ELF};
  165. /// The name of the section header string table section. If it is .strtab or
  166. /// .dynstr, the section header strings will be written to the same string
  167. /// table as the static/dynamic symbols respectively. Otherwise a dedicated
  168. /// section will be created with that name.
  169. StringRef SectionHeaderStringTableName = ".shstrtab";
  170. StringTableBuilder *ShStrtabStrings = &DotShStrtab;
  171. NameToIdxMap SN2I;
  172. NameToIdxMap SymN2I;
  173. NameToIdxMap DynSymN2I;
  174. ELFYAML::Object &Doc;
  175. StringSet<> ExcludedSectionHeaders;
  176. uint64_t LocationCounter = 0;
  177. bool HasError = false;
  178. yaml::ErrorHandler ErrHandler;
  179. void reportError(const Twine &Msg);
  180. void reportError(Error Err);
  181. std::vector<Elf_Sym> toELFSymbols(ArrayRef<ELFYAML::Symbol> Symbols,
  182. const StringTableBuilder &Strtab);
  183. unsigned toSectionIndex(StringRef S, StringRef LocSec, StringRef LocSym = "");
  184. unsigned toSymbolIndex(StringRef S, StringRef LocSec, bool IsDynamic);
  185. void buildSectionIndex();
  186. void buildSymbolIndexes();
  187. void initProgramHeaders(std::vector<Elf_Phdr> &PHeaders);
  188. bool initImplicitHeader(ContiguousBlobAccumulator &CBA, Elf_Shdr &Header,
  189. StringRef SecName, ELFYAML::Section *YAMLSec);
  190. void initSectionHeaders(std::vector<Elf_Shdr> &SHeaders,
  191. ContiguousBlobAccumulator &CBA);
  192. void initSymtabSectionHeader(Elf_Shdr &SHeader, SymtabType STType,
  193. ContiguousBlobAccumulator &CBA,
  194. ELFYAML::Section *YAMLSec);
  195. void initStrtabSectionHeader(Elf_Shdr &SHeader, StringRef Name,
  196. StringTableBuilder &STB,
  197. ContiguousBlobAccumulator &CBA,
  198. ELFYAML::Section *YAMLSec);
  199. void initDWARFSectionHeader(Elf_Shdr &SHeader, StringRef Name,
  200. ContiguousBlobAccumulator &CBA,
  201. ELFYAML::Section *YAMLSec);
  202. void setProgramHeaderLayout(std::vector<Elf_Phdr> &PHeaders,
  203. std::vector<Elf_Shdr> &SHeaders);
  204. std::vector<Fragment>
  205. getPhdrFragments(const ELFYAML::ProgramHeader &Phdr,
  206. ArrayRef<typename ELFT::Shdr> SHeaders);
  207. void finalizeStrings();
  208. void writeELFHeader(raw_ostream &OS);
  209. void writeSectionContent(Elf_Shdr &SHeader,
  210. const ELFYAML::NoBitsSection &Section,
  211. ContiguousBlobAccumulator &CBA);
  212. void writeSectionContent(Elf_Shdr &SHeader,
  213. const ELFYAML::RawContentSection &Section,
  214. ContiguousBlobAccumulator &CBA);
  215. void writeSectionContent(Elf_Shdr &SHeader,
  216. const ELFYAML::RelocationSection &Section,
  217. ContiguousBlobAccumulator &CBA);
  218. void writeSectionContent(Elf_Shdr &SHeader,
  219. const ELFYAML::RelrSection &Section,
  220. ContiguousBlobAccumulator &CBA);
  221. void writeSectionContent(Elf_Shdr &SHeader,
  222. const ELFYAML::GroupSection &Group,
  223. ContiguousBlobAccumulator &CBA);
  224. void writeSectionContent(Elf_Shdr &SHeader,
  225. const ELFYAML::SymtabShndxSection &Shndx,
  226. ContiguousBlobAccumulator &CBA);
  227. void writeSectionContent(Elf_Shdr &SHeader,
  228. const ELFYAML::SymverSection &Section,
  229. ContiguousBlobAccumulator &CBA);
  230. void writeSectionContent(Elf_Shdr &SHeader,
  231. const ELFYAML::VerneedSection &Section,
  232. ContiguousBlobAccumulator &CBA);
  233. void writeSectionContent(Elf_Shdr &SHeader,
  234. const ELFYAML::VerdefSection &Section,
  235. ContiguousBlobAccumulator &CBA);
  236. void writeSectionContent(Elf_Shdr &SHeader,
  237. const ELFYAML::ARMIndexTableSection &Section,
  238. ContiguousBlobAccumulator &CBA);
  239. void writeSectionContent(Elf_Shdr &SHeader,
  240. const ELFYAML::MipsABIFlags &Section,
  241. ContiguousBlobAccumulator &CBA);
  242. void writeSectionContent(Elf_Shdr &SHeader,
  243. const ELFYAML::DynamicSection &Section,
  244. ContiguousBlobAccumulator &CBA);
  245. void writeSectionContent(Elf_Shdr &SHeader,
  246. const ELFYAML::StackSizesSection &Section,
  247. ContiguousBlobAccumulator &CBA);
  248. void writeSectionContent(Elf_Shdr &SHeader,
  249. const ELFYAML::BBAddrMapSection &Section,
  250. ContiguousBlobAccumulator &CBA);
  251. void writeSectionContent(Elf_Shdr &SHeader,
  252. const ELFYAML::HashSection &Section,
  253. ContiguousBlobAccumulator &CBA);
  254. void writeSectionContent(Elf_Shdr &SHeader,
  255. const ELFYAML::AddrsigSection &Section,
  256. ContiguousBlobAccumulator &CBA);
  257. void writeSectionContent(Elf_Shdr &SHeader,
  258. const ELFYAML::NoteSection &Section,
  259. ContiguousBlobAccumulator &CBA);
  260. void writeSectionContent(Elf_Shdr &SHeader,
  261. const ELFYAML::GnuHashSection &Section,
  262. ContiguousBlobAccumulator &CBA);
  263. void writeSectionContent(Elf_Shdr &SHeader,
  264. const ELFYAML::LinkerOptionsSection &Section,
  265. ContiguousBlobAccumulator &CBA);
  266. void writeSectionContent(Elf_Shdr &SHeader,
  267. const ELFYAML::DependentLibrariesSection &Section,
  268. ContiguousBlobAccumulator &CBA);
  269. void writeSectionContent(Elf_Shdr &SHeader,
  270. const ELFYAML::CallGraphProfileSection &Section,
  271. ContiguousBlobAccumulator &CBA);
  272. void writeFill(ELFYAML::Fill &Fill, ContiguousBlobAccumulator &CBA);
  273. ELFState(ELFYAML::Object &D, yaml::ErrorHandler EH);
  274. void assignSectionAddress(Elf_Shdr &SHeader, ELFYAML::Section *YAMLSec);
  275. DenseMap<StringRef, size_t> buildSectionHeaderReorderMap();
  276. BumpPtrAllocator StringAlloc;
  277. uint64_t alignToOffset(ContiguousBlobAccumulator &CBA, uint64_t Align,
  278. std::optional<llvm::yaml::Hex64> Offset);
  279. uint64_t getSectionNameOffset(StringRef Name);
  280. public:
  281. static bool writeELF(raw_ostream &OS, ELFYAML::Object &Doc,
  282. yaml::ErrorHandler EH, uint64_t MaxSize);
  283. };
  284. } // end anonymous namespace
  285. template <class T> static size_t arrayDataSize(ArrayRef<T> A) {
  286. return A.size() * sizeof(T);
  287. }
  288. template <class T> static void writeArrayData(raw_ostream &OS, ArrayRef<T> A) {
  289. OS.write((const char *)A.data(), arrayDataSize(A));
  290. }
  291. template <class T> static void zero(T &Obj) { memset(&Obj, 0, sizeof(Obj)); }
  292. template <class ELFT>
  293. ELFState<ELFT>::ELFState(ELFYAML::Object &D, yaml::ErrorHandler EH)
  294. : Doc(D), ErrHandler(EH) {
  295. // The input may explicitly request to store the section header table strings
  296. // in the same string table as dynamic or static symbol names. Set the
  297. // ShStrtabStrings member accordingly.
  298. if (Doc.Header.SectionHeaderStringTable) {
  299. SectionHeaderStringTableName = *Doc.Header.SectionHeaderStringTable;
  300. if (*Doc.Header.SectionHeaderStringTable == ".strtab")
  301. ShStrtabStrings = &DotStrtab;
  302. else if (*Doc.Header.SectionHeaderStringTable == ".dynstr")
  303. ShStrtabStrings = &DotDynstr;
  304. // Otherwise, the unique table will be used.
  305. }
  306. std::vector<ELFYAML::Section *> Sections = Doc.getSections();
  307. // Insert SHT_NULL section implicitly when it is not defined in YAML.
  308. if (Sections.empty() || Sections.front()->Type != ELF::SHT_NULL)
  309. Doc.Chunks.insert(
  310. Doc.Chunks.begin(),
  311. std::make_unique<ELFYAML::Section>(
  312. ELFYAML::Chunk::ChunkKind::RawContent, /*IsImplicit=*/true));
  313. StringSet<> DocSections;
  314. ELFYAML::SectionHeaderTable *SecHdrTable = nullptr;
  315. for (size_t I = 0; I < Doc.Chunks.size(); ++I) {
  316. const std::unique_ptr<ELFYAML::Chunk> &C = Doc.Chunks[I];
  317. // We might have an explicit section header table declaration.
  318. if (auto S = dyn_cast<ELFYAML::SectionHeaderTable>(C.get())) {
  319. if (SecHdrTable)
  320. reportError("multiple section header tables are not allowed");
  321. SecHdrTable = S;
  322. continue;
  323. }
  324. // We add a technical suffix for each unnamed section/fill. It does not
  325. // affect the output, but allows us to map them by name in the code and
  326. // report better error messages.
  327. if (C->Name.empty()) {
  328. std::string NewName = ELFYAML::appendUniqueSuffix(
  329. /*Name=*/"", "index " + Twine(I));
  330. C->Name = StringRef(NewName).copy(StringAlloc);
  331. assert(ELFYAML::dropUniqueSuffix(C->Name).empty());
  332. }
  333. if (!DocSections.insert(C->Name).second)
  334. reportError("repeated section/fill name: '" + C->Name +
  335. "' at YAML section/fill number " + Twine(I));
  336. }
  337. SmallSetVector<StringRef, 8> ImplicitSections;
  338. if (Doc.DynamicSymbols) {
  339. if (SectionHeaderStringTableName == ".dynsym")
  340. reportError("cannot use '.dynsym' as the section header name table when "
  341. "there are dynamic symbols");
  342. ImplicitSections.insert(".dynsym");
  343. ImplicitSections.insert(".dynstr");
  344. }
  345. if (Doc.Symbols) {
  346. if (SectionHeaderStringTableName == ".symtab")
  347. reportError("cannot use '.symtab' as the section header name table when "
  348. "there are symbols");
  349. ImplicitSections.insert(".symtab");
  350. }
  351. if (Doc.DWARF)
  352. for (StringRef DebugSecName : Doc.DWARF->getNonEmptySectionNames()) {
  353. std::string SecName = ("." + DebugSecName).str();
  354. // TODO: For .debug_str it should be possible to share the string table,
  355. // in the same manner as the symbol string tables.
  356. if (SectionHeaderStringTableName == SecName)
  357. reportError("cannot use '" + SecName +
  358. "' as the section header name table when it is needed for "
  359. "DWARF output");
  360. ImplicitSections.insert(StringRef(SecName).copy(StringAlloc));
  361. }
  362. // TODO: Only create the .strtab here if any symbols have been requested.
  363. ImplicitSections.insert(".strtab");
  364. if (!SecHdrTable || !SecHdrTable->NoHeaders.value_or(false))
  365. ImplicitSections.insert(SectionHeaderStringTableName);
  366. // Insert placeholders for implicit sections that are not
  367. // defined explicitly in YAML.
  368. for (StringRef SecName : ImplicitSections) {
  369. if (DocSections.count(SecName))
  370. continue;
  371. std::unique_ptr<ELFYAML::Section> Sec = std::make_unique<ELFYAML::Section>(
  372. ELFYAML::Chunk::ChunkKind::RawContent, true /*IsImplicit*/);
  373. Sec->Name = SecName;
  374. if (SecName == SectionHeaderStringTableName)
  375. Sec->Type = ELF::SHT_STRTAB;
  376. else if (SecName == ".dynsym")
  377. Sec->Type = ELF::SHT_DYNSYM;
  378. else if (SecName == ".symtab")
  379. Sec->Type = ELF::SHT_SYMTAB;
  380. else
  381. Sec->Type = ELF::SHT_STRTAB;
  382. // When the section header table is explicitly defined at the end of the
  383. // sections list, it is reasonable to assume that the user wants to reorder
  384. // section headers, but still wants to place the section header table after
  385. // all sections, like it normally happens. In this case we want to insert
  386. // other implicit sections right before the section header table.
  387. if (Doc.Chunks.back().get() == SecHdrTable)
  388. Doc.Chunks.insert(Doc.Chunks.end() - 1, std::move(Sec));
  389. else
  390. Doc.Chunks.push_back(std::move(Sec));
  391. }
  392. // Insert the section header table implicitly at the end, when it is not
  393. // explicitly defined.
  394. if (!SecHdrTable)
  395. Doc.Chunks.push_back(
  396. std::make_unique<ELFYAML::SectionHeaderTable>(/*IsImplicit=*/true));
  397. }
  398. template <class ELFT>
  399. void ELFState<ELFT>::writeELFHeader(raw_ostream &OS) {
  400. using namespace llvm::ELF;
  401. Elf_Ehdr Header;
  402. zero(Header);
  403. Header.e_ident[EI_MAG0] = 0x7f;
  404. Header.e_ident[EI_MAG1] = 'E';
  405. Header.e_ident[EI_MAG2] = 'L';
  406. Header.e_ident[EI_MAG3] = 'F';
  407. Header.e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;
  408. Header.e_ident[EI_DATA] = Doc.Header.Data;
  409. Header.e_ident[EI_VERSION] = EV_CURRENT;
  410. Header.e_ident[EI_OSABI] = Doc.Header.OSABI;
  411. Header.e_ident[EI_ABIVERSION] = Doc.Header.ABIVersion;
  412. Header.e_type = Doc.Header.Type;
  413. if (Doc.Header.Machine)
  414. Header.e_machine = *Doc.Header.Machine;
  415. else
  416. Header.e_machine = EM_NONE;
  417. Header.e_version = EV_CURRENT;
  418. Header.e_entry = Doc.Header.Entry;
  419. Header.e_flags = Doc.Header.Flags;
  420. Header.e_ehsize = sizeof(Elf_Ehdr);
  421. if (Doc.Header.EPhOff)
  422. Header.e_phoff = *Doc.Header.EPhOff;
  423. else if (!Doc.ProgramHeaders.empty())
  424. Header.e_phoff = sizeof(Header);
  425. else
  426. Header.e_phoff = 0;
  427. if (Doc.Header.EPhEntSize)
  428. Header.e_phentsize = *Doc.Header.EPhEntSize;
  429. else if (!Doc.ProgramHeaders.empty())
  430. Header.e_phentsize = sizeof(Elf_Phdr);
  431. else
  432. Header.e_phentsize = 0;
  433. if (Doc.Header.EPhNum)
  434. Header.e_phnum = *Doc.Header.EPhNum;
  435. else if (!Doc.ProgramHeaders.empty())
  436. Header.e_phnum = Doc.ProgramHeaders.size();
  437. else
  438. Header.e_phnum = 0;
  439. Header.e_shentsize = Doc.Header.EShEntSize ? (uint16_t)*Doc.Header.EShEntSize
  440. : sizeof(Elf_Shdr);
  441. const ELFYAML::SectionHeaderTable &SectionHeaders =
  442. Doc.getSectionHeaderTable();
  443. if (Doc.Header.EShOff)
  444. Header.e_shoff = *Doc.Header.EShOff;
  445. else if (SectionHeaders.Offset)
  446. Header.e_shoff = *SectionHeaders.Offset;
  447. else
  448. Header.e_shoff = 0;
  449. if (Doc.Header.EShNum)
  450. Header.e_shnum = *Doc.Header.EShNum;
  451. else
  452. Header.e_shnum = SectionHeaders.getNumHeaders(Doc.getSections().size());
  453. if (Doc.Header.EShStrNdx)
  454. Header.e_shstrndx = *Doc.Header.EShStrNdx;
  455. else if (SectionHeaders.Offset &&
  456. !ExcludedSectionHeaders.count(SectionHeaderStringTableName))
  457. Header.e_shstrndx = SN2I.get(SectionHeaderStringTableName);
  458. else
  459. Header.e_shstrndx = 0;
  460. OS.write((const char *)&Header, sizeof(Header));
  461. }
  462. template <class ELFT>
  463. void ELFState<ELFT>::initProgramHeaders(std::vector<Elf_Phdr> &PHeaders) {
  464. DenseMap<StringRef, ELFYAML::Fill *> NameToFill;
  465. DenseMap<StringRef, size_t> NameToIndex;
  466. for (size_t I = 0, E = Doc.Chunks.size(); I != E; ++I) {
  467. if (auto S = dyn_cast<ELFYAML::Fill>(Doc.Chunks[I].get()))
  468. NameToFill[S->Name] = S;
  469. NameToIndex[Doc.Chunks[I]->Name] = I + 1;
  470. }
  471. std::vector<ELFYAML::Section *> Sections = Doc.getSections();
  472. for (size_t I = 0, E = Doc.ProgramHeaders.size(); I != E; ++I) {
  473. ELFYAML::ProgramHeader &YamlPhdr = Doc.ProgramHeaders[I];
  474. Elf_Phdr Phdr;
  475. zero(Phdr);
  476. Phdr.p_type = YamlPhdr.Type;
  477. Phdr.p_flags = YamlPhdr.Flags;
  478. Phdr.p_vaddr = YamlPhdr.VAddr;
  479. Phdr.p_paddr = YamlPhdr.PAddr;
  480. PHeaders.push_back(Phdr);
  481. if (!YamlPhdr.FirstSec && !YamlPhdr.LastSec)
  482. continue;
  483. // Get the index of the section, or 0 in the case when the section doesn't exist.
  484. size_t First = NameToIndex[*YamlPhdr.FirstSec];
  485. if (!First)
  486. reportError("unknown section or fill referenced: '" + *YamlPhdr.FirstSec +
  487. "' by the 'FirstSec' key of the program header with index " +
  488. Twine(I));
  489. size_t Last = NameToIndex[*YamlPhdr.LastSec];
  490. if (!Last)
  491. reportError("unknown section or fill referenced: '" + *YamlPhdr.LastSec +
  492. "' by the 'LastSec' key of the program header with index " +
  493. Twine(I));
  494. if (!First || !Last)
  495. continue;
  496. if (First > Last)
  497. reportError("program header with index " + Twine(I) +
  498. ": the section index of " + *YamlPhdr.FirstSec +
  499. " is greater than the index of " + *YamlPhdr.LastSec);
  500. for (size_t I = First; I <= Last; ++I)
  501. YamlPhdr.Chunks.push_back(Doc.Chunks[I - 1].get());
  502. }
  503. }
  504. template <class ELFT>
  505. unsigned ELFState<ELFT>::toSectionIndex(StringRef S, StringRef LocSec,
  506. StringRef LocSym) {
  507. assert(LocSec.empty() || LocSym.empty());
  508. unsigned Index;
  509. if (!SN2I.lookup(S, Index) && !to_integer(S, Index)) {
  510. if (!LocSym.empty())
  511. reportError("unknown section referenced: '" + S + "' by YAML symbol '" +
  512. LocSym + "'");
  513. else
  514. reportError("unknown section referenced: '" + S + "' by YAML section '" +
  515. LocSec + "'");
  516. return 0;
  517. }
  518. const ELFYAML::SectionHeaderTable &SectionHeaders =
  519. Doc.getSectionHeaderTable();
  520. if (SectionHeaders.IsImplicit ||
  521. (SectionHeaders.NoHeaders && !*SectionHeaders.NoHeaders) ||
  522. SectionHeaders.isDefault())
  523. return Index;
  524. assert(!SectionHeaders.NoHeaders.value_or(false) || !SectionHeaders.Sections);
  525. size_t FirstExcluded =
  526. SectionHeaders.Sections ? SectionHeaders.Sections->size() : 0;
  527. if (Index > FirstExcluded) {
  528. if (LocSym.empty())
  529. reportError("unable to link '" + LocSec + "' to excluded section '" + S +
  530. "'");
  531. else
  532. reportError("excluded section referenced: '" + S + "' by symbol '" +
  533. LocSym + "'");
  534. }
  535. return Index;
  536. }
  537. template <class ELFT>
  538. unsigned ELFState<ELFT>::toSymbolIndex(StringRef S, StringRef LocSec,
  539. bool IsDynamic) {
  540. const NameToIdxMap &SymMap = IsDynamic ? DynSymN2I : SymN2I;
  541. unsigned Index;
  542. // Here we try to look up S in the symbol table. If it is not there,
  543. // treat its value as a symbol index.
  544. if (!SymMap.lookup(S, Index) && !to_integer(S, Index)) {
  545. reportError("unknown symbol referenced: '" + S + "' by YAML section '" +
  546. LocSec + "'");
  547. return 0;
  548. }
  549. return Index;
  550. }
  551. template <class ELFT>
  552. static void overrideFields(ELFYAML::Section *From, typename ELFT::Shdr &To) {
  553. if (!From)
  554. return;
  555. if (From->ShAddrAlign)
  556. To.sh_addralign = *From->ShAddrAlign;
  557. if (From->ShFlags)
  558. To.sh_flags = *From->ShFlags;
  559. if (From->ShName)
  560. To.sh_name = *From->ShName;
  561. if (From->ShOffset)
  562. To.sh_offset = *From->ShOffset;
  563. if (From->ShSize)
  564. To.sh_size = *From->ShSize;
  565. if (From->ShType)
  566. To.sh_type = *From->ShType;
  567. }
  568. template <class ELFT>
  569. bool ELFState<ELFT>::initImplicitHeader(ContiguousBlobAccumulator &CBA,
  570. Elf_Shdr &Header, StringRef SecName,
  571. ELFYAML::Section *YAMLSec) {
  572. // Check if the header was already initialized.
  573. if (Header.sh_offset)
  574. return false;
  575. if (SecName == ".strtab")
  576. initStrtabSectionHeader(Header, SecName, DotStrtab, CBA, YAMLSec);
  577. else if (SecName == ".dynstr")
  578. initStrtabSectionHeader(Header, SecName, DotDynstr, CBA, YAMLSec);
  579. else if (SecName == SectionHeaderStringTableName)
  580. initStrtabSectionHeader(Header, SecName, *ShStrtabStrings, CBA, YAMLSec);
  581. else if (SecName == ".symtab")
  582. initSymtabSectionHeader(Header, SymtabType::Static, CBA, YAMLSec);
  583. else if (SecName == ".dynsym")
  584. initSymtabSectionHeader(Header, SymtabType::Dynamic, CBA, YAMLSec);
  585. else if (SecName.startswith(".debug_")) {
  586. // If a ".debug_*" section's type is a preserved one, e.g., SHT_DYNAMIC, we
  587. // will not treat it as a debug section.
  588. if (YAMLSec && !isa<ELFYAML::RawContentSection>(YAMLSec))
  589. return false;
  590. initDWARFSectionHeader(Header, SecName, CBA, YAMLSec);
  591. } else
  592. return false;
  593. LocationCounter += Header.sh_size;
  594. // Override section fields if requested.
  595. overrideFields<ELFT>(YAMLSec, Header);
  596. return true;
  597. }
  598. constexpr char SuffixStart = '(';
  599. constexpr char SuffixEnd = ')';
  600. std::string llvm::ELFYAML::appendUniqueSuffix(StringRef Name,
  601. const Twine &Msg) {
  602. // Do not add a space when a Name is empty.
  603. std::string Ret = Name.empty() ? "" : Name.str() + ' ';
  604. return Ret + (Twine(SuffixStart) + Msg + Twine(SuffixEnd)).str();
  605. }
  606. StringRef llvm::ELFYAML::dropUniqueSuffix(StringRef S) {
  607. if (S.empty() || S.back() != SuffixEnd)
  608. return S;
  609. // A special case for empty names. See appendUniqueSuffix() above.
  610. size_t SuffixPos = S.rfind(SuffixStart);
  611. if (SuffixPos == 0)
  612. return "";
  613. if (SuffixPos == StringRef::npos || S[SuffixPos - 1] != ' ')
  614. return S;
  615. return S.substr(0, SuffixPos - 1);
  616. }
  617. template <class ELFT>
  618. uint64_t ELFState<ELFT>::getSectionNameOffset(StringRef Name) {
  619. // If a section is excluded from section headers, we do not save its name in
  620. // the string table.
  621. if (ExcludedSectionHeaders.count(Name))
  622. return 0;
  623. return ShStrtabStrings->getOffset(Name);
  624. }
  625. static uint64_t writeContent(ContiguousBlobAccumulator &CBA,
  626. const std::optional<yaml::BinaryRef> &Content,
  627. const std::optional<llvm::yaml::Hex64> &Size) {
  628. size_t ContentSize = 0;
  629. if (Content) {
  630. CBA.writeAsBinary(*Content);
  631. ContentSize = Content->binary_size();
  632. }
  633. if (!Size)
  634. return ContentSize;
  635. CBA.writeZeros(*Size - ContentSize);
  636. return *Size;
  637. }
  638. static StringRef getDefaultLinkSec(unsigned SecType) {
  639. switch (SecType) {
  640. case ELF::SHT_REL:
  641. case ELF::SHT_RELA:
  642. case ELF::SHT_GROUP:
  643. case ELF::SHT_LLVM_CALL_GRAPH_PROFILE:
  644. case ELF::SHT_LLVM_ADDRSIG:
  645. return ".symtab";
  646. case ELF::SHT_GNU_versym:
  647. case ELF::SHT_HASH:
  648. case ELF::SHT_GNU_HASH:
  649. return ".dynsym";
  650. case ELF::SHT_DYNSYM:
  651. case ELF::SHT_GNU_verdef:
  652. case ELF::SHT_GNU_verneed:
  653. return ".dynstr";
  654. case ELF::SHT_SYMTAB:
  655. return ".strtab";
  656. default:
  657. return "";
  658. }
  659. }
  660. template <class ELFT>
  661. void ELFState<ELFT>::initSectionHeaders(std::vector<Elf_Shdr> &SHeaders,
  662. ContiguousBlobAccumulator &CBA) {
  663. // Ensure SHN_UNDEF entry is present. An all-zero section header is a
  664. // valid SHN_UNDEF entry since SHT_NULL == 0.
  665. SHeaders.resize(Doc.getSections().size());
  666. for (const std::unique_ptr<ELFYAML::Chunk> &D : Doc.Chunks) {
  667. if (ELFYAML::Fill *S = dyn_cast<ELFYAML::Fill>(D.get())) {
  668. S->Offset = alignToOffset(CBA, /*Align=*/1, S->Offset);
  669. writeFill(*S, CBA);
  670. LocationCounter += S->Size;
  671. continue;
  672. }
  673. if (ELFYAML::SectionHeaderTable *S =
  674. dyn_cast<ELFYAML::SectionHeaderTable>(D.get())) {
  675. if (S->NoHeaders.value_or(false))
  676. continue;
  677. if (!S->Offset)
  678. S->Offset = alignToOffset(CBA, sizeof(typename ELFT::uint),
  679. /*Offset=*/std::nullopt);
  680. else
  681. S->Offset = alignToOffset(CBA, /*Align=*/1, S->Offset);
  682. uint64_t Size = S->getNumHeaders(SHeaders.size()) * sizeof(Elf_Shdr);
  683. // The full section header information might be not available here, so
  684. // fill the space with zeroes as a placeholder.
  685. CBA.writeZeros(Size);
  686. LocationCounter += Size;
  687. continue;
  688. }
  689. ELFYAML::Section *Sec = cast<ELFYAML::Section>(D.get());
  690. bool IsFirstUndefSection = Sec == Doc.getSections().front();
  691. if (IsFirstUndefSection && Sec->IsImplicit)
  692. continue;
  693. Elf_Shdr &SHeader = SHeaders[SN2I.get(Sec->Name)];
  694. if (Sec->Link) {
  695. SHeader.sh_link = toSectionIndex(*Sec->Link, Sec->Name);
  696. } else {
  697. StringRef LinkSec = getDefaultLinkSec(Sec->Type);
  698. unsigned Link = 0;
  699. if (!LinkSec.empty() && !ExcludedSectionHeaders.count(LinkSec) &&
  700. SN2I.lookup(LinkSec, Link))
  701. SHeader.sh_link = Link;
  702. }
  703. if (Sec->EntSize)
  704. SHeader.sh_entsize = *Sec->EntSize;
  705. else
  706. SHeader.sh_entsize = ELFYAML::getDefaultShEntSize<ELFT>(
  707. Doc.Header.Machine.value_or(ELF::EM_NONE), Sec->Type, Sec->Name);
  708. // We have a few sections like string or symbol tables that are usually
  709. // added implicitly to the end. However, if they are explicitly specified
  710. // in the YAML, we need to write them here. This ensures the file offset
  711. // remains correct.
  712. if (initImplicitHeader(CBA, SHeader, Sec->Name,
  713. Sec->IsImplicit ? nullptr : Sec))
  714. continue;
  715. assert(Sec && "It can't be null unless it is an implicit section. But all "
  716. "implicit sections should already have been handled above.");
  717. SHeader.sh_name =
  718. getSectionNameOffset(ELFYAML::dropUniqueSuffix(Sec->Name));
  719. SHeader.sh_type = Sec->Type;
  720. if (Sec->Flags)
  721. SHeader.sh_flags = *Sec->Flags;
  722. SHeader.sh_addralign = Sec->AddressAlign;
  723. // Set the offset for all sections, except the SHN_UNDEF section with index
  724. // 0 when not explicitly requested.
  725. if (!IsFirstUndefSection || Sec->Offset)
  726. SHeader.sh_offset = alignToOffset(CBA, SHeader.sh_addralign, Sec->Offset);
  727. assignSectionAddress(SHeader, Sec);
  728. if (IsFirstUndefSection) {
  729. if (auto RawSec = dyn_cast<ELFYAML::RawContentSection>(Sec)) {
  730. // We do not write any content for special SHN_UNDEF section.
  731. if (RawSec->Size)
  732. SHeader.sh_size = *RawSec->Size;
  733. if (RawSec->Info)
  734. SHeader.sh_info = *RawSec->Info;
  735. }
  736. LocationCounter += SHeader.sh_size;
  737. overrideFields<ELFT>(Sec, SHeader);
  738. continue;
  739. }
  740. if (!isa<ELFYAML::NoBitsSection>(Sec) && (Sec->Content || Sec->Size))
  741. SHeader.sh_size = writeContent(CBA, Sec->Content, Sec->Size);
  742. if (auto S = dyn_cast<ELFYAML::RawContentSection>(Sec)) {
  743. writeSectionContent(SHeader, *S, CBA);
  744. } else if (auto S = dyn_cast<ELFYAML::SymtabShndxSection>(Sec)) {
  745. writeSectionContent(SHeader, *S, CBA);
  746. } else if (auto S = dyn_cast<ELFYAML::RelocationSection>(Sec)) {
  747. writeSectionContent(SHeader, *S, CBA);
  748. } else if (auto S = dyn_cast<ELFYAML::RelrSection>(Sec)) {
  749. writeSectionContent(SHeader, *S, CBA);
  750. } else if (auto S = dyn_cast<ELFYAML::GroupSection>(Sec)) {
  751. writeSectionContent(SHeader, *S, CBA);
  752. } else if (auto S = dyn_cast<ELFYAML::ARMIndexTableSection>(Sec)) {
  753. writeSectionContent(SHeader, *S, CBA);
  754. } else if (auto S = dyn_cast<ELFYAML::MipsABIFlags>(Sec)) {
  755. writeSectionContent(SHeader, *S, CBA);
  756. } else if (auto S = dyn_cast<ELFYAML::NoBitsSection>(Sec)) {
  757. writeSectionContent(SHeader, *S, CBA);
  758. } else if (auto S = dyn_cast<ELFYAML::DynamicSection>(Sec)) {
  759. writeSectionContent(SHeader, *S, CBA);
  760. } else if (auto S = dyn_cast<ELFYAML::SymverSection>(Sec)) {
  761. writeSectionContent(SHeader, *S, CBA);
  762. } else if (auto S = dyn_cast<ELFYAML::VerneedSection>(Sec)) {
  763. writeSectionContent(SHeader, *S, CBA);
  764. } else if (auto S = dyn_cast<ELFYAML::VerdefSection>(Sec)) {
  765. writeSectionContent(SHeader, *S, CBA);
  766. } else if (auto S = dyn_cast<ELFYAML::StackSizesSection>(Sec)) {
  767. writeSectionContent(SHeader, *S, CBA);
  768. } else if (auto S = dyn_cast<ELFYAML::HashSection>(Sec)) {
  769. writeSectionContent(SHeader, *S, CBA);
  770. } else if (auto S = dyn_cast<ELFYAML::AddrsigSection>(Sec)) {
  771. writeSectionContent(SHeader, *S, CBA);
  772. } else if (auto S = dyn_cast<ELFYAML::LinkerOptionsSection>(Sec)) {
  773. writeSectionContent(SHeader, *S, CBA);
  774. } else if (auto S = dyn_cast<ELFYAML::NoteSection>(Sec)) {
  775. writeSectionContent(SHeader, *S, CBA);
  776. } else if (auto S = dyn_cast<ELFYAML::GnuHashSection>(Sec)) {
  777. writeSectionContent(SHeader, *S, CBA);
  778. } else if (auto S = dyn_cast<ELFYAML::DependentLibrariesSection>(Sec)) {
  779. writeSectionContent(SHeader, *S, CBA);
  780. } else if (auto S = dyn_cast<ELFYAML::CallGraphProfileSection>(Sec)) {
  781. writeSectionContent(SHeader, *S, CBA);
  782. } else if (auto S = dyn_cast<ELFYAML::BBAddrMapSection>(Sec)) {
  783. writeSectionContent(SHeader, *S, CBA);
  784. } else {
  785. llvm_unreachable("Unknown section type");
  786. }
  787. LocationCounter += SHeader.sh_size;
  788. // Override section fields if requested.
  789. overrideFields<ELFT>(Sec, SHeader);
  790. }
  791. }
  792. template <class ELFT>
  793. void ELFState<ELFT>::assignSectionAddress(Elf_Shdr &SHeader,
  794. ELFYAML::Section *YAMLSec) {
  795. if (YAMLSec && YAMLSec->Address) {
  796. SHeader.sh_addr = *YAMLSec->Address;
  797. LocationCounter = *YAMLSec->Address;
  798. return;
  799. }
  800. // sh_addr represents the address in the memory image of a process. Sections
  801. // in a relocatable object file or non-allocatable sections do not need
  802. // sh_addr assignment.
  803. if (Doc.Header.Type.value == ELF::ET_REL ||
  804. !(SHeader.sh_flags & ELF::SHF_ALLOC))
  805. return;
  806. LocationCounter =
  807. alignTo(LocationCounter, SHeader.sh_addralign ? SHeader.sh_addralign : 1);
  808. SHeader.sh_addr = LocationCounter;
  809. }
  810. static size_t findFirstNonGlobal(ArrayRef<ELFYAML::Symbol> Symbols) {
  811. for (size_t I = 0; I < Symbols.size(); ++I)
  812. if (Symbols[I].Binding.value != ELF::STB_LOCAL)
  813. return I;
  814. return Symbols.size();
  815. }
  816. template <class ELFT>
  817. std::vector<typename ELFT::Sym>
  818. ELFState<ELFT>::toELFSymbols(ArrayRef<ELFYAML::Symbol> Symbols,
  819. const StringTableBuilder &Strtab) {
  820. std::vector<Elf_Sym> Ret;
  821. Ret.resize(Symbols.size() + 1);
  822. size_t I = 0;
  823. for (const ELFYAML::Symbol &Sym : Symbols) {
  824. Elf_Sym &Symbol = Ret[++I];
  825. // If NameIndex, which contains the name offset, is explicitly specified, we
  826. // use it. This is useful for preparing broken objects. Otherwise, we add
  827. // the specified Name to the string table builder to get its offset.
  828. if (Sym.StName)
  829. Symbol.st_name = *Sym.StName;
  830. else if (!Sym.Name.empty())
  831. Symbol.st_name = Strtab.getOffset(ELFYAML::dropUniqueSuffix(Sym.Name));
  832. Symbol.setBindingAndType(Sym.Binding, Sym.Type);
  833. if (Sym.Section)
  834. Symbol.st_shndx = toSectionIndex(*Sym.Section, "", Sym.Name);
  835. else if (Sym.Index)
  836. Symbol.st_shndx = *Sym.Index;
  837. Symbol.st_value = Sym.Value.value_or(yaml::Hex64(0));
  838. Symbol.st_other = Sym.Other ? *Sym.Other : 0;
  839. Symbol.st_size = Sym.Size.value_or(yaml::Hex64(0));
  840. }
  841. return Ret;
  842. }
  843. template <class ELFT>
  844. void ELFState<ELFT>::initSymtabSectionHeader(Elf_Shdr &SHeader,
  845. SymtabType STType,
  846. ContiguousBlobAccumulator &CBA,
  847. ELFYAML::Section *YAMLSec) {
  848. bool IsStatic = STType == SymtabType::Static;
  849. ArrayRef<ELFYAML::Symbol> Symbols;
  850. if (IsStatic && Doc.Symbols)
  851. Symbols = *Doc.Symbols;
  852. else if (!IsStatic && Doc.DynamicSymbols)
  853. Symbols = *Doc.DynamicSymbols;
  854. ELFYAML::RawContentSection *RawSec =
  855. dyn_cast_or_null<ELFYAML::RawContentSection>(YAMLSec);
  856. if (RawSec && (RawSec->Content || RawSec->Size)) {
  857. bool HasSymbolsDescription =
  858. (IsStatic && Doc.Symbols) || (!IsStatic && Doc.DynamicSymbols);
  859. if (HasSymbolsDescription) {
  860. StringRef Property = (IsStatic ? "`Symbols`" : "`DynamicSymbols`");
  861. if (RawSec->Content)
  862. reportError("cannot specify both `Content` and " + Property +
  863. " for symbol table section '" + RawSec->Name + "'");
  864. if (RawSec->Size)
  865. reportError("cannot specify both `Size` and " + Property +
  866. " for symbol table section '" + RawSec->Name + "'");
  867. return;
  868. }
  869. }
  870. SHeader.sh_name = getSectionNameOffset(IsStatic ? ".symtab" : ".dynsym");
  871. if (YAMLSec)
  872. SHeader.sh_type = YAMLSec->Type;
  873. else
  874. SHeader.sh_type = IsStatic ? ELF::SHT_SYMTAB : ELF::SHT_DYNSYM;
  875. if (YAMLSec && YAMLSec->Flags)
  876. SHeader.sh_flags = *YAMLSec->Flags;
  877. else if (!IsStatic)
  878. SHeader.sh_flags = ELF::SHF_ALLOC;
  879. // If the symbol table section is explicitly described in the YAML
  880. // then we should set the fields requested.
  881. SHeader.sh_info = (RawSec && RawSec->Info) ? (unsigned)(*RawSec->Info)
  882. : findFirstNonGlobal(Symbols) + 1;
  883. SHeader.sh_addralign = YAMLSec ? (uint64_t)YAMLSec->AddressAlign : 8;
  884. assignSectionAddress(SHeader, YAMLSec);
  885. SHeader.sh_offset = alignToOffset(CBA, SHeader.sh_addralign,
  886. RawSec ? RawSec->Offset : std::nullopt);
  887. if (RawSec && (RawSec->Content || RawSec->Size)) {
  888. assert(Symbols.empty());
  889. SHeader.sh_size = writeContent(CBA, RawSec->Content, RawSec->Size);
  890. return;
  891. }
  892. std::vector<Elf_Sym> Syms =
  893. toELFSymbols(Symbols, IsStatic ? DotStrtab : DotDynstr);
  894. SHeader.sh_size = Syms.size() * sizeof(Elf_Sym);
  895. CBA.write((const char *)Syms.data(), SHeader.sh_size);
  896. }
  897. template <class ELFT>
  898. void ELFState<ELFT>::initStrtabSectionHeader(Elf_Shdr &SHeader, StringRef Name,
  899. StringTableBuilder &STB,
  900. ContiguousBlobAccumulator &CBA,
  901. ELFYAML::Section *YAMLSec) {
  902. SHeader.sh_name = getSectionNameOffset(ELFYAML::dropUniqueSuffix(Name));
  903. SHeader.sh_type = YAMLSec ? YAMLSec->Type : ELF::SHT_STRTAB;
  904. SHeader.sh_addralign = YAMLSec ? (uint64_t)YAMLSec->AddressAlign : 1;
  905. ELFYAML::RawContentSection *RawSec =
  906. dyn_cast_or_null<ELFYAML::RawContentSection>(YAMLSec);
  907. SHeader.sh_offset = alignToOffset(CBA, SHeader.sh_addralign,
  908. YAMLSec ? YAMLSec->Offset : std::nullopt);
  909. if (RawSec && (RawSec->Content || RawSec->Size)) {
  910. SHeader.sh_size = writeContent(CBA, RawSec->Content, RawSec->Size);
  911. } else {
  912. if (raw_ostream *OS = CBA.getRawOS(STB.getSize()))
  913. STB.write(*OS);
  914. SHeader.sh_size = STB.getSize();
  915. }
  916. if (RawSec && RawSec->Info)
  917. SHeader.sh_info = *RawSec->Info;
  918. if (YAMLSec && YAMLSec->Flags)
  919. SHeader.sh_flags = *YAMLSec->Flags;
  920. else if (Name == ".dynstr")
  921. SHeader.sh_flags = ELF::SHF_ALLOC;
  922. assignSectionAddress(SHeader, YAMLSec);
  923. }
  924. static bool shouldEmitDWARF(DWARFYAML::Data &DWARF, StringRef Name) {
  925. SetVector<StringRef> DebugSecNames = DWARF.getNonEmptySectionNames();
  926. return Name.consume_front(".") && DebugSecNames.count(Name);
  927. }
  928. template <class ELFT>
  929. Expected<uint64_t> emitDWARF(typename ELFT::Shdr &SHeader, StringRef Name,
  930. const DWARFYAML::Data &DWARF,
  931. ContiguousBlobAccumulator &CBA) {
  932. // We are unable to predict the size of debug data, so we request to write 0
  933. // bytes. This should always return us an output stream unless CBA is already
  934. // in an error state.
  935. raw_ostream *OS = CBA.getRawOS(0);
  936. if (!OS)
  937. return 0;
  938. uint64_t BeginOffset = CBA.tell();
  939. auto EmitFunc = DWARFYAML::getDWARFEmitterByName(Name.substr(1));
  940. if (Error Err = EmitFunc(*OS, DWARF))
  941. return std::move(Err);
  942. return CBA.tell() - BeginOffset;
  943. }
  944. template <class ELFT>
  945. void ELFState<ELFT>::initDWARFSectionHeader(Elf_Shdr &SHeader, StringRef Name,
  946. ContiguousBlobAccumulator &CBA,
  947. ELFYAML::Section *YAMLSec) {
  948. SHeader.sh_name = getSectionNameOffset(ELFYAML::dropUniqueSuffix(Name));
  949. SHeader.sh_type = YAMLSec ? YAMLSec->Type : ELF::SHT_PROGBITS;
  950. SHeader.sh_addralign = YAMLSec ? (uint64_t)YAMLSec->AddressAlign : 1;
  951. SHeader.sh_offset = alignToOffset(CBA, SHeader.sh_addralign,
  952. YAMLSec ? YAMLSec->Offset : std::nullopt);
  953. ELFYAML::RawContentSection *RawSec =
  954. dyn_cast_or_null<ELFYAML::RawContentSection>(YAMLSec);
  955. if (Doc.DWARF && shouldEmitDWARF(*Doc.DWARF, Name)) {
  956. if (RawSec && (RawSec->Content || RawSec->Size))
  957. reportError("cannot specify section '" + Name +
  958. "' contents in the 'DWARF' entry and the 'Content' "
  959. "or 'Size' in the 'Sections' entry at the same time");
  960. else {
  961. if (Expected<uint64_t> ShSizeOrErr =
  962. emitDWARF<ELFT>(SHeader, Name, *Doc.DWARF, CBA))
  963. SHeader.sh_size = *ShSizeOrErr;
  964. else
  965. reportError(ShSizeOrErr.takeError());
  966. }
  967. } else if (RawSec)
  968. SHeader.sh_size = writeContent(CBA, RawSec->Content, RawSec->Size);
  969. else
  970. llvm_unreachable("debug sections can only be initialized via the 'DWARF' "
  971. "entry or a RawContentSection");
  972. if (RawSec && RawSec->Info)
  973. SHeader.sh_info = *RawSec->Info;
  974. if (YAMLSec && YAMLSec->Flags)
  975. SHeader.sh_flags = *YAMLSec->Flags;
  976. else if (Name == ".debug_str")
  977. SHeader.sh_flags = ELF::SHF_MERGE | ELF::SHF_STRINGS;
  978. assignSectionAddress(SHeader, YAMLSec);
  979. }
  980. template <class ELFT> void ELFState<ELFT>::reportError(const Twine &Msg) {
  981. ErrHandler(Msg);
  982. HasError = true;
  983. }
  984. template <class ELFT> void ELFState<ELFT>::reportError(Error Err) {
  985. handleAllErrors(std::move(Err), [&](const ErrorInfoBase &Err) {
  986. reportError(Err.message());
  987. });
  988. }
  989. template <class ELFT>
  990. std::vector<Fragment>
  991. ELFState<ELFT>::getPhdrFragments(const ELFYAML::ProgramHeader &Phdr,
  992. ArrayRef<Elf_Shdr> SHeaders) {
  993. std::vector<Fragment> Ret;
  994. for (const ELFYAML::Chunk *C : Phdr.Chunks) {
  995. if (const ELFYAML::Fill *F = dyn_cast<ELFYAML::Fill>(C)) {
  996. Ret.push_back({*F->Offset, F->Size, llvm::ELF::SHT_PROGBITS,
  997. /*ShAddrAlign=*/1});
  998. continue;
  999. }
  1000. const ELFYAML::Section *S = cast<ELFYAML::Section>(C);
  1001. const Elf_Shdr &H = SHeaders[SN2I.get(S->Name)];
  1002. Ret.push_back({H.sh_offset, H.sh_size, H.sh_type, H.sh_addralign});
  1003. }
  1004. return Ret;
  1005. }
  1006. template <class ELFT>
  1007. void ELFState<ELFT>::setProgramHeaderLayout(std::vector<Elf_Phdr> &PHeaders,
  1008. std::vector<Elf_Shdr> &SHeaders) {
  1009. uint32_t PhdrIdx = 0;
  1010. for (auto &YamlPhdr : Doc.ProgramHeaders) {
  1011. Elf_Phdr &PHeader = PHeaders[PhdrIdx++];
  1012. std::vector<Fragment> Fragments = getPhdrFragments(YamlPhdr, SHeaders);
  1013. if (!llvm::is_sorted(Fragments, [](const Fragment &A, const Fragment &B) {
  1014. return A.Offset < B.Offset;
  1015. }))
  1016. reportError("sections in the program header with index " +
  1017. Twine(PhdrIdx) + " are not sorted by their file offset");
  1018. if (YamlPhdr.Offset) {
  1019. if (!Fragments.empty() && *YamlPhdr.Offset > Fragments.front().Offset)
  1020. reportError("'Offset' for segment with index " + Twine(PhdrIdx) +
  1021. " must be less than or equal to the minimum file offset of "
  1022. "all included sections (0x" +
  1023. Twine::utohexstr(Fragments.front().Offset) + ")");
  1024. PHeader.p_offset = *YamlPhdr.Offset;
  1025. } else if (!Fragments.empty()) {
  1026. PHeader.p_offset = Fragments.front().Offset;
  1027. }
  1028. // Set the file size if not set explicitly.
  1029. if (YamlPhdr.FileSize) {
  1030. PHeader.p_filesz = *YamlPhdr.FileSize;
  1031. } else if (!Fragments.empty()) {
  1032. uint64_t FileSize = Fragments.back().Offset - PHeader.p_offset;
  1033. // SHT_NOBITS sections occupy no physical space in a file, we should not
  1034. // take their sizes into account when calculating the file size of a
  1035. // segment.
  1036. if (Fragments.back().Type != llvm::ELF::SHT_NOBITS)
  1037. FileSize += Fragments.back().Size;
  1038. PHeader.p_filesz = FileSize;
  1039. }
  1040. // Find the maximum offset of the end of a section in order to set p_memsz.
  1041. uint64_t MemOffset = PHeader.p_offset;
  1042. for (const Fragment &F : Fragments)
  1043. MemOffset = std::max(MemOffset, F.Offset + F.Size);
  1044. // Set the memory size if not set explicitly.
  1045. PHeader.p_memsz = YamlPhdr.MemSize ? uint64_t(*YamlPhdr.MemSize)
  1046. : MemOffset - PHeader.p_offset;
  1047. if (YamlPhdr.Align) {
  1048. PHeader.p_align = *YamlPhdr.Align;
  1049. } else {
  1050. // Set the alignment of the segment to be the maximum alignment of the
  1051. // sections so that by default the segment has a valid and sensible
  1052. // alignment.
  1053. PHeader.p_align = 1;
  1054. for (const Fragment &F : Fragments)
  1055. PHeader.p_align = std::max((uint64_t)PHeader.p_align, F.AddrAlign);
  1056. }
  1057. }
  1058. }
  1059. bool llvm::ELFYAML::shouldAllocateFileSpace(
  1060. ArrayRef<ELFYAML::ProgramHeader> Phdrs, const ELFYAML::NoBitsSection &S) {
  1061. for (const ELFYAML::ProgramHeader &PH : Phdrs) {
  1062. auto It = llvm::find_if(
  1063. PH.Chunks, [&](ELFYAML::Chunk *C) { return C->Name == S.Name; });
  1064. if (std::any_of(It, PH.Chunks.end(), [](ELFYAML::Chunk *C) {
  1065. return (isa<ELFYAML::Fill>(C) ||
  1066. cast<ELFYAML::Section>(C)->Type != ELF::SHT_NOBITS);
  1067. }))
  1068. return true;
  1069. }
  1070. return false;
  1071. }
  1072. template <class ELFT>
  1073. void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
  1074. const ELFYAML::NoBitsSection &S,
  1075. ContiguousBlobAccumulator &CBA) {
  1076. if (!S.Size)
  1077. return;
  1078. SHeader.sh_size = *S.Size;
  1079. // When a nobits section is followed by a non-nobits section or fill
  1080. // in the same segment, we allocate the file space for it. This behavior
  1081. // matches linkers.
  1082. if (shouldAllocateFileSpace(Doc.ProgramHeaders, S))
  1083. CBA.writeZeros(*S.Size);
  1084. }
  1085. template <class ELFT>
  1086. void ELFState<ELFT>::writeSectionContent(
  1087. Elf_Shdr &SHeader, const ELFYAML::RawContentSection &Section,
  1088. ContiguousBlobAccumulator &CBA) {
  1089. if (Section.Info)
  1090. SHeader.sh_info = *Section.Info;
  1091. }
  1092. static bool isMips64EL(const ELFYAML::Object &Obj) {
  1093. return Obj.getMachine() == llvm::ELF::EM_MIPS &&
  1094. Obj.Header.Class == ELFYAML::ELF_ELFCLASS(ELF::ELFCLASS64) &&
  1095. Obj.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB);
  1096. }
  1097. template <class ELFT>
  1098. void ELFState<ELFT>::writeSectionContent(
  1099. Elf_Shdr &SHeader, const ELFYAML::RelocationSection &Section,
  1100. ContiguousBlobAccumulator &CBA) {
  1101. assert((Section.Type == llvm::ELF::SHT_REL ||
  1102. Section.Type == llvm::ELF::SHT_RELA) &&
  1103. "Section type is not SHT_REL nor SHT_RELA");
  1104. if (!Section.RelocatableSec.empty())
  1105. SHeader.sh_info = toSectionIndex(Section.RelocatableSec, Section.Name);
  1106. if (!Section.Relocations)
  1107. return;
  1108. const bool IsRela = Section.Type == llvm::ELF::SHT_RELA;
  1109. for (const ELFYAML::Relocation &Rel : *Section.Relocations) {
  1110. const bool IsDynamic = Section.Link && (*Section.Link == ".dynsym");
  1111. unsigned SymIdx =
  1112. Rel.Symbol ? toSymbolIndex(*Rel.Symbol, Section.Name, IsDynamic) : 0;
  1113. if (IsRela) {
  1114. Elf_Rela REntry;
  1115. zero(REntry);
  1116. REntry.r_offset = Rel.Offset;
  1117. REntry.r_addend = Rel.Addend;
  1118. REntry.setSymbolAndType(SymIdx, Rel.Type, isMips64EL(Doc));
  1119. CBA.write((const char *)&REntry, sizeof(REntry));
  1120. } else {
  1121. Elf_Rel REntry;
  1122. zero(REntry);
  1123. REntry.r_offset = Rel.Offset;
  1124. REntry.setSymbolAndType(SymIdx, Rel.Type, isMips64EL(Doc));
  1125. CBA.write((const char *)&REntry, sizeof(REntry));
  1126. }
  1127. }
  1128. SHeader.sh_size = (IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel)) *
  1129. Section.Relocations->size();
  1130. }
  1131. template <class ELFT>
  1132. void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
  1133. const ELFYAML::RelrSection &Section,
  1134. ContiguousBlobAccumulator &CBA) {
  1135. if (!Section.Entries)
  1136. return;
  1137. for (llvm::yaml::Hex64 E : *Section.Entries) {
  1138. if (!ELFT::Is64Bits && E > UINT32_MAX)
  1139. reportError(Section.Name + ": the value is too large for 32-bits: 0x" +
  1140. Twine::utohexstr(E));
  1141. CBA.write<uintX_t>(E, ELFT::TargetEndianness);
  1142. }
  1143. SHeader.sh_size = sizeof(uintX_t) * Section.Entries->size();
  1144. }
  1145. template <class ELFT>
  1146. void ELFState<ELFT>::writeSectionContent(
  1147. Elf_Shdr &SHeader, const ELFYAML::SymtabShndxSection &Shndx,
  1148. ContiguousBlobAccumulator &CBA) {
  1149. if (Shndx.Content || Shndx.Size) {
  1150. SHeader.sh_size = writeContent(CBA, Shndx.Content, Shndx.Size);
  1151. return;
  1152. }
  1153. if (!Shndx.Entries)
  1154. return;
  1155. for (uint32_t E : *Shndx.Entries)
  1156. CBA.write<uint32_t>(E, ELFT::TargetEndianness);
  1157. SHeader.sh_size = Shndx.Entries->size() * SHeader.sh_entsize;
  1158. }
  1159. template <class ELFT>
  1160. void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
  1161. const ELFYAML::GroupSection &Section,
  1162. ContiguousBlobAccumulator &CBA) {
  1163. assert(Section.Type == llvm::ELF::SHT_GROUP &&
  1164. "Section type is not SHT_GROUP");
  1165. if (Section.Signature)
  1166. SHeader.sh_info =
  1167. toSymbolIndex(*Section.Signature, Section.Name, /*IsDynamic=*/false);
  1168. if (!Section.Members)
  1169. return;
  1170. for (const ELFYAML::SectionOrType &Member : *Section.Members) {
  1171. unsigned int SectionIndex = 0;
  1172. if (Member.sectionNameOrType == "GRP_COMDAT")
  1173. SectionIndex = llvm::ELF::GRP_COMDAT;
  1174. else
  1175. SectionIndex = toSectionIndex(Member.sectionNameOrType, Section.Name);
  1176. CBA.write<uint32_t>(SectionIndex, ELFT::TargetEndianness);
  1177. }
  1178. SHeader.sh_size = SHeader.sh_entsize * Section.Members->size();
  1179. }
  1180. template <class ELFT>
  1181. void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
  1182. const ELFYAML::SymverSection &Section,
  1183. ContiguousBlobAccumulator &CBA) {
  1184. if (!Section.Entries)
  1185. return;
  1186. for (uint16_t Version : *Section.Entries)
  1187. CBA.write<uint16_t>(Version, ELFT::TargetEndianness);
  1188. SHeader.sh_size = Section.Entries->size() * SHeader.sh_entsize;
  1189. }
  1190. template <class ELFT>
  1191. void ELFState<ELFT>::writeSectionContent(
  1192. Elf_Shdr &SHeader, const ELFYAML::StackSizesSection &Section,
  1193. ContiguousBlobAccumulator &CBA) {
  1194. if (!Section.Entries)
  1195. return;
  1196. for (const ELFYAML::StackSizeEntry &E : *Section.Entries) {
  1197. CBA.write<uintX_t>(E.Address, ELFT::TargetEndianness);
  1198. SHeader.sh_size += sizeof(uintX_t) + CBA.writeULEB128(E.Size);
  1199. }
  1200. }
  1201. template <class ELFT>
  1202. void ELFState<ELFT>::writeSectionContent(
  1203. Elf_Shdr &SHeader, const ELFYAML::BBAddrMapSection &Section,
  1204. ContiguousBlobAccumulator &CBA) {
  1205. if (!Section.Entries)
  1206. return;
  1207. for (const ELFYAML::BBAddrMapEntry &E : *Section.Entries) {
  1208. // Write version and feature values.
  1209. if (Section.Type == llvm::ELF::SHT_LLVM_BB_ADDR_MAP) {
  1210. if (E.Version > 2)
  1211. WithColor::warning() << "unsupported SHT_LLVM_BB_ADDR_MAP version: "
  1212. << static_cast<int>(E.Version)
  1213. << "; encoding using the most recent version";
  1214. CBA.write(E.Version);
  1215. CBA.write(E.Feature);
  1216. SHeader.sh_size += 2;
  1217. }
  1218. // Write the address of the function.
  1219. CBA.write<uintX_t>(E.Address, ELFT::TargetEndianness);
  1220. // Write number of BBEntries (number of basic blocks in the function). This
  1221. // is overridden by the 'NumBlocks' YAML field when specified.
  1222. uint64_t NumBlocks =
  1223. E.NumBlocks.value_or(E.BBEntries ? E.BBEntries->size() : 0);
  1224. SHeader.sh_size += sizeof(uintX_t) + CBA.writeULEB128(NumBlocks);
  1225. // Write all BBEntries.
  1226. if (!E.BBEntries)
  1227. continue;
  1228. for (const ELFYAML::BBAddrMapEntry::BBEntry &BBE : *E.BBEntries) {
  1229. if (Section.Type == llvm::ELF::SHT_LLVM_BB_ADDR_MAP && E.Version > 1)
  1230. SHeader.sh_size += CBA.writeULEB128(BBE.ID);
  1231. SHeader.sh_size += CBA.writeULEB128(BBE.AddressOffset) +
  1232. CBA.writeULEB128(BBE.Size) +
  1233. CBA.writeULEB128(BBE.Metadata);
  1234. }
  1235. }
  1236. }
  1237. template <class ELFT>
  1238. void ELFState<ELFT>::writeSectionContent(
  1239. Elf_Shdr &SHeader, const ELFYAML::LinkerOptionsSection &Section,
  1240. ContiguousBlobAccumulator &CBA) {
  1241. if (!Section.Options)
  1242. return;
  1243. for (const ELFYAML::LinkerOption &LO : *Section.Options) {
  1244. CBA.write(LO.Key.data(), LO.Key.size());
  1245. CBA.write('\0');
  1246. CBA.write(LO.Value.data(), LO.Value.size());
  1247. CBA.write('\0');
  1248. SHeader.sh_size += (LO.Key.size() + LO.Value.size() + 2);
  1249. }
  1250. }
  1251. template <class ELFT>
  1252. void ELFState<ELFT>::writeSectionContent(
  1253. Elf_Shdr &SHeader, const ELFYAML::DependentLibrariesSection &Section,
  1254. ContiguousBlobAccumulator &CBA) {
  1255. if (!Section.Libs)
  1256. return;
  1257. for (StringRef Lib : *Section.Libs) {
  1258. CBA.write(Lib.data(), Lib.size());
  1259. CBA.write('\0');
  1260. SHeader.sh_size += Lib.size() + 1;
  1261. }
  1262. }
  1263. template <class ELFT>
  1264. uint64_t
  1265. ELFState<ELFT>::alignToOffset(ContiguousBlobAccumulator &CBA, uint64_t Align,
  1266. std::optional<llvm::yaml::Hex64> Offset) {
  1267. uint64_t CurrentOffset = CBA.getOffset();
  1268. uint64_t AlignedOffset;
  1269. if (Offset) {
  1270. if ((uint64_t)*Offset < CurrentOffset) {
  1271. reportError("the 'Offset' value (0x" +
  1272. Twine::utohexstr((uint64_t)*Offset) + ") goes backward");
  1273. return CurrentOffset;
  1274. }
  1275. // We ignore an alignment when an explicit offset has been requested.
  1276. AlignedOffset = *Offset;
  1277. } else {
  1278. AlignedOffset = alignTo(CurrentOffset, std::max(Align, (uint64_t)1));
  1279. }
  1280. CBA.writeZeros(AlignedOffset - CurrentOffset);
  1281. return AlignedOffset;
  1282. }
  1283. template <class ELFT>
  1284. void ELFState<ELFT>::writeSectionContent(
  1285. Elf_Shdr &SHeader, const ELFYAML::CallGraphProfileSection &Section,
  1286. ContiguousBlobAccumulator &CBA) {
  1287. if (!Section.Entries)
  1288. return;
  1289. for (const ELFYAML::CallGraphEntryWeight &E : *Section.Entries) {
  1290. CBA.write<uint64_t>(E.Weight, ELFT::TargetEndianness);
  1291. SHeader.sh_size += sizeof(object::Elf_CGProfile_Impl<ELFT>);
  1292. }
  1293. }
  1294. template <class ELFT>
  1295. void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
  1296. const ELFYAML::HashSection &Section,
  1297. ContiguousBlobAccumulator &CBA) {
  1298. if (!Section.Bucket)
  1299. return;
  1300. CBA.write<uint32_t>(
  1301. Section.NBucket.value_or(llvm::yaml::Hex64(Section.Bucket->size())),
  1302. ELFT::TargetEndianness);
  1303. CBA.write<uint32_t>(
  1304. Section.NChain.value_or(llvm::yaml::Hex64(Section.Chain->size())),
  1305. ELFT::TargetEndianness);
  1306. for (uint32_t Val : *Section.Bucket)
  1307. CBA.write<uint32_t>(Val, ELFT::TargetEndianness);
  1308. for (uint32_t Val : *Section.Chain)
  1309. CBA.write<uint32_t>(Val, ELFT::TargetEndianness);
  1310. SHeader.sh_size = (2 + Section.Bucket->size() + Section.Chain->size()) * 4;
  1311. }
  1312. template <class ELFT>
  1313. void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
  1314. const ELFYAML::VerdefSection &Section,
  1315. ContiguousBlobAccumulator &CBA) {
  1316. if (Section.Info)
  1317. SHeader.sh_info = *Section.Info;
  1318. else if (Section.Entries)
  1319. SHeader.sh_info = Section.Entries->size();
  1320. if (!Section.Entries)
  1321. return;
  1322. uint64_t AuxCnt = 0;
  1323. for (size_t I = 0; I < Section.Entries->size(); ++I) {
  1324. const ELFYAML::VerdefEntry &E = (*Section.Entries)[I];
  1325. Elf_Verdef VerDef;
  1326. VerDef.vd_version = E.Version.value_or(1);
  1327. VerDef.vd_flags = E.Flags.value_or(0);
  1328. VerDef.vd_ndx = E.VersionNdx.value_or(0);
  1329. VerDef.vd_hash = E.Hash.value_or(0);
  1330. VerDef.vd_aux = sizeof(Elf_Verdef);
  1331. VerDef.vd_cnt = E.VerNames.size();
  1332. if (I == Section.Entries->size() - 1)
  1333. VerDef.vd_next = 0;
  1334. else
  1335. VerDef.vd_next =
  1336. sizeof(Elf_Verdef) + E.VerNames.size() * sizeof(Elf_Verdaux);
  1337. CBA.write((const char *)&VerDef, sizeof(Elf_Verdef));
  1338. for (size_t J = 0; J < E.VerNames.size(); ++J, ++AuxCnt) {
  1339. Elf_Verdaux VernAux;
  1340. VernAux.vda_name = DotDynstr.getOffset(E.VerNames[J]);
  1341. if (J == E.VerNames.size() - 1)
  1342. VernAux.vda_next = 0;
  1343. else
  1344. VernAux.vda_next = sizeof(Elf_Verdaux);
  1345. CBA.write((const char *)&VernAux, sizeof(Elf_Verdaux));
  1346. }
  1347. }
  1348. SHeader.sh_size = Section.Entries->size() * sizeof(Elf_Verdef) +
  1349. AuxCnt * sizeof(Elf_Verdaux);
  1350. }
  1351. template <class ELFT>
  1352. void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
  1353. const ELFYAML::VerneedSection &Section,
  1354. ContiguousBlobAccumulator &CBA) {
  1355. if (Section.Info)
  1356. SHeader.sh_info = *Section.Info;
  1357. else if (Section.VerneedV)
  1358. SHeader.sh_info = Section.VerneedV->size();
  1359. if (!Section.VerneedV)
  1360. return;
  1361. uint64_t AuxCnt = 0;
  1362. for (size_t I = 0; I < Section.VerneedV->size(); ++I) {
  1363. const ELFYAML::VerneedEntry &VE = (*Section.VerneedV)[I];
  1364. Elf_Verneed VerNeed;
  1365. VerNeed.vn_version = VE.Version;
  1366. VerNeed.vn_file = DotDynstr.getOffset(VE.File);
  1367. if (I == Section.VerneedV->size() - 1)
  1368. VerNeed.vn_next = 0;
  1369. else
  1370. VerNeed.vn_next =
  1371. sizeof(Elf_Verneed) + VE.AuxV.size() * sizeof(Elf_Vernaux);
  1372. VerNeed.vn_cnt = VE.AuxV.size();
  1373. VerNeed.vn_aux = sizeof(Elf_Verneed);
  1374. CBA.write((const char *)&VerNeed, sizeof(Elf_Verneed));
  1375. for (size_t J = 0; J < VE.AuxV.size(); ++J, ++AuxCnt) {
  1376. const ELFYAML::VernauxEntry &VAuxE = VE.AuxV[J];
  1377. Elf_Vernaux VernAux;
  1378. VernAux.vna_hash = VAuxE.Hash;
  1379. VernAux.vna_flags = VAuxE.Flags;
  1380. VernAux.vna_other = VAuxE.Other;
  1381. VernAux.vna_name = DotDynstr.getOffset(VAuxE.Name);
  1382. if (J == VE.AuxV.size() - 1)
  1383. VernAux.vna_next = 0;
  1384. else
  1385. VernAux.vna_next = sizeof(Elf_Vernaux);
  1386. CBA.write((const char *)&VernAux, sizeof(Elf_Vernaux));
  1387. }
  1388. }
  1389. SHeader.sh_size = Section.VerneedV->size() * sizeof(Elf_Verneed) +
  1390. AuxCnt * sizeof(Elf_Vernaux);
  1391. }
  1392. template <class ELFT>
  1393. void ELFState<ELFT>::writeSectionContent(
  1394. Elf_Shdr &SHeader, const ELFYAML::ARMIndexTableSection &Section,
  1395. ContiguousBlobAccumulator &CBA) {
  1396. if (!Section.Entries)
  1397. return;
  1398. for (const ELFYAML::ARMIndexTableEntry &E : *Section.Entries) {
  1399. CBA.write<uint32_t>(E.Offset, ELFT::TargetEndianness);
  1400. CBA.write<uint32_t>(E.Value, ELFT::TargetEndianness);
  1401. }
  1402. SHeader.sh_size = Section.Entries->size() * 8;
  1403. }
  1404. template <class ELFT>
  1405. void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
  1406. const ELFYAML::MipsABIFlags &Section,
  1407. ContiguousBlobAccumulator &CBA) {
  1408. assert(Section.Type == llvm::ELF::SHT_MIPS_ABIFLAGS &&
  1409. "Section type is not SHT_MIPS_ABIFLAGS");
  1410. object::Elf_Mips_ABIFlags<ELFT> Flags;
  1411. zero(Flags);
  1412. SHeader.sh_size = SHeader.sh_entsize;
  1413. Flags.version = Section.Version;
  1414. Flags.isa_level = Section.ISALevel;
  1415. Flags.isa_rev = Section.ISARevision;
  1416. Flags.gpr_size = Section.GPRSize;
  1417. Flags.cpr1_size = Section.CPR1Size;
  1418. Flags.cpr2_size = Section.CPR2Size;
  1419. Flags.fp_abi = Section.FpABI;
  1420. Flags.isa_ext = Section.ISAExtension;
  1421. Flags.ases = Section.ASEs;
  1422. Flags.flags1 = Section.Flags1;
  1423. Flags.flags2 = Section.Flags2;
  1424. CBA.write((const char *)&Flags, sizeof(Flags));
  1425. }
  1426. template <class ELFT>
  1427. void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
  1428. const ELFYAML::DynamicSection &Section,
  1429. ContiguousBlobAccumulator &CBA) {
  1430. assert(Section.Type == llvm::ELF::SHT_DYNAMIC &&
  1431. "Section type is not SHT_DYNAMIC");
  1432. if (!Section.Entries)
  1433. return;
  1434. for (const ELFYAML::DynamicEntry &DE : *Section.Entries) {
  1435. CBA.write<uintX_t>(DE.Tag, ELFT::TargetEndianness);
  1436. CBA.write<uintX_t>(DE.Val, ELFT::TargetEndianness);
  1437. }
  1438. SHeader.sh_size = 2 * sizeof(uintX_t) * Section.Entries->size();
  1439. }
  1440. template <class ELFT>
  1441. void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
  1442. const ELFYAML::AddrsigSection &Section,
  1443. ContiguousBlobAccumulator &CBA) {
  1444. if (!Section.Symbols)
  1445. return;
  1446. for (StringRef Sym : *Section.Symbols)
  1447. SHeader.sh_size +=
  1448. CBA.writeULEB128(toSymbolIndex(Sym, Section.Name, /*IsDynamic=*/false));
  1449. }
  1450. template <class ELFT>
  1451. void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
  1452. const ELFYAML::NoteSection &Section,
  1453. ContiguousBlobAccumulator &CBA) {
  1454. if (!Section.Notes)
  1455. return;
  1456. uint64_t Offset = CBA.tell();
  1457. for (const ELFYAML::NoteEntry &NE : *Section.Notes) {
  1458. // Write name size.
  1459. if (NE.Name.empty())
  1460. CBA.write<uint32_t>(0, ELFT::TargetEndianness);
  1461. else
  1462. CBA.write<uint32_t>(NE.Name.size() + 1, ELFT::TargetEndianness);
  1463. // Write description size.
  1464. if (NE.Desc.binary_size() == 0)
  1465. CBA.write<uint32_t>(0, ELFT::TargetEndianness);
  1466. else
  1467. CBA.write<uint32_t>(NE.Desc.binary_size(), ELFT::TargetEndianness);
  1468. // Write type.
  1469. CBA.write<uint32_t>(NE.Type, ELFT::TargetEndianness);
  1470. // Write name, null terminator and padding.
  1471. if (!NE.Name.empty()) {
  1472. CBA.write(NE.Name.data(), NE.Name.size());
  1473. CBA.write('\0');
  1474. CBA.padToAlignment(4);
  1475. }
  1476. // Write description and padding.
  1477. if (NE.Desc.binary_size() != 0) {
  1478. CBA.writeAsBinary(NE.Desc);
  1479. CBA.padToAlignment(4);
  1480. }
  1481. }
  1482. SHeader.sh_size = CBA.tell() - Offset;
  1483. }
  1484. template <class ELFT>
  1485. void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
  1486. const ELFYAML::GnuHashSection &Section,
  1487. ContiguousBlobAccumulator &CBA) {
  1488. if (!Section.HashBuckets)
  1489. return;
  1490. if (!Section.Header)
  1491. return;
  1492. // We write the header first, starting with the hash buckets count. Normally
  1493. // it is the number of entries in HashBuckets, but the "NBuckets" property can
  1494. // be used to override this field, which is useful for producing broken
  1495. // objects.
  1496. if (Section.Header->NBuckets)
  1497. CBA.write<uint32_t>(*Section.Header->NBuckets, ELFT::TargetEndianness);
  1498. else
  1499. CBA.write<uint32_t>(Section.HashBuckets->size(), ELFT::TargetEndianness);
  1500. // Write the index of the first symbol in the dynamic symbol table accessible
  1501. // via the hash table.
  1502. CBA.write<uint32_t>(Section.Header->SymNdx, ELFT::TargetEndianness);
  1503. // Write the number of words in the Bloom filter. As above, the "MaskWords"
  1504. // property can be used to set this field to any value.
  1505. if (Section.Header->MaskWords)
  1506. CBA.write<uint32_t>(*Section.Header->MaskWords, ELFT::TargetEndianness);
  1507. else
  1508. CBA.write<uint32_t>(Section.BloomFilter->size(), ELFT::TargetEndianness);
  1509. // Write the shift constant used by the Bloom filter.
  1510. CBA.write<uint32_t>(Section.Header->Shift2, ELFT::TargetEndianness);
  1511. // We've finished writing the header. Now write the Bloom filter.
  1512. for (llvm::yaml::Hex64 Val : *Section.BloomFilter)
  1513. CBA.write<uintX_t>(Val, ELFT::TargetEndianness);
  1514. // Write an array of hash buckets.
  1515. for (llvm::yaml::Hex32 Val : *Section.HashBuckets)
  1516. CBA.write<uint32_t>(Val, ELFT::TargetEndianness);
  1517. // Write an array of hash values.
  1518. for (llvm::yaml::Hex32 Val : *Section.HashValues)
  1519. CBA.write<uint32_t>(Val, ELFT::TargetEndianness);
  1520. SHeader.sh_size = 16 /*Header size*/ +
  1521. Section.BloomFilter->size() * sizeof(typename ELFT::uint) +
  1522. Section.HashBuckets->size() * 4 +
  1523. Section.HashValues->size() * 4;
  1524. }
  1525. template <class ELFT>
  1526. void ELFState<ELFT>::writeFill(ELFYAML::Fill &Fill,
  1527. ContiguousBlobAccumulator &CBA) {
  1528. size_t PatternSize = Fill.Pattern ? Fill.Pattern->binary_size() : 0;
  1529. if (!PatternSize) {
  1530. CBA.writeZeros(Fill.Size);
  1531. return;
  1532. }
  1533. // Fill the content with the specified pattern.
  1534. uint64_t Written = 0;
  1535. for (; Written + PatternSize <= Fill.Size; Written += PatternSize)
  1536. CBA.writeAsBinary(*Fill.Pattern);
  1537. CBA.writeAsBinary(*Fill.Pattern, Fill.Size - Written);
  1538. }
  1539. template <class ELFT>
  1540. DenseMap<StringRef, size_t> ELFState<ELFT>::buildSectionHeaderReorderMap() {
  1541. const ELFYAML::SectionHeaderTable &SectionHeaders =
  1542. Doc.getSectionHeaderTable();
  1543. if (SectionHeaders.IsImplicit || SectionHeaders.NoHeaders ||
  1544. SectionHeaders.isDefault())
  1545. return DenseMap<StringRef, size_t>();
  1546. DenseMap<StringRef, size_t> Ret;
  1547. size_t SecNdx = 0;
  1548. StringSet<> Seen;
  1549. auto AddSection = [&](const ELFYAML::SectionHeader &Hdr) {
  1550. if (!Ret.try_emplace(Hdr.Name, ++SecNdx).second)
  1551. reportError("repeated section name: '" + Hdr.Name +
  1552. "' in the section header description");
  1553. Seen.insert(Hdr.Name);
  1554. };
  1555. if (SectionHeaders.Sections)
  1556. for (const ELFYAML::SectionHeader &Hdr : *SectionHeaders.Sections)
  1557. AddSection(Hdr);
  1558. if (SectionHeaders.Excluded)
  1559. for (const ELFYAML::SectionHeader &Hdr : *SectionHeaders.Excluded)
  1560. AddSection(Hdr);
  1561. for (const ELFYAML::Section *S : Doc.getSections()) {
  1562. // Ignore special first SHT_NULL section.
  1563. if (S == Doc.getSections().front())
  1564. continue;
  1565. if (!Seen.count(S->Name))
  1566. reportError("section '" + S->Name +
  1567. "' should be present in the 'Sections' or 'Excluded' lists");
  1568. Seen.erase(S->Name);
  1569. }
  1570. for (const auto &It : Seen)
  1571. reportError("section header contains undefined section '" + It.getKey() +
  1572. "'");
  1573. return Ret;
  1574. }
  1575. template <class ELFT> void ELFState<ELFT>::buildSectionIndex() {
  1576. // A YAML description can have an explicit section header declaration that
  1577. // allows to change the order of section headers.
  1578. DenseMap<StringRef, size_t> ReorderMap = buildSectionHeaderReorderMap();
  1579. if (HasError)
  1580. return;
  1581. // Build excluded section headers map.
  1582. std::vector<ELFYAML::Section *> Sections = Doc.getSections();
  1583. const ELFYAML::SectionHeaderTable &SectionHeaders =
  1584. Doc.getSectionHeaderTable();
  1585. if (SectionHeaders.Excluded)
  1586. for (const ELFYAML::SectionHeader &Hdr : *SectionHeaders.Excluded)
  1587. if (!ExcludedSectionHeaders.insert(Hdr.Name).second)
  1588. llvm_unreachable("buildSectionIndex() failed");
  1589. if (SectionHeaders.NoHeaders.value_or(false))
  1590. for (const ELFYAML::Section *S : Sections)
  1591. if (!ExcludedSectionHeaders.insert(S->Name).second)
  1592. llvm_unreachable("buildSectionIndex() failed");
  1593. size_t SecNdx = -1;
  1594. for (const ELFYAML::Section *S : Sections) {
  1595. ++SecNdx;
  1596. size_t Index = ReorderMap.empty() ? SecNdx : ReorderMap.lookup(S->Name);
  1597. if (!SN2I.addName(S->Name, Index))
  1598. llvm_unreachable("buildSectionIndex() failed");
  1599. if (!ExcludedSectionHeaders.count(S->Name))
  1600. ShStrtabStrings->add(ELFYAML::dropUniqueSuffix(S->Name));
  1601. }
  1602. }
  1603. template <class ELFT> void ELFState<ELFT>::buildSymbolIndexes() {
  1604. auto Build = [this](ArrayRef<ELFYAML::Symbol> V, NameToIdxMap &Map) {
  1605. for (size_t I = 0, S = V.size(); I < S; ++I) {
  1606. const ELFYAML::Symbol &Sym = V[I];
  1607. if (!Sym.Name.empty() && !Map.addName(Sym.Name, I + 1))
  1608. reportError("repeated symbol name: '" + Sym.Name + "'");
  1609. }
  1610. };
  1611. if (Doc.Symbols)
  1612. Build(*Doc.Symbols, SymN2I);
  1613. if (Doc.DynamicSymbols)
  1614. Build(*Doc.DynamicSymbols, DynSymN2I);
  1615. }
  1616. template <class ELFT> void ELFState<ELFT>::finalizeStrings() {
  1617. // Add the regular symbol names to .strtab section.
  1618. if (Doc.Symbols)
  1619. for (const ELFYAML::Symbol &Sym : *Doc.Symbols)
  1620. DotStrtab.add(ELFYAML::dropUniqueSuffix(Sym.Name));
  1621. DotStrtab.finalize();
  1622. // Add the dynamic symbol names to .dynstr section.
  1623. if (Doc.DynamicSymbols)
  1624. for (const ELFYAML::Symbol &Sym : *Doc.DynamicSymbols)
  1625. DotDynstr.add(ELFYAML::dropUniqueSuffix(Sym.Name));
  1626. // SHT_GNU_verdef and SHT_GNU_verneed sections might also
  1627. // add strings to .dynstr section.
  1628. for (const ELFYAML::Chunk *Sec : Doc.getSections()) {
  1629. if (auto VerNeed = dyn_cast<ELFYAML::VerneedSection>(Sec)) {
  1630. if (VerNeed->VerneedV) {
  1631. for (const ELFYAML::VerneedEntry &VE : *VerNeed->VerneedV) {
  1632. DotDynstr.add(VE.File);
  1633. for (const ELFYAML::VernauxEntry &Aux : VE.AuxV)
  1634. DotDynstr.add(Aux.Name);
  1635. }
  1636. }
  1637. } else if (auto VerDef = dyn_cast<ELFYAML::VerdefSection>(Sec)) {
  1638. if (VerDef->Entries)
  1639. for (const ELFYAML::VerdefEntry &E : *VerDef->Entries)
  1640. for (StringRef Name : E.VerNames)
  1641. DotDynstr.add(Name);
  1642. }
  1643. }
  1644. DotDynstr.finalize();
  1645. // Don't finalize the section header string table a second time if it has
  1646. // already been finalized due to being one of the symbol string tables.
  1647. if (ShStrtabStrings != &DotStrtab && ShStrtabStrings != &DotDynstr)
  1648. ShStrtabStrings->finalize();
  1649. }
  1650. template <class ELFT>
  1651. bool ELFState<ELFT>::writeELF(raw_ostream &OS, ELFYAML::Object &Doc,
  1652. yaml::ErrorHandler EH, uint64_t MaxSize) {
  1653. ELFState<ELFT> State(Doc, EH);
  1654. if (State.HasError)
  1655. return false;
  1656. // Build the section index, which adds sections to the section header string
  1657. // table first, so that we can finalize the section header string table.
  1658. State.buildSectionIndex();
  1659. State.buildSymbolIndexes();
  1660. // Finalize section header string table and the .strtab and .dynstr sections.
  1661. // We do this early because we want to finalize the string table builders
  1662. // before writing the content of the sections that might want to use them.
  1663. State.finalizeStrings();
  1664. if (State.HasError)
  1665. return false;
  1666. std::vector<Elf_Phdr> PHeaders;
  1667. State.initProgramHeaders(PHeaders);
  1668. // XXX: This offset is tightly coupled with the order that we write
  1669. // things to `OS`.
  1670. const size_t SectionContentBeginOffset =
  1671. sizeof(Elf_Ehdr) + sizeof(Elf_Phdr) * Doc.ProgramHeaders.size();
  1672. // It is quite easy to accidentally create output with yaml2obj that is larger
  1673. // than intended, for example, due to an issue in the YAML description.
  1674. // We limit the maximum allowed output size, but also provide a command line
  1675. // option to change this limitation.
  1676. ContiguousBlobAccumulator CBA(SectionContentBeginOffset, MaxSize);
  1677. std::vector<Elf_Shdr> SHeaders;
  1678. State.initSectionHeaders(SHeaders, CBA);
  1679. // Now we can decide segment offsets.
  1680. State.setProgramHeaderLayout(PHeaders, SHeaders);
  1681. bool ReachedLimit = CBA.getOffset() > MaxSize;
  1682. if (Error E = CBA.takeLimitError()) {
  1683. // We report a custom error message instead below.
  1684. consumeError(std::move(E));
  1685. ReachedLimit = true;
  1686. }
  1687. if (ReachedLimit)
  1688. State.reportError(
  1689. "the desired output size is greater than permitted. Use the "
  1690. "--max-size option to change the limit");
  1691. if (State.HasError)
  1692. return false;
  1693. State.writeELFHeader(OS);
  1694. writeArrayData(OS, ArrayRef(PHeaders));
  1695. const ELFYAML::SectionHeaderTable &SHT = Doc.getSectionHeaderTable();
  1696. if (!SHT.NoHeaders.value_or(false))
  1697. CBA.updateDataAt(*SHT.Offset, SHeaders.data(),
  1698. SHT.getNumHeaders(SHeaders.size()) * sizeof(Elf_Shdr));
  1699. CBA.writeBlobToStream(OS);
  1700. return true;
  1701. }
  1702. namespace llvm {
  1703. namespace yaml {
  1704. bool yaml2elf(llvm::ELFYAML::Object &Doc, raw_ostream &Out, ErrorHandler EH,
  1705. uint64_t MaxSize) {
  1706. bool IsLE = Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB);
  1707. bool Is64Bit = Doc.Header.Class == ELFYAML::ELF_ELFCLASS(ELF::ELFCLASS64);
  1708. if (Is64Bit) {
  1709. if (IsLE)
  1710. return ELFState<object::ELF64LE>::writeELF(Out, Doc, EH, MaxSize);
  1711. return ELFState<object::ELF64BE>::writeELF(Out, Doc, EH, MaxSize);
  1712. }
  1713. if (IsLE)
  1714. return ELFState<object::ELF32LE>::writeELF(Out, Doc, EH, MaxSize);
  1715. return ELFState<object::ELF32BE>::writeELF(Out, Doc, EH, MaxSize);
  1716. }
  1717. } // namespace yaml
  1718. } // namespace llvm