blob: 072f40d32dd7f4d4d120da9bc7525f4a3faee2fb [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 Kledzika0c13a22014-05-22 01:42:06 +0000182 case DefinedAtom::typeLiteral4:
183 return new (_allocator) SectionInfo("__TEXT", "__literal4",
184 S_4BYTE_LITERALS);
185 case DefinedAtom::typeLiteral8:
186 return new (_allocator) SectionInfo("__TEXT", "__literal8",
187 S_8BYTE_LITERALS);
188 case DefinedAtom::typeLiteral16:
189 return new (_allocator) SectionInfo("__TEXT", "__literal16",
190 S_16BYTE_LITERALS);
Nick Kledzike34182f2013-11-06 21:36:55 +0000191 default:
192 llvm_unreachable("TO DO: add support for more sections");
193 break;
194 }
195}
196
197
198
199SectionInfo *Util::sectionForAtom(const DefinedAtom *atom) {
200 DefinedAtom::ContentType type = atom->contentType();
201 auto pos = _sectionMap.find(type);
202 if ( pos != _sectionMap.end() )
203 return pos->second;
204 SectionInfo *si = makeSection(type);
205 _sectionInfos.push_back(si);
206 _sectionMap[type] = si;
207 return si;
208}
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000209
Nick Kledzike34182f2013-11-06 21:36:55 +0000210
211void Util::appendAtom(SectionInfo *sect, const DefinedAtom *atom) {
212 // Figure out offset for atom in this section given alignment constraints.
213 uint64_t offset = sect->size;
214 DefinedAtom::Alignment atomAlign = atom->alignment();
215 uint64_t align2 = 1 << atomAlign.powerOf2;
216 uint64_t requiredModulus = atomAlign.modulus;
217 uint64_t currentModulus = (offset % align2);
218 if ( currentModulus != requiredModulus ) {
219 if ( requiredModulus > currentModulus )
220 offset += requiredModulus-currentModulus;
221 else
222 offset += align2+requiredModulus-currentModulus;
223 }
224 // Record max alignment of any atom in this section.
225 if ( atomAlign.powerOf2 > sect->alignment )
226 sect->alignment = atomAlign.powerOf2;
227 // Assign atom to this section with this offset.
228 AtomInfo ai = {atom, offset};
229 sect->atomsAndOffsets.push_back(ai);
230 // Update section size to include this atom.
231 sect->size = offset + atom->size();
232}
233
234void Util::assignAtomsToSections(const lld::File &atomFile) {
235 for (const DefinedAtom *atom : atomFile.defined()) {
236 appendAtom(sectionForAtom(atom), atom);
237 }
238}
239
240SegmentInfo *Util::segmentForName(StringRef segName) {
241 for (SegmentInfo *si : _segmentInfos) {
242 if ( si->name.equals(segName) )
243 return si;
244 }
245 SegmentInfo *info = new (_allocator) SegmentInfo(segName);
246 if (segName.equals("__TEXT"))
247 info->access = VM_PROT_READ | VM_PROT_EXECUTE;
248 else if (segName.equals("__DATA"))
249 info->access = VM_PROT_READ | VM_PROT_WRITE;
250 else if (segName.equals("__PAGEZERO"))
251 info->access = 0;
252 _segmentInfos.push_back(info);
253 return info;
254}
255
256unsigned Util::SegmentSorter::weight(const SegmentInfo *seg) {
257 return llvm::StringSwitch<unsigned>(seg->name)
258 .Case("__PAGEZERO", 1)
259 .Case("__TEXT", 2)
260 .Case("__DATA", 3)
261 .Default(100);
262}
263
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000264bool Util::SegmentSorter::operator()(const SegmentInfo *left,
Nick Kledzike34182f2013-11-06 21:36:55 +0000265 const SegmentInfo *right) {
266 return (weight(left) < weight(right));
267}
268
269unsigned Util::TextSectionSorter::weight(const SectionInfo *sect) {
270 return llvm::StringSwitch<unsigned>(sect->sectionName)
271 .Case("__text", 1)
272 .Case("__stubs", 2)
273 .Case("__stub_helper", 3)
274 .Case("__const", 4)
275 .Case("__cstring", 5)
276 .Case("__unwind_info", 98)
277 .Case("__eh_frame", 99)
278 .Default(10);
279}
280
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000281bool Util::TextSectionSorter::operator()(const SectionInfo *left,
Nick Kledzike34182f2013-11-06 21:36:55 +0000282 const SectionInfo *right) {
283 return (weight(left) < weight(right));
284}
285
286
287void Util::organizeSections() {
288 if (_context.outputFileType() == llvm::MachO::MH_OBJECT) {
289 // Leave sections ordered as normalized file specified.
290 uint32_t sectionIndex = 1;
291 for (SectionInfo *si : _sectionInfos) {
292 si->finalSectionIndex = sectionIndex++;
293 }
294 } else {
295 // Main executables, need a zero-page segment
296 if (_context.outputFileType() == llvm::MachO::MH_EXECUTE)
297 segmentForName("__PAGEZERO");
298 // Group sections into segments.
299 for (SectionInfo *si : _sectionInfos) {
300 SegmentInfo *seg = segmentForName(si->segmentName);
301 seg->sections.push_back(si);
302 }
303 // Sort segments.
304 std::sort(_segmentInfos.begin(), _segmentInfos.end(), SegmentSorter());
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000305
Nick Kledzike34182f2013-11-06 21:36:55 +0000306 // Sort sections within segments.
307 for (SegmentInfo *seg : _segmentInfos) {
308 if (seg->name.equals("__TEXT")) {
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000309 std::sort(seg->sections.begin(), seg->sections.end(),
Nick Kledzike34182f2013-11-06 21:36:55 +0000310 TextSectionSorter());
311 }
312 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000313
Nick Kledzike34182f2013-11-06 21:36:55 +0000314 // Record final section indexes.
315 uint32_t sectionIndex = 1;
316 for (SegmentInfo *seg : _segmentInfos) {
317 for (SectionInfo *sect : seg->sections) {
318 sect->finalSectionIndex = sectionIndex++;
319 }
320 }
321 }
322
323}
324
325uint64_t Util::alignTo(uint64_t value, uint8_t align2) {
326 return llvm::RoundUpToAlignment(value, 1 << align2);
327}
328
329
330void Util::layoutSectionsInSegment(SegmentInfo *seg, uint64_t &addr) {
331 seg->address = addr;
332 for (SectionInfo *sect : seg->sections) {
333 sect->address = alignTo(addr, sect->alignment);
334 addr += sect->size;
335 }
336 seg->size = llvm::RoundUpToAlignment(addr - seg->address,_context.pageSize());
337}
338
339
340// __TEXT segment lays out backwards so padding is at front after load commands.
341void Util::layoutSectionsInTextSegment(SegmentInfo *seg, uint64_t &addr) {
342 seg->address = addr;
343 // Walks sections starting at end to calculate padding for start.
344 int64_t taddr = 0;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000345 for (auto it = seg->sections.rbegin(); it != seg->sections.rend(); ++it) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000346 SectionInfo *sect = *it;
347 taddr -= sect->size;
348 taddr = taddr & (0 - (1 << sect->alignment));
349 }
350 int64_t padding = taddr;
351 while (padding < 0)
352 padding += _context.pageSize();
353 // Start assigning section address starting at padded offset.
354 addr += padding;
355 for (SectionInfo *sect : seg->sections) {
356 sect->address = alignTo(addr, sect->alignment);
357 addr = sect->address + sect->size;
358 }
359 seg->size = llvm::RoundUpToAlignment(addr - seg->address,_context.pageSize());
360}
361
362
363void Util::assignAddressesToSections() {
364 uint64_t address = 0; // FIXME
365 if (_context.outputFileType() != llvm::MachO::MH_OBJECT) {
366 for (SegmentInfo *seg : _segmentInfos) {
367 if (seg->name.equals("__PAGEZERO")) {
368 seg->size = _context.pageZeroSize();
369 address += seg->size;
370 }
371 else if (seg->name.equals("__TEXT"))
372 layoutSectionsInTextSegment(seg, address);
373 else
374 layoutSectionsInSegment(seg, address);
375 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000376 DEBUG_WITH_TYPE("WriterMachO-norm",
Nick Kledzik020a49c2013-11-06 21:57:52 +0000377 llvm::dbgs() << "assignAddressesToSections()\n";
378 for (SegmentInfo *sgi : _segmentInfos) {
379 llvm::dbgs() << " address=" << llvm::format("0x%08llX", sgi->address)
Nick Kledzike34182f2013-11-06 21:36:55 +0000380 << ", size=" << llvm::format("0x%08llX", sgi->size)
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000381 << ", segment-name='" << sgi->name
Nick Kledzik020a49c2013-11-06 21:57:52 +0000382 << "'\n";
383 for (SectionInfo *si : sgi->sections) {
384 llvm::dbgs()<< " addr=" << llvm::format("0x%08llX", si->address)
Nick Kledzike34182f2013-11-06 21:36:55 +0000385 << ", size=" << llvm::format("0x%08llX", si->size)
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000386 << ", section-name='" << si->sectionName
Nick Kledzik020a49c2013-11-06 21:57:52 +0000387 << "\n";
388 }
Nick Kledzike34182f2013-11-06 21:36:55 +0000389 }
Nick Kledzik020a49c2013-11-06 21:57:52 +0000390 );
Nick Kledzike34182f2013-11-06 21:36:55 +0000391 } else {
392 for (SectionInfo *sect : _sectionInfos) {
393 sect->address = alignTo(address, sect->alignment);
394 address = sect->address + sect->size;
395 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000396 DEBUG_WITH_TYPE("WriterMachO-norm",
Nick Kledzik020a49c2013-11-06 21:57:52 +0000397 llvm::dbgs() << "assignAddressesToSections()\n";
398 for (SectionInfo *si : _sectionInfos) {
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000399 llvm::dbgs() << " section=" << si->sectionName
Nick Kledzike34182f2013-11-06 21:36:55 +0000400 << " address= " << llvm::format("0x%08X", si->address)
401 << " size= " << llvm::format("0x%08X", si->size)
Nick Kledzik020a49c2013-11-06 21:57:52 +0000402 << "\n";
403 }
404 );
Nick Kledzike34182f2013-11-06 21:36:55 +0000405 }
Nick Kledzike34182f2013-11-06 21:36:55 +0000406}
407
408
409void Util::copySegmentInfo(NormalizedFile &file) {
410 for (SegmentInfo *sgi : _segmentInfos) {
411 Segment seg;
412 seg.name = sgi->name;
413 seg.address = sgi->address;
414 seg.size = sgi->size;
415 seg.access = sgi->access;
416 file.segments.push_back(seg);
417 }
418}
419
420void Util::appendSection(SectionInfo *si, NormalizedFile &file) {
421 // Add new empty section to end of file.sections.
422 Section temp;
423 file.sections.push_back(std::move(temp));
424 Section* normSect = &file.sections.back();
425 // Copy fields to normalized section.
426 normSect->segmentName = si->segmentName;
427 normSect->sectionName = si->sectionName;
428 normSect->type = si->type;
429 normSect->attributes = si->attributes;
430 normSect->address = si->address;
431 normSect->alignment = si->alignment;
432 // Record where normalized section is.
433 si->normalizedSectionIndex = file.sections.size()-1;
434 // Copy content from atoms to content buffer for section.
Nick Kledzik61fdef62014-05-15 20:59:23 +0000435 if (si->type == llvm::MachO::S_ZEROFILL)
436 return;
Nick Kledzik6edd7222014-01-11 01:07:43 +0000437 uint8_t *sectionContent = file.ownedAllocations.Allocate<uint8_t>(si->size);
438 normSect->content = llvm::makeArrayRef(sectionContent, si->size);
Nick Kledzike34182f2013-11-06 21:36:55 +0000439 for (AtomInfo &ai : si->atomsAndOffsets) {
440 // Copy raw bytes.
441 uint8_t *atomContent = reinterpret_cast<uint8_t*>
442 (&sectionContent[ai.offsetInSection]);
443 memcpy(atomContent, ai.atom->rawContent().data(), ai.atom->size());
444 // Apply fix-ups.
445 for (const Reference *ref : *ai.atom) {
446 uint32_t offset = ref->offsetInAtom();
447 uint64_t targetAddress = 0;
448 if ( ref->target() != nullptr )
449 targetAddress = _atomToAddress[ref->target()];
450 uint64_t fixupAddress = _atomToAddress[ai.atom] + offset;
Rui Ueyama170a1a82013-12-20 07:48:29 +0000451 _context.kindHandler().applyFixup(
452 ref->kindNamespace(), ref->kindArch(), ref->kindValue(),
453 ref->addend(), &atomContent[offset], fixupAddress, targetAddress);
Nick Kledzike34182f2013-11-06 21:36:55 +0000454 }
455 }
456}
457
458void Util::copySections(NormalizedFile &file) {
459 file.sections.reserve(_sectionInfos.size());
460 // For final linked images, write sections grouped by segment.
461 if (_context.outputFileType() != llvm::MachO::MH_OBJECT) {
462 for (SegmentInfo *sgi : _segmentInfos) {
463 for (SectionInfo *si : sgi->sections) {
464 appendSection(si, file);
465 }
466 }
467 } else {
468 // Object files write sections in default order.
469 for (SectionInfo *si : _sectionInfos) {
470 appendSection(si, file);
471 }
472 }
473}
474
475void Util::copyEntryPointAddress(NormalizedFile &nFile) {
476 if (_context.outputTypeHasEntry()) {
477 nFile.entryAddress = _atomToAddress[_entryAtom];
478 }
479}
480
481void Util::buildAtomToAddressMap() {
482 DEBUG_WITH_TYPE("WriterMachO-address", llvm::dbgs()
483 << "assign atom addresses:\n");
484 const bool lookForEntry = _context.outputTypeHasEntry();
485 for (SectionInfo *sect : _sectionInfos) {
486 for (const AtomInfo &info : sect->atomsAndOffsets) {
487 _atomToAddress[info.atom] = sect->address + info.offsetInSection;
488 if (lookForEntry && (info.atom->contentType() == DefinedAtom::typeCode) &&
489 (info.atom->size() != 0) &&
490 info.atom->name() == _context.entrySymbolName()) {
491 _entryAtom = info.atom;
492 }
493 DEBUG_WITH_TYPE("WriterMachO-address", llvm::dbgs()
494 << " address="
495 << llvm::format("0x%016X", _atomToAddress[info.atom])
496 << " atom=" << info.atom
497 << " name=" << info.atom->name() << "\n");
498 }
499 }
500}
501
502uint8_t Util::scopeBits(const DefinedAtom* atom) {
503 switch (atom->scope()) {
504 case Atom::scopeTranslationUnit:
505 return 0;
506 case Atom::scopeLinkageUnit:
507 return N_PEXT | N_EXT;
508 case Atom::scopeGlobal:
509 return N_EXT;
510 }
Nick Kledzik020fa7f2013-11-06 22:18:09 +0000511 llvm_unreachable("Unknown scope");
Nick Kledzike34182f2013-11-06 21:36:55 +0000512}
513
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000514bool Util::AtomSorter::operator()(const AtomAndIndex &left,
Nick Kledzike34182f2013-11-06 21:36:55 +0000515 const AtomAndIndex &right) {
516 return (left.atom->name().compare(right.atom->name()) < 0);
517}
518
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000519
Nick Kledzike34182f2013-11-06 21:36:55 +0000520bool Util::belongsInGlobalSymbolsSection(const DefinedAtom* atom) {
521 return (atom->scope() == Atom::scopeGlobal);
522}
523
524void Util::addSymbols(const lld::File &atomFile, NormalizedFile &file) {
525 // Mach-O symbol table has three regions: locals, globals, undefs.
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000526
Nick Kledzike34182f2013-11-06 21:36:55 +0000527 // Add all local (non-global) symbols in address order
528 std::vector<AtomAndIndex> globals;
529 globals.reserve(512);
530 for (SectionInfo *sect : _sectionInfos) {
531 for (const AtomInfo &info : sect->atomsAndOffsets) {
532 const DefinedAtom *atom = info.atom;
533 if (!atom->name().empty()) {
534 if (belongsInGlobalSymbolsSection(atom)) {
535 AtomAndIndex ai = { atom, sect->finalSectionIndex };
536 globals.push_back(ai);
537 } else {
538 Symbol sym;
539 sym.name = atom->name();
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000540 sym.type = N_SECT;
Nick Kledzike34182f2013-11-06 21:36:55 +0000541 sym.scope = scopeBits(atom);
542 sym.sect = sect->finalSectionIndex;
543 sym.desc = 0;
544 sym.value = _atomToAddress[atom];
545 file.localSymbols.push_back(sym);
546 }
547 }
548 }
549 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000550
Nick Kledzike34182f2013-11-06 21:36:55 +0000551 // Sort global symbol alphabetically, then add to symbol table.
552 std::sort(globals.begin(), globals.end(), AtomSorter());
553 for (AtomAndIndex &ai : globals) {
554 Symbol sym;
555 sym.name = ai.atom->name();
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000556 sym.type = N_SECT;
Nick Kledzike34182f2013-11-06 21:36:55 +0000557 sym.scope = scopeBits(static_cast<const DefinedAtom*>(ai.atom));
558 sym.sect = ai.index;
559 sym.desc = 0;
560 sym.value = _atomToAddress[ai.atom];
561 file.globalSymbols.push_back(sym);
562 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000563
564
Nick Kledzike34182f2013-11-06 21:36:55 +0000565 // Sort undefined symbol alphabetically, then add to symbol table.
566 std::vector<AtomAndIndex> undefs;
567 undefs.reserve(128);
568 for (const UndefinedAtom *atom : atomFile.undefined()) {
569 AtomAndIndex ai = { atom, 0 };
570 undefs.push_back(ai);
571 }
572 for (const SharedLibraryAtom *atom : atomFile.sharedLibrary()) {
573 AtomAndIndex ai = { atom, 0 };
574 undefs.push_back(ai);
575 }
576 std::sort(undefs.begin(), undefs.end(), AtomSorter());
577 const uint32_t start = file.globalSymbols.size() + file.localSymbols.size();
578 for (AtomAndIndex &ai : undefs) {
579 Symbol sym;
580 sym.name = ai.atom->name();
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000581 sym.type = N_UNDF;
Nick Kledzike34182f2013-11-06 21:36:55 +0000582 sym.scope = N_EXT;
583 sym.sect = 0;
584 sym.desc = 0;
585 sym.value = 0;
586 _atomToSymbolIndex[ai.atom] = file.undefinedSymbols.size() + start;
587 file.undefinedSymbols.push_back(sym);
588 }
589}
590
591const Atom *Util::targetOfLazyPointer(const DefinedAtom *lpAtom) {
592 for (const Reference *ref : *lpAtom) {
Nick Kledzike5552772013-12-19 21:58:00 +0000593 if (_context.kindHandler().isLazyTarget(*ref)) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000594 return ref->target();
595 }
596 }
597 return nullptr;
598}
599
600const Atom *Util::targetOfStub(const DefinedAtom *stubAtom) {
601 for (const Reference *ref : *stubAtom) {
602 if (const Atom *ta = ref->target()) {
603 if (const DefinedAtom *lpAtom = dyn_cast<DefinedAtom>(ta)) {
604 const Atom *target = targetOfLazyPointer(lpAtom);
605 if (target)
606 return target;
607 }
608 }
609 }
610 return nullptr;
611}
612
613
614void Util::addIndirectSymbols(const lld::File &atomFile, NormalizedFile &file) {
615 for (SectionInfo *si : _sectionInfos) {
616 Section &normSect = file.sections[si->normalizedSectionIndex];
617 switch (si->type) {
618 case llvm::MachO::S_NON_LAZY_SYMBOL_POINTERS:
619 for (const AtomInfo &info : si->atomsAndOffsets) {
620 bool foundTarget = false;
621 for (const Reference *ref : *info.atom) {
622 const Atom *target = ref->target();
623 if (target) {
624 if (isa<const SharedLibraryAtom>(target)) {
625 uint32_t index = _atomToSymbolIndex[target];
626 normSect.indirectSymbols.push_back(index);
627 foundTarget = true;
628 } else {
629 normSect.indirectSymbols.push_back(
630 llvm::MachO::INDIRECT_SYMBOL_LOCAL);
631 }
632 }
633 }
634 if (!foundTarget) {
635 normSect.indirectSymbols.push_back(
636 llvm::MachO::INDIRECT_SYMBOL_ABS);
637 }
638 }
639 break;
640 case llvm::MachO::S_LAZY_SYMBOL_POINTERS:
641 for (const AtomInfo &info : si->atomsAndOffsets) {
642 const Atom *target = targetOfLazyPointer(info.atom);
643 if (target) {
644 uint32_t index = _atomToSymbolIndex[target];
645 normSect.indirectSymbols.push_back(index);
646 }
647 }
648 break;
649 case llvm::MachO::S_SYMBOL_STUBS:
650 for (const AtomInfo &info : si->atomsAndOffsets) {
651 const Atom *target = targetOfStub(info.atom);
652 if (target) {
653 uint32_t index = _atomToSymbolIndex[target];
654 normSect.indirectSymbols.push_back(index);
655 }
656 }
657 break;
658 default:
659 break;
660 }
661 }
662
663}
664
665void Util::addDependentDylibs(const lld::File &atomFile,NormalizedFile &nFile) {
666 // Scan all imported symbols and build up list of dylibs they are from.
667 int ordinal = 1;
668 for (const SharedLibraryAtom *slAtom : atomFile.sharedLibrary()) {
669 StringRef loadPath = slAtom->loadName();
670 DylibPathToInfo::iterator pos = _dylibInfo.find(loadPath);
671 if (pos == _dylibInfo.end()) {
672 DylibInfo info;
673 info.ordinal = ordinal++;
674 info.hasWeak = slAtom->canBeNullAtRuntime();
675 info.hasNonWeak = !info.hasWeak;
676 _dylibInfo[loadPath] = info;
677 DependentDylib depInfo;
678 depInfo.path = loadPath;
679 depInfo.kind = llvm::MachO::LC_LOAD_DYLIB;
680 nFile.dependentDylibs.push_back(depInfo);
681 } else {
682 if ( slAtom->canBeNullAtRuntime() )
683 pos->second.hasWeak = true;
684 else
685 pos->second.hasNonWeak = true;
686 }
687 }
688 // Automatically weak link dylib in which all symbols are weak (canBeNull).
689 for (DependentDylib &dep : nFile.dependentDylibs) {
690 DylibInfo &info = _dylibInfo[dep.path];
691 if (info.hasWeak && !info.hasNonWeak)
692 dep.kind = llvm::MachO::LC_LOAD_WEAK_DYLIB;
693 }
694}
695
696
697int Util::dylibOrdinal(const SharedLibraryAtom *sa) {
698 return _dylibInfo[sa->loadName()].ordinal;
699}
700
701void Util::segIndexForSection(const SectionInfo *sect, uint8_t &segmentIndex,
702 uint64_t &segmentStartAddr) {
703 segmentIndex = 0;
704 for (const SegmentInfo *seg : _segmentInfos) {
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000705 if ((seg->address <= sect->address)
Nick Kledzike34182f2013-11-06 21:36:55 +0000706 && (seg->address+seg->size >= sect->address+sect->size)) {
707 segmentStartAddr = seg->address;
708 return;
709 }
710 ++segmentIndex;
711 }
712 llvm_unreachable("section not in any segment");
713}
714
715
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000716void Util::appendReloc(const DefinedAtom *atom, const Reference *ref,
Nick Kledzike34182f2013-11-06 21:36:55 +0000717 Relocations &relocations) {
718 // TODO: convert Reference to normalized relocation
719}
720
721void Util::addSectionRelocs(const lld::File &, NormalizedFile &file) {
722 if (_context.outputFileType() != llvm::MachO::MH_OBJECT)
723 return;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000724
Nick Kledzike34182f2013-11-06 21:36:55 +0000725 for (SectionInfo *si : _sectionInfos) {
726 Section &normSect = file.sections[si->normalizedSectionIndex];
727 for (const AtomInfo &info : si->atomsAndOffsets) {
728 const DefinedAtom *atom = info.atom;
729 for (const Reference *ref : *atom) {
730 appendReloc(atom, ref, normSect.relocations);
731 }
732 }
733 }
734}
735
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000736void Util::addRebaseAndBindingInfo(const lld::File &atomFile,
Nick Kledzike34182f2013-11-06 21:36:55 +0000737 NormalizedFile &nFile) {
738 if (_context.outputFileType() == llvm::MachO::MH_OBJECT)
739 return;
740
741 uint8_t segmentIndex;
742 uint64_t segmentStartAddr;
743 for (SectionInfo *sect : _sectionInfos) {
744 segIndexForSection(sect, segmentIndex, segmentStartAddr);
745 for (const AtomInfo &info : sect->atomsAndOffsets) {
746 const DefinedAtom *atom = info.atom;
747 for (const Reference *ref : *atom) {
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000748 uint64_t segmentOffset = _atomToAddress[atom] + ref->offsetInAtom()
Nick Kledzike34182f2013-11-06 21:36:55 +0000749 - segmentStartAddr;
750 const Atom* targ = ref->target();
Nick Kledzike5552772013-12-19 21:58:00 +0000751 if (_context.kindHandler().isPointer(*ref)) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000752 // A pointer to a DefinedAtom requires rebasing.
753 if (dyn_cast<DefinedAtom>(targ)) {
754 RebaseLocation rebase;
755 rebase.segIndex = segmentIndex;
756 rebase.segOffset = segmentOffset;
757 rebase.kind = llvm::MachO::REBASE_TYPE_POINTER;
758 nFile.rebasingInfo.push_back(rebase);
759 }
760 // A pointer to an SharedLibraryAtom requires binding.
761 if (const SharedLibraryAtom *sa = dyn_cast<SharedLibraryAtom>(targ)) {
762 BindLocation bind;
763 bind.segIndex = segmentIndex;
764 bind.segOffset = segmentOffset;
765 bind.kind = llvm::MachO::BIND_TYPE_POINTER;
766 bind.canBeNull = sa->canBeNullAtRuntime();
767 bind.ordinal = dylibOrdinal(sa);
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000768 bind.symbolName = targ->name();
Nick Kledzike34182f2013-11-06 21:36:55 +0000769 bind.addend = ref->addend();
770 nFile.bindingInfo.push_back(bind);
771 }
772 }
Nick Kledzike5552772013-12-19 21:58:00 +0000773 if (_context.kindHandler().isLazyTarget(*ref)) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000774 BindLocation bind;
775 bind.segIndex = segmentIndex;
776 bind.segOffset = segmentOffset;
777 bind.kind = llvm::MachO::BIND_TYPE_POINTER;
778 bind.canBeNull = false; //sa->canBeNullAtRuntime();
779 bind.ordinal = 1;
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.lazyBindingInfo.push_back(bind);
783 }
784 }
785 }
786 }
787}
788
789uint32_t Util::fileFlags() {
790 return 0; //FIX ME
791}
792
793} // end anonymous namespace
794
795
796namespace lld {
797namespace mach_o {
798namespace normalized {
799
800/// Convert a set of Atoms into a normalized mach-o file.
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000801ErrorOr<std::unique_ptr<NormalizedFile>>
802normalizedFromAtoms(const lld::File &atomFile,
Nick Kledzike34182f2013-11-06 21:36:55 +0000803 const MachOLinkingContext &context) {
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000804 // The util object buffers info until the normalized file can be made.
Nick Kledzike34182f2013-11-06 21:36:55 +0000805 Util util(context);
806 util.assignAtomsToSections(atomFile);
807 util.organizeSections();
808 util.assignAddressesToSections();
809 util.buildAtomToAddressMap();
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000810
Nick Kledzike34182f2013-11-06 21:36:55 +0000811 std::unique_ptr<NormalizedFile> f(new NormalizedFile());
812 NormalizedFile &normFile = *f.get();
813 f->arch = context.arch();
814 f->fileType = context.outputFileType();
815 f->flags = util.fileFlags();
816 util.copySegmentInfo(normFile);
817 util.copySections(normFile);
818 util.addDependentDylibs(atomFile, normFile);
819 util.addSymbols(atomFile, normFile);
820 util.addIndirectSymbols(atomFile, normFile);
821 util.addRebaseAndBindingInfo(atomFile, normFile);
822 util.addSectionRelocs(atomFile, normFile);
823 util.copyEntryPointAddress(normFile);
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000824
Nick Kledzike34182f2013-11-06 21:36:55 +0000825 return std::move(f);
826}
827
828
829} // namespace normalized
830} // namespace mach_o
831} // namespace lld
832