]> Cypherpunks.ru repositories - gostls13.git/blob - src/go/build/deps_test.go
cmd/go: don't install most GOROOT .a files in pkg
[gostls13.git] / src / go / build / deps_test.go
1 // Copyright 2022 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         "go/token"
14         "internal/dag"
15         "internal/testenv"
16         "io/fs"
17         "os"
18         "path/filepath"
19         "runtime"
20         "sort"
21         "strings"
22         "testing"
23 )
24
25 // depsRules defines the expected dependencies between packages in
26 // the Go source tree. It is a statement of policy.
27 //
28 // DO NOT CHANGE THIS DATA TO FIX BUILDS.
29 // Existing packages should not have their constraints relaxed
30 // without prior discussion.
31 // Negative assertions should almost never be removed.
32 //
33 // "a < b" means package b can import package a.
34 //
35 // See `go doc internal/dag' for the full syntax.
36 //
37 // All-caps names are pseudo-names for specific points
38 // in the dependency lattice.
39 var depsRules = `
40         # No dependencies allowed for any of these packages.
41         NONE
42         < constraints, container/list, container/ring,
43           internal/buildinternal,
44           internal/cfg, internal/coverage, internal/coverage/rtcov,
45           internal/coverage/uleb128, internal/coverage/calloc,
46           internal/cpu, internal/goarch,
47           internal/goexperiment, internal/goos,
48           internal/goversion, internal/nettrace, internal/platform,
49           unicode/utf8, unicode/utf16, unicode,
50           unsafe;
51
52         # These packages depend only on internal/goarch and unsafe.
53         internal/goarch, unsafe
54         < internal/abi;
55
56         unsafe
57         < internal/godebug;
58
59         # RUNTIME is the core runtime group of packages, all of them very light-weight.
60         internal/abi, internal/cpu, internal/goarch,
61         internal/coverage/rtcov, internal/goexperiment,
62         internal/goos, internal/godebug, unsafe
63         < internal/bytealg
64         < internal/itoa
65         < internal/unsafeheader
66         < runtime/internal/sys
67         < runtime/internal/syscall
68         < runtime/internal/atomic
69         < runtime/internal/math
70         < runtime
71         < sync/atomic
72         < internal/race
73         < sync
74         < internal/reflectlite
75         < errors
76         < internal/oserror, math/bits
77         < RUNTIME;
78
79         RUNTIME
80         < sort
81         < container/heap;
82
83         RUNTIME
84         < io;
85
86         RUNTIME
87         < arena;
88
89         syscall !< io;
90         reflect !< sort;
91
92         RUNTIME, unicode/utf8
93         < path;
94
95         unicode !< path;
96
97         # SYSCALL is RUNTIME plus the packages necessary for basic system calls.
98         RUNTIME, unicode/utf8, unicode/utf16
99         < internal/syscall/windows/sysdll, syscall/js
100         < syscall
101         < internal/syscall/unix, internal/syscall/windows, internal/syscall/windows/registry
102         < internal/syscall/execenv
103         < SYSCALL;
104
105         # TIME is SYSCALL plus the core packages about time, including context.
106         SYSCALL
107         < time/tzdata
108         < time
109         < context
110         < TIME;
111
112         TIME, io, path, sort
113         < io/fs;
114
115         # MATH is RUNTIME plus the basic math packages.
116         RUNTIME
117         < math
118         < MATH;
119
120         unicode !< math;
121
122         MATH
123         < math/cmplx;
124
125         MATH
126         < math/rand;
127
128         MATH
129         < runtime/metrics;
130
131         MATH, unicode/utf8
132         < strconv;
133
134         unicode !< strconv;
135
136         # STR is basic string and buffer manipulation.
137         RUNTIME, io, unicode/utf8, unicode/utf16, unicode
138         < bytes, strings
139         < bufio;
140
141         bufio, path, strconv
142         < STR;
143
144         # OS is basic OS access, including helpers (path/filepath, os/exec, etc).
145         # OS includes string routines, but those must be layered above package os.
146         # OS does not include reflection.
147         io/fs
148         < internal/testlog
149         < internal/poll
150         < os
151         < os/signal;
152
153         io/fs
154         < embed;
155
156         unicode, fmt !< net, os, os/signal;
157
158         os/signal, STR
159         < path/filepath
160         < io/ioutil;
161
162         path/filepath, internal/godebug < os/exec;
163
164         io/ioutil, os/exec, os/signal
165         < OS;
166
167         reflect !< OS;
168
169         OS
170         < golang.org/x/sys/cpu;
171
172         # FMT is OS (which includes string routines) plus reflect and fmt.
173         # It does not include package log, which should be avoided in core packages.
174         arena, strconv, unicode
175         < reflect;
176
177         os, reflect
178         < internal/fmtsort
179         < fmt;
180
181         OS, fmt
182         < FMT;
183
184         log !< FMT;
185
186         # Misc packages needing only FMT.
187         FMT
188         < html,
189           internal/dag,
190           internal/goroot,
191           internal/types/errors,
192           mime/quotedprintable,
193           net/internal/socktest,
194           net/url,
195           runtime/trace,
196           text/scanner,
197           text/tabwriter;
198
199         io, reflect
200         < internal/saferio;
201
202         # encodings
203         # core ones do not use fmt.
204         io, strconv
205         < encoding;
206
207         encoding, reflect
208         < encoding/binary
209         < encoding/base32, encoding/base64;
210
211         FMT, encoding < flag;
212
213         fmt !< encoding/base32, encoding/base64;
214
215         FMT, encoding/base32, encoding/base64, internal/saferio
216         < encoding/ascii85, encoding/csv, encoding/gob, encoding/hex,
217           encoding/json, encoding/pem, encoding/xml, mime;
218
219         # hashes
220         io
221         < hash
222         < hash/adler32, hash/crc32, hash/crc64, hash/fnv, hash/maphash;
223
224         # math/big
225         FMT, encoding/binary, math/rand
226         < math/big;
227
228         # compression
229         FMT, encoding/binary, hash/adler32, hash/crc32
230         < compress/bzip2, compress/flate, compress/lzw
231         < archive/zip, compress/gzip, compress/zlib;
232
233         # templates
234         FMT
235         < text/template/parse;
236
237         net/url, text/template/parse
238         < text/template
239         < internal/lazytemplate;
240
241         encoding/json, html, text/template
242         < html/template;
243
244         # regexp
245         FMT
246         < regexp/syntax
247         < regexp
248         < internal/lazyregexp;
249
250         # suffix array
251         encoding/binary, regexp
252         < index/suffixarray;
253
254         # executable parsing
255         FMT, encoding/binary, compress/zlib, internal/saferio
256         < runtime/debug
257         < debug/dwarf
258         < debug/elf, debug/gosym, debug/macho, debug/pe, debug/plan9obj, internal/xcoff
259         < debug/buildinfo
260         < DEBUG;
261
262         # go parser and friends.
263         FMT
264         < go/token
265         < go/scanner
266         < go/ast
267         < go/internal/typeparams
268         < go/parser;
269
270         FMT
271         < go/build/constraint, go/doc/comment;
272
273         go/build/constraint, go/doc/comment, go/parser, text/tabwriter
274         < go/printer
275         < go/format;
276
277         go/doc/comment, go/parser, internal/lazyregexp, text/template
278         < go/doc;
279
280         math/big, go/token
281         < go/constant;
282
283         container/heap, go/constant, go/parser, internal/types/errors, regexp
284         < go/types;
285
286         FMT, internal/goexperiment
287         < internal/buildcfg;
288
289         go/build/constraint, go/doc, go/parser, internal/buildcfg, internal/goroot, internal/goversion, internal/buildinternal
290         < go/build;
291
292         # databases
293         FMT
294         < database/sql/internal
295         < database/sql/driver
296         < database/sql;
297
298         # images
299         FMT, compress/lzw, compress/zlib
300         < image/color
301         < image, image/color/palette
302         < image/internal/imageutil
303         < image/draw
304         < image/gif, image/jpeg, image/png;
305
306         # cgo, delayed as long as possible.
307         # If you add a dependency on CGO, you must add the package
308         # to cgoPackages in cmd/dist/test.go as well.
309         RUNTIME
310         < C
311         < runtime/cgo
312         < CGO
313         < runtime/msan, runtime/asan;
314
315         # runtime/race
316         NONE < runtime/race/internal/amd64v1;
317         NONE < runtime/race/internal/amd64v3;
318         CGO, runtime/race/internal/amd64v1, runtime/race/internal/amd64v3 < runtime/race;
319
320         # Bulk of the standard library must not use cgo.
321         # The prohibition stops at net and os/user.
322         C !< fmt, go/types, CRYPTO-MATH;
323
324         CGO, OS
325         < plugin;
326
327         CGO, FMT
328         < os/user
329         < archive/tar;
330
331         sync
332         < internal/singleflight;
333
334         os
335         < golang.org/x/net/dns/dnsmessage,
336           golang.org/x/net/lif,
337           golang.org/x/net/route;
338
339         os, runtime, strconv, sync, unsafe,
340         internal/godebug
341         < internal/intern;
342
343         internal/bytealg, internal/intern, internal/itoa, math/bits, sort, strconv
344         < net/netip;
345
346         # net is unavoidable when doing any networking,
347         # so large dependencies must be kept out.
348         # This is a long-looking list but most of these
349         # are small with few dependencies.
350         CGO,
351         golang.org/x/net/dns/dnsmessage,
352         golang.org/x/net/lif,
353         golang.org/x/net/route,
354         internal/godebug,
355         internal/nettrace,
356         internal/poll,
357         internal/singleflight,
358         internal/race,
359         net/netip,
360         os
361         < net;
362
363         fmt, unicode !< net;
364         math/rand !< net; # net uses runtime instead
365
366         # NET is net plus net-helper packages.
367         FMT, net
368         < net/textproto;
369
370         mime, net/textproto, net/url
371         < NET;
372
373         # logging - most packages should not import; http and up is allowed
374         FMT
375         < log;
376
377         log !< crypto/tls, database/sql, go/importer, testing;
378
379         FMT, log, net
380         < log/syslog;
381
382         NET, log
383         < net/mail;
384
385         NONE < crypto/internal/boring/sig, crypto/internal/boring/syso;
386         sync/atomic < crypto/internal/boring/bcache, crypto/internal/boring/fipstls;
387         crypto/internal/boring/sig, crypto/internal/boring/fipstls < crypto/tls/fipsonly;
388
389         # CRYPTO is core crypto algorithms - no cgo, fmt, net.
390         # Unfortunately, stuck with reflect via encoding/binary.
391         crypto/internal/boring/sig,
392         crypto/internal/boring/syso,
393         encoding/binary,
394         golang.org/x/sys/cpu,
395         hash, embed
396         < crypto
397         < crypto/subtle
398         < crypto/internal/alias
399         < crypto/internal/randutil
400         < crypto/internal/nistec/fiat
401         < crypto/internal/nistec
402         < crypto/internal/edwards25519/field
403         < crypto/internal/edwards25519, crypto/ecdh
404         < crypto/cipher;
405
406         crypto/cipher,
407         crypto/internal/boring/bcache
408         < crypto/internal/boring
409         < crypto/boring
410         < crypto/aes, crypto/des, crypto/hmac, crypto/md5, crypto/rc4,
411           crypto/sha1, crypto/sha256, crypto/sha512
412         < CRYPTO;
413
414         CGO, fmt, net !< CRYPTO;
415
416         # CRYPTO-MATH is core bignum-based crypto - no cgo, net; fmt now ok.
417         CRYPTO, FMT, math/big
418         < crypto/internal/boring/bbig
419         < crypto/rand
420         < crypto/ed25519
421         < encoding/asn1
422         < golang.org/x/crypto/cryptobyte/asn1
423         < golang.org/x/crypto/cryptobyte
424         < crypto/dsa, crypto/elliptic, crypto/rsa
425         < crypto/ecdsa
426         < CRYPTO-MATH;
427
428         CGO, net !< CRYPTO-MATH;
429
430         # TLS, Prince of Dependencies.
431         CRYPTO-MATH, NET, container/list, encoding/hex, encoding/pem
432         < golang.org/x/crypto/internal/alias
433         < golang.org/x/crypto/internal/subtle
434         < golang.org/x/crypto/chacha20
435         < golang.org/x/crypto/internal/poly1305
436         < golang.org/x/crypto/chacha20poly1305
437         < golang.org/x/crypto/hkdf
438         < crypto/x509/internal/macos
439         < crypto/x509/pkix;
440
441         crypto/internal/boring/fipstls, crypto/x509/pkix
442         < crypto/x509
443         < crypto/tls;
444
445         # crypto-aware packages
446
447         DEBUG, go/build, go/types, text/scanner, crypto/md5
448         < internal/pkgbits
449         < go/internal/gcimporter, go/internal/gccgoimporter, go/internal/srcimporter
450         < go/importer;
451
452         NET, crypto/rand, mime/quotedprintable
453         < mime/multipart;
454
455         crypto/tls
456         < net/smtp;
457
458         # HTTP, King of Dependencies.
459
460         FMT
461         < golang.org/x/net/http2/hpack
462         < net/http/internal, net/http/internal/ascii, net/http/internal/testcert;
463
464         FMT, NET, container/list, encoding/binary, log
465         < golang.org/x/text/transform
466         < golang.org/x/text/unicode/norm
467         < golang.org/x/text/unicode/bidi
468         < golang.org/x/text/secure/bidirule
469         < golang.org/x/net/idna
470         < golang.org/x/net/http/httpguts, golang.org/x/net/http/httpproxy;
471
472         NET, crypto/tls
473         < net/http/httptrace;
474
475         compress/gzip,
476         golang.org/x/net/http/httpguts,
477         golang.org/x/net/http/httpproxy,
478         golang.org/x/net/http2/hpack,
479         net/http/internal,
480         net/http/internal/ascii,
481         net/http/internal/testcert,
482         net/http/httptrace,
483         mime/multipart,
484         log
485         < net/http;
486
487         # HTTP-aware packages
488
489         encoding/json, net/http
490         < expvar;
491
492         net/http, net/http/internal/ascii
493         < net/http/cookiejar, net/http/httputil;
494
495         net/http, flag
496         < net/http/httptest;
497
498         net/http, regexp
499         < net/http/cgi
500         < net/http/fcgi;
501
502         # Profiling
503         FMT, compress/gzip, encoding/binary, text/tabwriter
504         < runtime/pprof;
505
506         OS, compress/gzip, regexp
507         < internal/profile;
508
509         html, internal/profile, net/http, runtime/pprof, runtime/trace
510         < net/http/pprof;
511
512         # RPC
513         encoding/gob, encoding/json, go/token, html/template, net/http
514         < net/rpc
515         < net/rpc/jsonrpc;
516
517         # System Information
518         internal/cpu, sync
519         < internal/sysinfo;
520
521         # Test-only
522         log
523         < testing/iotest
524         < testing/fstest;
525
526         FMT, flag, math/rand
527         < testing/quick;
528
529         FMT, DEBUG, flag, runtime/trace, internal/sysinfo, math/rand
530         < testing;
531
532         FMT, crypto/sha256, encoding/json, go/ast, go/parser, go/token,
533         internal/godebug, math/rand, encoding/hex, crypto/sha256
534         < internal/fuzz;
535
536         internal/fuzz, internal/testlog, runtime/pprof, regexp
537         < testing/internal/testdeps;
538
539         OS, flag, testing, internal/cfg, internal/platform, internal/goroot
540         < internal/testenv;
541
542         OS, encoding/base64
543         < internal/obscuretestdata;
544
545         CGO, OS, fmt
546         < os/signal/internal/pty;
547
548         NET, testing, math/rand
549         < golang.org/x/net/nettest;
550
551         syscall
552         < os/exec/internal/fdtest;
553
554         FMT, container/heap, math/rand
555         < internal/trace;
556
557         FMT
558         < internal/diff, internal/txtar;
559
560         FMT, crypto/md5, encoding/binary, regexp, sort, text/tabwriter, unsafe,
561         internal/coverage, internal/coverage/uleb128
562         < internal/coverage/cmerge,
563           internal/coverage/pods,
564           internal/coverage/slicereader,
565           internal/coverage/slicewriter;
566
567         internal/coverage/slicereader, internal/coverage/slicewriter
568         < internal/coverage/stringtab
569         < internal/coverage/decodecounter, internal/coverage/decodemeta,
570           internal/coverage/encodecounter, internal/coverage/encodemeta;
571
572         internal/coverage/cmerge
573         < internal/coverage/cformat;
574
575         runtime/debug,
576         internal/coverage/calloc,
577         internal/coverage/cformat,
578         internal/coverage/decodecounter, internal/coverage/decodemeta,
579         internal/coverage/encodecounter, internal/coverage/encodemeta,
580         internal/coverage/pods
581         < runtime/coverage;
582 `
583
584 // listStdPkgs returns the same list of packages as "go list std".
585 func listStdPkgs(goroot string) ([]string, error) {
586         // Based on cmd/go's matchPackages function.
587         var pkgs []string
588
589         src := filepath.Join(goroot, "src") + string(filepath.Separator)
590         walkFn := func(path string, d fs.DirEntry, err error) error {
591                 if err != nil || !d.IsDir() || path == src {
592                         return nil
593                 }
594
595                 base := filepath.Base(path)
596                 if strings.HasPrefix(base, ".") || strings.HasPrefix(base, "_") || base == "testdata" {
597                         return filepath.SkipDir
598                 }
599
600                 name := filepath.ToSlash(path[len(src):])
601                 if name == "builtin" || name == "cmd" {
602                         return filepath.SkipDir
603                 }
604
605                 pkgs = append(pkgs, strings.TrimPrefix(name, "vendor/"))
606                 return nil
607         }
608         if err := filepath.WalkDir(src, walkFn); err != nil {
609                 return nil, err
610         }
611         return pkgs, nil
612 }
613
614 func TestDependencies(t *testing.T) {
615         if !testenv.HasSrc() {
616                 // Tests run in a limited file system and we do not
617                 // provide access to every source file.
618                 t.Skipf("skipping on %s/%s, missing full GOROOT", runtime.GOOS, runtime.GOARCH)
619         }
620
621         ctxt := Default
622         all, err := listStdPkgs(ctxt.GOROOT)
623         if err != nil {
624                 t.Fatal(err)
625         }
626         sort.Strings(all)
627
628         sawImport := map[string]map[string]bool{} // from package => to package => true
629         policy := depsPolicy(t)
630
631         for _, pkg := range all {
632                 imports, err := findImports(pkg)
633                 if err != nil {
634                         t.Error(err)
635                         continue
636                 }
637                 if sawImport[pkg] == nil {
638                         sawImport[pkg] = map[string]bool{}
639                 }
640                 var bad []string
641                 for _, imp := range imports {
642                         sawImport[pkg][imp] = true
643                         if !policy.HasEdge(pkg, imp) {
644                                 bad = append(bad, imp)
645                         }
646                 }
647                 if bad != nil {
648                         t.Errorf("unexpected dependency: %s imports %v", pkg, bad)
649                 }
650         }
651 }
652
653 var buildIgnore = []byte("\n//go:build ignore")
654
655 func findImports(pkg string) ([]string, error) {
656         vpkg := pkg
657         if strings.HasPrefix(pkg, "golang.org") {
658                 vpkg = "vendor/" + pkg
659         }
660         dir := filepath.Join(Default.GOROOT, "src", vpkg)
661         files, err := os.ReadDir(dir)
662         if err != nil {
663                 return nil, err
664         }
665         var imports []string
666         var haveImport = map[string]bool{}
667         if pkg == "crypto/internal/boring" {
668                 haveImport["C"] = true // kludge: prevent C from appearing in crypto/internal/boring imports
669         }
670         fset := token.NewFileSet()
671         for _, file := range files {
672                 name := file.Name()
673                 if name == "slice_go14.go" || name == "slice_go18.go" {
674                         // These files are for compiler bootstrap with older versions of Go and not built in the standard build.
675                         continue
676                 }
677                 if !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") {
678                         continue
679                 }
680                 info := fileInfo{
681                         name: filepath.Join(dir, name),
682                         fset: fset,
683                 }
684                 f, err := os.Open(info.name)
685                 if err != nil {
686                         return nil, err
687                 }
688                 err = readGoInfo(f, &info)
689                 f.Close()
690                 if err != nil {
691                         return nil, fmt.Errorf("reading %v: %v", name, err)
692                 }
693                 if info.parsed.Name.Name == "main" {
694                         continue
695                 }
696                 if bytes.Contains(info.header, buildIgnore) {
697                         continue
698                 }
699                 for _, imp := range info.imports {
700                         path := imp.path
701                         if !haveImport[path] {
702                                 haveImport[path] = true
703                                 imports = append(imports, path)
704                         }
705                 }
706         }
707         sort.Strings(imports)
708         return imports, nil
709 }
710
711 // depsPolicy returns a map m such that m[p][d] == true when p can import d.
712 func depsPolicy(t *testing.T) *dag.Graph {
713         g, err := dag.Parse(depsRules)
714         if err != nil {
715                 t.Fatal(err)
716         }
717         return g
718 }
719
720 // TestStdlibLowercase tests that all standard library package names are
721 // lowercase. See Issue 40065.
722 func TestStdlibLowercase(t *testing.T) {
723         if !testenv.HasSrc() {
724                 t.Skipf("skipping on %s/%s, missing full GOROOT", runtime.GOOS, runtime.GOARCH)
725         }
726
727         ctxt := Default
728         all, err := listStdPkgs(ctxt.GOROOT)
729         if err != nil {
730                 t.Fatal(err)
731         }
732
733         for _, pkgname := range all {
734                 if strings.ToLower(pkgname) != pkgname {
735                         t.Errorf("package %q should not use upper-case path", pkgname)
736                 }
737         }
738 }
739
740 // TestFindImports tests that findImports works.  See #43249.
741 func TestFindImports(t *testing.T) {
742         imports, err := findImports("go/build")
743         if err != nil {
744                 t.Fatal(err)
745         }
746         t.Logf("go/build imports %q", imports)
747         want := []string{"bytes", "os", "path/filepath", "strings"}
748 wantLoop:
749         for _, w := range want {
750                 for _, imp := range imports {
751                         if imp == w {
752                                 continue wantLoop
753                         }
754                 }
755                 t.Errorf("expected to find %q in import list", w)
756         }
757 }