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