blob: d863027afb9e9db86f266090b6071139de45d194 [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 Rimar13a364e2019-07-22 12:01:52 +000020#include "llvm/ADT/StringSet.h"
George Rimard063c7d2019-02-20 13:58:43 +000021#include "llvm/Support/EndianStream.h"
Sean Silvaf99309c2013-06-10 23:44:15 +000022#include "llvm/Support/MemoryBuffer.h"
Jonas Devlieghere2cd41eb2018-04-21 21:11:59 +000023#include "llvm/Support/WithColor.h"
Sean Silvaf99309c2013-06-10 23:44:15 +000024#include "llvm/Support/YAMLTraits.h"
25#include "llvm/Support/raw_ostream.h"
26
27using namespace llvm;
28
Sean Silva46dffff2013-06-13 22:20:01 +000029// This class is used to build up a contiguous binary blob while keeping
30// track of an offset in the output (which notionally begins at
31// `InitialOffset`).
Sean Silva2a74f702013-06-15 00:31:46 +000032namespace {
Sean Silva46dffff2013-06-13 22:20:01 +000033class ContiguousBlobAccumulator {
34 const uint64_t InitialOffset;
Sean Silvabd3bc692013-06-20 19:11:41 +000035 SmallVector<char, 128> Buf;
Sean Silva46dffff2013-06-13 22:20:01 +000036 raw_svector_ostream OS;
37
Sean Silvad93323f2013-06-22 00:47:43 +000038 /// \returns The new offset.
39 uint64_t padToAlignment(unsigned Align) {
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +000040 if (Align == 0)
41 Align = 1;
Sean Silvad93323f2013-06-22 00:47:43 +000042 uint64_t CurrentOffset = InitialOffset + OS.tell();
Rui Ueyamada00f2f2016-01-14 21:06:47 +000043 uint64_t AlignedOffset = alignTo(CurrentOffset, Align);
George Rimarbd8bfd32019-04-29 12:05:53 +000044 OS.write_zeros(AlignedOffset - CurrentOffset);
Sean Silvad93323f2013-06-22 00:47:43 +000045 return AlignedOffset; // == CurrentOffset;
46 }
47
Sean Silva46dffff2013-06-13 22:20:01 +000048public:
Sean Silvabd3bc692013-06-20 19:11:41 +000049 ContiguousBlobAccumulator(uint64_t InitialOffset_)
50 : InitialOffset(InitialOffset_), Buf(), OS(Buf) {}
Sean Silvad93323f2013-06-22 00:47:43 +000051 template <class Integer>
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +000052 raw_ostream &getOSAndAlignedOffset(Integer &Offset, unsigned Align) {
Sean Silvad93323f2013-06-22 00:47:43 +000053 Offset = padToAlignment(Align);
54 return OS;
55 }
Sean Silva46dffff2013-06-13 22:20:01 +000056 void writeBlobToStream(raw_ostream &Out) { Out << OS.str(); }
57};
Sean Silva2a74f702013-06-15 00:31:46 +000058} // end anonymous namespace
Sean Silva46dffff2013-06-13 22:20:01 +000059
Simon Atanasyan35babf92014-04-06 09:02:55 +000060// Used to keep track of section and symbol names, so that in the YAML file
George Rimar09746882019-05-07 12:10:51 +000061// sections and symbols can be referenced by name instead of by index.
62namespace {
63class NameToIdxMap {
Puyan Lotfia10f0162019-05-11 17:03:36 +000064 StringMap<unsigned> Map;
65
George Rimar09746882019-05-07 12:10:51 +000066public:
Puyan Lotfia10f0162019-05-11 17:03:36 +000067 /// \Returns false if name is already present in the map.
68 bool addName(StringRef Name, unsigned Ndx) {
69 return Map.insert({Name, Ndx}).second;
George Rimar09746882019-05-07 12:10:51 +000070 }
Puyan Lotfia10f0162019-05-11 17:03:36 +000071 /// \Returns false if name is not present in the map.
George Rimar09746882019-05-07 12:10:51 +000072 bool lookup(StringRef Name, unsigned &Idx) const {
Puyan Lotfia10f0162019-05-11 17:03:36 +000073 auto I = Map.find(Name);
George Rimar09746882019-05-07 12:10:51 +000074 if (I == Map.end())
Puyan Lotfia10f0162019-05-11 17:03:36 +000075 return false;
George Rimar09746882019-05-07 12:10:51 +000076 Idx = I->getValue();
Puyan Lotfia10f0162019-05-11 17:03:36 +000077 return true;
George Rimar09746882019-05-07 12:10:51 +000078 }
Puyan Lotfia10f0162019-05-11 17:03:36 +000079 /// Asserts if name is not present in the map.
George Rimar09746882019-05-07 12:10:51 +000080 unsigned get(StringRef Name) const {
Puyan Lotfia10f0162019-05-11 17:03:36 +000081 unsigned Idx;
82 if (lookup(Name, Idx))
83 return Idx;
84 assert(false && "Expected section not found in index");
85 return 0;
George Rimar09746882019-05-07 12:10:51 +000086 }
87 unsigned size() const { return Map.size(); }
88};
Sean Silva2a74f702013-06-15 00:31:46 +000089} // end anonymous namespace
Sean Silvaa6423eb2013-06-15 00:25:26 +000090
Sean Silva38205932013-06-13 22:19:48 +000091template <class T>
Will Dietz0b48c732013-10-12 21:29:16 +000092static size_t arrayDataSize(ArrayRef<T> A) {
93 return A.size() * sizeof(T);
Sean Silva38205932013-06-13 22:19:48 +000094}
95
96template <class T>
Will Dietz0b48c732013-10-12 21:29:16 +000097static void writeArrayData(raw_ostream &OS, ArrayRef<T> A) {
98 OS.write((const char *)A.data(), arrayDataSize(A));
Sean Silva38205932013-06-13 22:19:48 +000099}
100
101template <class T>
102static void zero(T &Obj) {
103 memset(&Obj, 0, sizeof(Obj));
104}
105
Sean Silva08a75ae2013-06-20 19:11:44 +0000106namespace {
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000107/// "Single point of truth" for the ELF file construction.
Sean Silva08a75ae2013-06-20 19:11:44 +0000108/// TODO: This class still has a ways to go before it is truly a "single
109/// point of truth".
110template <class ELFT>
111class ELFState {
Rui Ueyama478d6352018-01-12 02:28:31 +0000112 typedef typename ELFT::Ehdr Elf_Ehdr;
113 typedef typename ELFT::Phdr Elf_Phdr;
114 typedef typename ELFT::Shdr Elf_Shdr;
115 typedef typename ELFT::Sym Elf_Sym;
116 typedef typename ELFT::Rel Elf_Rel;
117 typedef typename ELFT::Rela Elf_Rela;
Jake Ehrlich0f440d82018-06-28 21:07:34 +0000118 typedef typename ELFT::Relr Elf_Relr;
Paul Semel1dbbfba2018-07-23 18:49:04 +0000119 typedef typename ELFT::Dyn Elf_Dyn;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000120
Dave Lee67b49662017-11-16 18:10:15 +0000121 enum class SymtabType { Static, Dynamic };
122
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000123 /// The future ".strtab" section.
Rafael Espindola21956e42015-10-23 21:48:05 +0000124 StringTableBuilder DotStrtab{StringTableBuilder::ELF};
Sean Silva08a75ae2013-06-20 19:11:44 +0000125
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000126 /// The future ".shstrtab" section.
Rafael Espindola21956e42015-10-23 21:48:05 +0000127 StringTableBuilder DotShStrtab{StringTableBuilder::ELF};
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000128
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000129 /// The future ".dynstr" section.
Dave Lee67b49662017-11-16 18:10:15 +0000130 StringTableBuilder DotDynstr{StringTableBuilder::ELF};
131
Simon Atanasyan35babf92014-04-06 09:02:55 +0000132 NameToIdxMap SN2I;
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000133 NameToIdxMap SymN2I;
George Rimar13a364e2019-07-22 12:01:52 +0000134 ELFYAML::Object &Doc;
Sean Silvac1c290b2013-06-20 20:59:34 +0000135
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000136 bool buildSectionIndex();
George Rimar6da44ad2019-04-03 14:53:42 +0000137 bool buildSymbolIndex(ArrayRef<ELFYAML::Symbol> Symbols);
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000138 void initELFHeader(Elf_Ehdr &Header);
Petr Hosekeb04da32017-07-19 20:38:46 +0000139 void initProgramHeaders(std::vector<Elf_Phdr> &PHeaders);
George Rimar66296dc2019-06-05 13:16:53 +0000140 bool initImplicitHeader(ELFState<ELFT> &State, ContiguousBlobAccumulator &CBA,
141 Elf_Shdr &Header, StringRef SecName,
142 ELFYAML::Section *YAMLSec);
143 bool initSectionHeaders(ELFState<ELFT> &State,
144 std::vector<Elf_Shdr> &SHeaders,
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000145 ContiguousBlobAccumulator &CBA);
Dave Lee67b49662017-11-16 18:10:15 +0000146 void initSymtabSectionHeader(Elf_Shdr &SHeader, SymtabType STType,
George Rimar66296dc2019-06-05 13:16:53 +0000147 ContiguousBlobAccumulator &CBA,
148 ELFYAML::Section *YAMLSec);
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000149 void initStrtabSectionHeader(Elf_Shdr &SHeader, StringRef Name,
150 StringTableBuilder &STB,
George Rimar66296dc2019-06-05 13:16:53 +0000151 ContiguousBlobAccumulator &CBA,
152 ELFYAML::Section *YAMLSec);
Petr Hosekeb04da32017-07-19 20:38:46 +0000153 void setProgramHeaderLayout(std::vector<Elf_Phdr> &PHeaders,
154 std::vector<Elf_Shdr> &SHeaders);
George Rimarda1b3ab2019-04-26 12:15:32 +0000155 bool writeSectionContent(Elf_Shdr &SHeader,
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000156 const ELFYAML::RawContentSection &Section,
157 ContiguousBlobAccumulator &CBA);
158 bool writeSectionContent(Elf_Shdr &SHeader,
159 const ELFYAML::RelocationSection &Section,
160 ContiguousBlobAccumulator &CBA);
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000161 bool writeSectionContent(Elf_Shdr &SHeader, const ELFYAML::Group &Group,
162 ContiguousBlobAccumulator &CBA);
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000163 bool writeSectionContent(Elf_Shdr &SHeader,
George Rimar646af082019-02-19 15:29:07 +0000164 const ELFYAML::SymverSection &Section,
165 ContiguousBlobAccumulator &CBA);
166 bool writeSectionContent(Elf_Shdr &SHeader,
George Rimar0621b792019-02-19 14:53:48 +0000167 const ELFYAML::VerneedSection &Section,
168 ContiguousBlobAccumulator &CBA);
169 bool writeSectionContent(Elf_Shdr &SHeader,
George Rimar623ae722019-02-21 12:21:43 +0000170 const ELFYAML::VerdefSection &Section,
171 ContiguousBlobAccumulator &CBA);
172 bool writeSectionContent(Elf_Shdr &SHeader,
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000173 const ELFYAML::MipsABIFlags &Section,
174 ContiguousBlobAccumulator &CBA);
James Hendersonfd997802019-02-25 11:02:24 +0000175 bool writeSectionContent(Elf_Shdr &SHeader,
George Rimar0e7ed912019-02-09 11:34:28 +0000176 const ELFYAML::DynamicSection &Section,
177 ContiguousBlobAccumulator &CBA);
George Rimar13a364e2019-07-22 12:01:52 +0000178 ELFState(ELFYAML::Object &D);
Simon Atanasyan220c54a2014-04-02 16:34:40 +0000179
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000180public:
George Rimar13a364e2019-07-22 12:01:52 +0000181 static int writeELF(raw_ostream &OS, ELFYAML::Object &Doc);
George Rimar0621b792019-02-19 14:53:48 +0000182
183private:
184 void finalizeStrings();
Sean Silva08a75ae2013-06-20 19:11:44 +0000185};
186} // end anonymous namespace
187
Sean Silva37e817c2013-06-21 00:33:01 +0000188template <class ELFT>
George Rimar13a364e2019-07-22 12:01:52 +0000189ELFState<ELFT>::ELFState(ELFYAML::Object &D) : Doc(D) {
190 StringSet<> DocSections;
191 for (std::unique_ptr<ELFYAML::Section> &D : Doc.Sections)
192 if (!D->Name.empty())
193 DocSections.insert(D->Name);
194
195 std::vector<StringRef> ImplicitSections = {".symtab", ".strtab", ".shstrtab"};
196 if (!Doc.DynamicSymbols.empty())
197 ImplicitSections.insert(ImplicitSections.end(), {".dynsym", ".dynstr"});
198
199 // Insert placeholders for implicit sections that are not
200 // defined explicitly in YAML.
201 for (StringRef SecName : ImplicitSections) {
202 if (DocSections.count(SecName))
203 continue;
204
205 std::unique_ptr<ELFYAML::Section> Sec = llvm::make_unique<ELFYAML::Section>(
206 ELFYAML::Section::SectionKind::RawContent, true /*IsImplicit*/);
207 Sec->Name = SecName;
208 Doc.Sections.push_back(std::move(Sec));
209 }
210}
211
212template <class ELFT>
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000213void ELFState<ELFT>::initELFHeader(Elf_Ehdr &Header) {
214 using namespace llvm::ELF;
215 zero(Header);
216 Header.e_ident[EI_MAG0] = 0x7f;
217 Header.e_ident[EI_MAG1] = 'E';
218 Header.e_ident[EI_MAG2] = 'L';
219 Header.e_ident[EI_MAG3] = 'F';
220 Header.e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;
George Rimara5a0a0f2019-03-07 12:09:19 +0000221 Header.e_ident[EI_DATA] = Doc.Header.Data;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000222 Header.e_ident[EI_VERSION] = EV_CURRENT;
223 Header.e_ident[EI_OSABI] = Doc.Header.OSABI;
George Rimar6367d7a2018-12-20 10:43:49 +0000224 Header.e_ident[EI_ABIVERSION] = Doc.Header.ABIVersion;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000225 Header.e_type = Doc.Header.Type;
226 Header.e_machine = Doc.Header.Machine;
227 Header.e_version = EV_CURRENT;
228 Header.e_entry = Doc.Header.Entry;
Petr Hosekeb04da32017-07-19 20:38:46 +0000229 Header.e_phoff = sizeof(Header);
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000230 Header.e_flags = Doc.Header.Flags;
231 Header.e_ehsize = sizeof(Elf_Ehdr);
Petr Hosekeb04da32017-07-19 20:38:46 +0000232 Header.e_phentsize = sizeof(Elf_Phdr);
233 Header.e_phnum = Doc.ProgramHeaders.size();
George Rimar687d47c2019-06-27 11:08:42 +0000234
235 Header.e_shentsize =
236 Doc.Header.SHEntSize ? (uint16_t)*Doc.Header.SHEntSize : sizeof(Elf_Shdr);
Petr Hosekeb04da32017-07-19 20:38:46 +0000237 // Immediately following the ELF header and program headers.
238 Header.e_shoff =
George Rimar687d47c2019-06-27 11:08:42 +0000239 Doc.Header.SHOffset
240 ? (uint16_t)*Doc.Header.SHOffset
241 : sizeof(Header) + sizeof(Elf_Phdr) * Doc.ProgramHeaders.size();
242 Header.e_shnum =
243 Doc.Header.SHNum ? (uint16_t)*Doc.Header.SHNum : SN2I.size() + 1;
244 Header.e_shstrndx = Doc.Header.SHStrNdx ? (uint16_t)*Doc.Header.SHStrNdx
245 : SN2I.get(".shstrtab");
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000246}
247
248template <class ELFT>
Petr Hosekeb04da32017-07-19 20:38:46 +0000249void ELFState<ELFT>::initProgramHeaders(std::vector<Elf_Phdr> &PHeaders) {
250 for (const auto &YamlPhdr : Doc.ProgramHeaders) {
251 Elf_Phdr Phdr;
252 Phdr.p_type = YamlPhdr.Type;
253 Phdr.p_flags = YamlPhdr.Flags;
254 Phdr.p_vaddr = YamlPhdr.VAddr;
255 Phdr.p_paddr = YamlPhdr.PAddr;
256 PHeaders.push_back(Phdr);
257 }
258}
George Rimar09746882019-05-07 12:10:51 +0000259
260static bool convertSectionIndex(NameToIdxMap &SN2I, StringRef SecName,
261 StringRef IndexSrc, unsigned &IndexDest) {
Puyan Lotfia10f0162019-05-11 17:03:36 +0000262 if (!SN2I.lookup(IndexSrc, IndexDest) && !to_integer(IndexSrc, IndexDest)) {
George Rimar09746882019-05-07 12:10:51 +0000263 WithColor::error() << "Unknown section referenced: '" << IndexSrc
264 << "' at YAML section '" << SecName << "'.\n";
265 return false;
Xing GUO98228352018-12-04 14:27:51 +0000266 }
267 return true;
268}
269
Petr Hosekeb04da32017-07-19 20:38:46 +0000270template <class ELFT>
George Rimar66296dc2019-06-05 13:16:53 +0000271bool ELFState<ELFT>::initImplicitHeader(ELFState<ELFT> &State,
272 ContiguousBlobAccumulator &CBA,
273 Elf_Shdr &Header, StringRef SecName,
274 ELFYAML::Section *YAMLSec) {
275 // Check if the header was already initialized.
276 if (Header.sh_offset)
277 return false;
278
279 if (SecName == ".symtab")
280 State.initSymtabSectionHeader(Header, SymtabType::Static, CBA, YAMLSec);
281 else if (SecName == ".strtab")
282 State.initStrtabSectionHeader(Header, SecName, State.DotStrtab, CBA,
283 YAMLSec);
284 else if (SecName == ".shstrtab")
285 State.initStrtabSectionHeader(Header, SecName, State.DotShStrtab, CBA,
286 YAMLSec);
287
288 else if (SecName == ".dynsym")
289 State.initSymtabSectionHeader(Header, SymtabType::Dynamic, CBA, YAMLSec);
290 else if (SecName == ".dynstr")
291 State.initStrtabSectionHeader(Header, SecName, State.DotDynstr, CBA,
292 YAMLSec);
293 else
294 return false;
George Rimar9df825f2019-07-02 10:20:12 +0000295
George Rimareb41f7f2019-07-11 12:59:29 +0000296 // Override the sh_offset/sh_size fields if requested.
297 if (YAMLSec) {
298 if (YAMLSec->ShOffset)
299 Header.sh_offset = *YAMLSec->ShOffset;
300 if (YAMLSec->ShSize)
301 Header.sh_size = *YAMLSec->ShSize;
302 }
George Rimar9df825f2019-07-02 10:20:12 +0000303
George Rimar66296dc2019-06-05 13:16:53 +0000304 return true;
305}
306
George Rimar60dc5d42019-06-25 08:22:57 +0000307static StringRef dropUniqueSuffix(StringRef S) {
308 size_t SuffixPos = S.rfind(" [");
309 if (SuffixPos == StringRef::npos)
310 return S;
311 return S.substr(0, SuffixPos);
312}
313
George Rimar66296dc2019-06-05 13:16:53 +0000314template <class ELFT>
315bool ELFState<ELFT>::initSectionHeaders(ELFState<ELFT> &State,
316 std::vector<Elf_Shdr> &SHeaders,
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000317 ContiguousBlobAccumulator &CBA) {
318 // Ensure SHN_UNDEF entry is present. An all-zero section header is a
319 // valid SHN_UNDEF entry since SHT_NULL == 0.
George Rimar13a364e2019-07-22 12:01:52 +0000320 SHeaders.resize(Doc.Sections.size() + 1);
George Rimareb394e92019-06-07 08:31:36 +0000321 zero(SHeaders[0]);
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000322
George Rimar13a364e2019-07-22 12:01:52 +0000323 for (size_t I = 1; I < Doc.Sections.size() + 1; ++I) {
George Rimareb394e92019-06-07 08:31:36 +0000324 Elf_Shdr &SHeader = SHeaders[I];
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000325 zero(SHeader);
George Rimar13a364e2019-07-22 12:01:52 +0000326 ELFYAML::Section *Sec = Doc.Sections[I - 1].get();
George Rimareb394e92019-06-07 08:31:36 +0000327
328 // We have a few sections like string or symbol tables that are usually
329 // added implicitly to the end. However, if they are explicitly specified
330 // in the YAML, we need to write them here. This ensures the file offset
331 // remains correct.
George Rimar13a364e2019-07-22 12:01:52 +0000332 if (initImplicitHeader(State, CBA, SHeader, Sec->Name,
333 Sec->IsImplicit ? nullptr : Sec))
George Rimareb394e92019-06-07 08:31:36 +0000334 continue;
335
336 assert(Sec && "It can't be null unless it is an implicit section. But all "
337 "implicit sections should already have been handled above.");
338
George Rimar13a364e2019-07-22 12:01:52 +0000339 SHeader.sh_name = DotShStrtab.getOffset(dropUniqueSuffix(Sec->Name));
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000340 SHeader.sh_type = Sec->Type;
George Rimarcfa1a622019-06-14 11:01:14 +0000341 if (Sec->Flags)
342 SHeader.sh_flags = *Sec->Flags;
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000343 SHeader.sh_addr = Sec->Address;
344 SHeader.sh_addralign = Sec->AddressAlign;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000345
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000346 if (!Sec->Link.empty()) {
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000347 unsigned Index;
Xing GUO98228352018-12-04 14:27:51 +0000348 if (!convertSectionIndex(SN2I, Sec->Name, Sec->Link, Index))
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000349 return false;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000350 SHeader.sh_link = Index;
351 }
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000352
George Rimareb394e92019-06-07 08:31:36 +0000353 if (auto S = dyn_cast<ELFYAML::RawContentSection>(Sec)) {
George Rimarda1b3ab2019-04-26 12:15:32 +0000354 if (!writeSectionContent(SHeader, *S, CBA))
George Rimar7f2df7d2018-08-16 12:23:22 +0000355 return false;
George Rimareb394e92019-06-07 08:31:36 +0000356 } else if (auto S = dyn_cast<ELFYAML::RelocationSection>(Sec)) {
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000357 if (!writeSectionContent(SHeader, *S, CBA))
358 return false;
George Rimareb394e92019-06-07 08:31:36 +0000359 } else if (auto S = dyn_cast<ELFYAML::Group>(Sec)) {
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000360 if (!writeSectionContent(SHeader, *S, CBA))
361 return false;
George Rimareb394e92019-06-07 08:31:36 +0000362 } else if (auto S = dyn_cast<ELFYAML::MipsABIFlags>(Sec)) {
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000363 if (!writeSectionContent(SHeader, *S, CBA))
364 return false;
George Rimareb394e92019-06-07 08:31:36 +0000365 } else if (auto S = dyn_cast<ELFYAML::NoBitsSection>(Sec)) {
Simon Atanasyan5db02762015-07-03 23:00:54 +0000366 SHeader.sh_entsize = 0;
367 SHeader.sh_size = S->Size;
368 // SHT_NOBITS section does not have content
369 // so just to setup the section offset.
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000370 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
George Rimareb394e92019-06-07 08:31:36 +0000371 } else if (auto S = dyn_cast<ELFYAML::DynamicSection>(Sec)) {
James Hendersonfd997802019-02-25 11:02:24 +0000372 if (!writeSectionContent(SHeader, *S, CBA))
373 return false;
George Rimareb394e92019-06-07 08:31:36 +0000374 } else if (auto S = dyn_cast<ELFYAML::SymverSection>(Sec)) {
George Rimarda1b3ab2019-04-26 12:15:32 +0000375 if (!writeSectionContent(SHeader, *S, CBA))
376 return false;
George Rimareb394e92019-06-07 08:31:36 +0000377 } else if (auto S = dyn_cast<ELFYAML::VerneedSection>(Sec)) {
George Rimarda1b3ab2019-04-26 12:15:32 +0000378 if (!writeSectionContent(SHeader, *S, CBA))
379 return false;
George Rimareb394e92019-06-07 08:31:36 +0000380 } else if (auto S = dyn_cast<ELFYAML::VerdefSection>(Sec)) {
George Rimarda1b3ab2019-04-26 12:15:32 +0000381 if (!writeSectionContent(SHeader, *S, CBA))
382 return false;
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000383 } else
384 llvm_unreachable("Unknown section type");
George Rimar9df825f2019-07-02 10:20:12 +0000385
George Rimareb41f7f2019-07-11 12:59:29 +0000386 // Override the sh_offset/sh_size fields if requested.
387 if (Sec) {
388 if (Sec->ShOffset)
389 SHeader.sh_offset = *Sec->ShOffset;
390 if (Sec->ShSize)
391 SHeader.sh_size = *Sec->ShSize;
392 }
George Rimar66296dc2019-06-05 13:16:53 +0000393 }
394
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000395 return true;
396}
397
George Rimar6da44ad2019-04-03 14:53:42 +0000398static size_t findFirstNonGlobal(ArrayRef<ELFYAML::Symbol> Symbols) {
399 for (size_t I = 0; I < Symbols.size(); ++I)
400 if (Symbols[I].Binding.value != ELF::STB_LOCAL)
401 return I;
402 return Symbols.size();
403}
404
George Rimar1e410072019-06-10 12:43:18 +0000405static uint64_t writeRawSectionData(raw_ostream &OS,
406 const ELFYAML::RawContentSection &RawSec) {
407 size_t ContentSize = 0;
408 if (RawSec.Content) {
409 RawSec.Content->writeAsBinary(OS);
410 ContentSize = RawSec.Content->binary_size();
411 }
412
413 if (!RawSec.Size)
414 return ContentSize;
415
416 OS.write_zeros(*RawSec.Size - ContentSize);
417 return *RawSec.Size;
418}
419
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000420template <class ELFT>
George Rimar30ea0c42019-06-20 14:44:48 +0000421static std::vector<typename ELFT::Sym>
422toELFSymbols(NameToIdxMap &SN2I, ArrayRef<ELFYAML::Symbol> Symbols,
423 const StringTableBuilder &Strtab) {
424 using Elf_Sym = typename ELFT::Sym;
425
426 std::vector<Elf_Sym> Ret;
427 Ret.resize(Symbols.size() + 1);
428
429 size_t I = 0;
430 for (const auto &Sym : Symbols) {
431 Elf_Sym &Symbol = Ret[++I];
432
433 // If NameIndex, which contains the name offset, is explicitly specified, we
434 // use it. This is useful for preparing broken objects. Otherwise, we add
435 // the specified Name to the string table builder to get its offset.
436 if (Sym.NameIndex)
437 Symbol.st_name = *Sym.NameIndex;
438 else if (!Sym.Name.empty())
George Rimar60dc5d42019-06-25 08:22:57 +0000439 Symbol.st_name = Strtab.getOffset(dropUniqueSuffix(Sym.Name));
George Rimar30ea0c42019-06-20 14:44:48 +0000440
441 Symbol.setBindingAndType(Sym.Binding, Sym.Type);
442 if (!Sym.Section.empty()) {
443 unsigned Index;
444 if (!SN2I.lookup(Sym.Section, Index)) {
445 WithColor::error() << "Unknown section referenced: '" << Sym.Section
446 << "' by YAML symbol " << Sym.Name << ".\n";
447 exit(1);
448 }
449 Symbol.st_shndx = Index;
450 } else if (Sym.Index) {
451 Symbol.st_shndx = *Sym.Index;
452 }
453 // else Symbol.st_shndex == SHN_UNDEF (== 0), since it was zero'd earlier.
454 Symbol.st_value = Sym.Value;
455 Symbol.st_other = Sym.Other;
456 Symbol.st_size = Sym.Size;
457 }
458
459 return Ret;
460}
461
462template <class ELFT>
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000463void ELFState<ELFT>::initSymtabSectionHeader(Elf_Shdr &SHeader,
Dave Lee67b49662017-11-16 18:10:15 +0000464 SymtabType STType,
George Rimar66296dc2019-06-05 13:16:53 +0000465 ContiguousBlobAccumulator &CBA,
466 ELFYAML::Section *YAMLSec) {
George Rimar1e410072019-06-10 12:43:18 +0000467
Dave Lee67b49662017-11-16 18:10:15 +0000468 bool IsStatic = STType == SymtabType::Static;
George Rimar1e410072019-06-10 12:43:18 +0000469 const auto &Symbols = IsStatic ? Doc.Symbols : Doc.DynamicSymbols;
470
471 ELFYAML::RawContentSection *RawSec =
472 dyn_cast_or_null<ELFYAML::RawContentSection>(YAMLSec);
473 if (RawSec && !Symbols.empty() && (RawSec->Content || RawSec->Size)) {
474 if (RawSec->Content)
475 WithColor::error() << "Cannot specify both `Content` and " +
476 (IsStatic ? Twine("`Symbols`")
477 : Twine("`DynamicSymbols`")) +
478 " for symbol table section '"
479 << RawSec->Name << "'.\n";
480 if (RawSec->Size)
481 WithColor::error() << "Cannot specify both `Size` and " +
482 (IsStatic ? Twine("`Symbols`")
483 : Twine("`DynamicSymbols`")) +
484 " for symbol table section '"
485 << RawSec->Name << "'.\n";
486 exit(1);
487 }
488
489 zero(SHeader);
Dave Lee67b49662017-11-16 18:10:15 +0000490 SHeader.sh_name = DotShStrtab.getOffset(IsStatic ? ".symtab" : ".dynsym");
George Rimar0aecaba2019-06-14 14:25:34 +0000491
492 if (YAMLSec)
493 SHeader.sh_type = YAMLSec->Type;
494 else
495 SHeader.sh_type = IsStatic ? ELF::SHT_SYMTAB : ELF::SHT_DYNSYM;
George Rimar379aa182019-06-10 11:38:06 +0000496
George Rimarffb3c722019-06-11 10:00:51 +0000497 if (RawSec && !RawSec->Link.empty()) {
498 // If the Link field is explicitly defined in the document,
499 // we should use it.
500 unsigned Index;
501 if (!convertSectionIndex(SN2I, RawSec->Name, RawSec->Link, Index))
502 return;
503 SHeader.sh_link = Index;
504 } else {
505 // When we describe the .dynsym section in the document explicitly, it is
506 // allowed to omit the "DynamicSymbols" tag. In this case .dynstr is not
507 // added implicitly and we should be able to leave the Link zeroed if
508 // .dynstr is not defined.
509 unsigned Link = 0;
510 if (IsStatic)
511 Link = SN2I.get(".strtab");
512 else
513 SN2I.lookup(".dynstr", Link);
514 SHeader.sh_link = Link;
515 }
George Rimar379aa182019-06-10 11:38:06 +0000516
George Rimarcfa1a622019-06-14 11:01:14 +0000517 if (YAMLSec && YAMLSec->Flags)
518 SHeader.sh_flags = *YAMLSec->Flags;
519 else if (!IsStatic)
520 SHeader.sh_flags = ELF::SHF_ALLOC;
George Rimarc1da1492019-04-26 12:45:54 +0000521
George Rimara7ba1a02019-03-01 10:18:16 +0000522 // If the symbol table section is explicitly described in the YAML
523 // then we should set the fields requested.
George Rimarb6e20932019-06-19 08:57:38 +0000524 SHeader.sh_info = (RawSec && RawSec->Info) ? (unsigned)(*RawSec->Info)
525 : findFirstNonGlobal(Symbols) + 1;
George Rimar66296dc2019-06-05 13:16:53 +0000526 SHeader.sh_entsize = (YAMLSec && YAMLSec->EntSize)
527 ? (uint64_t)(*YAMLSec->EntSize)
528 : sizeof(Elf_Sym);
529 SHeader.sh_addralign = YAMLSec ? (uint64_t)YAMLSec->AddressAlign : 8;
530 SHeader.sh_addr = YAMLSec ? (uint64_t)YAMLSec->Address : 0;
531
George Rimar1e410072019-06-10 12:43:18 +0000532 auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
533 if (RawSec && (RawSec->Content || RawSec->Size)) {
534 assert(Symbols.empty());
535 SHeader.sh_size = writeRawSectionData(OS, *RawSec);
536 return;
George Rimar6947acd2019-02-19 12:15:04 +0000537 }
George Rimar1e410072019-06-10 12:43:18 +0000538
George Rimar30ea0c42019-06-20 14:44:48 +0000539 std::vector<Elf_Sym> Syms =
540 toELFSymbols<ELFT>(SN2I, Symbols, IsStatic ? DotStrtab : DotDynstr);
George Rimar1e410072019-06-10 12:43:18 +0000541 writeArrayData(OS, makeArrayRef(Syms));
542 SHeader.sh_size = arrayDataSize(makeArrayRef(Syms));
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000543}
544
545template <class ELFT>
546void ELFState<ELFT>::initStrtabSectionHeader(Elf_Shdr &SHeader, StringRef Name,
547 StringTableBuilder &STB,
George Rimar66296dc2019-06-05 13:16:53 +0000548 ContiguousBlobAccumulator &CBA,
549 ELFYAML::Section *YAMLSec) {
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000550 zero(SHeader);
Hans Wennborg59f0cba2014-04-30 19:38:09 +0000551 SHeader.sh_name = DotShStrtab.getOffset(Name);
George Rimar0aecaba2019-06-14 14:25:34 +0000552 SHeader.sh_type = YAMLSec ? YAMLSec->Type : ELF::SHT_STRTAB;
George Rimar66296dc2019-06-05 13:16:53 +0000553 SHeader.sh_addralign = YAMLSec ? (uint64_t)YAMLSec->AddressAlign : 1;
554
555 ELFYAML::RawContentSection *RawSec =
556 dyn_cast_or_null<ELFYAML::RawContentSection>(YAMLSec);
George Rimar1e410072019-06-10 12:43:18 +0000557
558 auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
559 if (RawSec && (RawSec->Content || RawSec->Size)) {
560 SHeader.sh_size = writeRawSectionData(OS, *RawSec);
George Rimar66296dc2019-06-05 13:16:53 +0000561 } else {
George Rimar1e410072019-06-10 12:43:18 +0000562 STB.write(OS);
George Rimar66296dc2019-06-05 13:16:53 +0000563 SHeader.sh_size = STB.getSize();
564 }
565
566 if (YAMLSec && YAMLSec->EntSize)
567 SHeader.sh_entsize = *YAMLSec->EntSize;
George Rimar6947acd2019-02-19 12:15:04 +0000568
George Rimarb6e20932019-06-19 08:57:38 +0000569 if (RawSec && RawSec->Info)
570 SHeader.sh_info = *RawSec->Info;
571
George Rimarcfa1a622019-06-14 11:01:14 +0000572 if (YAMLSec && YAMLSec->Flags)
573 SHeader.sh_flags = *YAMLSec->Flags;
574 else if (Name == ".dynstr")
575 SHeader.sh_flags = ELF::SHF_ALLOC;
576
George Rimar43f62ff2019-06-14 11:13:32 +0000577 // If the section is explicitly described in the YAML
George Rimar6947acd2019-02-19 12:15:04 +0000578 // then we want to use its section address.
George Rimar43f62ff2019-06-14 11:13:32 +0000579 if (YAMLSec)
George Rimarcfa1a622019-06-14 11:01:14 +0000580 SHeader.sh_addr = YAMLSec->Address;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000581}
582
583template <class ELFT>
Petr Hosekeb04da32017-07-19 20:38:46 +0000584void ELFState<ELFT>::setProgramHeaderLayout(std::vector<Elf_Phdr> &PHeaders,
585 std::vector<Elf_Shdr> &SHeaders) {
586 uint32_t PhdrIdx = 0;
587 for (auto &YamlPhdr : Doc.ProgramHeaders) {
George Rimarf5345a32019-05-01 09:45:55 +0000588 Elf_Phdr &PHeader = PHeaders[PhdrIdx++];
589
Puyan Lotfia10f0162019-05-11 17:03:36 +0000590 std::vector<Elf_Shdr *> Sections;
591 for (const ELFYAML::SectionName &SecName : YamlPhdr.Sections) {
592 unsigned Index;
593 if (!SN2I.lookup(SecName.Section, Index)) {
594 WithColor::error() << "Unknown section referenced: '" << SecName.Section
595 << "' by program header.\n";
596 exit(1);
George Rimarf5345a32019-05-01 09:45:55 +0000597 }
598 Sections.push_back(&SHeaders[Index]);
599 }
Petr Hosekeb04da32017-07-19 20:38:46 +0000600
James Hendersonb10f48b2019-03-15 10:35:27 +0000601 if (YamlPhdr.Offset) {
602 PHeader.p_offset = *YamlPhdr.Offset;
603 } else {
604 if (YamlPhdr.Sections.size())
605 PHeader.p_offset = UINT32_MAX;
Petr Hosekeb04da32017-07-19 20:38:46 +0000606 else
James Hendersonb10f48b2019-03-15 10:35:27 +0000607 PHeader.p_offset = 0;
608
609 // Find the minimum offset for the program header.
George Rimarf5345a32019-05-01 09:45:55 +0000610 for (Elf_Shdr *SHeader : Sections)
611 PHeader.p_offset = std::min(PHeader.p_offset, SHeader->sh_offset);
Petr Hosekeb04da32017-07-19 20:38:46 +0000612 }
613
James Hendersonb10f48b2019-03-15 10:35:27 +0000614 // Find the maximum offset of the end of a section in order to set p_filesz,
615 // if not set explicitly.
616 if (YamlPhdr.FileSize) {
617 PHeader.p_filesz = *YamlPhdr.FileSize;
618 } else {
619 PHeader.p_filesz = 0;
George Rimarf5345a32019-05-01 09:45:55 +0000620 for (Elf_Shdr *SHeader : Sections) {
James Hendersonb10f48b2019-03-15 10:35:27 +0000621 uint64_t EndOfSection;
George Rimarf5345a32019-05-01 09:45:55 +0000622 if (SHeader->sh_type == llvm::ELF::SHT_NOBITS)
623 EndOfSection = SHeader->sh_offset;
James Hendersonb10f48b2019-03-15 10:35:27 +0000624 else
George Rimarf5345a32019-05-01 09:45:55 +0000625 EndOfSection = SHeader->sh_offset + SHeader->sh_size;
James Hendersonb10f48b2019-03-15 10:35:27 +0000626 uint64_t EndOfSegment = PHeader.p_offset + PHeader.p_filesz;
627 EndOfSegment = std::max(EndOfSegment, EndOfSection);
628 PHeader.p_filesz = EndOfSegment - PHeader.p_offset;
629 }
630 }
631
632 // If not set explicitly, find the memory size by adding the size of
633 // sections at the end of the segment. These should be empty (size of zero)
634 // and NOBITS sections.
635 if (YamlPhdr.MemSize) {
636 PHeader.p_memsz = *YamlPhdr.MemSize;
637 } else {
638 PHeader.p_memsz = PHeader.p_filesz;
George Rimarf5345a32019-05-01 09:45:55 +0000639 for (Elf_Shdr *SHeader : Sections)
640 if (SHeader->sh_offset == PHeader.p_offset + PHeader.p_filesz)
641 PHeader.p_memsz += SHeader->sh_size;
Petr Hosekeb04da32017-07-19 20:38:46 +0000642 }
643
644 // Set the alignment of the segment to be the same as the maximum alignment
Jake Ehrlich03aeeb092017-11-01 23:14:48 +0000645 // of the sections with the same offset so that by default the segment
Petr Hosekeb04da32017-07-19 20:38:46 +0000646 // has a valid and sensible alignment.
Jake Ehrlich03aeeb092017-11-01 23:14:48 +0000647 if (YamlPhdr.Align) {
648 PHeader.p_align = *YamlPhdr.Align;
649 } else {
650 PHeader.p_align = 1;
George Rimarf5345a32019-05-01 09:45:55 +0000651 for (Elf_Shdr *SHeader : Sections)
652 if (SHeader->sh_offset == PHeader.p_offset)
653 PHeader.p_align = std::max(PHeader.p_align, SHeader->sh_addralign);
Petr Hosekeb04da32017-07-19 20:38:46 +0000654 }
655 }
656}
657
658template <class ELFT>
George Rimarda1b3ab2019-04-26 12:15:32 +0000659bool ELFState<ELFT>::writeSectionContent(
George Rimarb49e1922019-04-24 13:02:15 +0000660 Elf_Shdr &SHeader, const ELFYAML::RawContentSection &Section,
661 ContiguousBlobAccumulator &CBA) {
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000662 raw_ostream &OS =
663 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
George Rimar1e410072019-06-10 12:43:18 +0000664 SHeader.sh_size = writeRawSectionData(OS, Section);
George Rimarb49e1922019-04-24 13:02:15 +0000665
George Rimar65a68282018-08-07 08:11:38 +0000666 if (Section.EntSize)
667 SHeader.sh_entsize = *Section.EntSize;
668 else if (Section.Type == llvm::ELF::SHT_RELR)
Jake Ehrlich0f440d82018-06-28 21:07:34 +0000669 SHeader.sh_entsize = sizeof(Elf_Relr);
670 else
671 SHeader.sh_entsize = 0;
George Rimarb6e20932019-06-19 08:57:38 +0000672
673 if (Section.Info)
674 SHeader.sh_info = *Section.Info;
675
George Rimarda1b3ab2019-04-26 12:15:32 +0000676 return true;
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000677}
678
Simon Atanasyan5d19c672015-01-25 13:29:25 +0000679static bool isMips64EL(const ELFYAML::Object &Doc) {
680 return Doc.Header.Machine == ELFYAML::ELF_EM(llvm::ELF::EM_MIPS) &&
681 Doc.Header.Class == ELFYAML::ELF_ELFCLASS(ELF::ELFCLASS64) &&
682 Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB);
683}
684
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000685template <class ELFT>
686bool
687ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
688 const ELFYAML::RelocationSection &Section,
689 ContiguousBlobAccumulator &CBA) {
Simon Atanasyan8eb9d1b2015-05-08 07:05:04 +0000690 assert((Section.Type == llvm::ELF::SHT_REL ||
691 Section.Type == llvm::ELF::SHT_RELA) &&
692 "Section type is not SHT_REL nor SHT_RELA");
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000693
694 bool IsRela = Section.Type == llvm::ELF::SHT_RELA;
695 SHeader.sh_entsize = IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
696 SHeader.sh_size = SHeader.sh_entsize * Section.Relocations.size();
697
George Rimarda1b3ab2019-04-26 12:15:32 +0000698 // For relocation section set link to .symtab by default.
699 if (Section.Link.empty())
George Rimard71017b2019-06-10 09:57:29 +0000700 SHeader.sh_link = SN2I.get(".symtab");
George Rimarda1b3ab2019-04-26 12:15:32 +0000701
702 unsigned Index = 0;
703 if (!Section.RelocatableSec.empty() &&
704 !convertSectionIndex(SN2I, Section.Name, Section.RelocatableSec, Index))
705 return false;
706 SHeader.sh_info = Index;
707
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000708 auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000709
710 for (const auto &Rel : Section.Relocations) {
George Rimar09746882019-05-07 12:10:51 +0000711 unsigned SymIdx = 0;
712 // If a relocation references a symbol, try to look one up in the symbol
713 // table. If it is not there, treat the value as a symbol index.
Puyan Lotfia10f0162019-05-11 17:03:36 +0000714 if (Rel.Symbol && !SymN2I.lookup(*Rel.Symbol, SymIdx) &&
George Rimar09746882019-05-07 12:10:51 +0000715 !to_integer(*Rel.Symbol, SymIdx)) {
716 WithColor::error() << "Unknown symbol referenced: '" << *Rel.Symbol
717 << "' at YAML section '" << Section.Name << "'.\n";
James Henderson9bc817a2019-03-12 17:00:25 +0000718 return false;
719 }
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000720
721 if (IsRela) {
722 Elf_Rela REntry;
723 zero(REntry);
724 REntry.r_offset = Rel.Offset;
725 REntry.r_addend = Rel.Addend;
Simon Atanasyan5d19c672015-01-25 13:29:25 +0000726 REntry.setSymbolAndType(SymIdx, Rel.Type, isMips64EL(Doc));
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000727 OS.write((const char *)&REntry, sizeof(REntry));
728 } else {
729 Elf_Rel REntry;
730 zero(REntry);
731 REntry.r_offset = Rel.Offset;
Simon Atanasyan5d19c672015-01-25 13:29:25 +0000732 REntry.setSymbolAndType(SymIdx, Rel.Type, isMips64EL(Doc));
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000733 OS.write((const char *)&REntry, sizeof(REntry));
734 }
735 }
736 return true;
737}
738
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000739template <class ELFT>
740bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
741 const ELFYAML::Group &Section,
742 ContiguousBlobAccumulator &CBA) {
Simon Atanasyan8eb9d1b2015-05-08 07:05:04 +0000743 assert(Section.Type == llvm::ELF::SHT_GROUP &&
744 "Section type is not SHT_GROUP");
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000745
George Rimard063c7d2019-02-20 13:58:43 +0000746 SHeader.sh_entsize = 4;
George Rimar09746882019-05-07 12:10:51 +0000747 SHeader.sh_size = SHeader.sh_entsize * Section.Members.size();
748
Puyan Lotfia10f0162019-05-11 17:03:36 +0000749 unsigned SymIdx;
750 if (!SymN2I.lookup(Section.Signature, SymIdx) &&
751 !to_integer(Section.Signature, SymIdx)) {
752 WithColor::error() << "Unknown symbol referenced: '" << Section.Signature
753 << "' at YAML section '" << Section.Name << "'.\n";
George Rimarda1b3ab2019-04-26 12:15:32 +0000754 return false;
755 }
756 SHeader.sh_info = SymIdx;
757
George Rimard063c7d2019-02-20 13:58:43 +0000758 raw_ostream &OS =
759 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000760
George Rimarfb7780a2019-04-26 12:20:51 +0000761 for (const ELFYAML::SectionOrType &Member : Section.Members) {
762 unsigned int SectionIndex = 0;
763 if (Member.sectionNameOrType == "GRP_COMDAT")
764 SectionIndex = llvm::ELF::GRP_COMDAT;
765 else if (!convertSectionIndex(SN2I, Section.Name, Member.sectionNameOrType,
766 SectionIndex))
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000767 return false;
George Rimarfb7780a2019-04-26 12:20:51 +0000768 support::endian::write<uint32_t>(OS, SectionIndex, ELFT::TargetEndianness);
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000769 }
770 return true;
771}
772
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000773template <class ELFT>
774bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
George Rimar646af082019-02-19 15:29:07 +0000775 const ELFYAML::SymverSection &Section,
776 ContiguousBlobAccumulator &CBA) {
George Rimar646af082019-02-19 15:29:07 +0000777 raw_ostream &OS =
778 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
George Rimardac37fb2019-02-20 14:01:02 +0000779 for (uint16_t Version : Section.Entries)
780 support::endian::write<uint16_t>(OS, Version, ELFT::TargetEndianness);
George Rimar646af082019-02-19 15:29:07 +0000781
George Rimard063c7d2019-02-20 13:58:43 +0000782 SHeader.sh_entsize = 2;
783 SHeader.sh_size = Section.Entries.size() * SHeader.sh_entsize;
George Rimar646af082019-02-19 15:29:07 +0000784 return true;
785}
786
787template <class ELFT>
788bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
George Rimar623ae722019-02-21 12:21:43 +0000789 const ELFYAML::VerdefSection &Section,
790 ContiguousBlobAccumulator &CBA) {
791 typedef typename ELFT::Verdef Elf_Verdef;
792 typedef typename ELFT::Verdaux Elf_Verdaux;
793 raw_ostream &OS =
794 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
795
796 uint64_t AuxCnt = 0;
797 for (size_t I = 0; I < Section.Entries.size(); ++I) {
798 const ELFYAML::VerdefEntry &E = Section.Entries[I];
799
800 Elf_Verdef VerDef;
801 VerDef.vd_version = E.Version;
802 VerDef.vd_flags = E.Flags;
803 VerDef.vd_ndx = E.VersionNdx;
804 VerDef.vd_hash = E.Hash;
805 VerDef.vd_aux = sizeof(Elf_Verdef);
806 VerDef.vd_cnt = E.VerNames.size();
807 if (I == Section.Entries.size() - 1)
808 VerDef.vd_next = 0;
809 else
810 VerDef.vd_next =
811 sizeof(Elf_Verdef) + E.VerNames.size() * sizeof(Elf_Verdaux);
812 OS.write((const char *)&VerDef, sizeof(Elf_Verdef));
813
814 for (size_t J = 0; J < E.VerNames.size(); ++J, ++AuxCnt) {
815 Elf_Verdaux VernAux;
816 VernAux.vda_name = DotDynstr.getOffset(E.VerNames[J]);
817 if (J == E.VerNames.size() - 1)
818 VernAux.vda_next = 0;
819 else
820 VernAux.vda_next = sizeof(Elf_Verdaux);
821 OS.write((const char *)&VernAux, sizeof(Elf_Verdaux));
822 }
823 }
824
825 SHeader.sh_size = Section.Entries.size() * sizeof(Elf_Verdef) +
826 AuxCnt * sizeof(Elf_Verdaux);
827 SHeader.sh_info = Section.Info;
828
829 return true;
830}
831
832template <class ELFT>
833bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
George Rimar0621b792019-02-19 14:53:48 +0000834 const ELFYAML::VerneedSection &Section,
835 ContiguousBlobAccumulator &CBA) {
George Rimarda1b3ab2019-04-26 12:15:32 +0000836 typedef typename ELFT::Verneed Elf_Verneed;
837 typedef typename ELFT::Vernaux Elf_Vernaux;
George Rimar0621b792019-02-19 14:53:48 +0000838
George Rimarda1b3ab2019-04-26 12:15:32 +0000839 auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
George Rimar0621b792019-02-19 14:53:48 +0000840
George Rimarda1b3ab2019-04-26 12:15:32 +0000841 uint64_t AuxCnt = 0;
842 for (size_t I = 0; I < Section.VerneedV.size(); ++I) {
843 const ELFYAML::VerneedEntry &VE = Section.VerneedV[I];
George Rimar0621b792019-02-19 14:53:48 +0000844
George Rimarda1b3ab2019-04-26 12:15:32 +0000845 Elf_Verneed VerNeed;
846 VerNeed.vn_version = VE.Version;
847 VerNeed.vn_file = DotDynstr.getOffset(VE.File);
848 if (I == Section.VerneedV.size() - 1)
849 VerNeed.vn_next = 0;
850 else
851 VerNeed.vn_next =
852 sizeof(Elf_Verneed) + VE.AuxV.size() * sizeof(Elf_Vernaux);
853 VerNeed.vn_cnt = VE.AuxV.size();
854 VerNeed.vn_aux = sizeof(Elf_Verneed);
855 OS.write((const char *)&VerNeed, sizeof(Elf_Verneed));
George Rimar0621b792019-02-19 14:53:48 +0000856
George Rimarda1b3ab2019-04-26 12:15:32 +0000857 for (size_t J = 0; J < VE.AuxV.size(); ++J, ++AuxCnt) {
858 const ELFYAML::VernauxEntry &VAuxE = VE.AuxV[J];
George Rimar0621b792019-02-19 14:53:48 +0000859
George Rimarda1b3ab2019-04-26 12:15:32 +0000860 Elf_Vernaux VernAux;
861 VernAux.vna_hash = VAuxE.Hash;
862 VernAux.vna_flags = VAuxE.Flags;
863 VernAux.vna_other = VAuxE.Other;
864 VernAux.vna_name = DotDynstr.getOffset(VAuxE.Name);
865 if (J == VE.AuxV.size() - 1)
866 VernAux.vna_next = 0;
867 else
868 VernAux.vna_next = sizeof(Elf_Vernaux);
869 OS.write((const char *)&VernAux, sizeof(Elf_Vernaux));
870 }
871 }
George Rimar0621b792019-02-19 14:53:48 +0000872
George Rimarda1b3ab2019-04-26 12:15:32 +0000873 SHeader.sh_size = Section.VerneedV.size() * sizeof(Elf_Verneed) +
874 AuxCnt * sizeof(Elf_Vernaux);
875 SHeader.sh_info = Section.Info;
George Rimar0621b792019-02-19 14:53:48 +0000876
George Rimarda1b3ab2019-04-26 12:15:32 +0000877 return true;
George Rimar0621b792019-02-19 14:53:48 +0000878}
879
880template <class ELFT>
881bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000882 const ELFYAML::MipsABIFlags &Section,
883 ContiguousBlobAccumulator &CBA) {
Simon Atanasyan8eb9d1b2015-05-08 07:05:04 +0000884 assert(Section.Type == llvm::ELF::SHT_MIPS_ABIFLAGS &&
885 "Section type is not SHT_MIPS_ABIFLAGS");
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000886
887 object::Elf_Mips_ABIFlags<ELFT> Flags;
888 zero(Flags);
889 SHeader.sh_entsize = sizeof(Flags);
890 SHeader.sh_size = SHeader.sh_entsize;
891
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000892 auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000893 Flags.version = Section.Version;
894 Flags.isa_level = Section.ISALevel;
895 Flags.isa_rev = Section.ISARevision;
896 Flags.gpr_size = Section.GPRSize;
897 Flags.cpr1_size = Section.CPR1Size;
898 Flags.cpr2_size = Section.CPR2Size;
899 Flags.fp_abi = Section.FpABI;
900 Flags.isa_ext = Section.ISAExtension;
901 Flags.ases = Section.ASEs;
902 Flags.flags1 = Section.Flags1;
903 Flags.flags2 = Section.Flags2;
904 OS.write((const char *)&Flags, sizeof(Flags));
905
906 return true;
907}
908
George Rimar0e7ed912019-02-09 11:34:28 +0000909template <class ELFT>
James Hendersonfd997802019-02-25 11:02:24 +0000910bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
George Rimar0e7ed912019-02-09 11:34:28 +0000911 const ELFYAML::DynamicSection &Section,
912 ContiguousBlobAccumulator &CBA) {
George Rimard063c7d2019-02-20 13:58:43 +0000913 typedef typename ELFT::uint uintX_t;
914
George Rimar0e7ed912019-02-09 11:34:28 +0000915 assert(Section.Type == llvm::ELF::SHT_DYNAMIC &&
916 "Section type is not SHT_DYNAMIC");
917
James Hendersonfd997802019-02-25 11:02:24 +0000918 if (!Section.Entries.empty() && Section.Content) {
919 WithColor::error()
920 << "Cannot specify both raw content and explicit entries "
921 "for dynamic section '"
922 << Section.Name << "'.\n";
923 return false;
924 }
925
926 if (Section.Content)
927 SHeader.sh_size = Section.Content->binary_size();
928 else
929 SHeader.sh_size = 2 * sizeof(uintX_t) * Section.Entries.size();
George Rimar0e7ed912019-02-09 11:34:28 +0000930 if (Section.EntSize)
931 SHeader.sh_entsize = *Section.EntSize;
932 else
933 SHeader.sh_entsize = sizeof(Elf_Dyn);
934
George Rimard063c7d2019-02-20 13:58:43 +0000935 raw_ostream &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
George Rimar0e7ed912019-02-09 11:34:28 +0000936 for (const ELFYAML::DynamicEntry &DE : Section.Entries) {
George Rimard063c7d2019-02-20 13:58:43 +0000937 support::endian::write<uintX_t>(OS, DE.Tag, ELFT::TargetEndianness);
938 support::endian::write<uintX_t>(OS, DE.Val, ELFT::TargetEndianness);
George Rimar0e7ed912019-02-09 11:34:28 +0000939 }
James Hendersonfd997802019-02-25 11:02:24 +0000940 if (Section.Content)
941 Section.Content->writeAsBinary(OS);
942
943 return true;
George Rimar0e7ed912019-02-09 11:34:28 +0000944}
945
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000946template <class ELFT> bool ELFState<ELFT>::buildSectionIndex() {
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000947 for (unsigned i = 0, e = Doc.Sections.size(); i != e; ++i) {
George Rimar09746882019-05-07 12:10:51 +0000948 StringRef Name = Doc.Sections[i]->Name;
George Rimar60dc5d42019-06-25 08:22:57 +0000949 DotShStrtab.add(dropUniqueSuffix(Name));
George Rimar09746882019-05-07 12:10:51 +0000950 // "+ 1" to take into account the SHT_NULL entry.
Puyan Lotfia10f0162019-05-11 17:03:36 +0000951 if (!SN2I.addName(Name, i + 1)) {
George Rimar09746882019-05-07 12:10:51 +0000952 WithColor::error() << "Repeated section name: '" << Name
953 << "' at YAML section number " << i << ".\n";
954 return false;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000955 }
Sean Silvaaff51252013-06-21 00:27:50 +0000956 }
Dave Lee17307d92017-11-09 14:53:43 +0000957
Dave Lee17307d92017-11-09 14:53:43 +0000958 DotShStrtab.finalize();
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000959 return true;
Sean Silva6b083882013-06-18 23:14:03 +0000960}
961
Sean Silvaf99309c2013-06-10 23:44:15 +0000962template <class ELFT>
George Rimar6da44ad2019-04-03 14:53:42 +0000963bool ELFState<ELFT>::buildSymbolIndex(ArrayRef<ELFYAML::Symbol> Symbols) {
964 bool GlobalSymbolSeen = false;
George Rimar33e498b2019-03-11 16:10:02 +0000965 std::size_t I = 0;
George Rimar6da44ad2019-04-03 14:53:42 +0000966 for (const auto &Sym : Symbols) {
967 ++I;
968
969 StringRef Name = Sym.Name;
970 if (Sym.Binding.value == ELF::STB_LOCAL && GlobalSymbolSeen) {
971 WithColor::error() << "Local symbol '" + Name +
972 "' after global in Symbols list.\n";
973 return false;
974 }
George Rimar09746882019-05-07 12:10:51 +0000975 if (Sym.Binding.value != ELF::STB_LOCAL)
976 GlobalSymbolSeen = true;
977
Puyan Lotfia10f0162019-05-11 17:03:36 +0000978 if (!Name.empty() && !SymN2I.addName(Name, I)) {
George Rimar09746882019-05-07 12:10:51 +0000979 WithColor::error() << "Repeated symbol name: '" << Name << "'.\n";
980 return false;
981 }
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000982 }
983 return true;
984}
985
George Rimar0621b792019-02-19 14:53:48 +0000986template <class ELFT> void ELFState<ELFT>::finalizeStrings() {
George Rimar0621b792019-02-19 14:53:48 +0000987 // Add the regular symbol names to .strtab section.
George Rimar6da44ad2019-04-03 14:53:42 +0000988 for (const ELFYAML::Symbol &Sym : Doc.Symbols)
George Rimar60dc5d42019-06-25 08:22:57 +0000989 DotStrtab.add(dropUniqueSuffix(Sym.Name));
George Rimar0621b792019-02-19 14:53:48 +0000990 DotStrtab.finalize();
991
George Rimar0621b792019-02-19 14:53:48 +0000992 // Add the dynamic symbol names to .dynstr section.
George Rimar6da44ad2019-04-03 14:53:42 +0000993 for (const ELFYAML::Symbol &Sym : Doc.DynamicSymbols)
George Rimar60dc5d42019-06-25 08:22:57 +0000994 DotDynstr.add(dropUniqueSuffix(Sym.Name));
George Rimar0621b792019-02-19 14:53:48 +0000995
George Rimar623ae722019-02-21 12:21:43 +0000996 // SHT_GNU_verdef and SHT_GNU_verneed sections might also
997 // add strings to .dynstr section.
George Rimar0621b792019-02-19 14:53:48 +0000998 for (const std::unique_ptr<ELFYAML::Section> &Sec : Doc.Sections) {
George Rimar623ae722019-02-21 12:21:43 +0000999 if (auto VerNeed = dyn_cast<ELFYAML::VerneedSection>(Sec.get())) {
1000 for (const ELFYAML::VerneedEntry &VE : VerNeed->VerneedV) {
1001 DotDynstr.add(VE.File);
1002 for (const ELFYAML::VernauxEntry &Aux : VE.AuxV)
1003 DotDynstr.add(Aux.Name);
1004 }
1005 } else if (auto VerDef = dyn_cast<ELFYAML::VerdefSection>(Sec.get())) {
1006 for (const ELFYAML::VerdefEntry &E : VerDef->Entries)
1007 for (StringRef Name : E.VerNames)
1008 DotDynstr.add(Name);
George Rimar0621b792019-02-19 14:53:48 +00001009 }
1010 }
1011
1012 DotDynstr.finalize();
1013}
1014
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +00001015template <class ELFT>
George Rimar13a364e2019-07-22 12:01:52 +00001016int ELFState<ELFT>::writeELF(raw_ostream &OS, ELFYAML::Object &Doc) {
Simon Atanasyan220c54a2014-04-02 16:34:40 +00001017 ELFState<ELFT> State(Doc);
George Rimar0621b792019-02-19 14:53:48 +00001018
1019 // Finalize .strtab and .dynstr sections. We do that early because want to
1020 // finalize the string table builders before writing the content of the
1021 // sections that might want to use them.
1022 State.finalizeStrings();
1023
Simon Atanasyan220c54a2014-04-02 16:34:40 +00001024 if (!State.buildSectionIndex())
1025 return 1;
1026
George Rimar33e498b2019-03-11 16:10:02 +00001027 if (!State.buildSymbolIndex(Doc.Symbols))
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +00001028 return 1;
1029
Sean Silva38205932013-06-13 22:19:48 +00001030 Elf_Ehdr Header;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +00001031 State.initELFHeader(Header);
Sean Silvaf99309c2013-06-10 23:44:15 +00001032
Sean Silva38205932013-06-13 22:19:48 +00001033 // TODO: Flesh out section header support.
Petr Hosekeb04da32017-07-19 20:38:46 +00001034
1035 std::vector<Elf_Phdr> PHeaders;
1036 State.initProgramHeaders(PHeaders);
Sean Silva38205932013-06-13 22:19:48 +00001037
Sean Silva08a75ae2013-06-20 19:11:44 +00001038 // XXX: This offset is tightly coupled with the order that we write
1039 // things to `OS`.
Petr Hosekeb04da32017-07-19 20:38:46 +00001040 const size_t SectionContentBeginOffset = Header.e_ehsize +
1041 Header.e_phentsize * Header.e_phnum +
1042 Header.e_shentsize * Header.e_shnum;
Sean Silva08a75ae2013-06-20 19:11:44 +00001043 ContiguousBlobAccumulator CBA(SectionContentBeginOffset);
Sean Silvac1c290b2013-06-20 20:59:34 +00001044
Sean Silva38205932013-06-13 22:19:48 +00001045 std::vector<Elf_Shdr> SHeaders;
George Rimar66296dc2019-06-05 13:16:53 +00001046 if (!State.initSectionHeaders(State, SHeaders, CBA))
Simon Atanasyan3ee21b02014-04-02 16:34:54 +00001047 return 1;
Sean Silva38205932013-06-13 22:19:48 +00001048
Petr Hosekeb04da32017-07-19 20:38:46 +00001049 // Now we can decide segment offsets
1050 State.setProgramHeaderLayout(PHeaders, SHeaders);
1051
Sean Silvaf99309c2013-06-10 23:44:15 +00001052 OS.write((const char *)&Header, sizeof(Header));
Petr Hosekeb04da32017-07-19 20:38:46 +00001053 writeArrayData(OS, makeArrayRef(PHeaders));
Will Dietz0b48c732013-10-12 21:29:16 +00001054 writeArrayData(OS, makeArrayRef(SHeaders));
Sean Silva46dffff2013-06-13 22:20:01 +00001055 CBA.writeBlobToStream(OS);
Sean Silva415d93f2013-06-17 20:14:59 +00001056 return 0;
Sean Silvaf99309c2013-06-10 23:44:15 +00001057}
1058
Chris Bieneman8ff0c112016-06-27 19:53:53 +00001059int yaml2elf(llvm::ELFYAML::Object &Doc, raw_ostream &Out) {
George Rimarbc4d3c42019-04-29 12:25:01 +00001060 bool IsLE = Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB);
1061 bool Is64Bit = Doc.Header.Class == ELFYAML::ELF_ELFCLASS(ELF::ELFCLASS64);
1062 if (Is64Bit) {
1063 if (IsLE)
Rui Ueyama1b31eb92018-01-12 01:40:32 +00001064 return ELFState<object::ELF64LE>::writeELF(Out, Doc);
George Rimarbc4d3c42019-04-29 12:25:01 +00001065 return ELFState<object::ELF64BE>::writeELF(Out, Doc);
Sean Silvaf99309c2013-06-10 23:44:15 +00001066 }
George Rimarbc4d3c42019-04-29 12:25:01 +00001067 if (IsLE)
1068 return ELFState<object::ELF32LE>::writeELF(Out, Doc);
1069 return ELFState<object::ELF32BE>::writeELF(Out, Doc);
Sean Silvaf99309c2013-06-10 23:44:15 +00001070}