blob: 098c3d6f6bf9f9076da61ea0474bddd8eed070c7 [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;
George Rimarcfa1a622019-06-14 11:01:14 +0000306 if (Sec->Flags)
307 SHeader.sh_flags = *Sec->Flags;
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000308 SHeader.sh_addr = Sec->Address;
309 SHeader.sh_addralign = Sec->AddressAlign;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000310
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000311 if (!Sec->Link.empty()) {
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000312 unsigned Index;
Xing GUO98228352018-12-04 14:27:51 +0000313 if (!convertSectionIndex(SN2I, Sec->Name, Sec->Link, Index))
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000314 return false;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000315 SHeader.sh_link = Index;
316 }
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000317
George Rimareb394e92019-06-07 08:31:36 +0000318 if (auto S = dyn_cast<ELFYAML::RawContentSection>(Sec)) {
George Rimarda1b3ab2019-04-26 12:15:32 +0000319 if (!writeSectionContent(SHeader, *S, CBA))
George Rimar7f2df7d2018-08-16 12:23:22 +0000320 return false;
George Rimareb394e92019-06-07 08:31:36 +0000321 } else if (auto S = dyn_cast<ELFYAML::RelocationSection>(Sec)) {
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000322 if (!writeSectionContent(SHeader, *S, CBA))
323 return false;
George Rimareb394e92019-06-07 08:31:36 +0000324 } else if (auto S = dyn_cast<ELFYAML::Group>(Sec)) {
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000325 if (!writeSectionContent(SHeader, *S, CBA))
326 return false;
George Rimareb394e92019-06-07 08:31:36 +0000327 } else if (auto S = dyn_cast<ELFYAML::MipsABIFlags>(Sec)) {
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000328 if (!writeSectionContent(SHeader, *S, CBA))
329 return false;
George Rimareb394e92019-06-07 08:31:36 +0000330 } else if (auto S = dyn_cast<ELFYAML::NoBitsSection>(Sec)) {
Simon Atanasyan5db02762015-07-03 23:00:54 +0000331 SHeader.sh_entsize = 0;
332 SHeader.sh_size = S->Size;
333 // SHT_NOBITS section does not have content
334 // so just to setup the section offset.
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000335 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
George Rimareb394e92019-06-07 08:31:36 +0000336 } else if (auto S = dyn_cast<ELFYAML::DynamicSection>(Sec)) {
James Hendersonfd997802019-02-25 11:02:24 +0000337 if (!writeSectionContent(SHeader, *S, CBA))
338 return false;
George Rimareb394e92019-06-07 08:31:36 +0000339 } else if (auto S = dyn_cast<ELFYAML::SymverSection>(Sec)) {
George Rimarda1b3ab2019-04-26 12:15:32 +0000340 if (!writeSectionContent(SHeader, *S, CBA))
341 return false;
George Rimareb394e92019-06-07 08:31:36 +0000342 } else if (auto S = dyn_cast<ELFYAML::VerneedSection>(Sec)) {
George Rimarda1b3ab2019-04-26 12:15:32 +0000343 if (!writeSectionContent(SHeader, *S, CBA))
344 return false;
George Rimareb394e92019-06-07 08:31:36 +0000345 } else if (auto S = dyn_cast<ELFYAML::VerdefSection>(Sec)) {
George Rimarda1b3ab2019-04-26 12:15:32 +0000346 if (!writeSectionContent(SHeader, *S, CBA))
347 return false;
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000348 } else
349 llvm_unreachable("Unknown section type");
George Rimar66296dc2019-06-05 13:16:53 +0000350 }
351
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000352 return true;
353}
354
George Rimar6da44ad2019-04-03 14:53:42 +0000355static size_t findFirstNonGlobal(ArrayRef<ELFYAML::Symbol> Symbols) {
356 for (size_t I = 0; I < Symbols.size(); ++I)
357 if (Symbols[I].Binding.value != ELF::STB_LOCAL)
358 return I;
359 return Symbols.size();
360}
361
George Rimar1e410072019-06-10 12:43:18 +0000362static uint64_t writeRawSectionData(raw_ostream &OS,
363 const ELFYAML::RawContentSection &RawSec) {
364 size_t ContentSize = 0;
365 if (RawSec.Content) {
366 RawSec.Content->writeAsBinary(OS);
367 ContentSize = RawSec.Content->binary_size();
368 }
369
370 if (!RawSec.Size)
371 return ContentSize;
372
373 OS.write_zeros(*RawSec.Size - ContentSize);
374 return *RawSec.Size;
375}
376
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000377template <class ELFT>
378void ELFState<ELFT>::initSymtabSectionHeader(Elf_Shdr &SHeader,
Dave Lee67b49662017-11-16 18:10:15 +0000379 SymtabType STType,
George Rimar66296dc2019-06-05 13:16:53 +0000380 ContiguousBlobAccumulator &CBA,
381 ELFYAML::Section *YAMLSec) {
George Rimar1e410072019-06-10 12:43:18 +0000382
Dave Lee67b49662017-11-16 18:10:15 +0000383 bool IsStatic = STType == SymtabType::Static;
George Rimar1e410072019-06-10 12:43:18 +0000384 const auto &Symbols = IsStatic ? Doc.Symbols : Doc.DynamicSymbols;
385
386 ELFYAML::RawContentSection *RawSec =
387 dyn_cast_or_null<ELFYAML::RawContentSection>(YAMLSec);
388 if (RawSec && !Symbols.empty() && (RawSec->Content || RawSec->Size)) {
389 if (RawSec->Content)
390 WithColor::error() << "Cannot specify both `Content` and " +
391 (IsStatic ? Twine("`Symbols`")
392 : Twine("`DynamicSymbols`")) +
393 " for symbol table section '"
394 << RawSec->Name << "'.\n";
395 if (RawSec->Size)
396 WithColor::error() << "Cannot specify both `Size` and " +
397 (IsStatic ? Twine("`Symbols`")
398 : Twine("`DynamicSymbols`")) +
399 " for symbol table section '"
400 << RawSec->Name << "'.\n";
401 exit(1);
402 }
403
404 zero(SHeader);
Dave Lee67b49662017-11-16 18:10:15 +0000405 SHeader.sh_name = DotShStrtab.getOffset(IsStatic ? ".symtab" : ".dynsym");
406 SHeader.sh_type = IsStatic ? ELF::SHT_SYMTAB : ELF::SHT_DYNSYM;
George Rimar379aa182019-06-10 11:38:06 +0000407
George Rimarffb3c722019-06-11 10:00:51 +0000408 if (RawSec && !RawSec->Link.empty()) {
409 // If the Link field is explicitly defined in the document,
410 // we should use it.
411 unsigned Index;
412 if (!convertSectionIndex(SN2I, RawSec->Name, RawSec->Link, Index))
413 return;
414 SHeader.sh_link = Index;
415 } else {
416 // When we describe the .dynsym section in the document explicitly, it is
417 // allowed to omit the "DynamicSymbols" tag. In this case .dynstr is not
418 // added implicitly and we should be able to leave the Link zeroed if
419 // .dynstr is not defined.
420 unsigned Link = 0;
421 if (IsStatic)
422 Link = SN2I.get(".strtab");
423 else
424 SN2I.lookup(".dynstr", Link);
425 SHeader.sh_link = Link;
426 }
George Rimar379aa182019-06-10 11:38:06 +0000427
George Rimarcfa1a622019-06-14 11:01:14 +0000428 if (YAMLSec && YAMLSec->Flags)
429 SHeader.sh_flags = *YAMLSec->Flags;
430 else if (!IsStatic)
431 SHeader.sh_flags = ELF::SHF_ALLOC;
George Rimarc1da1492019-04-26 12:45:54 +0000432
George Rimara7ba1a02019-03-01 10:18:16 +0000433 // If the symbol table section is explicitly described in the YAML
434 // then we should set the fields requested.
George Rimar66296dc2019-06-05 13:16:53 +0000435 SHeader.sh_info =
436 RawSec ? (unsigned)RawSec->Info : findFirstNonGlobal(Symbols) + 1;
437 SHeader.sh_entsize = (YAMLSec && YAMLSec->EntSize)
438 ? (uint64_t)(*YAMLSec->EntSize)
439 : sizeof(Elf_Sym);
440 SHeader.sh_addralign = YAMLSec ? (uint64_t)YAMLSec->AddressAlign : 8;
441 SHeader.sh_addr = YAMLSec ? (uint64_t)YAMLSec->Address : 0;
442
George Rimar1e410072019-06-10 12:43:18 +0000443 auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
444 if (RawSec && (RawSec->Content || RawSec->Size)) {
445 assert(Symbols.empty());
446 SHeader.sh_size = writeRawSectionData(OS, *RawSec);
447 return;
George Rimar6947acd2019-02-19 12:15:04 +0000448 }
George Rimar1e410072019-06-10 12:43:18 +0000449
450 std::vector<Elf_Sym> Syms;
451 {
452 // Ensure STN_UNDEF is present
453 Elf_Sym Sym;
454 zero(Sym);
455 Syms.push_back(Sym);
456 }
457
458 addSymbols(Symbols, Syms, IsStatic ? DotStrtab : DotDynstr);
459 writeArrayData(OS, makeArrayRef(Syms));
460 SHeader.sh_size = arrayDataSize(makeArrayRef(Syms));
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000461}
462
463template <class ELFT>
464void ELFState<ELFT>::initStrtabSectionHeader(Elf_Shdr &SHeader, StringRef Name,
465 StringTableBuilder &STB,
George Rimar66296dc2019-06-05 13:16:53 +0000466 ContiguousBlobAccumulator &CBA,
467 ELFYAML::Section *YAMLSec) {
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000468 zero(SHeader);
Hans Wennborg59f0cba2014-04-30 19:38:09 +0000469 SHeader.sh_name = DotShStrtab.getOffset(Name);
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000470 SHeader.sh_type = ELF::SHT_STRTAB;
George Rimar66296dc2019-06-05 13:16:53 +0000471 SHeader.sh_addralign = YAMLSec ? (uint64_t)YAMLSec->AddressAlign : 1;
472
473 ELFYAML::RawContentSection *RawSec =
474 dyn_cast_or_null<ELFYAML::RawContentSection>(YAMLSec);
George Rimar1e410072019-06-10 12:43:18 +0000475
476 auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
477 if (RawSec && (RawSec->Content || RawSec->Size)) {
478 SHeader.sh_size = writeRawSectionData(OS, *RawSec);
George Rimar66296dc2019-06-05 13:16:53 +0000479 } else {
George Rimar1e410072019-06-10 12:43:18 +0000480 STB.write(OS);
George Rimar66296dc2019-06-05 13:16:53 +0000481 SHeader.sh_size = STB.getSize();
482 }
483
484 if (YAMLSec && YAMLSec->EntSize)
485 SHeader.sh_entsize = *YAMLSec->EntSize;
George Rimar6947acd2019-02-19 12:15:04 +0000486
George Rimarcfa1a622019-06-14 11:01:14 +0000487 if (YAMLSec && YAMLSec->Flags)
488 SHeader.sh_flags = *YAMLSec->Flags;
489 else if (Name == ".dynstr")
490 SHeader.sh_flags = ELF::SHF_ALLOC;
491
George Rimar43f62ff2019-06-14 11:13:32 +0000492 // If the section is explicitly described in the YAML
George Rimar6947acd2019-02-19 12:15:04 +0000493 // then we want to use its section address.
George Rimar43f62ff2019-06-14 11:13:32 +0000494 if (YAMLSec)
George Rimarcfa1a622019-06-14 11:01:14 +0000495 SHeader.sh_addr = YAMLSec->Address;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000496}
497
498template <class ELFT>
Petr Hosekeb04da32017-07-19 20:38:46 +0000499void ELFState<ELFT>::setProgramHeaderLayout(std::vector<Elf_Phdr> &PHeaders,
500 std::vector<Elf_Shdr> &SHeaders) {
501 uint32_t PhdrIdx = 0;
502 for (auto &YamlPhdr : Doc.ProgramHeaders) {
George Rimarf5345a32019-05-01 09:45:55 +0000503 Elf_Phdr &PHeader = PHeaders[PhdrIdx++];
504
Puyan Lotfia10f0162019-05-11 17:03:36 +0000505 std::vector<Elf_Shdr *> Sections;
506 for (const ELFYAML::SectionName &SecName : YamlPhdr.Sections) {
507 unsigned Index;
508 if (!SN2I.lookup(SecName.Section, Index)) {
509 WithColor::error() << "Unknown section referenced: '" << SecName.Section
510 << "' by program header.\n";
511 exit(1);
George Rimarf5345a32019-05-01 09:45:55 +0000512 }
513 Sections.push_back(&SHeaders[Index]);
514 }
Petr Hosekeb04da32017-07-19 20:38:46 +0000515
James Hendersonb10f48b2019-03-15 10:35:27 +0000516 if (YamlPhdr.Offset) {
517 PHeader.p_offset = *YamlPhdr.Offset;
518 } else {
519 if (YamlPhdr.Sections.size())
520 PHeader.p_offset = UINT32_MAX;
Petr Hosekeb04da32017-07-19 20:38:46 +0000521 else
James Hendersonb10f48b2019-03-15 10:35:27 +0000522 PHeader.p_offset = 0;
523
524 // Find the minimum offset for the program header.
George Rimarf5345a32019-05-01 09:45:55 +0000525 for (Elf_Shdr *SHeader : Sections)
526 PHeader.p_offset = std::min(PHeader.p_offset, SHeader->sh_offset);
Petr Hosekeb04da32017-07-19 20:38:46 +0000527 }
528
James Hendersonb10f48b2019-03-15 10:35:27 +0000529 // Find the maximum offset of the end of a section in order to set p_filesz,
530 // if not set explicitly.
531 if (YamlPhdr.FileSize) {
532 PHeader.p_filesz = *YamlPhdr.FileSize;
533 } else {
534 PHeader.p_filesz = 0;
George Rimarf5345a32019-05-01 09:45:55 +0000535 for (Elf_Shdr *SHeader : Sections) {
James Hendersonb10f48b2019-03-15 10:35:27 +0000536 uint64_t EndOfSection;
George Rimarf5345a32019-05-01 09:45:55 +0000537 if (SHeader->sh_type == llvm::ELF::SHT_NOBITS)
538 EndOfSection = SHeader->sh_offset;
James Hendersonb10f48b2019-03-15 10:35:27 +0000539 else
George Rimarf5345a32019-05-01 09:45:55 +0000540 EndOfSection = SHeader->sh_offset + SHeader->sh_size;
James Hendersonb10f48b2019-03-15 10:35:27 +0000541 uint64_t EndOfSegment = PHeader.p_offset + PHeader.p_filesz;
542 EndOfSegment = std::max(EndOfSegment, EndOfSection);
543 PHeader.p_filesz = EndOfSegment - PHeader.p_offset;
544 }
545 }
546
547 // If not set explicitly, find the memory size by adding the size of
548 // sections at the end of the segment. These should be empty (size of zero)
549 // and NOBITS sections.
550 if (YamlPhdr.MemSize) {
551 PHeader.p_memsz = *YamlPhdr.MemSize;
552 } else {
553 PHeader.p_memsz = PHeader.p_filesz;
George Rimarf5345a32019-05-01 09:45:55 +0000554 for (Elf_Shdr *SHeader : Sections)
555 if (SHeader->sh_offset == PHeader.p_offset + PHeader.p_filesz)
556 PHeader.p_memsz += SHeader->sh_size;
Petr Hosekeb04da32017-07-19 20:38:46 +0000557 }
558
559 // Set the alignment of the segment to be the same as the maximum alignment
Jake Ehrlich03aeeb092017-11-01 23:14:48 +0000560 // of the sections with the same offset so that by default the segment
Petr Hosekeb04da32017-07-19 20:38:46 +0000561 // has a valid and sensible alignment.
Jake Ehrlich03aeeb092017-11-01 23:14:48 +0000562 if (YamlPhdr.Align) {
563 PHeader.p_align = *YamlPhdr.Align;
564 } else {
565 PHeader.p_align = 1;
George Rimarf5345a32019-05-01 09:45:55 +0000566 for (Elf_Shdr *SHeader : Sections)
567 if (SHeader->sh_offset == PHeader.p_offset)
568 PHeader.p_align = std::max(PHeader.p_align, SHeader->sh_addralign);
Petr Hosekeb04da32017-07-19 20:38:46 +0000569 }
570 }
571}
572
573template <class ELFT>
George Rimar6da44ad2019-04-03 14:53:42 +0000574void ELFState<ELFT>::addSymbols(ArrayRef<ELFYAML::Symbol> Symbols,
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000575 std::vector<Elf_Sym> &Syms,
Dave Lee67b49662017-11-16 18:10:15 +0000576 const StringTableBuilder &Strtab) {
Simon Atanasyan048baca2014-03-14 06:53:30 +0000577 for (const auto &Sym : Symbols) {
Sean Silva6b083882013-06-18 23:14:03 +0000578 Elf_Sym Symbol;
579 zero(Symbol);
George Rimar09746882019-05-07 12:10:51 +0000580
581 // If NameIndex, which contains the name offset, is explicitly specified, we
582 // use it. This is useful for preparing broken objects. Otherwise, we add
583 // the specified Name to the string table builder to get its offset.
584 if (Sym.NameIndex)
585 Symbol.st_name = *Sym.NameIndex;
586 else if (!Sym.Name.empty())
Dave Lee67b49662017-11-16 18:10:15 +0000587 Symbol.st_name = Strtab.getOffset(Sym.Name);
George Rimar09746882019-05-07 12:10:51 +0000588
589 Symbol.setBindingAndType(Sym.Binding, Sym.Type);
590 if (!Sym.Section.empty()) {
591 unsigned Index;
Puyan Lotfia10f0162019-05-11 17:03:36 +0000592 if (!SN2I.lookup(Sym.Section, Index)) {
George Rimar09746882019-05-07 12:10:51 +0000593 WithColor::error() << "Unknown section referenced: '" << Sym.Section
594 << "' by YAML symbol " << Sym.Name << ".\n";
595 exit(1);
Sean Silvac4afa6d2013-06-21 01:11:48 +0000596 }
597 Symbol.st_shndx = Index;
Petr Hosek5c469a32017-09-07 20:44:16 +0000598 } else if (Sym.Index) {
599 Symbol.st_shndx = *Sym.Index;
600 }
601 // else Symbol.st_shndex == SHN_UNDEF (== 0), since it was zero'd earlier.
Sean Silva05001b92013-06-20 20:59:47 +0000602 Symbol.st_value = Sym.Value;
Simon Atanasyan60e1a792014-11-06 22:46:24 +0000603 Symbol.st_other = Sym.Other;
Sean Silva05001b92013-06-20 20:59:47 +0000604 Symbol.st_size = Sym.Size;
Sean Silva6b083882013-06-18 23:14:03 +0000605 Syms.push_back(Symbol);
606 }
Sean Silvaaff51252013-06-21 00:27:50 +0000607}
608
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000609template <class ELFT>
George Rimarda1b3ab2019-04-26 12:15:32 +0000610bool ELFState<ELFT>::writeSectionContent(
George Rimarb49e1922019-04-24 13:02:15 +0000611 Elf_Shdr &SHeader, const ELFYAML::RawContentSection &Section,
612 ContiguousBlobAccumulator &CBA) {
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000613 raw_ostream &OS =
614 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
George Rimar1e410072019-06-10 12:43:18 +0000615 SHeader.sh_size = writeRawSectionData(OS, Section);
George Rimarb49e1922019-04-24 13:02:15 +0000616
George Rimar65a68282018-08-07 08:11:38 +0000617 if (Section.EntSize)
618 SHeader.sh_entsize = *Section.EntSize;
619 else if (Section.Type == llvm::ELF::SHT_RELR)
Jake Ehrlich0f440d82018-06-28 21:07:34 +0000620 SHeader.sh_entsize = sizeof(Elf_Relr);
621 else
622 SHeader.sh_entsize = 0;
George Rimara7ba1a02019-03-01 10:18:16 +0000623 SHeader.sh_info = Section.Info;
George Rimarda1b3ab2019-04-26 12:15:32 +0000624 return true;
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000625}
626
Simon Atanasyan5d19c672015-01-25 13:29:25 +0000627static bool isMips64EL(const ELFYAML::Object &Doc) {
628 return Doc.Header.Machine == ELFYAML::ELF_EM(llvm::ELF::EM_MIPS) &&
629 Doc.Header.Class == ELFYAML::ELF_ELFCLASS(ELF::ELFCLASS64) &&
630 Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB);
631}
632
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000633template <class ELFT>
634bool
635ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
636 const ELFYAML::RelocationSection &Section,
637 ContiguousBlobAccumulator &CBA) {
Simon Atanasyan8eb9d1b2015-05-08 07:05:04 +0000638 assert((Section.Type == llvm::ELF::SHT_REL ||
639 Section.Type == llvm::ELF::SHT_RELA) &&
640 "Section type is not SHT_REL nor SHT_RELA");
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000641
642 bool IsRela = Section.Type == llvm::ELF::SHT_RELA;
643 SHeader.sh_entsize = IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
644 SHeader.sh_size = SHeader.sh_entsize * Section.Relocations.size();
645
George Rimarda1b3ab2019-04-26 12:15:32 +0000646 // For relocation section set link to .symtab by default.
647 if (Section.Link.empty())
George Rimard71017b2019-06-10 09:57:29 +0000648 SHeader.sh_link = SN2I.get(".symtab");
George Rimarda1b3ab2019-04-26 12:15:32 +0000649
650 unsigned Index = 0;
651 if (!Section.RelocatableSec.empty() &&
652 !convertSectionIndex(SN2I, Section.Name, Section.RelocatableSec, Index))
653 return false;
654 SHeader.sh_info = Index;
655
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000656 auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000657
658 for (const auto &Rel : Section.Relocations) {
George Rimar09746882019-05-07 12:10:51 +0000659 unsigned SymIdx = 0;
660 // If a relocation references a symbol, try to look one up in the symbol
661 // table. If it is not there, treat the value as a symbol index.
Puyan Lotfia10f0162019-05-11 17:03:36 +0000662 if (Rel.Symbol && !SymN2I.lookup(*Rel.Symbol, SymIdx) &&
George Rimar09746882019-05-07 12:10:51 +0000663 !to_integer(*Rel.Symbol, SymIdx)) {
664 WithColor::error() << "Unknown symbol referenced: '" << *Rel.Symbol
665 << "' at YAML section '" << Section.Name << "'.\n";
James Henderson9bc817a2019-03-12 17:00:25 +0000666 return false;
667 }
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000668
669 if (IsRela) {
670 Elf_Rela REntry;
671 zero(REntry);
672 REntry.r_offset = Rel.Offset;
673 REntry.r_addend = Rel.Addend;
Simon Atanasyan5d19c672015-01-25 13:29:25 +0000674 REntry.setSymbolAndType(SymIdx, Rel.Type, isMips64EL(Doc));
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000675 OS.write((const char *)&REntry, sizeof(REntry));
676 } else {
677 Elf_Rel REntry;
678 zero(REntry);
679 REntry.r_offset = Rel.Offset;
Simon Atanasyan5d19c672015-01-25 13:29:25 +0000680 REntry.setSymbolAndType(SymIdx, Rel.Type, isMips64EL(Doc));
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000681 OS.write((const char *)&REntry, sizeof(REntry));
682 }
683 }
684 return true;
685}
686
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000687template <class ELFT>
688bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
689 const ELFYAML::Group &Section,
690 ContiguousBlobAccumulator &CBA) {
Simon Atanasyan8eb9d1b2015-05-08 07:05:04 +0000691 assert(Section.Type == llvm::ELF::SHT_GROUP &&
692 "Section type is not SHT_GROUP");
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000693
George Rimard063c7d2019-02-20 13:58:43 +0000694 SHeader.sh_entsize = 4;
George Rimar09746882019-05-07 12:10:51 +0000695 SHeader.sh_size = SHeader.sh_entsize * Section.Members.size();
696
Puyan Lotfia10f0162019-05-11 17:03:36 +0000697 unsigned SymIdx;
698 if (!SymN2I.lookup(Section.Signature, SymIdx) &&
699 !to_integer(Section.Signature, SymIdx)) {
700 WithColor::error() << "Unknown symbol referenced: '" << Section.Signature
701 << "' at YAML section '" << Section.Name << "'.\n";
George Rimarda1b3ab2019-04-26 12:15:32 +0000702 return false;
703 }
704 SHeader.sh_info = SymIdx;
705
George Rimard063c7d2019-02-20 13:58:43 +0000706 raw_ostream &OS =
707 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000708
George Rimarfb7780a2019-04-26 12:20:51 +0000709 for (const ELFYAML::SectionOrType &Member : Section.Members) {
710 unsigned int SectionIndex = 0;
711 if (Member.sectionNameOrType == "GRP_COMDAT")
712 SectionIndex = llvm::ELF::GRP_COMDAT;
713 else if (!convertSectionIndex(SN2I, Section.Name, Member.sectionNameOrType,
714 SectionIndex))
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000715 return false;
George Rimarfb7780a2019-04-26 12:20:51 +0000716 support::endian::write<uint32_t>(OS, SectionIndex, ELFT::TargetEndianness);
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000717 }
718 return true;
719}
720
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000721template <class ELFT>
722bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
George Rimar646af082019-02-19 15:29:07 +0000723 const ELFYAML::SymverSection &Section,
724 ContiguousBlobAccumulator &CBA) {
George Rimar646af082019-02-19 15:29:07 +0000725 raw_ostream &OS =
726 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
George Rimardac37fb2019-02-20 14:01:02 +0000727 for (uint16_t Version : Section.Entries)
728 support::endian::write<uint16_t>(OS, Version, ELFT::TargetEndianness);
George Rimar646af082019-02-19 15:29:07 +0000729
George Rimard063c7d2019-02-20 13:58:43 +0000730 SHeader.sh_entsize = 2;
731 SHeader.sh_size = Section.Entries.size() * SHeader.sh_entsize;
George Rimar646af082019-02-19 15:29:07 +0000732 return true;
733}
734
735template <class ELFT>
736bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
George Rimar623ae722019-02-21 12:21:43 +0000737 const ELFYAML::VerdefSection &Section,
738 ContiguousBlobAccumulator &CBA) {
739 typedef typename ELFT::Verdef Elf_Verdef;
740 typedef typename ELFT::Verdaux Elf_Verdaux;
741 raw_ostream &OS =
742 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
743
744 uint64_t AuxCnt = 0;
745 for (size_t I = 0; I < Section.Entries.size(); ++I) {
746 const ELFYAML::VerdefEntry &E = Section.Entries[I];
747
748 Elf_Verdef VerDef;
749 VerDef.vd_version = E.Version;
750 VerDef.vd_flags = E.Flags;
751 VerDef.vd_ndx = E.VersionNdx;
752 VerDef.vd_hash = E.Hash;
753 VerDef.vd_aux = sizeof(Elf_Verdef);
754 VerDef.vd_cnt = E.VerNames.size();
755 if (I == Section.Entries.size() - 1)
756 VerDef.vd_next = 0;
757 else
758 VerDef.vd_next =
759 sizeof(Elf_Verdef) + E.VerNames.size() * sizeof(Elf_Verdaux);
760 OS.write((const char *)&VerDef, sizeof(Elf_Verdef));
761
762 for (size_t J = 0; J < E.VerNames.size(); ++J, ++AuxCnt) {
763 Elf_Verdaux VernAux;
764 VernAux.vda_name = DotDynstr.getOffset(E.VerNames[J]);
765 if (J == E.VerNames.size() - 1)
766 VernAux.vda_next = 0;
767 else
768 VernAux.vda_next = sizeof(Elf_Verdaux);
769 OS.write((const char *)&VernAux, sizeof(Elf_Verdaux));
770 }
771 }
772
773 SHeader.sh_size = Section.Entries.size() * sizeof(Elf_Verdef) +
774 AuxCnt * sizeof(Elf_Verdaux);
775 SHeader.sh_info = Section.Info;
776
777 return true;
778}
779
780template <class ELFT>
781bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
George Rimar0621b792019-02-19 14:53:48 +0000782 const ELFYAML::VerneedSection &Section,
783 ContiguousBlobAccumulator &CBA) {
George Rimarda1b3ab2019-04-26 12:15:32 +0000784 typedef typename ELFT::Verneed Elf_Verneed;
785 typedef typename ELFT::Vernaux Elf_Vernaux;
George Rimar0621b792019-02-19 14:53:48 +0000786
George Rimarda1b3ab2019-04-26 12:15:32 +0000787 auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
George Rimar0621b792019-02-19 14:53:48 +0000788
George Rimarda1b3ab2019-04-26 12:15:32 +0000789 uint64_t AuxCnt = 0;
790 for (size_t I = 0; I < Section.VerneedV.size(); ++I) {
791 const ELFYAML::VerneedEntry &VE = Section.VerneedV[I];
George Rimar0621b792019-02-19 14:53:48 +0000792
George Rimarda1b3ab2019-04-26 12:15:32 +0000793 Elf_Verneed VerNeed;
794 VerNeed.vn_version = VE.Version;
795 VerNeed.vn_file = DotDynstr.getOffset(VE.File);
796 if (I == Section.VerneedV.size() - 1)
797 VerNeed.vn_next = 0;
798 else
799 VerNeed.vn_next =
800 sizeof(Elf_Verneed) + VE.AuxV.size() * sizeof(Elf_Vernaux);
801 VerNeed.vn_cnt = VE.AuxV.size();
802 VerNeed.vn_aux = sizeof(Elf_Verneed);
803 OS.write((const char *)&VerNeed, sizeof(Elf_Verneed));
George Rimar0621b792019-02-19 14:53:48 +0000804
George Rimarda1b3ab2019-04-26 12:15:32 +0000805 for (size_t J = 0; J < VE.AuxV.size(); ++J, ++AuxCnt) {
806 const ELFYAML::VernauxEntry &VAuxE = VE.AuxV[J];
George Rimar0621b792019-02-19 14:53:48 +0000807
George Rimarda1b3ab2019-04-26 12:15:32 +0000808 Elf_Vernaux VernAux;
809 VernAux.vna_hash = VAuxE.Hash;
810 VernAux.vna_flags = VAuxE.Flags;
811 VernAux.vna_other = VAuxE.Other;
812 VernAux.vna_name = DotDynstr.getOffset(VAuxE.Name);
813 if (J == VE.AuxV.size() - 1)
814 VernAux.vna_next = 0;
815 else
816 VernAux.vna_next = sizeof(Elf_Vernaux);
817 OS.write((const char *)&VernAux, sizeof(Elf_Vernaux));
818 }
819 }
George Rimar0621b792019-02-19 14:53:48 +0000820
George Rimarda1b3ab2019-04-26 12:15:32 +0000821 SHeader.sh_size = Section.VerneedV.size() * sizeof(Elf_Verneed) +
822 AuxCnt * sizeof(Elf_Vernaux);
823 SHeader.sh_info = Section.Info;
George Rimar0621b792019-02-19 14:53:48 +0000824
George Rimarda1b3ab2019-04-26 12:15:32 +0000825 return true;
George Rimar0621b792019-02-19 14:53:48 +0000826}
827
828template <class ELFT>
829bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000830 const ELFYAML::MipsABIFlags &Section,
831 ContiguousBlobAccumulator &CBA) {
Simon Atanasyan8eb9d1b2015-05-08 07:05:04 +0000832 assert(Section.Type == llvm::ELF::SHT_MIPS_ABIFLAGS &&
833 "Section type is not SHT_MIPS_ABIFLAGS");
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000834
835 object::Elf_Mips_ABIFlags<ELFT> Flags;
836 zero(Flags);
837 SHeader.sh_entsize = sizeof(Flags);
838 SHeader.sh_size = SHeader.sh_entsize;
839
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000840 auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000841 Flags.version = Section.Version;
842 Flags.isa_level = Section.ISALevel;
843 Flags.isa_rev = Section.ISARevision;
844 Flags.gpr_size = Section.GPRSize;
845 Flags.cpr1_size = Section.CPR1Size;
846 Flags.cpr2_size = Section.CPR2Size;
847 Flags.fp_abi = Section.FpABI;
848 Flags.isa_ext = Section.ISAExtension;
849 Flags.ases = Section.ASEs;
850 Flags.flags1 = Section.Flags1;
851 Flags.flags2 = Section.Flags2;
852 OS.write((const char *)&Flags, sizeof(Flags));
853
854 return true;
855}
856
George Rimar0e7ed912019-02-09 11:34:28 +0000857template <class ELFT>
James Hendersonfd997802019-02-25 11:02:24 +0000858bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
George Rimar0e7ed912019-02-09 11:34:28 +0000859 const ELFYAML::DynamicSection &Section,
860 ContiguousBlobAccumulator &CBA) {
George Rimard063c7d2019-02-20 13:58:43 +0000861 typedef typename ELFT::uint uintX_t;
862
George Rimar0e7ed912019-02-09 11:34:28 +0000863 assert(Section.Type == llvm::ELF::SHT_DYNAMIC &&
864 "Section type is not SHT_DYNAMIC");
865
James Hendersonfd997802019-02-25 11:02:24 +0000866 if (!Section.Entries.empty() && Section.Content) {
867 WithColor::error()
868 << "Cannot specify both raw content and explicit entries "
869 "for dynamic section '"
870 << Section.Name << "'.\n";
871 return false;
872 }
873
874 if (Section.Content)
875 SHeader.sh_size = Section.Content->binary_size();
876 else
877 SHeader.sh_size = 2 * sizeof(uintX_t) * Section.Entries.size();
George Rimar0e7ed912019-02-09 11:34:28 +0000878 if (Section.EntSize)
879 SHeader.sh_entsize = *Section.EntSize;
880 else
881 SHeader.sh_entsize = sizeof(Elf_Dyn);
882
George Rimard063c7d2019-02-20 13:58:43 +0000883 raw_ostream &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
George Rimar0e7ed912019-02-09 11:34:28 +0000884 for (const ELFYAML::DynamicEntry &DE : Section.Entries) {
George Rimard063c7d2019-02-20 13:58:43 +0000885 support::endian::write<uintX_t>(OS, DE.Tag, ELFT::TargetEndianness);
886 support::endian::write<uintX_t>(OS, DE.Val, ELFT::TargetEndianness);
George Rimar0e7ed912019-02-09 11:34:28 +0000887 }
James Hendersonfd997802019-02-25 11:02:24 +0000888 if (Section.Content)
889 Section.Content->writeAsBinary(OS);
890
891 return true;
George Rimar0e7ed912019-02-09 11:34:28 +0000892}
893
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000894template <class ELFT> bool ELFState<ELFT>::buildSectionIndex() {
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000895 for (unsigned i = 0, e = Doc.Sections.size(); i != e; ++i) {
George Rimar09746882019-05-07 12:10:51 +0000896 StringRef Name = Doc.Sections[i]->Name;
897 DotShStrtab.add(Name);
898 // "+ 1" to take into account the SHT_NULL entry.
Puyan Lotfia10f0162019-05-11 17:03:36 +0000899 if (!SN2I.addName(Name, i + 1)) {
George Rimar09746882019-05-07 12:10:51 +0000900 WithColor::error() << "Repeated section name: '" << Name
901 << "' at YAML section number " << i << ".\n";
902 return false;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000903 }
Sean Silvaaff51252013-06-21 00:27:50 +0000904 }
Dave Lee17307d92017-11-09 14:53:43 +0000905
906 auto SecNo = 1 + Doc.Sections.size();
907 // Add special sections after input sections, if necessary.
George Rimar5fcdebe2019-04-26 13:09:11 +0000908 for (StringRef Name : implicitSectionNames())
George Rimar36621272019-05-02 19:28:04 +0000909 if (SN2I.addName(Name, SecNo)) {
Dave Lee17307d92017-11-09 14:53:43 +0000910 // Account for this section, since it wasn't in the Doc
911 ++SecNo;
912 DotShStrtab.add(Name);
913 }
914
915 DotShStrtab.finalize();
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000916 return true;
Sean Silva6b083882013-06-18 23:14:03 +0000917}
918
Sean Silvaf99309c2013-06-10 23:44:15 +0000919template <class ELFT>
George Rimar6da44ad2019-04-03 14:53:42 +0000920bool ELFState<ELFT>::buildSymbolIndex(ArrayRef<ELFYAML::Symbol> Symbols) {
921 bool GlobalSymbolSeen = false;
George Rimar33e498b2019-03-11 16:10:02 +0000922 std::size_t I = 0;
George Rimar6da44ad2019-04-03 14:53:42 +0000923 for (const auto &Sym : Symbols) {
924 ++I;
925
926 StringRef Name = Sym.Name;
927 if (Sym.Binding.value == ELF::STB_LOCAL && GlobalSymbolSeen) {
928 WithColor::error() << "Local symbol '" + Name +
929 "' after global in Symbols list.\n";
930 return false;
931 }
George Rimar09746882019-05-07 12:10:51 +0000932 if (Sym.Binding.value != ELF::STB_LOCAL)
933 GlobalSymbolSeen = true;
934
Puyan Lotfia10f0162019-05-11 17:03:36 +0000935 if (!Name.empty() && !SymN2I.addName(Name, I)) {
George Rimar09746882019-05-07 12:10:51 +0000936 WithColor::error() << "Repeated symbol name: '" << Name << "'.\n";
937 return false;
938 }
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000939 }
940 return true;
941}
942
George Rimar0621b792019-02-19 14:53:48 +0000943template <class ELFT> void ELFState<ELFT>::finalizeStrings() {
George Rimar0621b792019-02-19 14:53:48 +0000944 // Add the regular symbol names to .strtab section.
George Rimar6da44ad2019-04-03 14:53:42 +0000945 for (const ELFYAML::Symbol &Sym : Doc.Symbols)
946 DotStrtab.add(Sym.Name);
George Rimar0621b792019-02-19 14:53:48 +0000947 DotStrtab.finalize();
948
George Rimar0621b792019-02-19 14:53:48 +0000949 // Add the dynamic symbol names to .dynstr section.
George Rimar6da44ad2019-04-03 14:53:42 +0000950 for (const ELFYAML::Symbol &Sym : Doc.DynamicSymbols)
951 DotDynstr.add(Sym.Name);
George Rimar0621b792019-02-19 14:53:48 +0000952
George Rimar623ae722019-02-21 12:21:43 +0000953 // SHT_GNU_verdef and SHT_GNU_verneed sections might also
954 // add strings to .dynstr section.
George Rimar0621b792019-02-19 14:53:48 +0000955 for (const std::unique_ptr<ELFYAML::Section> &Sec : Doc.Sections) {
George Rimar623ae722019-02-21 12:21:43 +0000956 if (auto VerNeed = dyn_cast<ELFYAML::VerneedSection>(Sec.get())) {
957 for (const ELFYAML::VerneedEntry &VE : VerNeed->VerneedV) {
958 DotDynstr.add(VE.File);
959 for (const ELFYAML::VernauxEntry &Aux : VE.AuxV)
960 DotDynstr.add(Aux.Name);
961 }
962 } else if (auto VerDef = dyn_cast<ELFYAML::VerdefSection>(Sec.get())) {
963 for (const ELFYAML::VerdefEntry &E : VerDef->Entries)
964 for (StringRef Name : E.VerNames)
965 DotDynstr.add(Name);
George Rimar0621b792019-02-19 14:53:48 +0000966 }
967 }
968
969 DotDynstr.finalize();
970}
971
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000972template <class ELFT>
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000973int ELFState<ELFT>::writeELF(raw_ostream &OS, const ELFYAML::Object &Doc) {
Simon Atanasyan220c54a2014-04-02 16:34:40 +0000974 ELFState<ELFT> State(Doc);
George Rimar0621b792019-02-19 14:53:48 +0000975
976 // Finalize .strtab and .dynstr sections. We do that early because want to
977 // finalize the string table builders before writing the content of the
978 // sections that might want to use them.
979 State.finalizeStrings();
980
Simon Atanasyan220c54a2014-04-02 16:34:40 +0000981 if (!State.buildSectionIndex())
982 return 1;
983
George Rimar33e498b2019-03-11 16:10:02 +0000984 if (!State.buildSymbolIndex(Doc.Symbols))
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000985 return 1;
986
Sean Silva38205932013-06-13 22:19:48 +0000987 Elf_Ehdr Header;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000988 State.initELFHeader(Header);
Sean Silvaf99309c2013-06-10 23:44:15 +0000989
Sean Silva38205932013-06-13 22:19:48 +0000990 // TODO: Flesh out section header support.
Petr Hosekeb04da32017-07-19 20:38:46 +0000991
992 std::vector<Elf_Phdr> PHeaders;
993 State.initProgramHeaders(PHeaders);
Sean Silva38205932013-06-13 22:19:48 +0000994
Sean Silva08a75ae2013-06-20 19:11:44 +0000995 // XXX: This offset is tightly coupled with the order that we write
996 // things to `OS`.
Petr Hosekeb04da32017-07-19 20:38:46 +0000997 const size_t SectionContentBeginOffset = Header.e_ehsize +
998 Header.e_phentsize * Header.e_phnum +
999 Header.e_shentsize * Header.e_shnum;
Sean Silva08a75ae2013-06-20 19:11:44 +00001000 ContiguousBlobAccumulator CBA(SectionContentBeginOffset);
Sean Silvac1c290b2013-06-20 20:59:34 +00001001
Sean Silva38205932013-06-13 22:19:48 +00001002 std::vector<Elf_Shdr> SHeaders;
George Rimar66296dc2019-06-05 13:16:53 +00001003 if (!State.initSectionHeaders(State, SHeaders, CBA))
Simon Atanasyan3ee21b02014-04-02 16:34:54 +00001004 return 1;
Sean Silva38205932013-06-13 22:19:48 +00001005
Petr Hosekeb04da32017-07-19 20:38:46 +00001006 // Now we can decide segment offsets
1007 State.setProgramHeaderLayout(PHeaders, SHeaders);
1008
Sean Silvaf99309c2013-06-10 23:44:15 +00001009 OS.write((const char *)&Header, sizeof(Header));
Petr Hosekeb04da32017-07-19 20:38:46 +00001010 writeArrayData(OS, makeArrayRef(PHeaders));
Will Dietz0b48c732013-10-12 21:29:16 +00001011 writeArrayData(OS, makeArrayRef(SHeaders));
Sean Silva46dffff2013-06-13 22:20:01 +00001012 CBA.writeBlobToStream(OS);
Sean Silva415d93f2013-06-17 20:14:59 +00001013 return 0;
Sean Silvaf99309c2013-06-10 23:44:15 +00001014}
1015
Xing GUObac78642018-12-07 11:04:22 +00001016template <class ELFT>
George Rimar5fcdebe2019-04-26 13:09:11 +00001017std::vector<StringRef> ELFState<ELFT>::implicitSectionNames() const {
George Rimar6da44ad2019-04-03 14:53:42 +00001018 if (Doc.DynamicSymbols.empty())
Dave Lee67b49662017-11-16 18:10:15 +00001019 return {".symtab", ".strtab", ".shstrtab"};
1020 return {".symtab", ".strtab", ".shstrtab", ".dynsym", ".dynstr"};
1021}
1022
Chris Bieneman8ff0c112016-06-27 19:53:53 +00001023int yaml2elf(llvm::ELFYAML::Object &Doc, raw_ostream &Out) {
George Rimarbc4d3c42019-04-29 12:25:01 +00001024 bool IsLE = Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB);
1025 bool Is64Bit = Doc.Header.Class == ELFYAML::ELF_ELFCLASS(ELF::ELFCLASS64);
1026 if (Is64Bit) {
1027 if (IsLE)
Rui Ueyama1b31eb92018-01-12 01:40:32 +00001028 return ELFState<object::ELF64LE>::writeELF(Out, Doc);
George Rimarbc4d3c42019-04-29 12:25:01 +00001029 return ELFState<object::ELF64BE>::writeELF(Out, Doc);
Sean Silvaf99309c2013-06-10 23:44:15 +00001030 }
George Rimarbc4d3c42019-04-29 12:25:01 +00001031 if (IsLE)
1032 return ELFState<object::ELF32LE>::writeELF(Out, Doc);
1033 return ELFState<object::ELF32BE>::writeELF(Out, Doc);
Sean Silvaf99309c2013-06-10 23:44:15 +00001034}