-
Notifications
You must be signed in to change notification settings - Fork 69
/
DyldRuntimeState.cpp
2383 lines (2155 loc) · 93.9 KB
/
DyldRuntimeState.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2019 Apple Inc. All rights reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_LICENSE_HEADER_END@
*/
#include <TargetConditionals.h>
#include <_simple.h>
#include <stdint.h>
#include <sys/sysctl.h>
#include <sys/socket.h>
#include <sys/syslog.h>
#include <sys/uio.h>
#include <sys/un.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <System/sys/reason.h>
#include <kern/kcdata.h>
#include <libkern/OSAtomic.h>
// atexit header is missing C++ guards
extern "C" {
#include <System/atexit.h>
}
// no libc header for send() syscall interface
extern "C" ssize_t __sendto(int, const void*, size_t, int, const struct sockaddr*, socklen_t);
#if TARGET_OS_SIMULATOR
enum
{
AMFI_DYLD_INPUT_PROC_IN_SIMULATOR = (1 << 0),
};
enum amfi_dyld_policy_output_flag_set
{
AMFI_DYLD_OUTPUT_ALLOW_AT_PATH = (1 << 0),
AMFI_DYLD_OUTPUT_ALLOW_PATH_VARS = (1 << 1),
AMFI_DYLD_OUTPUT_ALLOW_CUSTOM_SHARED_CACHE = (1 << 2),
AMFI_DYLD_OUTPUT_ALLOW_FALLBACK_PATHS = (1 << 3),
AMFI_DYLD_OUTPUT_ALLOW_PRINT_VARS = (1 << 4),
AMFI_DYLD_OUTPUT_ALLOW_FAILED_LIBRARY_INSERTION = (1 << 5),
};
extern "C" int amfi_check_dyld_policy_self(uint64_t input_flags, uint64_t* output_flags);
#else
#include <libamfi.h>
#endif
#include "MachOLoaded.h"
#include "DyldSharedCache.h"
#include "SharedCacheRuntime.h"
#include "Tracing.h"
#include "FileUtils.h"
#include "Loader.h"
#include "PrebuiltLoader.h"
#include "DyldRuntimeState.h"
#include "DebuggerSupport.h"
#include "DyldProcessConfig.h"
#include "RosettaSupport.h"
#include "Vector.h"
// implemented in assembly
extern "C" void* tlv_get_addr(MachOAnalyzer::TLV_Thunk*);
using dyld3::MachOAnalyzer;
using dyld3::MachOFile;
using dyld3::Platform;
extern "C" {
// historically crash reporter look for this symbol named "error_string" in dyld, but that may not be needed anymore
char error_string[1024] = "dyld: launch, loading dependent libraries";
};
#define DYLD_CLOSURE_XATTR_NAME "com.apple.dyld"
extern "C" const dyld3::MachOLoaded __dso_handle; // mach_header of dyld itself
static bool hexCharToByte(const char hexByte, uint8_t& value)
{
if ( hexByte >= '0' && hexByte <= '9' ) {
value = hexByte - '0';
return true;
}
else if ( hexByte >= 'A' && hexByte <= 'F' ) {
value = hexByte - 'A' + 10;
return true;
}
else if ( hexByte >= 'a' && hexByte <= 'f' ) {
value = hexByte - 'a' + 10;
return true;
}
return false;
}
static bool hexStringToBytes(const char* hexString, uint8_t buffer[], unsigned bufferMaxSize, unsigned& bufferLenUsed)
{
bufferLenUsed = 0;
bool high = true;
for ( const char* s = hexString; *s != '\0'; ++s ) {
if ( bufferLenUsed > bufferMaxSize )
return false;
uint8_t value;
if ( !hexCharToByte(*s, value) )
return false;
if ( high )
buffer[bufferLenUsed] = value << 4;
else
buffer[bufferLenUsed++] |= value;
high = !high;
}
return true;
}
namespace dyld4 {
void RuntimeState::withLoadersReadLock(void (^work)())
{
#if BUILDING_DYLD
if ( this->libSystemHelpers != nullptr ) {
this->libSystemHelpers->os_unfair_recursive_lock_lock_with_options(&(_locks.loadersLock), OS_UNFAIR_LOCK_NONE);
work();
this->libSystemHelpers->os_unfair_recursive_lock_unlock(&_locks.loadersLock);
}
else
#endif
{
work();
}
}
void RuntimeState::withLoadersWriteLock(void (^work)())
{
#if BUILDING_DYLD
if ( this->libSystemHelpers != nullptr ) {
this->libSystemHelpers->os_unfair_recursive_lock_lock_with_options(&_locks.loadersLock, OS_UNFAIR_LOCK_NONE);
this->incWritable();
work();
this->decWritable();
this->libSystemHelpers->os_unfair_recursive_lock_unlock(&_locks.loadersLock);
}
else
#endif
{
work();
}
}
void RuntimeState::incWritable()
{
#if BUILDING_DYLD
// FIXME: move inc/decWritable() into Allocator to replace writeProtect()
pthread_mutex_lock(&_locks.writableLock);
_locks.writeableCount += 1;
if ( _locks.writeableCount == 1 )
longTermAllocator.writeProtect(false);
pthread_mutex_unlock(&_locks.writableLock);
#endif
}
void RuntimeState::decWritable()
{
#if BUILDING_DYLD
pthread_mutex_lock(&_locks.writableLock);
_locks.writeableCount -= 1;
if ( _locks.writeableCount == 0 )
longTermAllocator.writeProtect(true);
pthread_mutex_unlock(&_locks.writableLock);
#endif
}
uint8_t* RuntimeState::appState(uint16_t index)
{
assert(_processPrebuiltLoaderSet != nullptr);
assert(index < _processPrebuiltLoaderSet->loaderCount());
return &_processDylibStateArray[index];
}
const MachOLoaded* RuntimeState::appLoadAddress(uint16_t index)
{
assert(_processPrebuiltLoaderSet != nullptr);
assert(index < _processPrebuiltLoaderSet->loaderCount());
return _processLoadedAddressArray[index];
}
void RuntimeState::setAppLoadAddress(uint16_t index, const MachOLoaded* ml)
{
assert(_processPrebuiltLoaderSet != nullptr);
assert(index < _processPrebuiltLoaderSet->loaderCount());
_processLoadedAddressArray[index] = ml;
}
uint8_t* RuntimeState::cachedDylibState(uint16_t index)
{
assert(index < this->config.dyldCache.dylibCount);
return &_cachedDylibsStateArray[index];
}
const MachOLoaded* RuntimeState::cachedDylibLoadAddress(uint16_t index)
{
assert(index < this->config.dyldCache.dylibCount);
uint64_t mTime;
uint64_t inode;
return (MachOLoaded*)this->config.dyldCache.addr->getIndexedImageEntry(index, mTime, inode);
}
void RuntimeState::add(const Loader* ldr)
{
// append to list
loaded.push_back(ldr);
// done if libdyld and libSystem loaders already found
if ( (this->libdyldLoader != nullptr) && (this->libSystemLoader != nullptr) )
return;
// remember special loaders
const char* installName = nullptr;
if ( ldr->isPrebuilt && ldr->dylibInDyldCache ) {
// in normal case where special loaders are Prebuilt and in dyld cache
// improve performance by not accessing load commands of dylib (may not be paged-in)
installName = ldr->path();
}
else {
const MachOAnalyzer* ma = ldr->analyzer(*this);
if ( ma->isDylib() ) {
installName = ma->installName();
}
}
if ( installName != nullptr ) {
if ( config.process.platform == dyld3::Platform::driverKit ) {
if ( strcmp(installName, "/System/DriverKit/usr/lib/system/libdyld.dylib") == 0 )
setDyldLoader(ldr);
else if ( strcmp(installName, "/System/DriverKit/usr/lib/libSystem.dylib") == 0 )
libSystemLoader = ldr;
}
else {
if ( strcmp(installName, "/usr/lib/system/libdyld.dylib") == 0 )
setDyldLoader(ldr);
else if ( strcmp(installName, "/usr/lib/libSystem.B.dylib") == 0 )
libSystemLoader = ldr;
}
}
}
void RuntimeState::setDyldLoader(const Loader* ldr)
{
this->libdyldLoader = ldr;
Loader::ResolvedSymbol result = { nullptr, "", 0, Loader::ResolvedSymbol::Kind::bindAbsolute, false, false };
Diagnostics diag;
if ( ldr->hasExportedSymbol(diag, *this, "__dyld_missing_symbol_abort", Loader::shallow, &result) )
this->libdyldMissingSymbol = (const void*)Loader::resolvedAddress(*this, result);
}
void RuntimeState::setMainLoader(const Loader* ldr)
{
this->mainExecutableLoader = ldr;
#if BUILDING_DYLD
// main executable is mapped by kernel so walk mappings here to find immutable ranges and do logging
const MachOAnalyzer* ma = ldr->analyzer(*this);
if ( this->config.log.libraries )
Loader::logLoad(*this, ma, this->config.process.mainExecutablePath);
if ( this->config.log.segments ) {
this->log("Kernel mapped %s\n", this->config.process.mainExecutablePath);
uintptr_t slide = ma->getSlide();
__block uint32_t segIndex = 0;
ma->forEachSegment(^(const MachOAnalyzer::SegmentInfo& segInfo, bool& stop) {
uint8_t permissions = segInfo.protections;
uint64_t segAddr = segInfo.vmAddr + slide;
uint64_t segSize = round_page(segInfo.fileSize);
if ( (segSize == 0) && (segIndex == 0) )
segSize = (uint64_t)ma; // kernel stretches __PAGEZERO
if ( this->config.log.segments ) {
this->log("%14s (%c%c%c) 0x%012llX->0x%012llX \n", ma->segmentName(segIndex),
(permissions & PROT_READ) ? 'r' : '.', (permissions & PROT_WRITE) ? 'w' : '.', (permissions & PROT_EXEC) ? 'x' : '.',
segAddr,
segAddr + segSize);
}
segIndex++;
});
}
#endif
#if BUILDING_DYLD && SUPPORT_ROSETTA
// if translated, update all_image_info
if ( this->config.process.isTranslated ) {
dyld_all_runtime_info* aotInfo;
int ret = aot_get_runtime_info(aotInfo);
if ( ret == 0 ) {
for ( uint64_t i = 0; i < aotInfo->uuid_count; i++ ) {
dyld_image_info image_info = aotInfo->images[i];
dyld_uuid_info uuid_info = aotInfo->uuids[i];
// add the arm64 Rosetta runtime to uuid info
addNonSharedCacheImageUUID(this->longTermAllocator, uuid_info);
// ktrace notify about main executables translation
struct stat sb;
if ( dyld3::stat(image_info.imageFilePath, &sb) == 0 ) {
fsid_t fsid = { { 0, 0 } };
fsobj_id_t fsobj = { 0 };
ino_t inode = sb.st_ino;
fsobj.fid_objno = (uint32_t)inode;
fsobj.fid_generation = (uint32_t)(inode >> 32);
fsid.val[0] = sb.st_dev;
dyld3::kdebug_trace_dyld_image(DBG_DYLD_UUID_MAP_A, image_info.imageFilePath, &(uuid_info.imageUUID), fsobj, fsid, image_info.imageLoadAddress);
}
}
// add aot images to dyld_all_image_info
addAotImagesToAllAotImages(this->longTermAllocator, (uint32_t)aotInfo->aot_image_count, aotInfo->aots);
// add the arm64 Rosetta runtime to dyld_all_image_info
addImagesToAllImages(this->longTermAllocator, (uint32_t)aotInfo->image_count, aotInfo->images);
// set the aot shared cache info in dyld_all_image_info
gProcessInfo->aotSharedCacheBaseAddress = aotInfo->aot_cache_info.cacheBaseAddress;
::memcpy(gProcessInfo->aotSharedCacheUUID, aotInfo->aot_cache_info.cacheUUID, sizeof(uuid_t));
}
}
#endif // SUPPORT_ROSETTA
}
void RuntimeState::withNotifiersReadLock(void (^work)())
{
#if BUILDING_DYLD
if ( this->libSystemHelpers != nullptr ) {
this->libSystemHelpers->os_unfair_recursive_lock_lock_with_options(&_locks.notifiersLock, OS_UNFAIR_LOCK_NONE);
work();
this->libSystemHelpers->os_unfair_recursive_lock_unlock(&_locks.notifiersLock);
}
else
#endif
{
work();
}
}
void RuntimeState::withNotifiersWriteLock(void (^work)())
{
#if BUILDING_DYLD
if ( this->libSystemHelpers != nullptr ) {
this->libSystemHelpers->os_unfair_recursive_lock_lock_with_options(&_locks.notifiersLock, OS_UNFAIR_LOCK_NONE);
this->incWritable();
work();
this->decWritable();
this->libSystemHelpers->os_unfair_recursive_lock_unlock(&_locks.notifiersLock);
}
else
#endif
{
work();
}
}
void RuntimeState::withTLVLock(void (^work)())
{
#if BUILDING_DYLD
if ( this->libSystemHelpers != nullptr ) {
this->libSystemHelpers->os_unfair_recursive_lock_lock_with_options(&_locks.tlvInfosLock, OS_UNFAIR_LOCK_NONE);
work();
this->libSystemHelpers->os_unfair_recursive_lock_unlock(&_locks.tlvInfosLock);
}
else
#endif
{
work();
}
}
void RuntimeState::addDynamicReference(const Loader* from, const Loader* to)
{
// don't add dynamic reference if target can't be unloaded
if ( to->neverUnload )
return;
withLoadersWriteLock(^{
// don't add if already in list
for (const DynamicReference& ref : _dynamicReferences) {
if ( (ref.from == from) && (ref.to == to) ) {
return;
}
}
//log("addDynamicReference(%s, %s\n", from->leafName(), to->leafName());
_dynamicReferences.push_back({from, to});
});
}
void RuntimeState::log(const char* format, ...) const
{
va_list list;
va_start(list, format);
(const_cast<RuntimeState*>(this))->vlog(format, list);
va_end(list);
}
void RuntimeState::setUpLogging()
{
if ( config.log.useStderr || config.log.useFile ) {
// logging forced to a file or stderr
_logDescriptor = config.log.descriptor;
_logToSyslog = false;
_logSetUp = true;
}
else {
struct stat sb;
if ( config.process.pid == 1 ) {
// for launchd, write to console
_logDescriptor = config.syscall.open("/dev/console", O_WRONLY | O_NOCTTY, 0);
_logToSyslog = false;
_logSetUp = true;
}
else if ( config.syscall.fstat(config.log.descriptor, &sb) >= 0 ) {
// descriptor is open, use normal logging to it
_logDescriptor = config.log.descriptor;
_logToSyslog = false;
_logSetUp = true;
}
#if BUILDING_DYLD
else {
// Use syslog() for processes managed by launchd
// we can only check if launchd owned after libSystem initialized
if ( libSystemHelpers != nullptr ) {
if ( libSystemHelpers->isLaunchdOwned() ) {
_logToSyslog = true;
_logSetUp = true;
}
}
// note: if libSystem not initialzed yet, don't set _logSetUp, but try again on next log()
}
#if !TARGET_OS_SIMULATOR
if ( _logToSyslog ) {
// if loggging to syslog, set up a socket connection
_logDescriptor = config.syscall.socket(AF_UNIX, SOCK_DGRAM, 0);
if ( _logDescriptor != -1 ) {
config.syscall.fcntl(_logDescriptor, F_SETFD, (void*)1);
struct sockaddr_un addr;
addr.sun_family = AF_UNIX;
strncpy(addr.sun_path, _PATH_LOG, sizeof(addr.sun_path));
if ( config.syscall.connect(_logDescriptor, (struct sockaddr*)&addr, sizeof(addr)) == -1 ) {
config.syscall.close(_logDescriptor);
_logDescriptor = -1;
}
}
if ( _logDescriptor == -1 ) {
_logToSyslog = false;
}
}
#endif // !TARGET_OS_SIMULATOR
#endif // BUILDING_DYLD
}
}
void RuntimeState::vlog(const char* format, va_list list)
{
#if BUILDING_CLOSURE_UTIL
vprintf(format, list);
return;
#else
#if BUILDING_DYLD && !TARGET_OS_SIMULATOR
// prevent multi-thread log() calls from intermingling their text
os_lock_lock(&_locks.logSerializer);
#endif
// lazy initialize logging output
if ( !_logSetUp )
this->setUpLogging();
#if !TARGET_OS_SIMULATOR
// write to log
if ( _logToSyslog ) {
// send formatted message to syslogd
if ( _SIMPLE_STRING strbuf = ::_simple_salloc() ) {
if ( ::_simple_sprintf(strbuf, "<%d>%s[%d]: ", LOG_USER | LOG_NOTICE, config.process.progname, config.process.pid) == 0 ) {
if ( ::_simple_vsprintf(strbuf, format, list) == 0 ) {
const char* p = _simple_string(strbuf);
::__sendto(_logDescriptor, p, strlen(p), 0, NULL, 0);
}
}
::_simple_sfree(strbuf);
}
}
else
#endif // !TARGET_OS_SIMULATORb
if ( _logDescriptor != -1 ) {
// NOTE: it would be nicer to somehow merge these into one write call to reduce multithread interleaving
::_simple_dprintf(_logDescriptor, "dyld[%d]: ", config.process.pid);
// write to file, stderr, or console
::_simple_vdprintf(_logDescriptor, format, list);
}
#if BUILDING_DYLD && !TARGET_OS_SIMULATOR
os_lock_unlock(&_locks.logSerializer);
#endif
#endif
}
RuntimeState::PermanentRanges* RuntimeState::PermanentRanges::make(RuntimeState& state, const Array<const Loader*>& neverUnloadLoaders)
{
// rather that doing this in two passes, we build the ranges into a temp stack buffer, then allocate the real PermanentRanges
STACK_ALLOC_OVERFLOW_SAFE_ARRAY(Range, tempRanges, neverUnloadLoaders.count()*8);
for (const Loader* ldr : neverUnloadLoaders) {
const MachOLoaded* ma = ldr->loadAddress(state);
const uintptr_t slide = ma->getSlide();
__block uintptr_t lastSegEnd = 0;
__block uint8_t lastPerms = 0;
ldr->loadAddress(state)->forEachSegment(^(const MachOAnalyzer::SegmentInfo& segInfo, bool& stop) {
uintptr_t segStart = (uintptr_t)(segInfo.vmAddr + slide);
uintptr_t segEnd = segStart + (uintptr_t)segInfo.vmSize;
if ( (segStart == lastSegEnd) && (segInfo.protections == lastPerms) && !tempRanges.empty() ) {
// back to back segments with same perms, so just extend last range
tempRanges.back().end = segEnd;
}
else if ( segInfo.protections != 0 ) {
Range r;
r.start = segStart;
r.end = segEnd;
r.permissions = segInfo.protections;
r.loader = ldr;
tempRanges.push_back(r);
}
lastSegEnd = segEnd;
lastPerms = segInfo.protections;
});
}
unsigned count = (unsigned)tempRanges.count();
PermanentRanges* p = (PermanentRanges*)state.longTermAllocator.malloc(offsetof(PermanentRanges, _ranges[count]));
p->_next.store(nullptr);
p->_rangeCount = count;
for (unsigned i=0; i < count; ++i)
p->_ranges[i] = tempRanges[i];
return p;
}
bool RuntimeState::PermanentRanges::contains(uintptr_t start, uintptr_t end, uint8_t* perms, const Loader** loader) const
{
for (uint i=0; i < _rangeCount; ++i) {
const Range& range = _ranges[i];
if ( (range.start <= start) && (range.end > end) ) {
*perms = range.permissions;
*loader = range.loader;
return true;
}
}
return false;
}
RuntimeState::PermanentRanges* RuntimeState::PermanentRanges::next() const
{
return this->_next.load(std::memory_order_acquire);
}
void RuntimeState::PermanentRanges::append(PermanentRanges* pr)
{
// if _next is unused, set it to 'pr', otherwise recurse down linked list
PermanentRanges* n = _next.load(std::memory_order_acquire);
if ( n == nullptr )
_next.store(pr, std::memory_order_release);
else
n->append(pr);
}
void RuntimeState::addPermanentRanges(const Array<const Loader*>& neverUnloadLoaders)
{
PermanentRanges* pr = PermanentRanges::make(*this, neverUnloadLoaders);
if ( _permanentRanges == nullptr )
_permanentRanges = pr;
else
_permanentRanges->append(pr);
}
bool RuntimeState::inPermanentRange(uintptr_t start, uintptr_t end, uint8_t* perms, const Loader** loader)
{
for (const PermanentRanges* p = _permanentRanges; p != nullptr; p = p->next()) {
if ( p->contains(start, end, perms, loader) )
return true;
}
return false;
}
// if a dylib interposes a function which would be in the dyld cache, except there is a dylib
// overriding the cache, we need to record the original address of the function in the cache
// in order to patch other parts of the cache (to use the interposer function)
void RuntimeState::checkHiddenCacheAddr(const Loader* targetLoader, const void* targetAddr, const char* symbolName,
dyld3::OverflowSafeArray<HiddenCacheAddr>& hiddenCacheAddrs) const
{
if ( targetLoader != nullptr ) {
if ( const JustInTimeLoader* jl = targetLoader->isJustInTimeLoader() ) {
const Loader::DylibPatch* patchTable;
uint16_t cacheDylibOverriddenIndex;
if ( jl->overridesDylibInCache(patchTable, cacheDylibOverriddenIndex) ) {
uint64_t mTime;
uint64_t inode;
if ( const MachOAnalyzer* overriddenMA = (MachOAnalyzer*)config.dyldCache.addr->getIndexedImageEntry(cacheDylibOverriddenIndex, mTime, inode) ) {
void* functionAddrInCache;
bool resultPointsToInstructions;
if ( overriddenMA->hasExportedSymbol(symbolName, nullptr, &functionAddrInCache, &resultPointsToInstructions) ) {
hiddenCacheAddrs.push_back({functionAddrInCache, targetAddr});
}
}
}
}
}
}
void RuntimeState::appendInterposingTuples(const Loader* ldr, const uint8_t* rawDylibTuples, uint32_t tupleCount)
{
// AMFI can ban interposing
if ( !config.security.allowInterposing )
return;
// make a temp array of tuples for use while binding
struct TuplePlus { InterposeTupleSpecific tuple; const char* symbolName; };
STACK_ALLOC_ARRAY(TuplePlus, tempTuples, tupleCount);
const TuplePlus empty = { {nullptr, 0, 0}, nullptr };
for ( uint32_t i = 0; i < tupleCount; ++i )
tempTuples.push_back(empty);
const uintptr_t* rawStart = (uintptr_t*)rawDylibTuples;
const uintptr_t* rawEnd = &rawStart[2 * tupleCount];
// if cached dylib is overridden and interposed keep track of cache address for later patching
STACK_ALLOC_OVERFLOW_SAFE_ARRAY(HiddenCacheAddr, hiddenCacheAddrs, 32);
// The __interpose section has a bind and rebase for each entry. We have to eval those to make a tuple.
// This has to be done before the real fixups are applied because the real fixups need the tuples to be already built.
__block Diagnostics diag;
const MachOAnalyzer* ma = ldr->analyzer(*this);
if ( ma->hasChainedFixups() ) {
ma->withChainStarts(diag, 0, ^(const dyld_chained_starts_in_image* starts) {
STACK_ALLOC_OVERFLOW_SAFE_ARRAY(const void*, targetAddrs, 128);
STACK_ALLOC_OVERFLOW_SAFE_ARRAY(const char*, targetNames, 128);
ma->forEachChainedFixupTarget(diag, ^(int libOrdinal, const char* symbolName, uint64_t addend, bool weakImport, bool& stop) {
Loader::ResolvedSymbol target = ldr->resolveSymbol(diag, *this, libOrdinal, symbolName, weakImport, false, nullptr);
targetAddrs.push_back((void*)(Loader::resolvedAddress(*this, target) + addend));
checkHiddenCacheAddr(target.targetLoader, targetAddrs.back(), symbolName, hiddenCacheAddrs);
targetNames.push_back(symbolName);
});
const uintptr_t prefLoadAddresss = (uintptr_t)(ma->preferredLoadAddress());
ma->forEachFixupInAllChains(diag, starts, false, ^(MachOLoaded::ChainedFixupPointerOnDisk* fixupLoc, const dyld_chained_starts_in_segment* segInfo, bool& stop) {
if ( ((uintptr_t*)fixupLoc >= rawStart) && ((uintptr_t*)fixupLoc < rawEnd) ) {
uintptr_t index = ((uintptr_t*)fixupLoc - rawStart) / 2;
if ( index * 2 == (uintptr_t)(((uintptr_t*)fixupLoc - rawStart)) ) {
uint64_t targetRuntimeOffset;
if ( fixupLoc->isRebase(segInfo->pointer_format, prefLoadAddresss, targetRuntimeOffset) ) {
tempTuples[index].tuple.replacement = (uintptr_t)ma + (uintptr_t)targetRuntimeOffset;
tempTuples[index].tuple.onlyImage = ldr;
//this->log("replacement=0x%08lX at %lu in %s\n", interposingTuples[index].replacement, index, ldr->path());
}
}
else {
uint32_t bindOrdinal;
int64_t addend;
if ( fixupLoc->isBind(segInfo->pointer_format, bindOrdinal, addend) ) {
tempTuples[index].tuple.replacee = (uintptr_t)targetAddrs[bindOrdinal];
tempTuples[index].symbolName = targetNames[bindOrdinal];
//this->log("replacee=0x%08lX at %lu for %s in %s\n", tempTuples[index].tuple.replacee, index, tempTuples[index].symbolName, ldr->path());
}
}
}
});
});
}
else {
// rebase
intptr_t slide = (uintptr_t)ma - (uintptr_t)ma->preferredLoadAddress();
ma->forEachRebase(diag, false, ^(uint64_t runtimeOffset, bool& stop) {
uintptr_t* fixupLoc = (uintptr_t*)((uint64_t)ma + runtimeOffset);
if ( (fixupLoc >= rawStart) && (fixupLoc < rawEnd) ) {
// the first column (replacement) in raw tuples are rebases
uintptr_t index = (fixupLoc - rawStart) / 2;
uintptr_t replacement = *fixupLoc + slide;
tempTuples[index].tuple.replacement = replacement;
tempTuples[index].tuple.onlyImage = ldr;
//this->log("replacement=0x%08lX at %lu in %s\n", replacement, index, ldr->path());
}
});
// bind
ma->forEachBind(diag, ^(uint64_t runtimeOffset, int libOrdinal, uint8_t type, const char* symbolName, bool weakImport, bool lazyBind, uint64_t addend, bool& stop) {
uintptr_t* fixupLoc = (uintptr_t*)((uint64_t)ma + runtimeOffset);
if ( (fixupLoc >= rawStart) && (fixupLoc < rawEnd) ) {
Loader::ResolvedSymbol target = ldr->resolveSymbol(diag, *this, libOrdinal, symbolName, weakImport, lazyBind, nullptr);
if ( diag.noError() ) {
uintptr_t index = (fixupLoc - rawStart) / 2;
uintptr_t replacee = Loader::resolvedAddress(*this, target) + (uintptr_t)addend;
tempTuples[index].tuple.replacee = replacee;
tempTuples[index].symbolName = symbolName;
checkHiddenCacheAddr(target.targetLoader, (const void*)replacee, symbolName, hiddenCacheAddrs);
//this->log("replacee=0x%08lX at %lu in %s\n", replacee, index, ldr->path());
}
}
},
^(const char*) {});
}
// transfer temp tuples to interposingTuples
for ( TuplePlus& t : tempTuples ) {
// ignore tuples where one of the pointers is NULL
if ( (t.tuple.replacee == 0) || (t.tuple.replacement == 0) )
continue;
// add generic interpose for all images, if one already exists, alter it
uintptr_t previousReplacement = 0;
for ( InterposeTupleAll& existing : this->interposingTuplesAll ) {
if ( existing.replacee == t.tuple.replacee ) {
previousReplacement = existing.replacement;
existing.replacement = t.tuple.replacement;
}
}
if ( previousReplacement == 0 )
this->interposingTuplesAll.push_back({t.tuple.replacement, t.tuple.replacee});
if ( this->config.log.interposing )
this->log("%s has interposed '%s' to replacing binds to 0x%08lX with 0x%08lX\n", ldr->leafName(), t.symbolName, t.tuple.replacee, t.tuple.replacement);
// now add specific interpose so that the generic is not applied to the interposing dylib, so it can call through to old impl
if ( previousReplacement != 0 ) {
// need to chain to previous interpose replacement
this->interposingTuplesSpecific.push_back({ldr, previousReplacement, t.tuple.replacee});
if ( this->config.log.interposing )
this->log(" '%s' was previously interposed, so chaining 0x%08lX to call through to 0x%08lX\n", t.symbolName, t.tuple.replacement, previousReplacement);
}
else {
this->interposingTuplesSpecific.push_back({ldr, t.tuple.replacee, t.tuple.replacee});
}
// if the replacee is in a dylib that overrode the dyld cache, we need to
// add a tuple to replace the original cache impl address for cache patching to work
for ( const HiddenCacheAddr& entry : hiddenCacheAddrs ) {
if ( entry.replacementAddr == (void*)(t.tuple.replacee) ) {
this->interposingTuplesAll.push_back({t.tuple.replacement, (uintptr_t)entry.cacheAddr});
if ( this->config.log.interposing )
this->log("%s has interposed '%s' so need to patch cache uses of 0x%08lX\n", ldr->leafName(), t.symbolName, (uintptr_t)entry.cacheAddr);
}
}
}
}
void RuntimeState::buildInterposingTables()
{
// AMFI can ban interposing
if ( !config.security.allowInterposing )
return;
// look for __interpose section in dylibs loaded at launch
const uint32_t pointerSize = sizeof(void*);
__block uint32_t tupleCount = 0;
STACK_ALLOC_OVERFLOW_SAFE_ARRAY(const Loader*, dylibsWithTuples, 8);
for ( const Loader* ldr : loaded ) {
const MachOAnalyzer* ma = ldr->analyzer(*this);
if ( !ma->isDylib() )
continue;
if ( ldr->dylibInDyldCache )
continue;
Diagnostics diag;
ma->forEachInterposingSection(diag, ^(uint64_t vmOffset, uint64_t vmSize, bool& stop) {
tupleCount += (vmSize / (2 * pointerSize));
dylibsWithTuples.push_back(ldr);
});
}
if ( tupleCount == 0 )
return;
// fixups have not been apply yet. We need to peek ahead to resolve the __interpose section content
interposingTuplesAll.reserve(tupleCount);
interposingTuplesSpecific.reserve(tupleCount);
for ( const Loader* ldr : dylibsWithTuples ) {
Diagnostics diag;
const MachOAnalyzer* ma = ldr->analyzer(*this);
ma->forEachInterposingSection(diag, ^(uint64_t vmOffset, uint64_t vmSize, bool& stop) {
this->appendInterposingTuples(ldr, (uint8_t*)ma + vmOffset, (uint32_t)(vmSize / (2 * pointerSize)));
});
}
}
void RuntimeState::setLaunchMissingDylib(const char* missingDylibPath, const char* clientUsingDylib)
{
gProcessInfo->errorKind = DYLD_EXIT_REASON_DYLIB_MISSING;
gProcessInfo->errorClientOfDylibPath = clientUsingDylib;
gProcessInfo->errorTargetDylibPath = missingDylibPath;
gProcessInfo->errorSymbol = nullptr;
}
void RuntimeState::setLaunchMissingSymbol(const char* missingSymbolName, const char* dylibThatShouldHaveSymbol, const char* clientUsingSymbol)
{
gProcessInfo->errorKind = DYLD_EXIT_REASON_SYMBOL_MISSING;
gProcessInfo->errorClientOfDylibPath = clientUsingSymbol;
gProcessInfo->errorTargetDylibPath = dylibThatShouldHaveSymbol;
gProcessInfo->errorSymbol = missingSymbolName;
}
void RuntimeState::addMissingFlatLazySymbol(const Loader* ldr, const char* symbolName, uintptr_t* bindLoc)
{
_missingFlatLazySymbols.push_back({ ldr, symbolName, bindLoc });
}
void RuntimeState::rebindMissingFlatLazySymbols(const dyld3::Array<const Loader*>& newLoaders)
{
// FIXME: Do we want to drop diagnostics here? We don't want to fail a dlopen because a missing
// symbol lookup caused an error
Diagnostics diag;
_missingFlatLazySymbols.erase(std::remove_if(_missingFlatLazySymbols.begin(), _missingFlatLazySymbols.end(), [&](const MissingFlatSymbol& symbol) {
Loader::ResolvedSymbol result = { nullptr, symbol.symbolName, 0, Loader::ResolvedSymbol::Kind::bindAbsolute, false, false };
for ( const Loader* ldr : newLoaders ) {
// flat lookup can look in self, even if hidden
if ( ldr->hiddenFromFlat() )
continue;
if ( ldr->hasExportedSymbol(diag, *this, symbol.symbolName, Loader::shallow, &result) ) {
// Note we don't try to interpose here. Interposing is only registered at launch, when we know the symbol wasn't defined
uintptr_t targetAddr = Loader::resolvedAddress(*this, result);
if ( this->config.log.fixups )
this->log("fixup: *0x%012lX = 0x%012lX <%s>\n", (uintptr_t)symbol.bindLoc, (uintptr_t)targetAddr, ldr->leafName());
*symbol.bindLoc = targetAddr;
this->addDynamicReference(symbol.ldr, result.targetLoader);
return true;
}
}
return false;
}), _missingFlatLazySymbols.end());
}
void RuntimeState::removeMissingFlatLazySymbols(const dyld3::Array<const Loader*>& removingLoaders)
{
_missingFlatLazySymbols.erase(std::remove_if(_missingFlatLazySymbols.begin(), _missingFlatLazySymbols.end(), [&](const MissingFlatSymbol& symbol) {
return removingLoaders.contains(symbol.ldr);
}), _missingFlatLazySymbols.end());
}
bool RuntimeState::hasMissingFlatLazySymbols() const
{
return !_missingFlatLazySymbols.empty();
}
// <rdar://problem/29099600> dyld should tell the kernel when it is doing root fix-ups
void RuntimeState::setVMAccountingSuspending(bool suspend)
{
#if TARGET_OS_IPHONE && !TARGET_OS_SIMULATOR
if ( suspend == _vmAccountingSuspended )
return;
if ( this->config.log.fixups )
this->log("set vm.footprint_suspend=%d\n", suspend);
int newValue = suspend ? 1 : 0;
int oldValue = 0;
size_t newlen = sizeof(newValue);
size_t oldlen = sizeof(oldValue);
int ret = ::sysctlbyname("vm.footprint_suspend", &oldValue, &oldlen, &newValue, newlen);
if ( this->config.log.fixups && (ret != 0) )
this->log("vm.footprint_suspend => %d, errno=%d\n", ret, errno);
_vmAccountingSuspended = suspend;
#endif
}
void RuntimeState::incDlRefCount(const Loader* ldr)
{
// don't track dlopen ref-counts for things that never unload
if ( ldr->neverUnload )
return;
// check for existing entry
for ( DlopenCount& entry : _dlopenRefCounts ) {
if ( entry.loader == ldr ) {
// found existing DlopenCount entry, bump counter
entry.refCount += 1;
return;
}
}
// no existing DlopenCount, add new one
_dlopenRefCounts.push_back({ ldr, 1 });
}
void RuntimeState::decDlRefCount(const Loader* ldr)
{
// don't track dlopen ref-counts for things that never unload
if ( ldr->neverUnload )
return;
this->incWritable();
bool doCollect = false;
for (auto it=_dlopenRefCounts.begin(); it != _dlopenRefCounts.end(); ++it) {
if ( it->loader == ldr ) {
// found existing DlopenCount entry, bump counter
it->refCount -= 1;
if ( it->refCount == 0 ) {
_dlopenRefCounts.erase(it);
doCollect = true;
break;
}
return;
}
}
if ( doCollect )
garbageCollectImages();
this->decWritable();
}
class VIS_HIDDEN Reaper
{
public:
struct LoaderAndUse
{
const Loader* loader;
bool inUse;
};
Reaper(RuntimeState& state, Array<LoaderAndUse>& unloadables);
void garbageCollect();
void finalizeDeadImages();
void runTerminators(const Loader* ldr);
private:
void markDirectlyDlopenedImagesAsUsed();
void markDynamicNeverUnloadImagesAsUsed();
void markDependentOfInUseImages();
void markDependentsOf(const Loader* ldr);
uint32_t inUseCount();
void dump(const char* msg);
RuntimeState& _state;
Array<LoaderAndUse>& _unloadables;
uint32_t _deadCount;
};
Reaper::Reaper(RuntimeState& state, Array<LoaderAndUse>& unloadables)
: _state(state)
, _unloadables(unloadables)
, _deadCount(0)
{
}
void Reaper::markDirectlyDlopenedImagesAsUsed()
{
for ( const RuntimeState::DlopenCount& entry : _state._dlopenRefCounts ) {
if ( entry.refCount != 0 ) {
for ( LoaderAndUse& lu : _unloadables ) {
if ( lu.loader == entry.loader ) {
lu.inUse = true;
break;
}
}
}
}
}
void Reaper::markDynamicNeverUnloadImagesAsUsed()
{
for ( const Loader* ldr : _state._dynamicNeverUnloads ) {
for ( LoaderAndUse& lu : _unloadables ) {
if ( lu.loader == ldr ) {
lu.inUse = true;
break;
}
}
}
}
uint32_t Reaper::inUseCount()
{
uint32_t count = 0;
for ( LoaderAndUse& iu : _unloadables ) {
if ( iu.inUse )
++count;
}
return count;
}
void Reaper::markDependentsOf(const Loader* ldr)
{
// mark static dependents
const uint32_t depCount = ldr->dependentCount();
for ( uint32_t depIndex = 0; depIndex < depCount; ++depIndex ) {
const Loader* child = ldr->dependent(_state, depIndex);
for ( LoaderAndUse& lu : _unloadables ) {
if ( !lu.inUse && (lu.loader == child) ) {
lu.inUse = true;
break;
}
}
}