dyld-732.8.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 uint32_t maxStringOffset = leInfo.symTab->strsize;
587 const char* stringPool = (char*)getLinkEditContent(leInfo.layout, leInfo.symTab->stroff);
588 const struct nlist* symbols = (struct nlist*) (getLinkEditContent(leInfo.layout, leInfo.symTab->symoff));
589 if ( is64() ) {
590 const struct nlist_64* symbols64 = (struct nlist_64*)symbols;
591 const struct nlist_64* bestSymbol = nullptr;
592 // first walk all global symbols
593 const struct nlist_64* const globalsStart = &symbols64[leInfo.dynSymTab->iextdefsym];
594 const struct nlist_64* const globalsEnd = &globalsStart[leInfo.dynSymTab->nextdefsym];
595 for (const struct nlist_64* s = globalsStart; s < globalsEnd; ++s) {
596 if ( (s->n_type & N_TYPE) == N_SECT ) {
597 if ( bestSymbol == nullptr ) {
598 if ( s->n_value <= targetUnslidAddress )
599 bestSymbol = s;
600 }
601 else if ( (s->n_value <= targetUnslidAddress) && (bestSymbol->n_value < s->n_value) ) {
602 bestSymbol = s;
603 }
604 }
605 }
606 // next walk all local symbols
607 const struct nlist_64* const localsStart = &symbols64[leInfo.dynSymTab->ilocalsym];
608 const struct nlist_64* const localsEnd = &localsStart[leInfo.dynSymTab->nlocalsym];
609 for (const struct nlist_64* s = localsStart; s < localsEnd; ++s) {
610 if ( ((s->n_type & N_TYPE) == N_SECT) && ((s->n_type & N_STAB) == 0) ) {
611 if ( bestSymbol == nullptr ) {
612 if ( s->n_value <= targetUnslidAddress )
613 bestSymbol = s;
614 }
615 else if ( (s->n_value <= targetUnslidAddress) && (bestSymbol->n_value < s->n_value) ) {
616 bestSymbol = s;
617 }
618 }
619 }
620 if ( bestSymbol != NULL ) {
621 *symbolAddr = bestSymbol->n_value + leInfo.layout.slide;
622 if ( bestSymbol->n_un.n_strx < maxStringOffset )
623 *symbolName = &stringPool[bestSymbol->n_un.n_strx];
624 return true;
625 }
626 }
627 else {
628 const struct nlist* bestSymbol = nullptr;
629 // first walk all global symbols
630 const struct nlist* const globalsStart = &symbols[leInfo.dynSymTab->iextdefsym];
631 const struct nlist* const globalsEnd = &globalsStart[leInfo.dynSymTab->nextdefsym];
632 for (const struct nlist* s = globalsStart; s < globalsEnd; ++s) {
633 if ( (s->n_type & N_TYPE) == N_SECT ) {
634 if ( bestSymbol == nullptr ) {
635 if ( s->n_value <= targetUnslidAddress )
636 bestSymbol = s;
637 }
638 else if ( (s->n_value <= targetUnslidAddress) && (bestSymbol->n_value < s->n_value) ) {
639 bestSymbol = s;
640 }
641 }
642 }
643 // next walk all local symbols
644 const struct nlist* const localsStart = &symbols[leInfo.dynSymTab->ilocalsym];
645 const struct nlist* const localsEnd = &localsStart[leInfo.dynSymTab->nlocalsym];
646 for (const struct nlist* s = localsStart; s < localsEnd; ++s) {
647 if ( ((s->n_type & N_TYPE) == N_SECT) && ((s->n_type & N_STAB) == 0) ) {
648 if ( bestSymbol == nullptr ) {
649 if ( s->n_value <= targetUnslidAddress )
650 bestSymbol = s;
651 }
652 else if ( (s->n_value <= targetUnslidAddress) && (bestSymbol->n_value < s->n_value) ) {
653 bestSymbol = s;
654 }
655 }
656 }
657 if ( bestSymbol != nullptr ) {
658 #if __arm__
659 if ( bestSymbol->n_desc & N_ARM_THUMB_DEF )
660 *symbolAddr = (bestSymbol->n_value | 1) + leInfo.layout.slide;
661 else
662 *symbolAddr = bestSymbol->n_value + leInfo.layout.slide;
663 #else
664 *symbolAddr = bestSymbol->n_value + leInfo.layout.slide;
665 #endif
666 if ( bestSymbol->n_un.n_strx < maxStringOffset )
667 *symbolName = &stringPool[bestSymbol->n_un.n_strx];
668 return true;
669 }
670 }
671
672 return false;
673 }
674
675 const void* MachOLoaded::findSectionContent(const char* segName, const char* sectName, uint64_t& size) const
676 {
677 __block const void* result = nullptr;
678 forEachSection(^(const SectionInfo& sectInfo, bool malformedSectionRange, bool& stop) {
679 if ( (strcmp(sectInfo.sectName, sectName) == 0) && (strcmp(sectInfo.segInfo.segName, segName) == 0) ) {
680 size = sectInfo.sectSize;
681 result = (void*)(sectInfo.sectAddr + getSlide());
682 }
683 });
684 return result;
685 }
686
687
688 bool MachOLoaded::intersectsRange(uintptr_t start, uintptr_t length) const
689 {
690 __block bool result = false;
691 uintptr_t slide = getSlide();
692 forEachSegment(^(const SegmentInfo& info, bool& stop) {
693 if ( (info.vmAddr+info.vmSize+slide >= start) && (info.vmAddr+slide < start+length) )
694 result = true;
695 });
696 return result;
697 }
698
699 const uint8_t* MachOLoaded::trieWalk(Diagnostics& diag, const uint8_t* start, const uint8_t* end, const char* symbol)
700 {
701 uint32_t visitedNodeOffsets[128];
702 int visitedNodeOffsetCount = 0;
703 visitedNodeOffsets[visitedNodeOffsetCount++] = 0;
704 const uint8_t* p = start;
705 while ( p < end ) {
706 uint64_t terminalSize = *p++;
707 if ( terminalSize > 127 ) {
708 // except for re-export-with-rename, all terminal sizes fit in one byte
709 --p;
710 terminalSize = read_uleb128(diag, p, end);
711 if ( diag.hasError() )
712 return nullptr;
713 }
714 if ( (*symbol == '\0') && (terminalSize != 0) ) {
715 return p;
716 }
717 const uint8_t* children = p + terminalSize;
718 if ( children > end ) {
719 //diag.error("malformed trie node, terminalSize=0x%llX extends past end of trie\n", terminalSize);
720 return nullptr;
721 }
722 uint8_t childrenRemaining = *children++;
723 p = children;
724 uint64_t nodeOffset = 0;
725 for (; childrenRemaining > 0; --childrenRemaining) {
726 const char* ss = symbol;
727 bool wrongEdge = false;
728 // scan whole edge to get to next edge
729 // if edge is longer than target symbol name, don't read past end of symbol name
730 char c = *p;
731 while ( c != '\0' ) {
732 if ( !wrongEdge ) {
733 if ( c != *ss )
734 wrongEdge = true;
735 ++ss;
736 }
737 ++p;
738 c = *p;
739 }
740 if ( wrongEdge ) {
741 // advance to next child
742 ++p; // skip over zero terminator
743 // skip over uleb128 until last byte is found
744 while ( (*p & 0x80) != 0 )
745 ++p;
746 ++p; // skip over last byte of uleb128
747 if ( p > end ) {
748 diag.error("malformed trie node, child node extends past end of trie\n");
749 return nullptr;
750 }
751 }
752 else {
753 // the symbol so far matches this edge (child)
754 // so advance to the child's node
755 ++p;
756 nodeOffset = read_uleb128(diag, p, end);
757 if ( diag.hasError() )
758 return nullptr;
759 if ( (nodeOffset == 0) || ( &start[nodeOffset] > end) ) {
760 diag.error("malformed trie child, nodeOffset=0x%llX out of range\n", nodeOffset);
761 return nullptr;
762 }
763 symbol = ss;
764 break;
765 }
766 }
767 if ( nodeOffset != 0 ) {
768 if ( nodeOffset > (uint64_t)(end-start) ) {
769 diag.error("malformed trie child, nodeOffset=0x%llX out of range\n", nodeOffset);
770 return nullptr;
771 }
772 for (int i=0; i < visitedNodeOffsetCount; ++i) {
773 if ( visitedNodeOffsets[i] == nodeOffset ) {
774 diag.error("malformed trie child, cycle to nodeOffset=0x%llX\n", nodeOffset);
775 return nullptr;
776 }
777 }
778 visitedNodeOffsets[visitedNodeOffsetCount++] = (uint32_t)nodeOffset;
779 if ( visitedNodeOffsetCount >= 128 ) {
780 diag.error("malformed trie too deep\n");
781 return nullptr;
782 }
783 p = &start[nodeOffset];
784 }
785 else
786 p = end;
787 }
788 return nullptr;
789 }
790
791 void MachOLoaded::forEachCDHashOfCodeSignature(const void* codeSigStart, size_t codeSignLen,
792 void (^callback)(const uint8_t cdHash[20])) const
793 {
794 forEachCodeDirectoryBlob(codeSigStart, codeSignLen, ^(const void *cdBuffer) {
795 const CS_CodeDirectory* cd = (const CS_CodeDirectory*)cdBuffer;
796 uint32_t cdLength = htonl(cd->length);
797 uint8_t cdHash[20];
798 if ( cd->hashType == CS_HASHTYPE_SHA384 ) {
799 uint8_t digest[CCSHA384_OUTPUT_SIZE];
800 const struct ccdigest_info* di = ccsha384_di();
801 ccdigest_di_decl(di, tempBuf); // declares tempBuf array in stack
802 ccdigest_init(di, tempBuf);
803 ccdigest_update(di, tempBuf, cdLength, cd);
804 ccdigest_final(di, tempBuf, digest);
805 ccdigest_di_clear(di, tempBuf);
806 // cd-hash of sigs that use SHA384 is the first 20 bytes of the SHA384 of the code digest
807 memcpy(cdHash, digest, 20);
808 callback(cdHash);
809 return;
810 }
811 else if ( (cd->hashType == CS_HASHTYPE_SHA256) || (cd->hashType == CS_HASHTYPE_SHA256_TRUNCATED) ) {
812 uint8_t digest[CCSHA256_OUTPUT_SIZE];
813 const struct ccdigest_info* di = ccsha256_di();
814 ccdigest_di_decl(di, tempBuf); // declares tempBuf array in stack
815 ccdigest_init(di, tempBuf);
816 ccdigest_update(di, tempBuf, cdLength, cd);
817 ccdigest_final(di, tempBuf, digest);
818 ccdigest_di_clear(di, tempBuf);
819 // cd-hash of sigs that use SHA256 is the first 20 bytes of the SHA256 of the code digest
820 memcpy(cdHash, digest, 20);
821 callback(cdHash);
822 return;
823 }
824 else if ( cd->hashType == CS_HASHTYPE_SHA1 ) {
825 // compute hash directly into return buffer
826 const struct ccdigest_info* di = ccsha1_di();
827 ccdigest_di_decl(di, tempBuf); // declares tempBuf array in stack
828 ccdigest_init(di, tempBuf);
829 ccdigest_update(di, tempBuf, cdLength, cd);
830 ccdigest_final(di, tempBuf, cdHash);
831 ccdigest_di_clear(di, tempBuf);
832 callback(cdHash);
833 return;
834 }
835 });
836 }
837
838
839 // Note, this has to match the kernel
840 static const uint32_t hashPriorities[] = {
841 CS_HASHTYPE_SHA1,
842 CS_HASHTYPE_SHA256_TRUNCATED,
843 CS_HASHTYPE_SHA256,
844 CS_HASHTYPE_SHA384,
845 };
846
847 static unsigned int hash_rank(const CS_CodeDirectory *cd)
848 {
849 uint32_t type = cd->hashType;
850 for (uint32_t n = 0; n < sizeof(hashPriorities) / sizeof(hashPriorities[0]); ++n) {
851 if (hashPriorities[n] == type)
852 return n + 1;
853 }
854
855 /* not supported */
856 return 0;
857 }
858
859 // Note, this does NOT match the kernel.
860 // On watchOS, in main executables, we will record all cd hashes then make sure
861 // one of the ones we record matches the kernel.
862 // This list is only for dylibs where we embed the cd hash in the closure instead of the
863 // mod time and inode
864 // This is sorted so that we choose sha1 first when checking dylibs
865 static const uint32_t hashPriorities_watchOS_dylibs[] = {
866 CS_HASHTYPE_SHA256_TRUNCATED,
867 CS_HASHTYPE_SHA256,
868 CS_HASHTYPE_SHA384,
869 CS_HASHTYPE_SHA1
870 };
871
872 static unsigned int hash_rank_watchOS_dylibs(const CS_CodeDirectory *cd)
873 {
874 uint32_t type = cd->hashType;
875 for (uint32_t n = 0; n < sizeof(hashPriorities_watchOS_dylibs) / sizeof(hashPriorities_watchOS_dylibs[0]); ++n) {
876 if (hashPriorities_watchOS_dylibs[n] == type)
877 return n + 1;
878 }
879
880 /* not supported */
881 return 0;
882 }
883
884 // This calls the callback for all code directories required for a given platform/binary combination.
885 // On watchOS main executables this is all cd hashes.
886 // On watchOS dylibs this is only the single cd hash we need (by rank defined by dyld, not the kernel).
887 // On all other platforms this always returns a single best cd hash (ranked to match the kernel).
888 // Note the callback parameter is really a CS_CodeDirectory.
889 void MachOLoaded::forEachCodeDirectoryBlob(const void* codeSigStart, size_t codeSignLen,
890 void (^callback)(const void* cd)) const
891 {
892 // verify min length of overall code signature
893 if ( codeSignLen < sizeof(CS_SuperBlob) )
894 return;
895
896 // verify magic at start
897 const CS_SuperBlob* codeSuperBlob = (CS_SuperBlob*)codeSigStart;
898 if ( codeSuperBlob->magic != htonl(CSMAGIC_EMBEDDED_SIGNATURE) )
899 return;
900
901 // verify count of sub-blobs not too large
902 uint32_t subBlobCount = htonl(codeSuperBlob->count);
903 if ( (codeSignLen-sizeof(CS_SuperBlob))/sizeof(CS_BlobIndex) < subBlobCount )
904 return;
905
906 // Note: The kernel sometimes chooses sha1 on watchOS, and sometimes sha256.
907 // Embed all of them so that we just need to match any of them
908 const bool isWatchOS = this->supportsPlatform(Platform::watchOS);
909 const bool isMainExecutable = this->isMainExecutable();
910 auto hashRankFn = isWatchOS ? &hash_rank_watchOS_dylibs : &hash_rank;
911
912 // walk each sub blob, looking at ones with type CSSLOT_CODEDIRECTORY
913 const CS_CodeDirectory* bestCd = nullptr;
914 for (uint32_t i=0; i < subBlobCount; ++i) {
915 if ( codeSuperBlob->index[i].type == htonl(CSSLOT_CODEDIRECTORY) ) {
916 // Ok, this is the regular code directory
917 } else if ( codeSuperBlob->index[i].type >= htonl(CSSLOT_ALTERNATE_CODEDIRECTORIES) && codeSuperBlob->index[i].type <= htonl(CSSLOT_ALTERNATE_CODEDIRECTORY_LIMIT)) {
918 // Ok, this is the alternative code directory
919 } else {
920 continue;
921 }
922 uint32_t cdOffset = htonl(codeSuperBlob->index[i].offset);
923 // verify offset is not out of range
924 if ( cdOffset > (codeSignLen - sizeof(CS_CodeDirectory)) )
925 continue;
926 const CS_CodeDirectory* cd = (CS_CodeDirectory*)((uint8_t*)codeSuperBlob + cdOffset);
927 uint32_t cdLength = htonl(cd->length);
928 // verify code directory length not out of range
929 if ( cdLength > (codeSignLen - cdOffset) )
930 continue;
931
932 // The watch main executable wants to know about all cd hashes
933 if ( isWatchOS && isMainExecutable ) {
934 callback(cd);
935 continue;
936 }
937
938 if ( cd->magic == htonl(CSMAGIC_CODEDIRECTORY) ) {
939 if ( !bestCd || (hashRankFn(cd) > hashRankFn(bestCd)) )
940 bestCd = cd;
941 }
942 }
943
944 // Note this callback won't happen on watchOS as that one was done in the loop
945 if ( bestCd != nullptr )
946 callback(bestCd);
947 }
948
949
950 uint64_t MachOLoaded::ChainedFixupPointerOnDisk::Arm64e::unpackTarget() const
951 {
952 assert(this->authBind.bind == 0);
953 assert(this->authBind.auth == 0);
954 return ((uint64_t)(this->rebase.high8) << 56) | (this->rebase.target);
955 }
956
957 uint64_t MachOLoaded::ChainedFixupPointerOnDisk::Arm64e::signExtendedAddend() const
958 {
959 assert(this->authBind.bind == 1);
960 assert(this->authBind.auth == 0);
961 uint64_t addend19 = this->bind.addend;
962 if ( addend19 & 0x40000 )
963 return addend19 | 0xFFFFFFFFFFFC0000ULL;
964 else
965 return addend19;
966 }
967
968 const char* MachOLoaded::ChainedFixupPointerOnDisk::Arm64e::keyName() const
969 {
970 static const char* names[] = {
971 "IA", "IB", "DA", "DB"
972 };
973 assert(this->authBind.auth == 1);
974 uint8_t keyBits = this->authBind.key;
975 assert(keyBits < 4);
976 return names[keyBits];
977 }
978
979 uint64_t MachOLoaded::ChainedFixupPointerOnDisk::Arm64e::signPointer(void* loc, uint64_t target) const
980 {
981 assert(this->authBind.auth == 1);
982 #if __has_feature(ptrauth_calls)
983 uint64_t discriminator = authBind.diversity;
984 if ( authBind.addrDiv )
985 discriminator = __builtin_ptrauth_blend_discriminator(loc, discriminator);
986 switch ( authBind.key ) {
987 case 0: // IA
988 return (uint64_t)__builtin_ptrauth_sign_unauthenticated((void*)target, 0, discriminator);
989 case 1: // IB
990 return (uint64_t)__builtin_ptrauth_sign_unauthenticated((void*)target, 1, discriminator);
991 case 2: // DA
992 return (uint64_t)__builtin_ptrauth_sign_unauthenticated((void*)target, 2, discriminator);
993 case 3: // DB
994 return (uint64_t)__builtin_ptrauth_sign_unauthenticated((void*)target, 3, discriminator);
995 }
996 #endif
997 return target;
998 }
999
1000 uint64_t MachOLoaded::ChainedFixupPointerOnDisk::Generic64::unpackedTarget() const
1001 {
1002 return (((uint64_t)this->rebase.high8) << 56) | (uint64_t)(this->rebase.target);
1003 }
1004
1005 uint64_t MachOLoaded::ChainedFixupPointerOnDisk::Generic64::signExtendedAddend() const
1006 {
1007 uint64_t addend27 = this->bind.addend;
1008 uint64_t top8Bits = addend27 & 0x00007F80000ULL;
1009 uint64_t bottom19Bits = addend27 & 0x0000007FFFFULL;
1010 uint64_t newValue = (top8Bits << 13) | (((uint64_t)(bottom19Bits << 37) >> 37) & 0x00FFFFFFFFFFFFFF);
1011 return newValue;
1012 }
1013
1014 bool MachOLoaded::ChainedFixupPointerOnDisk::isRebase(uint16_t pointerFormat, uint64_t preferedLoadAddress, uint64_t& targetRuntimeOffset) const
1015 {
1016 switch (pointerFormat) {
1017 case DYLD_CHAINED_PTR_ARM64E:
1018 if ( this->arm64e.bind.bind )
1019 return false;
1020 if ( this->arm64e.authRebase.auth ) {
1021 targetRuntimeOffset = this->arm64e.authRebase.target;
1022 return true;
1023 }
1024 else {
1025 targetRuntimeOffset = this->arm64e.unpackTarget() - preferedLoadAddress;
1026 return true;
1027 }
1028 break;
1029 case DYLD_CHAINED_PTR_64:
1030 if ( this->generic64.bind.bind )
1031 return false;
1032 targetRuntimeOffset = this->generic64.unpackedTarget() - preferedLoadAddress;
1033 return true;
1034 break;
1035 case DYLD_CHAINED_PTR_32:
1036 if ( this->generic32.bind.bind )
1037 return false;
1038 targetRuntimeOffset = this->generic32.rebase.target - preferedLoadAddress;
1039 return true;
1040 break;
1041 default:
1042 break;
1043 }
1044 assert(0 && "unsupported pointer chain format");
1045 }
1046
1047 bool MachOLoaded::ChainedFixupPointerOnDisk::isBind(uint16_t pointerFormat, uint32_t& bindOrdinal) const
1048 {
1049 switch (pointerFormat) {
1050 case DYLD_CHAINED_PTR_ARM64E:
1051 if ( !this->arm64e.authBind.bind )
1052 return false;
1053 if ( this->arm64e.authBind.auth ) {
1054 bindOrdinal = this->arm64e.authBind.ordinal;
1055 return true;
1056 }
1057 else {
1058 bindOrdinal = this->arm64e.bind.ordinal;
1059 return true;
1060 }
1061 break;
1062 case DYLD_CHAINED_PTR_64:
1063 if ( !this->generic64.bind.bind )
1064 return false;
1065 bindOrdinal = this->generic64.bind.ordinal;
1066 return true;
1067 break;
1068 case DYLD_CHAINED_PTR_32:
1069 if ( !this->generic32.bind.bind )
1070 return false;
1071 bindOrdinal = this->generic32.bind.ordinal;
1072 return true;
1073 break;
1074 default:
1075 break;
1076 }
1077 assert(0 && "unsupported pointer chain format");
1078 }
1079
1080 #if BUILDING_DYLD || BUILDING_LIBDYLD
1081 void MachOLoaded::fixupAllChainedFixups(Diagnostics& diag, const dyld_chained_starts_in_image* starts, uintptr_t slide,
1082 Array<const void*> bindTargets, void (^logFixup)(void* loc, void* newValue)) const
1083 {
1084 forEachFixupInAllChains(diag, starts, true, ^(ChainedFixupPointerOnDisk* fixupLoc, const dyld_chained_starts_in_segment* segInfo, bool& stop) {
1085 void* newValue;
1086 switch (segInfo->pointer_format) {
1087 #if __LP64__
1088 #if __has_feature(ptrauth_calls)
1089 case DYLD_CHAINED_PTR_ARM64E:
1090 if ( fixupLoc->arm64e.authRebase.auth ) {
1091 if ( fixupLoc->arm64e.authBind.bind ) {
1092 if ( fixupLoc->arm64e.authBind.ordinal >= bindTargets.count() ) {
1093 diag.error("out of range bind ordinal %d (max %lu)", fixupLoc->arm64e.authBind.ordinal, bindTargets.count());
1094 stop = true;
1095 break;
1096 }
1097 else {
1098 // authenticated bind
1099 newValue = (void*)(bindTargets[fixupLoc->arm64e.bind.ordinal]);
1100 if (newValue != 0) // Don't sign missing weak imports
1101 newValue = (void*)fixupLoc->arm64e.signPointer(fixupLoc, (uintptr_t)newValue);
1102 }
1103 }
1104 else {
1105 // authenticated rebase
1106 newValue = (void*)fixupLoc->arm64e.signPointer(fixupLoc, (uintptr_t)this + fixupLoc->arm64e.authRebase.target);
1107 }
1108 }
1109 else {
1110 if ( fixupLoc->arm64e.bind.bind ) {
1111 if ( fixupLoc->arm64e.bind.ordinal >= bindTargets.count() ) {
1112 diag.error("out of range bind ordinal %d (max %lu)", fixupLoc->arm64e.bind.ordinal, bindTargets.count());
1113 stop = true;
1114 break;
1115 }
1116 else {
1117 // plain bind
1118 newValue = (void*)((long)bindTargets[fixupLoc->arm64e.bind.ordinal] + fixupLoc->arm64e.signExtendedAddend());
1119 }
1120 }
1121 else {
1122 // plain rebase
1123 newValue = (void*)(fixupLoc->arm64e.unpackTarget()+slide);
1124 }
1125 }
1126 if ( logFixup )
1127 logFixup(fixupLoc, newValue);
1128 fixupLoc->raw64 = (uintptr_t)newValue;
1129 break;
1130 #endif
1131 case DYLD_CHAINED_PTR_64:
1132 if ( fixupLoc->generic64.bind.bind ) {
1133 if ( fixupLoc->generic64.bind.ordinal >= bindTargets.count() ) {
1134 diag.error("out of range bind ordinal %d (max %lu)", fixupLoc->generic64.bind.ordinal, bindTargets.count());
1135 stop = true;
1136 break;
1137 }
1138 else {
1139 newValue = (void*)((long)bindTargets[fixupLoc->generic64.bind.ordinal] + fixupLoc->generic64.signExtendedAddend());
1140 }
1141 }
1142 else {
1143 newValue = (void*)(fixupLoc->generic64.unpackedTarget()+slide);
1144 }
1145 if ( logFixup )
1146 logFixup(fixupLoc, newValue);
1147 fixupLoc->raw64 = (uintptr_t)newValue;
1148 break;
1149 #else
1150 case DYLD_CHAINED_PTR_32:
1151 if ( fixupLoc->generic32.bind.bind ) {
1152 if ( fixupLoc->generic32.bind.ordinal >= bindTargets.count() ) {
1153 diag.error("out of range bind ordinal %d (max %lu)", fixupLoc->generic32.bind.ordinal, bindTargets.count());
1154 stop = true;
1155 break;
1156 }
1157 else {
1158 newValue = (void*)((long)bindTargets[fixupLoc->generic32.bind.ordinal] + fixupLoc->generic32.bind.addend);
1159 }
1160 }
1161 else {
1162 if ( fixupLoc->generic32.rebase.target > segInfo->max_valid_pointer ) {
1163 // handle non-pointers in chain
1164 uint32_t bias = (0x04000000 + segInfo->max_valid_pointer)/2;
1165 newValue = (void*)(fixupLoc->generic32.rebase.target - bias);
1166 }
1167 else {
1168 newValue = (void*)(fixupLoc->generic32.rebase.target + slide);
1169 }
1170 }
1171 if ( logFixup )
1172 logFixup(fixupLoc, newValue);
1173 fixupLoc->raw32 = (uint32_t)(uintptr_t)newValue;
1174 break;
1175 #endif // __LP64__
1176 default:
1177 diag.error("unsupported pointer chain format: 0x%04X", segInfo->pointer_format);
1178 stop = true;
1179 break;
1180 }
1181 });
1182 }
1183 #endif
1184
1185 bool MachOLoaded::walkChain(Diagnostics& diag, const dyld_chained_starts_in_segment* segInfo, uint32_t pageIndex, uint16_t offsetInPage,
1186 bool notifyNonPointers, void (^handler)(ChainedFixupPointerOnDisk* fixupLocation, const dyld_chained_starts_in_segment* segInfo, bool& stop)) const
1187 {
1188 bool stop = false;
1189 uint8_t* pageContentStart = (uint8_t*)this + segInfo->segment_offset + (pageIndex * segInfo->page_size);
1190 ChainedFixupPointerOnDisk* chain = (ChainedFixupPointerOnDisk*)(pageContentStart+offsetInPage);
1191 bool chainEnd = false;
1192 while (!stop && !chainEnd) {
1193 // copy chain content, in case handler modifies location to final value
1194 ChainedFixupPointerOnDisk chainContent = *chain;
1195 handler(chain, segInfo, stop);
1196 if ( !stop ) {
1197 switch (segInfo->pointer_format) {
1198 case DYLD_CHAINED_PTR_ARM64E:
1199 if ( chainContent.arm64e.rebase.next == 0 )
1200 chainEnd = true;
1201 else
1202 chain = (ChainedFixupPointerOnDisk*)((uint8_t*)chain + chainContent.arm64e.rebase.next*8);
1203 break;
1204 case DYLD_CHAINED_PTR_64:
1205 if ( chainContent.generic64.rebase.next == 0 )
1206 chainEnd = true;
1207 else
1208 chain = (ChainedFixupPointerOnDisk*)((uint8_t*)chain + chainContent.generic64.rebase.next*4);
1209 break;
1210 case DYLD_CHAINED_PTR_32:
1211 if ( chainContent.generic32.rebase.next == 0 )
1212 chainEnd = true;
1213 else {
1214 chain = (ChainedFixupPointerOnDisk*)((uint8_t*)chain + chainContent.generic32.rebase.next*4);
1215 if ( !notifyNonPointers ) {
1216 while ( (chain->generic32.rebase.bind == 0) && (chain->generic32.rebase.target > segInfo->max_valid_pointer) ) {
1217 // not a real pointer, but a non-pointer co-opted into chain
1218 chain = (ChainedFixupPointerOnDisk*)((uint8_t*)chain + chain->generic32.rebase.next*4);
1219 }
1220 }
1221 }
1222 break;
1223 default:
1224 diag.error("unknown pointer format 0x%04X", segInfo->pointer_format);
1225 stop = true;
1226 }
1227 }
1228 }
1229 return stop;
1230 }
1231
1232 void MachOLoaded::forEachFixupInAllChains(Diagnostics& diag, const dyld_chained_starts_in_image* starts, bool notifyNonPointers,
1233 void (^handler)(ChainedFixupPointerOnDisk* fixupLocation, const dyld_chained_starts_in_segment* segInfo, bool& stop)) const
1234 {
1235 bool stopped = false;
1236 for (uint32_t segIndex=0; segIndex < starts->seg_count && !stopped; ++segIndex) {
1237 if ( starts->seg_info_offset[segIndex] == 0 )
1238 continue;
1239 const dyld_chained_starts_in_segment* segInfo = (dyld_chained_starts_in_segment*)((uint8_t*)starts + starts->seg_info_offset[segIndex]);
1240 for (uint32_t pageIndex=0; pageIndex < segInfo->page_count && !stopped; ++pageIndex) {
1241 uint16_t offsetInPage = segInfo->page_start[pageIndex];
1242 if ( offsetInPage == DYLD_CHAINED_PTR_START_NONE )
1243 continue;
1244 if ( offsetInPage & DYLD_CHAINED_PTR_START_MULTI ) {
1245 // 32-bit chains which may need multiple starts per page
1246 uint32_t overflowIndex = offsetInPage & ~DYLD_CHAINED_PTR_START_MULTI;
1247 bool chainEnd = false;
1248 while (!stopped && !chainEnd) {
1249 chainEnd = (segInfo->page_start[overflowIndex] & DYLD_CHAINED_PTR_START_LAST);
1250 offsetInPage = (segInfo->page_start[overflowIndex] & ~DYLD_CHAINED_PTR_START_LAST);
1251 if ( walkChain(diag, segInfo, pageIndex, offsetInPage, notifyNonPointers, handler) )
1252 stopped = true;
1253 ++overflowIndex;
1254 }
1255 }
1256 else {
1257 // one chain per page
1258 walkChain(diag, segInfo, pageIndex, offsetInPage, notifyNonPointers, handler);
1259 }
1260 }
1261 }
1262 }
1263
1264
1265 } // namespace dyld3
1266