github.com/riscv/riscv-go@v0.0.0-20200123204226-124ebd6fcc8e/src/go/build/deps_test.go (about)

     1  // Copyright 2012 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  // This file exercises the import parser but also checks that
     6  // some low-level packages do not have new dependencies added.
     7  
     8  package build
     9  
    10  import (
    11  	"bytes"
    12  	"fmt"
    13  	"io/ioutil"
    14  	"os"
    15  	"path/filepath"
    16  	"runtime"
    17  	"sort"
    18  	"strconv"
    19  	"strings"
    20  	"testing"
    21  )
    22  
    23  // pkgDeps defines the expected dependencies between packages in
    24  // the Go source tree. It is a statement of policy.
    25  // Changes should not be made to this map without prior discussion.
    26  //
    27  // The map contains two kinds of entries:
    28  // 1) Lower-case keys are standard import paths and list the
    29  // allowed imports in that package.
    30  // 2) Upper-case keys define aliases for package sets, which can then
    31  // be used as dependencies by other rules.
    32  //
    33  // DO NOT CHANGE THIS DATA TO FIX BUILDS.
    34  //
    35  var pkgDeps = map[string][]string{
    36  	// L0 is the lowest level, core, nearly unavoidable packages.
    37  	"errors":                  {},
    38  	"io":                      {"errors", "sync"},
    39  	"runtime":                 {"unsafe", "runtime/internal/atomic", "runtime/internal/sys"},
    40  	"runtime/internal/sys":    {},
    41  	"runtime/internal/atomic": {"unsafe", "runtime/internal/sys"},
    42  	"internal/race":           {"runtime", "unsafe"},
    43  	"sync":                    {"internal/race", "runtime", "sync/atomic", "unsafe"},
    44  	"sync/atomic":             {"unsafe"},
    45  	"unsafe":                  {},
    46  
    47  	"L0": {
    48  		"errors",
    49  		"io",
    50  		"runtime",
    51  		"runtime/internal/atomic",
    52  		"sync",
    53  		"sync/atomic",
    54  		"unsafe",
    55  	},
    56  
    57  	// L1 adds simple functions and strings processing,
    58  	// but not Unicode tables.
    59  	"math":          {"unsafe"},
    60  	"math/cmplx":    {"math"},
    61  	"math/rand":     {"L0", "math"},
    62  	"strconv":       {"L0", "unicode/utf8", "math"},
    63  	"unicode/utf16": {},
    64  	"unicode/utf8":  {},
    65  
    66  	"L1": {
    67  		"L0",
    68  		"math",
    69  		"math/cmplx",
    70  		"math/rand",
    71  		"sort",
    72  		"strconv",
    73  		"unicode/utf16",
    74  		"unicode/utf8",
    75  	},
    76  
    77  	// L2 adds Unicode and strings processing.
    78  	"bufio":   {"L0", "unicode/utf8", "bytes"},
    79  	"bytes":   {"L0", "unicode", "unicode/utf8"},
    80  	"path":    {"L0", "unicode/utf8", "strings"},
    81  	"strings": {"L0", "unicode", "unicode/utf8"},
    82  	"unicode": {},
    83  
    84  	"L2": {
    85  		"L1",
    86  		"bufio",
    87  		"bytes",
    88  		"path",
    89  		"strings",
    90  		"unicode",
    91  	},
    92  
    93  	// L3 adds reflection and some basic utility packages
    94  	// and interface definitions, but nothing that makes
    95  	// system calls.
    96  	"crypto":              {"L2", "hash"}, // interfaces
    97  	"crypto/cipher":       {"L2", "crypto/subtle"},
    98  	"crypto/subtle":       {},
    99  	"encoding/base32":     {"L2"},
   100  	"encoding/base64":     {"L2"},
   101  	"encoding/binary":     {"L2", "reflect"},
   102  	"hash":                {"L2"}, // interfaces
   103  	"hash/adler32":        {"L2", "hash"},
   104  	"hash/crc32":          {"L2", "hash"},
   105  	"hash/crc64":          {"L2", "hash"},
   106  	"hash/fnv":            {"L2", "hash"},
   107  	"image":               {"L2", "image/color"}, // interfaces
   108  	"image/color":         {"L2"},                // interfaces
   109  	"image/color/palette": {"L2", "image/color"},
   110  	"reflect":             {"L2"},
   111  	"sort":                {"reflect"},
   112  
   113  	"L3": {
   114  		"L2",
   115  		"crypto",
   116  		"crypto/cipher",
   117  		"crypto/internal/cipherhw",
   118  		"crypto/subtle",
   119  		"encoding/base32",
   120  		"encoding/base64",
   121  		"encoding/binary",
   122  		"hash",
   123  		"hash/adler32",
   124  		"hash/crc32",
   125  		"hash/crc64",
   126  		"hash/fnv",
   127  		"image",
   128  		"image/color",
   129  		"image/color/palette",
   130  		"reflect",
   131  	},
   132  
   133  	// End of linear dependency definitions.
   134  
   135  	// Operating system access.
   136  	"syscall":                           {"L0", "internal/race", "internal/syscall/windows/sysdll", "unicode/utf16"},
   137  	"internal/syscall/unix":             {"L0", "syscall"},
   138  	"internal/syscall/windows":          {"L0", "syscall", "internal/syscall/windows/sysdll"},
   139  	"internal/syscall/windows/registry": {"L0", "syscall", "internal/syscall/windows/sysdll", "unicode/utf16"},
   140  	"time": {
   141  		// "L0" without the "io" package:
   142  		"errors",
   143  		"runtime",
   144  		"runtime/internal/atomic",
   145  		"sync",
   146  		"sync/atomic",
   147  		"unsafe",
   148  		// Other time dependencies:
   149  		"internal/syscall/windows/registry",
   150  		"syscall",
   151  	},
   152  
   153  	"os":            {"L1", "os", "syscall", "time", "internal/syscall/windows"},
   154  	"path/filepath": {"L2", "os", "syscall"},
   155  	"io/ioutil":     {"L2", "os", "path/filepath", "time"},
   156  	"os/exec":       {"L2", "os", "context", "path/filepath", "syscall"},
   157  	"os/signal":     {"L2", "os", "syscall"},
   158  
   159  	// OS enables basic operating system functionality,
   160  	// but not direct use of package syscall, nor os/signal.
   161  	"OS": {
   162  		"io/ioutil",
   163  		"os",
   164  		"os/exec",
   165  		"path/filepath",
   166  		"time",
   167  	},
   168  
   169  	// Formatted I/O: few dependencies (L1) but we must add reflect.
   170  	"fmt": {"L1", "os", "reflect"},
   171  	"log": {"L1", "os", "fmt", "time"},
   172  
   173  	// Packages used by testing must be low-level (L2+fmt).
   174  	"regexp":                            {"L2", "regexp/syntax"},
   175  	"regexp/syntax":                     {"L2"},
   176  	"runtime/debug":                     {"L2", "fmt", "io/ioutil", "os", "time"},
   177  	"runtime/pprof/internal/protopprof": {"L2", "fmt", "internal/pprof/profile", "os", "time"},
   178  	"runtime/pprof":                     {"L2", "fmt", "internal/pprof/profile", "os", "runtime/pprof/internal/protopprof", "text/tabwriter", "time"},
   179  	"runtime/trace":                     {"L0"},
   180  	"text/tabwriter":                    {"L2"},
   181  
   182  	"testing":          {"L2", "flag", "fmt", "internal/race", "os", "runtime/debug", "runtime/pprof", "runtime/trace", "time"},
   183  	"testing/iotest":   {"L2", "log"},
   184  	"testing/quick":    {"L2", "flag", "fmt", "reflect"},
   185  	"internal/testenv": {"L2", "OS", "flag", "testing", "syscall"},
   186  
   187  	// L4 is defined as L3+fmt+log+time, because in general once
   188  	// you're using L3 packages, use of fmt, log, or time is not a big deal.
   189  	"L4": {
   190  		"L3",
   191  		"fmt",
   192  		"log",
   193  		"time",
   194  	},
   195  
   196  	// Go parser.
   197  	"go/ast":     {"L4", "OS", "go/scanner", "go/token"},
   198  	"go/doc":     {"L4", "go/ast", "go/token", "regexp", "text/template"},
   199  	"go/parser":  {"L4", "OS", "go/ast", "go/scanner", "go/token"},
   200  	"go/printer": {"L4", "OS", "go/ast", "go/scanner", "go/token", "text/tabwriter"},
   201  	"go/scanner": {"L4", "OS", "go/token"},
   202  	"go/token":   {"L4"},
   203  
   204  	"GOPARSER": {
   205  		"go/ast",
   206  		"go/doc",
   207  		"go/parser",
   208  		"go/printer",
   209  		"go/scanner",
   210  		"go/token",
   211  	},
   212  
   213  	"go/format":       {"L4", "GOPARSER", "internal/format"},
   214  	"internal/format": {"L4", "GOPARSER"},
   215  
   216  	// Go type checking.
   217  	"go/constant":               {"L4", "go/token", "math/big"},
   218  	"go/importer":               {"L4", "go/internal/gcimporter", "go/internal/gccgoimporter", "go/types"},
   219  	"go/internal/gcimporter":    {"L4", "OS", "go/build", "go/constant", "go/token", "go/types", "text/scanner"},
   220  	"go/internal/gccgoimporter": {"L4", "OS", "debug/elf", "go/constant", "go/token", "go/types", "text/scanner"},
   221  	"go/types":                  {"L4", "GOPARSER", "container/heap", "go/constant"},
   222  
   223  	// One of a kind.
   224  	"archive/tar":               {"L4", "OS", "syscall"},
   225  	"archive/zip":               {"L4", "OS", "compress/flate"},
   226  	"container/heap":            {"sort"},
   227  	"compress/bzip2":            {"L4"},
   228  	"compress/flate":            {"L4"},
   229  	"compress/gzip":             {"L4", "compress/flate"},
   230  	"compress/lzw":              {"L4"},
   231  	"compress/zlib":             {"L4", "compress/flate"},
   232  	"context":                   {"errors", "fmt", "reflect", "sync", "time"},
   233  	"database/sql":              {"L4", "container/list", "context", "database/sql/driver", "database/sql/internal"},
   234  	"database/sql/driver":       {"L4", "context", "time", "database/sql/internal"},
   235  	"debug/dwarf":               {"L4"},
   236  	"debug/elf":                 {"L4", "OS", "debug/dwarf", "compress/zlib"},
   237  	"debug/gosym":               {"L4"},
   238  	"debug/macho":               {"L4", "OS", "debug/dwarf"},
   239  	"debug/pe":                  {"L4", "OS", "debug/dwarf"},
   240  	"debug/plan9obj":            {"L4", "OS"},
   241  	"encoding":                  {"L4"},
   242  	"encoding/ascii85":          {"L4"},
   243  	"encoding/asn1":             {"L4", "math/big"},
   244  	"encoding/csv":              {"L4"},
   245  	"encoding/gob":              {"L4", "OS", "encoding"},
   246  	"encoding/hex":              {"L4"},
   247  	"encoding/json":             {"L4", "encoding"},
   248  	"encoding/pem":              {"L4"},
   249  	"encoding/xml":              {"L4", "encoding"},
   250  	"flag":                      {"L4", "OS"},
   251  	"go/build":                  {"L4", "OS", "GOPARSER"},
   252  	"html":                      {"L4"},
   253  	"image/draw":                {"L4", "image/internal/imageutil"},
   254  	"image/gif":                 {"L4", "compress/lzw", "image/color/palette", "image/draw"},
   255  	"image/internal/imageutil":  {"L4"},
   256  	"image/jpeg":                {"L4", "image/internal/imageutil"},
   257  	"image/png":                 {"L4", "compress/zlib"},
   258  	"index/suffixarray":         {"L4", "regexp"},
   259  	"internal/singleflight":     {"sync"},
   260  	"internal/trace":            {"L4", "OS"},
   261  	"internal/pprof/profile":    {"L4", "OS", "compress/gzip", "regexp"},
   262  	"math/big":                  {"L4"},
   263  	"mime":                      {"L4", "OS", "syscall", "internal/syscall/windows/registry"},
   264  	"mime/quotedprintable":      {"L4"},
   265  	"net/internal/socktest":     {"L4", "OS", "syscall"},
   266  	"net/url":                   {"L4"},
   267  	"plugin":                    {"L0", "OS", "CGO"},
   268  	"testing/internal/testdeps": {"L4", "runtime/pprof", "regexp"},
   269  	"text/scanner":              {"L4", "OS"},
   270  	"text/template/parse":       {"L4"},
   271  
   272  	"html/template": {
   273  		"L4", "OS", "encoding/json", "html", "text/template",
   274  		"text/template/parse",
   275  	},
   276  	"text/template": {
   277  		"L4", "OS", "net/url", "text/template/parse",
   278  	},
   279  
   280  	// Cgo.
   281  	// If you add a dependency on CGO, you must add the package to
   282  	// cgoPackages in cmd/dist/test.go.
   283  	"runtime/cgo": {"L0", "C"},
   284  	"CGO":         {"C", "runtime/cgo"},
   285  
   286  	// Fake entry to satisfy the pseudo-import "C"
   287  	// that shows up in programs that use cgo.
   288  	"C": {},
   289  
   290  	// Race detector/MSan uses cgo.
   291  	"runtime/race": {"C"},
   292  	"runtime/msan": {"C"},
   293  
   294  	// Plan 9 alone needs io/ioutil and os.
   295  	"os/user": {"L4", "CGO", "io/ioutil", "os", "syscall"},
   296  
   297  	// Basic networking.
   298  	// Because net must be used by any package that wants to
   299  	// do networking portably, it must have a small dependency set: just L0+basic os.
   300  	"net": {
   301  		"L0", "CGO",
   302  		"context", "math/rand", "os", "sort", "syscall", "time",
   303  		"internal/nettrace",
   304  		"internal/syscall/windows", "internal/singleflight", "internal/race",
   305  		"golang_org/x/net/lif", "golang_org/x/net/route",
   306  	},
   307  
   308  	// NET enables use of basic network-related packages.
   309  	"NET": {
   310  		"net",
   311  		"mime",
   312  		"net/textproto",
   313  		"net/url",
   314  	},
   315  
   316  	// Uses of networking.
   317  	"log/syslog":    {"L4", "OS", "net"},
   318  	"net/mail":      {"L4", "NET", "OS", "mime"},
   319  	"net/textproto": {"L4", "OS", "net"},
   320  
   321  	// Core crypto.
   322  	"crypto/aes":    {"L3"},
   323  	"crypto/des":    {"L3"},
   324  	"crypto/hmac":   {"L3"},
   325  	"crypto/md5":    {"L3"},
   326  	"crypto/rc4":    {"L3"},
   327  	"crypto/sha1":   {"L3"},
   328  	"crypto/sha256": {"L3"},
   329  	"crypto/sha512": {"L3"},
   330  
   331  	"CRYPTO": {
   332  		"crypto/aes",
   333  		"crypto/des",
   334  		"crypto/hmac",
   335  		"crypto/md5",
   336  		"crypto/rc4",
   337  		"crypto/sha1",
   338  		"crypto/sha256",
   339  		"crypto/sha512",
   340  		"golang_org/x/crypto/chacha20poly1305",
   341  		"golang_org/x/crypto/curve25519",
   342  		"golang_org/x/crypto/poly1305",
   343  	},
   344  
   345  	// Random byte, number generation.
   346  	// This would be part of core crypto except that it imports
   347  	// math/big, which imports fmt.
   348  	"crypto/rand": {"L4", "CRYPTO", "OS", "math/big", "syscall", "internal/syscall/unix"},
   349  
   350  	// Mathematical crypto: dependencies on fmt (L4) and math/big.
   351  	// We could avoid some of the fmt, but math/big imports fmt anyway.
   352  	"crypto/dsa":      {"L4", "CRYPTO", "math/big"},
   353  	"crypto/ecdsa":    {"L4", "CRYPTO", "crypto/elliptic", "math/big", "encoding/asn1"},
   354  	"crypto/elliptic": {"L4", "CRYPTO", "math/big"},
   355  	"crypto/rsa":      {"L4", "CRYPTO", "crypto/rand", "math/big"},
   356  
   357  	"CRYPTO-MATH": {
   358  		"CRYPTO",
   359  		"crypto/dsa",
   360  		"crypto/ecdsa",
   361  		"crypto/elliptic",
   362  		"crypto/rand",
   363  		"crypto/rsa",
   364  		"encoding/asn1",
   365  		"math/big",
   366  	},
   367  
   368  	// SSL/TLS.
   369  	"crypto/tls": {
   370  		"L4", "CRYPTO-MATH", "OS",
   371  		"container/list", "crypto/x509", "encoding/pem", "net", "syscall",
   372  	},
   373  	"crypto/x509": {
   374  		"L4", "CRYPTO-MATH", "OS", "CGO",
   375  		"crypto/x509/pkix", "encoding/pem", "encoding/hex", "net", "syscall",
   376  	},
   377  	"crypto/x509/pkix": {"L4", "CRYPTO-MATH"},
   378  
   379  	// Simple net+crypto-aware packages.
   380  	"mime/multipart": {"L4", "OS", "mime", "crypto/rand", "net/textproto", "mime/quotedprintable"},
   381  	"net/smtp":       {"L4", "CRYPTO", "NET", "crypto/tls"},
   382  
   383  	// HTTP, kingpin of dependencies.
   384  	"net/http": {
   385  		"L4", "NET", "OS",
   386  		"compress/gzip",
   387  		"container/list",
   388  		"context",
   389  		"crypto/rand",
   390  		"crypto/tls",
   391  		"golang_org/x/net/http2/hpack",
   392  		"golang_org/x/net/idna",
   393  		"golang_org/x/net/lex/httplex",
   394  		"golang_org/x/text/unicode/norm",
   395  		"golang_org/x/text/width",
   396  		"internal/nettrace",
   397  		"mime/multipart",
   398  		"net/http/httptrace",
   399  		"net/http/internal",
   400  		"runtime/debug",
   401  	},
   402  	"net/http/internal":  {"L4"},
   403  	"net/http/httptrace": {"context", "crypto/tls", "internal/nettrace", "net", "reflect", "time"},
   404  
   405  	// HTTP-using packages.
   406  	"expvar":             {"L4", "OS", "encoding/json", "net/http"},
   407  	"net/http/cgi":       {"L4", "NET", "OS", "crypto/tls", "net/http", "regexp"},
   408  	"net/http/cookiejar": {"L4", "NET", "net/http"},
   409  	"net/http/fcgi":      {"L4", "NET", "OS", "net/http", "net/http/cgi"},
   410  	"net/http/httptest":  {"L4", "NET", "OS", "crypto/tls", "flag", "net/http", "net/http/internal"},
   411  	"net/http/httputil":  {"L4", "NET", "OS", "context", "net/http", "net/http/internal"},
   412  	"net/http/pprof":     {"L4", "OS", "html/template", "net/http", "runtime/pprof", "runtime/trace"},
   413  	"net/rpc":            {"L4", "NET", "encoding/gob", "html/template", "net/http"},
   414  	"net/rpc/jsonrpc":    {"L4", "NET", "encoding/json", "net/rpc"},
   415  }
   416  
   417  // isMacro reports whether p is a package dependency macro
   418  // (uppercase name).
   419  func isMacro(p string) bool {
   420  	return 'A' <= p[0] && p[0] <= 'Z'
   421  }
   422  
   423  func allowed(pkg string) map[string]bool {
   424  	m := map[string]bool{}
   425  	var allow func(string)
   426  	allow = func(p string) {
   427  		if m[p] {
   428  			return
   429  		}
   430  		m[p] = true // set even for macros, to avoid loop on cycle
   431  
   432  		// Upper-case names are macro-expanded.
   433  		if isMacro(p) {
   434  			for _, pp := range pkgDeps[p] {
   435  				allow(pp)
   436  			}
   437  		}
   438  	}
   439  	for _, pp := range pkgDeps[pkg] {
   440  		allow(pp)
   441  	}
   442  	return m
   443  }
   444  
   445  // listStdPkgs returns the same list of packages as "go list std".
   446  func listStdPkgs(goroot string) ([]string, error) {
   447  	// Based on cmd/go's matchPackages function.
   448  	var pkgs []string
   449  
   450  	src := filepath.Join(goroot, "src") + string(filepath.Separator)
   451  	walkFn := func(path string, fi os.FileInfo, err error) error {
   452  		if err != nil || !fi.IsDir() || path == src {
   453  			return nil
   454  		}
   455  
   456  		base := filepath.Base(path)
   457  		if strings.HasPrefix(base, ".") || strings.HasPrefix(base, "_") || base == "testdata" {
   458  			return filepath.SkipDir
   459  		}
   460  
   461  		name := filepath.ToSlash(path[len(src):])
   462  		if name == "builtin" || name == "cmd" || strings.Contains(name, "golang_org") {
   463  			return filepath.SkipDir
   464  		}
   465  
   466  		pkgs = append(pkgs, name)
   467  		return nil
   468  	}
   469  	if err := filepath.Walk(src, walkFn); err != nil {
   470  		return nil, err
   471  	}
   472  	return pkgs, nil
   473  }
   474  
   475  func TestDependencies(t *testing.T) {
   476  	iOS := runtime.GOOS == "darwin" && (runtime.GOARCH == "arm" || runtime.GOARCH == "arm64")
   477  	if runtime.GOOS == "nacl" || iOS {
   478  		// Tests run in a limited file system and we do not
   479  		// provide access to every source file.
   480  		t.Skipf("skipping on %s/%s, missing full GOROOT", runtime.GOOS, runtime.GOARCH)
   481  	}
   482  
   483  	ctxt := Default
   484  	all, err := listStdPkgs(ctxt.GOROOT)
   485  	if err != nil {
   486  		t.Fatal(err)
   487  	}
   488  	sort.Strings(all)
   489  
   490  	for _, pkg := range all {
   491  		imports, err := findImports(pkg)
   492  		if err != nil {
   493  			t.Error(err)
   494  			continue
   495  		}
   496  		ok := allowed(pkg)
   497  		var bad []string
   498  		for _, imp := range imports {
   499  			if !ok[imp] {
   500  				bad = append(bad, imp)
   501  			}
   502  		}
   503  		if bad != nil {
   504  			t.Errorf("unexpected dependency: %s imports %v", pkg, bad)
   505  		}
   506  	}
   507  }
   508  
   509  var buildIgnore = []byte("\n// +build ignore")
   510  
   511  func findImports(pkg string) ([]string, error) {
   512  	dir := filepath.Join(Default.GOROOT, "src", pkg)
   513  	files, err := ioutil.ReadDir(dir)
   514  	if err != nil {
   515  		return nil, err
   516  	}
   517  	var imports []string
   518  	var haveImport = map[string]bool{}
   519  	for _, file := range files {
   520  		name := file.Name()
   521  		if !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") {
   522  			continue
   523  		}
   524  		f, err := os.Open(filepath.Join(dir, name))
   525  		if err != nil {
   526  			return nil, err
   527  		}
   528  		var imp []string
   529  		data, err := readImports(f, false, &imp)
   530  		f.Close()
   531  		if err != nil {
   532  			return nil, fmt.Errorf("reading %v: %v", name, err)
   533  		}
   534  		if bytes.Contains(data, buildIgnore) {
   535  			continue
   536  		}
   537  		for _, quoted := range imp {
   538  			path, err := strconv.Unquote(quoted)
   539  			if err != nil {
   540  				continue
   541  			}
   542  			if !haveImport[path] {
   543  				haveImport[path] = true
   544  				imports = append(imports, path)
   545  			}
   546  		}
   547  	}
   548  	sort.Strings(imports)
   549  	return imports, nil
   550  }