1//===- MachOObjectFile.cpp - Mach-O object file binding -------------------===//
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 defines the MachOObjectFile class, which binds the MachOObject
10// class to the generic ObjectFile wrapper.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/ADT/ArrayRef.h"
15#include "llvm/ADT/STLExtras.h"
16#include "llvm/ADT/SmallVector.h"
17#include "llvm/ADT/StringRef.h"
18#include "llvm/ADT/StringSwitch.h"
19#include "llvm/ADT/Twine.h"
20#include "llvm/ADT/bit.h"
21#include "llvm/BinaryFormat/MachO.h"
22#include "llvm/BinaryFormat/Swift.h"
23#include "llvm/Object/Error.h"
24#include "llvm/Object/MachO.h"
25#include "llvm/Object/ObjectFile.h"
26#include "llvm/Object/SymbolicFile.h"
27#include "llvm/Support/DataExtractor.h"
28#include "llvm/Support/Debug.h"
29#include "llvm/Support/Errc.h"
30#include "llvm/Support/Error.h"
31#include "llvm/Support/ErrorHandling.h"
32#include "llvm/Support/FileSystem.h"
33#include "llvm/Support/Format.h"
34#include "llvm/Support/LEB128.h"
35#include "llvm/Support/MemoryBufferRef.h"
36#include "llvm/Support/Path.h"
37#include "llvm/Support/SwapByteOrder.h"
38#include "llvm/Support/raw_ostream.h"
39#include "llvm/TargetParser/Host.h"
40#include "llvm/TargetParser/Triple.h"
41#include <algorithm>
42#include <cassert>
43#include <cstddef>
44#include <cstdint>
45#include <cstring>
46#include <limits>
47#include <list>
48#include <memory>
49#include <system_error>
50
51using namespace llvm;
52using namespace object;
53
54namespace {
55
56 struct section_base {
57 char sectname[16];
58 char segname[16];
59 };
60
61} // end anonymous namespace
62
63static Error malformedError(const Twine &Msg) {
64 return make_error<GenericBinaryError>(Args: "truncated or malformed object (" +
65 Msg + ")",
66 Args: object_error::parse_failed);
67}
68
69// FIXME: Replace all uses of this function with getStructOrErr.
70template <typename T>
71static T getStruct(const MachOObjectFile &O, const char *P) {
72 // Don't read before the beginning or past the end of the file
73 if (P < O.getData().begin() || P + sizeof(T) > O.getData().end())
74 report_fatal_error(reason: "Malformed MachO file.");
75
76 T Cmd;
77 memcpy(&Cmd, P, sizeof(T));
78 if (O.isLittleEndian() != sys::IsLittleEndianHost)
79 MachO::swapStruct(Cmd);
80 return Cmd;
81}
82
83template <typename T>
84static Expected<T> getStructOrErr(const MachOObjectFile &O, const char *P) {
85 // Don't read before the beginning or past the end of the file
86 if (P < O.getData().begin() || P + sizeof(T) > O.getData().end())
87 return malformedError(Msg: "Structure read out-of-range");
88
89 T Cmd;
90 memcpy(&Cmd, P, sizeof(T));
91 if (O.isLittleEndian() != sys::IsLittleEndianHost)
92 MachO::swapStruct(Cmd);
93 return Cmd;
94}
95
96static const char *
97getSectionPtr(const MachOObjectFile &O, MachOObjectFile::LoadCommandInfo L,
98 unsigned Sec) {
99 uintptr_t CommandAddr = reinterpret_cast<uintptr_t>(L.Ptr);
100
101 bool Is64 = O.is64Bit();
102 unsigned SegmentLoadSize = Is64 ? sizeof(MachO::segment_command_64) :
103 sizeof(MachO::segment_command);
104 unsigned SectionSize = Is64 ? sizeof(MachO::section_64) :
105 sizeof(MachO::section);
106
107 uintptr_t SectionAddr = CommandAddr + SegmentLoadSize + Sec * SectionSize;
108 return reinterpret_cast<const char*>(SectionAddr);
109}
110
111static const char *getPtr(const MachOObjectFile &O, size_t Offset,
112 size_t MachOFilesetEntryOffset = 0) {
113 assert(Offset <= O.getData().size() &&
114 MachOFilesetEntryOffset <= O.getData().size());
115 return O.getData().data() + Offset + MachOFilesetEntryOffset;
116}
117
118static MachO::nlist_base
119getSymbolTableEntryBase(const MachOObjectFile &O, DataRefImpl DRI) {
120 const char *P = reinterpret_cast<const char *>(DRI.p);
121 return getStruct<MachO::nlist_base>(O, P);
122}
123
124static StringRef parseSegmentOrSectionName(const char *P) {
125 if (P[15] == 0)
126 // Null terminated.
127 return P;
128 // Not null terminated, so this is a 16 char string.
129 return StringRef(P, 16);
130}
131
132static unsigned getCPUType(const MachOObjectFile &O) {
133 return O.getHeader().cputype;
134}
135
136static unsigned getCPUSubType(const MachOObjectFile &O) {
137 return O.getHeader().cpusubtype & ~MachO::CPU_SUBTYPE_MASK;
138}
139
140static uint32_t
141getPlainRelocationAddress(const MachO::any_relocation_info &RE) {
142 return RE.r_word0;
143}
144
145static unsigned
146getScatteredRelocationAddress(const MachO::any_relocation_info &RE) {
147 return RE.r_word0 & 0xffffff;
148}
149
150static bool getPlainRelocationPCRel(const MachOObjectFile &O,
151 const MachO::any_relocation_info &RE) {
152 if (O.isLittleEndian())
153 return (RE.r_word1 >> 24) & 1;
154 return (RE.r_word1 >> 7) & 1;
155}
156
157static bool
158getScatteredRelocationPCRel(const MachO::any_relocation_info &RE) {
159 return (RE.r_word0 >> 30) & 1;
160}
161
162static unsigned getPlainRelocationLength(const MachOObjectFile &O,
163 const MachO::any_relocation_info &RE) {
164 if (O.isLittleEndian())
165 return (RE.r_word1 >> 25) & 3;
166 return (RE.r_word1 >> 5) & 3;
167}
168
169static unsigned
170getScatteredRelocationLength(const MachO::any_relocation_info &RE) {
171 return (RE.r_word0 >> 28) & 3;
172}
173
174static unsigned getPlainRelocationType(const MachOObjectFile &O,
175 const MachO::any_relocation_info &RE) {
176 if (O.isLittleEndian())
177 return RE.r_word1 >> 28;
178 return RE.r_word1 & 0xf;
179}
180
181static uint32_t getSectionFlags(const MachOObjectFile &O,
182 DataRefImpl Sec) {
183 if (O.is64Bit()) {
184 MachO::section_64 Sect = O.getSection64(DRI: Sec);
185 return Sect.flags;
186 }
187 MachO::section Sect = O.getSection(DRI: Sec);
188 return Sect.flags;
189}
190
191static Expected<MachOObjectFile::LoadCommandInfo>
192getLoadCommandInfo(const MachOObjectFile &Obj, const char *Ptr,
193 uint32_t LoadCommandIndex) {
194 if (auto CmdOrErr = getStructOrErr<MachO::load_command>(O: Obj, P: Ptr)) {
195 assert(Ptr <= Obj.getData().end() && "Start must be before end");
196 if (CmdOrErr->cmdsize > (uintptr_t)(Obj.getData().end() - Ptr))
197 return malformedError(Msg: "load command " + Twine(LoadCommandIndex) +
198 " extends past end of file");
199 if (CmdOrErr->cmdsize < 8)
200 return malformedError(Msg: "load command " + Twine(LoadCommandIndex) +
201 " with size less than 8 bytes");
202 return MachOObjectFile::LoadCommandInfo({.Ptr: Ptr, .C: *CmdOrErr});
203 } else
204 return CmdOrErr.takeError();
205}
206
207static Expected<MachOObjectFile::LoadCommandInfo>
208getFirstLoadCommandInfo(const MachOObjectFile &Obj) {
209 unsigned HeaderSize = Obj.is64Bit() ? sizeof(MachO::mach_header_64)
210 : sizeof(MachO::mach_header);
211 if (sizeof(MachO::load_command) > Obj.getHeader().sizeofcmds)
212 return malformedError(Msg: "load command 0 extends past the end all load "
213 "commands in the file");
214 return getLoadCommandInfo(
215 Obj, Ptr: getPtr(O: Obj, Offset: HeaderSize, MachOFilesetEntryOffset: Obj.getMachOFilesetEntryOffset()), LoadCommandIndex: 0);
216}
217
218static Expected<MachOObjectFile::LoadCommandInfo>
219getNextLoadCommandInfo(const MachOObjectFile &Obj, uint32_t LoadCommandIndex,
220 const MachOObjectFile::LoadCommandInfo &L) {
221 unsigned HeaderSize = Obj.is64Bit() ? sizeof(MachO::mach_header_64)
222 : sizeof(MachO::mach_header);
223 if (L.Ptr + L.C.cmdsize + sizeof(MachO::load_command) >
224 Obj.getData().data() + Obj.getMachOFilesetEntryOffset() + HeaderSize +
225 Obj.getHeader().sizeofcmds)
226 return malformedError(Msg: "load command " + Twine(LoadCommandIndex + 1) +
227 " extends past the end all load commands in the file");
228 return getLoadCommandInfo(Obj, Ptr: L.Ptr + L.C.cmdsize, LoadCommandIndex: LoadCommandIndex + 1);
229}
230
231template <typename T>
232static void parseHeader(const MachOObjectFile &Obj, T &Header,
233 Error &Err) {
234 if (sizeof(T) > Obj.getData().size()) {
235 Err = malformedError(Msg: "the mach header extends past the end of the "
236 "file");
237 return;
238 }
239 if (auto HeaderOrErr = getStructOrErr<T>(
240 Obj, getPtr(O: Obj, Offset: 0, MachOFilesetEntryOffset: Obj.getMachOFilesetEntryOffset())))
241 Header = *HeaderOrErr;
242 else
243 Err = HeaderOrErr.takeError();
244}
245
246// This is used to check for overlapping of Mach-O elements.
247struct MachOElement {
248 uint64_t Offset;
249 uint64_t Size;
250 const char *Name;
251};
252
253static Error checkOverlappingElement(std::list<MachOElement> &Elements,
254 uint64_t Offset, uint64_t Size,
255 const char *Name) {
256 if (Size == 0)
257 return Error::success();
258
259 for (auto it = Elements.begin(); it != Elements.end(); ++it) {
260 const auto &E = *it;
261 if ((Offset >= E.Offset && Offset < E.Offset + E.Size) ||
262 (Offset + Size > E.Offset && Offset + Size < E.Offset + E.Size) ||
263 (Offset <= E.Offset && Offset + Size >= E.Offset + E.Size))
264 return malformedError(Msg: Twine(Name) + " at offset " + Twine(Offset) +
265 " with a size of " + Twine(Size) + ", overlaps " +
266 E.Name + " at offset " + Twine(E.Offset) + " with "
267 "a size of " + Twine(E.Size));
268 auto nt = it;
269 nt++;
270 if (nt != Elements.end()) {
271 const auto &N = *nt;
272 if (Offset + Size <= N.Offset) {
273 Elements.insert(position: nt, x: {.Offset: Offset, .Size: Size, .Name: Name});
274 return Error::success();
275 }
276 }
277 }
278 Elements.push_back(x: {.Offset: Offset, .Size: Size, .Name: Name});
279 return Error::success();
280}
281
282// Parses LC_SEGMENT or LC_SEGMENT_64 load command, adds addresses of all
283// sections to \param Sections, and optionally sets
284// \param IsPageZeroSegment to true.
285template <typename Segment, typename Section>
286static Error parseSegmentLoadCommand(
287 const MachOObjectFile &Obj, const MachOObjectFile::LoadCommandInfo &Load,
288 SmallVectorImpl<const char *> &Sections, bool &IsPageZeroSegment,
289 uint32_t LoadCommandIndex, const char *CmdName, uint64_t SizeOfHeaders,
290 std::list<MachOElement> &Elements) {
291 const unsigned SegmentLoadSize = sizeof(Segment);
292 if (Load.C.cmdsize < SegmentLoadSize)
293 return malformedError(Msg: "load command " + Twine(LoadCommandIndex) +
294 " " + CmdName + " cmdsize too small");
295 if (auto SegOrErr = getStructOrErr<Segment>(Obj, Load.Ptr)) {
296 Segment S = SegOrErr.get();
297 const unsigned SectionSize = sizeof(Section);
298 uint64_t FileSize = Obj.getData().size();
299 if (S.nsects > std::numeric_limits<uint32_t>::max() / SectionSize ||
300 S.nsects * SectionSize > Load.C.cmdsize - SegmentLoadSize)
301 return malformedError(Msg: "load command " + Twine(LoadCommandIndex) +
302 " inconsistent cmdsize in " + CmdName +
303 " for the number of sections");
304 for (unsigned J = 0; J < S.nsects; ++J) {
305 const char *Sec = getSectionPtr(O: Obj, L: Load, Sec: J);
306 Sections.push_back(Elt: Sec);
307 auto SectionOrErr = getStructOrErr<Section>(Obj, Sec);
308 if (!SectionOrErr)
309 return SectionOrErr.takeError();
310 Section s = SectionOrErr.get();
311 if (Obj.getHeader().filetype != MachO::MH_DYLIB_STUB &&
312 Obj.getHeader().filetype != MachO::MH_DSYM &&
313 s.flags != MachO::S_ZEROFILL &&
314 s.flags != MachO::S_THREAD_LOCAL_ZEROFILL &&
315 s.offset > FileSize)
316 return malformedError(Msg: "offset field of section " + Twine(J) + " in " +
317 CmdName + " command " + Twine(LoadCommandIndex) +
318 " extends past the end of the file");
319 if (Obj.getHeader().filetype != MachO::MH_DYLIB_STUB &&
320 Obj.getHeader().filetype != MachO::MH_DSYM &&
321 s.flags != MachO::S_ZEROFILL &&
322 s.flags != MachO::S_THREAD_LOCAL_ZEROFILL && S.fileoff == 0 &&
323 s.offset < SizeOfHeaders && s.size != 0)
324 return malformedError(Msg: "offset field of section " + Twine(J) + " in " +
325 CmdName + " command " + Twine(LoadCommandIndex) +
326 " not past the headers of the file");
327 uint64_t BigSize = s.offset;
328 BigSize += s.size;
329 if (Obj.getHeader().filetype != MachO::MH_DYLIB_STUB &&
330 Obj.getHeader().filetype != MachO::MH_DSYM &&
331 s.flags != MachO::S_ZEROFILL &&
332 s.flags != MachO::S_THREAD_LOCAL_ZEROFILL &&
333 BigSize > FileSize)
334 return malformedError(Msg: "offset field plus size field of section " +
335 Twine(J) + " in " + CmdName + " command " +
336 Twine(LoadCommandIndex) +
337 " extends past the end of the file");
338 if (Obj.getHeader().filetype != MachO::MH_DYLIB_STUB &&
339 Obj.getHeader().filetype != MachO::MH_DSYM &&
340 s.flags != MachO::S_ZEROFILL &&
341 s.flags != MachO::S_THREAD_LOCAL_ZEROFILL &&
342 s.size > S.filesize)
343 return malformedError(Msg: "size field of section " +
344 Twine(J) + " in " + CmdName + " command " +
345 Twine(LoadCommandIndex) +
346 " greater than the segment");
347 if (Obj.getHeader().filetype != MachO::MH_DYLIB_STUB &&
348 Obj.getHeader().filetype != MachO::MH_DSYM && s.size != 0 &&
349 s.addr < S.vmaddr)
350 return malformedError(Msg: "addr field of section " + Twine(J) + " in " +
351 CmdName + " command " + Twine(LoadCommandIndex) +
352 " less than the segment's vmaddr");
353 BigSize = s.addr;
354 BigSize += s.size;
355 uint64_t BigEnd = S.vmaddr;
356 BigEnd += S.vmsize;
357 if (S.vmsize != 0 && s.size != 0 && BigSize > BigEnd)
358 return malformedError(Msg: "addr field plus size of section " + Twine(J) +
359 " in " + CmdName + " command " +
360 Twine(LoadCommandIndex) +
361 " greater than than "
362 "the segment's vmaddr plus vmsize");
363 if (Obj.getHeader().filetype != MachO::MH_DYLIB_STUB &&
364 Obj.getHeader().filetype != MachO::MH_DSYM &&
365 s.flags != MachO::S_ZEROFILL &&
366 s.flags != MachO::S_THREAD_LOCAL_ZEROFILL)
367 if (Error Err = checkOverlappingElement(Elements, s.offset, s.size,
368 "section contents"))
369 return Err;
370 if (s.reloff > FileSize)
371 return malformedError(Msg: "reloff field of section " + Twine(J) + " in " +
372 CmdName + " command " + Twine(LoadCommandIndex) +
373 " extends past the end of the file");
374 BigSize = s.nreloc;
375 BigSize *= sizeof(struct MachO::relocation_info);
376 BigSize += s.reloff;
377 if (BigSize > FileSize)
378 return malformedError(Msg: "reloff field plus nreloc field times sizeof("
379 "struct relocation_info) of section " +
380 Twine(J) + " in " + CmdName + " command " +
381 Twine(LoadCommandIndex) +
382 " extends past the end of the file");
383 if (Error Err = checkOverlappingElement(Elements, s.reloff, s.nreloc *
384 sizeof(struct
385 MachO::relocation_info),
386 "section relocation entries"))
387 return Err;
388 }
389 if (S.fileoff > FileSize)
390 return malformedError(Msg: "load command " + Twine(LoadCommandIndex) +
391 " fileoff field in " + CmdName +
392 " extends past the end of the file");
393 uint64_t BigSize = S.fileoff;
394 BigSize += S.filesize;
395 if (BigSize > FileSize)
396 return malformedError(Msg: "load command " + Twine(LoadCommandIndex) +
397 " fileoff field plus filesize field in " +
398 CmdName + " extends past the end of the file");
399 if (S.vmsize != 0 && S.filesize > S.vmsize)
400 return malformedError(Msg: "load command " + Twine(LoadCommandIndex) +
401 " filesize field in " + CmdName +
402 " greater than vmsize field");
403 IsPageZeroSegment |= StringRef("__PAGEZERO") == S.segname;
404 } else
405 return SegOrErr.takeError();
406
407 return Error::success();
408}
409
410static Error checkSymtabCommand(const MachOObjectFile &Obj,
411 const MachOObjectFile::LoadCommandInfo &Load,
412 uint32_t LoadCommandIndex,
413 const char **SymtabLoadCmd,
414 std::list<MachOElement> &Elements) {
415 if (Load.C.cmdsize < sizeof(MachO::symtab_command))
416 return malformedError(Msg: "load command " + Twine(LoadCommandIndex) +
417 " LC_SYMTAB cmdsize too small");
418 if (*SymtabLoadCmd != nullptr)
419 return malformedError(Msg: "more than one LC_SYMTAB command");
420 auto SymtabOrErr = getStructOrErr<MachO::symtab_command>(O: Obj, P: Load.Ptr);
421 if (!SymtabOrErr)
422 return SymtabOrErr.takeError();
423 MachO::symtab_command Symtab = SymtabOrErr.get();
424 if (Symtab.cmdsize != sizeof(MachO::symtab_command))
425 return malformedError(Msg: "LC_SYMTAB command " + Twine(LoadCommandIndex) +
426 " has incorrect cmdsize");
427 uint64_t FileSize = Obj.getData().size();
428 if (Symtab.symoff > FileSize)
429 return malformedError(Msg: "symoff field of LC_SYMTAB command " +
430 Twine(LoadCommandIndex) + " extends past the end "
431 "of the file");
432 uint64_t SymtabSize = Symtab.nsyms;
433 const char *struct_nlist_name;
434 if (Obj.is64Bit()) {
435 SymtabSize *= sizeof(MachO::nlist_64);
436 struct_nlist_name = "struct nlist_64";
437 } else {
438 SymtabSize *= sizeof(MachO::nlist);
439 struct_nlist_name = "struct nlist";
440 }
441 uint64_t BigSize = SymtabSize;
442 BigSize += Symtab.symoff;
443 if (BigSize > FileSize)
444 return malformedError(Msg: "symoff field plus nsyms field times sizeof(" +
445 Twine(struct_nlist_name) + ") of LC_SYMTAB command " +
446 Twine(LoadCommandIndex) + " extends past the end "
447 "of the file");
448 if (Error Err = checkOverlappingElement(Elements, Offset: Symtab.symoff, Size: SymtabSize,
449 Name: "symbol table"))
450 return Err;
451 if (Symtab.stroff > FileSize)
452 return malformedError(Msg: "stroff field of LC_SYMTAB command " +
453 Twine(LoadCommandIndex) + " extends past the end "
454 "of the file");
455 BigSize = Symtab.stroff;
456 BigSize += Symtab.strsize;
457 if (BigSize > FileSize)
458 return malformedError(Msg: "stroff field plus strsize field of LC_SYMTAB "
459 "command " + Twine(LoadCommandIndex) + " extends "
460 "past the end of the file");
461 if (Error Err = checkOverlappingElement(Elements, Offset: Symtab.stroff,
462 Size: Symtab.strsize, Name: "string table"))
463 return Err;
464 *SymtabLoadCmd = Load.Ptr;
465 return Error::success();
466}
467
468static Error checkDysymtabCommand(const MachOObjectFile &Obj,
469 const MachOObjectFile::LoadCommandInfo &Load,
470 uint32_t LoadCommandIndex,
471 const char **DysymtabLoadCmd,
472 std::list<MachOElement> &Elements) {
473 if (Load.C.cmdsize < sizeof(MachO::dysymtab_command))
474 return malformedError(Msg: "load command " + Twine(LoadCommandIndex) +
475 " LC_DYSYMTAB cmdsize too small");
476 if (*DysymtabLoadCmd != nullptr)
477 return malformedError(Msg: "more than one LC_DYSYMTAB command");
478 auto DysymtabOrErr =
479 getStructOrErr<MachO::dysymtab_command>(O: Obj, P: Load.Ptr);
480 if (!DysymtabOrErr)
481 return DysymtabOrErr.takeError();
482 MachO::dysymtab_command Dysymtab = DysymtabOrErr.get();
483 if (Dysymtab.cmdsize != sizeof(MachO::dysymtab_command))
484 return malformedError(Msg: "LC_DYSYMTAB command " + Twine(LoadCommandIndex) +
485 " has incorrect cmdsize");
486 uint64_t FileSize = Obj.getData().size();
487 if (Dysymtab.tocoff > FileSize)
488 return malformedError(Msg: "tocoff field of LC_DYSYMTAB command " +
489 Twine(LoadCommandIndex) + " extends past the end of "
490 "the file");
491 uint64_t BigSize = Dysymtab.ntoc;
492 BigSize *= sizeof(MachO::dylib_table_of_contents);
493 BigSize += Dysymtab.tocoff;
494 if (BigSize > FileSize)
495 return malformedError(Msg: "tocoff field plus ntoc field times sizeof(struct "
496 "dylib_table_of_contents) of LC_DYSYMTAB command " +
497 Twine(LoadCommandIndex) + " extends past the end of "
498 "the file");
499 if (Error Err = checkOverlappingElement(Elements, Offset: Dysymtab.tocoff,
500 Size: Dysymtab.ntoc * sizeof(struct
501 MachO::dylib_table_of_contents),
502 Name: "table of contents"))
503 return Err;
504 if (Dysymtab.modtaboff > FileSize)
505 return malformedError(Msg: "modtaboff field of LC_DYSYMTAB command " +
506 Twine(LoadCommandIndex) + " extends past the end of "
507 "the file");
508 BigSize = Dysymtab.nmodtab;
509 const char *struct_dylib_module_name;
510 uint64_t sizeof_modtab;
511 if (Obj.is64Bit()) {
512 sizeof_modtab = sizeof(MachO::dylib_module_64);
513 struct_dylib_module_name = "struct dylib_module_64";
514 } else {
515 sizeof_modtab = sizeof(MachO::dylib_module);
516 struct_dylib_module_name = "struct dylib_module";
517 }
518 BigSize *= sizeof_modtab;
519 BigSize += Dysymtab.modtaboff;
520 if (BigSize > FileSize)
521 return malformedError(Msg: "modtaboff field plus nmodtab field times sizeof(" +
522 Twine(struct_dylib_module_name) + ") of LC_DYSYMTAB "
523 "command " + Twine(LoadCommandIndex) + " extends "
524 "past the end of the file");
525 if (Error Err = checkOverlappingElement(Elements, Offset: Dysymtab.modtaboff,
526 Size: Dysymtab.nmodtab * sizeof_modtab,
527 Name: "module table"))
528 return Err;
529 if (Dysymtab.extrefsymoff > FileSize)
530 return malformedError(Msg: "extrefsymoff field of LC_DYSYMTAB command " +
531 Twine(LoadCommandIndex) + " extends past the end of "
532 "the file");
533 BigSize = Dysymtab.nextrefsyms;
534 BigSize *= sizeof(MachO::dylib_reference);
535 BigSize += Dysymtab.extrefsymoff;
536 if (BigSize > FileSize)
537 return malformedError(Msg: "extrefsymoff field plus nextrefsyms field times "
538 "sizeof(struct dylib_reference) of LC_DYSYMTAB "
539 "command " + Twine(LoadCommandIndex) + " extends "
540 "past the end of the file");
541 if (Error Err = checkOverlappingElement(Elements, Offset: Dysymtab.extrefsymoff,
542 Size: Dysymtab.nextrefsyms *
543 sizeof(MachO::dylib_reference),
544 Name: "reference table"))
545 return Err;
546 if (Dysymtab.indirectsymoff > FileSize)
547 return malformedError(Msg: "indirectsymoff field of LC_DYSYMTAB command " +
548 Twine(LoadCommandIndex) + " extends past the end of "
549 "the file");
550 BigSize = Dysymtab.nindirectsyms;
551 BigSize *= sizeof(uint32_t);
552 BigSize += Dysymtab.indirectsymoff;
553 if (BigSize > FileSize)
554 return malformedError(Msg: "indirectsymoff field plus nindirectsyms field times "
555 "sizeof(uint32_t) of LC_DYSYMTAB command " +
556 Twine(LoadCommandIndex) + " extends past the end of "
557 "the file");
558 if (Error Err = checkOverlappingElement(Elements, Offset: Dysymtab.indirectsymoff,
559 Size: Dysymtab.nindirectsyms *
560 sizeof(uint32_t),
561 Name: "indirect table"))
562 return Err;
563 if (Dysymtab.extreloff > FileSize)
564 return malformedError(Msg: "extreloff field of LC_DYSYMTAB command " +
565 Twine(LoadCommandIndex) + " extends past the end of "
566 "the file");
567 BigSize = Dysymtab.nextrel;
568 BigSize *= sizeof(MachO::relocation_info);
569 BigSize += Dysymtab.extreloff;
570 if (BigSize > FileSize)
571 return malformedError(Msg: "extreloff field plus nextrel field times sizeof"
572 "(struct relocation_info) of LC_DYSYMTAB command " +
573 Twine(LoadCommandIndex) + " extends past the end of "
574 "the file");
575 if (Error Err = checkOverlappingElement(Elements, Offset: Dysymtab.extreloff,
576 Size: Dysymtab.nextrel *
577 sizeof(MachO::relocation_info),
578 Name: "external relocation table"))
579 return Err;
580 if (Dysymtab.locreloff > FileSize)
581 return malformedError(Msg: "locreloff field of LC_DYSYMTAB command " +
582 Twine(LoadCommandIndex) + " extends past the end of "
583 "the file");
584 BigSize = Dysymtab.nlocrel;
585 BigSize *= sizeof(MachO::relocation_info);
586 BigSize += Dysymtab.locreloff;
587 if (BigSize > FileSize)
588 return malformedError(Msg: "locreloff field plus nlocrel field times sizeof"
589 "(struct relocation_info) of LC_DYSYMTAB command " +
590 Twine(LoadCommandIndex) + " extends past the end of "
591 "the file");
592 if (Error Err = checkOverlappingElement(Elements, Offset: Dysymtab.locreloff,
593 Size: Dysymtab.nlocrel *
594 sizeof(MachO::relocation_info),
595 Name: "local relocation table"))
596 return Err;
597 *DysymtabLoadCmd = Load.Ptr;
598 return Error::success();
599}
600
601static Error checkLinkeditDataCommand(const MachOObjectFile &Obj,
602 const MachOObjectFile::LoadCommandInfo &Load,
603 uint32_t LoadCommandIndex,
604 const char **LoadCmd, const char *CmdName,
605 std::list<MachOElement> &Elements,
606 const char *ElementName) {
607 if (Load.C.cmdsize < sizeof(MachO::linkedit_data_command))
608 return malformedError(Msg: "load command " + Twine(LoadCommandIndex) + " " +
609 CmdName + " cmdsize too small");
610 if (*LoadCmd != nullptr)
611 return malformedError(Msg: "more than one " + Twine(CmdName) + " command");
612 auto LinkDataOrError =
613 getStructOrErr<MachO::linkedit_data_command>(O: Obj, P: Load.Ptr);
614 if (!LinkDataOrError)
615 return LinkDataOrError.takeError();
616 MachO::linkedit_data_command LinkData = LinkDataOrError.get();
617 if (LinkData.cmdsize != sizeof(MachO::linkedit_data_command))
618 return malformedError(Msg: Twine(CmdName) + " command " +
619 Twine(LoadCommandIndex) + " has incorrect cmdsize");
620 uint64_t FileSize = Obj.getData().size();
621 if (LinkData.dataoff > FileSize)
622 return malformedError(Msg: "dataoff field of " + Twine(CmdName) + " command " +
623 Twine(LoadCommandIndex) + " extends past the end of "
624 "the file");
625 uint64_t BigSize = LinkData.dataoff;
626 BigSize += LinkData.datasize;
627 if (BigSize > FileSize)
628 return malformedError(Msg: "dataoff field plus datasize field of " +
629 Twine(CmdName) + " command " +
630 Twine(LoadCommandIndex) + " extends past the end of "
631 "the file");
632 if (Error Err = checkOverlappingElement(Elements, Offset: LinkData.dataoff,
633 Size: LinkData.datasize, Name: ElementName))
634 return Err;
635 *LoadCmd = Load.Ptr;
636 return Error::success();
637}
638
639static Error checkDyldInfoCommand(const MachOObjectFile &Obj,
640 const MachOObjectFile::LoadCommandInfo &Load,
641 uint32_t LoadCommandIndex,
642 const char **LoadCmd, const char *CmdName,
643 std::list<MachOElement> &Elements) {
644 if (Load.C.cmdsize < sizeof(MachO::dyld_info_command))
645 return malformedError(Msg: "load command " + Twine(LoadCommandIndex) + " " +
646 CmdName + " cmdsize too small");
647 if (*LoadCmd != nullptr)
648 return malformedError(Msg: "more than one LC_DYLD_INFO and or LC_DYLD_INFO_ONLY "
649 "command");
650 auto DyldInfoOrErr =
651 getStructOrErr<MachO::dyld_info_command>(O: Obj, P: Load.Ptr);
652 if (!DyldInfoOrErr)
653 return DyldInfoOrErr.takeError();
654 MachO::dyld_info_command DyldInfo = DyldInfoOrErr.get();
655 if (DyldInfo.cmdsize != sizeof(MachO::dyld_info_command))
656 return malformedError(Msg: Twine(CmdName) + " command " +
657 Twine(LoadCommandIndex) + " has incorrect cmdsize");
658 uint64_t FileSize = Obj.getData().size();
659 if (DyldInfo.rebase_off > FileSize)
660 return malformedError(Msg: "rebase_off field of " + Twine(CmdName) +
661 " command " + Twine(LoadCommandIndex) + " extends "
662 "past the end of the file");
663 uint64_t BigSize = DyldInfo.rebase_off;
664 BigSize += DyldInfo.rebase_size;
665 if (BigSize > FileSize)
666 return malformedError(Msg: "rebase_off field plus rebase_size field of " +
667 Twine(CmdName) + " command " +
668 Twine(LoadCommandIndex) + " extends past the end of "
669 "the file");
670 if (Error Err = checkOverlappingElement(Elements, Offset: DyldInfo.rebase_off,
671 Size: DyldInfo.rebase_size,
672 Name: "dyld rebase info"))
673 return Err;
674 if (DyldInfo.bind_off > FileSize)
675 return malformedError(Msg: "bind_off field of " + Twine(CmdName) +
676 " command " + Twine(LoadCommandIndex) + " extends "
677 "past the end of the file");
678 BigSize = DyldInfo.bind_off;
679 BigSize += DyldInfo.bind_size;
680 if (BigSize > FileSize)
681 return malformedError(Msg: "bind_off field plus bind_size field of " +
682 Twine(CmdName) + " command " +
683 Twine(LoadCommandIndex) + " extends past the end of "
684 "the file");
685 if (Error Err = checkOverlappingElement(Elements, Offset: DyldInfo.bind_off,
686 Size: DyldInfo.bind_size,
687 Name: "dyld bind info"))
688 return Err;
689 if (DyldInfo.weak_bind_off > FileSize)
690 return malformedError(Msg: "weak_bind_off field of " + Twine(CmdName) +
691 " command " + Twine(LoadCommandIndex) + " extends "
692 "past the end of the file");
693 BigSize = DyldInfo.weak_bind_off;
694 BigSize += DyldInfo.weak_bind_size;
695 if (BigSize > FileSize)
696 return malformedError(Msg: "weak_bind_off field plus weak_bind_size field of " +
697 Twine(CmdName) + " command " +
698 Twine(LoadCommandIndex) + " extends past the end of "
699 "the file");
700 if (Error Err = checkOverlappingElement(Elements, Offset: DyldInfo.weak_bind_off,
701 Size: DyldInfo.weak_bind_size,
702 Name: "dyld weak bind info"))
703 return Err;
704 if (DyldInfo.lazy_bind_off > FileSize)
705 return malformedError(Msg: "lazy_bind_off field of " + Twine(CmdName) +
706 " command " + Twine(LoadCommandIndex) + " extends "
707 "past the end of the file");
708 BigSize = DyldInfo.lazy_bind_off;
709 BigSize += DyldInfo.lazy_bind_size;
710 if (BigSize > FileSize)
711 return malformedError(Msg: "lazy_bind_off field plus lazy_bind_size field of " +
712 Twine(CmdName) + " command " +
713 Twine(LoadCommandIndex) + " extends past the end of "
714 "the file");
715 if (Error Err = checkOverlappingElement(Elements, Offset: DyldInfo.lazy_bind_off,
716 Size: DyldInfo.lazy_bind_size,
717 Name: "dyld lazy bind info"))
718 return Err;
719 if (DyldInfo.export_off > FileSize)
720 return malformedError(Msg: "export_off field of " + Twine(CmdName) +
721 " command " + Twine(LoadCommandIndex) + " extends "
722 "past the end of the file");
723 BigSize = DyldInfo.export_off;
724 BigSize += DyldInfo.export_size;
725 if (BigSize > FileSize)
726 return malformedError(Msg: "export_off field plus export_size field of " +
727 Twine(CmdName) + " command " +
728 Twine(LoadCommandIndex) + " extends past the end of "
729 "the file");
730 if (Error Err = checkOverlappingElement(Elements, Offset: DyldInfo.export_off,
731 Size: DyldInfo.export_size,
732 Name: "dyld export info"))
733 return Err;
734 *LoadCmd = Load.Ptr;
735 return Error::success();
736}
737
738static Error checkDylibCommand(const MachOObjectFile &Obj,
739 const MachOObjectFile::LoadCommandInfo &Load,
740 uint32_t LoadCommandIndex, const char *CmdName) {
741 if (Load.C.cmdsize < sizeof(MachO::dylib_command))
742 return malformedError(Msg: "load command " + Twine(LoadCommandIndex) + " " +
743 CmdName + " cmdsize too small");
744 auto CommandOrErr = getStructOrErr<MachO::dylib_command>(O: Obj, P: Load.Ptr);
745 if (!CommandOrErr)
746 return CommandOrErr.takeError();
747 MachO::dylib_command D = CommandOrErr.get();
748 if (D.dylib.name < sizeof(MachO::dylib_command))
749 return malformedError(Msg: "load command " + Twine(LoadCommandIndex) + " " +
750 CmdName + " name.offset field too small, not past "
751 "the end of the dylib_command struct");
752 if (D.dylib.name >= D.cmdsize)
753 return malformedError(Msg: "load command " + Twine(LoadCommandIndex) + " " +
754 CmdName + " name.offset field extends past the end "
755 "of the load command");
756 // Make sure there is a null between the starting offset of the name and
757 // the end of the load command.
758 uint32_t i;
759 const char *P = (const char *)Load.Ptr;
760 for (i = D.dylib.name; i < D.cmdsize; i++)
761 if (P[i] == '\0')
762 break;
763 if (i >= D.cmdsize)
764 return malformedError(Msg: "load command " + Twine(LoadCommandIndex) + " " +
765 CmdName + " library name extends past the end of the "
766 "load command");
767 return Error::success();
768}
769
770static Error checkDylibIdCommand(const MachOObjectFile &Obj,
771 const MachOObjectFile::LoadCommandInfo &Load,
772 uint32_t LoadCommandIndex,
773 const char **LoadCmd) {
774 if (Error Err = checkDylibCommand(Obj, Load, LoadCommandIndex,
775 CmdName: "LC_ID_DYLIB"))
776 return Err;
777 if (*LoadCmd != nullptr)
778 return malformedError(Msg: "more than one LC_ID_DYLIB command");
779 if (Obj.getHeader().filetype != MachO::MH_DYLIB &&
780 Obj.getHeader().filetype != MachO::MH_DYLIB_STUB)
781 return malformedError(Msg: "LC_ID_DYLIB load command in non-dynamic library "
782 "file type");
783 *LoadCmd = Load.Ptr;
784 return Error::success();
785}
786
787static Error checkDyldCommand(const MachOObjectFile &Obj,
788 const MachOObjectFile::LoadCommandInfo &Load,
789 uint32_t LoadCommandIndex, const char *CmdName) {
790 if (Load.C.cmdsize < sizeof(MachO::dylinker_command))
791 return malformedError(Msg: "load command " + Twine(LoadCommandIndex) + " " +
792 CmdName + " cmdsize too small");
793 auto CommandOrErr = getStructOrErr<MachO::dylinker_command>(O: Obj, P: Load.Ptr);
794 if (!CommandOrErr)
795 return CommandOrErr.takeError();
796 MachO::dylinker_command D = CommandOrErr.get();
797 if (D.name < sizeof(MachO::dylinker_command))
798 return malformedError(Msg: "load command " + Twine(LoadCommandIndex) + " " +
799 CmdName + " name.offset field too small, not past "
800 "the end of the dylinker_command struct");
801 if (D.name >= D.cmdsize)
802 return malformedError(Msg: "load command " + Twine(LoadCommandIndex) + " " +
803 CmdName + " name.offset field extends past the end "
804 "of the load command");
805 // Make sure there is a null between the starting offset of the name and
806 // the end of the load command.
807 uint32_t i;
808 const char *P = (const char *)Load.Ptr;
809 for (i = D.name; i < D.cmdsize; i++)
810 if (P[i] == '\0')
811 break;
812 if (i >= D.cmdsize)
813 return malformedError(Msg: "load command " + Twine(LoadCommandIndex) + " " +
814 CmdName + " dyld name extends past the end of the "
815 "load command");
816 return Error::success();
817}
818
819static Error checkVersCommand(const MachOObjectFile &Obj,
820 const MachOObjectFile::LoadCommandInfo &Load,
821 uint32_t LoadCommandIndex,
822 const char **LoadCmd, const char *CmdName) {
823 if (Load.C.cmdsize != sizeof(MachO::version_min_command))
824 return malformedError(Msg: "load command " + Twine(LoadCommandIndex) + " " +
825 CmdName + " has incorrect cmdsize");
826 if (*LoadCmd != nullptr)
827 return malformedError(Msg: "more than one LC_VERSION_MIN_MACOSX, "
828 "LC_VERSION_MIN_IPHONEOS, LC_VERSION_MIN_TVOS or "
829 "LC_VERSION_MIN_WATCHOS command");
830 *LoadCmd = Load.Ptr;
831 return Error::success();
832}
833
834static Error checkNoteCommand(const MachOObjectFile &Obj,
835 const MachOObjectFile::LoadCommandInfo &Load,
836 uint32_t LoadCommandIndex,
837 std::list<MachOElement> &Elements) {
838 if (Load.C.cmdsize != sizeof(MachO::note_command))
839 return malformedError(Msg: "load command " + Twine(LoadCommandIndex) +
840 " LC_NOTE has incorrect cmdsize");
841 auto NoteCmdOrErr = getStructOrErr<MachO::note_command>(O: Obj, P: Load.Ptr);
842 if (!NoteCmdOrErr)
843 return NoteCmdOrErr.takeError();
844 MachO::note_command Nt = NoteCmdOrErr.get();
845 uint64_t FileSize = Obj.getData().size();
846 if (Nt.offset > FileSize)
847 return malformedError(Msg: "offset field of LC_NOTE command " +
848 Twine(LoadCommandIndex) + " extends "
849 "past the end of the file");
850 uint64_t BigSize = Nt.offset;
851 BigSize += Nt.size;
852 if (BigSize > FileSize)
853 return malformedError(Msg: "size field plus offset field of LC_NOTE command " +
854 Twine(LoadCommandIndex) + " extends past the end of "
855 "the file");
856 if (Error Err = checkOverlappingElement(Elements, Offset: Nt.offset, Size: Nt.size,
857 Name: "LC_NOTE data"))
858 return Err;
859 return Error::success();
860}
861
862static Error
863parseBuildVersionCommand(const MachOObjectFile &Obj,
864 const MachOObjectFile::LoadCommandInfo &Load,
865 SmallVectorImpl<const char*> &BuildTools,
866 uint32_t LoadCommandIndex) {
867 auto BVCOrErr =
868 getStructOrErr<MachO::build_version_command>(O: Obj, P: Load.Ptr);
869 if (!BVCOrErr)
870 return BVCOrErr.takeError();
871 MachO::build_version_command BVC = BVCOrErr.get();
872 if (Load.C.cmdsize !=
873 sizeof(MachO::build_version_command) +
874 BVC.ntools * sizeof(MachO::build_tool_version))
875 return malformedError(Msg: "load command " + Twine(LoadCommandIndex) +
876 " LC_BUILD_VERSION_COMMAND has incorrect cmdsize");
877
878 auto Start = Load.Ptr + sizeof(MachO::build_version_command);
879 BuildTools.resize(N: BVC.ntools);
880 for (unsigned i = 0; i < BVC.ntools; ++i)
881 BuildTools[i] = Start + i * sizeof(MachO::build_tool_version);
882
883 return Error::success();
884}
885
886static Error
887checkTargetTripleCommand(const MachOObjectFile &Obj,
888 const MachOObjectFile::LoadCommandInfo &Load,
889 uint32_t LoadCommandIndex) {
890 // Check the command size is big enough for the command struct.
891 if (Load.C.cmdsize < sizeof(MachO::target_triple_command))
892 return malformedError(Msg: "load command " + Twine(LoadCommandIndex) +
893 " LC_TARGET_TRIPLE cmdsize too small");
894
895 auto TTOrErr = getStructOrErr<MachO::target_triple_command>(O: Obj, P: Load.Ptr);
896 if (!TTOrErr)
897 return TTOrErr.takeError();
898 MachO::target_triple_command TT = TTOrErr.get();
899
900 // Check the triple offset is after the command struct.
901 if (TT.triple < sizeof(MachO::target_triple_command))
902 return malformedError(
903 Msg: "load command " + Twine(LoadCommandIndex) +
904 " LC_TARGET_TRIPLE triple.offset field too small, not past the end of "
905 "the target_triple_command struct");
906
907 // Check the triple offset is before the end of the command.
908 if (TT.triple >= TT.cmdsize)
909 return malformedError(Msg: "load command " + Twine(LoadCommandIndex) +
910 " LC_TARGET_TRIPLE triple.offset field extends past "
911 "the end of the load command");
912
913 // Check there is a NUL between the starting offset of the triple and the end
914 // of the command.
915 uint32_t i;
916 const char *P = (const char *)Load.Ptr;
917 for (i = TT.triple; i < TT.cmdsize; i++)
918 if (P[i] == '\0')
919 break;
920 if (i >= TT.cmdsize)
921 return malformedError(Msg: "load command " + Twine(LoadCommandIndex) +
922 " LC_TARGET_TRIPLE triple name extends past the end "
923 "of the load command");
924
925 return Error::success();
926}
927
928static Error checkRpathCommand(const MachOObjectFile &Obj,
929 const MachOObjectFile::LoadCommandInfo &Load,
930 uint32_t LoadCommandIndex) {
931 if (Load.C.cmdsize < sizeof(MachO::rpath_command))
932 return malformedError(Msg: "load command " + Twine(LoadCommandIndex) +
933 " LC_RPATH cmdsize too small");
934 auto ROrErr = getStructOrErr<MachO::rpath_command>(O: Obj, P: Load.Ptr);
935 if (!ROrErr)
936 return ROrErr.takeError();
937 MachO::rpath_command R = ROrErr.get();
938 if (R.path < sizeof(MachO::rpath_command))
939 return malformedError(Msg: "load command " + Twine(LoadCommandIndex) +
940 " LC_RPATH path.offset field too small, not past "
941 "the end of the rpath_command struct");
942 if (R.path >= R.cmdsize)
943 return malformedError(Msg: "load command " + Twine(LoadCommandIndex) +
944 " LC_RPATH path.offset field extends past the end "
945 "of the load command");
946 // Make sure there is a null between the starting offset of the path and
947 // the end of the load command.
948 uint32_t i;
949 const char *P = (const char *)Load.Ptr;
950 for (i = R.path; i < R.cmdsize; i++)
951 if (P[i] == '\0')
952 break;
953 if (i >= R.cmdsize)
954 return malformedError(Msg: "load command " + Twine(LoadCommandIndex) +
955 " LC_RPATH library name extends past the end of the "
956 "load command");
957 return Error::success();
958}
959
960static Error checkEncryptCommand(const MachOObjectFile &Obj,
961 const MachOObjectFile::LoadCommandInfo &Load,
962 uint32_t LoadCommandIndex,
963 uint64_t cryptoff, uint64_t cryptsize,
964 const char **LoadCmd, const char *CmdName) {
965 if (*LoadCmd != nullptr)
966 return malformedError(Msg: "more than one LC_ENCRYPTION_INFO and or "
967 "LC_ENCRYPTION_INFO_64 command");
968 uint64_t FileSize = Obj.getData().size();
969 if (cryptoff > FileSize)
970 return malformedError(Msg: "cryptoff field of " + Twine(CmdName) +
971 " command " + Twine(LoadCommandIndex) + " extends "
972 "past the end of the file");
973 uint64_t BigSize = cryptoff;
974 BigSize += cryptsize;
975 if (BigSize > FileSize)
976 return malformedError(Msg: "cryptoff field plus cryptsize field of " +
977 Twine(CmdName) + " command " +
978 Twine(LoadCommandIndex) + " extends past the end of "
979 "the file");
980 *LoadCmd = Load.Ptr;
981 return Error::success();
982}
983
984static Error checkLinkerOptCommand(const MachOObjectFile &Obj,
985 const MachOObjectFile::LoadCommandInfo &Load,
986 uint32_t LoadCommandIndex) {
987 if (Load.C.cmdsize < sizeof(MachO::linker_option_command))
988 return malformedError(Msg: "load command " + Twine(LoadCommandIndex) +
989 " LC_LINKER_OPTION cmdsize too small");
990 auto LinkOptionOrErr =
991 getStructOrErr<MachO::linker_option_command>(O: Obj, P: Load.Ptr);
992 if (!LinkOptionOrErr)
993 return LinkOptionOrErr.takeError();
994 MachO::linker_option_command L = LinkOptionOrErr.get();
995 // Make sure the count of strings is correct.
996 const char *string = (const char *)Load.Ptr +
997 sizeof(struct MachO::linker_option_command);
998 uint32_t left = L.cmdsize - sizeof(struct MachO::linker_option_command);
999 uint32_t i = 0;
1000 while (left > 0) {
1001 while (*string == '\0' && left > 0) {
1002 string++;
1003 left--;
1004 }
1005 if (left > 0) {
1006 i++;
1007 uint32_t NullPos = StringRef(string, left).find(C: '\0');
1008 if (0xffffffff == NullPos)
1009 return malformedError(Msg: "load command " + Twine(LoadCommandIndex) +
1010 " LC_LINKER_OPTION string #" + Twine(i) +
1011 " is not NULL terminated");
1012 uint32_t len = std::min(a: NullPos, b: left) + 1;
1013 string += len;
1014 left -= len;
1015 }
1016 }
1017 if (L.count != i)
1018 return malformedError(Msg: "load command " + Twine(LoadCommandIndex) +
1019 " LC_LINKER_OPTION string count " + Twine(L.count) +
1020 " does not match number of strings");
1021 return Error::success();
1022}
1023
1024static Error checkSubCommand(const MachOObjectFile &Obj,
1025 const MachOObjectFile::LoadCommandInfo &Load,
1026 uint32_t LoadCommandIndex, const char *CmdName,
1027 size_t SizeOfCmd, const char *CmdStructName,
1028 uint32_t PathOffset, const char *PathFieldName) {
1029 if (PathOffset < SizeOfCmd)
1030 return malformedError(Msg: "load command " + Twine(LoadCommandIndex) + " " +
1031 CmdName + " " + PathFieldName + ".offset field too "
1032 "small, not past the end of the " + CmdStructName);
1033 if (PathOffset >= Load.C.cmdsize)
1034 return malformedError(Msg: "load command " + Twine(LoadCommandIndex) + " " +
1035 CmdName + " " + PathFieldName + ".offset field "
1036 "extends past the end of the load command");
1037 // Make sure there is a null between the starting offset of the path and
1038 // the end of the load command.
1039 uint32_t i;
1040 const char *P = (const char *)Load.Ptr;
1041 for (i = PathOffset; i < Load.C.cmdsize; i++)
1042 if (P[i] == '\0')
1043 break;
1044 if (i >= Load.C.cmdsize)
1045 return malformedError(Msg: "load command " + Twine(LoadCommandIndex) + " " +
1046 CmdName + " " + PathFieldName + " name extends past "
1047 "the end of the load command");
1048 return Error::success();
1049}
1050
1051static Error checkThreadCommand(const MachOObjectFile &Obj,
1052 const MachOObjectFile::LoadCommandInfo &Load,
1053 uint32_t LoadCommandIndex,
1054 const char *CmdName) {
1055 if (Load.C.cmdsize < sizeof(MachO::thread_command))
1056 return malformedError(Msg: "load command " + Twine(LoadCommandIndex) +
1057 CmdName + " cmdsize too small");
1058 auto ThreadCommandOrErr =
1059 getStructOrErr<MachO::thread_command>(O: Obj, P: Load.Ptr);
1060 if (!ThreadCommandOrErr)
1061 return ThreadCommandOrErr.takeError();
1062 MachO::thread_command T = ThreadCommandOrErr.get();
1063 const char *state = Load.Ptr + sizeof(MachO::thread_command);
1064 const char *end = Load.Ptr + T.cmdsize;
1065 uint32_t nflavor = 0;
1066 uint32_t cputype = getCPUType(O: Obj);
1067 while (state < end) {
1068 if(state + sizeof(uint32_t) > end)
1069 return malformedError(Msg: "load command " + Twine(LoadCommandIndex) +
1070 "flavor in " + CmdName + " extends past end of "
1071 "command");
1072 uint32_t flavor;
1073 memcpy(dest: &flavor, src: state, n: sizeof(uint32_t));
1074 if (Obj.isLittleEndian() != sys::IsLittleEndianHost)
1075 sys::swapByteOrder(Value&: flavor);
1076 state += sizeof(uint32_t);
1077
1078 if(state + sizeof(uint32_t) > end)
1079 return malformedError(Msg: "load command " + Twine(LoadCommandIndex) +
1080 " count in " + CmdName + " extends past end of "
1081 "command");
1082 uint32_t count;
1083 memcpy(dest: &count, src: state, n: sizeof(uint32_t));
1084 if (Obj.isLittleEndian() != sys::IsLittleEndianHost)
1085 sys::swapByteOrder(Value&: count);
1086 state += sizeof(uint32_t);
1087
1088 if (cputype == MachO::CPU_TYPE_I386) {
1089 if (flavor == MachO::x86_THREAD_STATE32) {
1090 if (count != MachO::x86_THREAD_STATE32_COUNT)
1091 return malformedError(Msg: "load command " + Twine(LoadCommandIndex) +
1092 " count not x86_THREAD_STATE32_COUNT for "
1093 "flavor number " + Twine(nflavor) + " which is "
1094 "a x86_THREAD_STATE32 flavor in " + CmdName +
1095 " command");
1096 if (state + sizeof(MachO::x86_thread_state32_t) > end)
1097 return malformedError(Msg: "load command " + Twine(LoadCommandIndex) +
1098 " x86_THREAD_STATE32 extends past end of "
1099 "command in " + CmdName + " command");
1100 state += sizeof(MachO::x86_thread_state32_t);
1101 } else {
1102 return malformedError(Msg: "load command " + Twine(LoadCommandIndex) +
1103 " unknown flavor (" + Twine(flavor) + ") for "
1104 "flavor number " + Twine(nflavor) + " in " +
1105 CmdName + " command");
1106 }
1107 } else if (cputype == MachO::CPU_TYPE_X86_64) {
1108 if (flavor == MachO::x86_THREAD_STATE) {
1109 if (count != MachO::x86_THREAD_STATE_COUNT)
1110 return malformedError(Msg: "load command " + Twine(LoadCommandIndex) +
1111 " count not x86_THREAD_STATE_COUNT for "
1112 "flavor number " + Twine(nflavor) + " which is "
1113 "a x86_THREAD_STATE flavor in " + CmdName +
1114 " command");
1115 if (state + sizeof(MachO::x86_thread_state_t) > end)
1116 return malformedError(Msg: "load command " + Twine(LoadCommandIndex) +
1117 " x86_THREAD_STATE extends past end of "
1118 "command in " + CmdName + " command");
1119 state += sizeof(MachO::x86_thread_state_t);
1120 } else if (flavor == MachO::x86_FLOAT_STATE) {
1121 if (count != MachO::x86_FLOAT_STATE_COUNT)
1122 return malformedError(Msg: "load command " + Twine(LoadCommandIndex) +
1123 " count not x86_FLOAT_STATE_COUNT for "
1124 "flavor number " + Twine(nflavor) + " which is "
1125 "a x86_FLOAT_STATE flavor in " + CmdName +
1126 " command");
1127 if (state + sizeof(MachO::x86_float_state_t) > end)
1128 return malformedError(Msg: "load command " + Twine(LoadCommandIndex) +
1129 " x86_FLOAT_STATE extends past end of "
1130 "command in " + CmdName + " command");
1131 state += sizeof(MachO::x86_float_state_t);
1132 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
1133 if (count != MachO::x86_EXCEPTION_STATE_COUNT)
1134 return malformedError(Msg: "load command " + Twine(LoadCommandIndex) +
1135 " count not x86_EXCEPTION_STATE_COUNT for "
1136 "flavor number " + Twine(nflavor) + " which is "
1137 "a x86_EXCEPTION_STATE flavor in " + CmdName +
1138 " command");
1139 if (state + sizeof(MachO::x86_exception_state_t) > end)
1140 return malformedError(Msg: "load command " + Twine(LoadCommandIndex) +
1141 " x86_EXCEPTION_STATE extends past end of "
1142 "command in " + CmdName + " command");
1143 state += sizeof(MachO::x86_exception_state_t);
1144 } else if (flavor == MachO::x86_THREAD_STATE64) {
1145 if (count != MachO::x86_THREAD_STATE64_COUNT)
1146 return malformedError(Msg: "load command " + Twine(LoadCommandIndex) +
1147 " count not x86_THREAD_STATE64_COUNT for "
1148 "flavor number " + Twine(nflavor) + " which is "
1149 "a x86_THREAD_STATE64 flavor in " + CmdName +
1150 " command");
1151 if (state + sizeof(MachO::x86_thread_state64_t) > end)
1152 return malformedError(Msg: "load command " + Twine(LoadCommandIndex) +
1153 " x86_THREAD_STATE64 extends past end of "
1154 "command in " + CmdName + " command");
1155 state += sizeof(MachO::x86_thread_state64_t);
1156 } else if (flavor == MachO::x86_EXCEPTION_STATE64) {
1157 if (count != MachO::x86_EXCEPTION_STATE64_COUNT)
1158 return malformedError(Msg: "load command " + Twine(LoadCommandIndex) +
1159 " count not x86_EXCEPTION_STATE64_COUNT for "
1160 "flavor number " + Twine(nflavor) + " which is "
1161 "a x86_EXCEPTION_STATE64 flavor in " + CmdName +
1162 " command");
1163 if (state + sizeof(MachO::x86_exception_state64_t) > end)
1164 return malformedError(Msg: "load command " + Twine(LoadCommandIndex) +
1165 " x86_EXCEPTION_STATE64 extends past end of "
1166 "command in " + CmdName + " command");
1167 state += sizeof(MachO::x86_exception_state64_t);
1168 } else {
1169 return malformedError(Msg: "load command " + Twine(LoadCommandIndex) +
1170 " unknown flavor (" + Twine(flavor) + ") for "
1171 "flavor number " + Twine(nflavor) + " in " +
1172 CmdName + " command");
1173 }
1174 } else if (cputype == MachO::CPU_TYPE_ARM) {
1175 if (flavor == MachO::ARM_THREAD_STATE) {
1176 if (count != MachO::ARM_THREAD_STATE_COUNT)
1177 return malformedError(Msg: "load command " + Twine(LoadCommandIndex) +
1178 " count not ARM_THREAD_STATE_COUNT for "
1179 "flavor number " + Twine(nflavor) + " which is "
1180 "a ARM_THREAD_STATE flavor in " + CmdName +
1181 " command");
1182 if (state + sizeof(MachO::arm_thread_state32_t) > end)
1183 return malformedError(Msg: "load command " + Twine(LoadCommandIndex) +
1184 " ARM_THREAD_STATE extends past end of "
1185 "command in " + CmdName + " command");
1186 state += sizeof(MachO::arm_thread_state32_t);
1187 } else {
1188 return malformedError(Msg: "load command " + Twine(LoadCommandIndex) +
1189 " unknown flavor (" + Twine(flavor) + ") for "
1190 "flavor number " + Twine(nflavor) + " in " +
1191 CmdName + " command");
1192 }
1193 } else if (cputype == MachO::CPU_TYPE_ARM64 ||
1194 cputype == MachO::CPU_TYPE_ARM64_32) {
1195 if (flavor == MachO::ARM_THREAD_STATE64) {
1196 if (count != MachO::ARM_THREAD_STATE64_COUNT)
1197 return malformedError(Msg: "load command " + Twine(LoadCommandIndex) +
1198 " count not ARM_THREAD_STATE64_COUNT for "
1199 "flavor number " + Twine(nflavor) + " which is "
1200 "a ARM_THREAD_STATE64 flavor in " + CmdName +
1201 " command");
1202 if (state + sizeof(MachO::arm_thread_state64_t) > end)
1203 return malformedError(Msg: "load command " + Twine(LoadCommandIndex) +
1204 " ARM_THREAD_STATE64 extends past end of "
1205 "command in " + CmdName + " command");
1206 state += sizeof(MachO::arm_thread_state64_t);
1207 } else {
1208 return malformedError(Msg: "load command " + Twine(LoadCommandIndex) +
1209 " unknown flavor (" + Twine(flavor) + ") for "
1210 "flavor number " + Twine(nflavor) + " in " +
1211 CmdName + " command");
1212 }
1213 } else if (cputype == MachO::CPU_TYPE_POWERPC) {
1214 if (flavor == MachO::PPC_THREAD_STATE) {
1215 if (count != MachO::PPC_THREAD_STATE_COUNT)
1216 return malformedError(Msg: "load command " + Twine(LoadCommandIndex) +
1217 " count not PPC_THREAD_STATE_COUNT for "
1218 "flavor number " + Twine(nflavor) + " which is "
1219 "a PPC_THREAD_STATE flavor in " + CmdName +
1220 " command");
1221 if (state + sizeof(MachO::ppc_thread_state32_t) > end)
1222 return malformedError(Msg: "load command " + Twine(LoadCommandIndex) +
1223 " PPC_THREAD_STATE extends past end of "
1224 "command in " + CmdName + " command");
1225 state += sizeof(MachO::ppc_thread_state32_t);
1226 } else {
1227 return malformedError(Msg: "load command " + Twine(LoadCommandIndex) +
1228 " unknown flavor (" + Twine(flavor) + ") for "
1229 "flavor number " + Twine(nflavor) + " in " +
1230 CmdName + " command");
1231 }
1232 } else {
1233 return malformedError(Msg: "unknown cputype (" + Twine(cputype) + ") load "
1234 "command " + Twine(LoadCommandIndex) + " for " +
1235 CmdName + " command can't be checked");
1236 }
1237 nflavor++;
1238 }
1239 return Error::success();
1240}
1241
1242static Error checkTwoLevelHintsCommand(const MachOObjectFile &Obj,
1243 const MachOObjectFile::LoadCommandInfo
1244 &Load,
1245 uint32_t LoadCommandIndex,
1246 const char **LoadCmd,
1247 std::list<MachOElement> &Elements) {
1248 if (Load.C.cmdsize != sizeof(MachO::twolevel_hints_command))
1249 return malformedError(Msg: "load command " + Twine(LoadCommandIndex) +
1250 " LC_TWOLEVEL_HINTS has incorrect cmdsize");
1251 if (*LoadCmd != nullptr)
1252 return malformedError(Msg: "more than one LC_TWOLEVEL_HINTS command");
1253 auto HintsOrErr = getStructOrErr<MachO::twolevel_hints_command>(O: Obj, P: Load.Ptr);
1254 if(!HintsOrErr)
1255 return HintsOrErr.takeError();
1256 MachO::twolevel_hints_command Hints = HintsOrErr.get();
1257 uint64_t FileSize = Obj.getData().size();
1258 if (Hints.offset > FileSize)
1259 return malformedError(Msg: "offset field of LC_TWOLEVEL_HINTS command " +
1260 Twine(LoadCommandIndex) + " extends past the end of "
1261 "the file");
1262 uint64_t BigSize = Hints.nhints;
1263 BigSize *= sizeof(MachO::twolevel_hint);
1264 BigSize += Hints.offset;
1265 if (BigSize > FileSize)
1266 return malformedError(Msg: "offset field plus nhints times sizeof(struct "
1267 "twolevel_hint) field of LC_TWOLEVEL_HINTS command " +
1268 Twine(LoadCommandIndex) + " extends past the end of "
1269 "the file");
1270 if (Error Err = checkOverlappingElement(Elements, Offset: Hints.offset, Size: Hints.nhints *
1271 sizeof(MachO::twolevel_hint),
1272 Name: "two level hints"))
1273 return Err;
1274 *LoadCmd = Load.Ptr;
1275 return Error::success();
1276}
1277
1278// Returns true if the libObject code does not support the load command and its
1279// contents. The cmd value it is treated as an unknown load command but with
1280// an error message that says the cmd value is obsolete.
1281static bool isLoadCommandObsolete(uint32_t cmd) {
1282 if (cmd == MachO::LC_SYMSEG ||
1283 cmd == MachO::LC_LOADFVMLIB ||
1284 cmd == MachO::LC_IDFVMLIB ||
1285 cmd == MachO::LC_IDENT ||
1286 cmd == MachO::LC_FVMFILE ||
1287 cmd == MachO::LC_PREPAGE ||
1288 cmd == MachO::LC_PREBOUND_DYLIB ||
1289 cmd == MachO::LC_TWOLEVEL_HINTS ||
1290 cmd == MachO::LC_PREBIND_CKSUM)
1291 return true;
1292 return false;
1293}
1294
1295Expected<std::unique_ptr<MachOObjectFile>>
1296MachOObjectFile::create(MemoryBufferRef Object, bool IsLittleEndian,
1297 bool Is64Bits, uint32_t UniversalCputype,
1298 uint32_t UniversalIndex,
1299 size_t MachOFilesetEntryOffset) {
1300 Error Err = Error::success();
1301 std::unique_ptr<MachOObjectFile> Obj(new MachOObjectFile(
1302 std::move(Object), IsLittleEndian, Is64Bits, Err, UniversalCputype,
1303 UniversalIndex, MachOFilesetEntryOffset));
1304 if (Err)
1305 return std::move(Err);
1306 return std::move(Obj);
1307}
1308
1309MachOObjectFile::MachOObjectFile(MemoryBufferRef Object, bool IsLittleEndian,
1310 bool Is64bits, Error &Err,
1311 uint32_t UniversalCputype,
1312 uint32_t UniversalIndex,
1313 size_t MachOFilesetEntryOffset)
1314 : ObjectFile(getMachOType(isLE: IsLittleEndian, is64Bits: Is64bits), Object),
1315 MachOFilesetEntryOffset(MachOFilesetEntryOffset) {
1316 ErrorAsOutParameter ErrAsOutParam(Err);
1317 uint64_t SizeOfHeaders;
1318 uint32_t cputype;
1319 if (is64Bit()) {
1320 parseHeader(Obj: *this, Header&: Header64, Err);
1321 SizeOfHeaders = sizeof(MachO::mach_header_64);
1322 cputype = Header64.cputype;
1323 } else {
1324 parseHeader(Obj: *this, Header&: Header, Err);
1325 SizeOfHeaders = sizeof(MachO::mach_header);
1326 cputype = Header.cputype;
1327 }
1328 if (Err)
1329 return;
1330 SizeOfHeaders += getHeader().sizeofcmds;
1331 if (getData().data() + SizeOfHeaders > getData().end()) {
1332 Err = malformedError(Msg: "load commands extend past the end of the file");
1333 return;
1334 }
1335 if (UniversalCputype != 0 && cputype != UniversalCputype) {
1336 Err = malformedError(Msg: "universal header architecture: " +
1337 Twine(UniversalIndex) + "'s cputype does not match "
1338 "object file's mach header");
1339 return;
1340 }
1341 std::list<MachOElement> Elements;
1342 Elements.push_back(x: {.Offset: 0, .Size: SizeOfHeaders, .Name: "Mach-O headers"});
1343
1344 uint32_t LoadCommandCount = getHeader().ncmds;
1345 LoadCommandInfo Load;
1346 if (LoadCommandCount != 0) {
1347 if (auto LoadOrErr = getFirstLoadCommandInfo(Obj: *this))
1348 Load = *LoadOrErr;
1349 else {
1350 Err = LoadOrErr.takeError();
1351 return;
1352 }
1353 }
1354
1355 const char *DyldIdLoadCmd = nullptr;
1356 const char *SplitInfoLoadCmd = nullptr;
1357 const char *CodeSignDrsLoadCmd = nullptr;
1358 const char *CodeSignLoadCmd = nullptr;
1359 const char *VersLoadCmd = nullptr;
1360 const char *SourceLoadCmd = nullptr;
1361 const char *EntryPointLoadCmd = nullptr;
1362 const char *EncryptLoadCmd = nullptr;
1363 const char *RoutinesLoadCmd = nullptr;
1364 const char *UnixThreadLoadCmd = nullptr;
1365 const char *TwoLevelHintsLoadCmd = nullptr;
1366 for (unsigned I = 0; I < LoadCommandCount; ++I) {
1367 if (is64Bit()) {
1368 if (Load.C.cmdsize % 8 != 0) {
1369 // We have a hack here to allow 64-bit Mach-O core files to have
1370 // LC_THREAD commands that are only a multiple of 4 and not 8 to be
1371 // allowed since the macOS kernel produces them.
1372 if (getHeader().filetype != MachO::MH_CORE ||
1373 Load.C.cmd != MachO::LC_THREAD || Load.C.cmdsize % 4) {
1374 Err = malformedError(Msg: "load command " + Twine(I) + " cmdsize not a "
1375 "multiple of 8");
1376 return;
1377 }
1378 }
1379 } else {
1380 if (Load.C.cmdsize % 4 != 0) {
1381 Err = malformedError(Msg: "load command " + Twine(I) + " cmdsize not a "
1382 "multiple of 4");
1383 return;
1384 }
1385 }
1386 LoadCommands.push_back(Elt: Load);
1387 if (Load.C.cmd == MachO::LC_SYMTAB) {
1388 if ((Err = checkSymtabCommand(Obj: *this, Load, LoadCommandIndex: I, SymtabLoadCmd: &SymtabLoadCmd, Elements)))
1389 return;
1390 } else if (Load.C.cmd == MachO::LC_DYSYMTAB) {
1391 if ((Err = checkDysymtabCommand(Obj: *this, Load, LoadCommandIndex: I, DysymtabLoadCmd: &DysymtabLoadCmd,
1392 Elements)))
1393 return;
1394 } else if (Load.C.cmd == MachO::LC_DATA_IN_CODE) {
1395 if ((Err = checkLinkeditDataCommand(Obj: *this, Load, LoadCommandIndex: I, LoadCmd: &DataInCodeLoadCmd,
1396 CmdName: "LC_DATA_IN_CODE", Elements,
1397 ElementName: "data in code info")))
1398 return;
1399 } else if (Load.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
1400 if ((Err = checkLinkeditDataCommand(Obj: *this, Load, LoadCommandIndex: I, LoadCmd: &LinkOptHintsLoadCmd,
1401 CmdName: "LC_LINKER_OPTIMIZATION_HINT",
1402 Elements, ElementName: "linker optimization "
1403 "hints")))
1404 return;
1405 } else if (Load.C.cmd == MachO::LC_FUNCTION_STARTS) {
1406 if ((Err = checkLinkeditDataCommand(Obj: *this, Load, LoadCommandIndex: I, LoadCmd: &FuncStartsLoadCmd,
1407 CmdName: "LC_FUNCTION_STARTS", Elements,
1408 ElementName: "function starts data")))
1409 return;
1410 } else if (Load.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO) {
1411 if ((Err = checkLinkeditDataCommand(Obj: *this, Load, LoadCommandIndex: I, LoadCmd: &SplitInfoLoadCmd,
1412 CmdName: "LC_SEGMENT_SPLIT_INFO", Elements,
1413 ElementName: "split info data")))
1414 return;
1415 } else if (Load.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS) {
1416 if ((Err = checkLinkeditDataCommand(Obj: *this, Load, LoadCommandIndex: I, LoadCmd: &CodeSignDrsLoadCmd,
1417 CmdName: "LC_DYLIB_CODE_SIGN_DRS", Elements,
1418 ElementName: "code signing RDs data")))
1419 return;
1420 } else if (Load.C.cmd == MachO::LC_CODE_SIGNATURE) {
1421 if ((Err = checkLinkeditDataCommand(Obj: *this, Load, LoadCommandIndex: I, LoadCmd: &CodeSignLoadCmd,
1422 CmdName: "LC_CODE_SIGNATURE", Elements,
1423 ElementName: "code signature data")))
1424 return;
1425 } else if (Load.C.cmd == MachO::LC_DYLD_INFO) {
1426 if ((Err = checkDyldInfoCommand(Obj: *this, Load, LoadCommandIndex: I, LoadCmd: &DyldInfoLoadCmd,
1427 CmdName: "LC_DYLD_INFO", Elements)))
1428 return;
1429 } else if (Load.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
1430 if ((Err = checkDyldInfoCommand(Obj: *this, Load, LoadCommandIndex: I, LoadCmd: &DyldInfoLoadCmd,
1431 CmdName: "LC_DYLD_INFO_ONLY", Elements)))
1432 return;
1433 } else if (Load.C.cmd == MachO::LC_DYLD_CHAINED_FIXUPS) {
1434 if ((Err = checkLinkeditDataCommand(
1435 Obj: *this, Load, LoadCommandIndex: I, LoadCmd: &DyldChainedFixupsLoadCmd,
1436 CmdName: "LC_DYLD_CHAINED_FIXUPS", Elements, ElementName: "chained fixups")))
1437 return;
1438 } else if (Load.C.cmd == MachO::LC_DYLD_EXPORTS_TRIE) {
1439 if ((Err = checkLinkeditDataCommand(
1440 Obj: *this, Load, LoadCommandIndex: I, LoadCmd: &DyldExportsTrieLoadCmd, CmdName: "LC_DYLD_EXPORTS_TRIE",
1441 Elements, ElementName: "exports trie")))
1442 return;
1443 } else if (Load.C.cmd == MachO::LC_UUID) {
1444 if (Load.C.cmdsize != sizeof(MachO::uuid_command)) {
1445 Err = malformedError(Msg: "LC_UUID command " + Twine(I) + " has incorrect "
1446 "cmdsize");
1447 return;
1448 }
1449 if (UuidLoadCmd) {
1450 Err = malformedError(Msg: "more than one LC_UUID command");
1451 return;
1452 }
1453 UuidLoadCmd = Load.Ptr;
1454 } else if (Load.C.cmd == MachO::LC_SEGMENT_64) {
1455 if ((Err = parseSegmentLoadCommand<MachO::segment_command_64,
1456 MachO::section_64>(
1457 Obj: *this, Load, Sections, IsPageZeroSegment&: HasPageZeroSegment, LoadCommandIndex: I,
1458 CmdName: "LC_SEGMENT_64", SizeOfHeaders, Elements)))
1459 return;
1460 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
1461 if ((Err = parseSegmentLoadCommand<MachO::segment_command,
1462 MachO::section>(
1463 Obj: *this, Load, Sections, IsPageZeroSegment&: HasPageZeroSegment, LoadCommandIndex: I,
1464 CmdName: "LC_SEGMENT", SizeOfHeaders, Elements)))
1465 return;
1466 } else if (Load.C.cmd == MachO::LC_ID_DYLIB) {
1467 if ((Err = checkDylibIdCommand(Obj: *this, Load, LoadCommandIndex: I, LoadCmd: &DyldIdLoadCmd)))
1468 return;
1469 } else if (Load.C.cmd == MachO::LC_LOAD_DYLIB) {
1470 if ((Err = checkDylibCommand(Obj: *this, Load, LoadCommandIndex: I, CmdName: "LC_LOAD_DYLIB")))
1471 return;
1472 Libraries.push_back(Elt: Load.Ptr);
1473 } else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB) {
1474 if ((Err = checkDylibCommand(Obj: *this, Load, LoadCommandIndex: I, CmdName: "LC_LOAD_WEAK_DYLIB")))
1475 return;
1476 Libraries.push_back(Elt: Load.Ptr);
1477 } else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB) {
1478 if ((Err = checkDylibCommand(Obj: *this, Load, LoadCommandIndex: I, CmdName: "LC_LAZY_LOAD_DYLIB")))
1479 return;
1480 Libraries.push_back(Elt: Load.Ptr);
1481 } else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB) {
1482 if ((Err = checkDylibCommand(Obj: *this, Load, LoadCommandIndex: I, CmdName: "LC_REEXPORT_DYLIB")))
1483 return;
1484 Libraries.push_back(Elt: Load.Ptr);
1485 } else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
1486 if ((Err = checkDylibCommand(Obj: *this, Load, LoadCommandIndex: I, CmdName: "LC_LOAD_UPWARD_DYLIB")))
1487 return;
1488 Libraries.push_back(Elt: Load.Ptr);
1489 } else if (Load.C.cmd == MachO::LC_ID_DYLINKER) {
1490 if ((Err = checkDyldCommand(Obj: *this, Load, LoadCommandIndex: I, CmdName: "LC_ID_DYLINKER")))
1491 return;
1492 } else if (Load.C.cmd == MachO::LC_LOAD_DYLINKER) {
1493 if ((Err = checkDyldCommand(Obj: *this, Load, LoadCommandIndex: I, CmdName: "LC_LOAD_DYLINKER")))
1494 return;
1495 } else if (Load.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
1496 if ((Err = checkDyldCommand(Obj: *this, Load, LoadCommandIndex: I, CmdName: "LC_DYLD_ENVIRONMENT")))
1497 return;
1498 } else if (Load.C.cmd == MachO::LC_VERSION_MIN_MACOSX) {
1499 if ((Err = checkVersCommand(Obj: *this, Load, LoadCommandIndex: I, LoadCmd: &VersLoadCmd,
1500 CmdName: "LC_VERSION_MIN_MACOSX")))
1501 return;
1502 } else if (Load.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS) {
1503 if ((Err = checkVersCommand(Obj: *this, Load, LoadCommandIndex: I, LoadCmd: &VersLoadCmd,
1504 CmdName: "LC_VERSION_MIN_IPHONEOS")))
1505 return;
1506 } else if (Load.C.cmd == MachO::LC_VERSION_MIN_TVOS) {
1507 if ((Err = checkVersCommand(Obj: *this, Load, LoadCommandIndex: I, LoadCmd: &VersLoadCmd,
1508 CmdName: "LC_VERSION_MIN_TVOS")))
1509 return;
1510 } else if (Load.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
1511 if ((Err = checkVersCommand(Obj: *this, Load, LoadCommandIndex: I, LoadCmd: &VersLoadCmd,
1512 CmdName: "LC_VERSION_MIN_WATCHOS")))
1513 return;
1514 } else if (Load.C.cmd == MachO::LC_NOTE) {
1515 if ((Err = checkNoteCommand(Obj: *this, Load, LoadCommandIndex: I, Elements)))
1516 return;
1517 } else if (Load.C.cmd == MachO::LC_BUILD_VERSION) {
1518 if ((Err = parseBuildVersionCommand(Obj: *this, Load, BuildTools, LoadCommandIndex: I)))
1519 return;
1520 } else if (Load.C.cmd == MachO::LC_TARGET_TRIPLE) {
1521 if ((Err = checkTargetTripleCommand(Obj: *this, Load, LoadCommandIndex: I)))
1522 return;
1523 } else if (Load.C.cmd == MachO::LC_RPATH) {
1524 if ((Err = checkRpathCommand(Obj: *this, Load, LoadCommandIndex: I)))
1525 return;
1526 } else if (Load.C.cmd == MachO::LC_SOURCE_VERSION) {
1527 if (Load.C.cmdsize != sizeof(MachO::source_version_command)) {
1528 Err = malformedError(Msg: "LC_SOURCE_VERSION command " + Twine(I) +
1529 " has incorrect cmdsize");
1530 return;
1531 }
1532 if (SourceLoadCmd) {
1533 Err = malformedError(Msg: "more than one LC_SOURCE_VERSION command");
1534 return;
1535 }
1536 SourceLoadCmd = Load.Ptr;
1537 } else if (Load.C.cmd == MachO::LC_MAIN) {
1538 if (Load.C.cmdsize != sizeof(MachO::entry_point_command)) {
1539 Err = malformedError(Msg: "LC_MAIN command " + Twine(I) +
1540 " has incorrect cmdsize");
1541 return;
1542 }
1543 if (EntryPointLoadCmd) {
1544 Err = malformedError(Msg: "more than one LC_MAIN command");
1545 return;
1546 }
1547 EntryPointLoadCmd = Load.Ptr;
1548 } else if (Load.C.cmd == MachO::LC_ENCRYPTION_INFO) {
1549 if (Load.C.cmdsize != sizeof(MachO::encryption_info_command)) {
1550 Err = malformedError(Msg: "LC_ENCRYPTION_INFO command " + Twine(I) +
1551 " has incorrect cmdsize");
1552 return;
1553 }
1554 MachO::encryption_info_command E =
1555 getStruct<MachO::encryption_info_command>(O: *this, P: Load.Ptr);
1556 if ((Err = checkEncryptCommand(Obj: *this, Load, LoadCommandIndex: I, cryptoff: E.cryptoff, cryptsize: E.cryptsize,
1557 LoadCmd: &EncryptLoadCmd, CmdName: "LC_ENCRYPTION_INFO")))
1558 return;
1559 } else if (Load.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
1560 if (Load.C.cmdsize != sizeof(MachO::encryption_info_command_64)) {
1561 Err = malformedError(Msg: "LC_ENCRYPTION_INFO_64 command " + Twine(I) +
1562 " has incorrect cmdsize");
1563 return;
1564 }
1565 MachO::encryption_info_command_64 E =
1566 getStruct<MachO::encryption_info_command_64>(O: *this, P: Load.Ptr);
1567 if ((Err = checkEncryptCommand(Obj: *this, Load, LoadCommandIndex: I, cryptoff: E.cryptoff, cryptsize: E.cryptsize,
1568 LoadCmd: &EncryptLoadCmd, CmdName: "LC_ENCRYPTION_INFO_64")))
1569 return;
1570 } else if (Load.C.cmd == MachO::LC_LINKER_OPTION) {
1571 if ((Err = checkLinkerOptCommand(Obj: *this, Load, LoadCommandIndex: I)))
1572 return;
1573 } else if (Load.C.cmd == MachO::LC_SUB_FRAMEWORK) {
1574 if (Load.C.cmdsize < sizeof(MachO::sub_framework_command)) {
1575 Err = malformedError(Msg: "load command " + Twine(I) +
1576 " LC_SUB_FRAMEWORK cmdsize too small");
1577 return;
1578 }
1579 MachO::sub_framework_command S =
1580 getStruct<MachO::sub_framework_command>(O: *this, P: Load.Ptr);
1581 if ((Err = checkSubCommand(Obj: *this, Load, LoadCommandIndex: I, CmdName: "LC_SUB_FRAMEWORK",
1582 SizeOfCmd: sizeof(MachO::sub_framework_command),
1583 CmdStructName: "sub_framework_command", PathOffset: S.umbrella,
1584 PathFieldName: "umbrella")))
1585 return;
1586 } else if (Load.C.cmd == MachO::LC_SUB_UMBRELLA) {
1587 if (Load.C.cmdsize < sizeof(MachO::sub_umbrella_command)) {
1588 Err = malformedError(Msg: "load command " + Twine(I) +
1589 " LC_SUB_UMBRELLA cmdsize too small");
1590 return;
1591 }
1592 MachO::sub_umbrella_command S =
1593 getStruct<MachO::sub_umbrella_command>(O: *this, P: Load.Ptr);
1594 if ((Err = checkSubCommand(Obj: *this, Load, LoadCommandIndex: I, CmdName: "LC_SUB_UMBRELLA",
1595 SizeOfCmd: sizeof(MachO::sub_umbrella_command),
1596 CmdStructName: "sub_umbrella_command", PathOffset: S.sub_umbrella,
1597 PathFieldName: "sub_umbrella")))
1598 return;
1599 } else if (Load.C.cmd == MachO::LC_SUB_LIBRARY) {
1600 if (Load.C.cmdsize < sizeof(MachO::sub_library_command)) {
1601 Err = malformedError(Msg: "load command " + Twine(I) +
1602 " LC_SUB_LIBRARY cmdsize too small");
1603 return;
1604 }
1605 MachO::sub_library_command S =
1606 getStruct<MachO::sub_library_command>(O: *this, P: Load.Ptr);
1607 if ((Err = checkSubCommand(Obj: *this, Load, LoadCommandIndex: I, CmdName: "LC_SUB_LIBRARY",
1608 SizeOfCmd: sizeof(MachO::sub_library_command),
1609 CmdStructName: "sub_library_command", PathOffset: S.sub_library,
1610 PathFieldName: "sub_library")))
1611 return;
1612 } else if (Load.C.cmd == MachO::LC_SUB_CLIENT) {
1613 if (Load.C.cmdsize < sizeof(MachO::sub_client_command)) {
1614 Err = malformedError(Msg: "load command " + Twine(I) +
1615 " LC_SUB_CLIENT cmdsize too small");
1616 return;
1617 }
1618 MachO::sub_client_command S =
1619 getStruct<MachO::sub_client_command>(O: *this, P: Load.Ptr);
1620 if ((Err = checkSubCommand(Obj: *this, Load, LoadCommandIndex: I, CmdName: "LC_SUB_CLIENT",
1621 SizeOfCmd: sizeof(MachO::sub_client_command),
1622 CmdStructName: "sub_client_command", PathOffset: S.client, PathFieldName: "client")))
1623 return;
1624 } else if (Load.C.cmd == MachO::LC_ROUTINES) {
1625 if (Load.C.cmdsize != sizeof(MachO::routines_command)) {
1626 Err = malformedError(Msg: "LC_ROUTINES command " + Twine(I) +
1627 " has incorrect cmdsize");
1628 return;
1629 }
1630 if (RoutinesLoadCmd) {
1631 Err = malformedError(Msg: "more than one LC_ROUTINES and or LC_ROUTINES_64 "
1632 "command");
1633 return;
1634 }
1635 RoutinesLoadCmd = Load.Ptr;
1636 } else if (Load.C.cmd == MachO::LC_ROUTINES_64) {
1637 if (Load.C.cmdsize != sizeof(MachO::routines_command_64)) {
1638 Err = malformedError(Msg: "LC_ROUTINES_64 command " + Twine(I) +
1639 " has incorrect cmdsize");
1640 return;
1641 }
1642 if (RoutinesLoadCmd) {
1643 Err = malformedError(Msg: "more than one LC_ROUTINES_64 and or LC_ROUTINES "
1644 "command");
1645 return;
1646 }
1647 RoutinesLoadCmd = Load.Ptr;
1648 } else if (Load.C.cmd == MachO::LC_UNIXTHREAD) {
1649 if ((Err = checkThreadCommand(Obj: *this, Load, LoadCommandIndex: I, CmdName: "LC_UNIXTHREAD")))
1650 return;
1651 if (UnixThreadLoadCmd) {
1652 Err = malformedError(Msg: "more than one LC_UNIXTHREAD command");
1653 return;
1654 }
1655 UnixThreadLoadCmd = Load.Ptr;
1656 } else if (Load.C.cmd == MachO::LC_THREAD) {
1657 if ((Err = checkThreadCommand(Obj: *this, Load, LoadCommandIndex: I, CmdName: "LC_THREAD")))
1658 return;
1659 // Note: LC_TWOLEVEL_HINTS is really obsolete and is not supported.
1660 } else if (Load.C.cmd == MachO::LC_TWOLEVEL_HINTS) {
1661 if ((Err = checkTwoLevelHintsCommand(Obj: *this, Load, LoadCommandIndex: I,
1662 LoadCmd: &TwoLevelHintsLoadCmd, Elements)))
1663 return;
1664 } else if (Load.C.cmd == MachO::LC_IDENT) {
1665 // Note: LC_IDENT is ignored.
1666 continue;
1667 } else if (isLoadCommandObsolete(cmd: Load.C.cmd)) {
1668 Err = malformedError(Msg: "load command " + Twine(I) + " for cmd value of: " +
1669 Twine(Load.C.cmd) + " is obsolete and not "
1670 "supported");
1671 return;
1672 }
1673 // TODO: generate a error for unknown load commands by default. But still
1674 // need work out an approach to allow or not allow unknown values like this
1675 // as an option for some uses like lldb.
1676 if (I < LoadCommandCount - 1) {
1677 if (auto LoadOrErr = getNextLoadCommandInfo(Obj: *this, LoadCommandIndex: I, L: Load))
1678 Load = *LoadOrErr;
1679 else {
1680 Err = LoadOrErr.takeError();
1681 return;
1682 }
1683 }
1684 }
1685 if (!SymtabLoadCmd) {
1686 if (DysymtabLoadCmd) {
1687 Err = malformedError(Msg: "contains LC_DYSYMTAB load command without a "
1688 "LC_SYMTAB load command");
1689 return;
1690 }
1691 } else if (DysymtabLoadCmd) {
1692 MachO::symtab_command Symtab =
1693 getStruct<MachO::symtab_command>(O: *this, P: SymtabLoadCmd);
1694 MachO::dysymtab_command Dysymtab =
1695 getStruct<MachO::dysymtab_command>(O: *this, P: DysymtabLoadCmd);
1696 if (Dysymtab.nlocalsym != 0 && Dysymtab.ilocalsym > Symtab.nsyms) {
1697 Err = malformedError(Msg: "ilocalsym in LC_DYSYMTAB load command "
1698 "extends past the end of the symbol table");
1699 return;
1700 }
1701 uint64_t BigSize = Dysymtab.ilocalsym;
1702 BigSize += Dysymtab.nlocalsym;
1703 if (Dysymtab.nlocalsym != 0 && BigSize > Symtab.nsyms) {
1704 Err = malformedError(Msg: "ilocalsym plus nlocalsym in LC_DYSYMTAB load "
1705 "command extends past the end of the symbol table");
1706 return;
1707 }
1708 if (Dysymtab.nextdefsym != 0 && Dysymtab.iextdefsym > Symtab.nsyms) {
1709 Err = malformedError(Msg: "iextdefsym in LC_DYSYMTAB load command "
1710 "extends past the end of the symbol table");
1711 return;
1712 }
1713 BigSize = Dysymtab.iextdefsym;
1714 BigSize += Dysymtab.nextdefsym;
1715 if (Dysymtab.nextdefsym != 0 && BigSize > Symtab.nsyms) {
1716 Err = malformedError(Msg: "iextdefsym plus nextdefsym in LC_DYSYMTAB "
1717 "load command extends past the end of the symbol "
1718 "table");
1719 return;
1720 }
1721 if (Dysymtab.nundefsym != 0 && Dysymtab.iundefsym > Symtab.nsyms) {
1722 Err = malformedError(Msg: "iundefsym in LC_DYSYMTAB load command "
1723 "extends past the end of the symbol table");
1724 return;
1725 }
1726 BigSize = Dysymtab.iundefsym;
1727 BigSize += Dysymtab.nundefsym;
1728 if (Dysymtab.nundefsym != 0 && BigSize > Symtab.nsyms) {
1729 Err = malformedError(Msg: "iundefsym plus nundefsym in LC_DYSYMTAB load "
1730 " command extends past the end of the symbol table");
1731 return;
1732 }
1733 }
1734 if ((getHeader().filetype == MachO::MH_DYLIB ||
1735 getHeader().filetype == MachO::MH_DYLIB_STUB) &&
1736 DyldIdLoadCmd == nullptr) {
1737 Err = malformedError(Msg: "no LC_ID_DYLIB load command in dynamic library "
1738 "filetype");
1739 return;
1740 }
1741 assert(LoadCommands.size() == LoadCommandCount);
1742
1743 Err = Error::success();
1744}
1745
1746Error MachOObjectFile::checkSymbolTable() const {
1747 uint32_t Flags = 0;
1748 if (is64Bit()) {
1749 MachO::mach_header_64 H_64 = MachOObjectFile::getHeader64();
1750 Flags = H_64.flags;
1751 } else {
1752 MachO::mach_header H = MachOObjectFile::getHeader();
1753 Flags = H.flags;
1754 }
1755 uint8_t NType = 0;
1756 uint8_t NSect = 0;
1757 uint16_t NDesc = 0;
1758 uint32_t NStrx = 0;
1759 uint64_t NValue = 0;
1760 uint32_t SymbolIndex = 0;
1761 MachO::symtab_command S = getSymtabLoadCommand();
1762 for (const SymbolRef &Symbol : symbols()) {
1763 DataRefImpl SymDRI = Symbol.getRawDataRefImpl();
1764 if (is64Bit()) {
1765 MachO::nlist_64 STE_64 = getSymbol64TableEntry(DRI: SymDRI);
1766 NType = STE_64.n_type;
1767 NSect = STE_64.n_sect;
1768 NDesc = STE_64.n_desc;
1769 NStrx = STE_64.n_strx;
1770 NValue = STE_64.n_value;
1771 } else {
1772 MachO::nlist STE = getSymbolTableEntry(DRI: SymDRI);
1773 NType = STE.n_type;
1774 NSect = STE.n_sect;
1775 NDesc = STE.n_desc;
1776 NStrx = STE.n_strx;
1777 NValue = STE.n_value;
1778 }
1779 if ((NType & MachO::N_STAB) == 0) {
1780 if ((NType & MachO::N_TYPE) == MachO::N_SECT) {
1781 if (NSect == 0 || NSect > Sections.size())
1782 return malformedError(Msg: "bad section index: " + Twine((int)NSect) +
1783 " for symbol at index " + Twine(SymbolIndex));
1784 }
1785 if ((NType & MachO::N_TYPE) == MachO::N_INDR) {
1786 if (NValue >= S.strsize)
1787 return malformedError(Msg: "bad n_value: " + Twine((int)NValue) + " past "
1788 "the end of string table, for N_INDR symbol at "
1789 "index " + Twine(SymbolIndex));
1790 }
1791 if ((Flags & MachO::MH_TWOLEVEL) == MachO::MH_TWOLEVEL &&
1792 (((NType & MachO::N_TYPE) == MachO::N_UNDF && NValue == 0) ||
1793 (NType & MachO::N_TYPE) == MachO::N_PBUD)) {
1794 uint32_t LibraryOrdinal = MachO::GET_LIBRARY_ORDINAL(n_desc: NDesc);
1795 if (LibraryOrdinal != 0 &&
1796 LibraryOrdinal != MachO::EXECUTABLE_ORDINAL &&
1797 LibraryOrdinal != MachO::DYNAMIC_LOOKUP_ORDINAL &&
1798 LibraryOrdinal - 1 >= Libraries.size() ) {
1799 return malformedError(Msg: "bad library ordinal: " + Twine(LibraryOrdinal) +
1800 " for symbol at index " + Twine(SymbolIndex));
1801 }
1802 }
1803 }
1804 if (NStrx >= S.strsize)
1805 return malformedError(Msg: "bad string table index: " + Twine((int)NStrx) +
1806 " past the end of string table, for symbol at "
1807 "index " + Twine(SymbolIndex));
1808 SymbolIndex++;
1809 }
1810 return Error::success();
1811}
1812
1813void MachOObjectFile::moveSymbolNext(DataRefImpl &Symb) const {
1814 unsigned SymbolTableEntrySize = is64Bit() ?
1815 sizeof(MachO::nlist_64) :
1816 sizeof(MachO::nlist);
1817 Symb.p += SymbolTableEntrySize;
1818}
1819
1820Expected<StringRef> MachOObjectFile::getSymbolName(DataRefImpl Symb) const {
1821 StringRef StringTable = getStringTableData();
1822 MachO::nlist_base Entry = getSymbolTableEntryBase(O: *this, DRI: Symb);
1823 if (Entry.n_strx == 0)
1824 // A n_strx value of 0 indicates that no name is associated with a
1825 // particular symbol table entry.
1826 return StringRef();
1827 const char *Start = &StringTable.data()[Entry.n_strx];
1828 if (Start < getData().begin() || Start >= getData().end()) {
1829 return malformedError(Msg: "bad string index: " + Twine(Entry.n_strx) +
1830 " for symbol at index " + Twine(getSymbolIndex(Symb)));
1831 }
1832 return StringRef(Start);
1833}
1834
1835unsigned MachOObjectFile::getSectionType(SectionRef Sec) const {
1836 DataRefImpl DRI = Sec.getRawDataRefImpl();
1837 uint32_t Flags = getSectionFlags(O: *this, Sec: DRI);
1838 return Flags & MachO::SECTION_TYPE;
1839}
1840
1841uint64_t MachOObjectFile::getNValue(DataRefImpl Sym) const {
1842 if (is64Bit()) {
1843 MachO::nlist_64 Entry = getSymbol64TableEntry(DRI: Sym);
1844 return Entry.n_value;
1845 }
1846 MachO::nlist Entry = getSymbolTableEntry(DRI: Sym);
1847 return Entry.n_value;
1848}
1849
1850// getIndirectName() returns the name of the alias'ed symbol who's string table
1851// index is in the n_value field.
1852std::error_code MachOObjectFile::getIndirectName(DataRefImpl Symb,
1853 StringRef &Res) const {
1854 StringRef StringTable = getStringTableData();
1855 MachO::nlist_base Entry = getSymbolTableEntryBase(O: *this, DRI: Symb);
1856 if ((Entry.n_type & MachO::N_TYPE) != MachO::N_INDR)
1857 return object_error::parse_failed;
1858 uint64_t NValue = getNValue(Sym: Symb);
1859 if (NValue >= StringTable.size())
1860 return object_error::parse_failed;
1861 const char *Start = &StringTable.data()[NValue];
1862 Res = StringRef(Start);
1863 return std::error_code();
1864}
1865
1866uint64_t MachOObjectFile::getSymbolValueImpl(DataRefImpl Sym) const {
1867 return getNValue(Sym);
1868}
1869
1870Expected<uint64_t> MachOObjectFile::getSymbolAddress(DataRefImpl Sym) const {
1871 return getSymbolValue(Symb: Sym);
1872}
1873
1874uint32_t MachOObjectFile::getSymbolAlignment(DataRefImpl DRI) const {
1875 uint32_t Flags = cantFail(ValOrErr: getSymbolFlags(Symb: DRI));
1876 if (Flags & SymbolRef::SF_Common) {
1877 MachO::nlist_base Entry = getSymbolTableEntryBase(O: *this, DRI);
1878 return 1 << MachO::GET_COMM_ALIGN(n_desc: Entry.n_desc);
1879 }
1880 return 0;
1881}
1882
1883uint64_t MachOObjectFile::getCommonSymbolSizeImpl(DataRefImpl DRI) const {
1884 return getNValue(Sym: DRI);
1885}
1886
1887Expected<SymbolRef::Type>
1888MachOObjectFile::getSymbolType(DataRefImpl Symb) const {
1889 MachO::nlist_base Entry = getSymbolTableEntryBase(O: *this, DRI: Symb);
1890 uint8_t n_type = Entry.n_type;
1891
1892 // If this is a STAB debugging symbol, we can do nothing more.
1893 if (n_type & MachO::N_STAB)
1894 return SymbolRef::ST_Debug;
1895
1896 switch (n_type & MachO::N_TYPE) {
1897 case MachO::N_UNDF :
1898 return SymbolRef::ST_Unknown;
1899 case MachO::N_SECT :
1900 Expected<section_iterator> SecOrError = getSymbolSection(Symb);
1901 if (!SecOrError)
1902 return SecOrError.takeError();
1903 section_iterator Sec = *SecOrError;
1904 if (Sec == section_end())
1905 return SymbolRef::ST_Other;
1906 if (Sec->isData() || Sec->isBSS())
1907 return SymbolRef::ST_Data;
1908 return SymbolRef::ST_Function;
1909 }
1910 return SymbolRef::ST_Other;
1911}
1912
1913Expected<uint32_t> MachOObjectFile::getSymbolFlags(DataRefImpl DRI) const {
1914 MachO::nlist_base Entry = getSymbolTableEntryBase(O: *this, DRI);
1915
1916 uint8_t MachOType = Entry.n_type;
1917 uint16_t MachOFlags = Entry.n_desc;
1918
1919 uint32_t Result = SymbolRef::SF_None;
1920
1921 if ((MachOType & MachO::N_TYPE) == MachO::N_INDR)
1922 Result |= SymbolRef::SF_Indirect;
1923
1924 if (MachOType & MachO::N_STAB)
1925 Result |= SymbolRef::SF_FormatSpecific;
1926
1927 if (MachOType & MachO::N_EXT) {
1928 Result |= SymbolRef::SF_Global;
1929 if ((MachOType & MachO::N_TYPE) == MachO::N_UNDF) {
1930 if (getNValue(Sym: DRI))
1931 Result |= SymbolRef::SF_Common;
1932 else
1933 Result |= SymbolRef::SF_Undefined;
1934 }
1935
1936 if (MachOType & MachO::N_PEXT)
1937 Result |= SymbolRef::SF_Hidden;
1938 else
1939 Result |= SymbolRef::SF_Exported;
1940
1941 } else if (MachOType & MachO::N_PEXT)
1942 Result |= SymbolRef::SF_Hidden;
1943
1944 if (MachOFlags & (MachO::N_WEAK_REF | MachO::N_WEAK_DEF))
1945 Result |= SymbolRef::SF_Weak;
1946
1947 if (MachOFlags & (MachO::N_ARM_THUMB_DEF))
1948 Result |= SymbolRef::SF_Thumb;
1949
1950 if ((MachOType & MachO::N_TYPE) == MachO::N_ABS)
1951 Result |= SymbolRef::SF_Absolute;
1952
1953 return Result;
1954}
1955
1956Expected<section_iterator>
1957MachOObjectFile::getSymbolSection(DataRefImpl Symb) const {
1958 MachO::nlist_base Entry = getSymbolTableEntryBase(O: *this, DRI: Symb);
1959 uint8_t index = Entry.n_sect;
1960
1961 if (index == 0)
1962 return section_end();
1963 DataRefImpl DRI;
1964 DRI.d.a = index - 1;
1965 if (DRI.d.a >= Sections.size()){
1966 return malformedError(Msg: "bad section index: " + Twine((int)index) +
1967 " for symbol at index " + Twine(getSymbolIndex(Symb)));
1968 }
1969 return section_iterator(SectionRef(DRI, this));
1970}
1971
1972unsigned MachOObjectFile::getSymbolSectionID(SymbolRef Sym) const {
1973 MachO::nlist_base Entry =
1974 getSymbolTableEntryBase(O: *this, DRI: Sym.getRawDataRefImpl());
1975 return Entry.n_sect - 1;
1976}
1977
1978void MachOObjectFile::moveSectionNext(DataRefImpl &Sec) const {
1979 Sec.d.a++;
1980}
1981
1982Expected<StringRef> MachOObjectFile::getSectionName(DataRefImpl Sec) const {
1983 ArrayRef<char> Raw = getSectionRawName(Sec);
1984 return parseSegmentOrSectionName(P: Raw.data());
1985}
1986
1987uint64_t MachOObjectFile::getSectionAddress(DataRefImpl Sec) const {
1988 if (is64Bit())
1989 return getSection64(DRI: Sec).addr;
1990 return getSection(DRI: Sec).addr;
1991}
1992
1993uint64_t MachOObjectFile::getSectionIndex(DataRefImpl Sec) const {
1994 return Sec.d.a;
1995}
1996
1997uint64_t MachOObjectFile::getSectionSize(DataRefImpl Sec) const {
1998 // In the case if a malformed Mach-O file where the section offset is past
1999 // the end of the file or some part of the section size is past the end of
2000 // the file return a size of zero or a size that covers the rest of the file
2001 // but does not extend past the end of the file.
2002 uint32_t SectOffset, SectType;
2003 uint64_t SectSize;
2004
2005 if (is64Bit()) {
2006 MachO::section_64 Sect = getSection64(DRI: Sec);
2007 SectOffset = Sect.offset;
2008 SectSize = Sect.size;
2009 SectType = Sect.flags & MachO::SECTION_TYPE;
2010 } else {
2011 MachO::section Sect = getSection(DRI: Sec);
2012 SectOffset = Sect.offset;
2013 SectSize = Sect.size;
2014 SectType = Sect.flags & MachO::SECTION_TYPE;
2015 }
2016 if (SectType == MachO::S_ZEROFILL || SectType == MachO::S_GB_ZEROFILL)
2017 return SectSize;
2018 uint64_t FileSize = getData().size();
2019 if (SectOffset > FileSize)
2020 return 0;
2021 if (FileSize - SectOffset < SectSize)
2022 return FileSize - SectOffset;
2023 return SectSize;
2024}
2025
2026ArrayRef<uint8_t> MachOObjectFile::getSectionContents(uint64_t Offset,
2027 uint64_t Size) const {
2028 return arrayRefFromStringRef(Input: getData().substr(Start: Offset, N: Size));
2029}
2030
2031Expected<ArrayRef<uint8_t>>
2032MachOObjectFile::getSectionContents(DataRefImpl Sec) const {
2033 uint64_t Offset;
2034 uint64_t Size;
2035
2036 if (is64Bit()) {
2037 MachO::section_64 Sect = getSection64(DRI: Sec);
2038 Offset = Sect.offset;
2039 Size = Sect.size;
2040 // Check for large mach-o files where the section contents might exceed
2041 // 4GB. MachO::section_64 objects only have 32 bit file offsets to the
2042 // section contents and can overflow in dSYM files. We can track this and
2043 // adjust the section offset to be 64 bit safe. If sections overflow then
2044 // section ordering is enforced. If sections are not ordered, then an error
2045 // will be returned stopping invalid section data from being returned.
2046 uint64_t PrevTrueOffset = 0;
2047 uint64_t SectOffsetAdjust = 0;
2048 for (uint32_t SectIdx = 0; SectIdx < Sec.d.a; ++SectIdx) {
2049 MachO::section_64 CurrSect =
2050 getStruct<MachO::section_64>(O: *this, P: Sections[SectIdx]);
2051 uint64_t CurrTrueOffset = (uint64_t)CurrSect.offset + SectOffsetAdjust;
2052 if ((SectOffsetAdjust > 0) && (PrevTrueOffset > CurrTrueOffset))
2053 return malformedError(Msg: "section data exceeds 4GB and section file "
2054 "offsets are not ordered");
2055 const uint64_t EndSectFileOffset =
2056 (uint64_t)CurrSect.offset + CurrSect.size;
2057 if (EndSectFileOffset > UINT32_MAX)
2058 SectOffsetAdjust += EndSectFileOffset & 0xFFFFFFFF00000000ull;
2059 PrevTrueOffset = CurrTrueOffset;
2060 }
2061 Offset += SectOffsetAdjust;
2062 } else {
2063 MachO::section Sect = getSection(DRI: Sec);
2064 Offset = Sect.offset;
2065 Size = Sect.size;
2066 }
2067
2068 return getSectionContents(Offset, Size);
2069}
2070
2071uint64_t MachOObjectFile::getSectionAlignment(DataRefImpl Sec) const {
2072 uint32_t Align;
2073 if (is64Bit()) {
2074 MachO::section_64 Sect = getSection64(DRI: Sec);
2075 Align = Sect.align;
2076 } else {
2077 MachO::section Sect = getSection(DRI: Sec);
2078 Align = Sect.align;
2079 }
2080
2081 return uint64_t(1) << Align;
2082}
2083
2084Expected<SectionRef> MachOObjectFile::getSection(unsigned SectionIndex) const {
2085 if (SectionIndex < 1 || SectionIndex > Sections.size())
2086 return malformedError(Msg: "bad section index: " + Twine((int)SectionIndex));
2087
2088 DataRefImpl DRI;
2089 DRI.d.a = SectionIndex - 1;
2090 return SectionRef(DRI, this);
2091}
2092
2093Expected<SectionRef> MachOObjectFile::getSection(StringRef SectionName) const {
2094 for (const SectionRef &Section : sections()) {
2095 auto NameOrErr = Section.getName();
2096 if (!NameOrErr)
2097 return NameOrErr.takeError();
2098 if (*NameOrErr == SectionName)
2099 return Section;
2100 }
2101 return errorCodeToError(EC: object_error::parse_failed);
2102}
2103
2104bool MachOObjectFile::isSectionCompressed(DataRefImpl Sec) const {
2105 return false;
2106}
2107
2108bool MachOObjectFile::isSectionText(DataRefImpl Sec) const {
2109 uint32_t Flags = getSectionFlags(O: *this, Sec);
2110 return Flags & MachO::S_ATTR_PURE_INSTRUCTIONS;
2111}
2112
2113bool MachOObjectFile::isSectionData(DataRefImpl Sec) const {
2114 uint32_t Flags = getSectionFlags(O: *this, Sec);
2115 unsigned SectionType = Flags & MachO::SECTION_TYPE;
2116 return !(Flags & MachO::S_ATTR_PURE_INSTRUCTIONS) &&
2117 !(SectionType == MachO::S_ZEROFILL ||
2118 SectionType == MachO::S_GB_ZEROFILL);
2119}
2120
2121bool MachOObjectFile::isSectionBSS(DataRefImpl Sec) const {
2122 uint32_t Flags = getSectionFlags(O: *this, Sec);
2123 unsigned SectionType = Flags & MachO::SECTION_TYPE;
2124 return !(Flags & MachO::S_ATTR_PURE_INSTRUCTIONS) &&
2125 (SectionType == MachO::S_ZEROFILL ||
2126 SectionType == MachO::S_GB_ZEROFILL);
2127}
2128
2129bool MachOObjectFile::isDebugSection(DataRefImpl Sec) const {
2130 Expected<StringRef> SectionNameOrErr = getSectionName(Sec);
2131 if (!SectionNameOrErr) {
2132 // TODO: Report the error message properly.
2133 consumeError(Err: SectionNameOrErr.takeError());
2134 return false;
2135 }
2136 StringRef SectionName = SectionNameOrErr.get();
2137 return SectionName.starts_with(Prefix: "__debug") ||
2138 SectionName.starts_with(Prefix: "__zdebug") ||
2139 SectionName.starts_with(Prefix: "__apple") || SectionName == "__gdb_index" ||
2140 SectionName == "__swift_ast";
2141}
2142
2143namespace {
2144template <typename LoadCommandType>
2145ArrayRef<uint8_t> getSegmentContents(const MachOObjectFile &Obj,
2146 MachOObjectFile::LoadCommandInfo LoadCmd,
2147 StringRef SegmentName) {
2148 auto SegmentOrErr = getStructOrErr<LoadCommandType>(Obj, LoadCmd.Ptr);
2149 if (!SegmentOrErr) {
2150 consumeError(SegmentOrErr.takeError());
2151 return {};
2152 }
2153 auto &Segment = SegmentOrErr.get();
2154 if (StringRef(Segment.segname, 16).starts_with(Prefix: SegmentName))
2155 return arrayRefFromStringRef(Obj.getData().slice(
2156 Start: Segment.fileoff, End: Segment.fileoff + Segment.filesize));
2157 return {};
2158}
2159
2160template <typename LoadCommandType>
2161ArrayRef<uint8_t> getSegmentContents(const MachOObjectFile &Obj,
2162 MachOObjectFile::LoadCommandInfo LoadCmd) {
2163 auto SegmentOrErr = getStructOrErr<LoadCommandType>(Obj, LoadCmd.Ptr);
2164 if (!SegmentOrErr) {
2165 consumeError(SegmentOrErr.takeError());
2166 return {};
2167 }
2168 auto &Segment = SegmentOrErr.get();
2169 return arrayRefFromStringRef(
2170 Obj.getData().substr(Start: Segment.fileoff, N: Segment.filesize));
2171}
2172} // namespace
2173
2174ArrayRef<uint8_t>
2175MachOObjectFile::getSegmentContents(StringRef SegmentName) const {
2176 for (auto LoadCmd : load_commands()) {
2177 ArrayRef<uint8_t> Contents;
2178 switch (LoadCmd.C.cmd) {
2179 case MachO::LC_SEGMENT:
2180 Contents = ::getSegmentContents<MachO::segment_command>(Obj: *this, LoadCmd,
2181 SegmentName);
2182 break;
2183 case MachO::LC_SEGMENT_64:
2184 Contents = ::getSegmentContents<MachO::segment_command_64>(Obj: *this, LoadCmd,
2185 SegmentName);
2186 break;
2187 default:
2188 continue;
2189 }
2190 if (!Contents.empty())
2191 return Contents;
2192 }
2193 return {};
2194}
2195
2196ArrayRef<uint8_t>
2197MachOObjectFile::getSegmentContents(size_t SegmentIndex) const {
2198 size_t Idx = 0;
2199 for (auto LoadCmd : load_commands()) {
2200 switch (LoadCmd.C.cmd) {
2201 case MachO::LC_SEGMENT:
2202 if (Idx == SegmentIndex)
2203 return ::getSegmentContents<MachO::segment_command>(Obj: *this, LoadCmd);
2204 ++Idx;
2205 break;
2206 case MachO::LC_SEGMENT_64:
2207 if (Idx == SegmentIndex)
2208 return ::getSegmentContents<MachO::segment_command_64>(Obj: *this, LoadCmd);
2209 ++Idx;
2210 break;
2211 default:
2212 continue;
2213 }
2214 }
2215 return {};
2216}
2217
2218unsigned MachOObjectFile::getSectionID(SectionRef Sec) const {
2219 return Sec.getRawDataRefImpl().d.a;
2220}
2221
2222bool MachOObjectFile::isSectionVirtual(DataRefImpl Sec) const {
2223 uint32_t Flags = getSectionFlags(O: *this, Sec);
2224 unsigned SectionType = Flags & MachO::SECTION_TYPE;
2225 return SectionType == MachO::S_ZEROFILL ||
2226 SectionType == MachO::S_GB_ZEROFILL;
2227}
2228
2229bool MachOObjectFile::isSectionBitcode(DataRefImpl Sec) const {
2230 StringRef SegmentName = getSectionFinalSegmentName(Sec);
2231 if (Expected<StringRef> NameOrErr = getSectionName(Sec))
2232 return (SegmentName == "__LLVM" && *NameOrErr == "__bitcode");
2233 return false;
2234}
2235
2236bool MachOObjectFile::isSectionStripped(DataRefImpl Sec) const {
2237 if (is64Bit())
2238 return getSection64(DRI: Sec).offset == 0;
2239 return getSection(DRI: Sec).offset == 0;
2240}
2241
2242relocation_iterator MachOObjectFile::section_rel_begin(DataRefImpl Sec) const {
2243 DataRefImpl Ret;
2244 Ret.d.a = Sec.d.a;
2245 Ret.d.b = 0;
2246 return relocation_iterator(RelocationRef(Ret, this));
2247}
2248
2249relocation_iterator
2250MachOObjectFile::section_rel_end(DataRefImpl Sec) const {
2251 uint32_t Num;
2252 if (is64Bit()) {
2253 MachO::section_64 Sect = getSection64(DRI: Sec);
2254 Num = Sect.nreloc;
2255 } else {
2256 MachO::section Sect = getSection(DRI: Sec);
2257 Num = Sect.nreloc;
2258 }
2259
2260 DataRefImpl Ret;
2261 Ret.d.a = Sec.d.a;
2262 Ret.d.b = Num;
2263 return relocation_iterator(RelocationRef(Ret, this));
2264}
2265
2266relocation_iterator MachOObjectFile::extrel_begin() const {
2267 DataRefImpl Ret;
2268 // for DYSYMTAB symbols, Ret.d.a == 0 for external relocations
2269 Ret.d.a = 0; // Would normally be a section index.
2270 Ret.d.b = 0; // Index into the external relocations
2271 return relocation_iterator(RelocationRef(Ret, this));
2272}
2273
2274relocation_iterator MachOObjectFile::extrel_end() const {
2275 MachO::dysymtab_command DysymtabLoadCmd = getDysymtabLoadCommand();
2276 DataRefImpl Ret;
2277 // for DYSYMTAB symbols, Ret.d.a == 0 for external relocations
2278 Ret.d.a = 0; // Would normally be a section index.
2279 Ret.d.b = DysymtabLoadCmd.nextrel; // Index into the external relocations
2280 return relocation_iterator(RelocationRef(Ret, this));
2281}
2282
2283relocation_iterator MachOObjectFile::locrel_begin() const {
2284 DataRefImpl Ret;
2285 // for DYSYMTAB symbols, Ret.d.a == 1 for local relocations
2286 Ret.d.a = 1; // Would normally be a section index.
2287 Ret.d.b = 0; // Index into the local relocations
2288 return relocation_iterator(RelocationRef(Ret, this));
2289}
2290
2291relocation_iterator MachOObjectFile::locrel_end() const {
2292 MachO::dysymtab_command DysymtabLoadCmd = getDysymtabLoadCommand();
2293 DataRefImpl Ret;
2294 // for DYSYMTAB symbols, Ret.d.a == 1 for local relocations
2295 Ret.d.a = 1; // Would normally be a section index.
2296 Ret.d.b = DysymtabLoadCmd.nlocrel; // Index into the local relocations
2297 return relocation_iterator(RelocationRef(Ret, this));
2298}
2299
2300void MachOObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
2301 ++Rel.d.b;
2302}
2303
2304uint64_t MachOObjectFile::getRelocationOffset(DataRefImpl Rel) const {
2305 assert((getHeader().filetype == MachO::MH_OBJECT ||
2306 getHeader().filetype == MachO::MH_KEXT_BUNDLE) &&
2307 "Only implemented for MH_OBJECT && MH_KEXT_BUNDLE");
2308 MachO::any_relocation_info RE = getRelocation(Rel);
2309 return getAnyRelocationAddress(RE);
2310}
2311
2312symbol_iterator
2313MachOObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
2314 MachO::any_relocation_info RE = getRelocation(Rel);
2315 if (isRelocationScattered(RE))
2316 return symbol_end();
2317
2318 uint32_t SymbolIdx = getPlainRelocationSymbolNum(RE);
2319 bool isExtern = getPlainRelocationExternal(RE);
2320 if (!isExtern)
2321 return symbol_end();
2322
2323 MachO::symtab_command S = getSymtabLoadCommand();
2324 unsigned SymbolTableEntrySize = is64Bit() ?
2325 sizeof(MachO::nlist_64) :
2326 sizeof(MachO::nlist);
2327 uint64_t Offset = S.symoff + SymbolIdx * SymbolTableEntrySize;
2328 DataRefImpl Sym;
2329 Sym.p = reinterpret_cast<uintptr_t>(getPtr(O: *this, Offset));
2330 return symbol_iterator(SymbolRef(Sym, this));
2331}
2332
2333section_iterator
2334MachOObjectFile::getRelocationSection(DataRefImpl Rel) const {
2335 return section_iterator(getAnyRelocationSection(RE: getRelocation(Rel)));
2336}
2337
2338uint64_t MachOObjectFile::getRelocationType(DataRefImpl Rel) const {
2339 MachO::any_relocation_info RE = getRelocation(Rel);
2340 return getAnyRelocationType(RE);
2341}
2342
2343void MachOObjectFile::getRelocationTypeName(
2344 DataRefImpl Rel, SmallVectorImpl<char> &Result) const {
2345 StringRef res;
2346 uint64_t RType = getRelocationType(Rel);
2347
2348 unsigned Arch = this->getArch();
2349
2350 switch (Arch) {
2351 case Triple::x86: {
2352 static const char *const Table[] = {
2353 "GENERIC_RELOC_VANILLA",
2354 "GENERIC_RELOC_PAIR",
2355 "GENERIC_RELOC_SECTDIFF",
2356 "GENERIC_RELOC_PB_LA_PTR",
2357 "GENERIC_RELOC_LOCAL_SECTDIFF",
2358 "GENERIC_RELOC_TLV" };
2359
2360 if (RType > 5)
2361 res = "Unknown";
2362 else
2363 res = Table[RType];
2364 break;
2365 }
2366 case Triple::x86_64: {
2367 static const char *const Table[] = {
2368 "X86_64_RELOC_UNSIGNED",
2369 "X86_64_RELOC_SIGNED",
2370 "X86_64_RELOC_BRANCH",
2371 "X86_64_RELOC_GOT_LOAD",
2372 "X86_64_RELOC_GOT",
2373 "X86_64_RELOC_SUBTRACTOR",
2374 "X86_64_RELOC_SIGNED_1",
2375 "X86_64_RELOC_SIGNED_2",
2376 "X86_64_RELOC_SIGNED_4",
2377 "X86_64_RELOC_TLV" };
2378
2379 if (RType > 9)
2380 res = "Unknown";
2381 else
2382 res = Table[RType];
2383 break;
2384 }
2385 case Triple::arm: {
2386 static const char *const Table[] = {
2387 "ARM_RELOC_VANILLA",
2388 "ARM_RELOC_PAIR",
2389 "ARM_RELOC_SECTDIFF",
2390 "ARM_RELOC_LOCAL_SECTDIFF",
2391 "ARM_RELOC_PB_LA_PTR",
2392 "ARM_RELOC_BR24",
2393 "ARM_THUMB_RELOC_BR22",
2394 "ARM_THUMB_32BIT_BRANCH",
2395 "ARM_RELOC_HALF",
2396 "ARM_RELOC_HALF_SECTDIFF" };
2397
2398 if (RType > 9)
2399 res = "Unknown";
2400 else
2401 res = Table[RType];
2402 break;
2403 }
2404 case Triple::aarch64:
2405 case Triple::aarch64_32: {
2406 static const char *const Table[] = {
2407 "ARM64_RELOC_UNSIGNED", "ARM64_RELOC_SUBTRACTOR",
2408 "ARM64_RELOC_BRANCH26", "ARM64_RELOC_PAGE21",
2409 "ARM64_RELOC_PAGEOFF12", "ARM64_RELOC_GOT_LOAD_PAGE21",
2410 "ARM64_RELOC_GOT_LOAD_PAGEOFF12", "ARM64_RELOC_POINTER_TO_GOT",
2411 "ARM64_RELOC_TLVP_LOAD_PAGE21", "ARM64_RELOC_TLVP_LOAD_PAGEOFF12",
2412 "ARM64_RELOC_ADDEND", "ARM64_RELOC_AUTHENTICATED_POINTER"
2413 };
2414
2415 if (RType >= std::size(Table))
2416 res = "Unknown";
2417 else
2418 res = Table[RType];
2419 break;
2420 }
2421 case Triple::ppc: {
2422 static const char *const Table[] = {
2423 "PPC_RELOC_VANILLA",
2424 "PPC_RELOC_PAIR",
2425 "PPC_RELOC_BR14",
2426 "PPC_RELOC_BR24",
2427 "PPC_RELOC_HI16",
2428 "PPC_RELOC_LO16",
2429 "PPC_RELOC_HA16",
2430 "PPC_RELOC_LO14",
2431 "PPC_RELOC_SECTDIFF",
2432 "PPC_RELOC_PB_LA_PTR",
2433 "PPC_RELOC_HI16_SECTDIFF",
2434 "PPC_RELOC_LO16_SECTDIFF",
2435 "PPC_RELOC_HA16_SECTDIFF",
2436 "PPC_RELOC_JBSR",
2437 "PPC_RELOC_LO14_SECTDIFF",
2438 "PPC_RELOC_LOCAL_SECTDIFF" };
2439
2440 if (RType > 15)
2441 res = "Unknown";
2442 else
2443 res = Table[RType];
2444 break;
2445 }
2446 case Triple::riscv32: {
2447 static const char *const Table[] = {
2448 "RISCV_RELOC_UNSIGNED", "RISCV_RELOC_SUBTRACTOR",
2449 "RISCV_RELOC_BRANCH21", "RISCV_RELOC_HI20",
2450 "RISCV_RELOC_LO12", "RISCV_RELOC_GOT_HI20",
2451 "RISCV_RELOC_GOT_LO12", "RISCV_RELOC_POINTER_TO_GOT",
2452 "RISCV_RELOC_ADDEND",
2453 };
2454
2455 if (RType >= std::size(Table))
2456 res = "Unknown";
2457 else
2458 res = Table[RType];
2459 Result.append(in_start: res.begin(), in_end: res.end());
2460 if ((RType == MachO::RISCV_RELOC_HI20 ||
2461 RType == MachO::RISCV_RELOC_GOT_HI20 ||
2462 RType == MachO::RISCV_RELOC_LO12 ||
2463 RType == MachO::RISCV_RELOC_GOT_LO12) &&
2464 getAnyRelocationPCRel(RE: getRelocation(Rel))) {
2465 StringRef PCRel("(pcrel)");
2466 Result.append(in_start: PCRel.begin(), in_end: PCRel.end());
2467 }
2468 return;
2469 }
2470 case Triple::UnknownArch:
2471 res = "Unknown";
2472 break;
2473 }
2474 Result.append(in_start: res.begin(), in_end: res.end());
2475}
2476
2477uint8_t MachOObjectFile::getRelocationLength(DataRefImpl Rel) const {
2478 MachO::any_relocation_info RE = getRelocation(Rel);
2479 return getAnyRelocationLength(RE);
2480}
2481
2482//
2483// guessLibraryShortName() is passed a name of a dynamic library and returns a
2484// guess on what the short name is. Then name is returned as a substring of the
2485// StringRef Name passed in. The name of the dynamic library is recognized as
2486// a framework if it has one of the two following forms:
2487// Foo.framework/Versions/A/Foo
2488// Foo.framework/Foo
2489// Where A and Foo can be any string. And may contain a trailing suffix
2490// starting with an underbar. If the Name is recognized as a framework then
2491// isFramework is set to true else it is set to false. If the Name has a
2492// suffix then Suffix is set to the substring in Name that contains the suffix
2493// else it is set to a NULL StringRef.
2494//
2495// The Name of the dynamic library is recognized as a library name if it has
2496// one of the two following forms:
2497// libFoo.A.dylib
2498// libFoo.dylib
2499//
2500// The library may have a suffix trailing the name Foo of the form:
2501// libFoo_profile.A.dylib
2502// libFoo_profile.dylib
2503// These dyld image suffixes are separated from the short name by a '_'
2504// character. Because the '_' character is commonly used to separate words in
2505// filenames guessLibraryShortName() cannot reliably separate a dylib's short
2506// name from an arbitrary image suffix; imagine if both the short name and the
2507// suffix contains an '_' character! To better deal with this ambiguity,
2508// guessLibraryShortName() will recognize only "_debug" and "_profile" as valid
2509// Suffix values. Calling code needs to be tolerant of guessLibraryShortName()
2510// guessing incorrectly.
2511//
2512// The Name of the dynamic library is also recognized as a library name if it
2513// has the following form:
2514// Foo.qtx
2515//
2516// If the Name of the dynamic library is none of the forms above then a NULL
2517// StringRef is returned.
2518StringRef MachOObjectFile::guessLibraryShortName(StringRef Name,
2519 bool &isFramework,
2520 StringRef &Suffix) {
2521 StringRef Foo, F, DotFramework, V, Dylib, Lib, Dot, Qtx;
2522 size_t a, b, c, d, Idx;
2523
2524 isFramework = false;
2525 Suffix = StringRef();
2526
2527 // Pull off the last component and make Foo point to it
2528 a = Name.rfind(C: '/');
2529 if (a == Name.npos || a == 0)
2530 goto guess_library;
2531 Foo = Name.substr(Start: a + 1);
2532
2533 // Look for a suffix starting with a '_'
2534 Idx = Foo.rfind(C: '_');
2535 if (Idx != Foo.npos && Foo.size() >= 2) {
2536 Suffix = Foo.substr(Start: Idx);
2537 if (Suffix != "_debug" && Suffix != "_profile")
2538 Suffix = StringRef();
2539 else
2540 Foo = Foo.slice(Start: 0, End: Idx);
2541 }
2542
2543 // First look for the form Foo.framework/Foo
2544 b = Name.rfind(C: '/', From: a);
2545 if (b == Name.npos)
2546 Idx = 0;
2547 else
2548 Idx = b+1;
2549 F = Name.substr(Start: Idx, N: Foo.size());
2550 DotFramework = Name.substr(Start: Idx + Foo.size(), N: sizeof(".framework/") - 1);
2551 if (F == Foo && DotFramework == ".framework/") {
2552 isFramework = true;
2553 return Foo;
2554 }
2555
2556 // Next look for the form Foo.framework/Versions/A/Foo
2557 if (b == Name.npos)
2558 goto guess_library;
2559 c = Name.rfind(C: '/', From: b);
2560 if (c == Name.npos || c == 0)
2561 goto guess_library;
2562 V = Name.substr(Start: c + 1);
2563 if (!V.starts_with(Prefix: "Versions/"))
2564 goto guess_library;
2565 d = Name.rfind(C: '/', From: c);
2566 if (d == Name.npos)
2567 Idx = 0;
2568 else
2569 Idx = d+1;
2570 F = Name.substr(Start: Idx, N: Foo.size());
2571 DotFramework = Name.substr(Start: Idx + Foo.size(), N: sizeof(".framework/") - 1);
2572 if (F == Foo && DotFramework == ".framework/") {
2573 isFramework = true;
2574 return Foo;
2575 }
2576
2577guess_library:
2578 // pull off the suffix after the "." and make a point to it
2579 a = Name.rfind(C: '.');
2580 if (a == Name.npos || a == 0)
2581 return StringRef();
2582 Dylib = Name.substr(Start: a);
2583 if (Dylib != ".dylib")
2584 goto guess_qtx;
2585
2586 // First pull off the version letter for the form Foo.A.dylib if any.
2587 if (a >= 3) {
2588 Dot = Name.substr(Start: a - 2, N: 1);
2589 if (Dot == ".")
2590 a = a - 2;
2591 }
2592
2593 b = Name.rfind(C: '/', From: a);
2594 if (b == Name.npos)
2595 b = 0;
2596 else
2597 b = b+1;
2598 // ignore any suffix after an underbar like Foo_profile.A.dylib
2599 Idx = Name.rfind(C: '_');
2600 if (Idx != Name.npos && Idx != b) {
2601 Lib = Name.slice(Start: b, End: Idx);
2602 Suffix = Name.slice(Start: Idx, End: a);
2603 if (Suffix != "_debug" && Suffix != "_profile") {
2604 Suffix = StringRef();
2605 Lib = Name.slice(Start: b, End: a);
2606 }
2607 }
2608 else
2609 Lib = Name.slice(Start: b, End: a);
2610 // There are incorrect library names of the form:
2611 // libATS.A_profile.dylib so check for these.
2612 if (Lib.size() >= 3) {
2613 Dot = Lib.substr(Start: Lib.size() - 2, N: 1);
2614 if (Dot == ".")
2615 Lib = Lib.slice(Start: 0, End: Lib.size()-2);
2616 }
2617 return Lib;
2618
2619guess_qtx:
2620 Qtx = Name.substr(Start: a);
2621 if (Qtx != ".qtx")
2622 return StringRef();
2623 b = Name.rfind(C: '/', From: a);
2624 if (b == Name.npos)
2625 Lib = Name.slice(Start: 0, End: a);
2626 else
2627 Lib = Name.slice(Start: b+1, End: a);
2628 // There are library names of the form: QT.A.qtx so check for these.
2629 if (Lib.size() >= 3) {
2630 Dot = Lib.substr(Start: Lib.size() - 2, N: 1);
2631 if (Dot == ".")
2632 Lib = Lib.slice(Start: 0, End: Lib.size()-2);
2633 }
2634 return Lib;
2635}
2636
2637// getLibraryShortNameByIndex() is used to get the short name of the library
2638// for an undefined symbol in a linked Mach-O binary that was linked with the
2639// normal two-level namespace default (that is MH_TWOLEVEL in the header).
2640// It is passed the index (0 - based) of the library as translated from
2641// GET_LIBRARY_ORDINAL (1 - based).
2642std::error_code MachOObjectFile::getLibraryShortNameByIndex(unsigned Index,
2643 StringRef &Res) const {
2644 if (Index >= Libraries.size())
2645 return object_error::parse_failed;
2646
2647 // If the cache of LibrariesShortNames is not built up do that first for
2648 // all the Libraries.
2649 if (LibrariesShortNames.size() == 0) {
2650 for (unsigned i = 0; i < Libraries.size(); i++) {
2651 auto CommandOrErr =
2652 getStructOrErr<MachO::dylib_command>(O: *this, P: Libraries[i]);
2653 if (!CommandOrErr)
2654 return object_error::parse_failed;
2655 MachO::dylib_command D = CommandOrErr.get();
2656 if (D.dylib.name >= D.cmdsize)
2657 return object_error::parse_failed;
2658 const char *P = (const char *)(Libraries[i]) + D.dylib.name;
2659 StringRef Name = StringRef(P);
2660 if (D.dylib.name+Name.size() >= D.cmdsize)
2661 return object_error::parse_failed;
2662 StringRef Suffix;
2663 bool isFramework;
2664 StringRef shortName = guessLibraryShortName(Name, isFramework, Suffix);
2665 if (shortName.empty())
2666 LibrariesShortNames.push_back(Elt: Name);
2667 else
2668 LibrariesShortNames.push_back(Elt: shortName);
2669 }
2670 }
2671
2672 Res = LibrariesShortNames[Index];
2673 return std::error_code();
2674}
2675
2676uint32_t MachOObjectFile::getLibraryCount() const {
2677 return Libraries.size();
2678}
2679
2680section_iterator
2681MachOObjectFile::getRelocationRelocatedSection(relocation_iterator Rel) const {
2682 DataRefImpl Sec;
2683 Sec.d.a = Rel->getRawDataRefImpl().d.a;
2684 return section_iterator(SectionRef(Sec, this));
2685}
2686
2687basic_symbol_iterator MachOObjectFile::symbol_begin() const {
2688 DataRefImpl DRI;
2689 MachO::symtab_command Symtab = getSymtabLoadCommand();
2690 if (!SymtabLoadCmd || Symtab.nsyms == 0)
2691 return basic_symbol_iterator(SymbolRef(DRI, this));
2692
2693 return getSymbolByIndex(Index: 0);
2694}
2695
2696basic_symbol_iterator MachOObjectFile::symbol_end() const {
2697 DataRefImpl DRI;
2698 MachO::symtab_command Symtab = getSymtabLoadCommand();
2699 if (!SymtabLoadCmd || Symtab.nsyms == 0)
2700 return basic_symbol_iterator(SymbolRef(DRI, this));
2701
2702 uint64_t SymbolTableEntrySize =
2703 is64Bit() ? sizeof(MachO::nlist_64) : sizeof(MachO::nlist);
2704 uint64_t Offset = Symtab.symoff + Symtab.nsyms * SymbolTableEntrySize;
2705 DRI.p = reinterpret_cast<uintptr_t>(getPtr(O: *this, Offset));
2706 return basic_symbol_iterator(SymbolRef(DRI, this));
2707}
2708
2709symbol_iterator MachOObjectFile::getSymbolByIndex(unsigned Index) const {
2710 MachO::symtab_command Symtab = getSymtabLoadCommand();
2711 if (!SymtabLoadCmd || Index >= Symtab.nsyms)
2712 report_fatal_error(reason: "Requested symbol index is out of range.");
2713 uint64_t SymbolTableEntrySize =
2714 is64Bit() ? sizeof(MachO::nlist_64) : sizeof(MachO::nlist);
2715 DataRefImpl DRI;
2716 DRI.p = reinterpret_cast<uintptr_t>(getPtr(O: *this, Offset: Symtab.symoff));
2717 DRI.p += Index * SymbolTableEntrySize;
2718 return basic_symbol_iterator(SymbolRef(DRI, this));
2719}
2720
2721uint64_t MachOObjectFile::getSymbolIndex(DataRefImpl Symb) const {
2722 MachO::symtab_command Symtab = getSymtabLoadCommand();
2723 if (!SymtabLoadCmd)
2724 report_fatal_error(reason: "getSymbolIndex() called with no symbol table symbol");
2725 unsigned SymbolTableEntrySize =
2726 is64Bit() ? sizeof(MachO::nlist_64) : sizeof(MachO::nlist);
2727 DataRefImpl DRIstart;
2728 DRIstart.p = reinterpret_cast<uintptr_t>(getPtr(O: *this, Offset: Symtab.symoff));
2729 uint64_t Index = (Symb.p - DRIstart.p) / SymbolTableEntrySize;
2730 return Index;
2731}
2732
2733section_iterator MachOObjectFile::section_begin() const {
2734 DataRefImpl DRI;
2735 return section_iterator(SectionRef(DRI, this));
2736}
2737
2738section_iterator MachOObjectFile::section_end() const {
2739 DataRefImpl DRI;
2740 DRI.d.a = Sections.size();
2741 return section_iterator(SectionRef(DRI, this));
2742}
2743
2744uint8_t MachOObjectFile::getBytesInAddress() const {
2745 return is64Bit() ? 8 : 4;
2746}
2747
2748StringRef MachOObjectFile::getFileFormatName() const {
2749 unsigned CPUType = getCPUType(O: *this);
2750 if (!is64Bit()) {
2751 switch (CPUType) {
2752 case MachO::CPU_TYPE_I386:
2753 return "Mach-O 32-bit i386";
2754 case MachO::CPU_TYPE_ARM:
2755 return "Mach-O arm";
2756 case MachO::CPU_TYPE_ARM64_32:
2757 return "Mach-O arm64 (ILP32)";
2758 case MachO::CPU_TYPE_POWERPC:
2759 return "Mach-O 32-bit ppc";
2760 case MachO::CPU_TYPE_RISCV:
2761 return "Mach-O 32-bit RISC-V";
2762 default:
2763 return "Mach-O 32-bit unknown";
2764 }
2765 }
2766
2767 switch (CPUType) {
2768 case MachO::CPU_TYPE_X86_64:
2769 return "Mach-O 64-bit x86-64";
2770 case MachO::CPU_TYPE_ARM64:
2771 return "Mach-O arm64";
2772 case MachO::CPU_TYPE_POWERPC64:
2773 return "Mach-O 64-bit ppc64";
2774 default:
2775 return "Mach-O 64-bit unknown";
2776 }
2777}
2778
2779Triple::ArchType MachOObjectFile::getArch(uint32_t CPUType, uint32_t CPUSubType) {
2780 switch (CPUType) {
2781 case MachO::CPU_TYPE_I386:
2782 return Triple::x86;
2783 case MachO::CPU_TYPE_X86_64:
2784 return Triple::x86_64;
2785 case MachO::CPU_TYPE_ARM:
2786 return Triple::arm;
2787 case MachO::CPU_TYPE_ARM64:
2788 return Triple::aarch64;
2789 case MachO::CPU_TYPE_ARM64_32:
2790 return Triple::aarch64_32;
2791 case MachO::CPU_TYPE_POWERPC:
2792 return Triple::ppc;
2793 case MachO::CPU_TYPE_POWERPC64:
2794 return Triple::ppc64;
2795 case MachO::CPU_TYPE_RISCV:
2796 return Triple::riscv32;
2797 default:
2798 return Triple::UnknownArch;
2799 }
2800}
2801
2802Triple MachOObjectFile::getArchTriple(uint32_t CPUType, uint32_t CPUSubType,
2803 const char **McpuDefault,
2804 const char **ArchFlag) {
2805 if (McpuDefault)
2806 *McpuDefault = nullptr;
2807 if (ArchFlag)
2808 *ArchFlag = nullptr;
2809
2810 switch (CPUType) {
2811 case MachO::CPU_TYPE_I386:
2812 switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2813 case MachO::CPU_SUBTYPE_I386_ALL:
2814 if (ArchFlag)
2815 *ArchFlag = "i386";
2816 return Triple("i386-apple-darwin");
2817 default:
2818 return Triple();
2819 }
2820 case MachO::CPU_TYPE_X86_64:
2821 switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2822 case MachO::CPU_SUBTYPE_X86_64_ALL:
2823 if (ArchFlag)
2824 *ArchFlag = "x86_64";
2825 return Triple("x86_64-apple-darwin");
2826 case MachO::CPU_SUBTYPE_X86_64_H:
2827 if (ArchFlag)
2828 *ArchFlag = "x86_64h";
2829 return Triple("x86_64h-apple-darwin");
2830 default:
2831 return Triple();
2832 }
2833 case MachO::CPU_TYPE_ARM:
2834 switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2835 case MachO::CPU_SUBTYPE_ARM_V4T:
2836 if (ArchFlag)
2837 *ArchFlag = "armv4t";
2838 return Triple("armv4t-apple-darwin");
2839 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
2840 if (ArchFlag)
2841 *ArchFlag = "armv5e";
2842 return Triple("armv5e-apple-darwin");
2843 case MachO::CPU_SUBTYPE_ARM_XSCALE:
2844 if (ArchFlag)
2845 *ArchFlag = "xscale";
2846 return Triple("xscale-apple-darwin");
2847 case MachO::CPU_SUBTYPE_ARM_V6:
2848 if (ArchFlag)
2849 *ArchFlag = "armv6";
2850 return Triple("armv6-apple-darwin");
2851 case MachO::CPU_SUBTYPE_ARM_V6M:
2852 if (McpuDefault)
2853 *McpuDefault = "cortex-m0";
2854 if (ArchFlag)
2855 *ArchFlag = "armv6m";
2856 return Triple("armv6m-apple-darwin");
2857 case MachO::CPU_SUBTYPE_ARM_V7:
2858 if (ArchFlag)
2859 *ArchFlag = "armv7";
2860 return Triple("armv7-apple-darwin");
2861 case MachO::CPU_SUBTYPE_ARM_V7EM:
2862 if (McpuDefault)
2863 *McpuDefault = "cortex-m4";
2864 if (ArchFlag)
2865 *ArchFlag = "armv7em";
2866 return Triple("thumbv7em-apple-darwin");
2867 case MachO::CPU_SUBTYPE_ARM_V7K:
2868 if (McpuDefault)
2869 *McpuDefault = "cortex-a7";
2870 if (ArchFlag)
2871 *ArchFlag = "armv7k";
2872 return Triple("armv7k-apple-darwin");
2873 case MachO::CPU_SUBTYPE_ARM_V7M:
2874 if (McpuDefault)
2875 *McpuDefault = "cortex-m3";
2876 if (ArchFlag)
2877 *ArchFlag = "armv7m";
2878 return Triple("thumbv7m-apple-darwin");
2879 case MachO::CPU_SUBTYPE_ARM_V7S:
2880 if (McpuDefault)
2881 *McpuDefault = "cortex-a7";
2882 if (ArchFlag)
2883 *ArchFlag = "armv7s";
2884 return Triple("armv7s-apple-darwin");
2885 case MachO::CPU_SUBTYPE_ARM_V8M_BASE:
2886 if (McpuDefault)
2887 *McpuDefault = "cortex-m23";
2888 if (ArchFlag)
2889 *ArchFlag = "armv8m.base";
2890 return Triple("thumbv8m-apple-darwin");
2891 case MachO::CPU_SUBTYPE_ARM_V8M_MAIN:
2892 if (McpuDefault)
2893 *McpuDefault = "cortex-m33";
2894 if (ArchFlag)
2895 *ArchFlag = "armv8m.main";
2896 return Triple("thumbv8m-apple-darwin");
2897 case MachO::CPU_SUBTYPE_ARM_V8_1M_MAIN:
2898 if (McpuDefault)
2899 *McpuDefault = "cortex-m52";
2900 if (ArchFlag)
2901 *ArchFlag = "armv8.1m.main";
2902 return Triple("thumbv8m-apple-darwin");
2903 default:
2904 return Triple();
2905 }
2906 case MachO::CPU_TYPE_ARM64:
2907 switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2908 case MachO::CPU_SUBTYPE_ARM64_ALL:
2909 if (McpuDefault)
2910 *McpuDefault = "cyclone";
2911 if (ArchFlag)
2912 *ArchFlag = "arm64";
2913 return Triple("arm64-apple-darwin");
2914 case MachO::CPU_SUBTYPE_ARM64E:
2915 if (McpuDefault)
2916 *McpuDefault = "apple-a12";
2917 if (ArchFlag)
2918 *ArchFlag = "arm64e";
2919 return Triple("arm64e-apple-darwin");
2920 case MachO::CPU_SUBTYPE_ARM64E_X1:
2921 if (McpuDefault)
2922 *McpuDefault = "apple-m6";
2923 if (ArchFlag)
2924 *ArchFlag = "arm64e.x1";
2925 return Triple("arm64e.x1-apple-darwin");
2926 default:
2927 return Triple();
2928 }
2929 case MachO::CPU_TYPE_ARM64_32:
2930 switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2931 case MachO::CPU_SUBTYPE_ARM64_32_V8:
2932 if (McpuDefault)
2933 *McpuDefault = "cyclone";
2934 if (ArchFlag)
2935 *ArchFlag = "arm64_32";
2936 return Triple("arm64_32-apple-darwin");
2937 default:
2938 return Triple();
2939 }
2940 case MachO::CPU_TYPE_POWERPC:
2941 switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2942 case MachO::CPU_SUBTYPE_POWERPC_ALL:
2943 if (ArchFlag)
2944 *ArchFlag = "ppc";
2945 return Triple("ppc-apple-darwin");
2946 default:
2947 return Triple();
2948 }
2949 case MachO::CPU_TYPE_POWERPC64:
2950 switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2951 case MachO::CPU_SUBTYPE_POWERPC_ALL:
2952 if (ArchFlag)
2953 *ArchFlag = "ppc64";
2954 return Triple("ppc64-apple-darwin");
2955 default:
2956 return Triple();
2957 }
2958 case MachO::CPU_TYPE_RISCV:
2959 switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2960 case MachO::CPU_SUBTYPE_RISCV_ALL:
2961 if (ArchFlag)
2962 *ArchFlag = "riscv32";
2963 return Triple("riscv32-apple-macho");
2964 default:
2965 return Triple();
2966 }
2967 default:
2968 return Triple();
2969 }
2970}
2971
2972Triple MachOObjectFile::getHostArch() {
2973 return Triple(sys::getDefaultTargetTriple());
2974}
2975
2976bool MachOObjectFile::isValidArch(StringRef ArchFlag) {
2977 auto validArchs = getValidArchs();
2978 return llvm::is_contained(Range&: validArchs, Element: ArchFlag);
2979}
2980
2981ArrayRef<StringRef> MachOObjectFile::getValidArchs() {
2982 static const std::array<StringRef, 22> ValidArchs = {._M_elems: {
2983 "i386", "x86_64", "x86_64h", "armv4t", "arm",
2984 "armv5e", "armv6", "armv6m", "armv7", "armv7em",
2985 "armv7k", "armv7m", "armv7s", "armv8m.base", "armv8m.main",
2986 "armv8.1m.main", "arm64", "arm64e", "arm64e.x1", "arm64_32",
2987 "ppc", "ppc64",
2988 }};
2989
2990 return ValidArchs;
2991}
2992
2993Triple::ArchType MachOObjectFile::getArch() const {
2994 return getArch(CPUType: getCPUType(O: *this), CPUSubType: getCPUSubType(O: *this));
2995}
2996
2997Triple MachOObjectFile::getArchTriple(const char **McpuDefault) const {
2998 return getArchTriple(CPUType: Header.cputype, CPUSubType: Header.cpusubtype, McpuDefault);
2999}
3000
3001relocation_iterator MachOObjectFile::section_rel_begin(unsigned Index) const {
3002 DataRefImpl DRI;
3003 DRI.d.a = Index;
3004 return section_rel_begin(Sec: DRI);
3005}
3006
3007relocation_iterator MachOObjectFile::section_rel_end(unsigned Index) const {
3008 DataRefImpl DRI;
3009 DRI.d.a = Index;
3010 return section_rel_end(Sec: DRI);
3011}
3012
3013dice_iterator MachOObjectFile::begin_dices() const {
3014 DataRefImpl DRI;
3015 if (!DataInCodeLoadCmd)
3016 return dice_iterator(DiceRef(DRI, this));
3017
3018 MachO::linkedit_data_command DicLC = getDataInCodeLoadCommand();
3019 DRI.p = reinterpret_cast<uintptr_t>(getPtr(O: *this, Offset: DicLC.dataoff));
3020 return dice_iterator(DiceRef(DRI, this));
3021}
3022
3023dice_iterator MachOObjectFile::end_dices() const {
3024 DataRefImpl DRI;
3025 if (!DataInCodeLoadCmd)
3026 return dice_iterator(DiceRef(DRI, this));
3027
3028 MachO::linkedit_data_command DicLC = getDataInCodeLoadCommand();
3029 unsigned Offset = DicLC.dataoff + DicLC.datasize;
3030 DRI.p = reinterpret_cast<uintptr_t>(getPtr(O: *this, Offset));
3031 return dice_iterator(DiceRef(DRI, this));
3032}
3033
3034ExportEntry::ExportEntry(Error *E, const MachOObjectFile *O,
3035 ArrayRef<uint8_t> T) : E(E), O(O), Trie(T) {}
3036
3037void ExportEntry::moveToFirst() {
3038 ErrorAsOutParameter ErrAsOutParam(E);
3039 pushNode(Offset: 0);
3040 if (*E)
3041 return;
3042 pushDownUntilBottom();
3043}
3044
3045void ExportEntry::moveToEnd() {
3046 Stack.clear();
3047 Done = true;
3048}
3049
3050bool ExportEntry::operator==(const ExportEntry &Other) const {
3051 // Common case, one at end, other iterating from begin.
3052 if (Done || Other.Done)
3053 return (Done == Other.Done);
3054 // Not equal if different stack sizes.
3055 if (Stack.size() != Other.Stack.size())
3056 return false;
3057 // Not equal if different cumulative strings.
3058 if (!CumulativeString.equals(RHS: Other.CumulativeString))
3059 return false;
3060 // Equal if all nodes in both stacks match.
3061 for (unsigned i=0; i < Stack.size(); ++i) {
3062 if (Stack[i].Start != Other.Stack[i].Start)
3063 return false;
3064 }
3065 return true;
3066}
3067
3068uint64_t ExportEntry::readULEB128(const uint8_t *&Ptr, const char **error) {
3069 unsigned Count;
3070 uint64_t Result = decodeULEB128(p: Ptr, n: &Count, end: Trie.end(), error);
3071 Ptr += Count;
3072 if (Ptr > Trie.end())
3073 Ptr = Trie.end();
3074 return Result;
3075}
3076
3077StringRef ExportEntry::name() const {
3078 return CumulativeString;
3079}
3080
3081uint64_t ExportEntry::flags() const {
3082 return Stack.back().Flags;
3083}
3084
3085uint64_t ExportEntry::address() const {
3086 return Stack.back().Address;
3087}
3088
3089uint64_t ExportEntry::other() const {
3090 return Stack.back().Other;
3091}
3092
3093StringRef ExportEntry::otherName() const {
3094 const char* ImportName = Stack.back().ImportName;
3095 if (ImportName)
3096 return StringRef(ImportName);
3097 return StringRef();
3098}
3099
3100uint32_t ExportEntry::nodeOffset() const {
3101 return Stack.back().Start - Trie.begin();
3102}
3103
3104ExportEntry::NodeState::NodeState(const uint8_t *Ptr)
3105 : Start(Ptr), Current(Ptr) {}
3106
3107void ExportEntry::pushNode(uint64_t offset) {
3108 ErrorAsOutParameter ErrAsOutParam(E);
3109 const uint8_t *Ptr = Trie.begin() + offset;
3110 NodeState State(Ptr);
3111 const char *error = nullptr;
3112 uint64_t ExportInfoSize = readULEB128(Ptr&: State.Current, error: &error);
3113 if (error) {
3114 *E = malformedError(Msg: "export info size " + Twine(error) +
3115 " in export trie data at node: 0x" +
3116 Twine::utohexstr(Val: offset));
3117 moveToEnd();
3118 return;
3119 }
3120 State.IsExportNode = (ExportInfoSize != 0);
3121 const uint8_t* Children = State.Current + ExportInfoSize;
3122 if (Children > Trie.end()) {
3123 *E = malformedError(
3124 Msg: "export info size: 0x" + Twine::utohexstr(Val: ExportInfoSize) +
3125 " in export trie data at node: 0x" + Twine::utohexstr(Val: offset) +
3126 " too big and extends past end of trie data");
3127 moveToEnd();
3128 return;
3129 }
3130 if (State.IsExportNode) {
3131 const uint8_t *ExportStart = State.Current;
3132 State.Flags = readULEB128(Ptr&: State.Current, error: &error);
3133 if (error) {
3134 *E = malformedError(Msg: "flags " + Twine(error) +
3135 " in export trie data at node: 0x" +
3136 Twine::utohexstr(Val: offset));
3137 moveToEnd();
3138 return;
3139 }
3140 uint64_t Kind = State.Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK;
3141 if (State.Flags != 0 &&
3142 (Kind != MachO::EXPORT_SYMBOL_FLAGS_KIND_REGULAR &&
3143 Kind != MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE &&
3144 Kind != MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL)) {
3145 *E = malformedError(
3146 Msg: "unsupported exported symbol kind: " + Twine((int)Kind) +
3147 " in flags: 0x" + Twine::utohexstr(Val: State.Flags) +
3148 " in export trie data at node: 0x" + Twine::utohexstr(Val: offset));
3149 moveToEnd();
3150 return;
3151 }
3152 if (State.Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT) {
3153 State.Address = 0;
3154 State.Other = readULEB128(Ptr&: State.Current, error: &error); // dylib ordinal
3155 if (error) {
3156 *E = malformedError(Msg: "dylib ordinal of re-export " + Twine(error) +
3157 " in export trie data at node: 0x" +
3158 Twine::utohexstr(Val: offset));
3159 moveToEnd();
3160 return;
3161 }
3162 if (O != nullptr) {
3163 // Only positive numbers represent library ordinals. Zero and negative
3164 // numbers have special meaning (see BindSpecialDylib).
3165 if ((int64_t)State.Other > 0 && State.Other > O->getLibraryCount()) {
3166 *E = malformedError(
3167 Msg: "bad library ordinal: " + Twine((int)State.Other) + " (max " +
3168 Twine((int)O->getLibraryCount()) +
3169 ") in export trie data at node: 0x" + Twine::utohexstr(Val: offset));
3170 moveToEnd();
3171 return;
3172 }
3173 }
3174 State.ImportName = reinterpret_cast<const char*>(State.Current);
3175 if (*State.ImportName == '\0') {
3176 State.Current++;
3177 } else {
3178 const uint8_t *End = State.Current + 1;
3179 if (End >= Trie.end()) {
3180 *E = malformedError(Msg: "import name of re-export in export trie data at "
3181 "node: 0x" +
3182 Twine::utohexstr(Val: offset) +
3183 " starts past end of trie data");
3184 moveToEnd();
3185 return;
3186 }
3187 while(*End != '\0' && End < Trie.end())
3188 End++;
3189 if (*End != '\0') {
3190 *E = malformedError(Msg: "import name of re-export in export trie data at "
3191 "node: 0x" +
3192 Twine::utohexstr(Val: offset) +
3193 " extends past end of trie data");
3194 moveToEnd();
3195 return;
3196 }
3197 State.Current = End + 1;
3198 }
3199 } else {
3200 State.Address = readULEB128(Ptr&: State.Current, error: &error);
3201 if (error) {
3202 *E = malformedError(Msg: "address " + Twine(error) +
3203 " in export trie data at node: 0x" +
3204 Twine::utohexstr(Val: offset));
3205 moveToEnd();
3206 return;
3207 }
3208 if (State.Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER) {
3209 State.Other = readULEB128(Ptr&: State.Current, error: &error);
3210 if (error) {
3211 *E = malformedError(Msg: "resolver of stub and resolver " + Twine(error) +
3212 " in export trie data at node: 0x" +
3213 Twine::utohexstr(Val: offset));
3214 moveToEnd();
3215 return;
3216 }
3217 }
3218 }
3219 if (ExportStart + ExportInfoSize < State.Current) {
3220 *E = malformedError(
3221 Msg: "inconsistent export info size: 0x" +
3222 Twine::utohexstr(Val: ExportInfoSize) + " where actual size was: 0x" +
3223 Twine::utohexstr(Val: State.Current - ExportStart) +
3224 " in export trie data at node: 0x" + Twine::utohexstr(Val: offset));
3225 moveToEnd();
3226 return;
3227 }
3228 }
3229 State.ChildCount = *Children;
3230 if (State.ChildCount != 0 && Children + 1 >= Trie.end()) {
3231 *E = malformedError(Msg: "byte for count of children in export trie data at "
3232 "node: 0x" +
3233 Twine::utohexstr(Val: offset) +
3234 " extends past end of trie data");
3235 moveToEnd();
3236 return;
3237 }
3238 State.Current = Children + 1;
3239 State.NextChildIndex = 0;
3240 State.ParentStringLength = CumulativeString.size();
3241 Stack.push_back(Elt: State);
3242}
3243
3244void ExportEntry::pushDownUntilBottom() {
3245 ErrorAsOutParameter ErrAsOutParam(E);
3246 const char *error = nullptr;
3247 while (Stack.back().NextChildIndex < Stack.back().ChildCount) {
3248 NodeState &Top = Stack.back();
3249 CumulativeString.resize(N: Top.ParentStringLength);
3250 for (;*Top.Current != 0 && Top.Current < Trie.end(); Top.Current++) {
3251 char C = *Top.Current;
3252 CumulativeString.push_back(Elt: C);
3253 }
3254 if (Top.Current >= Trie.end()) {
3255 *E = malformedError(Msg: "edge sub-string in export trie data at node: 0x" +
3256 Twine::utohexstr(Val: Top.Start - Trie.begin()) +
3257 " for child #" + Twine((int)Top.NextChildIndex) +
3258 " extends past end of trie data");
3259 moveToEnd();
3260 return;
3261 }
3262 Top.Current += 1;
3263 uint64_t childNodeIndex = readULEB128(Ptr&: Top.Current, error: &error);
3264 if (error) {
3265 *E = malformedError(Msg: "child node offset " + Twine(error) +
3266 " in export trie data at node: 0x" +
3267 Twine::utohexstr(Val: Top.Start - Trie.begin()));
3268 moveToEnd();
3269 return;
3270 }
3271 for (const NodeState &node : nodes()) {
3272 if (node.Start == Trie.begin() + childNodeIndex){
3273 *E = malformedError(Msg: "loop in children in export trie data at node: 0x" +
3274 Twine::utohexstr(Val: Top.Start - Trie.begin()) +
3275 " back to node: 0x" +
3276 Twine::utohexstr(Val: childNodeIndex));
3277 moveToEnd();
3278 return;
3279 }
3280 }
3281 Top.NextChildIndex += 1;
3282 pushNode(offset: childNodeIndex);
3283 if (*E)
3284 return;
3285 }
3286 if (!Stack.back().IsExportNode) {
3287 *E = malformedError(Msg: "node is not an export node in export trie data at "
3288 "node: 0x" +
3289 Twine::utohexstr(Val: Stack.back().Start - Trie.begin()));
3290 moveToEnd();
3291 return;
3292 }
3293}
3294
3295// We have a trie data structure and need a way to walk it that is compatible
3296// with the C++ iterator model. The solution is a non-recursive depth first
3297// traversal where the iterator contains a stack of parent nodes along with a
3298// string that is the accumulation of all edge strings along the parent chain
3299// to this point.
3300//
3301// There is one "export" node for each exported symbol. But because some
3302// symbols may be a prefix of another symbol (e.g. _dup and _dup2), an export
3303// node may have child nodes too.
3304//
3305// The algorithm for moveNext() is to keep moving down the leftmost unvisited
3306// child until hitting a node with no children (which is an export node or
3307// else the trie is malformed). On the way down, each node is pushed on the
3308// stack ivar. If there is no more ways down, it pops up one and tries to go
3309// down a sibling path until a childless node is reached.
3310void ExportEntry::moveNext() {
3311 assert(!Stack.empty() && "ExportEntry::moveNext() with empty node stack");
3312 if (!Stack.back().IsExportNode) {
3313 *E = malformedError(Msg: "node is not an export node in export trie data at "
3314 "node: 0x" +
3315 Twine::utohexstr(Val: Stack.back().Start - Trie.begin()));
3316 moveToEnd();
3317 return;
3318 }
3319
3320 Stack.pop_back();
3321 while (!Stack.empty()) {
3322 NodeState &Top = Stack.back();
3323 if (Top.NextChildIndex < Top.ChildCount) {
3324 pushDownUntilBottom();
3325 // Now at the next export node.
3326 return;
3327 } else {
3328 if (Top.IsExportNode) {
3329 // This node has no children but is itself an export node.
3330 CumulativeString.resize(N: Top.ParentStringLength);
3331 return;
3332 }
3333 Stack.pop_back();
3334 }
3335 }
3336 Done = true;
3337}
3338
3339iterator_range<export_iterator>
3340MachOObjectFile::exports(Error &E, ArrayRef<uint8_t> Trie,
3341 const MachOObjectFile *O) {
3342 ExportEntry Start(&E, O, Trie);
3343 if (Trie.empty())
3344 Start.moveToEnd();
3345 else
3346 Start.moveToFirst();
3347
3348 ExportEntry Finish(&E, O, Trie);
3349 Finish.moveToEnd();
3350
3351 return make_range(x: export_iterator(Start), y: export_iterator(Finish));
3352}
3353
3354iterator_range<export_iterator> MachOObjectFile::exports(Error &Err) const {
3355 ArrayRef<uint8_t> Trie;
3356 if (DyldInfoLoadCmd)
3357 Trie = getDyldInfoExportsTrie();
3358 else if (DyldExportsTrieLoadCmd)
3359 Trie = getDyldExportsTrie();
3360
3361 return exports(E&: Err, Trie, O: this);
3362}
3363
3364MachOAbstractFixupEntry::MachOAbstractFixupEntry(Error *E,
3365 const MachOObjectFile *O)
3366 : E(E), O(O) {
3367 // Cache the vmaddress of __TEXT
3368 for (const auto &Command : O->load_commands()) {
3369 if (Command.C.cmd == MachO::LC_SEGMENT) {
3370 MachO::segment_command SLC = O->getSegmentLoadCommand(L: Command);
3371 if (StringRef(SLC.segname) == "__TEXT") {
3372 TextAddress = SLC.vmaddr;
3373 break;
3374 }
3375 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
3376 MachO::segment_command_64 SLC_64 = O->getSegment64LoadCommand(L: Command);
3377 if (StringRef(SLC_64.segname) == "__TEXT") {
3378 TextAddress = SLC_64.vmaddr;
3379 break;
3380 }
3381 }
3382 }
3383}
3384
3385int32_t MachOAbstractFixupEntry::segmentIndex() const { return SegmentIndex; }
3386
3387uint64_t MachOAbstractFixupEntry::segmentOffset() const {
3388 return SegmentOffset;
3389}
3390
3391uint64_t MachOAbstractFixupEntry::segmentAddress() const {
3392 return O->BindRebaseAddress(SegIndex: SegmentIndex, SegOffset: 0);
3393}
3394
3395StringRef MachOAbstractFixupEntry::segmentName() const {
3396 return O->BindRebaseSegmentName(SegIndex: SegmentIndex);
3397}
3398
3399StringRef MachOAbstractFixupEntry::sectionName() const {
3400 return O->BindRebaseSectionName(SegIndex: SegmentIndex, SegOffset: SegmentOffset);
3401}
3402
3403uint64_t MachOAbstractFixupEntry::address() const {
3404 return O->BindRebaseAddress(SegIndex: SegmentIndex, SegOffset: SegmentOffset);
3405}
3406
3407StringRef MachOAbstractFixupEntry::symbolName() const { return SymbolName; }
3408
3409int64_t MachOAbstractFixupEntry::addend() const { return Addend; }
3410
3411uint32_t MachOAbstractFixupEntry::flags() const { return Flags; }
3412
3413int MachOAbstractFixupEntry::ordinal() const { return Ordinal; }
3414
3415StringRef MachOAbstractFixupEntry::typeName() const { return "unknown"; }
3416
3417void MachOAbstractFixupEntry::moveToFirst() {
3418 SegmentOffset = 0;
3419 SegmentIndex = -1;
3420 Ordinal = 0;
3421 Flags = 0;
3422 Addend = 0;
3423 Done = false;
3424}
3425
3426void MachOAbstractFixupEntry::moveToEnd() { Done = true; }
3427
3428void MachOAbstractFixupEntry::moveNext() {}
3429
3430MachOChainedFixupEntry::MachOChainedFixupEntry(Error *E,
3431 const MachOObjectFile *O,
3432 bool Parse)
3433 : MachOAbstractFixupEntry(E, O) {
3434 ErrorAsOutParameter e(E);
3435 if (!Parse)
3436 return;
3437
3438 if (auto FixupTargetsOrErr = O->getDyldChainedFixupTargets()) {
3439 FixupTargets = *FixupTargetsOrErr;
3440 } else {
3441 *E = FixupTargetsOrErr.takeError();
3442 return;
3443 }
3444
3445 if (auto SegmentsOrErr = O->getChainedFixupsSegments()) {
3446 Segments = std::move(SegmentsOrErr->second);
3447 } else {
3448 *E = SegmentsOrErr.takeError();
3449 return;
3450 }
3451}
3452
3453void MachOChainedFixupEntry::findNextPageWithFixups() {
3454 auto FindInSegment = [this]() {
3455 const ChainedFixupsSegment &SegInfo = Segments[InfoSegIndex];
3456 while (PageIndex < SegInfo.PageStarts.size() &&
3457 SegInfo.PageStarts[PageIndex] == MachO::DYLD_CHAINED_PTR_START_NONE)
3458 ++PageIndex;
3459 return PageIndex < SegInfo.PageStarts.size();
3460 };
3461
3462 while (InfoSegIndex < Segments.size()) {
3463 if (FindInSegment()) {
3464 PageOffset = Segments[InfoSegIndex].PageStarts[PageIndex];
3465 SegmentData = O->getSegmentContents(SegmentIndex: Segments[InfoSegIndex].SegIdx);
3466 return;
3467 }
3468
3469 InfoSegIndex++;
3470 PageIndex = 0;
3471 }
3472}
3473
3474void MachOChainedFixupEntry::moveToFirst() {
3475 MachOAbstractFixupEntry::moveToFirst();
3476 if (Segments.empty()) {
3477 Done = true;
3478 return;
3479 }
3480
3481 InfoSegIndex = 0;
3482 PageIndex = 0;
3483
3484 findNextPageWithFixups();
3485 moveNext();
3486}
3487
3488void MachOChainedFixupEntry::moveToEnd() {
3489 MachOAbstractFixupEntry::moveToEnd();
3490}
3491
3492void MachOChainedFixupEntry::moveNext() {
3493 ErrorAsOutParameter ErrAsOutParam(E);
3494
3495 if (InfoSegIndex == Segments.size()) {
3496 Done = true;
3497 return;
3498 }
3499
3500 const ChainedFixupsSegment &SegInfo = Segments[InfoSegIndex];
3501 SegmentIndex = SegInfo.SegIdx;
3502 SegmentOffset = SegInfo.Header.page_size * PageIndex + PageOffset;
3503
3504 // FIXME: Handle the 32-bit, kernel and firmware pointer formats, and
3505 // DYLD_CHAINED_PTR_ARM64E_USERLAND.
3506 PointerFormat = SegInfo.Header.pointer_format;
3507 bool IsArm64e = PointerFormat == MachO::DYLD_CHAINED_PTR_ARM64E ||
3508 PointerFormat == MachO::DYLD_CHAINED_PTR_ARM64E_USERLAND24;
3509 if (PointerFormat != MachO::DYLD_CHAINED_PTR_64 &&
3510 PointerFormat != MachO::DYLD_CHAINED_PTR_64_OFFSET && !IsArm64e) {
3511 *E = createError(Err: "segment " + Twine(SegmentIndex) +
3512 " has unsupported chained fixup pointer_format " +
3513 Twine(PointerFormat));
3514 moveToEnd();
3515 return;
3516 }
3517
3518 Ordinal = 0;
3519 Flags = 0;
3520 Addend = 0;
3521 PointerValue = 0;
3522 SymbolName = {};
3523 IsAuthenticated = false;
3524 HasAddressDiversity = false;
3525 Key = 0;
3526 Diversity = 0;
3527
3528 if (SegmentOffset + sizeof(RawValue) > SegmentData.size()) {
3529 *E = malformedError(Msg: "fixup in segment " + Twine(SegmentIndex) +
3530 " at offset " + Twine(SegmentOffset) +
3531 " extends past segment's end");
3532 moveToEnd();
3533 return;
3534 }
3535
3536 static_assert(sizeof(RawValue) == sizeof(MachO::dyld_chained_import_addend));
3537 memcpy(dest: &RawValue, src: SegmentData.data() + SegmentOffset, n: sizeof(RawValue));
3538 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3539 sys::swapByteOrder(Value&: RawValue);
3540
3541 // The bit extraction below assumes little-endian fixup entries.
3542 assert(O->isLittleEndian() && "big-endian object should have been rejected "
3543 "by getDyldChainedFixupTargets()");
3544 auto Field = [this](uint8_t Right, uint8_t Count) {
3545 return (RawValue >> Right) & ((1ULL << Count) - 1);
3546 };
3547
3548 bool IsBind;
3549 uint32_t Next;
3550 uint32_t ImportOrdinal = 0;
3551 int64_t InlineAddend = 0;
3552 if (IsArm64e) {
3553 // The `auth` and `bind` fields (the two most significant bits) of the
3554 // encoded fixup determine which dyld_chained_ptr_arm64e_* struct it is.
3555 IsAuthenticated = Field(63, 1);
3556 IsBind = Field(62, 1);
3557 Next = Field(51, 11);
3558 if (IsAuthenticated) {
3559 Diversity = Field(32, 16);
3560 HasAddressDiversity = Field(48, 1);
3561 Key = Field(49, 2);
3562 }
3563 if (IsBind) {
3564 ImportOrdinal = Field(
3565 0,
3566 PointerFormat == MachO::DYLD_CHAINED_PTR_ARM64E_USERLAND24 ? 24 : 16);
3567 // Authenticated binds have no room for an addend.
3568 if (!IsAuthenticated)
3569 InlineAddend = SignExtend64<19>(x: Field(32, 19));
3570 } else if (IsAuthenticated) {
3571 // The target of an authenticated rebase is an offset from the image.
3572 PointerValue = Field(0, 32) + textAddress();
3573 } else {
3574 // DYLD_CHAINED_PTR_ARM64E rebases hold an address, and
3575 // DYLD_CHAINED_PTR_ARM64E_USERLAND24 rebases an offset from the image.
3576 uint64_t Target = Field(0, 43);
3577 if (PointerFormat == MachO::DYLD_CHAINED_PTR_ARM64E_USERLAND24)
3578 Target += textAddress();
3579 PointerValue = Target | (Field(43, 8) << 56);
3580 }
3581 } else {
3582 // The `bind` field (most significant bit) of the encoded fixup determines
3583 // whether it is dyld_chained_ptr_64_bind or dyld_chained_ptr_64_rebase.
3584 IsBind = Field(63, 1);
3585 Next = Field(51, 12);
3586 if (IsBind) {
3587 ImportOrdinal = Field(0, 24);
3588 InlineAddend = Field(24, 8);
3589 } else {
3590 uint64_t Target = Field(0, 36);
3591 uint64_t High8 = Field(36, 8);
3592
3593 PointerValue = Target | (High8 << 56);
3594 if (PointerFormat == MachO::DYLD_CHAINED_PTR_64_OFFSET)
3595 PointerValue += textAddress();
3596 }
3597 }
3598
3599 Kind = IsBind ? FixupKind::Bind : FixupKind::Rebase;
3600 if (IsBind) {
3601 if (ImportOrdinal >= FixupTargets.size()) {
3602 *E = malformedError(Msg: "fixup in segment " + Twine(SegmentIndex) +
3603 " at offset " + Twine(SegmentOffset) +
3604 " has out-of range import ordinal " +
3605 Twine(ImportOrdinal));
3606 moveToEnd();
3607 return;
3608 }
3609
3610 ChainedFixupTarget &Target = FixupTargets[ImportOrdinal];
3611 Ordinal = Target.libOrdinal();
3612 Addend = InlineAddend ? InlineAddend : Target.addend();
3613 Flags = Target.weakImport() ? MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT : 0;
3614 SymbolName = Target.symbolName();
3615 }
3616
3617 // The stride is 8 bytes for the arm64e formats and 4 bytes for
3618 // DYLD_CHAINED_PTR_64(_OFFSET).
3619 if (Next != 0) {
3620 PageOffset += (IsArm64e ? 8 : 4) * Next;
3621 } else {
3622 ++PageIndex;
3623 findNextPageWithFixups();
3624 }
3625}
3626
3627bool MachOChainedFixupEntry::operator==(
3628 const MachOChainedFixupEntry &Other) const {
3629 if (Done && Other.Done)
3630 return true;
3631 if (Done != Other.Done)
3632 return false;
3633 return InfoSegIndex == Other.InfoSegIndex && PageIndex == Other.PageIndex &&
3634 PageOffset == Other.PageOffset;
3635}
3636
3637MachORebaseEntry::MachORebaseEntry(Error *E, const MachOObjectFile *O,
3638 ArrayRef<uint8_t> Bytes, bool is64Bit)
3639 : E(E), O(O), Opcodes(Bytes), Ptr(Bytes.begin()),
3640 PointerSize(is64Bit ? 8 : 4) {}
3641
3642void MachORebaseEntry::moveToFirst() {
3643 Ptr = Opcodes.begin();
3644 moveNext();
3645}
3646
3647void MachORebaseEntry::moveToEnd() {
3648 Ptr = Opcodes.end();
3649 RemainingLoopCount = 0;
3650 Done = true;
3651}
3652
3653void MachORebaseEntry::moveNext() {
3654 ErrorAsOutParameter ErrAsOutParam(E);
3655 // If in the middle of some loop, move to next rebasing in loop.
3656 SegmentOffset += AdvanceAmount;
3657 if (RemainingLoopCount) {
3658 --RemainingLoopCount;
3659 return;
3660 }
3661
3662 bool More = true;
3663 while (More) {
3664 // REBASE_OPCODE_DONE is only used for padding if we are not aligned to
3665 // pointer size. Therefore it is possible to reach the end without ever
3666 // having seen REBASE_OPCODE_DONE.
3667 if (Ptr == Opcodes.end()) {
3668 Done = true;
3669 return;
3670 }
3671
3672 // Parse next opcode and set up next loop.
3673 const uint8_t *OpcodeStart = Ptr;
3674 uint8_t Byte = *Ptr++;
3675 uint8_t ImmValue = Byte & MachO::REBASE_IMMEDIATE_MASK;
3676 uint8_t Opcode = Byte & MachO::REBASE_OPCODE_MASK;
3677 uint64_t Count, Skip;
3678 const char *error = nullptr;
3679 switch (Opcode) {
3680 case MachO::REBASE_OPCODE_DONE:
3681 More = false;
3682 Done = true;
3683 moveToEnd();
3684 DEBUG_WITH_TYPE("mach-o-rebase", dbgs() << "REBASE_OPCODE_DONE\n");
3685 break;
3686 case MachO::REBASE_OPCODE_SET_TYPE_IMM:
3687 RebaseType = ImmValue;
3688 if (RebaseType > MachO::REBASE_TYPE_TEXT_PCREL32) {
3689 *E = malformedError(Msg: "for REBASE_OPCODE_SET_TYPE_IMM bad bind type: " +
3690 Twine((int)RebaseType) + " for opcode at: 0x" +
3691 Twine::utohexstr(Val: OpcodeStart - Opcodes.begin()));
3692 moveToEnd();
3693 return;
3694 }
3695 DEBUG_WITH_TYPE(
3696 "mach-o-rebase",
3697 dbgs() << "REBASE_OPCODE_SET_TYPE_IMM: "
3698 << "RebaseType=" << (int) RebaseType << "\n");
3699 break;
3700 case MachO::REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB:
3701 SegmentIndex = ImmValue;
3702 SegmentOffset = readULEB128(error: &error);
3703 if (error) {
3704 *E = malformedError(Msg: "for REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB " +
3705 Twine(error) + " for opcode at: 0x" +
3706 Twine::utohexstr(Val: OpcodeStart - Opcodes.begin()));
3707 moveToEnd();
3708 return;
3709 }
3710 error = O->RebaseEntryCheckSegAndOffsets(SegIndex: SegmentIndex, SegOffset: SegmentOffset,
3711 PointerSize);
3712 if (error) {
3713 *E = malformedError(Msg: "for REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB " +
3714 Twine(error) + " for opcode at: 0x" +
3715 Twine::utohexstr(Val: OpcodeStart - Opcodes.begin()));
3716 moveToEnd();
3717 return;
3718 }
3719 DEBUG_WITH_TYPE(
3720 "mach-o-rebase",
3721 dbgs() << "REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB: "
3722 << "SegmentIndex=" << SegmentIndex << ", "
3723 << format("SegmentOffset=0x%06X", SegmentOffset)
3724 << "\n");
3725 break;
3726 case MachO::REBASE_OPCODE_ADD_ADDR_ULEB:
3727 SegmentOffset += readULEB128(error: &error);
3728 if (error) {
3729 *E = malformedError(Msg: "for REBASE_OPCODE_ADD_ADDR_ULEB " + Twine(error) +
3730 " for opcode at: 0x" +
3731 Twine::utohexstr(Val: OpcodeStart - Opcodes.begin()));
3732 moveToEnd();
3733 return;
3734 }
3735 error = O->RebaseEntryCheckSegAndOffsets(SegIndex: SegmentIndex, SegOffset: SegmentOffset,
3736 PointerSize);
3737 if (error) {
3738 *E = malformedError(Msg: "for REBASE_OPCODE_ADD_ADDR_ULEB " + Twine(error) +
3739 " for opcode at: 0x" +
3740 Twine::utohexstr(Val: OpcodeStart - Opcodes.begin()));
3741 moveToEnd();
3742 return;
3743 }
3744 DEBUG_WITH_TYPE("mach-o-rebase",
3745 dbgs() << "REBASE_OPCODE_ADD_ADDR_ULEB: "
3746 << format("SegmentOffset=0x%06X",
3747 SegmentOffset) << "\n");
3748 break;
3749 case MachO::REBASE_OPCODE_ADD_ADDR_IMM_SCALED:
3750 SegmentOffset += ImmValue * PointerSize;
3751 error = O->RebaseEntryCheckSegAndOffsets(SegIndex: SegmentIndex, SegOffset: SegmentOffset,
3752 PointerSize);
3753 if (error) {
3754 *E = malformedError(Msg: "for REBASE_OPCODE_ADD_ADDR_IMM_SCALED " +
3755 Twine(error) + " for opcode at: 0x" +
3756 Twine::utohexstr(Val: OpcodeStart - Opcodes.begin()));
3757 moveToEnd();
3758 return;
3759 }
3760 DEBUG_WITH_TYPE("mach-o-rebase",
3761 dbgs() << "REBASE_OPCODE_ADD_ADDR_IMM_SCALED: "
3762 << format("SegmentOffset=0x%06X",
3763 SegmentOffset) << "\n");
3764 break;
3765 case MachO::REBASE_OPCODE_DO_REBASE_IMM_TIMES:
3766 AdvanceAmount = PointerSize;
3767 Skip = 0;
3768 Count = ImmValue;
3769 if (ImmValue != 0)
3770 RemainingLoopCount = ImmValue - 1;
3771 else
3772 RemainingLoopCount = 0;
3773 error = O->RebaseEntryCheckSegAndOffsets(SegIndex: SegmentIndex, SegOffset: SegmentOffset,
3774 PointerSize, Count, Skip);
3775 if (error) {
3776 *E = malformedError(Msg: "for REBASE_OPCODE_DO_REBASE_IMM_TIMES " +
3777 Twine(error) + " for opcode at: 0x" +
3778 Twine::utohexstr(Val: OpcodeStart - Opcodes.begin()));
3779 moveToEnd();
3780 return;
3781 }
3782 DEBUG_WITH_TYPE(
3783 "mach-o-rebase",
3784 dbgs() << "REBASE_OPCODE_DO_REBASE_IMM_TIMES: "
3785 << format("SegmentOffset=0x%06X", SegmentOffset)
3786 << ", AdvanceAmount=" << AdvanceAmount
3787 << ", RemainingLoopCount=" << RemainingLoopCount
3788 << "\n");
3789 return;
3790 case MachO::REBASE_OPCODE_DO_REBASE_ULEB_TIMES:
3791 AdvanceAmount = PointerSize;
3792 Skip = 0;
3793 Count = readULEB128(error: &error);
3794 if (error) {
3795 *E = malformedError(Msg: "for REBASE_OPCODE_DO_REBASE_ULEB_TIMES " +
3796 Twine(error) + " for opcode at: 0x" +
3797 Twine::utohexstr(Val: OpcodeStart - Opcodes.begin()));
3798 moveToEnd();
3799 return;
3800 }
3801 if (Count != 0)
3802 RemainingLoopCount = Count - 1;
3803 else
3804 RemainingLoopCount = 0;
3805 error = O->RebaseEntryCheckSegAndOffsets(SegIndex: SegmentIndex, SegOffset: SegmentOffset,
3806 PointerSize, Count, Skip);
3807 if (error) {
3808 *E = malformedError(Msg: "for REBASE_OPCODE_DO_REBASE_ULEB_TIMES " +
3809 Twine(error) + " for opcode at: 0x" +
3810 Twine::utohexstr(Val: OpcodeStart - Opcodes.begin()));
3811 moveToEnd();
3812 return;
3813 }
3814 DEBUG_WITH_TYPE(
3815 "mach-o-rebase",
3816 dbgs() << "REBASE_OPCODE_DO_REBASE_ULEB_TIMES: "
3817 << format("SegmentOffset=0x%06X", SegmentOffset)
3818 << ", AdvanceAmount=" << AdvanceAmount
3819 << ", RemainingLoopCount=" << RemainingLoopCount
3820 << "\n");
3821 return;
3822 case MachO::REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB:
3823 Skip = readULEB128(error: &error);
3824 if (error) {
3825 *E = malformedError(Msg: "for REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB " +
3826 Twine(error) + " for opcode at: 0x" +
3827 Twine::utohexstr(Val: OpcodeStart - Opcodes.begin()));
3828 moveToEnd();
3829 return;
3830 }
3831 AdvanceAmount = Skip + PointerSize;
3832 Count = 1;
3833 RemainingLoopCount = 0;
3834 error = O->RebaseEntryCheckSegAndOffsets(SegIndex: SegmentIndex, SegOffset: SegmentOffset,
3835 PointerSize, Count, Skip);
3836 if (error) {
3837 *E = malformedError(Msg: "for REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB " +
3838 Twine(error) + " for opcode at: 0x" +
3839 Twine::utohexstr(Val: OpcodeStart - Opcodes.begin()));
3840 moveToEnd();
3841 return;
3842 }
3843 DEBUG_WITH_TYPE(
3844 "mach-o-rebase",
3845 dbgs() << "REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB: "
3846 << format("SegmentOffset=0x%06X", SegmentOffset)
3847 << ", AdvanceAmount=" << AdvanceAmount
3848 << ", RemainingLoopCount=" << RemainingLoopCount
3849 << "\n");
3850 return;
3851 case MachO::REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB:
3852 Count = readULEB128(error: &error);
3853 if (error) {
3854 *E = malformedError(Msg: "for REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_"
3855 "ULEB " +
3856 Twine(error) + " for opcode at: 0x" +
3857 Twine::utohexstr(Val: OpcodeStart - Opcodes.begin()));
3858 moveToEnd();
3859 return;
3860 }
3861 if (Count != 0)
3862 RemainingLoopCount = Count - 1;
3863 else
3864 RemainingLoopCount = 0;
3865 Skip = readULEB128(error: &error);
3866 if (error) {
3867 *E = malformedError(Msg: "for REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_"
3868 "ULEB " +
3869 Twine(error) + " for opcode at: 0x" +
3870 Twine::utohexstr(Val: OpcodeStart - Opcodes.begin()));
3871 moveToEnd();
3872 return;
3873 }
3874 AdvanceAmount = Skip + PointerSize;
3875
3876 error = O->RebaseEntryCheckSegAndOffsets(SegIndex: SegmentIndex, SegOffset: SegmentOffset,
3877 PointerSize, Count, Skip);
3878 if (error) {
3879 *E = malformedError(Msg: "for REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_"
3880 "ULEB " +
3881 Twine(error) + " for opcode at: 0x" +
3882 Twine::utohexstr(Val: OpcodeStart - Opcodes.begin()));
3883 moveToEnd();
3884 return;
3885 }
3886 DEBUG_WITH_TYPE(
3887 "mach-o-rebase",
3888 dbgs() << "REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB: "
3889 << format("SegmentOffset=0x%06X", SegmentOffset)
3890 << ", AdvanceAmount=" << AdvanceAmount
3891 << ", RemainingLoopCount=" << RemainingLoopCount
3892 << "\n");
3893 return;
3894 default:
3895 *E = malformedError(Msg: "bad rebase info (bad opcode value 0x" +
3896 Twine::utohexstr(Val: Opcode) + " for opcode at: 0x" +
3897 Twine::utohexstr(Val: OpcodeStart - Opcodes.begin()));
3898 moveToEnd();
3899 return;
3900 }
3901 }
3902}
3903
3904uint64_t MachORebaseEntry::readULEB128(const char **error) {
3905 unsigned Count;
3906 uint64_t Result = decodeULEB128(p: Ptr, n: &Count, end: Opcodes.end(), error);
3907 Ptr += Count;
3908 if (Ptr > Opcodes.end())
3909 Ptr = Opcodes.end();
3910 return Result;
3911}
3912
3913int32_t MachORebaseEntry::segmentIndex() const { return SegmentIndex; }
3914
3915uint64_t MachORebaseEntry::segmentOffset() const { return SegmentOffset; }
3916
3917StringRef MachORebaseEntry::typeName() const {
3918 switch (RebaseType) {
3919 case MachO::REBASE_TYPE_POINTER:
3920 return "pointer";
3921 case MachO::REBASE_TYPE_TEXT_ABSOLUTE32:
3922 return "text abs32";
3923 case MachO::REBASE_TYPE_TEXT_PCREL32:
3924 return "text rel32";
3925 }
3926 return "unknown";
3927}
3928
3929// For use with the SegIndex of a checked Mach-O Rebase entry
3930// to get the segment name.
3931StringRef MachORebaseEntry::segmentName() const {
3932 return O->BindRebaseSegmentName(SegIndex: SegmentIndex);
3933}
3934
3935// For use with a SegIndex,SegOffset pair from a checked Mach-O Rebase entry
3936// to get the section name.
3937StringRef MachORebaseEntry::sectionName() const {
3938 return O->BindRebaseSectionName(SegIndex: SegmentIndex, SegOffset: SegmentOffset);
3939}
3940
3941// For use with a SegIndex,SegOffset pair from a checked Mach-O Rebase entry
3942// to get the address.
3943uint64_t MachORebaseEntry::address() const {
3944 return O->BindRebaseAddress(SegIndex: SegmentIndex, SegOffset: SegmentOffset);
3945}
3946
3947bool MachORebaseEntry::operator==(const MachORebaseEntry &Other) const {
3948#ifdef EXPENSIVE_CHECKS
3949 assert(Opcodes == Other.Opcodes && "compare iterators of different files");
3950#else
3951 assert(Opcodes.data() == Other.Opcodes.data() && "compare iterators of different files");
3952#endif
3953 return (Ptr == Other.Ptr) &&
3954 (RemainingLoopCount == Other.RemainingLoopCount) &&
3955 (Done == Other.Done);
3956}
3957
3958iterator_range<rebase_iterator>
3959MachOObjectFile::rebaseTable(Error &Err, MachOObjectFile *O,
3960 ArrayRef<uint8_t> Opcodes, bool is64) {
3961 if (O->BindRebaseSectionTable == nullptr)
3962 O->BindRebaseSectionTable = std::make_unique<BindRebaseSegInfo>(args&: O);
3963 MachORebaseEntry Start(&Err, O, Opcodes, is64);
3964 Start.moveToFirst();
3965
3966 MachORebaseEntry Finish(&Err, O, Opcodes, is64);
3967 Finish.moveToEnd();
3968
3969 return make_range(x: rebase_iterator(Start), y: rebase_iterator(Finish));
3970}
3971
3972iterator_range<rebase_iterator> MachOObjectFile::rebaseTable(Error &Err) {
3973 return rebaseTable(Err, O: this, Opcodes: getDyldInfoRebaseOpcodes(), is64: is64Bit());
3974}
3975
3976MachOBindEntry::MachOBindEntry(Error *E, const MachOObjectFile *O,
3977 ArrayRef<uint8_t> Bytes, bool is64Bit, Kind BK)
3978 : E(E), O(O), Opcodes(Bytes), Ptr(Bytes.begin()),
3979 PointerSize(is64Bit ? 8 : 4), TableKind(BK) {}
3980
3981void MachOBindEntry::moveToFirst() {
3982 Ptr = Opcodes.begin();
3983 moveNext();
3984}
3985
3986void MachOBindEntry::moveToEnd() {
3987 Ptr = Opcodes.end();
3988 RemainingLoopCount = 0;
3989 Done = true;
3990}
3991
3992void MachOBindEntry::moveNext() {
3993 ErrorAsOutParameter ErrAsOutParam(E);
3994 // If in the middle of some loop, move to next binding in loop.
3995 SegmentOffset += AdvanceAmount;
3996 if (RemainingLoopCount) {
3997 --RemainingLoopCount;
3998 return;
3999 }
4000
4001 bool More = true;
4002 while (More) {
4003 // BIND_OPCODE_DONE is only used for padding if we are not aligned to
4004 // pointer size. Therefore it is possible to reach the end without ever
4005 // having seen BIND_OPCODE_DONE.
4006 if (Ptr == Opcodes.end()) {
4007 Done = true;
4008 return;
4009 }
4010
4011 // Parse next opcode and set up next loop.
4012 const uint8_t *OpcodeStart = Ptr;
4013 uint8_t Byte = *Ptr++;
4014 uint8_t ImmValue = Byte & MachO::BIND_IMMEDIATE_MASK;
4015 uint8_t Opcode = Byte & MachO::BIND_OPCODE_MASK;
4016 int8_t SignExtended;
4017 const uint8_t *SymStart;
4018 uint64_t Count, Skip;
4019 const char *error = nullptr;
4020 switch (Opcode) {
4021 case MachO::BIND_OPCODE_DONE:
4022 if (TableKind == Kind::Lazy) {
4023 // Lazying bindings have a DONE opcode between entries. Need to ignore
4024 // it to advance to next entry. But need not if this is last entry.
4025 bool NotLastEntry = false;
4026 for (const uint8_t *P = Ptr; P < Opcodes.end(); ++P) {
4027 if (*P) {
4028 NotLastEntry = true;
4029 }
4030 }
4031 if (NotLastEntry)
4032 break;
4033 }
4034 More = false;
4035 moveToEnd();
4036 DEBUG_WITH_TYPE("mach-o-bind", dbgs() << "BIND_OPCODE_DONE\n");
4037 break;
4038 case MachO::BIND_OPCODE_SET_DYLIB_ORDINAL_IMM:
4039 if (TableKind == Kind::Weak) {
4040 *E = malformedError(Msg: "BIND_OPCODE_SET_DYLIB_ORDINAL_IMM not allowed in "
4041 "weak bind table for opcode at: 0x" +
4042 Twine::utohexstr(Val: OpcodeStart - Opcodes.begin()));
4043 moveToEnd();
4044 return;
4045 }
4046 Ordinal = ImmValue;
4047 LibraryOrdinalSet = true;
4048 if (ImmValue > O->getLibraryCount()) {
4049 *E = malformedError(Msg: "for BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB bad "
4050 "library ordinal: " +
4051 Twine((int)ImmValue) + " (max " +
4052 Twine((int)O->getLibraryCount()) +
4053 ") for opcode at: 0x" +
4054 Twine::utohexstr(Val: OpcodeStart - Opcodes.begin()));
4055 moveToEnd();
4056 return;
4057 }
4058 DEBUG_WITH_TYPE(
4059 "mach-o-bind",
4060 dbgs() << "BIND_OPCODE_SET_DYLIB_ORDINAL_IMM: "
4061 << "Ordinal=" << Ordinal << "\n");
4062 break;
4063 case MachO::BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB:
4064 if (TableKind == Kind::Weak) {
4065 *E = malformedError(Msg: "BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB not allowed in "
4066 "weak bind table for opcode at: 0x" +
4067 Twine::utohexstr(Val: OpcodeStart - Opcodes.begin()));
4068 moveToEnd();
4069 return;
4070 }
4071 Ordinal = readULEB128(error: &error);
4072 LibraryOrdinalSet = true;
4073 if (error) {
4074 *E = malformedError(Msg: "for BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB " +
4075 Twine(error) + " for opcode at: 0x" +
4076 Twine::utohexstr(Val: OpcodeStart - Opcodes.begin()));
4077 moveToEnd();
4078 return;
4079 }
4080 if (Ordinal > (int)O->getLibraryCount()) {
4081 *E = malformedError(Msg: "for BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB bad "
4082 "library ordinal: " +
4083 Twine((int)Ordinal) + " (max " +
4084 Twine((int)O->getLibraryCount()) +
4085 ") for opcode at: 0x" +
4086 Twine::utohexstr(Val: OpcodeStart - Opcodes.begin()));
4087 moveToEnd();
4088 return;
4089 }
4090 DEBUG_WITH_TYPE(
4091 "mach-o-bind",
4092 dbgs() << "BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB: "
4093 << "Ordinal=" << Ordinal << "\n");
4094 break;
4095 case MachO::BIND_OPCODE_SET_DYLIB_SPECIAL_IMM:
4096 if (TableKind == Kind::Weak) {
4097 *E = malformedError(Msg: "BIND_OPCODE_SET_DYLIB_SPECIAL_IMM not allowed in "
4098 "weak bind table for opcode at: 0x" +
4099 Twine::utohexstr(Val: OpcodeStart - Opcodes.begin()));
4100 moveToEnd();
4101 return;
4102 }
4103 if (ImmValue) {
4104 SignExtended = MachO::BIND_OPCODE_MASK | ImmValue;
4105 Ordinal = SignExtended;
4106 if (Ordinal < MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP) {
4107 *E = malformedError(Msg: "for BIND_OPCODE_SET_DYLIB_SPECIAL_IMM unknown "
4108 "special ordinal: " +
4109 Twine((int)Ordinal) + " for opcode at: 0x" +
4110 Twine::utohexstr(Val: OpcodeStart - Opcodes.begin()));
4111 moveToEnd();
4112 return;
4113 }
4114 } else
4115 Ordinal = 0;
4116 LibraryOrdinalSet = true;
4117 DEBUG_WITH_TYPE(
4118 "mach-o-bind",
4119 dbgs() << "BIND_OPCODE_SET_DYLIB_SPECIAL_IMM: "
4120 << "Ordinal=" << Ordinal << "\n");
4121 break;
4122 case MachO::BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM:
4123 Flags = ImmValue;
4124 SymStart = Ptr;
4125 while (*Ptr && (Ptr < Opcodes.end())) {
4126 ++Ptr;
4127 }
4128 if (Ptr == Opcodes.end()) {
4129 *E = malformedError(
4130 Msg: "for BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM "
4131 "symbol name extends past opcodes for opcode at: 0x" +
4132 Twine::utohexstr(Val: OpcodeStart - Opcodes.begin()));
4133 moveToEnd();
4134 return;
4135 }
4136 SymbolName = StringRef(reinterpret_cast<const char*>(SymStart),
4137 Ptr-SymStart);
4138 ++Ptr;
4139 DEBUG_WITH_TYPE(
4140 "mach-o-bind",
4141 dbgs() << "BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM: "
4142 << "SymbolName=" << SymbolName << "\n");
4143 if (TableKind == Kind::Weak) {
4144 if (ImmValue & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION)
4145 return;
4146 }
4147 break;
4148 case MachO::BIND_OPCODE_SET_TYPE_IMM:
4149 BindType = ImmValue;
4150 if (ImmValue > MachO::BIND_TYPE_TEXT_PCREL32) {
4151 *E = malformedError(Msg: "for BIND_OPCODE_SET_TYPE_IMM bad bind type: " +
4152 Twine((int)ImmValue) + " for opcode at: 0x" +
4153 Twine::utohexstr(Val: OpcodeStart - Opcodes.begin()));
4154 moveToEnd();
4155 return;
4156 }
4157 DEBUG_WITH_TYPE(
4158 "mach-o-bind",
4159 dbgs() << "BIND_OPCODE_SET_TYPE_IMM: "
4160 << "BindType=" << (int)BindType << "\n");
4161 break;
4162 case MachO::BIND_OPCODE_SET_ADDEND_SLEB:
4163 Addend = readSLEB128(error: &error);
4164 if (error) {
4165 *E = malformedError(Msg: "for BIND_OPCODE_SET_ADDEND_SLEB " + Twine(error) +
4166 " for opcode at: 0x" +
4167 Twine::utohexstr(Val: OpcodeStart - Opcodes.begin()));
4168 moveToEnd();
4169 return;
4170 }
4171 DEBUG_WITH_TYPE(
4172 "mach-o-bind",
4173 dbgs() << "BIND_OPCODE_SET_ADDEND_SLEB: "
4174 << "Addend=" << Addend << "\n");
4175 break;
4176 case MachO::BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB:
4177 SegmentIndex = ImmValue;
4178 SegmentOffset = readULEB128(error: &error);
4179 if (error) {
4180 *E = malformedError(Msg: "for BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB " +
4181 Twine(error) + " for opcode at: 0x" +
4182 Twine::utohexstr(Val: OpcodeStart - Opcodes.begin()));
4183 moveToEnd();
4184 return;
4185 }
4186 error = O->BindEntryCheckSegAndOffsets(SegIndex: SegmentIndex, SegOffset: SegmentOffset,
4187 PointerSize);
4188 if (error) {
4189 *E = malformedError(Msg: "for BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB " +
4190 Twine(error) + " for opcode at: 0x" +
4191 Twine::utohexstr(Val: OpcodeStart - Opcodes.begin()));
4192 moveToEnd();
4193 return;
4194 }
4195 DEBUG_WITH_TYPE(
4196 "mach-o-bind",
4197 dbgs() << "BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB: "
4198 << "SegmentIndex=" << SegmentIndex << ", "
4199 << format("SegmentOffset=0x%06X", SegmentOffset)
4200 << "\n");
4201 break;
4202 case MachO::BIND_OPCODE_ADD_ADDR_ULEB:
4203 SegmentOffset += readULEB128(error: &error);
4204 if (error) {
4205 *E = malformedError(Msg: "for BIND_OPCODE_ADD_ADDR_ULEB " + Twine(error) +
4206 " for opcode at: 0x" +
4207 Twine::utohexstr(Val: OpcodeStart - Opcodes.begin()));
4208 moveToEnd();
4209 return;
4210 }
4211 error = O->BindEntryCheckSegAndOffsets(SegIndex: SegmentIndex, SegOffset: SegmentOffset,
4212 PointerSize);
4213 if (error) {
4214 *E = malformedError(Msg: "for BIND_OPCODE_ADD_ADDR_ULEB " + Twine(error) +
4215 " for opcode at: 0x" +
4216 Twine::utohexstr(Val: OpcodeStart - Opcodes.begin()));
4217 moveToEnd();
4218 return;
4219 }
4220 DEBUG_WITH_TYPE("mach-o-bind",
4221 dbgs() << "BIND_OPCODE_ADD_ADDR_ULEB: "
4222 << format("SegmentOffset=0x%06X",
4223 SegmentOffset) << "\n");
4224 break;
4225 case MachO::BIND_OPCODE_DO_BIND:
4226 AdvanceAmount = PointerSize;
4227 RemainingLoopCount = 0;
4228 error = O->BindEntryCheckSegAndOffsets(SegIndex: SegmentIndex, SegOffset: SegmentOffset,
4229 PointerSize);
4230 if (error) {
4231 *E = malformedError(Msg: "for BIND_OPCODE_DO_BIND " + Twine(error) +
4232 " for opcode at: 0x" +
4233 Twine::utohexstr(Val: OpcodeStart - Opcodes.begin()));
4234 moveToEnd();
4235 return;
4236 }
4237 if (SymbolName == StringRef()) {
4238 *E = malformedError(
4239 Msg: "for BIND_OPCODE_DO_BIND missing preceding "
4240 "BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM for opcode at: 0x" +
4241 Twine::utohexstr(Val: OpcodeStart - Opcodes.begin()));
4242 moveToEnd();
4243 return;
4244 }
4245 if (!LibraryOrdinalSet && TableKind != Kind::Weak) {
4246 *E =
4247 malformedError(Msg: "for BIND_OPCODE_DO_BIND missing preceding "
4248 "BIND_OPCODE_SET_DYLIB_ORDINAL_* for opcode at: 0x" +
4249 Twine::utohexstr(Val: OpcodeStart - Opcodes.begin()));
4250 moveToEnd();
4251 return;
4252 }
4253 DEBUG_WITH_TYPE("mach-o-bind",
4254 dbgs() << "BIND_OPCODE_DO_BIND: "
4255 << format("SegmentOffset=0x%06X",
4256 SegmentOffset) << "\n");
4257 return;
4258 case MachO::BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB:
4259 if (TableKind == Kind::Lazy) {
4260 *E = malformedError(Msg: "BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB not allowed in "
4261 "lazy bind table for opcode at: 0x" +
4262 Twine::utohexstr(Val: OpcodeStart - Opcodes.begin()));
4263 moveToEnd();
4264 return;
4265 }
4266 error = O->BindEntryCheckSegAndOffsets(SegIndex: SegmentIndex, SegOffset: SegmentOffset,
4267 PointerSize);
4268 if (error) {
4269 *E = malformedError(Msg: "for BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB " +
4270 Twine(error) + " for opcode at: 0x" +
4271 Twine::utohexstr(Val: OpcodeStart - Opcodes.begin()));
4272 moveToEnd();
4273 return;
4274 }
4275 if (SymbolName == StringRef()) {
4276 *E = malformedError(
4277 Msg: "for BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB missing "
4278 "preceding BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM for opcode "
4279 "at: 0x" +
4280 Twine::utohexstr(Val: OpcodeStart - Opcodes.begin()));
4281 moveToEnd();
4282 return;
4283 }
4284 if (!LibraryOrdinalSet && TableKind != Kind::Weak) {
4285 *E = malformedError(
4286 Msg: "for BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB missing "
4287 "preceding BIND_OPCODE_SET_DYLIB_ORDINAL_* for opcode at: 0x" +
4288 Twine::utohexstr(Val: OpcodeStart - Opcodes.begin()));
4289 moveToEnd();
4290 return;
4291 }
4292 AdvanceAmount = readULEB128(error: &error) + PointerSize;
4293 if (error) {
4294 *E = malformedError(Msg: "for BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB " +
4295 Twine(error) + " for opcode at: 0x" +
4296 Twine::utohexstr(Val: OpcodeStart - Opcodes.begin()));
4297 moveToEnd();
4298 return;
4299 }
4300 // Note, this is not really an error until the next bind but make no sense
4301 // for a BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB to not be followed by another
4302 // bind operation.
4303 error = O->BindEntryCheckSegAndOffsets(SegIndex: SegmentIndex, SegOffset: SegmentOffset +
4304 AdvanceAmount, PointerSize);
4305 if (error) {
4306 *E = malformedError(Msg: "for BIND_OPCODE_ADD_ADDR_ULEB (after adding "
4307 "ULEB) " +
4308 Twine(error) + " for opcode at: 0x" +
4309 Twine::utohexstr(Val: OpcodeStart - Opcodes.begin()));
4310 moveToEnd();
4311 return;
4312 }
4313 RemainingLoopCount = 0;
4314 DEBUG_WITH_TYPE(
4315 "mach-o-bind",
4316 dbgs() << "BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB: "
4317 << format("SegmentOffset=0x%06X", SegmentOffset)
4318 << ", AdvanceAmount=" << AdvanceAmount
4319 << ", RemainingLoopCount=" << RemainingLoopCount
4320 << "\n");
4321 return;
4322 case MachO::BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED:
4323 if (TableKind == Kind::Lazy) {
4324 *E = malformedError(Msg: "BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED not "
4325 "allowed in lazy bind table for opcode at: 0x" +
4326 Twine::utohexstr(Val: OpcodeStart - Opcodes.begin()));
4327 moveToEnd();
4328 return;
4329 }
4330 if (SymbolName == StringRef()) {
4331 *E = malformedError(
4332 Msg: "for BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED "
4333 "missing preceding BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM for "
4334 "opcode at: 0x" +
4335 Twine::utohexstr(Val: OpcodeStart - Opcodes.begin()));
4336 moveToEnd();
4337 return;
4338 }
4339 if (!LibraryOrdinalSet && TableKind != Kind::Weak) {
4340 *E = malformedError(
4341 Msg: "for BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED "
4342 "missing preceding BIND_OPCODE_SET_DYLIB_ORDINAL_* for opcode "
4343 "at: 0x" +
4344 Twine::utohexstr(Val: OpcodeStart - Opcodes.begin()));
4345 moveToEnd();
4346 return;
4347 }
4348 AdvanceAmount = ImmValue * PointerSize + PointerSize;
4349 RemainingLoopCount = 0;
4350 error = O->BindEntryCheckSegAndOffsets(SegIndex: SegmentIndex, SegOffset: SegmentOffset +
4351 AdvanceAmount, PointerSize);
4352 if (error) {
4353 *E = malformedError(Msg: "for BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED " +
4354 Twine(error) + " for opcode at: 0x" +
4355 Twine::utohexstr(Val: OpcodeStart - Opcodes.begin()));
4356 moveToEnd();
4357 return;
4358 }
4359 DEBUG_WITH_TYPE("mach-o-bind",
4360 dbgs()
4361 << "BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED: "
4362 << format("SegmentOffset=0x%06X", SegmentOffset) << "\n");
4363 return;
4364 case MachO::BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB:
4365 if (TableKind == Kind::Lazy) {
4366 *E = malformedError(Msg: "BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB not "
4367 "allowed in lazy bind table for opcode at: 0x" +
4368 Twine::utohexstr(Val: OpcodeStart - Opcodes.begin()));
4369 moveToEnd();
4370 return;
4371 }
4372 Count = readULEB128(error: &error);
4373 if (Count != 0)
4374 RemainingLoopCount = Count - 1;
4375 else
4376 RemainingLoopCount = 0;
4377 if (error) {
4378 *E = malformedError(Msg: "for BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB "
4379 " (count value) " +
4380 Twine(error) + " for opcode at: 0x" +
4381 Twine::utohexstr(Val: OpcodeStart - Opcodes.begin()));
4382 moveToEnd();
4383 return;
4384 }
4385 Skip = readULEB128(error: &error);
4386 AdvanceAmount = Skip + PointerSize;
4387 if (error) {
4388 *E = malformedError(Msg: "for BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB "
4389 " (skip value) " +
4390 Twine(error) + " for opcode at: 0x" +
4391 Twine::utohexstr(Val: OpcodeStart - Opcodes.begin()));
4392 moveToEnd();
4393 return;
4394 }
4395 if (SymbolName == StringRef()) {
4396 *E = malformedError(
4397 Msg: "for BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB "
4398 "missing preceding BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM for "
4399 "opcode at: 0x" +
4400 Twine::utohexstr(Val: OpcodeStart - Opcodes.begin()));
4401 moveToEnd();
4402 return;
4403 }
4404 if (!LibraryOrdinalSet && TableKind != Kind::Weak) {
4405 *E = malformedError(
4406 Msg: "for BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB "
4407 "missing preceding BIND_OPCODE_SET_DYLIB_ORDINAL_* for opcode "
4408 "at: 0x" +
4409 Twine::utohexstr(Val: OpcodeStart - Opcodes.begin()));
4410 moveToEnd();
4411 return;
4412 }
4413 error = O->BindEntryCheckSegAndOffsets(SegIndex: SegmentIndex, SegOffset: SegmentOffset,
4414 PointerSize, Count, Skip);
4415 if (error) {
4416 *E =
4417 malformedError(Msg: "for BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB " +
4418 Twine(error) + " for opcode at: 0x" +
4419 Twine::utohexstr(Val: OpcodeStart - Opcodes.begin()));
4420 moveToEnd();
4421 return;
4422 }
4423 DEBUG_WITH_TYPE(
4424 "mach-o-bind",
4425 dbgs() << "BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB: "
4426 << format("SegmentOffset=0x%06X", SegmentOffset)
4427 << ", AdvanceAmount=" << AdvanceAmount
4428 << ", RemainingLoopCount=" << RemainingLoopCount
4429 << "\n");
4430 return;
4431 default:
4432 *E = malformedError(Msg: "bad bind info (bad opcode value 0x" +
4433 Twine::utohexstr(Val: Opcode) + " for opcode at: 0x" +
4434 Twine::utohexstr(Val: OpcodeStart - Opcodes.begin()));
4435 moveToEnd();
4436 return;
4437 }
4438 }
4439}
4440
4441uint64_t MachOBindEntry::readULEB128(const char **error) {
4442 unsigned Count;
4443 uint64_t Result = decodeULEB128(p: Ptr, n: &Count, end: Opcodes.end(), error);
4444 Ptr += Count;
4445 if (Ptr > Opcodes.end())
4446 Ptr = Opcodes.end();
4447 return Result;
4448}
4449
4450int64_t MachOBindEntry::readSLEB128(const char **error) {
4451 unsigned Count;
4452 int64_t Result = decodeSLEB128(p: Ptr, n: &Count, end: Opcodes.end(), error);
4453 Ptr += Count;
4454 if (Ptr > Opcodes.end())
4455 Ptr = Opcodes.end();
4456 return Result;
4457}
4458
4459int32_t MachOBindEntry::segmentIndex() const { return SegmentIndex; }
4460
4461uint64_t MachOBindEntry::segmentOffset() const { return SegmentOffset; }
4462
4463StringRef MachOBindEntry::typeName() const {
4464 switch (BindType) {
4465 case MachO::BIND_TYPE_POINTER:
4466 return "pointer";
4467 case MachO::BIND_TYPE_TEXT_ABSOLUTE32:
4468 return "text abs32";
4469 case MachO::BIND_TYPE_TEXT_PCREL32:
4470 return "text rel32";
4471 }
4472 return "unknown";
4473}
4474
4475StringRef MachOBindEntry::symbolName() const { return SymbolName; }
4476
4477int64_t MachOBindEntry::addend() const { return Addend; }
4478
4479uint32_t MachOBindEntry::flags() const { return Flags; }
4480
4481int MachOBindEntry::ordinal() const { return Ordinal; }
4482
4483// For use with the SegIndex of a checked Mach-O Bind entry
4484// to get the segment name.
4485StringRef MachOBindEntry::segmentName() const {
4486 return O->BindRebaseSegmentName(SegIndex: SegmentIndex);
4487}
4488
4489// For use with a SegIndex,SegOffset pair from a checked Mach-O Bind entry
4490// to get the section name.
4491StringRef MachOBindEntry::sectionName() const {
4492 return O->BindRebaseSectionName(SegIndex: SegmentIndex, SegOffset: SegmentOffset);
4493}
4494
4495// For use with a SegIndex,SegOffset pair from a checked Mach-O Bind entry
4496// to get the address.
4497uint64_t MachOBindEntry::address() const {
4498 return O->BindRebaseAddress(SegIndex: SegmentIndex, SegOffset: SegmentOffset);
4499}
4500
4501bool MachOBindEntry::operator==(const MachOBindEntry &Other) const {
4502#ifdef EXPENSIVE_CHECKS
4503 assert(Opcodes == Other.Opcodes && "compare iterators of different files");
4504#else
4505 assert(Opcodes.data() == Other.Opcodes.data() && "compare iterators of different files");
4506#endif
4507 return (Ptr == Other.Ptr) &&
4508 (RemainingLoopCount == Other.RemainingLoopCount) &&
4509 (Done == Other.Done);
4510}
4511
4512// Build table of sections so SegIndex/SegOffset pairs can be translated.
4513BindRebaseSegInfo::BindRebaseSegInfo(const object::MachOObjectFile *Obj) {
4514 uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
4515 StringRef CurSegName;
4516 uint64_t CurSegAddress;
4517 for (const SectionRef &Section : Obj->sections()) {
4518 SectionInfo Info;
4519 Expected<StringRef> NameOrErr = Section.getName();
4520 if (!NameOrErr)
4521 consumeError(Err: NameOrErr.takeError());
4522 else
4523 Info.SectionName = *NameOrErr;
4524 Info.Address = Section.getAddress();
4525 Info.Size = Section.getSize();
4526 Info.SegmentName =
4527 Obj->getSectionFinalSegmentName(Sec: Section.getRawDataRefImpl());
4528 if (Info.SegmentName != CurSegName) {
4529 ++CurSegIndex;
4530 CurSegName = Info.SegmentName;
4531 CurSegAddress = Info.Address;
4532 }
4533 Info.SegmentIndex = CurSegIndex - 1;
4534 Info.OffsetInSegment = Info.Address - CurSegAddress;
4535 Info.SegmentStartAddress = CurSegAddress;
4536 Sections.push_back(Elt: Info);
4537 }
4538 MaxSegIndex = CurSegIndex;
4539}
4540
4541// For use with a SegIndex, SegOffset, and PointerSize triple in
4542// MachOBindEntry::moveNext() to validate a MachOBindEntry or MachORebaseEntry.
4543//
4544// Given a SegIndex, SegOffset, and PointerSize, verify a valid section exists
4545// that fully contains a pointer at that location. Multiple fixups in a bind
4546// (such as with the BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB opcode) can
4547// be tested via the Count and Skip parameters.
4548const char *BindRebaseSegInfo::checkSegAndOffsets(int32_t SegIndex,
4549 uint64_t SegOffset,
4550 uint8_t PointerSize,
4551 uint64_t Count,
4552 uint64_t Skip) {
4553 if (SegIndex == -1)
4554 return "missing preceding *_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB";
4555 if (SegIndex >= MaxSegIndex)
4556 return "bad segIndex (too large)";
4557 for (uint64_t i = 0; i < Count; ++i) {
4558 uint64_t Start = SegOffset + i * (PointerSize + Skip);
4559 uint64_t End = Start + PointerSize;
4560 bool Found = false;
4561 for (const SectionInfo &SI : Sections) {
4562 if (SI.SegmentIndex != SegIndex)
4563 continue;
4564 if ((SI.OffsetInSegment<=Start) && (Start<(SI.OffsetInSegment+SI.Size))) {
4565 if (End <= SI.OffsetInSegment + SI.Size) {
4566 Found = true;
4567 break;
4568 }
4569 else
4570 return "bad offset, extends beyond section boundary";
4571 }
4572 }
4573 if (!Found)
4574 return "bad offset, not in section";
4575 }
4576 return nullptr;
4577}
4578
4579// For use with the SegIndex of a checked Mach-O Bind or Rebase entry
4580// to get the segment name.
4581StringRef BindRebaseSegInfo::segmentName(int32_t SegIndex) {
4582 for (const SectionInfo &SI : Sections) {
4583 if (SI.SegmentIndex == SegIndex)
4584 return SI.SegmentName;
4585 }
4586 llvm_unreachable("invalid SegIndex");
4587}
4588
4589// For use with a SegIndex,SegOffset pair from a checked Mach-O Bind or Rebase
4590// to get the SectionInfo.
4591const BindRebaseSegInfo::SectionInfo &BindRebaseSegInfo::findSection(
4592 int32_t SegIndex, uint64_t SegOffset) {
4593 for (const SectionInfo &SI : Sections) {
4594 if (SI.SegmentIndex != SegIndex)
4595 continue;
4596 if (SI.OffsetInSegment > SegOffset)
4597 continue;
4598 if (SegOffset >= (SI.OffsetInSegment + SI.Size))
4599 continue;
4600 return SI;
4601 }
4602 llvm_unreachable("SegIndex and SegOffset not in any section");
4603}
4604
4605// For use with a SegIndex,SegOffset pair from a checked Mach-O Bind or Rebase
4606// entry to get the section name.
4607StringRef BindRebaseSegInfo::sectionName(int32_t SegIndex,
4608 uint64_t SegOffset) {
4609 return findSection(SegIndex, SegOffset).SectionName;
4610}
4611
4612// For use with a SegIndex,SegOffset pair from a checked Mach-O Bind or Rebase
4613// entry to get the address.
4614uint64_t BindRebaseSegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) {
4615 const SectionInfo &SI = findSection(SegIndex, SegOffset: OffsetInSeg);
4616 return SI.SegmentStartAddress + OffsetInSeg;
4617}
4618
4619iterator_range<bind_iterator>
4620MachOObjectFile::bindTable(Error &Err, MachOObjectFile *O,
4621 ArrayRef<uint8_t> Opcodes, bool is64,
4622 MachOBindEntry::Kind BKind) {
4623 if (O->BindRebaseSectionTable == nullptr)
4624 O->BindRebaseSectionTable = std::make_unique<BindRebaseSegInfo>(args&: O);
4625 MachOBindEntry Start(&Err, O, Opcodes, is64, BKind);
4626 Start.moveToFirst();
4627
4628 MachOBindEntry Finish(&Err, O, Opcodes, is64, BKind);
4629 Finish.moveToEnd();
4630
4631 return make_range(x: bind_iterator(Start), y: bind_iterator(Finish));
4632}
4633
4634iterator_range<bind_iterator> MachOObjectFile::bindTable(Error &Err) {
4635 return bindTable(Err, O: this, Opcodes: getDyldInfoBindOpcodes(), is64: is64Bit(),
4636 BKind: MachOBindEntry::Kind::Regular);
4637}
4638
4639iterator_range<bind_iterator> MachOObjectFile::lazyBindTable(Error &Err) {
4640 return bindTable(Err, O: this, Opcodes: getDyldInfoLazyBindOpcodes(), is64: is64Bit(),
4641 BKind: MachOBindEntry::Kind::Lazy);
4642}
4643
4644iterator_range<bind_iterator> MachOObjectFile::weakBindTable(Error &Err) {
4645 return bindTable(Err, O: this, Opcodes: getDyldInfoWeakBindOpcodes(), is64: is64Bit(),
4646 BKind: MachOBindEntry::Kind::Weak);
4647}
4648
4649iterator_range<fixup_iterator> MachOObjectFile::fixupTable(Error &Err) {
4650 if (BindRebaseSectionTable == nullptr)
4651 BindRebaseSectionTable = std::make_unique<BindRebaseSegInfo>(args: this);
4652
4653 MachOChainedFixupEntry Start(&Err, this, true);
4654 Start.moveToFirst();
4655
4656 MachOChainedFixupEntry Finish(&Err, this, false);
4657 Finish.moveToEnd();
4658
4659 return make_range(x: fixup_iterator(Start), y: fixup_iterator(Finish));
4660}
4661
4662MachOObjectFile::load_command_iterator
4663MachOObjectFile::begin_load_commands() const {
4664 return LoadCommands.begin();
4665}
4666
4667MachOObjectFile::load_command_iterator
4668MachOObjectFile::end_load_commands() const {
4669 return LoadCommands.end();
4670}
4671
4672iterator_range<MachOObjectFile::load_command_iterator>
4673MachOObjectFile::load_commands() const {
4674 return make_range(x: begin_load_commands(), y: end_load_commands());
4675}
4676
4677StringRef
4678MachOObjectFile::getSectionFinalSegmentName(DataRefImpl Sec) const {
4679 ArrayRef<char> Raw = getSectionRawFinalSegmentName(Sec);
4680 return parseSegmentOrSectionName(P: Raw.data());
4681}
4682
4683ArrayRef<char>
4684MachOObjectFile::getSectionRawName(DataRefImpl Sec) const {
4685 assert(Sec.d.a < Sections.size() && "Should have detected this earlier");
4686 const section_base *Base =
4687 reinterpret_cast<const section_base *>(Sections[Sec.d.a]);
4688 return ArrayRef(Base->sectname);
4689}
4690
4691ArrayRef<char>
4692MachOObjectFile::getSectionRawFinalSegmentName(DataRefImpl Sec) const {
4693 assert(Sec.d.a < Sections.size() && "Should have detected this earlier");
4694 const section_base *Base =
4695 reinterpret_cast<const section_base *>(Sections[Sec.d.a]);
4696 return ArrayRef(Base->segname);
4697}
4698
4699bool
4700MachOObjectFile::isRelocationScattered(const MachO::any_relocation_info &RE)
4701 const {
4702 if (getCPUType(O: *this) == MachO::CPU_TYPE_X86_64)
4703 return false;
4704 return getPlainRelocationAddress(RE) & MachO::R_SCATTERED;
4705}
4706
4707unsigned MachOObjectFile::getPlainRelocationSymbolNum(
4708 const MachO::any_relocation_info &RE) const {
4709 if (isLittleEndian())
4710 return RE.r_word1 & 0xffffff;
4711 return RE.r_word1 >> 8;
4712}
4713
4714bool MachOObjectFile::getPlainRelocationExternal(
4715 const MachO::any_relocation_info &RE) const {
4716 if (isLittleEndian())
4717 return (RE.r_word1 >> 27) & 1;
4718 return (RE.r_word1 >> 4) & 1;
4719}
4720
4721bool MachOObjectFile::getScatteredRelocationScattered(
4722 const MachO::any_relocation_info &RE) const {
4723 return RE.r_word0 >> 31;
4724}
4725
4726uint32_t MachOObjectFile::getScatteredRelocationValue(
4727 const MachO::any_relocation_info &RE) const {
4728 return RE.r_word1;
4729}
4730
4731uint32_t MachOObjectFile::getScatteredRelocationType(
4732 const MachO::any_relocation_info &RE) const {
4733 return (RE.r_word0 >> 24) & 0xf;
4734}
4735
4736unsigned MachOObjectFile::getAnyRelocationAddress(
4737 const MachO::any_relocation_info &RE) const {
4738 if (isRelocationScattered(RE))
4739 return getScatteredRelocationAddress(RE);
4740 return getPlainRelocationAddress(RE);
4741}
4742
4743unsigned MachOObjectFile::getAnyRelocationPCRel(
4744 const MachO::any_relocation_info &RE) const {
4745 if (isRelocationScattered(RE))
4746 return getScatteredRelocationPCRel(RE);
4747 return getPlainRelocationPCRel(O: *this, RE);
4748}
4749
4750unsigned MachOObjectFile::getAnyRelocationLength(
4751 const MachO::any_relocation_info &RE) const {
4752 if (isRelocationScattered(RE))
4753 return getScatteredRelocationLength(RE);
4754 return getPlainRelocationLength(O: *this, RE);
4755}
4756
4757unsigned
4758MachOObjectFile::getAnyRelocationType(
4759 const MachO::any_relocation_info &RE) const {
4760 if (isRelocationScattered(RE))
4761 return getScatteredRelocationType(RE);
4762 return getPlainRelocationType(O: *this, RE);
4763}
4764
4765SectionRef
4766MachOObjectFile::getAnyRelocationSection(
4767 const MachO::any_relocation_info &RE) const {
4768 if (isRelocationScattered(RE) || getPlainRelocationExternal(RE))
4769 return *section_end();
4770 unsigned SecNum = getPlainRelocationSymbolNum(RE);
4771 if (SecNum == MachO::R_ABS || SecNum > Sections.size())
4772 return *section_end();
4773 DataRefImpl DRI;
4774 DRI.d.a = SecNum - 1;
4775 return SectionRef(DRI, this);
4776}
4777
4778MachO::section MachOObjectFile::getSection(DataRefImpl DRI) const {
4779 assert(DRI.d.a < Sections.size() && "Should have detected this earlier");
4780 return getStruct<MachO::section>(O: *this, P: Sections[DRI.d.a]);
4781}
4782
4783MachO::section_64 MachOObjectFile::getSection64(DataRefImpl DRI) const {
4784 assert(DRI.d.a < Sections.size() && "Should have detected this earlier");
4785 return getStruct<MachO::section_64>(O: *this, P: Sections[DRI.d.a]);
4786}
4787
4788MachO::section MachOObjectFile::getSection(const LoadCommandInfo &L,
4789 unsigned Index) const {
4790 const char *Sec = getSectionPtr(O: *this, L, Sec: Index);
4791 return getStruct<MachO::section>(O: *this, P: Sec);
4792}
4793
4794MachO::section_64 MachOObjectFile::getSection64(const LoadCommandInfo &L,
4795 unsigned Index) const {
4796 const char *Sec = getSectionPtr(O: *this, L, Sec: Index);
4797 return getStruct<MachO::section_64>(O: *this, P: Sec);
4798}
4799
4800MachO::nlist
4801MachOObjectFile::getSymbolTableEntry(DataRefImpl DRI) const {
4802 const char *P = reinterpret_cast<const char *>(DRI.p);
4803 return getStruct<MachO::nlist>(O: *this, P);
4804}
4805
4806MachO::nlist_64
4807MachOObjectFile::getSymbol64TableEntry(DataRefImpl DRI) const {
4808 const char *P = reinterpret_cast<const char *>(DRI.p);
4809 return getStruct<MachO::nlist_64>(O: *this, P);
4810}
4811
4812MachO::linkedit_data_command
4813MachOObjectFile::getLinkeditDataLoadCommand(const LoadCommandInfo &L) const {
4814 return getStruct<MachO::linkedit_data_command>(O: *this, P: L.Ptr);
4815}
4816
4817MachO::segment_command
4818MachOObjectFile::getSegmentLoadCommand(const LoadCommandInfo &L) const {
4819 return getStruct<MachO::segment_command>(O: *this, P: L.Ptr);
4820}
4821
4822MachO::segment_command_64
4823MachOObjectFile::getSegment64LoadCommand(const LoadCommandInfo &L) const {
4824 return getStruct<MachO::segment_command_64>(O: *this, P: L.Ptr);
4825}
4826
4827MachO::linker_option_command
4828MachOObjectFile::getLinkerOptionLoadCommand(const LoadCommandInfo &L) const {
4829 return getStruct<MachO::linker_option_command>(O: *this, P: L.Ptr);
4830}
4831
4832MachO::version_min_command
4833MachOObjectFile::getVersionMinLoadCommand(const LoadCommandInfo &L) const {
4834 return getStruct<MachO::version_min_command>(O: *this, P: L.Ptr);
4835}
4836
4837MachO::note_command
4838MachOObjectFile::getNoteLoadCommand(const LoadCommandInfo &L) const {
4839 return getStruct<MachO::note_command>(O: *this, P: L.Ptr);
4840}
4841
4842MachO::build_version_command
4843MachOObjectFile::getBuildVersionLoadCommand(const LoadCommandInfo &L) const {
4844 return getStruct<MachO::build_version_command>(O: *this, P: L.Ptr);
4845}
4846
4847MachO::target_triple_command
4848MachOObjectFile::getTargetTripleLoadCommand(const LoadCommandInfo &L) const {
4849 return getStruct<MachO::target_triple_command>(O: *this, P: L.Ptr);
4850}
4851
4852MachO::build_tool_version
4853MachOObjectFile::getBuildToolVersion(unsigned index) const {
4854 return getStruct<MachO::build_tool_version>(O: *this, P: BuildTools[index]);
4855}
4856
4857MachO::dylib_command
4858MachOObjectFile::getDylibIDLoadCommand(const LoadCommandInfo &L) const {
4859 return getStruct<MachO::dylib_command>(O: *this, P: L.Ptr);
4860}
4861
4862MachO::dyld_info_command
4863MachOObjectFile::getDyldInfoLoadCommand(const LoadCommandInfo &L) const {
4864 return getStruct<MachO::dyld_info_command>(O: *this, P: L.Ptr);
4865}
4866
4867MachO::dylinker_command
4868MachOObjectFile::getDylinkerCommand(const LoadCommandInfo &L) const {
4869 return getStruct<MachO::dylinker_command>(O: *this, P: L.Ptr);
4870}
4871
4872MachO::uuid_command
4873MachOObjectFile::getUuidCommand(const LoadCommandInfo &L) const {
4874 return getStruct<MachO::uuid_command>(O: *this, P: L.Ptr);
4875}
4876
4877MachO::rpath_command
4878MachOObjectFile::getRpathCommand(const LoadCommandInfo &L) const {
4879 return getStruct<MachO::rpath_command>(O: *this, P: L.Ptr);
4880}
4881
4882MachO::source_version_command
4883MachOObjectFile::getSourceVersionCommand(const LoadCommandInfo &L) const {
4884 return getStruct<MachO::source_version_command>(O: *this, P: L.Ptr);
4885}
4886
4887MachO::entry_point_command
4888MachOObjectFile::getEntryPointCommand(const LoadCommandInfo &L) const {
4889 return getStruct<MachO::entry_point_command>(O: *this, P: L.Ptr);
4890}
4891
4892MachO::encryption_info_command
4893MachOObjectFile::getEncryptionInfoCommand(const LoadCommandInfo &L) const {
4894 return getStruct<MachO::encryption_info_command>(O: *this, P: L.Ptr);
4895}
4896
4897MachO::encryption_info_command_64
4898MachOObjectFile::getEncryptionInfoCommand64(const LoadCommandInfo &L) const {
4899 return getStruct<MachO::encryption_info_command_64>(O: *this, P: L.Ptr);
4900}
4901
4902MachO::sub_framework_command
4903MachOObjectFile::getSubFrameworkCommand(const LoadCommandInfo &L) const {
4904 return getStruct<MachO::sub_framework_command>(O: *this, P: L.Ptr);
4905}
4906
4907MachO::sub_umbrella_command
4908MachOObjectFile::getSubUmbrellaCommand(const LoadCommandInfo &L) const {
4909 return getStruct<MachO::sub_umbrella_command>(O: *this, P: L.Ptr);
4910}
4911
4912MachO::sub_library_command
4913MachOObjectFile::getSubLibraryCommand(const LoadCommandInfo &L) const {
4914 return getStruct<MachO::sub_library_command>(O: *this, P: L.Ptr);
4915}
4916
4917MachO::sub_client_command
4918MachOObjectFile::getSubClientCommand(const LoadCommandInfo &L) const {
4919 return getStruct<MachO::sub_client_command>(O: *this, P: L.Ptr);
4920}
4921
4922MachO::routines_command
4923MachOObjectFile::getRoutinesCommand(const LoadCommandInfo &L) const {
4924 return getStruct<MachO::routines_command>(O: *this, P: L.Ptr);
4925}
4926
4927MachO::routines_command_64
4928MachOObjectFile::getRoutinesCommand64(const LoadCommandInfo &L) const {
4929 return getStruct<MachO::routines_command_64>(O: *this, P: L.Ptr);
4930}
4931
4932MachO::thread_command
4933MachOObjectFile::getThreadCommand(const LoadCommandInfo &L) const {
4934 return getStruct<MachO::thread_command>(O: *this, P: L.Ptr);
4935}
4936
4937MachO::fileset_entry_command
4938MachOObjectFile::getFilesetEntryLoadCommand(const LoadCommandInfo &L) const {
4939 return getStruct<MachO::fileset_entry_command>(O: *this, P: L.Ptr);
4940}
4941
4942MachO::any_relocation_info
4943MachOObjectFile::getRelocation(DataRefImpl Rel) const {
4944 uint32_t Offset;
4945 if (getHeader().filetype == MachO::MH_OBJECT) {
4946 DataRefImpl Sec;
4947 Sec.d.a = Rel.d.a;
4948 if (is64Bit()) {
4949 MachO::section_64 Sect = getSection64(DRI: Sec);
4950 Offset = Sect.reloff;
4951 } else {
4952 MachO::section Sect = getSection(DRI: Sec);
4953 Offset = Sect.reloff;
4954 }
4955 } else {
4956 MachO::dysymtab_command DysymtabLoadCmd = getDysymtabLoadCommand();
4957 if (Rel.d.a == 0)
4958 Offset = DysymtabLoadCmd.extreloff; // Offset to the external relocations
4959 else
4960 Offset = DysymtabLoadCmd.locreloff; // Offset to the local relocations
4961 }
4962
4963 auto P = reinterpret_cast<const MachO::any_relocation_info *>(
4964 getPtr(O: *this, Offset)) + Rel.d.b;
4965 return getStruct<MachO::any_relocation_info>(
4966 O: *this, P: reinterpret_cast<const char *>(P));
4967}
4968
4969MachO::data_in_code_entry
4970MachOObjectFile::getDice(DataRefImpl Rel) const {
4971 const char *P = reinterpret_cast<const char *>(Rel.p);
4972 return getStruct<MachO::data_in_code_entry>(O: *this, P);
4973}
4974
4975const MachO::mach_header &MachOObjectFile::getHeader() const {
4976 return Header;
4977}
4978
4979const MachO::mach_header_64 &MachOObjectFile::getHeader64() const {
4980 assert(is64Bit());
4981 return Header64;
4982}
4983
4984uint32_t MachOObjectFile::getIndirectSymbolTableEntry(
4985 const MachO::dysymtab_command &DLC,
4986 unsigned Index) const {
4987 uint64_t Offset = DLC.indirectsymoff + Index * sizeof(uint32_t);
4988 return getStruct<uint32_t>(O: *this, P: getPtr(O: *this, Offset));
4989}
4990
4991MachO::data_in_code_entry
4992MachOObjectFile::getDataInCodeTableEntry(uint32_t DataOffset,
4993 unsigned Index) const {
4994 uint64_t Offset = DataOffset + Index * sizeof(MachO::data_in_code_entry);
4995 return getStruct<MachO::data_in_code_entry>(O: *this, P: getPtr(O: *this, Offset));
4996}
4997
4998MachO::symtab_command MachOObjectFile::getSymtabLoadCommand() const {
4999 if (SymtabLoadCmd)
5000 return getStruct<MachO::symtab_command>(O: *this, P: SymtabLoadCmd);
5001
5002 // If there is no SymtabLoadCmd return a load command with zero'ed fields.
5003 MachO::symtab_command Cmd;
5004 Cmd.cmd = MachO::LC_SYMTAB;
5005 Cmd.cmdsize = sizeof(MachO::symtab_command);
5006 Cmd.symoff = 0;
5007 Cmd.nsyms = 0;
5008 Cmd.stroff = 0;
5009 Cmd.strsize = 0;
5010 return Cmd;
5011}
5012
5013MachO::dysymtab_command MachOObjectFile::getDysymtabLoadCommand() const {
5014 if (DysymtabLoadCmd)
5015 return getStruct<MachO::dysymtab_command>(O: *this, P: DysymtabLoadCmd);
5016
5017 // If there is no DysymtabLoadCmd return a load command with zero'ed fields.
5018 MachO::dysymtab_command Cmd;
5019 Cmd.cmd = MachO::LC_DYSYMTAB;
5020 Cmd.cmdsize = sizeof(MachO::dysymtab_command);
5021 Cmd.ilocalsym = 0;
5022 Cmd.nlocalsym = 0;
5023 Cmd.iextdefsym = 0;
5024 Cmd.nextdefsym = 0;
5025 Cmd.iundefsym = 0;
5026 Cmd.nundefsym = 0;
5027 Cmd.tocoff = 0;
5028 Cmd.ntoc = 0;
5029 Cmd.modtaboff = 0;
5030 Cmd.nmodtab = 0;
5031 Cmd.extrefsymoff = 0;
5032 Cmd.nextrefsyms = 0;
5033 Cmd.indirectsymoff = 0;
5034 Cmd.nindirectsyms = 0;
5035 Cmd.extreloff = 0;
5036 Cmd.nextrel = 0;
5037 Cmd.locreloff = 0;
5038 Cmd.nlocrel = 0;
5039 return Cmd;
5040}
5041
5042MachO::linkedit_data_command
5043MachOObjectFile::getDataInCodeLoadCommand() const {
5044 if (DataInCodeLoadCmd)
5045 return getStruct<MachO::linkedit_data_command>(O: *this, P: DataInCodeLoadCmd);
5046
5047 // If there is no DataInCodeLoadCmd return a load command with zero'ed fields.
5048 MachO::linkedit_data_command Cmd;
5049 Cmd.cmd = MachO::LC_DATA_IN_CODE;
5050 Cmd.cmdsize = sizeof(MachO::linkedit_data_command);
5051 Cmd.dataoff = 0;
5052 Cmd.datasize = 0;
5053 return Cmd;
5054}
5055
5056MachO::linkedit_data_command
5057MachOObjectFile::getLinkOptHintsLoadCommand() const {
5058 if (LinkOptHintsLoadCmd)
5059 return getStruct<MachO::linkedit_data_command>(O: *this, P: LinkOptHintsLoadCmd);
5060
5061 // If there is no LinkOptHintsLoadCmd return a load command with zero'ed
5062 // fields.
5063 MachO::linkedit_data_command Cmd;
5064 Cmd.cmd = MachO::LC_LINKER_OPTIMIZATION_HINT;
5065 Cmd.cmdsize = sizeof(MachO::linkedit_data_command);
5066 Cmd.dataoff = 0;
5067 Cmd.datasize = 0;
5068 return Cmd;
5069}
5070
5071ArrayRef<uint8_t> MachOObjectFile::getDyldInfoRebaseOpcodes() const {
5072 if (!DyldInfoLoadCmd)
5073 return {};
5074
5075 auto DyldInfoOrErr =
5076 getStructOrErr<MachO::dyld_info_command>(O: *this, P: DyldInfoLoadCmd);
5077 if (!DyldInfoOrErr)
5078 return {};
5079 MachO::dyld_info_command DyldInfo = DyldInfoOrErr.get();
5080 const uint8_t *Ptr =
5081 reinterpret_cast<const uint8_t *>(getPtr(O: *this, Offset: DyldInfo.rebase_off));
5082 return ArrayRef(Ptr, DyldInfo.rebase_size);
5083}
5084
5085ArrayRef<uint8_t> MachOObjectFile::getDyldInfoBindOpcodes() const {
5086 if (!DyldInfoLoadCmd)
5087 return {};
5088
5089 auto DyldInfoOrErr =
5090 getStructOrErr<MachO::dyld_info_command>(O: *this, P: DyldInfoLoadCmd);
5091 if (!DyldInfoOrErr)
5092 return {};
5093 MachO::dyld_info_command DyldInfo = DyldInfoOrErr.get();
5094 const uint8_t *Ptr =
5095 reinterpret_cast<const uint8_t *>(getPtr(O: *this, Offset: DyldInfo.bind_off));
5096 return ArrayRef(Ptr, DyldInfo.bind_size);
5097}
5098
5099ArrayRef<uint8_t> MachOObjectFile::getDyldInfoWeakBindOpcodes() const {
5100 if (!DyldInfoLoadCmd)
5101 return {};
5102
5103 auto DyldInfoOrErr =
5104 getStructOrErr<MachO::dyld_info_command>(O: *this, P: DyldInfoLoadCmd);
5105 if (!DyldInfoOrErr)
5106 return {};
5107 MachO::dyld_info_command DyldInfo = DyldInfoOrErr.get();
5108 const uint8_t *Ptr =
5109 reinterpret_cast<const uint8_t *>(getPtr(O: *this, Offset: DyldInfo.weak_bind_off));
5110 return ArrayRef(Ptr, DyldInfo.weak_bind_size);
5111}
5112
5113ArrayRef<uint8_t> MachOObjectFile::getDyldInfoLazyBindOpcodes() const {
5114 if (!DyldInfoLoadCmd)
5115 return {};
5116
5117 auto DyldInfoOrErr =
5118 getStructOrErr<MachO::dyld_info_command>(O: *this, P: DyldInfoLoadCmd);
5119 if (!DyldInfoOrErr)
5120 return {};
5121 MachO::dyld_info_command DyldInfo = DyldInfoOrErr.get();
5122 const uint8_t *Ptr =
5123 reinterpret_cast<const uint8_t *>(getPtr(O: *this, Offset: DyldInfo.lazy_bind_off));
5124 return ArrayRef(Ptr, DyldInfo.lazy_bind_size);
5125}
5126
5127ArrayRef<uint8_t> MachOObjectFile::getDyldInfoExportsTrie() const {
5128 if (!DyldInfoLoadCmd)
5129 return {};
5130
5131 auto DyldInfoOrErr =
5132 getStructOrErr<MachO::dyld_info_command>(O: *this, P: DyldInfoLoadCmd);
5133 if (!DyldInfoOrErr)
5134 return {};
5135 MachO::dyld_info_command DyldInfo = DyldInfoOrErr.get();
5136 const uint8_t *Ptr =
5137 reinterpret_cast<const uint8_t *>(getPtr(O: *this, Offset: DyldInfo.export_off));
5138 return ArrayRef(Ptr, DyldInfo.export_size);
5139}
5140
5141Expected<std::optional<MachO::linkedit_data_command>>
5142MachOObjectFile::getChainedFixupsLoadCommand() const {
5143 // Load the dyld chained fixups load command.
5144 if (!DyldChainedFixupsLoadCmd)
5145 return std::nullopt;
5146 auto DyldChainedFixupsOrErr = getStructOrErr<MachO::linkedit_data_command>(
5147 O: *this, P: DyldChainedFixupsLoadCmd);
5148 if (!DyldChainedFixupsOrErr)
5149 return DyldChainedFixupsOrErr.takeError();
5150 const MachO::linkedit_data_command &DyldChainedFixups =
5151 *DyldChainedFixupsOrErr;
5152
5153 // If the load command is present but the data offset has been zeroed out,
5154 // as is the case for dylib stubs, return std::nullopt (no error).
5155 if (!DyldChainedFixups.dataoff)
5156 return std::nullopt;
5157 return DyldChainedFixups;
5158}
5159
5160Expected<std::optional<MachO::dyld_chained_fixups_header>>
5161MachOObjectFile::getChainedFixupsHeader() const {
5162 auto CFOrErr = getChainedFixupsLoadCommand();
5163 if (!CFOrErr)
5164 return CFOrErr.takeError();
5165 if (!CFOrErr->has_value())
5166 return std::nullopt;
5167
5168 const MachO::linkedit_data_command &DyldChainedFixups = **CFOrErr;
5169
5170 uint64_t CFHeaderOffset = DyldChainedFixups.dataoff;
5171 uint64_t CFSize = DyldChainedFixups.datasize;
5172
5173 // Load the dyld chained fixups header.
5174 const char *CFHeaderPtr = getPtr(O: *this, Offset: CFHeaderOffset);
5175 auto CFHeaderOrErr =
5176 getStructOrErr<MachO::dyld_chained_fixups_header>(O: *this, P: CFHeaderPtr);
5177 if (!CFHeaderOrErr)
5178 return CFHeaderOrErr.takeError();
5179 MachO::dyld_chained_fixups_header CFHeader = CFHeaderOrErr.get();
5180
5181 // Reject unknown chained fixup formats.
5182 if (CFHeader.fixups_version != 0)
5183 return malformedError(Msg: Twine("bad chained fixups: unknown version: ") +
5184 Twine(CFHeader.fixups_version));
5185 if (CFHeader.imports_format < 1 || CFHeader.imports_format > 3)
5186 return malformedError(
5187 Msg: Twine("bad chained fixups: unknown imports format: ") +
5188 Twine(CFHeader.imports_format));
5189
5190 // Validate the image format.
5191 //
5192 // Load the image starts.
5193 uint64_t CFImageStartsOffset = (CFHeaderOffset + CFHeader.starts_offset);
5194 if (CFHeader.starts_offset < sizeof(MachO::dyld_chained_fixups_header)) {
5195 return malformedError(Msg: Twine("bad chained fixups: image starts offset ") +
5196 Twine(CFHeader.starts_offset) +
5197 " overlaps with chained fixups header");
5198 }
5199 uint32_t EndOffset = CFHeaderOffset + CFSize;
5200 if (CFImageStartsOffset + sizeof(MachO::dyld_chained_starts_in_image) >
5201 EndOffset) {
5202 return malformedError(Msg: Twine("bad chained fixups: image starts end ") +
5203 Twine(CFImageStartsOffset +
5204 sizeof(MachO::dyld_chained_starts_in_image)) +
5205 " extends past end " + Twine(EndOffset));
5206 }
5207
5208 return CFHeader;
5209}
5210
5211Expected<std::pair<size_t, std::vector<ChainedFixupsSegment>>>
5212MachOObjectFile::getChainedFixupsSegments() const {
5213 auto CFOrErr = getChainedFixupsLoadCommand();
5214 if (!CFOrErr)
5215 return CFOrErr.takeError();
5216
5217 std::vector<ChainedFixupsSegment> Segments;
5218 if (!CFOrErr->has_value())
5219 return std::make_pair(x: 0, y&: Segments);
5220
5221 const MachO::linkedit_data_command &DyldChainedFixups = **CFOrErr;
5222
5223 auto HeaderOrErr = getChainedFixupsHeader();
5224 if (!HeaderOrErr)
5225 return HeaderOrErr.takeError();
5226 if (!HeaderOrErr->has_value())
5227 return std::make_pair(x: 0, y&: Segments);
5228 const MachO::dyld_chained_fixups_header &Header = **HeaderOrErr;
5229
5230 const char *Contents = getPtr(O: *this, Offset: DyldChainedFixups.dataoff);
5231
5232 auto ImageStartsOrErr = getStructOrErr<MachO::dyld_chained_starts_in_image>(
5233 O: *this, P: Contents + Header.starts_offset);
5234 if (!ImageStartsOrErr)
5235 return ImageStartsOrErr.takeError();
5236 const MachO::dyld_chained_starts_in_image &ImageStarts = *ImageStartsOrErr;
5237
5238 const char *SegOffsPtr =
5239 Contents + Header.starts_offset +
5240 offsetof(MachO::dyld_chained_starts_in_image, seg_info_offset);
5241 const char *SegOffsEnd =
5242 SegOffsPtr + ImageStarts.seg_count * sizeof(uint32_t);
5243 if (SegOffsEnd > Contents + DyldChainedFixups.datasize)
5244 return malformedError(
5245 Msg: "bad chained fixups: seg_info_offset extends past end");
5246
5247 const char *LastSegEnd = nullptr;
5248 for (size_t I = 0, N = ImageStarts.seg_count; I < N; ++I) {
5249 auto OffOrErr =
5250 getStructOrErr<uint32_t>(O: *this, P: SegOffsPtr + I * sizeof(uint32_t));
5251 if (!OffOrErr)
5252 return OffOrErr.takeError();
5253 // seg_info_offset == 0 means there is no associated starts_in_segment
5254 // entry.
5255 if (!*OffOrErr)
5256 continue;
5257
5258 auto Fail = [&](Twine Message) {
5259 return malformedError(Msg: "bad chained fixups: segment info" + Twine(I) +
5260 " at offset " + Twine(*OffOrErr) + Message);
5261 };
5262
5263 const char *SegPtr = Contents + Header.starts_offset + *OffOrErr;
5264 if (LastSegEnd && SegPtr < LastSegEnd)
5265 return Fail(" overlaps with previous segment info");
5266
5267 auto SegOrErr =
5268 getStructOrErr<MachO::dyld_chained_starts_in_segment>(O: *this, P: SegPtr);
5269 if (!SegOrErr)
5270 return SegOrErr.takeError();
5271 const MachO::dyld_chained_starts_in_segment &Seg = *SegOrErr;
5272
5273 LastSegEnd = SegPtr + Seg.size;
5274 if (Seg.pointer_format < 1 || Seg.pointer_format > 12)
5275 return Fail(" has unknown pointer format: " + Twine(Seg.pointer_format));
5276
5277 const char *PageStart =
5278 SegPtr + offsetof(MachO::dyld_chained_starts_in_segment, page_start);
5279 const char *PageEnd = PageStart + Seg.page_count * sizeof(uint16_t);
5280 if (PageEnd > SegPtr + Seg.size)
5281 return Fail(" : page_starts extend past seg_info size");
5282
5283 // FIXME: This does not account for multiple offsets on a single page
5284 // (DYLD_CHAINED_PTR_START_MULTI; 32-bit only).
5285 std::vector<uint16_t> PageStarts;
5286 for (size_t PageIdx = 0; PageIdx < Seg.page_count; ++PageIdx) {
5287 uint16_t Start;
5288 memcpy(dest: &Start, src: PageStart + PageIdx * sizeof(uint16_t), n: sizeof(uint16_t));
5289 if (isLittleEndian() != sys::IsLittleEndianHost)
5290 sys::swapByteOrder(Value&: Start);
5291 PageStarts.push_back(x: Start);
5292 }
5293
5294 Segments.emplace_back(args&: I, args&: *OffOrErr, args: Seg, args: std::move(PageStarts));
5295 }
5296
5297 return std::make_pair(x: ImageStarts.seg_count, y&: Segments);
5298}
5299
5300// The special library ordinals have a negative value, but they are encoded in
5301// an unsigned bitfield, so we need to sign extend the value.
5302template <typename T> static int getEncodedOrdinal(T Value) {
5303 if (Value == static_cast<T>(MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE) ||
5304 Value == static_cast<T>(MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP) ||
5305 Value == static_cast<T>(MachO::BIND_SPECIAL_DYLIB_WEAK_LOOKUP))
5306 return SignExtend32<sizeof(T) * CHAR_BIT>(Value);
5307 return Value;
5308}
5309
5310template <typename T, unsigned N>
5311static std::array<T, N> getArray(const MachOObjectFile &O, const void *Ptr) {
5312 std::array<T, N> RawValue;
5313 memcpy(RawValue.data(), Ptr, N * sizeof(T));
5314 if (O.isLittleEndian() != sys::IsLittleEndianHost)
5315 for (auto &Element : RawValue)
5316 sys::swapByteOrder(Element);
5317 return RawValue;
5318}
5319
5320Expected<std::vector<ChainedFixupTarget>>
5321MachOObjectFile::getDyldChainedFixupTargets() const {
5322 auto CFOrErr = getChainedFixupsLoadCommand();
5323 if (!CFOrErr)
5324 return CFOrErr.takeError();
5325
5326 std::vector<ChainedFixupTarget> Targets;
5327 if (!CFOrErr->has_value())
5328 return Targets;
5329
5330 const MachO::linkedit_data_command &DyldChainedFixups = **CFOrErr;
5331
5332 auto CFHeaderOrErr = getChainedFixupsHeader();
5333 if (!CFHeaderOrErr)
5334 return CFHeaderOrErr.takeError();
5335 if (!(*CFHeaderOrErr))
5336 return Targets;
5337 const MachO::dyld_chained_fixups_header &Header = **CFHeaderOrErr;
5338
5339 size_t ImportSize = 0;
5340 if (Header.imports_format == MachO::DYLD_CHAINED_IMPORT)
5341 ImportSize = sizeof(MachO::dyld_chained_import);
5342 else if (Header.imports_format == MachO::DYLD_CHAINED_IMPORT_ADDEND)
5343 ImportSize = sizeof(MachO::dyld_chained_import_addend);
5344 else if (Header.imports_format == MachO::DYLD_CHAINED_IMPORT_ADDEND64)
5345 ImportSize = sizeof(MachO::dyld_chained_import_addend64);
5346 else
5347 return malformedError(Msg: "bad chained fixups: unknown imports format: " +
5348 Twine(Header.imports_format));
5349
5350 const char *Contents = getPtr(O: *this, Offset: DyldChainedFixups.dataoff);
5351 const char *Imports = Contents + Header.imports_offset;
5352 size_t ImportsEndOffset =
5353 Header.imports_offset + ImportSize * Header.imports_count;
5354 const char *ImportsEnd = Contents + ImportsEndOffset;
5355 const char *Symbols = Contents + Header.symbols_offset;
5356 const char *SymbolsEnd = Contents + DyldChainedFixups.datasize;
5357
5358 if (ImportsEnd > Symbols)
5359 return malformedError(Msg: "bad chained fixups: imports end " +
5360 Twine(ImportsEndOffset) + " overlaps with symbols");
5361
5362 // We use bit manipulation to extract data from the bitfields. This is correct
5363 // for both LE and BE hosts, but we assume that the object is little-endian.
5364 if (!isLittleEndian())
5365 return createError(Err: "parsing big-endian chained fixups is not implemented");
5366 for (const char *ImportPtr = Imports; ImportPtr < ImportsEnd;
5367 ImportPtr += ImportSize) {
5368 int LibOrdinal;
5369 bool WeakImport;
5370 uint32_t NameOffset;
5371 uint64_t Addend;
5372 if (Header.imports_format == MachO::DYLD_CHAINED_IMPORT) {
5373 static_assert(sizeof(uint32_t) == sizeof(MachO::dyld_chained_import));
5374 auto RawValue = getArray<uint32_t, 1>(O: *this, Ptr: ImportPtr);
5375
5376 LibOrdinal = getEncodedOrdinal<uint8_t>(Value: RawValue[0] & 0xFF);
5377 WeakImport = (RawValue[0] >> 8) & 1;
5378 NameOffset = RawValue[0] >> 9;
5379 Addend = 0;
5380 } else if (Header.imports_format == MachO::DYLD_CHAINED_IMPORT_ADDEND) {
5381 static_assert(sizeof(uint64_t) ==
5382 sizeof(MachO::dyld_chained_import_addend));
5383 auto RawValue = getArray<uint32_t, 2>(O: *this, Ptr: ImportPtr);
5384
5385 LibOrdinal = getEncodedOrdinal<uint8_t>(Value: RawValue[0] & 0xFF);
5386 WeakImport = (RawValue[0] >> 8) & 1;
5387 NameOffset = RawValue[0] >> 9;
5388 Addend = bit_cast<int32_t>(from: RawValue[1]);
5389 } else if (Header.imports_format == MachO::DYLD_CHAINED_IMPORT_ADDEND64) {
5390 static_assert(2 * sizeof(uint64_t) ==
5391 sizeof(MachO::dyld_chained_import_addend64));
5392 auto RawValue = getArray<uint64_t, 2>(O: *this, Ptr: ImportPtr);
5393
5394 LibOrdinal = getEncodedOrdinal<uint16_t>(Value: RawValue[0] & 0xFFFF);
5395 NameOffset = (RawValue[0] >> 16) & 1;
5396 WeakImport = RawValue[0] >> 17;
5397 Addend = RawValue[1];
5398 } else {
5399 llvm_unreachable("Import format should have been checked");
5400 }
5401
5402 const char *Str = Symbols + NameOffset;
5403 if (Str >= SymbolsEnd)
5404 return malformedError(Msg: "bad chained fixups: symbol offset " +
5405 Twine(NameOffset) + " extends past end " +
5406 Twine(DyldChainedFixups.datasize));
5407 Targets.emplace_back(args&: LibOrdinal, args&: NameOffset, args&: Str, args&: Addend, args&: WeakImport);
5408 }
5409
5410 return std::move(Targets);
5411}
5412
5413ArrayRef<uint8_t> MachOObjectFile::getDyldExportsTrie() const {
5414 if (!DyldExportsTrieLoadCmd)
5415 return {};
5416
5417 auto DyldExportsTrieOrError = getStructOrErr<MachO::linkedit_data_command>(
5418 O: *this, P: DyldExportsTrieLoadCmd);
5419 if (!DyldExportsTrieOrError)
5420 return {};
5421 MachO::linkedit_data_command DyldExportsTrie = DyldExportsTrieOrError.get();
5422 const uint8_t *Ptr =
5423 reinterpret_cast<const uint8_t *>(getPtr(O: *this, Offset: DyldExportsTrie.dataoff));
5424 return ArrayRef(Ptr, DyldExportsTrie.datasize);
5425}
5426
5427SmallVector<uint64_t> MachOObjectFile::getFunctionStarts() const {
5428 if (!FuncStartsLoadCmd)
5429 return {};
5430
5431 auto InfoOrErr =
5432 getStructOrErr<MachO::linkedit_data_command>(O: *this, P: FuncStartsLoadCmd);
5433 if (!InfoOrErr)
5434 return {};
5435
5436 MachO::linkedit_data_command Info = InfoOrErr.get();
5437 SmallVector<uint64_t, 8> FunctionStarts;
5438 this->ReadULEB128s(Index: Info.dataoff, Out&: FunctionStarts);
5439 return std::move(FunctionStarts);
5440}
5441
5442ArrayRef<uint8_t> MachOObjectFile::getUuid() const {
5443 if (!UuidLoadCmd)
5444 return {};
5445 // Returning a pointer is fine as uuid doesn't need endian swapping.
5446 const char *Ptr = UuidLoadCmd + offsetof(MachO::uuid_command, uuid);
5447 return ArrayRef(reinterpret_cast<const uint8_t *>(Ptr), 16);
5448}
5449
5450StringRef MachOObjectFile::getStringTableData() const {
5451 MachO::symtab_command S = getSymtabLoadCommand();
5452 return getData().substr(Start: S.stroff, N: S.strsize);
5453}
5454
5455bool MachOObjectFile::is64Bit() const {
5456 return getType() == getMachOType(isLE: false, is64Bits: true) ||
5457 getType() == getMachOType(isLE: true, is64Bits: true);
5458}
5459
5460void MachOObjectFile::ReadULEB128s(uint64_t Index,
5461 SmallVectorImpl<uint64_t> &Out) const {
5462 DataExtractor extractor(ObjectFile::getData(), true);
5463
5464 uint64_t offset = Index;
5465 uint64_t data = 0;
5466 while (uint64_t delta = extractor.getULEB128(offset_ptr: &offset)) {
5467 data += delta;
5468 Out.push_back(Elt: data);
5469 }
5470}
5471
5472bool MachOObjectFile::isRelocatableObject() const {
5473 return getHeader().filetype == MachO::MH_OBJECT;
5474}
5475
5476/// Create a MachOObjectFile instance from a given buffer.
5477///
5478/// \param Buffer Memory buffer containing the MachO binary data.
5479/// \param UniversalCputype CPU type when the MachO part of a universal binary.
5480/// \param UniversalIndex Index of the MachO within a universal binary.
5481/// \param MachOFilesetEntryOffset Offset of the MachO entry in a fileset MachO.
5482/// \returns A std::unique_ptr to a MachOObjectFile instance on success.
5483Expected<std::unique_ptr<MachOObjectFile>> ObjectFile::createMachOObjectFile(
5484 MemoryBufferRef Buffer, uint32_t UniversalCputype, uint32_t UniversalIndex,
5485 size_t MachOFilesetEntryOffset) {
5486 StringRef Magic = Buffer.getBuffer().slice(Start: 0, End: 4);
5487 if (Magic == "\xFE\xED\xFA\xCE")
5488 return MachOObjectFile::create(Object: Buffer, IsLittleEndian: false, Is64Bits: false, UniversalCputype,
5489 UniversalIndex, MachOFilesetEntryOffset);
5490 if (Magic == "\xCE\xFA\xED\xFE")
5491 return MachOObjectFile::create(Object: Buffer, IsLittleEndian: true, Is64Bits: false, UniversalCputype,
5492 UniversalIndex, MachOFilesetEntryOffset);
5493 if (Magic == "\xFE\xED\xFA\xCF")
5494 return MachOObjectFile::create(Object: Buffer, IsLittleEndian: false, Is64Bits: true, UniversalCputype,
5495 UniversalIndex, MachOFilesetEntryOffset);
5496 if (Magic == "\xCF\xFA\xED\xFE")
5497 return MachOObjectFile::create(Object: Buffer, IsLittleEndian: true, Is64Bits: true, UniversalCputype,
5498 UniversalIndex, MachOFilesetEntryOffset);
5499 return make_error<GenericBinaryError>(Args: "Unrecognized MachO magic number",
5500 Args: object_error::invalid_file_type);
5501}
5502
5503StringRef MachOObjectFile::mapDebugSectionName(StringRef Name) const {
5504 return StringSwitch<StringRef>(Name)
5505 .Case(S: "debug_str_offs", Value: "debug_str_offsets")
5506 .Default(Value: Name);
5507}
5508
5509Expected<std::vector<std::string>>
5510MachOObjectFile::findDsymObjectMembers(StringRef Path) {
5511 SmallString<256> BundlePath(Path);
5512 // Normalize input path. This is necessary to accept `bundle.dSYM/`.
5513 sys::path::remove_dots(path&: BundlePath);
5514 if (!sys::fs::is_directory(Path: BundlePath) ||
5515 sys::path::extension(path: BundlePath) != ".dSYM")
5516 return std::vector<std::string>();
5517 sys::path::append(path&: BundlePath, a: "Contents", b: "Resources", c: "DWARF");
5518 bool IsDir;
5519 auto EC = sys::fs::is_directory(path: BundlePath, result&: IsDir);
5520 if (EC == errc::no_such_file_or_directory || (!EC && !IsDir))
5521 return createStringError(
5522 EC, Fmt: "%s: expected directory 'Contents/Resources/DWARF' in dSYM bundle",
5523 Vals: Path.str().c_str());
5524 if (EC)
5525 return createFileError(F: BundlePath, E: errorCodeToError(EC));
5526
5527 std::vector<std::string> ObjectPaths;
5528 for (sys::fs::directory_iterator Dir(BundlePath, EC), DirEnd;
5529 Dir != DirEnd && !EC; Dir.increment(ec&: EC)) {
5530 StringRef ObjectPath = Dir->path();
5531 sys::fs::file_status Status;
5532 if (auto EC = sys::fs::status(path: ObjectPath, result&: Status))
5533 return createFileError(F: ObjectPath, E: errorCodeToError(EC));
5534 switch (Status.type()) {
5535 case sys::fs::file_type::regular_file:
5536 case sys::fs::file_type::symlink_file:
5537 case sys::fs::file_type::type_unknown:
5538 ObjectPaths.push_back(x: ObjectPath.str());
5539 break;
5540 default: /*ignore*/;
5541 }
5542 }
5543 if (EC)
5544 return createFileError(F: BundlePath, E: errorCodeToError(EC));
5545 if (ObjectPaths.empty())
5546 return createStringError(EC: std::error_code(),
5547 Fmt: "%s: no objects found in dSYM bundle",
5548 Vals: Path.str().c_str());
5549 return ObjectPaths;
5550}
5551
5552llvm::binaryformat::Swift5ReflectionSectionKind
5553MachOObjectFile::mapReflectionSectionNameToEnumValue(
5554 StringRef SectionName) const {
5555#define HANDLE_SWIFT_SECTION(KIND, MACHO, ELF, COFF) \
5556 .Case(MACHO, llvm::binaryformat::Swift5ReflectionSectionKind::KIND)
5557 return StringSwitch<llvm::binaryformat::Swift5ReflectionSectionKind>(
5558 SectionName)
5559#include "llvm/BinaryFormat/Swift.def"
5560 .Default(Value: llvm::binaryformat::Swift5ReflectionSectionKind::unknown);
5561#undef HANDLE_SWIFT_SECTION
5562}
5563
5564bool MachOObjectFile::isMachOPairedReloc(uint64_t RelocType, uint64_t Arch) {
5565 switch (Arch) {
5566 case Triple::x86:
5567 return RelocType == MachO::GENERIC_RELOC_SECTDIFF ||
5568 RelocType == MachO::GENERIC_RELOC_LOCAL_SECTDIFF;
5569 case Triple::x86_64:
5570 return RelocType == MachO::X86_64_RELOC_SUBTRACTOR;
5571 case Triple::arm:
5572 case Triple::thumb:
5573 return RelocType == MachO::ARM_RELOC_SECTDIFF ||
5574 RelocType == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
5575 RelocType == MachO::ARM_RELOC_HALF ||
5576 RelocType == MachO::ARM_RELOC_HALF_SECTDIFF;
5577 case Triple::aarch64:
5578 return RelocType == MachO::ARM64_RELOC_SUBTRACTOR;
5579 default:
5580 return false;
5581 }
5582}
5583