blob: 00aabc2266323fedb8b8473c52ac3f58a08bffab [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 Kledzikb367c252014-05-29 23:07:20 +0000203 case DefinedAtom::typeCFI:
204 return new (_allocator) SectionInfo("__TEXT", "__eh_frame",
205 S_COALESCED);
Nick Kledzike34182f2013-11-06 21:36:55 +0000206 default:
207 llvm_unreachable("TO DO: add support for more sections");
208 break;
209 }
210}
211
212
213
214SectionInfo *Util::sectionForAtom(const DefinedAtom *atom) {
215 DefinedAtom::ContentType type = atom->contentType();
216 auto pos = _sectionMap.find(type);
217 if ( pos != _sectionMap.end() )
218 return pos->second;
219 SectionInfo *si = makeSection(type);
220 _sectionInfos.push_back(si);
221 _sectionMap[type] = si;
222 return si;
223}
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000224
Nick Kledzike34182f2013-11-06 21:36:55 +0000225
226void Util::appendAtom(SectionInfo *sect, const DefinedAtom *atom) {
227 // Figure out offset for atom in this section given alignment constraints.
228 uint64_t offset = sect->size;
229 DefinedAtom::Alignment atomAlign = atom->alignment();
230 uint64_t align2 = 1 << atomAlign.powerOf2;
231 uint64_t requiredModulus = atomAlign.modulus;
232 uint64_t currentModulus = (offset % align2);
233 if ( currentModulus != requiredModulus ) {
234 if ( requiredModulus > currentModulus )
235 offset += requiredModulus-currentModulus;
236 else
237 offset += align2+requiredModulus-currentModulus;
238 }
239 // Record max alignment of any atom in this section.
240 if ( atomAlign.powerOf2 > sect->alignment )
241 sect->alignment = atomAlign.powerOf2;
242 // Assign atom to this section with this offset.
243 AtomInfo ai = {atom, offset};
244 sect->atomsAndOffsets.push_back(ai);
245 // Update section size to include this atom.
246 sect->size = offset + atom->size();
247}
248
249void Util::assignAtomsToSections(const lld::File &atomFile) {
250 for (const DefinedAtom *atom : atomFile.defined()) {
251 appendAtom(sectionForAtom(atom), atom);
252 }
253}
254
255SegmentInfo *Util::segmentForName(StringRef segName) {
256 for (SegmentInfo *si : _segmentInfos) {
257 if ( si->name.equals(segName) )
258 return si;
259 }
260 SegmentInfo *info = new (_allocator) SegmentInfo(segName);
261 if (segName.equals("__TEXT"))
262 info->access = VM_PROT_READ | VM_PROT_EXECUTE;
263 else if (segName.equals("__DATA"))
264 info->access = VM_PROT_READ | VM_PROT_WRITE;
265 else if (segName.equals("__PAGEZERO"))
266 info->access = 0;
267 _segmentInfos.push_back(info);
268 return info;
269}
270
271unsigned Util::SegmentSorter::weight(const SegmentInfo *seg) {
272 return llvm::StringSwitch<unsigned>(seg->name)
273 .Case("__PAGEZERO", 1)
274 .Case("__TEXT", 2)
275 .Case("__DATA", 3)
276 .Default(100);
277}
278
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000279bool Util::SegmentSorter::operator()(const SegmentInfo *left,
Nick Kledzike34182f2013-11-06 21:36:55 +0000280 const SegmentInfo *right) {
281 return (weight(left) < weight(right));
282}
283
284unsigned Util::TextSectionSorter::weight(const SectionInfo *sect) {
285 return llvm::StringSwitch<unsigned>(sect->sectionName)
286 .Case("__text", 1)
287 .Case("__stubs", 2)
288 .Case("__stub_helper", 3)
289 .Case("__const", 4)
290 .Case("__cstring", 5)
291 .Case("__unwind_info", 98)
292 .Case("__eh_frame", 99)
293 .Default(10);
294}
295
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000296bool Util::TextSectionSorter::operator()(const SectionInfo *left,
Nick Kledzike34182f2013-11-06 21:36:55 +0000297 const SectionInfo *right) {
298 return (weight(left) < weight(right));
299}
300
301
302void Util::organizeSections() {
303 if (_context.outputFileType() == llvm::MachO::MH_OBJECT) {
304 // Leave sections ordered as normalized file specified.
305 uint32_t sectionIndex = 1;
306 for (SectionInfo *si : _sectionInfos) {
307 si->finalSectionIndex = sectionIndex++;
308 }
309 } else {
310 // Main executables, need a zero-page segment
311 if (_context.outputFileType() == llvm::MachO::MH_EXECUTE)
312 segmentForName("__PAGEZERO");
313 // Group sections into segments.
314 for (SectionInfo *si : _sectionInfos) {
315 SegmentInfo *seg = segmentForName(si->segmentName);
316 seg->sections.push_back(si);
317 }
318 // Sort segments.
319 std::sort(_segmentInfos.begin(), _segmentInfos.end(), SegmentSorter());
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000320
Nick Kledzike34182f2013-11-06 21:36:55 +0000321 // Sort sections within segments.
322 for (SegmentInfo *seg : _segmentInfos) {
323 if (seg->name.equals("__TEXT")) {
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000324 std::sort(seg->sections.begin(), seg->sections.end(),
Nick Kledzike34182f2013-11-06 21:36:55 +0000325 TextSectionSorter());
326 }
327 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000328
Nick Kledzike34182f2013-11-06 21:36:55 +0000329 // Record final section indexes.
330 uint32_t sectionIndex = 1;
331 for (SegmentInfo *seg : _segmentInfos) {
332 for (SectionInfo *sect : seg->sections) {
333 sect->finalSectionIndex = sectionIndex++;
334 }
335 }
336 }
337
338}
339
340uint64_t Util::alignTo(uint64_t value, uint8_t align2) {
341 return llvm::RoundUpToAlignment(value, 1 << align2);
342}
343
344
345void Util::layoutSectionsInSegment(SegmentInfo *seg, uint64_t &addr) {
346 seg->address = addr;
347 for (SectionInfo *sect : seg->sections) {
348 sect->address = alignTo(addr, sect->alignment);
349 addr += sect->size;
350 }
351 seg->size = llvm::RoundUpToAlignment(addr - seg->address,_context.pageSize());
352}
353
354
355// __TEXT segment lays out backwards so padding is at front after load commands.
356void Util::layoutSectionsInTextSegment(SegmentInfo *seg, uint64_t &addr) {
357 seg->address = addr;
358 // Walks sections starting at end to calculate padding for start.
359 int64_t taddr = 0;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000360 for (auto it = seg->sections.rbegin(); it != seg->sections.rend(); ++it) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000361 SectionInfo *sect = *it;
362 taddr -= sect->size;
363 taddr = taddr & (0 - (1 << sect->alignment));
364 }
365 int64_t padding = taddr;
366 while (padding < 0)
367 padding += _context.pageSize();
368 // Start assigning section address starting at padded offset.
369 addr += padding;
370 for (SectionInfo *sect : seg->sections) {
371 sect->address = alignTo(addr, sect->alignment);
372 addr = sect->address + sect->size;
373 }
374 seg->size = llvm::RoundUpToAlignment(addr - seg->address,_context.pageSize());
375}
376
377
378void Util::assignAddressesToSections() {
379 uint64_t address = 0; // FIXME
380 if (_context.outputFileType() != llvm::MachO::MH_OBJECT) {
381 for (SegmentInfo *seg : _segmentInfos) {
382 if (seg->name.equals("__PAGEZERO")) {
383 seg->size = _context.pageZeroSize();
384 address += seg->size;
385 }
386 else if (seg->name.equals("__TEXT"))
387 layoutSectionsInTextSegment(seg, address);
388 else
389 layoutSectionsInSegment(seg, address);
390 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000391 DEBUG_WITH_TYPE("WriterMachO-norm",
Nick Kledzik020a49c2013-11-06 21:57:52 +0000392 llvm::dbgs() << "assignAddressesToSections()\n";
393 for (SegmentInfo *sgi : _segmentInfos) {
394 llvm::dbgs() << " address=" << llvm::format("0x%08llX", sgi->address)
Nick Kledzike34182f2013-11-06 21:36:55 +0000395 << ", size=" << llvm::format("0x%08llX", sgi->size)
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000396 << ", segment-name='" << sgi->name
Nick Kledzik020a49c2013-11-06 21:57:52 +0000397 << "'\n";
398 for (SectionInfo *si : sgi->sections) {
399 llvm::dbgs()<< " addr=" << llvm::format("0x%08llX", si->address)
Nick Kledzike34182f2013-11-06 21:36:55 +0000400 << ", size=" << llvm::format("0x%08llX", si->size)
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000401 << ", section-name='" << si->sectionName
Nick Kledzik020a49c2013-11-06 21:57:52 +0000402 << "\n";
403 }
Nick Kledzike34182f2013-11-06 21:36:55 +0000404 }
Nick Kledzik020a49c2013-11-06 21:57:52 +0000405 );
Nick Kledzike34182f2013-11-06 21:36:55 +0000406 } else {
407 for (SectionInfo *sect : _sectionInfos) {
408 sect->address = alignTo(address, sect->alignment);
409 address = sect->address + sect->size;
410 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000411 DEBUG_WITH_TYPE("WriterMachO-norm",
Nick Kledzik020a49c2013-11-06 21:57:52 +0000412 llvm::dbgs() << "assignAddressesToSections()\n";
413 for (SectionInfo *si : _sectionInfos) {
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000414 llvm::dbgs() << " section=" << si->sectionName
Nick Kledzike34182f2013-11-06 21:36:55 +0000415 << " address= " << llvm::format("0x%08X", si->address)
416 << " size= " << llvm::format("0x%08X", si->size)
Nick Kledzik020a49c2013-11-06 21:57:52 +0000417 << "\n";
418 }
419 );
Nick Kledzike34182f2013-11-06 21:36:55 +0000420 }
Nick Kledzike34182f2013-11-06 21:36:55 +0000421}
422
423
424void Util::copySegmentInfo(NormalizedFile &file) {
425 for (SegmentInfo *sgi : _segmentInfos) {
426 Segment seg;
427 seg.name = sgi->name;
428 seg.address = sgi->address;
429 seg.size = sgi->size;
430 seg.access = sgi->access;
431 file.segments.push_back(seg);
432 }
433}
434
435void Util::appendSection(SectionInfo *si, NormalizedFile &file) {
436 // Add new empty section to end of file.sections.
437 Section temp;
438 file.sections.push_back(std::move(temp));
439 Section* normSect = &file.sections.back();
440 // Copy fields to normalized section.
441 normSect->segmentName = si->segmentName;
442 normSect->sectionName = si->sectionName;
443 normSect->type = si->type;
444 normSect->attributes = si->attributes;
445 normSect->address = si->address;
446 normSect->alignment = si->alignment;
447 // Record where normalized section is.
448 si->normalizedSectionIndex = file.sections.size()-1;
449 // Copy content from atoms to content buffer for section.
Nick Kledzik61fdef62014-05-15 20:59:23 +0000450 if (si->type == llvm::MachO::S_ZEROFILL)
451 return;
Nick Kledzik6edd7222014-01-11 01:07:43 +0000452 uint8_t *sectionContent = file.ownedAllocations.Allocate<uint8_t>(si->size);
453 normSect->content = llvm::makeArrayRef(sectionContent, si->size);
Nick Kledzike34182f2013-11-06 21:36:55 +0000454 for (AtomInfo &ai : si->atomsAndOffsets) {
455 // Copy raw bytes.
456 uint8_t *atomContent = reinterpret_cast<uint8_t*>
457 (&sectionContent[ai.offsetInSection]);
458 memcpy(atomContent, ai.atom->rawContent().data(), ai.atom->size());
459 // Apply fix-ups.
460 for (const Reference *ref : *ai.atom) {
461 uint32_t offset = ref->offsetInAtom();
462 uint64_t targetAddress = 0;
463 if ( ref->target() != nullptr )
464 targetAddress = _atomToAddress[ref->target()];
465 uint64_t fixupAddress = _atomToAddress[ai.atom] + offset;
Rui Ueyama170a1a82013-12-20 07:48:29 +0000466 _context.kindHandler().applyFixup(
467 ref->kindNamespace(), ref->kindArch(), ref->kindValue(),
468 ref->addend(), &atomContent[offset], fixupAddress, targetAddress);
Nick Kledzike34182f2013-11-06 21:36:55 +0000469 }
470 }
471}
472
473void Util::copySections(NormalizedFile &file) {
474 file.sections.reserve(_sectionInfos.size());
475 // For final linked images, write sections grouped by segment.
476 if (_context.outputFileType() != llvm::MachO::MH_OBJECT) {
477 for (SegmentInfo *sgi : _segmentInfos) {
478 for (SectionInfo *si : sgi->sections) {
479 appendSection(si, file);
480 }
481 }
482 } else {
483 // Object files write sections in default order.
484 for (SectionInfo *si : _sectionInfos) {
485 appendSection(si, file);
486 }
487 }
488}
489
490void Util::copyEntryPointAddress(NormalizedFile &nFile) {
491 if (_context.outputTypeHasEntry()) {
492 nFile.entryAddress = _atomToAddress[_entryAtom];
493 }
494}
495
496void Util::buildAtomToAddressMap() {
497 DEBUG_WITH_TYPE("WriterMachO-address", llvm::dbgs()
498 << "assign atom addresses:\n");
499 const bool lookForEntry = _context.outputTypeHasEntry();
500 for (SectionInfo *sect : _sectionInfos) {
501 for (const AtomInfo &info : sect->atomsAndOffsets) {
502 _atomToAddress[info.atom] = sect->address + info.offsetInSection;
503 if (lookForEntry && (info.atom->contentType() == DefinedAtom::typeCode) &&
504 (info.atom->size() != 0) &&
505 info.atom->name() == _context.entrySymbolName()) {
506 _entryAtom = info.atom;
507 }
508 DEBUG_WITH_TYPE("WriterMachO-address", llvm::dbgs()
509 << " address="
510 << llvm::format("0x%016X", _atomToAddress[info.atom])
511 << " atom=" << info.atom
512 << " name=" << info.atom->name() << "\n");
513 }
514 }
515}
516
517uint8_t Util::scopeBits(const DefinedAtom* atom) {
518 switch (atom->scope()) {
519 case Atom::scopeTranslationUnit:
520 return 0;
521 case Atom::scopeLinkageUnit:
522 return N_PEXT | N_EXT;
523 case Atom::scopeGlobal:
524 return N_EXT;
525 }
Nick Kledzik020fa7f2013-11-06 22:18:09 +0000526 llvm_unreachable("Unknown scope");
Nick Kledzike34182f2013-11-06 21:36:55 +0000527}
528
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000529bool Util::AtomSorter::operator()(const AtomAndIndex &left,
Nick Kledzike34182f2013-11-06 21:36:55 +0000530 const AtomAndIndex &right) {
531 return (left.atom->name().compare(right.atom->name()) < 0);
532}
533
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000534
Nick Kledzike34182f2013-11-06 21:36:55 +0000535bool Util::belongsInGlobalSymbolsSection(const DefinedAtom* atom) {
536 return (atom->scope() == Atom::scopeGlobal);
537}
538
539void Util::addSymbols(const lld::File &atomFile, NormalizedFile &file) {
540 // Mach-O symbol table has three regions: locals, globals, undefs.
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000541
Nick Kledzike34182f2013-11-06 21:36:55 +0000542 // Add all local (non-global) symbols in address order
543 std::vector<AtomAndIndex> globals;
544 globals.reserve(512);
545 for (SectionInfo *sect : _sectionInfos) {
546 for (const AtomInfo &info : sect->atomsAndOffsets) {
547 const DefinedAtom *atom = info.atom;
548 if (!atom->name().empty()) {
549 if (belongsInGlobalSymbolsSection(atom)) {
550 AtomAndIndex ai = { atom, sect->finalSectionIndex };
551 globals.push_back(ai);
552 } else {
553 Symbol sym;
554 sym.name = atom->name();
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000555 sym.type = N_SECT;
Nick Kledzike34182f2013-11-06 21:36:55 +0000556 sym.scope = scopeBits(atom);
557 sym.sect = sect->finalSectionIndex;
558 sym.desc = 0;
559 sym.value = _atomToAddress[atom];
560 file.localSymbols.push_back(sym);
561 }
562 }
563 }
564 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000565
Nick Kledzike34182f2013-11-06 21:36:55 +0000566 // Sort global symbol alphabetically, then add to symbol table.
567 std::sort(globals.begin(), globals.end(), AtomSorter());
568 for (AtomAndIndex &ai : globals) {
569 Symbol sym;
570 sym.name = ai.atom->name();
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000571 sym.type = N_SECT;
Nick Kledzike34182f2013-11-06 21:36:55 +0000572 sym.scope = scopeBits(static_cast<const DefinedAtom*>(ai.atom));
573 sym.sect = ai.index;
574 sym.desc = 0;
575 sym.value = _atomToAddress[ai.atom];
576 file.globalSymbols.push_back(sym);
577 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000578
579
Nick Kledzike34182f2013-11-06 21:36:55 +0000580 // Sort undefined symbol alphabetically, then add to symbol table.
581 std::vector<AtomAndIndex> undefs;
582 undefs.reserve(128);
583 for (const UndefinedAtom *atom : atomFile.undefined()) {
584 AtomAndIndex ai = { atom, 0 };
585 undefs.push_back(ai);
586 }
587 for (const SharedLibraryAtom *atom : atomFile.sharedLibrary()) {
588 AtomAndIndex ai = { atom, 0 };
589 undefs.push_back(ai);
590 }
591 std::sort(undefs.begin(), undefs.end(), AtomSorter());
592 const uint32_t start = file.globalSymbols.size() + file.localSymbols.size();
593 for (AtomAndIndex &ai : undefs) {
594 Symbol sym;
595 sym.name = ai.atom->name();
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000596 sym.type = N_UNDF;
Nick Kledzike34182f2013-11-06 21:36:55 +0000597 sym.scope = N_EXT;
598 sym.sect = 0;
599 sym.desc = 0;
600 sym.value = 0;
601 _atomToSymbolIndex[ai.atom] = file.undefinedSymbols.size() + start;
602 file.undefinedSymbols.push_back(sym);
603 }
604}
605
606const Atom *Util::targetOfLazyPointer(const DefinedAtom *lpAtom) {
607 for (const Reference *ref : *lpAtom) {
Nick Kledzike5552772013-12-19 21:58:00 +0000608 if (_context.kindHandler().isLazyTarget(*ref)) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000609 return ref->target();
610 }
611 }
612 return nullptr;
613}
614
615const Atom *Util::targetOfStub(const DefinedAtom *stubAtom) {
616 for (const Reference *ref : *stubAtom) {
617 if (const Atom *ta = ref->target()) {
618 if (const DefinedAtom *lpAtom = dyn_cast<DefinedAtom>(ta)) {
619 const Atom *target = targetOfLazyPointer(lpAtom);
620 if (target)
621 return target;
622 }
623 }
624 }
625 return nullptr;
626}
627
628
629void Util::addIndirectSymbols(const lld::File &atomFile, NormalizedFile &file) {
630 for (SectionInfo *si : _sectionInfos) {
631 Section &normSect = file.sections[si->normalizedSectionIndex];
632 switch (si->type) {
633 case llvm::MachO::S_NON_LAZY_SYMBOL_POINTERS:
634 for (const AtomInfo &info : si->atomsAndOffsets) {
635 bool foundTarget = false;
636 for (const Reference *ref : *info.atom) {
637 const Atom *target = ref->target();
638 if (target) {
639 if (isa<const SharedLibraryAtom>(target)) {
640 uint32_t index = _atomToSymbolIndex[target];
641 normSect.indirectSymbols.push_back(index);
642 foundTarget = true;
643 } else {
644 normSect.indirectSymbols.push_back(
645 llvm::MachO::INDIRECT_SYMBOL_LOCAL);
646 }
647 }
648 }
649 if (!foundTarget) {
650 normSect.indirectSymbols.push_back(
651 llvm::MachO::INDIRECT_SYMBOL_ABS);
652 }
653 }
654 break;
655 case llvm::MachO::S_LAZY_SYMBOL_POINTERS:
656 for (const AtomInfo &info : si->atomsAndOffsets) {
657 const Atom *target = targetOfLazyPointer(info.atom);
658 if (target) {
659 uint32_t index = _atomToSymbolIndex[target];
660 normSect.indirectSymbols.push_back(index);
661 }
662 }
663 break;
664 case llvm::MachO::S_SYMBOL_STUBS:
665 for (const AtomInfo &info : si->atomsAndOffsets) {
666 const Atom *target = targetOfStub(info.atom);
667 if (target) {
668 uint32_t index = _atomToSymbolIndex[target];
669 normSect.indirectSymbols.push_back(index);
670 }
671 }
672 break;
673 default:
674 break;
675 }
676 }
677
678}
679
680void Util::addDependentDylibs(const lld::File &atomFile,NormalizedFile &nFile) {
681 // Scan all imported symbols and build up list of dylibs they are from.
682 int ordinal = 1;
683 for (const SharedLibraryAtom *slAtom : atomFile.sharedLibrary()) {
684 StringRef loadPath = slAtom->loadName();
685 DylibPathToInfo::iterator pos = _dylibInfo.find(loadPath);
686 if (pos == _dylibInfo.end()) {
687 DylibInfo info;
688 info.ordinal = ordinal++;
689 info.hasWeak = slAtom->canBeNullAtRuntime();
690 info.hasNonWeak = !info.hasWeak;
691 _dylibInfo[loadPath] = info;
692 DependentDylib depInfo;
693 depInfo.path = loadPath;
694 depInfo.kind = llvm::MachO::LC_LOAD_DYLIB;
695 nFile.dependentDylibs.push_back(depInfo);
696 } else {
697 if ( slAtom->canBeNullAtRuntime() )
698 pos->second.hasWeak = true;
699 else
700 pos->second.hasNonWeak = true;
701 }
702 }
703 // Automatically weak link dylib in which all symbols are weak (canBeNull).
704 for (DependentDylib &dep : nFile.dependentDylibs) {
705 DylibInfo &info = _dylibInfo[dep.path];
706 if (info.hasWeak && !info.hasNonWeak)
707 dep.kind = llvm::MachO::LC_LOAD_WEAK_DYLIB;
708 }
709}
710
711
712int Util::dylibOrdinal(const SharedLibraryAtom *sa) {
713 return _dylibInfo[sa->loadName()].ordinal;
714}
715
716void Util::segIndexForSection(const SectionInfo *sect, uint8_t &segmentIndex,
717 uint64_t &segmentStartAddr) {
718 segmentIndex = 0;
719 for (const SegmentInfo *seg : _segmentInfos) {
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000720 if ((seg->address <= sect->address)
Nick Kledzike34182f2013-11-06 21:36:55 +0000721 && (seg->address+seg->size >= sect->address+sect->size)) {
722 segmentStartAddr = seg->address;
723 return;
724 }
725 ++segmentIndex;
726 }
727 llvm_unreachable("section not in any segment");
728}
729
730
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000731void Util::appendReloc(const DefinedAtom *atom, const Reference *ref,
Nick Kledzike34182f2013-11-06 21:36:55 +0000732 Relocations &relocations) {
733 // TODO: convert Reference to normalized relocation
734}
735
736void Util::addSectionRelocs(const lld::File &, NormalizedFile &file) {
737 if (_context.outputFileType() != llvm::MachO::MH_OBJECT)
738 return;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000739
Nick Kledzike34182f2013-11-06 21:36:55 +0000740 for (SectionInfo *si : _sectionInfos) {
741 Section &normSect = file.sections[si->normalizedSectionIndex];
742 for (const AtomInfo &info : si->atomsAndOffsets) {
743 const DefinedAtom *atom = info.atom;
744 for (const Reference *ref : *atom) {
745 appendReloc(atom, ref, normSect.relocations);
746 }
747 }
748 }
749}
750
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000751void Util::addRebaseAndBindingInfo(const lld::File &atomFile,
Nick Kledzike34182f2013-11-06 21:36:55 +0000752 NormalizedFile &nFile) {
753 if (_context.outputFileType() == llvm::MachO::MH_OBJECT)
754 return;
755
756 uint8_t segmentIndex;
757 uint64_t segmentStartAddr;
758 for (SectionInfo *sect : _sectionInfos) {
759 segIndexForSection(sect, segmentIndex, segmentStartAddr);
760 for (const AtomInfo &info : sect->atomsAndOffsets) {
761 const DefinedAtom *atom = info.atom;
762 for (const Reference *ref : *atom) {
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000763 uint64_t segmentOffset = _atomToAddress[atom] + ref->offsetInAtom()
Nick Kledzike34182f2013-11-06 21:36:55 +0000764 - segmentStartAddr;
765 const Atom* targ = ref->target();
Nick Kledzike5552772013-12-19 21:58:00 +0000766 if (_context.kindHandler().isPointer(*ref)) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000767 // A pointer to a DefinedAtom requires rebasing.
768 if (dyn_cast<DefinedAtom>(targ)) {
769 RebaseLocation rebase;
770 rebase.segIndex = segmentIndex;
771 rebase.segOffset = segmentOffset;
772 rebase.kind = llvm::MachO::REBASE_TYPE_POINTER;
773 nFile.rebasingInfo.push_back(rebase);
774 }
775 // A pointer to an SharedLibraryAtom requires binding.
776 if (const SharedLibraryAtom *sa = dyn_cast<SharedLibraryAtom>(targ)) {
777 BindLocation bind;
778 bind.segIndex = segmentIndex;
779 bind.segOffset = segmentOffset;
780 bind.kind = llvm::MachO::BIND_TYPE_POINTER;
781 bind.canBeNull = sa->canBeNullAtRuntime();
782 bind.ordinal = dylibOrdinal(sa);
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000783 bind.symbolName = targ->name();
Nick Kledzike34182f2013-11-06 21:36:55 +0000784 bind.addend = ref->addend();
785 nFile.bindingInfo.push_back(bind);
786 }
787 }
Nick Kledzike5552772013-12-19 21:58:00 +0000788 if (_context.kindHandler().isLazyTarget(*ref)) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000789 BindLocation bind;
790 bind.segIndex = segmentIndex;
791 bind.segOffset = segmentOffset;
792 bind.kind = llvm::MachO::BIND_TYPE_POINTER;
793 bind.canBeNull = false; //sa->canBeNullAtRuntime();
794 bind.ordinal = 1;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000795 bind.symbolName = targ->name();
Nick Kledzike34182f2013-11-06 21:36:55 +0000796 bind.addend = ref->addend();
797 nFile.lazyBindingInfo.push_back(bind);
798 }
799 }
800 }
801 }
802}
803
804uint32_t Util::fileFlags() {
805 return 0; //FIX ME
806}
807
808} // end anonymous namespace
809
810
811namespace lld {
812namespace mach_o {
813namespace normalized {
814
815/// Convert a set of Atoms into a normalized mach-o file.
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000816ErrorOr<std::unique_ptr<NormalizedFile>>
817normalizedFromAtoms(const lld::File &atomFile,
Nick Kledzike34182f2013-11-06 21:36:55 +0000818 const MachOLinkingContext &context) {
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000819 // The util object buffers info until the normalized file can be made.
Nick Kledzike34182f2013-11-06 21:36:55 +0000820 Util util(context);
821 util.assignAtomsToSections(atomFile);
822 util.organizeSections();
823 util.assignAddressesToSections();
824 util.buildAtomToAddressMap();
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000825
Nick Kledzike34182f2013-11-06 21:36:55 +0000826 std::unique_ptr<NormalizedFile> f(new NormalizedFile());
827 NormalizedFile &normFile = *f.get();
828 f->arch = context.arch();
829 f->fileType = context.outputFileType();
830 f->flags = util.fileFlags();
831 util.copySegmentInfo(normFile);
832 util.copySections(normFile);
833 util.addDependentDylibs(atomFile, normFile);
834 util.addSymbols(atomFile, normFile);
835 util.addIndirectSymbols(atomFile, normFile);
836 util.addRebaseAndBindingInfo(atomFile, normFile);
837 util.addSectionRelocs(atomFile, normFile);
838 util.copyEntryPointAddress(normFile);
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000839
Nick Kledzike34182f2013-11-06 21:36:55 +0000840 return std::move(f);
841}
842
843
844} // namespace normalized
845} // namespace mach_o
846} // namespace lld
847