LLVM 24.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.
248 uint64_t Offset;
249 uint64_t Size;
250 const char *Name;
251};
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
886static Error
889 uint32_t LoadCommandIndex) {
890 // Check the command size is big enough for the command struct.
891 if (Load.C.cmdsize < sizeof(MachO::target_triple_command))
892 return malformedError("load command " + Twine(LoadCommandIndex) +
893 " LC_TARGET_TRIPLE cmdsize too small");
894
895 auto TTOrErr = getStructOrErr<MachO::target_triple_command>(Obj, Load.Ptr);
896 if (!TTOrErr)
897 return TTOrErr.takeError();
898 MachO::target_triple_command TT = TTOrErr.get();
899
900 // Check the triple offset is after the command struct.
901 if (TT.triple < sizeof(MachO::target_triple_command))
902 return malformedError(
903 "load command " + Twine(LoadCommandIndex) +
904 " LC_TARGET_TRIPLE triple.offset field too small, not past the end of "
905 "the target_triple_command struct");
906
907 // Check the triple offset is before the end of the command.
908 if (TT.triple >= TT.cmdsize)
909 return malformedError("load command " + Twine(LoadCommandIndex) +
910 " LC_TARGET_TRIPLE triple.offset field extends past "
911 "the end of the load command");
912
913 // Check there is a NUL between the starting offset of the triple and the end
914 // of the command.
915 uint32_t i;
916 const char *P = (const char *)Load.Ptr;
917 for (i = TT.triple; i < TT.cmdsize; i++)
918 if (P[i] == '\0')
919 break;
920 if (i >= TT.cmdsize)
921 return malformedError("load command " + Twine(LoadCommandIndex) +
922 " LC_TARGET_TRIPLE triple name extends past the end "
923 "of the load command");
924
925 return Error::success();
926}
927
930 uint32_t LoadCommandIndex) {
931 if (Load.C.cmdsize < sizeof(MachO::rpath_command))
932 return malformedError("load command " + Twine(LoadCommandIndex) +
933 " LC_RPATH cmdsize too small");
934 auto ROrErr = getStructOrErr<MachO::rpath_command>(Obj, Load.Ptr);
935 if (!ROrErr)
936 return ROrErr.takeError();
937 MachO::rpath_command R = ROrErr.get();
938 if (R.path < sizeof(MachO::rpath_command))
939 return malformedError("load command " + Twine(LoadCommandIndex) +
940 " LC_RPATH path.offset field too small, not past "
941 "the end of the rpath_command struct");
942 if (R.path >= R.cmdsize)
943 return malformedError("load command " + Twine(LoadCommandIndex) +
944 " LC_RPATH path.offset field extends past the end "
945 "of the load command");
946 // Make sure there is a null between the starting offset of the path and
947 // the end of the load command.
948 uint32_t i;
949 const char *P = (const char *)Load.Ptr;
950 for (i = R.path; i < R.cmdsize; i++)
951 if (P[i] == '\0')
952 break;
953 if (i >= R.cmdsize)
954 return malformedError("load command " + Twine(LoadCommandIndex) +
955 " LC_RPATH library name extends past the end of the "
956 "load command");
957 return Error::success();
958}
959
962 uint32_t LoadCommandIndex,
963 uint64_t cryptoff, uint64_t cryptsize,
964 const char **LoadCmd, const char *CmdName) {
965 if (*LoadCmd != nullptr)
966 return malformedError("more than one LC_ENCRYPTION_INFO and or "
967 "LC_ENCRYPTION_INFO_64 command");
968 uint64_t FileSize = Obj.getData().size();
969 if (cryptoff > FileSize)
970 return malformedError("cryptoff field of " + Twine(CmdName) +
971 " command " + Twine(LoadCommandIndex) + " extends "
972 "past the end of the file");
973 uint64_t BigSize = cryptoff;
974 BigSize += cryptsize;
975 if (BigSize > FileSize)
976 return malformedError("cryptoff field plus cryptsize field of " +
977 Twine(CmdName) + " command " +
978 Twine(LoadCommandIndex) + " extends past the end of "
979 "the file");
980 *LoadCmd = Load.Ptr;
981 return Error::success();
982}
983
986 uint32_t LoadCommandIndex) {
987 if (Load.C.cmdsize < sizeof(MachO::linker_option_command))
988 return malformedError("load command " + Twine(LoadCommandIndex) +
989 " LC_LINKER_OPTION cmdsize too small");
990 auto LinkOptionOrErr =
992 if (!LinkOptionOrErr)
993 return LinkOptionOrErr.takeError();
994 MachO::linker_option_command L = LinkOptionOrErr.get();
995 // Make sure the count of strings is correct.
996 const char *string = (const char *)Load.Ptr +
997 sizeof(struct MachO::linker_option_command);
998 uint32_t left = L.cmdsize - sizeof(struct MachO::linker_option_command);
999 uint32_t i = 0;
1000 while (left > 0) {
1001 while (*string == '\0' && left > 0) {
1002 string++;
1003 left--;
1004 }
1005 if (left > 0) {
1006 i++;
1007 uint32_t NullPos = StringRef(string, left).find('\0');
1008 if (0xffffffff == NullPos)
1009 return malformedError("load command " + Twine(LoadCommandIndex) +
1010 " LC_LINKER_OPTION string #" + Twine(i) +
1011 " is not NULL terminated");
1012 uint32_t len = std::min(NullPos, left) + 1;
1013 string += len;
1014 left -= len;
1015 }
1016 }
1017 if (L.count != i)
1018 return malformedError("load command " + Twine(LoadCommandIndex) +
1019 " LC_LINKER_OPTION string count " + Twine(L.count) +
1020 " does not match number of strings");
1021 return Error::success();
1022}
1023
1026 uint32_t LoadCommandIndex, const char *CmdName,
1027 size_t SizeOfCmd, const char *CmdStructName,
1028 uint32_t PathOffset, const char *PathFieldName) {
1029 if (PathOffset < SizeOfCmd)
1030 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
1031 CmdName + " " + PathFieldName + ".offset field too "
1032 "small, not past the end of the " + CmdStructName);
1033 if (PathOffset >= Load.C.cmdsize)
1034 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
1035 CmdName + " " + PathFieldName + ".offset field "
1036 "extends past the end of the load command");
1037 // Make sure there is a null between the starting offset of the path and
1038 // the end of the load command.
1039 uint32_t i;
1040 const char *P = (const char *)Load.Ptr;
1041 for (i = PathOffset; i < Load.C.cmdsize; i++)
1042 if (P[i] == '\0')
1043 break;
1044 if (i >= Load.C.cmdsize)
1045 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
1046 CmdName + " " + PathFieldName + " name extends past "
1047 "the end of the load command");
1048 return Error::success();
1049}
1050
1053 uint32_t LoadCommandIndex,
1054 const char *CmdName) {
1055 if (Load.C.cmdsize < sizeof(MachO::thread_command))
1056 return malformedError("load command " + Twine(LoadCommandIndex) +
1057 CmdName + " cmdsize too small");
1058 auto ThreadCommandOrErr =
1060 if (!ThreadCommandOrErr)
1061 return ThreadCommandOrErr.takeError();
1062 MachO::thread_command T = ThreadCommandOrErr.get();
1063 const char *state = Load.Ptr + sizeof(MachO::thread_command);
1064 const char *end = Load.Ptr + T.cmdsize;
1065 uint32_t nflavor = 0;
1066 uint32_t cputype = getCPUType(Obj);
1067 while (state < end) {
1068 if(state + sizeof(uint32_t) > end)
1069 return malformedError("load command " + Twine(LoadCommandIndex) +
1070 "flavor in " + CmdName + " extends past end of "
1071 "command");
1072 uint32_t flavor;
1073 memcpy(&flavor, state, sizeof(uint32_t));
1074 if (Obj.isLittleEndian() != sys::IsLittleEndianHost)
1075 sys::swapByteOrder(flavor);
1076 state += sizeof(uint32_t);
1077
1078 if(state + sizeof(uint32_t) > end)
1079 return malformedError("load command " + Twine(LoadCommandIndex) +
1080 " count in " + CmdName + " extends past end of "
1081 "command");
1083 memcpy(&count, state, sizeof(uint32_t));
1084 if (Obj.isLittleEndian() != sys::IsLittleEndianHost)
1086 state += sizeof(uint32_t);
1087
1088 if (cputype == MachO::CPU_TYPE_I386) {
1089 if (flavor == MachO::x86_THREAD_STATE32) {
1091 return malformedError("load command " + Twine(LoadCommandIndex) +
1092 " count not x86_THREAD_STATE32_COUNT for "
1093 "flavor number " + Twine(nflavor) + " which is "
1094 "a x86_THREAD_STATE32 flavor in " + CmdName +
1095 " command");
1096 if (state + sizeof(MachO::x86_thread_state32_t) > end)
1097 return malformedError("load command " + Twine(LoadCommandIndex) +
1098 " x86_THREAD_STATE32 extends past end of "
1099 "command in " + CmdName + " command");
1100 state += sizeof(MachO::x86_thread_state32_t);
1101 } else {
1102 return malformedError("load command " + Twine(LoadCommandIndex) +
1103 " unknown flavor (" + Twine(flavor) + ") for "
1104 "flavor number " + Twine(nflavor) + " in " +
1105 CmdName + " command");
1106 }
1107 } else if (cputype == MachO::CPU_TYPE_X86_64) {
1108 if (flavor == MachO::x86_THREAD_STATE) {
1110 return malformedError("load command " + Twine(LoadCommandIndex) +
1111 " count not x86_THREAD_STATE_COUNT for "
1112 "flavor number " + Twine(nflavor) + " which is "
1113 "a x86_THREAD_STATE flavor in " + CmdName +
1114 " command");
1115 if (state + sizeof(MachO::x86_thread_state_t) > end)
1116 return malformedError("load command " + Twine(LoadCommandIndex) +
1117 " x86_THREAD_STATE extends past end of "
1118 "command in " + CmdName + " command");
1119 state += sizeof(MachO::x86_thread_state_t);
1120 } else if (flavor == MachO::x86_FLOAT_STATE) {
1122 return malformedError("load command " + Twine(LoadCommandIndex) +
1123 " count not x86_FLOAT_STATE_COUNT for "
1124 "flavor number " + Twine(nflavor) + " which is "
1125 "a x86_FLOAT_STATE flavor in " + CmdName +
1126 " command");
1127 if (state + sizeof(MachO::x86_float_state_t) > end)
1128 return malformedError("load command " + Twine(LoadCommandIndex) +
1129 " x86_FLOAT_STATE extends past end of "
1130 "command in " + CmdName + " command");
1131 state += sizeof(MachO::x86_float_state_t);
1132 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
1134 return malformedError("load command " + Twine(LoadCommandIndex) +
1135 " count not x86_EXCEPTION_STATE_COUNT for "
1136 "flavor number " + Twine(nflavor) + " which is "
1137 "a x86_EXCEPTION_STATE flavor in " + CmdName +
1138 " command");
1139 if (state + sizeof(MachO::x86_exception_state_t) > end)
1140 return malformedError("load command " + Twine(LoadCommandIndex) +
1141 " x86_EXCEPTION_STATE extends past end of "
1142 "command in " + CmdName + " command");
1143 state += sizeof(MachO::x86_exception_state_t);
1144 } else if (flavor == MachO::x86_THREAD_STATE64) {
1146 return malformedError("load command " + Twine(LoadCommandIndex) +
1147 " count not x86_THREAD_STATE64_COUNT for "
1148 "flavor number " + Twine(nflavor) + " which is "
1149 "a x86_THREAD_STATE64 flavor in " + CmdName +
1150 " command");
1151 if (state + sizeof(MachO::x86_thread_state64_t) > end)
1152 return malformedError("load command " + Twine(LoadCommandIndex) +
1153 " x86_THREAD_STATE64 extends past end of "
1154 "command in " + CmdName + " command");
1155 state += sizeof(MachO::x86_thread_state64_t);
1156 } else if (flavor == MachO::x86_EXCEPTION_STATE64) {
1158 return malformedError("load command " + Twine(LoadCommandIndex) +
1159 " count not x86_EXCEPTION_STATE64_COUNT for "
1160 "flavor number " + Twine(nflavor) + " which is "
1161 "a x86_EXCEPTION_STATE64 flavor in " + CmdName +
1162 " command");
1163 if (state + sizeof(MachO::x86_exception_state64_t) > end)
1164 return malformedError("load command " + Twine(LoadCommandIndex) +
1165 " x86_EXCEPTION_STATE64 extends past end of "
1166 "command in " + CmdName + " command");
1167 state += sizeof(MachO::x86_exception_state64_t);
1168 } else {
1169 return malformedError("load command " + Twine(LoadCommandIndex) +
1170 " unknown flavor (" + Twine(flavor) + ") for "
1171 "flavor number " + Twine(nflavor) + " in " +
1172 CmdName + " command");
1173 }
1174 } else if (cputype == MachO::CPU_TYPE_ARM) {
1175 if (flavor == MachO::ARM_THREAD_STATE) {
1177 return malformedError("load command " + Twine(LoadCommandIndex) +
1178 " count not ARM_THREAD_STATE_COUNT for "
1179 "flavor number " + Twine(nflavor) + " which is "
1180 "a ARM_THREAD_STATE flavor in " + CmdName +
1181 " command");
1182 if (state + sizeof(MachO::arm_thread_state32_t) > end)
1183 return malformedError("load command " + Twine(LoadCommandIndex) +
1184 " ARM_THREAD_STATE extends past end of "
1185 "command in " + CmdName + " command");
1186 state += sizeof(MachO::arm_thread_state32_t);
1187 } else {
1188 return malformedError("load command " + Twine(LoadCommandIndex) +
1189 " unknown flavor (" + Twine(flavor) + ") for "
1190 "flavor number " + Twine(nflavor) + " in " +
1191 CmdName + " command");
1192 }
1193 } else if (cputype == MachO::CPU_TYPE_ARM64 ||
1194 cputype == MachO::CPU_TYPE_ARM64_32) {
1195 if (flavor == MachO::ARM_THREAD_STATE64) {
1197 return malformedError("load command " + Twine(LoadCommandIndex) +
1198 " count not ARM_THREAD_STATE64_COUNT for "
1199 "flavor number " + Twine(nflavor) + " which is "
1200 "a ARM_THREAD_STATE64 flavor in " + CmdName +
1201 " command");
1202 if (state + sizeof(MachO::arm_thread_state64_t) > end)
1203 return malformedError("load command " + Twine(LoadCommandIndex) +
1204 " ARM_THREAD_STATE64 extends past end of "
1205 "command in " + CmdName + " command");
1206 state += sizeof(MachO::arm_thread_state64_t);
1207 } else {
1208 return malformedError("load command " + Twine(LoadCommandIndex) +
1209 " unknown flavor (" + Twine(flavor) + ") for "
1210 "flavor number " + Twine(nflavor) + " in " +
1211 CmdName + " command");
1212 }
1213 } else if (cputype == MachO::CPU_TYPE_POWERPC) {
1214 if (flavor == MachO::PPC_THREAD_STATE) {
1216 return malformedError("load command " + Twine(LoadCommandIndex) +
1217 " count not PPC_THREAD_STATE_COUNT for "
1218 "flavor number " + Twine(nflavor) + " which is "
1219 "a PPC_THREAD_STATE flavor in " + CmdName +
1220 " command");
1221 if (state + sizeof(MachO::ppc_thread_state32_t) > end)
1222 return malformedError("load command " + Twine(LoadCommandIndex) +
1223 " PPC_THREAD_STATE extends past end of "
1224 "command in " + CmdName + " command");
1225 state += sizeof(MachO::ppc_thread_state32_t);
1226 } else {
1227 return malformedError("load command " + Twine(LoadCommandIndex) +
1228 " unknown flavor (" + Twine(flavor) + ") for "
1229 "flavor number " + Twine(nflavor) + " in " +
1230 CmdName + " command");
1231 }
1232 } else {
1233 return malformedError("unknown cputype (" + Twine(cputype) + ") load "
1234 "command " + Twine(LoadCommandIndex) + " for " +
1235 CmdName + " command can't be checked");
1236 }
1237 nflavor++;
1238 }
1239 return Error::success();
1240}
1241
1244 &Load,
1245 uint32_t LoadCommandIndex,
1246 const char **LoadCmd,
1247 std::list<MachOElement> &Elements) {
1248 if (Load.C.cmdsize != sizeof(MachO::twolevel_hints_command))
1249 return malformedError("load command " + Twine(LoadCommandIndex) +
1250 " LC_TWOLEVEL_HINTS has incorrect cmdsize");
1251 if (*LoadCmd != nullptr)
1252 return malformedError("more than one LC_TWOLEVEL_HINTS command");
1253 auto HintsOrErr = getStructOrErr<MachO::twolevel_hints_command>(Obj, Load.Ptr);
1254 if(!HintsOrErr)
1255 return HintsOrErr.takeError();
1256 MachO::twolevel_hints_command Hints = HintsOrErr.get();
1257 uint64_t FileSize = Obj.getData().size();
1258 if (Hints.offset > FileSize)
1259 return malformedError("offset field of LC_TWOLEVEL_HINTS command " +
1260 Twine(LoadCommandIndex) + " extends past the end of "
1261 "the file");
1262 uint64_t BigSize = Hints.nhints;
1263 BigSize *= sizeof(MachO::twolevel_hint);
1264 BigSize += Hints.offset;
1265 if (BigSize > FileSize)
1266 return malformedError("offset field plus nhints times sizeof(struct "
1267 "twolevel_hint) field of LC_TWOLEVEL_HINTS command " +
1268 Twine(LoadCommandIndex) + " extends past the end of "
1269 "the file");
1270 if (Error Err = checkOverlappingElement(Elements, Hints.offset, Hints.nhints *
1271 sizeof(MachO::twolevel_hint),
1272 "two level hints"))
1273 return Err;
1274 *LoadCmd = Load.Ptr;
1275 return Error::success();
1276}
1277
1278// Returns true if the libObject code does not support the load command and its
1279// contents. The cmd value it is treated as an unknown load command but with
1280// an error message that says the cmd value is obsolete.
1282 if (cmd == MachO::LC_SYMSEG ||
1283 cmd == MachO::LC_LOADFVMLIB ||
1284 cmd == MachO::LC_IDFVMLIB ||
1285 cmd == MachO::LC_IDENT ||
1286 cmd == MachO::LC_FVMFILE ||
1287 cmd == MachO::LC_PREPAGE ||
1288 cmd == MachO::LC_PREBOUND_DYLIB ||
1289 cmd == MachO::LC_TWOLEVEL_HINTS ||
1290 cmd == MachO::LC_PREBIND_CKSUM)
1291 return true;
1292 return false;
1293}
1294
1296MachOObjectFile::create(MemoryBufferRef Object, bool IsLittleEndian,
1297 bool Is64Bits, uint32_t UniversalCputype,
1298 uint32_t UniversalIndex,
1299 size_t MachOFilesetEntryOffset) {
1300 Error Err = Error::success();
1301 std::unique_ptr<MachOObjectFile> Obj(new MachOObjectFile(
1302 std::move(Object), IsLittleEndian, Is64Bits, Err, UniversalCputype,
1303 UniversalIndex, MachOFilesetEntryOffset));
1304 if (Err)
1305 return std::move(Err);
1306 return std::move(Obj);
1307}
1308
1309MachOObjectFile::MachOObjectFile(MemoryBufferRef Object, bool IsLittleEndian,
1310 bool Is64bits, Error &Err,
1311 uint32_t UniversalCputype,
1312 uint32_t UniversalIndex,
1313 size_t MachOFilesetEntryOffset)
1314 : ObjectFile(getMachOType(IsLittleEndian, Is64bits), Object),
1315 MachOFilesetEntryOffset(MachOFilesetEntryOffset) {
1316 ErrorAsOutParameter ErrAsOutParam(Err);
1317 uint64_t SizeOfHeaders;
1318 uint32_t cputype;
1319 if (is64Bit()) {
1320 parseHeader(*this, Header64, Err);
1321 SizeOfHeaders = sizeof(MachO::mach_header_64);
1322 cputype = Header64.cputype;
1323 } else {
1324 parseHeader(*this, Header, Err);
1325 SizeOfHeaders = sizeof(MachO::mach_header);
1326 cputype = Header.cputype;
1327 }
1328 if (Err)
1329 return;
1330 SizeOfHeaders += getHeader().sizeofcmds;
1331 if (getData().data() + SizeOfHeaders > getData().end()) {
1332 Err = malformedError("load commands extend past the end of the file");
1333 return;
1334 }
1335 if (UniversalCputype != 0 && cputype != UniversalCputype) {
1336 Err = malformedError("universal header architecture: " +
1337 Twine(UniversalIndex) + "'s cputype does not match "
1338 "object file's mach header");
1339 return;
1340 }
1341 std::list<MachOElement> Elements;
1342 Elements.push_back({0, SizeOfHeaders, "Mach-O headers"});
1343
1344 uint32_t LoadCommandCount = getHeader().ncmds;
1346 if (LoadCommandCount != 0) {
1347 if (auto LoadOrErr = getFirstLoadCommandInfo(*this))
1348 Load = *LoadOrErr;
1349 else {
1350 Err = LoadOrErr.takeError();
1351 return;
1352 }
1353 }
1354
1355 const char *DyldIdLoadCmd = nullptr;
1356 const char *SplitInfoLoadCmd = nullptr;
1357 const char *CodeSignDrsLoadCmd = nullptr;
1358 const char *CodeSignLoadCmd = nullptr;
1359 const char *VersLoadCmd = nullptr;
1360 const char *SourceLoadCmd = nullptr;
1361 const char *EntryPointLoadCmd = nullptr;
1362 const char *EncryptLoadCmd = nullptr;
1363 const char *RoutinesLoadCmd = nullptr;
1364 const char *UnixThreadLoadCmd = nullptr;
1365 const char *TwoLevelHintsLoadCmd = nullptr;
1366 for (unsigned I = 0; I < LoadCommandCount; ++I) {
1367 if (is64Bit()) {
1368 if (Load.C.cmdsize % 8 != 0) {
1369 // We have a hack here to allow 64-bit Mach-O core files to have
1370 // LC_THREAD commands that are only a multiple of 4 and not 8 to be
1371 // allowed since the macOS kernel produces them.
1372 if (getHeader().filetype != MachO::MH_CORE ||
1373 Load.C.cmd != MachO::LC_THREAD || Load.C.cmdsize % 4) {
1374 Err = malformedError("load command " + Twine(I) + " cmdsize not a "
1375 "multiple of 8");
1376 return;
1377 }
1378 }
1379 } else {
1380 if (Load.C.cmdsize % 4 != 0) {
1381 Err = malformedError("load command " + Twine(I) + " cmdsize not a "
1382 "multiple of 4");
1383 return;
1384 }
1385 }
1386 LoadCommands.push_back(Load);
1387 if (Load.C.cmd == MachO::LC_SYMTAB) {
1388 if ((Err = checkSymtabCommand(*this, Load, I, &SymtabLoadCmd, Elements)))
1389 return;
1390 } else if (Load.C.cmd == MachO::LC_DYSYMTAB) {
1391 if ((Err = checkDysymtabCommand(*this, Load, I, &DysymtabLoadCmd,
1392 Elements)))
1393 return;
1394 } else if (Load.C.cmd == MachO::LC_DATA_IN_CODE) {
1395 if ((Err = checkLinkeditDataCommand(*this, Load, I, &DataInCodeLoadCmd,
1396 "LC_DATA_IN_CODE", Elements,
1397 "data in code info")))
1398 return;
1399 } else if (Load.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
1400 if ((Err = checkLinkeditDataCommand(*this, Load, I, &LinkOptHintsLoadCmd,
1401 "LC_LINKER_OPTIMIZATION_HINT",
1402 Elements, "linker optimization "
1403 "hints")))
1404 return;
1405 } else if (Load.C.cmd == MachO::LC_FUNCTION_STARTS) {
1406 if ((Err = checkLinkeditDataCommand(*this, Load, I, &FuncStartsLoadCmd,
1407 "LC_FUNCTION_STARTS", Elements,
1408 "function starts data")))
1409 return;
1410 } else if (Load.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO) {
1411 if ((Err = checkLinkeditDataCommand(*this, Load, I, &SplitInfoLoadCmd,
1412 "LC_SEGMENT_SPLIT_INFO", Elements,
1413 "split info data")))
1414 return;
1415 } else if (Load.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS) {
1416 if ((Err = checkLinkeditDataCommand(*this, Load, I, &CodeSignDrsLoadCmd,
1417 "LC_DYLIB_CODE_SIGN_DRS", Elements,
1418 "code signing RDs data")))
1419 return;
1420 } else if (Load.C.cmd == MachO::LC_CODE_SIGNATURE) {
1421 if ((Err = checkLinkeditDataCommand(*this, Load, I, &CodeSignLoadCmd,
1422 "LC_CODE_SIGNATURE", Elements,
1423 "code signature data")))
1424 return;
1425 } else if (Load.C.cmd == MachO::LC_DYLD_INFO) {
1426 if ((Err = checkDyldInfoCommand(*this, Load, I, &DyldInfoLoadCmd,
1427 "LC_DYLD_INFO", Elements)))
1428 return;
1429 } else if (Load.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
1430 if ((Err = checkDyldInfoCommand(*this, Load, I, &DyldInfoLoadCmd,
1431 "LC_DYLD_INFO_ONLY", Elements)))
1432 return;
1433 } else if (Load.C.cmd == MachO::LC_DYLD_CHAINED_FIXUPS) {
1434 if ((Err = checkLinkeditDataCommand(
1435 *this, Load, I, &DyldChainedFixupsLoadCmd,
1436 "LC_DYLD_CHAINED_FIXUPS", Elements, "chained fixups")))
1437 return;
1438 } else if (Load.C.cmd == MachO::LC_DYLD_EXPORTS_TRIE) {
1439 if ((Err = checkLinkeditDataCommand(
1440 *this, Load, I, &DyldExportsTrieLoadCmd, "LC_DYLD_EXPORTS_TRIE",
1441 Elements, "exports trie")))
1442 return;
1443 } else if (Load.C.cmd == MachO::LC_UUID) {
1444 if (Load.C.cmdsize != sizeof(MachO::uuid_command)) {
1445 Err = malformedError("LC_UUID command " + Twine(I) + " has incorrect "
1446 "cmdsize");
1447 return;
1448 }
1449 if (UuidLoadCmd) {
1450 Err = malformedError("more than one LC_UUID command");
1451 return;
1452 }
1453 UuidLoadCmd = Load.Ptr;
1454 } else if (Load.C.cmd == MachO::LC_SEGMENT_64) {
1455 if ((Err = parseSegmentLoadCommand<MachO::segment_command_64,
1456 MachO::section_64>(
1457 *this, Load, Sections, HasPageZeroSegment, I,
1458 "LC_SEGMENT_64", SizeOfHeaders, Elements)))
1459 return;
1460 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
1461 if ((Err = parseSegmentLoadCommand<MachO::segment_command,
1462 MachO::section>(
1463 *this, Load, Sections, HasPageZeroSegment, I,
1464 "LC_SEGMENT", SizeOfHeaders, Elements)))
1465 return;
1466 } else if (Load.C.cmd == MachO::LC_ID_DYLIB) {
1467 if ((Err = checkDylibIdCommand(*this, Load, I, &DyldIdLoadCmd)))
1468 return;
1469 } else if (Load.C.cmd == MachO::LC_LOAD_DYLIB) {
1470 if ((Err = checkDylibCommand(*this, Load, I, "LC_LOAD_DYLIB")))
1471 return;
1472 Libraries.push_back(Load.Ptr);
1473 } else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB) {
1474 if ((Err = checkDylibCommand(*this, Load, I, "LC_LOAD_WEAK_DYLIB")))
1475 return;
1476 Libraries.push_back(Load.Ptr);
1477 } else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB) {
1478 if ((Err = checkDylibCommand(*this, Load, I, "LC_LAZY_LOAD_DYLIB")))
1479 return;
1480 Libraries.push_back(Load.Ptr);
1481 } else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB) {
1482 if ((Err = checkDylibCommand(*this, Load, I, "LC_REEXPORT_DYLIB")))
1483 return;
1484 Libraries.push_back(Load.Ptr);
1485 } else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
1486 if ((Err = checkDylibCommand(*this, Load, I, "LC_LOAD_UPWARD_DYLIB")))
1487 return;
1488 Libraries.push_back(Load.Ptr);
1489 } else if (Load.C.cmd == MachO::LC_ID_DYLINKER) {
1490 if ((Err = checkDyldCommand(*this, Load, I, "LC_ID_DYLINKER")))
1491 return;
1492 } else if (Load.C.cmd == MachO::LC_LOAD_DYLINKER) {
1493 if ((Err = checkDyldCommand(*this, Load, I, "LC_LOAD_DYLINKER")))
1494 return;
1495 } else if (Load.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
1496 if ((Err = checkDyldCommand(*this, Load, I, "LC_DYLD_ENVIRONMENT")))
1497 return;
1498 } else if (Load.C.cmd == MachO::LC_VERSION_MIN_MACOSX) {
1499 if ((Err = checkVersCommand(*this, Load, I, &VersLoadCmd,
1500 "LC_VERSION_MIN_MACOSX")))
1501 return;
1502 } else if (Load.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS) {
1503 if ((Err = checkVersCommand(*this, Load, I, &VersLoadCmd,
1504 "LC_VERSION_MIN_IPHONEOS")))
1505 return;
1506 } else if (Load.C.cmd == MachO::LC_VERSION_MIN_TVOS) {
1507 if ((Err = checkVersCommand(*this, Load, I, &VersLoadCmd,
1508 "LC_VERSION_MIN_TVOS")))
1509 return;
1510 } else if (Load.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
1511 if ((Err = checkVersCommand(*this, Load, I, &VersLoadCmd,
1512 "LC_VERSION_MIN_WATCHOS")))
1513 return;
1514 } else if (Load.C.cmd == MachO::LC_NOTE) {
1515 if ((Err = checkNoteCommand(*this, Load, I, Elements)))
1516 return;
1517 } else if (Load.C.cmd == MachO::LC_BUILD_VERSION) {
1518 if ((Err = parseBuildVersionCommand(*this, Load, BuildTools, I)))
1519 return;
1520 } else if (Load.C.cmd == MachO::LC_TARGET_TRIPLE) {
1521 if ((Err = checkTargetTripleCommand(*this, Load, I)))
1522 return;
1523 } else if (Load.C.cmd == MachO::LC_RPATH) {
1524 if ((Err = checkRpathCommand(*this, Load, I)))
1525 return;
1526 } else if (Load.C.cmd == MachO::LC_SOURCE_VERSION) {
1527 if (Load.C.cmdsize != sizeof(MachO::source_version_command)) {
1528 Err = malformedError("LC_SOURCE_VERSION command " + Twine(I) +
1529 " has incorrect cmdsize");
1530 return;
1531 }
1532 if (SourceLoadCmd) {
1533 Err = malformedError("more than one LC_SOURCE_VERSION command");
1534 return;
1535 }
1536 SourceLoadCmd = Load.Ptr;
1537 } else if (Load.C.cmd == MachO::LC_MAIN) {
1538 if (Load.C.cmdsize != sizeof(MachO::entry_point_command)) {
1539 Err = malformedError("LC_MAIN command " + Twine(I) +
1540 " has incorrect cmdsize");
1541 return;
1542 }
1543 if (EntryPointLoadCmd) {
1544 Err = malformedError("more than one LC_MAIN command");
1545 return;
1546 }
1547 EntryPointLoadCmd = Load.Ptr;
1548 } else if (Load.C.cmd == MachO::LC_ENCRYPTION_INFO) {
1549 if (Load.C.cmdsize != sizeof(MachO::encryption_info_command)) {
1550 Err = malformedError("LC_ENCRYPTION_INFO command " + Twine(I) +
1551 " has incorrect cmdsize");
1552 return;
1553 }
1554 MachO::encryption_info_command E =
1556 if ((Err = checkEncryptCommand(*this, Load, I, E.cryptoff, E.cryptsize,
1557 &EncryptLoadCmd, "LC_ENCRYPTION_INFO")))
1558 return;
1559 } else if (Load.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
1560 if (Load.C.cmdsize != sizeof(MachO::encryption_info_command_64)) {
1561 Err = malformedError("LC_ENCRYPTION_INFO_64 command " + Twine(I) +
1562 " has incorrect cmdsize");
1563 return;
1564 }
1565 MachO::encryption_info_command_64 E =
1567 if ((Err = checkEncryptCommand(*this, Load, I, E.cryptoff, E.cryptsize,
1568 &EncryptLoadCmd, "LC_ENCRYPTION_INFO_64")))
1569 return;
1570 } else if (Load.C.cmd == MachO::LC_LINKER_OPTION) {
1571 if ((Err = checkLinkerOptCommand(*this, Load, I)))
1572 return;
1573 } else if (Load.C.cmd == MachO::LC_SUB_FRAMEWORK) {
1574 if (Load.C.cmdsize < sizeof(MachO::sub_framework_command)) {
1575 Err = malformedError("load command " + Twine(I) +
1576 " LC_SUB_FRAMEWORK cmdsize too small");
1577 return;
1578 }
1579 MachO::sub_framework_command S =
1581 if ((Err = checkSubCommand(*this, Load, I, "LC_SUB_FRAMEWORK",
1582 sizeof(MachO::sub_framework_command),
1583 "sub_framework_command", S.umbrella,
1584 "umbrella")))
1585 return;
1586 } else if (Load.C.cmd == MachO::LC_SUB_UMBRELLA) {
1587 if (Load.C.cmdsize < sizeof(MachO::sub_umbrella_command)) {
1588 Err = malformedError("load command " + Twine(I) +
1589 " LC_SUB_UMBRELLA cmdsize too small");
1590 return;
1591 }
1592 MachO::sub_umbrella_command S =
1594 if ((Err = checkSubCommand(*this, Load, I, "LC_SUB_UMBRELLA",
1595 sizeof(MachO::sub_umbrella_command),
1596 "sub_umbrella_command", S.sub_umbrella,
1597 "sub_umbrella")))
1598 return;
1599 } else if (Load.C.cmd == MachO::LC_SUB_LIBRARY) {
1600 if (Load.C.cmdsize < sizeof(MachO::sub_library_command)) {
1601 Err = malformedError("load command " + Twine(I) +
1602 " LC_SUB_LIBRARY cmdsize too small");
1603 return;
1604 }
1605 MachO::sub_library_command S =
1607 if ((Err = checkSubCommand(*this, Load, I, "LC_SUB_LIBRARY",
1608 sizeof(MachO::sub_library_command),
1609 "sub_library_command", S.sub_library,
1610 "sub_library")))
1611 return;
1612 } else if (Load.C.cmd == MachO::LC_SUB_CLIENT) {
1613 if (Load.C.cmdsize < sizeof(MachO::sub_client_command)) {
1614 Err = malformedError("load command " + Twine(I) +
1615 " LC_SUB_CLIENT cmdsize too small");
1616 return;
1617 }
1618 MachO::sub_client_command S =
1620 if ((Err = checkSubCommand(*this, Load, I, "LC_SUB_CLIENT",
1621 sizeof(MachO::sub_client_command),
1622 "sub_client_command", S.client, "client")))
1623 return;
1624 } else if (Load.C.cmd == MachO::LC_ROUTINES) {
1625 if (Load.C.cmdsize != sizeof(MachO::routines_command)) {
1626 Err = malformedError("LC_ROUTINES command " + Twine(I) +
1627 " has incorrect cmdsize");
1628 return;
1629 }
1630 if (RoutinesLoadCmd) {
1631 Err = malformedError("more than one LC_ROUTINES and or LC_ROUTINES_64 "
1632 "command");
1633 return;
1634 }
1635 RoutinesLoadCmd = Load.Ptr;
1636 } else if (Load.C.cmd == MachO::LC_ROUTINES_64) {
1637 if (Load.C.cmdsize != sizeof(MachO::routines_command_64)) {
1638 Err = malformedError("LC_ROUTINES_64 command " + Twine(I) +
1639 " has incorrect cmdsize");
1640 return;
1641 }
1642 if (RoutinesLoadCmd) {
1643 Err = malformedError("more than one LC_ROUTINES_64 and or LC_ROUTINES "
1644 "command");
1645 return;
1646 }
1647 RoutinesLoadCmd = Load.Ptr;
1648 } else if (Load.C.cmd == MachO::LC_UNIXTHREAD) {
1649 if ((Err = checkThreadCommand(*this, Load, I, "LC_UNIXTHREAD")))
1650 return;
1651 if (UnixThreadLoadCmd) {
1652 Err = malformedError("more than one LC_UNIXTHREAD command");
1653 return;
1654 }
1655 UnixThreadLoadCmd = Load.Ptr;
1656 } else if (Load.C.cmd == MachO::LC_THREAD) {
1657 if ((Err = checkThreadCommand(*this, Load, I, "LC_THREAD")))
1658 return;
1659 // Note: LC_TWOLEVEL_HINTS is really obsolete and is not supported.
1660 } else if (Load.C.cmd == MachO::LC_TWOLEVEL_HINTS) {
1661 if ((Err = checkTwoLevelHintsCommand(*this, Load, I,
1662 &TwoLevelHintsLoadCmd, Elements)))
1663 return;
1664 } else if (Load.C.cmd == MachO::LC_IDENT) {
1665 // Note: LC_IDENT is ignored.
1666 continue;
1667 } else if (isLoadCommandObsolete(Load.C.cmd)) {
1668 Err = malformedError("load command " + Twine(I) + " for cmd value of: " +
1669 Twine(Load.C.cmd) + " is obsolete and not "
1670 "supported");
1671 return;
1672 }
1673 // TODO: generate a error for unknown load commands by default. But still
1674 // need work out an approach to allow or not allow unknown values like this
1675 // as an option for some uses like lldb.
1676 if (I < LoadCommandCount - 1) {
1677 if (auto LoadOrErr = getNextLoadCommandInfo(*this, I, Load))
1678 Load = *LoadOrErr;
1679 else {
1680 Err = LoadOrErr.takeError();
1681 return;
1682 }
1683 }
1684 }
1685 if (!SymtabLoadCmd) {
1686 if (DysymtabLoadCmd) {
1687 Err = malformedError("contains LC_DYSYMTAB load command without a "
1688 "LC_SYMTAB load command");
1689 return;
1690 }
1691 } else if (DysymtabLoadCmd) {
1692 MachO::symtab_command Symtab =
1693 getStruct<MachO::symtab_command>(*this, SymtabLoadCmd);
1694 MachO::dysymtab_command Dysymtab =
1695 getStruct<MachO::dysymtab_command>(*this, DysymtabLoadCmd);
1696 if (Dysymtab.nlocalsym != 0 && Dysymtab.ilocalsym > Symtab.nsyms) {
1697 Err = malformedError("ilocalsym in LC_DYSYMTAB load command "
1698 "extends past the end of the symbol table");
1699 return;
1700 }
1701 uint64_t BigSize = Dysymtab.ilocalsym;
1702 BigSize += Dysymtab.nlocalsym;
1703 if (Dysymtab.nlocalsym != 0 && BigSize > Symtab.nsyms) {
1704 Err = malformedError("ilocalsym plus nlocalsym in LC_DYSYMTAB load "
1705 "command extends past the end of the symbol table");
1706 return;
1707 }
1708 if (Dysymtab.nextdefsym != 0 && Dysymtab.iextdefsym > Symtab.nsyms) {
1709 Err = malformedError("iextdefsym in LC_DYSYMTAB load command "
1710 "extends past the end of the symbol table");
1711 return;
1712 }
1713 BigSize = Dysymtab.iextdefsym;
1714 BigSize += Dysymtab.nextdefsym;
1715 if (Dysymtab.nextdefsym != 0 && BigSize > Symtab.nsyms) {
1716 Err = malformedError("iextdefsym plus nextdefsym in LC_DYSYMTAB "
1717 "load command extends past the end of the symbol "
1718 "table");
1719 return;
1720 }
1721 if (Dysymtab.nundefsym != 0 && Dysymtab.iundefsym > Symtab.nsyms) {
1722 Err = malformedError("iundefsym in LC_DYSYMTAB load command "
1723 "extends past the end of the symbol table");
1724 return;
1725 }
1726 BigSize = Dysymtab.iundefsym;
1727 BigSize += Dysymtab.nundefsym;
1728 if (Dysymtab.nundefsym != 0 && BigSize > Symtab.nsyms) {
1729 Err = malformedError("iundefsym plus nundefsym in LC_DYSYMTAB load "
1730 " command extends past the end of the symbol table");
1731 return;
1732 }
1733 }
1734 if ((getHeader().filetype == MachO::MH_DYLIB ||
1735 getHeader().filetype == MachO::MH_DYLIB_STUB) &&
1736 DyldIdLoadCmd == nullptr) {
1737 Err = malformedError("no LC_ID_DYLIB load command in dynamic library "
1738 "filetype");
1739 return;
1740 }
1741 assert(LoadCommands.size() == LoadCommandCount);
1742
1743 Err = Error::success();
1744}
1745
1747 uint32_t Flags = 0;
1748 if (is64Bit()) {
1750 Flags = H_64.flags;
1751 } else {
1753 Flags = H.flags;
1754 }
1755 uint8_t NType = 0;
1756 uint8_t NSect = 0;
1757 uint16_t NDesc = 0;
1758 uint32_t NStrx = 0;
1759 uint64_t NValue = 0;
1760 uint32_t SymbolIndex = 0;
1762 for (const SymbolRef &Symbol : symbols()) {
1763 DataRefImpl SymDRI = Symbol.getRawDataRefImpl();
1764 if (is64Bit()) {
1765 MachO::nlist_64 STE_64 = getSymbol64TableEntry(SymDRI);
1766 NType = STE_64.n_type;
1767 NSect = STE_64.n_sect;
1768 NDesc = STE_64.n_desc;
1769 NStrx = STE_64.n_strx;
1770 NValue = STE_64.n_value;
1771 } else {
1772 MachO::nlist STE = getSymbolTableEntry(SymDRI);
1773 NType = STE.n_type;
1774 NSect = STE.n_sect;
1775 NDesc = STE.n_desc;
1776 NStrx = STE.n_strx;
1777 NValue = STE.n_value;
1778 }
1779 if ((NType & MachO::N_STAB) == 0) {
1780 if ((NType & MachO::N_TYPE) == MachO::N_SECT) {
1781 if (NSect == 0 || NSect > Sections.size())
1782 return malformedError("bad section index: " + Twine((int)NSect) +
1783 " for symbol at index " + Twine(SymbolIndex));
1784 }
1785 if ((NType & MachO::N_TYPE) == MachO::N_INDR) {
1786 if (NValue >= S.strsize)
1787 return malformedError("bad n_value: " + Twine((int)NValue) + " past "
1788 "the end of string table, for N_INDR symbol at "
1789 "index " + Twine(SymbolIndex));
1790 }
1791 if ((Flags & MachO::MH_TWOLEVEL) == MachO::MH_TWOLEVEL &&
1792 (((NType & MachO::N_TYPE) == MachO::N_UNDF && NValue == 0) ||
1793 (NType & MachO::N_TYPE) == MachO::N_PBUD)) {
1794 uint32_t LibraryOrdinal = MachO::GET_LIBRARY_ORDINAL(NDesc);
1795 if (LibraryOrdinal != 0 &&
1796 LibraryOrdinal != MachO::EXECUTABLE_ORDINAL &&
1797 LibraryOrdinal != MachO::DYNAMIC_LOOKUP_ORDINAL &&
1798 LibraryOrdinal - 1 >= Libraries.size() ) {
1799 return malformedError("bad library ordinal: " + Twine(LibraryOrdinal) +
1800 " for symbol at index " + Twine(SymbolIndex));
1801 }
1802 }
1803 }
1804 if (NStrx >= S.strsize)
1805 return malformedError("bad string table index: " + Twine((int)NStrx) +
1806 " past the end of string table, for symbol at "
1807 "index " + Twine(SymbolIndex));
1808 SymbolIndex++;
1809 }
1810 return Error::success();
1811}
1812
1814 unsigned SymbolTableEntrySize = is64Bit() ?
1815 sizeof(MachO::nlist_64) :
1816 sizeof(MachO::nlist);
1817 Symb.p += SymbolTableEntrySize;
1818}
1819
1822 MachO::nlist_base Entry = getSymbolTableEntryBase(*this, Symb);
1823 if (Entry.n_strx == 0)
1824 // A n_strx value of 0 indicates that no name is associated with a
1825 // particular symbol table entry.
1826 return StringRef();
1827 const char *Start = &StringTable.data()[Entry.n_strx];
1828 if (Start < getData().begin() || Start >= getData().end()) {
1829 return malformedError("bad string index: " + Twine(Entry.n_strx) +
1830 " for symbol at index " + Twine(getSymbolIndex(Symb)));
1831 }
1832 return StringRef(Start);
1833}
1834
1836 DataRefImpl DRI = Sec.getRawDataRefImpl();
1837 uint32_t Flags = getSectionFlags(*this, DRI);
1838 return Flags & MachO::SECTION_TYPE;
1839}
1840
1842 if (is64Bit()) {
1844 return Entry.n_value;
1845 }
1846 MachO::nlist Entry = getSymbolTableEntry(Sym);
1847 return Entry.n_value;
1848}
1849
1850// getIndirectName() returns the name of the alias'ed symbol who's string table
1851// index is in the n_value field.
1853 StringRef &Res) const {
1855 MachO::nlist_base Entry = getSymbolTableEntryBase(*this, Symb);
1856 if ((Entry.n_type & MachO::N_TYPE) != MachO::N_INDR)
1858 uint64_t NValue = getNValue(Symb);
1859 if (NValue >= StringTable.size())
1861 const char *Start = &StringTable.data()[NValue];
1862 Res = StringRef(Start);
1863 return std::error_code();
1864}
1865
1866uint64_t MachOObjectFile::getSymbolValueImpl(DataRefImpl Sym) const {
1867 return getNValue(Sym);
1868}
1869
1873
1875 uint32_t Flags = cantFail(getSymbolFlags(DRI));
1876 if (Flags & SymbolRef::SF_Common) {
1877 MachO::nlist_base Entry = getSymbolTableEntryBase(*this, DRI);
1878 return 1 << MachO::GET_COMM_ALIGN(Entry.n_desc);
1879 }
1880 return 0;
1881}
1882
1884 return getNValue(DRI);
1885}
1886
1889 MachO::nlist_base Entry = getSymbolTableEntryBase(*this, Symb);
1890 uint8_t n_type = Entry.n_type;
1891
1892 // If this is a STAB debugging symbol, we can do nothing more.
1893 if (n_type & MachO::N_STAB)
1894 return SymbolRef::ST_Debug;
1895
1896 switch (n_type & MachO::N_TYPE) {
1897 case MachO::N_UNDF :
1898 return SymbolRef::ST_Unknown;
1899 case MachO::N_SECT :
1901 if (!SecOrError)
1902 return SecOrError.takeError();
1903 section_iterator Sec = *SecOrError;
1904 if (Sec == section_end())
1905 return SymbolRef::ST_Other;
1906 if (Sec->isData() || Sec->isBSS())
1907 return SymbolRef::ST_Data;
1909 }
1910 return SymbolRef::ST_Other;
1911}
1912
1914 MachO::nlist_base Entry = getSymbolTableEntryBase(*this, DRI);
1915
1916 uint8_t MachOType = Entry.n_type;
1917 uint16_t MachOFlags = Entry.n_desc;
1918
1920
1921 if ((MachOType & MachO::N_TYPE) == MachO::N_INDR)
1922 Result |= SymbolRef::SF_Indirect;
1923
1924 if (MachOType & MachO::N_STAB)
1926
1927 if (MachOType & MachO::N_EXT) {
1928 Result |= SymbolRef::SF_Global;
1929 if ((MachOType & MachO::N_TYPE) == MachO::N_UNDF) {
1930 if (getNValue(DRI))
1931 Result |= SymbolRef::SF_Common;
1932 else
1933 Result |= SymbolRef::SF_Undefined;
1934 }
1935
1936 if (MachOType & MachO::N_PEXT)
1937 Result |= SymbolRef::SF_Hidden;
1938 else
1939 Result |= SymbolRef::SF_Exported;
1940
1941 } else if (MachOType & MachO::N_PEXT)
1942 Result |= SymbolRef::SF_Hidden;
1943
1944 if (MachOFlags & (MachO::N_WEAK_REF | MachO::N_WEAK_DEF))
1945 Result |= SymbolRef::SF_Weak;
1946
1947 if (MachOFlags & (MachO::N_ARM_THUMB_DEF))
1948 Result |= SymbolRef::SF_Thumb;
1949
1950 if ((MachOType & MachO::N_TYPE) == MachO::N_ABS)
1951 Result |= SymbolRef::SF_Absolute;
1952
1953 return Result;
1954}
1955
1958 MachO::nlist_base Entry = getSymbolTableEntryBase(*this, Symb);
1959 uint8_t index = Entry.n_sect;
1960
1961 if (index == 0)
1962 return section_end();
1963 DataRefImpl DRI;
1964 DRI.d.a = index - 1;
1965 if (DRI.d.a >= Sections.size()){
1966 return malformedError("bad section index: " + Twine((int)index) +
1967 " for symbol at index " + Twine(getSymbolIndex(Symb)));
1968 }
1969 return section_iterator(SectionRef(DRI, this));
1970}
1971
1973 MachO::nlist_base Entry =
1975 return Entry.n_sect - 1;
1976}
1977
1979 Sec.d.a++;
1980}
1981
1986
1988 if (is64Bit())
1989 return getSection64(Sec).addr;
1990 return getSection(Sec).addr;
1991}
1992
1994 return Sec.d.a;
1995}
1996
1998 // In the case if a malformed Mach-O file where the section offset is past
1999 // the end of the file or some part of the section size is past the end of
2000 // the file return a size of zero or a size that covers the rest of the file
2001 // but does not extend past the end of the file.
2002 uint32_t SectOffset, SectType;
2003 uint64_t SectSize;
2004
2005 if (is64Bit()) {
2006 MachO::section_64 Sect = getSection64(Sec);
2007 SectOffset = Sect.offset;
2008 SectSize = Sect.size;
2009 SectType = Sect.flags & MachO::SECTION_TYPE;
2010 } else {
2011 MachO::section Sect = getSection(Sec);
2012 SectOffset = Sect.offset;
2013 SectSize = Sect.size;
2014 SectType = Sect.flags & MachO::SECTION_TYPE;
2015 }
2016 if (SectType == MachO::S_ZEROFILL || SectType == MachO::S_GB_ZEROFILL)
2017 return SectSize;
2018 uint64_t FileSize = getData().size();
2019 if (SectOffset > FileSize)
2020 return 0;
2021 if (FileSize - SectOffset < SectSize)
2022 return FileSize - SectOffset;
2023 return SectSize;
2024}
2025
2030
2033 uint64_t Offset;
2034 uint64_t Size;
2035
2036 if (is64Bit()) {
2037 MachO::section_64 Sect = getSection64(Sec);
2038 Offset = Sect.offset;
2039 Size = Sect.size;
2040 // Check for large mach-o files where the section contents might exceed
2041 // 4GB. MachO::section_64 objects only have 32 bit file offsets to the
2042 // section contents and can overflow in dSYM files. We can track this and
2043 // adjust the section offset to be 64 bit safe. If sections overflow then
2044 // section ordering is enforced. If sections are not ordered, then an error
2045 // will be returned stopping invalid section data from being returned.
2046 uint64_t PrevTrueOffset = 0;
2047 uint64_t SectOffsetAdjust = 0;
2048 for (uint32_t SectIdx = 0; SectIdx < Sec.d.a; ++SectIdx) {
2049 MachO::section_64 CurrSect =
2050 getStruct<MachO::section_64>(*this, Sections[SectIdx]);
2051 uint64_t CurrTrueOffset = (uint64_t)CurrSect.offset + SectOffsetAdjust;
2052 if ((SectOffsetAdjust > 0) && (PrevTrueOffset > CurrTrueOffset))
2053 return malformedError("section data exceeds 4GB and section file "
2054 "offsets are not ordered");
2055 const uint64_t EndSectFileOffset =
2056 (uint64_t)CurrSect.offset + CurrSect.size;
2057 if (EndSectFileOffset > UINT32_MAX)
2058 SectOffsetAdjust += EndSectFileOffset & 0xFFFFFFFF00000000ull;
2059 PrevTrueOffset = CurrTrueOffset;
2060 }
2061 Offset += SectOffsetAdjust;
2062 } else {
2063 MachO::section Sect = getSection(Sec);
2064 Offset = Sect.offset;
2065 Size = Sect.size;
2066 }
2067
2069}
2070
2073 if (is64Bit()) {
2074 MachO::section_64 Sect = getSection64(Sec);
2075 Align = Sect.align;
2076 } else {
2077 MachO::section Sect = getSection(Sec);
2078 Align = Sect.align;
2079 }
2080
2081 return uint64_t(1) << Align;
2082}
2083
2085 if (SectionIndex < 1 || SectionIndex > Sections.size())
2086 return malformedError("bad section index: " + Twine((int)SectionIndex));
2087
2088 DataRefImpl DRI;
2089 DRI.d.a = SectionIndex - 1;
2090 return SectionRef(DRI, this);
2091}
2092
2094 for (const SectionRef &Section : sections()) {
2095 auto NameOrErr = Section.getName();
2096 if (!NameOrErr)
2097 return NameOrErr.takeError();
2098 if (*NameOrErr == SectionName)
2099 return Section;
2100 }
2102}
2103
2105 return false;
2106}
2107
2109 uint32_t Flags = getSectionFlags(*this, Sec);
2110 return Flags & MachO::S_ATTR_PURE_INSTRUCTIONS;
2111}
2112
2114 uint32_t Flags = getSectionFlags(*this, Sec);
2115 unsigned SectionType = Flags & MachO::SECTION_TYPE;
2116 return !(Flags & MachO::S_ATTR_PURE_INSTRUCTIONS) &&
2117 !(SectionType == MachO::S_ZEROFILL ||
2118 SectionType == MachO::S_GB_ZEROFILL);
2119}
2120
2122 uint32_t Flags = getSectionFlags(*this, Sec);
2123 unsigned SectionType = Flags & MachO::SECTION_TYPE;
2124 return !(Flags & MachO::S_ATTR_PURE_INSTRUCTIONS) &&
2125 (SectionType == MachO::S_ZEROFILL ||
2126 SectionType == MachO::S_GB_ZEROFILL);
2127}
2128
2130 Expected<StringRef> SectionNameOrErr = getSectionName(Sec);
2131 if (!SectionNameOrErr) {
2132 // TODO: Report the error message properly.
2133 consumeError(SectionNameOrErr.takeError());
2134 return false;
2135 }
2136 StringRef SectionName = SectionNameOrErr.get();
2137 return SectionName.starts_with("__debug") ||
2138 SectionName.starts_with("__zdebug") ||
2139 SectionName.starts_with("__apple") || SectionName == "__gdb_index" ||
2140 SectionName == "__swift_ast";
2141}
2142
2143namespace {
2144template <typename LoadCommandType>
2145ArrayRef<uint8_t> getSegmentContents(const MachOObjectFile &Obj,
2147 StringRef SegmentName) {
2148 auto SegmentOrErr = getStructOrErr<LoadCommandType>(Obj, LoadCmd.Ptr);
2149 if (!SegmentOrErr) {
2150 consumeError(SegmentOrErr.takeError());
2151 return {};
2152 }
2153 auto &Segment = SegmentOrErr.get();
2154 if (StringRef(Segment.segname, 16).starts_with(SegmentName))
2155 return arrayRefFromStringRef(Obj.getData().slice(
2156 Segment.fileoff, Segment.fileoff + Segment.filesize));
2157 return {};
2158}
2159
2160template <typename LoadCommandType>
2161ArrayRef<uint8_t> getSegmentContents(const MachOObjectFile &Obj,
2162 MachOObjectFile::LoadCommandInfo LoadCmd) {
2163 auto SegmentOrErr = getStructOrErr<LoadCommandType>(Obj, LoadCmd.Ptr);
2164 if (!SegmentOrErr) {
2165 consumeError(SegmentOrErr.takeError());
2166 return {};
2167 }
2168 auto &Segment = SegmentOrErr.get();
2169 return arrayRefFromStringRef(
2170 Obj.getData().substr(Segment.fileoff, Segment.filesize));
2171}
2172} // namespace
2173
2174ArrayRef<uint8_t>
2176 for (auto LoadCmd : load_commands()) {
2177 ArrayRef<uint8_t> Contents;
2178 switch (LoadCmd.C.cmd) {
2179 case MachO::LC_SEGMENT:
2180 Contents = ::getSegmentContents<MachO::segment_command>(*this, LoadCmd,
2181 SegmentName);
2182 break;
2183 case MachO::LC_SEGMENT_64:
2184 Contents = ::getSegmentContents<MachO::segment_command_64>(*this, LoadCmd,
2185 SegmentName);
2186 break;
2187 default:
2188 continue;
2189 }
2190 if (!Contents.empty())
2191 return Contents;
2192 }
2193 return {};
2194}
2195
2197MachOObjectFile::getSegmentContents(size_t SegmentIndex) const {
2198 size_t Idx = 0;
2199 for (auto LoadCmd : load_commands()) {
2200 switch (LoadCmd.C.cmd) {
2201 case MachO::LC_SEGMENT:
2202 if (Idx == SegmentIndex)
2203 return ::getSegmentContents<MachO::segment_command>(*this, LoadCmd);
2204 ++Idx;
2205 break;
2206 case MachO::LC_SEGMENT_64:
2207 if (Idx == SegmentIndex)
2208 return ::getSegmentContents<MachO::segment_command_64>(*this, LoadCmd);
2209 ++Idx;
2210 break;
2211 default:
2212 continue;
2213 }
2214 }
2215 return {};
2216}
2217
2219 return Sec.getRawDataRefImpl().d.a;
2220}
2221
2223 uint32_t Flags = getSectionFlags(*this, Sec);
2224 unsigned SectionType = Flags & MachO::SECTION_TYPE;
2225 return SectionType == MachO::S_ZEROFILL ||
2226 SectionType == MachO::S_GB_ZEROFILL;
2227}
2228
2230 StringRef SegmentName = getSectionFinalSegmentName(Sec);
2231 if (Expected<StringRef> NameOrErr = getSectionName(Sec))
2232 return (SegmentName == "__LLVM" && *NameOrErr == "__bitcode");
2233 return false;
2234}
2235
2237 if (is64Bit())
2238 return getSection64(Sec).offset == 0;
2239 return getSection(Sec).offset == 0;
2240}
2241
2243 DataRefImpl Ret;
2244 Ret.d.a = Sec.d.a;
2245 Ret.d.b = 0;
2246 return relocation_iterator(RelocationRef(Ret, this));
2247}
2248
2251 uint32_t Num;
2252 if (is64Bit()) {
2253 MachO::section_64 Sect = getSection64(Sec);
2254 Num = Sect.nreloc;
2255 } else {
2256 MachO::section Sect = getSection(Sec);
2257 Num = Sect.nreloc;
2258 }
2259
2260 DataRefImpl Ret;
2261 Ret.d.a = Sec.d.a;
2262 Ret.d.b = Num;
2263 return relocation_iterator(RelocationRef(Ret, this));
2264}
2265
2267 DataRefImpl Ret;
2268 // for DYSYMTAB symbols, Ret.d.a == 0 for external relocations
2269 Ret.d.a = 0; // Would normally be a section index.
2270 Ret.d.b = 0; // Index into the external relocations
2271 return relocation_iterator(RelocationRef(Ret, this));
2272}
2273
2276 DataRefImpl Ret;
2277 // for DYSYMTAB symbols, Ret.d.a == 0 for external relocations
2278 Ret.d.a = 0; // Would normally be a section index.
2279 Ret.d.b = DysymtabLoadCmd.nextrel; // Index into the external relocations
2280 return relocation_iterator(RelocationRef(Ret, this));
2281}
2282
2284 DataRefImpl Ret;
2285 // for DYSYMTAB symbols, Ret.d.a == 1 for local relocations
2286 Ret.d.a = 1; // Would normally be a section index.
2287 Ret.d.b = 0; // Index into the local relocations
2288 return relocation_iterator(RelocationRef(Ret, this));
2289}
2290
2293 DataRefImpl Ret;
2294 // for DYSYMTAB symbols, Ret.d.a == 1 for local relocations
2295 Ret.d.a = 1; // Would normally be a section index.
2296 Ret.d.b = DysymtabLoadCmd.nlocrel; // Index into the local relocations
2297 return relocation_iterator(RelocationRef(Ret, this));
2298}
2299
2301 ++Rel.d.b;
2302}
2303
2305 assert((getHeader().filetype == MachO::MH_OBJECT ||
2306 getHeader().filetype == MachO::MH_KEXT_BUNDLE) &&
2307 "Only implemented for MH_OBJECT && MH_KEXT_BUNDLE");
2309 return getAnyRelocationAddress(RE);
2310}
2311
2315 if (isRelocationScattered(RE))
2316 return symbol_end();
2317
2318 uint32_t SymbolIdx = getPlainRelocationSymbolNum(RE);
2319 bool isExtern = getPlainRelocationExternal(RE);
2320 if (!isExtern)
2321 return symbol_end();
2322
2324 unsigned SymbolTableEntrySize = is64Bit() ?
2325 sizeof(MachO::nlist_64) :
2326 sizeof(MachO::nlist);
2327 uint64_t Offset = S.symoff + SymbolIdx * SymbolTableEntrySize;
2328 DataRefImpl Sym;
2329 Sym.p = reinterpret_cast<uintptr_t>(getPtr(*this, Offset));
2330 return symbol_iterator(SymbolRef(Sym, this));
2331}
2332
2337
2342
2344 DataRefImpl Rel, SmallVectorImpl<char> &Result) const {
2345 StringRef res;
2346 uint64_t RType = getRelocationType(Rel);
2347
2348 unsigned Arch = this->getArch();
2349
2350 switch (Arch) {
2351 case Triple::x86: {
2352 static const char *const Table[] = {
2353 "GENERIC_RELOC_VANILLA",
2354 "GENERIC_RELOC_PAIR",
2355 "GENERIC_RELOC_SECTDIFF",
2356 "GENERIC_RELOC_PB_LA_PTR",
2357 "GENERIC_RELOC_LOCAL_SECTDIFF",
2358 "GENERIC_RELOC_TLV" };
2359
2360 if (RType > 5)
2361 res = "Unknown";
2362 else
2363 res = Table[RType];
2364 break;
2365 }
2366 case Triple::x86_64: {
2367 static const char *const Table[] = {
2368 "X86_64_RELOC_UNSIGNED",
2369 "X86_64_RELOC_SIGNED",
2370 "X86_64_RELOC_BRANCH",
2371 "X86_64_RELOC_GOT_LOAD",
2372 "X86_64_RELOC_GOT",
2373 "X86_64_RELOC_SUBTRACTOR",
2374 "X86_64_RELOC_SIGNED_1",
2375 "X86_64_RELOC_SIGNED_2",
2376 "X86_64_RELOC_SIGNED_4",
2377 "X86_64_RELOC_TLV" };
2378
2379 if (RType > 9)
2380 res = "Unknown";
2381 else
2382 res = Table[RType];
2383 break;
2384 }
2385 case Triple::arm: {
2386 static const char *const Table[] = {
2387 "ARM_RELOC_VANILLA",
2388 "ARM_RELOC_PAIR",
2389 "ARM_RELOC_SECTDIFF",
2390 "ARM_RELOC_LOCAL_SECTDIFF",
2391 "ARM_RELOC_PB_LA_PTR",
2392 "ARM_RELOC_BR24",
2393 "ARM_THUMB_RELOC_BR22",
2394 "ARM_THUMB_32BIT_BRANCH",
2395 "ARM_RELOC_HALF",
2396 "ARM_RELOC_HALF_SECTDIFF" };
2397
2398 if (RType > 9)
2399 res = "Unknown";
2400 else
2401 res = Table[RType];
2402 break;
2403 }
2404 case Triple::aarch64:
2405 case Triple::aarch64_32: {
2406 static const char *const Table[] = {
2407 "ARM64_RELOC_UNSIGNED", "ARM64_RELOC_SUBTRACTOR",
2408 "ARM64_RELOC_BRANCH26", "ARM64_RELOC_PAGE21",
2409 "ARM64_RELOC_PAGEOFF12", "ARM64_RELOC_GOT_LOAD_PAGE21",
2410 "ARM64_RELOC_GOT_LOAD_PAGEOFF12", "ARM64_RELOC_POINTER_TO_GOT",
2411 "ARM64_RELOC_TLVP_LOAD_PAGE21", "ARM64_RELOC_TLVP_LOAD_PAGEOFF12",
2412 "ARM64_RELOC_ADDEND", "ARM64_RELOC_AUTHENTICATED_POINTER"
2413 };
2414
2415 if (RType >= std::size(Table))
2416 res = "Unknown";
2417 else
2418 res = Table[RType];
2419 break;
2420 }
2421 case Triple::ppc: {
2422 static const char *const Table[] = {
2423 "PPC_RELOC_VANILLA",
2424 "PPC_RELOC_PAIR",
2425 "PPC_RELOC_BR14",
2426 "PPC_RELOC_BR24",
2427 "PPC_RELOC_HI16",
2428 "PPC_RELOC_LO16",
2429 "PPC_RELOC_HA16",
2430 "PPC_RELOC_LO14",
2431 "PPC_RELOC_SECTDIFF",
2432 "PPC_RELOC_PB_LA_PTR",
2433 "PPC_RELOC_HI16_SECTDIFF",
2434 "PPC_RELOC_LO16_SECTDIFF",
2435 "PPC_RELOC_HA16_SECTDIFF",
2436 "PPC_RELOC_JBSR",
2437 "PPC_RELOC_LO14_SECTDIFF",
2438 "PPC_RELOC_LOCAL_SECTDIFF" };
2439
2440 if (RType > 15)
2441 res = "Unknown";
2442 else
2443 res = Table[RType];
2444 break;
2445 }
2446 case Triple::riscv32: {
2447 static const char *const Table[] = {
2448 "RISCV_RELOC_UNSIGNED", "RISCV_RELOC_SUBTRACTOR",
2449 "RISCV_RELOC_BRANCH21", "RISCV_RELOC_HI20",
2450 "RISCV_RELOC_LO12", "RISCV_RELOC_GOT_HI20",
2451 "RISCV_RELOC_GOT_LO12", "RISCV_RELOC_POINTER_TO_GOT",
2452 "RISCV_RELOC_ADDEND",
2453 };
2454
2455 if (RType >= std::size(Table))
2456 res = "Unknown";
2457 else
2458 res = Table[RType];
2459 Result.append(res.begin(), res.end());
2460 if ((RType == MachO::RISCV_RELOC_HI20 ||
2461 RType == MachO::RISCV_RELOC_GOT_HI20 ||
2462 RType == MachO::RISCV_RELOC_LO12 ||
2463 RType == MachO::RISCV_RELOC_GOT_LO12) &&
2465 StringRef PCRel("(pcrel)");
2466 Result.append(PCRel.begin(), PCRel.end());
2467 }
2468 return;
2469 }
2471 res = "Unknown";
2472 break;
2473 }
2474 Result.append(res.begin(), res.end());
2475}
2476
2481
2482//
2483// guessLibraryShortName() is passed a name of a dynamic library and returns a
2484// guess on what the short name is. Then name is returned as a substring of the
2485// StringRef Name passed in. The name of the dynamic library is recognized as
2486// a framework if it has one of the two following forms:
2487// Foo.framework/Versions/A/Foo
2488// Foo.framework/Foo
2489// Where A and Foo can be any string. And may contain a trailing suffix
2490// starting with an underbar. If the Name is recognized as a framework then
2491// isFramework is set to true else it is set to false. If the Name has a
2492// suffix then Suffix is set to the substring in Name that contains the suffix
2493// else it is set to a NULL StringRef.
2494//
2495// The Name of the dynamic library is recognized as a library name if it has
2496// one of the two following forms:
2497// libFoo.A.dylib
2498// libFoo.dylib
2499//
2500// The library may have a suffix trailing the name Foo of the form:
2501// libFoo_profile.A.dylib
2502// libFoo_profile.dylib
2503// These dyld image suffixes are separated from the short name by a '_'
2504// character. Because the '_' character is commonly used to separate words in
2505// filenames guessLibraryShortName() cannot reliably separate a dylib's short
2506// name from an arbitrary image suffix; imagine if both the short name and the
2507// suffix contains an '_' character! To better deal with this ambiguity,
2508// guessLibraryShortName() will recognize only "_debug" and "_profile" as valid
2509// Suffix values. Calling code needs to be tolerant of guessLibraryShortName()
2510// guessing incorrectly.
2511//
2512// The Name of the dynamic library is also recognized as a library name if it
2513// has the following form:
2514// Foo.qtx
2515//
2516// If the Name of the dynamic library is none of the forms above then a NULL
2517// StringRef is returned.
2519 bool &isFramework,
2520 StringRef &Suffix) {
2521 StringRef Foo, F, DotFramework, V, Dylib, Lib, Dot, Qtx;
2522 size_t a, b, c, d, Idx;
2523
2524 isFramework = false;
2525 Suffix = StringRef();
2526
2527 // Pull off the last component and make Foo point to it
2528 a = Name.rfind('/');
2529 if (a == Name.npos || a == 0)
2530 goto guess_library;
2531 Foo = Name.substr(a + 1);
2532
2533 // Look for a suffix starting with a '_'
2534 Idx = Foo.rfind('_');
2535 if (Idx != Foo.npos && Foo.size() >= 2) {
2536 Suffix = Foo.substr(Idx);
2537 if (Suffix != "_debug" && Suffix != "_profile")
2538 Suffix = StringRef();
2539 else
2540 Foo = Foo.slice(0, Idx);
2541 }
2542
2543 // First look for the form Foo.framework/Foo
2544 b = Name.rfind('/', a);
2545 if (b == Name.npos)
2546 Idx = 0;
2547 else
2548 Idx = b+1;
2549 F = Name.substr(Idx, Foo.size());
2550 DotFramework = Name.substr(Idx + Foo.size(), sizeof(".framework/") - 1);
2551 if (F == Foo && DotFramework == ".framework/") {
2552 isFramework = true;
2553 return Foo;
2554 }
2555
2556 // Next look for the form Foo.framework/Versions/A/Foo
2557 if (b == Name.npos)
2558 goto guess_library;
2559 c = Name.rfind('/', b);
2560 if (c == Name.npos || c == 0)
2561 goto guess_library;
2562 V = Name.substr(c + 1);
2563 if (!V.starts_with("Versions/"))
2564 goto guess_library;
2565 d = Name.rfind('/', c);
2566 if (d == Name.npos)
2567 Idx = 0;
2568 else
2569 Idx = d+1;
2570 F = Name.substr(Idx, Foo.size());
2571 DotFramework = Name.substr(Idx + Foo.size(), sizeof(".framework/") - 1);
2572 if (F == Foo && DotFramework == ".framework/") {
2573 isFramework = true;
2574 return Foo;
2575 }
2576
2577guess_library:
2578 // pull off the suffix after the "." and make a point to it
2579 a = Name.rfind('.');
2580 if (a == Name.npos || a == 0)
2581 return StringRef();
2582 Dylib = Name.substr(a);
2583 if (Dylib != ".dylib")
2584 goto guess_qtx;
2585
2586 // First pull off the version letter for the form Foo.A.dylib if any.
2587 if (a >= 3) {
2588 Dot = Name.substr(a - 2, 1);
2589 if (Dot == ".")
2590 a = a - 2;
2591 }
2592
2593 b = Name.rfind('/', a);
2594 if (b == Name.npos)
2595 b = 0;
2596 else
2597 b = b+1;
2598 // ignore any suffix after an underbar like Foo_profile.A.dylib
2599 Idx = Name.rfind('_');
2600 if (Idx != Name.npos && Idx != b) {
2601 Lib = Name.slice(b, Idx);
2602 Suffix = Name.slice(Idx, a);
2603 if (Suffix != "_debug" && Suffix != "_profile") {
2604 Suffix = StringRef();
2605 Lib = Name.slice(b, a);
2606 }
2607 }
2608 else
2609 Lib = Name.slice(b, a);
2610 // There are incorrect library names of the form:
2611 // libATS.A_profile.dylib so check for these.
2612 if (Lib.size() >= 3) {
2613 Dot = Lib.substr(Lib.size() - 2, 1);
2614 if (Dot == ".")
2615 Lib = Lib.slice(0, Lib.size()-2);
2616 }
2617 return Lib;
2618
2619guess_qtx:
2620 Qtx = Name.substr(a);
2621 if (Qtx != ".qtx")
2622 return StringRef();
2623 b = Name.rfind('/', a);
2624 if (b == Name.npos)
2625 Lib = Name.slice(0, a);
2626 else
2627 Lib = Name.slice(b+1, a);
2628 // There are library names of the form: QT.A.qtx so check for these.
2629 if (Lib.size() >= 3) {
2630 Dot = Lib.substr(Lib.size() - 2, 1);
2631 if (Dot == ".")
2632 Lib = Lib.slice(0, Lib.size()-2);
2633 }
2634 return Lib;
2635}
2636
2637// getLibraryShortNameByIndex() is used to get the short name of the library
2638// for an undefined symbol in a linked Mach-O binary that was linked with the
2639// normal two-level namespace default (that is MH_TWOLEVEL in the header).
2640// It is passed the index (0 - based) of the library as translated from
2641// GET_LIBRARY_ORDINAL (1 - based).
2642std::error_code MachOObjectFile::getLibraryShortNameByIndex(unsigned Index,
2643 StringRef &Res) const {
2644 if (Index >= Libraries.size())
2646
2647 // If the cache of LibrariesShortNames is not built up do that first for
2648 // all the Libraries.
2649 if (LibrariesShortNames.size() == 0) {
2650 for (unsigned i = 0; i < Libraries.size(); i++) {
2651 auto CommandOrErr =
2652 getStructOrErr<MachO::dylib_command>(*this, Libraries[i]);
2653 if (!CommandOrErr)
2655 MachO::dylib_command D = CommandOrErr.get();
2656 if (D.dylib.name >= D.cmdsize)
2658 const char *P = (const char *)(Libraries[i]) + D.dylib.name;
2659 StringRef Name = StringRef(P);
2660 if (D.dylib.name+Name.size() >= D.cmdsize)
2662 StringRef Suffix;
2663 bool isFramework;
2664 StringRef shortName = guessLibraryShortName(Name, isFramework, Suffix);
2665 if (shortName.empty())
2666 LibrariesShortNames.push_back(Name);
2667 else
2668 LibrariesShortNames.push_back(shortName);
2669 }
2670 }
2671
2672 Res = LibrariesShortNames[Index];
2673 return std::error_code();
2674}
2675
2677 return Libraries.size();
2678}
2679
2686
2688 DataRefImpl DRI;
2690 if (!SymtabLoadCmd || Symtab.nsyms == 0)
2691 return basic_symbol_iterator(SymbolRef(DRI, this));
2692
2693 return getSymbolByIndex(0);
2694}
2695
2697 DataRefImpl DRI;
2699 if (!SymtabLoadCmd || Symtab.nsyms == 0)
2700 return basic_symbol_iterator(SymbolRef(DRI, this));
2701
2702 unsigned SymbolTableEntrySize = is64Bit() ?
2703 sizeof(MachO::nlist_64) :
2704 sizeof(MachO::nlist);
2705 unsigned Offset = Symtab.symoff +
2706 Symtab.nsyms * SymbolTableEntrySize;
2707 DRI.p = reinterpret_cast<uintptr_t>(getPtr(*this, Offset));
2708 return basic_symbol_iterator(SymbolRef(DRI, this));
2709}
2710
2713 if (!SymtabLoadCmd || Index >= Symtab.nsyms)
2714 report_fatal_error("Requested symbol index is out of range.");
2715 unsigned SymbolTableEntrySize =
2716 is64Bit() ? sizeof(MachO::nlist_64) : sizeof(MachO::nlist);
2717 DataRefImpl DRI;
2718 DRI.p = reinterpret_cast<uintptr_t>(getPtr(*this, Symtab.symoff));
2719 DRI.p += Index * SymbolTableEntrySize;
2720 return basic_symbol_iterator(SymbolRef(DRI, this));
2721}
2722
2725 if (!SymtabLoadCmd)
2726 report_fatal_error("getSymbolIndex() called with no symbol table symbol");
2727 unsigned SymbolTableEntrySize =
2728 is64Bit() ? sizeof(MachO::nlist_64) : sizeof(MachO::nlist);
2729 DataRefImpl DRIstart;
2730 DRIstart.p = reinterpret_cast<uintptr_t>(getPtr(*this, Symtab.symoff));
2731 uint64_t Index = (Symb.p - DRIstart.p) / SymbolTableEntrySize;
2732 return Index;
2733}
2734
2739
2741 DataRefImpl DRI;
2742 DRI.d.a = Sections.size();
2743 return section_iterator(SectionRef(DRI, this));
2744}
2745
2747 return is64Bit() ? 8 : 4;
2748}
2749
2751 unsigned CPUType = getCPUType(*this);
2752 if (!is64Bit()) {
2753 switch (CPUType) {
2755 return "Mach-O 32-bit i386";
2757 return "Mach-O arm";
2759 return "Mach-O arm64 (ILP32)";
2761 return "Mach-O 32-bit ppc";
2763 return "Mach-O 32-bit RISC-V";
2764 default:
2765 return "Mach-O 32-bit unknown";
2766 }
2767 }
2768
2769 switch (CPUType) {
2771 return "Mach-O 64-bit x86-64";
2773 return "Mach-O arm64";
2775 return "Mach-O 64-bit ppc64";
2776 default:
2777 return "Mach-O 64-bit unknown";
2778 }
2779}
2780
2782 switch (CPUType) {
2784 return Triple::x86;
2786 return Triple::x86_64;
2788 return Triple::arm;
2790 return Triple::aarch64;
2792 return Triple::aarch64_32;
2794 return Triple::ppc;
2796 return Triple::ppc64;
2798 return Triple::riscv32;
2799 default:
2800 return Triple::UnknownArch;
2801 }
2802}
2803
2805 const char **McpuDefault,
2806 const char **ArchFlag) {
2807 if (McpuDefault)
2808 *McpuDefault = nullptr;
2809 if (ArchFlag)
2810 *ArchFlag = nullptr;
2811
2812 switch (CPUType) {
2814 switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2816 if (ArchFlag)
2817 *ArchFlag = "i386";
2818 return Triple("i386-apple-darwin");
2819 default:
2820 return Triple();
2821 }
2823 switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2825 if (ArchFlag)
2826 *ArchFlag = "x86_64";
2827 return Triple("x86_64-apple-darwin");
2829 if (ArchFlag)
2830 *ArchFlag = "x86_64h";
2831 return Triple("x86_64h-apple-darwin");
2832 default:
2833 return Triple();
2834 }
2836 switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2838 if (ArchFlag)
2839 *ArchFlag = "armv4t";
2840 return Triple("armv4t-apple-darwin");
2842 if (ArchFlag)
2843 *ArchFlag = "armv5e";
2844 return Triple("armv5e-apple-darwin");
2846 if (ArchFlag)
2847 *ArchFlag = "xscale";
2848 return Triple("xscale-apple-darwin");
2850 if (ArchFlag)
2851 *ArchFlag = "armv6";
2852 return Triple("armv6-apple-darwin");
2854 if (McpuDefault)
2855 *McpuDefault = "cortex-m0";
2856 if (ArchFlag)
2857 *ArchFlag = "armv6m";
2858 return Triple("armv6m-apple-darwin");
2860 if (ArchFlag)
2861 *ArchFlag = "armv7";
2862 return Triple("armv7-apple-darwin");
2864 if (McpuDefault)
2865 *McpuDefault = "cortex-m4";
2866 if (ArchFlag)
2867 *ArchFlag = "armv7em";
2868 return Triple("thumbv7em-apple-darwin");
2870 if (McpuDefault)
2871 *McpuDefault = "cortex-a7";
2872 if (ArchFlag)
2873 *ArchFlag = "armv7k";
2874 return Triple("armv7k-apple-darwin");
2876 if (McpuDefault)
2877 *McpuDefault = "cortex-m3";
2878 if (ArchFlag)
2879 *ArchFlag = "armv7m";
2880 return Triple("thumbv7m-apple-darwin");
2882 if (McpuDefault)
2883 *McpuDefault = "cortex-a7";
2884 if (ArchFlag)
2885 *ArchFlag = "armv7s";
2886 return Triple("armv7s-apple-darwin");
2888 if (McpuDefault)
2889 *McpuDefault = "cortex-m23";
2890 if (ArchFlag)
2891 *ArchFlag = "armv8m.base";
2892 return Triple("thumbv8m-apple-darwin");
2894 if (McpuDefault)
2895 *McpuDefault = "cortex-m33";
2896 if (ArchFlag)
2897 *ArchFlag = "armv8m.main";
2898 return Triple("thumbv8m-apple-darwin");
2900 if (McpuDefault)
2901 *McpuDefault = "cortex-m52";
2902 if (ArchFlag)
2903 *ArchFlag = "armv8.1m.main";
2904 return Triple("thumbv8m-apple-darwin");
2905 default:
2906 return Triple();
2907 }
2909 switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2911 if (McpuDefault)
2912 *McpuDefault = "cyclone";
2913 if (ArchFlag)
2914 *ArchFlag = "arm64";
2915 return Triple("arm64-apple-darwin");
2917 if (McpuDefault)
2918 *McpuDefault = "apple-a12";
2919 if (ArchFlag)
2920 *ArchFlag = "arm64e";
2921 return Triple("arm64e-apple-darwin");
2923 if (McpuDefault)
2924 *McpuDefault = "apple-a20";
2925 if (ArchFlag)
2926 *ArchFlag = "arm64e.x1";
2927 return Triple("arm64e.x1-apple-darwin");
2928 default:
2929 return Triple();
2930 }
2932 switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2934 if (McpuDefault)
2935 *McpuDefault = "cyclone";
2936 if (ArchFlag)
2937 *ArchFlag = "arm64_32";
2938 return Triple("arm64_32-apple-darwin");
2939 default:
2940 return Triple();
2941 }
2943 switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2945 if (ArchFlag)
2946 *ArchFlag = "ppc";
2947 return Triple("ppc-apple-darwin");
2948 default:
2949 return Triple();
2950 }
2952 switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2954 if (ArchFlag)
2955 *ArchFlag = "ppc64";
2956 return Triple("ppc64-apple-darwin");
2957 default:
2958 return Triple();
2959 }
2961 switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2963 if (ArchFlag)
2964 *ArchFlag = "riscv32";
2965 return Triple("riscv32-apple-macho");
2966 default:
2967 return Triple();
2968 }
2969 default:
2970 return Triple();
2971 }
2972}
2973
2977
2979 auto validArchs = getValidArchs();
2980 return llvm::is_contained(validArchs, ArchFlag);
2981}
2982
2984 static const std::array<StringRef, 21> ValidArchs = {{
2985 "i386", "x86_64", "x86_64h", "armv4t", "arm",
2986 "armv5e", "armv6", "armv6m", "armv7", "armv7em",
2987 "armv7k", "armv7m", "armv7s", "armv8m.base", "armv8m.main",
2988 "armv8.1m.main", "arm64", "arm64e", "arm64_32", "ppc",
2989 "ppc64",
2990 }};
2991
2992 return ValidArchs;
2993}
2994
2996 return getArch(getCPUType(*this), getCPUSubType(*this));
2997}
2998
2999Triple MachOObjectFile::getArchTriple(const char **McpuDefault) const {
3000 return getArchTriple(Header.cputype, Header.cpusubtype, McpuDefault);
3001}
3002
3004 DataRefImpl DRI;
3005 DRI.d.a = Index;
3006 return section_rel_begin(DRI);
3007}
3008
3010 DataRefImpl DRI;
3011 DRI.d.a = Index;
3012 return section_rel_end(DRI);
3013}
3014
3016 DataRefImpl DRI;
3017 if (!DataInCodeLoadCmd)
3018 return dice_iterator(DiceRef(DRI, this));
3019
3021 DRI.p = reinterpret_cast<uintptr_t>(getPtr(*this, DicLC.dataoff));
3022 return dice_iterator(DiceRef(DRI, this));
3023}
3024
3026 DataRefImpl DRI;
3027 if (!DataInCodeLoadCmd)
3028 return dice_iterator(DiceRef(DRI, this));
3029
3031 unsigned Offset = DicLC.dataoff + DicLC.datasize;
3032 DRI.p = reinterpret_cast<uintptr_t>(getPtr(*this, Offset));
3033 return dice_iterator(DiceRef(DRI, this));
3034}
3035
3037 ArrayRef<uint8_t> T) : E(E), O(O), Trie(T) {}
3038
3039void ExportEntry::moveToFirst() {
3040 ErrorAsOutParameter ErrAsOutParam(E);
3041 pushNode(0);
3042 if (*E)
3043 return;
3044 pushDownUntilBottom();
3045}
3046
3047void ExportEntry::moveToEnd() {
3048 Stack.clear();
3049 Done = true;
3050}
3051
3053 // Common case, one at end, other iterating from begin.
3054 if (Done || Other.Done)
3055 return (Done == Other.Done);
3056 // Not equal if different stack sizes.
3057 if (Stack.size() != Other.Stack.size())
3058 return false;
3059 // Not equal if different cumulative strings.
3060 if (!CumulativeString.equals(Other.CumulativeString))
3061 return false;
3062 // Equal if all nodes in both stacks match.
3063 for (unsigned i=0; i < Stack.size(); ++i) {
3064 if (Stack[i].Start != Other.Stack[i].Start)
3065 return false;
3066 }
3067 return true;
3068}
3069
3070uint64_t ExportEntry::readULEB128(const uint8_t *&Ptr, const char **error) {
3071 unsigned Count;
3072 uint64_t Result = decodeULEB128(Ptr, &Count, Trie.end(), error);
3073 Ptr += Count;
3074 if (Ptr > Trie.end())
3075 Ptr = Trie.end();
3076 return Result;
3077}
3078
3080 return CumulativeString;
3081}
3082
3083uint64_t ExportEntry::flags() const {
3084 return Stack.back().Flags;
3085}
3086
3087uint64_t ExportEntry::address() const {
3088 return Stack.back().Address;
3089}
3090
3091uint64_t ExportEntry::other() const {
3092 return Stack.back().Other;
3093}
3094
3096 const char* ImportName = Stack.back().ImportName;
3097 if (ImportName)
3098 return StringRef(ImportName);
3099 return StringRef();
3100}
3101
3103 return Stack.back().Start - Trie.begin();
3104}
3105
3106ExportEntry::NodeState::NodeState(const uint8_t *Ptr)
3107 : Start(Ptr), Current(Ptr) {}
3108
3109void ExportEntry::pushNode(uint64_t offset) {
3110 ErrorAsOutParameter ErrAsOutParam(E);
3111 const uint8_t *Ptr = Trie.begin() + offset;
3112 NodeState State(Ptr);
3113 const char *error = nullptr;
3114 uint64_t ExportInfoSize = readULEB128(State.Current, &error);
3115 if (error) {
3116 *E = malformedError("export info size " + Twine(error) +
3117 " in export trie data at node: 0x" +
3118 Twine::utohexstr(offset));
3119 moveToEnd();
3120 return;
3121 }
3122 State.IsExportNode = (ExportInfoSize != 0);
3123 const uint8_t* Children = State.Current + ExportInfoSize;
3124 if (Children > Trie.end()) {
3125 *E = malformedError(
3126 "export info size: 0x" + Twine::utohexstr(ExportInfoSize) +
3127 " in export trie data at node: 0x" + Twine::utohexstr(offset) +
3128 " too big and extends past end of trie data");
3129 moveToEnd();
3130 return;
3131 }
3132 if (State.IsExportNode) {
3133 const uint8_t *ExportStart = State.Current;
3134 State.Flags = readULEB128(State.Current, &error);
3135 if (error) {
3136 *E = malformedError("flags " + Twine(error) +
3137 " in export trie data at node: 0x" +
3138 Twine::utohexstr(offset));
3139 moveToEnd();
3140 return;
3141 }
3143 if (State.Flags != 0 &&
3147 *E = malformedError(
3148 "unsupported exported symbol kind: " + Twine((int)Kind) +
3149 " in flags: 0x" + Twine::utohexstr(State.Flags) +
3150 " in export trie data at node: 0x" + Twine::utohexstr(offset));
3151 moveToEnd();
3152 return;
3153 }
3154 if (State.Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT) {
3155 State.Address = 0;
3156 State.Other = readULEB128(State.Current, &error); // dylib ordinal
3157 if (error) {
3158 *E = malformedError("dylib ordinal of re-export " + Twine(error) +
3159 " in export trie data at node: 0x" +
3160 Twine::utohexstr(offset));
3161 moveToEnd();
3162 return;
3163 }
3164 if (O != nullptr) {
3165 // Only positive numbers represent library ordinals. Zero and negative
3166 // numbers have special meaning (see BindSpecialDylib).
3167 if ((int64_t)State.Other > 0 && State.Other > O->getLibraryCount()) {
3168 *E = malformedError(
3169 "bad library ordinal: " + Twine((int)State.Other) + " (max " +
3170 Twine((int)O->getLibraryCount()) +
3171 ") in export trie data at node: 0x" + Twine::utohexstr(offset));
3172 moveToEnd();
3173 return;
3174 }
3175 }
3176 State.ImportName = reinterpret_cast<const char*>(State.Current);
3177 if (*State.ImportName == '\0') {
3178 State.Current++;
3179 } else {
3180 const uint8_t *End = State.Current + 1;
3181 if (End >= Trie.end()) {
3182 *E = malformedError("import name of re-export in export trie data at "
3183 "node: 0x" +
3184 Twine::utohexstr(offset) +
3185 " starts past end of trie data");
3186 moveToEnd();
3187 return;
3188 }
3189 while(*End != '\0' && End < Trie.end())
3190 End++;
3191 if (*End != '\0') {
3192 *E = malformedError("import name of re-export in export trie data at "
3193 "node: 0x" +
3194 Twine::utohexstr(offset) +
3195 " extends past end of trie data");
3196 moveToEnd();
3197 return;
3198 }
3199 State.Current = End + 1;
3200 }
3201 } else {
3202 State.Address = readULEB128(State.Current, &error);
3203 if (error) {
3204 *E = malformedError("address " + Twine(error) +
3205 " in export trie data at node: 0x" +
3206 Twine::utohexstr(offset));
3207 moveToEnd();
3208 return;
3209 }
3211 State.Other = readULEB128(State.Current, &error);
3212 if (error) {
3213 *E = malformedError("resolver of stub and resolver " + Twine(error) +
3214 " in export trie data at node: 0x" +
3215 Twine::utohexstr(offset));
3216 moveToEnd();
3217 return;
3218 }
3219 }
3220 }
3221 if (ExportStart + ExportInfoSize < State.Current) {
3222 *E = malformedError(
3223 "inconsistent export info size: 0x" +
3224 Twine::utohexstr(ExportInfoSize) + " where actual size was: 0x" +
3225 Twine::utohexstr(State.Current - ExportStart) +
3226 " in export trie data at node: 0x" + Twine::utohexstr(offset));
3227 moveToEnd();
3228 return;
3229 }
3230 }
3231 State.ChildCount = *Children;
3232 if (State.ChildCount != 0 && Children + 1 >= Trie.end()) {
3233 *E = malformedError("byte for count of children in export trie data at "
3234 "node: 0x" +
3235 Twine::utohexstr(offset) +
3236 " extends past end of trie data");
3237 moveToEnd();
3238 return;
3239 }
3240 State.Current = Children + 1;
3241 State.NextChildIndex = 0;
3242 State.ParentStringLength = CumulativeString.size();
3243 Stack.push_back(State);
3244}
3245
3246void ExportEntry::pushDownUntilBottom() {
3247 ErrorAsOutParameter ErrAsOutParam(E);
3248 const char *error = nullptr;
3249 while (Stack.back().NextChildIndex < Stack.back().ChildCount) {
3250 NodeState &Top = Stack.back();
3251 CumulativeString.resize(Top.ParentStringLength);
3252 for (;*Top.Current != 0 && Top.Current < Trie.end(); Top.Current++) {
3253 char C = *Top.Current;
3254 CumulativeString.push_back(C);
3255 }
3256 if (Top.Current >= Trie.end()) {
3257 *E = malformedError("edge sub-string in export trie data at node: 0x" +
3258 Twine::utohexstr(Top.Start - Trie.begin()) +
3259 " for child #" + Twine((int)Top.NextChildIndex) +
3260 " extends past end of trie data");
3261 moveToEnd();
3262 return;
3263 }
3264 Top.Current += 1;
3265 uint64_t childNodeIndex = readULEB128(Top.Current, &error);
3266 if (error) {
3267 *E = malformedError("child node offset " + Twine(error) +
3268 " in export trie data at node: 0x" +
3269 Twine::utohexstr(Top.Start - Trie.begin()));
3270 moveToEnd();
3271 return;
3272 }
3273 for (const NodeState &node : nodes()) {
3274 if (node.Start == Trie.begin() + childNodeIndex){
3275 *E = malformedError("loop in children in export trie data at node: 0x" +
3276 Twine::utohexstr(Top.Start - Trie.begin()) +
3277 " back to node: 0x" +
3278 Twine::utohexstr(childNodeIndex));
3279 moveToEnd();
3280 return;
3281 }
3282 }
3283 Top.NextChildIndex += 1;
3284 pushNode(childNodeIndex);
3285 if (*E)
3286 return;
3287 }
3288 if (!Stack.back().IsExportNode) {
3289 *E = malformedError("node is not an export node in export trie data at "
3290 "node: 0x" +
3291 Twine::utohexstr(Stack.back().Start - Trie.begin()));
3292 moveToEnd();
3293 return;
3294 }
3295}
3296
3297// We have a trie data structure and need a way to walk it that is compatible
3298// with the C++ iterator model. The solution is a non-recursive depth first
3299// traversal where the iterator contains a stack of parent nodes along with a
3300// string that is the accumulation of all edge strings along the parent chain
3301// to this point.
3302//
3303// There is one "export" node for each exported symbol. But because some
3304// symbols may be a prefix of another symbol (e.g. _dup and _dup2), an export
3305// node may have child nodes too.
3306//
3307// The algorithm for moveNext() is to keep moving down the leftmost unvisited
3308// child until hitting a node with no children (which is an export node or
3309// else the trie is malformed). On the way down, each node is pushed on the
3310// stack ivar. If there is no more ways down, it pops up one and tries to go
3311// down a sibling path until a childless node is reached.
3313 assert(!Stack.empty() && "ExportEntry::moveNext() with empty node stack");
3314 if (!Stack.back().IsExportNode) {
3315 *E = malformedError("node is not an export node in export trie data at "
3316 "node: 0x" +
3317 Twine::utohexstr(Stack.back().Start - Trie.begin()));
3318 moveToEnd();
3319 return;
3320 }
3321
3322 Stack.pop_back();
3323 while (!Stack.empty()) {
3324 NodeState &Top = Stack.back();
3325 if (Top.NextChildIndex < Top.ChildCount) {
3326 pushDownUntilBottom();
3327 // Now at the next export node.
3328 return;
3329 } else {
3330 if (Top.IsExportNode) {
3331 // This node has no children but is itself an export node.
3332 CumulativeString.resize(Top.ParentStringLength);
3333 return;
3334 }
3335 Stack.pop_back();
3336 }
3337 }
3338 Done = true;
3339}
3340
3343 const MachOObjectFile *O) {
3344 ExportEntry Start(&E, O, Trie);
3345 if (Trie.empty())
3346 Start.moveToEnd();
3347 else
3348 Start.moveToFirst();
3349
3350 ExportEntry Finish(&E, O, Trie);
3351 Finish.moveToEnd();
3352
3353 return make_range(export_iterator(Start), export_iterator(Finish));
3354}
3355
3357 ArrayRef<uint8_t> Trie;
3358 if (DyldInfoLoadCmd)
3359 Trie = getDyldInfoExportsTrie();
3360 else if (DyldExportsTrieLoadCmd)
3361 Trie = getDyldExportsTrie();
3362
3363 return exports(Err, Trie, this);
3364}
3365
3367 const MachOObjectFile *O)
3368 : E(E), O(O) {
3369 // Cache the vmaddress of __TEXT
3370 for (const auto &Command : O->load_commands()) {
3371 if (Command.C.cmd == MachO::LC_SEGMENT) {
3372 MachO::segment_command SLC = O->getSegmentLoadCommand(Command);
3373 if (StringRef(SLC.segname) == "__TEXT") {
3374 TextAddress = SLC.vmaddr;
3375 break;
3376 }
3377 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
3378 MachO::segment_command_64 SLC_64 = O->getSegment64LoadCommand(Command);
3379 if (StringRef(SLC_64.segname) == "__TEXT") {
3380 TextAddress = SLC_64.vmaddr;
3381 break;
3382 }
3383 }
3384 }
3385}
3386
3388
3390 return SegmentOffset;
3391}
3392
3394 return O->BindRebaseAddress(SegmentIndex, 0);
3395}
3396
3398 return O->BindRebaseSegmentName(SegmentIndex);
3399}
3400
3402 return O->BindRebaseSectionName(SegmentIndex, SegmentOffset);
3403}
3404
3406 return O->BindRebaseAddress(SegmentIndex, SegmentOffset);
3407}
3408
3410
3411int64_t MachOAbstractFixupEntry::addend() const { return Addend; }
3412
3414
3416
3418
3420 SegmentOffset = 0;
3421 SegmentIndex = -1;
3422 Ordinal = 0;
3423 Flags = 0;
3424 Addend = 0;
3425 Done = false;
3426}
3427
3429
3431
3433 const MachOObjectFile *O,
3434 bool Parse)
3437 if (!Parse)
3438 return;
3439
3440 if (auto FixupTargetsOrErr = O->getDyldChainedFixupTargets()) {
3441 FixupTargets = *FixupTargetsOrErr;
3442 } else {
3443 *E = FixupTargetsOrErr.takeError();
3444 return;
3445 }
3446
3447 if (auto SegmentsOrErr = O->getChainedFixupsSegments()) {
3448 Segments = std::move(SegmentsOrErr->second);
3449 } else {
3450 *E = SegmentsOrErr.takeError();
3451 return;
3452 }
3453}
3454
3455void MachOChainedFixupEntry::findNextPageWithFixups() {
3456 auto FindInSegment = [this]() {
3457 const ChainedFixupsSegment &SegInfo = Segments[InfoSegIndex];
3458 while (PageIndex < SegInfo.PageStarts.size() &&
3459 SegInfo.PageStarts[PageIndex] == MachO::DYLD_CHAINED_PTR_START_NONE)
3460 ++PageIndex;
3461 return PageIndex < SegInfo.PageStarts.size();
3462 };
3463
3464 while (InfoSegIndex < Segments.size()) {
3465 if (FindInSegment()) {
3466 PageOffset = Segments[InfoSegIndex].PageStarts[PageIndex];
3467 SegmentData = O->getSegmentContents(Segments[InfoSegIndex].SegIdx);
3468 return;
3469 }
3470
3471 InfoSegIndex++;
3472 PageIndex = 0;
3473 }
3474}
3475
3478 if (Segments.empty()) {
3479 Done = true;
3480 return;
3481 }
3482
3483 InfoSegIndex = 0;
3484 PageIndex = 0;
3485
3486 findNextPageWithFixups();
3487 moveNext();
3488}
3489
3493
3495 ErrorAsOutParameter ErrAsOutParam(E);
3496
3497 if (InfoSegIndex == Segments.size()) {
3498 Done = true;
3499 return;
3500 }
3501
3502 const ChainedFixupsSegment &SegInfo = Segments[InfoSegIndex];
3503 SegmentIndex = SegInfo.SegIdx;
3504 SegmentOffset = SegInfo.Header.page_size * PageIndex + PageOffset;
3505
3506 // FIXME: Handle other pointer formats.
3507 uint16_t PointerFormat = SegInfo.Header.pointer_format;
3508 if (PointerFormat != MachO::DYLD_CHAINED_PTR_64 &&
3509 PointerFormat != MachO::DYLD_CHAINED_PTR_64_OFFSET) {
3510 *E = createError("segment " + Twine(SegmentIndex) +
3511 " has unsupported chained fixup pointer_format " +
3512 Twine(PointerFormat));
3513 moveToEnd();
3514 return;
3515 }
3516
3517 Ordinal = 0;
3518 Flags = 0;
3519 Addend = 0;
3520 PointerValue = 0;
3521 SymbolName = {};
3522
3523 if (SegmentOffset + sizeof(RawValue) > SegmentData.size()) {
3524 *E = malformedError("fixup in segment " + Twine(SegmentIndex) +
3525 " at offset " + Twine(SegmentOffset) +
3526 " extends past segment's end");
3527 moveToEnd();
3528 return;
3529 }
3530
3531 static_assert(sizeof(RawValue) == sizeof(MachO::dyld_chained_import_addend));
3532 memcpy(&RawValue, SegmentData.data() + SegmentOffset, sizeof(RawValue));
3533 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3535
3536 // The bit extraction below assumes little-endian fixup entries.
3537 assert(O->isLittleEndian() && "big-endian object should have been rejected "
3538 "by getDyldChainedFixupTargets()");
3539 auto Field = [this](uint8_t Right, uint8_t Count) {
3540 return (RawValue >> Right) & ((1ULL << Count) - 1);
3541 };
3542
3543 // The `bind` field (most significant bit) of the encoded fixup determines
3544 // whether it is dyld_chained_ptr_64_bind or dyld_chained_ptr_64_rebase.
3545 bool IsBind = Field(63, 1);
3546 Kind = IsBind ? FixupKind::Bind : FixupKind::Rebase;
3547 uint32_t Next = Field(51, 12);
3548 if (IsBind) {
3549 uint32_t ImportOrdinal = Field(0, 24);
3550 uint8_t InlineAddend = Field(24, 8);
3551
3552 if (ImportOrdinal >= FixupTargets.size()) {
3553 *E = malformedError("fixup in segment " + Twine(SegmentIndex) +
3554 " at offset " + Twine(SegmentOffset) +
3555 " has out-of range import ordinal " +
3556 Twine(ImportOrdinal));
3557 moveToEnd();
3558 return;
3559 }
3560
3561 ChainedFixupTarget &Target = FixupTargets[ImportOrdinal];
3562 Ordinal = Target.libOrdinal();
3563 Addend = InlineAddend ? InlineAddend : Target.addend();
3565 SymbolName = Target.symbolName();
3566 } else {
3567 uint64_t Target = Field(0, 36);
3568 uint64_t High8 = Field(36, 8);
3569
3570 PointerValue = Target | (High8 << 56);
3571 if (PointerFormat == MachO::DYLD_CHAINED_PTR_64_OFFSET)
3573 }
3574
3575 // The stride is 4 bytes for DYLD_CHAINED_PTR_64(_OFFSET).
3576 if (Next != 0) {
3577 PageOffset += 4 * Next;
3578 } else {
3579 ++PageIndex;
3580 findNextPageWithFixups();
3581 }
3582}
3583
3585 const MachOChainedFixupEntry &Other) const {
3586 if (Done && Other.Done)
3587 return true;
3588 if (Done != Other.Done)
3589 return false;
3590 return InfoSegIndex == Other.InfoSegIndex && PageIndex == Other.PageIndex &&
3591 PageOffset == Other.PageOffset;
3592}
3593
3595 ArrayRef<uint8_t> Bytes, bool is64Bit)
3596 : E(E), O(O), Opcodes(Bytes), Ptr(Bytes.begin()),
3597 PointerSize(is64Bit ? 8 : 4) {}
3598
3599void MachORebaseEntry::moveToFirst() {
3600 Ptr = Opcodes.begin();
3601 moveNext();
3602}
3603
3604void MachORebaseEntry::moveToEnd() {
3605 Ptr = Opcodes.end();
3606 RemainingLoopCount = 0;
3607 Done = true;
3608}
3609
3611 ErrorAsOutParameter ErrAsOutParam(E);
3612 // If in the middle of some loop, move to next rebasing in loop.
3613 SegmentOffset += AdvanceAmount;
3614 if (RemainingLoopCount) {
3615 --RemainingLoopCount;
3616 return;
3617 }
3618
3619 bool More = true;
3620 while (More) {
3621 // REBASE_OPCODE_DONE is only used for padding if we are not aligned to
3622 // pointer size. Therefore it is possible to reach the end without ever
3623 // having seen REBASE_OPCODE_DONE.
3624 if (Ptr == Opcodes.end()) {
3625 Done = true;
3626 return;
3627 }
3628
3629 // Parse next opcode and set up next loop.
3630 const uint8_t *OpcodeStart = Ptr;
3631 uint8_t Byte = *Ptr++;
3632 uint8_t ImmValue = Byte & MachO::REBASE_IMMEDIATE_MASK;
3633 uint8_t Opcode = Byte & MachO::REBASE_OPCODE_MASK;
3634 uint64_t Count, Skip;
3635 const char *error = nullptr;
3636 switch (Opcode) {
3638 More = false;
3639 Done = true;
3640 moveToEnd();
3641 DEBUG_WITH_TYPE("mach-o-rebase", dbgs() << "REBASE_OPCODE_DONE\n");
3642 break;
3644 RebaseType = ImmValue;
3645 if (RebaseType > MachO::REBASE_TYPE_TEXT_PCREL32) {
3646 *E = malformedError("for REBASE_OPCODE_SET_TYPE_IMM bad bind type: " +
3647 Twine((int)RebaseType) + " for opcode at: 0x" +
3648 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3649 moveToEnd();
3650 return;
3651 }
3653 "mach-o-rebase",
3654 dbgs() << "REBASE_OPCODE_SET_TYPE_IMM: "
3655 << "RebaseType=" << (int) RebaseType << "\n");
3656 break;
3658 SegmentIndex = ImmValue;
3659 SegmentOffset = readULEB128(&error);
3660 if (error) {
3661 *E = malformedError("for REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB " +
3662 Twine(error) + " for opcode at: 0x" +
3663 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3664 moveToEnd();
3665 return;
3666 }
3667 error = O->RebaseEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3668 PointerSize);
3669 if (error) {
3670 *E = malformedError("for REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB " +
3671 Twine(error) + " for opcode at: 0x" +
3672 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3673 moveToEnd();
3674 return;
3675 }
3677 "mach-o-rebase",
3678 dbgs() << "REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB: "
3679 << "SegmentIndex=" << SegmentIndex << ", "
3680 << format("SegmentOffset=0x%06X", SegmentOffset)
3681 << "\n");
3682 break;
3684 SegmentOffset += readULEB128(&error);
3685 if (error) {
3686 *E = malformedError("for REBASE_OPCODE_ADD_ADDR_ULEB " + Twine(error) +
3687 " for opcode at: 0x" +
3688 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3689 moveToEnd();
3690 return;
3691 }
3692 error = O->RebaseEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3693 PointerSize);
3694 if (error) {
3695 *E = malformedError("for REBASE_OPCODE_ADD_ADDR_ULEB " + Twine(error) +
3696 " for opcode at: 0x" +
3697 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3698 moveToEnd();
3699 return;
3700 }
3701 DEBUG_WITH_TYPE("mach-o-rebase",
3702 dbgs() << "REBASE_OPCODE_ADD_ADDR_ULEB: "
3703 << format("SegmentOffset=0x%06X",
3704 SegmentOffset) << "\n");
3705 break;
3707 SegmentOffset += ImmValue * PointerSize;
3708 error = O->RebaseEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3709 PointerSize);
3710 if (error) {
3711 *E = malformedError("for REBASE_OPCODE_ADD_ADDR_IMM_SCALED " +
3712 Twine(error) + " for opcode at: 0x" +
3713 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3714 moveToEnd();
3715 return;
3716 }
3717 DEBUG_WITH_TYPE("mach-o-rebase",
3718 dbgs() << "REBASE_OPCODE_ADD_ADDR_IMM_SCALED: "
3719 << format("SegmentOffset=0x%06X",
3720 SegmentOffset) << "\n");
3721 break;
3723 AdvanceAmount = PointerSize;
3724 Skip = 0;
3725 Count = ImmValue;
3726 if (ImmValue != 0)
3727 RemainingLoopCount = ImmValue - 1;
3728 else
3729 RemainingLoopCount = 0;
3730 error = O->RebaseEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3731 PointerSize, Count, Skip);
3732 if (error) {
3733 *E = malformedError("for REBASE_OPCODE_DO_REBASE_IMM_TIMES " +
3734 Twine(error) + " for opcode at: 0x" +
3735 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3736 moveToEnd();
3737 return;
3738 }
3740 "mach-o-rebase",
3741 dbgs() << "REBASE_OPCODE_DO_REBASE_IMM_TIMES: "
3742 << format("SegmentOffset=0x%06X", SegmentOffset)
3743 << ", AdvanceAmount=" << AdvanceAmount
3744 << ", RemainingLoopCount=" << RemainingLoopCount
3745 << "\n");
3746 return;
3748 AdvanceAmount = PointerSize;
3749 Skip = 0;
3750 Count = readULEB128(&error);
3751 if (error) {
3752 *E = malformedError("for REBASE_OPCODE_DO_REBASE_ULEB_TIMES " +
3753 Twine(error) + " for opcode at: 0x" +
3754 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3755 moveToEnd();
3756 return;
3757 }
3758 if (Count != 0)
3759 RemainingLoopCount = Count - 1;
3760 else
3761 RemainingLoopCount = 0;
3762 error = O->RebaseEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3763 PointerSize, Count, Skip);
3764 if (error) {
3765 *E = malformedError("for REBASE_OPCODE_DO_REBASE_ULEB_TIMES " +
3766 Twine(error) + " for opcode at: 0x" +
3767 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3768 moveToEnd();
3769 return;
3770 }
3772 "mach-o-rebase",
3773 dbgs() << "REBASE_OPCODE_DO_REBASE_ULEB_TIMES: "
3774 << format("SegmentOffset=0x%06X", SegmentOffset)
3775 << ", AdvanceAmount=" << AdvanceAmount
3776 << ", RemainingLoopCount=" << RemainingLoopCount
3777 << "\n");
3778 return;
3780 Skip = readULEB128(&error);
3781 if (error) {
3782 *E = malformedError("for REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB " +
3783 Twine(error) + " for opcode at: 0x" +
3784 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3785 moveToEnd();
3786 return;
3787 }
3788 AdvanceAmount = Skip + PointerSize;
3789 Count = 1;
3790 RemainingLoopCount = 0;
3791 error = O->RebaseEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3792 PointerSize, Count, Skip);
3793 if (error) {
3794 *E = malformedError("for REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB " +
3795 Twine(error) + " for opcode at: 0x" +
3796 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3797 moveToEnd();
3798 return;
3799 }
3801 "mach-o-rebase",
3802 dbgs() << "REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB: "
3803 << format("SegmentOffset=0x%06X", SegmentOffset)
3804 << ", AdvanceAmount=" << AdvanceAmount
3805 << ", RemainingLoopCount=" << RemainingLoopCount
3806 << "\n");
3807 return;
3809 Count = readULEB128(&error);
3810 if (error) {
3811 *E = malformedError("for REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_"
3812 "ULEB " +
3813 Twine(error) + " for opcode at: 0x" +
3814 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3815 moveToEnd();
3816 return;
3817 }
3818 if (Count != 0)
3819 RemainingLoopCount = Count - 1;
3820 else
3821 RemainingLoopCount = 0;
3822 Skip = readULEB128(&error);
3823 if (error) {
3824 *E = malformedError("for REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_"
3825 "ULEB " +
3826 Twine(error) + " for opcode at: 0x" +
3827 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3828 moveToEnd();
3829 return;
3830 }
3831 AdvanceAmount = Skip + PointerSize;
3832
3833 error = O->RebaseEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3834 PointerSize, Count, Skip);
3835 if (error) {
3836 *E = malformedError("for REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_"
3837 "ULEB " +
3838 Twine(error) + " for opcode at: 0x" +
3839 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3840 moveToEnd();
3841 return;
3842 }
3844 "mach-o-rebase",
3845 dbgs() << "REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB: "
3846 << format("SegmentOffset=0x%06X", SegmentOffset)
3847 << ", AdvanceAmount=" << AdvanceAmount
3848 << ", RemainingLoopCount=" << RemainingLoopCount
3849 << "\n");
3850 return;
3851 default:
3852 *E = malformedError("bad rebase info (bad opcode value 0x" +
3853 Twine::utohexstr(Opcode) + " for opcode at: 0x" +
3854 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3855 moveToEnd();
3856 return;
3857 }
3858 }
3859}
3860
3861uint64_t MachORebaseEntry::readULEB128(const char **error) {
3862 unsigned Count;
3863 uint64_t Result = decodeULEB128(Ptr, &Count, Opcodes.end(), error);
3864 Ptr += Count;
3865 if (Ptr > Opcodes.end())
3866 Ptr = Opcodes.end();
3867 return Result;
3868}
3869
3870int32_t MachORebaseEntry::segmentIndex() const { return SegmentIndex; }
3871
3872uint64_t MachORebaseEntry::segmentOffset() const { return SegmentOffset; }
3873
3875 switch (RebaseType) {
3877 return "pointer";
3879 return "text abs32";
3881 return "text rel32";
3882 }
3883 return "unknown";
3884}
3885
3886// For use with the SegIndex of a checked Mach-O Rebase entry
3887// to get the segment name.
3889 return O->BindRebaseSegmentName(SegmentIndex);
3890}
3891
3892// For use with a SegIndex,SegOffset pair from a checked Mach-O Rebase entry
3893// to get the section name.
3895 return O->BindRebaseSectionName(SegmentIndex, SegmentOffset);
3896}
3897
3898// For use with a SegIndex,SegOffset pair from a checked Mach-O Rebase entry
3899// to get the address.
3901 return O->BindRebaseAddress(SegmentIndex, SegmentOffset);
3902}
3903
3905#ifdef EXPENSIVE_CHECKS
3906 assert(Opcodes == Other.Opcodes && "compare iterators of different files");
3907#else
3908 assert(Opcodes.data() == Other.Opcodes.data() && "compare iterators of different files");
3909#endif
3910 return (Ptr == Other.Ptr) &&
3911 (RemainingLoopCount == Other.RemainingLoopCount) &&
3912 (Done == Other.Done);
3913}
3914
3916MachOObjectFile::rebaseTable(Error &Err, MachOObjectFile *O,
3917 ArrayRef<uint8_t> Opcodes, bool is64) {
3918 if (O->BindRebaseSectionTable == nullptr)
3919 O->BindRebaseSectionTable = std::make_unique<BindRebaseSegInfo>(O);
3920 MachORebaseEntry Start(&Err, O, Opcodes, is64);
3921 Start.moveToFirst();
3922
3923 MachORebaseEntry Finish(&Err, O, Opcodes, is64);
3924 Finish.moveToEnd();
3925
3926 return make_range(rebase_iterator(Start), rebase_iterator(Finish));
3927}
3928
3932
3934 ArrayRef<uint8_t> Bytes, bool is64Bit, Kind BK)
3935 : E(E), O(O), Opcodes(Bytes), Ptr(Bytes.begin()),
3936 PointerSize(is64Bit ? 8 : 4), TableKind(BK) {}
3937
3938void MachOBindEntry::moveToFirst() {
3939 Ptr = Opcodes.begin();
3940 moveNext();
3941}
3942
3943void MachOBindEntry::moveToEnd() {
3944 Ptr = Opcodes.end();
3945 RemainingLoopCount = 0;
3946 Done = true;
3947}
3948
3950 ErrorAsOutParameter ErrAsOutParam(E);
3951 // If in the middle of some loop, move to next binding in loop.
3952 SegmentOffset += AdvanceAmount;
3953 if (RemainingLoopCount) {
3954 --RemainingLoopCount;
3955 return;
3956 }
3957
3958 bool More = true;
3959 while (More) {
3960 // BIND_OPCODE_DONE is only used for padding if we are not aligned to
3961 // pointer size. Therefore it is possible to reach the end without ever
3962 // having seen BIND_OPCODE_DONE.
3963 if (Ptr == Opcodes.end()) {
3964 Done = true;
3965 return;
3966 }
3967
3968 // Parse next opcode and set up next loop.
3969 const uint8_t *OpcodeStart = Ptr;
3970 uint8_t Byte = *Ptr++;
3971 uint8_t ImmValue = Byte & MachO::BIND_IMMEDIATE_MASK;
3972 uint8_t Opcode = Byte & MachO::BIND_OPCODE_MASK;
3973 int8_t SignExtended;
3974 const uint8_t *SymStart;
3975 uint64_t Count, Skip;
3976 const char *error = nullptr;
3977 switch (Opcode) {
3979 if (TableKind == Kind::Lazy) {
3980 // Lazying bindings have a DONE opcode between entries. Need to ignore
3981 // it to advance to next entry. But need not if this is last entry.
3982 bool NotLastEntry = false;
3983 for (const uint8_t *P = Ptr; P < Opcodes.end(); ++P) {
3984 if (*P) {
3985 NotLastEntry = true;
3986 }
3987 }
3988 if (NotLastEntry)
3989 break;
3990 }
3991 More = false;
3992 moveToEnd();
3993 DEBUG_WITH_TYPE("mach-o-bind", dbgs() << "BIND_OPCODE_DONE\n");
3994 break;
3996 if (TableKind == Kind::Weak) {
3997 *E = malformedError("BIND_OPCODE_SET_DYLIB_ORDINAL_IMM not allowed in "
3998 "weak bind table for opcode at: 0x" +
3999 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4000 moveToEnd();
4001 return;
4002 }
4003 Ordinal = ImmValue;
4004 LibraryOrdinalSet = true;
4005 if (ImmValue > O->getLibraryCount()) {
4006 *E = malformedError("for BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB bad "
4007 "library ordinal: " +
4008 Twine((int)ImmValue) + " (max " +
4009 Twine((int)O->getLibraryCount()) +
4010 ") for opcode at: 0x" +
4011 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4012 moveToEnd();
4013 return;
4014 }
4016 "mach-o-bind",
4017 dbgs() << "BIND_OPCODE_SET_DYLIB_ORDINAL_IMM: "
4018 << "Ordinal=" << Ordinal << "\n");
4019 break;
4021 if (TableKind == Kind::Weak) {
4022 *E = malformedError("BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB not allowed in "
4023 "weak bind table for opcode at: 0x" +
4024 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4025 moveToEnd();
4026 return;
4027 }
4028 Ordinal = readULEB128(&error);
4029 LibraryOrdinalSet = true;
4030 if (error) {
4031 *E = malformedError("for BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB " +
4032 Twine(error) + " for opcode at: 0x" +
4033 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4034 moveToEnd();
4035 return;
4036 }
4037 if (Ordinal > (int)O->getLibraryCount()) {
4038 *E = malformedError("for BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB bad "
4039 "library ordinal: " +
4040 Twine((int)Ordinal) + " (max " +
4041 Twine((int)O->getLibraryCount()) +
4042 ") for opcode at: 0x" +
4043 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4044 moveToEnd();
4045 return;
4046 }
4048 "mach-o-bind",
4049 dbgs() << "BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB: "
4050 << "Ordinal=" << Ordinal << "\n");
4051 break;
4053 if (TableKind == Kind::Weak) {
4054 *E = malformedError("BIND_OPCODE_SET_DYLIB_SPECIAL_IMM not allowed in "
4055 "weak bind table for opcode at: 0x" +
4056 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4057 moveToEnd();
4058 return;
4059 }
4060 if (ImmValue) {
4061 SignExtended = MachO::BIND_OPCODE_MASK | ImmValue;
4062 Ordinal = SignExtended;
4064 *E = malformedError("for BIND_OPCODE_SET_DYLIB_SPECIAL_IMM unknown "
4065 "special ordinal: " +
4066 Twine((int)Ordinal) + " for opcode at: 0x" +
4067 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4068 moveToEnd();
4069 return;
4070 }
4071 } else
4072 Ordinal = 0;
4073 LibraryOrdinalSet = true;
4075 "mach-o-bind",
4076 dbgs() << "BIND_OPCODE_SET_DYLIB_SPECIAL_IMM: "
4077 << "Ordinal=" << Ordinal << "\n");
4078 break;
4080 Flags = ImmValue;
4081 SymStart = Ptr;
4082 while (*Ptr && (Ptr < Opcodes.end())) {
4083 ++Ptr;
4084 }
4085 if (Ptr == Opcodes.end()) {
4086 *E = malformedError(
4087 "for BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM "
4088 "symbol name extends past opcodes for opcode at: 0x" +
4089 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4090 moveToEnd();
4091 return;
4092 }
4093 SymbolName = StringRef(reinterpret_cast<const char*>(SymStart),
4094 Ptr-SymStart);
4095 ++Ptr;
4097 "mach-o-bind",
4098 dbgs() << "BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM: "
4099 << "SymbolName=" << SymbolName << "\n");
4100 if (TableKind == Kind::Weak) {
4102 return;
4103 }
4104 break;
4106 BindType = ImmValue;
4107 if (ImmValue > MachO::BIND_TYPE_TEXT_PCREL32) {
4108 *E = malformedError("for BIND_OPCODE_SET_TYPE_IMM bad bind type: " +
4109 Twine((int)ImmValue) + " for opcode at: 0x" +
4110 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4111 moveToEnd();
4112 return;
4113 }
4115 "mach-o-bind",
4116 dbgs() << "BIND_OPCODE_SET_TYPE_IMM: "
4117 << "BindType=" << (int)BindType << "\n");
4118 break;
4120 Addend = readSLEB128(&error);
4121 if (error) {
4122 *E = malformedError("for BIND_OPCODE_SET_ADDEND_SLEB " + Twine(error) +
4123 " for opcode at: 0x" +
4124 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4125 moveToEnd();
4126 return;
4127 }
4129 "mach-o-bind",
4130 dbgs() << "BIND_OPCODE_SET_ADDEND_SLEB: "
4131 << "Addend=" << Addend << "\n");
4132 break;
4134 SegmentIndex = ImmValue;
4135 SegmentOffset = readULEB128(&error);
4136 if (error) {
4137 *E = malformedError("for BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB " +
4138 Twine(error) + " 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_SET_SEGMENT_AND_OFFSET_ULEB " +
4147 Twine(error) + " for opcode at: 0x" +
4148 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4149 moveToEnd();
4150 return;
4151 }
4153 "mach-o-bind",
4154 dbgs() << "BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB: "
4155 << "SegmentIndex=" << SegmentIndex << ", "
4156 << format("SegmentOffset=0x%06X", SegmentOffset)
4157 << "\n");
4158 break;
4160 SegmentOffset += readULEB128(&error);
4161 if (error) {
4162 *E = malformedError("for BIND_OPCODE_ADD_ADDR_ULEB " + Twine(error) +
4163 " for opcode at: 0x" +
4164 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4165 moveToEnd();
4166 return;
4167 }
4168 error = O->BindEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
4169 PointerSize);
4170 if (error) {
4171 *E = malformedError("for BIND_OPCODE_ADD_ADDR_ULEB " + Twine(error) +
4172 " for opcode at: 0x" +
4173 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4174 moveToEnd();
4175 return;
4176 }
4177 DEBUG_WITH_TYPE("mach-o-bind",
4178 dbgs() << "BIND_OPCODE_ADD_ADDR_ULEB: "
4179 << format("SegmentOffset=0x%06X",
4180 SegmentOffset) << "\n");
4181 break;
4183 AdvanceAmount = PointerSize;
4184 RemainingLoopCount = 0;
4185 error = O->BindEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
4186 PointerSize);
4187 if (error) {
4188 *E = malformedError("for BIND_OPCODE_DO_BIND " + Twine(error) +
4189 " for opcode at: 0x" +
4190 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4191 moveToEnd();
4192 return;
4193 }
4194 if (SymbolName == StringRef()) {
4195 *E = malformedError(
4196 "for BIND_OPCODE_DO_BIND missing preceding "
4197 "BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM for opcode at: 0x" +
4198 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4199 moveToEnd();
4200 return;
4201 }
4202 if (!LibraryOrdinalSet && TableKind != Kind::Weak) {
4203 *E =
4204 malformedError("for BIND_OPCODE_DO_BIND missing preceding "
4205 "BIND_OPCODE_SET_DYLIB_ORDINAL_* for opcode at: 0x" +
4206 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4207 moveToEnd();
4208 return;
4209 }
4210 DEBUG_WITH_TYPE("mach-o-bind",
4211 dbgs() << "BIND_OPCODE_DO_BIND: "
4212 << format("SegmentOffset=0x%06X",
4213 SegmentOffset) << "\n");
4214 return;
4216 if (TableKind == Kind::Lazy) {
4217 *E = malformedError("BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB not allowed in "
4218 "lazy bind table for opcode at: 0x" +
4219 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4220 moveToEnd();
4221 return;
4222 }
4223 error = O->BindEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
4224 PointerSize);
4225 if (error) {
4226 *E = malformedError("for BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB " +
4227 Twine(error) + " for opcode at: 0x" +
4228 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4229 moveToEnd();
4230 return;
4231 }
4232 if (SymbolName == StringRef()) {
4233 *E = malformedError(
4234 "for BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB missing "
4235 "preceding BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM for opcode "
4236 "at: 0x" +
4237 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4238 moveToEnd();
4239 return;
4240 }
4241 if (!LibraryOrdinalSet && TableKind != Kind::Weak) {
4242 *E = malformedError(
4243 "for BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB missing "
4244 "preceding BIND_OPCODE_SET_DYLIB_ORDINAL_* for opcode at: 0x" +
4245 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4246 moveToEnd();
4247 return;
4248 }
4249 AdvanceAmount = readULEB128(&error) + PointerSize;
4250 if (error) {
4251 *E = malformedError("for BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB " +
4252 Twine(error) + " for opcode at: 0x" +
4253 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4254 moveToEnd();
4255 return;
4256 }
4257 // Note, this is not really an error until the next bind but make no sense
4258 // for a BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB to not be followed by another
4259 // bind operation.
4260 error = O->BindEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset +
4261 AdvanceAmount, PointerSize);
4262 if (error) {
4263 *E = malformedError("for BIND_OPCODE_ADD_ADDR_ULEB (after adding "
4264 "ULEB) " +
4265 Twine(error) + " for opcode at: 0x" +
4266 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4267 moveToEnd();
4268 return;
4269 }
4270 RemainingLoopCount = 0;
4272 "mach-o-bind",
4273 dbgs() << "BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB: "
4274 << format("SegmentOffset=0x%06X", SegmentOffset)
4275 << ", AdvanceAmount=" << AdvanceAmount
4276 << ", RemainingLoopCount=" << RemainingLoopCount
4277 << "\n");
4278 return;
4280 if (TableKind == Kind::Lazy) {
4281 *E = malformedError("BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED not "
4282 "allowed in lazy bind table for opcode at: 0x" +
4283 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4284 moveToEnd();
4285 return;
4286 }
4287 if (SymbolName == StringRef()) {
4288 *E = malformedError(
4289 "for BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED "
4290 "missing preceding BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM for "
4291 "opcode at: 0x" +
4292 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4293 moveToEnd();
4294 return;
4295 }
4296 if (!LibraryOrdinalSet && TableKind != Kind::Weak) {
4297 *E = malformedError(
4298 "for BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED "
4299 "missing preceding BIND_OPCODE_SET_DYLIB_ORDINAL_* for opcode "
4300 "at: 0x" +
4301 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4302 moveToEnd();
4303 return;
4304 }
4305 AdvanceAmount = ImmValue * PointerSize + PointerSize;
4306 RemainingLoopCount = 0;
4307 error = O->BindEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset +
4308 AdvanceAmount, PointerSize);
4309 if (error) {
4310 *E = malformedError("for BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED " +
4311 Twine(error) + " for opcode at: 0x" +
4312 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4313 moveToEnd();
4314 return;
4315 }
4316 DEBUG_WITH_TYPE("mach-o-bind",
4317 dbgs()
4318 << "BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED: "
4319 << format("SegmentOffset=0x%06X", SegmentOffset) << "\n");
4320 return;
4322 if (TableKind == Kind::Lazy) {
4323 *E = malformedError("BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB not "
4324 "allowed in lazy bind table for opcode at: 0x" +
4325 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4326 moveToEnd();
4327 return;
4328 }
4329 Count = readULEB128(&error);
4330 if (Count != 0)
4331 RemainingLoopCount = Count - 1;
4332 else
4333 RemainingLoopCount = 0;
4334 if (error) {
4335 *E = malformedError("for BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB "
4336 " (count value) " +
4337 Twine(error) + " for opcode at: 0x" +
4338 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4339 moveToEnd();
4340 return;
4341 }
4342 Skip = readULEB128(&error);
4343 AdvanceAmount = Skip + PointerSize;
4344 if (error) {
4345 *E = malformedError("for BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB "
4346 " (skip value) " +
4347 Twine(error) + " for opcode at: 0x" +
4348 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4349 moveToEnd();
4350 return;
4351 }
4352 if (SymbolName == StringRef()) {
4353 *E = malformedError(
4354 "for BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB "
4355 "missing preceding BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM for "
4356 "opcode at: 0x" +
4357 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4358 moveToEnd();
4359 return;
4360 }
4361 if (!LibraryOrdinalSet && TableKind != Kind::Weak) {
4362 *E = malformedError(
4363 "for BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB "
4364 "missing preceding BIND_OPCODE_SET_DYLIB_ORDINAL_* for opcode "
4365 "at: 0x" +
4366 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4367 moveToEnd();
4368 return;
4369 }
4370 error = O->BindEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
4371 PointerSize, Count, Skip);
4372 if (error) {
4373 *E =
4374 malformedError("for BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB " +
4375 Twine(error) + " for opcode at: 0x" +
4376 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4377 moveToEnd();
4378 return;
4379 }
4381 "mach-o-bind",
4382 dbgs() << "BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB: "
4383 << format("SegmentOffset=0x%06X", SegmentOffset)
4384 << ", AdvanceAmount=" << AdvanceAmount
4385 << ", RemainingLoopCount=" << RemainingLoopCount
4386 << "\n");
4387 return;
4388 default:
4389 *E = malformedError("bad bind info (bad opcode value 0x" +
4390 Twine::utohexstr(Opcode) + " for opcode at: 0x" +
4391 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4392 moveToEnd();
4393 return;
4394 }
4395 }
4396}
4397
4398uint64_t MachOBindEntry::readULEB128(const char **error) {
4399 unsigned Count;
4400 uint64_t Result = decodeULEB128(Ptr, &Count, Opcodes.end(), error);
4401 Ptr += Count;
4402 if (Ptr > Opcodes.end())
4403 Ptr = Opcodes.end();
4404 return Result;
4405}
4406
4407int64_t MachOBindEntry::readSLEB128(const char **error) {
4408 unsigned Count;
4409 int64_t Result = decodeSLEB128(Ptr, &Count, Opcodes.end(), error);
4410 Ptr += Count;
4411 if (Ptr > Opcodes.end())
4412 Ptr = Opcodes.end();
4413 return Result;
4414}
4415
4416int32_t MachOBindEntry::segmentIndex() const { return SegmentIndex; }
4417
4418uint64_t MachOBindEntry::segmentOffset() const { return SegmentOffset; }
4419
4421 switch (BindType) {
4423 return "pointer";
4425 return "text abs32";
4427 return "text rel32";
4428 }
4429 return "unknown";
4430}
4431
4432StringRef MachOBindEntry::symbolName() const { return SymbolName; }
4433
4434int64_t MachOBindEntry::addend() const { return Addend; }
4435
4436uint32_t MachOBindEntry::flags() const { return Flags; }
4437
4438int MachOBindEntry::ordinal() const { return Ordinal; }
4439
4440// For use with the SegIndex of a checked Mach-O Bind entry
4441// to get the segment name.
4443 return O->BindRebaseSegmentName(SegmentIndex);
4444}
4445
4446// For use with a SegIndex,SegOffset pair from a checked Mach-O Bind entry
4447// to get the section name.
4449 return O->BindRebaseSectionName(SegmentIndex, SegmentOffset);
4450}
4451
4452// For use with a SegIndex,SegOffset pair from a checked Mach-O Bind entry
4453// to get the address.
4454uint64_t MachOBindEntry::address() const {
4455 return O->BindRebaseAddress(SegmentIndex, SegmentOffset);
4456}
4457
4459#ifdef EXPENSIVE_CHECKS
4460 assert(Opcodes == Other.Opcodes && "compare iterators of different files");
4461#else
4462 assert(Opcodes.data() == Other.Opcodes.data() && "compare iterators of different files");
4463#endif
4464 return (Ptr == Other.Ptr) &&
4465 (RemainingLoopCount == Other.RemainingLoopCount) &&
4466 (Done == Other.Done);
4467}
4468
4469// Build table of sections so SegIndex/SegOffset pairs can be translated.
4471 uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
4472 StringRef CurSegName;
4473 uint64_t CurSegAddress;
4474 for (const SectionRef &Section : Obj->sections()) {
4475 SectionInfo Info;
4476 Expected<StringRef> NameOrErr = Section.getName();
4477 if (!NameOrErr)
4478 consumeError(NameOrErr.takeError());
4479 else
4480 Info.SectionName = *NameOrErr;
4481 Info.Address = Section.getAddress();
4482 Info.Size = Section.getSize();
4483 Info.SegmentName =
4484 Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
4485 if (Info.SegmentName != CurSegName) {
4486 ++CurSegIndex;
4487 CurSegName = Info.SegmentName;
4488 CurSegAddress = Info.Address;
4489 }
4490 Info.SegmentIndex = CurSegIndex - 1;
4491 Info.OffsetInSegment = Info.Address - CurSegAddress;
4492 Info.SegmentStartAddress = CurSegAddress;
4493 Sections.push_back(Info);
4494 }
4495 MaxSegIndex = CurSegIndex;
4496}
4497
4498// For use with a SegIndex, SegOffset, and PointerSize triple in
4499// MachOBindEntry::moveNext() to validate a MachOBindEntry or MachORebaseEntry.
4500//
4501// Given a SegIndex, SegOffset, and PointerSize, verify a valid section exists
4502// that fully contains a pointer at that location. Multiple fixups in a bind
4503// (such as with the BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB opcode) can
4504// be tested via the Count and Skip parameters.
4505const char *BindRebaseSegInfo::checkSegAndOffsets(int32_t SegIndex,
4506 uint64_t SegOffset,
4507 uint8_t PointerSize,
4508 uint64_t Count,
4509 uint64_t Skip) {
4510 if (SegIndex == -1)
4511 return "missing preceding *_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB";
4512 if (SegIndex >= MaxSegIndex)
4513 return "bad segIndex (too large)";
4514 for (uint64_t i = 0; i < Count; ++i) {
4515 uint64_t Start = SegOffset + i * (PointerSize + Skip);
4516 uint64_t End = Start + PointerSize;
4517 bool Found = false;
4518 for (const SectionInfo &SI : Sections) {
4519 if (SI.SegmentIndex != SegIndex)
4520 continue;
4521 if ((SI.OffsetInSegment<=Start) && (Start<(SI.OffsetInSegment+SI.Size))) {
4522 if (End <= SI.OffsetInSegment + SI.Size) {
4523 Found = true;
4524 break;
4525 }
4526 else
4527 return "bad offset, extends beyond section boundary";
4528 }
4529 }
4530 if (!Found)
4531 return "bad offset, not in section";
4532 }
4533 return nullptr;
4534}
4535
4536// For use with the SegIndex of a checked Mach-O Bind or Rebase entry
4537// to get the segment name.
4539 for (const SectionInfo &SI : Sections) {
4540 if (SI.SegmentIndex == SegIndex)
4541 return SI.SegmentName;
4542 }
4543 llvm_unreachable("invalid SegIndex");
4544}
4545
4546// For use with a SegIndex,SegOffset pair from a checked Mach-O Bind or Rebase
4547// to get the SectionInfo.
4548const BindRebaseSegInfo::SectionInfo &BindRebaseSegInfo::findSection(
4549 int32_t SegIndex, uint64_t SegOffset) {
4550 for (const SectionInfo &SI : Sections) {
4551 if (SI.SegmentIndex != SegIndex)
4552 continue;
4553 if (SI.OffsetInSegment > SegOffset)
4554 continue;
4555 if (SegOffset >= (SI.OffsetInSegment + SI.Size))
4556 continue;
4557 return SI;
4558 }
4559 llvm_unreachable("SegIndex and SegOffset not in any section");
4560}
4561
4562// For use with a SegIndex,SegOffset pair from a checked Mach-O Bind or Rebase
4563// entry to get the section name.
4565 uint64_t SegOffset) {
4566 return findSection(SegIndex, SegOffset).SectionName;
4567}
4568
4569// For use with a SegIndex,SegOffset pair from a checked Mach-O Bind or Rebase
4570// entry to get the address.
4571uint64_t BindRebaseSegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) {
4572 const SectionInfo &SI = findSection(SegIndex, OffsetInSeg);
4573 return SI.SegmentStartAddress + OffsetInSeg;
4574}
4575
4577MachOObjectFile::bindTable(Error &Err, MachOObjectFile *O,
4578 ArrayRef<uint8_t> Opcodes, bool is64,
4579 MachOBindEntry::Kind BKind) {
4580 if (O->BindRebaseSectionTable == nullptr)
4581 O->BindRebaseSectionTable = std::make_unique<BindRebaseSegInfo>(O);
4582 MachOBindEntry Start(&Err, O, Opcodes, is64, BKind);
4583 Start.moveToFirst();
4584
4585 MachOBindEntry Finish(&Err, O, Opcodes, is64, BKind);
4586 Finish.moveToEnd();
4587
4588 return make_range(bind_iterator(Start), bind_iterator(Finish));
4589}
4590
4595
4600
4605
4607 if (BindRebaseSectionTable == nullptr)
4608 BindRebaseSectionTable = std::make_unique<BindRebaseSegInfo>(this);
4609
4610 MachOChainedFixupEntry Start(&Err, this, true);
4611 Start.moveToFirst();
4612
4613 MachOChainedFixupEntry Finish(&Err, this, false);
4614 Finish.moveToEnd();
4615
4616 return make_range(fixup_iterator(Start), fixup_iterator(Finish));
4617}
4618
4621 return LoadCommands.begin();
4622}
4623
4626 return LoadCommands.end();
4627}
4628
4633
4639
4642 assert(Sec.d.a < Sections.size() && "Should have detected this earlier");
4643 const section_base *Base =
4644 reinterpret_cast<const section_base *>(Sections[Sec.d.a]);
4645 return ArrayRef(Base->sectname);
4646}
4647
4650 assert(Sec.d.a < Sections.size() && "Should have detected this earlier");
4651 const section_base *Base =
4652 reinterpret_cast<const section_base *>(Sections[Sec.d.a]);
4653 return ArrayRef(Base->segname);
4654}
4655
4656bool
4663
4665 const MachO::any_relocation_info &RE) const {
4666 if (isLittleEndian())
4667 return RE.r_word1 & 0xffffff;
4668 return RE.r_word1 >> 8;
4669}
4670
4672 const MachO::any_relocation_info &RE) const {
4673 if (isLittleEndian())
4674 return (RE.r_word1 >> 27) & 1;
4675 return (RE.r_word1 >> 4) & 1;
4676}
4677
4679 const MachO::any_relocation_info &RE) const {
4680 return RE.r_word0 >> 31;
4681}
4682
4687
4689 const MachO::any_relocation_info &RE) const {
4690 return (RE.r_word0 >> 24) & 0xf;
4691}
4692
4699
4701 const MachO::any_relocation_info &RE) const {
4702 if (isRelocationScattered(RE))
4703 return getScatteredRelocationPCRel(RE);
4704 return getPlainRelocationPCRel(*this, RE);
4705}
4706
4708 const MachO::any_relocation_info &RE) const {
4709 if (isRelocationScattered(RE))
4711 return getPlainRelocationLength(*this, RE);
4712}
4713
4714unsigned
4721
4724 const MachO::any_relocation_info &RE) const {
4726 return *section_end();
4727 unsigned SecNum = getPlainRelocationSymbolNum(RE);
4728 if (SecNum == MachO::R_ABS || SecNum > Sections.size())
4729 return *section_end();
4730 DataRefImpl DRI;
4731 DRI.d.a = SecNum - 1;
4732 return SectionRef(DRI, this);
4733}
4734
4736 assert(DRI.d.a < Sections.size() && "Should have detected this earlier");
4737 return getStruct<MachO::section>(*this, Sections[DRI.d.a]);
4738}
4739
4741 assert(DRI.d.a < Sections.size() && "Should have detected this earlier");
4742 return getStruct<MachO::section_64>(*this, Sections[DRI.d.a]);
4743}
4744
4746 unsigned Index) const {
4747 const char *Sec = getSectionPtr(*this, L, Index);
4748 return getStruct<MachO::section>(*this, Sec);
4749}
4750
4752 unsigned Index) const {
4753 const char *Sec = getSectionPtr(*this, L, Index);
4754 return getStruct<MachO::section_64>(*this, Sec);
4755}
4756
4759 const char *P = reinterpret_cast<const char *>(DRI.p);
4760 return getStruct<MachO::nlist>(*this, P);
4761}
4762
4765 const char *P = reinterpret_cast<const char *>(DRI.p);
4766 return getStruct<MachO::nlist_64>(*this, P);
4767}
4768
4773
4778
4783
4788
4793
4798
4803
4808
4811 return getStruct<MachO::build_tool_version>(*this, BuildTools[index]);
4812}
4813
4818
4823
4828
4831 return getStruct<MachO::uuid_command>(*this, L.Ptr);
4832}
4833
4838
4843
4848
4853
4858
4863
4868
4873
4878
4883
4888
4893
4898
4902 if (getHeader().filetype == MachO::MH_OBJECT) {
4903 DataRefImpl Sec;
4904 Sec.d.a = Rel.d.a;
4905 if (is64Bit()) {
4906 MachO::section_64 Sect = getSection64(Sec);
4907 Offset = Sect.reloff;
4908 } else {
4909 MachO::section Sect = getSection(Sec);
4910 Offset = Sect.reloff;
4911 }
4912 } else {
4914 if (Rel.d.a == 0)
4915 Offset = DysymtabLoadCmd.extreloff; // Offset to the external relocations
4916 else
4917 Offset = DysymtabLoadCmd.locreloff; // Offset to the local relocations
4918 }
4919
4920 auto P = reinterpret_cast<const MachO::any_relocation_info *>(
4921 getPtr(*this, Offset)) + Rel.d.b;
4923 *this, reinterpret_cast<const char *>(P));
4924}
4925
4928 const char *P = reinterpret_cast<const char *>(Rel.p);
4930}
4931
4933 return Header;
4934}
4935
4937 assert(is64Bit());
4938 return Header64;
4939}
4940
4942 const MachO::dysymtab_command &DLC,
4943 unsigned Index) const {
4944 uint64_t Offset = DLC.indirectsymoff + Index * sizeof(uint32_t);
4945 return getStruct<uint32_t>(*this, getPtr(*this, Offset));
4946}
4947
4950 unsigned Index) const {
4951 uint64_t Offset = DataOffset + Index * sizeof(MachO::data_in_code_entry);
4952 return getStruct<MachO::data_in_code_entry>(*this, getPtr(*this, Offset));
4953}
4954
4956 if (SymtabLoadCmd)
4957 return getStruct<MachO::symtab_command>(*this, SymtabLoadCmd);
4958
4959 // If there is no SymtabLoadCmd return a load command with zero'ed fields.
4961 Cmd.cmd = MachO::LC_SYMTAB;
4962 Cmd.cmdsize = sizeof(MachO::symtab_command);
4963 Cmd.symoff = 0;
4964 Cmd.nsyms = 0;
4965 Cmd.stroff = 0;
4966 Cmd.strsize = 0;
4967 return Cmd;
4968}
4969
4971 if (DysymtabLoadCmd)
4972 return getStruct<MachO::dysymtab_command>(*this, DysymtabLoadCmd);
4973
4974 // If there is no DysymtabLoadCmd return a load command with zero'ed fields.
4976 Cmd.cmd = MachO::LC_DYSYMTAB;
4977 Cmd.cmdsize = sizeof(MachO::dysymtab_command);
4978 Cmd.ilocalsym = 0;
4979 Cmd.nlocalsym = 0;
4980 Cmd.iextdefsym = 0;
4981 Cmd.nextdefsym = 0;
4982 Cmd.iundefsym = 0;
4983 Cmd.nundefsym = 0;
4984 Cmd.tocoff = 0;
4985 Cmd.ntoc = 0;
4986 Cmd.modtaboff = 0;
4987 Cmd.nmodtab = 0;
4988 Cmd.extrefsymoff = 0;
4989 Cmd.nextrefsyms = 0;
4990 Cmd.indirectsymoff = 0;
4991 Cmd.nindirectsyms = 0;
4992 Cmd.extreloff = 0;
4993 Cmd.nextrel = 0;
4994 Cmd.locreloff = 0;
4995 Cmd.nlocrel = 0;
4996 return Cmd;
4997}
4998
5001 if (DataInCodeLoadCmd)
5002 return getStruct<MachO::linkedit_data_command>(*this, DataInCodeLoadCmd);
5003
5004 // If there is no DataInCodeLoadCmd return a load command with zero'ed fields.
5006 Cmd.cmd = MachO::LC_DATA_IN_CODE;
5008 Cmd.dataoff = 0;
5009 Cmd.datasize = 0;
5010 return Cmd;
5011}
5012
5015 if (LinkOptHintsLoadCmd)
5016 return getStruct<MachO::linkedit_data_command>(*this, LinkOptHintsLoadCmd);
5017
5018 // If there is no LinkOptHintsLoadCmd return a load command with zero'ed
5019 // fields.
5021 Cmd.cmd = MachO::LC_LINKER_OPTIMIZATION_HINT;
5023 Cmd.dataoff = 0;
5024 Cmd.datasize = 0;
5025 return Cmd;
5026}
5027
5029 if (!DyldInfoLoadCmd)
5030 return {};
5031
5032 auto DyldInfoOrErr =
5033 getStructOrErr<MachO::dyld_info_command>(*this, DyldInfoLoadCmd);
5034 if (!DyldInfoOrErr)
5035 return {};
5036 MachO::dyld_info_command DyldInfo = DyldInfoOrErr.get();
5037 const uint8_t *Ptr =
5038 reinterpret_cast<const uint8_t *>(getPtr(*this, DyldInfo.rebase_off));
5039 return ArrayRef(Ptr, DyldInfo.rebase_size);
5040}
5041
5043 if (!DyldInfoLoadCmd)
5044 return {};
5045
5046 auto DyldInfoOrErr =
5047 getStructOrErr<MachO::dyld_info_command>(*this, DyldInfoLoadCmd);
5048 if (!DyldInfoOrErr)
5049 return {};
5050 MachO::dyld_info_command DyldInfo = DyldInfoOrErr.get();
5051 const uint8_t *Ptr =
5052 reinterpret_cast<const uint8_t *>(getPtr(*this, DyldInfo.bind_off));
5053 return ArrayRef(Ptr, DyldInfo.bind_size);
5054}
5055
5057 if (!DyldInfoLoadCmd)
5058 return {};
5059
5060 auto DyldInfoOrErr =
5061 getStructOrErr<MachO::dyld_info_command>(*this, DyldInfoLoadCmd);
5062 if (!DyldInfoOrErr)
5063 return {};
5064 MachO::dyld_info_command DyldInfo = DyldInfoOrErr.get();
5065 const uint8_t *Ptr =
5066 reinterpret_cast<const uint8_t *>(getPtr(*this, DyldInfo.weak_bind_off));
5067 return ArrayRef(Ptr, DyldInfo.weak_bind_size);
5068}
5069
5071 if (!DyldInfoLoadCmd)
5072 return {};
5073
5074 auto DyldInfoOrErr =
5075 getStructOrErr<MachO::dyld_info_command>(*this, DyldInfoLoadCmd);
5076 if (!DyldInfoOrErr)
5077 return {};
5078 MachO::dyld_info_command DyldInfo = DyldInfoOrErr.get();
5079 const uint8_t *Ptr =
5080 reinterpret_cast<const uint8_t *>(getPtr(*this, DyldInfo.lazy_bind_off));
5081 return ArrayRef(Ptr, DyldInfo.lazy_bind_size);
5082}
5083
5085 if (!DyldInfoLoadCmd)
5086 return {};
5087
5088 auto DyldInfoOrErr =
5089 getStructOrErr<MachO::dyld_info_command>(*this, DyldInfoLoadCmd);
5090 if (!DyldInfoOrErr)
5091 return {};
5092 MachO::dyld_info_command DyldInfo = DyldInfoOrErr.get();
5093 const uint8_t *Ptr =
5094 reinterpret_cast<const uint8_t *>(getPtr(*this, DyldInfo.export_off));
5095 return ArrayRef(Ptr, DyldInfo.export_size);
5096}
5097
5100 // Load the dyld chained fixups load command.
5101 if (!DyldChainedFixupsLoadCmd)
5102 return std::nullopt;
5103 auto DyldChainedFixupsOrErr = getStructOrErr<MachO::linkedit_data_command>(
5104 *this, DyldChainedFixupsLoadCmd);
5105 if (!DyldChainedFixupsOrErr)
5106 return DyldChainedFixupsOrErr.takeError();
5107 const MachO::linkedit_data_command &DyldChainedFixups =
5108 *DyldChainedFixupsOrErr;
5109
5110 // If the load command is present but the data offset has been zeroed out,
5111 // as is the case for dylib stubs, return std::nullopt (no error).
5112 if (!DyldChainedFixups.dataoff)
5113 return std::nullopt;
5114 return DyldChainedFixups;
5115}
5116
5119 auto CFOrErr = getChainedFixupsLoadCommand();
5120 if (!CFOrErr)
5121 return CFOrErr.takeError();
5122 if (!CFOrErr->has_value())
5123 return std::nullopt;
5124
5125 const MachO::linkedit_data_command &DyldChainedFixups = **CFOrErr;
5126
5127 uint64_t CFHeaderOffset = DyldChainedFixups.dataoff;
5128 uint64_t CFSize = DyldChainedFixups.datasize;
5129
5130 // Load the dyld chained fixups header.
5131 const char *CFHeaderPtr = getPtr(*this, CFHeaderOffset);
5132 auto CFHeaderOrErr =
5134 if (!CFHeaderOrErr)
5135 return CFHeaderOrErr.takeError();
5136 MachO::dyld_chained_fixups_header CFHeader = CFHeaderOrErr.get();
5137
5138 // Reject unknown chained fixup formats.
5139 if (CFHeader.fixups_version != 0)
5140 return malformedError(Twine("bad chained fixups: unknown version: ") +
5141 Twine(CFHeader.fixups_version));
5142 if (CFHeader.imports_format < 1 || CFHeader.imports_format > 3)
5143 return malformedError(
5144 Twine("bad chained fixups: unknown imports format: ") +
5145 Twine(CFHeader.imports_format));
5146
5147 // Validate the image format.
5148 //
5149 // Load the image starts.
5150 uint64_t CFImageStartsOffset = (CFHeaderOffset + CFHeader.starts_offset);
5151 if (CFHeader.starts_offset < sizeof(MachO::dyld_chained_fixups_header)) {
5152 return malformedError(Twine("bad chained fixups: image starts offset ") +
5153 Twine(CFHeader.starts_offset) +
5154 " overlaps with chained fixups header");
5155 }
5156 uint32_t EndOffset = CFHeaderOffset + CFSize;
5157 if (CFImageStartsOffset + sizeof(MachO::dyld_chained_starts_in_image) >
5158 EndOffset) {
5159 return malformedError(Twine("bad chained fixups: image starts end ") +
5160 Twine(CFImageStartsOffset +
5162 " extends past end " + Twine(EndOffset));
5163 }
5164
5165 return CFHeader;
5166}
5167
5170 auto CFOrErr = getChainedFixupsLoadCommand();
5171 if (!CFOrErr)
5172 return CFOrErr.takeError();
5173
5174 std::vector<ChainedFixupsSegment> Segments;
5175 if (!CFOrErr->has_value())
5176 return std::make_pair(0, Segments);
5177
5178 const MachO::linkedit_data_command &DyldChainedFixups = **CFOrErr;
5179
5180 auto HeaderOrErr = getChainedFixupsHeader();
5181 if (!HeaderOrErr)
5182 return HeaderOrErr.takeError();
5183 if (!HeaderOrErr->has_value())
5184 return std::make_pair(0, Segments);
5185 const MachO::dyld_chained_fixups_header &Header = **HeaderOrErr;
5186
5187 const char *Contents = getPtr(*this, DyldChainedFixups.dataoff);
5188
5190 *this, Contents + Header.starts_offset);
5191 if (!ImageStartsOrErr)
5192 return ImageStartsOrErr.takeError();
5193 const MachO::dyld_chained_starts_in_image &ImageStarts = *ImageStartsOrErr;
5194
5195 const char *SegOffsPtr =
5196 Contents + Header.starts_offset +
5198 const char *SegOffsEnd =
5199 SegOffsPtr + ImageStarts.seg_count * sizeof(uint32_t);
5200 if (SegOffsEnd > Contents + DyldChainedFixups.datasize)
5201 return malformedError(
5202 "bad chained fixups: seg_info_offset extends past end");
5203
5204 const char *LastSegEnd = nullptr;
5205 for (size_t I = 0, N = ImageStarts.seg_count; I < N; ++I) {
5206 auto OffOrErr =
5207 getStructOrErr<uint32_t>(*this, SegOffsPtr + I * sizeof(uint32_t));
5208 if (!OffOrErr)
5209 return OffOrErr.takeError();
5210 // seg_info_offset == 0 means there is no associated starts_in_segment
5211 // entry.
5212 if (!*OffOrErr)
5213 continue;
5214
5215 auto Fail = [&](Twine Message) {
5216 return malformedError("bad chained fixups: segment info" + Twine(I) +
5217 " at offset " + Twine(*OffOrErr) + Message);
5218 };
5219
5220 const char *SegPtr = Contents + Header.starts_offset + *OffOrErr;
5221 if (LastSegEnd && SegPtr < LastSegEnd)
5222 return Fail(" overlaps with previous segment info");
5223
5224 auto SegOrErr =
5226 if (!SegOrErr)
5227 return SegOrErr.takeError();
5228 const MachO::dyld_chained_starts_in_segment &Seg = *SegOrErr;
5229
5230 LastSegEnd = SegPtr + Seg.size;
5231 if (Seg.pointer_format < 1 || Seg.pointer_format > 12)
5232 return Fail(" has unknown pointer format: " + Twine(Seg.pointer_format));
5233
5234 const char *PageStart =
5235 SegPtr + offsetof(MachO::dyld_chained_starts_in_segment, page_start);
5236 const char *PageEnd = PageStart + Seg.page_count * sizeof(uint16_t);
5237 if (PageEnd > SegPtr + Seg.size)
5238 return Fail(" : page_starts extend past seg_info size");
5239
5240 // FIXME: This does not account for multiple offsets on a single page
5241 // (DYLD_CHAINED_PTR_START_MULTI; 32-bit only).
5242 std::vector<uint16_t> PageStarts;
5243 for (size_t PageIdx = 0; PageIdx < Seg.page_count; ++PageIdx) {
5244 uint16_t Start;
5245 memcpy(&Start, PageStart + PageIdx * sizeof(uint16_t), sizeof(uint16_t));
5247 sys::swapByteOrder(Start);
5248 PageStarts.push_back(Start);
5249 }
5250
5251 Segments.emplace_back(I, *OffOrErr, Seg, std::move(PageStarts));
5252 }
5253
5254 return std::make_pair(ImageStarts.seg_count, Segments);
5255}
5256
5257// The special library ordinals have a negative value, but they are encoded in
5258// an unsigned bitfield, so we need to sign extend the value.
5259template <typename T> static int getEncodedOrdinal(T Value) {
5260 if (Value == static_cast<T>(MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE) ||
5264 return Value;
5265}
5266
5267template <typename T, unsigned N>
5268static std::array<T, N> getArray(const MachOObjectFile &O, const void *Ptr) {
5269 std::array<T, N> RawValue;
5270 memcpy(RawValue.data(), Ptr, N * sizeof(T));
5271 if (O.isLittleEndian() != sys::IsLittleEndianHost)
5272 for (auto &Element : RawValue)
5273 sys::swapByteOrder(Element);
5274 return RawValue;
5275}
5276
5277Expected<std::vector<ChainedFixupTarget>>
5279 auto CFOrErr = getChainedFixupsLoadCommand();
5280 if (!CFOrErr)
5281 return CFOrErr.takeError();
5282
5283 std::vector<ChainedFixupTarget> Targets;
5284 if (!CFOrErr->has_value())
5285 return Targets;
5286
5287 const MachO::linkedit_data_command &DyldChainedFixups = **CFOrErr;
5288
5289 auto CFHeaderOrErr = getChainedFixupsHeader();
5290 if (!CFHeaderOrErr)
5291 return CFHeaderOrErr.takeError();
5292 if (!(*CFHeaderOrErr))
5293 return Targets;
5294 const MachO::dyld_chained_fixups_header &Header = **CFHeaderOrErr;
5295
5296 size_t ImportSize = 0;
5297 if (Header.imports_format == MachO::DYLD_CHAINED_IMPORT)
5298 ImportSize = sizeof(MachO::dyld_chained_import);
5299 else if (Header.imports_format == MachO::DYLD_CHAINED_IMPORT_ADDEND)
5300 ImportSize = sizeof(MachO::dyld_chained_import_addend);
5301 else if (Header.imports_format == MachO::DYLD_CHAINED_IMPORT_ADDEND64)
5302 ImportSize = sizeof(MachO::dyld_chained_import_addend64);
5303 else
5304 return malformedError("bad chained fixups: unknown imports format: " +
5305 Twine(Header.imports_format));
5306
5307 const char *Contents = getPtr(*this, DyldChainedFixups.dataoff);
5308 const char *Imports = Contents + Header.imports_offset;
5309 size_t ImportsEndOffset =
5310 Header.imports_offset + ImportSize * Header.imports_count;
5311 const char *ImportsEnd = Contents + ImportsEndOffset;
5312 const char *Symbols = Contents + Header.symbols_offset;
5313 const char *SymbolsEnd = Contents + DyldChainedFixups.datasize;
5314
5315 if (ImportsEnd > Symbols)
5316 return malformedError("bad chained fixups: imports end " +
5317 Twine(ImportsEndOffset) + " overlaps with symbols");
5318
5319 // We use bit manipulation to extract data from the bitfields. This is correct
5320 // for both LE and BE hosts, but we assume that the object is little-endian.
5321 if (!isLittleEndian())
5322 return createError("parsing big-endian chained fixups is not implemented");
5323 for (const char *ImportPtr = Imports; ImportPtr < ImportsEnd;
5324 ImportPtr += ImportSize) {
5325 int LibOrdinal;
5326 bool WeakImport;
5327 uint32_t NameOffset;
5328 uint64_t Addend;
5329 if (Header.imports_format == MachO::DYLD_CHAINED_IMPORT) {
5330 static_assert(sizeof(uint32_t) == sizeof(MachO::dyld_chained_import));
5331 auto RawValue = getArray<uint32_t, 1>(*this, ImportPtr);
5332
5333 LibOrdinal = getEncodedOrdinal<uint8_t>(RawValue[0] & 0xFF);
5334 WeakImport = (RawValue[0] >> 8) & 1;
5335 NameOffset = RawValue[0] >> 9;
5336 Addend = 0;
5337 } else if (Header.imports_format == MachO::DYLD_CHAINED_IMPORT_ADDEND) {
5338 static_assert(sizeof(uint64_t) ==
5340 auto RawValue = getArray<uint32_t, 2>(*this, ImportPtr);
5341
5342 LibOrdinal = getEncodedOrdinal<uint8_t>(RawValue[0] & 0xFF);
5343 WeakImport = (RawValue[0] >> 8) & 1;
5344 NameOffset = RawValue[0] >> 9;
5345 Addend = bit_cast<int32_t>(RawValue[1]);
5346 } else if (Header.imports_format == MachO::DYLD_CHAINED_IMPORT_ADDEND64) {
5347 static_assert(2 * sizeof(uint64_t) ==
5349 auto RawValue = getArray<uint64_t, 2>(*this, ImportPtr);
5350
5351 LibOrdinal = getEncodedOrdinal<uint16_t>(RawValue[0] & 0xFFFF);
5352 NameOffset = (RawValue[0] >> 16) & 1;
5353 WeakImport = RawValue[0] >> 17;
5354 Addend = RawValue[1];
5355 } else {
5356 llvm_unreachable("Import format should have been checked");
5357 }
5358
5359 const char *Str = Symbols + NameOffset;
5360 if (Str >= SymbolsEnd)
5361 return malformedError("bad chained fixups: symbol offset " +
5362 Twine(NameOffset) + " extends past end " +
5363 Twine(DyldChainedFixups.datasize));
5364 Targets.emplace_back(LibOrdinal, NameOffset, Str, Addend, WeakImport);
5365 }
5366
5367 return std::move(Targets);
5368}
5369
5371 if (!DyldExportsTrieLoadCmd)
5372 return {};
5373
5374 auto DyldExportsTrieOrError = getStructOrErr<MachO::linkedit_data_command>(
5375 *this, DyldExportsTrieLoadCmd);
5376 if (!DyldExportsTrieOrError)
5377 return {};
5378 MachO::linkedit_data_command DyldExportsTrie = DyldExportsTrieOrError.get();
5379 const uint8_t *Ptr =
5380 reinterpret_cast<const uint8_t *>(getPtr(*this, DyldExportsTrie.dataoff));
5381 return ArrayRef(Ptr, DyldExportsTrie.datasize);
5382}
5383
5385 if (!FuncStartsLoadCmd)
5386 return {};
5387
5388 auto InfoOrErr =
5389 getStructOrErr<MachO::linkedit_data_command>(*this, FuncStartsLoadCmd);
5390 if (!InfoOrErr)
5391 return {};
5392
5393 MachO::linkedit_data_command Info = InfoOrErr.get();
5394 SmallVector<uint64_t, 8> FunctionStarts;
5395 this->ReadULEB128s(Info.dataoff, FunctionStarts);
5396 return std::move(FunctionStarts);
5397}
5398
5400 if (!UuidLoadCmd)
5401 return {};
5402 // Returning a pointer is fine as uuid doesn't need endian swapping.
5403 const char *Ptr = UuidLoadCmd + offsetof(MachO::uuid_command, uuid);
5404 return ArrayRef(reinterpret_cast<const uint8_t *>(Ptr), 16);
5405}
5406
5411
5413 return getType() == getMachOType(false, true) ||
5414 getType() == getMachOType(true, true);
5415}
5416
5418 SmallVectorImpl<uint64_t> &Out) const {
5419 DataExtractor extractor(ObjectFile::getData(), true);
5420
5421 uint64_t offset = Index;
5422 uint64_t data = 0;
5423 while (uint64_t delta = extractor.getULEB128(&offset)) {
5424 data += delta;
5425 Out.push_back(data);
5426 }
5427}
5428
5432
5433/// Create a MachOObjectFile instance from a given buffer.
5434///
5435/// \param Buffer Memory buffer containing the MachO binary data.
5436/// \param UniversalCputype CPU type when the MachO part of a universal binary.
5437/// \param UniversalIndex Index of the MachO within a universal binary.
5438/// \param MachOFilesetEntryOffset Offset of the MachO entry in a fileset MachO.
5439/// \returns A std::unique_ptr to a MachOObjectFile instance on success.
5441 MemoryBufferRef Buffer, uint32_t UniversalCputype, uint32_t UniversalIndex,
5442 size_t MachOFilesetEntryOffset) {
5443 StringRef Magic = Buffer.getBuffer().slice(0, 4);
5444 if (Magic == "\xFE\xED\xFA\xCE")
5445 return MachOObjectFile::create(Buffer, false, false, UniversalCputype,
5446 UniversalIndex, MachOFilesetEntryOffset);
5447 if (Magic == "\xCE\xFA\xED\xFE")
5448 return MachOObjectFile::create(Buffer, true, false, UniversalCputype,
5449 UniversalIndex, MachOFilesetEntryOffset);
5450 if (Magic == "\xFE\xED\xFA\xCF")
5451 return MachOObjectFile::create(Buffer, false, true, UniversalCputype,
5452 UniversalIndex, MachOFilesetEntryOffset);
5453 if (Magic == "\xCF\xFA\xED\xFE")
5454 return MachOObjectFile::create(Buffer, true, true, UniversalCputype,
5455 UniversalIndex, MachOFilesetEntryOffset);
5456 return make_error<GenericBinaryError>("Unrecognized MachO magic number",
5458}
5459
5461 return StringSwitch<StringRef>(Name)
5462 .Case("debug_str_offs", "debug_str_offsets")
5463 .Default(Name);
5464}
5465
5468 SmallString<256> BundlePath(Path);
5469 // Normalize input path. This is necessary to accept `bundle.dSYM/`.
5470 sys::path::remove_dots(BundlePath);
5471 if (!sys::fs::is_directory(BundlePath) ||
5472 sys::path::extension(BundlePath) != ".dSYM")
5473 return std::vector<std::string>();
5474 sys::path::append(BundlePath, "Contents", "Resources", "DWARF");
5475 bool IsDir;
5476 auto EC = sys::fs::is_directory(BundlePath, IsDir);
5477 if (EC == errc::no_such_file_or_directory || (!EC && !IsDir))
5478 return createStringError(
5479 EC, "%s: expected directory 'Contents/Resources/DWARF' in dSYM bundle",
5480 Path.str().c_str());
5481 if (EC)
5482 return createFileError(BundlePath, errorCodeToError(EC));
5483
5484 std::vector<std::string> ObjectPaths;
5485 for (sys::fs::directory_iterator Dir(BundlePath, EC), DirEnd;
5486 Dir != DirEnd && !EC; Dir.increment(EC)) {
5487 StringRef ObjectPath = Dir->path();
5489 if (auto EC = sys::fs::status(ObjectPath, Status))
5490 return createFileError(ObjectPath, errorCodeToError(EC));
5491 switch (Status.type()) {
5495 ObjectPaths.push_back(ObjectPath.str());
5496 break;
5497 default: /*ignore*/;
5498 }
5499 }
5500 if (EC)
5501 return createFileError(BundlePath, errorCodeToError(EC));
5502 if (ObjectPaths.empty())
5503 return createStringError(std::error_code(),
5504 "%s: no objects found in dSYM bundle",
5505 Path.str().c_str());
5506 return ObjectPaths;
5507}
5508
5511 StringRef SectionName) const {
5512#define HANDLE_SWIFT_SECTION(KIND, MACHO, ELF, COFF) \
5513 .Case(MACHO, llvm::binaryformat::Swift5ReflectionSectionKind::KIND)
5516#include "llvm/BinaryFormat/Swift.def"
5518#undef HANDLE_SWIFT_SECTION
5519}
5520
5521bool MachOObjectFile::isMachOPairedReloc(uint64_t RelocType, uint64_t Arch) {
5522 switch (Arch) {
5523 case Triple::x86:
5524 return RelocType == MachO::GENERIC_RELOC_SECTDIFF ||
5526 case Triple::x86_64:
5527 return RelocType == MachO::X86_64_RELOC_SUBTRACTOR;
5528 case Triple::arm:
5529 case Triple::thumb:
5530 return RelocType == MachO::ARM_RELOC_SECTDIFF ||
5531 RelocType == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
5532 RelocType == MachO::ARM_RELOC_HALF ||
5533 RelocType == MachO::ARM_RELOC_HALF_SECTDIFF;
5534 case Triple::aarch64:
5535 return RelocType == MachO::ARM64_RELOC_SUBTRACTOR;
5536 default:
5537 return false;
5538 }
5539}
#define Fail
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
Unify divergent function exit nodes
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
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 Error checkTargetTripleCommand(const MachOObjectFile &Obj, const MachOObjectFile::LoadCommandInfo &Load, uint32_t LoadCommandIndex)
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:44
OptimizedStructLayoutField Field
#define P(N)
if(PassOpts->AAPipeline)
const char * Msg
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.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
iterator end() const
Definition ArrayRef.h:130
iterator begin() const
Definition ArrayRef.h:129
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
const T * data() const
Definition ArrayRef.h:138
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:1160
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.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
static constexpr size_t npos
Definition StringRef.h:58
std::string str() const
Get the contents as an std::string.
Definition StringRef.h:222
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition StringRef.h:597
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition StringRef.h:258
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
iterator begin() const
Definition StringRef.h:114
char back() const
Get the last character in the string.
Definition StringRef.h:153
StringRef slice(size_t Start, size_t End) const
Return a reference to the substring from [Start, End).
Definition StringRef.h:720
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
size_t rfind(char C, size_t From=npos) const
Search for the last character C in the string.
Definition StringRef.h:365
iterator end() const
Definition StringRef.h:116
size_t find(char C, size_t From=0) const
Search for the first character C in the string.
Definition StringRef.h:290
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:48
@ UnknownArch
Definition Triple.h:51
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:854
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:855
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
MachO::target_triple_command getTargetTripleLoadCommand(const LoadCommandInfo &L) 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.
const uint32_t x86_FLOAT_STATE_COUNT
Definition MachO.h:2056
@ SECTION_TYPE
Definition MachO.h:114
@ DYLD_CHAINED_IMPORT
Definition MachO.h:1090
@ DYLD_CHAINED_IMPORT_ADDEND
Definition MachO.h:1091
@ DYLD_CHAINED_IMPORT_ADDEND64
Definition MachO.h:1092
const uint32_t ARM_THREAD_STATE64_COUNT
Definition MachO.h:2134
@ 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:2058
@ ARM_THREAD_STATE64
Definition MachO.h:2121
@ ARM_THREAD_STATE
Definition MachO.h:2116
@ 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:1103
uint8_t GET_COMM_ALIGN(uint16_t n_desc)
Definition MachO.h:1614
void swapStruct(fat_header &mh)
Definition MachO.h:1203
const uint32_t x86_THREAD_STATE32_COUNT
Definition MachO.h:2044
@ 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:2241
@ CPU_SUBTYPE_POWERPC_ALL
Definition MachO.h:1758
@ 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:1115
@ DYLD_CHAINED_PTR_64
Definition MachO.h:1111
@ x86_THREAD_STATE
Definition MachO.h:2018
@ x86_THREAD_STATE64
Definition MachO.h:2015
@ x86_EXCEPTION_STATE64
Definition MachO.h:2017
@ x86_EXCEPTION_STATE
Definition MachO.h:2020
@ x86_THREAD_STATE32
Definition MachO.h:2012
@ x86_FLOAT_STATE
Definition MachO.h:2019
const uint32_t PPC_THREAD_STATE_COUNT
Definition MachO.h:2256
const uint32_t ARM_THREAD_STATE_COUNT
Definition MachO.h:2131
@ 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:1777
@ CPU_SUBTYPE_ARM_V7
Definition MachO.h:1702
@ CPU_SUBTYPE_ARM_V8M_BASE
Definition MachO.h:1710
@ CPU_SUBTYPE_ARM_V5TEJ
Definition MachO.h:1700
@ CPU_SUBTYPE_ARM_V7M
Definition MachO.h:1707
@ CPU_SUBTYPE_ARM_V6
Definition MachO.h:1698
@ CPU_SUBTYPE_ARM_V8M_MAIN
Definition MachO.h:1709
@ CPU_SUBTYPE_ARM_XSCALE
Definition MachO.h:1701
@ CPU_SUBTYPE_ARM_V7K
Definition MachO.h:1705
@ CPU_SUBTYPE_ARM_V6M
Definition MachO.h:1706
@ CPU_SUBTYPE_ARM_V7EM
Definition MachO.h:1708
@ CPU_SUBTYPE_ARM_V8_1M_MAIN
Definition MachO.h:1711
@ CPU_SUBTYPE_ARM_V7S
Definition MachO.h:1704
@ CPU_SUBTYPE_ARM_V4T
Definition MachO.h:1697
@ CPU_SUBTYPE_ARM64E
Definition MachO.h:1717
@ CPU_SUBTYPE_ARM64_ALL
Definition MachO.h:1715
@ CPU_SUBTYPE_ARM64E_X1
Definition MachO.h:1718
const uint32_t x86_THREAD_STATE_COUNT
Definition MachO.h:2054
@ CPU_SUBTYPE_ARM64_32_V8
Definition MachO.h:1753
@ GENERIC_RELOC_LOCAL_SECTDIFF
Definition MachO.h:414
@ RISCV_RELOC_GOT_HI20
Definition MachO.h:522
@ ARM_RELOC_LOCAL_SECTDIFF
Definition MachO.h:443
@ RISCV_RELOC_HI20
Definition MachO.h:505
@ RISCV_RELOC_GOT_LO12
Definition MachO.h:525
@ ARM64_RELOC_SUBTRACTOR
Definition MachO.h:458
@ ARM_RELOC_HALF_SECTDIFF
Definition MachO.h:449
@ ARM_RELOC_SECTDIFF
Definition MachO.h:442
@ RISCV_RELOC_LO12
Definition MachO.h:516
@ GENERIC_RELOC_SECTDIFF
Definition MachO.h:412
@ X86_64_RELOC_SUBTRACTOR
Definition MachO.h:545
@ ARM_RELOC_HALF
Definition MachO.h:448
uint16_t GET_LIBRARY_ORDINAL(uint16_t n_desc)
Definition MachO.h:1606
@ 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:2051
@ CPU_SUBTYPE_I386_ALL
Definition MachO.h:1659
@ CPU_SUBTYPE_X86_64_H
Definition MachO.h:1684
@ CPU_SUBTYPE_X86_64_ALL
Definition MachO.h:1682
const uint32_t x86_THREAD_STATE64_COUNT
Definition MachO.h:2047
@ CPU_SUBTYPE_MASK
Definition MachO.h:1650
@ CPU_TYPE_ARM64_32
Definition MachO.h:1640
@ CPU_TYPE_ARM64
Definition MachO.h:1639
@ CPU_TYPE_POWERPC
Definition MachO.h:1642
@ CPU_TYPE_X86_64
Definition MachO.h:1635
@ CPU_TYPE_POWERPC64
Definition MachO.h:1643
@ CPU_TYPE_RISCV
Definition MachO.h:1645
@ CPU_TYPE_I386
Definition MachO.h:1634
@ CPU_TYPE_ARM
Definition MachO.h:1638
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:1122
LLVM_ABI bool remove_dots(SmallVectorImpl< char > &path, bool remove_dot_dot=false, Style style=Style::native)
Remove '.
Definition Path.cpp:779
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:467
LLVM_ABI StringRef extension(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get extension.
Definition Path.cpp:607
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.
@ Offset
Definition DWP.cpp:577
Error createFileError(const Twine &F, Error E)
Concatenate a source file path and/or name with an Error.
Definition Error.h:1415
ArrayRef< CharT > arrayRefFromStringRef(StringRef Input)
Construct an array ref of bytes from a string ref.
@ Done
Definition Threading.h:60
@ Load
The value being inserted comes from a load (InsertElement only).
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:169
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition Error.h:1321
@ 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:209
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition Format.h:102
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
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
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:2012
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:549
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1947
LLVM_ABI Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
Definition Error.cpp:107
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
Definition InstrProf.h:147
void consumeError(Error Err)
Consume a Error without doing anything.
Definition Error.h:1106
#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:865
Structs for dyld chained fixups.
Definition MachO.h:1127
uint32_t imports_format
DYLD_CHAINED_IMPORT*.
Definition MachO.h:1133
uint32_t starts_offset
Offset of dyld_chained_starts_in_image.
Definition MachO.h:1129
dyld_chained_starts_in_image is embedded in LC_DYLD_CHAINED_FIXUPS payload.
Definition MachO.h:1140
uint16_t page_count
Length of the page_start array.
Definition MachO.h:1151
uint16_t page_size
Page size in bytes (0x1000 or 0x4000)
Definition MachO.h:1147
uint16_t pointer_format
DYLD_CHAINED_PTR*.
Definition MachO.h:1148
uint32_t size
Size of this, including chain_starts entries.
Definition MachO.h:1146
Definition MachO.h:962
uint32_t n_strx
Definition MachO.h:1073
uint32_t n_value
Definition MachO.h:1077
uint32_t reloff
Definition MachO.h:630
uint32_t offset
Definition MachO.h:628
uint32_t nreloc
Definition MachO.h:631
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