Source file src/cmd/compile/internal/noder/import.go

     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.
     4  
     5  package noder
     6  
     7  import (
     8  	"errors"
     9  	"fmt"
    10  	"internal/buildcfg"
    11  	"internal/exportdata"
    12  	"internal/pkgbits"
    13  	"os"
    14  	pathpkg "path"
    15  	"runtime"
    16  	"strings"
    17  	"unicode"
    18  	"unicode/utf8"
    19  
    20  	"cmd/compile/internal/base"
    21  	"cmd/compile/internal/importer"
    22  	"cmd/compile/internal/ir"
    23  	"cmd/compile/internal/typecheck"
    24  	"cmd/compile/internal/types"
    25  	"cmd/compile/internal/types2"
    26  	"cmd/internal/bio"
    27  	"cmd/internal/goobj"
    28  	"cmd/internal/objabi"
    29  )
    30  
    31  type gcimports struct {
    32  	ctxt     *types2.Context
    33  	packages map[string]*types2.Package
    34  }
    35  
    36  func (m *gcimports) Import(path string) (*types2.Package, error) {
    37  	return m.ImportFrom(path, "" /* no vendoring */, 0)
    38  }
    39  
    40  func (m *gcimports) ImportFrom(path, srcDir string, mode types2.ImportMode) (*types2.Package, error) {
    41  	if mode != 0 {
    42  		panic("mode must be 0")
    43  	}
    44  
    45  	_, pkg, err := readImportFile(path, typecheck.Target, m.ctxt, m.packages)
    46  	return pkg, err
    47  }
    48  
    49  func isDriveLetter(b byte) bool {
    50  	return 'a' <= b && b <= 'z' || 'A' <= b && b <= 'Z'
    51  }
    52  
    53  // is this path a local name? begins with ./ or ../ or /
    54  func islocalname(name string) bool {
    55  	return strings.HasPrefix(name, "/") ||
    56  		runtime.GOOS == "windows" && len(name) >= 3 && isDriveLetter(name[0]) && name[1] == ':' && name[2] == '/' ||
    57  		strings.HasPrefix(name, "./") || name == "." ||
    58  		strings.HasPrefix(name, "../") || name == ".."
    59  }
    60  
    61  func openPackage(path string) (*os.File, error) {
    62  	if islocalname(path) {
    63  		if base.Flag.NoLocalImports {
    64  			return nil, errors.New("local imports disallowed")
    65  		}
    66  
    67  		if base.Flag.Cfg.PackageFile != nil {
    68  			return os.Open(base.Flag.Cfg.PackageFile[path])
    69  		}
    70  
    71  		// try .a before .o.  important for building libraries:
    72  		// if there is an array.o in the array.a library,
    73  		// want to find all of array.a, not just array.o.
    74  		if file, err := os.Open(fmt.Sprintf("%s.a", path)); err == nil {
    75  			return file, nil
    76  		}
    77  		if file, err := os.Open(fmt.Sprintf("%s.o", path)); err == nil {
    78  			return file, nil
    79  		}
    80  		return nil, errors.New("file not found")
    81  	}
    82  
    83  	// local imports should be canonicalized already.
    84  	// don't want to see "encoding/../encoding/base64"
    85  	// as different from "encoding/base64".
    86  	if q := pathpkg.Clean(path); q != path {
    87  		return nil, fmt.Errorf("non-canonical import path %q (should be %q)", path, q)
    88  	}
    89  
    90  	if base.Flag.Cfg.PackageFile != nil {
    91  		return os.Open(base.Flag.Cfg.PackageFile[path])
    92  	}
    93  
    94  	for _, dir := range base.Flag.Cfg.ImportDirs {
    95  		if file, err := os.Open(fmt.Sprintf("%s/%s.a", dir, path)); err == nil {
    96  			return file, nil
    97  		}
    98  		if file, err := os.Open(fmt.Sprintf("%s/%s.o", dir, path)); err == nil {
    99  			return file, nil
   100  		}
   101  	}
   102  
   103  	if buildcfg.GOROOT != "" {
   104  		suffix := ""
   105  		if base.Flag.InstallSuffix != "" {
   106  			suffix = "_" + base.Flag.InstallSuffix
   107  		} else if base.Flag.Race {
   108  			suffix = "_race"
   109  		} else if base.Flag.MSan {
   110  			suffix = "_msan"
   111  		} else if base.Flag.ASan {
   112  			suffix = "_asan"
   113  		}
   114  
   115  		if file, err := os.Open(fmt.Sprintf("%s/pkg/%s_%s%s/%s.a", buildcfg.GOROOT, buildcfg.GOOS, buildcfg.GOARCH, suffix, path)); err == nil {
   116  			return file, nil
   117  		}
   118  		if file, err := os.Open(fmt.Sprintf("%s/pkg/%s_%s%s/%s.o", buildcfg.GOROOT, buildcfg.GOOS, buildcfg.GOARCH, suffix, path)); err == nil {
   119  			return file, nil
   120  		}
   121  	}
   122  	return nil, errors.New("file not found")
   123  }
   124  
   125  // resolveImportPath resolves an import path as it appears in a Go
   126  // source file to the package's full path.
   127  func resolveImportPath(path string) (string, error) {
   128  	// The package name main is no longer reserved,
   129  	// but we reserve the import path "main" to identify
   130  	// the main package, just as we reserve the import
   131  	// path "math" to identify the standard math package.
   132  	if path == "main" {
   133  		return "", errors.New("cannot import \"main\"")
   134  	}
   135  
   136  	if base.Ctxt.Pkgpath == "" {
   137  		panic("missing pkgpath")
   138  	}
   139  	if path == base.Ctxt.Pkgpath {
   140  		return "", fmt.Errorf("import %q while compiling that package (import cycle)", path)
   141  	}
   142  
   143  	if mapped, ok := base.Flag.Cfg.ImportMap[path]; ok {
   144  		path = mapped
   145  	}
   146  
   147  	if islocalname(path) {
   148  		if path[0] == '/' {
   149  			return "", errors.New("import path cannot be absolute path")
   150  		}
   151  
   152  		prefix := base.Flag.D
   153  		if prefix == "" {
   154  			// Questionable, but when -D isn't specified, historically we
   155  			// resolve local import paths relative to the directory the
   156  			// compiler's current directory, not the respective source
   157  			// file's directory.
   158  			prefix = base.Ctxt.Pathname
   159  		}
   160  		path = pathpkg.Join(prefix, path)
   161  
   162  		if err := checkImportPath(path, true); err != nil {
   163  			return "", err
   164  		}
   165  	}
   166  
   167  	return path, nil
   168  }
   169  
   170  // readImportFile reads the import file for the given package path and
   171  // returns its types.Pkg representation. If packages is non-nil, the
   172  // types2.Package representation is also returned.
   173  func readImportFile(path string, target *ir.Package, env *types2.Context, packages map[string]*types2.Package) (pkg1 *types.Pkg, pkg2 *types2.Package, err error) {
   174  	path, err = resolveImportPath(path)
   175  	if err != nil {
   176  		return
   177  	}
   178  
   179  	if path == "unsafe" {
   180  		pkg1, pkg2 = types.UnsafePkg, types2.Unsafe
   181  
   182  		// TODO(mdempsky): Investigate if this actually matters. Why would
   183  		// the linker or runtime care whether a package imported unsafe?
   184  		if !pkg1.Direct {
   185  			pkg1.Direct = true
   186  			target.Imports = append(target.Imports, pkg1)
   187  		}
   188  
   189  		return
   190  	}
   191  
   192  	pkg1 = types.NewPkg(path, "")
   193  	if packages != nil {
   194  		pkg2 = packages[path]
   195  		assert(pkg1.Direct == (pkg2 != nil && pkg2.Complete()))
   196  	}
   197  
   198  	if pkg1.Direct {
   199  		return
   200  	}
   201  	pkg1.Direct = true
   202  	target.Imports = append(target.Imports, pkg1)
   203  
   204  	f, err := openPackage(path)
   205  	if err != nil {
   206  		return
   207  	}
   208  	defer f.Close()
   209  
   210  	data, err := readExportData(f)
   211  	if err != nil {
   212  		return
   213  	}
   214  
   215  	if base.Debug.Export != 0 {
   216  		fmt.Printf("importing %s (%s)\n", path, f.Name())
   217  	}
   218  
   219  	pr := pkgbits.NewPkgDecoder(pkg1.Path, data)
   220  
   221  	// Read package descriptors for both types2 and compiler backend.
   222  	readPackage(newPkgReader(pr), pkg1, false)
   223  	pkg2 = importer.ReadPackage(env, packages, pr)
   224  
   225  	err = addFingerprint(path, data)
   226  	return
   227  }
   228  
   229  // readExportData returns the contents of GC-created unified export data.
   230  func readExportData(f *os.File) (data string, err error) {
   231  	r := bio.NewReader(f)
   232  
   233  	sz, err := exportdata.FindPackageDefinition(r.Reader)
   234  	if err != nil {
   235  		return
   236  	}
   237  	end := r.Offset() + int64(sz)
   238  
   239  	abihdr, _, err := exportdata.ReadObjectHeaders(r.Reader)
   240  	if err != nil {
   241  		return
   242  	}
   243  
   244  	if expect := objabi.HeaderString(); abihdr != expect {
   245  		err = fmt.Errorf("object is [%s] expected [%s]", abihdr, expect)
   246  		return
   247  	}
   248  
   249  	_, err = exportdata.ReadExportDataHeader(r.Reader)
   250  	if err != nil {
   251  		return
   252  	}
   253  
   254  	pos := r.Offset()
   255  
   256  	// Map export data section (+ end-of-section marker) into memory
   257  	// as a single large string. This reduces heap fragmentation and
   258  	// allows returning individual substrings very efficiently.
   259  	var mapped string
   260  	mapped, err = base.MapFile(r.File(), pos, end-pos)
   261  	if err != nil {
   262  		return
   263  	}
   264  
   265  	// check for end-of-section marker "\n$$\n" and remove it
   266  	const marker = "\n$$\n"
   267  
   268  	var ok bool
   269  	data, ok = strings.CutSuffix(mapped, marker)
   270  	if !ok {
   271  		cutoff := data // include last 10 bytes in error message
   272  		if len(cutoff) >= 10 {
   273  			cutoff = cutoff[len(cutoff)-10:]
   274  		}
   275  		err = fmt.Errorf("expected $$ marker, but found %q (recompile package)", cutoff)
   276  		return
   277  	}
   278  
   279  	return
   280  }
   281  
   282  // addFingerprint reads the linker fingerprint included at the end of
   283  // the exportdata.
   284  func addFingerprint(path string, data string) error {
   285  	var fingerprint goobj.FingerprintType
   286  
   287  	pos := len(data) - len(fingerprint)
   288  	if pos < 0 {
   289  		return fmt.Errorf("missing linker fingerprint in exportdata, but found %q", data)
   290  	}
   291  	buf := []byte(data[pos:])
   292  
   293  	copy(fingerprint[:], buf)
   294  	base.Ctxt.AddImport(path, fingerprint)
   295  
   296  	return nil
   297  }
   298  
   299  func checkImportPath(path string, allowSpace bool) error {
   300  	if path == "" {
   301  		return errors.New("import path is empty")
   302  	}
   303  
   304  	if strings.Contains(path, "\x00") {
   305  		return errors.New("import path contains NUL")
   306  	}
   307  
   308  	for ri := range base.ReservedImports {
   309  		if path == ri {
   310  			return fmt.Errorf("import path %q is reserved and cannot be used", path)
   311  		}
   312  	}
   313  
   314  	for _, r := range path {
   315  		switch {
   316  		case r == utf8.RuneError:
   317  			return fmt.Errorf("import path contains invalid UTF-8 sequence: %q", path)
   318  		case r < 0x20 || r == 0x7f:
   319  			return fmt.Errorf("import path contains control character: %q", path)
   320  		case r == '\\':
   321  			return fmt.Errorf("import path contains backslash; use slash: %q", path)
   322  		case !allowSpace && unicode.IsSpace(r):
   323  			return fmt.Errorf("import path contains space character: %q", path)
   324  		case strings.ContainsRune("!\"#$%&'()*,:;<=>?[]^`{|}", r):
   325  			return fmt.Errorf("import path contains invalid character '%c': %q", r, path)
   326  		}
   327  	}
   328  
   329  	return nil
   330  }
   331  

View as plain text