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