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