]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/lld/lib/ReaderWriter/MachO/MachONormalizedFileFromAtoms.cpp
Merge lld trunk r321017 to contrib/llvm/tools/lld.
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / lld / lib / ReaderWriter / MachO / MachONormalizedFileFromAtoms.cpp
1 //===- 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 ///                        |
19 ///                    +-------+
20 ///                    | Atoms |
21 ///                    +-------+
22
23 #include "ArchHandler.h"
24 #include "DebugInfo.h"
25 #include "MachONormalizedFile.h"
26 #include "MachONormalizedFileBinaryUtils.h"
27 #include "lld/Common/LLVM.h"
28 #include "lld/Core/Error.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"
36 #include <map>
37 #include <system_error>
38 #include <unordered_set>
39
40 using llvm::StringRef;
41 using llvm::isa;
42 using namespace llvm::MachO;
43 using namespace lld::mach_o::normalized;
44 using namespace lld;
45
46 namespace {
47
48 struct AtomInfo {
49   const DefinedAtom  *atom;
50   uint64_t            offsetInSection;
51 };
52
53 struct SectionInfo {
54   SectionInfo(StringRef seg, StringRef sect, SectionType type,
55               const MachOLinkingContext &ctxt, uint32_t attr,
56               bool relocsToDefinedCanBeImplicit);
57
58   StringRef                 segmentName;
59   StringRef                 sectionName;
60   SectionType               type;
61   uint32_t                  attributes;
62   uint64_t                  address;
63   uint64_t                  size;
64   uint16_t                  alignment;
65
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;
71
72
73   std::vector<AtomInfo>     atomsAndOffsets;
74   uint32_t                  normalizedSectionIndex;
75   uint32_t                  finalSectionIndex;
76 };
77
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) {
85   uint16_t align = 1;
86   if (ctxt.sectionAligned(segmentName, sectionName, align)) {
87     alignment = align;
88   }
89 }
90
91 struct SegmentInfo {
92   SegmentInfo(StringRef name);
93
94   StringRef                  name;
95   uint64_t                   address;
96   uint64_t                   size;
97   uint32_t                   init_access;
98   uint32_t                   max_access;
99   std::vector<SectionInfo*>  sections;
100   uint32_t                   normalizedSegmentIndex;
101 };
102
103 SegmentInfo::SegmentInfo(StringRef n)
104  : name(n), address(0), size(0), init_access(0), max_access(0),
105    normalizedSegmentIndex(0) {
106 }
107
108 class Util {
109 public:
110   Util(const MachOLinkingContext &ctxt)
111       : _ctx(ctxt), _archHandler(ctxt.archHandler()), _entryAtom(nullptr),
112         _hasTLVDescriptors(false), _subsectionsViaSymbols(true) {}
113   ~Util();
114
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);
136
137   bool allSourceFilesHaveMinVersions() const {
138     return _allSourceFilesHaveMinVersions;
139   }
140
141   uint32_t minVersion() const {
142     return _minVersion;
143   }
144
145   LoadCommandType minVersionCommandType() const {
146     return _minVersionCommandType;
147   }
148
149 private:
150   typedef std::map<DefinedAtom::ContentType, SectionInfo*> TypeToSection;
151   typedef llvm::DenseMap<const Atom*, uint64_t> AtomToAddress;
152
153   struct DylibInfo { int ordinal; bool hasWeak; bool hasNonWeak; };
154   typedef llvm::StringMap<DylibInfo> DylibPathToInfo;
155
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);
175   void fixLazyReferenceImm(const DefinedAtom *atom, uint32_t offset,
176                            NormalizedFile &file);
177
178   typedef llvm::DenseMap<const Atom*, uint32_t> AtomToIndex;
179   struct AtomAndIndex { const Atom *atom; uint32_t index; SymbolScope scope; };
180   struct AtomSorter {
181     bool operator()(const AtomAndIndex &left, const AtomAndIndex &right);
182   };
183   struct SegmentSorter {
184     bool operator()(const SegmentInfo *left, const SegmentInfo *right);
185     static unsigned weight(const SegmentInfo *);
186   };
187   struct TextSectionSorter {
188     bool operator()(const SectionInfo *left, const SectionInfo *right);
189     static unsigned weight(const SectionInfo *);
190   };
191
192   const MachOLinkingContext &_ctx;
193   mach_o::ArchHandler          &_archHandler;
194   llvm::BumpPtrAllocator        _allocator;
195   std::vector<SectionInfo*>     _sectionInfos;
196   std::vector<SegmentInfo*>     _segmentInfos;
197   TypeToSection                 _sectionMap;
198   std::vector<SectionInfo*>     _customSections;
199   AtomToAddress                 _atomToAddress;
200   DylibPathToInfo               _dylibInfo;
201   const DefinedAtom            *_entryAtom;
202   AtomToIndex                   _atomToSymbolIndex;
203   std::vector<const Atom *>     _machHeaderAliasAtoms;
204   bool                          _hasTLVDescriptors;
205   bool                          _subsectionsViaSymbols;
206   bool                          _allSourceFilesHaveMinVersions = true;
207   LoadCommandType               _minVersionCommandType = (LoadCommandType)0;
208   uint32_t                      _minVersion = 0;
209   std::vector<lld::mach_o::Stab> _stabs;
210 };
211
212 Util::~Util() {
213   // The SectionInfo structs are BumpPtr allocated, but atomsAndOffsets needs
214   // to be deleted.
215   for (SectionInfo *si : _sectionInfos) {
216     // clear() destroys vector elements, but does not deallocate.
217     // Instead use swap() to deallocate vector buffer.
218     std::vector<AtomInfo> empty;
219     si->atomsAndOffsets.swap(empty);
220   }
221   // The SegmentInfo structs are BumpPtr allocated, but sections needs
222   // to be deleted.
223   for (SegmentInfo *sgi : _segmentInfos) {
224     std::vector<SectionInfo*> empty2;
225     sgi->sections.swap(empty2);
226   }
227 }
228
229 SectionInfo *Util::getRelocatableSection(DefinedAtom::ContentType type) {
230   StringRef segmentName;
231   StringRef sectionName;
232   SectionType sectionType;
233   SectionAttr sectionAttrs;
234   bool relocsToDefinedCanBeImplicit;
235
236   // Use same table used by when parsing .o files.
237   relocatableSectionInfoForContentType(type, segmentName, sectionName,
238                                        sectionType, sectionAttrs,
239                                        relocsToDefinedCanBeImplicit);
240   // If we already have a SectionInfo with this name, re-use it.
241   // This can happen if two ContentType map to the same mach-o section.
242   for (auto sect : _sectionMap) {
243     if (sect.second->sectionName.equals(sectionName) &&
244         sect.second->segmentName.equals(segmentName)) {
245       return sect.second;
246     }
247   }
248   // Otherwise allocate new SectionInfo object.
249   auto *sect = new (_allocator)
250       SectionInfo(segmentName, sectionName, sectionType, _ctx, sectionAttrs,
251                   relocsToDefinedCanBeImplicit);
252   _sectionInfos.push_back(sect);
253   _sectionMap[type] = sect;
254   return sect;
255 }
256
257 #define ENTRY(seg, sect, type, atomType) \
258   {seg, sect, type, DefinedAtom::atomType }
259
260 struct MachOFinalSectionFromAtomType {
261   StringRef                 segmentName;
262   StringRef                 sectionName;
263   SectionType               sectionType;
264   DefinedAtom::ContentType  atomType;
265 };
266
267 const MachOFinalSectionFromAtomType sectsToAtomType[] = {
268   ENTRY("__TEXT", "__text",           S_REGULAR,          typeCode),
269   ENTRY("__TEXT", "__text",           S_REGULAR,          typeMachHeader),
270   ENTRY("__TEXT", "__cstring",        S_CSTRING_LITERALS, typeCString),
271   ENTRY("__TEXT", "__ustring",        S_REGULAR,          typeUTF16String),
272   ENTRY("__TEXT", "__const",          S_REGULAR,          typeConstant),
273   ENTRY("__TEXT", "__const",          S_4BYTE_LITERALS,   typeLiteral4),
274   ENTRY("__TEXT", "__const",          S_8BYTE_LITERALS,   typeLiteral8),
275   ENTRY("__TEXT", "__const",          S_16BYTE_LITERALS,  typeLiteral16),
276   ENTRY("__TEXT", "__stubs",          S_SYMBOL_STUBS,     typeStub),
277   ENTRY("__TEXT", "__stub_helper",    S_REGULAR,          typeStubHelper),
278   ENTRY("__TEXT", "__gcc_except_tab", S_REGULAR,          typeLSDA),
279   ENTRY("__TEXT", "__eh_frame",       S_COALESCED,        typeCFI),
280   ENTRY("__TEXT", "__unwind_info",    S_REGULAR,          typeProcessedUnwindInfo),
281   ENTRY("__DATA", "__data",           S_REGULAR,          typeData),
282   ENTRY("__DATA", "__const",          S_REGULAR,          typeConstData),
283   ENTRY("__DATA", "__cfstring",       S_REGULAR,          typeCFString),
284   ENTRY("__DATA", "__la_symbol_ptr",  S_LAZY_SYMBOL_POINTERS,
285                                                           typeLazyPointer),
286   ENTRY("__DATA", "__mod_init_func",  S_MOD_INIT_FUNC_POINTERS,
287                                                           typeInitializerPtr),
288   ENTRY("__DATA", "__mod_term_func",  S_MOD_TERM_FUNC_POINTERS,
289                                                           typeTerminatorPtr),
290   ENTRY("__DATA", "__got",            S_NON_LAZY_SYMBOL_POINTERS,
291                                                           typeGOT),
292   ENTRY("__DATA", "__nl_symbol_ptr",  S_NON_LAZY_SYMBOL_POINTERS,
293                                                           typeNonLazyPointer),
294   ENTRY("__DATA", "__thread_vars",    S_THREAD_LOCAL_VARIABLES,
295                                                           typeThunkTLV),
296   ENTRY("__DATA", "__thread_data",    S_THREAD_LOCAL_REGULAR,
297                                                           typeTLVInitialData),
298   ENTRY("__DATA", "__thread_ptrs",    S_THREAD_LOCAL_VARIABLE_POINTERS,
299                                                           typeTLVInitializerPtr),
300   ENTRY("__DATA", "__thread_bss",     S_THREAD_LOCAL_ZEROFILL,
301                                                          typeTLVInitialZeroFill),
302   ENTRY("__DATA", "__bss",            S_ZEROFILL,         typeZeroFill),
303   ENTRY("__DATA", "__interposing",    S_INTERPOSING,      typeInterposingTuples),
304 };
305 #undef ENTRY
306
307 SectionInfo *Util::getFinalSection(DefinedAtom::ContentType atomType) {
308   for (auto &p : sectsToAtomType) {
309     if (p.atomType != atomType)
310       continue;
311     SectionAttr sectionAttrs = 0;
312     switch (atomType) {
313     case DefinedAtom::typeMachHeader:
314     case DefinedAtom::typeCode:
315     case DefinedAtom::typeStub:
316     case DefinedAtom::typeStubHelper:
317       sectionAttrs = S_ATTR_PURE_INSTRUCTIONS | S_ATTR_SOME_INSTRUCTIONS;
318       break;
319     case DefinedAtom::typeThunkTLV:
320       _hasTLVDescriptors = true;
321       break;
322     default:
323       break;
324     }
325     // If we already have a SectionInfo with this name, re-use it.
326     // This can happen if two ContentType map to the same mach-o section.
327     for (auto sect : _sectionMap) {
328       if (sect.second->sectionName.equals(p.sectionName) &&
329           sect.second->segmentName.equals(p.segmentName)) {
330         return sect.second;
331       }
332     }
333     // Otherwise allocate new SectionInfo object.
334     auto *sect = new (_allocator) SectionInfo(
335         p.segmentName, p.sectionName, p.sectionType, _ctx, sectionAttrs,
336         /* relocsToDefinedCanBeImplicit */ false);
337     _sectionInfos.push_back(sect);
338     _sectionMap[atomType] = sect;
339     return sect;
340   }
341   llvm_unreachable("content type not yet supported");
342 }
343
344 SectionInfo *Util::sectionForAtom(const DefinedAtom *atom) {
345   if (atom->sectionChoice() == DefinedAtom::sectionBasedOnContent) {
346     // Section for this atom is derived from content type.
347     DefinedAtom::ContentType type = atom->contentType();
348     auto pos = _sectionMap.find(type);
349     if ( pos != _sectionMap.end() )
350       return pos->second;
351     bool rMode = (_ctx.outputMachOType() == llvm::MachO::MH_OBJECT);
352     return rMode ? getRelocatableSection(type) : getFinalSection(type);
353   } else {
354     // This atom needs to be in a custom section.
355     StringRef customName = atom->customSectionName();
356     // Look to see if we have already allocated the needed custom section.
357     for(SectionInfo *sect : _customSections) {
358       const DefinedAtom *firstAtom = sect->atomsAndOffsets.front().atom;
359       if (firstAtom->customSectionName().equals(customName)) {
360         return sect;
361       }
362     }
363     // Not found, so need to create a new custom section.
364     size_t seperatorIndex = customName.find('/');
365     assert(seperatorIndex != StringRef::npos);
366     StringRef segName = customName.slice(0, seperatorIndex);
367     StringRef sectName = customName.drop_front(seperatorIndex + 1);
368     auto *sect =
369         new (_allocator) SectionInfo(segName, sectName, S_REGULAR, _ctx,
370                                      0, /* relocsToDefinedCanBeImplicit */ false);
371     _customSections.push_back(sect);
372     _sectionInfos.push_back(sect);
373     return sect;
374   }
375 }
376
377 void Util::appendAtom(SectionInfo *sect, const DefinedAtom *atom) {
378   // Figure out offset for atom in this section given alignment constraints.
379   uint64_t offset = sect->size;
380   DefinedAtom::Alignment atomAlign = atom->alignment();
381   uint64_t align = atomAlign.value;
382   uint64_t requiredModulus = atomAlign.modulus;
383   uint64_t currentModulus = (offset % align);
384   if ( currentModulus != requiredModulus ) {
385     if ( requiredModulus > currentModulus )
386       offset += requiredModulus-currentModulus;
387     else
388       offset += align+requiredModulus-currentModulus;
389   }
390   // Record max alignment of any atom in this section.
391   if (align > sect->alignment)
392     sect->alignment = atomAlign.value;
393   // Assign atom to this section with this offset.
394   AtomInfo ai = {atom, offset};
395   sect->atomsAndOffsets.push_back(ai);
396   // Update section size to include this atom.
397   sect->size = offset + atom->size();
398 }
399
400 void Util::processDefinedAtoms(const lld::File &atomFile) {
401   for (const DefinedAtom *atom : atomFile.defined()) {
402     processAtomAttributes(atom);
403     assignAtomToSection(atom);
404   }
405 }
406
407 void Util::processAtomAttributes(const DefinedAtom *atom) {
408   if (auto *machoFile = dyn_cast<mach_o::MachOFile>(&atom->file())) {
409     // If the file doesn't use subsections via symbols, then make sure we don't
410     // add that flag to the final output file if we have a relocatable file.
411     if (!machoFile->subsectionsViaSymbols())
412       _subsectionsViaSymbols = false;
413
414     // All the source files must have min versions for us to output an object
415     // file with a min version.
416     if (auto v = machoFile->minVersion())
417       _minVersion = std::max(_minVersion, v);
418     else
419       _allSourceFilesHaveMinVersions = false;
420
421     // If we don't have a platform load command, but one of the source files
422     // does, then take the one from the file.
423     if (!_minVersionCommandType)
424       if (auto v = machoFile->minVersionLoadCommandKind())
425         _minVersionCommandType = v;
426   }
427 }
428
429 void Util::assignAtomToSection(const DefinedAtom *atom) {
430   if (atom->contentType() == DefinedAtom::typeMachHeader) {
431     _machHeaderAliasAtoms.push_back(atom);
432     // Assign atom to this section with this offset.
433     AtomInfo ai = {atom, 0};
434     sectionForAtom(atom)->atomsAndOffsets.push_back(ai);
435   } else if (atom->contentType() == DefinedAtom::typeDSOHandle)
436     _machHeaderAliasAtoms.push_back(atom);
437   else
438     appendAtom(sectionForAtom(atom), atom);
439 }
440
441 SegmentInfo *Util::segmentForName(StringRef segName) {
442   for (SegmentInfo *si : _segmentInfos) {
443     if ( si->name.equals(segName) )
444       return si;
445   }
446   auto *info = new (_allocator) SegmentInfo(segName);
447
448   // Set the initial segment protection.
449   if (segName.equals("__TEXT"))
450     info->init_access = VM_PROT_READ | VM_PROT_EXECUTE;
451   else if (segName.equals("__PAGEZERO"))
452     info->init_access = 0;
453   else if (segName.equals("__LINKEDIT"))
454     info->init_access = VM_PROT_READ;
455   else {
456     // All others default to read-write
457     info->init_access = VM_PROT_READ | VM_PROT_WRITE;
458   }
459
460   // Set max segment protection
461   // Note, its overkill to use a switch statement here, but makes it so much
462   // easier to use switch coverage to catch new cases.
463   switch (_ctx.os()) {
464     case lld::MachOLinkingContext::OS::unknown:
465     case lld::MachOLinkingContext::OS::macOSX:
466     case lld::MachOLinkingContext::OS::iOS_simulator:
467       if (segName.equals("__PAGEZERO")) {
468         info->max_access = 0;
469         break;
470       }
471       // All others default to all
472       info->max_access = VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE;
473       break;
474     case lld::MachOLinkingContext::OS::iOS:
475       // iPhoneOS always uses same protection for max and initial
476       info->max_access = info->init_access;
477       break;
478   }
479   _segmentInfos.push_back(info);
480   return info;
481 }
482
483 unsigned Util::SegmentSorter::weight(const SegmentInfo *seg) {
484  return llvm::StringSwitch<unsigned>(seg->name)
485     .Case("__PAGEZERO",  1)
486     .Case("__TEXT",      2)
487     .Case("__DATA",      3)
488     .Default(100);
489 }
490
491 bool Util::SegmentSorter::operator()(const SegmentInfo *left,
492                                   const SegmentInfo *right) {
493   return (weight(left) < weight(right));
494 }
495
496 unsigned Util::TextSectionSorter::weight(const SectionInfo *sect) {
497  return llvm::StringSwitch<unsigned>(sect->sectionName)
498     .Case("__text",         1)
499     .Case("__stubs",        2)
500     .Case("__stub_helper",  3)
501     .Case("__const",        4)
502     .Case("__cstring",      5)
503     .Case("__unwind_info",  98)
504     .Case("__eh_frame",     99)
505     .Default(10);
506 }
507
508 bool Util::TextSectionSorter::operator()(const SectionInfo *left,
509                                          const SectionInfo *right) {
510   return (weight(left) < weight(right));
511 }
512
513 void Util::organizeSections() {
514   // NOTE!: Keep this in sync with assignAddressesToSections.
515   switch (_ctx.outputMachOType()) {
516     case llvm::MachO::MH_EXECUTE:
517       // Main executables, need a zero-page segment
518       segmentForName("__PAGEZERO");
519       // Fall into next case.
520       LLVM_FALLTHROUGH;
521     case llvm::MachO::MH_DYLIB:
522     case llvm::MachO::MH_BUNDLE:
523       // All dynamic code needs TEXT segment to hold the load commands.
524       segmentForName("__TEXT");
525       break;
526     default:
527       break;
528   }
529   segmentForName("__LINKEDIT");
530
531   // Group sections into segments.
532   for (SectionInfo *si : _sectionInfos) {
533     SegmentInfo *seg = segmentForName(si->segmentName);
534     seg->sections.push_back(si);
535   }
536   // Sort segments.
537   std::sort(_segmentInfos.begin(), _segmentInfos.end(), SegmentSorter());
538
539   // Sort sections within segments.
540   for (SegmentInfo *seg : _segmentInfos) {
541     if (seg->name.equals("__TEXT")) {
542       std::sort(seg->sections.begin(), seg->sections.end(),
543                 TextSectionSorter());
544     }
545   }
546
547   // Record final section indexes.
548   uint32_t segmentIndex = 0;
549   uint32_t sectionIndex = 1;
550   for (SegmentInfo *seg : _segmentInfos) {
551     seg->normalizedSegmentIndex = segmentIndex++;
552     for (SectionInfo *sect : seg->sections)
553       sect->finalSectionIndex = sectionIndex++;
554   }
555 }
556
557 void Util::layoutSectionsInSegment(SegmentInfo *seg, uint64_t &addr) {
558   seg->address = addr;
559   for (SectionInfo *sect : seg->sections) {
560     sect->address = llvm::alignTo(addr, sect->alignment);
561     addr = sect->address + sect->size;
562   }
563   seg->size = llvm::alignTo(addr - seg->address, _ctx.pageSize());
564 }
565
566 // __TEXT segment lays out backwards so padding is at front after load commands.
567 void Util::layoutSectionsInTextSegment(size_t hlcSize, SegmentInfo *seg,
568                                                                uint64_t &addr) {
569   seg->address = addr;
570   // Walks sections starting at end to calculate padding for start.
571   int64_t taddr = 0;
572   for (auto it = seg->sections.rbegin(); it != seg->sections.rend(); ++it) {
573     SectionInfo *sect = *it;
574     taddr -= sect->size;
575     taddr = taddr & (0 - sect->alignment);
576   }
577   int64_t padding = taddr - hlcSize;
578   while (padding < 0)
579     padding += _ctx.pageSize();
580   // Start assigning section address starting at padded offset.
581   addr += (padding + hlcSize);
582   for (SectionInfo *sect : seg->sections) {
583     sect->address = llvm::alignTo(addr, sect->alignment);
584     addr = sect->address + sect->size;
585   }
586   seg->size = llvm::alignTo(addr - seg->address, _ctx.pageSize());
587 }
588
589 void Util::assignAddressesToSections(const NormalizedFile &file) {
590   // NOTE!: Keep this in sync with organizeSections.
591   size_t hlcSize = headerAndLoadCommandsSize(file);
592   uint64_t address = 0;
593   for (SegmentInfo *seg : _segmentInfos) {
594     if (seg->name.equals("__PAGEZERO")) {
595       seg->size = _ctx.pageZeroSize();
596       address += seg->size;
597     }
598     else if (seg->name.equals("__TEXT")) {
599       // _ctx.baseAddress()  == 0 implies it was either unspecified or
600       // pageZeroSize is also 0. In either case resetting address is safe.
601       address = _ctx.baseAddress() ? _ctx.baseAddress() : address;
602       layoutSectionsInTextSegment(hlcSize, seg, address);
603     } else
604       layoutSectionsInSegment(seg, address);
605
606     address = llvm::alignTo(address, _ctx.pageSize());
607   }
608   DEBUG_WITH_TYPE("WriterMachO-norm",
609     llvm::dbgs() << "assignAddressesToSections()\n";
610     for (SegmentInfo *sgi : _segmentInfos) {
611       llvm::dbgs()  << "   address=" << llvm::format("0x%08llX", sgi->address)
612                     << ", size="  << llvm::format("0x%08llX", sgi->size)
613                     << ", segment-name='" << sgi->name
614                     << "'\n";
615       for (SectionInfo *si : sgi->sections) {
616         llvm::dbgs()<< "      addr="  << llvm::format("0x%08llX", si->address)
617                     << ", size="  << llvm::format("0x%08llX", si->size)
618                     << ", section-name='" << si->sectionName
619                     << "\n";
620       }
621     }
622   );
623 }
624
625 void Util::copySegmentInfo(NormalizedFile &file) {
626   for (SegmentInfo *sgi : _segmentInfos) {
627     Segment seg;
628     seg.name    = sgi->name;
629     seg.address = sgi->address;
630     seg.size    = sgi->size;
631     seg.init_access  = sgi->init_access;
632     seg.max_access  = sgi->max_access;
633     file.segments.push_back(seg);
634   }
635 }
636
637 void Util::appendSection(SectionInfo *si, NormalizedFile &file) {
638    // Add new empty section to end of file.sections.
639   Section temp;
640   file.sections.push_back(std::move(temp));
641   Section* normSect = &file.sections.back();
642   // Copy fields to normalized section.
643   normSect->segmentName   = si->segmentName;
644   normSect->sectionName   = si->sectionName;
645   normSect->type          = si->type;
646   normSect->attributes    = si->attributes;
647   normSect->address       = si->address;
648   normSect->alignment     = si->alignment;
649   // Record where normalized section is.
650   si->normalizedSectionIndex = file.sections.size()-1;
651 }
652
653 void Util::copySectionContent(NormalizedFile &file) {
654   const bool r = (_ctx.outputMachOType() == llvm::MachO::MH_OBJECT);
655
656   // Utility function for ArchHandler to find address of atom in output file.
657   auto addrForAtom = [&] (const Atom &atom) -> uint64_t {
658     auto pos = _atomToAddress.find(&atom);
659     assert(pos != _atomToAddress.end());
660     return pos->second;
661   };
662
663   auto sectionAddrForAtom = [&] (const Atom &atom) -> uint64_t {
664     for (const SectionInfo *sectInfo : _sectionInfos)
665       for (const AtomInfo &atomInfo : sectInfo->atomsAndOffsets)
666         if (atomInfo.atom == &atom)
667           return sectInfo->address;
668     llvm_unreachable("atom not assigned to section");
669   };
670
671   for (SectionInfo *si : _sectionInfos) {
672     Section *normSect = &file.sections[si->normalizedSectionIndex];
673     if (isZeroFillSection(si->type)) {
674       const uint8_t *empty = nullptr;
675       normSect->content = llvm::makeArrayRef(empty, si->size);
676       continue;
677     }
678     // Copy content from atoms to content buffer for section.
679     llvm::MutableArrayRef<uint8_t> sectionContent;
680     if (si->size) {
681       uint8_t *sectContent = file.ownedAllocations.Allocate<uint8_t>(si->size);
682       sectionContent = llvm::MutableArrayRef<uint8_t>(sectContent, si->size);
683       normSect->content = sectionContent;
684     }
685     for (AtomInfo &ai : si->atomsAndOffsets) {
686       if (!ai.atom->size()) {
687         assert(ai.atom->begin() == ai.atom->end() &&
688                "Cannot have references without content");
689         continue;
690       }
691       auto atomContent = sectionContent.slice(ai.offsetInSection,
692                                               ai.atom->size());
693       _archHandler.generateAtomContent(*ai.atom, r, addrForAtom,
694                                        sectionAddrForAtom, _ctx.baseAddress(),
695                                        atomContent);
696     }
697   }
698 }
699
700 void Util::copySectionInfo(NormalizedFile &file) {
701   file.sections.reserve(_sectionInfos.size());
702   // Write sections grouped by segment.
703   for (SegmentInfo *sgi : _segmentInfos) {
704     for (SectionInfo *si : sgi->sections) {
705       appendSection(si, file);
706     }
707   }
708 }
709
710 void Util::updateSectionInfo(NormalizedFile &file) {
711   file.sections.reserve(_sectionInfos.size());
712   // sections grouped by segment.
713   for (SegmentInfo *sgi : _segmentInfos) {
714     Segment *normSeg = &file.segments[sgi->normalizedSegmentIndex];
715     normSeg->address = sgi->address;
716     normSeg->size = sgi->size;
717     for (SectionInfo *si : sgi->sections) {
718       Section *normSect = &file.sections[si->normalizedSectionIndex];
719       normSect->address = si->address;
720     }
721   }
722 }
723
724 void Util::copyEntryPointAddress(NormalizedFile &nFile) {
725   if (!_entryAtom) {
726     nFile.entryAddress = 0;
727     return;
728   }
729
730   if (_ctx.outputTypeHasEntry()) {
731     if (_archHandler.isThumbFunction(*_entryAtom))
732       nFile.entryAddress = (_atomToAddress[_entryAtom] | 1);
733     else
734       nFile.entryAddress = _atomToAddress[_entryAtom];
735   }
736 }
737
738 void Util::buildAtomToAddressMap() {
739   DEBUG_WITH_TYPE("WriterMachO-address", llvm::dbgs()
740                    << "assign atom addresses:\n");
741   const bool lookForEntry = _ctx.outputTypeHasEntry();
742   for (SectionInfo *sect : _sectionInfos) {
743     for (const AtomInfo &info : sect->atomsAndOffsets) {
744       _atomToAddress[info.atom] = sect->address + info.offsetInSection;
745       if (lookForEntry && (info.atom->contentType() == DefinedAtom::typeCode) &&
746           (info.atom->size() != 0) &&
747           info.atom->name() == _ctx.entrySymbolName()) {
748         _entryAtom = info.atom;
749       }
750       DEBUG_WITH_TYPE("WriterMachO-address", llvm::dbgs()
751                       << "   address="
752                       << llvm::format("0x%016X", _atomToAddress[info.atom])
753                       << llvm::format("    0x%09lX", info.atom)
754                       << ", file=#"
755                       << info.atom->file().ordinal()
756                       << ", atom=#"
757                       << info.atom->ordinal()
758                       << ", name="
759                       << info.atom->name()
760                       << ", type="
761                       << info.atom->contentType()
762                       << "\n");
763     }
764   }
765   DEBUG_WITH_TYPE("WriterMachO-address", llvm::dbgs()
766                   << "assign header alias atom addresses:\n");
767   for (const Atom *atom : _machHeaderAliasAtoms) {
768     _atomToAddress[atom] = _ctx.baseAddress();
769 #ifndef NDEBUG
770     if (auto *definedAtom = dyn_cast<DefinedAtom>(atom)) {
771       DEBUG_WITH_TYPE("WriterMachO-address", llvm::dbgs()
772                       << "   address="
773                       << llvm::format("0x%016X", _atomToAddress[atom])
774                       << llvm::format("    0x%09lX", atom)
775                       << ", file=#"
776                       << definedAtom->file().ordinal()
777                       << ", atom=#"
778                       << definedAtom->ordinal()
779                       << ", name="
780                       << definedAtom->name()
781                       << ", type="
782                       << definedAtom->contentType()
783                       << "\n");
784     } else {
785       DEBUG_WITH_TYPE("WriterMachO-address", llvm::dbgs()
786                       << "   address="
787                       << llvm::format("0x%016X", _atomToAddress[atom])
788                       << " atom=" << atom
789                       << " name=" << atom->name() << "\n");
790     }
791 #endif
792   }
793 }
794
795 llvm::Error Util::synthesizeDebugNotes(NormalizedFile &file) {
796
797   // Bail out early if we don't need to generate a debug map.
798   if (_ctx.debugInfoMode() == MachOLinkingContext::DebugInfoMode::noDebugMap)
799     return llvm::Error::success();
800
801   std::vector<const DefinedAtom*> atomsNeedingDebugNotes;
802   std::set<const mach_o::MachOFile*> filesWithStabs;
803   bool objFileHasDwarf = false;
804   const File *objFile = nullptr;
805
806   for (SectionInfo *sect : _sectionInfos) {
807     for (const AtomInfo &info : sect->atomsAndOffsets) {
808       if (const DefinedAtom *atom = dyn_cast<DefinedAtom>(info.atom)) {
809
810         // FIXME: No stabs/debug-notes for symbols that wouldn't be in the
811         //        symbol table.
812         // FIXME: No stabs/debug-notes for kernel dtrace probes.
813
814         if (atom->contentType() == DefinedAtom::typeCFI ||
815             atom->contentType() == DefinedAtom::typeCString)
816           continue;
817
818         // Whenever we encounter a new file, update the 'objfileHasDwarf' flag.
819         if (&info.atom->file() != objFile) {
820           objFileHasDwarf = false;
821           if (const mach_o::MachOFile *atomFile =
822               dyn_cast<mach_o::MachOFile>(&info.atom->file())) {
823             if (atomFile->debugInfo()) {
824               if (isa<mach_o::DwarfDebugInfo>(atomFile->debugInfo()))
825                 objFileHasDwarf = true;
826               else if (isa<mach_o::StabsDebugInfo>(atomFile->debugInfo()))
827                 filesWithStabs.insert(atomFile);
828             }
829           }
830         }
831
832         // If this atom is from a file that needs dwarf, add it to the list.
833         if (objFileHasDwarf)
834           atomsNeedingDebugNotes.push_back(info.atom);
835       }
836     }
837   }
838
839   // Sort atoms needing debug notes by file ordinal, then atom ordinal.
840   std::sort(atomsNeedingDebugNotes.begin(), atomsNeedingDebugNotes.end(),
841             [](const DefinedAtom *lhs, const DefinedAtom *rhs) {
842               if (lhs->file().ordinal() != rhs->file().ordinal())
843                 return (lhs->file().ordinal() < rhs->file().ordinal());
844               return (lhs->ordinal() < rhs->ordinal());
845             });
846
847   // FIXME: Handle <rdar://problem/17689030>: Add -add_ast_path option to \
848   //        linker which add N_AST stab entry to output
849   // See OutputFile::synthesizeDebugNotes in ObjectFile.cpp in ld64.
850
851   StringRef oldFileName = "";
852   StringRef oldDirPath = "";
853   bool wroteStartSO = false;
854   std::unordered_set<std::string> seenFiles;
855   for (const DefinedAtom *atom : atomsNeedingDebugNotes) {
856     const auto &atomFile = cast<mach_o::MachOFile>(atom->file());
857     assert(dyn_cast_or_null<lld::mach_o::DwarfDebugInfo>(atomFile.debugInfo())
858            && "file for atom needing debug notes does not contain dwarf");
859     auto &dwarf = cast<lld::mach_o::DwarfDebugInfo>(*atomFile.debugInfo());
860
861     auto &tu = dwarf.translationUnitSource();
862     StringRef newFileName = tu.name;
863     StringRef newDirPath = tu.path;
864
865     // Add an SO whenever the TU source file changes.
866     if (newFileName != oldFileName || newDirPath != oldDirPath) {
867       // Translation unit change, emit ending SO
868       if (oldFileName != "")
869         _stabs.push_back(mach_o::Stab(nullptr, N_SO, 1, 0, 0, ""));
870
871       oldFileName = newFileName;
872       oldDirPath = newDirPath;
873
874       // If newDirPath doesn't end with a '/' we need to add one:
875       if (newDirPath.back() != '/') {
876         char *p =
877           file.ownedAllocations.Allocate<char>(newDirPath.size() + 2);
878         memcpy(p, newDirPath.data(), newDirPath.size());
879         p[newDirPath.size()] = '/';
880         p[newDirPath.size() + 1] = '\0';
881         newDirPath = p;
882       }
883
884       // New translation unit, emit start SOs:
885       _stabs.push_back(mach_o::Stab(nullptr, N_SO, 0, 0, 0, newDirPath));
886       _stabs.push_back(mach_o::Stab(nullptr, N_SO, 0, 0, 0, newFileName));
887
888       // Synthesize OSO for start of file.
889       char *fullPath = nullptr;
890       {
891         SmallString<1024> pathBuf(atomFile.path());
892         if (auto EC = llvm::sys::fs::make_absolute(pathBuf))
893           return llvm::errorCodeToError(EC);
894         fullPath = file.ownedAllocations.Allocate<char>(pathBuf.size() + 1);
895         memcpy(fullPath, pathBuf.c_str(), pathBuf.size() + 1);
896       }
897
898       // Get mod time.
899       uint32_t modTime = 0;
900       llvm::sys::fs::file_status stat;
901       if (!llvm::sys::fs::status(fullPath, stat))
902         if (llvm::sys::fs::exists(stat))
903           modTime = llvm::sys::toTimeT(stat.getLastModificationTime());
904
905       _stabs.push_back(mach_o::Stab(nullptr, N_OSO, _ctx.getCPUSubType(), 1,
906                                     modTime, fullPath));
907       // <rdar://problem/6337329> linker should put cpusubtype in n_sect field
908       // of nlist entry for N_OSO debug note entries.
909       wroteStartSO = true;
910     }
911
912     if (atom->contentType() == DefinedAtom::typeCode) {
913       // Synthesize BNSYM and start FUN stabs.
914       _stabs.push_back(mach_o::Stab(atom, N_BNSYM, 1, 0, 0, ""));
915       _stabs.push_back(mach_o::Stab(atom, N_FUN, 1, 0, 0, atom->name()));
916       // Synthesize any SOL stabs needed
917       // FIXME: add SOL stabs.
918       _stabs.push_back(mach_o::Stab(nullptr, N_FUN, 0, 0,
919                                     atom->rawContent().size(), ""));
920       _stabs.push_back(mach_o::Stab(nullptr, N_ENSYM, 1, 0,
921                                     atom->rawContent().size(), ""));
922     } else {
923       if (atom->scope() == Atom::scopeTranslationUnit)
924         _stabs.push_back(mach_o::Stab(atom, N_STSYM, 1, 0, 0, atom->name()));
925       else
926         _stabs.push_back(mach_o::Stab(nullptr, N_GSYM, 1, 0, 0, atom->name()));
927     }
928   }
929
930   // Emit ending SO if necessary.
931   if (wroteStartSO)
932     _stabs.push_back(mach_o::Stab(nullptr, N_SO, 1, 0, 0, ""));
933
934   // Copy any stabs from .o file.
935   for (const auto *objFile : filesWithStabs) {
936     const auto &stabsList =
937       cast<mach_o::StabsDebugInfo>(objFile->debugInfo())->stabs();
938     for (auto &stab : stabsList) {
939       // FIXME: Drop stabs whose atoms have been dead-stripped.
940       _stabs.push_back(stab);
941     }
942   }
943
944   return llvm::Error::success();
945 }
946
947 uint16_t Util::descBits(const DefinedAtom* atom) {
948   uint16_t desc = 0;
949   switch (atom->merge()) {
950   case lld::DefinedAtom::mergeNo:
951   case lld::DefinedAtom::mergeAsTentative:
952     break;
953   case lld::DefinedAtom::mergeAsWeak:
954   case lld::DefinedAtom::mergeAsWeakAndAddressUsed:
955     desc |= N_WEAK_DEF;
956     break;
957   case lld::DefinedAtom::mergeSameNameAndSize:
958   case lld::DefinedAtom::mergeByLargestSection:
959   case lld::DefinedAtom::mergeByContent:
960     llvm_unreachable("Unsupported DefinedAtom::merge()");
961     break;
962   }
963   if (atom->contentType() == lld::DefinedAtom::typeResolver)
964     desc |= N_SYMBOL_RESOLVER;
965   if (atom->contentType() == lld::DefinedAtom::typeMachHeader)
966     desc |= REFERENCED_DYNAMICALLY;
967   if (_archHandler.isThumbFunction(*atom))
968     desc |= N_ARM_THUMB_DEF;
969   if (atom->deadStrip() == DefinedAtom::deadStripNever &&
970       _ctx.outputMachOType() == llvm::MachO::MH_OBJECT) {
971     if ((atom->contentType() != DefinedAtom::typeInitializerPtr)
972      && (atom->contentType() != DefinedAtom::typeTerminatorPtr))
973     desc |= N_NO_DEAD_STRIP;
974   }
975   return desc;
976 }
977
978 bool Util::AtomSorter::operator()(const AtomAndIndex &left,
979                                   const AtomAndIndex &right) {
980   return (left.atom->name().compare(right.atom->name()) < 0);
981 }
982
983 llvm::Error Util::getSymbolTableRegion(const DefinedAtom* atom,
984                                        bool &inGlobalsRegion,
985                                        SymbolScope &scope) {
986   bool rMode = (_ctx.outputMachOType() == llvm::MachO::MH_OBJECT);
987   switch (atom->scope()) {
988   case Atom::scopeTranslationUnit:
989     scope = 0;
990     inGlobalsRegion = false;
991     return llvm::Error::success();
992   case Atom::scopeLinkageUnit:
993     if ((_ctx.exportMode() == MachOLinkingContext::ExportMode::whiteList) &&
994         _ctx.exportSymbolNamed(atom->name())) {
995       return llvm::make_error<GenericError>(
996                           Twine("cannot export hidden symbol ") + atom->name());
997     }
998     if (rMode) {
999       if (_ctx.keepPrivateExterns()) {
1000         // -keep_private_externs means keep in globals region as N_PEXT.
1001         scope = N_PEXT | N_EXT;
1002         inGlobalsRegion = true;
1003         return llvm::Error::success();
1004       }
1005     }
1006     // scopeLinkageUnit symbols are no longer global once linked.
1007     scope = N_PEXT;
1008     inGlobalsRegion = false;
1009     return llvm::Error::success();
1010   case Atom::scopeGlobal:
1011     if (_ctx.exportRestrictMode()) {
1012       if (_ctx.exportSymbolNamed(atom->name())) {
1013         scope = N_EXT;
1014         inGlobalsRegion = true;
1015         return llvm::Error::success();
1016       } else {
1017         scope = N_PEXT;
1018         inGlobalsRegion = false;
1019         return llvm::Error::success();
1020       }
1021     } else {
1022       scope = N_EXT;
1023       inGlobalsRegion = true;
1024       return llvm::Error::success();
1025     }
1026     break;
1027   }
1028   llvm_unreachable("atom->scope() unknown enum value");
1029 }
1030
1031
1032
1033 llvm::Error Util::addSymbols(const lld::File &atomFile,
1034                              NormalizedFile &file) {
1035   bool rMode = (_ctx.outputMachOType() == llvm::MachO::MH_OBJECT);
1036   // Mach-O symbol table has four regions: stabs, locals, globals, undefs.
1037
1038   // Add all stabs.
1039   for (auto &stab : _stabs) {
1040     Symbol sym;
1041     sym.type = static_cast<NListType>(stab.type);
1042     sym.scope = 0;
1043     sym.sect = stab.other;
1044     sym.desc = stab.desc;
1045     if (stab.atom)
1046       sym.value = _atomToAddress[stab.atom];
1047     else
1048       sym.value = stab.value;
1049     sym.name = stab.str;
1050     file.stabsSymbols.push_back(sym);
1051   }
1052
1053   // Add all local (non-global) symbols in address order
1054   std::vector<AtomAndIndex> globals;
1055   globals.reserve(512);
1056   for (SectionInfo *sect : _sectionInfos) {
1057     for (const AtomInfo &info : sect->atomsAndOffsets) {
1058       const DefinedAtom *atom = info.atom;
1059       if (!atom->name().empty()) {
1060         SymbolScope symbolScope;
1061         bool inGlobalsRegion;
1062         if (auto ec = getSymbolTableRegion(atom, inGlobalsRegion, symbolScope)){
1063           return ec;
1064         }
1065         if (inGlobalsRegion) {
1066           AtomAndIndex ai = { atom, sect->finalSectionIndex, symbolScope };
1067           globals.push_back(ai);
1068         } else {
1069           Symbol sym;
1070           sym.name  = atom->name();
1071           sym.type  = N_SECT;
1072           sym.scope = symbolScope;
1073           sym.sect  = sect->finalSectionIndex;
1074           sym.desc  = descBits(atom);
1075           sym.value = _atomToAddress[atom];
1076           _atomToSymbolIndex[atom] = file.localSymbols.size();
1077           file.localSymbols.push_back(sym);
1078         }
1079       } else if (rMode && _archHandler.needsLocalSymbolInRelocatableFile(atom)){
1080         // Create 'Lxxx' labels for anonymous atoms if archHandler says so.
1081         static unsigned tempNum = 1;
1082         char tmpName[16];
1083         sprintf(tmpName, "L%04u", tempNum++);
1084         StringRef tempRef(tmpName);
1085         Symbol sym;
1086         sym.name  = tempRef.copy(file.ownedAllocations);
1087         sym.type  = N_SECT;
1088         sym.scope = 0;
1089         sym.sect  = sect->finalSectionIndex;
1090         sym.desc  = 0;
1091         sym.value = _atomToAddress[atom];
1092         _atomToSymbolIndex[atom] = file.localSymbols.size();
1093         file.localSymbols.push_back(sym);
1094       }
1095     }
1096   }
1097
1098   // Sort global symbol alphabetically, then add to symbol table.
1099   std::sort(globals.begin(), globals.end(), AtomSorter());
1100   const uint32_t globalStartIndex = file.localSymbols.size();
1101   for (AtomAndIndex &ai : globals) {
1102     Symbol sym;
1103     sym.name  = ai.atom->name();
1104     sym.type  = N_SECT;
1105     sym.scope = ai.scope;
1106     sym.sect  = ai.index;
1107     sym.desc  = descBits(static_cast<const DefinedAtom*>(ai.atom));
1108     sym.value = _atomToAddress[ai.atom];
1109     _atomToSymbolIndex[ai.atom] = globalStartIndex + file.globalSymbols.size();
1110     file.globalSymbols.push_back(sym);
1111   }
1112
1113   // Sort undefined symbol alphabetically, then add to symbol table.
1114   std::vector<AtomAndIndex> undefs;
1115   undefs.reserve(128);
1116   for (const UndefinedAtom *atom : atomFile.undefined()) {
1117     AtomAndIndex ai = { atom, 0, N_EXT };
1118     undefs.push_back(ai);
1119   }
1120   for (const SharedLibraryAtom *atom : atomFile.sharedLibrary()) {
1121     AtomAndIndex ai = { atom, 0, N_EXT };
1122     undefs.push_back(ai);
1123   }
1124   std::sort(undefs.begin(), undefs.end(), AtomSorter());
1125   const uint32_t start = file.globalSymbols.size() + file.localSymbols.size();
1126   for (AtomAndIndex &ai : undefs) {
1127     Symbol sym;
1128     uint16_t desc = 0;
1129     if (!rMode) {
1130       uint8_t ordinal = 0;
1131       if (!_ctx.useFlatNamespace())
1132         ordinal = dylibOrdinal(dyn_cast<SharedLibraryAtom>(ai.atom));
1133       llvm::MachO::SET_LIBRARY_ORDINAL(desc, ordinal);
1134     }
1135     sym.name  = ai.atom->name();
1136     sym.type  = N_UNDF;
1137     sym.scope = ai.scope;
1138     sym.sect  = 0;
1139     sym.desc  = desc;
1140     sym.value = 0;
1141     _atomToSymbolIndex[ai.atom] = file.undefinedSymbols.size() + start;
1142     file.undefinedSymbols.push_back(sym);
1143   }
1144
1145   return llvm::Error::success();
1146 }
1147
1148 const Atom *Util::targetOfLazyPointer(const DefinedAtom *lpAtom) {
1149   for (const Reference *ref : *lpAtom) {
1150     if (_archHandler.isLazyPointer(*ref)) {
1151       return ref->target();
1152     }
1153   }
1154   return nullptr;
1155 }
1156
1157 const Atom *Util::targetOfStub(const DefinedAtom *stubAtom) {
1158   for (const Reference *ref : *stubAtom) {
1159     if (const Atom *ta = ref->target()) {
1160       if (const DefinedAtom *lpAtom = dyn_cast<DefinedAtom>(ta)) {
1161         const Atom *target = targetOfLazyPointer(lpAtom);
1162         if (target)
1163           return target;
1164       }
1165     }
1166   }
1167   return nullptr;
1168 }
1169
1170 void Util::addIndirectSymbols(const lld::File &atomFile, NormalizedFile &file) {
1171   for (SectionInfo *si : _sectionInfos) {
1172     Section &normSect = file.sections[si->normalizedSectionIndex];
1173     switch (si->type) {
1174     case llvm::MachO::S_NON_LAZY_SYMBOL_POINTERS:
1175       for (const AtomInfo &info : si->atomsAndOffsets) {
1176         bool foundTarget = false;
1177         for (const Reference *ref : *info.atom) {
1178           const Atom *target = ref->target();
1179           if (target) {
1180             if (isa<const SharedLibraryAtom>(target)) {
1181               uint32_t index = _atomToSymbolIndex[target];
1182               normSect.indirectSymbols.push_back(index);
1183               foundTarget = true;
1184             } else {
1185               normSect.indirectSymbols.push_back(
1186                                             llvm::MachO::INDIRECT_SYMBOL_LOCAL);
1187             }
1188           }
1189         }
1190         if (!foundTarget) {
1191           normSect.indirectSymbols.push_back(
1192                                              llvm::MachO::INDIRECT_SYMBOL_ABS);
1193         }
1194       }
1195       break;
1196     case llvm::MachO::S_LAZY_SYMBOL_POINTERS:
1197       for (const AtomInfo &info : si->atomsAndOffsets) {
1198         const Atom *target = targetOfLazyPointer(info.atom);
1199         if (target) {
1200           uint32_t index = _atomToSymbolIndex[target];
1201           normSect.indirectSymbols.push_back(index);
1202         }
1203       }
1204       break;
1205     case llvm::MachO::S_SYMBOL_STUBS:
1206       for (const AtomInfo &info : si->atomsAndOffsets) {
1207         const Atom *target = targetOfStub(info.atom);
1208         if (target) {
1209           uint32_t index = _atomToSymbolIndex[target];
1210           normSect.indirectSymbols.push_back(index);
1211         }
1212       }
1213       break;
1214     default:
1215       break;
1216     }
1217   }
1218 }
1219
1220 void Util::addDependentDylibs(const lld::File &atomFile,
1221                               NormalizedFile &nFile) {
1222   // Scan all imported symbols and build up list of dylibs they are from.
1223   int ordinal = 1;
1224   for (const auto *dylib : _ctx.allDylibs()) {
1225     DylibPathToInfo::iterator pos = _dylibInfo.find(dylib->installName());
1226     if (pos == _dylibInfo.end()) {
1227       DylibInfo info;
1228       bool flatNamespaceAtom = dylib == _ctx.flatNamespaceFile();
1229
1230       // If we're in -flat_namespace mode (or this atom came from the flat
1231       // namespace file under -undefined dynamic_lookup) then use the flat
1232       // lookup ordinal.
1233       if (flatNamespaceAtom || _ctx.useFlatNamespace())
1234         info.ordinal = BIND_SPECIAL_DYLIB_FLAT_LOOKUP;
1235       else
1236         info.ordinal = ordinal++;
1237       info.hasWeak = false;
1238       info.hasNonWeak = !info.hasWeak;
1239       _dylibInfo[dylib->installName()] = info;
1240
1241       // Unless this was a flat_namespace atom, record the source dylib.
1242       if (!flatNamespaceAtom) {
1243         DependentDylib depInfo;
1244         depInfo.path = dylib->installName();
1245         depInfo.kind = llvm::MachO::LC_LOAD_DYLIB;
1246         depInfo.currentVersion = _ctx.dylibCurrentVersion(dylib->path());
1247         depInfo.compatVersion = _ctx.dylibCompatVersion(dylib->path());
1248         nFile.dependentDylibs.push_back(depInfo);
1249       }
1250     } else {
1251       pos->second.hasWeak = false;
1252       pos->second.hasNonWeak = !pos->second.hasWeak;
1253     }
1254   }
1255   // Automatically weak link dylib in which all symbols are weak (canBeNull).
1256   for (DependentDylib &dep : nFile.dependentDylibs) {
1257     DylibInfo &info = _dylibInfo[dep.path];
1258     if (info.hasWeak && !info.hasNonWeak)
1259       dep.kind = llvm::MachO::LC_LOAD_WEAK_DYLIB;
1260     else if (_ctx.isUpwardDylib(dep.path))
1261       dep.kind = llvm::MachO::LC_LOAD_UPWARD_DYLIB;
1262   }
1263 }
1264
1265 int Util::dylibOrdinal(const SharedLibraryAtom *sa) {
1266   return _dylibInfo[sa->loadName()].ordinal;
1267 }
1268
1269 void Util::segIndexForSection(const SectionInfo *sect, uint8_t &segmentIndex,
1270                                                   uint64_t &segmentStartAddr) {
1271   segmentIndex = 0;
1272   for (const SegmentInfo *seg : _segmentInfos) {
1273     if ((seg->address <= sect->address)
1274       && (seg->address+seg->size >= sect->address+sect->size)) {
1275       segmentStartAddr = seg->address;
1276       return;
1277     }
1278     ++segmentIndex;
1279   }
1280   llvm_unreachable("section not in any segment");
1281 }
1282
1283 uint32_t Util::sectionIndexForAtom(const Atom *atom) {
1284   uint64_t address = _atomToAddress[atom];
1285   for (const SectionInfo *si : _sectionInfos) {
1286     if ((si->address <= address) && (address < si->address+si->size))
1287       return si->finalSectionIndex;
1288   }
1289   llvm_unreachable("atom not in any section");
1290 }
1291
1292 void Util::addSectionRelocs(const lld::File &, NormalizedFile &file) {
1293   if (_ctx.outputMachOType() != llvm::MachO::MH_OBJECT)
1294     return;
1295
1296   // Utility function for ArchHandler to find symbol index for an atom.
1297   auto symIndexForAtom = [&] (const Atom &atom) -> uint32_t {
1298     auto pos = _atomToSymbolIndex.find(&atom);
1299     assert(pos != _atomToSymbolIndex.end());
1300     return pos->second;
1301   };
1302
1303   // Utility function for ArchHandler to find section index for an atom.
1304   auto sectIndexForAtom = [&] (const Atom &atom) -> uint32_t {
1305     return sectionIndexForAtom(&atom);
1306   };
1307
1308   // Utility function for ArchHandler to find address of atom in output file.
1309   auto addressForAtom = [&] (const Atom &atom) -> uint64_t {
1310     auto pos = _atomToAddress.find(&atom);
1311     assert(pos != _atomToAddress.end());
1312     return pos->second;
1313   };
1314
1315   for (SectionInfo *si : _sectionInfos) {
1316     Section &normSect = file.sections[si->normalizedSectionIndex];
1317     for (const AtomInfo &info : si->atomsAndOffsets) {
1318       const DefinedAtom *atom = info.atom;
1319       for (const Reference *ref : *atom) {
1320         // Skip emitting relocs for sections which are always able to be
1321         // implicitly regenerated and where the relocation targets an address
1322         // which is defined.
1323         if (si->relocsToDefinedCanBeImplicit && isa<DefinedAtom>(ref->target()))
1324           continue;
1325         _archHandler.appendSectionRelocations(*atom, info.offsetInSection, *ref,
1326                                               symIndexForAtom,
1327                                               sectIndexForAtom,
1328                                               addressForAtom,
1329                                               normSect.relocations);
1330       }
1331     }
1332   }
1333 }
1334
1335 void Util::addFunctionStarts(const lld::File &, NormalizedFile &file) {
1336   if (!_ctx.generateFunctionStartsLoadCommand())
1337     return;
1338   file.functionStarts.reserve(8192);
1339   // Delta compress function starts, starting with the mach header symbol.
1340   const uint64_t badAddress = ~0ULL;
1341   uint64_t addr = badAddress;
1342   for (SectionInfo *si : _sectionInfos) {
1343     for (const AtomInfo &info : si->atomsAndOffsets) {
1344       auto type = info.atom->contentType();
1345       if (type == DefinedAtom::typeMachHeader) {
1346         addr = _atomToAddress[info.atom];
1347         continue;
1348       }
1349       if (type != DefinedAtom::typeCode)
1350         continue;
1351       assert(addr != badAddress && "Missing mach header symbol");
1352       // Skip atoms which have 0 size.  This is so that LC_FUNCTION_STARTS
1353       // can't spill in to the next section.
1354       if (!info.atom->size())
1355         continue;
1356       uint64_t nextAddr = _atomToAddress[info.atom];
1357       if (_archHandler.isThumbFunction(*info.atom))
1358         nextAddr |= 1;
1359       uint64_t delta = nextAddr - addr;
1360       if (delta) {
1361         ByteBuffer buffer;
1362         buffer.append_uleb128(delta);
1363         file.functionStarts.insert(file.functionStarts.end(), buffer.bytes(),
1364                                    buffer.bytes() + buffer.size());
1365       }
1366       addr = nextAddr;
1367     }
1368   }
1369
1370   // Null terminate, and pad to pointer size for this arch.
1371   file.functionStarts.push_back(0);
1372
1373   auto size = file.functionStarts.size();
1374   for (unsigned i = size, e = llvm::alignTo(size, _ctx.is64Bit() ? 8 : 4);
1375        i != e; ++i)
1376     file.functionStarts.push_back(0);
1377 }
1378
1379 void Util::buildDataInCodeArray(const lld::File &, NormalizedFile &file) {
1380   if (!_ctx.generateDataInCodeLoadCommand())
1381     return;
1382   for (SectionInfo *si : _sectionInfos) {
1383     for (const AtomInfo &info : si->atomsAndOffsets) {
1384       // Atoms that contain data-in-code have "transition" references
1385       // which mark a point where the embedded data starts of ends.
1386       // This needs to be converted to the mach-o format which is an array
1387       // of data-in-code ranges.
1388       uint32_t startOffset = 0;
1389       DataRegionType mode = DataRegionType(0);
1390       for (const Reference *ref : *info.atom) {
1391         if (ref->kindNamespace() != Reference::KindNamespace::mach_o)
1392           continue;
1393         if (_archHandler.isDataInCodeTransition(ref->kindValue())) {
1394           DataRegionType nextMode = (DataRegionType)ref->addend();
1395           if (mode != nextMode) {
1396             if (mode != 0) {
1397               // Found end data range, so make range entry.
1398               DataInCode entry;
1399               entry.offset = si->address + info.offsetInSection + startOffset;
1400               entry.length = ref->offsetInAtom() - startOffset;
1401               entry.kind   = mode;
1402               file.dataInCode.push_back(entry);
1403             }
1404           }
1405           mode = nextMode;
1406           startOffset = ref->offsetInAtom();
1407         }
1408       }
1409       if (mode != 0) {
1410         // Function ends with data (no end transition).
1411         DataInCode entry;
1412         entry.offset = si->address + info.offsetInSection + startOffset;
1413         entry.length = info.atom->size() - startOffset;
1414         entry.kind   = mode;
1415         file.dataInCode.push_back(entry);
1416       }
1417     }
1418   }
1419 }
1420
1421 void Util::addRebaseAndBindingInfo(const lld::File &atomFile,
1422                                                         NormalizedFile &nFile) {
1423   if (_ctx.outputMachOType() == llvm::MachO::MH_OBJECT)
1424     return;
1425
1426   uint8_t segmentIndex;
1427   uint64_t segmentStartAddr;
1428   uint32_t offsetInBindInfo = 0;
1429
1430   for (SectionInfo *sect : _sectionInfos) {
1431     segIndexForSection(sect, segmentIndex, segmentStartAddr);
1432     for (const AtomInfo &info : sect->atomsAndOffsets) {
1433       const DefinedAtom *atom = info.atom;
1434       for (const Reference *ref : *atom) {
1435         uint64_t segmentOffset = _atomToAddress[atom] + ref->offsetInAtom()
1436                                 - segmentStartAddr;
1437         const Atom* targ = ref->target();
1438         if (_archHandler.isPointer(*ref)) {
1439           // A pointer to a DefinedAtom requires rebasing.
1440           if (isa<DefinedAtom>(targ)) {
1441             RebaseLocation rebase;
1442             rebase.segIndex = segmentIndex;
1443             rebase.segOffset = segmentOffset;
1444             rebase.kind = llvm::MachO::REBASE_TYPE_POINTER;
1445             nFile.rebasingInfo.push_back(rebase);
1446           }
1447           // A pointer to an SharedLibraryAtom requires binding.
1448           if (const SharedLibraryAtom *sa = dyn_cast<SharedLibraryAtom>(targ)) {
1449             BindLocation bind;
1450             bind.segIndex = segmentIndex;
1451             bind.segOffset = segmentOffset;
1452             bind.kind = llvm::MachO::BIND_TYPE_POINTER;
1453             bind.canBeNull = sa->canBeNullAtRuntime();
1454             bind.ordinal = dylibOrdinal(sa);
1455             bind.symbolName = targ->name();
1456             bind.addend = ref->addend();
1457             nFile.bindingInfo.push_back(bind);
1458           }
1459         }
1460         else if (_archHandler.isLazyPointer(*ref)) {
1461           BindLocation bind;
1462           if (const SharedLibraryAtom *sa = dyn_cast<SharedLibraryAtom>(targ)) {
1463             bind.ordinal = dylibOrdinal(sa);
1464           } else {
1465             bind.ordinal = llvm::MachO::BIND_SPECIAL_DYLIB_SELF;
1466           }
1467           bind.segIndex = segmentIndex;
1468           bind.segOffset = segmentOffset;
1469           bind.kind = llvm::MachO::BIND_TYPE_POINTER;
1470           bind.canBeNull = false; //sa->canBeNullAtRuntime();
1471           bind.symbolName = targ->name();
1472           bind.addend = ref->addend();
1473           nFile.lazyBindingInfo.push_back(bind);
1474
1475           // Now that we know the segmentOffset and the ordinal attribute,
1476           // we can fix the helper's code
1477
1478           fixLazyReferenceImm(atom, offsetInBindInfo, nFile);
1479
1480           // 5 bytes for opcodes + variable sizes (target name + \0 and offset
1481           // encode's size)
1482           offsetInBindInfo +=
1483               6 + targ->name().size() + llvm::getULEB128Size(bind.segOffset);
1484           if (bind.ordinal > BIND_IMMEDIATE_MASK)
1485             offsetInBindInfo += llvm::getULEB128Size(bind.ordinal);
1486         }
1487       }
1488     }
1489   }
1490 }
1491
1492 void Util::fixLazyReferenceImm(const DefinedAtom *atom, uint32_t offset,
1493                                NormalizedFile &file) {
1494   for (const auto &ref : *atom) {
1495     const DefinedAtom *da = dyn_cast<DefinedAtom>(ref->target());
1496     if (da == nullptr)
1497       return;
1498
1499     const Reference *helperRef = nullptr;
1500     for (const Reference *hr : *da) {
1501       if (hr->kindValue() == _archHandler.lazyImmediateLocationKind()) {
1502         helperRef = hr;
1503         break;
1504       }
1505     }
1506     if (helperRef == nullptr)
1507       continue;
1508
1509     // TODO: maybe get the fixed atom content from _archHandler ?
1510     for (SectionInfo *sectInfo : _sectionInfos) {
1511       for (const AtomInfo &atomInfo : sectInfo->atomsAndOffsets) {
1512         if (atomInfo.atom == helperRef->target()) {
1513           auto sectionContent =
1514               file.sections[sectInfo->normalizedSectionIndex].content;
1515           uint8_t *rawb =
1516               file.ownedAllocations.Allocate<uint8_t>(sectionContent.size());
1517           llvm::MutableArrayRef<uint8_t> newContent{rawb,
1518                                                     sectionContent.size()};
1519           std::copy(sectionContent.begin(), sectionContent.end(),
1520                     newContent.begin());
1521           llvm::support::ulittle32_t *loc =
1522               reinterpret_cast<llvm::support::ulittle32_t *>(
1523                   &newContent[atomInfo.offsetInSection +
1524                               helperRef->offsetInAtom()]);
1525           *loc = offset;
1526           file.sections[sectInfo->normalizedSectionIndex].content = newContent;
1527         }
1528       }
1529     }
1530   }
1531 }
1532
1533 void Util::addExportInfo(const lld::File &atomFile, NormalizedFile &nFile) {
1534   if (_ctx.outputMachOType() == llvm::MachO::MH_OBJECT)
1535     return;
1536
1537   for (SectionInfo *sect : _sectionInfos) {
1538     for (const AtomInfo &info : sect->atomsAndOffsets) {
1539       const DefinedAtom *atom = info.atom;
1540       if (atom->scope() != Atom::scopeGlobal)
1541         continue;
1542       if (_ctx.exportRestrictMode()) {
1543         if (!_ctx.exportSymbolNamed(atom->name()))
1544           continue;
1545       }
1546       Export exprt;
1547       exprt.name = atom->name();
1548       exprt.offset = _atomToAddress[atom] - _ctx.baseAddress();
1549       exprt.kind = EXPORT_SYMBOL_FLAGS_KIND_REGULAR;
1550       if (atom->merge() == DefinedAtom::mergeAsWeak)
1551         exprt.flags = EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION;
1552       else
1553         exprt.flags = 0;
1554       exprt.otherOffset = 0;
1555       exprt.otherName = StringRef();
1556       nFile.exportInfo.push_back(exprt);
1557     }
1558   }
1559 }
1560
1561 uint32_t Util::fileFlags() {
1562   // FIXME: these need to determined at runtime.
1563   if (_ctx.outputMachOType() == MH_OBJECT) {
1564     return _subsectionsViaSymbols ? MH_SUBSECTIONS_VIA_SYMBOLS : 0;
1565   } else {
1566     uint32_t flags = MH_DYLDLINK;
1567     if (!_ctx.useFlatNamespace())
1568         flags |= MH_TWOLEVEL | MH_NOUNDEFS;
1569     if ((_ctx.outputMachOType() == MH_EXECUTE) && _ctx.PIE())
1570       flags |= MH_PIE;
1571     if (_hasTLVDescriptors)
1572       flags |= (MH_PIE | MH_HAS_TLV_DESCRIPTORS);
1573     return flags;
1574   }
1575 }
1576
1577 } // end anonymous namespace
1578
1579 namespace lld {
1580 namespace mach_o {
1581 namespace normalized {
1582
1583 /// Convert a set of Atoms into a normalized mach-o file.
1584 llvm::Expected<std::unique_ptr<NormalizedFile>>
1585 normalizedFromAtoms(const lld::File &atomFile,
1586                                            const MachOLinkingContext &context) {
1587   // The util object buffers info until the normalized file can be made.
1588   Util util(context);
1589   util.processDefinedAtoms(atomFile);
1590   util.organizeSections();
1591
1592   std::unique_ptr<NormalizedFile> f(new NormalizedFile());
1593   NormalizedFile &normFile = *f.get();
1594   normFile.arch = context.arch();
1595   normFile.fileType = context.outputMachOType();
1596   normFile.flags = util.fileFlags();
1597   normFile.stackSize = context.stackSize();
1598   normFile.installName = context.installName();
1599   normFile.currentVersion = context.currentVersion();
1600   normFile.compatVersion = context.compatibilityVersion();
1601   normFile.os = context.os();
1602
1603   // If we are emitting an object file, then the min version is the maximum
1604   // of the min's of all the source files and the cmdline.
1605   if (normFile.fileType == llvm::MachO::MH_OBJECT)
1606     normFile.minOSverson = std::max(context.osMinVersion(), util.minVersion());
1607   else
1608     normFile.minOSverson = context.osMinVersion();
1609
1610   normFile.minOSVersionKind = util.minVersionCommandType();
1611
1612   normFile.sdkVersion = context.sdkVersion();
1613   normFile.sourceVersion = context.sourceVersion();
1614
1615   if (context.generateVersionLoadCommand() &&
1616       context.os() != MachOLinkingContext::OS::unknown)
1617     normFile.hasMinVersionLoadCommand = true;
1618   else if (normFile.fileType == llvm::MachO::MH_OBJECT &&
1619            util.allSourceFilesHaveMinVersions() &&
1620            ((normFile.os != MachOLinkingContext::OS::unknown) ||
1621             util.minVersionCommandType())) {
1622     // If we emit an object file, then it should contain a min version load
1623     // command if all of the source files also contained min version commands.
1624     // Also, we either need to have a platform, or found a platform from the
1625     // source object files.
1626     normFile.hasMinVersionLoadCommand = true;
1627   }
1628   normFile.generateDataInCodeLoadCommand =
1629     context.generateDataInCodeLoadCommand();
1630   normFile.pageSize = context.pageSize();
1631   normFile.rpaths = context.rpaths();
1632   util.addDependentDylibs(atomFile, normFile);
1633   util.copySegmentInfo(normFile);
1634   util.copySectionInfo(normFile);
1635   util.assignAddressesToSections(normFile);
1636   util.buildAtomToAddressMap();
1637   if (auto err = util.synthesizeDebugNotes(normFile))
1638     return std::move(err);
1639   util.updateSectionInfo(normFile);
1640   util.copySectionContent(normFile);
1641   if (auto ec = util.addSymbols(atomFile, normFile)) {
1642     return std::move(ec);
1643   }
1644   util.addIndirectSymbols(atomFile, normFile);
1645   util.addRebaseAndBindingInfo(atomFile, normFile);
1646   util.addExportInfo(atomFile, normFile);
1647   util.addSectionRelocs(atomFile, normFile);
1648   util.addFunctionStarts(atomFile, normFile);
1649   util.buildDataInCodeArray(atomFile, normFile);
1650   util.copyEntryPointAddress(normFile);
1651
1652   return std::move(f);
1653 }
1654
1655 } // namespace normalized
1656 } // namespace mach_o
1657 } // namespace lld