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 elf implements access to ELF object files.
18 // TODO: error reporting detail
21 * Internal ELF representation
24 // A FileHeader represents an ELF file header.
25 type FileHeader struct {
31 ByteOrder binary.ByteOrder
36 // A File represents an open ELF file.
46 // A SectionHeader represents a single ELF section header.
47 type SectionHeader struct {
60 // A Section represents a single section in an ELF file.
64 // Embed ReaderAt for ReadAt method.
65 // Do not embed SectionReader directly
66 // to avoid having Read and Seek.
67 // If a client wants Read and Seek it must use
68 // Open() to avoid fighting over the seek offset
69 // with other clients.
74 // Data reads and returns the contents of the ELF section.
75 func (s *Section) Data() ([]byte, error) {
76 dat := make([]byte, s.sr.Size())
77 n, err := s.sr.ReadAt(dat, 0)
81 // stringTable reads and returns the string table given by the
82 // specified link value.
83 func (f *File) stringTable(link uint32) ([]byte, error) {
84 if link <= 0 || link >= uint32(len(f.Sections)) {
85 return nil, errors.New("section has invalid string table link")
87 return f.Sections[link].Data()
90 // Open returns a new ReadSeeker reading the ELF section.
91 func (s *Section) Open() io.ReadSeeker { return io.NewSectionReader(s.sr, 0, 1<<63-1) }
93 // A ProgHeader represents a single ELF program header.
94 type ProgHeader struct {
105 // A Prog represents a single ELF program header in an ELF binary.
109 // Embed ReaderAt for ReadAt method.
110 // Do not embed SectionReader directly
111 // to avoid having Read and Seek.
112 // If a client wants Read and Seek it must use
113 // Open() to avoid fighting over the seek offset
114 // with other clients.
119 // Open returns a new ReadSeeker reading the ELF program body.
120 func (p *Prog) Open() io.ReadSeeker { return io.NewSectionReader(p.sr, 0, 1<<63-1) }
122 // A Symbol represents an entry in an ELF symbol table section.
134 type FormatError struct {
140 func (e *FormatError) Error() string {
143 msg += fmt.Sprintf(" '%v' ", e.val)
145 msg += fmt.Sprintf("in record at byte %#x", e.off)
149 // Open opens the named file using os.Open and prepares it for use as an ELF binary.
150 func Open(name string) (*File, error) {
151 f, err := os.Open(name)
155 ff, err := NewFile(f)
164 // Close closes the File.
165 // If the File was created using NewFile directly instead of Open,
166 // Close has no effect.
167 func (f *File) Close() error {
170 err = f.closer.Close()
176 // SectionByType returns the first section in f with the
177 // given type, or nil if there is no such section.
178 func (f *File) SectionByType(typ SectionType) *Section {
179 for _, s := range f.Sections {
187 // NewFile creates a new File for accessing an ELF binary in an underlying reader.
188 // The ELF binary is expected to start at position 0 in the ReaderAt.
189 func NewFile(r io.ReaderAt) (*File, error) {
190 sr := io.NewSectionReader(r, 0, 1<<63-1)
191 // Read and decode ELF identifier
193 if _, err := r.ReadAt(ident[0:], 0); err != nil {
196 if ident[0] != '\x7f' || ident[1] != 'E' || ident[2] != 'L' || ident[3] != 'F' {
197 return nil, &FormatError{0, "bad magic number", ident[0:4]}
201 f.Class = Class(ident[EI_CLASS])
207 return nil, &FormatError{0, "unknown ELF class", f.Class}
210 f.Data = Data(ident[EI_DATA])
213 f.ByteOrder = binary.LittleEndian
215 f.ByteOrder = binary.BigEndian
217 return nil, &FormatError{0, "unknown ELF data encoding", f.Data}
220 f.Version = Version(ident[EI_VERSION])
221 if f.Version != EV_CURRENT {
222 return nil, &FormatError{0, "unknown ELF version", f.Version}
225 f.OSABI = OSABI(ident[EI_OSABI])
226 f.ABIVersion = ident[EI_ABIVERSION]
228 // Read ELF file header
230 var phentsize, phnum int
232 var shentsize, shnum, shstrndx int
237 sr.Seek(0, os.SEEK_SET)
238 if err := binary.Read(sr, f.ByteOrder, hdr); err != nil {
241 f.Type = Type(hdr.Type)
242 f.Machine = Machine(hdr.Machine)
243 if v := Version(hdr.Version); v != f.Version {
244 return nil, &FormatError{0, "mismatched ELF version", v}
246 phoff = int64(hdr.Phoff)
247 phentsize = int(hdr.Phentsize)
248 phnum = int(hdr.Phnum)
249 shoff = int64(hdr.Shoff)
250 shentsize = int(hdr.Shentsize)
251 shnum = int(hdr.Shnum)
252 shstrndx = int(hdr.Shstrndx)
255 sr.Seek(0, os.SEEK_SET)
256 if err := binary.Read(sr, f.ByteOrder, hdr); err != nil {
259 f.Type = Type(hdr.Type)
260 f.Machine = Machine(hdr.Machine)
261 if v := Version(hdr.Version); v != f.Version {
262 return nil, &FormatError{0, "mismatched ELF version", v}
264 phoff = int64(hdr.Phoff)
265 phentsize = int(hdr.Phentsize)
266 phnum = int(hdr.Phnum)
267 shoff = int64(hdr.Shoff)
268 shentsize = int(hdr.Shentsize)
269 shnum = int(hdr.Shnum)
270 shstrndx = int(hdr.Shstrndx)
272 if shstrndx < 0 || shstrndx >= shnum {
273 return nil, &FormatError{0, "invalid ELF shstrndx", shstrndx}
276 // Read program headers
277 f.Progs = make([]*Prog, phnum)
278 for i := 0; i < phnum; i++ {
279 off := phoff + int64(i)*int64(phentsize)
280 sr.Seek(off, os.SEEK_SET)
285 if err := binary.Read(sr, f.ByteOrder, ph); err != nil {
288 p.ProgHeader = ProgHeader{
289 Type: ProgType(ph.Type),
290 Flags: ProgFlag(ph.Flags),
292 Vaddr: uint64(ph.Vaddr),
293 Paddr: uint64(ph.Paddr),
294 Filesz: uint64(ph.Filesz),
295 Memsz: uint64(ph.Memsz),
296 Align: uint64(ph.Align),
300 if err := binary.Read(sr, f.ByteOrder, ph); err != nil {
303 p.ProgHeader = ProgHeader{
304 Type: ProgType(ph.Type),
305 Flags: ProgFlag(ph.Flags),
307 Vaddr: uint64(ph.Vaddr),
308 Paddr: uint64(ph.Paddr),
309 Filesz: uint64(ph.Filesz),
310 Memsz: uint64(ph.Memsz),
311 Align: uint64(ph.Align),
314 p.sr = io.NewSectionReader(r, int64(p.Off), int64(p.Filesz))
319 // Read section headers
320 f.Sections = make([]*Section, shnum)
321 names := make([]uint32, shnum)
322 for i := 0; i < shnum; i++ {
323 off := shoff + int64(i)*int64(shentsize)
324 sr.Seek(off, os.SEEK_SET)
329 if err := binary.Read(sr, f.ByteOrder, sh); err != nil {
333 s.SectionHeader = SectionHeader{
334 Type: SectionType(sh.Type),
335 Flags: SectionFlag(sh.Flags),
336 Addr: uint64(sh.Addr),
337 Offset: uint64(sh.Off),
338 Size: uint64(sh.Size),
339 Link: uint32(sh.Link),
340 Info: uint32(sh.Info),
341 Addralign: uint64(sh.Addralign),
342 Entsize: uint64(sh.Entsize),
346 if err := binary.Read(sr, f.ByteOrder, sh); err != nil {
350 s.SectionHeader = SectionHeader{
351 Type: SectionType(sh.Type),
352 Flags: SectionFlag(sh.Flags),
353 Offset: uint64(sh.Off),
354 Size: uint64(sh.Size),
355 Addr: uint64(sh.Addr),
356 Link: uint32(sh.Link),
357 Info: uint32(sh.Info),
358 Addralign: uint64(sh.Addralign),
359 Entsize: uint64(sh.Entsize),
362 s.sr = io.NewSectionReader(r, int64(s.Offset), int64(s.Size))
367 // Load section header string table.
368 shstrtab, err := f.Sections[shstrndx].Data()
372 for i, s := range f.Sections {
374 s.Name, ok = getString(shstrtab, int(names[i]))
376 return nil, &FormatError{shoff + int64(i*shentsize), "bad section name index", names[i]}
383 // getSymbols returns a slice of Symbols from parsing the symbol table
384 // with the given type, along with the associated string table.
385 func (f *File) getSymbols(typ SectionType) ([]Symbol, []byte, error) {
388 return f.getSymbols64(typ)
391 return f.getSymbols32(typ)
394 return nil, nil, errors.New("not implemented")
397 func (f *File) getSymbols32(typ SectionType) ([]Symbol, []byte, error) {
398 symtabSection := f.SectionByType(typ)
399 if symtabSection == nil {
400 return nil, nil, errors.New("no symbol section")
403 data, err := symtabSection.Data()
405 return nil, nil, errors.New("cannot load symbol section")
407 symtab := bytes.NewBuffer(data)
408 if symtab.Len()%Sym32Size != 0 {
409 return nil, nil, errors.New("length of symbol section is not a multiple of SymSize")
412 strdata, err := f.stringTable(symtabSection.Link)
414 return nil, nil, errors.New("cannot load string table section")
417 // The first entry is all zeros.
418 var skip [Sym32Size]byte
419 symtab.Read(skip[0:])
421 symbols := make([]Symbol, symtab.Len()/Sym32Size)
425 for symtab.Len() > 0 {
426 binary.Read(symtab, f.ByteOrder, &sym)
427 str, _ := getString(strdata, int(sym.Name))
428 symbols[i].Name = str
429 symbols[i].Info = sym.Info
430 symbols[i].Other = sym.Other
431 symbols[i].Section = SectionIndex(sym.Shndx)
432 symbols[i].Value = uint64(sym.Value)
433 symbols[i].Size = uint64(sym.Size)
437 return symbols, strdata, nil
440 func (f *File) getSymbols64(typ SectionType) ([]Symbol, []byte, error) {
441 symtabSection := f.SectionByType(typ)
442 if symtabSection == nil {
443 return nil, nil, errors.New("no symbol section")
446 data, err := symtabSection.Data()
448 return nil, nil, errors.New("cannot load symbol section")
450 symtab := bytes.NewBuffer(data)
451 if symtab.Len()%Sym64Size != 0 {
452 return nil, nil, errors.New("length of symbol section is not a multiple of Sym64Size")
455 strdata, err := f.stringTable(symtabSection.Link)
457 return nil, nil, errors.New("cannot load string table section")
460 // The first entry is all zeros.
461 var skip [Sym64Size]byte
462 symtab.Read(skip[0:])
464 symbols := make([]Symbol, symtab.Len()/Sym64Size)
468 for symtab.Len() > 0 {
469 binary.Read(symtab, f.ByteOrder, &sym)
470 str, _ := getString(strdata, int(sym.Name))
471 symbols[i].Name = str
472 symbols[i].Info = sym.Info
473 symbols[i].Other = sym.Other
474 symbols[i].Section = SectionIndex(sym.Shndx)
475 symbols[i].Value = sym.Value
476 symbols[i].Size = sym.Size
480 return symbols, strdata, nil
483 // getString extracts a string from an ELF string table.
484 func getString(section []byte, start int) (string, bool) {
485 if start < 0 || start >= len(section) {
489 for end := start; end < len(section); end++ {
490 if section[end] == 0 {
491 return string(section[start:end]), true
497 // Section returns a section with the given name, or nil if no such
499 func (f *File) Section(name string) *Section {
500 for _, s := range f.Sections {
508 // applyRelocations applies relocations to dst. rels is a relocations section
510 func (f *File) applyRelocations(dst []byte, rels []byte) error {
511 if f.Class == ELFCLASS64 && f.Machine == EM_X86_64 {
512 return f.applyRelocationsAMD64(dst, rels)
515 return errors.New("not implemented")
518 func (f *File) applyRelocationsAMD64(dst []byte, rels []byte) error {
519 if len(rels)%Sym64Size != 0 {
520 return errors.New("length of relocation section is not a multiple of Sym64Size")
523 symbols, _, err := f.getSymbols(SHT_SYMTAB)
528 b := bytes.NewBuffer(rels)
532 binary.Read(b, f.ByteOrder, &rela)
533 symNo := rela.Info >> 32
534 t := R_X86_64(rela.Info & 0xffff)
536 if symNo >= uint64(len(symbols)) {
539 sym := &symbols[symNo]
540 if SymType(sym.Info&0xf) != STT_SECTION {
541 // We don't handle non-section relocations for now.
547 if rela.Off+8 >= uint64(len(dst)) || rela.Addend < 0 {
550 f.ByteOrder.PutUint64(dst[rela.Off:rela.Off+8], uint64(rela.Addend))
552 if rela.Off+4 >= uint64(len(dst)) || rela.Addend < 0 {
555 f.ByteOrder.PutUint32(dst[rela.Off:rela.Off+4], uint32(rela.Addend))
562 func (f *File) DWARF() (*dwarf.Data, error) {
563 // There are many other DWARF sections, but these
564 // are the required ones, and the debug/dwarf package
565 // does not use the others, so don't bother loading them.
566 var names = [...]string{"abbrev", "info", "line", "ranges", "str"}
567 var dat [len(names)][]byte
568 for i, name := range names {
569 name = ".debug_" + name
575 if err != nil && uint64(len(b)) < s.Size {
581 // If there's a relocation table for .debug_info, we have to process it
582 // now otherwise the data in .debug_info is invalid for x86-64 objects.
583 rela := f.Section(".rela.debug_info")
584 if rela != nil && rela.Type == SHT_RELA && f.Machine == EM_X86_64 {
585 data, err := rela.Data()
589 err = f.applyRelocations(dat[1], data)
595 abbrev, info, line, ranges, str := dat[0], dat[1], dat[2], dat[3], dat[4]
596 return dwarf.New(abbrev, nil, nil, info, line, nil, ranges, str)
599 // Symbols returns the symbol table for f.
600 func (f *File) Symbols() ([]Symbol, error) {
601 sym, _, err := f.getSymbols(SHT_SYMTAB)
605 type ImportedSymbol struct {
611 // ImportedSymbols returns the names of all symbols
612 // referred to by the binary f that are expected to be
613 // satisfied by other libraries at dynamic load time.
614 // It does not return weak symbols.
615 func (f *File) ImportedSymbols() ([]ImportedSymbol, error) {
616 sym, str, err := f.getSymbols(SHT_DYNSYM)
620 f.gnuVersionInit(str)
621 var all []ImportedSymbol
622 for i, s := range sym {
623 if ST_BIND(s.Info) == STB_GLOBAL && s.Section == SHN_UNDEF {
624 all = append(all, ImportedSymbol{Name: s.Name})
625 f.gnuVersion(i, &all[len(all)-1])
631 type verneed struct {
636 // gnuVersionInit parses the GNU version tables
637 // for use by calls to gnuVersion.
638 func (f *File) gnuVersionInit(str []byte) {
639 // Accumulate verneed information.
640 vn := f.SectionByType(SHT_GNU_VERNEED)
652 vers := f.ByteOrder.Uint16(d[i : i+2])
656 cnt := f.ByteOrder.Uint16(d[i+2 : i+4])
657 fileoff := f.ByteOrder.Uint32(d[i+4 : i+8])
658 aux := f.ByteOrder.Uint32(d[i+8 : i+12])
659 next := f.ByteOrder.Uint32(d[i+12 : i+16])
660 file, _ := getString(str, int(fileoff))
664 for c := 0; c < int(cnt); c++ {
668 // hash := f.ByteOrder.Uint32(d[j:j+4])
669 // flags := f.ByteOrder.Uint16(d[j+4:j+6])
670 other := f.ByteOrder.Uint16(d[j+6 : j+8])
671 nameoff := f.ByteOrder.Uint32(d[j+8 : j+12])
672 next := f.ByteOrder.Uint32(d[j+12 : j+16])
673 name, _ = getString(str, int(nameoff))
675 if ndx >= len(need) {
676 a := make([]verneed, 2*(ndx+1))
681 need[ndx] = verneed{file, name}
694 // Versym parallels symbol table, indexing into verneed.
695 vs := f.SectionByType(SHT_GNU_VERSYM)
705 // gnuVersion adds Library and Version information to sym,
706 // which came from offset i of the symbol table.
707 func (f *File) gnuVersion(i int, sym *ImportedSymbol) {
708 // Each entry is two bytes; skip undef entry at beginning.
710 if i >= len(f.gnuVersym) {
713 j := int(f.ByteOrder.Uint16(f.gnuVersym[i:]))
714 if j < 2 || j >= len(f.gnuNeed) {
722 // ImportedLibraries returns the names of all libraries
723 // referred to by the binary f that are expected to be
724 // linked with the binary at dynamic link time.
725 func (f *File) ImportedLibraries() ([]string, error) {
726 ds := f.SectionByType(SHT_DYNAMIC)
728 // not dynamic, so no libraries
735 str, err := f.stringTable(ds.Link)
745 tag = DynTag(f.ByteOrder.Uint32(d[0:4]))
746 value = uint64(f.ByteOrder.Uint32(d[4:8]))
749 tag = DynTag(f.ByteOrder.Uint64(d[0:8]))
750 value = f.ByteOrder.Uint64(d[8:16])
753 if tag == DT_NEEDED {
754 s, ok := getString(str, int(value))