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