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 // find section index the address is in to validate n_sect
587 __block
uint32_t sectionIndexForTargetAddress
= 0;
588 forEachSection(^(const SectionInfo
& sectInfo
, bool malformedSectionRange
, bool& stop
) {
589 ++sectionIndexForTargetAddress
;
590 if ( (sectInfo
.sectAddr
<= targetUnslidAddress
) && (targetUnslidAddress
< sectInfo
.sectAddr
+sectInfo
.sectSize
) ) {
595 uint32_t maxStringOffset
= leInfo
.symTab
->strsize
;
596 const char* stringPool
= (char*)getLinkEditContent(leInfo
.layout
, leInfo
.symTab
->stroff
);
597 const struct nlist
* symbols
= (struct nlist
*) (getLinkEditContent(leInfo
.layout
, leInfo
.symTab
->symoff
));
599 const struct nlist_64
* symbols64
= (struct nlist_64
*)symbols
;
600 const struct nlist_64
* bestSymbol
= nullptr;
601 // first walk all global symbols
602 const struct nlist_64
* const globalsStart
= &symbols64
[leInfo
.dynSymTab
->iextdefsym
];
603 const struct nlist_64
* const globalsEnd
= &globalsStart
[leInfo
.dynSymTab
->nextdefsym
];
604 for (const struct nlist_64
* s
= globalsStart
; s
< globalsEnd
; ++s
) {
605 if ( (s
->n_type
& N_TYPE
) == N_SECT
) {
606 if ( bestSymbol
== nullptr ) {
607 if ( (s
->n_value
<= targetUnslidAddress
) && (s
->n_sect
== sectionIndexForTargetAddress
) )
610 else if ( (s
->n_value
<= targetUnslidAddress
) && (bestSymbol
->n_value
< s
->n_value
) && (s
->n_sect
== sectionIndexForTargetAddress
) ) {
615 // next walk all local symbols
616 const struct nlist_64
* const localsStart
= &symbols64
[leInfo
.dynSymTab
->ilocalsym
];
617 const struct nlist_64
* const localsEnd
= &localsStart
[leInfo
.dynSymTab
->nlocalsym
];
618 for (const struct nlist_64
* s
= localsStart
; s
< localsEnd
; ++s
) {
619 if ( ((s
->n_type
& N_TYPE
) == N_SECT
) && ((s
->n_type
& N_STAB
) == 0) ) {
620 if ( bestSymbol
== nullptr ) {
621 if ( (s
->n_value
<= targetUnslidAddress
) && (s
->n_sect
== sectionIndexForTargetAddress
) )
624 else if ( (s
->n_value
<= targetUnslidAddress
) && (bestSymbol
->n_value
< s
->n_value
) && (s
->n_sect
== sectionIndexForTargetAddress
) ) {
629 if ( bestSymbol
!= NULL
) {
630 *symbolAddr
= bestSymbol
->n_value
+ leInfo
.layout
.slide
;
631 if ( bestSymbol
->n_un
.n_strx
< maxStringOffset
)
632 *symbolName
= &stringPool
[bestSymbol
->n_un
.n_strx
];
637 const struct nlist
* bestSymbol
= nullptr;
638 // first walk all global symbols
639 const struct nlist
* const globalsStart
= &symbols
[leInfo
.dynSymTab
->iextdefsym
];
640 const struct nlist
* const globalsEnd
= &globalsStart
[leInfo
.dynSymTab
->nextdefsym
];
641 for (const struct nlist
* s
= globalsStart
; s
< globalsEnd
; ++s
) {
642 if ( (s
->n_type
& N_TYPE
) == N_SECT
) {
643 if ( bestSymbol
== nullptr ) {
644 if ( (s
->n_value
<= targetUnslidAddress
) && (s
->n_sect
== sectionIndexForTargetAddress
) )
647 else if ( (s
->n_value
<= targetUnslidAddress
) && (bestSymbol
->n_value
< s
->n_value
) && (s
->n_sect
== sectionIndexForTargetAddress
) ) {
652 // next walk all local symbols
653 const struct nlist
* const localsStart
= &symbols
[leInfo
.dynSymTab
->ilocalsym
];
654 const struct nlist
* const localsEnd
= &localsStart
[leInfo
.dynSymTab
->nlocalsym
];
655 for (const struct nlist
* s
= localsStart
; s
< localsEnd
; ++s
) {
656 if ( ((s
->n_type
& N_TYPE
) == N_SECT
) && ((s
->n_type
& N_STAB
) == 0) ) {
657 if ( bestSymbol
== nullptr ) {
658 if ( (s
->n_value
<= targetUnslidAddress
) && (s
->n_sect
== sectionIndexForTargetAddress
) )
661 else if ( (s
->n_value
<= targetUnslidAddress
) && (bestSymbol
->n_value
< s
->n_value
) && (s
->n_sect
== sectionIndexForTargetAddress
) ) {
666 if ( bestSymbol
!= nullptr ) {
668 if ( bestSymbol
->n_desc
& N_ARM_THUMB_DEF
)
669 *symbolAddr
= (bestSymbol
->n_value
| 1) + leInfo
.layout
.slide
;
671 *symbolAddr
= bestSymbol
->n_value
+ leInfo
.layout
.slide
;
673 *symbolAddr
= bestSymbol
->n_value
+ leInfo
.layout
.slide
;
675 if ( bestSymbol
->n_un
.n_strx
< maxStringOffset
)
676 *symbolName
= &stringPool
[bestSymbol
->n_un
.n_strx
];
684 const void* MachOLoaded::findSectionContent(const char* segName
, const char* sectName
, uint64_t& size
) const
686 __block
const void* result
= nullptr;
687 forEachSection(^(const SectionInfo
& sectInfo
, bool malformedSectionRange
, bool& stop
) {
688 if ( (strcmp(sectInfo
.sectName
, sectName
) == 0) && (strcmp(sectInfo
.segInfo
.segName
, segName
) == 0) ) {
689 size
= sectInfo
.sectSize
;
690 result
= (void*)(sectInfo
.sectAddr
+ getSlide());
697 bool MachOLoaded::intersectsRange(uintptr_t start
, uintptr_t length
) const
699 __block
bool result
= false;
700 uintptr_t slide
= getSlide();
701 forEachSegment(^(const SegmentInfo
& info
, bool& stop
) {
702 if ( (info
.vmAddr
+info
.vmSize
+slide
>= start
) && (info
.vmAddr
+slide
< start
+length
) )
708 const uint8_t* MachOLoaded::trieWalk(Diagnostics
& diag
, const uint8_t* start
, const uint8_t* end
, const char* symbol
)
710 uint32_t visitedNodeOffsets
[128];
711 int visitedNodeOffsetCount
= 0;
712 visitedNodeOffsets
[visitedNodeOffsetCount
++] = 0;
713 const uint8_t* p
= start
;
715 uint64_t terminalSize
= *p
++;
716 if ( terminalSize
> 127 ) {
717 // except for re-export-with-rename, all terminal sizes fit in one byte
719 terminalSize
= read_uleb128(diag
, p
, end
);
720 if ( diag
.hasError() )
723 if ( (*symbol
== '\0') && (terminalSize
!= 0) ) {
726 const uint8_t* children
= p
+ terminalSize
;
727 if ( children
> end
) {
728 //diag.error("malformed trie node, terminalSize=0x%llX extends past end of trie\n", terminalSize);
731 uint8_t childrenRemaining
= *children
++;
733 uint64_t nodeOffset
= 0;
734 for (; childrenRemaining
> 0; --childrenRemaining
) {
735 const char* ss
= symbol
;
736 bool wrongEdge
= false;
737 // scan whole edge to get to next edge
738 // if edge is longer than target symbol name, don't read past end of symbol name
740 while ( c
!= '\0' ) {
750 // advance to next child
751 ++p
; // skip over zero terminator
752 // skip over uleb128 until last byte is found
753 while ( (*p
& 0x80) != 0 )
755 ++p
; // skip over last byte of uleb128
757 diag
.error("malformed trie node, child node extends past end of trie\n");
762 // the symbol so far matches this edge (child)
763 // so advance to the child's node
765 nodeOffset
= read_uleb128(diag
, p
, end
);
766 if ( diag
.hasError() )
768 if ( (nodeOffset
== 0) || ( &start
[nodeOffset
] > end
) ) {
769 diag
.error("malformed trie child, nodeOffset=0x%llX out of range\n", nodeOffset
);
776 if ( nodeOffset
!= 0 ) {
777 if ( nodeOffset
> (uint64_t)(end
-start
) ) {
778 diag
.error("malformed trie child, nodeOffset=0x%llX out of range\n", nodeOffset
);
781 for (int i
=0; i
< visitedNodeOffsetCount
; ++i
) {
782 if ( visitedNodeOffsets
[i
] == nodeOffset
) {
783 diag
.error("malformed trie child, cycle to nodeOffset=0x%llX\n", nodeOffset
);
787 visitedNodeOffsets
[visitedNodeOffsetCount
++] = (uint32_t)nodeOffset
;
788 if ( visitedNodeOffsetCount
>= 128 ) {
789 diag
.error("malformed trie too deep\n");
792 p
= &start
[nodeOffset
];
800 void MachOLoaded::forEachCDHashOfCodeSignature(const void* codeSigStart
, size_t codeSignLen
,
801 void (^callback
)(const uint8_t cdHash
[20])) const
803 forEachCodeDirectoryBlob(codeSigStart
, codeSignLen
, ^(const void *cdBuffer
) {
804 const CS_CodeDirectory
* cd
= (const CS_CodeDirectory
*)cdBuffer
;
805 uint32_t cdLength
= htonl(cd
->length
);
807 if ( cd
->hashType
== CS_HASHTYPE_SHA384
) {
808 uint8_t digest
[CCSHA384_OUTPUT_SIZE
];
809 const struct ccdigest_info
* di
= ccsha384_di();
810 ccdigest_di_decl(di
, tempBuf
); // declares tempBuf array in stack
811 ccdigest_init(di
, tempBuf
);
812 ccdigest_update(di
, tempBuf
, cdLength
, cd
);
813 ccdigest_final(di
, tempBuf
, digest
);
814 ccdigest_di_clear(di
, tempBuf
);
815 // cd-hash of sigs that use SHA384 is the first 20 bytes of the SHA384 of the code digest
816 memcpy(cdHash
, digest
, 20);
820 else if ( (cd
->hashType
== CS_HASHTYPE_SHA256
) || (cd
->hashType
== CS_HASHTYPE_SHA256_TRUNCATED
) ) {
821 uint8_t digest
[CCSHA256_OUTPUT_SIZE
];
822 const struct ccdigest_info
* di
= ccsha256_di();
823 ccdigest_di_decl(di
, tempBuf
); // declares tempBuf array in stack
824 ccdigest_init(di
, tempBuf
);
825 ccdigest_update(di
, tempBuf
, cdLength
, cd
);
826 ccdigest_final(di
, tempBuf
, digest
);
827 ccdigest_di_clear(di
, tempBuf
);
828 // cd-hash of sigs that use SHA256 is the first 20 bytes of the SHA256 of the code digest
829 memcpy(cdHash
, digest
, 20);
833 else if ( cd
->hashType
== CS_HASHTYPE_SHA1
) {
834 // compute hash directly into return buffer
835 const struct ccdigest_info
* di
= ccsha1_di();
836 ccdigest_di_decl(di
, tempBuf
); // declares tempBuf array in stack
837 ccdigest_init(di
, tempBuf
);
838 ccdigest_update(di
, tempBuf
, cdLength
, cd
);
839 ccdigest_final(di
, tempBuf
, cdHash
);
840 ccdigest_di_clear(di
, tempBuf
);
848 // Note, this has to match the kernel
849 static const uint32_t hashPriorities
[] = {
851 CS_HASHTYPE_SHA256_TRUNCATED
,
856 static unsigned int hash_rank(const CS_CodeDirectory
*cd
)
858 uint32_t type
= cd
->hashType
;
859 for (uint32_t n
= 0; n
< sizeof(hashPriorities
) / sizeof(hashPriorities
[0]); ++n
) {
860 if (hashPriorities
[n
] == type
)
868 // Note, this does NOT match the kernel.
869 // On watchOS, in main executables, we will record all cd hashes then make sure
870 // one of the ones we record matches the kernel.
871 // This list is only for dylibs where we embed the cd hash in the closure instead of the
872 // mod time and inode
873 // This is sorted so that we choose sha1 first when checking dylibs
874 static const uint32_t hashPriorities_watchOS_dylibs
[] = {
875 CS_HASHTYPE_SHA256_TRUNCATED
,
881 static unsigned int hash_rank_watchOS_dylibs(const CS_CodeDirectory
*cd
)
883 uint32_t type
= cd
->hashType
;
884 for (uint32_t n
= 0; n
< sizeof(hashPriorities_watchOS_dylibs
) / sizeof(hashPriorities_watchOS_dylibs
[0]); ++n
) {
885 if (hashPriorities_watchOS_dylibs
[n
] == type
)
893 // This calls the callback for all code directories required for a given platform/binary combination.
894 // On watchOS main executables this is all cd hashes.
895 // On watchOS dylibs this is only the single cd hash we need (by rank defined by dyld, not the kernel).
896 // On all other platforms this always returns a single best cd hash (ranked to match the kernel).
897 // Note the callback parameter is really a CS_CodeDirectory.
898 void MachOLoaded::forEachCodeDirectoryBlob(const void* codeSigStart
, size_t codeSignLen
,
899 void (^callback
)(const void* cd
)) const
901 // verify min length of overall code signature
902 if ( codeSignLen
< sizeof(CS_SuperBlob
) )
905 // verify magic at start
906 const CS_SuperBlob
* codeSuperBlob
= (CS_SuperBlob
*)codeSigStart
;
907 if ( codeSuperBlob
->magic
!= htonl(CSMAGIC_EMBEDDED_SIGNATURE
) )
910 // verify count of sub-blobs not too large
911 uint32_t subBlobCount
= htonl(codeSuperBlob
->count
);
912 if ( (codeSignLen
-sizeof(CS_SuperBlob
))/sizeof(CS_BlobIndex
) < subBlobCount
)
915 // Note: The kernel sometimes chooses sha1 on watchOS, and sometimes sha256.
916 // Embed all of them so that we just need to match any of them
917 const bool isWatchOS
= this->supportsPlatform(Platform::watchOS
);
918 const bool isMainExecutable
= this->isMainExecutable();
919 auto hashRankFn
= isWatchOS
? &hash_rank_watchOS_dylibs
: &hash_rank
;
921 // walk each sub blob, looking at ones with type CSSLOT_CODEDIRECTORY
922 const CS_CodeDirectory
* bestCd
= nullptr;
923 for (uint32_t i
=0; i
< subBlobCount
; ++i
) {
924 if ( codeSuperBlob
->index
[i
].type
== htonl(CSSLOT_CODEDIRECTORY
) ) {
925 // Ok, this is the regular code directory
926 } else if ( codeSuperBlob
->index
[i
].type
>= htonl(CSSLOT_ALTERNATE_CODEDIRECTORIES
) && codeSuperBlob
->index
[i
].type
<= htonl(CSSLOT_ALTERNATE_CODEDIRECTORY_LIMIT
)) {
927 // Ok, this is the alternative code directory
931 uint32_t cdOffset
= htonl(codeSuperBlob
->index
[i
].offset
);
932 // verify offset is not out of range
933 if ( cdOffset
> (codeSignLen
- sizeof(CS_CodeDirectory
)) )
935 const CS_CodeDirectory
* cd
= (CS_CodeDirectory
*)((uint8_t*)codeSuperBlob
+ cdOffset
);
936 uint32_t cdLength
= htonl(cd
->length
);
937 // verify code directory length not out of range
938 if ( cdLength
> (codeSignLen
- cdOffset
) )
941 // The watch main executable wants to know about all cd hashes
942 if ( isWatchOS
&& isMainExecutable
) {
947 if ( cd
->magic
== htonl(CSMAGIC_CODEDIRECTORY
) ) {
948 if ( !bestCd
|| (hashRankFn(cd
) > hashRankFn(bestCd
)) )
953 // Note this callback won't happen on watchOS as that one was done in the loop
954 if ( bestCd
!= nullptr )
959 uint64_t MachOLoaded::ChainedFixupPointerOnDisk::Arm64e::unpackTarget() const
961 assert(this->authBind
.bind
== 0);
962 assert(this->authBind
.auth
== 0);
963 return ((uint64_t)(this->rebase
.high8
) << 56) | (this->rebase
.target
);
966 uint64_t MachOLoaded::ChainedFixupPointerOnDisk::Arm64e::signExtendedAddend() const
968 assert(this->authBind
.bind
== 1);
969 assert(this->authBind
.auth
== 0);
970 uint64_t addend19
= this->bind
.addend
;
971 if ( addend19
& 0x40000 )
972 return addend19
| 0xFFFFFFFFFFFC0000ULL
;
977 const char* MachOLoaded::ChainedFixupPointerOnDisk::Arm64e::keyName() const
979 static const char* names
[] = {
980 "IA", "IB", "DA", "DB"
982 assert(this->authBind
.auth
== 1);
983 uint8_t keyBits
= this->authBind
.key
;
985 return names
[keyBits
];
988 uint64_t MachOLoaded::ChainedFixupPointerOnDisk::Arm64e::signPointer(void* loc
, uint64_t target
) const
990 assert(this->authBind
.auth
== 1);
991 #if __has_feature(ptrauth_calls)
992 uint64_t discriminator
= authBind
.diversity
;
993 if ( authBind
.addrDiv
)
994 discriminator
= __builtin_ptrauth_blend_discriminator(loc
, discriminator
);
995 switch ( authBind
.key
) {
997 return (uint64_t)__builtin_ptrauth_sign_unauthenticated((void*)target
, 0, discriminator
);
999 return (uint64_t)__builtin_ptrauth_sign_unauthenticated((void*)target
, 1, discriminator
);
1001 return (uint64_t)__builtin_ptrauth_sign_unauthenticated((void*)target
, 2, discriminator
);
1003 return (uint64_t)__builtin_ptrauth_sign_unauthenticated((void*)target
, 3, discriminator
);
1009 uint64_t MachOLoaded::ChainedFixupPointerOnDisk::Generic64::unpackedTarget() const
1011 return (((uint64_t)this->rebase
.high8
) << 56) | (uint64_t)(this->rebase
.target
);
1014 uint64_t MachOLoaded::ChainedFixupPointerOnDisk::Generic64::signExtendedAddend() const
1016 uint64_t addend27
= this->bind
.addend
;
1017 uint64_t top8Bits
= addend27
& 0x00007F80000ULL
;
1018 uint64_t bottom19Bits
= addend27
& 0x0000007FFFFULL
;
1019 uint64_t newValue
= (top8Bits
<< 13) | (((uint64_t)(bottom19Bits
<< 37) >> 37) & 0x00FFFFFFFFFFFFFF);
1023 bool MachOLoaded::ChainedFixupPointerOnDisk::isRebase(uint16_t pointerFormat
, uint64_t preferedLoadAddress
, uint64_t& targetRuntimeOffset
) const
1025 switch (pointerFormat
) {
1026 case DYLD_CHAINED_PTR_ARM64E
:
1027 if ( this->arm64e
.bind
.bind
)
1029 if ( this->arm64e
.authRebase
.auth
) {
1030 targetRuntimeOffset
= this->arm64e
.authRebase
.target
;
1034 targetRuntimeOffset
= this->arm64e
.unpackTarget() - preferedLoadAddress
;
1038 case DYLD_CHAINED_PTR_ARM64E_OFFSET
:
1039 case DYLD_CHAINED_PTR_ARM64E_USERLAND
:
1040 if ( this->arm64e
.bind
.bind
)
1042 if ( this->arm64e
.authRebase
.auth
) {
1043 targetRuntimeOffset
= this->arm64e
.authRebase
.target
;
1047 targetRuntimeOffset
= this->arm64e
.unpackTarget();
1051 case DYLD_CHAINED_PTR_64
:
1052 if ( this->generic64
.bind
.bind
)
1054 targetRuntimeOffset
= this->generic64
.unpackedTarget() - preferedLoadAddress
;
1057 case DYLD_CHAINED_PTR_64_OFFSET
:
1058 if ( this->generic64
.bind
.bind
)
1060 targetRuntimeOffset
= this->generic64
.unpackedTarget();
1063 case DYLD_CHAINED_PTR_32
:
1064 if ( this->generic32
.bind
.bind
)
1066 targetRuntimeOffset
= this->generic32
.rebase
.target
- preferedLoadAddress
;
1072 assert(0 && "unsupported pointer chain format");
1075 bool MachOLoaded::ChainedFixupPointerOnDisk::isBind(uint16_t pointerFormat
, uint32_t& bindOrdinal
) const
1077 switch (pointerFormat
) {
1078 case DYLD_CHAINED_PTR_ARM64E
:
1079 case DYLD_CHAINED_PTR_ARM64E_OFFSET
:
1080 case DYLD_CHAINED_PTR_ARM64E_USERLAND
:
1081 if ( !this->arm64e
.authBind
.bind
)
1083 if ( this->arm64e
.authBind
.auth
) {
1084 bindOrdinal
= this->arm64e
.authBind
.ordinal
;
1088 bindOrdinal
= this->arm64e
.bind
.ordinal
;
1092 case DYLD_CHAINED_PTR_64
:
1093 case DYLD_CHAINED_PTR_64_OFFSET
:
1094 if ( !this->generic64
.bind
.bind
)
1096 bindOrdinal
= this->generic64
.bind
.ordinal
;
1099 case DYLD_CHAINED_PTR_32
:
1100 if ( !this->generic32
.bind
.bind
)
1102 bindOrdinal
= this->generic32
.bind
.ordinal
;
1108 assert(0 && "unsupported pointer chain format");
1111 #if BUILDING_DYLD || BUILDING_LIBDYLD
1112 void MachOLoaded::fixupAllChainedFixups(Diagnostics
& diag
, const dyld_chained_starts_in_image
* starts
, uintptr_t slide
,
1113 Array
<const void*> bindTargets
, void (^logFixup
)(void* loc
, void* newValue
)) const
1115 forEachFixupInAllChains(diag
, starts
, true, ^(ChainedFixupPointerOnDisk
* fixupLoc
, const dyld_chained_starts_in_segment
* segInfo
, bool& stop
) {
1117 switch (segInfo
->pointer_format
) {
1119 #if __has_feature(ptrauth_calls)
1120 case DYLD_CHAINED_PTR_ARM64E
:
1121 if ( fixupLoc
->arm64e
.authRebase
.auth
) {
1122 if ( fixupLoc
->arm64e
.authBind
.bind
) {
1123 if ( fixupLoc
->arm64e
.authBind
.ordinal
>= bindTargets
.count() ) {
1124 diag
.error("out of range bind ordinal %d (max %lu)", fixupLoc
->arm64e
.authBind
.ordinal
, bindTargets
.count());
1129 // authenticated bind
1130 newValue
= (void*)(bindTargets
[fixupLoc
->arm64e
.bind
.ordinal
]);
1131 if (newValue
!= 0) // Don't sign missing weak imports
1132 newValue
= (void*)fixupLoc
->arm64e
.signPointer(fixupLoc
, (uintptr_t)newValue
);
1136 // authenticated rebase
1137 newValue
= (void*)fixupLoc
->arm64e
.signPointer(fixupLoc
, (uintptr_t)this + fixupLoc
->arm64e
.authRebase
.target
);
1141 if ( fixupLoc
->arm64e
.bind
.bind
) {
1142 if ( fixupLoc
->arm64e
.bind
.ordinal
>= bindTargets
.count() ) {
1143 diag
.error("out of range bind ordinal %d (max %lu)", fixupLoc
->arm64e
.bind
.ordinal
, bindTargets
.count());
1149 newValue
= (void*)((long)bindTargets
[fixupLoc
->arm64e
.bind
.ordinal
] + fixupLoc
->arm64e
.signExtendedAddend());
1154 newValue
= (void*)(fixupLoc
->arm64e
.unpackTarget()+slide
);
1158 logFixup(fixupLoc
, newValue
);
1159 fixupLoc
->raw64
= (uintptr_t)newValue
;
1161 case DYLD_CHAINED_PTR_ARM64E_OFFSET
:
1162 case DYLD_CHAINED_PTR_ARM64E_USERLAND
:
1163 if ( fixupLoc
->arm64e
.authRebase
.auth
) {
1164 if ( fixupLoc
->arm64e
.authBind
.bind
) {
1165 if ( fixupLoc
->arm64e
.authBind
.ordinal
>= bindTargets
.count() ) {
1166 diag
.error("out of range bind ordinal %d (max %lu)", fixupLoc
->arm64e
.authBind
.ordinal
, bindTargets
.count());
1171 // authenticated bind
1172 newValue
= (void*)(bindTargets
[fixupLoc
->arm64e
.bind
.ordinal
]);
1173 if (newValue
!= 0) // Don't sign missing weak imports
1174 newValue
= (void*)fixupLoc
->arm64e
.signPointer(fixupLoc
, (uintptr_t)newValue
);
1178 // authenticated rebase
1179 newValue
= (void*)fixupLoc
->arm64e
.signPointer(fixupLoc
, (uintptr_t)this + fixupLoc
->arm64e
.authRebase
.target
);
1183 if ( fixupLoc
->arm64e
.bind
.bind
) {
1184 if ( fixupLoc
->arm64e
.bind
.ordinal
>= bindTargets
.count() ) {
1185 diag
.error("out of range bind ordinal %d (max %lu)", fixupLoc
->arm64e
.bind
.ordinal
, bindTargets
.count());
1191 newValue
= (void*)((long)bindTargets
[fixupLoc
->arm64e
.bind
.ordinal
] + fixupLoc
->arm64e
.signExtendedAddend());
1196 newValue
= (void*)((uintptr_t)this + fixupLoc
->arm64e
.unpackTarget());
1200 logFixup(fixupLoc
, newValue
);
1201 fixupLoc
->raw64
= (uintptr_t)newValue
;
1204 case DYLD_CHAINED_PTR_64
:
1205 if ( fixupLoc
->generic64
.bind
.bind
) {
1206 if ( fixupLoc
->generic64
.bind
.ordinal
>= bindTargets
.count() ) {
1207 diag
.error("out of range bind ordinal %d (max %lu)", fixupLoc
->generic64
.bind
.ordinal
, bindTargets
.count());
1212 newValue
= (void*)((long)bindTargets
[fixupLoc
->generic64
.bind
.ordinal
] + fixupLoc
->generic64
.signExtendedAddend());
1216 newValue
= (void*)(fixupLoc
->generic64
.unpackedTarget()+slide
);
1219 logFixup(fixupLoc
, newValue
);
1220 fixupLoc
->raw64
= (uintptr_t)newValue
;
1222 case DYLD_CHAINED_PTR_64_OFFSET
:
1223 if ( fixupLoc
->generic64
.bind
.bind
) {
1224 if ( fixupLoc
->generic64
.bind
.ordinal
>= bindTargets
.count() ) {
1225 diag
.error("out of range bind ordinal %d (max %lu)", fixupLoc
->generic64
.bind
.ordinal
, bindTargets
.count());
1230 newValue
= (void*)((long)bindTargets
[fixupLoc
->generic64
.bind
.ordinal
] + fixupLoc
->generic64
.signExtendedAddend());
1234 newValue
= (void*)((uintptr_t)this + fixupLoc
->generic64
.unpackedTarget());
1237 logFixup(fixupLoc
, newValue
);
1238 fixupLoc
->raw64
= (uintptr_t)newValue
;
1241 case DYLD_CHAINED_PTR_32
:
1242 if ( fixupLoc
->generic32
.bind
.bind
) {
1243 if ( fixupLoc
->generic32
.bind
.ordinal
>= bindTargets
.count() ) {
1244 diag
.error("out of range bind ordinal %d (max %lu)", fixupLoc
->generic32
.bind
.ordinal
, bindTargets
.count());
1249 newValue
= (void*)((long)bindTargets
[fixupLoc
->generic32
.bind
.ordinal
] + fixupLoc
->generic32
.bind
.addend
);
1253 if ( fixupLoc
->generic32
.rebase
.target
> segInfo
->max_valid_pointer
) {
1254 // handle non-pointers in chain
1255 uint32_t bias
= (0x04000000 + segInfo
->max_valid_pointer
)/2;
1256 newValue
= (void*)(fixupLoc
->generic32
.rebase
.target
- bias
);
1259 newValue
= (void*)(fixupLoc
->generic32
.rebase
.target
+ slide
);
1263 logFixup(fixupLoc
, newValue
);
1264 fixupLoc
->raw32
= (uint32_t)(uintptr_t)newValue
;
1268 diag
.error("unsupported pointer chain format: 0x%04X", segInfo
->pointer_format
);
1276 bool MachOLoaded::walkChain(Diagnostics
& diag
, const dyld_chained_starts_in_segment
* segInfo
, uint32_t pageIndex
, uint16_t offsetInPage
,
1277 bool notifyNonPointers
, void (^handler
)(ChainedFixupPointerOnDisk
* fixupLocation
, const dyld_chained_starts_in_segment
* segInfo
, bool& stop
)) const
1280 uint8_t* pageContentStart
= (uint8_t*)this + segInfo
->segment_offset
+ (pageIndex
* segInfo
->page_size
);
1281 ChainedFixupPointerOnDisk
* chain
= (ChainedFixupPointerOnDisk
*)(pageContentStart
+offsetInPage
);
1282 bool chainEnd
= false;
1283 while (!stop
&& !chainEnd
) {
1284 // copy chain content, in case handler modifies location to final value
1285 ChainedFixupPointerOnDisk chainContent
= *chain
;
1286 handler(chain
, segInfo
, stop
);
1288 switch (segInfo
->pointer_format
) {
1289 case DYLD_CHAINED_PTR_ARM64E
:
1290 case DYLD_CHAINED_PTR_ARM64E_USERLAND
:
1291 if ( chainContent
.arm64e
.rebase
.next
== 0 )
1294 chain
= (ChainedFixupPointerOnDisk
*)((uint8_t*)chain
+ chainContent
.arm64e
.rebase
.next
*8);
1296 case DYLD_CHAINED_PTR_64
:
1297 case DYLD_CHAINED_PTR_64_OFFSET
:
1298 case DYLD_CHAINED_PTR_ARM64E_OFFSET
:
1299 if ( chainContent
.generic64
.rebase
.next
== 0 )
1302 chain
= (ChainedFixupPointerOnDisk
*)((uint8_t*)chain
+ chainContent
.generic64
.rebase
.next
*4);
1304 case DYLD_CHAINED_PTR_32
:
1305 if ( chainContent
.generic32
.rebase
.next
== 0 )
1308 chain
= (ChainedFixupPointerOnDisk
*)((uint8_t*)chain
+ chainContent
.generic32
.rebase
.next
*4);
1309 if ( !notifyNonPointers
) {
1310 while ( (chain
->generic32
.rebase
.bind
== 0) && (chain
->generic32
.rebase
.target
> segInfo
->max_valid_pointer
) ) {
1311 // not a real pointer, but a non-pointer co-opted into chain
1312 chain
= (ChainedFixupPointerOnDisk
*)((uint8_t*)chain
+ chain
->generic32
.rebase
.next
*4);
1318 diag
.error("unknown pointer format 0x%04X", segInfo
->pointer_format
);
1326 void MachOLoaded::forEachFixupInAllChains(Diagnostics
& diag
, const dyld_chained_starts_in_image
* starts
, bool notifyNonPointers
,
1327 void (^handler
)(ChainedFixupPointerOnDisk
* fixupLocation
, const dyld_chained_starts_in_segment
* segInfo
, bool& stop
)) const
1329 bool stopped
= false;
1330 for (uint32_t segIndex
=0; segIndex
< starts
->seg_count
&& !stopped
; ++segIndex
) {
1331 if ( starts
->seg_info_offset
[segIndex
] == 0 )
1333 const dyld_chained_starts_in_segment
* segInfo
= (dyld_chained_starts_in_segment
*)((uint8_t*)starts
+ starts
->seg_info_offset
[segIndex
]);
1334 for (uint32_t pageIndex
=0; pageIndex
< segInfo
->page_count
&& !stopped
; ++pageIndex
) {
1335 uint16_t offsetInPage
= segInfo
->page_start
[pageIndex
];
1336 if ( offsetInPage
== DYLD_CHAINED_PTR_START_NONE
)
1338 if ( offsetInPage
& DYLD_CHAINED_PTR_START_MULTI
) {
1339 // 32-bit chains which may need multiple starts per page
1340 uint32_t overflowIndex
= offsetInPage
& ~DYLD_CHAINED_PTR_START_MULTI
;
1341 bool chainEnd
= false;
1342 while (!stopped
&& !chainEnd
) {
1343 chainEnd
= (segInfo
->page_start
[overflowIndex
] & DYLD_CHAINED_PTR_START_LAST
);
1344 offsetInPage
= (segInfo
->page_start
[overflowIndex
] & ~DYLD_CHAINED_PTR_START_LAST
);
1345 if ( walkChain(diag
, segInfo
, pageIndex
, offsetInPage
, notifyNonPointers
, handler
) )
1351 // one chain per page
1352 walkChain(diag
, segInfo
, pageIndex
, offsetInPage
, notifyNonPointers
, handler
);
1359 } // namespace dyld3