blob: fce910a093dedc1d2891db555e6c15f4663dbb5d [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"
22#include "llvm/Support/YAMLTraits.h"
23#include "llvm/Support/raw_ostream.h"
24
25using namespace llvm;
26
Sean Silva46dffff2013-06-13 22:20:01 +000027// This class is used to build up a contiguous binary blob while keeping
28// track of an offset in the output (which notionally begins at
29// `InitialOffset`).
Sean Silva2a74f702013-06-15 00:31:46 +000030namespace {
Sean Silva46dffff2013-06-13 22:20:01 +000031class ContiguousBlobAccumulator {
32 const uint64_t InitialOffset;
Sean Silvabd3bc692013-06-20 19:11:41 +000033 SmallVector<char, 128> Buf;
Sean Silva46dffff2013-06-13 22:20:01 +000034 raw_svector_ostream OS;
35
Sean Silvad93323f2013-06-22 00:47:43 +000036 /// \returns The new offset.
37 uint64_t padToAlignment(unsigned Align) {
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +000038 if (Align == 0)
39 Align = 1;
Sean Silvad93323f2013-06-22 00:47:43 +000040 uint64_t CurrentOffset = InitialOffset + OS.tell();
Rui Ueyamada00f2f2016-01-14 21:06:47 +000041 uint64_t AlignedOffset = alignTo(CurrentOffset, Align);
Sean Silvad93323f2013-06-22 00:47:43 +000042 for (; CurrentOffset != AlignedOffset; ++CurrentOffset)
43 OS.write('\0');
44 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
60// sections and symbols can be referenced by name instead of by index.
Sean Silva2a74f702013-06-15 00:31:46 +000061namespace {
Simon Atanasyan35babf92014-04-06 09:02:55 +000062class NameToIdxMap {
Sean Silvaa6423eb2013-06-15 00:25:26 +000063 StringMap<int> Map;
64public:
65 /// \returns true if name is already present in the map.
Simon Atanasyan35babf92014-04-06 09:02:55 +000066 bool addName(StringRef Name, unsigned i) {
David Blaikie5106ce72014-11-19 05:49:42 +000067 return !Map.insert(std::make_pair(Name, (int)i)).second;
Sean Silvaa6423eb2013-06-15 00:25:26 +000068 }
69 /// \returns true if name is not present in the map
Simon Atanasyan35babf92014-04-06 09:02:55 +000070 bool lookup(StringRef Name, unsigned &Idx) const {
71 StringMap<int>::const_iterator I = Map.find(Name);
Sean Silvaa6423eb2013-06-15 00:25:26 +000072 if (I == Map.end())
73 return true;
74 Idx = I->getValue();
75 return false;
76 }
Dave Lee17307d92017-11-09 14:53:43 +000077 /// asserts if name is not present in the map
78 unsigned get(StringRef Name) const {
79 unsigned Idx = 0;
80 auto missing = lookup(Name, Idx);
81 (void)missing;
82 assert(!missing && "Expected section not found in index");
83 return Idx;
84 }
85 unsigned size() const { return Map.size(); }
Sean Silvaa6423eb2013-06-15 00:25:26 +000086};
Sean Silva2a74f702013-06-15 00:31:46 +000087} // end anonymous namespace
Sean Silvaa6423eb2013-06-15 00:25:26 +000088
Sean Silva38205932013-06-13 22:19:48 +000089template <class T>
Will Dietz0b48c732013-10-12 21:29:16 +000090static size_t arrayDataSize(ArrayRef<T> A) {
91 return A.size() * sizeof(T);
Sean Silva38205932013-06-13 22:19:48 +000092}
93
94template <class T>
Will Dietz0b48c732013-10-12 21:29:16 +000095static void writeArrayData(raw_ostream &OS, ArrayRef<T> A) {
96 OS.write((const char *)A.data(), arrayDataSize(A));
Sean Silva38205932013-06-13 22:19:48 +000097}
98
99template <class T>
100static void zero(T &Obj) {
101 memset(&Obj, 0, sizeof(Obj));
102}
103
Sean Silva08a75ae2013-06-20 19:11:44 +0000104namespace {
105/// \brief "Single point of truth" for the ELF file construction.
106/// TODO: This class still has a ways to go before it is truly a "single
107/// point of truth".
108template <class ELFT>
109class ELFState {
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000110 typedef typename object::ELFFile<ELFT>::Elf_Ehdr Elf_Ehdr;
Petr Hosekeb04da32017-07-19 20:38:46 +0000111 typedef typename object::ELFFile<ELFT>::Elf_Phdr Elf_Phdr;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000112 typedef typename object::ELFFile<ELFT>::Elf_Shdr Elf_Shdr;
113 typedef typename object::ELFFile<ELFT>::Elf_Sym Elf_Sym;
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000114 typedef typename object::ELFFile<ELFT>::Elf_Rel Elf_Rel;
115 typedef typename object::ELFFile<ELFT>::Elf_Rela Elf_Rela;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000116
Sean Silva08a75ae2013-06-20 19:11:44 +0000117 /// \brief The future ".strtab" section.
Rafael Espindola21956e42015-10-23 21:48:05 +0000118 StringTableBuilder DotStrtab{StringTableBuilder::ELF};
Sean Silva08a75ae2013-06-20 19:11:44 +0000119
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000120 /// \brief The future ".shstrtab" section.
Rafael Espindola21956e42015-10-23 21:48:05 +0000121 StringTableBuilder DotShStrtab{StringTableBuilder::ELF};
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000122
Simon Atanasyan35babf92014-04-06 09:02:55 +0000123 NameToIdxMap SN2I;
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000124 NameToIdxMap SymN2I;
Simon Atanasyan220c54a2014-04-02 16:34:40 +0000125 const ELFYAML::Object &Doc;
Sean Silvac1c290b2013-06-20 20:59:34 +0000126
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000127 bool buildSectionIndex();
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000128 bool buildSymbolIndex(std::size_t &StartIndex,
129 const std::vector<ELFYAML::Symbol> &Symbols);
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000130 void initELFHeader(Elf_Ehdr &Header);
Petr Hosekeb04da32017-07-19 20:38:46 +0000131 void initProgramHeaders(std::vector<Elf_Phdr> &PHeaders);
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000132 bool initSectionHeaders(std::vector<Elf_Shdr> &SHeaders,
133 ContiguousBlobAccumulator &CBA);
134 void initSymtabSectionHeader(Elf_Shdr &SHeader,
135 ContiguousBlobAccumulator &CBA);
136 void initStrtabSectionHeader(Elf_Shdr &SHeader, StringRef Name,
137 StringTableBuilder &STB,
138 ContiguousBlobAccumulator &CBA);
Petr Hosekeb04da32017-07-19 20:38:46 +0000139 void setProgramHeaderLayout(std::vector<Elf_Phdr> &PHeaders,
140 std::vector<Elf_Shdr> &SHeaders);
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000141 void addSymbols(const std::vector<ELFYAML::Symbol> &Symbols,
142 std::vector<Elf_Sym> &Syms, unsigned SymbolBinding);
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000143 void writeSectionContent(Elf_Shdr &SHeader,
144 const ELFYAML::RawContentSection &Section,
145 ContiguousBlobAccumulator &CBA);
146 bool writeSectionContent(Elf_Shdr &SHeader,
147 const ELFYAML::RelocationSection &Section,
148 ContiguousBlobAccumulator &CBA);
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000149 bool writeSectionContent(Elf_Shdr &SHeader, const ELFYAML::Group &Group,
150 ContiguousBlobAccumulator &CBA);
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000151 bool writeSectionContent(Elf_Shdr &SHeader,
152 const ELFYAML::MipsABIFlags &Section,
153 ContiguousBlobAccumulator &CBA);
Sean Silva08a75ae2013-06-20 19:11:44 +0000154
Simon Atanasyan220c54a2014-04-02 16:34:40 +0000155 // - SHT_NULL entry (placed first, i.e. 0'th entry)
Dave Lee17307d92017-11-09 14:53:43 +0000156 // - symbol table (.symtab) (defaults to third to last)
157 // - string table (.strtab) (defaults to second to last)
158 // - section header string table (.shstrtab) (defaults to last)
159 unsigned getDotSymTabSecNo() const { return SN2I.get(".symtab"); }
160 unsigned getDotStrTabSecNo() const { return SN2I.get(".strtab"); }
161 unsigned getDotShStrTabSecNo() const { return SN2I.get(".shstrtab"); }
162 unsigned getSectionCount() const { return SN2I.size() + 1; }
Simon Atanasyan220c54a2014-04-02 16:34:40 +0000163
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000164 ELFState(const ELFYAML::Object &D) : Doc(D) {}
Simon Atanasyan220c54a2014-04-02 16:34:40 +0000165
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000166public:
167 static int writeELF(raw_ostream &OS, const ELFYAML::Object &Doc);
Sean Silva08a75ae2013-06-20 19:11:44 +0000168};
Dave Lee17307d92017-11-09 14:53:43 +0000169
170static const char * const ImplicitSecNames[] = {".symtab", ".strtab", ".shstrtab"};
Sean Silva08a75ae2013-06-20 19:11:44 +0000171} // end anonymous namespace
172
Sean Silva37e817c2013-06-21 00:33:01 +0000173template <class ELFT>
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000174void ELFState<ELFT>::initELFHeader(Elf_Ehdr &Header) {
175 using namespace llvm::ELF;
176 zero(Header);
177 Header.e_ident[EI_MAG0] = 0x7f;
178 Header.e_ident[EI_MAG1] = 'E';
179 Header.e_ident[EI_MAG2] = 'L';
180 Header.e_ident[EI_MAG3] = 'F';
181 Header.e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;
182 bool IsLittleEndian = ELFT::TargetEndianness == support::little;
183 Header.e_ident[EI_DATA] = IsLittleEndian ? ELFDATA2LSB : ELFDATA2MSB;
184 Header.e_ident[EI_VERSION] = EV_CURRENT;
185 Header.e_ident[EI_OSABI] = Doc.Header.OSABI;
186 Header.e_ident[EI_ABIVERSION] = 0;
187 Header.e_type = Doc.Header.Type;
188 Header.e_machine = Doc.Header.Machine;
189 Header.e_version = EV_CURRENT;
190 Header.e_entry = Doc.Header.Entry;
Petr Hosekeb04da32017-07-19 20:38:46 +0000191 Header.e_phoff = sizeof(Header);
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000192 Header.e_flags = Doc.Header.Flags;
193 Header.e_ehsize = sizeof(Elf_Ehdr);
Petr Hosekeb04da32017-07-19 20:38:46 +0000194 Header.e_phentsize = sizeof(Elf_Phdr);
195 Header.e_phnum = Doc.ProgramHeaders.size();
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000196 Header.e_shentsize = sizeof(Elf_Shdr);
Petr Hosekeb04da32017-07-19 20:38:46 +0000197 // Immediately following the ELF header and program headers.
198 Header.e_shoff =
199 sizeof(Header) + sizeof(Elf_Phdr) * Doc.ProgramHeaders.size();
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000200 Header.e_shnum = getSectionCount();
201 Header.e_shstrndx = getDotShStrTabSecNo();
202}
203
204template <class ELFT>
Petr Hosekeb04da32017-07-19 20:38:46 +0000205void ELFState<ELFT>::initProgramHeaders(std::vector<Elf_Phdr> &PHeaders) {
206 for (const auto &YamlPhdr : Doc.ProgramHeaders) {
207 Elf_Phdr Phdr;
208 Phdr.p_type = YamlPhdr.Type;
209 Phdr.p_flags = YamlPhdr.Flags;
210 Phdr.p_vaddr = YamlPhdr.VAddr;
211 Phdr.p_paddr = YamlPhdr.PAddr;
212 PHeaders.push_back(Phdr);
213 }
214}
215
216template <class ELFT>
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000217bool ELFState<ELFT>::initSectionHeaders(std::vector<Elf_Shdr> &SHeaders,
218 ContiguousBlobAccumulator &CBA) {
219 // Ensure SHN_UNDEF entry is present. An all-zero section header is a
220 // valid SHN_UNDEF entry since SHT_NULL == 0.
221 Elf_Shdr SHeader;
222 zero(SHeader);
223 SHeaders.push_back(SHeader);
224
225 for (const auto &Sec : Doc.Sections) {
226 zero(SHeader);
Hans Wennborg59f0cba2014-04-30 19:38:09 +0000227 SHeader.sh_name = DotShStrtab.getOffset(Sec->Name);
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000228 SHeader.sh_type = Sec->Type;
229 SHeader.sh_flags = Sec->Flags;
230 SHeader.sh_addr = Sec->Address;
231 SHeader.sh_addralign = Sec->AddressAlign;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000232
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000233 if (!Sec->Link.empty()) {
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000234 unsigned Index;
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000235 if (SN2I.lookup(Sec->Link, Index)) {
236 errs() << "error: Unknown section referenced: '" << Sec->Link
237 << "' at YAML section '" << Sec->Name << "'.\n";
238 return false;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000239 }
240 SHeader.sh_link = Index;
241 }
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000242
243 if (auto S = dyn_cast<ELFYAML::RawContentSection>(Sec.get()))
244 writeSectionContent(SHeader, *S, CBA);
245 else if (auto S = dyn_cast<ELFYAML::RelocationSection>(Sec.get())) {
246 if (S->Link.empty())
247 // For relocation section set link to .symtab by default.
248 SHeader.sh_link = getDotSymTabSecNo();
249
250 unsigned Index;
251 if (SN2I.lookup(S->Info, Index)) {
Michael J. Spencer572d7422015-08-27 23:11:20 +0000252 if (S->Info.getAsInteger(0, Index)) {
253 errs() << "error: Unknown section referenced: '" << S->Info
254 << "' at YAML section '" << S->Name << "'.\n";
255 return false;
256 }
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000257 }
258 SHeader.sh_info = Index;
259
260 if (!writeSectionContent(SHeader, *S, CBA))
261 return false;
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000262 } else if (auto S = dyn_cast<ELFYAML::Group>(Sec.get())) {
263 unsigned SymIdx;
264 if (SymN2I.lookup(S->Info, SymIdx)) {
265 errs() << "error: Unknown symbol referenced: '" << S->Info
266 << "' at YAML section '" << S->Name << "'.\n";
267 return false;
268 }
269 SHeader.sh_info = SymIdx;
270 if (!writeSectionContent(SHeader, *S, CBA))
271 return false;
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000272 } else if (auto S = dyn_cast<ELFYAML::MipsABIFlags>(Sec.get())) {
273 if (!writeSectionContent(SHeader, *S, CBA))
274 return false;
Simon Atanasyan5db02762015-07-03 23:00:54 +0000275 } else if (auto S = dyn_cast<ELFYAML::NoBitsSection>(Sec.get())) {
276 SHeader.sh_entsize = 0;
277 SHeader.sh_size = S->Size;
278 // SHT_NOBITS section does not have content
279 // so just to setup the section offset.
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000280 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000281 } else
282 llvm_unreachable("Unknown section type");
283
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000284 SHeaders.push_back(SHeader);
285 }
286 return true;
287}
288
289template <class ELFT>
290void ELFState<ELFT>::initSymtabSectionHeader(Elf_Shdr &SHeader,
291 ContiguousBlobAccumulator &CBA) {
292 zero(SHeader);
Hans Wennborg59f0cba2014-04-30 19:38:09 +0000293 SHeader.sh_name = DotShStrtab.getOffset(".symtab");
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000294 SHeader.sh_type = ELF::SHT_SYMTAB;
295 SHeader.sh_link = getDotStrTabSecNo();
296 // One greater than symbol table index of the last local symbol.
297 SHeader.sh_info = Doc.Symbols.Local.size() + 1;
298 SHeader.sh_entsize = sizeof(Elf_Sym);
Simon Atanasyan3a120922015-07-09 18:23:02 +0000299 SHeader.sh_addralign = 8;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000300
301 std::vector<Elf_Sym> Syms;
302 {
303 // Ensure STN_UNDEF is present
304 Elf_Sym Sym;
305 zero(Sym);
306 Syms.push_back(Sym);
307 }
Hans Wennborg59f0cba2014-04-30 19:38:09 +0000308
309 // Add symbol names to .strtab.
310 for (const auto &Sym : Doc.Symbols.Local)
311 DotStrtab.add(Sym.Name);
312 for (const auto &Sym : Doc.Symbols.Global)
313 DotStrtab.add(Sym.Name);
314 for (const auto &Sym : Doc.Symbols.Weak)
315 DotStrtab.add(Sym.Name);
Rafael Espindola21956e42015-10-23 21:48:05 +0000316 DotStrtab.finalize();
Hans Wennborg59f0cba2014-04-30 19:38:09 +0000317
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000318 addSymbols(Doc.Symbols.Local, Syms, ELF::STB_LOCAL);
319 addSymbols(Doc.Symbols.Global, Syms, ELF::STB_GLOBAL);
320 addSymbols(Doc.Symbols.Weak, Syms, ELF::STB_WEAK);
321
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000322 writeArrayData(
323 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign),
324 makeArrayRef(Syms));
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000325 SHeader.sh_size = arrayDataSize(makeArrayRef(Syms));
326}
327
328template <class ELFT>
329void ELFState<ELFT>::initStrtabSectionHeader(Elf_Shdr &SHeader, StringRef Name,
330 StringTableBuilder &STB,
331 ContiguousBlobAccumulator &CBA) {
332 zero(SHeader);
Hans Wennborg59f0cba2014-04-30 19:38:09 +0000333 SHeader.sh_name = DotShStrtab.getOffset(Name);
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000334 SHeader.sh_type = ELF::SHT_STRTAB;
Rafael Espindola39751af2016-10-04 22:43:25 +0000335 STB.write(CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign));
336 SHeader.sh_size = STB.getSize();
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000337 SHeader.sh_addralign = 1;
338}
339
340template <class ELFT>
Petr Hosekeb04da32017-07-19 20:38:46 +0000341void ELFState<ELFT>::setProgramHeaderLayout(std::vector<Elf_Phdr> &PHeaders,
342 std::vector<Elf_Shdr> &SHeaders) {
343 uint32_t PhdrIdx = 0;
344 for (auto &YamlPhdr : Doc.ProgramHeaders) {
345 auto &PHeader = PHeaders[PhdrIdx++];
346
347 if (YamlPhdr.Sections.size())
348 PHeader.p_offset = UINT32_MAX;
349 else
350 PHeader.p_offset = 0;
351
352 // Find the minimum offset for the program header.
353 for (auto SecName : YamlPhdr.Sections) {
354 uint32_t Index = 0;
355 SN2I.lookup(SecName.Section, Index);
356 const auto &SHeader = SHeaders[Index];
357 PHeader.p_offset = std::min(PHeader.p_offset, SHeader.sh_offset);
358 }
359
360 // Find the maximum offset of the end of a section in order to set p_filesz.
361 PHeader.p_filesz = 0;
362 for (auto SecName : YamlPhdr.Sections) {
363 uint32_t Index = 0;
364 SN2I.lookup(SecName.Section, Index);
365 const auto &SHeader = SHeaders[Index];
366 uint64_t EndOfSection;
367 if (SHeader.sh_type == llvm::ELF::SHT_NOBITS)
368 EndOfSection = SHeader.sh_offset;
369 else
370 EndOfSection = SHeader.sh_offset + SHeader.sh_size;
371 uint64_t EndOfSegment = PHeader.p_offset + PHeader.p_filesz;
372 EndOfSegment = std::max(EndOfSegment, EndOfSection);
373 PHeader.p_filesz = EndOfSegment - PHeader.p_offset;
374 }
375
376 // Find the memory size by adding the size of sections at the end of the
377 // segment. These should be empty (size of zero) and NOBITS sections.
378 PHeader.p_memsz = PHeader.p_filesz;
379 for (auto SecName : YamlPhdr.Sections) {
380 uint32_t Index = 0;
381 SN2I.lookup(SecName.Section, Index);
382 const auto &SHeader = SHeaders[Index];
383 if (SHeader.sh_offset == PHeader.p_offset + PHeader.p_filesz)
384 PHeader.p_memsz += SHeader.sh_size;
385 }
386
387 // Set the alignment of the segment to be the same as the maximum alignment
Jake Ehrlich03aeeb092017-11-01 23:14:48 +0000388 // of the sections with the same offset so that by default the segment
Petr Hosekeb04da32017-07-19 20:38:46 +0000389 // has a valid and sensible alignment.
Jake Ehrlich03aeeb092017-11-01 23:14:48 +0000390 if (YamlPhdr.Align) {
391 PHeader.p_align = *YamlPhdr.Align;
392 } else {
393 PHeader.p_align = 1;
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)
399 PHeader.p_align = std::max(PHeader.p_align, SHeader.sh_addralign);
400 }
Petr Hosekeb04da32017-07-19 20:38:46 +0000401 }
402 }
403}
404
405template <class ELFT>
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000406void ELFState<ELFT>::addSymbols(const std::vector<ELFYAML::Symbol> &Symbols,
407 std::vector<Elf_Sym> &Syms,
408 unsigned SymbolBinding) {
Simon Atanasyan048baca2014-03-14 06:53:30 +0000409 for (const auto &Sym : Symbols) {
Sean Silva6b083882013-06-18 23:14:03 +0000410 Elf_Sym Symbol;
411 zero(Symbol);
412 if (!Sym.Name.empty())
Hans Wennborg59f0cba2014-04-30 19:38:09 +0000413 Symbol.st_name = DotStrtab.getOffset(Sym.Name);
Sean Silvaaff51252013-06-21 00:27:50 +0000414 Symbol.setBindingAndType(SymbolBinding, Sym.Type);
Sean Silvac4afa6d2013-06-21 01:11:48 +0000415 if (!Sym.Section.empty()) {
416 unsigned Index;
Simon Atanasyan35babf92014-04-06 09:02:55 +0000417 if (SN2I.lookup(Sym.Section, Index)) {
Sean Silvac4afa6d2013-06-21 01:11:48 +0000418 errs() << "error: Unknown section referenced: '" << Sym.Section
419 << "' by YAML symbol " << Sym.Name << ".\n";
420 exit(1);
421 }
422 Symbol.st_shndx = Index;
Petr Hosek5c469a32017-09-07 20:44:16 +0000423 } else if (Sym.Index) {
424 Symbol.st_shndx = *Sym.Index;
425 }
426 // else Symbol.st_shndex == SHN_UNDEF (== 0), since it was zero'd earlier.
Sean Silva05001b92013-06-20 20:59:47 +0000427 Symbol.st_value = Sym.Value;
Simon Atanasyan60e1a792014-11-06 22:46:24 +0000428 Symbol.st_other = Sym.Other;
Sean Silva05001b92013-06-20 20:59:47 +0000429 Symbol.st_size = Sym.Size;
Sean Silva6b083882013-06-18 23:14:03 +0000430 Syms.push_back(Symbol);
431 }
Sean Silvaaff51252013-06-21 00:27:50 +0000432}
433
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000434template <class ELFT>
435void
436ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
437 const ELFYAML::RawContentSection &Section,
438 ContiguousBlobAccumulator &CBA) {
Simon Atanasyanb83f3802014-05-16 16:01:00 +0000439 assert(Section.Size >= Section.Content.binary_size() &&
440 "Section size and section content are inconsistent");
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000441 raw_ostream &OS =
442 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
Simon Atanasyanb83f3802014-05-16 16:01:00 +0000443 Section.Content.writeAsBinary(OS);
444 for (auto i = Section.Content.binary_size(); i < Section.Size; ++i)
445 OS.write(0);
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000446 SHeader.sh_entsize = 0;
Simon Atanasyanb83f3802014-05-16 16:01:00 +0000447 SHeader.sh_size = Section.Size;
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000448}
449
Simon Atanasyan5d19c672015-01-25 13:29:25 +0000450static bool isMips64EL(const ELFYAML::Object &Doc) {
451 return Doc.Header.Machine == ELFYAML::ELF_EM(llvm::ELF::EM_MIPS) &&
452 Doc.Header.Class == ELFYAML::ELF_ELFCLASS(ELF::ELFCLASS64) &&
453 Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB);
454}
455
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000456template <class ELFT>
457bool
458ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
459 const ELFYAML::RelocationSection &Section,
460 ContiguousBlobAccumulator &CBA) {
Simon Atanasyan8eb9d1b2015-05-08 07:05:04 +0000461 assert((Section.Type == llvm::ELF::SHT_REL ||
462 Section.Type == llvm::ELF::SHT_RELA) &&
463 "Section type is not SHT_REL nor SHT_RELA");
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000464
465 bool IsRela = Section.Type == llvm::ELF::SHT_RELA;
466 SHeader.sh_entsize = IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
467 SHeader.sh_size = SHeader.sh_entsize * Section.Relocations.size();
468
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000469 auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000470
471 for (const auto &Rel : Section.Relocations) {
Adhemerval Zanella9f3dbff2015-04-22 15:26:43 +0000472 unsigned SymIdx = 0;
473 // Some special relocation, R_ARM_v4BX for instance, does not have
474 // an external reference. So it ignores the return value of lookup()
475 // here.
Petr Hosek5aa80f12017-08-30 23:13:31 +0000476 if (Rel.Symbol)
477 SymN2I.lookup(*Rel.Symbol, SymIdx);
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000478
479 if (IsRela) {
480 Elf_Rela REntry;
481 zero(REntry);
482 REntry.r_offset = Rel.Offset;
483 REntry.r_addend = Rel.Addend;
Simon Atanasyan5d19c672015-01-25 13:29:25 +0000484 REntry.setSymbolAndType(SymIdx, Rel.Type, isMips64EL(Doc));
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000485 OS.write((const char *)&REntry, sizeof(REntry));
486 } else {
487 Elf_Rel REntry;
488 zero(REntry);
489 REntry.r_offset = Rel.Offset;
Simon Atanasyan5d19c672015-01-25 13:29:25 +0000490 REntry.setSymbolAndType(SymIdx, Rel.Type, isMips64EL(Doc));
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000491 OS.write((const char *)&REntry, sizeof(REntry));
492 }
493 }
494 return true;
495}
496
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000497template <class ELFT>
498bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
499 const ELFYAML::Group &Section,
500 ContiguousBlobAccumulator &CBA) {
501 typedef typename object::ELFFile<ELFT>::Elf_Word Elf_Word;
Simon Atanasyan8eb9d1b2015-05-08 07:05:04 +0000502 assert(Section.Type == llvm::ELF::SHT_GROUP &&
503 "Section type is not SHT_GROUP");
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000504
505 SHeader.sh_entsize = sizeof(Elf_Word);
506 SHeader.sh_size = SHeader.sh_entsize * Section.Members.size();
507
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000508 auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000509
510 for (auto member : Section.Members) {
511 Elf_Word SIdx;
512 unsigned int sectionIndex = 0;
513 if (member.sectionNameOrType == "GRP_COMDAT")
514 sectionIndex = llvm::ELF::GRP_COMDAT;
515 else if (SN2I.lookup(member.sectionNameOrType, sectionIndex)) {
516 errs() << "error: Unknown section referenced: '"
517 << member.sectionNameOrType << "' at YAML section' "
518 << Section.Name << "\n";
519 return false;
520 }
521 SIdx = sectionIndex;
522 OS.write((const char *)&SIdx, sizeof(SIdx));
523 }
524 return true;
525}
526
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000527template <class ELFT>
528bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
529 const ELFYAML::MipsABIFlags &Section,
530 ContiguousBlobAccumulator &CBA) {
Simon Atanasyan8eb9d1b2015-05-08 07:05:04 +0000531 assert(Section.Type == llvm::ELF::SHT_MIPS_ABIFLAGS &&
532 "Section type is not SHT_MIPS_ABIFLAGS");
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000533
534 object::Elf_Mips_ABIFlags<ELFT> Flags;
535 zero(Flags);
536 SHeader.sh_entsize = sizeof(Flags);
537 SHeader.sh_size = SHeader.sh_entsize;
538
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000539 auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000540 Flags.version = Section.Version;
541 Flags.isa_level = Section.ISALevel;
542 Flags.isa_rev = Section.ISARevision;
543 Flags.gpr_size = Section.GPRSize;
544 Flags.cpr1_size = Section.CPR1Size;
545 Flags.cpr2_size = Section.CPR2Size;
546 Flags.fp_abi = Section.FpABI;
547 Flags.isa_ext = Section.ISAExtension;
548 Flags.ases = Section.ASEs;
549 Flags.flags1 = Section.Flags1;
550 Flags.flags2 = Section.Flags2;
551 OS.write((const char *)&Flags, sizeof(Flags));
552
553 return true;
554}
555
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000556template <class ELFT> bool ELFState<ELFT>::buildSectionIndex() {
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000557 for (unsigned i = 0, e = Doc.Sections.size(); i != e; ++i) {
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000558 StringRef Name = Doc.Sections[i]->Name;
Dave Lee17307d92017-11-09 14:53:43 +0000559 DotShStrtab.add(Name);
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000560 // "+ 1" to take into account the SHT_NULL entry.
561 if (SN2I.addName(Name, i + 1)) {
562 errs() << "error: Repeated section name: '" << Name
563 << "' at YAML section number " << i << ".\n";
564 return false;
565 }
Sean Silvaaff51252013-06-21 00:27:50 +0000566 }
Dave Lee17307d92017-11-09 14:53:43 +0000567
568 auto SecNo = 1 + Doc.Sections.size();
569 // Add special sections after input sections, if necessary.
570 for (const auto &Name : ImplicitSecNames)
571 if (!SN2I.addName(Name, SecNo)) {
572 // Account for this section, since it wasn't in the Doc
573 ++SecNo;
574 DotShStrtab.add(Name);
575 }
576
577 DotShStrtab.finalize();
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000578 return true;
Sean Silva6b083882013-06-18 23:14:03 +0000579}
580
Sean Silvaf99309c2013-06-10 23:44:15 +0000581template <class ELFT>
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000582bool
583ELFState<ELFT>::buildSymbolIndex(std::size_t &StartIndex,
584 const std::vector<ELFYAML::Symbol> &Symbols) {
585 for (const auto &Sym : Symbols) {
586 ++StartIndex;
587 if (Sym.Name.empty())
588 continue;
589 if (SymN2I.addName(Sym.Name, StartIndex)) {
590 errs() << "error: Repeated symbol name: '" << Sym.Name << "'.\n";
591 return false;
592 }
593 }
594 return true;
595}
596
597template <class ELFT>
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000598int ELFState<ELFT>::writeELF(raw_ostream &OS, const ELFYAML::Object &Doc) {
Simon Atanasyan220c54a2014-04-02 16:34:40 +0000599 ELFState<ELFT> State(Doc);
600 if (!State.buildSectionIndex())
601 return 1;
602
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000603 std::size_t StartSymIndex = 0;
604 if (!State.buildSymbolIndex(StartSymIndex, Doc.Symbols.Local) ||
605 !State.buildSymbolIndex(StartSymIndex, Doc.Symbols.Global) ||
606 !State.buildSymbolIndex(StartSymIndex, Doc.Symbols.Weak))
607 return 1;
608
Sean Silva38205932013-06-13 22:19:48 +0000609 Elf_Ehdr Header;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000610 State.initELFHeader(Header);
Sean Silvaf99309c2013-06-10 23:44:15 +0000611
Sean Silva38205932013-06-13 22:19:48 +0000612 // TODO: Flesh out section header support.
Petr Hosekeb04da32017-07-19 20:38:46 +0000613
614 std::vector<Elf_Phdr> PHeaders;
615 State.initProgramHeaders(PHeaders);
Sean Silva38205932013-06-13 22:19:48 +0000616
Sean Silva08a75ae2013-06-20 19:11:44 +0000617 // XXX: This offset is tightly coupled with the order that we write
618 // things to `OS`.
Petr Hosekeb04da32017-07-19 20:38:46 +0000619 const size_t SectionContentBeginOffset = Header.e_ehsize +
620 Header.e_phentsize * Header.e_phnum +
621 Header.e_shentsize * Header.e_shnum;
Sean Silva08a75ae2013-06-20 19:11:44 +0000622 ContiguousBlobAccumulator CBA(SectionContentBeginOffset);
Sean Silvac1c290b2013-06-20 20:59:34 +0000623
Sean Silva38205932013-06-13 22:19:48 +0000624 std::vector<Elf_Shdr> SHeaders;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000625 if(!State.initSectionHeaders(SHeaders, CBA))
626 return 1;
Sean Silva38205932013-06-13 22:19:48 +0000627
Dave Lee17307d92017-11-09 14:53:43 +0000628 // Populate SHeaders with implicit sections not present in the Doc
629 for (const auto &Name : ImplicitSecNames)
630 if (State.SN2I.get(Name) >= SHeaders.size())
631 SHeaders.push_back({});
Sean Silva82177572013-06-22 01:38:00 +0000632
Dave Lee17307d92017-11-09 14:53:43 +0000633 // Initialize the implicit sections
634 auto Index = State.SN2I.get(".symtab");
635 State.initSymtabSectionHeader(SHeaders[Index], CBA);
636 Index = State.SN2I.get(".strtab");
637 State.initStrtabSectionHeader(SHeaders[Index], ".strtab", State.DotStrtab, CBA);
638 Index = State.SN2I.get(".shstrtab");
639 State.initStrtabSectionHeader(SHeaders[Index], ".shstrtab", State.DotShStrtab, CBA);
Sean Silvaf99309c2013-06-10 23:44:15 +0000640
Petr Hosekeb04da32017-07-19 20:38:46 +0000641 // Now we can decide segment offsets
642 State.setProgramHeaderLayout(PHeaders, SHeaders);
643
Sean Silvaf99309c2013-06-10 23:44:15 +0000644 OS.write((const char *)&Header, sizeof(Header));
Petr Hosekeb04da32017-07-19 20:38:46 +0000645 writeArrayData(OS, makeArrayRef(PHeaders));
Will Dietz0b48c732013-10-12 21:29:16 +0000646 writeArrayData(OS, makeArrayRef(SHeaders));
Sean Silva46dffff2013-06-13 22:20:01 +0000647 CBA.writeBlobToStream(OS);
Sean Silva415d93f2013-06-17 20:14:59 +0000648 return 0;
Sean Silvaf99309c2013-06-10 23:44:15 +0000649}
650
Sean Silva11caeba2013-06-22 01:03:35 +0000651static bool is64Bit(const ELFYAML::Object &Doc) {
652 return Doc.Header.Class == ELFYAML::ELF_ELFCLASS(ELF::ELFCLASS64);
653}
654
655static bool isLittleEndian(const ELFYAML::Object &Doc) {
656 return Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB);
657}
658
Chris Bieneman8ff0c112016-06-27 19:53:53 +0000659int yaml2elf(llvm::ELFYAML::Object &Doc, raw_ostream &Out) {
Sean Silva11caeba2013-06-22 01:03:35 +0000660 using object::ELFType;
Rafael Espindolaac729b42015-06-02 12:05:27 +0000661 typedef ELFType<support::little, true> LE64;
662 typedef ELFType<support::big, true> BE64;
663 typedef ELFType<support::little, false> LE32;
664 typedef ELFType<support::big, false> BE32;
Sean Silva11caeba2013-06-22 01:03:35 +0000665 if (is64Bit(Doc)) {
666 if (isLittleEndian(Doc))
Simon Atanasyan73e047e2014-05-15 16:14:02 +0000667 return ELFState<LE64>::writeELF(Out, Doc);
Sean Silvaf99309c2013-06-10 23:44:15 +0000668 else
Simon Atanasyan73e047e2014-05-15 16:14:02 +0000669 return ELFState<BE64>::writeELF(Out, Doc);
Sean Silvaf99309c2013-06-10 23:44:15 +0000670 } else {
Sean Silva11caeba2013-06-22 01:03:35 +0000671 if (isLittleEndian(Doc))
Simon Atanasyan73e047e2014-05-15 16:14:02 +0000672 return ELFState<LE32>::writeELF(Out, Doc);
Sean Silvaf99309c2013-06-10 23:44:15 +0000673 else
Simon Atanasyan73e047e2014-05-15 16:14:02 +0000674 return ELFState<BE32>::writeELF(Out, Doc);
Sean Silvaf99309c2013-06-10 23:44:15 +0000675 }
Sean Silvaf99309c2013-06-10 23:44:15 +0000676}