dyld-750.5.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 });
215 }
216
217 bool MachOLoaded::hasExportTrie(uint32_t& runtimeOffset, uint32_t& size) const
218 {
219 runtimeOffset = 0;
220 size = 0;
221 Diagnostics diag;
222 LinkEditInfo leInfo;
223 getLinkEditPointers(diag, leInfo);
224 diag.assertNoError(); // any malformations in the file should have been caught by earlier validate() call
225 if ( diag.hasError() )
226 return false;
227 uint64_t trieSize;
228 if ( const uint8_t* trie = getExportsTrie(leInfo, trieSize) ) {
229 runtimeOffset = (uint32_t)(trie - (uint8_t*)this);
230 size = (uint32_t)trieSize;
231 return true;
232 }
233 return false;
234 }
235
236
237 #if BUILDING_LIBDYLD
238 // this is only used by dlsym() at runtime. All other binding is done when the closure is built.
239 bool MachOLoaded::hasExportedSymbol(const char* symbolName, DependentToMachOLoaded finder, void** result,
240 bool* resultPointsToInstructions) const
241 {
242 typedef void* (*ResolverFunc)(void);
243 ResolverFunc resolver;
244 Diagnostics diag;
245 FoundSymbol foundInfo;
246 if ( findExportedSymbol(diag, symbolName, false, foundInfo, finder) ) {
247 switch ( foundInfo.kind ) {
248 case FoundSymbol::Kind::headerOffset: {
249 *result = (uint8_t*)foundInfo.foundInDylib + foundInfo.value;
250 *resultPointsToInstructions = false;
251 int64_t slide = foundInfo.foundInDylib->getSlide();
252 foundInfo.foundInDylib->forEachSection(^(const SectionInfo& sectInfo, bool malformedSectionRange, bool& stop) {
253 uint64_t sectStartAddr = sectInfo.sectAddr + slide;
254 uint64_t sectEndAddr = sectStartAddr + sectInfo.sectSize;
255 if ( ((uint64_t)*result >= sectStartAddr) && ((uint64_t)*result < sectEndAddr) ) {
256 *resultPointsToInstructions = (sectInfo.sectFlags & S_ATTR_PURE_INSTRUCTIONS) || (sectInfo.sectFlags & S_ATTR_SOME_INSTRUCTIONS);
257 stop = true;
258 }
259 });
260 break;
261 }
262 case FoundSymbol::Kind::absolute:
263 *result = (void*)(long)foundInfo.value;
264 *resultPointsToInstructions = false;
265 break;
266 case FoundSymbol::Kind::resolverOffset:
267 // foundInfo.value contains "stub".
268 // in dlsym() we want to call resolver function to get final function address
269 resolver = (ResolverFunc)((uint8_t*)foundInfo.foundInDylib + foundInfo.resolverFuncOffset);
270 *result = (*resolver)();
271 // FIXME: Set this properly
272 *resultPointsToInstructions = true;
273 break;
274 }
275 return true;
276 }
277 return false;
278 }
279 #endif // BUILDING_LIBDYLD
280
281 bool MachOLoaded::findExportedSymbol(Diagnostics& diag, const char* symbolName, bool weakImport, FoundSymbol& foundInfo, DependentToMachOLoaded findDependent) const
282 {
283 LinkEditInfo leInfo;
284 getLinkEditPointers(diag, leInfo);
285 if ( diag.hasError() )
286 return false;
287 uint64_t trieSize;
288 if ( const uint8_t* trieStart = getExportsTrie(leInfo, trieSize) ) {
289 const uint8_t* trieEnd = trieStart + trieSize;
290 const uint8_t* node = trieWalk(diag, trieStart, trieEnd, symbolName);
291 if ( node == nullptr ) {
292 // symbol not exported from this image. Seach any re-exported dylibs
293 __block unsigned depIndex = 0;
294 __block bool foundInReExportedDylib = false;
295 forEachDependentDylib(^(const char* loadPath, bool isWeak, bool isReExport, bool isUpward, uint32_t compatVersion, uint32_t curVersion, bool& stop) {
296 if ( isReExport && findDependent ) {
297 if ( const MachOLoaded* depMH = findDependent(this, depIndex) ) {
298 if ( depMH->findExportedSymbol(diag, symbolName, weakImport, foundInfo, findDependent) ) {
299 stop = true;
300 foundInReExportedDylib = true;
301 }
302 }
303 }
304 ++depIndex;
305 });
306 return foundInReExportedDylib;
307 }
308 const uint8_t* p = node;
309 const uint64_t flags = read_uleb128(diag, p, trieEnd);
310 if ( flags & EXPORT_SYMBOL_FLAGS_REEXPORT ) {
311 if ( !findDependent )
312 return false;
313 // re-export from another dylib, lookup there
314 const uint64_t ordinal = read_uleb128(diag, p, trieEnd);
315 const char* importedName = (char*)p;
316 if ( importedName[0] == '\0' )
317 importedName = symbolName;
318 if ( (ordinal == 0) || (ordinal > dependentDylibCount()) ) {
319 diag.error("re-export ordinal %lld out of range for %s", ordinal, symbolName);
320 return false;
321 }
322 uint32_t depIndex = (uint32_t)(ordinal-1);
323 if ( const MachOLoaded* depMH = findDependent(this, depIndex) ) {
324 return depMH->findExportedSymbol(diag, importedName, weakImport, foundInfo, findDependent);
325 }
326 else if (weakImport) {
327 return false;
328 }
329 else {
330 diag.error("dependent dylib %lld not found for re-exported symbol %s", ordinal, symbolName);
331 return false;
332 }
333 }
334 foundInfo.kind = FoundSymbol::Kind::headerOffset;
335 foundInfo.isThreadLocal = false;
336 foundInfo.isWeakDef = false;
337 foundInfo.foundInDylib = this;
338 foundInfo.value = read_uleb128(diag, p, trieEnd);
339 foundInfo.resolverFuncOffset = 0;
340 foundInfo.foundSymbolName = symbolName;
341 if ( diag.hasError() )
342 return false;
343 switch ( flags & EXPORT_SYMBOL_FLAGS_KIND_MASK ) {
344 case EXPORT_SYMBOL_FLAGS_KIND_REGULAR:
345 if ( flags & EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER ) {
346 foundInfo.kind = FoundSymbol::Kind::headerOffset;
347 foundInfo.resolverFuncOffset = (uint32_t)read_uleb128(diag, p, trieEnd);
348 }
349 else {
350 foundInfo.kind = FoundSymbol::Kind::headerOffset;
351 }
352 if ( flags & EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION )
353 foundInfo.isWeakDef = true;
354 break;
355 case EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL:
356 foundInfo.isThreadLocal = true;
357 break;
358 case EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE:
359 foundInfo.kind = FoundSymbol::Kind::absolute;
360 break;
361 default:
362 diag.error("unsupported exported symbol kind. flags=%llu at node offset=0x%0lX", flags, (long)(node-trieStart));
363 return false;
364 }
365 return true;
366 }
367 else {
368 // this is an old binary (before macOS 10.6), scan the symbol table
369 foundInfo.foundInDylib = nullptr;
370 forEachGlobalSymbol(diag, ^(const char* aSymbolName, uint64_t n_value, uint8_t n_type, uint8_t n_sect, uint16_t n_desc, bool& stop) {
371 if ( strcmp(aSymbolName, symbolName) == 0 ) {
372 foundInfo.kind = FoundSymbol::Kind::headerOffset;
373 foundInfo.isThreadLocal = false;
374 foundInfo.foundInDylib = this;
375 foundInfo.value = n_value - leInfo.layout.textUnslidVMAddr;
376 foundInfo.resolverFuncOffset = 0;
377 foundInfo.foundSymbolName = symbolName;
378 stop = true;
379 }
380 });
381 if ( foundInfo.foundInDylib == nullptr ) {
382 // symbol not exported from this image. Search any re-exported dylibs
383 __block unsigned depIndex = 0;
384 forEachDependentDylib(^(const char* loadPath, bool isWeak, bool isReExport, bool isUpward, uint32_t compatVersion, uint32_t curVersion, bool& stop) {
385 if ( isReExport && findDependent ) {
386 if ( const MachOLoaded* depMH = findDependent(this, depIndex) ) {
387 if ( depMH->findExportedSymbol(diag, symbolName, weakImport, foundInfo, findDependent) ) {
388 stop = true;
389 }
390 }
391 }
392 ++depIndex;
393 });
394 }
395 return (foundInfo.foundInDylib != nullptr);
396 }
397 }
398
399 intptr_t MachOLoaded::getSlide() const
400 {
401 Diagnostics diag;
402 __block intptr_t slide = 0;
403 forEachLoadCommand(diag, ^(const load_command* cmd, bool& stop) {
404 if ( cmd->cmd == LC_SEGMENT_64 ) {
405 const segment_command_64* seg = (segment_command_64*)cmd;
406 if ( strcmp(seg->segname, "__TEXT") == 0 ) {
407 slide = (uintptr_t)(((uint64_t)this) - seg->vmaddr);
408 stop = true;
409 }
410 }
411 else if ( cmd->cmd == LC_SEGMENT ) {
412 const segment_command* seg = (segment_command*)cmd;
413 if ( strcmp(seg->segname, "__TEXT") == 0 ) {
414 slide = (uintptr_t)(((uint64_t)this) - seg->vmaddr);
415 stop = true;
416 }
417 }
418 });
419 diag.assertNoError(); // any malformations in the file should have been caught by earlier validate() call
420 return slide;
421 }
422
423 const uint8_t* MachOLoaded::getLinkEditContent(const LayoutInfo& info, uint32_t fileOffset) const
424 {
425 uint32_t offsetInLinkedit = fileOffset - info.linkeditFileOffset;
426 uintptr_t linkeditStartAddr = info.linkeditUnslidVMAddr + info.slide;
427 return (uint8_t*)(linkeditStartAddr + offsetInLinkedit);
428 }
429
430
431 void MachOLoaded::forEachGlobalSymbol(Diagnostics& diag, void (^callback)(const char* symbolName, uint64_t n_value, uint8_t n_type, uint8_t n_sect, uint16_t n_desc, bool& stop)) const
432 {
433 LinkEditInfo leInfo;
434 getLinkEditPointers(diag, leInfo);
435 if ( diag.hasError() )
436 return;
437
438 const bool is64Bit = is64();
439 if ( leInfo.symTab != nullptr ) {
440 uint32_t globalsStartIndex = 0;
441 uint32_t globalsCount = leInfo.symTab->nsyms;
442 if ( leInfo.dynSymTab != nullptr ) {
443 globalsStartIndex = leInfo.dynSymTab->iextdefsym;
444 globalsCount = leInfo.dynSymTab->nextdefsym;
445 }
446 uint32_t maxStringOffset = leInfo.symTab->strsize;
447 const char* stringPool = (char*)getLinkEditContent(leInfo.layout, leInfo.symTab->stroff);
448 const struct nlist* symbols = (struct nlist*) (getLinkEditContent(leInfo.layout, leInfo.symTab->symoff));
449 const struct nlist_64* symbols64 = (struct nlist_64*)symbols;
450 bool stop = false;
451 for (uint32_t i=0; (i < globalsCount) && !stop; ++i) {
452 if ( is64Bit ) {
453 const struct nlist_64& sym = symbols64[globalsStartIndex+i];
454 if ( sym.n_un.n_strx > maxStringOffset )
455 continue;
456 if ( (sym.n_type & N_EXT) && ((sym.n_type & N_TYPE) == N_SECT) && ((sym.n_type & N_STAB) == 0) )
457 callback(&stringPool[sym.n_un.n_strx], sym.n_value, sym.n_type, sym.n_sect, sym.n_desc, stop);
458 }
459 else {
460 const struct nlist& sym = symbols[globalsStartIndex+i];
461 if ( sym.n_un.n_strx > maxStringOffset )
462 continue;
463 if ( (sym.n_type & N_EXT) && ((sym.n_type & N_TYPE) == N_SECT) && ((sym.n_type & N_STAB) == 0) )
464 callback(&stringPool[sym.n_un.n_strx], sym.n_value, sym.n_type, sym.n_sect, sym.n_desc, stop);
465 }
466 }
467 }
468 }
469
470 void MachOLoaded::forEachLocalSymbol(Diagnostics& diag, void (^callback)(const char* symbolName, uint64_t n_value, uint8_t n_type, uint8_t n_sect, uint16_t n_desc, bool& stop)) const
471 {
472 LinkEditInfo leInfo;
473 getLinkEditPointers(diag, leInfo);
474 if ( diag.hasError() )
475 return;
476
477 const bool is64Bit = is64();
478 if ( leInfo.symTab != nullptr ) {
479 uint32_t localsStartIndex = 0;
480 uint32_t localsCount = leInfo.symTab->nsyms;
481 if ( leInfo.dynSymTab != nullptr ) {
482 localsStartIndex = leInfo.dynSymTab->ilocalsym;
483 localsCount = leInfo.dynSymTab->nlocalsym;
484 }
485 uint32_t maxStringOffset = leInfo.symTab->strsize;
486 const char* stringPool = (char*)getLinkEditContent(leInfo.layout, leInfo.symTab->stroff);
487 const struct nlist* symbols = (struct nlist*) (getLinkEditContent(leInfo.layout, leInfo.symTab->symoff));
488 const struct nlist_64* symbols64 = (struct nlist_64*)(getLinkEditContent(leInfo.layout, leInfo.symTab->symoff));
489 bool stop = false;
490 for (uint32_t i=0; (i < localsCount) && !stop; ++i) {
491 if ( is64Bit ) {
492 const struct nlist_64& sym = symbols64[localsStartIndex+i];
493 if ( sym.n_un.n_strx > maxStringOffset )
494 continue;
495 if ( ((sym.n_type & N_EXT) == 0) && ((sym.n_type & N_TYPE) == N_SECT) && ((sym.n_type & N_STAB) == 0) )
496 callback(&stringPool[sym.n_un.n_strx], sym.n_value, sym.n_type, sym.n_sect, sym.n_desc, stop);
497 }
498 else {
499 const struct nlist& sym = symbols[localsStartIndex+i];
500 if ( sym.n_un.n_strx > maxStringOffset )
501 continue;
502 if ( ((sym.n_type & N_EXT) == 0) && ((sym.n_type & N_TYPE) == N_SECT) && ((sym.n_type & N_STAB) == 0) )
503 callback(&stringPool[sym.n_un.n_strx], sym.n_value, sym.n_type, sym.n_sect, sym.n_desc, stop);
504 }
505 }
506 }
507 }
508
509 uint32_t MachOLoaded::dependentDylibCount() const
510 {
511 __block uint32_t count = 0;
512 forEachDependentDylib(^(const char* loadPath, bool isWeak, bool isReExport, bool isUpward, uint32_t compatVersion, uint32_t curVersion, bool& stop) {
513 ++count;
514 });
515 return count;
516 }
517
518 const char* MachOLoaded::dependentDylibLoadPath(uint32_t depIndex) const
519 {
520 __block const char* foundLoadPath = nullptr;
521 __block uint32_t curDepIndex = 0;
522 forEachDependentDylib(^(const char* loadPath, bool isWeak, bool isReExport, bool isUpward, uint32_t compatVersion, uint32_t curVersion, bool& stop) {
523 if ( curDepIndex == depIndex ) {
524 foundLoadPath = loadPath;
525 stop = true;
526 }
527 ++curDepIndex;
528 });
529 return foundLoadPath;
530 }
531
532 const char* MachOLoaded::segmentName(uint32_t targetSegIndex) const
533 {
534 __block const char* result = nullptr;
535 forEachSegment(^(const SegmentInfo& info, bool& stop) {
536 if ( targetSegIndex == info.segIndex ) {
537 result = info.segName;
538 stop = true;
539 }
540 });
541 return result;
542 }
543
544 bool MachOLoaded::findClosestFunctionStart(uint64_t address, uint64_t* functionStartAddress) const
545 {
546 Diagnostics diag;
547 LinkEditInfo leInfo;
548 getLinkEditPointers(diag, leInfo);
549 if ( diag.hasError() )
550 return false;
551 if ( leInfo.functionStarts == nullptr )
552 return false;
553
554 const uint8_t* starts = getLinkEditContent(leInfo.layout, leInfo.functionStarts->dataoff);
555 const uint8_t* startsEnd = starts + leInfo.functionStarts->datasize;
556
557 uint64_t lastAddr = (uint64_t)(long)this;
558 uint64_t runningAddr = lastAddr;
559 while (diag.noError()) {
560 uint64_t value = read_uleb128(diag, starts, startsEnd);
561 if ( value == 0 )
562 break;
563 lastAddr = runningAddr;
564 runningAddr += value;
565 //fprintf(stderr, " addr=0x%08llX\n", runningAddr);
566 if ( runningAddr > address ) {
567 *functionStartAddress = lastAddr;
568 return true;
569 }
570 };
571
572 return false;
573 }
574
575 bool MachOLoaded::findClosestSymbol(uint64_t address, const char** symbolName, uint64_t* symbolAddr) const
576 {
577 Diagnostics diag;
578 LinkEditInfo leInfo;
579 getLinkEditPointers(diag, leInfo);
580 if ( diag.hasError() )
581 return false;
582 if ( (leInfo.symTab == nullptr) || (leInfo.dynSymTab == nullptr) )
583 return false;
584 uint64_t targetUnslidAddress = address - leInfo.layout.slide;
585
586 // find section index the address is in to validate n_sect
587 __block uint32_t sectionIndexForTargetAddress = 0;
588 forEachSection(^(const SectionInfo& sectInfo, bool malformedSectionRange, bool& stop) {
589 ++sectionIndexForTargetAddress;
590 if ( (sectInfo.sectAddr <= targetUnslidAddress) && (targetUnslidAddress < sectInfo.sectAddr+sectInfo.sectSize) ) {
591 stop = true;
592 }
593 });
594
595 uint32_t maxStringOffset = leInfo.symTab->strsize;
596 const char* stringPool = (char*)getLinkEditContent(leInfo.layout, leInfo.symTab->stroff);
597 const struct nlist* symbols = (struct nlist*) (getLinkEditContent(leInfo.layout, leInfo.symTab->symoff));
598 if ( is64() ) {
599 const struct nlist_64* symbols64 = (struct nlist_64*)symbols;
600 const struct nlist_64* bestSymbol = nullptr;
601 // first walk all global symbols
602 const struct nlist_64* const globalsStart = &symbols64[leInfo.dynSymTab->iextdefsym];
603 const struct nlist_64* const globalsEnd = &globalsStart[leInfo.dynSymTab->nextdefsym];
604 for (const struct nlist_64* s = globalsStart; s < globalsEnd; ++s) {
605 if ( (s->n_type & N_TYPE) == N_SECT ) {
606 if ( bestSymbol == nullptr ) {
607 if ( (s->n_value <= targetUnslidAddress) && (s->n_sect == sectionIndexForTargetAddress) )
608 bestSymbol = s;
609 }
610 else if ( (s->n_value <= targetUnslidAddress) && (bestSymbol->n_value < s->n_value) && (s->n_sect == sectionIndexForTargetAddress) ) {
611 bestSymbol = s;
612 }
613 }
614 }
615 // next walk all local symbols
616 const struct nlist_64* const localsStart = &symbols64[leInfo.dynSymTab->ilocalsym];
617 const struct nlist_64* const localsEnd = &localsStart[leInfo.dynSymTab->nlocalsym];
618 for (const struct nlist_64* s = localsStart; s < localsEnd; ++s) {
619 if ( ((s->n_type & N_TYPE) == N_SECT) && ((s->n_type & N_STAB) == 0) ) {
620 if ( bestSymbol == nullptr ) {
621 if ( (s->n_value <= targetUnslidAddress) && (s->n_sect == sectionIndexForTargetAddress) )
622 bestSymbol = s;
623 }
624 else if ( (s->n_value <= targetUnslidAddress) && (bestSymbol->n_value < s->n_value) && (s->n_sect == sectionIndexForTargetAddress) ) {
625 bestSymbol = s;
626 }
627 }
628 }
629 if ( bestSymbol != NULL ) {
630 *symbolAddr = bestSymbol->n_value + leInfo.layout.slide;
631 if ( bestSymbol->n_un.n_strx < maxStringOffset )
632 *symbolName = &stringPool[bestSymbol->n_un.n_strx];
633 return true;
634 }
635 }
636 else {
637 const struct nlist* bestSymbol = nullptr;
638 // first walk all global symbols
639 const struct nlist* const globalsStart = &symbols[leInfo.dynSymTab->iextdefsym];
640 const struct nlist* const globalsEnd = &globalsStart[leInfo.dynSymTab->nextdefsym];
641 for (const struct nlist* s = globalsStart; s < globalsEnd; ++s) {
642 if ( (s->n_type & N_TYPE) == N_SECT ) {
643 if ( bestSymbol == nullptr ) {
644 if ( (s->n_value <= targetUnslidAddress) && (s->n_sect == sectionIndexForTargetAddress) )
645 bestSymbol = s;
646 }
647 else if ( (s->n_value <= targetUnslidAddress) && (bestSymbol->n_value < s->n_value) && (s->n_sect == sectionIndexForTargetAddress) ) {
648 bestSymbol = s;
649 }
650 }
651 }
652 // next walk all local symbols
653 const struct nlist* const localsStart = &symbols[leInfo.dynSymTab->ilocalsym];
654 const struct nlist* const localsEnd = &localsStart[leInfo.dynSymTab->nlocalsym];
655 for (const struct nlist* s = localsStart; s < localsEnd; ++s) {
656 if ( ((s->n_type & N_TYPE) == N_SECT) && ((s->n_type & N_STAB) == 0) ) {
657 if ( bestSymbol == nullptr ) {
658 if ( (s->n_value <= targetUnslidAddress) && (s->n_sect == sectionIndexForTargetAddress) )
659 bestSymbol = s;
660 }
661 else if ( (s->n_value <= targetUnslidAddress) && (bestSymbol->n_value < s->n_value) && (s->n_sect == sectionIndexForTargetAddress) ) {
662 bestSymbol = s;
663 }
664 }
665 }
666 if ( bestSymbol != nullptr ) {
667 #if __arm__
668 if ( bestSymbol->n_desc & N_ARM_THUMB_DEF )
669 *symbolAddr = (bestSymbol->n_value | 1) + leInfo.layout.slide;
670 else
671 *symbolAddr = bestSymbol->n_value + leInfo.layout.slide;
672 #else
673 *symbolAddr = bestSymbol->n_value + leInfo.layout.slide;
674 #endif
675 if ( bestSymbol->n_un.n_strx < maxStringOffset )
676 *symbolName = &stringPool[bestSymbol->n_un.n_strx];
677 return true;
678 }
679 }
680
681 return false;
682 }
683
684 const void* MachOLoaded::findSectionContent(const char* segName, const char* sectName, uint64_t& size) const
685 {
686 __block const void* result = nullptr;
687 forEachSection(^(const SectionInfo& sectInfo, bool malformedSectionRange, bool& stop) {
688 if ( (strcmp(sectInfo.sectName, sectName) == 0) && (strcmp(sectInfo.segInfo.segName, segName) == 0) ) {
689 size = sectInfo.sectSize;
690 result = (void*)(sectInfo.sectAddr + getSlide());
691 }
692 });
693 return result;
694 }
695
696
697 bool MachOLoaded::intersectsRange(uintptr_t start, uintptr_t length) const
698 {
699 __block bool result = false;
700 uintptr_t slide = getSlide();
701 forEachSegment(^(const SegmentInfo& info, bool& stop) {
702 if ( (info.vmAddr+info.vmSize+slide >= start) && (info.vmAddr+slide < start+length) )
703 result = true;
704 });
705 return result;
706 }
707
708 const uint8_t* MachOLoaded::trieWalk(Diagnostics& diag, const uint8_t* start, const uint8_t* end, const char* symbol)
709 {
710 uint32_t visitedNodeOffsets[128];
711 int visitedNodeOffsetCount = 0;
712 visitedNodeOffsets[visitedNodeOffsetCount++] = 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 for (int i=0; i < visitedNodeOffsetCount; ++i) {
782 if ( visitedNodeOffsets[i] == nodeOffset ) {
783 diag.error("malformed trie child, cycle to nodeOffset=0x%llX\n", nodeOffset);
784 return nullptr;
785 }
786 }
787 visitedNodeOffsets[visitedNodeOffsetCount++] = (uint32_t)nodeOffset;
788 if ( visitedNodeOffsetCount >= 128 ) {
789 diag.error("malformed trie too deep\n");
790 return nullptr;
791 }
792 p = &start[nodeOffset];
793 }
794 else
795 p = end;
796 }
797 return nullptr;
798 }
799
800 void MachOLoaded::forEachCDHashOfCodeSignature(const void* codeSigStart, size_t codeSignLen,
801 void (^callback)(const uint8_t cdHash[20])) const
802 {
803 forEachCodeDirectoryBlob(codeSigStart, codeSignLen, ^(const void *cdBuffer) {
804 const CS_CodeDirectory* cd = (const CS_CodeDirectory*)cdBuffer;
805 uint32_t cdLength = htonl(cd->length);
806 uint8_t cdHash[20];
807 if ( cd->hashType == CS_HASHTYPE_SHA384 ) {
808 uint8_t digest[CCSHA384_OUTPUT_SIZE];
809 const struct ccdigest_info* di = ccsha384_di();
810 ccdigest_di_decl(di, tempBuf); // declares tempBuf array in stack
811 ccdigest_init(di, tempBuf);
812 ccdigest_update(di, tempBuf, cdLength, cd);
813 ccdigest_final(di, tempBuf, digest);
814 ccdigest_di_clear(di, tempBuf);
815 // cd-hash of sigs that use SHA384 is the first 20 bytes of the SHA384 of the code digest
816 memcpy(cdHash, digest, 20);
817 callback(cdHash);
818 return;
819 }
820 else if ( (cd->hashType == CS_HASHTYPE_SHA256) || (cd->hashType == CS_HASHTYPE_SHA256_TRUNCATED) ) {
821 uint8_t digest[CCSHA256_OUTPUT_SIZE];
822 const struct ccdigest_info* di = ccsha256_di();
823 ccdigest_di_decl(di, tempBuf); // declares tempBuf array in stack
824 ccdigest_init(di, tempBuf);
825 ccdigest_update(di, tempBuf, cdLength, cd);
826 ccdigest_final(di, tempBuf, digest);
827 ccdigest_di_clear(di, tempBuf);
828 // cd-hash of sigs that use SHA256 is the first 20 bytes of the SHA256 of the code digest
829 memcpy(cdHash, digest, 20);
830 callback(cdHash);
831 return;
832 }
833 else if ( cd->hashType == CS_HASHTYPE_SHA1 ) {
834 // compute hash directly into return buffer
835 const struct ccdigest_info* di = ccsha1_di();
836 ccdigest_di_decl(di, tempBuf); // declares tempBuf array in stack
837 ccdigest_init(di, tempBuf);
838 ccdigest_update(di, tempBuf, cdLength, cd);
839 ccdigest_final(di, tempBuf, cdHash);
840 ccdigest_di_clear(di, tempBuf);
841 callback(cdHash);
842 return;
843 }
844 });
845 }
846
847
848 // Note, this has to match the kernel
849 static const uint32_t hashPriorities[] = {
850 CS_HASHTYPE_SHA1,
851 CS_HASHTYPE_SHA256_TRUNCATED,
852 CS_HASHTYPE_SHA256,
853 CS_HASHTYPE_SHA384,
854 };
855
856 static unsigned int hash_rank(const CS_CodeDirectory *cd)
857 {
858 uint32_t type = cd->hashType;
859 for (uint32_t n = 0; n < sizeof(hashPriorities) / sizeof(hashPriorities[0]); ++n) {
860 if (hashPriorities[n] == type)
861 return n + 1;
862 }
863
864 /* not supported */
865 return 0;
866 }
867
868 // Note, this does NOT match the kernel.
869 // On watchOS, in main executables, we will record all cd hashes then make sure
870 // one of the ones we record matches the kernel.
871 // This list is only for dylibs where we embed the cd hash in the closure instead of the
872 // mod time and inode
873 // This is sorted so that we choose sha1 first when checking dylibs
874 static const uint32_t hashPriorities_watchOS_dylibs[] = {
875 CS_HASHTYPE_SHA256_TRUNCATED,
876 CS_HASHTYPE_SHA256,
877 CS_HASHTYPE_SHA384,
878 CS_HASHTYPE_SHA1
879 };
880
881 static unsigned int hash_rank_watchOS_dylibs(const CS_CodeDirectory *cd)
882 {
883 uint32_t type = cd->hashType;
884 for (uint32_t n = 0; n < sizeof(hashPriorities_watchOS_dylibs) / sizeof(hashPriorities_watchOS_dylibs[0]); ++n) {
885 if (hashPriorities_watchOS_dylibs[n] == type)
886 return n + 1;
887 }
888
889 /* not supported */
890 return 0;
891 }
892
893 // This calls the callback for all code directories required for a given platform/binary combination.
894 // On watchOS main executables this is all cd hashes.
895 // On watchOS dylibs this is only the single cd hash we need (by rank defined by dyld, not the kernel).
896 // On all other platforms this always returns a single best cd hash (ranked to match the kernel).
897 // Note the callback parameter is really a CS_CodeDirectory.
898 void MachOLoaded::forEachCodeDirectoryBlob(const void* codeSigStart, size_t codeSignLen,
899 void (^callback)(const void* cd)) const
900 {
901 // verify min length of overall code signature
902 if ( codeSignLen < sizeof(CS_SuperBlob) )
903 return;
904
905 // verify magic at start
906 const CS_SuperBlob* codeSuperBlob = (CS_SuperBlob*)codeSigStart;
907 if ( codeSuperBlob->magic != htonl(CSMAGIC_EMBEDDED_SIGNATURE) )
908 return;
909
910 // verify count of sub-blobs not too large
911 uint32_t subBlobCount = htonl(codeSuperBlob->count);
912 if ( (codeSignLen-sizeof(CS_SuperBlob))/sizeof(CS_BlobIndex) < subBlobCount )
913 return;
914
915 // Note: The kernel sometimes chooses sha1 on watchOS, and sometimes sha256.
916 // Embed all of them so that we just need to match any of them
917 const bool isWatchOS = this->supportsPlatform(Platform::watchOS);
918 const bool isMainExecutable = this->isMainExecutable();
919 auto hashRankFn = isWatchOS ? &hash_rank_watchOS_dylibs : &hash_rank;
920
921 // walk each sub blob, looking at ones with type CSSLOT_CODEDIRECTORY
922 const CS_CodeDirectory* bestCd = nullptr;
923 for (uint32_t i=0; i < subBlobCount; ++i) {
924 if ( codeSuperBlob->index[i].type == htonl(CSSLOT_CODEDIRECTORY) ) {
925 // Ok, this is the regular code directory
926 } else if ( codeSuperBlob->index[i].type >= htonl(CSSLOT_ALTERNATE_CODEDIRECTORIES) && codeSuperBlob->index[i].type <= htonl(CSSLOT_ALTERNATE_CODEDIRECTORY_LIMIT)) {
927 // Ok, this is the alternative code directory
928 } else {
929 continue;
930 }
931 uint32_t cdOffset = htonl(codeSuperBlob->index[i].offset);
932 // verify offset is not out of range
933 if ( cdOffset > (codeSignLen - sizeof(CS_CodeDirectory)) )
934 continue;
935 const CS_CodeDirectory* cd = (CS_CodeDirectory*)((uint8_t*)codeSuperBlob + cdOffset);
936 uint32_t cdLength = htonl(cd->length);
937 // verify code directory length not out of range
938 if ( cdLength > (codeSignLen - cdOffset) )
939 continue;
940
941 // The watch main executable wants to know about all cd hashes
942 if ( isWatchOS && isMainExecutable ) {
943 callback(cd);
944 continue;
945 }
946
947 if ( cd->magic == htonl(CSMAGIC_CODEDIRECTORY) ) {
948 if ( !bestCd || (hashRankFn(cd) > hashRankFn(bestCd)) )
949 bestCd = cd;
950 }
951 }
952
953 // Note this callback won't happen on watchOS as that one was done in the loop
954 if ( bestCd != nullptr )
955 callback(bestCd);
956 }
957
958
959 uint64_t MachOLoaded::ChainedFixupPointerOnDisk::Arm64e::unpackTarget() const
960 {
961 assert(this->authBind.bind == 0);
962 assert(this->authBind.auth == 0);
963 return ((uint64_t)(this->rebase.high8) << 56) | (this->rebase.target);
964 }
965
966 uint64_t MachOLoaded::ChainedFixupPointerOnDisk::Arm64e::signExtendedAddend() const
967 {
968 assert(this->authBind.bind == 1);
969 assert(this->authBind.auth == 0);
970 uint64_t addend19 = this->bind.addend;
971 if ( addend19 & 0x40000 )
972 return addend19 | 0xFFFFFFFFFFFC0000ULL;
973 else
974 return addend19;
975 }
976
977 const char* MachOLoaded::ChainedFixupPointerOnDisk::Arm64e::keyName() const
978 {
979 static const char* names[] = {
980 "IA", "IB", "DA", "DB"
981 };
982 assert(this->authBind.auth == 1);
983 uint8_t keyBits = this->authBind.key;
984 assert(keyBits < 4);
985 return names[keyBits];
986 }
987
988 uint64_t MachOLoaded::ChainedFixupPointerOnDisk::Arm64e::signPointer(void* loc, uint64_t target) const
989 {
990 assert(this->authBind.auth == 1);
991 #if __has_feature(ptrauth_calls)
992 uint64_t discriminator = authBind.diversity;
993 if ( authBind.addrDiv )
994 discriminator = __builtin_ptrauth_blend_discriminator(loc, discriminator);
995 switch ( authBind.key ) {
996 case 0: // IA
997 return (uint64_t)__builtin_ptrauth_sign_unauthenticated((void*)target, 0, discriminator);
998 case 1: // IB
999 return (uint64_t)__builtin_ptrauth_sign_unauthenticated((void*)target, 1, discriminator);
1000 case 2: // DA
1001 return (uint64_t)__builtin_ptrauth_sign_unauthenticated((void*)target, 2, discriminator);
1002 case 3: // DB
1003 return (uint64_t)__builtin_ptrauth_sign_unauthenticated((void*)target, 3, discriminator);
1004 }
1005 #endif
1006 return target;
1007 }
1008
1009 uint64_t MachOLoaded::ChainedFixupPointerOnDisk::Generic64::unpackedTarget() const
1010 {
1011 return (((uint64_t)this->rebase.high8) << 56) | (uint64_t)(this->rebase.target);
1012 }
1013
1014 uint64_t MachOLoaded::ChainedFixupPointerOnDisk::Generic64::signExtendedAddend() const
1015 {
1016 uint64_t addend27 = this->bind.addend;
1017 uint64_t top8Bits = addend27 & 0x00007F80000ULL;
1018 uint64_t bottom19Bits = addend27 & 0x0000007FFFFULL;
1019 uint64_t newValue = (top8Bits << 13) | (((uint64_t)(bottom19Bits << 37) >> 37) & 0x00FFFFFFFFFFFFFF);
1020 return newValue;
1021 }
1022
1023 bool MachOLoaded::ChainedFixupPointerOnDisk::isRebase(uint16_t pointerFormat, uint64_t preferedLoadAddress, uint64_t& targetRuntimeOffset) const
1024 {
1025 switch (pointerFormat) {
1026 case DYLD_CHAINED_PTR_ARM64E:
1027 if ( this->arm64e.bind.bind )
1028 return false;
1029 if ( this->arm64e.authRebase.auth ) {
1030 targetRuntimeOffset = this->arm64e.authRebase.target;
1031 return true;
1032 }
1033 else {
1034 targetRuntimeOffset = this->arm64e.unpackTarget() - preferedLoadAddress;
1035 return true;
1036 }
1037 break;
1038 case DYLD_CHAINED_PTR_ARM64E_OFFSET:
1039 case DYLD_CHAINED_PTR_ARM64E_USERLAND:
1040 if ( this->arm64e.bind.bind )
1041 return false;
1042 if ( this->arm64e.authRebase.auth ) {
1043 targetRuntimeOffset = this->arm64e.authRebase.target;
1044 return true;
1045 }
1046 else {
1047 targetRuntimeOffset = this->arm64e.unpackTarget();
1048 return true;
1049 }
1050 break;
1051 case DYLD_CHAINED_PTR_64:
1052 if ( this->generic64.bind.bind )
1053 return false;
1054 targetRuntimeOffset = this->generic64.unpackedTarget() - preferedLoadAddress;
1055 return true;
1056 break;
1057 case DYLD_CHAINED_PTR_64_OFFSET:
1058 if ( this->generic64.bind.bind )
1059 return false;
1060 targetRuntimeOffset = this->generic64.unpackedTarget();
1061 return true;
1062 break;
1063 case DYLD_CHAINED_PTR_32:
1064 if ( this->generic32.bind.bind )
1065 return false;
1066 targetRuntimeOffset = this->generic32.rebase.target - preferedLoadAddress;
1067 return true;
1068 break;
1069 default:
1070 break;
1071 }
1072 assert(0 && "unsupported pointer chain format");
1073 }
1074
1075 bool MachOLoaded::ChainedFixupPointerOnDisk::isBind(uint16_t pointerFormat, uint32_t& bindOrdinal) const
1076 {
1077 switch (pointerFormat) {
1078 case DYLD_CHAINED_PTR_ARM64E:
1079 case DYLD_CHAINED_PTR_ARM64E_OFFSET:
1080 case DYLD_CHAINED_PTR_ARM64E_USERLAND:
1081 if ( !this->arm64e.authBind.bind )
1082 return false;
1083 if ( this->arm64e.authBind.auth ) {
1084 bindOrdinal = this->arm64e.authBind.ordinal;
1085 return true;
1086 }
1087 else {
1088 bindOrdinal = this->arm64e.bind.ordinal;
1089 return true;
1090 }
1091 break;
1092 case DYLD_CHAINED_PTR_64:
1093 case DYLD_CHAINED_PTR_64_OFFSET:
1094 if ( !this->generic64.bind.bind )
1095 return false;
1096 bindOrdinal = this->generic64.bind.ordinal;
1097 return true;
1098 break;
1099 case DYLD_CHAINED_PTR_32:
1100 if ( !this->generic32.bind.bind )
1101 return false;
1102 bindOrdinal = this->generic32.bind.ordinal;
1103 return true;
1104 break;
1105 default:
1106 break;
1107 }
1108 assert(0 && "unsupported pointer chain format");
1109 }
1110
1111 #if BUILDING_DYLD || BUILDING_LIBDYLD
1112 void MachOLoaded::fixupAllChainedFixups(Diagnostics& diag, const dyld_chained_starts_in_image* starts, uintptr_t slide,
1113 Array<const void*> bindTargets, void (^logFixup)(void* loc, void* newValue)) const
1114 {
1115 forEachFixupInAllChains(diag, starts, true, ^(ChainedFixupPointerOnDisk* fixupLoc, const dyld_chained_starts_in_segment* segInfo, bool& stop) {
1116 void* newValue;
1117 switch (segInfo->pointer_format) {
1118 #if __LP64__
1119 #if __has_feature(ptrauth_calls)
1120 case DYLD_CHAINED_PTR_ARM64E:
1121 if ( fixupLoc->arm64e.authRebase.auth ) {
1122 if ( fixupLoc->arm64e.authBind.bind ) {
1123 if ( fixupLoc->arm64e.authBind.ordinal >= bindTargets.count() ) {
1124 diag.error("out of range bind ordinal %d (max %lu)", fixupLoc->arm64e.authBind.ordinal, bindTargets.count());
1125 stop = true;
1126 break;
1127 }
1128 else {
1129 // authenticated bind
1130 newValue = (void*)(bindTargets[fixupLoc->arm64e.bind.ordinal]);
1131 if (newValue != 0) // Don't sign missing weak imports
1132 newValue = (void*)fixupLoc->arm64e.signPointer(fixupLoc, (uintptr_t)newValue);
1133 }
1134 }
1135 else {
1136 // authenticated rebase
1137 newValue = (void*)fixupLoc->arm64e.signPointer(fixupLoc, (uintptr_t)this + fixupLoc->arm64e.authRebase.target);
1138 }
1139 }
1140 else {
1141 if ( fixupLoc->arm64e.bind.bind ) {
1142 if ( fixupLoc->arm64e.bind.ordinal >= bindTargets.count() ) {
1143 diag.error("out of range bind ordinal %d (max %lu)", fixupLoc->arm64e.bind.ordinal, bindTargets.count());
1144 stop = true;
1145 break;
1146 }
1147 else {
1148 // plain bind
1149 newValue = (void*)((long)bindTargets[fixupLoc->arm64e.bind.ordinal] + fixupLoc->arm64e.signExtendedAddend());
1150 }
1151 }
1152 else {
1153 // plain rebase
1154 newValue = (void*)(fixupLoc->arm64e.unpackTarget()+slide);
1155 }
1156 }
1157 if ( logFixup )
1158 logFixup(fixupLoc, newValue);
1159 fixupLoc->raw64 = (uintptr_t)newValue;
1160 break;
1161 case DYLD_CHAINED_PTR_ARM64E_OFFSET:
1162 case DYLD_CHAINED_PTR_ARM64E_USERLAND:
1163 if ( fixupLoc->arm64e.authRebase.auth ) {
1164 if ( fixupLoc->arm64e.authBind.bind ) {
1165 if ( fixupLoc->arm64e.authBind.ordinal >= bindTargets.count() ) {
1166 diag.error("out of range bind ordinal %d (max %lu)", fixupLoc->arm64e.authBind.ordinal, bindTargets.count());
1167 stop = true;
1168 break;
1169 }
1170 else {
1171 // authenticated bind
1172 newValue = (void*)(bindTargets[fixupLoc->arm64e.bind.ordinal]);
1173 if (newValue != 0) // Don't sign missing weak imports
1174 newValue = (void*)fixupLoc->arm64e.signPointer(fixupLoc, (uintptr_t)newValue);
1175 }
1176 }
1177 else {
1178 // authenticated rebase
1179 newValue = (void*)fixupLoc->arm64e.signPointer(fixupLoc, (uintptr_t)this + fixupLoc->arm64e.authRebase.target);
1180 }
1181 }
1182 else {
1183 if ( fixupLoc->arm64e.bind.bind ) {
1184 if ( fixupLoc->arm64e.bind.ordinal >= bindTargets.count() ) {
1185 diag.error("out of range bind ordinal %d (max %lu)", fixupLoc->arm64e.bind.ordinal, bindTargets.count());
1186 stop = true;
1187 break;
1188 }
1189 else {
1190 // plain bind
1191 newValue = (void*)((long)bindTargets[fixupLoc->arm64e.bind.ordinal] + fixupLoc->arm64e.signExtendedAddend());
1192 }
1193 }
1194 else {
1195 // plain rebase
1196 newValue = (void*)((uintptr_t)this + fixupLoc->arm64e.unpackTarget());
1197 }
1198 }
1199 if ( logFixup )
1200 logFixup(fixupLoc, newValue);
1201 fixupLoc->raw64 = (uintptr_t)newValue;
1202 break;
1203 #endif
1204 case DYLD_CHAINED_PTR_64:
1205 if ( fixupLoc->generic64.bind.bind ) {
1206 if ( fixupLoc->generic64.bind.ordinal >= bindTargets.count() ) {
1207 diag.error("out of range bind ordinal %d (max %lu)", fixupLoc->generic64.bind.ordinal, bindTargets.count());
1208 stop = true;
1209 break;
1210 }
1211 else {
1212 newValue = (void*)((long)bindTargets[fixupLoc->generic64.bind.ordinal] + fixupLoc->generic64.signExtendedAddend());
1213 }
1214 }
1215 else {
1216 newValue = (void*)(fixupLoc->generic64.unpackedTarget()+slide);
1217 }
1218 if ( logFixup )
1219 logFixup(fixupLoc, newValue);
1220 fixupLoc->raw64 = (uintptr_t)newValue;
1221 break;
1222 case DYLD_CHAINED_PTR_64_OFFSET:
1223 if ( fixupLoc->generic64.bind.bind ) {
1224 if ( fixupLoc->generic64.bind.ordinal >= bindTargets.count() ) {
1225 diag.error("out of range bind ordinal %d (max %lu)", fixupLoc->generic64.bind.ordinal, bindTargets.count());
1226 stop = true;
1227 break;
1228 }
1229 else {
1230 newValue = (void*)((long)bindTargets[fixupLoc->generic64.bind.ordinal] + fixupLoc->generic64.signExtendedAddend());
1231 }
1232 }
1233 else {
1234 newValue = (void*)((uintptr_t)this + fixupLoc->generic64.unpackedTarget());
1235 }
1236 if ( logFixup )
1237 logFixup(fixupLoc, newValue);
1238 fixupLoc->raw64 = (uintptr_t)newValue;
1239 break;
1240 #else
1241 case DYLD_CHAINED_PTR_32:
1242 if ( fixupLoc->generic32.bind.bind ) {
1243 if ( fixupLoc->generic32.bind.ordinal >= bindTargets.count() ) {
1244 diag.error("out of range bind ordinal %d (max %lu)", fixupLoc->generic32.bind.ordinal, bindTargets.count());
1245 stop = true;
1246 break;
1247 }
1248 else {
1249 newValue = (void*)((long)bindTargets[fixupLoc->generic32.bind.ordinal] + fixupLoc->generic32.bind.addend);
1250 }
1251 }
1252 else {
1253 if ( fixupLoc->generic32.rebase.target > segInfo->max_valid_pointer ) {
1254 // handle non-pointers in chain
1255 uint32_t bias = (0x04000000 + segInfo->max_valid_pointer)/2;
1256 newValue = (void*)(fixupLoc->generic32.rebase.target - bias);
1257 }
1258 else {
1259 newValue = (void*)(fixupLoc->generic32.rebase.target + slide);
1260 }
1261 }
1262 if ( logFixup )
1263 logFixup(fixupLoc, newValue);
1264 fixupLoc->raw32 = (uint32_t)(uintptr_t)newValue;
1265 break;
1266 #endif // __LP64__
1267 default:
1268 diag.error("unsupported pointer chain format: 0x%04X", segInfo->pointer_format);
1269 stop = true;
1270 break;
1271 }
1272 });
1273 }
1274 #endif
1275
1276 bool MachOLoaded::walkChain(Diagnostics& diag, const dyld_chained_starts_in_segment* segInfo, uint32_t pageIndex, uint16_t offsetInPage,
1277 bool notifyNonPointers, void (^handler)(ChainedFixupPointerOnDisk* fixupLocation, const dyld_chained_starts_in_segment* segInfo, bool& stop)) const
1278 {
1279 bool stop = false;
1280 uint8_t* pageContentStart = (uint8_t*)this + segInfo->segment_offset + (pageIndex * segInfo->page_size);
1281 ChainedFixupPointerOnDisk* chain = (ChainedFixupPointerOnDisk*)(pageContentStart+offsetInPage);
1282 bool chainEnd = false;
1283 while (!stop && !chainEnd) {
1284 // copy chain content, in case handler modifies location to final value
1285 ChainedFixupPointerOnDisk chainContent = *chain;
1286 handler(chain, segInfo, stop);
1287 if ( !stop ) {
1288 switch (segInfo->pointer_format) {
1289 case DYLD_CHAINED_PTR_ARM64E:
1290 case DYLD_CHAINED_PTR_ARM64E_USERLAND:
1291 if ( chainContent.arm64e.rebase.next == 0 )
1292 chainEnd = true;
1293 else
1294 chain = (ChainedFixupPointerOnDisk*)((uint8_t*)chain + chainContent.arm64e.rebase.next*8);
1295 break;
1296 case DYLD_CHAINED_PTR_64:
1297 case DYLD_CHAINED_PTR_64_OFFSET:
1298 case DYLD_CHAINED_PTR_ARM64E_OFFSET:
1299 if ( chainContent.generic64.rebase.next == 0 )
1300 chainEnd = true;
1301 else
1302 chain = (ChainedFixupPointerOnDisk*)((uint8_t*)chain + chainContent.generic64.rebase.next*4);
1303 break;
1304 case DYLD_CHAINED_PTR_32:
1305 if ( chainContent.generic32.rebase.next == 0 )
1306 chainEnd = true;
1307 else {
1308 chain = (ChainedFixupPointerOnDisk*)((uint8_t*)chain + chainContent.generic32.rebase.next*4);
1309 if ( !notifyNonPointers ) {
1310 while ( (chain->generic32.rebase.bind == 0) && (chain->generic32.rebase.target > segInfo->max_valid_pointer) ) {
1311 // not a real pointer, but a non-pointer co-opted into chain
1312 chain = (ChainedFixupPointerOnDisk*)((uint8_t*)chain + chain->generic32.rebase.next*4);
1313 }
1314 }
1315 }
1316 break;
1317 default:
1318 diag.error("unknown pointer format 0x%04X", segInfo->pointer_format);
1319 stop = true;
1320 }
1321 }
1322 }
1323 return stop;
1324 }
1325
1326 void MachOLoaded::forEachFixupInAllChains(Diagnostics& diag, const dyld_chained_starts_in_image* starts, bool notifyNonPointers,
1327 void (^handler)(ChainedFixupPointerOnDisk* fixupLocation, const dyld_chained_starts_in_segment* segInfo, bool& stop)) const
1328 {
1329 bool stopped = false;
1330 for (uint32_t segIndex=0; segIndex < starts->seg_count && !stopped; ++segIndex) {
1331 if ( starts->seg_info_offset[segIndex] == 0 )
1332 continue;
1333 const dyld_chained_starts_in_segment* segInfo = (dyld_chained_starts_in_segment*)((uint8_t*)starts + starts->seg_info_offset[segIndex]);
1334 for (uint32_t pageIndex=0; pageIndex < segInfo->page_count && !stopped; ++pageIndex) {
1335 uint16_t offsetInPage = segInfo->page_start[pageIndex];
1336 if ( offsetInPage == DYLD_CHAINED_PTR_START_NONE )
1337 continue;
1338 if ( offsetInPage & DYLD_CHAINED_PTR_START_MULTI ) {
1339 // 32-bit chains which may need multiple starts per page
1340 uint32_t overflowIndex = offsetInPage & ~DYLD_CHAINED_PTR_START_MULTI;
1341 bool chainEnd = false;
1342 while (!stopped && !chainEnd) {
1343 chainEnd = (segInfo->page_start[overflowIndex] & DYLD_CHAINED_PTR_START_LAST);
1344 offsetInPage = (segInfo->page_start[overflowIndex] & ~DYLD_CHAINED_PTR_START_LAST);
1345 if ( walkChain(diag, segInfo, pageIndex, offsetInPage, notifyNonPointers, handler) )
1346 stopped = true;
1347 ++overflowIndex;
1348 }
1349 }
1350 else {
1351 // one chain per page
1352 walkChain(diag, segInfo, pageIndex, offsetInPage, notifyNonPointers, handler);
1353 }
1354 }
1355 }
1356 }
1357
1358
1359 } // namespace dyld3
1360