blob: d410da29ebf2c4a3b8db26b881dc7ae2e4adc4b3 [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",
Reid Klecknere974bd12013-01-05 02:21:42 +00001216 Chunk<target_endianness, max_align, is64Bits>::K_ELFProgramHeader) {
1217 resetProgramHeaders();
1218 }
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001219
Michael J. Spencera2c97272013-01-04 21:09:21 +00001220 bool addSegment(Segment<target_endianness, max_align, is64Bits> *segment) {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001221 Elf_Phdr *phdr = nullptr;
1222 bool ret = false;
1223
Michael J. Spencera2c97272013-01-04 21:09:21 +00001224 for (auto sei = segment->slices_begin(), see = segment->slices_end();
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001225 sei != see; ++sei) {
1226 if (_phi == _ph.end()) {
1227 phdr = new(_allocator.Allocate<Elf_Phdr>()) Elf_Phdr;
1228 _ph.push_back(phdr);
1229 _phi = _ph.end();
1230 ret = true;
1231 } else {
1232 phdr = (*_phi);
1233 ++_phi;
1234 }
1235 phdr->p_type = segment->segmentType();
1236 phdr->p_offset = (*sei)->fileOffset();
1237 phdr->p_vaddr = (*sei)->virtualAddr();
1238 phdr->p_paddr = (*sei)->virtualAddr();
1239 phdr->p_filesz = (*sei)->fileSize();
1240 phdr->p_memsz = (*sei)->memSize();
1241 phdr->p_flags = segment->flags();
Michael J. Spencera2c97272013-01-04 21:09:21 +00001242 phdr->p_align = (phdr->p_type == llvm::ELF::PT_LOAD) ?
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001243 segment->pageSize() : (*sei)->align2();
1244 }
1245 return ret;
1246 }
1247
1248 void resetProgramHeaders() {
Michael J. Spencera2c97272013-01-04 21:09:21 +00001249 _phi = _ph.begin();
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001250 }
1251
1252 void setVAddr(uint64_t addr) {
1253 this->_start = llvm::RoundUpToAlignment(addr, 8);
1254 this->_fsize = this->_start - addr;
1255 }
1256
Michael J. Spencera2c97272013-01-04 21:09:21 +00001257 uint64_t fileSize() {
1258 return this->_fsize + (sizeof (Elf_Phdr) * _ph.size());
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001259 }
1260
Michael J. Spencera2c97272013-01-04 21:09:21 +00001261 static inline bool classof(
1262 const Chunk<target_endianness, max_align, is64Bits> *c) {
1263 return c->Kind() ==
1264 Chunk<target_endianness, max_align, is64Bits>::K_ELFProgramHeader;
1265 }
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001266
Michael J. Spencera2c97272013-01-04 21:09:21 +00001267 void write(ELFWriter *writer,
1268 OwningPtr<FileOutputBuffer> &buffer) {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001269 uint8_t *chunkBuffer = buffer->getBufferStart();
1270 uint8_t *dest = chunkBuffer + this->fileOffset();
1271 for (auto phi : _ph) {
1272 memcpy(dest, phi, sizeof(Elf_Phdr));
1273 dest += sizeof(Elf_Phdr);
1274 }
1275 }
1276
1277 void finalize() { }
1278
Michael J. Spencera2c97272013-01-04 21:09:21 +00001279 int64_t entsize() {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001280 return sizeof(Elf_Phdr);
1281 }
1282
1283 int64_t numHeaders() {
1284 return _ph.size();
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001285 }
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001286
1287private:
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001288 std::vector<Elf_Phdr *> _ph;
1289 typedef typename std::vector<Elf_Phdr *>::iterator ph_iter;
1290 ph_iter _phi;
1291 llvm::BumpPtrAllocator _allocator;
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001292};
1293
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001294/// \brief An ELFSectionHeader represents the Elf[32/64]_Shdr structure
1295/// at the end of the file
Michael J. Spencera2c97272013-01-04 21:09:21 +00001296template<support::endianness target_endianness,
1297 std::size_t max_align,
1298 bool is64Bits>
1299class ELFSectionHeader : public Chunk<target_endianness, max_align, is64Bits> {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001300public:
Michael J. Spencera2c97272013-01-04 21:09:21 +00001301 typedef Elf_Shdr_Impl<target_endianness, max_align, is64Bits> Elf_Shdr;
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001302
Michael J. Spencera2c97272013-01-04 21:09:21 +00001303 ELFSectionHeader(int32_t order)
1304 : Chunk<target_endianness, max_align, is64Bits>(
1305 "shdr",
1306 Chunk<target_endianness, max_align, is64Bits>::K_ELFSectionHeader) {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001307 this->_fsize = 0;
1308 this->_align2 = 8;
1309 this->setOrder(order);
1310 // The first element in the list is always NULL
1311 Elf_Shdr *nullshdr = new (_sectionAllocate.Allocate<Elf_Shdr>()) Elf_Shdr;
1312 ::memset(nullshdr, 0, sizeof (Elf_Shdr));
1313 _sectionInfo.push_back(nullshdr);
1314 this->_fsize += sizeof (Elf_Shdr);
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001315 }
1316
Michael J. Spencera2c97272013-01-04 21:09:21 +00001317 uint16_t fileSize() {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001318 return sizeof(Elf_Shdr) * _sectionInfo.size();
Hemant Kulkarni08e410292012-10-01 23:53:20 +00001319 }
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001320
Michael J. Spencera2c97272013-01-04 21:09:21 +00001321 void appendSection(
1322 MergedSections<target_endianness, max_align, is64Bits> *section) {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001323 Elf_Shdr *shdr = new (_sectionAllocate.Allocate<Elf_Shdr>()) Elf_Shdr;
1324 shdr->sh_name = _stringSection->addString(section->name());
1325 shdr->sh_type = section->type();
1326 shdr->sh_flags = section->flags();
1327 shdr->sh_offset = section->fileOffset();
1328 shdr->sh_addr = section->virtualAddr();
1329 shdr->sh_size = section->memSize();
1330 shdr->sh_link = section->link();
1331 shdr->sh_info = section->shinfo();
1332 shdr->sh_addralign = section->align2();
1333 shdr->sh_entsize = section->entsize();
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001334 _sectionInfo.push_back(shdr);
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001335 }
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001336
Michael J. Spencera2c97272013-01-04 21:09:21 +00001337 void updateSection(Section<target_endianness, max_align, is64Bits> *section) {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001338 Elf_Shdr *shdr = _sectionInfo[section->ordinal()];
1339 shdr->sh_type = section->type();
1340 shdr->sh_flags = section->flags();
1341 shdr->sh_offset = section->fileOffset();
1342 shdr->sh_addr = section->virtualAddr();
1343 shdr->sh_size = section->fileSize();
1344 shdr->sh_link = section->link();
1345 shdr->sh_info = section->shinfo();
1346 shdr->sh_addralign = section->align2();
1347 shdr->sh_entsize = section->entsize();
1348 }
1349
Michael J. Spencera2c97272013-01-04 21:09:21 +00001350 static inline bool classof(
1351 const Chunk<target_endianness, max_align, is64Bits> *c) {
1352 return c->getChunkKind() ==
1353 Chunk<target_endianness, max_align, is64Bits>::K_ELFSectionHeader;
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001354 }
1355
Michael J. Spencera2c97272013-01-04 21:09:21 +00001356 void setStringSection(
1357 ELFStringTable<target_endianness, max_align, is64Bits> *s) {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001358 _stringSection = s;
1359 }
1360
Michael J. Spencera2c97272013-01-04 21:09:21 +00001361 void write(ELFWriter *writer,
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001362 OwningPtr<FileOutputBuffer> &buffer) {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001363 uint8_t *chunkBuffer = buffer->getBufferStart();
1364 uint8_t *dest = chunkBuffer + this->fileOffset();
1365 for (auto shi : _sectionInfo) {
1366 memcpy(dest, shi, sizeof(Elf_Shdr));
1367 dest += sizeof(Elf_Shdr);
1368 }
1369 _stringSection->write(writer, buffer);
1370 }
1371
1372 void finalize() { }
1373
Michael J. Spencera2c97272013-01-04 21:09:21 +00001374 int64_t entsize() {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001375 return sizeof(Elf_Shdr);
1376 }
1377
1378 int64_t numHeaders() {
1379 return _sectionInfo.size();
1380 }
1381
1382private:
Michael J. Spencera2c97272013-01-04 21:09:21 +00001383 ELFStringTable<target_endianness, max_align, is64Bits> *_stringSection;
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001384 std::vector<Elf_Shdr*> _sectionInfo;
1385 llvm::BumpPtrAllocator _sectionAllocate;
1386};
1387
Michael J. Spencera2c97272013-01-04 21:09:21 +00001388/// \brief The DefaultELFLayout class is used by the Writer to arrange
1389/// sections and segments in the order determined by the target ELF
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001390/// format. The writer creates a single instance of the DefaultELFLayout
Michael J. Spencera2c97272013-01-04 21:09:21 +00001391/// class
1392template<support::endianness target_endianness,
1393 std::size_t max_align,
1394 bool is64Bits>
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001395class DefaultELFLayout : public ELFLayout {
1396public:
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001397
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001398 // The order in which the sections appear in the output file
Michael J. Spencera2c97272013-01-04 21:09:21 +00001399 // If its determined, that the layout needs to change
1400 // just changing the order of enumerations would essentially
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001401 // change the layout in the output file
1402 enum DefaultSectionOrder {
1403 ORDER_NOT_DEFINED = 0,
1404 ORDER_INTERP,
1405 ORDER_NOTE,
1406 ORDER_HASH,
1407 ORDER_DYNAMIC_SYMBOLS,
1408 ORDER_DYNAMIC_STRINGS,
1409 ORDER_INIT,
1410 ORDER_TEXT,
1411 ORDER_PLT,
1412 ORDER_FINI,
1413 ORDER_RODATA,
1414 ORDER_EH_FRAME,
1415 ORDER_EH_FRAMEHDR,
1416 ORDER_CTORS,
1417 ORDER_DTORS,
1418 ORDER_DYNAMIC,
1419 ORDER_GOT,
1420 ORDER_GOT_PLT,
1421 ORDER_DATA,
1422 ORDER_BSS,
1423 ORDER_OTHER,
1424 ORDER_SECTION_STRINGS,
1425 ORDER_SYMBOL_TABLE,
1426 ORDER_STRING_TABLE,
1427 ORDER_SECTION_HEADERS
1428 };
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001429
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001430public:
1431
1432 // The Key used for creating Sections
Michael J. Spencera2c97272013-01-04 21:09:21 +00001433 // The sections are created using
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001434 // SectionName, [contentType, contentPermissions]
Michael J. Spencera2c97272013-01-04 21:09:21 +00001435 typedef std::pair<StringRef,
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001436 std::pair<int32_t, int32_t>> Key;
Michael J. Spencera2c97272013-01-04 21:09:21 +00001437 typedef typename std::vector<
1438 Chunk<target_endianness, max_align, is64Bits> *>::iterator ChunkIter;
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001439 // The key used for Segments
Michael J. Spencera2c97272013-01-04 21:09:21 +00001440 // The segments are created using
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001441 // SegmentName, Segment flags
1442 typedef std::pair<StringRef, int64_t> SegmentKey;
1443 // Merged Sections contain the map of Sectionnames to a vector of sections,
1444 // that have been merged to form a single section
Michael J. Spencera2c97272013-01-04 21:09:21 +00001445 typedef std::map<StringRef, MergedSections<
1446 target_endianness, max_align, is64Bits> *> MergedSectionMapT;
1447 typedef typename std::vector<MergedSections<
1448 target_endianness, max_align, is64Bits> *>::iterator MergedSectionIter;
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001449
1450 // HashKey for the Section
1451 class HashKey {
1452 public:
1453 int64_t operator() (const Key &k) const {
1454 // k.first = section Name
1455 // k.second = [contentType, Permissions]
1456 return llvm::hash_combine(k.first, k.second.first, k.second.second);
1457 }
1458 };
1459
1460 // HashKey for the Segment
1461 class SegmentHashKey {
1462 public:
1463 int64_t operator() (const SegmentKey &k) const {
1464 // k.first = SegmentName
1465 // k.second = SegmentFlags
1466 return llvm::hash_combine(k.first, k.second);
1467 }
1468 };
1469
Michael J. Spencera2c97272013-01-04 21:09:21 +00001470 typedef std::unordered_map<Key, Section<
1471 target_endianness, max_align, is64Bits>*, HashKey> SectionMapT;
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001472 typedef std::unordered_map<SegmentKey,
Michael J. Spencera2c97272013-01-04 21:09:21 +00001473 Segment<target_endianness, max_align, is64Bits>*,
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001474 SegmentHashKey> SegmentMapT;
1475
1476 DefaultELFLayout(const WriterOptionsELF &options):_options(options) { }
1477
1478 /// \brief Return the section order for a input section
1479 virtual SectionOrder getSectionOrder
1480 (const StringRef name,
1481 int32_t contentType,
1482 int32_t contentPermissions) {
1483 switch (contentType) {
1484 case DefinedAtom::typeCode:
1485 return llvm::StringSwitch<Reference::Kind>(name)
1486 .StartsWith(".eh_frame_hdr", ORDER_EH_FRAMEHDR)
1487 .StartsWith(".eh_frame", ORDER_EH_FRAME)
1488 .StartsWith(".init", ORDER_INIT)
1489 .StartsWith(".fini", ORDER_FINI)
1490 .StartsWith(".hash", ORDER_HASH)
1491 .Default(ORDER_TEXT);
1492
1493 case DefinedAtom::typeConstant:
Michael J. Spencera2c97272013-01-04 21:09:21 +00001494 return ORDER_RODATA;
1495
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001496 case DefinedAtom::typeData:
1497 return ORDER_DATA;
Michael J. Spencera2c97272013-01-04 21:09:21 +00001498
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001499 case DefinedAtom::typeZeroFill:
1500 return ORDER_BSS;
1501
1502 default:
1503 // If we get passed in a section push it to OTHER
Michael J. Spencera2c97272013-01-04 21:09:21 +00001504 if (contentPermissions == DefinedAtom::perm___)
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001505 return ORDER_OTHER;
Michael J. Spencera2c97272013-01-04 21:09:21 +00001506
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001507 return ORDER_NOT_DEFINED;
1508 }
1509 }
1510
1511 /// \brief This maps the input sections to the output section names
1512 StringRef getSectionName(const StringRef name,
1513 const int32_t contentType) {
Michael J. Spencera2c97272013-01-04 21:09:21 +00001514 if (contentType == DefinedAtom::typeZeroFill)
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001515 return ".bss";
Michael J. Spencera2c97272013-01-04 21:09:21 +00001516 if (name.startswith(".text"))
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001517 return ".text";
Michael J. Spencera2c97272013-01-04 21:09:21 +00001518 if (name.startswith(".rodata"))
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001519 return ".rodata";
1520 return name;
1521 }
1522
1523 /// \brief Gets the segment for a output section
Michael J. Spencera2c97272013-01-04 21:09:21 +00001524 virtual ELFLayout::SegmentType getSegmentType(
1525 Section<target_endianness, max_align, is64Bits> *section) const {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001526 switch(section->order()) {
1527 case ORDER_INTERP:
1528 return llvm::ELF::PT_INTERP;
1529
1530 case ORDER_TEXT:
1531 case ORDER_HASH:
1532 case ORDER_DYNAMIC_SYMBOLS:
1533 case ORDER_DYNAMIC_STRINGS:
1534 case ORDER_INIT:
1535 case ORDER_PLT:
1536 case ORDER_FINI:
1537 case ORDER_RODATA:
1538 case ORDER_EH_FRAME:
1539 case ORDER_EH_FRAMEHDR:
1540 return llvm::ELF::PT_LOAD;
1541
1542 case ORDER_NOTE:
1543 return llvm::ELF::PT_NOTE;
1544
1545 case ORDER_DYNAMIC:
1546 return llvm::ELF::PT_DYNAMIC;
1547
1548 case ORDER_CTORS:
1549 case ORDER_DTORS:
1550 case ORDER_GOT:
1551 return llvm::ELF::PT_GNU_RELRO;
1552
1553 case ORDER_GOT_PLT:
1554 case ORDER_DATA:
1555 case ORDER_BSS:
1556 return llvm::ELF::PT_LOAD;
1557
1558 default:
1559 return llvm::ELF::PT_NULL;
1560 }
1561 }
1562
1563 /// \brief Returns true/false depending on whether the section has a Output
1564 // segment or not
Michael J. Spencera2c97272013-01-04 21:09:21 +00001565 static bool hasOutputSegment(Section<target_endianness, max_align,
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001566 is64Bits> *section) {
1567 switch(section->order()) {
1568 case ORDER_INTERP:
1569 case ORDER_HASH:
1570 case ORDER_DYNAMIC_SYMBOLS:
1571 case ORDER_DYNAMIC_STRINGS:
1572 case ORDER_INIT:
1573 case ORDER_PLT:
1574 case ORDER_TEXT:
1575 case ORDER_FINI:
1576 case ORDER_RODATA:
1577 case ORDER_EH_FRAME:
1578 case ORDER_EH_FRAMEHDR:
1579 case ORDER_NOTE:
1580 case ORDER_DYNAMIC:
1581 case ORDER_CTORS:
1582 case ORDER_DTORS:
1583 case ORDER_GOT:
1584 case ORDER_GOT_PLT:
1585 case ORDER_DATA:
1586 case ORDER_BSS:
1587 return true;
1588
1589 default:
1590 return false;
1591 }
1592 }
1593
1594 // Adds an atom to the section
1595 virtual error_code addAtom(const Atom *atom) {
1596 const DefinedAtom *definedAtom = dyn_cast<DefinedAtom>(atom);
Michael J. Spencera2c97272013-01-04 21:09:21 +00001597 const StringRef sectionName =
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001598 getSectionName(definedAtom->customSectionName(),
1599 definedAtom->contentType());
Michael J. Spencera2c97272013-01-04 21:09:21 +00001600 const lld::DefinedAtom::ContentPermissions permissions =
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001601 definedAtom->permissions();
Michael J. Spencera2c97272013-01-04 21:09:21 +00001602 const lld::DefinedAtom::ContentType contentType =
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001603 definedAtom->contentType();
1604 const Key key(sectionName, std::make_pair(contentType, permissions));
Michael J. Spencera2c97272013-01-04 21:09:21 +00001605 const std::pair<Key, Section<target_endianness, max_align, is64Bits> *>
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001606 currentSection(key, nullptr);
Michael J. Spencera2c97272013-01-04 21:09:21 +00001607 std::pair<typename SectionMapT::iterator, bool>
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001608 sectionInsert(_sectionMap.insert(currentSection));
Michael J. Spencera2c97272013-01-04 21:09:21 +00001609 Section<target_endianness, max_align, is64Bits> *section;
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001610 // the section is already in the map
1611 if (!sectionInsert.second) {
1612 section = sectionInsert.first->second;
1613 section->setContentPermissions(permissions);
1614 }
1615 else {
1616 SectionOrder section_order = getSectionOrder(sectionName,
1617 contentType,
1618 permissions);
1619 section = new (_allocator.Allocate
Michael J. Spencera2c97272013-01-04 21:09:21 +00001620 <Section<target_endianness, max_align, is64Bits>>())
1621 Section<target_endianness, max_align, is64Bits>
1622 (sectionName, contentType,
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001623 permissions, section_order);
1624 sectionInsert.first->second = section;
1625 section->setOrder(section_order);
1626 _sections.push_back(section);
1627 }
1628 section->appendAtom(atom);
1629 return error_code::success();
1630 }
1631
1632 // Merge sections with the same name into a MergedSections
1633 void mergeSimiliarSections() {
Michael J. Spencera2c97272013-01-04 21:09:21 +00001634 MergedSections<target_endianness, max_align, is64Bits> *mergedSection;
1635
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001636 for (auto &si : _sections) {
Michael J. Spencera2c97272013-01-04 21:09:21 +00001637 const std::pair<StringRef,
1638 MergedSections<target_endianness, max_align, is64Bits> *>
1639 currentMergedSections(si->name(), nullptr);
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001640 std::pair<typename MergedSectionMapT::iterator, bool>
1641 mergedSectionInsert
1642 (_mergedSectionMap.insert(currentMergedSections));
1643 if (!mergedSectionInsert.second) {
1644 mergedSection = mergedSectionInsert.first->second;
1645 }
1646 else {
Michael J. Spencera2c97272013-01-04 21:09:21 +00001647 mergedSection = new (_allocator.Allocate<
1648 MergedSections<target_endianness, max_align, is64Bits>>())
1649 MergedSections<target_endianness, max_align, is64Bits>(si->name());
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001650 _mergedSections.push_back(mergedSection);
1651 mergedSectionInsert.first->second = mergedSection;
1652 }
1653 mergedSection->appendSection(si);
1654 }
1655 }
1656
1657 void assignSectionsToSegments() {
1658 // sort the sections by their order as defined by the layout
1659 std::stable_sort(_sections.begin(), _sections.end(),
Michael J. Spencera2c97272013-01-04 21:09:21 +00001660 [](Chunk<target_endianness, max_align, is64Bits> *A,
1661 Chunk<target_endianness, max_align, is64Bits> *B) {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001662 return A->order() < B->order();
1663 });
1664 // Merge all sections
1665 mergeSimiliarSections();
1666 // Set the ordinal after sorting the sections
1667 int ordinal = 1;
1668 for (auto &msi : _mergedSections) {
1669 (*msi).setOrdinal(ordinal);
1670 for (auto ai = (*msi).begin_sections(), ae = (*msi).end_sections();
1671 ai != ae; ++ai) {
1672 (*ai)->setOrdinal(ordinal);
1673 }
1674 ++ordinal;
1675 }
Michael J. Spencera2c97272013-01-04 21:09:21 +00001676 Section<target_endianness, max_align, is64Bits> *section;
1677 Segment<target_endianness, max_align, is64Bits> *segment;
1678 for (auto msi = merged_sections_begin(), mse = merged_sections_end();
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001679 msi != mse; ++msi) {
Michael J. Spencera2c97272013-01-04 21:09:21 +00001680 for (auto ai = (*msi)->begin_sections(), ae = (*msi)->end_sections();
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001681 ai != ae; ++ai) {
Michael J. Spencera2c97272013-01-04 21:09:21 +00001682 if ((*ai)->kind() ==
1683 Chunk<target_endianness, max_align, is64Bits>::K_ELFSection) {
1684 section = llvm::dyn_cast<
1685 Section<target_endianness, max_align, is64Bits>>(*ai);
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001686 if (!hasOutputSegment(section))
1687 continue;
1688 (*msi)->setHasSegment();
1689 section->setSegment(getSegmentType(section));
1690 const StringRef segmentName = section->segmentKindToStr();
1691 // Use the flags of the merged Section for the segment
1692 const SegmentKey key(segmentName, (*msi)->flags());
Michael J. Spencera2c97272013-01-04 21:09:21 +00001693 const std::pair<SegmentKey,
1694 Segment<target_endianness, max_align, is64Bits> *>
1695 currentSegment(key, nullptr);
1696 std::pair<typename SegmentMapT::iterator, bool>
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001697 segmentInsert(_segmentMap.insert(currentSegment));
1698
1699 if (!segmentInsert.second) {
1700 segment = segmentInsert.first->second;
1701 } else {
1702 segment = new (_allocator.Allocate
Michael J. Spencera2c97272013-01-04 21:09:21 +00001703 <Segment<target_endianness, max_align, is64Bits>>())
1704 Segment<target_endianness, max_align, is64Bits>
1705 (segmentName, getSegmentType(section),
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001706 _options);
1707 segmentInsert.first->second = segment;
1708 _segments.push_back(segment);
1709 }
1710 segment->append(section);
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001711 }
1712 }
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001713 }
1714 }
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001715
Michael J. Spencera2c97272013-01-04 21:09:21 +00001716 void addSection(Chunk<target_endianness, max_align, is64Bits> *c) {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001717 _sections.push_back(c);
1718 }
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001719
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001720 void assignFileOffsets() {
Michael J. Spencera2c97272013-01-04 21:09:21 +00001721 std::sort(_segments.begin(),
1722 _segments.end(),
1723 Segment<target_endianness, max_align, is64Bits>::compareSegments);
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001724 int ordinal = 0;
1725 // Compute the number of segments that might be needed, so that the
1726 // size of the program header can be computed
1727 uint64_t offset = 0;
1728 for (auto si : _segments) {
1729 si->setOrdinal(++ordinal);
1730 si->assignOffsets(offset);
1731 offset += si->fileSize();
1732 }
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001733 }
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001734
Michael J. Spencera2c97272013-01-04 21:09:21 +00001735 void setELFHeader(ELFHeader<target_endianness, max_align, is64Bits> *e) {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001736 _elfHeader = e;
1737 }
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001738
Michael J. Spencera2c97272013-01-04 21:09:21 +00001739 void setProgramHeader(
1740 ELFProgramHeader<target_endianness, max_align, is64Bits> *p) {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001741 _programHeader = p;
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001742 }
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001743
1744 void assignVirtualAddress() {
1745 int32_t numSlices = 0;
1746 uint64_t virtualAddress = _options.baseAddress();
1747
1748 // Add the ELF Header
1749 if (_elfHeader) {
1750 _elfHeader->setFileOffset(0);
1751 _elfHeader->setVAddr(virtualAddress);
1752 }
1753 // Add the program header
1754 if (_programHeader) {
Michael J. Spencera2c97272013-01-04 21:09:21 +00001755 _programHeader->setVAddr(
1756 uint64_t(virtualAddress + _elfHeader->fileSize()));
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001757 _programHeader->setFileOffset(_elfHeader->fileSize());
1758 }
1759 bool newSegmentHeaderAdded = true;
Michael J. Spencer5adebbd2013-01-05 00:46:23 +00001760 while (true && !_segments.empty()) {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001761 for (auto si : _segments) {
1762 newSegmentHeaderAdded = _programHeader->addSegment(si);
1763 numSlices += si->numSlices();
1764 }
Michael J. Spencera2c97272013-01-04 21:09:21 +00001765 if (!newSegmentHeaderAdded)
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001766 break;
1767 uint64_t fileoffset = _elfHeader->fileSize() + _programHeader->fileSize();
1768 uint64_t address = virtualAddress;
1769 // Fix the offsets after adding the program header
1770 for (auto &si : _segments) {
1771 // Align the segment to a page boundary
1772 fileoffset = llvm::RoundUpToAlignment(fileoffset, _options.pageSize());
1773 si->assignOffsets(fileoffset);
1774 fileoffset = si->fileOffset() + si->fileSize();
1775 }
1776 // start assigning virtual addresses
1777 for (auto si = _segments.begin(); si != _segments.end(); ++si) {
1778 (*si)->setVAddr(virtualAddress);
1779 // The first segment has the virtualAddress set to the base address as
1780 // we have added the file header and the program header dont align the
Michael J. Spencera2c97272013-01-04 21:09:21 +00001781 // first segment to the pagesize
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001782 (*si)->assignVirtualAddress(address, (si == _segments.begin()));
1783 (*si)->setMemSize(address - virtualAddress);
1784 virtualAddress = llvm::RoundUpToAlignment(address, _options.pageSize());
1785 }
1786 _programHeader->resetProgramHeaders();
1787 }
Michael J. Spencera2c97272013-01-04 21:09:21 +00001788 Section<target_endianness, max_align, is64Bits> *section;
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001789 // Fix the offsets of all the atoms within a section
1790 for (auto &si : _sections) {
Michael J. Spencera2c97272013-01-04 21:09:21 +00001791 section =
1792 llvm::dyn_cast<Section<target_endianness, max_align, is64Bits>>(si);
1793 if (section &&
1794 DefaultELFLayout<target_endianness,
1795 max_align, is64Bits>::hasOutputSegment(section))
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001796 section->assignOffsets(section->fileOffset());
1797 }
1798 // Set the size of the merged Sections
Michael J. Spencera2c97272013-01-04 21:09:21 +00001799 for (auto msi = merged_sections_begin(), mse = merged_sections_end();
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001800 msi != mse; ++msi) {
1801 uint64_t sectionfileoffset = 0;
1802 uint64_t startFileOffset = 0;
1803 uint64_t sectionsize = 0;
1804 bool isFirstSection = true;
Michael J. Spencera2c97272013-01-04 21:09:21 +00001805 for (auto si = (*msi)->begin_sections(); si != (*msi)->end_sections();
1806 ++si) {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001807 if (isFirstSection) {
1808 startFileOffset = (*si)->fileOffset();
1809 isFirstSection = false;
1810 }
1811 sectionfileoffset = (*si)->fileOffset();
1812 sectionsize = (*si)->fileSize();
1813 }
1814 sectionsize = (sectionfileoffset - startFileOffset) + sectionsize;
1815 (*msi)->setFileOffset(startFileOffset);
1816 (*msi)->setSize(sectionsize);
1817 }
1818 // Set the virtual addr of the merged Sections
Michael J. Spencera2c97272013-01-04 21:09:21 +00001819 for (auto msi = merged_sections_begin(), mse = merged_sections_end();
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001820 msi != mse; ++msi) {
1821 uint64_t sectionstartaddr = 0;
1822 uint64_t startaddr = 0;
1823 uint64_t sectionsize = 0;
1824 bool isFirstSection = true;
Michael J. Spencera2c97272013-01-04 21:09:21 +00001825 for (auto si = (*msi)->begin_sections(), se = (*msi)->end_sections();
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001826 si != se; ++si) {
1827 if (isFirstSection) {
1828 startaddr = (*si)->virtualAddr();
1829 isFirstSection = false;
1830 }
1831 sectionstartaddr = (*si)->virtualAddr();
1832 sectionsize = (*si)->memSize();
1833 }
1834 sectionsize = (sectionstartaddr - startaddr) + sectionsize;
1835 (*msi)->setMemSize(sectionsize);
1836 (*msi)->setAddr(startaddr);
1837 }
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001838 }
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001839
1840 void assignOffsetsForMiscSections() {
1841 uint64_t fileoffset = 0;
1842 uint64_t size = 0;
1843 for (auto si : _segments) {
1844 fileoffset = si->fileOffset();
1845 size = si->fileSize();
1846 }
1847 fileoffset = fileoffset + size;
Michael J. Spencera2c97272013-01-04 21:09:21 +00001848 Section<target_endianness, max_align, is64Bits> *section;
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001849 for (auto si : _sections) {
Michael J. Spencera2c97272013-01-04 21:09:21 +00001850 section =
1851 llvm::dyn_cast<Section<target_endianness, max_align, is64Bits>>(si);
1852 if (section &&
1853 DefaultELFLayout<target_endianness,
1854 max_align, is64Bits>::hasOutputSegment(section))
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001855 continue;
1856 fileoffset = llvm::RoundUpToAlignment(fileoffset, si->align2());
1857 si->setFileOffset(fileoffset);
1858 si->setVAddr(0);
1859 fileoffset += si->fileSize();
1860 }
Hemant Kulkarni08e410292012-10-01 23:53:20 +00001861 }
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001862
1863 void finalize() {
1864 for (auto &si : _sections) {
1865 si->finalize();
1866 }
1867 }
1868
1869 bool findAtomAddrByName(const StringRef name, uint64_t &addr) {
Michael J. Spencera2c97272013-01-04 21:09:21 +00001870 Section<target_endianness, max_align, is64Bits> *section;
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001871 for (auto ai = _sections.begin(); ai != _sections.end(); ++ai) {
Michael J. Spencera2c97272013-01-04 21:09:21 +00001872 if ((*ai)->kind() ==
1873 Chunk<target_endianness, max_align, is64Bits>::K_ELFSection) {
1874 section =
1875 llvm::dyn_cast<Section<target_endianness, max_align, is64Bits>>(*ai);
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001876 if (section->findAtomAddrByName(name, addr))
1877 return true;
1878 }
1879 }
Michael J. Spencera2c97272013-01-04 21:09:21 +00001880 return false;
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001881 }
1882
Michael J. Spencera2c97272013-01-04 21:09:21 +00001883 MergedSectionIter merged_sections_begin() {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001884 return _mergedSections.begin();
1885 }
1886
Michael J. Spencera2c97272013-01-04 21:09:21 +00001887 MergedSectionIter merged_sections_end() {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001888 return _mergedSections.end();
1889 }
1890
1891 ChunkIter sections_begin() {
1892 return _sections.begin();
1893 }
1894 ChunkIter sections_end() {
1895 return _sections.end();
1896 }
1897
1898 ChunkIter segments_begin() {
1899 return _segments.begin();
1900 }
1901
1902 ChunkIter segments_end() {
1903 return _segments.end();
1904 }
1905
Michael J. Spencera2c97272013-01-04 21:09:21 +00001906 ELFHeader<target_endianness, max_align, is64Bits> *elfHeader() {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001907 return _elfHeader;
1908 }
1909
Michael J. Spencera2c97272013-01-04 21:09:21 +00001910 ELFProgramHeader<target_endianness, max_align, is64Bits> *elfProgramHeader() {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001911 return _programHeader;
Hemant Kulkarni08e410292012-10-01 23:53:20 +00001912 }
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001913
1914private:
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001915 SectionMapT _sectionMap;
1916 MergedSectionMapT _mergedSectionMap;
1917 SegmentMapT _segmentMap;
Sid Manningdd110202012-09-25 18:22:09 +00001918
Michael J. Spencera2c97272013-01-04 21:09:21 +00001919 std::vector<Chunk<target_endianness, max_align, is64Bits> *> _sections;
1920 std::vector<Segment<target_endianness, max_align, is64Bits> *> _segments;
1921 std::vector<MergedSections<target_endianness, max_align, is64Bits> *>
1922 _mergedSections;
1923 ELFHeader<target_endianness, max_align, is64Bits> *_elfHeader;
1924 ELFProgramHeader<target_endianness, max_align, is64Bits> *_programHeader;
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001925 llvm::BumpPtrAllocator _allocator;
1926 const WriterOptionsELF &_options;
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001927};
1928
1929//===----------------------------------------------------------------------===//
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001930// ELFExecutableWriter Class
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001931//===----------------------------------------------------------------------===//
Michael J. Spencera2c97272013-01-04 21:09:21 +00001932template<support::endianness target_endianness,
1933 std::size_t max_align,
1934 bool is64Bits>
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001935class ELFExecutableWriter : public ELFWriter {
1936public:
Michael J. Spencera2c97272013-01-04 21:09:21 +00001937 typedef Elf_Shdr_Impl<target_endianness, max_align, is64Bits> Elf_Shdr;
1938 typedef Elf_Sym_Impl<target_endianness, max_align, is64Bits> Elf_Sym;
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001939
1940 ELFExecutableWriter(const WriterOptionsELF &options);
1941
1942private:
Michael J. Spencera2c97272013-01-04 21:09:21 +00001943 // build the sections that need to be created
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001944 void buildChunks(const lld::File &file);
1945 virtual error_code writeFile(const lld::File &File, StringRef path);
1946 void buildAtomToAddressMap();
1947 void buildSymbolTable ();
1948 void buildSectionHeaderTable();
1949 void assignSectionsWithNoSegments();
1950 void addAbsoluteUndefinedSymbols(const lld::File &File);
1951
Michael J. Spencera2c97272013-01-04 21:09:21 +00001952 uint64_t addressOfAtom(const Atom *atom) {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001953 return _atomToAddressMap[atom];
1954 }
1955
1956 KindHandler *kindHandler() { return _referenceKindHandler.get(); }
1957
1958 void createDefaultSections();
1959
1960 const WriterOptionsELF &_options;
1961
1962 typedef llvm::DenseMap<const Atom*, uint64_t> AtomToAddress;
1963 std::unique_ptr<KindHandler> _referenceKindHandler;
1964 AtomToAddress _atomToAddressMap;
1965 llvm::BumpPtrAllocator _chunkAllocate;
Michael J. Spencera2c97272013-01-04 21:09:21 +00001966 DefaultELFLayout<target_endianness, max_align, is64Bits> *_layout;
1967 ELFHeader<target_endianness, max_align, is64Bits> *_elfHeader;
1968 ELFProgramHeader<target_endianness, max_align, is64Bits> *_programHeader;
1969 ELFSymbolTable<target_endianness, max_align, is64Bits> * _symtab;
1970 ELFStringTable<target_endianness, max_align, is64Bits> *_strtab;
1971 ELFStringTable<target_endianness, max_align, is64Bits> *_shstrtab;
1972 ELFSectionHeader<target_endianness, max_align, is64Bits> *_shdrtab;
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001973};
1974
1975//===----------------------------------------------------------------------===//
1976// ELFExecutableWriter
1977//===----------------------------------------------------------------------===//
Michael J. Spencera2c97272013-01-04 21:09:21 +00001978template<support::endianness target_endianness,
1979 std::size_t max_align,
1980 bool is64Bits>
1981ELFExecutableWriter<target_endianness, max_align, is64Bits>
1982 ::ELFExecutableWriter(const WriterOptionsELF &options)
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001983 : _options(options)
Sid Manning42064e52012-10-09 02:20:47 +00001984 , _referenceKindHandler(KindHandler::makeHandler(_options.machine(),
Michael J. Spencera2c97272013-01-04 21:09:21 +00001985 target_endianness)) {
1986 _layout =
1987 new DefaultELFLayout<target_endianness, max_align, is64Bits>(options);
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001988}
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001989
Michael J. Spencera2c97272013-01-04 21:09:21 +00001990template<support::endianness target_endianness,
1991 std::size_t max_align,
1992 bool is64Bits>
1993void ELFExecutableWriter<target_endianness, max_align, is64Bits>
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001994 ::buildChunks(const lld::File &file){
1995 for (const DefinedAtom *definedAtom : file.defined() ) {
1996 _layout->addAtom(definedAtom);
1997 }
1998}
1999
Michael J. Spencera2c97272013-01-04 21:09:21 +00002000template<support::endianness target_endianness,
2001 std::size_t max_align,
2002 bool is64Bits>
2003void ELFExecutableWriter<target_endianness, max_align, is64Bits>
2004 ::buildSymbolTable () {
2005 Section<target_endianness, max_align, is64Bits> *section;
2006 for (auto si = _layout->sections_begin(); si != _layout->sections_end();
2007 ++si) {
2008 if ((*si)->kind() !=
2009 Chunk<target_endianness, max_align, is64Bits>::K_ELFSection)
Shankar Easwaran495d38b2012-12-27 02:26:30 +00002010 continue;
Michael J. Spencera2c97272013-01-04 21:09:21 +00002011 section =
2012 llvm::dyn_cast<Section<target_endianness, max_align, is64Bits>>(*si);
Shankar Easwaran495d38b2012-12-27 02:26:30 +00002013 for (auto ai = section->atoms_begin(); ai != section->atoms_end(); ++ai) {
2014 _symtab->addSymbol(ai->first, section->ordinal(), ai->second.second);
Hemant Kulkarni736f7fb2012-11-21 21:07:36 +00002015 }
2016 }
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00002017}
2018
Michael J. Spencera2c97272013-01-04 21:09:21 +00002019template<support::endianness target_endianness,
2020 std::size_t max_align,
2021 bool is64Bits>
2022void ELFExecutableWriter<target_endianness, max_align, is64Bits>
2023 ::addAbsoluteUndefinedSymbols(const lld::File &file) {
Hemant Kulkarni08e410292012-10-01 23:53:20 +00002024 for (const UndefinedAtom *a : file.undefined()) {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00002025 _symtab->addSymbol(a, ELF::SHN_UNDEF);
Hemant Kulkarni08e410292012-10-01 23:53:20 +00002026 }
Michael J. Spencera2c97272013-01-04 21:09:21 +00002027
Hemant Kulkarni08e410292012-10-01 23:53:20 +00002028 for (const AbsoluteAtom *a : file.absolute()) {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00002029 _symtab->addSymbol(a, ELF::SHN_ABS);
Hemant Kulkarni08e410292012-10-01 23:53:20 +00002030 }
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00002031}
2032
Michael J. Spencera2c97272013-01-04 21:09:21 +00002033template<support::endianness target_endianness,
2034 std::size_t max_align,
2035 bool is64Bits>
2036void ELFExecutableWriter<target_endianness, max_align, is64Bits>
2037 ::buildAtomToAddressMap () {
2038 Section<target_endianness, max_align, is64Bits> *section;
2039 for (auto si = _layout->sections_begin();
Shankar Easwaran495d38b2012-12-27 02:26:30 +00002040 si != _layout->sections_end(); ++si) {
Michael J. Spencera2c97272013-01-04 21:09:21 +00002041 if ((*si)->kind() !=
2042 Chunk<target_endianness, max_align, is64Bits>::K_ELFSection)
Shankar Easwaran495d38b2012-12-27 02:26:30 +00002043 continue;
Michael J. Spencera2c97272013-01-04 21:09:21 +00002044 section =
2045 llvm::dyn_cast<Section<target_endianness, max_align, is64Bits>>(*si);
Shankar Easwaran495d38b2012-12-27 02:26:30 +00002046 for (auto ai = section->atoms_begin(); ai != section->atoms_end(); ++ai) {
2047 _atomToAddressMap[ai->first] = (ai)->second.second;
Sid Manningdd110202012-09-25 18:22:09 +00002048 }
2049 }
Sid Manningdd110202012-09-25 18:22:09 +00002050}
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00002051
Michael J. Spencera2c97272013-01-04 21:09:21 +00002052template<support::endianness target_endianness,
2053 std::size_t max_align,
2054 bool is64Bits>
2055void ELFExecutableWriter<target_endianness, max_align, is64Bits>
2056 ::buildSectionHeaderTable() {
2057 for (auto msi = _layout->merged_sections_begin();
Shankar Easwaran495d38b2012-12-27 02:26:30 +00002058 msi != _layout->merged_sections_end(); ++msi) {
Michael J. Spencera2c97272013-01-04 21:09:21 +00002059 if ((*msi)->kind() !=
2060 Chunk<target_endianness, max_align, is64Bits>::K_ELFSection)
Shankar Easwaran495d38b2012-12-27 02:26:30 +00002061 continue;
2062 if ((*msi)->hasSegment())
2063 _shdrtab->appendSection(*msi);
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00002064 }
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00002065}
2066
Michael J. Spencera2c97272013-01-04 21:09:21 +00002067template<support::endianness target_endianness,
2068 std::size_t max_align,
2069 bool is64Bits>
2070void ELFExecutableWriter<target_endianness, max_align, is64Bits>
2071 ::assignSectionsWithNoSegments() {
2072 Section<target_endianness, max_align, is64Bits> *section;
2073 for (auto msi = _layout->merged_sections_begin();
Shankar Easwaran495d38b2012-12-27 02:26:30 +00002074 msi != _layout->merged_sections_end(); ++msi) {
Michael J. Spencera2c97272013-01-04 21:09:21 +00002075 if ((*msi)->kind() !=
2076 Chunk<target_endianness, max_align, is64Bits>::K_ELFSection)
Shankar Easwaran495d38b2012-12-27 02:26:30 +00002077 continue;
2078 if (!(*msi)->hasSegment())
2079 _shdrtab->appendSection(*msi);
2080 }
2081 _layout->assignOffsetsForMiscSections();
Michael J. Spencera2c97272013-01-04 21:09:21 +00002082 for (auto si = _layout->sections_begin();
Shankar Easwaran495d38b2012-12-27 02:26:30 +00002083 si != _layout->sections_end(); ++si) {
Michael J. Spencera2c97272013-01-04 21:09:21 +00002084 if ((*si)->kind() !=
2085 Chunk<target_endianness, max_align, is64Bits>::K_ELFSection)
Shankar Easwaran495d38b2012-12-27 02:26:30 +00002086 continue;
Michael J. Spencera2c97272013-01-04 21:09:21 +00002087 section =
2088 llvm::dyn_cast<Section<target_endianness, max_align, is64Bits>>(*si);
2089 if (!DefaultELFLayout<target_endianness, max_align, is64Bits>
2090 ::hasOutputSegment(section))
Shankar Easwaran495d38b2012-12-27 02:26:30 +00002091 _shdrtab->updateSection(section);
2092 }
2093}
2094
Michael J. Spencera2c97272013-01-04 21:09:21 +00002095template<support::endianness target_endianness,
2096 std::size_t max_align,
2097 bool is64Bits>
2098error_code ELFExecutableWriter<target_endianness, max_align, is64Bits>
2099 ::writeFile(const lld::File &file, StringRef path) {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00002100 buildChunks(file);
2101 // Create the default sections like the symbol table, string table, and the
2102 // section string table
2103 createDefaultSections();
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00002104
Shankar Easwaran495d38b2012-12-27 02:26:30 +00002105 // Set the Layout
2106 _layout->assignSectionsToSegments();
2107 _layout->assignFileOffsets();
2108 _layout->assignVirtualAddress();
2109
2110 // Build the Atom To Address map for applying relocations
2111 buildAtomToAddressMap();
2112
2113 // Create symbol table and section string table
2114 buildSymbolTable();
2115
2116 // add other symbols
2117 addAbsoluteUndefinedSymbols(file);
2118
2119 // Finalize the layout by calling the finalize() functions
2120 _layout->finalize();
2121
2122 // build Section Header table
2123 buildSectionHeaderTable();
2124
2125 // assign Offsets and virtual addresses
2126 // for sections with no segments
2127 assignSectionsWithNoSegments();
2128
2129 uint64_t totalSize = _shdrtab->fileOffset() + _shdrtab->fileSize();
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00002130
2131 OwningPtr<FileOutputBuffer> buffer;
2132 error_code ec = FileOutputBuffer::create(path,
2133 totalSize, buffer,
2134 FileOutputBuffer::F_executable);
2135 if (ec)
2136 return ec;
2137
Shankar Easwaran495d38b2012-12-27 02:26:30 +00002138 for (auto si = _layout->sections_begin(); si != _layout->sections_end(); ++si)
2139 (*si)->write(this, buffer);
2140
2141 _elfHeader->e_ident(ELF::EI_CLASS, (_options.is64Bit() ? ELF::ELFCLASS64
2142 : ELF::ELFCLASS32));
Michael J. Spencera2c97272013-01-04 21:09:21 +00002143 _elfHeader->e_ident(ELF::EI_DATA, _options.endianness() == llvm::support::big
Shankar Easwaran495d38b2012-12-27 02:26:30 +00002144 ? ELF::ELFDATA2MSB : ELF::ELFDATA2LSB);
2145 _elfHeader->e_ident(ELF::EI_VERSION, 1);
2146 _elfHeader->e_ident(ELF::EI_OSABI, 0);
2147 _elfHeader->e_type(_options.type());
2148 _elfHeader->e_machine(_options.machine());
2149 _elfHeader->e_version(1);
2150 _elfHeader->e_entry(0ULL);
2151 _elfHeader->e_phoff(_programHeader->fileOffset());
2152 _elfHeader->e_shoff(_shdrtab->fileOffset());
2153 _elfHeader->e_phentsize(_programHeader->entsize());
2154 _elfHeader->e_phnum(_programHeader->numHeaders());
2155 _elfHeader->e_shentsize(_shdrtab->entsize());
2156 _elfHeader->e_shnum(_shdrtab->numHeaders());
2157 _elfHeader->e_shstrndx(_shstrtab->ordinal());
2158 uint64_t virtualAddr = 0;
2159 _layout->findAtomAddrByName("_start", virtualAddr);
2160 _elfHeader->e_entry(virtualAddr);
2161 _elfHeader->write(this, buffer);
2162 _programHeader->write(this, buffer);
2163
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00002164 return buffer->commit();
2165}
Nick Kledzikabb69812012-05-31 22:34:00 +00002166
Michael J. Spencera2c97272013-01-04 21:09:21 +00002167template<support::endianness target_endianness,
2168 std::size_t max_align,
2169 bool is64Bits>
2170void ELFExecutableWriter<target_endianness, max_align, is64Bits>
2171 ::createDefaultSections() {
2172 _elfHeader =
2173 new ELFHeader<target_endianness, max_align, is64Bits>();
2174 _programHeader =
2175 new ELFProgramHeader<target_endianness, max_align, is64Bits>();
Shankar Easwaran495d38b2012-12-27 02:26:30 +00002176 _layout->setELFHeader(_elfHeader);
2177 _layout->setProgramHeader(_programHeader);
2178
Michael J. Spencera2c97272013-01-04 21:09:21 +00002179 _symtab = new ELFSymbolTable<target_endianness, max_align, is64Bits>(
2180 ".symtab",
2181 DefaultELFLayout<target_endianness, max_align, is64Bits>
2182 ::ORDER_SYMBOL_TABLE);
2183 _strtab = new ELFStringTable<target_endianness, max_align, is64Bits>(
2184 ".strtab",
2185 DefaultELFLayout<target_endianness, max_align, is64Bits>
2186 ::ORDER_STRING_TABLE);
2187 _shstrtab = new ELFStringTable<target_endianness, max_align, is64Bits>(
2188 ".shstrtab",
2189 DefaultELFLayout<target_endianness, max_align, is64Bits>
2190 ::ORDER_SECTION_STRINGS);
2191 _shdrtab = new ELFSectionHeader<target_endianness, max_align, is64Bits>(
2192 DefaultELFLayout<target_endianness, max_align, is64Bits>
2193 ::ORDER_SECTION_HEADERS);
Shankar Easwaran495d38b2012-12-27 02:26:30 +00002194 _layout->addSection(_symtab);
2195 _layout->addSection(_strtab);
2196 _layout->addSection(_shstrtab);
2197 _shdrtab->setStringSection(_shstrtab);
2198 _symtab->setStringSection(_strtab);
2199 _layout->addSection(_shdrtab);
Sid Manningdd110202012-09-25 18:22:09 +00002200}
Nick Kledzikabb69812012-05-31 22:34:00 +00002201} // namespace elf
2202
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00002203Writer *createWriterELF(const WriterOptionsELF &options) {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00002204 // Set the default layout to be the static executable layout
Michael J. Spencera2c97272013-01-04 21:09:21 +00002205 // We would set the layout to a dynamic executable layout
Shankar Easwaran495d38b2012-12-27 02:26:30 +00002206 // if we came across any shared libraries in the process
Michael J. Spencera2c97272013-01-04 21:09:21 +00002207
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00002208 if (!options.is64Bit() && options.endianness() == llvm::support::little)
Michael J. Spencera2c97272013-01-04 21:09:21 +00002209 return new elf::ELFExecutableWriter<support::little, 4, false>(options);
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00002210 else if (options.is64Bit() && options.endianness() == llvm::support::little)
Michael J. Spencera2c97272013-01-04 21:09:21 +00002211 return new elf::ELFExecutableWriter<support::little, 8, true>(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, 4, false>(options);
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00002214 else if (options.is64Bit() && options.endianness() == llvm::support::big)
Michael J. Spencera2c97272013-01-04 21:09:21 +00002215 return new elf::ELFExecutableWriter<support::big, 8, true>(options);
Nick Kledzikabb69812012-05-31 22:34:00 +00002216
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00002217 llvm_unreachable("Invalid Options!");
Nick Kledzikabb69812012-05-31 22:34:00 +00002218}
Nick Kledzikabb69812012-05-31 22:34:00 +00002219} // namespace lld