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
;
214 result
.lastSegIndex
= info
.segIndex
;
218 bool MachOLoaded::hasExportTrie(uint32_t& runtimeOffset
, uint32_t& size
) const
224 getLinkEditPointers(diag
, leInfo
);
225 diag
.assertNoError(); // any malformations in the file should have been caught by earlier validate() call
226 if ( diag
.hasError() )
229 if ( const uint8_t* trie
= getExportsTrie(leInfo
, trieSize
) ) {
230 runtimeOffset
= (uint32_t)(trie
- (uint8_t*)this);
231 size
= (uint32_t)trieSize
;
239 // this is only used by dlsym() at runtime. All other binding is done when the closure is built.
240 bool MachOLoaded::hasExportedSymbol(const char* symbolName
, DependentToMachOLoaded finder
, void** result
,
241 bool* resultPointsToInstructions
) const
243 typedef void* (*ResolverFunc
)(void);
244 ResolverFunc resolver
;
246 FoundSymbol foundInfo
;
247 if ( findExportedSymbol(diag
, symbolName
, false, foundInfo
, finder
) ) {
248 switch ( foundInfo
.kind
) {
249 case FoundSymbol::Kind::headerOffset
: {
250 *result
= (uint8_t*)foundInfo
.foundInDylib
+ foundInfo
.value
;
251 *resultPointsToInstructions
= false;
252 int64_t slide
= foundInfo
.foundInDylib
->getSlide();
253 foundInfo
.foundInDylib
->forEachSection(^(const SectionInfo
& sectInfo
, bool malformedSectionRange
, bool& stop
) {
254 uint64_t sectStartAddr
= sectInfo
.sectAddr
+ slide
;
255 uint64_t sectEndAddr
= sectStartAddr
+ sectInfo
.sectSize
;
256 if ( ((uint64_t)*result
>= sectStartAddr
) && ((uint64_t)*result
< sectEndAddr
) ) {
257 *resultPointsToInstructions
= (sectInfo
.sectFlags
& S_ATTR_PURE_INSTRUCTIONS
) || (sectInfo
.sectFlags
& S_ATTR_SOME_INSTRUCTIONS
);
263 case FoundSymbol::Kind::absolute
:
264 *result
= (void*)(long)foundInfo
.value
;
265 *resultPointsToInstructions
= false;
267 case FoundSymbol::Kind::resolverOffset
:
268 // foundInfo.value contains "stub".
269 // in dlsym() we want to call resolver function to get final function address
270 resolver
= (ResolverFunc
)((uint8_t*)foundInfo
.foundInDylib
+ foundInfo
.resolverFuncOffset
);
271 *result
= (*resolver
)();
272 // FIXME: Set this properly
273 *resultPointsToInstructions
= true;
280 #endif // BUILDING_LIBDYLD
282 bool MachOLoaded::findExportedSymbol(Diagnostics
& diag
, const char* symbolName
, bool weakImport
, FoundSymbol
& foundInfo
, DependentToMachOLoaded findDependent
) const
285 getLinkEditPointers(diag
, leInfo
);
286 if ( diag
.hasError() )
289 if ( const uint8_t* trieStart
= getExportsTrie(leInfo
, trieSize
) ) {
290 const uint8_t* trieEnd
= trieStart
+ trieSize
;
291 const uint8_t* node
= trieWalk(diag
, trieStart
, trieEnd
, symbolName
);
292 if ( node
== nullptr ) {
293 // symbol not exported from this image. Seach any re-exported dylibs
294 __block
unsigned depIndex
= 0;
295 __block
bool foundInReExportedDylib
= false;
296 forEachDependentDylib(^(const char* loadPath
, bool isWeak
, bool isReExport
, bool isUpward
, uint32_t compatVersion
, uint32_t curVersion
, bool& stop
) {
297 if ( isReExport
&& findDependent
) {
298 if ( const MachOLoaded
* depMH
= findDependent(this, depIndex
) ) {
299 if ( depMH
->findExportedSymbol(diag
, symbolName
, weakImport
, foundInfo
, findDependent
) ) {
301 foundInReExportedDylib
= true;
307 return foundInReExportedDylib
;
309 const uint8_t* p
= node
;
310 const uint64_t flags
= read_uleb128(diag
, p
, trieEnd
);
311 if ( flags
& EXPORT_SYMBOL_FLAGS_REEXPORT
) {
312 if ( !findDependent
)
314 // re-export from another dylib, lookup there
315 const uint64_t ordinal
= read_uleb128(diag
, p
, trieEnd
);
316 const char* importedName
= (char*)p
;
317 if ( importedName
[0] == '\0' )
318 importedName
= symbolName
;
319 if ( (ordinal
== 0) || (ordinal
> dependentDylibCount()) ) {
320 diag
.error("re-export ordinal %lld out of range for %s", ordinal
, symbolName
);
323 uint32_t depIndex
= (uint32_t)(ordinal
-1);
324 if ( const MachOLoaded
* depMH
= findDependent(this, depIndex
) ) {
325 return depMH
->findExportedSymbol(diag
, importedName
, weakImport
, foundInfo
, findDependent
);
327 else if (weakImport
) {
331 diag
.error("dependent dylib %lld not found for re-exported symbol %s", ordinal
, symbolName
);
335 foundInfo
.kind
= FoundSymbol::Kind::headerOffset
;
336 foundInfo
.isThreadLocal
= false;
337 foundInfo
.isWeakDef
= false;
338 foundInfo
.foundInDylib
= this;
339 foundInfo
.value
= read_uleb128(diag
, p
, trieEnd
);
340 foundInfo
.resolverFuncOffset
= 0;
341 foundInfo
.foundSymbolName
= symbolName
;
342 if ( diag
.hasError() )
344 switch ( flags
& EXPORT_SYMBOL_FLAGS_KIND_MASK
) {
345 case EXPORT_SYMBOL_FLAGS_KIND_REGULAR
:
346 if ( flags
& EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER
) {
347 foundInfo
.kind
= FoundSymbol::Kind::headerOffset
;
348 foundInfo
.resolverFuncOffset
= (uint32_t)read_uleb128(diag
, p
, trieEnd
);
351 foundInfo
.kind
= FoundSymbol::Kind::headerOffset
;
353 if ( flags
& EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION
)
354 foundInfo
.isWeakDef
= true;
356 case EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL
:
357 foundInfo
.isThreadLocal
= true;
359 case EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE
:
360 foundInfo
.kind
= FoundSymbol::Kind::absolute
;
363 diag
.error("unsupported exported symbol kind. flags=%llu at node offset=0x%0lX", flags
, (long)(node
-trieStart
));
369 // this is an old binary (before macOS 10.6), scan the symbol table
370 foundInfo
.foundInDylib
= nullptr;
371 forEachGlobalSymbol(diag
, ^(const char* aSymbolName
, uint64_t n_value
, uint8_t n_type
, uint8_t n_sect
, uint16_t n_desc
, bool& stop
) {
372 if ( strcmp(aSymbolName
, symbolName
) == 0 ) {
373 foundInfo
.kind
= FoundSymbol::Kind::headerOffset
;
374 foundInfo
.isThreadLocal
= false;
375 foundInfo
.foundInDylib
= this;
376 foundInfo
.value
= n_value
- leInfo
.layout
.textUnslidVMAddr
;
377 foundInfo
.resolverFuncOffset
= 0;
378 foundInfo
.foundSymbolName
= symbolName
;
382 if ( foundInfo
.foundInDylib
== nullptr ) {
383 // symbol not exported from this image. Search any re-exported dylibs
384 __block
unsigned depIndex
= 0;
385 forEachDependentDylib(^(const char* loadPath
, bool isWeak
, bool isReExport
, bool isUpward
, uint32_t compatVersion
, uint32_t curVersion
, bool& stop
) {
386 if ( isReExport
&& findDependent
) {
387 if ( const MachOLoaded
* depMH
= findDependent(this, depIndex
) ) {
388 if ( depMH
->findExportedSymbol(diag
, symbolName
, weakImport
, foundInfo
, findDependent
) ) {
396 return (foundInfo
.foundInDylib
!= nullptr);
400 intptr_t MachOLoaded::getSlide() const
403 __block
intptr_t slide
= 0;
404 forEachLoadCommand(diag
, ^(const load_command
* cmd
, bool& stop
) {
405 if ( cmd
->cmd
== LC_SEGMENT_64
) {
406 const segment_command_64
* seg
= (segment_command_64
*)cmd
;
407 if ( strcmp(seg
->segname
, "__TEXT") == 0 ) {
408 slide
= (uintptr_t)(((uint64_t)this) - seg
->vmaddr
);
412 else if ( cmd
->cmd
== LC_SEGMENT
) {
413 const segment_command
* seg
= (segment_command
*)cmd
;
414 if ( strcmp(seg
->segname
, "__TEXT") == 0 ) {
415 slide
= (uintptr_t)(((uint64_t)this) - seg
->vmaddr
);
420 diag
.assertNoError(); // any malformations in the file should have been caught by earlier validate() call
424 const uint8_t* MachOLoaded::getLinkEditContent(const LayoutInfo
& info
, uint32_t fileOffset
) const
426 uint32_t offsetInLinkedit
= fileOffset
- info
.linkeditFileOffset
;
427 uintptr_t linkeditStartAddr
= info
.linkeditUnslidVMAddr
+ info
.slide
;
428 return (uint8_t*)(linkeditStartAddr
+ offsetInLinkedit
);
432 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
435 getLinkEditPointers(diag
, leInfo
);
436 if ( diag
.hasError() )
439 const bool is64Bit
= is64();
440 if ( leInfo
.symTab
!= nullptr ) {
441 uint32_t globalsStartIndex
= 0;
442 uint32_t globalsCount
= leInfo
.symTab
->nsyms
;
443 if ( leInfo
.dynSymTab
!= nullptr ) {
444 globalsStartIndex
= leInfo
.dynSymTab
->iextdefsym
;
445 globalsCount
= leInfo
.dynSymTab
->nextdefsym
;
447 uint32_t maxStringOffset
= leInfo
.symTab
->strsize
;
448 const char* stringPool
= (char*)getLinkEditContent(leInfo
.layout
, leInfo
.symTab
->stroff
);
449 const struct nlist
* symbols
= (struct nlist
*) (getLinkEditContent(leInfo
.layout
, leInfo
.symTab
->symoff
));
450 const struct nlist_64
* symbols64
= (struct nlist_64
*)symbols
;
452 for (uint32_t i
=0; (i
< globalsCount
) && !stop
; ++i
) {
454 const struct nlist_64
& sym
= symbols64
[globalsStartIndex
+i
];
455 if ( sym
.n_un
.n_strx
> maxStringOffset
)
457 if ( (sym
.n_type
& N_EXT
) && ((sym
.n_type
& N_TYPE
) == N_SECT
) && ((sym
.n_type
& N_STAB
) == 0) )
458 callback(&stringPool
[sym
.n_un
.n_strx
], sym
.n_value
, sym
.n_type
, sym
.n_sect
, sym
.n_desc
, stop
);
461 const struct nlist
& sym
= symbols
[globalsStartIndex
+i
];
462 if ( sym
.n_un
.n_strx
> maxStringOffset
)
464 if ( (sym
.n_type
& N_EXT
) && ((sym
.n_type
& N_TYPE
) == N_SECT
) && ((sym
.n_type
& N_STAB
) == 0) )
465 callback(&stringPool
[sym
.n_un
.n_strx
], sym
.n_value
, sym
.n_type
, sym
.n_sect
, sym
.n_desc
, stop
);
471 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
474 getLinkEditPointers(diag
, leInfo
);
475 if ( diag
.hasError() )
478 const bool is64Bit
= is64();
479 if ( leInfo
.symTab
!= nullptr ) {
480 uint32_t localsStartIndex
= 0;
481 uint32_t localsCount
= leInfo
.symTab
->nsyms
;
482 if ( leInfo
.dynSymTab
!= nullptr ) {
483 localsStartIndex
= leInfo
.dynSymTab
->ilocalsym
;
484 localsCount
= leInfo
.dynSymTab
->nlocalsym
;
486 uint32_t maxStringOffset
= leInfo
.symTab
->strsize
;
487 const char* stringPool
= (char*)getLinkEditContent(leInfo
.layout
, leInfo
.symTab
->stroff
);
488 const struct nlist
* symbols
= (struct nlist
*) (getLinkEditContent(leInfo
.layout
, leInfo
.symTab
->symoff
));
489 const struct nlist_64
* symbols64
= (struct nlist_64
*)(getLinkEditContent(leInfo
.layout
, leInfo
.symTab
->symoff
));
491 for (uint32_t i
=0; (i
< localsCount
) && !stop
; ++i
) {
493 const struct nlist_64
& sym
= symbols64
[localsStartIndex
+i
];
494 if ( sym
.n_un
.n_strx
> maxStringOffset
)
496 if ( ((sym
.n_type
& N_EXT
) == 0) && ((sym
.n_type
& N_TYPE
) == N_SECT
) && ((sym
.n_type
& N_STAB
) == 0) )
497 callback(&stringPool
[sym
.n_un
.n_strx
], sym
.n_value
, sym
.n_type
, sym
.n_sect
, sym
.n_desc
, stop
);
500 const struct nlist
& sym
= symbols
[localsStartIndex
+i
];
501 if ( sym
.n_un
.n_strx
> maxStringOffset
)
503 if ( ((sym
.n_type
& N_EXT
) == 0) && ((sym
.n_type
& N_TYPE
) == N_SECT
) && ((sym
.n_type
& N_STAB
) == 0) )
504 callback(&stringPool
[sym
.n_un
.n_strx
], sym
.n_value
, sym
.n_type
, sym
.n_sect
, sym
.n_desc
, stop
);
510 uint32_t MachOLoaded::dependentDylibCount() const
512 __block
uint32_t count
= 0;
513 forEachDependentDylib(^(const char* loadPath
, bool isWeak
, bool isReExport
, bool isUpward
, uint32_t compatVersion
, uint32_t curVersion
, bool& stop
) {
519 const char* MachOLoaded::dependentDylibLoadPath(uint32_t depIndex
) const
521 __block
const char* foundLoadPath
= nullptr;
522 __block
uint32_t curDepIndex
= 0;
523 forEachDependentDylib(^(const char* loadPath
, bool isWeak
, bool isReExport
, bool isUpward
, uint32_t compatVersion
, uint32_t curVersion
, bool& stop
) {
524 if ( curDepIndex
== depIndex
) {
525 foundLoadPath
= loadPath
;
530 return foundLoadPath
;
533 const char* MachOLoaded::segmentName(uint32_t targetSegIndex
) const
535 __block
const char* result
= nullptr;
536 forEachSegment(^(const SegmentInfo
& info
, bool& stop
) {
537 if ( targetSegIndex
== info
.segIndex
) {
538 result
= info
.segName
;
545 bool MachOLoaded::findClosestFunctionStart(uint64_t address
, uint64_t* functionStartAddress
) const
549 getLinkEditPointers(diag
, leInfo
);
550 if ( diag
.hasError() )
552 if ( leInfo
.functionStarts
== nullptr )
555 const uint8_t* starts
= getLinkEditContent(leInfo
.layout
, leInfo
.functionStarts
->dataoff
);
556 const uint8_t* startsEnd
= starts
+ leInfo
.functionStarts
->datasize
;
558 uint64_t lastAddr
= (uint64_t)(long)this;
559 uint64_t runningAddr
= lastAddr
;
560 while (diag
.noError()) {
561 uint64_t value
= read_uleb128(diag
, starts
, startsEnd
);
564 lastAddr
= runningAddr
;
565 runningAddr
+= value
;
566 //fprintf(stderr, " addr=0x%08llX\n", runningAddr);
567 if ( runningAddr
> address
) {
568 *functionStartAddress
= lastAddr
;
576 bool MachOLoaded::findClosestSymbol(uint64_t address
, const char** symbolName
, uint64_t* symbolAddr
) const
580 getLinkEditPointers(diag
, leInfo
);
581 if ( diag
.hasError() )
583 if ( (leInfo
.symTab
== nullptr) || (leInfo
.dynSymTab
== nullptr) )
585 uint64_t targetUnslidAddress
= address
- leInfo
.layout
.slide
;
587 // find section index the address is in to validate n_sect
588 __block
uint32_t sectionIndexForTargetAddress
= 0;
589 forEachSection(^(const SectionInfo
& sectInfo
, bool malformedSectionRange
, bool& stop
) {
590 ++sectionIndexForTargetAddress
;
591 if ( (sectInfo
.sectAddr
<= targetUnslidAddress
) && (targetUnslidAddress
< sectInfo
.sectAddr
+sectInfo
.sectSize
) ) {
596 uint32_t maxStringOffset
= leInfo
.symTab
->strsize
;
597 const char* stringPool
= (char*)getLinkEditContent(leInfo
.layout
, leInfo
.symTab
->stroff
);
598 const struct nlist
* symbols
= (struct nlist
*) (getLinkEditContent(leInfo
.layout
, leInfo
.symTab
->symoff
));
600 const struct nlist_64
* symbols64
= (struct nlist_64
*)symbols
;
601 const struct nlist_64
* bestSymbol
= nullptr;
602 // first walk all global symbols
603 const struct nlist_64
* const globalsStart
= &symbols64
[leInfo
.dynSymTab
->iextdefsym
];
604 const struct nlist_64
* const globalsEnd
= &globalsStart
[leInfo
.dynSymTab
->nextdefsym
];
605 for (const struct nlist_64
* s
= globalsStart
; s
< globalsEnd
; ++s
) {
606 if ( (s
->n_type
& N_TYPE
) == N_SECT
) {
607 if ( bestSymbol
== nullptr ) {
608 if ( (s
->n_value
<= targetUnslidAddress
) && (s
->n_sect
== sectionIndexForTargetAddress
) )
611 else if ( (s
->n_value
<= targetUnslidAddress
) && (bestSymbol
->n_value
< s
->n_value
) && (s
->n_sect
== sectionIndexForTargetAddress
) ) {
616 // next walk all local symbols
617 const struct nlist_64
* const localsStart
= &symbols64
[leInfo
.dynSymTab
->ilocalsym
];
618 const struct nlist_64
* const localsEnd
= &localsStart
[leInfo
.dynSymTab
->nlocalsym
];
619 for (const struct nlist_64
* s
= localsStart
; s
< localsEnd
; ++s
) {
620 if ( ((s
->n_type
& N_TYPE
) == N_SECT
) && ((s
->n_type
& N_STAB
) == 0) ) {
621 if ( bestSymbol
== nullptr ) {
622 if ( (s
->n_value
<= targetUnslidAddress
) && (s
->n_sect
== sectionIndexForTargetAddress
) )
625 else if ( (s
->n_value
<= targetUnslidAddress
) && (bestSymbol
->n_value
< s
->n_value
) && (s
->n_sect
== sectionIndexForTargetAddress
) ) {
630 if ( bestSymbol
!= NULL
) {
631 *symbolAddr
= bestSymbol
->n_value
+ leInfo
.layout
.slide
;
632 if ( bestSymbol
->n_un
.n_strx
< maxStringOffset
)
633 *symbolName
= &stringPool
[bestSymbol
->n_un
.n_strx
];
638 const struct nlist
* bestSymbol
= nullptr;
639 // first walk all global symbols
640 const struct nlist
* const globalsStart
= &symbols
[leInfo
.dynSymTab
->iextdefsym
];
641 const struct nlist
* const globalsEnd
= &globalsStart
[leInfo
.dynSymTab
->nextdefsym
];
642 for (const struct nlist
* s
= globalsStart
; s
< globalsEnd
; ++s
) {
643 if ( (s
->n_type
& N_TYPE
) == N_SECT
) {
644 if ( bestSymbol
== nullptr ) {
645 if ( (s
->n_value
<= targetUnslidAddress
) && (s
->n_sect
== sectionIndexForTargetAddress
) )
648 else if ( (s
->n_value
<= targetUnslidAddress
) && (bestSymbol
->n_value
< s
->n_value
) && (s
->n_sect
== sectionIndexForTargetAddress
) ) {
653 // next walk all local symbols
654 const struct nlist
* const localsStart
= &symbols
[leInfo
.dynSymTab
->ilocalsym
];
655 const struct nlist
* const localsEnd
= &localsStart
[leInfo
.dynSymTab
->nlocalsym
];
656 for (const struct nlist
* s
= localsStart
; s
< localsEnd
; ++s
) {
657 if ( ((s
->n_type
& N_TYPE
) == N_SECT
) && ((s
->n_type
& N_STAB
) == 0) ) {
658 if ( bestSymbol
== nullptr ) {
659 if ( (s
->n_value
<= targetUnslidAddress
) && (s
->n_sect
== sectionIndexForTargetAddress
) )
662 else if ( (s
->n_value
<= targetUnslidAddress
) && (bestSymbol
->n_value
< s
->n_value
) && (s
->n_sect
== sectionIndexForTargetAddress
) ) {
667 if ( bestSymbol
!= nullptr ) {
669 if ( bestSymbol
->n_desc
& N_ARM_THUMB_DEF
)
670 *symbolAddr
= (bestSymbol
->n_value
| 1) + leInfo
.layout
.slide
;
672 *symbolAddr
= bestSymbol
->n_value
+ leInfo
.layout
.slide
;
674 *symbolAddr
= bestSymbol
->n_value
+ leInfo
.layout
.slide
;
676 if ( bestSymbol
->n_un
.n_strx
< maxStringOffset
)
677 *symbolName
= &stringPool
[bestSymbol
->n_un
.n_strx
];
685 const void* MachOLoaded::findSectionContent(const char* segName
, const char* sectName
, uint64_t& size
) const
687 __block
const void* result
= nullptr;
688 forEachSection(^(const SectionInfo
& sectInfo
, bool malformedSectionRange
, bool& stop
) {
689 if ( (strcmp(sectInfo
.sectName
, sectName
) == 0) && (strcmp(sectInfo
.segInfo
.segName
, segName
) == 0) ) {
690 size
= sectInfo
.sectSize
;
691 result
= (void*)(sectInfo
.sectAddr
+ getSlide());
698 bool MachOLoaded::intersectsRange(uintptr_t start
, uintptr_t length
) const
700 __block
bool result
= false;
701 uintptr_t slide
= getSlide();
702 forEachSegment(^(const SegmentInfo
& info
, bool& stop
) {
703 if ( (info
.vmAddr
+info
.vmSize
+slide
>= start
) && (info
.vmAddr
+slide
< start
+length
) )
709 const uint8_t* MachOLoaded::trieWalk(Diagnostics
& diag
, const uint8_t* start
, const uint8_t* end
, const char* symbol
)
711 STACK_ALLOC_OVERFLOW_SAFE_ARRAY(uint32_t, visitedNodeOffsets
, 128);
712 visitedNodeOffsets
.push_back(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
);
782 for (uint32_t aVisitedNodeOffset
: visitedNodeOffsets
) {
783 if ( aVisitedNodeOffset
== nodeOffset
) {
784 diag
.error("malformed trie child, cycle to nodeOffset=0x%llX\n", nodeOffset
);
788 visitedNodeOffsets
.push_back((uint32_t)nodeOffset
);
789 p
= &start
[nodeOffset
];
797 void MachOLoaded::forEachCDHashOfCodeSignature(const void* codeSigStart
, size_t codeSignLen
,
798 void (^callback
)(const uint8_t cdHash
[20])) const
800 forEachCodeDirectoryBlob(codeSigStart
, codeSignLen
, ^(const void *cdBuffer
) {
801 const CS_CodeDirectory
* cd
= (const CS_CodeDirectory
*)cdBuffer
;
802 uint32_t cdLength
= htonl(cd
->length
);
804 if ( cd
->hashType
== CS_HASHTYPE_SHA384
) {
805 uint8_t digest
[CCSHA384_OUTPUT_SIZE
];
806 const struct ccdigest_info
* di
= ccsha384_di();
807 ccdigest_di_decl(di
, tempBuf
); // declares tempBuf array in stack
808 ccdigest_init(di
, tempBuf
);
809 ccdigest_update(di
, tempBuf
, cdLength
, cd
);
810 ccdigest_final(di
, tempBuf
, digest
);
811 ccdigest_di_clear(di
, tempBuf
);
812 // cd-hash of sigs that use SHA384 is the first 20 bytes of the SHA384 of the code digest
813 memcpy(cdHash
, digest
, 20);
817 else if ( (cd
->hashType
== CS_HASHTYPE_SHA256
) || (cd
->hashType
== CS_HASHTYPE_SHA256_TRUNCATED
) ) {
818 uint8_t digest
[CCSHA256_OUTPUT_SIZE
];
819 const struct ccdigest_info
* di
= ccsha256_di();
820 ccdigest_di_decl(di
, tempBuf
); // declares tempBuf array in stack
821 ccdigest_init(di
, tempBuf
);
822 ccdigest_update(di
, tempBuf
, cdLength
, cd
);
823 ccdigest_final(di
, tempBuf
, digest
);
824 ccdigest_di_clear(di
, tempBuf
);
825 // cd-hash of sigs that use SHA256 is the first 20 bytes of the SHA256 of the code digest
826 memcpy(cdHash
, digest
, 20);
830 else if ( cd
->hashType
== CS_HASHTYPE_SHA1
) {
831 // compute hash directly into return buffer
832 const struct ccdigest_info
* di
= ccsha1_di();
833 ccdigest_di_decl(di
, tempBuf
); // declares tempBuf array in stack
834 ccdigest_init(di
, tempBuf
);
835 ccdigest_update(di
, tempBuf
, cdLength
, cd
);
836 ccdigest_final(di
, tempBuf
, cdHash
);
837 ccdigest_di_clear(di
, tempBuf
);
845 // Note, this has to match the kernel
846 static const uint32_t hashPriorities
[] = {
848 CS_HASHTYPE_SHA256_TRUNCATED
,
853 static unsigned int hash_rank(const CS_CodeDirectory
*cd
)
855 uint32_t type
= cd
->hashType
;
856 for (uint32_t n
= 0; n
< sizeof(hashPriorities
) / sizeof(hashPriorities
[0]); ++n
) {
857 if (hashPriorities
[n
] == type
)
865 // Note, this does NOT match the kernel.
866 // On watchOS, in main executables, we will record all cd hashes then make sure
867 // one of the ones we record matches the kernel.
868 // This list is only for dylibs where we embed the cd hash in the closure instead of the
869 // mod time and inode
870 // This is sorted so that we choose sha1 first when checking dylibs
871 static const uint32_t hashPriorities_watchOS_dylibs
[] = {
872 CS_HASHTYPE_SHA256_TRUNCATED
,
878 static unsigned int hash_rank_watchOS_dylibs(const CS_CodeDirectory
*cd
)
880 uint32_t type
= cd
->hashType
;
881 for (uint32_t n
= 0; n
< sizeof(hashPriorities_watchOS_dylibs
) / sizeof(hashPriorities_watchOS_dylibs
[0]); ++n
) {
882 if (hashPriorities_watchOS_dylibs
[n
] == type
)
890 // This calls the callback for all code directories required for a given platform/binary combination.
891 // On watchOS main executables this is all cd hashes.
892 // On watchOS dylibs this is only the single cd hash we need (by rank defined by dyld, not the kernel).
893 // On all other platforms this always returns a single best cd hash (ranked to match the kernel).
894 // Note the callback parameter is really a CS_CodeDirectory.
895 void MachOLoaded::forEachCodeDirectoryBlob(const void* codeSigStart
, size_t codeSignLen
,
896 void (^callback
)(const void* cd
)) const
898 // verify min length of overall code signature
899 if ( codeSignLen
< sizeof(CS_SuperBlob
) )
902 // verify magic at start
903 const CS_SuperBlob
* codeSuperBlob
= (CS_SuperBlob
*)codeSigStart
;
904 if ( codeSuperBlob
->magic
!= htonl(CSMAGIC_EMBEDDED_SIGNATURE
) )
907 // verify count of sub-blobs not too large
908 uint32_t subBlobCount
= htonl(codeSuperBlob
->count
);
909 if ( (codeSignLen
-sizeof(CS_SuperBlob
))/sizeof(CS_BlobIndex
) < subBlobCount
)
912 // Note: The kernel sometimes chooses sha1 on watchOS, and sometimes sha256.
913 // Embed all of them so that we just need to match any of them
914 const bool isWatchOS
= this->builtForPlatform(Platform::watchOS
);
915 const bool isMainExecutable
= this->isMainExecutable();
916 auto hashRankFn
= isWatchOS
? &hash_rank_watchOS_dylibs
: &hash_rank
;
918 // walk each sub blob, looking at ones with type CSSLOT_CODEDIRECTORY
919 const CS_CodeDirectory
* bestCd
= nullptr;
920 for (uint32_t i
=0; i
< subBlobCount
; ++i
) {
921 if ( codeSuperBlob
->index
[i
].type
== htonl(CSSLOT_CODEDIRECTORY
) ) {
922 // Ok, this is the regular code directory
923 } else if ( codeSuperBlob
->index
[i
].type
>= htonl(CSSLOT_ALTERNATE_CODEDIRECTORIES
) && codeSuperBlob
->index
[i
].type
<= htonl(CSSLOT_ALTERNATE_CODEDIRECTORY_LIMIT
)) {
924 // Ok, this is the alternative code directory
928 uint32_t cdOffset
= htonl(codeSuperBlob
->index
[i
].offset
);
929 // verify offset is not out of range
930 if ( cdOffset
> (codeSignLen
- sizeof(CS_CodeDirectory
)) )
932 const CS_CodeDirectory
* cd
= (CS_CodeDirectory
*)((uint8_t*)codeSuperBlob
+ cdOffset
);
933 uint32_t cdLength
= htonl(cd
->length
);
934 // verify code directory length not out of range
935 if ( cdLength
> (codeSignLen
- cdOffset
) )
938 // The watch main executable wants to know about all cd hashes
939 if ( isWatchOS
&& isMainExecutable
) {
944 if ( cd
->magic
== htonl(CSMAGIC_CODEDIRECTORY
) ) {
945 if ( !bestCd
|| (hashRankFn(cd
) > hashRankFn(bestCd
)) )
950 // Note this callback won't happen on watchOS as that one was done in the loop
951 if ( bestCd
!= nullptr )
956 uint64_t MachOLoaded::ChainedFixupPointerOnDisk::Arm64e::unpackTarget() const
958 assert(this->authBind
.bind
== 0);
959 assert(this->authBind
.auth
== 0);
960 return ((uint64_t)(this->rebase
.high8
) << 56) | (this->rebase
.target
);
963 uint64_t MachOLoaded::ChainedFixupPointerOnDisk::Arm64e::signExtendedAddend() const
965 assert(this->authBind
.bind
== 1);
966 assert(this->authBind
.auth
== 0);
967 uint64_t addend19
= this->bind
.addend
;
968 if ( addend19
& 0x40000 )
969 return addend19
| 0xFFFFFFFFFFFC0000ULL
;
974 const char* MachOLoaded::ChainedFixupPointerOnDisk::Arm64e::keyName(uint8_t keyBits
)
976 static const char* names
[] = {
977 "IA", "IB", "DA", "DB"
980 return names
[keyBits
];
982 const char* MachOLoaded::ChainedFixupPointerOnDisk::Arm64e::keyName() const
984 assert(this->authBind
.auth
== 1);
985 return keyName(this->authBind
.key
);
988 uint64_t MachOLoaded::ChainedFixupPointerOnDisk::Arm64e::signPointer(uint64_t unsignedAddr
, void* loc
, bool addrDiv
, uint16_t diversity
, uint8_t key
)
991 if ( unsignedAddr
== 0 )
994 #if __has_feature(ptrauth_calls)
995 uint64_t extendedDiscriminator
= diversity
;
997 extendedDiscriminator
= __builtin_ptrauth_blend_discriminator(loc
, extendedDiscriminator
);
1000 return (uintptr_t)__builtin_ptrauth_sign_unauthenticated((void*)unsignedAddr
, 0, extendedDiscriminator
);
1002 return (uintptr_t)__builtin_ptrauth_sign_unauthenticated((void*)unsignedAddr
, 1, extendedDiscriminator
);
1004 return (uintptr_t)__builtin_ptrauth_sign_unauthenticated((void*)unsignedAddr
, 2, extendedDiscriminator
);
1006 return (uintptr_t)__builtin_ptrauth_sign_unauthenticated((void*)unsignedAddr
, 3, extendedDiscriminator
);
1008 assert(0 && "invalid signing key");
1010 assert(0 && "arm64e signing only arm64e");
1015 uint64_t MachOLoaded::ChainedFixupPointerOnDisk::Arm64e::signPointer(void* loc
, uint64_t target
) const
1017 assert(this->authBind
.auth
== 1);
1018 return signPointer(target
, loc
, authBind
.addrDiv
, authBind
.diversity
, authBind
.key
);
1021 uint64_t MachOLoaded::ChainedFixupPointerOnDisk::Generic64::unpackedTarget() const
1023 return (((uint64_t)this->rebase
.high8
) << 56) | (uint64_t)(this->rebase
.target
);
1026 uint64_t MachOLoaded::ChainedFixupPointerOnDisk::Generic64::signExtendedAddend() const
1028 uint64_t addend27
= this->bind
.addend
;
1029 uint64_t top8Bits
= addend27
& 0x00007F80000ULL
;
1030 uint64_t bottom19Bits
= addend27
& 0x0000007FFFFULL
;
1031 uint64_t newValue
= (top8Bits
<< 13) | (((uint64_t)(bottom19Bits
<< 37) >> 37) & 0x00FFFFFFFFFFFFFF);
1035 const char* MachOLoaded::ChainedFixupPointerOnDisk::Kernel64::keyName() const
1037 static const char* names
[] = {
1038 "IA", "IB", "DA", "DB"
1040 assert(this->isAuth
== 1);
1041 uint8_t keyBits
= this->key
;
1042 assert(keyBits
< 4);
1043 return names
[keyBits
];
1046 bool MachOLoaded::ChainedFixupPointerOnDisk::isRebase(uint16_t pointerFormat
, uint64_t preferedLoadAddress
, uint64_t& targetRuntimeOffset
) const
1048 switch (pointerFormat
) {
1049 case DYLD_CHAINED_PTR_ARM64E
:
1050 case DYLD_CHAINED_PTR_ARM64E_USERLAND
:
1051 case DYLD_CHAINED_PTR_ARM64E_USERLAND24
:
1052 case DYLD_CHAINED_PTR_ARM64E_KERNEL
:
1053 case DYLD_CHAINED_PTR_ARM64E_FIRMWARE
:
1054 if ( this->arm64e
.bind
.bind
)
1056 if ( this->arm64e
.authRebase
.auth
) {
1057 targetRuntimeOffset
= this->arm64e
.authRebase
.target
;
1061 targetRuntimeOffset
= this->arm64e
.unpackTarget();
1062 if ( (pointerFormat
== DYLD_CHAINED_PTR_ARM64E
) || (pointerFormat
== DYLD_CHAINED_PTR_ARM64E_FIRMWARE
) ) {
1063 targetRuntimeOffset
-= preferedLoadAddress
;
1068 case DYLD_CHAINED_PTR_64
:
1069 case DYLD_CHAINED_PTR_64_OFFSET
:
1070 if ( this->generic64
.bind
.bind
)
1072 targetRuntimeOffset
= this->generic64
.unpackedTarget();
1073 if ( pointerFormat
== DYLD_CHAINED_PTR_64
)
1074 targetRuntimeOffset
-= preferedLoadAddress
;
1077 case DYLD_CHAINED_PTR_64_KERNEL_CACHE
:
1078 case DYLD_CHAINED_PTR_X86_64_KERNEL_CACHE
:
1079 targetRuntimeOffset
= this->kernel64
.target
;
1082 case DYLD_CHAINED_PTR_32
:
1083 if ( this->generic32
.bind
.bind
)
1085 targetRuntimeOffset
= this->generic32
.rebase
.target
- preferedLoadAddress
;
1088 case DYLD_CHAINED_PTR_32_FIRMWARE
:
1089 targetRuntimeOffset
= this->firmware32
.target
- preferedLoadAddress
;
1095 assert(0 && "unsupported pointer chain format");
1098 bool MachOLoaded::ChainedFixupPointerOnDisk::isBind(uint16_t pointerFormat
, uint32_t& bindOrdinal
, int64_t& addend
) const
1101 switch (pointerFormat
) {
1102 case DYLD_CHAINED_PTR_ARM64E
:
1103 case DYLD_CHAINED_PTR_ARM64E_USERLAND
:
1104 case DYLD_CHAINED_PTR_ARM64E_USERLAND24
:
1105 case DYLD_CHAINED_PTR_ARM64E_KERNEL
:
1106 case DYLD_CHAINED_PTR_ARM64E_FIRMWARE
:
1107 if ( !this->arm64e
.authBind
.bind
)
1109 if ( this->arm64e
.authBind
.auth
) {
1110 if ( pointerFormat
== DYLD_CHAINED_PTR_ARM64E_USERLAND24
)
1111 bindOrdinal
= this->arm64e
.authBind24
.ordinal
;
1113 bindOrdinal
= this->arm64e
.authBind
.ordinal
;
1117 if ( pointerFormat
== DYLD_CHAINED_PTR_ARM64E_USERLAND24
)
1118 bindOrdinal
= this->arm64e
.bind24
.ordinal
;
1120 bindOrdinal
= this->arm64e
.bind
.ordinal
;
1121 addend
= this->arm64e
.signExtendedAddend();
1125 case DYLD_CHAINED_PTR_64
:
1126 case DYLD_CHAINED_PTR_64_OFFSET
:
1127 if ( !this->generic64
.bind
.bind
)
1129 bindOrdinal
= this->generic64
.bind
.ordinal
;
1130 addend
= this->generic64
.bind
.addend
;
1133 case DYLD_CHAINED_PTR_32
:
1134 if ( !this->generic32
.bind
.bind
)
1136 bindOrdinal
= this->generic32
.bind
.ordinal
;
1137 addend
= this->generic32
.bind
.addend
;
1140 case DYLD_CHAINED_PTR_64_KERNEL_CACHE
:
1141 case DYLD_CHAINED_PTR_X86_64_KERNEL_CACHE
:
1146 assert(0 && "unsupported pointer chain format");
1149 unsigned MachOLoaded::ChainedFixupPointerOnDisk::strideSize(uint16_t pointerFormat
)
1151 switch (pointerFormat
) {
1152 case DYLD_CHAINED_PTR_ARM64E
:
1153 case DYLD_CHAINED_PTR_ARM64E_USERLAND
:
1154 case DYLD_CHAINED_PTR_ARM64E_USERLAND24
:
1156 case DYLD_CHAINED_PTR_ARM64E_KERNEL
:
1157 case DYLD_CHAINED_PTR_ARM64E_FIRMWARE
:
1158 case DYLD_CHAINED_PTR_32_FIRMWARE
:
1159 case DYLD_CHAINED_PTR_64
:
1160 case DYLD_CHAINED_PTR_64_OFFSET
:
1161 case DYLD_CHAINED_PTR_32
:
1162 case DYLD_CHAINED_PTR_32_CACHE
:
1163 case DYLD_CHAINED_PTR_64_KERNEL_CACHE
:
1165 case DYLD_CHAINED_PTR_X86_64_KERNEL_CACHE
:
1168 assert(0 && "unsupported pointer chain format");
1171 #if BUILDING_DYLD || BUILDING_LIBDYLD
1172 void MachOLoaded::fixupAllChainedFixups(Diagnostics
& diag
, const dyld_chained_starts_in_image
* starts
, uintptr_t slide
,
1173 Array
<const void*> bindTargets
, void (^logFixup
)(void* loc
, void* newValue
)) const
1175 forEachFixupInAllChains(diag
, starts
, true, ^(ChainedFixupPointerOnDisk
* fixupLoc
, const dyld_chained_starts_in_segment
* segInfo
, bool& stop
) {
1177 switch (segInfo
->pointer_format
) {
1179 #if __has_feature(ptrauth_calls)
1180 case DYLD_CHAINED_PTR_ARM64E
:
1181 case DYLD_CHAINED_PTR_ARM64E_KERNEL
:
1182 case DYLD_CHAINED_PTR_ARM64E_USERLAND
:
1183 case DYLD_CHAINED_PTR_ARM64E_USERLAND24
:
1184 if ( fixupLoc
->arm64e
.authRebase
.auth
) {
1185 if ( fixupLoc
->arm64e
.authBind
.bind
) {
1186 uint32_t bindOrdinal
= (segInfo
->pointer_format
== DYLD_CHAINED_PTR_ARM64E_USERLAND24
) ? fixupLoc
->arm64e
.authBind24
.ordinal
: fixupLoc
->arm64e
.authBind
.ordinal
;
1187 if ( bindOrdinal
>= bindTargets
.count() ) {
1188 diag
.error("out of range bind ordinal %d (max %lu)", bindOrdinal
, bindTargets
.count());
1193 // authenticated bind
1194 newValue
= (void*)(bindTargets
[bindOrdinal
]);
1195 if (newValue
!= 0) // Don't sign missing weak imports
1196 newValue
= (void*)fixupLoc
->arm64e
.signPointer(fixupLoc
, (uintptr_t)newValue
);
1200 // authenticated rebase
1201 newValue
= (void*)fixupLoc
->arm64e
.signPointer(fixupLoc
, (uintptr_t)this + fixupLoc
->arm64e
.authRebase
.target
);
1205 if ( fixupLoc
->arm64e
.bind
.bind
) {
1206 uint32_t bindOrdinal
= (segInfo
->pointer_format
== DYLD_CHAINED_PTR_ARM64E_USERLAND24
) ? fixupLoc
->arm64e
.bind24
.ordinal
: fixupLoc
->arm64e
.bind
.ordinal
;
1207 if ( bindOrdinal
>= bindTargets
.count() ) {
1208 diag
.error("out of range bind ordinal %d (max %lu)", bindOrdinal
, bindTargets
.count());
1214 newValue
= (void*)((long)bindTargets
[bindOrdinal
] + fixupLoc
->arm64e
.signExtendedAddend());
1218 // plain rebase (old format target is vmaddr, new format target is offset)
1219 if ( segInfo
->pointer_format
== DYLD_CHAINED_PTR_ARM64E
)
1220 newValue
= (void*)(fixupLoc
->arm64e
.unpackTarget()+slide
);
1222 newValue
= (void*)((uintptr_t)this + fixupLoc
->arm64e
.unpackTarget());
1226 logFixup(fixupLoc
, newValue
);
1227 fixupLoc
->raw64
= (uintptr_t)newValue
;
1230 case DYLD_CHAINED_PTR_64
:
1231 case DYLD_CHAINED_PTR_64_OFFSET
:
1232 if ( fixupLoc
->generic64
.bind
.bind
) {
1233 if ( fixupLoc
->generic64
.bind
.ordinal
>= bindTargets
.count() ) {
1234 diag
.error("out of range bind ordinal %d (max %lu)", fixupLoc
->generic64
.bind
.ordinal
, bindTargets
.count());
1239 newValue
= (void*)((long)bindTargets
[fixupLoc
->generic64
.bind
.ordinal
] + fixupLoc
->generic64
.signExtendedAddend());
1243 // plain rebase (old format target is vmaddr, new format target is offset)
1244 if ( segInfo
->pointer_format
== DYLD_CHAINED_PTR_64
)
1245 newValue
= (void*)(fixupLoc
->generic64
.unpackedTarget()+slide
);
1247 newValue
= (void*)((uintptr_t)this + fixupLoc
->generic64
.unpackedTarget());
1250 logFixup(fixupLoc
, newValue
);
1251 fixupLoc
->raw64
= (uintptr_t)newValue
;
1254 case DYLD_CHAINED_PTR_32
:
1255 if ( fixupLoc
->generic32
.bind
.bind
) {
1256 if ( fixupLoc
->generic32
.bind
.ordinal
>= bindTargets
.count() ) {
1257 diag
.error("out of range bind ordinal %d (max %lu)", fixupLoc
->generic32
.bind
.ordinal
, bindTargets
.count());
1262 newValue
= (void*)((long)bindTargets
[fixupLoc
->generic32
.bind
.ordinal
] + fixupLoc
->generic32
.bind
.addend
);
1266 if ( fixupLoc
->generic32
.rebase
.target
> segInfo
->max_valid_pointer
) {
1267 // handle non-pointers in chain
1268 uint32_t bias
= (0x04000000 + segInfo
->max_valid_pointer
)/2;
1269 newValue
= (void*)(fixupLoc
->generic32
.rebase
.target
- bias
);
1272 newValue
= (void*)(fixupLoc
->generic32
.rebase
.target
+ slide
);
1276 logFixup(fixupLoc
, newValue
);
1277 fixupLoc
->raw32
= (uint32_t)(uintptr_t)newValue
;
1281 diag
.error("unsupported pointer chain format: 0x%04X", segInfo
->pointer_format
);
1290 bool MachOLoaded::walkChain(Diagnostics
& diag
, ChainedFixupPointerOnDisk
* chain
, uint16_t pointer_format
, bool notifyNonPointers
, uint32_t max_valid_pointer
,
1291 void (^handler
)(ChainedFixupPointerOnDisk
* fixupLocation
, bool& stop
)) const
1293 const unsigned stride
= ChainedFixupPointerOnDisk::strideSize(pointer_format
);
1295 bool chainEnd
= false;
1296 while (!stop
&& !chainEnd
) {
1297 // copy chain content, in case handler modifies location to final value
1298 ChainedFixupPointerOnDisk chainContent
= *chain
;
1299 handler(chain
, stop
);
1301 switch (pointer_format
) {
1302 case DYLD_CHAINED_PTR_ARM64E
:
1303 case DYLD_CHAINED_PTR_ARM64E_KERNEL
:
1304 case DYLD_CHAINED_PTR_ARM64E_USERLAND
:
1305 case DYLD_CHAINED_PTR_ARM64E_USERLAND24
:
1306 case DYLD_CHAINED_PTR_ARM64E_FIRMWARE
:
1307 if ( chainContent
.arm64e
.rebase
.next
== 0 )
1310 chain
= (ChainedFixupPointerOnDisk
*)((uint8_t*)chain
+ chainContent
.arm64e
.rebase
.next
*stride
);
1312 case DYLD_CHAINED_PTR_64
:
1313 case DYLD_CHAINED_PTR_64_OFFSET
:
1314 if ( chainContent
.generic64
.rebase
.next
== 0 )
1317 chain
= (ChainedFixupPointerOnDisk
*)((uint8_t*)chain
+ chainContent
.generic64
.rebase
.next
*4);
1319 case DYLD_CHAINED_PTR_32
:
1320 if ( chainContent
.generic32
.rebase
.next
== 0 )
1323 chain
= (ChainedFixupPointerOnDisk
*)((uint8_t*)chain
+ chainContent
.generic32
.rebase
.next
*4);
1324 if ( !notifyNonPointers
) {
1325 while ( (chain
->generic32
.rebase
.bind
== 0) && (chain
->generic32
.rebase
.target
> max_valid_pointer
) ) {
1326 // not a real pointer, but a non-pointer co-opted into chain
1327 chain
= (ChainedFixupPointerOnDisk
*)((uint8_t*)chain
+ chain
->generic32
.rebase
.next
*4);
1332 case DYLD_CHAINED_PTR_64_KERNEL_CACHE
:
1333 case DYLD_CHAINED_PTR_X86_64_KERNEL_CACHE
:
1334 if ( chainContent
.kernel64
.next
== 0 )
1337 chain
= (ChainedFixupPointerOnDisk
*)((uint8_t*)chain
+ chainContent
.kernel64
.next
*stride
);
1339 case DYLD_CHAINED_PTR_32_FIRMWARE
:
1340 if ( chainContent
.firmware32
.next
== 0 )
1343 chain
= (ChainedFixupPointerOnDisk
*)((uint8_t*)chain
+ chainContent
.firmware32
.next
*4);
1346 diag
.error("unknown pointer format 0x%04X", pointer_format
);
1354 void MachOLoaded::forEachFixupChainSegment(Diagnostics
& diag
, const dyld_chained_starts_in_image
* starts
,
1355 void (^handler
)(const dyld_chained_starts_in_segment
* segInfo
, uint32_t segIndex
, bool& stop
)) const
1357 bool stopped
= false;
1358 for (uint32_t segIndex
=0; segIndex
< starts
->seg_count
&& !stopped
; ++segIndex
) {
1359 if ( starts
->seg_info_offset
[segIndex
] == 0 )
1361 const dyld_chained_starts_in_segment
* segInfo
= (dyld_chained_starts_in_segment
*)((uint8_t*)starts
+ starts
->seg_info_offset
[segIndex
]);
1362 handler(segInfo
, segIndex
, stopped
);
1366 void MachOLoaded::forEachFixupInSegmentChains(Diagnostics
& diag
, const dyld_chained_starts_in_segment
* segInfo
, bool notifyNonPointers
,
1367 void (^handler
)(ChainedFixupPointerOnDisk
* fixupLocation
, const dyld_chained_starts_in_segment
* segInfo
, bool& stop
)) const
1369 auto adaptor
= ^(ChainedFixupPointerOnDisk
* fixupLocation
, bool& stop
) {
1370 handler(fixupLocation
, segInfo
, stop
);
1372 bool stopped
= false;
1373 for (uint32_t pageIndex
=0; pageIndex
< segInfo
->page_count
&& !stopped
; ++pageIndex
) {
1374 uint16_t offsetInPage
= segInfo
->page_start
[pageIndex
];
1375 if ( offsetInPage
== DYLD_CHAINED_PTR_START_NONE
)
1377 if ( offsetInPage
& DYLD_CHAINED_PTR_START_MULTI
) {
1378 // 32-bit chains which may need multiple starts per page
1379 uint32_t overflowIndex
= offsetInPage
& ~DYLD_CHAINED_PTR_START_MULTI
;
1380 bool chainEnd
= false;
1381 while (!stopped
&& !chainEnd
) {
1382 chainEnd
= (segInfo
->page_start
[overflowIndex
] & DYLD_CHAINED_PTR_START_LAST
);
1383 offsetInPage
= (segInfo
->page_start
[overflowIndex
] & ~DYLD_CHAINED_PTR_START_LAST
);
1384 uint8_t* pageContentStart
= (uint8_t*)this + segInfo
->segment_offset
+ (pageIndex
* segInfo
->page_size
);
1385 ChainedFixupPointerOnDisk
* chain
= (ChainedFixupPointerOnDisk
*)(pageContentStart
+offsetInPage
);
1386 stopped
= walkChain(diag
, chain
, segInfo
->pointer_format
, notifyNonPointers
, segInfo
->max_valid_pointer
, adaptor
);
1391 // one chain per page
1392 uint8_t* pageContentStart
= (uint8_t*)this + segInfo
->segment_offset
+ (pageIndex
* segInfo
->page_size
);
1393 ChainedFixupPointerOnDisk
* chain
= (ChainedFixupPointerOnDisk
*)(pageContentStart
+offsetInPage
);
1394 stopped
= walkChain(diag
, chain
, segInfo
->pointer_format
, notifyNonPointers
, segInfo
->max_valid_pointer
, adaptor
);
1399 void MachOLoaded::forEachFixupInAllChains(Diagnostics
& diag
, const dyld_chained_starts_in_image
* starts
, bool notifyNonPointers
,
1400 void (^handler
)(ChainedFixupPointerOnDisk
* fixupLocation
, const dyld_chained_starts_in_segment
* segInfo
, bool& stop
)) const
1402 bool stopped
= false;
1403 for (uint32_t segIndex
=0; segIndex
< starts
->seg_count
&& !stopped
; ++segIndex
) {
1404 if ( starts
->seg_info_offset
[segIndex
] == 0 )
1406 const dyld_chained_starts_in_segment
* segInfo
= (dyld_chained_starts_in_segment
*)((uint8_t*)starts
+ starts
->seg_info_offset
[segIndex
]);
1407 forEachFixupInSegmentChains(diag
, segInfo
, notifyNonPointers
, handler
);
1411 void MachOLoaded::forEachFixupInAllChains(Diagnostics
& diag
, uint16_t pointer_format
, uint32_t starts_count
, const uint32_t chain_starts
[],
1412 void (^handler
)(ChainedFixupPointerOnDisk
* fixupLocation
, bool& stop
)) const
1414 for (uint32_t i
=0; i
< starts_count
; ++i
) {
1415 ChainedFixupPointerOnDisk
* chain
= (ChainedFixupPointerOnDisk
*)((uint8_t*)this + chain_starts
[i
]);
1416 if ( walkChain(diag
, chain
, pointer_format
, false, 0, handler
) )
1422 } // namespace dyld3