-
Notifications
You must be signed in to change notification settings - Fork 5
/
Output.m
1298 lines (980 loc) · 33.7 KB
/
Output.m
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
#define IMPOSTOR_OBJC_TEMP "dsce.objc"
#define IMPOSTOR_OBJC_OLD "dsce.objc.old"
#define IMPOSTOR_GOT "dsce.got"
#define IMPOSTOR_PAD "dsce.pad"
#define IMPORT_HACK_OFFSET 0x1000000000
// TODO: broken currently
#define HEADER_EXTRA 0 // 0x1000
// https://en.wikipedia.org/wiki/LEB128
NSData* ulebWithLong(long value)
{
NSMutableData* output=NSMutableData.alloc.init;
do
{
char byte=value&0x7f;
value>>=7;
if(value)
{
byte|=0x80;
}
[output appendBytes:&byte length:1];
}
while(value);
return output;
}
long align(long address,int amount,BOOL ceil,int* deltaOut)
{
long newAddress=address/amount*amount;
if(ceil&&newAddress!=address)
{
newAddress+=amount;
}
if(deltaOut)
{
*deltaOut=newAddress-address;
}
return newAddress;
}
BOOL isAligned(long address,int amount)
{
return align(address,amount,false,NULL)==address;
}
@implementation Output
+(void)runWithCache:(CacheSet*)cache image:(CacheImage*)image outPath:(NSString*)outPath
{
Output* output=[Output.alloc initWithCache:cache image:image].autorelease;
[output extractWithPath:outPath];
}
-(instancetype)initWithCache:(CacheSet*)cache image:(CacheImage*)image
{
self=super.init;
assert(cache);
self.cache=cache;
assert(image);
self.cacheImage=image;
return self;
}
-(void)extractWithPath:(NSString*)outPath
{
assert(!self.header);
self.stepImportHeader;
self.stepImportSegmentsExceptLinkedit;
self.stepImportRebases;
self.stepImportExports;
self.stepFixImageInfo;
self.stepFindEmbeddedSels;
self.stepFixSelRefs;
self.stepFixClasses;
self.stepFixCats;
self.stepFixProtoRefs;
self.stepFixProtos;
self.stepFixPointersNew;
self.stepFixInitOffsets;
self.stepBuildLinkedit;
self.stepMarkUUID;
self.stepSyncHeader;
trace(@"write %@",outPath);
NSError* error=nil;
[self.data writeToFile:outPath options:0 error:&error];
assert(!error);
}
-(BOOL)needsObjcImpostor
{
return !self.shouldMakeContiguous&&!![self.cacheImage.header sectionCommandWithName:(char*)"__objc_imageinfo"];
}
-(BOOL)needsGotImpostor
{
if(self.cache.majorVersion<13)
{
return false;
}
struct section_64* section=[self.cacheImage.header sectionCommandWithName:(char*)"__got"];
if(section)
{
if(!(section->flags&SECTION_TYPE&S_NON_LAZY_SYMBOL_POINTERS))
{
return true;
}
}
return false;
}
-(BOOL)shouldMakeContiguous
{
return flagPad;
}
-(void)stepImportHeader
{
self.header=ImageHeader.alloc.initEmpty.autorelease;
self.header.header->flags=self.cacheImage.header.header->flags;
self.header.header->flags&=~MH_DYLIB_IN_CACHE;
__block int copied=0;
__block int skipped=0;
// MachOAnalyzer.cpp - load command order must mirror offset/address order
// TODO: dumb way to do this
NSMutableArray<NSNumber*>* addresses=NSMutableArray.alloc.init.autorelease;
[self.cacheImage.header forEachSegmentCommand:^(struct segment_command_64* command)
{
[addresses addObject:[NSNumber numberWithLong:command->vmaddr]];
}];
[addresses sortUsingComparator:^NSComparisonResult(NSNumber* first,NSNumber* second)
{
return first.longValue<second.longValue?NSOrderedAscending:NSOrderedDescending;
}];
for(NSNumber* address in addresses)
{
[self.cacheImage.header forEachSegmentCommand:^(struct segment_command_64* command)
{
if(command->vmaddr==address.longValue)
{
// prevent offset collisions mid-import by temporarily adding an implausible amount
// TODO: a horrible hack, but requires significant refactoring to fix
command->fileoff+=IMPORT_HACK_OFFSET;
[self.header addCommand:(struct load_command*)command];
copied++;
// Ventura assumes __DATA,__objc_imageinfo is right after __TEXT
// can't adjust addresses without LC_SEGMENT_SPLIT_INFO or very good static analysis
// so just create a second fake one 😅
if(self.needsObjcImpostor&&!strcmp(command->segname,SEG_TEXT))
{
int impostorSize=sizeof(struct segment_command_64)+sizeof(struct section_64);
NSMutableData* impostorData=[NSMutableData dataWithLength:impostorSize];
struct segment_command_64* impostor=(struct segment_command_64*)impostorData.mutableBytes;
impostor->cmd=LC_SEGMENT_64;
impostor->cmdsize=impostorSize;
memcpy(impostor->segname,IMPOSTOR_OBJC_TEMP,strlen(IMPOSTOR_OBJC_TEMP)+1);
impostor->maxprot=VM_PROT_READ;
impostor->initprot=VM_PROT_READ;
impostor->nsects=1;
[self.header addCommand:(struct load_command*)impostor];
}
// Ventura cache builder uniques __got sections into a region outside all images
// infeasible to restore just needed ones, again lacking LC_SEGMENT_SPLIT_INFO
// copying the entire thing works...
if(self.needsGotImpostor&&!strcmp(command->segname,"__DATA_CONST"))
{
if(self.shouldMakeContiguous)
{
self.addPadCommandCommon;
}
int impostorSize=sizeof(struct segment_command_64)+sizeof(struct section_64);
NSMutableData* impostorData=[NSMutableData dataWithLength:impostorSize];
struct segment_command_64* impostor=(struct segment_command_64*)impostorData.mutableBytes;
impostor->cmd=LC_SEGMENT_64;
impostor->cmdsize=impostorSize;
memcpy(impostor->segname,IMPOSTOR_GOT,strlen(IMPOSTOR_GOT)+1);
// must be writable for binding
impostor->maxprot=VM_PROT_READ|VM_PROT_WRITE;
impostor->initprot=VM_PROT_READ|VM_PROT_WRITE;
impostor->nsects=1;
long gotStartAddress=align(self.cacheImage.file.maxConstDataSegmentAddress,0x1000,false,NULL);
impostor->vmaddr=gotStartAddress;
[self.header addCommand:(struct load_command*)impostor];
}
if(self.shouldMakeContiguous&&strcmp(command->segname,SEG_LINKEDIT))
{
self.addPadCommandCommon;
}
}
}];
}
[self.cacheImage.header forEachCommand:^(struct load_command* command)
{
switch(command->cmd)
{
case LC_SEGMENT_64:
// don't count as skipped
break;
case LC_ID_DYLIB:
case LC_UUID:
case LC_BUILD_VERSION:
case LC_SOURCE_VERSION:
case LC_LOAD_DYLIB:
case LC_LOAD_WEAK_DYLIB:
case LC_LOAD_UPWARD_DYLIB:
case LC_REEXPORT_DYLIB:
[self.header addCommand:command];
copied++;
break;
// TODO: explicitly list ignored commands, add assert for unrecognied
// the current list is sort of arbitrary and could be omitting important things
default:
skipped++;
}
}];
trace(@"copied %x load commands (skipped %x)",copied,skipped);
}
-(void)addPadCommandCommon
{
int size=sizeof(struct segment_command_64)+sizeof(struct section_64);
NSMutableData* data=[NSMutableData dataWithLength:size];
struct segment_command_64* seg=(struct segment_command_64*)data.mutableBytes;
seg->cmd=LC_SEGMENT_64;
seg->cmdsize=size;
memcpy(seg->segname,IMPOSTOR_PAD,strlen(IMPOSTOR_PAD)+1);
[self.header addCommand:(struct load_command*)seg];
}
-(void)stepImportSegmentsExceptLinkedit
{
// TODO: similar problem and workaround as ImageHeader
self.data=[NSMutableData dataWithCapacity:0x100000000];
[self importSegmentsCommon:false];
}
-(void)stepBuildLinkedit
{
[self importSegmentsCommon:true];
}
// TODO: ugly due to special linkedit treatment
// but difficult to separate without code duplication
-(void)importSegmentsCommon:(BOOL)linkeditPhase
{
__block struct segment_command_64* nextPrevCommand=NULL;
[self.header forEachSegmentCommand:^(struct segment_command_64* command)
{
struct segment_command_64* prevCommand=nextPrevCommand;
nextPrevCommand=command;
BOOL isLinkedit=!strcmp(command->segname,SEG_LINKEDIT);
if(linkeditPhase!=isLinkedit)
{
return;
}
if(self.needsObjcImpostor&&!strcmp(command->segname,IMPOSTOR_OBJC_TEMP))
{
memcpy(command->segname,SEG_DATA,strlen(SEG_DATA)+1);
command->vmaddr=prevCommand->vmaddr+prevCommand->vmsize;
command->fileoff=self.data.length;
command->vmsize=0x1000;
command->filesize=0x1000;
struct section_64* impostor=(struct section_64*)(command+1);
impostor->offset=command->fileoff;
impostor->addr=command->vmaddr;
impostor->size=sizeof(objc_image_info);
struct section_64* original=[self.cacheImage.header sectionCommandWithName:(char*)"__objc_imageinfo"];
assert(original);
objc_image_info* originalInfo=(objc_image_info*)wrapOffset(self.cacheImage.file,original->offset).pointer;
objc_image_info* info=(objc_image_info*)wrapOffset(self,impostor->offset).pointer;
[self.data increaseLengthBy:0x1000];
memcpy(info,originalInfo,sizeof(objc_image_info));
memcpy(impostor->segname,SEG_DATA,strlen(SEG_DATA)+1);
memcpy(impostor->sectname,"__objc_imageinfo",16);
trace(@"created fake __objc_imageinfo section");
return;
}
if(!strcmp(command->segname,IMPOSTOR_GOT))
{
// no obvious way to locate this section, but (so far) it's consistently at the end
// of the read-only data mapping
// TODO: may be brittle, and copies slightly more than necessary
long gotEndAddress=self.cacheImage.file.maxConstDataMappingAddress;
long gotLength=gotEndAddress-command->vmaddr;
assert(isAligned(gotEndAddress,0x1000));
command->fileoff=self.data.length;
command->vmsize=gotLength;
command->filesize=gotLength;
struct section_64* impostor=(struct section_64*)(command+1);
impostor->offset=command->fileoff;
impostor->addr=command->vmaddr;
impostor->size=gotLength;
memcpy(impostor->sectname,IMPOSTOR_GOT,strlen(IMPOSTOR_GOT)+1);
memcpy(impostor->segname,IMPOSTOR_GOT,strlen(IMPOSTOR_GOT)+1);
char* destination=wrapOffset(self,impostor->offset).pointer;
char* source=wrapAddress(self.cache,command->vmaddr).pointer;
[self.data increaseLengthBy:gotLength];
memcpy(destination,source,gotLength);
trace(@"restored __got section (source %lx, length %lx)",command->vmaddr,gotLength);
return;
}
if(!strcmp(command->segname,IMPOSTOR_PAD))
{
command->vmaddr=prevCommand->vmaddr+prevCommand->vmsize;
command->fileoff=self.data.length;
command->nsects=1;
// TODO: questionable
__block struct segment_command_64* nextSeg=NULL;
[self.header forEachSegmentCommand:^(struct segment_command_64* seg)
{
if(!nextSeg&&seg->vmaddr>command->vmaddr)
{
nextSeg=seg;
}
}];
long delta=align(nextSeg->vmaddr,0x1000,false,NULL)-command->vmaddr;
command->vmsize=delta;
command->filesize=delta;
struct section_64* sect=(struct section_64*)(command+1);
sect->offset=command->fileoff;
sect->addr=command->vmaddr;
sect->size=delta;
memcpy(sect->sectname,IMPOSTOR_PAD,strlen(IMPOSTOR_PAD)+1);
memcpy(sect->segname,IMPOSTOR_PAD,strlen(IMPOSTOR_PAD)+1);
[self.data increaseLengthBy:delta];
trace(@"added %lx padding at %lx",delta,command->vmaddr);
return;
}
trace(@"build %s",command->segname);
// TODO: second half of an awful hack
command->fileoff-=IMPORT_HACK_OFFSET;
NSMutableData* data=NSMutableData.alloc.init.autorelease;
// silently fails to mmap segments with un-aligned vmaddr
// so, move vmaddr to a page boundary, then left-pad to keep section addresses unchanged
int addressDelta;
long newSegAddress=align(command->vmaddr,0x1000,false,&addressDelta);
// offset is aligned by right-pad at the end of this function
long newSegOffset=self.data.length;
assert(isAligned(newSegOffset,0x1000));
// TODO: in contiguous mode, assert that we are actually contiguous
if(newSegOffset==0)
{
newSegAddress-=HEADER_EXTRA;
addressDelta-=HEADER_EXTRA;
self.baseAddressDelta=addressDelta;
}
[data increaseLengthBy:-addressDelta];
[self.header forEachSectionCommand:^(struct segment_command_64* segment,struct section_64* section)
{
if(segment==command)
{
long newSectOffset=0;
if(section->offset)
{
long fileOffsetInSegment=section->offset-command->fileoff-addressDelta;
newSectOffset=newSegOffset+fileOffsetInSegment;
}
section->offset=newSectOffset;
// TODO: remove rather than just renaming?
if(self.needsObjcImpostor&&!strncmp(section->sectname,"__objc_imageinfo",16))
{
memcpy(section->sectname,IMPOSTOR_OBJC_OLD,strlen(IMPOSTOR_OBJC_OLD)+1);
}
}
}];
// filesize (but not vmsize) must be an integer multiple of page size
// does not apply to linkedit, and tools complain if there is unused space at the end
unsigned long newSegFileSize;
unsigned long newSegMemorySize;
if(isLinkedit)
{
[self buildLinkeditWithData:data];
newSegFileSize=data.length;
newSegMemorySize=data.length;
}
else
{
[data appendBytes:wrapAddress(self.cache,command->vmaddr).pointer length:command->filesize];
newSegFileSize=command->filesize-addressDelta;
int sizeDelta;
newSegFileSize=align(newSegFileSize,0x1000,true,&sizeDelta);
[data increaseLengthBy:sizeDelta];
newSegMemorySize=command->vmsize-addressDelta+sizeDelta;
}
assert(newSegMemorySize>=newSegFileSize);
command->fileoff=newSegOffset;
command->vmaddr=newSegAddress;
command->filesize=newSegFileSize;
command->vmsize=newSegMemorySize;
[self.data appendData:data];
}];
}
-(void)buildLinkeditWithData:(NSMutableData*)data
{
// checkout.c - dyld info must be at the start of linkedit
[self writeFixupsWithData:data];
[self importLegacyCommandsWithData:data];
}
-(void)writeFixupsWithData:(NSMutableData*)data
{
assert(isAligned(self.data.length+data.length,0x1000));
struct segment_command_64* linkeditCommand=[self.header segmentCommandWithName:(char*)SEG_LINKEDIT];
assert(linkeditCommand);
long rebaseStart=data.length;
// TODO: much less space-efficient than compiler output (binds too)
// possible to steal Apple's implementation like the export trie?
char byte=REBASE_OPCODE_SET_TYPE_IMM|REBASE_TYPE_POINTER;
[data appendBytes:&byte length:1];
int rebaseCount=0;
for(Address* fixup in self.fixups.allValues)
{
if(!fixup.isRebase)
{
continue;
}
int segmentIndex;
struct segment_command_64* command=[self.header segmentCommandWithAddress:fixup.address indexOut:&segmentIndex];
assert(command);
long segmentOffset=fixup.address-command->vmaddr;
byte=REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB|segmentIndex;
[data appendBytes:&byte length:1];
[data appendData:ulebWithLong(segmentOffset)];
byte=REBASE_OPCODE_DO_REBASE_IMM_TIMES|1;
[data appendBytes:&byte length:1];
rebaseCount++;
}
byte=REBASE_OPCODE_DONE;
[data appendBytes:&byte length:1];
long rebaseLength=data.length-rebaseStart;
// MachOAnalyzer.cpp - must be 8 byte aligned
int padding;
align(data.length,8,true,&padding);
[data increaseLengthBy:padding];
long bindStart=data.length;
byte=BIND_OPCODE_SET_TYPE_IMM|BIND_TYPE_POINTER;
[data appendBytes:&byte length:1];
int bindCount=0;
for(Address* fixup in self.fixups.allValues)
{
if(!fixup.isBind)
{
continue;
}
int segmentIndex;
struct segment_command_64* command=[self.header segmentCommandWithAddress:fixup.address indexOut:&segmentIndex];
assert(command);
long segmentOffset=fixup.address-command->vmaddr;
byte=BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB;
[data appendBytes:&byte length:1];
[data appendData:ulebWithLong(fixup.dylibOrdinal)];
byte=BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB|segmentIndex;
[data appendBytes:&byte length:1];
[data appendData:ulebWithLong(segmentOffset)];
byte=BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM|0;
[data appendBytes:&byte length:1];
[data appendBytes:fixup.name.UTF8String length:fixup.name.length+1];
if(!!fixup.addend)
{
// TODO: implement SLEB if needed
assert(fixup.addend>0);
byte=BIND_OPCODE_SET_ADDEND_SLEB;
[data appendBytes:&byte length:1];
[data appendData:ulebWithLong(fixup.addend)];
}
byte=BIND_OPCODE_DO_BIND;
[data appendBytes:&byte length:1];
if(!!fixup.addend)
{
// addend persists across binds and breaks everything otherwise
byte=BIND_OPCODE_SET_ADDEND_SLEB;
[data appendBytes:&byte length:1];
[data appendData:ulebWithLong(0)];
}
bindCount++;
}
byte=BIND_OPCODE_DONE;
[data appendBytes:&byte length:1];
long bindLength=data.length-bindStart;
align(data.length,8,true,&padding);
[data increaseLengthBy:padding];
long exportStart=data.length;
// instead of trying to write a trie generator (terrifying) just use Apple's
// Trie.hpp, SharedCacheBuilder.cpp
long reexportCount=0;
long baseAddress=wrapOffset(self,0).address;
std::vector<ExportInfoTrie::Entry> trieEntries;
for(Address* item in self.exports)
{
assert(item.isExport||item.isReexport);
struct ExportInfo info={};
if(item.address)
{
info.address=item.address-baseAddress;
}
if(item.isReexport)
{
info.flags=EXPORT_SYMBOL_FLAGS_REEXPORT;
info.importName=std::string(item.importName.UTF8String);
info.other=item.dylibOrdinal;
reexportCount++;
}
else
{
info.flags=EXPORT_SYMBOL_FLAGS_KIND_REGULAR;
}
ExportInfoTrie::Entry entry(std::string(item.name.UTF8String),info);
trieEntries.push_back(entry);
}
ExportInfoTrie trie(trieEntries);
std::vector<unsigned char> trieBytes;
trie.emit(trieBytes);
[data appendBytes:trieBytes.data() length:trieBytes.size()];
// to avoid gap before symtab, the padding is counted as part of the exports trie
align(data.length,0x1000,true,&padding);
[data increaseLengthBy:padding];
long exportLength=data.length-exportStart;
// TODO: any difference between LC_DYLD_INFO and LC_DYLD_INFO_ONLY?
struct dyld_info_command command={};
command.cmd=LC_DYLD_INFO;
command.cmdsize=sizeof(struct dyld_info_command);
command.rebase_off=self.data.length+rebaseStart;
command.rebase_size=rebaseLength;
command.bind_off=self.data.length+bindStart;
command.bind_size=bindLength;
command.export_off=self.data.length+exportStart;
command.export_size=exportLength;
[self.header addCommand:(struct load_command*)&command];
trace(@"generated %x rebases (%lx bytes), %x binds (%lx bytes), %x exports (%lx re-exports, %lx bytes), total size %lx",rebaseCount,rebaseLength,bindCount,bindLength,trieEntries.size(),reexportCount,exportLength,data.length);
}
// LC_SYMTAB and LC_DYSYMTAB are completely superseded by LC_DYLD_INFO for linking
// purely needed for nm and Hopper external symbols
// TODO: not entirely sure this still works correctly in Ventura, particularly with __got uniquing
-(void)importLegacyCommandsWithData:(NSMutableData*)data
{
// checkout.c - order must be symbols, indirects, strings with no gaps
// MachOAnalyzer.cpp - must be 8 byte aligned
long symbolsStart=self.data.length+data.length;
// should be aligned by writeFixupsWithData:
assert(isAligned(symbolsStart,0x1000));
NSMutableData* stringsData=NSMutableData.alloc.init.autorelease;
// zero string table offset is interpreted as null symbol name
[stringsData increaseLengthBy:1];
__block int symbolCount=0;
[self.cacheImage forEachLegacySymbol:^(struct nlist_64* cacheEntry,char* name)
{
struct nlist_64 entry={};
memcpy(&entry,cacheEntry,sizeof(struct nlist_64));
entry.n_un.n_strx=stringsData.length;
if(entry.n_value)
{
assert(entry.n_value!=-1);
}
[data appendBytes:&entry length:sizeof(struct nlist_64)];
[stringsData appendBytes:name length:strlen(name)+1];
symbolCount++;
}];
struct dysymtab_command* cacheDysymtabCommand=(struct dysymtab_command*)[self.cacheImage.header commandWithType:LC_DYSYMTAB];
assert(cacheDysymtabCommand);
long indirectStart=self.data.length+data.length;
// should be 8-byte aligned since nlist_64 are 16 bytes
assert(isAligned(indirectStart,8));
long indirectSize=cacheDysymtabCommand->nindirectsyms*sizeof(int);
[data appendBytes:wrapOffset(self.cacheImage.file,cacheDysymtabCommand->indirectsymoff).pointer length:indirectSize];
// TODO: this is only guaranteed to be aligned to 4 bytes
// not sure if that's a problem or not
long stringsStart=self.data.length+data.length;
[data appendData:stringsData];
struct symtab_command symtabCommand={};
symtabCommand.cmd=LC_SYMTAB;
symtabCommand.cmdsize=sizeof(struct symtab_command);
symtabCommand.symoff=symbolsStart;
symtabCommand.nsyms=symbolCount;
symtabCommand.stroff=stringsStart;
symtabCommand.strsize=stringsData.length;
[self.header addCommand:(struct load_command*)&symtabCommand];
struct dysymtab_command dysymtabCommand={};
dysymtabCommand.cmd=LC_DYSYMTAB;
dysymtabCommand.cmdsize=sizeof(struct dysymtab_command);
dysymtabCommand.indirectsymoff=indirectStart;
dysymtabCommand.nindirectsyms=cacheDysymtabCommand->nindirectsyms;
[self.header addCommand:(struct load_command*)&dysymtabCommand];
trace(@"copied %lx symtab entries, %lx bytes of indirect entries, %lx bytes of strings",symbolCount,indirectSize,stringsData.length);
}
-(long)addressWithOffset:(long)offset
{
struct segment_command_64* command=[self.header segmentCommandWithOffset:offset indexOut:NULL];
if(!command)
{
return -1;
}
long segmentOffset=offset-command->fileoff;
return command->vmaddr+segmentOffset;
// Location checks address validity
}
-(long)addressWithPointer:(char*)pointer
{
return [self addressWithOffset:pointer-(char*)self.data.mutableBytes];
}
-(long)offsetWithAddress:(long)address
{
struct segment_command_64* command=[self.header segmentCommandWithAddress:address indexOut:NULL];
if(!command)
{
return -1;
}
long segmentOffset=address-command->vmaddr;
long offset=command->fileoff+segmentOffset;
// exception for base address (outside any section but needed for exports trie)
if(offset==0)
{
return offset;
}
__block BOOL inSection=false;
[self.header forEachSectionCommand:^(struct segment_command_64* segment,struct section_64* section)
{
if(segment==command)
{
if(self.shouldMakeContiguous&&!strcmp(section->sectname,IMPOSTOR_PAD))
{
return;
}
if(address>=section->addr&&address<section->addr+section->size)
{
inSection=true;
}
}
}];
if(!inSection)
{
return -1;
}
return offset;
}
-(char*)pointerWithAddress:(long)address
{
return (char*)self.data.mutableBytes+[self offsetWithAddress:address];
}
-(void)stepImportRebases
{
self.fixups=NSMutableDictionary.alloc.init.autorelease;
[self.header forEachSectionCommand:^(struct segment_command_64* segment,struct section_64* section)
{
if(self.shouldMakeContiguous&&!strcmp(section->sectname,IMPOSTOR_PAD))
{
return;
}
NSArray<NSNumber*>* rebases=[self.cacheImage.file rebasesWithStartAddress:section->addr endAddress:section->addr+section->size];
for(NSNumber* rebase in rebases)
{
NSNumber* key=[NSNumber numberWithLong:rebase.longValue];
self.fixups[key]=[Address rebaseWithAddress:rebase.longValue];
}
}];
trace(@"found %x rebases",self.fixups.count);
}
-(void)stepImportExports
{
self.exports=self.cacheImage.exports.copy;
self.exports.autorelease;
trace(@"found %lx exports",self.exports.count);
}
-(void)stepFixImageInfo
{
struct section_64* section=[self.header sectionCommandWithName:(char*)"__objc_imageinfo"];
if(!section)
{
return;
}
objc_image_info* info=(objc_image_info*)wrapOffset(self,section->offset).pointer;
// prevents crash in map_images_nolock
info->flags&=~OptimizedByDyld;
}
// selector strings get uniqued and copied to libobjc, but originals remain (for now)
// just revert the pointers without copying any strings
-(void)stepFindEmbeddedSels
{
self.sels=NSMutableDictionary.alloc.init.autorelease;
struct section_64* section=[self.header sectionCommandWithName:(char*)"__objc_methname"];
if(!section)
{
return;
}
char* name=wrapOffset(self,section->offset).pointer;
char* end=name+section->size;
while(name<end)
{
Selector* sel=Selector.alloc.init.autorelease;
sel.stringAddress=wrapPointer(self,name).address;
self.sels[[NSString stringWithUTF8String:name]]=sel;
name+=strlen(name)+1;
}
trace(@"found %x embedded selectors",self.sels.count);
}
-(void)stepFixSelRefs
{
struct section_64* section=[self.header sectionCommandWithName:(char*)"__objc_selrefs"];
if(!section)
{
return;
}
long* refs=(long*)wrapOffset(self,section->offset).pointer;
int count=section->size/sizeof(long);
trace(@"fix %x selector refs",count);
for(int index=0;index<count;index++)
{
NSString* name=[NSString stringWithUTF8String:wrapAddress(self.cache,refs[index]).pointer];
refs[index]=[self selStringAddressWithName:name];
long refAddress=wrapPointer(self,(char*)&refs[index]).address;
self.sels[name].refAddress=refAddress;
}
}
-(long)selRefAddressWithName:(NSString*)target
{
Selector* sel=self.sels[target];
assert(sel);
return sel.refAddress;
}
-(long)selStringAddressWithName:(NSString*)target
{
Selector* sel=self.sels[target];
assert(sel);
return sel.stringAddress;
}
-(void)stepFixClasses
{
struct section_64* section=[self.header sectionCommandWithName:(char*)"__objc_classlist"];
if(!section)
{
return;
}
long* classes=(long*)wrapOffset(self,section->offset).pointer;
int count=section->size/sizeof(long);
trace(@"fix %x classes",count);
for(int index=0;index<count;index++)
{
struct objc_class* cls=(struct objc_class*)wrapAddress(self,classes[index]).pointer;
// TODO: check and find this constant in objc4
struct objc_data* data=(struct objc_data*)wrapAddress(self,((long)cls->data)&~3).pointer;
struct objc_class* metaCls=(struct objc_class*)wrapAddress(self,(long)cls->metaclass).pointer;
struct objc_data* metaData=(struct objc_data*)wrapAddress(self,(long)metaCls->data).pointer;
[self fixMethodListWithAddress:(long)data->baseMethods];
[self fixMethodListWithAddress:(long)metaData->baseMethods];
[self fixProtoListWithAddress:(long)data->baseProtocols];
[self fixProtoListWithAddress:(long)metaData->baseProtocols];
}
}
-(void)stepFixCats
{
struct section_64* section=[self.header sectionCommandWithName:(char*)"__objc_catlist"];
if(!section)
{
return;
}
long* cats=(long*)wrapOffset(self,section->offset).pointer;
int count=section->size/sizeof(long);
trace(@"fix %x categories",count);
for(int index=0;index<count;index++)
{
struct objc_category* cat=(struct objc_category*)wrapAddress(self,cats[index]).pointer;
[self fixMethodListWithAddress:(long)cat->instanceMethods];
[self fixMethodListWithAddress:(long)cat->classMethods];
[self fixProtoListWithAddress:(long)cat->protocols];
}
}
// like selectors, these have been uniqued, but the originals aren't removed
-(void)stepFixProtoRefs
{
struct section_64* section=[self.header sectionCommandWithName:(char*)"__objc_protorefs"];
if(!section)
{
return;
}