blob: fb23d1f7cf75bb6ceac7c51088f252b0cda75ff1 [file] [log] [blame]
Sean Silvaf99309c2013-06-10 23:44:15 +00001//===- yaml2elf - Convert YAML to a ELF object file -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// \file
11/// \brief The ELF component of yaml2obj.
12///
13//===----------------------------------------------------------------------===//
14
15#include "yaml2obj.h"
Will Dietz0b48c732013-10-12 21:29:16 +000016#include "llvm/ADT/ArrayRef.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000017#include "llvm/BinaryFormat/ELF.h"
Rafael Espindola97de4742014-07-03 02:01:39 +000018#include "llvm/MC/StringTableBuilder.h"
Michael J. Spencer126973b2013-08-08 22:27:13 +000019#include "llvm/Object/ELFObjectFile.h"
Rafael Espindolaebd91932016-03-01 19:15:06 +000020#include "llvm/ObjectYAML/ELFYAML.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);
Sean Silvad93323f2013-06-22 00:47:43 +000043 for (; CurrentOffset != AlignedOffset; ++CurrentOffset)
44 OS.write('\0');
45 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
61// sections and symbols can be referenced by name instead of by index.
Sean Silva2a74f702013-06-15 00:31:46 +000062namespace {
Simon Atanasyan35babf92014-04-06 09:02:55 +000063class NameToIdxMap {
Sean Silvaa6423eb2013-06-15 00:25:26 +000064 StringMap<int> Map;
65public:
66 /// \returns true if name is already present in the map.
Simon Atanasyan35babf92014-04-06 09:02:55 +000067 bool addName(StringRef Name, unsigned i) {
David Blaikie5106ce72014-11-19 05:49:42 +000068 return !Map.insert(std::make_pair(Name, (int)i)).second;
Sean Silvaa6423eb2013-06-15 00:25:26 +000069 }
70 /// \returns true if name is not present in the map
Simon Atanasyan35babf92014-04-06 09:02:55 +000071 bool lookup(StringRef Name, unsigned &Idx) const {
72 StringMap<int>::const_iterator I = Map.find(Name);
Sean Silvaa6423eb2013-06-15 00:25:26 +000073 if (I == Map.end())
74 return true;
75 Idx = I->getValue();
76 return false;
77 }
Dave Lee17307d92017-11-09 14:53:43 +000078 /// asserts if name is not present in the map
79 unsigned get(StringRef Name) const {
80 unsigned Idx = 0;
81 auto missing = lookup(Name, Idx);
82 (void)missing;
83 assert(!missing && "Expected section not found in index");
84 return Idx;
85 }
86 unsigned size() const { return Map.size(); }
Sean Silvaa6423eb2013-06-15 00:25:26 +000087};
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 {
106/// \brief "Single point of truth" for the ELF file construction.
107/// 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;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000117
Dave Lee67b49662017-11-16 18:10:15 +0000118 enum class SymtabType { Static, Dynamic };
119
Sean Silva08a75ae2013-06-20 19:11:44 +0000120 /// \brief The future ".strtab" section.
Rafael Espindola21956e42015-10-23 21:48:05 +0000121 StringTableBuilder DotStrtab{StringTableBuilder::ELF};
Sean Silva08a75ae2013-06-20 19:11:44 +0000122
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000123 /// \brief The future ".shstrtab" section.
Rafael Espindola21956e42015-10-23 21:48:05 +0000124 StringTableBuilder DotShStrtab{StringTableBuilder::ELF};
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000125
Dave Lee67b49662017-11-16 18:10:15 +0000126 /// \brief The future ".dynstr" section.
127 StringTableBuilder DotDynstr{StringTableBuilder::ELF};
128
Simon Atanasyan35babf92014-04-06 09:02:55 +0000129 NameToIdxMap SN2I;
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000130 NameToIdxMap SymN2I;
Simon Atanasyan220c54a2014-04-02 16:34:40 +0000131 const ELFYAML::Object &Doc;
Sean Silvac1c290b2013-06-20 20:59:34 +0000132
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000133 bool buildSectionIndex();
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000134 bool buildSymbolIndex(std::size_t &StartIndex,
135 const std::vector<ELFYAML::Symbol> &Symbols);
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000136 void initELFHeader(Elf_Ehdr &Header);
Petr Hosekeb04da32017-07-19 20:38:46 +0000137 void initProgramHeaders(std::vector<Elf_Phdr> &PHeaders);
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000138 bool initSectionHeaders(std::vector<Elf_Shdr> &SHeaders,
139 ContiguousBlobAccumulator &CBA);
Dave Lee67b49662017-11-16 18:10:15 +0000140 void initSymtabSectionHeader(Elf_Shdr &SHeader, SymtabType STType,
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000141 ContiguousBlobAccumulator &CBA);
142 void initStrtabSectionHeader(Elf_Shdr &SHeader, StringRef Name,
143 StringTableBuilder &STB,
144 ContiguousBlobAccumulator &CBA);
Petr Hosekeb04da32017-07-19 20:38:46 +0000145 void setProgramHeaderLayout(std::vector<Elf_Phdr> &PHeaders,
146 std::vector<Elf_Shdr> &SHeaders);
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000147 void addSymbols(const std::vector<ELFYAML::Symbol> &Symbols,
Dave Lee67b49662017-11-16 18:10:15 +0000148 std::vector<Elf_Sym> &Syms, unsigned SymbolBinding,
149 const StringTableBuilder &Strtab);
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000150 void writeSectionContent(Elf_Shdr &SHeader,
151 const ELFYAML::RawContentSection &Section,
152 ContiguousBlobAccumulator &CBA);
153 bool writeSectionContent(Elf_Shdr &SHeader,
154 const ELFYAML::RelocationSection &Section,
155 ContiguousBlobAccumulator &CBA);
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000156 bool writeSectionContent(Elf_Shdr &SHeader, const ELFYAML::Group &Group,
157 ContiguousBlobAccumulator &CBA);
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000158 bool writeSectionContent(Elf_Shdr &SHeader,
159 const ELFYAML::MipsABIFlags &Section,
160 ContiguousBlobAccumulator &CBA);
Dave Lee67b49662017-11-16 18:10:15 +0000161 bool hasDynamicSymbols() const;
162 SmallVector<const char *, 5> implicitSectionNames() const;
Sean Silva08a75ae2013-06-20 19:11:44 +0000163
Simon Atanasyan220c54a2014-04-02 16:34:40 +0000164 // - SHT_NULL entry (placed first, i.e. 0'th entry)
Dave Lee67b49662017-11-16 18:10:15 +0000165 // - symbol table (.symtab) (defaults to after last yaml section)
166 // - string table (.strtab) (defaults to after .symtab)
167 // - section header string table (.shstrtab) (defaults to after .strtab)
168 // - dynamic symbol table (.dynsym) (defaults to after .shstrtab)
169 // - dynamic string table (.dynstr) (defaults to after .dynsym)
Dave Lee17307d92017-11-09 14:53:43 +0000170 unsigned getDotSymTabSecNo() const { return SN2I.get(".symtab"); }
171 unsigned getDotStrTabSecNo() const { return SN2I.get(".strtab"); }
172 unsigned getDotShStrTabSecNo() const { return SN2I.get(".shstrtab"); }
Dave Lee67b49662017-11-16 18:10:15 +0000173 unsigned getDotDynSymSecNo() const { return SN2I.get(".dynsym"); }
174 unsigned getDotDynStrSecNo() const { return SN2I.get(".dynstr"); }
Dave Lee17307d92017-11-09 14:53:43 +0000175 unsigned getSectionCount() const { return SN2I.size() + 1; }
Simon Atanasyan220c54a2014-04-02 16:34:40 +0000176
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000177 ELFState(const ELFYAML::Object &D) : Doc(D) {}
Simon Atanasyan220c54a2014-04-02 16:34:40 +0000178
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000179public:
180 static int writeELF(raw_ostream &OS, const ELFYAML::Object &Doc);
Sean Silva08a75ae2013-06-20 19:11:44 +0000181};
182} // end anonymous namespace
183
Sean Silva37e817c2013-06-21 00:33:01 +0000184template <class ELFT>
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000185void ELFState<ELFT>::initELFHeader(Elf_Ehdr &Header) {
186 using namespace llvm::ELF;
187 zero(Header);
188 Header.e_ident[EI_MAG0] = 0x7f;
189 Header.e_ident[EI_MAG1] = 'E';
190 Header.e_ident[EI_MAG2] = 'L';
191 Header.e_ident[EI_MAG3] = 'F';
192 Header.e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;
193 bool IsLittleEndian = ELFT::TargetEndianness == support::little;
194 Header.e_ident[EI_DATA] = IsLittleEndian ? ELFDATA2LSB : ELFDATA2MSB;
195 Header.e_ident[EI_VERSION] = EV_CURRENT;
196 Header.e_ident[EI_OSABI] = Doc.Header.OSABI;
197 Header.e_ident[EI_ABIVERSION] = 0;
198 Header.e_type = Doc.Header.Type;
199 Header.e_machine = Doc.Header.Machine;
200 Header.e_version = EV_CURRENT;
201 Header.e_entry = Doc.Header.Entry;
Petr Hosekeb04da32017-07-19 20:38:46 +0000202 Header.e_phoff = sizeof(Header);
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000203 Header.e_flags = Doc.Header.Flags;
204 Header.e_ehsize = sizeof(Elf_Ehdr);
Petr Hosekeb04da32017-07-19 20:38:46 +0000205 Header.e_phentsize = sizeof(Elf_Phdr);
206 Header.e_phnum = Doc.ProgramHeaders.size();
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000207 Header.e_shentsize = sizeof(Elf_Shdr);
Petr Hosekeb04da32017-07-19 20:38:46 +0000208 // Immediately following the ELF header and program headers.
209 Header.e_shoff =
210 sizeof(Header) + sizeof(Elf_Phdr) * Doc.ProgramHeaders.size();
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000211 Header.e_shnum = getSectionCount();
212 Header.e_shstrndx = getDotShStrTabSecNo();
213}
214
215template <class ELFT>
Petr Hosekeb04da32017-07-19 20:38:46 +0000216void ELFState<ELFT>::initProgramHeaders(std::vector<Elf_Phdr> &PHeaders) {
217 for (const auto &YamlPhdr : Doc.ProgramHeaders) {
218 Elf_Phdr Phdr;
219 Phdr.p_type = YamlPhdr.Type;
220 Phdr.p_flags = YamlPhdr.Flags;
221 Phdr.p_vaddr = YamlPhdr.VAddr;
222 Phdr.p_paddr = YamlPhdr.PAddr;
223 PHeaders.push_back(Phdr);
224 }
225}
226
227template <class ELFT>
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000228bool ELFState<ELFT>::initSectionHeaders(std::vector<Elf_Shdr> &SHeaders,
229 ContiguousBlobAccumulator &CBA) {
230 // Ensure SHN_UNDEF entry is present. An all-zero section header is a
231 // valid SHN_UNDEF entry since SHT_NULL == 0.
232 Elf_Shdr SHeader;
233 zero(SHeader);
234 SHeaders.push_back(SHeader);
235
236 for (const auto &Sec : Doc.Sections) {
237 zero(SHeader);
Hans Wennborg59f0cba2014-04-30 19:38:09 +0000238 SHeader.sh_name = DotShStrtab.getOffset(Sec->Name);
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000239 SHeader.sh_type = Sec->Type;
240 SHeader.sh_flags = Sec->Flags;
241 SHeader.sh_addr = Sec->Address;
242 SHeader.sh_addralign = Sec->AddressAlign;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000243
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000244 if (!Sec->Link.empty()) {
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000245 unsigned Index;
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000246 if (SN2I.lookup(Sec->Link, Index)) {
Jonas Devlieghere2cd41eb2018-04-21 21:11:59 +0000247 WithColor::error() << "Unknown section referenced: '" << Sec->Link
248 << "' at YAML section '" << Sec->Name << "'.\n";
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000249 return false;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000250 }
251 SHeader.sh_link = Index;
252 }
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000253
254 if (auto S = dyn_cast<ELFYAML::RawContentSection>(Sec.get()))
255 writeSectionContent(SHeader, *S, CBA);
256 else if (auto S = dyn_cast<ELFYAML::RelocationSection>(Sec.get())) {
257 if (S->Link.empty())
258 // For relocation section set link to .symtab by default.
259 SHeader.sh_link = getDotSymTabSecNo();
260
261 unsigned Index;
262 if (SN2I.lookup(S->Info, Index)) {
Michael J. Spencer572d7422015-08-27 23:11:20 +0000263 if (S->Info.getAsInteger(0, Index)) {
Jonas Devlieghere2cd41eb2018-04-21 21:11:59 +0000264 WithColor::error() << "Unknown section referenced: '" << S->Info
265 << "' at YAML section '" << S->Name << "'.\n";
Michael J. Spencer572d7422015-08-27 23:11:20 +0000266 return false;
267 }
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000268 }
269 SHeader.sh_info = Index;
270
271 if (!writeSectionContent(SHeader, *S, CBA))
272 return false;
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000273 } else if (auto S = dyn_cast<ELFYAML::Group>(Sec.get())) {
274 unsigned SymIdx;
275 if (SymN2I.lookup(S->Info, SymIdx)) {
Jonas Devlieghere2cd41eb2018-04-21 21:11:59 +0000276 WithColor::error() << "Unknown symbol referenced: '" << S->Info
277 << "' at YAML section '" << S->Name << "'.\n";
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000278 return false;
279 }
280 SHeader.sh_info = SymIdx;
281 if (!writeSectionContent(SHeader, *S, CBA))
282 return false;
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000283 } else if (auto S = dyn_cast<ELFYAML::MipsABIFlags>(Sec.get())) {
284 if (!writeSectionContent(SHeader, *S, CBA))
285 return false;
Simon Atanasyan5db02762015-07-03 23:00:54 +0000286 } else if (auto S = dyn_cast<ELFYAML::NoBitsSection>(Sec.get())) {
287 SHeader.sh_entsize = 0;
288 SHeader.sh_size = S->Size;
289 // SHT_NOBITS section does not have content
290 // so just to setup the section offset.
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000291 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000292 } else
293 llvm_unreachable("Unknown section type");
294
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000295 SHeaders.push_back(SHeader);
296 }
297 return true;
298}
299
300template <class ELFT>
301void ELFState<ELFT>::initSymtabSectionHeader(Elf_Shdr &SHeader,
Dave Lee67b49662017-11-16 18:10:15 +0000302 SymtabType STType,
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000303 ContiguousBlobAccumulator &CBA) {
304 zero(SHeader);
Dave Lee67b49662017-11-16 18:10:15 +0000305 bool IsStatic = STType == SymtabType::Static;
306 SHeader.sh_name = DotShStrtab.getOffset(IsStatic ? ".symtab" : ".dynsym");
307 SHeader.sh_type = IsStatic ? ELF::SHT_SYMTAB : ELF::SHT_DYNSYM;
308 SHeader.sh_link = IsStatic ? getDotStrTabSecNo() : getDotDynStrSecNo();
309 const auto &Symbols = IsStatic ? Doc.Symbols : Doc.DynamicSymbols;
310 auto &Strtab = IsStatic ? DotStrtab : DotDynstr;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000311 // One greater than symbol table index of the last local symbol.
Dave Lee67b49662017-11-16 18:10:15 +0000312 SHeader.sh_info = Symbols.Local.size() + 1;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000313 SHeader.sh_entsize = sizeof(Elf_Sym);
Simon Atanasyan3a120922015-07-09 18:23:02 +0000314 SHeader.sh_addralign = 8;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000315
316 std::vector<Elf_Sym> Syms;
317 {
318 // Ensure STN_UNDEF is present
319 Elf_Sym Sym;
320 zero(Sym);
321 Syms.push_back(Sym);
322 }
Hans Wennborg59f0cba2014-04-30 19:38:09 +0000323
Dave Lee67b49662017-11-16 18:10:15 +0000324 // Add symbol names to .strtab or .dynstr.
325 for (const auto &Sym : Symbols.Local)
326 Strtab.add(Sym.Name);
327 for (const auto &Sym : Symbols.Global)
328 Strtab.add(Sym.Name);
329 for (const auto &Sym : Symbols.Weak)
330 Strtab.add(Sym.Name);
331 Strtab.finalize();
Hans Wennborg59f0cba2014-04-30 19:38:09 +0000332
Dave Lee67b49662017-11-16 18:10:15 +0000333 addSymbols(Symbols.Local, Syms, ELF::STB_LOCAL, Strtab);
334 addSymbols(Symbols.Global, Syms, ELF::STB_GLOBAL, Strtab);
335 addSymbols(Symbols.Weak, Syms, ELF::STB_WEAK, Strtab);
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000336
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000337 writeArrayData(
338 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign),
339 makeArrayRef(Syms));
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000340 SHeader.sh_size = arrayDataSize(makeArrayRef(Syms));
341}
342
343template <class ELFT>
344void ELFState<ELFT>::initStrtabSectionHeader(Elf_Shdr &SHeader, StringRef Name,
345 StringTableBuilder &STB,
346 ContiguousBlobAccumulator &CBA) {
347 zero(SHeader);
Hans Wennborg59f0cba2014-04-30 19:38:09 +0000348 SHeader.sh_name = DotShStrtab.getOffset(Name);
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000349 SHeader.sh_type = ELF::SHT_STRTAB;
Rafael Espindola39751af2016-10-04 22:43:25 +0000350 STB.write(CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign));
351 SHeader.sh_size = STB.getSize();
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000352 SHeader.sh_addralign = 1;
353}
354
355template <class ELFT>
Petr Hosekeb04da32017-07-19 20:38:46 +0000356void ELFState<ELFT>::setProgramHeaderLayout(std::vector<Elf_Phdr> &PHeaders,
357 std::vector<Elf_Shdr> &SHeaders) {
358 uint32_t PhdrIdx = 0;
359 for (auto &YamlPhdr : Doc.ProgramHeaders) {
360 auto &PHeader = PHeaders[PhdrIdx++];
361
362 if (YamlPhdr.Sections.size())
363 PHeader.p_offset = UINT32_MAX;
364 else
365 PHeader.p_offset = 0;
366
367 // Find the minimum offset for the program header.
368 for (auto SecName : YamlPhdr.Sections) {
369 uint32_t Index = 0;
370 SN2I.lookup(SecName.Section, Index);
371 const auto &SHeader = SHeaders[Index];
372 PHeader.p_offset = std::min(PHeader.p_offset, SHeader.sh_offset);
373 }
374
375 // Find the maximum offset of the end of a section in order to set p_filesz.
376 PHeader.p_filesz = 0;
377 for (auto SecName : YamlPhdr.Sections) {
378 uint32_t Index = 0;
379 SN2I.lookup(SecName.Section, Index);
380 const auto &SHeader = SHeaders[Index];
381 uint64_t EndOfSection;
382 if (SHeader.sh_type == llvm::ELF::SHT_NOBITS)
383 EndOfSection = SHeader.sh_offset;
384 else
385 EndOfSection = SHeader.sh_offset + SHeader.sh_size;
386 uint64_t EndOfSegment = PHeader.p_offset + PHeader.p_filesz;
387 EndOfSegment = std::max(EndOfSegment, EndOfSection);
388 PHeader.p_filesz = EndOfSegment - PHeader.p_offset;
389 }
390
391 // Find the memory size by adding the size of sections at the end of the
392 // segment. These should be empty (size of zero) and NOBITS sections.
393 PHeader.p_memsz = PHeader.p_filesz;
394 for (auto SecName : YamlPhdr.Sections) {
395 uint32_t Index = 0;
396 SN2I.lookup(SecName.Section, Index);
397 const auto &SHeader = SHeaders[Index];
398 if (SHeader.sh_offset == PHeader.p_offset + PHeader.p_filesz)
399 PHeader.p_memsz += SHeader.sh_size;
400 }
401
402 // Set the alignment of the segment to be the same as the maximum alignment
Jake Ehrlich03aeeb092017-11-01 23:14:48 +0000403 // of the sections with the same offset so that by default the segment
Petr Hosekeb04da32017-07-19 20:38:46 +0000404 // has a valid and sensible alignment.
Jake Ehrlich03aeeb092017-11-01 23:14:48 +0000405 if (YamlPhdr.Align) {
406 PHeader.p_align = *YamlPhdr.Align;
407 } else {
408 PHeader.p_align = 1;
409 for (auto SecName : YamlPhdr.Sections) {
410 uint32_t Index = 0;
411 SN2I.lookup(SecName.Section, Index);
412 const auto &SHeader = SHeaders[Index];
413 if (SHeader.sh_offset == PHeader.p_offset)
414 PHeader.p_align = std::max(PHeader.p_align, SHeader.sh_addralign);
415 }
Petr Hosekeb04da32017-07-19 20:38:46 +0000416 }
417 }
418}
419
420template <class ELFT>
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000421void ELFState<ELFT>::addSymbols(const std::vector<ELFYAML::Symbol> &Symbols,
422 std::vector<Elf_Sym> &Syms,
Dave Lee67b49662017-11-16 18:10:15 +0000423 unsigned SymbolBinding,
424 const StringTableBuilder &Strtab) {
Simon Atanasyan048baca2014-03-14 06:53:30 +0000425 for (const auto &Sym : Symbols) {
Sean Silva6b083882013-06-18 23:14:03 +0000426 Elf_Sym Symbol;
427 zero(Symbol);
428 if (!Sym.Name.empty())
Dave Lee67b49662017-11-16 18:10:15 +0000429 Symbol.st_name = Strtab.getOffset(Sym.Name);
Sean Silvaaff51252013-06-21 00:27:50 +0000430 Symbol.setBindingAndType(SymbolBinding, Sym.Type);
Sean Silvac4afa6d2013-06-21 01:11:48 +0000431 if (!Sym.Section.empty()) {
432 unsigned Index;
Simon Atanasyan35babf92014-04-06 09:02:55 +0000433 if (SN2I.lookup(Sym.Section, Index)) {
Jonas Devlieghere2cd41eb2018-04-21 21:11:59 +0000434 WithColor::error() << "Unknown section referenced: '" << Sym.Section
435 << "' by YAML symbol " << Sym.Name << ".\n";
Sean Silvac4afa6d2013-06-21 01:11:48 +0000436 exit(1);
437 }
438 Symbol.st_shndx = Index;
Petr Hosek5c469a32017-09-07 20:44:16 +0000439 } else if (Sym.Index) {
440 Symbol.st_shndx = *Sym.Index;
441 }
442 // else Symbol.st_shndex == SHN_UNDEF (== 0), since it was zero'd earlier.
Sean Silva05001b92013-06-20 20:59:47 +0000443 Symbol.st_value = Sym.Value;
Simon Atanasyan60e1a792014-11-06 22:46:24 +0000444 Symbol.st_other = Sym.Other;
Sean Silva05001b92013-06-20 20:59:47 +0000445 Symbol.st_size = Sym.Size;
Sean Silva6b083882013-06-18 23:14:03 +0000446 Syms.push_back(Symbol);
447 }
Sean Silvaaff51252013-06-21 00:27:50 +0000448}
449
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000450template <class ELFT>
451void
452ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
453 const ELFYAML::RawContentSection &Section,
454 ContiguousBlobAccumulator &CBA) {
Simon Atanasyanb83f3802014-05-16 16:01:00 +0000455 assert(Section.Size >= Section.Content.binary_size() &&
456 "Section size and section content are inconsistent");
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000457 raw_ostream &OS =
458 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
Simon Atanasyanb83f3802014-05-16 16:01:00 +0000459 Section.Content.writeAsBinary(OS);
460 for (auto i = Section.Content.binary_size(); i < Section.Size; ++i)
461 OS.write(0);
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000462 SHeader.sh_entsize = 0;
Simon Atanasyanb83f3802014-05-16 16:01:00 +0000463 SHeader.sh_size = Section.Size;
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000464}
465
Simon Atanasyan5d19c672015-01-25 13:29:25 +0000466static bool isMips64EL(const ELFYAML::Object &Doc) {
467 return Doc.Header.Machine == ELFYAML::ELF_EM(llvm::ELF::EM_MIPS) &&
468 Doc.Header.Class == ELFYAML::ELF_ELFCLASS(ELF::ELFCLASS64) &&
469 Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB);
470}
471
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000472template <class ELFT>
473bool
474ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
475 const ELFYAML::RelocationSection &Section,
476 ContiguousBlobAccumulator &CBA) {
Simon Atanasyan8eb9d1b2015-05-08 07:05:04 +0000477 assert((Section.Type == llvm::ELF::SHT_REL ||
478 Section.Type == llvm::ELF::SHT_RELA) &&
479 "Section type is not SHT_REL nor SHT_RELA");
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000480
481 bool IsRela = Section.Type == llvm::ELF::SHT_RELA;
482 SHeader.sh_entsize = IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
483 SHeader.sh_size = SHeader.sh_entsize * Section.Relocations.size();
484
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000485 auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000486
487 for (const auto &Rel : Section.Relocations) {
Adhemerval Zanella9f3dbff2015-04-22 15:26:43 +0000488 unsigned SymIdx = 0;
489 // Some special relocation, R_ARM_v4BX for instance, does not have
490 // an external reference. So it ignores the return value of lookup()
491 // here.
Petr Hosek5aa80f12017-08-30 23:13:31 +0000492 if (Rel.Symbol)
493 SymN2I.lookup(*Rel.Symbol, SymIdx);
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000494
495 if (IsRela) {
496 Elf_Rela REntry;
497 zero(REntry);
498 REntry.r_offset = Rel.Offset;
499 REntry.r_addend = Rel.Addend;
Simon Atanasyan5d19c672015-01-25 13:29:25 +0000500 REntry.setSymbolAndType(SymIdx, Rel.Type, isMips64EL(Doc));
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000501 OS.write((const char *)&REntry, sizeof(REntry));
502 } else {
503 Elf_Rel REntry;
504 zero(REntry);
505 REntry.r_offset = Rel.Offset;
Simon Atanasyan5d19c672015-01-25 13:29:25 +0000506 REntry.setSymbolAndType(SymIdx, Rel.Type, isMips64EL(Doc));
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000507 OS.write((const char *)&REntry, sizeof(REntry));
508 }
509 }
510 return true;
511}
512
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000513template <class ELFT>
514bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
515 const ELFYAML::Group &Section,
516 ContiguousBlobAccumulator &CBA) {
Rui Ueyama478d6352018-01-12 02:28:31 +0000517 typedef typename ELFT::Word Elf_Word;
Simon Atanasyan8eb9d1b2015-05-08 07:05:04 +0000518 assert(Section.Type == llvm::ELF::SHT_GROUP &&
519 "Section type is not SHT_GROUP");
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000520
521 SHeader.sh_entsize = sizeof(Elf_Word);
522 SHeader.sh_size = SHeader.sh_entsize * Section.Members.size();
523
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000524 auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000525
526 for (auto member : Section.Members) {
527 Elf_Word SIdx;
528 unsigned int sectionIndex = 0;
529 if (member.sectionNameOrType == "GRP_COMDAT")
530 sectionIndex = llvm::ELF::GRP_COMDAT;
531 else if (SN2I.lookup(member.sectionNameOrType, sectionIndex)) {
Jonas Devlieghere2cd41eb2018-04-21 21:11:59 +0000532 WithColor::error() << "Unknown section referenced: '"
533 << member.sectionNameOrType << "' at YAML section' "
534 << Section.Name << "\n";
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000535 return false;
536 }
537 SIdx = sectionIndex;
538 OS.write((const char *)&SIdx, sizeof(SIdx));
539 }
540 return true;
541}
542
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000543template <class ELFT>
544bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
545 const ELFYAML::MipsABIFlags &Section,
546 ContiguousBlobAccumulator &CBA) {
Simon Atanasyan8eb9d1b2015-05-08 07:05:04 +0000547 assert(Section.Type == llvm::ELF::SHT_MIPS_ABIFLAGS &&
548 "Section type is not SHT_MIPS_ABIFLAGS");
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000549
550 object::Elf_Mips_ABIFlags<ELFT> Flags;
551 zero(Flags);
552 SHeader.sh_entsize = sizeof(Flags);
553 SHeader.sh_size = SHeader.sh_entsize;
554
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000555 auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000556 Flags.version = Section.Version;
557 Flags.isa_level = Section.ISALevel;
558 Flags.isa_rev = Section.ISARevision;
559 Flags.gpr_size = Section.GPRSize;
560 Flags.cpr1_size = Section.CPR1Size;
561 Flags.cpr2_size = Section.CPR2Size;
562 Flags.fp_abi = Section.FpABI;
563 Flags.isa_ext = Section.ISAExtension;
564 Flags.ases = Section.ASEs;
565 Flags.flags1 = Section.Flags1;
566 Flags.flags2 = Section.Flags2;
567 OS.write((const char *)&Flags, sizeof(Flags));
568
569 return true;
570}
571
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000572template <class ELFT> bool ELFState<ELFT>::buildSectionIndex() {
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000573 for (unsigned i = 0, e = Doc.Sections.size(); i != e; ++i) {
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000574 StringRef Name = Doc.Sections[i]->Name;
Dave Lee17307d92017-11-09 14:53:43 +0000575 DotShStrtab.add(Name);
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000576 // "+ 1" to take into account the SHT_NULL entry.
577 if (SN2I.addName(Name, i + 1)) {
Jonas Devlieghere2cd41eb2018-04-21 21:11:59 +0000578 WithColor::error() << "Repeated section name: '" << Name
579 << "' at YAML section number " << i << ".\n";
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000580 return false;
581 }
Sean Silvaaff51252013-06-21 00:27:50 +0000582 }
Dave Lee17307d92017-11-09 14:53:43 +0000583
584 auto SecNo = 1 + Doc.Sections.size();
585 // Add special sections after input sections, if necessary.
Dave Lee67b49662017-11-16 18:10:15 +0000586 for (const auto &Name : implicitSectionNames())
Dave Lee17307d92017-11-09 14:53:43 +0000587 if (!SN2I.addName(Name, SecNo)) {
588 // Account for this section, since it wasn't in the Doc
589 ++SecNo;
590 DotShStrtab.add(Name);
591 }
592
593 DotShStrtab.finalize();
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000594 return true;
Sean Silva6b083882013-06-18 23:14:03 +0000595}
596
Sean Silvaf99309c2013-06-10 23:44:15 +0000597template <class ELFT>
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000598bool
599ELFState<ELFT>::buildSymbolIndex(std::size_t &StartIndex,
600 const std::vector<ELFYAML::Symbol> &Symbols) {
601 for (const auto &Sym : Symbols) {
602 ++StartIndex;
603 if (Sym.Name.empty())
604 continue;
605 if (SymN2I.addName(Sym.Name, StartIndex)) {
Jonas Devlieghere2cd41eb2018-04-21 21:11:59 +0000606 WithColor::error() << "Repeated symbol name: '" << Sym.Name << "'.\n";
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000607 return false;
608 }
609 }
610 return true;
611}
612
613template <class ELFT>
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000614int ELFState<ELFT>::writeELF(raw_ostream &OS, const ELFYAML::Object &Doc) {
Simon Atanasyan220c54a2014-04-02 16:34:40 +0000615 ELFState<ELFT> State(Doc);
616 if (!State.buildSectionIndex())
617 return 1;
618
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000619 std::size_t StartSymIndex = 0;
620 if (!State.buildSymbolIndex(StartSymIndex, Doc.Symbols.Local) ||
621 !State.buildSymbolIndex(StartSymIndex, Doc.Symbols.Global) ||
622 !State.buildSymbolIndex(StartSymIndex, Doc.Symbols.Weak))
623 return 1;
624
Sean Silva38205932013-06-13 22:19:48 +0000625 Elf_Ehdr Header;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000626 State.initELFHeader(Header);
Sean Silvaf99309c2013-06-10 23:44:15 +0000627
Sean Silva38205932013-06-13 22:19:48 +0000628 // TODO: Flesh out section header support.
Petr Hosekeb04da32017-07-19 20:38:46 +0000629
630 std::vector<Elf_Phdr> PHeaders;
631 State.initProgramHeaders(PHeaders);
Sean Silva38205932013-06-13 22:19:48 +0000632
Sean Silva08a75ae2013-06-20 19:11:44 +0000633 // XXX: This offset is tightly coupled with the order that we write
634 // things to `OS`.
Petr Hosekeb04da32017-07-19 20:38:46 +0000635 const size_t SectionContentBeginOffset = Header.e_ehsize +
636 Header.e_phentsize * Header.e_phnum +
637 Header.e_shentsize * Header.e_shnum;
Sean Silva08a75ae2013-06-20 19:11:44 +0000638 ContiguousBlobAccumulator CBA(SectionContentBeginOffset);
Sean Silvac1c290b2013-06-20 20:59:34 +0000639
Sean Silva38205932013-06-13 22:19:48 +0000640 std::vector<Elf_Shdr> SHeaders;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000641 if(!State.initSectionHeaders(SHeaders, CBA))
642 return 1;
Sean Silva38205932013-06-13 22:19:48 +0000643
Dave Lee17307d92017-11-09 14:53:43 +0000644 // Populate SHeaders with implicit sections not present in the Doc
Dave Lee67b49662017-11-16 18:10:15 +0000645 for (const auto &Name : State.implicitSectionNames())
Dave Lee17307d92017-11-09 14:53:43 +0000646 if (State.SN2I.get(Name) >= SHeaders.size())
647 SHeaders.push_back({});
Sean Silva82177572013-06-22 01:38:00 +0000648
Dave Lee17307d92017-11-09 14:53:43 +0000649 // Initialize the implicit sections
650 auto Index = State.SN2I.get(".symtab");
Dave Lee67b49662017-11-16 18:10:15 +0000651 State.initSymtabSectionHeader(SHeaders[Index], SymtabType::Static, CBA);
Dave Lee17307d92017-11-09 14:53:43 +0000652 Index = State.SN2I.get(".strtab");
653 State.initStrtabSectionHeader(SHeaders[Index], ".strtab", State.DotStrtab, CBA);
654 Index = State.SN2I.get(".shstrtab");
655 State.initStrtabSectionHeader(SHeaders[Index], ".shstrtab", State.DotShStrtab, CBA);
Dave Lee67b49662017-11-16 18:10:15 +0000656 if (State.hasDynamicSymbols()) {
657 Index = State.SN2I.get(".dynsym");
658 State.initSymtabSectionHeader(SHeaders[Index], SymtabType::Dynamic, CBA);
659 SHeaders[Index].sh_flags |= ELF::SHF_ALLOC;
660 Index = State.SN2I.get(".dynstr");
661 State.initStrtabSectionHeader(SHeaders[Index], ".dynstr", State.DotDynstr, CBA);
662 SHeaders[Index].sh_flags |= ELF::SHF_ALLOC;
663 }
Sean Silvaf99309c2013-06-10 23:44:15 +0000664
Petr Hosekeb04da32017-07-19 20:38:46 +0000665 // Now we can decide segment offsets
666 State.setProgramHeaderLayout(PHeaders, SHeaders);
667
Sean Silvaf99309c2013-06-10 23:44:15 +0000668 OS.write((const char *)&Header, sizeof(Header));
Petr Hosekeb04da32017-07-19 20:38:46 +0000669 writeArrayData(OS, makeArrayRef(PHeaders));
Will Dietz0b48c732013-10-12 21:29:16 +0000670 writeArrayData(OS, makeArrayRef(SHeaders));
Sean Silva46dffff2013-06-13 22:20:01 +0000671 CBA.writeBlobToStream(OS);
Sean Silva415d93f2013-06-17 20:14:59 +0000672 return 0;
Sean Silvaf99309c2013-06-10 23:44:15 +0000673}
674
Dave Lee67b49662017-11-16 18:10:15 +0000675template <class ELFT> bool ELFState<ELFT>::hasDynamicSymbols() const {
676 return Doc.DynamicSymbols.Global.size() > 0 ||
677 Doc.DynamicSymbols.Weak.size() > 0 ||
678 Doc.DynamicSymbols.Local.size() > 0;
679}
680
681template <class ELFT> SmallVector<const char *, 5> ELFState<ELFT>::implicitSectionNames() const {
682 if (!hasDynamicSymbols())
683 return {".symtab", ".strtab", ".shstrtab"};
684 return {".symtab", ".strtab", ".shstrtab", ".dynsym", ".dynstr"};
685}
686
Sean Silva11caeba2013-06-22 01:03:35 +0000687static bool is64Bit(const ELFYAML::Object &Doc) {
688 return Doc.Header.Class == ELFYAML::ELF_ELFCLASS(ELF::ELFCLASS64);
689}
690
691static bool isLittleEndian(const ELFYAML::Object &Doc) {
692 return Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB);
693}
694
Chris Bieneman8ff0c112016-06-27 19:53:53 +0000695int yaml2elf(llvm::ELFYAML::Object &Doc, raw_ostream &Out) {
Sean Silva11caeba2013-06-22 01:03:35 +0000696 if (is64Bit(Doc)) {
697 if (isLittleEndian(Doc))
Rui Ueyama1b31eb92018-01-12 01:40:32 +0000698 return ELFState<object::ELF64LE>::writeELF(Out, Doc);
Sean Silvaf99309c2013-06-10 23:44:15 +0000699 else
Rui Ueyama1b31eb92018-01-12 01:40:32 +0000700 return ELFState<object::ELF64BE>::writeELF(Out, Doc);
Sean Silvaf99309c2013-06-10 23:44:15 +0000701 } else {
Sean Silva11caeba2013-06-22 01:03:35 +0000702 if (isLittleEndian(Doc))
Rui Ueyama1b31eb92018-01-12 01:40:32 +0000703 return ELFState<object::ELF32LE>::writeELF(Out, Doc);
Sean Silvaf99309c2013-06-10 23:44:15 +0000704 else
Rui Ueyama1b31eb92018-01-12 01:40:32 +0000705 return ELFState<object::ELF32BE>::writeELF(Out, Doc);
Sean Silvaf99309c2013-06-10 23:44:15 +0000706 }
Sean Silvaf99309c2013-06-10 23:44:15 +0000707}