1 //===- lib/ReaderWriter/MachO/MachONormalizedFileFromAtoms.cpp ------------===//
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// \file Converts from in-memory Atoms to in-memory normalized mach-o.
23 #include "ArchHandler.h"
24 #include "DebugInfo.h"
25 #include "MachONormalizedFile.h"
26 #include "MachONormalizedFileBinaryUtils.h"
27 #include "lld/Core/Error.h"
28 #include "lld/Core/LLVM.h"
29 #include "llvm/ADT/StringRef.h"
30 #include "llvm/ADT/StringSwitch.h"
31 #include "llvm/BinaryFormat/MachO.h"
32 #include "llvm/Support/Casting.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/Format.h"
37 #include <system_error>
38 #include <unordered_set>
40 using llvm::StringRef;
42 using namespace llvm::MachO;
43 using namespace lld::mach_o::normalized;
49 const DefinedAtom *atom;
50 uint64_t offsetInSection;
54 SectionInfo(StringRef seg, StringRef sect, SectionType type,
55 const MachOLinkingContext &ctxt, uint32_t attr,
56 bool relocsToDefinedCanBeImplicit);
58 StringRef segmentName;
59 StringRef sectionName;
66 /// If this is set, the any relocs in this section which point to defined
67 /// addresses can be implicitly generated. This is the case for the
68 /// __eh_frame section where references to the function can be implicit if the
69 /// function is defined.
70 bool relocsToDefinedCanBeImplicit;
73 std::vector<AtomInfo> atomsAndOffsets;
74 uint32_t normalizedSectionIndex;
75 uint32_t finalSectionIndex;
78 SectionInfo::SectionInfo(StringRef sg, StringRef sct, SectionType t,
79 const MachOLinkingContext &ctxt, uint32_t attrs,
80 bool relocsToDefinedCanBeImplicit)
81 : segmentName(sg), sectionName(sct), type(t), attributes(attrs),
82 address(0), size(0), alignment(1),
83 relocsToDefinedCanBeImplicit(relocsToDefinedCanBeImplicit),
84 normalizedSectionIndex(0), finalSectionIndex(0) {
86 if (ctxt.sectionAligned(segmentName, sectionName, align)) {
92 SegmentInfo(StringRef name);
99 std::vector<SectionInfo*> sections;
100 uint32_t normalizedSegmentIndex;
103 SegmentInfo::SegmentInfo(StringRef n)
104 : name(n), address(0), size(0), init_access(0), max_access(0),
105 normalizedSegmentIndex(0) {
110 Util(const MachOLinkingContext &ctxt)
111 : _ctx(ctxt), _archHandler(ctxt.archHandler()), _entryAtom(nullptr),
112 _hasTLVDescriptors(false), _subsectionsViaSymbols(true) {}
115 void processDefinedAtoms(const lld::File &atomFile);
116 void processAtomAttributes(const DefinedAtom *atom);
117 void assignAtomToSection(const DefinedAtom *atom);
118 void organizeSections();
119 void assignAddressesToSections(const NormalizedFile &file);
120 uint32_t fileFlags();
121 void copySegmentInfo(NormalizedFile &file);
122 void copySectionInfo(NormalizedFile &file);
123 void updateSectionInfo(NormalizedFile &file);
124 void buildAtomToAddressMap();
125 llvm::Error synthesizeDebugNotes(NormalizedFile &file);
126 llvm::Error addSymbols(const lld::File &atomFile, NormalizedFile &file);
127 void addIndirectSymbols(const lld::File &atomFile, NormalizedFile &file);
128 void addRebaseAndBindingInfo(const lld::File &, NormalizedFile &file);
129 void addExportInfo(const lld::File &, NormalizedFile &file);
130 void addSectionRelocs(const lld::File &, NormalizedFile &file);
131 void addFunctionStarts(const lld::File &, NormalizedFile &file);
132 void buildDataInCodeArray(const lld::File &, NormalizedFile &file);
133 void addDependentDylibs(const lld::File &, NormalizedFile &file);
134 void copyEntryPointAddress(NormalizedFile &file);
135 void copySectionContent(NormalizedFile &file);
137 bool allSourceFilesHaveMinVersions() const {
138 return _allSourceFilesHaveMinVersions;
141 uint32_t minVersion() const {
145 LoadCommandType minVersionCommandType() const {
146 return _minVersionCommandType;
150 typedef std::map<DefinedAtom::ContentType, SectionInfo*> TypeToSection;
151 typedef llvm::DenseMap<const Atom*, uint64_t> AtomToAddress;
153 struct DylibInfo { int ordinal; bool hasWeak; bool hasNonWeak; };
154 typedef llvm::StringMap<DylibInfo> DylibPathToInfo;
156 SectionInfo *sectionForAtom(const DefinedAtom*);
157 SectionInfo *getRelocatableSection(DefinedAtom::ContentType type);
158 SectionInfo *getFinalSection(DefinedAtom::ContentType type);
159 void appendAtom(SectionInfo *sect, const DefinedAtom *atom);
160 SegmentInfo *segmentForName(StringRef segName);
161 void layoutSectionsInSegment(SegmentInfo *seg, uint64_t &addr);
162 void layoutSectionsInTextSegment(size_t, SegmentInfo *, uint64_t &);
163 void copySectionContent(SectionInfo *si, ContentBytes &content);
164 uint16_t descBits(const DefinedAtom* atom);
165 int dylibOrdinal(const SharedLibraryAtom *sa);
166 void segIndexForSection(const SectionInfo *sect,
167 uint8_t &segmentIndex, uint64_t &segmentStartAddr);
168 const Atom *targetOfLazyPointer(const DefinedAtom *lpAtom);
169 const Atom *targetOfStub(const DefinedAtom *stubAtom);
170 llvm::Error getSymbolTableRegion(const DefinedAtom* atom,
171 bool &inGlobalsRegion,
172 SymbolScope &symbolScope);
173 void appendSection(SectionInfo *si, NormalizedFile &file);
174 uint32_t sectionIndexForAtom(const Atom *atom);
176 typedef llvm::DenseMap<const Atom*, uint32_t> AtomToIndex;
177 struct AtomAndIndex { const Atom *atom; uint32_t index; SymbolScope scope; };
179 bool operator()(const AtomAndIndex &left, const AtomAndIndex &right);
181 struct SegmentSorter {
182 bool operator()(const SegmentInfo *left, const SegmentInfo *right);
183 static unsigned weight(const SegmentInfo *);
185 struct TextSectionSorter {
186 bool operator()(const SectionInfo *left, const SectionInfo *right);
187 static unsigned weight(const SectionInfo *);
190 const MachOLinkingContext &_ctx;
191 mach_o::ArchHandler &_archHandler;
192 llvm::BumpPtrAllocator _allocator;
193 std::vector<SectionInfo*> _sectionInfos;
194 std::vector<SegmentInfo*> _segmentInfos;
195 TypeToSection _sectionMap;
196 std::vector<SectionInfo*> _customSections;
197 AtomToAddress _atomToAddress;
198 DylibPathToInfo _dylibInfo;
199 const DefinedAtom *_entryAtom;
200 AtomToIndex _atomToSymbolIndex;
201 std::vector<const Atom *> _machHeaderAliasAtoms;
202 bool _hasTLVDescriptors;
203 bool _subsectionsViaSymbols;
204 bool _allSourceFilesHaveMinVersions = true;
205 LoadCommandType _minVersionCommandType = (LoadCommandType)0;
206 uint32_t _minVersion = 0;
207 std::vector<lld::mach_o::Stab> _stabs;
211 // The SectionInfo structs are BumpPtr allocated, but atomsAndOffsets needs
213 for (SectionInfo *si : _sectionInfos) {
214 // clear() destroys vector elements, but does not deallocate.
215 // Instead use swap() to deallocate vector buffer.
216 std::vector<AtomInfo> empty;
217 si->atomsAndOffsets.swap(empty);
219 // The SegmentInfo structs are BumpPtr allocated, but sections needs
221 for (SegmentInfo *sgi : _segmentInfos) {
222 std::vector<SectionInfo*> empty2;
223 sgi->sections.swap(empty2);
227 SectionInfo *Util::getRelocatableSection(DefinedAtom::ContentType type) {
228 StringRef segmentName;
229 StringRef sectionName;
230 SectionType sectionType;
231 SectionAttr sectionAttrs;
232 bool relocsToDefinedCanBeImplicit;
234 // Use same table used by when parsing .o files.
235 relocatableSectionInfoForContentType(type, segmentName, sectionName,
236 sectionType, sectionAttrs,
237 relocsToDefinedCanBeImplicit);
238 // If we already have a SectionInfo with this name, re-use it.
239 // This can happen if two ContentType map to the same mach-o section.
240 for (auto sect : _sectionMap) {
241 if (sect.second->sectionName.equals(sectionName) &&
242 sect.second->segmentName.equals(segmentName)) {
246 // Otherwise allocate new SectionInfo object.
247 auto *sect = new (_allocator)
248 SectionInfo(segmentName, sectionName, sectionType, _ctx, sectionAttrs,
249 relocsToDefinedCanBeImplicit);
250 _sectionInfos.push_back(sect);
251 _sectionMap[type] = sect;
255 #define ENTRY(seg, sect, type, atomType) \
256 {seg, sect, type, DefinedAtom::atomType }
258 struct MachOFinalSectionFromAtomType {
259 StringRef segmentName;
260 StringRef sectionName;
261 SectionType sectionType;
262 DefinedAtom::ContentType atomType;
265 const MachOFinalSectionFromAtomType sectsToAtomType[] = {
266 ENTRY("__TEXT", "__text", S_REGULAR, typeCode),
267 ENTRY("__TEXT", "__text", S_REGULAR, typeMachHeader),
268 ENTRY("__TEXT", "__cstring", S_CSTRING_LITERALS, typeCString),
269 ENTRY("__TEXT", "__ustring", S_REGULAR, typeUTF16String),
270 ENTRY("__TEXT", "__const", S_REGULAR, typeConstant),
271 ENTRY("__TEXT", "__const", S_4BYTE_LITERALS, typeLiteral4),
272 ENTRY("__TEXT", "__const", S_8BYTE_LITERALS, typeLiteral8),
273 ENTRY("__TEXT", "__const", S_16BYTE_LITERALS, typeLiteral16),
274 ENTRY("__TEXT", "__stubs", S_SYMBOL_STUBS, typeStub),
275 ENTRY("__TEXT", "__stub_helper", S_REGULAR, typeStubHelper),
276 ENTRY("__TEXT", "__gcc_except_tab", S_REGULAR, typeLSDA),
277 ENTRY("__TEXT", "__eh_frame", S_COALESCED, typeCFI),
278 ENTRY("__TEXT", "__unwind_info", S_REGULAR, typeProcessedUnwindInfo),
279 ENTRY("__DATA", "__data", S_REGULAR, typeData),
280 ENTRY("__DATA", "__const", S_REGULAR, typeConstData),
281 ENTRY("__DATA", "__cfstring", S_REGULAR, typeCFString),
282 ENTRY("__DATA", "__la_symbol_ptr", S_LAZY_SYMBOL_POINTERS,
284 ENTRY("__DATA", "__mod_init_func", S_MOD_INIT_FUNC_POINTERS,
286 ENTRY("__DATA", "__mod_term_func", S_MOD_TERM_FUNC_POINTERS,
288 ENTRY("__DATA", "__got", S_NON_LAZY_SYMBOL_POINTERS,
290 ENTRY("__DATA", "__nl_symbol_ptr", S_NON_LAZY_SYMBOL_POINTERS,
292 ENTRY("__DATA", "__thread_vars", S_THREAD_LOCAL_VARIABLES,
294 ENTRY("__DATA", "__thread_data", S_THREAD_LOCAL_REGULAR,
296 ENTRY("__DATA", "__thread_ptrs", S_THREAD_LOCAL_VARIABLE_POINTERS,
297 typeTLVInitializerPtr),
298 ENTRY("__DATA", "__thread_bss", S_THREAD_LOCAL_ZEROFILL,
299 typeTLVInitialZeroFill),
300 ENTRY("__DATA", "__bss", S_ZEROFILL, typeZeroFill),
301 ENTRY("__DATA", "__interposing", S_INTERPOSING, typeInterposingTuples),
305 SectionInfo *Util::getFinalSection(DefinedAtom::ContentType atomType) {
306 for (auto &p : sectsToAtomType) {
307 if (p.atomType != atomType)
309 SectionAttr sectionAttrs = 0;
311 case DefinedAtom::typeMachHeader:
312 case DefinedAtom::typeCode:
313 case DefinedAtom::typeStub:
314 case DefinedAtom::typeStubHelper:
315 sectionAttrs = S_ATTR_PURE_INSTRUCTIONS | S_ATTR_SOME_INSTRUCTIONS;
317 case DefinedAtom::typeThunkTLV:
318 _hasTLVDescriptors = true;
323 // If we already have a SectionInfo with this name, re-use it.
324 // This can happen if two ContentType map to the same mach-o section.
325 for (auto sect : _sectionMap) {
326 if (sect.second->sectionName.equals(p.sectionName) &&
327 sect.second->segmentName.equals(p.segmentName)) {
331 // Otherwise allocate new SectionInfo object.
332 auto *sect = new (_allocator) SectionInfo(
333 p.segmentName, p.sectionName, p.sectionType, _ctx, sectionAttrs,
334 /* relocsToDefinedCanBeImplicit */ false);
335 _sectionInfos.push_back(sect);
336 _sectionMap[atomType] = sect;
339 llvm_unreachable("content type not yet supported");
342 SectionInfo *Util::sectionForAtom(const DefinedAtom *atom) {
343 if (atom->sectionChoice() == DefinedAtom::sectionBasedOnContent) {
344 // Section for this atom is derived from content type.
345 DefinedAtom::ContentType type = atom->contentType();
346 auto pos = _sectionMap.find(type);
347 if ( pos != _sectionMap.end() )
349 bool rMode = (_ctx.outputMachOType() == llvm::MachO::MH_OBJECT);
350 return rMode ? getRelocatableSection(type) : getFinalSection(type);
352 // This atom needs to be in a custom section.
353 StringRef customName = atom->customSectionName();
354 // Look to see if we have already allocated the needed custom section.
355 for(SectionInfo *sect : _customSections) {
356 const DefinedAtom *firstAtom = sect->atomsAndOffsets.front().atom;
357 if (firstAtom->customSectionName().equals(customName)) {
361 // Not found, so need to create a new custom section.
362 size_t seperatorIndex = customName.find('/');
363 assert(seperatorIndex != StringRef::npos);
364 StringRef segName = customName.slice(0, seperatorIndex);
365 StringRef sectName = customName.drop_front(seperatorIndex + 1);
367 new (_allocator) SectionInfo(segName, sectName, S_REGULAR, _ctx,
368 0, /* relocsToDefinedCanBeImplicit */ false);
369 _customSections.push_back(sect);
370 _sectionInfos.push_back(sect);
375 void Util::appendAtom(SectionInfo *sect, const DefinedAtom *atom) {
376 // Figure out offset for atom in this section given alignment constraints.
377 uint64_t offset = sect->size;
378 DefinedAtom::Alignment atomAlign = atom->alignment();
379 uint64_t align = atomAlign.value;
380 uint64_t requiredModulus = atomAlign.modulus;
381 uint64_t currentModulus = (offset % align);
382 if ( currentModulus != requiredModulus ) {
383 if ( requiredModulus > currentModulus )
384 offset += requiredModulus-currentModulus;
386 offset += align+requiredModulus-currentModulus;
388 // Record max alignment of any atom in this section.
389 if (align > sect->alignment)
390 sect->alignment = atomAlign.value;
391 // Assign atom to this section with this offset.
392 AtomInfo ai = {atom, offset};
393 sect->atomsAndOffsets.push_back(ai);
394 // Update section size to include this atom.
395 sect->size = offset + atom->size();
398 void Util::processDefinedAtoms(const lld::File &atomFile) {
399 for (const DefinedAtom *atom : atomFile.defined()) {
400 processAtomAttributes(atom);
401 assignAtomToSection(atom);
405 void Util::processAtomAttributes(const DefinedAtom *atom) {
406 if (auto *machoFile = dyn_cast<mach_o::MachOFile>(&atom->file())) {
407 // If the file doesn't use subsections via symbols, then make sure we don't
408 // add that flag to the final output file if we have a relocatable file.
409 if (!machoFile->subsectionsViaSymbols())
410 _subsectionsViaSymbols = false;
412 // All the source files must have min versions for us to output an object
413 // file with a min version.
414 if (auto v = machoFile->minVersion())
415 _minVersion = std::max(_minVersion, v);
417 _allSourceFilesHaveMinVersions = false;
419 // If we don't have a platform load command, but one of the source files
420 // does, then take the one from the file.
421 if (!_minVersionCommandType)
422 if (auto v = machoFile->minVersionLoadCommandKind())
423 _minVersionCommandType = v;
427 void Util::assignAtomToSection(const DefinedAtom *atom) {
428 if (atom->contentType() == DefinedAtom::typeMachHeader) {
429 _machHeaderAliasAtoms.push_back(atom);
430 // Assign atom to this section with this offset.
431 AtomInfo ai = {atom, 0};
432 sectionForAtom(atom)->atomsAndOffsets.push_back(ai);
433 } else if (atom->contentType() == DefinedAtom::typeDSOHandle)
434 _machHeaderAliasAtoms.push_back(atom);
436 appendAtom(sectionForAtom(atom), atom);
439 SegmentInfo *Util::segmentForName(StringRef segName) {
440 for (SegmentInfo *si : _segmentInfos) {
441 if ( si->name.equals(segName) )
444 auto *info = new (_allocator) SegmentInfo(segName);
446 // Set the initial segment protection.
447 if (segName.equals("__TEXT"))
448 info->init_access = VM_PROT_READ | VM_PROT_EXECUTE;
449 else if (segName.equals("__PAGEZERO"))
450 info->init_access = 0;
451 else if (segName.equals("__LINKEDIT"))
452 info->init_access = VM_PROT_READ;
454 // All others default to read-write
455 info->init_access = VM_PROT_READ | VM_PROT_WRITE;
458 // Set max segment protection
459 // Note, its overkill to use a switch statement here, but makes it so much
460 // easier to use switch coverage to catch new cases.
462 case lld::MachOLinkingContext::OS::unknown:
463 case lld::MachOLinkingContext::OS::macOSX:
464 case lld::MachOLinkingContext::OS::iOS_simulator:
465 if (segName.equals("__PAGEZERO")) {
466 info->max_access = 0;
469 // All others default to all
470 info->max_access = VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE;
472 case lld::MachOLinkingContext::OS::iOS:
473 // iPhoneOS always uses same protection for max and initial
474 info->max_access = info->init_access;
477 _segmentInfos.push_back(info);
481 unsigned Util::SegmentSorter::weight(const SegmentInfo *seg) {
482 return llvm::StringSwitch<unsigned>(seg->name)
483 .Case("__PAGEZERO", 1)
489 bool Util::SegmentSorter::operator()(const SegmentInfo *left,
490 const SegmentInfo *right) {
491 return (weight(left) < weight(right));
494 unsigned Util::TextSectionSorter::weight(const SectionInfo *sect) {
495 return llvm::StringSwitch<unsigned>(sect->sectionName)
498 .Case("__stub_helper", 3)
500 .Case("__cstring", 5)
501 .Case("__unwind_info", 98)
502 .Case("__eh_frame", 99)
506 bool Util::TextSectionSorter::operator()(const SectionInfo *left,
507 const SectionInfo *right) {
508 return (weight(left) < weight(right));
511 void Util::organizeSections() {
512 // NOTE!: Keep this in sync with assignAddressesToSections.
513 switch (_ctx.outputMachOType()) {
514 case llvm::MachO::MH_EXECUTE:
515 // Main executables, need a zero-page segment
516 segmentForName("__PAGEZERO");
517 // Fall into next case.
519 case llvm::MachO::MH_DYLIB:
520 case llvm::MachO::MH_BUNDLE:
521 // All dynamic code needs TEXT segment to hold the load commands.
522 segmentForName("__TEXT");
527 segmentForName("__LINKEDIT");
529 // Group sections into segments.
530 for (SectionInfo *si : _sectionInfos) {
531 SegmentInfo *seg = segmentForName(si->segmentName);
532 seg->sections.push_back(si);
535 std::sort(_segmentInfos.begin(), _segmentInfos.end(), SegmentSorter());
537 // Sort sections within segments.
538 for (SegmentInfo *seg : _segmentInfos) {
539 if (seg->name.equals("__TEXT")) {
540 std::sort(seg->sections.begin(), seg->sections.end(),
541 TextSectionSorter());
545 // Record final section indexes.
546 uint32_t segmentIndex = 0;
547 uint32_t sectionIndex = 1;
548 for (SegmentInfo *seg : _segmentInfos) {
549 seg->normalizedSegmentIndex = segmentIndex++;
550 for (SectionInfo *sect : seg->sections)
551 sect->finalSectionIndex = sectionIndex++;
555 void Util::layoutSectionsInSegment(SegmentInfo *seg, uint64_t &addr) {
557 for (SectionInfo *sect : seg->sections) {
558 sect->address = llvm::alignTo(addr, sect->alignment);
559 addr = sect->address + sect->size;
561 seg->size = llvm::alignTo(addr - seg->address, _ctx.pageSize());
564 // __TEXT segment lays out backwards so padding is at front after load commands.
565 void Util::layoutSectionsInTextSegment(size_t hlcSize, SegmentInfo *seg,
568 // Walks sections starting at end to calculate padding for start.
570 for (auto it = seg->sections.rbegin(); it != seg->sections.rend(); ++it) {
571 SectionInfo *sect = *it;
573 taddr = taddr & (0 - sect->alignment);
575 int64_t padding = taddr - hlcSize;
577 padding += _ctx.pageSize();
578 // Start assigning section address starting at padded offset.
579 addr += (padding + hlcSize);
580 for (SectionInfo *sect : seg->sections) {
581 sect->address = llvm::alignTo(addr, sect->alignment);
582 addr = sect->address + sect->size;
584 seg->size = llvm::alignTo(addr - seg->address, _ctx.pageSize());
587 void Util::assignAddressesToSections(const NormalizedFile &file) {
588 // NOTE!: Keep this in sync with organizeSections.
589 size_t hlcSize = headerAndLoadCommandsSize(file);
590 uint64_t address = 0;
591 for (SegmentInfo *seg : _segmentInfos) {
592 if (seg->name.equals("__PAGEZERO")) {
593 seg->size = _ctx.pageZeroSize();
594 address += seg->size;
596 else if (seg->name.equals("__TEXT")) {
597 // _ctx.baseAddress() == 0 implies it was either unspecified or
598 // pageZeroSize is also 0. In either case resetting address is safe.
599 address = _ctx.baseAddress() ? _ctx.baseAddress() : address;
600 layoutSectionsInTextSegment(hlcSize, seg, address);
602 layoutSectionsInSegment(seg, address);
604 address = llvm::alignTo(address, _ctx.pageSize());
606 DEBUG_WITH_TYPE("WriterMachO-norm",
607 llvm::dbgs() << "assignAddressesToSections()\n";
608 for (SegmentInfo *sgi : _segmentInfos) {
609 llvm::dbgs() << " address=" << llvm::format("0x%08llX", sgi->address)
610 << ", size=" << llvm::format("0x%08llX", sgi->size)
611 << ", segment-name='" << sgi->name
613 for (SectionInfo *si : sgi->sections) {
614 llvm::dbgs()<< " addr=" << llvm::format("0x%08llX", si->address)
615 << ", size=" << llvm::format("0x%08llX", si->size)
616 << ", section-name='" << si->sectionName
623 void Util::copySegmentInfo(NormalizedFile &file) {
624 for (SegmentInfo *sgi : _segmentInfos) {
626 seg.name = sgi->name;
627 seg.address = sgi->address;
628 seg.size = sgi->size;
629 seg.init_access = sgi->init_access;
630 seg.max_access = sgi->max_access;
631 file.segments.push_back(seg);
635 void Util::appendSection(SectionInfo *si, NormalizedFile &file) {
636 // Add new empty section to end of file.sections.
638 file.sections.push_back(std::move(temp));
639 Section* normSect = &file.sections.back();
640 // Copy fields to normalized section.
641 normSect->segmentName = si->segmentName;
642 normSect->sectionName = si->sectionName;
643 normSect->type = si->type;
644 normSect->attributes = si->attributes;
645 normSect->address = si->address;
646 normSect->alignment = si->alignment;
647 // Record where normalized section is.
648 si->normalizedSectionIndex = file.sections.size()-1;
651 void Util::copySectionContent(NormalizedFile &file) {
652 const bool r = (_ctx.outputMachOType() == llvm::MachO::MH_OBJECT);
654 // Utility function for ArchHandler to find address of atom in output file.
655 auto addrForAtom = [&] (const Atom &atom) -> uint64_t {
656 auto pos = _atomToAddress.find(&atom);
657 assert(pos != _atomToAddress.end());
661 auto sectionAddrForAtom = [&] (const Atom &atom) -> uint64_t {
662 for (const SectionInfo *sectInfo : _sectionInfos)
663 for (const AtomInfo &atomInfo : sectInfo->atomsAndOffsets)
664 if (atomInfo.atom == &atom)
665 return sectInfo->address;
666 llvm_unreachable("atom not assigned to section");
669 for (SectionInfo *si : _sectionInfos) {
670 Section *normSect = &file.sections[si->normalizedSectionIndex];
671 if (isZeroFillSection(si->type)) {
672 const uint8_t *empty = nullptr;
673 normSect->content = llvm::makeArrayRef(empty, si->size);
676 // Copy content from atoms to content buffer for section.
677 llvm::MutableArrayRef<uint8_t> sectionContent;
679 uint8_t *sectContent = file.ownedAllocations.Allocate<uint8_t>(si->size);
680 sectionContent = llvm::MutableArrayRef<uint8_t>(sectContent, si->size);
681 normSect->content = sectionContent;
683 for (AtomInfo &ai : si->atomsAndOffsets) {
684 if (!ai.atom->size()) {
685 assert(ai.atom->begin() == ai.atom->end() &&
686 "Cannot have references without content");
689 auto atomContent = sectionContent.slice(ai.offsetInSection,
691 _archHandler.generateAtomContent(*ai.atom, r, addrForAtom,
692 sectionAddrForAtom, _ctx.baseAddress(),
698 void Util::copySectionInfo(NormalizedFile &file) {
699 file.sections.reserve(_sectionInfos.size());
700 // Write sections grouped by segment.
701 for (SegmentInfo *sgi : _segmentInfos) {
702 for (SectionInfo *si : sgi->sections) {
703 appendSection(si, file);
708 void Util::updateSectionInfo(NormalizedFile &file) {
709 file.sections.reserve(_sectionInfos.size());
710 // sections grouped by segment.
711 for (SegmentInfo *sgi : _segmentInfos) {
712 Segment *normSeg = &file.segments[sgi->normalizedSegmentIndex];
713 normSeg->address = sgi->address;
714 normSeg->size = sgi->size;
715 for (SectionInfo *si : sgi->sections) {
716 Section *normSect = &file.sections[si->normalizedSectionIndex];
717 normSect->address = si->address;
722 void Util::copyEntryPointAddress(NormalizedFile &nFile) {
724 nFile.entryAddress = 0;
728 if (_ctx.outputTypeHasEntry()) {
729 if (_archHandler.isThumbFunction(*_entryAtom))
730 nFile.entryAddress = (_atomToAddress[_entryAtom] | 1);
732 nFile.entryAddress = _atomToAddress[_entryAtom];
736 void Util::buildAtomToAddressMap() {
737 DEBUG_WITH_TYPE("WriterMachO-address", llvm::dbgs()
738 << "assign atom addresses:\n");
739 const bool lookForEntry = _ctx.outputTypeHasEntry();
740 for (SectionInfo *sect : _sectionInfos) {
741 for (const AtomInfo &info : sect->atomsAndOffsets) {
742 _atomToAddress[info.atom] = sect->address + info.offsetInSection;
743 if (lookForEntry && (info.atom->contentType() == DefinedAtom::typeCode) &&
744 (info.atom->size() != 0) &&
745 info.atom->name() == _ctx.entrySymbolName()) {
746 _entryAtom = info.atom;
748 DEBUG_WITH_TYPE("WriterMachO-address", llvm::dbgs()
750 << llvm::format("0x%016X", _atomToAddress[info.atom])
751 << llvm::format(" 0x%09lX", info.atom)
753 << info.atom->file().ordinal()
755 << info.atom->ordinal()
759 << info.atom->contentType()
763 DEBUG_WITH_TYPE("WriterMachO-address", llvm::dbgs()
764 << "assign header alias atom addresses:\n");
765 for (const Atom *atom : _machHeaderAliasAtoms) {
766 _atomToAddress[atom] = _ctx.baseAddress();
768 if (auto *definedAtom = dyn_cast<DefinedAtom>(atom)) {
769 DEBUG_WITH_TYPE("WriterMachO-address", llvm::dbgs()
771 << llvm::format("0x%016X", _atomToAddress[atom])
772 << llvm::format(" 0x%09lX", atom)
774 << definedAtom->file().ordinal()
776 << definedAtom->ordinal()
778 << definedAtom->name()
780 << definedAtom->contentType()
783 DEBUG_WITH_TYPE("WriterMachO-address", llvm::dbgs()
785 << llvm::format("0x%016X", _atomToAddress[atom])
787 << " name=" << atom->name() << "\n");
793 llvm::Error Util::synthesizeDebugNotes(NormalizedFile &file) {
795 // Bail out early if we don't need to generate a debug map.
796 if (_ctx.debugInfoMode() == MachOLinkingContext::DebugInfoMode::noDebugMap)
797 return llvm::Error::success();
799 std::vector<const DefinedAtom*> atomsNeedingDebugNotes;
800 std::set<const mach_o::MachOFile*> filesWithStabs;
801 bool objFileHasDwarf = false;
802 const File *objFile = nullptr;
804 for (SectionInfo *sect : _sectionInfos) {
805 for (const AtomInfo &info : sect->atomsAndOffsets) {
806 if (const DefinedAtom *atom = dyn_cast<DefinedAtom>(info.atom)) {
808 // FIXME: No stabs/debug-notes for symbols that wouldn't be in the
810 // FIXME: No stabs/debug-notes for kernel dtrace probes.
812 if (atom->contentType() == DefinedAtom::typeCFI ||
813 atom->contentType() == DefinedAtom::typeCString)
816 // Whenever we encounter a new file, update the 'objfileHasDwarf' flag.
817 if (&info.atom->file() != objFile) {
818 objFileHasDwarf = false;
819 if (const mach_o::MachOFile *atomFile =
820 dyn_cast<mach_o::MachOFile>(&info.atom->file())) {
821 if (atomFile->debugInfo()) {
822 if (isa<mach_o::DwarfDebugInfo>(atomFile->debugInfo()))
823 objFileHasDwarf = true;
824 else if (isa<mach_o::StabsDebugInfo>(atomFile->debugInfo()))
825 filesWithStabs.insert(atomFile);
830 // If this atom is from a file that needs dwarf, add it to the list.
832 atomsNeedingDebugNotes.push_back(info.atom);
837 // Sort atoms needing debug notes by file ordinal, then atom ordinal.
838 std::sort(atomsNeedingDebugNotes.begin(), atomsNeedingDebugNotes.end(),
839 [](const DefinedAtom *lhs, const DefinedAtom *rhs) {
840 if (lhs->file().ordinal() != rhs->file().ordinal())
841 return (lhs->file().ordinal() < rhs->file().ordinal());
842 return (lhs->ordinal() < rhs->ordinal());
845 // FIXME: Handle <rdar://problem/17689030>: Add -add_ast_path option to \
846 // linker which add N_AST stab entry to output
847 // See OutputFile::synthesizeDebugNotes in ObjectFile.cpp in ld64.
849 StringRef oldFileName = "";
850 StringRef oldDirPath = "";
851 bool wroteStartSO = false;
852 std::unordered_set<std::string> seenFiles;
853 for (const DefinedAtom *atom : atomsNeedingDebugNotes) {
854 const auto &atomFile = cast<mach_o::MachOFile>(atom->file());
855 assert(dyn_cast_or_null<lld::mach_o::DwarfDebugInfo>(atomFile.debugInfo())
856 && "file for atom needing debug notes does not contain dwarf");
857 auto &dwarf = cast<lld::mach_o::DwarfDebugInfo>(*atomFile.debugInfo());
859 auto &tu = dwarf.translationUnitSource();
860 StringRef newFileName = tu.name;
861 StringRef newDirPath = tu.path;
863 // Add an SO whenever the TU source file changes.
864 if (newFileName != oldFileName || newDirPath != oldDirPath) {
865 // Translation unit change, emit ending SO
866 if (oldFileName != "")
867 _stabs.push_back(mach_o::Stab(nullptr, N_SO, 1, 0, 0, ""));
869 oldFileName = newFileName;
870 oldDirPath = newDirPath;
872 // If newDirPath doesn't end with a '/' we need to add one:
873 if (newDirPath.back() != '/') {
875 file.ownedAllocations.Allocate<char>(newDirPath.size() + 2);
876 memcpy(p, newDirPath.data(), newDirPath.size());
877 p[newDirPath.size()] = '/';
878 p[newDirPath.size() + 1] = '\0';
882 // New translation unit, emit start SOs:
883 _stabs.push_back(mach_o::Stab(nullptr, N_SO, 0, 0, 0, newDirPath));
884 _stabs.push_back(mach_o::Stab(nullptr, N_SO, 0, 0, 0, newFileName));
886 // Synthesize OSO for start of file.
887 char *fullPath = nullptr;
889 SmallString<1024> pathBuf(atomFile.path());
890 if (auto EC = llvm::sys::fs::make_absolute(pathBuf))
891 return llvm::errorCodeToError(EC);
892 fullPath = file.ownedAllocations.Allocate<char>(pathBuf.size() + 1);
893 memcpy(fullPath, pathBuf.c_str(), pathBuf.size() + 1);
897 uint32_t modTime = 0;
898 llvm::sys::fs::file_status stat;
899 if (!llvm::sys::fs::status(fullPath, stat))
900 if (llvm::sys::fs::exists(stat))
901 modTime = llvm::sys::toTimeT(stat.getLastModificationTime());
903 _stabs.push_back(mach_o::Stab(nullptr, N_OSO, _ctx.getCPUSubType(), 1,
905 // <rdar://problem/6337329> linker should put cpusubtype in n_sect field
906 // of nlist entry for N_OSO debug note entries.
910 if (atom->contentType() == DefinedAtom::typeCode) {
911 // Synthesize BNSYM and start FUN stabs.
912 _stabs.push_back(mach_o::Stab(atom, N_BNSYM, 1, 0, 0, ""));
913 _stabs.push_back(mach_o::Stab(atom, N_FUN, 1, 0, 0, atom->name()));
914 // Synthesize any SOL stabs needed
915 // FIXME: add SOL stabs.
916 _stabs.push_back(mach_o::Stab(nullptr, N_FUN, 0, 0,
917 atom->rawContent().size(), ""));
918 _stabs.push_back(mach_o::Stab(nullptr, N_ENSYM, 1, 0,
919 atom->rawContent().size(), ""));
921 if (atom->scope() == Atom::scopeTranslationUnit)
922 _stabs.push_back(mach_o::Stab(atom, N_STSYM, 1, 0, 0, atom->name()));
924 _stabs.push_back(mach_o::Stab(nullptr, N_GSYM, 1, 0, 0, atom->name()));
928 // Emit ending SO if necessary.
930 _stabs.push_back(mach_o::Stab(nullptr, N_SO, 1, 0, 0, ""));
932 // Copy any stabs from .o file.
933 for (const auto *objFile : filesWithStabs) {
934 const auto &stabsList =
935 cast<mach_o::StabsDebugInfo>(objFile->debugInfo())->stabs();
936 for (auto &stab : stabsList) {
937 // FIXME: Drop stabs whose atoms have been dead-stripped.
938 _stabs.push_back(stab);
942 return llvm::Error::success();
945 uint16_t Util::descBits(const DefinedAtom* atom) {
947 switch (atom->merge()) {
948 case lld::DefinedAtom::mergeNo:
949 case lld::DefinedAtom::mergeAsTentative:
951 case lld::DefinedAtom::mergeAsWeak:
952 case lld::DefinedAtom::mergeAsWeakAndAddressUsed:
955 case lld::DefinedAtom::mergeSameNameAndSize:
956 case lld::DefinedAtom::mergeByLargestSection:
957 case lld::DefinedAtom::mergeByContent:
958 llvm_unreachable("Unsupported DefinedAtom::merge()");
961 if (atom->contentType() == lld::DefinedAtom::typeResolver)
962 desc |= N_SYMBOL_RESOLVER;
963 if (atom->contentType() == lld::DefinedAtom::typeMachHeader)
964 desc |= REFERENCED_DYNAMICALLY;
965 if (_archHandler.isThumbFunction(*atom))
966 desc |= N_ARM_THUMB_DEF;
967 if (atom->deadStrip() == DefinedAtom::deadStripNever &&
968 _ctx.outputMachOType() == llvm::MachO::MH_OBJECT) {
969 if ((atom->contentType() != DefinedAtom::typeInitializerPtr)
970 && (atom->contentType() != DefinedAtom::typeTerminatorPtr))
971 desc |= N_NO_DEAD_STRIP;
976 bool Util::AtomSorter::operator()(const AtomAndIndex &left,
977 const AtomAndIndex &right) {
978 return (left.atom->name().compare(right.atom->name()) < 0);
981 llvm::Error Util::getSymbolTableRegion(const DefinedAtom* atom,
982 bool &inGlobalsRegion,
983 SymbolScope &scope) {
984 bool rMode = (_ctx.outputMachOType() == llvm::MachO::MH_OBJECT);
985 switch (atom->scope()) {
986 case Atom::scopeTranslationUnit:
988 inGlobalsRegion = false;
989 return llvm::Error::success();
990 case Atom::scopeLinkageUnit:
991 if ((_ctx.exportMode() == MachOLinkingContext::ExportMode::whiteList) &&
992 _ctx.exportSymbolNamed(atom->name())) {
993 return llvm::make_error<GenericError>(
994 Twine("cannot export hidden symbol ") + atom->name());
997 if (_ctx.keepPrivateExterns()) {
998 // -keep_private_externs means keep in globals region as N_PEXT.
999 scope = N_PEXT | N_EXT;
1000 inGlobalsRegion = true;
1001 return llvm::Error::success();
1004 // scopeLinkageUnit symbols are no longer global once linked.
1006 inGlobalsRegion = false;
1007 return llvm::Error::success();
1008 case Atom::scopeGlobal:
1009 if (_ctx.exportRestrictMode()) {
1010 if (_ctx.exportSymbolNamed(atom->name())) {
1012 inGlobalsRegion = true;
1013 return llvm::Error::success();
1016 inGlobalsRegion = false;
1017 return llvm::Error::success();
1021 inGlobalsRegion = true;
1022 return llvm::Error::success();
1026 llvm_unreachable("atom->scope() unknown enum value");
1031 llvm::Error Util::addSymbols(const lld::File &atomFile,
1032 NormalizedFile &file) {
1033 bool rMode = (_ctx.outputMachOType() == llvm::MachO::MH_OBJECT);
1034 // Mach-O symbol table has four regions: stabs, locals, globals, undefs.
1037 for (auto &stab : _stabs) {
1039 sym.type = static_cast<NListType>(stab.type);
1041 sym.sect = stab.other;
1042 sym.desc = stab.desc;
1044 sym.value = _atomToAddress[stab.atom];
1046 sym.value = stab.value;
1047 sym.name = stab.str;
1048 file.stabsSymbols.push_back(sym);
1051 // Add all local (non-global) symbols in address order
1052 std::vector<AtomAndIndex> globals;
1053 globals.reserve(512);
1054 for (SectionInfo *sect : _sectionInfos) {
1055 for (const AtomInfo &info : sect->atomsAndOffsets) {
1056 const DefinedAtom *atom = info.atom;
1057 if (!atom->name().empty()) {
1058 SymbolScope symbolScope;
1059 bool inGlobalsRegion;
1060 if (auto ec = getSymbolTableRegion(atom, inGlobalsRegion, symbolScope)){
1063 if (inGlobalsRegion) {
1064 AtomAndIndex ai = { atom, sect->finalSectionIndex, symbolScope };
1065 globals.push_back(ai);
1068 sym.name = atom->name();
1070 sym.scope = symbolScope;
1071 sym.sect = sect->finalSectionIndex;
1072 sym.desc = descBits(atom);
1073 sym.value = _atomToAddress[atom];
1074 _atomToSymbolIndex[atom] = file.localSymbols.size();
1075 file.localSymbols.push_back(sym);
1077 } else if (rMode && _archHandler.needsLocalSymbolInRelocatableFile(atom)){
1078 // Create 'Lxxx' labels for anonymous atoms if archHandler says so.
1079 static unsigned tempNum = 1;
1081 sprintf(tmpName, "L%04u", tempNum++);
1082 StringRef tempRef(tmpName);
1084 sym.name = tempRef.copy(file.ownedAllocations);
1087 sym.sect = sect->finalSectionIndex;
1089 sym.value = _atomToAddress[atom];
1090 _atomToSymbolIndex[atom] = file.localSymbols.size();
1091 file.localSymbols.push_back(sym);
1096 // Sort global symbol alphabetically, then add to symbol table.
1097 std::sort(globals.begin(), globals.end(), AtomSorter());
1098 const uint32_t globalStartIndex = file.localSymbols.size();
1099 for (AtomAndIndex &ai : globals) {
1101 sym.name = ai.atom->name();
1103 sym.scope = ai.scope;
1104 sym.sect = ai.index;
1105 sym.desc = descBits(static_cast<const DefinedAtom*>(ai.atom));
1106 sym.value = _atomToAddress[ai.atom];
1107 _atomToSymbolIndex[ai.atom] = globalStartIndex + file.globalSymbols.size();
1108 file.globalSymbols.push_back(sym);
1111 // Sort undefined symbol alphabetically, then add to symbol table.
1112 std::vector<AtomAndIndex> undefs;
1113 undefs.reserve(128);
1114 for (const UndefinedAtom *atom : atomFile.undefined()) {
1115 AtomAndIndex ai = { atom, 0, N_EXT };
1116 undefs.push_back(ai);
1118 for (const SharedLibraryAtom *atom : atomFile.sharedLibrary()) {
1119 AtomAndIndex ai = { atom, 0, N_EXT };
1120 undefs.push_back(ai);
1122 std::sort(undefs.begin(), undefs.end(), AtomSorter());
1123 const uint32_t start = file.globalSymbols.size() + file.localSymbols.size();
1124 for (AtomAndIndex &ai : undefs) {
1128 uint8_t ordinal = 0;
1129 if (!_ctx.useFlatNamespace())
1130 ordinal = dylibOrdinal(dyn_cast<SharedLibraryAtom>(ai.atom));
1131 llvm::MachO::SET_LIBRARY_ORDINAL(desc, ordinal);
1133 sym.name = ai.atom->name();
1135 sym.scope = ai.scope;
1139 _atomToSymbolIndex[ai.atom] = file.undefinedSymbols.size() + start;
1140 file.undefinedSymbols.push_back(sym);
1143 return llvm::Error::success();
1146 const Atom *Util::targetOfLazyPointer(const DefinedAtom *lpAtom) {
1147 for (const Reference *ref : *lpAtom) {
1148 if (_archHandler.isLazyPointer(*ref)) {
1149 return ref->target();
1155 const Atom *Util::targetOfStub(const DefinedAtom *stubAtom) {
1156 for (const Reference *ref : *stubAtom) {
1157 if (const Atom *ta = ref->target()) {
1158 if (const DefinedAtom *lpAtom = dyn_cast<DefinedAtom>(ta)) {
1159 const Atom *target = targetOfLazyPointer(lpAtom);
1168 void Util::addIndirectSymbols(const lld::File &atomFile, NormalizedFile &file) {
1169 for (SectionInfo *si : _sectionInfos) {
1170 Section &normSect = file.sections[si->normalizedSectionIndex];
1172 case llvm::MachO::S_NON_LAZY_SYMBOL_POINTERS:
1173 for (const AtomInfo &info : si->atomsAndOffsets) {
1174 bool foundTarget = false;
1175 for (const Reference *ref : *info.atom) {
1176 const Atom *target = ref->target();
1178 if (isa<const SharedLibraryAtom>(target)) {
1179 uint32_t index = _atomToSymbolIndex[target];
1180 normSect.indirectSymbols.push_back(index);
1183 normSect.indirectSymbols.push_back(
1184 llvm::MachO::INDIRECT_SYMBOL_LOCAL);
1189 normSect.indirectSymbols.push_back(
1190 llvm::MachO::INDIRECT_SYMBOL_ABS);
1194 case llvm::MachO::S_LAZY_SYMBOL_POINTERS:
1195 for (const AtomInfo &info : si->atomsAndOffsets) {
1196 const Atom *target = targetOfLazyPointer(info.atom);
1198 uint32_t index = _atomToSymbolIndex[target];
1199 normSect.indirectSymbols.push_back(index);
1203 case llvm::MachO::S_SYMBOL_STUBS:
1204 for (const AtomInfo &info : si->atomsAndOffsets) {
1205 const Atom *target = targetOfStub(info.atom);
1207 uint32_t index = _atomToSymbolIndex[target];
1208 normSect.indirectSymbols.push_back(index);
1218 void Util::addDependentDylibs(const lld::File &atomFile,
1219 NormalizedFile &nFile) {
1220 // Scan all imported symbols and build up list of dylibs they are from.
1222 for (const auto *dylib : _ctx.allDylibs()) {
1223 DylibPathToInfo::iterator pos = _dylibInfo.find(dylib->installName());
1224 if (pos == _dylibInfo.end()) {
1226 bool flatNamespaceAtom = dylib == _ctx.flatNamespaceFile();
1228 // If we're in -flat_namespace mode (or this atom came from the flat
1229 // namespace file under -undefined dynamic_lookup) then use the flat
1231 if (flatNamespaceAtom || _ctx.useFlatNamespace())
1232 info.ordinal = BIND_SPECIAL_DYLIB_FLAT_LOOKUP;
1234 info.ordinal = ordinal++;
1235 info.hasWeak = false;
1236 info.hasNonWeak = !info.hasWeak;
1237 _dylibInfo[dylib->installName()] = info;
1239 // Unless this was a flat_namespace atom, record the source dylib.
1240 if (!flatNamespaceAtom) {
1241 DependentDylib depInfo;
1242 depInfo.path = dylib->installName();
1243 depInfo.kind = llvm::MachO::LC_LOAD_DYLIB;
1244 depInfo.currentVersion = _ctx.dylibCurrentVersion(dylib->path());
1245 depInfo.compatVersion = _ctx.dylibCompatVersion(dylib->path());
1246 nFile.dependentDylibs.push_back(depInfo);
1249 pos->second.hasWeak = false;
1250 pos->second.hasNonWeak = !pos->second.hasWeak;
1253 // Automatically weak link dylib in which all symbols are weak (canBeNull).
1254 for (DependentDylib &dep : nFile.dependentDylibs) {
1255 DylibInfo &info = _dylibInfo[dep.path];
1256 if (info.hasWeak && !info.hasNonWeak)
1257 dep.kind = llvm::MachO::LC_LOAD_WEAK_DYLIB;
1258 else if (_ctx.isUpwardDylib(dep.path))
1259 dep.kind = llvm::MachO::LC_LOAD_UPWARD_DYLIB;
1263 int Util::dylibOrdinal(const SharedLibraryAtom *sa) {
1264 return _dylibInfo[sa->loadName()].ordinal;
1267 void Util::segIndexForSection(const SectionInfo *sect, uint8_t &segmentIndex,
1268 uint64_t &segmentStartAddr) {
1270 for (const SegmentInfo *seg : _segmentInfos) {
1271 if ((seg->address <= sect->address)
1272 && (seg->address+seg->size >= sect->address+sect->size)) {
1273 segmentStartAddr = seg->address;
1278 llvm_unreachable("section not in any segment");
1281 uint32_t Util::sectionIndexForAtom(const Atom *atom) {
1282 uint64_t address = _atomToAddress[atom];
1283 for (const SectionInfo *si : _sectionInfos) {
1284 if ((si->address <= address) && (address < si->address+si->size))
1285 return si->finalSectionIndex;
1287 llvm_unreachable("atom not in any section");
1290 void Util::addSectionRelocs(const lld::File &, NormalizedFile &file) {
1291 if (_ctx.outputMachOType() != llvm::MachO::MH_OBJECT)
1294 // Utility function for ArchHandler to find symbol index for an atom.
1295 auto symIndexForAtom = [&] (const Atom &atom) -> uint32_t {
1296 auto pos = _atomToSymbolIndex.find(&atom);
1297 assert(pos != _atomToSymbolIndex.end());
1301 // Utility function for ArchHandler to find section index for an atom.
1302 auto sectIndexForAtom = [&] (const Atom &atom) -> uint32_t {
1303 return sectionIndexForAtom(&atom);
1306 // Utility function for ArchHandler to find address of atom in output file.
1307 auto addressForAtom = [&] (const Atom &atom) -> uint64_t {
1308 auto pos = _atomToAddress.find(&atom);
1309 assert(pos != _atomToAddress.end());
1313 for (SectionInfo *si : _sectionInfos) {
1314 Section &normSect = file.sections[si->normalizedSectionIndex];
1315 for (const AtomInfo &info : si->atomsAndOffsets) {
1316 const DefinedAtom *atom = info.atom;
1317 for (const Reference *ref : *atom) {
1318 // Skip emitting relocs for sections which are always able to be
1319 // implicitly regenerated and where the relocation targets an address
1320 // which is defined.
1321 if (si->relocsToDefinedCanBeImplicit && isa<DefinedAtom>(ref->target()))
1323 _archHandler.appendSectionRelocations(*atom, info.offsetInSection, *ref,
1327 normSect.relocations);
1333 void Util::addFunctionStarts(const lld::File &, NormalizedFile &file) {
1334 if (!_ctx.generateFunctionStartsLoadCommand())
1336 file.functionStarts.reserve(8192);
1337 // Delta compress function starts, starting with the mach header symbol.
1338 const uint64_t badAddress = ~0ULL;
1339 uint64_t addr = badAddress;
1340 for (SectionInfo *si : _sectionInfos) {
1341 for (const AtomInfo &info : si->atomsAndOffsets) {
1342 auto type = info.atom->contentType();
1343 if (type == DefinedAtom::typeMachHeader) {
1344 addr = _atomToAddress[info.atom];
1347 if (type != DefinedAtom::typeCode)
1349 assert(addr != badAddress && "Missing mach header symbol");
1350 // Skip atoms which have 0 size. This is so that LC_FUNCTION_STARTS
1351 // can't spill in to the next section.
1352 if (!info.atom->size())
1354 uint64_t nextAddr = _atomToAddress[info.atom];
1355 if (_archHandler.isThumbFunction(*info.atom))
1357 uint64_t delta = nextAddr - addr;
1360 buffer.append_uleb128(delta);
1361 file.functionStarts.insert(file.functionStarts.end(), buffer.bytes(),
1362 buffer.bytes() + buffer.size());
1368 // Null terminate, and pad to pointer size for this arch.
1369 file.functionStarts.push_back(0);
1371 auto size = file.functionStarts.size();
1372 for (unsigned i = size, e = llvm::alignTo(size, _ctx.is64Bit() ? 8 : 4);
1374 file.functionStarts.push_back(0);
1377 void Util::buildDataInCodeArray(const lld::File &, NormalizedFile &file) {
1378 if (!_ctx.generateDataInCodeLoadCommand())
1380 for (SectionInfo *si : _sectionInfos) {
1381 for (const AtomInfo &info : si->atomsAndOffsets) {
1382 // Atoms that contain data-in-code have "transition" references
1383 // which mark a point where the embedded data starts of ends.
1384 // This needs to be converted to the mach-o format which is an array
1385 // of data-in-code ranges.
1386 uint32_t startOffset = 0;
1387 DataRegionType mode = DataRegionType(0);
1388 for (const Reference *ref : *info.atom) {
1389 if (ref->kindNamespace() != Reference::KindNamespace::mach_o)
1391 if (_archHandler.isDataInCodeTransition(ref->kindValue())) {
1392 DataRegionType nextMode = (DataRegionType)ref->addend();
1393 if (mode != nextMode) {
1395 // Found end data range, so make range entry.
1397 entry.offset = si->address + info.offsetInSection + startOffset;
1398 entry.length = ref->offsetInAtom() - startOffset;
1400 file.dataInCode.push_back(entry);
1404 startOffset = ref->offsetInAtom();
1408 // Function ends with data (no end transition).
1410 entry.offset = si->address + info.offsetInSection + startOffset;
1411 entry.length = info.atom->size() - startOffset;
1413 file.dataInCode.push_back(entry);
1419 void Util::addRebaseAndBindingInfo(const lld::File &atomFile,
1420 NormalizedFile &nFile) {
1421 if (_ctx.outputMachOType() == llvm::MachO::MH_OBJECT)
1424 uint8_t segmentIndex;
1425 uint64_t segmentStartAddr;
1426 for (SectionInfo *sect : _sectionInfos) {
1427 segIndexForSection(sect, segmentIndex, segmentStartAddr);
1428 for (const AtomInfo &info : sect->atomsAndOffsets) {
1429 const DefinedAtom *atom = info.atom;
1430 for (const Reference *ref : *atom) {
1431 uint64_t segmentOffset = _atomToAddress[atom] + ref->offsetInAtom()
1433 const Atom* targ = ref->target();
1434 if (_archHandler.isPointer(*ref)) {
1435 // A pointer to a DefinedAtom requires rebasing.
1436 if (isa<DefinedAtom>(targ)) {
1437 RebaseLocation rebase;
1438 rebase.segIndex = segmentIndex;
1439 rebase.segOffset = segmentOffset;
1440 rebase.kind = llvm::MachO::REBASE_TYPE_POINTER;
1441 nFile.rebasingInfo.push_back(rebase);
1443 // A pointer to an SharedLibraryAtom requires binding.
1444 if (const SharedLibraryAtom *sa = dyn_cast<SharedLibraryAtom>(targ)) {
1446 bind.segIndex = segmentIndex;
1447 bind.segOffset = segmentOffset;
1448 bind.kind = llvm::MachO::BIND_TYPE_POINTER;
1449 bind.canBeNull = sa->canBeNullAtRuntime();
1450 bind.ordinal = dylibOrdinal(sa);
1451 bind.symbolName = targ->name();
1452 bind.addend = ref->addend();
1453 nFile.bindingInfo.push_back(bind);
1456 else if (_archHandler.isLazyPointer(*ref)) {
1458 if (const SharedLibraryAtom *sa = dyn_cast<SharedLibraryAtom>(targ)) {
1459 bind.ordinal = dylibOrdinal(sa);
1461 bind.ordinal = llvm::MachO::BIND_SPECIAL_DYLIB_SELF;
1463 bind.segIndex = segmentIndex;
1464 bind.segOffset = segmentOffset;
1465 bind.kind = llvm::MachO::BIND_TYPE_POINTER;
1466 bind.canBeNull = false; //sa->canBeNullAtRuntime();
1467 bind.symbolName = targ->name();
1468 bind.addend = ref->addend();
1469 nFile.lazyBindingInfo.push_back(bind);
1476 void Util::addExportInfo(const lld::File &atomFile, NormalizedFile &nFile) {
1477 if (_ctx.outputMachOType() == llvm::MachO::MH_OBJECT)
1480 for (SectionInfo *sect : _sectionInfos) {
1481 for (const AtomInfo &info : sect->atomsAndOffsets) {
1482 const DefinedAtom *atom = info.atom;
1483 if (atom->scope() != Atom::scopeGlobal)
1485 if (_ctx.exportRestrictMode()) {
1486 if (!_ctx.exportSymbolNamed(atom->name()))
1490 exprt.name = atom->name();
1491 exprt.offset = _atomToAddress[atom] - _ctx.baseAddress();
1492 exprt.kind = EXPORT_SYMBOL_FLAGS_KIND_REGULAR;
1493 if (atom->merge() == DefinedAtom::mergeAsWeak)
1494 exprt.flags = EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION;
1497 exprt.otherOffset = 0;
1498 exprt.otherName = StringRef();
1499 nFile.exportInfo.push_back(exprt);
1504 uint32_t Util::fileFlags() {
1505 // FIXME: these need to determined at runtime.
1506 if (_ctx.outputMachOType() == MH_OBJECT) {
1507 return _subsectionsViaSymbols ? MH_SUBSECTIONS_VIA_SYMBOLS : 0;
1509 uint32_t flags = MH_DYLDLINK;
1510 if (!_ctx.useFlatNamespace())
1511 flags |= MH_TWOLEVEL | MH_NOUNDEFS;
1512 if ((_ctx.outputMachOType() == MH_EXECUTE) && _ctx.PIE())
1514 if (_hasTLVDescriptors)
1515 flags |= (MH_PIE | MH_HAS_TLV_DESCRIPTORS);
1520 } // end anonymous namespace
1524 namespace normalized {
1526 /// Convert a set of Atoms into a normalized mach-o file.
1527 llvm::Expected<std::unique_ptr<NormalizedFile>>
1528 normalizedFromAtoms(const lld::File &atomFile,
1529 const MachOLinkingContext &context) {
1530 // The util object buffers info until the normalized file can be made.
1532 util.processDefinedAtoms(atomFile);
1533 util.organizeSections();
1535 std::unique_ptr<NormalizedFile> f(new NormalizedFile());
1536 NormalizedFile &normFile = *f.get();
1537 normFile.arch = context.arch();
1538 normFile.fileType = context.outputMachOType();
1539 normFile.flags = util.fileFlags();
1540 normFile.stackSize = context.stackSize();
1541 normFile.installName = context.installName();
1542 normFile.currentVersion = context.currentVersion();
1543 normFile.compatVersion = context.compatibilityVersion();
1544 normFile.os = context.os();
1546 // If we are emitting an object file, then the min version is the maximum
1547 // of the min's of all the source files and the cmdline.
1548 if (normFile.fileType == llvm::MachO::MH_OBJECT)
1549 normFile.minOSverson = std::max(context.osMinVersion(), util.minVersion());
1551 normFile.minOSverson = context.osMinVersion();
1553 normFile.minOSVersionKind = util.minVersionCommandType();
1555 normFile.sdkVersion = context.sdkVersion();
1556 normFile.sourceVersion = context.sourceVersion();
1558 if (context.generateVersionLoadCommand() &&
1559 context.os() != MachOLinkingContext::OS::unknown)
1560 normFile.hasMinVersionLoadCommand = true;
1561 else if (normFile.fileType == llvm::MachO::MH_OBJECT &&
1562 util.allSourceFilesHaveMinVersions() &&
1563 ((normFile.os != MachOLinkingContext::OS::unknown) ||
1564 util.minVersionCommandType())) {
1565 // If we emit an object file, then it should contain a min version load
1566 // command if all of the source files also contained min version commands.
1567 // Also, we either need to have a platform, or found a platform from the
1568 // source object files.
1569 normFile.hasMinVersionLoadCommand = true;
1571 normFile.generateDataInCodeLoadCommand =
1572 context.generateDataInCodeLoadCommand();
1573 normFile.pageSize = context.pageSize();
1574 normFile.rpaths = context.rpaths();
1575 util.addDependentDylibs(atomFile, normFile);
1576 util.copySegmentInfo(normFile);
1577 util.copySectionInfo(normFile);
1578 util.assignAddressesToSections(normFile);
1579 util.buildAtomToAddressMap();
1580 if (auto err = util.synthesizeDebugNotes(normFile))
1581 return std::move(err);
1582 util.updateSectionInfo(normFile);
1583 util.copySectionContent(normFile);
1584 if (auto ec = util.addSymbols(atomFile, normFile)) {
1585 return std::move(ec);
1587 util.addIndirectSymbols(atomFile, normFile);
1588 util.addRebaseAndBindingInfo(atomFile, normFile);
1589 util.addExportInfo(atomFile, normFile);
1590 util.addSectionRelocs(atomFile, normFile);
1591 util.addFunctionStarts(atomFile, normFile);
1592 util.buildDataInCodeArray(atomFile, normFile);
1593 util.copyEntryPointAddress(normFile);
1595 return std::move(f);
1598 } // namespace normalized
1599 } // namespace mach_o