blob: b233741e5fb9e7bcda3fa70158dc83ceb90643c9 [file] [log] [blame]
Nick Kledzike34182f2013-11-06 21:36:55 +00001//===- lib/ReaderWriter/MachO/MachONormalizedFileFromAtoms.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///
11/// \file Converts from in-memory Atoms to in-memory normalized mach-o.
12///
13/// +------------+
14/// | normalized |
15/// +------------+
16/// ^
17/// |
18/// |
Shankar Easwaran3d8de472014-01-27 03:09:26 +000019/// +-------+
Nick Kledzike34182f2013-11-06 21:36:55 +000020/// | Atoms |
Shankar Easwaran3d8de472014-01-27 03:09:26 +000021/// +-------+
Nick Kledzike34182f2013-11-06 21:36:55 +000022
23#include "MachONormalizedFile.h"
24#include "ReferenceKinds.h"
25
26#include "lld/Core/Error.h"
27#include "lld/Core/LLVM.h"
28
29#include "llvm/ADT/StringRef.h"
30#include "llvm/ADT/StringSwitch.h"
31#include "llvm/Support/Casting.h"
32#include "llvm/Support/Debug.h"
33#include "llvm/Support/ErrorHandling.h"
34#include "llvm/Support/Format.h"
35#include "llvm/Support/MachO.h"
36#include "llvm/Support/system_error.h"
37
38#include <map>
39
40using llvm::StringRef;
Nick Kledzike34182f2013-11-06 21:36:55 +000041using llvm::isa;
42using namespace llvm::MachO;
43using namespace lld::mach_o::normalized;
44using namespace lld;
45
46namespace {
47
48struct AtomInfo {
49 const DefinedAtom *atom;
50 uint64_t offsetInSection;
51};
52
53struct SectionInfo {
54 SectionInfo(StringRef seg, StringRef sect, SectionType type, uint32_t attr=0);
Shankar Easwaran3d8de472014-01-27 03:09:26 +000055
Nick Kledzike34182f2013-11-06 21:36:55 +000056 StringRef segmentName;
57 StringRef sectionName;
58 SectionType type;
59 uint32_t attributes;
60 uint64_t address;
61 uint64_t size;
62 uint32_t alignment;
63 std::vector<AtomInfo> atomsAndOffsets;
64 uint32_t normalizedSectionIndex;
65 uint32_t finalSectionIndex;
66};
67
Shankar Easwaran3d8de472014-01-27 03:09:26 +000068SectionInfo::SectionInfo(StringRef sg, StringRef sct, SectionType t, uint32_t a)
69 : segmentName(sg), sectionName(sct), type(t), attributes(a),
70 address(0), size(0), alignment(0),
Nick Kledzike34182f2013-11-06 21:36:55 +000071 normalizedSectionIndex(0), finalSectionIndex(0) {
72}
73
74struct SegmentInfo {
75 SegmentInfo(StringRef name);
Shankar Easwaran3d8de472014-01-27 03:09:26 +000076
Nick Kledzike34182f2013-11-06 21:36:55 +000077 StringRef name;
78 uint64_t address;
79 uint64_t size;
80 uint32_t access;
81 std::vector<SectionInfo*> sections;
82};
83
Shankar Easwaran3d8de472014-01-27 03:09:26 +000084SegmentInfo::SegmentInfo(StringRef n)
Nick Kledzike34182f2013-11-06 21:36:55 +000085 : name(n), address(0), size(0), access(0) {
86}
87
88
89class Util {
90public:
91 Util(const MachOLinkingContext &ctxt) : _context(ctxt), _entryAtom(nullptr) {}
92
93 void assignAtomsToSections(const lld::File &atomFile);
94 void organizeSections();
95 void assignAddressesToSections();
96 uint32_t fileFlags();
97 void copySegmentInfo(NormalizedFile &file);
98 void copySections(NormalizedFile &file);
99 void buildAtomToAddressMap();
100 void addSymbols(const lld::File &atomFile, NormalizedFile &file);
101 void addIndirectSymbols(const lld::File &atomFile, NormalizedFile &file);
102 void addRebaseAndBindingInfo(const lld::File &, NormalizedFile &file);
103 void addSectionRelocs(const lld::File &, NormalizedFile &file);
104 void addDependentDylibs(const lld::File &, NormalizedFile &file);
105 void copyEntryPointAddress(NormalizedFile &file);
106
107private:
108 typedef std::map<DefinedAtom::ContentType, SectionInfo*> TypeToSection;
109 typedef llvm::DenseMap<const Atom*, uint64_t> AtomToAddress;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000110
Nick Kledzike34182f2013-11-06 21:36:55 +0000111 struct DylibInfo { int ordinal; bool hasWeak; bool hasNonWeak; };
112 typedef llvm::StringMap<DylibInfo> DylibPathToInfo;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000113
Nick Kledzike34182f2013-11-06 21:36:55 +0000114 SectionInfo *sectionForAtom(const DefinedAtom*);
115 SectionInfo *makeSection(DefinedAtom::ContentType);
116 void appendAtom(SectionInfo *sect, const DefinedAtom *atom);
117 SegmentInfo *segmentForName(StringRef segName);
118 void layoutSectionsInSegment(SegmentInfo *seg, uint64_t &addr);
119 void layoutSectionsInTextSegment(SegmentInfo *seg, uint64_t &addr);
120 void copySectionContent(SectionInfo *si, ContentBytes &content);
121 uint8_t scopeBits(const DefinedAtom* atom);
122 int dylibOrdinal(const SharedLibraryAtom *sa);
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000123 void segIndexForSection(const SectionInfo *sect,
Nick Kledzike34182f2013-11-06 21:36:55 +0000124 uint8_t &segmentIndex, uint64_t &segmentStartAddr);
125 const Atom *targetOfLazyPointer(const DefinedAtom *lpAtom);
126 const Atom *targetOfStub(const DefinedAtom *stubAtom);
127 bool belongsInGlobalSymbolsSection(const DefinedAtom* atom);
128 void appendSection(SectionInfo *si, NormalizedFile &file);
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000129 void appendReloc(const DefinedAtom *atom, const Reference *ref,
Nick Kledzike34182f2013-11-06 21:36:55 +0000130 Relocations &relocations);
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000131
Nick Kledzike34182f2013-11-06 21:36:55 +0000132 static uint64_t alignTo(uint64_t value, uint8_t align2);
133 typedef llvm::DenseMap<const Atom*, uint32_t> AtomToIndex;
134 struct AtomAndIndex { const Atom *atom; uint32_t index; };
Joey Gouly9d263e02013-12-25 19:39:08 +0000135 struct AtomSorter {
136 bool operator()(const AtomAndIndex &left, const AtomAndIndex &right);
Nick Kledzike34182f2013-11-06 21:36:55 +0000137 };
Joey Gouly9d263e02013-12-25 19:39:08 +0000138 struct SegmentSorter {
139 bool operator()(const SegmentInfo *left, const SegmentInfo *right);
Nick Kledzike34182f2013-11-06 21:36:55 +0000140 static unsigned weight(const SegmentInfo *);
141 };
Joey Gouly9d263e02013-12-25 19:39:08 +0000142 struct TextSectionSorter {
143 bool operator()(const SectionInfo *left, const SectionInfo *right);
Nick Kledzike34182f2013-11-06 21:36:55 +0000144 static unsigned weight(const SectionInfo *);
145 };
146
147 const MachOLinkingContext &_context;
148 llvm::BumpPtrAllocator _allocator;
149 std::vector<SectionInfo*> _sectionInfos;
150 std::vector<SegmentInfo*> _segmentInfos;
151 TypeToSection _sectionMap;
152 AtomToAddress _atomToAddress;
153 DylibPathToInfo _dylibInfo;
154 const DefinedAtom *_entryAtom;
155 AtomToIndex _atomToSymbolIndex;
156};
157
158SectionInfo *Util::makeSection(DefinedAtom::ContentType type) {
159 switch ( type ) {
160 case DefinedAtom::typeCode:
161 return new (_allocator) SectionInfo("__TEXT", "__text",
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000162 S_REGULAR, S_ATTR_PURE_INSTRUCTIONS
Nick Kledzike34182f2013-11-06 21:36:55 +0000163 | S_ATTR_SOME_INSTRUCTIONS);
164 case DefinedAtom::typeCString:
165 return new (_allocator) SectionInfo("__TEXT", "__cstring",
166 S_CSTRING_LITERALS);
167 case DefinedAtom::typeStub:
168 return new (_allocator) SectionInfo("__TEXT", "__stubs",
169 S_SYMBOL_STUBS, S_ATTR_PURE_INSTRUCTIONS);
170 case DefinedAtom::typeStubHelper:
171 return new (_allocator) SectionInfo("__TEXT", "__stub_helper",
172 S_REGULAR, S_ATTR_PURE_INSTRUCTIONS);
173 case DefinedAtom::typeLazyPointer:
174 return new (_allocator) SectionInfo("__DATA", "__la_symbol_ptr",
175 S_LAZY_SYMBOL_POINTERS);
176 case DefinedAtom::typeGOT:
177 return new (_allocator) SectionInfo("__DATA", "__got",
178 S_NON_LAZY_SYMBOL_POINTERS);
179 default:
180 llvm_unreachable("TO DO: add support for more sections");
181 break;
182 }
183}
184
185
186
187SectionInfo *Util::sectionForAtom(const DefinedAtom *atom) {
188 DefinedAtom::ContentType type = atom->contentType();
189 auto pos = _sectionMap.find(type);
190 if ( pos != _sectionMap.end() )
191 return pos->second;
192 SectionInfo *si = makeSection(type);
193 _sectionInfos.push_back(si);
194 _sectionMap[type] = si;
195 return si;
196}
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000197
Nick Kledzike34182f2013-11-06 21:36:55 +0000198
199void Util::appendAtom(SectionInfo *sect, const DefinedAtom *atom) {
200 // Figure out offset for atom in this section given alignment constraints.
201 uint64_t offset = sect->size;
202 DefinedAtom::Alignment atomAlign = atom->alignment();
203 uint64_t align2 = 1 << atomAlign.powerOf2;
204 uint64_t requiredModulus = atomAlign.modulus;
205 uint64_t currentModulus = (offset % align2);
206 if ( currentModulus != requiredModulus ) {
207 if ( requiredModulus > currentModulus )
208 offset += requiredModulus-currentModulus;
209 else
210 offset += align2+requiredModulus-currentModulus;
211 }
212 // Record max alignment of any atom in this section.
213 if ( atomAlign.powerOf2 > sect->alignment )
214 sect->alignment = atomAlign.powerOf2;
215 // Assign atom to this section with this offset.
216 AtomInfo ai = {atom, offset};
217 sect->atomsAndOffsets.push_back(ai);
218 // Update section size to include this atom.
219 sect->size = offset + atom->size();
220}
221
222void Util::assignAtomsToSections(const lld::File &atomFile) {
223 for (const DefinedAtom *atom : atomFile.defined()) {
224 appendAtom(sectionForAtom(atom), atom);
225 }
226}
227
228SegmentInfo *Util::segmentForName(StringRef segName) {
229 for (SegmentInfo *si : _segmentInfos) {
230 if ( si->name.equals(segName) )
231 return si;
232 }
233 SegmentInfo *info = new (_allocator) SegmentInfo(segName);
234 if (segName.equals("__TEXT"))
235 info->access = VM_PROT_READ | VM_PROT_EXECUTE;
236 else if (segName.equals("__DATA"))
237 info->access = VM_PROT_READ | VM_PROT_WRITE;
238 else if (segName.equals("__PAGEZERO"))
239 info->access = 0;
240 _segmentInfos.push_back(info);
241 return info;
242}
243
244unsigned Util::SegmentSorter::weight(const SegmentInfo *seg) {
245 return llvm::StringSwitch<unsigned>(seg->name)
246 .Case("__PAGEZERO", 1)
247 .Case("__TEXT", 2)
248 .Case("__DATA", 3)
249 .Default(100);
250}
251
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000252bool Util::SegmentSorter::operator()(const SegmentInfo *left,
Nick Kledzike34182f2013-11-06 21:36:55 +0000253 const SegmentInfo *right) {
254 return (weight(left) < weight(right));
255}
256
257unsigned Util::TextSectionSorter::weight(const SectionInfo *sect) {
258 return llvm::StringSwitch<unsigned>(sect->sectionName)
259 .Case("__text", 1)
260 .Case("__stubs", 2)
261 .Case("__stub_helper", 3)
262 .Case("__const", 4)
263 .Case("__cstring", 5)
264 .Case("__unwind_info", 98)
265 .Case("__eh_frame", 99)
266 .Default(10);
267}
268
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000269bool Util::TextSectionSorter::operator()(const SectionInfo *left,
Nick Kledzike34182f2013-11-06 21:36:55 +0000270 const SectionInfo *right) {
271 return (weight(left) < weight(right));
272}
273
274
275void Util::organizeSections() {
276 if (_context.outputFileType() == llvm::MachO::MH_OBJECT) {
277 // Leave sections ordered as normalized file specified.
278 uint32_t sectionIndex = 1;
279 for (SectionInfo *si : _sectionInfos) {
280 si->finalSectionIndex = sectionIndex++;
281 }
282 } else {
283 // Main executables, need a zero-page segment
284 if (_context.outputFileType() == llvm::MachO::MH_EXECUTE)
285 segmentForName("__PAGEZERO");
286 // Group sections into segments.
287 for (SectionInfo *si : _sectionInfos) {
288 SegmentInfo *seg = segmentForName(si->segmentName);
289 seg->sections.push_back(si);
290 }
291 // Sort segments.
292 std::sort(_segmentInfos.begin(), _segmentInfos.end(), SegmentSorter());
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000293
Nick Kledzike34182f2013-11-06 21:36:55 +0000294 // Sort sections within segments.
295 for (SegmentInfo *seg : _segmentInfos) {
296 if (seg->name.equals("__TEXT")) {
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000297 std::sort(seg->sections.begin(), seg->sections.end(),
Nick Kledzike34182f2013-11-06 21:36:55 +0000298 TextSectionSorter());
299 }
300 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000301
Nick Kledzike34182f2013-11-06 21:36:55 +0000302 // Record final section indexes.
303 uint32_t sectionIndex = 1;
304 for (SegmentInfo *seg : _segmentInfos) {
305 for (SectionInfo *sect : seg->sections) {
306 sect->finalSectionIndex = sectionIndex++;
307 }
308 }
309 }
310
311}
312
313uint64_t Util::alignTo(uint64_t value, uint8_t align2) {
314 return llvm::RoundUpToAlignment(value, 1 << align2);
315}
316
317
318void Util::layoutSectionsInSegment(SegmentInfo *seg, uint64_t &addr) {
319 seg->address = addr;
320 for (SectionInfo *sect : seg->sections) {
321 sect->address = alignTo(addr, sect->alignment);
322 addr += sect->size;
323 }
324 seg->size = llvm::RoundUpToAlignment(addr - seg->address,_context.pageSize());
325}
326
327
328// __TEXT segment lays out backwards so padding is at front after load commands.
329void Util::layoutSectionsInTextSegment(SegmentInfo *seg, uint64_t &addr) {
330 seg->address = addr;
331 // Walks sections starting at end to calculate padding for start.
332 int64_t taddr = 0;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000333 for (auto it = seg->sections.rbegin(); it != seg->sections.rend(); ++it) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000334 SectionInfo *sect = *it;
335 taddr -= sect->size;
336 taddr = taddr & (0 - (1 << sect->alignment));
337 }
338 int64_t padding = taddr;
339 while (padding < 0)
340 padding += _context.pageSize();
341 // Start assigning section address starting at padded offset.
342 addr += padding;
343 for (SectionInfo *sect : seg->sections) {
344 sect->address = alignTo(addr, sect->alignment);
345 addr = sect->address + sect->size;
346 }
347 seg->size = llvm::RoundUpToAlignment(addr - seg->address,_context.pageSize());
348}
349
350
351void Util::assignAddressesToSections() {
352 uint64_t address = 0; // FIXME
353 if (_context.outputFileType() != llvm::MachO::MH_OBJECT) {
354 for (SegmentInfo *seg : _segmentInfos) {
355 if (seg->name.equals("__PAGEZERO")) {
356 seg->size = _context.pageZeroSize();
357 address += seg->size;
358 }
359 else if (seg->name.equals("__TEXT"))
360 layoutSectionsInTextSegment(seg, address);
361 else
362 layoutSectionsInSegment(seg, address);
363 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000364 DEBUG_WITH_TYPE("WriterMachO-norm",
Nick Kledzik020a49c2013-11-06 21:57:52 +0000365 llvm::dbgs() << "assignAddressesToSections()\n";
366 for (SegmentInfo *sgi : _segmentInfos) {
367 llvm::dbgs() << " address=" << llvm::format("0x%08llX", sgi->address)
Nick Kledzike34182f2013-11-06 21:36:55 +0000368 << ", size=" << llvm::format("0x%08llX", sgi->size)
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000369 << ", segment-name='" << sgi->name
Nick Kledzik020a49c2013-11-06 21:57:52 +0000370 << "'\n";
371 for (SectionInfo *si : sgi->sections) {
372 llvm::dbgs()<< " addr=" << llvm::format("0x%08llX", si->address)
Nick Kledzike34182f2013-11-06 21:36:55 +0000373 << ", size=" << llvm::format("0x%08llX", si->size)
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000374 << ", section-name='" << si->sectionName
Nick Kledzik020a49c2013-11-06 21:57:52 +0000375 << "\n";
376 }
Nick Kledzike34182f2013-11-06 21:36:55 +0000377 }
Nick Kledzik020a49c2013-11-06 21:57:52 +0000378 );
Nick Kledzike34182f2013-11-06 21:36:55 +0000379 } else {
380 for (SectionInfo *sect : _sectionInfos) {
381 sect->address = alignTo(address, sect->alignment);
382 address = sect->address + sect->size;
383 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000384 DEBUG_WITH_TYPE("WriterMachO-norm",
Nick Kledzik020a49c2013-11-06 21:57:52 +0000385 llvm::dbgs() << "assignAddressesToSections()\n";
386 for (SectionInfo *si : _sectionInfos) {
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000387 llvm::dbgs() << " section=" << si->sectionName
Nick Kledzike34182f2013-11-06 21:36:55 +0000388 << " address= " << llvm::format("0x%08X", si->address)
389 << " size= " << llvm::format("0x%08X", si->size)
Nick Kledzik020a49c2013-11-06 21:57:52 +0000390 << "\n";
391 }
392 );
Nick Kledzike34182f2013-11-06 21:36:55 +0000393 }
Nick Kledzike34182f2013-11-06 21:36:55 +0000394}
395
396
397void Util::copySegmentInfo(NormalizedFile &file) {
398 for (SegmentInfo *sgi : _segmentInfos) {
399 Segment seg;
400 seg.name = sgi->name;
401 seg.address = sgi->address;
402 seg.size = sgi->size;
403 seg.access = sgi->access;
404 file.segments.push_back(seg);
405 }
406}
407
408void Util::appendSection(SectionInfo *si, NormalizedFile &file) {
409 // Add new empty section to end of file.sections.
410 Section temp;
411 file.sections.push_back(std::move(temp));
412 Section* normSect = &file.sections.back();
413 // Copy fields to normalized section.
414 normSect->segmentName = si->segmentName;
415 normSect->sectionName = si->sectionName;
416 normSect->type = si->type;
417 normSect->attributes = si->attributes;
418 normSect->address = si->address;
419 normSect->alignment = si->alignment;
420 // Record where normalized section is.
421 si->normalizedSectionIndex = file.sections.size()-1;
422 // Copy content from atoms to content buffer for section.
423 // FIXME: zerofill atoms/sections should not take up content space.
Nick Kledzik6edd7222014-01-11 01:07:43 +0000424 uint8_t *sectionContent = file.ownedAllocations.Allocate<uint8_t>(si->size);
425 normSect->content = llvm::makeArrayRef(sectionContent, si->size);
Nick Kledzike34182f2013-11-06 21:36:55 +0000426 for (AtomInfo &ai : si->atomsAndOffsets) {
427 // Copy raw bytes.
428 uint8_t *atomContent = reinterpret_cast<uint8_t*>
429 (&sectionContent[ai.offsetInSection]);
430 memcpy(atomContent, ai.atom->rawContent().data(), ai.atom->size());
431 // Apply fix-ups.
432 for (const Reference *ref : *ai.atom) {
433 uint32_t offset = ref->offsetInAtom();
434 uint64_t targetAddress = 0;
435 if ( ref->target() != nullptr )
436 targetAddress = _atomToAddress[ref->target()];
437 uint64_t fixupAddress = _atomToAddress[ai.atom] + offset;
Rui Ueyama170a1a82013-12-20 07:48:29 +0000438 _context.kindHandler().applyFixup(
439 ref->kindNamespace(), ref->kindArch(), ref->kindValue(),
440 ref->addend(), &atomContent[offset], fixupAddress, targetAddress);
Nick Kledzike34182f2013-11-06 21:36:55 +0000441 }
442 }
443}
444
445void Util::copySections(NormalizedFile &file) {
446 file.sections.reserve(_sectionInfos.size());
447 // For final linked images, write sections grouped by segment.
448 if (_context.outputFileType() != llvm::MachO::MH_OBJECT) {
449 for (SegmentInfo *sgi : _segmentInfos) {
450 for (SectionInfo *si : sgi->sections) {
451 appendSection(si, file);
452 }
453 }
454 } else {
455 // Object files write sections in default order.
456 for (SectionInfo *si : _sectionInfos) {
457 appendSection(si, file);
458 }
459 }
460}
461
462void Util::copyEntryPointAddress(NormalizedFile &nFile) {
463 if (_context.outputTypeHasEntry()) {
464 nFile.entryAddress = _atomToAddress[_entryAtom];
465 }
466}
467
468void Util::buildAtomToAddressMap() {
469 DEBUG_WITH_TYPE("WriterMachO-address", llvm::dbgs()
470 << "assign atom addresses:\n");
471 const bool lookForEntry = _context.outputTypeHasEntry();
472 for (SectionInfo *sect : _sectionInfos) {
473 for (const AtomInfo &info : sect->atomsAndOffsets) {
474 _atomToAddress[info.atom] = sect->address + info.offsetInSection;
475 if (lookForEntry && (info.atom->contentType() == DefinedAtom::typeCode) &&
476 (info.atom->size() != 0) &&
477 info.atom->name() == _context.entrySymbolName()) {
478 _entryAtom = info.atom;
479 }
480 DEBUG_WITH_TYPE("WriterMachO-address", llvm::dbgs()
481 << " address="
482 << llvm::format("0x%016X", _atomToAddress[info.atom])
483 << " atom=" << info.atom
484 << " name=" << info.atom->name() << "\n");
485 }
486 }
487}
488
489uint8_t Util::scopeBits(const DefinedAtom* atom) {
490 switch (atom->scope()) {
491 case Atom::scopeTranslationUnit:
492 return 0;
493 case Atom::scopeLinkageUnit:
494 return N_PEXT | N_EXT;
495 case Atom::scopeGlobal:
496 return N_EXT;
497 }
Nick Kledzik020fa7f2013-11-06 22:18:09 +0000498 llvm_unreachable("Unknown scope");
Nick Kledzike34182f2013-11-06 21:36:55 +0000499}
500
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000501bool Util::AtomSorter::operator()(const AtomAndIndex &left,
Nick Kledzike34182f2013-11-06 21:36:55 +0000502 const AtomAndIndex &right) {
503 return (left.atom->name().compare(right.atom->name()) < 0);
504}
505
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000506
Nick Kledzike34182f2013-11-06 21:36:55 +0000507bool Util::belongsInGlobalSymbolsSection(const DefinedAtom* atom) {
508 return (atom->scope() == Atom::scopeGlobal);
509}
510
511void Util::addSymbols(const lld::File &atomFile, NormalizedFile &file) {
512 // Mach-O symbol table has three regions: locals, globals, undefs.
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000513
Nick Kledzike34182f2013-11-06 21:36:55 +0000514 // Add all local (non-global) symbols in address order
515 std::vector<AtomAndIndex> globals;
516 globals.reserve(512);
517 for (SectionInfo *sect : _sectionInfos) {
518 for (const AtomInfo &info : sect->atomsAndOffsets) {
519 const DefinedAtom *atom = info.atom;
520 if (!atom->name().empty()) {
521 if (belongsInGlobalSymbolsSection(atom)) {
522 AtomAndIndex ai = { atom, sect->finalSectionIndex };
523 globals.push_back(ai);
524 } else {
525 Symbol sym;
526 sym.name = atom->name();
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000527 sym.type = N_SECT;
Nick Kledzike34182f2013-11-06 21:36:55 +0000528 sym.scope = scopeBits(atom);
529 sym.sect = sect->finalSectionIndex;
530 sym.desc = 0;
531 sym.value = _atomToAddress[atom];
532 file.localSymbols.push_back(sym);
533 }
534 }
535 }
536 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000537
Nick Kledzike34182f2013-11-06 21:36:55 +0000538 // Sort global symbol alphabetically, then add to symbol table.
539 std::sort(globals.begin(), globals.end(), AtomSorter());
540 for (AtomAndIndex &ai : globals) {
541 Symbol sym;
542 sym.name = ai.atom->name();
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000543 sym.type = N_SECT;
Nick Kledzike34182f2013-11-06 21:36:55 +0000544 sym.scope = scopeBits(static_cast<const DefinedAtom*>(ai.atom));
545 sym.sect = ai.index;
546 sym.desc = 0;
547 sym.value = _atomToAddress[ai.atom];
548 file.globalSymbols.push_back(sym);
549 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000550
551
Nick Kledzike34182f2013-11-06 21:36:55 +0000552 // Sort undefined symbol alphabetically, then add to symbol table.
553 std::vector<AtomAndIndex> undefs;
554 undefs.reserve(128);
555 for (const UndefinedAtom *atom : atomFile.undefined()) {
556 AtomAndIndex ai = { atom, 0 };
557 undefs.push_back(ai);
558 }
559 for (const SharedLibraryAtom *atom : atomFile.sharedLibrary()) {
560 AtomAndIndex ai = { atom, 0 };
561 undefs.push_back(ai);
562 }
563 std::sort(undefs.begin(), undefs.end(), AtomSorter());
564 const uint32_t start = file.globalSymbols.size() + file.localSymbols.size();
565 for (AtomAndIndex &ai : undefs) {
566 Symbol sym;
567 sym.name = ai.atom->name();
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000568 sym.type = N_UNDF;
Nick Kledzike34182f2013-11-06 21:36:55 +0000569 sym.scope = N_EXT;
570 sym.sect = 0;
571 sym.desc = 0;
572 sym.value = 0;
573 _atomToSymbolIndex[ai.atom] = file.undefinedSymbols.size() + start;
574 file.undefinedSymbols.push_back(sym);
575 }
576}
577
578const Atom *Util::targetOfLazyPointer(const DefinedAtom *lpAtom) {
579 for (const Reference *ref : *lpAtom) {
Nick Kledzike5552772013-12-19 21:58:00 +0000580 if (_context.kindHandler().isLazyTarget(*ref)) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000581 return ref->target();
582 }
583 }
584 return nullptr;
585}
586
587const Atom *Util::targetOfStub(const DefinedAtom *stubAtom) {
588 for (const Reference *ref : *stubAtom) {
589 if (const Atom *ta = ref->target()) {
590 if (const DefinedAtom *lpAtom = dyn_cast<DefinedAtom>(ta)) {
591 const Atom *target = targetOfLazyPointer(lpAtom);
592 if (target)
593 return target;
594 }
595 }
596 }
597 return nullptr;
598}
599
600
601void Util::addIndirectSymbols(const lld::File &atomFile, NormalizedFile &file) {
602 for (SectionInfo *si : _sectionInfos) {
603 Section &normSect = file.sections[si->normalizedSectionIndex];
604 switch (si->type) {
605 case llvm::MachO::S_NON_LAZY_SYMBOL_POINTERS:
606 for (const AtomInfo &info : si->atomsAndOffsets) {
607 bool foundTarget = false;
608 for (const Reference *ref : *info.atom) {
609 const Atom *target = ref->target();
610 if (target) {
611 if (isa<const SharedLibraryAtom>(target)) {
612 uint32_t index = _atomToSymbolIndex[target];
613 normSect.indirectSymbols.push_back(index);
614 foundTarget = true;
615 } else {
616 normSect.indirectSymbols.push_back(
617 llvm::MachO::INDIRECT_SYMBOL_LOCAL);
618 }
619 }
620 }
621 if (!foundTarget) {
622 normSect.indirectSymbols.push_back(
623 llvm::MachO::INDIRECT_SYMBOL_ABS);
624 }
625 }
626 break;
627 case llvm::MachO::S_LAZY_SYMBOL_POINTERS:
628 for (const AtomInfo &info : si->atomsAndOffsets) {
629 const Atom *target = targetOfLazyPointer(info.atom);
630 if (target) {
631 uint32_t index = _atomToSymbolIndex[target];
632 normSect.indirectSymbols.push_back(index);
633 }
634 }
635 break;
636 case llvm::MachO::S_SYMBOL_STUBS:
637 for (const AtomInfo &info : si->atomsAndOffsets) {
638 const Atom *target = targetOfStub(info.atom);
639 if (target) {
640 uint32_t index = _atomToSymbolIndex[target];
641 normSect.indirectSymbols.push_back(index);
642 }
643 }
644 break;
645 default:
646 break;
647 }
648 }
649
650}
651
652void Util::addDependentDylibs(const lld::File &atomFile,NormalizedFile &nFile) {
653 // Scan all imported symbols and build up list of dylibs they are from.
654 int ordinal = 1;
655 for (const SharedLibraryAtom *slAtom : atomFile.sharedLibrary()) {
656 StringRef loadPath = slAtom->loadName();
657 DylibPathToInfo::iterator pos = _dylibInfo.find(loadPath);
658 if (pos == _dylibInfo.end()) {
659 DylibInfo info;
660 info.ordinal = ordinal++;
661 info.hasWeak = slAtom->canBeNullAtRuntime();
662 info.hasNonWeak = !info.hasWeak;
663 _dylibInfo[loadPath] = info;
664 DependentDylib depInfo;
665 depInfo.path = loadPath;
666 depInfo.kind = llvm::MachO::LC_LOAD_DYLIB;
667 nFile.dependentDylibs.push_back(depInfo);
668 } else {
669 if ( slAtom->canBeNullAtRuntime() )
670 pos->second.hasWeak = true;
671 else
672 pos->second.hasNonWeak = true;
673 }
674 }
675 // Automatically weak link dylib in which all symbols are weak (canBeNull).
676 for (DependentDylib &dep : nFile.dependentDylibs) {
677 DylibInfo &info = _dylibInfo[dep.path];
678 if (info.hasWeak && !info.hasNonWeak)
679 dep.kind = llvm::MachO::LC_LOAD_WEAK_DYLIB;
680 }
681}
682
683
684int Util::dylibOrdinal(const SharedLibraryAtom *sa) {
685 return _dylibInfo[sa->loadName()].ordinal;
686}
687
688void Util::segIndexForSection(const SectionInfo *sect, uint8_t &segmentIndex,
689 uint64_t &segmentStartAddr) {
690 segmentIndex = 0;
691 for (const SegmentInfo *seg : _segmentInfos) {
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000692 if ((seg->address <= sect->address)
Nick Kledzike34182f2013-11-06 21:36:55 +0000693 && (seg->address+seg->size >= sect->address+sect->size)) {
694 segmentStartAddr = seg->address;
695 return;
696 }
697 ++segmentIndex;
698 }
699 llvm_unreachable("section not in any segment");
700}
701
702
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000703void Util::appendReloc(const DefinedAtom *atom, const Reference *ref,
Nick Kledzike34182f2013-11-06 21:36:55 +0000704 Relocations &relocations) {
705 // TODO: convert Reference to normalized relocation
706}
707
708void Util::addSectionRelocs(const lld::File &, NormalizedFile &file) {
709 if (_context.outputFileType() != llvm::MachO::MH_OBJECT)
710 return;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000711
Nick Kledzike34182f2013-11-06 21:36:55 +0000712 for (SectionInfo *si : _sectionInfos) {
713 Section &normSect = file.sections[si->normalizedSectionIndex];
714 for (const AtomInfo &info : si->atomsAndOffsets) {
715 const DefinedAtom *atom = info.atom;
716 for (const Reference *ref : *atom) {
717 appendReloc(atom, ref, normSect.relocations);
718 }
719 }
720 }
721}
722
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000723void Util::addRebaseAndBindingInfo(const lld::File &atomFile,
Nick Kledzike34182f2013-11-06 21:36:55 +0000724 NormalizedFile &nFile) {
725 if (_context.outputFileType() == llvm::MachO::MH_OBJECT)
726 return;
727
728 uint8_t segmentIndex;
729 uint64_t segmentStartAddr;
730 for (SectionInfo *sect : _sectionInfos) {
731 segIndexForSection(sect, segmentIndex, segmentStartAddr);
732 for (const AtomInfo &info : sect->atomsAndOffsets) {
733 const DefinedAtom *atom = info.atom;
734 for (const Reference *ref : *atom) {
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000735 uint64_t segmentOffset = _atomToAddress[atom] + ref->offsetInAtom()
Nick Kledzike34182f2013-11-06 21:36:55 +0000736 - segmentStartAddr;
737 const Atom* targ = ref->target();
Nick Kledzike5552772013-12-19 21:58:00 +0000738 if (_context.kindHandler().isPointer(*ref)) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000739 // A pointer to a DefinedAtom requires rebasing.
740 if (dyn_cast<DefinedAtom>(targ)) {
741 RebaseLocation rebase;
742 rebase.segIndex = segmentIndex;
743 rebase.segOffset = segmentOffset;
744 rebase.kind = llvm::MachO::REBASE_TYPE_POINTER;
745 nFile.rebasingInfo.push_back(rebase);
746 }
747 // A pointer to an SharedLibraryAtom requires binding.
748 if (const SharedLibraryAtom *sa = dyn_cast<SharedLibraryAtom>(targ)) {
749 BindLocation bind;
750 bind.segIndex = segmentIndex;
751 bind.segOffset = segmentOffset;
752 bind.kind = llvm::MachO::BIND_TYPE_POINTER;
753 bind.canBeNull = sa->canBeNullAtRuntime();
754 bind.ordinal = dylibOrdinal(sa);
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000755 bind.symbolName = targ->name();
Nick Kledzike34182f2013-11-06 21:36:55 +0000756 bind.addend = ref->addend();
757 nFile.bindingInfo.push_back(bind);
758 }
759 }
Nick Kledzike5552772013-12-19 21:58:00 +0000760 if (_context.kindHandler().isLazyTarget(*ref)) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000761 BindLocation bind;
762 bind.segIndex = segmentIndex;
763 bind.segOffset = segmentOffset;
764 bind.kind = llvm::MachO::BIND_TYPE_POINTER;
765 bind.canBeNull = false; //sa->canBeNullAtRuntime();
766 bind.ordinal = 1;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000767 bind.symbolName = targ->name();
Nick Kledzike34182f2013-11-06 21:36:55 +0000768 bind.addend = ref->addend();
769 nFile.lazyBindingInfo.push_back(bind);
770 }
771 }
772 }
773 }
774}
775
776uint32_t Util::fileFlags() {
777 return 0; //FIX ME
778}
779
780} // end anonymous namespace
781
782
783namespace lld {
784namespace mach_o {
785namespace normalized {
786
787/// Convert a set of Atoms into a normalized mach-o file.
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000788ErrorOr<std::unique_ptr<NormalizedFile>>
789normalizedFromAtoms(const lld::File &atomFile,
Nick Kledzike34182f2013-11-06 21:36:55 +0000790 const MachOLinkingContext &context) {
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000791 // The util object buffers info until the normalized file can be made.
Nick Kledzike34182f2013-11-06 21:36:55 +0000792 Util util(context);
793 util.assignAtomsToSections(atomFile);
794 util.organizeSections();
795 util.assignAddressesToSections();
796 util.buildAtomToAddressMap();
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000797
Nick Kledzike34182f2013-11-06 21:36:55 +0000798 std::unique_ptr<NormalizedFile> f(new NormalizedFile());
799 NormalizedFile &normFile = *f.get();
800 f->arch = context.arch();
801 f->fileType = context.outputFileType();
802 f->flags = util.fileFlags();
803 util.copySegmentInfo(normFile);
804 util.copySections(normFile);
805 util.addDependentDylibs(atomFile, normFile);
806 util.addSymbols(atomFile, normFile);
807 util.addIndirectSymbols(atomFile, normFile);
808 util.addRebaseAndBindingInfo(atomFile, normFile);
809 util.addSectionRelocs(atomFile, normFile);
810 util.copyEntryPointAddress(normFile);
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000811
Nick Kledzike34182f2013-11-06 21:36:55 +0000812 return std::move(f);
813}
814
815
816} // namespace normalized
817} // namespace mach_o
818} // namespace lld
819