blob: 1f83656a606b49f1cac5d3fd2e97799f249a2266 [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();
George Rimar6da44ad2019-04-03 14:53:42 +0000136 bool buildSymbolIndex(ArrayRef<ELFYAML::Symbol> Symbols);
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000137 void initELFHeader(Elf_Ehdr &Header);
Petr Hosekeb04da32017-07-19 20:38:46 +0000138 void initProgramHeaders(std::vector<Elf_Phdr> &PHeaders);
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000139 bool initSectionHeaders(std::vector<Elf_Shdr> &SHeaders,
140 ContiguousBlobAccumulator &CBA);
Dave Lee67b49662017-11-16 18:10:15 +0000141 void initSymtabSectionHeader(Elf_Shdr &SHeader, SymtabType STType,
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000142 ContiguousBlobAccumulator &CBA);
143 void initStrtabSectionHeader(Elf_Shdr &SHeader, StringRef Name,
144 StringTableBuilder &STB,
145 ContiguousBlobAccumulator &CBA);
Petr Hosekeb04da32017-07-19 20:38:46 +0000146 void setProgramHeaderLayout(std::vector<Elf_Phdr> &PHeaders,
147 std::vector<Elf_Shdr> &SHeaders);
George Rimar6da44ad2019-04-03 14:53:42 +0000148 void addSymbols(ArrayRef<ELFYAML::Symbol> Symbols, std::vector<Elf_Sym> &Syms,
Dave Lee67b49662017-11-16 18:10:15 +0000149 const StringTableBuilder &Strtab);
George Rimarda1b3ab2019-04-26 12:15:32 +0000150 bool writeSectionContent(Elf_Shdr &SHeader,
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000151 const ELFYAML::RawContentSection &Section,
152 ContiguousBlobAccumulator &CBA);
153 bool writeSectionContent(Elf_Shdr &SHeader,
154 const ELFYAML::RelocationSection &Section,
155 ContiguousBlobAccumulator &CBA);
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000156 bool writeSectionContent(Elf_Shdr &SHeader, const ELFYAML::Group &Group,
157 ContiguousBlobAccumulator &CBA);
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000158 bool writeSectionContent(Elf_Shdr &SHeader,
George Rimar646af082019-02-19 15:29:07 +0000159 const ELFYAML::SymverSection &Section,
160 ContiguousBlobAccumulator &CBA);
161 bool writeSectionContent(Elf_Shdr &SHeader,
George Rimar0621b792019-02-19 14:53:48 +0000162 const ELFYAML::VerneedSection &Section,
163 ContiguousBlobAccumulator &CBA);
164 bool writeSectionContent(Elf_Shdr &SHeader,
George Rimar623ae722019-02-21 12:21:43 +0000165 const ELFYAML::VerdefSection &Section,
166 ContiguousBlobAccumulator &CBA);
167 bool writeSectionContent(Elf_Shdr &SHeader,
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000168 const ELFYAML::MipsABIFlags &Section,
169 ContiguousBlobAccumulator &CBA);
James Hendersonfd997802019-02-25 11:02:24 +0000170 bool writeSectionContent(Elf_Shdr &SHeader,
George Rimar0e7ed912019-02-09 11:34:28 +0000171 const ELFYAML::DynamicSection &Section,
172 ContiguousBlobAccumulator &CBA);
George Rimar5fcdebe2019-04-26 13:09:11 +0000173 std::vector<StringRef> implicitSectionNames() const;
Sean Silva08a75ae2013-06-20 19:11:44 +0000174
Simon Atanasyan220c54a2014-04-02 16:34:40 +0000175 // - SHT_NULL entry (placed first, i.e. 0'th entry)
Dave Lee67b49662017-11-16 18:10:15 +0000176 // - symbol table (.symtab) (defaults to after last yaml section)
177 // - string table (.strtab) (defaults to after .symtab)
178 // - section header string table (.shstrtab) (defaults to after .strtab)
179 // - dynamic symbol table (.dynsym) (defaults to after .shstrtab)
180 // - dynamic string table (.dynstr) (defaults to after .dynsym)
Dave Lee17307d92017-11-09 14:53:43 +0000181 unsigned getDotSymTabSecNo() const { return SN2I.get(".symtab"); }
182 unsigned getDotStrTabSecNo() const { return SN2I.get(".strtab"); }
183 unsigned getDotShStrTabSecNo() const { return SN2I.get(".shstrtab"); }
Dave Lee67b49662017-11-16 18:10:15 +0000184 unsigned getDotDynSymSecNo() const { return SN2I.get(".dynsym"); }
185 unsigned getDotDynStrSecNo() const { return SN2I.get(".dynstr"); }
Dave Lee17307d92017-11-09 14:53:43 +0000186 unsigned getSectionCount() const { return SN2I.size() + 1; }
Simon Atanasyan220c54a2014-04-02 16:34:40 +0000187
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000188 ELFState(const ELFYAML::Object &D) : Doc(D) {}
Simon Atanasyan220c54a2014-04-02 16:34:40 +0000189
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000190public:
191 static int writeELF(raw_ostream &OS, const ELFYAML::Object &Doc);
George Rimar0621b792019-02-19 14:53:48 +0000192
193private:
194 void finalizeStrings();
Sean Silva08a75ae2013-06-20 19:11:44 +0000195};
196} // end anonymous namespace
197
Sean Silva37e817c2013-06-21 00:33:01 +0000198template <class ELFT>
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000199void ELFState<ELFT>::initELFHeader(Elf_Ehdr &Header) {
200 using namespace llvm::ELF;
201 zero(Header);
202 Header.e_ident[EI_MAG0] = 0x7f;
203 Header.e_ident[EI_MAG1] = 'E';
204 Header.e_ident[EI_MAG2] = 'L';
205 Header.e_ident[EI_MAG3] = 'F';
206 Header.e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;
George Rimara5a0a0f2019-03-07 12:09:19 +0000207 Header.e_ident[EI_DATA] = Doc.Header.Data;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000208 Header.e_ident[EI_VERSION] = EV_CURRENT;
209 Header.e_ident[EI_OSABI] = Doc.Header.OSABI;
George Rimar6367d7a2018-12-20 10:43:49 +0000210 Header.e_ident[EI_ABIVERSION] = Doc.Header.ABIVersion;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000211 Header.e_type = Doc.Header.Type;
212 Header.e_machine = Doc.Header.Machine;
213 Header.e_version = EV_CURRENT;
214 Header.e_entry = Doc.Header.Entry;
Petr Hosekeb04da32017-07-19 20:38:46 +0000215 Header.e_phoff = sizeof(Header);
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000216 Header.e_flags = Doc.Header.Flags;
217 Header.e_ehsize = sizeof(Elf_Ehdr);
Petr Hosekeb04da32017-07-19 20:38:46 +0000218 Header.e_phentsize = sizeof(Elf_Phdr);
219 Header.e_phnum = Doc.ProgramHeaders.size();
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000220 Header.e_shentsize = sizeof(Elf_Shdr);
Petr Hosekeb04da32017-07-19 20:38:46 +0000221 // Immediately following the ELF header and program headers.
222 Header.e_shoff =
223 sizeof(Header) + sizeof(Elf_Phdr) * Doc.ProgramHeaders.size();
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000224 Header.e_shnum = getSectionCount();
225 Header.e_shstrndx = getDotShStrTabSecNo();
226}
227
228template <class ELFT>
Petr Hosekeb04da32017-07-19 20:38:46 +0000229void ELFState<ELFT>::initProgramHeaders(std::vector<Elf_Phdr> &PHeaders) {
230 for (const auto &YamlPhdr : Doc.ProgramHeaders) {
231 Elf_Phdr Phdr;
232 Phdr.p_type = YamlPhdr.Type;
233 Phdr.p_flags = YamlPhdr.Flags;
234 Phdr.p_vaddr = YamlPhdr.VAddr;
235 Phdr.p_paddr = YamlPhdr.PAddr;
236 PHeaders.push_back(Phdr);
237 }
238}
239
Xing GUO98228352018-12-04 14:27:51 +0000240static bool convertSectionIndex(NameToIdxMap &SN2I, StringRef SecName,
241 StringRef IndexSrc, unsigned &IndexDest) {
242 if (SN2I.lookup(IndexSrc, IndexDest) && !to_integer(IndexSrc, IndexDest)) {
243 WithColor::error() << "Unknown section referenced: '" << IndexSrc
244 << "' at YAML section '" << SecName << "'.\n";
245 return false;
246 }
247 return true;
248}
249
Petr Hosekeb04da32017-07-19 20:38:46 +0000250template <class ELFT>
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000251bool ELFState<ELFT>::initSectionHeaders(std::vector<Elf_Shdr> &SHeaders,
252 ContiguousBlobAccumulator &CBA) {
253 // Ensure SHN_UNDEF entry is present. An all-zero section header is a
254 // valid SHN_UNDEF entry since SHT_NULL == 0.
255 Elf_Shdr SHeader;
256 zero(SHeader);
257 SHeaders.push_back(SHeader);
258
259 for (const auto &Sec : Doc.Sections) {
260 zero(SHeader);
Hans Wennborg59f0cba2014-04-30 19:38:09 +0000261 SHeader.sh_name = DotShStrtab.getOffset(Sec->Name);
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000262 SHeader.sh_type = Sec->Type;
263 SHeader.sh_flags = Sec->Flags;
264 SHeader.sh_addr = Sec->Address;
265 SHeader.sh_addralign = Sec->AddressAlign;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000266
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000267 if (!Sec->Link.empty()) {
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000268 unsigned Index;
Xing GUO98228352018-12-04 14:27:51 +0000269 if (!convertSectionIndex(SN2I, Sec->Name, Sec->Link, Index))
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000270 return false;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000271 SHeader.sh_link = Index;
272 }
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000273
George Rimarda1b3ab2019-04-26 12:15:32 +0000274 if (auto S = dyn_cast<ELFYAML::RawContentSection>(Sec.get())) {
275 if (!writeSectionContent(SHeader, *S, CBA))
George Rimar7f2df7d2018-08-16 12:23:22 +0000276 return false;
George Rimarda1b3ab2019-04-26 12:15:32 +0000277 } else if (auto S = dyn_cast<ELFYAML::RelocationSection>(Sec.get())) {
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000278 if (!writeSectionContent(SHeader, *S, CBA))
279 return false;
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000280 } else if (auto S = dyn_cast<ELFYAML::Group>(Sec.get())) {
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000281 if (!writeSectionContent(SHeader, *S, CBA))
282 return false;
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000283 } else if (auto S = dyn_cast<ELFYAML::MipsABIFlags>(Sec.get())) {
284 if (!writeSectionContent(SHeader, *S, CBA))
285 return false;
Simon Atanasyan5db02762015-07-03 23:00:54 +0000286 } else if (auto S = dyn_cast<ELFYAML::NoBitsSection>(Sec.get())) {
287 SHeader.sh_entsize = 0;
288 SHeader.sh_size = S->Size;
289 // SHT_NOBITS section does not have content
290 // so just to setup the section offset.
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000291 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
George Rimar0e7ed912019-02-09 11:34:28 +0000292 } else if (auto S = dyn_cast<ELFYAML::DynamicSection>(Sec.get())) {
James Hendersonfd997802019-02-25 11:02:24 +0000293 if (!writeSectionContent(SHeader, *S, CBA))
294 return false;
George Rimar646af082019-02-19 15:29:07 +0000295 } else if (auto S = dyn_cast<ELFYAML::SymverSection>(Sec.get())) {
George Rimarda1b3ab2019-04-26 12:15:32 +0000296 if (!writeSectionContent(SHeader, *S, CBA))
297 return false;
George Rimar0621b792019-02-19 14:53:48 +0000298 } else if (auto S = dyn_cast<ELFYAML::VerneedSection>(Sec.get())) {
George Rimarda1b3ab2019-04-26 12:15:32 +0000299 if (!writeSectionContent(SHeader, *S, CBA))
300 return false;
George Rimar623ae722019-02-21 12:21:43 +0000301 } else if (auto S = dyn_cast<ELFYAML::VerdefSection>(Sec.get())) {
George Rimarda1b3ab2019-04-26 12:15:32 +0000302 if (!writeSectionContent(SHeader, *S, CBA))
303 return false;
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000304 } else
305 llvm_unreachable("Unknown section type");
306
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000307 SHeaders.push_back(SHeader);
308 }
309 return true;
310}
311
George Rimar6da44ad2019-04-03 14:53:42 +0000312static size_t findFirstNonGlobal(ArrayRef<ELFYAML::Symbol> Symbols) {
313 for (size_t I = 0; I < Symbols.size(); ++I)
314 if (Symbols[I].Binding.value != ELF::STB_LOCAL)
315 return I;
316 return Symbols.size();
317}
318
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000319template <class ELFT>
320void ELFState<ELFT>::initSymtabSectionHeader(Elf_Shdr &SHeader,
Dave Lee67b49662017-11-16 18:10:15 +0000321 SymtabType STType,
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000322 ContiguousBlobAccumulator &CBA) {
323 zero(SHeader);
Dave Lee67b49662017-11-16 18:10:15 +0000324 bool IsStatic = STType == SymtabType::Static;
325 SHeader.sh_name = DotShStrtab.getOffset(IsStatic ? ".symtab" : ".dynsym");
326 SHeader.sh_type = IsStatic ? ELF::SHT_SYMTAB : ELF::SHT_DYNSYM;
327 SHeader.sh_link = IsStatic ? getDotStrTabSecNo() : getDotDynStrSecNo();
George Rimarc1da1492019-04-26 12:45:54 +0000328
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000329 // One greater than symbol table index of the last local symbol.
George Rimarc1da1492019-04-26 12:45:54 +0000330 const auto &Symbols = IsStatic ? Doc.Symbols : Doc.DynamicSymbols;
George Rimar6da44ad2019-04-03 14:53:42 +0000331 SHeader.sh_info = findFirstNonGlobal(Symbols) + 1;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000332 SHeader.sh_entsize = sizeof(Elf_Sym);
Simon Atanasyan3a120922015-07-09 18:23:02 +0000333 SHeader.sh_addralign = 8;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000334
George Rimara7ba1a02019-03-01 10:18:16 +0000335 // Get the section index ignoring the SHT_NULL section.
336 unsigned SecNdx =
337 IsStatic ? getDotSymTabSecNo() - 1 : getDotDynSymSecNo() - 1;
338 // If the symbol table section is explicitly described in the YAML
339 // then we should set the fields requested.
340 if (SecNdx < Doc.Sections.size()) {
341 ELFYAML::Section *Sec = Doc.Sections[SecNdx].get();
342 SHeader.sh_addr = Sec->Address;
343 if (auto S = dyn_cast<ELFYAML::RawContentSection>(Sec))
344 SHeader.sh_info = S->Info;
George Rimar6947acd2019-02-19 12:15:04 +0000345 }
346
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000347 std::vector<Elf_Sym> Syms;
348 {
349 // Ensure STN_UNDEF is present
350 Elf_Sym Sym;
351 zero(Sym);
352 Syms.push_back(Sym);
353 }
Hans Wennborg59f0cba2014-04-30 19:38:09 +0000354
George Rimarc1da1492019-04-26 12:45:54 +0000355 addSymbols(Symbols, Syms, IsStatic ? DotStrtab : DotDynstr);
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000356
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000357 writeArrayData(
358 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign),
359 makeArrayRef(Syms));
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000360 SHeader.sh_size = arrayDataSize(makeArrayRef(Syms));
361}
362
363template <class ELFT>
364void ELFState<ELFT>::initStrtabSectionHeader(Elf_Shdr &SHeader, StringRef Name,
365 StringTableBuilder &STB,
366 ContiguousBlobAccumulator &CBA) {
367 zero(SHeader);
Hans Wennborg59f0cba2014-04-30 19:38:09 +0000368 SHeader.sh_name = DotShStrtab.getOffset(Name);
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000369 SHeader.sh_type = ELF::SHT_STRTAB;
Rafael Espindola39751af2016-10-04 22:43:25 +0000370 STB.write(CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign));
371 SHeader.sh_size = STB.getSize();
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000372 SHeader.sh_addralign = 1;
George Rimar6947acd2019-02-19 12:15:04 +0000373
374 // If .dynstr section is explicitly described in the YAML
375 // then we want to use its section address.
376 if (Name == ".dynstr") {
377 // Take section index and ignore the SHT_NULL section.
378 unsigned SecNdx = getDotDynStrSecNo() - 1;
379 if (SecNdx < Doc.Sections.size())
380 SHeader.sh_addr = Doc.Sections[SecNdx]->Address;
381 }
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000382}
383
384template <class ELFT>
Petr Hosekeb04da32017-07-19 20:38:46 +0000385void ELFState<ELFT>::setProgramHeaderLayout(std::vector<Elf_Phdr> &PHeaders,
386 std::vector<Elf_Shdr> &SHeaders) {
387 uint32_t PhdrIdx = 0;
388 for (auto &YamlPhdr : Doc.ProgramHeaders) {
389 auto &PHeader = PHeaders[PhdrIdx++];
390
James Hendersonb10f48b2019-03-15 10:35:27 +0000391 if (YamlPhdr.Offset) {
392 PHeader.p_offset = *YamlPhdr.Offset;
393 } else {
394 if (YamlPhdr.Sections.size())
395 PHeader.p_offset = UINT32_MAX;
Petr Hosekeb04da32017-07-19 20:38:46 +0000396 else
James Hendersonb10f48b2019-03-15 10:35:27 +0000397 PHeader.p_offset = 0;
398
399 // Find the minimum offset for the program header.
400 for (auto SecName : YamlPhdr.Sections) {
401 uint32_t Index = 0;
402 SN2I.lookup(SecName.Section, Index);
403 const auto &SHeader = SHeaders[Index];
404 PHeader.p_offset = std::min(PHeader.p_offset, SHeader.sh_offset);
405 }
Petr Hosekeb04da32017-07-19 20:38:46 +0000406 }
407
James Hendersonb10f48b2019-03-15 10:35:27 +0000408 // Find the maximum offset of the end of a section in order to set p_filesz,
409 // if not set explicitly.
410 if (YamlPhdr.FileSize) {
411 PHeader.p_filesz = *YamlPhdr.FileSize;
412 } else {
413 PHeader.p_filesz = 0;
414 for (auto SecName : YamlPhdr.Sections) {
415 uint32_t Index = 0;
416 SN2I.lookup(SecName.Section, Index);
417 const auto &SHeader = SHeaders[Index];
418 uint64_t EndOfSection;
419 if (SHeader.sh_type == llvm::ELF::SHT_NOBITS)
420 EndOfSection = SHeader.sh_offset;
421 else
422 EndOfSection = SHeader.sh_offset + SHeader.sh_size;
423 uint64_t EndOfSegment = PHeader.p_offset + PHeader.p_filesz;
424 EndOfSegment = std::max(EndOfSegment, EndOfSection);
425 PHeader.p_filesz = EndOfSegment - PHeader.p_offset;
426 }
427 }
428
429 // If not set explicitly, find the memory size by adding the size of
430 // sections at the end of the segment. These should be empty (size of zero)
431 // and NOBITS sections.
432 if (YamlPhdr.MemSize) {
433 PHeader.p_memsz = *YamlPhdr.MemSize;
434 } else {
435 PHeader.p_memsz = PHeader.p_filesz;
436 for (auto SecName : YamlPhdr.Sections) {
437 uint32_t Index = 0;
438 SN2I.lookup(SecName.Section, Index);
439 const auto &SHeader = SHeaders[Index];
440 if (SHeader.sh_offset == PHeader.p_offset + PHeader.p_filesz)
441 PHeader.p_memsz += SHeader.sh_size;
442 }
Petr Hosekeb04da32017-07-19 20:38:46 +0000443 }
444
445 // Set the alignment of the segment to be the same as the maximum alignment
Jake Ehrlich03aeeb092017-11-01 23:14:48 +0000446 // of the sections with the same offset so that by default the segment
Petr Hosekeb04da32017-07-19 20:38:46 +0000447 // has a valid and sensible alignment.
Jake Ehrlich03aeeb092017-11-01 23:14:48 +0000448 if (YamlPhdr.Align) {
449 PHeader.p_align = *YamlPhdr.Align;
450 } else {
451 PHeader.p_align = 1;
452 for (auto SecName : YamlPhdr.Sections) {
453 uint32_t Index = 0;
454 SN2I.lookup(SecName.Section, Index);
455 const auto &SHeader = SHeaders[Index];
456 if (SHeader.sh_offset == PHeader.p_offset)
457 PHeader.p_align = std::max(PHeader.p_align, SHeader.sh_addralign);
458 }
Petr Hosekeb04da32017-07-19 20:38:46 +0000459 }
460 }
461}
462
463template <class ELFT>
George Rimar6da44ad2019-04-03 14:53:42 +0000464void ELFState<ELFT>::addSymbols(ArrayRef<ELFYAML::Symbol> Symbols,
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000465 std::vector<Elf_Sym> &Syms,
Dave Lee67b49662017-11-16 18:10:15 +0000466 const StringTableBuilder &Strtab) {
Simon Atanasyan048baca2014-03-14 06:53:30 +0000467 for (const auto &Sym : Symbols) {
Sean Silva6b083882013-06-18 23:14:03 +0000468 Elf_Sym Symbol;
469 zero(Symbol);
470 if (!Sym.Name.empty())
Dave Lee67b49662017-11-16 18:10:15 +0000471 Symbol.st_name = Strtab.getOffset(Sym.Name);
George Rimar6da44ad2019-04-03 14:53:42 +0000472 Symbol.setBindingAndType(Sym.Binding, Sym.Type);
Sean Silvac4afa6d2013-06-21 01:11:48 +0000473 if (!Sym.Section.empty()) {
474 unsigned Index;
Simon Atanasyan35babf92014-04-06 09:02:55 +0000475 if (SN2I.lookup(Sym.Section, Index)) {
Jonas Devlieghere2cd41eb2018-04-21 21:11:59 +0000476 WithColor::error() << "Unknown section referenced: '" << Sym.Section
477 << "' by YAML symbol " << Sym.Name << ".\n";
Sean Silvac4afa6d2013-06-21 01:11:48 +0000478 exit(1);
479 }
480 Symbol.st_shndx = Index;
Petr Hosek5c469a32017-09-07 20:44:16 +0000481 } else if (Sym.Index) {
482 Symbol.st_shndx = *Sym.Index;
483 }
484 // else Symbol.st_shndex == SHN_UNDEF (== 0), since it was zero'd earlier.
Sean Silva05001b92013-06-20 20:59:47 +0000485 Symbol.st_value = Sym.Value;
Simon Atanasyan60e1a792014-11-06 22:46:24 +0000486 Symbol.st_other = Sym.Other;
Sean Silva05001b92013-06-20 20:59:47 +0000487 Symbol.st_size = Sym.Size;
Sean Silva6b083882013-06-18 23:14:03 +0000488 Syms.push_back(Symbol);
489 }
Sean Silvaaff51252013-06-21 00:27:50 +0000490}
491
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000492template <class ELFT>
George Rimarda1b3ab2019-04-26 12:15:32 +0000493bool ELFState<ELFT>::writeSectionContent(
George Rimarb49e1922019-04-24 13:02:15 +0000494 Elf_Shdr &SHeader, const ELFYAML::RawContentSection &Section,
495 ContiguousBlobAccumulator &CBA) {
Simon Atanasyanb83f3802014-05-16 16:01:00 +0000496 assert(Section.Size >= Section.Content.binary_size() &&
497 "Section size and section content are inconsistent");
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000498 raw_ostream &OS =
499 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
Simon Atanasyanb83f3802014-05-16 16:01:00 +0000500 Section.Content.writeAsBinary(OS);
George Rimarb49e1922019-04-24 13:02:15 +0000501 OS.write_zeros(Section.Size - Section.Content.binary_size());
502
George Rimar65a68282018-08-07 08:11:38 +0000503 if (Section.EntSize)
504 SHeader.sh_entsize = *Section.EntSize;
505 else if (Section.Type == llvm::ELF::SHT_RELR)
Jake Ehrlich0f440d82018-06-28 21:07:34 +0000506 SHeader.sh_entsize = sizeof(Elf_Relr);
507 else
508 SHeader.sh_entsize = 0;
Simon Atanasyanb83f3802014-05-16 16:01:00 +0000509 SHeader.sh_size = Section.Size;
George Rimara7ba1a02019-03-01 10:18:16 +0000510 SHeader.sh_info = Section.Info;
George Rimarda1b3ab2019-04-26 12:15:32 +0000511 return true;
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000512}
513
Simon Atanasyan5d19c672015-01-25 13:29:25 +0000514static bool isMips64EL(const ELFYAML::Object &Doc) {
515 return Doc.Header.Machine == ELFYAML::ELF_EM(llvm::ELF::EM_MIPS) &&
516 Doc.Header.Class == ELFYAML::ELF_ELFCLASS(ELF::ELFCLASS64) &&
517 Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB);
518}
519
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000520template <class ELFT>
521bool
522ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
523 const ELFYAML::RelocationSection &Section,
524 ContiguousBlobAccumulator &CBA) {
Simon Atanasyan8eb9d1b2015-05-08 07:05:04 +0000525 assert((Section.Type == llvm::ELF::SHT_REL ||
526 Section.Type == llvm::ELF::SHT_RELA) &&
527 "Section type is not SHT_REL nor SHT_RELA");
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000528
529 bool IsRela = Section.Type == llvm::ELF::SHT_RELA;
530 SHeader.sh_entsize = IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
531 SHeader.sh_size = SHeader.sh_entsize * Section.Relocations.size();
532
George Rimarda1b3ab2019-04-26 12:15:32 +0000533 // For relocation section set link to .symtab by default.
534 if (Section.Link.empty())
535 SHeader.sh_link = getDotSymTabSecNo();
536
537 unsigned Index = 0;
538 if (!Section.RelocatableSec.empty() &&
539 !convertSectionIndex(SN2I, Section.Name, Section.RelocatableSec, Index))
540 return false;
541 SHeader.sh_info = Index;
542
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000543 auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000544
545 for (const auto &Rel : Section.Relocations) {
Adhemerval Zanella9f3dbff2015-04-22 15:26:43 +0000546 unsigned SymIdx = 0;
James Henderson9bc817a2019-03-12 17:00:25 +0000547 // If a relocation references a symbol, try to look one up in the symbol
548 // table. If it is not there, treat the value as a symbol index.
549 if (Rel.Symbol && SymN2I.lookup(*Rel.Symbol, SymIdx) &&
550 !to_integer(*Rel.Symbol, SymIdx)) {
551 WithColor::error() << "Unknown symbol referenced: '" << *Rel.Symbol
552 << "' at YAML section '" << Section.Name << "'.\n";
553 return false;
554 }
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000555
556 if (IsRela) {
557 Elf_Rela REntry;
558 zero(REntry);
559 REntry.r_offset = Rel.Offset;
560 REntry.r_addend = Rel.Addend;
Simon Atanasyan5d19c672015-01-25 13:29:25 +0000561 REntry.setSymbolAndType(SymIdx, Rel.Type, isMips64EL(Doc));
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000562 OS.write((const char *)&REntry, sizeof(REntry));
563 } else {
564 Elf_Rel REntry;
565 zero(REntry);
566 REntry.r_offset = Rel.Offset;
Simon Atanasyan5d19c672015-01-25 13:29:25 +0000567 REntry.setSymbolAndType(SymIdx, Rel.Type, isMips64EL(Doc));
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000568 OS.write((const char *)&REntry, sizeof(REntry));
569 }
570 }
571 return true;
572}
573
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000574template <class ELFT>
575bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
576 const ELFYAML::Group &Section,
577 ContiguousBlobAccumulator &CBA) {
Simon Atanasyan8eb9d1b2015-05-08 07:05:04 +0000578 assert(Section.Type == llvm::ELF::SHT_GROUP &&
579 "Section type is not SHT_GROUP");
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000580
George Rimard063c7d2019-02-20 13:58:43 +0000581 SHeader.sh_entsize = 4;
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000582 SHeader.sh_size = SHeader.sh_entsize * Section.Members.size();
583
George Rimarda1b3ab2019-04-26 12:15:32 +0000584 unsigned SymIdx;
585 if (SymN2I.lookup(Section.Signature, SymIdx) &&
586 !to_integer(Section.Signature, SymIdx)) {
587 WithColor::error() << "Unknown symbol referenced: '" << Section.Signature
588 << "' at YAML section '" << Section.Name << "'.\n";
589 return false;
590 }
591 SHeader.sh_info = SymIdx;
592
George Rimard063c7d2019-02-20 13:58:43 +0000593 raw_ostream &OS =
594 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000595
George Rimarfb7780a2019-04-26 12:20:51 +0000596 for (const ELFYAML::SectionOrType &Member : Section.Members) {
597 unsigned int SectionIndex = 0;
598 if (Member.sectionNameOrType == "GRP_COMDAT")
599 SectionIndex = llvm::ELF::GRP_COMDAT;
600 else if (!convertSectionIndex(SN2I, Section.Name, Member.sectionNameOrType,
601 SectionIndex))
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000602 return false;
George Rimarfb7780a2019-04-26 12:20:51 +0000603 support::endian::write<uint32_t>(OS, SectionIndex, ELFT::TargetEndianness);
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000604 }
605 return true;
606}
607
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000608template <class ELFT>
609bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
George Rimar646af082019-02-19 15:29:07 +0000610 const ELFYAML::SymverSection &Section,
611 ContiguousBlobAccumulator &CBA) {
George Rimar646af082019-02-19 15:29:07 +0000612 raw_ostream &OS =
613 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
George Rimardac37fb2019-02-20 14:01:02 +0000614 for (uint16_t Version : Section.Entries)
615 support::endian::write<uint16_t>(OS, Version, ELFT::TargetEndianness);
George Rimar646af082019-02-19 15:29:07 +0000616
George Rimard063c7d2019-02-20 13:58:43 +0000617 SHeader.sh_entsize = 2;
618 SHeader.sh_size = Section.Entries.size() * SHeader.sh_entsize;
George Rimar646af082019-02-19 15:29:07 +0000619 return true;
620}
621
622template <class ELFT>
623bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
George Rimar623ae722019-02-21 12:21:43 +0000624 const ELFYAML::VerdefSection &Section,
625 ContiguousBlobAccumulator &CBA) {
626 typedef typename ELFT::Verdef Elf_Verdef;
627 typedef typename ELFT::Verdaux Elf_Verdaux;
628 raw_ostream &OS =
629 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
630
631 uint64_t AuxCnt = 0;
632 for (size_t I = 0; I < Section.Entries.size(); ++I) {
633 const ELFYAML::VerdefEntry &E = Section.Entries[I];
634
635 Elf_Verdef VerDef;
636 VerDef.vd_version = E.Version;
637 VerDef.vd_flags = E.Flags;
638 VerDef.vd_ndx = E.VersionNdx;
639 VerDef.vd_hash = E.Hash;
640 VerDef.vd_aux = sizeof(Elf_Verdef);
641 VerDef.vd_cnt = E.VerNames.size();
642 if (I == Section.Entries.size() - 1)
643 VerDef.vd_next = 0;
644 else
645 VerDef.vd_next =
646 sizeof(Elf_Verdef) + E.VerNames.size() * sizeof(Elf_Verdaux);
647 OS.write((const char *)&VerDef, sizeof(Elf_Verdef));
648
649 for (size_t J = 0; J < E.VerNames.size(); ++J, ++AuxCnt) {
650 Elf_Verdaux VernAux;
651 VernAux.vda_name = DotDynstr.getOffset(E.VerNames[J]);
652 if (J == E.VerNames.size() - 1)
653 VernAux.vda_next = 0;
654 else
655 VernAux.vda_next = sizeof(Elf_Verdaux);
656 OS.write((const char *)&VernAux, sizeof(Elf_Verdaux));
657 }
658 }
659
660 SHeader.sh_size = Section.Entries.size() * sizeof(Elf_Verdef) +
661 AuxCnt * sizeof(Elf_Verdaux);
662 SHeader.sh_info = Section.Info;
663
664 return true;
665}
666
667template <class ELFT>
668bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
George Rimar0621b792019-02-19 14:53:48 +0000669 const ELFYAML::VerneedSection &Section,
670 ContiguousBlobAccumulator &CBA) {
George Rimarda1b3ab2019-04-26 12:15:32 +0000671 typedef typename ELFT::Verneed Elf_Verneed;
672 typedef typename ELFT::Vernaux Elf_Vernaux;
George Rimar0621b792019-02-19 14:53:48 +0000673
George Rimarda1b3ab2019-04-26 12:15:32 +0000674 auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
George Rimar0621b792019-02-19 14:53:48 +0000675
George Rimarda1b3ab2019-04-26 12:15:32 +0000676 uint64_t AuxCnt = 0;
677 for (size_t I = 0; I < Section.VerneedV.size(); ++I) {
678 const ELFYAML::VerneedEntry &VE = Section.VerneedV[I];
George Rimar0621b792019-02-19 14:53:48 +0000679
George Rimarda1b3ab2019-04-26 12:15:32 +0000680 Elf_Verneed VerNeed;
681 VerNeed.vn_version = VE.Version;
682 VerNeed.vn_file = DotDynstr.getOffset(VE.File);
683 if (I == Section.VerneedV.size() - 1)
684 VerNeed.vn_next = 0;
685 else
686 VerNeed.vn_next =
687 sizeof(Elf_Verneed) + VE.AuxV.size() * sizeof(Elf_Vernaux);
688 VerNeed.vn_cnt = VE.AuxV.size();
689 VerNeed.vn_aux = sizeof(Elf_Verneed);
690 OS.write((const char *)&VerNeed, sizeof(Elf_Verneed));
George Rimar0621b792019-02-19 14:53:48 +0000691
George Rimarda1b3ab2019-04-26 12:15:32 +0000692 for (size_t J = 0; J < VE.AuxV.size(); ++J, ++AuxCnt) {
693 const ELFYAML::VernauxEntry &VAuxE = VE.AuxV[J];
George Rimar0621b792019-02-19 14:53:48 +0000694
George Rimarda1b3ab2019-04-26 12:15:32 +0000695 Elf_Vernaux VernAux;
696 VernAux.vna_hash = VAuxE.Hash;
697 VernAux.vna_flags = VAuxE.Flags;
698 VernAux.vna_other = VAuxE.Other;
699 VernAux.vna_name = DotDynstr.getOffset(VAuxE.Name);
700 if (J == VE.AuxV.size() - 1)
701 VernAux.vna_next = 0;
702 else
703 VernAux.vna_next = sizeof(Elf_Vernaux);
704 OS.write((const char *)&VernAux, sizeof(Elf_Vernaux));
705 }
706 }
George Rimar0621b792019-02-19 14:53:48 +0000707
George Rimarda1b3ab2019-04-26 12:15:32 +0000708 SHeader.sh_size = Section.VerneedV.size() * sizeof(Elf_Verneed) +
709 AuxCnt * sizeof(Elf_Vernaux);
710 SHeader.sh_info = Section.Info;
George Rimar0621b792019-02-19 14:53:48 +0000711
George Rimarda1b3ab2019-04-26 12:15:32 +0000712 return true;
George Rimar0621b792019-02-19 14:53:48 +0000713}
714
715template <class ELFT>
716bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000717 const ELFYAML::MipsABIFlags &Section,
718 ContiguousBlobAccumulator &CBA) {
Simon Atanasyan8eb9d1b2015-05-08 07:05:04 +0000719 assert(Section.Type == llvm::ELF::SHT_MIPS_ABIFLAGS &&
720 "Section type is not SHT_MIPS_ABIFLAGS");
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000721
722 object::Elf_Mips_ABIFlags<ELFT> Flags;
723 zero(Flags);
724 SHeader.sh_entsize = sizeof(Flags);
725 SHeader.sh_size = SHeader.sh_entsize;
726
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000727 auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000728 Flags.version = Section.Version;
729 Flags.isa_level = Section.ISALevel;
730 Flags.isa_rev = Section.ISARevision;
731 Flags.gpr_size = Section.GPRSize;
732 Flags.cpr1_size = Section.CPR1Size;
733 Flags.cpr2_size = Section.CPR2Size;
734 Flags.fp_abi = Section.FpABI;
735 Flags.isa_ext = Section.ISAExtension;
736 Flags.ases = Section.ASEs;
737 Flags.flags1 = Section.Flags1;
738 Flags.flags2 = Section.Flags2;
739 OS.write((const char *)&Flags, sizeof(Flags));
740
741 return true;
742}
743
George Rimar0e7ed912019-02-09 11:34:28 +0000744template <class ELFT>
James Hendersonfd997802019-02-25 11:02:24 +0000745bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
George Rimar0e7ed912019-02-09 11:34:28 +0000746 const ELFYAML::DynamicSection &Section,
747 ContiguousBlobAccumulator &CBA) {
George Rimard063c7d2019-02-20 13:58:43 +0000748 typedef typename ELFT::uint uintX_t;
749
George Rimar0e7ed912019-02-09 11:34:28 +0000750 assert(Section.Type == llvm::ELF::SHT_DYNAMIC &&
751 "Section type is not SHT_DYNAMIC");
752
James Hendersonfd997802019-02-25 11:02:24 +0000753 if (!Section.Entries.empty() && Section.Content) {
754 WithColor::error()
755 << "Cannot specify both raw content and explicit entries "
756 "for dynamic section '"
757 << Section.Name << "'.\n";
758 return false;
759 }
760
761 if (Section.Content)
762 SHeader.sh_size = Section.Content->binary_size();
763 else
764 SHeader.sh_size = 2 * sizeof(uintX_t) * Section.Entries.size();
George Rimar0e7ed912019-02-09 11:34:28 +0000765 if (Section.EntSize)
766 SHeader.sh_entsize = *Section.EntSize;
767 else
768 SHeader.sh_entsize = sizeof(Elf_Dyn);
769
George Rimard063c7d2019-02-20 13:58:43 +0000770 raw_ostream &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
George Rimar0e7ed912019-02-09 11:34:28 +0000771 for (const ELFYAML::DynamicEntry &DE : Section.Entries) {
George Rimard063c7d2019-02-20 13:58:43 +0000772 support::endian::write<uintX_t>(OS, DE.Tag, ELFT::TargetEndianness);
773 support::endian::write<uintX_t>(OS, DE.Val, ELFT::TargetEndianness);
George Rimar0e7ed912019-02-09 11:34:28 +0000774 }
James Hendersonfd997802019-02-25 11:02:24 +0000775 if (Section.Content)
776 Section.Content->writeAsBinary(OS);
777
778 return true;
George Rimar0e7ed912019-02-09 11:34:28 +0000779}
780
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000781template <class ELFT> bool ELFState<ELFT>::buildSectionIndex() {
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000782 for (unsigned i = 0, e = Doc.Sections.size(); i != e; ++i) {
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000783 StringRef Name = Doc.Sections[i]->Name;
Dave Lee17307d92017-11-09 14:53:43 +0000784 DotShStrtab.add(Name);
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000785 // "+ 1" to take into account the SHT_NULL entry.
786 if (SN2I.addName(Name, i + 1)) {
Jonas Devlieghere2cd41eb2018-04-21 21:11:59 +0000787 WithColor::error() << "Repeated section name: '" << Name
788 << "' at YAML section number " << i << ".\n";
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000789 return false;
790 }
Sean Silvaaff51252013-06-21 00:27:50 +0000791 }
Dave Lee17307d92017-11-09 14:53:43 +0000792
793 auto SecNo = 1 + Doc.Sections.size();
794 // Add special sections after input sections, if necessary.
George Rimar5fcdebe2019-04-26 13:09:11 +0000795 for (StringRef Name : implicitSectionNames())
Dave Lee17307d92017-11-09 14:53:43 +0000796 if (!SN2I.addName(Name, SecNo)) {
797 // Account for this section, since it wasn't in the Doc
798 ++SecNo;
799 DotShStrtab.add(Name);
800 }
801
802 DotShStrtab.finalize();
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000803 return true;
Sean Silva6b083882013-06-18 23:14:03 +0000804}
805
Sean Silvaf99309c2013-06-10 23:44:15 +0000806template <class ELFT>
George Rimar6da44ad2019-04-03 14:53:42 +0000807bool ELFState<ELFT>::buildSymbolIndex(ArrayRef<ELFYAML::Symbol> Symbols) {
808 bool GlobalSymbolSeen = false;
George Rimar33e498b2019-03-11 16:10:02 +0000809 std::size_t I = 0;
George Rimar6da44ad2019-04-03 14:53:42 +0000810 for (const auto &Sym : Symbols) {
811 ++I;
812
813 StringRef Name = Sym.Name;
814 if (Sym.Binding.value == ELF::STB_LOCAL && GlobalSymbolSeen) {
815 WithColor::error() << "Local symbol '" + Name +
816 "' after global in Symbols list.\n";
817 return false;
818 }
819 if (Sym.Binding.value != ELF::STB_LOCAL)
820 GlobalSymbolSeen = true;
821
822 if (!Name.empty() && SymN2I.addName(Name, I)) {
823 WithColor::error() << "Repeated symbol name: '" << Name << "'.\n";
824 return false;
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000825 }
826 }
827 return true;
828}
829
George Rimar0621b792019-02-19 14:53:48 +0000830template <class ELFT> void ELFState<ELFT>::finalizeStrings() {
George Rimar0621b792019-02-19 14:53:48 +0000831 // Add the regular symbol names to .strtab section.
George Rimar6da44ad2019-04-03 14:53:42 +0000832 for (const ELFYAML::Symbol &Sym : Doc.Symbols)
833 DotStrtab.add(Sym.Name);
George Rimar0621b792019-02-19 14:53:48 +0000834 DotStrtab.finalize();
835
George Rimar6da44ad2019-04-03 14:53:42 +0000836 if (Doc.DynamicSymbols.empty())
George Rimar0621b792019-02-19 14:53:48 +0000837 return;
838
839 // Add the dynamic symbol names to .dynstr section.
George Rimar6da44ad2019-04-03 14:53:42 +0000840 for (const ELFYAML::Symbol &Sym : Doc.DynamicSymbols)
841 DotDynstr.add(Sym.Name);
George Rimar0621b792019-02-19 14:53:48 +0000842
George Rimar623ae722019-02-21 12:21:43 +0000843 // SHT_GNU_verdef and SHT_GNU_verneed sections might also
844 // add strings to .dynstr section.
George Rimar0621b792019-02-19 14:53:48 +0000845 for (const std::unique_ptr<ELFYAML::Section> &Sec : Doc.Sections) {
George Rimar623ae722019-02-21 12:21:43 +0000846 if (auto VerNeed = dyn_cast<ELFYAML::VerneedSection>(Sec.get())) {
847 for (const ELFYAML::VerneedEntry &VE : VerNeed->VerneedV) {
848 DotDynstr.add(VE.File);
849 for (const ELFYAML::VernauxEntry &Aux : VE.AuxV)
850 DotDynstr.add(Aux.Name);
851 }
852 } else if (auto VerDef = dyn_cast<ELFYAML::VerdefSection>(Sec.get())) {
853 for (const ELFYAML::VerdefEntry &E : VerDef->Entries)
854 for (StringRef Name : E.VerNames)
855 DotDynstr.add(Name);
George Rimar0621b792019-02-19 14:53:48 +0000856 }
857 }
858
859 DotDynstr.finalize();
860}
861
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000862template <class ELFT>
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000863int ELFState<ELFT>::writeELF(raw_ostream &OS, const ELFYAML::Object &Doc) {
Simon Atanasyan220c54a2014-04-02 16:34:40 +0000864 ELFState<ELFT> State(Doc);
George Rimar0621b792019-02-19 14:53:48 +0000865
866 // Finalize .strtab and .dynstr sections. We do that early because want to
867 // finalize the string table builders before writing the content of the
868 // sections that might want to use them.
869 State.finalizeStrings();
870
Simon Atanasyan220c54a2014-04-02 16:34:40 +0000871 if (!State.buildSectionIndex())
872 return 1;
873
George Rimar33e498b2019-03-11 16:10:02 +0000874 if (!State.buildSymbolIndex(Doc.Symbols))
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000875 return 1;
876
Sean Silva38205932013-06-13 22:19:48 +0000877 Elf_Ehdr Header;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000878 State.initELFHeader(Header);
Sean Silvaf99309c2013-06-10 23:44:15 +0000879
Sean Silva38205932013-06-13 22:19:48 +0000880 // TODO: Flesh out section header support.
Petr Hosekeb04da32017-07-19 20:38:46 +0000881
882 std::vector<Elf_Phdr> PHeaders;
883 State.initProgramHeaders(PHeaders);
Sean Silva38205932013-06-13 22:19:48 +0000884
Sean Silva08a75ae2013-06-20 19:11:44 +0000885 // XXX: This offset is tightly coupled with the order that we write
886 // things to `OS`.
Petr Hosekeb04da32017-07-19 20:38:46 +0000887 const size_t SectionContentBeginOffset = Header.e_ehsize +
888 Header.e_phentsize * Header.e_phnum +
889 Header.e_shentsize * Header.e_shnum;
Sean Silva08a75ae2013-06-20 19:11:44 +0000890 ContiguousBlobAccumulator CBA(SectionContentBeginOffset);
Sean Silvac1c290b2013-06-20 20:59:34 +0000891
Sean Silva38205932013-06-13 22:19:48 +0000892 std::vector<Elf_Shdr> SHeaders;
George Rimarda1b3ab2019-04-26 12:15:32 +0000893 if (!State.initSectionHeaders(SHeaders, CBA))
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000894 return 1;
Sean Silva38205932013-06-13 22:19:48 +0000895
Dave Lee17307d92017-11-09 14:53:43 +0000896 // Populate SHeaders with implicit sections not present in the Doc
George Rimar5fcdebe2019-04-26 13:09:11 +0000897 for (StringRef Name : State.implicitSectionNames())
Dave Lee17307d92017-11-09 14:53:43 +0000898 if (State.SN2I.get(Name) >= SHeaders.size())
899 SHeaders.push_back({});
Sean Silva82177572013-06-22 01:38:00 +0000900
Dave Lee17307d92017-11-09 14:53:43 +0000901 // Initialize the implicit sections
902 auto Index = State.SN2I.get(".symtab");
Dave Lee67b49662017-11-16 18:10:15 +0000903 State.initSymtabSectionHeader(SHeaders[Index], SymtabType::Static, CBA);
Dave Lee17307d92017-11-09 14:53:43 +0000904 Index = State.SN2I.get(".strtab");
905 State.initStrtabSectionHeader(SHeaders[Index], ".strtab", State.DotStrtab, CBA);
906 Index = State.SN2I.get(".shstrtab");
907 State.initStrtabSectionHeader(SHeaders[Index], ".shstrtab", State.DotShStrtab, CBA);
George Rimar6da44ad2019-04-03 14:53:42 +0000908 if (!Doc.DynamicSymbols.empty()) {
Dave Lee67b49662017-11-16 18:10:15 +0000909 Index = State.SN2I.get(".dynsym");
910 State.initSymtabSectionHeader(SHeaders[Index], SymtabType::Dynamic, CBA);
911 SHeaders[Index].sh_flags |= ELF::SHF_ALLOC;
912 Index = State.SN2I.get(".dynstr");
913 State.initStrtabSectionHeader(SHeaders[Index], ".dynstr", State.DotDynstr, CBA);
914 SHeaders[Index].sh_flags |= ELF::SHF_ALLOC;
915 }
Sean Silvaf99309c2013-06-10 23:44:15 +0000916
Petr Hosekeb04da32017-07-19 20:38:46 +0000917 // Now we can decide segment offsets
918 State.setProgramHeaderLayout(PHeaders, SHeaders);
919
Sean Silvaf99309c2013-06-10 23:44:15 +0000920 OS.write((const char *)&Header, sizeof(Header));
Petr Hosekeb04da32017-07-19 20:38:46 +0000921 writeArrayData(OS, makeArrayRef(PHeaders));
Will Dietz0b48c732013-10-12 21:29:16 +0000922 writeArrayData(OS, makeArrayRef(SHeaders));
Sean Silva46dffff2013-06-13 22:20:01 +0000923 CBA.writeBlobToStream(OS);
Sean Silva415d93f2013-06-17 20:14:59 +0000924 return 0;
Sean Silvaf99309c2013-06-10 23:44:15 +0000925}
926
Xing GUObac78642018-12-07 11:04:22 +0000927template <class ELFT>
George Rimar5fcdebe2019-04-26 13:09:11 +0000928std::vector<StringRef> ELFState<ELFT>::implicitSectionNames() const {
George Rimar6da44ad2019-04-03 14:53:42 +0000929 if (Doc.DynamicSymbols.empty())
Dave Lee67b49662017-11-16 18:10:15 +0000930 return {".symtab", ".strtab", ".shstrtab"};
931 return {".symtab", ".strtab", ".shstrtab", ".dynsym", ".dynstr"};
932}
933
Sean Silva11caeba2013-06-22 01:03:35 +0000934static bool is64Bit(const ELFYAML::Object &Doc) {
935 return Doc.Header.Class == ELFYAML::ELF_ELFCLASS(ELF::ELFCLASS64);
936}
937
938static bool isLittleEndian(const ELFYAML::Object &Doc) {
939 return Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB);
940}
941
Chris Bieneman8ff0c112016-06-27 19:53:53 +0000942int yaml2elf(llvm::ELFYAML::Object &Doc, raw_ostream &Out) {
Sean Silva11caeba2013-06-22 01:03:35 +0000943 if (is64Bit(Doc)) {
944 if (isLittleEndian(Doc))
Rui Ueyama1b31eb92018-01-12 01:40:32 +0000945 return ELFState<object::ELF64LE>::writeELF(Out, Doc);
Sean Silvaf99309c2013-06-10 23:44:15 +0000946 else
Rui Ueyama1b31eb92018-01-12 01:40:32 +0000947 return ELFState<object::ELF64BE>::writeELF(Out, Doc);
Sean Silvaf99309c2013-06-10 23:44:15 +0000948 } else {
Sean Silva11caeba2013-06-22 01:03:35 +0000949 if (isLittleEndian(Doc))
Rui Ueyama1b31eb92018-01-12 01:40:32 +0000950 return ELFState<object::ELF32LE>::writeELF(Out, Doc);
Sean Silvaf99309c2013-06-10 23:44:15 +0000951 else
Rui Ueyama1b31eb92018-01-12 01:40:32 +0000952 return ELFState<object::ELF32BE>::writeELF(Out, Doc);
Sean Silvaf99309c2013-06-10 23:44:15 +0000953 }
Sean Silvaf99309c2013-06-10 23:44:15 +0000954}