blob: 1b548d9df6236a00e26d05fa7fafacbf7f5a0464 [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 Kledzike34182f2013-11-06 21:36:55 +0000200 default:
201 llvm_unreachable("TO DO: add support for more sections");
202 break;
203 }
204}
205
206
207
208SectionInfo *Util::sectionForAtom(const DefinedAtom *atom) {
209 DefinedAtom::ContentType type = atom->contentType();
210 auto pos = _sectionMap.find(type);
211 if ( pos != _sectionMap.end() )
212 return pos->second;
213 SectionInfo *si = makeSection(type);
214 _sectionInfos.push_back(si);
215 _sectionMap[type] = si;
216 return si;
217}
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000218
Nick Kledzike34182f2013-11-06 21:36:55 +0000219
220void Util::appendAtom(SectionInfo *sect, const DefinedAtom *atom) {
221 // Figure out offset for atom in this section given alignment constraints.
222 uint64_t offset = sect->size;
223 DefinedAtom::Alignment atomAlign = atom->alignment();
224 uint64_t align2 = 1 << atomAlign.powerOf2;
225 uint64_t requiredModulus = atomAlign.modulus;
226 uint64_t currentModulus = (offset % align2);
227 if ( currentModulus != requiredModulus ) {
228 if ( requiredModulus > currentModulus )
229 offset += requiredModulus-currentModulus;
230 else
231 offset += align2+requiredModulus-currentModulus;
232 }
233 // Record max alignment of any atom in this section.
234 if ( atomAlign.powerOf2 > sect->alignment )
235 sect->alignment = atomAlign.powerOf2;
236 // Assign atom to this section with this offset.
237 AtomInfo ai = {atom, offset};
238 sect->atomsAndOffsets.push_back(ai);
239 // Update section size to include this atom.
240 sect->size = offset + atom->size();
241}
242
243void Util::assignAtomsToSections(const lld::File &atomFile) {
244 for (const DefinedAtom *atom : atomFile.defined()) {
245 appendAtom(sectionForAtom(atom), atom);
246 }
247}
248
249SegmentInfo *Util::segmentForName(StringRef segName) {
250 for (SegmentInfo *si : _segmentInfos) {
251 if ( si->name.equals(segName) )
252 return si;
253 }
254 SegmentInfo *info = new (_allocator) SegmentInfo(segName);
255 if (segName.equals("__TEXT"))
256 info->access = VM_PROT_READ | VM_PROT_EXECUTE;
257 else if (segName.equals("__DATA"))
258 info->access = VM_PROT_READ | VM_PROT_WRITE;
259 else if (segName.equals("__PAGEZERO"))
260 info->access = 0;
261 _segmentInfos.push_back(info);
262 return info;
263}
264
265unsigned Util::SegmentSorter::weight(const SegmentInfo *seg) {
266 return llvm::StringSwitch<unsigned>(seg->name)
267 .Case("__PAGEZERO", 1)
268 .Case("__TEXT", 2)
269 .Case("__DATA", 3)
270 .Default(100);
271}
272
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000273bool Util::SegmentSorter::operator()(const SegmentInfo *left,
Nick Kledzike34182f2013-11-06 21:36:55 +0000274 const SegmentInfo *right) {
275 return (weight(left) < weight(right));
276}
277
278unsigned Util::TextSectionSorter::weight(const SectionInfo *sect) {
279 return llvm::StringSwitch<unsigned>(sect->sectionName)
280 .Case("__text", 1)
281 .Case("__stubs", 2)
282 .Case("__stub_helper", 3)
283 .Case("__const", 4)
284 .Case("__cstring", 5)
285 .Case("__unwind_info", 98)
286 .Case("__eh_frame", 99)
287 .Default(10);
288}
289
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000290bool Util::TextSectionSorter::operator()(const SectionInfo *left,
Nick Kledzike34182f2013-11-06 21:36:55 +0000291 const SectionInfo *right) {
292 return (weight(left) < weight(right));
293}
294
295
296void Util::organizeSections() {
297 if (_context.outputFileType() == llvm::MachO::MH_OBJECT) {
298 // Leave sections ordered as normalized file specified.
299 uint32_t sectionIndex = 1;
300 for (SectionInfo *si : _sectionInfos) {
301 si->finalSectionIndex = sectionIndex++;
302 }
303 } else {
304 // Main executables, need a zero-page segment
305 if (_context.outputFileType() == llvm::MachO::MH_EXECUTE)
306 segmentForName("__PAGEZERO");
307 // Group sections into segments.
308 for (SectionInfo *si : _sectionInfos) {
309 SegmentInfo *seg = segmentForName(si->segmentName);
310 seg->sections.push_back(si);
311 }
312 // Sort segments.
313 std::sort(_segmentInfos.begin(), _segmentInfos.end(), SegmentSorter());
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000314
Nick Kledzike34182f2013-11-06 21:36:55 +0000315 // Sort sections within segments.
316 for (SegmentInfo *seg : _segmentInfos) {
317 if (seg->name.equals("__TEXT")) {
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000318 std::sort(seg->sections.begin(), seg->sections.end(),
Nick Kledzike34182f2013-11-06 21:36:55 +0000319 TextSectionSorter());
320 }
321 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000322
Nick Kledzike34182f2013-11-06 21:36:55 +0000323 // Record final section indexes.
324 uint32_t sectionIndex = 1;
325 for (SegmentInfo *seg : _segmentInfos) {
326 for (SectionInfo *sect : seg->sections) {
327 sect->finalSectionIndex = sectionIndex++;
328 }
329 }
330 }
331
332}
333
334uint64_t Util::alignTo(uint64_t value, uint8_t align2) {
335 return llvm::RoundUpToAlignment(value, 1 << align2);
336}
337
338
339void Util::layoutSectionsInSegment(SegmentInfo *seg, uint64_t &addr) {
340 seg->address = addr;
341 for (SectionInfo *sect : seg->sections) {
342 sect->address = alignTo(addr, sect->alignment);
343 addr += sect->size;
344 }
345 seg->size = llvm::RoundUpToAlignment(addr - seg->address,_context.pageSize());
346}
347
348
349// __TEXT segment lays out backwards so padding is at front after load commands.
350void Util::layoutSectionsInTextSegment(SegmentInfo *seg, uint64_t &addr) {
351 seg->address = addr;
352 // Walks sections starting at end to calculate padding for start.
353 int64_t taddr = 0;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000354 for (auto it = seg->sections.rbegin(); it != seg->sections.rend(); ++it) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000355 SectionInfo *sect = *it;
356 taddr -= sect->size;
357 taddr = taddr & (0 - (1 << sect->alignment));
358 }
359 int64_t padding = taddr;
360 while (padding < 0)
361 padding += _context.pageSize();
362 // Start assigning section address starting at padded offset.
363 addr += padding;
364 for (SectionInfo *sect : seg->sections) {
365 sect->address = alignTo(addr, sect->alignment);
366 addr = sect->address + sect->size;
367 }
368 seg->size = llvm::RoundUpToAlignment(addr - seg->address,_context.pageSize());
369}
370
371
372void Util::assignAddressesToSections() {
373 uint64_t address = 0; // FIXME
374 if (_context.outputFileType() != llvm::MachO::MH_OBJECT) {
375 for (SegmentInfo *seg : _segmentInfos) {
376 if (seg->name.equals("__PAGEZERO")) {
377 seg->size = _context.pageZeroSize();
378 address += seg->size;
379 }
380 else if (seg->name.equals("__TEXT"))
381 layoutSectionsInTextSegment(seg, address);
382 else
383 layoutSectionsInSegment(seg, address);
384 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000385 DEBUG_WITH_TYPE("WriterMachO-norm",
Nick Kledzik020a49c2013-11-06 21:57:52 +0000386 llvm::dbgs() << "assignAddressesToSections()\n";
387 for (SegmentInfo *sgi : _segmentInfos) {
388 llvm::dbgs() << " address=" << llvm::format("0x%08llX", sgi->address)
Nick Kledzike34182f2013-11-06 21:36:55 +0000389 << ", size=" << llvm::format("0x%08llX", sgi->size)
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000390 << ", segment-name='" << sgi->name
Nick Kledzik020a49c2013-11-06 21:57:52 +0000391 << "'\n";
392 for (SectionInfo *si : sgi->sections) {
393 llvm::dbgs()<< " addr=" << llvm::format("0x%08llX", si->address)
Nick Kledzike34182f2013-11-06 21:36:55 +0000394 << ", size=" << llvm::format("0x%08llX", si->size)
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000395 << ", section-name='" << si->sectionName
Nick Kledzik020a49c2013-11-06 21:57:52 +0000396 << "\n";
397 }
Nick Kledzike34182f2013-11-06 21:36:55 +0000398 }
Nick Kledzik020a49c2013-11-06 21:57:52 +0000399 );
Nick Kledzike34182f2013-11-06 21:36:55 +0000400 } else {
401 for (SectionInfo *sect : _sectionInfos) {
402 sect->address = alignTo(address, sect->alignment);
403 address = sect->address + sect->size;
404 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000405 DEBUG_WITH_TYPE("WriterMachO-norm",
Nick Kledzik020a49c2013-11-06 21:57:52 +0000406 llvm::dbgs() << "assignAddressesToSections()\n";
407 for (SectionInfo *si : _sectionInfos) {
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000408 llvm::dbgs() << " section=" << si->sectionName
Nick Kledzike34182f2013-11-06 21:36:55 +0000409 << " address= " << llvm::format("0x%08X", si->address)
410 << " size= " << llvm::format("0x%08X", si->size)
Nick Kledzik020a49c2013-11-06 21:57:52 +0000411 << "\n";
412 }
413 );
Nick Kledzike34182f2013-11-06 21:36:55 +0000414 }
Nick Kledzike34182f2013-11-06 21:36:55 +0000415}
416
417
418void Util::copySegmentInfo(NormalizedFile &file) {
419 for (SegmentInfo *sgi : _segmentInfos) {
420 Segment seg;
421 seg.name = sgi->name;
422 seg.address = sgi->address;
423 seg.size = sgi->size;
424 seg.access = sgi->access;
425 file.segments.push_back(seg);
426 }
427}
428
429void Util::appendSection(SectionInfo *si, NormalizedFile &file) {
430 // Add new empty section to end of file.sections.
431 Section temp;
432 file.sections.push_back(std::move(temp));
433 Section* normSect = &file.sections.back();
434 // Copy fields to normalized section.
435 normSect->segmentName = si->segmentName;
436 normSect->sectionName = si->sectionName;
437 normSect->type = si->type;
438 normSect->attributes = si->attributes;
439 normSect->address = si->address;
440 normSect->alignment = si->alignment;
441 // Record where normalized section is.
442 si->normalizedSectionIndex = file.sections.size()-1;
443 // Copy content from atoms to content buffer for section.
Nick Kledzik61fdef62014-05-15 20:59:23 +0000444 if (si->type == llvm::MachO::S_ZEROFILL)
445 return;
Nick Kledzik6edd7222014-01-11 01:07:43 +0000446 uint8_t *sectionContent = file.ownedAllocations.Allocate<uint8_t>(si->size);
447 normSect->content = llvm::makeArrayRef(sectionContent, si->size);
Nick Kledzike34182f2013-11-06 21:36:55 +0000448 for (AtomInfo &ai : si->atomsAndOffsets) {
449 // Copy raw bytes.
450 uint8_t *atomContent = reinterpret_cast<uint8_t*>
451 (&sectionContent[ai.offsetInSection]);
452 memcpy(atomContent, ai.atom->rawContent().data(), ai.atom->size());
453 // Apply fix-ups.
454 for (const Reference *ref : *ai.atom) {
455 uint32_t offset = ref->offsetInAtom();
456 uint64_t targetAddress = 0;
457 if ( ref->target() != nullptr )
458 targetAddress = _atomToAddress[ref->target()];
459 uint64_t fixupAddress = _atomToAddress[ai.atom] + offset;
Rui Ueyama170a1a82013-12-20 07:48:29 +0000460 _context.kindHandler().applyFixup(
461 ref->kindNamespace(), ref->kindArch(), ref->kindValue(),
462 ref->addend(), &atomContent[offset], fixupAddress, targetAddress);
Nick Kledzike34182f2013-11-06 21:36:55 +0000463 }
464 }
465}
466
467void Util::copySections(NormalizedFile &file) {
468 file.sections.reserve(_sectionInfos.size());
469 // For final linked images, write sections grouped by segment.
470 if (_context.outputFileType() != llvm::MachO::MH_OBJECT) {
471 for (SegmentInfo *sgi : _segmentInfos) {
472 for (SectionInfo *si : sgi->sections) {
473 appendSection(si, file);
474 }
475 }
476 } else {
477 // Object files write sections in default order.
478 for (SectionInfo *si : _sectionInfos) {
479 appendSection(si, file);
480 }
481 }
482}
483
484void Util::copyEntryPointAddress(NormalizedFile &nFile) {
485 if (_context.outputTypeHasEntry()) {
486 nFile.entryAddress = _atomToAddress[_entryAtom];
487 }
488}
489
490void Util::buildAtomToAddressMap() {
491 DEBUG_WITH_TYPE("WriterMachO-address", llvm::dbgs()
492 << "assign atom addresses:\n");
493 const bool lookForEntry = _context.outputTypeHasEntry();
494 for (SectionInfo *sect : _sectionInfos) {
495 for (const AtomInfo &info : sect->atomsAndOffsets) {
496 _atomToAddress[info.atom] = sect->address + info.offsetInSection;
497 if (lookForEntry && (info.atom->contentType() == DefinedAtom::typeCode) &&
498 (info.atom->size() != 0) &&
499 info.atom->name() == _context.entrySymbolName()) {
500 _entryAtom = info.atom;
501 }
502 DEBUG_WITH_TYPE("WriterMachO-address", llvm::dbgs()
503 << " address="
504 << llvm::format("0x%016X", _atomToAddress[info.atom])
505 << " atom=" << info.atom
506 << " name=" << info.atom->name() << "\n");
507 }
508 }
509}
510
511uint8_t Util::scopeBits(const DefinedAtom* atom) {
512 switch (atom->scope()) {
513 case Atom::scopeTranslationUnit:
514 return 0;
515 case Atom::scopeLinkageUnit:
516 return N_PEXT | N_EXT;
517 case Atom::scopeGlobal:
518 return N_EXT;
519 }
Nick Kledzik020fa7f2013-11-06 22:18:09 +0000520 llvm_unreachable("Unknown scope");
Nick Kledzike34182f2013-11-06 21:36:55 +0000521}
522
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000523bool Util::AtomSorter::operator()(const AtomAndIndex &left,
Nick Kledzike34182f2013-11-06 21:36:55 +0000524 const AtomAndIndex &right) {
525 return (left.atom->name().compare(right.atom->name()) < 0);
526}
527
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000528
Nick Kledzike34182f2013-11-06 21:36:55 +0000529bool Util::belongsInGlobalSymbolsSection(const DefinedAtom* atom) {
530 return (atom->scope() == Atom::scopeGlobal);
531}
532
533void Util::addSymbols(const lld::File &atomFile, NormalizedFile &file) {
534 // Mach-O symbol table has three regions: locals, globals, undefs.
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000535
Nick Kledzike34182f2013-11-06 21:36:55 +0000536 // Add all local (non-global) symbols in address order
537 std::vector<AtomAndIndex> globals;
538 globals.reserve(512);
539 for (SectionInfo *sect : _sectionInfos) {
540 for (const AtomInfo &info : sect->atomsAndOffsets) {
541 const DefinedAtom *atom = info.atom;
542 if (!atom->name().empty()) {
543 if (belongsInGlobalSymbolsSection(atom)) {
544 AtomAndIndex ai = { atom, sect->finalSectionIndex };
545 globals.push_back(ai);
546 } else {
547 Symbol sym;
548 sym.name = atom->name();
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000549 sym.type = N_SECT;
Nick Kledzike34182f2013-11-06 21:36:55 +0000550 sym.scope = scopeBits(atom);
551 sym.sect = sect->finalSectionIndex;
552 sym.desc = 0;
553 sym.value = _atomToAddress[atom];
554 file.localSymbols.push_back(sym);
555 }
556 }
557 }
558 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000559
Nick Kledzike34182f2013-11-06 21:36:55 +0000560 // Sort global symbol alphabetically, then add to symbol table.
561 std::sort(globals.begin(), globals.end(), AtomSorter());
562 for (AtomAndIndex &ai : globals) {
563 Symbol sym;
564 sym.name = ai.atom->name();
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000565 sym.type = N_SECT;
Nick Kledzike34182f2013-11-06 21:36:55 +0000566 sym.scope = scopeBits(static_cast<const DefinedAtom*>(ai.atom));
567 sym.sect = ai.index;
568 sym.desc = 0;
569 sym.value = _atomToAddress[ai.atom];
570 file.globalSymbols.push_back(sym);
571 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000572
573
Nick Kledzike34182f2013-11-06 21:36:55 +0000574 // Sort undefined symbol alphabetically, then add to symbol table.
575 std::vector<AtomAndIndex> undefs;
576 undefs.reserve(128);
577 for (const UndefinedAtom *atom : atomFile.undefined()) {
578 AtomAndIndex ai = { atom, 0 };
579 undefs.push_back(ai);
580 }
581 for (const SharedLibraryAtom *atom : atomFile.sharedLibrary()) {
582 AtomAndIndex ai = { atom, 0 };
583 undefs.push_back(ai);
584 }
585 std::sort(undefs.begin(), undefs.end(), AtomSorter());
586 const uint32_t start = file.globalSymbols.size() + file.localSymbols.size();
587 for (AtomAndIndex &ai : undefs) {
588 Symbol sym;
589 sym.name = ai.atom->name();
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000590 sym.type = N_UNDF;
Nick Kledzike34182f2013-11-06 21:36:55 +0000591 sym.scope = N_EXT;
592 sym.sect = 0;
593 sym.desc = 0;
594 sym.value = 0;
595 _atomToSymbolIndex[ai.atom] = file.undefinedSymbols.size() + start;
596 file.undefinedSymbols.push_back(sym);
597 }
598}
599
600const Atom *Util::targetOfLazyPointer(const DefinedAtom *lpAtom) {
601 for (const Reference *ref : *lpAtom) {
Nick Kledzike5552772013-12-19 21:58:00 +0000602 if (_context.kindHandler().isLazyTarget(*ref)) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000603 return ref->target();
604 }
605 }
606 return nullptr;
607}
608
609const Atom *Util::targetOfStub(const DefinedAtom *stubAtom) {
610 for (const Reference *ref : *stubAtom) {
611 if (const Atom *ta = ref->target()) {
612 if (const DefinedAtom *lpAtom = dyn_cast<DefinedAtom>(ta)) {
613 const Atom *target = targetOfLazyPointer(lpAtom);
614 if (target)
615 return target;
616 }
617 }
618 }
619 return nullptr;
620}
621
622
623void Util::addIndirectSymbols(const lld::File &atomFile, NormalizedFile &file) {
624 for (SectionInfo *si : _sectionInfos) {
625 Section &normSect = file.sections[si->normalizedSectionIndex];
626 switch (si->type) {
627 case llvm::MachO::S_NON_LAZY_SYMBOL_POINTERS:
628 for (const AtomInfo &info : si->atomsAndOffsets) {
629 bool foundTarget = false;
630 for (const Reference *ref : *info.atom) {
631 const Atom *target = ref->target();
632 if (target) {
633 if (isa<const SharedLibraryAtom>(target)) {
634 uint32_t index = _atomToSymbolIndex[target];
635 normSect.indirectSymbols.push_back(index);
636 foundTarget = true;
637 } else {
638 normSect.indirectSymbols.push_back(
639 llvm::MachO::INDIRECT_SYMBOL_LOCAL);
640 }
641 }
642 }
643 if (!foundTarget) {
644 normSect.indirectSymbols.push_back(
645 llvm::MachO::INDIRECT_SYMBOL_ABS);
646 }
647 }
648 break;
649 case llvm::MachO::S_LAZY_SYMBOL_POINTERS:
650 for (const AtomInfo &info : si->atomsAndOffsets) {
651 const Atom *target = targetOfLazyPointer(info.atom);
652 if (target) {
653 uint32_t index = _atomToSymbolIndex[target];
654 normSect.indirectSymbols.push_back(index);
655 }
656 }
657 break;
658 case llvm::MachO::S_SYMBOL_STUBS:
659 for (const AtomInfo &info : si->atomsAndOffsets) {
660 const Atom *target = targetOfStub(info.atom);
661 if (target) {
662 uint32_t index = _atomToSymbolIndex[target];
663 normSect.indirectSymbols.push_back(index);
664 }
665 }
666 break;
667 default:
668 break;
669 }
670 }
671
672}
673
674void Util::addDependentDylibs(const lld::File &atomFile,NormalizedFile &nFile) {
675 // Scan all imported symbols and build up list of dylibs they are from.
676 int ordinal = 1;
677 for (const SharedLibraryAtom *slAtom : atomFile.sharedLibrary()) {
678 StringRef loadPath = slAtom->loadName();
679 DylibPathToInfo::iterator pos = _dylibInfo.find(loadPath);
680 if (pos == _dylibInfo.end()) {
681 DylibInfo info;
682 info.ordinal = ordinal++;
683 info.hasWeak = slAtom->canBeNullAtRuntime();
684 info.hasNonWeak = !info.hasWeak;
685 _dylibInfo[loadPath] = info;
686 DependentDylib depInfo;
687 depInfo.path = loadPath;
688 depInfo.kind = llvm::MachO::LC_LOAD_DYLIB;
689 nFile.dependentDylibs.push_back(depInfo);
690 } else {
691 if ( slAtom->canBeNullAtRuntime() )
692 pos->second.hasWeak = true;
693 else
694 pos->second.hasNonWeak = true;
695 }
696 }
697 // Automatically weak link dylib in which all symbols are weak (canBeNull).
698 for (DependentDylib &dep : nFile.dependentDylibs) {
699 DylibInfo &info = _dylibInfo[dep.path];
700 if (info.hasWeak && !info.hasNonWeak)
701 dep.kind = llvm::MachO::LC_LOAD_WEAK_DYLIB;
702 }
703}
704
705
706int Util::dylibOrdinal(const SharedLibraryAtom *sa) {
707 return _dylibInfo[sa->loadName()].ordinal;
708}
709
710void Util::segIndexForSection(const SectionInfo *sect, uint8_t &segmentIndex,
711 uint64_t &segmentStartAddr) {
712 segmentIndex = 0;
713 for (const SegmentInfo *seg : _segmentInfos) {
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000714 if ((seg->address <= sect->address)
Nick Kledzike34182f2013-11-06 21:36:55 +0000715 && (seg->address+seg->size >= sect->address+sect->size)) {
716 segmentStartAddr = seg->address;
717 return;
718 }
719 ++segmentIndex;
720 }
721 llvm_unreachable("section not in any segment");
722}
723
724
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000725void Util::appendReloc(const DefinedAtom *atom, const Reference *ref,
Nick Kledzike34182f2013-11-06 21:36:55 +0000726 Relocations &relocations) {
727 // TODO: convert Reference to normalized relocation
728}
729
730void Util::addSectionRelocs(const lld::File &, NormalizedFile &file) {
731 if (_context.outputFileType() != llvm::MachO::MH_OBJECT)
732 return;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000733
Nick Kledzike34182f2013-11-06 21:36:55 +0000734 for (SectionInfo *si : _sectionInfos) {
735 Section &normSect = file.sections[si->normalizedSectionIndex];
736 for (const AtomInfo &info : si->atomsAndOffsets) {
737 const DefinedAtom *atom = info.atom;
738 for (const Reference *ref : *atom) {
739 appendReloc(atom, ref, normSect.relocations);
740 }
741 }
742 }
743}
744
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000745void Util::addRebaseAndBindingInfo(const lld::File &atomFile,
Nick Kledzike34182f2013-11-06 21:36:55 +0000746 NormalizedFile &nFile) {
747 if (_context.outputFileType() == llvm::MachO::MH_OBJECT)
748 return;
749
750 uint8_t segmentIndex;
751 uint64_t segmentStartAddr;
752 for (SectionInfo *sect : _sectionInfos) {
753 segIndexForSection(sect, segmentIndex, segmentStartAddr);
754 for (const AtomInfo &info : sect->atomsAndOffsets) {
755 const DefinedAtom *atom = info.atom;
756 for (const Reference *ref : *atom) {
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000757 uint64_t segmentOffset = _atomToAddress[atom] + ref->offsetInAtom()
Nick Kledzike34182f2013-11-06 21:36:55 +0000758 - segmentStartAddr;
759 const Atom* targ = ref->target();
Nick Kledzike5552772013-12-19 21:58:00 +0000760 if (_context.kindHandler().isPointer(*ref)) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000761 // A pointer to a DefinedAtom requires rebasing.
762 if (dyn_cast<DefinedAtom>(targ)) {
763 RebaseLocation rebase;
764 rebase.segIndex = segmentIndex;
765 rebase.segOffset = segmentOffset;
766 rebase.kind = llvm::MachO::REBASE_TYPE_POINTER;
767 nFile.rebasingInfo.push_back(rebase);
768 }
769 // A pointer to an SharedLibraryAtom requires binding.
770 if (const SharedLibraryAtom *sa = dyn_cast<SharedLibraryAtom>(targ)) {
771 BindLocation bind;
772 bind.segIndex = segmentIndex;
773 bind.segOffset = segmentOffset;
774 bind.kind = llvm::MachO::BIND_TYPE_POINTER;
775 bind.canBeNull = sa->canBeNullAtRuntime();
776 bind.ordinal = dylibOrdinal(sa);
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000777 bind.symbolName = targ->name();
Nick Kledzike34182f2013-11-06 21:36:55 +0000778 bind.addend = ref->addend();
779 nFile.bindingInfo.push_back(bind);
780 }
781 }
Nick Kledzike5552772013-12-19 21:58:00 +0000782 if (_context.kindHandler().isLazyTarget(*ref)) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000783 BindLocation bind;
784 bind.segIndex = segmentIndex;
785 bind.segOffset = segmentOffset;
786 bind.kind = llvm::MachO::BIND_TYPE_POINTER;
787 bind.canBeNull = false; //sa->canBeNullAtRuntime();
788 bind.ordinal = 1;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000789 bind.symbolName = targ->name();
Nick Kledzike34182f2013-11-06 21:36:55 +0000790 bind.addend = ref->addend();
791 nFile.lazyBindingInfo.push_back(bind);
792 }
793 }
794 }
795 }
796}
797
798uint32_t Util::fileFlags() {
799 return 0; //FIX ME
800}
801
802} // end anonymous namespace
803
804
805namespace lld {
806namespace mach_o {
807namespace normalized {
808
809/// Convert a set of Atoms into a normalized mach-o file.
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000810ErrorOr<std::unique_ptr<NormalizedFile>>
811normalizedFromAtoms(const lld::File &atomFile,
Nick Kledzike34182f2013-11-06 21:36:55 +0000812 const MachOLinkingContext &context) {
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000813 // The util object buffers info until the normalized file can be made.
Nick Kledzike34182f2013-11-06 21:36:55 +0000814 Util util(context);
815 util.assignAtomsToSections(atomFile);
816 util.organizeSections();
817 util.assignAddressesToSections();
818 util.buildAtomToAddressMap();
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000819
Nick Kledzike34182f2013-11-06 21:36:55 +0000820 std::unique_ptr<NormalizedFile> f(new NormalizedFile());
821 NormalizedFile &normFile = *f.get();
822 f->arch = context.arch();
823 f->fileType = context.outputFileType();
824 f->flags = util.fileFlags();
825 util.copySegmentInfo(normFile);
826 util.copySections(normFile);
827 util.addDependentDylibs(atomFile, normFile);
828 util.addSymbols(atomFile, normFile);
829 util.addIndirectSymbols(atomFile, normFile);
830 util.addRebaseAndBindingInfo(atomFile, normFile);
831 util.addSectionRelocs(atomFile, normFile);
832 util.copyEntryPointAddress(normFile);
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000833
Nick Kledzike34182f2013-11-06 21:36:55 +0000834 return std::move(f);
835}
836
837
838} // namespace normalized
839} // namespace mach_o
840} // namespace lld
841