blob: e093ed8d72f81647c3df8d6a9f52c9437a3eb550 [file] [log] [blame]
Sean Silvaf99309c2013-06-10 23:44:15 +00001//===- yaml2elf - Convert YAML to a ELF object file -----------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Sean Silvaf99309c2013-06-10 23:44:15 +00006//
7//===----------------------------------------------------------------------===//
8///
9/// \file
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000010/// The ELF component of yaml2obj.
Sean Silvaf99309c2013-06-10 23:44:15 +000011///
12//===----------------------------------------------------------------------===//
13
14#include "yaml2obj.h"
Will Dietz0b48c732013-10-12 21:29:16 +000015#include "llvm/ADT/ArrayRef.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000016#include "llvm/BinaryFormat/ELF.h"
Rafael Espindola97de4742014-07-03 02:01:39 +000017#include "llvm/MC/StringTableBuilder.h"
Michael J. Spencer126973b2013-08-08 22:27:13 +000018#include "llvm/Object/ELFObjectFile.h"
Rafael Espindolaebd91932016-03-01 19:15:06 +000019#include "llvm/ObjectYAML/ELFYAML.h"
George Rimard063c7d2019-02-20 13:58:43 +000020#include "llvm/Support/EndianStream.h"
Sean Silvaf99309c2013-06-10 23:44:15 +000021#include "llvm/Support/MemoryBuffer.h"
Jonas Devlieghere2cd41eb2018-04-21 21:11:59 +000022#include "llvm/Support/WithColor.h"
Sean Silvaf99309c2013-06-10 23:44:15 +000023#include "llvm/Support/YAMLTraits.h"
24#include "llvm/Support/raw_ostream.h"
25
26using namespace llvm;
27
Sean Silva46dffff2013-06-13 22:20:01 +000028// This class is used to build up a contiguous binary blob while keeping
29// track of an offset in the output (which notionally begins at
30// `InitialOffset`).
Sean Silva2a74f702013-06-15 00:31:46 +000031namespace {
Sean Silva46dffff2013-06-13 22:20:01 +000032class ContiguousBlobAccumulator {
33 const uint64_t InitialOffset;
Sean Silvabd3bc692013-06-20 19:11:41 +000034 SmallVector<char, 128> Buf;
Sean Silva46dffff2013-06-13 22:20:01 +000035 raw_svector_ostream OS;
36
Sean Silvad93323f2013-06-22 00:47:43 +000037 /// \returns The new offset.
38 uint64_t padToAlignment(unsigned Align) {
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +000039 if (Align == 0)
40 Align = 1;
Sean Silvad93323f2013-06-22 00:47:43 +000041 uint64_t CurrentOffset = InitialOffset + OS.tell();
Rui Ueyamada00f2f2016-01-14 21:06:47 +000042 uint64_t AlignedOffset = alignTo(CurrentOffset, Align);
George Rimarbd8bfd32019-04-29 12:05:53 +000043 OS.write_zeros(AlignedOffset - CurrentOffset);
Sean Silvad93323f2013-06-22 00:47:43 +000044 return AlignedOffset; // == CurrentOffset;
45 }
46
Sean Silva46dffff2013-06-13 22:20:01 +000047public:
Sean Silvabd3bc692013-06-20 19:11:41 +000048 ContiguousBlobAccumulator(uint64_t InitialOffset_)
49 : InitialOffset(InitialOffset_), Buf(), OS(Buf) {}
Sean Silvad93323f2013-06-22 00:47:43 +000050 template <class Integer>
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +000051 raw_ostream &getOSAndAlignedOffset(Integer &Offset, unsigned Align) {
Sean Silvad93323f2013-06-22 00:47:43 +000052 Offset = padToAlignment(Align);
53 return OS;
54 }
Sean Silva46dffff2013-06-13 22:20:01 +000055 void writeBlobToStream(raw_ostream &Out) { Out << OS.str(); }
56};
Sean Silva2a74f702013-06-15 00:31:46 +000057} // end anonymous namespace
Sean Silva46dffff2013-06-13 22:20:01 +000058
Simon Atanasyan35babf92014-04-06 09:02:55 +000059// Used to keep track of section and symbol names, so that in the YAML file
George Rimar09746882019-05-07 12:10:51 +000060// sections and symbols can be referenced by name instead of by index.
61namespace {
62class NameToIdxMap {
Puyan Lotfia10f0162019-05-11 17:03:36 +000063 StringMap<unsigned> Map;
64
George Rimar09746882019-05-07 12:10:51 +000065public:
Puyan Lotfia10f0162019-05-11 17:03:36 +000066 /// \Returns false if name is already present in the map.
67 bool addName(StringRef Name, unsigned Ndx) {
68 return Map.insert({Name, Ndx}).second;
George Rimar09746882019-05-07 12:10:51 +000069 }
Puyan Lotfia10f0162019-05-11 17:03:36 +000070 /// \Returns false if name is not present in the map.
George Rimar09746882019-05-07 12:10:51 +000071 bool lookup(StringRef Name, unsigned &Idx) const {
Puyan Lotfia10f0162019-05-11 17:03:36 +000072 auto I = Map.find(Name);
George Rimar09746882019-05-07 12:10:51 +000073 if (I == Map.end())
Puyan Lotfia10f0162019-05-11 17:03:36 +000074 return false;
George Rimar09746882019-05-07 12:10:51 +000075 Idx = I->getValue();
Puyan Lotfia10f0162019-05-11 17:03:36 +000076 return true;
George Rimar09746882019-05-07 12:10:51 +000077 }
Puyan Lotfia10f0162019-05-11 17:03:36 +000078 /// Asserts if name is not present in the map.
George Rimar09746882019-05-07 12:10:51 +000079 unsigned get(StringRef Name) const {
Puyan Lotfia10f0162019-05-11 17:03:36 +000080 unsigned Idx;
81 if (lookup(Name, Idx))
82 return Idx;
83 assert(false && "Expected section not found in index");
84 return 0;
George Rimar09746882019-05-07 12:10:51 +000085 }
86 unsigned size() const { return Map.size(); }
87};
Sean Silva2a74f702013-06-15 00:31:46 +000088} // end anonymous namespace
Sean Silvaa6423eb2013-06-15 00:25:26 +000089
Sean Silva38205932013-06-13 22:19:48 +000090template <class T>
Will Dietz0b48c732013-10-12 21:29:16 +000091static size_t arrayDataSize(ArrayRef<T> A) {
92 return A.size() * sizeof(T);
Sean Silva38205932013-06-13 22:19:48 +000093}
94
95template <class T>
Will Dietz0b48c732013-10-12 21:29:16 +000096static void writeArrayData(raw_ostream &OS, ArrayRef<T> A) {
97 OS.write((const char *)A.data(), arrayDataSize(A));
Sean Silva38205932013-06-13 22:19:48 +000098}
99
100template <class T>
101static void zero(T &Obj) {
102 memset(&Obj, 0, sizeof(Obj));
103}
104
Sean Silva08a75ae2013-06-20 19:11:44 +0000105namespace {
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000106/// "Single point of truth" for the ELF file construction.
Sean Silva08a75ae2013-06-20 19:11:44 +0000107/// TODO: This class still has a ways to go before it is truly a "single
108/// point of truth".
109template <class ELFT>
110class ELFState {
Rui Ueyama478d6352018-01-12 02:28:31 +0000111 typedef typename ELFT::Ehdr Elf_Ehdr;
112 typedef typename ELFT::Phdr Elf_Phdr;
113 typedef typename ELFT::Shdr Elf_Shdr;
114 typedef typename ELFT::Sym Elf_Sym;
115 typedef typename ELFT::Rel Elf_Rel;
116 typedef typename ELFT::Rela Elf_Rela;
Jake Ehrlich0f440d82018-06-28 21:07:34 +0000117 typedef typename ELFT::Relr Elf_Relr;
Paul Semel1dbbfba2018-07-23 18:49:04 +0000118 typedef typename ELFT::Dyn Elf_Dyn;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000119
Dave Lee67b49662017-11-16 18:10:15 +0000120 enum class SymtabType { Static, Dynamic };
121
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000122 /// The future ".strtab" section.
Rafael Espindola21956e42015-10-23 21:48:05 +0000123 StringTableBuilder DotStrtab{StringTableBuilder::ELF};
Sean Silva08a75ae2013-06-20 19:11:44 +0000124
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000125 /// The future ".shstrtab" section.
Rafael Espindola21956e42015-10-23 21:48:05 +0000126 StringTableBuilder DotShStrtab{StringTableBuilder::ELF};
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000127
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000128 /// The future ".dynstr" section.
Dave Lee67b49662017-11-16 18:10:15 +0000129 StringTableBuilder DotDynstr{StringTableBuilder::ELF};
130
Simon Atanasyan35babf92014-04-06 09:02:55 +0000131 NameToIdxMap SN2I;
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000132 NameToIdxMap SymN2I;
Simon Atanasyan220c54a2014-04-02 16:34:40 +0000133 const ELFYAML::Object &Doc;
Sean Silvac1c290b2013-06-20 20:59:34 +0000134
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000135 bool buildSectionIndex();
George Rimar6da44ad2019-04-03 14:53:42 +0000136 bool buildSymbolIndex(ArrayRef<ELFYAML::Symbol> Symbols);
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000137 void initELFHeader(Elf_Ehdr &Header);
Petr Hosekeb04da32017-07-19 20:38:46 +0000138 void initProgramHeaders(std::vector<Elf_Phdr> &PHeaders);
George Rimar66296dc2019-06-05 13:16:53 +0000139 bool initImplicitHeader(ELFState<ELFT> &State, ContiguousBlobAccumulator &CBA,
140 Elf_Shdr &Header, StringRef SecName,
141 ELFYAML::Section *YAMLSec);
142 bool initSectionHeaders(ELFState<ELFT> &State,
143 std::vector<Elf_Shdr> &SHeaders,
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000144 ContiguousBlobAccumulator &CBA);
Dave Lee67b49662017-11-16 18:10:15 +0000145 void initSymtabSectionHeader(Elf_Shdr &SHeader, SymtabType STType,
George Rimar66296dc2019-06-05 13:16:53 +0000146 ContiguousBlobAccumulator &CBA,
147 ELFYAML::Section *YAMLSec);
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000148 void initStrtabSectionHeader(Elf_Shdr &SHeader, StringRef Name,
149 StringTableBuilder &STB,
George Rimar66296dc2019-06-05 13:16:53 +0000150 ContiguousBlobAccumulator &CBA,
151 ELFYAML::Section *YAMLSec);
Petr Hosekeb04da32017-07-19 20:38:46 +0000152 void setProgramHeaderLayout(std::vector<Elf_Phdr> &PHeaders,
153 std::vector<Elf_Shdr> &SHeaders);
George Rimarda1b3ab2019-04-26 12:15:32 +0000154 bool writeSectionContent(Elf_Shdr &SHeader,
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000155 const ELFYAML::RawContentSection &Section,
156 ContiguousBlobAccumulator &CBA);
157 bool writeSectionContent(Elf_Shdr &SHeader,
158 const ELFYAML::RelocationSection &Section,
159 ContiguousBlobAccumulator &CBA);
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000160 bool writeSectionContent(Elf_Shdr &SHeader, const ELFYAML::Group &Group,
161 ContiguousBlobAccumulator &CBA);
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000162 bool writeSectionContent(Elf_Shdr &SHeader,
George Rimar646af082019-02-19 15:29:07 +0000163 const ELFYAML::SymverSection &Section,
164 ContiguousBlobAccumulator &CBA);
165 bool writeSectionContent(Elf_Shdr &SHeader,
George Rimar0621b792019-02-19 14:53:48 +0000166 const ELFYAML::VerneedSection &Section,
167 ContiguousBlobAccumulator &CBA);
168 bool writeSectionContent(Elf_Shdr &SHeader,
George Rimar623ae722019-02-21 12:21:43 +0000169 const ELFYAML::VerdefSection &Section,
170 ContiguousBlobAccumulator &CBA);
171 bool writeSectionContent(Elf_Shdr &SHeader,
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000172 const ELFYAML::MipsABIFlags &Section,
173 ContiguousBlobAccumulator &CBA);
James Hendersonfd997802019-02-25 11:02:24 +0000174 bool writeSectionContent(Elf_Shdr &SHeader,
George Rimar0e7ed912019-02-09 11:34:28 +0000175 const ELFYAML::DynamicSection &Section,
176 ContiguousBlobAccumulator &CBA);
George Rimar5fcdebe2019-04-26 13:09:11 +0000177 std::vector<StringRef> implicitSectionNames() const;
Sean Silva08a75ae2013-06-20 19:11:44 +0000178
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000179 ELFState(const ELFYAML::Object &D) : Doc(D) {}
Simon Atanasyan220c54a2014-04-02 16:34:40 +0000180
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000181public:
182 static int writeELF(raw_ostream &OS, const ELFYAML::Object &Doc);
George Rimar0621b792019-02-19 14:53:48 +0000183
184private:
185 void finalizeStrings();
Sean Silva08a75ae2013-06-20 19:11:44 +0000186};
187} // end anonymous namespace
188
Sean Silva37e817c2013-06-21 00:33:01 +0000189template <class ELFT>
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000190void ELFState<ELFT>::initELFHeader(Elf_Ehdr &Header) {
191 using namespace llvm::ELF;
192 zero(Header);
193 Header.e_ident[EI_MAG0] = 0x7f;
194 Header.e_ident[EI_MAG1] = 'E';
195 Header.e_ident[EI_MAG2] = 'L';
196 Header.e_ident[EI_MAG3] = 'F';
197 Header.e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;
George Rimara5a0a0f2019-03-07 12:09:19 +0000198 Header.e_ident[EI_DATA] = Doc.Header.Data;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000199 Header.e_ident[EI_VERSION] = EV_CURRENT;
200 Header.e_ident[EI_OSABI] = Doc.Header.OSABI;
George Rimar6367d7a2018-12-20 10:43:49 +0000201 Header.e_ident[EI_ABIVERSION] = Doc.Header.ABIVersion;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000202 Header.e_type = Doc.Header.Type;
203 Header.e_machine = Doc.Header.Machine;
204 Header.e_version = EV_CURRENT;
205 Header.e_entry = Doc.Header.Entry;
Petr Hosekeb04da32017-07-19 20:38:46 +0000206 Header.e_phoff = sizeof(Header);
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000207 Header.e_flags = Doc.Header.Flags;
208 Header.e_ehsize = sizeof(Elf_Ehdr);
Petr Hosekeb04da32017-07-19 20:38:46 +0000209 Header.e_phentsize = sizeof(Elf_Phdr);
210 Header.e_phnum = Doc.ProgramHeaders.size();
George Rimar687d47c2019-06-27 11:08:42 +0000211
212 Header.e_shentsize =
213 Doc.Header.SHEntSize ? (uint16_t)*Doc.Header.SHEntSize : sizeof(Elf_Shdr);
Petr Hosekeb04da32017-07-19 20:38:46 +0000214 // Immediately following the ELF header and program headers.
215 Header.e_shoff =
George Rimar687d47c2019-06-27 11:08:42 +0000216 Doc.Header.SHOffset
217 ? (uint16_t)*Doc.Header.SHOffset
218 : sizeof(Header) + sizeof(Elf_Phdr) * Doc.ProgramHeaders.size();
219 Header.e_shnum =
220 Doc.Header.SHNum ? (uint16_t)*Doc.Header.SHNum : SN2I.size() + 1;
221 Header.e_shstrndx = Doc.Header.SHStrNdx ? (uint16_t)*Doc.Header.SHStrNdx
222 : SN2I.get(".shstrtab");
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000223}
224
225template <class ELFT>
Petr Hosekeb04da32017-07-19 20:38:46 +0000226void ELFState<ELFT>::initProgramHeaders(std::vector<Elf_Phdr> &PHeaders) {
227 for (const auto &YamlPhdr : Doc.ProgramHeaders) {
228 Elf_Phdr Phdr;
229 Phdr.p_type = YamlPhdr.Type;
230 Phdr.p_flags = YamlPhdr.Flags;
231 Phdr.p_vaddr = YamlPhdr.VAddr;
232 Phdr.p_paddr = YamlPhdr.PAddr;
233 PHeaders.push_back(Phdr);
234 }
235}
George Rimar09746882019-05-07 12:10:51 +0000236
237static bool convertSectionIndex(NameToIdxMap &SN2I, StringRef SecName,
238 StringRef IndexSrc, unsigned &IndexDest) {
Puyan Lotfia10f0162019-05-11 17:03:36 +0000239 if (!SN2I.lookup(IndexSrc, IndexDest) && !to_integer(IndexSrc, IndexDest)) {
George Rimar09746882019-05-07 12:10:51 +0000240 WithColor::error() << "Unknown section referenced: '" << IndexSrc
241 << "' at YAML section '" << SecName << "'.\n";
242 return false;
Xing GUO98228352018-12-04 14:27:51 +0000243 }
244 return true;
245}
246
Petr Hosekeb04da32017-07-19 20:38:46 +0000247template <class ELFT>
George Rimar66296dc2019-06-05 13:16:53 +0000248bool ELFState<ELFT>::initImplicitHeader(ELFState<ELFT> &State,
249 ContiguousBlobAccumulator &CBA,
250 Elf_Shdr &Header, StringRef SecName,
251 ELFYAML::Section *YAMLSec) {
252 // Check if the header was already initialized.
253 if (Header.sh_offset)
254 return false;
255
256 if (SecName == ".symtab")
257 State.initSymtabSectionHeader(Header, SymtabType::Static, CBA, YAMLSec);
258 else if (SecName == ".strtab")
259 State.initStrtabSectionHeader(Header, SecName, State.DotStrtab, CBA,
260 YAMLSec);
261 else if (SecName == ".shstrtab")
262 State.initStrtabSectionHeader(Header, SecName, State.DotShStrtab, CBA,
263 YAMLSec);
264
265 else if (SecName == ".dynsym")
266 State.initSymtabSectionHeader(Header, SymtabType::Dynamic, CBA, YAMLSec);
267 else if (SecName == ".dynstr")
268 State.initStrtabSectionHeader(Header, SecName, State.DotDynstr, CBA,
269 YAMLSec);
270 else
271 return false;
272 return true;
273}
274
George Rimar60dc5d42019-06-25 08:22:57 +0000275static StringRef dropUniqueSuffix(StringRef S) {
276 size_t SuffixPos = S.rfind(" [");
277 if (SuffixPos == StringRef::npos)
278 return S;
279 return S.substr(0, SuffixPos);
280}
281
George Rimar66296dc2019-06-05 13:16:53 +0000282template <class ELFT>
283bool ELFState<ELFT>::initSectionHeaders(ELFState<ELFT> &State,
284 std::vector<Elf_Shdr> &SHeaders,
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000285 ContiguousBlobAccumulator &CBA) {
George Rimareb394e92019-06-07 08:31:36 +0000286 // Build a list of sections we are going to add implicitly.
287 std::vector<StringRef> ImplicitSections;
288 for (StringRef Name : State.implicitSectionNames())
289 if (State.SN2I.get(Name) > Doc.Sections.size())
290 ImplicitSections.push_back(Name);
291
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000292 // Ensure SHN_UNDEF entry is present. An all-zero section header is a
293 // valid SHN_UNDEF entry since SHT_NULL == 0.
George Rimareb394e92019-06-07 08:31:36 +0000294 SHeaders.resize(Doc.Sections.size() + ImplicitSections.size() + 1);
295 zero(SHeaders[0]);
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000296
George Rimareb394e92019-06-07 08:31:36 +0000297 for (size_t I = 1; I < Doc.Sections.size() + ImplicitSections.size() + 1; ++I) {
298 Elf_Shdr &SHeader = SHeaders[I];
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000299 zero(SHeader);
George Rimareb394e92019-06-07 08:31:36 +0000300 ELFYAML::Section *Sec =
301 I > Doc.Sections.size() ? nullptr : Doc.Sections[I - 1].get();
302
303 // We have a few sections like string or symbol tables that are usually
304 // added implicitly to the end. However, if they are explicitly specified
305 // in the YAML, we need to write them here. This ensures the file offset
306 // remains correct.
307 StringRef SecName =
308 Sec ? Sec->Name : ImplicitSections[I - Doc.Sections.size() - 1];
309 if (initImplicitHeader(State, CBA, SHeader, SecName, Sec))
310 continue;
311
312 assert(Sec && "It can't be null unless it is an implicit section. But all "
313 "implicit sections should already have been handled above.");
314
George Rimar60dc5d42019-06-25 08:22:57 +0000315 SHeader.sh_name = DotShStrtab.getOffset(dropUniqueSuffix(SecName));
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000316 SHeader.sh_type = Sec->Type;
George Rimarcfa1a622019-06-14 11:01:14 +0000317 if (Sec->Flags)
318 SHeader.sh_flags = *Sec->Flags;
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000319 SHeader.sh_addr = Sec->Address;
320 SHeader.sh_addralign = Sec->AddressAlign;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000321
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000322 if (!Sec->Link.empty()) {
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000323 unsigned Index;
Xing GUO98228352018-12-04 14:27:51 +0000324 if (!convertSectionIndex(SN2I, Sec->Name, Sec->Link, Index))
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000325 return false;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000326 SHeader.sh_link = Index;
327 }
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000328
George Rimareb394e92019-06-07 08:31:36 +0000329 if (auto S = dyn_cast<ELFYAML::RawContentSection>(Sec)) {
George Rimarda1b3ab2019-04-26 12:15:32 +0000330 if (!writeSectionContent(SHeader, *S, CBA))
George Rimar7f2df7d2018-08-16 12:23:22 +0000331 return false;
George Rimareb394e92019-06-07 08:31:36 +0000332 } else if (auto S = dyn_cast<ELFYAML::RelocationSection>(Sec)) {
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000333 if (!writeSectionContent(SHeader, *S, CBA))
334 return false;
George Rimareb394e92019-06-07 08:31:36 +0000335 } else if (auto S = dyn_cast<ELFYAML::Group>(Sec)) {
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000336 if (!writeSectionContent(SHeader, *S, CBA))
337 return false;
George Rimareb394e92019-06-07 08:31:36 +0000338 } else if (auto S = dyn_cast<ELFYAML::MipsABIFlags>(Sec)) {
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000339 if (!writeSectionContent(SHeader, *S, CBA))
340 return false;
George Rimareb394e92019-06-07 08:31:36 +0000341 } else if (auto S = dyn_cast<ELFYAML::NoBitsSection>(Sec)) {
Simon Atanasyan5db02762015-07-03 23:00:54 +0000342 SHeader.sh_entsize = 0;
343 SHeader.sh_size = S->Size;
344 // SHT_NOBITS section does not have content
345 // so just to setup the section offset.
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000346 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
George Rimareb394e92019-06-07 08:31:36 +0000347 } else if (auto S = dyn_cast<ELFYAML::DynamicSection>(Sec)) {
James Hendersonfd997802019-02-25 11:02:24 +0000348 if (!writeSectionContent(SHeader, *S, CBA))
349 return false;
George Rimareb394e92019-06-07 08:31:36 +0000350 } else if (auto S = dyn_cast<ELFYAML::SymverSection>(Sec)) {
George Rimarda1b3ab2019-04-26 12:15:32 +0000351 if (!writeSectionContent(SHeader, *S, CBA))
352 return false;
George Rimareb394e92019-06-07 08:31:36 +0000353 } else if (auto S = dyn_cast<ELFYAML::VerneedSection>(Sec)) {
George Rimarda1b3ab2019-04-26 12:15:32 +0000354 if (!writeSectionContent(SHeader, *S, CBA))
355 return false;
George Rimareb394e92019-06-07 08:31:36 +0000356 } else if (auto S = dyn_cast<ELFYAML::VerdefSection>(Sec)) {
George Rimarda1b3ab2019-04-26 12:15:32 +0000357 if (!writeSectionContent(SHeader, *S, CBA))
358 return false;
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000359 } else
360 llvm_unreachable("Unknown section type");
George Rimar66296dc2019-06-05 13:16:53 +0000361 }
362
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000363 return true;
364}
365
George Rimar6da44ad2019-04-03 14:53:42 +0000366static size_t findFirstNonGlobal(ArrayRef<ELFYAML::Symbol> Symbols) {
367 for (size_t I = 0; I < Symbols.size(); ++I)
368 if (Symbols[I].Binding.value != ELF::STB_LOCAL)
369 return I;
370 return Symbols.size();
371}
372
George Rimar1e410072019-06-10 12:43:18 +0000373static uint64_t writeRawSectionData(raw_ostream &OS,
374 const ELFYAML::RawContentSection &RawSec) {
375 size_t ContentSize = 0;
376 if (RawSec.Content) {
377 RawSec.Content->writeAsBinary(OS);
378 ContentSize = RawSec.Content->binary_size();
379 }
380
381 if (!RawSec.Size)
382 return ContentSize;
383
384 OS.write_zeros(*RawSec.Size - ContentSize);
385 return *RawSec.Size;
386}
387
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000388template <class ELFT>
George Rimar30ea0c42019-06-20 14:44:48 +0000389static std::vector<typename ELFT::Sym>
390toELFSymbols(NameToIdxMap &SN2I, ArrayRef<ELFYAML::Symbol> Symbols,
391 const StringTableBuilder &Strtab) {
392 using Elf_Sym = typename ELFT::Sym;
393
394 std::vector<Elf_Sym> Ret;
395 Ret.resize(Symbols.size() + 1);
396
397 size_t I = 0;
398 for (const auto &Sym : Symbols) {
399 Elf_Sym &Symbol = Ret[++I];
400
401 // If NameIndex, which contains the name offset, is explicitly specified, we
402 // use it. This is useful for preparing broken objects. Otherwise, we add
403 // the specified Name to the string table builder to get its offset.
404 if (Sym.NameIndex)
405 Symbol.st_name = *Sym.NameIndex;
406 else if (!Sym.Name.empty())
George Rimar60dc5d42019-06-25 08:22:57 +0000407 Symbol.st_name = Strtab.getOffset(dropUniqueSuffix(Sym.Name));
George Rimar30ea0c42019-06-20 14:44:48 +0000408
409 Symbol.setBindingAndType(Sym.Binding, Sym.Type);
410 if (!Sym.Section.empty()) {
411 unsigned Index;
412 if (!SN2I.lookup(Sym.Section, Index)) {
413 WithColor::error() << "Unknown section referenced: '" << Sym.Section
414 << "' by YAML symbol " << Sym.Name << ".\n";
415 exit(1);
416 }
417 Symbol.st_shndx = Index;
418 } else if (Sym.Index) {
419 Symbol.st_shndx = *Sym.Index;
420 }
421 // else Symbol.st_shndex == SHN_UNDEF (== 0), since it was zero'd earlier.
422 Symbol.st_value = Sym.Value;
423 Symbol.st_other = Sym.Other;
424 Symbol.st_size = Sym.Size;
425 }
426
427 return Ret;
428}
429
430template <class ELFT>
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000431void ELFState<ELFT>::initSymtabSectionHeader(Elf_Shdr &SHeader,
Dave Lee67b49662017-11-16 18:10:15 +0000432 SymtabType STType,
George Rimar66296dc2019-06-05 13:16:53 +0000433 ContiguousBlobAccumulator &CBA,
434 ELFYAML::Section *YAMLSec) {
George Rimar1e410072019-06-10 12:43:18 +0000435
Dave Lee67b49662017-11-16 18:10:15 +0000436 bool IsStatic = STType == SymtabType::Static;
George Rimar1e410072019-06-10 12:43:18 +0000437 const auto &Symbols = IsStatic ? Doc.Symbols : Doc.DynamicSymbols;
438
439 ELFYAML::RawContentSection *RawSec =
440 dyn_cast_or_null<ELFYAML::RawContentSection>(YAMLSec);
441 if (RawSec && !Symbols.empty() && (RawSec->Content || RawSec->Size)) {
442 if (RawSec->Content)
443 WithColor::error() << "Cannot specify both `Content` and " +
444 (IsStatic ? Twine("`Symbols`")
445 : Twine("`DynamicSymbols`")) +
446 " for symbol table section '"
447 << RawSec->Name << "'.\n";
448 if (RawSec->Size)
449 WithColor::error() << "Cannot specify both `Size` and " +
450 (IsStatic ? Twine("`Symbols`")
451 : Twine("`DynamicSymbols`")) +
452 " for symbol table section '"
453 << RawSec->Name << "'.\n";
454 exit(1);
455 }
456
457 zero(SHeader);
Dave Lee67b49662017-11-16 18:10:15 +0000458 SHeader.sh_name = DotShStrtab.getOffset(IsStatic ? ".symtab" : ".dynsym");
George Rimar0aecaba2019-06-14 14:25:34 +0000459
460 if (YAMLSec)
461 SHeader.sh_type = YAMLSec->Type;
462 else
463 SHeader.sh_type = IsStatic ? ELF::SHT_SYMTAB : ELF::SHT_DYNSYM;
George Rimar379aa182019-06-10 11:38:06 +0000464
George Rimarffb3c722019-06-11 10:00:51 +0000465 if (RawSec && !RawSec->Link.empty()) {
466 // If the Link field is explicitly defined in the document,
467 // we should use it.
468 unsigned Index;
469 if (!convertSectionIndex(SN2I, RawSec->Name, RawSec->Link, Index))
470 return;
471 SHeader.sh_link = Index;
472 } else {
473 // When we describe the .dynsym section in the document explicitly, it is
474 // allowed to omit the "DynamicSymbols" tag. In this case .dynstr is not
475 // added implicitly and we should be able to leave the Link zeroed if
476 // .dynstr is not defined.
477 unsigned Link = 0;
478 if (IsStatic)
479 Link = SN2I.get(".strtab");
480 else
481 SN2I.lookup(".dynstr", Link);
482 SHeader.sh_link = Link;
483 }
George Rimar379aa182019-06-10 11:38:06 +0000484
George Rimarcfa1a622019-06-14 11:01:14 +0000485 if (YAMLSec && YAMLSec->Flags)
486 SHeader.sh_flags = *YAMLSec->Flags;
487 else if (!IsStatic)
488 SHeader.sh_flags = ELF::SHF_ALLOC;
George Rimarc1da1492019-04-26 12:45:54 +0000489
George Rimara7ba1a02019-03-01 10:18:16 +0000490 // If the symbol table section is explicitly described in the YAML
491 // then we should set the fields requested.
George Rimarb6e20932019-06-19 08:57:38 +0000492 SHeader.sh_info = (RawSec && RawSec->Info) ? (unsigned)(*RawSec->Info)
493 : findFirstNonGlobal(Symbols) + 1;
George Rimar66296dc2019-06-05 13:16:53 +0000494 SHeader.sh_entsize = (YAMLSec && YAMLSec->EntSize)
495 ? (uint64_t)(*YAMLSec->EntSize)
496 : sizeof(Elf_Sym);
497 SHeader.sh_addralign = YAMLSec ? (uint64_t)YAMLSec->AddressAlign : 8;
498 SHeader.sh_addr = YAMLSec ? (uint64_t)YAMLSec->Address : 0;
499
George Rimar1e410072019-06-10 12:43:18 +0000500 auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
501 if (RawSec && (RawSec->Content || RawSec->Size)) {
502 assert(Symbols.empty());
503 SHeader.sh_size = writeRawSectionData(OS, *RawSec);
504 return;
George Rimar6947acd2019-02-19 12:15:04 +0000505 }
George Rimar1e410072019-06-10 12:43:18 +0000506
George Rimar30ea0c42019-06-20 14:44:48 +0000507 std::vector<Elf_Sym> Syms =
508 toELFSymbols<ELFT>(SN2I, Symbols, IsStatic ? DotStrtab : DotDynstr);
George Rimar1e410072019-06-10 12:43:18 +0000509 writeArrayData(OS, makeArrayRef(Syms));
510 SHeader.sh_size = arrayDataSize(makeArrayRef(Syms));
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000511}
512
513template <class ELFT>
514void ELFState<ELFT>::initStrtabSectionHeader(Elf_Shdr &SHeader, StringRef Name,
515 StringTableBuilder &STB,
George Rimar66296dc2019-06-05 13:16:53 +0000516 ContiguousBlobAccumulator &CBA,
517 ELFYAML::Section *YAMLSec) {
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000518 zero(SHeader);
Hans Wennborg59f0cba2014-04-30 19:38:09 +0000519 SHeader.sh_name = DotShStrtab.getOffset(Name);
George Rimar0aecaba2019-06-14 14:25:34 +0000520 SHeader.sh_type = YAMLSec ? YAMLSec->Type : ELF::SHT_STRTAB;
George Rimar66296dc2019-06-05 13:16:53 +0000521 SHeader.sh_addralign = YAMLSec ? (uint64_t)YAMLSec->AddressAlign : 1;
522
523 ELFYAML::RawContentSection *RawSec =
524 dyn_cast_or_null<ELFYAML::RawContentSection>(YAMLSec);
George Rimar1e410072019-06-10 12:43:18 +0000525
526 auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
527 if (RawSec && (RawSec->Content || RawSec->Size)) {
528 SHeader.sh_size = writeRawSectionData(OS, *RawSec);
George Rimar66296dc2019-06-05 13:16:53 +0000529 } else {
George Rimar1e410072019-06-10 12:43:18 +0000530 STB.write(OS);
George Rimar66296dc2019-06-05 13:16:53 +0000531 SHeader.sh_size = STB.getSize();
532 }
533
534 if (YAMLSec && YAMLSec->EntSize)
535 SHeader.sh_entsize = *YAMLSec->EntSize;
George Rimar6947acd2019-02-19 12:15:04 +0000536
George Rimarb6e20932019-06-19 08:57:38 +0000537 if (RawSec && RawSec->Info)
538 SHeader.sh_info = *RawSec->Info;
539
George Rimarcfa1a622019-06-14 11:01:14 +0000540 if (YAMLSec && YAMLSec->Flags)
541 SHeader.sh_flags = *YAMLSec->Flags;
542 else if (Name == ".dynstr")
543 SHeader.sh_flags = ELF::SHF_ALLOC;
544
George Rimar43f62ff2019-06-14 11:13:32 +0000545 // If the section is explicitly described in the YAML
George Rimar6947acd2019-02-19 12:15:04 +0000546 // then we want to use its section address.
George Rimar43f62ff2019-06-14 11:13:32 +0000547 if (YAMLSec)
George Rimarcfa1a622019-06-14 11:01:14 +0000548 SHeader.sh_addr = YAMLSec->Address;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000549}
550
551template <class ELFT>
Petr Hosekeb04da32017-07-19 20:38:46 +0000552void ELFState<ELFT>::setProgramHeaderLayout(std::vector<Elf_Phdr> &PHeaders,
553 std::vector<Elf_Shdr> &SHeaders) {
554 uint32_t PhdrIdx = 0;
555 for (auto &YamlPhdr : Doc.ProgramHeaders) {
George Rimarf5345a32019-05-01 09:45:55 +0000556 Elf_Phdr &PHeader = PHeaders[PhdrIdx++];
557
Puyan Lotfia10f0162019-05-11 17:03:36 +0000558 std::vector<Elf_Shdr *> Sections;
559 for (const ELFYAML::SectionName &SecName : YamlPhdr.Sections) {
560 unsigned Index;
561 if (!SN2I.lookup(SecName.Section, Index)) {
562 WithColor::error() << "Unknown section referenced: '" << SecName.Section
563 << "' by program header.\n";
564 exit(1);
George Rimarf5345a32019-05-01 09:45:55 +0000565 }
566 Sections.push_back(&SHeaders[Index]);
567 }
Petr Hosekeb04da32017-07-19 20:38:46 +0000568
James Hendersonb10f48b2019-03-15 10:35:27 +0000569 if (YamlPhdr.Offset) {
570 PHeader.p_offset = *YamlPhdr.Offset;
571 } else {
572 if (YamlPhdr.Sections.size())
573 PHeader.p_offset = UINT32_MAX;
Petr Hosekeb04da32017-07-19 20:38:46 +0000574 else
James Hendersonb10f48b2019-03-15 10:35:27 +0000575 PHeader.p_offset = 0;
576
577 // Find the minimum offset for the program header.
George Rimarf5345a32019-05-01 09:45:55 +0000578 for (Elf_Shdr *SHeader : Sections)
579 PHeader.p_offset = std::min(PHeader.p_offset, SHeader->sh_offset);
Petr Hosekeb04da32017-07-19 20:38:46 +0000580 }
581
James Hendersonb10f48b2019-03-15 10:35:27 +0000582 // Find the maximum offset of the end of a section in order to set p_filesz,
583 // if not set explicitly.
584 if (YamlPhdr.FileSize) {
585 PHeader.p_filesz = *YamlPhdr.FileSize;
586 } else {
587 PHeader.p_filesz = 0;
George Rimarf5345a32019-05-01 09:45:55 +0000588 for (Elf_Shdr *SHeader : Sections) {
James Hendersonb10f48b2019-03-15 10:35:27 +0000589 uint64_t EndOfSection;
George Rimarf5345a32019-05-01 09:45:55 +0000590 if (SHeader->sh_type == llvm::ELF::SHT_NOBITS)
591 EndOfSection = SHeader->sh_offset;
James Hendersonb10f48b2019-03-15 10:35:27 +0000592 else
George Rimarf5345a32019-05-01 09:45:55 +0000593 EndOfSection = SHeader->sh_offset + SHeader->sh_size;
James Hendersonb10f48b2019-03-15 10:35:27 +0000594 uint64_t EndOfSegment = PHeader.p_offset + PHeader.p_filesz;
595 EndOfSegment = std::max(EndOfSegment, EndOfSection);
596 PHeader.p_filesz = EndOfSegment - PHeader.p_offset;
597 }
598 }
599
600 // If not set explicitly, find the memory size by adding the size of
601 // sections at the end of the segment. These should be empty (size of zero)
602 // and NOBITS sections.
603 if (YamlPhdr.MemSize) {
604 PHeader.p_memsz = *YamlPhdr.MemSize;
605 } else {
606 PHeader.p_memsz = PHeader.p_filesz;
George Rimarf5345a32019-05-01 09:45:55 +0000607 for (Elf_Shdr *SHeader : Sections)
608 if (SHeader->sh_offset == PHeader.p_offset + PHeader.p_filesz)
609 PHeader.p_memsz += SHeader->sh_size;
Petr Hosekeb04da32017-07-19 20:38:46 +0000610 }
611
612 // Set the alignment of the segment to be the same as the maximum alignment
Jake Ehrlich03aeeb092017-11-01 23:14:48 +0000613 // of the sections with the same offset so that by default the segment
Petr Hosekeb04da32017-07-19 20:38:46 +0000614 // has a valid and sensible alignment.
Jake Ehrlich03aeeb092017-11-01 23:14:48 +0000615 if (YamlPhdr.Align) {
616 PHeader.p_align = *YamlPhdr.Align;
617 } else {
618 PHeader.p_align = 1;
George Rimarf5345a32019-05-01 09:45:55 +0000619 for (Elf_Shdr *SHeader : Sections)
620 if (SHeader->sh_offset == PHeader.p_offset)
621 PHeader.p_align = std::max(PHeader.p_align, SHeader->sh_addralign);
Petr Hosekeb04da32017-07-19 20:38:46 +0000622 }
623 }
624}
625
626template <class ELFT>
George Rimarda1b3ab2019-04-26 12:15:32 +0000627bool ELFState<ELFT>::writeSectionContent(
George Rimarb49e1922019-04-24 13:02:15 +0000628 Elf_Shdr &SHeader, const ELFYAML::RawContentSection &Section,
629 ContiguousBlobAccumulator &CBA) {
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000630 raw_ostream &OS =
631 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
George Rimar1e410072019-06-10 12:43:18 +0000632 SHeader.sh_size = writeRawSectionData(OS, Section);
George Rimarb49e1922019-04-24 13:02:15 +0000633
George Rimar65a68282018-08-07 08:11:38 +0000634 if (Section.EntSize)
635 SHeader.sh_entsize = *Section.EntSize;
636 else if (Section.Type == llvm::ELF::SHT_RELR)
Jake Ehrlich0f440d82018-06-28 21:07:34 +0000637 SHeader.sh_entsize = sizeof(Elf_Relr);
638 else
639 SHeader.sh_entsize = 0;
George Rimarb6e20932019-06-19 08:57:38 +0000640
641 if (Section.Info)
642 SHeader.sh_info = *Section.Info;
643
George Rimarda1b3ab2019-04-26 12:15:32 +0000644 return true;
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000645}
646
Simon Atanasyan5d19c672015-01-25 13:29:25 +0000647static bool isMips64EL(const ELFYAML::Object &Doc) {
648 return Doc.Header.Machine == ELFYAML::ELF_EM(llvm::ELF::EM_MIPS) &&
649 Doc.Header.Class == ELFYAML::ELF_ELFCLASS(ELF::ELFCLASS64) &&
650 Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB);
651}
652
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000653template <class ELFT>
654bool
655ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
656 const ELFYAML::RelocationSection &Section,
657 ContiguousBlobAccumulator &CBA) {
Simon Atanasyan8eb9d1b2015-05-08 07:05:04 +0000658 assert((Section.Type == llvm::ELF::SHT_REL ||
659 Section.Type == llvm::ELF::SHT_RELA) &&
660 "Section type is not SHT_REL nor SHT_RELA");
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000661
662 bool IsRela = Section.Type == llvm::ELF::SHT_RELA;
663 SHeader.sh_entsize = IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
664 SHeader.sh_size = SHeader.sh_entsize * Section.Relocations.size();
665
George Rimarda1b3ab2019-04-26 12:15:32 +0000666 // For relocation section set link to .symtab by default.
667 if (Section.Link.empty())
George Rimard71017b2019-06-10 09:57:29 +0000668 SHeader.sh_link = SN2I.get(".symtab");
George Rimarda1b3ab2019-04-26 12:15:32 +0000669
670 unsigned Index = 0;
671 if (!Section.RelocatableSec.empty() &&
672 !convertSectionIndex(SN2I, Section.Name, Section.RelocatableSec, Index))
673 return false;
674 SHeader.sh_info = Index;
675
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000676 auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000677
678 for (const auto &Rel : Section.Relocations) {
George Rimar09746882019-05-07 12:10:51 +0000679 unsigned SymIdx = 0;
680 // If a relocation references a symbol, try to look one up in the symbol
681 // table. If it is not there, treat the value as a symbol index.
Puyan Lotfia10f0162019-05-11 17:03:36 +0000682 if (Rel.Symbol && !SymN2I.lookup(*Rel.Symbol, SymIdx) &&
George Rimar09746882019-05-07 12:10:51 +0000683 !to_integer(*Rel.Symbol, SymIdx)) {
684 WithColor::error() << "Unknown symbol referenced: '" << *Rel.Symbol
685 << "' at YAML section '" << Section.Name << "'.\n";
James Henderson9bc817a2019-03-12 17:00:25 +0000686 return false;
687 }
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000688
689 if (IsRela) {
690 Elf_Rela REntry;
691 zero(REntry);
692 REntry.r_offset = Rel.Offset;
693 REntry.r_addend = Rel.Addend;
Simon Atanasyan5d19c672015-01-25 13:29:25 +0000694 REntry.setSymbolAndType(SymIdx, Rel.Type, isMips64EL(Doc));
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000695 OS.write((const char *)&REntry, sizeof(REntry));
696 } else {
697 Elf_Rel REntry;
698 zero(REntry);
699 REntry.r_offset = Rel.Offset;
Simon Atanasyan5d19c672015-01-25 13:29:25 +0000700 REntry.setSymbolAndType(SymIdx, Rel.Type, isMips64EL(Doc));
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000701 OS.write((const char *)&REntry, sizeof(REntry));
702 }
703 }
704 return true;
705}
706
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000707template <class ELFT>
708bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
709 const ELFYAML::Group &Section,
710 ContiguousBlobAccumulator &CBA) {
Simon Atanasyan8eb9d1b2015-05-08 07:05:04 +0000711 assert(Section.Type == llvm::ELF::SHT_GROUP &&
712 "Section type is not SHT_GROUP");
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000713
George Rimard063c7d2019-02-20 13:58:43 +0000714 SHeader.sh_entsize = 4;
George Rimar09746882019-05-07 12:10:51 +0000715 SHeader.sh_size = SHeader.sh_entsize * Section.Members.size();
716
Puyan Lotfia10f0162019-05-11 17:03:36 +0000717 unsigned SymIdx;
718 if (!SymN2I.lookup(Section.Signature, SymIdx) &&
719 !to_integer(Section.Signature, SymIdx)) {
720 WithColor::error() << "Unknown symbol referenced: '" << Section.Signature
721 << "' at YAML section '" << Section.Name << "'.\n";
George Rimarda1b3ab2019-04-26 12:15:32 +0000722 return false;
723 }
724 SHeader.sh_info = SymIdx;
725
George Rimard063c7d2019-02-20 13:58:43 +0000726 raw_ostream &OS =
727 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000728
George Rimarfb7780a2019-04-26 12:20:51 +0000729 for (const ELFYAML::SectionOrType &Member : Section.Members) {
730 unsigned int SectionIndex = 0;
731 if (Member.sectionNameOrType == "GRP_COMDAT")
732 SectionIndex = llvm::ELF::GRP_COMDAT;
733 else if (!convertSectionIndex(SN2I, Section.Name, Member.sectionNameOrType,
734 SectionIndex))
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000735 return false;
George Rimarfb7780a2019-04-26 12:20:51 +0000736 support::endian::write<uint32_t>(OS, SectionIndex, ELFT::TargetEndianness);
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000737 }
738 return true;
739}
740
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000741template <class ELFT>
742bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
George Rimar646af082019-02-19 15:29:07 +0000743 const ELFYAML::SymverSection &Section,
744 ContiguousBlobAccumulator &CBA) {
George Rimar646af082019-02-19 15:29:07 +0000745 raw_ostream &OS =
746 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
George Rimardac37fb2019-02-20 14:01:02 +0000747 for (uint16_t Version : Section.Entries)
748 support::endian::write<uint16_t>(OS, Version, ELFT::TargetEndianness);
George Rimar646af082019-02-19 15:29:07 +0000749
George Rimard063c7d2019-02-20 13:58:43 +0000750 SHeader.sh_entsize = 2;
751 SHeader.sh_size = Section.Entries.size() * SHeader.sh_entsize;
George Rimar646af082019-02-19 15:29:07 +0000752 return true;
753}
754
755template <class ELFT>
756bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
George Rimar623ae722019-02-21 12:21:43 +0000757 const ELFYAML::VerdefSection &Section,
758 ContiguousBlobAccumulator &CBA) {
759 typedef typename ELFT::Verdef Elf_Verdef;
760 typedef typename ELFT::Verdaux Elf_Verdaux;
761 raw_ostream &OS =
762 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
763
764 uint64_t AuxCnt = 0;
765 for (size_t I = 0; I < Section.Entries.size(); ++I) {
766 const ELFYAML::VerdefEntry &E = Section.Entries[I];
767
768 Elf_Verdef VerDef;
769 VerDef.vd_version = E.Version;
770 VerDef.vd_flags = E.Flags;
771 VerDef.vd_ndx = E.VersionNdx;
772 VerDef.vd_hash = E.Hash;
773 VerDef.vd_aux = sizeof(Elf_Verdef);
774 VerDef.vd_cnt = E.VerNames.size();
775 if (I == Section.Entries.size() - 1)
776 VerDef.vd_next = 0;
777 else
778 VerDef.vd_next =
779 sizeof(Elf_Verdef) + E.VerNames.size() * sizeof(Elf_Verdaux);
780 OS.write((const char *)&VerDef, sizeof(Elf_Verdef));
781
782 for (size_t J = 0; J < E.VerNames.size(); ++J, ++AuxCnt) {
783 Elf_Verdaux VernAux;
784 VernAux.vda_name = DotDynstr.getOffset(E.VerNames[J]);
785 if (J == E.VerNames.size() - 1)
786 VernAux.vda_next = 0;
787 else
788 VernAux.vda_next = sizeof(Elf_Verdaux);
789 OS.write((const char *)&VernAux, sizeof(Elf_Verdaux));
790 }
791 }
792
793 SHeader.sh_size = Section.Entries.size() * sizeof(Elf_Verdef) +
794 AuxCnt * sizeof(Elf_Verdaux);
795 SHeader.sh_info = Section.Info;
796
797 return true;
798}
799
800template <class ELFT>
801bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
George Rimar0621b792019-02-19 14:53:48 +0000802 const ELFYAML::VerneedSection &Section,
803 ContiguousBlobAccumulator &CBA) {
George Rimarda1b3ab2019-04-26 12:15:32 +0000804 typedef typename ELFT::Verneed Elf_Verneed;
805 typedef typename ELFT::Vernaux Elf_Vernaux;
George Rimar0621b792019-02-19 14:53:48 +0000806
George Rimarda1b3ab2019-04-26 12:15:32 +0000807 auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
George Rimar0621b792019-02-19 14:53:48 +0000808
George Rimarda1b3ab2019-04-26 12:15:32 +0000809 uint64_t AuxCnt = 0;
810 for (size_t I = 0; I < Section.VerneedV.size(); ++I) {
811 const ELFYAML::VerneedEntry &VE = Section.VerneedV[I];
George Rimar0621b792019-02-19 14:53:48 +0000812
George Rimarda1b3ab2019-04-26 12:15:32 +0000813 Elf_Verneed VerNeed;
814 VerNeed.vn_version = VE.Version;
815 VerNeed.vn_file = DotDynstr.getOffset(VE.File);
816 if (I == Section.VerneedV.size() - 1)
817 VerNeed.vn_next = 0;
818 else
819 VerNeed.vn_next =
820 sizeof(Elf_Verneed) + VE.AuxV.size() * sizeof(Elf_Vernaux);
821 VerNeed.vn_cnt = VE.AuxV.size();
822 VerNeed.vn_aux = sizeof(Elf_Verneed);
823 OS.write((const char *)&VerNeed, sizeof(Elf_Verneed));
George Rimar0621b792019-02-19 14:53:48 +0000824
George Rimarda1b3ab2019-04-26 12:15:32 +0000825 for (size_t J = 0; J < VE.AuxV.size(); ++J, ++AuxCnt) {
826 const ELFYAML::VernauxEntry &VAuxE = VE.AuxV[J];
George Rimar0621b792019-02-19 14:53:48 +0000827
George Rimarda1b3ab2019-04-26 12:15:32 +0000828 Elf_Vernaux VernAux;
829 VernAux.vna_hash = VAuxE.Hash;
830 VernAux.vna_flags = VAuxE.Flags;
831 VernAux.vna_other = VAuxE.Other;
832 VernAux.vna_name = DotDynstr.getOffset(VAuxE.Name);
833 if (J == VE.AuxV.size() - 1)
834 VernAux.vna_next = 0;
835 else
836 VernAux.vna_next = sizeof(Elf_Vernaux);
837 OS.write((const char *)&VernAux, sizeof(Elf_Vernaux));
838 }
839 }
George Rimar0621b792019-02-19 14:53:48 +0000840
George Rimarda1b3ab2019-04-26 12:15:32 +0000841 SHeader.sh_size = Section.VerneedV.size() * sizeof(Elf_Verneed) +
842 AuxCnt * sizeof(Elf_Vernaux);
843 SHeader.sh_info = Section.Info;
George Rimar0621b792019-02-19 14:53:48 +0000844
George Rimarda1b3ab2019-04-26 12:15:32 +0000845 return true;
George Rimar0621b792019-02-19 14:53:48 +0000846}
847
848template <class ELFT>
849bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000850 const ELFYAML::MipsABIFlags &Section,
851 ContiguousBlobAccumulator &CBA) {
Simon Atanasyan8eb9d1b2015-05-08 07:05:04 +0000852 assert(Section.Type == llvm::ELF::SHT_MIPS_ABIFLAGS &&
853 "Section type is not SHT_MIPS_ABIFLAGS");
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000854
855 object::Elf_Mips_ABIFlags<ELFT> Flags;
856 zero(Flags);
857 SHeader.sh_entsize = sizeof(Flags);
858 SHeader.sh_size = SHeader.sh_entsize;
859
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000860 auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000861 Flags.version = Section.Version;
862 Flags.isa_level = Section.ISALevel;
863 Flags.isa_rev = Section.ISARevision;
864 Flags.gpr_size = Section.GPRSize;
865 Flags.cpr1_size = Section.CPR1Size;
866 Flags.cpr2_size = Section.CPR2Size;
867 Flags.fp_abi = Section.FpABI;
868 Flags.isa_ext = Section.ISAExtension;
869 Flags.ases = Section.ASEs;
870 Flags.flags1 = Section.Flags1;
871 Flags.flags2 = Section.Flags2;
872 OS.write((const char *)&Flags, sizeof(Flags));
873
874 return true;
875}
876
George Rimar0e7ed912019-02-09 11:34:28 +0000877template <class ELFT>
James Hendersonfd997802019-02-25 11:02:24 +0000878bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
George Rimar0e7ed912019-02-09 11:34:28 +0000879 const ELFYAML::DynamicSection &Section,
880 ContiguousBlobAccumulator &CBA) {
George Rimard063c7d2019-02-20 13:58:43 +0000881 typedef typename ELFT::uint uintX_t;
882
George Rimar0e7ed912019-02-09 11:34:28 +0000883 assert(Section.Type == llvm::ELF::SHT_DYNAMIC &&
884 "Section type is not SHT_DYNAMIC");
885
James Hendersonfd997802019-02-25 11:02:24 +0000886 if (!Section.Entries.empty() && Section.Content) {
887 WithColor::error()
888 << "Cannot specify both raw content and explicit entries "
889 "for dynamic section '"
890 << Section.Name << "'.\n";
891 return false;
892 }
893
894 if (Section.Content)
895 SHeader.sh_size = Section.Content->binary_size();
896 else
897 SHeader.sh_size = 2 * sizeof(uintX_t) * Section.Entries.size();
George Rimar0e7ed912019-02-09 11:34:28 +0000898 if (Section.EntSize)
899 SHeader.sh_entsize = *Section.EntSize;
900 else
901 SHeader.sh_entsize = sizeof(Elf_Dyn);
902
George Rimard063c7d2019-02-20 13:58:43 +0000903 raw_ostream &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
George Rimar0e7ed912019-02-09 11:34:28 +0000904 for (const ELFYAML::DynamicEntry &DE : Section.Entries) {
George Rimard063c7d2019-02-20 13:58:43 +0000905 support::endian::write<uintX_t>(OS, DE.Tag, ELFT::TargetEndianness);
906 support::endian::write<uintX_t>(OS, DE.Val, ELFT::TargetEndianness);
George Rimar0e7ed912019-02-09 11:34:28 +0000907 }
James Hendersonfd997802019-02-25 11:02:24 +0000908 if (Section.Content)
909 Section.Content->writeAsBinary(OS);
910
911 return true;
George Rimar0e7ed912019-02-09 11:34:28 +0000912}
913
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000914template <class ELFT> bool ELFState<ELFT>::buildSectionIndex() {
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000915 for (unsigned i = 0, e = Doc.Sections.size(); i != e; ++i) {
George Rimar09746882019-05-07 12:10:51 +0000916 StringRef Name = Doc.Sections[i]->Name;
George Rimar60dc5d42019-06-25 08:22:57 +0000917 DotShStrtab.add(dropUniqueSuffix(Name));
George Rimar09746882019-05-07 12:10:51 +0000918 // "+ 1" to take into account the SHT_NULL entry.
Puyan Lotfia10f0162019-05-11 17:03:36 +0000919 if (!SN2I.addName(Name, i + 1)) {
George Rimar09746882019-05-07 12:10:51 +0000920 WithColor::error() << "Repeated section name: '" << Name
921 << "' at YAML section number " << i << ".\n";
922 return false;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000923 }
Sean Silvaaff51252013-06-21 00:27:50 +0000924 }
Dave Lee17307d92017-11-09 14:53:43 +0000925
926 auto SecNo = 1 + Doc.Sections.size();
927 // Add special sections after input sections, if necessary.
George Rimar5fcdebe2019-04-26 13:09:11 +0000928 for (StringRef Name : implicitSectionNames())
George Rimar36621272019-05-02 19:28:04 +0000929 if (SN2I.addName(Name, SecNo)) {
Dave Lee17307d92017-11-09 14:53:43 +0000930 // Account for this section, since it wasn't in the Doc
931 ++SecNo;
932 DotShStrtab.add(Name);
933 }
934
935 DotShStrtab.finalize();
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000936 return true;
Sean Silva6b083882013-06-18 23:14:03 +0000937}
938
Sean Silvaf99309c2013-06-10 23:44:15 +0000939template <class ELFT>
George Rimar6da44ad2019-04-03 14:53:42 +0000940bool ELFState<ELFT>::buildSymbolIndex(ArrayRef<ELFYAML::Symbol> Symbols) {
941 bool GlobalSymbolSeen = false;
George Rimar33e498b2019-03-11 16:10:02 +0000942 std::size_t I = 0;
George Rimar6da44ad2019-04-03 14:53:42 +0000943 for (const auto &Sym : Symbols) {
944 ++I;
945
946 StringRef Name = Sym.Name;
947 if (Sym.Binding.value == ELF::STB_LOCAL && GlobalSymbolSeen) {
948 WithColor::error() << "Local symbol '" + Name +
949 "' after global in Symbols list.\n";
950 return false;
951 }
George Rimar09746882019-05-07 12:10:51 +0000952 if (Sym.Binding.value != ELF::STB_LOCAL)
953 GlobalSymbolSeen = true;
954
Puyan Lotfia10f0162019-05-11 17:03:36 +0000955 if (!Name.empty() && !SymN2I.addName(Name, I)) {
George Rimar09746882019-05-07 12:10:51 +0000956 WithColor::error() << "Repeated symbol name: '" << Name << "'.\n";
957 return false;
958 }
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000959 }
960 return true;
961}
962
George Rimar0621b792019-02-19 14:53:48 +0000963template <class ELFT> void ELFState<ELFT>::finalizeStrings() {
George Rimar0621b792019-02-19 14:53:48 +0000964 // Add the regular symbol names to .strtab section.
George Rimar6da44ad2019-04-03 14:53:42 +0000965 for (const ELFYAML::Symbol &Sym : Doc.Symbols)
George Rimar60dc5d42019-06-25 08:22:57 +0000966 DotStrtab.add(dropUniqueSuffix(Sym.Name));
George Rimar0621b792019-02-19 14:53:48 +0000967 DotStrtab.finalize();
968
George Rimar0621b792019-02-19 14:53:48 +0000969 // Add the dynamic symbol names to .dynstr section.
George Rimar6da44ad2019-04-03 14:53:42 +0000970 for (const ELFYAML::Symbol &Sym : Doc.DynamicSymbols)
George Rimar60dc5d42019-06-25 08:22:57 +0000971 DotDynstr.add(dropUniqueSuffix(Sym.Name));
George Rimar0621b792019-02-19 14:53:48 +0000972
George Rimar623ae722019-02-21 12:21:43 +0000973 // SHT_GNU_verdef and SHT_GNU_verneed sections might also
974 // add strings to .dynstr section.
George Rimar0621b792019-02-19 14:53:48 +0000975 for (const std::unique_ptr<ELFYAML::Section> &Sec : Doc.Sections) {
George Rimar623ae722019-02-21 12:21:43 +0000976 if (auto VerNeed = dyn_cast<ELFYAML::VerneedSection>(Sec.get())) {
977 for (const ELFYAML::VerneedEntry &VE : VerNeed->VerneedV) {
978 DotDynstr.add(VE.File);
979 for (const ELFYAML::VernauxEntry &Aux : VE.AuxV)
980 DotDynstr.add(Aux.Name);
981 }
982 } else if (auto VerDef = dyn_cast<ELFYAML::VerdefSection>(Sec.get())) {
983 for (const ELFYAML::VerdefEntry &E : VerDef->Entries)
984 for (StringRef Name : E.VerNames)
985 DotDynstr.add(Name);
George Rimar0621b792019-02-19 14:53:48 +0000986 }
987 }
988
989 DotDynstr.finalize();
990}
991
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000992template <class ELFT>
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000993int ELFState<ELFT>::writeELF(raw_ostream &OS, const ELFYAML::Object &Doc) {
Simon Atanasyan220c54a2014-04-02 16:34:40 +0000994 ELFState<ELFT> State(Doc);
George Rimar0621b792019-02-19 14:53:48 +0000995
996 // Finalize .strtab and .dynstr sections. We do that early because want to
997 // finalize the string table builders before writing the content of the
998 // sections that might want to use them.
999 State.finalizeStrings();
1000
Simon Atanasyan220c54a2014-04-02 16:34:40 +00001001 if (!State.buildSectionIndex())
1002 return 1;
1003
George Rimar33e498b2019-03-11 16:10:02 +00001004 if (!State.buildSymbolIndex(Doc.Symbols))
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +00001005 return 1;
1006
Sean Silva38205932013-06-13 22:19:48 +00001007 Elf_Ehdr Header;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +00001008 State.initELFHeader(Header);
Sean Silvaf99309c2013-06-10 23:44:15 +00001009
Sean Silva38205932013-06-13 22:19:48 +00001010 // TODO: Flesh out section header support.
Petr Hosekeb04da32017-07-19 20:38:46 +00001011
1012 std::vector<Elf_Phdr> PHeaders;
1013 State.initProgramHeaders(PHeaders);
Sean Silva38205932013-06-13 22:19:48 +00001014
Sean Silva08a75ae2013-06-20 19:11:44 +00001015 // XXX: This offset is tightly coupled with the order that we write
1016 // things to `OS`.
Petr Hosekeb04da32017-07-19 20:38:46 +00001017 const size_t SectionContentBeginOffset = Header.e_ehsize +
1018 Header.e_phentsize * Header.e_phnum +
1019 Header.e_shentsize * Header.e_shnum;
Sean Silva08a75ae2013-06-20 19:11:44 +00001020 ContiguousBlobAccumulator CBA(SectionContentBeginOffset);
Sean Silvac1c290b2013-06-20 20:59:34 +00001021
Sean Silva38205932013-06-13 22:19:48 +00001022 std::vector<Elf_Shdr> SHeaders;
George Rimar66296dc2019-06-05 13:16:53 +00001023 if (!State.initSectionHeaders(State, SHeaders, CBA))
Simon Atanasyan3ee21b02014-04-02 16:34:54 +00001024 return 1;
Sean Silva38205932013-06-13 22:19:48 +00001025
Petr Hosekeb04da32017-07-19 20:38:46 +00001026 // Now we can decide segment offsets
1027 State.setProgramHeaderLayout(PHeaders, SHeaders);
1028
Sean Silvaf99309c2013-06-10 23:44:15 +00001029 OS.write((const char *)&Header, sizeof(Header));
Petr Hosekeb04da32017-07-19 20:38:46 +00001030 writeArrayData(OS, makeArrayRef(PHeaders));
Will Dietz0b48c732013-10-12 21:29:16 +00001031 writeArrayData(OS, makeArrayRef(SHeaders));
Sean Silva46dffff2013-06-13 22:20:01 +00001032 CBA.writeBlobToStream(OS);
Sean Silva415d93f2013-06-17 20:14:59 +00001033 return 0;
Sean Silvaf99309c2013-06-10 23:44:15 +00001034}
1035
Xing GUObac78642018-12-07 11:04:22 +00001036template <class ELFT>
George Rimar5fcdebe2019-04-26 13:09:11 +00001037std::vector<StringRef> ELFState<ELFT>::implicitSectionNames() const {
George Rimar6da44ad2019-04-03 14:53:42 +00001038 if (Doc.DynamicSymbols.empty())
Dave Lee67b49662017-11-16 18:10:15 +00001039 return {".symtab", ".strtab", ".shstrtab"};
1040 return {".symtab", ".strtab", ".shstrtab", ".dynsym", ".dynstr"};
1041}
1042
Chris Bieneman8ff0c112016-06-27 19:53:53 +00001043int yaml2elf(llvm::ELFYAML::Object &Doc, raw_ostream &Out) {
George Rimarbc4d3c42019-04-29 12:25:01 +00001044 bool IsLE = Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB);
1045 bool Is64Bit = Doc.Header.Class == ELFYAML::ELF_ELFCLASS(ELF::ELFCLASS64);
1046 if (Is64Bit) {
1047 if (IsLE)
Rui Ueyama1b31eb92018-01-12 01:40:32 +00001048 return ELFState<object::ELF64LE>::writeELF(Out, Doc);
George Rimarbc4d3c42019-04-29 12:25:01 +00001049 return ELFState<object::ELF64BE>::writeELF(Out, Doc);
Sean Silvaf99309c2013-06-10 23:44:15 +00001050 }
George Rimarbc4d3c42019-04-29 12:25:01 +00001051 if (IsLE)
1052 return ELFState<object::ELF32LE>::writeELF(Out, Doc);
1053 return ELFState<object::ELF32BE>::writeELF(Out, Doc);
Sean Silvaf99309c2013-06-10 23:44:15 +00001054}