2 * Copyright (c) 2017 Apple Inc. All rights reserved.
4 * @APPLE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
21 * @APPLE_LICENSE_HEADER_END@
25 #include <sys/types.h>
27 #include <sys/errno.h>
29 #include <mach/mach.h>
35 #include <mach-o/reloc.h>
36 #include <mach-o/nlist.h>
38 #include <corecrypto/ccdigest.h>
39 #include <corecrypto/ccsha1.h>
40 #include <corecrypto/ccsha2.h>
43 #include "MachOFile.h"
44 #include "MachOLoaded.h"
45 #include "CodeSigningTypes.h"
52 void MachOLoaded::getLinkEditLoadCommands(Diagnostics
& diag
, LinkEditInfo
& result
) const
54 result
.dyldInfo
= nullptr;
55 result
.exportsTrie
= nullptr;
56 result
.chainedFixups
= nullptr;
57 result
.symTab
= nullptr;
58 result
.dynSymTab
= nullptr;
59 result
.splitSegInfo
= nullptr;
60 result
.functionStarts
= nullptr;
61 result
.dataInCode
= nullptr;
62 result
.codeSig
= nullptr;
63 __block
bool hasUUID
= false;
64 __block
bool hasMinVersion
= false;
65 __block
bool hasEncrypt
= false;
66 forEachLoadCommand(diag
, ^(const load_command
* cmd
, bool& stop
) {
69 case LC_DYLD_INFO_ONLY
:
70 if ( cmd
->cmdsize
!= sizeof(dyld_info_command
) )
71 diag
.error("LC_DYLD_INFO load command size wrong");
72 else if ( result
.dyldInfo
!= nullptr )
73 diag
.error("multiple LC_DYLD_INFO load commands");
74 result
.dyldInfo
= (dyld_info_command
*)cmd
;
76 case LC_DYLD_EXPORTS_TRIE
:
77 if ( cmd
->cmdsize
!= sizeof(linkedit_data_command
) )
78 diag
.error("LC_DYLD_EXPORTS_TRIE load command size wrong");
79 else if ( result
.exportsTrie
!= nullptr )
80 diag
.error("multiple LC_DYLD_EXPORTS_TRIE load commands");
81 result
.exportsTrie
= (linkedit_data_command
*)cmd
;
83 case LC_DYLD_CHAINED_FIXUPS
:
84 if ( cmd
->cmdsize
!= sizeof(linkedit_data_command
) )
85 diag
.error("LC_DYLD_CHAINED_FIXUPS load command size wrong");
86 else if ( result
.chainedFixups
!= nullptr )
87 diag
.error("multiple LC_DYLD_CHAINED_FIXUPS load commands");
88 result
.chainedFixups
= (linkedit_data_command
*)cmd
;
91 if ( cmd
->cmdsize
!= sizeof(symtab_command
) )
92 diag
.error("LC_SYMTAB load command size wrong");
93 else if ( result
.symTab
!= nullptr )
94 diag
.error("multiple LC_SYMTAB load commands");
95 result
.symTab
= (symtab_command
*)cmd
;
98 if ( cmd
->cmdsize
!= sizeof(dysymtab_command
) )
99 diag
.error("LC_DYSYMTAB load command size wrong");
100 else if ( result
.dynSymTab
!= nullptr )
101 diag
.error("multiple LC_DYSYMTAB load commands");
102 result
.dynSymTab
= (dysymtab_command
*)cmd
;
104 case LC_SEGMENT_SPLIT_INFO
:
105 if ( cmd
->cmdsize
!= sizeof(linkedit_data_command
) )
106 diag
.error("LC_SEGMENT_SPLIT_INFO load command size wrong");
107 else if ( result
.splitSegInfo
!= nullptr )
108 diag
.error("multiple LC_SEGMENT_SPLIT_INFO load commands");
109 result
.splitSegInfo
= (linkedit_data_command
*)cmd
;
111 case LC_FUNCTION_STARTS
:
112 if ( cmd
->cmdsize
!= sizeof(linkedit_data_command
) )
113 diag
.error("LC_FUNCTION_STARTS load command size wrong");
114 else if ( result
.functionStarts
!= nullptr )
115 diag
.error("multiple LC_FUNCTION_STARTS load commands");
116 result
.functionStarts
= (linkedit_data_command
*)cmd
;
118 case LC_DATA_IN_CODE
:
119 if ( cmd
->cmdsize
!= sizeof(linkedit_data_command
) )
120 diag
.error("LC_DATA_IN_CODE load command size wrong");
121 else if ( result
.dataInCode
!= nullptr )
122 diag
.error("multiple LC_DATA_IN_CODE load commands");
123 result
.dataInCode
= (linkedit_data_command
*)cmd
;
125 case LC_CODE_SIGNATURE
:
126 if ( cmd
->cmdsize
!= sizeof(linkedit_data_command
) )
127 diag
.error("LC_CODE_SIGNATURE load command size wrong");
128 else if ( result
.codeSig
!= nullptr )
129 diag
.error("multiple LC_CODE_SIGNATURE load commands");
130 result
.codeSig
= (linkedit_data_command
*)cmd
;
133 if ( cmd
->cmdsize
!= sizeof(uuid_command
) )
134 diag
.error("LC_UUID load command size wrong");
136 diag
.error("multiple LC_UUID load commands");
139 case LC_VERSION_MIN_IPHONEOS
:
140 case LC_VERSION_MIN_MACOSX
:
141 case LC_VERSION_MIN_TVOS
:
142 case LC_VERSION_MIN_WATCHOS
:
143 if ( cmd
->cmdsize
!= sizeof(version_min_command
) )
144 diag
.error("LC_VERSION_* load command size wrong");
145 else if ( hasMinVersion
)
146 diag
.error("multiple LC_VERSION_MIN_* load commands");
147 hasMinVersion
= true;
149 case LC_BUILD_VERSION
:
150 if ( cmd
->cmdsize
!= (sizeof(build_version_command
) + ((build_version_command
*)cmd
)->ntools
* sizeof(build_tool_version
)) )
151 diag
.error("LC_BUILD_VERSION load command size wrong");
153 case LC_ENCRYPTION_INFO
:
154 if ( cmd
->cmdsize
!= sizeof(encryption_info_command
) )
155 diag
.error("LC_ENCRYPTION_INFO load command size wrong");
156 else if ( hasEncrypt
)
157 diag
.error("multiple LC_ENCRYPTION_INFO load commands");
159 diag
.error("LC_ENCRYPTION_INFO found in 64-bit mach-o");
162 case LC_ENCRYPTION_INFO_64
:
163 if ( cmd
->cmdsize
!= sizeof(encryption_info_command_64
) )
164 diag
.error("LC_ENCRYPTION_INFO_64 load command size wrong");
165 else if ( hasEncrypt
)
166 diag
.error("multiple LC_ENCRYPTION_INFO_64 load commands");
168 diag
.error("LC_ENCRYPTION_INFO_64 found in 32-bit mach-o");
173 if ( diag
.noError() && (result
.dynSymTab
!= nullptr) && (result
.symTab
== nullptr) )
174 diag
.error("LC_DYSYMTAB but no LC_SYMTAB load command");
177 void MachOLoaded::getLinkEditPointers(Diagnostics
& diag
, LinkEditInfo
& result
) const
179 getLinkEditLoadCommands(diag
, result
);
180 if ( diag
.noError() )
181 getLayoutInfo(result
.layout
);
184 const uint8_t* MachOLoaded::getExportsTrie(const LinkEditInfo
& leInfo
, uint64_t& trieSize
) const
186 if ( leInfo
.exportsTrie
!= nullptr) {
187 trieSize
= leInfo
.exportsTrie
->datasize
;
188 uint64_t offsetInLinkEdit
= leInfo
.exportsTrie
->dataoff
- leInfo
.layout
.linkeditFileOffset
;
189 return (uint8_t*)this + (leInfo
.layout
.linkeditUnslidVMAddr
- leInfo
.layout
.textUnslidVMAddr
) + offsetInLinkEdit
;
191 else if ( leInfo
.dyldInfo
!= nullptr ) {
192 trieSize
= leInfo
.dyldInfo
->export_size
;
193 uint64_t offsetInLinkEdit
= leInfo
.dyldInfo
->export_off
- leInfo
.layout
.linkeditFileOffset
;
194 return (uint8_t*)this + (leInfo
.layout
.linkeditUnslidVMAddr
- leInfo
.layout
.textUnslidVMAddr
) + offsetInLinkEdit
;
201 void MachOLoaded::getLayoutInfo(LayoutInfo
& result
) const
203 forEachSegment(^(const SegmentInfo
& info
, bool& stop
) {
204 if ( strcmp(info
.segName
, "__TEXT") == 0 ) {
205 result
.textUnslidVMAddr
= (uintptr_t)info
.vmAddr
;
206 result
.slide
= (uintptr_t)(((uint64_t)this) - info
.vmAddr
);
208 else if ( strcmp(info
.segName
, "__LINKEDIT") == 0 ) {
209 result
.linkeditUnslidVMAddr
= (uintptr_t)info
.vmAddr
;
210 result
.linkeditFileOffset
= (uint32_t)info
.fileOffset
;
211 result
.linkeditFileSize
= (uint32_t)info
.fileSize
;
212 result
.linkeditSegIndex
= info
.segIndex
;
217 bool MachOLoaded::hasExportTrie(uint32_t& runtimeOffset
, uint32_t& size
) const
223 getLinkEditPointers(diag
, leInfo
);
224 diag
.assertNoError(); // any malformations in the file should have been caught by earlier validate() call
225 if ( diag
.hasError() )
228 if ( const uint8_t* trie
= getExportsTrie(leInfo
, trieSize
) ) {
229 runtimeOffset
= (uint32_t)(trie
- (uint8_t*)this);
230 size
= (uint32_t)trieSize
;
238 // this is only used by dlsym() at runtime. All other binding is done when the closure is built.
239 bool MachOLoaded::hasExportedSymbol(const char* symbolName
, DependentToMachOLoaded finder
, void** result
,
240 bool* resultPointsToInstructions
) const
242 typedef void* (*ResolverFunc
)(void);
243 ResolverFunc resolver
;
245 FoundSymbol foundInfo
;
246 if ( findExportedSymbol(diag
, symbolName
, false, foundInfo
, finder
) ) {
247 switch ( foundInfo
.kind
) {
248 case FoundSymbol::Kind::headerOffset
: {
249 *result
= (uint8_t*)foundInfo
.foundInDylib
+ foundInfo
.value
;
250 *resultPointsToInstructions
= false;
251 int64_t slide
= foundInfo
.foundInDylib
->getSlide();
252 foundInfo
.foundInDylib
->forEachSection(^(const SectionInfo
& sectInfo
, bool malformedSectionRange
, bool& stop
) {
253 uint64_t sectStartAddr
= sectInfo
.sectAddr
+ slide
;
254 uint64_t sectEndAddr
= sectStartAddr
+ sectInfo
.sectSize
;
255 if ( ((uint64_t)*result
>= sectStartAddr
) && ((uint64_t)*result
< sectEndAddr
) ) {
256 *resultPointsToInstructions
= (sectInfo
.sectFlags
& S_ATTR_PURE_INSTRUCTIONS
) || (sectInfo
.sectFlags
& S_ATTR_SOME_INSTRUCTIONS
);
262 case FoundSymbol::Kind::absolute
:
263 *result
= (void*)(long)foundInfo
.value
;
264 *resultPointsToInstructions
= false;
266 case FoundSymbol::Kind::resolverOffset
:
267 // foundInfo.value contains "stub".
268 // in dlsym() we want to call resolver function to get final function address
269 resolver
= (ResolverFunc
)((uint8_t*)foundInfo
.foundInDylib
+ foundInfo
.resolverFuncOffset
);
270 *result
= (*resolver
)();
271 // FIXME: Set this properly
272 *resultPointsToInstructions
= true;
279 #endif // BUILDING_LIBDYLD
281 bool MachOLoaded::findExportedSymbol(Diagnostics
& diag
, const char* symbolName
, bool weakImport
, FoundSymbol
& foundInfo
, DependentToMachOLoaded findDependent
) const
284 getLinkEditPointers(diag
, leInfo
);
285 if ( diag
.hasError() )
288 if ( const uint8_t* trieStart
= getExportsTrie(leInfo
, trieSize
) ) {
289 const uint8_t* trieEnd
= trieStart
+ trieSize
;
290 const uint8_t* node
= trieWalk(diag
, trieStart
, trieEnd
, symbolName
);
291 if ( node
== nullptr ) {
292 // symbol not exported from this image. Seach any re-exported dylibs
293 __block
unsigned depIndex
= 0;
294 __block
bool foundInReExportedDylib
= false;
295 forEachDependentDylib(^(const char* loadPath
, bool isWeak
, bool isReExport
, bool isUpward
, uint32_t compatVersion
, uint32_t curVersion
, bool& stop
) {
296 if ( isReExport
&& findDependent
) {
297 if ( const MachOLoaded
* depMH
= findDependent(this, depIndex
) ) {
298 if ( depMH
->findExportedSymbol(diag
, symbolName
, weakImport
, foundInfo
, findDependent
) ) {
300 foundInReExportedDylib
= true;
306 return foundInReExportedDylib
;
308 const uint8_t* p
= node
;
309 const uint64_t flags
= read_uleb128(diag
, p
, trieEnd
);
310 if ( flags
& EXPORT_SYMBOL_FLAGS_REEXPORT
) {
311 if ( !findDependent
)
313 // re-export from another dylib, lookup there
314 const uint64_t ordinal
= read_uleb128(diag
, p
, trieEnd
);
315 const char* importedName
= (char*)p
;
316 if ( importedName
[0] == '\0' )
317 importedName
= symbolName
;
318 if ( (ordinal
== 0) || (ordinal
> dependentDylibCount()) ) {
319 diag
.error("re-export ordinal %lld out of range for %s", ordinal
, symbolName
);
322 uint32_t depIndex
= (uint32_t)(ordinal
-1);
323 if ( const MachOLoaded
* depMH
= findDependent(this, depIndex
) ) {
324 return depMH
->findExportedSymbol(diag
, importedName
, weakImport
, foundInfo
, findDependent
);
326 else if (weakImport
) {
330 diag
.error("dependent dylib %lld not found for re-exported symbol %s", ordinal
, symbolName
);
334 foundInfo
.kind
= FoundSymbol::Kind::headerOffset
;
335 foundInfo
.isThreadLocal
= false;
336 foundInfo
.isWeakDef
= false;
337 foundInfo
.foundInDylib
= this;
338 foundInfo
.value
= read_uleb128(diag
, p
, trieEnd
);
339 foundInfo
.resolverFuncOffset
= 0;
340 foundInfo
.foundSymbolName
= symbolName
;
341 if ( diag
.hasError() )
343 switch ( flags
& EXPORT_SYMBOL_FLAGS_KIND_MASK
) {
344 case EXPORT_SYMBOL_FLAGS_KIND_REGULAR
:
345 if ( flags
& EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER
) {
346 foundInfo
.kind
= FoundSymbol::Kind::headerOffset
;
347 foundInfo
.resolverFuncOffset
= (uint32_t)read_uleb128(diag
, p
, trieEnd
);
350 foundInfo
.kind
= FoundSymbol::Kind::headerOffset
;
352 if ( flags
& EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION
)
353 foundInfo
.isWeakDef
= true;
355 case EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL
:
356 foundInfo
.isThreadLocal
= true;
358 case EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE
:
359 foundInfo
.kind
= FoundSymbol::Kind::absolute
;
362 diag
.error("unsupported exported symbol kind. flags=%llu at node offset=0x%0lX", flags
, (long)(node
-trieStart
));
368 // this is an old binary (before macOS 10.6), scan the symbol table
369 foundInfo
.foundInDylib
= nullptr;
370 forEachGlobalSymbol(diag
, ^(const char* aSymbolName
, uint64_t n_value
, uint8_t n_type
, uint8_t n_sect
, uint16_t n_desc
, bool& stop
) {
371 if ( strcmp(aSymbolName
, symbolName
) == 0 ) {
372 foundInfo
.kind
= FoundSymbol::Kind::headerOffset
;
373 foundInfo
.isThreadLocal
= false;
374 foundInfo
.foundInDylib
= this;
375 foundInfo
.value
= n_value
- leInfo
.layout
.textUnslidVMAddr
;
376 foundInfo
.resolverFuncOffset
= 0;
377 foundInfo
.foundSymbolName
= symbolName
;
381 if ( foundInfo
.foundInDylib
== nullptr ) {
382 // symbol not exported from this image. Search any re-exported dylibs
383 __block
unsigned depIndex
= 0;
384 forEachDependentDylib(^(const char* loadPath
, bool isWeak
, bool isReExport
, bool isUpward
, uint32_t compatVersion
, uint32_t curVersion
, bool& stop
) {
385 if ( isReExport
&& findDependent
) {
386 if ( const MachOLoaded
* depMH
= findDependent(this, depIndex
) ) {
387 if ( depMH
->findExportedSymbol(diag
, symbolName
, weakImport
, foundInfo
, findDependent
) ) {
395 return (foundInfo
.foundInDylib
!= nullptr);
399 intptr_t MachOLoaded::getSlide() const
402 __block
intptr_t slide
= 0;
403 forEachLoadCommand(diag
, ^(const load_command
* cmd
, bool& stop
) {
404 if ( cmd
->cmd
== LC_SEGMENT_64
) {
405 const segment_command_64
* seg
= (segment_command_64
*)cmd
;
406 if ( strcmp(seg
->segname
, "__TEXT") == 0 ) {
407 slide
= (uintptr_t)(((uint64_t)this) - seg
->vmaddr
);
411 else if ( cmd
->cmd
== LC_SEGMENT
) {
412 const segment_command
* seg
= (segment_command
*)cmd
;
413 if ( strcmp(seg
->segname
, "__TEXT") == 0 ) {
414 slide
= (uintptr_t)(((uint64_t)this) - seg
->vmaddr
);
419 diag
.assertNoError(); // any malformations in the file should have been caught by earlier validate() call
423 const uint8_t* MachOLoaded::getLinkEditContent(const LayoutInfo
& info
, uint32_t fileOffset
) const
425 uint32_t offsetInLinkedit
= fileOffset
- info
.linkeditFileOffset
;
426 uintptr_t linkeditStartAddr
= info
.linkeditUnslidVMAddr
+ info
.slide
;
427 return (uint8_t*)(linkeditStartAddr
+ offsetInLinkedit
);
431 void MachOLoaded::forEachGlobalSymbol(Diagnostics
& diag
, void (^callback
)(const char* symbolName
, uint64_t n_value
, uint8_t n_type
, uint8_t n_sect
, uint16_t n_desc
, bool& stop
)) const
434 getLinkEditPointers(diag
, leInfo
);
435 if ( diag
.hasError() )
438 const bool is64Bit
= is64();
439 if ( leInfo
.symTab
!= nullptr ) {
440 uint32_t globalsStartIndex
= 0;
441 uint32_t globalsCount
= leInfo
.symTab
->nsyms
;
442 if ( leInfo
.dynSymTab
!= nullptr ) {
443 globalsStartIndex
= leInfo
.dynSymTab
->iextdefsym
;
444 globalsCount
= leInfo
.dynSymTab
->nextdefsym
;
446 uint32_t maxStringOffset
= leInfo
.symTab
->strsize
;
447 const char* stringPool
= (char*)getLinkEditContent(leInfo
.layout
, leInfo
.symTab
->stroff
);
448 const struct nlist
* symbols
= (struct nlist
*) (getLinkEditContent(leInfo
.layout
, leInfo
.symTab
->symoff
));
449 const struct nlist_64
* symbols64
= (struct nlist_64
*)symbols
;
451 for (uint32_t i
=0; (i
< globalsCount
) && !stop
; ++i
) {
453 const struct nlist_64
& sym
= symbols64
[globalsStartIndex
+i
];
454 if ( sym
.n_un
.n_strx
> maxStringOffset
)
456 if ( (sym
.n_type
& N_EXT
) && ((sym
.n_type
& N_TYPE
) == N_SECT
) && ((sym
.n_type
& N_STAB
) == 0) )
457 callback(&stringPool
[sym
.n_un
.n_strx
], sym
.n_value
, sym
.n_type
, sym
.n_sect
, sym
.n_desc
, stop
);
460 const struct nlist
& sym
= symbols
[globalsStartIndex
+i
];
461 if ( sym
.n_un
.n_strx
> maxStringOffset
)
463 if ( (sym
.n_type
& N_EXT
) && ((sym
.n_type
& N_TYPE
) == N_SECT
) && ((sym
.n_type
& N_STAB
) == 0) )
464 callback(&stringPool
[sym
.n_un
.n_strx
], sym
.n_value
, sym
.n_type
, sym
.n_sect
, sym
.n_desc
, stop
);
470 void MachOLoaded::forEachLocalSymbol(Diagnostics
& diag
, void (^callback
)(const char* symbolName
, uint64_t n_value
, uint8_t n_type
, uint8_t n_sect
, uint16_t n_desc
, bool& stop
)) const
473 getLinkEditPointers(diag
, leInfo
);
474 if ( diag
.hasError() )
477 const bool is64Bit
= is64();
478 if ( leInfo
.symTab
!= nullptr ) {
479 uint32_t localsStartIndex
= 0;
480 uint32_t localsCount
= leInfo
.symTab
->nsyms
;
481 if ( leInfo
.dynSymTab
!= nullptr ) {
482 localsStartIndex
= leInfo
.dynSymTab
->ilocalsym
;
483 localsCount
= leInfo
.dynSymTab
->nlocalsym
;
485 uint32_t maxStringOffset
= leInfo
.symTab
->strsize
;
486 const char* stringPool
= (char*)getLinkEditContent(leInfo
.layout
, leInfo
.symTab
->stroff
);
487 const struct nlist
* symbols
= (struct nlist
*) (getLinkEditContent(leInfo
.layout
, leInfo
.symTab
->symoff
));
488 const struct nlist_64
* symbols64
= (struct nlist_64
*)(getLinkEditContent(leInfo
.layout
, leInfo
.symTab
->symoff
));
490 for (uint32_t i
=0; (i
< localsCount
) && !stop
; ++i
) {
492 const struct nlist_64
& sym
= symbols64
[localsStartIndex
+i
];
493 if ( sym
.n_un
.n_strx
> maxStringOffset
)
495 if ( ((sym
.n_type
& N_EXT
) == 0) && ((sym
.n_type
& N_TYPE
) == N_SECT
) && ((sym
.n_type
& N_STAB
) == 0) )
496 callback(&stringPool
[sym
.n_un
.n_strx
], sym
.n_value
, sym
.n_type
, sym
.n_sect
, sym
.n_desc
, stop
);
499 const struct nlist
& sym
= symbols
[localsStartIndex
+i
];
500 if ( sym
.n_un
.n_strx
> maxStringOffset
)
502 if ( ((sym
.n_type
& N_EXT
) == 0) && ((sym
.n_type
& N_TYPE
) == N_SECT
) && ((sym
.n_type
& N_STAB
) == 0) )
503 callback(&stringPool
[sym
.n_un
.n_strx
], sym
.n_value
, sym
.n_type
, sym
.n_sect
, sym
.n_desc
, stop
);
509 uint32_t MachOLoaded::dependentDylibCount() const
511 __block
uint32_t count
= 0;
512 forEachDependentDylib(^(const char* loadPath
, bool isWeak
, bool isReExport
, bool isUpward
, uint32_t compatVersion
, uint32_t curVersion
, bool& stop
) {
518 const char* MachOLoaded::dependentDylibLoadPath(uint32_t depIndex
) const
520 __block
const char* foundLoadPath
= nullptr;
521 __block
uint32_t curDepIndex
= 0;
522 forEachDependentDylib(^(const char* loadPath
, bool isWeak
, bool isReExport
, bool isUpward
, uint32_t compatVersion
, uint32_t curVersion
, bool& stop
) {
523 if ( curDepIndex
== depIndex
) {
524 foundLoadPath
= loadPath
;
529 return foundLoadPath
;
532 const char* MachOLoaded::segmentName(uint32_t targetSegIndex
) const
534 __block
const char* result
= nullptr;
535 forEachSegment(^(const SegmentInfo
& info
, bool& stop
) {
536 if ( targetSegIndex
== info
.segIndex
) {
537 result
= info
.segName
;
544 bool MachOLoaded::findClosestFunctionStart(uint64_t address
, uint64_t* functionStartAddress
) const
548 getLinkEditPointers(diag
, leInfo
);
549 if ( diag
.hasError() )
551 if ( leInfo
.functionStarts
== nullptr )
554 const uint8_t* starts
= getLinkEditContent(leInfo
.layout
, leInfo
.functionStarts
->dataoff
);
555 const uint8_t* startsEnd
= starts
+ leInfo
.functionStarts
->datasize
;
557 uint64_t lastAddr
= (uint64_t)(long)this;
558 uint64_t runningAddr
= lastAddr
;
559 while (diag
.noError()) {
560 uint64_t value
= read_uleb128(diag
, starts
, startsEnd
);
563 lastAddr
= runningAddr
;
564 runningAddr
+= value
;
565 //fprintf(stderr, " addr=0x%08llX\n", runningAddr);
566 if ( runningAddr
> address
) {
567 *functionStartAddress
= lastAddr
;
575 bool MachOLoaded::findClosestSymbol(uint64_t address
, const char** symbolName
, uint64_t* symbolAddr
) const
579 getLinkEditPointers(diag
, leInfo
);
580 if ( diag
.hasError() )
582 if ( (leInfo
.symTab
== nullptr) || (leInfo
.dynSymTab
== nullptr) )
584 uint64_t targetUnslidAddress
= address
- leInfo
.layout
.slide
;
586 uint32_t maxStringOffset
= leInfo
.symTab
->strsize
;
587 const char* stringPool
= (char*)getLinkEditContent(leInfo
.layout
, leInfo
.symTab
->stroff
);
588 const struct nlist
* symbols
= (struct nlist
*) (getLinkEditContent(leInfo
.layout
, leInfo
.symTab
->symoff
));
590 const struct nlist_64
* symbols64
= (struct nlist_64
*)symbols
;
591 const struct nlist_64
* bestSymbol
= nullptr;
592 // first walk all global symbols
593 const struct nlist_64
* const globalsStart
= &symbols64
[leInfo
.dynSymTab
->iextdefsym
];
594 const struct nlist_64
* const globalsEnd
= &globalsStart
[leInfo
.dynSymTab
->nextdefsym
];
595 for (const struct nlist_64
* s
= globalsStart
; s
< globalsEnd
; ++s
) {
596 if ( (s
->n_type
& N_TYPE
) == N_SECT
) {
597 if ( bestSymbol
== nullptr ) {
598 if ( s
->n_value
<= targetUnslidAddress
)
601 else if ( (s
->n_value
<= targetUnslidAddress
) && (bestSymbol
->n_value
< s
->n_value
) ) {
606 // next walk all local symbols
607 const struct nlist_64
* const localsStart
= &symbols64
[leInfo
.dynSymTab
->ilocalsym
];
608 const struct nlist_64
* const localsEnd
= &localsStart
[leInfo
.dynSymTab
->nlocalsym
];
609 for (const struct nlist_64
* s
= localsStart
; s
< localsEnd
; ++s
) {
610 if ( ((s
->n_type
& N_TYPE
) == N_SECT
) && ((s
->n_type
& N_STAB
) == 0) ) {
611 if ( bestSymbol
== nullptr ) {
612 if ( s
->n_value
<= targetUnslidAddress
)
615 else if ( (s
->n_value
<= targetUnslidAddress
) && (bestSymbol
->n_value
< s
->n_value
) ) {
620 if ( bestSymbol
!= NULL
) {
621 *symbolAddr
= bestSymbol
->n_value
+ leInfo
.layout
.slide
;
622 if ( bestSymbol
->n_un
.n_strx
< maxStringOffset
)
623 *symbolName
= &stringPool
[bestSymbol
->n_un
.n_strx
];
628 const struct nlist
* bestSymbol
= nullptr;
629 // first walk all global symbols
630 const struct nlist
* const globalsStart
= &symbols
[leInfo
.dynSymTab
->iextdefsym
];
631 const struct nlist
* const globalsEnd
= &globalsStart
[leInfo
.dynSymTab
->nextdefsym
];
632 for (const struct nlist
* s
= globalsStart
; s
< globalsEnd
; ++s
) {
633 if ( (s
->n_type
& N_TYPE
) == N_SECT
) {
634 if ( bestSymbol
== nullptr ) {
635 if ( s
->n_value
<= targetUnslidAddress
)
638 else if ( (s
->n_value
<= targetUnslidAddress
) && (bestSymbol
->n_value
< s
->n_value
) ) {
643 // next walk all local symbols
644 const struct nlist
* const localsStart
= &symbols
[leInfo
.dynSymTab
->ilocalsym
];
645 const struct nlist
* const localsEnd
= &localsStart
[leInfo
.dynSymTab
->nlocalsym
];
646 for (const struct nlist
* s
= localsStart
; s
< localsEnd
; ++s
) {
647 if ( ((s
->n_type
& N_TYPE
) == N_SECT
) && ((s
->n_type
& N_STAB
) == 0) ) {
648 if ( bestSymbol
== nullptr ) {
649 if ( s
->n_value
<= targetUnslidAddress
)
652 else if ( (s
->n_value
<= targetUnslidAddress
) && (bestSymbol
->n_value
< s
->n_value
) ) {
657 if ( bestSymbol
!= nullptr ) {
659 if ( bestSymbol
->n_desc
& N_ARM_THUMB_DEF
)
660 *symbolAddr
= (bestSymbol
->n_value
| 1) + leInfo
.layout
.slide
;
662 *symbolAddr
= bestSymbol
->n_value
+ leInfo
.layout
.slide
;
664 *symbolAddr
= bestSymbol
->n_value
+ leInfo
.layout
.slide
;
666 if ( bestSymbol
->n_un
.n_strx
< maxStringOffset
)
667 *symbolName
= &stringPool
[bestSymbol
->n_un
.n_strx
];
675 const void* MachOLoaded::findSectionContent(const char* segName
, const char* sectName
, uint64_t& size
) const
677 __block
const void* result
= nullptr;
678 forEachSection(^(const SectionInfo
& sectInfo
, bool malformedSectionRange
, bool& stop
) {
679 if ( (strcmp(sectInfo
.sectName
, sectName
) == 0) && (strcmp(sectInfo
.segInfo
.segName
, segName
) == 0) ) {
680 size
= sectInfo
.sectSize
;
681 result
= (void*)(sectInfo
.sectAddr
+ getSlide());
688 bool MachOLoaded::intersectsRange(uintptr_t start
, uintptr_t length
) const
690 __block
bool result
= false;
691 uintptr_t slide
= getSlide();
692 forEachSegment(^(const SegmentInfo
& info
, bool& stop
) {
693 if ( (info
.vmAddr
+info
.vmSize
+slide
>= start
) && (info
.vmAddr
+slide
< start
+length
) )
699 const uint8_t* MachOLoaded::trieWalk(Diagnostics
& diag
, const uint8_t* start
, const uint8_t* end
, const char* symbol
)
701 uint32_t visitedNodeOffsets
[128];
702 int visitedNodeOffsetCount
= 0;
703 visitedNodeOffsets
[visitedNodeOffsetCount
++] = 0;
704 const uint8_t* p
= start
;
706 uint64_t terminalSize
= *p
++;
707 if ( terminalSize
> 127 ) {
708 // except for re-export-with-rename, all terminal sizes fit in one byte
710 terminalSize
= read_uleb128(diag
, p
, end
);
711 if ( diag
.hasError() )
714 if ( (*symbol
== '\0') && (terminalSize
!= 0) ) {
717 const uint8_t* children
= p
+ terminalSize
;
718 if ( children
> end
) {
719 //diag.error("malformed trie node, terminalSize=0x%llX extends past end of trie\n", terminalSize);
722 uint8_t childrenRemaining
= *children
++;
724 uint64_t nodeOffset
= 0;
725 for (; childrenRemaining
> 0; --childrenRemaining
) {
726 const char* ss
= symbol
;
727 bool wrongEdge
= false;
728 // scan whole edge to get to next edge
729 // if edge is longer than target symbol name, don't read past end of symbol name
731 while ( c
!= '\0' ) {
741 // advance to next child
742 ++p
; // skip over zero terminator
743 // skip over uleb128 until last byte is found
744 while ( (*p
& 0x80) != 0 )
746 ++p
; // skip over last byte of uleb128
748 diag
.error("malformed trie node, child node extends past end of trie\n");
753 // the symbol so far matches this edge (child)
754 // so advance to the child's node
756 nodeOffset
= read_uleb128(diag
, p
, end
);
757 if ( diag
.hasError() )
759 if ( (nodeOffset
== 0) || ( &start
[nodeOffset
] > end
) ) {
760 diag
.error("malformed trie child, nodeOffset=0x%llX out of range\n", nodeOffset
);
767 if ( nodeOffset
!= 0 ) {
768 if ( nodeOffset
> (uint64_t)(end
-start
) ) {
769 diag
.error("malformed trie child, nodeOffset=0x%llX out of range\n", nodeOffset
);
772 for (int i
=0; i
< visitedNodeOffsetCount
; ++i
) {
773 if ( visitedNodeOffsets
[i
] == nodeOffset
) {
774 diag
.error("malformed trie child, cycle to nodeOffset=0x%llX\n", nodeOffset
);
778 visitedNodeOffsets
[visitedNodeOffsetCount
++] = (uint32_t)nodeOffset
;
779 if ( visitedNodeOffsetCount
>= 128 ) {
780 diag
.error("malformed trie too deep\n");
783 p
= &start
[nodeOffset
];
791 void MachOLoaded::forEachCDHashOfCodeSignature(const void* codeSigStart
, size_t codeSignLen
,
792 void (^callback
)(const uint8_t cdHash
[20])) const
794 forEachCodeDirectoryBlob(codeSigStart
, codeSignLen
, ^(const void *cdBuffer
) {
795 const CS_CodeDirectory
* cd
= (const CS_CodeDirectory
*)cdBuffer
;
796 uint32_t cdLength
= htonl(cd
->length
);
798 if ( cd
->hashType
== CS_HASHTYPE_SHA384
) {
799 uint8_t digest
[CCSHA384_OUTPUT_SIZE
];
800 const struct ccdigest_info
* di
= ccsha384_di();
801 ccdigest_di_decl(di
, tempBuf
); // declares tempBuf array in stack
802 ccdigest_init(di
, tempBuf
);
803 ccdigest_update(di
, tempBuf
, cdLength
, cd
);
804 ccdigest_final(di
, tempBuf
, digest
);
805 ccdigest_di_clear(di
, tempBuf
);
806 // cd-hash of sigs that use SHA384 is the first 20 bytes of the SHA384 of the code digest
807 memcpy(cdHash
, digest
, 20);
811 else if ( (cd
->hashType
== CS_HASHTYPE_SHA256
) || (cd
->hashType
== CS_HASHTYPE_SHA256_TRUNCATED
) ) {
812 uint8_t digest
[CCSHA256_OUTPUT_SIZE
];
813 const struct ccdigest_info
* di
= ccsha256_di();
814 ccdigest_di_decl(di
, tempBuf
); // declares tempBuf array in stack
815 ccdigest_init(di
, tempBuf
);
816 ccdigest_update(di
, tempBuf
, cdLength
, cd
);
817 ccdigest_final(di
, tempBuf
, digest
);
818 ccdigest_di_clear(di
, tempBuf
);
819 // cd-hash of sigs that use SHA256 is the first 20 bytes of the SHA256 of the code digest
820 memcpy(cdHash
, digest
, 20);
824 else if ( cd
->hashType
== CS_HASHTYPE_SHA1
) {
825 // compute hash directly into return buffer
826 const struct ccdigest_info
* di
= ccsha1_di();
827 ccdigest_di_decl(di
, tempBuf
); // declares tempBuf array in stack
828 ccdigest_init(di
, tempBuf
);
829 ccdigest_update(di
, tempBuf
, cdLength
, cd
);
830 ccdigest_final(di
, tempBuf
, cdHash
);
831 ccdigest_di_clear(di
, tempBuf
);
839 // Note, this has to match the kernel
840 static const uint32_t hashPriorities
[] = {
842 CS_HASHTYPE_SHA256_TRUNCATED
,
847 static unsigned int hash_rank(const CS_CodeDirectory
*cd
)
849 uint32_t type
= cd
->hashType
;
850 for (uint32_t n
= 0; n
< sizeof(hashPriorities
) / sizeof(hashPriorities
[0]); ++n
) {
851 if (hashPriorities
[n
] == type
)
859 // Note, this does NOT match the kernel.
860 // On watchOS, in main executables, we will record all cd hashes then make sure
861 // one of the ones we record matches the kernel.
862 // This list is only for dylibs where we embed the cd hash in the closure instead of the
863 // mod time and inode
864 // This is sorted so that we choose sha1 first when checking dylibs
865 static const uint32_t hashPriorities_watchOS_dylibs
[] = {
866 CS_HASHTYPE_SHA256_TRUNCATED
,
872 static unsigned int hash_rank_watchOS_dylibs(const CS_CodeDirectory
*cd
)
874 uint32_t type
= cd
->hashType
;
875 for (uint32_t n
= 0; n
< sizeof(hashPriorities_watchOS_dylibs
) / sizeof(hashPriorities_watchOS_dylibs
[0]); ++n
) {
876 if (hashPriorities_watchOS_dylibs
[n
] == type
)
884 // This calls the callback for all code directories required for a given platform/binary combination.
885 // On watchOS main executables this is all cd hashes.
886 // On watchOS dylibs this is only the single cd hash we need (by rank defined by dyld, not the kernel).
887 // On all other platforms this always returns a single best cd hash (ranked to match the kernel).
888 // Note the callback parameter is really a CS_CodeDirectory.
889 void MachOLoaded::forEachCodeDirectoryBlob(const void* codeSigStart
, size_t codeSignLen
,
890 void (^callback
)(const void* cd
)) const
892 // verify min length of overall code signature
893 if ( codeSignLen
< sizeof(CS_SuperBlob
) )
896 // verify magic at start
897 const CS_SuperBlob
* codeSuperBlob
= (CS_SuperBlob
*)codeSigStart
;
898 if ( codeSuperBlob
->magic
!= htonl(CSMAGIC_EMBEDDED_SIGNATURE
) )
901 // verify count of sub-blobs not too large
902 uint32_t subBlobCount
= htonl(codeSuperBlob
->count
);
903 if ( (codeSignLen
-sizeof(CS_SuperBlob
))/sizeof(CS_BlobIndex
) < subBlobCount
)
906 // Note: The kernel sometimes chooses sha1 on watchOS, and sometimes sha256.
907 // Embed all of them so that we just need to match any of them
908 const bool isWatchOS
= this->supportsPlatform(Platform::watchOS
);
909 const bool isMainExecutable
= this->isMainExecutable();
910 auto hashRankFn
= isWatchOS
? &hash_rank_watchOS_dylibs
: &hash_rank
;
912 // walk each sub blob, looking at ones with type CSSLOT_CODEDIRECTORY
913 const CS_CodeDirectory
* bestCd
= nullptr;
914 for (uint32_t i
=0; i
< subBlobCount
; ++i
) {
915 if ( codeSuperBlob
->index
[i
].type
== htonl(CSSLOT_CODEDIRECTORY
) ) {
916 // Ok, this is the regular code directory
917 } else if ( codeSuperBlob
->index
[i
].type
>= htonl(CSSLOT_ALTERNATE_CODEDIRECTORIES
) && codeSuperBlob
->index
[i
].type
<= htonl(CSSLOT_ALTERNATE_CODEDIRECTORY_LIMIT
)) {
918 // Ok, this is the alternative code directory
922 uint32_t cdOffset
= htonl(codeSuperBlob
->index
[i
].offset
);
923 // verify offset is not out of range
924 if ( cdOffset
> (codeSignLen
- sizeof(CS_CodeDirectory
)) )
926 const CS_CodeDirectory
* cd
= (CS_CodeDirectory
*)((uint8_t*)codeSuperBlob
+ cdOffset
);
927 uint32_t cdLength
= htonl(cd
->length
);
928 // verify code directory length not out of range
929 if ( cdLength
> (codeSignLen
- cdOffset
) )
932 // The watch main executable wants to know about all cd hashes
933 if ( isWatchOS
&& isMainExecutable
) {
938 if ( cd
->magic
== htonl(CSMAGIC_CODEDIRECTORY
) ) {
939 if ( !bestCd
|| (hashRankFn(cd
) > hashRankFn(bestCd
)) )
944 // Note this callback won't happen on watchOS as that one was done in the loop
945 if ( bestCd
!= nullptr )
950 uint64_t MachOLoaded::ChainedFixupPointerOnDisk::Arm64e::unpackTarget() const
952 assert(this->authBind
.bind
== 0);
953 assert(this->authBind
.auth
== 0);
954 return ((uint64_t)(this->rebase
.high8
) << 56) | (this->rebase
.target
);
957 uint64_t MachOLoaded::ChainedFixupPointerOnDisk::Arm64e::signExtendedAddend() const
959 assert(this->authBind
.bind
== 1);
960 assert(this->authBind
.auth
== 0);
961 uint64_t addend19
= this->bind
.addend
;
962 if ( addend19
& 0x40000 )
963 return addend19
| 0xFFFFFFFFFFFC0000ULL
;
968 const char* MachOLoaded::ChainedFixupPointerOnDisk::Arm64e::keyName() const
970 static const char* names
[] = {
971 "IA", "IB", "DA", "DB"
973 assert(this->authBind
.auth
== 1);
974 uint8_t keyBits
= this->authBind
.key
;
976 return names
[keyBits
];
979 uint64_t MachOLoaded::ChainedFixupPointerOnDisk::Arm64e::signPointer(void* loc
, uint64_t target
) const
981 assert(this->authBind
.auth
== 1);
982 #if __has_feature(ptrauth_calls)
983 uint64_t discriminator
= authBind
.diversity
;
984 if ( authBind
.addrDiv
)
985 discriminator
= __builtin_ptrauth_blend_discriminator(loc
, discriminator
);
986 switch ( authBind
.key
) {
988 return (uint64_t)__builtin_ptrauth_sign_unauthenticated((void*)target
, 0, discriminator
);
990 return (uint64_t)__builtin_ptrauth_sign_unauthenticated((void*)target
, 1, discriminator
);
992 return (uint64_t)__builtin_ptrauth_sign_unauthenticated((void*)target
, 2, discriminator
);
994 return (uint64_t)__builtin_ptrauth_sign_unauthenticated((void*)target
, 3, discriminator
);
1000 uint64_t MachOLoaded::ChainedFixupPointerOnDisk::Generic64::unpackedTarget() const
1002 return (((uint64_t)this->rebase
.high8
) << 56) | (uint64_t)(this->rebase
.target
);
1005 uint64_t MachOLoaded::ChainedFixupPointerOnDisk::Generic64::signExtendedAddend() const
1007 uint64_t addend27
= this->bind
.addend
;
1008 uint64_t top8Bits
= addend27
& 0x00007F80000ULL
;
1009 uint64_t bottom19Bits
= addend27
& 0x0000007FFFFULL
;
1010 uint64_t newValue
= (top8Bits
<< 13) | (((uint64_t)(bottom19Bits
<< 37) >> 37) & 0x00FFFFFFFFFFFFFF);
1014 bool MachOLoaded::ChainedFixupPointerOnDisk::isRebase(uint16_t pointerFormat
, uint64_t preferedLoadAddress
, uint64_t& targetRuntimeOffset
) const
1016 switch (pointerFormat
) {
1017 case DYLD_CHAINED_PTR_ARM64E
:
1018 if ( this->arm64e
.bind
.bind
)
1020 if ( this->arm64e
.authRebase
.auth
) {
1021 targetRuntimeOffset
= this->arm64e
.authRebase
.target
;
1025 targetRuntimeOffset
= this->arm64e
.unpackTarget() - preferedLoadAddress
;
1029 case DYLD_CHAINED_PTR_64
:
1030 if ( this->generic64
.bind
.bind
)
1032 targetRuntimeOffset
= this->generic64
.unpackedTarget() - preferedLoadAddress
;
1035 case DYLD_CHAINED_PTR_32
:
1036 if ( this->generic32
.bind
.bind
)
1038 targetRuntimeOffset
= this->generic32
.rebase
.target
- preferedLoadAddress
;
1044 assert(0 && "unsupported pointer chain format");
1047 bool MachOLoaded::ChainedFixupPointerOnDisk::isBind(uint16_t pointerFormat
, uint32_t& bindOrdinal
) const
1049 switch (pointerFormat
) {
1050 case DYLD_CHAINED_PTR_ARM64E
:
1051 if ( !this->arm64e
.authBind
.bind
)
1053 if ( this->arm64e
.authBind
.auth
) {
1054 bindOrdinal
= this->arm64e
.authBind
.ordinal
;
1058 bindOrdinal
= this->arm64e
.bind
.ordinal
;
1062 case DYLD_CHAINED_PTR_64
:
1063 if ( !this->generic64
.bind
.bind
)
1065 bindOrdinal
= this->generic64
.bind
.ordinal
;
1068 case DYLD_CHAINED_PTR_32
:
1069 if ( !this->generic32
.bind
.bind
)
1071 bindOrdinal
= this->generic32
.bind
.ordinal
;
1077 assert(0 && "unsupported pointer chain format");
1080 #if BUILDING_DYLD || BUILDING_LIBDYLD
1081 void MachOLoaded::fixupAllChainedFixups(Diagnostics
& diag
, const dyld_chained_starts_in_image
* starts
, uintptr_t slide
,
1082 Array
<const void*> bindTargets
, void (^logFixup
)(void* loc
, void* newValue
)) const
1084 forEachFixupInAllChains(diag
, starts
, true, ^(ChainedFixupPointerOnDisk
* fixupLoc
, const dyld_chained_starts_in_segment
* segInfo
, bool& stop
) {
1086 switch (segInfo
->pointer_format
) {
1088 #if __has_feature(ptrauth_calls)
1089 case DYLD_CHAINED_PTR_ARM64E
:
1090 if ( fixupLoc
->arm64e
.authRebase
.auth
) {
1091 if ( fixupLoc
->arm64e
.authBind
.bind
) {
1092 if ( fixupLoc
->arm64e
.authBind
.ordinal
>= bindTargets
.count() ) {
1093 diag
.error("out of range bind ordinal %d (max %lu)", fixupLoc
->arm64e
.authBind
.ordinal
, bindTargets
.count());
1098 // authenticated bind
1099 newValue
= (void*)(bindTargets
[fixupLoc
->arm64e
.bind
.ordinal
]);
1100 if (newValue
!= 0) // Don't sign missing weak imports
1101 newValue
= (void*)fixupLoc
->arm64e
.signPointer(fixupLoc
, (uintptr_t)newValue
);
1105 // authenticated rebase
1106 newValue
= (void*)fixupLoc
->arm64e
.signPointer(fixupLoc
, (uintptr_t)this + fixupLoc
->arm64e
.authRebase
.target
);
1110 if ( fixupLoc
->arm64e
.bind
.bind
) {
1111 if ( fixupLoc
->arm64e
.bind
.ordinal
>= bindTargets
.count() ) {
1112 diag
.error("out of range bind ordinal %d (max %lu)", fixupLoc
->arm64e
.bind
.ordinal
, bindTargets
.count());
1118 newValue
= (void*)((long)bindTargets
[fixupLoc
->arm64e
.bind
.ordinal
] + fixupLoc
->arm64e
.signExtendedAddend());
1123 newValue
= (void*)(fixupLoc
->arm64e
.unpackTarget()+slide
);
1127 logFixup(fixupLoc
, newValue
);
1128 fixupLoc
->raw64
= (uintptr_t)newValue
;
1131 case DYLD_CHAINED_PTR_64
:
1132 if ( fixupLoc
->generic64
.bind
.bind
) {
1133 if ( fixupLoc
->generic64
.bind
.ordinal
>= bindTargets
.count() ) {
1134 diag
.error("out of range bind ordinal %d (max %lu)", fixupLoc
->generic64
.bind
.ordinal
, bindTargets
.count());
1139 newValue
= (void*)((long)bindTargets
[fixupLoc
->generic64
.bind
.ordinal
] + fixupLoc
->generic64
.signExtendedAddend());
1143 newValue
= (void*)(fixupLoc
->generic64
.unpackedTarget()+slide
);
1146 logFixup(fixupLoc
, newValue
);
1147 fixupLoc
->raw64
= (uintptr_t)newValue
;
1150 case DYLD_CHAINED_PTR_32
:
1151 if ( fixupLoc
->generic32
.bind
.bind
) {
1152 if ( fixupLoc
->generic32
.bind
.ordinal
>= bindTargets
.count() ) {
1153 diag
.error("out of range bind ordinal %d (max %lu)", fixupLoc
->generic32
.bind
.ordinal
, bindTargets
.count());
1158 newValue
= (void*)((long)bindTargets
[fixupLoc
->generic32
.bind
.ordinal
] + fixupLoc
->generic32
.bind
.addend
);
1162 if ( fixupLoc
->generic32
.rebase
.target
> segInfo
->max_valid_pointer
) {
1163 // handle non-pointers in chain
1164 uint32_t bias
= (0x04000000 + segInfo
->max_valid_pointer
)/2;
1165 newValue
= (void*)(fixupLoc
->generic32
.rebase
.target
- bias
);
1168 newValue
= (void*)(fixupLoc
->generic32
.rebase
.target
+ slide
);
1172 logFixup(fixupLoc
, newValue
);
1173 fixupLoc
->raw32
= (uint32_t)(uintptr_t)newValue
;
1177 diag
.error("unsupported pointer chain format: 0x%04X", segInfo
->pointer_format
);
1185 bool MachOLoaded::walkChain(Diagnostics
& diag
, const dyld_chained_starts_in_segment
* segInfo
, uint32_t pageIndex
, uint16_t offsetInPage
,
1186 bool notifyNonPointers
, void (^handler
)(ChainedFixupPointerOnDisk
* fixupLocation
, const dyld_chained_starts_in_segment
* segInfo
, bool& stop
)) const
1189 uint8_t* pageContentStart
= (uint8_t*)this + segInfo
->segment_offset
+ (pageIndex
* segInfo
->page_size
);
1190 ChainedFixupPointerOnDisk
* chain
= (ChainedFixupPointerOnDisk
*)(pageContentStart
+offsetInPage
);
1191 bool chainEnd
= false;
1192 while (!stop
&& !chainEnd
) {
1193 // copy chain content, in case handler modifies location to final value
1194 ChainedFixupPointerOnDisk chainContent
= *chain
;
1195 handler(chain
, segInfo
, stop
);
1197 switch (segInfo
->pointer_format
) {
1198 case DYLD_CHAINED_PTR_ARM64E
:
1199 if ( chainContent
.arm64e
.rebase
.next
== 0 )
1202 chain
= (ChainedFixupPointerOnDisk
*)((uint8_t*)chain
+ chainContent
.arm64e
.rebase
.next
*8);
1204 case DYLD_CHAINED_PTR_64
:
1205 if ( chainContent
.generic64
.rebase
.next
== 0 )
1208 chain
= (ChainedFixupPointerOnDisk
*)((uint8_t*)chain
+ chainContent
.generic64
.rebase
.next
*4);
1210 case DYLD_CHAINED_PTR_32
:
1211 if ( chainContent
.generic32
.rebase
.next
== 0 )
1214 chain
= (ChainedFixupPointerOnDisk
*)((uint8_t*)chain
+ chainContent
.generic32
.rebase
.next
*4);
1215 if ( !notifyNonPointers
) {
1216 while ( (chain
->generic32
.rebase
.bind
== 0) && (chain
->generic32
.rebase
.target
> segInfo
->max_valid_pointer
) ) {
1217 // not a real pointer, but a non-pointer co-opted into chain
1218 chain
= (ChainedFixupPointerOnDisk
*)((uint8_t*)chain
+ chain
->generic32
.rebase
.next
*4);
1224 diag
.error("unknown pointer format 0x%04X", segInfo
->pointer_format
);
1232 void MachOLoaded::forEachFixupInAllChains(Diagnostics
& diag
, const dyld_chained_starts_in_image
* starts
, bool notifyNonPointers
,
1233 void (^handler
)(ChainedFixupPointerOnDisk
* fixupLocation
, const dyld_chained_starts_in_segment
* segInfo
, bool& stop
)) const
1235 bool stopped
= false;
1236 for (uint32_t segIndex
=0; segIndex
< starts
->seg_count
&& !stopped
; ++segIndex
) {
1237 if ( starts
->seg_info_offset
[segIndex
] == 0 )
1239 const dyld_chained_starts_in_segment
* segInfo
= (dyld_chained_starts_in_segment
*)((uint8_t*)starts
+ starts
->seg_info_offset
[segIndex
]);
1240 for (uint32_t pageIndex
=0; pageIndex
< segInfo
->page_count
&& !stopped
; ++pageIndex
) {
1241 uint16_t offsetInPage
= segInfo
->page_start
[pageIndex
];
1242 if ( offsetInPage
== DYLD_CHAINED_PTR_START_NONE
)
1244 if ( offsetInPage
& DYLD_CHAINED_PTR_START_MULTI
) {
1245 // 32-bit chains which may need multiple starts per page
1246 uint32_t overflowIndex
= offsetInPage
& ~DYLD_CHAINED_PTR_START_MULTI
;
1247 bool chainEnd
= false;
1248 while (!stopped
&& !chainEnd
) {
1249 chainEnd
= (segInfo
->page_start
[overflowIndex
] & DYLD_CHAINED_PTR_START_LAST
);
1250 offsetInPage
= (segInfo
->page_start
[overflowIndex
] & ~DYLD_CHAINED_PTR_START_LAST
);
1251 if ( walkChain(diag
, segInfo
, pageIndex
, offsetInPage
, notifyNonPointers
, handler
) )
1257 // one chain per page
1258 walkChain(diag
, segInfo
, pageIndex
, offsetInPage
, notifyNonPointers
, handler
);
1265 } // namespace dyld3