xref: /freebsd/contrib/llvm-project/lld/MachO/InputFiles.cpp (revision 5e801ac66d24704442eba426ed13c3effb8a34e7)
1 //===- InputFiles.cpp -----------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains functions to parse Mach-O object files. In this comment,
10 // we describe the Mach-O file structure and how we parse it.
11 //
12 // Mach-O is not very different from ELF or COFF. The notion of symbols,
13 // sections and relocations exists in Mach-O as it does in ELF and COFF.
14 //
15 // Perhaps the notion that is new to those who know ELF/COFF is "subsections".
16 // In ELF/COFF, sections are an atomic unit of data copied from input files to
17 // output files. When we merge or garbage-collect sections, we treat each
18 // section as an atomic unit. In Mach-O, that's not the case. Sections can
19 // consist of multiple subsections, and subsections are a unit of merging and
20 // garbage-collecting. Therefore, Mach-O's subsections are more similar to
21 // ELF/COFF's sections than Mach-O's sections are.
22 //
23 // A section can have multiple symbols. A symbol that does not have the
24 // N_ALT_ENTRY attribute indicates a beginning of a subsection. Therefore, by
25 // definition, a symbol is always present at the beginning of each subsection. A
26 // symbol with N_ALT_ENTRY attribute does not start a new subsection and can
27 // point to a middle of a subsection.
28 //
29 // The notion of subsections also affects how relocations are represented in
30 // Mach-O. All references within a section need to be explicitly represented as
31 // relocations if they refer to different subsections, because we obviously need
32 // to fix up addresses if subsections are laid out in an output file differently
33 // than they were in object files. To represent that, Mach-O relocations can
34 // refer to an unnamed location via its address. Scattered relocations (those
35 // with the R_SCATTERED bit set) always refer to unnamed locations.
36 // Non-scattered relocations refer to an unnamed location if r_extern is not set
37 // and r_symbolnum is zero.
38 //
39 // Without the above differences, I think you can use your knowledge about ELF
40 // and COFF for Mach-O.
41 //
42 //===----------------------------------------------------------------------===//
43 
44 #include "InputFiles.h"
45 #include "Config.h"
46 #include "Driver.h"
47 #include "Dwarf.h"
48 #include "ExportTrie.h"
49 #include "InputSection.h"
50 #include "MachOStructs.h"
51 #include "ObjC.h"
52 #include "OutputSection.h"
53 #include "OutputSegment.h"
54 #include "SymbolTable.h"
55 #include "Symbols.h"
56 #include "SyntheticSections.h"
57 #include "Target.h"
58 
59 #include "lld/Common/DWARF.h"
60 #include "lld/Common/ErrorHandler.h"
61 #include "lld/Common/Memory.h"
62 #include "lld/Common/Reproduce.h"
63 #include "llvm/ADT/iterator.h"
64 #include "llvm/BinaryFormat/MachO.h"
65 #include "llvm/LTO/LTO.h"
66 #include "llvm/Support/Endian.h"
67 #include "llvm/Support/MemoryBuffer.h"
68 #include "llvm/Support/Path.h"
69 #include "llvm/Support/TarWriter.h"
70 #include "llvm/TextAPI/Architecture.h"
71 #include "llvm/TextAPI/InterfaceFile.h"
72 
73 #include <type_traits>
74 
75 using namespace llvm;
76 using namespace llvm::MachO;
77 using namespace llvm::support::endian;
78 using namespace llvm::sys;
79 using namespace lld;
80 using namespace lld::macho;
81 
82 // Returns "<internal>", "foo.a(bar.o)", or "baz.o".
83 std::string lld::toString(const InputFile *f) {
84   if (!f)
85     return "<internal>";
86 
87   // Multiple dylibs can be defined in one .tbd file.
88   if (auto dylibFile = dyn_cast<DylibFile>(f))
89     if (f->getName().endswith(".tbd"))
90       return (f->getName() + "(" + dylibFile->installName + ")").str();
91 
92   if (f->archiveName.empty())
93     return std::string(f->getName());
94   return (f->archiveName + "(" + path::filename(f->getName()) + ")").str();
95 }
96 
97 SetVector<InputFile *> macho::inputFiles;
98 std::unique_ptr<TarWriter> macho::tar;
99 int InputFile::idCount = 0;
100 
101 static VersionTuple decodeVersion(uint32_t version) {
102   unsigned major = version >> 16;
103   unsigned minor = (version >> 8) & 0xffu;
104   unsigned subMinor = version & 0xffu;
105   return VersionTuple(major, minor, subMinor);
106 }
107 
108 static std::vector<PlatformInfo> getPlatformInfos(const InputFile *input) {
109   if (!isa<ObjFile>(input) && !isa<DylibFile>(input))
110     return {};
111 
112   const char *hdr = input->mb.getBufferStart();
113 
114   std::vector<PlatformInfo> platformInfos;
115   for (auto *cmd : findCommands<build_version_command>(hdr, LC_BUILD_VERSION)) {
116     PlatformInfo info;
117     info.target.Platform = static_cast<PlatformKind>(cmd->platform);
118     info.minimum = decodeVersion(cmd->minos);
119     platformInfos.emplace_back(std::move(info));
120   }
121   for (auto *cmd : findCommands<version_min_command>(
122            hdr, LC_VERSION_MIN_MACOSX, LC_VERSION_MIN_IPHONEOS,
123            LC_VERSION_MIN_TVOS, LC_VERSION_MIN_WATCHOS)) {
124     PlatformInfo info;
125     switch (cmd->cmd) {
126     case LC_VERSION_MIN_MACOSX:
127       info.target.Platform = PlatformKind::macOS;
128       break;
129     case LC_VERSION_MIN_IPHONEOS:
130       info.target.Platform = PlatformKind::iOS;
131       break;
132     case LC_VERSION_MIN_TVOS:
133       info.target.Platform = PlatformKind::tvOS;
134       break;
135     case LC_VERSION_MIN_WATCHOS:
136       info.target.Platform = PlatformKind::watchOS;
137       break;
138     }
139     info.minimum = decodeVersion(cmd->version);
140     platformInfos.emplace_back(std::move(info));
141   }
142 
143   return platformInfos;
144 }
145 
146 static bool checkCompatibility(const InputFile *input) {
147   std::vector<PlatformInfo> platformInfos = getPlatformInfos(input);
148   if (platformInfos.empty())
149     return true;
150 
151   auto it = find_if(platformInfos, [&](const PlatformInfo &info) {
152     return removeSimulator(info.target.Platform) ==
153            removeSimulator(config->platform());
154   });
155   if (it == platformInfos.end()) {
156     std::string platformNames;
157     raw_string_ostream os(platformNames);
158     interleave(
159         platformInfos, os,
160         [&](const PlatformInfo &info) {
161           os << getPlatformName(info.target.Platform);
162         },
163         "/");
164     error(toString(input) + " has platform " + platformNames +
165           Twine(", which is different from target platform ") +
166           getPlatformName(config->platform()));
167     return false;
168   }
169 
170   if (it->minimum > config->platformInfo.minimum)
171     warn(toString(input) + " has version " + it->minimum.getAsString() +
172          ", which is newer than target minimum of " +
173          config->platformInfo.minimum.getAsString());
174 
175   return true;
176 }
177 
178 // This cache mostly exists to store system libraries (and .tbds) as they're
179 // loaded, rather than the input archives, which are already cached at a higher
180 // level, and other files like the filelist that are only read once.
181 // Theoretically this caching could be more efficient by hoisting it, but that
182 // would require altering many callers to track the state.
183 DenseMap<CachedHashStringRef, MemoryBufferRef> macho::cachedReads;
184 // Open a given file path and return it as a memory-mapped file.
185 Optional<MemoryBufferRef> macho::readFile(StringRef path) {
186   CachedHashStringRef key(path);
187   auto entry = cachedReads.find(key);
188   if (entry != cachedReads.end())
189     return entry->second;
190 
191   ErrorOr<std::unique_ptr<MemoryBuffer>> mbOrErr = MemoryBuffer::getFile(path);
192   if (std::error_code ec = mbOrErr.getError()) {
193     error("cannot open " + path + ": " + ec.message());
194     return None;
195   }
196 
197   std::unique_ptr<MemoryBuffer> &mb = *mbOrErr;
198   MemoryBufferRef mbref = mb->getMemBufferRef();
199   make<std::unique_ptr<MemoryBuffer>>(std::move(mb)); // take mb ownership
200 
201   // If this is a regular non-fat file, return it.
202   const char *buf = mbref.getBufferStart();
203   const auto *hdr = reinterpret_cast<const fat_header *>(buf);
204   if (mbref.getBufferSize() < sizeof(uint32_t) ||
205       read32be(&hdr->magic) != FAT_MAGIC) {
206     if (tar)
207       tar->append(relativeToRoot(path), mbref.getBuffer());
208     return cachedReads[key] = mbref;
209   }
210 
211   // Object files and archive files may be fat files, which contain multiple
212   // real files for different CPU ISAs. Here, we search for a file that matches
213   // with the current link target and returns it as a MemoryBufferRef.
214   const auto *arch = reinterpret_cast<const fat_arch *>(buf + sizeof(*hdr));
215 
216   for (uint32_t i = 0, n = read32be(&hdr->nfat_arch); i < n; ++i) {
217     if (reinterpret_cast<const char *>(arch + i + 1) >
218         buf + mbref.getBufferSize()) {
219       error(path + ": fat_arch struct extends beyond end of file");
220       return None;
221     }
222 
223     if (read32be(&arch[i].cputype) != static_cast<uint32_t>(target->cpuType) ||
224         read32be(&arch[i].cpusubtype) != target->cpuSubtype)
225       continue;
226 
227     uint32_t offset = read32be(&arch[i].offset);
228     uint32_t size = read32be(&arch[i].size);
229     if (offset + size > mbref.getBufferSize())
230       error(path + ": slice extends beyond end of file");
231     if (tar)
232       tar->append(relativeToRoot(path), mbref.getBuffer());
233     return cachedReads[key] = MemoryBufferRef(StringRef(buf + offset, size),
234                                               path.copy(bAlloc));
235   }
236 
237   error("unable to find matching architecture in " + path);
238   return None;
239 }
240 
241 InputFile::InputFile(Kind kind, const InterfaceFile &interface)
242     : id(idCount++), fileKind(kind), name(saver.save(interface.getPath())) {}
243 
244 // Some sections comprise of fixed-size records, so instead of splitting them at
245 // symbol boundaries, we split them based on size. Records are distinct from
246 // literals in that they may contain references to other sections, instead of
247 // being leaf nodes in the InputSection graph.
248 //
249 // Note that "record" is a term I came up with. In contrast, "literal" is a term
250 // used by the Mach-O format.
251 static Optional<size_t> getRecordSize(StringRef segname, StringRef name) {
252   if (name == section_names::cfString) {
253     if (config->icfLevel != ICFLevel::none && segname == segment_names::data)
254       return target->wordSize == 8 ? 32 : 16;
255   } else if (name == section_names::compactUnwind) {
256     if (segname == segment_names::ld)
257       return target->wordSize == 8 ? 32 : 20;
258   }
259   return {};
260 }
261 
262 // Parse the sequence of sections within a single LC_SEGMENT(_64).
263 // Split each section into subsections.
264 template <class SectionHeader>
265 void ObjFile::parseSections(ArrayRef<SectionHeader> sectionHeaders) {
266   sections.reserve(sectionHeaders.size());
267   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
268 
269   for (const SectionHeader &sec : sectionHeaders) {
270     StringRef name =
271         StringRef(sec.sectname, strnlen(sec.sectname, sizeof(sec.sectname)));
272     StringRef segname =
273         StringRef(sec.segname, strnlen(sec.segname, sizeof(sec.segname)));
274     ArrayRef<uint8_t> data = {isZeroFill(sec.flags) ? nullptr
275                                                     : buf + sec.offset,
276                               static_cast<size_t>(sec.size)};
277     if (sec.align >= 32) {
278       error("alignment " + std::to_string(sec.align) + " of section " + name +
279             " is too large");
280       sections.push_back(sec.addr);
281       continue;
282     }
283     uint32_t align = 1 << sec.align;
284     uint32_t flags = sec.flags;
285 
286     auto splitRecords = [&](int recordSize) -> void {
287       sections.push_back(sec.addr);
288       if (data.empty())
289         return;
290       Subsections &subsections = sections.back().subsections;
291       subsections.reserve(data.size() / recordSize);
292       auto *isec = make<ConcatInputSection>(
293           segname, name, this, data.slice(0, recordSize), align, flags);
294       subsections.push_back({0, isec});
295       for (uint64_t off = recordSize; off < data.size(); off += recordSize) {
296         // Copying requires less memory than constructing a fresh InputSection.
297         auto *copy = make<ConcatInputSection>(*isec);
298         copy->data = data.slice(off, recordSize);
299         subsections.push_back({off, copy});
300       }
301     };
302 
303     if (sectionType(sec.flags) == S_CSTRING_LITERALS ||
304         (config->dedupLiterals && isWordLiteralSection(sec.flags))) {
305       if (sec.nreloc && config->dedupLiterals)
306         fatal(toString(this) + " contains relocations in " + sec.segname + "," +
307               sec.sectname +
308               ", so LLD cannot deduplicate literals. Try re-running without "
309               "--deduplicate-literals.");
310 
311       InputSection *isec;
312       if (sectionType(sec.flags) == S_CSTRING_LITERALS) {
313         isec =
314             make<CStringInputSection>(segname, name, this, data, align, flags);
315         // FIXME: parallelize this?
316         cast<CStringInputSection>(isec)->splitIntoPieces();
317       } else {
318         isec = make<WordLiteralInputSection>(segname, name, this, data, align,
319                                              flags);
320       }
321       sections.push_back(sec.addr);
322       sections.back().subsections.push_back({0, isec});
323     } else if (auto recordSize = getRecordSize(segname, name)) {
324       splitRecords(*recordSize);
325       if (name == section_names::compactUnwind)
326         compactUnwindSection = &sections.back();
327     } else if (segname == segment_names::llvm) {
328       // ld64 does not appear to emit contents from sections within the __LLVM
329       // segment. Symbols within those sections point to bitcode metadata
330       // instead of actual symbols. Global symbols within those sections could
331       // have the same name without causing duplicate symbol errors. Push an
332       // empty entry to ensure indices line up for the remaining sections.
333       // TODO: Evaluate whether the bitcode metadata is needed.
334       sections.push_back(sec.addr);
335     } else {
336       auto *isec =
337           make<ConcatInputSection>(segname, name, this, data, align, flags);
338       if (isDebugSection(isec->getFlags()) &&
339           isec->getSegName() == segment_names::dwarf) {
340         // Instead of emitting DWARF sections, we emit STABS symbols to the
341         // object files that contain them. We filter them out early to avoid
342         // parsing their relocations unnecessarily. But we must still push an
343         // empty entry to ensure the indices line up for the remaining sections.
344         sections.push_back(sec.addr);
345         debugSections.push_back(isec);
346       } else {
347         sections.push_back(sec.addr);
348         sections.back().subsections.push_back({0, isec});
349       }
350     }
351   }
352 }
353 
354 // Find the subsection corresponding to the greatest section offset that is <=
355 // that of the given offset.
356 //
357 // offset: an offset relative to the start of the original InputSection (before
358 // any subsection splitting has occurred). It will be updated to represent the
359 // same location as an offset relative to the start of the containing
360 // subsection.
361 template <class T>
362 static InputSection *findContainingSubsection(const Subsections &subsections,
363                                               T *offset) {
364   static_assert(std::is_same<uint64_t, T>::value ||
365                     std::is_same<uint32_t, T>::value,
366                 "unexpected type for offset");
367   auto it = std::prev(llvm::upper_bound(
368       subsections, *offset,
369       [](uint64_t value, Subsection subsec) { return value < subsec.offset; }));
370   *offset -= it->offset;
371   return it->isec;
372 }
373 
374 template <class SectionHeader>
375 static bool validateRelocationInfo(InputFile *file, const SectionHeader &sec,
376                                    relocation_info rel) {
377   const RelocAttrs &relocAttrs = target->getRelocAttrs(rel.r_type);
378   bool valid = true;
379   auto message = [relocAttrs, file, sec, rel, &valid](const Twine &diagnostic) {
380     valid = false;
381     return (relocAttrs.name + " relocation " + diagnostic + " at offset " +
382             std::to_string(rel.r_address) + " of " + sec.segname + "," +
383             sec.sectname + " in " + toString(file))
384         .str();
385   };
386 
387   if (!relocAttrs.hasAttr(RelocAttrBits::LOCAL) && !rel.r_extern)
388     error(message("must be extern"));
389   if (relocAttrs.hasAttr(RelocAttrBits::PCREL) != rel.r_pcrel)
390     error(message(Twine("must ") + (rel.r_pcrel ? "not " : "") +
391                   "be PC-relative"));
392   if (isThreadLocalVariables(sec.flags) &&
393       !relocAttrs.hasAttr(RelocAttrBits::UNSIGNED))
394     error(message("not allowed in thread-local section, must be UNSIGNED"));
395   if (rel.r_length < 2 || rel.r_length > 3 ||
396       !relocAttrs.hasAttr(static_cast<RelocAttrBits>(1 << rel.r_length))) {
397     static SmallVector<StringRef, 4> widths{"0", "4", "8", "4 or 8"};
398     error(message("has width " + std::to_string(1 << rel.r_length) +
399                   " bytes, but must be " +
400                   widths[(static_cast<int>(relocAttrs.bits) >> 2) & 3] +
401                   " bytes"));
402   }
403   return valid;
404 }
405 
406 template <class SectionHeader>
407 void ObjFile::parseRelocations(ArrayRef<SectionHeader> sectionHeaders,
408                                const SectionHeader &sec,
409                                Subsections &subsections) {
410   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
411   ArrayRef<relocation_info> relInfos(
412       reinterpret_cast<const relocation_info *>(buf + sec.reloff), sec.nreloc);
413 
414   auto subsecIt = subsections.rbegin();
415   for (size_t i = 0; i < relInfos.size(); i++) {
416     // Paired relocations serve as Mach-O's method for attaching a
417     // supplemental datum to a primary relocation record. ELF does not
418     // need them because the *_RELOC_RELA records contain the extra
419     // addend field, vs. *_RELOC_REL which omit the addend.
420     //
421     // The {X86_64,ARM64}_RELOC_SUBTRACTOR record holds the subtrahend,
422     // and the paired *_RELOC_UNSIGNED record holds the minuend. The
423     // datum for each is a symbolic address. The result is the offset
424     // between two addresses.
425     //
426     // The ARM64_RELOC_ADDEND record holds the addend, and the paired
427     // ARM64_RELOC_BRANCH26 or ARM64_RELOC_PAGE21/PAGEOFF12 holds the
428     // base symbolic address.
429     //
430     // Note: X86 does not use *_RELOC_ADDEND because it can embed an
431     // addend into the instruction stream. On X86, a relocatable address
432     // field always occupies an entire contiguous sequence of byte(s),
433     // so there is no need to merge opcode bits with address
434     // bits. Therefore, it's easy and convenient to store addends in the
435     // instruction-stream bytes that would otherwise contain zeroes. By
436     // contrast, RISC ISAs such as ARM64 mix opcode bits with with
437     // address bits so that bitwise arithmetic is necessary to extract
438     // and insert them. Storing addends in the instruction stream is
439     // possible, but inconvenient and more costly at link time.
440 
441     relocation_info relInfo = relInfos[i];
442     bool isSubtrahend =
443         target->hasAttr(relInfo.r_type, RelocAttrBits::SUBTRAHEND);
444     if (isSubtrahend && StringRef(sec.sectname) == section_names::ehFrame) {
445       // __TEXT,__eh_frame only has symbols and SUBTRACTOR relocs when ld64 -r
446       // adds local "EH_Frame1" and "func.eh". Ignore them because they have
447       // gone unused by Mac OS since Snow Leopard (10.6), vintage 2009.
448       ++i;
449       continue;
450     }
451     int64_t pairedAddend = 0;
452     if (target->hasAttr(relInfo.r_type, RelocAttrBits::ADDEND)) {
453       pairedAddend = SignExtend64<24>(relInfo.r_symbolnum);
454       relInfo = relInfos[++i];
455     }
456     assert(i < relInfos.size());
457     if (!validateRelocationInfo(this, sec, relInfo))
458       continue;
459     if (relInfo.r_address & R_SCATTERED)
460       fatal("TODO: Scattered relocations not supported");
461 
462     int64_t embeddedAddend = target->getEmbeddedAddend(mb, sec.offset, relInfo);
463     assert(!(embeddedAddend && pairedAddend));
464     int64_t totalAddend = pairedAddend + embeddedAddend;
465     Reloc r;
466     r.type = relInfo.r_type;
467     r.pcrel = relInfo.r_pcrel;
468     r.length = relInfo.r_length;
469     r.offset = relInfo.r_address;
470     if (relInfo.r_extern) {
471       r.referent = symbols[relInfo.r_symbolnum];
472       r.addend = isSubtrahend ? 0 : totalAddend;
473     } else {
474       assert(!isSubtrahend);
475       const SectionHeader &referentSecHead =
476           sectionHeaders[relInfo.r_symbolnum - 1];
477       uint64_t referentOffset;
478       if (relInfo.r_pcrel) {
479         // The implicit addend for pcrel section relocations is the pcrel offset
480         // in terms of the addresses in the input file. Here we adjust it so
481         // that it describes the offset from the start of the referent section.
482         // FIXME This logic was written around x86_64 behavior -- ARM64 doesn't
483         // have pcrel section relocations. We may want to factor this out into
484         // the arch-specific .cpp file.
485         assert(target->hasAttr(r.type, RelocAttrBits::BYTE4));
486         referentOffset = sec.addr + relInfo.r_address + 4 + totalAddend -
487                          referentSecHead.addr;
488       } else {
489         // The addend for a non-pcrel relocation is its absolute address.
490         referentOffset = totalAddend - referentSecHead.addr;
491       }
492       Subsections &referentSubsections =
493           sections[relInfo.r_symbolnum - 1].subsections;
494       r.referent =
495           findContainingSubsection(referentSubsections, &referentOffset);
496       r.addend = referentOffset;
497     }
498 
499     // Find the subsection that this relocation belongs to.
500     // Though not required by the Mach-O format, clang and gcc seem to emit
501     // relocations in order, so let's take advantage of it. However, ld64 emits
502     // unsorted relocations (in `-r` mode), so we have a fallback for that
503     // uncommon case.
504     InputSection *subsec;
505     while (subsecIt != subsections.rend() && subsecIt->offset > r.offset)
506       ++subsecIt;
507     if (subsecIt == subsections.rend() ||
508         subsecIt->offset + subsecIt->isec->getSize() <= r.offset) {
509       subsec = findContainingSubsection(subsections, &r.offset);
510       // Now that we know the relocs are unsorted, avoid trying the 'fast path'
511       // for the other relocations.
512       subsecIt = subsections.rend();
513     } else {
514       subsec = subsecIt->isec;
515       r.offset -= subsecIt->offset;
516     }
517     subsec->relocs.push_back(r);
518 
519     if (isSubtrahend) {
520       relocation_info minuendInfo = relInfos[++i];
521       // SUBTRACTOR relocations should always be followed by an UNSIGNED one
522       // attached to the same address.
523       assert(target->hasAttr(minuendInfo.r_type, RelocAttrBits::UNSIGNED) &&
524              relInfo.r_address == minuendInfo.r_address);
525       Reloc p;
526       p.type = minuendInfo.r_type;
527       if (minuendInfo.r_extern) {
528         p.referent = symbols[minuendInfo.r_symbolnum];
529         p.addend = totalAddend;
530       } else {
531         uint64_t referentOffset =
532             totalAddend - sectionHeaders[minuendInfo.r_symbolnum - 1].addr;
533         Subsections &referentSubsectVec =
534             sections[minuendInfo.r_symbolnum - 1].subsections;
535         p.referent =
536             findContainingSubsection(referentSubsectVec, &referentOffset);
537         p.addend = referentOffset;
538       }
539       subsec->relocs.push_back(p);
540     }
541   }
542 }
543 
544 template <class NList>
545 static macho::Symbol *createDefined(const NList &sym, StringRef name,
546                                     InputSection *isec, uint64_t value,
547                                     uint64_t size) {
548   // Symbol scope is determined by sym.n_type & (N_EXT | N_PEXT):
549   // N_EXT: Global symbols. These go in the symbol table during the link,
550   //        and also in the export table of the output so that the dynamic
551   //        linker sees them.
552   // N_EXT | N_PEXT: Linkage unit (think: dylib) scoped. These go in the
553   //                 symbol table during the link so that duplicates are
554   //                 either reported (for non-weak symbols) or merged
555   //                 (for weak symbols), but they do not go in the export
556   //                 table of the output.
557   // N_PEXT: llvm-mc does not emit these, but `ld -r` (wherein ld64 emits
558   //         object files) may produce them. LLD does not yet support -r.
559   //         These are translation-unit scoped, identical to the `0` case.
560   // 0: Translation-unit scoped. These are not in the symbol table during
561   //    link, and not in the export table of the output either.
562   bool isWeakDefCanBeHidden =
563       (sym.n_desc & (N_WEAK_DEF | N_WEAK_REF)) == (N_WEAK_DEF | N_WEAK_REF);
564 
565   if (sym.n_type & N_EXT) {
566     bool isPrivateExtern = sym.n_type & N_PEXT;
567     // lld's behavior for merging symbols is slightly different from ld64:
568     // ld64 picks the winning symbol based on several criteria (see
569     // pickBetweenRegularAtoms() in ld64's SymbolTable.cpp), while lld
570     // just merges metadata and keeps the contents of the first symbol
571     // with that name (see SymbolTable::addDefined). For:
572     // * inline function F in a TU built with -fvisibility-inlines-hidden
573     // * and inline function F in another TU built without that flag
574     // ld64 will pick the one from the file built without
575     // -fvisibility-inlines-hidden.
576     // lld will instead pick the one listed first on the link command line and
577     // give it visibility as if the function was built without
578     // -fvisibility-inlines-hidden.
579     // If both functions have the same contents, this will have the same
580     // behavior. If not, it won't, but the input had an ODR violation in
581     // that case.
582     //
583     // Similarly, merging a symbol
584     // that's isPrivateExtern and not isWeakDefCanBeHidden with one
585     // that's not isPrivateExtern but isWeakDefCanBeHidden technically
586     // should produce one
587     // that's not isPrivateExtern but isWeakDefCanBeHidden. That matters
588     // with ld64's semantics, because it means the non-private-extern
589     // definition will continue to take priority if more private extern
590     // definitions are encountered. With lld's semantics there's no observable
591     // difference between a symbol that's isWeakDefCanBeHidden(autohide) or one
592     // that's privateExtern -- neither makes it into the dynamic symbol table,
593     // unless the autohide symbol is explicitly exported.
594     // But if a symbol is both privateExtern and autohide then it can't
595     // be exported.
596     // So we nullify the autohide flag when privateExtern is present
597     // and promote the symbol to privateExtern when it is not already.
598     if (isWeakDefCanBeHidden && isPrivateExtern)
599       isWeakDefCanBeHidden = false;
600     else if (isWeakDefCanBeHidden)
601       isPrivateExtern = true;
602     return symtab->addDefined(
603         name, isec->getFile(), isec, value, size, sym.n_desc & N_WEAK_DEF,
604         isPrivateExtern, sym.n_desc & N_ARM_THUMB_DEF,
605         sym.n_desc & REFERENCED_DYNAMICALLY, sym.n_desc & N_NO_DEAD_STRIP,
606         isWeakDefCanBeHidden);
607   }
608   assert(!isWeakDefCanBeHidden &&
609          "weak_def_can_be_hidden on already-hidden symbol?");
610   return make<Defined>(
611       name, isec->getFile(), isec, value, size, sym.n_desc & N_WEAK_DEF,
612       /*isExternal=*/false, /*isPrivateExtern=*/false,
613       sym.n_desc & N_ARM_THUMB_DEF, sym.n_desc & REFERENCED_DYNAMICALLY,
614       sym.n_desc & N_NO_DEAD_STRIP);
615 }
616 
617 // Absolute symbols are defined symbols that do not have an associated
618 // InputSection. They cannot be weak.
619 template <class NList>
620 static macho::Symbol *createAbsolute(const NList &sym, InputFile *file,
621                                      StringRef name) {
622   if (sym.n_type & N_EXT) {
623     return symtab->addDefined(
624         name, file, nullptr, sym.n_value, /*size=*/0,
625         /*isWeakDef=*/false, sym.n_type & N_PEXT, sym.n_desc & N_ARM_THUMB_DEF,
626         /*isReferencedDynamically=*/false, sym.n_desc & N_NO_DEAD_STRIP,
627         /*isWeakDefCanBeHidden=*/false);
628   }
629   return make<Defined>(name, file, nullptr, sym.n_value, /*size=*/0,
630                        /*isWeakDef=*/false,
631                        /*isExternal=*/false, /*isPrivateExtern=*/false,
632                        sym.n_desc & N_ARM_THUMB_DEF,
633                        /*isReferencedDynamically=*/false,
634                        sym.n_desc & N_NO_DEAD_STRIP);
635 }
636 
637 template <class NList>
638 macho::Symbol *ObjFile::parseNonSectionSymbol(const NList &sym,
639                                               StringRef name) {
640   uint8_t type = sym.n_type & N_TYPE;
641   switch (type) {
642   case N_UNDF:
643     return sym.n_value == 0
644                ? symtab->addUndefined(name, this, sym.n_desc & N_WEAK_REF)
645                : symtab->addCommon(name, this, sym.n_value,
646                                    1 << GET_COMM_ALIGN(sym.n_desc),
647                                    sym.n_type & N_PEXT);
648   case N_ABS:
649     return createAbsolute(sym, this, name);
650   case N_PBUD:
651   case N_INDR:
652     error("TODO: support symbols of type " + std::to_string(type));
653     return nullptr;
654   case N_SECT:
655     llvm_unreachable(
656         "N_SECT symbols should not be passed to parseNonSectionSymbol");
657   default:
658     llvm_unreachable("invalid symbol type");
659   }
660 }
661 
662 template <class NList> static bool isUndef(const NList &sym) {
663   return (sym.n_type & N_TYPE) == N_UNDF && sym.n_value == 0;
664 }
665 
666 template <class LP>
667 void ObjFile::parseSymbols(ArrayRef<typename LP::section> sectionHeaders,
668                            ArrayRef<typename LP::nlist> nList,
669                            const char *strtab, bool subsectionsViaSymbols) {
670   using NList = typename LP::nlist;
671 
672   // Groups indices of the symbols by the sections that contain them.
673   std::vector<std::vector<uint32_t>> symbolsBySection(sections.size());
674   symbols.resize(nList.size());
675   SmallVector<unsigned, 32> undefineds;
676   for (uint32_t i = 0; i < nList.size(); ++i) {
677     const NList &sym = nList[i];
678 
679     // Ignore debug symbols for now.
680     // FIXME: may need special handling.
681     if (sym.n_type & N_STAB)
682       continue;
683 
684     StringRef name = strtab + sym.n_strx;
685     if ((sym.n_type & N_TYPE) == N_SECT) {
686       Subsections &subsections = sections[sym.n_sect - 1].subsections;
687       // parseSections() may have chosen not to parse this section.
688       if (subsections.empty())
689         continue;
690       symbolsBySection[sym.n_sect - 1].push_back(i);
691     } else if (isUndef(sym)) {
692       undefineds.push_back(i);
693     } else {
694       symbols[i] = parseNonSectionSymbol(sym, name);
695     }
696   }
697 
698   for (size_t i = 0; i < sections.size(); ++i) {
699     Subsections &subsections = sections[i].subsections;
700     if (subsections.empty())
701       continue;
702     InputSection *lastIsec = subsections.back().isec;
703     if (lastIsec->getName() == section_names::ehFrame) {
704       // __TEXT,__eh_frame only has symbols and SUBTRACTOR relocs when ld64 -r
705       // adds local "EH_Frame1" and "func.eh". Ignore them because they have
706       // gone unused by Mac OS since Snow Leopard (10.6), vintage 2009.
707       continue;
708     }
709     std::vector<uint32_t> &symbolIndices = symbolsBySection[i];
710     uint64_t sectionAddr = sectionHeaders[i].addr;
711     uint32_t sectionAlign = 1u << sectionHeaders[i].align;
712 
713     // Record-based sections have already been split into subsections during
714     // parseSections(), so we simply need to match Symbols to the corresponding
715     // subsection here.
716     if (getRecordSize(lastIsec->getSegName(), lastIsec->getName())) {
717       for (size_t j = 0; j < symbolIndices.size(); ++j) {
718         uint32_t symIndex = symbolIndices[j];
719         const NList &sym = nList[symIndex];
720         StringRef name = strtab + sym.n_strx;
721         uint64_t symbolOffset = sym.n_value - sectionAddr;
722         InputSection *isec =
723             findContainingSubsection(subsections, &symbolOffset);
724         if (symbolOffset != 0) {
725           error(toString(lastIsec) + ":  symbol " + name +
726                 " at misaligned offset");
727           continue;
728         }
729         symbols[symIndex] = createDefined(sym, name, isec, 0, isec->getSize());
730       }
731       continue;
732     }
733 
734     // Calculate symbol sizes and create subsections by splitting the sections
735     // along symbol boundaries.
736     // We populate subsections by repeatedly splitting the last (highest
737     // address) subsection.
738     llvm::stable_sort(symbolIndices, [&](uint32_t lhs, uint32_t rhs) {
739       return nList[lhs].n_value < nList[rhs].n_value;
740     });
741     for (size_t j = 0; j < symbolIndices.size(); ++j) {
742       uint32_t symIndex = symbolIndices[j];
743       const NList &sym = nList[symIndex];
744       StringRef name = strtab + sym.n_strx;
745       Subsection &subsec = subsections.back();
746       InputSection *isec = subsec.isec;
747 
748       uint64_t subsecAddr = sectionAddr + subsec.offset;
749       size_t symbolOffset = sym.n_value - subsecAddr;
750       uint64_t symbolSize =
751           j + 1 < symbolIndices.size()
752               ? nList[symbolIndices[j + 1]].n_value - sym.n_value
753               : isec->data.size() - symbolOffset;
754       // There are 4 cases where we do not need to create a new subsection:
755       //   1. If the input file does not use subsections-via-symbols.
756       //   2. Multiple symbols at the same address only induce one subsection.
757       //      (The symbolOffset == 0 check covers both this case as well as
758       //      the first loop iteration.)
759       //   3. Alternative entry points do not induce new subsections.
760       //   4. If we have a literal section (e.g. __cstring and __literal4).
761       if (!subsectionsViaSymbols || symbolOffset == 0 ||
762           sym.n_desc & N_ALT_ENTRY || !isa<ConcatInputSection>(isec)) {
763         symbols[symIndex] =
764             createDefined(sym, name, isec, symbolOffset, symbolSize);
765         continue;
766       }
767       auto *concatIsec = cast<ConcatInputSection>(isec);
768 
769       auto *nextIsec = make<ConcatInputSection>(*concatIsec);
770       nextIsec->wasCoalesced = false;
771       if (isZeroFill(isec->getFlags())) {
772         // Zero-fill sections have NULL data.data() non-zero data.size()
773         nextIsec->data = {nullptr, isec->data.size() - symbolOffset};
774         isec->data = {nullptr, symbolOffset};
775       } else {
776         nextIsec->data = isec->data.slice(symbolOffset);
777         isec->data = isec->data.slice(0, symbolOffset);
778       }
779 
780       // By construction, the symbol will be at offset zero in the new
781       // subsection.
782       symbols[symIndex] =
783           createDefined(sym, name, nextIsec, /*value=*/0, symbolSize);
784       // TODO: ld64 appears to preserve the original alignment as well as each
785       // subsection's offset from the last aligned address. We should consider
786       // emulating that behavior.
787       nextIsec->align = MinAlign(sectionAlign, sym.n_value);
788       subsections.push_back({sym.n_value - sectionAddr, nextIsec});
789     }
790   }
791 
792   // Undefined symbols can trigger recursive fetch from Archives due to
793   // LazySymbols. Process defined symbols first so that the relative order
794   // between a defined symbol and an undefined symbol does not change the
795   // symbol resolution behavior. In addition, a set of interconnected symbols
796   // will all be resolved to the same file, instead of being resolved to
797   // different files.
798   for (unsigned i : undefineds) {
799     const NList &sym = nList[i];
800     StringRef name = strtab + sym.n_strx;
801     symbols[i] = parseNonSectionSymbol(sym, name);
802   }
803 }
804 
805 OpaqueFile::OpaqueFile(MemoryBufferRef mb, StringRef segName,
806                        StringRef sectName)
807     : InputFile(OpaqueKind, mb) {
808   const auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
809   ArrayRef<uint8_t> data = {buf, mb.getBufferSize()};
810   ConcatInputSection *isec =
811       make<ConcatInputSection>(segName.take_front(16), sectName.take_front(16),
812                                /*file=*/this, data);
813   isec->live = true;
814   sections.push_back(0);
815   sections.back().subsections.push_back({0, isec});
816 }
817 
818 ObjFile::ObjFile(MemoryBufferRef mb, uint32_t modTime, StringRef archiveName)
819     : InputFile(ObjKind, mb), modTime(modTime) {
820   this->archiveName = std::string(archiveName);
821   if (target->wordSize == 8)
822     parse<LP64>();
823   else
824     parse<ILP32>();
825 }
826 
827 template <class LP> void ObjFile::parse() {
828   using Header = typename LP::mach_header;
829   using SegmentCommand = typename LP::segment_command;
830   using SectionHeader = typename LP::section;
831   using NList = typename LP::nlist;
832 
833   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
834   auto *hdr = reinterpret_cast<const Header *>(mb.getBufferStart());
835 
836   Architecture arch = getArchitectureFromCpuType(hdr->cputype, hdr->cpusubtype);
837   if (arch != config->arch()) {
838     auto msg = config->errorForArchMismatch
839                    ? static_cast<void (*)(const Twine &)>(error)
840                    : warn;
841     msg(toString(this) + " has architecture " + getArchitectureName(arch) +
842         " which is incompatible with target architecture " +
843         getArchitectureName(config->arch()));
844     return;
845   }
846 
847   if (!checkCompatibility(this))
848     return;
849 
850   for (auto *cmd : findCommands<linker_option_command>(hdr, LC_LINKER_OPTION)) {
851     StringRef data{reinterpret_cast<const char *>(cmd + 1),
852                    cmd->cmdsize - sizeof(linker_option_command)};
853     parseLCLinkerOption(this, cmd->count, data);
854   }
855 
856   ArrayRef<SectionHeader> sectionHeaders;
857   if (const load_command *cmd = findCommand(hdr, LP::segmentLCType)) {
858     auto *c = reinterpret_cast<const SegmentCommand *>(cmd);
859     sectionHeaders = ArrayRef<SectionHeader>{
860         reinterpret_cast<const SectionHeader *>(c + 1), c->nsects};
861     parseSections(sectionHeaders);
862   }
863 
864   // TODO: Error on missing LC_SYMTAB?
865   if (const load_command *cmd = findCommand(hdr, LC_SYMTAB)) {
866     auto *c = reinterpret_cast<const symtab_command *>(cmd);
867     ArrayRef<NList> nList(reinterpret_cast<const NList *>(buf + c->symoff),
868                           c->nsyms);
869     const char *strtab = reinterpret_cast<const char *>(buf) + c->stroff;
870     bool subsectionsViaSymbols = hdr->flags & MH_SUBSECTIONS_VIA_SYMBOLS;
871     parseSymbols<LP>(sectionHeaders, nList, strtab, subsectionsViaSymbols);
872   }
873 
874   // The relocations may refer to the symbols, so we parse them after we have
875   // parsed all the symbols.
876   for (size_t i = 0, n = sections.size(); i < n; ++i)
877     if (!sections[i].subsections.empty())
878       parseRelocations(sectionHeaders, sectionHeaders[i],
879                        sections[i].subsections);
880 
881   parseDebugInfo();
882   if (config->emitDataInCodeInfo)
883     parseDataInCode();
884   if (compactUnwindSection)
885     registerCompactUnwind();
886 }
887 
888 void ObjFile::parseDebugInfo() {
889   std::unique_ptr<DwarfObject> dObj = DwarfObject::create(this);
890   if (!dObj)
891     return;
892 
893   auto *ctx = make<DWARFContext>(
894       std::move(dObj), "",
895       [&](Error err) {
896         warn(toString(this) + ": " + toString(std::move(err)));
897       },
898       [&](Error warning) {
899         warn(toString(this) + ": " + toString(std::move(warning)));
900       });
901 
902   // TODO: Since object files can contain a lot of DWARF info, we should verify
903   // that we are parsing just the info we need
904   const DWARFContext::compile_unit_range &units = ctx->compile_units();
905   // FIXME: There can be more than one compile unit per object file. See
906   // PR48637.
907   auto it = units.begin();
908   compileUnit = it->get();
909 }
910 
911 void ObjFile::parseDataInCode() {
912   const auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
913   const load_command *cmd = findCommand(buf, LC_DATA_IN_CODE);
914   if (!cmd)
915     return;
916   const auto *c = reinterpret_cast<const linkedit_data_command *>(cmd);
917   dataInCodeEntries = {
918       reinterpret_cast<const data_in_code_entry *>(buf + c->dataoff),
919       c->datasize / sizeof(data_in_code_entry)};
920   assert(is_sorted(dataInCodeEntries, [](const data_in_code_entry &lhs,
921                                          const data_in_code_entry &rhs) {
922     return lhs.offset < rhs.offset;
923   }));
924 }
925 
926 // Create pointers from symbols to their associated compact unwind entries.
927 void ObjFile::registerCompactUnwind() {
928   for (const Subsection &subsection : compactUnwindSection->subsections) {
929     ConcatInputSection *isec = cast<ConcatInputSection>(subsection.isec);
930     // Hack!! Since each CUE contains a different function address, if ICF
931     // operated naively and compared the entire contents of each CUE, entries
932     // with identical unwind info but belonging to different functions would
933     // never be considered equivalent. To work around this problem, we slice
934     // away the function address here. (Note that we do not adjust the offsets
935     // of the corresponding relocations.) We rely on `relocateCompactUnwind()`
936     // to correctly handle these truncated input sections.
937     isec->data = isec->data.slice(target->wordSize);
938 
939     ConcatInputSection *referentIsec;
940     for (auto it = isec->relocs.begin(); it != isec->relocs.end();) {
941       Reloc &r = *it;
942       // CUE::functionAddress is at offset 0. Skip personality & LSDA relocs.
943       if (r.offset != 0) {
944         ++it;
945         continue;
946       }
947       uint64_t add = r.addend;
948       if (auto *sym = cast_or_null<Defined>(r.referent.dyn_cast<Symbol *>())) {
949         // Check whether the symbol defined in this file is the prevailing one.
950         // Skip if it is e.g. a weak def that didn't prevail.
951         if (sym->getFile() != this) {
952           ++it;
953           continue;
954         }
955         add += sym->value;
956         referentIsec = cast<ConcatInputSection>(sym->isec);
957       } else {
958         referentIsec =
959             cast<ConcatInputSection>(r.referent.dyn_cast<InputSection *>());
960       }
961       if (referentIsec->getSegName() != segment_names::text)
962         error("compact unwind references address in " + toString(referentIsec) +
963               " which is not in segment __TEXT");
964       // The functionAddress relocations are typically section relocations.
965       // However, unwind info operates on a per-symbol basis, so we search for
966       // the function symbol here.
967       auto symIt = llvm::lower_bound(
968           referentIsec->symbols, add,
969           [](Defined *d, uint64_t add) { return d->value < add; });
970       // The relocation should point at the exact address of a symbol (with no
971       // addend).
972       if (symIt == referentIsec->symbols.end() || (*symIt)->value != add) {
973         assert(referentIsec->wasCoalesced);
974         ++it;
975         continue;
976       }
977       (*symIt)->unwindEntry = isec;
978       // Since we've sliced away the functionAddress, we should remove the
979       // corresponding relocation too. Given that clang emits relocations in
980       // reverse order of address, this relocation should be at the end of the
981       // vector for most of our input object files, so this is typically an O(1)
982       // operation.
983       it = isec->relocs.erase(it);
984     }
985   }
986 }
987 
988 // The path can point to either a dylib or a .tbd file.
989 static DylibFile *loadDylib(StringRef path, DylibFile *umbrella) {
990   Optional<MemoryBufferRef> mbref = readFile(path);
991   if (!mbref) {
992     error("could not read dylib file at " + path);
993     return nullptr;
994   }
995   return loadDylib(*mbref, umbrella);
996 }
997 
998 // TBD files are parsed into a series of TAPI documents (InterfaceFiles), with
999 // the first document storing child pointers to the rest of them. When we are
1000 // processing a given TBD file, we store that top-level document in
1001 // currentTopLevelTapi. When processing re-exports, we search its children for
1002 // potentially matching documents in the same TBD file. Note that the children
1003 // themselves don't point to further documents, i.e. this is a two-level tree.
1004 //
1005 // Re-exports can either refer to on-disk files, or to documents within .tbd
1006 // files.
1007 static DylibFile *findDylib(StringRef path, DylibFile *umbrella,
1008                             const InterfaceFile *currentTopLevelTapi) {
1009   // Search order:
1010   // 1. Install name basename in -F / -L directories.
1011   {
1012     StringRef stem = path::stem(path);
1013     SmallString<128> frameworkName;
1014     path::append(frameworkName, path::Style::posix, stem + ".framework", stem);
1015     bool isFramework = path.endswith(frameworkName);
1016     if (isFramework) {
1017       for (StringRef dir : config->frameworkSearchPaths) {
1018         SmallString<128> candidate = dir;
1019         path::append(candidate, frameworkName);
1020         if (Optional<StringRef> dylibPath = resolveDylibPath(candidate.str()))
1021           return loadDylib(*dylibPath, umbrella);
1022       }
1023     } else if (Optional<StringRef> dylibPath = findPathCombination(
1024                    stem, config->librarySearchPaths, {".tbd", ".dylib"}))
1025       return loadDylib(*dylibPath, umbrella);
1026   }
1027 
1028   // 2. As absolute path.
1029   if (path::is_absolute(path, path::Style::posix))
1030     for (StringRef root : config->systemLibraryRoots)
1031       if (Optional<StringRef> dylibPath = resolveDylibPath((root + path).str()))
1032         return loadDylib(*dylibPath, umbrella);
1033 
1034   // 3. As relative path.
1035 
1036   // TODO: Handle -dylib_file
1037 
1038   // Replace @executable_path, @loader_path, @rpath prefixes in install name.
1039   SmallString<128> newPath;
1040   if (config->outputType == MH_EXECUTE &&
1041       path.consume_front("@executable_path/")) {
1042     // ld64 allows overriding this with the undocumented flag -executable_path.
1043     // lld doesn't currently implement that flag.
1044     // FIXME: Consider using finalOutput instead of outputFile.
1045     path::append(newPath, path::parent_path(config->outputFile), path);
1046     path = newPath;
1047   } else if (path.consume_front("@loader_path/")) {
1048     fs::real_path(umbrella->getName(), newPath);
1049     path::remove_filename(newPath);
1050     path::append(newPath, path);
1051     path = newPath;
1052   } else if (path.startswith("@rpath/")) {
1053     for (StringRef rpath : umbrella->rpaths) {
1054       newPath.clear();
1055       if (rpath.consume_front("@loader_path/")) {
1056         fs::real_path(umbrella->getName(), newPath);
1057         path::remove_filename(newPath);
1058       }
1059       path::append(newPath, rpath, path.drop_front(strlen("@rpath/")));
1060       if (Optional<StringRef> dylibPath = resolveDylibPath(newPath.str()))
1061         return loadDylib(*dylibPath, umbrella);
1062     }
1063   }
1064 
1065   // FIXME: Should this be further up?
1066   if (currentTopLevelTapi) {
1067     for (InterfaceFile &child :
1068          make_pointee_range(currentTopLevelTapi->documents())) {
1069       assert(child.documents().empty());
1070       if (path == child.getInstallName()) {
1071         auto file = make<DylibFile>(child, umbrella);
1072         file->parseReexports(child);
1073         return file;
1074       }
1075     }
1076   }
1077 
1078   if (Optional<StringRef> dylibPath = resolveDylibPath(path))
1079     return loadDylib(*dylibPath, umbrella);
1080 
1081   return nullptr;
1082 }
1083 
1084 // If a re-exported dylib is public (lives in /usr/lib or
1085 // /System/Library/Frameworks), then it is considered implicitly linked: we
1086 // should bind to its symbols directly instead of via the re-exporting umbrella
1087 // library.
1088 static bool isImplicitlyLinked(StringRef path) {
1089   if (!config->implicitDylibs)
1090     return false;
1091 
1092   if (path::parent_path(path) == "/usr/lib")
1093     return true;
1094 
1095   // Match /System/Library/Frameworks/$FOO.framework/**/$FOO
1096   if (path.consume_front("/System/Library/Frameworks/")) {
1097     StringRef frameworkName = path.take_until([](char c) { return c == '.'; });
1098     return path::filename(path) == frameworkName;
1099   }
1100 
1101   return false;
1102 }
1103 
1104 static void loadReexport(StringRef path, DylibFile *umbrella,
1105                          const InterfaceFile *currentTopLevelTapi) {
1106   DylibFile *reexport = findDylib(path, umbrella, currentTopLevelTapi);
1107   if (!reexport)
1108     error("unable to locate re-export with install name " + path);
1109 }
1110 
1111 DylibFile::DylibFile(MemoryBufferRef mb, DylibFile *umbrella,
1112                      bool isBundleLoader)
1113     : InputFile(DylibKind, mb), refState(RefState::Unreferenced),
1114       isBundleLoader(isBundleLoader) {
1115   assert(!isBundleLoader || !umbrella);
1116   if (umbrella == nullptr)
1117     umbrella = this;
1118   this->umbrella = umbrella;
1119 
1120   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
1121   auto *hdr = reinterpret_cast<const mach_header *>(mb.getBufferStart());
1122 
1123   // Initialize installName.
1124   if (const load_command *cmd = findCommand(hdr, LC_ID_DYLIB)) {
1125     auto *c = reinterpret_cast<const dylib_command *>(cmd);
1126     currentVersion = read32le(&c->dylib.current_version);
1127     compatibilityVersion = read32le(&c->dylib.compatibility_version);
1128     installName =
1129         reinterpret_cast<const char *>(cmd) + read32le(&c->dylib.name);
1130   } else if (!isBundleLoader) {
1131     // macho_executable and macho_bundle don't have LC_ID_DYLIB,
1132     // so it's OK.
1133     error("dylib " + toString(this) + " missing LC_ID_DYLIB load command");
1134     return;
1135   }
1136 
1137   if (config->printEachFile)
1138     message(toString(this));
1139   inputFiles.insert(this);
1140 
1141   deadStrippable = hdr->flags & MH_DEAD_STRIPPABLE_DYLIB;
1142 
1143   if (!checkCompatibility(this))
1144     return;
1145 
1146   checkAppExtensionSafety(hdr->flags & MH_APP_EXTENSION_SAFE);
1147 
1148   for (auto *cmd : findCommands<rpath_command>(hdr, LC_RPATH)) {
1149     StringRef rpath{reinterpret_cast<const char *>(cmd) + cmd->path};
1150     rpaths.push_back(rpath);
1151   }
1152 
1153   // Initialize symbols.
1154   exportingFile = isImplicitlyLinked(installName) ? this : this->umbrella;
1155   if (const load_command *cmd = findCommand(hdr, LC_DYLD_INFO_ONLY)) {
1156     auto *c = reinterpret_cast<const dyld_info_command *>(cmd);
1157     parseTrie(buf + c->export_off, c->export_size,
1158               [&](const Twine &name, uint64_t flags) {
1159                 StringRef savedName = saver.save(name);
1160                 if (handleLDSymbol(savedName))
1161                   return;
1162                 bool isWeakDef = flags & EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION;
1163                 bool isTlv = flags & EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL;
1164                 symbols.push_back(symtab->addDylib(savedName, exportingFile,
1165                                                    isWeakDef, isTlv));
1166               });
1167   } else {
1168     error("LC_DYLD_INFO_ONLY not found in " + toString(this));
1169     return;
1170   }
1171 }
1172 
1173 void DylibFile::parseLoadCommands(MemoryBufferRef mb) {
1174   auto *hdr = reinterpret_cast<const mach_header *>(mb.getBufferStart());
1175   const uint8_t *p = reinterpret_cast<const uint8_t *>(mb.getBufferStart()) +
1176                      target->headerSize;
1177   for (uint32_t i = 0, n = hdr->ncmds; i < n; ++i) {
1178     auto *cmd = reinterpret_cast<const load_command *>(p);
1179     p += cmd->cmdsize;
1180 
1181     if (!(hdr->flags & MH_NO_REEXPORTED_DYLIBS) &&
1182         cmd->cmd == LC_REEXPORT_DYLIB) {
1183       const auto *c = reinterpret_cast<const dylib_command *>(cmd);
1184       StringRef reexportPath =
1185           reinterpret_cast<const char *>(c) + read32le(&c->dylib.name);
1186       loadReexport(reexportPath, exportingFile, nullptr);
1187     }
1188 
1189     // FIXME: What about LC_LOAD_UPWARD_DYLIB, LC_LAZY_LOAD_DYLIB,
1190     // LC_LOAD_WEAK_DYLIB, LC_REEXPORT_DYLIB (..are reexports from dylibs with
1191     // MH_NO_REEXPORTED_DYLIBS loaded for -flat_namespace)?
1192     if (config->namespaceKind == NamespaceKind::flat &&
1193         cmd->cmd == LC_LOAD_DYLIB) {
1194       const auto *c = reinterpret_cast<const dylib_command *>(cmd);
1195       StringRef dylibPath =
1196           reinterpret_cast<const char *>(c) + read32le(&c->dylib.name);
1197       DylibFile *dylib = findDylib(dylibPath, umbrella, nullptr);
1198       if (!dylib)
1199         error(Twine("unable to locate library '") + dylibPath +
1200               "' loaded from '" + toString(this) + "' for -flat_namespace");
1201     }
1202   }
1203 }
1204 
1205 // Some versions of XCode ship with .tbd files that don't have the right
1206 // platform settings.
1207 static constexpr std::array<StringRef, 3> skipPlatformChecks{
1208     "/usr/lib/system/libsystem_kernel.dylib",
1209     "/usr/lib/system/libsystem_platform.dylib",
1210     "/usr/lib/system/libsystem_pthread.dylib"};
1211 
1212 DylibFile::DylibFile(const InterfaceFile &interface, DylibFile *umbrella,
1213                      bool isBundleLoader)
1214     : InputFile(DylibKind, interface), refState(RefState::Unreferenced),
1215       isBundleLoader(isBundleLoader) {
1216   // FIXME: Add test for the missing TBD code path.
1217 
1218   if (umbrella == nullptr)
1219     umbrella = this;
1220   this->umbrella = umbrella;
1221 
1222   installName = saver.save(interface.getInstallName());
1223   compatibilityVersion = interface.getCompatibilityVersion().rawValue();
1224   currentVersion = interface.getCurrentVersion().rawValue();
1225 
1226   if (config->printEachFile)
1227     message(toString(this));
1228   inputFiles.insert(this);
1229 
1230   if (!is_contained(skipPlatformChecks, installName) &&
1231       !is_contained(interface.targets(), config->platformInfo.target)) {
1232     error(toString(this) + " is incompatible with " +
1233           std::string(config->platformInfo.target));
1234     return;
1235   }
1236 
1237   checkAppExtensionSafety(interface.isApplicationExtensionSafe());
1238 
1239   exportingFile = isImplicitlyLinked(installName) ? this : umbrella;
1240   auto addSymbol = [&](const Twine &name) -> void {
1241     symbols.push_back(symtab->addDylib(saver.save(name), exportingFile,
1242                                        /*isWeakDef=*/false,
1243                                        /*isTlv=*/false));
1244   };
1245   // TODO(compnerd) filter out symbols based on the target platform
1246   // TODO: handle weak defs, thread locals
1247   for (const auto *symbol : interface.symbols()) {
1248     if (!symbol->getArchitectures().has(config->arch()))
1249       continue;
1250 
1251     if (handleLDSymbol(symbol->getName()))
1252       continue;
1253 
1254     switch (symbol->getKind()) {
1255     case SymbolKind::GlobalSymbol:
1256       addSymbol(symbol->getName());
1257       break;
1258     case SymbolKind::ObjectiveCClass:
1259       // XXX ld64 only creates these symbols when -ObjC is passed in. We may
1260       // want to emulate that.
1261       addSymbol(objc::klass + symbol->getName());
1262       addSymbol(objc::metaclass + symbol->getName());
1263       break;
1264     case SymbolKind::ObjectiveCClassEHType:
1265       addSymbol(objc::ehtype + symbol->getName());
1266       break;
1267     case SymbolKind::ObjectiveCInstanceVariable:
1268       addSymbol(objc::ivar + symbol->getName());
1269       break;
1270     }
1271   }
1272 }
1273 
1274 void DylibFile::parseReexports(const InterfaceFile &interface) {
1275   const InterfaceFile *topLevel =
1276       interface.getParent() == nullptr ? &interface : interface.getParent();
1277   for (const InterfaceFileRef &intfRef : interface.reexportedLibraries()) {
1278     InterfaceFile::const_target_range targets = intfRef.targets();
1279     if (is_contained(skipPlatformChecks, intfRef.getInstallName()) ||
1280         is_contained(targets, config->platformInfo.target))
1281       loadReexport(intfRef.getInstallName(), exportingFile, topLevel);
1282   }
1283 }
1284 
1285 // $ld$ symbols modify the properties/behavior of the library (e.g. its install
1286 // name, compatibility version or hide/add symbols) for specific target
1287 // versions.
1288 bool DylibFile::handleLDSymbol(StringRef originalName) {
1289   if (!originalName.startswith("$ld$"))
1290     return false;
1291 
1292   StringRef action;
1293   StringRef name;
1294   std::tie(action, name) = originalName.drop_front(strlen("$ld$")).split('$');
1295   if (action == "previous")
1296     handleLDPreviousSymbol(name, originalName);
1297   else if (action == "install_name")
1298     handleLDInstallNameSymbol(name, originalName);
1299   return true;
1300 }
1301 
1302 void DylibFile::handleLDPreviousSymbol(StringRef name, StringRef originalName) {
1303   // originalName: $ld$ previous $ <installname> $ <compatversion> $
1304   // <platformstr> $ <startversion> $ <endversion> $ <symbol-name> $
1305   StringRef installName;
1306   StringRef compatVersion;
1307   StringRef platformStr;
1308   StringRef startVersion;
1309   StringRef endVersion;
1310   StringRef symbolName;
1311   StringRef rest;
1312 
1313   std::tie(installName, name) = name.split('$');
1314   std::tie(compatVersion, name) = name.split('$');
1315   std::tie(platformStr, name) = name.split('$');
1316   std::tie(startVersion, name) = name.split('$');
1317   std::tie(endVersion, name) = name.split('$');
1318   std::tie(symbolName, rest) = name.split('$');
1319   // TODO: ld64 contains some logic for non-empty symbolName as well.
1320   if (!symbolName.empty())
1321     return;
1322   unsigned platform;
1323   if (platformStr.getAsInteger(10, platform) ||
1324       platform != static_cast<unsigned>(config->platform()))
1325     return;
1326 
1327   VersionTuple start;
1328   if (start.tryParse(startVersion)) {
1329     warn("failed to parse start version, symbol '" + originalName +
1330          "' ignored");
1331     return;
1332   }
1333   VersionTuple end;
1334   if (end.tryParse(endVersion)) {
1335     warn("failed to parse end version, symbol '" + originalName + "' ignored");
1336     return;
1337   }
1338   if (config->platformInfo.minimum < start ||
1339       config->platformInfo.minimum >= end)
1340     return;
1341 
1342   this->installName = saver.save(installName);
1343 
1344   if (!compatVersion.empty()) {
1345     VersionTuple cVersion;
1346     if (cVersion.tryParse(compatVersion)) {
1347       warn("failed to parse compatibility version, symbol '" + originalName +
1348            "' ignored");
1349       return;
1350     }
1351     compatibilityVersion = encodeVersion(cVersion);
1352   }
1353 }
1354 
1355 void DylibFile::handleLDInstallNameSymbol(StringRef name,
1356                                           StringRef originalName) {
1357   // originalName: $ld$ install_name $ os<version> $ install_name
1358   StringRef condition, installName;
1359   std::tie(condition, installName) = name.split('$');
1360   VersionTuple version;
1361   if (!condition.consume_front("os") || version.tryParse(condition))
1362     warn("failed to parse os version, symbol '" + originalName + "' ignored");
1363   else if (version == config->platformInfo.minimum)
1364     this->installName = saver.save(installName);
1365 }
1366 
1367 void DylibFile::checkAppExtensionSafety(bool dylibIsAppExtensionSafe) const {
1368   if (config->applicationExtension && !dylibIsAppExtensionSafe)
1369     warn("using '-application_extension' with unsafe dylib: " + toString(this));
1370 }
1371 
1372 ArchiveFile::ArchiveFile(std::unique_ptr<object::Archive> &&f)
1373     : InputFile(ArchiveKind, f->getMemoryBufferRef()), file(std::move(f)) {}
1374 
1375 void ArchiveFile::addLazySymbols() {
1376   for (const object::Archive::Symbol &sym : file->symbols())
1377     symtab->addLazy(sym.getName(), this, sym);
1378 }
1379 
1380 static Expected<InputFile *> loadArchiveMember(MemoryBufferRef mb,
1381                                                uint32_t modTime,
1382                                                StringRef archiveName,
1383                                                uint64_t offsetInArchive) {
1384   if (config->zeroModTime)
1385     modTime = 0;
1386 
1387   switch (identify_magic(mb.getBuffer())) {
1388   case file_magic::macho_object:
1389     return make<ObjFile>(mb, modTime, archiveName);
1390   case file_magic::bitcode:
1391     return make<BitcodeFile>(mb, archiveName, offsetInArchive);
1392   default:
1393     return createStringError(inconvertibleErrorCode(),
1394                              mb.getBufferIdentifier() +
1395                                  " has unhandled file type");
1396   }
1397 }
1398 
1399 Error ArchiveFile::fetch(const object::Archive::Child &c, StringRef reason) {
1400   if (!seen.insert(c.getChildOffset()).second)
1401     return Error::success();
1402 
1403   Expected<MemoryBufferRef> mb = c.getMemoryBufferRef();
1404   if (!mb)
1405     return mb.takeError();
1406 
1407   // Thin archives refer to .o files, so --reproduce needs the .o files too.
1408   if (tar && c.getParent()->isThin())
1409     tar->append(relativeToRoot(CHECK(c.getFullName(), this)), mb->getBuffer());
1410 
1411   Expected<TimePoint<std::chrono::seconds>> modTime = c.getLastModified();
1412   if (!modTime)
1413     return modTime.takeError();
1414 
1415   Expected<InputFile *> file =
1416       loadArchiveMember(*mb, toTimeT(*modTime), getName(), c.getChildOffset());
1417 
1418   if (!file)
1419     return file.takeError();
1420 
1421   inputFiles.insert(*file);
1422   printArchiveMemberLoad(reason, *file);
1423   return Error::success();
1424 }
1425 
1426 void ArchiveFile::fetch(const object::Archive::Symbol &sym) {
1427   object::Archive::Child c =
1428       CHECK(sym.getMember(), toString(this) +
1429                                  ": could not get the member defining symbol " +
1430                                  toMachOString(sym));
1431 
1432   // `sym` is owned by a LazySym, which will be replace<>()d by make<ObjFile>
1433   // and become invalid after that call. Copy it to the stack so we can refer
1434   // to it later.
1435   const object::Archive::Symbol symCopy = sym;
1436 
1437   // ld64 doesn't demangle sym here even with -demangle.
1438   // Match that: intentionally don't call toMachOString().
1439   if (Error e = fetch(c, symCopy.getName()))
1440     error(toString(this) + ": could not get the member defining symbol " +
1441           toMachOString(symCopy) + ": " + toString(std::move(e)));
1442 }
1443 
1444 static macho::Symbol *createBitcodeSymbol(const lto::InputFile::Symbol &objSym,
1445                                           BitcodeFile &file) {
1446   StringRef name = saver.save(objSym.getName());
1447 
1448   // TODO: support weak references
1449   if (objSym.isUndefined())
1450     return symtab->addUndefined(name, &file, /*isWeakRef=*/false);
1451 
1452   // TODO: Write a test demonstrating why computing isPrivateExtern before
1453   // LTO compilation is important.
1454   bool isPrivateExtern = false;
1455   switch (objSym.getVisibility()) {
1456   case GlobalValue::HiddenVisibility:
1457     isPrivateExtern = true;
1458     break;
1459   case GlobalValue::ProtectedVisibility:
1460     error(name + " has protected visibility, which is not supported by Mach-O");
1461     break;
1462   case GlobalValue::DefaultVisibility:
1463     break;
1464   }
1465 
1466   if (objSym.isCommon())
1467     return symtab->addCommon(name, &file, objSym.getCommonSize(),
1468                              objSym.getCommonAlignment(), isPrivateExtern);
1469 
1470   return symtab->addDefined(name, &file, /*isec=*/nullptr, /*value=*/0,
1471                             /*size=*/0, objSym.isWeak(), isPrivateExtern,
1472                             /*isThumb=*/false,
1473                             /*isReferencedDynamically=*/false,
1474                             /*noDeadStrip=*/false,
1475                             /*isWeakDefCanBeHidden=*/false);
1476 }
1477 
1478 BitcodeFile::BitcodeFile(MemoryBufferRef mb, StringRef archiveName,
1479                          uint64_t offsetInArchive)
1480     : InputFile(BitcodeKind, mb) {
1481   std::string path = mb.getBufferIdentifier().str();
1482   // ThinLTO assumes that all MemoryBufferRefs given to it have a unique
1483   // name. If two members with the same name are provided, this causes a
1484   // collision and ThinLTO can't proceed.
1485   // So, we append the archive name to disambiguate two members with the same
1486   // name from multiple different archives, and offset within the archive to
1487   // disambiguate two members of the same name from a single archive.
1488   MemoryBufferRef mbref(
1489       mb.getBuffer(),
1490       saver.save(archiveName.empty() ? path
1491                                      : archiveName + sys::path::filename(path) +
1492                                            utostr(offsetInArchive)));
1493 
1494   obj = check(lto::InputFile::create(mbref));
1495 
1496   // Convert LTO Symbols to LLD Symbols in order to perform resolution. The
1497   // "winning" symbol will then be marked as Prevailing at LTO compilation
1498   // time.
1499   for (const lto::InputFile::Symbol &objSym : obj->symbols())
1500     symbols.push_back(createBitcodeSymbol(objSym, *this));
1501 }
1502 
1503 template void ObjFile::parse<LP64>();
1504