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