-
-
Notifications
You must be signed in to change notification settings - Fork 32
/
swift.go
2777 lines (2480 loc) · 97.1 KB
/
swift.go
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
package macho
import (
"bufio"
"bytes"
"encoding/binary"
"errors"
"fmt"
"io"
"regexp"
"strings"
"unicode"
"github.com/blacktop/go-macho/types/swift"
)
const sizeOfInt32 = 4
const sizeOfInt64 = 8
var ErrSwiftSectionError = fmt.Errorf("missing swift section")
// HasSwift checks if the MachO has swift info
func (f *File) HasSwift() bool {
if info, err := f.GetObjCImageInfo(); err == nil {
if info != nil && info.HasSwift() {
return true
}
}
for _, sec := range f.Sections {
switch sec.Name {
case "__swift5_types", "__swift5_types2", "__swift5_builtin", "__swift5_fieldmd", "__swift5_assocty", "__swift5_protos", "__swift5_proto", "__swift5_reflstr", "__swift5_capture", "__swift5_typeref", "__swift5_mpenum", "__constg_swiftt", "__swift5_replace", "__swift5_replac2", "__swift5_acfuncs":
return true
}
}
return false
}
// GetSwiftTOC returns a table of contents of the Swift objects in the MachO
func (f *File) GetSwiftTOC() swift.TOC {
var toc swift.TOC
for _, sec := range f.Sections {
switch sec.Name {
case "__swift5_builtin":
toc.Builtins = int(sec.Size) / binary.Size(swift.BuiltinTypeDescriptor{})
// case "__swift5_fieldmd":
// toc.Fields = sec.Size / f.pointerSize()
case "__swift5_types":
toc.Types += int(sec.Size / sizeOfInt32)
case "__swift5_types2":
toc.Types += int(sec.Size / sizeOfInt32)
// case "__swift5_assocty":
// toc.AssociatedTypes = sec.Size / f.pointerSize()
case "__swift5_protos":
toc.Protocols = int(sec.Size / sizeOfInt32)
case "__swift5_proto":
toc.ProtocolConformances = int(sec.Size / sizeOfInt32)
}
}
return toc
}
// GetSwiftEntry parses the __TEXT.__swift5_entry section
func (f *File) GetSwiftEntry() (uint64, error) {
if sec := f.Section("__TEXT", "__swift5_entry"); sec != nil {
off, err := f.vma.GetOffset(f.vma.Convert(sec.Addr))
if err != nil {
return 0, fmt.Errorf("failed to convert vmaddr: %v", err)
}
f.cr.Seek(int64(off), io.SeekStart)
dat := make([]byte, sec.Size)
if err := binary.Read(f.cr, f.ByteOrder, dat); err != nil {
return 0, fmt.Errorf("failed to read %s.%s data: %v", sec.Seg, sec.Name, err)
}
var swiftEntry int32
if err := binary.Read(bytes.NewReader(dat), f.ByteOrder, &swiftEntry); err != nil {
return 0, fmt.Errorf("failed to read __swift5_entry data: %v", err)
}
return sec.Addr + uint64(swiftEntry), nil
}
return 0, fmt.Errorf("MachO has no '__swift5_entry' section: %w", ErrSwiftSectionError)
}
// GetSwiftBuiltinTypes parses all the built-in types in the __TEXT.__swift5_builtin section
func (f *File) GetSwiftBuiltinTypes() (builtins []swift.BuiltinType, err error) {
if sec := f.Section("__TEXT", "__swift5_builtin"); sec != nil {
f.cr.SeekToAddr(sec.Addr)
dat := make([]byte, sec.Size)
if err := binary.Read(f.cr, f.ByteOrder, dat); err != nil {
return nil, fmt.Errorf("failed to read %s.%s data: %w", sec.Seg, sec.Name, err)
}
r := bytes.NewReader(dat)
for {
curr, _ := r.Seek(0, io.SeekCurrent)
var bi swift.BuiltinType
err := bi.BuiltinTypeDescriptor.Read(r, sec.Addr+uint64(curr))
if err != nil {
if errors.Is(err, io.EOF) {
break
}
return nil, fmt.Errorf("failed to read swift builtin type descriptor at address %#x: %w", sec.Addr+uint64(curr), err)
}
bi.Name, err = f.makeSymbolicMangledNameStringRef(bi.TypeName.GetAddress())
if err != nil {
return nil, fmt.Errorf("failed to read swift builtin type name at address %#x: %w", bi.TypeName.GetAddress(), err)
}
builtins = append(builtins, bi)
}
return builtins, nil
}
return nil, fmt.Errorf("MachO has no '__swift5_builtin' section: %w", ErrSwiftSectionError)
}
// GetSwiftReflectionStrings parses all the reflection strings in the __TEXT.__swift5_reflstr section
func (f *File) GetSwiftReflectionStrings() (map[uint64]string, error) {
reflStrings := make(map[uint64]string)
if sec := f.Section("__TEXT", "__swift5_reflstr"); sec != nil {
off, err := f.vma.GetOffset(f.vma.Convert(sec.Addr))
if err != nil {
return nil, fmt.Errorf("failed to convert vmaddr: %w", err)
}
f.cr.Seek(int64(off), io.SeekStart)
dat := make([]byte, sec.Size)
if err := binary.Read(f.cr, f.ByteOrder, dat); err != nil {
return nil, fmt.Errorf("failed to read %s.%s data: %w", sec.Seg, sec.Name, err)
}
r := bytes.NewBuffer(dat)
for {
s, err := r.ReadString('\x00')
if err != nil {
if errors.Is(err, io.EOF) {
break
}
return nil, fmt.Errorf("failed to read swift reflection string: %w", err)
}
if len(strings.Trim(s, "\x00")) > 0 {
reflStrings[sec.Addr+(sec.Size-uint64(r.Len()+len(s)))] = strings.Trim(s, "\x00")
}
}
return reflStrings, nil
}
return nil, fmt.Errorf("MachO has no '__swift5_reflstr' section: %w", ErrSwiftSectionError)
}
// GetSwiftFields parses all the fields in the __TEXT.__swift5_fields section
func (f *File) GetSwiftFields() (fields []swift.Field, err error) {
if sec := f.Section("__TEXT", "__swift5_fieldmd"); sec != nil {
off, err := f.vma.GetOffset(f.vma.Convert(sec.Addr))
if err != nil {
return nil, fmt.Errorf("failed to convert vmaddr: %v", err)
}
f.cr.Seek(int64(off), io.SeekStart)
dat := make([]byte, sec.Size)
if err := binary.Read(f.cr, f.ByteOrder, dat); err != nil {
return nil, fmt.Errorf("failed to read %s.%s data: %v", sec.Seg, sec.Name, err)
}
r := bytes.NewReader(dat)
// read field descriptors
for {
curr, _ := r.Seek(0, io.SeekCurrent)
field, err := f.readField(r, sec.Addr+uint64(curr))
if err != nil {
if errors.Is(err, io.EOF) {
break
}
return nil, fmt.Errorf("failed to read swift field at address %#x: %w", sec.Addr+uint64(curr), err)
}
fields = append(fields, *field)
}
return fields, nil
}
return nil, fmt.Errorf("MachO has no '__swift5_fieldmd' section: %w", ErrSwiftSectionError)
}
func (f *File) readField(r io.ReadSeeker, addr uint64) (field *swift.Field, err error) {
off, _ := r.Seek(0, io.SeekCurrent) // save offset
field = &swift.Field{Address: addr}
if err := field.FieldDescriptor.Read(r, addr); err != nil {
return nil, fmt.Errorf("failed to read swift field descriptor string: %w", err)
}
field.Records = make([]swift.FieldRecord, field.NumFields)
for i := 0; i < int(field.NumFields); i++ {
curr, _ := r.Seek(0, io.SeekCurrent)
if err := field.Records[i].FieldRecordDescriptor.Read(r, field.Address+uint64(curr-off)); err != nil {
return nil, fmt.Errorf("failed to read swift FieldRecordDescriptor: %v", err)
}
}
if field.MangledTypeNameOffset.IsSet() {
field.Type, err = f.makeSymbolicMangledNameStringRef(field.MangledTypeNameOffset.GetAddress())
if err != nil {
return nil, fmt.Errorf("failed to read swift field mangled type name: %w", err)
}
}
if field.SuperclassOffset.IsSet() {
field.SuperClass, err = f.makeSymbolicMangledNameStringRef(field.SuperclassOffset.GetAddress())
if err != nil {
return nil, fmt.Errorf("failed to read swift field super class mangled name: %w", err)
}
}
for idx, rec := range field.Records {
field.Records[idx].Name, err = f.GetCString(rec.FieldNameOffset.GetAddress())
if err != nil {
return nil, fmt.Errorf("failed to read swift field record name cstring: %w", err)
}
if rec.MangledTypeNameOffset.IsSet() {
field.Records[idx].MangledType, err = f.makeSymbolicMangledNameStringRef(rec.MangledTypeNameOffset.GetAddress())
if err != nil {
return nil, fmt.Errorf("failed to read swift field record mangled type name; %w", err)
}
}
}
f.swift[field.Address] = field // cache field
return field, nil
}
// GetSwiftAssociatedTypes parses all the associated types in the __TEXT.__swift5_assocty section
func (f *File) GetSwiftAssociatedTypes() (asstypes []swift.AssociatedType, err error) {
if sec := f.Section("__TEXT", "__swift5_assocty"); sec != nil {
f.cr.SeekToAddr(sec.Addr)
dat := make([]byte, sec.Size)
if err := binary.Read(f.cr, f.ByteOrder, dat); err != nil {
return nil, fmt.Errorf("failed to read %s.%s data: %w", sec.Seg, sec.Name, err)
}
r := bytes.NewReader(dat)
for {
curr, _ := r.Seek(0, io.SeekCurrent)
atyp := swift.AssociatedType{
Address: sec.Addr + uint64(curr),
}
err = atyp.AssociatedTypeDescriptor.Read(r, sec.Addr+uint64(curr))
if err != nil {
if errors.Is(err, io.EOF) {
break
}
return nil, fmt.Errorf("failed to read swift AssociatedTypeDescriptor: %w", err)
}
atyp.TypeRecords = make([]swift.ATRecordType, atyp.NumAssociatedTypes)
for i := uint32(0); i < atyp.NumAssociatedTypes; i++ {
curr, _ = r.Seek(0, io.SeekCurrent)
if err := atyp.TypeRecords[i].AssociatedTypeRecord.Read(r, sec.Addr+uint64(curr)); err != nil {
return nil, fmt.Errorf("failed to read AssociatedTypeRecord: %w", err)
}
}
atyp.ConformingTypeName, err = f.makeSymbolicMangledNameStringRef(atyp.ConformingTypeNameOffset.GetAddress())
if err != nil {
return nil, fmt.Errorf("failed to read conforming type for associated type at addr %#x: %v", atyp.ConformingTypeNameOffset.GetAddress(), err)
}
atyp.ProtocolTypeName, err = f.makeSymbolicMangledNameStringRef(atyp.ProtocolTypeNameOffset.GetAddress())
if err != nil {
return nil, fmt.Errorf("failed to read swift assocated type protocol type name at addr %#x: %v", atyp.ProtocolTypeNameOffset.GetAddress(), err)
}
for idx, rec := range atyp.TypeRecords {
atyp.TypeRecords[idx].Name, err = f.GetCString(rec.NameOffset.GetAddress())
if err != nil {
return nil, fmt.Errorf("failed to read associated type record name: %w", err)
}
atyp.TypeRecords[idx].SubstitutedTypeName, err = f.makeSymbolicMangledNameStringRef(rec.SubstitutedTypeNameOffset.GetAddress())
if err != nil {
return nil, fmt.Errorf("failed to read associated type substituted type name: %w", err)
}
}
asstypes = append(asstypes, atyp)
}
return asstypes, nil
}
return nil, fmt.Errorf("MachO has no '__swift5_assocty' section: %w", ErrSwiftSectionError)
}
// GetSwiftProtocols parses all the protocols in the __TEXT.__swift5_protos section
func (f *File) GetSwiftProtocols() (protos []swift.Protocol, err error) {
if sec := f.Section("__TEXT", "__swift5_protos"); sec != nil {
f.cr.SeekToAddr(sec.Addr)
dat := make([]byte, sec.Size)
if err := binary.Read(f.cr, f.ByteOrder, dat); err != nil {
return nil, fmt.Errorf("failed to read %s.%s data: %w", sec.Seg, sec.Name, err)
}
r := bytes.NewReader(dat)
relOffsets := make([]swift.RelativeIndirectablePointer, len(dat)/sizeOfInt32)
for i := 0; i < len(dat)/sizeOfInt32; i++ {
curr, _ := r.Seek(0, io.SeekCurrent)
relOffsets[i].Address = sec.Addr + uint64(curr)
if err := binary.Read(r, f.ByteOrder, &relOffsets[i].RelOff); err != nil {
return nil, fmt.Errorf("failed to read relative offsets: %v", err)
}
}
for _, relOff := range relOffsets {
addr, err := relOff.GetAddress(f.GetPointerAtAddress)
if err != nil {
return nil, fmt.Errorf("failed to get swift protocol address from relative indirectable pointer: %v", err)
}
if typ, ok := f.swift[addr]; ok { // check cache
if typ, ok := typ.(*swift.Type); ok {
if typ.Kind == swift.CDKindProtocol {
protos = append(protos, typ.Type.(swift.Protocol))
}
}
} else {
if err := f.cr.SeekToAddr(addr); err != nil {
return nil, fmt.Errorf("failed to seek to swift protocol address %#x: %v", addr, err)
}
proto, err := f.parseProtocol(f.cr, &swift.Type{Address: addr})
if err != nil {
return nil, fmt.Errorf("failed to read swift protocol at address %#x: %w", addr, err)
}
protos = append(protos, *proto)
}
}
return protos, nil
}
return nil, fmt.Errorf("MachO has no '__swift5_protos' section: %w", ErrSwiftSectionError)
}
// GetSwiftProtocolConformances parses all the protocol conformances in the __TEXT.__swift5_proto section
func (f *File) GetSwiftProtocolConformances() (protoConfDescs []swift.ConformanceDescriptor, err error) {
if sec := f.Section("__TEXT", "__swift5_proto"); sec != nil {
f.cr.SeekToAddr(sec.Addr)
dat := make([]byte, sec.Size)
if err := binary.Read(f.cr, f.ByteOrder, dat); err != nil {
return nil, fmt.Errorf("failed to read %s.%s data: %w", sec.Seg, sec.Name, err)
}
r := bytes.NewReader(dat)
relOffsets := make([]swift.RelativeIndirectablePointer, len(dat)/sizeOfInt32)
for i := 0; i < len(dat)/sizeOfInt32; i++ {
curr, _ := r.Seek(0, io.SeekCurrent)
relOffsets[i].Address = sec.Addr + uint64(curr)
if err := binary.Read(r, f.ByteOrder, &relOffsets[i].RelOff); err != nil {
return nil, fmt.Errorf("failed to read relative offsets: %v", err)
}
}
for _, relOff := range relOffsets {
addr, err := relOff.GetAddress(f.GetPointerAtAddress)
if err != nil {
return nil, fmt.Errorf("failed to get swift protocol conformance address from relative indirectable pointer: %v", err)
}
if err := f.cr.SeekToAddr(addr); err != nil {
return nil, fmt.Errorf("failed to seek to swift protocol conformance address %#x: %v", addr, err)
}
pcd, err := f.readProtocolConformance(f.cr, addr)
if err != nil {
return nil, fmt.Errorf("failed to read swift protocol conformance at address %#x: %w", addr, err)
}
protoConfDescs = append(protoConfDescs, *pcd)
}
return protoConfDescs, nil
}
return nil, fmt.Errorf("MachO has no '__swift5_proto' section: %w", ErrSwiftSectionError)
}
// GetSwiftClosures parses all the closure context objects in the __TEXT.__swift5_capture section
func (f *File) GetSwiftClosures() (closures []swift.Capture, err error) {
if sec := f.Section("__TEXT", "__swift5_capture"); sec != nil {
f.cr.SeekToAddr(sec.Addr)
dat := make([]byte, sec.Size)
if err := binary.Read(f.cr, f.ByteOrder, dat); err != nil {
return nil, fmt.Errorf("failed to read %s.%s data: %v", sec.Seg, sec.Name, err)
}
r := bytes.NewReader(dat)
for {
off, _ := r.Seek(0, io.SeekCurrent)
capture := swift.Capture{Address: sec.Addr + uint64(off)}
if err := binary.Read(r, f.ByteOrder, &capture.CaptureDescriptor); err != nil {
if errors.Is(err, io.EOF) {
break
}
return nil, fmt.Errorf("failed to read swift %T: %w", capture.CaptureDescriptor, err)
}
if capture.NumCaptureTypes > 0 {
capture.CaptureTypes = make([]swift.CaptureType, capture.NumCaptureTypes)
for i := uint32(0); i < capture.NumCaptureTypes; i++ {
curr, _ := r.Seek(0, io.SeekCurrent)
if err := capture.CaptureTypes[i].CaptureTypeRecord.Read(r, capture.Address+uint64(curr-off)); err != nil {
return nil, fmt.Errorf("failed to read swift %T: %v", capture.CaptureTypes[i].CaptureTypeRecord, err)
}
}
for idx, ctype := range capture.CaptureTypes {
capture.CaptureTypes[idx].TypeName, err = f.makeSymbolicMangledNameStringRef(ctype.MangledTypeName.GetAddress())
if err != nil {
return nil, fmt.Errorf("failed to read mangled type name at address %#x: %v", ctype.MangledTypeName.GetAddress(), err)
}
}
}
if capture.NumMetadataSources > 0 {
capture.MetadataSources = make([]swift.MetadataSource, capture.NumMetadataSources)
for i := uint32(0); i < capture.NumMetadataSources; i++ {
curr, _ := r.Seek(0, io.SeekCurrent)
if err := capture.MetadataSources[i].MetadataSourceRecord.Read(r, capture.Address+uint64(curr-off)); err != nil {
return nil, fmt.Errorf("failed to read swift %T: %v", capture.MetadataSources[i].MetadataSourceRecord, err)
}
}
for idx, msrc := range capture.MetadataSources {
capture.MetadataSources[idx].MangledType, err = f.makeSymbolicMangledNameStringRef(msrc.MangledTypeNameOff.GetAddress())
if err != nil {
return nil, fmt.Errorf("failed to read mangled type name at address %#x: %v", msrc.MangledTypeNameOff.GetAddress(), err)
}
capture.MetadataSources[idx].MangledMetadataSource, err = f.makeSymbolicMangledNameStringRef(msrc.MangledMetadataSourceOff.GetAddress())
if err != nil {
return nil, fmt.Errorf("failed to read mangled metadata source at address %#x: %v", msrc.MangledMetadataSourceOff.GetAddress(), err)
}
}
}
// if capture.NumBindings > 0 {
// capture.Bindings = make([]swift.NecessaryBindings, capture.NumBindings)
// for i := uint32(0); i < capture.NumBindings; i++ {
// curr, _ := r.Seek(0, io.SeekCurrent)
// if err := capture.Bindings[i].Read(r, capture.Address+uint64(curr-off)); err != nil {
// return nil, fmt.Errorf("failed to read swift %T: %v", capture.Bindings[i], err)
// }
// }
// }
closures = append(closures, capture)
}
return closures, nil
}
return nil, fmt.Errorf("MachO has no '__swift5_capture' section: %w", ErrSwiftSectionError)
}
// GetSwiftDynamicReplacementInfo parses the __TEXT.__swift5_replace section
func (f *File) GetSwiftDynamicReplacementInfo() (*swift.AutomaticDynamicReplacements, error) {
if sec := f.Section("__TEXT", "__swift5_replace"); sec != nil {
off, err := f.vma.GetOffset(f.vma.Convert(sec.Addr))
if err != nil {
return nil, fmt.Errorf("failed to convert vmaddr: %v", err)
}
f.cr.Seek(int64(off), io.SeekStart)
dat := make([]byte, sec.Size)
if err := binary.Read(f.cr, f.ByteOrder, dat); err != nil {
return nil, fmt.Errorf("failed to read %s.%s data: %v", sec.Seg, sec.Name, err)
}
var rep swift.AutomaticDynamicReplacements
if err := binary.Read(bytes.NewReader(dat), f.ByteOrder, &rep); err != nil {
return nil, fmt.Errorf("failed to read %T: %v", rep, err)
}
f.cr.Seek(int64(off)+int64(sizeOfInt32*2)+int64(rep.ReplacementScope), io.SeekStart)
var rscope swift.DynamicReplacementScope
if err := binary.Read(f.cr, f.ByteOrder, &rscope); err != nil {
return nil, fmt.Errorf("failed to read %T: %v", rscope, err)
}
return &rep, nil
}
return nil, fmt.Errorf("MachO has no '__swift5_replace' section: %w", ErrSwiftSectionError)
}
// GetSwiftDynamicReplacementInfoForOpaqueTypes parses the __TEXT.__swift5_replac2 section
func (f *File) GetSwiftDynamicReplacementInfoForOpaqueTypes() (*swift.AutomaticDynamicReplacementsSome, error) {
if sec := f.Section("__TEXT", "__swift5_replac2"); sec != nil {
off, err := f.vma.GetOffset(f.vma.Convert(sec.Addr))
if err != nil {
return nil, fmt.Errorf("failed to convert vmaddr: %v", err)
}
f.cr.Seek(int64(off), io.SeekStart)
dat := make([]byte, sec.Size)
if err := binary.Read(f.cr, f.ByteOrder, dat); err != nil {
return nil, fmt.Errorf("failed to read %s.%s data: %v", sec.Seg, sec.Name, err)
}
var rep2 swift.AutomaticDynamicReplacementsSome
if err := binary.Read(bytes.NewReader(dat), f.ByteOrder, &rep2.Flags); err != nil {
return nil, fmt.Errorf("failed to read %T: %v", rep2.Flags, err)
}
if err := binary.Read(bytes.NewReader(dat), f.ByteOrder, &rep2.NumReplacements); err != nil {
return nil, fmt.Errorf("failed to read %T: %v", rep2.NumReplacements, err)
}
rep2.Replacements = make([]swift.DynamicReplacementSomeDescriptor, rep2.NumReplacements)
if err := binary.Read(bytes.NewReader(dat), f.ByteOrder, &rep2.Replacements); err != nil {
return nil, fmt.Errorf("failed to read %T: %v", rep2.Replacements, err)
}
return &rep2, nil
}
return nil, fmt.Errorf("MachO has no '__swift5_replac2' section: %w", ErrSwiftSectionError)
}
// GetSwiftAccessibleFunctions parses the __TEXT.__swift5_acfuncs section
func (f *File) GetSwiftAccessibleFunctions() (funcs []swift.TargetAccessibleFunctionRecord, err error) {
if sec := f.Section("__TEXT", "__swift5_acfuncs"); sec != nil {
off, err := f.vma.GetOffset(f.vma.Convert(sec.Addr))
if err != nil {
return nil, fmt.Errorf("failed to convert vmaddr: %v", err)
}
f.cr.Seek(int64(off), io.SeekStart)
dat := make([]byte, sec.Size)
if err := binary.Read(f.cr, f.ByteOrder, dat); err != nil {
return nil, fmt.Errorf("failed to read %s.%s data: %v", sec.Seg, sec.Name, err)
}
r := bytes.NewReader(dat)
for {
curr, _ := r.Seek(0, io.SeekCurrent)
var afr swift.TargetAccessibleFunctionRecord
if err := afr.Read(r, sec.Addr+uint64(curr)); err != nil {
if errors.Is(err, io.EOF) {
break
}
return nil, fmt.Errorf("failed to read swift %T: %w", afr, err)
}
funcs = append(funcs, afr)
}
return funcs, nil
}
return nil, fmt.Errorf("MachO has no '__swift5_acfuncs' section: %w", ErrSwiftSectionError)
}
// TODO: With the improvements to makeSymbolicMangledNameStringRef I believe I can NOW add this back in and add it to `PreCache()`
//// GetSwiftTypeRefs parses all the type references in the __TEXT.__swift5_typeref section
// func (f *File) GetSwiftTypeRefs() (trefs map[uint64]string, err error) {
// trefs = make(map[uint64]string)
// if sec := f.Section("__TEXT", "__swift5_typeref"); sec != nil {
// off, err := f.vma.GetOffset(f.vma.Convert(sec.Addr))
// if err != nil {
// return nil, fmt.Errorf("failed to convert vmaddr: %v", err)
// }
// f.cr.Seek(int64(off), io.SeekStart)
// dat := make([]byte, sec.Size)
// if err := binary.Read(f.cr, f.ByteOrder, dat); err != nil {
// return nil, fmt.Errorf("failed to read %s.%s data: %v", sec.Seg, sec.Name, err)
// }
// r := bytes.NewReader(dat)
// for {
// curr, _ := r.Seek(0, io.SeekCurrent)
// typ, err := f.makeSymbolicMangledNameStringRef(sec.Addr + uint64(curr))
// if err != nil {
// if errors.Is(err, io.EOF) {
// break
// }
// return nil, fmt.Errorf("failed to read swift AssociatedTypeDescriptor: %w", err)
// }
// trefs[sec.Addr+uint64(curr)] = typ
// }
// return trefs, nil
// }
// return nil, fmt.Errorf("MachO has no '__swift5_typeref' section: %w", ErrSwiftSectionError)
// }
// GetSwiftMultiPayloadEnums TODO: finish me
func (f *File) GetSwiftMultiPayloadEnums() (mpenums []swift.MultiPayloadEnum, err error) {
if sec := f.Section("__TEXT", "__swift5_mpenum"); sec != nil {
off, err := f.vma.GetOffset(f.vma.Convert(sec.Addr))
if err != nil {
return nil, fmt.Errorf("failed to convert vmaddr: %v", err)
}
f.cr.Seek(int64(off), io.SeekStart)
dat := make([]byte, sec.Size)
if err := binary.Read(f.cr, f.ByteOrder, dat); err != nil {
return nil, fmt.Errorf("failed to read %s.%s data: %v", sec.Seg, sec.Name, err)
}
r := bytes.NewReader(dat)
for {
curr, _ := r.Seek(0, io.SeekCurrent)
var mpenum swift.MultiPayloadEnumDescriptor
if err := binary.Read(r, f.ByteOrder, &mpenum.TypeName); err != nil {
if errors.Is(err, io.EOF) {
break
}
return nil, fmt.Errorf("failed to read %T: %w", mpenum, err)
}
var sizeFlags swift.MultiPayloadEnumSizeAndFlags
if err := binary.Read(r, f.ByteOrder, &sizeFlags); err != nil {
return nil, fmt.Errorf("failed to read %T: %w", sizeFlags, err)
}
if sizeFlags.UsesPayloadSpareBits() {
var psbmask swift.MultiPayloadEnumPayloadSpareBitMaskByteCount
if err := binary.Read(r, f.ByteOrder, &psbmask); err != nil {
return nil, fmt.Errorf("failed to read %T: %w", psbmask, err)
}
r.Seek(-int64(binary.Size(sizeFlags)+binary.Size(psbmask)), io.SeekCurrent) // rewind
} else {
r.Seek(-int64(binary.Size(sizeFlags)), io.SeekCurrent) // rewind
}
mpenum.Contents = make([]uint32, sizeFlags.Size())
// mpenumFlags = sizeFlags & 0xffff
if err := binary.Read(r, f.ByteOrder, &mpenum.Contents); err != nil {
return nil, fmt.Errorf("failed to read mpenum contents: %w", err)
}
// TODO: understand and use the large bit-mask
addr := int64(sec.Addr) + int64(curr) + int64(mpenum.TypeName)
name, err := f.makeSymbolicMangledNameStringRef(uint64(addr))
if err != nil {
return nil, fmt.Errorf("failed to read mangled type name @ %#x: %v", addr, err)
}
mpenums = append(mpenums, swift.MultiPayloadEnum{
Address: sec.Addr + uint64(curr),
Type: name,
Contents: mpenum.Contents,
})
}
return mpenums, nil
}
return nil, fmt.Errorf("MachO has no '__swift5_mpenum' section: %w", ErrSwiftSectionError)
}
// GetSwiftColocateTypeDescriptors parses all the colocated type descriptors in the __TEXT.__constg_swiftt section
func (f *File) GetSwiftColocateTypeDescriptors() ([]swift.Type, error) {
if sec := f.Section("__TEXT", "__constg_swiftt"); sec != nil {
var typs []swift.Type
off, err := f.vma.GetOffset(f.vma.Convert(sec.Addr))
if err != nil {
return nil, fmt.Errorf("failed to convert vmaddr: %w", err)
}
f.cr.Seek(int64(off), io.SeekStart)
dat := make([]byte, sec.Size)
if err := binary.Read(f.cr, f.ByteOrder, dat); err != nil {
return nil, fmt.Errorf("failed to read %s.%s data: %w", sec.Seg, sec.Name, err)
}
r := bytes.NewReader(dat)
for {
curr, _ := r.Seek(0, io.SeekCurrent)
typ, err := f.readType(r, sec.Addr+uint64(curr))
if err != nil {
if errors.Is(err, io.EOF) {
break
}
return nil, fmt.Errorf("failed to read swift colocate type at address %#x: %w", sec.Addr+uint64(curr), err)
}
typs = append(typs, *typ)
}
return typs, nil
}
return nil, fmt.Errorf("MachO has no '__constg_swiftt' section: %w", ErrSwiftSectionError)
}
// GetSwiftColocateMetadata parses all the colocated metadata in the __TEXT.__textg_swiftm section
func (f *File) GetSwiftColocateMetadata() ([]swift.ConformanceDescriptor, error) {
if sec := f.Section("__TEXT", "__textg_swiftm"); sec != nil {
off, err := f.vma.GetOffset(f.vma.Convert(sec.Addr))
if err != nil {
return nil, fmt.Errorf("failed to convert vmaddr: %v", err)
}
f.cr.Seek(int64(off), io.SeekStart)
panic("not implimented") // FIXME: finish me (I can't find any examples of this section in the wild)
}
return nil, fmt.Errorf("MachO has no '__textg_swiftm' section: %w", ErrSwiftSectionError)
}
// GetSwiftTypes parses all the swift in the __TEXT.__swift5_types section
func (f *File) GetSwiftTypes() (typs []swift.Type, err error) {
for _, sec := range f.Sections {
if sec.Seg == "__TEXT" && (sec.Name == "__swift5_types" || sec.Name == "__swift5_types2") {
off, err := f.vma.GetOffset(f.vma.Convert(sec.Addr))
if err != nil {
return nil, fmt.Errorf("failed to convert vmaddr: %v", err)
}
f.cr.Seek(int64(off), io.SeekStart)
dat := make([]byte, sec.Size)
if err := binary.Read(f.cr, f.ByteOrder, dat); err != nil {
return nil, fmt.Errorf("failed to read %s.%s data: %v", sec.Seg, sec.Name, err)
}
r := bytes.NewReader(dat)
relOffsets := make([]swift.RelativeIndirectablePointer, len(dat)/sizeOfInt32)
for i := 0; i < len(dat)/sizeOfInt32; i++ {
curr, _ := r.Seek(0, io.SeekCurrent)
relOffsets[i].Address = sec.Addr + uint64(curr)
if err := binary.Read(r, f.ByteOrder, &relOffsets[i].RelOff); err != nil {
return nil, fmt.Errorf("failed to read relative offsets: %v", err)
}
}
for _, relOff := range relOffsets {
addr, err := relOff.GetAddress(f.GetPointerAtAddress)
if err != nil {
return nil, fmt.Errorf("failed to get type address from relative indirectable pointer: %v", err)
}
if typ, ok := f.swift[addr]; ok { // check cache
if typ, ok := typ.(*swift.Type); ok {
typs = append(typs, *typ)
}
} else {
if err := f.cr.SeekToAddr(addr); err != nil {
return nil, fmt.Errorf("failed to seek to swift type address %#x: %v", addr, err)
}
typ, err := f.readType(f.cr, addr)
if err != nil {
return nil, fmt.Errorf("failed to read type at address %#x: %v", addr, err)
}
typs = append(typs, *typ)
}
}
}
}
if len(typs) > 0 {
return typs, nil
}
return nil, fmt.Errorf("MachO has no '__swift5_types' or '__swift5_types2' sections: %w", ErrSwiftSectionError)
}
func (f *File) readType(r io.ReadSeeker, addr uint64) (typ *swift.Type, err error) {
var desc swift.TargetContextDescriptor
if err := desc.Read(r, addr); err != nil {
return nil, fmt.Errorf("failed to read swift type context descriptor: %w", err)
}
r.Seek(-desc.Size(), io.SeekCurrent) // rewind
typ = &swift.Type{Address: addr, Kind: desc.Flags.Kind()}
switch desc.Flags.Kind() {
case swift.CDKindModule:
if err := f.parseModule(r, typ); err != nil {
return nil, fmt.Errorf("failed to read type kind %s flags(%s): %w", typ.Kind, desc.Flags, err)
}
case swift.CDKindExtension:
if err := f.parseExtension(r, typ); err != nil {
return nil, fmt.Errorf("failed to read type kind %s flags(%s): %w", typ.Kind, desc.Flags, err)
}
case swift.CDKindAnonymous:
if err := f.parseAnonymous(r, typ); err != nil {
return nil, fmt.Errorf("failed to read type kind %s flags(%s): %w", typ.Kind, desc.Flags, err)
}
case swift.CDKindProtocol:
if _, err := f.parseProtocol(r, typ); err != nil {
return nil, fmt.Errorf("failed to read type kind %s flags(%s): %w", typ.Kind, desc.Flags, err)
}
case swift.CDKindOpaqueType:
if err := f.parseOpaqueType(r, typ); err != nil {
return nil, fmt.Errorf("failed to read type kind %s flags(%s): %w", typ.Kind, desc.Flags, err)
}
case swift.CDKindClass:
if err := f.parseClassDescriptor(r, typ); err != nil {
return nil, fmt.Errorf("failed to read type kind %s flags(%s): %w", typ.Kind, desc.Flags, err)
}
case swift.CDKindStruct:
if err := f.parseStructDescriptor(r, typ); err != nil {
return nil, fmt.Errorf("failed to read type kind %s flags(%s): %w", typ.Kind, desc.Flags, err)
}
case swift.CDKindEnum:
if err := f.parseEnumDescriptor(r, typ); err != nil {
return nil, fmt.Errorf("failed to read type kind %s flags(%s): %w", typ.Kind, desc.Flags, err)
}
default:
return nil, fmt.Errorf("unknown swift type kind: %v flags(%s)", desc.Flags.Kind(), desc.Flags)
}
f.swift[typ.Address] = typ // cache type
return typ, nil
}
/***************
* TYPE PARSERS *
****************/
func (f *File) parseModule(r io.Reader, typ *swift.Type) (err error) {
var mod swift.TargetModuleContextDescriptor
if err := mod.Read(r, typ.Address); err != nil {
return fmt.Errorf("failed to read swift module descriptor: %v", err)
}
typ.Name, err = f.GetCString(mod.NameOffset.GetAddress())
if err != nil {
return fmt.Errorf("failed to read type name: %v", err)
}
if mod.ParentOffset.IsSet() {
f.cr.SeekToAddr(mod.ParentOffset.GetAddress())
ctx, err := f.getContextDesc(mod.ParentOffset.GetAddress())
if err != nil {
return fmt.Errorf("failed to get parent: %v", err)
}
typ.Parent = &swift.Type{
Address: mod.ParentOffset.GetAddress(),
Name: ctx.Name,
Parent: &swift.Type{
Name: ctx.Parent,
},
}
}
typ.Type = mod
typ.Size = mod.Size()
return nil
}
func (f *File) parseExtension(r io.ReadSeeker, typ *swift.Type) (err error) {
off, _ := r.Seek(0, io.SeekCurrent) // save offset
var ext swift.Extension
if err := ext.TargetExtensionContextDescriptor.Read(r, typ.Address); err != nil {
return fmt.Errorf("failed to read swift module descriptor: %v", err)
}
if ext.Flags.IsGeneric() {
ext.GenericContext = &swift.GenericContext{}
if err := binary.Read(r, f.ByteOrder, &ext.GenericContext.TargetGenericContextDescriptorHeader); err != nil {
return fmt.Errorf("failed to read generic header: %v", err)
}
ext.GenericContext.Parameters = make([]swift.GenericParamDescriptor, ext.GenericContext.NumParams)
if err := binary.Read(r, f.ByteOrder, &ext.GenericContext.Parameters); err != nil {
return fmt.Errorf("failed to read generic params: %v", err)
}
curr, _ := r.Seek(0, io.SeekCurrent)
r.Seek(int64(Align(uint64(curr), 4)), io.SeekStart)
ext.GenericContext.Requirements = make([]swift.TargetGenericRequirementDescriptor, ext.GenericContext.NumRequirements)
for i := 0; i < int(ext.GenericContext.NumRequirements); i++ {
curr, _ = r.Seek(0, io.SeekCurrent)
if err := ext.GenericContext.Requirements[i].Read(r, typ.Address+uint64(curr-off)); err != nil {
return fmt.Errorf("failed to read generic requirement: %v", err)
}
}
if ext.GenericContext.Flags.HasTypePacks() {
var hdr swift.GenericPackShapeHeader
if err := binary.Read(r, f.ByteOrder, &hdr); err != nil {
return fmt.Errorf("failed to read generic pack shape header: %v", err)
}
ext.GenericContext.TypePacks = make([]swift.GenericPackShapeDescriptor, hdr.NumPacks)
if err := binary.Read(r, f.ByteOrder, &ext.GenericContext.TypePacks); err != nil {
return fmt.Errorf("failed to read generic pack shape descriptors: %v", err)
}
}
}
if ext.ParentOffset.IsSet() {
f.cr.SeekToAddr(ext.ParentOffset.GetAddress())
ctx, err := f.getContextDesc(ext.ParentOffset.GetAddress())
if err != nil {
return fmt.Errorf("failed to get parent: %v", err)
}
typ.Parent = &swift.Type{
Address: ext.ParentOffset.GetAddress(),
Name: ctx.Name,
Parent: &swift.Type{
Name: ctx.Parent,
},
}
}
typ.Name, err = f.makeSymbolicMangledNameStringRef(ext.ExtendedContext.GetAddress())
if err != nil {
return fmt.Errorf("failed to read extended context: %v", err)
}
curr, _ := r.Seek(0, io.SeekCurrent)
typ.Size = int64(curr - off)
typ.Type = &ext
return nil
}
func (f *File) parseAnonymous(r io.ReadSeeker, typ *swift.Type) (err error) {
off, _ := r.Seek(0, io.SeekCurrent) // save offset
var anon swift.Anonymous
if err := anon.TargetAnonymousContextDescriptor.Read(r, typ.Address); err != nil {
return fmt.Errorf("failed to read swift anonymous descriptor: %v", err)
}
if anon.Flags.IsGeneric() {
anon.GenericContext = &swift.GenericContext{}
if err := binary.Read(r, f.ByteOrder, &anon.GenericContext.TargetGenericContextDescriptorHeader); err != nil {
return fmt.Errorf("failed to read generic header: %v", err)
}
anon.GenericContext.Parameters = make([]swift.GenericParamDescriptor, anon.GenericContext.NumParams)
if err := binary.Read(r, f.ByteOrder, &anon.GenericContext.Parameters); err != nil {
return fmt.Errorf("failed to read generic params: %v", err)
}
curr, _ := r.Seek(0, io.SeekCurrent)
r.Seek(int64(Align(uint64(curr), 4)), io.SeekStart)
anon.GenericContext.Requirements = make([]swift.TargetGenericRequirementDescriptor, anon.GenericContext.NumRequirements)
for i := 0; i < int(anon.GenericContext.NumRequirements); i++ {
curr, _ = r.Seek(0, io.SeekCurrent)
if err := anon.GenericContext.Requirements[i].Read(r, typ.Address+uint64(curr-off)); err != nil {
return fmt.Errorf("failed to read generic requirement: %v", err)
}
}
if anon.GenericContext.Flags.HasTypePacks() {
var hdr swift.GenericPackShapeHeader
if err := binary.Read(r, f.ByteOrder, &hdr); err != nil {
return fmt.Errorf("failed to read generic pack shape header: %v", err)
}
anon.GenericContext.TypePacks = make([]swift.GenericPackShapeDescriptor, hdr.NumPacks)
if err := binary.Read(r, f.ByteOrder, &anon.GenericContext.TypePacks); err != nil {
return fmt.Errorf("failed to read generic pack shape descriptors: %v", err)
}
}
}
if anon.HasMangledName() {
curr, _ := r.Seek(0, io.SeekCurrent)