blob: 6531455ed9266a541139163e6ef03aba41f9684f [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);
Nick Kledzik61fdef62014-05-15 20:59:23 +0000179 case DefinedAtom::typeZeroFill:
180 return new (_allocator) SectionInfo("__DATA", "__bss",
181 S_ZEROFILL);
Nick Kledzika4a08d32014-05-27 23:20:52 +0000182 case DefinedAtom::typeInitializerPtr:
183 return new (_allocator) SectionInfo("__DATA", "__mod_init_func",
184 S_MOD_INIT_FUNC_POINTERS);
185 case DefinedAtom::typeTerminatorPtr:
186 return new (_allocator) SectionInfo("__DATA", "__mod_term_func",
187 S_MOD_TERM_FUNC_POINTERS);
Nick Kledzika0c13a22014-05-22 01:42:06 +0000188 case DefinedAtom::typeLiteral4:
189 return new (_allocator) SectionInfo("__TEXT", "__literal4",
190 S_4BYTE_LITERALS);
191 case DefinedAtom::typeLiteral8:
192 return new (_allocator) SectionInfo("__TEXT", "__literal8",
193 S_8BYTE_LITERALS);
194 case DefinedAtom::typeLiteral16:
195 return new (_allocator) SectionInfo("__TEXT", "__literal16",
196 S_16BYTE_LITERALS);
Nick Kledzik3e90e5f2014-05-27 20:25:06 +0000197 case DefinedAtom::typeUTF16String:
198 return new (_allocator) SectionInfo("__TEXT", "__ustring",
199 S_REGULAR);
Nick Kledzik9ede7022014-05-29 20:44:21 +0000200 case DefinedAtom::typeCFString:
201 return new (_allocator) SectionInfo("__DATA", "__cfstring",
202 S_REGULAR);
Nick Kledzike34182f2013-11-06 21:36:55 +0000203 default:
204 llvm_unreachable("TO DO: add support for more sections");
205 break;
206 }
207}
208
209
210
211SectionInfo *Util::sectionForAtom(const DefinedAtom *atom) {
212 DefinedAtom::ContentType type = atom->contentType();
213 auto pos = _sectionMap.find(type);
214 if ( pos != _sectionMap.end() )
215 return pos->second;
216 SectionInfo *si = makeSection(type);
217 _sectionInfos.push_back(si);
218 _sectionMap[type] = si;
219 return si;
220}
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000221
Nick Kledzike34182f2013-11-06 21:36:55 +0000222
223void Util::appendAtom(SectionInfo *sect, const DefinedAtom *atom) {
224 // Figure out offset for atom in this section given alignment constraints.
225 uint64_t offset = sect->size;
226 DefinedAtom::Alignment atomAlign = atom->alignment();
227 uint64_t align2 = 1 << atomAlign.powerOf2;
228 uint64_t requiredModulus = atomAlign.modulus;
229 uint64_t currentModulus = (offset % align2);
230 if ( currentModulus != requiredModulus ) {
231 if ( requiredModulus > currentModulus )
232 offset += requiredModulus-currentModulus;
233 else
234 offset += align2+requiredModulus-currentModulus;
235 }
236 // Record max alignment of any atom in this section.
237 if ( atomAlign.powerOf2 > sect->alignment )
238 sect->alignment = atomAlign.powerOf2;
239 // Assign atom to this section with this offset.
240 AtomInfo ai = {atom, offset};
241 sect->atomsAndOffsets.push_back(ai);
242 // Update section size to include this atom.
243 sect->size = offset + atom->size();
244}
245
246void Util::assignAtomsToSections(const lld::File &atomFile) {
247 for (const DefinedAtom *atom : atomFile.defined()) {
248 appendAtom(sectionForAtom(atom), atom);
249 }
250}
251
252SegmentInfo *Util::segmentForName(StringRef segName) {
253 for (SegmentInfo *si : _segmentInfos) {
254 if ( si->name.equals(segName) )
255 return si;
256 }
257 SegmentInfo *info = new (_allocator) SegmentInfo(segName);
258 if (segName.equals("__TEXT"))
259 info->access = VM_PROT_READ | VM_PROT_EXECUTE;
260 else if (segName.equals("__DATA"))
261 info->access = VM_PROT_READ | VM_PROT_WRITE;
262 else if (segName.equals("__PAGEZERO"))
263 info->access = 0;
264 _segmentInfos.push_back(info);
265 return info;
266}
267
268unsigned Util::SegmentSorter::weight(const SegmentInfo *seg) {
269 return llvm::StringSwitch<unsigned>(seg->name)
270 .Case("__PAGEZERO", 1)
271 .Case("__TEXT", 2)
272 .Case("__DATA", 3)
273 .Default(100);
274}
275
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000276bool Util::SegmentSorter::operator()(const SegmentInfo *left,
Nick Kledzike34182f2013-11-06 21:36:55 +0000277 const SegmentInfo *right) {
278 return (weight(left) < weight(right));
279}
280
281unsigned Util::TextSectionSorter::weight(const SectionInfo *sect) {
282 return llvm::StringSwitch<unsigned>(sect->sectionName)
283 .Case("__text", 1)
284 .Case("__stubs", 2)
285 .Case("__stub_helper", 3)
286 .Case("__const", 4)
287 .Case("__cstring", 5)
288 .Case("__unwind_info", 98)
289 .Case("__eh_frame", 99)
290 .Default(10);
291}
292
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000293bool Util::TextSectionSorter::operator()(const SectionInfo *left,
Nick Kledzike34182f2013-11-06 21:36:55 +0000294 const SectionInfo *right) {
295 return (weight(left) < weight(right));
296}
297
298
299void Util::organizeSections() {
300 if (_context.outputFileType() == llvm::MachO::MH_OBJECT) {
301 // Leave sections ordered as normalized file specified.
302 uint32_t sectionIndex = 1;
303 for (SectionInfo *si : _sectionInfos) {
304 si->finalSectionIndex = sectionIndex++;
305 }
306 } else {
307 // Main executables, need a zero-page segment
308 if (_context.outputFileType() == llvm::MachO::MH_EXECUTE)
309 segmentForName("__PAGEZERO");
310 // Group sections into segments.
311 for (SectionInfo *si : _sectionInfos) {
312 SegmentInfo *seg = segmentForName(si->segmentName);
313 seg->sections.push_back(si);
314 }
315 // Sort segments.
316 std::sort(_segmentInfos.begin(), _segmentInfos.end(), SegmentSorter());
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000317
Nick Kledzike34182f2013-11-06 21:36:55 +0000318 // Sort sections within segments.
319 for (SegmentInfo *seg : _segmentInfos) {
320 if (seg->name.equals("__TEXT")) {
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000321 std::sort(seg->sections.begin(), seg->sections.end(),
Nick Kledzike34182f2013-11-06 21:36:55 +0000322 TextSectionSorter());
323 }
324 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000325
Nick Kledzike34182f2013-11-06 21:36:55 +0000326 // Record final section indexes.
327 uint32_t sectionIndex = 1;
328 for (SegmentInfo *seg : _segmentInfos) {
329 for (SectionInfo *sect : seg->sections) {
330 sect->finalSectionIndex = sectionIndex++;
331 }
332 }
333 }
334
335}
336
337uint64_t Util::alignTo(uint64_t value, uint8_t align2) {
338 return llvm::RoundUpToAlignment(value, 1 << align2);
339}
340
341
342void Util::layoutSectionsInSegment(SegmentInfo *seg, uint64_t &addr) {
343 seg->address = addr;
344 for (SectionInfo *sect : seg->sections) {
345 sect->address = alignTo(addr, sect->alignment);
346 addr += sect->size;
347 }
348 seg->size = llvm::RoundUpToAlignment(addr - seg->address,_context.pageSize());
349}
350
351
352// __TEXT segment lays out backwards so padding is at front after load commands.
353void Util::layoutSectionsInTextSegment(SegmentInfo *seg, uint64_t &addr) {
354 seg->address = addr;
355 // Walks sections starting at end to calculate padding for start.
356 int64_t taddr = 0;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000357 for (auto it = seg->sections.rbegin(); it != seg->sections.rend(); ++it) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000358 SectionInfo *sect = *it;
359 taddr -= sect->size;
360 taddr = taddr & (0 - (1 << sect->alignment));
361 }
362 int64_t padding = taddr;
363 while (padding < 0)
364 padding += _context.pageSize();
365 // Start assigning section address starting at padded offset.
366 addr += padding;
367 for (SectionInfo *sect : seg->sections) {
368 sect->address = alignTo(addr, sect->alignment);
369 addr = sect->address + sect->size;
370 }
371 seg->size = llvm::RoundUpToAlignment(addr - seg->address,_context.pageSize());
372}
373
374
375void Util::assignAddressesToSections() {
376 uint64_t address = 0; // FIXME
377 if (_context.outputFileType() != llvm::MachO::MH_OBJECT) {
378 for (SegmentInfo *seg : _segmentInfos) {
379 if (seg->name.equals("__PAGEZERO")) {
380 seg->size = _context.pageZeroSize();
381 address += seg->size;
382 }
383 else if (seg->name.equals("__TEXT"))
384 layoutSectionsInTextSegment(seg, address);
385 else
386 layoutSectionsInSegment(seg, address);
387 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000388 DEBUG_WITH_TYPE("WriterMachO-norm",
Nick Kledzik020a49c2013-11-06 21:57:52 +0000389 llvm::dbgs() << "assignAddressesToSections()\n";
390 for (SegmentInfo *sgi : _segmentInfos) {
391 llvm::dbgs() << " address=" << llvm::format("0x%08llX", sgi->address)
Nick Kledzike34182f2013-11-06 21:36:55 +0000392 << ", size=" << llvm::format("0x%08llX", sgi->size)
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000393 << ", segment-name='" << sgi->name
Nick Kledzik020a49c2013-11-06 21:57:52 +0000394 << "'\n";
395 for (SectionInfo *si : sgi->sections) {
396 llvm::dbgs()<< " addr=" << llvm::format("0x%08llX", si->address)
Nick Kledzike34182f2013-11-06 21:36:55 +0000397 << ", size=" << llvm::format("0x%08llX", si->size)
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000398 << ", section-name='" << si->sectionName
Nick Kledzik020a49c2013-11-06 21:57:52 +0000399 << "\n";
400 }
Nick Kledzike34182f2013-11-06 21:36:55 +0000401 }
Nick Kledzik020a49c2013-11-06 21:57:52 +0000402 );
Nick Kledzike34182f2013-11-06 21:36:55 +0000403 } else {
404 for (SectionInfo *sect : _sectionInfos) {
405 sect->address = alignTo(address, sect->alignment);
406 address = sect->address + sect->size;
407 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000408 DEBUG_WITH_TYPE("WriterMachO-norm",
Nick Kledzik020a49c2013-11-06 21:57:52 +0000409 llvm::dbgs() << "assignAddressesToSections()\n";
410 for (SectionInfo *si : _sectionInfos) {
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000411 llvm::dbgs() << " section=" << si->sectionName
Nick Kledzike34182f2013-11-06 21:36:55 +0000412 << " address= " << llvm::format("0x%08X", si->address)
413 << " size= " << llvm::format("0x%08X", si->size)
Nick Kledzik020a49c2013-11-06 21:57:52 +0000414 << "\n";
415 }
416 );
Nick Kledzike34182f2013-11-06 21:36:55 +0000417 }
Nick Kledzike34182f2013-11-06 21:36:55 +0000418}
419
420
421void Util::copySegmentInfo(NormalizedFile &file) {
422 for (SegmentInfo *sgi : _segmentInfos) {
423 Segment seg;
424 seg.name = sgi->name;
425 seg.address = sgi->address;
426 seg.size = sgi->size;
427 seg.access = sgi->access;
428 file.segments.push_back(seg);
429 }
430}
431
432void Util::appendSection(SectionInfo *si, NormalizedFile &file) {
433 // Add new empty section to end of file.sections.
434 Section temp;
435 file.sections.push_back(std::move(temp));
436 Section* normSect = &file.sections.back();
437 // Copy fields to normalized section.
438 normSect->segmentName = si->segmentName;
439 normSect->sectionName = si->sectionName;
440 normSect->type = si->type;
441 normSect->attributes = si->attributes;
442 normSect->address = si->address;
443 normSect->alignment = si->alignment;
444 // Record where normalized section is.
445 si->normalizedSectionIndex = file.sections.size()-1;
446 // Copy content from atoms to content buffer for section.
Nick Kledzik61fdef62014-05-15 20:59:23 +0000447 if (si->type == llvm::MachO::S_ZEROFILL)
448 return;
Nick Kledzik6edd7222014-01-11 01:07:43 +0000449 uint8_t *sectionContent = file.ownedAllocations.Allocate<uint8_t>(si->size);
450 normSect->content = llvm::makeArrayRef(sectionContent, si->size);
Nick Kledzike34182f2013-11-06 21:36:55 +0000451 for (AtomInfo &ai : si->atomsAndOffsets) {
452 // Copy raw bytes.
453 uint8_t *atomContent = reinterpret_cast<uint8_t*>
454 (&sectionContent[ai.offsetInSection]);
455 memcpy(atomContent, ai.atom->rawContent().data(), ai.atom->size());
456 // Apply fix-ups.
457 for (const Reference *ref : *ai.atom) {
458 uint32_t offset = ref->offsetInAtom();
459 uint64_t targetAddress = 0;
460 if ( ref->target() != nullptr )
461 targetAddress = _atomToAddress[ref->target()];
462 uint64_t fixupAddress = _atomToAddress[ai.atom] + offset;
Rui Ueyama170a1a82013-12-20 07:48:29 +0000463 _context.kindHandler().applyFixup(
464 ref->kindNamespace(), ref->kindArch(), ref->kindValue(),
465 ref->addend(), &atomContent[offset], fixupAddress, targetAddress);
Nick Kledzike34182f2013-11-06 21:36:55 +0000466 }
467 }
468}
469
470void Util::copySections(NormalizedFile &file) {
471 file.sections.reserve(_sectionInfos.size());
472 // For final linked images, write sections grouped by segment.
473 if (_context.outputFileType() != llvm::MachO::MH_OBJECT) {
474 for (SegmentInfo *sgi : _segmentInfos) {
475 for (SectionInfo *si : sgi->sections) {
476 appendSection(si, file);
477 }
478 }
479 } else {
480 // Object files write sections in default order.
481 for (SectionInfo *si : _sectionInfos) {
482 appendSection(si, file);
483 }
484 }
485}
486
487void Util::copyEntryPointAddress(NormalizedFile &nFile) {
488 if (_context.outputTypeHasEntry()) {
489 nFile.entryAddress = _atomToAddress[_entryAtom];
490 }
491}
492
493void Util::buildAtomToAddressMap() {
494 DEBUG_WITH_TYPE("WriterMachO-address", llvm::dbgs()
495 << "assign atom addresses:\n");
496 const bool lookForEntry = _context.outputTypeHasEntry();
497 for (SectionInfo *sect : _sectionInfos) {
498 for (const AtomInfo &info : sect->atomsAndOffsets) {
499 _atomToAddress[info.atom] = sect->address + info.offsetInSection;
500 if (lookForEntry && (info.atom->contentType() == DefinedAtom::typeCode) &&
501 (info.atom->size() != 0) &&
502 info.atom->name() == _context.entrySymbolName()) {
503 _entryAtom = info.atom;
504 }
505 DEBUG_WITH_TYPE("WriterMachO-address", llvm::dbgs()
506 << " address="
507 << llvm::format("0x%016X", _atomToAddress[info.atom])
508 << " atom=" << info.atom
509 << " name=" << info.atom->name() << "\n");
510 }
511 }
512}
513
514uint8_t Util::scopeBits(const DefinedAtom* atom) {
515 switch (atom->scope()) {
516 case Atom::scopeTranslationUnit:
517 return 0;
518 case Atom::scopeLinkageUnit:
519 return N_PEXT | N_EXT;
520 case Atom::scopeGlobal:
521 return N_EXT;
522 }
Nick Kledzik020fa7f2013-11-06 22:18:09 +0000523 llvm_unreachable("Unknown scope");
Nick Kledzike34182f2013-11-06 21:36:55 +0000524}
525
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000526bool Util::AtomSorter::operator()(const AtomAndIndex &left,
Nick Kledzike34182f2013-11-06 21:36:55 +0000527 const AtomAndIndex &right) {
528 return (left.atom->name().compare(right.atom->name()) < 0);
529}
530
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000531
Nick Kledzike34182f2013-11-06 21:36:55 +0000532bool Util::belongsInGlobalSymbolsSection(const DefinedAtom* atom) {
533 return (atom->scope() == Atom::scopeGlobal);
534}
535
536void Util::addSymbols(const lld::File &atomFile, NormalizedFile &file) {
537 // Mach-O symbol table has three regions: locals, globals, undefs.
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000538
Nick Kledzike34182f2013-11-06 21:36:55 +0000539 // Add all local (non-global) symbols in address order
540 std::vector<AtomAndIndex> globals;
541 globals.reserve(512);
542 for (SectionInfo *sect : _sectionInfos) {
543 for (const AtomInfo &info : sect->atomsAndOffsets) {
544 const DefinedAtom *atom = info.atom;
545 if (!atom->name().empty()) {
546 if (belongsInGlobalSymbolsSection(atom)) {
547 AtomAndIndex ai = { atom, sect->finalSectionIndex };
548 globals.push_back(ai);
549 } else {
550 Symbol sym;
551 sym.name = atom->name();
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000552 sym.type = N_SECT;
Nick Kledzike34182f2013-11-06 21:36:55 +0000553 sym.scope = scopeBits(atom);
554 sym.sect = sect->finalSectionIndex;
555 sym.desc = 0;
556 sym.value = _atomToAddress[atom];
557 file.localSymbols.push_back(sym);
558 }
559 }
560 }
561 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000562
Nick Kledzike34182f2013-11-06 21:36:55 +0000563 // Sort global symbol alphabetically, then add to symbol table.
564 std::sort(globals.begin(), globals.end(), AtomSorter());
565 for (AtomAndIndex &ai : globals) {
566 Symbol sym;
567 sym.name = ai.atom->name();
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000568 sym.type = N_SECT;
Nick Kledzike34182f2013-11-06 21:36:55 +0000569 sym.scope = scopeBits(static_cast<const DefinedAtom*>(ai.atom));
570 sym.sect = ai.index;
571 sym.desc = 0;
572 sym.value = _atomToAddress[ai.atom];
573 file.globalSymbols.push_back(sym);
574 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000575
576
Nick Kledzike34182f2013-11-06 21:36:55 +0000577 // Sort undefined symbol alphabetically, then add to symbol table.
578 std::vector<AtomAndIndex> undefs;
579 undefs.reserve(128);
580 for (const UndefinedAtom *atom : atomFile.undefined()) {
581 AtomAndIndex ai = { atom, 0 };
582 undefs.push_back(ai);
583 }
584 for (const SharedLibraryAtom *atom : atomFile.sharedLibrary()) {
585 AtomAndIndex ai = { atom, 0 };
586 undefs.push_back(ai);
587 }
588 std::sort(undefs.begin(), undefs.end(), AtomSorter());
589 const uint32_t start = file.globalSymbols.size() + file.localSymbols.size();
590 for (AtomAndIndex &ai : undefs) {
591 Symbol sym;
592 sym.name = ai.atom->name();
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000593 sym.type = N_UNDF;
Nick Kledzike34182f2013-11-06 21:36:55 +0000594 sym.scope = N_EXT;
595 sym.sect = 0;
596 sym.desc = 0;
597 sym.value = 0;
598 _atomToSymbolIndex[ai.atom] = file.undefinedSymbols.size() + start;
599 file.undefinedSymbols.push_back(sym);
600 }
601}
602
603const Atom *Util::targetOfLazyPointer(const DefinedAtom *lpAtom) {
604 for (const Reference *ref : *lpAtom) {
Nick Kledzike5552772013-12-19 21:58:00 +0000605 if (_context.kindHandler().isLazyTarget(*ref)) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000606 return ref->target();
607 }
608 }
609 return nullptr;
610}
611
612const Atom *Util::targetOfStub(const DefinedAtom *stubAtom) {
613 for (const Reference *ref : *stubAtom) {
614 if (const Atom *ta = ref->target()) {
615 if (const DefinedAtom *lpAtom = dyn_cast<DefinedAtom>(ta)) {
616 const Atom *target = targetOfLazyPointer(lpAtom);
617 if (target)
618 return target;
619 }
620 }
621 }
622 return nullptr;
623}
624
625
626void Util::addIndirectSymbols(const lld::File &atomFile, NormalizedFile &file) {
627 for (SectionInfo *si : _sectionInfos) {
628 Section &normSect = file.sections[si->normalizedSectionIndex];
629 switch (si->type) {
630 case llvm::MachO::S_NON_LAZY_SYMBOL_POINTERS:
631 for (const AtomInfo &info : si->atomsAndOffsets) {
632 bool foundTarget = false;
633 for (const Reference *ref : *info.atom) {
634 const Atom *target = ref->target();
635 if (target) {
636 if (isa<const SharedLibraryAtom>(target)) {
637 uint32_t index = _atomToSymbolIndex[target];
638 normSect.indirectSymbols.push_back(index);
639 foundTarget = true;
640 } else {
641 normSect.indirectSymbols.push_back(
642 llvm::MachO::INDIRECT_SYMBOL_LOCAL);
643 }
644 }
645 }
646 if (!foundTarget) {
647 normSect.indirectSymbols.push_back(
648 llvm::MachO::INDIRECT_SYMBOL_ABS);
649 }
650 }
651 break;
652 case llvm::MachO::S_LAZY_SYMBOL_POINTERS:
653 for (const AtomInfo &info : si->atomsAndOffsets) {
654 const Atom *target = targetOfLazyPointer(info.atom);
655 if (target) {
656 uint32_t index = _atomToSymbolIndex[target];
657 normSect.indirectSymbols.push_back(index);
658 }
659 }
660 break;
661 case llvm::MachO::S_SYMBOL_STUBS:
662 for (const AtomInfo &info : si->atomsAndOffsets) {
663 const Atom *target = targetOfStub(info.atom);
664 if (target) {
665 uint32_t index = _atomToSymbolIndex[target];
666 normSect.indirectSymbols.push_back(index);
667 }
668 }
669 break;
670 default:
671 break;
672 }
673 }
674
675}
676
677void Util::addDependentDylibs(const lld::File &atomFile,NormalizedFile &nFile) {
678 // Scan all imported symbols and build up list of dylibs they are from.
679 int ordinal = 1;
680 for (const SharedLibraryAtom *slAtom : atomFile.sharedLibrary()) {
681 StringRef loadPath = slAtom->loadName();
682 DylibPathToInfo::iterator pos = _dylibInfo.find(loadPath);
683 if (pos == _dylibInfo.end()) {
684 DylibInfo info;
685 info.ordinal = ordinal++;
686 info.hasWeak = slAtom->canBeNullAtRuntime();
687 info.hasNonWeak = !info.hasWeak;
688 _dylibInfo[loadPath] = info;
689 DependentDylib depInfo;
690 depInfo.path = loadPath;
691 depInfo.kind = llvm::MachO::LC_LOAD_DYLIB;
692 nFile.dependentDylibs.push_back(depInfo);
693 } else {
694 if ( slAtom->canBeNullAtRuntime() )
695 pos->second.hasWeak = true;
696 else
697 pos->second.hasNonWeak = true;
698 }
699 }
700 // Automatically weak link dylib in which all symbols are weak (canBeNull).
701 for (DependentDylib &dep : nFile.dependentDylibs) {
702 DylibInfo &info = _dylibInfo[dep.path];
703 if (info.hasWeak && !info.hasNonWeak)
704 dep.kind = llvm::MachO::LC_LOAD_WEAK_DYLIB;
705 }
706}
707
708
709int Util::dylibOrdinal(const SharedLibraryAtom *sa) {
710 return _dylibInfo[sa->loadName()].ordinal;
711}
712
713void Util::segIndexForSection(const SectionInfo *sect, uint8_t &segmentIndex,
714 uint64_t &segmentStartAddr) {
715 segmentIndex = 0;
716 for (const SegmentInfo *seg : _segmentInfos) {
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000717 if ((seg->address <= sect->address)
Nick Kledzike34182f2013-11-06 21:36:55 +0000718 && (seg->address+seg->size >= sect->address+sect->size)) {
719 segmentStartAddr = seg->address;
720 return;
721 }
722 ++segmentIndex;
723 }
724 llvm_unreachable("section not in any segment");
725}
726
727
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000728void Util::appendReloc(const DefinedAtom *atom, const Reference *ref,
Nick Kledzike34182f2013-11-06 21:36:55 +0000729 Relocations &relocations) {
730 // TODO: convert Reference to normalized relocation
731}
732
733void Util::addSectionRelocs(const lld::File &, NormalizedFile &file) {
734 if (_context.outputFileType() != llvm::MachO::MH_OBJECT)
735 return;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000736
Nick Kledzike34182f2013-11-06 21:36:55 +0000737 for (SectionInfo *si : _sectionInfos) {
738 Section &normSect = file.sections[si->normalizedSectionIndex];
739 for (const AtomInfo &info : si->atomsAndOffsets) {
740 const DefinedAtom *atom = info.atom;
741 for (const Reference *ref : *atom) {
742 appendReloc(atom, ref, normSect.relocations);
743 }
744 }
745 }
746}
747
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000748void Util::addRebaseAndBindingInfo(const lld::File &atomFile,
Nick Kledzike34182f2013-11-06 21:36:55 +0000749 NormalizedFile &nFile) {
750 if (_context.outputFileType() == llvm::MachO::MH_OBJECT)
751 return;
752
753 uint8_t segmentIndex;
754 uint64_t segmentStartAddr;
755 for (SectionInfo *sect : _sectionInfos) {
756 segIndexForSection(sect, segmentIndex, segmentStartAddr);
757 for (const AtomInfo &info : sect->atomsAndOffsets) {
758 const DefinedAtom *atom = info.atom;
759 for (const Reference *ref : *atom) {
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000760 uint64_t segmentOffset = _atomToAddress[atom] + ref->offsetInAtom()
Nick Kledzike34182f2013-11-06 21:36:55 +0000761 - segmentStartAddr;
762 const Atom* targ = ref->target();
Nick Kledzike5552772013-12-19 21:58:00 +0000763 if (_context.kindHandler().isPointer(*ref)) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000764 // A pointer to a DefinedAtom requires rebasing.
765 if (dyn_cast<DefinedAtom>(targ)) {
766 RebaseLocation rebase;
767 rebase.segIndex = segmentIndex;
768 rebase.segOffset = segmentOffset;
769 rebase.kind = llvm::MachO::REBASE_TYPE_POINTER;
770 nFile.rebasingInfo.push_back(rebase);
771 }
772 // A pointer to an SharedLibraryAtom requires binding.
773 if (const SharedLibraryAtom *sa = dyn_cast<SharedLibraryAtom>(targ)) {
774 BindLocation bind;
775 bind.segIndex = segmentIndex;
776 bind.segOffset = segmentOffset;
777 bind.kind = llvm::MachO::BIND_TYPE_POINTER;
778 bind.canBeNull = sa->canBeNullAtRuntime();
779 bind.ordinal = dylibOrdinal(sa);
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000780 bind.symbolName = targ->name();
Nick Kledzike34182f2013-11-06 21:36:55 +0000781 bind.addend = ref->addend();
782 nFile.bindingInfo.push_back(bind);
783 }
784 }
Nick Kledzike5552772013-12-19 21:58:00 +0000785 if (_context.kindHandler().isLazyTarget(*ref)) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000786 BindLocation bind;
787 bind.segIndex = segmentIndex;
788 bind.segOffset = segmentOffset;
789 bind.kind = llvm::MachO::BIND_TYPE_POINTER;
790 bind.canBeNull = false; //sa->canBeNullAtRuntime();
791 bind.ordinal = 1;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000792 bind.symbolName = targ->name();
Nick Kledzike34182f2013-11-06 21:36:55 +0000793 bind.addend = ref->addend();
794 nFile.lazyBindingInfo.push_back(bind);
795 }
796 }
797 }
798 }
799}
800
801uint32_t Util::fileFlags() {
802 return 0; //FIX ME
803}
804
805} // end anonymous namespace
806
807
808namespace lld {
809namespace mach_o {
810namespace normalized {
811
812/// Convert a set of Atoms into a normalized mach-o file.
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000813ErrorOr<std::unique_ptr<NormalizedFile>>
814normalizedFromAtoms(const lld::File &atomFile,
Nick Kledzike34182f2013-11-06 21:36:55 +0000815 const MachOLinkingContext &context) {
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000816 // The util object buffers info until the normalized file can be made.
Nick Kledzike34182f2013-11-06 21:36:55 +0000817 Util util(context);
818 util.assignAtomsToSections(atomFile);
819 util.organizeSections();
820 util.assignAddressesToSections();
821 util.buildAtomToAddressMap();
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000822
Nick Kledzike34182f2013-11-06 21:36:55 +0000823 std::unique_ptr<NormalizedFile> f(new NormalizedFile());
824 NormalizedFile &normFile = *f.get();
825 f->arch = context.arch();
826 f->fileType = context.outputFileType();
827 f->flags = util.fileFlags();
828 util.copySegmentInfo(normFile);
829 util.copySections(normFile);
830 util.addDependentDylibs(atomFile, normFile);
831 util.addSymbols(atomFile, normFile);
832 util.addIndirectSymbols(atomFile, normFile);
833 util.addRebaseAndBindingInfo(atomFile, normFile);
834 util.addSectionRelocs(atomFile, normFile);
835 util.copyEntryPointAddress(normFile);
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000836
Nick Kledzike34182f2013-11-06 21:36:55 +0000837 return std::move(f);
838}
839
840
841} // namespace normalized
842} // namespace mach_o
843} // namespace lld
844