github.com/decomp/exp@v0.0.0-20210624183419-6d058f5e1da6/bin/raw/raw.go (about)

     1  // Package raw provides access to raw binary executables.
     2  package raw
     3  
     4  import (
     5  	"io"
     6  	"io/ioutil"
     7  	"os"
     8  
     9  	"github.com/decomp/exp/bin"
    10  	"github.com/pkg/errors"
    11  )
    12  
    13  // ParseFile parses the given raw binary executable, reading from path.
    14  //
    15  // The entry point and base address are both 0 by default. To specify a custom
    16  // entry point, set file.Entry, and to specify a custom base address, set
    17  // file.Sections[0].Addr.
    18  func ParseFile(path string, arch bin.Arch) (*bin.File, error) {
    19  	f, err := os.Open(path)
    20  	if err != nil {
    21  		return nil, errors.WithStack(err)
    22  	}
    23  	defer f.Close()
    24  	return Parse(f, arch)
    25  }
    26  
    27  // Parse parses the given raw binary executable, reading from r.
    28  //
    29  // The entry point and base address are both 0 by default. To specify a custom
    30  // entry point, set file.Entry, and to specify a custom base address, set
    31  // file.Sections[0].Addr.
    32  func Parse(r io.Reader, arch bin.Arch) (*bin.File, error) {
    33  	// Parse segments.
    34  	file := &bin.File{
    35  		Arch: arch,
    36  	}
    37  	data, err := ioutil.ReadAll(r)
    38  	if err != nil {
    39  		return nil, errors.WithStack(err)
    40  	}
    41  	seg := &bin.Section{
    42  		Addr:     0,
    43  		Data:     data,
    44  		FileSize: len(data),
    45  		MemSize:  len(data),
    46  		Perm:     bin.PermR | bin.PermW | bin.PermX,
    47  	}
    48  	file.Sections = append(file.Sections, seg)
    49  	return file, nil
    50  }