1 //===- MachOObjectFile.cpp - Mach-O object file binding -------------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file defines the MachOObjectFile class, which binds the MachOObject
10 // class to the generic ObjectFile wrapper.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/ADT/ArrayRef.h"
15 #include "llvm/ADT/None.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/ADT/StringSwitch.h"
20 #include "llvm/ADT/Triple.h"
21 #include "llvm/ADT/Twine.h"
22 #include "llvm/BinaryFormat/MachO.h"
23 #include "llvm/Object/Error.h"
24 #include "llvm/Object/MachO.h"
25 #include "llvm/Object/ObjectFile.h"
26 #include "llvm/Object/SymbolicFile.h"
27 #include "llvm/Support/DataExtractor.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/Error.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/Format.h"
32 #include "llvm/Support/Host.h"
33 #include "llvm/Support/LEB128.h"
34 #include "llvm/Support/MemoryBuffer.h"
35 #include "llvm/Support/SwapByteOrder.h"
36 #include "llvm/Support/raw_ostream.h"
46 #include <system_error>
49 using namespace object;
58 } // end anonymous namespace
60 static const std::array<StringRef, 17> validArchs = {
61 "i386", "x86_64", "x86_64h", "armv4t", "arm", "armv5e",
62 "armv6", "armv6m", "armv7", "armv7em", "armv7k", "armv7m",
63 "armv7s", "arm64", "arm64_32", "ppc", "ppc64",
66 static Error malformedError(const Twine &Msg) {
67 return make_error<GenericBinaryError>("truncated or malformed object (" +
69 object_error::parse_failed);
72 // FIXME: Replace all uses of this function with getStructOrErr.
74 static T getStruct(const MachOObjectFile &O, const char *P) {
75 // Don't read before the beginning or past the end of the file
76 if (P < O.getData().begin() || P + sizeof(T) > O.getData().end())
77 report_fatal_error("Malformed MachO file.");
80 memcpy(&Cmd, P, sizeof(T));
81 if (O.isLittleEndian() != sys::IsLittleEndianHost)
82 MachO::swapStruct(Cmd);
87 static Expected<T> getStructOrErr(const MachOObjectFile &O, const char *P) {
88 // Don't read before the beginning or past the end of the file
89 if (P < O.getData().begin() || P + sizeof(T) > O.getData().end())
90 return malformedError("Structure read out-of-range");
93 memcpy(&Cmd, P, sizeof(T));
94 if (O.isLittleEndian() != sys::IsLittleEndianHost)
95 MachO::swapStruct(Cmd);
100 getSectionPtr(const MachOObjectFile &O, MachOObjectFile::LoadCommandInfo L,
102 uintptr_t CommandAddr = reinterpret_cast<uintptr_t>(L.Ptr);
104 bool Is64 = O.is64Bit();
105 unsigned SegmentLoadSize = Is64 ? sizeof(MachO::segment_command_64) :
106 sizeof(MachO::segment_command);
107 unsigned SectionSize = Is64 ? sizeof(MachO::section_64) :
108 sizeof(MachO::section);
110 uintptr_t SectionAddr = CommandAddr + SegmentLoadSize + Sec * SectionSize;
111 return reinterpret_cast<const char*>(SectionAddr);
114 static const char *getPtr(const MachOObjectFile &O, size_t Offset) {
115 assert(Offset <= O.getData().size());
116 return O.getData().data() + Offset;
119 static MachO::nlist_base
120 getSymbolTableEntryBase(const MachOObjectFile &O, DataRefImpl DRI) {
121 const char *P = reinterpret_cast<const char *>(DRI.p);
122 return getStruct<MachO::nlist_base>(O, P);
125 static StringRef parseSegmentOrSectionName(const char *P) {
129 // Not null terminated, so this is a 16 char string.
130 return StringRef(P, 16);
133 static unsigned getCPUType(const MachOObjectFile &O) {
134 return O.getHeader().cputype;
138 getPlainRelocationAddress(const MachO::any_relocation_info &RE) {
143 getScatteredRelocationAddress(const MachO::any_relocation_info &RE) {
144 return RE.r_word0 & 0xffffff;
147 static bool getPlainRelocationPCRel(const MachOObjectFile &O,
148 const MachO::any_relocation_info &RE) {
149 if (O.isLittleEndian())
150 return (RE.r_word1 >> 24) & 1;
151 return (RE.r_word1 >> 7) & 1;
155 getScatteredRelocationPCRel(const MachO::any_relocation_info &RE) {
156 return (RE.r_word0 >> 30) & 1;
159 static unsigned getPlainRelocationLength(const MachOObjectFile &O,
160 const MachO::any_relocation_info &RE) {
161 if (O.isLittleEndian())
162 return (RE.r_word1 >> 25) & 3;
163 return (RE.r_word1 >> 5) & 3;
167 getScatteredRelocationLength(const MachO::any_relocation_info &RE) {
168 return (RE.r_word0 >> 28) & 3;
171 static unsigned getPlainRelocationType(const MachOObjectFile &O,
172 const MachO::any_relocation_info &RE) {
173 if (O.isLittleEndian())
174 return RE.r_word1 >> 28;
175 return RE.r_word1 & 0xf;
178 static uint32_t getSectionFlags(const MachOObjectFile &O,
181 MachO::section_64 Sect = O.getSection64(Sec);
184 MachO::section Sect = O.getSection(Sec);
188 static Expected<MachOObjectFile::LoadCommandInfo>
189 getLoadCommandInfo(const MachOObjectFile &Obj, const char *Ptr,
190 uint32_t LoadCommandIndex) {
191 if (auto CmdOrErr = getStructOrErr<MachO::load_command>(Obj, Ptr)) {
192 if (CmdOrErr->cmdsize + Ptr > Obj.getData().end())
193 return malformedError("load command " + Twine(LoadCommandIndex) +
194 " extends past end of file");
195 if (CmdOrErr->cmdsize < 8)
196 return malformedError("load command " + Twine(LoadCommandIndex) +
197 " with size less than 8 bytes");
198 return MachOObjectFile::LoadCommandInfo({Ptr, *CmdOrErr});
200 return CmdOrErr.takeError();
203 static Expected<MachOObjectFile::LoadCommandInfo>
204 getFirstLoadCommandInfo(const MachOObjectFile &Obj) {
205 unsigned HeaderSize = Obj.is64Bit() ? sizeof(MachO::mach_header_64)
206 : sizeof(MachO::mach_header);
207 if (sizeof(MachO::load_command) > Obj.getHeader().sizeofcmds)
208 return malformedError("load command 0 extends past the end all load "
209 "commands in the file");
210 return getLoadCommandInfo(Obj, getPtr(Obj, HeaderSize), 0);
213 static Expected<MachOObjectFile::LoadCommandInfo>
214 getNextLoadCommandInfo(const MachOObjectFile &Obj, uint32_t LoadCommandIndex,
215 const MachOObjectFile::LoadCommandInfo &L) {
216 unsigned HeaderSize = Obj.is64Bit() ? sizeof(MachO::mach_header_64)
217 : sizeof(MachO::mach_header);
218 if (L.Ptr + L.C.cmdsize + sizeof(MachO::load_command) >
219 Obj.getData().data() + HeaderSize + Obj.getHeader().sizeofcmds)
220 return malformedError("load command " + Twine(LoadCommandIndex + 1) +
221 " extends past the end all load commands in the file");
222 return getLoadCommandInfo(Obj, L.Ptr + L.C.cmdsize, LoadCommandIndex + 1);
225 template <typename T>
226 static void parseHeader(const MachOObjectFile &Obj, T &Header,
228 if (sizeof(T) > Obj.getData().size()) {
229 Err = malformedError("the mach header extends past the end of the "
233 if (auto HeaderOrErr = getStructOrErr<T>(Obj, getPtr(Obj, 0)))
234 Header = *HeaderOrErr;
236 Err = HeaderOrErr.takeError();
239 // This is used to check for overlapping of Mach-O elements.
240 struct MachOElement {
246 static Error checkOverlappingElement(std::list<MachOElement> &Elements,
247 uint64_t Offset, uint64_t Size,
250 return Error::success();
252 for (auto it=Elements.begin() ; it != Elements.end(); ++it) {
254 if ((Offset >= E.Offset && Offset < E.Offset + E.Size) ||
255 (Offset + Size > E.Offset && Offset + Size < E.Offset + E.Size) ||
256 (Offset <= E.Offset && Offset + Size >= E.Offset + E.Size))
257 return malformedError(Twine(Name) + " at offset " + Twine(Offset) +
258 " with a size of " + Twine(Size) + ", overlaps " +
259 E.Name + " at offset " + Twine(E.Offset) + " with "
260 "a size of " + Twine(E.Size));
263 if (nt != Elements.end()) {
265 if (Offset + Size <= N.Offset) {
266 Elements.insert(nt, {Offset, Size, Name});
267 return Error::success();
271 Elements.push_back({Offset, Size, Name});
272 return Error::success();
275 // Parses LC_SEGMENT or LC_SEGMENT_64 load command, adds addresses of all
276 // sections to \param Sections, and optionally sets
277 // \param IsPageZeroSegment to true.
278 template <typename Segment, typename Section>
279 static Error parseSegmentLoadCommand(
280 const MachOObjectFile &Obj, const MachOObjectFile::LoadCommandInfo &Load,
281 SmallVectorImpl<const char *> &Sections, bool &IsPageZeroSegment,
282 uint32_t LoadCommandIndex, const char *CmdName, uint64_t SizeOfHeaders,
283 std::list<MachOElement> &Elements) {
284 const unsigned SegmentLoadSize = sizeof(Segment);
285 if (Load.C.cmdsize < SegmentLoadSize)
286 return malformedError("load command " + Twine(LoadCommandIndex) +
287 " " + CmdName + " cmdsize too small");
288 if (auto SegOrErr = getStructOrErr<Segment>(Obj, Load.Ptr)) {
289 Segment S = SegOrErr.get();
290 const unsigned SectionSize = sizeof(Section);
291 uint64_t FileSize = Obj.getData().size();
292 if (S.nsects > std::numeric_limits<uint32_t>::max() / SectionSize ||
293 S.nsects * SectionSize > Load.C.cmdsize - SegmentLoadSize)
294 return malformedError("load command " + Twine(LoadCommandIndex) +
295 " inconsistent cmdsize in " + CmdName +
296 " for the number of sections");
297 for (unsigned J = 0; J < S.nsects; ++J) {
298 const char *Sec = getSectionPtr(Obj, Load, J);
299 Sections.push_back(Sec);
300 auto SectionOrErr = getStructOrErr<Section>(Obj, Sec);
302 return SectionOrErr.takeError();
303 Section s = SectionOrErr.get();
304 if (Obj.getHeader().filetype != MachO::MH_DYLIB_STUB &&
305 Obj.getHeader().filetype != MachO::MH_DSYM &&
306 s.flags != MachO::S_ZEROFILL &&
307 s.flags != MachO::S_THREAD_LOCAL_ZEROFILL &&
309 return malformedError("offset field of section " + Twine(J) + " in " +
310 CmdName + " command " + Twine(LoadCommandIndex) +
311 " extends past the end of the file");
312 if (Obj.getHeader().filetype != MachO::MH_DYLIB_STUB &&
313 Obj.getHeader().filetype != MachO::MH_DSYM &&
314 s.flags != MachO::S_ZEROFILL &&
315 s.flags != MachO::S_THREAD_LOCAL_ZEROFILL && S.fileoff == 0 &&
316 s.offset < SizeOfHeaders && s.size != 0)
317 return malformedError("offset field of section " + Twine(J) + " in " +
318 CmdName + " command " + Twine(LoadCommandIndex) +
319 " not past the headers of the file");
320 uint64_t BigSize = s.offset;
322 if (Obj.getHeader().filetype != MachO::MH_DYLIB_STUB &&
323 Obj.getHeader().filetype != MachO::MH_DSYM &&
324 s.flags != MachO::S_ZEROFILL &&
325 s.flags != MachO::S_THREAD_LOCAL_ZEROFILL &&
327 return malformedError("offset field plus size field of section " +
328 Twine(J) + " in " + CmdName + " command " +
329 Twine(LoadCommandIndex) +
330 " extends past the end of the file");
331 if (Obj.getHeader().filetype != MachO::MH_DYLIB_STUB &&
332 Obj.getHeader().filetype != MachO::MH_DSYM &&
333 s.flags != MachO::S_ZEROFILL &&
334 s.flags != MachO::S_THREAD_LOCAL_ZEROFILL &&
336 return malformedError("size field of section " +
337 Twine(J) + " in " + CmdName + " command " +
338 Twine(LoadCommandIndex) +
339 " greater than the segment");
340 if (Obj.getHeader().filetype != MachO::MH_DYLIB_STUB &&
341 Obj.getHeader().filetype != MachO::MH_DSYM && s.size != 0 &&
343 return malformedError("addr field of section " + Twine(J) + " in " +
344 CmdName + " command " + Twine(LoadCommandIndex) +
345 " less than the segment's vmaddr");
348 uint64_t BigEnd = S.vmaddr;
350 if (S.vmsize != 0 && s.size != 0 && BigSize > BigEnd)
351 return malformedError("addr field plus size of section " + Twine(J) +
352 " in " + CmdName + " command " +
353 Twine(LoadCommandIndex) +
354 " greater than than "
355 "the segment's vmaddr plus vmsize");
356 if (Obj.getHeader().filetype != MachO::MH_DYLIB_STUB &&
357 Obj.getHeader().filetype != MachO::MH_DSYM &&
358 s.flags != MachO::S_ZEROFILL &&
359 s.flags != MachO::S_THREAD_LOCAL_ZEROFILL)
360 if (Error Err = checkOverlappingElement(Elements, s.offset, s.size,
363 if (s.reloff > FileSize)
364 return malformedError("reloff field of section " + Twine(J) + " in " +
365 CmdName + " command " + Twine(LoadCommandIndex) +
366 " extends past the end of the file");
368 BigSize *= sizeof(struct MachO::relocation_info);
370 if (BigSize > FileSize)
371 return malformedError("reloff field plus nreloc field times sizeof("
372 "struct relocation_info) of section " +
373 Twine(J) + " in " + CmdName + " command " +
374 Twine(LoadCommandIndex) +
375 " extends past the end of the file");
376 if (Error Err = checkOverlappingElement(Elements, s.reloff, s.nreloc *
378 MachO::relocation_info),
379 "section relocation entries"))
382 if (S.fileoff > FileSize)
383 return malformedError("load command " + Twine(LoadCommandIndex) +
384 " fileoff field in " + CmdName +
385 " extends past the end of the file");
386 uint64_t BigSize = S.fileoff;
387 BigSize += S.filesize;
388 if (BigSize > FileSize)
389 return malformedError("load command " + Twine(LoadCommandIndex) +
390 " fileoff field plus filesize field in " +
391 CmdName + " extends past the end of the file");
392 if (S.vmsize != 0 && S.filesize > S.vmsize)
393 return malformedError("load command " + Twine(LoadCommandIndex) +
394 " filesize field in " + CmdName +
395 " greater than vmsize field");
396 IsPageZeroSegment |= StringRef("__PAGEZERO").equals(S.segname);
398 return SegOrErr.takeError();
400 return Error::success();
403 static Error checkSymtabCommand(const MachOObjectFile &Obj,
404 const MachOObjectFile::LoadCommandInfo &Load,
405 uint32_t LoadCommandIndex,
406 const char **SymtabLoadCmd,
407 std::list<MachOElement> &Elements) {
408 if (Load.C.cmdsize < sizeof(MachO::symtab_command))
409 return malformedError("load command " + Twine(LoadCommandIndex) +
410 " LC_SYMTAB cmdsize too small");
411 if (*SymtabLoadCmd != nullptr)
412 return malformedError("more than one LC_SYMTAB command");
413 auto SymtabOrErr = getStructOrErr<MachO::symtab_command>(Obj, Load.Ptr);
415 return SymtabOrErr.takeError();
416 MachO::symtab_command Symtab = SymtabOrErr.get();
417 if (Symtab.cmdsize != sizeof(MachO::symtab_command))
418 return malformedError("LC_SYMTAB command " + Twine(LoadCommandIndex) +
419 " has incorrect cmdsize");
420 uint64_t FileSize = Obj.getData().size();
421 if (Symtab.symoff > FileSize)
422 return malformedError("symoff field of LC_SYMTAB command " +
423 Twine(LoadCommandIndex) + " extends past the end "
425 uint64_t SymtabSize = Symtab.nsyms;
426 const char *struct_nlist_name;
428 SymtabSize *= sizeof(MachO::nlist_64);
429 struct_nlist_name = "struct nlist_64";
431 SymtabSize *= sizeof(MachO::nlist);
432 struct_nlist_name = "struct nlist";
434 uint64_t BigSize = SymtabSize;
435 BigSize += Symtab.symoff;
436 if (BigSize > FileSize)
437 return malformedError("symoff field plus nsyms field times sizeof(" +
438 Twine(struct_nlist_name) + ") of LC_SYMTAB command " +
439 Twine(LoadCommandIndex) + " extends past the end "
441 if (Error Err = checkOverlappingElement(Elements, Symtab.symoff, SymtabSize,
444 if (Symtab.stroff > FileSize)
445 return malformedError("stroff field of LC_SYMTAB command " +
446 Twine(LoadCommandIndex) + " extends past the end "
448 BigSize = Symtab.stroff;
449 BigSize += Symtab.strsize;
450 if (BigSize > FileSize)
451 return malformedError("stroff field plus strsize field of LC_SYMTAB "
452 "command " + Twine(LoadCommandIndex) + " extends "
453 "past the end of the file");
454 if (Error Err = checkOverlappingElement(Elements, Symtab.stroff,
455 Symtab.strsize, "string table"))
457 *SymtabLoadCmd = Load.Ptr;
458 return Error::success();
461 static Error checkDysymtabCommand(const MachOObjectFile &Obj,
462 const MachOObjectFile::LoadCommandInfo &Load,
463 uint32_t LoadCommandIndex,
464 const char **DysymtabLoadCmd,
465 std::list<MachOElement> &Elements) {
466 if (Load.C.cmdsize < sizeof(MachO::dysymtab_command))
467 return malformedError("load command " + Twine(LoadCommandIndex) +
468 " LC_DYSYMTAB cmdsize too small");
469 if (*DysymtabLoadCmd != nullptr)
470 return malformedError("more than one LC_DYSYMTAB command");
472 getStructOrErr<MachO::dysymtab_command>(Obj, Load.Ptr);
474 return DysymtabOrErr.takeError();
475 MachO::dysymtab_command Dysymtab = DysymtabOrErr.get();
476 if (Dysymtab.cmdsize != sizeof(MachO::dysymtab_command))
477 return malformedError("LC_DYSYMTAB command " + Twine(LoadCommandIndex) +
478 " has incorrect cmdsize");
479 uint64_t FileSize = Obj.getData().size();
480 if (Dysymtab.tocoff > FileSize)
481 return malformedError("tocoff field of LC_DYSYMTAB command " +
482 Twine(LoadCommandIndex) + " extends past the end of "
484 uint64_t BigSize = Dysymtab.ntoc;
485 BigSize *= sizeof(MachO::dylib_table_of_contents);
486 BigSize += Dysymtab.tocoff;
487 if (BigSize > FileSize)
488 return malformedError("tocoff field plus ntoc field times sizeof(struct "
489 "dylib_table_of_contents) of LC_DYSYMTAB command " +
490 Twine(LoadCommandIndex) + " extends past the end of "
492 if (Error Err = checkOverlappingElement(Elements, Dysymtab.tocoff,
493 Dysymtab.ntoc * sizeof(struct
494 MachO::dylib_table_of_contents),
495 "table of contents"))
497 if (Dysymtab.modtaboff > FileSize)
498 return malformedError("modtaboff field of LC_DYSYMTAB command " +
499 Twine(LoadCommandIndex) + " extends past the end of "
501 BigSize = Dysymtab.nmodtab;
502 const char *struct_dylib_module_name;
503 uint64_t sizeof_modtab;
505 sizeof_modtab = sizeof(MachO::dylib_module_64);
506 struct_dylib_module_name = "struct dylib_module_64";
508 sizeof_modtab = sizeof(MachO::dylib_module);
509 struct_dylib_module_name = "struct dylib_module";
511 BigSize *= sizeof_modtab;
512 BigSize += Dysymtab.modtaboff;
513 if (BigSize > FileSize)
514 return malformedError("modtaboff field plus nmodtab field times sizeof(" +
515 Twine(struct_dylib_module_name) + ") of LC_DYSYMTAB "
516 "command " + Twine(LoadCommandIndex) + " extends "
517 "past the end of the file");
518 if (Error Err = checkOverlappingElement(Elements, Dysymtab.modtaboff,
519 Dysymtab.nmodtab * sizeof_modtab,
522 if (Dysymtab.extrefsymoff > FileSize)
523 return malformedError("extrefsymoff field of LC_DYSYMTAB command " +
524 Twine(LoadCommandIndex) + " extends past the end of "
526 BigSize = Dysymtab.nextrefsyms;
527 BigSize *= sizeof(MachO::dylib_reference);
528 BigSize += Dysymtab.extrefsymoff;
529 if (BigSize > FileSize)
530 return malformedError("extrefsymoff field plus nextrefsyms field times "
531 "sizeof(struct dylib_reference) of LC_DYSYMTAB "
532 "command " + Twine(LoadCommandIndex) + " extends "
533 "past the end of the file");
534 if (Error Err = checkOverlappingElement(Elements, Dysymtab.extrefsymoff,
535 Dysymtab.nextrefsyms *
536 sizeof(MachO::dylib_reference),
539 if (Dysymtab.indirectsymoff > FileSize)
540 return malformedError("indirectsymoff field of LC_DYSYMTAB command " +
541 Twine(LoadCommandIndex) + " extends past the end of "
543 BigSize = Dysymtab.nindirectsyms;
544 BigSize *= sizeof(uint32_t);
545 BigSize += Dysymtab.indirectsymoff;
546 if (BigSize > FileSize)
547 return malformedError("indirectsymoff field plus nindirectsyms field times "
548 "sizeof(uint32_t) of LC_DYSYMTAB command " +
549 Twine(LoadCommandIndex) + " extends past the end of "
551 if (Error Err = checkOverlappingElement(Elements, Dysymtab.indirectsymoff,
552 Dysymtab.nindirectsyms *
556 if (Dysymtab.extreloff > FileSize)
557 return malformedError("extreloff field of LC_DYSYMTAB command " +
558 Twine(LoadCommandIndex) + " extends past the end of "
560 BigSize = Dysymtab.nextrel;
561 BigSize *= sizeof(MachO::relocation_info);
562 BigSize += Dysymtab.extreloff;
563 if (BigSize > FileSize)
564 return malformedError("extreloff field plus nextrel field times sizeof"
565 "(struct relocation_info) of LC_DYSYMTAB command " +
566 Twine(LoadCommandIndex) + " extends past the end of "
568 if (Error Err = checkOverlappingElement(Elements, Dysymtab.extreloff,
570 sizeof(MachO::relocation_info),
571 "external relocation table"))
573 if (Dysymtab.locreloff > FileSize)
574 return malformedError("locreloff field of LC_DYSYMTAB command " +
575 Twine(LoadCommandIndex) + " extends past the end of "
577 BigSize = Dysymtab.nlocrel;
578 BigSize *= sizeof(MachO::relocation_info);
579 BigSize += Dysymtab.locreloff;
580 if (BigSize > FileSize)
581 return malformedError("locreloff field plus nlocrel field times sizeof"
582 "(struct relocation_info) of LC_DYSYMTAB command " +
583 Twine(LoadCommandIndex) + " extends past the end of "
585 if (Error Err = checkOverlappingElement(Elements, Dysymtab.locreloff,
587 sizeof(MachO::relocation_info),
588 "local relocation table"))
590 *DysymtabLoadCmd = Load.Ptr;
591 return Error::success();
594 static Error checkLinkeditDataCommand(const MachOObjectFile &Obj,
595 const MachOObjectFile::LoadCommandInfo &Load,
596 uint32_t LoadCommandIndex,
597 const char **LoadCmd, const char *CmdName,
598 std::list<MachOElement> &Elements,
599 const char *ElementName) {
600 if (Load.C.cmdsize < sizeof(MachO::linkedit_data_command))
601 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
602 CmdName + " cmdsize too small");
603 if (*LoadCmd != nullptr)
604 return malformedError("more than one " + Twine(CmdName) + " command");
605 auto LinkDataOrError =
606 getStructOrErr<MachO::linkedit_data_command>(Obj, Load.Ptr);
607 if (!LinkDataOrError)
608 return LinkDataOrError.takeError();
609 MachO::linkedit_data_command LinkData = LinkDataOrError.get();
610 if (LinkData.cmdsize != sizeof(MachO::linkedit_data_command))
611 return malformedError(Twine(CmdName) + " command " +
612 Twine(LoadCommandIndex) + " has incorrect cmdsize");
613 uint64_t FileSize = Obj.getData().size();
614 if (LinkData.dataoff > FileSize)
615 return malformedError("dataoff field of " + Twine(CmdName) + " command " +
616 Twine(LoadCommandIndex) + " extends past the end of "
618 uint64_t BigSize = LinkData.dataoff;
619 BigSize += LinkData.datasize;
620 if (BigSize > FileSize)
621 return malformedError("dataoff field plus datasize field of " +
622 Twine(CmdName) + " command " +
623 Twine(LoadCommandIndex) + " extends past the end of "
625 if (Error Err = checkOverlappingElement(Elements, LinkData.dataoff,
626 LinkData.datasize, ElementName))
629 return Error::success();
632 static Error checkDyldInfoCommand(const MachOObjectFile &Obj,
633 const MachOObjectFile::LoadCommandInfo &Load,
634 uint32_t LoadCommandIndex,
635 const char **LoadCmd, const char *CmdName,
636 std::list<MachOElement> &Elements) {
637 if (Load.C.cmdsize < sizeof(MachO::dyld_info_command))
638 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
639 CmdName + " cmdsize too small");
640 if (*LoadCmd != nullptr)
641 return malformedError("more than one LC_DYLD_INFO and or LC_DYLD_INFO_ONLY "
644 getStructOrErr<MachO::dyld_info_command>(Obj, Load.Ptr);
646 return DyldInfoOrErr.takeError();
647 MachO::dyld_info_command DyldInfo = DyldInfoOrErr.get();
648 if (DyldInfo.cmdsize != sizeof(MachO::dyld_info_command))
649 return malformedError(Twine(CmdName) + " command " +
650 Twine(LoadCommandIndex) + " has incorrect cmdsize");
651 uint64_t FileSize = Obj.getData().size();
652 if (DyldInfo.rebase_off > FileSize)
653 return malformedError("rebase_off field of " + Twine(CmdName) +
654 " command " + Twine(LoadCommandIndex) + " extends "
655 "past the end of the file");
656 uint64_t BigSize = DyldInfo.rebase_off;
657 BigSize += DyldInfo.rebase_size;
658 if (BigSize > FileSize)
659 return malformedError("rebase_off field plus rebase_size field of " +
660 Twine(CmdName) + " command " +
661 Twine(LoadCommandIndex) + " extends past the end of "
663 if (Error Err = checkOverlappingElement(Elements, DyldInfo.rebase_off,
664 DyldInfo.rebase_size,
667 if (DyldInfo.bind_off > FileSize)
668 return malformedError("bind_off field of " + Twine(CmdName) +
669 " command " + Twine(LoadCommandIndex) + " extends "
670 "past the end of the file");
671 BigSize = DyldInfo.bind_off;
672 BigSize += DyldInfo.bind_size;
673 if (BigSize > FileSize)
674 return malformedError("bind_off field plus bind_size field of " +
675 Twine(CmdName) + " command " +
676 Twine(LoadCommandIndex) + " extends past the end of "
678 if (Error Err = checkOverlappingElement(Elements, DyldInfo.bind_off,
682 if (DyldInfo.weak_bind_off > FileSize)
683 return malformedError("weak_bind_off field of " + Twine(CmdName) +
684 " command " + Twine(LoadCommandIndex) + " extends "
685 "past the end of the file");
686 BigSize = DyldInfo.weak_bind_off;
687 BigSize += DyldInfo.weak_bind_size;
688 if (BigSize > FileSize)
689 return malformedError("weak_bind_off field plus weak_bind_size field of " +
690 Twine(CmdName) + " command " +
691 Twine(LoadCommandIndex) + " extends past the end of "
693 if (Error Err = checkOverlappingElement(Elements, DyldInfo.weak_bind_off,
694 DyldInfo.weak_bind_size,
695 "dyld weak bind info"))
697 if (DyldInfo.lazy_bind_off > FileSize)
698 return malformedError("lazy_bind_off field of " + Twine(CmdName) +
699 " command " + Twine(LoadCommandIndex) + " extends "
700 "past the end of the file");
701 BigSize = DyldInfo.lazy_bind_off;
702 BigSize += DyldInfo.lazy_bind_size;
703 if (BigSize > FileSize)
704 return malformedError("lazy_bind_off field plus lazy_bind_size field of " +
705 Twine(CmdName) + " command " +
706 Twine(LoadCommandIndex) + " extends past the end of "
708 if (Error Err = checkOverlappingElement(Elements, DyldInfo.lazy_bind_off,
709 DyldInfo.lazy_bind_size,
710 "dyld lazy bind info"))
712 if (DyldInfo.export_off > FileSize)
713 return malformedError("export_off field of " + Twine(CmdName) +
714 " command " + Twine(LoadCommandIndex) + " extends "
715 "past the end of the file");
716 BigSize = DyldInfo.export_off;
717 BigSize += DyldInfo.export_size;
718 if (BigSize > FileSize)
719 return malformedError("export_off field plus export_size field of " +
720 Twine(CmdName) + " command " +
721 Twine(LoadCommandIndex) + " extends past the end of "
723 if (Error Err = checkOverlappingElement(Elements, DyldInfo.export_off,
724 DyldInfo.export_size,
728 return Error::success();
731 static Error checkDylibCommand(const MachOObjectFile &Obj,
732 const MachOObjectFile::LoadCommandInfo &Load,
733 uint32_t LoadCommandIndex, const char *CmdName) {
734 if (Load.C.cmdsize < sizeof(MachO::dylib_command))
735 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
736 CmdName + " cmdsize too small");
737 auto CommandOrErr = getStructOrErr<MachO::dylib_command>(Obj, Load.Ptr);
739 return CommandOrErr.takeError();
740 MachO::dylib_command D = CommandOrErr.get();
741 if (D.dylib.name < sizeof(MachO::dylib_command))
742 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
743 CmdName + " name.offset field too small, not past "
744 "the end of the dylib_command struct");
745 if (D.dylib.name >= D.cmdsize)
746 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
747 CmdName + " name.offset field extends past the end "
748 "of the load command");
749 // Make sure there is a null between the starting offset of the name and
750 // the end of the load command.
752 const char *P = (const char *)Load.Ptr;
753 for (i = D.dylib.name; i < D.cmdsize; i++)
757 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
758 CmdName + " library name extends past the end of the "
760 return Error::success();
763 static Error checkDylibIdCommand(const MachOObjectFile &Obj,
764 const MachOObjectFile::LoadCommandInfo &Load,
765 uint32_t LoadCommandIndex,
766 const char **LoadCmd) {
767 if (Error Err = checkDylibCommand(Obj, Load, LoadCommandIndex,
770 if (*LoadCmd != nullptr)
771 return malformedError("more than one LC_ID_DYLIB command");
772 if (Obj.getHeader().filetype != MachO::MH_DYLIB &&
773 Obj.getHeader().filetype != MachO::MH_DYLIB_STUB)
774 return malformedError("LC_ID_DYLIB load command in non-dynamic library "
777 return Error::success();
780 static Error checkDyldCommand(const MachOObjectFile &Obj,
781 const MachOObjectFile::LoadCommandInfo &Load,
782 uint32_t LoadCommandIndex, const char *CmdName) {
783 if (Load.C.cmdsize < sizeof(MachO::dylinker_command))
784 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
785 CmdName + " cmdsize too small");
786 auto CommandOrErr = getStructOrErr<MachO::dylinker_command>(Obj, Load.Ptr);
788 return CommandOrErr.takeError();
789 MachO::dylinker_command D = CommandOrErr.get();
790 if (D.name < sizeof(MachO::dylinker_command))
791 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
792 CmdName + " name.offset field too small, not past "
793 "the end of the dylinker_command struct");
794 if (D.name >= D.cmdsize)
795 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
796 CmdName + " name.offset field extends past the end "
797 "of the load command");
798 // Make sure there is a null between the starting offset of the name and
799 // the end of the load command.
801 const char *P = (const char *)Load.Ptr;
802 for (i = D.name; i < D.cmdsize; i++)
806 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
807 CmdName + " dyld name extends past the end of the "
809 return Error::success();
812 static Error checkVersCommand(const MachOObjectFile &Obj,
813 const MachOObjectFile::LoadCommandInfo &Load,
814 uint32_t LoadCommandIndex,
815 const char **LoadCmd, const char *CmdName) {
816 if (Load.C.cmdsize != sizeof(MachO::version_min_command))
817 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
818 CmdName + " has incorrect cmdsize");
819 if (*LoadCmd != nullptr)
820 return malformedError("more than one LC_VERSION_MIN_MACOSX, "
821 "LC_VERSION_MIN_IPHONEOS, LC_VERSION_MIN_TVOS or "
822 "LC_VERSION_MIN_WATCHOS command");
824 return Error::success();
827 static Error checkNoteCommand(const MachOObjectFile &Obj,
828 const MachOObjectFile::LoadCommandInfo &Load,
829 uint32_t LoadCommandIndex,
830 std::list<MachOElement> &Elements) {
831 if (Load.C.cmdsize != sizeof(MachO::note_command))
832 return malformedError("load command " + Twine(LoadCommandIndex) +
833 " LC_NOTE has incorrect cmdsize");
834 auto NoteCmdOrErr = getStructOrErr<MachO::note_command>(Obj, Load.Ptr);
836 return NoteCmdOrErr.takeError();
837 MachO::note_command Nt = NoteCmdOrErr.get();
838 uint64_t FileSize = Obj.getData().size();
839 if (Nt.offset > FileSize)
840 return malformedError("offset field of LC_NOTE command " +
841 Twine(LoadCommandIndex) + " extends "
842 "past the end of the file");
843 uint64_t BigSize = Nt.offset;
845 if (BigSize > FileSize)
846 return malformedError("size field plus offset field of LC_NOTE command " +
847 Twine(LoadCommandIndex) + " extends past the end of "
849 if (Error Err = checkOverlappingElement(Elements, Nt.offset, Nt.size,
852 return Error::success();
856 parseBuildVersionCommand(const MachOObjectFile &Obj,
857 const MachOObjectFile::LoadCommandInfo &Load,
858 SmallVectorImpl<const char*> &BuildTools,
859 uint32_t LoadCommandIndex) {
861 getStructOrErr<MachO::build_version_command>(Obj, Load.Ptr);
863 return BVCOrErr.takeError();
864 MachO::build_version_command BVC = BVCOrErr.get();
865 if (Load.C.cmdsize !=
866 sizeof(MachO::build_version_command) +
867 BVC.ntools * sizeof(MachO::build_tool_version))
868 return malformedError("load command " + Twine(LoadCommandIndex) +
869 " LC_BUILD_VERSION_COMMAND has incorrect cmdsize");
871 auto Start = Load.Ptr + sizeof(MachO::build_version_command);
872 BuildTools.resize(BVC.ntools);
873 for (unsigned i = 0; i < BVC.ntools; ++i)
874 BuildTools[i] = Start + i * sizeof(MachO::build_tool_version);
876 return Error::success();
879 static Error checkRpathCommand(const MachOObjectFile &Obj,
880 const MachOObjectFile::LoadCommandInfo &Load,
881 uint32_t LoadCommandIndex) {
882 if (Load.C.cmdsize < sizeof(MachO::rpath_command))
883 return malformedError("load command " + Twine(LoadCommandIndex) +
884 " LC_RPATH cmdsize too small");
885 auto ROrErr = getStructOrErr<MachO::rpath_command>(Obj, Load.Ptr);
887 return ROrErr.takeError();
888 MachO::rpath_command R = ROrErr.get();
889 if (R.path < sizeof(MachO::rpath_command))
890 return malformedError("load command " + Twine(LoadCommandIndex) +
891 " LC_RPATH path.offset field too small, not past "
892 "the end of the rpath_command struct");
893 if (R.path >= R.cmdsize)
894 return malformedError("load command " + Twine(LoadCommandIndex) +
895 " LC_RPATH path.offset field extends past the end "
896 "of the load command");
897 // Make sure there is a null between the starting offset of the path and
898 // the end of the load command.
900 const char *P = (const char *)Load.Ptr;
901 for (i = R.path; i < R.cmdsize; i++)
905 return malformedError("load command " + Twine(LoadCommandIndex) +
906 " LC_RPATH library name extends past the end of the "
908 return Error::success();
911 static Error checkEncryptCommand(const MachOObjectFile &Obj,
912 const MachOObjectFile::LoadCommandInfo &Load,
913 uint32_t LoadCommandIndex,
914 uint64_t cryptoff, uint64_t cryptsize,
915 const char **LoadCmd, const char *CmdName) {
916 if (*LoadCmd != nullptr)
917 return malformedError("more than one LC_ENCRYPTION_INFO and or "
918 "LC_ENCRYPTION_INFO_64 command");
919 uint64_t FileSize = Obj.getData().size();
920 if (cryptoff > FileSize)
921 return malformedError("cryptoff field of " + Twine(CmdName) +
922 " command " + Twine(LoadCommandIndex) + " extends "
923 "past the end of the file");
924 uint64_t BigSize = cryptoff;
925 BigSize += cryptsize;
926 if (BigSize > FileSize)
927 return malformedError("cryptoff field plus cryptsize field of " +
928 Twine(CmdName) + " command " +
929 Twine(LoadCommandIndex) + " extends past the end of "
932 return Error::success();
935 static Error checkLinkerOptCommand(const MachOObjectFile &Obj,
936 const MachOObjectFile::LoadCommandInfo &Load,
937 uint32_t LoadCommandIndex) {
938 if (Load.C.cmdsize < sizeof(MachO::linker_option_command))
939 return malformedError("load command " + Twine(LoadCommandIndex) +
940 " LC_LINKER_OPTION cmdsize too small");
941 auto LinkOptionOrErr =
942 getStructOrErr<MachO::linker_option_command>(Obj, Load.Ptr);
943 if (!LinkOptionOrErr)
944 return LinkOptionOrErr.takeError();
945 MachO::linker_option_command L = LinkOptionOrErr.get();
946 // Make sure the count of strings is correct.
947 const char *string = (const char *)Load.Ptr +
948 sizeof(struct MachO::linker_option_command);
949 uint32_t left = L.cmdsize - sizeof(struct MachO::linker_option_command);
952 while (*string == '\0' && left > 0) {
958 uint32_t NullPos = StringRef(string, left).find('\0');
959 if (0xffffffff == NullPos)
960 return malformedError("load command " + Twine(LoadCommandIndex) +
961 " LC_LINKER_OPTION string #" + Twine(i) +
962 " is not NULL terminated");
963 uint32_t len = std::min(NullPos, left) + 1;
969 return malformedError("load command " + Twine(LoadCommandIndex) +
970 " LC_LINKER_OPTION string count " + Twine(L.count) +
971 " does not match number of strings");
972 return Error::success();
975 static Error checkSubCommand(const MachOObjectFile &Obj,
976 const MachOObjectFile::LoadCommandInfo &Load,
977 uint32_t LoadCommandIndex, const char *CmdName,
978 size_t SizeOfCmd, const char *CmdStructName,
979 uint32_t PathOffset, const char *PathFieldName) {
980 if (PathOffset < SizeOfCmd)
981 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
982 CmdName + " " + PathFieldName + ".offset field too "
983 "small, not past the end of the " + CmdStructName);
984 if (PathOffset >= Load.C.cmdsize)
985 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
986 CmdName + " " + PathFieldName + ".offset field "
987 "extends past the end of the load command");
988 // Make sure there is a null between the starting offset of the path and
989 // the end of the load command.
991 const char *P = (const char *)Load.Ptr;
992 for (i = PathOffset; i < Load.C.cmdsize; i++)
995 if (i >= Load.C.cmdsize)
996 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
997 CmdName + " " + PathFieldName + " name extends past "
998 "the end of the load command");
999 return Error::success();
1002 static Error checkThreadCommand(const MachOObjectFile &Obj,
1003 const MachOObjectFile::LoadCommandInfo &Load,
1004 uint32_t LoadCommandIndex,
1005 const char *CmdName) {
1006 if (Load.C.cmdsize < sizeof(MachO::thread_command))
1007 return malformedError("load command " + Twine(LoadCommandIndex) +
1008 CmdName + " cmdsize too small");
1009 auto ThreadCommandOrErr =
1010 getStructOrErr<MachO::thread_command>(Obj, Load.Ptr);
1011 if (!ThreadCommandOrErr)
1012 return ThreadCommandOrErr.takeError();
1013 MachO::thread_command T = ThreadCommandOrErr.get();
1014 const char *state = Load.Ptr + sizeof(MachO::thread_command);
1015 const char *end = Load.Ptr + T.cmdsize;
1016 uint32_t nflavor = 0;
1017 uint32_t cputype = getCPUType(Obj);
1018 while (state < end) {
1019 if(state + sizeof(uint32_t) > end)
1020 return malformedError("load command " + Twine(LoadCommandIndex) +
1021 "flavor in " + CmdName + " extends past end of "
1024 memcpy(&flavor, state, sizeof(uint32_t));
1025 if (Obj.isLittleEndian() != sys::IsLittleEndianHost)
1026 sys::swapByteOrder(flavor);
1027 state += sizeof(uint32_t);
1029 if(state + sizeof(uint32_t) > end)
1030 return malformedError("load command " + Twine(LoadCommandIndex) +
1031 " count in " + CmdName + " extends past end of "
1034 memcpy(&count, state, sizeof(uint32_t));
1035 if (Obj.isLittleEndian() != sys::IsLittleEndianHost)
1036 sys::swapByteOrder(count);
1037 state += sizeof(uint32_t);
1039 if (cputype == MachO::CPU_TYPE_I386) {
1040 if (flavor == MachO::x86_THREAD_STATE32) {
1041 if (count != MachO::x86_THREAD_STATE32_COUNT)
1042 return malformedError("load command " + Twine(LoadCommandIndex) +
1043 " count not x86_THREAD_STATE32_COUNT for "
1044 "flavor number " + Twine(nflavor) + " which is "
1045 "a x86_THREAD_STATE32 flavor in " + CmdName +
1047 if (state + sizeof(MachO::x86_thread_state32_t) > end)
1048 return malformedError("load command " + Twine(LoadCommandIndex) +
1049 " x86_THREAD_STATE32 extends past end of "
1050 "command in " + CmdName + " command");
1051 state += sizeof(MachO::x86_thread_state32_t);
1053 return malformedError("load command " + Twine(LoadCommandIndex) +
1054 " unknown flavor (" + Twine(flavor) + ") for "
1055 "flavor number " + Twine(nflavor) + " in " +
1056 CmdName + " command");
1058 } else if (cputype == MachO::CPU_TYPE_X86_64) {
1059 if (flavor == MachO::x86_THREAD_STATE) {
1060 if (count != MachO::x86_THREAD_STATE_COUNT)
1061 return malformedError("load command " + Twine(LoadCommandIndex) +
1062 " count not x86_THREAD_STATE_COUNT for "
1063 "flavor number " + Twine(nflavor) + " which is "
1064 "a x86_THREAD_STATE flavor in " + CmdName +
1066 if (state + sizeof(MachO::x86_thread_state_t) > end)
1067 return malformedError("load command " + Twine(LoadCommandIndex) +
1068 " x86_THREAD_STATE extends past end of "
1069 "command in " + CmdName + " command");
1070 state += sizeof(MachO::x86_thread_state_t);
1071 } else if (flavor == MachO::x86_FLOAT_STATE) {
1072 if (count != MachO::x86_FLOAT_STATE_COUNT)
1073 return malformedError("load command " + Twine(LoadCommandIndex) +
1074 " count not x86_FLOAT_STATE_COUNT for "
1075 "flavor number " + Twine(nflavor) + " which is "
1076 "a x86_FLOAT_STATE flavor in " + CmdName +
1078 if (state + sizeof(MachO::x86_float_state_t) > end)
1079 return malformedError("load command " + Twine(LoadCommandIndex) +
1080 " x86_FLOAT_STATE extends past end of "
1081 "command in " + CmdName + " command");
1082 state += sizeof(MachO::x86_float_state_t);
1083 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
1084 if (count != MachO::x86_EXCEPTION_STATE_COUNT)
1085 return malformedError("load command " + Twine(LoadCommandIndex) +
1086 " count not x86_EXCEPTION_STATE_COUNT for "
1087 "flavor number " + Twine(nflavor) + " which is "
1088 "a x86_EXCEPTION_STATE flavor in " + CmdName +
1090 if (state + sizeof(MachO::x86_exception_state_t) > end)
1091 return malformedError("load command " + Twine(LoadCommandIndex) +
1092 " x86_EXCEPTION_STATE extends past end of "
1093 "command in " + CmdName + " command");
1094 state += sizeof(MachO::x86_exception_state_t);
1095 } else if (flavor == MachO::x86_THREAD_STATE64) {
1096 if (count != MachO::x86_THREAD_STATE64_COUNT)
1097 return malformedError("load command " + Twine(LoadCommandIndex) +
1098 " count not x86_THREAD_STATE64_COUNT for "
1099 "flavor number " + Twine(nflavor) + " which is "
1100 "a x86_THREAD_STATE64 flavor in " + CmdName +
1102 if (state + sizeof(MachO::x86_thread_state64_t) > end)
1103 return malformedError("load command " + Twine(LoadCommandIndex) +
1104 " x86_THREAD_STATE64 extends past end of "
1105 "command in " + CmdName + " command");
1106 state += sizeof(MachO::x86_thread_state64_t);
1107 } else if (flavor == MachO::x86_EXCEPTION_STATE64) {
1108 if (count != MachO::x86_EXCEPTION_STATE64_COUNT)
1109 return malformedError("load command " + Twine(LoadCommandIndex) +
1110 " count not x86_EXCEPTION_STATE64_COUNT for "
1111 "flavor number " + Twine(nflavor) + " which is "
1112 "a x86_EXCEPTION_STATE64 flavor in " + CmdName +
1114 if (state + sizeof(MachO::x86_exception_state64_t) > end)
1115 return malformedError("load command " + Twine(LoadCommandIndex) +
1116 " x86_EXCEPTION_STATE64 extends past end of "
1117 "command in " + CmdName + " command");
1118 state += sizeof(MachO::x86_exception_state64_t);
1120 return malformedError("load command " + Twine(LoadCommandIndex) +
1121 " unknown flavor (" + Twine(flavor) + ") for "
1122 "flavor number " + Twine(nflavor) + " in " +
1123 CmdName + " command");
1125 } else if (cputype == MachO::CPU_TYPE_ARM) {
1126 if (flavor == MachO::ARM_THREAD_STATE) {
1127 if (count != MachO::ARM_THREAD_STATE_COUNT)
1128 return malformedError("load command " + Twine(LoadCommandIndex) +
1129 " count not ARM_THREAD_STATE_COUNT for "
1130 "flavor number " + Twine(nflavor) + " which is "
1131 "a ARM_THREAD_STATE flavor in " + CmdName +
1133 if (state + sizeof(MachO::arm_thread_state32_t) > end)
1134 return malformedError("load command " + Twine(LoadCommandIndex) +
1135 " ARM_THREAD_STATE extends past end of "
1136 "command in " + CmdName + " command");
1137 state += sizeof(MachO::arm_thread_state32_t);
1139 return malformedError("load command " + Twine(LoadCommandIndex) +
1140 " unknown flavor (" + Twine(flavor) + ") for "
1141 "flavor number " + Twine(nflavor) + " in " +
1142 CmdName + " command");
1144 } else if (cputype == MachO::CPU_TYPE_ARM64 ||
1145 cputype == MachO::CPU_TYPE_ARM64_32) {
1146 if (flavor == MachO::ARM_THREAD_STATE64) {
1147 if (count != MachO::ARM_THREAD_STATE64_COUNT)
1148 return malformedError("load command " + Twine(LoadCommandIndex) +
1149 " count not ARM_THREAD_STATE64_COUNT for "
1150 "flavor number " + Twine(nflavor) + " which is "
1151 "a ARM_THREAD_STATE64 flavor in " + CmdName +
1153 if (state + sizeof(MachO::arm_thread_state64_t) > end)
1154 return malformedError("load command " + Twine(LoadCommandIndex) +
1155 " ARM_THREAD_STATE64 extends past end of "
1156 "command in " + CmdName + " command");
1157 state += sizeof(MachO::arm_thread_state64_t);
1159 return malformedError("load command " + Twine(LoadCommandIndex) +
1160 " unknown flavor (" + Twine(flavor) + ") for "
1161 "flavor number " + Twine(nflavor) + " in " +
1162 CmdName + " command");
1164 } else if (cputype == MachO::CPU_TYPE_POWERPC) {
1165 if (flavor == MachO::PPC_THREAD_STATE) {
1166 if (count != MachO::PPC_THREAD_STATE_COUNT)
1167 return malformedError("load command " + Twine(LoadCommandIndex) +
1168 " count not PPC_THREAD_STATE_COUNT for "
1169 "flavor number " + Twine(nflavor) + " which is "
1170 "a PPC_THREAD_STATE flavor in " + CmdName +
1172 if (state + sizeof(MachO::ppc_thread_state32_t) > end)
1173 return malformedError("load command " + Twine(LoadCommandIndex) +
1174 " PPC_THREAD_STATE extends past end of "
1175 "command in " + CmdName + " command");
1176 state += sizeof(MachO::ppc_thread_state32_t);
1178 return malformedError("load command " + Twine(LoadCommandIndex) +
1179 " unknown flavor (" + Twine(flavor) + ") for "
1180 "flavor number " + Twine(nflavor) + " in " +
1181 CmdName + " command");
1184 return malformedError("unknown cputype (" + Twine(cputype) + ") load "
1185 "command " + Twine(LoadCommandIndex) + " for " +
1186 CmdName + " command can't be checked");
1190 return Error::success();
1193 static Error checkTwoLevelHintsCommand(const MachOObjectFile &Obj,
1194 const MachOObjectFile::LoadCommandInfo
1196 uint32_t LoadCommandIndex,
1197 const char **LoadCmd,
1198 std::list<MachOElement> &Elements) {
1199 if (Load.C.cmdsize != sizeof(MachO::twolevel_hints_command))
1200 return malformedError("load command " + Twine(LoadCommandIndex) +
1201 " LC_TWOLEVEL_HINTS has incorrect cmdsize");
1202 if (*LoadCmd != nullptr)
1203 return malformedError("more than one LC_TWOLEVEL_HINTS command");
1204 auto HintsOrErr = getStructOrErr<MachO::twolevel_hints_command>(Obj, Load.Ptr);
1206 return HintsOrErr.takeError();
1207 MachO::twolevel_hints_command Hints = HintsOrErr.get();
1208 uint64_t FileSize = Obj.getData().size();
1209 if (Hints.offset > FileSize)
1210 return malformedError("offset field of LC_TWOLEVEL_HINTS command " +
1211 Twine(LoadCommandIndex) + " extends past the end of "
1213 uint64_t BigSize = Hints.nhints;
1214 BigSize *= sizeof(MachO::twolevel_hint);
1215 BigSize += Hints.offset;
1216 if (BigSize > FileSize)
1217 return malformedError("offset field plus nhints times sizeof(struct "
1218 "twolevel_hint) field of LC_TWOLEVEL_HINTS command " +
1219 Twine(LoadCommandIndex) + " extends past the end of "
1221 if (Error Err = checkOverlappingElement(Elements, Hints.offset, Hints.nhints *
1222 sizeof(MachO::twolevel_hint),
1225 *LoadCmd = Load.Ptr;
1226 return Error::success();
1229 // Returns true if the libObject code does not support the load command and its
1230 // contents. The cmd value it is treated as an unknown load command but with
1231 // an error message that says the cmd value is obsolete.
1232 static bool isLoadCommandObsolete(uint32_t cmd) {
1233 if (cmd == MachO::LC_SYMSEG ||
1234 cmd == MachO::LC_LOADFVMLIB ||
1235 cmd == MachO::LC_IDFVMLIB ||
1236 cmd == MachO::LC_IDENT ||
1237 cmd == MachO::LC_FVMFILE ||
1238 cmd == MachO::LC_PREPAGE ||
1239 cmd == MachO::LC_PREBOUND_DYLIB ||
1240 cmd == MachO::LC_TWOLEVEL_HINTS ||
1241 cmd == MachO::LC_PREBIND_CKSUM)
1246 Expected<std::unique_ptr<MachOObjectFile>>
1247 MachOObjectFile::create(MemoryBufferRef Object, bool IsLittleEndian,
1248 bool Is64Bits, uint32_t UniversalCputype,
1249 uint32_t UniversalIndex) {
1250 Error Err = Error::success();
1251 std::unique_ptr<MachOObjectFile> Obj(
1252 new MachOObjectFile(std::move(Object), IsLittleEndian,
1253 Is64Bits, Err, UniversalCputype,
1256 return std::move(Err);
1257 return std::move(Obj);
1260 MachOObjectFile::MachOObjectFile(MemoryBufferRef Object, bool IsLittleEndian,
1261 bool Is64bits, Error &Err,
1262 uint32_t UniversalCputype,
1263 uint32_t UniversalIndex)
1264 : ObjectFile(getMachOType(IsLittleEndian, Is64bits), Object) {
1265 ErrorAsOutParameter ErrAsOutParam(&Err);
1266 uint64_t SizeOfHeaders;
1269 parseHeader(*this, Header64, Err);
1270 SizeOfHeaders = sizeof(MachO::mach_header_64);
1271 cputype = Header64.cputype;
1273 parseHeader(*this, Header, Err);
1274 SizeOfHeaders = sizeof(MachO::mach_header);
1275 cputype = Header.cputype;
1279 SizeOfHeaders += getHeader().sizeofcmds;
1280 if (getData().data() + SizeOfHeaders > getData().end()) {
1281 Err = malformedError("load commands extend past the end of the file");
1284 if (UniversalCputype != 0 && cputype != UniversalCputype) {
1285 Err = malformedError("universal header architecture: " +
1286 Twine(UniversalIndex) + "'s cputype does not match "
1287 "object file's mach header");
1290 std::list<MachOElement> Elements;
1291 Elements.push_back({0, SizeOfHeaders, "Mach-O headers"});
1293 uint32_t LoadCommandCount = getHeader().ncmds;
1294 LoadCommandInfo Load;
1295 if (LoadCommandCount != 0) {
1296 if (auto LoadOrErr = getFirstLoadCommandInfo(*this))
1299 Err = LoadOrErr.takeError();
1304 const char *DyldIdLoadCmd = nullptr;
1305 const char *FuncStartsLoadCmd = 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) {
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 "
1330 if (Load.C.cmdsize % 4 != 0) {
1331 Err = malformedError("load command " + Twine(I) + " cmdsize not a "
1336 LoadCommands.push_back(Load);
1337 if (Load.C.cmd == MachO::LC_SYMTAB) {
1338 if ((Err = checkSymtabCommand(*this, Load, I, &SymtabLoadCmd, Elements)))
1340 } else if (Load.C.cmd == MachO::LC_DYSYMTAB) {
1341 if ((Err = checkDysymtabCommand(*this, Load, I, &DysymtabLoadCmd,
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")))
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 "
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")))
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")))
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")))
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")))
1375 } else if (Load.C.cmd == MachO::LC_DYLD_INFO) {
1376 if ((Err = checkDyldInfoCommand(*this, Load, I, &DyldInfoLoadCmd,
1377 "LC_DYLD_INFO", Elements)))
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)))
1383 } else if (Load.C.cmd == MachO::LC_UUID) {
1384 if (Load.C.cmdsize != sizeof(MachO::uuid_command)) {
1385 Err = malformedError("LC_UUID command " + Twine(I) + " has incorrect "
1390 Err = malformedError("more than one LC_UUID command");
1393 UuidLoadCmd = Load.Ptr;
1394 } else if (Load.C.cmd == MachO::LC_SEGMENT_64) {
1395 if ((Err = parseSegmentLoadCommand<MachO::segment_command_64,
1397 *this, Load, Sections, HasPageZeroSegment, I,
1398 "LC_SEGMENT_64", SizeOfHeaders, Elements)))
1400 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
1401 if ((Err = parseSegmentLoadCommand<MachO::segment_command,
1403 *this, Load, Sections, HasPageZeroSegment, I,
1404 "LC_SEGMENT", SizeOfHeaders, Elements)))
1406 } else if (Load.C.cmd == MachO::LC_ID_DYLIB) {
1407 if ((Err = checkDylibIdCommand(*this, Load, I, &DyldIdLoadCmd)))
1409 } else if (Load.C.cmd == MachO::LC_LOAD_DYLIB) {
1410 if ((Err = checkDylibCommand(*this, Load, I, "LC_LOAD_DYLIB")))
1412 Libraries.push_back(Load.Ptr);
1413 } else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB) {
1414 if ((Err = checkDylibCommand(*this, Load, I, "LC_LOAD_WEAK_DYLIB")))
1416 Libraries.push_back(Load.Ptr);
1417 } else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB) {
1418 if ((Err = checkDylibCommand(*this, Load, I, "LC_LAZY_LOAD_DYLIB")))
1420 Libraries.push_back(Load.Ptr);
1421 } else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB) {
1422 if ((Err = checkDylibCommand(*this, Load, I, "LC_REEXPORT_DYLIB")))
1424 Libraries.push_back(Load.Ptr);
1425 } else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
1426 if ((Err = checkDylibCommand(*this, Load, I, "LC_LOAD_UPWARD_DYLIB")))
1428 Libraries.push_back(Load.Ptr);
1429 } else if (Load.C.cmd == MachO::LC_ID_DYLINKER) {
1430 if ((Err = checkDyldCommand(*this, Load, I, "LC_ID_DYLINKER")))
1432 } else if (Load.C.cmd == MachO::LC_LOAD_DYLINKER) {
1433 if ((Err = checkDyldCommand(*this, Load, I, "LC_LOAD_DYLINKER")))
1435 } else if (Load.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
1436 if ((Err = checkDyldCommand(*this, Load, I, "LC_DYLD_ENVIRONMENT")))
1438 } else if (Load.C.cmd == MachO::LC_VERSION_MIN_MACOSX) {
1439 if ((Err = checkVersCommand(*this, Load, I, &VersLoadCmd,
1440 "LC_VERSION_MIN_MACOSX")))
1442 } else if (Load.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS) {
1443 if ((Err = checkVersCommand(*this, Load, I, &VersLoadCmd,
1444 "LC_VERSION_MIN_IPHONEOS")))
1446 } else if (Load.C.cmd == MachO::LC_VERSION_MIN_TVOS) {
1447 if ((Err = checkVersCommand(*this, Load, I, &VersLoadCmd,
1448 "LC_VERSION_MIN_TVOS")))
1450 } else if (Load.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
1451 if ((Err = checkVersCommand(*this, Load, I, &VersLoadCmd,
1452 "LC_VERSION_MIN_WATCHOS")))
1454 } else if (Load.C.cmd == MachO::LC_NOTE) {
1455 if ((Err = checkNoteCommand(*this, Load, I, Elements)))
1457 } else if (Load.C.cmd == MachO::LC_BUILD_VERSION) {
1458 if ((Err = parseBuildVersionCommand(*this, Load, BuildTools, I)))
1460 } else if (Load.C.cmd == MachO::LC_RPATH) {
1461 if ((Err = checkRpathCommand(*this, Load, I)))
1463 } else if (Load.C.cmd == MachO::LC_SOURCE_VERSION) {
1464 if (Load.C.cmdsize != sizeof(MachO::source_version_command)) {
1465 Err = malformedError("LC_SOURCE_VERSION command " + Twine(I) +
1466 " has incorrect cmdsize");
1469 if (SourceLoadCmd) {
1470 Err = malformedError("more than one LC_SOURCE_VERSION command");
1473 SourceLoadCmd = Load.Ptr;
1474 } else if (Load.C.cmd == MachO::LC_MAIN) {
1475 if (Load.C.cmdsize != sizeof(MachO::entry_point_command)) {
1476 Err = malformedError("LC_MAIN command " + Twine(I) +
1477 " has incorrect cmdsize");
1480 if (EntryPointLoadCmd) {
1481 Err = malformedError("more than one LC_MAIN command");
1484 EntryPointLoadCmd = Load.Ptr;
1485 } else if (Load.C.cmd == MachO::LC_ENCRYPTION_INFO) {
1486 if (Load.C.cmdsize != sizeof(MachO::encryption_info_command)) {
1487 Err = malformedError("LC_ENCRYPTION_INFO command " + Twine(I) +
1488 " has incorrect cmdsize");
1491 MachO::encryption_info_command E =
1492 getStruct<MachO::encryption_info_command>(*this, Load.Ptr);
1493 if ((Err = checkEncryptCommand(*this, Load, I, E.cryptoff, E.cryptsize,
1494 &EncryptLoadCmd, "LC_ENCRYPTION_INFO")))
1496 } else if (Load.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
1497 if (Load.C.cmdsize != sizeof(MachO::encryption_info_command_64)) {
1498 Err = malformedError("LC_ENCRYPTION_INFO_64 command " + Twine(I) +
1499 " has incorrect cmdsize");
1502 MachO::encryption_info_command_64 E =
1503 getStruct<MachO::encryption_info_command_64>(*this, Load.Ptr);
1504 if ((Err = checkEncryptCommand(*this, Load, I, E.cryptoff, E.cryptsize,
1505 &EncryptLoadCmd, "LC_ENCRYPTION_INFO_64")))
1507 } else if (Load.C.cmd == MachO::LC_LINKER_OPTION) {
1508 if ((Err = checkLinkerOptCommand(*this, Load, I)))
1510 } else if (Load.C.cmd == MachO::LC_SUB_FRAMEWORK) {
1511 if (Load.C.cmdsize < sizeof(MachO::sub_framework_command)) {
1512 Err = malformedError("load command " + Twine(I) +
1513 " LC_SUB_FRAMEWORK cmdsize too small");
1516 MachO::sub_framework_command S =
1517 getStruct<MachO::sub_framework_command>(*this, Load.Ptr);
1518 if ((Err = checkSubCommand(*this, Load, I, "LC_SUB_FRAMEWORK",
1519 sizeof(MachO::sub_framework_command),
1520 "sub_framework_command", S.umbrella,
1523 } else if (Load.C.cmd == MachO::LC_SUB_UMBRELLA) {
1524 if (Load.C.cmdsize < sizeof(MachO::sub_umbrella_command)) {
1525 Err = malformedError("load command " + Twine(I) +
1526 " LC_SUB_UMBRELLA cmdsize too small");
1529 MachO::sub_umbrella_command S =
1530 getStruct<MachO::sub_umbrella_command>(*this, Load.Ptr);
1531 if ((Err = checkSubCommand(*this, Load, I, "LC_SUB_UMBRELLA",
1532 sizeof(MachO::sub_umbrella_command),
1533 "sub_umbrella_command", S.sub_umbrella,
1536 } else if (Load.C.cmd == MachO::LC_SUB_LIBRARY) {
1537 if (Load.C.cmdsize < sizeof(MachO::sub_library_command)) {
1538 Err = malformedError("load command " + Twine(I) +
1539 " LC_SUB_LIBRARY cmdsize too small");
1542 MachO::sub_library_command S =
1543 getStruct<MachO::sub_library_command>(*this, Load.Ptr);
1544 if ((Err = checkSubCommand(*this, Load, I, "LC_SUB_LIBRARY",
1545 sizeof(MachO::sub_library_command),
1546 "sub_library_command", S.sub_library,
1549 } else if (Load.C.cmd == MachO::LC_SUB_CLIENT) {
1550 if (Load.C.cmdsize < sizeof(MachO::sub_client_command)) {
1551 Err = malformedError("load command " + Twine(I) +
1552 " LC_SUB_CLIENT cmdsize too small");
1555 MachO::sub_client_command S =
1556 getStruct<MachO::sub_client_command>(*this, Load.Ptr);
1557 if ((Err = checkSubCommand(*this, Load, I, "LC_SUB_CLIENT",
1558 sizeof(MachO::sub_client_command),
1559 "sub_client_command", S.client, "client")))
1561 } else if (Load.C.cmd == MachO::LC_ROUTINES) {
1562 if (Load.C.cmdsize != sizeof(MachO::routines_command)) {
1563 Err = malformedError("LC_ROUTINES command " + Twine(I) +
1564 " has incorrect cmdsize");
1567 if (RoutinesLoadCmd) {
1568 Err = malformedError("more than one LC_ROUTINES and or LC_ROUTINES_64 "
1572 RoutinesLoadCmd = Load.Ptr;
1573 } else if (Load.C.cmd == MachO::LC_ROUTINES_64) {
1574 if (Load.C.cmdsize != sizeof(MachO::routines_command_64)) {
1575 Err = malformedError("LC_ROUTINES_64 command " + Twine(I) +
1576 " has incorrect cmdsize");
1579 if (RoutinesLoadCmd) {
1580 Err = malformedError("more than one LC_ROUTINES_64 and or LC_ROUTINES "
1584 RoutinesLoadCmd = Load.Ptr;
1585 } else if (Load.C.cmd == MachO::LC_UNIXTHREAD) {
1586 if ((Err = checkThreadCommand(*this, Load, I, "LC_UNIXTHREAD")))
1588 if (UnixThreadLoadCmd) {
1589 Err = malformedError("more than one LC_UNIXTHREAD command");
1592 UnixThreadLoadCmd = Load.Ptr;
1593 } else if (Load.C.cmd == MachO::LC_THREAD) {
1594 if ((Err = checkThreadCommand(*this, Load, I, "LC_THREAD")))
1596 // Note: LC_TWOLEVEL_HINTS is really obsolete and is not supported.
1597 } else if (Load.C.cmd == MachO::LC_TWOLEVEL_HINTS) {
1598 if ((Err = checkTwoLevelHintsCommand(*this, Load, I,
1599 &TwoLevelHintsLoadCmd, Elements)))
1601 } else if (isLoadCommandObsolete(Load.C.cmd)) {
1602 Err = malformedError("load command " + Twine(I) + " for cmd value of: " +
1603 Twine(Load.C.cmd) + " is obsolete and not "
1607 // TODO: generate a error for unknown load commands by default. But still
1608 // need work out an approach to allow or not allow unknown values like this
1609 // as an option for some uses like lldb.
1610 if (I < LoadCommandCount - 1) {
1611 if (auto LoadOrErr = getNextLoadCommandInfo(*this, I, Load))
1614 Err = LoadOrErr.takeError();
1619 if (!SymtabLoadCmd) {
1620 if (DysymtabLoadCmd) {
1621 Err = malformedError("contains LC_DYSYMTAB load command without a "
1622 "LC_SYMTAB load command");
1625 } else if (DysymtabLoadCmd) {
1626 MachO::symtab_command Symtab =
1627 getStruct<MachO::symtab_command>(*this, SymtabLoadCmd);
1628 MachO::dysymtab_command Dysymtab =
1629 getStruct<MachO::dysymtab_command>(*this, DysymtabLoadCmd);
1630 if (Dysymtab.nlocalsym != 0 && Dysymtab.ilocalsym > Symtab.nsyms) {
1631 Err = malformedError("ilocalsym in LC_DYSYMTAB load command "
1632 "extends past the end of the symbol table");
1635 uint64_t BigSize = Dysymtab.ilocalsym;
1636 BigSize += Dysymtab.nlocalsym;
1637 if (Dysymtab.nlocalsym != 0 && BigSize > Symtab.nsyms) {
1638 Err = malformedError("ilocalsym plus nlocalsym in LC_DYSYMTAB load "
1639 "command extends past the end of the symbol table");
1642 if (Dysymtab.nextdefsym != 0 && Dysymtab.iextdefsym > Symtab.nsyms) {
1643 Err = malformedError("iextdefsym in LC_DYSYMTAB load command "
1644 "extends past the end of the symbol table");
1647 BigSize = Dysymtab.iextdefsym;
1648 BigSize += Dysymtab.nextdefsym;
1649 if (Dysymtab.nextdefsym != 0 && BigSize > Symtab.nsyms) {
1650 Err = malformedError("iextdefsym plus nextdefsym in LC_DYSYMTAB "
1651 "load command extends past the end of the symbol "
1655 if (Dysymtab.nundefsym != 0 && Dysymtab.iundefsym > Symtab.nsyms) {
1656 Err = malformedError("iundefsym in LC_DYSYMTAB load command "
1657 "extends past the end of the symbol table");
1660 BigSize = Dysymtab.iundefsym;
1661 BigSize += Dysymtab.nundefsym;
1662 if (Dysymtab.nundefsym != 0 && BigSize > Symtab.nsyms) {
1663 Err = malformedError("iundefsym plus nundefsym in LC_DYSYMTAB load "
1664 " command extends past the end of the symbol table");
1668 if ((getHeader().filetype == MachO::MH_DYLIB ||
1669 getHeader().filetype == MachO::MH_DYLIB_STUB) &&
1670 DyldIdLoadCmd == nullptr) {
1671 Err = malformedError("no LC_ID_DYLIB load command in dynamic library "
1675 assert(LoadCommands.size() == LoadCommandCount);
1677 Err = Error::success();
1680 Error MachOObjectFile::checkSymbolTable() const {
1683 MachO::mach_header_64 H_64 = MachOObjectFile::getHeader64();
1686 MachO::mach_header H = MachOObjectFile::getHeader();
1693 uint64_t NValue = 0;
1694 uint32_t SymbolIndex = 0;
1695 MachO::symtab_command S = getSymtabLoadCommand();
1696 for (const SymbolRef &Symbol : symbols()) {
1697 DataRefImpl SymDRI = Symbol.getRawDataRefImpl();
1699 MachO::nlist_64 STE_64 = getSymbol64TableEntry(SymDRI);
1700 NType = STE_64.n_type;
1701 NSect = STE_64.n_sect;
1702 NDesc = STE_64.n_desc;
1703 NStrx = STE_64.n_strx;
1704 NValue = STE_64.n_value;
1706 MachO::nlist STE = getSymbolTableEntry(SymDRI);
1711 NValue = STE.n_value;
1713 if ((NType & MachO::N_STAB) == 0) {
1714 if ((NType & MachO::N_TYPE) == MachO::N_SECT) {
1715 if (NSect == 0 || NSect > Sections.size())
1716 return malformedError("bad section index: " + Twine((int)NSect) +
1717 " for symbol at index " + Twine(SymbolIndex));
1719 if ((NType & MachO::N_TYPE) == MachO::N_INDR) {
1720 if (NValue >= S.strsize)
1721 return malformedError("bad n_value: " + Twine((int)NValue) + " past "
1722 "the end of string table, for N_INDR symbol at "
1723 "index " + Twine(SymbolIndex));
1725 if ((Flags & MachO::MH_TWOLEVEL) == MachO::MH_TWOLEVEL &&
1726 (((NType & MachO::N_TYPE) == MachO::N_UNDF && NValue == 0) ||
1727 (NType & MachO::N_TYPE) == MachO::N_PBUD)) {
1728 uint32_t LibraryOrdinal = MachO::GET_LIBRARY_ORDINAL(NDesc);
1729 if (LibraryOrdinal != 0 &&
1730 LibraryOrdinal != MachO::EXECUTABLE_ORDINAL &&
1731 LibraryOrdinal != MachO::DYNAMIC_LOOKUP_ORDINAL &&
1732 LibraryOrdinal - 1 >= Libraries.size() ) {
1733 return malformedError("bad library ordinal: " + Twine(LibraryOrdinal) +
1734 " for symbol at index " + Twine(SymbolIndex));
1738 if (NStrx >= S.strsize)
1739 return malformedError("bad string table index: " + Twine((int)NStrx) +
1740 " past the end of string table, for symbol at "
1741 "index " + Twine(SymbolIndex));
1744 return Error::success();
1747 void MachOObjectFile::moveSymbolNext(DataRefImpl &Symb) const {
1748 unsigned SymbolTableEntrySize = is64Bit() ?
1749 sizeof(MachO::nlist_64) :
1750 sizeof(MachO::nlist);
1751 Symb.p += SymbolTableEntrySize;
1754 Expected<StringRef> MachOObjectFile::getSymbolName(DataRefImpl Symb) const {
1755 StringRef StringTable = getStringTableData();
1756 MachO::nlist_base Entry = getSymbolTableEntryBase(*this, Symb);
1757 if (Entry.n_strx == 0)
1758 // A n_strx value of 0 indicates that no name is associated with a
1759 // particular symbol table entry.
1761 const char *Start = &StringTable.data()[Entry.n_strx];
1762 if (Start < getData().begin() || Start >= getData().end()) {
1763 return malformedError("bad string index: " + Twine(Entry.n_strx) +
1764 " for symbol at index " + Twine(getSymbolIndex(Symb)));
1766 return StringRef(Start);
1769 unsigned MachOObjectFile::getSectionType(SectionRef Sec) const {
1770 DataRefImpl DRI = Sec.getRawDataRefImpl();
1771 uint32_t Flags = getSectionFlags(*this, DRI);
1772 return Flags & MachO::SECTION_TYPE;
1775 uint64_t MachOObjectFile::getNValue(DataRefImpl Sym) const {
1777 MachO::nlist_64 Entry = getSymbol64TableEntry(Sym);
1778 return Entry.n_value;
1780 MachO::nlist Entry = getSymbolTableEntry(Sym);
1781 return Entry.n_value;
1784 // getIndirectName() returns the name of the alias'ed symbol who's string table
1785 // index is in the n_value field.
1786 std::error_code MachOObjectFile::getIndirectName(DataRefImpl Symb,
1787 StringRef &Res) const {
1788 StringRef StringTable = getStringTableData();
1789 MachO::nlist_base Entry = getSymbolTableEntryBase(*this, Symb);
1790 if ((Entry.n_type & MachO::N_TYPE) != MachO::N_INDR)
1791 return object_error::parse_failed;
1792 uint64_t NValue = getNValue(Symb);
1793 if (NValue >= StringTable.size())
1794 return object_error::parse_failed;
1795 const char *Start = &StringTable.data()[NValue];
1796 Res = StringRef(Start);
1797 return std::error_code();
1800 uint64_t MachOObjectFile::getSymbolValueImpl(DataRefImpl Sym) const {
1801 return getNValue(Sym);
1804 Expected<uint64_t> MachOObjectFile::getSymbolAddress(DataRefImpl Sym) const {
1805 return getSymbolValue(Sym);
1808 uint32_t MachOObjectFile::getSymbolAlignment(DataRefImpl DRI) const {
1809 uint32_t flags = getSymbolFlags(DRI);
1810 if (flags & SymbolRef::SF_Common) {
1811 MachO::nlist_base Entry = getSymbolTableEntryBase(*this, DRI);
1812 return 1 << MachO::GET_COMM_ALIGN(Entry.n_desc);
1817 uint64_t MachOObjectFile::getCommonSymbolSizeImpl(DataRefImpl DRI) const {
1818 return getNValue(DRI);
1821 Expected<SymbolRef::Type>
1822 MachOObjectFile::getSymbolType(DataRefImpl Symb) const {
1823 MachO::nlist_base Entry = getSymbolTableEntryBase(*this, Symb);
1824 uint8_t n_type = Entry.n_type;
1826 // If this is a STAB debugging symbol, we can do nothing more.
1827 if (n_type & MachO::N_STAB)
1828 return SymbolRef::ST_Debug;
1830 switch (n_type & MachO::N_TYPE) {
1831 case MachO::N_UNDF :
1832 return SymbolRef::ST_Unknown;
1833 case MachO::N_SECT :
1834 Expected<section_iterator> SecOrError = getSymbolSection(Symb);
1836 return SecOrError.takeError();
1837 section_iterator Sec = *SecOrError;
1838 if (Sec->isData() || Sec->isBSS())
1839 return SymbolRef::ST_Data;
1840 return SymbolRef::ST_Function;
1842 return SymbolRef::ST_Other;
1845 uint32_t MachOObjectFile::getSymbolFlags(DataRefImpl DRI) const {
1846 MachO::nlist_base Entry = getSymbolTableEntryBase(*this, DRI);
1848 uint8_t MachOType = Entry.n_type;
1849 uint16_t MachOFlags = Entry.n_desc;
1851 uint32_t Result = SymbolRef::SF_None;
1853 if ((MachOType & MachO::N_TYPE) == MachO::N_INDR)
1854 Result |= SymbolRef::SF_Indirect;
1856 if (MachOType & MachO::N_STAB)
1857 Result |= SymbolRef::SF_FormatSpecific;
1859 if (MachOType & MachO::N_EXT) {
1860 Result |= SymbolRef::SF_Global;
1861 if ((MachOType & MachO::N_TYPE) == MachO::N_UNDF) {
1863 Result |= SymbolRef::SF_Common;
1865 Result |= SymbolRef::SF_Undefined;
1868 if (!(MachOType & MachO::N_PEXT))
1869 Result |= SymbolRef::SF_Exported;
1872 if (MachOFlags & (MachO::N_WEAK_REF | MachO::N_WEAK_DEF))
1873 Result |= SymbolRef::SF_Weak;
1875 if (MachOFlags & (MachO::N_ARM_THUMB_DEF))
1876 Result |= SymbolRef::SF_Thumb;
1878 if ((MachOType & MachO::N_TYPE) == MachO::N_ABS)
1879 Result |= SymbolRef::SF_Absolute;
1884 Expected<section_iterator>
1885 MachOObjectFile::getSymbolSection(DataRefImpl Symb) const {
1886 MachO::nlist_base Entry = getSymbolTableEntryBase(*this, Symb);
1887 uint8_t index = Entry.n_sect;
1890 return section_end();
1892 DRI.d.a = index - 1;
1893 if (DRI.d.a >= Sections.size()){
1894 return malformedError("bad section index: " + Twine((int)index) +
1895 " for symbol at index " + Twine(getSymbolIndex(Symb)));
1897 return section_iterator(SectionRef(DRI, this));
1900 unsigned MachOObjectFile::getSymbolSectionID(SymbolRef Sym) const {
1901 MachO::nlist_base Entry =
1902 getSymbolTableEntryBase(*this, Sym.getRawDataRefImpl());
1903 return Entry.n_sect - 1;
1906 void MachOObjectFile::moveSectionNext(DataRefImpl &Sec) const {
1910 Expected<StringRef> MachOObjectFile::getSectionName(DataRefImpl Sec) const {
1911 ArrayRef<char> Raw = getSectionRawName(Sec);
1912 return parseSegmentOrSectionName(Raw.data());
1915 uint64_t MachOObjectFile::getSectionAddress(DataRefImpl Sec) const {
1917 return getSection64(Sec).addr;
1918 return getSection(Sec).addr;
1921 uint64_t MachOObjectFile::getSectionIndex(DataRefImpl Sec) const {
1925 uint64_t MachOObjectFile::getSectionSize(DataRefImpl Sec) const {
1926 // In the case if a malformed Mach-O file where the section offset is past
1927 // the end of the file or some part of the section size is past the end of
1928 // the file return a size of zero or a size that covers the rest of the file
1929 // but does not extend past the end of the file.
1930 uint32_t SectOffset, SectType;
1934 MachO::section_64 Sect = getSection64(Sec);
1935 SectOffset = Sect.offset;
1936 SectSize = Sect.size;
1937 SectType = Sect.flags & MachO::SECTION_TYPE;
1939 MachO::section Sect = getSection(Sec);
1940 SectOffset = Sect.offset;
1941 SectSize = Sect.size;
1942 SectType = Sect.flags & MachO::SECTION_TYPE;
1944 if (SectType == MachO::S_ZEROFILL || SectType == MachO::S_GB_ZEROFILL)
1946 uint64_t FileSize = getData().size();
1947 if (SectOffset > FileSize)
1949 if (FileSize - SectOffset < SectSize)
1950 return FileSize - SectOffset;
1954 Expected<ArrayRef<uint8_t>>
1955 MachOObjectFile::getSectionContents(DataRefImpl Sec) const {
1960 MachO::section_64 Sect = getSection64(Sec);
1961 Offset = Sect.offset;
1964 MachO::section Sect = getSection(Sec);
1965 Offset = Sect.offset;
1969 return arrayRefFromStringRef(getData().substr(Offset, Size));
1972 uint64_t MachOObjectFile::getSectionAlignment(DataRefImpl Sec) const {
1975 MachO::section_64 Sect = getSection64(Sec);
1978 MachO::section Sect = getSection(Sec);
1982 return uint64_t(1) << Align;
1985 Expected<SectionRef> MachOObjectFile::getSection(unsigned SectionIndex) const {
1986 if (SectionIndex < 1 || SectionIndex > Sections.size())
1987 return malformedError("bad section index: " + Twine((int)SectionIndex));
1990 DRI.d.a = SectionIndex - 1;
1991 return SectionRef(DRI, this);
1994 Expected<SectionRef> MachOObjectFile::getSection(StringRef SectionName) const {
1996 for (const SectionRef &Section : sections()) {
1997 if (std::error_code E = Section.getName(SecName))
1998 return errorCodeToError(E);
1999 if (SecName == SectionName) {
2003 return errorCodeToError(object_error::parse_failed);
2006 bool MachOObjectFile::isSectionCompressed(DataRefImpl Sec) const {
2010 bool MachOObjectFile::isSectionText(DataRefImpl Sec) const {
2011 uint32_t Flags = getSectionFlags(*this, Sec);
2012 return Flags & MachO::S_ATTR_PURE_INSTRUCTIONS;
2015 bool MachOObjectFile::isSectionData(DataRefImpl Sec) const {
2016 uint32_t Flags = getSectionFlags(*this, Sec);
2017 unsigned SectionType = Flags & MachO::SECTION_TYPE;
2018 return !(Flags & MachO::S_ATTR_PURE_INSTRUCTIONS) &&
2019 !(SectionType == MachO::S_ZEROFILL ||
2020 SectionType == MachO::S_GB_ZEROFILL);
2023 bool MachOObjectFile::isSectionBSS(DataRefImpl Sec) const {
2024 uint32_t Flags = getSectionFlags(*this, Sec);
2025 unsigned SectionType = Flags & MachO::SECTION_TYPE;
2026 return !(Flags & MachO::S_ATTR_PURE_INSTRUCTIONS) &&
2027 (SectionType == MachO::S_ZEROFILL ||
2028 SectionType == MachO::S_GB_ZEROFILL);
2031 unsigned MachOObjectFile::getSectionID(SectionRef Sec) const {
2032 return Sec.getRawDataRefImpl().d.a;
2035 bool MachOObjectFile::isSectionVirtual(DataRefImpl Sec) const {
2036 uint32_t Flags = getSectionFlags(*this, Sec);
2037 unsigned SectionType = Flags & MachO::SECTION_TYPE;
2038 return SectionType == MachO::S_ZEROFILL ||
2039 SectionType == MachO::S_GB_ZEROFILL;
2042 bool MachOObjectFile::isSectionBitcode(DataRefImpl Sec) const {
2043 StringRef SegmentName = getSectionFinalSegmentName(Sec);
2044 if (Expected<StringRef> NameOrErr = getSectionName(Sec))
2045 return (SegmentName == "__LLVM" && *NameOrErr == "__bitcode");
2049 bool MachOObjectFile::isSectionStripped(DataRefImpl Sec) const {
2051 return getSection64(Sec).offset == 0;
2052 return getSection(Sec).offset == 0;
2055 relocation_iterator MachOObjectFile::section_rel_begin(DataRefImpl Sec) const {
2059 return relocation_iterator(RelocationRef(Ret, this));
2063 MachOObjectFile::section_rel_end(DataRefImpl Sec) const {
2066 MachO::section_64 Sect = getSection64(Sec);
2069 MachO::section Sect = getSection(Sec);
2076 return relocation_iterator(RelocationRef(Ret, this));
2079 relocation_iterator MachOObjectFile::extrel_begin() const {
2081 // for DYSYMTAB symbols, Ret.d.a == 0 for external relocations
2082 Ret.d.a = 0; // Would normally be a section index.
2083 Ret.d.b = 0; // Index into the external relocations
2084 return relocation_iterator(RelocationRef(Ret, this));
2087 relocation_iterator MachOObjectFile::extrel_end() const {
2088 MachO::dysymtab_command DysymtabLoadCmd = getDysymtabLoadCommand();
2090 // for DYSYMTAB symbols, Ret.d.a == 0 for external relocations
2091 Ret.d.a = 0; // Would normally be a section index.
2092 Ret.d.b = DysymtabLoadCmd.nextrel; // Index into the external relocations
2093 return relocation_iterator(RelocationRef(Ret, this));
2096 relocation_iterator MachOObjectFile::locrel_begin() const {
2098 // for DYSYMTAB symbols, Ret.d.a == 1 for local relocations
2099 Ret.d.a = 1; // Would normally be a section index.
2100 Ret.d.b = 0; // Index into the local relocations
2101 return relocation_iterator(RelocationRef(Ret, this));
2104 relocation_iterator MachOObjectFile::locrel_end() const {
2105 MachO::dysymtab_command DysymtabLoadCmd = getDysymtabLoadCommand();
2107 // for DYSYMTAB symbols, Ret.d.a == 1 for local relocations
2108 Ret.d.a = 1; // Would normally be a section index.
2109 Ret.d.b = DysymtabLoadCmd.nlocrel; // Index into the local relocations
2110 return relocation_iterator(RelocationRef(Ret, this));
2113 void MachOObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
2117 uint64_t MachOObjectFile::getRelocationOffset(DataRefImpl Rel) const {
2118 assert((getHeader().filetype == MachO::MH_OBJECT ||
2119 getHeader().filetype == MachO::MH_KEXT_BUNDLE) &&
2120 "Only implemented for MH_OBJECT && MH_KEXT_BUNDLE");
2121 MachO::any_relocation_info RE = getRelocation(Rel);
2122 return getAnyRelocationAddress(RE);
2126 MachOObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
2127 MachO::any_relocation_info RE = getRelocation(Rel);
2128 if (isRelocationScattered(RE))
2129 return symbol_end();
2131 uint32_t SymbolIdx = getPlainRelocationSymbolNum(RE);
2132 bool isExtern = getPlainRelocationExternal(RE);
2134 return symbol_end();
2136 MachO::symtab_command S = getSymtabLoadCommand();
2137 unsigned SymbolTableEntrySize = is64Bit() ?
2138 sizeof(MachO::nlist_64) :
2139 sizeof(MachO::nlist);
2140 uint64_t Offset = S.symoff + SymbolIdx * SymbolTableEntrySize;
2142 Sym.p = reinterpret_cast<uintptr_t>(getPtr(*this, Offset));
2143 return symbol_iterator(SymbolRef(Sym, this));
2147 MachOObjectFile::getRelocationSection(DataRefImpl Rel) const {
2148 return section_iterator(getAnyRelocationSection(getRelocation(Rel)));
2151 uint64_t MachOObjectFile::getRelocationType(DataRefImpl Rel) const {
2152 MachO::any_relocation_info RE = getRelocation(Rel);
2153 return getAnyRelocationType(RE);
2156 void MachOObjectFile::getRelocationTypeName(
2157 DataRefImpl Rel, SmallVectorImpl<char> &Result) const {
2159 uint64_t RType = getRelocationType(Rel);
2161 unsigned Arch = this->getArch();
2165 static const char *const Table[] = {
2166 "GENERIC_RELOC_VANILLA",
2167 "GENERIC_RELOC_PAIR",
2168 "GENERIC_RELOC_SECTDIFF",
2169 "GENERIC_RELOC_PB_LA_PTR",
2170 "GENERIC_RELOC_LOCAL_SECTDIFF",
2171 "GENERIC_RELOC_TLV" };
2179 case Triple::x86_64: {
2180 static const char *const Table[] = {
2181 "X86_64_RELOC_UNSIGNED",
2182 "X86_64_RELOC_SIGNED",
2183 "X86_64_RELOC_BRANCH",
2184 "X86_64_RELOC_GOT_LOAD",
2186 "X86_64_RELOC_SUBTRACTOR",
2187 "X86_64_RELOC_SIGNED_1",
2188 "X86_64_RELOC_SIGNED_2",
2189 "X86_64_RELOC_SIGNED_4",
2190 "X86_64_RELOC_TLV" };
2199 static const char *const Table[] = {
2200 "ARM_RELOC_VANILLA",
2202 "ARM_RELOC_SECTDIFF",
2203 "ARM_RELOC_LOCAL_SECTDIFF",
2204 "ARM_RELOC_PB_LA_PTR",
2206 "ARM_THUMB_RELOC_BR22",
2207 "ARM_THUMB_32BIT_BRANCH",
2209 "ARM_RELOC_HALF_SECTDIFF" };
2217 case Triple::aarch64:
2218 case Triple::aarch64_32: {
2219 static const char *const Table[] = {
2220 "ARM64_RELOC_UNSIGNED", "ARM64_RELOC_SUBTRACTOR",
2221 "ARM64_RELOC_BRANCH26", "ARM64_RELOC_PAGE21",
2222 "ARM64_RELOC_PAGEOFF12", "ARM64_RELOC_GOT_LOAD_PAGE21",
2223 "ARM64_RELOC_GOT_LOAD_PAGEOFF12", "ARM64_RELOC_POINTER_TO_GOT",
2224 "ARM64_RELOC_TLVP_LOAD_PAGE21", "ARM64_RELOC_TLVP_LOAD_PAGEOFF12",
2225 "ARM64_RELOC_ADDEND"
2228 if (RType >= array_lengthof(Table))
2235 static const char *const Table[] = {
2236 "PPC_RELOC_VANILLA",
2244 "PPC_RELOC_SECTDIFF",
2245 "PPC_RELOC_PB_LA_PTR",
2246 "PPC_RELOC_HI16_SECTDIFF",
2247 "PPC_RELOC_LO16_SECTDIFF",
2248 "PPC_RELOC_HA16_SECTDIFF",
2250 "PPC_RELOC_LO14_SECTDIFF",
2251 "PPC_RELOC_LOCAL_SECTDIFF" };
2259 case Triple::UnknownArch:
2263 Result.append(res.begin(), res.end());
2266 uint8_t MachOObjectFile::getRelocationLength(DataRefImpl Rel) const {
2267 MachO::any_relocation_info RE = getRelocation(Rel);
2268 return getAnyRelocationLength(RE);
2272 // guessLibraryShortName() is passed a name of a dynamic library and returns a
2273 // guess on what the short name is. Then name is returned as a substring of the
2274 // StringRef Name passed in. The name of the dynamic library is recognized as
2275 // a framework if it has one of the two following forms:
2276 // Foo.framework/Versions/A/Foo
2277 // Foo.framework/Foo
2278 // Where A and Foo can be any string. And may contain a trailing suffix
2279 // starting with an underbar. If the Name is recognized as a framework then
2280 // isFramework is set to true else it is set to false. If the Name has a
2281 // suffix then Suffix is set to the substring in Name that contains the suffix
2282 // else it is set to a NULL StringRef.
2284 // The Name of the dynamic library is recognized as a library name if it has
2285 // one of the two following forms:
2289 // The library may have a suffix trailing the name Foo of the form:
2290 // libFoo_profile.A.dylib
2291 // libFoo_profile.dylib
2292 // These dyld image suffixes are separated from the short name by a '_'
2293 // character. Because the '_' character is commonly used to separate words in
2294 // filenames guessLibraryShortName() cannot reliably separate a dylib's short
2295 // name from an arbitrary image suffix; imagine if both the short name and the
2296 // suffix contains an '_' character! To better deal with this ambiguity,
2297 // guessLibraryShortName() will recognize only "_debug" and "_profile" as valid
2298 // Suffix values. Calling code needs to be tolerant of guessLibraryShortName()
2299 // guessing incorrectly.
2301 // The Name of the dynamic library is also recognized as a library name if it
2302 // has the following form:
2305 // If the Name of the dynamic library is none of the forms above then a NULL
2306 // StringRef is returned.
2307 StringRef MachOObjectFile::guessLibraryShortName(StringRef Name,
2309 StringRef &Suffix) {
2310 StringRef Foo, F, DotFramework, V, Dylib, Lib, Dot, Qtx;
2311 size_t a, b, c, d, Idx;
2313 isFramework = false;
2314 Suffix = StringRef();
2316 // Pull off the last component and make Foo point to it
2317 a = Name.rfind('/');
2318 if (a == Name.npos || a == 0)
2320 Foo = Name.slice(a+1, Name.npos);
2322 // Look for a suffix starting with a '_'
2323 Idx = Foo.rfind('_');
2324 if (Idx != Foo.npos && Foo.size() >= 2) {
2325 Suffix = Foo.slice(Idx, Foo.npos);
2326 if (Suffix != "_debug" && Suffix != "_profile")
2327 Suffix = StringRef();
2329 Foo = Foo.slice(0, Idx);
2332 // First look for the form Foo.framework/Foo
2333 b = Name.rfind('/', a);
2338 F = Name.slice(Idx, Idx + Foo.size());
2339 DotFramework = Name.slice(Idx + Foo.size(),
2340 Idx + Foo.size() + sizeof(".framework/")-1);
2341 if (F == Foo && DotFramework == ".framework/") {
2346 // Next look for the form Foo.framework/Versions/A/Foo
2349 c = Name.rfind('/', b);
2350 if (c == Name.npos || c == 0)
2352 V = Name.slice(c+1, Name.npos);
2353 if (!V.startswith("Versions/"))
2355 d = Name.rfind('/', c);
2360 F = Name.slice(Idx, Idx + Foo.size());
2361 DotFramework = Name.slice(Idx + Foo.size(),
2362 Idx + Foo.size() + sizeof(".framework/")-1);
2363 if (F == Foo && DotFramework == ".framework/") {
2369 // pull off the suffix after the "." and make a point to it
2370 a = Name.rfind('.');
2371 if (a == Name.npos || a == 0)
2373 Dylib = Name.slice(a, Name.npos);
2374 if (Dylib != ".dylib")
2377 // First pull off the version letter for the form Foo.A.dylib if any.
2379 Dot = Name.slice(a-2, a-1);
2384 b = Name.rfind('/', a);
2389 // ignore any suffix after an underbar like Foo_profile.A.dylib
2390 Idx = Name.rfind('_');
2391 if (Idx != Name.npos && Idx != b) {
2392 Lib = Name.slice(b, Idx);
2393 Suffix = Name.slice(Idx, a);
2394 if (Suffix != "_debug" && Suffix != "_profile") {
2395 Suffix = StringRef();
2396 Lib = Name.slice(b, a);
2400 Lib = Name.slice(b, a);
2401 // There are incorrect library names of the form:
2402 // libATS.A_profile.dylib so check for these.
2403 if (Lib.size() >= 3) {
2404 Dot = Lib.slice(Lib.size()-2, Lib.size()-1);
2406 Lib = Lib.slice(0, Lib.size()-2);
2411 Qtx = Name.slice(a, Name.npos);
2414 b = Name.rfind('/', a);
2416 Lib = Name.slice(0, a);
2418 Lib = Name.slice(b+1, a);
2419 // There are library names of the form: QT.A.qtx so check for these.
2420 if (Lib.size() >= 3) {
2421 Dot = Lib.slice(Lib.size()-2, Lib.size()-1);
2423 Lib = Lib.slice(0, Lib.size()-2);
2428 // getLibraryShortNameByIndex() is used to get the short name of the library
2429 // for an undefined symbol in a linked Mach-O binary that was linked with the
2430 // normal two-level namespace default (that is MH_TWOLEVEL in the header).
2431 // It is passed the index (0 - based) of the library as translated from
2432 // GET_LIBRARY_ORDINAL (1 - based).
2433 std::error_code MachOObjectFile::getLibraryShortNameByIndex(unsigned Index,
2434 StringRef &Res) const {
2435 if (Index >= Libraries.size())
2436 return object_error::parse_failed;
2438 // If the cache of LibrariesShortNames is not built up do that first for
2439 // all the Libraries.
2440 if (LibrariesShortNames.size() == 0) {
2441 for (unsigned i = 0; i < Libraries.size(); i++) {
2443 getStructOrErr<MachO::dylib_command>(*this, Libraries[i]);
2445 return object_error::parse_failed;
2446 MachO::dylib_command D = CommandOrErr.get();
2447 if (D.dylib.name >= D.cmdsize)
2448 return object_error::parse_failed;
2449 const char *P = (const char *)(Libraries[i]) + D.dylib.name;
2450 StringRef Name = StringRef(P);
2451 if (D.dylib.name+Name.size() >= D.cmdsize)
2452 return object_error::parse_failed;
2455 StringRef shortName = guessLibraryShortName(Name, isFramework, Suffix);
2456 if (shortName.empty())
2457 LibrariesShortNames.push_back(Name);
2459 LibrariesShortNames.push_back(shortName);
2463 Res = LibrariesShortNames[Index];
2464 return std::error_code();
2467 uint32_t MachOObjectFile::getLibraryCount() const {
2468 return Libraries.size();
2472 MachOObjectFile::getRelocationRelocatedSection(relocation_iterator Rel) const {
2474 Sec.d.a = Rel->getRawDataRefImpl().d.a;
2475 return section_iterator(SectionRef(Sec, this));
2478 basic_symbol_iterator MachOObjectFile::symbol_begin() const {
2480 MachO::symtab_command Symtab = getSymtabLoadCommand();
2481 if (!SymtabLoadCmd || Symtab.nsyms == 0)
2482 return basic_symbol_iterator(SymbolRef(DRI, this));
2484 return getSymbolByIndex(0);
2487 basic_symbol_iterator MachOObjectFile::symbol_end() const {
2489 MachO::symtab_command Symtab = getSymtabLoadCommand();
2490 if (!SymtabLoadCmd || Symtab.nsyms == 0)
2491 return basic_symbol_iterator(SymbolRef(DRI, this));
2493 unsigned SymbolTableEntrySize = is64Bit() ?
2494 sizeof(MachO::nlist_64) :
2495 sizeof(MachO::nlist);
2496 unsigned Offset = Symtab.symoff +
2497 Symtab.nsyms * SymbolTableEntrySize;
2498 DRI.p = reinterpret_cast<uintptr_t>(getPtr(*this, Offset));
2499 return basic_symbol_iterator(SymbolRef(DRI, this));
2502 symbol_iterator MachOObjectFile::getSymbolByIndex(unsigned Index) const {
2503 MachO::symtab_command Symtab = getSymtabLoadCommand();
2504 if (!SymtabLoadCmd || Index >= Symtab.nsyms)
2505 report_fatal_error("Requested symbol index is out of range.");
2506 unsigned SymbolTableEntrySize =
2507 is64Bit() ? sizeof(MachO::nlist_64) : sizeof(MachO::nlist);
2509 DRI.p = reinterpret_cast<uintptr_t>(getPtr(*this, Symtab.symoff));
2510 DRI.p += Index * SymbolTableEntrySize;
2511 return basic_symbol_iterator(SymbolRef(DRI, this));
2514 uint64_t MachOObjectFile::getSymbolIndex(DataRefImpl Symb) const {
2515 MachO::symtab_command Symtab = getSymtabLoadCommand();
2517 report_fatal_error("getSymbolIndex() called with no symbol table symbol");
2518 unsigned SymbolTableEntrySize =
2519 is64Bit() ? sizeof(MachO::nlist_64) : sizeof(MachO::nlist);
2520 DataRefImpl DRIstart;
2521 DRIstart.p = reinterpret_cast<uintptr_t>(getPtr(*this, Symtab.symoff));
2522 uint64_t Index = (Symb.p - DRIstart.p) / SymbolTableEntrySize;
2526 section_iterator MachOObjectFile::section_begin() const {
2528 return section_iterator(SectionRef(DRI, this));
2531 section_iterator MachOObjectFile::section_end() const {
2533 DRI.d.a = Sections.size();
2534 return section_iterator(SectionRef(DRI, this));
2537 uint8_t MachOObjectFile::getBytesInAddress() const {
2538 return is64Bit() ? 8 : 4;
2541 StringRef MachOObjectFile::getFileFormatName() const {
2542 unsigned CPUType = getCPUType(*this);
2545 case MachO::CPU_TYPE_I386:
2546 return "Mach-O 32-bit i386";
2547 case MachO::CPU_TYPE_ARM:
2548 return "Mach-O arm";
2549 case MachO::CPU_TYPE_ARM64_32:
2550 return "Mach-O arm64 (ILP32)";
2551 case MachO::CPU_TYPE_POWERPC:
2552 return "Mach-O 32-bit ppc";
2554 return "Mach-O 32-bit unknown";
2559 case MachO::CPU_TYPE_X86_64:
2560 return "Mach-O 64-bit x86-64";
2561 case MachO::CPU_TYPE_ARM64:
2562 return "Mach-O arm64";
2563 case MachO::CPU_TYPE_POWERPC64:
2564 return "Mach-O 64-bit ppc64";
2566 return "Mach-O 64-bit unknown";
2570 Triple::ArchType MachOObjectFile::getArch(uint32_t CPUType) {
2572 case MachO::CPU_TYPE_I386:
2574 case MachO::CPU_TYPE_X86_64:
2575 return Triple::x86_64;
2576 case MachO::CPU_TYPE_ARM:
2578 case MachO::CPU_TYPE_ARM64:
2579 return Triple::aarch64;
2580 case MachO::CPU_TYPE_ARM64_32:
2581 return Triple::aarch64_32;
2582 case MachO::CPU_TYPE_POWERPC:
2584 case MachO::CPU_TYPE_POWERPC64:
2585 return Triple::ppc64;
2587 return Triple::UnknownArch;
2591 Triple MachOObjectFile::getArchTriple(uint32_t CPUType, uint32_t CPUSubType,
2592 const char **McpuDefault,
2593 const char **ArchFlag) {
2595 *McpuDefault = nullptr;
2597 *ArchFlag = nullptr;
2600 case MachO::CPU_TYPE_I386:
2601 switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2602 case MachO::CPU_SUBTYPE_I386_ALL:
2605 return Triple("i386-apple-darwin");
2609 case MachO::CPU_TYPE_X86_64:
2610 switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2611 case MachO::CPU_SUBTYPE_X86_64_ALL:
2613 *ArchFlag = "x86_64";
2614 return Triple("x86_64-apple-darwin");
2615 case MachO::CPU_SUBTYPE_X86_64_H:
2617 *ArchFlag = "x86_64h";
2618 return Triple("x86_64h-apple-darwin");
2622 case MachO::CPU_TYPE_ARM:
2623 switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2624 case MachO::CPU_SUBTYPE_ARM_V4T:
2626 *ArchFlag = "armv4t";
2627 return Triple("armv4t-apple-darwin");
2628 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
2630 *ArchFlag = "armv5e";
2631 return Triple("armv5e-apple-darwin");
2632 case MachO::CPU_SUBTYPE_ARM_XSCALE:
2634 *ArchFlag = "xscale";
2635 return Triple("xscale-apple-darwin");
2636 case MachO::CPU_SUBTYPE_ARM_V6:
2638 *ArchFlag = "armv6";
2639 return Triple("armv6-apple-darwin");
2640 case MachO::CPU_SUBTYPE_ARM_V6M:
2642 *McpuDefault = "cortex-m0";
2644 *ArchFlag = "armv6m";
2645 return Triple("armv6m-apple-darwin");
2646 case MachO::CPU_SUBTYPE_ARM_V7:
2648 *ArchFlag = "armv7";
2649 return Triple("armv7-apple-darwin");
2650 case MachO::CPU_SUBTYPE_ARM_V7EM:
2652 *McpuDefault = "cortex-m4";
2654 *ArchFlag = "armv7em";
2655 return Triple("thumbv7em-apple-darwin");
2656 case MachO::CPU_SUBTYPE_ARM_V7K:
2658 *McpuDefault = "cortex-a7";
2660 *ArchFlag = "armv7k";
2661 return Triple("armv7k-apple-darwin");
2662 case MachO::CPU_SUBTYPE_ARM_V7M:
2664 *McpuDefault = "cortex-m3";
2666 *ArchFlag = "armv7m";
2667 return Triple("thumbv7m-apple-darwin");
2668 case MachO::CPU_SUBTYPE_ARM_V7S:
2670 *McpuDefault = "cortex-a7";
2672 *ArchFlag = "armv7s";
2673 return Triple("armv7s-apple-darwin");
2677 case MachO::CPU_TYPE_ARM64:
2678 switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2679 case MachO::CPU_SUBTYPE_ARM64_ALL:
2681 *McpuDefault = "cyclone";
2683 *ArchFlag = "arm64";
2684 return Triple("arm64-apple-darwin");
2688 case MachO::CPU_TYPE_ARM64_32:
2689 switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2690 case MachO::CPU_SUBTYPE_ARM64_32_V8:
2692 *McpuDefault = "cyclone";
2694 *ArchFlag = "arm64_32";
2695 return Triple("arm64_32-apple-darwin");
2699 case MachO::CPU_TYPE_POWERPC:
2700 switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2701 case MachO::CPU_SUBTYPE_POWERPC_ALL:
2704 return Triple("ppc-apple-darwin");
2708 case MachO::CPU_TYPE_POWERPC64:
2709 switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2710 case MachO::CPU_SUBTYPE_POWERPC_ALL:
2712 *ArchFlag = "ppc64";
2713 return Triple("ppc64-apple-darwin");
2722 Triple MachOObjectFile::getHostArch() {
2723 return Triple(sys::getDefaultTargetTriple());
2726 bool MachOObjectFile::isValidArch(StringRef ArchFlag) {
2727 return std::find(validArchs.cbegin(), validArchs.cend(), ArchFlag) !=
2731 ArrayRef<StringRef> MachOObjectFile::getValidArchs() { return validArchs; }
2733 Triple::ArchType MachOObjectFile::getArch() const {
2734 return getArch(getCPUType(*this));
2737 Triple MachOObjectFile::getArchTriple(const char **McpuDefault) const {
2738 return getArchTriple(Header.cputype, Header.cpusubtype, McpuDefault);
2741 relocation_iterator MachOObjectFile::section_rel_begin(unsigned Index) const {
2744 return section_rel_begin(DRI);
2747 relocation_iterator MachOObjectFile::section_rel_end(unsigned Index) const {
2750 return section_rel_end(DRI);
2753 dice_iterator MachOObjectFile::begin_dices() const {
2755 if (!DataInCodeLoadCmd)
2756 return dice_iterator(DiceRef(DRI, this));
2758 MachO::linkedit_data_command DicLC = getDataInCodeLoadCommand();
2759 DRI.p = reinterpret_cast<uintptr_t>(getPtr(*this, DicLC.dataoff));
2760 return dice_iterator(DiceRef(DRI, this));
2763 dice_iterator MachOObjectFile::end_dices() const {
2765 if (!DataInCodeLoadCmd)
2766 return dice_iterator(DiceRef(DRI, this));
2768 MachO::linkedit_data_command DicLC = getDataInCodeLoadCommand();
2769 unsigned Offset = DicLC.dataoff + DicLC.datasize;
2770 DRI.p = reinterpret_cast<uintptr_t>(getPtr(*this, Offset));
2771 return dice_iterator(DiceRef(DRI, this));
2774 ExportEntry::ExportEntry(Error *E, const MachOObjectFile *O,
2775 ArrayRef<uint8_t> T) : E(E), O(O), Trie(T) {}
2777 void ExportEntry::moveToFirst() {
2778 ErrorAsOutParameter ErrAsOutParam(E);
2782 pushDownUntilBottom();
2785 void ExportEntry::moveToEnd() {
2790 bool ExportEntry::operator==(const ExportEntry &Other) const {
2791 // Common case, one at end, other iterating from begin.
2792 if (Done || Other.Done)
2793 return (Done == Other.Done);
2794 // Not equal if different stack sizes.
2795 if (Stack.size() != Other.Stack.size())
2797 // Not equal if different cumulative strings.
2798 if (!CumulativeString.equals(Other.CumulativeString))
2800 // Equal if all nodes in both stacks match.
2801 for (unsigned i=0; i < Stack.size(); ++i) {
2802 if (Stack[i].Start != Other.Stack[i].Start)
2808 uint64_t ExportEntry::readULEB128(const uint8_t *&Ptr, const char **error) {
2810 uint64_t Result = decodeULEB128(Ptr, &Count, Trie.end(), error);
2812 if (Ptr > Trie.end())
2817 StringRef ExportEntry::name() const {
2818 return CumulativeString;
2821 uint64_t ExportEntry::flags() const {
2822 return Stack.back().Flags;
2825 uint64_t ExportEntry::address() const {
2826 return Stack.back().Address;
2829 uint64_t ExportEntry::other() const {
2830 return Stack.back().Other;
2833 StringRef ExportEntry::otherName() const {
2834 const char* ImportName = Stack.back().ImportName;
2836 return StringRef(ImportName);
2840 uint32_t ExportEntry::nodeOffset() const {
2841 return Stack.back().Start - Trie.begin();
2844 ExportEntry::NodeState::NodeState(const uint8_t *Ptr)
2845 : Start(Ptr), Current(Ptr) {}
2847 void ExportEntry::pushNode(uint64_t offset) {
2848 ErrorAsOutParameter ErrAsOutParam(E);
2849 const uint8_t *Ptr = Trie.begin() + offset;
2850 NodeState State(Ptr);
2852 uint64_t ExportInfoSize = readULEB128(State.Current, &error);
2854 *E = malformedError("export info size " + Twine(error) +
2855 " in export trie data at node: 0x" +
2856 Twine::utohexstr(offset));
2860 State.IsExportNode = (ExportInfoSize != 0);
2861 const uint8_t* Children = State.Current + ExportInfoSize;
2862 if (Children > Trie.end()) {
2863 *E = malformedError(
2864 "export info size: 0x" + Twine::utohexstr(ExportInfoSize) +
2865 " in export trie data at node: 0x" + Twine::utohexstr(offset) +
2866 " too big and extends past end of trie data");
2870 if (State.IsExportNode) {
2871 const uint8_t *ExportStart = State.Current;
2872 State.Flags = readULEB128(State.Current, &error);
2874 *E = malformedError("flags " + Twine(error) +
2875 " in export trie data at node: 0x" +
2876 Twine::utohexstr(offset));
2880 uint64_t Kind = State.Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK;
2881 if (State.Flags != 0 &&
2882 (Kind != MachO::EXPORT_SYMBOL_FLAGS_KIND_REGULAR &&
2883 Kind != MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE &&
2884 Kind != MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL)) {
2885 *E = malformedError(
2886 "unsupported exported symbol kind: " + Twine((int)Kind) +
2887 " in flags: 0x" + Twine::utohexstr(State.Flags) +
2888 " in export trie data at node: 0x" + Twine::utohexstr(offset));
2892 if (State.Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT) {
2894 State.Other = readULEB128(State.Current, &error); // dylib ordinal
2896 *E = malformedError("dylib ordinal of re-export " + Twine(error) +
2897 " in export trie data at node: 0x" +
2898 Twine::utohexstr(offset));
2903 if (State.Other > O->getLibraryCount()) {
2904 *E = malformedError(
2905 "bad library ordinal: " + Twine((int)State.Other) + " (max " +
2906 Twine((int)O->getLibraryCount()) +
2907 ") in export trie data at node: 0x" + Twine::utohexstr(offset));
2912 State.ImportName = reinterpret_cast<const char*>(State.Current);
2913 if (*State.ImportName == '\0') {
2916 const uint8_t *End = State.Current + 1;
2917 if (End >= Trie.end()) {
2918 *E = malformedError("import name of re-export in export trie data at "
2920 Twine::utohexstr(offset) +
2921 " starts past end of trie data");
2925 while(*End != '\0' && End < Trie.end())
2928 *E = malformedError("import name of re-export in export trie data at "
2930 Twine::utohexstr(offset) +
2931 " extends past end of trie data");
2935 State.Current = End + 1;
2938 State.Address = readULEB128(State.Current, &error);
2940 *E = malformedError("address " + Twine(error) +
2941 " in export trie data at node: 0x" +
2942 Twine::utohexstr(offset));
2946 if (State.Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER) {
2947 State.Other = readULEB128(State.Current, &error);
2949 *E = malformedError("resolver of stub and resolver " + Twine(error) +
2950 " in export trie data at node: 0x" +
2951 Twine::utohexstr(offset));
2957 if(ExportStart + ExportInfoSize != State.Current) {
2958 *E = malformedError(
2959 "inconsistant export info size: 0x" +
2960 Twine::utohexstr(ExportInfoSize) + " where actual size was: 0x" +
2961 Twine::utohexstr(State.Current - ExportStart) +
2962 " in export trie data at node: 0x" + Twine::utohexstr(offset));
2967 State.ChildCount = *Children;
2968 if (State.ChildCount != 0 && Children + 1 >= Trie.end()) {
2969 *E = malformedError("byte for count of childern in export trie data at "
2971 Twine::utohexstr(offset) +
2972 " extends past end of trie data");
2976 State.Current = Children + 1;
2977 State.NextChildIndex = 0;
2978 State.ParentStringLength = CumulativeString.size();
2979 Stack.push_back(State);
2982 void ExportEntry::pushDownUntilBottom() {
2983 ErrorAsOutParameter ErrAsOutParam(E);
2985 while (Stack.back().NextChildIndex < Stack.back().ChildCount) {
2986 NodeState &Top = Stack.back();
2987 CumulativeString.resize(Top.ParentStringLength);
2988 for (;*Top.Current != 0 && Top.Current < Trie.end(); Top.Current++) {
2989 char C = *Top.Current;
2990 CumulativeString.push_back(C);
2992 if (Top.Current >= Trie.end()) {
2993 *E = malformedError("edge sub-string in export trie data at node: 0x" +
2994 Twine::utohexstr(Top.Start - Trie.begin()) +
2995 " for child #" + Twine((int)Top.NextChildIndex) +
2996 " extends past end of trie data");
3001 uint64_t childNodeIndex = readULEB128(Top.Current, &error);
3003 *E = malformedError("child node offset " + Twine(error) +
3004 " in export trie data at node: 0x" +
3005 Twine::utohexstr(Top.Start - Trie.begin()));
3009 for (const NodeState &node : nodes()) {
3010 if (node.Start == Trie.begin() + childNodeIndex){
3011 *E = malformedError("loop in childern in export trie data at node: 0x" +
3012 Twine::utohexstr(Top.Start - Trie.begin()) +
3013 " back to node: 0x" +
3014 Twine::utohexstr(childNodeIndex));
3019 Top.NextChildIndex += 1;
3020 pushNode(childNodeIndex);
3024 if (!Stack.back().IsExportNode) {
3025 *E = malformedError("node is not an export node in export trie data at "
3027 Twine::utohexstr(Stack.back().Start - Trie.begin()));
3033 // We have a trie data structure and need a way to walk it that is compatible
3034 // with the C++ iterator model. The solution is a non-recursive depth first
3035 // traversal where the iterator contains a stack of parent nodes along with a
3036 // string that is the accumulation of all edge strings along the parent chain
3039 // There is one "export" node for each exported symbol. But because some
3040 // symbols may be a prefix of another symbol (e.g. _dup and _dup2), an export
3041 // node may have child nodes too.
3043 // The algorithm for moveNext() is to keep moving down the leftmost unvisited
3044 // child until hitting a node with no children (which is an export node or
3045 // else the trie is malformed). On the way down, each node is pushed on the
3046 // stack ivar. If there is no more ways down, it pops up one and tries to go
3047 // down a sibling path until a childless node is reached.
3048 void ExportEntry::moveNext() {
3049 assert(!Stack.empty() && "ExportEntry::moveNext() with empty node stack");
3050 if (!Stack.back().IsExportNode) {
3051 *E = malformedError("node is not an export node in export trie data at "
3053 Twine::utohexstr(Stack.back().Start - Trie.begin()));
3059 while (!Stack.empty()) {
3060 NodeState &Top = Stack.back();
3061 if (Top.NextChildIndex < Top.ChildCount) {
3062 pushDownUntilBottom();
3063 // Now at the next export node.
3066 if (Top.IsExportNode) {
3067 // This node has no children but is itself an export node.
3068 CumulativeString.resize(Top.ParentStringLength);
3077 iterator_range<export_iterator>
3078 MachOObjectFile::exports(Error &E, ArrayRef<uint8_t> Trie,
3079 const MachOObjectFile *O) {
3080 ExportEntry Start(&E, O, Trie);
3084 Start.moveToFirst();
3086 ExportEntry Finish(&E, O, Trie);
3089 return make_range(export_iterator(Start), export_iterator(Finish));
3092 iterator_range<export_iterator> MachOObjectFile::exports(Error &Err) const {
3093 return exports(Err, getDyldInfoExportsTrie(), this);
3096 MachORebaseEntry::MachORebaseEntry(Error *E, const MachOObjectFile *O,
3097 ArrayRef<uint8_t> Bytes, bool is64Bit)
3098 : E(E), O(O), Opcodes(Bytes), Ptr(Bytes.begin()),
3099 PointerSize(is64Bit ? 8 : 4) {}
3101 void MachORebaseEntry::moveToFirst() {
3102 Ptr = Opcodes.begin();
3106 void MachORebaseEntry::moveToEnd() {
3107 Ptr = Opcodes.end();
3108 RemainingLoopCount = 0;
3112 void MachORebaseEntry::moveNext() {
3113 ErrorAsOutParameter ErrAsOutParam(E);
3114 // If in the middle of some loop, move to next rebasing in loop.
3115 SegmentOffset += AdvanceAmount;
3116 if (RemainingLoopCount) {
3117 --RemainingLoopCount;
3120 // REBASE_OPCODE_DONE is only used for padding if we are not aligned to
3121 // pointer size. Therefore it is possible to reach the end without ever having
3122 // seen REBASE_OPCODE_DONE.
3123 if (Ptr == Opcodes.end()) {
3129 // Parse next opcode and set up next loop.
3130 const uint8_t *OpcodeStart = Ptr;
3131 uint8_t Byte = *Ptr++;
3132 uint8_t ImmValue = Byte & MachO::REBASE_IMMEDIATE_MASK;
3133 uint8_t Opcode = Byte & MachO::REBASE_OPCODE_MASK;
3134 uint32_t Count, Skip;
3135 const char *error = nullptr;
3137 case MachO::REBASE_OPCODE_DONE:
3141 DEBUG_WITH_TYPE("mach-o-rebase", dbgs() << "REBASE_OPCODE_DONE\n");
3143 case MachO::REBASE_OPCODE_SET_TYPE_IMM:
3144 RebaseType = ImmValue;
3145 if (RebaseType > MachO::REBASE_TYPE_TEXT_PCREL32) {
3146 *E = malformedError("for REBASE_OPCODE_SET_TYPE_IMM bad bind type: " +
3147 Twine((int)RebaseType) + " for opcode at: 0x" +
3148 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3154 dbgs() << "REBASE_OPCODE_SET_TYPE_IMM: "
3155 << "RebaseType=" << (int) RebaseType << "\n");
3157 case MachO::REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB:
3158 SegmentIndex = ImmValue;
3159 SegmentOffset = readULEB128(&error);
3161 *E = malformedError("for REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB " +
3162 Twine(error) + " for opcode at: 0x" +
3163 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3167 error = O->RebaseEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3170 *E = malformedError("for REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB " +
3171 Twine(error) + " for opcode at: 0x" +
3172 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3178 dbgs() << "REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB: "
3179 << "SegmentIndex=" << SegmentIndex << ", "
3180 << format("SegmentOffset=0x%06X", SegmentOffset)
3183 case MachO::REBASE_OPCODE_ADD_ADDR_ULEB:
3184 SegmentOffset += readULEB128(&error);
3186 *E = malformedError("for REBASE_OPCODE_ADD_ADDR_ULEB " + Twine(error) +
3187 " for opcode at: 0x" +
3188 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3192 error = O->RebaseEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3195 *E = malformedError("for REBASE_OPCODE_ADD_ADDR_ULEB " + Twine(error) +
3196 " for opcode at: 0x" +
3197 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3201 DEBUG_WITH_TYPE("mach-o-rebase",
3202 dbgs() << "REBASE_OPCODE_ADD_ADDR_ULEB: "
3203 << format("SegmentOffset=0x%06X",
3204 SegmentOffset) << "\n");
3206 case MachO::REBASE_OPCODE_ADD_ADDR_IMM_SCALED:
3207 error = O->RebaseEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3210 *E = malformedError("for REBASE_OPCODE_ADD_ADDR_IMM_SCALED " +
3211 Twine(error) + " for opcode at: 0x" +
3212 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3216 SegmentOffset += ImmValue * PointerSize;
3217 error = O->RebaseEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3221 malformedError("for REBASE_OPCODE_ADD_ADDR_IMM_SCALED "
3222 " (after adding immediate times the pointer size) " +
3223 Twine(error) + " for opcode at: 0x" +
3224 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3228 DEBUG_WITH_TYPE("mach-o-rebase",
3229 dbgs() << "REBASE_OPCODE_ADD_ADDR_IMM_SCALED: "
3230 << format("SegmentOffset=0x%06X",
3231 SegmentOffset) << "\n");
3233 case MachO::REBASE_OPCODE_DO_REBASE_IMM_TIMES:
3234 AdvanceAmount = PointerSize;
3238 RemainingLoopCount = ImmValue - 1;
3240 RemainingLoopCount = 0;
3241 error = O->RebaseEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3242 PointerSize, Count, Skip);
3244 *E = malformedError("for REBASE_OPCODE_DO_REBASE_IMM_TIMES " +
3245 Twine(error) + " for opcode at: 0x" +
3246 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3252 dbgs() << "REBASE_OPCODE_DO_REBASE_IMM_TIMES: "
3253 << format("SegmentOffset=0x%06X", SegmentOffset)
3254 << ", AdvanceAmount=" << AdvanceAmount
3255 << ", RemainingLoopCount=" << RemainingLoopCount
3258 case MachO::REBASE_OPCODE_DO_REBASE_ULEB_TIMES:
3259 AdvanceAmount = PointerSize;
3261 Count = readULEB128(&error);
3263 *E = malformedError("for REBASE_OPCODE_DO_REBASE_ULEB_TIMES " +
3264 Twine(error) + " for opcode at: 0x" +
3265 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3270 RemainingLoopCount = Count - 1;
3272 RemainingLoopCount = 0;
3273 error = O->RebaseEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3274 PointerSize, Count, Skip);
3276 *E = malformedError("for REBASE_OPCODE_DO_REBASE_ULEB_TIMES " +
3277 Twine(error) + " for opcode at: 0x" +
3278 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3284 dbgs() << "REBASE_OPCODE_DO_REBASE_ULEB_TIMES: "
3285 << format("SegmentOffset=0x%06X", SegmentOffset)
3286 << ", AdvanceAmount=" << AdvanceAmount
3287 << ", RemainingLoopCount=" << RemainingLoopCount
3290 case MachO::REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB:
3291 Skip = readULEB128(&error);
3293 *E = malformedError("for REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB " +
3294 Twine(error) + " for opcode at: 0x" +
3295 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3299 AdvanceAmount = Skip + PointerSize;
3301 RemainingLoopCount = 0;
3302 error = O->RebaseEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3303 PointerSize, Count, Skip);
3305 *E = malformedError("for REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB " +
3306 Twine(error) + " for opcode at: 0x" +
3307 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3313 dbgs() << "REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB: "
3314 << format("SegmentOffset=0x%06X", SegmentOffset)
3315 << ", AdvanceAmount=" << AdvanceAmount
3316 << ", RemainingLoopCount=" << RemainingLoopCount
3319 case MachO::REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB:
3320 Count = readULEB128(&error);
3322 *E = malformedError("for REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_"
3324 Twine(error) + " for opcode at: 0x" +
3325 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3330 RemainingLoopCount = Count - 1;
3332 RemainingLoopCount = 0;
3333 Skip = readULEB128(&error);
3335 *E = malformedError("for REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_"
3337 Twine(error) + " for opcode at: 0x" +
3338 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3342 AdvanceAmount = Skip + PointerSize;
3344 error = O->RebaseEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3345 PointerSize, Count, Skip);
3347 *E = malformedError("for REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_"
3349 Twine(error) + " for opcode at: 0x" +
3350 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3356 dbgs() << "REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB: "
3357 << format("SegmentOffset=0x%06X", SegmentOffset)
3358 << ", AdvanceAmount=" << AdvanceAmount
3359 << ", RemainingLoopCount=" << RemainingLoopCount
3363 *E = malformedError("bad rebase info (bad opcode value 0x" +
3364 Twine::utohexstr(Opcode) + " for opcode at: 0x" +
3365 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3372 uint64_t MachORebaseEntry::readULEB128(const char **error) {
3374 uint64_t Result = decodeULEB128(Ptr, &Count, Opcodes.end(), error);
3376 if (Ptr > Opcodes.end())
3377 Ptr = Opcodes.end();
3381 int32_t MachORebaseEntry::segmentIndex() const { return SegmentIndex; }
3383 uint64_t MachORebaseEntry::segmentOffset() const { return SegmentOffset; }
3385 StringRef MachORebaseEntry::typeName() const {
3386 switch (RebaseType) {
3387 case MachO::REBASE_TYPE_POINTER:
3389 case MachO::REBASE_TYPE_TEXT_ABSOLUTE32:
3390 return "text abs32";
3391 case MachO::REBASE_TYPE_TEXT_PCREL32:
3392 return "text rel32";
3397 // For use with the SegIndex of a checked Mach-O Rebase entry
3398 // to get the segment name.
3399 StringRef MachORebaseEntry::segmentName() const {
3400 return O->BindRebaseSegmentName(SegmentIndex);
3403 // For use with a SegIndex,SegOffset pair from a checked Mach-O Rebase entry
3404 // to get the section name.
3405 StringRef MachORebaseEntry::sectionName() const {
3406 return O->BindRebaseSectionName(SegmentIndex, SegmentOffset);
3409 // For use with a SegIndex,SegOffset pair from a checked Mach-O Rebase entry
3410 // to get the address.
3411 uint64_t MachORebaseEntry::address() const {
3412 return O->BindRebaseAddress(SegmentIndex, SegmentOffset);
3415 bool MachORebaseEntry::operator==(const MachORebaseEntry &Other) const {
3416 #ifdef EXPENSIVE_CHECKS
3417 assert(Opcodes == Other.Opcodes && "compare iterators of different files");
3419 assert(Opcodes.data() == Other.Opcodes.data() && "compare iterators of different files");
3421 return (Ptr == Other.Ptr) &&
3422 (RemainingLoopCount == Other.RemainingLoopCount) &&
3423 (Done == Other.Done);
3426 iterator_range<rebase_iterator>
3427 MachOObjectFile::rebaseTable(Error &Err, MachOObjectFile *O,
3428 ArrayRef<uint8_t> Opcodes, bool is64) {
3429 if (O->BindRebaseSectionTable == nullptr)
3430 O->BindRebaseSectionTable = llvm::make_unique<BindRebaseSegInfo>(O);
3431 MachORebaseEntry Start(&Err, O, Opcodes, is64);
3432 Start.moveToFirst();
3434 MachORebaseEntry Finish(&Err, O, Opcodes, is64);
3437 return make_range(rebase_iterator(Start), rebase_iterator(Finish));
3440 iterator_range<rebase_iterator> MachOObjectFile::rebaseTable(Error &Err) {
3441 return rebaseTable(Err, this, getDyldInfoRebaseOpcodes(), is64Bit());
3444 MachOBindEntry::MachOBindEntry(Error *E, const MachOObjectFile *O,
3445 ArrayRef<uint8_t> Bytes, bool is64Bit, Kind BK)
3446 : E(E), O(O), Opcodes(Bytes), Ptr(Bytes.begin()),
3447 PointerSize(is64Bit ? 8 : 4), TableKind(BK) {}
3449 void MachOBindEntry::moveToFirst() {
3450 Ptr = Opcodes.begin();
3454 void MachOBindEntry::moveToEnd() {
3455 Ptr = Opcodes.end();
3456 RemainingLoopCount = 0;
3460 void MachOBindEntry::moveNext() {
3461 ErrorAsOutParameter ErrAsOutParam(E);
3462 // If in the middle of some loop, move to next binding in loop.
3463 SegmentOffset += AdvanceAmount;
3464 if (RemainingLoopCount) {
3465 --RemainingLoopCount;
3468 // BIND_OPCODE_DONE is only used for padding if we are not aligned to
3469 // pointer size. Therefore it is possible to reach the end without ever having
3470 // seen BIND_OPCODE_DONE.
3471 if (Ptr == Opcodes.end()) {
3477 // Parse next opcode and set up next loop.
3478 const uint8_t *OpcodeStart = Ptr;
3479 uint8_t Byte = *Ptr++;
3480 uint8_t ImmValue = Byte & MachO::BIND_IMMEDIATE_MASK;
3481 uint8_t Opcode = Byte & MachO::BIND_OPCODE_MASK;
3482 int8_t SignExtended;
3483 const uint8_t *SymStart;
3484 uint32_t Count, Skip;
3485 const char *error = nullptr;
3487 case MachO::BIND_OPCODE_DONE:
3488 if (TableKind == Kind::Lazy) {
3489 // Lazying bindings have a DONE opcode between entries. Need to ignore
3490 // it to advance to next entry. But need not if this is last entry.
3491 bool NotLastEntry = false;
3492 for (const uint8_t *P = Ptr; P < Opcodes.end(); ++P) {
3494 NotLastEntry = true;
3502 DEBUG_WITH_TYPE("mach-o-bind", dbgs() << "BIND_OPCODE_DONE\n");
3504 case MachO::BIND_OPCODE_SET_DYLIB_ORDINAL_IMM:
3505 if (TableKind == Kind::Weak) {
3506 *E = malformedError("BIND_OPCODE_SET_DYLIB_ORDINAL_IMM not allowed in "
3507 "weak bind table for opcode at: 0x" +
3508 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3513 LibraryOrdinalSet = true;
3514 if (ImmValue > O->getLibraryCount()) {
3515 *E = malformedError("for BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB bad "
3516 "library ordinal: " +
3517 Twine((int)ImmValue) + " (max " +
3518 Twine((int)O->getLibraryCount()) +
3519 ") for opcode at: 0x" +
3520 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3526 dbgs() << "BIND_OPCODE_SET_DYLIB_ORDINAL_IMM: "
3527 << "Ordinal=" << Ordinal << "\n");
3529 case MachO::BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB:
3530 if (TableKind == Kind::Weak) {
3531 *E = malformedError("BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB not allowed in "
3532 "weak bind table for opcode at: 0x" +
3533 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3537 Ordinal = readULEB128(&error);
3538 LibraryOrdinalSet = true;
3540 *E = malformedError("for BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB " +
3541 Twine(error) + " for opcode at: 0x" +
3542 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3546 if (Ordinal > (int)O->getLibraryCount()) {
3547 *E = malformedError("for BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB bad "
3548 "library ordinal: " +
3549 Twine((int)Ordinal) + " (max " +
3550 Twine((int)O->getLibraryCount()) +
3551 ") for opcode at: 0x" +
3552 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3558 dbgs() << "BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB: "
3559 << "Ordinal=" << Ordinal << "\n");
3561 case MachO::BIND_OPCODE_SET_DYLIB_SPECIAL_IMM:
3562 if (TableKind == Kind::Weak) {
3563 *E = malformedError("BIND_OPCODE_SET_DYLIB_SPECIAL_IMM not allowed in "
3564 "weak bind table for opcode at: 0x" +
3565 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3570 SignExtended = MachO::BIND_OPCODE_MASK | ImmValue;
3571 Ordinal = SignExtended;
3572 if (Ordinal < MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP) {
3573 *E = malformedError("for BIND_OPCODE_SET_DYLIB_SPECIAL_IMM unknown "
3574 "special ordinal: " +
3575 Twine((int)Ordinal) + " for opcode at: 0x" +
3576 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3582 LibraryOrdinalSet = true;
3585 dbgs() << "BIND_OPCODE_SET_DYLIB_SPECIAL_IMM: "
3586 << "Ordinal=" << Ordinal << "\n");
3588 case MachO::BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM:
3591 while (*Ptr && (Ptr < Opcodes.end())) {
3594 if (Ptr == Opcodes.end()) {
3595 *E = malformedError(
3596 "for BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM "
3597 "symbol name extends past opcodes for opcode at: 0x" +
3598 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3602 SymbolName = StringRef(reinterpret_cast<const char*>(SymStart),
3607 dbgs() << "BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM: "
3608 << "SymbolName=" << SymbolName << "\n");
3609 if (TableKind == Kind::Weak) {
3610 if (ImmValue & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION)
3614 case MachO::BIND_OPCODE_SET_TYPE_IMM:
3615 BindType = ImmValue;
3616 if (ImmValue > MachO::BIND_TYPE_TEXT_PCREL32) {
3617 *E = malformedError("for BIND_OPCODE_SET_TYPE_IMM bad bind type: " +
3618 Twine((int)ImmValue) + " for opcode at: 0x" +
3619 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3625 dbgs() << "BIND_OPCODE_SET_TYPE_IMM: "
3626 << "BindType=" << (int)BindType << "\n");
3628 case MachO::BIND_OPCODE_SET_ADDEND_SLEB:
3629 Addend = readSLEB128(&error);
3631 *E = malformedError("for BIND_OPCODE_SET_ADDEND_SLEB " + Twine(error) +
3632 " for opcode at: 0x" +
3633 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3639 dbgs() << "BIND_OPCODE_SET_ADDEND_SLEB: "
3640 << "Addend=" << Addend << "\n");
3642 case MachO::BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB:
3643 SegmentIndex = ImmValue;
3644 SegmentOffset = readULEB128(&error);
3646 *E = malformedError("for BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB " +
3647 Twine(error) + " for opcode at: 0x" +
3648 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3652 error = O->BindEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3655 *E = malformedError("for BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB " +
3656 Twine(error) + " for opcode at: 0x" +
3657 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3663 dbgs() << "BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB: "
3664 << "SegmentIndex=" << SegmentIndex << ", "
3665 << format("SegmentOffset=0x%06X", SegmentOffset)
3668 case MachO::BIND_OPCODE_ADD_ADDR_ULEB:
3669 SegmentOffset += readULEB128(&error);
3671 *E = malformedError("for BIND_OPCODE_ADD_ADDR_ULEB " + Twine(error) +
3672 " for opcode at: 0x" +
3673 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3677 error = O->BindEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3680 *E = malformedError("for BIND_OPCODE_ADD_ADDR_ULEB " + Twine(error) +
3681 " for opcode at: 0x" +
3682 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3686 DEBUG_WITH_TYPE("mach-o-bind",
3687 dbgs() << "BIND_OPCODE_ADD_ADDR_ULEB: "
3688 << format("SegmentOffset=0x%06X",
3689 SegmentOffset) << "\n");
3691 case MachO::BIND_OPCODE_DO_BIND:
3692 AdvanceAmount = PointerSize;
3693 RemainingLoopCount = 0;
3694 error = O->BindEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3697 *E = malformedError("for BIND_OPCODE_DO_BIND " + Twine(error) +
3698 " for opcode at: 0x" +
3699 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3703 if (SymbolName == StringRef()) {
3704 *E = malformedError(
3705 "for BIND_OPCODE_DO_BIND missing preceding "
3706 "BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM for opcode at: 0x" +
3707 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3711 if (!LibraryOrdinalSet && TableKind != Kind::Weak) {
3713 malformedError("for BIND_OPCODE_DO_BIND missing preceding "
3714 "BIND_OPCODE_SET_DYLIB_ORDINAL_* for opcode at: 0x" +
3715 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3719 DEBUG_WITH_TYPE("mach-o-bind",
3720 dbgs() << "BIND_OPCODE_DO_BIND: "
3721 << format("SegmentOffset=0x%06X",
3722 SegmentOffset) << "\n");
3724 case MachO::BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB:
3725 if (TableKind == Kind::Lazy) {
3726 *E = malformedError("BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB not allowed in "
3727 "lazy bind table for opcode at: 0x" +
3728 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3732 error = O->BindEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3735 *E = malformedError("for BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB " +
3736 Twine(error) + " for opcode at: 0x" +
3737 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3741 if (SymbolName == StringRef()) {
3742 *E = malformedError(
3743 "for BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB missing "
3744 "preceding BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM for opcode "
3746 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3750 if (!LibraryOrdinalSet && TableKind != Kind::Weak) {
3751 *E = malformedError(
3752 "for BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB missing "
3753 "preceding BIND_OPCODE_SET_DYLIB_ORDINAL_* for opcode at: 0x" +
3754 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3758 AdvanceAmount = readULEB128(&error) + PointerSize;
3760 *E = malformedError("for BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB " +
3761 Twine(error) + " for opcode at: 0x" +
3762 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3766 // Note, this is not really an error until the next bind but make no sense
3767 // for a BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB to not be followed by another
3769 error = O->BindEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset +
3770 AdvanceAmount, PointerSize);
3772 *E = malformedError("for BIND_OPCODE_ADD_ADDR_ULEB (after adding "
3774 Twine(error) + " for opcode at: 0x" +
3775 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3779 RemainingLoopCount = 0;
3782 dbgs() << "BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB: "
3783 << format("SegmentOffset=0x%06X", SegmentOffset)
3784 << ", AdvanceAmount=" << AdvanceAmount
3785 << ", RemainingLoopCount=" << RemainingLoopCount
3788 case MachO::BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED:
3789 if (TableKind == Kind::Lazy) {
3790 *E = malformedError("BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED not "
3791 "allowed in lazy bind table for opcode at: 0x" +
3792 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3796 error = O->BindEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3799 *E = malformedError("for BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED " +
3800 Twine(error) + " for opcode at: 0x" +
3801 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3805 if (SymbolName == StringRef()) {
3806 *E = malformedError(
3807 "for BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED "
3808 "missing preceding BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM for "
3810 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3814 if (!LibraryOrdinalSet && TableKind != Kind::Weak) {
3815 *E = malformedError(
3816 "for BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED "
3817 "missing preceding BIND_OPCODE_SET_DYLIB_ORDINAL_* for opcode "
3819 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3823 AdvanceAmount = ImmValue * PointerSize + PointerSize;
3824 RemainingLoopCount = 0;
3825 error = O->BindEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset +
3826 AdvanceAmount, PointerSize);
3829 malformedError("for BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED "
3830 " (after adding immediate times the pointer size) " +
3831 Twine(error) + " for opcode at: 0x" +
3832 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3836 DEBUG_WITH_TYPE("mach-o-bind",
3838 << "BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED: "
3839 << format("SegmentOffset=0x%06X", SegmentOffset) << "\n");
3841 case MachO::BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB:
3842 if (TableKind == Kind::Lazy) {
3843 *E = malformedError("BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB not "
3844 "allowed in lazy bind table for opcode at: 0x" +
3845 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3849 Count = readULEB128(&error);
3851 RemainingLoopCount = Count - 1;
3853 RemainingLoopCount = 0;
3855 *E = malformedError("for BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB "
3857 Twine(error) + " for opcode at: 0x" +
3858 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3862 Skip = readULEB128(&error);
3863 AdvanceAmount = Skip + PointerSize;
3865 *E = malformedError("for BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB "
3867 Twine(error) + " for opcode at: 0x" +
3868 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3872 if (SymbolName == StringRef()) {
3873 *E = malformedError(
3874 "for BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB "
3875 "missing preceding BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM for "
3877 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3881 if (!LibraryOrdinalSet && TableKind != Kind::Weak) {
3882 *E = malformedError(
3883 "for BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB "
3884 "missing preceding BIND_OPCODE_SET_DYLIB_ORDINAL_* for opcode "
3886 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3890 error = O->BindEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3891 PointerSize, Count, Skip);
3894 malformedError("for BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB " +
3895 Twine(error) + " for opcode at: 0x" +
3896 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3902 dbgs() << "BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB: "
3903 << format("SegmentOffset=0x%06X", SegmentOffset)
3904 << ", AdvanceAmount=" << AdvanceAmount
3905 << ", RemainingLoopCount=" << RemainingLoopCount
3909 *E = malformedError("bad bind info (bad opcode value 0x" +
3910 Twine::utohexstr(Opcode) + " for opcode at: 0x" +
3911 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3918 uint64_t MachOBindEntry::readULEB128(const char **error) {
3920 uint64_t Result = decodeULEB128(Ptr, &Count, Opcodes.end(), error);
3922 if (Ptr > Opcodes.end())
3923 Ptr = Opcodes.end();
3927 int64_t MachOBindEntry::readSLEB128(const char **error) {
3929 int64_t Result = decodeSLEB128(Ptr, &Count, Opcodes.end(), error);
3931 if (Ptr > Opcodes.end())
3932 Ptr = Opcodes.end();
3936 int32_t MachOBindEntry::segmentIndex() const { return SegmentIndex; }
3938 uint64_t MachOBindEntry::segmentOffset() const { return SegmentOffset; }
3940 StringRef MachOBindEntry::typeName() const {
3942 case MachO::BIND_TYPE_POINTER:
3944 case MachO::BIND_TYPE_TEXT_ABSOLUTE32:
3945 return "text abs32";
3946 case MachO::BIND_TYPE_TEXT_PCREL32:
3947 return "text rel32";
3952 StringRef MachOBindEntry::symbolName() const { return SymbolName; }
3954 int64_t MachOBindEntry::addend() const { return Addend; }
3956 uint32_t MachOBindEntry::flags() const { return Flags; }
3958 int MachOBindEntry::ordinal() const { return Ordinal; }
3960 // For use with the SegIndex of a checked Mach-O Bind entry
3961 // to get the segment name.
3962 StringRef MachOBindEntry::segmentName() const {
3963 return O->BindRebaseSegmentName(SegmentIndex);
3966 // For use with a SegIndex,SegOffset pair from a checked Mach-O Bind entry
3967 // to get the section name.
3968 StringRef MachOBindEntry::sectionName() const {
3969 return O->BindRebaseSectionName(SegmentIndex, SegmentOffset);
3972 // For use with a SegIndex,SegOffset pair from a checked Mach-O Bind entry
3973 // to get the address.
3974 uint64_t MachOBindEntry::address() const {
3975 return O->BindRebaseAddress(SegmentIndex, SegmentOffset);
3978 bool MachOBindEntry::operator==(const MachOBindEntry &Other) const {
3979 #ifdef EXPENSIVE_CHECKS
3980 assert(Opcodes == Other.Opcodes && "compare iterators of different files");
3982 assert(Opcodes.data() == Other.Opcodes.data() && "compare iterators of different files");
3984 return (Ptr == Other.Ptr) &&
3985 (RemainingLoopCount == Other.RemainingLoopCount) &&
3986 (Done == Other.Done);
3989 // Build table of sections so SegIndex/SegOffset pairs can be translated.
3990 BindRebaseSegInfo::BindRebaseSegInfo(const object::MachOObjectFile *Obj) {
3991 uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
3992 StringRef CurSegName;
3993 uint64_t CurSegAddress;
3994 for (const SectionRef &Section : Obj->sections()) {
3996 Section.getName(Info.SectionName);
3997 Info.Address = Section.getAddress();
3998 Info.Size = Section.getSize();
4000 Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
4001 if (!Info.SegmentName.equals(CurSegName)) {
4003 CurSegName = Info.SegmentName;
4004 CurSegAddress = Info.Address;
4006 Info.SegmentIndex = CurSegIndex - 1;
4007 Info.OffsetInSegment = Info.Address - CurSegAddress;
4008 Info.SegmentStartAddress = CurSegAddress;
4009 Sections.push_back(Info);
4011 MaxSegIndex = CurSegIndex;
4014 // For use with a SegIndex, SegOffset, and PointerSize triple in
4015 // MachOBindEntry::moveNext() to validate a MachOBindEntry or MachORebaseEntry.
4017 // Given a SegIndex, SegOffset, and PointerSize, verify a valid section exists
4018 // that fully contains a pointer at that location. Multiple fixups in a bind
4019 // (such as with the BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB opcode) can
4020 // be tested via the Count and Skip parameters.
4021 const char * BindRebaseSegInfo::checkSegAndOffsets(int32_t SegIndex,
4023 uint8_t PointerSize,
4027 return "missing preceding *_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB";
4028 if (SegIndex >= MaxSegIndex)
4029 return "bad segIndex (too large)";
4030 for (uint32_t i = 0; i < Count; ++i) {
4031 uint32_t Start = SegOffset + i * (PointerSize + Skip);
4032 uint32_t End = Start + PointerSize;
4034 for (const SectionInfo &SI : Sections) {
4035 if (SI.SegmentIndex != SegIndex)
4037 if ((SI.OffsetInSegment<=Start) && (Start<(SI.OffsetInSegment+SI.Size))) {
4038 if (End <= SI.OffsetInSegment + SI.Size) {
4043 return "bad offset, extends beyond section boundary";
4047 return "bad offset, not in section";
4052 // For use with the SegIndex of a checked Mach-O Bind or Rebase entry
4053 // to get the segment name.
4054 StringRef BindRebaseSegInfo::segmentName(int32_t SegIndex) {
4055 for (const SectionInfo &SI : Sections) {
4056 if (SI.SegmentIndex == SegIndex)
4057 return SI.SegmentName;
4059 llvm_unreachable("invalid SegIndex");
4062 // For use with a SegIndex,SegOffset pair from a checked Mach-O Bind or Rebase
4063 // to get the SectionInfo.
4064 const BindRebaseSegInfo::SectionInfo &BindRebaseSegInfo::findSection(
4065 int32_t SegIndex, uint64_t SegOffset) {
4066 for (const SectionInfo &SI : Sections) {
4067 if (SI.SegmentIndex != SegIndex)
4069 if (SI.OffsetInSegment > SegOffset)
4071 if (SegOffset >= (SI.OffsetInSegment + SI.Size))
4075 llvm_unreachable("SegIndex and SegOffset not in any section");
4078 // For use with a SegIndex,SegOffset pair from a checked Mach-O Bind or Rebase
4079 // entry to get the section name.
4080 StringRef BindRebaseSegInfo::sectionName(int32_t SegIndex,
4081 uint64_t SegOffset) {
4082 return findSection(SegIndex, SegOffset).SectionName;
4085 // For use with a SegIndex,SegOffset pair from a checked Mach-O Bind or Rebase
4086 // entry to get the address.
4087 uint64_t BindRebaseSegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) {
4088 const SectionInfo &SI = findSection(SegIndex, OffsetInSeg);
4089 return SI.SegmentStartAddress + OffsetInSeg;
4092 iterator_range<bind_iterator>
4093 MachOObjectFile::bindTable(Error &Err, MachOObjectFile *O,
4094 ArrayRef<uint8_t> Opcodes, bool is64,
4095 MachOBindEntry::Kind BKind) {
4096 if (O->BindRebaseSectionTable == nullptr)
4097 O->BindRebaseSectionTable = llvm::make_unique<BindRebaseSegInfo>(O);
4098 MachOBindEntry Start(&Err, O, Opcodes, is64, BKind);
4099 Start.moveToFirst();
4101 MachOBindEntry Finish(&Err, O, Opcodes, is64, BKind);
4104 return make_range(bind_iterator(Start), bind_iterator(Finish));
4107 iterator_range<bind_iterator> MachOObjectFile::bindTable(Error &Err) {
4108 return bindTable(Err, this, getDyldInfoBindOpcodes(), is64Bit(),
4109 MachOBindEntry::Kind::Regular);
4112 iterator_range<bind_iterator> MachOObjectFile::lazyBindTable(Error &Err) {
4113 return bindTable(Err, this, getDyldInfoLazyBindOpcodes(), is64Bit(),
4114 MachOBindEntry::Kind::Lazy);
4117 iterator_range<bind_iterator> MachOObjectFile::weakBindTable(Error &Err) {
4118 return bindTable(Err, this, getDyldInfoWeakBindOpcodes(), is64Bit(),
4119 MachOBindEntry::Kind::Weak);
4122 MachOObjectFile::load_command_iterator
4123 MachOObjectFile::begin_load_commands() const {
4124 return LoadCommands.begin();
4127 MachOObjectFile::load_command_iterator
4128 MachOObjectFile::end_load_commands() const {
4129 return LoadCommands.end();
4132 iterator_range<MachOObjectFile::load_command_iterator>
4133 MachOObjectFile::load_commands() const {
4134 return make_range(begin_load_commands(), end_load_commands());
4138 MachOObjectFile::getSectionFinalSegmentName(DataRefImpl Sec) const {
4139 ArrayRef<char> Raw = getSectionRawFinalSegmentName(Sec);
4140 return parseSegmentOrSectionName(Raw.data());
4144 MachOObjectFile::getSectionRawName(DataRefImpl Sec) const {
4145 assert(Sec.d.a < Sections.size() && "Should have detected this earlier");
4146 const section_base *Base =
4147 reinterpret_cast<const section_base *>(Sections[Sec.d.a]);
4148 return makeArrayRef(Base->sectname);
4152 MachOObjectFile::getSectionRawFinalSegmentName(DataRefImpl Sec) const {
4153 assert(Sec.d.a < Sections.size() && "Should have detected this earlier");
4154 const section_base *Base =
4155 reinterpret_cast<const section_base *>(Sections[Sec.d.a]);
4156 return makeArrayRef(Base->segname);
4160 MachOObjectFile::isRelocationScattered(const MachO::any_relocation_info &RE)
4162 if (getCPUType(*this) == MachO::CPU_TYPE_X86_64)
4164 return getPlainRelocationAddress(RE) & MachO::R_SCATTERED;
4167 unsigned MachOObjectFile::getPlainRelocationSymbolNum(
4168 const MachO::any_relocation_info &RE) const {
4169 if (isLittleEndian())
4170 return RE.r_word1 & 0xffffff;
4171 return RE.r_word1 >> 8;
4174 bool MachOObjectFile::getPlainRelocationExternal(
4175 const MachO::any_relocation_info &RE) const {
4176 if (isLittleEndian())
4177 return (RE.r_word1 >> 27) & 1;
4178 return (RE.r_word1 >> 4) & 1;
4181 bool MachOObjectFile::getScatteredRelocationScattered(
4182 const MachO::any_relocation_info &RE) const {
4183 return RE.r_word0 >> 31;
4186 uint32_t MachOObjectFile::getScatteredRelocationValue(
4187 const MachO::any_relocation_info &RE) const {
4191 uint32_t MachOObjectFile::getScatteredRelocationType(
4192 const MachO::any_relocation_info &RE) const {
4193 return (RE.r_word0 >> 24) & 0xf;
4196 unsigned MachOObjectFile::getAnyRelocationAddress(
4197 const MachO::any_relocation_info &RE) const {
4198 if (isRelocationScattered(RE))
4199 return getScatteredRelocationAddress(RE);
4200 return getPlainRelocationAddress(RE);
4203 unsigned MachOObjectFile::getAnyRelocationPCRel(
4204 const MachO::any_relocation_info &RE) const {
4205 if (isRelocationScattered(RE))
4206 return getScatteredRelocationPCRel(RE);
4207 return getPlainRelocationPCRel(*this, RE);
4210 unsigned MachOObjectFile::getAnyRelocationLength(
4211 const MachO::any_relocation_info &RE) const {
4212 if (isRelocationScattered(RE))
4213 return getScatteredRelocationLength(RE);
4214 return getPlainRelocationLength(*this, RE);
4218 MachOObjectFile::getAnyRelocationType(
4219 const MachO::any_relocation_info &RE) const {
4220 if (isRelocationScattered(RE))
4221 return getScatteredRelocationType(RE);
4222 return getPlainRelocationType(*this, RE);
4226 MachOObjectFile::getAnyRelocationSection(
4227 const MachO::any_relocation_info &RE) const {
4228 if (isRelocationScattered(RE) || getPlainRelocationExternal(RE))
4229 return *section_end();
4230 unsigned SecNum = getPlainRelocationSymbolNum(RE);
4231 if (SecNum == MachO::R_ABS || SecNum > Sections.size())
4232 return *section_end();
4234 DRI.d.a = SecNum - 1;
4235 return SectionRef(DRI, this);
4238 MachO::section MachOObjectFile::getSection(DataRefImpl DRI) const {
4239 assert(DRI.d.a < Sections.size() && "Should have detected this earlier");
4240 return getStruct<MachO::section>(*this, Sections[DRI.d.a]);
4243 MachO::section_64 MachOObjectFile::getSection64(DataRefImpl DRI) const {
4244 assert(DRI.d.a < Sections.size() && "Should have detected this earlier");
4245 return getStruct<MachO::section_64>(*this, Sections[DRI.d.a]);
4248 MachO::section MachOObjectFile::getSection(const LoadCommandInfo &L,
4249 unsigned Index) const {
4250 const char *Sec = getSectionPtr(*this, L, Index);
4251 return getStruct<MachO::section>(*this, Sec);
4254 MachO::section_64 MachOObjectFile::getSection64(const LoadCommandInfo &L,
4255 unsigned Index) const {
4256 const char *Sec = getSectionPtr(*this, L, Index);
4257 return getStruct<MachO::section_64>(*this, Sec);
4261 MachOObjectFile::getSymbolTableEntry(DataRefImpl DRI) const {
4262 const char *P = reinterpret_cast<const char *>(DRI.p);
4263 return getStruct<MachO::nlist>(*this, P);
4267 MachOObjectFile::getSymbol64TableEntry(DataRefImpl DRI) const {
4268 const char *P = reinterpret_cast<const char *>(DRI.p);
4269 return getStruct<MachO::nlist_64>(*this, P);
4272 MachO::linkedit_data_command
4273 MachOObjectFile::getLinkeditDataLoadCommand(const LoadCommandInfo &L) const {
4274 return getStruct<MachO::linkedit_data_command>(*this, L.Ptr);
4277 MachO::segment_command
4278 MachOObjectFile::getSegmentLoadCommand(const LoadCommandInfo &L) const {
4279 return getStruct<MachO::segment_command>(*this, L.Ptr);
4282 MachO::segment_command_64
4283 MachOObjectFile::getSegment64LoadCommand(const LoadCommandInfo &L) const {
4284 return getStruct<MachO::segment_command_64>(*this, L.Ptr);
4287 MachO::linker_option_command
4288 MachOObjectFile::getLinkerOptionLoadCommand(const LoadCommandInfo &L) const {
4289 return getStruct<MachO::linker_option_command>(*this, L.Ptr);
4292 MachO::version_min_command
4293 MachOObjectFile::getVersionMinLoadCommand(const LoadCommandInfo &L) const {
4294 return getStruct<MachO::version_min_command>(*this, L.Ptr);
4298 MachOObjectFile::getNoteLoadCommand(const LoadCommandInfo &L) const {
4299 return getStruct<MachO::note_command>(*this, L.Ptr);
4302 MachO::build_version_command
4303 MachOObjectFile::getBuildVersionLoadCommand(const LoadCommandInfo &L) const {
4304 return getStruct<MachO::build_version_command>(*this, L.Ptr);
4307 MachO::build_tool_version
4308 MachOObjectFile::getBuildToolVersion(unsigned index) const {
4309 return getStruct<MachO::build_tool_version>(*this, BuildTools[index]);
4312 MachO::dylib_command
4313 MachOObjectFile::getDylibIDLoadCommand(const LoadCommandInfo &L) const {
4314 return getStruct<MachO::dylib_command>(*this, L.Ptr);
4317 MachO::dyld_info_command
4318 MachOObjectFile::getDyldInfoLoadCommand(const LoadCommandInfo &L) const {
4319 return getStruct<MachO::dyld_info_command>(*this, L.Ptr);
4322 MachO::dylinker_command
4323 MachOObjectFile::getDylinkerCommand(const LoadCommandInfo &L) const {
4324 return getStruct<MachO::dylinker_command>(*this, L.Ptr);
4328 MachOObjectFile::getUuidCommand(const LoadCommandInfo &L) const {
4329 return getStruct<MachO::uuid_command>(*this, L.Ptr);
4332 MachO::rpath_command
4333 MachOObjectFile::getRpathCommand(const LoadCommandInfo &L) const {
4334 return getStruct<MachO::rpath_command>(*this, L.Ptr);
4337 MachO::source_version_command
4338 MachOObjectFile::getSourceVersionCommand(const LoadCommandInfo &L) const {
4339 return getStruct<MachO::source_version_command>(*this, L.Ptr);
4342 MachO::entry_point_command
4343 MachOObjectFile::getEntryPointCommand(const LoadCommandInfo &L) const {
4344 return getStruct<MachO::entry_point_command>(*this, L.Ptr);
4347 MachO::encryption_info_command
4348 MachOObjectFile::getEncryptionInfoCommand(const LoadCommandInfo &L) const {
4349 return getStruct<MachO::encryption_info_command>(*this, L.Ptr);
4352 MachO::encryption_info_command_64
4353 MachOObjectFile::getEncryptionInfoCommand64(const LoadCommandInfo &L) const {
4354 return getStruct<MachO::encryption_info_command_64>(*this, L.Ptr);
4357 MachO::sub_framework_command
4358 MachOObjectFile::getSubFrameworkCommand(const LoadCommandInfo &L) const {
4359 return getStruct<MachO::sub_framework_command>(*this, L.Ptr);
4362 MachO::sub_umbrella_command
4363 MachOObjectFile::getSubUmbrellaCommand(const LoadCommandInfo &L) const {
4364 return getStruct<MachO::sub_umbrella_command>(*this, L.Ptr);
4367 MachO::sub_library_command
4368 MachOObjectFile::getSubLibraryCommand(const LoadCommandInfo &L) const {
4369 return getStruct<MachO::sub_library_command>(*this, L.Ptr);
4372 MachO::sub_client_command
4373 MachOObjectFile::getSubClientCommand(const LoadCommandInfo &L) const {
4374 return getStruct<MachO::sub_client_command>(*this, L.Ptr);
4377 MachO::routines_command
4378 MachOObjectFile::getRoutinesCommand(const LoadCommandInfo &L) const {
4379 return getStruct<MachO::routines_command>(*this, L.Ptr);
4382 MachO::routines_command_64
4383 MachOObjectFile::getRoutinesCommand64(const LoadCommandInfo &L) const {
4384 return getStruct<MachO::routines_command_64>(*this, L.Ptr);
4387 MachO::thread_command
4388 MachOObjectFile::getThreadCommand(const LoadCommandInfo &L) const {
4389 return getStruct<MachO::thread_command>(*this, L.Ptr);
4392 MachO::any_relocation_info
4393 MachOObjectFile::getRelocation(DataRefImpl Rel) const {
4395 if (getHeader().filetype == MachO::MH_OBJECT) {
4399 MachO::section_64 Sect = getSection64(Sec);
4400 Offset = Sect.reloff;
4402 MachO::section Sect = getSection(Sec);
4403 Offset = Sect.reloff;
4406 MachO::dysymtab_command DysymtabLoadCmd = getDysymtabLoadCommand();
4408 Offset = DysymtabLoadCmd.extreloff; // Offset to the external relocations
4410 Offset = DysymtabLoadCmd.locreloff; // Offset to the local relocations
4413 auto P = reinterpret_cast<const MachO::any_relocation_info *>(
4414 getPtr(*this, Offset)) + Rel.d.b;
4415 return getStruct<MachO::any_relocation_info>(
4416 *this, reinterpret_cast<const char *>(P));
4419 MachO::data_in_code_entry
4420 MachOObjectFile::getDice(DataRefImpl Rel) const {
4421 const char *P = reinterpret_cast<const char *>(Rel.p);
4422 return getStruct<MachO::data_in_code_entry>(*this, P);
4425 const MachO::mach_header &MachOObjectFile::getHeader() const {
4429 const MachO::mach_header_64 &MachOObjectFile::getHeader64() const {
4434 uint32_t MachOObjectFile::getIndirectSymbolTableEntry(
4435 const MachO::dysymtab_command &DLC,
4436 unsigned Index) const {
4437 uint64_t Offset = DLC.indirectsymoff + Index * sizeof(uint32_t);
4438 return getStruct<uint32_t>(*this, getPtr(*this, Offset));
4441 MachO::data_in_code_entry
4442 MachOObjectFile::getDataInCodeTableEntry(uint32_t DataOffset,
4443 unsigned Index) const {
4444 uint64_t Offset = DataOffset + Index * sizeof(MachO::data_in_code_entry);
4445 return getStruct<MachO::data_in_code_entry>(*this, getPtr(*this, Offset));
4448 MachO::symtab_command MachOObjectFile::getSymtabLoadCommand() const {
4450 return getStruct<MachO::symtab_command>(*this, SymtabLoadCmd);
4452 // If there is no SymtabLoadCmd return a load command with zero'ed fields.
4453 MachO::symtab_command Cmd;
4454 Cmd.cmd = MachO::LC_SYMTAB;
4455 Cmd.cmdsize = sizeof(MachO::symtab_command);
4463 MachO::dysymtab_command MachOObjectFile::getDysymtabLoadCommand() const {
4464 if (DysymtabLoadCmd)
4465 return getStruct<MachO::dysymtab_command>(*this, DysymtabLoadCmd);
4467 // If there is no DysymtabLoadCmd return a load command with zero'ed fields.
4468 MachO::dysymtab_command Cmd;
4469 Cmd.cmd = MachO::LC_DYSYMTAB;
4470 Cmd.cmdsize = sizeof(MachO::dysymtab_command);
4481 Cmd.extrefsymoff = 0;
4482 Cmd.nextrefsyms = 0;
4483 Cmd.indirectsymoff = 0;
4484 Cmd.nindirectsyms = 0;
4492 MachO::linkedit_data_command
4493 MachOObjectFile::getDataInCodeLoadCommand() const {
4494 if (DataInCodeLoadCmd)
4495 return getStruct<MachO::linkedit_data_command>(*this, DataInCodeLoadCmd);
4497 // If there is no DataInCodeLoadCmd return a load command with zero'ed fields.
4498 MachO::linkedit_data_command Cmd;
4499 Cmd.cmd = MachO::LC_DATA_IN_CODE;
4500 Cmd.cmdsize = sizeof(MachO::linkedit_data_command);
4506 MachO::linkedit_data_command
4507 MachOObjectFile::getLinkOptHintsLoadCommand() const {
4508 if (LinkOptHintsLoadCmd)
4509 return getStruct<MachO::linkedit_data_command>(*this, LinkOptHintsLoadCmd);
4511 // If there is no LinkOptHintsLoadCmd return a load command with zero'ed
4513 MachO::linkedit_data_command Cmd;
4514 Cmd.cmd = MachO::LC_LINKER_OPTIMIZATION_HINT;
4515 Cmd.cmdsize = sizeof(MachO::linkedit_data_command);
4521 ArrayRef<uint8_t> MachOObjectFile::getDyldInfoRebaseOpcodes() const {
4522 if (!DyldInfoLoadCmd)
4525 auto DyldInfoOrErr =
4526 getStructOrErr<MachO::dyld_info_command>(*this, DyldInfoLoadCmd);
4529 MachO::dyld_info_command DyldInfo = DyldInfoOrErr.get();
4530 const uint8_t *Ptr =
4531 reinterpret_cast<const uint8_t *>(getPtr(*this, DyldInfo.rebase_off));
4532 return makeArrayRef(Ptr, DyldInfo.rebase_size);
4535 ArrayRef<uint8_t> MachOObjectFile::getDyldInfoBindOpcodes() const {
4536 if (!DyldInfoLoadCmd)
4539 auto DyldInfoOrErr =
4540 getStructOrErr<MachO::dyld_info_command>(*this, DyldInfoLoadCmd);
4543 MachO::dyld_info_command DyldInfo = DyldInfoOrErr.get();
4544 const uint8_t *Ptr =
4545 reinterpret_cast<const uint8_t *>(getPtr(*this, DyldInfo.bind_off));
4546 return makeArrayRef(Ptr, DyldInfo.bind_size);
4549 ArrayRef<uint8_t> MachOObjectFile::getDyldInfoWeakBindOpcodes() const {
4550 if (!DyldInfoLoadCmd)
4553 auto DyldInfoOrErr =
4554 getStructOrErr<MachO::dyld_info_command>(*this, DyldInfoLoadCmd);
4557 MachO::dyld_info_command DyldInfo = DyldInfoOrErr.get();
4558 const uint8_t *Ptr =
4559 reinterpret_cast<const uint8_t *>(getPtr(*this, DyldInfo.weak_bind_off));
4560 return makeArrayRef(Ptr, DyldInfo.weak_bind_size);
4563 ArrayRef<uint8_t> MachOObjectFile::getDyldInfoLazyBindOpcodes() const {
4564 if (!DyldInfoLoadCmd)
4567 auto DyldInfoOrErr =
4568 getStructOrErr<MachO::dyld_info_command>(*this, DyldInfoLoadCmd);
4571 MachO::dyld_info_command DyldInfo = DyldInfoOrErr.get();
4572 const uint8_t *Ptr =
4573 reinterpret_cast<const uint8_t *>(getPtr(*this, DyldInfo.lazy_bind_off));
4574 return makeArrayRef(Ptr, DyldInfo.lazy_bind_size);
4577 ArrayRef<uint8_t> MachOObjectFile::getDyldInfoExportsTrie() const {
4578 if (!DyldInfoLoadCmd)
4581 auto DyldInfoOrErr =
4582 getStructOrErr<MachO::dyld_info_command>(*this, DyldInfoLoadCmd);
4585 MachO::dyld_info_command DyldInfo = DyldInfoOrErr.get();
4586 const uint8_t *Ptr =
4587 reinterpret_cast<const uint8_t *>(getPtr(*this, DyldInfo.export_off));
4588 return makeArrayRef(Ptr, DyldInfo.export_size);
4591 ArrayRef<uint8_t> MachOObjectFile::getUuid() const {
4594 // Returning a pointer is fine as uuid doesn't need endian swapping.
4595 const char *Ptr = UuidLoadCmd + offsetof(MachO::uuid_command, uuid);
4596 return makeArrayRef(reinterpret_cast<const uint8_t *>(Ptr), 16);
4599 StringRef MachOObjectFile::getStringTableData() const {
4600 MachO::symtab_command S = getSymtabLoadCommand();
4601 return getData().substr(S.stroff, S.strsize);
4604 bool MachOObjectFile::is64Bit() const {
4605 return getType() == getMachOType(false, true) ||
4606 getType() == getMachOType(true, true);
4609 void MachOObjectFile::ReadULEB128s(uint64_t Index,
4610 SmallVectorImpl<uint64_t> &Out) const {
4611 DataExtractor extractor(ObjectFile::getData(), true, 0);
4613 uint32_t offset = Index;
4615 while (uint64_t delta = extractor.getULEB128(&offset)) {
4617 Out.push_back(data);
4621 bool MachOObjectFile::isRelocatableObject() const {
4622 return getHeader().filetype == MachO::MH_OBJECT;
4625 Expected<std::unique_ptr<MachOObjectFile>>
4626 ObjectFile::createMachOObjectFile(MemoryBufferRef Buffer,
4627 uint32_t UniversalCputype,
4628 uint32_t UniversalIndex) {
4629 StringRef Magic = Buffer.getBuffer().slice(0, 4);
4630 if (Magic == "\xFE\xED\xFA\xCE")
4631 return MachOObjectFile::create(Buffer, false, false,
4632 UniversalCputype, UniversalIndex);
4633 if (Magic == "\xCE\xFA\xED\xFE")
4634 return MachOObjectFile::create(Buffer, true, false,
4635 UniversalCputype, UniversalIndex);
4636 if (Magic == "\xFE\xED\xFA\xCF")
4637 return MachOObjectFile::create(Buffer, false, true,
4638 UniversalCputype, UniversalIndex);
4639 if (Magic == "\xCF\xFA\xED\xFE")
4640 return MachOObjectFile::create(Buffer, true, true,
4641 UniversalCputype, UniversalIndex);
4642 return make_error<GenericBinaryError>("Unrecognized MachO magic number",
4643 object_error::invalid_file_type);
4646 StringRef MachOObjectFile::mapDebugSectionName(StringRef Name) const {
4647 return StringSwitch<StringRef>(Name)
4648 .Case("debug_str_offs", "debug_str_offsets")