Debian Codegraph @

cmd/splitdwarf/internal/macho/file.go

raw symbols SCIP
1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // Package macho implements access to Mach-O object files.
6 package macho
7
8 // High level access to low level data structures.
9
10 import (
11 "bytes"
12 "compress/zlib"
13 "debug/dwarf"
14 "encoding/binary"
15 "fmt"
16 "io"
17 "os"
18 "slices"
19 "strings"
20 "unsafe"
21 )
22
23 // A File represents an open Mach-O file.
24 type File struct {
25 FileTOC
26
27 Symtab *Symtab
28 Dysymtab *Dysymtab
29
30 closer io.Closer
31 }
32
33 type FileTOC struct {
34 FileHeader
35 ByteOrder binary.ByteOrder
36 Loads []Load
37 Sections []*Section
38 }
39
40 func (t *FileTOC) AddLoad(l Load) {
41 t.Loads = append(t.Loads, l)
42 t.NCommands++
43 t.SizeCommands += l.LoadSize(t)
44 }
45
46 // AddSegment adds segment s to the file table of contents,
47 // and also zeroes out the segment information with the expectation
48 // that this will be added next.
49 func (t *FileTOC) AddSegment(s *Segment) {
50 t.AddLoad(s)
51 s.Nsect = 0
52 s.Firstsect = 0
53 }
54
55 // Adds section to the most recently added Segment
56 func (t *FileTOC) AddSection(s *Section) {
57 g := t.Loads[len(t.Loads)-1].(*Segment)
58 if g.Nsect == 0 {
59 g.Firstsect = uint32(len(t.Sections))
60 }
61 g.Nsect++
62 t.Sections = append(t.Sections, s)
63 sectionsize := uint32(unsafe.Sizeof(Section32{}))
64 if g.Command() == LcSegment64 {
65 sectionsize = uint32(unsafe.Sizeof(Section64{}))
66 }
67 t.SizeCommands += sectionsize
68 g.Len += sectionsize
69 }
70
71 // A Load represents any Mach-O load command.
72 type Load interface {
73 String() string
74 Command() LoadCmd
75 LoadSize(*FileTOC) uint32 // Need the TOC for alignment, sigh.
76 Put([]byte, binary.ByteOrder) int
77
78 // command LC_DYLD_INFO_ONLY contains offsets into __LINKEDIT
79 // e.g., from "otool -l a.out"
80 //
81 // Load command 3
82 // cmd LC_SEGMENT_64
83 // cmdsize 72
84 // segname __LINKEDIT
85 // vmaddr 0x0000000100002000
86 // vmsize 0x0000000000001000
87 // fileoff 8192
88 // filesize 520
89 // maxprot 0x00000007
90 // initprot 0x00000001
91 // nsects 0
92 // flags 0x0
93 // Load command 4
94 // cmd LC_DYLD_INFO_ONLY
95 // cmdsize 48
96 // rebase_off 8192
97 // rebase_size 8
98 // bind_off 8200
99 // bind_size 24
100 // weak_bind_off 0
101 // weak_bind_size 0
102 // lazy_bind_off 8224
103 // lazy_bind_size 16
104 // export_off 8240
105 // export_size 48
106 }
107
108 // LoadBytes is the uninterpreted bytes of a Mach-O load command.
109 type LoadBytes []byte
110
111 // A SegmentHeader is the header for a Mach-O 32-bit or 64-bit load segment command.
112 type SegmentHeader struct {
113 LoadCmd
114 Len uint32
115 Name string // 16 characters or fewer
116 Addr uint64 // memory address
117 Memsz uint64 // memory size
118 Offset uint64 // file offset
119 Filesz uint64 // number of bytes starting at that file offset
120 Maxprot uint32
121 Prot uint32
122 Nsect uint32
123 Flag SegFlags
124 Firstsect uint32
125 }
126
127 // A Segment represents a Mach-O 32-bit or 64-bit load segment command.
128 type Segment struct {
129 SegmentHeader
130
131 // Embed ReaderAt for ReadAt method.
132 // Do not embed SectionReader directly
133 // to avoid having Read and Seek.
134 // If a client wants Read and Seek it must use
135 // Open() to avoid fighting over the seek offset
136 // with other clients.
137 io.ReaderAt
138 sr *io.SectionReader
139 }
140
141 func (s *Segment) Put32(b []byte, o binary.ByteOrder) int {
142 o.PutUint32(b[0*4:], uint32(s.LoadCmd))
143 o.PutUint32(b[1*4:], s.Len)
144 putAtMost16Bytes(b[2*4:], s.Name)
145 o.PutUint32(b[6*4:], uint32(s.Addr))
146 o.PutUint32(b[7*4:], uint32(s.Memsz))
147 o.PutUint32(b[8*4:], uint32(s.Offset))
148 o.PutUint32(b[9*4:], uint32(s.Filesz))
149 o.PutUint32(b[10*4:], s.Maxprot)
150 o.PutUint32(b[11*4:], s.Prot)
151 o.PutUint32(b[12*4:], s.Nsect)
152 o.PutUint32(b[13*4:], uint32(s.Flag))
153 return 14 * 4
154 }
155
156 func (s *Segment) Put64(b []byte, o binary.ByteOrder) int {
157 o.PutUint32(b[0*4:], uint32(s.LoadCmd))
158 o.PutUint32(b[1*4:], s.Len)
159 putAtMost16Bytes(b[2*4:], s.Name)
160 o.PutUint64(b[6*4+0*8:], s.Addr)
161 o.PutUint64(b[6*4+1*8:], s.Memsz)
162 o.PutUint64(b[6*4+2*8:], s.Offset)
163 o.PutUint64(b[6*4+3*8:], s.Filesz)
164 o.PutUint32(b[6*4+4*8:], s.Maxprot)
165 o.PutUint32(b[7*4+4*8:], s.Prot)
166 o.PutUint32(b[8*4+4*8:], s.Nsect)
167 o.PutUint32(b[9*4+4*8:], uint32(s.Flag))
168 return 10*4 + 4*8
169 }
170
171 // LoadCmdBytes is a command-tagged sequence of bytes.
172 // This is used for Load Commands that are not (yet)
173 // interesting to us, and to common up this behavior for
174 // all those that are.
175 type LoadCmdBytes struct {
176 LoadCmd
177 LoadBytes
178 }
179
180 type SectionHeader struct {
181 Name string
182 Seg string
183 Addr uint64
184 Size uint64
185 Offset uint32
186 Align uint32
187 Reloff uint32
188 Nreloc uint32
189 Flags SecFlags
190 Reserved1 uint32
191 Reserved2 uint32
192 Reserved3 uint32 // only present if original was 64-bit
193 }
194
195 // A Reloc represents a Mach-O relocation.
196 type Reloc struct {
197 Addr uint32
198 Value uint32
199 // when Scattered == false && Extern == true, Value is the symbol number.
200 // when Scattered == false && Extern == false, Value is the section number.
201 // when Scattered == true, Value is the value that this reloc refers to.
202 Type uint8
203 Len uint8 // 0=byte, 1=word, 2=long, 3=quad
204 Pcrel bool
205 Extern bool // valid if Scattered == false
206 Scattered bool
207 }
208
209 type Section struct {
210 SectionHeader
211 Relocs []Reloc
212
213 // Embed ReaderAt for ReadAt method.
214 // Do not embed SectionReader directly
215 // to avoid having Read and Seek.
216 // If a client wants Read and Seek it must use
217 // Open() to avoid fighting over the seek offset
218 // with other clients.
219 io.ReaderAt
220 sr *io.SectionReader
221 }
222
223 func (s *Section) Put32(b []byte, o binary.ByteOrder) int {
224 putAtMost16Bytes(b[0:], s.Name)
225 putAtMost16Bytes(b[16:], s.Seg)
226 o.PutUint32(b[8*4:], uint32(s.Addr))
227 o.PutUint32(b[9*4:], uint32(s.Size))
228 o.PutUint32(b[10*4:], s.Offset)
229 o.PutUint32(b[11*4:], s.Align)
230 o.PutUint32(b[12*4:], s.Reloff)
231 o.PutUint32(b[13*4:], s.Nreloc)
232 o.PutUint32(b[14*4:], uint32(s.Flags))
233 o.PutUint32(b[15*4:], s.Reserved1)
234 o.PutUint32(b[16*4:], s.Reserved2)
235 a := 17 * 4
236 return a + s.PutRelocs(b[a:], o)
237 }
238
239 func (s *Section) Put64(b []byte, o binary.ByteOrder) int {
240 putAtMost16Bytes(b[0:], s.Name)
241 putAtMost16Bytes(b[16:], s.Seg)
242 o.PutUint64(b[8*4+0*8:], s.Addr)
243 o.PutUint64(b[8*4+1*8:], s.Size)
244 o.PutUint32(b[8*4+2*8:], s.Offset)
245 o.PutUint32(b[9*4+2*8:], s.Align)
246 o.PutUint32(b[10*4+2*8:], s.Reloff)
247 o.PutUint32(b[11*4+2*8:], s.Nreloc)
248 o.PutUint32(b[12*4+2*8:], uint32(s.Flags))
249 o.PutUint32(b[13*4+2*8:], s.Reserved1)
250 o.PutUint32(b[14*4+2*8:], s.Reserved2)
251 o.PutUint32(b[15*4+2*8:], s.Reserved3)
252 a := 16*4 + 2*8
253 return a + s.PutRelocs(b[a:], o)
254 }
255
256 func (s *Section) PutRelocs(b []byte, o binary.ByteOrder) int {
257 a := 0
258 for _, r := range s.Relocs {
259 var ri relocInfo
260 typ := uint32(r.Type) & (1<<4 - 1)
261 len := uint32(r.Len) & (1<<2 - 1)
262 pcrel := uint32(0)
263 if r.Pcrel {
264 pcrel = 1
265 }
266 ext := uint32(0)
267 if r.Extern {
268 ext = 1
269 }
270 switch {
271 case r.Scattered:
272 ri.Addr = r.Addr&(1<<24-1) | typ<<24 | len<<28 | 1<<31 | pcrel<<30
273 ri.Symnum = r.Value
274 case o == binary.LittleEndian:
275 ri.Addr = r.Addr
276 ri.Symnum = r.Value&(1<<24-1) | pcrel<<24 | len<<25 | ext<<27 | typ<<28
277 case o == binary.BigEndian:
278 ri.Addr = r.Addr
279 ri.Symnum = r.Value<<8 | pcrel<<7 | len<<5 | ext<<4 | typ
280 }
281 o.PutUint32(b, ri.Addr)
282 o.PutUint32(b[4:], ri.Symnum)
283 a += 8
284 b = b[8:]
285 }
286 return a
287 }
288
289 func putAtMost16Bytes(b []byte, n string) {
290 for i := range n { // at most 16 bytes
291 if i == 16 {
292 break
293 }
294 b[i] = n[i]
295 }
296 }
297
298 // A Symbol is a Mach-O 32-bit or 64-bit symbol table entry.
299 type Symbol struct {
300 Name string
301 Type uint8
302 Sect uint8
303 Desc uint16
304 Value uint64
305 }
306
307 /*
308 * Mach-O reader
309 */
310
311 // FormatError is returned by some operations if the data does
312 // not have the correct format for an object file.
313 type FormatError struct {
314 off int64
315 msg string
316 }
317
318 func formatError(off int64, format string, data ...any) *FormatError {
319 return &FormatError{off, fmt.Sprintf(format, data...)}
320 }
321
322 func (e *FormatError) Error() string {
323 return e.msg + fmt.Sprintf(" in record at byte %#x", e.off)
324 }
325
326 func (e *FormatError) String() string {
327 return e.Error()
328 }
329
330 // DerivedCopy returns a modified copy of the TOC, with empty loads and sections,
331 // and with the specified header type and flags.
332 func (t *FileTOC) DerivedCopy(Type HdrType, Flags HdrFlags) *FileTOC {
333 h := t.FileHeader
334 h.NCommands, h.SizeCommands, h.Type, h.Flags = 0, 0, Type, Flags
335
336 return &FileTOC{FileHeader: h, ByteOrder: t.ByteOrder}
337 }
338
339 // TOCSize returns the size in bytes of the object file representation
340 // of the header and Load Commands (including Segments and Sections, but
341 // not their contents) at the beginning of a Mach-O file. This typically
342 // overlaps the text segment in the object file.
343 func (t *FileTOC) TOCSize() uint32 {
344 return t.HdrSize() + t.LoadSize()
345 }
346
347 // LoadAlign returns the required alignment of Load commands in a binary.
348 // This is used to add padding for necessary alignment.
349 func (t *FileTOC) LoadAlign() uint64 {
350 if t.Magic == Magic64 {
351 return 8
352 }
353 return 4
354 }
355
356 // SymbolSize returns the size in bytes of a Symbol (Nlist32 or Nlist64)
357 func (t *FileTOC) SymbolSize() uint32 {
358 if t.Magic == Magic64 {
359 return uint32(unsafe.Sizeof(Nlist64{}))
360 }
361 return uint32(unsafe.Sizeof(Nlist32{}))
362 }
363
364 // HdrSize returns the size in bytes of the Macho header for a given
365 // magic number (where the magic number has been appropriately byte-swapped).
366 func (t *FileTOC) HdrSize() uint32 {
367 switch t.Magic {
368 case Magic32:
369 return fileHeaderSize32
370 case Magic64:
371 return fileHeaderSize64
372 case MagicFat:
373 panic("MagicFat not handled yet")
374 default:
375 panic(fmt.Sprintf("Unexpected magic number 0x%x, expected Mach-O object file", t.Magic))
376 }
377 }
378
379 // LoadSize returns the size of all the load commands in a file's table-of contents
380 // (but not their associated data, e.g., sections and symbol tables)
381 func (t *FileTOC) LoadSize() uint32 {
382 cmdsz := uint32(0)
383 for _, l := range t.Loads {
384 s := l.LoadSize(t)
385 cmdsz += s
386 }
387 return cmdsz
388 }
389
390 // FileSize returns the size in bytes of the header, load commands, and the
391 // in-file contents of all the segments and sections included in those
392 // load commands, accounting for their offsets within the file.
393 func (t *FileTOC) FileSize() uint64 {
394 sz := uint64(t.LoadSize()) // ought to be contained in text segment, but just in case.
395 for _, l := range t.Loads {
396 if s, ok := l.(*Segment); ok {
397 if m := s.Offset + s.Filesz; m > sz {
398 sz = m
399 }
400 }
401 }
402 return sz
403 }
404
405 // Put writes the header and all load commands to buffer, using
406 // the byte ordering specified in FileTOC t. For sections, this
407 // writes the headers that come in-line with the segment Load commands,
408 // but does not write the reference data for those sections.
409 func (t *FileTOC) Put(buffer []byte) int {
410 next := t.FileHeader.Put(buffer, t.ByteOrder)
411 for _, l := range t.Loads {
412 if s, ok := l.(*Segment); ok {
413 switch t.Magic {
414 case Magic64:
415 next += s.Put64(buffer[next:], t.ByteOrder)
416 for i := uint32(0); i < s.Nsect; i++ {
417 c := t.Sections[i+s.Firstsect]
418 next += c.Put64(buffer[next:], t.ByteOrder)
419 }
420 case Magic32:
421 next += s.Put32(buffer[next:], t.ByteOrder)
422 for i := uint32(0); i < s.Nsect; i++ {
423 c := t.Sections[i+s.Firstsect]
424 next += c.Put32(buffer[next:], t.ByteOrder)
425 }
426 default:
427 panic(fmt.Sprintf("Unexpected magic number 0x%x", t.Magic))
428 }
429
430 } else {
431 next += l.Put(buffer[next:], t.ByteOrder)
432 }
433 }
434 return next
435 }
436
437 // UncompressedSize returns the size of the segment with its sections uncompressed, ignoring
438 // its offset within the file. The returned size is rounded up to the power of two in align.
439 func (s *Segment) UncompressedSize(t *FileTOC, align uint64) uint64 {
440 sz := uint64(0)
441 for j := uint32(0); j < s.Nsect; j++ {
442 c := t.Sections[j+s.Firstsect]
443 sz += c.UncompressedSize()
444 }
445 return (sz + align - 1) & uint64(-int64(align))
446 }
447
448 func (s *Section) UncompressedSize() uint64 {
449 if !strings.HasPrefix(s.Name, "__z") {
450 return s.Size
451 }
452 b := make([]byte, 12)
453 n, err := s.sr.ReadAt(b, 0)
454 if err != nil {
455 panic("Malformed object file")
456 }
457 if n != len(b) {
458 return s.Size
459 }
460 if string(b[:4]) == "ZLIB" {
461 return binary.BigEndian.Uint64(b[4:12])
462 }
463 return s.Size
464 }
465
466 func (s *Section) PutData(b []byte) {
467 bb := b[0:s.Size]
468 n, err := s.sr.ReadAt(bb, 0)
469 if err != nil || uint64(n) != s.Size {
470 panic("Malformed object file (ReadAt error)")
471 }
472 }
473
474 func (s *Section) PutUncompressedData(b []byte) {
475 if strings.HasPrefix(s.Name, "__z") {
476 bb := make([]byte, 12)
477 n, err := s.sr.ReadAt(bb, 0)
478 if err != nil {
479 panic("Malformed object file")
480 }
481 if n == len(bb) && string(bb[:4]) == "ZLIB" {
482 size := binary.BigEndian.Uint64(bb[4:12])
483 // Decompress starting at b[12:]
484 r, err := zlib.NewReader(io.NewSectionReader(s, 12, int64(size)-12))
485 if err != nil {
486 panic("Malformed object file (zlib.NewReader error)")
487 }
488 n, err := io.ReadFull(r, b[0:size])
489 if err != nil {
490 panic("Malformed object file (ReadFull error)")
491 }
492 if uint64(n) != size {
493 panic(fmt.Sprintf("PutUncompressedData, expected to read %d bytes, instead read %d", size, n))
494 }
495 if err := r.Close(); err != nil {
496 panic("Malformed object file (Close error)")
497 }
498 return
499 }
500 }
501 // Not compressed
502 s.PutData(b)
503 }
504
505 func (b LoadBytes) String() string {
506 var s strings.Builder
507 s.WriteString("[")
508 for i, a := range b {
509 if i > 0 {
510 s.WriteString(" ")
511 if len(b) > 48 && i >= 16 {
512 fmt.Fprintf(&s, "... (%d bytes)", len(b))
513 break
514 }
515 }
516 fmt.Fprintf(&s, "%x", a)
517 }
518 s.WriteString("]")
519 return s.String()
520 }
521
522 func (b LoadBytes) Raw() []byte { return b }
523 func (b LoadBytes) Copy() LoadBytes { return LoadBytes(slices.Clone(b)) }
524 func (b LoadBytes) LoadSize(t *FileTOC) uint32 { return uint32(len(b)) }
525
526 func (lc LoadCmd) Put(b []byte, o binary.ByteOrder) int {
527 panic(fmt.Sprintf("Put not implemented for %s", lc.String()))
528 }
529
530 func (s LoadCmdBytes) String() string {
531 return s.LoadCmd.String() + ": " + s.LoadBytes.String()
532 }
533 func (s LoadCmdBytes) Copy() LoadCmdBytes {
534 return LoadCmdBytes{LoadCmd: s.LoadCmd, LoadBytes: s.LoadBytes.Copy()}
535 }
536
537 func (s *SegmentHeader) String() string {
538 return fmt.Sprintf(
539 "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",
540 s.Name, s.Len, s.Addr, s.Memsz, s.Offset, s.Filesz, s.Maxprot, s.Prot, s.Nsect, s.Flag, s.Firstsect)
541 }
542
543 func (s *Segment) String() string {
544 return fmt.Sprintf(
545 "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",
546 s.Name, s.Len, s.Addr, s.Memsz, s.Offset, s.Filesz, s.Maxprot, s.Prot, s.Nsect, s.Flag, s.Firstsect)
547 }
548
549 // Data reads and returns the contents of the segment.
550 func (s *Segment) Data() ([]byte, error) {
551 dat := make([]byte, s.sr.Size())
552 n, err := s.sr.ReadAt(dat, 0)
553 if n == len(dat) {
554 err = nil
555 }
556 return dat[0:n], err
557 }
558
559 func (s *Segment) Copy() *Segment {
560 r := &Segment{SegmentHeader: s.SegmentHeader}
561 return r
562 }
563 func (s *Segment) CopyZeroed() *Segment {
564 r := s.Copy()
565 r.Filesz = 0
566 r.Offset = 0
567 r.Nsect = 0
568 r.Firstsect = 0
569 if s.Command() == LcSegment64 {
570 r.Len = uint32(unsafe.Sizeof(Segment64{}))
571 } else {
572 r.Len = uint32(unsafe.Sizeof(Segment32{}))
573 }
574 return r
575 }
576
577 func (s *Segment) LoadSize(t *FileTOC) uint32 {
578 if s.Command() == LcSegment64 {
579 return uint32(unsafe.Sizeof(Segment64{})) + uint32(s.Nsect)*uint32(unsafe.Sizeof(Section64{}))
580 }
581 return uint32(unsafe.Sizeof(Segment32{})) + uint32(s.Nsect)*uint32(unsafe.Sizeof(Section32{}))
582 }
583
584 // Open returns a new ReadSeeker reading the segment.
585 func (s *Segment) Open() io.ReadSeeker { return io.NewSectionReader(s.sr, 0, 1<<63-1) }
586
587 // Data reads and returns the contents of the Mach-O section.
588 func (s *Section) Data() ([]byte, error) {
589 dat := make([]byte, s.sr.Size())
590 n, err := s.sr.ReadAt(dat, 0)
591 if n == len(dat) {
592 err = nil
593 }
594 return dat[0:n], err
595 }
596
597 func (s *Section) Copy() *Section {
598 return &Section{SectionHeader: s.SectionHeader}
599 }
600
601 // Open returns a new ReadSeeker reading the Mach-O section.
602 func (s *Section) Open() io.ReadSeeker { return io.NewSectionReader(s.sr, 0, 1<<63-1) }
603
604 // A Dylib represents a Mach-O load dynamic library command.
605 type Dylib struct {
606 DylibCmd
607 Name string
608 Time uint32
609 CurrentVersion uint32
610 CompatVersion uint32
611 }
612
613 func (s *Dylib) String() string { return "Dylib " + s.Name }
614 func (s *Dylib) Copy() *Dylib {
615 r := *s
616 return &r
617 }
618 func (s *Dylib) LoadSize(t *FileTOC) uint32 {
619 return uint32(RoundUp(uint64(unsafe.Sizeof(DylibCmd{}))+uint64(len(s.Name)), t.LoadAlign()))
620 }
621
622 type Dylinker struct {
623 DylinkerCmd // shared by 3 commands, need the LoadCmd
624 Name string
625 }
626
627 func (s *Dylinker) String() string { return s.DylinkerCmd.LoadCmd.String() + " " + s.Name }
628 func (s *Dylinker) Copy() *Dylinker {
629 return &Dylinker{DylinkerCmd: s.DylinkerCmd, Name: s.Name}
630 }
631 func (s *Dylinker) LoadSize(t *FileTOC) uint32 {
632 return uint32(RoundUp(uint64(unsafe.Sizeof(DylinkerCmd{}))+uint64(len(s.Name)), t.LoadAlign()))
633 }
634
635 // A Symtab represents a Mach-O symbol table command.
636 type Symtab struct {
637 SymtabCmd
638 Syms []Symbol
639 }
640
641 func (s *Symtab) Put(b []byte, o binary.ByteOrder) int {
642 o.PutUint32(b[0*4:], uint32(s.LoadCmd))
643 o.PutUint32(b[1*4:], s.Len)
644 o.PutUint32(b[2*4:], s.Symoff)
645 o.PutUint32(b[3*4:], s.Nsyms)
646 o.PutUint32(b[4*4:], s.Stroff)
647 o.PutUint32(b[5*4:], s.Strsize)
648 return 6 * 4
649 }
650
651 func (s *Symtab) String() string { return fmt.Sprintf("Symtab %#v", s.SymtabCmd) }
652 func (s *Symtab) Copy() *Symtab {
653 return &Symtab{SymtabCmd: s.SymtabCmd, Syms: slices.Clone(s.Syms)}
654 }
655 func (s *Symtab) LoadSize(t *FileTOC) uint32 {
656 return uint32(unsafe.Sizeof(SymtabCmd{}))
657 }
658
659 type LinkEditData struct {
660 LinkEditDataCmd
661 }
662
663 func (s *LinkEditData) String() string { return "LinkEditData " + s.LoadCmd.String() }
664 func (s *LinkEditData) Copy() *LinkEditData {
665 return &LinkEditData{LinkEditDataCmd: s.LinkEditDataCmd}
666 }
667 func (s *LinkEditData) LoadSize(t *FileTOC) uint32 {
668 return uint32(unsafe.Sizeof(LinkEditDataCmd{}))
669 }
670
671 type Uuid struct {
672 UuidCmd
673 }
674
675 func (s *Uuid) String() string {
676 return fmt.Sprintf("Uuid %X-%X-%X-%X-%X",
677 s.Id[0:4], s.Id[4:6], s.Id[6:8], s.Id[8:10], s.Id[10:16])
678 } // 8-4-4-4-12
679 func (s *Uuid) Copy() *Uuid {
680 return &Uuid{UuidCmd: s.UuidCmd}
681 }
682 func (s *Uuid) LoadSize(t *FileTOC) uint32 {
683 return uint32(unsafe.Sizeof(UuidCmd{}))
684 }
685 func (s *Uuid) Put(b []byte, o binary.ByteOrder) int {
686 o.PutUint32(b[0*4:], uint32(s.LoadCmd))
687 o.PutUint32(b[1*4:], s.Len)
688 copy(b[2*4:], s.Id[0:])
689 return int(s.Len)
690 }
691
692 type DyldInfo struct {
693 DyldInfoCmd
694 }
695
696 func (s *DyldInfo) String() string { return "DyldInfo " + s.LoadCmd.String() }
697 func (s *DyldInfo) Copy() *DyldInfo {
698 return &DyldInfo{DyldInfoCmd: s.DyldInfoCmd}
699 }
700 func (s *DyldInfo) LoadSize(t *FileTOC) uint32 {
701 return uint32(unsafe.Sizeof(DyldInfoCmd{}))
702 }
703
704 type EncryptionInfo struct {
705 EncryptionInfoCmd
706 }
707
708 func (s *EncryptionInfo) String() string { return "EncryptionInfo " + s.LoadCmd.String() }
709 func (s *EncryptionInfo) Copy() *EncryptionInfo {
710 return &EncryptionInfo{EncryptionInfoCmd: s.EncryptionInfoCmd}
711 }
712 func (s *EncryptionInfo) LoadSize(t *FileTOC) uint32 {
713 return uint32(unsafe.Sizeof(EncryptionInfoCmd{}))
714 }
715
716 // A Dysymtab represents a Mach-O dynamic symbol table command.
717 type Dysymtab struct {
718 DysymtabCmd
719 IndirectSyms []uint32 // indices into Symtab.Syms
720 }
721
722 func (s *Dysymtab) String() string { return fmt.Sprintf("Dysymtab %#v", s.DysymtabCmd) }
723 func (s *Dysymtab) Copy() *Dysymtab {
724 return &Dysymtab{DysymtabCmd: s.DysymtabCmd, IndirectSyms: slices.Clone(s.IndirectSyms)}
725 }
726 func (s *Dysymtab) LoadSize(t *FileTOC) uint32 {
727 return uint32(unsafe.Sizeof(DysymtabCmd{}))
728 }
729
730 // A Rpath represents a Mach-O rpath command.
731 type Rpath struct {
732 LoadCmd
733 Path string
734 }
735
736 func (s *Rpath) String() string { return "Rpath " + s.Path }
737 func (s *Rpath) Command() LoadCmd { return LcRpath }
738 func (s *Rpath) Copy() *Rpath {
739 return &Rpath{Path: s.Path}
740 }
741 func (s *Rpath) LoadSize(t *FileTOC) uint32 {
742 return uint32(RoundUp(uint64(unsafe.Sizeof(RpathCmd{}))+uint64(len(s.Path)), t.LoadAlign()))
743 }
744
745 // Open opens the named file using os.Open and prepares it for use as a Mach-O binary.
746 func Open(name string) (*File, error) {
747 f, err := os.Open(name)
748 if err != nil {
749 return nil, err
750 }
751 ff, err := NewFile(f)
752 if err != nil {
753 f.Close()
754 return nil, err
755 }
756 ff.closer = f
757 return ff, nil
758 }
759
760 // Close closes the File.
761 // If the File was created using NewFile directly instead of Open,
762 // Close has no effect.
763 func (f *File) Close() error {
764 var err error
765 if f.closer != nil {
766 err = f.closer.Close()
767 f.closer = nil
768 }
769 return err
770 }
771
772 // NewFile creates a new File for accessing a Mach-O binary in an underlying reader.
773 // The Mach-O binary is expected to start at position 0 in the ReaderAt.
774 func NewFile(r io.ReaderAt) (*File, error) {
775 f := new(File)
776 sr := io.NewSectionReader(r, 0, 1<<63-1)
777
778 // Read and decode Mach magic to determine byte order, size.
779 // Magic32 and Magic64 differ only in the bottom bit.
780 var ident [4]byte
781 if _, err := r.ReadAt(ident[0:], 0); err != nil {
782 return nil, err
783 }
784 be := binary.BigEndian.Uint32(ident[0:])
785 le := binary.LittleEndian.Uint32(ident[0:])
786 switch Magic32 &^ 1 {
787 case be &^ 1:
788 f.ByteOrder = binary.BigEndian
789 f.Magic = be
790 case le &^ 1:
791 f.ByteOrder = binary.LittleEndian
792 f.Magic = le
793 default:
794 return nil, formatError(0, "invalid magic number be=0x%x, le=0x%x", be, le)
795 }
796
797 // Read entire file header.
798 if err := binary.Read(sr, f.ByteOrder, &f.FileHeader); err != nil {
799 return nil, err
800 }
801
802 // Then load commands.
803 offset := int64(fileHeaderSize32)
804 if f.Magic == Magic64 {
805 offset = fileHeaderSize64
806 }
807 dat := make([]byte, f.SizeCommands)
808 if _, err := r.ReadAt(dat, offset); err != nil {
809 return nil, err
810 }
811 f.Loads = make([]Load, f.NCommands)
812 bo := f.ByteOrder
813 for i := range f.Loads {
814 // Each load command begins with uint32 command and length.
815 if len(dat) < 8 {
816 return nil, formatError(offset, "command block too small, len(dat) = %d", len(dat))
817 }
818 cmd, siz := LoadCmd(bo.Uint32(dat[0:4])), bo.Uint32(dat[4:8])
819 if siz < 8 || siz > uint32(len(dat)) {
820 return nil, formatError(offset, "invalid command block size, len(dat)=%d, size=%d", len(dat), siz)
821 }
822 var cmddat []byte
823 cmddat, dat = dat[0:siz], dat[siz:]
824 offset += int64(siz)
825 var s *Segment
826 switch cmd {
827 default:
828 f.Loads[i] = LoadCmdBytes{LoadCmd(cmd), LoadBytes(cmddat)}
829
830 case LcUuid:
831 var hdr UuidCmd
832 b := bytes.NewReader(cmddat)
833 if err := binary.Read(b, bo, &hdr); err != nil {
834 return nil, err
835 }
836 l := &Uuid{UuidCmd: hdr}
837
838 f.Loads[i] = l
839
840 case LcRpath:
841 var hdr RpathCmd
842 b := bytes.NewReader(cmddat)
843 if err := binary.Read(b, bo, &hdr); err != nil {
844 return nil, err
845 }
846 l := &Rpath{LoadCmd: hdr.LoadCmd}
847 if hdr.Path >= uint32(len(cmddat)) {
848 return nil, formatError(offset, "invalid path in rpath command, len(cmddat)=%d, hdr.Path=%d", len(cmddat), hdr.Path)
849 }
850 l.Path = cstring(cmddat[hdr.Path:])
851 f.Loads[i] = l
852
853 case LcLoadDylinker, LcIdDylinker, LcDyldEnvironment:
854 var hdr DylinkerCmd
855 b := bytes.NewReader(cmddat)
856 if err := binary.Read(b, bo, &hdr); err != nil {
857 return nil, err
858 }
859 l := new(Dylinker)
860 if hdr.Name >= uint32(len(cmddat)) {
861 return nil, formatError(offset, "invalid name in dynamic linker command, hdr.Name=%d, len(cmddat)=%d", hdr.Name, len(cmddat))
862 }
863 l.Name = cstring(cmddat[hdr.Name:])
864 l.DylinkerCmd = hdr
865 f.Loads[i] = l
866
867 case LcDylib:
868 var hdr DylibCmd
869 b := bytes.NewReader(cmddat)
870 if err := binary.Read(b, bo, &hdr); err != nil {
871 return nil, err
872 }
873 l := new(Dylib)
874 if hdr.Name >= uint32(len(cmddat)) {
875 return nil, formatError(offset, "invalid name in dynamic library command, hdr.Name=%d, len(cmddat)=%d", hdr.Name, len(cmddat))
876 }
877 l.Name = cstring(cmddat[hdr.Name:])
878 l.Time = hdr.Time
879 l.CurrentVersion = hdr.CurrentVersion
880 l.CompatVersion = hdr.CompatVersion
881 f.Loads[i] = l
882
883 case LcSymtab:
884 var hdr SymtabCmd
885 b := bytes.NewReader(cmddat)
886 if err := binary.Read(b, bo, &hdr); err != nil {
887 return nil, err
888 }
889 strtab := make([]byte, hdr.Strsize)
890 if _, err := r.ReadAt(strtab, int64(hdr.Stroff)); err != nil {
891 return nil, err
892 }
893 var symsz int
894 if f.Magic == Magic64 {
895 symsz = 16
896 } else {
897 symsz = 12
898 }
899 symdat := make([]byte, int(hdr.Nsyms)*symsz)
900 if _, err := r.ReadAt(symdat, int64(hdr.Symoff)); err != nil {
901 return nil, err
902 }
903 st, err := f.parseSymtab(symdat, strtab, &hdr, offset)
904 st.SymtabCmd = hdr
905 if err != nil {
906 return nil, err
907 }
908 f.Loads[i] = st
909 f.Symtab = st
910
911 case LcDysymtab:
912 var hdr DysymtabCmd
913 b := bytes.NewReader(cmddat)
914 if err := binary.Read(b, bo, &hdr); err != nil {
915 return nil, err
916 }
917 dat := make([]byte, hdr.Nindirectsyms*4)
918 if _, err := r.ReadAt(dat, int64(hdr.Indirectsymoff)); err != nil {
919 return nil, err
920 }
921 x := make([]uint32, hdr.Nindirectsyms)
922 if err := binary.Read(bytes.NewReader(dat), bo, x); err != nil {
923 return nil, err
924 }
925 st := new(Dysymtab)
926 st.DysymtabCmd = hdr
927 st.IndirectSyms = x
928 f.Loads[i] = st
929 f.Dysymtab = st
930
931 case LcSegment:
932 var seg32 Segment32
933 b := bytes.NewReader(cmddat)
934 if err := binary.Read(b, bo, &seg32); err != nil {
935 return nil, err
936 }
937 s = new(Segment)
938 s.LoadCmd = cmd
939 s.Len = siz
940 s.Name = cstring(seg32.Name[0:])
941 s.Addr = uint64(seg32.Addr)
942 s.Memsz = uint64(seg32.Memsz)
943 s.Offset = uint64(seg32.Offset)
944 s.Filesz = uint64(seg32.Filesz)
945 s.Maxprot = seg32.Maxprot
946 s.Prot = seg32.Prot
947 s.Nsect = seg32.Nsect
948 s.Flag = seg32.Flag
949 s.Firstsect = uint32(len(f.Sections))
950 f.Loads[i] = s
951 for i := 0; i < int(s.Nsect); i++ {
952 var sh32 Section32
953 if err := binary.Read(b, bo, &sh32); err != nil {
954 return nil, err
955 }
956 sh := new(Section)
957 sh.Name = cstring(sh32.Name[0:])
958 sh.Seg = cstring(sh32.Seg[0:])
959 sh.Addr = uint64(sh32.Addr)
960 sh.Size = uint64(sh32.Size)
961 sh.Offset = sh32.Offset
962 sh.Align = sh32.Align
963 sh.Reloff = sh32.Reloff
964 sh.Nreloc = sh32.Nreloc
965 sh.Flags = sh32.Flags
966 sh.Reserved1 = sh32.Reserve1
967 sh.Reserved2 = sh32.Reserve2
968 if err := f.pushSection(sh, r); err != nil {
969 return nil, err
970 }
971 }
972
973 case LcSegment64:
974 var seg64 Segment64
975 b := bytes.NewReader(cmddat)
976 if err := binary.Read(b, bo, &seg64); err != nil {
977 return nil, err
978 }
979 s = new(Segment)
980 s.LoadCmd = cmd
981 s.Len = siz
982 s.Name = cstring(seg64.Name[0:])
983 s.Addr = seg64.Addr
984 s.Memsz = seg64.Memsz
985 s.Offset = seg64.Offset
986 s.Filesz = seg64.Filesz
987 s.Maxprot = seg64.Maxprot
988 s.Prot = seg64.Prot
989 s.Nsect = seg64.Nsect
990 s.Flag = seg64.Flag
991 s.Firstsect = uint32(len(f.Sections))
992 f.Loads[i] = s
993 for i := 0; i < int(s.Nsect); i++ {
994 var sh64 Section64
995 if err := binary.Read(b, bo, &sh64); err != nil {
996 return nil, err
997 }
998 sh := new(Section)
999 sh.Name = cstring(sh64.Name[0:])
1000 sh.Seg = cstring(sh64.Seg[0:])
1001 sh.Addr = sh64.Addr
1002 sh.Size = sh64.Size
1003 sh.Offset = sh64.Offset
1004 sh.Align = sh64.Align
1005 sh.Reloff = sh64.Reloff
1006 sh.Nreloc = sh64.Nreloc
1007 sh.Flags = sh64.Flags
1008 sh.Reserved1 = sh64.Reserve1
1009 sh.Reserved2 = sh64.Reserve2
1010 sh.Reserved3 = sh64.Reserve3
1011 if err := f.pushSection(sh, r); err != nil {
1012 return nil, err
1013 }
1014 }
1015
1016 case LcCodeSignature, LcSegmentSplitInfo, LcFunctionStarts,
1017 LcDataInCode, LcDylibCodeSignDrs:
1018 var hdr LinkEditDataCmd
1019 b := bytes.NewReader(cmddat)
1020
1021 if err := binary.Read(b, bo, &hdr); err != nil {
1022 return nil, err
1023 }
1024 l := new(LinkEditData)
1025
1026 l.LinkEditDataCmd = hdr
1027 f.Loads[i] = l
1028
1029 case LcEncryptionInfo, LcEncryptionInfo64:
1030 var hdr EncryptionInfoCmd
1031 b := bytes.NewReader(cmddat)
1032
1033 if err := binary.Read(b, bo, &hdr); err != nil {
1034 return nil, err
1035 }
1036 l := new(EncryptionInfo)
1037
1038 l.EncryptionInfoCmd = hdr
1039 f.Loads[i] = l
1040
1041 case LcDyldInfo, LcDyldInfoOnly:
1042 var hdr DyldInfoCmd
1043 b := bytes.NewReader(cmddat)
1044
1045 if err := binary.Read(b, bo, &hdr); err != nil {
1046 return nil, err
1047 }
1048 l := new(DyldInfo)
1049
1050 l.DyldInfoCmd = hdr
1051 f.Loads[i] = l
1052 }
1053 if s != nil {
1054 s.sr = io.NewSectionReader(r, int64(s.Offset), int64(s.Filesz))
1055 s.ReaderAt = s.sr
1056 }
1057 if f.Loads[i].LoadSize(&f.FileTOC) != siz {
1058 fmt.Printf("Oops, actual size was %d, calculated was %d, load was %s\n", siz, f.Loads[i].LoadSize(&f.FileTOC), f.Loads[i].String())
1059 panic("oops")
1060 }
1061 }
1062 return f, nil
1063 }
1064
1065 func (f *File) parseSymtab(symdat, strtab []byte, hdr *SymtabCmd, offset int64) (*Symtab, error) {
1066 bo := f.ByteOrder
1067 symtab := make([]Symbol, hdr.Nsyms)
1068 b := bytes.NewReader(symdat)
1069 for i := range symtab {
1070 var n Nlist64
1071 if f.Magic == Magic64 {
1072 if err := binary.Read(b, bo, &n); err != nil {
1073 return nil, err
1074 }
1075 } else {
1076 var n32 Nlist32
1077 if err := binary.Read(b, bo, &n32); err != nil {
1078 return nil, err
1079 }
1080 n.Name = n32.Name
1081 n.Type = n32.Type
1082 n.Sect = n32.Sect
1083 n.Desc = n32.Desc
1084 n.Value = uint64(n32.Value)
1085 }
1086 sym := &symtab[i]
1087 if n.Name >= uint32(len(strtab)) {
1088 return nil, formatError(offset, "invalid name in symbol table, n.Name=%d, len(strtab)=%d", n.Name, len(strtab))
1089 }
1090 sym.Name = cstring(strtab[n.Name:])
1091 sym.Type = n.Type
1092 sym.Sect = n.Sect
1093 sym.Desc = n.Desc
1094 sym.Value = n.Value
1095 }
1096 st := new(Symtab)
1097 st.Syms = symtab
1098 return st, nil
1099 }
1100
1101 type relocInfo struct {
1102 Addr uint32
1103 Symnum uint32
1104 }
1105
1106 func (f *File) pushSection(sh *Section, r io.ReaderAt) error {
1107 f.Sections = append(f.Sections, sh)
1108 sh.sr = io.NewSectionReader(r, int64(sh.Offset), int64(sh.Size))
1109 sh.ReaderAt = sh.sr
1110
1111 if sh.Nreloc > 0 {
1112 reldat := make([]byte, int(sh.Nreloc)*8)
1113 if _, err := r.ReadAt(reldat, int64(sh.Reloff)); err != nil {
1114 return err
1115 }
1116 b := bytes.NewReader(reldat)
1117
1118 bo := f.ByteOrder
1119
1120 sh.Relocs = make([]Reloc, sh.Nreloc)
1121 for i := range sh.Relocs {
1122 rel := &sh.Relocs[i]
1123
1124 var ri relocInfo
1125 if err := binary.Read(b, bo, &ri); err != nil {
1126 return err
1127 }
1128
1129 if ri.Addr&(1<<31) != 0 { // scattered
1130 rel.Addr = ri.Addr & (1<<24 - 1)
1131 rel.Type = uint8((ri.Addr >> 24) & (1<<4 - 1))
1132 rel.Len = uint8((ri.Addr >> 28) & (1<<2 - 1))
1133 rel.Pcrel = ri.Addr&(1<<30) != 0
1134 rel.Value = ri.Symnum
1135 rel.Scattered = true
1136 } else {
1137 switch bo {
1138 case binary.LittleEndian:
1139 rel.Addr = ri.Addr
1140 rel.Value = ri.Symnum & (1<<24 - 1)
1141 rel.Pcrel = ri.Symnum&(1<<24) != 0
1142 rel.Len = uint8((ri.Symnum >> 25) & (1<<2 - 1))
1143 rel.Extern = ri.Symnum&(1<<27) != 0
1144 rel.Type = uint8((ri.Symnum >> 28) & (1<<4 - 1))
1145 case binary.BigEndian:
1146 rel.Addr = ri.Addr
1147 rel.Value = ri.Symnum >> 8
1148 rel.Pcrel = ri.Symnum&(1<<7) != 0
1149 rel.Len = uint8((ri.Symnum >> 5) & (1<<2 - 1))
1150 rel.Extern = ri.Symnum&(1<<4) != 0
1151 rel.Type = uint8(ri.Symnum & (1<<4 - 1))
1152 default:
1153 panic("unreachable")
1154 }
1155 }
1156 }
1157 }
1158
1159 return nil
1160 }
1161
1162 func cstring(b []byte) string {
1163 i := bytes.IndexByte(b, 0)
1164 if i == -1 {
1165 i = len(b)
1166 }
1167 return string(b[0:i])
1168 }
1169
1170 // Segment returns the first Segment with the given name, or nil if no such segment exists.
1171 func (f *File) Segment(name string) *Segment {
1172 for _, l := range f.Loads {
1173 if s, ok := l.(*Segment); ok && s.Name == name {
1174 return s
1175 }
1176 }
1177 return nil
1178 }
1179
1180 // Section returns the first section with the given name, or nil if no such
1181 // section exists.
1182 func (f *File) Section(name string) *Section {
1183 for _, s := range f.Sections {
1184 if s.Name == name {
1185 return s
1186 }
1187 }
1188 return nil
1189 }
1190
1191 // DWARF returns the DWARF debug information for the Mach-O file.
1192 func (f *File) DWARF() (*dwarf.Data, error) {
1193 dwarfSuffix := func(s *Section) string {
1194 switch {
1195 case strings.HasPrefix(s.Name, "__debug_"):
1196 return s.Name[8:]
1197 case strings.HasPrefix(s.Name, "__zdebug_"):
1198 return s.Name[9:]
1199 default:
1200 return ""
1201 }
1202
1203 }
1204 sectionData := func(s *Section) ([]byte, error) {
1205 b, err := s.Data()
1206 if err != nil && uint64(len(b)) < s.Size {
1207 return nil, err
1208 }
1209
1210 if len(b) >= 12 && string(b[:4]) == "ZLIB" {
1211 dlen := binary.BigEndian.Uint64(b[4:12])
1212 dbuf := make([]byte, dlen)
1213 r, err := zlib.NewReader(bytes.NewBuffer(b[12:]))
1214 if err != nil {
1215 return nil, err
1216 }
1217 if _, err := io.ReadFull(r, dbuf); err != nil {
1218 return nil, err
1219 }
1220 if err := r.Close(); err != nil {
1221 return nil, err
1222 }
1223 b = dbuf
1224 }
1225 return b, nil
1226 }
1227
1228 // There are many other DWARF sections, but these
1229 // are the ones the debug/dwarf package uses.
1230 // Don't bother loading others.
1231 var dat = map[string][]byte{"abbrev": nil, "info": nil, "str": nil, "line": nil, "ranges": nil}
1232 for _, s := range f.Sections {
1233 suffix := dwarfSuffix(s)
1234 if suffix == "" {
1235 continue
1236 }
1237 if _, ok := dat[suffix]; !ok {
1238 continue
1239 }
1240 b, err := sectionData(s)
1241 if err != nil {
1242 return nil, err
1243 }
1244 dat[suffix] = b
1245 }
1246
1247 d, err := dwarf.New(dat["abbrev"], nil, nil, dat["info"], dat["line"], nil, dat["ranges"], dat["str"])
1248 if err != nil {
1249 return nil, err
1250 }
1251
1252 // Look for DWARF4 .debug_types sections.
1253 for i, s := range f.Sections {
1254 suffix := dwarfSuffix(s)
1255 if suffix != "types" {
1256 continue
1257 }
1258
1259 b, err := sectionData(s)
1260 if err != nil {
1261 return nil, err
1262 }
1263
1264 err = d.AddTypes(fmt.Sprintf("types-%d", i), b)
1265 if err != nil {
1266 return nil, err
1267 }
1268 }
1269
1270 return d, nil
1271 }
1272
1273 // ImportedSymbols returns the names of all symbols
1274 // referred to by the binary f that are expected to be
1275 // satisfied by other libraries at dynamic load time.
1276 func (f *File) ImportedSymbols() ([]string, error) {
1277 if f.Dysymtab == nil || f.Symtab == nil {
1278 return nil, formatError(0, "missing symbol table, f.Dsymtab=%v, f.Symtab=%v", f.Dysymtab, f.Symtab)
1279 }
1280
1281 st := f.Symtab
1282 dt := f.Dysymtab
1283 var all []string
1284 for _, s := range st.Syms[dt.Iundefsym : dt.Iundefsym+dt.Nundefsym] {
1285 all = append(all, s.Name)
1286 }
1287 return all, nil
1288 }
1289
1290 // ImportedLibraries returns the paths of all libraries
1291 // referred to by the binary f that are expected to be
1292 // linked with the binary at dynamic link time.
1293 func (f *File) ImportedLibraries() ([]string, error) {
1294 var all []string
1295 for _, l := range f.Loads {
1296 if lib, ok := l.(*Dylib); ok {
1297 all = append(all, lib.Name)
1298 }
1299 }
1300 return all, nil
1301 }
1302
1303 func RoundUp(x, align uint64) uint64 {
1304 return uint64((x + align - 1) & -align)
1305 }