dyld-832.7.1.tar.gz
[apple/dyld.git] / dyld3 / MachOLoaded.cpp
1 /*
2 * Copyright (c) 2017 Apple Inc. All rights reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
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
11 * file.
12 *
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.
20 *
21 * @APPLE_LICENSE_HEADER_END@
22 */
23
24
25 #include <sys/types.h>
26 #include <sys/stat.h>
27 #include <sys/errno.h>
28 #include <sys/mman.h>
29 #include <mach/mach.h>
30 #include <fcntl.h>
31 #include <stdlib.h>
32 #include <stdio.h>
33 #include <unistd.h>
34 #include <assert.h>
35 #include <mach-o/reloc.h>
36 #include <mach-o/nlist.h>
37 extern "C" {
38 #include <corecrypto/ccdigest.h>
39 #include <corecrypto/ccsha1.h>
40 #include <corecrypto/ccsha2.h>
41 }
42
43 #include "MachOFile.h"
44 #include "MachOLoaded.h"
45 #include "CodeSigningTypes.h"
46
47
48
49 namespace dyld3 {
50
51
52 void MachOLoaded::getLinkEditLoadCommands(Diagnostics& diag, LinkEditInfo& result) const
53 {
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) {
67 switch ( cmd->cmd ) {
68 case LC_DYLD_INFO:
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;
75 break;
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;
82 break;
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;
89 break;
90 case LC_SYMTAB:
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;
96 break;
97 case LC_DYSYMTAB:
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;
103 break;
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;
110 break;
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;
117 break;
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;
124 break;
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;
131 break;
132 case LC_UUID:
133 if ( cmd->cmdsize != sizeof(uuid_command) )
134 diag.error("LC_UUID load command size wrong");
135 else if ( hasUUID )
136 diag.error("multiple LC_UUID load commands");
137 hasUUID = true;
138 break;
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;
148 break;
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");
152 break;
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");
158 else if ( is64() )
159 diag.error("LC_ENCRYPTION_INFO found in 64-bit mach-o");
160 hasEncrypt = true;
161 break;
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");
167 else if ( !is64() )
168 diag.error("LC_ENCRYPTION_INFO_64 found in 32-bit mach-o");
169 hasEncrypt = true;
170 break;
171 }
172 });
173 if ( diag.noError() && (result.dynSymTab != nullptr) && (result.symTab == nullptr) )
174 diag.error("LC_DYSYMTAB but no LC_SYMTAB load command");
175 }
176
177 void MachOLoaded::getLinkEditPointers(Diagnostics& diag, LinkEditInfo& result) const
178 {
179 getLinkEditLoadCommands(diag, result);
180 if ( diag.noError() )
181 getLayoutInfo(result.layout);
182 }
183
184 const uint8_t* MachOLoaded::getExportsTrie(const LinkEditInfo& leInfo, uint64_t& trieSize) const
185 {
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;
190 }
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;
195 }
196 trieSize = 0;
197 return nullptr;
198 }
199
200
201 void MachOLoaded::getLayoutInfo(LayoutInfo& result) const
202 {
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);
207 }
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;
213 }
214 result.lastSegIndex = info.segIndex;
215 });
216 }
217
218 bool MachOLoaded::hasExportTrie(uint32_t& runtimeOffset, uint32_t& size) const
219 {
220 runtimeOffset = 0;
221 size = 0;
222 Diagnostics diag;
223 LinkEditInfo leInfo;
224 getLinkEditPointers(diag, leInfo);
225 diag.assertNoError(); // any malformations in the file should have been caught by earlier validate() call
226 if ( diag.hasError() )
227 return false;
228 uint64_t trieSize;
229 if ( const uint8_t* trie = getExportsTrie(leInfo, trieSize) ) {
230 runtimeOffset = (uint32_t)(trie - (uint8_t*)this);
231 size = (uint32_t)trieSize;
232 return true;
233 }
234 return false;
235 }
236
237
238 #if BUILDING_LIBDYLD
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
242 {
243 typedef void* (*ResolverFunc)(void);
244 ResolverFunc resolver;
245 Diagnostics diag;
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);
258 stop = true;
259 }
260 });
261 break;
262 }
263 case FoundSymbol::Kind::absolute:
264 *result = (void*)(long)foundInfo.value;
265 *resultPointsToInstructions = false;
266 break;
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;
274 break;
275 }
276 return true;
277 }
278 return false;
279 }
280 #endif // BUILDING_LIBDYLD
281
282 bool MachOLoaded::findExportedSymbol(Diagnostics& diag, const char* symbolName, bool weakImport, FoundSymbol& foundInfo, DependentToMachOLoaded findDependent) const
283 {
284 LinkEditInfo leInfo;
285 getLinkEditPointers(diag, leInfo);
286 if ( diag.hasError() )
287 return false;
288 uint64_t trieSize;
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) ) {
300 stop = true;
301 foundInReExportedDylib = true;
302 }
303 }
304 }
305 ++depIndex;
306 });
307 return foundInReExportedDylib;
308 }
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 )
313 return false;
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);
321 return false;
322 }
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);
326 }
327 else if (weakImport) {
328 return false;
329 }
330 else {
331 diag.error("dependent dylib %lld not found for re-exported symbol %s", ordinal, symbolName);
332 return false;
333 }
334 }
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() )
343 return false;
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);
349 }
350 else {
351 foundInfo.kind = FoundSymbol::Kind::headerOffset;
352 }
353 if ( flags & EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION )
354 foundInfo.isWeakDef = true;
355 break;
356 case EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL:
357 foundInfo.isThreadLocal = true;
358 break;
359 case EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE:
360 foundInfo.kind = FoundSymbol::Kind::absolute;
361 break;
362 default:
363 diag.error("unsupported exported symbol kind. flags=%llu at node offset=0x%0lX", flags, (long)(node-trieStart));
364 return false;
365 }
366 return true;
367 }
368 else {
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;
379 stop = true;
380 }
381 });
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) ) {
389 stop = true;
390 }
391 }
392 }
393 ++depIndex;
394 });
395 }
396 return (foundInfo.foundInDylib != nullptr);
397 }
398 }
399
400 intptr_t MachOLoaded::getSlide() const
401 {
402 Diagnostics diag;
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);
409 stop = true;
410 }
411 }
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);
416 stop = true;
417 }
418 }
419 });
420 diag.assertNoError(); // any malformations in the file should have been caught by earlier validate() call
421 return slide;
422 }
423
424 const uint8_t* MachOLoaded::getLinkEditContent(const LayoutInfo& info, uint32_t fileOffset) const
425 {
426 uint32_t offsetInLinkedit = fileOffset - info.linkeditFileOffset;
427 uintptr_t linkeditStartAddr = info.linkeditUnslidVMAddr + info.slide;
428 return (uint8_t*)(linkeditStartAddr + offsetInLinkedit);
429 }
430
431
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
433 {
434 LinkEditInfo leInfo;
435 getLinkEditPointers(diag, leInfo);
436 if ( diag.hasError() )
437 return;
438
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;
446 }
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;
451 bool stop = false;
452 for (uint32_t i=0; (i < globalsCount) && !stop; ++i) {
453 if ( is64Bit ) {
454 const struct nlist_64& sym = symbols64[globalsStartIndex+i];
455 if ( sym.n_un.n_strx > maxStringOffset )
456 continue;
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);
459 }
460 else {
461 const struct nlist& sym = symbols[globalsStartIndex+i];
462 if ( sym.n_un.n_strx > maxStringOffset )
463 continue;
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);
466 }
467 }
468 }
469 }
470
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
472 {
473 LinkEditInfo leInfo;
474 getLinkEditPointers(diag, leInfo);
475 if ( diag.hasError() )
476 return;
477
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;
485 }
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));
490 bool stop = false;
491 for (uint32_t i=0; (i < localsCount) && !stop; ++i) {
492 if ( is64Bit ) {
493 const struct nlist_64& sym = symbols64[localsStartIndex+i];
494 if ( sym.n_un.n_strx > maxStringOffset )
495 continue;
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);
498 }
499 else {
500 const struct nlist& sym = symbols[localsStartIndex+i];
501 if ( sym.n_un.n_strx > maxStringOffset )
502 continue;
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);
505 }
506 }
507 }
508 }
509
510 uint32_t MachOLoaded::dependentDylibCount() const
511 {
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) {
514 ++count;
515 });
516 return count;
517 }
518
519 const char* MachOLoaded::dependentDylibLoadPath(uint32_t depIndex) const
520 {
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;
526 stop = true;
527 }
528 ++curDepIndex;
529 });
530 return foundLoadPath;
531 }
532
533 const char* MachOLoaded::segmentName(uint32_t targetSegIndex) const
534 {
535 __block const char* result = nullptr;
536 forEachSegment(^(const SegmentInfo& info, bool& stop) {
537 if ( targetSegIndex == info.segIndex ) {
538 result = info.segName;
539 stop = true;
540 }
541 });
542 return result;
543 }
544
545 bool MachOLoaded::findClosestFunctionStart(uint64_t address, uint64_t* functionStartAddress) const
546 {
547 Diagnostics diag;
548 LinkEditInfo leInfo;
549 getLinkEditPointers(diag, leInfo);
550 if ( diag.hasError() )
551 return false;
552 if ( leInfo.functionStarts == nullptr )
553 return false;
554
555 const uint8_t* starts = getLinkEditContent(leInfo.layout, leInfo.functionStarts->dataoff);
556 const uint8_t* startsEnd = starts + leInfo.functionStarts->datasize;
557
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);
562 if ( value == 0 )
563 break;
564 lastAddr = runningAddr;
565 runningAddr += value;
566 //fprintf(stderr, " addr=0x%08llX\n", runningAddr);
567 if ( runningAddr > address ) {
568 *functionStartAddress = lastAddr;
569 return true;
570 }
571 };
572
573 return false;
574 }
575
576 bool MachOLoaded::findClosestSymbol(uint64_t address, const char** symbolName, uint64_t* symbolAddr) const
577 {
578 Diagnostics diag;
579 LinkEditInfo leInfo;
580 getLinkEditPointers(diag, leInfo);
581 if ( diag.hasError() )
582 return false;
583 if ( (leInfo.symTab == nullptr) || (leInfo.dynSymTab == nullptr) )
584 return false;
585 uint64_t targetUnslidAddress = address - leInfo.layout.slide;
586
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) ) {
592 stop = true;
593 }
594 });
595
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));
599 if ( is64() ) {
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) )
609 bestSymbol = s;
610 }
611 else if ( (s->n_value <= targetUnslidAddress) && (bestSymbol->n_value < s->n_value) && (s->n_sect == sectionIndexForTargetAddress) ) {
612 bestSymbol = s;
613 }
614 }
615 }
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) )
623 bestSymbol = s;
624 }
625 else if ( (s->n_value <= targetUnslidAddress) && (bestSymbol->n_value < s->n_value) && (s->n_sect == sectionIndexForTargetAddress) ) {
626 bestSymbol = s;
627 }
628 }
629 }
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];
634 return true;
635 }
636 }
637 else {
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) )
646 bestSymbol = s;
647 }
648 else if ( (s->n_value <= targetUnslidAddress) && (bestSymbol->n_value < s->n_value) && (s->n_sect == sectionIndexForTargetAddress) ) {
649 bestSymbol = s;
650 }
651 }
652 }
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) )
660 bestSymbol = s;
661 }
662 else if ( (s->n_value <= targetUnslidAddress) && (bestSymbol->n_value < s->n_value) && (s->n_sect == sectionIndexForTargetAddress) ) {
663 bestSymbol = s;
664 }
665 }
666 }
667 if ( bestSymbol != nullptr ) {
668 #if __arm__
669 if ( bestSymbol->n_desc & N_ARM_THUMB_DEF )
670 *symbolAddr = (bestSymbol->n_value | 1) + leInfo.layout.slide;
671 else
672 *symbolAddr = bestSymbol->n_value + leInfo.layout.slide;
673 #else
674 *symbolAddr = bestSymbol->n_value + leInfo.layout.slide;
675 #endif
676 if ( bestSymbol->n_un.n_strx < maxStringOffset )
677 *symbolName = &stringPool[bestSymbol->n_un.n_strx];
678 return true;
679 }
680 }
681
682 return false;
683 }
684
685 const void* MachOLoaded::findSectionContent(const char* segName, const char* sectName, uint64_t& size) const
686 {
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());
692 }
693 });
694 return result;
695 }
696
697
698 bool MachOLoaded::intersectsRange(uintptr_t start, uintptr_t length) const
699 {
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) )
704 result = true;
705 });
706 return result;
707 }
708
709 const uint8_t* MachOLoaded::trieWalk(Diagnostics& diag, const uint8_t* start, const uint8_t* end, const char* symbol)
710 {
711 STACK_ALLOC_OVERFLOW_SAFE_ARRAY(uint32_t, visitedNodeOffsets, 128);
712 visitedNodeOffsets.push_back(0);
713 const uint8_t* p = start;
714 while ( p < end ) {
715 uint64_t terminalSize = *p++;
716 if ( terminalSize > 127 ) {
717 // except for re-export-with-rename, all terminal sizes fit in one byte
718 --p;
719 terminalSize = read_uleb128(diag, p, end);
720 if ( diag.hasError() )
721 return nullptr;
722 }
723 if ( (*symbol == '\0') && (terminalSize != 0) ) {
724 return p;
725 }
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);
729 return nullptr;
730 }
731 uint8_t childrenRemaining = *children++;
732 p = 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
739 char c = *p;
740 while ( c != '\0' ) {
741 if ( !wrongEdge ) {
742 if ( c != *ss )
743 wrongEdge = true;
744 ++ss;
745 }
746 ++p;
747 c = *p;
748 }
749 if ( wrongEdge ) {
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 )
754 ++p;
755 ++p; // skip over last byte of uleb128
756 if ( p > end ) {
757 diag.error("malformed trie node, child node extends past end of trie\n");
758 return nullptr;
759 }
760 }
761 else {
762 // the symbol so far matches this edge (child)
763 // so advance to the child's node
764 ++p;
765 nodeOffset = read_uleb128(diag, p, end);
766 if ( diag.hasError() )
767 return nullptr;
768 if ( (nodeOffset == 0) || ( &start[nodeOffset] > end) ) {
769 diag.error("malformed trie child, nodeOffset=0x%llX out of range\n", nodeOffset);
770 return nullptr;
771 }
772 symbol = ss;
773 break;
774 }
775 }
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);
779 return nullptr;
780 }
781 // check for cycles
782 for (uint32_t aVisitedNodeOffset : visitedNodeOffsets) {
783 if ( aVisitedNodeOffset == nodeOffset ) {
784 diag.error("malformed trie child, cycle to nodeOffset=0x%llX\n", nodeOffset);
785 return nullptr;
786 }
787 }
788 visitedNodeOffsets.push_back((uint32_t)nodeOffset);
789 p = &start[nodeOffset];
790 }
791 else
792 p = end;
793 }
794 return nullptr;
795 }
796
797 void MachOLoaded::forEachCDHashOfCodeSignature(const void* codeSigStart, size_t codeSignLen,
798 void (^callback)(const uint8_t cdHash[20])) const
799 {
800 forEachCodeDirectoryBlob(codeSigStart, codeSignLen, ^(const void *cdBuffer) {
801 const CS_CodeDirectory* cd = (const CS_CodeDirectory*)cdBuffer;
802 uint32_t cdLength = htonl(cd->length);
803 uint8_t cdHash[20];
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);
814 callback(cdHash);
815 return;
816 }
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);
827 callback(cdHash);
828 return;
829 }
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);
838 callback(cdHash);
839 return;
840 }
841 });
842 }
843
844
845 // Note, this has to match the kernel
846 static const uint32_t hashPriorities[] = {
847 CS_HASHTYPE_SHA1,
848 CS_HASHTYPE_SHA256_TRUNCATED,
849 CS_HASHTYPE_SHA256,
850 CS_HASHTYPE_SHA384,
851 };
852
853 static unsigned int hash_rank(const CS_CodeDirectory *cd)
854 {
855 uint32_t type = cd->hashType;
856 for (uint32_t n = 0; n < sizeof(hashPriorities) / sizeof(hashPriorities[0]); ++n) {
857 if (hashPriorities[n] == type)
858 return n + 1;
859 }
860
861 /* not supported */
862 return 0;
863 }
864
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,
873 CS_HASHTYPE_SHA256,
874 CS_HASHTYPE_SHA384,
875 CS_HASHTYPE_SHA1
876 };
877
878 static unsigned int hash_rank_watchOS_dylibs(const CS_CodeDirectory *cd)
879 {
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)
883 return n + 1;
884 }
885
886 /* not supported */
887 return 0;
888 }
889
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
897 {
898 // verify min length of overall code signature
899 if ( codeSignLen < sizeof(CS_SuperBlob) )
900 return;
901
902 // verify magic at start
903 const CS_SuperBlob* codeSuperBlob = (CS_SuperBlob*)codeSigStart;
904 if ( codeSuperBlob->magic != htonl(CSMAGIC_EMBEDDED_SIGNATURE) )
905 return;
906
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 )
910 return;
911
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;
917
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
925 } else {
926 continue;
927 }
928 uint32_t cdOffset = htonl(codeSuperBlob->index[i].offset);
929 // verify offset is not out of range
930 if ( cdOffset > (codeSignLen - sizeof(CS_CodeDirectory)) )
931 continue;
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) )
936 continue;
937
938 // The watch main executable wants to know about all cd hashes
939 if ( isWatchOS && isMainExecutable ) {
940 callback(cd);
941 continue;
942 }
943
944 if ( cd->magic == htonl(CSMAGIC_CODEDIRECTORY) ) {
945 if ( !bestCd || (hashRankFn(cd) > hashRankFn(bestCd)) )
946 bestCd = cd;
947 }
948 }
949
950 // Note this callback won't happen on watchOS as that one was done in the loop
951 if ( bestCd != nullptr )
952 callback(bestCd);
953 }
954
955
956 uint64_t MachOLoaded::ChainedFixupPointerOnDisk::Arm64e::unpackTarget() const
957 {
958 assert(this->authBind.bind == 0);
959 assert(this->authBind.auth == 0);
960 return ((uint64_t)(this->rebase.high8) << 56) | (this->rebase.target);
961 }
962
963 uint64_t MachOLoaded::ChainedFixupPointerOnDisk::Arm64e::signExtendedAddend() const
964 {
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;
970 else
971 return addend19;
972 }
973
974 const char* MachOLoaded::ChainedFixupPointerOnDisk::Arm64e::keyName(uint8_t keyBits)
975 {
976 static const char* names[] = {
977 "IA", "IB", "DA", "DB"
978 };
979 assert(keyBits < 4);
980 return names[keyBits];
981 }
982 const char* MachOLoaded::ChainedFixupPointerOnDisk::Arm64e::keyName() const
983 {
984 assert(this->authBind.auth == 1);
985 return keyName(this->authBind.key);
986 }
987
988 uint64_t MachOLoaded::ChainedFixupPointerOnDisk::Arm64e::signPointer(uint64_t unsignedAddr, void* loc, bool addrDiv, uint16_t diversity, uint8_t key)
989 {
990 // don't sign NULL
991 if ( unsignedAddr == 0 )
992 return 0;
993
994 #if __has_feature(ptrauth_calls)
995 uint64_t extendedDiscriminator = diversity;
996 if ( addrDiv )
997 extendedDiscriminator = __builtin_ptrauth_blend_discriminator(loc, extendedDiscriminator);
998 switch ( key ) {
999 case 0: // IA
1000 return (uintptr_t)__builtin_ptrauth_sign_unauthenticated((void*)unsignedAddr, 0, extendedDiscriminator);
1001 case 1: // IB
1002 return (uintptr_t)__builtin_ptrauth_sign_unauthenticated((void*)unsignedAddr, 1, extendedDiscriminator);
1003 case 2: // DA
1004 return (uintptr_t)__builtin_ptrauth_sign_unauthenticated((void*)unsignedAddr, 2, extendedDiscriminator);
1005 case 3: // DB
1006 return (uintptr_t)__builtin_ptrauth_sign_unauthenticated((void*)unsignedAddr, 3, extendedDiscriminator);
1007 }
1008 assert(0 && "invalid signing key");
1009 #else
1010 assert(0 && "arm64e signing only arm64e");
1011 #endif
1012 }
1013
1014
1015 uint64_t MachOLoaded::ChainedFixupPointerOnDisk::Arm64e::signPointer(void* loc, uint64_t target) const
1016 {
1017 assert(this->authBind.auth == 1);
1018 return signPointer(target, loc, authBind.addrDiv, authBind.diversity, authBind.key);
1019 }
1020
1021 uint64_t MachOLoaded::ChainedFixupPointerOnDisk::Generic64::unpackedTarget() const
1022 {
1023 return (((uint64_t)this->rebase.high8) << 56) | (uint64_t)(this->rebase.target);
1024 }
1025
1026 uint64_t MachOLoaded::ChainedFixupPointerOnDisk::Generic64::signExtendedAddend() const
1027 {
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);
1032 return newValue;
1033 }
1034
1035 const char* MachOLoaded::ChainedFixupPointerOnDisk::Kernel64::keyName() const
1036 {
1037 static const char* names[] = {
1038 "IA", "IB", "DA", "DB"
1039 };
1040 assert(this->isAuth == 1);
1041 uint8_t keyBits = this->key;
1042 assert(keyBits < 4);
1043 return names[keyBits];
1044 }
1045
1046 bool MachOLoaded::ChainedFixupPointerOnDisk::isRebase(uint16_t pointerFormat, uint64_t preferedLoadAddress, uint64_t& targetRuntimeOffset) const
1047 {
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 )
1055 return false;
1056 if ( this->arm64e.authRebase.auth ) {
1057 targetRuntimeOffset = this->arm64e.authRebase.target;
1058 return true;
1059 }
1060 else {
1061 targetRuntimeOffset = this->arm64e.unpackTarget();
1062 if ( (pointerFormat == DYLD_CHAINED_PTR_ARM64E) || (pointerFormat == DYLD_CHAINED_PTR_ARM64E_FIRMWARE) ) {
1063 targetRuntimeOffset -= preferedLoadAddress;
1064 }
1065 return true;
1066 }
1067 break;
1068 case DYLD_CHAINED_PTR_64:
1069 case DYLD_CHAINED_PTR_64_OFFSET:
1070 if ( this->generic64.bind.bind )
1071 return false;
1072 targetRuntimeOffset = this->generic64.unpackedTarget();
1073 if ( pointerFormat == DYLD_CHAINED_PTR_64 )
1074 targetRuntimeOffset -= preferedLoadAddress;
1075 return true;
1076 break;
1077 case DYLD_CHAINED_PTR_64_KERNEL_CACHE:
1078 case DYLD_CHAINED_PTR_X86_64_KERNEL_CACHE:
1079 targetRuntimeOffset = this->kernel64.target;
1080 return true;
1081 break;
1082 case DYLD_CHAINED_PTR_32:
1083 if ( this->generic32.bind.bind )
1084 return false;
1085 targetRuntimeOffset = this->generic32.rebase.target - preferedLoadAddress;
1086 return true;
1087 break;
1088 case DYLD_CHAINED_PTR_32_FIRMWARE:
1089 targetRuntimeOffset = this->firmware32.target - preferedLoadAddress;
1090 return true;
1091 break;
1092 default:
1093 break;
1094 }
1095 assert(0 && "unsupported pointer chain format");
1096 }
1097
1098 bool MachOLoaded::ChainedFixupPointerOnDisk::isBind(uint16_t pointerFormat, uint32_t& bindOrdinal, int64_t& addend) const
1099 {
1100 addend = 0;
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 )
1108 return false;
1109 if ( this->arm64e.authBind.auth ) {
1110 if ( pointerFormat == DYLD_CHAINED_PTR_ARM64E_USERLAND24 )
1111 bindOrdinal = this->arm64e.authBind24.ordinal;
1112 else
1113 bindOrdinal = this->arm64e.authBind.ordinal;
1114 return true;
1115 }
1116 else {
1117 if ( pointerFormat == DYLD_CHAINED_PTR_ARM64E_USERLAND24 )
1118 bindOrdinal = this->arm64e.bind24.ordinal;
1119 else
1120 bindOrdinal = this->arm64e.bind.ordinal;
1121 addend = this->arm64e.signExtendedAddend();
1122 return true;
1123 }
1124 break;
1125 case DYLD_CHAINED_PTR_64:
1126 case DYLD_CHAINED_PTR_64_OFFSET:
1127 if ( !this->generic64.bind.bind )
1128 return false;
1129 bindOrdinal = this->generic64.bind.ordinal;
1130 addend = this->generic64.bind.addend;
1131 return true;
1132 break;
1133 case DYLD_CHAINED_PTR_32:
1134 if ( !this->generic32.bind.bind )
1135 return false;
1136 bindOrdinal = this->generic32.bind.ordinal;
1137 addend = this->generic32.bind.addend;
1138 return true;
1139 break;
1140 case DYLD_CHAINED_PTR_64_KERNEL_CACHE:
1141 case DYLD_CHAINED_PTR_X86_64_KERNEL_CACHE:
1142 return false;
1143 default:
1144 break;
1145 }
1146 assert(0 && "unsupported pointer chain format");
1147 }
1148
1149 unsigned MachOLoaded::ChainedFixupPointerOnDisk::strideSize(uint16_t pointerFormat)
1150 {
1151 switch (pointerFormat) {
1152 case DYLD_CHAINED_PTR_ARM64E:
1153 case DYLD_CHAINED_PTR_ARM64E_USERLAND:
1154 case DYLD_CHAINED_PTR_ARM64E_USERLAND24:
1155 return 8;
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:
1164 return 4;
1165 case DYLD_CHAINED_PTR_X86_64_KERNEL_CACHE:
1166 return 1;
1167 }
1168 assert(0 && "unsupported pointer chain format");
1169 }
1170
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
1174 {
1175 forEachFixupInAllChains(diag, starts, true, ^(ChainedFixupPointerOnDisk* fixupLoc, const dyld_chained_starts_in_segment* segInfo, bool& stop) {
1176 void* newValue;
1177 switch (segInfo->pointer_format) {
1178 #if __LP64__
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());
1189 stop = true;
1190 break;
1191 }
1192 else {
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);
1197 }
1198 }
1199 else {
1200 // authenticated rebase
1201 newValue = (void*)fixupLoc->arm64e.signPointer(fixupLoc, (uintptr_t)this + fixupLoc->arm64e.authRebase.target);
1202 }
1203 }
1204 else {
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());
1209 stop = true;
1210 break;
1211 }
1212 else {
1213 // plain bind
1214 newValue = (void*)((long)bindTargets[bindOrdinal] + fixupLoc->arm64e.signExtendedAddend());
1215 }
1216 }
1217 else {
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);
1221 else
1222 newValue = (void*)((uintptr_t)this + fixupLoc->arm64e.unpackTarget());
1223 }
1224 }
1225 if ( logFixup )
1226 logFixup(fixupLoc, newValue);
1227 fixupLoc->raw64 = (uintptr_t)newValue;
1228 break;
1229 #endif
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());
1235 stop = true;
1236 break;
1237 }
1238 else {
1239 newValue = (void*)((long)bindTargets[fixupLoc->generic64.bind.ordinal] + fixupLoc->generic64.signExtendedAddend());
1240 }
1241 }
1242 else {
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);
1246 else
1247 newValue = (void*)((uintptr_t)this + fixupLoc->generic64.unpackedTarget());
1248 }
1249 if ( logFixup )
1250 logFixup(fixupLoc, newValue);
1251 fixupLoc->raw64 = (uintptr_t)newValue;
1252 break;
1253 #else
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());
1258 stop = true;
1259 break;
1260 }
1261 else {
1262 newValue = (void*)((long)bindTargets[fixupLoc->generic32.bind.ordinal] + fixupLoc->generic32.bind.addend);
1263 }
1264 }
1265 else {
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);
1270 }
1271 else {
1272 newValue = (void*)(fixupLoc->generic32.rebase.target + slide);
1273 }
1274 }
1275 if ( logFixup )
1276 logFixup(fixupLoc, newValue);
1277 fixupLoc->raw32 = (uint32_t)(uintptr_t)newValue;
1278 break;
1279 #endif // __LP64__
1280 default:
1281 diag.error("unsupported pointer chain format: 0x%04X", segInfo->pointer_format);
1282 stop = true;
1283 break;
1284 }
1285 });
1286 }
1287 #endif
1288
1289
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
1292 {
1293 const unsigned stride = ChainedFixupPointerOnDisk::strideSize(pointer_format);
1294 bool stop = false;
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);
1300 if ( !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 )
1308 chainEnd = true;
1309 else
1310 chain = (ChainedFixupPointerOnDisk*)((uint8_t*)chain + chainContent.arm64e.rebase.next*stride);
1311 break;
1312 case DYLD_CHAINED_PTR_64:
1313 case DYLD_CHAINED_PTR_64_OFFSET:
1314 if ( chainContent.generic64.rebase.next == 0 )
1315 chainEnd = true;
1316 else
1317 chain = (ChainedFixupPointerOnDisk*)((uint8_t*)chain + chainContent.generic64.rebase.next*4);
1318 break;
1319 case DYLD_CHAINED_PTR_32:
1320 if ( chainContent.generic32.rebase.next == 0 )
1321 chainEnd = true;
1322 else {
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);
1328 }
1329 }
1330 }
1331 break;
1332 case DYLD_CHAINED_PTR_64_KERNEL_CACHE:
1333 case DYLD_CHAINED_PTR_X86_64_KERNEL_CACHE:
1334 if ( chainContent.kernel64.next == 0 )
1335 chainEnd = true;
1336 else
1337 chain = (ChainedFixupPointerOnDisk*)((uint8_t*)chain + chainContent.kernel64.next*stride);
1338 break;
1339 case DYLD_CHAINED_PTR_32_FIRMWARE:
1340 if ( chainContent.firmware32.next == 0 )
1341 chainEnd = true;
1342 else
1343 chain = (ChainedFixupPointerOnDisk*)((uint8_t*)chain + chainContent.firmware32.next*4);
1344 break;
1345 default:
1346 diag.error("unknown pointer format 0x%04X", pointer_format);
1347 stop = true;
1348 }
1349 }
1350 }
1351 return stop;
1352 }
1353
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
1356 {
1357 bool stopped = false;
1358 for (uint32_t segIndex=0; segIndex < starts->seg_count && !stopped; ++segIndex) {
1359 if ( starts->seg_info_offset[segIndex] == 0 )
1360 continue;
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);
1363 }
1364 }
1365
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
1368 {
1369 auto adaptor = ^(ChainedFixupPointerOnDisk* fixupLocation, bool& stop) {
1370 handler(fixupLocation, segInfo, stop);
1371 };
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 )
1376 continue;
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);
1387 ++overflowIndex;
1388 }
1389 }
1390 else {
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);
1395 }
1396 }
1397 }
1398
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
1401 {
1402 bool stopped = false;
1403 for (uint32_t segIndex=0; segIndex < starts->seg_count && !stopped; ++segIndex) {
1404 if ( starts->seg_info_offset[segIndex] == 0 )
1405 continue;
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);
1408 }
1409 }
1410
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
1413 {
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) )
1417 break;
1418 }
1419 }
1420
1421
1422 } // namespace dyld3
1423