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