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