blob: 1267a26dac2a5389402366b50a852fa744c3ed56 [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 {
Rui Ueyama478d6352018-01-12 02:28:31 +0000110 typedef typename ELFT::Ehdr Elf_Ehdr;
111 typedef typename ELFT::Phdr Elf_Phdr;
112 typedef typename ELFT::Shdr Elf_Shdr;
113 typedef typename ELFT::Sym Elf_Sym;
114 typedef typename ELFT::Rel Elf_Rel;
115 typedef typename ELFT::Rela Elf_Rela;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000116
Dave Lee67b49662017-11-16 18:10:15 +0000117 enum class SymtabType { Static, Dynamic };
118
Sean Silva08a75ae2013-06-20 19:11:44 +0000119 /// \brief The future ".strtab" section.
Rafael Espindola21956e42015-10-23 21:48:05 +0000120 StringTableBuilder DotStrtab{StringTableBuilder::ELF};
Sean Silva08a75ae2013-06-20 19:11:44 +0000121
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000122 /// \brief The future ".shstrtab" section.
Rafael Espindola21956e42015-10-23 21:48:05 +0000123 StringTableBuilder DotShStrtab{StringTableBuilder::ELF};
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000124
Dave Lee67b49662017-11-16 18:10:15 +0000125 /// \brief The future ".dynstr" section.
126 StringTableBuilder DotDynstr{StringTableBuilder::ELF};
127
Simon Atanasyan35babf92014-04-06 09:02:55 +0000128 NameToIdxMap SN2I;
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000129 NameToIdxMap SymN2I;
Simon Atanasyan220c54a2014-04-02 16:34:40 +0000130 const ELFYAML::Object &Doc;
Sean Silvac1c290b2013-06-20 20:59:34 +0000131
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000132 bool buildSectionIndex();
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000133 bool buildSymbolIndex(std::size_t &StartIndex,
134 const std::vector<ELFYAML::Symbol> &Symbols);
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000135 void initELFHeader(Elf_Ehdr &Header);
Petr Hosekeb04da32017-07-19 20:38:46 +0000136 void initProgramHeaders(std::vector<Elf_Phdr> &PHeaders);
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000137 bool initSectionHeaders(std::vector<Elf_Shdr> &SHeaders,
138 ContiguousBlobAccumulator &CBA);
Dave Lee67b49662017-11-16 18:10:15 +0000139 void initSymtabSectionHeader(Elf_Shdr &SHeader, SymtabType STType,
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000140 ContiguousBlobAccumulator &CBA);
141 void initStrtabSectionHeader(Elf_Shdr &SHeader, StringRef Name,
142 StringTableBuilder &STB,
143 ContiguousBlobAccumulator &CBA);
Petr Hosekeb04da32017-07-19 20:38:46 +0000144 void setProgramHeaderLayout(std::vector<Elf_Phdr> &PHeaders,
145 std::vector<Elf_Shdr> &SHeaders);
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000146 void addSymbols(const std::vector<ELFYAML::Symbol> &Symbols,
Dave Lee67b49662017-11-16 18:10:15 +0000147 std::vector<Elf_Sym> &Syms, unsigned SymbolBinding,
148 const StringTableBuilder &Strtab);
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000149 void writeSectionContent(Elf_Shdr &SHeader,
150 const ELFYAML::RawContentSection &Section,
151 ContiguousBlobAccumulator &CBA);
152 bool writeSectionContent(Elf_Shdr &SHeader,
153 const ELFYAML::RelocationSection &Section,
154 ContiguousBlobAccumulator &CBA);
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000155 bool writeSectionContent(Elf_Shdr &SHeader, const ELFYAML::Group &Group,
156 ContiguousBlobAccumulator &CBA);
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000157 bool writeSectionContent(Elf_Shdr &SHeader,
158 const ELFYAML::MipsABIFlags &Section,
159 ContiguousBlobAccumulator &CBA);
Dave Lee67b49662017-11-16 18:10:15 +0000160 bool hasDynamicSymbols() const;
161 SmallVector<const char *, 5> implicitSectionNames() const;
Sean Silva08a75ae2013-06-20 19:11:44 +0000162
Simon Atanasyan220c54a2014-04-02 16:34:40 +0000163 // - SHT_NULL entry (placed first, i.e. 0'th entry)
Dave Lee67b49662017-11-16 18:10:15 +0000164 // - symbol table (.symtab) (defaults to after last yaml section)
165 // - string table (.strtab) (defaults to after .symtab)
166 // - section header string table (.shstrtab) (defaults to after .strtab)
167 // - dynamic symbol table (.dynsym) (defaults to after .shstrtab)
168 // - dynamic string table (.dynstr) (defaults to after .dynsym)
Dave Lee17307d92017-11-09 14:53:43 +0000169 unsigned getDotSymTabSecNo() const { return SN2I.get(".symtab"); }
170 unsigned getDotStrTabSecNo() const { return SN2I.get(".strtab"); }
171 unsigned getDotShStrTabSecNo() const { return SN2I.get(".shstrtab"); }
Dave Lee67b49662017-11-16 18:10:15 +0000172 unsigned getDotDynSymSecNo() const { return SN2I.get(".dynsym"); }
173 unsigned getDotDynStrSecNo() const { return SN2I.get(".dynstr"); }
Dave Lee17307d92017-11-09 14:53:43 +0000174 unsigned getSectionCount() const { return SN2I.size() + 1; }
Simon Atanasyan220c54a2014-04-02 16:34:40 +0000175
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000176 ELFState(const ELFYAML::Object &D) : Doc(D) {}
Simon Atanasyan220c54a2014-04-02 16:34:40 +0000177
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000178public:
179 static int writeELF(raw_ostream &OS, const ELFYAML::Object &Doc);
Sean Silva08a75ae2013-06-20 19:11:44 +0000180};
181} // end anonymous namespace
182
Sean Silva37e817c2013-06-21 00:33:01 +0000183template <class ELFT>
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000184void ELFState<ELFT>::initELFHeader(Elf_Ehdr &Header) {
185 using namespace llvm::ELF;
186 zero(Header);
187 Header.e_ident[EI_MAG0] = 0x7f;
188 Header.e_ident[EI_MAG1] = 'E';
189 Header.e_ident[EI_MAG2] = 'L';
190 Header.e_ident[EI_MAG3] = 'F';
191 Header.e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;
192 bool IsLittleEndian = ELFT::TargetEndianness == support::little;
193 Header.e_ident[EI_DATA] = IsLittleEndian ? ELFDATA2LSB : ELFDATA2MSB;
194 Header.e_ident[EI_VERSION] = EV_CURRENT;
195 Header.e_ident[EI_OSABI] = Doc.Header.OSABI;
196 Header.e_ident[EI_ABIVERSION] = 0;
197 Header.e_type = Doc.Header.Type;
198 Header.e_machine = Doc.Header.Machine;
199 Header.e_version = EV_CURRENT;
200 Header.e_entry = Doc.Header.Entry;
Petr Hosekeb04da32017-07-19 20:38:46 +0000201 Header.e_phoff = sizeof(Header);
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000202 Header.e_flags = Doc.Header.Flags;
203 Header.e_ehsize = sizeof(Elf_Ehdr);
Petr Hosekeb04da32017-07-19 20:38:46 +0000204 Header.e_phentsize = sizeof(Elf_Phdr);
205 Header.e_phnum = Doc.ProgramHeaders.size();
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000206 Header.e_shentsize = sizeof(Elf_Shdr);
Petr Hosekeb04da32017-07-19 20:38:46 +0000207 // Immediately following the ELF header and program headers.
208 Header.e_shoff =
209 sizeof(Header) + sizeof(Elf_Phdr) * Doc.ProgramHeaders.size();
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000210 Header.e_shnum = getSectionCount();
211 Header.e_shstrndx = getDotShStrTabSecNo();
212}
213
214template <class ELFT>
Petr Hosekeb04da32017-07-19 20:38:46 +0000215void ELFState<ELFT>::initProgramHeaders(std::vector<Elf_Phdr> &PHeaders) {
216 for (const auto &YamlPhdr : Doc.ProgramHeaders) {
217 Elf_Phdr Phdr;
218 Phdr.p_type = YamlPhdr.Type;
219 Phdr.p_flags = YamlPhdr.Flags;
220 Phdr.p_vaddr = YamlPhdr.VAddr;
221 Phdr.p_paddr = YamlPhdr.PAddr;
222 PHeaders.push_back(Phdr);
223 }
224}
225
226template <class ELFT>
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000227bool ELFState<ELFT>::initSectionHeaders(std::vector<Elf_Shdr> &SHeaders,
228 ContiguousBlobAccumulator &CBA) {
229 // Ensure SHN_UNDEF entry is present. An all-zero section header is a
230 // valid SHN_UNDEF entry since SHT_NULL == 0.
231 Elf_Shdr SHeader;
232 zero(SHeader);
233 SHeaders.push_back(SHeader);
234
235 for (const auto &Sec : Doc.Sections) {
236 zero(SHeader);
Hans Wennborg59f0cba2014-04-30 19:38:09 +0000237 SHeader.sh_name = DotShStrtab.getOffset(Sec->Name);
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000238 SHeader.sh_type = Sec->Type;
239 SHeader.sh_flags = Sec->Flags;
240 SHeader.sh_addr = Sec->Address;
241 SHeader.sh_addralign = Sec->AddressAlign;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000242
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000243 if (!Sec->Link.empty()) {
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000244 unsigned Index;
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000245 if (SN2I.lookup(Sec->Link, Index)) {
246 errs() << "error: Unknown section referenced: '" << Sec->Link
247 << "' at YAML section '" << Sec->Name << "'.\n";
248 return false;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000249 }
250 SHeader.sh_link = Index;
251 }
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000252
253 if (auto S = dyn_cast<ELFYAML::RawContentSection>(Sec.get()))
254 writeSectionContent(SHeader, *S, CBA);
255 else if (auto S = dyn_cast<ELFYAML::RelocationSection>(Sec.get())) {
256 if (S->Link.empty())
257 // For relocation section set link to .symtab by default.
258 SHeader.sh_link = getDotSymTabSecNo();
259
260 unsigned Index;
261 if (SN2I.lookup(S->Info, Index)) {
Michael J. Spencer572d7422015-08-27 23:11:20 +0000262 if (S->Info.getAsInteger(0, Index)) {
263 errs() << "error: Unknown section referenced: '" << S->Info
264 << "' at YAML section '" << S->Name << "'.\n";
265 return false;
266 }
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000267 }
268 SHeader.sh_info = Index;
269
270 if (!writeSectionContent(SHeader, *S, CBA))
271 return false;
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000272 } else if (auto S = dyn_cast<ELFYAML::Group>(Sec.get())) {
273 unsigned SymIdx;
274 if (SymN2I.lookup(S->Info, SymIdx)) {
275 errs() << "error: Unknown symbol referenced: '" << S->Info
276 << "' at YAML section '" << S->Name << "'.\n";
277 return false;
278 }
279 SHeader.sh_info = SymIdx;
280 if (!writeSectionContent(SHeader, *S, CBA))
281 return false;
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000282 } else if (auto S = dyn_cast<ELFYAML::MipsABIFlags>(Sec.get())) {
283 if (!writeSectionContent(SHeader, *S, CBA))
284 return false;
Simon Atanasyan5db02762015-07-03 23:00:54 +0000285 } else if (auto S = dyn_cast<ELFYAML::NoBitsSection>(Sec.get())) {
286 SHeader.sh_entsize = 0;
287 SHeader.sh_size = S->Size;
288 // SHT_NOBITS section does not have content
289 // so just to setup the section offset.
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000290 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000291 } else
292 llvm_unreachable("Unknown section type");
293
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000294 SHeaders.push_back(SHeader);
295 }
296 return true;
297}
298
299template <class ELFT>
300void ELFState<ELFT>::initSymtabSectionHeader(Elf_Shdr &SHeader,
Dave Lee67b49662017-11-16 18:10:15 +0000301 SymtabType STType,
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000302 ContiguousBlobAccumulator &CBA) {
303 zero(SHeader);
Dave Lee67b49662017-11-16 18:10:15 +0000304 bool IsStatic = STType == SymtabType::Static;
305 SHeader.sh_name = DotShStrtab.getOffset(IsStatic ? ".symtab" : ".dynsym");
306 SHeader.sh_type = IsStatic ? ELF::SHT_SYMTAB : ELF::SHT_DYNSYM;
307 SHeader.sh_link = IsStatic ? getDotStrTabSecNo() : getDotDynStrSecNo();
308 const auto &Symbols = IsStatic ? Doc.Symbols : Doc.DynamicSymbols;
309 auto &Strtab = IsStatic ? DotStrtab : DotDynstr;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000310 // One greater than symbol table index of the last local symbol.
Dave Lee67b49662017-11-16 18:10:15 +0000311 SHeader.sh_info = Symbols.Local.size() + 1;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000312 SHeader.sh_entsize = sizeof(Elf_Sym);
Simon Atanasyan3a120922015-07-09 18:23:02 +0000313 SHeader.sh_addralign = 8;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000314
315 std::vector<Elf_Sym> Syms;
316 {
317 // Ensure STN_UNDEF is present
318 Elf_Sym Sym;
319 zero(Sym);
320 Syms.push_back(Sym);
321 }
Hans Wennborg59f0cba2014-04-30 19:38:09 +0000322
Dave Lee67b49662017-11-16 18:10:15 +0000323 // Add symbol names to .strtab or .dynstr.
324 for (const auto &Sym : Symbols.Local)
325 Strtab.add(Sym.Name);
326 for (const auto &Sym : Symbols.Global)
327 Strtab.add(Sym.Name);
328 for (const auto &Sym : Symbols.Weak)
329 Strtab.add(Sym.Name);
330 Strtab.finalize();
Hans Wennborg59f0cba2014-04-30 19:38:09 +0000331
Dave Lee67b49662017-11-16 18:10:15 +0000332 addSymbols(Symbols.Local, Syms, ELF::STB_LOCAL, Strtab);
333 addSymbols(Symbols.Global, Syms, ELF::STB_GLOBAL, Strtab);
334 addSymbols(Symbols.Weak, Syms, ELF::STB_WEAK, Strtab);
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000335
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000336 writeArrayData(
337 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign),
338 makeArrayRef(Syms));
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000339 SHeader.sh_size = arrayDataSize(makeArrayRef(Syms));
340}
341
342template <class ELFT>
343void ELFState<ELFT>::initStrtabSectionHeader(Elf_Shdr &SHeader, StringRef Name,
344 StringTableBuilder &STB,
345 ContiguousBlobAccumulator &CBA) {
346 zero(SHeader);
Hans Wennborg59f0cba2014-04-30 19:38:09 +0000347 SHeader.sh_name = DotShStrtab.getOffset(Name);
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000348 SHeader.sh_type = ELF::SHT_STRTAB;
Rafael Espindola39751af2016-10-04 22:43:25 +0000349 STB.write(CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign));
350 SHeader.sh_size = STB.getSize();
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000351 SHeader.sh_addralign = 1;
352}
353
354template <class ELFT>
Petr Hosekeb04da32017-07-19 20:38:46 +0000355void ELFState<ELFT>::setProgramHeaderLayout(std::vector<Elf_Phdr> &PHeaders,
356 std::vector<Elf_Shdr> &SHeaders) {
357 uint32_t PhdrIdx = 0;
358 for (auto &YamlPhdr : Doc.ProgramHeaders) {
359 auto &PHeader = PHeaders[PhdrIdx++];
360
361 if (YamlPhdr.Sections.size())
362 PHeader.p_offset = UINT32_MAX;
363 else
364 PHeader.p_offset = 0;
365
366 // Find the minimum offset for the program header.
367 for (auto SecName : YamlPhdr.Sections) {
368 uint32_t Index = 0;
369 SN2I.lookup(SecName.Section, Index);
370 const auto &SHeader = SHeaders[Index];
371 PHeader.p_offset = std::min(PHeader.p_offset, SHeader.sh_offset);
372 }
373
374 // Find the maximum offset of the end of a section in order to set p_filesz.
375 PHeader.p_filesz = 0;
376 for (auto SecName : YamlPhdr.Sections) {
377 uint32_t Index = 0;
378 SN2I.lookup(SecName.Section, Index);
379 const auto &SHeader = SHeaders[Index];
380 uint64_t EndOfSection;
381 if (SHeader.sh_type == llvm::ELF::SHT_NOBITS)
382 EndOfSection = SHeader.sh_offset;
383 else
384 EndOfSection = SHeader.sh_offset + SHeader.sh_size;
385 uint64_t EndOfSegment = PHeader.p_offset + PHeader.p_filesz;
386 EndOfSegment = std::max(EndOfSegment, EndOfSection);
387 PHeader.p_filesz = EndOfSegment - PHeader.p_offset;
388 }
389
390 // Find the memory size by adding the size of sections at the end of the
391 // segment. These should be empty (size of zero) and NOBITS sections.
392 PHeader.p_memsz = PHeader.p_filesz;
393 for (auto SecName : YamlPhdr.Sections) {
394 uint32_t Index = 0;
395 SN2I.lookup(SecName.Section, Index);
396 const auto &SHeader = SHeaders[Index];
397 if (SHeader.sh_offset == PHeader.p_offset + PHeader.p_filesz)
398 PHeader.p_memsz += SHeader.sh_size;
399 }
400
401 // Set the alignment of the segment to be the same as the maximum alignment
Jake Ehrlich03aeeb092017-11-01 23:14:48 +0000402 // of the sections with the same offset so that by default the segment
Petr Hosekeb04da32017-07-19 20:38:46 +0000403 // has a valid and sensible alignment.
Jake Ehrlich03aeeb092017-11-01 23:14:48 +0000404 if (YamlPhdr.Align) {
405 PHeader.p_align = *YamlPhdr.Align;
406 } else {
407 PHeader.p_align = 1;
408 for (auto SecName : YamlPhdr.Sections) {
409 uint32_t Index = 0;
410 SN2I.lookup(SecName.Section, Index);
411 const auto &SHeader = SHeaders[Index];
412 if (SHeader.sh_offset == PHeader.p_offset)
413 PHeader.p_align = std::max(PHeader.p_align, SHeader.sh_addralign);
414 }
Petr Hosekeb04da32017-07-19 20:38:46 +0000415 }
416 }
417}
418
419template <class ELFT>
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000420void ELFState<ELFT>::addSymbols(const std::vector<ELFYAML::Symbol> &Symbols,
421 std::vector<Elf_Sym> &Syms,
Dave Lee67b49662017-11-16 18:10:15 +0000422 unsigned SymbolBinding,
423 const StringTableBuilder &Strtab) {
Simon Atanasyan048baca2014-03-14 06:53:30 +0000424 for (const auto &Sym : Symbols) {
Sean Silva6b083882013-06-18 23:14:03 +0000425 Elf_Sym Symbol;
426 zero(Symbol);
427 if (!Sym.Name.empty())
Dave Lee67b49662017-11-16 18:10:15 +0000428 Symbol.st_name = Strtab.getOffset(Sym.Name);
Sean Silvaaff51252013-06-21 00:27:50 +0000429 Symbol.setBindingAndType(SymbolBinding, Sym.Type);
Sean Silvac4afa6d2013-06-21 01:11:48 +0000430 if (!Sym.Section.empty()) {
431 unsigned Index;
Simon Atanasyan35babf92014-04-06 09:02:55 +0000432 if (SN2I.lookup(Sym.Section, Index)) {
Sean Silvac4afa6d2013-06-21 01:11:48 +0000433 errs() << "error: Unknown section referenced: '" << Sym.Section
434 << "' by YAML symbol " << Sym.Name << ".\n";
435 exit(1);
436 }
437 Symbol.st_shndx = Index;
Petr Hosek5c469a32017-09-07 20:44:16 +0000438 } else if (Sym.Index) {
439 Symbol.st_shndx = *Sym.Index;
440 }
441 // else Symbol.st_shndex == SHN_UNDEF (== 0), since it was zero'd earlier.
Sean Silva05001b92013-06-20 20:59:47 +0000442 Symbol.st_value = Sym.Value;
Simon Atanasyan60e1a792014-11-06 22:46:24 +0000443 Symbol.st_other = Sym.Other;
Sean Silva05001b92013-06-20 20:59:47 +0000444 Symbol.st_size = Sym.Size;
Sean Silva6b083882013-06-18 23:14:03 +0000445 Syms.push_back(Symbol);
446 }
Sean Silvaaff51252013-06-21 00:27:50 +0000447}
448
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000449template <class ELFT>
450void
451ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
452 const ELFYAML::RawContentSection &Section,
453 ContiguousBlobAccumulator &CBA) {
Simon Atanasyanb83f3802014-05-16 16:01:00 +0000454 assert(Section.Size >= Section.Content.binary_size() &&
455 "Section size and section content are inconsistent");
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000456 raw_ostream &OS =
457 CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
Simon Atanasyanb83f3802014-05-16 16:01:00 +0000458 Section.Content.writeAsBinary(OS);
459 for (auto i = Section.Content.binary_size(); i < Section.Size; ++i)
460 OS.write(0);
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000461 SHeader.sh_entsize = 0;
Simon Atanasyanb83f3802014-05-16 16:01:00 +0000462 SHeader.sh_size = Section.Size;
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000463}
464
Simon Atanasyan5d19c672015-01-25 13:29:25 +0000465static bool isMips64EL(const ELFYAML::Object &Doc) {
466 return Doc.Header.Machine == ELFYAML::ELF_EM(llvm::ELF::EM_MIPS) &&
467 Doc.Header.Class == ELFYAML::ELF_ELFCLASS(ELF::ELFCLASS64) &&
468 Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB);
469}
470
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000471template <class ELFT>
472bool
473ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
474 const ELFYAML::RelocationSection &Section,
475 ContiguousBlobAccumulator &CBA) {
Simon Atanasyan8eb9d1b2015-05-08 07:05:04 +0000476 assert((Section.Type == llvm::ELF::SHT_REL ||
477 Section.Type == llvm::ELF::SHT_RELA) &&
478 "Section type is not SHT_REL nor SHT_RELA");
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000479
480 bool IsRela = Section.Type == llvm::ELF::SHT_RELA;
481 SHeader.sh_entsize = IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
482 SHeader.sh_size = SHeader.sh_entsize * Section.Relocations.size();
483
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000484 auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000485
486 for (const auto &Rel : Section.Relocations) {
Adhemerval Zanella9f3dbff2015-04-22 15:26:43 +0000487 unsigned SymIdx = 0;
488 // Some special relocation, R_ARM_v4BX for instance, does not have
489 // an external reference. So it ignores the return value of lookup()
490 // here.
Petr Hosek5aa80f12017-08-30 23:13:31 +0000491 if (Rel.Symbol)
492 SymN2I.lookup(*Rel.Symbol, SymIdx);
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000493
494 if (IsRela) {
495 Elf_Rela REntry;
496 zero(REntry);
497 REntry.r_offset = Rel.Offset;
498 REntry.r_addend = Rel.Addend;
Simon Atanasyan5d19c672015-01-25 13:29:25 +0000499 REntry.setSymbolAndType(SymIdx, Rel.Type, isMips64EL(Doc));
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000500 OS.write((const char *)&REntry, sizeof(REntry));
501 } else {
502 Elf_Rel REntry;
503 zero(REntry);
504 REntry.r_offset = Rel.Offset;
Simon Atanasyan5d19c672015-01-25 13:29:25 +0000505 REntry.setSymbolAndType(SymIdx, Rel.Type, isMips64EL(Doc));
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000506 OS.write((const char *)&REntry, sizeof(REntry));
507 }
508 }
509 return true;
510}
511
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000512template <class ELFT>
513bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
514 const ELFYAML::Group &Section,
515 ContiguousBlobAccumulator &CBA) {
Rui Ueyama478d6352018-01-12 02:28:31 +0000516 typedef typename ELFT::Word Elf_Word;
Simon Atanasyan8eb9d1b2015-05-08 07:05:04 +0000517 assert(Section.Type == llvm::ELF::SHT_GROUP &&
518 "Section type is not SHT_GROUP");
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000519
520 SHeader.sh_entsize = sizeof(Elf_Word);
521 SHeader.sh_size = SHeader.sh_entsize * Section.Members.size();
522
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000523 auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
Shankar Easwaran6fbbe202015-02-21 04:28:26 +0000524
525 for (auto member : Section.Members) {
526 Elf_Word SIdx;
527 unsigned int sectionIndex = 0;
528 if (member.sectionNameOrType == "GRP_COMDAT")
529 sectionIndex = llvm::ELF::GRP_COMDAT;
530 else if (SN2I.lookup(member.sectionNameOrType, sectionIndex)) {
531 errs() << "error: Unknown section referenced: '"
532 << member.sectionNameOrType << "' at YAML section' "
533 << Section.Name << "\n";
534 return false;
535 }
536 SIdx = sectionIndex;
537 OS.write((const char *)&SIdx, sizeof(SIdx));
538 }
539 return true;
540}
541
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000542template <class ELFT>
543bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
544 const ELFYAML::MipsABIFlags &Section,
545 ContiguousBlobAccumulator &CBA) {
Simon Atanasyan8eb9d1b2015-05-08 07:05:04 +0000546 assert(Section.Type == llvm::ELF::SHT_MIPS_ABIFLAGS &&
547 "Section type is not SHT_MIPS_ABIFLAGS");
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000548
549 object::Elf_Mips_ABIFlags<ELFT> Flags;
550 zero(Flags);
551 SHeader.sh_entsize = sizeof(Flags);
552 SHeader.sh_size = SHeader.sh_entsize;
553
Simon Atanasyan22c4c9e2015-07-08 10:12:40 +0000554 auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign);
Simon Atanasyan04d9e652015-05-07 15:40:48 +0000555 Flags.version = Section.Version;
556 Flags.isa_level = Section.ISALevel;
557 Flags.isa_rev = Section.ISARevision;
558 Flags.gpr_size = Section.GPRSize;
559 Flags.cpr1_size = Section.CPR1Size;
560 Flags.cpr2_size = Section.CPR2Size;
561 Flags.fp_abi = Section.FpABI;
562 Flags.isa_ext = Section.ISAExtension;
563 Flags.ases = Section.ASEs;
564 Flags.flags1 = Section.Flags1;
565 Flags.flags2 = Section.Flags2;
566 OS.write((const char *)&Flags, sizeof(Flags));
567
568 return true;
569}
570
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000571template <class ELFT> bool ELFState<ELFT>::buildSectionIndex() {
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000572 for (unsigned i = 0, e = Doc.Sections.size(); i != e; ++i) {
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000573 StringRef Name = Doc.Sections[i]->Name;
Dave Lee17307d92017-11-09 14:53:43 +0000574 DotShStrtab.add(Name);
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000575 // "+ 1" to take into account the SHT_NULL entry.
576 if (SN2I.addName(Name, i + 1)) {
577 errs() << "error: Repeated section name: '" << Name
578 << "' at YAML section number " << i << ".\n";
579 return false;
580 }
Sean Silvaaff51252013-06-21 00:27:50 +0000581 }
Dave Lee17307d92017-11-09 14:53:43 +0000582
583 auto SecNo = 1 + Doc.Sections.size();
584 // Add special sections after input sections, if necessary.
Dave Lee67b49662017-11-16 18:10:15 +0000585 for (const auto &Name : implicitSectionNames())
Dave Lee17307d92017-11-09 14:53:43 +0000586 if (!SN2I.addName(Name, SecNo)) {
587 // Account for this section, since it wasn't in the Doc
588 ++SecNo;
589 DotShStrtab.add(Name);
590 }
591
592 DotShStrtab.finalize();
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000593 return true;
Sean Silva6b083882013-06-18 23:14:03 +0000594}
595
Sean Silvaf99309c2013-06-10 23:44:15 +0000596template <class ELFT>
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000597bool
598ELFState<ELFT>::buildSymbolIndex(std::size_t &StartIndex,
599 const std::vector<ELFYAML::Symbol> &Symbols) {
600 for (const auto &Sym : Symbols) {
601 ++StartIndex;
602 if (Sym.Name.empty())
603 continue;
604 if (SymN2I.addName(Sym.Name, StartIndex)) {
605 errs() << "error: Repeated symbol name: '" << Sym.Name << "'.\n";
606 return false;
607 }
608 }
609 return true;
610}
611
612template <class ELFT>
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000613int ELFState<ELFT>::writeELF(raw_ostream &OS, const ELFYAML::Object &Doc) {
Simon Atanasyan220c54a2014-04-02 16:34:40 +0000614 ELFState<ELFT> State(Doc);
615 if (!State.buildSectionIndex())
616 return 1;
617
Simon Atanasyan42ac0dd2014-04-11 04:13:39 +0000618 std::size_t StartSymIndex = 0;
619 if (!State.buildSymbolIndex(StartSymIndex, Doc.Symbols.Local) ||
620 !State.buildSymbolIndex(StartSymIndex, Doc.Symbols.Global) ||
621 !State.buildSymbolIndex(StartSymIndex, Doc.Symbols.Weak))
622 return 1;
623
Sean Silva38205932013-06-13 22:19:48 +0000624 Elf_Ehdr Header;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000625 State.initELFHeader(Header);
Sean Silvaf99309c2013-06-10 23:44:15 +0000626
Sean Silva38205932013-06-13 22:19:48 +0000627 // TODO: Flesh out section header support.
Petr Hosekeb04da32017-07-19 20:38:46 +0000628
629 std::vector<Elf_Phdr> PHeaders;
630 State.initProgramHeaders(PHeaders);
Sean Silva38205932013-06-13 22:19:48 +0000631
Sean Silva08a75ae2013-06-20 19:11:44 +0000632 // XXX: This offset is tightly coupled with the order that we write
633 // things to `OS`.
Petr Hosekeb04da32017-07-19 20:38:46 +0000634 const size_t SectionContentBeginOffset = Header.e_ehsize +
635 Header.e_phentsize * Header.e_phnum +
636 Header.e_shentsize * Header.e_shnum;
Sean Silva08a75ae2013-06-20 19:11:44 +0000637 ContiguousBlobAccumulator CBA(SectionContentBeginOffset);
Sean Silvac1c290b2013-06-20 20:59:34 +0000638
Sean Silva38205932013-06-13 22:19:48 +0000639 std::vector<Elf_Shdr> SHeaders;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000640 if(!State.initSectionHeaders(SHeaders, CBA))
641 return 1;
Sean Silva38205932013-06-13 22:19:48 +0000642
Dave Lee17307d92017-11-09 14:53:43 +0000643 // Populate SHeaders with implicit sections not present in the Doc
Dave Lee67b49662017-11-16 18:10:15 +0000644 for (const auto &Name : State.implicitSectionNames())
Dave Lee17307d92017-11-09 14:53:43 +0000645 if (State.SN2I.get(Name) >= SHeaders.size())
646 SHeaders.push_back({});
Sean Silva82177572013-06-22 01:38:00 +0000647
Dave Lee17307d92017-11-09 14:53:43 +0000648 // Initialize the implicit sections
649 auto Index = State.SN2I.get(".symtab");
Dave Lee67b49662017-11-16 18:10:15 +0000650 State.initSymtabSectionHeader(SHeaders[Index], SymtabType::Static, CBA);
Dave Lee17307d92017-11-09 14:53:43 +0000651 Index = State.SN2I.get(".strtab");
652 State.initStrtabSectionHeader(SHeaders[Index], ".strtab", State.DotStrtab, CBA);
653 Index = State.SN2I.get(".shstrtab");
654 State.initStrtabSectionHeader(SHeaders[Index], ".shstrtab", State.DotShStrtab, CBA);
Dave Lee67b49662017-11-16 18:10:15 +0000655 if (State.hasDynamicSymbols()) {
656 Index = State.SN2I.get(".dynsym");
657 State.initSymtabSectionHeader(SHeaders[Index], SymtabType::Dynamic, CBA);
658 SHeaders[Index].sh_flags |= ELF::SHF_ALLOC;
659 Index = State.SN2I.get(".dynstr");
660 State.initStrtabSectionHeader(SHeaders[Index], ".dynstr", State.DotDynstr, CBA);
661 SHeaders[Index].sh_flags |= ELF::SHF_ALLOC;
662 }
Sean Silvaf99309c2013-06-10 23:44:15 +0000663
Petr Hosekeb04da32017-07-19 20:38:46 +0000664 // Now we can decide segment offsets
665 State.setProgramHeaderLayout(PHeaders, SHeaders);
666
Sean Silvaf99309c2013-06-10 23:44:15 +0000667 OS.write((const char *)&Header, sizeof(Header));
Petr Hosekeb04da32017-07-19 20:38:46 +0000668 writeArrayData(OS, makeArrayRef(PHeaders));
Will Dietz0b48c732013-10-12 21:29:16 +0000669 writeArrayData(OS, makeArrayRef(SHeaders));
Sean Silva46dffff2013-06-13 22:20:01 +0000670 CBA.writeBlobToStream(OS);
Sean Silva415d93f2013-06-17 20:14:59 +0000671 return 0;
Sean Silvaf99309c2013-06-10 23:44:15 +0000672}
673
Dave Lee67b49662017-11-16 18:10:15 +0000674template <class ELFT> bool ELFState<ELFT>::hasDynamicSymbols() const {
675 return Doc.DynamicSymbols.Global.size() > 0 ||
676 Doc.DynamicSymbols.Weak.size() > 0 ||
677 Doc.DynamicSymbols.Local.size() > 0;
678}
679
680template <class ELFT> SmallVector<const char *, 5> ELFState<ELFT>::implicitSectionNames() const {
681 if (!hasDynamicSymbols())
682 return {".symtab", ".strtab", ".shstrtab"};
683 return {".symtab", ".strtab", ".shstrtab", ".dynsym", ".dynstr"};
684}
685
Sean Silva11caeba2013-06-22 01:03:35 +0000686static bool is64Bit(const ELFYAML::Object &Doc) {
687 return Doc.Header.Class == ELFYAML::ELF_ELFCLASS(ELF::ELFCLASS64);
688}
689
690static bool isLittleEndian(const ELFYAML::Object &Doc) {
691 return Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB);
692}
693
Chris Bieneman8ff0c112016-06-27 19:53:53 +0000694int yaml2elf(llvm::ELFYAML::Object &Doc, raw_ostream &Out) {
Sean Silva11caeba2013-06-22 01:03:35 +0000695 if (is64Bit(Doc)) {
696 if (isLittleEndian(Doc))
Rui Ueyama1b31eb92018-01-12 01:40:32 +0000697 return ELFState<object::ELF64LE>::writeELF(Out, Doc);
Sean Silvaf99309c2013-06-10 23:44:15 +0000698 else
Rui Ueyama1b31eb92018-01-12 01:40:32 +0000699 return ELFState<object::ELF64BE>::writeELF(Out, Doc);
Sean Silvaf99309c2013-06-10 23:44:15 +0000700 } else {
Sean Silva11caeba2013-06-22 01:03:35 +0000701 if (isLittleEndian(Doc))
Rui Ueyama1b31eb92018-01-12 01:40:32 +0000702 return ELFState<object::ELF32LE>::writeELF(Out, Doc);
Sean Silvaf99309c2013-06-10 23:44:15 +0000703 else
Rui Ueyama1b31eb92018-01-12 01:40:32 +0000704 return ELFState<object::ELF32BE>::writeELF(Out, Doc);
Sean Silvaf99309c2013-06-10 23:44:15 +0000705 }
Sean Silvaf99309c2013-06-10 23:44:15 +0000706}