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