blob: 2c4d384cd5dbec3dd025aade65ea6833bafd0759 [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 Kulkarni927bbc22012-09-14 16:11:34 +000091/// \brief A Chunk is a contiguous range of space.
92template<support::endianness target_endianness, bool is64Bits>
93class Chunk {
94public:
95 LLVM_ELF_IMPORT_TYPES(target_endianness, is64Bits)
96 virtual ~Chunk() {}
97 virtual StringRef segmentName() const = 0;
98 virtual bool occupiesNoDiskSpace();
99 virtual void write(uint8_t *fileBuffer) = 0;
100 void assignFileOffset(uint64_t &curOff, uint64_t &curAddr);
101 virtual const char *info() = 0;
102 uint64_t size() const;
103 uint64_t address() const;
104 uint64_t fileOffset() const;
105 uint64_t align2() const;
106 static uint64_t alignTo(uint64_t value, uint8_t align2);
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000107 uint64_t ordinal() const { return _ordinal;}
108 void setOrdinal(uint64_t newVal) { _ordinal = newVal;}
Hemant Kulkarni87dbac02012-11-13 21:34:45 +0000109 void setGroup(uint16_t val) { _group = val;}
110 uint16_t group() const { return _group;}
111 void init();
112 bool isLoadable() { return _isLoadable; }
113 void isLoadable(uint64_t val) { _isLoadable = val; }
114 enum class Kind {
115 Header, // This is a header chunk
116 Section // chunk represents a section
117 };
118 Kind getChunkKind() const { return _cKind; }
119private:
120 const Kind _cKind;
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000121protected:
122 Chunk();
Hemant Kulkarni87dbac02012-11-13 21:34:45 +0000123 Chunk(Kind K): _cKind(K) { this->init();}
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000124 uint64_t _size;
125 uint64_t _address;
126 uint64_t _fileOffset;
127 uint64_t _align2;
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000128 uint64_t _ordinal;
Hemant Kulkarni87dbac02012-11-13 21:34:45 +0000129 uint16_t _group;
130 bool _isLoadable;
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000131};
132
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000133template<support::endianness target_endianness, bool is64Bits>
134static void swapChunkPositions(Chunk<target_endianness, is64Bits>&a,
135 Chunk<target_endianness, is64Bits>&b) {
136 uint64_t tempOrdinal;
137 if (a.ordinal() == b.ordinal()) return;
138 tempOrdinal = a.ordinal();
139 a.setOrdinal(b.ordinal());
140 b.setOrdinal(tempOrdinal);
141}
142
Hemant Kulkarni87dbac02012-11-13 21:34:45 +0000143template<support::endianness target_endianness, bool is64Bits>
144bool chunkGroupSort(Chunk<target_endianness, is64Bits> *A,
145 Chunk<target_endianness, is64Bits> *B) {
146 if (A->group() == CG_INVALID || B->group() == CG_INVALID)
147 llvm_unreachable("Invalid group number");
148 return A->group() < B->group();
149}
150
151template<support::endianness target_endianness, bool is64Bits>
152struct ChunkComparator {
153 bool operator()(uint16_t A, Chunk<target_endianness, is64Bits> *B) {
154 return A < B->group();
155 }
156 bool operator()(Chunk<target_endianness, is64Bits> *A, uint16_t B) {
157 return A->group() < B;
158 }
159#if defined(_ITERATOR_DEBUG_LEVEL) && _ITERATOR_DEBUG_LEVEL == 2
160 bool operator()(Chunk<target_endianness, is64Bits> *A,
161 Chunk<target_endianness, is64Bits> *B) {
162 return A->group() < B->group();
163 }
164#endif
165};
166
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000167/// Pair of atom and offset in section.
168typedef std::tuple<const DefinedAtom*, uint64_t> AtomInfo;
169
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000170/// \brief A SectionChunk represents ELF sections
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000171template<support::endianness target_endianness, bool is64Bits>
172class SectionChunk : public Chunk<target_endianness, is64Bits> {
173public:
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000174 virtual StringRef segmentName() const { return _segmentName; }
175 virtual bool occupiesNoDiskSpace();
176 virtual const char *info();
177 StringRef sectionName() { return _sectionName; }
178 uint64_t shStrtableOffset(){ return _offsetInStringTable; }
179 void setShStrtableOffset (uint64_t val) {
180 _offsetInStringTable = val; }
181 uint32_t flags() { return _flags; }
Hemant Kulkarni87dbac02012-11-13 21:34:45 +0000182 uint32_t type() const { return _type; }
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000183 uint64_t link() { return _link; }
184 void link(uint64_t val) { _link = val; }
185 uint16_t shinfo() { return _shinfo; }
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000186 uint64_t entsize() { return _entsize; }
187 SectionChunk(StringRef secName, StringRef segName, bool loadable,
188 uint64_t flags , uint64_t link, uint64_t info ,
189 uint64_t type, uint64_t entsz, const WriterOptionsELF &op,
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000190 ELFWriter<target_endianness, is64Bits> &writer);
191
Hemant Kulkarni87dbac02012-11-13 21:34:45 +0000192 static inline bool classof(const Chunk<target_endianness, is64Bits> *c) {
193 return c->getChunkKind() == Chunk<target_endianness, is64Bits>::Kind
194 ::Section;
195 }
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000196protected:
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000197 uint64_t _link;
198 uint64_t _shinfo;
199 uint16_t _entsize;
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000200 StringRef _segmentName;
201 StringRef _sectionName;
202 const WriterOptionsELF &_options;
203 ELFWriter<target_endianness, is64Bits> &_writer;
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000204 uint64_t _flags;
205 uint64_t _type;
206 uint64_t _offsetInStringTable;
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000207};
208
Hemant Kulkarni87dbac02012-11-13 21:34:45 +0000209template<support::endianness target_endianness, bool is64Bits>
210bool IsBss(const Chunk<target_endianness, is64Bits> *A) {
211 if (auto X = llvm::dyn_cast<SectionChunk<target_endianness, is64Bits>>(A))
212 return X->type() != ELF::SHT_NOBITS;
213 llvm_unreachable("Call to a non section type chunk");
214 // adding a non-reachable return bool for making compiler happy
215 return false;
216}
217
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000218/// \brief A StockSectionChunk is a section created by linker with all
219/// attributes concluded from the defined atom contained within.
220template<support::endianness target_endianness, bool is64Bits>
221class StockSectionChunk : public SectionChunk<target_endianness, is64Bits> {
222public:
Michael J. Spencera1913fb2012-11-01 19:46:19 +0000223 virtual StringRef segmentName() const { return this->_segmentName; }
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000224 void appendAtom(const DefinedAtom*);
225 virtual void write(uint8_t *filebuffer);
226 const ArrayRef<AtomInfo> atoms() const;
227 StockSectionChunk(StringRef sectionName, bool loadable,
228 DefinedAtom::ContentType type,
229 const WriterOptionsELF &options,
230 ELFWriter<target_endianness, is64Bits> &writer);
231private:
232 std::vector<AtomInfo> _atoms;
233};
234
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000235/// \brief An ELFHeaderChunk represents the Elf[32/64]_Ehdr structure at the
236/// start of an ELF executable file.
237template<support::endianness target_endianness, bool is64Bits>
238class ELFHeaderChunk : public Chunk<target_endianness, is64Bits> {
239public:
240 LLVM_ELF_IMPORT_TYPES(target_endianness, is64Bits)
241 typedef object::Elf_Ehdr_Impl<target_endianness, is64Bits> Elf_Ehdr;
242
243 ELFHeaderChunk(const WriterOptionsELF &options,
244 const File &file);
245
246 void e_ident(int I, unsigned char C) { _eh.e_ident[I] = C; }
247 void e_type(uint16_t type) { _eh.e_type = type; }
248 void e_machine(uint16_t machine) { _eh.e_machine = machine; }
249 void e_version(uint32_t version) { _eh.e_version = version; }
250 void e_entry(uint64_t entry) { _eh.e_entry = entry; }
251 void e_phoff(uint64_t phoff) { _eh.e_phoff = phoff; }
252 void e_shoff(uint64_t shoff) { _eh.e_shoff = shoff; }
253 void e_flags(uint32_t flags) { _eh.e_flags = flags; }
254 void e_ehsize(uint16_t ehsize) { _eh.e_ehsize = ehsize; }
255 void e_phentsize(uint16_t phentsize) { _eh.e_phentsize = phentsize; }
256 void e_phnum(uint16_t phnum) { _eh.e_phnum = phnum; }
257 void e_shentsize(uint16_t shentsize) { _eh.e_shentsize = shentsize; }
258 void e_shnum(uint16_t shnum) { _eh.e_shnum = shnum; }
259 void e_shstrndx(uint16_t shstrndx) { _eh.e_shstrndx = shstrndx; }
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000260 uint64_t size() { return sizeof (Elf_Ehdr); }
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000261
262 virtual StringRef segmentName() const;
263 virtual void write(uint8_t *fileBuffer);
264 virtual const char *info();
Hemant Kulkarni87dbac02012-11-13 21:34:45 +0000265 static inline bool classof(const Chunk<target_endianness, is64Bits> *c) {
266 return c->getChunkKind() == Chunk<target_endianness, is64Bits>::Kind
267 ::Header;
268 }
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000269
270private:
271 Elf_Ehdr _eh;
272};
273
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000274/// \brief An ELFSectionHeaderChunk represents the Elf[32/64]_Shdr structure
275/// that is placed right after the ELFHeader.
276///
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000277template<support::endianness target_endianness, bool is64Bits>
278class ELFSectionHeaderChunk : public Chunk<target_endianness, is64Bits> {
279public:
280 LLVM_ELF_IMPORT_TYPES(target_endianness, is64Bits)
281 typedef object::Elf_Shdr_Impl<target_endianness, is64Bits> Elf_Shdr;
282 ELFSectionHeaderChunk(const WriterOptionsELF &Options,
283 ELFWriter<target_endianness, is64Bits>&);
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000284 void createHeaders();
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000285 virtual StringRef segmentName() const;
286 virtual void write(uint8_t *filebuffer);
287 virtual const char *info();
Hemant Kulkarni87dbac02012-11-13 21:34:45 +0000288 void computeSize();
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000289 uint16_t count();
290 uint16_t size();
Hemant Kulkarni87dbac02012-11-13 21:34:45 +0000291 void fixOffsets();
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000292 const ArrayRef<Elf_Shdr*> sectionInfo() {
293 return _sectionInfo;
294 }
Hemant Kulkarni87dbac02012-11-13 21:34:45 +0000295 static inline bool classof(const Chunk<target_endianness, is64Bits> *c) {
296 return c->getChunkKind() == Chunk<target_endianness, is64Bits>::Kind
297 ::Header;
298 }
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000299
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000300private:
301 const WriterOptionsELF &_options;
302 ELFWriter<target_endianness, is64Bits> &_writer;
303 llvm::BumpPtrAllocator _sectionAllocate;
304 std::vector<Elf_Shdr*> _sectionInfo;
305};
306
307/// \brief Represents the shstr section.
308///
309/// This is a contiguous memory that has all the symbol strings each ending with
310/// null character. We might need more than one such chunks shstrtab for setting
311/// e_shstrndx in ELHHeaderChunk and strtab for use with symtab
312template<support::endianness target_endianness, bool is64Bits>
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000313class ELFStringSectionChunk : public SectionChunk<target_endianness, is64Bits> {
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000314public:
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000315 ELFStringSectionChunk(const WriterOptionsELF &Options,
316 ELFWriter<target_endianness, is64Bits> &writer,
317 StringRef secName);
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000318 virtual StringRef segmentName() const { return this->_segmentName; }
319 uint64_t addString(StringRef symName);
320 const char *info();
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000321 virtual void write(uint8_t *filebuffer);
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000322
323private:
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000324 std::vector<StringRef> _stringSection;
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000325};
326
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000327/// \brief Represents the symtab section
328///
329/// ELFSymbolTableChunk represents the Symbol table as per ELF ABI
330/// This is a table with Elf[32/64]_Sym entries in it.
331template<support::endianness target_endianness, bool is64Bits>
332class ELFSymbolTableChunk : public SectionChunk<target_endianness, is64Bits> {
333public:
334 typedef object::Elf_Sym_Impl<target_endianness, is64Bits> Elf_Sym;
335 ELFSymbolTableChunk(const WriterOptionsELF &options,
336 ELFWriter<target_endianness, is64Bits> &writer,
337 StringRef secName);
338 virtual StringRef segmentName() const { return this->_segmentName; }
339 void addSymbol(const Atom *a, uint16_t shndx);
340 void addSymbol(Elf_Sym *x);
Hemant Kulkarni87dbac02012-11-13 21:34:45 +0000341 void fixSymbolValue();
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000342 const char *info();
343 void setAttributes();
344 virtual void write(uint8_t *fileBuffer);
345
346private:
347 std::vector<Elf_Sym*> _symbolTable;
348 ELFStringSectionChunk<target_endianness, is64Bits> *_stringSection;
349 llvm::BumpPtrAllocator _symbolAllocate;
Hemant Kulkarni87dbac02012-11-13 21:34:45 +0000350 std::map<Elf_Sym*, const Atom*> _symbolToAtom;
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000351};
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000352
Hemant Kulkarni87dbac02012-11-13 21:34:45 +0000353/// \brief ELFProgramHeaderChunk represents the Elf[32/64]_Phdr structure near
354/// the start of an ELF executable file. ELFHeader's e_phentsize and e_phnum
355/// show the number of entries in table and size of each one.
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000356template<support::endianness target_endianness, bool is64Bits>
357class ELFProgramHeaderChunk : public Chunk<target_endianness, is64Bits> {
358public:
359 LLVM_ELF_IMPORT_TYPES(target_endianness, is64Bits)
Hemant Kulkarni87dbac02012-11-13 21:34:45 +0000360 typedef object::Elf_Phdr<target_endianness, is64Bits> Elf_Phdr;
361 ELFProgramHeaderChunk(const WriterOptionsELF &options,
362 ELFWriter<target_endianness, is64Bits> &);
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000363
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000364 virtual StringRef segmentName() const;
365 virtual void write(uint8_t *filebuffer);
366 virtual const char *info();
Hemant Kulkarni87dbac02012-11-13 21:34:45 +0000367 void createPHeaders();
368 uint64_t computeNumber();
369 static inline bool classof(const Chunk<target_endianness, is64Bits> *c) {
370 return c->getChunkKind() == Chunk<target_endianness, is64Bits>::Kind
371 ::Header;
372 }
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000373
374private:
Hemant Kulkarni87dbac02012-11-13 21:34:45 +0000375 typedef typename std::vector<SectionChunk<target_endianness, is64Bits>*>
376 ::iterator secIterator;
377 const WriterOptionsELF &_options;
378 ELFWriter<target_endianness, is64Bits> &_writer;
379 std::vector<Elf_Phdr*> _programHeaders;
380 llvm::BumpPtrAllocator _headerAllocate;
381 typedef std::pair<uint64_t, uint64_t> sectionRange;
382 std::vector<sectionRange> _segments;
383 std::map<uint16_t, uint16_t> _groupToPF;
384
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000385};
386
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000387//===----------------------------------------------------------------------===//
388// Chunk
389//===----------------------------------------------------------------------===//
390
391template<support::endianness target_endianness, bool is64Bits>
Hemant Kulkarni87dbac02012-11-13 21:34:45 +0000392Chunk<target_endianness, is64Bits>::Chunk(){
393 this->init();
394}
395
396template<support::endianness target_endianness, bool is64Bits>
397void Chunk<target_endianness, is64Bits>::init(){
398 this->_size = 0;
399 this->_address = 0;
400 this->_fileOffset = 0;
401 this->_align2 = 0;
402 this->_group = CG_INVALID;
403 this->_isLoadable = false;
404 // 0 and 1 are reserved. 0 for ELF header and 1 for program header.
405 static uint64_t orderNumber = 0;
406 _ordinal = orderNumber++;
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000407}
408
409template<support::endianness target_endianness, bool is64Bits>
410bool Chunk<target_endianness, is64Bits>::occupiesNoDiskSpace() {
411 return false;
412}
413
414template<support::endianness target_endianness, bool is64Bits>
415uint64_t Chunk<target_endianness, is64Bits>::size() const {
416 return _size;
417}
418
419template<support::endianness target_endianness, bool is64Bits>
420uint64_t Chunk<target_endianness, is64Bits>::align2() const {
421 return _align2;
422}
423
424template<support::endianness target_endianness, bool is64Bits>
425uint64_t Chunk<target_endianness, is64Bits>::address() const {
426 return _address;
427}
428
429template<support::endianness target_endianness, bool is64Bits>
430uint64_t Chunk<target_endianness, is64Bits>::fileOffset() const {
431 return _fileOffset;
432}
433
434template<support::endianness target_endianness, bool is64Bits>
435uint64_t Chunk<target_endianness, is64Bits>::
436 alignTo(uint64_t value, uint8_t align2) {
437 uint64_t align = 1 << align2;
438 return (value + (align - 1)) & (-align);
439}
440
441template<support::endianness target_endianness, bool is64Bits>
442void Chunk<target_endianness, is64Bits>::
443 assignFileOffset(uint64_t &curOffset, uint64_t &curAddress) {
444 if (occupiesNoDiskSpace()) {
445 // FileOffset does not change, but virtual address does change.
446 uint64_t alignedAddress =
447 alignTo(curAddress, _align2 ? static_cast<uint8_t>(llvm::Log2_64(_align2))
448 : 0);
449 _address = alignedAddress;
450 curAddress = alignedAddress + _size;
451 } else {
452 // FileOffset and address both move by _size amount after alignment.
453 uint64_t alignPadding =
454 alignTo(curAddress, _align2 ? static_cast<uint8_t>(llvm::Log2_64(_align2))
455 : 0) - curAddress;
456 _fileOffset = curOffset + alignPadding;
457 _address = curAddress + alignPadding;
458 curOffset = _fileOffset + _size;
459 curAddress = _address + _size;
460 }
461
462 DEBUG_WITH_TYPE("WriterELF-layout", dbgs()
463 << " fileOffset="
464 << format("0x%08X", _fileOffset)
465 << " address="
466 << format("0x%016X", _address)
467 << " info=" << info() << "\n");
468}
469
470//===----------------------------------------------------------------------===//
471// SectionChunk
472//===----------------------------------------------------------------------===//
473
474template<support::endianness target_endianness, bool is64Bits>
475SectionChunk<target_endianness, is64Bits>::
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000476 SectionChunk(StringRef secName, StringRef segName, bool loadable,
477 uint64_t flags , uint64_t link, uint64_t info , uint64_t type,
478 uint64_t entsz, const WriterOptionsELF &op,
479 ELFWriter<target_endianness, is64Bits> &writer)
Hemant Kulkarni87dbac02012-11-13 21:34:45 +0000480 : Chunk<target_endianness, is64Bits>(Chunk<target_endianness, is64Bits>
481 ::Kind::Section)
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000482 , _link(link)
483 , _shinfo(info)
484 , _entsize(entsz)
485 , _segmentName(segName)
486 , _sectionName(secName)
487 , _options(op)
488 , _writer(writer)
489 , _flags(flags)
490 , _type(type)
Hemant Kulkarni87dbac02012-11-13 21:34:45 +0000491 , _offsetInStringTable(0) {
492 this->isLoadable(loadable);
493}
494//FIXME: We need to make decision here for every section created
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000495template<support::endianness target_endianness, bool is64Bits>
496bool SectionChunk<target_endianness, is64Bits>::occupiesNoDiskSpace() {
497 return false;
498}
499
500template<support::endianness target_endianness, bool is64Bits>
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000501const char *SectionChunk<target_endianness, is64Bits>::info() {
502 return _sectionName.data();
503}
504
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000505//===----------------------------------------------------------------------===//
506// StockSectionChunk
507//===----------------------------------------------------------------------===//
508
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000509template<support::endianness target_endianness, bool is64Bits>
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000510StockSectionChunk<target_endianness, is64Bits>::
511 StockSectionChunk(StringRef secName, bool loadable,
512 DefinedAtom::ContentType type,
513 const WriterOptionsELF &options,
514 ELFWriter<target_endianness, is64Bits> &writer)
515 : SectionChunk<target_endianness, is64Bits>(secName, "PT_NULL",
516 loadable, 0lu, 0lu, 0u, 0lu, 0lu,
517 options, writer) {
518 this->_segmentName = this->_isLoadable ? "PT_LOAD" : "PT_NULL" ;
Hemant Kulkarni87dbac02012-11-13 21:34:45 +0000519 // If the section is custom loadable section, group should be set explicitly.
520 // Stock non loadable section go as NO_LOAD and others will get their
521 // group determined by the atoms contained within. Many constant
522 // sections will have no symbols but the constants are referred as
523 // offset from start symbol, hence there may not be any defined atoms being
524 // appended to them, we force them at time of creation to CG_R
525 this->setGroup(this->isLoadable() ? CG_INVALID : CG_NO_LOAD);
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000526 switch(type) {
527 case DefinedAtom::typeCode:
528 this->_type = ELF::SHT_PROGBITS;
529 break;
530 case DefinedAtom::typeData:
531 this->_type = ELF::SHT_PROGBITS;
532 break;
533 case DefinedAtom::typeZeroFill:
534 this->_type = ELF::SHT_NOBITS;
Hemant Kulkarni8bd27612012-10-03 23:27:33 +0000535 break;
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000536 case DefinedAtom::typeConstant:
537 this->_type = ELF::SHT_PROGBITS;
Hemant Kulkarni87dbac02012-11-13 21:34:45 +0000538 this->_flags = ELF::SHF_ALLOC;
539 this->setGroup(CG_R);
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000540 break;
541 default:
542 llvm_unreachable("Unhandled content type for section!");
543 }
544}
545
546
547template<support::endianness target_endianness, bool is64Bits>
548const ArrayRef<AtomInfo> StockSectionChunk<target_endianness, is64Bits>::
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000549 atoms() const {
550 return _atoms;
551}
552
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000553template<support::endianness target_endianness, bool is64Bits>
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000554void StockSectionChunk<target_endianness, is64Bits>::
555 appendAtom(const DefinedAtom *atom) {
Hemant Kulkarni87dbac02012-11-13 21:34:45 +0000556 static uint16_t groupArray[] = {CG_INVALID, CG_W, CG_R, CG_RW, CG_X,
557 CG_WX, CG_RX, CG_RWX};
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000558 // Figure out offset for atom in this section given alignment constraints.
559 uint64_t offset = this->_size;
560 DefinedAtom::Alignment atomAlign = atom->alignment();
561 uint64_t align2 = 1 << atomAlign.powerOf2;
562 uint64_t requiredModulus = atomAlign.modulus;
563 uint64_t currentModulus = (offset % align2);
564 if (currentModulus != requiredModulus) {
565 if (requiredModulus > currentModulus)
566 offset += requiredModulus - currentModulus;
567 else
568 offset += align2 + requiredModulus - currentModulus;
569 }
570 // Record max alignment of any atom in this section.
571 if (align2 > this->_align2)
572 this->_align2 = align2;
573 // Assign atom to this section with this offset.
574 _atoms.emplace_back(atom, offset);
575 // Update section size to include this atom.
576 this->_size = offset + atom->size();
577 // Update permissions
578 DefinedAtom::ContentPermissions perms = atom->permissions();
Hemant Kulkarni87dbac02012-11-13 21:34:45 +0000579
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000580 if ((perms & DefinedAtom::permR__) == DefinedAtom::permR__)
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000581 this->_flags |= ELF::SHF_ALLOC;
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000582 if ((perms & DefinedAtom::permRW_) == DefinedAtom::permRW_)
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000583 this->_flags |= (ELF::SHF_ALLOC | ELF::SHF_WRITE);
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000584 if ((perms & DefinedAtom::permR_X) == DefinedAtom::permR_X)
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000585 this->_flags |= (ELF::SHF_ALLOC | ELF::SHF_EXECINSTR);
Hemant Kulkarni87dbac02012-11-13 21:34:45 +0000586 if (atom->contentType() == DefinedAtom::typeZeroFill)
587 this->_flags |= (ELF::SHF_ALLOC | ELF::SHF_WRITE);
588 this->setGroup(groupArray[this->_flags]);
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000589}
590
591template<support::endianness target_endianness, bool is64Bits>
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000592void StockSectionChunk<target_endianness, is64Bits>
593 ::write(uint8_t *chunkBuffer) {
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000594 // Each section's content is just its atoms' content.
595 for (const auto &ai : _atoms ) {
596 // Copy raw content of atom to file buffer.
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000597 ArrayRef<uint8_t> content = std::get<0>(ai)->rawContent();
598 uint64_t contentSize = content.size();
599 if (contentSize == 0)
600 continue;
601 uint8_t *atomContent = chunkBuffer + std::get<1>(ai);
602 std::copy_n(content.data(), contentSize, atomContent);
Sid Manningdd110202012-09-25 18:22:09 +0000603
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000604 for (const Reference *ref : *std::get<0>(ai)){
605 uint32_t offset = ref->offsetInAtom();
606 uint64_t targetAddress = 0;
Sid Manningdd110202012-09-25 18:22:09 +0000607
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000608 if ( ref->target() != nullptr )
609 targetAddress = this->_writer.addressOfAtom(ref->target());
Sid Manningdd110202012-09-25 18:22:09 +0000610
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000611 uint64_t fixupAddress = this->_writer.addressOfAtom(std::get<0>(ai)) +
612 offset;
613 this->_writer.kindHandler()->applyFixup(ref->kind(), ref->addend(),
614 &atomContent[offset],
615 fixupAddress,
616 targetAddress);
Sid Manningdd110202012-09-25 18:22:09 +0000617 }
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000618 }
619}
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000620
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000621//===----------------------------------------------------------------------===//
622// ELFStringSectionChunk
623//===----------------------------------------------------------------------===//
624template<support::endianness target_endianness, bool is64Bits>
625ELFStringSectionChunk<target_endianness, is64Bits>::
626 ELFStringSectionChunk(const WriterOptionsELF &options,
627 ELFWriter<target_endianness, is64Bits> &writer,
628 StringRef secName)
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000629 : SectionChunk<target_endianness, is64Bits>(secName, "PT_NULL",
630 false, 0lu, 0lu, 0lu,
631 ELF::SHT_STRTAB, 0lu, options,
632 writer) {
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000633 // First Add a null character. It also occupies 1 byte
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000634 _stringSection.emplace_back("");
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000635 this->_size = 1;
Hemant Kulkarni87dbac02012-11-13 21:34:45 +0000636 this->setGroup(CG_NO_LOAD);
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000637}
638
639template<support::endianness target_endianness, bool is64Bits>
640uint64_t ELFStringSectionChunk<target_endianness, is64Bits>::
641 addString(StringRef symName) {
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000642 _stringSection.emplace_back(symName);
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000643 uint64_t offset = this->_size;
644 this->_size += symName.size() + 1;
645
646 return offset;
647}
648
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000649// We need to unwrap the _stringSection and then make one large memory
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000650// chunk of null terminated strings
651template<support::endianness target_endianness, bool is64Bits>
652void ELFStringSectionChunk<target_endianness, is64Bits>::
653 write(uint8_t *chunkBuffer) {
654 uint64_t chunkOffset = 0;
655
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000656 for (auto it : _stringSection) {
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000657 ::memcpy(chunkBuffer + chunkOffset, it.data(), it.size());
658 chunkOffset += it.size();
659 ::memcpy(chunkBuffer + chunkOffset, "", 1);
660 chunkOffset += 1;
661 }
662}
663
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000664template<support::endianness target_endianness, bool is64Bits>
665const char *ELFStringSectionChunk<target_endianness, is64Bits>::info() {
666 return "String Table";
667}
668
669//===----------------------------------------------------------------------===//
670// ELFSymbolTableChunk
671//===----------------------------------------------------------------------===//
672template< support::endianness target_endianness, bool is64Bits>
673ELFSymbolTableChunk<target_endianness, is64Bits>::ELFSymbolTableChunk
674 (const WriterOptionsELF &options,
675 ELFWriter<target_endianness, is64Bits> &writer,
676 StringRef secName)
677 : SectionChunk<target_endianness, is64Bits>(secName, StringRef("PT_NULL"),
678 false, 0, 0, 0, ELF::SHT_SYMTAB,
679 sizeof(Elf_Sym), options, writer)
680{
681 _stringSection = this->_writer.strtab();
682 Elf_Sym *symbol = new (_symbolAllocate.Allocate<Elf_Sym>()) Elf_Sym;
683 memset ((void *)symbol,0, sizeof(Elf_Sym));
684 _symbolTable.push_back(symbol);
685 this->_link = 0;
686 this->_entsize = sizeof(Elf_Sym);
687 this->_size = sizeof(Elf_Sym);
Hemant Kulkarni87dbac02012-11-13 21:34:45 +0000688 this->_align2 = this->_options.pointerWidth();
689 this->setGroup(CG_NO_LOAD);
690}
691
692template< support::endianness target_endianness, bool is64Bits>
693void ELFSymbolTableChunk<target_endianness, is64Bits>::fixSymbolValue(){
694 for (auto sym : _symbolTable) {
695 if ( sym->st_shndx != ELF::SHN_ABS) {
696 sym->st_value = this->_writer.addressOfAtom(_symbolToAtom[sym]);
697 }
698 }
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000699}
700
701template< support::endianness target_endianness, bool is64Bits>
702void ELFSymbolTableChunk<target_endianness, is64Bits>::addSymbol(Elf_Sym *sym){
703 _symbolTable.push_back(sym);
704 this->_size+= sizeof(Elf_Sym) ;
705}
706
707/// \brief Add symbols to symbol table
708/// We examine each property of atom to infer the various st_* fields in Elf*_Sym
709template< support::endianness target_endianness, bool is64Bits>
710void ELFSymbolTableChunk<target_endianness, is64Bits>
711 ::addSymbol(const Atom *a, uint16_t shndx) {
712 Elf_Sym *symbol = new(_symbolAllocate.Allocate<Elf_Sym>()) Elf_Sym;
713 unsigned char b = 0, t = 0;
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000714 symbol->st_name = _stringSection->addString(a->name());
Hemant Kulkarni87dbac02012-11-13 21:34:45 +0000715 _symbolToAtom[symbol] = a;
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000716// In relocatable files, st_value holds a section offset for a defined symbol.
717// st_value is an offset from the beginning of the section that st_shndx
718// identifies. After we assign file offsets we can set this value correctly.
719 symbol->st_size = 0;
720 symbol->st_shndx = shndx;
721 symbol->st_value = 0;
722// FIXME: Need to change and account all STV* when visibilities are supported
723 symbol->st_other = ELF::STV_DEFAULT;
724 if (const DefinedAtom *da = llvm::dyn_cast<const DefinedAtom>(a)){
725 symbol->st_size = da->size();
726 lld::DefinedAtom::ContentType ct;
727 switch (ct = da->contentType()){
728 case DefinedAtom::typeCode:
729 t = ELF::STT_FUNC;
730 break;
731 case DefinedAtom::typeData:
732 t = ELF::STT_OBJECT;
733 break;
734 case DefinedAtom::typeZeroFill:
735 // In relocatable files, st_value holds alignment constraints for a symbol whose
736 // section index is SHN_COMMON
737 if (this->_options.type() == ELF::ET_REL){
738 t = ELF::STT_COMMON;
739 symbol->st_value = 1 << (da->alignment()).powerOf2;
740 symbol->st_shndx = ELF::SHN_COMMON;
741 }
742 break;
743 case DefinedAtom::typeFirstInSection:
744 t = ELF::STT_SECTION;
745 break;
746 // TODO:: How to find STT_FILE symbols?
747 default:
748 t = ELF::STT_NOTYPE;
749 }
750
751 if (da->scope() == DefinedAtom::scopeTranslationUnit)
752 b = ELF::STB_LOCAL;
753 else if (da->merge() == DefinedAtom::mergeAsWeak)
754 b = ELF::STB_WEAK;
755 else
756 b = ELF::STB_GLOBAL;
Sid Manning2a590242012-10-18 17:16:19 +0000757 } else if (const AbsoluteAtom *aa = llvm::dyn_cast<const AbsoluteAtom>(a)){
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000758//FIXME: Absolute atoms need more properties to differentiate each other
759// based on binding and type of symbol
Sid Manning2a590242012-10-18 17:16:19 +0000760 t = ELF::STT_OBJECT;
761
762 switch (aa->scope()) {
763 case AbsoluteAtom::scopeLinkageUnit:
764 symbol->st_other = ELF::STV_HIDDEN;
765 b = ELF::STB_LOCAL;
766 break;
767 case AbsoluteAtom::scopeTranslationUnit:
768 b = ELF::STB_LOCAL;
769 break;
770 case AbsoluteAtom::scopeGlobal:
771 b = ELF::STB_GLOBAL;
772 break;
773 }
774 symbol->st_value = aa->value();
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000775 } else {
Sid Manning2a590242012-10-18 17:16:19 +0000776 symbol->st_value = 0;
777 t = ELF::STT_NOTYPE;
778 b = ELF::STB_LOCAL;
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000779 }
780 symbol->setBindingAndType(b, t);
781
782 _symbolTable.push_back(symbol);
783 this->_size += sizeof(Elf_Sym);
784}
785
786template<support::endianness target_endianness, bool is64Bits>
787void ELFSymbolTableChunk<target_endianness, is64Bits>::setAttributes() {
788// sh_info should be one greater than last symbol with STB_LOCAL binding
789// we sort the symbol table to keep all local symbols at the beginning
790 std::stable_sort(_symbolTable.begin(), _symbolTable.end(), ([]
791 (const Elf_Sym *A, const Elf_Sym *B) -> bool {
792 return (A->getBinding() < B->getBinding());}));
793 uint16_t shInfo = 0;
794 for (auto i : _symbolTable) {
795 if (i->getBinding() != ELF::STB_LOCAL)
796 break;
797 shInfo++;
798 }
799 this->_shinfo = shInfo;
800// we set the associated string table index in th sh_link member
801 this->_link = this->_writer.strtab()->ordinal() - 1;
802 this->_align2 = this->_options.pointerWidth();
803}
804
805template<support::endianness target_endianness, bool is64Bits>
806const char *ELFSymbolTableChunk<target_endianness, is64Bits>::info() {
807 return "Symbol Table";
808}
809
810template<support::endianness target_endianness, bool is64Bits>
811void ELFSymbolTableChunk<target_endianness, is64Bits>::
812 write(uint8_t *chunkBuffer) {
813 uint64_t chunkOffset = 0;
814 for (auto it : _symbolTable) {
815 ::memcpy(chunkBuffer + chunkOffset, it, this->_entsize);
816 chunkOffset += this->_entsize;
817 }
818}
819
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000820//===----------------------------------------------------------------------===//
821// ELFHeaderChunk
822//===----------------------------------------------------------------------===//
823template<support::endianness target_endianness, bool is64Bits>
824ELFHeaderChunk<target_endianness, is64Bits>
825 ::ELFHeaderChunk(const WriterOptionsELF &options,
Hemant Kulkarni87dbac02012-11-13 21:34:45 +0000826 const File &File)
827 : Chunk<target_endianness, is64Bits>(Chunk<target_endianness, is64Bits>
828 ::Kind::Header){
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000829 this->_size = size();
830 e_ident(ELF::EI_MAG0, 0x7f);
831 e_ident(ELF::EI_MAG1, 'E');
832 e_ident(ELF::EI_MAG2, 'L');
833 e_ident(ELF::EI_MAG3, 'F');
834 e_ident(ELF::EI_CLASS, (options.is64Bit() ? ELF::ELFCLASS64
835 : ELF::ELFCLASS32));
Sid Manninge3612f02012-10-05 14:06:24 +0000836 e_ident(ELF::EI_DATA, (options.endianness() == llvm::support::big)
837 ? ELF::ELFDATA2MSB
838 : ELF::ELFDATA2LSB);
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000839 e_ident(ELF::EI_VERSION, 1);
840 e_ident(ELF::EI_OSABI, ELF::ELFOSABI_NONE);
841
842 e_type(options.type());
843 e_machine(options.machine());
844 e_version(1);
845
846 e_entry(0ULL);
Hemant Kulkarni87dbac02012-11-13 21:34:45 +0000847 e_phoff(0);
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000848 e_shoff(0ULL);
849
850 e_flags(0);
851 e_ehsize(this->_size);
852 e_phentsize(0);
853 e_phnum(0);
854 e_shentsize(0);
855 e_shnum(0);
856 e_shstrndx(0);
Hemant Kulkarni87dbac02012-11-13 21:34:45 +0000857 this->setGroup(CG_HEADER);
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000858}
859
860template<support::endianness target_endianness, bool is64Bits>
861StringRef ELFHeaderChunk<target_endianness, is64Bits>
862 ::segmentName() const {
863 return "ELF";
864}
865
866template<support::endianness target_endianness, bool is64Bits>
867void ELFHeaderChunk<target_endianness, is64Bits>
868 ::write(uint8_t *chunkBuffer) {
869 ::memcpy(chunkBuffer, &_eh, size());
870}
871
872template<support::endianness target_endianness, bool is64Bits>
873const char *ELFHeaderChunk<target_endianness, is64Bits>::info() {
874 return "elf_header";
875}
876
877//===----------------------------------------------------------------------===//
878// ELFSectionHeaderChunk
879// List of Section Headers:
880//[Nr] Name Type Addr Off Size ES Flg Lk Inf Al
881//[ 0] NULL 00000000 000000 000000 00 0 0 0
882//[ 1] .text PROGBITS 00000000 000034 000040 00 AX 0 0 4
883//===----------------------------------------------------------------------===//
884template<support::endianness target_endianness, bool is64Bits>
885ELFSectionHeaderChunk<target_endianness, is64Bits>
886 ::ELFSectionHeaderChunk(const WriterOptionsELF& options,
887 ELFWriter<target_endianness,
888 is64Bits> &writer)
Hemant Kulkarni87dbac02012-11-13 21:34:45 +0000889 : Chunk<target_endianness, is64Bits>(Chunk<target_endianness, is64Bits>
890 ::Kind::Header)
891 , _options(options)
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000892 , _writer(writer) {
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000893 this->_size = 0;
894 this->_align2 = 0;
895 // The first element in the list is always NULL
896 Elf_Shdr *nullshdr = new (_sectionAllocate.Allocate<Elf_Shdr>()) Elf_Shdr;
897 ::memset(nullshdr, 0, sizeof (Elf_Shdr));
898 _sectionInfo.push_back(nullshdr);
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000899 this->_size += sizeof (Elf_Shdr);
Hemant Kulkarni87dbac02012-11-13 21:34:45 +0000900 this->setGroup(CG_FILE_END);
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000901 }
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000902
Hemant Kulkarni87dbac02012-11-13 21:34:45 +0000903
904template<support::endianness target_endianness, bool is64Bits>
905void ELFSectionHeaderChunk<target_endianness, is64Bits>::computeSize(){
906 this->_size = (this->_writer.sectionChunks().size() + 1) * sizeof(Elf_Shdr);
907}
908
909template<support::endianness target_endianness, bool is64Bits>
910void ELFSectionHeaderChunk<target_endianness, is64Bits>::fixOffsets(){
911 auto it = _sectionInfo.begin();
912 auto sections = _writer.sectionChunks();
913 // First section is a NULL section with no sh_offset fix
914 (*it)->sh_offset = 0;
915 (*it)->sh_addr = 0;
916 ++it;
917 for (auto &chunk : sections){
918 (*it)->sh_offset = chunk->fileOffset();
919 (*it)->sh_addr = chunk->address();
920 ++it;
921 }
922}
923
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000924template<support::endianness target_endianness, bool is64Bits>
925void ELFSectionHeaderChunk<target_endianness, is64Bits>::createHeaders(){
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000926 ELFStringSectionChunk<target_endianness, is64Bits> *str = _writer.shstrtab();
927
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000928 for (const auto &chunk : _writer.sectionChunks()) {
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000929 Elf_Shdr *shdr = new (_sectionAllocate.Allocate<Elf_Shdr>()) Elf_Shdr;
930 StringRef Name = chunk->sectionName();
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000931 if (chunk->shStrtableOffset() == 0){
932 chunk->setShStrtableOffset(str->addString(Name));
933 }
934 shdr->sh_name = chunk->shStrtableOffset();
935
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000936 shdr->sh_type = chunk->type();
937 shdr->sh_flags = chunk->flags();
938 // TODO: At the time of creation of this section header, we will not have
939 // any address and offset info. We revisit this after assigning the file
940 // offsets.
941 shdr->sh_offset = chunk->fileOffset();
942 shdr->sh_addr = chunk->address();
943 shdr->sh_size = chunk->size();
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000944 shdr->sh_link = chunk->link() ;
945 shdr->sh_info = chunk->shinfo();
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000946 shdr->sh_addralign = chunk->align2();
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000947 shdr->sh_entsize = chunk->entsize();
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000948
949 _sectionInfo.push_back(shdr);
950 this->_size += sizeof (Elf_Shdr);
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000951 _writer.symtab()->setAttributes();
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000952 }
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000953}
954
955template<support::endianness target_endianness, bool is64Bits>
956StringRef ELFSectionHeaderChunk<target_endianness, is64Bits>
957 ::segmentName() const {
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000958 return "PT_NULL";
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000959}
960
961template<support::endianness target_endianness, bool is64Bits>
962void ELFSectionHeaderChunk<target_endianness, is64Bits>
963 ::write(uint8_t *chunkBuffer) {
964 for (const auto si : _sectionInfo) {
965 ::memcpy(chunkBuffer, si, sizeof(*si));
966 chunkBuffer += sizeof (*si);
967 }
968}
969
970template<support::endianness target_endianness, bool is64Bits>
971uint16_t ELFSectionHeaderChunk<target_endianness, is64Bits>::count() {
972 return _sectionInfo.size();
973}
974template<support::endianness target_endianness, bool is64Bits>
975uint16_t ELFSectionHeaderChunk<target_endianness, is64Bits>::size() {
976 return sizeof (Elf_Shdr);
977}
978
979template<support::endianness target_endianness, bool is64Bits>
980const char *ELFSectionHeaderChunk<target_endianness, is64Bits>::info() {
981 return "elf_section_header";
982}
983
984//===----------------------------------------------------------------------===//
985// ELFProgramHeaderChunk
986//===----------------------------------------------------------------------===//
Hemant Kulkarni87dbac02012-11-13 21:34:45 +0000987template<support::endianness target_endianness, bool is64Bits>
988ELFProgramHeaderChunk<target_endianness, is64Bits>
989 ::ELFProgramHeaderChunk(const WriterOptionsELF &options,
990 ELFWriter<target_endianness, is64Bits>
991 &writer)
992 : Chunk<target_endianness, is64Bits>(Chunk<target_endianness, is64Bits>
993 ::Kind::Header)
994 , _options(options)
995 , _writer(writer) {
996 this->_align2 = 0;
997 this->setGroup(CG_HEADER);
998 _groupToPF[CG_RWX] = ELF::PF_R | ELF::PF_W | ELF::PF_X;
999 _groupToPF[CG_RW] = ELF::PF_R | ELF::PF_W;
1000 _groupToPF[CG_RX] = ELF::PF_R | ELF::PF_X;
1001 _groupToPF[CG_R] = ELF::PF_R;
1002 _groupToPF[CG_W] = ELF::PF_W;
1003 _groupToPF[CG_WX] = ELF::PF_W | ELF::PF_X;
1004 _groupToPF[CG_X] = ELF::PF_X;
1005 }
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001006
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001007template<support::endianness target_endianness, bool is64Bits>
1008void ELFProgramHeaderChunk<target_endianness, is64Bits>::createPHeaders() {
1009
1010 //TODO Once dynamic linking is supported, implement PHDR segment
1011 // Implement mechanism inside this class to correctly find
1012 // attributes for sections such as eh_frame, note etc
1013 // when they are supported.
1014 const uint16_t seg[] = { CG_RWX, CG_RX, CG_R, CG_RW, CG_WX, CG_W, CG_X };
1015 std::pair<secIterator, secIterator> sectionPair;
1016 auto sections = _writer.sectionChunks();
1017 _programHeaders.clear();
1018 this->_size = 0;
1019 for (auto group : seg) {
1020 uint64_t size = 0, mSize = 0;
1021 sectionPair = std::equal_range(sections.begin(), sections.end(),
1022 group, ChunkComparator<target_endianness,
1023 is64Bits>());
1024 if (sectionPair.first != sectionPair.second) {
1025 // FIXME: fix occupiesNoDiskSpace() function in Chunks class
1026 auto segBegin = sectionPair.first, segEnd = segBegin + 1;
1027 // Since this group has a section, atleast this is a part of segment
1028 size = (*segBegin)->occupiesNoDiskSpace() ? 0 : (*segBegin)->size();
1029 mSize = (*segBegin)->size();
1030
1031 for (; segEnd != sectionPair.second; segEnd++) {
1032 // This means there are more than 1 sections of same permissions
1033 if ((*segEnd)->fileOffset() - (*segBegin)->fileOffset() - size >
1034 _options.pageSize()) {
1035 // we have a case where padding zeros span more than a page
1036 // we can skip those pages.
1037 Elf_Phdr *phdr = new(_headerAllocate.Allocate<Elf_Phdr>()) Elf_Phdr;
1038 phdr->p_type = ELF::PT_LOAD;
1039 phdr->p_offset = (*segBegin)->fileOffset();
1040 phdr->p_vaddr = (*segBegin)->address();
1041 phdr->p_paddr = phdr->p_vaddr;
1042 phdr->p_filesz = size;
1043 // memory size may be more than file size if there are sections
1044 // that do not occupy space on disk such as .bss
1045 phdr->p_memsz = mSize;
1046 phdr->p_flags = _groupToPF[group];
1047 phdr->p_align = _options.pageSize();
1048 _programHeaders.push_back(phdr);
1049 this->_size += sizeof(Elf_Phdr);
1050 segBegin = segEnd;
1051 size = (*segBegin)->occupiesNoDiskSpace() ? 0 : (*segBegin)->size();
1052 mSize = (*segBegin)->size();
1053 } else {
1054 size = (*segEnd)->fileOffset() - (*segBegin)->fileOffset() +
1055 ((*segEnd)->occupiesNoDiskSpace() ? 0 : (*segEnd)->size()) ;
1056 mSize = (*segEnd)->fileOffset() - (*segBegin)->fileOffset() +
1057 (*segEnd)->size();
1058 }
1059 }
1060
1061 Elf_Phdr *phdr = new(_headerAllocate.Allocate<Elf_Phdr>()) Elf_Phdr;
1062 phdr->p_type = ELF::PT_LOAD;
1063 phdr->p_offset = (*segBegin)->fileOffset();
1064 phdr->p_vaddr = (*segBegin)->address();
1065 phdr->p_paddr = phdr->p_vaddr;
1066 phdr->p_filesz = size;
1067 phdr->p_memsz = mSize;
1068 phdr->p_flags = _groupToPF[group];
1069 phdr->p_align = _options.pageSize();
1070 _programHeaders.push_back(phdr);
1071 this->_size += sizeof(Elf_Phdr);
1072 }
1073 }
1074}
1075
1076template<support::endianness target_endianness, bool is64Bits>
1077uint64_t ELFProgramHeaderChunk<target_endianness, is64Bits>::computeNumber() {
1078 return _programHeaders.size();
1079}
1080template<support::endianness target_endianness, bool is64Bits>
1081const char *ELFProgramHeaderChunk<target_endianness, is64Bits>::info() {
1082 return "elf_program_header";
1083}
1084
1085template<support::endianness target_endianness, bool is64Bits>
1086void ELFProgramHeaderChunk<target_endianness, is64Bits>
1087 ::write(uint8_t *chunkBuffer) {
1088 for (const auto si : _programHeaders) {
1089 ::memcpy(chunkBuffer, si, sizeof(*si));
1090 chunkBuffer += sizeof (*si);
1091 }
1092}
1093template<support::endianness target_endianness, bool is64Bits>
1094StringRef ELFProgramHeaderChunk<target_endianness, is64Bits>
1095 ::segmentName() const {
1096 return "PT_NULL";
1097}
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001098//===----------------------------------------------------------------------===//
1099// ELFWriter Class
1100//===----------------------------------------------------------------------===//
1101template<support::endianness target_endianness, bool is64Bits>
1102class ELFWriter : public Writer {
1103public:
1104 LLVM_ELF_IMPORT_TYPES(target_endianness, is64Bits)
1105 typedef object::Elf_Shdr_Impl<target_endianness, is64Bits> Elf_Shdr;
Hemant Kulkarni08e410292012-10-01 23:53:20 +00001106 typedef object::Elf_Sym_Impl<target_endianness, is64Bits> Elf_Sym;
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001107 typedef object::Elf_Phdr<target_endianness, is64Bits> Elf_Phdr;
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001108 ELFWriter(const WriterOptionsELF &options);
1109 virtual error_code writeFile(const lld::File &File, StringRef path);
Sid Manningdd110202012-09-25 18:22:09 +00001110 uint64_t addressOfAtom(const Atom *atom);
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001111
1112 std::vector<Chunk<target_endianness, is64Bits>*> chunks() const {
1113 return _chunks; }
1114
Sid Manningdd110202012-09-25 18:22:09 +00001115 KindHandler *kindHandler() { return _referenceKindHandler.get(); }
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001116
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001117 std::vector<SectionChunk<target_endianness, is64Bits>*> sectionChunks() const {
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001118 return _sectionChunks ;
1119 }
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001120
1121 ELFStringSectionChunk<target_endianness, is64Bits> *shstrtab() const {
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001122 return _shstrtable;
1123 }
Hemant Kulkarni08e410292012-10-01 23:53:20 +00001124
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001125 ELFStringSectionChunk<target_endianness, is64Bits> *strtab() const {
Hemant Kulkarni08e410292012-10-01 23:53:20 +00001126 return _strtable;
1127 }
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001128 ELFSymbolTableChunk<target_endianness, is64Bits> *symtab() const {
Hemant Kulkarni08e410292012-10-01 23:53:20 +00001129 return _symtable;
1130 }
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001131
1132private:
1133 void build(const lld::File &file);
1134 void createChunks(const lld::File &file);
Sid Manningdd110202012-09-25 18:22:09 +00001135 void buildAtomToAddressMap();
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001136 void assignFileOffsets();
1137 const WriterOptionsELF &_options;
Sid Manningdd110202012-09-25 18:22:09 +00001138
1139/// \brief AtomToAddress: Is a mapping from an Atom to the address where
1140/// it will live in the output file.
1141 typedef llvm::DenseMap<const Atom*, uint64_t> AtomToAddress;
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001142 typedef typename std::vector<Chunk<target_endianness, is64Bits>*>
1143 ::iterator chunkIterator;
1144 ELFProgramHeaderChunk<target_endianness, is64Bits> *_phdr;
1145 ELFHeaderChunk<target_endianness, is64Bits> *ehc;
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001146 ELFStringSectionChunk<target_endianness, is64Bits> *_shstrtable ;
Hemant Kulkarni08e410292012-10-01 23:53:20 +00001147 ELFStringSectionChunk<target_endianness, is64Bits> *_strtable ;
1148 ELFSymbolTableChunk<target_endianness, is64Bits> *_symtable;
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001149 std::unique_ptr<KindHandler> _referenceKindHandler;
1150 ELFSectionHeaderChunk<target_endianness, is64Bits> *_sectionHeaderChunk;
Sid Manningdd110202012-09-25 18:22:09 +00001151 AtomToAddress _atomToAddress;
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001152 std::vector<Chunk<target_endianness, is64Bits>*> _chunks;
1153 const DefinedAtom *_entryAtom;
1154 std::vector<SectionChunk<target_endianness, is64Bits>*> _sectionChunks;
Hemant Kulkarni08e410292012-10-01 23:53:20 +00001155 std::vector<StockSectionChunk<target_endianness, is64Bits>*>
1156 _stockSectionChunks;
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001157 llvm::BumpPtrAllocator _chunkAllocate;
1158};
1159
1160//===----------------------------------------------------------------------===//
1161// ELFWriter
1162//===----------------------------------------------------------------------===//
1163template<support::endianness target_endianness, bool is64Bits>
1164ELFWriter<target_endianness, is64Bits>
1165 ::ELFWriter(const WriterOptionsELF &options)
1166 : _options(options)
Sid Manning42064e52012-10-09 02:20:47 +00001167 , _referenceKindHandler(KindHandler::makeHandler(_options.machine(),
1168 target_endianness))
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001169{}
1170
1171template<support::endianness target_endianness, bool is64Bits>
1172void ELFWriter<target_endianness, is64Bits>::build(const lld::File &file){
Hemant Kulkarni08e410292012-10-01 23:53:20 +00001173// Create objects for each chunk.
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001174 createChunks(file);
1175 assignFileOffsets();
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001176 _phdr->createPHeaders();
1177 _sectionHeaderChunk->createHeaders();
1178 // Creating program headers changed its size. so we need to re-assign offsets
1179 assignFileOffsets();
1180 _sectionHeaderChunk->fixOffsets();
1181 _phdr->createPHeaders();
Sid Manningdd110202012-09-25 18:22:09 +00001182 buildAtomToAddressMap();
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001183 _symtable->fixSymbolValue();
1184 ehc->e_shentsize(_sectionHeaderChunk->size());
1185 ehc->e_shnum(_sectionHeaderChunk->count());
1186 // We need to put the index of section string table in ELF header
1187 // first two chunks are not sections so we subtract 2 to start sections
1188 // and add 1 since we have a NULL header
1189 ehc->e_shstrndx(_shstrtable->ordinal() - 1);
1190 ehc->e_phnum(_phdr->computeNumber());
1191 ehc->e_phoff(_phdr->fileOffset());
1192 ehc->e_phentsize(sizeof(Elf_Phdr));
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001193}
1194
1195template<support::endianness target_endianness, bool is64Bits>
1196void ELFWriter<target_endianness, is64Bits>
1197 ::createChunks (const lld::File &file) {
Hemant Kulkarni08e410292012-10-01 23:53:20 +00001198 std::map<StringRef, StockSectionChunk<target_endianness, is64Bits>*>
1199 sectionMap;
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001200
Hemant Kulkarni08e410292012-10-01 23:53:20 +00001201// Make header chunk
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001202 ehc = new (_chunkAllocate.Allocate
Hemant Kulkarni08e410292012-10-01 23:53:20 +00001203 <ELFHeaderChunk<target_endianness, is64Bits>>())
1204 ELFHeaderChunk<target_endianness, is64Bits>(_options, file);
1205 _chunks.push_back(ehc);
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001206
1207 _phdr = new (_chunkAllocate.Allocate
1208 <ELFProgramHeaderChunk<target_endianness, is64Bits>>())
1209 ELFProgramHeaderChunk<target_endianness, is64Bits>(_options,
1210 *this);
1211 _chunks.push_back(_phdr);
Hemant Kulkarni08e410292012-10-01 23:53:20 +00001212
Hemant Kulkarni08e410292012-10-01 23:53:20 +00001213// We need to create hand crafted sections such as shstrtab strtab hash and
1214// symtab to put relevant information in ELF structures and then process the
1215// atoms.
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001216
1217 _shstrtable = new (_chunkAllocate.Allocate
1218 <ELFStringSectionChunk<target_endianness, is64Bits>>())
1219 ELFStringSectionChunk<target_endianness, is64Bits>
1220 (_options, *this, ".shstrtab");
Hemant Kulkarni08e410292012-10-01 23:53:20 +00001221 _shstrtable->setShStrtableOffset(_shstrtable->addString(".shstrtab"));
1222 _sectionChunks.push_back(_shstrtable);
1223
1224 _strtable = new (_chunkAllocate.Allocate
1225 <ELFStringSectionChunk<target_endianness, is64Bits>>())
1226 ELFStringSectionChunk<target_endianness, is64Bits>
1227 (_options, *this, ".strtab");
1228 _strtable->setShStrtableOffset( _shstrtable->addString(".strtab"));
1229 _sectionChunks.push_back(_strtable);
1230
1231 _symtable = new (_chunkAllocate.Allocate
1232 <ELFSymbolTableChunk<target_endianness, is64Bits>>())
1233 ELFSymbolTableChunk<target_endianness, is64Bits>
1234 (_options, *this, ".symtab");
1235 _symtable->setShStrtableOffset( _shstrtable->addString(".symtab"));
1236 _sectionChunks.push_back(_symtable);
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001237
Hemant Kulkarni08e410292012-10-01 23:53:20 +00001238//TODO: implement .hash section
1239
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001240 for (const DefinedAtom *a : file.defined() ) {
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001241 StringRef sectionName = a->customSectionName();
Hemant Kulkarni08e410292012-10-01 23:53:20 +00001242 if (a->sectionChoice() ==
1243 DefinedAtom::SectionChoice::sectionBasedOnContent) {
Hemant Kulkarni8bd27612012-10-03 23:27:33 +00001244 if (a->contentType() == DefinedAtom::typeZeroFill)
Hemant Kulkarni08e410292012-10-01 23:53:20 +00001245 sectionName = ".bss";
1246 }
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001247 auto pos = sectionMap.find(sectionName);
1248 DefinedAtom::ContentType type = a->contentType();
Hemant Kulkarni08e410292012-10-01 23:53:20 +00001249 if (type != DefinedAtom::typeUnknown){
1250 if (pos == sectionMap.end()) {
1251 StockSectionChunk<target_endianness, is64Bits>
1252 *chunk = new(_chunkAllocate.Allocate
1253 <StockSectionChunk<target_endianness, is64Bits>>
1254 ())StockSectionChunk<target_endianness, is64Bits>
1255 (sectionName, true, type, _options, *this);
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001256
Hemant Kulkarni08e410292012-10-01 23:53:20 +00001257 sectionMap[sectionName] = chunk;
1258 chunk->appendAtom(a);
1259 _sectionChunks.push_back(chunk);
1260 _stockSectionChunks.push_back(chunk);
1261
1262 } else {
1263 pos->second->appendAtom(a);
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001264 }
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001265 }
1266 }
1267
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001268 for (auto chnk : _sectionChunks)
1269 _chunks.push_back(chnk);
Hemant Kulkarni08e410292012-10-01 23:53:20 +00001270
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001271 _sectionHeaderChunk = new (_chunkAllocate.Allocate<ELFSectionHeaderChunk
1272 <target_endianness, is64Bits>>())
1273 ELFSectionHeaderChunk
1274 <target_endianness, is64Bits>(_options, *this);
1275 _chunks.push_back(_sectionHeaderChunk);
1276 // We sort the chunks based on the group they belong to
1277 std::stable_sort(_chunks.begin(), _chunks.end(),
1278 chunkGroupSort<target_endianness, is64Bits>);
1279
1280 // The CG_RW group also has to be arranged such that all
1281 // SHT_NOBITS type of sections (.*bss) are at end of this
1282 // "partition" of group.
1283 chunkIterator cI;
1284 std::pair<chunkIterator, chunkIterator> range;
1285 range = std::equal_range(_chunks.begin() + 2, _chunks.end() - 1, CG_RW,
1286 ChunkComparator<target_endianness, is64Bits>());
1287
1288 cI = std::stable_partition(range.first, range.second,
1289 IsBss<target_endianness, is64Bits>);
Hemant Kulkarni08e410292012-10-01 23:53:20 +00001290
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001291 // We reassign all the ordinals since its needed when making headers and
1292 // populating symbol table.
1293 uint64_t i = 0;
1294 for (auto chnk : _chunks) {
1295 chnk->setOrdinal(i++);
1296 }
Hemant Kulkarni08e410292012-10-01 23:53:20 +00001297
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001298 // We sort the sections as per new ordinal set after group sorting.
Hemant Kulkarni08e410292012-10-01 23:53:20 +00001299 std::stable_sort(_sectionChunks.begin(), _sectionChunks.end(),([]
1300 (const SectionChunk<target_endianness, is64Bits> *A,
1301 const SectionChunk<target_endianness, is64Bits> *B) -> bool {
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001302 return A->ordinal() < B->ordinal();}));
Hemant Kulkarni08e410292012-10-01 23:53:20 +00001303
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001304 // Populate symbol table with correct st_shndx member.
1305 if (_options.type() == ELF::ET_REL) {
1306 for (auto chnk : _sectionChunks ) {
1307 Elf_Sym *sym = new (_chunkAllocate.Allocate<Elf_Sym>()) Elf_Sym;
1308 sym->st_name = 0;
1309 sym->st_value = 0;
1310 sym->st_size = 0;
1311 sym->st_other = ELF::STV_DEFAULT;
1312 // first two chunks are not sections hence we subtract 2 but there is a
1313 // NULL section in section table so add 1
1314 sym->st_shndx = chnk->ordinal() - 1 ;
1315 sym->setBindingAndType(ELF::STB_LOCAL, ELF::STT_SECTION);
1316 _symtable->addSymbol(sym);
1317 }
1318 }
Hemant Kulkarni08e410292012-10-01 23:53:20 +00001319 for (const auto ssc : _stockSectionChunks){
1320 for (const auto da : ssc->atoms()) {
1321 _symtable->addSymbol(std::get<0>(da), ssc->ordinal() -1);
1322 }
1323 }
1324 for (const UndefinedAtom *a : file.undefined()) {
1325 _symtable->addSymbol(a, ELF::SHN_UNDEF);
1326 }
1327
1328 for (const AbsoluteAtom *a : file.absolute()) {
1329 _symtable->addSymbol(a, ELF::SHN_ABS);
1330 }
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001331}
1332
Sid Manningdd110202012-09-25 18:22:09 +00001333template<support::endianness target_endianness, bool is64Bits>
1334void ELFWriter<target_endianness, is64Bits>
1335 ::buildAtomToAddressMap () {
1336
1337// _atomToAddress is a DenseMap that maps an atom its file address.
1338// std::get<1>(ai) is the offset from the start of the section to the atom.
Hemant Kulkarni08e410292012-10-01 23:53:20 +00001339 for (auto chunk : _stockSectionChunks){
Sid Manningdd110202012-09-25 18:22:09 +00001340 for (auto &ai : chunk->atoms() ) {
1341 _atomToAddress[std::get<0>(ai)] = chunk->address() + std::get<1>(ai);
1342 }
1343 }
Sid Manningdd110202012-09-25 18:22:09 +00001344}
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001345
1346template<support::endianness target_endianness, bool is64Bits>
1347void ELFWriter<target_endianness, is64Bits>::assignFileOffsets() {
1348 DEBUG_WITH_TYPE("WriterELF-layout", dbgs()
1349 << "assign file offsets:\n");
1350 uint64_t offset = 0;
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001351 uint64_t address = _options.type() == ELF::ET_REL ? 0 :
1352 _options.baseAddress();
1353 uint16_t chunkGroup;
1354 auto chunkIt = _chunks.begin();
1355 // first (two in case of ET_EXEC or ET_DYN) chunks is (are) not section(s)
1356 (*chunkIt)->assignFileOffset(offset, address);
1357 chunkIt++;
1358 if (_options.type() == ELF::ET_EXEC ||
1359 _options.type() == ELF::ET_DYN) {
1360 (*chunkIt)->assignFileOffset(offset, address);
1361 chunkIt++;
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001362 }
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001363 while (chunkIt != (_chunks.end() - 1) ) {
1364 (*chunkIt)->assignFileOffset(offset, address);
1365 if (_options.type() == ELF::ET_EXEC ||
1366 _options.type() == ELF::ET_DYN) {
1367 chunkGroup = (*chunkIt)->group();
1368 chunkIt++;
1369 // If the chunk group changes we start on new page
1370 if (chunkGroup != (*chunkIt)->group() && (*chunkIt)->group() != CG_NO_LOAD
1371 && (*chunkIt)->group() != CG_FILE_END)
1372 address = address + _options.pageSize();
1373 } else {
1374 chunkIt++;
1375 }
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001376 }
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001377 (*chunkIt)->assignFileOffset(offset, address);
1378 ehc->e_shoff(_sectionHeaderChunk->fileOffset());
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001379}
1380
1381template<support::endianness target_endianness, bool is64Bits>
1382error_code ELFWriter<target_endianness, is64Bits>
1383 ::writeFile(const lld::File &file, StringRef path) {
1384 build(file);
1385
1386 uint64_t totalSize = _chunks.back()->fileOffset() + _chunks.back()->size();
1387
1388 OwningPtr<FileOutputBuffer> buffer;
1389 error_code ec = FileOutputBuffer::create(path,
1390 totalSize, buffer,
1391 FileOutputBuffer::F_executable);
1392 if (ec)
1393 return ec;
1394
1395 for (auto chunk : _chunks) {
1396 chunk->write(buffer->getBufferStart() + chunk->fileOffset());
1397 }
1398 return buffer->commit();
1399}
Nick Kledzikabb69812012-05-31 22:34:00 +00001400
Sid Manningdd110202012-09-25 18:22:09 +00001401template<support::endianness target_endianness, bool is64Bits>
1402uint64_t ELFWriter<target_endianness, is64Bits>
1403 ::addressOfAtom(const Atom *atom) {
1404 return _atomToAddress[atom];
1405}
Nick Kledzikabb69812012-05-31 22:34:00 +00001406} // namespace elf
1407
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001408Writer *createWriterELF(const WriterOptionsELF &options) {
1409 if (!options.is64Bit() && options.endianness() == llvm::support::little)
Hemant Kulkarni08e410292012-10-01 23:53:20 +00001410 return new lld::elf::ELFWriter<support::little, false>(options);
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001411 else if (options.is64Bit() && options.endianness() == llvm::support::little)
1412 return new lld::elf::ELFWriter<support::little, true>(options);
1413 else if (!options.is64Bit() && options.endianness() == llvm::support::big)
1414 return new lld::elf::ELFWriter<support::big, false>(options);
1415 else if (options.is64Bit() && options.endianness() == llvm::support::big)
1416 return new lld::elf::ELFWriter<support::big, true>(options);
Nick Kledzikabb69812012-05-31 22:34:00 +00001417
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001418 llvm_unreachable("Invalid Options!");
Nick Kledzikabb69812012-05-31 22:34:00 +00001419}
Nick Kledzikabb69812012-05-31 22:34:00 +00001420} // namespace lld