blob: 8a53a1b2f48405946f816b6314e353e1920b6677 [file] [log] [blame]
Sean Silvaf99309c2013-06-10 23:44:15 +00001//===- yaml2elf - Convert YAML to a ELF object file -----------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Sean Silvaf99309c2013-06-10 23:44:15 +00006//
7//===----------------------------------------------------------------------===//
8///
9/// \file
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000010/// The ELF component of yaml2obj.
Sean Silvaf99309c2013-06-10 23:44:15 +000011///
12//===----------------------------------------------------------------------===//
13
14#include "yaml2obj.h"
Will Dietz0b48c732013-10-12 21:29:16 +000015#include "llvm/ADT/ArrayRef.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000016#include "llvm/BinaryFormat/ELF.h"
Rafael Espindola97de4742014-07-03 02:01:39 +000017#include "llvm/MC/StringTableBuilder.h"
Michael J. Spencer126973b2013-08-08 22:27:13 +000018#include "llvm/Object/ELFObjectFile.h"
Rafael Espindolaebd91932016-03-01 19:15:06 +000019#include "llvm/ObjectYAML/ELFYAML.h"
George Rimard063c7d2019-02-20 13:58:43 +000020#include "llvm/Support/EndianStream.h"
Sean Silvaf99309c2013-06-10 23:44:15 +000021#include "llvm/Support/MemoryBuffer.h"
Jonas Devlieghere2cd41eb2018-04-21 21:11:59 +000022#include "llvm/Support/WithColor.h"
Sean Silvaf99309c2013-06-10 23:44:15 +000023#include "llvm/Support/YAMLTraits.h"
24#include "llvm/Support/raw_ostream.h"
25
26using namespace llvm;
27
Sean Silva46dffff2013-06-13 22:20:01 +000028// This class is used to build up a contiguous binary blob while keeping
29// track of an offset in the output (which notionally begins at
30// `InitialOffset`).
Sean Silva2a74f702013-06-15 00:31:46 +000031namespace {
Sean Silva46dffff2013-06-13 22:20:01 +000032class ContiguousBlobAccumulator {
33 const uint64_t InitialOffset;
Sean Silvabd3bc692013-06-20 19:11:41 +000034 SmallVector<char, 128> Buf;
Sean Silva46dffff2013-06-13 22:20:01 +000035 raw_svector_ostream OS;
36
Sean Silvad93323f2013-06-22 00:47:43 +000037 /// \returns The new offset.
38 uint64_t padToAlignment(unsigned Align) {
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +000039 if (Align == 0)
40 Align = 1;
Sean Silvad93323f2013-06-22 00:47:43 +000041 uint64_t CurrentOffset = InitialOffset + OS.tell();
Rui Ueyamada00f2f2016-01-14 21:06:47 +000042 uint64_t AlignedOffset = alignTo(CurrentOffset, Align);
George Rimarbd8bfd32019-04-29 12:05:53 +000043 OS.write_zeros(AlignedOffset - CurrentOffset);
Sean Silvad93323f2013-06-22 00:47:43 +000044 return AlignedOffset; // == CurrentOffset;
45 }
46
Sean Silva46dffff2013-06-13 22:20:01 +000047public:
Sean Silvabd3bc692013-06-20 19:11:41 +000048 ContiguousBlobAccumulator(uint64_t InitialOffset_)
49 : InitialOffset(InitialOffset_), Buf(), OS(Buf) {}
Sean Silvad93323f2013-06-22 00:47:43 +000050 template <class Integer>
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +000051 raw_ostream &getOSAndAlignedOffset(Integer &Offset, unsigned Align) {
Sean Silvad93323f2013-06-22 00:47:43 +000052 Offset = padToAlignment(Align);
53 return OS;
54 }
Sean Silva46dffff2013-06-13 22:20:01 +000055 void writeBlobToStream(raw_ostream &Out) { Out << OS.str(); }
56};
Sean Silva2a74f702013-06-15 00:31:46 +000057} // end anonymous namespace
Sean Silva46dffff2013-06-13 22:20:01 +000058
Simon Atanasyan35babf92014-04-06 09:02:55 +000059// Used to keep track of section and symbol names, so that in the YAML file
George Rimar09746882019-05-07 12:10:51 +000060// sections and symbols can be referenced by name instead of by index.
61namespace {
62class NameToIdxMap {
Puyan Lotfia10f0162019-05-11 17:03:36 +000063 StringMap<unsigned> Map;
64
George Rimar09746882019-05-07 12:10:51 +000065public:
Puyan Lotfia10f0162019-05-11 17:03:36 +000066 /// \Returns false if name is already present in the map.
67 bool addName(StringRef Name, unsigned Ndx) {
68 return Map.insert({Name, Ndx}).second;
George Rimar09746882019-05-07 12:10:51 +000069 }
Puyan Lotfia10f0162019-05-11 17:03:36 +000070 /// \Returns false if name is not present in the map.
George Rimar09746882019-05-07 12:10:51 +000071 bool lookup(StringRef Name, unsigned &Idx) const {
Puyan Lotfia10f0162019-05-11 17:03:36 +000072 auto I = Map.find(Name);
George Rimar09746882019-05-07 12:10:51 +000073 if (I == Map.end())
Puyan Lotfia10f0162019-05-11 17:03:36 +000074 return false;
George Rimar09746882019-05-07 12:10:51 +000075 Idx = I->getValue();
Puyan Lotfia10f0162019-05-11 17:03:36 +000076 return true;
George Rimar09746882019-05-07 12:10:51 +000077 }
Puyan Lotfia10f0162019-05-11 17:03:36 +000078 /// Asserts if name is not present in the map.
George Rimar09746882019-05-07 12:10:51 +000079 unsigned get(StringRef Name) const {
Puyan Lotfia10f0162019-05-11 17:03:36 +000080 unsigned Idx;
81 if (lookup(Name, Idx))
82 return Idx;
83 assert(false && "Expected section not found in index");
84 return 0;
George Rimar09746882019-05-07 12:10:51 +000085 }
86 unsigned size() const { return Map.size(); }
87};
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);
George Rimar66296dc2019-06-05 13:16:53 +0000139 bool initImplicitHeader(ELFState<ELFT> &State, ContiguousBlobAccumulator &CBA,
140 Elf_Shdr &Header, StringRef SecName,
141 ELFYAML::Section *YAMLSec);
142 bool initSectionHeaders(ELFState<ELFT> &State,
143 std::vector<Elf_Shdr> &SHeaders,
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000144 ContiguousBlobAccumulator &CBA);
Dave Lee67b49662017-11-16 18:10:15 +0000145 void initSymtabSectionHeader(Elf_Shdr &SHeader, SymtabType STType,
George Rimar66296dc2019-06-05 13:16:53 +0000146 ContiguousBlobAccumulator &CBA,
147 ELFYAML::Section *YAMLSec);
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000148 void initStrtabSectionHeader(Elf_Shdr &SHeader, StringRef Name,
149 StringTableBuilder &STB,
George Rimar66296dc2019-06-05 13:16:53 +0000150 ContiguousBlobAccumulator &CBA,
151 ELFYAML::Section *YAMLSec);
Petr Hosekeb04da32017-07-19 20:38:46 +0000152 void setProgramHeaderLayout(std::vector<Elf_Phdr> &PHeaders,
153 std::vector<Elf_Shdr> &SHeaders);
George Rimar6da44ad2019-04-03 14:53:42 +0000154 void addSymbols(ArrayRef<ELFYAML::Symbol> Symbols, std::vector<Elf_Sym> &Syms,
Dave Lee67b49662017-11-16 18:10:15 +0000155 const StringTableBuilder &Strtab);
George Rimarda1b3ab2019-04-26 12:15:32 +0000156 bool writeSectionContent(Elf_Shdr &SHeader,
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000157 const ELFYAML::RawContentSection &Section,
158 ContiguousBlobAccumulator &CBA);
159 bool writeSectionContent(Elf_Shdr &SHeader,
160 const ELFYAML::RelocationSection &Section,
161 ContiguousBlobAccumulator &CBA);
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000162 bool writeSectionContent(Elf_Shdr &SHeader, const ELFYAML::Group &Group,
163 ContiguousBlobAccumulator &CBA);
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000164 bool writeSectionContent(Elf_Shdr &SHeader,
George Rimar646af082019-02-19 15:29:07 +0000165 const ELFYAML::SymverSection &Section,
166 ContiguousBlobAccumulator &CBA);
167 bool writeSectionContent(Elf_Shdr &SHeader,
George Rimar0621b792019-02-19 14:53:48 +0000168 const ELFYAML::VerneedSection &Section,
169 ContiguousBlobAccumulator &CBA);
170 bool writeSectionContent(Elf_Shdr &SHeader,
George Rimar623ae722019-02-21 12:21:43 +0000171 const ELFYAML::VerdefSection &Section,
172 ContiguousBlobAccumulator &CBA);
173 bool writeSectionContent(Elf_Shdr &SHeader,
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000174 const ELFYAML::MipsABIFlags &Section,
175 ContiguousBlobAccumulator &CBA);
James Hendersonfd997802019-02-25 11:02:24 +0000176 bool writeSectionContent(Elf_Shdr &SHeader,
George Rimar0e7ed912019-02-09 11:34:28 +0000177 const ELFYAML::DynamicSection &Section,
178 ContiguousBlobAccumulator &CBA);
George Rimar5fcdebe2019-04-26 13:09:11 +0000179 std::vector<StringRef> implicitSectionNames() const;
Sean Silva08a75ae2013-06-20 19:11:44 +0000180
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000181 ELFState(const ELFYAML::Object &D) : Doc(D) {}
Simon Atanasyan220c54a2014-04-02 16:34:40 +0000182
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000183public:
184 static int writeELF(raw_ostream &OS, const ELFYAML::Object &Doc);
George Rimar0621b792019-02-19 14:53:48 +0000185
186private:
187 void finalizeStrings();
Sean Silva08a75ae2013-06-20 19:11:44 +0000188};
189} // end anonymous namespace
190
Sean Silva37e817c2013-06-21 00:33:01 +0000191template <class ELFT>
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000192void ELFState<ELFT>::initELFHeader(Elf_Ehdr &Header) {
193 using namespace llvm::ELF;
194 zero(Header);
195 Header.e_ident[EI_MAG0] = 0x7f;
196 Header.e_ident[EI_MAG1] = 'E';
197 Header.e_ident[EI_MAG2] = 'L';
198 Header.e_ident[EI_MAG3] = 'F';
199 Header.e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;
George Rimara5a0a0f2019-03-07 12:09:19 +0000200 Header.e_ident[EI_DATA] = Doc.Header.Data;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000201 Header.e_ident[EI_VERSION] = EV_CURRENT;
202 Header.e_ident[EI_OSABI] = Doc.Header.OSABI;
George Rimar6367d7a2018-12-20 10:43:49 +0000203 Header.e_ident[EI_ABIVERSION] = Doc.Header.ABIVersion;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000204 Header.e_type = Doc.Header.Type;
205 Header.e_machine = Doc.Header.Machine;
206 Header.e_version = EV_CURRENT;
207 Header.e_entry = Doc.Header.Entry;
Petr Hosekeb04da32017-07-19 20:38:46 +0000208 Header.e_phoff = sizeof(Header);
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000209 Header.e_flags = Doc.Header.Flags;
210 Header.e_ehsize = sizeof(Elf_Ehdr);
Petr Hosekeb04da32017-07-19 20:38:46 +0000211 Header.e_phentsize = sizeof(Elf_Phdr);
212 Header.e_phnum = Doc.ProgramHeaders.size();
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000213 Header.e_shentsize = sizeof(Elf_Shdr);
Petr Hosekeb04da32017-07-19 20:38:46 +0000214 // Immediately following the ELF header and program headers.
215 Header.e_shoff =
216 sizeof(Header) + sizeof(Elf_Phdr) * Doc.ProgramHeaders.size();
George Rimard71017b2019-06-10 09:57:29 +0000217 Header.e_shnum = SN2I.size() + 1;
218 Header.e_shstrndx = SN2I.get(".shstrtab");
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000219}
220
221template <class ELFT>
Petr Hosekeb04da32017-07-19 20:38:46 +0000222void ELFState<ELFT>::initProgramHeaders(std::vector<Elf_Phdr> &PHeaders) {
223 for (const auto &YamlPhdr : Doc.ProgramHeaders) {
224 Elf_Phdr Phdr;
225 Phdr.p_type = YamlPhdr.Type;
226 Phdr.p_flags = YamlPhdr.Flags;
227 Phdr.p_vaddr = YamlPhdr.VAddr;
228 Phdr.p_paddr = YamlPhdr.PAddr;
229 PHeaders.push_back(Phdr);
230 }
231}
George Rimar09746882019-05-07 12:10:51 +0000232
233static bool convertSectionIndex(NameToIdxMap &SN2I, StringRef SecName,
234 StringRef IndexSrc, unsigned &IndexDest) {
Puyan Lotfia10f0162019-05-11 17:03:36 +0000235 if (!SN2I.lookup(IndexSrc, IndexDest) && !to_integer(IndexSrc, IndexDest)) {
George Rimar09746882019-05-07 12:10:51 +0000236 WithColor::error() << "Unknown section referenced: '" << IndexSrc
237 << "' at YAML section '" << SecName << "'.\n";
238 return false;
Xing GUO98228352018-12-04 14:27:51 +0000239 }
240 return true;
241}
242
Petr Hosekeb04da32017-07-19 20:38:46 +0000243template <class ELFT>
George Rimar66296dc2019-06-05 13:16:53 +0000244bool ELFState<ELFT>::initImplicitHeader(ELFState<ELFT> &State,
245 ContiguousBlobAccumulator &CBA,
246 Elf_Shdr &Header, StringRef SecName,
247 ELFYAML::Section *YAMLSec) {
248 // Check if the header was already initialized.
249 if (Header.sh_offset)
250 return false;
251
252 if (SecName == ".symtab")
253 State.initSymtabSectionHeader(Header, SymtabType::Static, CBA, YAMLSec);
254 else if (SecName == ".strtab")
255 State.initStrtabSectionHeader(Header, SecName, State.DotStrtab, CBA,
256 YAMLSec);
257 else if (SecName == ".shstrtab")
258 State.initStrtabSectionHeader(Header, SecName, State.DotShStrtab, CBA,
259 YAMLSec);
260
261 else if (SecName == ".dynsym")
262 State.initSymtabSectionHeader(Header, SymtabType::Dynamic, CBA, YAMLSec);
263 else if (SecName == ".dynstr")
264 State.initStrtabSectionHeader(Header, SecName, State.DotDynstr, CBA,
265 YAMLSec);
266 else
267 return false;
268 return true;
269}
270
271template <class ELFT>
272bool ELFState<ELFT>::initSectionHeaders(ELFState<ELFT> &State,
273 std::vector<Elf_Shdr> &SHeaders,
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000274 ContiguousBlobAccumulator &CBA) {
George Rimareb394e92019-06-07 08:31:36 +0000275 // Build a list of sections we are going to add implicitly.
276 std::vector<StringRef> ImplicitSections;
277 for (StringRef Name : State.implicitSectionNames())
278 if (State.SN2I.get(Name) > Doc.Sections.size())
279 ImplicitSections.push_back(Name);
280
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000281 // Ensure SHN_UNDEF entry is present. An all-zero section header is a
282 // valid SHN_UNDEF entry since SHT_NULL == 0.
George Rimareb394e92019-06-07 08:31:36 +0000283 SHeaders.resize(Doc.Sections.size() + ImplicitSections.size() + 1);
284 zero(SHeaders[0]);
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000285
George Rimareb394e92019-06-07 08:31:36 +0000286 for (size_t I = 1; I < Doc.Sections.size() + ImplicitSections.size() + 1; ++I) {
287 Elf_Shdr &SHeader = SHeaders[I];
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000288 zero(SHeader);
George Rimareb394e92019-06-07 08:31:36 +0000289 ELFYAML::Section *Sec =
290 I > Doc.Sections.size() ? nullptr : Doc.Sections[I - 1].get();
291
292 // We have a few sections like string or symbol tables that are usually
293 // added implicitly to the end. However, if they are explicitly specified
294 // in the YAML, we need to write them here. This ensures the file offset
295 // remains correct.
296 StringRef SecName =
297 Sec ? Sec->Name : ImplicitSections[I - Doc.Sections.size() - 1];
298 if (initImplicitHeader(State, CBA, SHeader, SecName, Sec))
299 continue;
300
301 assert(Sec && "It can't be null unless it is an implicit section. But all "
302 "implicit sections should already have been handled above.");
303
304 SHeader.sh_name = DotShStrtab.getOffset(SecName);
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000305 SHeader.sh_type = Sec->Type;
306 SHeader.sh_flags = Sec->Flags;
307 SHeader.sh_addr = Sec->Address;
308 SHeader.sh_addralign = Sec->AddressAlign;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000309
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000310 if (!Sec->Link.empty()) {
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000311 unsigned Index;
Xing GUO98228352018-12-04 14:27:51 +0000312 if (!convertSectionIndex(SN2I, Sec->Name, Sec->Link, Index))
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000313 return false;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000314 SHeader.sh_link = Index;
315 }
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000316
George Rimareb394e92019-06-07 08:31:36 +0000317 if (auto S = dyn_cast<ELFYAML::RawContentSection>(Sec)) {
George Rimarda1b3ab2019-04-26 12:15:32 +0000318 if (!writeSectionContent(SHeader, *S, CBA))
George Rimar7f2df7d2018-08-16 12:23:22 +0000319 return false;
George Rimareb394e92019-06-07 08:31:36 +0000320 } else if (auto S = dyn_cast<ELFYAML::RelocationSection>(Sec)) {
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000321 if (!writeSectionContent(SHeader, *S, CBA))
322 return false;
George Rimareb394e92019-06-07 08:31:36 +0000323 } else if (auto S = dyn_cast<ELFYAML::Group>(Sec)) {
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000324 if (!writeSectionContent(SHeader, *S, CBA))
325 return false;
George Rimareb394e92019-06-07 08:31:36 +0000326 } else if (auto S = dyn_cast<ELFYAML::MipsABIFlags>(Sec)) {
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000327 if (!writeSectionContent(SHeader, *S, CBA))
328 return false;
George Rimareb394e92019-06-07 08:31:36 +0000329 } else if (auto S = dyn_cast<ELFYAML::NoBitsSection>(Sec)) {
Simon Atanasyan5db02762015-07-03 23:00:54 +0000330 SHeader.sh_entsize = 0;
331 SHeader.sh_size = S->Size;
332 // SHT_NOBITS section does not have content
333 // so just to setup the section offset.
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000334 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
George Rimareb394e92019-06-07 08:31:36 +0000335 } else if (auto S = dyn_cast<ELFYAML::DynamicSection>(Sec)) {
James Hendersonfd997802019-02-25 11:02:24 +0000336 if (!writeSectionContent(SHeader, *S, CBA))
337 return false;
George Rimareb394e92019-06-07 08:31:36 +0000338 } else if (auto S = dyn_cast<ELFYAML::SymverSection>(Sec)) {
George Rimarda1b3ab2019-04-26 12:15:32 +0000339 if (!writeSectionContent(SHeader, *S, CBA))
340 return false;
George Rimareb394e92019-06-07 08:31:36 +0000341 } else if (auto S = dyn_cast<ELFYAML::VerneedSection>(Sec)) {
George Rimarda1b3ab2019-04-26 12:15:32 +0000342 if (!writeSectionContent(SHeader, *S, CBA))
343 return false;
George Rimareb394e92019-06-07 08:31:36 +0000344 } else if (auto S = dyn_cast<ELFYAML::VerdefSection>(Sec)) {
George Rimarda1b3ab2019-04-26 12:15:32 +0000345 if (!writeSectionContent(SHeader, *S, CBA))
346 return false;
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000347 } else
348 llvm_unreachable("Unknown section type");
George Rimar66296dc2019-06-05 13:16:53 +0000349 }
350
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000351 return true;
352}
353
George Rimar6da44ad2019-04-03 14:53:42 +0000354static size_t findFirstNonGlobal(ArrayRef<ELFYAML::Symbol> Symbols) {
355 for (size_t I = 0; I < Symbols.size(); ++I)
356 if (Symbols[I].Binding.value != ELF::STB_LOCAL)
357 return I;
358 return Symbols.size();
359}
360
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000361template <class ELFT>
362void ELFState<ELFT>::initSymtabSectionHeader(Elf_Shdr &SHeader,
Dave Lee67b49662017-11-16 18:10:15 +0000363 SymtabType STType,
George Rimar66296dc2019-06-05 13:16:53 +0000364 ContiguousBlobAccumulator &CBA,
365 ELFYAML::Section *YAMLSec) {
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000366 zero(SHeader);
Dave Lee67b49662017-11-16 18:10:15 +0000367 bool IsStatic = STType == SymtabType::Static;
368 SHeader.sh_name = DotShStrtab.getOffset(IsStatic ? ".symtab" : ".dynsym");
369 SHeader.sh_type = IsStatic ? ELF::SHT_SYMTAB : ELF::SHT_DYNSYM;
George Rimar379aa182019-06-10 11:38:06 +0000370
371 // When we describe the .dynsym section in the document explicitly, it is
372 // allowed to omit the "DynamicSymbols" tag. In this case .dynstr is not added
373 // implicitly and we should be able to leave the Link zeroed if .dynstr is not
374 // defined.
375 unsigned Link = 0;
376 if (IsStatic)
377 Link = SN2I.get(".strtab");
378 else
379 SN2I.lookup(".dynstr", Link);
380 SHeader.sh_link = Link;
381
George Rimar48288112019-04-29 11:54:10 +0000382 if (!IsStatic)
383 SHeader.sh_flags |= ELF::SHF_ALLOC;
George Rimarc1da1492019-04-26 12:45:54 +0000384
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000385 // One greater than symbol table index of the last local symbol.
George Rimarc1da1492019-04-26 12:45:54 +0000386 const auto &Symbols = IsStatic ? Doc.Symbols : Doc.DynamicSymbols;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000387
George Rimara7ba1a02019-03-01 10:18:16 +0000388 // If the symbol table section is explicitly described in the YAML
389 // then we should set the fields requested.
George Rimar66296dc2019-06-05 13:16:53 +0000390 ELFYAML::RawContentSection *RawSec =
391 dyn_cast_or_null<ELFYAML::RawContentSection>(YAMLSec);
392 SHeader.sh_info =
393 RawSec ? (unsigned)RawSec->Info : findFirstNonGlobal(Symbols) + 1;
394 SHeader.sh_entsize = (YAMLSec && YAMLSec->EntSize)
395 ? (uint64_t)(*YAMLSec->EntSize)
396 : sizeof(Elf_Sym);
397 SHeader.sh_addralign = YAMLSec ? (uint64_t)YAMLSec->AddressAlign : 8;
398 SHeader.sh_addr = YAMLSec ? (uint64_t)YAMLSec->Address : 0;
399
400 if (RawSec && RawSec->Content.binary_size()) {
401 RawSec->Content.writeAsBinary(
402 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign));
403 SHeader.sh_size = RawSec->Size;
404 } else {
405 std::vector<Elf_Sym> Syms;
406 {
407 // Ensure STN_UNDEF is present
408 Elf_Sym Sym;
409 zero(Sym);
410 Syms.push_back(Sym);
411 }
412
413 addSymbols(Symbols, Syms, IsStatic ? DotStrtab : DotDynstr);
414
415 writeArrayData(
416 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign),
417 makeArrayRef(Syms));
418 SHeader.sh_size = arrayDataSize(makeArrayRef(Syms));
George Rimar6947acd2019-02-19 12:15:04 +0000419 }
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000420}
421
422template <class ELFT>
423void ELFState<ELFT>::initStrtabSectionHeader(Elf_Shdr &SHeader, StringRef Name,
424 StringTableBuilder &STB,
George Rimar66296dc2019-06-05 13:16:53 +0000425 ContiguousBlobAccumulator &CBA,
426 ELFYAML::Section *YAMLSec) {
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000427 zero(SHeader);
Hans Wennborg59f0cba2014-04-30 19:38:09 +0000428 SHeader.sh_name = DotShStrtab.getOffset(Name);
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000429 SHeader.sh_type = ELF::SHT_STRTAB;
George Rimar66296dc2019-06-05 13:16:53 +0000430 SHeader.sh_addralign = YAMLSec ? (uint64_t)YAMLSec->AddressAlign : 1;
431
432 ELFYAML::RawContentSection *RawSec =
433 dyn_cast_or_null<ELFYAML::RawContentSection>(YAMLSec);
434 if (RawSec && RawSec->Content.binary_size()) {
435 RawSec->Content.writeAsBinary(
436 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign));
437 SHeader.sh_size = RawSec->Size;
438 } else {
439 STB.write(
440 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign));
441 SHeader.sh_size = STB.getSize();
442 }
443
444 if (YAMLSec && YAMLSec->EntSize)
445 SHeader.sh_entsize = *YAMLSec->EntSize;
George Rimar6947acd2019-02-19 12:15:04 +0000446
447 // If .dynstr section is explicitly described in the YAML
448 // then we want to use its section address.
449 if (Name == ".dynstr") {
George Rimar66296dc2019-06-05 13:16:53 +0000450 if (YAMLSec)
451 SHeader.sh_addr = YAMLSec->Address;
George Rimar48288112019-04-29 11:54:10 +0000452 // We assume that .dynstr is always allocatable.
453 SHeader.sh_flags |= ELF::SHF_ALLOC;
George Rimar6947acd2019-02-19 12:15:04 +0000454 }
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000455}
456
457template <class ELFT>
Petr Hosekeb04da32017-07-19 20:38:46 +0000458void ELFState<ELFT>::setProgramHeaderLayout(std::vector<Elf_Phdr> &PHeaders,
459 std::vector<Elf_Shdr> &SHeaders) {
460 uint32_t PhdrIdx = 0;
461 for (auto &YamlPhdr : Doc.ProgramHeaders) {
George Rimarf5345a32019-05-01 09:45:55 +0000462 Elf_Phdr &PHeader = PHeaders[PhdrIdx++];
463
Puyan Lotfia10f0162019-05-11 17:03:36 +0000464 std::vector<Elf_Shdr *> Sections;
465 for (const ELFYAML::SectionName &SecName : YamlPhdr.Sections) {
466 unsigned Index;
467 if (!SN2I.lookup(SecName.Section, Index)) {
468 WithColor::error() << "Unknown section referenced: '" << SecName.Section
469 << "' by program header.\n";
470 exit(1);
George Rimarf5345a32019-05-01 09:45:55 +0000471 }
472 Sections.push_back(&SHeaders[Index]);
473 }
Petr Hosekeb04da32017-07-19 20:38:46 +0000474
James Hendersonb10f48b2019-03-15 10:35:27 +0000475 if (YamlPhdr.Offset) {
476 PHeader.p_offset = *YamlPhdr.Offset;
477 } else {
478 if (YamlPhdr.Sections.size())
479 PHeader.p_offset = UINT32_MAX;
Petr Hosekeb04da32017-07-19 20:38:46 +0000480 else
James Hendersonb10f48b2019-03-15 10:35:27 +0000481 PHeader.p_offset = 0;
482
483 // Find the minimum offset for the program header.
George Rimarf5345a32019-05-01 09:45:55 +0000484 for (Elf_Shdr *SHeader : Sections)
485 PHeader.p_offset = std::min(PHeader.p_offset, SHeader->sh_offset);
Petr Hosekeb04da32017-07-19 20:38:46 +0000486 }
487
James Hendersonb10f48b2019-03-15 10:35:27 +0000488 // Find the maximum offset of the end of a section in order to set p_filesz,
489 // if not set explicitly.
490 if (YamlPhdr.FileSize) {
491 PHeader.p_filesz = *YamlPhdr.FileSize;
492 } else {
493 PHeader.p_filesz = 0;
George Rimarf5345a32019-05-01 09:45:55 +0000494 for (Elf_Shdr *SHeader : Sections) {
James Hendersonb10f48b2019-03-15 10:35:27 +0000495 uint64_t EndOfSection;
George Rimarf5345a32019-05-01 09:45:55 +0000496 if (SHeader->sh_type == llvm::ELF::SHT_NOBITS)
497 EndOfSection = SHeader->sh_offset;
James Hendersonb10f48b2019-03-15 10:35:27 +0000498 else
George Rimarf5345a32019-05-01 09:45:55 +0000499 EndOfSection = SHeader->sh_offset + SHeader->sh_size;
James Hendersonb10f48b2019-03-15 10:35:27 +0000500 uint64_t EndOfSegment = PHeader.p_offset + PHeader.p_filesz;
501 EndOfSegment = std::max(EndOfSegment, EndOfSection);
502 PHeader.p_filesz = EndOfSegment - PHeader.p_offset;
503 }
504 }
505
506 // If not set explicitly, find the memory size by adding the size of
507 // sections at the end of the segment. These should be empty (size of zero)
508 // and NOBITS sections.
509 if (YamlPhdr.MemSize) {
510 PHeader.p_memsz = *YamlPhdr.MemSize;
511 } else {
512 PHeader.p_memsz = PHeader.p_filesz;
George Rimarf5345a32019-05-01 09:45:55 +0000513 for (Elf_Shdr *SHeader : Sections)
514 if (SHeader->sh_offset == PHeader.p_offset + PHeader.p_filesz)
515 PHeader.p_memsz += SHeader->sh_size;
Petr Hosekeb04da32017-07-19 20:38:46 +0000516 }
517
518 // Set the alignment of the segment to be the same as the maximum alignment
Jake Ehrlich03aeeb092017-11-01 23:14:48 +0000519 // of the sections with the same offset so that by default the segment
Petr Hosekeb04da32017-07-19 20:38:46 +0000520 // has a valid and sensible alignment.
Jake Ehrlich03aeeb092017-11-01 23:14:48 +0000521 if (YamlPhdr.Align) {
522 PHeader.p_align = *YamlPhdr.Align;
523 } else {
524 PHeader.p_align = 1;
George Rimarf5345a32019-05-01 09:45:55 +0000525 for (Elf_Shdr *SHeader : Sections)
526 if (SHeader->sh_offset == PHeader.p_offset)
527 PHeader.p_align = std::max(PHeader.p_align, SHeader->sh_addralign);
Petr Hosekeb04da32017-07-19 20:38:46 +0000528 }
529 }
530}
531
532template <class ELFT>
George Rimar6da44ad2019-04-03 14:53:42 +0000533void ELFState<ELFT>::addSymbols(ArrayRef<ELFYAML::Symbol> Symbols,
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000534 std::vector<Elf_Sym> &Syms,
Dave Lee67b49662017-11-16 18:10:15 +0000535 const StringTableBuilder &Strtab) {
Simon Atanasyan048baca2014-03-14 06:53:30 +0000536 for (const auto &Sym : Symbols) {
Sean Silva6b083882013-06-18 23:14:03 +0000537 Elf_Sym Symbol;
538 zero(Symbol);
George Rimar09746882019-05-07 12:10:51 +0000539
540 // If NameIndex, which contains the name offset, is explicitly specified, we
541 // use it. This is useful for preparing broken objects. Otherwise, we add
542 // the specified Name to the string table builder to get its offset.
543 if (Sym.NameIndex)
544 Symbol.st_name = *Sym.NameIndex;
545 else if (!Sym.Name.empty())
Dave Lee67b49662017-11-16 18:10:15 +0000546 Symbol.st_name = Strtab.getOffset(Sym.Name);
George Rimar09746882019-05-07 12:10:51 +0000547
548 Symbol.setBindingAndType(Sym.Binding, Sym.Type);
549 if (!Sym.Section.empty()) {
550 unsigned Index;
Puyan Lotfia10f0162019-05-11 17:03:36 +0000551 if (!SN2I.lookup(Sym.Section, Index)) {
George Rimar09746882019-05-07 12:10:51 +0000552 WithColor::error() << "Unknown section referenced: '" << Sym.Section
553 << "' by YAML symbol " << Sym.Name << ".\n";
554 exit(1);
Sean Silvac4afa6d2013-06-21 01:11:48 +0000555 }
556 Symbol.st_shndx = Index;
Petr Hosek5c469a32017-09-07 20:44:16 +0000557 } else if (Sym.Index) {
558 Symbol.st_shndx = *Sym.Index;
559 }
560 // else Symbol.st_shndex == SHN_UNDEF (== 0), since it was zero'd earlier.
Sean Silva05001b92013-06-20 20:59:47 +0000561 Symbol.st_value = Sym.Value;
Simon Atanasyan60e1a792014-11-06 22:46:24 +0000562 Symbol.st_other = Sym.Other;
Sean Silva05001b92013-06-20 20:59:47 +0000563 Symbol.st_size = Sym.Size;
Sean Silva6b083882013-06-18 23:14:03 +0000564 Syms.push_back(Symbol);
565 }
Sean Silvaaff51252013-06-21 00:27:50 +0000566}
567
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000568template <class ELFT>
George Rimarda1b3ab2019-04-26 12:15:32 +0000569bool ELFState<ELFT>::writeSectionContent(
George Rimarb49e1922019-04-24 13:02:15 +0000570 Elf_Shdr &SHeader, const ELFYAML::RawContentSection &Section,
571 ContiguousBlobAccumulator &CBA) {
Simon Atanasyanb83f3802014-05-16 16:01:00 +0000572 assert(Section.Size >= Section.Content.binary_size() &&
573 "Section size and section content are inconsistent");
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000574 raw_ostream &OS =
575 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
Simon Atanasyanb83f3802014-05-16 16:01:00 +0000576 Section.Content.writeAsBinary(OS);
George Rimarb49e1922019-04-24 13:02:15 +0000577 OS.write_zeros(Section.Size - Section.Content.binary_size());
578
George Rimar65a68282018-08-07 08:11:38 +0000579 if (Section.EntSize)
580 SHeader.sh_entsize = *Section.EntSize;
581 else if (Section.Type == llvm::ELF::SHT_RELR)
Jake Ehrlich0f440d82018-06-28 21:07:34 +0000582 SHeader.sh_entsize = sizeof(Elf_Relr);
583 else
584 SHeader.sh_entsize = 0;
Simon Atanasyanb83f3802014-05-16 16:01:00 +0000585 SHeader.sh_size = Section.Size;
George Rimara7ba1a02019-03-01 10:18:16 +0000586 SHeader.sh_info = Section.Info;
George Rimarda1b3ab2019-04-26 12:15:32 +0000587 return true;
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000588}
589
Simon Atanasyan5d19c672015-01-25 13:29:25 +0000590static bool isMips64EL(const ELFYAML::Object &Doc) {
591 return Doc.Header.Machine == ELFYAML::ELF_EM(llvm::ELF::EM_MIPS) &&
592 Doc.Header.Class == ELFYAML::ELF_ELFCLASS(ELF::ELFCLASS64) &&
593 Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB);
594}
595
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000596template <class ELFT>
597bool
598ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
599 const ELFYAML::RelocationSection &Section,
600 ContiguousBlobAccumulator &CBA) {
Simon Atanasyan8eb9d1b2015-05-08 07:05:04 +0000601 assert((Section.Type == llvm::ELF::SHT_REL ||
602 Section.Type == llvm::ELF::SHT_RELA) &&
603 "Section type is not SHT_REL nor SHT_RELA");
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000604
605 bool IsRela = Section.Type == llvm::ELF::SHT_RELA;
606 SHeader.sh_entsize = IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
607 SHeader.sh_size = SHeader.sh_entsize * Section.Relocations.size();
608
George Rimarda1b3ab2019-04-26 12:15:32 +0000609 // For relocation section set link to .symtab by default.
610 if (Section.Link.empty())
George Rimard71017b2019-06-10 09:57:29 +0000611 SHeader.sh_link = SN2I.get(".symtab");
George Rimarda1b3ab2019-04-26 12:15:32 +0000612
613 unsigned Index = 0;
614 if (!Section.RelocatableSec.empty() &&
615 !convertSectionIndex(SN2I, Section.Name, Section.RelocatableSec, Index))
616 return false;
617 SHeader.sh_info = Index;
618
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000619 auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000620
621 for (const auto &Rel : Section.Relocations) {
George Rimar09746882019-05-07 12:10:51 +0000622 unsigned SymIdx = 0;
623 // If a relocation references a symbol, try to look one up in the symbol
624 // table. If it is not there, treat the value as a symbol index.
Puyan Lotfia10f0162019-05-11 17:03:36 +0000625 if (Rel.Symbol && !SymN2I.lookup(*Rel.Symbol, SymIdx) &&
George Rimar09746882019-05-07 12:10:51 +0000626 !to_integer(*Rel.Symbol, SymIdx)) {
627 WithColor::error() << "Unknown symbol referenced: '" << *Rel.Symbol
628 << "' at YAML section '" << Section.Name << "'.\n";
James Henderson9bc817a2019-03-12 17:00:25 +0000629 return false;
630 }
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000631
632 if (IsRela) {
633 Elf_Rela REntry;
634 zero(REntry);
635 REntry.r_offset = Rel.Offset;
636 REntry.r_addend = Rel.Addend;
Simon Atanasyan5d19c672015-01-25 13:29:25 +0000637 REntry.setSymbolAndType(SymIdx, Rel.Type, isMips64EL(Doc));
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000638 OS.write((const char *)&REntry, sizeof(REntry));
639 } else {
640 Elf_Rel REntry;
641 zero(REntry);
642 REntry.r_offset = Rel.Offset;
Simon Atanasyan5d19c672015-01-25 13:29:25 +0000643 REntry.setSymbolAndType(SymIdx, Rel.Type, isMips64EL(Doc));
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000644 OS.write((const char *)&REntry, sizeof(REntry));
645 }
646 }
647 return true;
648}
649
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000650template <class ELFT>
651bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
652 const ELFYAML::Group &Section,
653 ContiguousBlobAccumulator &CBA) {
Simon Atanasyan8eb9d1b2015-05-08 07:05:04 +0000654 assert(Section.Type == llvm::ELF::SHT_GROUP &&
655 "Section type is not SHT_GROUP");
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000656
George Rimard063c7d2019-02-20 13:58:43 +0000657 SHeader.sh_entsize = 4;
George Rimar09746882019-05-07 12:10:51 +0000658 SHeader.sh_size = SHeader.sh_entsize * Section.Members.size();
659
Puyan Lotfia10f0162019-05-11 17:03:36 +0000660 unsigned SymIdx;
661 if (!SymN2I.lookup(Section.Signature, SymIdx) &&
662 !to_integer(Section.Signature, SymIdx)) {
663 WithColor::error() << "Unknown symbol referenced: '" << Section.Signature
664 << "' at YAML section '" << Section.Name << "'.\n";
George Rimarda1b3ab2019-04-26 12:15:32 +0000665 return false;
666 }
667 SHeader.sh_info = SymIdx;
668
George Rimard063c7d2019-02-20 13:58:43 +0000669 raw_ostream &OS =
670 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000671
George Rimarfb7780a2019-04-26 12:20:51 +0000672 for (const ELFYAML::SectionOrType &Member : Section.Members) {
673 unsigned int SectionIndex = 0;
674 if (Member.sectionNameOrType == "GRP_COMDAT")
675 SectionIndex = llvm::ELF::GRP_COMDAT;
676 else if (!convertSectionIndex(SN2I, Section.Name, Member.sectionNameOrType,
677 SectionIndex))
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000678 return false;
George Rimarfb7780a2019-04-26 12:20:51 +0000679 support::endian::write<uint32_t>(OS, SectionIndex, ELFT::TargetEndianness);
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000680 }
681 return true;
682}
683
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000684template <class ELFT>
685bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
George Rimar646af082019-02-19 15:29:07 +0000686 const ELFYAML::SymverSection &Section,
687 ContiguousBlobAccumulator &CBA) {
George Rimar646af082019-02-19 15:29:07 +0000688 raw_ostream &OS =
689 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
George Rimardac37fb2019-02-20 14:01:02 +0000690 for (uint16_t Version : Section.Entries)
691 support::endian::write<uint16_t>(OS, Version, ELFT::TargetEndianness);
George Rimar646af082019-02-19 15:29:07 +0000692
George Rimard063c7d2019-02-20 13:58:43 +0000693 SHeader.sh_entsize = 2;
694 SHeader.sh_size = Section.Entries.size() * SHeader.sh_entsize;
George Rimar646af082019-02-19 15:29:07 +0000695 return true;
696}
697
698template <class ELFT>
699bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
George Rimar623ae722019-02-21 12:21:43 +0000700 const ELFYAML::VerdefSection &Section,
701 ContiguousBlobAccumulator &CBA) {
702 typedef typename ELFT::Verdef Elf_Verdef;
703 typedef typename ELFT::Verdaux Elf_Verdaux;
704 raw_ostream &OS =
705 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
706
707 uint64_t AuxCnt = 0;
708 for (size_t I = 0; I < Section.Entries.size(); ++I) {
709 const ELFYAML::VerdefEntry &E = Section.Entries[I];
710
711 Elf_Verdef VerDef;
712 VerDef.vd_version = E.Version;
713 VerDef.vd_flags = E.Flags;
714 VerDef.vd_ndx = E.VersionNdx;
715 VerDef.vd_hash = E.Hash;
716 VerDef.vd_aux = sizeof(Elf_Verdef);
717 VerDef.vd_cnt = E.VerNames.size();
718 if (I == Section.Entries.size() - 1)
719 VerDef.vd_next = 0;
720 else
721 VerDef.vd_next =
722 sizeof(Elf_Verdef) + E.VerNames.size() * sizeof(Elf_Verdaux);
723 OS.write((const char *)&VerDef, sizeof(Elf_Verdef));
724
725 for (size_t J = 0; J < E.VerNames.size(); ++J, ++AuxCnt) {
726 Elf_Verdaux VernAux;
727 VernAux.vda_name = DotDynstr.getOffset(E.VerNames[J]);
728 if (J == E.VerNames.size() - 1)
729 VernAux.vda_next = 0;
730 else
731 VernAux.vda_next = sizeof(Elf_Verdaux);
732 OS.write((const char *)&VernAux, sizeof(Elf_Verdaux));
733 }
734 }
735
736 SHeader.sh_size = Section.Entries.size() * sizeof(Elf_Verdef) +
737 AuxCnt * sizeof(Elf_Verdaux);
738 SHeader.sh_info = Section.Info;
739
740 return true;
741}
742
743template <class ELFT>
744bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
George Rimar0621b792019-02-19 14:53:48 +0000745 const ELFYAML::VerneedSection &Section,
746 ContiguousBlobAccumulator &CBA) {
George Rimarda1b3ab2019-04-26 12:15:32 +0000747 typedef typename ELFT::Verneed Elf_Verneed;
748 typedef typename ELFT::Vernaux Elf_Vernaux;
George Rimar0621b792019-02-19 14:53:48 +0000749
George Rimarda1b3ab2019-04-26 12:15:32 +0000750 auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
George Rimar0621b792019-02-19 14:53:48 +0000751
George Rimarda1b3ab2019-04-26 12:15:32 +0000752 uint64_t AuxCnt = 0;
753 for (size_t I = 0; I < Section.VerneedV.size(); ++I) {
754 const ELFYAML::VerneedEntry &VE = Section.VerneedV[I];
George Rimar0621b792019-02-19 14:53:48 +0000755
George Rimarda1b3ab2019-04-26 12:15:32 +0000756 Elf_Verneed VerNeed;
757 VerNeed.vn_version = VE.Version;
758 VerNeed.vn_file = DotDynstr.getOffset(VE.File);
759 if (I == Section.VerneedV.size() - 1)
760 VerNeed.vn_next = 0;
761 else
762 VerNeed.vn_next =
763 sizeof(Elf_Verneed) + VE.AuxV.size() * sizeof(Elf_Vernaux);
764 VerNeed.vn_cnt = VE.AuxV.size();
765 VerNeed.vn_aux = sizeof(Elf_Verneed);
766 OS.write((const char *)&VerNeed, sizeof(Elf_Verneed));
George Rimar0621b792019-02-19 14:53:48 +0000767
George Rimarda1b3ab2019-04-26 12:15:32 +0000768 for (size_t J = 0; J < VE.AuxV.size(); ++J, ++AuxCnt) {
769 const ELFYAML::VernauxEntry &VAuxE = VE.AuxV[J];
George Rimar0621b792019-02-19 14:53:48 +0000770
George Rimarda1b3ab2019-04-26 12:15:32 +0000771 Elf_Vernaux VernAux;
772 VernAux.vna_hash = VAuxE.Hash;
773 VernAux.vna_flags = VAuxE.Flags;
774 VernAux.vna_other = VAuxE.Other;
775 VernAux.vna_name = DotDynstr.getOffset(VAuxE.Name);
776 if (J == VE.AuxV.size() - 1)
777 VernAux.vna_next = 0;
778 else
779 VernAux.vna_next = sizeof(Elf_Vernaux);
780 OS.write((const char *)&VernAux, sizeof(Elf_Vernaux));
781 }
782 }
George Rimar0621b792019-02-19 14:53:48 +0000783
George Rimarda1b3ab2019-04-26 12:15:32 +0000784 SHeader.sh_size = Section.VerneedV.size() * sizeof(Elf_Verneed) +
785 AuxCnt * sizeof(Elf_Vernaux);
786 SHeader.sh_info = Section.Info;
George Rimar0621b792019-02-19 14:53:48 +0000787
George Rimarda1b3ab2019-04-26 12:15:32 +0000788 return true;
George Rimar0621b792019-02-19 14:53:48 +0000789}
790
791template <class ELFT>
792bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000793 const ELFYAML::MipsABIFlags &Section,
794 ContiguousBlobAccumulator &CBA) {
Simon Atanasyan8eb9d1b2015-05-08 07:05:04 +0000795 assert(Section.Type == llvm::ELF::SHT_MIPS_ABIFLAGS &&
796 "Section type is not SHT_MIPS_ABIFLAGS");
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000797
798 object::Elf_Mips_ABIFlags<ELFT> Flags;
799 zero(Flags);
800 SHeader.sh_entsize = sizeof(Flags);
801 SHeader.sh_size = SHeader.sh_entsize;
802
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000803 auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000804 Flags.version = Section.Version;
805 Flags.isa_level = Section.ISALevel;
806 Flags.isa_rev = Section.ISARevision;
807 Flags.gpr_size = Section.GPRSize;
808 Flags.cpr1_size = Section.CPR1Size;
809 Flags.cpr2_size = Section.CPR2Size;
810 Flags.fp_abi = Section.FpABI;
811 Flags.isa_ext = Section.ISAExtension;
812 Flags.ases = Section.ASEs;
813 Flags.flags1 = Section.Flags1;
814 Flags.flags2 = Section.Flags2;
815 OS.write((const char *)&Flags, sizeof(Flags));
816
817 return true;
818}
819
George Rimar0e7ed912019-02-09 11:34:28 +0000820template <class ELFT>
James Hendersonfd997802019-02-25 11:02:24 +0000821bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
George Rimar0e7ed912019-02-09 11:34:28 +0000822 const ELFYAML::DynamicSection &Section,
823 ContiguousBlobAccumulator &CBA) {
George Rimard063c7d2019-02-20 13:58:43 +0000824 typedef typename ELFT::uint uintX_t;
825
George Rimar0e7ed912019-02-09 11:34:28 +0000826 assert(Section.Type == llvm::ELF::SHT_DYNAMIC &&
827 "Section type is not SHT_DYNAMIC");
828
James Hendersonfd997802019-02-25 11:02:24 +0000829 if (!Section.Entries.empty() && Section.Content) {
830 WithColor::error()
831 << "Cannot specify both raw content and explicit entries "
832 "for dynamic section '"
833 << Section.Name << "'.\n";
834 return false;
835 }
836
837 if (Section.Content)
838 SHeader.sh_size = Section.Content->binary_size();
839 else
840 SHeader.sh_size = 2 * sizeof(uintX_t) * Section.Entries.size();
George Rimar0e7ed912019-02-09 11:34:28 +0000841 if (Section.EntSize)
842 SHeader.sh_entsize = *Section.EntSize;
843 else
844 SHeader.sh_entsize = sizeof(Elf_Dyn);
845
George Rimard063c7d2019-02-20 13:58:43 +0000846 raw_ostream &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
George Rimar0e7ed912019-02-09 11:34:28 +0000847 for (const ELFYAML::DynamicEntry &DE : Section.Entries) {
George Rimard063c7d2019-02-20 13:58:43 +0000848 support::endian::write<uintX_t>(OS, DE.Tag, ELFT::TargetEndianness);
849 support::endian::write<uintX_t>(OS, DE.Val, ELFT::TargetEndianness);
George Rimar0e7ed912019-02-09 11:34:28 +0000850 }
James Hendersonfd997802019-02-25 11:02:24 +0000851 if (Section.Content)
852 Section.Content->writeAsBinary(OS);
853
854 return true;
George Rimar0e7ed912019-02-09 11:34:28 +0000855}
856
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000857template <class ELFT> bool ELFState<ELFT>::buildSectionIndex() {
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000858 for (unsigned i = 0, e = Doc.Sections.size(); i != e; ++i) {
George Rimar09746882019-05-07 12:10:51 +0000859 StringRef Name = Doc.Sections[i]->Name;
860 DotShStrtab.add(Name);
861 // "+ 1" to take into account the SHT_NULL entry.
Puyan Lotfia10f0162019-05-11 17:03:36 +0000862 if (!SN2I.addName(Name, i + 1)) {
George Rimar09746882019-05-07 12:10:51 +0000863 WithColor::error() << "Repeated section name: '" << Name
864 << "' at YAML section number " << i << ".\n";
865 return false;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000866 }
Sean Silvaaff51252013-06-21 00:27:50 +0000867 }
Dave Lee17307d92017-11-09 14:53:43 +0000868
869 auto SecNo = 1 + Doc.Sections.size();
870 // Add special sections after input sections, if necessary.
George Rimar5fcdebe2019-04-26 13:09:11 +0000871 for (StringRef Name : implicitSectionNames())
George Rimar36621272019-05-02 19:28:04 +0000872 if (SN2I.addName(Name, SecNo)) {
Dave Lee17307d92017-11-09 14:53:43 +0000873 // Account for this section, since it wasn't in the Doc
874 ++SecNo;
875 DotShStrtab.add(Name);
876 }
877
878 DotShStrtab.finalize();
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000879 return true;
Sean Silva6b083882013-06-18 23:14:03 +0000880}
881
Sean Silvaf99309c2013-06-10 23:44:15 +0000882template <class ELFT>
George Rimar6da44ad2019-04-03 14:53:42 +0000883bool ELFState<ELFT>::buildSymbolIndex(ArrayRef<ELFYAML::Symbol> Symbols) {
884 bool GlobalSymbolSeen = false;
George Rimar33e498b2019-03-11 16:10:02 +0000885 std::size_t I = 0;
George Rimar6da44ad2019-04-03 14:53:42 +0000886 for (const auto &Sym : Symbols) {
887 ++I;
888
889 StringRef Name = Sym.Name;
890 if (Sym.Binding.value == ELF::STB_LOCAL && GlobalSymbolSeen) {
891 WithColor::error() << "Local symbol '" + Name +
892 "' after global in Symbols list.\n";
893 return false;
894 }
George Rimar09746882019-05-07 12:10:51 +0000895 if (Sym.Binding.value != ELF::STB_LOCAL)
896 GlobalSymbolSeen = true;
897
Puyan Lotfia10f0162019-05-11 17:03:36 +0000898 if (!Name.empty() && !SymN2I.addName(Name, I)) {
George Rimar09746882019-05-07 12:10:51 +0000899 WithColor::error() << "Repeated symbol name: '" << Name << "'.\n";
900 return false;
901 }
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000902 }
903 return true;
904}
905
George Rimar0621b792019-02-19 14:53:48 +0000906template <class ELFT> void ELFState<ELFT>::finalizeStrings() {
George Rimar0621b792019-02-19 14:53:48 +0000907 // Add the regular symbol names to .strtab section.
George Rimar6da44ad2019-04-03 14:53:42 +0000908 for (const ELFYAML::Symbol &Sym : Doc.Symbols)
909 DotStrtab.add(Sym.Name);
George Rimar0621b792019-02-19 14:53:48 +0000910 DotStrtab.finalize();
911
George Rimar0621b792019-02-19 14:53:48 +0000912 // Add the dynamic symbol names to .dynstr section.
George Rimar6da44ad2019-04-03 14:53:42 +0000913 for (const ELFYAML::Symbol &Sym : Doc.DynamicSymbols)
914 DotDynstr.add(Sym.Name);
George Rimar0621b792019-02-19 14:53:48 +0000915
George Rimar623ae722019-02-21 12:21:43 +0000916 // SHT_GNU_verdef and SHT_GNU_verneed sections might also
917 // add strings to .dynstr section.
George Rimar0621b792019-02-19 14:53:48 +0000918 for (const std::unique_ptr<ELFYAML::Section> &Sec : Doc.Sections) {
George Rimar623ae722019-02-21 12:21:43 +0000919 if (auto VerNeed = dyn_cast<ELFYAML::VerneedSection>(Sec.get())) {
920 for (const ELFYAML::VerneedEntry &VE : VerNeed->VerneedV) {
921 DotDynstr.add(VE.File);
922 for (const ELFYAML::VernauxEntry &Aux : VE.AuxV)
923 DotDynstr.add(Aux.Name);
924 }
925 } else if (auto VerDef = dyn_cast<ELFYAML::VerdefSection>(Sec.get())) {
926 for (const ELFYAML::VerdefEntry &E : VerDef->Entries)
927 for (StringRef Name : E.VerNames)
928 DotDynstr.add(Name);
George Rimar0621b792019-02-19 14:53:48 +0000929 }
930 }
931
932 DotDynstr.finalize();
933}
934
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000935template <class ELFT>
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000936int ELFState<ELFT>::writeELF(raw_ostream &OS, const ELFYAML::Object &Doc) {
Simon Atanasyan220c54a2014-04-02 16:34:40 +0000937 ELFState<ELFT> State(Doc);
George Rimar0621b792019-02-19 14:53:48 +0000938
939 // Finalize .strtab and .dynstr sections. We do that early because want to
940 // finalize the string table builders before writing the content of the
941 // sections that might want to use them.
942 State.finalizeStrings();
943
Simon Atanasyan220c54a2014-04-02 16:34:40 +0000944 if (!State.buildSectionIndex())
945 return 1;
946
George Rimar33e498b2019-03-11 16:10:02 +0000947 if (!State.buildSymbolIndex(Doc.Symbols))
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000948 return 1;
949
Sean Silva38205932013-06-13 22:19:48 +0000950 Elf_Ehdr Header;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000951 State.initELFHeader(Header);
Sean Silvaf99309c2013-06-10 23:44:15 +0000952
Sean Silva38205932013-06-13 22:19:48 +0000953 // TODO: Flesh out section header support.
Petr Hosekeb04da32017-07-19 20:38:46 +0000954
955 std::vector<Elf_Phdr> PHeaders;
956 State.initProgramHeaders(PHeaders);
Sean Silva38205932013-06-13 22:19:48 +0000957
Sean Silva08a75ae2013-06-20 19:11:44 +0000958 // XXX: This offset is tightly coupled with the order that we write
959 // things to `OS`.
Petr Hosekeb04da32017-07-19 20:38:46 +0000960 const size_t SectionContentBeginOffset = Header.e_ehsize +
961 Header.e_phentsize * Header.e_phnum +
962 Header.e_shentsize * Header.e_shnum;
Sean Silva08a75ae2013-06-20 19:11:44 +0000963 ContiguousBlobAccumulator CBA(SectionContentBeginOffset);
Sean Silvac1c290b2013-06-20 20:59:34 +0000964
Sean Silva38205932013-06-13 22:19:48 +0000965 std::vector<Elf_Shdr> SHeaders;
George Rimar66296dc2019-06-05 13:16:53 +0000966 if (!State.initSectionHeaders(State, SHeaders, CBA))
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000967 return 1;
Sean Silva38205932013-06-13 22:19:48 +0000968
Petr Hosekeb04da32017-07-19 20:38:46 +0000969 // Now we can decide segment offsets
970 State.setProgramHeaderLayout(PHeaders, SHeaders);
971
Sean Silvaf99309c2013-06-10 23:44:15 +0000972 OS.write((const char *)&Header, sizeof(Header));
Petr Hosekeb04da32017-07-19 20:38:46 +0000973 writeArrayData(OS, makeArrayRef(PHeaders));
Will Dietz0b48c732013-10-12 21:29:16 +0000974 writeArrayData(OS, makeArrayRef(SHeaders));
Sean Silva46dffff2013-06-13 22:20:01 +0000975 CBA.writeBlobToStream(OS);
Sean Silva415d93f2013-06-17 20:14:59 +0000976 return 0;
Sean Silvaf99309c2013-06-10 23:44:15 +0000977}
978
Xing GUObac78642018-12-07 11:04:22 +0000979template <class ELFT>
George Rimar5fcdebe2019-04-26 13:09:11 +0000980std::vector<StringRef> ELFState<ELFT>::implicitSectionNames() const {
George Rimar6da44ad2019-04-03 14:53:42 +0000981 if (Doc.DynamicSymbols.empty())
Dave Lee67b49662017-11-16 18:10:15 +0000982 return {".symtab", ".strtab", ".shstrtab"};
983 return {".symtab", ".strtab", ".shstrtab", ".dynsym", ".dynstr"};
984}
985
Chris Bieneman8ff0c112016-06-27 19:53:53 +0000986int yaml2elf(llvm::ELFYAML::Object &Doc, raw_ostream &Out) {
George Rimarbc4d3c42019-04-29 12:25:01 +0000987 bool IsLE = Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB);
988 bool Is64Bit = Doc.Header.Class == ELFYAML::ELF_ELFCLASS(ELF::ELFCLASS64);
989 if (Is64Bit) {
990 if (IsLE)
Rui Ueyama1b31eb92018-01-12 01:40:32 +0000991 return ELFState<object::ELF64LE>::writeELF(Out, Doc);
George Rimarbc4d3c42019-04-29 12:25:01 +0000992 return ELFState<object::ELF64BE>::writeELF(Out, Doc);
Sean Silvaf99309c2013-06-10 23:44:15 +0000993 }
George Rimarbc4d3c42019-04-29 12:25:01 +0000994 if (IsLE)
995 return ELFState<object::ELF32LE>::writeELF(Out, Doc);
996 return ELFState<object::ELF32BE>::writeELF(Out, Doc);
Sean Silvaf99309c2013-06-10 23:44:15 +0000997}