-
Notifications
You must be signed in to change notification settings - Fork 88
Expand file tree
/
Copy pathLoader.cpp
More file actions
3513 lines (3268 loc) · 167 KB
/
Loader.cpp
File metadata and controls
3513 lines (3268 loc) · 167 KB
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>
#if !TARGET_OS_EXCLAVEKIT
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/errno.h>
#include <sys/mman.h>
#endif
#include <assert.h>
#include <mach-o/nlist.h>
#include "Defines.h"
#include "MachOAnalyzer.h"
#include "Loader.h"
#include "JustInTimeLoader.h"
#include "PrebuiltLoader.h"
#include "PremappedLoader.h"
#include "DyldRuntimeState.h"
#include "DyldProcessConfig.h"
#include "StringUtils.h"
#if BUILDING_DYLD && SUPPORT_ROSETTA
#include "RosettaSupport.h"
#endif
#include "Tracing.h"
#include "Utils.h"
#ifndef VM_PROT_TPRO
#define VM_PROT_TPRO 0x200
#endif
#if !TARGET_OS_EXCLAVEKIT
#if __has_include(<System/mach/dyld_pager.h>)
#include <System/mach/dyld_pager.h>
// this #define can be removed when rdar://92861504 is fixed
#ifndef MWL_MAX_REGION_COUNT
#define MWL_MAX_REGION_COUNT 5
#endif
#else
struct mwl_region {
int mwlr_fd; /* fd of file file to over map */
vm_prot_t mwlr_protections;/* protections for new overmapping */
off_t mwlr_file_offset;/* offset in file of start of mapping */
mach_vm_address_t mwlr_address; /* start address of existing region */
mach_vm_size_t mwlr_size; /* size of existing region */
};
#define MWL_INFO_VERS 7
struct mwl_info_hdr {
uint32_t mwli_version; /* version of info blob, currently 7 */
uint16_t mwli_page_size; /* 0x1000 or 0x4000 (for sanity checking) */
uint16_t mwli_pointer_format; /* DYLD_CHAINED_PTR_* value */
uint32_t mwli_binds_offset; /* offset within this blob of bind pointers table */
uint32_t mwli_binds_count; /* number of pointers in bind pointers table (for range checks) */
uint32_t mwli_chains_offset; /* offset within this blob of dyld_chained_starts_in_image */
uint32_t mwli_chains_size; /* size of dyld_chained_starts_in_image */
uint64_t mwli_slide; /* slide to add to rebased pointers */
uint64_t mwli_image_address; /* add this to rebase offsets includes any slide */
/* followed by the binds pointers and dyld_chained_starts_in_image */
};
#define MWL_MAX_REGION_COUNT 5
extern int __map_with_linking_np(const struct mwl_region regions[], uint32_t regionCount, const struct mwl_info_hdr* blob, uint32_t blobSize);
#endif
#endif // !TARGET_OS_EXCLAVEKIT
extern struct mach_header __dso_handle;
// If a root is used that overrides a dylib in the dyld cache, dyld patches all uses of the dylib in the cache
// to point to the new dylib. But if that dylib is missing some symbol, dyld will patch other clients to point
// to BAD_ROOT_ADDRESS instead. That will cause a crash and the crash will be easy to identify in crash logs.
#define BAD_ROOT_ADDRESS 0xbad4007
using dyld3::MachOAnalyzer;
using dyld3::MachOFile;
using dyld3::Platform;
namespace dyld4 {
Loader::InitialOptions::InitialOptions()
: inDyldCache(false)
, hasObjc(false)
, mayHavePlusLoad(false)
, roData(false)
, neverUnloaded(false)
, leaveMapped(false)
, roObjC(false)
, pre2022Binary(false)
, hasUUID(false)
, hasWeakDefs(false)
, belowLibSystem(false)
{
}
Loader::InitialOptions::InitialOptions(const Loader& other)
: inDyldCache(other.dylibInDyldCache)
, hasObjc(other.hasObjC)
, mayHavePlusLoad(other.mayHavePlusLoad)
, roData(other.hasReadOnlyData)
, neverUnloaded(other.neverUnload)
, leaveMapped(other.leaveMapped)
, roObjC(other.hasReadOnlyObjC)
, pre2022Binary(other.pre2022Binary)
, hasUUID(other.hasUUIDLoadCommand)
, hasWeakDefs(other.hasWeakDefs)
, hasTLVs(other.hasTLVs)
, belowLibSystem(other.belowLibSystem)
{
}
const char* Loader::path(const RuntimeState& state) const
{
assert(this->magic == kMagic);
#if SUPPORT_CREATING_PREMAPPEDLOADERS
assert(this->isPremapped);
return ((PremappedLoader*)this)->path(state);
#else
#if SUPPORT_PREBUILTLOADERS
if ( this->isPrebuilt )
return ((PrebuiltLoader*)this)->path(state);
else
#endif // SUPPORT_PREBUILTLOADERS
return ((JustInTimeLoader*)this)->path(state);
#endif // SUPPORT_CREATING_PREMAPPEDLOADERS
}
const char* Loader::installName(const RuntimeState& state) const
{
assert(this->magic == kMagic);
#if SUPPORT_CREATING_PREMAPPEDLOADERS
assert(this->isPremapped);
return ((PremappedLoader*)this)->installName(state);
#else
#if SUPPORT_PREBUILTLOADERS
if ( this->isPrebuilt )
return ((PrebuiltLoader*)this)->installName(state);
else
#endif // SUPPORT_PREBUILTLOADERS
return ((JustInTimeLoader*)this)->installName(state);
#endif // SUPPORT_CREATING_PREMAPPEDLOADERS
}
const MachOFile* Loader::mf(const RuntimeState& state) const
{
assert(this->magic == kMagic);
#if SUPPORT_CREATING_PREMAPPEDLOADERS
assert(this->isPremapped);
return ((PremappedLoader*)this)->mf(state);
#else
#if SUPPORT_PREBUILTLOADERS
if ( this->isPrebuilt )
return ((PrebuiltLoader*)this)->mf(state);
else
#endif // SUPPORT_PREBUILTLOADERS
return ((JustInTimeLoader*)this)->mf(state);
#endif // SUPPORT_CREATING_PREMAPPEDLOADERS
}
#if SUPPORT_VM_LAYOUT
const MachOLoaded* Loader::loadAddress(const RuntimeState& state) const
{
assert(this->magic == kMagic);
#if SUPPORT_CREATING_PREMAPPEDLOADERS
assert(this->isPremapped);
return ((PremappedLoader*)this)->loadAddress(state);
#else
#if SUPPORT_PREBUILTLOADERS
if ( this->isPrebuilt )
return ((PrebuiltLoader*)this)->loadAddress(state);
else
#endif // SUPPORT_PREBUILTLOADERS
return ((JustInTimeLoader*)this)->loadAddress(state);
#endif // SUPPORT_CREATING_PREMAPPEDLOADERS
}
#endif
#if SUPPORT_VM_LAYOUT
bool Loader::contains(RuntimeState& state, const void* addr, const void** segAddr, uint64_t* segSize, uint8_t* segPerms) const
{
assert(this->magic == kMagic);
#if SUPPORT_CREATING_PREMAPPEDLOADERS
assert(this->isPremapped);
return ((PremappedLoader*)this)->contains(state, addr, segAddr, segSize, segPerms);
#else
#if SUPPORT_PREBUILTLOADERS
if ( this->isPrebuilt )
return ((PrebuiltLoader*)this)->contains(state, addr, segAddr, segSize, segPerms);
else
#endif // SUPPORT_PREBUILTLOADERS
return ((JustInTimeLoader*)this)->contains(state, addr, segAddr, segSize, segPerms);
#endif // SUPPORT_CREATING_PREMAPPEDLOADERS
}
#endif
bool Loader::matchesPath(const RuntimeState& state, const char* path) const
{
assert(this->magic == kMagic);
#if SUPPORT_CREATING_PREMAPPEDLOADERS
assert(this->isPremapped);
return ((PremappedLoader*)this)->matchesPath(state, path);
#else
#if SUPPORT_PREBUILTLOADERS
if ( this->isPrebuilt )
return ((PrebuiltLoader*)this)->matchesPath(state, path);
else
#endif // SUPPORT_PREBUILTLOADERS
return ((JustInTimeLoader*)this)->matchesPath(state, path);
#endif // SUPPORT_CREATING_PREMAPPEDLOADERS
}
#if !SUPPORT_CREATING_PREMAPPEDLOADERS
FileID Loader::fileID(const RuntimeState& state) const
{
assert(this->magic == kMagic);
#if SUPPORT_PREBUILTLOADERS
if ( this->isPrebuilt )
return ((PrebuiltLoader*)this)->fileID(state);
else
#endif // SUPPORT_PREBUILTLOADERS
return ((JustInTimeLoader*)this)->fileID(state);
}
#endif // !SUPPORT_CREATING_PREMAPPEDLOADERS
uint32_t Loader::dependentCount() const
{
assert(this->magic == kMagic);
#if SUPPORT_CREATING_PREMAPPEDLOADERS
assert(this->isPremapped);
return ((PremappedLoader*)this)->dependentCount();
#else
#if SUPPORT_PREBUILTLOADERS
if ( this->isPrebuilt )
return ((PrebuiltLoader*)this)->dependentCount();
else
#endif // SUPPORT_PREBUILTLOADERS
return ((JustInTimeLoader*)this)->dependentCount();
#endif // SUPPORT_CREATING_PREMAPPEDLOADERS
}
Loader* Loader::dependent(const RuntimeState& state, uint32_t depIndex, LinkedDylibAttributes* depAttr) const
{
assert(this->magic == kMagic);
#if SUPPORT_CREATING_PREMAPPEDLOADERS
assert(this->isPremapped);
return ((PremappedLoader*)this)->dependent(state, depIndex, depAttr);
#else
#if SUPPORT_PREBUILTLOADERS
if ( this->isPrebuilt )
return ((PrebuiltLoader*)this)->dependent(state, depIndex, depAttr);
else
#endif // SUPPORT_PREBUILTLOADERS
return ((JustInTimeLoader*)this)->dependent(state, depIndex, depAttr);
#endif // SUPPORT_CREATING_PREMAPPEDLOADERS
}
void Loader::loadDependents(Diagnostics& diag, RuntimeState& state, const LoadOptions& options)
{
assert(this->magic == kMagic);
#if SUPPORT_CREATING_PREMAPPEDLOADERS
assert(this->isPremapped);
return ((PremappedLoader*)this)->loadDependents(diag, state, options);
#else
#if SUPPORT_PREBUILTLOADERS
if ( this->isPrebuilt )
return ((PrebuiltLoader*)this)->loadDependents(diag, state, options);
else
#endif // SUPPORT_PREBUILTLOADERS
return ((JustInTimeLoader*)this)->loadDependents(diag, state, options);
#endif // SUPPORT_CREATING_PREMAPPEDLOADERS
}
bool Loader::getExportsTrie(uint64_t& runtimeOffset, uint32_t& size) const
{
assert(this->magic == kMagic);
#if SUPPORT_CREATING_PREMAPPEDLOADERS
assert(this->isPremapped);
return ((PremappedLoader*)this)->getExportsTrie(runtimeOffset, size);
#else
#if SUPPORT_PREBUILTLOADERS
if ( this->isPrebuilt )
return ((PrebuiltLoader*)this)->getExportsTrie(runtimeOffset, size);
else
#endif // SUPPORT_PREBUILTLOADERS
return ((JustInTimeLoader*)this)->getExportsTrie(runtimeOffset, size);
#endif // SUPPORT_CREATING_PREMAPPEDLOADERS
}
bool Loader::hiddenFromFlat(bool forceGlobal) const
{
assert(this->magic == kMagic);
#if SUPPORT_CREATING_PREMAPPEDLOADERS
assert(this->isPremapped);
return ((PremappedLoader*)this)->hiddenFromFlat(forceGlobal);
#else
#if SUPPORT_PREBUILTLOADERS
if ( this->isPrebuilt )
return ((PrebuiltLoader*)this)->hiddenFromFlat(forceGlobal);
else
#endif // SUPPORT_PREBUILTLOADERS
return ((JustInTimeLoader*)this)->hiddenFromFlat(forceGlobal);
#endif // SUPPORT_CREATING_PREMAPPEDLOADERS
}
#if !SUPPORT_CREATING_PREMAPPEDLOADERS
bool Loader::representsCachedDylibIndex(uint16_t dylibIndex) const
{
assert(this->magic == kMagic);
#if SUPPORT_PREBUILTLOADERS
if ( this->isPrebuilt )
return ((PrebuiltLoader*)this)->representsCachedDylibIndex(dylibIndex);
else
#endif // SUPPORT_PREBUILTLOADERS
return ((JustInTimeLoader*)this)->representsCachedDylibIndex(dylibIndex);
}
bool Loader::overridesDylibInCache(const DylibPatch*& patchTable, uint16_t& cacheDylibOverriddenIndex) const
{
assert(this->magic == kMagic);
#if SUPPORT_PREBUILTLOADERS
if ( this->isPrebuilt )
return ((PrebuiltLoader*)this)->overridesDylibInCache(patchTable, cacheDylibOverriddenIndex);
else
#endif // SUPPORT_PREBUILTLOADERS
return ((JustInTimeLoader*)this)->overridesDylibInCache(patchTable, cacheDylibOverriddenIndex);
}
#endif // !SUPPORT_CREATING_PREMAPPEDLOADERS
#if BUILDING_DYLD || BUILDING_UNIT_TESTS
void Loader::applyFixups(Diagnostics& diag, RuntimeState& state, DyldCacheDataConstLazyScopedWriter& dataConst, bool allowLazyBinds,
lsl::Vector<PseudoDylibSymbolToMaterialize>* materializingSymbols) const
{
assert(this->magic == kMagic);
#if SUPPORT_CREATING_PREMAPPEDLOADERS
assert(this->isPremapped);
((PremappedLoader*)this)->applyFixups(diag, state, dataConst, allowLazyBinds, materializingSymbols);
#else
#if SUPPORT_PREBUILTLOADERS
if ( this->isPrebuilt )
((PrebuiltLoader*)this)->applyFixups(diag, state, dataConst, allowLazyBinds, materializingSymbols);
else
#endif // SUPPORT_PREBUILTLOADERS
((JustInTimeLoader*)this)->applyFixups(diag, state, dataConst, allowLazyBinds, materializingSymbols);
#endif // SUPPORT_CREATING_PREMAPPEDLOADERS
}
#endif // BUILDING_DYLD || BUILDING_UNIT_TESTS
void Loader::withLayout(Diagnostics &diag, RuntimeState& state, void (^callback)(const mach_o::Layout &layout)) const
{
assert(this->magic == kMagic);
#if SUPPORT_CREATING_PREMAPPEDLOADERS
assert(this->isPremapped);
((PremappedLoader*)this)->withLayout(diag, state, callback);
#else
#if SUPPORT_PREBUILTLOADERS
if ( this->isPrebuilt )
return ((PrebuiltLoader*)this)->withLayout(diag, state, callback);
else
#endif // SUPPORT_PREBUILTLOADERS
return ((JustInTimeLoader*)this)->withLayout(diag, state, callback);
#endif // SUPPORT_CREATING_PREMAPPEDLOADERS
}
bool Loader::dyldDoesObjCFixups() const
{
assert(this->magic == kMagic);
#if SUPPORT_CREATING_PREMAPPEDLOADERS
assert(this->isPremapped);
return ((PremappedLoader*)this)->dyldDoesObjCFixups();
#else
#if SUPPORT_PREBUILTLOADERS
if ( this->isPrebuilt )
return ((PrebuiltLoader*)this)->dyldDoesObjCFixups();
else
#endif // SUPPORT_PREBUILTLOADERS
return ((JustInTimeLoader*)this)->dyldDoesObjCFixups();
#endif // SUPPORT_CREATING_PREMAPPEDLOADERS
}
const SectionLocations* Loader::getSectionLocations() const
{
assert(this->magic == kMagic);
#if SUPPORT_PREBUILTLOADERS
if ( this->isPrebuilt )
return ((PrebuiltLoader*)this)->getSectionLocations();
else
#endif // SUPPORT_PREBUILTLOADERS
return ((JustInTimeLoader*)this)->getSectionLocations();
}
#if SUPPORT_IMAGE_UNLOADING
void Loader::unmap(RuntimeState& state, bool force) const
{
assert(this->magic == kMagic);
#if SUPPORT_PREBUILTLOADERS
if ( this->isPrebuilt )
return ((PrebuiltLoader*)this)->unmap(state, force);
else
#endif // SUPPORT_PREBUILTLOADERS
return ((JustInTimeLoader*)this)->unmap(state, force);
}
#endif
bool Loader::hasBeenFixedUp(RuntimeState& state) const
{
assert(this->magic == kMagic);
#if SUPPORT_CREATING_PREMAPPEDLOADERS
assert(this->isPremapped);
return ((PremappedLoader*)this)->hasBeenFixedUp(state);
#else
#if SUPPORT_PREBUILTLOADERS
if ( this->isPrebuilt )
return ((PrebuiltLoader*)this)->hasBeenFixedUp(state);
else
#endif // SUPPORT_PREBUILTLOADERS
return ((JustInTimeLoader*)this)->hasBeenFixedUp(state);
#endif // SUPPORT_CREATING_PREMAPPEDLOADERS
}
bool Loader::beginInitializers(RuntimeState& state)
{
assert(this->magic == kMagic);
#if SUPPORT_CREATING_PREMAPPEDLOADERS
assert(this->isPremapped);
return ((PremappedLoader*)this)->beginInitializers(state);
#else
#if SUPPORT_PREBUILTLOADERS
if ( this->isPrebuilt )
return ((PrebuiltLoader*)this)->beginInitializers(state);
else
#endif // SUPPORT_PREBUILTLOADERS
return ((JustInTimeLoader*)this)->beginInitializers(state);
#endif // SUPPORT_CREATING_PREMAPPEDLOADERS
}
#if BUILDING_DYLD || BUILDING_UNIT_TESTS
void Loader::runInitializers(RuntimeState& state) const
{
assert(this->magic == kMagic);
#if SUPPORT_CREATING_PREMAPPEDLOADERS
assert(this->isPremapped);
((PremappedLoader*)this)->runInitializers(state);
#else
#if SUPPORT_PREBUILTLOADERS
if ( this->isPrebuilt )
((PrebuiltLoader*)this)->runInitializers(state);
else
#endif // SUPPORT_PREBUILTLOADERS
((JustInTimeLoader*)this)->runInitializers(state);
#endif // SUPPORT_CREATING_PREMAPPEDLOADERS
}
#endif
bool Loader::isDelayInit(RuntimeState& state) const
{
assert(this->magic == kMagic);
#if SUPPORT_CREATING_PREMAPPEDLOADERS
assert(this->isPremapped);
return false;
#else
#if SUPPORT_PREBUILTLOADERS
if ( this->isPrebuilt )
return ((PrebuiltLoader*)this)->isDelayInit(state);
else
#endif // SUPPORT_PREBUILTLOADERS
return ((JustInTimeLoader*)this)->isDelayInit(state);
#endif
}
void Loader::setDelayInit(RuntimeState& state, bool value) const
{
assert(this->magic == kMagic);
#if SUPPORT_CREATING_PREMAPPEDLOADERS
assert(this->isPremapped);
// do nothing, delay-init not supported in exclaveKit
#else
#if SUPPORT_PREBUILTLOADERS
if ( this->isPrebuilt )
((PrebuiltLoader*)this)->setDelayInit(state, value);
else
#endif // SUPPORT_PREBUILTLOADERS
((JustInTimeLoader*)this)->setDelayInit(state, value);
#endif
}
const PrebuiltLoader* Loader::LoaderRef::loader(const RuntimeState& state) const
{
if ( this->app )
return state.processPrebuiltLoaderSet()->atIndex(this->index);
else
return state.cachedDylibsPrebuiltLoaderSet()->atIndex(this->index);
}
const char* Loader::leafName(const char* path)
{
if ( const char* lastSlash = strrchr(path, '/') )
return lastSlash + 1;
else
return path;
}
const char* Loader::leafName(const RuntimeState& state) const
{
return leafName(path(state));
}
#if SUPPORT_VM_LAYOUT
const MachOAnalyzer* Loader::analyzer(RuntimeState& state) const
{
return (MachOAnalyzer*)loadAddress(state);
}
#endif
bool Loader::hasMagic() const
{
return (this->magic == kMagic);
}
void Loader::appendHexNibble(uint8_t value, char*& p)
{
if ( value < 10 )
*p++ = '0' + value;
else
*p++ = 'A' + value - 10;
}
void Loader::appendHexByte(uint8_t value, char*& p)
{
value &= 0xFF;
appendHexNibble(value >> 4, p);
appendHexNibble(value & 0x0F, p);
}
void Loader::uuidToStr(const uuid_t uuid, char uuidStr[64])
{
char* p = uuidStr;
appendHexByte(uuid[0], p);
appendHexByte(uuid[1], p);
appendHexByte(uuid[2], p);
appendHexByte(uuid[3], p);
*p++ = '-';
appendHexByte(uuid[4], p);
appendHexByte(uuid[5], p);
*p++ = '-';
appendHexByte(uuid[6], p);
appendHexByte(uuid[7], p);
*p++ = '-';
appendHexByte(uuid[8], p);
appendHexByte(uuid[9], p);
*p++ = '-';
appendHexByte(uuid[10], p);
appendHexByte(uuid[11], p);
appendHexByte(uuid[12], p);
appendHexByte(uuid[13], p);
appendHexByte(uuid[14], p);
appendHexByte(uuid[15], p);
*p = '\0';
}
void Loader::getUuidStr(char uuidStr[64]) const
{
if ( this->hasUUIDLoadCommand) {
uuidToStr(uuid, uuidStr);
}
else {
strlcpy(uuidStr, "no uuid", 64);
}
}
void Loader::logLoad(RuntimeState& state, const char* path) const
{
char uuidStr[64];
this->getUuidStr(uuidStr);
state.log("<%s> %s\n", uuidStr, path);
}
#if TARGET_OS_EXCLAVEKIT
const Loader* Loader::makePremappedLoader(Diagnostics& diag, RuntimeState& state, const char* path, const LoadOptions& options, const mach_o::Layout* layout)
{
return PremappedLoader::makePremappedLoader(diag, state, path, options, layout);
}
#endif // !TARGET_OS_EXCLAVEKIT
#if !TARGET_OS_EXCLAVEKIT
const Loader* Loader::makeDiskLoader(Diagnostics& diag, RuntimeState& state, const char* path, const LoadOptions& options,
bool overridesDyldCache, uint32_t dylibIndex,
const mach_o::Layout* layout)
{
// never create a new loader in RTLD_NOLOAD mode
if ( options.rtldNoLoad )
return nullptr;
// don't use PrebuiltLoaders for simulator because the paths will be wrong (missing SIMROOT prefix)
#if SUPPORT_PREBUILTLOADERS
// first check for a PrebuiltLoader
const Loader* result = (Loader*)state.findPrebuiltLoader(path);
if ( result != nullptr )
return result;
#endif // SUPPORT_PREBUILTLOADERS
// The dylibIndex for a catalyst root might be wrong. This can happen if the dylib is found via its macOS path (ie from a zippered dylib)
// but getLoader() found the root in the /System/iOSSupport path
// In this case, we want to rewrite the dylib index to be to the catalyst unzippered twin, not the macOS one
if ( overridesDyldCache && state.config.process.catalystRuntime ) {
uint32_t dylibInCacheIndex;
if ( state.config.dyldCache.indexOfPath(path, dylibInCacheIndex) )
dylibIndex = dylibInCacheIndex;
}
// try building a JustInTime Loader
return JustInTimeLoader::makeJustInTimeLoaderDisk(diag, state, path, options, overridesDyldCache, dylibIndex, layout);
}
const Loader* Loader::makeDyldCacheLoader(Diagnostics& diag, RuntimeState& state, const char* path, const LoadOptions& options, uint32_t dylibIndex,
const mach_o::Layout* layout)
{
// never create a new loader in RTLD_NOLOAD mode
if ( options.rtldNoLoad )
return nullptr;
#if SUPPORT_PREBUILTLOADERS
// first check for a PrebuiltLoader with compatible platform
// rdar://76406035 (simulator cache paths need prefix)
const PrebuiltLoader* result = state.findPrebuiltLoader(path);
if ( result != nullptr ) {
if ( result->mf(state)->loadableIntoProcess(state.config.process.platform, path, state.config.security.isInternalOS) ) {
return result;
}
}
#endif // SUPPORT_PREBUILTLOADERS
// try building a JustInTime Loader
return JustInTimeLoader::makeJustInTimeLoaderDyldCache(diag, state, path, options, dylibIndex, layout);
}
const Loader* Loader::makePseudoDylibLoader(Diagnostics& diag, RuntimeState &state, const char* path, const LoadOptions& options, const PseudoDylib* pd) {
return JustInTimeLoader::makePseudoDylibLoader(diag, state, path, options, pd);
}
static bool isFileRelativePath(const char* path)
{
if ( path[0] == '/' )
return false;
if ( (path[0] == '.') && (path[1] == '/') )
return true;
if ( (path[0] == '.') && (path[1] == '.') && (path[2] == '/') )
return true;
return (path[0] != '@');
}
static bool mightBeInSharedCache(const char* dylibName) {
return ( (strncmp(dylibName, "/usr/lib/", 9) == 0)
|| (strncmp(dylibName, "/System/Library/", 16) == 0)
|| (strncmp(dylibName, "/System/iOSSupport/usr/lib/", 27) == 0)
|| (strncmp(dylibName, "/System/iOSSupport/System/Library/", 34) == 0)
|| (strncmp(dylibName, "/System/DriverKit/", 18) == 0) );
}
// This composes DyldProcessConfig::forEachPathVariant() with Loader::forEachResolvedAtPathVar()
// They are separate layers because DyldProcessConfig handles DYLD_ env vars and Loader handle @ paths
void Loader::forEachPath(Diagnostics& diag, RuntimeState& state, const char* loadPath, const LoadOptions& options,
void (^handler)(const char* possiblePath, ProcessConfig::PathOverrides::Type type, bool&))
{
__block bool stop = false;
const ProcessConfig::PathOverrides& po = state.config.pathOverrides;
// <rdar://5951327> (DYLD_FALLBACK_LIBRARY_PATH should only apply to dlopen() of leaf names)
bool skipFallbacks = !options.staticLinkage && (strchr(loadPath, '/') != nullptr) && (state.config.pathOverrides.getFrameworkPartialPath(loadPath) == nullptr);
po.forEachPathVariant(loadPath, state.config.process.platform, options.requestorNeedsFallbacks, skipFallbacks, stop,
^(const char* possibleVariantPath, ProcessConfig::PathOverrides::Type type, bool&) {
#if !TARGET_OS_EXCLAVEKIT
// relative name to dlopen() has special behavior
if ( !options.staticLinkage && (type == ProcessConfig::PathOverrides::Type::rawPath) && (loadPath[0] != '/') ) {
// if relative path, turn into implicit @rpath
if ( (loadPath[0] != '@') ) {
char implicitRPath[PATH_MAX];
strlcpy(implicitRPath, "@rpath/", sizeof(implicitRPath));
strlcat(implicitRPath, possibleVariantPath, sizeof(implicitRPath));
Loader::forEachResolvedAtPathVar(state, implicitRPath, options, ProcessConfig::PathOverrides::Type::implictRpathExpansion, stop, handler);
if ( stop )
return;
// <rdar://47682983> always look in /usr/lib for leaf names
char implicitPath[PATH_MAX];
strlcpy(implicitPath, "/usr/lib/", sizeof(implicitRPath));
strlcat(implicitPath, loadPath, sizeof(implicitPath));
handler(implicitPath, ProcessConfig::PathOverrides::Type::standardFallback, stop);
if ( stop )
return;
// only try cwd relative if afmi allows
if ( state.config.security.allowAtPaths ) {
handler(loadPath, type, stop);
}
// don't try anything else for dlopen of non-absolute paths
return;
}
}
// expand @ paths
Loader::forEachResolvedAtPathVar(state, possibleVariantPath, options, type, stop, handler);
#else
handler(possibleVariantPath, type, stop);
#endif // !TARGET_OS_EXCLAVEKIT
});
}
#endif // !TARGET_OS_EXCLAVEKIT
//
// Use PathOverrides class to walk possible paths, for each, look on disk, then in cache.
// Special case customer caches to look in cache first, to avoid stat() when result will be disgarded.
// For dylibs loaded from disk, we need to know if they override something in the cache in order to patch it in.
// It is considered an override if the initial path or path found is in the dyld cache
//
const Loader* Loader::getLoader(Diagnostics& diag, RuntimeState& state, const char* loadPath, const LoadOptions& options)
{
#if TARGET_OS_EXCLAVEKIT
__block const Loader* result = nullptr;
// check if this path already in use by a Loader
for ( const Loader* ldr : state.loaded ) {
if ( !ldr->matchesPath(state, loadPath) )
continue;
result = ldr;
if ( state.config.log.searching )
state.log(" found: already-loaded-by-path: \"%s\"\n", loadPath);
}
if ( result == nullptr )
result = makePremappedLoader(diag, state, loadPath, options, nullptr);
if ( (result == nullptr) && options.canBeMissing ) {
diag.clearError();
}
return result;
#else
__block const Loader* result = nullptr;
const DyldSharedCache* cache = state.config.dyldCache.addr;
const bool customerCache = (cache != nullptr) && !state.config.dyldCache.development;
if ( state.config.log.searching )
state.log("find path \"%s\"\n", loadPath);
const bool loadPathIsRPath = (::strncmp(loadPath, "@rpath/", 7) == 0);
const bool loadPathIsFileRelativePath = isFileRelativePath(loadPath);
// for @rpath paths, first check if already loaded as rpath
if ( loadPathIsRPath ) {
for (const Vector<ConstAuthLoader>* list : { &state.loaded, &state.delayLoaded } ) {
for ( const Loader* ldr : *list ) {
if ( ldr->matchesPath(state, loadPath) ) {
if ( state.config.log.searching )
state.log(" found: already-loaded-by-rpath: %s\n", ldr->path(state));
return ldr;
}
}
}
}
else if ( !options.staticLinkage && (loadPath[0] != '@') && (loadPath[0] != '/') && (strchr(loadPath, '/') == nullptr) ) {
// handle dlopen("xxx") to mean "@rpath/xxx" when it is already loaded
char implicitRPath[strlen(loadPath)+8];
strlcpy(implicitRPath, "@rpath/", sizeof(implicitRPath));
strlcat(implicitRPath, loadPath, sizeof(implicitRPath));
for (const Vector<ConstAuthLoader>* list : { &state.loaded, &state.delayLoaded } ) {
for ( const Loader* ldr : *list ) {
if ( ldr->matchesPath(state, implicitRPath) ) {
if ( state.config.log.searching )
state.log(" found: already-loaded-by-rpath: %s\n", ldr->path(state));
return ldr;
}
}
}
}
// canonicalize shared cache paths
if ( const char* canonicalPathInCache = state.config.canonicalDylibPathInCache(loadPath) ) {
if ( strcmp(canonicalPathInCache, loadPath) != 0 ) {
loadPath = canonicalPathInCache;
if ( state.config.log.searching )
state.log(" switch to canonical cache path: %s\n", loadPath);
}
}
// get info about original path
__block uint32_t dylibInCacheIndex;
const bool originalPathIsInDyldCache = state.config.dyldCache.indexOfPath(loadPath, dylibInCacheIndex);
#if BUILDING_DYLD && TARGET_OS_OSX
// On macOS, we need to support unzippered twins, which look like roots. So if the original path is in the cache, it may
// still be overridable by an unzippered twin which is also in the cache
const bool originalPathIsOverridableInDyldCache = originalPathIsInDyldCache;
#else
const bool originalPathIsOverridableInDyldCache = originalPathIsInDyldCache && state.config.dyldCache.isOverridablePath(loadPath);
#endif
// search all locations
Loader::forEachPath(diag, state, loadPath, options,
^(const char* possiblePath, ProcessConfig::PathOverrides::Type type, bool& stop) {
// On customer dyld caches, if loaded a path in cache, don't look for overrides
if ( customerCache && originalPathIsInDyldCache && !originalPathIsOverridableInDyldCache && (possiblePath != loadPath) )
return;
if ( state.config.log.searching )
state.log(" possible path(%s): \"%s\"\n", ProcessConfig::PathOverrides::typeName(type), possiblePath);
// check if this path already in use by a Loader
for (const Vector<ConstAuthLoader>* list : { &state.loaded, &state.delayLoaded } ) {
if ( options.rtldNoLoad && (list == &state.delayLoaded) )
continue;
for ( const Loader* ldr : *list ) {
if ( ldr->matchesPath(state, possiblePath) ) {
result = ldr;
stop = true;
diag.clearError(); // found dylib, so clear any errors from previous paths tried
if ( state.config.log.searching )
state.log(" found: already-loaded-by-path: \"%s\"\n", possiblePath);
return;
}
}
}
// <rdar://problem/47682983> don't allow file system relative paths in hardened programs
// (type == ProcessConfig::PathOverrides::Type::implictRpathExpansion)
if ( !state.config.security.allowEnvVarsPath && isFileRelativePath(possiblePath) ) {
if ( diag.noError() )
diag.error("tried: '%s' (relative path not allowed in hardened program)", possiblePath);
else
diag.appendError(", '%s' (relative path not allowed in hardened program)", possiblePath);
return;
}
// check dyld cache trie to see if this is an alias to a cached dylib
uint32_t possibleCacheIndex;
if ( state.config.dyldCache.indexOfPath(possiblePath, possibleCacheIndex) ) {
for (const Vector<ConstAuthLoader>* list : { &state.loaded, &state.delayLoaded } ) {
if ( options.rtldNoLoad && (list == &state.delayLoaded) )
continue;
for ( const Loader* ldr : *list ) {
if ( ldr->representsCachedDylibIndex(possibleCacheIndex) ) {
result = ldr;
stop = true;
diag.clearError(); // found dylib, so clear any errors from previous paths tried
if ( state.config.log.searching )
state.log(" found: already-loaded-by-dylib-index: \"%s\" -> %s\n", possiblePath, ldr->path(state));
return;
}
}
}
}
// RTLD_NOLOAD used and this possible path not already in use, so skip to next
if ( options.rtldNoLoad ) {
return;
}
// Check for PseduoDylibs
if (!state.pseudoDylibs.empty()) {
// FIXME: Should all of this be in its own function?
if ( state.config.log.searching )
state.log("searching %llu pseudo-dylibs:\n", state.pseudoDylibs.size());
for (auto &pd : state.pseudoDylibs) {
if (auto *canonicalPath = pd->loadableAtPath(possiblePath)) {
if ( state.config.log.searching )
state.log(" found: pseduo-dylib: \"%s\"\n", possiblePath);
Diagnostics possiblePathDiag;
result = makePseudoDylibLoader(possiblePathDiag, state, canonicalPath, options, &*pd);
// Dispose of canonicalPath if it is different from possiblePath
// (loadableAtPath is allowed to return its argument, which should not be freed).
if (canonicalPath != possiblePath)
pd->disposeString(canonicalPath);
if ( possiblePathDiag.hasError() ) {
// Report error if pseudo-dylib failed to load.
if ( diag.noError() )
diag.error("tried: '%s' (%s)", possiblePath, possiblePathDiag.errorMessageCStr());
else
diag.appendError(", '%s' (%s)", possiblePath, possiblePathDiag.errorMessageCStr());
if ( state.config.log.searching )
state.log(" found: pseudo-dylib-error: \"%s\" => \"%s\"\n", possiblePath, possiblePathDiag.errorMessageCStr());
}
if (result) {
diag.clearError();
stop = true;
return;
}
}
}
if ( state.config.log.searching && !result)
state.log(" no pseudo-dylibs matched\n");
}
// see if this path is on disk or in dyld cache
int possiblePathOnDiskErrNo = 0;
bool possiblePathHasFileOnDisk = false;
bool possiblePathIsInDyldCache = false;
bool possiblePathOverridesCache = false;
FileID possiblePathFileID = FileID::none();
if ( customerCache ) {
// for customer cache, check cache first and only stat() if overridable
if ( !ProcessConfig::PathOverrides::isOnDiskOnlyType(type) )
possiblePathIsInDyldCache = state.config.dyldCache.indexOfPath(possiblePath, dylibInCacheIndex);
if ( possiblePathIsInDyldCache ) {
if ( state.config.dyldCache.isOverridablePath(possiblePath) ) {
// see if there is a root installed that overrides one of few overridable dylibs in the cache
possiblePathHasFileOnDisk = state.config.fileExists(possiblePath, &possiblePathFileID, &possiblePathOnDiskErrNo);
possiblePathOverridesCache = possiblePathHasFileOnDisk;
}
}
else {
possiblePathHasFileOnDisk = state.config.fileExists(possiblePath, &possiblePathFileID, &possiblePathOnDiskErrNo);
possiblePathOverridesCache = possiblePathHasFileOnDisk && originalPathIsOverridableInDyldCache;
}
}
else {
// for dev caches, always stat() and check cache
possiblePathHasFileOnDisk = state.config.fileExists(possiblePath, &possiblePathFileID, &possiblePathOnDiskErrNo);
if ( !ProcessConfig::PathOverrides::isOnDiskOnlyType(type) )
possiblePathIsInDyldCache = state.config.dyldCache.indexOfPath(possiblePath, dylibInCacheIndex);
possiblePathOverridesCache = possiblePathHasFileOnDisk && (originalPathIsInDyldCache || possiblePathIsInDyldCache);
}
// see if this possible path was already loaded via a symlink or hardlink by checking inode
if ( possiblePathHasFileOnDisk && possiblePathFileID.valid() ) {
for (const Vector<ConstAuthLoader>* list : { &state.loaded, &state.delayLoaded } ) {
if ( options.rtldNoLoad && (list == &state.delayLoaded) )
continue;
for ( const Loader* ldr : *list ) {
FileID ldrFileID = ldr->fileID(state);
if ( ldrFileID.valid() && (possiblePathFileID == ldrFileID) ) {
result = ldr;
stop = true;
diag.clearError(); // found dylib, so clear any errors from previous paths tried
if ( state.config.log.searching )
state.log(" found: already-loaded-by-inode-mtime: \"%s\"\n", ldr->path(state));
return;
}
}
}
}
#if TARGET_OS_SIMULATOR
// rdar://76406035 (load simulator dylibs from cache)
if ( (state.config.dyldCache.addr != nullptr) && state.config.dyldCache.addr->header.dylibsExpectedOnDisk ) {
if ( const char* simRoot = state.config.pathOverrides.simRootPath() ) {
size_t simRootLen = strlen(simRoot);
// compare inode/mtime of dylib now vs when cache was built
const char* possiblePathInSimDyldCache = nullptr;
if ( strncmp(possiblePath, simRoot, simRootLen) == 0 ) {
// looks like a dylib in the sim Runtime root, see if partial path is in the dyld cache
possiblePathInSimDyldCache = &possiblePath[simRootLen];
}
else if ( strncmp(possiblePath, "/usr/lib/system/", 16) == 0 ) {
// could be one of the magic host dylibs that got incorporated into the dyld cache
possiblePathInSimDyldCache = possiblePath;
}
if ( possiblePathInSimDyldCache != nullptr ) {
if ( state.config.dyldCache.indexOfPath(possiblePathInSimDyldCache, dylibInCacheIndex) ) {
uint64_t expectedMTime;
uint64_t expectedInode;
state.config.dyldCache.addr->getIndexedImageEntry(dylibInCacheIndex, expectedMTime, expectedInode);
FileID expectedID(expectedInode, state.config.process.dyldSimFSID, expectedMTime, true);
if ( possiblePathFileID == expectedID ) {
// inode/mtime matches when sim dyld cache was built, so use dylib from dyld cache and ignore file on disk
possiblePathHasFileOnDisk = false;
possiblePathIsInDyldCache = true;
}
}
}
}
}
#endif
// if possiblePath not a file and not in dyld cache, skip to next possible path
if ( !possiblePathHasFileOnDisk && !possiblePathIsInDyldCache ) {
if ( options.pathNotFoundHandler && !ProcessConfig::PathOverrides::isOnDiskOnlyType(type) )
options.pathNotFoundHandler(possiblePath);
// append each path tried to diag