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