blob: beb2ea26752308b1ec85b5324ed54c907b5a022b [file] [log] [blame]
Sean Silvaf99309c2013-06-10 23:44:15 +00001//===- yaml2elf - Convert YAML to a ELF object file -----------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Sean Silvaf99309c2013-06-10 23:44:15 +00006//
7//===----------------------------------------------------------------------===//
8///
9/// \file
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000010/// The ELF component of yaml2obj.
Sean Silvaf99309c2013-06-10 23:44:15 +000011///
12//===----------------------------------------------------------------------===//
13
14#include "yaml2obj.h"
Will Dietz0b48c732013-10-12 21:29:16 +000015#include "llvm/ADT/ArrayRef.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000016#include "llvm/BinaryFormat/ELF.h"
Rafael Espindola97de4742014-07-03 02:01:39 +000017#include "llvm/MC/StringTableBuilder.h"
Michael J. Spencer126973b2013-08-08 22:27:13 +000018#include "llvm/Object/ELFObjectFile.h"
Rafael Espindolaebd91932016-03-01 19:15:06 +000019#include "llvm/ObjectYAML/ELFYAML.h"
Sean Silvaf99309c2013-06-10 23:44:15 +000020#include "llvm/Support/MemoryBuffer.h"
Jonas Devlieghere2cd41eb2018-04-21 21:11:59 +000021#include "llvm/Support/WithColor.h"
Sean Silvaf99309c2013-06-10 23:44:15 +000022#include "llvm/Support/YAMLTraits.h"
23#include "llvm/Support/raw_ostream.h"
24
25using namespace llvm;
26
Sean Silva46dffff2013-06-13 22:20:01 +000027// This class is used to build up a contiguous binary blob while keeping
28// track of an offset in the output (which notionally begins at
29// `InitialOffset`).
Sean Silva2a74f702013-06-15 00:31:46 +000030namespace {
Sean Silva46dffff2013-06-13 22:20:01 +000031class ContiguousBlobAccumulator {
32 const uint64_t InitialOffset;
Sean Silvabd3bc692013-06-20 19:11:41 +000033 SmallVector<char, 128> Buf;
Sean Silva46dffff2013-06-13 22:20:01 +000034 raw_svector_ostream OS;
35
Sean Silvad93323f2013-06-22 00:47:43 +000036 /// \returns The new offset.
37 uint64_t padToAlignment(unsigned Align) {
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +000038 if (Align == 0)
39 Align = 1;
Sean Silvad93323f2013-06-22 00:47:43 +000040 uint64_t CurrentOffset = InitialOffset + OS.tell();
Rui Ueyamada00f2f2016-01-14 21:06:47 +000041 uint64_t AlignedOffset = alignTo(CurrentOffset, Align);
Sean Silvad93323f2013-06-22 00:47:43 +000042 for (; CurrentOffset != AlignedOffset; ++CurrentOffset)
43 OS.write('\0');
44 return AlignedOffset; // == CurrentOffset;
45 }
46
Sean Silva46dffff2013-06-13 22:20:01 +000047public:
Sean Silvabd3bc692013-06-20 19:11:41 +000048 ContiguousBlobAccumulator(uint64_t InitialOffset_)
49 : InitialOffset(InitialOffset_), Buf(), OS(Buf) {}
Sean Silvad93323f2013-06-22 00:47:43 +000050 template <class Integer>
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +000051 raw_ostream &getOSAndAlignedOffset(Integer &Offset, unsigned Align) {
Sean Silvad93323f2013-06-22 00:47:43 +000052 Offset = padToAlignment(Align);
53 return OS;
54 }
Sean Silva46dffff2013-06-13 22:20:01 +000055 void writeBlobToStream(raw_ostream &Out) { Out << OS.str(); }
56};
Sean Silva2a74f702013-06-15 00:31:46 +000057} // end anonymous namespace
Sean Silva46dffff2013-06-13 22:20:01 +000058
Simon Atanasyan35babf92014-04-06 09:02:55 +000059// Used to keep track of section and symbol names, so that in the YAML file
60// sections and symbols can be referenced by name instead of by index.
Sean Silva2a74f702013-06-15 00:31:46 +000061namespace {
Simon Atanasyan35babf92014-04-06 09:02:55 +000062class NameToIdxMap {
Sean Silvaa6423eb2013-06-15 00:25:26 +000063 StringMap<int> Map;
64public:
65 /// \returns true if name is already present in the map.
Simon Atanasyan35babf92014-04-06 09:02:55 +000066 bool addName(StringRef Name, unsigned i) {
David Blaikie5106ce72014-11-19 05:49:42 +000067 return !Map.insert(std::make_pair(Name, (int)i)).second;
Sean Silvaa6423eb2013-06-15 00:25:26 +000068 }
69 /// \returns true if name is not present in the map
Simon Atanasyan35babf92014-04-06 09:02:55 +000070 bool lookup(StringRef Name, unsigned &Idx) const {
71 StringMap<int>::const_iterator I = Map.find(Name);
Sean Silvaa6423eb2013-06-15 00:25:26 +000072 if (I == Map.end())
73 return true;
74 Idx = I->getValue();
75 return false;
76 }
Dave Lee17307d92017-11-09 14:53:43 +000077 /// asserts if name is not present in the map
78 unsigned get(StringRef Name) const {
79 unsigned Idx = 0;
80 auto missing = lookup(Name, Idx);
81 (void)missing;
82 assert(!missing && "Expected section not found in index");
83 return Idx;
84 }
85 unsigned size() const { return Map.size(); }
Sean Silvaa6423eb2013-06-15 00:25:26 +000086};
Sean Silva2a74f702013-06-15 00:31:46 +000087} // end anonymous namespace
Sean Silvaa6423eb2013-06-15 00:25:26 +000088
Sean Silva38205932013-06-13 22:19:48 +000089template <class T>
Will Dietz0b48c732013-10-12 21:29:16 +000090static size_t arrayDataSize(ArrayRef<T> A) {
91 return A.size() * sizeof(T);
Sean Silva38205932013-06-13 22:19:48 +000092}
93
94template <class T>
Will Dietz0b48c732013-10-12 21:29:16 +000095static void writeArrayData(raw_ostream &OS, ArrayRef<T> A) {
96 OS.write((const char *)A.data(), arrayDataSize(A));
Sean Silva38205932013-06-13 22:19:48 +000097}
98
99template <class T>
100static void zero(T &Obj) {
101 memset(&Obj, 0, sizeof(Obj));
102}
103
Sean Silva08a75ae2013-06-20 19:11:44 +0000104namespace {
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000105/// "Single point of truth" for the ELF file construction.
Sean Silva08a75ae2013-06-20 19:11:44 +0000106/// TODO: This class still has a ways to go before it is truly a "single
107/// point of truth".
108template <class ELFT>
109class ELFState {
Rui Ueyama478d6352018-01-12 02:28:31 +0000110 typedef typename ELFT::Ehdr Elf_Ehdr;
111 typedef typename ELFT::Phdr Elf_Phdr;
112 typedef typename ELFT::Shdr Elf_Shdr;
113 typedef typename ELFT::Sym Elf_Sym;
114 typedef typename ELFT::Rel Elf_Rel;
115 typedef typename ELFT::Rela Elf_Rela;
Jake Ehrlich0f440d82018-06-28 21:07:34 +0000116 typedef typename ELFT::Relr Elf_Relr;
Paul Semel1dbbfba2018-07-23 18:49:04 +0000117 typedef typename ELFT::Dyn Elf_Dyn;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000118
Dave Lee67b49662017-11-16 18:10:15 +0000119 enum class SymtabType { Static, Dynamic };
120
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000121 /// The future ".strtab" section.
Rafael Espindola21956e42015-10-23 21:48:05 +0000122 StringTableBuilder DotStrtab{StringTableBuilder::ELF};
Sean Silva08a75ae2013-06-20 19:11:44 +0000123
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000124 /// The future ".shstrtab" section.
Rafael Espindola21956e42015-10-23 21:48:05 +0000125 StringTableBuilder DotShStrtab{StringTableBuilder::ELF};
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000126
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000127 /// The future ".dynstr" section.
Dave Lee67b49662017-11-16 18:10:15 +0000128 StringTableBuilder DotDynstr{StringTableBuilder::ELF};
129
Simon Atanasyan35babf92014-04-06 09:02:55 +0000130 NameToIdxMap SN2I;
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000131 NameToIdxMap SymN2I;
Simon Atanasyan220c54a2014-04-02 16:34:40 +0000132 const ELFYAML::Object &Doc;
Sean Silvac1c290b2013-06-20 20:59:34 +0000133
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000134 bool buildSectionIndex();
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000135 bool buildSymbolIndex(std::size_t &StartIndex,
136 const std::vector<ELFYAML::Symbol> &Symbols);
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000137 void initELFHeader(Elf_Ehdr &Header);
Petr Hosekeb04da32017-07-19 20:38:46 +0000138 void initProgramHeaders(std::vector<Elf_Phdr> &PHeaders);
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000139 bool initSectionHeaders(std::vector<Elf_Shdr> &SHeaders,
140 ContiguousBlobAccumulator &CBA);
Dave Lee67b49662017-11-16 18:10:15 +0000141 void initSymtabSectionHeader(Elf_Shdr &SHeader, SymtabType STType,
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000142 ContiguousBlobAccumulator &CBA);
143 void initStrtabSectionHeader(Elf_Shdr &SHeader, StringRef Name,
144 StringTableBuilder &STB,
145 ContiguousBlobAccumulator &CBA);
Petr Hosekeb04da32017-07-19 20:38:46 +0000146 void setProgramHeaderLayout(std::vector<Elf_Phdr> &PHeaders,
147 std::vector<Elf_Shdr> &SHeaders);
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000148 void addSymbols(const std::vector<ELFYAML::Symbol> &Symbols,
Dave Lee67b49662017-11-16 18:10:15 +0000149 std::vector<Elf_Sym> &Syms, unsigned SymbolBinding,
150 const StringTableBuilder &Strtab);
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000151 void writeSectionContent(Elf_Shdr &SHeader,
152 const ELFYAML::RawContentSection &Section,
153 ContiguousBlobAccumulator &CBA);
154 bool writeSectionContent(Elf_Shdr &SHeader,
155 const ELFYAML::RelocationSection &Section,
156 ContiguousBlobAccumulator &CBA);
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000157 bool writeSectionContent(Elf_Shdr &SHeader, const ELFYAML::Group &Group,
158 ContiguousBlobAccumulator &CBA);
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000159 bool writeSectionContent(Elf_Shdr &SHeader,
George Rimar0621b792019-02-19 14:53:48 +0000160 const ELFYAML::VerneedSection &Section,
161 ContiguousBlobAccumulator &CBA);
162 bool writeSectionContent(Elf_Shdr &SHeader,
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000163 const ELFYAML::MipsABIFlags &Section,
164 ContiguousBlobAccumulator &CBA);
George Rimar0e7ed912019-02-09 11:34:28 +0000165 void writeSectionContent(Elf_Shdr &SHeader,
166 const ELFYAML::DynamicSection &Section,
167 ContiguousBlobAccumulator &CBA);
Dave Lee67b49662017-11-16 18:10:15 +0000168 bool hasDynamicSymbols() const;
169 SmallVector<const char *, 5> implicitSectionNames() const;
Sean Silva08a75ae2013-06-20 19:11:44 +0000170
Simon Atanasyan220c54a2014-04-02 16:34:40 +0000171 // - SHT_NULL entry (placed first, i.e. 0'th entry)
Dave Lee67b49662017-11-16 18:10:15 +0000172 // - symbol table (.symtab) (defaults to after last yaml section)
173 // - string table (.strtab) (defaults to after .symtab)
174 // - section header string table (.shstrtab) (defaults to after .strtab)
175 // - dynamic symbol table (.dynsym) (defaults to after .shstrtab)
176 // - dynamic string table (.dynstr) (defaults to after .dynsym)
Dave Lee17307d92017-11-09 14:53:43 +0000177 unsigned getDotSymTabSecNo() const { return SN2I.get(".symtab"); }
178 unsigned getDotStrTabSecNo() const { return SN2I.get(".strtab"); }
179 unsigned getDotShStrTabSecNo() const { return SN2I.get(".shstrtab"); }
Dave Lee67b49662017-11-16 18:10:15 +0000180 unsigned getDotDynSymSecNo() const { return SN2I.get(".dynsym"); }
181 unsigned getDotDynStrSecNo() const { return SN2I.get(".dynstr"); }
Dave Lee17307d92017-11-09 14:53:43 +0000182 unsigned getSectionCount() const { return SN2I.size() + 1; }
Simon Atanasyan220c54a2014-04-02 16:34:40 +0000183
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000184 ELFState(const ELFYAML::Object &D) : Doc(D) {}
Simon Atanasyan220c54a2014-04-02 16:34:40 +0000185
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000186public:
187 static int writeELF(raw_ostream &OS, const ELFYAML::Object &Doc);
George Rimar0621b792019-02-19 14:53:48 +0000188
189private:
190 void finalizeStrings();
Sean Silva08a75ae2013-06-20 19:11:44 +0000191};
192} // end anonymous namespace
193
Sean Silva37e817c2013-06-21 00:33:01 +0000194template <class ELFT>
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000195void ELFState<ELFT>::initELFHeader(Elf_Ehdr &Header) {
196 using namespace llvm::ELF;
197 zero(Header);
198 Header.e_ident[EI_MAG0] = 0x7f;
199 Header.e_ident[EI_MAG1] = 'E';
200 Header.e_ident[EI_MAG2] = 'L';
201 Header.e_ident[EI_MAG3] = 'F';
202 Header.e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;
203 bool IsLittleEndian = ELFT::TargetEndianness == support::little;
204 Header.e_ident[EI_DATA] = IsLittleEndian ? ELFDATA2LSB : ELFDATA2MSB;
205 Header.e_ident[EI_VERSION] = EV_CURRENT;
206 Header.e_ident[EI_OSABI] = Doc.Header.OSABI;
George Rimar6367d7a2018-12-20 10:43:49 +0000207 Header.e_ident[EI_ABIVERSION] = Doc.Header.ABIVersion;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000208 Header.e_type = Doc.Header.Type;
209 Header.e_machine = Doc.Header.Machine;
210 Header.e_version = EV_CURRENT;
211 Header.e_entry = Doc.Header.Entry;
Petr Hosekeb04da32017-07-19 20:38:46 +0000212 Header.e_phoff = sizeof(Header);
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000213 Header.e_flags = Doc.Header.Flags;
214 Header.e_ehsize = sizeof(Elf_Ehdr);
Petr Hosekeb04da32017-07-19 20:38:46 +0000215 Header.e_phentsize = sizeof(Elf_Phdr);
216 Header.e_phnum = Doc.ProgramHeaders.size();
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000217 Header.e_shentsize = sizeof(Elf_Shdr);
Petr Hosekeb04da32017-07-19 20:38:46 +0000218 // Immediately following the ELF header and program headers.
219 Header.e_shoff =
220 sizeof(Header) + sizeof(Elf_Phdr) * Doc.ProgramHeaders.size();
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000221 Header.e_shnum = getSectionCount();
222 Header.e_shstrndx = getDotShStrTabSecNo();
223}
224
225template <class ELFT>
Petr Hosekeb04da32017-07-19 20:38:46 +0000226void ELFState<ELFT>::initProgramHeaders(std::vector<Elf_Phdr> &PHeaders) {
227 for (const auto &YamlPhdr : Doc.ProgramHeaders) {
228 Elf_Phdr Phdr;
229 Phdr.p_type = YamlPhdr.Type;
230 Phdr.p_flags = YamlPhdr.Flags;
231 Phdr.p_vaddr = YamlPhdr.VAddr;
232 Phdr.p_paddr = YamlPhdr.PAddr;
233 PHeaders.push_back(Phdr);
234 }
235}
236
Xing GUO98228352018-12-04 14:27:51 +0000237static bool convertSectionIndex(NameToIdxMap &SN2I, StringRef SecName,
238 StringRef IndexSrc, unsigned &IndexDest) {
239 if (SN2I.lookup(IndexSrc, IndexDest) && !to_integer(IndexSrc, IndexDest)) {
240 WithColor::error() << "Unknown section referenced: '" << IndexSrc
241 << "' at YAML section '" << SecName << "'.\n";
242 return false;
243 }
244 return true;
245}
246
Petr Hosekeb04da32017-07-19 20:38:46 +0000247template <class ELFT>
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000248bool ELFState<ELFT>::initSectionHeaders(std::vector<Elf_Shdr> &SHeaders,
249 ContiguousBlobAccumulator &CBA) {
250 // Ensure SHN_UNDEF entry is present. An all-zero section header is a
251 // valid SHN_UNDEF entry since SHT_NULL == 0.
252 Elf_Shdr SHeader;
253 zero(SHeader);
254 SHeaders.push_back(SHeader);
255
256 for (const auto &Sec : Doc.Sections) {
257 zero(SHeader);
Hans Wennborg59f0cba2014-04-30 19:38:09 +0000258 SHeader.sh_name = DotShStrtab.getOffset(Sec->Name);
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000259 SHeader.sh_type = Sec->Type;
260 SHeader.sh_flags = Sec->Flags;
261 SHeader.sh_addr = Sec->Address;
262 SHeader.sh_addralign = Sec->AddressAlign;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000263
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000264 if (!Sec->Link.empty()) {
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000265 unsigned Index;
Xing GUO98228352018-12-04 14:27:51 +0000266 if (!convertSectionIndex(SN2I, Sec->Name, Sec->Link, Index))
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000267 return false;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000268 SHeader.sh_link = Index;
269 }
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000270
271 if (auto S = dyn_cast<ELFYAML::RawContentSection>(Sec.get()))
272 writeSectionContent(SHeader, *S, CBA);
273 else if (auto S = dyn_cast<ELFYAML::RelocationSection>(Sec.get())) {
274 if (S->Link.empty())
275 // For relocation section set link to .symtab by default.
276 SHeader.sh_link = getDotSymTabSecNo();
277
278 unsigned Index;
George Rimarb87ea732019-02-12 09:08:59 +0000279 if (!convertSectionIndex(SN2I, S->Name, S->RelocatableSec, Index))
George Rimar7f2df7d2018-08-16 12:23:22 +0000280 return false;
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000281 SHeader.sh_info = Index;
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000282 if (!writeSectionContent(SHeader, *S, CBA))
283 return false;
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000284 } else if (auto S = dyn_cast<ELFYAML::Group>(Sec.get())) {
285 unsigned SymIdx;
George Rimarb87ea732019-02-12 09:08:59 +0000286 if (SymN2I.lookup(S->Signature, SymIdx) &&
287 !to_integer(S->Signature, SymIdx)) {
288 WithColor::error() << "Unknown symbol referenced: '" << S->Signature
Jonas Devlieghere2cd41eb2018-04-21 21:11:59 +0000289 << "' at YAML section '" << S->Name << "'.\n";
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000290 return false;
291 }
292 SHeader.sh_info = SymIdx;
293 if (!writeSectionContent(SHeader, *S, CBA))
294 return false;
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000295 } else if (auto S = dyn_cast<ELFYAML::MipsABIFlags>(Sec.get())) {
296 if (!writeSectionContent(SHeader, *S, CBA))
297 return false;
Simon Atanasyan5db02762015-07-03 23:00:54 +0000298 } else if (auto S = dyn_cast<ELFYAML::NoBitsSection>(Sec.get())) {
299 SHeader.sh_entsize = 0;
300 SHeader.sh_size = S->Size;
301 // SHT_NOBITS section does not have content
302 // so just to setup the section offset.
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000303 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
George Rimar0e7ed912019-02-09 11:34:28 +0000304 } else if (auto S = dyn_cast<ELFYAML::DynamicSection>(Sec.get())) {
305 writeSectionContent(SHeader, *S, CBA);
George Rimar0621b792019-02-19 14:53:48 +0000306 } else if (auto S = dyn_cast<ELFYAML::VerneedSection>(Sec.get())) {
307 writeSectionContent(SHeader, *S, CBA);
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000308 } else
309 llvm_unreachable("Unknown section type");
310
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000311 SHeaders.push_back(SHeader);
312 }
313 return true;
314}
315
316template <class ELFT>
317void ELFState<ELFT>::initSymtabSectionHeader(Elf_Shdr &SHeader,
Dave Lee67b49662017-11-16 18:10:15 +0000318 SymtabType STType,
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000319 ContiguousBlobAccumulator &CBA) {
320 zero(SHeader);
Dave Lee67b49662017-11-16 18:10:15 +0000321 bool IsStatic = STType == SymtabType::Static;
322 SHeader.sh_name = DotShStrtab.getOffset(IsStatic ? ".symtab" : ".dynsym");
323 SHeader.sh_type = IsStatic ? ELF::SHT_SYMTAB : ELF::SHT_DYNSYM;
324 SHeader.sh_link = IsStatic ? getDotStrTabSecNo() : getDotDynStrSecNo();
325 const auto &Symbols = IsStatic ? Doc.Symbols : Doc.DynamicSymbols;
326 auto &Strtab = IsStatic ? DotStrtab : DotDynstr;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000327 // One greater than symbol table index of the last local symbol.
Dave Lee67b49662017-11-16 18:10:15 +0000328 SHeader.sh_info = Symbols.Local.size() + 1;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000329 SHeader.sh_entsize = sizeof(Elf_Sym);
Simon Atanasyan3a120922015-07-09 18:23:02 +0000330 SHeader.sh_addralign = 8;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000331
George Rimar6947acd2019-02-19 12:15:04 +0000332 // If .dynsym section is explicitly described in the YAML
333 // then we want to use its section address.
334 if (!IsStatic) {
335 // Take section index and ignore the SHT_NULL section.
336 unsigned SecNdx = getDotDynSymSecNo() - 1;
337 if (SecNdx < Doc.Sections.size())
338 SHeader.sh_addr = Doc.Sections[SecNdx]->Address;
339 }
340
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000341 std::vector<Elf_Sym> Syms;
342 {
343 // Ensure STN_UNDEF is present
344 Elf_Sym Sym;
345 zero(Sym);
346 Syms.push_back(Sym);
347 }
Hans Wennborg59f0cba2014-04-30 19:38:09 +0000348
Dave Lee67b49662017-11-16 18:10:15 +0000349 addSymbols(Symbols.Local, Syms, ELF::STB_LOCAL, Strtab);
350 addSymbols(Symbols.Global, Syms, ELF::STB_GLOBAL, Strtab);
351 addSymbols(Symbols.Weak, Syms, ELF::STB_WEAK, Strtab);
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000352
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000353 writeArrayData(
354 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign),
355 makeArrayRef(Syms));
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000356 SHeader.sh_size = arrayDataSize(makeArrayRef(Syms));
357}
358
359template <class ELFT>
360void ELFState<ELFT>::initStrtabSectionHeader(Elf_Shdr &SHeader, StringRef Name,
361 StringTableBuilder &STB,
362 ContiguousBlobAccumulator &CBA) {
363 zero(SHeader);
Hans Wennborg59f0cba2014-04-30 19:38:09 +0000364 SHeader.sh_name = DotShStrtab.getOffset(Name);
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000365 SHeader.sh_type = ELF::SHT_STRTAB;
Rafael Espindola39751af2016-10-04 22:43:25 +0000366 STB.write(CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign));
367 SHeader.sh_size = STB.getSize();
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000368 SHeader.sh_addralign = 1;
George Rimar6947acd2019-02-19 12:15:04 +0000369
370 // If .dynstr section is explicitly described in the YAML
371 // then we want to use its section address.
372 if (Name == ".dynstr") {
373 // Take section index and ignore the SHT_NULL section.
374 unsigned SecNdx = getDotDynStrSecNo() - 1;
375 if (SecNdx < Doc.Sections.size())
376 SHeader.sh_addr = Doc.Sections[SecNdx]->Address;
377 }
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000378}
379
380template <class ELFT>
Petr Hosekeb04da32017-07-19 20:38:46 +0000381void ELFState<ELFT>::setProgramHeaderLayout(std::vector<Elf_Phdr> &PHeaders,
382 std::vector<Elf_Shdr> &SHeaders) {
383 uint32_t PhdrIdx = 0;
384 for (auto &YamlPhdr : Doc.ProgramHeaders) {
385 auto &PHeader = PHeaders[PhdrIdx++];
386
387 if (YamlPhdr.Sections.size())
388 PHeader.p_offset = UINT32_MAX;
389 else
390 PHeader.p_offset = 0;
391
392 // Find the minimum offset for the program header.
393 for (auto SecName : YamlPhdr.Sections) {
394 uint32_t Index = 0;
395 SN2I.lookup(SecName.Section, Index);
396 const auto &SHeader = SHeaders[Index];
397 PHeader.p_offset = std::min(PHeader.p_offset, SHeader.sh_offset);
398 }
399
400 // Find the maximum offset of the end of a section in order to set p_filesz.
401 PHeader.p_filesz = 0;
402 for (auto SecName : YamlPhdr.Sections) {
403 uint32_t Index = 0;
404 SN2I.lookup(SecName.Section, Index);
405 const auto &SHeader = SHeaders[Index];
406 uint64_t EndOfSection;
407 if (SHeader.sh_type == llvm::ELF::SHT_NOBITS)
408 EndOfSection = SHeader.sh_offset;
409 else
410 EndOfSection = SHeader.sh_offset + SHeader.sh_size;
411 uint64_t EndOfSegment = PHeader.p_offset + PHeader.p_filesz;
412 EndOfSegment = std::max(EndOfSegment, EndOfSection);
413 PHeader.p_filesz = EndOfSegment - PHeader.p_offset;
414 }
415
416 // Find the memory size by adding the size of sections at the end of the
417 // segment. These should be empty (size of zero) and NOBITS sections.
418 PHeader.p_memsz = PHeader.p_filesz;
419 for (auto SecName : YamlPhdr.Sections) {
420 uint32_t Index = 0;
421 SN2I.lookup(SecName.Section, Index);
422 const auto &SHeader = SHeaders[Index];
423 if (SHeader.sh_offset == PHeader.p_offset + PHeader.p_filesz)
424 PHeader.p_memsz += SHeader.sh_size;
425 }
426
427 // Set the alignment of the segment to be the same as the maximum alignment
Jake Ehrlich03aeeb092017-11-01 23:14:48 +0000428 // of the sections with the same offset so that by default the segment
Petr Hosekeb04da32017-07-19 20:38:46 +0000429 // has a valid and sensible alignment.
Jake Ehrlich03aeeb092017-11-01 23:14:48 +0000430 if (YamlPhdr.Align) {
431 PHeader.p_align = *YamlPhdr.Align;
432 } else {
433 PHeader.p_align = 1;
434 for (auto SecName : YamlPhdr.Sections) {
435 uint32_t Index = 0;
436 SN2I.lookup(SecName.Section, Index);
437 const auto &SHeader = SHeaders[Index];
438 if (SHeader.sh_offset == PHeader.p_offset)
439 PHeader.p_align = std::max(PHeader.p_align, SHeader.sh_addralign);
440 }
Petr Hosekeb04da32017-07-19 20:38:46 +0000441 }
442 }
443}
444
445template <class ELFT>
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000446void ELFState<ELFT>::addSymbols(const std::vector<ELFYAML::Symbol> &Symbols,
447 std::vector<Elf_Sym> &Syms,
Dave Lee67b49662017-11-16 18:10:15 +0000448 unsigned SymbolBinding,
449 const StringTableBuilder &Strtab) {
Simon Atanasyan048baca2014-03-14 06:53:30 +0000450 for (const auto &Sym : Symbols) {
Sean Silva6b083882013-06-18 23:14:03 +0000451 Elf_Sym Symbol;
452 zero(Symbol);
453 if (!Sym.Name.empty())
Dave Lee67b49662017-11-16 18:10:15 +0000454 Symbol.st_name = Strtab.getOffset(Sym.Name);
Sean Silvaaff51252013-06-21 00:27:50 +0000455 Symbol.setBindingAndType(SymbolBinding, Sym.Type);
Sean Silvac4afa6d2013-06-21 01:11:48 +0000456 if (!Sym.Section.empty()) {
457 unsigned Index;
Simon Atanasyan35babf92014-04-06 09:02:55 +0000458 if (SN2I.lookup(Sym.Section, Index)) {
Jonas Devlieghere2cd41eb2018-04-21 21:11:59 +0000459 WithColor::error() << "Unknown section referenced: '" << Sym.Section
460 << "' by YAML symbol " << Sym.Name << ".\n";
Sean Silvac4afa6d2013-06-21 01:11:48 +0000461 exit(1);
462 }
463 Symbol.st_shndx = Index;
Petr Hosek5c469a32017-09-07 20:44:16 +0000464 } else if (Sym.Index) {
465 Symbol.st_shndx = *Sym.Index;
466 }
467 // else Symbol.st_shndex == SHN_UNDEF (== 0), since it was zero'd earlier.
Sean Silva05001b92013-06-20 20:59:47 +0000468 Symbol.st_value = Sym.Value;
Simon Atanasyan60e1a792014-11-06 22:46:24 +0000469 Symbol.st_other = Sym.Other;
Sean Silva05001b92013-06-20 20:59:47 +0000470 Symbol.st_size = Sym.Size;
Sean Silva6b083882013-06-18 23:14:03 +0000471 Syms.push_back(Symbol);
472 }
Sean Silvaaff51252013-06-21 00:27:50 +0000473}
474
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000475template <class ELFT>
476void
477ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
478 const ELFYAML::RawContentSection &Section,
479 ContiguousBlobAccumulator &CBA) {
Simon Atanasyanb83f3802014-05-16 16:01:00 +0000480 assert(Section.Size >= Section.Content.binary_size() &&
481 "Section size and section content are inconsistent");
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000482 raw_ostream &OS =
483 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
Simon Atanasyanb83f3802014-05-16 16:01:00 +0000484 Section.Content.writeAsBinary(OS);
485 for (auto i = Section.Content.binary_size(); i < Section.Size; ++i)
486 OS.write(0);
George Rimar65a68282018-08-07 08:11:38 +0000487 if (Section.EntSize)
488 SHeader.sh_entsize = *Section.EntSize;
489 else if (Section.Type == llvm::ELF::SHT_RELR)
Jake Ehrlich0f440d82018-06-28 21:07:34 +0000490 SHeader.sh_entsize = sizeof(Elf_Relr);
491 else
492 SHeader.sh_entsize = 0;
Simon Atanasyanb83f3802014-05-16 16:01:00 +0000493 SHeader.sh_size = Section.Size;
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000494}
495
Simon Atanasyan5d19c672015-01-25 13:29:25 +0000496static bool isMips64EL(const ELFYAML::Object &Doc) {
497 return Doc.Header.Machine == ELFYAML::ELF_EM(llvm::ELF::EM_MIPS) &&
498 Doc.Header.Class == ELFYAML::ELF_ELFCLASS(ELF::ELFCLASS64) &&
499 Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB);
500}
501
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000502template <class ELFT>
503bool
504ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
505 const ELFYAML::RelocationSection &Section,
506 ContiguousBlobAccumulator &CBA) {
Simon Atanasyan8eb9d1b2015-05-08 07:05:04 +0000507 assert((Section.Type == llvm::ELF::SHT_REL ||
508 Section.Type == llvm::ELF::SHT_RELA) &&
509 "Section type is not SHT_REL nor SHT_RELA");
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000510
511 bool IsRela = Section.Type == llvm::ELF::SHT_RELA;
512 SHeader.sh_entsize = IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
513 SHeader.sh_size = SHeader.sh_entsize * Section.Relocations.size();
514
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000515 auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000516
517 for (const auto &Rel : Section.Relocations) {
Adhemerval Zanella9f3dbff2015-04-22 15:26:43 +0000518 unsigned SymIdx = 0;
519 // Some special relocation, R_ARM_v4BX for instance, does not have
520 // an external reference. So it ignores the return value of lookup()
521 // here.
Petr Hosek5aa80f12017-08-30 23:13:31 +0000522 if (Rel.Symbol)
523 SymN2I.lookup(*Rel.Symbol, SymIdx);
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000524
525 if (IsRela) {
526 Elf_Rela REntry;
527 zero(REntry);
528 REntry.r_offset = Rel.Offset;
529 REntry.r_addend = Rel.Addend;
Simon Atanasyan5d19c672015-01-25 13:29:25 +0000530 REntry.setSymbolAndType(SymIdx, Rel.Type, isMips64EL(Doc));
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000531 OS.write((const char *)&REntry, sizeof(REntry));
532 } else {
533 Elf_Rel REntry;
534 zero(REntry);
535 REntry.r_offset = Rel.Offset;
Simon Atanasyan5d19c672015-01-25 13:29:25 +0000536 REntry.setSymbolAndType(SymIdx, Rel.Type, isMips64EL(Doc));
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000537 OS.write((const char *)&REntry, sizeof(REntry));
538 }
539 }
540 return true;
541}
542
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000543template <class ELFT>
544bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
545 const ELFYAML::Group &Section,
546 ContiguousBlobAccumulator &CBA) {
Rui Ueyama478d6352018-01-12 02:28:31 +0000547 typedef typename ELFT::Word Elf_Word;
Simon Atanasyan8eb9d1b2015-05-08 07:05:04 +0000548 assert(Section.Type == llvm::ELF::SHT_GROUP &&
549 "Section type is not SHT_GROUP");
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000550
551 SHeader.sh_entsize = sizeof(Elf_Word);
552 SHeader.sh_size = SHeader.sh_entsize * Section.Members.size();
553
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000554 auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000555
556 for (auto member : Section.Members) {
557 Elf_Word SIdx;
558 unsigned int sectionIndex = 0;
559 if (member.sectionNameOrType == "GRP_COMDAT")
560 sectionIndex = llvm::ELF::GRP_COMDAT;
Xing GUO98228352018-12-04 14:27:51 +0000561 else if (!convertSectionIndex(SN2I, Section.Name, member.sectionNameOrType,
562 sectionIndex))
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000563 return false;
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000564 SIdx = sectionIndex;
565 OS.write((const char *)&SIdx, sizeof(SIdx));
566 }
567 return true;
568}
569
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000570template <class ELFT>
571bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
George Rimar0621b792019-02-19 14:53:48 +0000572 const ELFYAML::VerneedSection &Section,
573 ContiguousBlobAccumulator &CBA) {
574 typedef typename ELFT::Verneed Elf_Verneed;
575 typedef typename ELFT::Vernaux Elf_Vernaux;
576
577 auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
578
579 uint64_t AuxCnt = 0;
580 for (size_t I = 0; I < Section.VerneedV.size(); ++I) {
581 const ELFYAML::VerneedEntry &VE = Section.VerneedV[I];
582
583 Elf_Verneed VerNeed;
584 VerNeed.vn_version = VE.Version;
585 VerNeed.vn_file = DotDynstr.getOffset(VE.File);
586 if (I == Section.VerneedV.size() - 1)
587 VerNeed.vn_next = 0;
588 else
589 VerNeed.vn_next =
590 sizeof(Elf_Verneed) + VE.AuxV.size() * sizeof(Elf_Vernaux);
591 VerNeed.vn_cnt = VE.AuxV.size();
592 VerNeed.vn_aux = sizeof(Elf_Verneed);
593 OS.write((const char *)&VerNeed, sizeof(Elf_Verneed));
594
595 for (size_t J = 0; J < VE.AuxV.size(); ++J, ++AuxCnt) {
596 const ELFYAML::VernauxEntry &VAuxE = VE.AuxV[J];
597
598 Elf_Vernaux VernAux;
599 VernAux.vna_hash = VAuxE.Hash;
600 VernAux.vna_flags = VAuxE.Flags;
601 VernAux.vna_other = VAuxE.Other;
602 VernAux.vna_name = DotDynstr.getOffset(VAuxE.Name);
603 if (J == VE.AuxV.size() - 1)
604 VernAux.vna_next = 0;
605 else
606 VernAux.vna_next = sizeof(Elf_Vernaux);
607 OS.write((const char *)&VernAux, sizeof(Elf_Vernaux));
608 }
609 }
610
611 SHeader.sh_size = Section.VerneedV.size() * sizeof(Elf_Verneed) +
612 AuxCnt * sizeof(Elf_Vernaux);
613 SHeader.sh_info = Section.Info;
614
615 return true;
616}
617
618template <class ELFT>
619bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000620 const ELFYAML::MipsABIFlags &Section,
621 ContiguousBlobAccumulator &CBA) {
Simon Atanasyan8eb9d1b2015-05-08 07:05:04 +0000622 assert(Section.Type == llvm::ELF::SHT_MIPS_ABIFLAGS &&
623 "Section type is not SHT_MIPS_ABIFLAGS");
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000624
625 object::Elf_Mips_ABIFlags<ELFT> Flags;
626 zero(Flags);
627 SHeader.sh_entsize = sizeof(Flags);
628 SHeader.sh_size = SHeader.sh_entsize;
629
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000630 auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000631 Flags.version = Section.Version;
632 Flags.isa_level = Section.ISALevel;
633 Flags.isa_rev = Section.ISARevision;
634 Flags.gpr_size = Section.GPRSize;
635 Flags.cpr1_size = Section.CPR1Size;
636 Flags.cpr2_size = Section.CPR2Size;
637 Flags.fp_abi = Section.FpABI;
638 Flags.isa_ext = Section.ISAExtension;
639 Flags.ases = Section.ASEs;
640 Flags.flags1 = Section.Flags1;
641 Flags.flags2 = Section.Flags2;
642 OS.write((const char *)&Flags, sizeof(Flags));
643
644 return true;
645}
646
George Rimar0e7ed912019-02-09 11:34:28 +0000647template <class ELFT>
648void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
649 const ELFYAML::DynamicSection &Section,
650 ContiguousBlobAccumulator &CBA) {
George Rimar5cb31732019-02-10 08:35:38 +0000651 typedef typename ELFT::Addr Elf_Addr;
George Rimar0e7ed912019-02-09 11:34:28 +0000652 assert(Section.Type == llvm::ELF::SHT_DYNAMIC &&
653 "Section type is not SHT_DYNAMIC");
654
George Rimar5cb31732019-02-10 08:35:38 +0000655 SHeader.sh_size = 2 * sizeof(Elf_Addr) * Section.Entries.size();
George Rimar0e7ed912019-02-09 11:34:28 +0000656 if (Section.EntSize)
657 SHeader.sh_entsize = *Section.EntSize;
658 else
659 SHeader.sh_entsize = sizeof(Elf_Dyn);
660
661 auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
662 for (const ELFYAML::DynamicEntry &DE : Section.Entries) {
George Rimar5cb31732019-02-10 08:35:38 +0000663 Elf_Addr Tag = (Elf_Addr)DE.Tag;
664 OS.write((const char *)&Tag, sizeof(Elf_Addr));
665 Elf_Addr Val = (Elf_Addr)DE.Val;
666 OS.write((const char *)&Val, sizeof(Elf_Addr));
George Rimar0e7ed912019-02-09 11:34:28 +0000667 }
668}
669
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000670template <class ELFT> bool ELFState<ELFT>::buildSectionIndex() {
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000671 for (unsigned i = 0, e = Doc.Sections.size(); i != e; ++i) {
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000672 StringRef Name = Doc.Sections[i]->Name;
Dave Lee17307d92017-11-09 14:53:43 +0000673 DotShStrtab.add(Name);
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000674 // "+ 1" to take into account the SHT_NULL entry.
675 if (SN2I.addName(Name, i + 1)) {
Jonas Devlieghere2cd41eb2018-04-21 21:11:59 +0000676 WithColor::error() << "Repeated section name: '" << Name
677 << "' at YAML section number " << i << ".\n";
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000678 return false;
679 }
Sean Silvaaff51252013-06-21 00:27:50 +0000680 }
Dave Lee17307d92017-11-09 14:53:43 +0000681
682 auto SecNo = 1 + Doc.Sections.size();
683 // Add special sections after input sections, if necessary.
Dave Lee67b49662017-11-16 18:10:15 +0000684 for (const auto &Name : implicitSectionNames())
Dave Lee17307d92017-11-09 14:53:43 +0000685 if (!SN2I.addName(Name, SecNo)) {
686 // Account for this section, since it wasn't in the Doc
687 ++SecNo;
688 DotShStrtab.add(Name);
689 }
690
691 DotShStrtab.finalize();
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000692 return true;
Sean Silva6b083882013-06-18 23:14:03 +0000693}
694
Sean Silvaf99309c2013-06-10 23:44:15 +0000695template <class ELFT>
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000696bool
697ELFState<ELFT>::buildSymbolIndex(std::size_t &StartIndex,
698 const std::vector<ELFYAML::Symbol> &Symbols) {
699 for (const auto &Sym : Symbols) {
700 ++StartIndex;
701 if (Sym.Name.empty())
702 continue;
703 if (SymN2I.addName(Sym.Name, StartIndex)) {
Jonas Devlieghere2cd41eb2018-04-21 21:11:59 +0000704 WithColor::error() << "Repeated symbol name: '" << Sym.Name << "'.\n";
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000705 return false;
706 }
707 }
708 return true;
709}
710
George Rimar0621b792019-02-19 14:53:48 +0000711template <class ELFT> void ELFState<ELFT>::finalizeStrings() {
712 auto AddSymbols = [](StringTableBuilder &StrTab,
713 const ELFYAML::LocalGlobalWeakSymbols &Symbols) {
714 for (const auto &Sym : Symbols.Local)
715 StrTab.add(Sym.Name);
716 for (const auto &Sym : Symbols.Global)
717 StrTab.add(Sym.Name);
718 for (const auto &Sym : Symbols.Weak)
719 StrTab.add(Sym.Name);
720 };
721
722 // Add the regular symbol names to .strtab section.
723 AddSymbols(DotStrtab, Doc.Symbols);
724 DotStrtab.finalize();
725
726 if (!hasDynamicSymbols())
727 return;
728
729 // Add the dynamic symbol names to .dynstr section.
730 AddSymbols(DotDynstr, Doc.DynamicSymbols);
731
732 // SHT_GNU_verneed section also adds strings to .dynstr section.
733 for (const std::unique_ptr<ELFYAML::Section> &Sec : Doc.Sections) {
734 auto VerNeed = dyn_cast<ELFYAML::VerneedSection>(Sec.get());
735 if (!VerNeed)
736 continue;
737
738 for (const ELFYAML::VerneedEntry &VE : VerNeed->VerneedV) {
739 DotDynstr.add(VE.File);
740 for (const ELFYAML::VernauxEntry &Aux : VE.AuxV)
741 DotDynstr.add(Aux.Name);
742 }
743 }
744
745 DotDynstr.finalize();
746}
747
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000748template <class ELFT>
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000749int ELFState<ELFT>::writeELF(raw_ostream &OS, const ELFYAML::Object &Doc) {
Simon Atanasyan220c54a2014-04-02 16:34:40 +0000750 ELFState<ELFT> State(Doc);
George Rimar0621b792019-02-19 14:53:48 +0000751
752 // Finalize .strtab and .dynstr sections. We do that early because want to
753 // finalize the string table builders before writing the content of the
754 // sections that might want to use them.
755 State.finalizeStrings();
756
Simon Atanasyan220c54a2014-04-02 16:34:40 +0000757 if (!State.buildSectionIndex())
758 return 1;
759
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000760 std::size_t StartSymIndex = 0;
761 if (!State.buildSymbolIndex(StartSymIndex, Doc.Symbols.Local) ||
762 !State.buildSymbolIndex(StartSymIndex, Doc.Symbols.Global) ||
763 !State.buildSymbolIndex(StartSymIndex, Doc.Symbols.Weak))
764 return 1;
765
Sean Silva38205932013-06-13 22:19:48 +0000766 Elf_Ehdr Header;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000767 State.initELFHeader(Header);
Sean Silvaf99309c2013-06-10 23:44:15 +0000768
Sean Silva38205932013-06-13 22:19:48 +0000769 // TODO: Flesh out section header support.
Petr Hosekeb04da32017-07-19 20:38:46 +0000770
771 std::vector<Elf_Phdr> PHeaders;
772 State.initProgramHeaders(PHeaders);
Sean Silva38205932013-06-13 22:19:48 +0000773
Sean Silva08a75ae2013-06-20 19:11:44 +0000774 // XXX: This offset is tightly coupled with the order that we write
775 // things to `OS`.
Petr Hosekeb04da32017-07-19 20:38:46 +0000776 const size_t SectionContentBeginOffset = Header.e_ehsize +
777 Header.e_phentsize * Header.e_phnum +
778 Header.e_shentsize * Header.e_shnum;
Sean Silva08a75ae2013-06-20 19:11:44 +0000779 ContiguousBlobAccumulator CBA(SectionContentBeginOffset);
Sean Silvac1c290b2013-06-20 20:59:34 +0000780
Sean Silva38205932013-06-13 22:19:48 +0000781 std::vector<Elf_Shdr> SHeaders;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000782 if(!State.initSectionHeaders(SHeaders, CBA))
783 return 1;
Sean Silva38205932013-06-13 22:19:48 +0000784
Dave Lee17307d92017-11-09 14:53:43 +0000785 // Populate SHeaders with implicit sections not present in the Doc
Dave Lee67b49662017-11-16 18:10:15 +0000786 for (const auto &Name : State.implicitSectionNames())
Dave Lee17307d92017-11-09 14:53:43 +0000787 if (State.SN2I.get(Name) >= SHeaders.size())
788 SHeaders.push_back({});
Sean Silva82177572013-06-22 01:38:00 +0000789
Dave Lee17307d92017-11-09 14:53:43 +0000790 // Initialize the implicit sections
791 auto Index = State.SN2I.get(".symtab");
Dave Lee67b49662017-11-16 18:10:15 +0000792 State.initSymtabSectionHeader(SHeaders[Index], SymtabType::Static, CBA);
Dave Lee17307d92017-11-09 14:53:43 +0000793 Index = State.SN2I.get(".strtab");
794 State.initStrtabSectionHeader(SHeaders[Index], ".strtab", State.DotStrtab, CBA);
795 Index = State.SN2I.get(".shstrtab");
796 State.initStrtabSectionHeader(SHeaders[Index], ".shstrtab", State.DotShStrtab, CBA);
Dave Lee67b49662017-11-16 18:10:15 +0000797 if (State.hasDynamicSymbols()) {
798 Index = State.SN2I.get(".dynsym");
799 State.initSymtabSectionHeader(SHeaders[Index], SymtabType::Dynamic, CBA);
800 SHeaders[Index].sh_flags |= ELF::SHF_ALLOC;
801 Index = State.SN2I.get(".dynstr");
802 State.initStrtabSectionHeader(SHeaders[Index], ".dynstr", State.DotDynstr, CBA);
803 SHeaders[Index].sh_flags |= ELF::SHF_ALLOC;
804 }
Sean Silvaf99309c2013-06-10 23:44:15 +0000805
Petr Hosekeb04da32017-07-19 20:38:46 +0000806 // Now we can decide segment offsets
807 State.setProgramHeaderLayout(PHeaders, SHeaders);
808
Sean Silvaf99309c2013-06-10 23:44:15 +0000809 OS.write((const char *)&Header, sizeof(Header));
Petr Hosekeb04da32017-07-19 20:38:46 +0000810 writeArrayData(OS, makeArrayRef(PHeaders));
Will Dietz0b48c732013-10-12 21:29:16 +0000811 writeArrayData(OS, makeArrayRef(SHeaders));
Sean Silva46dffff2013-06-13 22:20:01 +0000812 CBA.writeBlobToStream(OS);
Sean Silva415d93f2013-06-17 20:14:59 +0000813 return 0;
Sean Silvaf99309c2013-06-10 23:44:15 +0000814}
815
Dave Lee67b49662017-11-16 18:10:15 +0000816template <class ELFT> bool ELFState<ELFT>::hasDynamicSymbols() const {
817 return Doc.DynamicSymbols.Global.size() > 0 ||
818 Doc.DynamicSymbols.Weak.size() > 0 ||
819 Doc.DynamicSymbols.Local.size() > 0;
820}
821
Xing GUObac78642018-12-07 11:04:22 +0000822template <class ELFT>
823SmallVector<const char *, 5> ELFState<ELFT>::implicitSectionNames() const {
Dave Lee67b49662017-11-16 18:10:15 +0000824 if (!hasDynamicSymbols())
825 return {".symtab", ".strtab", ".shstrtab"};
826 return {".symtab", ".strtab", ".shstrtab", ".dynsym", ".dynstr"};
827}
828
Sean Silva11caeba2013-06-22 01:03:35 +0000829static bool is64Bit(const ELFYAML::Object &Doc) {
830 return Doc.Header.Class == ELFYAML::ELF_ELFCLASS(ELF::ELFCLASS64);
831}
832
833static bool isLittleEndian(const ELFYAML::Object &Doc) {
834 return Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB);
835}
836
Chris Bieneman8ff0c112016-06-27 19:53:53 +0000837int yaml2elf(llvm::ELFYAML::Object &Doc, raw_ostream &Out) {
Sean Silva11caeba2013-06-22 01:03:35 +0000838 if (is64Bit(Doc)) {
839 if (isLittleEndian(Doc))
Rui Ueyama1b31eb92018-01-12 01:40:32 +0000840 return ELFState<object::ELF64LE>::writeELF(Out, Doc);
Sean Silvaf99309c2013-06-10 23:44:15 +0000841 else
Rui Ueyama1b31eb92018-01-12 01:40:32 +0000842 return ELFState<object::ELF64BE>::writeELF(Out, Doc);
Sean Silvaf99309c2013-06-10 23:44:15 +0000843 } else {
Sean Silva11caeba2013-06-22 01:03:35 +0000844 if (isLittleEndian(Doc))
Rui Ueyama1b31eb92018-01-12 01:40:32 +0000845 return ELFState<object::ELF32LE>::writeELF(Out, Doc);
Sean Silvaf99309c2013-06-10 23:44:15 +0000846 else
Rui Ueyama1b31eb92018-01-12 01:40:32 +0000847 return ELFState<object::ELF32BE>::writeELF(Out, Doc);
Sean Silvaf99309c2013-06-10 23:44:15 +0000848 }
Sean Silvaf99309c2013-06-10 23:44:15 +0000849}