blob: e3246bc29412a09726f9e9b40f39f967388883d2 [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 Rimar48288112019-04-29 11:54:10 +0000328 if (!IsStatic)
329 SHeader.sh_flags |= ELF::SHF_ALLOC;
George Rimarc1da1492019-04-26 12:45:54 +0000330
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000331 // One greater than symbol table index of the last local symbol.
George Rimarc1da1492019-04-26 12:45:54 +0000332 const auto &Symbols = IsStatic ? Doc.Symbols : Doc.DynamicSymbols;
George Rimar6da44ad2019-04-03 14:53:42 +0000333 SHeader.sh_info = findFirstNonGlobal(Symbols) + 1;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000334 SHeader.sh_entsize = sizeof(Elf_Sym);
Simon Atanasyan3a120922015-07-09 18:23:02 +0000335 SHeader.sh_addralign = 8;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000336
George Rimara7ba1a02019-03-01 10:18:16 +0000337 // Get the section index ignoring the SHT_NULL section.
338 unsigned SecNdx =
339 IsStatic ? getDotSymTabSecNo() - 1 : getDotDynSymSecNo() - 1;
340 // If the symbol table section is explicitly described in the YAML
341 // then we should set the fields requested.
342 if (SecNdx < Doc.Sections.size()) {
343 ELFYAML::Section *Sec = Doc.Sections[SecNdx].get();
344 SHeader.sh_addr = Sec->Address;
345 if (auto S = dyn_cast<ELFYAML::RawContentSection>(Sec))
346 SHeader.sh_info = S->Info;
George Rimar6947acd2019-02-19 12:15:04 +0000347 }
348
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000349 std::vector<Elf_Sym> Syms;
350 {
351 // Ensure STN_UNDEF is present
352 Elf_Sym Sym;
353 zero(Sym);
354 Syms.push_back(Sym);
355 }
Hans Wennborg59f0cba2014-04-30 19:38:09 +0000356
George Rimarc1da1492019-04-26 12:45:54 +0000357 addSymbols(Symbols, Syms, IsStatic ? DotStrtab : DotDynstr);
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000358
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000359 writeArrayData(
360 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign),
361 makeArrayRef(Syms));
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000362 SHeader.sh_size = arrayDataSize(makeArrayRef(Syms));
363}
364
365template <class ELFT>
366void ELFState<ELFT>::initStrtabSectionHeader(Elf_Shdr &SHeader, StringRef Name,
367 StringTableBuilder &STB,
368 ContiguousBlobAccumulator &CBA) {
369 zero(SHeader);
Hans Wennborg59f0cba2014-04-30 19:38:09 +0000370 SHeader.sh_name = DotShStrtab.getOffset(Name);
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000371 SHeader.sh_type = ELF::SHT_STRTAB;
Rafael Espindola39751af2016-10-04 22:43:25 +0000372 STB.write(CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign));
373 SHeader.sh_size = STB.getSize();
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000374 SHeader.sh_addralign = 1;
George Rimar6947acd2019-02-19 12:15:04 +0000375
376 // If .dynstr section is explicitly described in the YAML
377 // then we want to use its section address.
378 if (Name == ".dynstr") {
379 // Take section index and ignore the SHT_NULL section.
380 unsigned SecNdx = getDotDynStrSecNo() - 1;
381 if (SecNdx < Doc.Sections.size())
382 SHeader.sh_addr = Doc.Sections[SecNdx]->Address;
George Rimar48288112019-04-29 11:54:10 +0000383
384 // We assume that .dynstr is always allocatable.
385 SHeader.sh_flags |= ELF::SHF_ALLOC;
George Rimar6947acd2019-02-19 12:15:04 +0000386 }
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000387}
388
389template <class ELFT>
Petr Hosekeb04da32017-07-19 20:38:46 +0000390void ELFState<ELFT>::setProgramHeaderLayout(std::vector<Elf_Phdr> &PHeaders,
391 std::vector<Elf_Shdr> &SHeaders) {
392 uint32_t PhdrIdx = 0;
393 for (auto &YamlPhdr : Doc.ProgramHeaders) {
394 auto &PHeader = PHeaders[PhdrIdx++];
395
James Hendersonb10f48b2019-03-15 10:35:27 +0000396 if (YamlPhdr.Offset) {
397 PHeader.p_offset = *YamlPhdr.Offset;
398 } else {
399 if (YamlPhdr.Sections.size())
400 PHeader.p_offset = UINT32_MAX;
Petr Hosekeb04da32017-07-19 20:38:46 +0000401 else
James Hendersonb10f48b2019-03-15 10:35:27 +0000402 PHeader.p_offset = 0;
403
404 // Find the minimum offset for the program header.
405 for (auto SecName : YamlPhdr.Sections) {
406 uint32_t Index = 0;
407 SN2I.lookup(SecName.Section, Index);
408 const auto &SHeader = SHeaders[Index];
409 PHeader.p_offset = std::min(PHeader.p_offset, SHeader.sh_offset);
410 }
Petr Hosekeb04da32017-07-19 20:38:46 +0000411 }
412
James Hendersonb10f48b2019-03-15 10:35:27 +0000413 // Find the maximum offset of the end of a section in order to set p_filesz,
414 // if not set explicitly.
415 if (YamlPhdr.FileSize) {
416 PHeader.p_filesz = *YamlPhdr.FileSize;
417 } else {
418 PHeader.p_filesz = 0;
419 for (auto SecName : YamlPhdr.Sections) {
420 uint32_t Index = 0;
421 SN2I.lookup(SecName.Section, Index);
422 const auto &SHeader = SHeaders[Index];
423 uint64_t EndOfSection;
424 if (SHeader.sh_type == llvm::ELF::SHT_NOBITS)
425 EndOfSection = SHeader.sh_offset;
426 else
427 EndOfSection = SHeader.sh_offset + SHeader.sh_size;
428 uint64_t EndOfSegment = PHeader.p_offset + PHeader.p_filesz;
429 EndOfSegment = std::max(EndOfSegment, EndOfSection);
430 PHeader.p_filesz = EndOfSegment - PHeader.p_offset;
431 }
432 }
433
434 // If not set explicitly, find the memory size by adding the size of
435 // sections at the end of the segment. These should be empty (size of zero)
436 // and NOBITS sections.
437 if (YamlPhdr.MemSize) {
438 PHeader.p_memsz = *YamlPhdr.MemSize;
439 } else {
440 PHeader.p_memsz = PHeader.p_filesz;
441 for (auto SecName : YamlPhdr.Sections) {
442 uint32_t Index = 0;
443 SN2I.lookup(SecName.Section, Index);
444 const auto &SHeader = SHeaders[Index];
445 if (SHeader.sh_offset == PHeader.p_offset + PHeader.p_filesz)
446 PHeader.p_memsz += SHeader.sh_size;
447 }
Petr Hosekeb04da32017-07-19 20:38:46 +0000448 }
449
450 // Set the alignment of the segment to be the same as the maximum alignment
Jake Ehrlich03aeeb092017-11-01 23:14:48 +0000451 // of the sections with the same offset so that by default the segment
Petr Hosekeb04da32017-07-19 20:38:46 +0000452 // has a valid and sensible alignment.
Jake Ehrlich03aeeb092017-11-01 23:14:48 +0000453 if (YamlPhdr.Align) {
454 PHeader.p_align = *YamlPhdr.Align;
455 } else {
456 PHeader.p_align = 1;
457 for (auto SecName : YamlPhdr.Sections) {
458 uint32_t Index = 0;
459 SN2I.lookup(SecName.Section, Index);
460 const auto &SHeader = SHeaders[Index];
461 if (SHeader.sh_offset == PHeader.p_offset)
462 PHeader.p_align = std::max(PHeader.p_align, SHeader.sh_addralign);
463 }
Petr Hosekeb04da32017-07-19 20:38:46 +0000464 }
465 }
466}
467
468template <class ELFT>
George Rimar6da44ad2019-04-03 14:53:42 +0000469void ELFState<ELFT>::addSymbols(ArrayRef<ELFYAML::Symbol> Symbols,
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000470 std::vector<Elf_Sym> &Syms,
Dave Lee67b49662017-11-16 18:10:15 +0000471 const StringTableBuilder &Strtab) {
Simon Atanasyan048baca2014-03-14 06:53:30 +0000472 for (const auto &Sym : Symbols) {
Sean Silva6b083882013-06-18 23:14:03 +0000473 Elf_Sym Symbol;
474 zero(Symbol);
475 if (!Sym.Name.empty())
Dave Lee67b49662017-11-16 18:10:15 +0000476 Symbol.st_name = Strtab.getOffset(Sym.Name);
George Rimar6da44ad2019-04-03 14:53:42 +0000477 Symbol.setBindingAndType(Sym.Binding, Sym.Type);
Sean Silvac4afa6d2013-06-21 01:11:48 +0000478 if (!Sym.Section.empty()) {
479 unsigned Index;
Simon Atanasyan35babf92014-04-06 09:02:55 +0000480 if (SN2I.lookup(Sym.Section, Index)) {
Jonas Devlieghere2cd41eb2018-04-21 21:11:59 +0000481 WithColor::error() << "Unknown section referenced: '" << Sym.Section
482 << "' by YAML symbol " << Sym.Name << ".\n";
Sean Silvac4afa6d2013-06-21 01:11:48 +0000483 exit(1);
484 }
485 Symbol.st_shndx = Index;
Petr Hosek5c469a32017-09-07 20:44:16 +0000486 } else if (Sym.Index) {
487 Symbol.st_shndx = *Sym.Index;
488 }
489 // else Symbol.st_shndex == SHN_UNDEF (== 0), since it was zero'd earlier.
Sean Silva05001b92013-06-20 20:59:47 +0000490 Symbol.st_value = Sym.Value;
Simon Atanasyan60e1a792014-11-06 22:46:24 +0000491 Symbol.st_other = Sym.Other;
Sean Silva05001b92013-06-20 20:59:47 +0000492 Symbol.st_size = Sym.Size;
Sean Silva6b083882013-06-18 23:14:03 +0000493 Syms.push_back(Symbol);
494 }
Sean Silvaaff51252013-06-21 00:27:50 +0000495}
496
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000497template <class ELFT>
George Rimarda1b3ab2019-04-26 12:15:32 +0000498bool ELFState<ELFT>::writeSectionContent(
George Rimarb49e1922019-04-24 13:02:15 +0000499 Elf_Shdr &SHeader, const ELFYAML::RawContentSection &Section,
500 ContiguousBlobAccumulator &CBA) {
Simon Atanasyanb83f3802014-05-16 16:01:00 +0000501 assert(Section.Size >= Section.Content.binary_size() &&
502 "Section size and section content are inconsistent");
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000503 raw_ostream &OS =
504 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
Simon Atanasyanb83f3802014-05-16 16:01:00 +0000505 Section.Content.writeAsBinary(OS);
George Rimarb49e1922019-04-24 13:02:15 +0000506 OS.write_zeros(Section.Size - Section.Content.binary_size());
507
George Rimar65a68282018-08-07 08:11:38 +0000508 if (Section.EntSize)
509 SHeader.sh_entsize = *Section.EntSize;
510 else if (Section.Type == llvm::ELF::SHT_RELR)
Jake Ehrlich0f440d82018-06-28 21:07:34 +0000511 SHeader.sh_entsize = sizeof(Elf_Relr);
512 else
513 SHeader.sh_entsize = 0;
Simon Atanasyanb83f3802014-05-16 16:01:00 +0000514 SHeader.sh_size = Section.Size;
George Rimara7ba1a02019-03-01 10:18:16 +0000515 SHeader.sh_info = Section.Info;
George Rimarda1b3ab2019-04-26 12:15:32 +0000516 return true;
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000517}
518
Simon Atanasyan5d19c672015-01-25 13:29:25 +0000519static bool isMips64EL(const ELFYAML::Object &Doc) {
520 return Doc.Header.Machine == ELFYAML::ELF_EM(llvm::ELF::EM_MIPS) &&
521 Doc.Header.Class == ELFYAML::ELF_ELFCLASS(ELF::ELFCLASS64) &&
522 Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB);
523}
524
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000525template <class ELFT>
526bool
527ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
528 const ELFYAML::RelocationSection &Section,
529 ContiguousBlobAccumulator &CBA) {
Simon Atanasyan8eb9d1b2015-05-08 07:05:04 +0000530 assert((Section.Type == llvm::ELF::SHT_REL ||
531 Section.Type == llvm::ELF::SHT_RELA) &&
532 "Section type is not SHT_REL nor SHT_RELA");
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000533
534 bool IsRela = Section.Type == llvm::ELF::SHT_RELA;
535 SHeader.sh_entsize = IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
536 SHeader.sh_size = SHeader.sh_entsize * Section.Relocations.size();
537
George Rimarda1b3ab2019-04-26 12:15:32 +0000538 // For relocation section set link to .symtab by default.
539 if (Section.Link.empty())
540 SHeader.sh_link = getDotSymTabSecNo();
541
542 unsigned Index = 0;
543 if (!Section.RelocatableSec.empty() &&
544 !convertSectionIndex(SN2I, Section.Name, Section.RelocatableSec, Index))
545 return false;
546 SHeader.sh_info = Index;
547
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000548 auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000549
550 for (const auto &Rel : Section.Relocations) {
Adhemerval Zanella9f3dbff2015-04-22 15:26:43 +0000551 unsigned SymIdx = 0;
James Henderson9bc817a2019-03-12 17:00:25 +0000552 // If a relocation references a symbol, try to look one up in the symbol
553 // table. If it is not there, treat the value as a symbol index.
554 if (Rel.Symbol && SymN2I.lookup(*Rel.Symbol, SymIdx) &&
555 !to_integer(*Rel.Symbol, SymIdx)) {
556 WithColor::error() << "Unknown symbol referenced: '" << *Rel.Symbol
557 << "' at YAML section '" << Section.Name << "'.\n";
558 return false;
559 }
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000560
561 if (IsRela) {
562 Elf_Rela REntry;
563 zero(REntry);
564 REntry.r_offset = Rel.Offset;
565 REntry.r_addend = Rel.Addend;
Simon Atanasyan5d19c672015-01-25 13:29:25 +0000566 REntry.setSymbolAndType(SymIdx, Rel.Type, isMips64EL(Doc));
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000567 OS.write((const char *)&REntry, sizeof(REntry));
568 } else {
569 Elf_Rel REntry;
570 zero(REntry);
571 REntry.r_offset = Rel.Offset;
Simon Atanasyan5d19c672015-01-25 13:29:25 +0000572 REntry.setSymbolAndType(SymIdx, Rel.Type, isMips64EL(Doc));
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000573 OS.write((const char *)&REntry, sizeof(REntry));
574 }
575 }
576 return true;
577}
578
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000579template <class ELFT>
580bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
581 const ELFYAML::Group &Section,
582 ContiguousBlobAccumulator &CBA) {
Simon Atanasyan8eb9d1b2015-05-08 07:05:04 +0000583 assert(Section.Type == llvm::ELF::SHT_GROUP &&
584 "Section type is not SHT_GROUP");
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000585
George Rimard063c7d2019-02-20 13:58:43 +0000586 SHeader.sh_entsize = 4;
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000587 SHeader.sh_size = SHeader.sh_entsize * Section.Members.size();
588
George Rimarda1b3ab2019-04-26 12:15:32 +0000589 unsigned SymIdx;
590 if (SymN2I.lookup(Section.Signature, SymIdx) &&
591 !to_integer(Section.Signature, SymIdx)) {
592 WithColor::error() << "Unknown symbol referenced: '" << Section.Signature
593 << "' at YAML section '" << Section.Name << "'.\n";
594 return false;
595 }
596 SHeader.sh_info = SymIdx;
597
George Rimard063c7d2019-02-20 13:58:43 +0000598 raw_ostream &OS =
599 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000600
George Rimarfb7780a2019-04-26 12:20:51 +0000601 for (const ELFYAML::SectionOrType &Member : Section.Members) {
602 unsigned int SectionIndex = 0;
603 if (Member.sectionNameOrType == "GRP_COMDAT")
604 SectionIndex = llvm::ELF::GRP_COMDAT;
605 else if (!convertSectionIndex(SN2I, Section.Name, Member.sectionNameOrType,
606 SectionIndex))
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000607 return false;
George Rimarfb7780a2019-04-26 12:20:51 +0000608 support::endian::write<uint32_t>(OS, SectionIndex, ELFT::TargetEndianness);
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000609 }
610 return true;
611}
612
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000613template <class ELFT>
614bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
George Rimar646af082019-02-19 15:29:07 +0000615 const ELFYAML::SymverSection &Section,
616 ContiguousBlobAccumulator &CBA) {
George Rimar646af082019-02-19 15:29:07 +0000617 raw_ostream &OS =
618 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
George Rimardac37fb2019-02-20 14:01:02 +0000619 for (uint16_t Version : Section.Entries)
620 support::endian::write<uint16_t>(OS, Version, ELFT::TargetEndianness);
George Rimar646af082019-02-19 15:29:07 +0000621
George Rimard063c7d2019-02-20 13:58:43 +0000622 SHeader.sh_entsize = 2;
623 SHeader.sh_size = Section.Entries.size() * SHeader.sh_entsize;
George Rimar646af082019-02-19 15:29:07 +0000624 return true;
625}
626
627template <class ELFT>
628bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
George Rimar623ae722019-02-21 12:21:43 +0000629 const ELFYAML::VerdefSection &Section,
630 ContiguousBlobAccumulator &CBA) {
631 typedef typename ELFT::Verdef Elf_Verdef;
632 typedef typename ELFT::Verdaux Elf_Verdaux;
633 raw_ostream &OS =
634 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
635
636 uint64_t AuxCnt = 0;
637 for (size_t I = 0; I < Section.Entries.size(); ++I) {
638 const ELFYAML::VerdefEntry &E = Section.Entries[I];
639
640 Elf_Verdef VerDef;
641 VerDef.vd_version = E.Version;
642 VerDef.vd_flags = E.Flags;
643 VerDef.vd_ndx = E.VersionNdx;
644 VerDef.vd_hash = E.Hash;
645 VerDef.vd_aux = sizeof(Elf_Verdef);
646 VerDef.vd_cnt = E.VerNames.size();
647 if (I == Section.Entries.size() - 1)
648 VerDef.vd_next = 0;
649 else
650 VerDef.vd_next =
651 sizeof(Elf_Verdef) + E.VerNames.size() * sizeof(Elf_Verdaux);
652 OS.write((const char *)&VerDef, sizeof(Elf_Verdef));
653
654 for (size_t J = 0; J < E.VerNames.size(); ++J, ++AuxCnt) {
655 Elf_Verdaux VernAux;
656 VernAux.vda_name = DotDynstr.getOffset(E.VerNames[J]);
657 if (J == E.VerNames.size() - 1)
658 VernAux.vda_next = 0;
659 else
660 VernAux.vda_next = sizeof(Elf_Verdaux);
661 OS.write((const char *)&VernAux, sizeof(Elf_Verdaux));
662 }
663 }
664
665 SHeader.sh_size = Section.Entries.size() * sizeof(Elf_Verdef) +
666 AuxCnt * sizeof(Elf_Verdaux);
667 SHeader.sh_info = Section.Info;
668
669 return true;
670}
671
672template <class ELFT>
673bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
George Rimar0621b792019-02-19 14:53:48 +0000674 const ELFYAML::VerneedSection &Section,
675 ContiguousBlobAccumulator &CBA) {
George Rimarda1b3ab2019-04-26 12:15:32 +0000676 typedef typename ELFT::Verneed Elf_Verneed;
677 typedef typename ELFT::Vernaux Elf_Vernaux;
George Rimar0621b792019-02-19 14:53:48 +0000678
George Rimarda1b3ab2019-04-26 12:15:32 +0000679 auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
George Rimar0621b792019-02-19 14:53:48 +0000680
George Rimarda1b3ab2019-04-26 12:15:32 +0000681 uint64_t AuxCnt = 0;
682 for (size_t I = 0; I < Section.VerneedV.size(); ++I) {
683 const ELFYAML::VerneedEntry &VE = Section.VerneedV[I];
George Rimar0621b792019-02-19 14:53:48 +0000684
George Rimarda1b3ab2019-04-26 12:15:32 +0000685 Elf_Verneed VerNeed;
686 VerNeed.vn_version = VE.Version;
687 VerNeed.vn_file = DotDynstr.getOffset(VE.File);
688 if (I == Section.VerneedV.size() - 1)
689 VerNeed.vn_next = 0;
690 else
691 VerNeed.vn_next =
692 sizeof(Elf_Verneed) + VE.AuxV.size() * sizeof(Elf_Vernaux);
693 VerNeed.vn_cnt = VE.AuxV.size();
694 VerNeed.vn_aux = sizeof(Elf_Verneed);
695 OS.write((const char *)&VerNeed, sizeof(Elf_Verneed));
George Rimar0621b792019-02-19 14:53:48 +0000696
George Rimarda1b3ab2019-04-26 12:15:32 +0000697 for (size_t J = 0; J < VE.AuxV.size(); ++J, ++AuxCnt) {
698 const ELFYAML::VernauxEntry &VAuxE = VE.AuxV[J];
George Rimar0621b792019-02-19 14:53:48 +0000699
George Rimarda1b3ab2019-04-26 12:15:32 +0000700 Elf_Vernaux VernAux;
701 VernAux.vna_hash = VAuxE.Hash;
702 VernAux.vna_flags = VAuxE.Flags;
703 VernAux.vna_other = VAuxE.Other;
704 VernAux.vna_name = DotDynstr.getOffset(VAuxE.Name);
705 if (J == VE.AuxV.size() - 1)
706 VernAux.vna_next = 0;
707 else
708 VernAux.vna_next = sizeof(Elf_Vernaux);
709 OS.write((const char *)&VernAux, sizeof(Elf_Vernaux));
710 }
711 }
George Rimar0621b792019-02-19 14:53:48 +0000712
George Rimarda1b3ab2019-04-26 12:15:32 +0000713 SHeader.sh_size = Section.VerneedV.size() * sizeof(Elf_Verneed) +
714 AuxCnt * sizeof(Elf_Vernaux);
715 SHeader.sh_info = Section.Info;
George Rimar0621b792019-02-19 14:53:48 +0000716
George Rimarda1b3ab2019-04-26 12:15:32 +0000717 return true;
George Rimar0621b792019-02-19 14:53:48 +0000718}
719
720template <class ELFT>
721bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000722 const ELFYAML::MipsABIFlags &Section,
723 ContiguousBlobAccumulator &CBA) {
Simon Atanasyan8eb9d1b2015-05-08 07:05:04 +0000724 assert(Section.Type == llvm::ELF::SHT_MIPS_ABIFLAGS &&
725 "Section type is not SHT_MIPS_ABIFLAGS");
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000726
727 object::Elf_Mips_ABIFlags<ELFT> Flags;
728 zero(Flags);
729 SHeader.sh_entsize = sizeof(Flags);
730 SHeader.sh_size = SHeader.sh_entsize;
731
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000732 auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000733 Flags.version = Section.Version;
734 Flags.isa_level = Section.ISALevel;
735 Flags.isa_rev = Section.ISARevision;
736 Flags.gpr_size = Section.GPRSize;
737 Flags.cpr1_size = Section.CPR1Size;
738 Flags.cpr2_size = Section.CPR2Size;
739 Flags.fp_abi = Section.FpABI;
740 Flags.isa_ext = Section.ISAExtension;
741 Flags.ases = Section.ASEs;
742 Flags.flags1 = Section.Flags1;
743 Flags.flags2 = Section.Flags2;
744 OS.write((const char *)&Flags, sizeof(Flags));
745
746 return true;
747}
748
George Rimar0e7ed912019-02-09 11:34:28 +0000749template <class ELFT>
James Hendersonfd997802019-02-25 11:02:24 +0000750bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
George Rimar0e7ed912019-02-09 11:34:28 +0000751 const ELFYAML::DynamicSection &Section,
752 ContiguousBlobAccumulator &CBA) {
George Rimard063c7d2019-02-20 13:58:43 +0000753 typedef typename ELFT::uint uintX_t;
754
George Rimar0e7ed912019-02-09 11:34:28 +0000755 assert(Section.Type == llvm::ELF::SHT_DYNAMIC &&
756 "Section type is not SHT_DYNAMIC");
757
James Hendersonfd997802019-02-25 11:02:24 +0000758 if (!Section.Entries.empty() && Section.Content) {
759 WithColor::error()
760 << "Cannot specify both raw content and explicit entries "
761 "for dynamic section '"
762 << Section.Name << "'.\n";
763 return false;
764 }
765
766 if (Section.Content)
767 SHeader.sh_size = Section.Content->binary_size();
768 else
769 SHeader.sh_size = 2 * sizeof(uintX_t) * Section.Entries.size();
George Rimar0e7ed912019-02-09 11:34:28 +0000770 if (Section.EntSize)
771 SHeader.sh_entsize = *Section.EntSize;
772 else
773 SHeader.sh_entsize = sizeof(Elf_Dyn);
774
George Rimard063c7d2019-02-20 13:58:43 +0000775 raw_ostream &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
George Rimar0e7ed912019-02-09 11:34:28 +0000776 for (const ELFYAML::DynamicEntry &DE : Section.Entries) {
George Rimard063c7d2019-02-20 13:58:43 +0000777 support::endian::write<uintX_t>(OS, DE.Tag, ELFT::TargetEndianness);
778 support::endian::write<uintX_t>(OS, DE.Val, ELFT::TargetEndianness);
George Rimar0e7ed912019-02-09 11:34:28 +0000779 }
James Hendersonfd997802019-02-25 11:02:24 +0000780 if (Section.Content)
781 Section.Content->writeAsBinary(OS);
782
783 return true;
George Rimar0e7ed912019-02-09 11:34:28 +0000784}
785
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000786template <class ELFT> bool ELFState<ELFT>::buildSectionIndex() {
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000787 for (unsigned i = 0, e = Doc.Sections.size(); i != e; ++i) {
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000788 StringRef Name = Doc.Sections[i]->Name;
Dave Lee17307d92017-11-09 14:53:43 +0000789 DotShStrtab.add(Name);
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000790 // "+ 1" to take into account the SHT_NULL entry.
791 if (SN2I.addName(Name, i + 1)) {
Jonas Devlieghere2cd41eb2018-04-21 21:11:59 +0000792 WithColor::error() << "Repeated section name: '" << Name
793 << "' at YAML section number " << i << ".\n";
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000794 return false;
795 }
Sean Silvaaff51252013-06-21 00:27:50 +0000796 }
Dave Lee17307d92017-11-09 14:53:43 +0000797
798 auto SecNo = 1 + Doc.Sections.size();
799 // Add special sections after input sections, if necessary.
George Rimar5fcdebe2019-04-26 13:09:11 +0000800 for (StringRef Name : implicitSectionNames())
Dave Lee17307d92017-11-09 14:53:43 +0000801 if (!SN2I.addName(Name, SecNo)) {
802 // Account for this section, since it wasn't in the Doc
803 ++SecNo;
804 DotShStrtab.add(Name);
805 }
806
807 DotShStrtab.finalize();
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000808 return true;
Sean Silva6b083882013-06-18 23:14:03 +0000809}
810
Sean Silvaf99309c2013-06-10 23:44:15 +0000811template <class ELFT>
George Rimar6da44ad2019-04-03 14:53:42 +0000812bool ELFState<ELFT>::buildSymbolIndex(ArrayRef<ELFYAML::Symbol> Symbols) {
813 bool GlobalSymbolSeen = false;
George Rimar33e498b2019-03-11 16:10:02 +0000814 std::size_t I = 0;
George Rimar6da44ad2019-04-03 14:53:42 +0000815 for (const auto &Sym : Symbols) {
816 ++I;
817
818 StringRef Name = Sym.Name;
819 if (Sym.Binding.value == ELF::STB_LOCAL && GlobalSymbolSeen) {
820 WithColor::error() << "Local symbol '" + Name +
821 "' after global in Symbols list.\n";
822 return false;
823 }
824 if (Sym.Binding.value != ELF::STB_LOCAL)
825 GlobalSymbolSeen = true;
826
827 if (!Name.empty() && SymN2I.addName(Name, I)) {
828 WithColor::error() << "Repeated symbol name: '" << Name << "'.\n";
829 return false;
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000830 }
831 }
832 return true;
833}
834
George Rimar0621b792019-02-19 14:53:48 +0000835template <class ELFT> void ELFState<ELFT>::finalizeStrings() {
George Rimar0621b792019-02-19 14:53:48 +0000836 // Add the regular symbol names to .strtab section.
George Rimar6da44ad2019-04-03 14:53:42 +0000837 for (const ELFYAML::Symbol &Sym : Doc.Symbols)
838 DotStrtab.add(Sym.Name);
George Rimar0621b792019-02-19 14:53:48 +0000839 DotStrtab.finalize();
840
George Rimar6da44ad2019-04-03 14:53:42 +0000841 if (Doc.DynamicSymbols.empty())
George Rimar0621b792019-02-19 14:53:48 +0000842 return;
843
844 // Add the dynamic symbol names to .dynstr section.
George Rimar6da44ad2019-04-03 14:53:42 +0000845 for (const ELFYAML::Symbol &Sym : Doc.DynamicSymbols)
846 DotDynstr.add(Sym.Name);
George Rimar0621b792019-02-19 14:53:48 +0000847
George Rimar623ae722019-02-21 12:21:43 +0000848 // SHT_GNU_verdef and SHT_GNU_verneed sections might also
849 // add strings to .dynstr section.
George Rimar0621b792019-02-19 14:53:48 +0000850 for (const std::unique_ptr<ELFYAML::Section> &Sec : Doc.Sections) {
George Rimar623ae722019-02-21 12:21:43 +0000851 if (auto VerNeed = dyn_cast<ELFYAML::VerneedSection>(Sec.get())) {
852 for (const ELFYAML::VerneedEntry &VE : VerNeed->VerneedV) {
853 DotDynstr.add(VE.File);
854 for (const ELFYAML::VernauxEntry &Aux : VE.AuxV)
855 DotDynstr.add(Aux.Name);
856 }
857 } else if (auto VerDef = dyn_cast<ELFYAML::VerdefSection>(Sec.get())) {
858 for (const ELFYAML::VerdefEntry &E : VerDef->Entries)
859 for (StringRef Name : E.VerNames)
860 DotDynstr.add(Name);
George Rimar0621b792019-02-19 14:53:48 +0000861 }
862 }
863
864 DotDynstr.finalize();
865}
866
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000867template <class ELFT>
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000868int ELFState<ELFT>::writeELF(raw_ostream &OS, const ELFYAML::Object &Doc) {
Simon Atanasyan220c54a2014-04-02 16:34:40 +0000869 ELFState<ELFT> State(Doc);
George Rimar0621b792019-02-19 14:53:48 +0000870
871 // Finalize .strtab and .dynstr sections. We do that early because want to
872 // finalize the string table builders before writing the content of the
873 // sections that might want to use them.
874 State.finalizeStrings();
875
Simon Atanasyan220c54a2014-04-02 16:34:40 +0000876 if (!State.buildSectionIndex())
877 return 1;
878
George Rimar33e498b2019-03-11 16:10:02 +0000879 if (!State.buildSymbolIndex(Doc.Symbols))
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000880 return 1;
881
Sean Silva38205932013-06-13 22:19:48 +0000882 Elf_Ehdr Header;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000883 State.initELFHeader(Header);
Sean Silvaf99309c2013-06-10 23:44:15 +0000884
Sean Silva38205932013-06-13 22:19:48 +0000885 // TODO: Flesh out section header support.
Petr Hosekeb04da32017-07-19 20:38:46 +0000886
887 std::vector<Elf_Phdr> PHeaders;
888 State.initProgramHeaders(PHeaders);
Sean Silva38205932013-06-13 22:19:48 +0000889
Sean Silva08a75ae2013-06-20 19:11:44 +0000890 // XXX: This offset is tightly coupled with the order that we write
891 // things to `OS`.
Petr Hosekeb04da32017-07-19 20:38:46 +0000892 const size_t SectionContentBeginOffset = Header.e_ehsize +
893 Header.e_phentsize * Header.e_phnum +
894 Header.e_shentsize * Header.e_shnum;
Sean Silva08a75ae2013-06-20 19:11:44 +0000895 ContiguousBlobAccumulator CBA(SectionContentBeginOffset);
Sean Silvac1c290b2013-06-20 20:59:34 +0000896
Sean Silva38205932013-06-13 22:19:48 +0000897 std::vector<Elf_Shdr> SHeaders;
George Rimarda1b3ab2019-04-26 12:15:32 +0000898 if (!State.initSectionHeaders(SHeaders, CBA))
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000899 return 1;
Sean Silva38205932013-06-13 22:19:48 +0000900
Dave Lee17307d92017-11-09 14:53:43 +0000901 // Populate SHeaders with implicit sections not present in the Doc
George Rimar5fcdebe2019-04-26 13:09:11 +0000902 for (StringRef Name : State.implicitSectionNames())
Dave Lee17307d92017-11-09 14:53:43 +0000903 if (State.SN2I.get(Name) >= SHeaders.size())
904 SHeaders.push_back({});
Sean Silva82177572013-06-22 01:38:00 +0000905
Dave Lee17307d92017-11-09 14:53:43 +0000906 // Initialize the implicit sections
George Rimar48288112019-04-29 11:54:10 +0000907 State.initSymtabSectionHeader(SHeaders[State.SN2I.get(".symtab")],
908 SymtabType::Static, CBA);
909 State.initStrtabSectionHeader(SHeaders[State.SN2I.get(".strtab")], ".strtab",
910 State.DotStrtab, CBA);
911 State.initStrtabSectionHeader(SHeaders[State.SN2I.get(".shstrtab")],
912 ".shstrtab", State.DotShStrtab, CBA);
George Rimar6da44ad2019-04-03 14:53:42 +0000913 if (!Doc.DynamicSymbols.empty()) {
George Rimar48288112019-04-29 11:54:10 +0000914 State.initSymtabSectionHeader(SHeaders[State.SN2I.get(".dynsym")],
915 SymtabType::Dynamic, CBA);
916 State.initStrtabSectionHeader(SHeaders[State.SN2I.get(".dynstr")],
917 ".dynstr", State.DotDynstr, CBA);
Dave Lee67b49662017-11-16 18:10:15 +0000918 }
Sean Silvaf99309c2013-06-10 23:44:15 +0000919
Petr Hosekeb04da32017-07-19 20:38:46 +0000920 // Now we can decide segment offsets
921 State.setProgramHeaderLayout(PHeaders, SHeaders);
922
Sean Silvaf99309c2013-06-10 23:44:15 +0000923 OS.write((const char *)&Header, sizeof(Header));
Petr Hosekeb04da32017-07-19 20:38:46 +0000924 writeArrayData(OS, makeArrayRef(PHeaders));
Will Dietz0b48c732013-10-12 21:29:16 +0000925 writeArrayData(OS, makeArrayRef(SHeaders));
Sean Silva46dffff2013-06-13 22:20:01 +0000926 CBA.writeBlobToStream(OS);
Sean Silva415d93f2013-06-17 20:14:59 +0000927 return 0;
Sean Silvaf99309c2013-06-10 23:44:15 +0000928}
929
Xing GUObac78642018-12-07 11:04:22 +0000930template <class ELFT>
George Rimar5fcdebe2019-04-26 13:09:11 +0000931std::vector<StringRef> ELFState<ELFT>::implicitSectionNames() const {
George Rimar6da44ad2019-04-03 14:53:42 +0000932 if (Doc.DynamicSymbols.empty())
Dave Lee67b49662017-11-16 18:10:15 +0000933 return {".symtab", ".strtab", ".shstrtab"};
934 return {".symtab", ".strtab", ".shstrtab", ".dynsym", ".dynstr"};
935}
936
Sean Silva11caeba2013-06-22 01:03:35 +0000937static bool is64Bit(const ELFYAML::Object &Doc) {
938 return Doc.Header.Class == ELFYAML::ELF_ELFCLASS(ELF::ELFCLASS64);
939}
940
941static bool isLittleEndian(const ELFYAML::Object &Doc) {
942 return Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB);
943}
944
Chris Bieneman8ff0c112016-06-27 19:53:53 +0000945int yaml2elf(llvm::ELFYAML::Object &Doc, raw_ostream &Out) {
Sean Silva11caeba2013-06-22 01:03:35 +0000946 if (is64Bit(Doc)) {
947 if (isLittleEndian(Doc))
Rui Ueyama1b31eb92018-01-12 01:40:32 +0000948 return ELFState<object::ELF64LE>::writeELF(Out, Doc);
Sean Silvaf99309c2013-06-10 23:44:15 +0000949 else
Rui Ueyama1b31eb92018-01-12 01:40:32 +0000950 return ELFState<object::ELF64BE>::writeELF(Out, Doc);
Sean Silvaf99309c2013-06-10 23:44:15 +0000951 } else {
Sean Silva11caeba2013-06-22 01:03:35 +0000952 if (isLittleEndian(Doc))
Rui Ueyama1b31eb92018-01-12 01:40:32 +0000953 return ELFState<object::ELF32LE>::writeELF(Out, Doc);
Sean Silvaf99309c2013-06-10 23:44:15 +0000954 else
Rui Ueyama1b31eb92018-01-12 01:40:32 +0000955 return ELFState<object::ELF32BE>::writeELF(Out, Doc);
Sean Silvaf99309c2013-06-10 23:44:15 +0000956 }
Sean Silvaf99309c2013-06-10 23:44:15 +0000957}