blob: 48da02688de6dbbd5eedfba10f3020a56e04ce25 [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 {
George Rimar36621272019-05-02 19:28:04 +000063 StringMap<unsigned> Map;
64
George Rimar09746882019-05-07 12:10:51 +000065public:
George Rimar36621272019-05-02 19:28:04 +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 }
George Rimar36621272019-05-02 19:28:04 +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 {
George Rimar36621272019-05-02 19:28:04 +000072 auto I = Map.find(Name);
George Rimar09746882019-05-07 12:10:51 +000073 if (I == Map.end())
George Rimar36621272019-05-02 19:28:04 +000074 return false;
George Rimar09746882019-05-07 12:10:51 +000075 Idx = I->getValue();
George Rimar36621272019-05-02 19:28:04 +000076 return true;
George Rimar09746882019-05-07 12:10:51 +000077 }
George Rimar36621272019-05-02 19:28:04 +000078 /// Asserts if name is not present in the map.
George Rimar09746882019-05-07 12:10:51 +000079 unsigned get(StringRef Name) const {
George Rimar36621272019-05-02 19:28:04 +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);
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000139 bool initSectionHeaders(std::vector<Elf_Shdr> &SHeaders,
140 ContiguousBlobAccumulator &CBA);
Dave Lee67b49662017-11-16 18:10:15 +0000141 void initSymtabSectionHeader(Elf_Shdr &SHeader, SymtabType STType,
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000142 ContiguousBlobAccumulator &CBA);
143 void initStrtabSectionHeader(Elf_Shdr &SHeader, StringRef Name,
144 StringTableBuilder &STB,
145 ContiguousBlobAccumulator &CBA);
Petr Hosekeb04da32017-07-19 20:38:46 +0000146 void setProgramHeaderLayout(std::vector<Elf_Phdr> &PHeaders,
147 std::vector<Elf_Shdr> &SHeaders);
George Rimar6da44ad2019-04-03 14:53:42 +0000148 void addSymbols(ArrayRef<ELFYAML::Symbol> Symbols, std::vector<Elf_Sym> &Syms,
Dave Lee67b49662017-11-16 18:10:15 +0000149 const StringTableBuilder &Strtab);
George Rimarda1b3ab2019-04-26 12:15:32 +0000150 bool writeSectionContent(Elf_Shdr &SHeader,
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000151 const ELFYAML::RawContentSection &Section,
152 ContiguousBlobAccumulator &CBA);
153 bool writeSectionContent(Elf_Shdr &SHeader,
154 const ELFYAML::RelocationSection &Section,
155 ContiguousBlobAccumulator &CBA);
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000156 bool writeSectionContent(Elf_Shdr &SHeader, const ELFYAML::Group &Group,
157 ContiguousBlobAccumulator &CBA);
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000158 bool writeSectionContent(Elf_Shdr &SHeader,
George Rimar646af082019-02-19 15:29:07 +0000159 const ELFYAML::SymverSection &Section,
160 ContiguousBlobAccumulator &CBA);
161 bool writeSectionContent(Elf_Shdr &SHeader,
George Rimar0621b792019-02-19 14:53:48 +0000162 const ELFYAML::VerneedSection &Section,
163 ContiguousBlobAccumulator &CBA);
164 bool writeSectionContent(Elf_Shdr &SHeader,
George Rimar623ae722019-02-21 12:21:43 +0000165 const ELFYAML::VerdefSection &Section,
166 ContiguousBlobAccumulator &CBA);
167 bool writeSectionContent(Elf_Shdr &SHeader,
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000168 const ELFYAML::MipsABIFlags &Section,
169 ContiguousBlobAccumulator &CBA);
James Hendersonfd997802019-02-25 11:02:24 +0000170 bool writeSectionContent(Elf_Shdr &SHeader,
George Rimar0e7ed912019-02-09 11:34:28 +0000171 const ELFYAML::DynamicSection &Section,
172 ContiguousBlobAccumulator &CBA);
George Rimar5fcdebe2019-04-26 13:09:11 +0000173 std::vector<StringRef> implicitSectionNames() const;
Sean Silva08a75ae2013-06-20 19:11:44 +0000174
Simon Atanasyan220c54a2014-04-02 16:34:40 +0000175 // - SHT_NULL entry (placed first, i.e. 0'th entry)
Dave Lee67b49662017-11-16 18:10:15 +0000176 // - symbol table (.symtab) (defaults to after last yaml section)
177 // - string table (.strtab) (defaults to after .symtab)
178 // - section header string table (.shstrtab) (defaults to after .strtab)
179 // - dynamic symbol table (.dynsym) (defaults to after .shstrtab)
180 // - dynamic string table (.dynstr) (defaults to after .dynsym)
Dave Lee17307d92017-11-09 14:53:43 +0000181 unsigned getDotSymTabSecNo() const { return SN2I.get(".symtab"); }
182 unsigned getDotStrTabSecNo() const { return SN2I.get(".strtab"); }
183 unsigned getDotShStrTabSecNo() const { return SN2I.get(".shstrtab"); }
Dave Lee67b49662017-11-16 18:10:15 +0000184 unsigned getDotDynSymSecNo() const { return SN2I.get(".dynsym"); }
185 unsigned getDotDynStrSecNo() const { return SN2I.get(".dynstr"); }
Dave Lee17307d92017-11-09 14:53:43 +0000186 unsigned getSectionCount() const { return SN2I.size() + 1; }
Simon Atanasyan220c54a2014-04-02 16:34:40 +0000187
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000188 ELFState(const ELFYAML::Object &D) : Doc(D) {}
Simon Atanasyan220c54a2014-04-02 16:34:40 +0000189
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000190public:
191 static int writeELF(raw_ostream &OS, const ELFYAML::Object &Doc);
George Rimar0621b792019-02-19 14:53:48 +0000192
193private:
194 void finalizeStrings();
Sean Silva08a75ae2013-06-20 19:11:44 +0000195};
196} // end anonymous namespace
197
Sean Silva37e817c2013-06-21 00:33:01 +0000198template <class ELFT>
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000199void ELFState<ELFT>::initELFHeader(Elf_Ehdr &Header) {
200 using namespace llvm::ELF;
201 zero(Header);
202 Header.e_ident[EI_MAG0] = 0x7f;
203 Header.e_ident[EI_MAG1] = 'E';
204 Header.e_ident[EI_MAG2] = 'L';
205 Header.e_ident[EI_MAG3] = 'F';
206 Header.e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;
George Rimara5a0a0f2019-03-07 12:09:19 +0000207 Header.e_ident[EI_DATA] = Doc.Header.Data;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000208 Header.e_ident[EI_VERSION] = EV_CURRENT;
209 Header.e_ident[EI_OSABI] = Doc.Header.OSABI;
George Rimar6367d7a2018-12-20 10:43:49 +0000210 Header.e_ident[EI_ABIVERSION] = Doc.Header.ABIVersion;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000211 Header.e_type = Doc.Header.Type;
212 Header.e_machine = Doc.Header.Machine;
213 Header.e_version = EV_CURRENT;
214 Header.e_entry = Doc.Header.Entry;
Petr Hosekeb04da32017-07-19 20:38:46 +0000215 Header.e_phoff = sizeof(Header);
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000216 Header.e_flags = Doc.Header.Flags;
217 Header.e_ehsize = sizeof(Elf_Ehdr);
Petr Hosekeb04da32017-07-19 20:38:46 +0000218 Header.e_phentsize = sizeof(Elf_Phdr);
219 Header.e_phnum = Doc.ProgramHeaders.size();
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000220 Header.e_shentsize = sizeof(Elf_Shdr);
Petr Hosekeb04da32017-07-19 20:38:46 +0000221 // Immediately following the ELF header and program headers.
222 Header.e_shoff =
223 sizeof(Header) + sizeof(Elf_Phdr) * Doc.ProgramHeaders.size();
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000224 Header.e_shnum = getSectionCount();
225 Header.e_shstrndx = getDotShStrTabSecNo();
226}
227
228template <class ELFT>
Petr Hosekeb04da32017-07-19 20:38:46 +0000229void ELFState<ELFT>::initProgramHeaders(std::vector<Elf_Phdr> &PHeaders) {
230 for (const auto &YamlPhdr : Doc.ProgramHeaders) {
231 Elf_Phdr Phdr;
232 Phdr.p_type = YamlPhdr.Type;
233 Phdr.p_flags = YamlPhdr.Flags;
234 Phdr.p_vaddr = YamlPhdr.VAddr;
235 Phdr.p_paddr = YamlPhdr.PAddr;
236 PHeaders.push_back(Phdr);
237 }
238}
George Rimar09746882019-05-07 12:10:51 +0000239
240static bool convertSectionIndex(NameToIdxMap &SN2I, StringRef SecName,
241 StringRef IndexSrc, unsigned &IndexDest) {
George Rimar36621272019-05-02 19:28:04 +0000242 if (!SN2I.lookup(IndexSrc, IndexDest) && !to_integer(IndexSrc, IndexDest)) {
George Rimar09746882019-05-07 12:10:51 +0000243 WithColor::error() << "Unknown section referenced: '" << IndexSrc
244 << "' at YAML section '" << SecName << "'.\n";
245 return false;
Xing GUO98228352018-12-04 14:27:51 +0000246 }
247 return true;
248}
249
Petr Hosekeb04da32017-07-19 20:38:46 +0000250template <class ELFT>
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000251bool ELFState<ELFT>::initSectionHeaders(std::vector<Elf_Shdr> &SHeaders,
252 ContiguousBlobAccumulator &CBA) {
253 // Ensure SHN_UNDEF entry is present. An all-zero section header is a
254 // valid SHN_UNDEF entry since SHT_NULL == 0.
255 Elf_Shdr SHeader;
256 zero(SHeader);
257 SHeaders.push_back(SHeader);
258
259 for (const auto &Sec : Doc.Sections) {
260 zero(SHeader);
Hans Wennborg59f0cba2014-04-30 19:38:09 +0000261 SHeader.sh_name = DotShStrtab.getOffset(Sec->Name);
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000262 SHeader.sh_type = Sec->Type;
263 SHeader.sh_flags = Sec->Flags;
264 SHeader.sh_addr = Sec->Address;
265 SHeader.sh_addralign = Sec->AddressAlign;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000266
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000267 if (!Sec->Link.empty()) {
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000268 unsigned Index;
Xing GUO98228352018-12-04 14:27:51 +0000269 if (!convertSectionIndex(SN2I, Sec->Name, Sec->Link, Index))
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000270 return false;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000271 SHeader.sh_link = Index;
272 }
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000273
George Rimarda1b3ab2019-04-26 12:15:32 +0000274 if (auto S = dyn_cast<ELFYAML::RawContentSection>(Sec.get())) {
275 if (!writeSectionContent(SHeader, *S, CBA))
George Rimar7f2df7d2018-08-16 12:23:22 +0000276 return false;
George Rimarda1b3ab2019-04-26 12:15:32 +0000277 } else if (auto S = dyn_cast<ELFYAML::RelocationSection>(Sec.get())) {
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000278 if (!writeSectionContent(SHeader, *S, CBA))
279 return false;
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000280 } else if (auto S = dyn_cast<ELFYAML::Group>(Sec.get())) {
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000281 if (!writeSectionContent(SHeader, *S, CBA))
282 return false;
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000283 } else if (auto S = dyn_cast<ELFYAML::MipsABIFlags>(Sec.get())) {
284 if (!writeSectionContent(SHeader, *S, CBA))
285 return false;
Simon Atanasyan5db02762015-07-03 23:00:54 +0000286 } else if (auto S = dyn_cast<ELFYAML::NoBitsSection>(Sec.get())) {
287 SHeader.sh_entsize = 0;
288 SHeader.sh_size = S->Size;
289 // SHT_NOBITS section does not have content
290 // so just to setup the section offset.
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000291 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
George Rimar0e7ed912019-02-09 11:34:28 +0000292 } else if (auto S = dyn_cast<ELFYAML::DynamicSection>(Sec.get())) {
James Hendersonfd997802019-02-25 11:02:24 +0000293 if (!writeSectionContent(SHeader, *S, CBA))
294 return false;
George Rimar646af082019-02-19 15:29:07 +0000295 } else if (auto S = dyn_cast<ELFYAML::SymverSection>(Sec.get())) {
George Rimarda1b3ab2019-04-26 12:15:32 +0000296 if (!writeSectionContent(SHeader, *S, CBA))
297 return false;
George Rimar0621b792019-02-19 14:53:48 +0000298 } else if (auto S = dyn_cast<ELFYAML::VerneedSection>(Sec.get())) {
George Rimarda1b3ab2019-04-26 12:15:32 +0000299 if (!writeSectionContent(SHeader, *S, CBA))
300 return false;
George Rimar623ae722019-02-21 12:21:43 +0000301 } else if (auto S = dyn_cast<ELFYAML::VerdefSection>(Sec.get())) {
George Rimarda1b3ab2019-04-26 12:15:32 +0000302 if (!writeSectionContent(SHeader, *S, CBA))
303 return false;
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000304 } else
305 llvm_unreachable("Unknown section type");
306
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000307 SHeaders.push_back(SHeader);
308 }
309 return true;
310}
311
George Rimar6da44ad2019-04-03 14:53:42 +0000312static size_t findFirstNonGlobal(ArrayRef<ELFYAML::Symbol> Symbols) {
313 for (size_t I = 0; I < Symbols.size(); ++I)
314 if (Symbols[I].Binding.value != ELF::STB_LOCAL)
315 return I;
316 return Symbols.size();
317}
318
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000319template <class ELFT>
320void ELFState<ELFT>::initSymtabSectionHeader(Elf_Shdr &SHeader,
Dave Lee67b49662017-11-16 18:10:15 +0000321 SymtabType STType,
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000322 ContiguousBlobAccumulator &CBA) {
323 zero(SHeader);
Dave Lee67b49662017-11-16 18:10:15 +0000324 bool IsStatic = STType == SymtabType::Static;
325 SHeader.sh_name = DotShStrtab.getOffset(IsStatic ? ".symtab" : ".dynsym");
326 SHeader.sh_type = IsStatic ? ELF::SHT_SYMTAB : ELF::SHT_DYNSYM;
327 SHeader.sh_link = IsStatic ? getDotStrTabSecNo() : getDotDynStrSecNo();
George Rimar48288112019-04-29 11:54:10 +0000328 if (!IsStatic)
329 SHeader.sh_flags |= ELF::SHF_ALLOC;
George Rimarc1da1492019-04-26 12:45:54 +0000330
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000331 // One greater than symbol table index of the last local symbol.
George Rimarc1da1492019-04-26 12:45:54 +0000332 const auto &Symbols = IsStatic ? Doc.Symbols : Doc.DynamicSymbols;
George Rimar6da44ad2019-04-03 14:53:42 +0000333 SHeader.sh_info = findFirstNonGlobal(Symbols) + 1;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000334 SHeader.sh_entsize = sizeof(Elf_Sym);
Simon Atanasyan3a120922015-07-09 18:23:02 +0000335 SHeader.sh_addralign = 8;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000336
George Rimara7ba1a02019-03-01 10:18:16 +0000337 // Get the section index ignoring the SHT_NULL section.
338 unsigned SecNdx =
339 IsStatic ? getDotSymTabSecNo() - 1 : getDotDynSymSecNo() - 1;
340 // If the symbol table section is explicitly described in the YAML
341 // then we should set the fields requested.
342 if (SecNdx < Doc.Sections.size()) {
343 ELFYAML::Section *Sec = Doc.Sections[SecNdx].get();
344 SHeader.sh_addr = Sec->Address;
345 if (auto S = dyn_cast<ELFYAML::RawContentSection>(Sec))
346 SHeader.sh_info = S->Info;
George Rimar6947acd2019-02-19 12:15:04 +0000347 }
348
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000349 std::vector<Elf_Sym> Syms;
350 {
351 // Ensure STN_UNDEF is present
352 Elf_Sym Sym;
353 zero(Sym);
354 Syms.push_back(Sym);
355 }
Hans Wennborg59f0cba2014-04-30 19:38:09 +0000356
George Rimarc1da1492019-04-26 12:45:54 +0000357 addSymbols(Symbols, Syms, IsStatic ? DotStrtab : DotDynstr);
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000358
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000359 writeArrayData(
360 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign),
361 makeArrayRef(Syms));
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000362 SHeader.sh_size = arrayDataSize(makeArrayRef(Syms));
363}
364
365template <class ELFT>
366void ELFState<ELFT>::initStrtabSectionHeader(Elf_Shdr &SHeader, StringRef Name,
367 StringTableBuilder &STB,
368 ContiguousBlobAccumulator &CBA) {
369 zero(SHeader);
Hans Wennborg59f0cba2014-04-30 19:38:09 +0000370 SHeader.sh_name = DotShStrtab.getOffset(Name);
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000371 SHeader.sh_type = ELF::SHT_STRTAB;
Rafael Espindola39751af2016-10-04 22:43:25 +0000372 STB.write(CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign));
373 SHeader.sh_size = STB.getSize();
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000374 SHeader.sh_addralign = 1;
George Rimar6947acd2019-02-19 12:15:04 +0000375
376 // If .dynstr section is explicitly described in the YAML
377 // then we want to use its section address.
378 if (Name == ".dynstr") {
379 // Take section index and ignore the SHT_NULL section.
380 unsigned SecNdx = getDotDynStrSecNo() - 1;
381 if (SecNdx < Doc.Sections.size())
382 SHeader.sh_addr = Doc.Sections[SecNdx]->Address;
George Rimar48288112019-04-29 11:54:10 +0000383
384 // We assume that .dynstr is always allocatable.
385 SHeader.sh_flags |= ELF::SHF_ALLOC;
George Rimar6947acd2019-02-19 12:15:04 +0000386 }
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000387}
388
389template <class ELFT>
Petr Hosekeb04da32017-07-19 20:38:46 +0000390void ELFState<ELFT>::setProgramHeaderLayout(std::vector<Elf_Phdr> &PHeaders,
391 std::vector<Elf_Shdr> &SHeaders) {
392 uint32_t PhdrIdx = 0;
393 for (auto &YamlPhdr : Doc.ProgramHeaders) {
George Rimarf5345a32019-05-01 09:45:55 +0000394 Elf_Phdr &PHeader = PHeaders[PhdrIdx++];
395
George Rimar36621272019-05-02 19:28:04 +0000396 std::vector<Elf_Shdr *> Sections;
397 for (const ELFYAML::SectionName &SecName : YamlPhdr.Sections) {
398 unsigned Index;
399 if (!SN2I.lookup(SecName.Section, Index)) {
400 WithColor::error() << "Unknown section referenced: '" << SecName.Section
401 << "' by program header.\n";
402 exit(1);
George Rimarf5345a32019-05-01 09:45:55 +0000403 }
404 Sections.push_back(&SHeaders[Index]);
405 }
Petr Hosekeb04da32017-07-19 20:38:46 +0000406
James Hendersonb10f48b2019-03-15 10:35:27 +0000407 if (YamlPhdr.Offset) {
408 PHeader.p_offset = *YamlPhdr.Offset;
409 } else {
410 if (YamlPhdr.Sections.size())
411 PHeader.p_offset = UINT32_MAX;
Petr Hosekeb04da32017-07-19 20:38:46 +0000412 else
James Hendersonb10f48b2019-03-15 10:35:27 +0000413 PHeader.p_offset = 0;
414
415 // Find the minimum offset for the program header.
George Rimarf5345a32019-05-01 09:45:55 +0000416 for (Elf_Shdr *SHeader : Sections)
417 PHeader.p_offset = std::min(PHeader.p_offset, SHeader->sh_offset);
Petr Hosekeb04da32017-07-19 20:38:46 +0000418 }
419
James Hendersonb10f48b2019-03-15 10:35:27 +0000420 // Find the maximum offset of the end of a section in order to set p_filesz,
421 // if not set explicitly.
422 if (YamlPhdr.FileSize) {
423 PHeader.p_filesz = *YamlPhdr.FileSize;
424 } else {
425 PHeader.p_filesz = 0;
George Rimarf5345a32019-05-01 09:45:55 +0000426 for (Elf_Shdr *SHeader : Sections) {
James Hendersonb10f48b2019-03-15 10:35:27 +0000427 uint64_t EndOfSection;
George Rimarf5345a32019-05-01 09:45:55 +0000428 if (SHeader->sh_type == llvm::ELF::SHT_NOBITS)
429 EndOfSection = SHeader->sh_offset;
James Hendersonb10f48b2019-03-15 10:35:27 +0000430 else
George Rimarf5345a32019-05-01 09:45:55 +0000431 EndOfSection = SHeader->sh_offset + SHeader->sh_size;
James Hendersonb10f48b2019-03-15 10:35:27 +0000432 uint64_t EndOfSegment = PHeader.p_offset + PHeader.p_filesz;
433 EndOfSegment = std::max(EndOfSegment, EndOfSection);
434 PHeader.p_filesz = EndOfSegment - PHeader.p_offset;
435 }
436 }
437
438 // If not set explicitly, find the memory size by adding the size of
439 // sections at the end of the segment. These should be empty (size of zero)
440 // and NOBITS sections.
441 if (YamlPhdr.MemSize) {
442 PHeader.p_memsz = *YamlPhdr.MemSize;
443 } else {
444 PHeader.p_memsz = PHeader.p_filesz;
George Rimarf5345a32019-05-01 09:45:55 +0000445 for (Elf_Shdr *SHeader : Sections)
446 if (SHeader->sh_offset == PHeader.p_offset + PHeader.p_filesz)
447 PHeader.p_memsz += SHeader->sh_size;
Petr Hosekeb04da32017-07-19 20:38:46 +0000448 }
449
450 // Set the alignment of the segment to be the same as the maximum alignment
Jake Ehrlich03aeeb092017-11-01 23:14:48 +0000451 // of the sections with the same offset so that by default the segment
Petr Hosekeb04da32017-07-19 20:38:46 +0000452 // has a valid and sensible alignment.
Jake Ehrlich03aeeb092017-11-01 23:14:48 +0000453 if (YamlPhdr.Align) {
454 PHeader.p_align = *YamlPhdr.Align;
455 } else {
456 PHeader.p_align = 1;
George Rimarf5345a32019-05-01 09:45:55 +0000457 for (Elf_Shdr *SHeader : Sections)
458 if (SHeader->sh_offset == PHeader.p_offset)
459 PHeader.p_align = std::max(PHeader.p_align, SHeader->sh_addralign);
Petr Hosekeb04da32017-07-19 20:38:46 +0000460 }
461 }
462}
463
464template <class ELFT>
George Rimar6da44ad2019-04-03 14:53:42 +0000465void ELFState<ELFT>::addSymbols(ArrayRef<ELFYAML::Symbol> Symbols,
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000466 std::vector<Elf_Sym> &Syms,
Dave Lee67b49662017-11-16 18:10:15 +0000467 const StringTableBuilder &Strtab) {
Simon Atanasyan048baca2014-03-14 06:53:30 +0000468 for (const auto &Sym : Symbols) {
Sean Silva6b083882013-06-18 23:14:03 +0000469 Elf_Sym Symbol;
470 zero(Symbol);
George Rimar09746882019-05-07 12:10:51 +0000471
472 // If NameIndex, which contains the name offset, is explicitly specified, we
473 // use it. This is useful for preparing broken objects. Otherwise, we add
474 // the specified Name to the string table builder to get its offset.
475 if (Sym.NameIndex)
476 Symbol.st_name = *Sym.NameIndex;
477 else if (!Sym.Name.empty())
Dave Lee67b49662017-11-16 18:10:15 +0000478 Symbol.st_name = Strtab.getOffset(Sym.Name);
George Rimar09746882019-05-07 12:10:51 +0000479
480 Symbol.setBindingAndType(Sym.Binding, Sym.Type);
481 if (!Sym.Section.empty()) {
482 unsigned Index;
George Rimar36621272019-05-02 19:28:04 +0000483 if (!SN2I.lookup(Sym.Section, Index)) {
George Rimar09746882019-05-07 12:10:51 +0000484 WithColor::error() << "Unknown section referenced: '" << Sym.Section
485 << "' by YAML symbol " << Sym.Name << ".\n";
486 exit(1);
Sean Silvac4afa6d2013-06-21 01:11:48 +0000487 }
488 Symbol.st_shndx = Index;
Petr Hosek5c469a32017-09-07 20:44:16 +0000489 } else if (Sym.Index) {
490 Symbol.st_shndx = *Sym.Index;
491 }
492 // else Symbol.st_shndex == SHN_UNDEF (== 0), since it was zero'd earlier.
Sean Silva05001b92013-06-20 20:59:47 +0000493 Symbol.st_value = Sym.Value;
Simon Atanasyan60e1a792014-11-06 22:46:24 +0000494 Symbol.st_other = Sym.Other;
Sean Silva05001b92013-06-20 20:59:47 +0000495 Symbol.st_size = Sym.Size;
Sean Silva6b083882013-06-18 23:14:03 +0000496 Syms.push_back(Symbol);
497 }
Sean Silvaaff51252013-06-21 00:27:50 +0000498}
499
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000500template <class ELFT>
George Rimarda1b3ab2019-04-26 12:15:32 +0000501bool ELFState<ELFT>::writeSectionContent(
George Rimarb49e1922019-04-24 13:02:15 +0000502 Elf_Shdr &SHeader, const ELFYAML::RawContentSection &Section,
503 ContiguousBlobAccumulator &CBA) {
Simon Atanasyanb83f3802014-05-16 16:01:00 +0000504 assert(Section.Size >= Section.Content.binary_size() &&
505 "Section size and section content are inconsistent");
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000506 raw_ostream &OS =
507 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
Simon Atanasyanb83f3802014-05-16 16:01:00 +0000508 Section.Content.writeAsBinary(OS);
George Rimarb49e1922019-04-24 13:02:15 +0000509 OS.write_zeros(Section.Size - Section.Content.binary_size());
510
George Rimar65a68282018-08-07 08:11:38 +0000511 if (Section.EntSize)
512 SHeader.sh_entsize = *Section.EntSize;
513 else if (Section.Type == llvm::ELF::SHT_RELR)
Jake Ehrlich0f440d82018-06-28 21:07:34 +0000514 SHeader.sh_entsize = sizeof(Elf_Relr);
515 else
516 SHeader.sh_entsize = 0;
Simon Atanasyanb83f3802014-05-16 16:01:00 +0000517 SHeader.sh_size = Section.Size;
George Rimara7ba1a02019-03-01 10:18:16 +0000518 SHeader.sh_info = Section.Info;
George Rimarda1b3ab2019-04-26 12:15:32 +0000519 return true;
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000520}
521
Simon Atanasyan5d19c672015-01-25 13:29:25 +0000522static bool isMips64EL(const ELFYAML::Object &Doc) {
523 return Doc.Header.Machine == ELFYAML::ELF_EM(llvm::ELF::EM_MIPS) &&
524 Doc.Header.Class == ELFYAML::ELF_ELFCLASS(ELF::ELFCLASS64) &&
525 Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB);
526}
527
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000528template <class ELFT>
529bool
530ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
531 const ELFYAML::RelocationSection &Section,
532 ContiguousBlobAccumulator &CBA) {
Simon Atanasyan8eb9d1b2015-05-08 07:05:04 +0000533 assert((Section.Type == llvm::ELF::SHT_REL ||
534 Section.Type == llvm::ELF::SHT_RELA) &&
535 "Section type is not SHT_REL nor SHT_RELA");
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000536
537 bool IsRela = Section.Type == llvm::ELF::SHT_RELA;
538 SHeader.sh_entsize = IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
539 SHeader.sh_size = SHeader.sh_entsize * Section.Relocations.size();
540
George Rimarda1b3ab2019-04-26 12:15:32 +0000541 // For relocation section set link to .symtab by default.
542 if (Section.Link.empty())
543 SHeader.sh_link = getDotSymTabSecNo();
544
545 unsigned Index = 0;
546 if (!Section.RelocatableSec.empty() &&
547 !convertSectionIndex(SN2I, Section.Name, Section.RelocatableSec, Index))
548 return false;
549 SHeader.sh_info = Index;
550
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000551 auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000552
553 for (const auto &Rel : Section.Relocations) {
George Rimar09746882019-05-07 12:10:51 +0000554 unsigned SymIdx = 0;
555 // If a relocation references a symbol, try to look one up in the symbol
556 // table. If it is not there, treat the value as a symbol index.
George Rimar36621272019-05-02 19:28:04 +0000557 if (Rel.Symbol && !SymN2I.lookup(*Rel.Symbol, SymIdx) &&
George Rimar09746882019-05-07 12:10:51 +0000558 !to_integer(*Rel.Symbol, SymIdx)) {
559 WithColor::error() << "Unknown symbol referenced: '" << *Rel.Symbol
560 << "' at YAML section '" << Section.Name << "'.\n";
James Henderson9bc817a2019-03-12 17:00:25 +0000561 return false;
562 }
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000563
564 if (IsRela) {
565 Elf_Rela REntry;
566 zero(REntry);
567 REntry.r_offset = Rel.Offset;
568 REntry.r_addend = Rel.Addend;
Simon Atanasyan5d19c672015-01-25 13:29:25 +0000569 REntry.setSymbolAndType(SymIdx, Rel.Type, isMips64EL(Doc));
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000570 OS.write((const char *)&REntry, sizeof(REntry));
571 } else {
572 Elf_Rel REntry;
573 zero(REntry);
574 REntry.r_offset = Rel.Offset;
Simon Atanasyan5d19c672015-01-25 13:29:25 +0000575 REntry.setSymbolAndType(SymIdx, Rel.Type, isMips64EL(Doc));
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000576 OS.write((const char *)&REntry, sizeof(REntry));
577 }
578 }
579 return true;
580}
581
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000582template <class ELFT>
583bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
584 const ELFYAML::Group &Section,
585 ContiguousBlobAccumulator &CBA) {
Simon Atanasyan8eb9d1b2015-05-08 07:05:04 +0000586 assert(Section.Type == llvm::ELF::SHT_GROUP &&
587 "Section type is not SHT_GROUP");
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000588
George Rimard063c7d2019-02-20 13:58:43 +0000589 SHeader.sh_entsize = 4;
George Rimar09746882019-05-07 12:10:51 +0000590 SHeader.sh_size = SHeader.sh_entsize * Section.Members.size();
591
George Rimar36621272019-05-02 19:28:04 +0000592 unsigned SymIdx;
593 if (!SymN2I.lookup(Section.Signature, SymIdx) &&
594 !to_integer(Section.Signature, SymIdx)) {
595 WithColor::error() << "Unknown symbol referenced: '" << Section.Signature
596 << "' at YAML section '" << Section.Name << "'.\n";
George Rimarda1b3ab2019-04-26 12:15:32 +0000597 return false;
598 }
599 SHeader.sh_info = SymIdx;
600
George Rimard063c7d2019-02-20 13:58:43 +0000601 raw_ostream &OS =
602 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000603
George Rimarfb7780a2019-04-26 12:20:51 +0000604 for (const ELFYAML::SectionOrType &Member : Section.Members) {
605 unsigned int SectionIndex = 0;
606 if (Member.sectionNameOrType == "GRP_COMDAT")
607 SectionIndex = llvm::ELF::GRP_COMDAT;
608 else if (!convertSectionIndex(SN2I, Section.Name, Member.sectionNameOrType,
609 SectionIndex))
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000610 return false;
George Rimarfb7780a2019-04-26 12:20:51 +0000611 support::endian::write<uint32_t>(OS, SectionIndex, ELFT::TargetEndianness);
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000612 }
613 return true;
614}
615
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000616template <class ELFT>
617bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
George Rimar646af082019-02-19 15:29:07 +0000618 const ELFYAML::SymverSection &Section,
619 ContiguousBlobAccumulator &CBA) {
George Rimar646af082019-02-19 15:29:07 +0000620 raw_ostream &OS =
621 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
George Rimardac37fb2019-02-20 14:01:02 +0000622 for (uint16_t Version : Section.Entries)
623 support::endian::write<uint16_t>(OS, Version, ELFT::TargetEndianness);
George Rimar646af082019-02-19 15:29:07 +0000624
George Rimard063c7d2019-02-20 13:58:43 +0000625 SHeader.sh_entsize = 2;
626 SHeader.sh_size = Section.Entries.size() * SHeader.sh_entsize;
George Rimar646af082019-02-19 15:29:07 +0000627 return true;
628}
629
630template <class ELFT>
631bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
George Rimar623ae722019-02-21 12:21:43 +0000632 const ELFYAML::VerdefSection &Section,
633 ContiguousBlobAccumulator &CBA) {
634 typedef typename ELFT::Verdef Elf_Verdef;
635 typedef typename ELFT::Verdaux Elf_Verdaux;
636 raw_ostream &OS =
637 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
638
639 uint64_t AuxCnt = 0;
640 for (size_t I = 0; I < Section.Entries.size(); ++I) {
641 const ELFYAML::VerdefEntry &E = Section.Entries[I];
642
643 Elf_Verdef VerDef;
644 VerDef.vd_version = E.Version;
645 VerDef.vd_flags = E.Flags;
646 VerDef.vd_ndx = E.VersionNdx;
647 VerDef.vd_hash = E.Hash;
648 VerDef.vd_aux = sizeof(Elf_Verdef);
649 VerDef.vd_cnt = E.VerNames.size();
650 if (I == Section.Entries.size() - 1)
651 VerDef.vd_next = 0;
652 else
653 VerDef.vd_next =
654 sizeof(Elf_Verdef) + E.VerNames.size() * sizeof(Elf_Verdaux);
655 OS.write((const char *)&VerDef, sizeof(Elf_Verdef));
656
657 for (size_t J = 0; J < E.VerNames.size(); ++J, ++AuxCnt) {
658 Elf_Verdaux VernAux;
659 VernAux.vda_name = DotDynstr.getOffset(E.VerNames[J]);
660 if (J == E.VerNames.size() - 1)
661 VernAux.vda_next = 0;
662 else
663 VernAux.vda_next = sizeof(Elf_Verdaux);
664 OS.write((const char *)&VernAux, sizeof(Elf_Verdaux));
665 }
666 }
667
668 SHeader.sh_size = Section.Entries.size() * sizeof(Elf_Verdef) +
669 AuxCnt * sizeof(Elf_Verdaux);
670 SHeader.sh_info = Section.Info;
671
672 return true;
673}
674
675template <class ELFT>
676bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
George Rimar0621b792019-02-19 14:53:48 +0000677 const ELFYAML::VerneedSection &Section,
678 ContiguousBlobAccumulator &CBA) {
George Rimarda1b3ab2019-04-26 12:15:32 +0000679 typedef typename ELFT::Verneed Elf_Verneed;
680 typedef typename ELFT::Vernaux Elf_Vernaux;
George Rimar0621b792019-02-19 14:53:48 +0000681
George Rimarda1b3ab2019-04-26 12:15:32 +0000682 auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
George Rimar0621b792019-02-19 14:53:48 +0000683
George Rimarda1b3ab2019-04-26 12:15:32 +0000684 uint64_t AuxCnt = 0;
685 for (size_t I = 0; I < Section.VerneedV.size(); ++I) {
686 const ELFYAML::VerneedEntry &VE = Section.VerneedV[I];
George Rimar0621b792019-02-19 14:53:48 +0000687
George Rimarda1b3ab2019-04-26 12:15:32 +0000688 Elf_Verneed VerNeed;
689 VerNeed.vn_version = VE.Version;
690 VerNeed.vn_file = DotDynstr.getOffset(VE.File);
691 if (I == Section.VerneedV.size() - 1)
692 VerNeed.vn_next = 0;
693 else
694 VerNeed.vn_next =
695 sizeof(Elf_Verneed) + VE.AuxV.size() * sizeof(Elf_Vernaux);
696 VerNeed.vn_cnt = VE.AuxV.size();
697 VerNeed.vn_aux = sizeof(Elf_Verneed);
698 OS.write((const char *)&VerNeed, sizeof(Elf_Verneed));
George Rimar0621b792019-02-19 14:53:48 +0000699
George Rimarda1b3ab2019-04-26 12:15:32 +0000700 for (size_t J = 0; J < VE.AuxV.size(); ++J, ++AuxCnt) {
701 const ELFYAML::VernauxEntry &VAuxE = VE.AuxV[J];
George Rimar0621b792019-02-19 14:53:48 +0000702
George Rimarda1b3ab2019-04-26 12:15:32 +0000703 Elf_Vernaux VernAux;
704 VernAux.vna_hash = VAuxE.Hash;
705 VernAux.vna_flags = VAuxE.Flags;
706 VernAux.vna_other = VAuxE.Other;
707 VernAux.vna_name = DotDynstr.getOffset(VAuxE.Name);
708 if (J == VE.AuxV.size() - 1)
709 VernAux.vna_next = 0;
710 else
711 VernAux.vna_next = sizeof(Elf_Vernaux);
712 OS.write((const char *)&VernAux, sizeof(Elf_Vernaux));
713 }
714 }
George Rimar0621b792019-02-19 14:53:48 +0000715
George Rimarda1b3ab2019-04-26 12:15:32 +0000716 SHeader.sh_size = Section.VerneedV.size() * sizeof(Elf_Verneed) +
717 AuxCnt * sizeof(Elf_Vernaux);
718 SHeader.sh_info = Section.Info;
George Rimar0621b792019-02-19 14:53:48 +0000719
George Rimarda1b3ab2019-04-26 12:15:32 +0000720 return true;
George Rimar0621b792019-02-19 14:53:48 +0000721}
722
723template <class ELFT>
724bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000725 const ELFYAML::MipsABIFlags &Section,
726 ContiguousBlobAccumulator &CBA) {
Simon Atanasyan8eb9d1b2015-05-08 07:05:04 +0000727 assert(Section.Type == llvm::ELF::SHT_MIPS_ABIFLAGS &&
728 "Section type is not SHT_MIPS_ABIFLAGS");
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000729
730 object::Elf_Mips_ABIFlags<ELFT> Flags;
731 zero(Flags);
732 SHeader.sh_entsize = sizeof(Flags);
733 SHeader.sh_size = SHeader.sh_entsize;
734
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000735 auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000736 Flags.version = Section.Version;
737 Flags.isa_level = Section.ISALevel;
738 Flags.isa_rev = Section.ISARevision;
739 Flags.gpr_size = Section.GPRSize;
740 Flags.cpr1_size = Section.CPR1Size;
741 Flags.cpr2_size = Section.CPR2Size;
742 Flags.fp_abi = Section.FpABI;
743 Flags.isa_ext = Section.ISAExtension;
744 Flags.ases = Section.ASEs;
745 Flags.flags1 = Section.Flags1;
746 Flags.flags2 = Section.Flags2;
747 OS.write((const char *)&Flags, sizeof(Flags));
748
749 return true;
750}
751
George Rimar0e7ed912019-02-09 11:34:28 +0000752template <class ELFT>
James Hendersonfd997802019-02-25 11:02:24 +0000753bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
George Rimar0e7ed912019-02-09 11:34:28 +0000754 const ELFYAML::DynamicSection &Section,
755 ContiguousBlobAccumulator &CBA) {
George Rimard063c7d2019-02-20 13:58:43 +0000756 typedef typename ELFT::uint uintX_t;
757
George Rimar0e7ed912019-02-09 11:34:28 +0000758 assert(Section.Type == llvm::ELF::SHT_DYNAMIC &&
759 "Section type is not SHT_DYNAMIC");
760
James Hendersonfd997802019-02-25 11:02:24 +0000761 if (!Section.Entries.empty() && Section.Content) {
762 WithColor::error()
763 << "Cannot specify both raw content and explicit entries "
764 "for dynamic section '"
765 << Section.Name << "'.\n";
766 return false;
767 }
768
769 if (Section.Content)
770 SHeader.sh_size = Section.Content->binary_size();
771 else
772 SHeader.sh_size = 2 * sizeof(uintX_t) * Section.Entries.size();
George Rimar0e7ed912019-02-09 11:34:28 +0000773 if (Section.EntSize)
774 SHeader.sh_entsize = *Section.EntSize;
775 else
776 SHeader.sh_entsize = sizeof(Elf_Dyn);
777
George Rimard063c7d2019-02-20 13:58:43 +0000778 raw_ostream &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
George Rimar0e7ed912019-02-09 11:34:28 +0000779 for (const ELFYAML::DynamicEntry &DE : Section.Entries) {
George Rimard063c7d2019-02-20 13:58:43 +0000780 support::endian::write<uintX_t>(OS, DE.Tag, ELFT::TargetEndianness);
781 support::endian::write<uintX_t>(OS, DE.Val, ELFT::TargetEndianness);
George Rimar0e7ed912019-02-09 11:34:28 +0000782 }
James Hendersonfd997802019-02-25 11:02:24 +0000783 if (Section.Content)
784 Section.Content->writeAsBinary(OS);
785
786 return true;
George Rimar0e7ed912019-02-09 11:34:28 +0000787}
788
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000789template <class ELFT> bool ELFState<ELFT>::buildSectionIndex() {
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000790 for (unsigned i = 0, e = Doc.Sections.size(); i != e; ++i) {
George Rimar09746882019-05-07 12:10:51 +0000791 StringRef Name = Doc.Sections[i]->Name;
792 DotShStrtab.add(Name);
793 // "+ 1" to take into account the SHT_NULL entry.
George Rimar36621272019-05-02 19:28:04 +0000794 if (!SN2I.addName(Name, i + 1)) {
George Rimar09746882019-05-07 12:10:51 +0000795 WithColor::error() << "Repeated section name: '" << Name
796 << "' at YAML section number " << i << ".\n";
797 return false;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000798 }
Sean Silvaaff51252013-06-21 00:27:50 +0000799 }
Dave Lee17307d92017-11-09 14:53:43 +0000800
801 auto SecNo = 1 + Doc.Sections.size();
802 // Add special sections after input sections, if necessary.
George Rimar5fcdebe2019-04-26 13:09:11 +0000803 for (StringRef Name : implicitSectionNames())
George Rimar36621272019-05-02 19:28:04 +0000804 if (SN2I.addName(Name, SecNo)) {
Dave Lee17307d92017-11-09 14:53:43 +0000805 // Account for this section, since it wasn't in the Doc
806 ++SecNo;
807 DotShStrtab.add(Name);
808 }
809
810 DotShStrtab.finalize();
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000811 return true;
Sean Silva6b083882013-06-18 23:14:03 +0000812}
813
Sean Silvaf99309c2013-06-10 23:44:15 +0000814template <class ELFT>
George Rimar6da44ad2019-04-03 14:53:42 +0000815bool ELFState<ELFT>::buildSymbolIndex(ArrayRef<ELFYAML::Symbol> Symbols) {
816 bool GlobalSymbolSeen = false;
George Rimar33e498b2019-03-11 16:10:02 +0000817 std::size_t I = 0;
George Rimar6da44ad2019-04-03 14:53:42 +0000818 for (const auto &Sym : Symbols) {
819 ++I;
820
821 StringRef Name = Sym.Name;
822 if (Sym.Binding.value == ELF::STB_LOCAL && GlobalSymbolSeen) {
823 WithColor::error() << "Local symbol '" + Name +
824 "' after global in Symbols list.\n";
825 return false;
826 }
George Rimar09746882019-05-07 12:10:51 +0000827 if (Sym.Binding.value != ELF::STB_LOCAL)
828 GlobalSymbolSeen = true;
829
George Rimar36621272019-05-02 19:28:04 +0000830 if (!Name.empty() && !SymN2I.addName(Name, I)) {
George Rimar09746882019-05-07 12:10:51 +0000831 WithColor::error() << "Repeated symbol name: '" << Name << "'.\n";
832 return false;
833 }
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000834 }
835 return true;
836}
837
George Rimar0621b792019-02-19 14:53:48 +0000838template <class ELFT> void ELFState<ELFT>::finalizeStrings() {
George Rimar0621b792019-02-19 14:53:48 +0000839 // Add the regular symbol names to .strtab section.
George Rimar6da44ad2019-04-03 14:53:42 +0000840 for (const ELFYAML::Symbol &Sym : Doc.Symbols)
841 DotStrtab.add(Sym.Name);
George Rimar0621b792019-02-19 14:53:48 +0000842 DotStrtab.finalize();
843
George Rimar6da44ad2019-04-03 14:53:42 +0000844 if (Doc.DynamicSymbols.empty())
George Rimar0621b792019-02-19 14:53:48 +0000845 return;
846
847 // Add the dynamic symbol names to .dynstr section.
George Rimar6da44ad2019-04-03 14:53:42 +0000848 for (const ELFYAML::Symbol &Sym : Doc.DynamicSymbols)
849 DotDynstr.add(Sym.Name);
George Rimar0621b792019-02-19 14:53:48 +0000850
George Rimar623ae722019-02-21 12:21:43 +0000851 // SHT_GNU_verdef and SHT_GNU_verneed sections might also
852 // add strings to .dynstr section.
George Rimar0621b792019-02-19 14:53:48 +0000853 for (const std::unique_ptr<ELFYAML::Section> &Sec : Doc.Sections) {
George Rimar623ae722019-02-21 12:21:43 +0000854 if (auto VerNeed = dyn_cast<ELFYAML::VerneedSection>(Sec.get())) {
855 for (const ELFYAML::VerneedEntry &VE : VerNeed->VerneedV) {
856 DotDynstr.add(VE.File);
857 for (const ELFYAML::VernauxEntry &Aux : VE.AuxV)
858 DotDynstr.add(Aux.Name);
859 }
860 } else if (auto VerDef = dyn_cast<ELFYAML::VerdefSection>(Sec.get())) {
861 for (const ELFYAML::VerdefEntry &E : VerDef->Entries)
862 for (StringRef Name : E.VerNames)
863 DotDynstr.add(Name);
George Rimar0621b792019-02-19 14:53:48 +0000864 }
865 }
866
867 DotDynstr.finalize();
868}
869
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000870template <class ELFT>
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000871int ELFState<ELFT>::writeELF(raw_ostream &OS, const ELFYAML::Object &Doc) {
Simon Atanasyan220c54a2014-04-02 16:34:40 +0000872 ELFState<ELFT> State(Doc);
George Rimar0621b792019-02-19 14:53:48 +0000873
874 // Finalize .strtab and .dynstr sections. We do that early because want to
875 // finalize the string table builders before writing the content of the
876 // sections that might want to use them.
877 State.finalizeStrings();
878
Simon Atanasyan220c54a2014-04-02 16:34:40 +0000879 if (!State.buildSectionIndex())
880 return 1;
881
George Rimar33e498b2019-03-11 16:10:02 +0000882 if (!State.buildSymbolIndex(Doc.Symbols))
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000883 return 1;
884
Sean Silva38205932013-06-13 22:19:48 +0000885 Elf_Ehdr Header;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000886 State.initELFHeader(Header);
Sean Silvaf99309c2013-06-10 23:44:15 +0000887
Sean Silva38205932013-06-13 22:19:48 +0000888 // TODO: Flesh out section header support.
Petr Hosekeb04da32017-07-19 20:38:46 +0000889
890 std::vector<Elf_Phdr> PHeaders;
891 State.initProgramHeaders(PHeaders);
Sean Silva38205932013-06-13 22:19:48 +0000892
Sean Silva08a75ae2013-06-20 19:11:44 +0000893 // XXX: This offset is tightly coupled with the order that we write
894 // things to `OS`.
Petr Hosekeb04da32017-07-19 20:38:46 +0000895 const size_t SectionContentBeginOffset = Header.e_ehsize +
896 Header.e_phentsize * Header.e_phnum +
897 Header.e_shentsize * Header.e_shnum;
Sean Silva08a75ae2013-06-20 19:11:44 +0000898 ContiguousBlobAccumulator CBA(SectionContentBeginOffset);
Sean Silvac1c290b2013-06-20 20:59:34 +0000899
Sean Silva38205932013-06-13 22:19:48 +0000900 std::vector<Elf_Shdr> SHeaders;
George Rimarda1b3ab2019-04-26 12:15:32 +0000901 if (!State.initSectionHeaders(SHeaders, CBA))
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000902 return 1;
Sean Silva38205932013-06-13 22:19:48 +0000903
Dave Lee17307d92017-11-09 14:53:43 +0000904 // Populate SHeaders with implicit sections not present in the Doc
George Rimar5fcdebe2019-04-26 13:09:11 +0000905 for (StringRef Name : State.implicitSectionNames())
Dave Lee17307d92017-11-09 14:53:43 +0000906 if (State.SN2I.get(Name) >= SHeaders.size())
907 SHeaders.push_back({});
Sean Silva82177572013-06-22 01:38:00 +0000908
Dave Lee17307d92017-11-09 14:53:43 +0000909 // Initialize the implicit sections
George Rimar48288112019-04-29 11:54:10 +0000910 State.initSymtabSectionHeader(SHeaders[State.SN2I.get(".symtab")],
911 SymtabType::Static, CBA);
912 State.initStrtabSectionHeader(SHeaders[State.SN2I.get(".strtab")], ".strtab",
913 State.DotStrtab, CBA);
914 State.initStrtabSectionHeader(SHeaders[State.SN2I.get(".shstrtab")],
915 ".shstrtab", State.DotShStrtab, CBA);
George Rimar6da44ad2019-04-03 14:53:42 +0000916 if (!Doc.DynamicSymbols.empty()) {
George Rimar48288112019-04-29 11:54:10 +0000917 State.initSymtabSectionHeader(SHeaders[State.SN2I.get(".dynsym")],
918 SymtabType::Dynamic, CBA);
919 State.initStrtabSectionHeader(SHeaders[State.SN2I.get(".dynstr")],
920 ".dynstr", State.DotDynstr, CBA);
Dave Lee67b49662017-11-16 18:10:15 +0000921 }
Sean Silvaf99309c2013-06-10 23:44:15 +0000922
Petr Hosekeb04da32017-07-19 20:38:46 +0000923 // Now we can decide segment offsets
924 State.setProgramHeaderLayout(PHeaders, SHeaders);
925
Sean Silvaf99309c2013-06-10 23:44:15 +0000926 OS.write((const char *)&Header, sizeof(Header));
Petr Hosekeb04da32017-07-19 20:38:46 +0000927 writeArrayData(OS, makeArrayRef(PHeaders));
Will Dietz0b48c732013-10-12 21:29:16 +0000928 writeArrayData(OS, makeArrayRef(SHeaders));
Sean Silva46dffff2013-06-13 22:20:01 +0000929 CBA.writeBlobToStream(OS);
Sean Silva415d93f2013-06-17 20:14:59 +0000930 return 0;
Sean Silvaf99309c2013-06-10 23:44:15 +0000931}
932
Xing GUObac78642018-12-07 11:04:22 +0000933template <class ELFT>
George Rimar5fcdebe2019-04-26 13:09:11 +0000934std::vector<StringRef> ELFState<ELFT>::implicitSectionNames() const {
George Rimar6da44ad2019-04-03 14:53:42 +0000935 if (Doc.DynamicSymbols.empty())
Dave Lee67b49662017-11-16 18:10:15 +0000936 return {".symtab", ".strtab", ".shstrtab"};
937 return {".symtab", ".strtab", ".shstrtab", ".dynsym", ".dynstr"};
938}
939
Chris Bieneman8ff0c112016-06-27 19:53:53 +0000940int yaml2elf(llvm::ELFYAML::Object &Doc, raw_ostream &Out) {
George Rimarbc4d3c42019-04-29 12:25:01 +0000941 bool IsLE = Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB);
942 bool Is64Bit = Doc.Header.Class == ELFYAML::ELF_ELFCLASS(ELF::ELFCLASS64);
943 if (Is64Bit) {
944 if (IsLE)
Rui Ueyama1b31eb92018-01-12 01:40:32 +0000945 return ELFState<object::ELF64LE>::writeELF(Out, Doc);
George Rimarbc4d3c42019-04-29 12:25:01 +0000946 return ELFState<object::ELF64BE>::writeELF(Out, Doc);
Sean Silvaf99309c2013-06-10 23:44:15 +0000947 }
George Rimarbc4d3c42019-04-29 12:25:01 +0000948 if (IsLE)
949 return ELFState<object::ELF32LE>::writeELF(Out, Doc);
950 return ELFState<object::ELF32BE>::writeELF(Out, Doc);
Sean Silvaf99309c2013-06-10 23:44:15 +0000951}