blob: 2973f0243e1d515be33a1365b83379916125a90b [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:
Michael J. Spencer8de83642013-01-07 08:00:42 +0000276 case DefinedAtom::typeConstant:
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000277 _atoms.push_back(std::make_pair(atom, std::make_pair(fOffset, 0)));
278 this->_fsize = fOffset + definedAtom->size();
279 this->_msize = mOffset + definedAtom->size();
280 break;
281 case DefinedAtom::typeZeroFill:
282 _atoms.push_back(std::make_pair(atom, std::make_pair(mOffset, 0)));
283 this->_msize = mOffset + definedAtom->size();
284 break;
285 default:
286 this->_fsize = fOffset + definedAtom->size();
287 this->_msize = mOffset + definedAtom->size();
288 break;
289 }
290 break;
291 default:
292 llvm_unreachable("Expecting only definedAtoms being passed here");
293 break;
Michael J. Spencera2c97272013-01-04 21:09:21 +0000294 }
295 // Set the section alignment to the largest alignment
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000296 // std::max doesnot support uint64_t
Michael J. Spencera2c97272013-01-04 21:09:21 +0000297 if (this->_align2 < align2)
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000298 this->_align2 = align2;
299 }
300
Michael J. Spencera2c97272013-01-04 21:09:21 +0000301 /// \brief Set the virtual address of each Atom in the Section. This
302 /// routine gets called after the linker fixes up the virtual address
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000303 /// of the section
304 void assignVirtualAddress(uint64_t &addr) {
305 for (auto &ai : _atoms) {
306 ai.second.second = addr + ai.second.first;
307 }
308 addr += this->memSize();
309 }
310
Michael J. Spencera2c97272013-01-04 21:09:21 +0000311 /// \brief Set the file offset of each Atom in the section. This routine
312 /// gets called after the linker fixes up the section offset
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000313 void assignOffsets(uint64_t offset) {
314 for (auto &ai : _atoms) {
315 ai.second.first = offset + ai.second.first;
316 }
317 }
318
Michael J. Spencera2c97272013-01-04 21:09:21 +0000319 /// \brief Find the Atom address given a name, this is needed to to properly
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000320 /// apply relocation. The section class calls this to find the atom address
321 /// to fix the relocation
322 bool findAtomAddrByName(const StringRef name, uint64_t &addr) {
323 for (auto ai : _atoms) {
324 if (ai.first->name() == name) {
325 addr = ai.second.second;
326 return true;
327 }
328 }
329 return false;
330 }
331
332 /// \brief Does the Atom occupy any disk space
333 bool occupiesNoDiskSpace() const {
334 return _contentType == DefinedAtom::typeZeroFill;
335 }
336
Michael J. Spencera2c97272013-01-04 21:09:21 +0000337 /// \brief The permission of the section is the most permissive permission
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000338 /// of all atoms that the section contains
339 void setContentPermissions(int32_t perm) {
340 _contentPermissions = std::max(perm, _contentPermissions);
341 }
342
343 /// \brief Get the section flags, defined by the permissions of the section
344 int64_t flags() {
345 switch (_contentPermissions) {
346 case DefinedAtom::perm___:
347 return 0;
348
349 case DefinedAtom::permR__:
350 return llvm::ELF::SHF_ALLOC;
Michael J. Spencera2c97272013-01-04 21:09:21 +0000351
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000352 case DefinedAtom::permR_X:
353 return llvm::ELF::SHF_ALLOC | llvm::ELF::SHF_EXECINSTR;
Michael J. Spencera2c97272013-01-04 21:09:21 +0000354
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000355 case DefinedAtom::permRW_:
356 case DefinedAtom::permRW_L:
357 return llvm::ELF::SHF_ALLOC | llvm::ELF::SHF_WRITE;
Michael J. Spencera2c97272013-01-04 21:09:21 +0000358
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000359 case DefinedAtom::permRWX:
Michael J. Spencera2c97272013-01-04 21:09:21 +0000360 return llvm::ELF::SHF_ALLOC |
361 llvm::ELF::SHF_WRITE |
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000362 llvm::ELF::SHF_EXECINSTR;
363
364 default:
365 break;
366 }
367 return llvm::ELF::SHF_ALLOC;
368 }
369
370 /// \brief Return the raw flags, we need this to sort segments
371 int64_t atomflags() const {
372 return _contentPermissions;
373 }
374
Michael J. Spencera2c97272013-01-04 21:09:21 +0000375 /// \brief Return the section type, the returned value is recorded in the
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000376 /// sh_type field of the Section Header
377 int type() {
378 switch (_contentType) {
379 case DefinedAtom::typeCode:
380 case DefinedAtom::typeData:
381 case DefinedAtom::typeConstant:
382 return llvm::ELF::SHT_PROGBITS;
383
384 case DefinedAtom::typeZeroFill:
385 return llvm::ELF::SHT_NOBITS;
386
387 // Case to handle section types
388 // Symtab, String Table ...
389 default:
390 return _contentType;
391 }
392 }
393
Michael J. Spencera2c97272013-01-04 21:09:21 +0000394 /// \brief Returns the section link field, the returned value is
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000395 /// recorded in the sh_link field of the Section Header
396 int link() const {
397 return _link;
398 }
399
400 void setLink(int32_t link) {
401 _link = link;
402 }
403
Michael J. Spencera2c97272013-01-04 21:09:21 +0000404 /// \brief Returns the section entsize field, the returned value is
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000405 /// recorded in the sh_entsize field of the Section Header
406 int entsize() const {
407 return _entSize;
408 }
409
Michael J. Spencera2c97272013-01-04 21:09:21 +0000410 /// \brief Returns the shinfo field, the returned value is
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000411 /// recorded in the sh_info field of the Section Header
Michael J. Spencera2c97272013-01-04 21:09:21 +0000412 int shinfo() const {
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000413 return _shInfo;
414 }
415
416 /// \brief Records the segmentType, that this section belongs to
417 void setSegment(const ELFLayout::SegmentType segmentType) {
418 _segmentType = segmentType;
419 }
420
421 /// \brief convert the segment type to a String for diagnostics
422 /// and printing purposes
423 StringRef segmentKindToStr() const {
424 switch(_segmentType) {
425 case llvm::ELF::PT_INTERP:
426 return "INTERP";
427 case llvm::ELF::PT_LOAD:
428 return "LOAD";
429 case llvm::ELF::PT_GNU_EH_FRAME:
430 return "EH_FRAME";
431 case llvm::ELF::PT_NOTE:
432 return "NOTE";
433 case llvm::ELF::PT_DYNAMIC:
434 return "DYNAMIC";
435 case llvm::ELF::PT_GNU_RELRO:
436 return "RELRO";
437 case llvm::ELF::PT_NULL:
438 return "NULL";
439 default:
440 return "UNKNOWN";
441 }
442 }
443
444 /// \brief for LLVM style RTTI information
Michael J. Spencera2c97272013-01-04 21:09:21 +0000445 static inline bool classof(
446 const Chunk<target_endianness, max_align, is64Bits> *c) {
447 return c->kind() ==
448 Chunk<target_endianness, max_align, is64Bits>::K_ELFSection;
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000449 }
450
451 /// \brief Finalize the section contents before writing
452 void finalize() { }
453
Michael J. Spencera2c97272013-01-04 21:09:21 +0000454 /// \brief Write the section and the atom contents to the buffer
455 void write(ELFWriter *writer,
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000456 OwningPtr<FileOutputBuffer> &buffer) {
457 uint8_t *chunkBuffer = buffer->getBufferStart();
458 for (auto &ai : _atoms) {
459 const DefinedAtom *definedAtom = llvm::dyn_cast<DefinedAtom>(ai.first);
Michael J. Spencer8de83642013-01-07 08:00:42 +0000460 if (definedAtom->contentType() == DefinedAtom::typeZeroFill)
461 continue;
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000462 // Copy raw content of atom to file buffer.
463 ArrayRef<uint8_t> content = definedAtom->rawContent();
464 uint64_t contentSize = content.size();
465 if (contentSize == 0)
466 continue;
467 uint8_t *atomContent = chunkBuffer + ai.second.first;
468 std::copy_n(content.data(), contentSize, atomContent);
469 for (auto ref = definedAtom->begin(); ref != definedAtom->end(); ++ref) {
470 uint32_t offset = ref->offsetInAtom();
471 uint64_t targetAddress = 0;
472 if (ref->target() != nullptr)
473 targetAddress = writer->addressOfAtom(ref->target());
474 else
475 assert(0 && "Found the target to be NULL");
476 uint64_t fixupAddress = writer->addressOfAtom(ai.first) + offset;
477 // apply the relocation
Michael J. Spencera2c97272013-01-04 21:09:21 +0000478 writer->kindHandler()->applyFixup(ref->kind(),
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000479 ref->addend(),
480 &atomContent[offset],
481 fixupAddress,
482 targetAddress);
483 }
484 }
485 }
486
487 /// Atom Iterators
Michael J. Spencera2c97272013-01-04 21:09:21 +0000488 typedef typename std::vector<std::pair<const Atom *,
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000489 std::pair<uint64_t, uint64_t>>>::iterator atom_iter;
490
491 atom_iter atoms_begin() { return _atoms.begin(); }
492
493 atom_iter atoms_end() { return _atoms.end(); }
494
495protected:
496 int32_t _contentType;
497 int32_t _contentPermissions;
498 SectionKind _sectionKind;
499 // An Atom is appended to the vector with the following fields
500 // field1 : Atom
501 // field2 : fileoffset (initially set with a base offset of 0)
502 // field3 : virtual address
503 std::vector<std::pair<const Atom *, std::pair<uint64_t, uint64_t>>> _atoms;
504 ELFLayout::SegmentType _segmentType;
505 int64_t _entSize;
506 int64_t _shInfo;
507 int64_t _link;
Michael J. Spencera2c97272013-01-04 21:09:21 +0000508};
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000509
Michael J. Spencera2c97272013-01-04 21:09:21 +0000510/// \brief A MergedSections represents a set of sections grouped by the same
511/// name. The output file that gets written by the linker has sections grouped
512/// by similiar names
513template<support::endianness target_endianness,
514 std::size_t max_align,
515 bool is64Bits>
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000516class MergedSections {
517public:
Michael J. Spencera2c97272013-01-04 21:09:21 +0000518 MergedSections(StringRef name)
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000519 : _name(name)
520 ,_hasSegment(false)
521 ,_ordinal(0)
522 ,_flags(0)
523 ,_size(0)
524 ,_memSize(0)
525 ,_fileOffset(0)
526 ,_virtualAddr(0)
527 ,_shInfo(0)
528 ,_entSize(0)
529 ,_link(0)
530 ,_align2(0)
531 ,_kind(0)
532 ,_type(0) { }
Michael J. Spencera2c97272013-01-04 21:09:21 +0000533
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000534 // Set the MergedSections is associated with a segment
535 void setHasSegment() { _hasSegment = true; }
536
Michael J. Spencera2c97272013-01-04 21:09:21 +0000537 /// Sets the ordinal
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000538 void setOrdinal(uint64_t ordinal) {
539 _ordinal = ordinal;
540 }
541
Michael J. Spencera2c97272013-01-04 21:09:21 +0000542 /// Sets the Memory size
543 void setMemSize(uint64_t memsz) {
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000544 _memSize = memsz;
545 }
546
547 /// Sets the size fo the merged Section
548 void setSize(uint64_t fsiz) {
549 _size = fsiz;
550 }
551
Michael J. Spencera2c97272013-01-04 21:09:21 +0000552 // The offset of the first section contained in the merged section is
553 // contained here
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000554 void setFileOffset(uint64_t foffset) {
555 _fileOffset = foffset;
556 }
557
558 // Sets the starting address of the section
559 void setAddr(uint64_t addr) {
560 _virtualAddr = addr;
561 }
562
563 // Appends a section into the list of sections that are part of this Merged
564 // Section
Michael J. Spencera2c97272013-01-04 21:09:21 +0000565 void appendSection(Chunk<target_endianness, max_align, is64Bits> *c) {
566 if (c->align2() > _align2)
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000567 _align2 = c->align2();
Michael J. Spencera2c97272013-01-04 21:09:21 +0000568 if (c->kind() ==
569 Chunk<target_endianness, max_align, is64Bits>::K_ELFSection) {
570 Section<target_endianness, max_align, is64Bits> *section;
571 section =
572 llvm::dyn_cast<Section<target_endianness, max_align, is64Bits>>(c);
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000573 _link = section->link();
574 _shInfo = section->shinfo();
575 _entSize = section->entsize();
576 _type = section->type();
577 if (_flags < section->flags())
578 _flags = section->flags();
579 }
580 _kind = c->kind();
581 _sections.push_back(c);
582 }
583
584 // Iterators
Michael J. Spencera2c97272013-01-04 21:09:21 +0000585 typedef typename std::vector<
586 Chunk<target_endianness, max_align, is64Bits> *>::iterator ChunkIter;
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000587
588 ChunkIter begin_sections() { return _sections.begin(); }
589
590 ChunkIter end_sections() { return _sections.end(); }
591
592 // The below functions returns the properties of the MergeSection
593 bool hasSegment() const { return _hasSegment; }
594
595 StringRef name() const { return _name; }
596
597 int64_t shinfo() const { return _shInfo; }
598
599 uint64_t align2() const { return _align2; }
600
601 int64_t link() const { return _link; }
602
603 int64_t type() const { return _type; }
604
605 uint64_t virtualAddr() const { return _virtualAddr; }
606
607 int64_t ordinal() const { return _ordinal; }
608
609 int64_t kind() const { return _kind; }
610
611 uint64_t fileSize() const { return _size; }
612
613 int64_t entsize() const { return _entSize; }
614
615 uint64_t fileOffset() const { return _fileOffset; }
616
617 int64_t flags() const { return _flags; }
618
619 uint64_t memSize() { return _memSize; }
620
621private:
622 StringRef _name;
623 bool _hasSegment;
624 uint64_t _ordinal;
625 int64_t _flags;
626 uint64_t _size;
627 uint64_t _memSize;
628 uint64_t _fileOffset;
629 uint64_t _virtualAddr;
630 int64_t _shInfo;
631 int64_t _entSize;
632 int64_t _link;
633 uint64_t _align2;
634 int64_t _kind;
635 int64_t _type;
Michael J. Spencera2c97272013-01-04 21:09:21 +0000636 std::vector<Chunk<target_endianness, max_align, is64Bits> *> _sections;
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000637};
638
Michael J. Spencera2c97272013-01-04 21:09:21 +0000639/// \brief A segment can be divided into segment slices
640/// depending on how the segments can be split
641template<support::endianness target_endianness,
642 std::size_t max_align,
643 bool is64Bits>
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000644class SegmentSlice {
645public:
Michael J. Spencera2c97272013-01-04 21:09:21 +0000646 typedef typename std::vector<
Michael J. Spencer00b702c2013-01-07 07:59:46 +0000647 Chunk<target_endianness, max_align, is64Bits> *>::iterator sectionIter;
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000648
649 SegmentSlice() { }
650
651 /// Set the segment slice so that it begins at the offset specified
Michael J. Spencera2c97272013-01-04 21:09:21 +0000652 /// by fileoffset and set the start of the slice to be s and the end
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000653 /// of the slice to be e
654 void set(uint64_t fileoffset, int32_t s, int e) {
655 _startSection = s;
656 _endSection = e+1;
657 _offset = fileoffset;
658 }
659
660 // Set the segment slice start and end iterators. This is used to walk through
661 // the sections that are part of the Segment slice
662 void setSections(sectionIter start, sectionIter end) {
663 _startSectionIter = start;
664 _endSectionIter = end;
665 }
666
667 // Return the fileOffset of the slice
668 uint64_t fileOffset() const { return _offset; }
669
670 // Return the size of the slice
671 uint64_t fileSize() const { return _size; }
672
673 // Return the start of the slice
674 int32_t startSection() const { return _startSection; }
675
676 // Return the start address of the slice
677 uint64_t virtualAddr() const { return _addr; }
678
679 // Return the memory size of the slice
680 uint64_t memSize() const { return _memSize; }
681
682 // Return the alignment of the slice
683 uint64_t align2() const { return _align2; }
684
685 void setSize(uint64_t sz) { _size = sz; }
686
687 void setMemSize(uint64_t memsz) { _memSize = memsz; }
688
689 void setVAddr(uint64_t addr) { _addr = addr; }
690
691 void setAlign(uint64_t align) { _align2 = align; }
692
Michael J. Spencera2c97272013-01-04 21:09:21 +0000693 static bool compare_slices(
694 SegmentSlice<target_endianness, max_align, is64Bits> *a,
695 SegmentSlice<target_endianness, max_align, is64Bits> *b) {
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000696 return (a->startSection() < b->startSection());
697 }
698
699 // Functions to run through the slice
700 sectionIter sections_begin() { return _startSectionIter; }
701
702 sectionIter sections_end() { return _endSectionIter; }
703
704private:
705 int32_t _startSection;
706 int32_t _endSection;
707 sectionIter _startSectionIter;
708 sectionIter _endSectionIter;
709 uint64_t _addr;
710 uint64_t _offset;
711 uint64_t _size;
712 uint64_t _align2;
713 uint64_t _memSize;
714};
715
716/// \brief A segment contains a set of sections, that have similiar properties
717// the sections are already seperated based on different flags and properties
718// the segment is just a way to concatenate sections to segments
Michael J. Spencera2c97272013-01-04 21:09:21 +0000719template<support::endianness target_endianness,
720 std::size_t max_align,
721 bool is64Bits>
722class Segment : public Chunk<target_endianness, max_align, is64Bits> {
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000723public:
Michael J. Spencera2c97272013-01-04 21:09:21 +0000724 typedef typename std::vector<SegmentSlice<
725 target_endianness, max_align, is64Bits> *>::iterator slice_iter;
726 typedef typename std::vector<
Michael J. Spencer00b702c2013-01-07 07:59:46 +0000727 Chunk<target_endianness, max_align, is64Bits> *>::iterator SectionIter;
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000728
729 Segment(const StringRef name,
730 const ELFLayout::SegmentType type,
731 const WriterOptionsELF &options)
Michael J. Spencera2c97272013-01-04 21:09:21 +0000732 : Chunk<target_endianness, max_align, is64Bits>(name,
733 Chunk<target_endianness, max_align, is64Bits>::K_ELFSegment)
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000734 , _segmentType(type)
735 , _flags(0)
736 , _atomflags(0)
737 , _options(options) {
738 this->_align2 = 0;
739 this->_fsize = 0;
740 }
741
742 /// append a section to a segment
Michael J. Spencera2c97272013-01-04 21:09:21 +0000743 void append(Section<target_endianness, max_align, is64Bits> *section) {
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000744 _sections.push_back(section);
745 if (_flags < section->flags())
746 _flags = section->flags();
747 if (_atomflags < section->atomflags())
748 _atomflags = section->atomflags();
749 if (this->_align2 < section->align2())
750 this->_align2 = section->align2();
751 }
752
Michael J. Spencer1ac382f02013-01-07 08:00:04 +0000753 /// Prepend a generic chunk to the segment.
754 void prepend(Chunk<target_endianness, max_align, is64Bits> *c) {
755 _sections.insert(_sections.begin(), c);
756 }
757
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000758 /// Sort segments depending on the property
759 /// If we have a Program Header segment, it should appear first
760 /// If we have a INTERP segment, that should appear after the Program Header
761 /// All Loadable segments appear next in this order
762 /// All Read Write Execute segments follow
763 /// All Read Execute segments appear next
764 /// All Read only segments appear first
Michael J. Spencera2c97272013-01-04 21:09:21 +0000765 /// All Write execute segments follow
766 static bool compareSegments(
767 Segment<target_endianness, max_align, is64Bits> *sega,
768 Segment<target_endianness, max_align, is64Bits> *segb) {
769 if (sega->atomflags() < segb->atomflags())
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000770 return false;
771 return true;
772 }
773
774 /// \brief Start assigning file offset to the segment chunks The fileoffset
775 /// needs to be page at the start of the segment and in addition the
776 /// fileoffset needs to be aligned to the max section alignment within the
777 /// segment. This is required so that the ELF property p_poffset % p_align =
778 /// p_vaddr mod p_align holds true.
779 /// The algorithm starts off by assigning the startOffset thats passed in as
780 /// parameter to the first section in the segment, if the difference between
781 /// the newly computed offset is greater than a page, then we create a segment
Michael J. Spencera2c97272013-01-04 21:09:21 +0000782 /// slice, as it would be a waste of virtual memory just to be filled with
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000783 /// zeroes
784 void assignOffsets(uint64_t startOffset) {
785 int startSection = 0;
786 int currSection = 0;
787 SectionIter startSectionIter, endSectionIter;
Michael J. Spencera2c97272013-01-04 21:09:21 +0000788 // slice align is set to the max alignment of the chunks that are
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000789 // contained in the slice
790 uint64_t sliceAlign = 0;
791 // Current slice size
792 uint64_t curSliceSize = 0;
793 // Current Slice File Offset
794 uint64_t curSliceFileOffset = 0;
795
796 startSectionIter = _sections.begin();
797 endSectionIter = _sections.end();
798 startSection = 0;
799 bool isFirstSection = true;
800 for (auto si = _sections.begin(); si != _sections.end(); ++si) {
801 if (isFirstSection) {
802 // align the startOffset to the section alignment
Michael J. Spencera2c97272013-01-04 21:09:21 +0000803 uint64_t newOffset =
804 llvm::RoundUpToAlignment(startOffset, (*si)->align2());
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000805 curSliceFileOffset = newOffset;
806 sliceAlign = (*si)->align2();
807 this->setFileOffset(startOffset);
808 (*si)->setFileOffset(newOffset);
809 curSliceSize = (*si)->fileSize();
810 isFirstSection = false;
811 } else {
812 uint64_t curOffset = curSliceFileOffset + curSliceSize;
Michael J. Spencera2c97272013-01-04 21:09:21 +0000813 uint64_t newOffset =
814 llvm::RoundUpToAlignment(curOffset, (*si)->align2());
815 SegmentSlice<target_endianness, max_align, is64Bits> *slice = nullptr;
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000816 // If the newOffset computed is more than a page away, lets create
817 // a seperate segment, so that memory is not used up while running
818 if ((newOffset - curOffset) > _options.pageSize()) {
819 // TODO: use std::find here
820 for (auto sei = slices_begin(); sei != slices_end(); ++sei) {
821 if ((*sei)->startSection() == startSection) {
822 slice = *sei;
823 break;
824 }
825 }
826 if (!slice) {
Michael J. Spencera2c97272013-01-04 21:09:21 +0000827 slice = new (_segmentAllocate.Allocate<
828 SegmentSlice<target_endianness, max_align, is64Bits>>())
829 SegmentSlice<target_endianness, max_align, is64Bits>();
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000830 _segmentSlices.push_back(slice);
831 }
832 slice->set(curSliceFileOffset, startSection, currSection);
833 slice->setSections(startSectionIter, endSectionIter);
834 slice->setSize(curSliceSize);
835 slice->setAlign(sliceAlign);
Michael J. Spencera2c97272013-01-04 21:09:21 +0000836 uint64_t newPageOffset =
837 llvm::RoundUpToAlignment(curOffset, _options.pageSize());
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000838 newOffset = llvm::RoundUpToAlignment(newPageOffset, (*si)->align2());
839 curSliceFileOffset = newOffset;
840 startSectionIter = endSectionIter;
841 startSection = currSection;
842 (*si)->setFileOffset(curSliceFileOffset);
843 curSliceSize = newOffset - curSliceFileOffset + (*si)->fileSize();
844 sliceAlign = (*si)->align2();
845 }
846 else {
847 if (sliceAlign < (*si)->align2())
848 sliceAlign = (*si)->align2();
849 (*si)->setFileOffset(newOffset);
850 curSliceSize = newOffset - curSliceFileOffset + (*si)->fileSize();
851 }
852 }
853 currSection++;
854 endSectionIter = si;
855 }
Michael J. Spencera2c97272013-01-04 21:09:21 +0000856 SegmentSlice<target_endianness, max_align, is64Bits> *slice = nullptr;
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000857 for (auto sei = slices_begin(); sei != slices_end(); ++sei) {
858 // TODO: add std::find
859 if ((*sei)->startSection() == startSection) {
860 slice = *sei;
861 break;
862 }
863 }
864 if (!slice) {
865 slice = new (_segmentAllocate.Allocate
Michael J. Spencera2c97272013-01-04 21:09:21 +0000866 <SegmentSlice<target_endianness, max_align, is64Bits>>())
867 SegmentSlice<target_endianness, max_align, is64Bits>();
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000868 _segmentSlices.push_back(slice);
869 }
870 slice->set(curSliceFileOffset, startSection, currSection);
871 slice->setSections(startSectionIter, _sections.end());
872 slice->setSize(curSliceSize);
873 slice->setAlign(sliceAlign);
874 this->_fsize = curSliceFileOffset - startOffset + curSliceSize;
Michael J. Spencera2c97272013-01-04 21:09:21 +0000875 std::stable_sort(slices_begin(), slices_end(),
876 SegmentSlice<target_endianness, max_align, is64Bits>::compare_slices);
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000877 }
878
879 /// \brief Assign virtual addresses to the slices
Michael J. Spencer1ac382f02013-01-07 08:00:04 +0000880 void assignVirtualAddress(uint64_t &addr) {
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000881 for (auto sei = slices_begin(), see = slices_end(); sei != see; ++sei) {
Michael J. Spencer1ac382f02013-01-07 08:00:04 +0000882 // 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
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000887 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());
Michael J. Spencer1ac382f02013-01-07 08:00:04 +0000892 if (!virtualAddressSet) {
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000893 (*sei)->setVAddr(addr);
894 virtualAddressSet = true;
895 }
896 (*si)->setVAddr(addr);
Michael J. Spencer00b702c2013-01-07 07:59:46 +0000897 if (auto s =
898 dyn_cast<Section<target_endianness, max_align, is64Bits>>(*si))
899 s->assignVirtualAddress(addr);
Michael J. Spencer1ac382f02013-01-07 08:00:04 +0000900 else
901 addr += (*si)->memSize();
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000902 (*si)->setMemSize(addr - (*si)->virtualAddr());
903 }
904 (*sei)->setMemSize(addr - (*sei)->virtualAddr());
905 }
906 }
907
908 slice_iter slices_begin() {
909 return _segmentSlices.begin();
910 }
911
912 slice_iter slices_end() {
913 return _segmentSlices.end();
914 }
915
Michael J. Spencera2c97272013-01-04 21:09:21 +0000916 // Write the Segment
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000917 void write(ELFWriter *writer, OwningPtr<FileOutputBuffer> &buffer) {
918 for (auto sei = slices_begin(), see = slices_end(); sei != see; ++sei) {
Michael J. Spencera2c97272013-01-04 21:09:21 +0000919 for (auto si = (*sei)->sections_begin(), se = (*sei)->sections_end();
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000920 si != se; ++si) {
921 (*si)->write(writer, buffer);
922 }
923 }
924 }
925
926 // Finalize the segment, before we want to write to the output file
927 void finalize() { }
928
Michael J. Spencera2c97272013-01-04 21:09:21 +0000929 // For LLVM RTTI
930 static inline bool classof(
931 const Chunk<target_endianness, max_align, is64Bits> *c) {
932 return c->kind() ==
933 Chunk<target_endianness, max_align, is64Bits>::K_ELFSegment;
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000934 }
935
936 // Getters
937 int32_t sectionCount() const {
938 return _sections.size();
939 }
940
941 ELFLayout::SegmentType segmentType() { return _segmentType; }
942
943 int pageSize() const { return _options.pageSize(); }
944
945 int64_t atomflags() const { return _atomflags; }
946
947 int64_t flags() const {
948 int64_t fl = 0;
949 if (_flags & llvm::ELF::SHF_ALLOC)
950 fl |= llvm::ELF::PF_R;
951 if (_flags & llvm::ELF::SHF_WRITE)
952 fl |= llvm::ELF::PF_W;
953 if (_flags & llvm::ELF::SHF_EXECINSTR)
954 fl |= llvm::ELF::PF_X;
955 return fl;
956 }
957
958 int64_t numSlices() const {
959 return _segmentSlices.size();
960 }
961
962private:
Michael J. Spencer00b702c2013-01-07 07:59:46 +0000963 /// \brief Section or some other chunk type.
964 std::vector<Chunk<target_endianness, max_align, is64Bits> *> _sections;
Michael J. Spencera2c97272013-01-04 21:09:21 +0000965 std::vector<SegmentSlice<target_endianness, max_align, is64Bits> *>
966 _segmentSlices;
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000967 ELFLayout::SegmentType _segmentType;
968 int64_t _flags;
969 int64_t _atomflags;
970 const WriterOptionsELF _options;
971 llvm::BumpPtrAllocator _segmentAllocate;
972};
973
974/// \brief The class represents the ELF String Table
Michael J. Spencera2c97272013-01-04 21:09:21 +0000975template<support::endianness target_endianness,
976 std::size_t max_align,
977 bool is64Bits>
978class ELFStringTable : public Section<target_endianness, max_align, is64Bits> {
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000979public:
Michael J. Spencera2c97272013-01-04 21:09:21 +0000980 ELFStringTable(const char *str, int32_t order)
981 : Section<target_endianness, max_align, is64Bits>(
982 str,
983 llvm::ELF::SHT_STRTAB,
984 DefinedAtom::perm___,
985 order,
986 Section<target_endianness, max_align, is64Bits>::K_StringTable) {
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000987 // the string table has a NULL entry for which
988 // add an empty string
989 _strings.push_back("");
990 this->_fsize = 1;
991 this->_align2 = 1;
992 this->setOrder(order);
993 }
994
Michael J. Spencera2c97272013-01-04 21:09:21 +0000995 static inline bool classof(
996 const Chunk<target_endianness, max_align, is64Bits> *c) {
997 return c->kind() ==
998 Section<target_endianness, max_align, is64Bits>::K_StringTable;
Shankar Easwaran495d38b2012-12-27 02:26:30 +0000999 }
1000
1001 uint64_t addString(const StringRef symname) {
1002 _strings.push_back(symname);
1003 uint64_t offset = this->_fsize;
1004 this->_fsize += symname.size() + 1;
1005 return offset;
1006 }
1007
Michael J. Spencera2c97272013-01-04 21:09:21 +00001008 void write(ELFWriter *writer,
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001009 OwningPtr<FileOutputBuffer> &buffer) {
1010 uint8_t *chunkBuffer = buffer->getBufferStart();
1011 uint8_t *dest = chunkBuffer + this->fileOffset();
1012 for (auto si : _strings) {
1013 memcpy(dest, si.data(), si.size());
1014 dest += si.size();
1015 memcpy(dest, "", 1);
1016 dest += 1;
1017 }
1018 }
1019
1020 void finalize() { }
1021
1022private:
1023 std::vector<StringRef> _strings;
1024};
1025
Michael J. Spencera2c97272013-01-04 21:09:21 +00001026/// \brief The ELFSymbolTable class represents the symbol table in a ELF file
1027template<support::endianness target_endianness,
1028 std::size_t max_align,
1029 bool is64Bits>
1030class ELFSymbolTable : public Section<target_endianness, max_align, is64Bits> {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001031public:
Michael J. Spencera2c97272013-01-04 21:09:21 +00001032 typedef object::Elf_Sym_Impl<target_endianness, max_align, is64Bits> Elf_Sym;
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001033
Michael J. Spencera2c97272013-01-04 21:09:21 +00001034 ELFSymbolTable(const char *str, int32_t order)
1035 : Section<target_endianness, max_align, is64Bits>(
1036 str,
1037 llvm::ELF::SHT_SYMTAB,
1038 0,
1039 order,
1040 Section<target_endianness, max_align, is64Bits>::K_SymbolTable) {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001041 this->setOrder(order);
1042 Elf_Sym *symbol = new (_symbolAllocate.Allocate<Elf_Sym>()) Elf_Sym;
Michael J. Spencera2c97272013-01-04 21:09:21 +00001043 memset((void *)symbol, 0, sizeof(Elf_Sym));
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001044 _symbolTable.push_back(symbol);
1045 this->_entSize = sizeof(Elf_Sym);
1046 this->_fsize = sizeof(Elf_Sym);
1047 this->_align2 = sizeof(void *);
1048 }
1049
Michael J. Spencera2c97272013-01-04 21:09:21 +00001050 static inline bool classof(
1051 const Chunk<target_endianness, max_align, is64Bits> *c) {
1052 return c->kind() ==
1053 Section<target_endianness, max_align, is64Bits>::K_SymbolTable;
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001054 }
1055
1056 void addSymbol(const Atom *atom, int32_t sectionIndex, uint64_t addr = 0) {
1057 Elf_Sym *symbol = new(_symbolAllocate.Allocate<Elf_Sym>()) Elf_Sym;
1058 unsigned char binding = 0, type = 0;
1059 symbol->st_name = _stringSection->addString(atom->name());
1060 symbol->st_size = 0;
1061 symbol->st_shndx = sectionIndex;
1062 symbol->st_value = 0;
1063 symbol->st_other = ELF::STV_DEFAULT;
1064 if (const DefinedAtom *da = llvm::dyn_cast<const DefinedAtom>(atom)){
1065 symbol->st_size = da->size();
1066 lld::DefinedAtom::ContentType ct;
1067 switch (ct = da->contentType()){
1068 case DefinedAtom::typeCode:
1069 symbol->st_value = addr;
1070 type = ELF::STT_FUNC;
1071 break;
1072 case DefinedAtom::typeData:
Michael J. Spencer8de83642013-01-07 08:00:42 +00001073 case DefinedAtom::typeConstant:
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001074 symbol->st_value = addr;
1075 type = ELF::STT_OBJECT;
1076 break;
1077 case DefinedAtom::typeZeroFill:
Michael J. Spencer28c65942013-01-07 07:05:52 +00001078 type = ELF::STT_OBJECT;
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001079 symbol->st_value = addr;
1080 break;
1081 default:
1082 type = ELF::STT_NOTYPE;
1083 }
Michael J. Spencera2c97272013-01-04 21:09:21 +00001084 if (da->scope() == DefinedAtom::scopeTranslationUnit)
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001085 binding = ELF::STB_LOCAL;
1086 else
1087 binding = ELF::STB_GLOBAL;
Michael J. Spencera2c97272013-01-04 21:09:21 +00001088 } else if (const AbsoluteAtom *aa =
1089 llvm::dyn_cast<const AbsoluteAtom>(atom)){
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001090 type = ELF::STT_OBJECT;
1091 symbol->st_shndx = ELF::SHN_ABS;
1092 switch (aa->scope()) {
1093 case AbsoluteAtom::scopeLinkageUnit:
1094 symbol->st_other = ELF::STV_HIDDEN;
1095 binding = ELF::STB_LOCAL;
1096 break;
1097 case AbsoluteAtom::scopeTranslationUnit:
1098 binding = ELF::STB_LOCAL;
1099 break;
1100 case AbsoluteAtom::scopeGlobal:
1101 binding = ELF::STB_GLOBAL;
1102 break;
1103 }
1104 symbol->st_value = aa->value();
Michael J. Spencera2c97272013-01-04 21:09:21 +00001105 }
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001106 else {
1107 symbol->st_value = 0;
1108 type = ELF::STT_NOTYPE;
1109 binding = ELF::STB_WEAK;
1110 }
1111 symbol->setBindingAndType(binding, type);
1112 _symbolTable.push_back(symbol);
1113 this->_fsize += sizeof(Elf_Sym);
1114 }
1115
Michael J. Spencera2c97272013-01-04 21:09:21 +00001116 void setStringSection(
1117 ELFStringTable<target_endianness, max_align, is64Bits> *s) {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001118 _stringSection = s;
1119 }
1120
1121 void finalize() {
1122 // sh_info should be one greater than last symbol with STB_LOCAL binding
1123 // we sort the symbol table to keep all local symbols at the beginning
1124 std::stable_sort(_symbolTable.begin(), _symbolTable.end(),
1125 [](const Elf_Sym *A, const Elf_Sym *B) {
1126 return A->getBinding() < B->getBinding();
Michael J. Spencera2c97272013-01-04 21:09:21 +00001127 });
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001128 uint16_t shInfo = 0;
1129 for (auto i : _symbolTable) {
1130 if (i->getBinding() != ELF::STB_LOCAL)
1131 break;
1132 shInfo++;
1133 }
1134 this->_shInfo = shInfo;
1135 this->setLink(_stringSection->ordinal());
1136 }
1137
Michael J. Spencera2c97272013-01-04 21:09:21 +00001138 void write(ELFWriter *writer,
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001139 OwningPtr<FileOutputBuffer> &buffer) {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001140 uint8_t *chunkBuffer = buffer->getBufferStart();
1141 uint8_t *dest = chunkBuffer + this->fileOffset();
1142 for (auto sti : _symbolTable) {
1143 memcpy(dest, sti, sizeof(Elf_Sym));
1144 dest += sizeof(Elf_Sym);
1145 }
1146 }
1147
1148private:
Michael J. Spencera2c97272013-01-04 21:09:21 +00001149 ELFStringTable<target_endianness, max_align, is64Bits> *_stringSection;
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001150 std::vector<Elf_Sym*> _symbolTable;
1151 llvm::BumpPtrAllocator _symbolAllocate;
1152 int64_t _link;
1153};
1154
1155/// \brief An ELFHeader represents the Elf[32/64]_Ehdr structure at the
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001156/// start of an ELF executable file.
Michael J. Spencera2c97272013-01-04 21:09:21 +00001157template<support::endianness target_endianness,
1158 std::size_t max_align,
1159 bool is64Bits>
1160class ELFHeader : public Chunk<target_endianness, max_align, is64Bits> {
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001161public:
Michael J. Spencera2c97272013-01-04 21:09:21 +00001162 typedef Elf_Ehdr_Impl<target_endianness, max_align, is64Bits> Elf_Ehdr;
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001163
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001164 ELFHeader()
Michael J. Spencera2c97272013-01-04 21:09:21 +00001165 : Chunk<target_endianness, max_align, is64Bits>(
1166 "elfhdr", Chunk<target_endianness, max_align, is64Bits>::K_ELFHeader) {
Michael J. Spencer1ac382f02013-01-07 08:00:04 +00001167 this->_align2 = is64Bits ? 8 : 4;
1168 this->_fsize = sizeof(Elf_Ehdr);
1169 this->_msize = sizeof(Elf_Ehdr);
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001170 memset(_eh.e_ident, 0, llvm::ELF::EI_NIDENT);
1171 e_ident(ELF::EI_MAG0, 0x7f);
1172 e_ident(ELF::EI_MAG1, 'E');
1173 e_ident(ELF::EI_MAG2, 'L');
1174 e_ident(ELF::EI_MAG3, 'F');
1175 e_ehsize(sizeof(Elf_Ehdr));
1176 e_flags(2);
1177 }
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001178 void e_ident(int I, unsigned char C) { _eh.e_ident[I] = C; }
1179 void e_type(uint16_t type) { _eh.e_type = type; }
1180 void e_machine(uint16_t machine) { _eh.e_machine = machine; }
1181 void e_version(uint32_t version) { _eh.e_version = version; }
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001182 void e_entry(int64_t entry) { _eh.e_entry = entry; }
1183 void e_phoff(int64_t phoff) { _eh.e_phoff = phoff; }
1184 void e_shoff(int64_t shoff) { _eh.e_shoff = shoff; }
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001185 void e_flags(uint32_t flags) { _eh.e_flags = flags; }
1186 void e_ehsize(uint16_t ehsize) { _eh.e_ehsize = ehsize; }
1187 void e_phentsize(uint16_t phentsize) { _eh.e_phentsize = phentsize; }
1188 void e_phnum(uint16_t phnum) { _eh.e_phnum = phnum; }
1189 void e_shentsize(uint16_t shentsize) { _eh.e_shentsize = shentsize; }
1190 void e_shnum(uint16_t shnum) { _eh.e_shnum = shnum; }
1191 void e_shstrndx(uint16_t shstrndx) { _eh.e_shstrndx = shstrndx; }
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001192 uint64_t fileSize() { return sizeof (Elf_Ehdr); }
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001193
Michael J. Spencera2c97272013-01-04 21:09:21 +00001194 static inline bool classof(
1195 const Chunk<target_endianness, max_align, is64Bits> *c) {
1196 return c->Kind() ==
1197 Chunk<target_endianness, max_align, is64Bits>::K_ELFHeader;
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001198 }
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001199
Michael J. Spencera2c97272013-01-04 21:09:21 +00001200 void write(ELFWriter *writer,
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001201 OwningPtr<FileOutputBuffer> &buffer) {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001202 uint8_t *chunkBuffer = buffer->getBufferStart();
1203 uint8_t *atomContent = chunkBuffer + this->fileOffset();
1204 memcpy(atomContent, &_eh, fileSize());
1205 }
1206
1207 void finalize() { }
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001208
1209private:
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001210 Elf_Ehdr _eh;
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001211};
1212
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001213/// \brief An ELFProgramHeader represents the Elf[32/64]_Phdr structure at the
1214/// start of an ELF executable file.
Michael J. Spencera2c97272013-01-04 21:09:21 +00001215template<support::endianness target_endianness,
1216 std::size_t max_align,
1217 bool is64Bits>
1218class ELFProgramHeader : public Chunk<target_endianness, max_align, is64Bits> {
Hemant Kulkarni08e410292012-10-01 23:53:20 +00001219public:
Michael J. Spencerfd3981d2013-01-06 05:40:27 +00001220 typedef Elf_Phdr_Impl<target_endianness, max_align, is64Bits> Elf_Phdr;
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001221
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001222 ELFProgramHeader()
Michael J. Spencera2c97272013-01-04 21:09:21 +00001223 : Chunk<target_endianness, max_align, is64Bits>(
1224 "elfphdr",
Reid Klecknere974bd12013-01-05 02:21:42 +00001225 Chunk<target_endianness, max_align, is64Bits>::K_ELFProgramHeader) {
Michael J. Spencer1ac382f02013-01-07 08:00:04 +00001226 this->_align2 = is64Bits ? 8 : 4;
Reid Klecknere974bd12013-01-05 02:21:42 +00001227 resetProgramHeaders();
1228 }
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001229
Michael J. Spencera2c97272013-01-04 21:09:21 +00001230 bool addSegment(Segment<target_endianness, max_align, is64Bits> *segment) {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001231 Elf_Phdr *phdr = nullptr;
1232 bool ret = false;
1233
Michael J. Spencera2c97272013-01-04 21:09:21 +00001234 for (auto sei = segment->slices_begin(), see = segment->slices_end();
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001235 sei != see; ++sei) {
1236 if (_phi == _ph.end()) {
1237 phdr = new(_allocator.Allocate<Elf_Phdr>()) Elf_Phdr;
1238 _ph.push_back(phdr);
1239 _phi = _ph.end();
1240 ret = true;
1241 } else {
1242 phdr = (*_phi);
1243 ++_phi;
1244 }
1245 phdr->p_type = segment->segmentType();
1246 phdr->p_offset = (*sei)->fileOffset();
1247 phdr->p_vaddr = (*sei)->virtualAddr();
1248 phdr->p_paddr = (*sei)->virtualAddr();
1249 phdr->p_filesz = (*sei)->fileSize();
1250 phdr->p_memsz = (*sei)->memSize();
1251 phdr->p_flags = segment->flags();
Michael J. Spencera2c97272013-01-04 21:09:21 +00001252 phdr->p_align = (phdr->p_type == llvm::ELF::PT_LOAD) ?
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001253 segment->pageSize() : (*sei)->align2();
1254 }
Michael J. Spencer1ac382f02013-01-07 08:00:04 +00001255
1256 this->_fsize = fileSize();
1257 this->_msize = this->_fsize;
1258
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001259 return ret;
1260 }
1261
1262 void resetProgramHeaders() {
Michael J. Spencera2c97272013-01-04 21:09:21 +00001263 _phi = _ph.begin();
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001264 }
1265
Michael J. Spencera2c97272013-01-04 21:09:21 +00001266 uint64_t fileSize() {
Michael J. Spencer1ac382f02013-01-07 08:00:04 +00001267 return sizeof(Elf_Phdr) * _ph.size();
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001268 }
1269
Michael J. Spencera2c97272013-01-04 21:09:21 +00001270 static inline bool classof(
1271 const Chunk<target_endianness, max_align, is64Bits> *c) {
1272 return c->Kind() ==
1273 Chunk<target_endianness, max_align, is64Bits>::K_ELFProgramHeader;
1274 }
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001275
Michael J. Spencera2c97272013-01-04 21:09:21 +00001276 void write(ELFWriter *writer,
1277 OwningPtr<FileOutputBuffer> &buffer) {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001278 uint8_t *chunkBuffer = buffer->getBufferStart();
1279 uint8_t *dest = chunkBuffer + this->fileOffset();
1280 for (auto phi : _ph) {
1281 memcpy(dest, phi, sizeof(Elf_Phdr));
1282 dest += sizeof(Elf_Phdr);
1283 }
1284 }
1285
1286 void finalize() { }
1287
Michael J. Spencera2c97272013-01-04 21:09:21 +00001288 int64_t entsize() {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001289 return sizeof(Elf_Phdr);
1290 }
1291
1292 int64_t numHeaders() {
1293 return _ph.size();
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001294 }
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001295
1296private:
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001297 std::vector<Elf_Phdr *> _ph;
1298 typedef typename std::vector<Elf_Phdr *>::iterator ph_iter;
1299 ph_iter _phi;
1300 llvm::BumpPtrAllocator _allocator;
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001301};
1302
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001303/// \brief An ELFSectionHeader represents the Elf[32/64]_Shdr structure
1304/// at the end of the file
Michael J. Spencera2c97272013-01-04 21:09:21 +00001305template<support::endianness target_endianness,
1306 std::size_t max_align,
1307 bool is64Bits>
1308class ELFSectionHeader : public Chunk<target_endianness, max_align, is64Bits> {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001309public:
Michael J. Spencera2c97272013-01-04 21:09:21 +00001310 typedef Elf_Shdr_Impl<target_endianness, max_align, is64Bits> Elf_Shdr;
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001311
Michael J. Spencera2c97272013-01-04 21:09:21 +00001312 ELFSectionHeader(int32_t order)
1313 : Chunk<target_endianness, max_align, is64Bits>(
1314 "shdr",
1315 Chunk<target_endianness, max_align, is64Bits>::K_ELFSectionHeader) {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001316 this->_fsize = 0;
1317 this->_align2 = 8;
1318 this->setOrder(order);
1319 // The first element in the list is always NULL
1320 Elf_Shdr *nullshdr = new (_sectionAllocate.Allocate<Elf_Shdr>()) Elf_Shdr;
1321 ::memset(nullshdr, 0, sizeof (Elf_Shdr));
1322 _sectionInfo.push_back(nullshdr);
1323 this->_fsize += sizeof (Elf_Shdr);
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001324 }
1325
Michael J. Spencera2c97272013-01-04 21:09:21 +00001326 uint16_t fileSize() {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001327 return sizeof(Elf_Shdr) * _sectionInfo.size();
Hemant Kulkarni08e410292012-10-01 23:53:20 +00001328 }
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001329
Michael J. Spencera2c97272013-01-04 21:09:21 +00001330 void appendSection(
1331 MergedSections<target_endianness, max_align, is64Bits> *section) {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001332 Elf_Shdr *shdr = new (_sectionAllocate.Allocate<Elf_Shdr>()) Elf_Shdr;
1333 shdr->sh_name = _stringSection->addString(section->name());
1334 shdr->sh_type = section->type();
1335 shdr->sh_flags = section->flags();
1336 shdr->sh_offset = section->fileOffset();
1337 shdr->sh_addr = section->virtualAddr();
1338 shdr->sh_size = section->memSize();
1339 shdr->sh_link = section->link();
1340 shdr->sh_info = section->shinfo();
1341 shdr->sh_addralign = section->align2();
1342 shdr->sh_entsize = section->entsize();
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001343 _sectionInfo.push_back(shdr);
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001344 }
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001345
Michael J. Spencera2c97272013-01-04 21:09:21 +00001346 void updateSection(Section<target_endianness, max_align, is64Bits> *section) {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001347 Elf_Shdr *shdr = _sectionInfo[section->ordinal()];
1348 shdr->sh_type = section->type();
1349 shdr->sh_flags = section->flags();
1350 shdr->sh_offset = section->fileOffset();
1351 shdr->sh_addr = section->virtualAddr();
1352 shdr->sh_size = section->fileSize();
1353 shdr->sh_link = section->link();
1354 shdr->sh_info = section->shinfo();
1355 shdr->sh_addralign = section->align2();
1356 shdr->sh_entsize = section->entsize();
1357 }
1358
Michael J. Spencera2c97272013-01-04 21:09:21 +00001359 static inline bool classof(
1360 const Chunk<target_endianness, max_align, is64Bits> *c) {
1361 return c->getChunkKind() ==
1362 Chunk<target_endianness, max_align, is64Bits>::K_ELFSectionHeader;
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001363 }
1364
Michael J. Spencera2c97272013-01-04 21:09:21 +00001365 void setStringSection(
1366 ELFStringTable<target_endianness, max_align, is64Bits> *s) {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001367 _stringSection = s;
1368 }
1369
Michael J. Spencera2c97272013-01-04 21:09:21 +00001370 void write(ELFWriter *writer,
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001371 OwningPtr<FileOutputBuffer> &buffer) {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001372 uint8_t *chunkBuffer = buffer->getBufferStart();
1373 uint8_t *dest = chunkBuffer + this->fileOffset();
1374 for (auto shi : _sectionInfo) {
1375 memcpy(dest, shi, sizeof(Elf_Shdr));
1376 dest += sizeof(Elf_Shdr);
1377 }
1378 _stringSection->write(writer, buffer);
1379 }
1380
1381 void finalize() { }
1382
Michael J. Spencera2c97272013-01-04 21:09:21 +00001383 int64_t entsize() {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001384 return sizeof(Elf_Shdr);
1385 }
1386
1387 int64_t numHeaders() {
1388 return _sectionInfo.size();
1389 }
1390
1391private:
Michael J. Spencera2c97272013-01-04 21:09:21 +00001392 ELFStringTable<target_endianness, max_align, is64Bits> *_stringSection;
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001393 std::vector<Elf_Shdr*> _sectionInfo;
1394 llvm::BumpPtrAllocator _sectionAllocate;
1395};
1396
Michael J. Spencera2c97272013-01-04 21:09:21 +00001397/// \brief The DefaultELFLayout class is used by the Writer to arrange
1398/// sections and segments in the order determined by the target ELF
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001399/// format. The writer creates a single instance of the DefaultELFLayout
Michael J. Spencera2c97272013-01-04 21:09:21 +00001400/// class
1401template<support::endianness target_endianness,
1402 std::size_t max_align,
1403 bool is64Bits>
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001404class DefaultELFLayout : public ELFLayout {
1405public:
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001406
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001407 // The order in which the sections appear in the output file
Michael J. Spencera2c97272013-01-04 21:09:21 +00001408 // If its determined, that the layout needs to change
1409 // just changing the order of enumerations would essentially
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001410 // change the layout in the output file
1411 enum DefaultSectionOrder {
1412 ORDER_NOT_DEFINED = 0,
1413 ORDER_INTERP,
1414 ORDER_NOTE,
1415 ORDER_HASH,
1416 ORDER_DYNAMIC_SYMBOLS,
1417 ORDER_DYNAMIC_STRINGS,
1418 ORDER_INIT,
1419 ORDER_TEXT,
1420 ORDER_PLT,
1421 ORDER_FINI,
1422 ORDER_RODATA,
1423 ORDER_EH_FRAME,
1424 ORDER_EH_FRAMEHDR,
1425 ORDER_CTORS,
1426 ORDER_DTORS,
1427 ORDER_DYNAMIC,
1428 ORDER_GOT,
1429 ORDER_GOT_PLT,
1430 ORDER_DATA,
1431 ORDER_BSS,
1432 ORDER_OTHER,
1433 ORDER_SECTION_STRINGS,
1434 ORDER_SYMBOL_TABLE,
1435 ORDER_STRING_TABLE,
1436 ORDER_SECTION_HEADERS
1437 };
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001438
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001439public:
1440
1441 // The Key used for creating Sections
Michael J. Spencera2c97272013-01-04 21:09:21 +00001442 // The sections are created using
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001443 // SectionName, [contentType, contentPermissions]
Michael J. Spencera2c97272013-01-04 21:09:21 +00001444 typedef std::pair<StringRef,
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001445 std::pair<int32_t, int32_t>> Key;
Michael J. Spencera2c97272013-01-04 21:09:21 +00001446 typedef typename std::vector<
1447 Chunk<target_endianness, max_align, is64Bits> *>::iterator ChunkIter;
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001448 // The key used for Segments
Michael J. Spencera2c97272013-01-04 21:09:21 +00001449 // The segments are created using
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001450 // SegmentName, Segment flags
1451 typedef std::pair<StringRef, int64_t> SegmentKey;
1452 // Merged Sections contain the map of Sectionnames to a vector of sections,
1453 // that have been merged to form a single section
Michael J. Spencera2c97272013-01-04 21:09:21 +00001454 typedef std::map<StringRef, MergedSections<
1455 target_endianness, max_align, is64Bits> *> MergedSectionMapT;
1456 typedef typename std::vector<MergedSections<
1457 target_endianness, max_align, is64Bits> *>::iterator MergedSectionIter;
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001458
1459 // HashKey for the Section
1460 class HashKey {
1461 public:
1462 int64_t operator() (const Key &k) const {
1463 // k.first = section Name
1464 // k.second = [contentType, Permissions]
1465 return llvm::hash_combine(k.first, k.second.first, k.second.second);
1466 }
1467 };
1468
1469 // HashKey for the Segment
1470 class SegmentHashKey {
1471 public:
1472 int64_t operator() (const SegmentKey &k) const {
1473 // k.first = SegmentName
1474 // k.second = SegmentFlags
1475 return llvm::hash_combine(k.first, k.second);
1476 }
1477 };
1478
Michael J. Spencera2c97272013-01-04 21:09:21 +00001479 typedef std::unordered_map<Key, Section<
1480 target_endianness, max_align, is64Bits>*, HashKey> SectionMapT;
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001481 typedef std::unordered_map<SegmentKey,
Michael J. Spencera2c97272013-01-04 21:09:21 +00001482 Segment<target_endianness, max_align, is64Bits>*,
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001483 SegmentHashKey> SegmentMapT;
1484
1485 DefaultELFLayout(const WriterOptionsELF &options):_options(options) { }
1486
1487 /// \brief Return the section order for a input section
1488 virtual SectionOrder getSectionOrder
1489 (const StringRef name,
1490 int32_t contentType,
1491 int32_t contentPermissions) {
1492 switch (contentType) {
1493 case DefinedAtom::typeCode:
1494 return llvm::StringSwitch<Reference::Kind>(name)
1495 .StartsWith(".eh_frame_hdr", ORDER_EH_FRAMEHDR)
1496 .StartsWith(".eh_frame", ORDER_EH_FRAME)
1497 .StartsWith(".init", ORDER_INIT)
1498 .StartsWith(".fini", ORDER_FINI)
1499 .StartsWith(".hash", ORDER_HASH)
1500 .Default(ORDER_TEXT);
1501
1502 case DefinedAtom::typeConstant:
Michael J. Spencera2c97272013-01-04 21:09:21 +00001503 return ORDER_RODATA;
1504
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001505 case DefinedAtom::typeData:
1506 return ORDER_DATA;
Michael J. Spencera2c97272013-01-04 21:09:21 +00001507
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001508 case DefinedAtom::typeZeroFill:
1509 return ORDER_BSS;
1510
1511 default:
1512 // If we get passed in a section push it to OTHER
Michael J. Spencera2c97272013-01-04 21:09:21 +00001513 if (contentPermissions == DefinedAtom::perm___)
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001514 return ORDER_OTHER;
Michael J. Spencera2c97272013-01-04 21:09:21 +00001515
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001516 return ORDER_NOT_DEFINED;
1517 }
1518 }
1519
1520 /// \brief This maps the input sections to the output section names
1521 StringRef getSectionName(const StringRef name,
1522 const int32_t contentType) {
Michael J. Spencera2c97272013-01-04 21:09:21 +00001523 if (contentType == DefinedAtom::typeZeroFill)
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001524 return ".bss";
Michael J. Spencera2c97272013-01-04 21:09:21 +00001525 if (name.startswith(".text"))
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001526 return ".text";
Michael J. Spencera2c97272013-01-04 21:09:21 +00001527 if (name.startswith(".rodata"))
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001528 return ".rodata";
1529 return name;
1530 }
1531
1532 /// \brief Gets the segment for a output section
Michael J. Spencera2c97272013-01-04 21:09:21 +00001533 virtual ELFLayout::SegmentType getSegmentType(
1534 Section<target_endianness, max_align, is64Bits> *section) const {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001535 switch(section->order()) {
1536 case ORDER_INTERP:
1537 return llvm::ELF::PT_INTERP;
1538
1539 case ORDER_TEXT:
1540 case ORDER_HASH:
1541 case ORDER_DYNAMIC_SYMBOLS:
1542 case ORDER_DYNAMIC_STRINGS:
1543 case ORDER_INIT:
1544 case ORDER_PLT:
1545 case ORDER_FINI:
1546 case ORDER_RODATA:
1547 case ORDER_EH_FRAME:
1548 case ORDER_EH_FRAMEHDR:
1549 return llvm::ELF::PT_LOAD;
1550
1551 case ORDER_NOTE:
1552 return llvm::ELF::PT_NOTE;
1553
1554 case ORDER_DYNAMIC:
1555 return llvm::ELF::PT_DYNAMIC;
1556
1557 case ORDER_CTORS:
1558 case ORDER_DTORS:
1559 case ORDER_GOT:
1560 return llvm::ELF::PT_GNU_RELRO;
1561
1562 case ORDER_GOT_PLT:
1563 case ORDER_DATA:
1564 case ORDER_BSS:
1565 return llvm::ELF::PT_LOAD;
1566
1567 default:
1568 return llvm::ELF::PT_NULL;
1569 }
1570 }
1571
1572 /// \brief Returns true/false depending on whether the section has a Output
1573 // segment or not
Michael J. Spencera2c97272013-01-04 21:09:21 +00001574 static bool hasOutputSegment(Section<target_endianness, max_align,
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001575 is64Bits> *section) {
1576 switch(section->order()) {
1577 case ORDER_INTERP:
1578 case ORDER_HASH:
1579 case ORDER_DYNAMIC_SYMBOLS:
1580 case ORDER_DYNAMIC_STRINGS:
1581 case ORDER_INIT:
1582 case ORDER_PLT:
1583 case ORDER_TEXT:
1584 case ORDER_FINI:
1585 case ORDER_RODATA:
1586 case ORDER_EH_FRAME:
1587 case ORDER_EH_FRAMEHDR:
1588 case ORDER_NOTE:
1589 case ORDER_DYNAMIC:
1590 case ORDER_CTORS:
1591 case ORDER_DTORS:
1592 case ORDER_GOT:
1593 case ORDER_GOT_PLT:
1594 case ORDER_DATA:
1595 case ORDER_BSS:
1596 return true;
1597
1598 default:
1599 return false;
1600 }
1601 }
1602
1603 // Adds an atom to the section
1604 virtual error_code addAtom(const Atom *atom) {
1605 const DefinedAtom *definedAtom = dyn_cast<DefinedAtom>(atom);
Michael J. Spencera2c97272013-01-04 21:09:21 +00001606 const StringRef sectionName =
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001607 getSectionName(definedAtom->customSectionName(),
1608 definedAtom->contentType());
Michael J. Spencera2c97272013-01-04 21:09:21 +00001609 const lld::DefinedAtom::ContentPermissions permissions =
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001610 definedAtom->permissions();
Michael J. Spencera2c97272013-01-04 21:09:21 +00001611 const lld::DefinedAtom::ContentType contentType =
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001612 definedAtom->contentType();
1613 const Key key(sectionName, std::make_pair(contentType, permissions));
Michael J. Spencera2c97272013-01-04 21:09:21 +00001614 const std::pair<Key, Section<target_endianness, max_align, is64Bits> *>
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001615 currentSection(key, nullptr);
Michael J. Spencera2c97272013-01-04 21:09:21 +00001616 std::pair<typename SectionMapT::iterator, bool>
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001617 sectionInsert(_sectionMap.insert(currentSection));
Michael J. Spencera2c97272013-01-04 21:09:21 +00001618 Section<target_endianness, max_align, is64Bits> *section;
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001619 // the section is already in the map
1620 if (!sectionInsert.second) {
1621 section = sectionInsert.first->second;
1622 section->setContentPermissions(permissions);
1623 }
1624 else {
1625 SectionOrder section_order = getSectionOrder(sectionName,
1626 contentType,
1627 permissions);
1628 section = new (_allocator.Allocate
Michael J. Spencera2c97272013-01-04 21:09:21 +00001629 <Section<target_endianness, max_align, is64Bits>>())
1630 Section<target_endianness, max_align, is64Bits>
1631 (sectionName, contentType,
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001632 permissions, section_order);
1633 sectionInsert.first->second = section;
1634 section->setOrder(section_order);
1635 _sections.push_back(section);
1636 }
1637 section->appendAtom(atom);
1638 return error_code::success();
1639 }
1640
1641 // Merge sections with the same name into a MergedSections
1642 void mergeSimiliarSections() {
Michael J. Spencera2c97272013-01-04 21:09:21 +00001643 MergedSections<target_endianness, max_align, is64Bits> *mergedSection;
1644
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001645 for (auto &si : _sections) {
Michael J. Spencera2c97272013-01-04 21:09:21 +00001646 const std::pair<StringRef,
1647 MergedSections<target_endianness, max_align, is64Bits> *>
1648 currentMergedSections(si->name(), nullptr);
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001649 std::pair<typename MergedSectionMapT::iterator, bool>
1650 mergedSectionInsert
1651 (_mergedSectionMap.insert(currentMergedSections));
1652 if (!mergedSectionInsert.second) {
1653 mergedSection = mergedSectionInsert.first->second;
1654 }
1655 else {
Michael J. Spencera2c97272013-01-04 21:09:21 +00001656 mergedSection = new (_allocator.Allocate<
1657 MergedSections<target_endianness, max_align, is64Bits>>())
1658 MergedSections<target_endianness, max_align, is64Bits>(si->name());
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001659 _mergedSections.push_back(mergedSection);
1660 mergedSectionInsert.first->second = mergedSection;
1661 }
1662 mergedSection->appendSection(si);
1663 }
1664 }
1665
1666 void assignSectionsToSegments() {
1667 // sort the sections by their order as defined by the layout
1668 std::stable_sort(_sections.begin(), _sections.end(),
Michael J. Spencera2c97272013-01-04 21:09:21 +00001669 [](Chunk<target_endianness, max_align, is64Bits> *A,
1670 Chunk<target_endianness, max_align, is64Bits> *B) {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001671 return A->order() < B->order();
1672 });
1673 // Merge all sections
1674 mergeSimiliarSections();
1675 // Set the ordinal after sorting the sections
1676 int ordinal = 1;
1677 for (auto &msi : _mergedSections) {
1678 (*msi).setOrdinal(ordinal);
1679 for (auto ai = (*msi).begin_sections(), ae = (*msi).end_sections();
1680 ai != ae; ++ai) {
1681 (*ai)->setOrdinal(ordinal);
1682 }
1683 ++ordinal;
1684 }
Michael J. Spencera2c97272013-01-04 21:09:21 +00001685 Section<target_endianness, max_align, is64Bits> *section;
1686 Segment<target_endianness, max_align, is64Bits> *segment;
1687 for (auto msi = merged_sections_begin(), mse = merged_sections_end();
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001688 msi != mse; ++msi) {
Michael J. Spencera2c97272013-01-04 21:09:21 +00001689 for (auto ai = (*msi)->begin_sections(), ae = (*msi)->end_sections();
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001690 ai != ae; ++ai) {
Michael J. Spencera2c97272013-01-04 21:09:21 +00001691 if ((*ai)->kind() ==
1692 Chunk<target_endianness, max_align, is64Bits>::K_ELFSection) {
1693 section = llvm::dyn_cast<
1694 Section<target_endianness, max_align, is64Bits>>(*ai);
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001695 if (!hasOutputSegment(section))
1696 continue;
1697 (*msi)->setHasSegment();
1698 section->setSegment(getSegmentType(section));
1699 const StringRef segmentName = section->segmentKindToStr();
1700 // Use the flags of the merged Section for the segment
1701 const SegmentKey key(segmentName, (*msi)->flags());
Michael J. Spencera2c97272013-01-04 21:09:21 +00001702 const std::pair<SegmentKey,
1703 Segment<target_endianness, max_align, is64Bits> *>
1704 currentSegment(key, nullptr);
1705 std::pair<typename SegmentMapT::iterator, bool>
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001706 segmentInsert(_segmentMap.insert(currentSegment));
1707
1708 if (!segmentInsert.second) {
1709 segment = segmentInsert.first->second;
1710 } else {
1711 segment = new (_allocator.Allocate
Michael J. Spencera2c97272013-01-04 21:09:21 +00001712 <Segment<target_endianness, max_align, is64Bits>>())
1713 Segment<target_endianness, max_align, is64Bits>
1714 (segmentName, getSegmentType(section),
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001715 _options);
1716 segmentInsert.first->second = segment;
1717 _segments.push_back(segment);
1718 }
1719 segment->append(section);
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001720 }
1721 }
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001722 }
1723 }
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001724
Michael J. Spencera2c97272013-01-04 21:09:21 +00001725 void addSection(Chunk<target_endianness, max_align, is64Bits> *c) {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001726 _sections.push_back(c);
1727 }
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001728
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001729 void assignFileOffsets() {
Michael J. Spencera2c97272013-01-04 21:09:21 +00001730 std::sort(_segments.begin(),
1731 _segments.end(),
1732 Segment<target_endianness, max_align, is64Bits>::compareSegments);
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001733 int ordinal = 0;
1734 // Compute the number of segments that might be needed, so that the
1735 // size of the program header can be computed
1736 uint64_t offset = 0;
1737 for (auto si : _segments) {
1738 si->setOrdinal(++ordinal);
1739 si->assignOffsets(offset);
1740 offset += si->fileSize();
1741 }
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001742 }
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001743
Michael J. Spencera2c97272013-01-04 21:09:21 +00001744 void setELFHeader(ELFHeader<target_endianness, max_align, is64Bits> *e) {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001745 _elfHeader = e;
1746 }
Hemant Kulkarni87dbac02012-11-13 21:34:45 +00001747
Michael J. Spencera2c97272013-01-04 21:09:21 +00001748 void setProgramHeader(
1749 ELFProgramHeader<target_endianness, max_align, is64Bits> *p) {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001750 _programHeader = p;
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001751 }
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001752
1753 void assignVirtualAddress() {
Michael J. Spencer1ac382f02013-01-07 08:00:04 +00001754 if (_segments.empty())
1755 return;
1756
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001757 uint64_t virtualAddress = _options.baseAddress();
1758
Michael J. Spencer1ac382f02013-01-07 08:00:04 +00001759 // HACK: This is a super dirty hack. The elf header and program header are
1760 // not part of a section, but we need them to be loaded at the base address
1761 // so that AT_PHDR is set correctly by the loader and so they are accessible
1762 // at runtime. To do this we simply prepend them to the first Segment and
1763 // let the layout logic take care of it.
1764 _segments[0]->prepend(_programHeader);
1765 _segments[0]->prepend(_elfHeader);
1766
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001767 bool newSegmentHeaderAdded = true;
Michael J. Spencer1ac382f02013-01-07 08:00:04 +00001768 while (true) {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001769 for (auto si : _segments) {
1770 newSegmentHeaderAdded = _programHeader->addSegment(si);
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001771 }
Michael J. Spencera2c97272013-01-04 21:09:21 +00001772 if (!newSegmentHeaderAdded)
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001773 break;
Michael J. Spencer1ac382f02013-01-07 08:00:04 +00001774 uint64_t fileoffset = 0;
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001775 uint64_t address = virtualAddress;
1776 // Fix the offsets after adding the program header
1777 for (auto &si : _segments) {
1778 // Align the segment to a page boundary
1779 fileoffset = llvm::RoundUpToAlignment(fileoffset, _options.pageSize());
1780 si->assignOffsets(fileoffset);
1781 fileoffset = si->fileOffset() + si->fileSize();
1782 }
1783 // start assigning virtual addresses
1784 for (auto si = _segments.begin(); si != _segments.end(); ++si) {
1785 (*si)->setVAddr(virtualAddress);
1786 // The first segment has the virtualAddress set to the base address as
1787 // we have added the file header and the program header dont align the
Michael J. Spencera2c97272013-01-04 21:09:21 +00001788 // first segment to the pagesize
Michael J. Spencer1ac382f02013-01-07 08:00:04 +00001789 (*si)->assignVirtualAddress(address);
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001790 (*si)->setMemSize(address - virtualAddress);
1791 virtualAddress = llvm::RoundUpToAlignment(address, _options.pageSize());
1792 }
1793 _programHeader->resetProgramHeaders();
1794 }
Michael J. Spencera2c97272013-01-04 21:09:21 +00001795 Section<target_endianness, max_align, is64Bits> *section;
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001796 // Fix the offsets of all the atoms within a section
1797 for (auto &si : _sections) {
Michael J. Spencera2c97272013-01-04 21:09:21 +00001798 section =
1799 llvm::dyn_cast<Section<target_endianness, max_align, is64Bits>>(si);
1800 if (section &&
1801 DefaultELFLayout<target_endianness,
1802 max_align, is64Bits>::hasOutputSegment(section))
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001803 section->assignOffsets(section->fileOffset());
1804 }
1805 // Set the size of the merged Sections
Michael J. Spencera2c97272013-01-04 21:09:21 +00001806 for (auto msi = merged_sections_begin(), mse = merged_sections_end();
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001807 msi != mse; ++msi) {
1808 uint64_t sectionfileoffset = 0;
1809 uint64_t startFileOffset = 0;
1810 uint64_t sectionsize = 0;
1811 bool isFirstSection = true;
Michael J. Spencera2c97272013-01-04 21:09:21 +00001812 for (auto si = (*msi)->begin_sections(); si != (*msi)->end_sections();
1813 ++si) {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001814 if (isFirstSection) {
1815 startFileOffset = (*si)->fileOffset();
1816 isFirstSection = false;
1817 }
1818 sectionfileoffset = (*si)->fileOffset();
1819 sectionsize = (*si)->fileSize();
1820 }
1821 sectionsize = (sectionfileoffset - startFileOffset) + sectionsize;
1822 (*msi)->setFileOffset(startFileOffset);
1823 (*msi)->setSize(sectionsize);
1824 }
1825 // Set the virtual addr of the merged Sections
Michael J. Spencera2c97272013-01-04 21:09:21 +00001826 for (auto msi = merged_sections_begin(), mse = merged_sections_end();
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001827 msi != mse; ++msi) {
1828 uint64_t sectionstartaddr = 0;
1829 uint64_t startaddr = 0;
1830 uint64_t sectionsize = 0;
1831 bool isFirstSection = true;
Michael J. Spencera2c97272013-01-04 21:09:21 +00001832 for (auto si = (*msi)->begin_sections(), se = (*msi)->end_sections();
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001833 si != se; ++si) {
1834 if (isFirstSection) {
1835 startaddr = (*si)->virtualAddr();
1836 isFirstSection = false;
1837 }
1838 sectionstartaddr = (*si)->virtualAddr();
1839 sectionsize = (*si)->memSize();
1840 }
1841 sectionsize = (sectionstartaddr - startaddr) + sectionsize;
1842 (*msi)->setMemSize(sectionsize);
1843 (*msi)->setAddr(startaddr);
1844 }
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001845 }
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001846
1847 void assignOffsetsForMiscSections() {
1848 uint64_t fileoffset = 0;
1849 uint64_t size = 0;
1850 for (auto si : _segments) {
1851 fileoffset = si->fileOffset();
1852 size = si->fileSize();
1853 }
1854 fileoffset = fileoffset + size;
Michael J. Spencera2c97272013-01-04 21:09:21 +00001855 Section<target_endianness, max_align, is64Bits> *section;
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001856 for (auto si : _sections) {
Michael J. Spencera2c97272013-01-04 21:09:21 +00001857 section =
1858 llvm::dyn_cast<Section<target_endianness, max_align, is64Bits>>(si);
1859 if (section &&
1860 DefaultELFLayout<target_endianness,
1861 max_align, is64Bits>::hasOutputSegment(section))
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001862 continue;
1863 fileoffset = llvm::RoundUpToAlignment(fileoffset, si->align2());
1864 si->setFileOffset(fileoffset);
1865 si->setVAddr(0);
1866 fileoffset += si->fileSize();
1867 }
Hemant Kulkarni08e410292012-10-01 23:53:20 +00001868 }
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001869
1870 void finalize() {
1871 for (auto &si : _sections) {
1872 si->finalize();
1873 }
1874 }
1875
1876 bool findAtomAddrByName(const StringRef name, uint64_t &addr) {
Michael J. Spencera2c97272013-01-04 21:09:21 +00001877 Section<target_endianness, max_align, is64Bits> *section;
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001878 for (auto ai = _sections.begin(); ai != _sections.end(); ++ai) {
Michael J. Spencera2c97272013-01-04 21:09:21 +00001879 if ((*ai)->kind() ==
1880 Chunk<target_endianness, max_align, is64Bits>::K_ELFSection) {
1881 section =
1882 llvm::dyn_cast<Section<target_endianness, max_align, is64Bits>>(*ai);
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001883 if (section->findAtomAddrByName(name, addr))
1884 return true;
1885 }
1886 }
Michael J. Spencera2c97272013-01-04 21:09:21 +00001887 return false;
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001888 }
1889
Michael J. Spencera2c97272013-01-04 21:09:21 +00001890 MergedSectionIter merged_sections_begin() {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001891 return _mergedSections.begin();
1892 }
1893
Michael J. Spencera2c97272013-01-04 21:09:21 +00001894 MergedSectionIter merged_sections_end() {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001895 return _mergedSections.end();
1896 }
1897
1898 ChunkIter sections_begin() {
1899 return _sections.begin();
1900 }
1901 ChunkIter sections_end() {
1902 return _sections.end();
1903 }
1904
1905 ChunkIter segments_begin() {
1906 return _segments.begin();
1907 }
1908
1909 ChunkIter segments_end() {
1910 return _segments.end();
1911 }
1912
Michael J. Spencera2c97272013-01-04 21:09:21 +00001913 ELFHeader<target_endianness, max_align, is64Bits> *elfHeader() {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001914 return _elfHeader;
1915 }
1916
Michael J. Spencera2c97272013-01-04 21:09:21 +00001917 ELFProgramHeader<target_endianness, max_align, is64Bits> *elfProgramHeader() {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001918 return _programHeader;
Hemant Kulkarni08e410292012-10-01 23:53:20 +00001919 }
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001920
1921private:
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001922 SectionMapT _sectionMap;
1923 MergedSectionMapT _mergedSectionMap;
1924 SegmentMapT _segmentMap;
Sid Manningdd110202012-09-25 18:22:09 +00001925
Michael J. Spencera2c97272013-01-04 21:09:21 +00001926 std::vector<Chunk<target_endianness, max_align, is64Bits> *> _sections;
1927 std::vector<Segment<target_endianness, max_align, is64Bits> *> _segments;
1928 std::vector<MergedSections<target_endianness, max_align, is64Bits> *>
1929 _mergedSections;
1930 ELFHeader<target_endianness, max_align, is64Bits> *_elfHeader;
1931 ELFProgramHeader<target_endianness, max_align, is64Bits> *_programHeader;
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001932 llvm::BumpPtrAllocator _allocator;
1933 const WriterOptionsELF &_options;
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001934};
1935
1936//===----------------------------------------------------------------------===//
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001937// ELFExecutableWriter Class
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001938//===----------------------------------------------------------------------===//
Michael J. Spencera2c97272013-01-04 21:09:21 +00001939template<support::endianness target_endianness,
1940 std::size_t max_align,
1941 bool is64Bits>
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001942class ELFExecutableWriter : public ELFWriter {
1943public:
Michael J. Spencera2c97272013-01-04 21:09:21 +00001944 typedef Elf_Shdr_Impl<target_endianness, max_align, is64Bits> Elf_Shdr;
1945 typedef Elf_Sym_Impl<target_endianness, max_align, is64Bits> Elf_Sym;
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001946
1947 ELFExecutableWriter(const WriterOptionsELF &options);
1948
1949private:
Michael J. Spencera2c97272013-01-04 21:09:21 +00001950 // build the sections that need to be created
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001951 void buildChunks(const lld::File &file);
1952 virtual error_code writeFile(const lld::File &File, StringRef path);
1953 void buildAtomToAddressMap();
1954 void buildSymbolTable ();
1955 void buildSectionHeaderTable();
1956 void assignSectionsWithNoSegments();
1957 void addAbsoluteUndefinedSymbols(const lld::File &File);
1958
Michael J. Spencera2c97272013-01-04 21:09:21 +00001959 uint64_t addressOfAtom(const Atom *atom) {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001960 return _atomToAddressMap[atom];
1961 }
1962
1963 KindHandler *kindHandler() { return _referenceKindHandler.get(); }
1964
1965 void createDefaultSections();
1966
1967 const WriterOptionsELF &_options;
1968
1969 typedef llvm::DenseMap<const Atom*, uint64_t> AtomToAddress;
1970 std::unique_ptr<KindHandler> _referenceKindHandler;
1971 AtomToAddress _atomToAddressMap;
1972 llvm::BumpPtrAllocator _chunkAllocate;
Michael J. Spencera2c97272013-01-04 21:09:21 +00001973 DefaultELFLayout<target_endianness, max_align, is64Bits> *_layout;
1974 ELFHeader<target_endianness, max_align, is64Bits> *_elfHeader;
1975 ELFProgramHeader<target_endianness, max_align, is64Bits> *_programHeader;
1976 ELFSymbolTable<target_endianness, max_align, is64Bits> * _symtab;
1977 ELFStringTable<target_endianness, max_align, is64Bits> *_strtab;
1978 ELFStringTable<target_endianness, max_align, is64Bits> *_shstrtab;
1979 ELFSectionHeader<target_endianness, max_align, is64Bits> *_shdrtab;
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001980};
1981
1982//===----------------------------------------------------------------------===//
1983// ELFExecutableWriter
1984//===----------------------------------------------------------------------===//
Michael J. Spencera2c97272013-01-04 21:09:21 +00001985template<support::endianness target_endianness,
1986 std::size_t max_align,
1987 bool is64Bits>
1988ELFExecutableWriter<target_endianness, max_align, is64Bits>
1989 ::ELFExecutableWriter(const WriterOptionsELF &options)
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001990 : _options(options)
Sid Manning42064e52012-10-09 02:20:47 +00001991 , _referenceKindHandler(KindHandler::makeHandler(_options.machine(),
Michael J. Spencera2c97272013-01-04 21:09:21 +00001992 target_endianness)) {
1993 _layout =
1994 new DefaultELFLayout<target_endianness, max_align, is64Bits>(options);
Shankar Easwaran495d38b2012-12-27 02:26:30 +00001995}
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00001996
Michael J. Spencera2c97272013-01-04 21:09:21 +00001997template<support::endianness target_endianness,
1998 std::size_t max_align,
1999 bool is64Bits>
2000void ELFExecutableWriter<target_endianness, max_align, is64Bits>
Shankar Easwaran495d38b2012-12-27 02:26:30 +00002001 ::buildChunks(const lld::File &file){
2002 for (const DefinedAtom *definedAtom : file.defined() ) {
2003 _layout->addAtom(definedAtom);
2004 }
2005}
2006
Michael J. Spencera2c97272013-01-04 21:09:21 +00002007template<support::endianness target_endianness,
2008 std::size_t max_align,
2009 bool is64Bits>
2010void ELFExecutableWriter<target_endianness, max_align, is64Bits>
2011 ::buildSymbolTable () {
2012 Section<target_endianness, max_align, is64Bits> *section;
2013 for (auto si = _layout->sections_begin(); si != _layout->sections_end();
2014 ++si) {
2015 if ((*si)->kind() !=
2016 Chunk<target_endianness, max_align, is64Bits>::K_ELFSection)
Shankar Easwaran495d38b2012-12-27 02:26:30 +00002017 continue;
Michael J. Spencera2c97272013-01-04 21:09:21 +00002018 section =
2019 llvm::dyn_cast<Section<target_endianness, max_align, is64Bits>>(*si);
Shankar Easwaran495d38b2012-12-27 02:26:30 +00002020 for (auto ai = section->atoms_begin(); ai != section->atoms_end(); ++ai) {
2021 _symtab->addSymbol(ai->first, section->ordinal(), ai->second.second);
Hemant Kulkarni736f7fb2012-11-21 21:07:36 +00002022 }
2023 }
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00002024}
2025
Michael J. Spencera2c97272013-01-04 21:09:21 +00002026template<support::endianness target_endianness,
2027 std::size_t max_align,
2028 bool is64Bits>
2029void ELFExecutableWriter<target_endianness, max_align, is64Bits>
2030 ::addAbsoluteUndefinedSymbols(const lld::File &file) {
Hemant Kulkarni08e410292012-10-01 23:53:20 +00002031 for (const UndefinedAtom *a : file.undefined()) {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00002032 _symtab->addSymbol(a, ELF::SHN_UNDEF);
Hemant Kulkarni08e410292012-10-01 23:53:20 +00002033 }
Michael J. Spencera2c97272013-01-04 21:09:21 +00002034
Hemant Kulkarni08e410292012-10-01 23:53:20 +00002035 for (const AbsoluteAtom *a : file.absolute()) {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00002036 _symtab->addSymbol(a, ELF::SHN_ABS);
Hemant Kulkarni08e410292012-10-01 23:53:20 +00002037 }
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00002038}
2039
Michael J. Spencera2c97272013-01-04 21:09:21 +00002040template<support::endianness target_endianness,
2041 std::size_t max_align,
2042 bool is64Bits>
2043void ELFExecutableWriter<target_endianness, max_align, is64Bits>
2044 ::buildAtomToAddressMap () {
2045 Section<target_endianness, max_align, is64Bits> *section;
2046 for (auto si = _layout->sections_begin();
Shankar Easwaran495d38b2012-12-27 02:26:30 +00002047 si != _layout->sections_end(); ++si) {
Michael J. Spencera2c97272013-01-04 21:09:21 +00002048 if ((*si)->kind() !=
2049 Chunk<target_endianness, max_align, is64Bits>::K_ELFSection)
Shankar Easwaran495d38b2012-12-27 02:26:30 +00002050 continue;
Michael J. Spencera2c97272013-01-04 21:09:21 +00002051 section =
2052 llvm::dyn_cast<Section<target_endianness, max_align, is64Bits>>(*si);
Shankar Easwaran495d38b2012-12-27 02:26:30 +00002053 for (auto ai = section->atoms_begin(); ai != section->atoms_end(); ++ai) {
2054 _atomToAddressMap[ai->first] = (ai)->second.second;
Sid Manningdd110202012-09-25 18:22:09 +00002055 }
2056 }
Sid Manningdd110202012-09-25 18:22:09 +00002057}
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00002058
Michael J. Spencera2c97272013-01-04 21:09:21 +00002059template<support::endianness target_endianness,
2060 std::size_t max_align,
2061 bool is64Bits>
2062void ELFExecutableWriter<target_endianness, max_align, is64Bits>
2063 ::buildSectionHeaderTable() {
2064 for (auto msi = _layout->merged_sections_begin();
Shankar Easwaran495d38b2012-12-27 02:26:30 +00002065 msi != _layout->merged_sections_end(); ++msi) {
Michael J. Spencera2c97272013-01-04 21:09:21 +00002066 if ((*msi)->kind() !=
2067 Chunk<target_endianness, max_align, is64Bits>::K_ELFSection)
Shankar Easwaran495d38b2012-12-27 02:26:30 +00002068 continue;
2069 if ((*msi)->hasSegment())
2070 _shdrtab->appendSection(*msi);
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00002071 }
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00002072}
2073
Michael J. Spencera2c97272013-01-04 21:09:21 +00002074template<support::endianness target_endianness,
2075 std::size_t max_align,
2076 bool is64Bits>
2077void ELFExecutableWriter<target_endianness, max_align, is64Bits>
2078 ::assignSectionsWithNoSegments() {
2079 Section<target_endianness, max_align, is64Bits> *section;
2080 for (auto msi = _layout->merged_sections_begin();
Shankar Easwaran495d38b2012-12-27 02:26:30 +00002081 msi != _layout->merged_sections_end(); ++msi) {
Michael J. Spencera2c97272013-01-04 21:09:21 +00002082 if ((*msi)->kind() !=
2083 Chunk<target_endianness, max_align, is64Bits>::K_ELFSection)
Shankar Easwaran495d38b2012-12-27 02:26:30 +00002084 continue;
2085 if (!(*msi)->hasSegment())
2086 _shdrtab->appendSection(*msi);
2087 }
2088 _layout->assignOffsetsForMiscSections();
Michael J. Spencera2c97272013-01-04 21:09:21 +00002089 for (auto si = _layout->sections_begin();
Shankar Easwaran495d38b2012-12-27 02:26:30 +00002090 si != _layout->sections_end(); ++si) {
Michael J. Spencera2c97272013-01-04 21:09:21 +00002091 if ((*si)->kind() !=
2092 Chunk<target_endianness, max_align, is64Bits>::K_ELFSection)
Shankar Easwaran495d38b2012-12-27 02:26:30 +00002093 continue;
Michael J. Spencera2c97272013-01-04 21:09:21 +00002094 section =
2095 llvm::dyn_cast<Section<target_endianness, max_align, is64Bits>>(*si);
2096 if (!DefaultELFLayout<target_endianness, max_align, is64Bits>
2097 ::hasOutputSegment(section))
Shankar Easwaran495d38b2012-12-27 02:26:30 +00002098 _shdrtab->updateSection(section);
2099 }
2100}
2101
Michael J. Spencera2c97272013-01-04 21:09:21 +00002102template<support::endianness target_endianness,
2103 std::size_t max_align,
2104 bool is64Bits>
2105error_code ELFExecutableWriter<target_endianness, max_align, is64Bits>
2106 ::writeFile(const lld::File &file, StringRef path) {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00002107 buildChunks(file);
2108 // Create the default sections like the symbol table, string table, and the
2109 // section string table
2110 createDefaultSections();
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00002111
Shankar Easwaran495d38b2012-12-27 02:26:30 +00002112 // Set the Layout
2113 _layout->assignSectionsToSegments();
2114 _layout->assignFileOffsets();
2115 _layout->assignVirtualAddress();
2116
2117 // Build the Atom To Address map for applying relocations
2118 buildAtomToAddressMap();
2119
2120 // Create symbol table and section string table
2121 buildSymbolTable();
2122
2123 // add other symbols
2124 addAbsoluteUndefinedSymbols(file);
2125
2126 // Finalize the layout by calling the finalize() functions
2127 _layout->finalize();
2128
2129 // build Section Header table
2130 buildSectionHeaderTable();
2131
2132 // assign Offsets and virtual addresses
2133 // for sections with no segments
2134 assignSectionsWithNoSegments();
2135
2136 uint64_t totalSize = _shdrtab->fileOffset() + _shdrtab->fileSize();
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00002137
2138 OwningPtr<FileOutputBuffer> buffer;
2139 error_code ec = FileOutputBuffer::create(path,
2140 totalSize, buffer,
2141 FileOutputBuffer::F_executable);
2142 if (ec)
2143 return ec;
2144
Shankar Easwaran495d38b2012-12-27 02:26:30 +00002145 _elfHeader->e_ident(ELF::EI_CLASS, (_options.is64Bit() ? ELF::ELFCLASS64
2146 : ELF::ELFCLASS32));
Michael J. Spencera2c97272013-01-04 21:09:21 +00002147 _elfHeader->e_ident(ELF::EI_DATA, _options.endianness() == llvm::support::big
Shankar Easwaran495d38b2012-12-27 02:26:30 +00002148 ? ELF::ELFDATA2MSB : ELF::ELFDATA2LSB);
2149 _elfHeader->e_ident(ELF::EI_VERSION, 1);
2150 _elfHeader->e_ident(ELF::EI_OSABI, 0);
2151 _elfHeader->e_type(_options.type());
2152 _elfHeader->e_machine(_options.machine());
2153 _elfHeader->e_version(1);
2154 _elfHeader->e_entry(0ULL);
2155 _elfHeader->e_phoff(_programHeader->fileOffset());
2156 _elfHeader->e_shoff(_shdrtab->fileOffset());
2157 _elfHeader->e_phentsize(_programHeader->entsize());
2158 _elfHeader->e_phnum(_programHeader->numHeaders());
2159 _elfHeader->e_shentsize(_shdrtab->entsize());
2160 _elfHeader->e_shnum(_shdrtab->numHeaders());
2161 _elfHeader->e_shstrndx(_shstrtab->ordinal());
2162 uint64_t virtualAddr = 0;
2163 _layout->findAtomAddrByName("_start", virtualAddr);
2164 _elfHeader->e_entry(virtualAddr);
Michael J. Spencer1ac382f02013-01-07 08:00:04 +00002165
2166 // HACK: We have to write out the header and program header here even though
2167 // they are a member of a segment because only sections are written in the
2168 // following loop.
Shankar Easwaran495d38b2012-12-27 02:26:30 +00002169 _elfHeader->write(this, buffer);
2170 _programHeader->write(this, buffer);
2171
Michael J. Spencer1ac382f02013-01-07 08:00:04 +00002172 for (auto si = _layout->sections_begin(); si != _layout->sections_end(); ++si)
2173 (*si)->write(this, buffer);
2174
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00002175 return buffer->commit();
2176}
Nick Kledzikabb69812012-05-31 22:34:00 +00002177
Michael J. Spencera2c97272013-01-04 21:09:21 +00002178template<support::endianness target_endianness,
2179 std::size_t max_align,
2180 bool is64Bits>
2181void ELFExecutableWriter<target_endianness, max_align, is64Bits>
2182 ::createDefaultSections() {
2183 _elfHeader =
2184 new ELFHeader<target_endianness, max_align, is64Bits>();
2185 _programHeader =
2186 new ELFProgramHeader<target_endianness, max_align, is64Bits>();
Shankar Easwaran495d38b2012-12-27 02:26:30 +00002187 _layout->setELFHeader(_elfHeader);
2188 _layout->setProgramHeader(_programHeader);
2189
Michael J. Spencera2c97272013-01-04 21:09:21 +00002190 _symtab = new ELFSymbolTable<target_endianness, max_align, is64Bits>(
2191 ".symtab",
2192 DefaultELFLayout<target_endianness, max_align, is64Bits>
2193 ::ORDER_SYMBOL_TABLE);
2194 _strtab = new ELFStringTable<target_endianness, max_align, is64Bits>(
2195 ".strtab",
2196 DefaultELFLayout<target_endianness, max_align, is64Bits>
2197 ::ORDER_STRING_TABLE);
2198 _shstrtab = new ELFStringTable<target_endianness, max_align, is64Bits>(
2199 ".shstrtab",
2200 DefaultELFLayout<target_endianness, max_align, is64Bits>
2201 ::ORDER_SECTION_STRINGS);
2202 _shdrtab = new ELFSectionHeader<target_endianness, max_align, is64Bits>(
2203 DefaultELFLayout<target_endianness, max_align, is64Bits>
2204 ::ORDER_SECTION_HEADERS);
Shankar Easwaran495d38b2012-12-27 02:26:30 +00002205 _layout->addSection(_symtab);
2206 _layout->addSection(_strtab);
2207 _layout->addSection(_shstrtab);
2208 _shdrtab->setStringSection(_shstrtab);
2209 _symtab->setStringSection(_strtab);
2210 _layout->addSection(_shdrtab);
Sid Manningdd110202012-09-25 18:22:09 +00002211}
Nick Kledzikabb69812012-05-31 22:34:00 +00002212} // namespace elf
2213
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00002214Writer *createWriterELF(const WriterOptionsELF &options) {
Shankar Easwaran495d38b2012-12-27 02:26:30 +00002215 // Set the default layout to be the static executable layout
Michael J. Spencera2c97272013-01-04 21:09:21 +00002216 // We would set the layout to a dynamic executable layout
Shankar Easwaran495d38b2012-12-27 02:26:30 +00002217 // if we came across any shared libraries in the process
Michael J. Spencera2c97272013-01-04 21:09:21 +00002218
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00002219 if (!options.is64Bit() && options.endianness() == llvm::support::little)
Michael J. Spencera2c97272013-01-04 21:09:21 +00002220 return new elf::ELFExecutableWriter<support::little, 4, false>(options);
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00002221 else if (options.is64Bit() && options.endianness() == llvm::support::little)
Michael J. Spencera2c97272013-01-04 21:09:21 +00002222 return new elf::ELFExecutableWriter<support::little, 8, true>(options);
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00002223 else if (!options.is64Bit() && options.endianness() == llvm::support::big)
Michael J. Spencera2c97272013-01-04 21:09:21 +00002224 return new elf::ELFExecutableWriter<support::big, 4, false>(options);
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00002225 else if (options.is64Bit() && options.endianness() == llvm::support::big)
Michael J. Spencera2c97272013-01-04 21:09:21 +00002226 return new elf::ELFExecutableWriter<support::big, 8, true>(options);
Nick Kledzikabb69812012-05-31 22:34:00 +00002227
Hemant Kulkarni927bbc22012-09-14 16:11:34 +00002228 llvm_unreachable("Invalid Options!");
Nick Kledzikabb69812012-05-31 22:34:00 +00002229}
Nick Kledzikabb69812012-05-31 22:34:00 +00002230} // namespace lld