blob: 84865341a2937cf9feddd9a4432cca62f0fd5ab7 [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 Rimar646af082019-02-19 15:29:07 +0000160 const ELFYAML::SymverSection &Section,
161 ContiguousBlobAccumulator &CBA);
162 bool writeSectionContent(Elf_Shdr &SHeader,
George Rimar0621b792019-02-19 14:53:48 +0000163 const ELFYAML::VerneedSection &Section,
164 ContiguousBlobAccumulator &CBA);
165 bool writeSectionContent(Elf_Shdr &SHeader,
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000166 const ELFYAML::MipsABIFlags &Section,
167 ContiguousBlobAccumulator &CBA);
George Rimar0e7ed912019-02-09 11:34:28 +0000168 void writeSectionContent(Elf_Shdr &SHeader,
169 const ELFYAML::DynamicSection &Section,
170 ContiguousBlobAccumulator &CBA);
Dave Lee67b49662017-11-16 18:10:15 +0000171 bool hasDynamicSymbols() const;
172 SmallVector<const char *, 5> implicitSectionNames() const;
Sean Silva08a75ae2013-06-20 19:11:44 +0000173
Simon Atanasyan220c54a2014-04-02 16:34:40 +0000174 // - SHT_NULL entry (placed first, i.e. 0'th entry)
Dave Lee67b49662017-11-16 18:10:15 +0000175 // - symbol table (.symtab) (defaults to after last yaml section)
176 // - string table (.strtab) (defaults to after .symtab)
177 // - section header string table (.shstrtab) (defaults to after .strtab)
178 // - dynamic symbol table (.dynsym) (defaults to after .shstrtab)
179 // - dynamic string table (.dynstr) (defaults to after .dynsym)
Dave Lee17307d92017-11-09 14:53:43 +0000180 unsigned getDotSymTabSecNo() const { return SN2I.get(".symtab"); }
181 unsigned getDotStrTabSecNo() const { return SN2I.get(".strtab"); }
182 unsigned getDotShStrTabSecNo() const { return SN2I.get(".shstrtab"); }
Dave Lee67b49662017-11-16 18:10:15 +0000183 unsigned getDotDynSymSecNo() const { return SN2I.get(".dynsym"); }
184 unsigned getDotDynStrSecNo() const { return SN2I.get(".dynstr"); }
Dave Lee17307d92017-11-09 14:53:43 +0000185 unsigned getSectionCount() const { return SN2I.size() + 1; }
Simon Atanasyan220c54a2014-04-02 16:34:40 +0000186
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000187 ELFState(const ELFYAML::Object &D) : Doc(D) {}
Simon Atanasyan220c54a2014-04-02 16:34:40 +0000188
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000189public:
190 static int writeELF(raw_ostream &OS, const ELFYAML::Object &Doc);
George Rimar0621b792019-02-19 14:53:48 +0000191
192private:
193 void finalizeStrings();
Sean Silva08a75ae2013-06-20 19:11:44 +0000194};
195} // end anonymous namespace
196
Sean Silva37e817c2013-06-21 00:33:01 +0000197template <class ELFT>
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000198void ELFState<ELFT>::initELFHeader(Elf_Ehdr &Header) {
199 using namespace llvm::ELF;
200 zero(Header);
201 Header.e_ident[EI_MAG0] = 0x7f;
202 Header.e_ident[EI_MAG1] = 'E';
203 Header.e_ident[EI_MAG2] = 'L';
204 Header.e_ident[EI_MAG3] = 'F';
205 Header.e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;
206 bool IsLittleEndian = ELFT::TargetEndianness == support::little;
207 Header.e_ident[EI_DATA] = IsLittleEndian ? ELFDATA2LSB : ELFDATA2MSB;
208 Header.e_ident[EI_VERSION] = EV_CURRENT;
209 Header.e_ident[EI_OSABI] = Doc.Header.OSABI;
George Rimar6367d7a2018-12-20 10:43:49 +0000210 Header.e_ident[EI_ABIVERSION] = Doc.Header.ABIVersion;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000211 Header.e_type = Doc.Header.Type;
212 Header.e_machine = Doc.Header.Machine;
213 Header.e_version = EV_CURRENT;
214 Header.e_entry = Doc.Header.Entry;
Petr Hosekeb04da32017-07-19 20:38:46 +0000215 Header.e_phoff = sizeof(Header);
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000216 Header.e_flags = Doc.Header.Flags;
217 Header.e_ehsize = sizeof(Elf_Ehdr);
Petr Hosekeb04da32017-07-19 20:38:46 +0000218 Header.e_phentsize = sizeof(Elf_Phdr);
219 Header.e_phnum = Doc.ProgramHeaders.size();
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000220 Header.e_shentsize = sizeof(Elf_Shdr);
Petr Hosekeb04da32017-07-19 20:38:46 +0000221 // Immediately following the ELF header and program headers.
222 Header.e_shoff =
223 sizeof(Header) + sizeof(Elf_Phdr) * Doc.ProgramHeaders.size();
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000224 Header.e_shnum = getSectionCount();
225 Header.e_shstrndx = getDotShStrTabSecNo();
226}
227
228template <class ELFT>
Petr Hosekeb04da32017-07-19 20:38:46 +0000229void ELFState<ELFT>::initProgramHeaders(std::vector<Elf_Phdr> &PHeaders) {
230 for (const auto &YamlPhdr : Doc.ProgramHeaders) {
231 Elf_Phdr Phdr;
232 Phdr.p_type = YamlPhdr.Type;
233 Phdr.p_flags = YamlPhdr.Flags;
234 Phdr.p_vaddr = YamlPhdr.VAddr;
235 Phdr.p_paddr = YamlPhdr.PAddr;
236 PHeaders.push_back(Phdr);
237 }
238}
239
Xing GUO98228352018-12-04 14:27:51 +0000240static bool convertSectionIndex(NameToIdxMap &SN2I, StringRef SecName,
241 StringRef IndexSrc, unsigned &IndexDest) {
242 if (SN2I.lookup(IndexSrc, IndexDest) && !to_integer(IndexSrc, IndexDest)) {
243 WithColor::error() << "Unknown section referenced: '" << IndexSrc
244 << "' at YAML section '" << SecName << "'.\n";
245 return false;
246 }
247 return true;
248}
249
Petr Hosekeb04da32017-07-19 20:38:46 +0000250template <class ELFT>
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000251bool ELFState<ELFT>::initSectionHeaders(std::vector<Elf_Shdr> &SHeaders,
252 ContiguousBlobAccumulator &CBA) {
253 // Ensure SHN_UNDEF entry is present. An all-zero section header is a
254 // valid SHN_UNDEF entry since SHT_NULL == 0.
255 Elf_Shdr SHeader;
256 zero(SHeader);
257 SHeaders.push_back(SHeader);
258
259 for (const auto &Sec : Doc.Sections) {
260 zero(SHeader);
Hans Wennborg59f0cba2014-04-30 19:38:09 +0000261 SHeader.sh_name = DotShStrtab.getOffset(Sec->Name);
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000262 SHeader.sh_type = Sec->Type;
263 SHeader.sh_flags = Sec->Flags;
264 SHeader.sh_addr = Sec->Address;
265 SHeader.sh_addralign = Sec->AddressAlign;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000266
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000267 if (!Sec->Link.empty()) {
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000268 unsigned Index;
Xing GUO98228352018-12-04 14:27:51 +0000269 if (!convertSectionIndex(SN2I, Sec->Name, Sec->Link, Index))
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000270 return false;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000271 SHeader.sh_link = Index;
272 }
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000273
274 if (auto S = dyn_cast<ELFYAML::RawContentSection>(Sec.get()))
275 writeSectionContent(SHeader, *S, CBA);
276 else if (auto S = dyn_cast<ELFYAML::RelocationSection>(Sec.get())) {
277 if (S->Link.empty())
278 // For relocation section set link to .symtab by default.
279 SHeader.sh_link = getDotSymTabSecNo();
280
281 unsigned Index;
George Rimarb87ea732019-02-12 09:08:59 +0000282 if (!convertSectionIndex(SN2I, S->Name, S->RelocatableSec, Index))
George Rimar7f2df7d2018-08-16 12:23:22 +0000283 return false;
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000284 SHeader.sh_info = Index;
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000285 if (!writeSectionContent(SHeader, *S, CBA))
286 return false;
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000287 } else if (auto S = dyn_cast<ELFYAML::Group>(Sec.get())) {
288 unsigned SymIdx;
George Rimarb87ea732019-02-12 09:08:59 +0000289 if (SymN2I.lookup(S->Signature, SymIdx) &&
290 !to_integer(S->Signature, SymIdx)) {
291 WithColor::error() << "Unknown symbol referenced: '" << S->Signature
Jonas Devlieghere2cd41eb2018-04-21 21:11:59 +0000292 << "' at YAML section '" << S->Name << "'.\n";
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000293 return false;
294 }
295 SHeader.sh_info = SymIdx;
296 if (!writeSectionContent(SHeader, *S, CBA))
297 return false;
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000298 } else if (auto S = dyn_cast<ELFYAML::MipsABIFlags>(Sec.get())) {
299 if (!writeSectionContent(SHeader, *S, CBA))
300 return false;
Simon Atanasyan5db02762015-07-03 23:00:54 +0000301 } else if (auto S = dyn_cast<ELFYAML::NoBitsSection>(Sec.get())) {
302 SHeader.sh_entsize = 0;
303 SHeader.sh_size = S->Size;
304 // SHT_NOBITS section does not have content
305 // so just to setup the section offset.
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000306 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
George Rimar0e7ed912019-02-09 11:34:28 +0000307 } else if (auto S = dyn_cast<ELFYAML::DynamicSection>(Sec.get())) {
308 writeSectionContent(SHeader, *S, CBA);
George Rimar646af082019-02-19 15:29:07 +0000309 } else if (auto S = dyn_cast<ELFYAML::SymverSection>(Sec.get())) {
310 writeSectionContent(SHeader, *S, CBA);
George Rimar0621b792019-02-19 14:53:48 +0000311 } else if (auto S = dyn_cast<ELFYAML::VerneedSection>(Sec.get())) {
312 writeSectionContent(SHeader, *S, CBA);
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000313 } else
314 llvm_unreachable("Unknown section type");
315
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000316 SHeaders.push_back(SHeader);
317 }
318 return true;
319}
320
321template <class ELFT>
322void ELFState<ELFT>::initSymtabSectionHeader(Elf_Shdr &SHeader,
Dave Lee67b49662017-11-16 18:10:15 +0000323 SymtabType STType,
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000324 ContiguousBlobAccumulator &CBA) {
325 zero(SHeader);
Dave Lee67b49662017-11-16 18:10:15 +0000326 bool IsStatic = STType == SymtabType::Static;
327 SHeader.sh_name = DotShStrtab.getOffset(IsStatic ? ".symtab" : ".dynsym");
328 SHeader.sh_type = IsStatic ? ELF::SHT_SYMTAB : ELF::SHT_DYNSYM;
329 SHeader.sh_link = IsStatic ? getDotStrTabSecNo() : getDotDynStrSecNo();
330 const auto &Symbols = IsStatic ? Doc.Symbols : Doc.DynamicSymbols;
331 auto &Strtab = IsStatic ? DotStrtab : DotDynstr;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000332 // One greater than symbol table index of the last local symbol.
Dave Lee67b49662017-11-16 18:10:15 +0000333 SHeader.sh_info = Symbols.Local.size() + 1;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000334 SHeader.sh_entsize = sizeof(Elf_Sym);
Simon Atanasyan3a120922015-07-09 18:23:02 +0000335 SHeader.sh_addralign = 8;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000336
George Rimar6947acd2019-02-19 12:15:04 +0000337 // If .dynsym section is explicitly described in the YAML
338 // then we want to use its section address.
339 if (!IsStatic) {
340 // Take section index and ignore the SHT_NULL section.
341 unsigned SecNdx = getDotDynSymSecNo() - 1;
342 if (SecNdx < Doc.Sections.size())
343 SHeader.sh_addr = Doc.Sections[SecNdx]->Address;
344 }
345
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000346 std::vector<Elf_Sym> Syms;
347 {
348 // Ensure STN_UNDEF is present
349 Elf_Sym Sym;
350 zero(Sym);
351 Syms.push_back(Sym);
352 }
Hans Wennborg59f0cba2014-04-30 19:38:09 +0000353
Dave Lee67b49662017-11-16 18:10:15 +0000354 addSymbols(Symbols.Local, Syms, ELF::STB_LOCAL, Strtab);
355 addSymbols(Symbols.Global, Syms, ELF::STB_GLOBAL, Strtab);
356 addSymbols(Symbols.Weak, Syms, ELF::STB_WEAK, Strtab);
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000357
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000358 writeArrayData(
359 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign),
360 makeArrayRef(Syms));
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000361 SHeader.sh_size = arrayDataSize(makeArrayRef(Syms));
362}
363
364template <class ELFT>
365void ELFState<ELFT>::initStrtabSectionHeader(Elf_Shdr &SHeader, StringRef Name,
366 StringTableBuilder &STB,
367 ContiguousBlobAccumulator &CBA) {
368 zero(SHeader);
Hans Wennborg59f0cba2014-04-30 19:38:09 +0000369 SHeader.sh_name = DotShStrtab.getOffset(Name);
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000370 SHeader.sh_type = ELF::SHT_STRTAB;
Rafael Espindola39751af2016-10-04 22:43:25 +0000371 STB.write(CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign));
372 SHeader.sh_size = STB.getSize();
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000373 SHeader.sh_addralign = 1;
George Rimar6947acd2019-02-19 12:15:04 +0000374
375 // If .dynstr section is explicitly described in the YAML
376 // then we want to use its section address.
377 if (Name == ".dynstr") {
378 // Take section index and ignore the SHT_NULL section.
379 unsigned SecNdx = getDotDynStrSecNo() - 1;
380 if (SecNdx < Doc.Sections.size())
381 SHeader.sh_addr = Doc.Sections[SecNdx]->Address;
382 }
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000383}
384
385template <class ELFT>
Petr Hosekeb04da32017-07-19 20:38:46 +0000386void ELFState<ELFT>::setProgramHeaderLayout(std::vector<Elf_Phdr> &PHeaders,
387 std::vector<Elf_Shdr> &SHeaders) {
388 uint32_t PhdrIdx = 0;
389 for (auto &YamlPhdr : Doc.ProgramHeaders) {
390 auto &PHeader = PHeaders[PhdrIdx++];
391
392 if (YamlPhdr.Sections.size())
393 PHeader.p_offset = UINT32_MAX;
394 else
395 PHeader.p_offset = 0;
396
397 // Find the minimum offset for the program header.
398 for (auto SecName : YamlPhdr.Sections) {
399 uint32_t Index = 0;
400 SN2I.lookup(SecName.Section, Index);
401 const auto &SHeader = SHeaders[Index];
402 PHeader.p_offset = std::min(PHeader.p_offset, SHeader.sh_offset);
403 }
404
405 // Find the maximum offset of the end of a section in order to set p_filesz.
406 PHeader.p_filesz = 0;
407 for (auto SecName : YamlPhdr.Sections) {
408 uint32_t Index = 0;
409 SN2I.lookup(SecName.Section, Index);
410 const auto &SHeader = SHeaders[Index];
411 uint64_t EndOfSection;
412 if (SHeader.sh_type == llvm::ELF::SHT_NOBITS)
413 EndOfSection = SHeader.sh_offset;
414 else
415 EndOfSection = SHeader.sh_offset + SHeader.sh_size;
416 uint64_t EndOfSegment = PHeader.p_offset + PHeader.p_filesz;
417 EndOfSegment = std::max(EndOfSegment, EndOfSection);
418 PHeader.p_filesz = EndOfSegment - PHeader.p_offset;
419 }
420
421 // Find the memory size by adding the size of sections at the end of the
422 // segment. These should be empty (size of zero) and NOBITS sections.
423 PHeader.p_memsz = PHeader.p_filesz;
424 for (auto SecName : YamlPhdr.Sections) {
425 uint32_t Index = 0;
426 SN2I.lookup(SecName.Section, Index);
427 const auto &SHeader = SHeaders[Index];
428 if (SHeader.sh_offset == PHeader.p_offset + PHeader.p_filesz)
429 PHeader.p_memsz += SHeader.sh_size;
430 }
431
432 // Set the alignment of the segment to be the same as the maximum alignment
Jake Ehrlich03aeeb092017-11-01 23:14:48 +0000433 // of the sections with the same offset so that by default the segment
Petr Hosekeb04da32017-07-19 20:38:46 +0000434 // has a valid and sensible alignment.
Jake Ehrlich03aeeb092017-11-01 23:14:48 +0000435 if (YamlPhdr.Align) {
436 PHeader.p_align = *YamlPhdr.Align;
437 } else {
438 PHeader.p_align = 1;
439 for (auto SecName : YamlPhdr.Sections) {
440 uint32_t Index = 0;
441 SN2I.lookup(SecName.Section, Index);
442 const auto &SHeader = SHeaders[Index];
443 if (SHeader.sh_offset == PHeader.p_offset)
444 PHeader.p_align = std::max(PHeader.p_align, SHeader.sh_addralign);
445 }
Petr Hosekeb04da32017-07-19 20:38:46 +0000446 }
447 }
448}
449
450template <class ELFT>
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000451void ELFState<ELFT>::addSymbols(const std::vector<ELFYAML::Symbol> &Symbols,
452 std::vector<Elf_Sym> &Syms,
Dave Lee67b49662017-11-16 18:10:15 +0000453 unsigned SymbolBinding,
454 const StringTableBuilder &Strtab) {
Simon Atanasyan048baca2014-03-14 06:53:30 +0000455 for (const auto &Sym : Symbols) {
Sean Silva6b083882013-06-18 23:14:03 +0000456 Elf_Sym Symbol;
457 zero(Symbol);
458 if (!Sym.Name.empty())
Dave Lee67b49662017-11-16 18:10:15 +0000459 Symbol.st_name = Strtab.getOffset(Sym.Name);
Sean Silvaaff51252013-06-21 00:27:50 +0000460 Symbol.setBindingAndType(SymbolBinding, Sym.Type);
Sean Silvac4afa6d2013-06-21 01:11:48 +0000461 if (!Sym.Section.empty()) {
462 unsigned Index;
Simon Atanasyan35babf92014-04-06 09:02:55 +0000463 if (SN2I.lookup(Sym.Section, Index)) {
Jonas Devlieghere2cd41eb2018-04-21 21:11:59 +0000464 WithColor::error() << "Unknown section referenced: '" << Sym.Section
465 << "' by YAML symbol " << Sym.Name << ".\n";
Sean Silvac4afa6d2013-06-21 01:11:48 +0000466 exit(1);
467 }
468 Symbol.st_shndx = Index;
Petr Hosek5c469a32017-09-07 20:44:16 +0000469 } else if (Sym.Index) {
470 Symbol.st_shndx = *Sym.Index;
471 }
472 // else Symbol.st_shndex == SHN_UNDEF (== 0), since it was zero'd earlier.
Sean Silva05001b92013-06-20 20:59:47 +0000473 Symbol.st_value = Sym.Value;
Simon Atanasyan60e1a792014-11-06 22:46:24 +0000474 Symbol.st_other = Sym.Other;
Sean Silva05001b92013-06-20 20:59:47 +0000475 Symbol.st_size = Sym.Size;
Sean Silva6b083882013-06-18 23:14:03 +0000476 Syms.push_back(Symbol);
477 }
Sean Silvaaff51252013-06-21 00:27:50 +0000478}
479
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000480template <class ELFT>
481void
482ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
483 const ELFYAML::RawContentSection &Section,
484 ContiguousBlobAccumulator &CBA) {
Simon Atanasyanb83f3802014-05-16 16:01:00 +0000485 assert(Section.Size >= Section.Content.binary_size() &&
486 "Section size and section content are inconsistent");
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000487 raw_ostream &OS =
488 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
Simon Atanasyanb83f3802014-05-16 16:01:00 +0000489 Section.Content.writeAsBinary(OS);
490 for (auto i = Section.Content.binary_size(); i < Section.Size; ++i)
491 OS.write(0);
George Rimar65a68282018-08-07 08:11:38 +0000492 if (Section.EntSize)
493 SHeader.sh_entsize = *Section.EntSize;
494 else if (Section.Type == llvm::ELF::SHT_RELR)
Jake Ehrlich0f440d82018-06-28 21:07:34 +0000495 SHeader.sh_entsize = sizeof(Elf_Relr);
496 else
497 SHeader.sh_entsize = 0;
Simon Atanasyanb83f3802014-05-16 16:01:00 +0000498 SHeader.sh_size = Section.Size;
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000499}
500
Simon Atanasyan5d19c672015-01-25 13:29:25 +0000501static bool isMips64EL(const ELFYAML::Object &Doc) {
502 return Doc.Header.Machine == ELFYAML::ELF_EM(llvm::ELF::EM_MIPS) &&
503 Doc.Header.Class == ELFYAML::ELF_ELFCLASS(ELF::ELFCLASS64) &&
504 Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB);
505}
506
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000507template <class ELFT>
508bool
509ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
510 const ELFYAML::RelocationSection &Section,
511 ContiguousBlobAccumulator &CBA) {
Simon Atanasyan8eb9d1b2015-05-08 07:05:04 +0000512 assert((Section.Type == llvm::ELF::SHT_REL ||
513 Section.Type == llvm::ELF::SHT_RELA) &&
514 "Section type is not SHT_REL nor SHT_RELA");
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000515
516 bool IsRela = Section.Type == llvm::ELF::SHT_RELA;
517 SHeader.sh_entsize = IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
518 SHeader.sh_size = SHeader.sh_entsize * Section.Relocations.size();
519
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000520 auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000521
522 for (const auto &Rel : Section.Relocations) {
Adhemerval Zanella9f3dbff2015-04-22 15:26:43 +0000523 unsigned SymIdx = 0;
524 // Some special relocation, R_ARM_v4BX for instance, does not have
525 // an external reference. So it ignores the return value of lookup()
526 // here.
Petr Hosek5aa80f12017-08-30 23:13:31 +0000527 if (Rel.Symbol)
528 SymN2I.lookup(*Rel.Symbol, SymIdx);
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000529
530 if (IsRela) {
531 Elf_Rela REntry;
532 zero(REntry);
533 REntry.r_offset = Rel.Offset;
534 REntry.r_addend = Rel.Addend;
Simon Atanasyan5d19c672015-01-25 13:29:25 +0000535 REntry.setSymbolAndType(SymIdx, Rel.Type, isMips64EL(Doc));
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000536 OS.write((const char *)&REntry, sizeof(REntry));
537 } else {
538 Elf_Rel REntry;
539 zero(REntry);
540 REntry.r_offset = Rel.Offset;
Simon Atanasyan5d19c672015-01-25 13:29:25 +0000541 REntry.setSymbolAndType(SymIdx, Rel.Type, isMips64EL(Doc));
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000542 OS.write((const char *)&REntry, sizeof(REntry));
543 }
544 }
545 return true;
546}
547
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000548template <class ELFT>
549bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
550 const ELFYAML::Group &Section,
551 ContiguousBlobAccumulator &CBA) {
Rui Ueyama478d6352018-01-12 02:28:31 +0000552 typedef typename ELFT::Word Elf_Word;
Simon Atanasyan8eb9d1b2015-05-08 07:05:04 +0000553 assert(Section.Type == llvm::ELF::SHT_GROUP &&
554 "Section type is not SHT_GROUP");
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000555
556 SHeader.sh_entsize = sizeof(Elf_Word);
557 SHeader.sh_size = SHeader.sh_entsize * Section.Members.size();
558
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000559 auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000560
561 for (auto member : Section.Members) {
562 Elf_Word SIdx;
563 unsigned int sectionIndex = 0;
564 if (member.sectionNameOrType == "GRP_COMDAT")
565 sectionIndex = llvm::ELF::GRP_COMDAT;
Xing GUO98228352018-12-04 14:27:51 +0000566 else if (!convertSectionIndex(SN2I, Section.Name, member.sectionNameOrType,
567 sectionIndex))
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000568 return false;
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000569 SIdx = sectionIndex;
570 OS.write((const char *)&SIdx, sizeof(SIdx));
571 }
572 return true;
573}
574
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000575template <class ELFT>
576bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
George Rimar646af082019-02-19 15:29:07 +0000577 const ELFYAML::SymverSection &Section,
578 ContiguousBlobAccumulator &CBA) {
579 typedef typename ELFT::Half Elf_Half;
580
581 raw_ostream &OS =
582 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
583 for (uint16_t V : Section.Entries) {
584 Elf_Half Version = (Elf_Half)V;
585 OS.write((const char *)&Version, sizeof(Elf_Half));
586 }
587
588 SHeader.sh_size = Section.Entries.size() * sizeof(Elf_Half);
589 SHeader.sh_entsize = sizeof(Elf_Half);
590 return true;
591}
592
593template <class ELFT>
594bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
George Rimar0621b792019-02-19 14:53:48 +0000595 const ELFYAML::VerneedSection &Section,
596 ContiguousBlobAccumulator &CBA) {
597 typedef typename ELFT::Verneed Elf_Verneed;
598 typedef typename ELFT::Vernaux Elf_Vernaux;
599
600 auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
601
602 uint64_t AuxCnt = 0;
603 for (size_t I = 0; I < Section.VerneedV.size(); ++I) {
604 const ELFYAML::VerneedEntry &VE = Section.VerneedV[I];
605
606 Elf_Verneed VerNeed;
607 VerNeed.vn_version = VE.Version;
608 VerNeed.vn_file = DotDynstr.getOffset(VE.File);
609 if (I == Section.VerneedV.size() - 1)
610 VerNeed.vn_next = 0;
611 else
612 VerNeed.vn_next =
613 sizeof(Elf_Verneed) + VE.AuxV.size() * sizeof(Elf_Vernaux);
614 VerNeed.vn_cnt = VE.AuxV.size();
615 VerNeed.vn_aux = sizeof(Elf_Verneed);
616 OS.write((const char *)&VerNeed, sizeof(Elf_Verneed));
617
618 for (size_t J = 0; J < VE.AuxV.size(); ++J, ++AuxCnt) {
619 const ELFYAML::VernauxEntry &VAuxE = VE.AuxV[J];
620
621 Elf_Vernaux VernAux;
622 VernAux.vna_hash = VAuxE.Hash;
623 VernAux.vna_flags = VAuxE.Flags;
624 VernAux.vna_other = VAuxE.Other;
625 VernAux.vna_name = DotDynstr.getOffset(VAuxE.Name);
626 if (J == VE.AuxV.size() - 1)
627 VernAux.vna_next = 0;
628 else
629 VernAux.vna_next = sizeof(Elf_Vernaux);
630 OS.write((const char *)&VernAux, sizeof(Elf_Vernaux));
631 }
632 }
633
634 SHeader.sh_size = Section.VerneedV.size() * sizeof(Elf_Verneed) +
635 AuxCnt * sizeof(Elf_Vernaux);
636 SHeader.sh_info = Section.Info;
637
638 return true;
639}
640
641template <class ELFT>
642bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000643 const ELFYAML::MipsABIFlags &Section,
644 ContiguousBlobAccumulator &CBA) {
Simon Atanasyan8eb9d1b2015-05-08 07:05:04 +0000645 assert(Section.Type == llvm::ELF::SHT_MIPS_ABIFLAGS &&
646 "Section type is not SHT_MIPS_ABIFLAGS");
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000647
648 object::Elf_Mips_ABIFlags<ELFT> Flags;
649 zero(Flags);
650 SHeader.sh_entsize = sizeof(Flags);
651 SHeader.sh_size = SHeader.sh_entsize;
652
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000653 auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000654 Flags.version = Section.Version;
655 Flags.isa_level = Section.ISALevel;
656 Flags.isa_rev = Section.ISARevision;
657 Flags.gpr_size = Section.GPRSize;
658 Flags.cpr1_size = Section.CPR1Size;
659 Flags.cpr2_size = Section.CPR2Size;
660 Flags.fp_abi = Section.FpABI;
661 Flags.isa_ext = Section.ISAExtension;
662 Flags.ases = Section.ASEs;
663 Flags.flags1 = Section.Flags1;
664 Flags.flags2 = Section.Flags2;
665 OS.write((const char *)&Flags, sizeof(Flags));
666
667 return true;
668}
669
George Rimar0e7ed912019-02-09 11:34:28 +0000670template <class ELFT>
671void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
672 const ELFYAML::DynamicSection &Section,
673 ContiguousBlobAccumulator &CBA) {
George Rimar5cb31732019-02-10 08:35:38 +0000674 typedef typename ELFT::Addr Elf_Addr;
George Rimar0e7ed912019-02-09 11:34:28 +0000675 assert(Section.Type == llvm::ELF::SHT_DYNAMIC &&
676 "Section type is not SHT_DYNAMIC");
677
George Rimar5cb31732019-02-10 08:35:38 +0000678 SHeader.sh_size = 2 * sizeof(Elf_Addr) * Section.Entries.size();
George Rimar0e7ed912019-02-09 11:34:28 +0000679 if (Section.EntSize)
680 SHeader.sh_entsize = *Section.EntSize;
681 else
682 SHeader.sh_entsize = sizeof(Elf_Dyn);
683
684 auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
685 for (const ELFYAML::DynamicEntry &DE : Section.Entries) {
George Rimar5cb31732019-02-10 08:35:38 +0000686 Elf_Addr Tag = (Elf_Addr)DE.Tag;
687 OS.write((const char *)&Tag, sizeof(Elf_Addr));
688 Elf_Addr Val = (Elf_Addr)DE.Val;
689 OS.write((const char *)&Val, sizeof(Elf_Addr));
George Rimar0e7ed912019-02-09 11:34:28 +0000690 }
691}
692
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000693template <class ELFT> bool ELFState<ELFT>::buildSectionIndex() {
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000694 for (unsigned i = 0, e = Doc.Sections.size(); i != e; ++i) {
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000695 StringRef Name = Doc.Sections[i]->Name;
Dave Lee17307d92017-11-09 14:53:43 +0000696 DotShStrtab.add(Name);
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000697 // "+ 1" to take into account the SHT_NULL entry.
698 if (SN2I.addName(Name, i + 1)) {
Jonas Devlieghere2cd41eb2018-04-21 21:11:59 +0000699 WithColor::error() << "Repeated section name: '" << Name
700 << "' at YAML section number " << i << ".\n";
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000701 return false;
702 }
Sean Silvaaff51252013-06-21 00:27:50 +0000703 }
Dave Lee17307d92017-11-09 14:53:43 +0000704
705 auto SecNo = 1 + Doc.Sections.size();
706 // Add special sections after input sections, if necessary.
Dave Lee67b49662017-11-16 18:10:15 +0000707 for (const auto &Name : implicitSectionNames())
Dave Lee17307d92017-11-09 14:53:43 +0000708 if (!SN2I.addName(Name, SecNo)) {
709 // Account for this section, since it wasn't in the Doc
710 ++SecNo;
711 DotShStrtab.add(Name);
712 }
713
714 DotShStrtab.finalize();
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000715 return true;
Sean Silva6b083882013-06-18 23:14:03 +0000716}
717
Sean Silvaf99309c2013-06-10 23:44:15 +0000718template <class ELFT>
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000719bool
720ELFState<ELFT>::buildSymbolIndex(std::size_t &StartIndex,
721 const std::vector<ELFYAML::Symbol> &Symbols) {
722 for (const auto &Sym : Symbols) {
723 ++StartIndex;
724 if (Sym.Name.empty())
725 continue;
726 if (SymN2I.addName(Sym.Name, StartIndex)) {
Jonas Devlieghere2cd41eb2018-04-21 21:11:59 +0000727 WithColor::error() << "Repeated symbol name: '" << Sym.Name << "'.\n";
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000728 return false;
729 }
730 }
731 return true;
732}
733
George Rimar0621b792019-02-19 14:53:48 +0000734template <class ELFT> void ELFState<ELFT>::finalizeStrings() {
735 auto AddSymbols = [](StringTableBuilder &StrTab,
736 const ELFYAML::LocalGlobalWeakSymbols &Symbols) {
737 for (const auto &Sym : Symbols.Local)
738 StrTab.add(Sym.Name);
739 for (const auto &Sym : Symbols.Global)
740 StrTab.add(Sym.Name);
741 for (const auto &Sym : Symbols.Weak)
742 StrTab.add(Sym.Name);
743 };
744
745 // Add the regular symbol names to .strtab section.
746 AddSymbols(DotStrtab, Doc.Symbols);
747 DotStrtab.finalize();
748
749 if (!hasDynamicSymbols())
750 return;
751
752 // Add the dynamic symbol names to .dynstr section.
753 AddSymbols(DotDynstr, Doc.DynamicSymbols);
754
755 // SHT_GNU_verneed section also adds strings to .dynstr section.
756 for (const std::unique_ptr<ELFYAML::Section> &Sec : Doc.Sections) {
757 auto VerNeed = dyn_cast<ELFYAML::VerneedSection>(Sec.get());
758 if (!VerNeed)
759 continue;
760
761 for (const ELFYAML::VerneedEntry &VE : VerNeed->VerneedV) {
762 DotDynstr.add(VE.File);
763 for (const ELFYAML::VernauxEntry &Aux : VE.AuxV)
764 DotDynstr.add(Aux.Name);
765 }
766 }
767
768 DotDynstr.finalize();
769}
770
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000771template <class ELFT>
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000772int ELFState<ELFT>::writeELF(raw_ostream &OS, const ELFYAML::Object &Doc) {
Simon Atanasyan220c54a2014-04-02 16:34:40 +0000773 ELFState<ELFT> State(Doc);
George Rimar0621b792019-02-19 14:53:48 +0000774
775 // Finalize .strtab and .dynstr sections. We do that early because want to
776 // finalize the string table builders before writing the content of the
777 // sections that might want to use them.
778 State.finalizeStrings();
779
Simon Atanasyan220c54a2014-04-02 16:34:40 +0000780 if (!State.buildSectionIndex())
781 return 1;
782
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000783 std::size_t StartSymIndex = 0;
784 if (!State.buildSymbolIndex(StartSymIndex, Doc.Symbols.Local) ||
785 !State.buildSymbolIndex(StartSymIndex, Doc.Symbols.Global) ||
786 !State.buildSymbolIndex(StartSymIndex, Doc.Symbols.Weak))
787 return 1;
788
Sean Silva38205932013-06-13 22:19:48 +0000789 Elf_Ehdr Header;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000790 State.initELFHeader(Header);
Sean Silvaf99309c2013-06-10 23:44:15 +0000791
Sean Silva38205932013-06-13 22:19:48 +0000792 // TODO: Flesh out section header support.
Petr Hosekeb04da32017-07-19 20:38:46 +0000793
794 std::vector<Elf_Phdr> PHeaders;
795 State.initProgramHeaders(PHeaders);
Sean Silva38205932013-06-13 22:19:48 +0000796
Sean Silva08a75ae2013-06-20 19:11:44 +0000797 // XXX: This offset is tightly coupled with the order that we write
798 // things to `OS`.
Petr Hosekeb04da32017-07-19 20:38:46 +0000799 const size_t SectionContentBeginOffset = Header.e_ehsize +
800 Header.e_phentsize * Header.e_phnum +
801 Header.e_shentsize * Header.e_shnum;
Sean Silva08a75ae2013-06-20 19:11:44 +0000802 ContiguousBlobAccumulator CBA(SectionContentBeginOffset);
Sean Silvac1c290b2013-06-20 20:59:34 +0000803
Sean Silva38205932013-06-13 22:19:48 +0000804 std::vector<Elf_Shdr> SHeaders;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000805 if(!State.initSectionHeaders(SHeaders, CBA))
806 return 1;
Sean Silva38205932013-06-13 22:19:48 +0000807
Dave Lee17307d92017-11-09 14:53:43 +0000808 // Populate SHeaders with implicit sections not present in the Doc
Dave Lee67b49662017-11-16 18:10:15 +0000809 for (const auto &Name : State.implicitSectionNames())
Dave Lee17307d92017-11-09 14:53:43 +0000810 if (State.SN2I.get(Name) >= SHeaders.size())
811 SHeaders.push_back({});
Sean Silva82177572013-06-22 01:38:00 +0000812
Dave Lee17307d92017-11-09 14:53:43 +0000813 // Initialize the implicit sections
814 auto Index = State.SN2I.get(".symtab");
Dave Lee67b49662017-11-16 18:10:15 +0000815 State.initSymtabSectionHeader(SHeaders[Index], SymtabType::Static, CBA);
Dave Lee17307d92017-11-09 14:53:43 +0000816 Index = State.SN2I.get(".strtab");
817 State.initStrtabSectionHeader(SHeaders[Index], ".strtab", State.DotStrtab, CBA);
818 Index = State.SN2I.get(".shstrtab");
819 State.initStrtabSectionHeader(SHeaders[Index], ".shstrtab", State.DotShStrtab, CBA);
Dave Lee67b49662017-11-16 18:10:15 +0000820 if (State.hasDynamicSymbols()) {
821 Index = State.SN2I.get(".dynsym");
822 State.initSymtabSectionHeader(SHeaders[Index], SymtabType::Dynamic, CBA);
823 SHeaders[Index].sh_flags |= ELF::SHF_ALLOC;
824 Index = State.SN2I.get(".dynstr");
825 State.initStrtabSectionHeader(SHeaders[Index], ".dynstr", State.DotDynstr, CBA);
826 SHeaders[Index].sh_flags |= ELF::SHF_ALLOC;
827 }
Sean Silvaf99309c2013-06-10 23:44:15 +0000828
Petr Hosekeb04da32017-07-19 20:38:46 +0000829 // Now we can decide segment offsets
830 State.setProgramHeaderLayout(PHeaders, SHeaders);
831
Sean Silvaf99309c2013-06-10 23:44:15 +0000832 OS.write((const char *)&Header, sizeof(Header));
Petr Hosekeb04da32017-07-19 20:38:46 +0000833 writeArrayData(OS, makeArrayRef(PHeaders));
Will Dietz0b48c732013-10-12 21:29:16 +0000834 writeArrayData(OS, makeArrayRef(SHeaders));
Sean Silva46dffff2013-06-13 22:20:01 +0000835 CBA.writeBlobToStream(OS);
Sean Silva415d93f2013-06-17 20:14:59 +0000836 return 0;
Sean Silvaf99309c2013-06-10 23:44:15 +0000837}
838
Dave Lee67b49662017-11-16 18:10:15 +0000839template <class ELFT> bool ELFState<ELFT>::hasDynamicSymbols() const {
840 return Doc.DynamicSymbols.Global.size() > 0 ||
841 Doc.DynamicSymbols.Weak.size() > 0 ||
842 Doc.DynamicSymbols.Local.size() > 0;
843}
844
Xing GUObac78642018-12-07 11:04:22 +0000845template <class ELFT>
846SmallVector<const char *, 5> ELFState<ELFT>::implicitSectionNames() const {
Dave Lee67b49662017-11-16 18:10:15 +0000847 if (!hasDynamicSymbols())
848 return {".symtab", ".strtab", ".shstrtab"};
849 return {".symtab", ".strtab", ".shstrtab", ".dynsym", ".dynstr"};
850}
851
Sean Silva11caeba2013-06-22 01:03:35 +0000852static bool is64Bit(const ELFYAML::Object &Doc) {
853 return Doc.Header.Class == ELFYAML::ELF_ELFCLASS(ELF::ELFCLASS64);
854}
855
856static bool isLittleEndian(const ELFYAML::Object &Doc) {
857 return Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB);
858}
859
Chris Bieneman8ff0c112016-06-27 19:53:53 +0000860int yaml2elf(llvm::ELFYAML::Object &Doc, raw_ostream &Out) {
Sean Silva11caeba2013-06-22 01:03:35 +0000861 if (is64Bit(Doc)) {
862 if (isLittleEndian(Doc))
Rui Ueyama1b31eb92018-01-12 01:40:32 +0000863 return ELFState<object::ELF64LE>::writeELF(Out, Doc);
Sean Silvaf99309c2013-06-10 23:44:15 +0000864 else
Rui Ueyama1b31eb92018-01-12 01:40:32 +0000865 return ELFState<object::ELF64BE>::writeELF(Out, Doc);
Sean Silvaf99309c2013-06-10 23:44:15 +0000866 } else {
Sean Silva11caeba2013-06-22 01:03:35 +0000867 if (isLittleEndian(Doc))
Rui Ueyama1b31eb92018-01-12 01:40:32 +0000868 return ELFState<object::ELF32LE>::writeELF(Out, Doc);
Sean Silvaf99309c2013-06-10 23:44:15 +0000869 else
Rui Ueyama1b31eb92018-01-12 01:40:32 +0000870 return ELFState<object::ELF32BE>::writeELF(Out, Doc);
Sean Silvaf99309c2013-06-10 23:44:15 +0000871 }
Sean Silvaf99309c2013-06-10 23:44:15 +0000872}