blob: be733dca6969f825b2a436c74e842ef8efe232b8 [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
Will Dietz0b48c732013-10-12 21:29:16 +000014#include "llvm/ADT/ArrayRef.h"
Alex Brachetc22d9662019-08-07 02:44:49 +000015#include "llvm/ADT/StringSet.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"
Alex Brachetc22d9662019-08-07 02:44:49 +000020#include "llvm/ObjectYAML/yaml2obj.h"
George Rimard063c7d2019-02-20 13:58:43 +000021#include "llvm/Support/EndianStream.h"
George Rimar1a219aa2019-09-24 14:22:37 +000022#include "llvm/Support/LEB128.h"
Sean Silvaf99309c2013-06-10 23:44:15 +000023#include "llvm/Support/MemoryBuffer.h"
Jonas Devlieghere2cd41eb2018-04-21 21:11:59 +000024#include "llvm/Support/WithColor.h"
Sean Silvaf99309c2013-06-10 23:44:15 +000025#include "llvm/Support/YAMLTraits.h"
26#include "llvm/Support/raw_ostream.h"
27
28using namespace llvm;
29
Sean Silva46dffff2013-06-13 22:20:01 +000030// This class is used to build up a contiguous binary blob while keeping
31// track of an offset in the output (which notionally begins at
32// `InitialOffset`).
Sean Silva2a74f702013-06-15 00:31:46 +000033namespace {
Sean Silva46dffff2013-06-13 22:20:01 +000034class ContiguousBlobAccumulator {
35 const uint64_t InitialOffset;
Sean Silvabd3bc692013-06-20 19:11:41 +000036 SmallVector<char, 128> Buf;
Sean Silva46dffff2013-06-13 22:20:01 +000037 raw_svector_ostream OS;
38
georgerimde3cef12019-10-25 13:03:19 +030039public:
40 ContiguousBlobAccumulator(uint64_t InitialOffset_)
41 : InitialOffset(InitialOffset_), Buf(), OS(Buf) {}
42
43 template <class Integer>
44 raw_ostream &getOSAndAlignedOffset(Integer &Offset, unsigned Align) {
45 Offset = padToAlignment(Align);
46 return OS;
47 }
48
Sean Silvad93323f2013-06-22 00:47:43 +000049 /// \returns The new offset.
50 uint64_t padToAlignment(unsigned Align) {
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +000051 if (Align == 0)
52 Align = 1;
Sean Silvad93323f2013-06-22 00:47:43 +000053 uint64_t CurrentOffset = InitialOffset + OS.tell();
Rui Ueyamada00f2f2016-01-14 21:06:47 +000054 uint64_t AlignedOffset = alignTo(CurrentOffset, Align);
George Rimarbd8bfd32019-04-29 12:05:53 +000055 OS.write_zeros(AlignedOffset - CurrentOffset);
Sean Silvad93323f2013-06-22 00:47:43 +000056 return AlignedOffset; // == CurrentOffset;
57 }
58
Sean Silva46dffff2013-06-13 22:20:01 +000059 void writeBlobToStream(raw_ostream &Out) { Out << OS.str(); }
60};
61
Simon Atanasyan35babf92014-04-06 09:02:55 +000062// Used to keep track of section and symbol names, so that in the YAML file
George Rimar09746882019-05-07 12:10:51 +000063// sections and symbols can be referenced by name instead of by index.
George Rimar09746882019-05-07 12:10:51 +000064class NameToIdxMap {
Puyan Lotfia10f0162019-05-11 17:03:36 +000065 StringMap<unsigned> Map;
66
George Rimar09746882019-05-07 12:10:51 +000067public:
Puyan Lotfia10f0162019-05-11 17:03:36 +000068 /// \Returns false if name is already present in the map.
69 bool addName(StringRef Name, unsigned Ndx) {
70 return Map.insert({Name, Ndx}).second;
George Rimar09746882019-05-07 12:10:51 +000071 }
Puyan Lotfia10f0162019-05-11 17:03:36 +000072 /// \Returns false if name is not present in the map.
George Rimar09746882019-05-07 12:10:51 +000073 bool lookup(StringRef Name, unsigned &Idx) const {
Puyan Lotfia10f0162019-05-11 17:03:36 +000074 auto I = Map.find(Name);
George Rimar09746882019-05-07 12:10:51 +000075 if (I == Map.end())
Puyan Lotfia10f0162019-05-11 17:03:36 +000076 return false;
George Rimar09746882019-05-07 12:10:51 +000077 Idx = I->getValue();
Puyan Lotfia10f0162019-05-11 17:03:36 +000078 return true;
George Rimar09746882019-05-07 12:10:51 +000079 }
Puyan Lotfia10f0162019-05-11 17:03:36 +000080 /// Asserts if name is not present in the map.
George Rimar09746882019-05-07 12:10:51 +000081 unsigned get(StringRef Name) const {
Puyan Lotfia10f0162019-05-11 17:03:36 +000082 unsigned Idx;
83 if (lookup(Name, Idx))
84 return Idx;
85 assert(false && "Expected section not found in index");
86 return 0;
George Rimar09746882019-05-07 12:10:51 +000087 }
88 unsigned size() const { return Map.size(); }
89};
Sean Silvaa6423eb2013-06-15 00:25:26 +000090
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000091/// "Single point of truth" for the ELF file construction.
Sean Silva08a75ae2013-06-20 19:11:44 +000092/// TODO: This class still has a ways to go before it is truly a "single
93/// point of truth".
Alex Brachetc22d9662019-08-07 02:44:49 +000094template <class ELFT> class ELFState {
Rui Ueyama478d6352018-01-12 02:28:31 +000095 typedef typename ELFT::Ehdr Elf_Ehdr;
96 typedef typename ELFT::Phdr Elf_Phdr;
97 typedef typename ELFT::Shdr Elf_Shdr;
98 typedef typename ELFT::Sym Elf_Sym;
99 typedef typename ELFT::Rel Elf_Rel;
100 typedef typename ELFT::Rela Elf_Rela;
Jake Ehrlich0f440d82018-06-28 21:07:34 +0000101 typedef typename ELFT::Relr Elf_Relr;
Paul Semel1dbbfba2018-07-23 18:49:04 +0000102 typedef typename ELFT::Dyn Elf_Dyn;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000103
Dave Lee67b49662017-11-16 18:10:15 +0000104 enum class SymtabType { Static, Dynamic };
105
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000106 /// The future ".strtab" section.
Rafael Espindola21956e42015-10-23 21:48:05 +0000107 StringTableBuilder DotStrtab{StringTableBuilder::ELF};
Sean Silva08a75ae2013-06-20 19:11:44 +0000108
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000109 /// The future ".shstrtab" section.
Rafael Espindola21956e42015-10-23 21:48:05 +0000110 StringTableBuilder DotShStrtab{StringTableBuilder::ELF};
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000111
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000112 /// The future ".dynstr" section.
Dave Lee67b49662017-11-16 18:10:15 +0000113 StringTableBuilder DotDynstr{StringTableBuilder::ELF};
114
Simon Atanasyan35babf92014-04-06 09:02:55 +0000115 NameToIdxMap SN2I;
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000116 NameToIdxMap SymN2I;
George Rimar91208442019-08-22 12:39:56 +0000117 NameToIdxMap DynSymN2I;
George Rimar13a364e2019-07-22 12:01:52 +0000118 ELFYAML::Object &Doc;
Sean Silvac1c290b2013-06-20 20:59:34 +0000119
George Rimar3212ecf2019-09-09 09:43:03 +0000120 bool HasError = false;
George Rimar85011022019-09-13 16:00:16 +0000121 yaml::ErrorHandler ErrHandler;
122 void reportError(const Twine &Msg);
George Rimar3212ecf2019-09-09 09:43:03 +0000123
124 std::vector<Elf_Sym> toELFSymbols(ArrayRef<ELFYAML::Symbol> Symbols,
125 const StringTableBuilder &Strtab);
126 unsigned toSectionIndex(StringRef S, StringRef LocSec, StringRef LocSym = "");
127 unsigned toSymbolIndex(StringRef S, StringRef LocSec, bool IsDynamic);
George Rimar3212ecf2019-09-09 09:43:03 +0000128
129 void buildSectionIndex();
130 void buildSymbolIndexes();
Petr Hosekeb04da32017-07-19 20:38:46 +0000131 void initProgramHeaders(std::vector<Elf_Phdr> &PHeaders);
George Rimar33b1a0e2019-09-05 08:59:28 +0000132 bool initImplicitHeader(ContiguousBlobAccumulator &CBA, Elf_Shdr &Header,
133 StringRef SecName, ELFYAML::Section *YAMLSec);
George Rimar3212ecf2019-09-09 09:43:03 +0000134 void initSectionHeaders(std::vector<Elf_Shdr> &SHeaders,
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000135 ContiguousBlobAccumulator &CBA);
Dave Lee67b49662017-11-16 18:10:15 +0000136 void initSymtabSectionHeader(Elf_Shdr &SHeader, SymtabType STType,
George Rimar66296dc2019-06-05 13:16:53 +0000137 ContiguousBlobAccumulator &CBA,
138 ELFYAML::Section *YAMLSec);
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000139 void initStrtabSectionHeader(Elf_Shdr &SHeader, StringRef Name,
140 StringTableBuilder &STB,
George Rimar66296dc2019-06-05 13:16:53 +0000141 ContiguousBlobAccumulator &CBA,
142 ELFYAML::Section *YAMLSec);
Petr Hosekeb04da32017-07-19 20:38:46 +0000143 void setProgramHeaderLayout(std::vector<Elf_Phdr> &PHeaders,
144 std::vector<Elf_Shdr> &SHeaders);
George Rimar33b1a0e2019-09-05 08:59:28 +0000145 void finalizeStrings();
Fangrui Songc3bc6972019-09-05 14:25:57 +0000146 void writeELFHeader(ContiguousBlobAccumulator &CBA, raw_ostream &OS);
George Rimar3212ecf2019-09-09 09:43:03 +0000147 void writeSectionContent(Elf_Shdr &SHeader,
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000148 const ELFYAML::RawContentSection &Section,
149 ContiguousBlobAccumulator &CBA);
George Rimar3212ecf2019-09-09 09:43:03 +0000150 void writeSectionContent(Elf_Shdr &SHeader,
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000151 const ELFYAML::RelocationSection &Section,
152 ContiguousBlobAccumulator &CBA);
George Rimar3212ecf2019-09-09 09:43:03 +0000153 void writeSectionContent(Elf_Shdr &SHeader, const ELFYAML::Group &Group,
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000154 ContiguousBlobAccumulator &CBA);
George Rimar3212ecf2019-09-09 09:43:03 +0000155 void writeSectionContent(Elf_Shdr &SHeader,
George Rimard3963052019-08-08 09:49:05 +0000156 const ELFYAML::SymtabShndxSection &Shndx,
157 ContiguousBlobAccumulator &CBA);
George Rimar3212ecf2019-09-09 09:43:03 +0000158 void writeSectionContent(Elf_Shdr &SHeader,
George Rimar646af082019-02-19 15:29:07 +0000159 const ELFYAML::SymverSection &Section,
160 ContiguousBlobAccumulator &CBA);
George Rimar3212ecf2019-09-09 09:43:03 +0000161 void writeSectionContent(Elf_Shdr &SHeader,
George Rimar0621b792019-02-19 14:53:48 +0000162 const ELFYAML::VerneedSection &Section,
163 ContiguousBlobAccumulator &CBA);
George Rimar3212ecf2019-09-09 09:43:03 +0000164 void writeSectionContent(Elf_Shdr &SHeader,
George Rimar623ae722019-02-21 12:21:43 +0000165 const ELFYAML::VerdefSection &Section,
166 ContiguousBlobAccumulator &CBA);
George Rimar3212ecf2019-09-09 09:43:03 +0000167 void writeSectionContent(Elf_Shdr &SHeader,
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000168 const ELFYAML::MipsABIFlags &Section,
169 ContiguousBlobAccumulator &CBA);
George Rimar3212ecf2019-09-09 09:43:03 +0000170 void writeSectionContent(Elf_Shdr &SHeader,
George Rimar0e7ed912019-02-09 11:34:28 +0000171 const ELFYAML::DynamicSection &Section,
172 ContiguousBlobAccumulator &CBA);
George Rimar1a219aa2019-09-24 14:22:37 +0000173 void writeSectionContent(Elf_Shdr &SHeader,
174 const ELFYAML::StackSizesSection &Section,
175 ContiguousBlobAccumulator &CBA);
George Rimare5163eb2019-10-01 09:45:59 +0000176 void writeSectionContent(Elf_Shdr &SHeader,
177 const ELFYAML::HashSection &Section,
178 ContiguousBlobAccumulator &CBA);
George Rimarfc9104d2019-10-03 14:52:33 +0000179 void writeSectionContent(Elf_Shdr &SHeader,
180 const ELFYAML::AddrsigSection &Section,
181 ContiguousBlobAccumulator &CBA);
georgerimde3cef12019-10-25 13:03:19 +0300182 void writeSectionContent(Elf_Shdr &SHeader,
183 const ELFYAML::NoteSection &Section,
184 ContiguousBlobAccumulator &CBA);
georgerima7aee6c2019-10-24 15:38:53 +0300185 void writeSectionContent(Elf_Shdr &SHeader,
186 const ELFYAML::GnuHashSection &Section,
187 ContiguousBlobAccumulator &CBA);
George Rimarfc9104d2019-10-03 14:52:33 +0000188
George Rimar85011022019-09-13 16:00:16 +0000189 ELFState(ELFYAML::Object &D, yaml::ErrorHandler EH);
190
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000191public:
George Rimar85011022019-09-13 16:00:16 +0000192 static bool writeELF(raw_ostream &OS, ELFYAML::Object &Doc,
193 yaml::ErrorHandler EH);
Sean Silva08a75ae2013-06-20 19:11:44 +0000194};
195} // end anonymous namespace
196
Alex Brachetc22d9662019-08-07 02:44:49 +0000197template <class T> static size_t arrayDataSize(ArrayRef<T> A) {
198 return A.size() * sizeof(T);
199}
200
201template <class T> static void writeArrayData(raw_ostream &OS, ArrayRef<T> A) {
202 OS.write((const char *)A.data(), arrayDataSize(A));
203}
204
205template <class T> static void zero(T &Obj) { memset(&Obj, 0, sizeof(Obj)); }
206
George Rimar85011022019-09-13 16:00:16 +0000207template <class ELFT>
208ELFState<ELFT>::ELFState(ELFYAML::Object &D, yaml::ErrorHandler EH)
209 : Doc(D), ErrHandler(EH) {
George Rimar13a364e2019-07-22 12:01:52 +0000210 StringSet<> DocSections;
Georgii Rymar3fe7f1d2019-10-28 13:47:44 +0300211 for (std::unique_ptr<ELFYAML::Section> &D : Doc.Sections)
George Rimar13a364e2019-07-22 12:01:52 +0000212 if (!D->Name.empty())
213 DocSections.insert(D->Name);
214
George Rimar1957d682019-07-23 11:03:37 +0000215 // Insert SHT_NULL section implicitly when it is not defined in YAML.
216 if (Doc.Sections.empty() || Doc.Sections.front()->Type != ELF::SHT_NULL)
217 Doc.Sections.insert(
218 Doc.Sections.begin(),
Jonas Devlieghere0eaee542019-08-15 15:54:37 +0000219 std::make_unique<ELFYAML::Section>(
Alex Brachetc22d9662019-08-07 02:44:49 +0000220 ELFYAML::Section::SectionKind::RawContent, /*IsImplicit=*/true));
George Rimarab658f42019-07-23 07:38:44 +0000221
George Rimar27799872019-10-20 14:47:17 +0000222 std::vector<StringRef> ImplicitSections;
223 if (Doc.Symbols)
224 ImplicitSections.push_back(".symtab");
225 ImplicitSections.insert(ImplicitSections.end(), {".strtab", ".shstrtab"});
226
George Rimar13a364e2019-07-22 12:01:52 +0000227 if (!Doc.DynamicSymbols.empty())
228 ImplicitSections.insert(ImplicitSections.end(), {".dynsym", ".dynstr"});
229
230 // Insert placeholders for implicit sections that are not
231 // defined explicitly in YAML.
232 for (StringRef SecName : ImplicitSections) {
233 if (DocSections.count(SecName))
234 continue;
235
Jonas Devlieghere0eaee542019-08-15 15:54:37 +0000236 std::unique_ptr<ELFYAML::Section> Sec = std::make_unique<ELFYAML::Section>(
George Rimar13a364e2019-07-22 12:01:52 +0000237 ELFYAML::Section::SectionKind::RawContent, true /*IsImplicit*/);
238 Sec->Name = SecName;
239 Doc.Sections.push_back(std::move(Sec));
240 }
241}
242
Fangrui Songc3bc6972019-09-05 14:25:57 +0000243template <class ELFT>
244void ELFState<ELFT>::writeELFHeader(ContiguousBlobAccumulator &CBA, raw_ostream &OS) {
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000245 using namespace llvm::ELF;
Fangrui Songc3bc6972019-09-05 14:25:57 +0000246
247 Elf_Ehdr Header;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000248 zero(Header);
249 Header.e_ident[EI_MAG0] = 0x7f;
250 Header.e_ident[EI_MAG1] = 'E';
251 Header.e_ident[EI_MAG2] = 'L';
252 Header.e_ident[EI_MAG3] = 'F';
253 Header.e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;
George Rimara5a0a0f2019-03-07 12:09:19 +0000254 Header.e_ident[EI_DATA] = Doc.Header.Data;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000255 Header.e_ident[EI_VERSION] = EV_CURRENT;
256 Header.e_ident[EI_OSABI] = Doc.Header.OSABI;
George Rimar6367d7a2018-12-20 10:43:49 +0000257 Header.e_ident[EI_ABIVERSION] = Doc.Header.ABIVersion;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000258 Header.e_type = Doc.Header.Type;
259 Header.e_machine = Doc.Header.Machine;
260 Header.e_version = EV_CURRENT;
261 Header.e_entry = Doc.Header.Entry;
Alex Brachet0b69c592019-09-06 02:27:55 +0000262 Header.e_phoff = Doc.ProgramHeaders.size() ? sizeof(Header) : 0;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000263 Header.e_flags = Doc.Header.Flags;
264 Header.e_ehsize = sizeof(Elf_Ehdr);
Alex Brachet0b69c592019-09-06 02:27:55 +0000265 Header.e_phentsize = Doc.ProgramHeaders.size() ? sizeof(Elf_Phdr) : 0;
Petr Hosekeb04da32017-07-19 20:38:46 +0000266 Header.e_phnum = Doc.ProgramHeaders.size();
George Rimar687d47c2019-06-27 11:08:42 +0000267
268 Header.e_shentsize =
269 Doc.Header.SHEntSize ? (uint16_t)*Doc.Header.SHEntSize : sizeof(Elf_Shdr);
Petr Hosekeb04da32017-07-19 20:38:46 +0000270 // Immediately following the ELF header and program headers.
Fangrui Songc3bc6972019-09-05 14:25:57 +0000271 // Align the start of the section header and write the ELF header.
Fangrui Songd20c41d2019-09-06 09:23:17 +0000272 uint64_t SHOff;
273 CBA.getOSAndAlignedOffset(SHOff, sizeof(typename ELFT::uint));
274 Header.e_shoff =
275 Doc.Header.SHOff ? typename ELFT::uint(*Doc.Header.SHOff) : SHOff;
George Rimar687d47c2019-06-27 11:08:42 +0000276 Header.e_shnum =
George Rimar14802292019-07-25 10:19:23 +0000277 Doc.Header.SHNum ? (uint16_t)*Doc.Header.SHNum : Doc.Sections.size();
George Rimar687d47c2019-06-27 11:08:42 +0000278 Header.e_shstrndx = Doc.Header.SHStrNdx ? (uint16_t)*Doc.Header.SHStrNdx
279 : SN2I.get(".shstrtab");
Fangrui Songc3bc6972019-09-05 14:25:57 +0000280
281 OS.write((const char *)&Header, sizeof(Header));
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000282}
283
284template <class ELFT>
Petr Hosekeb04da32017-07-19 20:38:46 +0000285void ELFState<ELFT>::initProgramHeaders(std::vector<Elf_Phdr> &PHeaders) {
286 for (const auto &YamlPhdr : Doc.ProgramHeaders) {
287 Elf_Phdr Phdr;
288 Phdr.p_type = YamlPhdr.Type;
289 Phdr.p_flags = YamlPhdr.Flags;
290 Phdr.p_vaddr = YamlPhdr.VAddr;
291 Phdr.p_paddr = YamlPhdr.PAddr;
292 PHeaders.push_back(Phdr);
293 }
294}
George Rimar09746882019-05-07 12:10:51 +0000295
George Rimar3212ecf2019-09-09 09:43:03 +0000296template <class ELFT>
297unsigned ELFState<ELFT>::toSectionIndex(StringRef S, StringRef LocSec,
298 StringRef LocSym) {
299 unsigned Index;
300 if (SN2I.lookup(S, Index) || to_integer(S, Index))
301 return Index;
302
303 assert(LocSec.empty() || LocSym.empty());
304 if (!LocSym.empty())
305 reportError("unknown section referenced: '" + S + "' by YAML symbol '" +
306 LocSym + "'");
307 else
308 reportError("unknown section referenced: '" + S + "' by YAML section '" +
309 LocSec + "'");
310 return 0;
311}
312
313template <class ELFT>
314unsigned ELFState<ELFT>::toSymbolIndex(StringRef S, StringRef LocSec,
315 bool IsDynamic) {
316 const NameToIdxMap &SymMap = IsDynamic ? DynSymN2I : SymN2I;
317 unsigned Index;
318 // Here we try to look up S in the symbol table. If it is not there,
319 // treat its value as a symbol index.
320 if (!SymMap.lookup(S, Index) && !to_integer(S, Index)) {
321 reportError("unknown symbol referenced: '" + S + "' by YAML section '" +
322 LocSec + "'");
323 return 0;
Xing GUO98228352018-12-04 14:27:51 +0000324 }
George Rimar3212ecf2019-09-09 09:43:03 +0000325 return Index;
Xing GUO98228352018-12-04 14:27:51 +0000326}
327
Petr Hosekeb04da32017-07-19 20:38:46 +0000328template <class ELFT>
George Rimar33b1a0e2019-09-05 08:59:28 +0000329bool ELFState<ELFT>::initImplicitHeader(ContiguousBlobAccumulator &CBA,
George Rimar66296dc2019-06-05 13:16:53 +0000330 Elf_Shdr &Header, StringRef SecName,
331 ELFYAML::Section *YAMLSec) {
332 // Check if the header was already initialized.
333 if (Header.sh_offset)
334 return false;
335
336 if (SecName == ".symtab")
George Rimar33b1a0e2019-09-05 08:59:28 +0000337 initSymtabSectionHeader(Header, SymtabType::Static, CBA, YAMLSec);
George Rimar66296dc2019-06-05 13:16:53 +0000338 else if (SecName == ".strtab")
George Rimar33b1a0e2019-09-05 08:59:28 +0000339 initStrtabSectionHeader(Header, SecName, DotStrtab, CBA, YAMLSec);
George Rimar66296dc2019-06-05 13:16:53 +0000340 else if (SecName == ".shstrtab")
George Rimar33b1a0e2019-09-05 08:59:28 +0000341 initStrtabSectionHeader(Header, SecName, DotShStrtab, CBA, YAMLSec);
George Rimar66296dc2019-06-05 13:16:53 +0000342 else if (SecName == ".dynsym")
George Rimar33b1a0e2019-09-05 08:59:28 +0000343 initSymtabSectionHeader(Header, SymtabType::Dynamic, CBA, YAMLSec);
George Rimar66296dc2019-06-05 13:16:53 +0000344 else if (SecName == ".dynstr")
George Rimar33b1a0e2019-09-05 08:59:28 +0000345 initStrtabSectionHeader(Header, SecName, DotDynstr, CBA, YAMLSec);
George Rimar66296dc2019-06-05 13:16:53 +0000346 else
347 return false;
George Rimar9df825f2019-07-02 10:20:12 +0000348
George Rimar86cc7362019-09-02 09:47:17 +0000349 // Override the fields if requested.
George Rimareb41f7f2019-07-11 12:59:29 +0000350 if (YAMLSec) {
George Rimar86cc7362019-09-02 09:47:17 +0000351 if (YAMLSec->ShName)
352 Header.sh_name = *YAMLSec->ShName;
George Rimareb41f7f2019-07-11 12:59:29 +0000353 if (YAMLSec->ShOffset)
354 Header.sh_offset = *YAMLSec->ShOffset;
355 if (YAMLSec->ShSize)
356 Header.sh_size = *YAMLSec->ShSize;
357 }
George Rimar9df825f2019-07-02 10:20:12 +0000358
George Rimar66296dc2019-06-05 13:16:53 +0000359 return true;
360}
361
George Rimarcfc2bcc2019-09-25 12:09:30 +0000362StringRef llvm::ELFYAML::dropUniqueSuffix(StringRef S) {
George Rimar60dc5d42019-06-25 08:22:57 +0000363 size_t SuffixPos = S.rfind(" [");
364 if (SuffixPos == StringRef::npos)
365 return S;
366 return S.substr(0, SuffixPos);
367}
368
George Rimar66296dc2019-06-05 13:16:53 +0000369template <class ELFT>
George Rimar3212ecf2019-09-09 09:43:03 +0000370void ELFState<ELFT>::initSectionHeaders(std::vector<Elf_Shdr> &SHeaders,
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000371 ContiguousBlobAccumulator &CBA) {
372 // Ensure SHN_UNDEF entry is present. An all-zero section header is a
373 // valid SHN_UNDEF entry since SHT_NULL == 0.
George Rimarab658f42019-07-23 07:38:44 +0000374 SHeaders.resize(Doc.Sections.size());
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000375
George Rimar1957d682019-07-23 11:03:37 +0000376 for (size_t I = 0; I < Doc.Sections.size(); ++I) {
George Rimarab658f42019-07-23 07:38:44 +0000377 ELFYAML::Section *Sec = Doc.Sections[I].get();
George Rimar14802292019-07-25 10:19:23 +0000378 if (I == 0 && Sec->IsImplicit)
George Rimar1957d682019-07-23 11:03:37 +0000379 continue;
George Rimar1957d682019-07-23 11:03:37 +0000380
George Rimareb394e92019-06-07 08:31:36 +0000381 // We have a few sections like string or symbol tables that are usually
382 // added implicitly to the end. However, if they are explicitly specified
383 // in the YAML, we need to write them here. This ensures the file offset
384 // remains correct.
George Rimar14802292019-07-25 10:19:23 +0000385 Elf_Shdr &SHeader = SHeaders[I];
George Rimar33b1a0e2019-09-05 08:59:28 +0000386 if (initImplicitHeader(CBA, SHeader, Sec->Name,
George Rimar13a364e2019-07-22 12:01:52 +0000387 Sec->IsImplicit ? nullptr : Sec))
George Rimareb394e92019-06-07 08:31:36 +0000388 continue;
389
390 assert(Sec && "It can't be null unless it is an implicit section. But all "
391 "implicit sections should already have been handled above.");
392
George Rimarcfc2bcc2019-09-25 12:09:30 +0000393 SHeader.sh_name =
394 DotShStrtab.getOffset(ELFYAML::dropUniqueSuffix(Sec->Name));
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000395 SHeader.sh_type = Sec->Type;
George Rimarcfa1a622019-06-14 11:01:14 +0000396 if (Sec->Flags)
397 SHeader.sh_flags = *Sec->Flags;
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000398 SHeader.sh_addr = Sec->Address;
399 SHeader.sh_addralign = Sec->AddressAlign;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000400
George Rimar3212ecf2019-09-09 09:43:03 +0000401 if (!Sec->Link.empty())
402 SHeader.sh_link = toSectionIndex(Sec->Link, Sec->Name);
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000403
George Rimar14802292019-07-25 10:19:23 +0000404 if (I == 0) {
405 if (auto RawSec = dyn_cast<ELFYAML::RawContentSection>(Sec)) {
406 // We do not write any content for special SHN_UNDEF section.
407 if (RawSec->Size)
408 SHeader.sh_size = *RawSec->Size;
409 if (RawSec->Info)
410 SHeader.sh_info = *RawSec->Info;
411 }
412 if (Sec->EntSize)
413 SHeader.sh_entsize = *Sec->EntSize;
414 } else if (auto S = dyn_cast<ELFYAML::RawContentSection>(Sec)) {
George Rimar3212ecf2019-09-09 09:43:03 +0000415 writeSectionContent(SHeader, *S, CBA);
George Rimard3963052019-08-08 09:49:05 +0000416 } else if (auto S = dyn_cast<ELFYAML::SymtabShndxSection>(Sec)) {
George Rimar3212ecf2019-09-09 09:43:03 +0000417 writeSectionContent(SHeader, *S, CBA);
George Rimareb394e92019-06-07 08:31:36 +0000418 } else if (auto S = dyn_cast<ELFYAML::RelocationSection>(Sec)) {
George Rimar3212ecf2019-09-09 09:43:03 +0000419 writeSectionContent(SHeader, *S, CBA);
George Rimareb394e92019-06-07 08:31:36 +0000420 } else if (auto S = dyn_cast<ELFYAML::Group>(Sec)) {
George Rimar3212ecf2019-09-09 09:43:03 +0000421 writeSectionContent(SHeader, *S, CBA);
George Rimareb394e92019-06-07 08:31:36 +0000422 } else if (auto S = dyn_cast<ELFYAML::MipsABIFlags>(Sec)) {
George Rimar3212ecf2019-09-09 09:43:03 +0000423 writeSectionContent(SHeader, *S, CBA);
George Rimareb394e92019-06-07 08:31:36 +0000424 } else if (auto S = dyn_cast<ELFYAML::NoBitsSection>(Sec)) {
Simon Atanasyan5db02762015-07-03 23:00:54 +0000425 SHeader.sh_entsize = 0;
426 SHeader.sh_size = S->Size;
427 // SHT_NOBITS section does not have content
428 // so just to setup the section offset.
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000429 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
George Rimareb394e92019-06-07 08:31:36 +0000430 } else if (auto S = dyn_cast<ELFYAML::DynamicSection>(Sec)) {
George Rimar3212ecf2019-09-09 09:43:03 +0000431 writeSectionContent(SHeader, *S, CBA);
George Rimareb394e92019-06-07 08:31:36 +0000432 } else if (auto S = dyn_cast<ELFYAML::SymverSection>(Sec)) {
George Rimar3212ecf2019-09-09 09:43:03 +0000433 writeSectionContent(SHeader, *S, CBA);
George Rimareb394e92019-06-07 08:31:36 +0000434 } else if (auto S = dyn_cast<ELFYAML::VerneedSection>(Sec)) {
George Rimar3212ecf2019-09-09 09:43:03 +0000435 writeSectionContent(SHeader, *S, CBA);
George Rimareb394e92019-06-07 08:31:36 +0000436 } else if (auto S = dyn_cast<ELFYAML::VerdefSection>(Sec)) {
George Rimar3212ecf2019-09-09 09:43:03 +0000437 writeSectionContent(SHeader, *S, CBA);
George Rimar1a219aa2019-09-24 14:22:37 +0000438 } else if (auto S = dyn_cast<ELFYAML::StackSizesSection>(Sec)) {
George Rimare5163eb2019-10-01 09:45:59 +0000439 writeSectionContent(SHeader, *S, CBA);
440 } else if (auto S = dyn_cast<ELFYAML::HashSection>(Sec)) {
441 writeSectionContent(SHeader, *S, CBA);
George Rimarfc9104d2019-10-03 14:52:33 +0000442 } else if (auto S = dyn_cast<ELFYAML::AddrsigSection>(Sec)) {
443 writeSectionContent(SHeader, *S, CBA);
georgerimde3cef12019-10-25 13:03:19 +0300444 } else if (auto S = dyn_cast<ELFYAML::NoteSection>(Sec)) {
445 writeSectionContent(SHeader, *S, CBA);
georgerima7aee6c2019-10-24 15:38:53 +0300446 } else if (auto S = dyn_cast<ELFYAML::GnuHashSection>(Sec)) {
447 writeSectionContent(SHeader, *S, CBA);
George Rimar3212ecf2019-09-09 09:43:03 +0000448 } else {
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000449 llvm_unreachable("Unknown section type");
George Rimar3212ecf2019-09-09 09:43:03 +0000450 }
George Rimar9df825f2019-07-02 10:20:12 +0000451
George Rimar86cc7362019-09-02 09:47:17 +0000452 // Override the fields if requested.
George Rimareb41f7f2019-07-11 12:59:29 +0000453 if (Sec) {
George Rimar86cc7362019-09-02 09:47:17 +0000454 if (Sec->ShName)
455 SHeader.sh_name = *Sec->ShName;
George Rimareb41f7f2019-07-11 12:59:29 +0000456 if (Sec->ShOffset)
457 SHeader.sh_offset = *Sec->ShOffset;
458 if (Sec->ShSize)
459 SHeader.sh_size = *Sec->ShSize;
460 }
George Rimar66296dc2019-06-05 13:16:53 +0000461 }
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000462}
463
George Rimar6da44ad2019-04-03 14:53:42 +0000464static size_t findFirstNonGlobal(ArrayRef<ELFYAML::Symbol> Symbols) {
465 for (size_t I = 0; I < Symbols.size(); ++I)
466 if (Symbols[I].Binding.value != ELF::STB_LOCAL)
467 return I;
468 return Symbols.size();
469}
470
George Rimarf3024362019-09-25 11:40:11 +0000471static uint64_t writeContent(raw_ostream &OS,
472 const Optional<yaml::BinaryRef> &Content,
473 const Optional<llvm::yaml::Hex64> &Size) {
George Rimar1e410072019-06-10 12:43:18 +0000474 size_t ContentSize = 0;
George Rimarf3024362019-09-25 11:40:11 +0000475 if (Content) {
476 Content->writeAsBinary(OS);
477 ContentSize = Content->binary_size();
George Rimar1e410072019-06-10 12:43:18 +0000478 }
479
George Rimarf3024362019-09-25 11:40:11 +0000480 if (!Size)
George Rimar1e410072019-06-10 12:43:18 +0000481 return ContentSize;
482
George Rimarf3024362019-09-25 11:40:11 +0000483 OS.write_zeros(*Size - ContentSize);
484 return *Size;
George Rimar1e410072019-06-10 12:43:18 +0000485}
486
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000487template <class ELFT>
George Rimar3212ecf2019-09-09 09:43:03 +0000488std::vector<typename ELFT::Sym>
489ELFState<ELFT>::toELFSymbols(ArrayRef<ELFYAML::Symbol> Symbols,
490 const StringTableBuilder &Strtab) {
George Rimar30ea0c42019-06-20 14:44:48 +0000491 std::vector<Elf_Sym> Ret;
492 Ret.resize(Symbols.size() + 1);
493
494 size_t I = 0;
Georgii Rymar073ab702019-10-26 15:08:49 +0300495 for (const ELFYAML::Symbol &Sym : Symbols) {
George Rimar30ea0c42019-06-20 14:44:48 +0000496 Elf_Sym &Symbol = Ret[++I];
497
498 // If NameIndex, which contains the name offset, is explicitly specified, we
499 // use it. This is useful for preparing broken objects. Otherwise, we add
500 // the specified Name to the string table builder to get its offset.
501 if (Sym.NameIndex)
502 Symbol.st_name = *Sym.NameIndex;
503 else if (!Sym.Name.empty())
George Rimarcfc2bcc2019-09-25 12:09:30 +0000504 Symbol.st_name = Strtab.getOffset(ELFYAML::dropUniqueSuffix(Sym.Name));
George Rimar30ea0c42019-06-20 14:44:48 +0000505
506 Symbol.setBindingAndType(Sym.Binding, Sym.Type);
George Rimar3212ecf2019-09-09 09:43:03 +0000507 if (!Sym.Section.empty())
508 Symbol.st_shndx = toSectionIndex(Sym.Section, "", Sym.Name);
509 else if (Sym.Index)
George Rimar30ea0c42019-06-20 14:44:48 +0000510 Symbol.st_shndx = *Sym.Index;
George Rimar3212ecf2019-09-09 09:43:03 +0000511
George Rimar30ea0c42019-06-20 14:44:48 +0000512 Symbol.st_value = Sym.Value;
George Rimar4e717022019-08-30 13:39:22 +0000513 Symbol.st_other = Sym.Other ? *Sym.Other : 0;
George Rimar30ea0c42019-06-20 14:44:48 +0000514 Symbol.st_size = Sym.Size;
515 }
516
517 return Ret;
518}
519
520template <class ELFT>
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000521void ELFState<ELFT>::initSymtabSectionHeader(Elf_Shdr &SHeader,
Dave Lee67b49662017-11-16 18:10:15 +0000522 SymtabType STType,
George Rimar66296dc2019-06-05 13:16:53 +0000523 ContiguousBlobAccumulator &CBA,
524 ELFYAML::Section *YAMLSec) {
George Rimar1e410072019-06-10 12:43:18 +0000525
Dave Lee67b49662017-11-16 18:10:15 +0000526 bool IsStatic = STType == SymtabType::Static;
George Rimar27799872019-10-20 14:47:17 +0000527 ArrayRef<ELFYAML::Symbol> Symbols;
528 if (IsStatic && Doc.Symbols)
529 Symbols = *Doc.Symbols;
530 else if (!IsStatic)
531 Symbols = Doc.DynamicSymbols;
George Rimar1e410072019-06-10 12:43:18 +0000532
533 ELFYAML::RawContentSection *RawSec =
534 dyn_cast_or_null<ELFYAML::RawContentSection>(YAMLSec);
535 if (RawSec && !Symbols.empty() && (RawSec->Content || RawSec->Size)) {
536 if (RawSec->Content)
George Rimar3212ecf2019-09-09 09:43:03 +0000537 reportError("cannot specify both `Content` and " +
538 (IsStatic ? Twine("`Symbols`") : Twine("`DynamicSymbols`")) +
539 " for symbol table section '" + RawSec->Name + "'");
George Rimar1e410072019-06-10 12:43:18 +0000540 if (RawSec->Size)
George Rimar3212ecf2019-09-09 09:43:03 +0000541 reportError("cannot specify both `Size` and " +
542 (IsStatic ? Twine("`Symbols`") : Twine("`DynamicSymbols`")) +
543 " for symbol table section '" + RawSec->Name + "'");
544 return;
George Rimar1e410072019-06-10 12:43:18 +0000545 }
546
547 zero(SHeader);
Dave Lee67b49662017-11-16 18:10:15 +0000548 SHeader.sh_name = DotShStrtab.getOffset(IsStatic ? ".symtab" : ".dynsym");
George Rimar0aecaba2019-06-14 14:25:34 +0000549
550 if (YAMLSec)
551 SHeader.sh_type = YAMLSec->Type;
552 else
553 SHeader.sh_type = IsStatic ? ELF::SHT_SYMTAB : ELF::SHT_DYNSYM;
George Rimar379aa182019-06-10 11:38:06 +0000554
George Rimarffb3c722019-06-11 10:00:51 +0000555 if (RawSec && !RawSec->Link.empty()) {
556 // If the Link field is explicitly defined in the document,
557 // we should use it.
George Rimar3212ecf2019-09-09 09:43:03 +0000558 SHeader.sh_link = toSectionIndex(RawSec->Link, RawSec->Name);
George Rimarffb3c722019-06-11 10:00:51 +0000559 } else {
560 // When we describe the .dynsym section in the document explicitly, it is
561 // allowed to omit the "DynamicSymbols" tag. In this case .dynstr is not
562 // added implicitly and we should be able to leave the Link zeroed if
563 // .dynstr is not defined.
564 unsigned Link = 0;
565 if (IsStatic)
566 Link = SN2I.get(".strtab");
567 else
568 SN2I.lookup(".dynstr", Link);
569 SHeader.sh_link = Link;
570 }
George Rimar379aa182019-06-10 11:38:06 +0000571
George Rimarcfa1a622019-06-14 11:01:14 +0000572 if (YAMLSec && YAMLSec->Flags)
573 SHeader.sh_flags = *YAMLSec->Flags;
574 else if (!IsStatic)
575 SHeader.sh_flags = ELF::SHF_ALLOC;
George Rimarc1da1492019-04-26 12:45:54 +0000576
George Rimara7ba1a02019-03-01 10:18:16 +0000577 // If the symbol table section is explicitly described in the YAML
578 // then we should set the fields requested.
George Rimarb6e20932019-06-19 08:57:38 +0000579 SHeader.sh_info = (RawSec && RawSec->Info) ? (unsigned)(*RawSec->Info)
580 : findFirstNonGlobal(Symbols) + 1;
George Rimar66296dc2019-06-05 13:16:53 +0000581 SHeader.sh_entsize = (YAMLSec && YAMLSec->EntSize)
582 ? (uint64_t)(*YAMLSec->EntSize)
583 : sizeof(Elf_Sym);
584 SHeader.sh_addralign = YAMLSec ? (uint64_t)YAMLSec->AddressAlign : 8;
585 SHeader.sh_addr = YAMLSec ? (uint64_t)YAMLSec->Address : 0;
586
George Rimar1e410072019-06-10 12:43:18 +0000587 auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
588 if (RawSec && (RawSec->Content || RawSec->Size)) {
589 assert(Symbols.empty());
George Rimarf3024362019-09-25 11:40:11 +0000590 SHeader.sh_size = writeContent(OS, RawSec->Content, RawSec->Size);
George Rimar1e410072019-06-10 12:43:18 +0000591 return;
George Rimar6947acd2019-02-19 12:15:04 +0000592 }
George Rimar1e410072019-06-10 12:43:18 +0000593
George Rimar30ea0c42019-06-20 14:44:48 +0000594 std::vector<Elf_Sym> Syms =
George Rimar3212ecf2019-09-09 09:43:03 +0000595 toELFSymbols(Symbols, IsStatic ? DotStrtab : DotDynstr);
George Rimar1e410072019-06-10 12:43:18 +0000596 writeArrayData(OS, makeArrayRef(Syms));
597 SHeader.sh_size = arrayDataSize(makeArrayRef(Syms));
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000598}
599
600template <class ELFT>
601void ELFState<ELFT>::initStrtabSectionHeader(Elf_Shdr &SHeader, StringRef Name,
602 StringTableBuilder &STB,
George Rimar66296dc2019-06-05 13:16:53 +0000603 ContiguousBlobAccumulator &CBA,
604 ELFYAML::Section *YAMLSec) {
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000605 zero(SHeader);
Hans Wennborg59f0cba2014-04-30 19:38:09 +0000606 SHeader.sh_name = DotShStrtab.getOffset(Name);
George Rimar0aecaba2019-06-14 14:25:34 +0000607 SHeader.sh_type = YAMLSec ? YAMLSec->Type : ELF::SHT_STRTAB;
George Rimar66296dc2019-06-05 13:16:53 +0000608 SHeader.sh_addralign = YAMLSec ? (uint64_t)YAMLSec->AddressAlign : 1;
609
610 ELFYAML::RawContentSection *RawSec =
611 dyn_cast_or_null<ELFYAML::RawContentSection>(YAMLSec);
George Rimar1e410072019-06-10 12:43:18 +0000612
613 auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
614 if (RawSec && (RawSec->Content || RawSec->Size)) {
George Rimarf3024362019-09-25 11:40:11 +0000615 SHeader.sh_size = writeContent(OS, RawSec->Content, RawSec->Size);
George Rimar66296dc2019-06-05 13:16:53 +0000616 } else {
George Rimar1e410072019-06-10 12:43:18 +0000617 STB.write(OS);
George Rimar66296dc2019-06-05 13:16:53 +0000618 SHeader.sh_size = STB.getSize();
619 }
620
621 if (YAMLSec && YAMLSec->EntSize)
622 SHeader.sh_entsize = *YAMLSec->EntSize;
George Rimar6947acd2019-02-19 12:15:04 +0000623
George Rimarb6e20932019-06-19 08:57:38 +0000624 if (RawSec && RawSec->Info)
625 SHeader.sh_info = *RawSec->Info;
626
George Rimarcfa1a622019-06-14 11:01:14 +0000627 if (YAMLSec && YAMLSec->Flags)
628 SHeader.sh_flags = *YAMLSec->Flags;
629 else if (Name == ".dynstr")
630 SHeader.sh_flags = ELF::SHF_ALLOC;
631
George Rimar43f62ff2019-06-14 11:13:32 +0000632 // If the section is explicitly described in the YAML
George Rimar6947acd2019-02-19 12:15:04 +0000633 // then we want to use its section address.
George Rimar43f62ff2019-06-14 11:13:32 +0000634 if (YAMLSec)
George Rimarcfa1a622019-06-14 11:01:14 +0000635 SHeader.sh_addr = YAMLSec->Address;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000636}
637
George Rimar3212ecf2019-09-09 09:43:03 +0000638template <class ELFT> void ELFState<ELFT>::reportError(const Twine &Msg) {
George Rimar85011022019-09-13 16:00:16 +0000639 ErrHandler(Msg);
George Rimar3212ecf2019-09-09 09:43:03 +0000640 HasError = true;
641}
642
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000643template <class ELFT>
Petr Hosekeb04da32017-07-19 20:38:46 +0000644void ELFState<ELFT>::setProgramHeaderLayout(std::vector<Elf_Phdr> &PHeaders,
645 std::vector<Elf_Shdr> &SHeaders) {
646 uint32_t PhdrIdx = 0;
647 for (auto &YamlPhdr : Doc.ProgramHeaders) {
George Rimarf5345a32019-05-01 09:45:55 +0000648 Elf_Phdr &PHeader = PHeaders[PhdrIdx++];
649
Puyan Lotfia10f0162019-05-11 17:03:36 +0000650 std::vector<Elf_Shdr *> Sections;
651 for (const ELFYAML::SectionName &SecName : YamlPhdr.Sections) {
652 unsigned Index;
653 if (!SN2I.lookup(SecName.Section, Index)) {
George Rimar3212ecf2019-09-09 09:43:03 +0000654 reportError("unknown section referenced: '" + SecName.Section +
655 "' by program header");
656 continue;
George Rimarf5345a32019-05-01 09:45:55 +0000657 }
658 Sections.push_back(&SHeaders[Index]);
659 }
Petr Hosekeb04da32017-07-19 20:38:46 +0000660
James Hendersonb10f48b2019-03-15 10:35:27 +0000661 if (YamlPhdr.Offset) {
662 PHeader.p_offset = *YamlPhdr.Offset;
663 } else {
664 if (YamlPhdr.Sections.size())
665 PHeader.p_offset = UINT32_MAX;
Petr Hosekeb04da32017-07-19 20:38:46 +0000666 else
James Hendersonb10f48b2019-03-15 10:35:27 +0000667 PHeader.p_offset = 0;
668
669 // Find the minimum offset for the program header.
George Rimarf5345a32019-05-01 09:45:55 +0000670 for (Elf_Shdr *SHeader : Sections)
671 PHeader.p_offset = std::min(PHeader.p_offset, SHeader->sh_offset);
Petr Hosekeb04da32017-07-19 20:38:46 +0000672 }
673
Fangrui Songc28f3e62019-09-09 16:45:17 +0000674 // Find the maximum offset of the end of a section in order to set p_filesz
675 // and p_memsz. When setting p_filesz, trailing SHT_NOBITS sections are not
676 // counted.
677 uint64_t FileOffset = PHeader.p_offset, MemOffset = PHeader.p_offset;
678 for (Elf_Shdr *SHeader : Sections) {
679 uint64_t End = SHeader->sh_offset + SHeader->sh_size;
680 MemOffset = std::max(MemOffset, End);
681
682 if (SHeader->sh_type != llvm::ELF::SHT_NOBITS)
683 FileOffset = std::max(FileOffset, End);
James Hendersonb10f48b2019-03-15 10:35:27 +0000684 }
685
Fangrui Songc28f3e62019-09-09 16:45:17 +0000686 // Set the file size and the memory size if not set explicitly.
687 PHeader.p_filesz = YamlPhdr.FileSize ? uint64_t(*YamlPhdr.FileSize)
688 : FileOffset - PHeader.p_offset;
689 PHeader.p_memsz = YamlPhdr.MemSize ? uint64_t(*YamlPhdr.MemSize)
690 : MemOffset - PHeader.p_offset;
Petr Hosekeb04da32017-07-19 20:38:46 +0000691
Jake Ehrlich03aeeb092017-11-01 23:14:48 +0000692 if (YamlPhdr.Align) {
693 PHeader.p_align = *YamlPhdr.Align;
694 } else {
Fangrui Song1da4f472019-09-10 09:16:34 +0000695 // Set the alignment of the segment to be the maximum alignment of the
696 // sections so that by default the segment has a valid and sensible
697 // alignment.
Jake Ehrlich03aeeb092017-11-01 23:14:48 +0000698 PHeader.p_align = 1;
George Rimarf5345a32019-05-01 09:45:55 +0000699 for (Elf_Shdr *SHeader : Sections)
Fangrui Song1da4f472019-09-10 09:16:34 +0000700 PHeader.p_align = std::max(PHeader.p_align, SHeader->sh_addralign);
Petr Hosekeb04da32017-07-19 20:38:46 +0000701 }
702 }
703}
704
705template <class ELFT>
George Rimar3212ecf2019-09-09 09:43:03 +0000706void ELFState<ELFT>::writeSectionContent(
George Rimarb49e1922019-04-24 13:02:15 +0000707 Elf_Shdr &SHeader, const ELFYAML::RawContentSection &Section,
708 ContiguousBlobAccumulator &CBA) {
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000709 raw_ostream &OS =
710 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
George Rimarf3024362019-09-25 11:40:11 +0000711 SHeader.sh_size = writeContent(OS, Section.Content, Section.Size);
George Rimarb49e1922019-04-24 13:02:15 +0000712
George Rimar65a68282018-08-07 08:11:38 +0000713 if (Section.EntSize)
714 SHeader.sh_entsize = *Section.EntSize;
715 else if (Section.Type == llvm::ELF::SHT_RELR)
Jake Ehrlich0f440d82018-06-28 21:07:34 +0000716 SHeader.sh_entsize = sizeof(Elf_Relr);
717 else
718 SHeader.sh_entsize = 0;
George Rimarb6e20932019-06-19 08:57:38 +0000719
720 if (Section.Info)
721 SHeader.sh_info = *Section.Info;
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000722}
723
Simon Atanasyan5d19c672015-01-25 13:29:25 +0000724static bool isMips64EL(const ELFYAML::Object &Doc) {
725 return Doc.Header.Machine == ELFYAML::ELF_EM(llvm::ELF::EM_MIPS) &&
726 Doc.Header.Class == ELFYAML::ELF_ELFCLASS(ELF::ELFCLASS64) &&
727 Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB);
728}
729
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000730template <class ELFT>
George Rimar3212ecf2019-09-09 09:43:03 +0000731void ELFState<ELFT>::writeSectionContent(
Alex Brachetc22d9662019-08-07 02:44:49 +0000732 Elf_Shdr &SHeader, const ELFYAML::RelocationSection &Section,
733 ContiguousBlobAccumulator &CBA) {
Simon Atanasyan8eb9d1b2015-05-08 07:05:04 +0000734 assert((Section.Type == llvm::ELF::SHT_REL ||
735 Section.Type == llvm::ELF::SHT_RELA) &&
736 "Section type is not SHT_REL nor SHT_RELA");
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000737
738 bool IsRela = Section.Type == llvm::ELF::SHT_RELA;
739 SHeader.sh_entsize = IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
740 SHeader.sh_size = SHeader.sh_entsize * Section.Relocations.size();
741
George Rimarda1b3ab2019-04-26 12:15:32 +0000742 // For relocation section set link to .symtab by default.
Georgii Rymar3fe7f1d2019-10-28 13:47:44 +0300743 unsigned Link = 0;
744 if (Section.Link.empty() && SN2I.lookup(".symtab", Link))
745 SHeader.sh_link = Link;
George Rimarda1b3ab2019-04-26 12:15:32 +0000746
George Rimar3212ecf2019-09-09 09:43:03 +0000747 if (!Section.RelocatableSec.empty())
748 SHeader.sh_info = toSectionIndex(Section.RelocatableSec, Section.Name);
George Rimarda1b3ab2019-04-26 12:15:32 +0000749
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000750 auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000751 for (const auto &Rel : Section.Relocations) {
George Rimar3212ecf2019-09-09 09:43:03 +0000752 unsigned SymIdx = Rel.Symbol ? toSymbolIndex(*Rel.Symbol, Section.Name,
753 Section.Link == ".dynsym")
754 : 0;
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000755 if (IsRela) {
756 Elf_Rela REntry;
757 zero(REntry);
758 REntry.r_offset = Rel.Offset;
759 REntry.r_addend = Rel.Addend;
Simon Atanasyan5d19c672015-01-25 13:29:25 +0000760 REntry.setSymbolAndType(SymIdx, Rel.Type, isMips64EL(Doc));
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000761 OS.write((const char *)&REntry, sizeof(REntry));
762 } else {
763 Elf_Rel REntry;
764 zero(REntry);
765 REntry.r_offset = Rel.Offset;
Simon Atanasyan5d19c672015-01-25 13:29:25 +0000766 REntry.setSymbolAndType(SymIdx, Rel.Type, isMips64EL(Doc));
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000767 OS.write((const char *)&REntry, sizeof(REntry));
768 }
769 }
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000770}
771
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000772template <class ELFT>
George Rimar3212ecf2019-09-09 09:43:03 +0000773void ELFState<ELFT>::writeSectionContent(
George Rimard3963052019-08-08 09:49:05 +0000774 Elf_Shdr &SHeader, const ELFYAML::SymtabShndxSection &Shndx,
775 ContiguousBlobAccumulator &CBA) {
776 raw_ostream &OS =
777 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
778
779 for (uint32_t E : Shndx.Entries)
780 support::endian::write<uint32_t>(OS, E, ELFT::TargetEndianness);
781
782 SHeader.sh_entsize = Shndx.EntSize ? (uint64_t)*Shndx.EntSize : 4;
783 SHeader.sh_size = Shndx.Entries.size() * SHeader.sh_entsize;
George Rimard3963052019-08-08 09:49:05 +0000784}
785
786template <class ELFT>
George Rimar3212ecf2019-09-09 09:43:03 +0000787void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000788 const ELFYAML::Group &Section,
789 ContiguousBlobAccumulator &CBA) {
Simon Atanasyan8eb9d1b2015-05-08 07:05:04 +0000790 assert(Section.Type == llvm::ELF::SHT_GROUP &&
791 "Section type is not SHT_GROUP");
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000792
Georgii Rymar5b118a02019-10-28 13:30:05 +0300793 unsigned Link = 0;
794 if (Section.Link.empty() && SN2I.lookup(".symtab", Link))
795 SHeader.sh_link = Link;
796
George Rimard063c7d2019-02-20 13:58:43 +0000797 SHeader.sh_entsize = 4;
George Rimar09746882019-05-07 12:10:51 +0000798 SHeader.sh_size = SHeader.sh_entsize * Section.Members.size();
Georgii Rymar5b118a02019-10-28 13:30:05 +0300799
800 if (Section.Signature)
801 SHeader.sh_info =
802 toSymbolIndex(*Section.Signature, Section.Name, /*IsDynamic=*/false);
George Rimarda1b3ab2019-04-26 12:15:32 +0000803
George Rimard063c7d2019-02-20 13:58:43 +0000804 raw_ostream &OS =
805 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000806
George Rimarfb7780a2019-04-26 12:20:51 +0000807 for (const ELFYAML::SectionOrType &Member : Section.Members) {
808 unsigned int SectionIndex = 0;
809 if (Member.sectionNameOrType == "GRP_COMDAT")
810 SectionIndex = llvm::ELF::GRP_COMDAT;
George Rimar3212ecf2019-09-09 09:43:03 +0000811 else
812 SectionIndex = toSectionIndex(Member.sectionNameOrType, Section.Name);
George Rimarfb7780a2019-04-26 12:20:51 +0000813 support::endian::write<uint32_t>(OS, SectionIndex, ELFT::TargetEndianness);
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000814 }
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000815}
816
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000817template <class ELFT>
George Rimar3212ecf2019-09-09 09:43:03 +0000818void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
George Rimar646af082019-02-19 15:29:07 +0000819 const ELFYAML::SymverSection &Section,
820 ContiguousBlobAccumulator &CBA) {
George Rimar646af082019-02-19 15:29:07 +0000821 raw_ostream &OS =
822 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
George Rimardac37fb2019-02-20 14:01:02 +0000823 for (uint16_t Version : Section.Entries)
824 support::endian::write<uint16_t>(OS, Version, ELFT::TargetEndianness);
George Rimar646af082019-02-19 15:29:07 +0000825
George Rimar149aa2f2019-08-05 13:54:35 +0000826 SHeader.sh_entsize = Section.EntSize ? (uint64_t)*Section.EntSize : 2;
George Rimard063c7d2019-02-20 13:58:43 +0000827 SHeader.sh_size = Section.Entries.size() * SHeader.sh_entsize;
George Rimar646af082019-02-19 15:29:07 +0000828}
829
830template <class ELFT>
George Rimar1a219aa2019-09-24 14:22:37 +0000831void ELFState<ELFT>::writeSectionContent(
832 Elf_Shdr &SHeader, const ELFYAML::StackSizesSection &Section,
833 ContiguousBlobAccumulator &CBA) {
834 using uintX_t = typename ELFT::uint;
835 raw_ostream &OS =
836 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
837
George Rimarf3024362019-09-25 11:40:11 +0000838 if (Section.Content || Section.Size) {
839 SHeader.sh_size = writeContent(OS, Section.Content, Section.Size);
George Rimar1a219aa2019-09-24 14:22:37 +0000840 return;
841 }
842
843 for (const ELFYAML::StackSizeEntry &E : *Section.Entries) {
844 support::endian::write<uintX_t>(OS, E.Address, ELFT::TargetEndianness);
845 SHeader.sh_size += sizeof(uintX_t) + encodeULEB128(E.Size, OS);
846 }
847}
848
849template <class ELFT>
George Rimar3212ecf2019-09-09 09:43:03 +0000850void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
George Rimare5163eb2019-10-01 09:45:59 +0000851 const ELFYAML::HashSection &Section,
852 ContiguousBlobAccumulator &CBA) {
853 raw_ostream &OS =
854 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
855
856 unsigned Link = 0;
George Rimar0210a1a2019-10-01 09:54:40 +0000857 if (Section.Link.empty() && SN2I.lookup(".dynsym", Link))
George Rimare5163eb2019-10-01 09:45:59 +0000858 SHeader.sh_link = Link;
859
George Rimar6fa696f2019-10-02 13:52:37 +0000860 if (Section.Content || Section.Size) {
861 SHeader.sh_size = writeContent(OS, Section.Content, Section.Size);
George Rimare5163eb2019-10-01 09:45:59 +0000862 return;
863 }
864
865 support::endian::write<uint32_t>(OS, Section.Bucket->size(),
866 ELFT::TargetEndianness);
867 support::endian::write<uint32_t>(OS, Section.Chain->size(),
868 ELFT::TargetEndianness);
869 for (uint32_t Val : *Section.Bucket)
870 support::endian::write<uint32_t>(OS, Val, ELFT::TargetEndianness);
871 for (uint32_t Val : *Section.Chain)
872 support::endian::write<uint32_t>(OS, Val, ELFT::TargetEndianness);
873
874 SHeader.sh_size = (2 + Section.Bucket->size() + Section.Chain->size()) * 4;
875}
876
877template <class ELFT>
878void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
George Rimar623ae722019-02-21 12:21:43 +0000879 const ELFYAML::VerdefSection &Section,
880 ContiguousBlobAccumulator &CBA) {
881 typedef typename ELFT::Verdef Elf_Verdef;
882 typedef typename ELFT::Verdaux Elf_Verdaux;
883 raw_ostream &OS =
884 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
885
886 uint64_t AuxCnt = 0;
887 for (size_t I = 0; I < Section.Entries.size(); ++I) {
888 const ELFYAML::VerdefEntry &E = Section.Entries[I];
889
890 Elf_Verdef VerDef;
891 VerDef.vd_version = E.Version;
892 VerDef.vd_flags = E.Flags;
893 VerDef.vd_ndx = E.VersionNdx;
894 VerDef.vd_hash = E.Hash;
895 VerDef.vd_aux = sizeof(Elf_Verdef);
896 VerDef.vd_cnt = E.VerNames.size();
897 if (I == Section.Entries.size() - 1)
898 VerDef.vd_next = 0;
899 else
900 VerDef.vd_next =
901 sizeof(Elf_Verdef) + E.VerNames.size() * sizeof(Elf_Verdaux);
902 OS.write((const char *)&VerDef, sizeof(Elf_Verdef));
903
904 for (size_t J = 0; J < E.VerNames.size(); ++J, ++AuxCnt) {
905 Elf_Verdaux VernAux;
906 VernAux.vda_name = DotDynstr.getOffset(E.VerNames[J]);
907 if (J == E.VerNames.size() - 1)
908 VernAux.vda_next = 0;
909 else
910 VernAux.vda_next = sizeof(Elf_Verdaux);
911 OS.write((const char *)&VernAux, sizeof(Elf_Verdaux));
912 }
913 }
914
915 SHeader.sh_size = Section.Entries.size() * sizeof(Elf_Verdef) +
916 AuxCnt * sizeof(Elf_Verdaux);
917 SHeader.sh_info = Section.Info;
George Rimar623ae722019-02-21 12:21:43 +0000918}
919
920template <class ELFT>
George Rimar3212ecf2019-09-09 09:43:03 +0000921void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
George Rimar0621b792019-02-19 14:53:48 +0000922 const ELFYAML::VerneedSection &Section,
923 ContiguousBlobAccumulator &CBA) {
George Rimarda1b3ab2019-04-26 12:15:32 +0000924 typedef typename ELFT::Verneed Elf_Verneed;
925 typedef typename ELFT::Vernaux Elf_Vernaux;
George Rimar0621b792019-02-19 14:53:48 +0000926
George Rimarda1b3ab2019-04-26 12:15:32 +0000927 auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
George Rimar0621b792019-02-19 14:53:48 +0000928
George Rimarda1b3ab2019-04-26 12:15:32 +0000929 uint64_t AuxCnt = 0;
930 for (size_t I = 0; I < Section.VerneedV.size(); ++I) {
931 const ELFYAML::VerneedEntry &VE = Section.VerneedV[I];
George Rimar0621b792019-02-19 14:53:48 +0000932
George Rimarda1b3ab2019-04-26 12:15:32 +0000933 Elf_Verneed VerNeed;
934 VerNeed.vn_version = VE.Version;
935 VerNeed.vn_file = DotDynstr.getOffset(VE.File);
936 if (I == Section.VerneedV.size() - 1)
937 VerNeed.vn_next = 0;
938 else
939 VerNeed.vn_next =
940 sizeof(Elf_Verneed) + VE.AuxV.size() * sizeof(Elf_Vernaux);
941 VerNeed.vn_cnt = VE.AuxV.size();
942 VerNeed.vn_aux = sizeof(Elf_Verneed);
943 OS.write((const char *)&VerNeed, sizeof(Elf_Verneed));
George Rimar0621b792019-02-19 14:53:48 +0000944
George Rimarda1b3ab2019-04-26 12:15:32 +0000945 for (size_t J = 0; J < VE.AuxV.size(); ++J, ++AuxCnt) {
946 const ELFYAML::VernauxEntry &VAuxE = VE.AuxV[J];
George Rimar0621b792019-02-19 14:53:48 +0000947
George Rimarda1b3ab2019-04-26 12:15:32 +0000948 Elf_Vernaux VernAux;
949 VernAux.vna_hash = VAuxE.Hash;
950 VernAux.vna_flags = VAuxE.Flags;
951 VernAux.vna_other = VAuxE.Other;
952 VernAux.vna_name = DotDynstr.getOffset(VAuxE.Name);
953 if (J == VE.AuxV.size() - 1)
954 VernAux.vna_next = 0;
955 else
956 VernAux.vna_next = sizeof(Elf_Vernaux);
957 OS.write((const char *)&VernAux, sizeof(Elf_Vernaux));
958 }
959 }
George Rimar0621b792019-02-19 14:53:48 +0000960
George Rimarda1b3ab2019-04-26 12:15:32 +0000961 SHeader.sh_size = Section.VerneedV.size() * sizeof(Elf_Verneed) +
962 AuxCnt * sizeof(Elf_Vernaux);
963 SHeader.sh_info = Section.Info;
George Rimar0621b792019-02-19 14:53:48 +0000964}
965
966template <class ELFT>
George Rimar3212ecf2019-09-09 09:43:03 +0000967void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000968 const ELFYAML::MipsABIFlags &Section,
969 ContiguousBlobAccumulator &CBA) {
Simon Atanasyan8eb9d1b2015-05-08 07:05:04 +0000970 assert(Section.Type == llvm::ELF::SHT_MIPS_ABIFLAGS &&
971 "Section type is not SHT_MIPS_ABIFLAGS");
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000972
973 object::Elf_Mips_ABIFlags<ELFT> Flags;
974 zero(Flags);
975 SHeader.sh_entsize = sizeof(Flags);
976 SHeader.sh_size = SHeader.sh_entsize;
977
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000978 auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000979 Flags.version = Section.Version;
980 Flags.isa_level = Section.ISALevel;
981 Flags.isa_rev = Section.ISARevision;
982 Flags.gpr_size = Section.GPRSize;
983 Flags.cpr1_size = Section.CPR1Size;
984 Flags.cpr2_size = Section.CPR2Size;
985 Flags.fp_abi = Section.FpABI;
986 Flags.isa_ext = Section.ISAExtension;
987 Flags.ases = Section.ASEs;
988 Flags.flags1 = Section.Flags1;
989 Flags.flags2 = Section.Flags2;
990 OS.write((const char *)&Flags, sizeof(Flags));
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000991}
992
George Rimar0e7ed912019-02-09 11:34:28 +0000993template <class ELFT>
George Rimar3212ecf2019-09-09 09:43:03 +0000994void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
George Rimar0e7ed912019-02-09 11:34:28 +0000995 const ELFYAML::DynamicSection &Section,
996 ContiguousBlobAccumulator &CBA) {
George Rimard063c7d2019-02-20 13:58:43 +0000997 typedef typename ELFT::uint uintX_t;
998
George Rimar0e7ed912019-02-09 11:34:28 +0000999 assert(Section.Type == llvm::ELF::SHT_DYNAMIC &&
1000 "Section type is not SHT_DYNAMIC");
1001
George Rimar3212ecf2019-09-09 09:43:03 +00001002 if (!Section.Entries.empty() && Section.Content)
1003 reportError("cannot specify both raw content and explicit entries "
1004 "for dynamic section '" +
1005 Section.Name + "'");
James Hendersonfd997802019-02-25 11:02:24 +00001006
1007 if (Section.Content)
1008 SHeader.sh_size = Section.Content->binary_size();
1009 else
1010 SHeader.sh_size = 2 * sizeof(uintX_t) * Section.Entries.size();
George Rimar0e7ed912019-02-09 11:34:28 +00001011 if (Section.EntSize)
1012 SHeader.sh_entsize = *Section.EntSize;
1013 else
1014 SHeader.sh_entsize = sizeof(Elf_Dyn);
1015
Alex Brachetc22d9662019-08-07 02:44:49 +00001016 raw_ostream &OS =
1017 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
George Rimar0e7ed912019-02-09 11:34:28 +00001018 for (const ELFYAML::DynamicEntry &DE : Section.Entries) {
George Rimard063c7d2019-02-20 13:58:43 +00001019 support::endian::write<uintX_t>(OS, DE.Tag, ELFT::TargetEndianness);
1020 support::endian::write<uintX_t>(OS, DE.Val, ELFT::TargetEndianness);
George Rimar0e7ed912019-02-09 11:34:28 +00001021 }
James Hendersonfd997802019-02-25 11:02:24 +00001022 if (Section.Content)
1023 Section.Content->writeAsBinary(OS);
George Rimar0e7ed912019-02-09 11:34:28 +00001024}
1025
George Rimarfc9104d2019-10-03 14:52:33 +00001026template <class ELFT>
1027void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
1028 const ELFYAML::AddrsigSection &Section,
1029 ContiguousBlobAccumulator &CBA) {
1030 raw_ostream &OS =
1031 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
1032
1033 unsigned Link = 0;
1034 if (Section.Link.empty() && SN2I.lookup(".symtab", Link))
1035 SHeader.sh_link = Link;
1036
George Rimarc18585e2019-10-03 15:02:18 +00001037 if (Section.Content || Section.Size) {
1038 SHeader.sh_size = writeContent(OS, Section.Content, Section.Size);
George Rimarfc9104d2019-10-03 14:52:33 +00001039 return;
1040 }
1041
1042 for (const ELFYAML::AddrsigSymbol &Sym : *Section.Symbols) {
1043 uint64_t Val =
1044 Sym.Name ? toSymbolIndex(*Sym.Name, Section.Name, /*IsDynamic=*/false)
1045 : (uint32_t)*Sym.Index;
1046 SHeader.sh_size += encodeULEB128(Val, OS);
1047 }
1048}
1049
georgerimde3cef12019-10-25 13:03:19 +03001050template <class ELFT>
1051void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
1052 const ELFYAML::NoteSection &Section,
1053 ContiguousBlobAccumulator &CBA) {
1054 raw_ostream &OS =
1055 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
1056 uint64_t Offset = OS.tell();
1057
1058 if (Section.Content || Section.Size) {
1059 SHeader.sh_size = writeContent(OS, Section.Content, Section.Size);
1060 return;
1061 }
1062
1063 for (const ELFYAML::NoteEntry &NE : *Section.Notes) {
1064 // Write name size.
1065 if (NE.Name.empty())
1066 support::endian::write<uint32_t>(OS, 0, ELFT::TargetEndianness);
1067 else
1068 support::endian::write<uint32_t>(OS, NE.Name.size() + 1,
1069 ELFT::TargetEndianness);
1070
1071 // Write description size.
1072 if (NE.Desc.binary_size() == 0)
1073 support::endian::write<uint32_t>(OS, 0, ELFT::TargetEndianness);
1074 else
1075 support::endian::write<uint32_t>(OS, NE.Desc.binary_size(),
1076 ELFT::TargetEndianness);
1077
1078 // Write type.
1079 support::endian::write<uint32_t>(OS, NE.Type, ELFT::TargetEndianness);
1080
1081 // Write name, null terminator and padding.
1082 if (!NE.Name.empty()) {
1083 support::endian::write<uint8_t>(OS, arrayRefFromStringRef(NE.Name),
1084 ELFT::TargetEndianness);
1085 support::endian::write<uint8_t>(OS, 0, ELFT::TargetEndianness);
1086 CBA.padToAlignment(4);
1087 }
1088
1089 // Write description and padding.
1090 if (NE.Desc.binary_size() != 0) {
1091 NE.Desc.writeAsBinary(OS);
1092 CBA.padToAlignment(4);
1093 }
1094 }
1095
1096 SHeader.sh_size = OS.tell() - Offset;
1097}
1098
georgerima7aee6c2019-10-24 15:38:53 +03001099template <class ELFT>
1100void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
1101 const ELFYAML::GnuHashSection &Section,
1102 ContiguousBlobAccumulator &CBA) {
1103 raw_ostream &OS =
1104 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
1105
1106 unsigned Link = 0;
1107 if (Section.Link.empty() && SN2I.lookup(".dynsym", Link))
1108 SHeader.sh_link = Link;
1109
1110 if (Section.Content) {
1111 SHeader.sh_size = writeContent(OS, Section.Content, None);
1112 return;
1113 }
1114
1115 // We write the header first, starting with the hash buckets count. Normally
1116 // it is the number of entries in HashBuckets, but the "NBuckets" property can
1117 // be used to override this field, which is useful for producing broken
1118 // objects.
1119 if (Section.Header->NBuckets)
1120 support::endian::write<uint32_t>(OS, *Section.Header->NBuckets,
1121 ELFT::TargetEndianness);
1122 else
1123 support::endian::write<uint32_t>(OS, Section.HashBuckets->size(),
1124 ELFT::TargetEndianness);
1125
1126 // Write the index of the first symbol in the dynamic symbol table accessible
1127 // via the hash table.
1128 support::endian::write<uint32_t>(OS, Section.Header->SymNdx,
1129 ELFT::TargetEndianness);
1130
1131 // Write the number of words in the Bloom filter. As above, the "MaskWords"
1132 // property can be used to set this field to any value.
1133 if (Section.Header->MaskWords)
1134 support::endian::write<uint32_t>(OS, *Section.Header->MaskWords,
1135 ELFT::TargetEndianness);
1136 else
1137 support::endian::write<uint32_t>(OS, Section.BloomFilter->size(),
1138 ELFT::TargetEndianness);
1139
1140 // Write the shift constant used by the Bloom filter.
1141 support::endian::write<uint32_t>(OS, Section.Header->Shift2,
1142 ELFT::TargetEndianness);
1143
1144 // We've finished writing the header. Now write the Bloom filter.
1145 for (llvm::yaml::Hex64 Val : *Section.BloomFilter)
1146 support::endian::write<typename ELFT::uint>(OS, Val,
1147 ELFT::TargetEndianness);
1148
1149 // Write an array of hash buckets.
1150 for (llvm::yaml::Hex32 Val : *Section.HashBuckets)
1151 support::endian::write<uint32_t>(OS, Val, ELFT::TargetEndianness);
1152
1153 // Write an array of hash values.
1154 for (llvm::yaml::Hex32 Val : *Section.HashValues)
1155 support::endian::write<uint32_t>(OS, Val, ELFT::TargetEndianness);
1156
1157 SHeader.sh_size = 16 /*Header size*/ +
1158 Section.BloomFilter->size() * sizeof(typename ELFT::uint) +
1159 Section.HashBuckets->size() * 4 +
1160 Section.HashValues->size() * 4;
1161}
1162
George Rimar3212ecf2019-09-09 09:43:03 +00001163template <class ELFT> void ELFState<ELFT>::buildSectionIndex() {
George Rimar14802292019-07-25 10:19:23 +00001164 for (unsigned I = 0, E = Doc.Sections.size(); I != E; ++I) {
George Rimarab658f42019-07-23 07:38:44 +00001165 StringRef Name = Doc.Sections[I]->Name;
George Rimar14802292019-07-25 10:19:23 +00001166 if (Name.empty())
1167 continue;
1168
George Rimarcfc2bcc2019-09-25 12:09:30 +00001169 DotShStrtab.add(ELFYAML::dropUniqueSuffix(Name));
George Rimar3212ecf2019-09-09 09:43:03 +00001170 if (!SN2I.addName(Name, I))
1171 reportError("repeated section name: '" + Name +
1172 "' at YAML section number " + Twine(I));
Sean Silvaaff51252013-06-21 00:27:50 +00001173 }
Dave Lee17307d92017-11-09 14:53:43 +00001174
Dave Lee17307d92017-11-09 14:53:43 +00001175 DotShStrtab.finalize();
Sean Silva6b083882013-06-18 23:14:03 +00001176}
1177
George Rimar3212ecf2019-09-09 09:43:03 +00001178template <class ELFT> void ELFState<ELFT>::buildSymbolIndexes() {
1179 auto Build = [this](ArrayRef<ELFYAML::Symbol> V, NameToIdxMap &Map) {
1180 for (size_t I = 0, S = V.size(); I < S; ++I) {
1181 const ELFYAML::Symbol &Sym = V[I];
1182 if (!Sym.Name.empty() && !Map.addName(Sym.Name, I + 1))
1183 reportError("repeated symbol name: '" + Sym.Name + "'");
1184 }
1185 };
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +00001186
George Rimar27799872019-10-20 14:47:17 +00001187 if (Doc.Symbols)
1188 Build(*Doc.Symbols, SymN2I);
George Rimar3212ecf2019-09-09 09:43:03 +00001189 Build(Doc.DynamicSymbols, DynSymN2I);
George Rimar91208442019-08-22 12:39:56 +00001190}
1191
George Rimar0621b792019-02-19 14:53:48 +00001192template <class ELFT> void ELFState<ELFT>::finalizeStrings() {
George Rimar0621b792019-02-19 14:53:48 +00001193 // Add the regular symbol names to .strtab section.
George Rimar27799872019-10-20 14:47:17 +00001194 if (Doc.Symbols)
1195 for (const ELFYAML::Symbol &Sym : *Doc.Symbols)
1196 DotStrtab.add(ELFYAML::dropUniqueSuffix(Sym.Name));
George Rimar0621b792019-02-19 14:53:48 +00001197 DotStrtab.finalize();
1198
George Rimar0621b792019-02-19 14:53:48 +00001199 // Add the dynamic symbol names to .dynstr section.
George Rimar6da44ad2019-04-03 14:53:42 +00001200 for (const ELFYAML::Symbol &Sym : Doc.DynamicSymbols)
George Rimarcfc2bcc2019-09-25 12:09:30 +00001201 DotDynstr.add(ELFYAML::dropUniqueSuffix(Sym.Name));
George Rimar0621b792019-02-19 14:53:48 +00001202
George Rimar623ae722019-02-21 12:21:43 +00001203 // SHT_GNU_verdef and SHT_GNU_verneed sections might also
1204 // add strings to .dynstr section.
George Rimar0621b792019-02-19 14:53:48 +00001205 for (const std::unique_ptr<ELFYAML::Section> &Sec : Doc.Sections) {
George Rimar623ae722019-02-21 12:21:43 +00001206 if (auto VerNeed = dyn_cast<ELFYAML::VerneedSection>(Sec.get())) {
1207 for (const ELFYAML::VerneedEntry &VE : VerNeed->VerneedV) {
1208 DotDynstr.add(VE.File);
1209 for (const ELFYAML::VernauxEntry &Aux : VE.AuxV)
1210 DotDynstr.add(Aux.Name);
1211 }
1212 } else if (auto VerDef = dyn_cast<ELFYAML::VerdefSection>(Sec.get())) {
1213 for (const ELFYAML::VerdefEntry &E : VerDef->Entries)
1214 for (StringRef Name : E.VerNames)
1215 DotDynstr.add(Name);
George Rimar0621b792019-02-19 14:53:48 +00001216 }
1217 }
1218
1219 DotDynstr.finalize();
1220}
1221
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +00001222template <class ELFT>
George Rimar85011022019-09-13 16:00:16 +00001223bool ELFState<ELFT>::writeELF(raw_ostream &OS, ELFYAML::Object &Doc,
1224 yaml::ErrorHandler EH) {
1225 ELFState<ELFT> State(Doc, EH);
George Rimar0621b792019-02-19 14:53:48 +00001226
1227 // Finalize .strtab and .dynstr sections. We do that early because want to
1228 // finalize the string table builders before writing the content of the
1229 // sections that might want to use them.
1230 State.finalizeStrings();
1231
George Rimar3212ecf2019-09-09 09:43:03 +00001232 State.buildSectionIndex();
1233 State.buildSymbolIndexes();
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +00001234
Petr Hosekeb04da32017-07-19 20:38:46 +00001235 std::vector<Elf_Phdr> PHeaders;
1236 State.initProgramHeaders(PHeaders);
Sean Silva38205932013-06-13 22:19:48 +00001237
Sean Silva08a75ae2013-06-20 19:11:44 +00001238 // XXX: This offset is tightly coupled with the order that we write
1239 // things to `OS`.
Fangrui Songc3bc6972019-09-05 14:25:57 +00001240 const size_t SectionContentBeginOffset =
1241 sizeof(Elf_Ehdr) + sizeof(Elf_Phdr) * Doc.ProgramHeaders.size();
Sean Silva08a75ae2013-06-20 19:11:44 +00001242 ContiguousBlobAccumulator CBA(SectionContentBeginOffset);
Sean Silvac1c290b2013-06-20 20:59:34 +00001243
Sean Silva38205932013-06-13 22:19:48 +00001244 std::vector<Elf_Shdr> SHeaders;
George Rimar3212ecf2019-09-09 09:43:03 +00001245 State.initSectionHeaders(SHeaders, CBA);
Sean Silva38205932013-06-13 22:19:48 +00001246
georgerim64df7082019-10-23 12:22:52 +03001247 // Now we can decide segment offsets.
Petr Hosekeb04da32017-07-19 20:38:46 +00001248 State.setProgramHeaderLayout(PHeaders, SHeaders);
1249
George Rimar3212ecf2019-09-09 09:43:03 +00001250 if (State.HasError)
George Rimar7da559f2019-09-13 09:12:38 +00001251 return false;
George Rimar3212ecf2019-09-09 09:43:03 +00001252
Fangrui Songc3bc6972019-09-05 14:25:57 +00001253 State.writeELFHeader(CBA, OS);
Petr Hosekeb04da32017-07-19 20:38:46 +00001254 writeArrayData(OS, makeArrayRef(PHeaders));
Sean Silva46dffff2013-06-13 22:20:01 +00001255 CBA.writeBlobToStream(OS);
Fangrui Songc3bc6972019-09-05 14:25:57 +00001256 writeArrayData(OS, makeArrayRef(SHeaders));
George Rimar7da559f2019-09-13 09:12:38 +00001257 return true;
Sean Silvaf99309c2013-06-10 23:44:15 +00001258}
1259
Alex Brachetc22d9662019-08-07 02:44:49 +00001260namespace llvm {
1261namespace yaml {
1262
George Rimar85011022019-09-13 16:00:16 +00001263bool yaml2elf(llvm::ELFYAML::Object &Doc, raw_ostream &Out, ErrorHandler EH) {
George Rimarbc4d3c42019-04-29 12:25:01 +00001264 bool IsLE = Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB);
1265 bool Is64Bit = Doc.Header.Class == ELFYAML::ELF_ELFCLASS(ELF::ELFCLASS64);
1266 if (Is64Bit) {
1267 if (IsLE)
George Rimar85011022019-09-13 16:00:16 +00001268 return ELFState<object::ELF64LE>::writeELF(Out, Doc, EH);
1269 return ELFState<object::ELF64BE>::writeELF(Out, Doc, EH);
Sean Silvaf99309c2013-06-10 23:44:15 +00001270 }
George Rimarbc4d3c42019-04-29 12:25:01 +00001271 if (IsLE)
George Rimar85011022019-09-13 16:00:16 +00001272 return ELFState<object::ELF32LE>::writeELF(Out, Doc, EH);
1273 return ELFState<object::ELF32BE>::writeELF(Out, Doc, EH);
Sean Silvaf99309c2013-06-10 23:44:15 +00001274}
Alex Brachetc22d9662019-08-07 02:44:49 +00001275
1276} // namespace yaml
1277} // namespace llvm