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 "Target.h"
57 
58 #include "lld/Common/DWARF.h"
59 #include "lld/Common/ErrorHandler.h"
60 #include "lld/Common/Memory.h"
61 #include "lld/Common/Reproduce.h"
62 #include "llvm/ADT/iterator.h"
63 #include "llvm/BinaryFormat/MachO.h"
64 #include "llvm/LTO/LTO.h"
65 #include "llvm/Support/Endian.h"
66 #include "llvm/Support/MemoryBuffer.h"
67 #include "llvm/Support/Path.h"
68 #include "llvm/Support/TarWriter.h"
69 #include "llvm/TextAPI/Architecture.h"
70 #include "llvm/TextAPI/InterfaceFile.h"
71 
72 using namespace llvm;
73 using namespace llvm::MachO;
74 using namespace llvm::support::endian;
75 using namespace llvm::sys;
76 using namespace lld;
77 using namespace lld::macho;
78 
79 // Returns "<internal>", "foo.a(bar.o)", or "baz.o".
80 std::string lld::toString(const InputFile *f) {
81   if (!f)
82     return "<internal>";
83 
84   // Multiple dylibs can be defined in one .tbd file.
85   if (auto dylibFile = dyn_cast<DylibFile>(f))
86     if (f->getName().endswith(".tbd"))
87       return (f->getName() + "(" + dylibFile->dylibName + ")").str();
88 
89   if (f->archiveName.empty())
90     return std::string(f->getName());
91   return (f->archiveName + "(" + path::filename(f->getName()) + ")").str();
92 }
93 
94 SetVector<InputFile *> macho::inputFiles;
95 std::unique_ptr<TarWriter> macho::tar;
96 int InputFile::idCount = 0;
97 
98 static VersionTuple decodeVersion(uint32_t version) {
99   unsigned major = version >> 16;
100   unsigned minor = (version >> 8) & 0xffu;
101   unsigned subMinor = version & 0xffu;
102   return VersionTuple(major, minor, subMinor);
103 }
104 
105 template <class LP>
106 static Optional<PlatformInfo> getPlatformInfo(const InputFile *input) {
107   if (!isa<ObjFile>(input) && !isa<DylibFile>(input))
108     return None;
109 
110   using Header = typename LP::mach_header;
111   auto *hdr = reinterpret_cast<const Header *>(input->mb.getBufferStart());
112 
113   PlatformInfo platformInfo;
114   if (const auto *cmd =
115           findCommand<build_version_command>(hdr, LC_BUILD_VERSION)) {
116     platformInfo.target.Platform = static_cast<PlatformKind>(cmd->platform);
117     platformInfo.minimum = decodeVersion(cmd->minos);
118     return platformInfo;
119   }
120   if (const auto *cmd = findCommand<version_min_command>(
121           hdr, LC_VERSION_MIN_MACOSX, LC_VERSION_MIN_IPHONEOS,
122           LC_VERSION_MIN_TVOS, LC_VERSION_MIN_WATCHOS)) {
123     switch (cmd->cmd) {
124     case LC_VERSION_MIN_MACOSX:
125       platformInfo.target.Platform = PlatformKind::macOS;
126       break;
127     case LC_VERSION_MIN_IPHONEOS:
128       platformInfo.target.Platform = PlatformKind::iOS;
129       break;
130     case LC_VERSION_MIN_TVOS:
131       platformInfo.target.Platform = PlatformKind::tvOS;
132       break;
133     case LC_VERSION_MIN_WATCHOS:
134       platformInfo.target.Platform = PlatformKind::watchOS;
135       break;
136     }
137     platformInfo.minimum = decodeVersion(cmd->version);
138     return platformInfo;
139   }
140 
141   return None;
142 }
143 
144 template <class LP> static bool checkCompatibility(const InputFile *input) {
145   Optional<PlatformInfo> platformInfo = getPlatformInfo<LP>(input);
146   if (!platformInfo)
147     return true;
148   // TODO: Correctly detect simulator platforms or relax this check.
149   if (config->platformInfo.target.Platform != platformInfo->target.Platform) {
150     error(toString(input) + " has platform " +
151           getPlatformName(platformInfo->target.Platform) +
152           Twine(", which is different from target platform ") +
153           getPlatformName(config->platformInfo.target.Platform));
154     return false;
155   }
156   if (platformInfo->minimum >= config->platformInfo.minimum)
157     return true;
158   error(toString(input) + " has version " +
159         platformInfo->minimum.getAsString() +
160         ", which is incompatible with target version of " +
161         config->platformInfo.minimum.getAsString());
162   return false;
163 }
164 
165 // Open a given file path and return it as a memory-mapped file.
166 Optional<MemoryBufferRef> macho::readFile(StringRef path) {
167   // Open a file.
168   ErrorOr<std::unique_ptr<MemoryBuffer>> mbOrErr = MemoryBuffer::getFile(path);
169   if (std::error_code ec = mbOrErr.getError()) {
170     error("cannot open " + path + ": " + ec.message());
171     return None;
172   }
173 
174   std::unique_ptr<MemoryBuffer> &mb = *mbOrErr;
175   MemoryBufferRef mbref = mb->getMemBufferRef();
176   make<std::unique_ptr<MemoryBuffer>>(std::move(mb)); // take mb ownership
177 
178   // If this is a regular non-fat file, return it.
179   const char *buf = mbref.getBufferStart();
180   const auto *hdr = reinterpret_cast<const fat_header *>(buf);
181   if (mbref.getBufferSize() < sizeof(uint32_t) ||
182       read32be(&hdr->magic) != FAT_MAGIC) {
183     if (tar)
184       tar->append(relativeToRoot(path), mbref.getBuffer());
185     return mbref;
186   }
187 
188   // Object files and archive files may be fat files, which contains
189   // multiple real files for different CPU ISAs. Here, we search for a
190   // file that matches with the current link target and returns it as
191   // a MemoryBufferRef.
192   const auto *arch = reinterpret_cast<const fat_arch *>(buf + sizeof(*hdr));
193 
194   for (uint32_t i = 0, n = read32be(&hdr->nfat_arch); i < n; ++i) {
195     if (reinterpret_cast<const char *>(arch + i + 1) >
196         buf + mbref.getBufferSize()) {
197       error(path + ": fat_arch struct extends beyond end of file");
198       return None;
199     }
200 
201     if (read32be(&arch[i].cputype) != target->cpuType ||
202         read32be(&arch[i].cpusubtype) != target->cpuSubtype)
203       continue;
204 
205     uint32_t offset = read32be(&arch[i].offset);
206     uint32_t size = read32be(&arch[i].size);
207     if (offset + size > mbref.getBufferSize())
208       error(path + ": slice extends beyond end of file");
209     if (tar)
210       tar->append(relativeToRoot(path), mbref.getBuffer());
211     return MemoryBufferRef(StringRef(buf + offset, size), path.copy(bAlloc));
212   }
213 
214   error("unable to find matching architecture in " + path);
215   return None;
216 }
217 
218 InputFile::InputFile(Kind kind, const InterfaceFile &interface)
219     : id(idCount++), fileKind(kind), name(saver.save(interface.getPath())) {}
220 
221 template <class Section>
222 void ObjFile::parseSections(ArrayRef<Section> sections) {
223   subsections.reserve(sections.size());
224   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
225 
226   for (const Section &sec : sections) {
227     InputSection *isec = make<InputSection>();
228     isec->file = this;
229     isec->name =
230         StringRef(sec.sectname, strnlen(sec.sectname, sizeof(sec.sectname)));
231     isec->segname =
232         StringRef(sec.segname, strnlen(sec.segname, sizeof(sec.segname)));
233     isec->data = {isZeroFill(sec.flags) ? nullptr : buf + sec.offset,
234                   static_cast<size_t>(sec.size)};
235     if (sec.align >= 32)
236       error("alignment " + std::to_string(sec.align) + " of section " +
237             isec->name + " is too large");
238     else
239       isec->align = 1 << sec.align;
240     isec->flags = sec.flags;
241 
242     if (!(isDebugSection(isec->flags) &&
243           isec->segname == segment_names::dwarf)) {
244       subsections.push_back({{0, isec}});
245     } else {
246       // Instead of emitting DWARF sections, we emit STABS symbols to the
247       // object files that contain them. We filter them out early to avoid
248       // parsing their relocations unnecessarily. But we must still push an
249       // empty map to ensure the indices line up for the remaining sections.
250       subsections.push_back({});
251       debugSections.push_back(isec);
252     }
253   }
254 }
255 
256 // Find the subsection corresponding to the greatest section offset that is <=
257 // that of the given offset.
258 //
259 // offset: an offset relative to the start of the original InputSection (before
260 // any subsection splitting has occurred). It will be updated to represent the
261 // same location as an offset relative to the start of the containing
262 // subsection.
263 static InputSection *findContainingSubsection(SubsectionMap &map,
264                                               uint64_t *offset) {
265   auto it = std::prev(llvm::upper_bound(
266       map, *offset, [](uint64_t value, SubsectionEntry subsecEntry) {
267         return value < subsecEntry.offset;
268       }));
269   *offset -= it->offset;
270   return it->isec;
271 }
272 
273 template <class Section>
274 static bool validateRelocationInfo(InputFile *file, const Section &sec,
275                                    relocation_info rel) {
276   const RelocAttrs &relocAttrs = target->getRelocAttrs(rel.r_type);
277   bool valid = true;
278   auto message = [relocAttrs, file, sec, rel, &valid](const Twine &diagnostic) {
279     valid = false;
280     return (relocAttrs.name + " relocation " + diagnostic + " at offset " +
281             std::to_string(rel.r_address) + " of " + sec.segname + "," +
282             sec.sectname + " in " + toString(file))
283         .str();
284   };
285 
286   if (!relocAttrs.hasAttr(RelocAttrBits::LOCAL) && !rel.r_extern)
287     error(message("must be extern"));
288   if (relocAttrs.hasAttr(RelocAttrBits::PCREL) != rel.r_pcrel)
289     error(message(Twine("must ") + (rel.r_pcrel ? "not " : "") +
290                   "be PC-relative"));
291   if (isThreadLocalVariables(sec.flags) &&
292       !relocAttrs.hasAttr(RelocAttrBits::UNSIGNED))
293     error(message("not allowed in thread-local section, must be UNSIGNED"));
294   if (rel.r_length < 2 || rel.r_length > 3 ||
295       !relocAttrs.hasAttr(static_cast<RelocAttrBits>(1 << rel.r_length))) {
296     static SmallVector<StringRef, 4> widths{"0", "4", "8", "4 or 8"};
297     error(message("has width " + std::to_string(1 << rel.r_length) +
298                   " bytes, but must be " +
299                   widths[(static_cast<int>(relocAttrs.bits) >> 2) & 3] +
300                   " bytes"));
301   }
302   return valid;
303 }
304 
305 template <class Section>
306 void ObjFile::parseRelocations(ArrayRef<Section> sectionHeaders,
307                                const Section &sec, SubsectionMap &subsecMap) {
308   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
309   ArrayRef<relocation_info> relInfos(
310       reinterpret_cast<const relocation_info *>(buf + sec.reloff), sec.nreloc);
311 
312   for (size_t i = 0; i < relInfos.size(); i++) {
313     // Paired relocations serve as Mach-O's method for attaching a
314     // supplemental datum to a primary relocation record. ELF does not
315     // need them because the *_RELOC_RELA records contain the extra
316     // addend field, vs. *_RELOC_REL which omit the addend.
317     //
318     // The {X86_64,ARM64}_RELOC_SUBTRACTOR record holds the subtrahend,
319     // and the paired *_RELOC_UNSIGNED record holds the minuend. The
320     // datum for each is a symbolic address. The result is the offset
321     // between two addresses.
322     //
323     // The ARM64_RELOC_ADDEND record holds the addend, and the paired
324     // ARM64_RELOC_BRANCH26 or ARM64_RELOC_PAGE21/PAGEOFF12 holds the
325     // base symbolic address.
326     //
327     // Note: X86 does not use *_RELOC_ADDEND because it can embed an
328     // addend into the instruction stream. On X86, a relocatable address
329     // field always occupies an entire contiguous sequence of byte(s),
330     // so there is no need to merge opcode bits with address
331     // bits. Therefore, it's easy and convenient to store addends in the
332     // instruction-stream bytes that would otherwise contain zeroes. By
333     // contrast, RISC ISAs such as ARM64 mix opcode bits with with
334     // address bits so that bitwise arithmetic is necessary to extract
335     // and insert them. Storing addends in the instruction stream is
336     // possible, but inconvenient and more costly at link time.
337 
338     int64_t pairedAddend = 0;
339     relocation_info relInfo = relInfos[i];
340     if (target->hasAttr(relInfo.r_type, RelocAttrBits::ADDEND)) {
341       pairedAddend = SignExtend64<24>(relInfo.r_symbolnum);
342       relInfo = relInfos[++i];
343     }
344     assert(i < relInfos.size());
345     if (!validateRelocationInfo(this, sec, relInfo))
346       continue;
347     if (relInfo.r_address & R_SCATTERED)
348       fatal("TODO: Scattered relocations not supported");
349 
350     bool isSubtrahend =
351         target->hasAttr(relInfo.r_type, RelocAttrBits::SUBTRAHEND);
352     int64_t embeddedAddend = target->getEmbeddedAddend(mb, sec.offset, relInfo);
353     assert(!(embeddedAddend && pairedAddend));
354     int64_t totalAddend = pairedAddend + embeddedAddend;
355     Reloc r;
356     r.type = relInfo.r_type;
357     r.pcrel = relInfo.r_pcrel;
358     r.length = relInfo.r_length;
359     r.offset = relInfo.r_address;
360     if (relInfo.r_extern) {
361       r.referent = symbols[relInfo.r_symbolnum];
362       r.addend = isSubtrahend ? 0 : totalAddend;
363     } else {
364       assert(!isSubtrahend);
365       const Section &referentSec = sectionHeaders[relInfo.r_symbolnum - 1];
366       uint64_t referentOffset;
367       if (relInfo.r_pcrel) {
368         // The implicit addend for pcrel section relocations is the pcrel offset
369         // in terms of the addresses in the input file. Here we adjust it so
370         // that it describes the offset from the start of the referent section.
371         // FIXME This logic was written around x86_64 behavior -- ARM64 doesn't
372         // have pcrel section relocations. We may want to factor this out into
373         // the arch-specific .cpp file.
374         assert(target->hasAttr(r.type, RelocAttrBits::BYTE4));
375         referentOffset =
376             sec.addr + relInfo.r_address + 4 + totalAddend - referentSec.addr;
377       } else {
378         // The addend for a non-pcrel relocation is its absolute address.
379         referentOffset = totalAddend - referentSec.addr;
380       }
381       SubsectionMap &referentSubsecMap = subsections[relInfo.r_symbolnum - 1];
382       r.referent = findContainingSubsection(referentSubsecMap, &referentOffset);
383       r.addend = referentOffset;
384     }
385 
386     InputSection *subsec = findContainingSubsection(subsecMap, &r.offset);
387     subsec->relocs.push_back(r);
388 
389     if (isSubtrahend) {
390       relocation_info minuendInfo = relInfos[++i];
391       // SUBTRACTOR relocations should always be followed by an UNSIGNED one
392       // attached to the same address.
393       assert(target->hasAttr(minuendInfo.r_type, RelocAttrBits::UNSIGNED) &&
394              relInfo.r_address == minuendInfo.r_address);
395       Reloc p;
396       p.type = minuendInfo.r_type;
397       if (minuendInfo.r_extern) {
398         p.referent = symbols[minuendInfo.r_symbolnum];
399         p.addend = totalAddend;
400       } else {
401         uint64_t referentOffset =
402             totalAddend - sectionHeaders[minuendInfo.r_symbolnum - 1].addr;
403         SubsectionMap &referentSubsecMap =
404             subsections[minuendInfo.r_symbolnum - 1];
405         p.referent =
406             findContainingSubsection(referentSubsecMap, &referentOffset);
407         p.addend = referentOffset;
408       }
409       subsec->relocs.push_back(p);
410     }
411   }
412 }
413 
414 template <class NList>
415 static macho::Symbol *createDefined(const NList &sym, StringRef name,
416                                     InputSection *isec, uint64_t value,
417                                     uint64_t size) {
418   // Symbol scope is determined by sym.n_type & (N_EXT | N_PEXT):
419   // N_EXT: Global symbols
420   // N_EXT | N_PEXT: Linkage unit (think: dylib) scoped
421   // N_PEXT: Does not occur in input files in practice,
422   //         a private extern must be external.
423   // 0: Translation-unit scoped. These are not in the symbol table.
424 
425   if (sym.n_type & (N_EXT | N_PEXT)) {
426     assert((sym.n_type & N_EXT) && "invalid input");
427     return symtab->addDefined(name, isec->file, isec, value, size,
428                               sym.n_desc & N_WEAK_DEF, sym.n_type & N_PEXT);
429   }
430   return make<Defined>(name, isec->file, isec, value, size,
431                        sym.n_desc & N_WEAK_DEF,
432                        /*isExternal=*/false, /*isPrivateExtern=*/false);
433 }
434 
435 // Absolute symbols are defined symbols that do not have an associated
436 // InputSection. They cannot be weak.
437 template <class NList>
438 static macho::Symbol *createAbsolute(const NList &sym, InputFile *file,
439                                      StringRef name) {
440   if (sym.n_type & (N_EXT | N_PEXT)) {
441     assert((sym.n_type & N_EXT) && "invalid input");
442     return symtab->addDefined(name, file, nullptr, sym.n_value, /*size=*/0,
443                               /*isWeakDef=*/false, sym.n_type & N_PEXT);
444   }
445   return make<Defined>(name, file, nullptr, sym.n_value, /*size=*/0,
446                        /*isWeakDef=*/false,
447                        /*isExternal=*/false, /*isPrivateExtern=*/false);
448 }
449 
450 template <class NList>
451 macho::Symbol *ObjFile::parseNonSectionSymbol(const NList &sym,
452                                               StringRef name) {
453   uint8_t type = sym.n_type & N_TYPE;
454   switch (type) {
455   case N_UNDF:
456     return sym.n_value == 0
457                ? symtab->addUndefined(name, this, sym.n_desc & N_WEAK_REF)
458                : symtab->addCommon(name, this, sym.n_value,
459                                    1 << GET_COMM_ALIGN(sym.n_desc),
460                                    sym.n_type & N_PEXT);
461   case N_ABS:
462     return createAbsolute(sym, this, name);
463   case N_PBUD:
464   case N_INDR:
465     error("TODO: support symbols of type " + std::to_string(type));
466     return nullptr;
467   case N_SECT:
468     llvm_unreachable(
469         "N_SECT symbols should not be passed to parseNonSectionSymbol");
470   default:
471     llvm_unreachable("invalid symbol type");
472   }
473 }
474 
475 template <class LP>
476 void ObjFile::parseSymbols(ArrayRef<typename LP::section> sectionHeaders,
477                            ArrayRef<typename LP::nlist> nList,
478                            const char *strtab, bool subsectionsViaSymbols) {
479   using NList = typename LP::nlist;
480 
481   // Groups indices of the symbols by the sections that contain them.
482   std::vector<std::vector<uint32_t>> symbolsBySection(subsections.size());
483   symbols.resize(nList.size());
484   for (uint32_t i = 0; i < nList.size(); ++i) {
485     const NList &sym = nList[i];
486     StringRef name = strtab + sym.n_strx;
487     if ((sym.n_type & N_TYPE) == N_SECT) {
488       SubsectionMap &subsecMap = subsections[sym.n_sect - 1];
489       // parseSections() may have chosen not to parse this section.
490       if (subsecMap.empty())
491         continue;
492       symbolsBySection[sym.n_sect - 1].push_back(i);
493     } else {
494       symbols[i] = parseNonSectionSymbol(sym, name);
495     }
496   }
497 
498   // Calculate symbol sizes and create subsections by splitting the sections
499   // along symbol boundaries.
500   for (size_t i = 0; i < subsections.size(); ++i) {
501     SubsectionMap &subsecMap = subsections[i];
502     if (subsecMap.empty())
503       continue;
504 
505     std::vector<uint32_t> &symbolIndices = symbolsBySection[i];
506     llvm::sort(symbolIndices, [&](uint32_t lhs, uint32_t rhs) {
507       return nList[lhs].n_value < nList[rhs].n_value;
508     });
509     uint64_t sectionAddr = sectionHeaders[i].addr;
510 
511     // We populate subsecMap by repeatedly splitting the last (highest address)
512     // subsection.
513     SubsectionEntry subsecEntry = subsecMap.back();
514     for (size_t j = 0; j < symbolIndices.size(); ++j) {
515       uint32_t symIndex = symbolIndices[j];
516       const NList &sym = nList[symIndex];
517       StringRef name = strtab + sym.n_strx;
518       InputSection *isec = subsecEntry.isec;
519 
520       uint64_t subsecAddr = sectionAddr + subsecEntry.offset;
521       uint64_t symbolOffset = sym.n_value - subsecAddr;
522       uint64_t symbolSize =
523           j + 1 < symbolIndices.size()
524               ? nList[symbolIndices[j + 1]].n_value - sym.n_value
525               : isec->data.size() - symbolOffset;
526       // There are 3 cases where we do not need to create a new subsection:
527       //   1. If the input file does not use subsections-via-symbols.
528       //   2. Multiple symbols at the same address only induce one subsection.
529       //   3. Alternative entry points do not induce new subsections.
530       if (!subsectionsViaSymbols || symbolOffset == 0 ||
531           sym.n_desc & N_ALT_ENTRY) {
532         symbols[symIndex] =
533             createDefined(sym, name, isec, symbolOffset, symbolSize);
534         continue;
535       }
536 
537       auto *nextIsec = make<InputSection>(*isec);
538       nextIsec->data = isec->data.slice(symbolOffset);
539       isec->data = isec->data.slice(0, symbolOffset);
540 
541       // By construction, the symbol will be at offset zero in the new
542       // subsection.
543       symbols[symIndex] =
544           createDefined(sym, name, nextIsec, /*value=*/0, symbolSize);
545       // TODO: ld64 appears to preserve the original alignment as well as each
546       // subsection's offset from the last aligned address. We should consider
547       // emulating that behavior.
548       nextIsec->align = MinAlign(isec->align, sym.n_value);
549       subsecMap.push_back({sym.n_value - sectionAddr, nextIsec});
550       subsecEntry = subsecMap.back();
551     }
552   }
553 }
554 
555 OpaqueFile::OpaqueFile(MemoryBufferRef mb, StringRef segName,
556                        StringRef sectName)
557     : InputFile(OpaqueKind, mb) {
558   InputSection *isec = make<InputSection>();
559   isec->file = this;
560   isec->name = sectName.take_front(16);
561   isec->segname = segName.take_front(16);
562   const auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
563   isec->data = {buf, mb.getBufferSize()};
564   subsections.push_back({{0, isec}});
565 }
566 
567 ObjFile::ObjFile(MemoryBufferRef mb, uint32_t modTime, StringRef archiveName)
568     : InputFile(ObjKind, mb), modTime(modTime) {
569   this->archiveName = std::string(archiveName);
570   if (target->wordSize == 8)
571     parse<LP64>();
572   else
573     parse<ILP32>();
574 }
575 
576 template <class LP> void ObjFile::parse() {
577   using Header = typename LP::mach_header;
578   using SegmentCommand = typename LP::segment_command;
579   using Section = typename LP::section;
580   using NList = typename LP::nlist;
581 
582   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
583   auto *hdr = reinterpret_cast<const Header *>(mb.getBufferStart());
584 
585   Architecture arch = getArchitectureFromCpuType(hdr->cputype, hdr->cpusubtype);
586   if (arch != config->platformInfo.target.Arch) {
587     error(toString(this) + " has architecture " + getArchitectureName(arch) +
588           " which is incompatible with target architecture " +
589           getArchitectureName(config->platformInfo.target.Arch));
590     return;
591   }
592 
593   if (!checkCompatibility<LP>(this))
594     return;
595 
596   if (const load_command *cmd = findCommand(hdr, LC_LINKER_OPTION)) {
597     auto *c = reinterpret_cast<const linker_option_command *>(cmd);
598     StringRef data{reinterpret_cast<const char *>(c + 1),
599                    c->cmdsize - sizeof(linker_option_command)};
600     parseLCLinkerOption(this, c->count, data);
601   }
602 
603   ArrayRef<Section> sectionHeaders;
604   if (const load_command *cmd = findCommand(hdr, LP::segmentLCType)) {
605     auto *c = reinterpret_cast<const SegmentCommand *>(cmd);
606     sectionHeaders =
607         ArrayRef<Section>{reinterpret_cast<const Section *>(c + 1), c->nsects};
608     parseSections(sectionHeaders);
609   }
610 
611   // TODO: Error on missing LC_SYMTAB?
612   if (const load_command *cmd = findCommand(hdr, LC_SYMTAB)) {
613     auto *c = reinterpret_cast<const symtab_command *>(cmd);
614     ArrayRef<NList> nList(reinterpret_cast<const NList *>(buf + c->symoff),
615                           c->nsyms);
616     const char *strtab = reinterpret_cast<const char *>(buf) + c->stroff;
617     bool subsectionsViaSymbols = hdr->flags & MH_SUBSECTIONS_VIA_SYMBOLS;
618     parseSymbols<LP>(sectionHeaders, nList, strtab, subsectionsViaSymbols);
619   }
620 
621   // The relocations may refer to the symbols, so we parse them after we have
622   // parsed all the symbols.
623   for (size_t i = 0, n = subsections.size(); i < n; ++i)
624     if (!subsections[i].empty())
625       parseRelocations(sectionHeaders, sectionHeaders[i], subsections[i]);
626 
627   parseDebugInfo();
628 }
629 
630 void ObjFile::parseDebugInfo() {
631   std::unique_ptr<DwarfObject> dObj = DwarfObject::create(this);
632   if (!dObj)
633     return;
634 
635   auto *ctx = make<DWARFContext>(
636       std::move(dObj), "",
637       [&](Error err) {
638         warn(toString(this) + ": " + toString(std::move(err)));
639       },
640       [&](Error warning) {
641         warn(toString(this) + ": " + toString(std::move(warning)));
642       });
643 
644   // TODO: Since object files can contain a lot of DWARF info, we should verify
645   // that we are parsing just the info we need
646   const DWARFContext::compile_unit_range &units = ctx->compile_units();
647   // FIXME: There can be more than one compile unit per object file. See
648   // PR48637.
649   auto it = units.begin();
650   compileUnit = it->get();
651 }
652 
653 // The path can point to either a dylib or a .tbd file.
654 static Optional<DylibFile *> loadDylib(StringRef path, DylibFile *umbrella) {
655   Optional<MemoryBufferRef> mbref = readFile(path);
656   if (!mbref) {
657     error("could not read dylib file at " + path);
658     return {};
659   }
660   return loadDylib(*mbref, umbrella);
661 }
662 
663 // TBD files are parsed into a series of TAPI documents (InterfaceFiles), with
664 // the first document storing child pointers to the rest of them. When we are
665 // processing a given TBD file, we store that top-level document in
666 // currentTopLevelTapi. When processing re-exports, we search its children for
667 // potentially matching documents in the same TBD file. Note that the children
668 // themselves don't point to further documents, i.e. this is a two-level tree.
669 //
670 // Re-exports can either refer to on-disk files, or to documents within .tbd
671 // files.
672 static Optional<DylibFile *>
673 findDylib(StringRef path, DylibFile *umbrella,
674           const InterfaceFile *currentTopLevelTapi) {
675   if (path::is_absolute(path, path::Style::posix))
676     for (StringRef root : config->systemLibraryRoots)
677       if (Optional<std::string> dylibPath =
678               resolveDylibPath((root + path).str()))
679         return loadDylib(*dylibPath, umbrella);
680 
681   // TODO: Expand @loader_path, @executable_path, @rpath etc, handle -dylib_path
682 
683   if (currentTopLevelTapi) {
684     for (InterfaceFile &child :
685          make_pointee_range(currentTopLevelTapi->documents())) {
686       assert(child.documents().empty());
687       if (path == child.getInstallName())
688         return make<DylibFile>(child, umbrella);
689     }
690   }
691 
692   if (Optional<std::string> dylibPath = resolveDylibPath(path))
693     return loadDylib(*dylibPath, umbrella);
694 
695   return {};
696 }
697 
698 // If a re-exported dylib is public (lives in /usr/lib or
699 // /System/Library/Frameworks), then it is considered implicitly linked: we
700 // should bind to its symbols directly instead of via the re-exporting umbrella
701 // library.
702 static bool isImplicitlyLinked(StringRef path) {
703   if (!config->implicitDylibs)
704     return false;
705 
706   if (path::parent_path(path) == "/usr/lib")
707     return true;
708 
709   // Match /System/Library/Frameworks/$FOO.framework/**/$FOO
710   if (path.consume_front("/System/Library/Frameworks/")) {
711     StringRef frameworkName = path.take_until([](char c) { return c == '.'; });
712     return path::filename(path) == frameworkName;
713   }
714 
715   return false;
716 }
717 
718 void loadReexport(StringRef path, DylibFile *umbrella,
719                   const InterfaceFile *currentTopLevelTapi) {
720   Optional<DylibFile *> reexport =
721       findDylib(path, umbrella, currentTopLevelTapi);
722   if (!reexport)
723     error("unable to locate re-export with install name " + path);
724   else if (isImplicitlyLinked(path))
725     inputFiles.insert(*reexport);
726 }
727 
728 DylibFile::DylibFile(MemoryBufferRef mb, DylibFile *umbrella,
729                      bool isBundleLoader)
730     : InputFile(DylibKind, mb), refState(RefState::Unreferenced),
731       isBundleLoader(isBundleLoader) {
732   assert(!isBundleLoader || !umbrella);
733   if (umbrella == nullptr)
734     umbrella = this;
735 
736   if (target->wordSize == 8)
737     parse<LP64>(umbrella);
738   else
739     parse<ILP32>(umbrella);
740 }
741 
742 template <class LP> void DylibFile::parse(DylibFile *umbrella) {
743   using Header = typename LP::mach_header;
744   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
745   auto *hdr = reinterpret_cast<const Header *>(mb.getBufferStart());
746 
747   // Initialize dylibName.
748   if (const load_command *cmd = findCommand(hdr, LC_ID_DYLIB)) {
749     auto *c = reinterpret_cast<const dylib_command *>(cmd);
750     currentVersion = read32le(&c->dylib.current_version);
751     compatibilityVersion = read32le(&c->dylib.compatibility_version);
752     dylibName = reinterpret_cast<const char *>(cmd) + read32le(&c->dylib.name);
753   } else if (!isBundleLoader) {
754     // macho_executable and macho_bundle don't have LC_ID_DYLIB,
755     // so it's OK.
756     error("dylib " + toString(this) + " missing LC_ID_DYLIB load command");
757     return;
758   }
759 
760   if (!checkCompatibility<LP>(this))
761     return;
762 
763   // Initialize symbols.
764   DylibFile *exportingFile = isImplicitlyLinked(dylibName) ? this : umbrella;
765   if (const load_command *cmd = findCommand(hdr, LC_DYLD_INFO_ONLY)) {
766     auto *c = reinterpret_cast<const dyld_info_command *>(cmd);
767     parseTrie(buf + c->export_off, c->export_size,
768               [&](const Twine &name, uint64_t flags) {
769                 bool isWeakDef = flags & EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION;
770                 bool isTlv = flags & EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL;
771                 symbols.push_back(symtab->addDylib(
772                     saver.save(name), exportingFile, isWeakDef, isTlv));
773               });
774   } else {
775     error("LC_DYLD_INFO_ONLY not found in " + toString(this));
776     return;
777   }
778 
779   const uint8_t *p = reinterpret_cast<const uint8_t *>(hdr) + sizeof(Header);
780   for (uint32_t i = 0, n = hdr->ncmds; i < n; ++i) {
781     auto *cmd = reinterpret_cast<const load_command *>(p);
782     p += cmd->cmdsize;
783 
784     if (!(hdr->flags & MH_NO_REEXPORTED_DYLIBS) &&
785         cmd->cmd == LC_REEXPORT_DYLIB) {
786       const auto *c = reinterpret_cast<const dylib_command *>(cmd);
787       StringRef reexportPath =
788           reinterpret_cast<const char *>(c) + read32le(&c->dylib.name);
789       loadReexport(reexportPath, exportingFile, nullptr);
790     }
791 
792     // FIXME: What about LC_LOAD_UPWARD_DYLIB, LC_LAZY_LOAD_DYLIB,
793     // LC_LOAD_WEAK_DYLIB, LC_REEXPORT_DYLIB (..are reexports from dylibs with
794     // MH_NO_REEXPORTED_DYLIBS loaded for -flat_namespace)?
795     if (config->namespaceKind == NamespaceKind::flat &&
796         cmd->cmd == LC_LOAD_DYLIB) {
797       const auto *c = reinterpret_cast<const dylib_command *>(cmd);
798       StringRef dylibPath =
799           reinterpret_cast<const char *>(c) + read32le(&c->dylib.name);
800       Optional<DylibFile *> dylib = findDylib(dylibPath, umbrella, nullptr);
801       if (!dylib)
802         error(Twine("unable to locate library '") + dylibPath +
803               "' loaded from '" + toString(this) + "' for -flat_namespace");
804     }
805   }
806 }
807 
808 DylibFile::DylibFile(const InterfaceFile &interface, DylibFile *umbrella,
809                      bool isBundleLoader)
810     : InputFile(DylibKind, interface), refState(RefState::Unreferenced),
811       isBundleLoader(isBundleLoader) {
812   // FIXME: Add test for the missing TBD code path.
813 
814   if (umbrella == nullptr)
815     umbrella = this;
816 
817   dylibName = saver.save(interface.getInstallName());
818   compatibilityVersion = interface.getCompatibilityVersion().rawValue();
819   currentVersion = interface.getCurrentVersion().rawValue();
820 
821   // Some versions of XCode ship with .tbd files that don't have the right
822   // platform settings.
823   static constexpr std::array<StringRef, 3> skipPlatformChecks{
824       "/usr/lib/system/libsystem_kernel.dylib",
825       "/usr/lib/system/libsystem_platform.dylib",
826       "/usr/lib/system/libsystem_pthread.dylib"};
827 
828   if (!is_contained(skipPlatformChecks, dylibName) &&
829       !is_contained(interface.targets(), config->platformInfo.target)) {
830     error(toString(this) + " is incompatible with " +
831           std::string(config->platformInfo.target));
832     return;
833   }
834 
835   DylibFile *exportingFile = isImplicitlyLinked(dylibName) ? this : umbrella;
836   auto addSymbol = [&](const Twine &name) -> void {
837     symbols.push_back(symtab->addDylib(saver.save(name), exportingFile,
838                                        /*isWeakDef=*/false,
839                                        /*isTlv=*/false));
840   };
841   // TODO(compnerd) filter out symbols based on the target platform
842   // TODO: handle weak defs, thread locals
843   for (const auto *symbol : interface.symbols()) {
844     if (!symbol->getArchitectures().has(config->platformInfo.target.Arch))
845       continue;
846 
847     switch (symbol->getKind()) {
848     case SymbolKind::GlobalSymbol:
849       addSymbol(symbol->getName());
850       break;
851     case SymbolKind::ObjectiveCClass:
852       // XXX ld64 only creates these symbols when -ObjC is passed in. We may
853       // want to emulate that.
854       addSymbol(objc::klass + symbol->getName());
855       addSymbol(objc::metaclass + symbol->getName());
856       break;
857     case SymbolKind::ObjectiveCClassEHType:
858       addSymbol(objc::ehtype + symbol->getName());
859       break;
860     case SymbolKind::ObjectiveCInstanceVariable:
861       addSymbol(objc::ivar + symbol->getName());
862       break;
863     }
864   }
865 
866   const InterfaceFile *topLevel =
867       interface.getParent() == nullptr ? &interface : interface.getParent();
868 
869   for (InterfaceFileRef intfRef : interface.reexportedLibraries()) {
870     InterfaceFile::const_target_range targets = intfRef.targets();
871     if (is_contained(skipPlatformChecks, intfRef.getInstallName()) ||
872         is_contained(targets, config->platformInfo.target))
873       loadReexport(intfRef.getInstallName(), exportingFile, topLevel);
874   }
875 }
876 
877 ArchiveFile::ArchiveFile(std::unique_ptr<object::Archive> &&f)
878     : InputFile(ArchiveKind, f->getMemoryBufferRef()), file(std::move(f)) {
879   for (const object::Archive::Symbol &sym : file->symbols())
880     symtab->addLazy(sym.getName(), this, sym);
881 }
882 
883 void ArchiveFile::fetch(const object::Archive::Symbol &sym) {
884   object::Archive::Child c =
885       CHECK(sym.getMember(), toString(this) +
886                                  ": could not get the member for symbol " +
887                                  toMachOString(sym));
888 
889   if (!seen.insert(c.getChildOffset()).second)
890     return;
891 
892   MemoryBufferRef mb =
893       CHECK(c.getMemoryBufferRef(),
894             toString(this) +
895                 ": could not get the buffer for the member defining symbol " +
896                 toMachOString(sym));
897 
898   if (tar && c.getParent()->isThin())
899     tar->append(relativeToRoot(CHECK(c.getFullName(), this)), mb.getBuffer());
900 
901   uint32_t modTime = toTimeT(
902       CHECK(c.getLastModified(), toString(this) +
903                                      ": could not get the modification time "
904                                      "for the member defining symbol " +
905                                      toMachOString(sym)));
906 
907   // `sym` is owned by a LazySym, which will be replace<>() by make<ObjFile>
908   // and become invalid after that call. Copy it to the stack so we can refer
909   // to it later.
910   const object::Archive::Symbol sym_copy = sym;
911 
912   if (Optional<InputFile *> file =
913           loadArchiveMember(mb, modTime, getName(), /*objCOnly=*/false)) {
914     inputFiles.insert(*file);
915     // ld64 doesn't demangle sym here even with -demangle. Match that, so
916     // intentionally no call to toMachOString() here.
917     printArchiveMemberLoad(sym_copy.getName(), *file);
918   }
919 }
920 
921 static macho::Symbol *createBitcodeSymbol(const lto::InputFile::Symbol &objSym,
922                                           BitcodeFile &file) {
923   StringRef name = saver.save(objSym.getName());
924 
925   // TODO: support weak references
926   if (objSym.isUndefined())
927     return symtab->addUndefined(name, &file, /*isWeakRef=*/false);
928 
929   assert(!objSym.isCommon() && "TODO: support common symbols in LTO");
930 
931   // TODO: Write a test demonstrating why computing isPrivateExtern before
932   // LTO compilation is important.
933   bool isPrivateExtern = false;
934   switch (objSym.getVisibility()) {
935   case GlobalValue::HiddenVisibility:
936     isPrivateExtern = true;
937     break;
938   case GlobalValue::ProtectedVisibility:
939     error(name + " has protected visibility, which is not supported by Mach-O");
940     break;
941   case GlobalValue::DefaultVisibility:
942     break;
943   }
944 
945   return symtab->addDefined(name, &file, /*isec=*/nullptr, /*value=*/0,
946                             /*size=*/0, objSym.isWeak(), isPrivateExtern);
947 }
948 
949 BitcodeFile::BitcodeFile(MemoryBufferRef mbref)
950     : InputFile(BitcodeKind, mbref) {
951   obj = check(lto::InputFile::create(mbref));
952 
953   // Convert LTO Symbols to LLD Symbols in order to perform resolution. The
954   // "winning" symbol will then be marked as Prevailing at LTO compilation
955   // time.
956   for (const lto::InputFile::Symbol &objSym : obj->symbols())
957     symbols.push_back(createBitcodeSymbol(objSym, *this));
958 }
959 
960 template void ObjFile::parse<LP64>();
961 template void DylibFile::parse<LP64>(DylibFile *umbrella);
962