LLVM 17.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 assert(Offset <= O.getData().size());
113 return O.getData().data() + Offset;
114}
115
118 const char *P = reinterpret_cast<const char *>(DRI.p);
119 return getStruct<MachO::nlist_base>(O, P);
120}
121
123 if (P[15] == 0)
124 // Null terminated.
125 return P;
126 // Not null terminated, so this is a 16 char string.
127 return StringRef(P, 16);
128}
129
130static unsigned getCPUType(const MachOObjectFile &O) {
131 return O.getHeader().cputype;
132}
133
134static unsigned getCPUSubType(const MachOObjectFile &O) {
135 return O.getHeader().cpusubtype;
136}
137
138static uint32_t
140 return RE.r_word0;
141}
142
143static unsigned
145 return RE.r_word0 & 0xffffff;
146}
147
149 const MachO::any_relocation_info &RE) {
150 if (O.isLittleEndian())
151 return (RE.r_word1 >> 24) & 1;
152 return (RE.r_word1 >> 7) & 1;
153}
154
155static bool
157 return (RE.r_word0 >> 30) & 1;
158}
159
161 const MachO::any_relocation_info &RE) {
162 if (O.isLittleEndian())
163 return (RE.r_word1 >> 25) & 3;
164 return (RE.r_word1 >> 5) & 3;
165}
166
167static unsigned
169 return (RE.r_word0 >> 28) & 3;
170}
171
173 const MachO::any_relocation_info &RE) {
174 if (O.isLittleEndian())
175 return RE.r_word1 >> 28;
176 return RE.r_word1 & 0xf;
177}
178
180 DataRefImpl Sec) {
181 if (O.is64Bit()) {
182 MachO::section_64 Sect = O.getSection64(Sec);
183 return Sect.flags;
184 }
185 MachO::section Sect = O.getSection(Sec);
186 return Sect.flags;
187}
188
190getLoadCommandInfo(const MachOObjectFile &Obj, const char *Ptr,
191 uint32_t LoadCommandIndex) {
192 if (auto CmdOrErr = getStructOrErr<MachO::load_command>(Obj, Ptr)) {
193 if (CmdOrErr->cmdsize + Ptr > Obj.getData().end())
194 return malformedError("load command " + Twine(LoadCommandIndex) +
195 " extends past end of file");
196 if (CmdOrErr->cmdsize < 8)
197 return malformedError("load command " + Twine(LoadCommandIndex) +
198 " with size less than 8 bytes");
199 return MachOObjectFile::LoadCommandInfo({Ptr, *CmdOrErr});
200 } else
201 return CmdOrErr.takeError();
202}
203
206 unsigned HeaderSize = Obj.is64Bit() ? sizeof(MachO::mach_header_64)
207 : sizeof(MachO::mach_header);
208 if (sizeof(MachO::load_command) > Obj.getHeader().sizeofcmds)
209 return malformedError("load command 0 extends past the end all load "
210 "commands in the file");
211 return getLoadCommandInfo(Obj, getPtr(Obj, HeaderSize), 0);
212}
213
217 unsigned HeaderSize = Obj.is64Bit() ? sizeof(MachO::mach_header_64)
218 : sizeof(MachO::mach_header);
219 if (L.Ptr + L.C.cmdsize + sizeof(MachO::load_command) >
220 Obj.getData().data() + HeaderSize + Obj.getHeader().sizeofcmds)
221 return malformedError("load command " + Twine(LoadCommandIndex + 1) +
222 " extends past the end all load commands in the file");
223 return getLoadCommandInfo(Obj, L.Ptr + L.C.cmdsize, LoadCommandIndex + 1);
224}
225
226template <typename T>
227static void parseHeader(const MachOObjectFile &Obj, T &Header,
228 Error &Err) {
229 if (sizeof(T) > Obj.getData().size()) {
230 Err = malformedError("the mach header extends past the end of the "
231 "file");
232 return;
233 }
234 if (auto HeaderOrErr = getStructOrErr<T>(Obj, getPtr(Obj, 0)))
235 Header = *HeaderOrErr;
236 else
237 Err = HeaderOrErr.takeError();
238}
239
240// This is used to check for overlapping of Mach-O elements.
244 const char *Name;
245};
246
247static Error checkOverlappingElement(std::list<MachOElement> &Elements,
249 const char *Name) {
250 if (Size == 0)
251 return Error::success();
252
253 for (auto it = Elements.begin(); it != Elements.end(); ++it) {
254 const auto &E = *it;
255 if ((Offset >= E.Offset && Offset < E.Offset + E.Size) ||
256 (Offset + Size > E.Offset && Offset + Size < E.Offset + E.Size) ||
257 (Offset <= E.Offset && Offset + Size >= E.Offset + E.Size))
258 return malformedError(Twine(Name) + " at offset " + Twine(Offset) +
259 " with a size of " + Twine(Size) + ", overlaps " +
260 E.Name + " at offset " + Twine(E.Offset) + " with "
261 "a size of " + Twine(E.Size));
262 auto nt = it;
263 nt++;
264 if (nt != Elements.end()) {
265 const auto &N = *nt;
266 if (Offset + Size <= N.Offset) {
267 Elements.insert(nt, {Offset, Size, Name});
268 return Error::success();
269 }
270 }
271 }
272 Elements.push_back({Offset, Size, Name});
273 return Error::success();
274}
275
276// Parses LC_SEGMENT or LC_SEGMENT_64 load command, adds addresses of all
277// sections to \param Sections, and optionally sets
278// \param IsPageZeroSegment to true.
279template <typename Segment, typename Section>
282 SmallVectorImpl<const char *> &Sections, bool &IsPageZeroSegment,
283 uint32_t LoadCommandIndex, const char *CmdName, uint64_t SizeOfHeaders,
284 std::list<MachOElement> &Elements) {
285 const unsigned SegmentLoadSize = sizeof(Segment);
286 if (Load.C.cmdsize < SegmentLoadSize)
287 return malformedError("load command " + Twine(LoadCommandIndex) +
288 " " + CmdName + " cmdsize too small");
289 if (auto SegOrErr = getStructOrErr<Segment>(Obj, Load.Ptr)) {
290 Segment S = SegOrErr.get();
291 const unsigned SectionSize = sizeof(Section);
292 uint64_t FileSize = Obj.getData().size();
293 if (S.nsects > std::numeric_limits<uint32_t>::max() / SectionSize ||
294 S.nsects * SectionSize > Load.C.cmdsize - SegmentLoadSize)
295 return malformedError("load command " + Twine(LoadCommandIndex) +
296 " inconsistent cmdsize in " + CmdName +
297 " for the number of sections");
298 for (unsigned J = 0; J < S.nsects; ++J) {
299 const char *Sec = getSectionPtr(Obj, Load, J);
300 Sections.push_back(Sec);
301 auto SectionOrErr = getStructOrErr<Section>(Obj, Sec);
302 if (!SectionOrErr)
303 return SectionOrErr.takeError();
304 Section s = SectionOrErr.get();
307 s.flags != MachO::S_ZEROFILL &&
309 s.offset > FileSize)
310 return malformedError("offset field of section " + Twine(J) + " in " +
311 CmdName + " command " + Twine(LoadCommandIndex) +
312 " extends past the end of the file");
315 s.flags != MachO::S_ZEROFILL &&
316 s.flags != MachO::S_THREAD_LOCAL_ZEROFILL && S.fileoff == 0 &&
317 s.offset < SizeOfHeaders && s.size != 0)
318 return malformedError("offset field of section " + Twine(J) + " in " +
319 CmdName + " command " + Twine(LoadCommandIndex) +
320 " not past the headers of the file");
321 uint64_t BigSize = s.offset;
322 BigSize += s.size;
325 s.flags != MachO::S_ZEROFILL &&
327 BigSize > FileSize)
328 return malformedError("offset field plus size field of section " +
329 Twine(J) + " in " + CmdName + " command " +
330 Twine(LoadCommandIndex) +
331 " extends past the end of the file");
334 s.flags != MachO::S_ZEROFILL &&
336 s.size > S.filesize)
337 return malformedError("size field of section " +
338 Twine(J) + " in " + CmdName + " command " +
339 Twine(LoadCommandIndex) +
340 " greater than the segment");
342 Obj.getHeader().filetype != MachO::MH_DSYM && s.size != 0 &&
343 s.addr < S.vmaddr)
344 return malformedError("addr field of section " + Twine(J) + " in " +
345 CmdName + " command " + Twine(LoadCommandIndex) +
346 " less than the segment's vmaddr");
347 BigSize = s.addr;
348 BigSize += s.size;
349 uint64_t BigEnd = S.vmaddr;
350 BigEnd += S.vmsize;
351 if (S.vmsize != 0 && s.size != 0 && BigSize > BigEnd)
352 return malformedError("addr field plus size of section " + Twine(J) +
353 " in " + CmdName + " command " +
354 Twine(LoadCommandIndex) +
355 " greater than than "
356 "the segment's vmaddr plus vmsize");
359 s.flags != MachO::S_ZEROFILL &&
361 if (Error Err = checkOverlappingElement(Elements, s.offset, s.size,
362 "section contents"))
363 return Err;
364 if (s.reloff > FileSize)
365 return malformedError("reloff field of section " + Twine(J) + " in " +
366 CmdName + " command " + Twine(LoadCommandIndex) +
367 " extends past the end of the file");
368 BigSize = s.nreloc;
369 BigSize *= sizeof(struct MachO::relocation_info);
370 BigSize += s.reloff;
371 if (BigSize > FileSize)
372 return malformedError("reloff field plus nreloc field times sizeof("
373 "struct relocation_info) of section " +
374 Twine(J) + " in " + CmdName + " command " +
375 Twine(LoadCommandIndex) +
376 " extends past the end of the file");
377 if (Error Err = checkOverlappingElement(Elements, s.reloff, s.nreloc *
378 sizeof(struct
380 "section relocation entries"))
381 return Err;
382 }
383 if (S.fileoff > FileSize)
384 return malformedError("load command " + Twine(LoadCommandIndex) +
385 " fileoff field in " + CmdName +
386 " extends past the end of the file");
387 uint64_t BigSize = S.fileoff;
388 BigSize += S.filesize;
389 if (BigSize > FileSize)
390 return malformedError("load command " + Twine(LoadCommandIndex) +
391 " fileoff field plus filesize field in " +
392 CmdName + " extends past the end of the file");
393 if (S.vmsize != 0 && S.filesize > S.vmsize)
394 return malformedError("load command " + Twine(LoadCommandIndex) +
395 " filesize field in " + CmdName +
396 " greater than vmsize field");
397 IsPageZeroSegment |= StringRef("__PAGEZERO").equals(S.segname);
398 } else
399 return SegOrErr.takeError();
400
401 return Error::success();
402}
403
406 uint32_t LoadCommandIndex,
407 const char **SymtabLoadCmd,
408 std::list<MachOElement> &Elements) {
409 if (Load.C.cmdsize < sizeof(MachO::symtab_command))
410 return malformedError("load command " + Twine(LoadCommandIndex) +
411 " LC_SYMTAB cmdsize too small");
412 if (*SymtabLoadCmd != nullptr)
413 return malformedError("more than one LC_SYMTAB command");
414 auto SymtabOrErr = getStructOrErr<MachO::symtab_command>(Obj, Load.Ptr);
415 if (!SymtabOrErr)
416 return SymtabOrErr.takeError();
417 MachO::symtab_command Symtab = SymtabOrErr.get();
418 if (Symtab.cmdsize != sizeof(MachO::symtab_command))
419 return malformedError("LC_SYMTAB command " + Twine(LoadCommandIndex) +
420 " has incorrect cmdsize");
421 uint64_t FileSize = Obj.getData().size();
422 if (Symtab.symoff > FileSize)
423 return malformedError("symoff field of LC_SYMTAB command " +
424 Twine(LoadCommandIndex) + " extends past the end "
425 "of the file");
426 uint64_t SymtabSize = Symtab.nsyms;
427 const char *struct_nlist_name;
428 if (Obj.is64Bit()) {
429 SymtabSize *= sizeof(MachO::nlist_64);
430 struct_nlist_name = "struct nlist_64";
431 } else {
432 SymtabSize *= sizeof(MachO::nlist);
433 struct_nlist_name = "struct nlist";
434 }
435 uint64_t BigSize = SymtabSize;
436 BigSize += Symtab.symoff;
437 if (BigSize > FileSize)
438 return malformedError("symoff field plus nsyms field times sizeof(" +
439 Twine(struct_nlist_name) + ") of LC_SYMTAB command " +
440 Twine(LoadCommandIndex) + " extends past the end "
441 "of the file");
442 if (Error Err = checkOverlappingElement(Elements, Symtab.symoff, SymtabSize,
443 "symbol table"))
444 return Err;
445 if (Symtab.stroff > FileSize)
446 return malformedError("stroff field of LC_SYMTAB command " +
447 Twine(LoadCommandIndex) + " extends past the end "
448 "of the file");
449 BigSize = Symtab.stroff;
450 BigSize += Symtab.strsize;
451 if (BigSize > FileSize)
452 return malformedError("stroff field plus strsize field of LC_SYMTAB "
453 "command " + Twine(LoadCommandIndex) + " extends "
454 "past the end of the file");
455 if (Error Err = checkOverlappingElement(Elements, Symtab.stroff,
456 Symtab.strsize, "string table"))
457 return Err;
458 *SymtabLoadCmd = Load.Ptr;
459 return Error::success();
460}
461
464 uint32_t LoadCommandIndex,
465 const char **DysymtabLoadCmd,
466 std::list<MachOElement> &Elements) {
467 if (Load.C.cmdsize < sizeof(MachO::dysymtab_command))
468 return malformedError("load command " + Twine(LoadCommandIndex) +
469 " LC_DYSYMTAB cmdsize too small");
470 if (*DysymtabLoadCmd != nullptr)
471 return malformedError("more than one LC_DYSYMTAB command");
472 auto DysymtabOrErr =
473 getStructOrErr<MachO::dysymtab_command>(Obj, Load.Ptr);
474 if (!DysymtabOrErr)
475 return DysymtabOrErr.takeError();
476 MachO::dysymtab_command Dysymtab = DysymtabOrErr.get();
477 if (Dysymtab.cmdsize != sizeof(MachO::dysymtab_command))
478 return malformedError("LC_DYSYMTAB command " + Twine(LoadCommandIndex) +
479 " has incorrect cmdsize");
480 uint64_t FileSize = Obj.getData().size();
481 if (Dysymtab.tocoff > FileSize)
482 return malformedError("tocoff field of LC_DYSYMTAB command " +
483 Twine(LoadCommandIndex) + " extends past the end of "
484 "the file");
485 uint64_t BigSize = Dysymtab.ntoc;
486 BigSize *= sizeof(MachO::dylib_table_of_contents);
487 BigSize += Dysymtab.tocoff;
488 if (BigSize > FileSize)
489 return malformedError("tocoff field plus ntoc field times sizeof(struct "
490 "dylib_table_of_contents) of LC_DYSYMTAB command " +
491 Twine(LoadCommandIndex) + " extends past the end of "
492 "the file");
493 if (Error Err = checkOverlappingElement(Elements, Dysymtab.tocoff,
494 Dysymtab.ntoc * sizeof(struct
496 "table of contents"))
497 return Err;
498 if (Dysymtab.modtaboff > FileSize)
499 return malformedError("modtaboff field of LC_DYSYMTAB command " +
500 Twine(LoadCommandIndex) + " extends past the end of "
501 "the file");
502 BigSize = Dysymtab.nmodtab;
503 const char *struct_dylib_module_name;
504 uint64_t sizeof_modtab;
505 if (Obj.is64Bit()) {
506 sizeof_modtab = sizeof(MachO::dylib_module_64);
507 struct_dylib_module_name = "struct dylib_module_64";
508 } else {
509 sizeof_modtab = sizeof(MachO::dylib_module);
510 struct_dylib_module_name = "struct dylib_module";
511 }
512 BigSize *= sizeof_modtab;
513 BigSize += Dysymtab.modtaboff;
514 if (BigSize > FileSize)
515 return malformedError("modtaboff field plus nmodtab field times sizeof(" +
516 Twine(struct_dylib_module_name) + ") of LC_DYSYMTAB "
517 "command " + Twine(LoadCommandIndex) + " extends "
518 "past the end of the file");
519 if (Error Err = checkOverlappingElement(Elements, Dysymtab.modtaboff,
520 Dysymtab.nmodtab * sizeof_modtab,
521 "module table"))
522 return Err;
523 if (Dysymtab.extrefsymoff > FileSize)
524 return malformedError("extrefsymoff field of LC_DYSYMTAB command " +
525 Twine(LoadCommandIndex) + " extends past the end of "
526 "the file");
527 BigSize = Dysymtab.nextrefsyms;
528 BigSize *= sizeof(MachO::dylib_reference);
529 BigSize += Dysymtab.extrefsymoff;
530 if (BigSize > FileSize)
531 return malformedError("extrefsymoff field plus nextrefsyms field times "
532 "sizeof(struct dylib_reference) of LC_DYSYMTAB "
533 "command " + Twine(LoadCommandIndex) + " extends "
534 "past the end of the file");
535 if (Error Err = checkOverlappingElement(Elements, Dysymtab.extrefsymoff,
536 Dysymtab.nextrefsyms *
538 "reference table"))
539 return Err;
540 if (Dysymtab.indirectsymoff > FileSize)
541 return malformedError("indirectsymoff field of LC_DYSYMTAB command " +
542 Twine(LoadCommandIndex) + " extends past the end of "
543 "the file");
544 BigSize = Dysymtab.nindirectsyms;
545 BigSize *= sizeof(uint32_t);
546 BigSize += Dysymtab.indirectsymoff;
547 if (BigSize > FileSize)
548 return malformedError("indirectsymoff field plus nindirectsyms field times "
549 "sizeof(uint32_t) of LC_DYSYMTAB command " +
550 Twine(LoadCommandIndex) + " extends past the end of "
551 "the file");
552 if (Error Err = checkOverlappingElement(Elements, Dysymtab.indirectsymoff,
553 Dysymtab.nindirectsyms *
554 sizeof(uint32_t),
555 "indirect table"))
556 return Err;
557 if (Dysymtab.extreloff > FileSize)
558 return malformedError("extreloff field of LC_DYSYMTAB command " +
559 Twine(LoadCommandIndex) + " extends past the end of "
560 "the file");
561 BigSize = Dysymtab.nextrel;
562 BigSize *= sizeof(MachO::relocation_info);
563 BigSize += Dysymtab.extreloff;
564 if (BigSize > FileSize)
565 return malformedError("extreloff field plus nextrel field times sizeof"
566 "(struct relocation_info) of LC_DYSYMTAB command " +
567 Twine(LoadCommandIndex) + " extends past the end of "
568 "the file");
569 if (Error Err = checkOverlappingElement(Elements, Dysymtab.extreloff,
570 Dysymtab.nextrel *
572 "external relocation table"))
573 return Err;
574 if (Dysymtab.locreloff > FileSize)
575 return malformedError("locreloff field of LC_DYSYMTAB command " +
576 Twine(LoadCommandIndex) + " extends past the end of "
577 "the file");
578 BigSize = Dysymtab.nlocrel;
579 BigSize *= sizeof(MachO::relocation_info);
580 BigSize += Dysymtab.locreloff;
581 if (BigSize > FileSize)
582 return malformedError("locreloff field plus nlocrel field times sizeof"
583 "(struct relocation_info) of LC_DYSYMTAB command " +
584 Twine(LoadCommandIndex) + " extends past the end of "
585 "the file");
586 if (Error Err = checkOverlappingElement(Elements, Dysymtab.locreloff,
587 Dysymtab.nlocrel *
589 "local relocation table"))
590 return Err;
591 *DysymtabLoadCmd = Load.Ptr;
592 return Error::success();
593}
594
597 uint32_t LoadCommandIndex,
598 const char **LoadCmd, const char *CmdName,
599 std::list<MachOElement> &Elements,
600 const char *ElementName) {
601 if (Load.C.cmdsize < sizeof(MachO::linkedit_data_command))
602 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
603 CmdName + " cmdsize too small");
604 if (*LoadCmd != nullptr)
605 return malformedError("more than one " + Twine(CmdName) + " command");
606 auto LinkDataOrError =
607 getStructOrErr<MachO::linkedit_data_command>(Obj, Load.Ptr);
608 if (!LinkDataOrError)
609 return LinkDataOrError.takeError();
610 MachO::linkedit_data_command LinkData = LinkDataOrError.get();
611 if (LinkData.cmdsize != sizeof(MachO::linkedit_data_command))
612 return malformedError(Twine(CmdName) + " command " +
613 Twine(LoadCommandIndex) + " has incorrect cmdsize");
614 uint64_t FileSize = Obj.getData().size();
615 if (LinkData.dataoff > FileSize)
616 return malformedError("dataoff field of " + Twine(CmdName) + " command " +
617 Twine(LoadCommandIndex) + " extends past the end of "
618 "the file");
619 uint64_t BigSize = LinkData.dataoff;
620 BigSize += LinkData.datasize;
621 if (BigSize > FileSize)
622 return malformedError("dataoff field plus datasize field of " +
623 Twine(CmdName) + " command " +
624 Twine(LoadCommandIndex) + " extends past the end of "
625 "the file");
626 if (Error Err = checkOverlappingElement(Elements, LinkData.dataoff,
627 LinkData.datasize, ElementName))
628 return Err;
629 *LoadCmd = Load.Ptr;
630 return Error::success();
631}
632
635 uint32_t LoadCommandIndex,
636 const char **LoadCmd, const char *CmdName,
637 std::list<MachOElement> &Elements) {
638 if (Load.C.cmdsize < sizeof(MachO::dyld_info_command))
639 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
640 CmdName + " cmdsize too small");
641 if (*LoadCmd != nullptr)
642 return malformedError("more than one LC_DYLD_INFO and or LC_DYLD_INFO_ONLY "
643 "command");
644 auto DyldInfoOrErr =
645 getStructOrErr<MachO::dyld_info_command>(Obj, Load.Ptr);
646 if (!DyldInfoOrErr)
647 return DyldInfoOrErr.takeError();
648 MachO::dyld_info_command DyldInfo = DyldInfoOrErr.get();
649 if (DyldInfo.cmdsize != sizeof(MachO::dyld_info_command))
650 return malformedError(Twine(CmdName) + " command " +
651 Twine(LoadCommandIndex) + " has incorrect cmdsize");
652 uint64_t FileSize = Obj.getData().size();
653 if (DyldInfo.rebase_off > FileSize)
654 return malformedError("rebase_off field of " + Twine(CmdName) +
655 " command " + Twine(LoadCommandIndex) + " extends "
656 "past the end of the file");
657 uint64_t BigSize = DyldInfo.rebase_off;
658 BigSize += DyldInfo.rebase_size;
659 if (BigSize > FileSize)
660 return malformedError("rebase_off field plus rebase_size field of " +
661 Twine(CmdName) + " command " +
662 Twine(LoadCommandIndex) + " extends past the end of "
663 "the file");
664 if (Error Err = checkOverlappingElement(Elements, DyldInfo.rebase_off,
665 DyldInfo.rebase_size,
666 "dyld rebase info"))
667 return Err;
668 if (DyldInfo.bind_off > FileSize)
669 return malformedError("bind_off field of " + Twine(CmdName) +
670 " command " + Twine(LoadCommandIndex) + " extends "
671 "past the end of the file");
672 BigSize = DyldInfo.bind_off;
673 BigSize += DyldInfo.bind_size;
674 if (BigSize > FileSize)
675 return malformedError("bind_off field plus bind_size field of " +
676 Twine(CmdName) + " command " +
677 Twine(LoadCommandIndex) + " extends past the end of "
678 "the file");
679 if (Error Err = checkOverlappingElement(Elements, DyldInfo.bind_off,
680 DyldInfo.bind_size,
681 "dyld bind info"))
682 return Err;
683 if (DyldInfo.weak_bind_off > FileSize)
684 return malformedError("weak_bind_off field of " + Twine(CmdName) +
685 " command " + Twine(LoadCommandIndex) + " extends "
686 "past the end of the file");
687 BigSize = DyldInfo.weak_bind_off;
688 BigSize += DyldInfo.weak_bind_size;
689 if (BigSize > FileSize)
690 return malformedError("weak_bind_off field plus weak_bind_size field of " +
691 Twine(CmdName) + " command " +
692 Twine(LoadCommandIndex) + " extends past the end of "
693 "the file");
694 if (Error Err = checkOverlappingElement(Elements, DyldInfo.weak_bind_off,
695 DyldInfo.weak_bind_size,
696 "dyld weak bind info"))
697 return Err;
698 if (DyldInfo.lazy_bind_off > FileSize)
699 return malformedError("lazy_bind_off field of " + Twine(CmdName) +
700 " command " + Twine(LoadCommandIndex) + " extends "
701 "past the end of the file");
702 BigSize = DyldInfo.lazy_bind_off;
703 BigSize += DyldInfo.lazy_bind_size;
704 if (BigSize > FileSize)
705 return malformedError("lazy_bind_off field plus lazy_bind_size field of " +
706 Twine(CmdName) + " command " +
707 Twine(LoadCommandIndex) + " extends past the end of "
708 "the file");
709 if (Error Err = checkOverlappingElement(Elements, DyldInfo.lazy_bind_off,
710 DyldInfo.lazy_bind_size,
711 "dyld lazy bind info"))
712 return Err;
713 if (DyldInfo.export_off > FileSize)
714 return malformedError("export_off field of " + Twine(CmdName) +
715 " command " + Twine(LoadCommandIndex) + " extends "
716 "past the end of the file");
717 BigSize = DyldInfo.export_off;
718 BigSize += DyldInfo.export_size;
719 if (BigSize > FileSize)
720 return malformedError("export_off field plus export_size field of " +
721 Twine(CmdName) + " command " +
722 Twine(LoadCommandIndex) + " extends past the end of "
723 "the file");
724 if (Error Err = checkOverlappingElement(Elements, DyldInfo.export_off,
725 DyldInfo.export_size,
726 "dyld export info"))
727 return Err;
728 *LoadCmd = Load.Ptr;
729 return Error::success();
730}
731
734 uint32_t LoadCommandIndex, const char *CmdName) {
735 if (Load.C.cmdsize < sizeof(MachO::dylib_command))
736 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
737 CmdName + " cmdsize too small");
738 auto CommandOrErr = getStructOrErr<MachO::dylib_command>(Obj, Load.Ptr);
739 if (!CommandOrErr)
740 return CommandOrErr.takeError();
741 MachO::dylib_command D = CommandOrErr.get();
742 if (D.dylib.name < sizeof(MachO::dylib_command))
743 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
744 CmdName + " name.offset field too small, not past "
745 "the end of the dylib_command struct");
746 if (D.dylib.name >= D.cmdsize)
747 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
748 CmdName + " name.offset field extends past the end "
749 "of the load command");
750 // Make sure there is a null between the starting offset of the name and
751 // the end of the load command.
752 uint32_t i;
753 const char *P = (const char *)Load.Ptr;
754 for (i = D.dylib.name; i < D.cmdsize; i++)
755 if (P[i] == '\0')
756 break;
757 if (i >= D.cmdsize)
758 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
759 CmdName + " library name extends past the end of the "
760 "load command");
761 return Error::success();
762}
763
766 uint32_t LoadCommandIndex,
767 const char **LoadCmd) {
768 if (Error Err = checkDylibCommand(Obj, Load, LoadCommandIndex,
769 "LC_ID_DYLIB"))
770 return Err;
771 if (*LoadCmd != nullptr)
772 return malformedError("more than one LC_ID_DYLIB command");
773 if (Obj.getHeader().filetype != MachO::MH_DYLIB &&
775 return malformedError("LC_ID_DYLIB load command in non-dynamic library "
776 "file type");
777 *LoadCmd = Load.Ptr;
778 return Error::success();
779}
780
783 uint32_t LoadCommandIndex, const char *CmdName) {
784 if (Load.C.cmdsize < sizeof(MachO::dylinker_command))
785 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
786 CmdName + " cmdsize too small");
787 auto CommandOrErr = getStructOrErr<MachO::dylinker_command>(Obj, Load.Ptr);
788 if (!CommandOrErr)
789 return CommandOrErr.takeError();
790 MachO::dylinker_command D = CommandOrErr.get();
791 if (D.name < sizeof(MachO::dylinker_command))
792 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
793 CmdName + " name.offset field too small, not past "
794 "the end of the dylinker_command struct");
795 if (D.name >= D.cmdsize)
796 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
797 CmdName + " name.offset field extends past the end "
798 "of the load command");
799 // Make sure there is a null between the starting offset of the name and
800 // the end of the load command.
801 uint32_t i;
802 const char *P = (const char *)Load.Ptr;
803 for (i = D.name; i < D.cmdsize; i++)
804 if (P[i] == '\0')
805 break;
806 if (i >= D.cmdsize)
807 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
808 CmdName + " dyld name extends past the end of the "
809 "load command");
810 return Error::success();
811}
812
815 uint32_t LoadCommandIndex,
816 const char **LoadCmd, const char *CmdName) {
817 if (Load.C.cmdsize != sizeof(MachO::version_min_command))
818 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
819 CmdName + " has incorrect cmdsize");
820 if (*LoadCmd != nullptr)
821 return malformedError("more than one LC_VERSION_MIN_MACOSX, "
822 "LC_VERSION_MIN_IPHONEOS, LC_VERSION_MIN_TVOS or "
823 "LC_VERSION_MIN_WATCHOS command");
824 *LoadCmd = Load.Ptr;
825 return Error::success();
826}
827
830 uint32_t LoadCommandIndex,
831 std::list<MachOElement> &Elements) {
832 if (Load.C.cmdsize != sizeof(MachO::note_command))
833 return malformedError("load command " + Twine(LoadCommandIndex) +
834 " LC_NOTE has incorrect cmdsize");
835 auto NoteCmdOrErr = getStructOrErr<MachO::note_command>(Obj, Load.Ptr);
836 if (!NoteCmdOrErr)
837 return NoteCmdOrErr.takeError();
838 MachO::note_command Nt = NoteCmdOrErr.get();
839 uint64_t FileSize = Obj.getData().size();
840 if (Nt.offset > FileSize)
841 return malformedError("offset field of LC_NOTE command " +
842 Twine(LoadCommandIndex) + " extends "
843 "past the end of the file");
844 uint64_t BigSize = Nt.offset;
845 BigSize += Nt.size;
846 if (BigSize > FileSize)
847 return malformedError("size field plus offset field of LC_NOTE command " +
848 Twine(LoadCommandIndex) + " extends past the end of "
849 "the file");
850 if (Error Err = checkOverlappingElement(Elements, Nt.offset, Nt.size,
851 "LC_NOTE data"))
852 return Err;
853 return Error::success();
854}
855
856static Error
860 uint32_t LoadCommandIndex) {
861 auto BVCOrErr =
862 getStructOrErr<MachO::build_version_command>(Obj, Load.Ptr);
863 if (!BVCOrErr)
864 return BVCOrErr.takeError();
865 MachO::build_version_command BVC = BVCOrErr.get();
866 if (Load.C.cmdsize !=
868 BVC.ntools * sizeof(MachO::build_tool_version))
869 return malformedError("load command " + Twine(LoadCommandIndex) +
870 " LC_BUILD_VERSION_COMMAND has incorrect cmdsize");
871
872 auto Start = Load.Ptr + sizeof(MachO::build_version_command);
873 BuildTools.resize(BVC.ntools);
874 for (unsigned i = 0; i < BVC.ntools; ++i)
875 BuildTools[i] = Start + i * sizeof(MachO::build_tool_version);
876
877 return Error::success();
878}
879
882 uint32_t LoadCommandIndex) {
883 if (Load.C.cmdsize < sizeof(MachO::rpath_command))
884 return malformedError("load command " + Twine(LoadCommandIndex) +
885 " LC_RPATH cmdsize too small");
886 auto ROrErr = getStructOrErr<MachO::rpath_command>(Obj, Load.Ptr);
887 if (!ROrErr)
888 return ROrErr.takeError();
889 MachO::rpath_command R = ROrErr.get();
890 if (R.path < sizeof(MachO::rpath_command))
891 return malformedError("load command " + Twine(LoadCommandIndex) +
892 " LC_RPATH path.offset field too small, not past "
893 "the end of the rpath_command struct");
894 if (R.path >= R.cmdsize)
895 return malformedError("load command " + Twine(LoadCommandIndex) +
896 " LC_RPATH path.offset field extends past the end "
897 "of the load command");
898 // Make sure there is a null between the starting offset of the path and
899 // the end of the load command.
900 uint32_t i;
901 const char *P = (const char *)Load.Ptr;
902 for (i = R.path; i < R.cmdsize; i++)
903 if (P[i] == '\0')
904 break;
905 if (i >= R.cmdsize)
906 return malformedError("load command " + Twine(LoadCommandIndex) +
907 " LC_RPATH library name extends past the end of the "
908 "load command");
909 return Error::success();
910}
911
914 uint32_t LoadCommandIndex,
915 uint64_t cryptoff, uint64_t cryptsize,
916 const char **LoadCmd, const char *CmdName) {
917 if (*LoadCmd != nullptr)
918 return malformedError("more than one LC_ENCRYPTION_INFO and or "
919 "LC_ENCRYPTION_INFO_64 command");
920 uint64_t FileSize = Obj.getData().size();
921 if (cryptoff > FileSize)
922 return malformedError("cryptoff field of " + Twine(CmdName) +
923 " command " + Twine(LoadCommandIndex) + " extends "
924 "past the end of the file");
925 uint64_t BigSize = cryptoff;
926 BigSize += cryptsize;
927 if (BigSize > FileSize)
928 return malformedError("cryptoff field plus cryptsize field of " +
929 Twine(CmdName) + " command " +
930 Twine(LoadCommandIndex) + " extends past the end of "
931 "the file");
932 *LoadCmd = Load.Ptr;
933 return Error::success();
934}
935
938 uint32_t LoadCommandIndex) {
939 if (Load.C.cmdsize < sizeof(MachO::linker_option_command))
940 return malformedError("load command " + Twine(LoadCommandIndex) +
941 " LC_LINKER_OPTION cmdsize too small");
942 auto LinkOptionOrErr =
943 getStructOrErr<MachO::linker_option_command>(Obj, Load.Ptr);
944 if (!LinkOptionOrErr)
945 return LinkOptionOrErr.takeError();
946 MachO::linker_option_command L = LinkOptionOrErr.get();
947 // Make sure the count of strings is correct.
948 const char *string = (const char *)Load.Ptr +
949 sizeof(struct MachO::linker_option_command);
950 uint32_t left = L.cmdsize - sizeof(struct MachO::linker_option_command);
951 uint32_t i = 0;
952 while (left > 0) {
953 while (*string == '\0' && left > 0) {
954 string++;
955 left--;
956 }
957 if (left > 0) {
958 i++;
959 uint32_t NullPos = StringRef(string, left).find('\0');
960 if (0xffffffff == NullPos)
961 return malformedError("load command " + Twine(LoadCommandIndex) +
962 " LC_LINKER_OPTION string #" + Twine(i) +
963 " is not NULL terminated");
964 uint32_t len = std::min(NullPos, left) + 1;
965 string += len;
966 left -= len;
967 }
968 }
969 if (L.count != i)
970 return malformedError("load command " + Twine(LoadCommandIndex) +
971 " LC_LINKER_OPTION string count " + Twine(L.count) +
972 " does not match number of strings");
973 return Error::success();
974}
975
978 uint32_t LoadCommandIndex, const char *CmdName,
979 size_t SizeOfCmd, const char *CmdStructName,
980 uint32_t PathOffset, const char *PathFieldName) {
981 if (PathOffset < SizeOfCmd)
982 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
983 CmdName + " " + PathFieldName + ".offset field too "
984 "small, not past the end of the " + CmdStructName);
985 if (PathOffset >= Load.C.cmdsize)
986 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
987 CmdName + " " + PathFieldName + ".offset field "
988 "extends past the end of the load command");
989 // Make sure there is a null between the starting offset of the path and
990 // the end of the load command.
991 uint32_t i;
992 const char *P = (const char *)Load.Ptr;
993 for (i = PathOffset; i < Load.C.cmdsize; i++)
994 if (P[i] == '\0')
995 break;
996 if (i >= Load.C.cmdsize)
997 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
998 CmdName + " " + PathFieldName + " name extends past "
999 "the end of the load command");
1000 return Error::success();
1001}
1002
1005 uint32_t LoadCommandIndex,
1006 const char *CmdName) {
1007 if (Load.C.cmdsize < sizeof(MachO::thread_command))
1008 return malformedError("load command " + Twine(LoadCommandIndex) +
1009 CmdName + " cmdsize too small");
1010 auto ThreadCommandOrErr =
1011 getStructOrErr<MachO::thread_command>(Obj, Load.Ptr);
1012 if (!ThreadCommandOrErr)
1013 return ThreadCommandOrErr.takeError();
1014 MachO::thread_command T = ThreadCommandOrErr.get();
1015 const char *state = Load.Ptr + sizeof(MachO::thread_command);
1016 const char *end = Load.Ptr + T.cmdsize;
1017 uint32_t nflavor = 0;
1018 uint32_t cputype = getCPUType(Obj);
1019 while (state < end) {
1020 if(state + sizeof(uint32_t) > end)
1021 return malformedError("load command " + Twine(LoadCommandIndex) +
1022 "flavor in " + CmdName + " extends past end of "
1023 "command");
1024 uint32_t flavor;
1025 memcpy(&flavor, state, sizeof(uint32_t));
1027 sys::swapByteOrder(flavor);
1028 state += sizeof(uint32_t);
1029
1030 if(state + sizeof(uint32_t) > end)
1031 return malformedError("load command " + Twine(LoadCommandIndex) +
1032 " count in " + CmdName + " extends past end of "
1033 "command");
1035 memcpy(&count, state, sizeof(uint32_t));
1038 state += sizeof(uint32_t);
1039
1040 if (cputype == MachO::CPU_TYPE_I386) {
1041 if (flavor == MachO::x86_THREAD_STATE32) {
1043 return malformedError("load command " + Twine(LoadCommandIndex) +
1044 " count not x86_THREAD_STATE32_COUNT for "
1045 "flavor number " + Twine(nflavor) + " which is "
1046 "a x86_THREAD_STATE32 flavor in " + CmdName +
1047 " command");
1048 if (state + sizeof(MachO::x86_thread_state32_t) > end)
1049 return malformedError("load command " + Twine(LoadCommandIndex) +
1050 " x86_THREAD_STATE32 extends past end of "
1051 "command in " + CmdName + " command");
1052 state += sizeof(MachO::x86_thread_state32_t);
1053 } else {
1054 return malformedError("load command " + Twine(LoadCommandIndex) +
1055 " unknown flavor (" + Twine(flavor) + ") for "
1056 "flavor number " + Twine(nflavor) + " in " +
1057 CmdName + " command");
1058 }
1059 } else if (cputype == MachO::CPU_TYPE_X86_64) {
1060 if (flavor == MachO::x86_THREAD_STATE) {
1062 return malformedError("load command " + Twine(LoadCommandIndex) +
1063 " count not x86_THREAD_STATE_COUNT for "
1064 "flavor number " + Twine(nflavor) + " which is "
1065 "a x86_THREAD_STATE flavor in " + CmdName +
1066 " command");
1067 if (state + sizeof(MachO::x86_thread_state_t) > end)
1068 return malformedError("load command " + Twine(LoadCommandIndex) +
1069 " x86_THREAD_STATE extends past end of "
1070 "command in " + CmdName + " command");
1071 state += sizeof(MachO::x86_thread_state_t);
1072 } else if (flavor == MachO::x86_FLOAT_STATE) {
1074 return malformedError("load command " + Twine(LoadCommandIndex) +
1075 " count not x86_FLOAT_STATE_COUNT for "
1076 "flavor number " + Twine(nflavor) + " which is "
1077 "a x86_FLOAT_STATE flavor in " + CmdName +
1078 " command");
1079 if (state + sizeof(MachO::x86_float_state_t) > end)
1080 return malformedError("load command " + Twine(LoadCommandIndex) +
1081 " x86_FLOAT_STATE extends past end of "
1082 "command in " + CmdName + " command");
1083 state += sizeof(MachO::x86_float_state_t);
1084 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
1086 return malformedError("load command " + Twine(LoadCommandIndex) +
1087 " count not x86_EXCEPTION_STATE_COUNT for "
1088 "flavor number " + Twine(nflavor) + " which is "
1089 "a x86_EXCEPTION_STATE flavor in " + CmdName +
1090 " command");
1091 if (state + sizeof(MachO::x86_exception_state_t) > end)
1092 return malformedError("load command " + Twine(LoadCommandIndex) +
1093 " x86_EXCEPTION_STATE extends past end of "
1094 "command in " + CmdName + " command");
1095 state += sizeof(MachO::x86_exception_state_t);
1096 } else if (flavor == MachO::x86_THREAD_STATE64) {
1098 return malformedError("load command " + Twine(LoadCommandIndex) +
1099 " count not x86_THREAD_STATE64_COUNT for "
1100 "flavor number " + Twine(nflavor) + " which is "
1101 "a x86_THREAD_STATE64 flavor in " + CmdName +
1102 " command");
1103 if (state + sizeof(MachO::x86_thread_state64_t) > end)
1104 return malformedError("load command " + Twine(LoadCommandIndex) +
1105 " x86_THREAD_STATE64 extends past end of "
1106 "command in " + CmdName + " command");
1107 state += sizeof(MachO::x86_thread_state64_t);
1108 } else if (flavor == MachO::x86_EXCEPTION_STATE64) {
1110 return malformedError("load command " + Twine(LoadCommandIndex) +
1111 " count not x86_EXCEPTION_STATE64_COUNT for "
1112 "flavor number " + Twine(nflavor) + " which is "
1113 "a x86_EXCEPTION_STATE64 flavor in " + CmdName +
1114 " command");
1115 if (state + sizeof(MachO::x86_exception_state64_t) > end)
1116 return malformedError("load command " + Twine(LoadCommandIndex) +
1117 " x86_EXCEPTION_STATE64 extends past end of "
1118 "command in " + CmdName + " command");
1119 state += sizeof(MachO::x86_exception_state64_t);
1120 } else {
1121 return malformedError("load command " + Twine(LoadCommandIndex) +
1122 " unknown flavor (" + Twine(flavor) + ") for "
1123 "flavor number " + Twine(nflavor) + " in " +
1124 CmdName + " command");
1125 }
1126 } else if (cputype == MachO::CPU_TYPE_ARM) {
1127 if (flavor == MachO::ARM_THREAD_STATE) {
1129 return malformedError("load command " + Twine(LoadCommandIndex) +
1130 " count not ARM_THREAD_STATE_COUNT for "
1131 "flavor number " + Twine(nflavor) + " which is "
1132 "a ARM_THREAD_STATE flavor in " + CmdName +
1133 " command");
1134 if (state + sizeof(MachO::arm_thread_state32_t) > end)
1135 return malformedError("load command " + Twine(LoadCommandIndex) +
1136 " ARM_THREAD_STATE extends past end of "
1137 "command in " + CmdName + " command");
1138 state += sizeof(MachO::arm_thread_state32_t);
1139 } else {
1140 return malformedError("load command " + Twine(LoadCommandIndex) +
1141 " unknown flavor (" + Twine(flavor) + ") for "
1142 "flavor number " + Twine(nflavor) + " in " +
1143 CmdName + " command");
1144 }
1145 } else if (cputype == MachO::CPU_TYPE_ARM64 ||
1146 cputype == MachO::CPU_TYPE_ARM64_32) {
1147 if (flavor == MachO::ARM_THREAD_STATE64) {
1149 return malformedError("load command " + Twine(LoadCommandIndex) +
1150 " count not ARM_THREAD_STATE64_COUNT for "
1151 "flavor number " + Twine(nflavor) + " which is "
1152 "a ARM_THREAD_STATE64 flavor in " + CmdName +
1153 " command");
1154 if (state + sizeof(MachO::arm_thread_state64_t) > end)
1155 return malformedError("load command " + Twine(LoadCommandIndex) +
1156 " ARM_THREAD_STATE64 extends past end of "
1157 "command in " + CmdName + " command");
1158 state += sizeof(MachO::arm_thread_state64_t);
1159 } else {
1160 return malformedError("load command " + Twine(LoadCommandIndex) +
1161 " unknown flavor (" + Twine(flavor) + ") for "
1162 "flavor number " + Twine(nflavor) + " in " +
1163 CmdName + " command");
1164 }
1165 } else if (cputype == MachO::CPU_TYPE_POWERPC) {
1166 if (flavor == MachO::PPC_THREAD_STATE) {
1168 return malformedError("load command " + Twine(LoadCommandIndex) +
1169 " count not PPC_THREAD_STATE_COUNT for "
1170 "flavor number " + Twine(nflavor) + " which is "
1171 "a PPC_THREAD_STATE flavor in " + CmdName +
1172 " command");
1173 if (state + sizeof(MachO::ppc_thread_state32_t) > end)
1174 return malformedError("load command " + Twine(LoadCommandIndex) +
1175 " PPC_THREAD_STATE extends past end of "
1176 "command in " + CmdName + " command");
1177 state += sizeof(MachO::ppc_thread_state32_t);
1178 } else {
1179 return malformedError("load command " + Twine(LoadCommandIndex) +
1180 " unknown flavor (" + Twine(flavor) + ") for "
1181 "flavor number " + Twine(nflavor) + " in " +
1182 CmdName + " command");
1183 }
1184 } else {
1185 return malformedError("unknown cputype (" + Twine(cputype) + ") load "
1186 "command " + Twine(LoadCommandIndex) + " for " +
1187 CmdName + " command can't be checked");
1188 }
1189 nflavor++;
1190 }
1191 return Error::success();
1192}
1193
1196 &Load,
1197 uint32_t LoadCommandIndex,
1198 const char **LoadCmd,
1199 std::list<MachOElement> &Elements) {
1200 if (Load.C.cmdsize != sizeof(MachO::twolevel_hints_command))
1201 return malformedError("load command " + Twine(LoadCommandIndex) +
1202 " LC_TWOLEVEL_HINTS has incorrect cmdsize");
1203 if (*LoadCmd != nullptr)
1204 return malformedError("more than one LC_TWOLEVEL_HINTS command");
1205 auto HintsOrErr = getStructOrErr<MachO::twolevel_hints_command>(Obj, Load.Ptr);
1206 if(!HintsOrErr)
1207 return HintsOrErr.takeError();
1208 MachO::twolevel_hints_command Hints = HintsOrErr.get();
1209 uint64_t FileSize = Obj.getData().size();
1210 if (Hints.offset > FileSize)
1211 return malformedError("offset field of LC_TWOLEVEL_HINTS command " +
1212 Twine(LoadCommandIndex) + " extends past the end of "
1213 "the file");
1214 uint64_t BigSize = Hints.nhints;
1215 BigSize *= sizeof(MachO::twolevel_hint);
1216 BigSize += Hints.offset;
1217 if (BigSize > FileSize)
1218 return malformedError("offset field plus nhints times sizeof(struct "
1219 "twolevel_hint) field of LC_TWOLEVEL_HINTS command " +
1220 Twine(LoadCommandIndex) + " extends past the end of "
1221 "the file");
1222 if (Error Err = checkOverlappingElement(Elements, Hints.offset, Hints.nhints *
1223 sizeof(MachO::twolevel_hint),
1224 "two level hints"))
1225 return Err;
1226 *LoadCmd = Load.Ptr;
1227 return Error::success();
1228}
1229
1230// Returns true if the libObject code does not support the load command and its
1231// contents. The cmd value it is treated as an unknown load command but with
1232// an error message that says the cmd value is obsolete.
1234 if (cmd == MachO::LC_SYMSEG ||
1235 cmd == MachO::LC_LOADFVMLIB ||
1236 cmd == MachO::LC_IDFVMLIB ||
1237 cmd == MachO::LC_IDENT ||
1238 cmd == MachO::LC_FVMFILE ||
1239 cmd == MachO::LC_PREPAGE ||
1240 cmd == MachO::LC_PREBOUND_DYLIB ||
1241 cmd == MachO::LC_TWOLEVEL_HINTS ||
1242 cmd == MachO::LC_PREBIND_CKSUM)
1243 return true;
1244 return false;
1245}
1246
1249 bool Is64Bits, uint32_t UniversalCputype,
1250 uint32_t UniversalIndex) {
1251 Error Err = Error::success();
1252 std::unique_ptr<MachOObjectFile> Obj(
1253 new MachOObjectFile(std::move(Object), IsLittleEndian,
1254 Is64Bits, Err, UniversalCputype,
1255 UniversalIndex));
1256 if (Err)
1257 return std::move(Err);
1258 return std::move(Obj);
1259}
1260
1261MachOObjectFile::MachOObjectFile(MemoryBufferRef Object, bool IsLittleEndian,
1262 bool Is64bits, Error &Err,
1263 uint32_t UniversalCputype,
1264 uint32_t UniversalIndex)
1265 : ObjectFile(getMachOType(IsLittleEndian, Is64bits), Object) {
1266 ErrorAsOutParameter ErrAsOutParam(&Err);
1267 uint64_t SizeOfHeaders;
1268 uint32_t cputype;
1269 if (is64Bit()) {
1270 parseHeader(*this, Header64, Err);
1271 SizeOfHeaders = sizeof(MachO::mach_header_64);
1272 cputype = Header64.cputype;
1273 } else {
1274 parseHeader(*this, Header, Err);
1275 SizeOfHeaders = sizeof(MachO::mach_header);
1276 cputype = Header.cputype;
1277 }
1278 if (Err)
1279 return;
1280 SizeOfHeaders += getHeader().sizeofcmds;
1281 if (getData().data() + SizeOfHeaders > getData().end()) {
1282 Err = malformedError("load commands extend past the end of the file");
1283 return;
1284 }
1285 if (UniversalCputype != 0 && cputype != UniversalCputype) {
1286 Err = malformedError("universal header architecture: " +
1287 Twine(UniversalIndex) + "'s cputype does not match "
1288 "object file's mach header");
1289 return;
1290 }
1291 std::list<MachOElement> Elements;
1292 Elements.push_back({0, SizeOfHeaders, "Mach-O headers"});
1293
1294 uint32_t LoadCommandCount = getHeader().ncmds;
1295 LoadCommandInfo Load;
1296 if (LoadCommandCount != 0) {
1297 if (auto LoadOrErr = getFirstLoadCommandInfo(*this))
1298 Load = *LoadOrErr;
1299 else {
1300 Err = LoadOrErr.takeError();
1301 return;
1302 }
1303 }
1304
1305 const char *DyldIdLoadCmd = nullptr;
1306 const char *SplitInfoLoadCmd = nullptr;
1307 const char *CodeSignDrsLoadCmd = nullptr;
1308 const char *CodeSignLoadCmd = nullptr;
1309 const char *VersLoadCmd = nullptr;
1310 const char *SourceLoadCmd = nullptr;
1311 const char *EntryPointLoadCmd = nullptr;
1312 const char *EncryptLoadCmd = nullptr;
1313 const char *RoutinesLoadCmd = nullptr;
1314 const char *UnixThreadLoadCmd = nullptr;
1315 const char *TwoLevelHintsLoadCmd = nullptr;
1316 for (unsigned I = 0; I < LoadCommandCount; ++I) {
1317 if (is64Bit()) {
1318 if (Load.C.cmdsize % 8 != 0) {
1319 // We have a hack here to allow 64-bit Mach-O core files to have
1320 // LC_THREAD commands that are only a multiple of 4 and not 8 to be
1321 // allowed since the macOS kernel produces them.
1322 if (getHeader().filetype != MachO::MH_CORE ||
1323 Load.C.cmd != MachO::LC_THREAD || Load.C.cmdsize % 4) {
1324 Err = malformedError("load command " + Twine(I) + " cmdsize not a "
1325 "multiple of 8");
1326 return;
1327 }
1328 }
1329 } else {
1330 if (Load.C.cmdsize % 4 != 0) {
1331 Err = malformedError("load command " + Twine(I) + " cmdsize not a "
1332 "multiple of 4");
1333 return;
1334 }
1335 }
1336 LoadCommands.push_back(Load);
1337 if (Load.C.cmd == MachO::LC_SYMTAB) {
1338 if ((Err = checkSymtabCommand(*this, Load, I, &SymtabLoadCmd, Elements)))
1339 return;
1340 } else if (Load.C.cmd == MachO::LC_DYSYMTAB) {
1341 if ((Err = checkDysymtabCommand(*this, Load, I, &DysymtabLoadCmd,
1342 Elements)))
1343 return;
1344 } else if (Load.C.cmd == MachO::LC_DATA_IN_CODE) {
1345 if ((Err = checkLinkeditDataCommand(*this, Load, I, &DataInCodeLoadCmd,
1346 "LC_DATA_IN_CODE", Elements,
1347 "data in code info")))
1348 return;
1349 } else if (Load.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
1350 if ((Err = checkLinkeditDataCommand(*this, Load, I, &LinkOptHintsLoadCmd,
1351 "LC_LINKER_OPTIMIZATION_HINT",
1352 Elements, "linker optimization "
1353 "hints")))
1354 return;
1355 } else if (Load.C.cmd == MachO::LC_FUNCTION_STARTS) {
1356 if ((Err = checkLinkeditDataCommand(*this, Load, I, &FuncStartsLoadCmd,
1357 "LC_FUNCTION_STARTS", Elements,
1358 "function starts data")))
1359 return;
1360 } else if (Load.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO) {
1361 if ((Err = checkLinkeditDataCommand(*this, Load, I, &SplitInfoLoadCmd,
1362 "LC_SEGMENT_SPLIT_INFO", Elements,
1363 "split info data")))
1364 return;
1365 } else if (Load.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS) {
1366 if ((Err = checkLinkeditDataCommand(*this, Load, I, &CodeSignDrsLoadCmd,
1367 "LC_DYLIB_CODE_SIGN_DRS", Elements,
1368 "code signing RDs data")))
1369 return;
1370 } else if (Load.C.cmd == MachO::LC_CODE_SIGNATURE) {
1371 if ((Err = checkLinkeditDataCommand(*this, Load, I, &CodeSignLoadCmd,
1372 "LC_CODE_SIGNATURE", Elements,
1373 "code signature data")))
1374 return;
1375 } else if (Load.C.cmd == MachO::LC_DYLD_INFO) {
1376 if ((Err = checkDyldInfoCommand(*this, Load, I, &DyldInfoLoadCmd,
1377 "LC_DYLD_INFO", Elements)))
1378 return;
1379 } else if (Load.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
1380 if ((Err = checkDyldInfoCommand(*this, Load, I, &DyldInfoLoadCmd,
1381 "LC_DYLD_INFO_ONLY", Elements)))
1382 return;
1383 } else if (Load.C.cmd == MachO::LC_DYLD_CHAINED_FIXUPS) {
1384 if ((Err = checkLinkeditDataCommand(
1385 *this, Load, I, &DyldChainedFixupsLoadCmd,
1386 "LC_DYLD_CHAINED_FIXUPS", Elements, "chained fixups")))
1387 return;
1388 } else if (Load.C.cmd == MachO::LC_DYLD_EXPORTS_TRIE) {
1389 if ((Err = checkLinkeditDataCommand(
1390 *this, Load, I, &DyldExportsTrieLoadCmd, "LC_DYLD_EXPORTS_TRIE",
1391 Elements, "exports trie")))
1392 return;
1393 } else if (Load.C.cmd == MachO::LC_UUID) {
1394 if (Load.C.cmdsize != sizeof(MachO::uuid_command)) {
1395 Err = malformedError("LC_UUID command " + Twine(I) + " has incorrect "
1396 "cmdsize");
1397 return;
1398 }
1399 if (UuidLoadCmd) {
1400 Err = malformedError("more than one LC_UUID command");
1401 return;
1402 }
1403 UuidLoadCmd = Load.Ptr;
1404 } else if (Load.C.cmd == MachO::LC_SEGMENT_64) {
1407 *this, Load, Sections, HasPageZeroSegment, I,
1408 "LC_SEGMENT_64", SizeOfHeaders, Elements)))
1409 return;
1410 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
1413 *this, Load, Sections, HasPageZeroSegment, I,
1414 "LC_SEGMENT", SizeOfHeaders, Elements)))
1415 return;
1416 } else if (Load.C.cmd == MachO::LC_ID_DYLIB) {
1417 if ((Err = checkDylibIdCommand(*this, Load, I, &DyldIdLoadCmd)))
1418 return;
1419 } else if (Load.C.cmd == MachO::LC_LOAD_DYLIB) {
1420 if ((Err = checkDylibCommand(*this, Load, I, "LC_LOAD_DYLIB")))
1421 return;
1422 Libraries.push_back(Load.Ptr);
1423 } else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB) {
1424 if ((Err = checkDylibCommand(*this, Load, I, "LC_LOAD_WEAK_DYLIB")))
1425 return;
1426 Libraries.push_back(Load.Ptr);
1427 } else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB) {
1428 if ((Err = checkDylibCommand(*this, Load, I, "LC_LAZY_LOAD_DYLIB")))
1429 return;
1430 Libraries.push_back(Load.Ptr);
1431 } else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB) {
1432 if ((Err = checkDylibCommand(*this, Load, I, "LC_REEXPORT_DYLIB")))
1433 return;
1434 Libraries.push_back(Load.Ptr);
1435 } else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
1436 if ((Err = checkDylibCommand(*this, Load, I, "LC_LOAD_UPWARD_DYLIB")))
1437 return;
1438 Libraries.push_back(Load.Ptr);
1439 } else if (Load.C.cmd == MachO::LC_ID_DYLINKER) {
1440 if ((Err = checkDyldCommand(*this, Load, I, "LC_ID_DYLINKER")))
1441 return;
1442 } else if (Load.C.cmd == MachO::LC_LOAD_DYLINKER) {
1443 if ((Err = checkDyldCommand(*this, Load, I, "LC_LOAD_DYLINKER")))
1444 return;
1445 } else if (Load.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
1446 if ((Err = checkDyldCommand(*this, Load, I, "LC_DYLD_ENVIRONMENT")))
1447 return;
1448 } else if (Load.C.cmd == MachO::LC_VERSION_MIN_MACOSX) {
1449 if ((Err = checkVersCommand(*this, Load, I, &VersLoadCmd,
1450 "LC_VERSION_MIN_MACOSX")))
1451 return;
1452 } else if (Load.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS) {
1453 if ((Err = checkVersCommand(*this, Load, I, &VersLoadCmd,
1454 "LC_VERSION_MIN_IPHONEOS")))
1455 return;
1456 } else if (Load.C.cmd == MachO::LC_VERSION_MIN_TVOS) {
1457 if ((Err = checkVersCommand(*this, Load, I, &VersLoadCmd,
1458 "LC_VERSION_MIN_TVOS")))
1459 return;
1460 } else if (Load.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
1461 if ((Err = checkVersCommand(*this, Load, I, &VersLoadCmd,
1462 "LC_VERSION_MIN_WATCHOS")))
1463 return;
1464 } else if (Load.C.cmd == MachO::LC_NOTE) {
1465 if ((Err = checkNoteCommand(*this, Load, I, Elements)))
1466 return;
1467 } else if (Load.C.cmd == MachO::LC_BUILD_VERSION) {
1468 if ((Err = parseBuildVersionCommand(*this, Load, BuildTools, I)))
1469 return;
1470 } else if (Load.C.cmd == MachO::LC_RPATH) {
1471 if ((Err = checkRpathCommand(*this, Load, I)))
1472 return;
1473 } else if (Load.C.cmd == MachO::LC_SOURCE_VERSION) {
1474 if (Load.C.cmdsize != sizeof(MachO::source_version_command)) {
1475 Err = malformedError("LC_SOURCE_VERSION command " + Twine(I) +
1476 " has incorrect cmdsize");
1477 return;
1478 }
1479 if (SourceLoadCmd) {
1480 Err = malformedError("more than one LC_SOURCE_VERSION command");
1481 return;
1482 }
1483 SourceLoadCmd = Load.Ptr;
1484 } else if (Load.C.cmd == MachO::LC_MAIN) {
1485 if (Load.C.cmdsize != sizeof(MachO::entry_point_command)) {
1486 Err = malformedError("LC_MAIN command " + Twine(I) +
1487 " has incorrect cmdsize");
1488 return;
1489 }
1490 if (EntryPointLoadCmd) {
1491 Err = malformedError("more than one LC_MAIN command");
1492 return;
1493 }
1494 EntryPointLoadCmd = Load.Ptr;
1495 } else if (Load.C.cmd == MachO::LC_ENCRYPTION_INFO) {
1496 if (Load.C.cmdsize != sizeof(MachO::encryption_info_command)) {
1497 Err = malformedError("LC_ENCRYPTION_INFO command " + Twine(I) +
1498 " has incorrect cmdsize");
1499 return;
1500 }
1502 getStruct<MachO::encryption_info_command>(*this, Load.Ptr);
1503 if ((Err = checkEncryptCommand(*this, Load, I, E.cryptoff, E.cryptsize,
1504 &EncryptLoadCmd, "LC_ENCRYPTION_INFO")))
1505 return;
1506 } else if (Load.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
1507 if (Load.C.cmdsize != sizeof(MachO::encryption_info_command_64)) {
1508 Err = malformedError("LC_ENCRYPTION_INFO_64 command " + Twine(I) +
1509 " has incorrect cmdsize");
1510 return;
1511 }
1513 getStruct<MachO::encryption_info_command_64>(*this, Load.Ptr);
1514 if ((Err = checkEncryptCommand(*this, Load, I, E.cryptoff, E.cryptsize,
1515 &EncryptLoadCmd, "LC_ENCRYPTION_INFO_64")))
1516 return;
1517 } else if (Load.C.cmd == MachO::LC_LINKER_OPTION) {
1518 if ((Err = checkLinkerOptCommand(*this, Load, I)))
1519 return;
1520 } else if (Load.C.cmd == MachO::LC_SUB_FRAMEWORK) {
1521 if (Load.C.cmdsize < sizeof(MachO::sub_framework_command)) {
1522 Err = malformedError("load command " + Twine(I) +
1523 " LC_SUB_FRAMEWORK cmdsize too small");
1524 return;
1525 }
1527 getStruct<MachO::sub_framework_command>(*this, Load.Ptr);
1528 if ((Err = checkSubCommand(*this, Load, I, "LC_SUB_FRAMEWORK",
1530 "sub_framework_command", S.umbrella,
1531 "umbrella")))
1532 return;
1533 } else if (Load.C.cmd == MachO::LC_SUB_UMBRELLA) {
1534 if (Load.C.cmdsize < sizeof(MachO::sub_umbrella_command)) {
1535 Err = malformedError("load command " + Twine(I) +
1536 " LC_SUB_UMBRELLA cmdsize too small");
1537 return;
1538 }
1540 getStruct<MachO::sub_umbrella_command>(*this, Load.Ptr);
1541 if ((Err = checkSubCommand(*this, Load, I, "LC_SUB_UMBRELLA",
1543 "sub_umbrella_command", S.sub_umbrella,
1544 "sub_umbrella")))
1545 return;
1546 } else if (Load.C.cmd == MachO::LC_SUB_LIBRARY) {
1547 if (Load.C.cmdsize < sizeof(MachO::sub_library_command)) {
1548 Err = malformedError("load command " + Twine(I) +
1549 " LC_SUB_LIBRARY cmdsize too small");
1550 return;
1551 }
1553 getStruct<MachO::sub_library_command>(*this, Load.Ptr);
1554 if ((Err = checkSubCommand(*this, Load, I, "LC_SUB_LIBRARY",
1556 "sub_library_command", S.sub_library,
1557 "sub_library")))
1558 return;
1559 } else if (Load.C.cmd == MachO::LC_SUB_CLIENT) {
1560 if (Load.C.cmdsize < sizeof(MachO::sub_client_command)) {
1561 Err = malformedError("load command " + Twine(I) +
1562 " LC_SUB_CLIENT cmdsize too small");
1563 return;
1564 }
1566 getStruct<MachO::sub_client_command>(*this, Load.Ptr);
1567 if ((Err = checkSubCommand(*this, Load, I, "LC_SUB_CLIENT",
1569 "sub_client_command", S.client, "client")))
1570 return;
1571 } else if (Load.C.cmd == MachO::LC_ROUTINES) {
1572 if (Load.C.cmdsize != sizeof(MachO::routines_command)) {
1573 Err = malformedError("LC_ROUTINES command " + Twine(I) +
1574 " has incorrect cmdsize");
1575 return;
1576 }
1577 if (RoutinesLoadCmd) {
1578 Err = malformedError("more than one LC_ROUTINES and or LC_ROUTINES_64 "
1579 "command");
1580 return;
1581 }
1582 RoutinesLoadCmd = Load.Ptr;
1583 } else if (Load.C.cmd == MachO::LC_ROUTINES_64) {
1584 if (Load.C.cmdsize != sizeof(MachO::routines_command_64)) {
1585 Err = malformedError("LC_ROUTINES_64 command " + Twine(I) +
1586 " has incorrect cmdsize");
1587 return;
1588 }
1589 if (RoutinesLoadCmd) {
1590 Err = malformedError("more than one LC_ROUTINES_64 and or LC_ROUTINES "
1591 "command");
1592 return;
1593 }
1594 RoutinesLoadCmd = Load.Ptr;
1595 } else if (Load.C.cmd == MachO::LC_UNIXTHREAD) {
1596 if ((Err = checkThreadCommand(*this, Load, I, "LC_UNIXTHREAD")))
1597 return;
1598 if (UnixThreadLoadCmd) {
1599 Err = malformedError("more than one LC_UNIXTHREAD command");
1600 return;
1601 }
1602 UnixThreadLoadCmd = Load.Ptr;
1603 } else if (Load.C.cmd == MachO::LC_THREAD) {
1604 if ((Err = checkThreadCommand(*this, Load, I, "LC_THREAD")))
1605 return;
1606 // Note: LC_TWOLEVEL_HINTS is really obsolete and is not supported.
1607 } else if (Load.C.cmd == MachO::LC_TWOLEVEL_HINTS) {
1608 if ((Err = checkTwoLevelHintsCommand(*this, Load, I,
1609 &TwoLevelHintsLoadCmd, Elements)))
1610 return;
1611 } else if (Load.C.cmd == MachO::LC_IDENT) {
1612 // Note: LC_IDENT is ignored.
1613 continue;
1614 } else if (isLoadCommandObsolete(Load.C.cmd)) {
1615 Err = malformedError("load command " + Twine(I) + " for cmd value of: " +
1616 Twine(Load.C.cmd) + " is obsolete and not "
1617 "supported");
1618 return;
1619 }
1620 // TODO: generate a error for unknown load commands by default. But still
1621 // need work out an approach to allow or not allow unknown values like this
1622 // as an option for some uses like lldb.
1623 if (I < LoadCommandCount - 1) {
1624 if (auto LoadOrErr = getNextLoadCommandInfo(*this, I, Load))
1625 Load = *LoadOrErr;
1626 else {
1627 Err = LoadOrErr.takeError();
1628 return;
1629 }
1630 }
1631 }
1632 if (!SymtabLoadCmd) {
1633 if (DysymtabLoadCmd) {
1634 Err = malformedError("contains LC_DYSYMTAB load command without a "
1635 "LC_SYMTAB load command");
1636 return;
1637 }
1638 } else if (DysymtabLoadCmd) {
1639 MachO::symtab_command Symtab =
1640 getStruct<MachO::symtab_command>(*this, SymtabLoadCmd);
1641 MachO::dysymtab_command Dysymtab =
1642 getStruct<MachO::dysymtab_command>(*this, DysymtabLoadCmd);
1643 if (Dysymtab.nlocalsym != 0 && Dysymtab.ilocalsym > Symtab.nsyms) {
1644 Err = malformedError("ilocalsym in LC_DYSYMTAB load command "
1645 "extends past the end of the symbol table");
1646 return;
1647 }
1648 uint64_t BigSize = Dysymtab.ilocalsym;
1649 BigSize += Dysymtab.nlocalsym;
1650 if (Dysymtab.nlocalsym != 0 && BigSize > Symtab.nsyms) {
1651 Err = malformedError("ilocalsym plus nlocalsym in LC_DYSYMTAB load "
1652 "command extends past the end of the symbol table");
1653 return;
1654 }
1655 if (Dysymtab.nextdefsym != 0 && Dysymtab.iextdefsym > Symtab.nsyms) {
1656 Err = malformedError("iextdefsym in LC_DYSYMTAB load command "
1657 "extends past the end of the symbol table");
1658 return;
1659 }
1660 BigSize = Dysymtab.iextdefsym;
1661 BigSize += Dysymtab.nextdefsym;
1662 if (Dysymtab.nextdefsym != 0 && BigSize > Symtab.nsyms) {
1663 Err = malformedError("iextdefsym plus nextdefsym in LC_DYSYMTAB "
1664 "load command extends past the end of the symbol "
1665 "table");
1666 return;
1667 }
1668 if (Dysymtab.nundefsym != 0 && Dysymtab.iundefsym > Symtab.nsyms) {
1669 Err = malformedError("iundefsym in LC_DYSYMTAB load command "
1670 "extends past the end of the symbol table");
1671 return;
1672 }
1673 BigSize = Dysymtab.iundefsym;
1674 BigSize += Dysymtab.nundefsym;
1675 if (Dysymtab.nundefsym != 0 && BigSize > Symtab.nsyms) {
1676 Err = malformedError("iundefsym plus nundefsym in LC_DYSYMTAB load "
1677 " command extends past the end of the symbol table");
1678 return;
1679 }
1680 }
1681 if ((getHeader().filetype == MachO::MH_DYLIB ||
1682 getHeader().filetype == MachO::MH_DYLIB_STUB) &&
1683 DyldIdLoadCmd == nullptr) {
1684 Err = malformedError("no LC_ID_DYLIB load command in dynamic library "
1685 "filetype");
1686 return;
1687 }
1688 assert(LoadCommands.size() == LoadCommandCount);
1689
1690 Err = Error::success();
1691}
1692
1694 uint32_t Flags = 0;
1695 if (is64Bit()) {
1697 Flags = H_64.flags;
1698 } else {
1700 Flags = H.flags;
1701 }
1702 uint8_t NType = 0;
1703 uint8_t NSect = 0;
1704 uint16_t NDesc = 0;
1705 uint32_t NStrx = 0;
1706 uint64_t NValue = 0;
1707 uint32_t SymbolIndex = 0;
1709 for (const SymbolRef &Symbol : symbols()) {
1710 DataRefImpl SymDRI = Symbol.getRawDataRefImpl();
1711 if (is64Bit()) {
1712 MachO::nlist_64 STE_64 = getSymbol64TableEntry(SymDRI);
1713 NType = STE_64.n_type;
1714 NSect = STE_64.n_sect;
1715 NDesc = STE_64.n_desc;
1716 NStrx = STE_64.n_strx;
1717 NValue = STE_64.n_value;
1718 } else {
1719 MachO::nlist STE = getSymbolTableEntry(SymDRI);
1720 NType = STE.n_type;
1721 NSect = STE.n_sect;
1722 NDesc = STE.n_desc;
1723 NStrx = STE.n_strx;
1724 NValue = STE.n_value;
1725 }
1726 if ((NType & MachO::N_STAB) == 0) {
1727 if ((NType & MachO::N_TYPE) == MachO::N_SECT) {
1728 if (NSect == 0 || NSect > Sections.size())
1729 return malformedError("bad section index: " + Twine((int)NSect) +
1730 " for symbol at index " + Twine(SymbolIndex));
1731 }
1732 if ((NType & MachO::N_TYPE) == MachO::N_INDR) {
1733 if (NValue >= S.strsize)
1734 return malformedError("bad n_value: " + Twine((int)NValue) + " past "
1735 "the end of string table, for N_INDR symbol at "
1736 "index " + Twine(SymbolIndex));
1737 }
1739 (((NType & MachO::N_TYPE) == MachO::N_UNDF && NValue == 0) ||
1740 (NType & MachO::N_TYPE) == MachO::N_PBUD)) {
1741 uint32_t LibraryOrdinal = MachO::GET_LIBRARY_ORDINAL(NDesc);
1742 if (LibraryOrdinal != 0 &&
1743 LibraryOrdinal != MachO::EXECUTABLE_ORDINAL &&
1744 LibraryOrdinal != MachO::DYNAMIC_LOOKUP_ORDINAL &&
1745 LibraryOrdinal - 1 >= Libraries.size() ) {
1746 return malformedError("bad library ordinal: " + Twine(LibraryOrdinal) +
1747 " for symbol at index " + Twine(SymbolIndex));
1748 }
1749 }
1750 }
1751 if (NStrx >= S.strsize)
1752 return malformedError("bad string table index: " + Twine((int)NStrx) +
1753 " past the end of string table, for symbol at "
1754 "index " + Twine(SymbolIndex));
1755 SymbolIndex++;
1756 }
1757 return Error::success();
1758}
1759
1761 unsigned SymbolTableEntrySize = is64Bit() ?
1762 sizeof(MachO::nlist_64) :
1763 sizeof(MachO::nlist);
1764 Symb.p += SymbolTableEntrySize;
1765}
1766
1768 StringRef StringTable = getStringTableData();
1769 MachO::nlist_base Entry = getSymbolTableEntryBase(*this, Symb);
1770 if (Entry.n_strx == 0)
1771 // A n_strx value of 0 indicates that no name is associated with a
1772 // particular symbol table entry.
1773 return StringRef();
1774 const char *Start = &StringTable.data()[Entry.n_strx];
1775 if (Start < getData().begin() || Start >= getData().end()) {
1776 return malformedError("bad string index: " + Twine(Entry.n_strx) +
1777 " for symbol at index " + Twine(getSymbolIndex(Symb)));
1778 }
1779 return StringRef(Start);
1780}
1781
1783 DataRefImpl DRI = Sec.getRawDataRefImpl();
1784 uint32_t Flags = getSectionFlags(*this, DRI);
1785 return Flags & MachO::SECTION_TYPE;
1786}
1787
1789 if (is64Bit()) {
1791 return Entry.n_value;
1792 }
1793 MachO::nlist Entry = getSymbolTableEntry(Sym);
1794 return Entry.n_value;
1795}
1796
1797// getIndirectName() returns the name of the alias'ed symbol who's string table
1798// index is in the n_value field.
1800 StringRef &Res) const {
1801 StringRef StringTable = getStringTableData();
1802 MachO::nlist_base Entry = getSymbolTableEntryBase(*this, Symb);
1803 if ((Entry.n_type & MachO::N_TYPE) != MachO::N_INDR)
1805 uint64_t NValue = getNValue(Symb);
1806 if (NValue >= StringTable.size())
1808 const char *Start = &StringTable.data()[NValue];
1809 Res = StringRef(Start);
1810 return std::error_code();
1811}
1812
1813uint64_t MachOObjectFile::getSymbolValueImpl(DataRefImpl Sym) const {
1814 return getNValue(Sym);
1815}
1816
1818 return getSymbolValue(Sym);
1819}
1820
1824 MachO::nlist_base Entry = getSymbolTableEntryBase(*this, DRI);
1825 return 1 << MachO::GET_COMM_ALIGN(Entry.n_desc);
1826 }
1827 return 0;
1828}
1829
1831 return getNValue(DRI);
1832}
1833
1836 MachO::nlist_base Entry = getSymbolTableEntryBase(*this, Symb);
1837 uint8_t n_type = Entry.n_type;
1838
1839 // If this is a STAB debugging symbol, we can do nothing more.
1840 if (n_type & MachO::N_STAB)
1841 return SymbolRef::ST_Debug;
1842
1843 switch (n_type & MachO::N_TYPE) {
1844 case MachO::N_UNDF :
1845 return SymbolRef::ST_Unknown;
1846 case MachO::N_SECT :
1848 if (!SecOrError)
1849 return SecOrError.takeError();
1850 section_iterator Sec = *SecOrError;
1851 if (Sec == section_end())
1852 return SymbolRef::ST_Other;
1853 if (Sec->isData() || Sec->isBSS())
1854 return SymbolRef::ST_Data;
1856 }
1857 return SymbolRef::ST_Other;
1858}
1859
1861 MachO::nlist_base Entry = getSymbolTableEntryBase(*this, DRI);
1862
1863 uint8_t MachOType = Entry.n_type;
1864 uint16_t MachOFlags = Entry.n_desc;
1865
1867
1868 if ((MachOType & MachO::N_TYPE) == MachO::N_INDR)
1869 Result |= SymbolRef::SF_Indirect;
1870
1871 if (MachOType & MachO::N_STAB)
1873
1874 if (MachOType & MachO::N_EXT) {
1875 Result |= SymbolRef::SF_Global;
1876 if ((MachOType & MachO::N_TYPE) == MachO::N_UNDF) {
1877 if (getNValue(DRI))
1878 Result |= SymbolRef::SF_Common;
1879 else
1880 Result |= SymbolRef::SF_Undefined;
1881 }
1882
1883 if (MachOType & MachO::N_PEXT)
1884 Result |= SymbolRef::SF_Hidden;
1885 else
1886 Result |= SymbolRef::SF_Exported;
1887
1888 } else if (MachOType & MachO::N_PEXT)
1889 Result |= SymbolRef::SF_Hidden;
1890
1891 if (MachOFlags & (MachO::N_WEAK_REF | MachO::N_WEAK_DEF))
1892 Result |= SymbolRef::SF_Weak;
1893
1894 if (MachOFlags & (MachO::N_ARM_THUMB_DEF))
1895 Result |= SymbolRef::SF_Thumb;
1896
1897 if ((MachOType & MachO::N_TYPE) == MachO::N_ABS)
1898 Result |= SymbolRef::SF_Absolute;
1899
1900 return Result;
1901}
1902
1905 MachO::nlist_base Entry = getSymbolTableEntryBase(*this, Symb);
1906 uint8_t index = Entry.n_sect;
1907
1908 if (index == 0)
1909 return section_end();
1910 DataRefImpl DRI;
1911 DRI.d.a = index - 1;
1912 if (DRI.d.a >= Sections.size()){
1913 return malformedError("bad section index: " + Twine((int)index) +
1914 " for symbol at index " + Twine(getSymbolIndex(Symb)));
1915 }
1916 return section_iterator(SectionRef(DRI, this));
1917}
1918
1920 MachO::nlist_base Entry =
1922 return Entry.n_sect - 1;
1923}
1924
1926 Sec.d.a++;
1927}
1928
1931 return parseSegmentOrSectionName(Raw.data());
1932}
1933
1935 if (is64Bit())
1936 return getSection64(Sec).addr;
1937 return getSection(Sec).addr;
1938}
1939
1941 return Sec.d.a;
1942}
1943
1945 // In the case if a malformed Mach-O file where the section offset is past
1946 // the end of the file or some part of the section size is past the end of
1947 // the file return a size of zero or a size that covers the rest of the file
1948 // but does not extend past the end of the file.
1949 uint32_t SectOffset, SectType;
1950 uint64_t SectSize;
1951
1952 if (is64Bit()) {
1953 MachO::section_64 Sect = getSection64(Sec);
1954 SectOffset = Sect.offset;
1955 SectSize = Sect.size;
1956 SectType = Sect.flags & MachO::SECTION_TYPE;
1957 } else {
1958 MachO::section Sect = getSection(Sec);
1959 SectOffset = Sect.offset;
1960 SectSize = Sect.size;
1961 SectType = Sect.flags & MachO::SECTION_TYPE;
1962 }
1963 if (SectType == MachO::S_ZEROFILL || SectType == MachO::S_GB_ZEROFILL)
1964 return SectSize;
1965 uint64_t FileSize = getData().size();
1966 if (SectOffset > FileSize)
1967 return 0;
1968 if (FileSize - SectOffset < SectSize)
1969 return FileSize - SectOffset;
1970 return SectSize;
1971}
1972
1974 uint64_t Size) const {
1975 return arrayRefFromStringRef(getData().substr(Offset, Size));
1976}
1977
1981 uint64_t Size;
1982
1983 if (is64Bit()) {
1984 MachO::section_64 Sect = getSection64(Sec);
1985 Offset = Sect.offset;
1986 Size = Sect.size;
1987 } else {
1988 MachO::section Sect = getSection(Sec);
1989 Offset = Sect.offset;
1990 Size = Sect.size;
1991 }
1992
1994}
1995
1998 if (is64Bit()) {
1999 MachO::section_64 Sect = getSection64(Sec);
2000 Align = Sect.align;
2001 } else {
2002 MachO::section Sect = getSection(Sec);
2003 Align = Sect.align;
2004 }
2005
2006 return uint64_t(1) << Align;
2007}
2008
2010 if (SectionIndex < 1 || SectionIndex > Sections.size())
2011 return malformedError("bad section index: " + Twine((int)SectionIndex));
2012
2013 DataRefImpl DRI;
2014 DRI.d.a = SectionIndex - 1;
2015 return SectionRef(DRI, this);
2016}
2017
2019 for (const SectionRef &Section : sections()) {
2020 auto NameOrErr = Section.getName();
2021 if (!NameOrErr)
2022 return NameOrErr.takeError();
2023 if (*NameOrErr == SectionName)
2024 return Section;
2025 }
2027}
2028
2030 return false;
2031}
2032
2034 uint32_t Flags = getSectionFlags(*this, Sec);
2036}
2037
2039 uint32_t Flags = getSectionFlags(*this, Sec);
2040 unsigned SectionType = Flags & MachO::SECTION_TYPE;
2042 !(SectionType == MachO::S_ZEROFILL ||
2043 SectionType == MachO::S_GB_ZEROFILL);
2044}
2045
2047 uint32_t Flags = getSectionFlags(*this, Sec);
2048 unsigned SectionType = Flags & MachO::SECTION_TYPE;
2050 (SectionType == MachO::S_ZEROFILL ||
2051 SectionType == MachO::S_GB_ZEROFILL);
2052}
2053
2055 Expected<StringRef> SectionNameOrErr = getSectionName(Sec);
2056 if (!SectionNameOrErr) {
2057 // TODO: Report the error message properly.
2058 consumeError(SectionNameOrErr.takeError());
2059 return false;
2060 }
2061 StringRef SectionName = SectionNameOrErr.get();
2062 return SectionName.startswith("__debug") ||
2063 SectionName.startswith("__zdebug") ||
2064 SectionName.startswith("__apple") || SectionName == "__gdb_index" ||
2065 SectionName == "__swift_ast";
2066}
2067
2068namespace {
2069template <typename LoadCommandType>
2070ArrayRef<uint8_t> getSegmentContents(const MachOObjectFile &Obj,
2072 StringRef SegmentName) {
2073 auto SegmentOrErr = getStructOrErr<LoadCommandType>(Obj, LoadCmd.Ptr);
2074 if (!SegmentOrErr) {
2075 consumeError(SegmentOrErr.takeError());
2076 return {};
2077 }
2078 auto &Segment = SegmentOrErr.get();
2079 if (StringRef(Segment.segname, 16).startswith(SegmentName))
2080 return arrayRefFromStringRef(Obj.getData().slice(
2081 Segment.fileoff, Segment.fileoff + Segment.filesize));
2082 return {};
2083}
2084
2085template <typename LoadCommandType>
2086ArrayRef<uint8_t> getSegmentContents(const MachOObjectFile &Obj,
2088 auto SegmentOrErr = getStructOrErr<LoadCommandType>(Obj, LoadCmd.Ptr);
2089 if (!SegmentOrErr) {
2090 consumeError(SegmentOrErr.takeError());
2091 return {};
2092 }
2093 auto &Segment = SegmentOrErr.get();
2094 return arrayRefFromStringRef(
2095 Obj.getData().slice(Segment.fileoff, Segment.fileoff + Segment.filesize));
2096}
2097} // namespace
2098
2101 for (auto LoadCmd : load_commands()) {
2102 ArrayRef<uint8_t> Contents;
2103 switch (LoadCmd.C.cmd) {
2104 case MachO::LC_SEGMENT:
2105 Contents = ::getSegmentContents<MachO::segment_command>(*this, LoadCmd,
2106 SegmentName);
2107 break;
2108 case MachO::LC_SEGMENT_64:
2109 Contents = ::getSegmentContents<MachO::segment_command_64>(*this, LoadCmd,
2110 SegmentName);
2111 break;
2112 default:
2113 continue;
2114 }
2115 if (!Contents.empty())
2116 return Contents;
2117 }
2118 return {};
2119}
2120
2122MachOObjectFile::getSegmentContents(size_t SegmentIndex) const {
2123 size_t Idx = 0;
2124 for (auto LoadCmd : load_commands()) {
2125 switch (LoadCmd.C.cmd) {
2126 case MachO::LC_SEGMENT:
2127 if (Idx == SegmentIndex)
2128 return ::getSegmentContents<MachO::segment_command>(*this, LoadCmd);
2129 ++Idx;
2130 break;
2131 case MachO::LC_SEGMENT_64:
2132 if (Idx == SegmentIndex)
2133 return ::getSegmentContents<MachO::segment_command_64>(*this, LoadCmd);
2134 ++Idx;
2135 break;
2136 default:
2137 continue;
2138 }
2139 }
2140 return {};
2141}
2142
2144 return Sec.getRawDataRefImpl().d.a;
2145}
2146
2148 uint32_t Flags = getSectionFlags(*this, Sec);
2149 unsigned SectionType = Flags & MachO::SECTION_TYPE;
2150 return SectionType == MachO::S_ZEROFILL ||
2151 SectionType == MachO::S_GB_ZEROFILL;
2152}
2153
2155 StringRef SegmentName = getSectionFinalSegmentName(Sec);
2156 if (Expected<StringRef> NameOrErr = getSectionName(Sec))
2157 return (SegmentName == "__LLVM" && *NameOrErr == "__bitcode");
2158 return false;
2159}
2160
2162 if (is64Bit())
2163 return getSection64(Sec).offset == 0;
2164 return getSection(Sec).offset == 0;
2165}
2166
2168 DataRefImpl Ret;
2169 Ret.d.a = Sec.d.a;
2170 Ret.d.b = 0;
2171 return relocation_iterator(RelocationRef(Ret, this));
2172}
2173
2176 uint32_t Num;
2177 if (is64Bit()) {
2178 MachO::section_64 Sect = getSection64(Sec);
2179 Num = Sect.nreloc;
2180 } else {
2181 MachO::section Sect = getSection(Sec);
2182 Num = Sect.nreloc;
2183 }
2184
2185 DataRefImpl Ret;
2186 Ret.d.a = Sec.d.a;
2187 Ret.d.b = Num;
2188 return relocation_iterator(RelocationRef(Ret, this));
2189}
2190
2192 DataRefImpl Ret;
2193 // for DYSYMTAB symbols, Ret.d.a == 0 for external relocations
2194 Ret.d.a = 0; // Would normally be a section index.
2195 Ret.d.b = 0; // Index into the external relocations
2196 return relocation_iterator(RelocationRef(Ret, this));
2197}
2198
2201 DataRefImpl Ret;
2202 // for DYSYMTAB symbols, Ret.d.a == 0 for external relocations
2203 Ret.d.a = 0; // Would normally be a section index.
2204 Ret.d.b = DysymtabLoadCmd.nextrel; // Index into the external relocations
2205 return relocation_iterator(RelocationRef(Ret, this));
2206}
2207
2209 DataRefImpl Ret;
2210 // for DYSYMTAB symbols, Ret.d.a == 1 for local relocations
2211 Ret.d.a = 1; // Would normally be a section index.
2212 Ret.d.b = 0; // Index into the local relocations
2213 return relocation_iterator(RelocationRef(Ret, this));
2214}
2215
2218 DataRefImpl Ret;
2219 // for DYSYMTAB symbols, Ret.d.a == 1 for local relocations
2220 Ret.d.a = 1; // Would normally be a section index.
2221 Ret.d.b = DysymtabLoadCmd.nlocrel; // Index into the local relocations
2222 return relocation_iterator(RelocationRef(Ret, this));
2223}
2224
2226 ++Rel.d.b;
2227}
2228
2230 assert((getHeader().filetype == MachO::MH_OBJECT ||
2231 getHeader().filetype == MachO::MH_KEXT_BUNDLE) &&
2232 "Only implemented for MH_OBJECT && MH_KEXT_BUNDLE");
2234 return getAnyRelocationAddress(RE);
2235}
2236
2240 if (isRelocationScattered(RE))
2241 return symbol_end();
2242
2243 uint32_t SymbolIdx = getPlainRelocationSymbolNum(RE);
2244 bool isExtern = getPlainRelocationExternal(RE);
2245 if (!isExtern)
2246 return symbol_end();
2247
2249 unsigned SymbolTableEntrySize = is64Bit() ?
2250 sizeof(MachO::nlist_64) :
2251 sizeof(MachO::nlist);
2252 uint64_t Offset = S.symoff + SymbolIdx * SymbolTableEntrySize;
2253 DataRefImpl Sym;
2254 Sym.p = reinterpret_cast<uintptr_t>(getPtr(*this, Offset));
2255 return symbol_iterator(SymbolRef(Sym, this));
2256}
2257
2261}
2262
2265 return getAnyRelocationType(RE);
2266}
2267
2269 DataRefImpl Rel, SmallVectorImpl<char> &Result) const {
2270 StringRef res;
2271 uint64_t RType = getRelocationType(Rel);
2272
2273 unsigned Arch = this->getArch();
2274
2275 switch (Arch) {
2276 case Triple::x86: {
2277 static const char *const Table[] = {
2278 "GENERIC_RELOC_VANILLA",
2279 "GENERIC_RELOC_PAIR",
2280 "GENERIC_RELOC_SECTDIFF",
2281 "GENERIC_RELOC_PB_LA_PTR",
2282 "GENERIC_RELOC_LOCAL_SECTDIFF",
2283 "GENERIC_RELOC_TLV" };
2284
2285 if (RType > 5)
2286 res = "Unknown";
2287 else
2288 res = Table[RType];
2289 break;
2290 }
2291 case Triple::x86_64: {
2292 static const char *const Table[] = {
2293 "X86_64_RELOC_UNSIGNED",
2294 "X86_64_RELOC_SIGNED",
2295 "X86_64_RELOC_BRANCH",
2296 "X86_64_RELOC_GOT_LOAD",
2297 "X86_64_RELOC_GOT",
2298 "X86_64_RELOC_SUBTRACTOR",
2299 "X86_64_RELOC_SIGNED_1",
2300 "X86_64_RELOC_SIGNED_2",
2301 "X86_64_RELOC_SIGNED_4",
2302 "X86_64_RELOC_TLV" };
2303
2304 if (RType > 9)
2305 res = "Unknown";
2306 else
2307 res = Table[RType];
2308 break;
2309 }
2310 case Triple::arm: {
2311 static const char *const Table[] = {
2312 "ARM_RELOC_VANILLA",
2313 "ARM_RELOC_PAIR",
2314 "ARM_RELOC_SECTDIFF",
2315 "ARM_RELOC_LOCAL_SECTDIFF",
2316 "ARM_RELOC_PB_LA_PTR",
2317 "ARM_RELOC_BR24",
2318 "ARM_THUMB_RELOC_BR22",
2319 "ARM_THUMB_32BIT_BRANCH",
2320 "ARM_RELOC_HALF",
2321 "ARM_RELOC_HALF_SECTDIFF" };
2322
2323 if (RType > 9)
2324 res = "Unknown";
2325 else
2326 res = Table[RType];
2327 break;
2328 }
2329 case Triple::aarch64:
2330 case Triple::aarch64_32: {
2331 static const char *const Table[] = {
2332 "ARM64_RELOC_UNSIGNED", "ARM64_RELOC_SUBTRACTOR",
2333 "ARM64_RELOC_BRANCH26", "ARM64_RELOC_PAGE21",
2334 "ARM64_RELOC_PAGEOFF12", "ARM64_RELOC_GOT_LOAD_PAGE21",
2335 "ARM64_RELOC_GOT_LOAD_PAGEOFF12", "ARM64_RELOC_POINTER_TO_GOT",
2336 "ARM64_RELOC_TLVP_LOAD_PAGE21", "ARM64_RELOC_TLVP_LOAD_PAGEOFF12",
2337 "ARM64_RELOC_ADDEND"
2338 };
2339
2340 if (RType >= std::size(Table))
2341 res = "Unknown";
2342 else
2343 res = Table[RType];
2344 break;
2345 }
2346 case Triple::ppc: {
2347 static const char *const Table[] = {
2348 "PPC_RELOC_VANILLA",
2349 "PPC_RELOC_PAIR",
2350 "PPC_RELOC_BR14",
2351 "PPC_RELOC_BR24",
2352 "PPC_RELOC_HI16",
2353 "PPC_RELOC_LO16",
2354 "PPC_RELOC_HA16",
2355 "PPC_RELOC_LO14",
2356 "PPC_RELOC_SECTDIFF",
2357 "PPC_RELOC_PB_LA_PTR",
2358 "PPC_RELOC_HI16_SECTDIFF",
2359 "PPC_RELOC_LO16_SECTDIFF",
2360 "PPC_RELOC_HA16_SECTDIFF",
2361 "PPC_RELOC_JBSR",
2362 "PPC_RELOC_LO14_SECTDIFF",
2363 "PPC_RELOC_LOCAL_SECTDIFF" };
2364
2365 if (RType > 15)
2366 res = "Unknown";
2367 else
2368 res = Table[RType];
2369 break;
2370 }
2372 res = "Unknown";
2373 break;
2374 }
2375 Result.append(res.begin(), res.end());
2376}
2377
2380 return getAnyRelocationLength(RE);
2381}
2382
2383//
2384// guessLibraryShortName() is passed a name of a dynamic library and returns a
2385// guess on what the short name is. Then name is returned as a substring of the
2386// StringRef Name passed in. The name of the dynamic library is recognized as
2387// a framework if it has one of the two following forms:
2388// Foo.framework/Versions/A/Foo
2389// Foo.framework/Foo
2390// Where A and Foo can be any string. And may contain a trailing suffix
2391// starting with an underbar. If the Name is recognized as a framework then
2392// isFramework is set to true else it is set to false. If the Name has a
2393// suffix then Suffix is set to the substring in Name that contains the suffix
2394// else it is set to a NULL StringRef.
2395//
2396// The Name of the dynamic library is recognized as a library name if it has
2397// one of the two following forms:
2398// libFoo.A.dylib
2399// libFoo.dylib
2400//
2401// The library may have a suffix trailing the name Foo of the form:
2402// libFoo_profile.A.dylib
2403// libFoo_profile.dylib
2404// These dyld image suffixes are separated from the short name by a '_'
2405// character. Because the '_' character is commonly used to separate words in
2406// filenames guessLibraryShortName() cannot reliably separate a dylib's short
2407// name from an arbitrary image suffix; imagine if both the short name and the
2408// suffix contains an '_' character! To better deal with this ambiguity,
2409// guessLibraryShortName() will recognize only "_debug" and "_profile" as valid
2410// Suffix values. Calling code needs to be tolerant of guessLibraryShortName()
2411// guessing incorrectly.
2412//
2413// The Name of the dynamic library is also recognized as a library name if it
2414// has the following form:
2415// Foo.qtx
2416//
2417// If the Name of the dynamic library is none of the forms above then a NULL
2418// StringRef is returned.
2420 bool &isFramework,
2421 StringRef &Suffix) {
2422 StringRef Foo, F, DotFramework, V, Dylib, Lib, Dot, Qtx;
2423 size_t a, b, c, d, Idx;
2424
2425 isFramework = false;
2426 Suffix = StringRef();
2427
2428 // Pull off the last component and make Foo point to it
2429 a = Name.rfind('/');
2430 if (a == Name.npos || a == 0)
2431 goto guess_library;
2432 Foo = Name.slice(a+1, Name.npos);
2433
2434 // Look for a suffix starting with a '_'
2435 Idx = Foo.rfind('_');
2436 if (Idx != Foo.npos && Foo.size() >= 2) {
2437 Suffix = Foo.slice(Idx, Foo.npos);
2438 if (Suffix != "_debug" && Suffix != "_profile")
2439 Suffix = StringRef();
2440 else
2441 Foo = Foo.slice(0, Idx);
2442 }
2443
2444 // First look for the form Foo.framework/Foo
2445 b = Name.rfind('/', a);
2446 if (b == Name.npos)
2447 Idx = 0;
2448 else
2449 Idx = b+1;
2450 F = Name.slice(Idx, Idx + Foo.size());
2451 DotFramework = Name.slice(Idx + Foo.size(),
2452 Idx + Foo.size() + sizeof(".framework/")-1);
2453 if (F == Foo && DotFramework == ".framework/") {
2454 isFramework = true;
2455 return Foo;
2456 }
2457
2458 // Next look for the form Foo.framework/Versions/A/Foo
2459 if (b == Name.npos)
2460 goto guess_library;
2461 c = Name.rfind('/', b);
2462 if (c == Name.npos || c == 0)
2463 goto guess_library;
2464 V = Name.slice(c+1, Name.npos);
2465 if (!V.startswith("Versions/"))
2466 goto guess_library;
2467 d = Name.rfind('/', c);
2468 if (d == Name.npos)
2469 Idx = 0;
2470 else
2471 Idx = d+1;
2472 F = Name.slice(Idx, Idx + Foo.size());
2473 DotFramework = Name.slice(Idx + Foo.size(),
2474 Idx + Foo.size() + sizeof(".framework/")-1);
2475 if (F == Foo && DotFramework == ".framework/") {
2476 isFramework = true;
2477 return Foo;
2478 }
2479
2480guess_library:
2481 // pull off the suffix after the "." and make a point to it
2482 a = Name.rfind('.');
2483 if (a == Name.npos || a == 0)
2484 return StringRef();
2485 Dylib = Name.slice(a, Name.npos);
2486 if (Dylib != ".dylib")
2487 goto guess_qtx;
2488
2489 // First pull off the version letter for the form Foo.A.dylib if any.
2490 if (a >= 3) {
2491 Dot = Name.slice(a-2, a-1);
2492 if (Dot == ".")
2493 a = a - 2;
2494 }
2495
2496 b = Name.rfind('/', a);
2497 if (b == Name.npos)
2498 b = 0;
2499 else
2500 b = b+1;
2501 // ignore any suffix after an underbar like Foo_profile.A.dylib
2502 Idx = Name.rfind('_');
2503 if (Idx != Name.npos && Idx != b) {
2504 Lib = Name.slice(b, Idx);
2505 Suffix = Name.slice(Idx, a);
2506 if (Suffix != "_debug" && Suffix != "_profile") {
2507 Suffix = StringRef();
2508 Lib = Name.slice(b, a);
2509 }
2510 }
2511 else
2512 Lib = Name.slice(b, a);
2513 // There are incorrect library names of the form:
2514 // libATS.A_profile.dylib so check for these.
2515 if (Lib.size() >= 3) {
2516 Dot = Lib.slice(Lib.size()-2, Lib.size()-1);
2517 if (Dot == ".")
2518 Lib = Lib.slice(0, Lib.size()-2);
2519 }
2520 return Lib;
2521
2522guess_qtx:
2523 Qtx = Name.slice(a, Name.npos);
2524 if (Qtx != ".qtx")
2525 return StringRef();
2526 b = Name.rfind('/', a);
2527 if (b == Name.npos)
2528 Lib = Name.slice(0, a);
2529 else
2530 Lib = Name.slice(b+1, a);
2531 // There are library names of the form: QT.A.qtx so check for these.
2532 if (Lib.size() >= 3) {
2533 Dot = Lib.slice(Lib.size()-2, Lib.size()-1);
2534 if (Dot == ".")
2535 Lib = Lib.slice(0, Lib.size()-2);
2536 }
2537 return Lib;
2538}
2539
2540// getLibraryShortNameByIndex() is used to get the short name of the library
2541// for an undefined symbol in a linked Mach-O binary that was linked with the
2542// normal two-level namespace default (that is MH_TWOLEVEL in the header).
2543// It is passed the index (0 - based) of the library as translated from
2544// GET_LIBRARY_ORDINAL (1 - based).
2546 StringRef &Res) const {
2547 if (Index >= Libraries.size())
2549
2550 // If the cache of LibrariesShortNames is not built up do that first for
2551 // all the Libraries.
2552 if (LibrariesShortNames.size() == 0) {
2553 for (unsigned i = 0; i < Libraries.size(); i++) {
2554 auto CommandOrErr =
2555 getStructOrErr<MachO::dylib_command>(*this, Libraries[i]);
2556 if (!CommandOrErr)
2558 MachO::dylib_command D = CommandOrErr.get();
2559 if (D.dylib.name >= D.cmdsize)
2561 const char *P = (const char *)(Libraries[i]) + D.dylib.name;
2563 if (D.dylib.name+Name.size() >= D.cmdsize)
2565 StringRef Suffix;
2566 bool isFramework;
2567 StringRef shortName = guessLibraryShortName(Name, isFramework, Suffix);
2568 if (shortName.empty())
2569 LibrariesShortNames.push_back(Name);
2570 else
2571 LibrariesShortNames.push_back(shortName);
2572 }
2573 }
2574
2575 Res = LibrariesShortNames[Index];
2576 return std::error_code();
2577}
2578
2580 return Libraries.size();
2581}
2582
2585 DataRefImpl Sec;
2586 Sec.d.a = Rel->getRawDataRefImpl().d.a;
2587 return section_iterator(SectionRef(Sec, this));
2588}
2589
2591 DataRefImpl DRI;
2593 if (!SymtabLoadCmd || Symtab.nsyms == 0)
2594 return basic_symbol_iterator(SymbolRef(DRI, this));
2595
2596 return getSymbolByIndex(0);
2597}
2598
2600 DataRefImpl DRI;
2602 if (!SymtabLoadCmd || Symtab.nsyms == 0)
2603 return basic_symbol_iterator(SymbolRef(DRI, this));
2604
2605 unsigned SymbolTableEntrySize = is64Bit() ?
2606 sizeof(MachO::nlist_64) :
2607 sizeof(MachO::nlist);
2608 unsigned Offset = Symtab.symoff +
2609 Symtab.nsyms * SymbolTableEntrySize;
2610 DRI.p = reinterpret_cast<uintptr_t>(getPtr(*this, Offset));
2611 return basic_symbol_iterator(SymbolRef(DRI, this));
2612}
2613
2616 if (!SymtabLoadCmd || Index >= Symtab.nsyms)
2617 report_fatal_error("Requested symbol index is out of range.");
2618 unsigned SymbolTableEntrySize =
2619 is64Bit() ? sizeof(MachO::nlist_64) : sizeof(MachO::nlist);
2620 DataRefImpl DRI;
2621 DRI.p = reinterpret_cast<uintptr_t>(getPtr(*this, Symtab.symoff));
2622 DRI.p += Index * SymbolTableEntrySize;
2623 return basic_symbol_iterator(SymbolRef(DRI, this));
2624}
2625
2628 if (!SymtabLoadCmd)
2629 report_fatal_error("getSymbolIndex() called with no symbol table symbol");
2630 unsigned SymbolTableEntrySize =
2631 is64Bit() ? sizeof(MachO::nlist_64) : sizeof(MachO::nlist);
2632 DataRefImpl DRIstart;
2633 DRIstart.p = reinterpret_cast<uintptr_t>(getPtr(*this, Symtab.symoff));
2634 uint64_t Index = (Symb.p - DRIstart.p) / SymbolTableEntrySize;
2635 return Index;
2636}
2637
2639 DataRefImpl DRI;
2640 return section_iterator(SectionRef(DRI, this));
2641}
2642
2644 DataRefImpl DRI;
2645 DRI.d.a = Sections.size();
2646 return section_iterator(SectionRef(DRI, this));
2647}
2648
2650 return is64Bit() ? 8 : 4;
2651}
2652
2654 unsigned CPUType = getCPUType(*this);
2655 if (!is64Bit()) {
2656 switch (CPUType) {
2658 return "Mach-O 32-bit i386";
2660 return "Mach-O arm";
2662 return "Mach-O arm64 (ILP32)";
2664 return "Mach-O 32-bit ppc";
2665 default:
2666 return "Mach-O 32-bit unknown";
2667 }
2668 }
2669
2670 switch (CPUType) {
2672 return "Mach-O 64-bit x86-64";
2674 return "Mach-O arm64";
2676 return "Mach-O 64-bit ppc64";
2677 default:
2678 return "Mach-O 64-bit unknown";
2679 }
2680}
2681
2683 switch (CPUType) {
2685 return Triple::x86;
2687 return Triple::x86_64;
2689 return Triple::arm;
2691 return Triple::aarch64;
2693 return Triple::aarch64_32;
2695 return Triple::ppc;
2697 return Triple::ppc64;
2698 default:
2699 return Triple::UnknownArch;
2700 }
2701}
2702
2704 const char **McpuDefault,
2705 const char **ArchFlag) {
2706 if (McpuDefault)
2707 *McpuDefault = nullptr;
2708 if (ArchFlag)
2709 *ArchFlag = nullptr;
2710
2711 switch (CPUType) {
2713 switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2715 if (ArchFlag)
2716 *ArchFlag = "i386";
2717 return Triple("i386-apple-darwin");
2718 default:
2719 return Triple();
2720 }
2722 switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2724 if (ArchFlag)
2725 *ArchFlag = "x86_64";
2726 return Triple("x86_64-apple-darwin");
2728 if (ArchFlag)
2729 *ArchFlag = "x86_64h";
2730 return Triple("x86_64h-apple-darwin");
2731 default:
2732 return Triple();
2733 }
2735 switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2737 if (ArchFlag)
2738 *ArchFlag = "armv4t";
2739 return Triple("armv4t-apple-darwin");
2741 if (ArchFlag)
2742 *ArchFlag = "armv5e";
2743 return Triple("armv5e-apple-darwin");
2745 if (ArchFlag)
2746 *ArchFlag = "xscale";
2747 return Triple("xscale-apple-darwin");
2749 if (ArchFlag)
2750 *ArchFlag = "armv6";
2751 return Triple("armv6-apple-darwin");
2753 if (McpuDefault)
2754 *McpuDefault = "cortex-m0";
2755 if (ArchFlag)
2756 *ArchFlag = "armv6m";
2757 return Triple("armv6m-apple-darwin");
2759 if (ArchFlag)
2760 *ArchFlag = "armv7";
2761 return Triple("armv7-apple-darwin");
2763 if (McpuDefault)
2764 *McpuDefault = "cortex-m4";
2765 if (ArchFlag)
2766 *ArchFlag = "armv7em";
2767 return Triple("thumbv7em-apple-darwin");
2769 if (McpuDefault)
2770 *McpuDefault = "cortex-a7";
2771 if (ArchFlag)
2772 *ArchFlag = "armv7k";
2773 return Triple("armv7k-apple-darwin");
2775 if (McpuDefault)
2776 *McpuDefault = "cortex-m3";
2777 if (ArchFlag)
2778 *ArchFlag = "armv7m";
2779 return Triple("thumbv7m-apple-darwin");
2781 if (McpuDefault)
2782 *McpuDefault = "cortex-a7";
2783 if (ArchFlag)
2784 *ArchFlag = "armv7s";
2785 return Triple("armv7s-apple-darwin");
2786 default:
2787 return Triple();
2788 }
2790 switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2792 if (McpuDefault)
2793 *McpuDefault = "cyclone";
2794 if (ArchFlag)
2795 *ArchFlag = "arm64";
2796 return Triple("arm64-apple-darwin");
2798 if (McpuDefault)
2799 *McpuDefault = "apple-a12";
2800 if (ArchFlag)
2801 *ArchFlag = "arm64e";
2802 return Triple("arm64e-apple-darwin");
2803 default:
2804 return Triple();
2805 }
2807 switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2809 if (McpuDefault)
2810 *McpuDefault = "cyclone";
2811 if (ArchFlag)
2812 *ArchFlag = "arm64_32";
2813 return Triple("arm64_32-apple-darwin");
2814 default:
2815 return Triple();
2816 }
2818 switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2820 if (ArchFlag)
2821 *ArchFlag = "ppc";
2822 return Triple("ppc-apple-darwin");
2823 default:
2824 return Triple();
2825 }
2827 switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2829 if (ArchFlag)
2830 *ArchFlag = "ppc64";
2831 return Triple("ppc64-apple-darwin");
2832 default:
2833 return Triple();
2834 }
2835 default:
2836 return Triple();
2837 }
2838}
2839
2842}
2843
2845 auto validArchs = getValidArchs();
2846 return llvm::is_contained(validArchs, ArchFlag);
2847}
2848
2850 static const std::array<StringRef, 18> ValidArchs = {{
2851 "i386",
2852 "x86_64",
2853 "x86_64h",
2854 "armv4t",
2855 "arm",
2856 "armv5e",
2857 "armv6",
2858 "armv6m",
2859 "armv7",
2860 "armv7em",
2861 "armv7k",
2862 "armv7m",
2863 "armv7s",
2864 "arm64",
2865 "arm64e",
2866 "arm64_32",
2867 "ppc",
2868 "ppc64",
2869 }};
2870
2871 return ValidArchs;
2872}
2873
2875 return getArch(getCPUType(*this), getCPUSubType(*this));
2876}
2877
2878Triple MachOObjectFile::getArchTriple(const char **McpuDefault) const {
2879 return getArchTriple(Header.cputype, Header.cpusubtype, McpuDefault);
2880}
2881
2883 DataRefImpl DRI;
2884 DRI.d.a = Index;
2885 return section_rel_begin(DRI);
2886}
2887
2889 DataRefImpl DRI;
2890 DRI.d.a = Index;
2891 return section_rel_end(DRI);
2892}
2893
2895 DataRefImpl DRI;
2896 if (!DataInCodeLoadCmd)
2897 return dice_iterator(DiceRef(DRI, this));
2898
2900 DRI.p = reinterpret_cast<uintptr_t>(getPtr(*this, DicLC.dataoff));
2901 return dice_iterator(DiceRef(DRI, this));
2902}
2903
2905 DataRefImpl DRI;
2906 if (!DataInCodeLoadCmd)
2907 return dice_iterator(DiceRef(DRI, this));
2908
2910 unsigned Offset = DicLC.dataoff + DicLC.datasize;
2911 DRI.p = reinterpret_cast<uintptr_t>(getPtr(*this, Offset));
2912 return dice_iterator(DiceRef(DRI, this));
2913}
2914
2916 ArrayRef<uint8_t> T) : E(E), O(O), Trie(T) {}
2917
2918void ExportEntry::moveToFirst() {
2919 ErrorAsOutParameter ErrAsOutParam(E);
2920 pushNode(0);
2921 if (*E)
2922 return;
2923 pushDownUntilBottom();
2924}
2925
2926void ExportEntry::moveToEnd() {
2927 Stack.clear();
2928 Done = true;
2929}
2930
2932 // Common case, one at end, other iterating from begin.
2933 if (Done || Other.Done)
2934 return (Done == Other.Done);
2935 // Not equal if different stack sizes.
2936 if (Stack.size() != Other.Stack.size())
2937 return false;
2938 // Not equal if different cumulative strings.
2939 if (!CumulativeString.equals(Other.CumulativeString))
2940 return false;
2941 // Equal if all nodes in both stacks match.
2942 for (unsigned i=0; i < Stack.size(); ++i) {
2943 if (Stack[i].Start != Other.Stack[i].Start)
2944 return false;
2945 }
2946 return true;
2947}
2948
2949uint64_t ExportEntry::readULEB128(const uint8_t *&Ptr, const char **error) {
2950 unsigned Count;
2951 uint64_t Result = decodeULEB128(Ptr, &Count, Trie.end(), error);
2952 Ptr += Count;
2953 if (Ptr > Trie.end())
2954 Ptr = Trie.end();
2955 return Result;
2956}
2957
2959 return CumulativeString;
2960}
2961
2963 return Stack.back().Flags;
2964}
2965
2967 return Stack.back().Address;
2968}
2969
2971 return Stack.back().Other;
2972}
2973
2975 const char* ImportName = Stack.back().ImportName;
2976 if (ImportName)
2977 return StringRef(ImportName);
2978 return StringRef();
2979}
2980
2982 return Stack.back().Start - Trie.begin();
2983}
2984
2985ExportEntry::NodeState::NodeState(const uint8_t *Ptr)
2986 : Start(Ptr), Current(Ptr) {}
2987
2988void ExportEntry::pushNode(uint64_t offset) {
2989 ErrorAsOutParameter ErrAsOutParam(E);
2990 const uint8_t *Ptr = Trie.begin() + offset;
2991 NodeState State(Ptr);
2992 const char *error;
2993 uint64_t ExportInfoSize = readULEB128(State.Current, &error);
2994 if (error) {
2995 *E = malformedError("export info size " + Twine(error) +
2996 " in export trie data at node: 0x" +
2997 Twine::utohexstr(offset));
2998 moveToEnd();
2999 return;
3000 }
3001 State.IsExportNode = (ExportInfoSize != 0);
3002 const uint8_t* Children = State.Current + ExportInfoSize;
3003 if (Children > Trie.end()) {
3004 *E = malformedError(
3005 "export info size: 0x" + Twine::utohexstr(ExportInfoSize) +
3006 " in export trie data at node: 0x" + Twine::utohexstr(offset) +
3007 " too big and extends past end of trie data");
3008 moveToEnd();
3009 return;
3010 }
3011 if (State.IsExportNode) {
3012 const uint8_t *ExportStart = State.Current;
3013 State.Flags = readULEB128(State.Current, &error);
3014 if (error) {
3015 *E = malformedError("flags " + Twine(error) +
3016 " in export trie data at node: 0x" +
3017 Twine::utohexstr(offset));
3018 moveToEnd();
3019 return;
3020 }
3022 if (State.Flags != 0 &&
3026 *E = malformedError(
3027 "unsupported exported symbol kind: " + Twine((int)Kind) +
3028 " in flags: 0x" + Twine::utohexstr(State.Flags) +
3029 " in export trie data at node: 0x" + Twine::utohexstr(offset));
3030 moveToEnd();
3031 return;
3032 }
3033 if (State.Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT) {
3034 State.Address = 0;
3035 State.Other = readULEB128(State.Current, &error); // dylib ordinal
3036 if (error) {
3037 *E = malformedError("dylib ordinal of re-export " + Twine(error) +
3038 " in export trie data at node: 0x" +
3039 Twine::utohexstr(offset));
3040 moveToEnd();
3041 return;
3042 }
3043 if (O != nullptr) {
3044 // Only positive numbers represent library ordinals. Zero and negative
3045 // numbers have special meaning (see BindSpecialDylib).
3046 if ((int64_t)State.Other > 0 && State.Other > O->getLibraryCount()) {
3047 *E = malformedError(
3048 "bad library ordinal: " + Twine((int)State.Other) + " (max " +
3049 Twine((int)O->getLibraryCount()) +
3050 ") in export trie data at node: 0x" + Twine::utohexstr(offset));
3051 moveToEnd();
3052 return;
3053 }
3054 }
3055 State.ImportName = reinterpret_cast<const char*>(State.Current);
3056 if (*State.ImportName == '\0') {
3057 State.Current++;
3058 } else {
3059 const uint8_t *End = State.Current + 1;
3060 if (End >= Trie.end()) {
3061 *E = malformedError("import name of re-export in export trie data at "
3062 "node: 0x" +
3063 Twine::utohexstr(offset) +
3064 " starts past end of trie data");
3065 moveToEnd();
3066 return;
3067 }
3068 while(*End != '\0' && End < Trie.end())
3069 End++;
3070 if (*End != '\0') {
3071 *E = malformedError("import name of re-export in export trie data at "
3072 "node: 0x" +
3073 Twine::utohexstr(offset) +
3074 " extends past end of trie data");
3075 moveToEnd();
3076 return;
3077 }
3078 State.Current = End + 1;
3079 }
3080 } else {
3081 State.Address = readULEB128(State.Current, &error);
3082 if (error) {
3083 *E = malformedError("address " + Twine(error) +
3084 " in export trie data at node: 0x" +
3085 Twine::utohexstr(offset));
3086 moveToEnd();
3087 return;
3088 }
3090 State.Other = readULEB128(State.Current, &error);
3091 if (error) {
3092 *E = malformedError("resolver of stub and resolver " + Twine(error) +
3093 " in export trie data at node: 0x" +
3094 Twine::utohexstr(offset));
3095 moveToEnd();
3096 return;
3097 }
3098 }
3099 }
3100 if(ExportStart + ExportInfoSize != State.Current) {
3101 *E = malformedError(
3102 "inconsistent export info size: 0x" +
3103 Twine::utohexstr(ExportInfoSize) + " where actual size was: 0x" +
3104 Twine::utohexstr(State.Current - ExportStart) +
3105 " in export trie data at node: 0x" + Twine::utohexstr(offset));
3106 moveToEnd();
3107 return;
3108 }
3109 }
3110 State.ChildCount = *Children;
3111 if (State.ChildCount != 0 && Children + 1 >= Trie.end()) {
3112 *E = malformedError("byte for count of childern in export trie data at "
3113 "node: 0x" +
3114 Twine::utohexstr(offset) +
3115 " extends past end of trie data");
3116 moveToEnd();
3117 return;
3118 }
3119 State.Current = Children + 1;
3120 State.NextChildIndex = 0;
3121 State.ParentStringLength = CumulativeString.size();
3122 Stack.push_back(State);
3123}
3124
3125void ExportEntry::pushDownUntilBottom() {
3126 ErrorAsOutParameter ErrAsOutParam(E);
3127 const char *error;
3128 while (Stack.back().NextChildIndex < Stack.back().ChildCount) {
3129 NodeState &Top = Stack.back();
3130 CumulativeString.resize(Top.ParentStringLength);
3131 for (;*Top.Current != 0 && Top.Current < Trie.end(); Top.Current++) {
3132 char C = *Top.Current;
3133 CumulativeString.push_back(C);
3134 }
3135 if (Top.Current >= Trie.end()) {
3136 *E = malformedError("edge sub-string in export trie data at node: 0x" +
3137 Twine::utohexstr(Top.Start - Trie.begin()) +
3138 " for child #" + Twine((int)Top.NextChildIndex) +
3139 " extends past end of trie data");
3140 moveToEnd();
3141 return;
3142 }
3143 Top.Current += 1;
3144 uint64_t childNodeIndex = readULEB128(Top.Current, &error);
3145 if (error) {
3146 *E = malformedError("child node offset " + Twine(error) +
3147 " in export trie data at node: 0x" +
3148 Twine::utohexstr(Top.Start - Trie.begin()));
3149 moveToEnd();
3150 return;
3151 }
3152 for (const NodeState &node : nodes()) {
3153 if (node.Start == Trie.begin() + childNodeIndex){
3154 *E = malformedError("loop in childern in export trie data at node: 0x" +
3155 Twine::utohexstr(Top.Start - Trie.begin()) +
3156 " back to node: 0x" +
3157 Twine::utohexstr(childNodeIndex));
3158 moveToEnd();
3159 return;
3160 }
3161 }
3162 Top.NextChildIndex += 1;
3163 pushNode(childNodeIndex);
3164 if (*E)
3165 return;
3166 }
3167 if (!Stack.back().IsExportNode) {
3168 *E = malformedError("node is not an export node in export trie data at "
3169 "node: 0x" +
3170 Twine::utohexstr(Stack.back().Start - Trie.begin()));
3171 moveToEnd();
3172 return;
3173 }
3174}
3175
3176// We have a trie data structure and need a way to walk it that is compatible
3177// with the C++ iterator model. The solution is a non-recursive depth first
3178// traversal where the iterator contains a stack of parent nodes along with a
3179// string that is the accumulation of all edge strings along the parent chain
3180// to this point.
3181//
3182// There is one "export" node for each exported symbol. But because some
3183// symbols may be a prefix of another symbol (e.g. _dup and _dup2), an export
3184// node may have child nodes too.
3185//
3186// The algorithm for moveNext() is to keep moving down the leftmost unvisited
3187// child until hitting a node with no children (which is an export node or
3188// else the trie is malformed). On the way down, each node is pushed on the
3189// stack ivar. If there is no more ways down, it pops up one and tries to go
3190// down a sibling path until a childless node is reached.
3192 assert(!Stack.empty() && "ExportEntry::moveNext() with empty node stack");
3193 if (!Stack.back().IsExportNode) {
3194 *E = malformedError("node is not an export node in export trie data at "
3195 "node: 0x" +
3196 Twine::utohexstr(Stack.back().Start - Trie.begin()));
3197 moveToEnd();
3198 return;
3199 }
3200
3201 Stack.pop_back();
3202 while (!Stack.empty()) {
3203 NodeState &Top = Stack.back();
3204 if (Top.NextChildIndex < Top.ChildCount) {
3205 pushDownUntilBottom();
3206 // Now at the next export node.
3207 return;
3208 } else {
3209 if (Top.IsExportNode) {
3210 // This node has no children but is itself an export node.
3211 CumulativeString.resize(Top.ParentStringLength);
3212 return;
3213 }
3214 Stack.pop_back();
3215 }
3216 }
3217 Done = true;
3218}
3219
3222 const MachOObjectFile *O) {
3223 ExportEntry Start(&E, O, Trie);
3224 if (Trie.empty())
3225 Start.moveToEnd();
3226 else
3227 Start.moveToFirst();
3228
3229 ExportEntry Finish(&E, O, Trie);
3230 Finish.moveToEnd();
3231
3232 return make_range(export_iterator(Start), export_iterator(Finish));
3233}
3234
3236 ArrayRef<uint8_t> Trie;
3237 if (DyldInfoLoadCmd)
3238 Trie = getDyldInfoExportsTrie();
3239 else if (DyldExportsTrieLoadCmd)
3240 Trie = getDyldExportsTrie();
3241
3242 return exports(Err, Trie, this);
3243}
3244
3246 const MachOObjectFile *O)
3247 : E(E), O(O) {
3248 // Cache the vmaddress of __TEXT
3249 for (const auto &Command : O->load_commands()) {
3250 if (Command.C.cmd == MachO::LC_SEGMENT) {
3252 if (StringRef(SLC.segname) == StringRef("__TEXT")) {
3253 TextAddress = SLC.vmaddr;
3254 break;
3255 }
3256 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
3258 if (StringRef(SLC_64.segname) == StringRef("__TEXT")) {
3259 TextAddress = SLC_64.vmaddr;
3260 break;
3261 }
3262 }
3263 }
3264}
3265
3267
3269 return SegmentOffset;
3270}
3271
3273 return O->BindRebaseAddress(SegmentIndex, 0);
3274}
3275
3278}
3279
3282}
3283
3286}
3287
3289
3290int64_t MachOAbstractFixupEntry::addend() const { return Addend; }
3291
3293
3295
3297
3299 SegmentOffset = 0;
3300 SegmentIndex = -1;
3301 Ordinal = 0;
3302 Flags = 0;
3303 Addend = 0;
3304 Done = false;
3305}
3306
3308
3310
3312 const MachOObjectFile *O,
3313 bool Parse)
3316 if (!Parse)
3317 return;
3318
3319 if (auto FixupTargetsOrErr = O->getDyldChainedFixupTargets()) {
3320 FixupTargets = *FixupTargetsOrErr;
3321 } else {
3322 *E = FixupTargetsOrErr.takeError();
3323 return;
3324 }
3325
3326 if (auto SegmentsOrErr = O->getChainedFixupsSegments()) {
3327 Segments = std::move(SegmentsOrErr->second);
3328 } else {
3329 *E = SegmentsOrErr.takeError();
3330 return;
3331 }
3332}
3333
3334void MachOChainedFixupEntry::findNextPageWithFixups() {
3335 auto FindInSegment = [this]() {
3336 const ChainedFixupsSegment &SegInfo = Segments[InfoSegIndex];
3337 while (PageIndex < SegInfo.PageStarts.size() &&
3338 SegInfo.PageStarts[PageIndex] == MachO::DYLD_CHAINED_PTR_START_NONE)
3339 ++PageIndex;
3340 return PageIndex < SegInfo.PageStarts.size();
3341 };
3342
3343 while (InfoSegIndex < Segments.size()) {
3344 if (FindInSegment()) {
3345 PageOffset = Segments[InfoSegIndex].PageStarts[PageIndex];
3346 SegmentData = O->getSegmentContents(Segments[InfoSegIndex].SegIdx);
3347 return;
3348 }
3349
3350 InfoSegIndex++;
3351 PageIndex = 0;
3352 }
3353}
3354
3357 if (Segments.empty()) {
3358 Done = true;
3359 return;
3360 }
3361
3362 InfoSegIndex = 0;
3363 PageIndex = 0;
3364
3365 findNextPageWithFixups();
3366 moveNext();
3367}
3368
3371}
3372
3374 ErrorAsOutParameter ErrAsOutParam(E);
3375
3376 if (InfoSegIndex == Segments.size()) {
3377 Done = true;
3378 return;
3379 }
3380
3381 const ChainedFixupsSegment &SegInfo = Segments[InfoSegIndex];
3382 SegmentIndex = SegInfo.SegIdx;
3383 SegmentOffset = SegInfo.Header.page_size * PageIndex + PageOffset;
3384
3385 // FIXME: Handle other pointer formats.
3386 uint16_t PointerFormat = SegInfo.Header.pointer_format;
3387 if (PointerFormat != MachO::DYLD_CHAINED_PTR_64 &&
3388 PointerFormat != MachO::DYLD_CHAINED_PTR_64_OFFSET) {
3389 *E = createError("segment " + Twine(SegmentIndex) +
3390 " has unsupported chained fixup pointer_format " +
3391 Twine(PointerFormat));
3392 moveToEnd();
3393 return;
3394 }
3395
3396 Ordinal = 0;
3397 Flags = 0;
3398 Addend = 0;
3399 PointerValue = 0;
3400 SymbolName = {};
3401
3402 if (SegmentOffset + sizeof(RawValue) > SegmentData.size()) {
3403 *E = malformedError("fixup in segment " + Twine(SegmentIndex) +
3404 " at offset " + Twine(SegmentOffset) +
3405 " extends past segment's end");
3406 moveToEnd();
3407 return;
3408 }
3409
3410 static_assert(sizeof(RawValue) == sizeof(MachO::dyld_chained_import_addend));
3411 memcpy(&RawValue, SegmentData.data() + SegmentOffset, sizeof(RawValue));
3414
3415 // The bit extraction below assumes little-endian fixup entries.
3416 assert(O->isLittleEndian() && "big-endian object should have been rejected "
3417 "by getDyldChainedFixupTargets()");
3418 auto Field = [this](uint8_t Right, uint8_t Count) {
3419 return (RawValue >> Right) & ((1ULL << Count) - 1);
3420 };
3421
3422 // The `bind` field (most significant bit) of the encoded fixup determines
3423 // whether it is dyld_chained_ptr_64_bind or dyld_chained_ptr_64_rebase.
3424 bool IsBind = Field(63, 1);
3426 uint32_t Next = Field(51, 12);
3427 if (IsBind) {
3428 uint32_t ImportOrdinal = Field(0, 24);
3429 uint8_t InlineAddend = Field(24, 8);
3430
3431 if (ImportOrdinal >= FixupTargets.size()) {
3432 *E = malformedError("fixup in segment " + Twine(SegmentIndex) +
3433 " at offset " + Twine(SegmentOffset) +
3434 " has out-of range import ordinal " +
3435 Twine(ImportOrdinal));
3436 moveToEnd();
3437 return;
3438 }
3439
3440 ChainedFixupTarget &Target = FixupTargets[ImportOrdinal];
3441 Ordinal = Target.libOrdinal();
3442 Addend = InlineAddend ? InlineAddend : Target.addend();
3444 SymbolName = Target.symbolName();
3445 } else {
3446 uint64_t Target = Field(0, 36);
3447 uint64_t High8 = Field(36, 8);
3448
3449 PointerValue = Target | (High8 << 56);
3450 if (PointerFormat == MachO::DYLD_CHAINED_PTR_64_OFFSET)
3452 }
3453
3454 // The stride is 4 bytes for DYLD_CHAINED_PTR_64(_OFFSET).
3455 if (Next != 0) {
3456 PageOffset += 4 * Next;
3457 } else {
3458 ++PageIndex;
3459 findNextPageWithFixups();
3460 }
3461}
3462
3464 const MachOChainedFixupEntry &Other) const {
3465 if (Done && Other.Done)
3466 return true;
3467 if (Done != Other.Done)
3468 return false;
3469 return InfoSegIndex == Other.InfoSegIndex && PageIndex == Other.PageIndex &&
3470 PageOffset == Other.PageOffset;
3471}
3472
3474 ArrayRef<uint8_t> Bytes, bool is64Bit)
3475 : E(E), O(O), Opcodes(Bytes), Ptr(Bytes.begin()),
3476 PointerSize(is64Bit ? 8 : 4) {}
3477
3478void MachORebaseEntry::moveToFirst() {
3479 Ptr = Opcodes.begin();
3480 moveNext();
3481}
3482
3483void MachORebaseEntry::moveToEnd() {
3484 Ptr = Opcodes.end();
3485 RemainingLoopCount = 0;
3486 Done = true;
3487}
3488
3490 ErrorAsOutParameter ErrAsOutParam(E);
3491 // If in the middle of some loop, move to next rebasing in loop.
3492 SegmentOffset += AdvanceAmount;
3493 if (RemainingLoopCount) {
3494 --RemainingLoopCount;
3495 return;
3496 }
3497 // REBASE_OPCODE_DONE is only used for padding if we are not aligned to
3498 // pointer size. Therefore it is possible to reach the end without ever having
3499 // seen REBASE_OPCODE_DONE.
3500 if (Ptr == Opcodes.end()) {
3501 Done = true;
3502 return;
3503 }
3504 bool More = true;
3505 while (More) {
3506 // Parse next opcode and set up next loop.
3507 const uint8_t *OpcodeStart = Ptr;
3508 uint8_t Byte = *Ptr++;
3509 uint8_t ImmValue = Byte & MachO::REBASE_IMMEDIATE_MASK;
3510 uint8_t Opcode = Byte & MachO::REBASE_OPCODE_MASK;
3511 uint32_t Count, Skip;
3512 const char *error = nullptr;
3513 switch (Opcode) {
3515 More = false;
3516 Done = true;
3517 moveToEnd();
3518 DEBUG_WITH_TYPE("mach-o-rebase", dbgs() << "REBASE_OPCODE_DONE\n");
3519 break;
3521 RebaseType = ImmValue;
3522 if (RebaseType > MachO::REBASE_TYPE_TEXT_PCREL32) {
3523 *E = malformedError("for REBASE_OPCODE_SET_TYPE_IMM bad bind type: " +
3524 Twine((int)RebaseType) + " for opcode at: 0x" +
3525 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3526 moveToEnd();
3527 return;
3528 }
3530 "mach-o-rebase",
3531 dbgs() << "REBASE_OPCODE_SET_TYPE_IMM: "
3532 << "RebaseType=" << (int) RebaseType << "\n");
3533 break;
3535 SegmentIndex = ImmValue;
3536 SegmentOffset = readULEB128(&error);
3537 if (error) {
3538 *E = malformedError("for REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB " +
3539 Twine(error) + " for opcode at: 0x" +
3540 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3541 moveToEnd();
3542 return;
3543 }
3544 error = O->RebaseEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3545 PointerSize);
3546 if (error) {
3547 *E = malformedError("for REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB " +
3548 Twine(error) + " for opcode at: 0x" +
3549 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3550 moveToEnd();
3551 return;
3552 }
3554 "mach-o-rebase",
3555 dbgs() << "REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB: "
3556 << "SegmentIndex=" << SegmentIndex << ", "
3557 << format("SegmentOffset=0x%06X", SegmentOffset)
3558 << "\n");
3559 break;
3561 SegmentOffset += readULEB128(&error);
3562 if (error) {
3563 *E = malformedError("for REBASE_OPCODE_ADD_ADDR_ULEB " + Twine(error) +
3564 " for opcode at: 0x" +
3565 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3566 moveToEnd();
3567 return;
3568 }
3569 error = O->RebaseEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3570 PointerSize);
3571 if (error) {
3572 *E = malformedError("for REBASE_OPCODE_ADD_ADDR_ULEB " + Twine(error) +
3573 " for opcode at: 0x" +
3574 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3575 moveToEnd();
3576 return;
3577 }
3578 DEBUG_WITH_TYPE("mach-o-rebase",
3579 dbgs() << "REBASE_OPCODE_ADD_ADDR_ULEB: "
3580 << format("SegmentOffset=0x%06X",
3581 SegmentOffset) << "\n");
3582 break;
3584 SegmentOffset += ImmValue * PointerSize;
3585 error = O->RebaseEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3586 PointerSize);
3587 if (error) {
3588 *E = malformedError("for REBASE_OPCODE_ADD_ADDR_IMM_SCALED " +
3589 Twine(error) + " for opcode at: 0x" +
3590 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3591 moveToEnd();
3592 return;
3593 }
3594 DEBUG_WITH_TYPE("mach-o-rebase",
3595 dbgs() << "REBASE_OPCODE_ADD_ADDR_IMM_SCALED: "
3596 << format("SegmentOffset=0x%06X",
3597 SegmentOffset) << "\n");
3598 break;
3600 AdvanceAmount = PointerSize;
3601 Skip = 0;
3602 Count = ImmValue;
3603 if (ImmValue != 0)
3604 RemainingLoopCount = ImmValue - 1;
3605 else
3606 RemainingLoopCount = 0;
3607 error = O->RebaseEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3608 PointerSize, Count, Skip);
3609 if (error) {
3610 *E = malformedError("for REBASE_OPCODE_DO_REBASE_IMM_TIMES " +
3611 Twine(error) + " for opcode at: 0x" +
3612 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3613 moveToEnd();
3614 return;
3615 }
3617 "mach-o-rebase",
3618 dbgs() << "REBASE_OPCODE_DO_REBASE_IMM_TIMES: "
3619 << format("SegmentOffset=0x%06X", SegmentOffset)
3620 << ", AdvanceAmount=" << AdvanceAmount
3621 << ", RemainingLoopCount=" << RemainingLoopCount
3622 << "\n");
3623 return;
3625 AdvanceAmount = PointerSize;
3626 Skip = 0;
3627 Count = readULEB128(&error);
3628 if (error) {
3629 *E = malformedError("for REBASE_OPCODE_DO_REBASE_ULEB_TIMES " +
3630 Twine(error) + " for opcode at: 0x" +
3631 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3632 moveToEnd();
3633 return;
3634 }
3635 if (Count != 0)
3636 RemainingLoopCount = Count - 1;
3637 else
3638 RemainingLoopCount = 0;
3639 error = O->RebaseEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3640 PointerSize, Count, Skip);
3641 if (error) {
3642 *E = malformedError("for REBASE_OPCODE_DO_REBASE_ULEB_TIMES " +
3643 Twine(error) + " for opcode at: 0x" +
3644 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3645 moveToEnd();
3646 return;
3647 }
3649 "mach-o-rebase",
3650 dbgs() << "REBASE_OPCODE_DO_REBASE_ULEB_TIMES: "
3651 << format("SegmentOffset=0x%06X", SegmentOffset)
3652 << ", AdvanceAmount=" << AdvanceAmount
3653 << ", RemainingLoopCount=" << RemainingLoopCount
3654 << "\n");
3655 return;
3657 Skip = readULEB128(&error);
3658 if (error) {
3659 *E = malformedError("for REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB " +
3660 Twine(error) + " for opcode at: 0x" +
3661 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3662 moveToEnd();
3663 return;
3664 }
3665 AdvanceAmount = Skip + PointerSize;
3666 Count = 1;
3667 RemainingLoopCount = 0;
3668 error = O->RebaseEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3669 PointerSize, Count, Skip);
3670 if (error) {
3671 *E = malformedError("for REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB " +
3672 Twine(error) + " for opcode at: 0x" +
3673 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3674 moveToEnd();
3675 return;
3676 }
3678 "mach-o-rebase",
3679 dbgs() << "REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB: "
3680 << format("SegmentOffset=0x%06X", SegmentOffset)
3681 << ", AdvanceAmount=" << AdvanceAmount
3682 << ", RemainingLoopCount=" << RemainingLoopCount
3683 << "\n");
3684 return;
3686 Count = readULEB128(&error);
3687 if (error) {
3688 *E = malformedError("for REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_"
3689 "ULEB " +
3690 Twine(error) + " for opcode at: 0x" +
3691 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3692 moveToEnd();
3693 return;
3694 }
3695 if (Count != 0)
3696 RemainingLoopCount = Count - 1;
3697 else
3698 RemainingLoopCount = 0;
3699 Skip = readULEB128(&error);
3700 if (error) {
3701 *E = malformedError("for REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_"
3702 "ULEB " +
3703 Twine(error) + " for opcode at: 0x" +
3704 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3705 moveToEnd();
3706 return;
3707 }
3708 AdvanceAmount = Skip + PointerSize;
3709
3710 error = O->RebaseEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3711 PointerSize, Count, Skip);
3712 if (error) {
3713 *E = malformedError("for REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_"
3714 "ULEB " +
3715 Twine(error) + " for opcode at: 0x" +
3716 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3717 moveToEnd();
3718 return;
3719 }
3721 "mach-o-rebase",
3722 dbgs() << "REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB: "
3723 << format("SegmentOffset=0x%06X", SegmentOffset)
3724 << ", AdvanceAmount=" << AdvanceAmount
3725 << ", RemainingLoopCount=" << RemainingLoopCount
3726 << "\n");
3727 return;
3728 default:
3729 *E = malformedError("bad rebase info (bad opcode value 0x" +
3730 Twine::utohexstr(Opcode) + " for opcode at: 0x" +
3731 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3732 moveToEnd();
3733 return;
3734 }
3735 }
3736}
3737
3738uint64_t MachORebaseEntry::readULEB128(const char **error) {
3739 unsigned Count;
3740 uint64_t Result = decodeULEB128(Ptr, &Count, Opcodes.end(), error);
3741 Ptr += Count;
3742 if (Ptr > Opcodes.end())
3743 Ptr = Opcodes.end();
3744 return Result;
3745}
3746
3747int32_t MachORebaseEntry::segmentIndex() const { return SegmentIndex; }
3748
3749uint64_t MachORebaseEntry::segmentOffset() const { return SegmentOffset; }
3750
3752 switch (RebaseType) {
3754 return "pointer";
3756 return "text abs32";
3758 return "text rel32";
3759 }
3760 return "unknown";
3761}
3762
3763// For use with the SegIndex of a checked Mach-O Rebase entry
3764// to get the segment name.
3766 return O->BindRebaseSegmentName(SegmentIndex);
3767}
3768
3769// For use with a SegIndex,SegOffset pair from a checked Mach-O Rebase entry
3770// to get the section name.
3772 return O->BindRebaseSectionName(SegmentIndex, SegmentOffset);
3773}
3774
3775// For use with a SegIndex,SegOffset pair from a checked Mach-O Rebase entry
3776// to get the address.
3778 return O->BindRebaseAddress(SegmentIndex, SegmentOffset);
3779}
3780
3782#ifdef EXPENSIVE_CHECKS
3783 assert(Opcodes == Other.Opcodes && "compare iterators of different files");
3784#else
3785 assert(Opcodes.data() == Other.Opcodes.data() && "compare iterators of different files");
3786#endif
3787 return (Ptr == Other.Ptr) &&
3788 (RemainingLoopCount == Other.RemainingLoopCount) &&
3789 (Done == Other.Done);
3790}
3791
3794 ArrayRef<uint8_t> Opcodes, bool is64) {
3795 if (O->BindRebaseSectionTable == nullptr)
3796 O->BindRebaseSectionTable = std::make_unique<BindRebaseSegInfo>(O);
3797 MachORebaseEntry Start(&Err, O, Opcodes, is64);
3798 Start.moveToFirst();
3799
3800 MachORebaseEntry Finish(&Err, O, Opcodes, is64);
3801 Finish.moveToEnd();
3802
3803 return make_range(rebase_iterator(Start), rebase_iterator(Finish));
3804}
3805
3807 return rebaseTable(Err, this, getDyldInfoRebaseOpcodes(), is64Bit());
3808}
3809
3811 ArrayRef<uint8_t> Bytes, bool is64Bit, Kind BK)
3812 : E(E), O(O), Opcodes(Bytes), Ptr(Bytes.begin()),
3813 PointerSize(is64Bit ? 8 : 4), TableKind(BK) {}
3814
3815void MachOBindEntry::moveToFirst() {
3816 Ptr = Opcodes.begin();
3817 moveNext();
3818}
3819
3820void MachOBindEntry::moveToEnd() {
3821 Ptr = Opcodes.end();
3822 RemainingLoopCount = 0;
3823 Done = true;
3824}
3825
3827 ErrorAsOutParameter ErrAsOutParam(E);
3828 // If in the middle of some loop, move to next binding in loop.
3829 SegmentOffset += AdvanceAmount;
3830 if (RemainingLoopCount) {
3831 --RemainingLoopCount;
3832 return;
3833 }
3834 // BIND_OPCODE_DONE is only used for padding if we are not aligned to
3835 // pointer size. Therefore it is possible to reach the end without ever having
3836 // seen BIND_OPCODE_DONE.
3837 if (Ptr == Opcodes.end()) {
3838 Done = true;
3839 return;
3840 }
3841 bool More = true;
3842 while (More) {
3843 // Parse next opcode and set up next loop.
3844 const uint8_t *OpcodeStart = Ptr;
3845 uint8_t Byte = *Ptr++;
3846 uint8_t ImmValue = Byte & MachO::BIND_IMMEDIATE_MASK;
3847 uint8_t Opcode = Byte & MachO::BIND_OPCODE_MASK;
3848 int8_t SignExtended;
3849 const uint8_t *SymStart;
3850 uint32_t Count, Skip;
3851 const char *error = nullptr;
3852 switch (Opcode) {
3854 if (TableKind == Kind::Lazy) {
3855 // Lazying bindings have a DONE opcode between entries. Need to ignore
3856 // it to advance to next entry. But need not if this is last entry.
3857 bool NotLastEntry = false;
3858 for (const uint8_t *P = Ptr; P < Opcodes.end(); ++P) {
3859 if (*P) {
3860 NotLastEntry = true;
3861 }
3862 }
3863 if (NotLastEntry)
3864 break;
3865 }
3866 More = false;
3867 moveToEnd();
3868 DEBUG_WITH_TYPE("mach-o-bind", dbgs() << "BIND_OPCODE_DONE\n");
3869 break;
3871 if (TableKind == Kind::Weak) {
3872 *E = malformedError("BIND_OPCODE_SET_DYLIB_ORDINAL_IMM not allowed in "
3873 "weak bind table for opcode at: 0x" +
3874 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3875 moveToEnd();
3876 return;
3877 }
3878 Ordinal = ImmValue;
3879 LibraryOrdinalSet = true;
3880 if (ImmValue > O->getLibraryCount()) {
3881 *E = malformedError("for BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB bad "
3882 "library ordinal: " +
3883 Twine((int)ImmValue) + " (max " +
3884 Twine((int)O->getLibraryCount()) +
3885 ") for opcode at: 0x" +
3886 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3887 moveToEnd();
3888 return;
3889 }
3891 "mach-o-bind",
3892 dbgs() << "BIND_OPCODE_SET_DYLIB_ORDINAL_IMM: "
3893 << "Ordinal=" << Ordinal << "\n");
3894 break;
3896 if (TableKind == Kind::Weak) {
3897 *E = malformedError("BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB not allowed in "
3898 "weak bind table for opcode at: 0x" +
3899 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3900 moveToEnd();
3901 return;
3902 }
3903 Ordinal = readULEB128(&error);
3904 LibraryOrdinalSet = true;
3905 if (error) {
3906 *E = malformedError("for BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB " +
3907 Twine(error) + " for opcode at: 0x" +
3908 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3909 moveToEnd();
3910 return;
3911 }
3912 if (Ordinal > (int)O->getLibraryCount()) {
3913 *E = malformedError("for BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB bad "
3914 "library ordinal: " +
3915 Twine((int)Ordinal) + " (max " +
3916 Twine((int)O->getLibraryCount()) +
3917 ") for opcode at: 0x" +
3918 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3919 moveToEnd();
3920 return;
3921 }
3923 "mach-o-bind",
3924 dbgs() << "BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB: "
3925 << "Ordinal=" << Ordinal << "\n");
3926 break;
3928 if (TableKind == Kind::Weak) {
3929 *E = malformedError("BIND_OPCODE_SET_DYLIB_SPECIAL_IMM not allowed in "
3930 "weak bind table for opcode at: 0x" +
3931 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3932 moveToEnd();
3933 return;
3934 }
3935 if (ImmValue) {
3936 SignExtended = MachO::BIND_OPCODE_MASK | ImmValue;
3937 Ordinal = SignExtended;
3939 *E = malformedError("for BIND_OPCODE_SET_DYLIB_SPECIAL_IMM unknown "
3940 "special ordinal: " +
3941 Twine((int)Ordinal) + " for opcode at: 0x" +
3942 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3943 moveToEnd();
3944 return;
3945 }
3946 } else
3947 Ordinal = 0;
3948 LibraryOrdinalSet = true;
3950 "mach-o-bind",
3951 dbgs() << "BIND_OPCODE_SET_DYLIB_SPECIAL_IMM: "
3952 << "Ordinal=" << Ordinal << "\n");
3953 break;
3955 Flags = ImmValue;
3956 SymStart = Ptr;
3957 while (*Ptr && (Ptr < Opcodes.end())) {
3958 ++Ptr;
3959 }
3960 if (Ptr == Opcodes.end()) {
3961 *E = malformedError(
3962 "for BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM "
3963 "symbol name extends past opcodes for opcode at: 0x" +
3964 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3965 moveToEnd();
3966 return;
3967 }
3968 SymbolName = StringRef(reinterpret_cast<const char*>(SymStart),
3969 Ptr-SymStart);
3970 ++Ptr;
3972 "mach-o-bind",
3973 dbgs() << "BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM: "
3974 << "SymbolName=" << SymbolName << "\n");
3975 if (TableKind == Kind::Weak) {
3977 return;
3978 }
3979 break;
3981 BindType = ImmValue;
3982 if (ImmValue > MachO::BIND_TYPE_TEXT_PCREL32) {
3983 *E = malformedError("for BIND_OPCODE_SET_TYPE_IMM bad bind type: " +
3984 Twine((int)ImmValue) + " for opcode at: 0x" +
3985 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3986 moveToEnd();
3987 return;
3988 }
3990 "mach-o-bind",
3991 dbgs() << "BIND_OPCODE_SET_TYPE_IMM: "
3992 << "BindType=" << (int)BindType << "\n");
3993 break;
3995 Addend = readSLEB128(&error);
3996 if (error) {
3997 *E = malformedError("for BIND_OPCODE_SET_ADDEND_SLEB " + Twine(error) +
3998 " for opcode at: 0x" +
3999 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4000 moveToEnd();
4001 return;
4002 }
4004 "mach-o-bind",
4005 dbgs() << "BIND_OPCODE_SET_ADDEND_SLEB: "
4006 << "Addend=" << Addend << "\n");
4007 break;
4009 SegmentIndex = ImmValue;
4010 SegmentOffset = readULEB128(&error);
4011 if (error) {
4012 *E = malformedError("for BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB " +
4013 Twine(error) + " for opcode at: 0x" +
4014 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4015 moveToEnd();
4016 return;
4017 }
4018 error = O->BindEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
4019 PointerSize);
4020 if (error) {
4021 *E = malformedError("for BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB " +
4022 Twine(error) + " for opcode at: 0x" +
4023 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4024 moveToEnd();
4025 return;
4026 }
4028 "mach-o-bind",
4029 dbgs() << "BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB: "
4030 << "SegmentIndex=" << SegmentIndex << ", "
4031 << format("SegmentOffset=0x%06X", SegmentOffset)
4032 << "\n");
4033 break;
4035 SegmentOffset += readULEB128(&error);
4036 if (error) {
4037 *E = malformedError("for BIND_OPCODE_ADD_ADDR_ULEB " + Twine(error) +
4038 " for opcode at: 0x" +
4039 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4040 moveToEnd();
4041 return;
4042 }
4043 error = O->BindEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
4044 PointerSize);
4045 if (error) {
4046 *E = malformedError("for BIND_OPCODE_ADD_ADDR_ULEB " + Twine(error) +
4047 " for opcode at: 0x" +
4048 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4049 moveToEnd();
4050 return;
4051 }
4052 DEBUG_WITH_TYPE("mach-o-bind",
4053 dbgs() << "BIND_OPCODE_ADD_ADDR_ULEB: "
4054 << format("SegmentOffset=0x%06X",
4055 SegmentOffset) << "\n");
4056 break;
4058 AdvanceAmount = PointerSize;
4059 RemainingLoopCount = 0;
4060 error = O->BindEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
4061 PointerSize);
4062 if (error) {
4063 *E = malformedError("for BIND_OPCODE_DO_BIND " + Twine(error) +
4064 " for opcode at: 0x" +
4065 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4066 moveToEnd();
4067 return;
4068 }
4069 if (SymbolName == StringRef()) {
4070 *E = malformedError(
4071 "for BIND_OPCODE_DO_BIND missing preceding "
4072 "BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM for opcode at: 0x" +
4073 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4074 moveToEnd();
4075 return;
4076 }
4077 if (!LibraryOrdinalSet && TableKind != Kind::Weak) {
4078 *E =
4079 malformedError("for BIND_OPCODE_DO_BIND missing preceding "
4080 "BIND_OPCODE_SET_DYLIB_ORDINAL_* for opcode at: 0x" +
4081 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4082 moveToEnd();
4083 return;
4084 }
4085 DEBUG_WITH_TYPE("mach-o-bind",
4086 dbgs() << "BIND_OPCODE_DO_BIND: "
4087 << format("SegmentOffset=0x%06X",
4088 SegmentOffset) << "\n");
4089 return;
4091 if (TableKind == Kind::Lazy) {
4092 *E = malformedError("BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB not allowed in "
4093 "lazy bind table for opcode at: 0x" +
4094 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4095 moveToEnd();
4096 return;
4097 }
4098 error = O->BindEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
4099 PointerSize);
4100 if (error) {
4101 *E = malformedError("for BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB " +
4102 Twine(error) + " for opcode at: 0x" +
4103 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4104 moveToEnd();
4105 return;
4106 }
4107 if (SymbolName == StringRef()) {
4108 *E = malformedError(
4109 "for BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB missing "
4110 "preceding BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM for opcode "
4111 "at: 0x" +
4112 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4113 moveToEnd();
4114 return;
4115 }
4116 if (!LibraryOrdinalSet && TableKind != Kind::Weak) {
4117 *E = malformedError(
4118 "for BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB missing "
4119 "preceding BIND_OPCODE_SET_DYLIB_ORDINAL_* for opcode at: 0x" +
4120 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4121 moveToEnd();
4122 return;
4123 }
4124 AdvanceAmount = readULEB128(&error) + PointerSize;
4125 if (error) {
4126 *E = malformedError("for BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB " +
4127 Twine(error) + " for opcode at: 0x" +
4128 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4129 moveToEnd();
4130 return;
4131 }
4132 // Note, this is not really an error until the next bind but make no sense
4133 // for a BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB to not be followed by another
4134 // bind operation.
4135 error = O->BindEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset +
4136 AdvanceAmount, PointerSize);
4137 if (error) {
4138 *E = malformedError("for BIND_OPCODE_ADD_ADDR_ULEB (after adding "
4139 "ULEB) " +
4140 Twine(error) + " for opcode at: 0x" +
4141 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4142 moveToEnd();
4143 return;
4144 }
4145 RemainingLoopCount = 0;
4147 "mach-o-bind",
4148 dbgs() << "BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB: "
4149 << format("SegmentOffset=0x%06X", SegmentOffset)
4150 << ", AdvanceAmount=" << AdvanceAmount
4151 << ", RemainingLoopCount=" << RemainingLoopCount
4152 << "\n");
4153 return;
4155 if (TableKind == Kind::Lazy) {
4156 *E = malformedError("BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED not "
4157 "allowed in lazy bind table for opcode at: 0x" +
4158 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4159 moveToEnd();
4160 return;
4161 }
4162 if (SymbolName == StringRef()) {
4163 *E = malformedError(
4164 "for BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED "
4165 "missing preceding BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM for "
4166 "opcode at: 0x" +
4167 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4168 moveToEnd();
4169 return;
4170 }
4171 if (!LibraryOrdinalSet && TableKind != Kind::Weak) {
4172 *E = malformedError(
4173 "for BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED "
4174 "missing preceding BIND_OPCODE_SET_DYLIB_ORDINAL_* for opcode "
4175 "at: 0x" +
4176 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4177 moveToEnd();
4178 return;
4179 }
4180 AdvanceAmount = ImmValue * PointerSize + PointerSize;
4181 RemainingLoopCount = 0;
4182 error = O->BindEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset +
4183 AdvanceAmount, PointerSize);
4184 if (error) {
4185 *E = malformedError("for BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED " +
4186 Twine(error) + " for opcode at: 0x" +
4187 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4188 moveToEnd();
4189 return;
4190 }
4191 DEBUG_WITH_TYPE("mach-o-bind",
4192 dbgs()
4193 << "BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED: "
4194 << format("SegmentOffset=0x%06X", SegmentOffset) << "\n");
4195 return;
4197 if (TableKind == Kind::Lazy) {
4198 *E = malformedError("BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB not "
4199 "allowed in lazy bind table for opcode at: 0x" +
4200 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4201 moveToEnd();
4202 return;
4203 }
4204 Count = readULEB128(&error);
4205 if (Count != 0)
4206 RemainingLoopCount = Count - 1;
4207 else
4208 RemainingLoopCount = 0;
4209 if (error) {
4210 *E = malformedError("for BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB "
4211 " (count value) " +
4212 Twine(error) + " for opcode at: 0x" +
4213 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4214 moveToEnd();
4215 return;
4216 }
4217 Skip = readULEB128(&error);
4218 AdvanceAmount = Skip + PointerSize;
4219 if (error) {
4220 *E = malformedError("for BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB "
4221 " (skip value) " +
4222 Twine(error) + " for opcode at: 0x" +
4223 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4224 moveToEnd();
4225 return;
4226 }
4227 if (SymbolName == StringRef()) {
4228 *E = malformedError(
4229 "for BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB "
4230 "missing preceding BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM for "
4231 "opcode at: 0x" +
4232 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4233 moveToEnd();
4234 return;
4235 }
4236 if (!LibraryOrdinalSet && TableKind != Kind::Weak) {
4237 *E = malformedError(
4238 "for BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB "
4239 "missing preceding BIND_OPCODE_SET_DYLIB_ORDINAL_* for opcode "
4240 "at: 0x" +
4241 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4242 moveToEnd();
4243 return;
4244 }
4245 error = O->BindEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
4246 PointerSize, Count, Skip);
4247 if (error) {
4248 *E =
4249 malformedError("for BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB " +
4250 Twine(error) + " for opcode at: 0x" +
4251 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4252 moveToEnd();
4253 return;
4254 }
4256 "mach-o-bind",
4257 dbgs() << "BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB: "
4258 << format("SegmentOffset=0x%06X", SegmentOffset)
4259 << ", AdvanceAmount=" << AdvanceAmount
4260 << ", RemainingLoopCount=" << RemainingLoopCount
4261 << "\n");
4262 return;
4263 default:
4264 *E = malformedError("bad bind info (bad opcode value 0x" +
4265 Twine::utohexstr(Opcode) + " for opcode at: 0x" +
4266 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4267 moveToEnd();
4268 return;
4269 }
4270 }
4271}
4272
4273uint64_t MachOBindEntry::readULEB128(const char **error) {
4274 unsigned Count;
4275 uint64_t Result = decodeULEB128(Ptr, &Count, Opcodes.end(), error);
4276 Ptr += Count;
4277 if (Ptr > Opcodes.end())
4278 Ptr = Opcodes.end();
4279 return Result;
4280}
4281
4282int64_t MachOBindEntry::readSLEB128(const char **error) {
4283 unsigned Count;
4284 int64_t Result = decodeSLEB128(Ptr, &Count, Opcodes.end(), error);
4285 Ptr += Count;
4286 if (Ptr > Opcodes.end())
4287 Ptr = Opcodes.end();
4288 return Result;
4289}
4290
4291int32_t MachOBindEntry::segmentIndex() const { return SegmentIndex; }
4292
4293uint64_t MachOBindEntry::segmentOffset() const { return SegmentOffset; }
4294
4296 switch (BindType) {
4298 return "pointer";
4300 return "text abs32";
4302 return "text rel32";
4303 }
4304 return "unknown";
4305}
4306
4307StringRef MachOBindEntry::symbolName() const { return SymbolName; }
4308
4309int64_t MachOBindEntry::addend() const { return Addend; }
4310
4311uint32_t MachOBindEntry::flags() const { return Flags; }
4312
4313int MachOBindEntry::ordinal() const { return Ordinal; }
4314
4315// For use with the SegIndex of a checked Mach-O Bind entry
4316// to get the segment name.
4318 return O->BindRebaseSegmentName(SegmentIndex);
4319}
4320
4321// For use with a SegIndex,SegOffset pair from a checked Mach-O Bind entry
4322// to get the section name.
4324 return O->BindRebaseSectionName(SegmentIndex, SegmentOffset);
4325}
4326
4327// For use with a SegIndex,SegOffset pair from a checked Mach-O Bind entry
4328// to get the address.
4330 return O->BindRebaseAddress(SegmentIndex, SegmentOffset);
4331}
4332
4334#ifdef EXPENSIVE_CHECKS
4335 assert(Opcodes == Other.Opcodes && "compare iterators of different files");
4336#else
4337 assert(Opcodes.data() == Other.Opcodes.data() && "compare iterators of different files");
4338#endif
4339 return (Ptr == Other.Ptr) &&
4340 (RemainingLoopCount == Other.RemainingLoopCount) &&
4341 (Done == Other.Done);
4342}
4343
4344// Build table of sections so SegIndex/SegOffset pairs can be translated.
4346 uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
4347 StringRef CurSegName;
4348 uint64_t CurSegAddress;
4349 for (const SectionRef &Section : Obj->sections()) {
4350 SectionInfo Info;
4351 Expected<StringRef> NameOrErr = Section.getName();
4352 if (!NameOrErr)
4353 consumeError(NameOrErr.takeError());
4354 else
4355 Info.SectionName = *NameOrErr;
4356 Info.Address = Section.getAddress();
4357 Info.Size = Section.getSize();
4358 Info.SegmentName =
4359 Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
4360 if (!Info.SegmentName.equals(CurSegName)) {
4361 ++CurSegIndex;
4362 CurSegName = Info.SegmentName;
4363 CurSegAddress = Info.Address;
4364 }
4365 Info.SegmentIndex = CurSegIndex - 1;
4366 Info.OffsetInSegment = Info.Address - CurSegAddress;
4367 Info.SegmentStartAddress = CurSegAddress;
4368 Sections.push_back(Info);
4369 }
4370 MaxSegIndex = CurSegIndex;
4371}
4372
4373// For use with a SegIndex, SegOffset, and PointerSize triple in
4374// MachOBindEntry::moveNext() to validate a MachOBindEntry or MachORebaseEntry.
4375//
4376// Given a SegIndex, SegOffset, and PointerSize, verify a valid section exists
4377// that fully contains a pointer at that location. Multiple fixups in a bind
4378// (such as with the BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB opcode) can
4379// be tested via the Count and Skip parameters.
4380const char * BindRebaseSegInfo::checkSegAndOffsets(int32_t SegIndex,
4381 uint64_t SegOffset,
4382 uint8_t PointerSize,
4383 uint32_t Count,
4384 uint32_t Skip) {
4385 if (SegIndex == -1)
4386 return "missing preceding *_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB";
4387 if (SegIndex >= MaxSegIndex)
4388 return "bad segIndex (too large)";
4389 for (uint32_t i = 0; i < Count; ++i) {
4390 uint32_t Start = SegOffset + i * (PointerSize + Skip);
4391 uint32_t End = Start + PointerSize;
4392 bool Found = false;
4393 for (const SectionInfo &SI : Sections) {
4394 if (SI.SegmentIndex != SegIndex)
4395 continue;
4396 if ((SI.OffsetInSegment<=Start) && (Start<(SI.OffsetInSegment+SI.Size))) {
4397 if (End <= SI.OffsetInSegment + SI.Size) {
4398 Found = true;
4399 break;
4400 }
4401 else
4402 return "bad offset, extends beyond section boundary";
4403 }
4404 }
4405 if (!Found)
4406 return "bad offset, not in section";
4407 }
4408 return nullptr;
4409}
4410
4411// For use with the SegIndex of a checked Mach-O Bind or Rebase entry
4412// to get the segment name.
4414 for (const SectionInfo &SI : Sections) {
4415 if (SI.SegmentIndex == SegIndex)
4416 return SI.SegmentName;
4417 }
4418 llvm_unreachable("invalid SegIndex");
4419}
4420
4421// For use with a SegIndex,SegOffset pair from a checked Mach-O Bind or Rebase
4422// to get the SectionInfo.
4423const BindRebaseSegInfo::SectionInfo &BindRebaseSegInfo::findSection(
4424 int32_t SegIndex, uint64_t SegOffset) {
4425 for (const SectionInfo &SI : Sections) {
4426 if (SI.SegmentIndex != Seg