-
Notifications
You must be signed in to change notification settings - Fork 69
/
DyldProcessConfig.cpp
1692 lines (1541 loc) · 67.1 KB
/
DyldProcessConfig.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-2020 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 <dyld/VersionMap.h>
#include <mach-o/dyld_priv.h>
#if BUILDING_DYLD
#include <sys/socket.h>
#include <sys/syslog.h>
#include <sys/uio.h>
#include <sys/un.h>
#include <sys/mman.h>
#include <System/sys/csr.h>
#include <System/sys/reason.h>
#include <kern/kcdata.h>
#include <System/machine/cpu_capabilities.h>
#if !TARGET_OS_DRIVERKIT
#include <vproc_priv.h>
#endif
// no libc header for send() syscall interface
extern "C" ssize_t __sendto(int, const void*, size_t, int, const struct sockaddr*, socklen_t);
#endif
#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),
AMFI_DYLD_OUTPUT_ALLOW_LIBRARY_INTERPOSING = (1 << 6),
};
extern "C" int amfi_check_dyld_policy_self(uint64_t input_flags, uint64_t* output_flags);
#include "dyldSyscallInterface.h"
#else
#include <libamfi.h>
#endif
#include "MachOLoaded.h"
#include "MachOAnalyzer.h"
#include "DyldSharedCache.h"
#include "SharedCacheRuntime.h"
#include "Loader.h"
#include "DyldProcessConfig.h"
#include "DebuggerSupport.h"
// based on ANSI-C strstr()
static const char* strrstr(const char* str, const char* sub)
{
const size_t sublen = strlen(sub);
for (const char* p = &str[strlen(str)]; p != str; --p) {
if ( ::strncmp(p, sub, sublen) == 0 )
return p;
}
return nullptr;
}
using dyld3::MachOFile;
using dyld3::Platform;
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 uint64_t hexToUInt64(const char* startHexByte, const char** endHexByte)
{
const char* scratch;
if ( endHexByte == nullptr ) {
endHexByte = &scratch;
}
if ( startHexByte == nullptr )
return 0;
uint64_t retval = 0;
if ( (startHexByte[0] == '0') && (startHexByte[1] == 'x') ) {
startHexByte += 2;
}
*endHexByte = startHexByte + 16;
//FIXME overrun?
for ( uint32_t i = 0; i < 16; ++i ) {
uint8_t value;
if ( !hexCharToByte(startHexByte[i], value) ) {
*endHexByte = &startHexByte[i];
break;
}
retval = (retval << 4) + value;
}
return retval;
}
namespace dyld4 {
//
// MARK: --- KernelArgs methods ---
//
#if !BUILDING_DYLD
KernelArgs::KernelArgs(const MachOAnalyzer* mh, const std::vector<const char*>& argv, const std::vector<const char*>& envp, const std::vector<const char*>& apple)
: mainExecutable(mh)
, argc(argv.size())
{
assert( argv.size() + envp.size() + apple.size() < MAX_KERNEL_ARGS);
// build the info passed to dyld on startup the same way the kernel does on the stack
size_t index = 0;
for ( const char* arg : argv )
args[index++] = arg;
args[index++] = nullptr;
for ( const char* arg : envp )
args[index++] = arg;
args[index++] = nullptr;
for ( const char* arg : apple )
args[index++] = arg;
args[index++] = nullptr;
}
#endif
const char** KernelArgs::findArgv() const
{
return (const char**)&args[0];
}
const char** KernelArgs::findEnvp() const
{
// argv array has nullptr at end, so envp starts at argc+1
return (const char**)&args[argc + 1];
}
const char** KernelArgs::findApple() const
{
// envp array has nullptr at end, apple starts after that
const char** p = findEnvp();
while ( *p != nullptr )
++p;
++p;
return p;
}
//
// MARK: --- ProcessConfig methods ---
//
ProcessConfig::ProcessConfig(const KernelArgs* kernArgs, SyscallDelegate& syscallDelegate)
: syscall(syscallDelegate),
process(kernArgs, syscallDelegate),
security(process, syscallDelegate),
log(process, security, syscallDelegate),
dyldCache(process, security, log, syscallDelegate),
pathOverrides(process, security, log, dyldCache, syscallDelegate)
{
}
#if !BUILDING_DYLD
void ProcessConfig::reset(const MachOAnalyzer* mainExe, const char* mainPath, const DyldSharedCache* cache)
{
process.mainExecutablePath = mainPath;
process.mainUnrealPath = mainPath;
process.mainExecutable = mainExe;
dyldCache.addr = cache;
dyldCache.slide = cache->slide();
}
#endif
//
// MARK: --- Process methods ---
//
static bool defaultDataConst(DyldCommPage commPage)
{
if ( commPage.forceRWDataConst ) {
return false;
} else if ( commPage.forceRWDataConst ) {
return true;
} else {
// __DATA_CONST is enabled by default, as the above boot-args didn't override it
return true;
}
}
ProcessConfig::Process::Process(const KernelArgs* kernArgs, SyscallDelegate& syscall)
{
this->mainExecutable = kernArgs->mainExecutable;
this->argc = (int)kernArgs->argc;
this->argv = kernArgs->findArgv();
this->envp = kernArgs->findEnvp();
this->apple = kernArgs->findApple();
this->pid = syscall.getpid();
this->platform = this->getMainPlatform();
this->mainUnrealPath = this->getMainUnrealPath(syscall);
this->mainExecutablePath = this->getMainPath(syscall);
this->dyldPath = this->getDyldPath(syscall);
this->progname = PathOverrides::getLibraryLeafName(this->mainUnrealPath);
this->catalystRuntime = this->usesCatalyst();
this->commPage = syscall.dyldCommPageFlags();
this->archs = this->getMainArchs(syscall);
this->isTranslated = syscall.isTranslated();
this->enableDataConst = defaultDataConst(this->commPage);
#if TARGET_OS_OSX
this->proactivelyUseWeakDefMap = (strncmp(progname, "MATLAB",6) == 0); // rdar://81498849
#else
this->proactivelyUseWeakDefMap = false;
#endif
}
const char* ProcessConfig::Process::appleParam(const char* key) const
{
return _simple_getenv((const char**)apple, key);
}
const char* ProcessConfig::Process::environ(const char* key) const
{
return _simple_getenv((const char**)envp, key);
}
void* ProcessConfig::Process::roalloc(size_t size) const
{
#if BUILDING_DYLD
// warning: fragile code here. The goal is to have a small buffer that
// goes onto the end of the __DATA_CONST segment. That segment is r/w
// while ProcessConfig is being constructed, then made r/o.
static uint8_t roBuffer[0x10000] __attribute__((section("__DATA_CONST,__bss")));
static uint8_t* next = roBuffer;
assert( next < &roBuffer[0x10000]);
void* result = next;
next += size;
return result;
#else
return ::malloc(size);
#endif
}
const char* ProcessConfig::Process::strdup(const char* str) const
{
#if BUILDING_DYLD
size_t size = strlen(str)+1;
char* result = (char*)roalloc(size);
::strcpy(result, str);
return result;
#else
return ::strdup(str);
#endif
}
const char* ProcessConfig::Process::pathFromFileHexStrings(SyscallDelegate& sys, const char* encodedFileInfo)
{
// kernel passes fsID and objID encoded as two hex values (e.g. 0x123,0x456)
const char* endPtr = nullptr;
uint64_t fsID = hexToUInt64(encodedFileInfo, &endPtr);
if ( endPtr != nullptr ) {
uint64_t objID = hexToUInt64(endPtr+1, &endPtr);
char pathFromIDs[MAXPATHLEN];
if ( sys.fsgetpath(pathFromIDs, MAXPATHLEN, fsID, objID) != -1 ) {
// return read-only copy of absolute path
return this->strdup(pathFromIDs);
}
}
// something wrong with "executable_file=" or "dyld_file=" encoding
return nullptr;
}
const char* ProcessConfig::Process::getDyldPath(SyscallDelegate& sys)
{
// kernel passes fsID and objID of dyld encoded as two hex values (e.g. 0x123,0x456)
if ( const char* dyldFsIdAndObjId = this->appleParam("dyld_file") ) {
if ( const char* path = this->pathFromFileHexStrings(sys, dyldFsIdAndObjId) )
return path;
}
// something wrong with "dyld_file=", fallback to default
return "/usr/lib/dyld";
}
const char* ProcessConfig::Process::getMainPath(SyscallDelegate& sys)
{
// kernel passes fsID and objID of main executable encoded as two hex values (e.g. 0x123,0x456)
if ( const char* mainPathFsIdAndObjId = this->appleParam("executable_file") ) {
if ( const char* path = this->pathFromFileHexStrings(sys, mainPathFsIdAndObjId) )
return path;
}
// something wrong with "executable_file=", fallback to (un)realpath
char resolvedPath[PATH_MAX];
if ( sys.realpath(this->mainUnrealPath, resolvedPath) ) {
return this->strdup(resolvedPath);
}
return this->mainUnrealPath;
}
const char* ProcessConfig::Process::getMainUnrealPath(SyscallDelegate& sys)
{
// if above failed, kernel also passes path to main executable in apple param
const char* mainPath = this->appleParam("executable_path");
// if kernel arg is missing, fallback to argv[0]
if ( mainPath == nullptr )
mainPath = argv[0];
// if path is not a full path, use cwd to transform it to a full path
if ( mainPath[0] != '/' ) {
// normalize someone running ./foo from the command line
if ( (mainPath[0] == '.') && (mainPath[1] == '/') ) {
mainPath += 2;
}
// have relative path, use cwd to make absolute
char buff[MAXPATHLEN];
if ( sys.getCWD(buff) ) {
strlcat(buff, "/", MAXPATHLEN);
strlcat(buff, mainPath, MAXPATHLEN);
mainPath = this->strdup(buff);
}
}
return mainPath;
}
bool ProcessConfig::Process::usesCatalyst()
{
#if BUILDING_DYLD
#if TARGET_OS_OSX
#if __arm64__
// on Apple Silicon macs, iOS apps and Catalyst apps use catalyst runtime
return ( (this->platform == Platform::iOSMac) || (this->platform == Platform::iOS) );
#else
return (this->platform == Platform::iOSMac);
#endif
#else
return false;
#endif
#else
// FIXME: may need a way to fake iOS-apps-on-Mac for unit tests
return ( this->platform == Platform::iOSMac );
#endif
}
uint32_t ProcessConfig::Process::findVersionSetEquivalent(dyld3::Platform versionPlatform, uint32_t version) const {
uint32_t candidateVersion = 0;
uint32_t candidateVersionEquivalent = 0;
uint32_t newVersionSetVersion = 0;
for (const auto& i : dyld3::sVersionMap) {
switch (MachOFile::basePlatform(versionPlatform)) {
case dyld3::Platform::macOS: newVersionSetVersion = i.macos; break;
case dyld3::Platform::iOS: newVersionSetVersion = i.ios; break;
case dyld3::Platform::watchOS: newVersionSetVersion = i.watchos; break;
case dyld3::Platform::tvOS: newVersionSetVersion = i.tvos; break;
case dyld3::Platform::bridgeOS: newVersionSetVersion = i.bridgeos; break;
default: newVersionSetVersion = 0xffffffff; // If we do not know about the platform it is newer than everything
}
if (newVersionSetVersion > version) { break; }
candidateVersion = newVersionSetVersion;
candidateVersionEquivalent = i.set;
}
if (newVersionSetVersion == 0xffffffff && candidateVersion == 0) {
candidateVersionEquivalent = newVersionSetVersion;
}
return candidateVersionEquivalent;
};
Platform ProcessConfig::Process::getMainPlatform()
{
// extract platform from main executable
this->mainExecutableSDKVersion = 0;
this->mainExecutableMinOSVersion = 0;
__block Platform result = Platform::unknown;
mainExecutable->forEachSupportedPlatform(^(Platform plat, uint32_t minOS, uint32_t sdk) {
result = plat;
this->mainExecutableSDKVersion = sdk;
this->mainExecutableMinOSVersion = minOS;
});
// platform overrides only applicable on macOS, and can only force to 6 or 2
if ( result == dyld3::Platform::macOS ) {
if ( const char* forcedPlatform = this->environ("DYLD_FORCE_PLATFORM") ) {
if ( mainExecutable->allowsAlternatePlatform() ) {
if ( strncmp(forcedPlatform, "6", 1) == 0 ) {
result = dyld3::Platform::iOSMac;
}
else if ( (strncmp(forcedPlatform, "2", 1) == 0) && (strcmp(mainExecutable->archName(), "arm64") == 0) ) {
result = dyld3::Platform::iOS;
}
for (const dyld3::VersionSetEntry& entry : dyld3::sVersionMap) {
if ( entry.macos == this->mainExecutableSDKVersion ) {
this->mainExecutableSDKVersion = entry.ios;
break;
}
}
for (const dyld3::VersionSetEntry& entry : dyld3::sVersionMap) {
if ( entry.macos == this->mainExecutableMinOSVersion ) {
this->mainExecutableMinOSVersion = entry.ios;
break;
}
}
}
}
}
this->basePlatform = MachOFile::basePlatform(result);
this->mainExecutableSDKVersionSet = findVersionSetEquivalent(this->basePlatform, this->mainExecutableSDKVersion);
this->mainExecutableMinOSVersionSet = findVersionSetEquivalent(this->basePlatform, this->mainExecutableMinOSVersion);
return result;
}
const GradedArchs* ProcessConfig::Process::getMainArchs(SyscallDelegate& sys)
{
bool keysOff = false;
#if BUILDING_CLOSURE_UTIL
// In closure util, just assume we want to allow arm64 binaries to get closures built
// against arm64e shared caches
if ( strcmp(mainExecutable->archName(), "arm64e") == 0 )
keysOff = true;
#else
// Check and see if kernel disabled JOP pointer signing (which lets us load plain arm64 binaries)
if ( const char* disableStr = this->appleParam("ptrauth_disabled") ) {
if ( strcmp(disableStr, "1") == 0 )
keysOff = true;
}
else {
// needed until kernel passes ptrauth_disabled for arm64 main executables
if ( strcmp(mainExecutable->archName(), "arm64") == 0 )
keysOff = true;
}
#endif
return &sys.getGradedArchs(mainExecutable->archName(), keysOff);
}
//
// MARK: --- Security methods ---
//
ProcessConfig::Security::Security(Process& process, SyscallDelegate& syscall)
{
this->internalInstall = syscall.internalInstall(); // Note: must be set up before calling getAMFI()
this->skipMain = this->internalInstall && process.environ("DYLD_SKIP_MAIN");
const uint64_t amfiFlags = getAMFI(process, syscall);
this->allowAtPaths = (amfiFlags & AMFI_DYLD_OUTPUT_ALLOW_AT_PATH);
this->allowEnvVarsPrint = (amfiFlags & AMFI_DYLD_OUTPUT_ALLOW_PRINT_VARS);
this->allowEnvVarsPath = (amfiFlags & AMFI_DYLD_OUTPUT_ALLOW_PATH_VARS);
this->allowEnvVarsSharedCache = (amfiFlags & AMFI_DYLD_OUTPUT_ALLOW_CUSTOM_SHARED_CACHE);
this->allowClassicFallbackPaths = (amfiFlags & AMFI_DYLD_OUTPUT_ALLOW_FALLBACK_PATHS);
this->allowInsertFailures = (amfiFlags & AMFI_DYLD_OUTPUT_ALLOW_FAILED_LIBRARY_INSERTION);
this->allowInterposing = (amfiFlags & AMFI_DYLD_OUTPUT_ALLOW_LIBRARY_INTERPOSING);
#if TARGET_OS_SIMULATOR
this->allowInsertFailures = true; // FIXME: amfi is returning the wrong value for simulators <rdar://74025454>
#endif
// env vars are only pruned on macOS
switch ( process.platform ) {
case dyld3::Platform::macOS:
case dyld3::Platform::iOSMac:
case dyld3::Platform::driverKit:
break;
default:
return;
}
// env vars are only pruned when process is restricted
if ( this->allowEnvVarsPrint || this->allowEnvVarsPath || this->allowEnvVarsSharedCache )
return;
this->pruneEnvVars(process);
}
uint64_t ProcessConfig::Security::getAMFI(const Process& proc, SyscallDelegate& sys)
{
uint32_t fpTextOffset;
uint32_t fpSize;
uint64_t amfiFlags = sys.amfiFlags(proc.mainExecutable->isRestricted(), proc.mainExecutable->isFairPlayEncrypted(fpTextOffset, fpSize));
bool testMode = proc.commPage.testMode;
#if !BUILDING_DYLD
// during unit tests, commPage not set up yet, so peak ahead
if ( const char* bootFlags = proc.appleParam("dyld_flags") ) {
testMode = ((hexToUInt64(bootFlags, nullptr) & 0x02) != 0);
}
#endif
// let DYLD_AMFI_FAKE override actual AMFI flags, but only on internalInstalls with boot-arg set
if ( const char* amfiFake = proc.environ("DYLD_AMFI_FAKE") ) {
//console("env DYLD_AMFI_FAKE set, boot-args dyld_flags=%s\n", this->getAppleParam("dyld_flags"));
if ( !testMode ) {
//console("env DYLD_AMFI_FAKE ignored because boot-args dyld_flags=2 is missing (%s)\n", this->getAppleParam("dyld_flags"));
}
else if ( !this->internalInstall ) {
//console("env DYLD_AMFI_FAKE ignored because not running on an Internal install\n");
}
else {
amfiFlags = hexToUInt64(amfiFake, nullptr);
//console("env DYLD_AMFI_FAKE parsed as 0x%08llX\n", amfiFlags);
}
}
return amfiFlags;
}
void ProcessConfig::Security::pruneEnvVars(Process& proc)
{
//
// For security, setuid programs ignore DYLD_* environment variables.
// Additionally, the DYLD_* enviroment variables are removed
// from the environment, so that any child processes doesn't see them.
//
// delete all DYLD_* environment variables
int removedCount = 0;
const char** d = (const char**)proc.envp;
for ( const char* const* s = proc.envp; *s != NULL; s++ ) {
if ( strncmp(*s, "DYLD_", 5) != 0 ) {
*d++ = *s;
}
else {
++removedCount;
}
}
*d++ = NULL;
// slide apple parameters
if ( removedCount > 0 ) {
proc.apple = d;
do {
*d = d[removedCount];
} while ( *d++ != NULL );
for ( int i = 0; i < removedCount; ++i )
*d++ = NULL;
}
}
//
// MARK: --- Logging methods ---
//
ProcessConfig::Logging::Logging(const Process& process, const Security& security, SyscallDelegate& syscall)
{
this->segments = security.allowEnvVarsPrint && process.environ("DYLD_PRINT_SEGMENTS");
this->libraries = security.allowEnvVarsPrint && process.environ("DYLD_PRINT_LIBRARIES");
this->fixups = security.allowEnvVarsPrint && process.environ("DYLD_PRINT_BINDINGS");
this->initializers = security.allowEnvVarsPrint && process.environ("DYLD_PRINT_INITIALIZERS");
this->apis = security.allowEnvVarsPrint && process.environ("DYLD_PRINT_APIS");
this->notifications = security.allowEnvVarsPrint && process.environ("DYLD_PRINT_NOTIFICATIONS");
this->interposing = security.allowEnvVarsPrint && process.environ("DYLD_PRINT_INTERPOSING");
this->loaders = security.allowEnvVarsPrint && process.environ("DYLD_PRINT_LOADERS");
this->searching = security.allowEnvVarsPrint && process.environ("DYLD_PRINT_SEARCHING");
this->env = security.allowEnvVarsPrint && process.environ("DYLD_PRINT_ENV");
this->useStderr = security.allowEnvVarsPrint && process.environ("DYLD_PRINT_TO_STDERR");
this->descriptor = STDERR_FILENO;
this->useFile = false;
if ( security.allowEnvVarsPrint && security.allowEnvVarsSharedCache ) {
if ( const char* path = process.environ("DYLD_PRINT_TO_FILE") ) {
int fd = syscall.openLogFile(path);
if ( fd != -1 ) {
this->useFile = true;
this->descriptor = fd;
}
}
}
}
//
// MARK: --- DyldCache methods ---
//
ProcessConfig::DyldCache::DyldCache(Process& process, const Security& security, const Logging& log, SyscallDelegate& syscall)
{
bool forceCustomerCache = process.commPage.forceCustomerCache;
bool forceDevCache = process.commPage.forceDevCache;
#if BUILDING_DYLD
// in launchd commpage is not set up yet
if ( process.pid == 1 ) {
if ( security.internalInstall ) {
// default to development cache for internal installs
forceCustomerCache = false;
if ( const char* bootFlags = process.appleParam("dyld_flags") ) {
// on internal installs, dyld_flags can force customer cache
DyldCommPage cpFlags;
*((uint32_t*)&cpFlags) = (uint32_t)hexToUInt64(bootFlags, nullptr);
if ( cpFlags.forceCustomerCache )
forceCustomerCache = true;
if ( cpFlags.forceDevCache ) {
forceDevCache = true;
forceCustomerCache = false;
}
}
}
else {
// customer installs always get customer dyld cache
forceCustomerCache = true;
forceDevCache = false;
}
}
#endif
// load dyld cache if needed
const char* cacheMode = process.environ("DYLD_SHARED_REGION");
#if TARGET_OS_SIMULATOR && __arm64__
if ( cacheMode == nullptr ) {
// A 2GB simulator app on Apple Silicon can overlay where the dyld cache is supposed to go
// Luckily, simulators still have dylibs on disk, so we can run the process without a dyld cache
// FIXME: Somehow get ARM64_SHARED_REGION_START = 0x180000000ULL
if ( process.mainExecutable->intersectsRange(0x180000000ULL, 0x100000000ULL) ) {
if ( log.segments )
console("main executable resides where dyld cache would be, so not using a dyld cache\n");
cacheMode = "avoid";
}
}
#endif
dyld3::SharedCacheOptions opts;
opts.cacheDirOverride = process.environ("DYLD_SHARED_CACHE_DIR");
opts.forcePrivate = security.allowEnvVarsSharedCache && (cacheMode != nullptr) && (strcmp(cacheMode, "private") == 0);
opts.useHaswell = syscall.onHaswell();
opts.verbose = log.segments;
opts.disableASLR = false; // FIXME
opts.enableReadOnlyDataConst = process.enableDataConst;
opts.preferCustomerCache = forceCustomerCache;
opts.forceDevCache = forceDevCache;
opts.isTranslated = process.isTranslated;
opts.platform = process.platform;
this->addr = nullptr;
this->slide = 0;
this->path = nullptr;
this->objCCacheInfo = nullptr;
this->swiftCacheInfo = nullptr;
this->platform = Platform::unknown;
this->osVersion = 0;
this->dylibCount = 0;
if ( (cacheMode == nullptr) || (strcmp(cacheMode, "avoid") != 0) ) {
dyld3::SharedCacheLoadInfo loadInfo;
syscall.getDyldCache(opts, loadInfo);
if ( loadInfo.loadAddress != nullptr ) {
this->addr = loadInfo.loadAddress;
this->slide = loadInfo.slide;
this->path = process.strdup(loadInfo.path);
this->objCCacheInfo = this->addr->objcOpt();
this->swiftCacheInfo = this->addr->swiftOpt();
this->dylibCount = this->addr->imagesCount();
this->setPlatformOSVersion(process);
// The shared cache is mapped with RO __DATA_CONST, but this
// process might need RW
if ( !opts.enableReadOnlyDataConst )
makeDataConstWritable(log, syscall, true);
}
else {
#if BUILDING_DYLD && !TARGET_OS_SIMULATOR
// <rdar://74102798> log all shared cache errors except no cache file
if ( loadInfo.cacheFileFound )
console("dyld cache '%s' not loaded: %s\n", loadInfo.path, loadInfo.errorMessage);
#endif
}
}
#if BUILDING_DYLD
// in launchd we set up the dyld comm-page bits
if ( process.pid == 1 )
#endif
this->setupDyldCommPage(process, security, syscall);
}
bool ProcessConfig::DyldCache::uuidOfFileMatchesDyldCache(const Process& proc, const SyscallDelegate& sys, const char* dylibPath) const
{
// get UUID of dylib in cache
if ( const dyld3::MachOFile* cacheMF = this->addr->getImageFromPath(dylibPath) ) {
uuid_t cacheUUID;
if ( !cacheMF->getUuid(cacheUUID) )
return false;
// get UUID of file on disk
uuid_t diskUUID;
uint8_t* diskUUIDPtr = diskUUID; // work around compiler bug with arrays and __block
__block bool diskUuidFound = false;
__block Diagnostics diag;
sys.withReadOnlyMappedFile(diag, dylibPath, false, ^(const void* mapping, size_t mappedSize, bool isOSBinary, const FileID& fileID, const char* canonicalPath) {
if ( const MachOFile* diskMF = MachOFile::compatibleSlice(diag, mapping, mappedSize, dylibPath, proc.platform, isOSBinary, *proc.archs) ) {
diskUuidFound = diskMF->getUuid(diskUUIDPtr);
}
});
if ( !diskUuidFound )
return false;
return (::memcmp(diskUUID, cacheUUID, sizeof(uuid_t)) == 0);
}
return false;
}
void ProcessConfig::DyldCache::setPlatformOSVersion(const Process& proc)
{
// new caches have OS version recorded
if ( addr->header.mappingOffset >= 0x170 ) {
// decide if process is using main platform or alternate platform
if ( proc.platform == (Platform)addr->header.platform ) {
this->platform = (Platform)addr->header.platform;
this->osVersion = addr->header.osVersion;
}
else {
this->platform = (Platform)addr->header.altPlatform;
this->osVersion = addr->header.altOsVersion;;
}
}
else {
// for older caches, need to find and inspect libdyld.dylib
const char* libdyldPath = (proc.platform == Platform::driverKit) ? "/System/DriverKit/usr/lib/system/libdyld.dylib" : "/usr/lib/system/libdyld.dylib";
if ( const dyld3::MachOFile* libdyldMF = this->addr->getImageFromPath(libdyldPath) ) {
libdyldMF->forEachSupportedPlatform(^(Platform aPlatform, uint32_t minOS, uint32_t sdk) {
if ( aPlatform == proc.platform ) {
this->platform = aPlatform;
this->osVersion = minOS;
}
else if ( (aPlatform == Platform::iOSMac) && proc.catalystRuntime ) {
// support iPad apps running on Apple Silicon
this->platform = aPlatform;
this->osVersion = minOS;
}
});
}
else {
console("initializeCachePlatformOSVersion(): libdyld.dylib not found for OS version info\n");
}
}
}
void ProcessConfig::DyldCache::setupDyldCommPage(Process& proc, const Security& sec, SyscallDelegate& sys)
{
DyldCommPage cpFlags;
#if !TARGET_OS_SIMULATOR
// in launchd we compute the comm-page flags we want and set them for other processes to read
cpFlags.bootVolumeWritable = sys.bootVolumeWritable();
if ( const char* bootFlags = proc.appleParam("dyld_flags") ) {
// low 32-bits of comm page comes from dyld_flags boot-arg
*((uint32_t*)&cpFlags) = (uint32_t)hexToUInt64(bootFlags, nullptr);
if ( !sec.internalInstall ) {
cpFlags.forceCustomerCache = true;
cpFlags.testMode = false;
cpFlags.forceDevCache = false;
cpFlags.bootVolumeWritable = false;
}
}
#endif
#if TARGET_OS_OSX
// on macOS, three dylibs under libsystem are on disk but may need to be ignored
if ( this->addr != nullptr ) {
cpFlags.libKernelRoot = !this->uuidOfFileMatchesDyldCache(proc, sys, "/usr/lib/system/libsystem_kernel.dylib");
cpFlags.libPlatformRoot = !this->uuidOfFileMatchesDyldCache(proc, sys, "/usr/lib/system/libsystem_platform.dylib");
cpFlags.libPthreadRoot = !this->uuidOfFileMatchesDyldCache(proc, sys, "/usr/lib/system/libsystem_pthread.dylib");
}
#endif
sys.setDyldCommPageFlags(cpFlags);
proc.commPage = cpFlags;
}
bool ProcessConfig::DyldCache::indexOfPath(const char* dylibPath, uint32_t& dylibIndex) const
{
if ( this->addr == nullptr )
return false;
return this->addr->hasImagePath(dylibPath, dylibIndex);
}
void ProcessConfig::DyldCache::makeDataConstWritable(const Logging& lg, const SyscallDelegate& sys, bool writable) const
{
const uint32_t perms = (writable ? VM_PROT_WRITE | VM_PROT_READ | VM_PROT_COPY : VM_PROT_READ);
addr->forEachCache(^(const DyldSharedCache *cache, bool& stopCache) {
cache->forEachRegion(^(const void*, uint64_t vmAddr, uint64_t size, uint32_t initProt, uint32_t maxProt, uint64_t flags, bool& stopRegion) {
void* content = (void*)(vmAddr + slide);
if ( flags & DYLD_CACHE_MAPPING_CONST_DATA ) {
if ( lg.segments )
console("marking shared cache range 0x%x permissions: 0x%09lX -> 0x%09lX\n", perms, (long)content, (long)content + (long)size);
kern_return_t result = sys.vm_protect(mach_task_self(), (vm_address_t)content, (vm_size_t)size, false, perms);
if ( result != KERN_SUCCESS ) {
if ( lg.segments )
console("failed to mprotect shared cache due to: %d\n", result);
}
}
});
});
}
//
// MARK: --- PathOverrides methods ---
//
ProcessConfig::PathOverrides::PathOverrides(const Process& process, const Security& security, const Logging& log, const DyldCache& cache, SyscallDelegate& syscall)
{
// set fallback path mode
_fallbackPathMode = security.allowClassicFallbackPaths ? FallbackPathMode::classic : FallbackPathMode::restricted;
// process DYLD_* env variables if allowed
if ( security.allowEnvVarsPath ) {
char crashMsg[2048];
strlcpy(crashMsg, "dyld4 config: ", sizeof(crashMsg));
for (const char* const* p = process.envp; *p != nullptr; ++p) {
this->addEnvVar(process, security, *p, false, crashMsg);
}
if ( strlen(crashMsg) > 15 ) {
// if there is a crash, have DYLD_ env vars show up in crash log
CRSetCrashLogMessage(process.strdup(crashMsg));
}
}
// process LC_DYLD_ENVIRONMENT variables
process.mainExecutable->forDyldEnv(^(const char* keyEqualValue, bool& stop) {
this->addEnvVar(process, security, keyEqualValue, true, nullptr);
});
// process DYLD_VERSIONED_* env vars if allowed
if ( security.allowEnvVarsPath )
this->processVersionedPaths(process, syscall, cache, process.platform, *process.archs);
}
void ProcessConfig::PathOverrides::checkVersionedPath(const Process& proc, const char* path, SyscallDelegate& sys, const DyldCache& cache, Platform platform, const GradedArchs& archs)
{
static bool verbose = false;
if (verbose) console("checkVersionedPath(%s)\n", path);
uint32_t foundDylibVersion;
char foundDylibTargetOverridePath[PATH_MAX];
if ( sys.getDylibInfo(path, platform, archs, foundDylibVersion, foundDylibTargetOverridePath) ) {
if (verbose) console(" dylib vers=0x%08X (%s)\n", foundDylibVersion, path);
uint32_t targetDylibVersion;
uint32_t dylibIndex;
char targetInstallName[PATH_MAX];
if (verbose) console(" look for OS dylib at %s\n", foundDylibTargetOverridePath);
bool foundOSdylib = false;
if ( sys.getDylibInfo(foundDylibTargetOverridePath, platform, archs, targetDylibVersion, targetInstallName) ) {
foundOSdylib = true;
}
else if ( cache.indexOfPath(foundDylibTargetOverridePath, dylibIndex) ) {
uint64_t unusedMTime = 0;
uint64_t unusedINode = 0;
const MachOAnalyzer* cacheMA = (MachOAnalyzer*)cache.addr->getIndexedImageEntry(dylibIndex, unusedMTime, unusedINode);
const char* dylibInstallName;
uint32_t compatVersion;
if ( cacheMA->getDylibInstallName(&dylibInstallName, &compatVersion, &targetDylibVersion) ) {
strlcpy(targetInstallName, dylibInstallName, PATH_MAX);
foundOSdylib = true;
}
}
if ( foundOSdylib ) {
if (verbose) console(" os dylib vers=0x%08X (%s)\n", targetDylibVersion, foundDylibTargetOverridePath);
if ( foundDylibVersion > targetDylibVersion ) {
// check if there already is an override path
bool add = true;
for (DylibOverride* existing=_versionedOverrides; existing != nullptr; existing=existing->next) {
if ( strcmp(existing->installName, targetInstallName) == 0 ) {
add = false; // already have an entry, don't add another
uint32_t previousDylibVersion;
char previousInstallName[PATH_MAX];
if ( sys.getDylibInfo(existing->overridePath, platform, archs, previousDylibVersion, previousInstallName) ) {
// if already found an override and its version is greater that this one, don't add this one
if ( foundDylibVersion > previousDylibVersion ) {
existing->overridePath = proc.strdup(path);
if (verbose) console(" override: alter to %s with: %s\n", targetInstallName, path);
}
}
break;
}
}
if ( add ) {
//console(" override: %s with: %s\n", installName, overridePath);
addPathOverride(proc, targetInstallName, path);
}
}
}
else {
// <rdar://problem/53215116> DYLD_VERSIONED_LIBRARY_PATH fails to load a dylib if it does not also exist at the system install path
addPathOverride(proc, foundDylibTargetOverridePath, path);
}
}
}
void ProcessConfig::PathOverrides::addPathOverride(const Process& proc, const char* installName, const char* overridePath)
{
DylibOverride* newElement = (DylibOverride*)proc.roalloc(sizeof(DylibOverride));
newElement->next = nullptr;
newElement->installName = proc.strdup(installName);
newElement->overridePath = proc.strdup(overridePath);
// add to end of linked list
if ( _versionedOverrides != nullptr ) {
DylibOverride* last = _versionedOverrides;
while ( last->next != nullptr )
last = last->next;
last->next = newElement;
}
else {
_versionedOverrides = newElement;
}
}
void ProcessConfig::PathOverrides::processVersionedPaths(const Process& proc, SyscallDelegate& sys, const DyldCache& cache, Platform platform, const GradedArchs& archs)
{
// check DYLD_VERSIONED_LIBRARY_PATH for dylib overrides
if ( (_versionedDylibPathsEnv != nullptr) || (_versionedDylibPathExeLC != nullptr) ) {
forEachInColonList(_versionedDylibPathsEnv, _versionedDylibPathExeLC, ^(const char* searchDir, bool& stop) {
sys.forEachInDirectory(searchDir, false, ^(const char* pathInDir) {
this->checkVersionedPath(proc, pathInDir, sys, cache, platform, archs);
});
});
}
// check DYLD_VERSIONED_FRAMEWORK_PATH for framework overrides
if ( (_versionedFrameworkPathsEnv != nullptr) || (_versionedFrameworkPathExeLC != nullptr) ) {
forEachInColonList(_versionedFrameworkPathsEnv, _versionedFrameworkPathExeLC, ^(const char* searchDir, bool& stop) {
sys.forEachInDirectory(searchDir, true, ^(const char* pathInDir) {
// ignore paths that don't end in ".framework"
size_t pathInDirLen = strlen(pathInDir);
if ( (pathInDirLen < 10) || (strcmp(&pathInDir[pathInDirLen-10], ".framework") != 0) )
return;
// make ..path/Foo.framework/Foo
char possibleFramework[PATH_MAX];
strlcpy(possibleFramework, pathInDir, PATH_MAX);
strlcat(possibleFramework, strrchr(pathInDir, '/'), PATH_MAX);
*strrchr(possibleFramework, '.') = '\0';
this->checkVersionedPath(proc, possibleFramework, sys, cache, platform, archs);
});
});
}
}
void ProcessConfig::PathOverrides::forEachInsertedDylib(void (^handler)(const char* dylibPath, bool& stop)) const
{
if ( _insertedDylibs != nullptr && _insertedDylibs[0] != '\0' ) {
forEachInColonList(_insertedDylibs, nullptr, ^(const char* path, bool& stop) {
handler(path, stop);
});
}
}
void ProcessConfig::PathOverrides::handleEnvVar(const char* key, const char* value, void (^handler)(const char* envVar)) const
{
if ( value == nullptr )
return;
size_t allocSize = strlen(key) + strlen(value) + 2;
char buffer[allocSize];
strlcpy(buffer, key, allocSize);
strlcat(buffer, "=", allocSize);
strlcat(buffer, value, allocSize);
handler(buffer);
}
// Note, this method only returns variables set on the environment, not those from the load command
void ProcessConfig::PathOverrides::forEachEnvVar(void (^handler)(const char* envVar)) const
{
handleEnvVar("DYLD_LIBRARY_PATH", _dylibPathOverridesEnv, handler);
handleEnvVar("DYLD_FRAMEWORK_PATH", _frameworkPathOverridesEnv, handler);
handleEnvVar("DYLD_FALLBACK_FRAMEWORK_PATH", _frameworkPathFallbacksEnv, handler);
handleEnvVar("DYLD_FALLBACK_LIBRARY_PATH", _dylibPathFallbacksEnv, handler);
handleEnvVar("DYLD_VERSIONED_FRAMEWORK_PATH", _versionedFrameworkPathsEnv, handler);