ELFEmitter.cpp 68 KB

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