...
Run Format

Source file src/go/internal/gccgoimporter/importer.go

Documentation: go/internal/gccgoimporter

     1  // Copyright 2013 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 gccgoimporter implements Import for gccgo-generated object files.
     6  package gccgoimporter // import "go/internal/gccgoimporter"
     7  
     8  import (
     9  	"debug/elf"
    10  	"fmt"
    11  	"go/types"
    12  	"io"
    13  	"os"
    14  	"path/filepath"
    15  	"strings"
    16  )
    17  
    18  // A PackageInit describes an imported package that needs initialization.
    19  type PackageInit struct {
    20  	Name     string // short package name
    21  	InitFunc string // name of init function
    22  	Priority int    // priority of init function, see InitData.Priority
    23  }
    24  
    25  // The gccgo-specific init data for a package.
    26  type InitData struct {
    27  	// Initialization priority of this package relative to other packages.
    28  	// This is based on the maximum depth of the package's dependency graph;
    29  	// it is guaranteed to be greater than that of its dependencies.
    30  	Priority int
    31  
    32  	// The list of packages which this package depends on to be initialized,
    33  	// including itself if needed. This is the subset of the transitive closure of
    34  	// the package's dependencies that need initialization.
    35  	Inits []PackageInit
    36  }
    37  
    38  // Locate the file from which to read export data.
    39  // This is intended to replicate the logic in gofrontend.
    40  func findExportFile(searchpaths []string, pkgpath string) (string, error) {
    41  	for _, spath := range searchpaths {
    42  		pkgfullpath := filepath.Join(spath, pkgpath)
    43  		pkgdir, name := filepath.Split(pkgfullpath)
    44  
    45  		for _, filepath := range [...]string{
    46  			pkgfullpath,
    47  			pkgfullpath + ".gox",
    48  			pkgdir + "lib" + name + ".so",
    49  			pkgdir + "lib" + name + ".a",
    50  			pkgfullpath + ".o",
    51  		} {
    52  			fi, err := os.Stat(filepath)
    53  			if err == nil && !fi.IsDir() {
    54  				return filepath, nil
    55  			}
    56  		}
    57  	}
    58  
    59  	return "", fmt.Errorf("%s: could not find export data (tried %s)", pkgpath, strings.Join(searchpaths, ":"))
    60  }
    61  
    62  const (
    63  	gccgov1Magic    = "v1;\n"
    64  	gccgov2Magic    = "v2;\n"
    65  	goimporterMagic = "\n$$ "
    66  	archiveMagic    = "!<ar"
    67  )
    68  
    69  // Opens the export data file at the given path. If this is an ELF file,
    70  // searches for and opens the .go_export section. If this is an archive,
    71  // reads the export data from the first member, which is assumed to be an ELF file.
    72  // This is intended to replicate the logic in gofrontend.
    73  func openExportFile(fpath string) (reader io.ReadSeeker, closer io.Closer, err error) {
    74  	f, err := os.Open(fpath)
    75  	if err != nil {
    76  		return
    77  	}
    78  	closer = f
    79  	defer func() {
    80  		if err != nil && closer != nil {
    81  			f.Close()
    82  		}
    83  	}()
    84  
    85  	var magic [4]byte
    86  	_, err = f.ReadAt(magic[:], 0)
    87  	if err != nil {
    88  		return
    89  	}
    90  
    91  	var elfreader io.ReaderAt
    92  	switch string(magic[:]) {
    93  	case gccgov1Magic, gccgov2Magic, goimporterMagic:
    94  		// Raw export data.
    95  		reader = f
    96  		return
    97  
    98  	case archiveMagic:
    99  		reader, err = arExportData(f)
   100  		return
   101  
   102  	default:
   103  		elfreader = f
   104  	}
   105  
   106  	ef, err := elf.NewFile(elfreader)
   107  	if err != nil {
   108  		return
   109  	}
   110  
   111  	sec := ef.Section(".go_export")
   112  	if sec == nil {
   113  		err = fmt.Errorf("%s: .go_export section not found", fpath)
   114  		return
   115  	}
   116  
   117  	reader = sec.Open()
   118  	return
   119  }
   120  
   121  // An Importer resolves import paths to Packages. The imports map records
   122  // packages already known, indexed by package path.
   123  // An importer must determine the canonical package path and check imports
   124  // to see if it is already present in the map. If so, the Importer can return
   125  // the map entry. Otherwise, the importer must load the package data for the
   126  // given path into a new *Package, record it in imports map, and return the
   127  // package.
   128  type Importer func(imports map[string]*types.Package, path, srcDir string, lookup func(string) (io.ReadCloser, error)) (*types.Package, error)
   129  
   130  func GetImporter(searchpaths []string, initmap map[*types.Package]InitData) Importer {
   131  	return func(imports map[string]*types.Package, pkgpath, srcDir string, lookup func(string) (io.ReadCloser, error)) (pkg *types.Package, err error) {
   132  		// TODO(gri): Use srcDir.
   133  		// Or not. It's possible that srcDir will fade in importance as
   134  		// the go command and other tools provide a translation table
   135  		// for relative imports (like ./foo or vendored imports).
   136  		if pkgpath == "unsafe" {
   137  			return types.Unsafe, nil
   138  		}
   139  
   140  		var reader io.ReadSeeker
   141  		var fpath string
   142  		var rc io.ReadCloser
   143  		if lookup != nil {
   144  			if p := imports[pkgpath]; p != nil && p.Complete() {
   145  				return p, nil
   146  			}
   147  			rc, err = lookup(pkgpath)
   148  			if err != nil {
   149  				return nil, err
   150  			}
   151  		}
   152  		if rc != nil {
   153  			defer rc.Close()
   154  			rs, ok := rc.(io.ReadSeeker)
   155  			if !ok {
   156  				return nil, fmt.Errorf("gccgo importer requires lookup to return an io.ReadSeeker, have %T", rc)
   157  			}
   158  			reader = rs
   159  			fpath = "<lookup " + pkgpath + ">"
   160  			// Take name from Name method (like on os.File) if present.
   161  			if n, ok := rc.(interface{ Name() string }); ok {
   162  				fpath = n.Name()
   163  			}
   164  		} else {
   165  			fpath, err = findExportFile(searchpaths, pkgpath)
   166  			if err != nil {
   167  				return nil, err
   168  			}
   169  
   170  			r, closer, err := openExportFile(fpath)
   171  			if err != nil {
   172  				return nil, err
   173  			}
   174  			if closer != nil {
   175  				defer closer.Close()
   176  			}
   177  			reader = r
   178  		}
   179  
   180  		var magics string
   181  		magics, err = readMagic(reader)
   182  		if err != nil {
   183  			return
   184  		}
   185  
   186  		if magics == archiveMagic {
   187  			reader, err = arExportData(reader)
   188  			if err != nil {
   189  				return
   190  			}
   191  			magics, err = readMagic(reader)
   192  			if err != nil {
   193  				return
   194  			}
   195  		}
   196  
   197  		switch magics {
   198  		case gccgov1Magic, gccgov2Magic:
   199  			var p parser
   200  			p.init(fpath, reader, imports)
   201  			pkg = p.parsePackage()
   202  			if initmap != nil {
   203  				initmap[pkg] = p.initdata
   204  			}
   205  
   206  		// Excluded for now: Standard gccgo doesn't support this import format currently.
   207  		// case goimporterMagic:
   208  		// 	var data []byte
   209  		// 	data, err = ioutil.ReadAll(reader)
   210  		// 	if err != nil {
   211  		// 		return
   212  		// 	}
   213  		// 	var n int
   214  		// 	n, pkg, err = importer.ImportData(imports, data)
   215  		// 	if err != nil {
   216  		// 		return
   217  		// 	}
   218  
   219  		// 	if initmap != nil {
   220  		// 		suffixreader := bytes.NewReader(data[n:])
   221  		// 		var p parser
   222  		// 		p.init(fpath, suffixreader, nil)
   223  		// 		p.parseInitData()
   224  		// 		initmap[pkg] = p.initdata
   225  		// 	}
   226  
   227  		default:
   228  			err = fmt.Errorf("unrecognized magic string: %q", magics)
   229  		}
   230  
   231  		return
   232  	}
   233  }
   234  
   235  // readMagic reads the four bytes at the start of a ReadSeeker and
   236  // returns them as a string.
   237  func readMagic(reader io.ReadSeeker) (string, error) {
   238  	var magic [4]byte
   239  	if _, err := reader.Read(magic[:]); err != nil {
   240  		return "", err
   241  	}
   242  	if _, err := reader.Seek(0, io.SeekStart); err != nil {
   243  		return "", err
   244  	}
   245  	return string(magic[:]), nil
   246  }
   247  

View as plain text