ELFEmitter.cpp 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989
  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. using namespace llvm;
  34. // This class is used to build up a contiguous binary blob while keeping
  35. // track of an offset in the output (which notionally begins at
  36. // `InitialOffset`).
  37. // The blob might be limited to an arbitrary size. All attempts to write data
  38. // are ignored and the error condition is remembered once the limit is reached.
  39. // Such an approach allows us to simplify the code by delaying error reporting
  40. // and doing it at a convenient time.
  41. namespace {
  42. class ContiguousBlobAccumulator {
  43. const uint64_t InitialOffset;
  44. const uint64_t MaxSize;
  45. SmallVector<char, 128> Buf;
  46. raw_svector_ostream OS;
  47. Error ReachedLimitErr = Error::success();
  48. bool checkLimit(uint64_t Size) {
  49. if (!ReachedLimitErr && getOffset() + Size <= MaxSize)
  50. return true;
  51. if (!ReachedLimitErr)
  52. ReachedLimitErr = createStringError(errc::invalid_argument,
  53. "reached the output size limit");
  54. return false;
  55. }
  56. public:
  57. ContiguousBlobAccumulator(uint64_t BaseOffset, uint64_t SizeLimit)
  58. : InitialOffset(BaseOffset), MaxSize(SizeLimit), OS(Buf) {}
  59. uint64_t tell() const { return OS.tell(); }
  60. uint64_t getOffset() const { return InitialOffset + OS.tell(); }
  61. void writeBlobToStream(raw_ostream &Out) const { Out << OS.str(); }
  62. Error takeLimitError() {
  63. // Request to write 0 bytes to check we did not reach the limit.
  64. checkLimit(0);
  65. return std::move(ReachedLimitErr);
  66. }
  67. /// \returns The new offset.
  68. uint64_t padToAlignment(unsigned Align) {
  69. uint64_t CurrentOffset = getOffset();
  70. if (ReachedLimitErr)
  71. return CurrentOffset;
  72. uint64_t AlignedOffset = alignTo(CurrentOffset, Align == 0 ? 1 : Align);
  73. uint64_t PaddingSize = AlignedOffset - CurrentOffset;
  74. if (!checkLimit(PaddingSize))
  75. return CurrentOffset;
  76. writeZeros(PaddingSize);
  77. return AlignedOffset;
  78. }
  79. raw_ostream *getRawOS(uint64_t Size) {
  80. if (checkLimit(Size))
  81. return &OS;
  82. return nullptr;
  83. }
  84. void writeAsBinary(const yaml::BinaryRef &Bin, uint64_t N = UINT64_MAX) {
  85. if (!checkLimit(Bin.binary_size()))
  86. return;
  87. Bin.writeAsBinary(OS, N);
  88. }
  89. void writeZeros(uint64_t Num) {
  90. if (checkLimit(Num))
  91. OS.write_zeros(Num);
  92. }
  93. void write(const char *Ptr, size_t Size) {
  94. if (checkLimit(Size))
  95. OS.write(Ptr, Size);
  96. }
  97. void write(unsigned char C) {
  98. if (checkLimit(1))
  99. OS.write(C);
  100. }
  101. unsigned writeULEB128(uint64_t Val) {
  102. if (!checkLimit(sizeof(uint64_t)))
  103. return 0;
  104. return encodeULEB128(Val, OS);
  105. }
  106. template <typename T> void write(T Val, support::endianness E) {
  107. if (checkLimit(sizeof(T)))
  108. support::endian::write<T>(OS, Val, E);
  109. }
  110. void updateDataAt(uint64_t Pos, void *Data, size_t Size) {
  111. assert(Pos >= InitialOffset && Pos + Size <= getOffset());
  112. memcpy(&Buf[Pos - InitialOffset], Data, Size);
  113. }
  114. };
  115. // Used to keep track of section and symbol names, so that in the YAML file
  116. // sections and symbols can be referenced by name instead of by index.
  117. class NameToIdxMap {
  118. StringMap<unsigned> Map;
  119. public:
  120. /// \Returns false if name is already present in the map.
  121. bool addName(StringRef Name, unsigned Ndx) {
  122. return Map.insert({Name, Ndx}).second;
  123. }
  124. /// \Returns false if name is not present in the map.
  125. bool lookup(StringRef Name, unsigned &Idx) const {
  126. auto I = Map.find(Name);
  127. if (I == Map.end())
  128. return false;
  129. Idx = I->getValue();
  130. return true;
  131. }
  132. /// Asserts if name is not present in the map.
  133. unsigned get(StringRef Name) const {
  134. unsigned Idx;
  135. if (lookup(Name, Idx))
  136. return Idx;
  137. assert(false && "Expected section not found in index");
  138. return 0;
  139. }
  140. unsigned size() const { return Map.size(); }
  141. };
  142. namespace {
  143. struct Fragment {
  144. uint64_t Offset;
  145. uint64_t Size;
  146. uint32_t Type;
  147. uint64_t AddrAlign;
  148. };
  149. } // namespace
  150. /// "Single point of truth" for the ELF file construction.
  151. /// TODO: This class still has a ways to go before it is truly a "single
  152. /// point of truth".
  153. template <class ELFT> class ELFState {
  154. LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
  155. enum class SymtabType { Static, Dynamic };
  156. /// The future symbol table string section.
  157. StringTableBuilder DotStrtab{StringTableBuilder::ELF};
  158. /// The future section header string table section, if a unique string table
  159. /// is needed. Don't reference this variable direectly: use the
  160. /// ShStrtabStrings member instead.
  161. StringTableBuilder DotShStrtab{StringTableBuilder::ELF};
  162. /// The future dynamic symbol string section.
  163. StringTableBuilder DotDynstr{StringTableBuilder::ELF};
  164. /// The name of the section header string table section. If it is .strtab or
  165. /// .dynstr, the section header strings will be written to the same string
  166. /// table as the static/dynamic symbols respectively. Otherwise a dedicated
  167. /// section will be created with that name.
  168. StringRef SectionHeaderStringTableName = ".shstrtab";
  169. StringTableBuilder *ShStrtabStrings = &DotShStrtab;
  170. NameToIdxMap SN2I;
  171. NameToIdxMap SymN2I;
  172. NameToIdxMap DynSymN2I;
  173. ELFYAML::Object &Doc;
  174. StringSet<> ExcludedSectionHeaders;
  175. uint64_t LocationCounter = 0;
  176. bool HasError = false;
  177. yaml::ErrorHandler ErrHandler;
  178. void reportError(const Twine &Msg);
  179. void reportError(Error Err);
  180. std::vector<Elf_Sym> toELFSymbols(ArrayRef<ELFYAML::Symbol> Symbols,
  181. const StringTableBuilder &Strtab);
  182. unsigned toSectionIndex(StringRef S, StringRef LocSec, StringRef LocSym = "");
  183. unsigned toSymbolIndex(StringRef S, StringRef LocSec, bool IsDynamic);
  184. void buildSectionIndex();
  185. void buildSymbolIndexes();
  186. void initProgramHeaders(std::vector<Elf_Phdr> &PHeaders);
  187. bool initImplicitHeader(ContiguousBlobAccumulator &CBA, Elf_Shdr &Header,
  188. StringRef SecName, ELFYAML::Section *YAMLSec);
  189. void initSectionHeaders(std::vector<Elf_Shdr> &SHeaders,
  190. ContiguousBlobAccumulator &CBA);
  191. void initSymtabSectionHeader(Elf_Shdr &SHeader, SymtabType STType,
  192. ContiguousBlobAccumulator &CBA,
  193. ELFYAML::Section *YAMLSec);
  194. void initStrtabSectionHeader(Elf_Shdr &SHeader, StringRef Name,
  195. StringTableBuilder &STB,
  196. ContiguousBlobAccumulator &CBA,
  197. ELFYAML::Section *YAMLSec);
  198. void initDWARFSectionHeader(Elf_Shdr &SHeader, StringRef Name,
  199. ContiguousBlobAccumulator &CBA,
  200. ELFYAML::Section *YAMLSec);
  201. void setProgramHeaderLayout(std::vector<Elf_Phdr> &PHeaders,
  202. std::vector<Elf_Shdr> &SHeaders);
  203. std::vector<Fragment>
  204. getPhdrFragments(const ELFYAML::ProgramHeader &Phdr,
  205. ArrayRef<typename ELFT::Shdr> SHeaders);
  206. void finalizeStrings();
  207. void writeELFHeader(raw_ostream &OS);
  208. void writeSectionContent(Elf_Shdr &SHeader,
  209. const ELFYAML::NoBitsSection &Section,
  210. ContiguousBlobAccumulator &CBA);
  211. void writeSectionContent(Elf_Shdr &SHeader,
  212. const ELFYAML::RawContentSection &Section,
  213. ContiguousBlobAccumulator &CBA);
  214. void writeSectionContent(Elf_Shdr &SHeader,
  215. const ELFYAML::RelocationSection &Section,
  216. ContiguousBlobAccumulator &CBA);
  217. void writeSectionContent(Elf_Shdr &SHeader,
  218. const ELFYAML::RelrSection &Section,
  219. ContiguousBlobAccumulator &CBA);
  220. void writeSectionContent(Elf_Shdr &SHeader,
  221. const ELFYAML::GroupSection &Group,
  222. ContiguousBlobAccumulator &CBA);
  223. void writeSectionContent(Elf_Shdr &SHeader,
  224. const ELFYAML::SymtabShndxSection &Shndx,
  225. ContiguousBlobAccumulator &CBA);
  226. void writeSectionContent(Elf_Shdr &SHeader,
  227. const ELFYAML::SymverSection &Section,
  228. ContiguousBlobAccumulator &CBA);
  229. void writeSectionContent(Elf_Shdr &SHeader,
  230. const ELFYAML::VerneedSection &Section,
  231. ContiguousBlobAccumulator &CBA);
  232. void writeSectionContent(Elf_Shdr &SHeader,
  233. const ELFYAML::VerdefSection &Section,
  234. ContiguousBlobAccumulator &CBA);
  235. void writeSectionContent(Elf_Shdr &SHeader,
  236. const ELFYAML::ARMIndexTableSection &Section,
  237. ContiguousBlobAccumulator &CBA);
  238. void writeSectionContent(Elf_Shdr &SHeader,
  239. const ELFYAML::MipsABIFlags &Section,
  240. ContiguousBlobAccumulator &CBA);
  241. void writeSectionContent(Elf_Shdr &SHeader,
  242. const ELFYAML::DynamicSection &Section,
  243. ContiguousBlobAccumulator &CBA);
  244. void writeSectionContent(Elf_Shdr &SHeader,
  245. const ELFYAML::StackSizesSection &Section,
  246. ContiguousBlobAccumulator &CBA);
  247. void writeSectionContent(Elf_Shdr &SHeader,
  248. const ELFYAML::BBAddrMapSection &Section,
  249. ContiguousBlobAccumulator &CBA);
  250. void writeSectionContent(Elf_Shdr &SHeader,
  251. const ELFYAML::HashSection &Section,
  252. ContiguousBlobAccumulator &CBA);
  253. void writeSectionContent(Elf_Shdr &SHeader,
  254. const ELFYAML::AddrsigSection &Section,
  255. ContiguousBlobAccumulator &CBA);
  256. void writeSectionContent(Elf_Shdr &SHeader,
  257. const ELFYAML::NoteSection &Section,
  258. ContiguousBlobAccumulator &CBA);
  259. void writeSectionContent(Elf_Shdr &SHeader,
  260. const ELFYAML::GnuHashSection &Section,
  261. ContiguousBlobAccumulator &CBA);
  262. void writeSectionContent(Elf_Shdr &SHeader,
  263. const ELFYAML::LinkerOptionsSection &Section,
  264. ContiguousBlobAccumulator &CBA);
  265. void writeSectionContent(Elf_Shdr &SHeader,
  266. const ELFYAML::DependentLibrariesSection &Section,
  267. ContiguousBlobAccumulator &CBA);
  268. void writeSectionContent(Elf_Shdr &SHeader,
  269. const ELFYAML::CallGraphProfileSection &Section,
  270. ContiguousBlobAccumulator &CBA);
  271. void writeFill(ELFYAML::Fill &Fill, ContiguousBlobAccumulator &CBA);
  272. ELFState(ELFYAML::Object &D, yaml::ErrorHandler EH);
  273. void assignSectionAddress(Elf_Shdr &SHeader, ELFYAML::Section *YAMLSec);
  274. DenseMap<StringRef, size_t> buildSectionHeaderReorderMap();
  275. BumpPtrAllocator StringAlloc;
  276. uint64_t alignToOffset(ContiguousBlobAccumulator &CBA, uint64_t Align,
  277. llvm::Optional<llvm::yaml::Hex64> Offset);
  278. uint64_t getSectionNameOffset(StringRef Name);
  279. public:
  280. static bool writeELF(raw_ostream &OS, ELFYAML::Object &Doc,
  281. yaml::ErrorHandler EH, uint64_t MaxSize);
  282. };
  283. } // end anonymous namespace
  284. template <class T> static size_t arrayDataSize(ArrayRef<T> A) {
  285. return A.size() * sizeof(T);
  286. }
  287. template <class T> static void writeArrayData(raw_ostream &OS, ArrayRef<T> A) {
  288. OS.write((const char *)A.data(), arrayDataSize(A));
  289. }
  290. template <class T> static void zero(T &Obj) { memset(&Obj, 0, sizeof(Obj)); }
  291. template <class ELFT>
  292. ELFState<ELFT>::ELFState(ELFYAML::Object &D, yaml::ErrorHandler EH)
  293. : Doc(D), ErrHandler(EH) {
  294. // The input may explicitly request to store the section header table strings
  295. // in the same string table as dynamic or static symbol names. Set the
  296. // ShStrtabStrings member accordingly.
  297. if (Doc.Header.SectionHeaderStringTable) {
  298. SectionHeaderStringTableName = *Doc.Header.SectionHeaderStringTable;
  299. if (*Doc.Header.SectionHeaderStringTable == ".strtab")
  300. ShStrtabStrings = &DotStrtab;
  301. else if (*Doc.Header.SectionHeaderStringTable == ".dynstr")
  302. ShStrtabStrings = &DotDynstr;
  303. // Otherwise, the unique table will be used.
  304. }
  305. std::vector<ELFYAML::Section *> Sections = Doc.getSections();
  306. // Insert SHT_NULL section implicitly when it is not defined in YAML.
  307. if (Sections.empty() || Sections.front()->Type != ELF::SHT_NULL)
  308. Doc.Chunks.insert(
  309. Doc.Chunks.begin(),
  310. std::make_unique<ELFYAML::Section>(
  311. ELFYAML::Chunk::ChunkKind::RawContent, /*IsImplicit=*/true));
  312. StringSet<> DocSections;
  313. ELFYAML::SectionHeaderTable *SecHdrTable = nullptr;
  314. for (size_t I = 0; I < Doc.Chunks.size(); ++I) {
  315. const std::unique_ptr<ELFYAML::Chunk> &C = Doc.Chunks[I];
  316. // We might have an explicit section header table declaration.
  317. if (auto S = dyn_cast<ELFYAML::SectionHeaderTable>(C.get())) {
  318. if (SecHdrTable)
  319. reportError("multiple section header tables are not allowed");
  320. SecHdrTable = S;
  321. continue;
  322. }
  323. // We add a technical suffix for each unnamed section/fill. It does not
  324. // affect the output, but allows us to map them by name in the code and
  325. // report better error messages.
  326. if (C->Name.empty()) {
  327. std::string NewName = ELFYAML::appendUniqueSuffix(
  328. /*Name=*/"", "index " + Twine(I));
  329. C->Name = StringRef(NewName).copy(StringAlloc);
  330. assert(ELFYAML::dropUniqueSuffix(C->Name).empty());
  331. }
  332. if (!DocSections.insert(C->Name).second)
  333. reportError("repeated section/fill name: '" + C->Name +
  334. "' at YAML section/fill number " + Twine(I));
  335. }
  336. SmallSetVector<StringRef, 8> ImplicitSections;
  337. if (Doc.DynamicSymbols) {
  338. if (SectionHeaderStringTableName == ".dynsym")
  339. reportError("cannot use '.dynsym' as the section header name table when "
  340. "there are dynamic symbols");
  341. ImplicitSections.insert(".dynsym");
  342. ImplicitSections.insert(".dynstr");
  343. }
  344. if (Doc.Symbols) {
  345. if (SectionHeaderStringTableName == ".symtab")
  346. reportError("cannot use '.symtab' as the section header name table when "
  347. "there are symbols");
  348. ImplicitSections.insert(".symtab");
  349. }
  350. if (Doc.DWARF)
  351. for (StringRef DebugSecName : Doc.DWARF->getNonEmptySectionNames()) {
  352. std::string SecName = ("." + DebugSecName).str();
  353. // TODO: For .debug_str it should be possible to share the string table,
  354. // in the same manner as the symbol string tables.
  355. if (SectionHeaderStringTableName == SecName)
  356. reportError("cannot use '" + SecName +
  357. "' as the section header name table when it is needed for "
  358. "DWARF output");
  359. ImplicitSections.insert(StringRef(SecName).copy(StringAlloc));
  360. }
  361. // TODO: Only create the .strtab here if any symbols have been requested.
  362. ImplicitSections.insert(".strtab");
  363. if (!SecHdrTable || !SecHdrTable->NoHeaders.getValueOr(false))
  364. ImplicitSections.insert(SectionHeaderStringTableName);
  365. // Insert placeholders for implicit sections that are not
  366. // defined explicitly in YAML.
  367. for (StringRef SecName : ImplicitSections) {
  368. if (DocSections.count(SecName))
  369. continue;
  370. std::unique_ptr<ELFYAML::Section> Sec = std::make_unique<ELFYAML::Section>(
  371. ELFYAML::Chunk::ChunkKind::RawContent, true /*IsImplicit*/);
  372. Sec->Name = SecName;
  373. if (SecName == SectionHeaderStringTableName)
  374. Sec->Type = ELF::SHT_STRTAB;
  375. else if (SecName == ".dynsym")
  376. Sec->Type = ELF::SHT_DYNSYM;
  377. else if (SecName == ".symtab")
  378. Sec->Type = ELF::SHT_SYMTAB;
  379. else
  380. Sec->Type = ELF::SHT_STRTAB;
  381. // When the section header table is explicitly defined at the end of the
  382. // sections list, it is reasonable to assume that the user wants to reorder
  383. // section headers, but still wants to place the section header table after
  384. // all sections, like it normally happens. In this case we want to insert
  385. // other implicit sections right before the section header table.
  386. if (Doc.Chunks.back().get() == SecHdrTable)
  387. Doc.Chunks.insert(Doc.Chunks.end() - 1, std::move(Sec));
  388. else
  389. Doc.Chunks.push_back(std::move(Sec));
  390. }
  391. // Insert the section header table implicitly at the end, when it is not
  392. // explicitly defined.
  393. if (!SecHdrTable)
  394. Doc.Chunks.push_back(
  395. std::make_unique<ELFYAML::SectionHeaderTable>(/*IsImplicit=*/true));
  396. }
  397. template <class ELFT>
  398. void ELFState<ELFT>::writeELFHeader(raw_ostream &OS) {
  399. using namespace llvm::ELF;
  400. Elf_Ehdr Header;
  401. zero(Header);
  402. Header.e_ident[EI_MAG0] = 0x7f;
  403. Header.e_ident[EI_MAG1] = 'E';
  404. Header.e_ident[EI_MAG2] = 'L';
  405. Header.e_ident[EI_MAG3] = 'F';
  406. Header.e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;
  407. Header.e_ident[EI_DATA] = Doc.Header.Data;
  408. Header.e_ident[EI_VERSION] = EV_CURRENT;
  409. Header.e_ident[EI_OSABI] = Doc.Header.OSABI;
  410. Header.e_ident[EI_ABIVERSION] = Doc.Header.ABIVersion;
  411. Header.e_type = Doc.Header.Type;
  412. if (Doc.Header.Machine)
  413. Header.e_machine = *Doc.Header.Machine;
  414. else
  415. Header.e_machine = EM_NONE;
  416. Header.e_version = EV_CURRENT;
  417. Header.e_entry = Doc.Header.Entry;
  418. Header.e_flags = Doc.Header.Flags;
  419. Header.e_ehsize = sizeof(Elf_Ehdr);
  420. if (Doc.Header.EPhOff)
  421. Header.e_phoff = *Doc.Header.EPhOff;
  422. else if (!Doc.ProgramHeaders.empty())
  423. Header.e_phoff = sizeof(Header);
  424. else
  425. Header.e_phoff = 0;
  426. if (Doc.Header.EPhEntSize)
  427. Header.e_phentsize = *Doc.Header.EPhEntSize;
  428. else if (!Doc.ProgramHeaders.empty())
  429. Header.e_phentsize = sizeof(Elf_Phdr);
  430. else
  431. Header.e_phentsize = 0;
  432. if (Doc.Header.EPhNum)
  433. Header.e_phnum = *Doc.Header.EPhNum;
  434. else if (!Doc.ProgramHeaders.empty())
  435. Header.e_phnum = Doc.ProgramHeaders.size();
  436. else
  437. Header.e_phnum = 0;
  438. Header.e_shentsize = Doc.Header.EShEntSize ? (uint16_t)*Doc.Header.EShEntSize
  439. : sizeof(Elf_Shdr);
  440. const ELFYAML::SectionHeaderTable &SectionHeaders =
  441. Doc.getSectionHeaderTable();
  442. if (Doc.Header.EShOff)
  443. Header.e_shoff = *Doc.Header.EShOff;
  444. else if (SectionHeaders.Offset)
  445. Header.e_shoff = *SectionHeaders.Offset;
  446. else
  447. Header.e_shoff = 0;
  448. if (Doc.Header.EShNum)
  449. Header.e_shnum = *Doc.Header.EShNum;
  450. else
  451. Header.e_shnum = SectionHeaders.getNumHeaders(Doc.getSections().size());
  452. if (Doc.Header.EShStrNdx)
  453. Header.e_shstrndx = *Doc.Header.EShStrNdx;
  454. else if (SectionHeaders.Offset &&
  455. !ExcludedSectionHeaders.count(SectionHeaderStringTableName))
  456. Header.e_shstrndx = SN2I.get(SectionHeaderStringTableName);
  457. else
  458. Header.e_shstrndx = 0;
  459. OS.write((const char *)&Header, sizeof(Header));
  460. }
  461. template <class ELFT>
  462. void ELFState<ELFT>::initProgramHeaders(std::vector<Elf_Phdr> &PHeaders) {
  463. DenseMap<StringRef, ELFYAML::Fill *> NameToFill;
  464. DenseMap<StringRef, size_t> NameToIndex;
  465. for (size_t I = 0, E = Doc.Chunks.size(); I != E; ++I) {
  466. if (auto S = dyn_cast<ELFYAML::Fill>(Doc.Chunks[I].get()))
  467. NameToFill[S->Name] = S;
  468. NameToIndex[Doc.Chunks[I]->Name] = I + 1;
  469. }
  470. std::vector<ELFYAML::Section *> Sections = Doc.getSections();
  471. for (size_t I = 0, E = Doc.ProgramHeaders.size(); I != E; ++I) {
  472. ELFYAML::ProgramHeader &YamlPhdr = Doc.ProgramHeaders[I];
  473. Elf_Phdr Phdr;
  474. zero(Phdr);
  475. Phdr.p_type = YamlPhdr.Type;
  476. Phdr.p_flags = YamlPhdr.Flags;
  477. Phdr.p_vaddr = YamlPhdr.VAddr;
  478. Phdr.p_paddr = YamlPhdr.PAddr;
  479. PHeaders.push_back(Phdr);
  480. if (!YamlPhdr.FirstSec && !YamlPhdr.LastSec)
  481. continue;
  482. // Get the index of the section, or 0 in the case when the section doesn't exist.
  483. size_t First = NameToIndex[*YamlPhdr.FirstSec];
  484. if (!First)
  485. reportError("unknown section or fill referenced: '" + *YamlPhdr.FirstSec +
  486. "' by the 'FirstSec' key of the program header with index " +
  487. Twine(I));
  488. size_t Last = NameToIndex[*YamlPhdr.LastSec];
  489. if (!Last)
  490. reportError("unknown section or fill referenced: '" + *YamlPhdr.LastSec +
  491. "' by the 'LastSec' key of the program header with index " +
  492. Twine(I));
  493. if (!First || !Last)
  494. continue;
  495. if (First > Last)
  496. reportError("program header with index " + Twine(I) +
  497. ": the section index of " + *YamlPhdr.FirstSec +
  498. " is greater than the index of " + *YamlPhdr.LastSec);
  499. for (size_t I = First; I <= Last; ++I)
  500. YamlPhdr.Chunks.push_back(Doc.Chunks[I - 1].get());
  501. }
  502. }
  503. template <class ELFT>
  504. unsigned ELFState<ELFT>::toSectionIndex(StringRef S, StringRef LocSec,
  505. StringRef LocSym) {
  506. assert(LocSec.empty() || LocSym.empty());
  507. unsigned Index;
  508. if (!SN2I.lookup(S, Index) && !to_integer(S, Index)) {
  509. if (!LocSym.empty())
  510. reportError("unknown section referenced: '" + S + "' by YAML symbol '" +
  511. LocSym + "'");
  512. else
  513. reportError("unknown section referenced: '" + S + "' by YAML section '" +
  514. LocSec + "'");
  515. return 0;
  516. }
  517. const ELFYAML::SectionHeaderTable &SectionHeaders =
  518. Doc.getSectionHeaderTable();
  519. if (SectionHeaders.IsImplicit ||
  520. (SectionHeaders.NoHeaders && !SectionHeaders.NoHeaders.getValue()) ||
  521. SectionHeaders.isDefault())
  522. return Index;
  523. assert(!SectionHeaders.NoHeaders.getValueOr(false) ||
  524. !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 Optional<yaml::BinaryRef> &Content,
  627. const 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.getValueOr(false))
  676. continue;
  677. if (!S->Offset)
  678. S->Offset = alignToOffset(CBA, sizeof(typename ELFT::uint),
  679. /*Offset=*/None);
  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.getValueOr(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.getValueOr(yaml::Hex64(0));
  838. Symbol.st_other = Sym.Other ? *Sym.Other : 0;
  839. Symbol.st_size = Sym.Size.getValueOr(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 =
  886. alignToOffset(CBA, SHeader.sh_addralign, RawSec ? RawSec->Offset : None);
  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 : None);
  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 : None);
  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 the address of the function.
  1209. CBA.write<uintX_t>(E.Address, ELFT::TargetEndianness);
  1210. // Write number of BBEntries (number of basic blocks in the function). This
  1211. // is overridden by the 'NumBlocks' YAML field when specified.
  1212. uint64_t NumBlocks =
  1213. E.NumBlocks.getValueOr(E.BBEntries ? E.BBEntries->size() : 0);
  1214. SHeader.sh_size += sizeof(uintX_t) + CBA.writeULEB128(NumBlocks);
  1215. // Write all BBEntries.
  1216. if (!E.BBEntries)
  1217. continue;
  1218. for (const ELFYAML::BBAddrMapEntry::BBEntry &BBE : *E.BBEntries)
  1219. SHeader.sh_size += CBA.writeULEB128(BBE.AddressOffset) +
  1220. CBA.writeULEB128(BBE.Size) +
  1221. CBA.writeULEB128(BBE.Metadata);
  1222. }
  1223. }
  1224. template <class ELFT>
  1225. void ELFState<ELFT>::writeSectionContent(
  1226. Elf_Shdr &SHeader, const ELFYAML::LinkerOptionsSection &Section,
  1227. ContiguousBlobAccumulator &CBA) {
  1228. if (!Section.Options)
  1229. return;
  1230. for (const ELFYAML::LinkerOption &LO : *Section.Options) {
  1231. CBA.write(LO.Key.data(), LO.Key.size());
  1232. CBA.write('\0');
  1233. CBA.write(LO.Value.data(), LO.Value.size());
  1234. CBA.write('\0');
  1235. SHeader.sh_size += (LO.Key.size() + LO.Value.size() + 2);
  1236. }
  1237. }
  1238. template <class ELFT>
  1239. void ELFState<ELFT>::writeSectionContent(
  1240. Elf_Shdr &SHeader, const ELFYAML::DependentLibrariesSection &Section,
  1241. ContiguousBlobAccumulator &CBA) {
  1242. if (!Section.Libs)
  1243. return;
  1244. for (StringRef Lib : *Section.Libs) {
  1245. CBA.write(Lib.data(), Lib.size());
  1246. CBA.write('\0');
  1247. SHeader.sh_size += Lib.size() + 1;
  1248. }
  1249. }
  1250. template <class ELFT>
  1251. uint64_t
  1252. ELFState<ELFT>::alignToOffset(ContiguousBlobAccumulator &CBA, uint64_t Align,
  1253. llvm::Optional<llvm::yaml::Hex64> Offset) {
  1254. uint64_t CurrentOffset = CBA.getOffset();
  1255. uint64_t AlignedOffset;
  1256. if (Offset) {
  1257. if ((uint64_t)*Offset < CurrentOffset) {
  1258. reportError("the 'Offset' value (0x" +
  1259. Twine::utohexstr((uint64_t)*Offset) + ") goes backward");
  1260. return CurrentOffset;
  1261. }
  1262. // We ignore an alignment when an explicit offset has been requested.
  1263. AlignedOffset = *Offset;
  1264. } else {
  1265. AlignedOffset = alignTo(CurrentOffset, std::max(Align, (uint64_t)1));
  1266. }
  1267. CBA.writeZeros(AlignedOffset - CurrentOffset);
  1268. return AlignedOffset;
  1269. }
  1270. template <class ELFT>
  1271. void ELFState<ELFT>::writeSectionContent(
  1272. Elf_Shdr &SHeader, const ELFYAML::CallGraphProfileSection &Section,
  1273. ContiguousBlobAccumulator &CBA) {
  1274. if (!Section.Entries)
  1275. return;
  1276. for (const ELFYAML::CallGraphEntryWeight &E : *Section.Entries) {
  1277. CBA.write<uint64_t>(E.Weight, ELFT::TargetEndianness);
  1278. SHeader.sh_size += sizeof(object::Elf_CGProfile_Impl<ELFT>);
  1279. }
  1280. }
  1281. template <class ELFT>
  1282. void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
  1283. const ELFYAML::HashSection &Section,
  1284. ContiguousBlobAccumulator &CBA) {
  1285. if (!Section.Bucket)
  1286. return;
  1287. CBA.write<uint32_t>(
  1288. Section.NBucket.getValueOr(llvm::yaml::Hex64(Section.Bucket->size())),
  1289. ELFT::TargetEndianness);
  1290. CBA.write<uint32_t>(
  1291. Section.NChain.getValueOr(llvm::yaml::Hex64(Section.Chain->size())),
  1292. ELFT::TargetEndianness);
  1293. for (uint32_t Val : *Section.Bucket)
  1294. CBA.write<uint32_t>(Val, ELFT::TargetEndianness);
  1295. for (uint32_t Val : *Section.Chain)
  1296. CBA.write<uint32_t>(Val, ELFT::TargetEndianness);
  1297. SHeader.sh_size = (2 + Section.Bucket->size() + Section.Chain->size()) * 4;
  1298. }
  1299. template <class ELFT>
  1300. void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
  1301. const ELFYAML::VerdefSection &Section,
  1302. ContiguousBlobAccumulator &CBA) {
  1303. if (Section.Info)
  1304. SHeader.sh_info = *Section.Info;
  1305. else if (Section.Entries)
  1306. SHeader.sh_info = Section.Entries->size();
  1307. if (!Section.Entries)
  1308. return;
  1309. uint64_t AuxCnt = 0;
  1310. for (size_t I = 0; I < Section.Entries->size(); ++I) {
  1311. const ELFYAML::VerdefEntry &E = (*Section.Entries)[I];
  1312. Elf_Verdef VerDef;
  1313. VerDef.vd_version = E.Version.getValueOr(1);
  1314. VerDef.vd_flags = E.Flags.getValueOr(0);
  1315. VerDef.vd_ndx = E.VersionNdx.getValueOr(0);
  1316. VerDef.vd_hash = E.Hash.getValueOr(0);
  1317. VerDef.vd_aux = sizeof(Elf_Verdef);
  1318. VerDef.vd_cnt = E.VerNames.size();
  1319. if (I == Section.Entries->size() - 1)
  1320. VerDef.vd_next = 0;
  1321. else
  1322. VerDef.vd_next =
  1323. sizeof(Elf_Verdef) + E.VerNames.size() * sizeof(Elf_Verdaux);
  1324. CBA.write((const char *)&VerDef, sizeof(Elf_Verdef));
  1325. for (size_t J = 0; J < E.VerNames.size(); ++J, ++AuxCnt) {
  1326. Elf_Verdaux VernAux;
  1327. VernAux.vda_name = DotDynstr.getOffset(E.VerNames[J]);
  1328. if (J == E.VerNames.size() - 1)
  1329. VernAux.vda_next = 0;
  1330. else
  1331. VernAux.vda_next = sizeof(Elf_Verdaux);
  1332. CBA.write((const char *)&VernAux, sizeof(Elf_Verdaux));
  1333. }
  1334. }
  1335. SHeader.sh_size = Section.Entries->size() * sizeof(Elf_Verdef) +
  1336. AuxCnt * sizeof(Elf_Verdaux);
  1337. }
  1338. template <class ELFT>
  1339. void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
  1340. const ELFYAML::VerneedSection &Section,
  1341. ContiguousBlobAccumulator &CBA) {
  1342. if (Section.Info)
  1343. SHeader.sh_info = *Section.Info;
  1344. else if (Section.VerneedV)
  1345. SHeader.sh_info = Section.VerneedV->size();
  1346. if (!Section.VerneedV)
  1347. return;
  1348. uint64_t AuxCnt = 0;
  1349. for (size_t I = 0; I < Section.VerneedV->size(); ++I) {
  1350. const ELFYAML::VerneedEntry &VE = (*Section.VerneedV)[I];
  1351. Elf_Verneed VerNeed;
  1352. VerNeed.vn_version = VE.Version;
  1353. VerNeed.vn_file = DotDynstr.getOffset(VE.File);
  1354. if (I == Section.VerneedV->size() - 1)
  1355. VerNeed.vn_next = 0;
  1356. else
  1357. VerNeed.vn_next =
  1358. sizeof(Elf_Verneed) + VE.AuxV.size() * sizeof(Elf_Vernaux);
  1359. VerNeed.vn_cnt = VE.AuxV.size();
  1360. VerNeed.vn_aux = sizeof(Elf_Verneed);
  1361. CBA.write((const char *)&VerNeed, sizeof(Elf_Verneed));
  1362. for (size_t J = 0; J < VE.AuxV.size(); ++J, ++AuxCnt) {
  1363. const ELFYAML::VernauxEntry &VAuxE = VE.AuxV[J];
  1364. Elf_Vernaux VernAux;
  1365. VernAux.vna_hash = VAuxE.Hash;
  1366. VernAux.vna_flags = VAuxE.Flags;
  1367. VernAux.vna_other = VAuxE.Other;
  1368. VernAux.vna_name = DotDynstr.getOffset(VAuxE.Name);
  1369. if (J == VE.AuxV.size() - 1)
  1370. VernAux.vna_next = 0;
  1371. else
  1372. VernAux.vna_next = sizeof(Elf_Vernaux);
  1373. CBA.write((const char *)&VernAux, sizeof(Elf_Vernaux));
  1374. }
  1375. }
  1376. SHeader.sh_size = Section.VerneedV->size() * sizeof(Elf_Verneed) +
  1377. AuxCnt * sizeof(Elf_Vernaux);
  1378. }
  1379. template <class ELFT>
  1380. void ELFState<ELFT>::writeSectionContent(
  1381. Elf_Shdr &SHeader, const ELFYAML::ARMIndexTableSection &Section,
  1382. ContiguousBlobAccumulator &CBA) {
  1383. if (!Section.Entries)
  1384. return;
  1385. for (const ELFYAML::ARMIndexTableEntry &E : *Section.Entries) {
  1386. CBA.write<uint32_t>(E.Offset, ELFT::TargetEndianness);
  1387. CBA.write<uint32_t>(E.Value, ELFT::TargetEndianness);
  1388. }
  1389. SHeader.sh_size = Section.Entries->size() * 8;
  1390. }
  1391. template <class ELFT>
  1392. void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
  1393. const ELFYAML::MipsABIFlags &Section,
  1394. ContiguousBlobAccumulator &CBA) {
  1395. assert(Section.Type == llvm::ELF::SHT_MIPS_ABIFLAGS &&
  1396. "Section type is not SHT_MIPS_ABIFLAGS");
  1397. object::Elf_Mips_ABIFlags<ELFT> Flags;
  1398. zero(Flags);
  1399. SHeader.sh_size = SHeader.sh_entsize;
  1400. Flags.version = Section.Version;
  1401. Flags.isa_level = Section.ISALevel;
  1402. Flags.isa_rev = Section.ISARevision;
  1403. Flags.gpr_size = Section.GPRSize;
  1404. Flags.cpr1_size = Section.CPR1Size;
  1405. Flags.cpr2_size = Section.CPR2Size;
  1406. Flags.fp_abi = Section.FpABI;
  1407. Flags.isa_ext = Section.ISAExtension;
  1408. Flags.ases = Section.ASEs;
  1409. Flags.flags1 = Section.Flags1;
  1410. Flags.flags2 = Section.Flags2;
  1411. CBA.write((const char *)&Flags, sizeof(Flags));
  1412. }
  1413. template <class ELFT>
  1414. void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
  1415. const ELFYAML::DynamicSection &Section,
  1416. ContiguousBlobAccumulator &CBA) {
  1417. assert(Section.Type == llvm::ELF::SHT_DYNAMIC &&
  1418. "Section type is not SHT_DYNAMIC");
  1419. if (!Section.Entries)
  1420. return;
  1421. for (const ELFYAML::DynamicEntry &DE : *Section.Entries) {
  1422. CBA.write<uintX_t>(DE.Tag, ELFT::TargetEndianness);
  1423. CBA.write<uintX_t>(DE.Val, ELFT::TargetEndianness);
  1424. }
  1425. SHeader.sh_size = 2 * sizeof(uintX_t) * Section.Entries->size();
  1426. }
  1427. template <class ELFT>
  1428. void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
  1429. const ELFYAML::AddrsigSection &Section,
  1430. ContiguousBlobAccumulator &CBA) {
  1431. if (!Section.Symbols)
  1432. return;
  1433. for (StringRef Sym : *Section.Symbols)
  1434. SHeader.sh_size +=
  1435. CBA.writeULEB128(toSymbolIndex(Sym, Section.Name, /*IsDynamic=*/false));
  1436. }
  1437. template <class ELFT>
  1438. void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
  1439. const ELFYAML::NoteSection &Section,
  1440. ContiguousBlobAccumulator &CBA) {
  1441. if (!Section.Notes)
  1442. return;
  1443. uint64_t Offset = CBA.tell();
  1444. for (const ELFYAML::NoteEntry &NE : *Section.Notes) {
  1445. // Write name size.
  1446. if (NE.Name.empty())
  1447. CBA.write<uint32_t>(0, ELFT::TargetEndianness);
  1448. else
  1449. CBA.write<uint32_t>(NE.Name.size() + 1, ELFT::TargetEndianness);
  1450. // Write description size.
  1451. if (NE.Desc.binary_size() == 0)
  1452. CBA.write<uint32_t>(0, ELFT::TargetEndianness);
  1453. else
  1454. CBA.write<uint32_t>(NE.Desc.binary_size(), ELFT::TargetEndianness);
  1455. // Write type.
  1456. CBA.write<uint32_t>(NE.Type, ELFT::TargetEndianness);
  1457. // Write name, null terminator and padding.
  1458. if (!NE.Name.empty()) {
  1459. CBA.write(NE.Name.data(), NE.Name.size());
  1460. CBA.write('\0');
  1461. CBA.padToAlignment(4);
  1462. }
  1463. // Write description and padding.
  1464. if (NE.Desc.binary_size() != 0) {
  1465. CBA.writeAsBinary(NE.Desc);
  1466. CBA.padToAlignment(4);
  1467. }
  1468. }
  1469. SHeader.sh_size = CBA.tell() - Offset;
  1470. }
  1471. template <class ELFT>
  1472. void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
  1473. const ELFYAML::GnuHashSection &Section,
  1474. ContiguousBlobAccumulator &CBA) {
  1475. if (!Section.HashBuckets)
  1476. return;
  1477. if (!Section.Header)
  1478. return;
  1479. // We write the header first, starting with the hash buckets count. Normally
  1480. // it is the number of entries in HashBuckets, but the "NBuckets" property can
  1481. // be used to override this field, which is useful for producing broken
  1482. // objects.
  1483. if (Section.Header->NBuckets)
  1484. CBA.write<uint32_t>(*Section.Header->NBuckets, ELFT::TargetEndianness);
  1485. else
  1486. CBA.write<uint32_t>(Section.HashBuckets->size(), ELFT::TargetEndianness);
  1487. // Write the index of the first symbol in the dynamic symbol table accessible
  1488. // via the hash table.
  1489. CBA.write<uint32_t>(Section.Header->SymNdx, ELFT::TargetEndianness);
  1490. // Write the number of words in the Bloom filter. As above, the "MaskWords"
  1491. // property can be used to set this field to any value.
  1492. if (Section.Header->MaskWords)
  1493. CBA.write<uint32_t>(*Section.Header->MaskWords, ELFT::TargetEndianness);
  1494. else
  1495. CBA.write<uint32_t>(Section.BloomFilter->size(), ELFT::TargetEndianness);
  1496. // Write the shift constant used by the Bloom filter.
  1497. CBA.write<uint32_t>(Section.Header->Shift2, ELFT::TargetEndianness);
  1498. // We've finished writing the header. Now write the Bloom filter.
  1499. for (llvm::yaml::Hex64 Val : *Section.BloomFilter)
  1500. CBA.write<uintX_t>(Val, ELFT::TargetEndianness);
  1501. // Write an array of hash buckets.
  1502. for (llvm::yaml::Hex32 Val : *Section.HashBuckets)
  1503. CBA.write<uint32_t>(Val, ELFT::TargetEndianness);
  1504. // Write an array of hash values.
  1505. for (llvm::yaml::Hex32 Val : *Section.HashValues)
  1506. CBA.write<uint32_t>(Val, ELFT::TargetEndianness);
  1507. SHeader.sh_size = 16 /*Header size*/ +
  1508. Section.BloomFilter->size() * sizeof(typename ELFT::uint) +
  1509. Section.HashBuckets->size() * 4 +
  1510. Section.HashValues->size() * 4;
  1511. }
  1512. template <class ELFT>
  1513. void ELFState<ELFT>::writeFill(ELFYAML::Fill &Fill,
  1514. ContiguousBlobAccumulator &CBA) {
  1515. size_t PatternSize = Fill.Pattern ? Fill.Pattern->binary_size() : 0;
  1516. if (!PatternSize) {
  1517. CBA.writeZeros(Fill.Size);
  1518. return;
  1519. }
  1520. // Fill the content with the specified pattern.
  1521. uint64_t Written = 0;
  1522. for (; Written + PatternSize <= Fill.Size; Written += PatternSize)
  1523. CBA.writeAsBinary(*Fill.Pattern);
  1524. CBA.writeAsBinary(*Fill.Pattern, Fill.Size - Written);
  1525. }
  1526. template <class ELFT>
  1527. DenseMap<StringRef, size_t> ELFState<ELFT>::buildSectionHeaderReorderMap() {
  1528. const ELFYAML::SectionHeaderTable &SectionHeaders =
  1529. Doc.getSectionHeaderTable();
  1530. if (SectionHeaders.IsImplicit || SectionHeaders.NoHeaders ||
  1531. SectionHeaders.isDefault())
  1532. return DenseMap<StringRef, size_t>();
  1533. DenseMap<StringRef, size_t> Ret;
  1534. size_t SecNdx = 0;
  1535. StringSet<> Seen;
  1536. auto AddSection = [&](const ELFYAML::SectionHeader &Hdr) {
  1537. if (!Ret.try_emplace(Hdr.Name, ++SecNdx).second)
  1538. reportError("repeated section name: '" + Hdr.Name +
  1539. "' in the section header description");
  1540. Seen.insert(Hdr.Name);
  1541. };
  1542. if (SectionHeaders.Sections)
  1543. for (const ELFYAML::SectionHeader &Hdr : *SectionHeaders.Sections)
  1544. AddSection(Hdr);
  1545. if (SectionHeaders.Excluded)
  1546. for (const ELFYAML::SectionHeader &Hdr : *SectionHeaders.Excluded)
  1547. AddSection(Hdr);
  1548. for (const ELFYAML::Section *S : Doc.getSections()) {
  1549. // Ignore special first SHT_NULL section.
  1550. if (S == Doc.getSections().front())
  1551. continue;
  1552. if (!Seen.count(S->Name))
  1553. reportError("section '" + S->Name +
  1554. "' should be present in the 'Sections' or 'Excluded' lists");
  1555. Seen.erase(S->Name);
  1556. }
  1557. for (const auto &It : Seen)
  1558. reportError("section header contains undefined section '" + It.getKey() +
  1559. "'");
  1560. return Ret;
  1561. }
  1562. template <class ELFT> void ELFState<ELFT>::buildSectionIndex() {
  1563. // A YAML description can have an explicit section header declaration that
  1564. // allows to change the order of section headers.
  1565. DenseMap<StringRef, size_t> ReorderMap = buildSectionHeaderReorderMap();
  1566. if (HasError)
  1567. return;
  1568. // Build excluded section headers map.
  1569. std::vector<ELFYAML::Section *> Sections = Doc.getSections();
  1570. const ELFYAML::SectionHeaderTable &SectionHeaders =
  1571. Doc.getSectionHeaderTable();
  1572. if (SectionHeaders.Excluded)
  1573. for (const ELFYAML::SectionHeader &Hdr : *SectionHeaders.Excluded)
  1574. if (!ExcludedSectionHeaders.insert(Hdr.Name).second)
  1575. llvm_unreachable("buildSectionIndex() failed");
  1576. if (SectionHeaders.NoHeaders.getValueOr(false))
  1577. for (const ELFYAML::Section *S : Sections)
  1578. if (!ExcludedSectionHeaders.insert(S->Name).second)
  1579. llvm_unreachable("buildSectionIndex() failed");
  1580. size_t SecNdx = -1;
  1581. for (const ELFYAML::Section *S : Sections) {
  1582. ++SecNdx;
  1583. size_t Index = ReorderMap.empty() ? SecNdx : ReorderMap.lookup(S->Name);
  1584. if (!SN2I.addName(S->Name, Index))
  1585. llvm_unreachable("buildSectionIndex() failed");
  1586. if (!ExcludedSectionHeaders.count(S->Name))
  1587. ShStrtabStrings->add(ELFYAML::dropUniqueSuffix(S->Name));
  1588. }
  1589. }
  1590. template <class ELFT> void ELFState<ELFT>::buildSymbolIndexes() {
  1591. auto Build = [this](ArrayRef<ELFYAML::Symbol> V, NameToIdxMap &Map) {
  1592. for (size_t I = 0, S = V.size(); I < S; ++I) {
  1593. const ELFYAML::Symbol &Sym = V[I];
  1594. if (!Sym.Name.empty() && !Map.addName(Sym.Name, I + 1))
  1595. reportError("repeated symbol name: '" + Sym.Name + "'");
  1596. }
  1597. };
  1598. if (Doc.Symbols)
  1599. Build(*Doc.Symbols, SymN2I);
  1600. if (Doc.DynamicSymbols)
  1601. Build(*Doc.DynamicSymbols, DynSymN2I);
  1602. }
  1603. template <class ELFT> void ELFState<ELFT>::finalizeStrings() {
  1604. // Add the regular symbol names to .strtab section.
  1605. if (Doc.Symbols)
  1606. for (const ELFYAML::Symbol &Sym : *Doc.Symbols)
  1607. DotStrtab.add(ELFYAML::dropUniqueSuffix(Sym.Name));
  1608. DotStrtab.finalize();
  1609. // Add the dynamic symbol names to .dynstr section.
  1610. if (Doc.DynamicSymbols)
  1611. for (const ELFYAML::Symbol &Sym : *Doc.DynamicSymbols)
  1612. DotDynstr.add(ELFYAML::dropUniqueSuffix(Sym.Name));
  1613. // SHT_GNU_verdef and SHT_GNU_verneed sections might also
  1614. // add strings to .dynstr section.
  1615. for (const ELFYAML::Chunk *Sec : Doc.getSections()) {
  1616. if (auto VerNeed = dyn_cast<ELFYAML::VerneedSection>(Sec)) {
  1617. if (VerNeed->VerneedV) {
  1618. for (const ELFYAML::VerneedEntry &VE : *VerNeed->VerneedV) {
  1619. DotDynstr.add(VE.File);
  1620. for (const ELFYAML::VernauxEntry &Aux : VE.AuxV)
  1621. DotDynstr.add(Aux.Name);
  1622. }
  1623. }
  1624. } else if (auto VerDef = dyn_cast<ELFYAML::VerdefSection>(Sec)) {
  1625. if (VerDef->Entries)
  1626. for (const ELFYAML::VerdefEntry &E : *VerDef->Entries)
  1627. for (StringRef Name : E.VerNames)
  1628. DotDynstr.add(Name);
  1629. }
  1630. }
  1631. DotDynstr.finalize();
  1632. // Don't finalize the section header string table a second time if it has
  1633. // already been finalized due to being one of the symbol string tables.
  1634. if (ShStrtabStrings != &DotStrtab && ShStrtabStrings != &DotDynstr)
  1635. ShStrtabStrings->finalize();
  1636. }
  1637. template <class ELFT>
  1638. bool ELFState<ELFT>::writeELF(raw_ostream &OS, ELFYAML::Object &Doc,
  1639. yaml::ErrorHandler EH, uint64_t MaxSize) {
  1640. ELFState<ELFT> State(Doc, EH);
  1641. if (State.HasError)
  1642. return false;
  1643. // Build the section index, which adds sections to the section header string
  1644. // table first, so that we can finalize the section header string table.
  1645. State.buildSectionIndex();
  1646. State.buildSymbolIndexes();
  1647. // Finalize section header string table and the .strtab and .dynstr sections.
  1648. // We do this early because we want to finalize the string table builders
  1649. // before writing the content of the sections that might want to use them.
  1650. State.finalizeStrings();
  1651. if (State.HasError)
  1652. return false;
  1653. std::vector<Elf_Phdr> PHeaders;
  1654. State.initProgramHeaders(PHeaders);
  1655. // XXX: This offset is tightly coupled with the order that we write
  1656. // things to `OS`.
  1657. const size_t SectionContentBeginOffset =
  1658. sizeof(Elf_Ehdr) + sizeof(Elf_Phdr) * Doc.ProgramHeaders.size();
  1659. // It is quite easy to accidentally create output with yaml2obj that is larger
  1660. // than intended, for example, due to an issue in the YAML description.
  1661. // We limit the maximum allowed output size, but also provide a command line
  1662. // option to change this limitation.
  1663. ContiguousBlobAccumulator CBA(SectionContentBeginOffset, MaxSize);
  1664. std::vector<Elf_Shdr> SHeaders;
  1665. State.initSectionHeaders(SHeaders, CBA);
  1666. // Now we can decide segment offsets.
  1667. State.setProgramHeaderLayout(PHeaders, SHeaders);
  1668. bool ReachedLimit = CBA.getOffset() > MaxSize;
  1669. if (Error E = CBA.takeLimitError()) {
  1670. // We report a custom error message instead below.
  1671. consumeError(std::move(E));
  1672. ReachedLimit = true;
  1673. }
  1674. if (ReachedLimit)
  1675. State.reportError(
  1676. "the desired output size is greater than permitted. Use the "
  1677. "--max-size option to change the limit");
  1678. if (State.HasError)
  1679. return false;
  1680. State.writeELFHeader(OS);
  1681. writeArrayData(OS, makeArrayRef(PHeaders));
  1682. const ELFYAML::SectionHeaderTable &SHT = Doc.getSectionHeaderTable();
  1683. if (!SHT.NoHeaders.getValueOr(false))
  1684. CBA.updateDataAt(*SHT.Offset, SHeaders.data(),
  1685. SHT.getNumHeaders(SHeaders.size()) * sizeof(Elf_Shdr));
  1686. CBA.writeBlobToStream(OS);
  1687. return true;
  1688. }
  1689. namespace llvm {
  1690. namespace yaml {
  1691. bool yaml2elf(llvm::ELFYAML::Object &Doc, raw_ostream &Out, ErrorHandler EH,
  1692. uint64_t MaxSize) {
  1693. bool IsLE = Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB);
  1694. bool Is64Bit = Doc.Header.Class == ELFYAML::ELF_ELFCLASS(ELF::ELFCLASS64);
  1695. if (Is64Bit) {
  1696. if (IsLE)
  1697. return ELFState<object::ELF64LE>::writeELF(Out, Doc, EH, MaxSize);
  1698. return ELFState<object::ELF64BE>::writeELF(Out, Doc, EH, MaxSize);
  1699. }
  1700. if (IsLE)
  1701. return ELFState<object::ELF32LE>::writeELF(Out, Doc, EH, MaxSize);
  1702. return ELFState<object::ELF32BE>::writeELF(Out, Doc, EH, MaxSize);
  1703. }
  1704. } // namespace yaml
  1705. } // namespace llvm