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/ir"
    22  	"cmd/compile/internal/testimporter"
    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  		if !(pkg1.Direct == (pkg2 != nil && pkg2.Complete())) {
   196  
   197  			base.Fatalf("pkg1.Direct == (pkg2 != nil && pkg2.Complete()), path=%s\npackages=%v", path, packages)
   198  		}
   199  	}
   200  
   201  	if pkg1.Direct {
   202  		return
   203  	}
   204  	pkg1.Direct = true
   205  	target.Imports = append(target.Imports, pkg1)
   206  
   207  	f, err := openPackage(path)
   208  	if err != nil {
   209  		return
   210  	}
   211  	defer f.Close()
   212  
   213  	data, err := readExportData(f)
   214  	if err != nil {
   215  		return
   216  	}
   217  
   218  	if base.Debug.Export != 0 {
   219  		fmt.Printf("importing %s (%s)\n", path, f.Name())
   220  	}
   221  
   222  	pr := pkgbits.NewPkgDecoder(pkg1.Path, data)
   223  
   224  	// Read package descriptors for both types2 and compiler backend.
   225  	readPackage(newPkgReader(pr), pkg1, false)
   226  	pkg2 = testimporter.ReadPackage(env, packages, pr)
   227  
   228  	err = addFingerprint(path, data)
   229  	return
   230  }
   231  
   232  // readExportData returns the contents of GC-created unified export data.
   233  func readExportData(f *os.File) (data string, err error) {
   234  	r := bio.NewReader(f)
   235  
   236  	sz, err := exportdata.FindPackageDefinition(r.Reader)
   237  	if err != nil {
   238  		return
   239  	}
   240  	end := r.Offset() + int64(sz)
   241  
   242  	abihdr, _, err := exportdata.ReadObjectHeaders(r.Reader)
   243  	if err != nil {
   244  		return
   245  	}
   246  
   247  	if expect := objabi.HeaderString(); abihdr != expect {
   248  		err = fmt.Errorf("object is [%s] expected [%s]", abihdr, expect)
   249  		return
   250  	}
   251  
   252  	_, err = exportdata.ReadExportDataHeader(r.Reader, true)
   253  	if err != nil {
   254  		return
   255  	}
   256  
   257  	pos := r.Offset()
   258  
   259  	// Map export data section (+ end-of-section marker) into memory
   260  	// as a single large string. This reduces heap fragmentation and
   261  	// allows returning individual substrings very efficiently.
   262  	var mapped string
   263  	mapped, err = base.MapFile(r.File(), pos, end-pos)
   264  	if err != nil {
   265  		return
   266  	}
   267  
   268  	// check for end-of-section marker "\n$$\n" and remove it
   269  	const marker = "\n$$\n"
   270  
   271  	var ok bool
   272  	data, ok = strings.CutSuffix(mapped, marker)
   273  	if !ok {
   274  		cutoff := data // include last 10 bytes in error message
   275  		if len(cutoff) >= 10 {
   276  			cutoff = cutoff[len(cutoff)-10:]
   277  		}
   278  		err = fmt.Errorf("expected $$ marker, but found %q (recompile package)", cutoff)
   279  		return
   280  	}
   281  
   282  	return
   283  }
   284  
   285  // addFingerprint reads the linker fingerprint included at the end of
   286  // the exportdata.
   287  func addFingerprint(path string, data string) error {
   288  	var fingerprint goobj.FingerprintType
   289  
   290  	pos := len(data) - len(fingerprint)
   291  	if pos < 0 {
   292  		return fmt.Errorf("missing linker fingerprint in exportdata, but found %q", data)
   293  	}
   294  	buf := []byte(data[pos:])
   295  
   296  	copy(fingerprint[:], buf)
   297  	base.Ctxt.AddImport(path, fingerprint)
   298  
   299  	return nil
   300  }
   301  
   302  func checkImportPath(path string, allowSpace bool) error {
   303  	if path == "" {
   304  		return errors.New("import path is empty")
   305  	}
   306  
   307  	if strings.Contains(path, "\x00") {
   308  		return errors.New("import path contains NUL")
   309  	}
   310  
   311  	for ri := range base.ReservedImports {
   312  		if path == ri {
   313  			return fmt.Errorf("import path %q is reserved and cannot be used", path)
   314  		}
   315  	}
   316  
   317  	for _, r := range path {
   318  		switch {
   319  		case r == utf8.RuneError:
   320  			return fmt.Errorf("import path contains invalid UTF-8 sequence: %q", path)
   321  		case r < 0x20 || r == 0x7f:
   322  			return fmt.Errorf("import path contains control character: %q", path)
   323  		case r == '\\':
   324  			return fmt.Errorf("import path contains backslash; use slash: %q", path)
   325  		case !allowSpace && unicode.IsSpace(r):
   326  			return fmt.Errorf("import path contains space character: %q", path)
   327  		case strings.ContainsRune("!\"#$%&'()*,:;<=>?[]^`{|}", r):
   328  			return fmt.Errorf("import path contains invalid character '%c': %q", r, path)
   329  		}
   330  	}
   331  
   332  	return nil
   333  }
   334  

View as plain text