github.com/razvanm/vanadium-go-1.3@v0.0.0-20160721203343-4a65068e5915/src/cmd/internal/objfile/objfile.go (about)

     1  // Copyright 2014 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 objfile implements portable access to OS-specific executable files.
     6  package objfile
     7  
     8  import (
     9  	"debug/gosym"
    10  	"fmt"
    11  	"os"
    12  )
    13  
    14  type rawFile interface {
    15  	symbols() (syms []Sym, err error)
    16  	pcln() (textStart uint64, symtab, pclntab []byte, err error)
    17  }
    18  
    19  // A File is an opened executable file.
    20  type File struct {
    21  	r   *os.File
    22  	raw rawFile
    23  }
    24  
    25  // A Sym is a symbol defined in an executable file.
    26  type Sym struct {
    27  	Name string // symbol name
    28  	Addr uint64 // virtual address of symbol
    29  	Size int64  // size in bytes
    30  	Code rune   // nm code (T for text, D for data, and so on)
    31  	Type string // XXX?
    32  }
    33  
    34  var openers = []func(*os.File) (rawFile, error){
    35  	openElf,
    36  	openGoobj,
    37  	openMacho,
    38  	openPE,
    39  	openPlan9,
    40  }
    41  
    42  // Open opens the named file.
    43  // The caller must call f.Close when the file is no longer needed.
    44  func Open(name string) (*File, error) {
    45  	r, err := os.Open(name)
    46  	if err != nil {
    47  		return nil, err
    48  	}
    49  	for _, try := range openers {
    50  		if raw, err := try(r); err == nil {
    51  			return &File{r, raw}, nil
    52  		}
    53  	}
    54  	r.Close()
    55  	return nil, fmt.Errorf("open %s: unrecognized object file", name)
    56  }
    57  
    58  func (f *File) Close() error {
    59  	return f.r.Close()
    60  }
    61  
    62  func (f *File) Symbols() ([]Sym, error) {
    63  	return f.raw.symbols()
    64  }
    65  
    66  func (f *File) PCLineTable() (*gosym.Table, error) {
    67  	textStart, symtab, pclntab, err := f.raw.pcln()
    68  	if err != nil {
    69  		return nil, err
    70  	}
    71  	return gosym.NewTable(symtab, gosym.NewLineTable(pclntab, textStart))
    72  }