blob: 351b734765377dc4d5e32ef46912170dd6dfe843 [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"
George Rimard063c7d2019-02-20 13:58:43 +000020#include "llvm/Support/EndianStream.h"
Sean Silvaf99309c2013-06-10 23:44:15 +000021#include "llvm/Support/MemoryBuffer.h"
Jonas Devlieghere2cd41eb2018-04-21 21:11:59 +000022#include "llvm/Support/WithColor.h"
Sean Silvaf99309c2013-06-10 23:44:15 +000023#include "llvm/Support/YAMLTraits.h"
24#include "llvm/Support/raw_ostream.h"
25
26using namespace llvm;
27
Sean Silva46dffff2013-06-13 22:20:01 +000028// This class is used to build up a contiguous binary blob while keeping
29// track of an offset in the output (which notionally begins at
30// `InitialOffset`).
Sean Silva2a74f702013-06-15 00:31:46 +000031namespace {
Sean Silva46dffff2013-06-13 22:20:01 +000032class ContiguousBlobAccumulator {
33 const uint64_t InitialOffset;
Sean Silvabd3bc692013-06-20 19:11:41 +000034 SmallVector<char, 128> Buf;
Sean Silva46dffff2013-06-13 22:20:01 +000035 raw_svector_ostream OS;
36
Sean Silvad93323f2013-06-22 00:47:43 +000037 /// \returns The new offset.
38 uint64_t padToAlignment(unsigned Align) {
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +000039 if (Align == 0)
40 Align = 1;
Sean Silvad93323f2013-06-22 00:47:43 +000041 uint64_t CurrentOffset = InitialOffset + OS.tell();
Rui Ueyamada00f2f2016-01-14 21:06:47 +000042 uint64_t AlignedOffset = alignTo(CurrentOffset, Align);
Sean Silvad93323f2013-06-22 00:47:43 +000043 for (; CurrentOffset != AlignedOffset; ++CurrentOffset)
44 OS.write('\0');
45 return AlignedOffset; // == CurrentOffset;
46 }
47
Sean Silva46dffff2013-06-13 22:20:01 +000048public:
Sean Silvabd3bc692013-06-20 19:11:41 +000049 ContiguousBlobAccumulator(uint64_t InitialOffset_)
50 : InitialOffset(InitialOffset_), Buf(), OS(Buf) {}
Sean Silvad93323f2013-06-22 00:47:43 +000051 template <class Integer>
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +000052 raw_ostream &getOSAndAlignedOffset(Integer &Offset, unsigned Align) {
Sean Silvad93323f2013-06-22 00:47:43 +000053 Offset = padToAlignment(Align);
54 return OS;
55 }
Sean Silva46dffff2013-06-13 22:20:01 +000056 void writeBlobToStream(raw_ostream &Out) { Out << OS.str(); }
57};
Sean Silva2a74f702013-06-15 00:31:46 +000058} // end anonymous namespace
Sean Silva46dffff2013-06-13 22:20:01 +000059
Simon Atanasyan35babf92014-04-06 09:02:55 +000060// Used to keep track of section and symbol names, so that in the YAML file
61// sections and symbols can be referenced by name instead of by index.
Sean Silva2a74f702013-06-15 00:31:46 +000062namespace {
Simon Atanasyan35babf92014-04-06 09:02:55 +000063class NameToIdxMap {
Sean Silvaa6423eb2013-06-15 00:25:26 +000064 StringMap<int> Map;
65public:
66 /// \returns true if name is already present in the map.
Simon Atanasyan35babf92014-04-06 09:02:55 +000067 bool addName(StringRef Name, unsigned i) {
David Blaikie5106ce72014-11-19 05:49:42 +000068 return !Map.insert(std::make_pair(Name, (int)i)).second;
Sean Silvaa6423eb2013-06-15 00:25:26 +000069 }
70 /// \returns true if name is not present in the map
Simon Atanasyan35babf92014-04-06 09:02:55 +000071 bool lookup(StringRef Name, unsigned &Idx) const {
72 StringMap<int>::const_iterator I = Map.find(Name);
Sean Silvaa6423eb2013-06-15 00:25:26 +000073 if (I == Map.end())
74 return true;
75 Idx = I->getValue();
76 return false;
77 }
Dave Lee17307d92017-11-09 14:53:43 +000078 /// asserts if name is not present in the map
79 unsigned get(StringRef Name) const {
80 unsigned Idx = 0;
81 auto missing = lookup(Name, Idx);
82 (void)missing;
83 assert(!missing && "Expected section not found in index");
84 return Idx;
85 }
86 unsigned size() const { return Map.size(); }
Sean Silvaa6423eb2013-06-15 00:25:26 +000087};
Sean Silva2a74f702013-06-15 00:31:46 +000088} // end anonymous namespace
Sean Silvaa6423eb2013-06-15 00:25:26 +000089
Sean Silva38205932013-06-13 22:19:48 +000090template <class T>
Will Dietz0b48c732013-10-12 21:29:16 +000091static size_t arrayDataSize(ArrayRef<T> A) {
92 return A.size() * sizeof(T);
Sean Silva38205932013-06-13 22:19:48 +000093}
94
95template <class T>
Will Dietz0b48c732013-10-12 21:29:16 +000096static void writeArrayData(raw_ostream &OS, ArrayRef<T> A) {
97 OS.write((const char *)A.data(), arrayDataSize(A));
Sean Silva38205932013-06-13 22:19:48 +000098}
99
100template <class T>
101static void zero(T &Obj) {
102 memset(&Obj, 0, sizeof(Obj));
103}
104
Sean Silva08a75ae2013-06-20 19:11:44 +0000105namespace {
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000106/// "Single point of truth" for the ELF file construction.
Sean Silva08a75ae2013-06-20 19:11:44 +0000107/// TODO: This class still has a ways to go before it is truly a "single
108/// point of truth".
109template <class ELFT>
110class ELFState {
Rui Ueyama478d6352018-01-12 02:28:31 +0000111 typedef typename ELFT::Ehdr Elf_Ehdr;
112 typedef typename ELFT::Phdr Elf_Phdr;
113 typedef typename ELFT::Shdr Elf_Shdr;
114 typedef typename ELFT::Sym Elf_Sym;
115 typedef typename ELFT::Rel Elf_Rel;
116 typedef typename ELFT::Rela Elf_Rela;
Jake Ehrlich0f440d82018-06-28 21:07:34 +0000117 typedef typename ELFT::Relr Elf_Relr;
Paul Semel1dbbfba2018-07-23 18:49:04 +0000118 typedef typename ELFT::Dyn Elf_Dyn;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000119
Dave Lee67b49662017-11-16 18:10:15 +0000120 enum class SymtabType { Static, Dynamic };
121
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000122 /// The future ".strtab" section.
Rafael Espindola21956e42015-10-23 21:48:05 +0000123 StringTableBuilder DotStrtab{StringTableBuilder::ELF};
Sean Silva08a75ae2013-06-20 19:11:44 +0000124
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000125 /// The future ".shstrtab" section.
Rafael Espindola21956e42015-10-23 21:48:05 +0000126 StringTableBuilder DotShStrtab{StringTableBuilder::ELF};
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000127
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000128 /// The future ".dynstr" section.
Dave Lee67b49662017-11-16 18:10:15 +0000129 StringTableBuilder DotDynstr{StringTableBuilder::ELF};
130
Simon Atanasyan35babf92014-04-06 09:02:55 +0000131 NameToIdxMap SN2I;
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000132 NameToIdxMap SymN2I;
Simon Atanasyan220c54a2014-04-02 16:34:40 +0000133 const ELFYAML::Object &Doc;
Sean Silvac1c290b2013-06-20 20:59:34 +0000134
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000135 bool buildSectionIndex();
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000136 bool buildSymbolIndex(std::size_t &StartIndex,
137 const std::vector<ELFYAML::Symbol> &Symbols);
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000138 void initELFHeader(Elf_Ehdr &Header);
Petr Hosekeb04da32017-07-19 20:38:46 +0000139 void initProgramHeaders(std::vector<Elf_Phdr> &PHeaders);
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000140 bool initSectionHeaders(std::vector<Elf_Shdr> &SHeaders,
141 ContiguousBlobAccumulator &CBA);
Dave Lee67b49662017-11-16 18:10:15 +0000142 void initSymtabSectionHeader(Elf_Shdr &SHeader, SymtabType STType,
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000143 ContiguousBlobAccumulator &CBA);
144 void initStrtabSectionHeader(Elf_Shdr &SHeader, StringRef Name,
145 StringTableBuilder &STB,
146 ContiguousBlobAccumulator &CBA);
Petr Hosekeb04da32017-07-19 20:38:46 +0000147 void setProgramHeaderLayout(std::vector<Elf_Phdr> &PHeaders,
148 std::vector<Elf_Shdr> &SHeaders);
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000149 void addSymbols(const std::vector<ELFYAML::Symbol> &Symbols,
Dave Lee67b49662017-11-16 18:10:15 +0000150 std::vector<Elf_Sym> &Syms, unsigned SymbolBinding,
151 const StringTableBuilder &Strtab);
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000152 void writeSectionContent(Elf_Shdr &SHeader,
153 const ELFYAML::RawContentSection &Section,
154 ContiguousBlobAccumulator &CBA);
155 bool writeSectionContent(Elf_Shdr &SHeader,
156 const ELFYAML::RelocationSection &Section,
157 ContiguousBlobAccumulator &CBA);
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000158 bool writeSectionContent(Elf_Shdr &SHeader, const ELFYAML::Group &Group,
159 ContiguousBlobAccumulator &CBA);
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000160 bool writeSectionContent(Elf_Shdr &SHeader,
George Rimar646af082019-02-19 15:29:07 +0000161 const ELFYAML::SymverSection &Section,
162 ContiguousBlobAccumulator &CBA);
163 bool writeSectionContent(Elf_Shdr &SHeader,
George Rimar0621b792019-02-19 14:53:48 +0000164 const ELFYAML::VerneedSection &Section,
165 ContiguousBlobAccumulator &CBA);
166 bool writeSectionContent(Elf_Shdr &SHeader,
George Rimar623ae722019-02-21 12:21:43 +0000167 const ELFYAML::VerdefSection &Section,
168 ContiguousBlobAccumulator &CBA);
169 bool writeSectionContent(Elf_Shdr &SHeader,
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000170 const ELFYAML::MipsABIFlags &Section,
171 ContiguousBlobAccumulator &CBA);
George Rimar0e7ed912019-02-09 11:34:28 +0000172 void writeSectionContent(Elf_Shdr &SHeader,
173 const ELFYAML::DynamicSection &Section,
174 ContiguousBlobAccumulator &CBA);
Dave Lee67b49662017-11-16 18:10:15 +0000175 bool hasDynamicSymbols() const;
176 SmallVector<const char *, 5> implicitSectionNames() const;
Sean Silva08a75ae2013-06-20 19:11:44 +0000177
Simon Atanasyan220c54a2014-04-02 16:34:40 +0000178 // - SHT_NULL entry (placed first, i.e. 0'th entry)
Dave Lee67b49662017-11-16 18:10:15 +0000179 // - symbol table (.symtab) (defaults to after last yaml section)
180 // - string table (.strtab) (defaults to after .symtab)
181 // - section header string table (.shstrtab) (defaults to after .strtab)
182 // - dynamic symbol table (.dynsym) (defaults to after .shstrtab)
183 // - dynamic string table (.dynstr) (defaults to after .dynsym)
Dave Lee17307d92017-11-09 14:53:43 +0000184 unsigned getDotSymTabSecNo() const { return SN2I.get(".symtab"); }
185 unsigned getDotStrTabSecNo() const { return SN2I.get(".strtab"); }
186 unsigned getDotShStrTabSecNo() const { return SN2I.get(".shstrtab"); }
Dave Lee67b49662017-11-16 18:10:15 +0000187 unsigned getDotDynSymSecNo() const { return SN2I.get(".dynsym"); }
188 unsigned getDotDynStrSecNo() const { return SN2I.get(".dynstr"); }
Dave Lee17307d92017-11-09 14:53:43 +0000189 unsigned getSectionCount() const { return SN2I.size() + 1; }
Simon Atanasyan220c54a2014-04-02 16:34:40 +0000190
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000191 ELFState(const ELFYAML::Object &D) : Doc(D) {}
Simon Atanasyan220c54a2014-04-02 16:34:40 +0000192
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000193public:
194 static int writeELF(raw_ostream &OS, const ELFYAML::Object &Doc);
George Rimar0621b792019-02-19 14:53:48 +0000195
196private:
197 void finalizeStrings();
Sean Silva08a75ae2013-06-20 19:11:44 +0000198};
199} // end anonymous namespace
200
Sean Silva37e817c2013-06-21 00:33:01 +0000201template <class ELFT>
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000202void ELFState<ELFT>::initELFHeader(Elf_Ehdr &Header) {
203 using namespace llvm::ELF;
204 zero(Header);
205 Header.e_ident[EI_MAG0] = 0x7f;
206 Header.e_ident[EI_MAG1] = 'E';
207 Header.e_ident[EI_MAG2] = 'L';
208 Header.e_ident[EI_MAG3] = 'F';
209 Header.e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;
210 bool IsLittleEndian = ELFT::TargetEndianness == support::little;
211 Header.e_ident[EI_DATA] = IsLittleEndian ? ELFDATA2LSB : ELFDATA2MSB;
212 Header.e_ident[EI_VERSION] = EV_CURRENT;
213 Header.e_ident[EI_OSABI] = Doc.Header.OSABI;
George Rimar6367d7a2018-12-20 10:43:49 +0000214 Header.e_ident[EI_ABIVERSION] = Doc.Header.ABIVersion;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000215 Header.e_type = Doc.Header.Type;
216 Header.e_machine = Doc.Header.Machine;
217 Header.e_version = EV_CURRENT;
218 Header.e_entry = Doc.Header.Entry;
Petr Hosekeb04da32017-07-19 20:38:46 +0000219 Header.e_phoff = sizeof(Header);
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000220 Header.e_flags = Doc.Header.Flags;
221 Header.e_ehsize = sizeof(Elf_Ehdr);
Petr Hosekeb04da32017-07-19 20:38:46 +0000222 Header.e_phentsize = sizeof(Elf_Phdr);
223 Header.e_phnum = Doc.ProgramHeaders.size();
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000224 Header.e_shentsize = sizeof(Elf_Shdr);
Petr Hosekeb04da32017-07-19 20:38:46 +0000225 // Immediately following the ELF header and program headers.
226 Header.e_shoff =
227 sizeof(Header) + sizeof(Elf_Phdr) * Doc.ProgramHeaders.size();
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000228 Header.e_shnum = getSectionCount();
229 Header.e_shstrndx = getDotShStrTabSecNo();
230}
231
232template <class ELFT>
Petr Hosekeb04da32017-07-19 20:38:46 +0000233void ELFState<ELFT>::initProgramHeaders(std::vector<Elf_Phdr> &PHeaders) {
234 for (const auto &YamlPhdr : Doc.ProgramHeaders) {
235 Elf_Phdr Phdr;
236 Phdr.p_type = YamlPhdr.Type;
237 Phdr.p_flags = YamlPhdr.Flags;
238 Phdr.p_vaddr = YamlPhdr.VAddr;
239 Phdr.p_paddr = YamlPhdr.PAddr;
240 PHeaders.push_back(Phdr);
241 }
242}
243
Xing GUO98228352018-12-04 14:27:51 +0000244static bool convertSectionIndex(NameToIdxMap &SN2I, StringRef SecName,
245 StringRef IndexSrc, unsigned &IndexDest) {
246 if (SN2I.lookup(IndexSrc, IndexDest) && !to_integer(IndexSrc, IndexDest)) {
247 WithColor::error() << "Unknown section referenced: '" << IndexSrc
248 << "' at YAML section '" << SecName << "'.\n";
249 return false;
250 }
251 return true;
252}
253
Petr Hosekeb04da32017-07-19 20:38:46 +0000254template <class ELFT>
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000255bool ELFState<ELFT>::initSectionHeaders(std::vector<Elf_Shdr> &SHeaders,
256 ContiguousBlobAccumulator &CBA) {
257 // Ensure SHN_UNDEF entry is present. An all-zero section header is a
258 // valid SHN_UNDEF entry since SHT_NULL == 0.
259 Elf_Shdr SHeader;
260 zero(SHeader);
261 SHeaders.push_back(SHeader);
262
263 for (const auto &Sec : Doc.Sections) {
264 zero(SHeader);
Hans Wennborg59f0cba2014-04-30 19:38:09 +0000265 SHeader.sh_name = DotShStrtab.getOffset(Sec->Name);
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000266 SHeader.sh_type = Sec->Type;
267 SHeader.sh_flags = Sec->Flags;
268 SHeader.sh_addr = Sec->Address;
269 SHeader.sh_addralign = Sec->AddressAlign;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000270
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000271 if (!Sec->Link.empty()) {
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000272 unsigned Index;
Xing GUO98228352018-12-04 14:27:51 +0000273 if (!convertSectionIndex(SN2I, Sec->Name, Sec->Link, Index))
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000274 return false;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000275 SHeader.sh_link = Index;
276 }
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000277
278 if (auto S = dyn_cast<ELFYAML::RawContentSection>(Sec.get()))
279 writeSectionContent(SHeader, *S, CBA);
280 else if (auto S = dyn_cast<ELFYAML::RelocationSection>(Sec.get())) {
281 if (S->Link.empty())
282 // For relocation section set link to .symtab by default.
283 SHeader.sh_link = getDotSymTabSecNo();
284
285 unsigned Index;
George Rimarb87ea732019-02-12 09:08:59 +0000286 if (!convertSectionIndex(SN2I, S->Name, S->RelocatableSec, Index))
George Rimar7f2df7d2018-08-16 12:23:22 +0000287 return false;
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000288 SHeader.sh_info = Index;
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000289 if (!writeSectionContent(SHeader, *S, CBA))
290 return false;
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000291 } else if (auto S = dyn_cast<ELFYAML::Group>(Sec.get())) {
292 unsigned SymIdx;
George Rimarb87ea732019-02-12 09:08:59 +0000293 if (SymN2I.lookup(S->Signature, SymIdx) &&
294 !to_integer(S->Signature, SymIdx)) {
295 WithColor::error() << "Unknown symbol referenced: '" << S->Signature
Jonas Devlieghere2cd41eb2018-04-21 21:11:59 +0000296 << "' at YAML section '" << S->Name << "'.\n";
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000297 return false;
298 }
299 SHeader.sh_info = SymIdx;
300 if (!writeSectionContent(SHeader, *S, CBA))
301 return false;
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000302 } else if (auto S = dyn_cast<ELFYAML::MipsABIFlags>(Sec.get())) {
303 if (!writeSectionContent(SHeader, *S, CBA))
304 return false;
Simon Atanasyan5db02762015-07-03 23:00:54 +0000305 } else if (auto S = dyn_cast<ELFYAML::NoBitsSection>(Sec.get())) {
306 SHeader.sh_entsize = 0;
307 SHeader.sh_size = S->Size;
308 // SHT_NOBITS section does not have content
309 // so just to setup the section offset.
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000310 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
George Rimar0e7ed912019-02-09 11:34:28 +0000311 } else if (auto S = dyn_cast<ELFYAML::DynamicSection>(Sec.get())) {
312 writeSectionContent(SHeader, *S, CBA);
George Rimar646af082019-02-19 15:29:07 +0000313 } else if (auto S = dyn_cast<ELFYAML::SymverSection>(Sec.get())) {
314 writeSectionContent(SHeader, *S, CBA);
George Rimar0621b792019-02-19 14:53:48 +0000315 } else if (auto S = dyn_cast<ELFYAML::VerneedSection>(Sec.get())) {
316 writeSectionContent(SHeader, *S, CBA);
George Rimar623ae722019-02-21 12:21:43 +0000317 } else if (auto S = dyn_cast<ELFYAML::VerdefSection>(Sec.get())) {
318 writeSectionContent(SHeader, *S, CBA);
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000319 } else
320 llvm_unreachable("Unknown section type");
321
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000322 SHeaders.push_back(SHeader);
323 }
324 return true;
325}
326
327template <class ELFT>
328void ELFState<ELFT>::initSymtabSectionHeader(Elf_Shdr &SHeader,
Dave Lee67b49662017-11-16 18:10:15 +0000329 SymtabType STType,
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000330 ContiguousBlobAccumulator &CBA) {
331 zero(SHeader);
Dave Lee67b49662017-11-16 18:10:15 +0000332 bool IsStatic = STType == SymtabType::Static;
333 SHeader.sh_name = DotShStrtab.getOffset(IsStatic ? ".symtab" : ".dynsym");
334 SHeader.sh_type = IsStatic ? ELF::SHT_SYMTAB : ELF::SHT_DYNSYM;
335 SHeader.sh_link = IsStatic ? getDotStrTabSecNo() : getDotDynStrSecNo();
336 const auto &Symbols = IsStatic ? Doc.Symbols : Doc.DynamicSymbols;
337 auto &Strtab = IsStatic ? DotStrtab : DotDynstr;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000338 // One greater than symbol table index of the last local symbol.
Dave Lee67b49662017-11-16 18:10:15 +0000339 SHeader.sh_info = Symbols.Local.size() + 1;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000340 SHeader.sh_entsize = sizeof(Elf_Sym);
Simon Atanasyan3a120922015-07-09 18:23:02 +0000341 SHeader.sh_addralign = 8;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000342
George Rimar6947acd2019-02-19 12:15:04 +0000343 // If .dynsym section is explicitly described in the YAML
344 // then we want to use its section address.
345 if (!IsStatic) {
346 // Take section index and ignore the SHT_NULL section.
347 unsigned SecNdx = getDotDynSymSecNo() - 1;
348 if (SecNdx < Doc.Sections.size())
349 SHeader.sh_addr = Doc.Sections[SecNdx]->Address;
350 }
351
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000352 std::vector<Elf_Sym> Syms;
353 {
354 // Ensure STN_UNDEF is present
355 Elf_Sym Sym;
356 zero(Sym);
357 Syms.push_back(Sym);
358 }
Hans Wennborg59f0cba2014-04-30 19:38:09 +0000359
Dave Lee67b49662017-11-16 18:10:15 +0000360 addSymbols(Symbols.Local, Syms, ELF::STB_LOCAL, Strtab);
361 addSymbols(Symbols.Global, Syms, ELF::STB_GLOBAL, Strtab);
362 addSymbols(Symbols.Weak, Syms, ELF::STB_WEAK, Strtab);
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000363
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000364 writeArrayData(
365 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign),
366 makeArrayRef(Syms));
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000367 SHeader.sh_size = arrayDataSize(makeArrayRef(Syms));
368}
369
370template <class ELFT>
371void ELFState<ELFT>::initStrtabSectionHeader(Elf_Shdr &SHeader, StringRef Name,
372 StringTableBuilder &STB,
373 ContiguousBlobAccumulator &CBA) {
374 zero(SHeader);
Hans Wennborg59f0cba2014-04-30 19:38:09 +0000375 SHeader.sh_name = DotShStrtab.getOffset(Name);
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000376 SHeader.sh_type = ELF::SHT_STRTAB;
Rafael Espindola39751af2016-10-04 22:43:25 +0000377 STB.write(CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign));
378 SHeader.sh_size = STB.getSize();
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000379 SHeader.sh_addralign = 1;
George Rimar6947acd2019-02-19 12:15:04 +0000380
381 // If .dynstr section is explicitly described in the YAML
382 // then we want to use its section address.
383 if (Name == ".dynstr") {
384 // Take section index and ignore the SHT_NULL section.
385 unsigned SecNdx = getDotDynStrSecNo() - 1;
386 if (SecNdx < Doc.Sections.size())
387 SHeader.sh_addr = Doc.Sections[SecNdx]->Address;
388 }
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000389}
390
391template <class ELFT>
Petr Hosekeb04da32017-07-19 20:38:46 +0000392void ELFState<ELFT>::setProgramHeaderLayout(std::vector<Elf_Phdr> &PHeaders,
393 std::vector<Elf_Shdr> &SHeaders) {
394 uint32_t PhdrIdx = 0;
395 for (auto &YamlPhdr : Doc.ProgramHeaders) {
396 auto &PHeader = PHeaders[PhdrIdx++];
397
398 if (YamlPhdr.Sections.size())
399 PHeader.p_offset = UINT32_MAX;
400 else
401 PHeader.p_offset = 0;
402
403 // Find the minimum offset for the program header.
404 for (auto SecName : YamlPhdr.Sections) {
405 uint32_t Index = 0;
406 SN2I.lookup(SecName.Section, Index);
407 const auto &SHeader = SHeaders[Index];
408 PHeader.p_offset = std::min(PHeader.p_offset, SHeader.sh_offset);
409 }
410
411 // Find the maximum offset of the end of a section in order to set p_filesz.
412 PHeader.p_filesz = 0;
413 for (auto SecName : YamlPhdr.Sections) {
414 uint32_t Index = 0;
415 SN2I.lookup(SecName.Section, Index);
416 const auto &SHeader = SHeaders[Index];
417 uint64_t EndOfSection;
418 if (SHeader.sh_type == llvm::ELF::SHT_NOBITS)
419 EndOfSection = SHeader.sh_offset;
420 else
421 EndOfSection = SHeader.sh_offset + SHeader.sh_size;
422 uint64_t EndOfSegment = PHeader.p_offset + PHeader.p_filesz;
423 EndOfSegment = std::max(EndOfSegment, EndOfSection);
424 PHeader.p_filesz = EndOfSegment - PHeader.p_offset;
425 }
426
427 // Find the memory size by adding the size of sections at the end of the
428 // segment. These should be empty (size of zero) and NOBITS sections.
429 PHeader.p_memsz = PHeader.p_filesz;
430 for (auto SecName : YamlPhdr.Sections) {
431 uint32_t Index = 0;
432 SN2I.lookup(SecName.Section, Index);
433 const auto &SHeader = SHeaders[Index];
434 if (SHeader.sh_offset == PHeader.p_offset + PHeader.p_filesz)
435 PHeader.p_memsz += SHeader.sh_size;
436 }
437
438 // Set the alignment of the segment to be the same as the maximum alignment
Jake Ehrlich03aeeb092017-11-01 23:14:48 +0000439 // of the sections with the same offset so that by default the segment
Petr Hosekeb04da32017-07-19 20:38:46 +0000440 // has a valid and sensible alignment.
Jake Ehrlich03aeeb092017-11-01 23:14:48 +0000441 if (YamlPhdr.Align) {
442 PHeader.p_align = *YamlPhdr.Align;
443 } else {
444 PHeader.p_align = 1;
445 for (auto SecName : YamlPhdr.Sections) {
446 uint32_t Index = 0;
447 SN2I.lookup(SecName.Section, Index);
448 const auto &SHeader = SHeaders[Index];
449 if (SHeader.sh_offset == PHeader.p_offset)
450 PHeader.p_align = std::max(PHeader.p_align, SHeader.sh_addralign);
451 }
Petr Hosekeb04da32017-07-19 20:38:46 +0000452 }
453 }
454}
455
456template <class ELFT>
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000457void ELFState<ELFT>::addSymbols(const std::vector<ELFYAML::Symbol> &Symbols,
458 std::vector<Elf_Sym> &Syms,
Dave Lee67b49662017-11-16 18:10:15 +0000459 unsigned SymbolBinding,
460 const StringTableBuilder &Strtab) {
Simon Atanasyan048baca2014-03-14 06:53:30 +0000461 for (const auto &Sym : Symbols) {
Sean Silva6b083882013-06-18 23:14:03 +0000462 Elf_Sym Symbol;
463 zero(Symbol);
464 if (!Sym.Name.empty())
Dave Lee67b49662017-11-16 18:10:15 +0000465 Symbol.st_name = Strtab.getOffset(Sym.Name);
Sean Silvaaff51252013-06-21 00:27:50 +0000466 Symbol.setBindingAndType(SymbolBinding, Sym.Type);
Sean Silvac4afa6d2013-06-21 01:11:48 +0000467 if (!Sym.Section.empty()) {
468 unsigned Index;
Simon Atanasyan35babf92014-04-06 09:02:55 +0000469 if (SN2I.lookup(Sym.Section, Index)) {
Jonas Devlieghere2cd41eb2018-04-21 21:11:59 +0000470 WithColor::error() << "Unknown section referenced: '" << Sym.Section
471 << "' by YAML symbol " << Sym.Name << ".\n";
Sean Silvac4afa6d2013-06-21 01:11:48 +0000472 exit(1);
473 }
474 Symbol.st_shndx = Index;
Petr Hosek5c469a32017-09-07 20:44:16 +0000475 } else if (Sym.Index) {
476 Symbol.st_shndx = *Sym.Index;
477 }
478 // else Symbol.st_shndex == SHN_UNDEF (== 0), since it was zero'd earlier.
Sean Silva05001b92013-06-20 20:59:47 +0000479 Symbol.st_value = Sym.Value;
Simon Atanasyan60e1a792014-11-06 22:46:24 +0000480 Symbol.st_other = Sym.Other;
Sean Silva05001b92013-06-20 20:59:47 +0000481 Symbol.st_size = Sym.Size;
Sean Silva6b083882013-06-18 23:14:03 +0000482 Syms.push_back(Symbol);
483 }
Sean Silvaaff51252013-06-21 00:27:50 +0000484}
485
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000486template <class ELFT>
487void
488ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
489 const ELFYAML::RawContentSection &Section,
490 ContiguousBlobAccumulator &CBA) {
Simon Atanasyanb83f3802014-05-16 16:01:00 +0000491 assert(Section.Size >= Section.Content.binary_size() &&
492 "Section size and section content are inconsistent");
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000493 raw_ostream &OS =
494 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
Simon Atanasyanb83f3802014-05-16 16:01:00 +0000495 Section.Content.writeAsBinary(OS);
496 for (auto i = Section.Content.binary_size(); i < Section.Size; ++i)
497 OS.write(0);
George Rimar65a68282018-08-07 08:11:38 +0000498 if (Section.EntSize)
499 SHeader.sh_entsize = *Section.EntSize;
500 else if (Section.Type == llvm::ELF::SHT_RELR)
Jake Ehrlich0f440d82018-06-28 21:07:34 +0000501 SHeader.sh_entsize = sizeof(Elf_Relr);
502 else
503 SHeader.sh_entsize = 0;
Simon Atanasyanb83f3802014-05-16 16:01:00 +0000504 SHeader.sh_size = Section.Size;
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000505}
506
Simon Atanasyan5d19c672015-01-25 13:29:25 +0000507static bool isMips64EL(const ELFYAML::Object &Doc) {
508 return Doc.Header.Machine == ELFYAML::ELF_EM(llvm::ELF::EM_MIPS) &&
509 Doc.Header.Class == ELFYAML::ELF_ELFCLASS(ELF::ELFCLASS64) &&
510 Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB);
511}
512
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000513template <class ELFT>
514bool
515ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
516 const ELFYAML::RelocationSection &Section,
517 ContiguousBlobAccumulator &CBA) {
Simon Atanasyan8eb9d1b2015-05-08 07:05:04 +0000518 assert((Section.Type == llvm::ELF::SHT_REL ||
519 Section.Type == llvm::ELF::SHT_RELA) &&
520 "Section type is not SHT_REL nor SHT_RELA");
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000521
522 bool IsRela = Section.Type == llvm::ELF::SHT_RELA;
523 SHeader.sh_entsize = IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
524 SHeader.sh_size = SHeader.sh_entsize * Section.Relocations.size();
525
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000526 auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000527
528 for (const auto &Rel : Section.Relocations) {
Adhemerval Zanella9f3dbff2015-04-22 15:26:43 +0000529 unsigned SymIdx = 0;
530 // Some special relocation, R_ARM_v4BX for instance, does not have
531 // an external reference. So it ignores the return value of lookup()
532 // here.
Petr Hosek5aa80f12017-08-30 23:13:31 +0000533 if (Rel.Symbol)
534 SymN2I.lookup(*Rel.Symbol, SymIdx);
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000535
536 if (IsRela) {
537 Elf_Rela REntry;
538 zero(REntry);
539 REntry.r_offset = Rel.Offset;
540 REntry.r_addend = Rel.Addend;
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 } else {
544 Elf_Rel REntry;
545 zero(REntry);
546 REntry.r_offset = Rel.Offset;
Simon Atanasyan5d19c672015-01-25 13:29:25 +0000547 REntry.setSymbolAndType(SymIdx, Rel.Type, isMips64EL(Doc));
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000548 OS.write((const char *)&REntry, sizeof(REntry));
549 }
550 }
551 return true;
552}
553
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000554template <class ELFT>
555bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
556 const ELFYAML::Group &Section,
557 ContiguousBlobAccumulator &CBA) {
Simon Atanasyan8eb9d1b2015-05-08 07:05:04 +0000558 assert(Section.Type == llvm::ELF::SHT_GROUP &&
559 "Section type is not SHT_GROUP");
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000560
George Rimard063c7d2019-02-20 13:58:43 +0000561 SHeader.sh_entsize = 4;
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000562 SHeader.sh_size = SHeader.sh_entsize * Section.Members.size();
563
George Rimard063c7d2019-02-20 13:58:43 +0000564 raw_ostream &OS =
565 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000566
567 for (auto member : Section.Members) {
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000568 unsigned int sectionIndex = 0;
569 if (member.sectionNameOrType == "GRP_COMDAT")
570 sectionIndex = llvm::ELF::GRP_COMDAT;
Xing GUO98228352018-12-04 14:27:51 +0000571 else if (!convertSectionIndex(SN2I, Section.Name, member.sectionNameOrType,
572 sectionIndex))
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000573 return false;
George Rimard063c7d2019-02-20 13:58:43 +0000574 support::endian::write<uint32_t>(OS, sectionIndex, ELFT::TargetEndianness);
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000575 }
576 return true;
577}
578
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000579template <class ELFT>
580bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
George Rimar646af082019-02-19 15:29:07 +0000581 const ELFYAML::SymverSection &Section,
582 ContiguousBlobAccumulator &CBA) {
George Rimar646af082019-02-19 15:29:07 +0000583 raw_ostream &OS =
584 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
George Rimardac37fb2019-02-20 14:01:02 +0000585 for (uint16_t Version : Section.Entries)
586 support::endian::write<uint16_t>(OS, Version, ELFT::TargetEndianness);
George Rimar646af082019-02-19 15:29:07 +0000587
George Rimard063c7d2019-02-20 13:58:43 +0000588 SHeader.sh_entsize = 2;
589 SHeader.sh_size = Section.Entries.size() * SHeader.sh_entsize;
George Rimar646af082019-02-19 15:29:07 +0000590 return true;
591}
592
593template <class ELFT>
594bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
George Rimar623ae722019-02-21 12:21:43 +0000595 const ELFYAML::VerdefSection &Section,
596 ContiguousBlobAccumulator &CBA) {
597 typedef typename ELFT::Verdef Elf_Verdef;
598 typedef typename ELFT::Verdaux Elf_Verdaux;
599 raw_ostream &OS =
600 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
601
602 uint64_t AuxCnt = 0;
603 for (size_t I = 0; I < Section.Entries.size(); ++I) {
604 const ELFYAML::VerdefEntry &E = Section.Entries[I];
605
606 Elf_Verdef VerDef;
607 VerDef.vd_version = E.Version;
608 VerDef.vd_flags = E.Flags;
609 VerDef.vd_ndx = E.VersionNdx;
610 VerDef.vd_hash = E.Hash;
611 VerDef.vd_aux = sizeof(Elf_Verdef);
612 VerDef.vd_cnt = E.VerNames.size();
613 if (I == Section.Entries.size() - 1)
614 VerDef.vd_next = 0;
615 else
616 VerDef.vd_next =
617 sizeof(Elf_Verdef) + E.VerNames.size() * sizeof(Elf_Verdaux);
618 OS.write((const char *)&VerDef, sizeof(Elf_Verdef));
619
620 for (size_t J = 0; J < E.VerNames.size(); ++J, ++AuxCnt) {
621 Elf_Verdaux VernAux;
622 VernAux.vda_name = DotDynstr.getOffset(E.VerNames[J]);
623 if (J == E.VerNames.size() - 1)
624 VernAux.vda_next = 0;
625 else
626 VernAux.vda_next = sizeof(Elf_Verdaux);
627 OS.write((const char *)&VernAux, sizeof(Elf_Verdaux));
628 }
629 }
630
631 SHeader.sh_size = Section.Entries.size() * sizeof(Elf_Verdef) +
632 AuxCnt * sizeof(Elf_Verdaux);
633 SHeader.sh_info = Section.Info;
634
635 return true;
636}
637
638template <class ELFT>
639bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
George Rimar0621b792019-02-19 14:53:48 +0000640 const ELFYAML::VerneedSection &Section,
641 ContiguousBlobAccumulator &CBA) {
642 typedef typename ELFT::Verneed Elf_Verneed;
643 typedef typename ELFT::Vernaux Elf_Vernaux;
644
645 auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
646
647 uint64_t AuxCnt = 0;
648 for (size_t I = 0; I < Section.VerneedV.size(); ++I) {
649 const ELFYAML::VerneedEntry &VE = Section.VerneedV[I];
650
651 Elf_Verneed VerNeed;
652 VerNeed.vn_version = VE.Version;
653 VerNeed.vn_file = DotDynstr.getOffset(VE.File);
654 if (I == Section.VerneedV.size() - 1)
655 VerNeed.vn_next = 0;
656 else
657 VerNeed.vn_next =
658 sizeof(Elf_Verneed) + VE.AuxV.size() * sizeof(Elf_Vernaux);
659 VerNeed.vn_cnt = VE.AuxV.size();
660 VerNeed.vn_aux = sizeof(Elf_Verneed);
661 OS.write((const char *)&VerNeed, sizeof(Elf_Verneed));
662
663 for (size_t J = 0; J < VE.AuxV.size(); ++J, ++AuxCnt) {
664 const ELFYAML::VernauxEntry &VAuxE = VE.AuxV[J];
665
666 Elf_Vernaux VernAux;
667 VernAux.vna_hash = VAuxE.Hash;
668 VernAux.vna_flags = VAuxE.Flags;
669 VernAux.vna_other = VAuxE.Other;
670 VernAux.vna_name = DotDynstr.getOffset(VAuxE.Name);
671 if (J == VE.AuxV.size() - 1)
672 VernAux.vna_next = 0;
673 else
674 VernAux.vna_next = sizeof(Elf_Vernaux);
675 OS.write((const char *)&VernAux, sizeof(Elf_Vernaux));
676 }
677 }
678
679 SHeader.sh_size = Section.VerneedV.size() * sizeof(Elf_Verneed) +
680 AuxCnt * sizeof(Elf_Vernaux);
681 SHeader.sh_info = Section.Info;
682
683 return true;
684}
685
686template <class ELFT>
687bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000688 const ELFYAML::MipsABIFlags &Section,
689 ContiguousBlobAccumulator &CBA) {
Simon Atanasyan8eb9d1b2015-05-08 07:05:04 +0000690 assert(Section.Type == llvm::ELF::SHT_MIPS_ABIFLAGS &&
691 "Section type is not SHT_MIPS_ABIFLAGS");
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000692
693 object::Elf_Mips_ABIFlags<ELFT> Flags;
694 zero(Flags);
695 SHeader.sh_entsize = sizeof(Flags);
696 SHeader.sh_size = SHeader.sh_entsize;
697
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000698 auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000699 Flags.version = Section.Version;
700 Flags.isa_level = Section.ISALevel;
701 Flags.isa_rev = Section.ISARevision;
702 Flags.gpr_size = Section.GPRSize;
703 Flags.cpr1_size = Section.CPR1Size;
704 Flags.cpr2_size = Section.CPR2Size;
705 Flags.fp_abi = Section.FpABI;
706 Flags.isa_ext = Section.ISAExtension;
707 Flags.ases = Section.ASEs;
708 Flags.flags1 = Section.Flags1;
709 Flags.flags2 = Section.Flags2;
710 OS.write((const char *)&Flags, sizeof(Flags));
711
712 return true;
713}
714
George Rimar0e7ed912019-02-09 11:34:28 +0000715template <class ELFT>
716void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
717 const ELFYAML::DynamicSection &Section,
718 ContiguousBlobAccumulator &CBA) {
George Rimard063c7d2019-02-20 13:58:43 +0000719 typedef typename ELFT::uint uintX_t;
720
George Rimar0e7ed912019-02-09 11:34:28 +0000721 assert(Section.Type == llvm::ELF::SHT_DYNAMIC &&
722 "Section type is not SHT_DYNAMIC");
723
George Rimard063c7d2019-02-20 13:58:43 +0000724 SHeader.sh_size = 2 * sizeof(uintX_t) * Section.Entries.size();
George Rimar0e7ed912019-02-09 11:34:28 +0000725 if (Section.EntSize)
726 SHeader.sh_entsize = *Section.EntSize;
727 else
728 SHeader.sh_entsize = sizeof(Elf_Dyn);
729
George Rimard063c7d2019-02-20 13:58:43 +0000730 raw_ostream &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
George Rimar0e7ed912019-02-09 11:34:28 +0000731 for (const ELFYAML::DynamicEntry &DE : Section.Entries) {
George Rimard063c7d2019-02-20 13:58:43 +0000732 support::endian::write<uintX_t>(OS, DE.Tag, ELFT::TargetEndianness);
733 support::endian::write<uintX_t>(OS, DE.Val, ELFT::TargetEndianness);
George Rimar0e7ed912019-02-09 11:34:28 +0000734 }
735}
736
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000737template <class ELFT> bool ELFState<ELFT>::buildSectionIndex() {
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000738 for (unsigned i = 0, e = Doc.Sections.size(); i != e; ++i) {
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000739 StringRef Name = Doc.Sections[i]->Name;
Dave Lee17307d92017-11-09 14:53:43 +0000740 DotShStrtab.add(Name);
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000741 // "+ 1" to take into account the SHT_NULL entry.
742 if (SN2I.addName(Name, i + 1)) {
Jonas Devlieghere2cd41eb2018-04-21 21:11:59 +0000743 WithColor::error() << "Repeated section name: '" << Name
744 << "' at YAML section number " << i << ".\n";
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000745 return false;
746 }
Sean Silvaaff51252013-06-21 00:27:50 +0000747 }
Dave Lee17307d92017-11-09 14:53:43 +0000748
749 auto SecNo = 1 + Doc.Sections.size();
750 // Add special sections after input sections, if necessary.
Dave Lee67b49662017-11-16 18:10:15 +0000751 for (const auto &Name : implicitSectionNames())
Dave Lee17307d92017-11-09 14:53:43 +0000752 if (!SN2I.addName(Name, SecNo)) {
753 // Account for this section, since it wasn't in the Doc
754 ++SecNo;
755 DotShStrtab.add(Name);
756 }
757
758 DotShStrtab.finalize();
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000759 return true;
Sean Silva6b083882013-06-18 23:14:03 +0000760}
761
Sean Silvaf99309c2013-06-10 23:44:15 +0000762template <class ELFT>
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000763bool
764ELFState<ELFT>::buildSymbolIndex(std::size_t &StartIndex,
765 const std::vector<ELFYAML::Symbol> &Symbols) {
766 for (const auto &Sym : Symbols) {
767 ++StartIndex;
768 if (Sym.Name.empty())
769 continue;
770 if (SymN2I.addName(Sym.Name, StartIndex)) {
Jonas Devlieghere2cd41eb2018-04-21 21:11:59 +0000771 WithColor::error() << "Repeated symbol name: '" << Sym.Name << "'.\n";
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000772 return false;
773 }
774 }
775 return true;
776}
777
George Rimar0621b792019-02-19 14:53:48 +0000778template <class ELFT> void ELFState<ELFT>::finalizeStrings() {
779 auto AddSymbols = [](StringTableBuilder &StrTab,
780 const ELFYAML::LocalGlobalWeakSymbols &Symbols) {
781 for (const auto &Sym : Symbols.Local)
782 StrTab.add(Sym.Name);
783 for (const auto &Sym : Symbols.Global)
784 StrTab.add(Sym.Name);
785 for (const auto &Sym : Symbols.Weak)
786 StrTab.add(Sym.Name);
787 };
788
789 // Add the regular symbol names to .strtab section.
790 AddSymbols(DotStrtab, Doc.Symbols);
791 DotStrtab.finalize();
792
793 if (!hasDynamicSymbols())
794 return;
795
796 // Add the dynamic symbol names to .dynstr section.
797 AddSymbols(DotDynstr, Doc.DynamicSymbols);
798
George Rimar623ae722019-02-21 12:21:43 +0000799 // SHT_GNU_verdef and SHT_GNU_verneed sections might also
800 // add strings to .dynstr section.
George Rimar0621b792019-02-19 14:53:48 +0000801 for (const std::unique_ptr<ELFYAML::Section> &Sec : Doc.Sections) {
George Rimar623ae722019-02-21 12:21:43 +0000802 if (auto VerNeed = dyn_cast<ELFYAML::VerneedSection>(Sec.get())) {
803 for (const ELFYAML::VerneedEntry &VE : VerNeed->VerneedV) {
804 DotDynstr.add(VE.File);
805 for (const ELFYAML::VernauxEntry &Aux : VE.AuxV)
806 DotDynstr.add(Aux.Name);
807 }
808 } else if (auto VerDef = dyn_cast<ELFYAML::VerdefSection>(Sec.get())) {
809 for (const ELFYAML::VerdefEntry &E : VerDef->Entries)
810 for (StringRef Name : E.VerNames)
811 DotDynstr.add(Name);
George Rimar0621b792019-02-19 14:53:48 +0000812 }
813 }
814
815 DotDynstr.finalize();
816}
817
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000818template <class ELFT>
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000819int ELFState<ELFT>::writeELF(raw_ostream &OS, const ELFYAML::Object &Doc) {
Simon Atanasyan220c54a2014-04-02 16:34:40 +0000820 ELFState<ELFT> State(Doc);
George Rimar0621b792019-02-19 14:53:48 +0000821
822 // Finalize .strtab and .dynstr sections. We do that early because want to
823 // finalize the string table builders before writing the content of the
824 // sections that might want to use them.
825 State.finalizeStrings();
826
Simon Atanasyan220c54a2014-04-02 16:34:40 +0000827 if (!State.buildSectionIndex())
828 return 1;
829
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000830 std::size_t StartSymIndex = 0;
831 if (!State.buildSymbolIndex(StartSymIndex, Doc.Symbols.Local) ||
832 !State.buildSymbolIndex(StartSymIndex, Doc.Symbols.Global) ||
833 !State.buildSymbolIndex(StartSymIndex, Doc.Symbols.Weak))
834 return 1;
835
Sean Silva38205932013-06-13 22:19:48 +0000836 Elf_Ehdr Header;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000837 State.initELFHeader(Header);
Sean Silvaf99309c2013-06-10 23:44:15 +0000838
Sean Silva38205932013-06-13 22:19:48 +0000839 // TODO: Flesh out section header support.
Petr Hosekeb04da32017-07-19 20:38:46 +0000840
841 std::vector<Elf_Phdr> PHeaders;
842 State.initProgramHeaders(PHeaders);
Sean Silva38205932013-06-13 22:19:48 +0000843
Sean Silva08a75ae2013-06-20 19:11:44 +0000844 // XXX: This offset is tightly coupled with the order that we write
845 // things to `OS`.
Petr Hosekeb04da32017-07-19 20:38:46 +0000846 const size_t SectionContentBeginOffset = Header.e_ehsize +
847 Header.e_phentsize * Header.e_phnum +
848 Header.e_shentsize * Header.e_shnum;
Sean Silva08a75ae2013-06-20 19:11:44 +0000849 ContiguousBlobAccumulator CBA(SectionContentBeginOffset);
Sean Silvac1c290b2013-06-20 20:59:34 +0000850
Sean Silva38205932013-06-13 22:19:48 +0000851 std::vector<Elf_Shdr> SHeaders;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000852 if(!State.initSectionHeaders(SHeaders, CBA))
853 return 1;
Sean Silva38205932013-06-13 22:19:48 +0000854
Dave Lee17307d92017-11-09 14:53:43 +0000855 // Populate SHeaders with implicit sections not present in the Doc
Dave Lee67b49662017-11-16 18:10:15 +0000856 for (const auto &Name : State.implicitSectionNames())
Dave Lee17307d92017-11-09 14:53:43 +0000857 if (State.SN2I.get(Name) >= SHeaders.size())
858 SHeaders.push_back({});
Sean Silva82177572013-06-22 01:38:00 +0000859
Dave Lee17307d92017-11-09 14:53:43 +0000860 // Initialize the implicit sections
861 auto Index = State.SN2I.get(".symtab");
Dave Lee67b49662017-11-16 18:10:15 +0000862 State.initSymtabSectionHeader(SHeaders[Index], SymtabType::Static, CBA);
Dave Lee17307d92017-11-09 14:53:43 +0000863 Index = State.SN2I.get(".strtab");
864 State.initStrtabSectionHeader(SHeaders[Index], ".strtab", State.DotStrtab, CBA);
865 Index = State.SN2I.get(".shstrtab");
866 State.initStrtabSectionHeader(SHeaders[Index], ".shstrtab", State.DotShStrtab, CBA);
Dave Lee67b49662017-11-16 18:10:15 +0000867 if (State.hasDynamicSymbols()) {
868 Index = State.SN2I.get(".dynsym");
869 State.initSymtabSectionHeader(SHeaders[Index], SymtabType::Dynamic, CBA);
870 SHeaders[Index].sh_flags |= ELF::SHF_ALLOC;
871 Index = State.SN2I.get(".dynstr");
872 State.initStrtabSectionHeader(SHeaders[Index], ".dynstr", State.DotDynstr, CBA);
873 SHeaders[Index].sh_flags |= ELF::SHF_ALLOC;
874 }
Sean Silvaf99309c2013-06-10 23:44:15 +0000875
Petr Hosekeb04da32017-07-19 20:38:46 +0000876 // Now we can decide segment offsets
877 State.setProgramHeaderLayout(PHeaders, SHeaders);
878
Sean Silvaf99309c2013-06-10 23:44:15 +0000879 OS.write((const char *)&Header, sizeof(Header));
Petr Hosekeb04da32017-07-19 20:38:46 +0000880 writeArrayData(OS, makeArrayRef(PHeaders));
Will Dietz0b48c732013-10-12 21:29:16 +0000881 writeArrayData(OS, makeArrayRef(SHeaders));
Sean Silva46dffff2013-06-13 22:20:01 +0000882 CBA.writeBlobToStream(OS);
Sean Silva415d93f2013-06-17 20:14:59 +0000883 return 0;
Sean Silvaf99309c2013-06-10 23:44:15 +0000884}
885
Dave Lee67b49662017-11-16 18:10:15 +0000886template <class ELFT> bool ELFState<ELFT>::hasDynamicSymbols() const {
887 return Doc.DynamicSymbols.Global.size() > 0 ||
888 Doc.DynamicSymbols.Weak.size() > 0 ||
889 Doc.DynamicSymbols.Local.size() > 0;
890}
891
Xing GUObac78642018-12-07 11:04:22 +0000892template <class ELFT>
893SmallVector<const char *, 5> ELFState<ELFT>::implicitSectionNames() const {
Dave Lee67b49662017-11-16 18:10:15 +0000894 if (!hasDynamicSymbols())
895 return {".symtab", ".strtab", ".shstrtab"};
896 return {".symtab", ".strtab", ".shstrtab", ".dynsym", ".dynstr"};
897}
898
Sean Silva11caeba2013-06-22 01:03:35 +0000899static bool is64Bit(const ELFYAML::Object &Doc) {
900 return Doc.Header.Class == ELFYAML::ELF_ELFCLASS(ELF::ELFCLASS64);
901}
902
903static bool isLittleEndian(const ELFYAML::Object &Doc) {
904 return Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB);
905}
906
Chris Bieneman8ff0c112016-06-27 19:53:53 +0000907int yaml2elf(llvm::ELFYAML::Object &Doc, raw_ostream &Out) {
Sean Silva11caeba2013-06-22 01:03:35 +0000908 if (is64Bit(Doc)) {
909 if (isLittleEndian(Doc))
Rui Ueyama1b31eb92018-01-12 01:40:32 +0000910 return ELFState<object::ELF64LE>::writeELF(Out, Doc);
Sean Silvaf99309c2013-06-10 23:44:15 +0000911 else
Rui Ueyama1b31eb92018-01-12 01:40:32 +0000912 return ELFState<object::ELF64BE>::writeELF(Out, Doc);
Sean Silvaf99309c2013-06-10 23:44:15 +0000913 } else {
Sean Silva11caeba2013-06-22 01:03:35 +0000914 if (isLittleEndian(Doc))
Rui Ueyama1b31eb92018-01-12 01:40:32 +0000915 return ELFState<object::ELF32LE>::writeELF(Out, Doc);
Sean Silvaf99309c2013-06-10 23:44:15 +0000916 else
Rui Ueyama1b31eb92018-01-12 01:40:32 +0000917 return ELFState<object::ELF32BE>::writeELF(Out, Doc);
Sean Silvaf99309c2013-06-10 23:44:15 +0000918 }
Sean Silvaf99309c2013-06-10 23:44:15 +0000919}