blob: cb12cdd5385df4925cbf1df1c30623d37e754ee8 [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);
George Rimarbd8bfd32019-04-29 12:05:53 +000043 OS.write_zeros(AlignedOffset - CurrentOffset);
Sean Silvad93323f2013-06-22 00:47:43 +000044 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();
George Rimar6da44ad2019-04-03 14:53:42 +0000135 bool buildSymbolIndex(ArrayRef<ELFYAML::Symbol> Symbols);
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000136 void initELFHeader(Elf_Ehdr &Header);
Petr Hosekeb04da32017-07-19 20:38:46 +0000137 void initProgramHeaders(std::vector<Elf_Phdr> &PHeaders);
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000138 bool initSectionHeaders(std::vector<Elf_Shdr> &SHeaders,
139 ContiguousBlobAccumulator &CBA);
Dave Lee67b49662017-11-16 18:10:15 +0000140 void initSymtabSectionHeader(Elf_Shdr &SHeader, SymtabType STType,
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000141 ContiguousBlobAccumulator &CBA);
142 void initStrtabSectionHeader(Elf_Shdr &SHeader, StringRef Name,
143 StringTableBuilder &STB,
144 ContiguousBlobAccumulator &CBA);
Petr Hosekeb04da32017-07-19 20:38:46 +0000145 void setProgramHeaderLayout(std::vector<Elf_Phdr> &PHeaders,
146 std::vector<Elf_Shdr> &SHeaders);
George Rimar6da44ad2019-04-03 14:53:42 +0000147 void addSymbols(ArrayRef<ELFYAML::Symbol> Symbols, std::vector<Elf_Sym> &Syms,
Dave Lee67b49662017-11-16 18:10:15 +0000148 const StringTableBuilder &Strtab);
George Rimarda1b3ab2019-04-26 12:15:32 +0000149 bool writeSectionContent(Elf_Shdr &SHeader,
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000150 const ELFYAML::RawContentSection &Section,
151 ContiguousBlobAccumulator &CBA);
152 bool writeSectionContent(Elf_Shdr &SHeader,
153 const ELFYAML::RelocationSection &Section,
154 ContiguousBlobAccumulator &CBA);
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000155 bool writeSectionContent(Elf_Shdr &SHeader, const ELFYAML::Group &Group,
156 ContiguousBlobAccumulator &CBA);
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000157 bool writeSectionContent(Elf_Shdr &SHeader,
George Rimar646af082019-02-19 15:29:07 +0000158 const ELFYAML::SymverSection &Section,
159 ContiguousBlobAccumulator &CBA);
160 bool writeSectionContent(Elf_Shdr &SHeader,
George Rimar0621b792019-02-19 14:53:48 +0000161 const ELFYAML::VerneedSection &Section,
162 ContiguousBlobAccumulator &CBA);
163 bool writeSectionContent(Elf_Shdr &SHeader,
George Rimar623ae722019-02-21 12:21:43 +0000164 const ELFYAML::VerdefSection &Section,
165 ContiguousBlobAccumulator &CBA);
166 bool writeSectionContent(Elf_Shdr &SHeader,
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000167 const ELFYAML::MipsABIFlags &Section,
168 ContiguousBlobAccumulator &CBA);
James Hendersonfd997802019-02-25 11:02:24 +0000169 bool writeSectionContent(Elf_Shdr &SHeader,
George Rimar0e7ed912019-02-09 11:34:28 +0000170 const ELFYAML::DynamicSection &Section,
171 ContiguousBlobAccumulator &CBA);
George Rimar5fcdebe2019-04-26 13:09:11 +0000172 std::vector<StringRef> 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;
George Rimara5a0a0f2019-03-07 12:09:19 +0000206 Header.e_ident[EI_DATA] = Doc.Header.Data;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000207 Header.e_ident[EI_VERSION] = EV_CURRENT;
208 Header.e_ident[EI_OSABI] = Doc.Header.OSABI;
George Rimar6367d7a2018-12-20 10:43:49 +0000209 Header.e_ident[EI_ABIVERSION] = Doc.Header.ABIVersion;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000210 Header.e_type = Doc.Header.Type;
211 Header.e_machine = Doc.Header.Machine;
212 Header.e_version = EV_CURRENT;
213 Header.e_entry = Doc.Header.Entry;
Petr Hosekeb04da32017-07-19 20:38:46 +0000214 Header.e_phoff = sizeof(Header);
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000215 Header.e_flags = Doc.Header.Flags;
216 Header.e_ehsize = sizeof(Elf_Ehdr);
Petr Hosekeb04da32017-07-19 20:38:46 +0000217 Header.e_phentsize = sizeof(Elf_Phdr);
218 Header.e_phnum = Doc.ProgramHeaders.size();
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000219 Header.e_shentsize = sizeof(Elf_Shdr);
Petr Hosekeb04da32017-07-19 20:38:46 +0000220 // Immediately following the ELF header and program headers.
221 Header.e_shoff =
222 sizeof(Header) + sizeof(Elf_Phdr) * Doc.ProgramHeaders.size();
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000223 Header.e_shnum = getSectionCount();
224 Header.e_shstrndx = getDotShStrTabSecNo();
225}
226
227template <class ELFT>
Petr Hosekeb04da32017-07-19 20:38:46 +0000228void ELFState<ELFT>::initProgramHeaders(std::vector<Elf_Phdr> &PHeaders) {
229 for (const auto &YamlPhdr : Doc.ProgramHeaders) {
230 Elf_Phdr Phdr;
231 Phdr.p_type = YamlPhdr.Type;
232 Phdr.p_flags = YamlPhdr.Flags;
233 Phdr.p_vaddr = YamlPhdr.VAddr;
234 Phdr.p_paddr = YamlPhdr.PAddr;
235 PHeaders.push_back(Phdr);
236 }
237}
238
Xing GUO98228352018-12-04 14:27:51 +0000239static bool convertSectionIndex(NameToIdxMap &SN2I, StringRef SecName,
240 StringRef IndexSrc, unsigned &IndexDest) {
241 if (SN2I.lookup(IndexSrc, IndexDest) && !to_integer(IndexSrc, IndexDest)) {
242 WithColor::error() << "Unknown section referenced: '" << IndexSrc
243 << "' at YAML section '" << SecName << "'.\n";
244 return false;
245 }
246 return true;
247}
248
Petr Hosekeb04da32017-07-19 20:38:46 +0000249template <class ELFT>
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000250bool ELFState<ELFT>::initSectionHeaders(std::vector<Elf_Shdr> &SHeaders,
251 ContiguousBlobAccumulator &CBA) {
252 // Ensure SHN_UNDEF entry is present. An all-zero section header is a
253 // valid SHN_UNDEF entry since SHT_NULL == 0.
254 Elf_Shdr SHeader;
255 zero(SHeader);
256 SHeaders.push_back(SHeader);
257
258 for (const auto &Sec : Doc.Sections) {
259 zero(SHeader);
Hans Wennborg59f0cba2014-04-30 19:38:09 +0000260 SHeader.sh_name = DotShStrtab.getOffset(Sec->Name);
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000261 SHeader.sh_type = Sec->Type;
262 SHeader.sh_flags = Sec->Flags;
263 SHeader.sh_addr = Sec->Address;
264 SHeader.sh_addralign = Sec->AddressAlign;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000265
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000266 if (!Sec->Link.empty()) {
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000267 unsigned Index;
Xing GUO98228352018-12-04 14:27:51 +0000268 if (!convertSectionIndex(SN2I, Sec->Name, Sec->Link, Index))
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000269 return false;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000270 SHeader.sh_link = Index;
271 }
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000272
George Rimarda1b3ab2019-04-26 12:15:32 +0000273 if (auto S = dyn_cast<ELFYAML::RawContentSection>(Sec.get())) {
274 if (!writeSectionContent(SHeader, *S, CBA))
George Rimar7f2df7d2018-08-16 12:23:22 +0000275 return false;
George Rimarda1b3ab2019-04-26 12:15:32 +0000276 } else if (auto S = dyn_cast<ELFYAML::RelocationSection>(Sec.get())) {
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000277 if (!writeSectionContent(SHeader, *S, CBA))
278 return false;
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000279 } else if (auto S = dyn_cast<ELFYAML::Group>(Sec.get())) {
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000280 if (!writeSectionContent(SHeader, *S, CBA))
281 return false;
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000282 } else if (auto S = dyn_cast<ELFYAML::MipsABIFlags>(Sec.get())) {
283 if (!writeSectionContent(SHeader, *S, CBA))
284 return false;
Simon Atanasyan5db02762015-07-03 23:00:54 +0000285 } else if (auto S = dyn_cast<ELFYAML::NoBitsSection>(Sec.get())) {
286 SHeader.sh_entsize = 0;
287 SHeader.sh_size = S->Size;
288 // SHT_NOBITS section does not have content
289 // so just to setup the section offset.
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000290 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
George Rimar0e7ed912019-02-09 11:34:28 +0000291 } else if (auto S = dyn_cast<ELFYAML::DynamicSection>(Sec.get())) {
James Hendersonfd997802019-02-25 11:02:24 +0000292 if (!writeSectionContent(SHeader, *S, CBA))
293 return false;
George Rimar646af082019-02-19 15:29:07 +0000294 } else if (auto S = dyn_cast<ELFYAML::SymverSection>(Sec.get())) {
George Rimarda1b3ab2019-04-26 12:15:32 +0000295 if (!writeSectionContent(SHeader, *S, CBA))
296 return false;
George Rimar0621b792019-02-19 14:53:48 +0000297 } else if (auto S = dyn_cast<ELFYAML::VerneedSection>(Sec.get())) {
George Rimarda1b3ab2019-04-26 12:15:32 +0000298 if (!writeSectionContent(SHeader, *S, CBA))
299 return false;
George Rimar623ae722019-02-21 12:21:43 +0000300 } else if (auto S = dyn_cast<ELFYAML::VerdefSection>(Sec.get())) {
George Rimarda1b3ab2019-04-26 12:15:32 +0000301 if (!writeSectionContent(SHeader, *S, CBA))
302 return false;
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000303 } else
304 llvm_unreachable("Unknown section type");
305
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000306 SHeaders.push_back(SHeader);
307 }
308 return true;
309}
310
George Rimar6da44ad2019-04-03 14:53:42 +0000311static size_t findFirstNonGlobal(ArrayRef<ELFYAML::Symbol> Symbols) {
312 for (size_t I = 0; I < Symbols.size(); ++I)
313 if (Symbols[I].Binding.value != ELF::STB_LOCAL)
314 return I;
315 return Symbols.size();
316}
317
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000318template <class ELFT>
319void ELFState<ELFT>::initSymtabSectionHeader(Elf_Shdr &SHeader,
Dave Lee67b49662017-11-16 18:10:15 +0000320 SymtabType STType,
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000321 ContiguousBlobAccumulator &CBA) {
322 zero(SHeader);
Dave Lee67b49662017-11-16 18:10:15 +0000323 bool IsStatic = STType == SymtabType::Static;
324 SHeader.sh_name = DotShStrtab.getOffset(IsStatic ? ".symtab" : ".dynsym");
325 SHeader.sh_type = IsStatic ? ELF::SHT_SYMTAB : ELF::SHT_DYNSYM;
326 SHeader.sh_link = IsStatic ? getDotStrTabSecNo() : getDotDynStrSecNo();
George Rimar48288112019-04-29 11:54:10 +0000327 if (!IsStatic)
328 SHeader.sh_flags |= ELF::SHF_ALLOC;
George Rimarc1da1492019-04-26 12:45:54 +0000329
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000330 // One greater than symbol table index of the last local symbol.
George Rimarc1da1492019-04-26 12:45:54 +0000331 const auto &Symbols = IsStatic ? Doc.Symbols : Doc.DynamicSymbols;
George Rimar6da44ad2019-04-03 14:53:42 +0000332 SHeader.sh_info = findFirstNonGlobal(Symbols) + 1;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000333 SHeader.sh_entsize = sizeof(Elf_Sym);
Simon Atanasyan3a120922015-07-09 18:23:02 +0000334 SHeader.sh_addralign = 8;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000335
George Rimara7ba1a02019-03-01 10:18:16 +0000336 // Get the section index ignoring the SHT_NULL section.
337 unsigned SecNdx =
338 IsStatic ? getDotSymTabSecNo() - 1 : getDotDynSymSecNo() - 1;
339 // If the symbol table section is explicitly described in the YAML
340 // then we should set the fields requested.
341 if (SecNdx < Doc.Sections.size()) {
342 ELFYAML::Section *Sec = Doc.Sections[SecNdx].get();
343 SHeader.sh_addr = Sec->Address;
344 if (auto S = dyn_cast<ELFYAML::RawContentSection>(Sec))
345 SHeader.sh_info = S->Info;
George Rimar6947acd2019-02-19 12:15:04 +0000346 }
347
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000348 std::vector<Elf_Sym> Syms;
349 {
350 // Ensure STN_UNDEF is present
351 Elf_Sym Sym;
352 zero(Sym);
353 Syms.push_back(Sym);
354 }
Hans Wennborg59f0cba2014-04-30 19:38:09 +0000355
George Rimarc1da1492019-04-26 12:45:54 +0000356 addSymbols(Symbols, Syms, IsStatic ? DotStrtab : DotDynstr);
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;
George Rimar48288112019-04-29 11:54:10 +0000382
383 // We assume that .dynstr is always allocatable.
384 SHeader.sh_flags |= ELF::SHF_ALLOC;
George Rimar6947acd2019-02-19 12:15:04 +0000385 }
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000386}
387
388template <class ELFT>
Petr Hosekeb04da32017-07-19 20:38:46 +0000389void ELFState<ELFT>::setProgramHeaderLayout(std::vector<Elf_Phdr> &PHeaders,
390 std::vector<Elf_Shdr> &SHeaders) {
391 uint32_t PhdrIdx = 0;
392 for (auto &YamlPhdr : Doc.ProgramHeaders) {
393 auto &PHeader = PHeaders[PhdrIdx++];
394
James Hendersonb10f48b2019-03-15 10:35:27 +0000395 if (YamlPhdr.Offset) {
396 PHeader.p_offset = *YamlPhdr.Offset;
397 } else {
398 if (YamlPhdr.Sections.size())
399 PHeader.p_offset = UINT32_MAX;
Petr Hosekeb04da32017-07-19 20:38:46 +0000400 else
James Hendersonb10f48b2019-03-15 10:35:27 +0000401 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 }
Petr Hosekeb04da32017-07-19 20:38:46 +0000410 }
411
James Hendersonb10f48b2019-03-15 10:35:27 +0000412 // Find the maximum offset of the end of a section in order to set p_filesz,
413 // if not set explicitly.
414 if (YamlPhdr.FileSize) {
415 PHeader.p_filesz = *YamlPhdr.FileSize;
416 } else {
417 PHeader.p_filesz = 0;
418 for (auto SecName : YamlPhdr.Sections) {
419 uint32_t Index = 0;
420 SN2I.lookup(SecName.Section, Index);
421 const auto &SHeader = SHeaders[Index];
422 uint64_t EndOfSection;
423 if (SHeader.sh_type == llvm::ELF::SHT_NOBITS)
424 EndOfSection = SHeader.sh_offset;
425 else
426 EndOfSection = SHeader.sh_offset + SHeader.sh_size;
427 uint64_t EndOfSegment = PHeader.p_offset + PHeader.p_filesz;
428 EndOfSegment = std::max(EndOfSegment, EndOfSection);
429 PHeader.p_filesz = EndOfSegment - PHeader.p_offset;
430 }
431 }
432
433 // If not set explicitly, find the memory size by adding the size of
434 // sections at the end of the segment. These should be empty (size of zero)
435 // and NOBITS sections.
436 if (YamlPhdr.MemSize) {
437 PHeader.p_memsz = *YamlPhdr.MemSize;
438 } else {
439 PHeader.p_memsz = PHeader.p_filesz;
440 for (auto SecName : YamlPhdr.Sections) {
441 uint32_t Index = 0;
442 SN2I.lookup(SecName.Section, Index);
443 const auto &SHeader = SHeaders[Index];
444 if (SHeader.sh_offset == PHeader.p_offset + PHeader.p_filesz)
445 PHeader.p_memsz += SHeader.sh_size;
446 }
Petr Hosekeb04da32017-07-19 20:38:46 +0000447 }
448
449 // Set the alignment of the segment to be the same as the maximum alignment
Jake Ehrlich03aeeb092017-11-01 23:14:48 +0000450 // of the sections with the same offset so that by default the segment
Petr Hosekeb04da32017-07-19 20:38:46 +0000451 // has a valid and sensible alignment.
Jake Ehrlich03aeeb092017-11-01 23:14:48 +0000452 if (YamlPhdr.Align) {
453 PHeader.p_align = *YamlPhdr.Align;
454 } else {
455 PHeader.p_align = 1;
456 for (auto SecName : YamlPhdr.Sections) {
457 uint32_t Index = 0;
458 SN2I.lookup(SecName.Section, Index);
459 const auto &SHeader = SHeaders[Index];
460 if (SHeader.sh_offset == PHeader.p_offset)
461 PHeader.p_align = std::max(PHeader.p_align, SHeader.sh_addralign);
462 }
Petr Hosekeb04da32017-07-19 20:38:46 +0000463 }
464 }
465}
466
467template <class ELFT>
George Rimar6da44ad2019-04-03 14:53:42 +0000468void ELFState<ELFT>::addSymbols(ArrayRef<ELFYAML::Symbol> Symbols,
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000469 std::vector<Elf_Sym> &Syms,
Dave Lee67b49662017-11-16 18:10:15 +0000470 const StringTableBuilder &Strtab) {
Simon Atanasyan048baca2014-03-14 06:53:30 +0000471 for (const auto &Sym : Symbols) {
Sean Silva6b083882013-06-18 23:14:03 +0000472 Elf_Sym Symbol;
473 zero(Symbol);
474 if (!Sym.Name.empty())
Dave Lee67b49662017-11-16 18:10:15 +0000475 Symbol.st_name = Strtab.getOffset(Sym.Name);
George Rimar6da44ad2019-04-03 14:53:42 +0000476 Symbol.setBindingAndType(Sym.Binding, Sym.Type);
Sean Silvac4afa6d2013-06-21 01:11:48 +0000477 if (!Sym.Section.empty()) {
478 unsigned Index;
Simon Atanasyan35babf92014-04-06 09:02:55 +0000479 if (SN2I.lookup(Sym.Section, Index)) {
Jonas Devlieghere2cd41eb2018-04-21 21:11:59 +0000480 WithColor::error() << "Unknown section referenced: '" << Sym.Section
481 << "' by YAML symbol " << Sym.Name << ".\n";
Sean Silvac4afa6d2013-06-21 01:11:48 +0000482 exit(1);
483 }
484 Symbol.st_shndx = Index;
Petr Hosek5c469a32017-09-07 20:44:16 +0000485 } else if (Sym.Index) {
486 Symbol.st_shndx = *Sym.Index;
487 }
488 // else Symbol.st_shndex == SHN_UNDEF (== 0), since it was zero'd earlier.
Sean Silva05001b92013-06-20 20:59:47 +0000489 Symbol.st_value = Sym.Value;
Simon Atanasyan60e1a792014-11-06 22:46:24 +0000490 Symbol.st_other = Sym.Other;
Sean Silva05001b92013-06-20 20:59:47 +0000491 Symbol.st_size = Sym.Size;
Sean Silva6b083882013-06-18 23:14:03 +0000492 Syms.push_back(Symbol);
493 }
Sean Silvaaff51252013-06-21 00:27:50 +0000494}
495
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000496template <class ELFT>
George Rimarda1b3ab2019-04-26 12:15:32 +0000497bool ELFState<ELFT>::writeSectionContent(
George Rimarb49e1922019-04-24 13:02:15 +0000498 Elf_Shdr &SHeader, const ELFYAML::RawContentSection &Section,
499 ContiguousBlobAccumulator &CBA) {
Simon Atanasyanb83f3802014-05-16 16:01:00 +0000500 assert(Section.Size >= Section.Content.binary_size() &&
501 "Section size and section content are inconsistent");
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000502 raw_ostream &OS =
503 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
Simon Atanasyanb83f3802014-05-16 16:01:00 +0000504 Section.Content.writeAsBinary(OS);
George Rimarb49e1922019-04-24 13:02:15 +0000505 OS.write_zeros(Section.Size - Section.Content.binary_size());
506
George Rimar65a68282018-08-07 08:11:38 +0000507 if (Section.EntSize)
508 SHeader.sh_entsize = *Section.EntSize;
509 else if (Section.Type == llvm::ELF::SHT_RELR)
Jake Ehrlich0f440d82018-06-28 21:07:34 +0000510 SHeader.sh_entsize = sizeof(Elf_Relr);
511 else
512 SHeader.sh_entsize = 0;
Simon Atanasyanb83f3802014-05-16 16:01:00 +0000513 SHeader.sh_size = Section.Size;
George Rimara7ba1a02019-03-01 10:18:16 +0000514 SHeader.sh_info = Section.Info;
George Rimarda1b3ab2019-04-26 12:15:32 +0000515 return true;
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000516}
517
Simon Atanasyan5d19c672015-01-25 13:29:25 +0000518static bool isMips64EL(const ELFYAML::Object &Doc) {
519 return Doc.Header.Machine == ELFYAML::ELF_EM(llvm::ELF::EM_MIPS) &&
520 Doc.Header.Class == ELFYAML::ELF_ELFCLASS(ELF::ELFCLASS64) &&
521 Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB);
522}
523
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000524template <class ELFT>
525bool
526ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
527 const ELFYAML::RelocationSection &Section,
528 ContiguousBlobAccumulator &CBA) {
Simon Atanasyan8eb9d1b2015-05-08 07:05:04 +0000529 assert((Section.Type == llvm::ELF::SHT_REL ||
530 Section.Type == llvm::ELF::SHT_RELA) &&
531 "Section type is not SHT_REL nor SHT_RELA");
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000532
533 bool IsRela = Section.Type == llvm::ELF::SHT_RELA;
534 SHeader.sh_entsize = IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
535 SHeader.sh_size = SHeader.sh_entsize * Section.Relocations.size();
536
George Rimarda1b3ab2019-04-26 12:15:32 +0000537 // For relocation section set link to .symtab by default.
538 if (Section.Link.empty())
539 SHeader.sh_link = getDotSymTabSecNo();
540
541 unsigned Index = 0;
542 if (!Section.RelocatableSec.empty() &&
543 !convertSectionIndex(SN2I, Section.Name, Section.RelocatableSec, Index))
544 return false;
545 SHeader.sh_info = Index;
546
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000547 auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000548
549 for (const auto &Rel : Section.Relocations) {
Adhemerval Zanella9f3dbff2015-04-22 15:26:43 +0000550 unsigned SymIdx = 0;
James Henderson9bc817a2019-03-12 17:00:25 +0000551 // If a relocation references a symbol, try to look one up in the symbol
552 // table. If it is not there, treat the value as a symbol index.
553 if (Rel.Symbol && SymN2I.lookup(*Rel.Symbol, SymIdx) &&
554 !to_integer(*Rel.Symbol, SymIdx)) {
555 WithColor::error() << "Unknown symbol referenced: '" << *Rel.Symbol
556 << "' at YAML section '" << Section.Name << "'.\n";
557 return false;
558 }
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000559
560 if (IsRela) {
561 Elf_Rela REntry;
562 zero(REntry);
563 REntry.r_offset = Rel.Offset;
564 REntry.r_addend = Rel.Addend;
Simon Atanasyan5d19c672015-01-25 13:29:25 +0000565 REntry.setSymbolAndType(SymIdx, Rel.Type, isMips64EL(Doc));
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000566 OS.write((const char *)&REntry, sizeof(REntry));
567 } else {
568 Elf_Rel REntry;
569 zero(REntry);
570 REntry.r_offset = Rel.Offset;
Simon Atanasyan5d19c672015-01-25 13:29:25 +0000571 REntry.setSymbolAndType(SymIdx, Rel.Type, isMips64EL(Doc));
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000572 OS.write((const char *)&REntry, sizeof(REntry));
573 }
574 }
575 return true;
576}
577
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000578template <class ELFT>
579bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
580 const ELFYAML::Group &Section,
581 ContiguousBlobAccumulator &CBA) {
Simon Atanasyan8eb9d1b2015-05-08 07:05:04 +0000582 assert(Section.Type == llvm::ELF::SHT_GROUP &&
583 "Section type is not SHT_GROUP");
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000584
George Rimard063c7d2019-02-20 13:58:43 +0000585 SHeader.sh_entsize = 4;
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000586 SHeader.sh_size = SHeader.sh_entsize * Section.Members.size();
587
George Rimarda1b3ab2019-04-26 12:15:32 +0000588 unsigned SymIdx;
589 if (SymN2I.lookup(Section.Signature, SymIdx) &&
590 !to_integer(Section.Signature, SymIdx)) {
591 WithColor::error() << "Unknown symbol referenced: '" << Section.Signature
592 << "' at YAML section '" << Section.Name << "'.\n";
593 return false;
594 }
595 SHeader.sh_info = SymIdx;
596
George Rimard063c7d2019-02-20 13:58:43 +0000597 raw_ostream &OS =
598 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000599
George Rimarfb7780a2019-04-26 12:20:51 +0000600 for (const ELFYAML::SectionOrType &Member : Section.Members) {
601 unsigned int SectionIndex = 0;
602 if (Member.sectionNameOrType == "GRP_COMDAT")
603 SectionIndex = llvm::ELF::GRP_COMDAT;
604 else if (!convertSectionIndex(SN2I, Section.Name, Member.sectionNameOrType,
605 SectionIndex))
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000606 return false;
George Rimarfb7780a2019-04-26 12:20:51 +0000607 support::endian::write<uint32_t>(OS, SectionIndex, ELFT::TargetEndianness);
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000608 }
609 return true;
610}
611
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000612template <class ELFT>
613bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
George Rimar646af082019-02-19 15:29:07 +0000614 const ELFYAML::SymverSection &Section,
615 ContiguousBlobAccumulator &CBA) {
George Rimar646af082019-02-19 15:29:07 +0000616 raw_ostream &OS =
617 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
George Rimardac37fb2019-02-20 14:01:02 +0000618 for (uint16_t Version : Section.Entries)
619 support::endian::write<uint16_t>(OS, Version, ELFT::TargetEndianness);
George Rimar646af082019-02-19 15:29:07 +0000620
George Rimard063c7d2019-02-20 13:58:43 +0000621 SHeader.sh_entsize = 2;
622 SHeader.sh_size = Section.Entries.size() * SHeader.sh_entsize;
George Rimar646af082019-02-19 15:29:07 +0000623 return true;
624}
625
626template <class ELFT>
627bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
George Rimar623ae722019-02-21 12:21:43 +0000628 const ELFYAML::VerdefSection &Section,
629 ContiguousBlobAccumulator &CBA) {
630 typedef typename ELFT::Verdef Elf_Verdef;
631 typedef typename ELFT::Verdaux Elf_Verdaux;
632 raw_ostream &OS =
633 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
634
635 uint64_t AuxCnt = 0;
636 for (size_t I = 0; I < Section.Entries.size(); ++I) {
637 const ELFYAML::VerdefEntry &E = Section.Entries[I];
638
639 Elf_Verdef VerDef;
640 VerDef.vd_version = E.Version;
641 VerDef.vd_flags = E.Flags;
642 VerDef.vd_ndx = E.VersionNdx;
643 VerDef.vd_hash = E.Hash;
644 VerDef.vd_aux = sizeof(Elf_Verdef);
645 VerDef.vd_cnt = E.VerNames.size();
646 if (I == Section.Entries.size() - 1)
647 VerDef.vd_next = 0;
648 else
649 VerDef.vd_next =
650 sizeof(Elf_Verdef) + E.VerNames.size() * sizeof(Elf_Verdaux);
651 OS.write((const char *)&VerDef, sizeof(Elf_Verdef));
652
653 for (size_t J = 0; J < E.VerNames.size(); ++J, ++AuxCnt) {
654 Elf_Verdaux VernAux;
655 VernAux.vda_name = DotDynstr.getOffset(E.VerNames[J]);
656 if (J == E.VerNames.size() - 1)
657 VernAux.vda_next = 0;
658 else
659 VernAux.vda_next = sizeof(Elf_Verdaux);
660 OS.write((const char *)&VernAux, sizeof(Elf_Verdaux));
661 }
662 }
663
664 SHeader.sh_size = Section.Entries.size() * sizeof(Elf_Verdef) +
665 AuxCnt * sizeof(Elf_Verdaux);
666 SHeader.sh_info = Section.Info;
667
668 return true;
669}
670
671template <class ELFT>
672bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
George Rimar0621b792019-02-19 14:53:48 +0000673 const ELFYAML::VerneedSection &Section,
674 ContiguousBlobAccumulator &CBA) {
George Rimarda1b3ab2019-04-26 12:15:32 +0000675 typedef typename ELFT::Verneed Elf_Verneed;
676 typedef typename ELFT::Vernaux Elf_Vernaux;
George Rimar0621b792019-02-19 14:53:48 +0000677
George Rimarda1b3ab2019-04-26 12:15:32 +0000678 auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
George Rimar0621b792019-02-19 14:53:48 +0000679
George Rimarda1b3ab2019-04-26 12:15:32 +0000680 uint64_t AuxCnt = 0;
681 for (size_t I = 0; I < Section.VerneedV.size(); ++I) {
682 const ELFYAML::VerneedEntry &VE = Section.VerneedV[I];
George Rimar0621b792019-02-19 14:53:48 +0000683
George Rimarda1b3ab2019-04-26 12:15:32 +0000684 Elf_Verneed VerNeed;
685 VerNeed.vn_version = VE.Version;
686 VerNeed.vn_file = DotDynstr.getOffset(VE.File);
687 if (I == Section.VerneedV.size() - 1)
688 VerNeed.vn_next = 0;
689 else
690 VerNeed.vn_next =
691 sizeof(Elf_Verneed) + VE.AuxV.size() * sizeof(Elf_Vernaux);
692 VerNeed.vn_cnt = VE.AuxV.size();
693 VerNeed.vn_aux = sizeof(Elf_Verneed);
694 OS.write((const char *)&VerNeed, sizeof(Elf_Verneed));
George Rimar0621b792019-02-19 14:53:48 +0000695
George Rimarda1b3ab2019-04-26 12:15:32 +0000696 for (size_t J = 0; J < VE.AuxV.size(); ++J, ++AuxCnt) {
697 const ELFYAML::VernauxEntry &VAuxE = VE.AuxV[J];
George Rimar0621b792019-02-19 14:53:48 +0000698
George Rimarda1b3ab2019-04-26 12:15:32 +0000699 Elf_Vernaux VernAux;
700 VernAux.vna_hash = VAuxE.Hash;
701 VernAux.vna_flags = VAuxE.Flags;
702 VernAux.vna_other = VAuxE.Other;
703 VernAux.vna_name = DotDynstr.getOffset(VAuxE.Name);
704 if (J == VE.AuxV.size() - 1)
705 VernAux.vna_next = 0;
706 else
707 VernAux.vna_next = sizeof(Elf_Vernaux);
708 OS.write((const char *)&VernAux, sizeof(Elf_Vernaux));
709 }
710 }
George Rimar0621b792019-02-19 14:53:48 +0000711
George Rimarda1b3ab2019-04-26 12:15:32 +0000712 SHeader.sh_size = Section.VerneedV.size() * sizeof(Elf_Verneed) +
713 AuxCnt * sizeof(Elf_Vernaux);
714 SHeader.sh_info = Section.Info;
George Rimar0621b792019-02-19 14:53:48 +0000715
George Rimarda1b3ab2019-04-26 12:15:32 +0000716 return true;
George Rimar0621b792019-02-19 14:53:48 +0000717}
718
719template <class ELFT>
720bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000721 const ELFYAML::MipsABIFlags &Section,
722 ContiguousBlobAccumulator &CBA) {
Simon Atanasyan8eb9d1b2015-05-08 07:05:04 +0000723 assert(Section.Type == llvm::ELF::SHT_MIPS_ABIFLAGS &&
724 "Section type is not SHT_MIPS_ABIFLAGS");
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000725
726 object::Elf_Mips_ABIFlags<ELFT> Flags;
727 zero(Flags);
728 SHeader.sh_entsize = sizeof(Flags);
729 SHeader.sh_size = SHeader.sh_entsize;
730
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000731 auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000732 Flags.version = Section.Version;
733 Flags.isa_level = Section.ISALevel;
734 Flags.isa_rev = Section.ISARevision;
735 Flags.gpr_size = Section.GPRSize;
736 Flags.cpr1_size = Section.CPR1Size;
737 Flags.cpr2_size = Section.CPR2Size;
738 Flags.fp_abi = Section.FpABI;
739 Flags.isa_ext = Section.ISAExtension;
740 Flags.ases = Section.ASEs;
741 Flags.flags1 = Section.Flags1;
742 Flags.flags2 = Section.Flags2;
743 OS.write((const char *)&Flags, sizeof(Flags));
744
745 return true;
746}
747
George Rimar0e7ed912019-02-09 11:34:28 +0000748template <class ELFT>
James Hendersonfd997802019-02-25 11:02:24 +0000749bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
George Rimar0e7ed912019-02-09 11:34:28 +0000750 const ELFYAML::DynamicSection &Section,
751 ContiguousBlobAccumulator &CBA) {
George Rimard063c7d2019-02-20 13:58:43 +0000752 typedef typename ELFT::uint uintX_t;
753
George Rimar0e7ed912019-02-09 11:34:28 +0000754 assert(Section.Type == llvm::ELF::SHT_DYNAMIC &&
755 "Section type is not SHT_DYNAMIC");
756
James Hendersonfd997802019-02-25 11:02:24 +0000757 if (!Section.Entries.empty() && Section.Content) {
758 WithColor::error()
759 << "Cannot specify both raw content and explicit entries "
760 "for dynamic section '"
761 << Section.Name << "'.\n";
762 return false;
763 }
764
765 if (Section.Content)
766 SHeader.sh_size = Section.Content->binary_size();
767 else
768 SHeader.sh_size = 2 * sizeof(uintX_t) * Section.Entries.size();
George Rimar0e7ed912019-02-09 11:34:28 +0000769 if (Section.EntSize)
770 SHeader.sh_entsize = *Section.EntSize;
771 else
772 SHeader.sh_entsize = sizeof(Elf_Dyn);
773
George Rimard063c7d2019-02-20 13:58:43 +0000774 raw_ostream &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
George Rimar0e7ed912019-02-09 11:34:28 +0000775 for (const ELFYAML::DynamicEntry &DE : Section.Entries) {
George Rimard063c7d2019-02-20 13:58:43 +0000776 support::endian::write<uintX_t>(OS, DE.Tag, ELFT::TargetEndianness);
777 support::endian::write<uintX_t>(OS, DE.Val, ELFT::TargetEndianness);
George Rimar0e7ed912019-02-09 11:34:28 +0000778 }
James Hendersonfd997802019-02-25 11:02:24 +0000779 if (Section.Content)
780 Section.Content->writeAsBinary(OS);
781
782 return true;
George Rimar0e7ed912019-02-09 11:34:28 +0000783}
784
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000785template <class ELFT> bool ELFState<ELFT>::buildSectionIndex() {
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000786 for (unsigned i = 0, e = Doc.Sections.size(); i != e; ++i) {
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000787 StringRef Name = Doc.Sections[i]->Name;
Dave Lee17307d92017-11-09 14:53:43 +0000788 DotShStrtab.add(Name);
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000789 // "+ 1" to take into account the SHT_NULL entry.
790 if (SN2I.addName(Name, i + 1)) {
Jonas Devlieghere2cd41eb2018-04-21 21:11:59 +0000791 WithColor::error() << "Repeated section name: '" << Name
792 << "' at YAML section number " << i << ".\n";
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000793 return false;
794 }
Sean Silvaaff51252013-06-21 00:27:50 +0000795 }
Dave Lee17307d92017-11-09 14:53:43 +0000796
797 auto SecNo = 1 + Doc.Sections.size();
798 // Add special sections after input sections, if necessary.
George Rimar5fcdebe2019-04-26 13:09:11 +0000799 for (StringRef Name : implicitSectionNames())
Dave Lee17307d92017-11-09 14:53:43 +0000800 if (!SN2I.addName(Name, SecNo)) {
801 // Account for this section, since it wasn't in the Doc
802 ++SecNo;
803 DotShStrtab.add(Name);
804 }
805
806 DotShStrtab.finalize();
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000807 return true;
Sean Silva6b083882013-06-18 23:14:03 +0000808}
809
Sean Silvaf99309c2013-06-10 23:44:15 +0000810template <class ELFT>
George Rimar6da44ad2019-04-03 14:53:42 +0000811bool ELFState<ELFT>::buildSymbolIndex(ArrayRef<ELFYAML::Symbol> Symbols) {
812 bool GlobalSymbolSeen = false;
George Rimar33e498b2019-03-11 16:10:02 +0000813 std::size_t I = 0;
George Rimar6da44ad2019-04-03 14:53:42 +0000814 for (const auto &Sym : Symbols) {
815 ++I;
816
817 StringRef Name = Sym.Name;
818 if (Sym.Binding.value == ELF::STB_LOCAL && GlobalSymbolSeen) {
819 WithColor::error() << "Local symbol '" + Name +
820 "' after global in Symbols list.\n";
821 return false;
822 }
823 if (Sym.Binding.value != ELF::STB_LOCAL)
824 GlobalSymbolSeen = true;
825
826 if (!Name.empty() && SymN2I.addName(Name, I)) {
827 WithColor::error() << "Repeated symbol name: '" << Name << "'.\n";
828 return false;
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000829 }
830 }
831 return true;
832}
833
George Rimar0621b792019-02-19 14:53:48 +0000834template <class ELFT> void ELFState<ELFT>::finalizeStrings() {
George Rimar0621b792019-02-19 14:53:48 +0000835 // Add the regular symbol names to .strtab section.
George Rimar6da44ad2019-04-03 14:53:42 +0000836 for (const ELFYAML::Symbol &Sym : Doc.Symbols)
837 DotStrtab.add(Sym.Name);
George Rimar0621b792019-02-19 14:53:48 +0000838 DotStrtab.finalize();
839
George Rimar6da44ad2019-04-03 14:53:42 +0000840 if (Doc.DynamicSymbols.empty())
George Rimar0621b792019-02-19 14:53:48 +0000841 return;
842
843 // Add the dynamic symbol names to .dynstr section.
George Rimar6da44ad2019-04-03 14:53:42 +0000844 for (const ELFYAML::Symbol &Sym : Doc.DynamicSymbols)
845 DotDynstr.add(Sym.Name);
George Rimar0621b792019-02-19 14:53:48 +0000846
George Rimar623ae722019-02-21 12:21:43 +0000847 // SHT_GNU_verdef and SHT_GNU_verneed sections might also
848 // add strings to .dynstr section.
George Rimar0621b792019-02-19 14:53:48 +0000849 for (const std::unique_ptr<ELFYAML::Section> &Sec : Doc.Sections) {
George Rimar623ae722019-02-21 12:21:43 +0000850 if (auto VerNeed = dyn_cast<ELFYAML::VerneedSection>(Sec.get())) {
851 for (const ELFYAML::VerneedEntry &VE : VerNeed->VerneedV) {
852 DotDynstr.add(VE.File);
853 for (const ELFYAML::VernauxEntry &Aux : VE.AuxV)
854 DotDynstr.add(Aux.Name);
855 }
856 } else if (auto VerDef = dyn_cast<ELFYAML::VerdefSection>(Sec.get())) {
857 for (const ELFYAML::VerdefEntry &E : VerDef->Entries)
858 for (StringRef Name : E.VerNames)
859 DotDynstr.add(Name);
George Rimar0621b792019-02-19 14:53:48 +0000860 }
861 }
862
863 DotDynstr.finalize();
864}
865
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000866template <class ELFT>
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000867int ELFState<ELFT>::writeELF(raw_ostream &OS, const ELFYAML::Object &Doc) {
Simon Atanasyan220c54a2014-04-02 16:34:40 +0000868 ELFState<ELFT> State(Doc);
George Rimar0621b792019-02-19 14:53:48 +0000869
870 // Finalize .strtab and .dynstr sections. We do that early because want to
871 // finalize the string table builders before writing the content of the
872 // sections that might want to use them.
873 State.finalizeStrings();
874
Simon Atanasyan220c54a2014-04-02 16:34:40 +0000875 if (!State.buildSectionIndex())
876 return 1;
877
George Rimar33e498b2019-03-11 16:10:02 +0000878 if (!State.buildSymbolIndex(Doc.Symbols))
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000879 return 1;
880
Sean Silva38205932013-06-13 22:19:48 +0000881 Elf_Ehdr Header;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000882 State.initELFHeader(Header);
Sean Silvaf99309c2013-06-10 23:44:15 +0000883
Sean Silva38205932013-06-13 22:19:48 +0000884 // TODO: Flesh out section header support.
Petr Hosekeb04da32017-07-19 20:38:46 +0000885
886 std::vector<Elf_Phdr> PHeaders;
887 State.initProgramHeaders(PHeaders);
Sean Silva38205932013-06-13 22:19:48 +0000888
Sean Silva08a75ae2013-06-20 19:11:44 +0000889 // XXX: This offset is tightly coupled with the order that we write
890 // things to `OS`.
Petr Hosekeb04da32017-07-19 20:38:46 +0000891 const size_t SectionContentBeginOffset = Header.e_ehsize +
892 Header.e_phentsize * Header.e_phnum +
893 Header.e_shentsize * Header.e_shnum;
Sean Silva08a75ae2013-06-20 19:11:44 +0000894 ContiguousBlobAccumulator CBA(SectionContentBeginOffset);
Sean Silvac1c290b2013-06-20 20:59:34 +0000895
Sean Silva38205932013-06-13 22:19:48 +0000896 std::vector<Elf_Shdr> SHeaders;
George Rimarda1b3ab2019-04-26 12:15:32 +0000897 if (!State.initSectionHeaders(SHeaders, CBA))
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000898 return 1;
Sean Silva38205932013-06-13 22:19:48 +0000899
Dave Lee17307d92017-11-09 14:53:43 +0000900 // Populate SHeaders with implicit sections not present in the Doc
George Rimar5fcdebe2019-04-26 13:09:11 +0000901 for (StringRef Name : State.implicitSectionNames())
Dave Lee17307d92017-11-09 14:53:43 +0000902 if (State.SN2I.get(Name) >= SHeaders.size())
903 SHeaders.push_back({});
Sean Silva82177572013-06-22 01:38:00 +0000904
Dave Lee17307d92017-11-09 14:53:43 +0000905 // Initialize the implicit sections
George Rimar48288112019-04-29 11:54:10 +0000906 State.initSymtabSectionHeader(SHeaders[State.SN2I.get(".symtab")],
907 SymtabType::Static, CBA);
908 State.initStrtabSectionHeader(SHeaders[State.SN2I.get(".strtab")], ".strtab",
909 State.DotStrtab, CBA);
910 State.initStrtabSectionHeader(SHeaders[State.SN2I.get(".shstrtab")],
911 ".shstrtab", State.DotShStrtab, CBA);
George Rimar6da44ad2019-04-03 14:53:42 +0000912 if (!Doc.DynamicSymbols.empty()) {
George Rimar48288112019-04-29 11:54:10 +0000913 State.initSymtabSectionHeader(SHeaders[State.SN2I.get(".dynsym")],
914 SymtabType::Dynamic, CBA);
915 State.initStrtabSectionHeader(SHeaders[State.SN2I.get(".dynstr")],
916 ".dynstr", State.DotDynstr, CBA);
Dave Lee67b49662017-11-16 18:10:15 +0000917 }
Sean Silvaf99309c2013-06-10 23:44:15 +0000918
Petr Hosekeb04da32017-07-19 20:38:46 +0000919 // Now we can decide segment offsets
920 State.setProgramHeaderLayout(PHeaders, SHeaders);
921
Sean Silvaf99309c2013-06-10 23:44:15 +0000922 OS.write((const char *)&Header, sizeof(Header));
Petr Hosekeb04da32017-07-19 20:38:46 +0000923 writeArrayData(OS, makeArrayRef(PHeaders));
Will Dietz0b48c732013-10-12 21:29:16 +0000924 writeArrayData(OS, makeArrayRef(SHeaders));
Sean Silva46dffff2013-06-13 22:20:01 +0000925 CBA.writeBlobToStream(OS);
Sean Silva415d93f2013-06-17 20:14:59 +0000926 return 0;
Sean Silvaf99309c2013-06-10 23:44:15 +0000927}
928
Xing GUObac78642018-12-07 11:04:22 +0000929template <class ELFT>
George Rimar5fcdebe2019-04-26 13:09:11 +0000930std::vector<StringRef> ELFState<ELFT>::implicitSectionNames() const {
George Rimar6da44ad2019-04-03 14:53:42 +0000931 if (Doc.DynamicSymbols.empty())
Dave Lee67b49662017-11-16 18:10:15 +0000932 return {".symtab", ".strtab", ".shstrtab"};
933 return {".symtab", ".strtab", ".shstrtab", ".dynsym", ".dynstr"};
934}
935
Chris Bieneman8ff0c112016-06-27 19:53:53 +0000936int yaml2elf(llvm::ELFYAML::Object &Doc, raw_ostream &Out) {
George Rimarbc4d3c42019-04-29 12:25:01 +0000937 bool IsLE = Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB);
938 bool Is64Bit = Doc.Header.Class == ELFYAML::ELF_ELFCLASS(ELF::ELFCLASS64);
939 if (Is64Bit) {
940 if (IsLE)
Rui Ueyama1b31eb92018-01-12 01:40:32 +0000941 return ELFState<object::ELF64LE>::writeELF(Out, Doc);
George Rimarbc4d3c42019-04-29 12:25:01 +0000942 return ELFState<object::ELF64BE>::writeELF(Out, Doc);
Sean Silvaf99309c2013-06-10 23:44:15 +0000943 }
George Rimarbc4d3c42019-04-29 12:25:01 +0000944 if (IsLE)
945 return ELFState<object::ELF32LE>::writeELF(Out, Doc);
946 return ELFState<object::ELF32BE>::writeELF(Out, Doc);
Sean Silvaf99309c2013-06-10 23:44:15 +0000947}