blob: d15e20e6150f6dfca960b642629a5c2fe6150e3c [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; };
136 struct AtomSorter {
137 bool operator()(const AtomAndIndex &left, const AtomAndIndex &right);
138 };
139 struct SegmentSorter {
140 bool operator()(const SegmentInfo *left, const SegmentInfo *right);
141 static unsigned weight(const SegmentInfo *);
142 };
143 struct TextSectionSorter {
144 bool operator()(const SectionInfo *left, const SectionInfo *right);
145 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;
439 _context.kindHandler().applyFixup(ref->kind(), ref->addend(),
440 &atomContent[offset], fixupAddress,
441 targetAddress);
442 }
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 }
499}
500
501bool Util::AtomSorter::operator()(const AtomAndIndex &left,
502 const AtomAndIndex &right) {
503 return (left.atom->name().compare(right.atom->name()) < 0);
504}
505
506
507bool 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.
513
514 // 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();
527 sym.type = N_SECT;
528 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 }
537
538 // 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();
543 sym.type = N_SECT;
544 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 }
550
551
552 // 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();
568 sym.type = N_UNDF;
569 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) {
580 if (_context.kindHandler().isLazyTarget(ref->kind())) {
581 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) {
692 if ((seg->address <= sect->address)
693 && (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
703void Util::appendReloc(const DefinedAtom *atom, const Reference *ref,
704 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;
711
712 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
723void Util::addRebaseAndBindingInfo(const lld::File &atomFile,
724 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) {
735 uint64_t segmentOffset = _atomToAddress[atom] + ref->offsetInAtom()
736 - segmentStartAddr;
737 const Atom* targ = ref->target();
738 if (_context.kindHandler().isPointer(ref->kind())) {
739 // 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);
755 bind.symbolName = targ->name();
756 bind.addend = ref->addend();
757 nFile.bindingInfo.push_back(bind);
758 }
759 }
760 if (_context.kindHandler().isLazyTarget(ref->kind())) {
761 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;
767 bind.symbolName = targ->name();
768 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.
788ErrorOr<std::unique_ptr<NormalizedFile>>
789normalizedFromAtoms(const lld::File &atomFile,
790 const MachOLinkingContext &context) {
791 // The util object buffers info until the normalized file can be made.
792 Util util(context);
793 util.assignAtomsToSections(atomFile);
794 util.organizeSections();
795 util.assignAddressesToSections();
796 util.buildAtomToAddressMap();
797
798 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);
811
812 return std::move(f);
813}
814
815
816} // namespace normalized
817} // namespace mach_o
818} // namespace lld
819