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