blob: 7907f3f7bc7899e54b08227128a17b3c2bfaa573 [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"
Hemant Kulkarni927bbc22012-09-14 16:11:34 +000018#include "llvm/ADT/ArrayRef.h"
19#include "llvm/ADT/DenseMap.h"
Shankar Easwaran495d38b2012-12-27 02:26:30 +000020#include "llvm/ADT/Hashing.h"
Hemant Kulkarni927bbc22012-09-14 16:11:34 +000021#include "llvm/ADT/OwningPtr.h"
22#include "llvm/ADT/SmallVector.h"
Shankar Easwaran495d38b2012-12-27 02:26:30 +000023#include "llvm/ADT/StringExtras.h"
Hemant Kulkarni927bbc22012-09-14 16:11:34 +000024#include "llvm/ADT/StringMap.h"
25#include "llvm/ADT/StringRef.h"
Shankar Easwaran495d38b2012-12-27 02:26:30 +000026#include "llvm/ADT/StringSwitch.h"
Hemant Kulkarni927bbc22012-09-14 16:11:34 +000027#include "llvm/Object/ELF.h"
Hemant Kulkarni927bbc22012-09-14 16:11:34 +000028#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"
Shankar Easwaran495d38b2012-12-27 02:26:30 +000037#include "AtomsELF.h"
Nick Kledzikabb69812012-05-31 22:34:00 +000038
Hemant Kulkarni927bbc22012-09-14 16:11:34 +000039#include <map>
Shankar Easwaran495d38b2012-12-27 02:26:30 +000040#include <unordered_map>
Hemant Kulkarni927bbc22012-09-14 16:11:34 +000041#include <tuple>
42#include <vector>
Nick Kledzikabb69812012-05-31 22:34:00 +000043
Hemant Kulkarni927bbc22012-09-14 16:11:34 +000044using namespace llvm;
45using namespace llvm::object;
Nick Kledzikabb69812012-05-31 22:34:00 +000046namespace lld {
47namespace elf {
Michael J. Spencera2c97272013-01-04 21:09:21 +000048template<support::endianness target_endianness,
49 std::size_t max_align,
50 bool is64Bits>
Shankar Easwaran495d38b2012-12-27 02:26:30 +000051class ELFExecutableWriter;
Hemant Kulkarni87dbac02012-11-13 21:34:45 +000052
Shankar Easwaran495d38b2012-12-27 02:26:30 +000053/// \brief The ELFWriter class is a base class for the linker to write
54/// various kinds of ELF files.
55class ELFWriter : public Writer {
Michael J. Spencera2c97272013-01-04 21:09:21 +000056public:
57 ELFWriter() { }
Shankar Easwaran495d38b2012-12-27 02:26:30 +000058
Michael J. Spencera2c97272013-01-04 21:09:21 +000059public:
60 /// \brief builds the chunks that needs to be written to the output
61 /// ELF file
62 virtual void buildChunks(const lld::File &file) = 0;
Shankar Easwaran495d38b2012-12-27 02:26:30 +000063
Michael J. Spencera2c97272013-01-04 21:09:21 +000064 /// \brief Writes the chunks into the output file specified by path
65 virtual error_code writeFile(const lld::File &File, StringRef path) = 0;
Shankar Easwaran495d38b2012-12-27 02:26:30 +000066
Michael J. Spencera2c97272013-01-04 21:09:21 +000067 /// \brief Writes the chunks into the output file specified by path
68 virtual uint64_t addressOfAtom(const Atom *atom) = 0;
Shankar Easwaran495d38b2012-12-27 02:26:30 +000069
Michael J. Spencera2c97272013-01-04 21:09:21 +000070 /// \brief Return the processing function to apply Relocations
71 virtual KindHandler *kindHandler() = 0;
Hemant Kulkarni87dbac02012-11-13 21:34:45 +000072};
73
Shankar Easwaran495d38b2012-12-27 02:26:30 +000074/// \brief A chunk is a contiguous region of space
Michael J. Spencera2c97272013-01-04 21:09:21 +000075template<support::endianness target_endianness,
76 std::size_t max_align,
77 bool is64Bits>
Hemant Kulkarni927bbc22012-09-14 16:11:34 +000078class Chunk {
79public:
Shankar Easwaran495d38b2012-12-27 02:26:30 +000080
81 /// \brief Describes the type of Chunk
82 enum Kind {
83 K_ELFHeader, // ELF Header
84 K_ELFProgramHeader, // Program Header
85 K_ELFSegment, // Segment
86 K_ELFSection, // Section
87 K_ELFSectionHeader // Section header
Hemant Kulkarni87dbac02012-11-13 21:34:45 +000088 };
Michael J. Spencera2c97272013-01-04 21:09:21 +000089 Chunk(StringRef name, Kind kind)
Shankar Easwaran495d38b2012-12-27 02:26:30 +000090 : _name(name)
91 , _kind(kind)
92 , _fsize(0)
93 , _msize(0)
94 , _align2(0)
95 , _order(0)
96 , _ordinal(1)
97 , _start(0)
98 , _fileoffset(0) {}
99 virtual ~Chunk() {}
Michael J. Spencera2c97272013-01-04 21:09:21 +0000100 // Does the chunk occupy disk space
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000101 virtual bool occupiesNoDiskSpace() const {
Michael J. Spencera2c97272013-01-04 21:09:21 +0000102 return false;
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000103 }
104 // The name of the chunk
105 StringRef name() const { return _name; }
106 // Kind of chunk
107 Kind kind() const { return _kind; }
108 uint64_t fileSize() const { return _fsize; }
109 uint64_t align2() const { return _align2; }
110 void appendAtom() const;
111
112 // The ordinal value of the chunk
113 uint64_t ordinal() const { return _ordinal;}
114 void setOrdinal(uint64_t newVal) { _ordinal = newVal;}
115 // The order in which the chunk would appear in the output file
116 uint64_t order() const { return _order; }
117 void setOrder(uint32_t order) { _order = order; }
118 // Output file offset of the chunk
119 uint64_t fileOffset() const { return _fileoffset; }
120 void setFileOffset(uint64_t offset) { _fileoffset = offset; }
121 // Output start address of the chunk
122 void setVAddr(uint64_t start) { _start = start; }
123 uint64_t virtualAddr() const { return _start; }
124 // Does the chunk occupy memory during execution ?
125 uint64_t memSize() const { return _msize; }
126 void setMemSize(uint64_t msize) { _msize = msize; }
Michael J. Spencera2c97272013-01-04 21:09:21 +0000127 // Writer the chunk
128 virtual void write(ELFWriter *writer,
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000129 OwningPtr<FileOutputBuffer> &buffer) = 0;
130 // Finalize the chunk before writing
131 virtual void finalize() = 0;
132
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000133protected:
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000134 StringRef _name;
135 Kind _kind;
136 uint64_t _fsize;
137 uint64_t _msize;
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000138 uint64_t _align2;
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000139 uint32_t _order;
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000140 uint64_t _ordinal;
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000141 uint64_t _start;
142 uint64_t _fileoffset;
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000143};
144
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000145/// \brief The ELFLayoutOptions encapsulates the options used by all Layouts
146/// Examples of the ELFLayoutOptions would be a script that would be used
Michael J. Spencera2c97272013-01-04 21:09:21 +0000147/// to drive the layout
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000148class ELFLayoutOptions {
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000149public:
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000150 ELFLayoutOptions() { }
Hemant Kulkarni927bbc22012-09-14 16:11:34 +0000151
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000152 ELFLayoutOptions(StringRef &linker_script) : _script(linker_script)
153 {}
Hemant Kulkarni87dbac02012-11-13 21:34:45 +0000154
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000155 /// parse the linker script
156 error_code parseLinkerScript();
Hemant Kulkarni736f7fb2012-11-21 21:07:36 +0000157
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000158 /// Is the current section present in the linker script
159 bool isSectionPresent();
160
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000161private:
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000162 StringRef _script;
Hemant Kulkarni08e410292012-10-01 23:53:20 +0000163};
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000164
Michael J. Spencera2c97272013-01-04 21:09:21 +0000165/// \brief The ELFLayout is an abstract class for managing the final layout for
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000166/// the kind of binaries(Shared Libraries / Relocatables / Executables 0
Michael J. Spencera2c97272013-01-04 21:09:21 +0000167/// Each architecture (Hexagon, PowerPC, MIPS) would have a concrete
168/// subclass derived from ELFLayout for generating each binary thats
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000169// needed by the lld linker
170class ELFLayout {
171public:
172 typedef uint32_t SectionOrder;
173 typedef uint32_t SegmentType;
174 typedef uint32_t Flags;
175
176public:
177 /// Return the order the section would appear in the output file
178 virtual SectionOrder getSectionOrder
179 (const StringRef name,
180 int32_t contentType,
181 int32_t contentPerm) = 0;
Michael J. Spencera2c97272013-01-04 21:09:21 +0000182 /// append the Atom to the layout and create appropriate sections
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000183 virtual error_code addAtom(const Atom *atom) = 0;
184 /// find the Atom Address in the current layout
185 virtual bool findAtomAddrByName(const StringRef name, uint64_t &addr) = 0;
186 /// associates a section to a segment
187 virtual void assignSectionsToSegments() = 0;
188 /// associates a virtual address to the segment, section, and the atom
189 virtual void assignVirtualAddress() = 0;
190 /// associates a file offset to the segment, section and the atom
191 virtual void assignFileOffsets() = 0;
192
193public:
194 ELFLayout() {}
Michael J. Spencera2c97272013-01-04 21:09:21 +0000195 ELFLayout(WriterOptionsELF &writerOptions,
196 ELFLayoutOptions &layoutOptions)
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000197 : _writerOptions(writerOptions)
198 , _layoutOptions(layoutOptions) {}
199 virtual ~ELFLayout() { }
200
201private:
202 WriterOptionsELF _writerOptions;
203 ELFLayoutOptions _layoutOptions;
204};
205
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000206/// \brief A section contains a set of atoms that have similiar properties
207/// The atoms that have similiar properties are merged to form a section
Michael J. Spencera2c97272013-01-04 21:09:21 +0000208template<support::endianness target_endianness,
209 std::size_t max_align,
210 bool is64Bits>
211class Section : public Chunk<target_endianness, max_align, is64Bits> {
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000212public:
Michael J. Spencera2c97272013-01-04 21:09:21 +0000213 // The Kind of section that the object represents
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000214 enum SectionKind {
215 K_Default,
216 K_SymbolTable,
217 K_StringTable,
218 };
219 // Create a section object, the section is set to the default type if the
220 // caller doesnot set it
Michael J. Spencera2c97272013-01-04 21:09:21 +0000221 Section(const StringRef sectionName,
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000222 const int32_t contentType,
223 const int32_t contentPermissions,
224 const int32_t order,
Michael J. Spencera2c97272013-01-04 21:09:21 +0000225 const SectionKind kind = K_Default)
226 : Chunk<target_endianness, max_align, is64Bits>(
227 sectionName, Chunk<target_endianness, max_align, is64Bits>::K_ELFSection)
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000228 , _contentType(contentType)
229 , _contentPermissions(contentPermissions)
230 , _sectionKind(kind)
231 , _entSize(0)
232 , _shInfo(0)
233 , _link(0) {
234 this->setOrder(order);
235 }
236
237 /// return the section kind
238 SectionKind sectionKind() const {
239 return _sectionKind;
240 }
241
242 /// Align the offset to the required modulus defined by the atom alignment
243 uint64_t alignOffset(uint64_t offset, DefinedAtom::Alignment &atomAlign) {
244 uint64_t requiredModulus = atomAlign.modulus;
245 uint64_t align2 = 1u << atomAlign.powerOf2;
246 uint64_t currentModulus = (offset % align2);
247 uint64_t retOffset = offset;
248 if (currentModulus != requiredModulus) {
249 if (requiredModulus > currentModulus)
250 retOffset += requiredModulus - currentModulus;
251 else
252 retOffset += align2 + requiredModulus - currentModulus;
253 }
254 return retOffset;
255 }
256
Michael J. Spencera2c97272013-01-04 21:09:21 +0000257 // \brief Append an atom to a Section. The atom gets pushed into a vector
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000258 // contains the atom, the atom file offset, the atom virtual address
259 // the atom file offset is aligned appropriately as set by the Reader
260 void appendAtom(const Atom *atom) {
261 Atom::Definition atomType = atom->definition();
262 const DefinedAtom *definedAtom = dyn_cast<DefinedAtom>(atom);
263 assert(atom != nullptr && "Expecting the atom to be a DefinedAtom");
264 DefinedAtom::Alignment atomAlign = definedAtom->alignment();
265 uint64_t align2 = 1u << atomAlign.powerOf2;
Michael J. Spencera2c97272013-01-04 21:09:21 +0000266 // Align the atom to the required modulus/ align the file offset and the
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000267 // memory offset seperately this is required so that BSS symbols are handled
268 // properly as the BSS symbols only occupy memory size and not file size
269 uint64_t fOffset = alignOffset(this->fileSize(), atomAlign);
270 uint64_t mOffset = alignOffset(this->memSize(), atomAlign);
271 switch (atomType) {
272 case Atom::definitionRegular:
273 switch(definedAtom->contentType()) {
274 case DefinedAtom::typeCode:
275 case DefinedAtom::typeData:
276 _atoms.push_back(std::make_pair(atom, std::make_pair(fOffset, 0)));
277 this->_fsize = fOffset + definedAtom->size();
278 this->_msize = mOffset + definedAtom->size();
279 break;
280 case DefinedAtom::typeZeroFill:
281 _atoms.push_back(std::make_pair(atom, std::make_pair(mOffset, 0)));
282 this->_msize = mOffset + definedAtom->size();
283 break;
284 default:
285 this->_fsize = fOffset + definedAtom->size();
286 this->_msize = mOffset + definedAtom->size();
287 break;
288 }
289 break;
290 default:
291 llvm_unreachable("Expecting only definedAtoms being passed here");
292 break;
Michael J. Spencera2c97272013-01-04 21:09:21 +0000293 }
294 // Set the section alignment to the largest alignment
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000295 // std::max doesnot support uint64_t
Michael J. Spencera2c97272013-01-04 21:09:21 +0000296 if (this->_align2 < align2)
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000297 this->_align2 = align2;
298 }
299
Michael J. Spencera2c97272013-01-04 21:09:21 +0000300 /// \brief Set the virtual address of each Atom in the Section. This
301 /// routine gets called after the linker fixes up the virtual address
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000302 /// of the section
303 void assignVirtualAddress(uint64_t &addr) {
304 for (auto &ai : _atoms) {
305 ai.second.second = addr + ai.second.first;
306 }
307 addr += this->memSize();
308 }
309
Michael J. Spencera2c97272013-01-04 21:09:21 +0000310 /// \brief Set the file offset of each Atom in the section. This routine
311 /// gets called after the linker fixes up the section offset
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000312 void assignOffsets(uint64_t offset) {
313 for (auto &ai : _atoms) {
314 ai.second.first = offset + ai.second.first;
315 }
316 }
317
Michael J. Spencera2c97272013-01-04 21:09:21 +0000318 /// \brief Find the Atom address given a name, this is needed to to properly
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000319 /// apply relocation. The section class calls this to find the atom address
320 /// to fix the relocation
321 bool findAtomAddrByName(const StringRef name, uint64_t &addr) {
322 for (auto ai : _atoms) {
323 if (ai.first->name() == name) {
324 addr = ai.second.second;
325 return true;
326 }
327 }
328 return false;
329 }
330
331 /// \brief Does the Atom occupy any disk space
332 bool occupiesNoDiskSpace() const {
333 return _contentType == DefinedAtom::typeZeroFill;
334 }
335
Michael J. Spencera2c97272013-01-04 21:09:21 +0000336 /// \brief The permission of the section is the most permissive permission
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000337 /// of all atoms that the section contains
338 void setContentPermissions(int32_t perm) {
339 _contentPermissions = std::max(perm, _contentPermissions);
340 }
341
342 /// \brief Get the section flags, defined by the permissions of the section
343 int64_t flags() {
344 switch (_contentPermissions) {
345 case DefinedAtom::perm___:
346 return 0;
347
348 case DefinedAtom::permR__:
349 return llvm::ELF::SHF_ALLOC;
Michael J. Spencera2c97272013-01-04 21:09:21 +0000350
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000351 case DefinedAtom::permR_X:
352 return llvm::ELF::SHF_ALLOC | llvm::ELF::SHF_EXECINSTR;
Michael J. Spencera2c97272013-01-04 21:09:21 +0000353
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000354 case DefinedAtom::permRW_:
355 case DefinedAtom::permRW_L:
356 return llvm::ELF::SHF_ALLOC | llvm::ELF::SHF_WRITE;
Michael J. Spencera2c97272013-01-04 21:09:21 +0000357
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000358 case DefinedAtom::permRWX:
Michael J. Spencera2c97272013-01-04 21:09:21 +0000359 return llvm::ELF::SHF_ALLOC |
360 llvm::ELF::SHF_WRITE |
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000361 llvm::ELF::SHF_EXECINSTR;
362
363 default:
364 break;
365 }
366 return llvm::ELF::SHF_ALLOC;
367 }
368
369 /// \brief Return the raw flags, we need this to sort segments
370 int64_t atomflags() const {
371 return _contentPermissions;
372 }
373
Michael J. Spencera2c97272013-01-04 21:09:21 +0000374 /// \brief Return the section type, the returned value is recorded in the
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000375 /// sh_type field of the Section Header
376 int type() {
377 switch (_contentType) {
378 case DefinedAtom::typeCode:
379 case DefinedAtom::typeData:
380 case DefinedAtom::typeConstant:
381 return llvm::ELF::SHT_PROGBITS;
382
383 case DefinedAtom::typeZeroFill:
384 return llvm::ELF::SHT_NOBITS;
385
386 // Case to handle section types
387 // Symtab, String Table ...
388 default:
389 return _contentType;
390 }
391 }
392
Michael J. Spencera2c97272013-01-04 21:09:21 +0000393 /// \brief Returns the section link field, the returned value is
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000394 /// recorded in the sh_link field of the Section Header
395 int link() const {
396 return _link;
397 }
398
399 void setLink(int32_t link) {
400 _link = link;
401 }
402
Michael J. Spencera2c97272013-01-04 21:09:21 +0000403 /// \brief Returns the section entsize field, the returned value is
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000404 /// recorded in the sh_entsize field of the Section Header
405 int entsize() const {
406 return _entSize;
407 }
408
Michael J. Spencera2c97272013-01-04 21:09:21 +0000409 /// \brief Returns the shinfo field, the returned value is
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000410 /// recorded in the sh_info field of the Section Header
Michael J. Spencera2c97272013-01-04 21:09:21 +0000411 int shinfo() const {
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000412 return _shInfo;
413 }
414
415 /// \brief Records the segmentType, that this section belongs to
416 void setSegment(const ELFLayout::SegmentType segmentType) {
417 _segmentType = segmentType;
418 }
419
420 /// \brief convert the segment type to a String for diagnostics
421 /// and printing purposes
422 StringRef segmentKindToStr() const {
423 switch(_segmentType) {
424 case llvm::ELF::PT_INTERP:
425 return "INTERP";
426 case llvm::ELF::PT_LOAD:
427 return "LOAD";
428 case llvm::ELF::PT_GNU_EH_FRAME:
429 return "EH_FRAME";
430 case llvm::ELF::PT_NOTE:
431 return "NOTE";
432 case llvm::ELF::PT_DYNAMIC:
433 return "DYNAMIC";
434 case llvm::ELF::PT_GNU_RELRO:
435 return "RELRO";
436 case llvm::ELF::PT_NULL:
437 return "NULL";
438 default:
439 return "UNKNOWN";
440 }
441 }
442
443 /// \brief for LLVM style RTTI information
Michael J. Spencera2c97272013-01-04 21:09:21 +0000444 static inline bool classof(
445 const Chunk<target_endianness, max_align, is64Bits> *c) {
446 return c->kind() ==
447 Chunk<target_endianness, max_align, is64Bits>::K_ELFSection;
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000448 }
449
450 /// \brief Finalize the section contents before writing
451 void finalize() { }
452
Michael J. Spencera2c97272013-01-04 21:09:21 +0000453 /// \brief Write the section and the atom contents to the buffer
454 void write(ELFWriter *writer,
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000455 OwningPtr<FileOutputBuffer> &buffer) {
456 uint8_t *chunkBuffer = buffer->getBufferStart();
457 for (auto &ai : _atoms) {
458 const DefinedAtom *definedAtom = llvm::dyn_cast<DefinedAtom>(ai.first);
459 // Copy raw content of atom to file buffer.
460 ArrayRef<uint8_t> content = definedAtom->rawContent();
461 uint64_t contentSize = content.size();
462 if (contentSize == 0)
463 continue;
464 uint8_t *atomContent = chunkBuffer + ai.second.first;
465 std::copy_n(content.data(), contentSize, atomContent);
466 for (auto ref = definedAtom->begin(); ref != definedAtom->end(); ++ref) {
467 uint32_t offset = ref->offsetInAtom();
468 uint64_t targetAddress = 0;
469 if (ref->target() != nullptr)
470 targetAddress = writer->addressOfAtom(ref->target());
471 else
472 assert(0 && "Found the target to be NULL");
473 uint64_t fixupAddress = writer->addressOfAtom(ai.first) + offset;
474 // apply the relocation
Michael J. Spencera2c97272013-01-04 21:09:21 +0000475 writer->kindHandler()->applyFixup(ref->kind(),
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000476 ref->addend(),
477 &atomContent[offset],
478 fixupAddress,
479 targetAddress);
480 }
481 }
482 }
483
484 /// Atom Iterators
Michael J. Spencera2c97272013-01-04 21:09:21 +0000485 typedef typename std::vector<std::pair<const Atom *,
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000486 std::pair<uint64_t, uint64_t>>>::iterator atom_iter;
487
488 atom_iter atoms_begin() { return _atoms.begin(); }
489
490 atom_iter atoms_end() { return _atoms.end(); }
491
492protected:
493 int32_t _contentType;
494 int32_t _contentPermissions;
495 SectionKind _sectionKind;
496 // An Atom is appended to the vector with the following fields
497 // field1 : Atom
498 // field2 : fileoffset (initially set with a base offset of 0)
499 // field3 : virtual address
500 std::vector<std::pair<const Atom *, std::pair<uint64_t, uint64_t>>> _atoms;
501 ELFLayout::SegmentType _segmentType;
502 int64_t _entSize;
503 int64_t _shInfo;
504 int64_t _link;
Michael J. Spencera2c97272013-01-04 21:09:21 +0000505};
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000506
Michael J. Spencera2c97272013-01-04 21:09:21 +0000507/// \brief A MergedSections represents a set of sections grouped by the same
508/// name. The output file that gets written by the linker has sections grouped
509/// by similiar names
510template<support::endianness target_endianness,
511 std::size_t max_align,
512 bool is64Bits>
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000513class MergedSections {
514public:
Michael J. Spencera2c97272013-01-04 21:09:21 +0000515 MergedSections(StringRef name)
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000516 : _name(name)
517 ,_hasSegment(false)
518 ,_ordinal(0)
519 ,_flags(0)
520 ,_size(0)
521 ,_memSize(0)
522 ,_fileOffset(0)
523 ,_virtualAddr(0)
524 ,_shInfo(0)
525 ,_entSize(0)
526 ,_link(0)
527 ,_align2(0)
528 ,_kind(0)
529 ,_type(0) { }
Michael J. Spencera2c97272013-01-04 21:09:21 +0000530
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000531 // Set the MergedSections is associated with a segment
532 void setHasSegment() { _hasSegment = true; }
533
Michael J. Spencera2c97272013-01-04 21:09:21 +0000534 /// Sets the ordinal
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000535 void setOrdinal(uint64_t ordinal) {
536 _ordinal = ordinal;
537 }
538
Michael J. Spencera2c97272013-01-04 21:09:21 +0000539 /// Sets the Memory size
540 void setMemSize(uint64_t memsz) {
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000541 _memSize = memsz;
542 }
543
544 /// Sets the size fo the merged Section
545 void setSize(uint64_t fsiz) {
546 _size = fsiz;
547 }
548
Michael J. Spencera2c97272013-01-04 21:09:21 +0000549 // The offset of the first section contained in the merged section is
550 // contained here
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000551 void setFileOffset(uint64_t foffset) {
552 _fileOffset = foffset;
553 }
554
555 // Sets the starting address of the section
556 void setAddr(uint64_t addr) {
557 _virtualAddr = addr;
558 }
559
560 // Appends a section into the list of sections that are part of this Merged
561 // Section
Michael J. Spencera2c97272013-01-04 21:09:21 +0000562 void appendSection(Chunk<target_endianness, max_align, is64Bits> *c) {
563 if (c->align2() > _align2)
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000564 _align2 = c->align2();
Michael J. Spencera2c97272013-01-04 21:09:21 +0000565 if (c->kind() ==
566 Chunk<target_endianness, max_align, is64Bits>::K_ELFSection) {
567 Section<target_endianness, max_align, is64Bits> *section;
568 section =
569 llvm::dyn_cast<Section<target_endianness, max_align, is64Bits>>(c);
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000570 _link = section->link();
571 _shInfo = section->shinfo();
572 _entSize = section->entsize();
573 _type = section->type();
574 if (_flags < section->flags())
575 _flags = section->flags();
576 }
577 _kind = c->kind();
578 _sections.push_back(c);
579 }
580
581 // Iterators
Michael J. Spencera2c97272013-01-04 21:09:21 +0000582 typedef typename std::vector<
583 Chunk<target_endianness, max_align, is64Bits> *>::iterator ChunkIter;
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000584
585 ChunkIter begin_sections() { return _sections.begin(); }
586
587 ChunkIter end_sections() { return _sections.end(); }
588
589 // The below functions returns the properties of the MergeSection
590 bool hasSegment() const { return _hasSegment; }
591
592 StringRef name() const { return _name; }
593
594 int64_t shinfo() const { return _shInfo; }
595
596 uint64_t align2() const { return _align2; }
597
598 int64_t link() const { return _link; }
599
600 int64_t type() const { return _type; }
601
602 uint64_t virtualAddr() const { return _virtualAddr; }
603
604 int64_t ordinal() const { return _ordinal; }
605
606 int64_t kind() const { return _kind; }
607
608 uint64_t fileSize() const { return _size; }
609
610 int64_t entsize() const { return _entSize; }
611
612 uint64_t fileOffset() const { return _fileOffset; }
613
614 int64_t flags() const { return _flags; }
615
616 uint64_t memSize() { return _memSize; }
617
618private:
619 StringRef _name;
620 bool _hasSegment;
621 uint64_t _ordinal;
622 int64_t _flags;
623 uint64_t _size;
624 uint64_t _memSize;
625 uint64_t _fileOffset;
626 uint64_t _virtualAddr;
627 int64_t _shInfo;
628 int64_t _entSize;
629 int64_t _link;
630 uint64_t _align2;
631 int64_t _kind;
632 int64_t _type;
Michael J. Spencera2c97272013-01-04 21:09:21 +0000633 std::vector<Chunk<target_endianness, max_align, is64Bits> *> _sections;
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000634};
635
Michael J. Spencera2c97272013-01-04 21:09:21 +0000636/// \brief A segment can be divided into segment slices
637/// depending on how the segments can be split
638template<support::endianness target_endianness,
639 std::size_t max_align,
640 bool is64Bits>
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000641class SegmentSlice {
642public:
Michael J. Spencera2c97272013-01-04 21:09:21 +0000643 typedef typename std::vector<
644 Section<target_endianness, max_align, is64Bits> *>::iterator sectionIter;
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000645
646 SegmentSlice() { }
647
648 /// Set the segment slice so that it begins at the offset specified
Michael J. Spencera2c97272013-01-04 21:09:21 +0000649 /// by fileoffset and set the start of the slice to be s and the end
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000650 /// of the slice to be e
651 void set(uint64_t fileoffset, int32_t s, int e) {
652 _startSection = s;
653 _endSection = e+1;
654 _offset = fileoffset;
655 }
656
657 // Set the segment slice start and end iterators. This is used to walk through
658 // the sections that are part of the Segment slice
659 void setSections(sectionIter start, sectionIter end) {
660 _startSectionIter = start;
661 _endSectionIter = end;
662 }
663
664 // Return the fileOffset of the slice
665 uint64_t fileOffset() const { return _offset; }
666
667 // Return the size of the slice
668 uint64_t fileSize() const { return _size; }
669
670 // Return the start of the slice
671 int32_t startSection() const { return _startSection; }
672
673 // Return the start address of the slice
674 uint64_t virtualAddr() const { return _addr; }
675
676 // Return the memory size of the slice
677 uint64_t memSize() const { return _memSize; }
678
679 // Return the alignment of the slice
680 uint64_t align2() const { return _align2; }
681
682 void setSize(uint64_t sz) { _size = sz; }
683
684 void setMemSize(uint64_t memsz) { _memSize = memsz; }
685
686 void setVAddr(uint64_t addr) { _addr = addr; }
687
688 void setAlign(uint64_t align) { _align2 = align; }
689
Michael J. Spencera2c97272013-01-04 21:09:21 +0000690 static bool compare_slices(
691 SegmentSlice<target_endianness, max_align, is64Bits> *a,
692 SegmentSlice<target_endianness, max_align, is64Bits> *b) {
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000693 return (a->startSection() < b->startSection());
694 }
695
696 // Functions to run through the slice
697 sectionIter sections_begin() { return _startSectionIter; }
698
699 sectionIter sections_end() { return _endSectionIter; }
700
701private:
702 int32_t _startSection;
703 int32_t _endSection;
704 sectionIter _startSectionIter;
705 sectionIter _endSectionIter;
706 uint64_t _addr;
707 uint64_t _offset;
708 uint64_t _size;
709 uint64_t _align2;
710 uint64_t _memSize;
711};
712
713/// \brief A segment contains a set of sections, that have similiar properties
714// the sections are already seperated based on different flags and properties
715// the segment is just a way to concatenate sections to segments
Michael J. Spencera2c97272013-01-04 21:09:21 +0000716template<support::endianness target_endianness,
717 std::size_t max_align,
718 bool is64Bits>
719class Segment : public Chunk<target_endianness, max_align, is64Bits> {
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000720public:
Michael J. Spencera2c97272013-01-04 21:09:21 +0000721 typedef typename std::vector<SegmentSlice<
722 target_endianness, max_align, is64Bits> *>::iterator slice_iter;
723 typedef typename std::vector<
724 Section<target_endianness, max_align, is64Bits> *>::iterator SectionIter;
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000725
726 Segment(const StringRef name,
727 const ELFLayout::SegmentType type,
728 const WriterOptionsELF &options)
Michael J. Spencera2c97272013-01-04 21:09:21 +0000729 : Chunk<target_endianness, max_align, is64Bits>(name,
730 Chunk<target_endianness, max_align, is64Bits>::K_ELFSegment)
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000731 , _segmentType(type)
732 , _flags(0)
733 , _atomflags(0)
734 , _options(options) {
735 this->_align2 = 0;
736 this->_fsize = 0;
737 }
738
739 /// append a section to a segment
Michael J. Spencera2c97272013-01-04 21:09:21 +0000740 void append(Section<target_endianness, max_align, is64Bits> *section) {
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000741 _sections.push_back(section);
742 if (_flags < section->flags())
743 _flags = section->flags();
744 if (_atomflags < section->atomflags())
745 _atomflags = section->atomflags();
746 if (this->_align2 < section->align2())
747 this->_align2 = section->align2();
748 }
749
750 /// Sort segments depending on the property
751 /// If we have a Program Header segment, it should appear first
752 /// If we have a INTERP segment, that should appear after the Program Header
753 /// All Loadable segments appear next in this order
754 /// All Read Write Execute segments follow
755 /// All Read Execute segments appear next
756 /// All Read only segments appear first
Michael J. Spencera2c97272013-01-04 21:09:21 +0000757 /// All Write execute segments follow
758 static bool compareSegments(
759 Segment<target_endianness, max_align, is64Bits> *sega,
760 Segment<target_endianness, max_align, is64Bits> *segb) {
761 if (sega->atomflags() < segb->atomflags())
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000762 return false;
763 return true;
764 }
765
766 /// \brief Start assigning file offset to the segment chunks The fileoffset
767 /// needs to be page at the start of the segment and in addition the
768 /// fileoffset needs to be aligned to the max section alignment within the
769 /// segment. This is required so that the ELF property p_poffset % p_align =
770 /// p_vaddr mod p_align holds true.
771 /// The algorithm starts off by assigning the startOffset thats passed in as
772 /// parameter to the first section in the segment, if the difference between
773 /// the newly computed offset is greater than a page, then we create a segment
Michael J. Spencera2c97272013-01-04 21:09:21 +0000774 /// slice, as it would be a waste of virtual memory just to be filled with
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000775 /// zeroes
776 void assignOffsets(uint64_t startOffset) {
777 int startSection = 0;
778 int currSection = 0;
779 SectionIter startSectionIter, endSectionIter;
Michael J. Spencera2c97272013-01-04 21:09:21 +0000780 // slice align is set to the max alignment of the chunks that are
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000781 // contained in the slice
782 uint64_t sliceAlign = 0;
783 // Current slice size
784 uint64_t curSliceSize = 0;
785 // Current Slice File Offset
786 uint64_t curSliceFileOffset = 0;
787
788 startSectionIter = _sections.begin();
789 endSectionIter = _sections.end();
790 startSection = 0;
791 bool isFirstSection = true;
792 for (auto si = _sections.begin(); si != _sections.end(); ++si) {
793 if (isFirstSection) {
794 // align the startOffset to the section alignment
Michael J. Spencera2c97272013-01-04 21:09:21 +0000795 uint64_t newOffset =
796 llvm::RoundUpToAlignment(startOffset, (*si)->align2());
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000797 curSliceFileOffset = newOffset;
798 sliceAlign = (*si)->align2();
799 this->setFileOffset(startOffset);
800 (*si)->setFileOffset(newOffset);
801 curSliceSize = (*si)->fileSize();
802 isFirstSection = false;
803 } else {
804 uint64_t curOffset = curSliceFileOffset + curSliceSize;
Michael J. Spencera2c97272013-01-04 21:09:21 +0000805 uint64_t newOffset =
806 llvm::RoundUpToAlignment(curOffset, (*si)->align2());
807 SegmentSlice<target_endianness, max_align, is64Bits> *slice = nullptr;
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000808 // If the newOffset computed is more than a page away, lets create
809 // a seperate segment, so that memory is not used up while running
810 if ((newOffset - curOffset) > _options.pageSize()) {
811 // TODO: use std::find here
812 for (auto sei = slices_begin(); sei != slices_end(); ++sei) {
813 if ((*sei)->startSection() == startSection) {
814 slice = *sei;
815 break;
816 }
817 }
818 if (!slice) {
Michael J. Spencera2c97272013-01-04 21:09:21 +0000819 slice = new (_segmentAllocate.Allocate<
820 SegmentSlice<target_endianness, max_align, is64Bits>>())
821 SegmentSlice<target_endianness, max_align, is64Bits>();
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000822 _segmentSlices.push_back(slice);
823 }
824 slice->set(curSliceFileOffset, startSection, currSection);
825 slice->setSections(startSectionIter, endSectionIter);
826 slice->setSize(curSliceSize);
827 slice->setAlign(sliceAlign);
Michael J. Spencera2c97272013-01-04 21:09:21 +0000828 uint64_t newPageOffset =
829 llvm::RoundUpToAlignment(curOffset, _options.pageSize());
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000830 newOffset = llvm::RoundUpToAlignment(newPageOffset, (*si)->align2());
831 curSliceFileOffset = newOffset;
832 startSectionIter = endSectionIter;
833 startSection = currSection;
834 (*si)->setFileOffset(curSliceFileOffset);
835 curSliceSize = newOffset - curSliceFileOffset + (*si)->fileSize();
836 sliceAlign = (*si)->align2();
837 }
838 else {
839 if (sliceAlign < (*si)->align2())
840 sliceAlign = (*si)->align2();
841 (*si)->setFileOffset(newOffset);
842 curSliceSize = newOffset - curSliceFileOffset + (*si)->fileSize();
843 }
844 }
845 currSection++;
846 endSectionIter = si;
847 }
Michael J. Spencera2c97272013-01-04 21:09:21 +0000848 SegmentSlice<target_endianness, max_align, is64Bits> *slice = nullptr;
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000849 for (auto sei = slices_begin(); sei != slices_end(); ++sei) {
850 // TODO: add std::find
851 if ((*sei)->startSection() == startSection) {
852 slice = *sei;
853 break;
854 }
855 }
856 if (!slice) {
857 slice = new (_segmentAllocate.Allocate
Michael J. Spencera2c97272013-01-04 21:09:21 +0000858 <SegmentSlice<target_endianness, max_align, is64Bits>>())
859 SegmentSlice<target_endianness, max_align, is64Bits>();
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000860 _segmentSlices.push_back(slice);
861 }
862 slice->set(curSliceFileOffset, startSection, currSection);
863 slice->setSections(startSectionIter, _sections.end());
864 slice->setSize(curSliceSize);
865 slice->setAlign(sliceAlign);
866 this->_fsize = curSliceFileOffset - startOffset + curSliceSize;
Michael J. Spencera2c97272013-01-04 21:09:21 +0000867 std::stable_sort(slices_begin(), slices_end(),
868 SegmentSlice<target_endianness, max_align, is64Bits>::compare_slices);
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000869 }
870
871 /// \brief Assign virtual addresses to the slices
872 void assignVirtualAddress(uint64_t &addr, bool isFirstSegment) {
873 for (auto sei = slices_begin(), see = slices_end(); sei != see; ++sei) {
874 bool firstSlice = (sei == slices_begin());
Michael J. Spencera2c97272013-01-04 21:09:21 +0000875 // The first segment has distinct since it contains the
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000876 // ELF header and the Program Header, if we get to the first segment
877 // and the first slice, set it to the baseaddress
878 // which is the segment address
879 if (isFirstSegment && firstSlice)
880 (*sei)->setVAddr(this->virtualAddr());
881 else {
882 // Align to a page
883 addr = llvm::RoundUpToAlignment(addr, _options.pageSize());
884 // Align to the slice alignment
885 addr = llvm::RoundUpToAlignment(addr, (*sei)->align2());
886 }
887 bool virtualAddressSet = false;
Michael J. Spencera2c97272013-01-04 21:09:21 +0000888 for (auto si = (*sei)->sections_begin(), se = (*sei)->sections_end();
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000889 si != se; ++si) {
890 // Align the section address
891 addr = llvm::RoundUpToAlignment(addr, (*si)->align2());
892 if (!isFirstSegment && !virtualAddressSet) {
893 (*sei)->setVAddr(addr);
894 virtualAddressSet = true;
895 }
896 (*si)->setVAddr(addr);
897 (*si)->assignVirtualAddress(addr);
898 (*si)->setMemSize(addr - (*si)->virtualAddr());
899 }
900 (*sei)->setMemSize(addr - (*sei)->virtualAddr());
901 }
902 }
903
904 slice_iter slices_begin() {
905 return _segmentSlices.begin();
906 }
907
908 slice_iter slices_end() {
909 return _segmentSlices.end();
910 }
911
Michael J. Spencera2c97272013-01-04 21:09:21 +0000912 // Write the Segment
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000913 void write(ELFWriter *writer, OwningPtr<FileOutputBuffer> &buffer) {
914 for (auto sei = slices_begin(), see = slices_end(); sei != see; ++sei) {
Michael J. Spencera2c97272013-01-04 21:09:21 +0000915 for (auto si = (*sei)->sections_begin(), se = (*sei)->sections_end();
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000916 si != se; ++si) {
917 (*si)->write(writer, buffer);
918 }
919 }
920 }
921
922 // Finalize the segment, before we want to write to the output file
923 void finalize() { }
924
Michael J. Spencera2c97272013-01-04 21:09:21 +0000925 // For LLVM RTTI
926 static inline bool classof(
927 const Chunk<target_endianness, max_align, is64Bits> *c) {
928 return c->kind() ==
929 Chunk<target_endianness, max_align, is64Bits>::K_ELFSegment;
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000930 }
931
932 // Getters
933 int32_t sectionCount() const {
934 return _sections.size();
935 }
936
937 ELFLayout::SegmentType segmentType() { return _segmentType; }
938
939 int pageSize() const { return _options.pageSize(); }
940
941 int64_t atomflags() const { return _atomflags; }
942
943 int64_t flags() const {
944 int64_t fl = 0;
945 if (_flags & llvm::ELF::SHF_ALLOC)
946 fl |= llvm::ELF::PF_R;
947 if (_flags & llvm::ELF::SHF_WRITE)
948 fl |= llvm::ELF::PF_W;
949 if (_flags & llvm::ELF::SHF_EXECINSTR)
950 fl |= llvm::ELF::PF_X;
951 return fl;
952 }
953
954 int64_t numSlices() const {
955 return _segmentSlices.size();
956 }
957
958private:
Michael J. Spencera2c97272013-01-04 21:09:21 +0000959 std::vector<Section<target_endianness, max_align, is64Bits> *> _sections;
960 std::vector<SegmentSlice<target_endianness, max_align, is64Bits> *>
961 _segmentSlices;
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000962 ELFLayout::SegmentType _segmentType;
963 int64_t _flags;
964 int64_t _atomflags;
965 const WriterOptionsELF _options;
966 llvm::BumpPtrAllocator _segmentAllocate;
967};
968
969/// \brief The class represents the ELF String Table
Michael J. Spencera2c97272013-01-04 21:09:21 +0000970template<support::endianness target_endianness,
971 std::size_t max_align,
972 bool is64Bits>
973class ELFStringTable : public Section<target_endianness, max_align, is64Bits> {
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000974public:
Michael J. Spencera2c97272013-01-04 21:09:21 +0000975 ELFStringTable(const char *str, int32_t order)
976 : Section<target_endianness, max_align, is64Bits>(
977 str,
978 llvm::ELF::SHT_STRTAB,
979 DefinedAtom::perm___,
980 order,
981 Section<target_endianness, max_align, is64Bits>::K_StringTable) {
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000982 // the string table has a NULL entry for which
983 // add an empty string
984 _strings.push_back("");
985 this->_fsize = 1;
986 this->_align2 = 1;
987 this->setOrder(order);
988 }
989
Michael J. Spencera2c97272013-01-04 21:09:21 +0000990 static inline bool classof(
991 const Chunk<target_endianness, max_align, is64Bits> *c) {
992 return c->kind() ==
993 Section<target_endianness, max_align, is64Bits>::K_StringTable;
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000994 }
995
996 uint64_t addString(const StringRef symname) {
997 _strings.push_back(symname);
998 uint64_t offset = this->_fsize;
999 this->_fsize += symname.size() + 1;
1000 return offset;
1001 }
1002
Michael J. Spencera2c97272013-01-04 21:09:21 +00001003 void write(ELFWriter *writer,
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001004 OwningPtr<FileOutputBuffer> &buffer) {
1005 uint8_t *chunkBuffer = buffer->getBufferStart();
1006 uint8_t *dest = chunkBuffer + this->fileOffset();
1007 for (auto si : _strings) {
1008 memcpy(dest, si.data(), si.size());
1009 dest += si.size();
1010 memcpy(dest, "", 1);
1011 dest += 1;
1012 }
1013 }
1014
1015 void finalize() { }
1016
1017private:
1018 std::vector<StringRef> _strings;
1019};
1020
Michael J. Spencera2c97272013-01-04 21:09:21 +00001021/// \brief The ELFSymbolTable class represents the symbol table in a ELF file
1022template<support::endianness target_endianness,
1023 std::size_t max_align,
1024 bool is64Bits>
1025class ELFSymbolTable : public Section<target_endianness, max_align, is64Bits> {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001026public:
Michael J. Spencera2c97272013-01-04 21:09:21 +00001027 typedef object::Elf_Sym_Impl<target_endianness, max_align, is64Bits> Elf_Sym;
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001028
Michael J. Spencera2c97272013-01-04 21:09:21 +00001029 ELFSymbolTable(const char *str, int32_t order)
1030 : Section<target_endianness, max_align, is64Bits>(
1031 str,
1032 llvm::ELF::SHT_SYMTAB,
1033 0,
1034 order,
1035 Section<target_endianness, max_align, is64Bits>::K_SymbolTable) {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001036 this->setOrder(order);
1037 Elf_Sym *symbol = new (_symbolAllocate.Allocate<Elf_Sym>()) Elf_Sym;
Michael J. Spencera2c97272013-01-04 21:09:21 +00001038 memset((void *)symbol, 0, sizeof(Elf_Sym));
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001039 _symbolTable.push_back(symbol);
1040 this->_entSize = sizeof(Elf_Sym);
1041 this->_fsize = sizeof(Elf_Sym);
1042 this->_align2 = sizeof(void *);
1043 }
1044
Michael J. Spencera2c97272013-01-04 21:09:21 +00001045 static inline bool classof(
1046 const Chunk<target_endianness, max_align, is64Bits> *c) {
1047 return c->kind() ==
1048 Section<target_endianness, max_align, is64Bits>::K_SymbolTable;
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001049 }
1050
1051 void addSymbol(const Atom *atom, int32_t sectionIndex, uint64_t addr = 0) {
1052 Elf_Sym *symbol = new(_symbolAllocate.Allocate<Elf_Sym>()) Elf_Sym;
1053 unsigned char binding = 0, type = 0;
1054 symbol->st_name = _stringSection->addString(atom->name());
1055 symbol->st_size = 0;
1056 symbol->st_shndx = sectionIndex;
1057 symbol->st_value = 0;
1058 symbol->st_other = ELF::STV_DEFAULT;
1059 if (const DefinedAtom *da = llvm::dyn_cast<const DefinedAtom>(atom)){
1060 symbol->st_size = da->size();
1061 lld::DefinedAtom::ContentType ct;
1062 switch (ct = da->contentType()){
1063 case DefinedAtom::typeCode:
1064 symbol->st_value = addr;
1065 type = ELF::STT_FUNC;
1066 break;
1067 case DefinedAtom::typeData:
1068 symbol->st_value = addr;
1069 type = ELF::STT_OBJECT;
1070 break;
1071 case DefinedAtom::typeZeroFill:
1072 type = ELF::STT_COMMON;
1073 symbol->st_value = addr;
1074 break;
1075 default:
1076 type = ELF::STT_NOTYPE;
1077 }
Michael J. Spencera2c97272013-01-04 21:09:21 +00001078 if (da->scope() == DefinedAtom::scopeTranslationUnit)
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001079 binding = ELF::STB_LOCAL;
1080 else
1081 binding = ELF::STB_GLOBAL;
Michael J. Spencera2c97272013-01-04 21:09:21 +00001082 } else if (const AbsoluteAtom *aa =
1083 llvm::dyn_cast<const AbsoluteAtom>(atom)){
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001084 type = ELF::STT_OBJECT;
1085 symbol->st_shndx = ELF::SHN_ABS;
1086 switch (aa->scope()) {
1087 case AbsoluteAtom::scopeLinkageUnit:
1088 symbol->st_other = ELF::STV_HIDDEN;
1089 binding = ELF::STB_LOCAL;
1090 break;
1091 case AbsoluteAtom::scopeTranslationUnit:
1092 binding = ELF::STB_LOCAL;
1093 break;
1094 case AbsoluteAtom::scopeGlobal:
1095 binding = ELF::STB_GLOBAL;
1096 break;
1097 }
1098 symbol->st_value = aa->value();
Michael J. Spencera2c97272013-01-04 21:09:21 +00001099 }
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001100 else {
1101 symbol->st_value = 0;
1102 type = ELF::STT_NOTYPE;
1103 binding = ELF::STB_WEAK;
1104 }
1105 symbol->setBindingAndType(binding, type);
1106 _symbolTable.push_back(symbol);
1107 this->_fsize += sizeof(Elf_Sym);
1108 }
1109
Michael J. Spencera2c97272013-01-04 21:09:21 +00001110 void setStringSection(
1111 ELFStringTable<target_endianness, max_align, is64Bits> *s) {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001112 _stringSection = s;
1113 }
1114
1115 void finalize() {
1116 // sh_info should be one greater than last symbol with STB_LOCAL binding
1117 // we sort the symbol table to keep all local symbols at the beginning
1118 std::stable_sort(_symbolTable.begin(), _symbolTable.end(),
1119 [](const Elf_Sym *A, const Elf_Sym *B) {
1120 return A->getBinding() < B->getBinding();
Michael J. Spencera2c97272013-01-04 21:09:21 +00001121 });
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001122 uint16_t shInfo = 0;
1123 for (auto i : _symbolTable) {
1124 if (i->getBinding() != ELF::STB_LOCAL)
1125 break;
1126 shInfo++;
1127 }
1128 this->_shInfo = shInfo;
1129 this->setLink(_stringSection->ordinal());
1130 }
1131
Michael J. Spencera2c97272013-01-04 21:09:21 +00001132 void write(ELFWriter *writer,
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001133 OwningPtr<FileOutputBuffer> &buffer) {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001134 uint8_t *chunkBuffer = buffer->getBufferStart();
1135 uint8_t *dest = chunkBuffer + this->fileOffset();
1136 for (auto sti : _symbolTable) {
1137 memcpy(dest, sti, sizeof(Elf_Sym));
1138 dest += sizeof(Elf_Sym);
1139 }
1140 }
1141
1142private:
Michael J. Spencera2c97272013-01-04 21:09:21 +00001143 ELFStringTable<target_endianness, max_align, is64Bits> *_stringSection;
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001144 std::vector<Elf_Sym*> _symbolTable;
1145 llvm::BumpPtrAllocator _symbolAllocate;
1146 int64_t _link;
1147};
1148
1149/// \brief An ELFHeader represents the Elf[32/64]_Ehdr structure at the
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001150/// start of an ELF executable file.
Michael J. Spencera2c97272013-01-04 21:09:21 +00001151template<support::endianness target_endianness,
1152 std::size_t max_align,
1153 bool is64Bits>
1154class ELFHeader : public Chunk<target_endianness, max_align, is64Bits> {
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001155public:
Michael J. Spencera2c97272013-01-04 21:09:21 +00001156 typedef Elf_Ehdr_Impl<target_endianness, max_align, is64Bits> Elf_Ehdr;
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001157
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001158 ELFHeader()
Michael J. Spencera2c97272013-01-04 21:09:21 +00001159 : Chunk<target_endianness, max_align, is64Bits>(
1160 "elfhdr", Chunk<target_endianness, max_align, is64Bits>::K_ELFHeader) {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001161 memset(_eh.e_ident, 0, llvm::ELF::EI_NIDENT);
1162 e_ident(ELF::EI_MAG0, 0x7f);
1163 e_ident(ELF::EI_MAG1, 'E');
1164 e_ident(ELF::EI_MAG2, 'L');
1165 e_ident(ELF::EI_MAG3, 'F');
1166 e_ehsize(sizeof(Elf_Ehdr));
1167 e_flags(2);
1168 }
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001169 void e_ident(int I, unsigned char C) { _eh.e_ident[I] = C; }
1170 void e_type(uint16_t type) { _eh.e_type = type; }
1171 void e_machine(uint16_t machine) { _eh.e_machine = machine; }
1172 void e_version(uint32_t version) { _eh.e_version = version; }
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001173 void e_entry(int64_t entry) { _eh.e_entry = entry; }
1174 void e_phoff(int64_t phoff) { _eh.e_phoff = phoff; }
1175 void e_shoff(int64_t shoff) { _eh.e_shoff = shoff; }
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001176 void e_flags(uint32_t flags) { _eh.e_flags = flags; }
1177 void e_ehsize(uint16_t ehsize) { _eh.e_ehsize = ehsize; }
1178 void e_phentsize(uint16_t phentsize) { _eh.e_phentsize = phentsize; }
1179 void e_phnum(uint16_t phnum) { _eh.e_phnum = phnum; }
1180 void e_shentsize(uint16_t shentsize) { _eh.e_shentsize = shentsize; }
1181 void e_shnum(uint16_t shnum) { _eh.e_shnum = shnum; }
1182 void e_shstrndx(uint16_t shstrndx) { _eh.e_shstrndx = shstrndx; }
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001183 uint64_t fileSize() { return sizeof (Elf_Ehdr); }
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001184
Michael J. Spencera2c97272013-01-04 21:09:21 +00001185 static inline bool classof(
1186 const Chunk<target_endianness, max_align, is64Bits> *c) {
1187 return c->Kind() ==
1188 Chunk<target_endianness, max_align, is64Bits>::K_ELFHeader;
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001189 }
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001190
Michael J. Spencera2c97272013-01-04 21:09:21 +00001191 void write(ELFWriter *writer,
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001192 OwningPtr<FileOutputBuffer> &buffer) {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001193 uint8_t *chunkBuffer = buffer->getBufferStart();
1194 uint8_t *atomContent = chunkBuffer + this->fileOffset();
1195 memcpy(atomContent, &_eh, fileSize());
1196 }
1197
1198 void finalize() { }
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001199
1200private:
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001201 Elf_Ehdr _eh;
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001202};
1203
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001204/// \brief An ELFProgramHeader represents the Elf[32/64]_Phdr structure at the
1205/// start of an ELF executable file.
Michael J. Spencera2c97272013-01-04 21:09:21 +00001206template<support::endianness target_endianness,
1207 std::size_t max_align,
1208 bool is64Bits>
1209class ELFProgramHeader : public Chunk<target_endianness, max_align, is64Bits> {
Hemant Kulkarni08e410292012-10-01 23:53:20 +00001210public:
Michael J. Spencera2c97272013-01-04 21:09:21 +00001211 typedef Elf_Phdr<target_endianness, max_align, is64Bits> Elf_Phdr;
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001212
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001213 ELFProgramHeader()
Michael J. Spencera2c97272013-01-04 21:09:21 +00001214 : Chunk<target_endianness, max_align, is64Bits>(
1215 "elfphdr",
1216 Chunk<target_endianness, max_align, is64Bits>::K_ELFProgramHeader) { }
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001217
Michael J. Spencera2c97272013-01-04 21:09:21 +00001218 bool addSegment(Segment<target_endianness, max_align, is64Bits> *segment) {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001219 Elf_Phdr *phdr = nullptr;
1220 bool ret = false;
1221
Michael J. Spencera2c97272013-01-04 21:09:21 +00001222 for (auto sei = segment->slices_begin(), see = segment->slices_end();
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001223 sei != see; ++sei) {
1224 if (_phi == _ph.end()) {
1225 phdr = new(_allocator.Allocate<Elf_Phdr>()) Elf_Phdr;
1226 _ph.push_back(phdr);
1227 _phi = _ph.end();
1228 ret = true;
1229 } else {
1230 phdr = (*_phi);
1231 ++_phi;
1232 }
1233 phdr->p_type = segment->segmentType();
1234 phdr->p_offset = (*sei)->fileOffset();
1235 phdr->p_vaddr = (*sei)->virtualAddr();
1236 phdr->p_paddr = (*sei)->virtualAddr();
1237 phdr->p_filesz = (*sei)->fileSize();
1238 phdr->p_memsz = (*sei)->memSize();
1239 phdr->p_flags = segment->flags();
Michael J. Spencera2c97272013-01-04 21:09:21 +00001240 phdr->p_align = (phdr->p_type == llvm::ELF::PT_LOAD) ?
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001241 segment->pageSize() : (*sei)->align2();
1242 }
1243 return ret;
1244 }
1245
1246 void resetProgramHeaders() {
Michael J. Spencera2c97272013-01-04 21:09:21 +00001247 _phi = _ph.begin();
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001248 }
1249
1250 void setVAddr(uint64_t addr) {
1251 this->_start = llvm::RoundUpToAlignment(addr, 8);
1252 this->_fsize = this->_start - addr;
1253 }
1254
Michael J. Spencera2c97272013-01-04 21:09:21 +00001255 uint64_t fileSize() {
1256 return this->_fsize + (sizeof (Elf_Phdr) * _ph.size());
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001257 }
1258
Michael J. Spencera2c97272013-01-04 21:09:21 +00001259 static inline bool classof(
1260 const Chunk<target_endianness, max_align, is64Bits> *c) {
1261 return c->Kind() ==
1262 Chunk<target_endianness, max_align, is64Bits>::K_ELFProgramHeader;
1263 }
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001264
Michael J. Spencera2c97272013-01-04 21:09:21 +00001265 void write(ELFWriter *writer,
1266 OwningPtr<FileOutputBuffer> &buffer) {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001267 uint8_t *chunkBuffer = buffer->getBufferStart();
1268 uint8_t *dest = chunkBuffer + this->fileOffset();
1269 for (auto phi : _ph) {
1270 memcpy(dest, phi, sizeof(Elf_Phdr));
1271 dest += sizeof(Elf_Phdr);
1272 }
1273 }
1274
1275 void finalize() { }
1276
Michael J. Spencera2c97272013-01-04 21:09:21 +00001277 int64_t entsize() {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001278 return sizeof(Elf_Phdr);
1279 }
1280
1281 int64_t numHeaders() {
1282 return _ph.size();
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001283 }
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001284
1285private:
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001286 std::vector<Elf_Phdr *> _ph;
1287 typedef typename std::vector<Elf_Phdr *>::iterator ph_iter;
1288 ph_iter _phi;
1289 llvm::BumpPtrAllocator _allocator;
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001290};
1291
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001292/// \brief An ELFSectionHeader represents the Elf[32/64]_Shdr structure
1293/// at the end of the file
Michael J. Spencera2c97272013-01-04 21:09:21 +00001294template<support::endianness target_endianness,
1295 std::size_t max_align,
1296 bool is64Bits>
1297class ELFSectionHeader : public Chunk<target_endianness, max_align, is64Bits> {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001298public:
Michael J. Spencera2c97272013-01-04 21:09:21 +00001299 typedef Elf_Shdr_Impl<target_endianness, max_align, is64Bits> Elf_Shdr;
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001300
Michael J. Spencera2c97272013-01-04 21:09:21 +00001301 ELFSectionHeader(int32_t order)
1302 : Chunk<target_endianness, max_align, is64Bits>(
1303 "shdr",
1304 Chunk<target_endianness, max_align, is64Bits>::K_ELFSectionHeader) {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001305 this->_fsize = 0;
1306 this->_align2 = 8;
1307 this->setOrder(order);
1308 // The first element in the list is always NULL
1309 Elf_Shdr *nullshdr = new (_sectionAllocate.Allocate<Elf_Shdr>()) Elf_Shdr;
1310 ::memset(nullshdr, 0, sizeof (Elf_Shdr));
1311 _sectionInfo.push_back(nullshdr);
1312 this->_fsize += sizeof (Elf_Shdr);
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001313 }
1314
Michael J. Spencera2c97272013-01-04 21:09:21 +00001315 uint16_t fileSize() {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001316 return sizeof(Elf_Shdr) * _sectionInfo.size();
Hemant Kulkarni08e410292012-10-01 23:53:20 +00001317 }
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001318
Michael J. Spencera2c97272013-01-04 21:09:21 +00001319 void appendSection(
1320 MergedSections<target_endianness, max_align, is64Bits> *section) {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001321 Elf_Shdr *shdr = new (_sectionAllocate.Allocate<Elf_Shdr>()) Elf_Shdr;
1322 shdr->sh_name = _stringSection->addString(section->name());
1323 shdr->sh_type = section->type();
1324 shdr->sh_flags = section->flags();
1325 shdr->sh_offset = section->fileOffset();
1326 shdr->sh_addr = section->virtualAddr();
1327 shdr->sh_size = section->memSize();
1328 shdr->sh_link = section->link();
1329 shdr->sh_info = section->shinfo();
1330 shdr->sh_addralign = section->align2();
1331 shdr->sh_entsize = section->entsize();
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001332 _sectionInfo.push_back(shdr);
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001333 }
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001334
Michael J. Spencera2c97272013-01-04 21:09:21 +00001335 void updateSection(Section<target_endianness, max_align, is64Bits> *section) {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001336 Elf_Shdr *shdr = _sectionInfo[section->ordinal()];
1337 shdr->sh_type = section->type();
1338 shdr->sh_flags = section->flags();
1339 shdr->sh_offset = section->fileOffset();
1340 shdr->sh_addr = section->virtualAddr();
1341 shdr->sh_size = section->fileSize();
1342 shdr->sh_link = section->link();
1343 shdr->sh_info = section->shinfo();
1344 shdr->sh_addralign = section->align2();
1345 shdr->sh_entsize = section->entsize();
1346 }
1347
Michael J. Spencera2c97272013-01-04 21:09:21 +00001348 static inline bool classof(
1349 const Chunk<target_endianness, max_align, is64Bits> *c) {
1350 return c->getChunkKind() ==
1351 Chunk<target_endianness, max_align, is64Bits>::K_ELFSectionHeader;
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001352 }
1353
Michael J. Spencera2c97272013-01-04 21:09:21 +00001354 void setStringSection(
1355 ELFStringTable<target_endianness, max_align, is64Bits> *s) {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001356 _stringSection = s;
1357 }
1358
Michael J. Spencera2c97272013-01-04 21:09:21 +00001359 void write(ELFWriter *writer,
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001360 OwningPtr<FileOutputBuffer> &buffer) {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001361 uint8_t *chunkBuffer = buffer->getBufferStart();
1362 uint8_t *dest = chunkBuffer + this->fileOffset();
1363 for (auto shi : _sectionInfo) {
1364 memcpy(dest, shi, sizeof(Elf_Shdr));
1365 dest += sizeof(Elf_Shdr);
1366 }
1367 _stringSection->write(writer, buffer);
1368 }
1369
1370 void finalize() { }
1371
Michael J. Spencera2c97272013-01-04 21:09:21 +00001372 int64_t entsize() {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001373 return sizeof(Elf_Shdr);
1374 }
1375
1376 int64_t numHeaders() {
1377 return _sectionInfo.size();
1378 }
1379
1380private:
Michael J. Spencera2c97272013-01-04 21:09:21 +00001381 ELFStringTable<target_endianness, max_align, is64Bits> *_stringSection;
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001382 std::vector<Elf_Shdr*> _sectionInfo;
1383 llvm::BumpPtrAllocator _sectionAllocate;
1384};
1385
Michael J. Spencera2c97272013-01-04 21:09:21 +00001386/// \brief The DefaultELFLayout class is used by the Writer to arrange
1387/// sections and segments in the order determined by the target ELF
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001388/// format. The writer creates a single instance of the DefaultELFLayout
Michael J. Spencera2c97272013-01-04 21:09:21 +00001389/// class
1390template<support::endianness target_endianness,
1391 std::size_t max_align,
1392 bool is64Bits>
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001393class DefaultELFLayout : public ELFLayout {
1394public:
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001395
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001396 // The order in which the sections appear in the output file
Michael J. Spencera2c97272013-01-04 21:09:21 +00001397 // If its determined, that the layout needs to change
1398 // just changing the order of enumerations would essentially
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001399 // change the layout in the output file
1400 enum DefaultSectionOrder {
1401 ORDER_NOT_DEFINED = 0,
1402 ORDER_INTERP,
1403 ORDER_NOTE,
1404 ORDER_HASH,
1405 ORDER_DYNAMIC_SYMBOLS,
1406 ORDER_DYNAMIC_STRINGS,
1407 ORDER_INIT,
1408 ORDER_TEXT,
1409 ORDER_PLT,
1410 ORDER_FINI,
1411 ORDER_RODATA,
1412 ORDER_EH_FRAME,
1413 ORDER_EH_FRAMEHDR,
1414 ORDER_CTORS,
1415 ORDER_DTORS,
1416 ORDER_DYNAMIC,
1417 ORDER_GOT,
1418 ORDER_GOT_PLT,
1419 ORDER_DATA,
1420 ORDER_BSS,
1421 ORDER_OTHER,
1422 ORDER_SECTION_STRINGS,
1423 ORDER_SYMBOL_TABLE,
1424 ORDER_STRING_TABLE,
1425 ORDER_SECTION_HEADERS
1426 };
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001427
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001428public:
1429
1430 // The Key used for creating Sections
Michael J. Spencera2c97272013-01-04 21:09:21 +00001431 // The sections are created using
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001432 // SectionName, [contentType, contentPermissions]
Michael J. Spencera2c97272013-01-04 21:09:21 +00001433 typedef std::pair<StringRef,
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001434 std::pair<int32_t, int32_t>> Key;
Michael J. Spencera2c97272013-01-04 21:09:21 +00001435 typedef typename std::vector<
1436 Chunk<target_endianness, max_align, is64Bits> *>::iterator ChunkIter;
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001437 // The key used for Segments
Michael J. Spencera2c97272013-01-04 21:09:21 +00001438 // The segments are created using
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001439 // SegmentName, Segment flags
1440 typedef std::pair<StringRef, int64_t> SegmentKey;
1441 // Merged Sections contain the map of Sectionnames to a vector of sections,
1442 // that have been merged to form a single section
Michael J. Spencera2c97272013-01-04 21:09:21 +00001443 typedef std::map<StringRef, MergedSections<
1444 target_endianness, max_align, is64Bits> *> MergedSectionMapT;
1445 typedef typename std::vector<MergedSections<
1446 target_endianness, max_align, is64Bits> *>::iterator MergedSectionIter;
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001447
1448 // HashKey for the Section
1449 class HashKey {
1450 public:
1451 int64_t operator() (const Key &k) const {
1452 // k.first = section Name
1453 // k.second = [contentType, Permissions]
1454 return llvm::hash_combine(k.first, k.second.first, k.second.second);
1455 }
1456 };
1457
1458 // HashKey for the Segment
1459 class SegmentHashKey {
1460 public:
1461 int64_t operator() (const SegmentKey &k) const {
1462 // k.first = SegmentName
1463 // k.second = SegmentFlags
1464 return llvm::hash_combine(k.first, k.second);
1465 }
1466 };
1467
Michael J. Spencera2c97272013-01-04 21:09:21 +00001468 typedef std::unordered_map<Key, Section<
1469 target_endianness, max_align, is64Bits>*, HashKey> SectionMapT;
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001470 typedef std::unordered_map<SegmentKey,
Michael J. Spencera2c97272013-01-04 21:09:21 +00001471 Segment<target_endianness, max_align, is64Bits>*,
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001472 SegmentHashKey> SegmentMapT;
1473
1474 DefaultELFLayout(const WriterOptionsELF &options):_options(options) { }
1475
1476 /// \brief Return the section order for a input section
1477 virtual SectionOrder getSectionOrder
1478 (const StringRef name,
1479 int32_t contentType,
1480 int32_t contentPermissions) {
1481 switch (contentType) {
1482 case DefinedAtom::typeCode:
1483 return llvm::StringSwitch<Reference::Kind>(name)
1484 .StartsWith(".eh_frame_hdr", ORDER_EH_FRAMEHDR)
1485 .StartsWith(".eh_frame", ORDER_EH_FRAME)
1486 .StartsWith(".init", ORDER_INIT)
1487 .StartsWith(".fini", ORDER_FINI)
1488 .StartsWith(".hash", ORDER_HASH)
1489 .Default(ORDER_TEXT);
1490
1491 case DefinedAtom::typeConstant:
Michael J. Spencera2c97272013-01-04 21:09:21 +00001492 return ORDER_RODATA;
1493
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001494 case DefinedAtom::typeData:
1495 return ORDER_DATA;
Michael J. Spencera2c97272013-01-04 21:09:21 +00001496
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001497 case DefinedAtom::typeZeroFill:
1498 return ORDER_BSS;
1499
1500 default:
1501 // If we get passed in a section push it to OTHER
Michael J. Spencera2c97272013-01-04 21:09:21 +00001502 if (contentPermissions == DefinedAtom::perm___)
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001503 return ORDER_OTHER;
Michael J. Spencera2c97272013-01-04 21:09:21 +00001504
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001505 return ORDER_NOT_DEFINED;
1506 }
1507 }
1508
1509 /// \brief This maps the input sections to the output section names
1510 StringRef getSectionName(const StringRef name,
1511 const int32_t contentType) {
Michael J. Spencera2c97272013-01-04 21:09:21 +00001512 if (contentType == DefinedAtom::typeZeroFill)
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001513 return ".bss";
Michael J. Spencera2c97272013-01-04 21:09:21 +00001514 if (name.startswith(".text"))
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001515 return ".text";
Michael J. Spencera2c97272013-01-04 21:09:21 +00001516 if (name.startswith(".rodata"))
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001517 return ".rodata";
1518 return name;
1519 }
1520
1521 /// \brief Gets the segment for a output section
Michael J. Spencera2c97272013-01-04 21:09:21 +00001522 virtual ELFLayout::SegmentType getSegmentType(
1523 Section<target_endianness, max_align, is64Bits> *section) const {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001524 switch(section->order()) {
1525 case ORDER_INTERP:
1526 return llvm::ELF::PT_INTERP;
1527
1528 case ORDER_TEXT:
1529 case ORDER_HASH:
1530 case ORDER_DYNAMIC_SYMBOLS:
1531 case ORDER_DYNAMIC_STRINGS:
1532 case ORDER_INIT:
1533 case ORDER_PLT:
1534 case ORDER_FINI:
1535 case ORDER_RODATA:
1536 case ORDER_EH_FRAME:
1537 case ORDER_EH_FRAMEHDR:
1538 return llvm::ELF::PT_LOAD;
1539
1540 case ORDER_NOTE:
1541 return llvm::ELF::PT_NOTE;
1542
1543 case ORDER_DYNAMIC:
1544 return llvm::ELF::PT_DYNAMIC;
1545
1546 case ORDER_CTORS:
1547 case ORDER_DTORS:
1548 case ORDER_GOT:
1549 return llvm::ELF::PT_GNU_RELRO;
1550
1551 case ORDER_GOT_PLT:
1552 case ORDER_DATA:
1553 case ORDER_BSS:
1554 return llvm::ELF::PT_LOAD;
1555
1556 default:
1557 return llvm::ELF::PT_NULL;
1558 }
1559 }
1560
1561 /// \brief Returns true/false depending on whether the section has a Output
1562 // segment or not
Michael J. Spencera2c97272013-01-04 21:09:21 +00001563 static bool hasOutputSegment(Section<target_endianness, max_align,
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001564 is64Bits> *section) {
1565 switch(section->order()) {
1566 case ORDER_INTERP:
1567 case ORDER_HASH:
1568 case ORDER_DYNAMIC_SYMBOLS:
1569 case ORDER_DYNAMIC_STRINGS:
1570 case ORDER_INIT:
1571 case ORDER_PLT:
1572 case ORDER_TEXT:
1573 case ORDER_FINI:
1574 case ORDER_RODATA:
1575 case ORDER_EH_FRAME:
1576 case ORDER_EH_FRAMEHDR:
1577 case ORDER_NOTE:
1578 case ORDER_DYNAMIC:
1579 case ORDER_CTORS:
1580 case ORDER_DTORS:
1581 case ORDER_GOT:
1582 case ORDER_GOT_PLT:
1583 case ORDER_DATA:
1584 case ORDER_BSS:
1585 return true;
1586
1587 default:
1588 return false;
1589 }
1590 }
1591
1592 // Adds an atom to the section
1593 virtual error_code addAtom(const Atom *atom) {
1594 const DefinedAtom *definedAtom = dyn_cast<DefinedAtom>(atom);
Michael J. Spencera2c97272013-01-04 21:09:21 +00001595 const StringRef sectionName =
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001596 getSectionName(definedAtom->customSectionName(),
1597 definedAtom->contentType());
Michael J. Spencera2c97272013-01-04 21:09:21 +00001598 const lld::DefinedAtom::ContentPermissions permissions =
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001599 definedAtom->permissions();
Michael J. Spencera2c97272013-01-04 21:09:21 +00001600 const lld::DefinedAtom::ContentType contentType =
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001601 definedAtom->contentType();
1602 const Key key(sectionName, std::make_pair(contentType, permissions));
Michael J. Spencera2c97272013-01-04 21:09:21 +00001603 const std::pair<Key, Section<target_endianness, max_align, is64Bits> *>
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001604 currentSection(key, nullptr);
Michael J. Spencera2c97272013-01-04 21:09:21 +00001605 std::pair<typename SectionMapT::iterator, bool>
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001606 sectionInsert(_sectionMap.insert(currentSection));
Michael J. Spencera2c97272013-01-04 21:09:21 +00001607 Section<target_endianness, max_align, is64Bits> *section;
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001608 // the section is already in the map
1609 if (!sectionInsert.second) {
1610 section = sectionInsert.first->second;
1611 section->setContentPermissions(permissions);
1612 }
1613 else {
1614 SectionOrder section_order = getSectionOrder(sectionName,
1615 contentType,
1616 permissions);
1617 section = new (_allocator.Allocate
Michael J. Spencera2c97272013-01-04 21:09:21 +00001618 <Section<target_endianness, max_align, is64Bits>>())
1619 Section<target_endianness, max_align, is64Bits>
1620 (sectionName, contentType,
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001621 permissions, section_order);
1622 sectionInsert.first->second = section;
1623 section->setOrder(section_order);
1624 _sections.push_back(section);
1625 }
1626 section->appendAtom(atom);
1627 return error_code::success();
1628 }
1629
1630 // Merge sections with the same name into a MergedSections
1631 void mergeSimiliarSections() {
Michael J. Spencera2c97272013-01-04 21:09:21 +00001632 MergedSections<target_endianness, max_align, is64Bits> *mergedSection;
1633
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001634 for (auto &si : _sections) {
Michael J. Spencera2c97272013-01-04 21:09:21 +00001635 const std::pair<StringRef,
1636 MergedSections<target_endianness, max_align, is64Bits> *>
1637 currentMergedSections(si->name(), nullptr);
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001638 std::pair<typename MergedSectionMapT::iterator, bool>
1639 mergedSectionInsert
1640 (_mergedSectionMap.insert(currentMergedSections));
1641 if (!mergedSectionInsert.second) {
1642 mergedSection = mergedSectionInsert.first->second;
1643 }
1644 else {
Michael J. Spencera2c97272013-01-04 21:09:21 +00001645 mergedSection = new (_allocator.Allocate<
1646 MergedSections<target_endianness, max_align, is64Bits>>())
1647 MergedSections<target_endianness, max_align, is64Bits>(si->name());
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001648 _mergedSections.push_back(mergedSection);
1649 mergedSectionInsert.first->second = mergedSection;
1650 }
1651 mergedSection->appendSection(si);
1652 }
1653 }
1654
1655 void assignSectionsToSegments() {
1656 // sort the sections by their order as defined by the layout
1657 std::stable_sort(_sections.begin(), _sections.end(),
Michael J. Spencera2c97272013-01-04 21:09:21 +00001658 [](Chunk<target_endianness, max_align, is64Bits> *A,
1659 Chunk<target_endianness, max_align, is64Bits> *B) {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001660 return A->order() < B->order();
1661 });
1662 // Merge all sections
1663 mergeSimiliarSections();
1664 // Set the ordinal after sorting the sections
1665 int ordinal = 1;
1666 for (auto &msi : _mergedSections) {
1667 (*msi).setOrdinal(ordinal);
1668 for (auto ai = (*msi).begin_sections(), ae = (*msi).end_sections();
1669 ai != ae; ++ai) {
1670 (*ai)->setOrdinal(ordinal);
1671 }
1672 ++ordinal;
1673 }
Michael J. Spencera2c97272013-01-04 21:09:21 +00001674 Section<target_endianness, max_align, is64Bits> *section;
1675 Segment<target_endianness, max_align, is64Bits> *segment;
1676 for (auto msi = merged_sections_begin(), mse = merged_sections_end();
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001677 msi != mse; ++msi) {
Michael J. Spencera2c97272013-01-04 21:09:21 +00001678 for (auto ai = (*msi)->begin_sections(), ae = (*msi)->end_sections();
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001679 ai != ae; ++ai) {
Michael J. Spencera2c97272013-01-04 21:09:21 +00001680 if ((*ai)->kind() ==
1681 Chunk<target_endianness, max_align, is64Bits>::K_ELFSection) {
1682 section = llvm::dyn_cast<
1683 Section<target_endianness, max_align, is64Bits>>(*ai);
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001684 if (!hasOutputSegment(section))
1685 continue;
1686 (*msi)->setHasSegment();
1687 section->setSegment(getSegmentType(section));
1688 const StringRef segmentName = section->segmentKindToStr();
1689 // Use the flags of the merged Section for the segment
1690 const SegmentKey key(segmentName, (*msi)->flags());
Michael J. Spencera2c97272013-01-04 21:09:21 +00001691 const std::pair<SegmentKey,
1692 Segment<target_endianness, max_align, is64Bits> *>
1693 currentSegment(key, nullptr);
1694 std::pair<typename SegmentMapT::iterator, bool>
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001695 segmentInsert(_segmentMap.insert(currentSegment));
1696
1697 if (!segmentInsert.second) {
1698 segment = segmentInsert.first->second;
1699 } else {
1700 segment = new (_allocator.Allocate
Michael J. Spencera2c97272013-01-04 21:09:21 +00001701 <Segment<target_endianness, max_align, is64Bits>>())
1702 Segment<target_endianness, max_align, is64Bits>
1703 (segmentName, getSegmentType(section),
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001704 _options);
1705 segmentInsert.first->second = segment;
1706 _segments.push_back(segment);
1707 }
1708 segment->append(section);
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001709 }
1710 }
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001711 }
1712 }
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001713
Michael J. Spencera2c97272013-01-04 21:09:21 +00001714 void addSection(Chunk<target_endianness, max_align, is64Bits> *c) {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001715 _sections.push_back(c);
1716 }
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001717
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001718 void assignFileOffsets() {
Michael J. Spencera2c97272013-01-04 21:09:21 +00001719 std::sort(_segments.begin(),
1720 _segments.end(),
1721 Segment<target_endianness, max_align, is64Bits>::compareSegments);
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001722 int ordinal = 0;
1723 // Compute the number of segments that might be needed, so that the
1724 // size of the program header can be computed
1725 uint64_t offset = 0;
1726 for (auto si : _segments) {
1727 si->setOrdinal(++ordinal);
1728 si->assignOffsets(offset);
1729 offset += si->fileSize();
1730 }
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001731 }
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001732
Michael J. Spencera2c97272013-01-04 21:09:21 +00001733 void setELFHeader(ELFHeader<target_endianness, max_align, is64Bits> *e) {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001734 _elfHeader = e;
1735 }
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001736
Michael J. Spencera2c97272013-01-04 21:09:21 +00001737 void setProgramHeader(
1738 ELFProgramHeader<target_endianness, max_align, is64Bits> *p) {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001739 _programHeader = p;
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001740 }
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001741
1742 void assignVirtualAddress() {
1743 int32_t numSlices = 0;
1744 uint64_t virtualAddress = _options.baseAddress();
1745
1746 // Add the ELF Header
1747 if (_elfHeader) {
1748 _elfHeader->setFileOffset(0);
1749 _elfHeader->setVAddr(virtualAddress);
1750 }
1751 // Add the program header
1752 if (_programHeader) {
Michael J. Spencera2c97272013-01-04 21:09:21 +00001753 _programHeader->setVAddr(
1754 uint64_t(virtualAddress + _elfHeader->fileSize()));
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001755 _programHeader->setFileOffset(_elfHeader->fileSize());
1756 }
1757 bool newSegmentHeaderAdded = true;
1758 while (true) {
1759 for (auto si : _segments) {
1760 newSegmentHeaderAdded = _programHeader->addSegment(si);
1761 numSlices += si->numSlices();
1762 }
Michael J. Spencera2c97272013-01-04 21:09:21 +00001763 if (!newSegmentHeaderAdded)
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001764 break;
1765 uint64_t fileoffset = _elfHeader->fileSize() + _programHeader->fileSize();
1766 uint64_t address = virtualAddress;
1767 // Fix the offsets after adding the program header
1768 for (auto &si : _segments) {
1769 // Align the segment to a page boundary
1770 fileoffset = llvm::RoundUpToAlignment(fileoffset, _options.pageSize());
1771 si->assignOffsets(fileoffset);
1772 fileoffset = si->fileOffset() + si->fileSize();
1773 }
1774 // start assigning virtual addresses
1775 for (auto si = _segments.begin(); si != _segments.end(); ++si) {
1776 (*si)->setVAddr(virtualAddress);
1777 // The first segment has the virtualAddress set to the base address as
1778 // we have added the file header and the program header dont align the
Michael J. Spencera2c97272013-01-04 21:09:21 +00001779 // first segment to the pagesize
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001780 (*si)->assignVirtualAddress(address, (si == _segments.begin()));
1781 (*si)->setMemSize(address - virtualAddress);
1782 virtualAddress = llvm::RoundUpToAlignment(address, _options.pageSize());
1783 }
1784 _programHeader->resetProgramHeaders();
1785 }
Michael J. Spencera2c97272013-01-04 21:09:21 +00001786 Section<target_endianness, max_align, is64Bits> *section;
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001787 // Fix the offsets of all the atoms within a section
1788 for (auto &si : _sections) {
Michael J. Spencera2c97272013-01-04 21:09:21 +00001789 section =
1790 llvm::dyn_cast<Section<target_endianness, max_align, is64Bits>>(si);
1791 if (section &&
1792 DefaultELFLayout<target_endianness,
1793 max_align, is64Bits>::hasOutputSegment(section))
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001794 section->assignOffsets(section->fileOffset());
1795 }
1796 // Set the size of the merged Sections
Michael J. Spencera2c97272013-01-04 21:09:21 +00001797 for (auto msi = merged_sections_begin(), mse = merged_sections_end();
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001798 msi != mse; ++msi) {
1799 uint64_t sectionfileoffset = 0;
1800 uint64_t startFileOffset = 0;
1801 uint64_t sectionsize = 0;
1802 bool isFirstSection = true;
Michael J. Spencera2c97272013-01-04 21:09:21 +00001803 for (auto si = (*msi)->begin_sections(); si != (*msi)->end_sections();
1804 ++si) {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001805 if (isFirstSection) {
1806 startFileOffset = (*si)->fileOffset();
1807 isFirstSection = false;
1808 }
1809 sectionfileoffset = (*si)->fileOffset();
1810 sectionsize = (*si)->fileSize();
1811 }
1812 sectionsize = (sectionfileoffset - startFileOffset) + sectionsize;
1813 (*msi)->setFileOffset(startFileOffset);
1814 (*msi)->setSize(sectionsize);
1815 }
1816 // Set the virtual addr of the merged Sections
Michael J. Spencera2c97272013-01-04 21:09:21 +00001817 for (auto msi = merged_sections_begin(), mse = merged_sections_end();
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001818 msi != mse; ++msi) {
1819 uint64_t sectionstartaddr = 0;
1820 uint64_t startaddr = 0;
1821 uint64_t sectionsize = 0;
1822 bool isFirstSection = true;
Michael J. Spencera2c97272013-01-04 21:09:21 +00001823 for (auto si = (*msi)->begin_sections(), se = (*msi)->end_sections();
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001824 si != se; ++si) {
1825 if (isFirstSection) {
1826 startaddr = (*si)->virtualAddr();
1827 isFirstSection = false;
1828 }
1829 sectionstartaddr = (*si)->virtualAddr();
1830 sectionsize = (*si)->memSize();
1831 }
1832 sectionsize = (sectionstartaddr - startaddr) + sectionsize;
1833 (*msi)->setMemSize(sectionsize);
1834 (*msi)->setAddr(startaddr);
1835 }
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001836 }
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001837
1838 void assignOffsetsForMiscSections() {
1839 uint64_t fileoffset = 0;
1840 uint64_t size = 0;
1841 for (auto si : _segments) {
1842 fileoffset = si->fileOffset();
1843 size = si->fileSize();
1844 }
1845 fileoffset = fileoffset + size;
Michael J. Spencera2c97272013-01-04 21:09:21 +00001846 Section<target_endianness, max_align, is64Bits> *section;
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001847 for (auto si : _sections) {
Michael J. Spencera2c97272013-01-04 21:09:21 +00001848 section =
1849 llvm::dyn_cast<Section<target_endianness, max_align, is64Bits>>(si);
1850 if (section &&
1851 DefaultELFLayout<target_endianness,
1852 max_align, is64Bits>::hasOutputSegment(section))
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001853 continue;
1854 fileoffset = llvm::RoundUpToAlignment(fileoffset, si->align2());
1855 si->setFileOffset(fileoffset);
1856 si->setVAddr(0);
1857 fileoffset += si->fileSize();
1858 }
Hemant Kulkarni08e410292012-10-01 23:53:20 +00001859 }
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001860
1861 void finalize() {
1862 for (auto &si : _sections) {
1863 si->finalize();
1864 }
1865 }
1866
1867 bool findAtomAddrByName(const StringRef name, uint64_t &addr) {
Michael J. Spencera2c97272013-01-04 21:09:21 +00001868 Section<target_endianness, max_align, is64Bits> *section;
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001869 for (auto ai = _sections.begin(); ai != _sections.end(); ++ai) {
Michael J. Spencera2c97272013-01-04 21:09:21 +00001870 if ((*ai)->kind() ==
1871 Chunk<target_endianness, max_align, is64Bits>::K_ELFSection) {
1872 section =
1873 llvm::dyn_cast<Section<target_endianness, max_align, is64Bits>>(*ai);
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001874 if (section->findAtomAddrByName(name, addr))
1875 return true;
1876 }
1877 }
Michael J. Spencera2c97272013-01-04 21:09:21 +00001878 return false;
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001879 }
1880
Michael J. Spencera2c97272013-01-04 21:09:21 +00001881 MergedSectionIter merged_sections_begin() {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001882 return _mergedSections.begin();
1883 }
1884
Michael J. Spencera2c97272013-01-04 21:09:21 +00001885 MergedSectionIter merged_sections_end() {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001886 return _mergedSections.end();
1887 }
1888
1889 ChunkIter sections_begin() {
1890 return _sections.begin();
1891 }
1892 ChunkIter sections_end() {
1893 return _sections.end();
1894 }
1895
1896 ChunkIter segments_begin() {
1897 return _segments.begin();
1898 }
1899
1900 ChunkIter segments_end() {
1901 return _segments.end();
1902 }
1903
Michael J. Spencera2c97272013-01-04 21:09:21 +00001904 ELFHeader<target_endianness, max_align, is64Bits> *elfHeader() {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001905 return _elfHeader;
1906 }
1907
Michael J. Spencera2c97272013-01-04 21:09:21 +00001908 ELFProgramHeader<target_endianness, max_align, is64Bits> *elfProgramHeader() {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001909 return _programHeader;
Hemant Kulkarni08e410292012-10-01 23:53:20 +00001910 }
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001911
1912private:
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001913 SectionMapT _sectionMap;
1914 MergedSectionMapT _mergedSectionMap;
1915 SegmentMapT _segmentMap;
Sid Manningdd110202012-09-25 18:22:09 +00001916
Michael J. Spencera2c97272013-01-04 21:09:21 +00001917 std::vector<Chunk<target_endianness, max_align, is64Bits> *> _sections;
1918 std::vector<Segment<target_endianness, max_align, is64Bits> *> _segments;
1919 std::vector<MergedSections<target_endianness, max_align, is64Bits> *>
1920 _mergedSections;
1921 ELFHeader<target_endianness, max_align, is64Bits> *_elfHeader;
1922 ELFProgramHeader<target_endianness, max_align, is64Bits> *_programHeader;
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001923 llvm::BumpPtrAllocator _allocator;
1924 const WriterOptionsELF &_options;
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001925};
1926
1927//===----------------------------------------------------------------------===//
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001928// ELFExecutableWriter Class
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001929//===----------------------------------------------------------------------===//
Michael J. Spencera2c97272013-01-04 21:09:21 +00001930template<support::endianness target_endianness,
1931 std::size_t max_align,
1932 bool is64Bits>
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001933class ELFExecutableWriter : public ELFWriter {
1934public:
Michael J. Spencera2c97272013-01-04 21:09:21 +00001935 typedef Elf_Shdr_Impl<target_endianness, max_align, is64Bits> Elf_Shdr;
1936 typedef Elf_Sym_Impl<target_endianness, max_align, is64Bits> Elf_Sym;
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001937
1938 ELFExecutableWriter(const WriterOptionsELF &options);
1939
1940private:
Michael J. Spencera2c97272013-01-04 21:09:21 +00001941 // build the sections that need to be created
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001942 void buildChunks(const lld::File &file);
1943 virtual error_code writeFile(const lld::File &File, StringRef path);
1944 void buildAtomToAddressMap();
1945 void buildSymbolTable ();
1946 void buildSectionHeaderTable();
1947 void assignSectionsWithNoSegments();
1948 void addAbsoluteUndefinedSymbols(const lld::File &File);
1949
Michael J. Spencera2c97272013-01-04 21:09:21 +00001950 uint64_t addressOfAtom(const Atom *atom) {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001951 return _atomToAddressMap[atom];
1952 }
1953
1954 KindHandler *kindHandler() { return _referenceKindHandler.get(); }
1955
1956 void createDefaultSections();
1957
1958 const WriterOptionsELF &_options;
1959
1960 typedef llvm::DenseMap<const Atom*, uint64_t> AtomToAddress;
1961 std::unique_ptr<KindHandler> _referenceKindHandler;
1962 AtomToAddress _atomToAddressMap;
1963 llvm::BumpPtrAllocator _chunkAllocate;
Michael J. Spencera2c97272013-01-04 21:09:21 +00001964 DefaultELFLayout<target_endianness, max_align, is64Bits> *_layout;
1965 ELFHeader<target_endianness, max_align, is64Bits> *_elfHeader;
1966 ELFProgramHeader<target_endianness, max_align, is64Bits> *_programHeader;
1967 ELFSymbolTable<target_endianness, max_align, is64Bits> * _symtab;
1968 ELFStringTable<target_endianness, max_align, is64Bits> *_strtab;
1969 ELFStringTable<target_endianness, max_align, is64Bits> *_shstrtab;
1970 ELFSectionHeader<target_endianness, max_align, is64Bits> *_shdrtab;
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001971};
1972
1973//===----------------------------------------------------------------------===//
1974// ELFExecutableWriter
1975//===----------------------------------------------------------------------===//
Michael J. Spencera2c97272013-01-04 21:09:21 +00001976template<support::endianness target_endianness,
1977 std::size_t max_align,
1978 bool is64Bits>
1979ELFExecutableWriter<target_endianness, max_align, is64Bits>
1980 ::ELFExecutableWriter(const WriterOptionsELF &options)
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001981 : _options(options)
Sid Manning42064e52012-10-09 02:20:47 +00001982 , _referenceKindHandler(KindHandler::makeHandler(_options.machine(),
Michael J. Spencera2c97272013-01-04 21:09:21 +00001983 target_endianness)) {
1984 _layout =
1985 new DefaultELFLayout<target_endianness, max_align, is64Bits>(options);
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001986}
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001987
Michael J. Spencera2c97272013-01-04 21:09:21 +00001988template<support::endianness target_endianness,
1989 std::size_t max_align,
1990 bool is64Bits>
1991void ELFExecutableWriter<target_endianness, max_align, is64Bits>
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001992 ::buildChunks(const lld::File &file){
1993 for (const DefinedAtom *definedAtom : file.defined() ) {
1994 _layout->addAtom(definedAtom);
1995 }
1996}
1997
Michael J. Spencera2c97272013-01-04 21:09:21 +00001998template<support::endianness target_endianness,
1999 std::size_t max_align,
2000 bool is64Bits>
2001void ELFExecutableWriter<target_endianness, max_align, is64Bits>
2002 ::buildSymbolTable () {
2003 Section<target_endianness, max_align, is64Bits> *section;
2004 for (auto si = _layout->sections_begin(); si != _layout->sections_end();
2005 ++si) {
2006 if ((*si)->kind() !=
2007 Chunk<target_endianness, max_align, is64Bits>::K_ELFSection)
Shankar Easwaran495d38b2012-12-27 02:26:30 +00002008 continue;
Michael J. Spencera2c97272013-01-04 21:09:21 +00002009 section =
2010 llvm::dyn_cast<Section<target_endianness, max_align, is64Bits>>(*si);
Shankar Easwaran495d38b2012-12-27 02:26:30 +00002011 for (auto ai = section->atoms_begin(); ai != section->atoms_end(); ++ai) {
2012 _symtab->addSymbol(ai->first, section->ordinal(), ai->second.second);
Hemant Kulkarni736f7fb2012-11-21 21:07:36 +00002013 }
2014 }
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00002015}
2016
Michael J. Spencera2c97272013-01-04 21:09:21 +00002017template<support::endianness target_endianness,
2018 std::size_t max_align,
2019 bool is64Bits>
2020void ELFExecutableWriter<target_endianness, max_align, is64Bits>
2021 ::addAbsoluteUndefinedSymbols(const lld::File &file) {
Hemant Kulkarni08e410292012-10-01 23:53:20 +00002022 for (const UndefinedAtom *a : file.undefined()) {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00002023 _symtab->addSymbol(a, ELF::SHN_UNDEF);
Hemant Kulkarni08e410292012-10-01 23:53:20 +00002024 }
Michael J. Spencera2c97272013-01-04 21:09:21 +00002025
Hemant Kulkarni08e410292012-10-01 23:53:20 +00002026 for (const AbsoluteAtom *a : file.absolute()) {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00002027 _symtab->addSymbol(a, ELF::SHN_ABS);
Hemant Kulkarni08e410292012-10-01 23:53:20 +00002028 }
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00002029}
2030
Michael J. Spencera2c97272013-01-04 21:09:21 +00002031template<support::endianness target_endianness,
2032 std::size_t max_align,
2033 bool is64Bits>
2034void ELFExecutableWriter<target_endianness, max_align, is64Bits>
2035 ::buildAtomToAddressMap () {
2036 Section<target_endianness, max_align, is64Bits> *section;
2037 for (auto si = _layout->sections_begin();
Shankar Easwaran495d38b2012-12-27 02:26:30 +00002038 si != _layout->sections_end(); ++si) {
Michael J. Spencera2c97272013-01-04 21:09:21 +00002039 if ((*si)->kind() !=
2040 Chunk<target_endianness, max_align, is64Bits>::K_ELFSection)
Shankar Easwaran495d38b2012-12-27 02:26:30 +00002041 continue;
Michael J. Spencera2c97272013-01-04 21:09:21 +00002042 section =
2043 llvm::dyn_cast<Section<target_endianness, max_align, is64Bits>>(*si);
Shankar Easwaran495d38b2012-12-27 02:26:30 +00002044 for (auto ai = section->atoms_begin(); ai != section->atoms_end(); ++ai) {
2045 _atomToAddressMap[ai->first] = (ai)->second.second;
Sid Manningdd110202012-09-25 18:22:09 +00002046 }
2047 }
Sid Manningdd110202012-09-25 18:22:09 +00002048}
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00002049
Michael J. Spencera2c97272013-01-04 21:09:21 +00002050template<support::endianness target_endianness,
2051 std::size_t max_align,
2052 bool is64Bits>
2053void ELFExecutableWriter<target_endianness, max_align, is64Bits>
2054 ::buildSectionHeaderTable() {
2055 for (auto msi = _layout->merged_sections_begin();
Shankar Easwaran495d38b2012-12-27 02:26:30 +00002056 msi != _layout->merged_sections_end(); ++msi) {
Michael J. Spencera2c97272013-01-04 21:09:21 +00002057 if ((*msi)->kind() !=
2058 Chunk<target_endianness, max_align, is64Bits>::K_ELFSection)
Shankar Easwaran495d38b2012-12-27 02:26:30 +00002059 continue;
2060 if ((*msi)->hasSegment())
2061 _shdrtab->appendSection(*msi);
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00002062 }
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00002063}
2064
Michael J. Spencera2c97272013-01-04 21:09:21 +00002065template<support::endianness target_endianness,
2066 std::size_t max_align,
2067 bool is64Bits>
2068void ELFExecutableWriter<target_endianness, max_align, is64Bits>
2069 ::assignSectionsWithNoSegments() {
2070 Section<target_endianness, max_align, is64Bits> *section;
2071 for (auto msi = _layout->merged_sections_begin();
Shankar Easwaran495d38b2012-12-27 02:26:30 +00002072 msi != _layout->merged_sections_end(); ++msi) {
Michael J. Spencera2c97272013-01-04 21:09:21 +00002073 if ((*msi)->kind() !=
2074 Chunk<target_endianness, max_align, is64Bits>::K_ELFSection)
Shankar Easwaran495d38b2012-12-27 02:26:30 +00002075 continue;
2076 if (!(*msi)->hasSegment())
2077 _shdrtab->appendSection(*msi);
2078 }
2079 _layout->assignOffsetsForMiscSections();
Michael J. Spencera2c97272013-01-04 21:09:21 +00002080 for (auto si = _layout->sections_begin();
Shankar Easwaran495d38b2012-12-27 02:26:30 +00002081 si != _layout->sections_end(); ++si) {
Michael J. Spencera2c97272013-01-04 21:09:21 +00002082 if ((*si)->kind() !=
2083 Chunk<target_endianness, max_align, is64Bits>::K_ELFSection)
Shankar Easwaran495d38b2012-12-27 02:26:30 +00002084 continue;
Michael J. Spencera2c97272013-01-04 21:09:21 +00002085 section =
2086 llvm::dyn_cast<Section<target_endianness, max_align, is64Bits>>(*si);
2087 if (!DefaultELFLayout<target_endianness, max_align, is64Bits>
2088 ::hasOutputSegment(section))
Shankar Easwaran495d38b2012-12-27 02:26:30 +00002089 _shdrtab->updateSection(section);
2090 }
2091}
2092
Michael J. Spencera2c97272013-01-04 21:09:21 +00002093template<support::endianness target_endianness,
2094 std::size_t max_align,
2095 bool is64Bits>
2096error_code ELFExecutableWriter<target_endianness, max_align, is64Bits>
2097 ::writeFile(const lld::File &file, StringRef path) {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00002098 buildChunks(file);
2099 // Create the default sections like the symbol table, string table, and the
2100 // section string table
2101 createDefaultSections();
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00002102
Shankar Easwaran495d38b2012-12-27 02:26:30 +00002103 // Set the Layout
2104 _layout->assignSectionsToSegments();
2105 _layout->assignFileOffsets();
2106 _layout->assignVirtualAddress();
2107
2108 // Build the Atom To Address map for applying relocations
2109 buildAtomToAddressMap();
2110
2111 // Create symbol table and section string table
2112 buildSymbolTable();
2113
2114 // add other symbols
2115 addAbsoluteUndefinedSymbols(file);
2116
2117 // Finalize the layout by calling the finalize() functions
2118 _layout->finalize();
2119
2120 // build Section Header table
2121 buildSectionHeaderTable();
2122
2123 // assign Offsets and virtual addresses
2124 // for sections with no segments
2125 assignSectionsWithNoSegments();
2126
2127 uint64_t totalSize = _shdrtab->fileOffset() + _shdrtab->fileSize();
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00002128
2129 OwningPtr<FileOutputBuffer> buffer;
2130 error_code ec = FileOutputBuffer::create(path,
2131 totalSize, buffer,
2132 FileOutputBuffer::F_executable);
2133 if (ec)
2134 return ec;
2135
Shankar Easwaran495d38b2012-12-27 02:26:30 +00002136 for (auto si = _layout->sections_begin(); si != _layout->sections_end(); ++si)
2137 (*si)->write(this, buffer);
2138
2139 _elfHeader->e_ident(ELF::EI_CLASS, (_options.is64Bit() ? ELF::ELFCLASS64
2140 : ELF::ELFCLASS32));
Michael J. Spencera2c97272013-01-04 21:09:21 +00002141 _elfHeader->e_ident(ELF::EI_DATA, _options.endianness() == llvm::support::big
Shankar Easwaran495d38b2012-12-27 02:26:30 +00002142 ? ELF::ELFDATA2MSB : ELF::ELFDATA2LSB);
2143 _elfHeader->e_ident(ELF::EI_VERSION, 1);
2144 _elfHeader->e_ident(ELF::EI_OSABI, 0);
2145 _elfHeader->e_type(_options.type());
2146 _elfHeader->e_machine(_options.machine());
2147 _elfHeader->e_version(1);
2148 _elfHeader->e_entry(0ULL);
2149 _elfHeader->e_phoff(_programHeader->fileOffset());
2150 _elfHeader->e_shoff(_shdrtab->fileOffset());
2151 _elfHeader->e_phentsize(_programHeader->entsize());
2152 _elfHeader->e_phnum(_programHeader->numHeaders());
2153 _elfHeader->e_shentsize(_shdrtab->entsize());
2154 _elfHeader->e_shnum(_shdrtab->numHeaders());
2155 _elfHeader->e_shstrndx(_shstrtab->ordinal());
2156 uint64_t virtualAddr = 0;
2157 _layout->findAtomAddrByName("_start", virtualAddr);
2158 _elfHeader->e_entry(virtualAddr);
2159 _elfHeader->write(this, buffer);
2160 _programHeader->write(this, buffer);
2161
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00002162 return buffer->commit();
2163}
Nick Kledzikabb69812012-05-31 22:34:00 +00002164
Michael J. Spencera2c97272013-01-04 21:09:21 +00002165template<support::endianness target_endianness,
2166 std::size_t max_align,
2167 bool is64Bits>
2168void ELFExecutableWriter<target_endianness, max_align, is64Bits>
2169 ::createDefaultSections() {
2170 _elfHeader =
2171 new ELFHeader<target_endianness, max_align, is64Bits>();
2172 _programHeader =
2173 new ELFProgramHeader<target_endianness, max_align, is64Bits>();
Shankar Easwaran495d38b2012-12-27 02:26:30 +00002174 _layout->setELFHeader(_elfHeader);
2175 _layout->setProgramHeader(_programHeader);
2176
Michael J. Spencera2c97272013-01-04 21:09:21 +00002177 _symtab = new ELFSymbolTable<target_endianness, max_align, is64Bits>(
2178 ".symtab",
2179 DefaultELFLayout<target_endianness, max_align, is64Bits>
2180 ::ORDER_SYMBOL_TABLE);
2181 _strtab = new ELFStringTable<target_endianness, max_align, is64Bits>(
2182 ".strtab",
2183 DefaultELFLayout<target_endianness, max_align, is64Bits>
2184 ::ORDER_STRING_TABLE);
2185 _shstrtab = new ELFStringTable<target_endianness, max_align, is64Bits>(
2186 ".shstrtab",
2187 DefaultELFLayout<target_endianness, max_align, is64Bits>
2188 ::ORDER_SECTION_STRINGS);
2189 _shdrtab = new ELFSectionHeader<target_endianness, max_align, is64Bits>(
2190 DefaultELFLayout<target_endianness, max_align, is64Bits>
2191 ::ORDER_SECTION_HEADERS);
Shankar Easwaran495d38b2012-12-27 02:26:30 +00002192 _layout->addSection(_symtab);
2193 _layout->addSection(_strtab);
2194 _layout->addSection(_shstrtab);
2195 _shdrtab->setStringSection(_shstrtab);
2196 _symtab->setStringSection(_strtab);
2197 _layout->addSection(_shdrtab);
Sid Manningdd110202012-09-25 18:22:09 +00002198}
Nick Kledzikabb69812012-05-31 22:34:00 +00002199} // namespace elf
2200
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00002201Writer *createWriterELF(const WriterOptionsELF &options) {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00002202 // Set the default layout to be the static executable layout
Michael J. Spencera2c97272013-01-04 21:09:21 +00002203 // We would set the layout to a dynamic executable layout
Shankar Easwaran495d38b2012-12-27 02:26:30 +00002204 // if we came across any shared libraries in the process
Michael J. Spencera2c97272013-01-04 21:09:21 +00002205
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00002206 if (!options.is64Bit() && options.endianness() == llvm::support::little)
Michael J. Spencera2c97272013-01-04 21:09:21 +00002207 return new elf::ELFExecutableWriter<support::little, 4, false>(options);
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00002208 else if (options.is64Bit() && options.endianness() == llvm::support::little)
Michael J. Spencera2c97272013-01-04 21:09:21 +00002209 return new elf::ELFExecutableWriter<support::little, 8, true>(options);
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00002210 else if (!options.is64Bit() && options.endianness() == llvm::support::big)
Michael J. Spencera2c97272013-01-04 21:09:21 +00002211 return new elf::ELFExecutableWriter<support::big, 4, false>(options);
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00002212 else if (options.is64Bit() && options.endianness() == llvm::support::big)
Michael J. Spencera2c97272013-01-04 21:09:21 +00002213 return new elf::ELFExecutableWriter<support::big, 8, true>(options);
Nick Kledzikabb69812012-05-31 22:34:00 +00002214
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00002215 llvm_unreachable("Invalid Options!");
Nick Kledzikabb69812012-05-31 22:34:00 +00002216}
Nick Kledzikabb69812012-05-31 22:34:00 +00002217} // namespace lld