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