/
DyldAPIs.cpp
3577 lines (3222 loc) · 139 KB
/
DyldAPIs.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 <sys/mman.h>
#include <sys/stat.h>
#include <dirent.h>
#include <fcntl.h>
#include <errno.h>
#include <dlfcn.h>
#include <dlfcn_private.h>
#include <mach-o/dyld_images.h>
#include <mach/shared_region.h>
#include <_simple.h>
#include <libkern/OSAtomic.h>
#include <dyld/VersionMap.h>
#include <string.h>
#include <stdio.h>
#include <stdint.h>
#include <_simple.h>
#include <sys/errno.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <dirent.h>
#include <fcntl.h>
#include <TargetConditionals.h>
#include <malloc/malloc.h>
#include <mach-o/dyld_priv.h>
#include <dlfcn.h>
#include <libc_private.h>
#include "dyld.h"
#include "dyld_priv.h"
#include "MachOFile.h"
#include "Loader.h"
#include "DebuggerSupport.h"
#include "Tracing.h"
#include "dyld_process_info_internal.h"
#include "DyldProcessConfig.h"
#include "DyldRuntimeState.h"
#include "Processatlas.h"
#include "OptimizerSwift.h"
#include "PrebuiltObjC.h"
#include "PrebuiltSwift.h"
#include "objc-shared-cache.h"
#include "OptimizerObjC.h"
#include "DyldAPIs.h"
#include "JustInTimeLoader.h"
#include "RemoteNotificationResponder.h"
#include "Utils.h"
// internal libc.a variable that needs to be reset during fork()
extern mach_port_t mach_task_self_;
using dyld3::MachOFile;
using dyld3::MachOLoaded;
extern const dyld3::MachOLoaded __dso_handle;
// only in macOS and deprecated
struct VIS_HIDDEN __NSObjectFileImage
{
const char* path = nullptr;
const void* memSource = nullptr;
size_t memLength = 0;
const dyld3::MachOLoaded* loadAddress = nullptr;
void* handle = nullptr;
};
namespace dyld4 {
RecursiveAutoLock::RecursiveAutoLock(RuntimeState& state, bool skip)
: _libSystemHelpers(state.libSystemHelpers)
#if BUILDING_DYLD
, _lock(state._locks.apiLock)
, _skip(skip)
#endif // !BUILDING_DYLD
{
#if BUILDING_DYLD
if ( (_libSystemHelpers != nullptr) && !_skip )
_libSystemHelpers->os_unfair_recursive_lock_lock_with_options(&_lock, OS_UNFAIR_LOCK_NONE);
#else
(void)_libSystemHelpers;
#endif // !BUILDING_DYLD
}
RecursiveAutoLock::~RecursiveAutoLock()
{
#if BUILDING_DYLD
if ( (_libSystemHelpers != nullptr) && !_skip )
_libSystemHelpers->os_unfair_recursive_lock_unlock(&_lock);
#endif // !BUILDING_DYLD
}
static void* handleFromLoader(const Loader* ldr, bool firstOnly)
{
uintptr_t dyldStart = (uintptr_t)&__dso_handle;
// We need the low bit to store the "firstOnly" flag. Loaders should be
// at least 4-byte aligned though, so this is ok
assert((((uintptr_t)ldr) & 1) == 0);
uintptr_t flags = (firstOnly ? 1 : 0);
void* handle = (void*)(((uintptr_t)ldr ^ dyldStart) | flags);
#if __has_feature(ptrauth_calls)
if ( handle != nullptr )
handle = ptrauth_sign_unauthenticated(handle, ptrauth_key_process_dependent_data, ptrauth_string_discriminator("dlopen"));
#endif
return handle;
}
static const Loader* loaderFromHandle(void* h, bool& firstOnly)
{
uintptr_t dyldStart = (uintptr_t)&__dso_handle;
#if __has_feature(ptrauth_calls)
if ( h != nullptr ) {
// Note we don't use ptrauth_auth_data, as we don't want to crash on bad handles
void* strippedHandle = ptrauth_strip(h, ptrauth_key_process_dependent_data);
void* validHandle = ptrauth_sign_unauthenticated(strippedHandle, ptrauth_key_process_dependent_data, ptrauth_string_discriminator("dlopen"));
if ( h == validHandle )
h = strippedHandle;
}
#endif
firstOnly = (((uintptr_t)h) & 1);
return (Loader*)((((uintptr_t)h) & ~1) ^ dyldStart);
}
bool APIs::validLoader(const Loader* maybeLoader)
{
// ideally we'd walk the loaded array and validate this is a currently registered Loader
// but that would require taking a lock, which may deadlock some apps
if ( maybeLoader == nullptr )
return false;
// verifier loader is within the Allocator pool, or in a PrebuiltLoaderSet
bool inDynamicPool = this->persistentAllocator.owned(maybeLoader, sizeof(Loader));
bool inPrebuiltLoader = !inDynamicPool && this->inPrebuiltLoader(maybeLoader, sizeof(Loader));
if ( !inDynamicPool && !inPrebuiltLoader )
return false;
// pointer into memory we own, so safe to dereference and see if it has magic header
return maybeLoader->hasMagic();
}
const mach_header* APIs::_dyld_get_dlopen_image_header(void* handle)
{
if ( handle == RTLD_SELF ) {
void* callerAddress = __builtin_return_address(0);
if ( const Loader* caller = findImageContaining(callerAddress) )
return caller->analyzer(*this);
}
if ( handle == RTLD_MAIN_ONLY ) {
return mainExecutableLoader->analyzer(*this);
}
bool firstOnly;
const Loader* ldr = loaderFromHandle(handle, firstOnly);
if ( !validLoader(ldr) ) {
// if an invalid 'handle` passed in, return NULL
return nullptr;
}
return ldr->analyzer(*this);
}
static const void* stripPointer(const void* ptr)
{
#if __has_feature(ptrauth_calls)
return __builtin_ptrauth_strip(ptr, ptrauth_key_asia);
#else
return ptr;
#endif
}
void APIs::_libdyld_initialize(const dyld4::LibSystemHelpers* helpers)
{
// libSystem.dylib is being initialized, set helpers pointer
this->libSystemHelpers = helpers;
// set up thread-local-variable and dlerror handling
this->initialize();
}
uint32_t APIs::_dyld_image_count()
{
// NOTE: we are not taking the LoaderLock here
// That is becuase count() on a array is a field read which is as
// thread safe as this API is in general.
uint32_t result = (uint32_t)loaded.size();
if ( config.log.apis )
log("_dyld_image_count() => %d\n", result);
return result;
}
static uint32_t normalizeImageIndex(const ProcessConfig& config, uint32_t index)
{
#if BUILDING_DYLD && TARGET_OS_OSX && __x86_64__
// some old macOS apps assume index of zero is always the main executable even when dylibs are inserted, so permute order
uint32_t insertCount = config.pathOverrides.insertedDylibCount();
if ( (insertCount != 0) && (config.process.platform == dyld3::Platform::macOS) && (config.process.mainExecutableMinOSVersion < 0x0000C0000) ) {
// special case index==0 to map to the main executable
if ( index == 0 )
return insertCount;
// shift inserted dylibs
if ( index <= insertCount )
return index-1;
}
#endif
return index;
}
const mach_header* APIs::_dyld_get_image_header(uint32_t imageIndex)
{
__block const mach_header* result = 0;
withLoadersReadLock(^{
if ( imageIndex < loaded.size() )
result = loaded[normalizeImageIndex(config, imageIndex)]->loadAddress(*this);
});
if ( config.log.apis )
log("_dyld_get_image_header(%u) => %p\n", imageIndex, result);
return result;
}
intptr_t APIs::_dyld_get_image_slide(const mach_header* mh)
{
intptr_t result = 0;
const MachOLoaded* ml = (MachOLoaded*)mh;
if ( ml->hasMachOMagic() ) {
if ( DyldSharedCache::inDyldCache(config.dyldCache.addr, ml) )
result = config.dyldCache.slide;
else
result = ml->getSlide();
}
if ( config.log.apis )
log("_dyld_get_image_slide(%p) => 0x%lX\n", mh, result);
return result;
}
intptr_t APIs::_dyld_get_image_vmaddr_slide(uint32_t imageIndex)
{
__block intptr_t result = 0;
withLoadersReadLock(^{
if ( imageIndex < loaded.size() )
result = loaded[normalizeImageIndex(config, imageIndex)]->loadAddress(*this)->getSlide();
});
if ( config.log.apis )
log("_dyld_get_image_vmaddr_slide(%u) => 0x%lX\n", imageIndex, result);
return result;
}
const char* APIs::_dyld_get_image_name(uint32_t imageIndex)
{
__block const char* result = 0;
withLoadersReadLock(^{
if ( imageIndex < loaded.size() )
result = loaded[normalizeImageIndex(config, imageIndex)]->path();
});
if ( config.log.apis )
log("_dyld_get_image_name(%u) => %s\n", imageIndex, result);
return result;
}
static bool nameMatch(const char* installName, const char* libraryName)
{
const char* leafName = strrchr(installName, '/');
if ( leafName == NULL )
leafName = installName;
else
leafName++;
// -framework case is exact match of leaf name
if ( strcmp(leafName, libraryName) == 0 )
return true;
// -lxxx case: leafName must match "lib" <libraryName> ["." ?] ".dylib"
size_t leafNameLen = strlen(leafName);
size_t libraryNameLen = strlen(libraryName);
if ( leafNameLen < (libraryNameLen + 9) )
return false;
if ( strncmp(leafName, "lib", 3) != 0 )
return false;
if ( strcmp(&leafName[leafNameLen - 6], ".dylib") != 0 )
return false;
if ( strncmp(&leafName[3], libraryName, libraryNameLen) != 0 )
return false;
return (leafName[libraryNameLen + 3] == '.');
}
int32_t APIs::NSVersionOfLinkTimeLibrary(const char* libraryName)
{
__block int32_t result = -1;
mainExecutableLoader->loadAddress(*this)->forEachDependentDylib(^(const char* loadPath, bool, bool, bool, uint32_t compatVersion, uint32_t currentVersion, bool& stop) {
if ( nameMatch(loadPath, libraryName) )
result = currentVersion;
});
if ( config.log.apis )
log("NSVersionOfLinkTimeLibrary(%s) =>0x%08X\n", libraryName, result);
return result;
}
int32_t APIs::NSVersionOfRunTimeLibrary(const char* libraryName)
{
__block int32_t result = -1;
withLoadersReadLock(^{
for ( const dyld4::Loader* image : loaded ) {
const MachOLoaded* ml = image->loadAddress(*this);
const char* installName;
uint32_t currentVersion;
uint32_t compatVersion;
if ( ml->getDylibInstallName(&installName, &compatVersion, ¤tVersion) && nameMatch(installName, libraryName) ) {
result = currentVersion;
break;
}
}
});
if ( config.log.apis )
log("NSVersionOfRunTimeLibrary(%s) => 0x%08X\n", libraryName, result);
return result;
}
uint32_t APIs::dyld_get_program_sdk_watch_os_version()
{
__block uint32_t retval = 0;
__block bool versionFound = false;
forEachImageVersion(config.process.mainExecutable, ^(dyld_platform_t platform, uint32_t sdk_version, uint32_t min_version) {
if ( versionFound )
return;
if ( MachOFile::basePlatform((dyld3::Platform)platform) == dyld3::Platform::watchOS ) {
versionFound = true;
retval = sdk_version;
}
});
if ( config.log.apis )
log("dyld_get_program_sdk_watch_os_version() => 0x%08X\n", retval);
return retval;
}
uint32_t APIs::dyld_get_program_min_watch_os_version()
{
__block uint32_t retval = 0;
__block bool versionFound = false;
forEachImageVersion(config.process.mainExecutable, ^(dyld_platform_t platform, uint32_t sdk_version, uint32_t min_version) {
if ( versionFound )
return;
if ( MachOFile::basePlatform((dyld3::Platform)platform) == dyld3::Platform::watchOS ) {
versionFound = true;
retval = min_version;
}
});
if ( config.log.apis )
log("dyld_get_program_min_watch_os_version() => 0x%08X\n", retval);
return retval;
}
uint32_t APIs::dyld_get_program_sdk_bridge_os_version()
{
__block uint32_t retval = 0;
__block bool versionFound = false;
forEachImageVersion(config.process.mainExecutable, ^(dyld_platform_t platform, uint32_t sdk_version, uint32_t min_version) {
if ( versionFound )
return;
if ( MachOFile::basePlatform((dyld3::Platform)platform) == dyld3::Platform::bridgeOS ) {
versionFound = true;
retval = sdk_version;
}
});
if ( config.log.apis )
log("dyld_get_program_sdk_bridge_os_version() => 0x%08X\n", retval);
return retval;
}
uint32_t APIs::dyld_get_program_min_bridge_os_version()
{
__block uint32_t retval = 0;
__block bool versionFound = false;
forEachImageVersion(config.process.mainExecutable, ^(dyld_platform_t platform, uint32_t sdk_version, uint32_t min_version) {
if ( versionFound )
return;
if ( MachOFile::basePlatform((dyld3::Platform)platform) == dyld3::Platform::bridgeOS ) {
versionFound = true;
retval = min_version;
}
});
if ( config.log.apis )
log("dyld_get_program_min_bridge_os_version() => 0x%08X\n", retval);
return retval;
}
//
// Returns the sdk version (encode as nibble XXXX.YY.ZZ) that the
// specified binary was built against.
//
// First looks for LC_VERSION_MIN_* in binary and if sdk field is
// not zero, return that value.
// Otherwise, looks for the libSystem.B.dylib the binary linked
// against and uses a table to convert that to an sdk version.
//
uint32_t APIs::getSdkVersion(const mach_header* mh)
{
__block bool versionFound = false;
__block uint32_t retval = 0;
forEachImageVersion(mh, ^(dyld_platform_t platform, uint32_t sdk_version, uint32_t min_version) {
if ( versionFound )
return;
if ( platform == (dyld_platform_t)config.process.platform ) {
versionFound = true;
switch ( MachOFile::basePlatform((dyld3::Platform)platform) ) {
case dyld3::Platform::bridgeOS:
retval = sdk_version + 0x00090000;
return;
case dyld3::Platform::watchOS:
retval = sdk_version + 0x00070000;
return;
default:
retval = sdk_version;
return;
}
}
else if ( platform == PLATFORM_IOSSIMULATOR && (dyld_platform_t)config.process.platform == PLATFORM_IOSMAC ) {
//FIXME bringup hack
versionFound = true;
retval = 0x000C0000;
}
});
return retval;
}
uint32_t APIs::dyld_get_sdk_version(const mach_header* mh)
{
uint32_t result = getSdkVersion(mh);
if ( config.log.apis )
log("dyld_get_sdk_version(%p) => 0x%08X\n", mh, result);
return result;
}
uint32_t APIs::dyld_get_program_sdk_version()
{
uint32_t result = getSdkVersion(config.process.mainExecutable);
if ( config.log.apis )
log("dyld_get_program_sdk_version() => 0x%08X\n", result);
return result;
}
uint32_t APIs::dyld_get_min_os_version(const mach_header* mh)
{
__block bool versionFound = false;
__block uint32_t retval = 0;
forEachImageVersion(mh, ^(dyld_platform_t platform, uint32_t sdk_version, uint32_t min_version) {
if ( versionFound )
return;
if ( platform == (dyld_platform_t)config.process.platform ) {
versionFound = true;
switch ( MachOFile::basePlatform((dyld3::Platform)platform) ) {
case dyld3::Platform::bridgeOS:
retval = min_version + 0x00090000;
return;
case dyld3::Platform::watchOS:
retval = min_version + 0x00070000;
return;
default:
retval = min_version;
return;
}
}
else if ( platform == PLATFORM_IOSSIMULATOR && (dyld_platform_t)config.process.platform == PLATFORM_IOSMAC ) {
//FIXME bringup hack
versionFound = true;
retval = 0x000C0000;
}
});
if ( config.log.apis )
log("dyld_get_min_os_version(%p) => 0x%08X\n", mh, retval);
return retval;
}
dyld_platform_t APIs::dyld_get_active_platform(void)
{
dyld_platform_t result = (dyld_platform_t)config.process.platform;
if ( config.log.apis )
log("dyld_get_active_platform() => %d\n", result);
return result;
}
dyld_platform_t APIs::dyld_get_base_platform(dyld_platform_t platform)
{
dyld_platform_t result = (dyld_platform_t)MachOFile::basePlatform((dyld3::Platform)platform);
if ( config.log.apis )
log("dyld_get_base_platform(%d) => %d\n", platform, result);
return result;
}
bool APIs::dyld_is_simulator_platform(dyld_platform_t platform)
{
bool result = MachOFile::isSimulatorPlatform((dyld3::Platform)platform);
if ( config.log.apis )
log("dyld_is_simulator_platform(%d) => %d\n", platform, result);
return result;
}
dyld_build_version_t APIs::mapFromVersionSet(dyld_build_version_t versionSet)
{
if ( versionSet.platform != 0xffffffff )
return versionSet;
const dyld3::VersionSetEntry* foundEntry = nullptr;
for (const dyld3::VersionSetEntry& entry : dyld3::sVersionMap) {
if ( entry.set >= versionSet.version ) {
foundEntry = &entry;
break;
}
}
if ( foundEntry == nullptr ) {
return { .platform = 0, .version = 0 };
}
switch ( MachOFile::basePlatform(config.process.platform) ) {
case dyld3::Platform::macOS:
return { .platform = PLATFORM_MACOS, .version = foundEntry->macos };
case dyld3::Platform::iOS:
return { .platform = PLATFORM_IOS, .version = foundEntry->ios };
case dyld3::Platform::watchOS:
return { .platform = PLATFORM_WATCHOS, .version = foundEntry->watchos };
case dyld3::Platform::tvOS:
return { .platform = PLATFORM_TVOS, .version = foundEntry->tvos };
case dyld3::Platform::bridgeOS:
return { .platform = PLATFORM_BRIDGEOS, .version = foundEntry->bridgeos };
default:
return { .platform = (dyld_platform_t)MachOFile::basePlatform(config.process.platform), .version = 0 };
}
}
bool APIs::dyld_sdk_at_least(const mach_header* mh, dyld_build_version_t atLeast)
{
dyld_build_version_t concreteAtLeast = mapFromVersionSet(atLeast);
__block bool retval = false;
forEachImageVersion(mh, ^(dyld_platform_t imagePlatform, uint32_t imageSDK, uint32_t imageOS) {
if ( MachOFile::basePlatform((dyld3::Platform)imagePlatform) == MachOFile::basePlatform((dyld3::Platform)concreteAtLeast.platform) ) {
if ( MachOFile::basePlatform((dyld3::Platform)imagePlatform) == dyld3::Platform::unknown )
return;
if ( imageSDK >= concreteAtLeast.version )
retval = true;
}
});
if ( config.log.apis )
log("dyld_sdk_at_least(%p, <%d,0x%08X>) => %d\n", mh, atLeast.platform, atLeast.version, retval);
return retval;
}
bool APIs::dyld_minos_at_least(const mach_header* mh, dyld_build_version_t atLeast)
{
dyld_build_version_t concreteAtLeast = mapFromVersionSet(atLeast);
__block bool retval = false;
forEachImageVersion(mh, ^(dyld_platform_t imagePlatform, uint32_t imageSDK, uint32_t imageMinOS) {
if ( MachOFile::basePlatform((dyld3::Platform)imagePlatform) == MachOFile::basePlatform((dyld3::Platform)concreteAtLeast.platform) ) {
if ( MachOFile::basePlatform((dyld3::Platform)imagePlatform) == dyld3::Platform::unknown )
return;
if ( imageMinOS >= concreteAtLeast.version )
retval = true;
}
});
if ( config.log.apis )
log("dyld_minos_at_least(%p, <%d,0x%08X>) => %d\n", mh, atLeast.platform, atLeast.version, retval);
return retval;
}
__attribute__((aligned(64)))
bool APIs::dyld_program_minos_at_least (dyld_build_version_t version) {
// contract(config.process.mainExecutableMinOSVersionSet != 0);
// contract(config.process.mainExecutableMinOSVersion != 0);
// contract((dyld_platform_t)config.process.basePlatform != 0);
uint32_t currentVersion = 0;
bool defaultResult = true;
if ( config.process.basePlatform == dyld3::Platform::unknown ) {
defaultResult = false;
}
if (version.platform == 0xffffffff) {
currentVersion = config.process.mainExecutableMinOSVersionSet;
} else if (version.platform == (dyld_platform_t)config.process.basePlatform) {
currentVersion = config.process.mainExecutableMinOSVersion;
} else if (version.platform == (dyld_platform_t)config.process.platform) {
currentVersion = config.process.mainExecutableMinOSVersion;
} else {
// Hack
// If it is not the specific platform or a version set, we should return false.
// If we explicitly return false here the compiler will emit a branch, so instead we change a value
// so that through a series of conditional selects we always return false.
defaultResult = false;
}
return ( currentVersion >= version.version ) ? defaultResult : false;
}
__attribute__((aligned(64)))
bool APIs::dyld_program_sdk_at_least (dyld_build_version_t version) {
// contract(config.process.mainExecutableSDKVersionSet != 0);
// contract(config.process.mainExecutableSDKVersion != 0);
// contract((dyld_platform_t)config.process.basePlatform != 0);
uint32_t currentVersion = 0;
bool defaultResult = true;
if ( config.process.basePlatform == dyld3::Platform::unknown ) {
defaultResult = false;
}
if (version.platform == 0xffffffff) {
currentVersion = config.process.mainExecutableSDKVersionSet;
} else if (version.platform == (dyld_platform_t)config.process.basePlatform) {
currentVersion = config.process.mainExecutableSDKVersion;
} else if (version.platform == (dyld_platform_t)config.process.platform) {
currentVersion = config.process.mainExecutableSDKVersion;
} else {
// Hack
// If it is not the specific platform or a version set, we should return false.
// If we explicitly return false here the compiler will emit a branch, so instead we change a value
// so that through a series of conditional selects we always return false.
defaultResult = false;
}
return ( currentVersion >= version.version ) ? defaultResult : false;
}
uint32_t APIs::linkedDylibVersion(const MachOFile* mf, const char* installname)
{
__block uint32_t retval = 0;
mf->forEachDependentDylib(^(const char* loadPath, bool, bool, bool, uint32_t compatVersion, uint32_t currentVersion, bool& stop) {
if ( strcmp(loadPath, installname) == 0 ) {
retval = currentVersion;
stop = true;
}
});
return retval;
}
#define PACKED_VERSION(major, minor, tiny) ((((major)&0xffff) << 16) | (((minor)&0xff) << 8) | ((tiny)&0xff))
uint32_t APIs::deriveVersionFromDylibs(const MachOFile* mf)
{
// This is a binary without a version load command, we need to infer things
struct DylibToOSMapping
{
uint32_t dylibVersion;
uint32_t osVersion;
};
uint32_t linkedVersion = 0;
#if TARGET_OS_OSX
linkedVersion = linkedDylibVersion(mf, "/usr/lib/libSystem.B.dylib");
static const DylibToOSMapping versionMapping[] = {
{ PACKED_VERSION(88, 1, 3), 0x000A0400 },
{ PACKED_VERSION(111, 0, 0), 0x000A0500 },
{ PACKED_VERSION(123, 0, 0), 0x000A0600 },
{ PACKED_VERSION(159, 0, 0), 0x000A0700 },
{ PACKED_VERSION(169, 3, 0), 0x000A0800 },
{ PACKED_VERSION(1197, 0, 0), 0x000A0900 },
{ PACKED_VERSION(0, 0, 0), 0x000A0900 }
// We don't need to expand this table because all recent
// binaries have LC_VERSION_MIN_ load command.
};
#elif TARGET_OS_IOS
linkedVersion = linkedDylibVersion(mf, "/System/Library/Frameworks/Foundation.framework/Foundation");
static const DylibToOSMapping versionMapping[] = {
{ PACKED_VERSION(678, 24, 0), 0x00020000 },
{ PACKED_VERSION(678, 26, 0), 0x00020100 },
{ PACKED_VERSION(678, 29, 0), 0x00020200 },
{ PACKED_VERSION(678, 47, 0), 0x00030000 },
{ PACKED_VERSION(678, 51, 0), 0x00030100 },
{ PACKED_VERSION(678, 60, 0), 0x00030200 },
{ PACKED_VERSION(751, 32, 0), 0x00040000 },
{ PACKED_VERSION(751, 37, 0), 0x00040100 },
{ PACKED_VERSION(751, 49, 0), 0x00040200 },
{ PACKED_VERSION(751, 58, 0), 0x00040300 },
{ PACKED_VERSION(881, 0, 0), 0x00050000 },
{ PACKED_VERSION(890, 1, 0), 0x00050100 },
{ PACKED_VERSION(992, 0, 0), 0x00060000 },
{ PACKED_VERSION(993, 0, 0), 0x00060100 },
{ PACKED_VERSION(1038, 14, 0), 0x00070000 },
{ PACKED_VERSION(0, 0, 0), 0x00070000 }
// We don't need to expand this table because all recent
// binaries have LC_VERSION_MIN_ load command.
};
#else
static const DylibToOSMapping versionMapping[] = {};
#endif
if ( linkedVersion != 0 ) {
uint32_t lastOsVersion = 0;
for ( const DylibToOSMapping* p = versionMapping;; ++p ) {
if ( p->dylibVersion == 0 ) {
return p->osVersion;
}
if ( linkedVersion < p->dylibVersion ) {
return lastOsVersion;
}
lastOsVersion = p->osVersion;
}
}
return 0;
}
// assumes mh has already been validated
void APIs::forEachPlatform(const MachOFile* mf, void (^callback)(dyld_platform_t platform, uint32_t sdk_version, uint32_t min_version))
{
__block bool lcFound = false;
mf->forEachSupportedPlatform(^(dyld3::Platform platform, uint32_t minOS, uint32_t sdk) {
lcFound = true;
// If SDK field is empty then derive the value from library linkages
if ( sdk == 0 ) {
sdk = deriveVersionFromDylibs(mf);
}
callback((const dyld_platform_t)platform, sdk, minOS);
});
// No load command was found, so again, fallback to deriving it from library linkages
if ( !lcFound ) {
#if TARGET_OS_IOS
#if __x86_64__ || __x86__
dyld_platform_t platform = PLATFORM_IOSSIMULATOR;
#else
dyld_platform_t platform = PLATFORM_IOS;
#endif
#elif TARGET_OS_OSX
dyld_platform_t platform = PLATFORM_MACOS;
#else
dyld_platform_t platform = 0;
#endif
uint32_t derivedVersion = deriveVersionFromDylibs(mf);
if ( platform != 0 && derivedVersion != 0 ) {
callback(platform, derivedVersion, 0);
}
}
}
void APIs::dyld_get_image_versions(const mach_header* mh, void (^callback)(dyld_platform_t platform, uint32_t sdk_version, uint32_t min_version))
{
if ( config.log.apis )
log("dyld_get_image_versions(%p, %p)\n", mh, callback);
forEachImageVersion(mh, callback);
}
void APIs::forEachImageVersion(const mach_header* mh, void (^callback)(dyld_platform_t platform, uint32_t sdk_version, uint32_t min_version))
{
Diagnostics diag;
const MachOFile* mf = (MachOFile*)mh;
if ( mh == config.process.mainExecutable ) {
// Special case main executable, that info is store in ProcessConfig
callback((dyld_platform_t)config.process.platform, config.process.mainExecutableSDKVersion, config.process.mainExecutableMinOSVersion);
}
else if ( DyldSharedCache::inDyldCache(config.dyldCache.addr, mf) ) {
// If the image is in the shared cache, then all versions OS and SDK versions are the same
callback((dyld_platform_t)config.dyldCache.platform, config.dyldCache.osVersion, config.dyldCache.osVersion);
}
else if ( mf->isMachO(diag, mh->sizeofcmds + sizeof(mach_header_64)) ) {
// look for LC_BUILD_VERSION or derive from dylib info
this->forEachPlatform(mf, callback);
}
}
uint32_t APIs::dyld_get_program_min_os_version()
{
return dyld_get_min_os_version(config.process.mainExecutable);
}
bool APIs::_dyld_get_image_uuid(const mach_header* mh, uuid_t uuid)
{
if ( config.log.apis )
log("_dyld_get_image_uuid(%p, %p)\n", mh, uuid);
const MachOFile* mf = (MachOFile*)mh;
return (mf->hasMachOMagic() && mf->getUuid(uuid));
}
int APIs::_NSGetExecutablePath(char* buf, uint32_t* bufsize)
{
if ( config.log.apis )
log("_NSGetExecutablePath(%p, %p)\n", buf, bufsize);
const char* path = config.process.mainExecutablePath;
if ( config.process.platform == dyld3::Platform::macOS )
path = config.process.mainUnrealPath; // Note: this is not real-path. It may be a symlink rdar://74451681
size_t pathSize = strlen(path) + 1;
if ( *bufsize >= pathSize ) {
strcpy(buf, path);
return 0;
}
*bufsize = (uint32_t)pathSize;
return -1;
}
void APIs::_dyld_register_func_for_add_image(void (*func)(const mach_header* mh, intptr_t slide))
{
if ( config.log.apis )
log("_dyld_register_func_for_add_image(%p)\n", func);
// callback about already loaded images
withLoadersReadLock(^{
for ( const Loader* ldr : loaded ) {
const MachOLoaded* ml = ldr->loadAddress(*this);
if ( config.log.notifications )
log("add notifier %p called with mh=%p\n", func, ml);
if ( DyldSharedCache::inDyldCache(config.dyldCache.addr, ml) )
func(ml, config.dyldCache.slide);
else
func(ml, ml->getSlide());
}
});
// add to list of functions to call about future loads
const Loader* callbackLoader = this->findImageContaining((void*)func);
withNotifiersWriteLock(^{
addNotifyAddFunc(callbackLoader, func);
});
}
void APIs::_dyld_register_func_for_remove_image(void (*func)(const mach_header* mh, intptr_t slide))
{
if ( config.log.apis )
log("_dyld_register_func_for_remove_image(%p)\n", func);
// add to list of functions to call about future unloads
const Loader* callbackLoader = this->findImageContaining((void*)func);
withNotifiersWriteLock(^{
addNotifyRemoveFunc(callbackLoader, func);
});
}
// FIXME: Remove this once libobjc moves to _dyld_objc_register_callbacks()
void APIs::_dyld_objc_notify_register(_dyld_objc_notify_mapped mapped,
_dyld_objc_notify_init init,
_dyld_objc_notify_unmapped unmapped)
{
if ( config.log.apis )
log("_dyld_objc_notify_register(%p, %p, %p)\n", mapped, init, unmapped);
setObjCNotifiers(mapped, init, unmapped, nullptr, nullptr);
// If we have prebuilt loaders, then the objc optimisations may hide duplicate classes from libobjc.
// We need to print the same warnings libobjc would have.
if ( const PrebuiltLoaderSet* mainSet = this->processPrebuiltLoaderSet() )
mainSet->logDuplicateObjCClasses(*this);
}
void APIs::_dyld_objc_register_callbacks(const _dyld_objc_callbacks* callbacks)
{
if ( config.log.apis ) {
void** p = (void**)callbacks;
log("_dyld_objc_register_callbacks(%lu, %p, %p, %p, %p)\n", callbacks->version, p[1], p[2], p[31], p[4]);
}
if ( callbacks->version == 1 ) {
const _dyld_objc_callbacks_v1* v1 = (const _dyld_objc_callbacks_v1*)callbacks;
setObjCNotifiers(v1->mapped, v1->init, v1->unmapped, v1->patches, nullptr);
}
else if ( callbacks->version == 2 ) {
const _dyld_objc_callbacks_v2* v2 = (const _dyld_objc_callbacks_v2*)callbacks;
setObjCNotifiers(nullptr, v2->init, v2->unmapped, v2->patches, v2->mapped);
}
else {
}
// If we have prebuilt loaders, then the objc optimisations may hide duplicate classes from libobjc.
// We need to print the same warnings libobjc would have.
if ( const PrebuiltLoaderSet* mainSet = this->processPrebuiltLoaderSet() )
mainSet->logDuplicateObjCClasses(*this);
}
bool APIs::findImageMappedAt(const void* addr, const MachOLoaded** ml, bool* neverUnloads, const char** path, const void** segAddr, uint64_t* segSize, uint8_t* segPerms)
{
__block bool result = false;
// if address is in cache, do fast search of TEXT segments in cache
const DyldSharedCache* dyldCache = config.dyldCache.addr;
bool inSharedCache = false;
if ( (dyldCache != nullptr) && (addr > dyldCache) ) {
if ( addr < (void*)((uint8_t*)dyldCache + dyldCache->mappedSize()) ) {
inSharedCache = true;
uint64_t cacheSlide = (uint64_t)dyldCache - dyldCache->unslidLoadAddress();
uint64_t unslidTargetAddr = (uint64_t)addr - cacheSlide;
// Find where we are in the cache. The permissions can be used to then do a faster check later
__block uint32_t sharedCacheRegionProt = 0;
dyldCache->forEachRange(^(const char *mappingName, uint64_t unslidVMAddr, uint64_t vmSize,
uint32_t cacheFileIndex, uint64_t fileOffset, uint32_t initProt, uint32_t maxProt, bool& stopRange) {
if ( (unslidVMAddr <= unslidTargetAddr) && (unslidTargetAddr < (unslidVMAddr + vmSize)) ) {
sharedCacheRegionProt = initProt;
stopRange = true;
}
});
#if !TARGET_OS_SIMULATOR
// rdar://76406035 (simulator cache paths need prefix)
if ( sharedCacheRegionProt == (VM_PROT_READ | VM_PROT_EXECUTE) ) {
dyldCache->forEachImageTextSegment(^(uint64_t loadAddressUnslid, uint64_t textSegmentSize, const unsigned char* dylibUUID, const char* installName, bool& stop) {
if ( (loadAddressUnslid <= unslidTargetAddr) && (unslidTargetAddr < loadAddressUnslid + textSegmentSize) ) {
if ( ml != nullptr )
*ml = (MachOLoaded*)(loadAddressUnslid + cacheSlide);
if ( neverUnloads != nullptr )
*neverUnloads = true;
if ( path != nullptr )
*path = installName;
if ( segAddr != nullptr )
*segAddr = (void*)(loadAddressUnslid + cacheSlide);
if ( segSize != nullptr )
*segSize = textSegmentSize;
if ( segPerms != nullptr )
*segPerms = VM_PROT_READ | VM_PROT_EXECUTE;
stop = true;
result = true;
}
});
if ( result )
return result;
}
#endif // TARGET_OS_SIMULATOR
}
}
// next check if address is in a permanent range
const Loader* ldr;
uint8_t perms;
if ( this->inPermanentRange((uintptr_t)addr, (uintptr_t)addr + 1, &perms, &ldr) ) {
if ( ml != nullptr )
*ml = ldr->loadAddress(*this);
if ( neverUnloads != nullptr )
*neverUnloads = true;
if ( path != nullptr )
*path = ldr->path();
if ( (segAddr != nullptr) || (segSize != nullptr) ) {
// only needed by _dyld_images_for_addresses()
const void* ldrSegAddr;
uint64_t ldrSegSize;
uint8_t ldrPerms;
if ( ldr->contains(*this, addr, &ldrSegAddr, &ldrSegSize, &ldrPerms) ) {
if ( segAddr != nullptr )
*segAddr = ldrSegAddr;
if ( segSize != nullptr )
*segSize = ldrSegSize;
}
}
if ( segPerms != nullptr )
*segPerms = perms;
return true;
}
// slow path - search image list
withLoadersReadLock(^{
// If we found a cache range for this address, then we know we only need to look in loaders for the cache
for ( const Loader* image : loaded ) {
if ( image->dylibInDyldCache != inSharedCache )
continue;
const void* sgAddr;
uint64_t sgSize;
uint8_t sgPerm;
if ( image->contains(*this, addr, &sgAddr, &sgSize, &sgPerm) ) {
if ( ml != nullptr )
*ml = image->loadAddress(*this);
if ( neverUnloads != nullptr )
*neverUnloads = image->neverUnload;
if ( path != nullptr )
*path = image->path();
if ( segAddr != nullptr )
*segAddr = sgAddr;
if ( segSize != nullptr )
*segSize = sgSize;
if ( segPerms != nullptr )
*segPerms = sgPerm;
result = true;
return;
}
}
});
// [NSBundle bundleForClass] will call dyld_image_path_containing_address(cls) with the shared
// cache version of the class, not the one in the root. We need to return the path to the root
// so that resources can be found relative to the bundle
if ( !result && !this->patchedObjCClasses.empty() ) {
for ( const InterposeTupleAll& tuple : this->patchedObjCClasses ) {
if ( tuple.replacement == (uintptr_t)addr )
return this->findImageMappedAt((void*)tuple.replacee, ml, neverUnloads, path, segAddr, segSize, segPerms);