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