github.com/lsg2020/gort@v0.0.0-20220515072951-7a7794baa036/gort.go (about)

     1  package gort
     2  
     3  import (
     4  	"errors"
     5  	"os"
     6  	"reflect"
     7  	"runtime"
     8  
     9  	"github.com/go-delve/delve/pkg/proc"
    10  )
    11  
    12  var (
    13  	ErrNeedInit         = errors.New("need init")
    14  	ErrNotFound         = errors.New("not found")
    15  	ErrNotSupport       = errors.New("not support")
    16  	ErrTooManyLibraries = errors.New("number of loaded libraries exceeds maximum")
    17  )
    18  
    19  func NewDwarfRT(path string) (*DwarfRT, error) {
    20  	return (&DwarfRT{}).init(path)
    21  }
    22  
    23  type DwarfRT struct {
    24  	bi *proc.BinaryInfo
    25  
    26  	mds             []moduleData
    27  	globals         map[string]reflect.Value
    28  	imageCacheTypes map[*proc.Image]map[string]uint64
    29  }
    30  
    31  func (d *DwarfRT) init(path string) (*DwarfRT, error) {
    32  	var err error
    33  	if path == "" {
    34  		if path, err = os.Executable(); err != nil {
    35  			return nil, err
    36  		}
    37  	}
    38  
    39  	bi := proc.NewBinaryInfo(runtime.GOOS, runtime.GOARCH)
    40  	err = bi.LoadBinaryInfo(path, 0, nil)
    41  	if err != nil {
    42  		return nil, err
    43  	}
    44  	d.bi = bi
    45  
    46  	if err = d.refreshModule(); err != nil {
    47  		return nil, err
    48  	}
    49  	return d, nil
    50  }
    51  
    52  func (d *DwarfRT) AddImage(path string, addr uint64) error {
    53  	if err := d.check(); err != nil {
    54  		return err
    55  	}
    56  
    57  	if err := d.bi.AddImage(path, addr); err != nil {
    58  		return err
    59  	}
    60  	return d.refreshModule()
    61  }
    62  
    63  func (d *DwarfRT) refreshModule() error {
    64  	mds, err := loadModuleData(d.bi, new(localMemory))
    65  	if err != nil {
    66  		return err
    67  	}
    68  	d.mds = mds
    69  	d.globals = nil
    70  	return nil
    71  }
    72  
    73  func (d *DwarfRT) check() error {
    74  	if d.bi == nil {
    75  		return ErrNeedInit
    76  	}
    77  	return nil
    78  }
    79  
    80  func (d *DwarfRT) BI() *proc.BinaryInfo {
    81  	return d.bi
    82  }