/
file.go
1303 lines (1175 loc) · 33.6 KB
/
file.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
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package macho implements access to Mach-O object files.
package macho
// High level access to low level data structures.
import (
"bytes"
"compress/zlib"
"debug/dwarf"
"encoding/binary"
"fmt"
"io"
"os"
"strings"
"unsafe"
)
// A File represents an open Mach-O file.
type File struct {
FileTOC
Symtab *Symtab
Dysymtab *Dysymtab
closer io.Closer
}
type FileTOC struct {
FileHeader
ByteOrder binary.ByteOrder
Loads []Load
Sections []*Section
}
func (t *FileTOC) AddLoad(l Load) {
t.Loads = append(t.Loads, l)
t.NCommands++
t.SizeCommands += l.LoadSize(t)
}
// AddSegment adds segment s to the file table of contents,
// and also zeroes out the segment information with the expectation
// that this will be added next.
func (t *FileTOC) AddSegment(s *Segment) {
t.AddLoad(s)
s.Nsect = 0
s.Firstsect = 0
}
// Adds section to the most recently added Segment
func (t *FileTOC) AddSection(s *Section) {
g := t.Loads[len(t.Loads)-1].(*Segment)
if g.Nsect == 0 {
g.Firstsect = uint32(len(t.Sections))
}
g.Nsect++
t.Sections = append(t.Sections, s)
sectionsize := uint32(unsafe.Sizeof(Section32{}))
if g.Command() == LcSegment64 {
sectionsize = uint32(unsafe.Sizeof(Section64{}))
}
t.SizeCommands += sectionsize
g.Len += sectionsize
}
// A Load represents any Mach-O load command.
type Load interface {
String() string
Command() LoadCmd
LoadSize(*FileTOC) uint32 // Need the TOC for alignment, sigh.
Put([]byte, binary.ByteOrder) int
// command LC_DYLD_INFO_ONLY contains offsets into __LINKEDIT
// e.g., from "otool -l a.out"
//
// Load command 3
// cmd LC_SEGMENT_64
// cmdsize 72
// segname __LINKEDIT
// vmaddr 0x0000000100002000
// vmsize 0x0000000000001000
// fileoff 8192
// filesize 520
// maxprot 0x00000007
// initprot 0x00000001
// nsects 0
// flags 0x0
// Load command 4
// cmd LC_DYLD_INFO_ONLY
// cmdsize 48
// rebase_off 8192
// rebase_size 8
// bind_off 8200
// bind_size 24
// weak_bind_off 0
// weak_bind_size 0
// lazy_bind_off 8224
// lazy_bind_size 16
// export_off 8240
// export_size 48
}
// LoadBytes is the uninterpreted bytes of a Mach-O load command.
type LoadBytes []byte
// A SegmentHeader is the header for a Mach-O 32-bit or 64-bit load segment command.
type SegmentHeader struct {
LoadCmd
Len uint32
Name string // 16 characters or fewer
Addr uint64 // memory address
Memsz uint64 // memory size
Offset uint64 // file offset
Filesz uint64 // number of bytes starting at that file offset
Maxprot uint32
Prot uint32
Nsect uint32
Flag SegFlags
Firstsect uint32
}
// A Segment represents a Mach-O 32-bit or 64-bit load segment command.
type Segment struct {
SegmentHeader
// Embed ReaderAt for ReadAt method.
// Do not embed SectionReader directly
// to avoid having Read and Seek.
// If a client wants Read and Seek it must use
// Open() to avoid fighting over the seek offset
// with other clients.
io.ReaderAt
sr *io.SectionReader
}
func (s *Segment) Put32(b []byte, o binary.ByteOrder) int {
o.PutUint32(b[0*4:], uint32(s.LoadCmd))
o.PutUint32(b[1*4:], s.Len)
putAtMost16Bytes(b[2*4:], s.Name)
o.PutUint32(b[6*4:], uint32(s.Addr))
o.PutUint32(b[7*4:], uint32(s.Memsz))
o.PutUint32(b[8*4:], uint32(s.Offset))
o.PutUint32(b[9*4:], uint32(s.Filesz))
o.PutUint32(b[10*4:], s.Maxprot)
o.PutUint32(b[11*4:], s.Prot)
o.PutUint32(b[12*4:], s.Nsect)
o.PutUint32(b[13*4:], uint32(s.Flag))
return 14 * 4
}
func (s *Segment) Put64(b []byte, o binary.ByteOrder) int {
o.PutUint32(b[0*4:], uint32(s.LoadCmd))
o.PutUint32(b[1*4:], s.Len)
putAtMost16Bytes(b[2*4:], s.Name)
o.PutUint64(b[6*4+0*8:], s.Addr)
o.PutUint64(b[6*4+1*8:], s.Memsz)
o.PutUint64(b[6*4+2*8:], s.Offset)
o.PutUint64(b[6*4+3*8:], s.Filesz)
o.PutUint32(b[6*4+4*8:], s.Maxprot)
o.PutUint32(b[7*4+4*8:], s.Prot)
o.PutUint32(b[8*4+4*8:], s.Nsect)
o.PutUint32(b[9*4+4*8:], uint32(s.Flag))
return 10*4 + 4*8
}
// LoadCmdBytes is a command-tagged sequence of bytes.
// This is used for Load Commands that are not (yet)
// interesting to us, and to common up this behavior for
// all those that are.
type LoadCmdBytes struct {
LoadCmd
LoadBytes
}
type SectionHeader struct {
Name string
Seg string
Addr uint64
Size uint64
Offset uint32
Align uint32
Reloff uint32
Nreloc uint32
Flags SecFlags
Reserved1 uint32
Reserved2 uint32
Reserved3 uint32 // only present if original was 64-bit
}
// A Reloc represents a Mach-O relocation.
type Reloc struct {
Addr uint32
Value uint32
// when Scattered == false && Extern == true, Value is the symbol number.
// when Scattered == false && Extern == false, Value is the section number.
// when Scattered == true, Value is the value that this reloc refers to.
Type uint8
Len uint8 // 0=byte, 1=word, 2=long, 3=quad
Pcrel bool
Extern bool // valid if Scattered == false
Scattered bool
}
type Section struct {
SectionHeader
Relocs []Reloc
// Embed ReaderAt for ReadAt method.
// Do not embed SectionReader directly
// to avoid having Read and Seek.
// If a client wants Read and Seek it must use
// Open() to avoid fighting over the seek offset
// with other clients.
io.ReaderAt
sr *io.SectionReader
}
func (s *Section) Put32(b []byte, o binary.ByteOrder) int {
putAtMost16Bytes(b[0:], s.Name)
putAtMost16Bytes(b[16:], s.Seg)
o.PutUint32(b[8*4:], uint32(s.Addr))
o.PutUint32(b[9*4:], uint32(s.Size))
o.PutUint32(b[10*4:], s.Offset)
o.PutUint32(b[11*4:], s.Align)
o.PutUint32(b[12*4:], s.Reloff)
o.PutUint32(b[13*4:], s.Nreloc)
o.PutUint32(b[14*4:], uint32(s.Flags))
o.PutUint32(b[15*4:], s.Reserved1)
o.PutUint32(b[16*4:], s.Reserved2)
a := 17 * 4
return a + s.PutRelocs(b[a:], o)
}
func (s *Section) Put64(b []byte, o binary.ByteOrder) int {
putAtMost16Bytes(b[0:], s.Name)
putAtMost16Bytes(b[16:], s.Seg)
o.PutUint64(b[8*4+0*8:], s.Addr)
o.PutUint64(b[8*4+1*8:], s.Size)
o.PutUint32(b[8*4+2*8:], s.Offset)
o.PutUint32(b[9*4+2*8:], s.Align)
o.PutUint32(b[10*4+2*8:], s.Reloff)
o.PutUint32(b[11*4+2*8:], s.Nreloc)
o.PutUint32(b[12*4+2*8:], uint32(s.Flags))
o.PutUint32(b[13*4+2*8:], s.Reserved1)
o.PutUint32(b[14*4+2*8:], s.Reserved2)
o.PutUint32(b[15*4+2*8:], s.Reserved3)
a := 16*4 + 2*8
return a + s.PutRelocs(b[a:], o)
}
func (s *Section) PutRelocs(b []byte, o binary.ByteOrder) int {
a := 0
for _, r := range s.Relocs {
var ri relocInfo
typ := uint32(r.Type) & (1<<4 - 1)
len := uint32(r.Len) & (1<<2 - 1)
pcrel := uint32(0)
if r.Pcrel {
pcrel = 1
}
ext := uint32(0)
if r.Extern {
ext = 1
}
switch {
case r.Scattered:
ri.Addr = r.Addr&(1<<24-1) | typ<<24 | len<<28 | 1<<31 | pcrel<<30
ri.Symnum = r.Value
case o == binary.LittleEndian:
ri.Addr = r.Addr
ri.Symnum = r.Value&(1<<24-1) | pcrel<<24 | len<<25 | ext<<27 | typ<<28
case o == binary.BigEndian:
ri.Addr = r.Addr
ri.Symnum = r.Value<<8 | pcrel<<7 | len<<5 | ext<<4 | typ
}
o.PutUint32(b, ri.Addr)
o.PutUint32(b[4:], ri.Symnum)
a += 8
b = b[8:]
}
return a
}
func putAtMost16Bytes(b []byte, n string) {
for i := range n { // at most 16 bytes
if i == 16 {
break
}
b[i] = n[i]
}
}
// A Symbol is a Mach-O 32-bit or 64-bit symbol table entry.
type Symbol struct {
Name string
Type uint8
Sect uint8
Desc uint16
Value uint64
}
/*
* Mach-O reader
*/
// FormatError is returned by some operations if the data does
// not have the correct format for an object file.
type FormatError struct {
off int64
msg string
}
func formatError(off int64, format string, data ...interface{}) *FormatError {
return &FormatError{off, fmt.Sprintf(format, data...)}
}
func (e *FormatError) Error() string {
return e.msg + fmt.Sprintf(" in record at byte %#x", e.off)
}
func (e *FormatError) String() string {
return e.Error()
}
// DerivedCopy returns a modified copy of the TOC, with empty loads and sections,
// and with the specified header type and flags.
func (t *FileTOC) DerivedCopy(Type HdrType, Flags HdrFlags) *FileTOC {
h := t.FileHeader
h.NCommands, h.SizeCommands, h.Type, h.Flags = 0, 0, Type, Flags
return &FileTOC{FileHeader: h, ByteOrder: t.ByteOrder}
}
// TOCSize returns the size in bytes of the object file representation
// of the header and Load Commands (including Segments and Sections, but
// not their contents) at the beginning of a Mach-O file. This typically
// overlaps the text segment in the object file.
func (t *FileTOC) TOCSize() uint32 {
return t.HdrSize() + t.LoadSize()
}
// LoadAlign returns the required alignment of Load commands in a binary.
// This is used to add padding for necessary alignment.
func (t *FileTOC) LoadAlign() uint64 {
if t.Magic == Magic64 {
return 8
}
return 4
}
// SymbolSize returns the size in bytes of a Symbol (Nlist32 or Nlist64)
func (t *FileTOC) SymbolSize() uint32 {
if t.Magic == Magic64 {
return uint32(unsafe.Sizeof(Nlist64{}))
}
return uint32(unsafe.Sizeof(Nlist32{}))
}
// HdrSize returns the size in bytes of the Macho header for a given
// magic number (where the magic number has been appropriately byte-swapped).
func (t *FileTOC) HdrSize() uint32 {
switch t.Magic {
case Magic32:
return fileHeaderSize32
case Magic64:
return fileHeaderSize64
case MagicFat:
panic("MagicFat not handled yet")
default:
panic(fmt.Sprintf("Unexpected magic number 0x%x, expected Mach-O object file", t.Magic))
}
}
// LoadSize returns the size of all the load commands in a file's table-of contents
// (but not their associated data, e.g., sections and symbol tables)
func (t *FileTOC) LoadSize() uint32 {
cmdsz := uint32(0)
for _, l := range t.Loads {
s := l.LoadSize(t)
cmdsz += s
}
return cmdsz
}
// FileSize returns the size in bytes of the header, load commands, and the
// in-file contents of all the segments and sections included in those
// load commands, accounting for their offsets within the file.
func (t *FileTOC) FileSize() uint64 {
sz := uint64(t.LoadSize()) // ought to be contained in text segment, but just in case.
for _, l := range t.Loads {
if s, ok := l.(*Segment); ok {
if m := s.Offset + s.Filesz; m > sz {
sz = m
}
}
}
return sz
}
// Put writes the header and all load commands to buffer, using
// the byte ordering specified in FileTOC t. For sections, this
// writes the headers that come in-line with the segment Load commands,
// but does not write the reference data for those sections.
func (t *FileTOC) Put(buffer []byte) int {
next := t.FileHeader.Put(buffer, t.ByteOrder)
for _, l := range t.Loads {
if s, ok := l.(*Segment); ok {
switch t.Magic {
case Magic64:
next += s.Put64(buffer[next:], t.ByteOrder)
for i := uint32(0); i < s.Nsect; i++ {
c := t.Sections[i+s.Firstsect]
next += c.Put64(buffer[next:], t.ByteOrder)
}
case Magic32:
next += s.Put32(buffer[next:], t.ByteOrder)
for i := uint32(0); i < s.Nsect; i++ {
c := t.Sections[i+s.Firstsect]
next += c.Put32(buffer[next:], t.ByteOrder)
}
default:
panic(fmt.Sprintf("Unexpected magic number 0x%x", t.Magic))
}
} else {
next += l.Put(buffer[next:], t.ByteOrder)
}
}
return next
}
// UncompressedSize returns the size of the segment with its sections uncompressed, ignoring
// its offset within the file. The returned size is rounded up to the power of two in align.
func (s *Segment) UncompressedSize(t *FileTOC, align uint64) uint64 {
sz := uint64(0)
for j := uint32(0); j < s.Nsect; j++ {
c := t.Sections[j+s.Firstsect]
sz += c.UncompressedSize()
}
return (sz + align - 1) & uint64(-int64(align))
}
func (s *Section) UncompressedSize() uint64 {
if !strings.HasPrefix(s.Name, "__z") {
return s.Size
}
b := make([]byte, 12)
n, err := s.sr.ReadAt(b, 0)
if err != nil {
panic("Malformed object file")
}
if n != len(b) {
return s.Size
}
if string(b[:4]) == "ZLIB" {
return binary.BigEndian.Uint64(b[4:12])
}
return s.Size
}
func (s *Section) PutData(b []byte) {
bb := b[0:s.Size]
n, err := s.sr.ReadAt(bb, 0)
if err != nil || uint64(n) != s.Size {
panic("Malformed object file (ReadAt error)")
}
}
func (s *Section) PutUncompressedData(b []byte) {
if strings.HasPrefix(s.Name, "__z") {
bb := make([]byte, 12)
n, err := s.sr.ReadAt(bb, 0)
if err != nil {
panic("Malformed object file")
}
if n == len(bb) && string(bb[:4]) == "ZLIB" {
size := binary.BigEndian.Uint64(bb[4:12])
// Decompress starting at b[12:]
r, err := zlib.NewReader(io.NewSectionReader(s, 12, int64(size)-12))
if err != nil {
panic("Malformed object file (zlib.NewReader error)")
}
n, err := io.ReadFull(r, b[0:size])
if err != nil {
panic("Malformed object file (ReadFull error)")
}
if uint64(n) != size {
panic(fmt.Sprintf("PutUncompressedData, expected to read %d bytes, instead read %d", size, n))
}
if err := r.Close(); err != nil {
panic("Malformed object file (Close error)")
}
return
}
}
// Not compressed
s.PutData(b)
}
func (b LoadBytes) String() string {
s := "["
for i, a := range b {
if i > 0 {
s += " "
if len(b) > 48 && i >= 16 {
s += fmt.Sprintf("... (%d bytes)", len(b))
break
}
}
s += fmt.Sprintf("%x", a)
}
s += "]"
return s
}
func (b LoadBytes) Raw() []byte { return b }
func (b LoadBytes) Copy() LoadBytes { return LoadBytes(append([]byte{}, b...)) }
func (b LoadBytes) LoadSize(t *FileTOC) uint32 { return uint32(len(b)) }
func (lc LoadCmd) Put(b []byte, o binary.ByteOrder) int {
panic(fmt.Sprintf("Put not implemented for %s", lc.String()))
}
func (s LoadCmdBytes) String() string {
return s.LoadCmd.String() + ": " + s.LoadBytes.String()
}
func (s LoadCmdBytes) Copy() LoadCmdBytes {
return LoadCmdBytes{LoadCmd: s.LoadCmd, LoadBytes: s.LoadBytes.Copy()}
}
func (s *SegmentHeader) String() string {
return fmt.Sprintf(
"Seg %s, len=0x%x, addr=0x%x, memsz=0x%x, offset=0x%x, filesz=0x%x, maxprot=0x%x, prot=0x%x, nsect=%d, flag=0x%x, firstsect=%d",
s.Name, s.Len, s.Addr, s.Memsz, s.Offset, s.Filesz, s.Maxprot, s.Prot, s.Nsect, s.Flag, s.Firstsect)
}
func (s *Segment) String() string {
return fmt.Sprintf(
"Seg %s, len=0x%x, addr=0x%x, memsz=0x%x, offset=0x%x, filesz=0x%x, maxprot=0x%x, prot=0x%x, nsect=%d, flag=0x%x, firstsect=%d",
s.Name, s.Len, s.Addr, s.Memsz, s.Offset, s.Filesz, s.Maxprot, s.Prot, s.Nsect, s.Flag, s.Firstsect)
}
// Data reads and returns the contents of the segment.
func (s *Segment) Data() ([]byte, error) {
dat := make([]byte, s.sr.Size())
n, err := s.sr.ReadAt(dat, 0)
if n == len(dat) {
err = nil
}
return dat[0:n], err
}
func (s *Segment) Copy() *Segment {
r := &Segment{SegmentHeader: s.SegmentHeader}
return r
}
func (s *Segment) CopyZeroed() *Segment {
r := s.Copy()
r.Filesz = 0
r.Offset = 0
r.Nsect = 0
r.Firstsect = 0
if s.Command() == LcSegment64 {
r.Len = uint32(unsafe.Sizeof(Segment64{}))
} else {
r.Len = uint32(unsafe.Sizeof(Segment32{}))
}
return r
}
func (s *Segment) LoadSize(t *FileTOC) uint32 {
if s.Command() == LcSegment64 {
return uint32(unsafe.Sizeof(Segment64{})) + uint32(s.Nsect)*uint32(unsafe.Sizeof(Section64{}))
}
return uint32(unsafe.Sizeof(Segment32{})) + uint32(s.Nsect)*uint32(unsafe.Sizeof(Section32{}))
}
// Open returns a new ReadSeeker reading the segment.
func (s *Segment) Open() io.ReadSeeker { return io.NewSectionReader(s.sr, 0, 1<<63-1) }
// Data reads and returns the contents of the Mach-O section.
func (s *Section) Data() ([]byte, error) {
dat := make([]byte, s.sr.Size())
n, err := s.sr.ReadAt(dat, 0)
if n == len(dat) {
err = nil
}
return dat[0:n], err
}
func (s *Section) Copy() *Section {
return &Section{SectionHeader: s.SectionHeader}
}
// Open returns a new ReadSeeker reading the Mach-O section.
func (s *Section) Open() io.ReadSeeker { return io.NewSectionReader(s.sr, 0, 1<<63-1) }
// A Dylib represents a Mach-O load dynamic library command.
type Dylib struct {
DylibCmd
Name string
Time uint32
CurrentVersion uint32
CompatVersion uint32
}
func (s *Dylib) String() string { return "Dylib " + s.Name }
func (s *Dylib) Copy() *Dylib {
r := *s
return &r
}
func (s *Dylib) LoadSize(t *FileTOC) uint32 {
return uint32(RoundUp(uint64(unsafe.Sizeof(DylibCmd{}))+uint64(len(s.Name)), t.LoadAlign()))
}
type Dylinker struct {
DylinkerCmd // shared by 3 commands, need the LoadCmd
Name string
}
func (s *Dylinker) String() string { return s.DylinkerCmd.LoadCmd.String() + " " + s.Name }
func (s *Dylinker) Copy() *Dylinker {
return &Dylinker{DylinkerCmd: s.DylinkerCmd, Name: s.Name}
}
func (s *Dylinker) LoadSize(t *FileTOC) uint32 {
return uint32(RoundUp(uint64(unsafe.Sizeof(DylinkerCmd{}))+uint64(len(s.Name)), t.LoadAlign()))
}
// A Symtab represents a Mach-O symbol table command.
type Symtab struct {
SymtabCmd
Syms []Symbol
}
func (s *Symtab) Put(b []byte, o binary.ByteOrder) int {
o.PutUint32(b[0*4:], uint32(s.LoadCmd))
o.PutUint32(b[1*4:], s.Len)
o.PutUint32(b[2*4:], s.Symoff)
o.PutUint32(b[3*4:], s.Nsyms)
o.PutUint32(b[4*4:], s.Stroff)
o.PutUint32(b[5*4:], s.Strsize)
return 6 * 4
}
func (s *Symtab) String() string { return fmt.Sprintf("Symtab %#v", s.SymtabCmd) }
func (s *Symtab) Copy() *Symtab {
return &Symtab{SymtabCmd: s.SymtabCmd, Syms: append([]Symbol{}, s.Syms...)}
}
func (s *Symtab) LoadSize(t *FileTOC) uint32 {
return uint32(unsafe.Sizeof(SymtabCmd{}))
}
type LinkEditData struct {
LinkEditDataCmd
}
func (s *LinkEditData) String() string { return "LinkEditData " + s.LoadCmd.String() }
func (s *LinkEditData) Copy() *LinkEditData {
return &LinkEditData{LinkEditDataCmd: s.LinkEditDataCmd}
}
func (s *LinkEditData) LoadSize(t *FileTOC) uint32 {
return uint32(unsafe.Sizeof(LinkEditDataCmd{}))
}
type Uuid struct {
UuidCmd
}
func (s *Uuid) String() string {
return fmt.Sprintf("Uuid %X-%X-%X-%X-%X",
s.Id[0:4], s.Id[4:6], s.Id[6:8], s.Id[8:10], s.Id[10:16])
} // 8-4-4-4-12
func (s *Uuid) Copy() *Uuid {
return &Uuid{UuidCmd: s.UuidCmd}
}
func (s *Uuid) LoadSize(t *FileTOC) uint32 {
return uint32(unsafe.Sizeof(UuidCmd{}))
}
func (s *Uuid) Put(b []byte, o binary.ByteOrder) int {
o.PutUint32(b[0*4:], uint32(s.LoadCmd))
o.PutUint32(b[1*4:], s.Len)
copy(b[2*4:], s.Id[0:])
return int(s.Len)
}
type DyldInfo struct {
DyldInfoCmd
}
func (s *DyldInfo) String() string { return "DyldInfo " + s.LoadCmd.String() }
func (s *DyldInfo) Copy() *DyldInfo {
return &DyldInfo{DyldInfoCmd: s.DyldInfoCmd}
}
func (s *DyldInfo) LoadSize(t *FileTOC) uint32 {
return uint32(unsafe.Sizeof(DyldInfoCmd{}))
}
type EncryptionInfo struct {
EncryptionInfoCmd
}
func (s *EncryptionInfo) String() string { return "EncryptionInfo " + s.LoadCmd.String() }
func (s *EncryptionInfo) Copy() *EncryptionInfo {
return &EncryptionInfo{EncryptionInfoCmd: s.EncryptionInfoCmd}
}
func (s *EncryptionInfo) LoadSize(t *FileTOC) uint32 {
return uint32(unsafe.Sizeof(EncryptionInfoCmd{}))
}
// A Dysymtab represents a Mach-O dynamic symbol table command.
type Dysymtab struct {
DysymtabCmd
IndirectSyms []uint32 // indices into Symtab.Syms
}
func (s *Dysymtab) String() string { return fmt.Sprintf("Dysymtab %#v", s.DysymtabCmd) }
func (s *Dysymtab) Copy() *Dysymtab {
return &Dysymtab{DysymtabCmd: s.DysymtabCmd, IndirectSyms: append([]uint32{}, s.IndirectSyms...)}
}
func (s *Dysymtab) LoadSize(t *FileTOC) uint32 {
return uint32(unsafe.Sizeof(DysymtabCmd{}))
}
// A Rpath represents a Mach-O rpath command.
type Rpath struct {
LoadCmd
Path string
}
func (s *Rpath) String() string { return "Rpath " + s.Path }
func (s *Rpath) Command() LoadCmd { return LcRpath }
func (s *Rpath) Copy() *Rpath {
return &Rpath{Path: s.Path}
}
func (s *Rpath) LoadSize(t *FileTOC) uint32 {
return uint32(RoundUp(uint64(unsafe.Sizeof(RpathCmd{}))+uint64(len(s.Path)), t.LoadAlign()))
}
// Open opens the named file using os.Open and prepares it for use as a Mach-O binary.
func Open(name string) (*File, error) {
f, err := os.Open(name)
if err != nil {
return nil, err
}
ff, err := NewFile(f)
if err != nil {
f.Close()
return nil, err
}
ff.closer = f
return ff, nil
}
// Close closes the File.
// If the File was created using NewFile directly instead of Open,
// Close has no effect.
func (f *File) Close() error {
var err error
if f.closer != nil {
err = f.closer.Close()
f.closer = nil
}
return err
}
// NewFile creates a new File for accessing a Mach-O binary in an underlying reader.
// The Mach-O binary is expected to start at position 0 in the ReaderAt.
func NewFile(r io.ReaderAt) (*File, error) {
f := new(File)
sr := io.NewSectionReader(r, 0, 1<<63-1)
// Read and decode Mach magic to determine byte order, size.
// Magic32 and Magic64 differ only in the bottom bit.
var ident [4]byte
if _, err := r.ReadAt(ident[0:], 0); err != nil {
return nil, err
}
be := binary.BigEndian.Uint32(ident[0:])
le := binary.LittleEndian.Uint32(ident[0:])
switch Magic32 &^ 1 {
case be &^ 1:
f.ByteOrder = binary.BigEndian
f.Magic = be
case le &^ 1:
f.ByteOrder = binary.LittleEndian
f.Magic = le
default:
return nil, formatError(0, "invalid magic number be=0x%x, le=0x%x", be, le)
}
// Read entire file header.
if err := binary.Read(sr, f.ByteOrder, &f.FileHeader); err != nil {
return nil, err
}
// Then load commands.
offset := int64(fileHeaderSize32)
if f.Magic == Magic64 {
offset = fileHeaderSize64
}
dat := make([]byte, f.SizeCommands)
if _, err := r.ReadAt(dat, offset); err != nil {
return nil, err
}
f.Loads = make([]Load, f.NCommands)
bo := f.ByteOrder
for i := range f.Loads {
// Each load command begins with uint32 command and length.
if len(dat) < 8 {
return nil, formatError(offset, "command block too small, len(dat) = %d", len(dat))
}
cmd, siz := LoadCmd(bo.Uint32(dat[0:4])), bo.Uint32(dat[4:8])
if siz < 8 || siz > uint32(len(dat)) {
return nil, formatError(offset, "invalid command block size, len(dat)=%d, size=%d", len(dat), siz)
}
var cmddat []byte
cmddat, dat = dat[0:siz], dat[siz:]
offset += int64(siz)
var s *Segment
switch cmd {
default:
f.Loads[i] = LoadCmdBytes{LoadCmd(cmd), LoadBytes(cmddat)}
case LcUuid:
var hdr UuidCmd
b := bytes.NewReader(cmddat)
if err := binary.Read(b, bo, &hdr); err != nil {
return nil, err
}
l := &Uuid{UuidCmd: hdr}
f.Loads[i] = l
case LcRpath:
var hdr RpathCmd
b := bytes.NewReader(cmddat)
if err := binary.Read(b, bo, &hdr); err != nil {
return nil, err
}
l := &Rpath{LoadCmd: hdr.LoadCmd}
if hdr.Path >= uint32(len(cmddat)) {
return nil, formatError(offset, "invalid path in rpath command, len(cmddat)=%d, hdr.Path=%d", len(cmddat), hdr.Path)
}
l.Path = cstring(cmddat[hdr.Path:])
f.Loads[i] = l
case LcLoadDylinker, LcIdDylinker, LcDyldEnvironment:
var hdr DylinkerCmd
b := bytes.NewReader(cmddat)
if err := binary.Read(b, bo, &hdr); err != nil {
return nil, err
}
l := new(Dylinker)
if hdr.Name >= uint32(len(cmddat)) {
return nil, formatError(offset, "invalid name in dynamic linker command, hdr.Name=%d, len(cmddat)=%d", hdr.Name, len(cmddat))
}
l.Name = cstring(cmddat[hdr.Name:])
l.DylinkerCmd = hdr
f.Loads[i] = l
case LcDylib:
var hdr DylibCmd
b := bytes.NewReader(cmddat)
if err := binary.Read(b, bo, &hdr); err != nil {
return nil, err
}
l := new(Dylib)
if hdr.Name >= uint32(len(cmddat)) {
return nil, formatError(offset, "invalid name in dynamic library command, hdr.Name=%d, len(cmddat)=%d", hdr.Name, len(cmddat))
}
l.Name = cstring(cmddat[hdr.Name:])
l.Time = hdr.Time
l.CurrentVersion = hdr.CurrentVersion
l.CompatVersion = hdr.CompatVersion
f.Loads[i] = l
case LcSymtab:
var hdr SymtabCmd
b := bytes.NewReader(cmddat)
if err := binary.Read(b, bo, &hdr); err != nil {
return nil, err
}
strtab := make([]byte, hdr.Strsize)
if _, err := r.ReadAt(strtab, int64(hdr.Stroff)); err != nil {
return nil, err
}
var symsz int
if f.Magic == Magic64 {
symsz = 16
} else {
symsz = 12
}
symdat := make([]byte, int(hdr.Nsyms)*symsz)
if _, err := r.ReadAt(symdat, int64(hdr.Symoff)); err != nil {
return nil, err
}
st, err := f.parseSymtab(symdat, strtab, cmddat, &hdr, offset)
st.SymtabCmd = hdr
if err != nil {
return nil, err
}
f.Loads[i] = st
f.Symtab = st
case LcDysymtab:
var hdr DysymtabCmd
b := bytes.NewReader(cmddat)
if err := binary.Read(b, bo, &hdr); err != nil {
return nil, err
}
dat := make([]byte, hdr.Nindirectsyms*4)
if _, err := r.ReadAt(dat, int64(hdr.Indirectsymoff)); err != nil {
return nil, err
}
x := make([]uint32, hdr.Nindirectsyms)
if err := binary.Read(bytes.NewReader(dat), bo, x); err != nil {
return nil, err
}
st := new(Dysymtab)
st.DysymtabCmd = hdr
st.IndirectSyms = x
f.Loads[i] = st
f.Dysymtab = st
case LcSegment:
var seg32 Segment32
b := bytes.NewReader(cmddat)
if err := binary.Read(b, bo, &seg32); err != nil {
return nil, err
}
s = new(Segment)
s.LoadCmd = cmd
s.Len = siz
s.Name = cstring(seg32.Name[0:])
s.Addr = uint64(seg32.Addr)
s.Memsz = uint64(seg32.Memsz)
s.Offset = uint64(seg32.Offset)
s.Filesz = uint64(seg32.Filesz)
s.Maxprot = seg32.Maxprot
s.Prot = seg32.Prot
s.Nsect = seg32.Nsect
s.Flag = seg32.Flag
s.Firstsect = uint32(len(f.Sections))
f.Loads[i] = s
for i := 0; i < int(s.Nsect); i++ {
var sh32 Section32
if err := binary.Read(b, bo, &sh32); err != nil {
return nil, err
}
sh := new(Section)
sh.Name = cstring(sh32.Name[0:])
sh.Seg = cstring(sh32.Seg[0:])
sh.Addr = uint64(sh32.Addr)
sh.Size = uint64(sh32.Size)
sh.Offset = sh32.Offset
sh.Align = sh32.Align
sh.Reloff = sh32.Reloff
sh.Nreloc = sh32.Nreloc
sh.Flags = sh32.Flags
sh.Reserved1 = sh32.Reserve1
sh.Reserved2 = sh32.Reserve2
if err := f.pushSection(sh, r); err != nil {
return nil, err
}
}
case LcSegment64:
var seg64 Segment64
b := bytes.NewReader(cmddat)
if err := binary.Read(b, bo, &seg64); err != nil {
return nil, err
}
s = new(Segment)
s.LoadCmd = cmd
s.Len = siz
s.Name = cstring(seg64.Name[0:])
s.Addr = seg64.Addr
s.Memsz = seg64.Memsz
s.Offset = seg64.Offset
s.Filesz = seg64.Filesz
s.Maxprot = seg64.Maxprot
s.Prot = seg64.Prot
s.Nsect = seg64.Nsect
s.Flag = seg64.Flag
s.Firstsect = uint32(len(f.Sections))
f.Loads[i] = s
for i := 0; i < int(s.Nsect); i++ {
var sh64 Section64
if err := binary.Read(b, bo, &sh64); err != nil {
return nil, err
}
sh := new(Section)
sh.Name = cstring(sh64.Name[0:])
sh.Seg = cstring(sh64.Seg[0:])
sh.Addr = sh64.Addr
sh.Size = sh64.Size