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.
5 // Package macho implements access to Mach-O object files.
8 // High level access to low level data structures.
22 // A File represents an open Mach-O file.
34 ByteOrder binary.ByteOrder
39 func (t *FileTOC) AddLoad(l Load) {
40 t.Loads = append(t.Loads, l)
42 t.SizeCommands += l.LoadSize(t)
45 // AddSegment adds segment s to the file table of contents,
46 // and also zeroes out the segment information with the expectation
47 // that this will be added next.
48 func (t *FileTOC) AddSegment(s *Segment) {
54 // Adds section to the most recently added Segment
55 func (t *FileTOC) AddSection(s *Section) {
56 g := t.Loads[len(t.Loads)-1].(*Segment)
58 g.Firstsect = uint32(len(t.Sections))
61 t.Sections = append(t.Sections, s)
62 sectionsize := uint32(unsafe.Sizeof(Section32{}))
63 if g.Command() == LcSegment64 {
64 sectionsize = uint32(unsafe.Sizeof(Section64{}))
66 t.SizeCommands += sectionsize
70 // A Load represents any Mach-O load command.
74 LoadSize(*FileTOC) uint32 // Need the TOC for alignment, sigh.
75 Put([]byte, binary.ByteOrder) int
77 // command LC_DYLD_INFO_ONLY contains offsets into __LINKEDIT
78 // e.g., from "otool -l a.out"
84 // vmaddr 0x0000000100002000
85 // vmsize 0x0000000000001000
89 // initprot 0x00000001
93 // cmd LC_DYLD_INFO_ONLY
101 // lazy_bind_off 8224
107 // LoadBytes is the uninterpreted bytes of a Mach-O load command.
108 type LoadBytes []byte
110 // A SegmentHeader is the header for a Mach-O 32-bit or 64-bit load segment command.
111 type SegmentHeader struct {
114 Name string // 16 characters or fewer
115 Addr uint64 // memory address
116 Memsz uint64 // memory size
117 Offset uint64 // file offset
118 Filesz uint64 // number of bytes starting at that file offset
126 // A Segment represents a Mach-O 32-bit or 64-bit load segment command.
127 type Segment struct {
130 // Embed ReaderAt for ReadAt method.
131 // Do not embed SectionReader directly
132 // to avoid having Read and Seek.
133 // If a client wants Read and Seek it must use
134 // Open() to avoid fighting over the seek offset
135 // with other clients.
140 func (s *Segment) Put32(b []byte, o binary.ByteOrder) int {
141 o.PutUint32(b[0*4:], uint32(s.LoadCmd))
142 o.PutUint32(b[1*4:], s.Len)
143 putAtMost16Bytes(b[2*4:], s.Name)
144 o.PutUint32(b[6*4:], uint32(s.Addr))
145 o.PutUint32(b[7*4:], uint32(s.Memsz))
146 o.PutUint32(b[8*4:], uint32(s.Offset))
147 o.PutUint32(b[9*4:], uint32(s.Filesz))
148 o.PutUint32(b[10*4:], s.Maxprot)
149 o.PutUint32(b[11*4:], s.Prot)
150 o.PutUint32(b[12*4:], s.Nsect)
151 o.PutUint32(b[13*4:], uint32(s.Flag))
155 func (s *Segment) Put64(b []byte, o binary.ByteOrder) int {
156 o.PutUint32(b[0*4:], uint32(s.LoadCmd))
157 o.PutUint32(b[1*4:], s.Len)
158 putAtMost16Bytes(b[2*4:], s.Name)
159 o.PutUint64(b[6*4+0*8:], s.Addr)
160 o.PutUint64(b[6*4+1*8:], s.Memsz)
161 o.PutUint64(b[6*4+2*8:], s.Offset)
162 o.PutUint64(b[6*4+3*8:], s.Filesz)
163 o.PutUint32(b[6*4+4*8:], s.Maxprot)
164 o.PutUint32(b[7*4+4*8:], s.Prot)
165 o.PutUint32(b[8*4+4*8:], s.Nsect)
166 o.PutUint32(b[9*4+4*8:], uint32(s.Flag))
170 // LoadCmdBytes is a command-tagged sequence of bytes.
171 // This is used for Load Commands that are not (yet)
172 // interesting to us, and to common up this behavior for
173 // all those that are.
174 type LoadCmdBytes struct {
179 type SectionHeader struct {
191 Reserved3 uint32 // only present if original was 64-bit
194 // A Reloc represents a Mach-O relocation.
198 // when Scattered == false && Extern == true, Value is the symbol number.
199 // when Scattered == false && Extern == false, Value is the section number.
200 // when Scattered == true, Value is the value that this reloc refers to.
202 Len uint8 // 0=byte, 1=word, 2=long, 3=quad
204 Extern bool // valid if Scattered == false
208 type Section struct {
212 // Embed ReaderAt for ReadAt method.
213 // Do not embed SectionReader directly
214 // to avoid having Read and Seek.
215 // If a client wants Read and Seek it must use
216 // Open() to avoid fighting over the seek offset
217 // with other clients.
222 func (s *Section) Put32(b []byte, o binary.ByteOrder) int {
223 putAtMost16Bytes(b[0:], s.Name)
224 putAtMost16Bytes(b[16:], s.Seg)
225 o.PutUint32(b[8*4:], uint32(s.Addr))
226 o.PutUint32(b[9*4:], uint32(s.Size))
227 o.PutUint32(b[10*4:], s.Offset)
228 o.PutUint32(b[11*4:], s.Align)
229 o.PutUint32(b[12*4:], s.Reloff)
230 o.PutUint32(b[13*4:], s.Nreloc)
231 o.PutUint32(b[14*4:], uint32(s.Flags))
232 o.PutUint32(b[15*4:], s.Reserved1)
233 o.PutUint32(b[16*4:], s.Reserved2)
235 return a + s.PutRelocs(b[a:], o)
238 func (s *Section) Put64(b []byte, o binary.ByteOrder) int {
239 putAtMost16Bytes(b[0:], s.Name)
240 putAtMost16Bytes(b[16:], s.Seg)
241 o.PutUint64(b[8*4+0*8:], s.Addr)
242 o.PutUint64(b[8*4+1*8:], s.Size)
243 o.PutUint32(b[8*4+2*8:], s.Offset)
244 o.PutUint32(b[9*4+2*8:], s.Align)
245 o.PutUint32(b[10*4+2*8:], s.Reloff)
246 o.PutUint32(b[11*4+2*8:], s.Nreloc)
247 o.PutUint32(b[12*4+2*8:], uint32(s.Flags))
248 o.PutUint32(b[13*4+2*8:], s.Reserved1)
249 o.PutUint32(b[14*4+2*8:], s.Reserved2)
250 o.PutUint32(b[15*4+2*8:], s.Reserved3)
252 return a + s.PutRelocs(b[a:], o)
255 func (s *Section) PutRelocs(b []byte, o binary.ByteOrder) int {
257 for _, r := range s.Relocs {
259 typ := uint32(r.Type) & (1<<4 - 1)
260 len := uint32(r.Len) & (1<<2 - 1)
271 ri.Addr = r.Addr&(1<<24-1) | typ<<24 | len<<28 | 1<<31 | pcrel<<30
273 case o == binary.LittleEndian:
275 ri.Symnum = r.Value&(1<<24-1) | pcrel<<24 | len<<25 | ext<<27 | typ<<28
276 case o == binary.BigEndian:
278 ri.Symnum = r.Value<<8 | pcrel<<7 | len<<5 | ext<<4 | typ
280 o.PutUint32(b, ri.Addr)
281 o.PutUint32(b[4:], ri.Symnum)
288 func putAtMost16Bytes(b []byte, n string) {
289 for i := range n { // at most 16 bytes
297 // A Symbol is a Mach-O 32-bit or 64-bit symbol table entry.
310 // FormatError is returned by some operations if the data does
311 // not have the correct format for an object file.
312 type FormatError struct {
317 func formatError(off int64, format string, data ...interface{}) *FormatError {
318 return &FormatError{off, fmt.Sprintf(format, data...)}
321 func (e *FormatError) Error() string {
322 return e.msg + fmt.Sprintf(" in record at byte %#x", e.off)
325 func (e *FormatError) String() string {
329 // DerivedCopy returns a modified copy of the TOC, with empty loads and sections,
330 // and with the specified header type and flags.
331 func (t *FileTOC) DerivedCopy(Type HdrType, Flags HdrFlags) *FileTOC {
333 h.NCommands, h.SizeCommands, h.Type, h.Flags = 0, 0, Type, Flags
335 return &FileTOC{FileHeader: h, ByteOrder: t.ByteOrder}
338 // TOCSize returns the size in bytes of the object file representation
339 // of the header and Load Commands (including Segments and Sections, but
340 // not their contents) at the beginning of a Mach-O file. This typically
341 // overlaps the text segment in the object file.
342 func (t *FileTOC) TOCSize() uint32 {
343 return t.HdrSize() + t.LoadSize()
346 // LoadAlign returns the required alignment of Load commands in a binary.
347 // This is used to add padding for necessary alignment.
348 func (t *FileTOC) LoadAlign() uint64 {
349 if t.Magic == Magic64 {
355 // SymbolSize returns the size in bytes of a Symbol (Nlist32 or Nlist64)
356 func (t *FileTOC) SymbolSize() uint32 {
357 if t.Magic == Magic64 {
358 return uint32(unsafe.Sizeof(Nlist64{}))
360 return uint32(unsafe.Sizeof(Nlist32{}))
363 // HdrSize returns the size in bytes of the Macho header for a given
364 // magic number (where the magic number has been appropriately byte-swapped).
365 func (t *FileTOC) HdrSize() uint32 {
368 return fileHeaderSize32
370 return fileHeaderSize64
372 panic("MagicFat not handled yet")
374 panic(fmt.Sprintf("Unexpected magic number 0x%x, expected Mach-O object file", t.Magic))
378 // LoadSize returns the size of all the load commands in a file's table-of contents
379 // (but not their associated data, e.g., sections and symbol tables)
380 func (t *FileTOC) LoadSize() uint32 {
382 for _, l := range t.Loads {
389 // FileSize returns the size in bytes of the header, load commands, and the
390 // in-file contents of all the segments and sections included in those
391 // load commands, accounting for their offsets within the file.
392 func (t *FileTOC) FileSize() uint64 {
393 sz := uint64(t.LoadSize()) // ought to be contained in text segment, but just in case.
394 for _, l := range t.Loads {
395 if s, ok := l.(*Segment); ok {
396 if m := s.Offset + s.Filesz; m > sz {
404 // Put writes the header and all load commands to buffer, using
405 // the byte ordering specified in FileTOC t. For sections, this
406 // writes the headers that come in-line with the segment Load commands,
407 // but does not write the reference data for those sections.
408 func (t *FileTOC) Put(buffer []byte) int {
409 next := t.FileHeader.Put(buffer, t.ByteOrder)
410 for _, l := range t.Loads {
411 if s, ok := l.(*Segment); ok {
414 next += s.Put64(buffer[next:], t.ByteOrder)
415 for i := uint32(0); i < s.Nsect; i++ {
416 c := t.Sections[i+s.Firstsect]
417 next += c.Put64(buffer[next:], t.ByteOrder)
420 next += s.Put32(buffer[next:], t.ByteOrder)
421 for i := uint32(0); i < s.Nsect; i++ {
422 c := t.Sections[i+s.Firstsect]
423 next += c.Put32(buffer[next:], t.ByteOrder)
426 panic(fmt.Sprintf("Unexpected magic number 0x%x", t.Magic))
430 next += l.Put(buffer[next:], t.ByteOrder)
436 // UncompressedSize returns the size of the segment with its sections uncompressed, ignoring
437 // its offset within the file. The returned size is rounded up to the power of two in align.
438 func (s *Segment) UncompressedSize(t *FileTOC, align uint64) uint64 {
440 for j := uint32(0); j < s.Nsect; j++ {
441 c := t.Sections[j+s.Firstsect]
442 sz += c.UncompressedSize()
444 return (sz + align - 1) & uint64(-int64(align))
447 func (s *Section) UncompressedSize() uint64 {
448 if !strings.HasPrefix(s.Name, "__z") {
451 b := make([]byte, 12)
452 n, err := s.sr.ReadAt(b, 0)
454 panic("Malformed object file")
459 if string(b[:4]) == "ZLIB" {
460 return binary.BigEndian.Uint64(b[4:12])
465 func (s *Section) PutData(b []byte) {
467 n, err := s.sr.ReadAt(bb, 0)
468 if err != nil || uint64(n) != s.Size {
469 panic("Malformed object file (ReadAt error)")
473 func (s *Section) PutUncompressedData(b []byte) {
474 if strings.HasPrefix(s.Name, "__z") {
475 bb := make([]byte, 12)
476 n, err := s.sr.ReadAt(bb, 0)
478 panic("Malformed object file")
480 if n == len(bb) && string(bb[:4]) == "ZLIB" {
481 size := binary.BigEndian.Uint64(bb[4:12])
482 // Decompress starting at b[12:]
483 r, err := zlib.NewReader(io.NewSectionReader(s, 12, int64(size)-12))
485 panic("Malformed object file (zlib.NewReader error)")
487 n, err := io.ReadFull(r, b[0:size])
489 panic("Malformed object file (ReadFull error)")
491 if uint64(n) != size {
492 panic(fmt.Sprintf("PutUncompressedData, expected to read %d bytes, instead read %d", size, n))
494 if err := r.Close(); err != nil {
495 panic("Malformed object file (Close error)")
504 func (b LoadBytes) String() string {
506 for i, a := range b {
509 if len(b) > 48 && i >= 16 {
510 s += fmt.Sprintf("... (%d bytes)", len(b))
514 s += fmt.Sprintf("%x", a)
520 func (b LoadBytes) Raw() []byte { return b }
521 func (b LoadBytes) Copy() LoadBytes { return LoadBytes(append([]byte{}, b...)) }
522 func (b LoadBytes) LoadSize(t *FileTOC) uint32 { return uint32(len(b)) }
524 func (lc LoadCmd) Put(b []byte, o binary.ByteOrder) int {
525 panic(fmt.Sprintf("Put not implemented for %s", lc.String()))
528 func (s LoadCmdBytes) String() string {
529 return s.LoadCmd.String() + ": " + s.LoadBytes.String()
531 func (s LoadCmdBytes) Copy() LoadCmdBytes {
532 return LoadCmdBytes{LoadCmd: s.LoadCmd, LoadBytes: s.LoadBytes.Copy()}
535 func (s *SegmentHeader) String() string {
537 "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",
538 s.Name, s.Len, s.Addr, s.Memsz, s.Offset, s.Filesz, s.Maxprot, s.Prot, s.Nsect, s.Flag, s.Firstsect)
541 func (s *Segment) String() string {
543 "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",
544 s.Name, s.Len, s.Addr, s.Memsz, s.Offset, s.Filesz, s.Maxprot, s.Prot, s.Nsect, s.Flag, s.Firstsect)
547 // Data reads and returns the contents of the segment.
548 func (s *Segment) Data() ([]byte, error) {
549 dat := make([]byte, s.sr.Size())
550 n, err := s.sr.ReadAt(dat, 0)
557 func (s *Segment) Copy() *Segment {
558 r := &Segment{SegmentHeader: s.SegmentHeader}
561 func (s *Segment) CopyZeroed() *Segment {
567 if s.Command() == LcSegment64 {
568 r.Len = uint32(unsafe.Sizeof(Segment64{}))
570 r.Len = uint32(unsafe.Sizeof(Segment32{}))
575 func (s *Segment) LoadSize(t *FileTOC) uint32 {
576 if s.Command() == LcSegment64 {
577 return uint32(unsafe.Sizeof(Segment64{})) + uint32(s.Nsect)*uint32(unsafe.Sizeof(Section64{}))
579 return uint32(unsafe.Sizeof(Segment32{})) + uint32(s.Nsect)*uint32(unsafe.Sizeof(Section32{}))
582 // Open returns a new ReadSeeker reading the segment.
583 func (s *Segment) Open() io.ReadSeeker { return io.NewSectionReader(s.sr, 0, 1<<63-1) }
585 // Data reads and returns the contents of the Mach-O section.
586 func (s *Section) Data() ([]byte, error) {
587 dat := make([]byte, s.sr.Size())
588 n, err := s.sr.ReadAt(dat, 0)
595 func (s *Section) Copy() *Section {
596 return &Section{SectionHeader: s.SectionHeader}
599 // Open returns a new ReadSeeker reading the Mach-O section.
600 func (s *Section) Open() io.ReadSeeker { return io.NewSectionReader(s.sr, 0, 1<<63-1) }
602 // A Dylib represents a Mach-O load dynamic library command.
607 CurrentVersion uint32
611 func (s *Dylib) String() string { return "Dylib " + s.Name }
612 func (s *Dylib) Copy() *Dylib {
616 func (s *Dylib) LoadSize(t *FileTOC) uint32 {
617 return uint32(RoundUp(uint64(unsafe.Sizeof(DylibCmd{}))+uint64(len(s.Name)), t.LoadAlign()))
620 type Dylinker struct {
621 DylinkerCmd // shared by 3 commands, need the LoadCmd
625 func (s *Dylinker) String() string { return s.DylinkerCmd.LoadCmd.String() + " " + s.Name }
626 func (s *Dylinker) Copy() *Dylinker {
627 return &Dylinker{DylinkerCmd: s.DylinkerCmd, Name: s.Name}
629 func (s *Dylinker) LoadSize(t *FileTOC) uint32 {
630 return uint32(RoundUp(uint64(unsafe.Sizeof(DylinkerCmd{}))+uint64(len(s.Name)), t.LoadAlign()))
633 // A Symtab represents a Mach-O symbol table command.
639 func (s *Symtab) Put(b []byte, o binary.ByteOrder) int {
640 o.PutUint32(b[0*4:], uint32(s.LoadCmd))
641 o.PutUint32(b[1*4:], s.Len)
642 o.PutUint32(b[2*4:], s.Symoff)
643 o.PutUint32(b[3*4:], s.Nsyms)
644 o.PutUint32(b[4*4:], s.Stroff)
645 o.PutUint32(b[5*4:], s.Strsize)
649 func (s *Symtab) String() string { return fmt.Sprintf("Symtab %#v", s.SymtabCmd) }
650 func (s *Symtab) Copy() *Symtab {
651 return &Symtab{SymtabCmd: s.SymtabCmd, Syms: append([]Symbol{}, s.Syms...)}
653 func (s *Symtab) LoadSize(t *FileTOC) uint32 {
654 return uint32(unsafe.Sizeof(SymtabCmd{}))
657 type LinkEditData struct {
661 func (s *LinkEditData) String() string { return "LinkEditData " + s.LoadCmd.String() }
662 func (s *LinkEditData) Copy() *LinkEditData {
663 return &LinkEditData{LinkEditDataCmd: s.LinkEditDataCmd}
665 func (s *LinkEditData) LoadSize(t *FileTOC) uint32 {
666 return uint32(unsafe.Sizeof(LinkEditDataCmd{}))
673 func (s *Uuid) String() string {
674 return fmt.Sprintf("Uuid %X-%X-%X-%X-%X",
675 s.Id[0:4], s.Id[4:6], s.Id[6:8], s.Id[8:10], s.Id[10:16])
677 func (s *Uuid) Copy() *Uuid {
678 return &Uuid{UuidCmd: s.UuidCmd}
680 func (s *Uuid) LoadSize(t *FileTOC) uint32 {
681 return uint32(unsafe.Sizeof(UuidCmd{}))
683 func (s *Uuid) Put(b []byte, o binary.ByteOrder) int {
684 o.PutUint32(b[0*4:], uint32(s.LoadCmd))
685 o.PutUint32(b[1*4:], s.Len)
686 copy(b[2*4:], s.Id[0:])
690 type DyldInfo struct {
694 func (s *DyldInfo) String() string { return "DyldInfo " + s.LoadCmd.String() }
695 func (s *DyldInfo) Copy() *DyldInfo {
696 return &DyldInfo{DyldInfoCmd: s.DyldInfoCmd}
698 func (s *DyldInfo) LoadSize(t *FileTOC) uint32 {
699 return uint32(unsafe.Sizeof(DyldInfoCmd{}))
702 type EncryptionInfo struct {
706 func (s *EncryptionInfo) String() string { return "EncryptionInfo " + s.LoadCmd.String() }
707 func (s *EncryptionInfo) Copy() *EncryptionInfo {
708 return &EncryptionInfo{EncryptionInfoCmd: s.EncryptionInfoCmd}
710 func (s *EncryptionInfo) LoadSize(t *FileTOC) uint32 {
711 return uint32(unsafe.Sizeof(EncryptionInfoCmd{}))
714 // A Dysymtab represents a Mach-O dynamic symbol table command.
715 type Dysymtab struct {
717 IndirectSyms []uint32 // indices into Symtab.Syms
720 func (s *Dysymtab) String() string { return fmt.Sprintf("Dysymtab %#v", s.DysymtabCmd) }
721 func (s *Dysymtab) Copy() *Dysymtab {
722 return &Dysymtab{DysymtabCmd: s.DysymtabCmd, IndirectSyms: append([]uint32{}, s.IndirectSyms...)}
724 func (s *Dysymtab) LoadSize(t *FileTOC) uint32 {
725 return uint32(unsafe.Sizeof(DysymtabCmd{}))
728 // A Rpath represents a Mach-O rpath command.
734 func (s *Rpath) String() string { return "Rpath " + s.Path }
735 func (s *Rpath) Command() LoadCmd { return LcRpath }
736 func (s *Rpath) Copy() *Rpath {
737 return &Rpath{Path: s.Path}
739 func (s *Rpath) LoadSize(t *FileTOC) uint32 {
740 return uint32(RoundUp(uint64(unsafe.Sizeof(RpathCmd{}))+uint64(len(s.Path)), t.LoadAlign()))
743 // Open opens the named file using os.Open and prepares it for use as a Mach-O binary.
744 func Open(name string) (*File, error) {
745 f, err := os.Open(name)
749 ff, err := NewFile(f)
758 // Close closes the File.
759 // If the File was created using NewFile directly instead of Open,
760 // Close has no effect.
761 func (f *File) Close() error {
764 err = f.closer.Close()
770 // NewFile creates a new File for accessing a Mach-O binary in an underlying reader.
771 // The Mach-O binary is expected to start at position 0 in the ReaderAt.
772 func NewFile(r io.ReaderAt) (*File, error) {
774 sr := io.NewSectionReader(r, 0, 1<<63-1)
776 // Read and decode Mach magic to determine byte order, size.
777 // Magic32 and Magic64 differ only in the bottom bit.
779 if _, err := r.ReadAt(ident[0:], 0); err != nil {
782 be := binary.BigEndian.Uint32(ident[0:])
783 le := binary.LittleEndian.Uint32(ident[0:])
784 switch Magic32 &^ 1 {
786 f.ByteOrder = binary.BigEndian
789 f.ByteOrder = binary.LittleEndian
792 return nil, formatError(0, "invalid magic number be=0x%x, le=0x%x", be, le)
795 // Read entire file header.
796 if err := binary.Read(sr, f.ByteOrder, &f.FileHeader); err != nil {
800 // Then load commands.
801 offset := int64(fileHeaderSize32)
802 if f.Magic == Magic64 {
803 offset = fileHeaderSize64
805 dat := make([]byte, f.SizeCommands)
806 if _, err := r.ReadAt(dat, offset); err != nil {
809 f.Loads = make([]Load, f.NCommands)
811 for i := range f.Loads {
812 // Each load command begins with uint32 command and length.
814 return nil, formatError(offset, "command block too small, len(dat) = %d", len(dat))
816 cmd, siz := LoadCmd(bo.Uint32(dat[0:4])), bo.Uint32(dat[4:8])
817 if siz < 8 || siz > uint32(len(dat)) {
818 return nil, formatError(offset, "invalid command block size, len(dat)=%d, size=%d", len(dat), siz)
821 cmddat, dat = dat[0:siz], dat[siz:]
826 f.Loads[i] = LoadCmdBytes{LoadCmd(cmd), LoadBytes(cmddat)}
830 b := bytes.NewReader(cmddat)
831 if err := binary.Read(b, bo, &hdr); err != nil {
834 l := &Uuid{UuidCmd: hdr}
840 b := bytes.NewReader(cmddat)
841 if err := binary.Read(b, bo, &hdr); err != nil {
844 l := &Rpath{LoadCmd: hdr.LoadCmd}
845 if hdr.Path >= uint32(len(cmddat)) {
846 return nil, formatError(offset, "invalid path in rpath command, len(cmddat)=%d, hdr.Path=%d", len(cmddat), hdr.Path)
848 l.Path = cstring(cmddat[hdr.Path:])
851 case LcLoadDylinker, LcIdDylinker, LcDyldEnvironment:
853 b := bytes.NewReader(cmddat)
854 if err := binary.Read(b, bo, &hdr); err != nil {
858 if hdr.Name >= uint32(len(cmddat)) {
859 return nil, formatError(offset, "invalid name in dynamic linker command, hdr.Name=%d, len(cmddat)=%d", hdr.Name, len(cmddat))
861 l.Name = cstring(cmddat[hdr.Name:])
867 b := bytes.NewReader(cmddat)
868 if err := binary.Read(b, bo, &hdr); err != nil {
872 if hdr.Name >= uint32(len(cmddat)) {
873 return nil, formatError(offset, "invalid name in dynamic library command, hdr.Name=%d, len(cmddat)=%d", hdr.Name, len(cmddat))
875 l.Name = cstring(cmddat[hdr.Name:])
877 l.CurrentVersion = hdr.CurrentVersion
878 l.CompatVersion = hdr.CompatVersion
883 b := bytes.NewReader(cmddat)
884 if err := binary.Read(b, bo, &hdr); err != nil {
887 strtab := make([]byte, hdr.Strsize)
888 if _, err := r.ReadAt(strtab, int64(hdr.Stroff)); err != nil {
892 if f.Magic == Magic64 {
897 symdat := make([]byte, int(hdr.Nsyms)*symsz)
898 if _, err := r.ReadAt(symdat, int64(hdr.Symoff)); err != nil {
901 st, err := f.parseSymtab(symdat, strtab, cmddat, &hdr, offset)
911 b := bytes.NewReader(cmddat)
912 if err := binary.Read(b, bo, &hdr); err != nil {
915 dat := make([]byte, hdr.Nindirectsyms*4)
916 if _, err := r.ReadAt(dat, int64(hdr.Indirectsymoff)); err != nil {
919 x := make([]uint32, hdr.Nindirectsyms)
920 if err := binary.Read(bytes.NewReader(dat), bo, x); err != nil {
931 b := bytes.NewReader(cmddat)
932 if err := binary.Read(b, bo, &seg32); err != nil {
938 s.Name = cstring(seg32.Name[0:])
939 s.Addr = uint64(seg32.Addr)
940 s.Memsz = uint64(seg32.Memsz)
941 s.Offset = uint64(seg32.Offset)
942 s.Filesz = uint64(seg32.Filesz)
943 s.Maxprot = seg32.Maxprot
945 s.Nsect = seg32.Nsect
947 s.Firstsect = uint32(len(f.Sections))
949 for i := 0; i < int(s.Nsect); i++ {
951 if err := binary.Read(b, bo, &sh32); err != nil {
955 sh.Name = cstring(sh32.Name[0:])
956 sh.Seg = cstring(sh32.Seg[0:])
957 sh.Addr = uint64(sh32.Addr)
958 sh.Size = uint64(sh32.Size)
959 sh.Offset = sh32.Offset
960 sh.Align = sh32.Align
961 sh.Reloff = sh32.Reloff
962 sh.Nreloc = sh32.Nreloc
963 sh.Flags = sh32.Flags
964 sh.Reserved1 = sh32.Reserve1
965 sh.Reserved2 = sh32.Reserve2
966 if err := f.pushSection(sh, r); err != nil {
973 b := bytes.NewReader(cmddat)
974 if err := binary.Read(b, bo, &seg64); err != nil {
980 s.Name = cstring(seg64.Name[0:])
982 s.Memsz = seg64.Memsz
983 s.Offset = seg64.Offset
984 s.Filesz = seg64.Filesz
985 s.Maxprot = seg64.Maxprot
987 s.Nsect = seg64.Nsect
989 s.Firstsect = uint32(len(f.Sections))
991 for i := 0; i < int(s.Nsect); i++ {
993 if err := binary.Read(b, bo, &sh64); err != nil {
997 sh.Name = cstring(sh64.Name[0:])
998 sh.Seg = cstring(sh64.Seg[0:])
1001 sh.Offset = sh64.Offset
1002 sh.Align = sh64.Align
1003 sh.Reloff = sh64.Reloff
1004 sh.Nreloc = sh64.Nreloc
1005 sh.Flags = sh64.Flags
1006 sh.Reserved1 = sh64.Reserve1
1007 sh.Reserved2 = sh64.Reserve2
1008 sh.Reserved3 = sh64.Reserve3
1009 if err := f.pushSection(sh, r); err != nil {
1014 case LcCodeSignature, LcSegmentSplitInfo, LcFunctionStarts,
1015 LcDataInCode, LcDylibCodeSignDrs:
1016 var hdr LinkEditDataCmd
1017 b := bytes.NewReader(cmddat)
1019 if err := binary.Read(b, bo, &hdr); err != nil {
1022 l := new(LinkEditData)
1024 l.LinkEditDataCmd = hdr
1027 case LcEncryptionInfo, LcEncryptionInfo64:
1028 var hdr EncryptionInfoCmd
1029 b := bytes.NewReader(cmddat)
1031 if err := binary.Read(b, bo, &hdr); err != nil {
1034 l := new(EncryptionInfo)
1036 l.EncryptionInfoCmd = hdr
1039 case LcDyldInfo, LcDyldInfoOnly:
1041 b := bytes.NewReader(cmddat)
1043 if err := binary.Read(b, bo, &hdr); err != nil {
1052 s.sr = io.NewSectionReader(r, int64(s.Offset), int64(s.Filesz))
1055 if f.Loads[i].LoadSize(&f.FileTOC) != siz {
1056 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())
1063 func (f *File) parseSymtab(symdat, strtab, cmddat []byte, hdr *SymtabCmd, offset int64) (*Symtab, error) {
1065 symtab := make([]Symbol, hdr.Nsyms)
1066 b := bytes.NewReader(symdat)
1067 for i := range symtab {
1069 if f.Magic == Magic64 {
1070 if err := binary.Read(b, bo, &n); err != nil {
1075 if err := binary.Read(b, bo, &n32); err != nil {
1082 n.Value = uint64(n32.Value)
1085 if n.Name >= uint32(len(strtab)) {
1086 return nil, formatError(offset, "invalid name in symbol table, n.Name=%d, len(strtab)=%d", n.Name, len(strtab))
1088 sym.Name = cstring(strtab[n.Name:])
1099 type relocInfo struct {
1104 func (f *File) pushSection(sh *Section, r io.ReaderAt) error {
1105 f.Sections = append(f.Sections, sh)
1106 sh.sr = io.NewSectionReader(r, int64(sh.Offset), int64(sh.Size))
1110 reldat := make([]byte, int(sh.Nreloc)*8)
1111 if _, err := r.ReadAt(reldat, int64(sh.Reloff)); err != nil {
1114 b := bytes.NewReader(reldat)
1118 sh.Relocs = make([]Reloc, sh.Nreloc)
1119 for i := range sh.Relocs {
1120 rel := &sh.Relocs[i]
1123 if err := binary.Read(b, bo, &ri); err != nil {
1127 if ri.Addr&(1<<31) != 0 { // scattered
1128 rel.Addr = ri.Addr & (1<<24 - 1)
1129 rel.Type = uint8((ri.Addr >> 24) & (1<<4 - 1))
1130 rel.Len = uint8((ri.Addr >> 28) & (1<<2 - 1))
1131 rel.Pcrel = ri.Addr&(1<<30) != 0
1132 rel.Value = ri.Symnum
1133 rel.Scattered = true
1136 case binary.LittleEndian:
1138 rel.Value = ri.Symnum & (1<<24 - 1)
1139 rel.Pcrel = ri.Symnum&(1<<24) != 0
1140 rel.Len = uint8((ri.Symnum >> 25) & (1<<2 - 1))
1141 rel.Extern = ri.Symnum&(1<<27) != 0
1142 rel.Type = uint8((ri.Symnum >> 28) & (1<<4 - 1))
1143 case binary.BigEndian:
1145 rel.Value = ri.Symnum >> 8
1146 rel.Pcrel = ri.Symnum&(1<<7) != 0
1147 rel.Len = uint8((ri.Symnum >> 5) & (1<<2 - 1))
1148 rel.Extern = ri.Symnum&(1<<4) != 0
1149 rel.Type = uint8(ri.Symnum & (1<<4 - 1))
1151 panic("unreachable")
1160 func cstring(b []byte) string {
1161 i := bytes.IndexByte(b, 0)
1165 return string(b[0:i])
1168 // Segment returns the first Segment with the given name, or nil if no such segment exists.
1169 func (f *File) Segment(name string) *Segment {
1170 for _, l := range f.Loads {
1171 if s, ok := l.(*Segment); ok && s.Name == name {
1178 // Section returns the first section with the given name, or nil if no such
1180 func (f *File) Section(name string) *Section {
1181 for _, s := range f.Sections {
1189 // DWARF returns the DWARF debug information for the Mach-O file.
1190 func (f *File) DWARF() (*dwarf.Data, error) {
1191 dwarfSuffix := func(s *Section) string {
1193 case strings.HasPrefix(s.Name, "__debug_"):
1195 case strings.HasPrefix(s.Name, "__zdebug_"):
1202 sectionData := func(s *Section) ([]byte, error) {
1204 if err != nil && uint64(len(b)) < s.Size {
1208 if len(b) >= 12 && string(b[:4]) == "ZLIB" {
1209 dlen := binary.BigEndian.Uint64(b[4:12])
1210 dbuf := make([]byte, dlen)
1211 r, err := zlib.NewReader(bytes.NewBuffer(b[12:]))
1215 if _, err := io.ReadFull(r, dbuf); err != nil {
1218 if err := r.Close(); err != nil {
1226 // There are many other DWARF sections, but these
1227 // are the ones the debug/dwarf package uses.
1228 // Don't bother loading others.
1229 var dat = map[string][]byte{"abbrev": nil, "info": nil, "str": nil, "line": nil, "ranges": nil}
1230 for _, s := range f.Sections {
1231 suffix := dwarfSuffix(s)
1235 if _, ok := dat[suffix]; !ok {
1238 b, err := sectionData(s)
1245 d, err := dwarf.New(dat["abbrev"], nil, nil, dat["info"], dat["line"], nil, dat["ranges"], dat["str"])
1250 // Look for DWARF4 .debug_types sections.
1251 for i, s := range f.Sections {
1252 suffix := dwarfSuffix(s)
1253 if suffix != "types" {
1257 b, err := sectionData(s)
1262 err = d.AddTypes(fmt.Sprintf("types-%d", i), b)
1271 // ImportedSymbols returns the names of all symbols
1272 // referred to by the binary f that are expected to be
1273 // satisfied by other libraries at dynamic load time.
1274 func (f *File) ImportedSymbols() ([]string, error) {
1275 if f.Dysymtab == nil || f.Symtab == nil {
1276 return nil, formatError(0, "missing symbol table, f.Dsymtab=%v, f.Symtab=%v", f.Dysymtab, f.Symtab)
1282 for _, s := range st.Syms[dt.Iundefsym : dt.Iundefsym+dt.Nundefsym] {
1283 all = append(all, s.Name)
1288 // ImportedLibraries returns the paths of all libraries
1289 // referred to by the binary f that are expected to be
1290 // linked with the binary at dynamic link time.
1291 func (f *File) ImportedLibraries() ([]string, error) {
1293 for _, l := range f.Loads {
1294 if lib, ok := l.(*Dylib); ok {
1295 all = append(all, lib.Name)
1301 func RoundUp(x, align uint64) uint64 {
1302 return uint64((x + align - 1) & -align)