blob: 4282732e0f4afc620b8d5fd8af58671adf5790b9 [file] [log] [blame]
Nick Kledzikabb69812012-05-31 22:34:00 +00001//===- lib/ReaderWriter/ELF/WriterELF.cpp ---------------------------------===//
2//
3// The LLVM Linker
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "lld/ReaderWriter/WriterELF.h"
Hemant Kulkarni927bbc22012-09-14 16:11:34 +000011#include "ReferenceKinds.h"
Nick Kledzikabb69812012-05-31 22:34:00 +000012
Hemant Kulkarni927bbc22012-09-14 16:11:34 +000013#include "lld/Core/DefinedAtom.h"
14#include "lld/Core/File.h"
15#include "lld/Core/InputFiles.h"
16#include "lld/Core/Reference.h"
17#include "lld/Core/SharedLibraryAtom.h"
18
19#include "llvm/ADT/ArrayRef.h"
20#include "llvm/ADT/DenseMap.h"
21#include "llvm/ADT/OwningPtr.h"
22#include "llvm/ADT/SmallVector.h"
23#include "llvm/ADT/StringMap.h"
24#include "llvm/ADT/StringRef.h"
25
26#include "llvm/Object/ELF.h"
27
28#include "llvm/Support/Allocator.h"
Nick Kledzikabb69812012-05-31 22:34:00 +000029#include "llvm/Support/Debug.h"
Hemant Kulkarni927bbc22012-09-14 16:11:34 +000030#include "llvm/Support/ELF.h"
31#include "llvm/Support/ErrorHandling.h"
32#include "llvm/Support/FileOutputBuffer.h"
33#include "llvm/Support/Format.h"
34#include "llvm/Support/MathExtras.h"
35#include "llvm/Support/raw_ostream.h"
36#include "llvm/Support/system_error.h"
Nick Kledzikabb69812012-05-31 22:34:00 +000037
Hemant Kulkarni927bbc22012-09-14 16:11:34 +000038#include <map>
39#include <tuple>
40#include <vector>
Hemant Kulkarni87dbac02012-11-13 21:34:45 +000041#include <algorithm>
Nick Kledzikabb69812012-05-31 22:34:00 +000042
Hemant Kulkarni927bbc22012-09-14 16:11:34 +000043using namespace llvm;
44using namespace llvm::object;
Nick Kledzikabb69812012-05-31 22:34:00 +000045namespace lld {
46namespace elf {
47
Hemant Kulkarni87dbac02012-11-13 21:34:45 +000048// The group decides where sections of similar permissions reside
49// inside a file. This is also used to create program headers. Each group
50// will be in a new segment.
51
52/// \name Chunk Groups
53/// Each "Chunk" should be arranged in a weak strict order
54/// This is done to minimize memory utilization when creating program segments.
55/// This will remain in place till a more felxible mechanism of moving chunks
56/// around and packing for memory efficiency is put in place.
57/// The Chunks are arranged by group numbers. Every switch from group A to B
58/// triggers a formation of new segment. Additionally segments are also made
59/// within a group if there are vast regions (multiple pages) of 0 for
60/// alignment constraints.
61enum {
62/// @{
63///Invalid group (default on creation)
64 CG_INVALID = 0x0,
65///This is a "header" kind of chunk that goes at beginning of ELF file
66 CG_HEADER = 0x1,
67///This is a section chunk with read write and execute permissions
68 CG_RWX = 0x3,
69///This is a section chunk with read and execute permissions
70 CG_RX = 0x4,
71///This is a section chunk with read permission
72 CG_R = 0x5,
73///This is a section chunk with read and write permissions
74 CG_RW = 0x6,
75///This is a section chunk with write and execute permissions
76 CG_WX = 0x7,
77///This is a section chunk with write permission
78 CG_W = 0x8,
79///This is a section chunk with execute permission
80 CG_X = 0x9,
81///This is a section which is no loaded by program loader
82 CG_NO_LOAD = 0xFE,
83///This is ELF file metadata that goes at end of file
84 CG_FILE_END = 0xFF
85/// @}
86};
87
Hemant Kulkarni927bbc22012-09-14 16:11:34 +000088template<support::endianness target_endianness, bool is64Bits>
89class ELFWriter;
Nick Kledzikabb69812012-05-31 22:34:00 +000090
Hemant Kulkarni736f7fb2012-11-21 21:07:36 +000091template<support::endianness target_endianness, bool is64Bits>
92class StockSectionChunk;
93
Hemant Kulkarni927bbc22012-09-14 16:11:34 +000094/// \brief A Chunk is a contiguous range of space.
95template<support::endianness target_endianness, bool is64Bits>
96class Chunk {
97public:
98 LLVM_ELF_IMPORT_TYPES(target_endianness, is64Bits)
99 virtual ~Chunk() {}
100 virtual StringRef segmentName() const = 0;
101 virtual bool occupiesNoDiskSpace();
102 virtual void write(uint8_t *fileBuffer) = 0;
103 void assignFileOffset(uint64_t &curOff, uint64_t &curAddr);
104 virtual const char *info() = 0;
105 uint64_t size() const;
106 uint64_t address() const;
107 uint64_t fileOffset() const;
108 uint64_t align2() const;
109 static uint64_t alignTo(uint64_t value, uint8_t align2);
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000110 uint64_t ordinal() const { return _ordinal;}
111 void setOrdinal(uint64_t newVal) { _ordinal = newVal;}
Hemant Kulkarni87dbac02012-11-13 21:34:45 +0000112 void setGroup(uint16_t val) { _group = val;}
113 uint16_t group() const { return _group;}
114 void init();
115 bool isLoadable() { return _isLoadable; }
116 void isLoadable(uint64_t val) { _isLoadable = val; }
117 enum class Kind {
118 Header, // This is a header chunk
119 Section // chunk represents a section
120 };
121 Kind getChunkKind() const { return _cKind; }
122private:
123 const Kind _cKind;
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000124protected:
125 Chunk();
Hemant Kulkarni87dbac02012-11-13 21:34:45 +0000126 Chunk(Kind K): _cKind(K) { this->init();}
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000127 uint64_t _size;
128 uint64_t _address;
129 uint64_t _fileOffset;
130 uint64_t _align2;
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000131 uint64_t _ordinal;
Hemant Kulkarni87dbac02012-11-13 21:34:45 +0000132 uint16_t _group;
133 bool _isLoadable;
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000134};
135
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000136template<support::endianness target_endianness, bool is64Bits>
137static void swapChunkPositions(Chunk<target_endianness, is64Bits>&a,
138 Chunk<target_endianness, is64Bits>&b) {
139 uint64_t tempOrdinal;
140 if (a.ordinal() == b.ordinal()) return;
141 tempOrdinal = a.ordinal();
142 a.setOrdinal(b.ordinal());
143 b.setOrdinal(tempOrdinal);
144}
145
Hemant Kulkarni87dbac02012-11-13 21:34:45 +0000146template<support::endianness target_endianness, bool is64Bits>
147bool chunkGroupSort(Chunk<target_endianness, is64Bits> *A,
148 Chunk<target_endianness, is64Bits> *B) {
149 if (A->group() == CG_INVALID || B->group() == CG_INVALID)
150 llvm_unreachable("Invalid group number");
151 return A->group() < B->group();
152}
153
154template<support::endianness target_endianness, bool is64Bits>
155struct ChunkComparator {
156 bool operator()(uint16_t A, Chunk<target_endianness, is64Bits> *B) {
157 return A < B->group();
158 }
159 bool operator()(Chunk<target_endianness, is64Bits> *A, uint16_t B) {
160 return A->group() < B;
161 }
162#if defined(_ITERATOR_DEBUG_LEVEL) && _ITERATOR_DEBUG_LEVEL == 2
163 bool operator()(Chunk<target_endianness, is64Bits> *A,
164 Chunk<target_endianness, is64Bits> *B) {
165 return A->group() < B->group();
166 }
167#endif
168};
169
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000170/// Pair of atom and offset in section.
171typedef std::tuple<const DefinedAtom*, uint64_t> AtomInfo;
172
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000173/// \brief A SectionChunk represents ELF sections
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000174template<support::endianness target_endianness, bool is64Bits>
175class SectionChunk : public Chunk<target_endianness, is64Bits> {
176public:
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000177 virtual StringRef segmentName() const { return _segmentName; }
178 virtual bool occupiesNoDiskSpace();
179 virtual const char *info();
180 StringRef sectionName() { return _sectionName; }
181 uint64_t shStrtableOffset(){ return _offsetInStringTable; }
182 void setShStrtableOffset (uint64_t val) {
183 _offsetInStringTable = val; }
184 uint32_t flags() { return _flags; }
Hemant Kulkarni87dbac02012-11-13 21:34:45 +0000185 uint32_t type() const { return _type; }
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000186 uint64_t link() { return _link; }
187 void link(uint64_t val) { _link = val; }
188 uint16_t shinfo() { return _shinfo; }
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000189 uint64_t entsize() { return _entsize; }
190 SectionChunk(StringRef secName, StringRef segName, bool loadable,
191 uint64_t flags , uint64_t link, uint64_t info ,
192 uint64_t type, uint64_t entsz, const WriterOptionsELF &op,
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000193 ELFWriter<target_endianness, is64Bits> &writer);
Hemant Kulkarni736f7fb2012-11-21 21:07:36 +0000194
Hemant Kulkarni87dbac02012-11-13 21:34:45 +0000195 static inline bool classof(const Chunk<target_endianness, is64Bits> *c) {
196 return c->getChunkKind() == Chunk<target_endianness, is64Bits>::Kind
197 ::Section;
198 }
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000199protected:
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000200 uint64_t _link;
201 uint64_t _shinfo;
202 uint16_t _entsize;
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000203 StringRef _segmentName;
204 StringRef _sectionName;
205 const WriterOptionsELF &_options;
206 ELFWriter<target_endianness, is64Bits> &_writer;
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000207 uint64_t _flags;
208 uint64_t _type;
209 uint64_t _offsetInStringTable;
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000210};
211
Hemant Kulkarni87dbac02012-11-13 21:34:45 +0000212template<support::endianness target_endianness, bool is64Bits>
213bool IsBss(const Chunk<target_endianness, is64Bits> *A) {
214 if (auto X = llvm::dyn_cast<SectionChunk<target_endianness, is64Bits>>(A))
215 return X->type() != ELF::SHT_NOBITS;
216 llvm_unreachable("Call to a non section type chunk");
217 // adding a non-reachable return bool for making compiler happy
218 return false;
219}
220
Hemant Kulkarni736f7fb2012-11-21 21:07:36 +0000221/// \brief Return pointer to a defined atom whose name is specified as parameter
222/// if present in the specified section.
223/// When all the atoms are resolved, get addresses and offsets, we
224/// have atoms with unique names. Only then this routine is guaranteed
225/// to return the atom of interest. This routine is useful in finding atoms
226/// which are special such as entry point to a file
227template<support::endianness target_endianness, bool is64Bits>
228static const DefinedAtom* findDefinedAtomByName(StringRef name,
229 StockSectionChunk<target_endianness,
230 is64Bits> *sec) {
231 ArrayRef<AtomInfo> atoms = sec->atoms();
232 for (auto ai = atoms.begin(); ai != atoms.end(); ai++) {
233 if ((std::get<0>(*ai))->name() == name )
234 return std::get<0>(*ai);
235 }
236 return nullptr;
237}
238
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000239/// \brief A StockSectionChunk is a section created by linker with all
240/// attributes concluded from the defined atom contained within.
241template<support::endianness target_endianness, bool is64Bits>
242class StockSectionChunk : public SectionChunk<target_endianness, is64Bits> {
243public:
Michael J. Spencera1913fb2012-11-01 19:46:19 +0000244 virtual StringRef segmentName() const { return this->_segmentName; }
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000245 void appendAtom(const DefinedAtom*);
246 virtual void write(uint8_t *filebuffer);
247 const ArrayRef<AtomInfo> atoms() const;
248 StockSectionChunk(StringRef sectionName, bool loadable,
249 DefinedAtom::ContentType type,
250 const WriterOptionsELF &options,
251 ELFWriter<target_endianness, is64Bits> &writer);
252private:
253 std::vector<AtomInfo> _atoms;
254};
255
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000256/// \brief An ELFHeaderChunk represents the Elf[32/64]_Ehdr structure at the
257/// start of an ELF executable file.
258template<support::endianness target_endianness, bool is64Bits>
259class ELFHeaderChunk : public Chunk<target_endianness, is64Bits> {
260public:
261 LLVM_ELF_IMPORT_TYPES(target_endianness, is64Bits)
262 typedef object::Elf_Ehdr_Impl<target_endianness, is64Bits> Elf_Ehdr;
263
264 ELFHeaderChunk(const WriterOptionsELF &options,
265 const File &file);
266
267 void e_ident(int I, unsigned char C) { _eh.e_ident[I] = C; }
268 void e_type(uint16_t type) { _eh.e_type = type; }
269 void e_machine(uint16_t machine) { _eh.e_machine = machine; }
270 void e_version(uint32_t version) { _eh.e_version = version; }
271 void e_entry(uint64_t entry) { _eh.e_entry = entry; }
272 void e_phoff(uint64_t phoff) { _eh.e_phoff = phoff; }
273 void e_shoff(uint64_t shoff) { _eh.e_shoff = shoff; }
274 void e_flags(uint32_t flags) { _eh.e_flags = flags; }
275 void e_ehsize(uint16_t ehsize) { _eh.e_ehsize = ehsize; }
276 void e_phentsize(uint16_t phentsize) { _eh.e_phentsize = phentsize; }
277 void e_phnum(uint16_t phnum) { _eh.e_phnum = phnum; }
278 void e_shentsize(uint16_t shentsize) { _eh.e_shentsize = shentsize; }
279 void e_shnum(uint16_t shnum) { _eh.e_shnum = shnum; }
280 void e_shstrndx(uint16_t shstrndx) { _eh.e_shstrndx = shstrndx; }
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000281 uint64_t size() { return sizeof (Elf_Ehdr); }
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000282
283 virtual StringRef segmentName() const;
284 virtual void write(uint8_t *fileBuffer);
285 virtual const char *info();
Hemant Kulkarni87dbac02012-11-13 21:34:45 +0000286 static inline bool classof(const Chunk<target_endianness, is64Bits> *c) {
287 return c->getChunkKind() == Chunk<target_endianness, is64Bits>::Kind
288 ::Header;
289 }
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000290private:
291 Elf_Ehdr _eh;
292};
293
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000294/// \brief An ELFSectionHeaderChunk represents the Elf[32/64]_Shdr structure
295/// that is placed right after the ELFHeader.
296///
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000297template<support::endianness target_endianness, bool is64Bits>
298class ELFSectionHeaderChunk : public Chunk<target_endianness, is64Bits> {
299public:
300 LLVM_ELF_IMPORT_TYPES(target_endianness, is64Bits)
301 typedef object::Elf_Shdr_Impl<target_endianness, is64Bits> Elf_Shdr;
302 ELFSectionHeaderChunk(const WriterOptionsELF &Options,
303 ELFWriter<target_endianness, is64Bits>&);
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000304 void createHeaders();
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000305 virtual StringRef segmentName() const;
306 virtual void write(uint8_t *filebuffer);
307 virtual const char *info();
Hemant Kulkarni87dbac02012-11-13 21:34:45 +0000308 void computeSize();
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000309 uint16_t count();
310 uint16_t size();
Hemant Kulkarni87dbac02012-11-13 21:34:45 +0000311 void fixOffsets();
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000312 const ArrayRef<Elf_Shdr*> sectionInfo() {
313 return _sectionInfo;
314 }
Hemant Kulkarni87dbac02012-11-13 21:34:45 +0000315 static inline bool classof(const Chunk<target_endianness, is64Bits> *c) {
316 return c->getChunkKind() == Chunk<target_endianness, is64Bits>::Kind
317 ::Header;
318 }
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000319
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000320private:
321 const WriterOptionsELF &_options;
322 ELFWriter<target_endianness, is64Bits> &_writer;
323 llvm::BumpPtrAllocator _sectionAllocate;
324 std::vector<Elf_Shdr*> _sectionInfo;
325};
326
327/// \brief Represents the shstr section.
328///
329/// This is a contiguous memory that has all the symbol strings each ending with
330/// null character. We might need more than one such chunks shstrtab for setting
331/// e_shstrndx in ELHHeaderChunk and strtab for use with symtab
332template<support::endianness target_endianness, bool is64Bits>
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000333class ELFStringSectionChunk : public SectionChunk<target_endianness, is64Bits> {
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000334public:
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000335 ELFStringSectionChunk(const WriterOptionsELF &Options,
336 ELFWriter<target_endianness, is64Bits> &writer,
337 StringRef secName);
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000338 virtual StringRef segmentName() const { return this->_segmentName; }
339 uint64_t addString(StringRef symName);
340 const char *info();
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000341 virtual void write(uint8_t *filebuffer);
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000342
343private:
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000344 std::vector<StringRef> _stringSection;
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000345};
346
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000347/// \brief Represents the symtab section
348///
349/// ELFSymbolTableChunk represents the Symbol table as per ELF ABI
350/// This is a table with Elf[32/64]_Sym entries in it.
351template<support::endianness target_endianness, bool is64Bits>
352class ELFSymbolTableChunk : public SectionChunk<target_endianness, is64Bits> {
353public:
354 typedef object::Elf_Sym_Impl<target_endianness, is64Bits> Elf_Sym;
355 ELFSymbolTableChunk(const WriterOptionsELF &options,
356 ELFWriter<target_endianness, is64Bits> &writer,
357 StringRef secName);
358 virtual StringRef segmentName() const { return this->_segmentName; }
359 void addSymbol(const Atom *a, uint16_t shndx);
360 void addSymbol(Elf_Sym *x);
Hemant Kulkarni87dbac02012-11-13 21:34:45 +0000361 void fixSymbolValue();
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000362 const char *info();
363 void setAttributes();
364 virtual void write(uint8_t *fileBuffer);
365
366private:
367 std::vector<Elf_Sym*> _symbolTable;
368 ELFStringSectionChunk<target_endianness, is64Bits> *_stringSection;
369 llvm::BumpPtrAllocator _symbolAllocate;
Hemant Kulkarni87dbac02012-11-13 21:34:45 +0000370 std::map<Elf_Sym*, const Atom*> _symbolToAtom;
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000371};
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000372
Hemant Kulkarni87dbac02012-11-13 21:34:45 +0000373/// \brief ELFProgramHeaderChunk represents the Elf[32/64]_Phdr structure near
374/// the start of an ELF executable file. ELFHeader's e_phentsize and e_phnum
375/// show the number of entries in table and size of each one.
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000376template<support::endianness target_endianness, bool is64Bits>
377class ELFProgramHeaderChunk : public Chunk<target_endianness, is64Bits> {
378public:
379 LLVM_ELF_IMPORT_TYPES(target_endianness, is64Bits)
Hemant Kulkarni87dbac02012-11-13 21:34:45 +0000380 typedef object::Elf_Phdr<target_endianness, is64Bits> Elf_Phdr;
381 ELFProgramHeaderChunk(const WriterOptionsELF &options,
382 ELFWriter<target_endianness, is64Bits> &);
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000383
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000384 virtual StringRef segmentName() const;
385 virtual void write(uint8_t *filebuffer);
386 virtual const char *info();
Hemant Kulkarni87dbac02012-11-13 21:34:45 +0000387 void createPHeaders();
388 uint64_t computeNumber();
389 static inline bool classof(const Chunk<target_endianness, is64Bits> *c) {
390 return c->getChunkKind() == Chunk<target_endianness, is64Bits>::Kind
391 ::Header;
392 }
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000393
394private:
Hemant Kulkarni87dbac02012-11-13 21:34:45 +0000395 typedef typename std::vector<SectionChunk<target_endianness, is64Bits>*>
396 ::iterator secIterator;
397 const WriterOptionsELF &_options;
398 ELFWriter<target_endianness, is64Bits> &_writer;
399 std::vector<Elf_Phdr*> _programHeaders;
400 llvm::BumpPtrAllocator _headerAllocate;
401 typedef std::pair<uint64_t, uint64_t> sectionRange;
402 std::vector<sectionRange> _segments;
403 std::map<uint16_t, uint16_t> _groupToPF;
404
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000405};
406
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000407//===----------------------------------------------------------------------===//
408// Chunk
409//===----------------------------------------------------------------------===//
410
411template<support::endianness target_endianness, bool is64Bits>
Hemant Kulkarni87dbac02012-11-13 21:34:45 +0000412Chunk<target_endianness, is64Bits>::Chunk(){
413 this->init();
414}
415
416template<support::endianness target_endianness, bool is64Bits>
417void Chunk<target_endianness, is64Bits>::init(){
418 this->_size = 0;
419 this->_address = 0;
420 this->_fileOffset = 0;
421 this->_align2 = 0;
422 this->_group = CG_INVALID;
423 this->_isLoadable = false;
424 // 0 and 1 are reserved. 0 for ELF header and 1 for program header.
425 static uint64_t orderNumber = 0;
426 _ordinal = orderNumber++;
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000427}
428
429template<support::endianness target_endianness, bool is64Bits>
430bool Chunk<target_endianness, is64Bits>::occupiesNoDiskSpace() {
431 return false;
432}
433
434template<support::endianness target_endianness, bool is64Bits>
435uint64_t Chunk<target_endianness, is64Bits>::size() const {
436 return _size;
437}
438
439template<support::endianness target_endianness, bool is64Bits>
440uint64_t Chunk<target_endianness, is64Bits>::align2() const {
441 return _align2;
442}
443
444template<support::endianness target_endianness, bool is64Bits>
445uint64_t Chunk<target_endianness, is64Bits>::address() const {
446 return _address;
447}
448
449template<support::endianness target_endianness, bool is64Bits>
450uint64_t Chunk<target_endianness, is64Bits>::fileOffset() const {
451 return _fileOffset;
452}
453
454template<support::endianness target_endianness, bool is64Bits>
455uint64_t Chunk<target_endianness, is64Bits>::
456 alignTo(uint64_t value, uint8_t align2) {
457 uint64_t align = 1 << align2;
458 return (value + (align - 1)) & (-align);
459}
460
461template<support::endianness target_endianness, bool is64Bits>
462void Chunk<target_endianness, is64Bits>::
463 assignFileOffset(uint64_t &curOffset, uint64_t &curAddress) {
464 if (occupiesNoDiskSpace()) {
465 // FileOffset does not change, but virtual address does change.
466 uint64_t alignedAddress =
467 alignTo(curAddress, _align2 ? static_cast<uint8_t>(llvm::Log2_64(_align2))
468 : 0);
469 _address = alignedAddress;
470 curAddress = alignedAddress + _size;
471 } else {
472 // FileOffset and address both move by _size amount after alignment.
473 uint64_t alignPadding =
474 alignTo(curAddress, _align2 ? static_cast<uint8_t>(llvm::Log2_64(_align2))
475 : 0) - curAddress;
476 _fileOffset = curOffset + alignPadding;
477 _address = curAddress + alignPadding;
478 curOffset = _fileOffset + _size;
479 curAddress = _address + _size;
480 }
481
482 DEBUG_WITH_TYPE("WriterELF-layout", dbgs()
483 << " fileOffset="
484 << format("0x%08X", _fileOffset)
485 << " address="
486 << format("0x%016X", _address)
487 << " info=" << info() << "\n");
488}
489
490//===----------------------------------------------------------------------===//
491// SectionChunk
492//===----------------------------------------------------------------------===//
493
494template<support::endianness target_endianness, bool is64Bits>
495SectionChunk<target_endianness, is64Bits>::
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000496 SectionChunk(StringRef secName, StringRef segName, bool loadable,
497 uint64_t flags , uint64_t link, uint64_t info , uint64_t type,
498 uint64_t entsz, const WriterOptionsELF &op,
499 ELFWriter<target_endianness, is64Bits> &writer)
Hemant Kulkarni87dbac02012-11-13 21:34:45 +0000500 : Chunk<target_endianness, is64Bits>(Chunk<target_endianness, is64Bits>
501 ::Kind::Section)
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000502 , _link(link)
503 , _shinfo(info)
504 , _entsize(entsz)
505 , _segmentName(segName)
506 , _sectionName(secName)
507 , _options(op)
508 , _writer(writer)
509 , _flags(flags)
510 , _type(type)
Hemant Kulkarni87dbac02012-11-13 21:34:45 +0000511 , _offsetInStringTable(0) {
512 this->isLoadable(loadable);
513}
514//FIXME: We need to make decision here for every section created
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000515template<support::endianness target_endianness, bool is64Bits>
516bool SectionChunk<target_endianness, is64Bits>::occupiesNoDiskSpace() {
517 return false;
518}
519
520template<support::endianness target_endianness, bool is64Bits>
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000521const char *SectionChunk<target_endianness, is64Bits>::info() {
522 return _sectionName.data();
523}
524
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000525//===----------------------------------------------------------------------===//
526// StockSectionChunk
527//===----------------------------------------------------------------------===//
528
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000529template<support::endianness target_endianness, bool is64Bits>
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000530StockSectionChunk<target_endianness, is64Bits>::
531 StockSectionChunk(StringRef secName, bool loadable,
532 DefinedAtom::ContentType type,
533 const WriterOptionsELF &options,
534 ELFWriter<target_endianness, is64Bits> &writer)
535 : SectionChunk<target_endianness, is64Bits>(secName, "PT_NULL",
536 loadable, 0lu, 0lu, 0u, 0lu, 0lu,
537 options, writer) {
538 this->_segmentName = this->_isLoadable ? "PT_LOAD" : "PT_NULL" ;
Hemant Kulkarni87dbac02012-11-13 21:34:45 +0000539 // If the section is custom loadable section, group should be set explicitly.
540 // Stock non loadable section go as NO_LOAD and others will get their
541 // group determined by the atoms contained within. Many constant
542 // sections will have no symbols but the constants are referred as
543 // offset from start symbol, hence there may not be any defined atoms being
544 // appended to them, we force them at time of creation to CG_R
545 this->setGroup(this->isLoadable() ? CG_INVALID : CG_NO_LOAD);
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000546 switch(type) {
547 case DefinedAtom::typeCode:
548 this->_type = ELF::SHT_PROGBITS;
549 break;
550 case DefinedAtom::typeData:
551 this->_type = ELF::SHT_PROGBITS;
552 break;
553 case DefinedAtom::typeZeroFill:
554 this->_type = ELF::SHT_NOBITS;
Hemant Kulkarni8bd27612012-10-03 23:27:33 +0000555 break;
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000556 case DefinedAtom::typeConstant:
557 this->_type = ELF::SHT_PROGBITS;
Hemant Kulkarni87dbac02012-11-13 21:34:45 +0000558 this->_flags = ELF::SHF_ALLOC;
559 this->setGroup(CG_R);
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000560 break;
561 default:
562 llvm_unreachable("Unhandled content type for section!");
563 }
564}
565
566
567template<support::endianness target_endianness, bool is64Bits>
568const ArrayRef<AtomInfo> StockSectionChunk<target_endianness, is64Bits>::
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000569 atoms() const {
570 return _atoms;
571}
572
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000573template<support::endianness target_endianness, bool is64Bits>
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000574void StockSectionChunk<target_endianness, is64Bits>::
575 appendAtom(const DefinedAtom *atom) {
Hemant Kulkarni87dbac02012-11-13 21:34:45 +0000576 static uint16_t groupArray[] = {CG_INVALID, CG_W, CG_R, CG_RW, CG_X,
577 CG_WX, CG_RX, CG_RWX};
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000578 // Figure out offset for atom in this section given alignment constraints.
579 uint64_t offset = this->_size;
580 DefinedAtom::Alignment atomAlign = atom->alignment();
581 uint64_t align2 = 1 << atomAlign.powerOf2;
582 uint64_t requiredModulus = atomAlign.modulus;
583 uint64_t currentModulus = (offset % align2);
584 if (currentModulus != requiredModulus) {
585 if (requiredModulus > currentModulus)
586 offset += requiredModulus - currentModulus;
587 else
588 offset += align2 + requiredModulus - currentModulus;
589 }
590 // Record max alignment of any atom in this section.
591 if (align2 > this->_align2)
592 this->_align2 = align2;
593 // Assign atom to this section with this offset.
594 _atoms.emplace_back(atom, offset);
595 // Update section size to include this atom.
596 this->_size = offset + atom->size();
597 // Update permissions
598 DefinedAtom::ContentPermissions perms = atom->permissions();
Hemant Kulkarni87dbac02012-11-13 21:34:45 +0000599
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000600 if ((perms & DefinedAtom::permR__) == DefinedAtom::permR__)
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000601 this->_flags |= ELF::SHF_ALLOC;
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000602 if ((perms & DefinedAtom::permRW_) == DefinedAtom::permRW_)
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000603 this->_flags |= (ELF::SHF_ALLOC | ELF::SHF_WRITE);
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000604 if ((perms & DefinedAtom::permR_X) == DefinedAtom::permR_X)
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000605 this->_flags |= (ELF::SHF_ALLOC | ELF::SHF_EXECINSTR);
Hemant Kulkarni87dbac02012-11-13 21:34:45 +0000606 if (atom->contentType() == DefinedAtom::typeZeroFill)
607 this->_flags |= (ELF::SHF_ALLOC | ELF::SHF_WRITE);
608 this->setGroup(groupArray[this->_flags]);
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000609}
610
611template<support::endianness target_endianness, bool is64Bits>
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000612void StockSectionChunk<target_endianness, is64Bits>
613 ::write(uint8_t *chunkBuffer) {
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000614 // Each section's content is just its atoms' content.
615 for (const auto &ai : _atoms ) {
616 // Copy raw content of atom to file buffer.
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000617 ArrayRef<uint8_t> content = std::get<0>(ai)->rawContent();
618 uint64_t contentSize = content.size();
619 if (contentSize == 0)
620 continue;
621 uint8_t *atomContent = chunkBuffer + std::get<1>(ai);
622 std::copy_n(content.data(), contentSize, atomContent);
Sid Manningdd110202012-09-25 18:22:09 +0000623
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000624 for (const Reference *ref : *std::get<0>(ai)){
625 uint32_t offset = ref->offsetInAtom();
626 uint64_t targetAddress = 0;
Sid Manningdd110202012-09-25 18:22:09 +0000627
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000628 if ( ref->target() != nullptr )
629 targetAddress = this->_writer.addressOfAtom(ref->target());
Sid Manningdd110202012-09-25 18:22:09 +0000630
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000631 uint64_t fixupAddress = this->_writer.addressOfAtom(std::get<0>(ai)) +
632 offset;
633 this->_writer.kindHandler()->applyFixup(ref->kind(), ref->addend(),
634 &atomContent[offset],
635 fixupAddress,
636 targetAddress);
Sid Manningdd110202012-09-25 18:22:09 +0000637 }
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000638 }
639}
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000640
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000641//===----------------------------------------------------------------------===//
642// ELFStringSectionChunk
643//===----------------------------------------------------------------------===//
644template<support::endianness target_endianness, bool is64Bits>
645ELFStringSectionChunk<target_endianness, is64Bits>::
646 ELFStringSectionChunk(const WriterOptionsELF &options,
647 ELFWriter<target_endianness, is64Bits> &writer,
648 StringRef secName)
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000649 : SectionChunk<target_endianness, is64Bits>(secName, "PT_NULL",
650 false, 0lu, 0lu, 0lu,
651 ELF::SHT_STRTAB, 0lu, options,
652 writer) {
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000653 // First Add a null character. It also occupies 1 byte
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000654 _stringSection.emplace_back("");
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000655 this->_size = 1;
Hemant Kulkarni87dbac02012-11-13 21:34:45 +0000656 this->setGroup(CG_NO_LOAD);
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000657}
658
659template<support::endianness target_endianness, bool is64Bits>
660uint64_t ELFStringSectionChunk<target_endianness, is64Bits>::
661 addString(StringRef symName) {
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000662 _stringSection.emplace_back(symName);
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000663 uint64_t offset = this->_size;
664 this->_size += symName.size() + 1;
665
666 return offset;
667}
668
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000669// We need to unwrap the _stringSection and then make one large memory
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000670// chunk of null terminated strings
671template<support::endianness target_endianness, bool is64Bits>
672void ELFStringSectionChunk<target_endianness, is64Bits>::
673 write(uint8_t *chunkBuffer) {
674 uint64_t chunkOffset = 0;
675
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000676 for (auto it : _stringSection) {
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000677 ::memcpy(chunkBuffer + chunkOffset, it.data(), it.size());
678 chunkOffset += it.size();
679 ::memcpy(chunkBuffer + chunkOffset, "", 1);
680 chunkOffset += 1;
681 }
682}
683
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000684template<support::endianness target_endianness, bool is64Bits>
685const char *ELFStringSectionChunk<target_endianness, is64Bits>::info() {
686 return "String Table";
687}
688
689//===----------------------------------------------------------------------===//
690// ELFSymbolTableChunk
691//===----------------------------------------------------------------------===//
692template< support::endianness target_endianness, bool is64Bits>
693ELFSymbolTableChunk<target_endianness, is64Bits>::ELFSymbolTableChunk
694 (const WriterOptionsELF &options,
695 ELFWriter<target_endianness, is64Bits> &writer,
696 StringRef secName)
697 : SectionChunk<target_endianness, is64Bits>(secName, StringRef("PT_NULL"),
698 false, 0, 0, 0, ELF::SHT_SYMTAB,
699 sizeof(Elf_Sym), options, writer)
700{
701 _stringSection = this->_writer.strtab();
702 Elf_Sym *symbol = new (_symbolAllocate.Allocate<Elf_Sym>()) Elf_Sym;
703 memset ((void *)symbol,0, sizeof(Elf_Sym));
704 _symbolTable.push_back(symbol);
705 this->_link = 0;
706 this->_entsize = sizeof(Elf_Sym);
707 this->_size = sizeof(Elf_Sym);
Hemant Kulkarni87dbac02012-11-13 21:34:45 +0000708 this->_align2 = this->_options.pointerWidth();
709 this->setGroup(CG_NO_LOAD);
710}
711
712template< support::endianness target_endianness, bool is64Bits>
713void ELFSymbolTableChunk<target_endianness, is64Bits>::fixSymbolValue(){
714 for (auto sym : _symbolTable) {
715 if ( sym->st_shndx != ELF::SHN_ABS) {
716 sym->st_value = this->_writer.addressOfAtom(_symbolToAtom[sym]);
717 }
718 }
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000719}
720
721template< support::endianness target_endianness, bool is64Bits>
722void ELFSymbolTableChunk<target_endianness, is64Bits>::addSymbol(Elf_Sym *sym){
723 _symbolTable.push_back(sym);
724 this->_size+= sizeof(Elf_Sym) ;
725}
726
727/// \brief Add symbols to symbol table
728/// We examine each property of atom to infer the various st_* fields in Elf*_Sym
729template< support::endianness target_endianness, bool is64Bits>
730void ELFSymbolTableChunk<target_endianness, is64Bits>
731 ::addSymbol(const Atom *a, uint16_t shndx) {
732 Elf_Sym *symbol = new(_symbolAllocate.Allocate<Elf_Sym>()) Elf_Sym;
733 unsigned char b = 0, t = 0;
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000734 symbol->st_name = _stringSection->addString(a->name());
Hemant Kulkarni87dbac02012-11-13 21:34:45 +0000735 _symbolToAtom[symbol] = a;
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000736// In relocatable files, st_value holds a section offset for a defined symbol.
737// st_value is an offset from the beginning of the section that st_shndx
738// identifies. After we assign file offsets we can set this value correctly.
739 symbol->st_size = 0;
740 symbol->st_shndx = shndx;
741 symbol->st_value = 0;
742// FIXME: Need to change and account all STV* when visibilities are supported
743 symbol->st_other = ELF::STV_DEFAULT;
744 if (const DefinedAtom *da = llvm::dyn_cast<const DefinedAtom>(a)){
745 symbol->st_size = da->size();
746 lld::DefinedAtom::ContentType ct;
747 switch (ct = da->contentType()){
748 case DefinedAtom::typeCode:
749 t = ELF::STT_FUNC;
750 break;
751 case DefinedAtom::typeData:
752 t = ELF::STT_OBJECT;
753 break;
754 case DefinedAtom::typeZeroFill:
755 // In relocatable files, st_value holds alignment constraints for a symbol whose
756 // section index is SHN_COMMON
757 if (this->_options.type() == ELF::ET_REL){
758 t = ELF::STT_COMMON;
759 symbol->st_value = 1 << (da->alignment()).powerOf2;
760 symbol->st_shndx = ELF::SHN_COMMON;
761 }
762 break;
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000763 // TODO:: How to find STT_FILE symbols?
764 default:
765 t = ELF::STT_NOTYPE;
766 }
767
768 if (da->scope() == DefinedAtom::scopeTranslationUnit)
769 b = ELF::STB_LOCAL;
770 else if (da->merge() == DefinedAtom::mergeAsWeak)
771 b = ELF::STB_WEAK;
772 else
773 b = ELF::STB_GLOBAL;
Sid Manning2a590242012-10-18 17:16:19 +0000774 } else if (const AbsoluteAtom *aa = llvm::dyn_cast<const AbsoluteAtom>(a)){
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000775//FIXME: Absolute atoms need more properties to differentiate each other
776// based on binding and type of symbol
Sid Manning2a590242012-10-18 17:16:19 +0000777 t = ELF::STT_OBJECT;
778
779 switch (aa->scope()) {
780 case AbsoluteAtom::scopeLinkageUnit:
781 symbol->st_other = ELF::STV_HIDDEN;
782 b = ELF::STB_LOCAL;
783 break;
784 case AbsoluteAtom::scopeTranslationUnit:
785 b = ELF::STB_LOCAL;
786 break;
787 case AbsoluteAtom::scopeGlobal:
788 b = ELF::STB_GLOBAL;
789 break;
790 }
791 symbol->st_value = aa->value();
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000792 } else {
Sid Manning2a590242012-10-18 17:16:19 +0000793 symbol->st_value = 0;
794 t = ELF::STT_NOTYPE;
795 b = ELF::STB_LOCAL;
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000796 }
797 symbol->setBindingAndType(b, t);
798
799 _symbolTable.push_back(symbol);
800 this->_size += sizeof(Elf_Sym);
801}
802
803template<support::endianness target_endianness, bool is64Bits>
804void ELFSymbolTableChunk<target_endianness, is64Bits>::setAttributes() {
805// sh_info should be one greater than last symbol with STB_LOCAL binding
806// we sort the symbol table to keep all local symbols at the beginning
807 std::stable_sort(_symbolTable.begin(), _symbolTable.end(), ([]
808 (const Elf_Sym *A, const Elf_Sym *B) -> bool {
809 return (A->getBinding() < B->getBinding());}));
810 uint16_t shInfo = 0;
811 for (auto i : _symbolTable) {
812 if (i->getBinding() != ELF::STB_LOCAL)
813 break;
814 shInfo++;
815 }
816 this->_shinfo = shInfo;
817// we set the associated string table index in th sh_link member
818 this->_link = this->_writer.strtab()->ordinal() - 1;
819 this->_align2 = this->_options.pointerWidth();
820}
821
822template<support::endianness target_endianness, bool is64Bits>
823const char *ELFSymbolTableChunk<target_endianness, is64Bits>::info() {
824 return "Symbol Table";
825}
826
827template<support::endianness target_endianness, bool is64Bits>
828void ELFSymbolTableChunk<target_endianness, is64Bits>::
829 write(uint8_t *chunkBuffer) {
830 uint64_t chunkOffset = 0;
831 for (auto it : _symbolTable) {
832 ::memcpy(chunkBuffer + chunkOffset, it, this->_entsize);
833 chunkOffset += this->_entsize;
834 }
835}
836
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000837//===----------------------------------------------------------------------===//
838// ELFHeaderChunk
839//===----------------------------------------------------------------------===//
840template<support::endianness target_endianness, bool is64Bits>
841ELFHeaderChunk<target_endianness, is64Bits>
842 ::ELFHeaderChunk(const WriterOptionsELF &options,
Hemant Kulkarni87dbac02012-11-13 21:34:45 +0000843 const File &File)
844 : Chunk<target_endianness, is64Bits>(Chunk<target_endianness, is64Bits>
845 ::Kind::Header){
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000846 this->_size = size();
847 e_ident(ELF::EI_MAG0, 0x7f);
848 e_ident(ELF::EI_MAG1, 'E');
849 e_ident(ELF::EI_MAG2, 'L');
850 e_ident(ELF::EI_MAG3, 'F');
851 e_ident(ELF::EI_CLASS, (options.is64Bit() ? ELF::ELFCLASS64
852 : ELF::ELFCLASS32));
Sid Manninge3612f02012-10-05 14:06:24 +0000853 e_ident(ELF::EI_DATA, (options.endianness() == llvm::support::big)
854 ? ELF::ELFDATA2MSB
855 : ELF::ELFDATA2LSB);
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000856 e_ident(ELF::EI_VERSION, 1);
857 e_ident(ELF::EI_OSABI, ELF::ELFOSABI_NONE);
858
859 e_type(options.type());
860 e_machine(options.machine());
861 e_version(1);
862
863 e_entry(0ULL);
Hemant Kulkarni87dbac02012-11-13 21:34:45 +0000864 e_phoff(0);
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000865 e_shoff(0ULL);
866
Hemant Kulkarni736f7fb2012-11-21 21:07:36 +0000867 e_flags(2);
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000868 e_ehsize(this->_size);
869 e_phentsize(0);
870 e_phnum(0);
871 e_shentsize(0);
872 e_shnum(0);
873 e_shstrndx(0);
Hemant Kulkarni87dbac02012-11-13 21:34:45 +0000874 this->setGroup(CG_HEADER);
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000875}
876
877template<support::endianness target_endianness, bool is64Bits>
878StringRef ELFHeaderChunk<target_endianness, is64Bits>
879 ::segmentName() const {
880 return "ELF";
881}
882
883template<support::endianness target_endianness, bool is64Bits>
884void ELFHeaderChunk<target_endianness, is64Bits>
885 ::write(uint8_t *chunkBuffer) {
886 ::memcpy(chunkBuffer, &_eh, size());
887}
888
889template<support::endianness target_endianness, bool is64Bits>
890const char *ELFHeaderChunk<target_endianness, is64Bits>::info() {
891 return "elf_header";
892}
893
894//===----------------------------------------------------------------------===//
895// ELFSectionHeaderChunk
896// List of Section Headers:
897//[Nr] Name Type Addr Off Size ES Flg Lk Inf Al
898//[ 0] NULL 00000000 000000 000000 00 0 0 0
899//[ 1] .text PROGBITS 00000000 000034 000040 00 AX 0 0 4
900//===----------------------------------------------------------------------===//
901template<support::endianness target_endianness, bool is64Bits>
902ELFSectionHeaderChunk<target_endianness, is64Bits>
903 ::ELFSectionHeaderChunk(const WriterOptionsELF& options,
904 ELFWriter<target_endianness,
905 is64Bits> &writer)
Hemant Kulkarni87dbac02012-11-13 21:34:45 +0000906 : Chunk<target_endianness, is64Bits>(Chunk<target_endianness, is64Bits>
907 ::Kind::Header)
908 , _options(options)
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000909 , _writer(writer) {
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000910 this->_size = 0;
911 this->_align2 = 0;
912 // The first element in the list is always NULL
913 Elf_Shdr *nullshdr = new (_sectionAllocate.Allocate<Elf_Shdr>()) Elf_Shdr;
914 ::memset(nullshdr, 0, sizeof (Elf_Shdr));
915 _sectionInfo.push_back(nullshdr);
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000916 this->_size += sizeof (Elf_Shdr);
Hemant Kulkarni87dbac02012-11-13 21:34:45 +0000917 this->setGroup(CG_FILE_END);
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000918 }
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000919
Hemant Kulkarni87dbac02012-11-13 21:34:45 +0000920
921template<support::endianness target_endianness, bool is64Bits>
922void ELFSectionHeaderChunk<target_endianness, is64Bits>::computeSize(){
923 this->_size = (this->_writer.sectionChunks().size() + 1) * sizeof(Elf_Shdr);
924}
925
926template<support::endianness target_endianness, bool is64Bits>
927void ELFSectionHeaderChunk<target_endianness, is64Bits>::fixOffsets(){
928 auto it = _sectionInfo.begin();
929 auto sections = _writer.sectionChunks();
930 // First section is a NULL section with no sh_offset fix
931 (*it)->sh_offset = 0;
932 (*it)->sh_addr = 0;
933 ++it;
934 for (auto &chunk : sections){
935 (*it)->sh_offset = chunk->fileOffset();
936 (*it)->sh_addr = chunk->address();
937 ++it;
938 }
939}
940
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000941template<support::endianness target_endianness, bool is64Bits>
942void ELFSectionHeaderChunk<target_endianness, is64Bits>::createHeaders(){
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000943 ELFStringSectionChunk<target_endianness, is64Bits> *str = _writer.shstrtab();
944
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000945 for (const auto &chunk : _writer.sectionChunks()) {
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000946 Elf_Shdr *shdr = new (_sectionAllocate.Allocate<Elf_Shdr>()) Elf_Shdr;
947 StringRef Name = chunk->sectionName();
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000948 if (chunk->shStrtableOffset() == 0){
949 chunk->setShStrtableOffset(str->addString(Name));
950 }
951 shdr->sh_name = chunk->shStrtableOffset();
952
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000953 shdr->sh_type = chunk->type();
954 shdr->sh_flags = chunk->flags();
955 // TODO: At the time of creation of this section header, we will not have
956 // any address and offset info. We revisit this after assigning the file
957 // offsets.
958 shdr->sh_offset = chunk->fileOffset();
959 shdr->sh_addr = chunk->address();
960 shdr->sh_size = chunk->size();
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000961 shdr->sh_link = chunk->link() ;
962 shdr->sh_info = chunk->shinfo();
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000963 shdr->sh_addralign = chunk->align2();
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000964 shdr->sh_entsize = chunk->entsize();
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000965
966 _sectionInfo.push_back(shdr);
967 this->_size += sizeof (Elf_Shdr);
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000968 _writer.symtab()->setAttributes();
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000969 }
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000970}
971
972template<support::endianness target_endianness, bool is64Bits>
973StringRef ELFSectionHeaderChunk<target_endianness, is64Bits>
974 ::segmentName() const {
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000975 return "PT_NULL";
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000976}
977
978template<support::endianness target_endianness, bool is64Bits>
979void ELFSectionHeaderChunk<target_endianness, is64Bits>
980 ::write(uint8_t *chunkBuffer) {
981 for (const auto si : _sectionInfo) {
982 ::memcpy(chunkBuffer, si, sizeof(*si));
983 chunkBuffer += sizeof (*si);
984 }
985}
986
987template<support::endianness target_endianness, bool is64Bits>
988uint16_t ELFSectionHeaderChunk<target_endianness, is64Bits>::count() {
989 return _sectionInfo.size();
990}
991template<support::endianness target_endianness, bool is64Bits>
992uint16_t ELFSectionHeaderChunk<target_endianness, is64Bits>::size() {
993 return sizeof (Elf_Shdr);
994}
995
996template<support::endianness target_endianness, bool is64Bits>
997const char *ELFSectionHeaderChunk<target_endianness, is64Bits>::info() {
998 return "elf_section_header";
999}
1000
1001//===----------------------------------------------------------------------===//
1002// ELFProgramHeaderChunk
1003//===----------------------------------------------------------------------===//
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001004template<support::endianness target_endianness, bool is64Bits>
1005ELFProgramHeaderChunk<target_endianness, is64Bits>
1006 ::ELFProgramHeaderChunk(const WriterOptionsELF &options,
1007 ELFWriter<target_endianness, is64Bits>
1008 &writer)
1009 : Chunk<target_endianness, is64Bits>(Chunk<target_endianness, is64Bits>
1010 ::Kind::Header)
1011 , _options(options)
1012 , _writer(writer) {
1013 this->_align2 = 0;
1014 this->setGroup(CG_HEADER);
1015 _groupToPF[CG_RWX] = ELF::PF_R | ELF::PF_W | ELF::PF_X;
1016 _groupToPF[CG_RW] = ELF::PF_R | ELF::PF_W;
1017 _groupToPF[CG_RX] = ELF::PF_R | ELF::PF_X;
1018 _groupToPF[CG_R] = ELF::PF_R;
1019 _groupToPF[CG_W] = ELF::PF_W;
1020 _groupToPF[CG_WX] = ELF::PF_W | ELF::PF_X;
1021 _groupToPF[CG_X] = ELF::PF_X;
1022 }
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001023
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001024template<support::endianness target_endianness, bool is64Bits>
1025void ELFProgramHeaderChunk<target_endianness, is64Bits>::createPHeaders() {
1026
1027 //TODO Once dynamic linking is supported, implement PHDR segment
1028 // Implement mechanism inside this class to correctly find
1029 // attributes for sections such as eh_frame, note etc
1030 // when they are supported.
1031 const uint16_t seg[] = { CG_RWX, CG_RX, CG_R, CG_RW, CG_WX, CG_W, CG_X };
1032 std::pair<secIterator, secIterator> sectionPair;
1033 auto sections = _writer.sectionChunks();
1034 _programHeaders.clear();
1035 this->_size = 0;
1036 for (auto group : seg) {
1037 uint64_t size = 0, mSize = 0;
1038 sectionPair = std::equal_range(sections.begin(), sections.end(),
1039 group, ChunkComparator<target_endianness,
1040 is64Bits>());
1041 if (sectionPair.first != sectionPair.second) {
1042 // FIXME: fix occupiesNoDiskSpace() function in Chunks class
1043 auto segBegin = sectionPair.first, segEnd = segBegin + 1;
1044 // Since this group has a section, atleast this is a part of segment
1045 size = (*segBegin)->occupiesNoDiskSpace() ? 0 : (*segBegin)->size();
1046 mSize = (*segBegin)->size();
1047
1048 for (; segEnd != sectionPair.second; segEnd++) {
1049 // This means there are more than 1 sections of same permissions
1050 if ((*segEnd)->fileOffset() - (*segBegin)->fileOffset() - size >
1051 _options.pageSize()) {
1052 // we have a case where padding zeros span more than a page
1053 // we can skip those pages.
1054 Elf_Phdr *phdr = new(_headerAllocate.Allocate<Elf_Phdr>()) Elf_Phdr;
1055 phdr->p_type = ELF::PT_LOAD;
1056 phdr->p_offset = (*segBegin)->fileOffset();
1057 phdr->p_vaddr = (*segBegin)->address();
1058 phdr->p_paddr = phdr->p_vaddr;
1059 phdr->p_filesz = size;
1060 // memory size may be more than file size if there are sections
1061 // that do not occupy space on disk such as .bss
1062 phdr->p_memsz = mSize;
1063 phdr->p_flags = _groupToPF[group];
1064 phdr->p_align = _options.pageSize();
1065 _programHeaders.push_back(phdr);
1066 this->_size += sizeof(Elf_Phdr);
1067 segBegin = segEnd;
1068 size = (*segBegin)->occupiesNoDiskSpace() ? 0 : (*segBegin)->size();
1069 mSize = (*segBegin)->size();
1070 } else {
1071 size = (*segEnd)->fileOffset() - (*segBegin)->fileOffset() +
1072 ((*segEnd)->occupiesNoDiskSpace() ? 0 : (*segEnd)->size()) ;
1073 mSize = (*segEnd)->fileOffset() - (*segBegin)->fileOffset() +
1074 (*segEnd)->size();
1075 }
1076 }
1077
1078 Elf_Phdr *phdr = new(_headerAllocate.Allocate<Elf_Phdr>()) Elf_Phdr;
1079 phdr->p_type = ELF::PT_LOAD;
1080 phdr->p_offset = (*segBegin)->fileOffset();
1081 phdr->p_vaddr = (*segBegin)->address();
1082 phdr->p_paddr = phdr->p_vaddr;
1083 phdr->p_filesz = size;
1084 phdr->p_memsz = mSize;
1085 phdr->p_flags = _groupToPF[group];
1086 phdr->p_align = _options.pageSize();
1087 _programHeaders.push_back(phdr);
1088 this->_size += sizeof(Elf_Phdr);
1089 }
1090 }
1091}
1092
1093template<support::endianness target_endianness, bool is64Bits>
1094uint64_t ELFProgramHeaderChunk<target_endianness, is64Bits>::computeNumber() {
1095 return _programHeaders.size();
1096}
1097template<support::endianness target_endianness, bool is64Bits>
1098const char *ELFProgramHeaderChunk<target_endianness, is64Bits>::info() {
1099 return "elf_program_header";
1100}
1101
1102template<support::endianness target_endianness, bool is64Bits>
1103void ELFProgramHeaderChunk<target_endianness, is64Bits>
1104 ::write(uint8_t *chunkBuffer) {
1105 for (const auto si : _programHeaders) {
1106 ::memcpy(chunkBuffer, si, sizeof(*si));
1107 chunkBuffer += sizeof (*si);
1108 }
1109}
1110template<support::endianness target_endianness, bool is64Bits>
1111StringRef ELFProgramHeaderChunk<target_endianness, is64Bits>
1112 ::segmentName() const {
1113 return "PT_NULL";
1114}
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001115//===----------------------------------------------------------------------===//
1116// ELFWriter Class
1117//===----------------------------------------------------------------------===//
1118template<support::endianness target_endianness, bool is64Bits>
1119class ELFWriter : public Writer {
1120public:
1121 LLVM_ELF_IMPORT_TYPES(target_endianness, is64Bits)
1122 typedef object::Elf_Shdr_Impl<target_endianness, is64Bits> Elf_Shdr;
Hemant Kulkarni08e410292012-10-01 23:53:20 +00001123 typedef object::Elf_Sym_Impl<target_endianness, is64Bits> Elf_Sym;
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001124 typedef object::Elf_Phdr<target_endianness, is64Bits> Elf_Phdr;
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001125 ELFWriter(const WriterOptionsELF &options);
1126 virtual error_code writeFile(const lld::File &File, StringRef path);
Sid Manningdd110202012-09-25 18:22:09 +00001127 uint64_t addressOfAtom(const Atom *atom);
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001128
1129 std::vector<Chunk<target_endianness, is64Bits>*> chunks() const {
1130 return _chunks; }
1131
Sid Manningdd110202012-09-25 18:22:09 +00001132 KindHandler *kindHandler() { return _referenceKindHandler.get(); }
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001133
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001134 std::vector<SectionChunk<target_endianness, is64Bits>*> sectionChunks() const {
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001135 return _sectionChunks ;
1136 }
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001137
1138 ELFStringSectionChunk<target_endianness, is64Bits> *shstrtab() const {
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001139 return _shstrtable;
1140 }
Hemant Kulkarni08e410292012-10-01 23:53:20 +00001141
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001142 ELFStringSectionChunk<target_endianness, is64Bits> *strtab() const {
Hemant Kulkarni08e410292012-10-01 23:53:20 +00001143 return _strtable;
1144 }
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001145 ELFSymbolTableChunk<target_endianness, is64Bits> *symtab() const {
Hemant Kulkarni08e410292012-10-01 23:53:20 +00001146 return _symtable;
1147 }
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001148
1149private:
1150 void build(const lld::File &file);
1151 void createChunks(const lld::File &file);
Sid Manningdd110202012-09-25 18:22:09 +00001152 void buildAtomToAddressMap();
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001153 void assignFileOffsets();
1154 const WriterOptionsELF &_options;
Sid Manningdd110202012-09-25 18:22:09 +00001155
1156/// \brief AtomToAddress: Is a mapping from an Atom to the address where
1157/// it will live in the output file.
1158 typedef llvm::DenseMap<const Atom*, uint64_t> AtomToAddress;
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001159 typedef typename std::vector<Chunk<target_endianness, is64Bits>*>
1160 ::iterator chunkIterator;
1161 ELFProgramHeaderChunk<target_endianness, is64Bits> *_phdr;
1162 ELFHeaderChunk<target_endianness, is64Bits> *ehc;
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001163 ELFStringSectionChunk<target_endianness, is64Bits> *_shstrtable ;
Hemant Kulkarni08e410292012-10-01 23:53:20 +00001164 ELFStringSectionChunk<target_endianness, is64Bits> *_strtable ;
1165 ELFSymbolTableChunk<target_endianness, is64Bits> *_symtable;
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001166 std::unique_ptr<KindHandler> _referenceKindHandler;
1167 ELFSectionHeaderChunk<target_endianness, is64Bits> *_sectionHeaderChunk;
Sid Manningdd110202012-09-25 18:22:09 +00001168 AtomToAddress _atomToAddress;
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001169 std::vector<Chunk<target_endianness, is64Bits>*> _chunks;
1170 const DefinedAtom *_entryAtom;
1171 std::vector<SectionChunk<target_endianness, is64Bits>*> _sectionChunks;
Hemant Kulkarni08e410292012-10-01 23:53:20 +00001172 std::vector<StockSectionChunk<target_endianness, is64Bits>*>
1173 _stockSectionChunks;
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001174 llvm::BumpPtrAllocator _chunkAllocate;
1175};
1176
1177//===----------------------------------------------------------------------===//
1178// ELFWriter
1179//===----------------------------------------------------------------------===//
1180template<support::endianness target_endianness, bool is64Bits>
1181ELFWriter<target_endianness, is64Bits>
1182 ::ELFWriter(const WriterOptionsELF &options)
1183 : _options(options)
Sid Manning42064e52012-10-09 02:20:47 +00001184 , _referenceKindHandler(KindHandler::makeHandler(_options.machine(),
1185 target_endianness))
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001186{}
1187
1188template<support::endianness target_endianness, bool is64Bits>
1189void ELFWriter<target_endianness, is64Bits>::build(const lld::File &file){
Hemant Kulkarni08e410292012-10-01 23:53:20 +00001190// Create objects for each chunk.
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001191 createChunks(file);
1192 assignFileOffsets();
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001193 _phdr->createPHeaders();
1194 _sectionHeaderChunk->createHeaders();
1195 // Creating program headers changed its size. so we need to re-assign offsets
1196 assignFileOffsets();
1197 _sectionHeaderChunk->fixOffsets();
1198 _phdr->createPHeaders();
Sid Manningdd110202012-09-25 18:22:09 +00001199 buildAtomToAddressMap();
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001200 _symtable->fixSymbolValue();
1201 ehc->e_shentsize(_sectionHeaderChunk->size());
1202 ehc->e_shnum(_sectionHeaderChunk->count());
1203 // We need to put the index of section string table in ELF header
1204 // first two chunks are not sections so we subtract 2 to start sections
1205 // and add 1 since we have a NULL header
1206 ehc->e_shstrndx(_shstrtable->ordinal() - 1);
1207 ehc->e_phnum(_phdr->computeNumber());
1208 ehc->e_phoff(_phdr->fileOffset());
1209 ehc->e_phentsize(sizeof(Elf_Phdr));
Hemant Kulkarni736f7fb2012-11-21 21:07:36 +00001210 for (auto i : _stockSectionChunks) {
1211 if(const DefinedAtom* da = findDefinedAtomByName(_options.entryPoint(), i)) {
1212 ehc->e_entry(this->addressOfAtom(da));
1213 return;
1214 }
1215 }
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001216}
1217
1218template<support::endianness target_endianness, bool is64Bits>
1219void ELFWriter<target_endianness, is64Bits>
1220 ::createChunks (const lld::File &file) {
Hemant Kulkarni08e410292012-10-01 23:53:20 +00001221 std::map<StringRef, StockSectionChunk<target_endianness, is64Bits>*>
1222 sectionMap;
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001223
Hemant Kulkarni08e410292012-10-01 23:53:20 +00001224// Make header chunk
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001225 ehc = new (_chunkAllocate.Allocate
Hemant Kulkarni08e410292012-10-01 23:53:20 +00001226 <ELFHeaderChunk<target_endianness, is64Bits>>())
1227 ELFHeaderChunk<target_endianness, is64Bits>(_options, file);
1228 _chunks.push_back(ehc);
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001229
1230 _phdr = new (_chunkAllocate.Allocate
1231 <ELFProgramHeaderChunk<target_endianness, is64Bits>>())
1232 ELFProgramHeaderChunk<target_endianness, is64Bits>(_options,
1233 *this);
1234 _chunks.push_back(_phdr);
Hemant Kulkarni08e410292012-10-01 23:53:20 +00001235
Hemant Kulkarni08e410292012-10-01 23:53:20 +00001236// We need to create hand crafted sections such as shstrtab strtab hash and
1237// symtab to put relevant information in ELF structures and then process the
1238// atoms.
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001239
1240 _shstrtable = new (_chunkAllocate.Allocate
1241 <ELFStringSectionChunk<target_endianness, is64Bits>>())
1242 ELFStringSectionChunk<target_endianness, is64Bits>
1243 (_options, *this, ".shstrtab");
Hemant Kulkarni08e410292012-10-01 23:53:20 +00001244 _shstrtable->setShStrtableOffset(_shstrtable->addString(".shstrtab"));
1245 _sectionChunks.push_back(_shstrtable);
1246
1247 _strtable = new (_chunkAllocate.Allocate
1248 <ELFStringSectionChunk<target_endianness, is64Bits>>())
1249 ELFStringSectionChunk<target_endianness, is64Bits>
1250 (_options, *this, ".strtab");
1251 _strtable->setShStrtableOffset( _shstrtable->addString(".strtab"));
1252 _sectionChunks.push_back(_strtable);
1253
1254 _symtable = new (_chunkAllocate.Allocate
1255 <ELFSymbolTableChunk<target_endianness, is64Bits>>())
1256 ELFSymbolTableChunk<target_endianness, is64Bits>
1257 (_options, *this, ".symtab");
1258 _symtable->setShStrtableOffset( _shstrtable->addString(".symtab"));
1259 _sectionChunks.push_back(_symtable);
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001260
Hemant Kulkarni08e410292012-10-01 23:53:20 +00001261//TODO: implement .hash section
1262
Hemant Kulkarni736f7fb2012-11-21 21:07:36 +00001263 DEBUG_WITH_TYPE("WriterELF-layout", dbgs()
1264 << "Atoms in file" << file.path()<<":\n");
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001265 for (const DefinedAtom *a : file.defined() ) {
Hemant Kulkarni736f7fb2012-11-21 21:07:36 +00001266 DEBUG_WITH_TYPE("WriterELF-layout", dbgs()
1267 << a->name() << " type: " << a->contentType() <<"\n");
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001268 StringRef sectionName = a->customSectionName();
Hemant Kulkarni08e410292012-10-01 23:53:20 +00001269 if (a->sectionChoice() ==
1270 DefinedAtom::SectionChoice::sectionBasedOnContent) {
Hemant Kulkarni8bd27612012-10-03 23:27:33 +00001271 if (a->contentType() == DefinedAtom::typeZeroFill)
Hemant Kulkarni08e410292012-10-01 23:53:20 +00001272 sectionName = ".bss";
1273 }
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001274 auto pos = sectionMap.find(sectionName);
1275 DefinedAtom::ContentType type = a->contentType();
Hemant Kulkarni08e410292012-10-01 23:53:20 +00001276 if (type != DefinedAtom::typeUnknown){
1277 if (pos == sectionMap.end()) {
1278 StockSectionChunk<target_endianness, is64Bits>
1279 *chunk = new(_chunkAllocate.Allocate
1280 <StockSectionChunk<target_endianness, is64Bits>>
1281 ())StockSectionChunk<target_endianness, is64Bits>
1282 (sectionName, true, type, _options, *this);
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001283
Hemant Kulkarni08e410292012-10-01 23:53:20 +00001284 sectionMap[sectionName] = chunk;
1285 chunk->appendAtom(a);
1286 _sectionChunks.push_back(chunk);
1287 _stockSectionChunks.push_back(chunk);
1288
1289 } else {
1290 pos->second->appendAtom(a);
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001291 }
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001292 }
1293 }
1294
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001295 for (auto chnk : _sectionChunks)
1296 _chunks.push_back(chnk);
Hemant Kulkarni08e410292012-10-01 23:53:20 +00001297
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001298 _sectionHeaderChunk = new (_chunkAllocate.Allocate<ELFSectionHeaderChunk
1299 <target_endianness, is64Bits>>())
1300 ELFSectionHeaderChunk
1301 <target_endianness, is64Bits>(_options, *this);
1302 _chunks.push_back(_sectionHeaderChunk);
1303 // We sort the chunks based on the group they belong to
1304 std::stable_sort(_chunks.begin(), _chunks.end(),
1305 chunkGroupSort<target_endianness, is64Bits>);
1306
1307 // The CG_RW group also has to be arranged such that all
1308 // SHT_NOBITS type of sections (.*bss) are at end of this
1309 // "partition" of group.
1310 chunkIterator cI;
1311 std::pair<chunkIterator, chunkIterator> range;
1312 range = std::equal_range(_chunks.begin() + 2, _chunks.end() - 1, CG_RW,
1313 ChunkComparator<target_endianness, is64Bits>());
1314
1315 cI = std::stable_partition(range.first, range.second,
1316 IsBss<target_endianness, is64Bits>);
Hemant Kulkarni08e410292012-10-01 23:53:20 +00001317
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001318 // We reassign all the ordinals since its needed when making headers and
1319 // populating symbol table.
1320 uint64_t i = 0;
1321 for (auto chnk : _chunks) {
1322 chnk->setOrdinal(i++);
1323 }
Hemant Kulkarni08e410292012-10-01 23:53:20 +00001324
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001325 // We sort the sections as per new ordinal set after group sorting.
Hemant Kulkarni08e410292012-10-01 23:53:20 +00001326 std::stable_sort(_sectionChunks.begin(), _sectionChunks.end(),([]
1327 (const SectionChunk<target_endianness, is64Bits> *A,
1328 const SectionChunk<target_endianness, is64Bits> *B) -> bool {
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001329 return A->ordinal() < B->ordinal();}));
Hemant Kulkarni08e410292012-10-01 23:53:20 +00001330
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001331 // Populate symbol table with correct st_shndx member.
Hemant Kulkarni736f7fb2012-11-21 21:07:36 +00001332 for (auto chnk : _sectionChunks ) {
1333 Elf_Sym *sym = new (_chunkAllocate.Allocate<Elf_Sym>()) Elf_Sym;
1334 sym->st_name = 0;
1335 sym->st_value = 0;
1336 sym->st_size = 0;
1337 sym->st_other = ELF::STV_DEFAULT;
1338 // first two chunks are not sections hence we subtract 2 but there is a
1339 // NULL section in section table so add 1
1340 sym->st_shndx = chnk->ordinal() - 1 ;
1341 sym->setBindingAndType(ELF::STB_LOCAL, ELF::STT_SECTION);
1342 _symtable->addSymbol(sym);
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001343 }
Hemant Kulkarni08e410292012-10-01 23:53:20 +00001344 for (const auto ssc : _stockSectionChunks){
1345 for (const auto da : ssc->atoms()) {
1346 _symtable->addSymbol(std::get<0>(da), ssc->ordinal() -1);
1347 }
1348 }
1349 for (const UndefinedAtom *a : file.undefined()) {
1350 _symtable->addSymbol(a, ELF::SHN_UNDEF);
1351 }
1352
1353 for (const AbsoluteAtom *a : file.absolute()) {
1354 _symtable->addSymbol(a, ELF::SHN_ABS);
1355 }
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001356}
1357
Sid Manningdd110202012-09-25 18:22:09 +00001358template<support::endianness target_endianness, bool is64Bits>
1359void ELFWriter<target_endianness, is64Bits>
1360 ::buildAtomToAddressMap () {
1361
1362// _atomToAddress is a DenseMap that maps an atom its file address.
1363// std::get<1>(ai) is the offset from the start of the section to the atom.
Hemant Kulkarni08e410292012-10-01 23:53:20 +00001364 for (auto chunk : _stockSectionChunks){
Sid Manningdd110202012-09-25 18:22:09 +00001365 for (auto &ai : chunk->atoms() ) {
1366 _atomToAddress[std::get<0>(ai)] = chunk->address() + std::get<1>(ai);
1367 }
1368 }
Sid Manningdd110202012-09-25 18:22:09 +00001369}
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001370
1371template<support::endianness target_endianness, bool is64Bits>
1372void ELFWriter<target_endianness, is64Bits>::assignFileOffsets() {
1373 DEBUG_WITH_TYPE("WriterELF-layout", dbgs()
1374 << "assign file offsets:\n");
1375 uint64_t offset = 0;
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001376 uint64_t address = _options.type() == ELF::ET_REL ? 0 :
1377 _options.baseAddress();
1378 uint16_t chunkGroup;
1379 auto chunkIt = _chunks.begin();
1380 // first (two in case of ET_EXEC or ET_DYN) chunks is (are) not section(s)
1381 (*chunkIt)->assignFileOffset(offset, address);
1382 chunkIt++;
1383 if (_options.type() == ELF::ET_EXEC ||
1384 _options.type() == ELF::ET_DYN) {
1385 (*chunkIt)->assignFileOffset(offset, address);
1386 chunkIt++;
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001387 }
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001388 while (chunkIt != (_chunks.end() - 1) ) {
1389 (*chunkIt)->assignFileOffset(offset, address);
1390 if (_options.type() == ELF::ET_EXEC ||
1391 _options.type() == ELF::ET_DYN) {
1392 chunkGroup = (*chunkIt)->group();
1393 chunkIt++;
1394 // If the chunk group changes we start on new page
1395 if (chunkGroup != (*chunkIt)->group() && (*chunkIt)->group() != CG_NO_LOAD
1396 && (*chunkIt)->group() != CG_FILE_END)
1397 address = address + _options.pageSize();
1398 } else {
1399 chunkIt++;
1400 }
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001401 }
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001402 (*chunkIt)->assignFileOffset(offset, address);
1403 ehc->e_shoff(_sectionHeaderChunk->fileOffset());
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001404}
1405
1406template<support::endianness target_endianness, bool is64Bits>
1407error_code ELFWriter<target_endianness, is64Bits>
1408 ::writeFile(const lld::File &file, StringRef path) {
1409 build(file);
1410
1411 uint64_t totalSize = _chunks.back()->fileOffset() + _chunks.back()->size();
1412
1413 OwningPtr<FileOutputBuffer> buffer;
1414 error_code ec = FileOutputBuffer::create(path,
1415 totalSize, buffer,
1416 FileOutputBuffer::F_executable);
1417 if (ec)
1418 return ec;
1419
1420 for (auto chunk : _chunks) {
1421 chunk->write(buffer->getBufferStart() + chunk->fileOffset());
1422 }
1423 return buffer->commit();
1424}
Nick Kledzikabb69812012-05-31 22:34:00 +00001425
Sid Manningdd110202012-09-25 18:22:09 +00001426template<support::endianness target_endianness, bool is64Bits>
1427uint64_t ELFWriter<target_endianness, is64Bits>
1428 ::addressOfAtom(const Atom *atom) {
1429 return _atomToAddress[atom];
1430}
Nick Kledzikabb69812012-05-31 22:34:00 +00001431} // namespace elf
1432
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001433Writer *createWriterELF(const WriterOptionsELF &options) {
1434 if (!options.is64Bit() && options.endianness() == llvm::support::little)
Hemant Kulkarni08e410292012-10-01 23:53:20 +00001435 return new lld::elf::ELFWriter<support::little, false>(options);
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001436 else if (options.is64Bit() && options.endianness() == llvm::support::little)
1437 return new lld::elf::ELFWriter<support::little, true>(options);
1438 else if (!options.is64Bit() && options.endianness() == llvm::support::big)
1439 return new lld::elf::ELFWriter<support::big, false>(options);
1440 else if (options.is64Bit() && options.endianness() == llvm::support::big)
1441 return new lld::elf::ELFWriter<support::big, true>(options);
Nick Kledzikabb69812012-05-31 22:34:00 +00001442
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001443 llvm_unreachable("Invalid Options!");
Nick Kledzikabb69812012-05-31 22:34:00 +00001444}
Nick Kledzikabb69812012-05-31 22:34:00 +00001445} // namespace lld