xref: /freebsd/contrib/llvm-project/lld/MachO/InputFiles.cpp (revision 5ffd83dbcc34f10e07f6d3e968ae6365869615f4)
1*5ffd83dbSDimitry Andric //===- InputFiles.cpp -----------------------------------------------------===//
2*5ffd83dbSDimitry Andric //
3*5ffd83dbSDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4*5ffd83dbSDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5*5ffd83dbSDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6*5ffd83dbSDimitry Andric //
7*5ffd83dbSDimitry Andric //===----------------------------------------------------------------------===//
8*5ffd83dbSDimitry Andric //
9*5ffd83dbSDimitry Andric // This file contains functions to parse Mach-O object files. In this comment,
10*5ffd83dbSDimitry Andric // we describe the Mach-O file structure and how we parse it.
11*5ffd83dbSDimitry Andric //
12*5ffd83dbSDimitry Andric // Mach-O is not very different from ELF or COFF. The notion of symbols,
13*5ffd83dbSDimitry Andric // sections and relocations exists in Mach-O as it does in ELF and COFF.
14*5ffd83dbSDimitry Andric //
15*5ffd83dbSDimitry Andric // Perhaps the notion that is new to those who know ELF/COFF is "subsections".
16*5ffd83dbSDimitry Andric // In ELF/COFF, sections are an atomic unit of data copied from input files to
17*5ffd83dbSDimitry Andric // output files. When we merge or garbage-collect sections, we treat each
18*5ffd83dbSDimitry Andric // section as an atomic unit. In Mach-O, that's not the case. Sections can
19*5ffd83dbSDimitry Andric // consist of multiple subsections, and subsections are a unit of merging and
20*5ffd83dbSDimitry Andric // garbage-collecting. Therefore, Mach-O's subsections are more similar to
21*5ffd83dbSDimitry Andric // ELF/COFF's sections than Mach-O's sections are.
22*5ffd83dbSDimitry Andric //
23*5ffd83dbSDimitry Andric // A section can have multiple symbols. A symbol that does not have the
24*5ffd83dbSDimitry Andric // N_ALT_ENTRY attribute indicates a beginning of a subsection. Therefore, by
25*5ffd83dbSDimitry Andric // definition, a symbol is always present at the beginning of each subsection. A
26*5ffd83dbSDimitry Andric // symbol with N_ALT_ENTRY attribute does not start a new subsection and can
27*5ffd83dbSDimitry Andric // point to a middle of a subsection.
28*5ffd83dbSDimitry Andric //
29*5ffd83dbSDimitry Andric // The notion of subsections also affects how relocations are represented in
30*5ffd83dbSDimitry Andric // Mach-O. All references within a section need to be explicitly represented as
31*5ffd83dbSDimitry Andric // relocations if they refer to different subsections, because we obviously need
32*5ffd83dbSDimitry Andric // to fix up addresses if subsections are laid out in an output file differently
33*5ffd83dbSDimitry Andric // than they were in object files. To represent that, Mach-O relocations can
34*5ffd83dbSDimitry Andric // refer to an unnamed location via its address. Scattered relocations (those
35*5ffd83dbSDimitry Andric // with the R_SCATTERED bit set) always refer to unnamed locations.
36*5ffd83dbSDimitry Andric // Non-scattered relocations refer to an unnamed location if r_extern is not set
37*5ffd83dbSDimitry Andric // and r_symbolnum is zero.
38*5ffd83dbSDimitry Andric //
39*5ffd83dbSDimitry Andric // Without the above differences, I think you can use your knowledge about ELF
40*5ffd83dbSDimitry Andric // and COFF for Mach-O.
41*5ffd83dbSDimitry Andric //
42*5ffd83dbSDimitry Andric //===----------------------------------------------------------------------===//
43*5ffd83dbSDimitry Andric 
44*5ffd83dbSDimitry Andric #include "InputFiles.h"
45*5ffd83dbSDimitry Andric #include "Config.h"
46*5ffd83dbSDimitry Andric #include "ExportTrie.h"
47*5ffd83dbSDimitry Andric #include "InputSection.h"
48*5ffd83dbSDimitry Andric #include "MachOStructs.h"
49*5ffd83dbSDimitry Andric #include "OutputSection.h"
50*5ffd83dbSDimitry Andric #include "SymbolTable.h"
51*5ffd83dbSDimitry Andric #include "Symbols.h"
52*5ffd83dbSDimitry Andric #include "Target.h"
53*5ffd83dbSDimitry Andric 
54*5ffd83dbSDimitry Andric #include "lld/Common/ErrorHandler.h"
55*5ffd83dbSDimitry Andric #include "lld/Common/Memory.h"
56*5ffd83dbSDimitry Andric #include "llvm/BinaryFormat/MachO.h"
57*5ffd83dbSDimitry Andric #include "llvm/Support/Endian.h"
58*5ffd83dbSDimitry Andric #include "llvm/Support/MemoryBuffer.h"
59*5ffd83dbSDimitry Andric #include "llvm/Support/Path.h"
60*5ffd83dbSDimitry Andric 
61*5ffd83dbSDimitry Andric using namespace llvm;
62*5ffd83dbSDimitry Andric using namespace llvm::MachO;
63*5ffd83dbSDimitry Andric using namespace llvm::support::endian;
64*5ffd83dbSDimitry Andric using namespace llvm::sys;
65*5ffd83dbSDimitry Andric using namespace lld;
66*5ffd83dbSDimitry Andric using namespace lld::macho;
67*5ffd83dbSDimitry Andric 
68*5ffd83dbSDimitry Andric std::vector<InputFile *> macho::inputFiles;
69*5ffd83dbSDimitry Andric 
70*5ffd83dbSDimitry Andric // Open a given file path and return it as a memory-mapped file.
71*5ffd83dbSDimitry Andric Optional<MemoryBufferRef> macho::readFile(StringRef path) {
72*5ffd83dbSDimitry Andric   // Open a file.
73*5ffd83dbSDimitry Andric   auto mbOrErr = MemoryBuffer::getFile(path);
74*5ffd83dbSDimitry Andric   if (auto ec = mbOrErr.getError()) {
75*5ffd83dbSDimitry Andric     error("cannot open " + path + ": " + ec.message());
76*5ffd83dbSDimitry Andric     return None;
77*5ffd83dbSDimitry Andric   }
78*5ffd83dbSDimitry Andric 
79*5ffd83dbSDimitry Andric   std::unique_ptr<MemoryBuffer> &mb = *mbOrErr;
80*5ffd83dbSDimitry Andric   MemoryBufferRef mbref = mb->getMemBufferRef();
81*5ffd83dbSDimitry Andric   make<std::unique_ptr<MemoryBuffer>>(std::move(mb)); // take mb ownership
82*5ffd83dbSDimitry Andric 
83*5ffd83dbSDimitry Andric   // If this is a regular non-fat file, return it.
84*5ffd83dbSDimitry Andric   const char *buf = mbref.getBufferStart();
85*5ffd83dbSDimitry Andric   auto *hdr = reinterpret_cast<const MachO::fat_header *>(buf);
86*5ffd83dbSDimitry Andric   if (read32be(&hdr->magic) != MachO::FAT_MAGIC)
87*5ffd83dbSDimitry Andric     return mbref;
88*5ffd83dbSDimitry Andric 
89*5ffd83dbSDimitry Andric   // Object files and archive files may be fat files, which contains
90*5ffd83dbSDimitry Andric   // multiple real files for different CPU ISAs. Here, we search for a
91*5ffd83dbSDimitry Andric   // file that matches with the current link target and returns it as
92*5ffd83dbSDimitry Andric   // a MemoryBufferRef.
93*5ffd83dbSDimitry Andric   auto *arch = reinterpret_cast<const MachO::fat_arch *>(buf + sizeof(*hdr));
94*5ffd83dbSDimitry Andric 
95*5ffd83dbSDimitry Andric   for (uint32_t i = 0, n = read32be(&hdr->nfat_arch); i < n; ++i) {
96*5ffd83dbSDimitry Andric     if (reinterpret_cast<const char *>(arch + i + 1) >
97*5ffd83dbSDimitry Andric         buf + mbref.getBufferSize()) {
98*5ffd83dbSDimitry Andric       error(path + ": fat_arch struct extends beyond end of file");
99*5ffd83dbSDimitry Andric       return None;
100*5ffd83dbSDimitry Andric     }
101*5ffd83dbSDimitry Andric 
102*5ffd83dbSDimitry Andric     if (read32be(&arch[i].cputype) != target->cpuType ||
103*5ffd83dbSDimitry Andric         read32be(&arch[i].cpusubtype) != target->cpuSubtype)
104*5ffd83dbSDimitry Andric       continue;
105*5ffd83dbSDimitry Andric 
106*5ffd83dbSDimitry Andric     uint32_t offset = read32be(&arch[i].offset);
107*5ffd83dbSDimitry Andric     uint32_t size = read32be(&arch[i].size);
108*5ffd83dbSDimitry Andric     if (offset + size > mbref.getBufferSize())
109*5ffd83dbSDimitry Andric       error(path + ": slice extends beyond end of file");
110*5ffd83dbSDimitry Andric     return MemoryBufferRef(StringRef(buf + offset, size), path.copy(bAlloc));
111*5ffd83dbSDimitry Andric   }
112*5ffd83dbSDimitry Andric 
113*5ffd83dbSDimitry Andric   error("unable to find matching architecture in " + path);
114*5ffd83dbSDimitry Andric   return None;
115*5ffd83dbSDimitry Andric }
116*5ffd83dbSDimitry Andric 
117*5ffd83dbSDimitry Andric static const load_command *findCommand(const mach_header_64 *hdr,
118*5ffd83dbSDimitry Andric                                        uint32_t type) {
119*5ffd83dbSDimitry Andric   const uint8_t *p =
120*5ffd83dbSDimitry Andric       reinterpret_cast<const uint8_t *>(hdr) + sizeof(mach_header_64);
121*5ffd83dbSDimitry Andric 
122*5ffd83dbSDimitry Andric   for (uint32_t i = 0, n = hdr->ncmds; i < n; ++i) {
123*5ffd83dbSDimitry Andric     auto *cmd = reinterpret_cast<const load_command *>(p);
124*5ffd83dbSDimitry Andric     if (cmd->cmd == type)
125*5ffd83dbSDimitry Andric       return cmd;
126*5ffd83dbSDimitry Andric     p += cmd->cmdsize;
127*5ffd83dbSDimitry Andric   }
128*5ffd83dbSDimitry Andric   return nullptr;
129*5ffd83dbSDimitry Andric }
130*5ffd83dbSDimitry Andric 
131*5ffd83dbSDimitry Andric void InputFile::parseSections(ArrayRef<section_64> sections) {
132*5ffd83dbSDimitry Andric   subsections.reserve(sections.size());
133*5ffd83dbSDimitry Andric   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
134*5ffd83dbSDimitry Andric 
135*5ffd83dbSDimitry Andric   for (const section_64 &sec : sections) {
136*5ffd83dbSDimitry Andric     InputSection *isec = make<InputSection>();
137*5ffd83dbSDimitry Andric     isec->file = this;
138*5ffd83dbSDimitry Andric     isec->name = StringRef(sec.sectname, strnlen(sec.sectname, 16));
139*5ffd83dbSDimitry Andric     isec->segname = StringRef(sec.segname, strnlen(sec.segname, 16));
140*5ffd83dbSDimitry Andric     isec->data = {isZeroFill(sec.flags) ? nullptr : buf + sec.offset,
141*5ffd83dbSDimitry Andric                   static_cast<size_t>(sec.size)};
142*5ffd83dbSDimitry Andric     if (sec.align >= 32)
143*5ffd83dbSDimitry Andric       error("alignment " + std::to_string(sec.align) + " of section " +
144*5ffd83dbSDimitry Andric             isec->name + " is too large");
145*5ffd83dbSDimitry Andric     else
146*5ffd83dbSDimitry Andric       isec->align = 1 << sec.align;
147*5ffd83dbSDimitry Andric     isec->flags = sec.flags;
148*5ffd83dbSDimitry Andric     subsections.push_back({{0, isec}});
149*5ffd83dbSDimitry Andric   }
150*5ffd83dbSDimitry Andric }
151*5ffd83dbSDimitry Andric 
152*5ffd83dbSDimitry Andric // Find the subsection corresponding to the greatest section offset that is <=
153*5ffd83dbSDimitry Andric // that of the given offset.
154*5ffd83dbSDimitry Andric //
155*5ffd83dbSDimitry Andric // offset: an offset relative to the start of the original InputSection (before
156*5ffd83dbSDimitry Andric // any subsection splitting has occurred). It will be updated to represent the
157*5ffd83dbSDimitry Andric // same location as an offset relative to the start of the containing
158*5ffd83dbSDimitry Andric // subsection.
159*5ffd83dbSDimitry Andric static InputSection *findContainingSubsection(SubsectionMap &map,
160*5ffd83dbSDimitry Andric                                               uint32_t *offset) {
161*5ffd83dbSDimitry Andric   auto it = std::prev(map.upper_bound(*offset));
162*5ffd83dbSDimitry Andric   *offset -= it->first;
163*5ffd83dbSDimitry Andric   return it->second;
164*5ffd83dbSDimitry Andric }
165*5ffd83dbSDimitry Andric 
166*5ffd83dbSDimitry Andric void InputFile::parseRelocations(const section_64 &sec,
167*5ffd83dbSDimitry Andric                                  SubsectionMap &subsecMap) {
168*5ffd83dbSDimitry Andric   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
169*5ffd83dbSDimitry Andric   ArrayRef<any_relocation_info> relInfos(
170*5ffd83dbSDimitry Andric       reinterpret_cast<const any_relocation_info *>(buf + sec.reloff),
171*5ffd83dbSDimitry Andric       sec.nreloc);
172*5ffd83dbSDimitry Andric 
173*5ffd83dbSDimitry Andric   for (const any_relocation_info &anyRel : relInfos) {
174*5ffd83dbSDimitry Andric     if (anyRel.r_word0 & R_SCATTERED)
175*5ffd83dbSDimitry Andric       fatal("TODO: Scattered relocations not supported");
176*5ffd83dbSDimitry Andric 
177*5ffd83dbSDimitry Andric     auto rel = reinterpret_cast<const relocation_info &>(anyRel);
178*5ffd83dbSDimitry Andric 
179*5ffd83dbSDimitry Andric     Reloc r;
180*5ffd83dbSDimitry Andric     r.type = rel.r_type;
181*5ffd83dbSDimitry Andric     r.pcrel = rel.r_pcrel;
182*5ffd83dbSDimitry Andric     r.length = rel.r_length;
183*5ffd83dbSDimitry Andric     uint64_t rawAddend = target->getImplicitAddend(mb, sec, rel);
184*5ffd83dbSDimitry Andric 
185*5ffd83dbSDimitry Andric     if (rel.r_extern) {
186*5ffd83dbSDimitry Andric       r.target = symbols[rel.r_symbolnum];
187*5ffd83dbSDimitry Andric       r.addend = rawAddend;
188*5ffd83dbSDimitry Andric     } else {
189*5ffd83dbSDimitry Andric       if (rel.r_symbolnum == 0 || rel.r_symbolnum > subsections.size())
190*5ffd83dbSDimitry Andric         fatal("invalid section index in relocation for offset " +
191*5ffd83dbSDimitry Andric               std::to_string(r.offset) + " in section " + sec.sectname +
192*5ffd83dbSDimitry Andric               " of " + getName());
193*5ffd83dbSDimitry Andric 
194*5ffd83dbSDimitry Andric       SubsectionMap &targetSubsecMap = subsections[rel.r_symbolnum - 1];
195*5ffd83dbSDimitry Andric       const section_64 &targetSec = sectionHeaders[rel.r_symbolnum - 1];
196*5ffd83dbSDimitry Andric       uint32_t targetOffset;
197*5ffd83dbSDimitry Andric       if (rel.r_pcrel) {
198*5ffd83dbSDimitry Andric         // The implicit addend for pcrel section relocations is the pcrel offset
199*5ffd83dbSDimitry Andric         // in terms of the addresses in the input file. Here we adjust it so
200*5ffd83dbSDimitry Andric         // that it describes the offset from the start of the target section.
201*5ffd83dbSDimitry Andric         // TODO: The offset of 4 is probably not right for ARM64, nor for
202*5ffd83dbSDimitry Andric         //       relocations with r_length != 2.
203*5ffd83dbSDimitry Andric         targetOffset =
204*5ffd83dbSDimitry Andric             sec.addr + rel.r_address + 4 + rawAddend - targetSec.addr;
205*5ffd83dbSDimitry Andric       } else {
206*5ffd83dbSDimitry Andric         // The addend for a non-pcrel relocation is its absolute address.
207*5ffd83dbSDimitry Andric         targetOffset = rawAddend - targetSec.addr;
208*5ffd83dbSDimitry Andric       }
209*5ffd83dbSDimitry Andric       r.target = findContainingSubsection(targetSubsecMap, &targetOffset);
210*5ffd83dbSDimitry Andric       r.addend = targetOffset;
211*5ffd83dbSDimitry Andric     }
212*5ffd83dbSDimitry Andric 
213*5ffd83dbSDimitry Andric     r.offset = rel.r_address;
214*5ffd83dbSDimitry Andric     InputSection *subsec = findContainingSubsection(subsecMap, &r.offset);
215*5ffd83dbSDimitry Andric     subsec->relocs.push_back(r);
216*5ffd83dbSDimitry Andric   }
217*5ffd83dbSDimitry Andric }
218*5ffd83dbSDimitry Andric 
219*5ffd83dbSDimitry Andric void InputFile::parseSymbols(ArrayRef<structs::nlist_64> nList,
220*5ffd83dbSDimitry Andric                              const char *strtab, bool subsectionsViaSymbols) {
221*5ffd83dbSDimitry Andric   // resize(), not reserve(), because we are going to create N_ALT_ENTRY symbols
222*5ffd83dbSDimitry Andric   // out-of-sequence.
223*5ffd83dbSDimitry Andric   symbols.resize(nList.size());
224*5ffd83dbSDimitry Andric   std::vector<size_t> altEntrySymIdxs;
225*5ffd83dbSDimitry Andric 
226*5ffd83dbSDimitry Andric   auto createDefined = [&](const structs::nlist_64 &sym, InputSection *isec,
227*5ffd83dbSDimitry Andric                            uint32_t value) -> Symbol * {
228*5ffd83dbSDimitry Andric     StringRef name = strtab + sym.n_strx;
229*5ffd83dbSDimitry Andric     if (sym.n_type & N_EXT)
230*5ffd83dbSDimitry Andric       // Global defined symbol
231*5ffd83dbSDimitry Andric       return symtab->addDefined(name, isec, value);
232*5ffd83dbSDimitry Andric     else
233*5ffd83dbSDimitry Andric       // Local defined symbol
234*5ffd83dbSDimitry Andric       return make<Defined>(name, isec, value);
235*5ffd83dbSDimitry Andric   };
236*5ffd83dbSDimitry Andric 
237*5ffd83dbSDimitry Andric   for (size_t i = 0, n = nList.size(); i < n; ++i) {
238*5ffd83dbSDimitry Andric     const structs::nlist_64 &sym = nList[i];
239*5ffd83dbSDimitry Andric 
240*5ffd83dbSDimitry Andric     // Undefined symbol
241*5ffd83dbSDimitry Andric     if (!sym.n_sect) {
242*5ffd83dbSDimitry Andric       StringRef name = strtab + sym.n_strx;
243*5ffd83dbSDimitry Andric       symbols[i] = symtab->addUndefined(name);
244*5ffd83dbSDimitry Andric       continue;
245*5ffd83dbSDimitry Andric     }
246*5ffd83dbSDimitry Andric 
247*5ffd83dbSDimitry Andric     const section_64 &sec = sectionHeaders[sym.n_sect - 1];
248*5ffd83dbSDimitry Andric     SubsectionMap &subsecMap = subsections[sym.n_sect - 1];
249*5ffd83dbSDimitry Andric     uint64_t offset = sym.n_value - sec.addr;
250*5ffd83dbSDimitry Andric 
251*5ffd83dbSDimitry Andric     // If the input file does not use subsections-via-symbols, all symbols can
252*5ffd83dbSDimitry Andric     // use the same subsection. Otherwise, we must split the sections along
253*5ffd83dbSDimitry Andric     // symbol boundaries.
254*5ffd83dbSDimitry Andric     if (!subsectionsViaSymbols) {
255*5ffd83dbSDimitry Andric       symbols[i] = createDefined(sym, subsecMap[0], offset);
256*5ffd83dbSDimitry Andric       continue;
257*5ffd83dbSDimitry Andric     }
258*5ffd83dbSDimitry Andric 
259*5ffd83dbSDimitry Andric     // nList entries aren't necessarily arranged in address order. Therefore,
260*5ffd83dbSDimitry Andric     // we can't create alt-entry symbols at this point because a later symbol
261*5ffd83dbSDimitry Andric     // may split its section, which may affect which subsection the alt-entry
262*5ffd83dbSDimitry Andric     // symbol is assigned to. So we need to handle them in a second pass below.
263*5ffd83dbSDimitry Andric     if (sym.n_desc & N_ALT_ENTRY) {
264*5ffd83dbSDimitry Andric       altEntrySymIdxs.push_back(i);
265*5ffd83dbSDimitry Andric       continue;
266*5ffd83dbSDimitry Andric     }
267*5ffd83dbSDimitry Andric 
268*5ffd83dbSDimitry Andric     // Find the subsection corresponding to the greatest section offset that is
269*5ffd83dbSDimitry Andric     // <= that of the current symbol. The subsection that we find either needs
270*5ffd83dbSDimitry Andric     // to be used directly or split in two.
271*5ffd83dbSDimitry Andric     uint32_t firstSize = offset;
272*5ffd83dbSDimitry Andric     InputSection *firstIsec = findContainingSubsection(subsecMap, &firstSize);
273*5ffd83dbSDimitry Andric 
274*5ffd83dbSDimitry Andric     if (firstSize == 0) {
275*5ffd83dbSDimitry Andric       // Alias of an existing symbol, or the first symbol in the section. These
276*5ffd83dbSDimitry Andric       // are handled by reusing the existing section.
277*5ffd83dbSDimitry Andric       symbols[i] = createDefined(sym, firstIsec, 0);
278*5ffd83dbSDimitry Andric       continue;
279*5ffd83dbSDimitry Andric     }
280*5ffd83dbSDimitry Andric 
281*5ffd83dbSDimitry Andric     // We saw a symbol definition at a new offset. Split the section into two
282*5ffd83dbSDimitry Andric     // subsections. The new symbol uses the second subsection.
283*5ffd83dbSDimitry Andric     auto *secondIsec = make<InputSection>(*firstIsec);
284*5ffd83dbSDimitry Andric     secondIsec->data = firstIsec->data.slice(firstSize);
285*5ffd83dbSDimitry Andric     firstIsec->data = firstIsec->data.slice(0, firstSize);
286*5ffd83dbSDimitry Andric     // TODO: ld64 appears to preserve the original alignment as well as each
287*5ffd83dbSDimitry Andric     // subsection's offset from the last aligned address. We should consider
288*5ffd83dbSDimitry Andric     // emulating that behavior.
289*5ffd83dbSDimitry Andric     secondIsec->align = MinAlign(firstIsec->align, offset);
290*5ffd83dbSDimitry Andric 
291*5ffd83dbSDimitry Andric     subsecMap[offset] = secondIsec;
292*5ffd83dbSDimitry Andric     // By construction, the symbol will be at offset zero in the new section.
293*5ffd83dbSDimitry Andric     symbols[i] = createDefined(sym, secondIsec, 0);
294*5ffd83dbSDimitry Andric   }
295*5ffd83dbSDimitry Andric 
296*5ffd83dbSDimitry Andric   for (size_t idx : altEntrySymIdxs) {
297*5ffd83dbSDimitry Andric     const structs::nlist_64 &sym = nList[idx];
298*5ffd83dbSDimitry Andric     SubsectionMap &subsecMap = subsections[sym.n_sect - 1];
299*5ffd83dbSDimitry Andric     uint32_t off = sym.n_value - sectionHeaders[sym.n_sect - 1].addr;
300*5ffd83dbSDimitry Andric     InputSection *subsec = findContainingSubsection(subsecMap, &off);
301*5ffd83dbSDimitry Andric     symbols[idx] = createDefined(sym, subsec, off);
302*5ffd83dbSDimitry Andric   }
303*5ffd83dbSDimitry Andric }
304*5ffd83dbSDimitry Andric 
305*5ffd83dbSDimitry Andric ObjFile::ObjFile(MemoryBufferRef mb) : InputFile(ObjKind, mb) {
306*5ffd83dbSDimitry Andric   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
307*5ffd83dbSDimitry Andric   auto *hdr = reinterpret_cast<const mach_header_64 *>(mb.getBufferStart());
308*5ffd83dbSDimitry Andric 
309*5ffd83dbSDimitry Andric   if (const load_command *cmd = findCommand(hdr, LC_SEGMENT_64)) {
310*5ffd83dbSDimitry Andric     auto *c = reinterpret_cast<const segment_command_64 *>(cmd);
311*5ffd83dbSDimitry Andric     sectionHeaders = ArrayRef<section_64>{
312*5ffd83dbSDimitry Andric         reinterpret_cast<const section_64 *>(c + 1), c->nsects};
313*5ffd83dbSDimitry Andric     parseSections(sectionHeaders);
314*5ffd83dbSDimitry Andric   }
315*5ffd83dbSDimitry Andric 
316*5ffd83dbSDimitry Andric   // TODO: Error on missing LC_SYMTAB?
317*5ffd83dbSDimitry Andric   if (const load_command *cmd = findCommand(hdr, LC_SYMTAB)) {
318*5ffd83dbSDimitry Andric     auto *c = reinterpret_cast<const symtab_command *>(cmd);
319*5ffd83dbSDimitry Andric     ArrayRef<structs::nlist_64> nList(
320*5ffd83dbSDimitry Andric         reinterpret_cast<const structs::nlist_64 *>(buf + c->symoff), c->nsyms);
321*5ffd83dbSDimitry Andric     const char *strtab = reinterpret_cast<const char *>(buf) + c->stroff;
322*5ffd83dbSDimitry Andric     bool subsectionsViaSymbols = hdr->flags & MH_SUBSECTIONS_VIA_SYMBOLS;
323*5ffd83dbSDimitry Andric     parseSymbols(nList, strtab, subsectionsViaSymbols);
324*5ffd83dbSDimitry Andric   }
325*5ffd83dbSDimitry Andric 
326*5ffd83dbSDimitry Andric   // The relocations may refer to the symbols, so we parse them after we have
327*5ffd83dbSDimitry Andric   // parsed all the symbols.
328*5ffd83dbSDimitry Andric   for (size_t i = 0, n = subsections.size(); i < n; ++i)
329*5ffd83dbSDimitry Andric     parseRelocations(sectionHeaders[i], subsections[i]);
330*5ffd83dbSDimitry Andric }
331*5ffd83dbSDimitry Andric 
332*5ffd83dbSDimitry Andric DylibFile::DylibFile(MemoryBufferRef mb, DylibFile *umbrella)
333*5ffd83dbSDimitry Andric     : InputFile(DylibKind, mb) {
334*5ffd83dbSDimitry Andric   if (umbrella == nullptr)
335*5ffd83dbSDimitry Andric     umbrella = this;
336*5ffd83dbSDimitry Andric 
337*5ffd83dbSDimitry Andric   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
338*5ffd83dbSDimitry Andric   auto *hdr = reinterpret_cast<const mach_header_64 *>(mb.getBufferStart());
339*5ffd83dbSDimitry Andric 
340*5ffd83dbSDimitry Andric   // Initialize dylibName.
341*5ffd83dbSDimitry Andric   if (const load_command *cmd = findCommand(hdr, LC_ID_DYLIB)) {
342*5ffd83dbSDimitry Andric     auto *c = reinterpret_cast<const dylib_command *>(cmd);
343*5ffd83dbSDimitry Andric     dylibName = reinterpret_cast<const char *>(cmd) + read32le(&c->dylib.name);
344*5ffd83dbSDimitry Andric   } else {
345*5ffd83dbSDimitry Andric     error("dylib " + getName() + " missing LC_ID_DYLIB load command");
346*5ffd83dbSDimitry Andric     return;
347*5ffd83dbSDimitry Andric   }
348*5ffd83dbSDimitry Andric 
349*5ffd83dbSDimitry Andric   // Initialize symbols.
350*5ffd83dbSDimitry Andric   if (const load_command *cmd = findCommand(hdr, LC_DYLD_INFO_ONLY)) {
351*5ffd83dbSDimitry Andric     auto *c = reinterpret_cast<const dyld_info_command *>(cmd);
352*5ffd83dbSDimitry Andric     parseTrie(buf + c->export_off, c->export_size,
353*5ffd83dbSDimitry Andric               [&](const Twine &name, uint64_t flags) {
354*5ffd83dbSDimitry Andric                 symbols.push_back(symtab->addDylib(saver.save(name), umbrella));
355*5ffd83dbSDimitry Andric               });
356*5ffd83dbSDimitry Andric   } else {
357*5ffd83dbSDimitry Andric     error("LC_DYLD_INFO_ONLY not found in " + getName());
358*5ffd83dbSDimitry Andric     return;
359*5ffd83dbSDimitry Andric   }
360*5ffd83dbSDimitry Andric 
361*5ffd83dbSDimitry Andric   if (hdr->flags & MH_NO_REEXPORTED_DYLIBS)
362*5ffd83dbSDimitry Andric     return;
363*5ffd83dbSDimitry Andric 
364*5ffd83dbSDimitry Andric   const uint8_t *p =
365*5ffd83dbSDimitry Andric       reinterpret_cast<const uint8_t *>(hdr) + sizeof(mach_header_64);
366*5ffd83dbSDimitry Andric   for (uint32_t i = 0, n = hdr->ncmds; i < n; ++i) {
367*5ffd83dbSDimitry Andric     auto *cmd = reinterpret_cast<const load_command *>(p);
368*5ffd83dbSDimitry Andric     p += cmd->cmdsize;
369*5ffd83dbSDimitry Andric     if (cmd->cmd != LC_REEXPORT_DYLIB)
370*5ffd83dbSDimitry Andric       continue;
371*5ffd83dbSDimitry Andric 
372*5ffd83dbSDimitry Andric     auto *c = reinterpret_cast<const dylib_command *>(cmd);
373*5ffd83dbSDimitry Andric     StringRef reexportPath =
374*5ffd83dbSDimitry Andric         reinterpret_cast<const char *>(c) + read32le(&c->dylib.name);
375*5ffd83dbSDimitry Andric     // TODO: Expand @loader_path, @executable_path etc in reexportPath
376*5ffd83dbSDimitry Andric     Optional<MemoryBufferRef> buffer = readFile(reexportPath);
377*5ffd83dbSDimitry Andric     if (!buffer) {
378*5ffd83dbSDimitry Andric       error("unable to read re-exported dylib at " + reexportPath);
379*5ffd83dbSDimitry Andric       return;
380*5ffd83dbSDimitry Andric     }
381*5ffd83dbSDimitry Andric     reexported.push_back(make<DylibFile>(*buffer, umbrella));
382*5ffd83dbSDimitry Andric   }
383*5ffd83dbSDimitry Andric }
384*5ffd83dbSDimitry Andric 
385*5ffd83dbSDimitry Andric DylibFile::DylibFile(std::shared_ptr<llvm::MachO::InterfaceFile> interface,
386*5ffd83dbSDimitry Andric                      DylibFile *umbrella)
387*5ffd83dbSDimitry Andric     : InputFile(DylibKind, MemoryBufferRef()) {
388*5ffd83dbSDimitry Andric   if (umbrella == nullptr)
389*5ffd83dbSDimitry Andric     umbrella = this;
390*5ffd83dbSDimitry Andric 
391*5ffd83dbSDimitry Andric   dylibName = saver.save(interface->getInstallName());
392*5ffd83dbSDimitry Andric   // TODO(compnerd) filter out symbols based on the target platform
393*5ffd83dbSDimitry Andric   for (const auto symbol : interface->symbols())
394*5ffd83dbSDimitry Andric     if (symbol->getArchitectures().has(config->arch))
395*5ffd83dbSDimitry Andric       symbols.push_back(
396*5ffd83dbSDimitry Andric           symtab->addDylib(saver.save(symbol->getName()), umbrella));
397*5ffd83dbSDimitry Andric   // TODO(compnerd) properly represent the hierarchy of the documents as it is
398*5ffd83dbSDimitry Andric   // in theory possible to have re-exported dylibs from re-exported dylibs which
399*5ffd83dbSDimitry Andric   // should be parent'ed to the child.
400*5ffd83dbSDimitry Andric   for (auto document : interface->documents())
401*5ffd83dbSDimitry Andric     reexported.push_back(make<DylibFile>(document, umbrella));
402*5ffd83dbSDimitry Andric }
403*5ffd83dbSDimitry Andric 
404*5ffd83dbSDimitry Andric ArchiveFile::ArchiveFile(std::unique_ptr<llvm::object::Archive> &&f)
405*5ffd83dbSDimitry Andric     : InputFile(ArchiveKind, f->getMemoryBufferRef()), file(std::move(f)) {
406*5ffd83dbSDimitry Andric   for (const object::Archive::Symbol &sym : file->symbols())
407*5ffd83dbSDimitry Andric     symtab->addLazy(sym.getName(), this, sym);
408*5ffd83dbSDimitry Andric }
409*5ffd83dbSDimitry Andric 
410*5ffd83dbSDimitry Andric void ArchiveFile::fetch(const object::Archive::Symbol &sym) {
411*5ffd83dbSDimitry Andric   object::Archive::Child c =
412*5ffd83dbSDimitry Andric       CHECK(sym.getMember(), toString(this) +
413*5ffd83dbSDimitry Andric                                  ": could not get the member for symbol " +
414*5ffd83dbSDimitry Andric                                  sym.getName());
415*5ffd83dbSDimitry Andric 
416*5ffd83dbSDimitry Andric   if (!seen.insert(c.getChildOffset()).second)
417*5ffd83dbSDimitry Andric     return;
418*5ffd83dbSDimitry Andric 
419*5ffd83dbSDimitry Andric   MemoryBufferRef mb =
420*5ffd83dbSDimitry Andric       CHECK(c.getMemoryBufferRef(),
421*5ffd83dbSDimitry Andric             toString(this) +
422*5ffd83dbSDimitry Andric                 ": could not get the buffer for the member defining symbol " +
423*5ffd83dbSDimitry Andric                 sym.getName());
424*5ffd83dbSDimitry Andric   auto file = make<ObjFile>(mb);
425*5ffd83dbSDimitry Andric   symbols.insert(symbols.end(), file->symbols.begin(), file->symbols.end());
426*5ffd83dbSDimitry Andric   subsections.insert(subsections.end(), file->subsections.begin(),
427*5ffd83dbSDimitry Andric                      file->subsections.end());
428*5ffd83dbSDimitry Andric }
429*5ffd83dbSDimitry Andric 
430*5ffd83dbSDimitry Andric // Returns "<internal>" or "baz.o".
431*5ffd83dbSDimitry Andric std::string lld::toString(const InputFile *file) {
432*5ffd83dbSDimitry Andric   return file ? std::string(file->getName()) : "<internal>";
433*5ffd83dbSDimitry Andric }
434