Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- go/src/cmd/addr2line/addr2line_test.go +119 -0
- go/src/cmd/addr2line/main.go +101 -0
- go/src/cmd/api/api_test.go +337 -0
- go/src/cmd/api/boring_test.go +17 -0
- go/src/cmd/api/main_test.go +1244 -0
- go/src/cmd/asm/doc.go +62 -0
- go/src/cmd/asm/main.go +130 -0
- go/src/cmd/buildid/buildid.go +84 -0
- go/src/cmd/buildid/doc.go +19 -0
- go/src/cmd/cgo/ast.go +576 -0
- go/src/cmd/cgo/doc.go +1111 -0
- go/src/cmd/cgo/gcc.go +0 -0
- go/src/cmd/cgo/godefs.go +127 -0
- go/src/cmd/cgo/main.go +617 -0
- go/src/cmd/cgo/out.go +2099 -0
- go/src/cmd/cgo/util.go +106 -0
- go/src/cmd/cgo/zdefaultcc.go +23 -0
- go/src/cmd/compile/README.md +366 -0
- go/src/cmd/compile/abi-internal.md +1016 -0
- go/src/cmd/compile/doc.go +360 -0
- go/src/cmd/compile/main.go +59 -0
- go/src/cmd/compile/profile.sh +21 -0
- go/src/cmd/compile/script_test.go +67 -0
- go/src/cmd/covdata/argsmerge.go +56 -0
- go/src/cmd/covdata/covdata.go +237 -0
- go/src/cmd/covdata/doc.go +80 -0
- go/src/cmd/covdata/dump.go +357 -0
- go/src/cmd/covdata/export_test.go +7 -0
- go/src/cmd/covdata/merge.go +111 -0
- go/src/cmd/covdata/metamerge.go +431 -0
- go/src/cmd/covdata/subtractintersect.go +196 -0
- go/src/cmd/covdata/tool_test.go +943 -0
- go/src/cmd/cover/cfg_test.go +271 -0
- go/src/cmd/cover/cover.go +1211 -0
- go/src/cmd/cover/cover_test.go +640 -0
- go/src/cmd/cover/doc.go +32 -0
- go/src/cmd/cover/export_test.go +7 -0
- go/src/cmd/cover/func.go +248 -0
- go/src/cmd/cover/html.go +306 -0
- go/src/cmd/cover/pkgname_test.go +31 -0
- go/src/cmd/dist/README +20 -0
- go/src/cmd/dist/build.go +2020 -0
- go/src/cmd/dist/build_test.go +43 -0
- go/src/cmd/dist/buildgo.go +145 -0
- go/src/cmd/dist/buildruntime.go +86 -0
- go/src/cmd/dist/buildtag.go +133 -0
- go/src/cmd/dist/buildtag_test.go +43 -0
- go/src/cmd/dist/buildtool.go +408 -0
- go/src/cmd/dist/doc.go +21 -0
- go/src/cmd/dist/exec.go +40 -0
go/src/cmd/addr2line/addr2line_test.go
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Copyright 2014 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 |
+
package main
|
| 6 |
+
|
| 7 |
+
import (
|
| 8 |
+
"bufio"
|
| 9 |
+
"bytes"
|
| 10 |
+
"internal/testenv"
|
| 11 |
+
"os"
|
| 12 |
+
"path/filepath"
|
| 13 |
+
"runtime"
|
| 14 |
+
"strings"
|
| 15 |
+
"testing"
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
// TestMain executes the test binary as the addr2line command if
|
| 19 |
+
// GO_ADDR2LINETEST_IS_ADDR2LINE is set, and runs the tests otherwise.
|
| 20 |
+
func TestMain(m *testing.M) {
|
| 21 |
+
if os.Getenv("GO_ADDR2LINETEST_IS_ADDR2LINE") != "" {
|
| 22 |
+
main()
|
| 23 |
+
os.Exit(0)
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
os.Setenv("GO_ADDR2LINETEST_IS_ADDR2LINE", "1") // Set for subprocesses to inherit.
|
| 27 |
+
os.Exit(m.Run())
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
func loadSyms(t *testing.T, dbgExePath string) map[string]string {
|
| 31 |
+
cmd := testenv.Command(t, testenv.GoToolPath(t), "tool", "nm", dbgExePath)
|
| 32 |
+
out, err := cmd.CombinedOutput()
|
| 33 |
+
if err != nil {
|
| 34 |
+
t.Fatalf("%v: %v\n%s", cmd, err, string(out))
|
| 35 |
+
}
|
| 36 |
+
syms := make(map[string]string)
|
| 37 |
+
scanner := bufio.NewScanner(bytes.NewReader(out))
|
| 38 |
+
for scanner.Scan() {
|
| 39 |
+
f := strings.Fields(scanner.Text())
|
| 40 |
+
if len(f) < 3 {
|
| 41 |
+
continue
|
| 42 |
+
}
|
| 43 |
+
syms[f[2]] = f[0]
|
| 44 |
+
}
|
| 45 |
+
if err := scanner.Err(); err != nil {
|
| 46 |
+
t.Fatalf("error reading symbols: %v", err)
|
| 47 |
+
}
|
| 48 |
+
return syms
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
func runAddr2Line(t *testing.T, dbgExePath, addr string) (funcname, path, lineno string) {
|
| 52 |
+
cmd := testenv.Command(t, testenv.Executable(t), dbgExePath)
|
| 53 |
+
cmd.Stdin = strings.NewReader(addr)
|
| 54 |
+
out, err := cmd.CombinedOutput()
|
| 55 |
+
if err != nil {
|
| 56 |
+
t.Fatalf("go tool addr2line %v: %v\n%s", os.Args[0], err, string(out))
|
| 57 |
+
}
|
| 58 |
+
f := strings.Split(string(out), "\n")
|
| 59 |
+
if len(f) < 3 && f[2] == "" {
|
| 60 |
+
t.Fatal("addr2line output must have 2 lines")
|
| 61 |
+
}
|
| 62 |
+
funcname = f[0]
|
| 63 |
+
pathAndLineNo := f[1]
|
| 64 |
+
f = strings.Split(pathAndLineNo, ":")
|
| 65 |
+
if runtime.GOOS == "windows" && len(f) == 3 {
|
| 66 |
+
// Reattach drive letter.
|
| 67 |
+
f = []string{f[0] + ":" + f[1], f[2]}
|
| 68 |
+
}
|
| 69 |
+
if len(f) != 2 {
|
| 70 |
+
t.Fatalf("no line number found in %q", pathAndLineNo)
|
| 71 |
+
}
|
| 72 |
+
return funcname, f[0], f[1]
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
const symName = "cmd/addr2line.TestAddr2Line"
|
| 76 |
+
|
| 77 |
+
func testAddr2Line(t *testing.T, dbgExePath, addr string) {
|
| 78 |
+
funcName, srcPath, srcLineNo := runAddr2Line(t, dbgExePath, addr)
|
| 79 |
+
if symName != funcName {
|
| 80 |
+
t.Fatalf("expected function name %v; got %v", symName, funcName)
|
| 81 |
+
}
|
| 82 |
+
fi1, err := os.Stat("addr2line_test.go")
|
| 83 |
+
if err != nil {
|
| 84 |
+
t.Fatalf("Stat failed: %v", err)
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
// Debug paths are stored slash-separated, so convert to system-native.
|
| 88 |
+
srcPath = filepath.FromSlash(srcPath)
|
| 89 |
+
fi2, err := os.Stat(srcPath)
|
| 90 |
+
if err != nil {
|
| 91 |
+
t.Fatalf("Stat failed: %v", err)
|
| 92 |
+
}
|
| 93 |
+
if !os.SameFile(fi1, fi2) {
|
| 94 |
+
t.Fatalf("addr2line_test.go and %s are not same file", srcPath)
|
| 95 |
+
}
|
| 96 |
+
if want := "102"; srcLineNo != want {
|
| 97 |
+
t.Fatalf("line number = %v; want %s", srcLineNo, want)
|
| 98 |
+
}
|
| 99 |
+
}
|
| 100 |
+
|
| 101 |
+
// This is line 101. The test depends on that.
|
| 102 |
+
func TestAddr2Line(t *testing.T) {
|
| 103 |
+
testenv.MustHaveGoBuild(t)
|
| 104 |
+
|
| 105 |
+
tmpDir := t.TempDir()
|
| 106 |
+
|
| 107 |
+
// Build copy of test binary with debug symbols,
|
| 108 |
+
// since the one running now may not have them.
|
| 109 |
+
exepath := filepath.Join(tmpDir, "testaddr2line_test.exe")
|
| 110 |
+
out, err := testenv.Command(t, testenv.GoToolPath(t), "test", "-c", "-o", exepath, "cmd/addr2line").CombinedOutput()
|
| 111 |
+
if err != nil {
|
| 112 |
+
t.Fatalf("go test -c -o %v cmd/addr2line: %v\n%s", exepath, err, string(out))
|
| 113 |
+
}
|
| 114 |
+
|
| 115 |
+
syms := loadSyms(t, exepath)
|
| 116 |
+
|
| 117 |
+
testAddr2Line(t, exepath, syms[symName])
|
| 118 |
+
testAddr2Line(t, exepath, "0x"+syms[symName])
|
| 119 |
+
}
|
go/src/cmd/addr2line/main.go
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
// Addr2line is a minimal simulation of the GNU addr2line tool,
|
| 6 |
+
// just enough to support pprof.
|
| 7 |
+
//
|
| 8 |
+
// Usage:
|
| 9 |
+
//
|
| 10 |
+
// go tool addr2line binary
|
| 11 |
+
//
|
| 12 |
+
// Addr2line reads hexadecimal addresses, one per line and with optional 0x prefix,
|
| 13 |
+
// from standard input. For each input address, addr2line prints two output lines,
|
| 14 |
+
// first the name of the function containing the address and second the file:line
|
| 15 |
+
// of the source code corresponding to that address.
|
| 16 |
+
//
|
| 17 |
+
// This tool is intended for use only by pprof; its interface may change or
|
| 18 |
+
// it may be deleted entirely in future releases.
|
| 19 |
+
package main
|
| 20 |
+
|
| 21 |
+
import (
|
| 22 |
+
"bufio"
|
| 23 |
+
"flag"
|
| 24 |
+
"fmt"
|
| 25 |
+
"log"
|
| 26 |
+
"os"
|
| 27 |
+
"strconv"
|
| 28 |
+
"strings"
|
| 29 |
+
|
| 30 |
+
"cmd/internal/objfile"
|
| 31 |
+
"cmd/internal/telemetry/counter"
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
func printUsage(w *os.File) {
|
| 35 |
+
fmt.Fprintf(w, "usage: addr2line binary\n")
|
| 36 |
+
fmt.Fprintf(w, "reads addresses from standard input and writes two lines for each:\n")
|
| 37 |
+
fmt.Fprintf(w, "\tfunction name\n")
|
| 38 |
+
fmt.Fprintf(w, "\tfile:line\n")
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
func usage() {
|
| 42 |
+
printUsage(os.Stderr)
|
| 43 |
+
os.Exit(2)
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
func main() {
|
| 47 |
+
log.SetFlags(0)
|
| 48 |
+
log.SetPrefix("addr2line: ")
|
| 49 |
+
counter.Open()
|
| 50 |
+
|
| 51 |
+
// pprof expects this behavior when checking for addr2line
|
| 52 |
+
if len(os.Args) > 1 && os.Args[1] == "--help" {
|
| 53 |
+
printUsage(os.Stdout)
|
| 54 |
+
os.Exit(0)
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
flag.Usage = usage
|
| 58 |
+
flag.Parse()
|
| 59 |
+
counter.Inc("addr2line/invocations")
|
| 60 |
+
counter.CountFlags("addr2line/flag:", *flag.CommandLine)
|
| 61 |
+
if flag.NArg() != 1 {
|
| 62 |
+
usage()
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
f, err := objfile.Open(flag.Arg(0))
|
| 66 |
+
if err != nil {
|
| 67 |
+
log.Fatal(err)
|
| 68 |
+
}
|
| 69 |
+
defer f.Close()
|
| 70 |
+
|
| 71 |
+
tab, err := f.PCLineTable()
|
| 72 |
+
if err != nil {
|
| 73 |
+
log.Fatalf("reading %s: %v", flag.Arg(0), err)
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
stdin := bufio.NewScanner(os.Stdin)
|
| 77 |
+
stdout := bufio.NewWriter(os.Stdout)
|
| 78 |
+
|
| 79 |
+
for stdin.Scan() {
|
| 80 |
+
p := stdin.Text()
|
| 81 |
+
if strings.Contains(p, ":") {
|
| 82 |
+
// Reverse translate file:line to pc.
|
| 83 |
+
// This was an extension in the old C version of 'go tool addr2line'
|
| 84 |
+
// and is probably not used by anyone, but recognize the syntax.
|
| 85 |
+
// We don't have an implementation.
|
| 86 |
+
fmt.Fprintf(stdout, "!reverse translation not implemented\n")
|
| 87 |
+
continue
|
| 88 |
+
}
|
| 89 |
+
pc, _ := strconv.ParseUint(strings.TrimPrefix(p, "0x"), 16, 64)
|
| 90 |
+
file, line, fn := tab.PCToLine(pc)
|
| 91 |
+
name := "?"
|
| 92 |
+
if fn != nil {
|
| 93 |
+
name = fn.Name
|
| 94 |
+
} else {
|
| 95 |
+
file = "?"
|
| 96 |
+
line = 0
|
| 97 |
+
}
|
| 98 |
+
fmt.Fprintf(stdout, "%s\n%s:%d\n", name, file, line)
|
| 99 |
+
}
|
| 100 |
+
stdout.Flush()
|
| 101 |
+
}
|
go/src/cmd/api/api_test.go
ADDED
|
@@ -0,0 +1,337 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Copyright 2011 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 |
+
package main
|
| 6 |
+
|
| 7 |
+
import (
|
| 8 |
+
"flag"
|
| 9 |
+
"fmt"
|
| 10 |
+
"go/build"
|
| 11 |
+
"internal/testenv"
|
| 12 |
+
"os"
|
| 13 |
+
"path/filepath"
|
| 14 |
+
"slices"
|
| 15 |
+
"strings"
|
| 16 |
+
"sync"
|
| 17 |
+
"testing"
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
var flagCheck = flag.Bool("check", false, "run API checks")
|
| 21 |
+
|
| 22 |
+
func TestMain(m *testing.M) {
|
| 23 |
+
flag.Parse()
|
| 24 |
+
for _, c := range contexts {
|
| 25 |
+
c.Compiler = build.Default.Compiler
|
| 26 |
+
}
|
| 27 |
+
build.Default.GOROOT = testenv.GOROOT(nil)
|
| 28 |
+
|
| 29 |
+
os.Exit(m.Run())
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
var (
|
| 33 |
+
updateGolden = flag.Bool("updategolden", false, "update golden files")
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
func TestGolden(t *testing.T) {
|
| 37 |
+
if *flagCheck {
|
| 38 |
+
// slow, not worth repeating in -check
|
| 39 |
+
t.Skip("skipping with -check set")
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
testenv.MustHaveGoBuild(t)
|
| 43 |
+
|
| 44 |
+
td, err := os.Open("testdata/src/pkg")
|
| 45 |
+
if err != nil {
|
| 46 |
+
t.Fatal(err)
|
| 47 |
+
}
|
| 48 |
+
fis, err := td.Readdir(0)
|
| 49 |
+
if err != nil {
|
| 50 |
+
t.Fatal(err)
|
| 51 |
+
}
|
| 52 |
+
for _, fi := range fis {
|
| 53 |
+
if !fi.IsDir() {
|
| 54 |
+
continue
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
// TODO(gri) remove extra pkg directory eventually
|
| 58 |
+
goldenFile := filepath.Join("testdata", "src", "pkg", fi.Name(), "golden.txt")
|
| 59 |
+
w := NewWalker(nil, "testdata/src/pkg")
|
| 60 |
+
pkg, err := w.import_(fi.Name())
|
| 61 |
+
if err != nil {
|
| 62 |
+
t.Fatalf("import %s: %v", fi.Name(), err)
|
| 63 |
+
}
|
| 64 |
+
w.export(pkg)
|
| 65 |
+
|
| 66 |
+
if *updateGolden {
|
| 67 |
+
os.Remove(goldenFile)
|
| 68 |
+
f, err := os.Create(goldenFile)
|
| 69 |
+
if err != nil {
|
| 70 |
+
t.Fatal(err)
|
| 71 |
+
}
|
| 72 |
+
for _, feat := range w.Features() {
|
| 73 |
+
fmt.Fprintf(f, "%s\n", feat)
|
| 74 |
+
}
|
| 75 |
+
f.Close()
|
| 76 |
+
}
|
| 77 |
+
|
| 78 |
+
bs, err := os.ReadFile(goldenFile)
|
| 79 |
+
if err != nil {
|
| 80 |
+
t.Fatalf("opening golden.txt for package %q: %v", fi.Name(), err)
|
| 81 |
+
}
|
| 82 |
+
wanted := strings.Split(string(bs), "\n")
|
| 83 |
+
slices.Sort(wanted)
|
| 84 |
+
for _, feature := range wanted {
|
| 85 |
+
if feature == "" {
|
| 86 |
+
continue
|
| 87 |
+
}
|
| 88 |
+
_, ok := w.features[feature]
|
| 89 |
+
if !ok {
|
| 90 |
+
t.Errorf("package %s: missing feature %q", fi.Name(), feature)
|
| 91 |
+
}
|
| 92 |
+
delete(w.features, feature)
|
| 93 |
+
}
|
| 94 |
+
|
| 95 |
+
for _, feature := range w.Features() {
|
| 96 |
+
t.Errorf("package %s: extra feature not in golden file: %q", fi.Name(), feature)
|
| 97 |
+
}
|
| 98 |
+
}
|
| 99 |
+
}
|
| 100 |
+
|
| 101 |
+
func TestCompareAPI(t *testing.T) {
|
| 102 |
+
if *flagCheck {
|
| 103 |
+
// not worth repeating in -check
|
| 104 |
+
t.Skip("skipping with -check set")
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
tests := []struct {
|
| 108 |
+
name string
|
| 109 |
+
features, required, exception []string
|
| 110 |
+
ok bool // want
|
| 111 |
+
out string // want
|
| 112 |
+
}{
|
| 113 |
+
{
|
| 114 |
+
name: "equal",
|
| 115 |
+
features: []string{"A", "B", "C"},
|
| 116 |
+
required: []string{"A", "B", "C"},
|
| 117 |
+
ok: true,
|
| 118 |
+
out: "",
|
| 119 |
+
},
|
| 120 |
+
{
|
| 121 |
+
name: "feature added",
|
| 122 |
+
features: []string{"A", "B", "C", "D", "E", "F"},
|
| 123 |
+
required: []string{"B", "D"},
|
| 124 |
+
ok: false,
|
| 125 |
+
out: "+A\n+C\n+E\n+F\n",
|
| 126 |
+
},
|
| 127 |
+
{
|
| 128 |
+
name: "feature removed",
|
| 129 |
+
features: []string{"C", "A"},
|
| 130 |
+
required: []string{"A", "B", "C"},
|
| 131 |
+
ok: false,
|
| 132 |
+
out: "-B\n",
|
| 133 |
+
},
|
| 134 |
+
{
|
| 135 |
+
name: "exception removal",
|
| 136 |
+
features: []string{"A", "C"},
|
| 137 |
+
required: []string{"A", "B", "C"},
|
| 138 |
+
exception: []string{"B"},
|
| 139 |
+
ok: true,
|
| 140 |
+
out: "",
|
| 141 |
+
},
|
| 142 |
+
|
| 143 |
+
// Test that a feature required on a subset of ports is implicitly satisfied
|
| 144 |
+
// by the same feature being implemented on all ports. That is, it shouldn't
|
| 145 |
+
// say "pkg syscall (darwin-amd64), type RawSockaddrInet6 struct" is missing.
|
| 146 |
+
// See https://go.dev/issue/4303.
|
| 147 |
+
{
|
| 148 |
+
name: "contexts reconverging after api/next/* update",
|
| 149 |
+
features: []string{
|
| 150 |
+
"A",
|
| 151 |
+
"pkg syscall, type RawSockaddrInet6 struct",
|
| 152 |
+
},
|
| 153 |
+
required: []string{
|
| 154 |
+
"A",
|
| 155 |
+
"pkg syscall (darwin-amd64), type RawSockaddrInet6 struct", // api/go1.n.txt
|
| 156 |
+
"pkg syscall, type RawSockaddrInet6 struct", // api/next/n.txt
|
| 157 |
+
},
|
| 158 |
+
ok: true,
|
| 159 |
+
out: "",
|
| 160 |
+
},
|
| 161 |
+
{
|
| 162 |
+
name: "contexts reconverging before api/next/* update",
|
| 163 |
+
features: []string{
|
| 164 |
+
"A",
|
| 165 |
+
"pkg syscall, type RawSockaddrInet6 struct",
|
| 166 |
+
},
|
| 167 |
+
required: []string{
|
| 168 |
+
"A",
|
| 169 |
+
"pkg syscall (darwin-amd64), type RawSockaddrInet6 struct",
|
| 170 |
+
},
|
| 171 |
+
ok: false,
|
| 172 |
+
out: "+pkg syscall, type RawSockaddrInet6 struct\n",
|
| 173 |
+
},
|
| 174 |
+
}
|
| 175 |
+
for _, tt := range tests {
|
| 176 |
+
buf := new(strings.Builder)
|
| 177 |
+
gotOK := compareAPI(buf, tt.features, tt.required, tt.exception)
|
| 178 |
+
if gotOK != tt.ok {
|
| 179 |
+
t.Errorf("%s: ok = %v; want %v", tt.name, gotOK, tt.ok)
|
| 180 |
+
}
|
| 181 |
+
if got := buf.String(); got != tt.out {
|
| 182 |
+
t.Errorf("%s: output differs\nGOT:\n%s\nWANT:\n%s", tt.name, got, tt.out)
|
| 183 |
+
}
|
| 184 |
+
}
|
| 185 |
+
}
|
| 186 |
+
|
| 187 |
+
func TestSkipInternal(t *testing.T) {
|
| 188 |
+
if *flagCheck {
|
| 189 |
+
// not worth repeating in -check
|
| 190 |
+
t.Skip("skipping with -check set")
|
| 191 |
+
}
|
| 192 |
+
|
| 193 |
+
tests := []struct {
|
| 194 |
+
pkg string
|
| 195 |
+
want bool
|
| 196 |
+
}{
|
| 197 |
+
{"net/http", true},
|
| 198 |
+
{"net/http/internal-foo", true},
|
| 199 |
+
{"net/http/internal", false},
|
| 200 |
+
{"net/http/internal/bar", false},
|
| 201 |
+
{"internal/foo", false},
|
| 202 |
+
{"internal", false},
|
| 203 |
+
}
|
| 204 |
+
for _, tt := range tests {
|
| 205 |
+
got := !internalPkg.MatchString(tt.pkg)
|
| 206 |
+
if got != tt.want {
|
| 207 |
+
t.Errorf("%s is internal = %v; want %v", tt.pkg, got, tt.want)
|
| 208 |
+
}
|
| 209 |
+
}
|
| 210 |
+
}
|
| 211 |
+
|
| 212 |
+
func BenchmarkAll(b *testing.B) {
|
| 213 |
+
for i := 0; i < b.N; i++ {
|
| 214 |
+
for _, context := range contexts {
|
| 215 |
+
w := NewWalker(context, filepath.Join(testenv.GOROOT(b), "src"))
|
| 216 |
+
for _, name := range w.stdPackages {
|
| 217 |
+
pkg, err := w.import_(name)
|
| 218 |
+
if _, nogo := err.(*build.NoGoError); nogo {
|
| 219 |
+
continue
|
| 220 |
+
}
|
| 221 |
+
if err != nil {
|
| 222 |
+
b.Fatalf("import %s (%s-%s): %v", name, context.GOOS, context.GOARCH, err)
|
| 223 |
+
}
|
| 224 |
+
w.export(pkg)
|
| 225 |
+
}
|
| 226 |
+
w.Features()
|
| 227 |
+
}
|
| 228 |
+
}
|
| 229 |
+
}
|
| 230 |
+
|
| 231 |
+
var warmupCache = sync.OnceFunc(func() {
|
| 232 |
+
// Warm up the import cache in parallel.
|
| 233 |
+
var wg sync.WaitGroup
|
| 234 |
+
for _, context := range contexts {
|
| 235 |
+
context := context
|
| 236 |
+
wg.Add(1)
|
| 237 |
+
go func() {
|
| 238 |
+
defer wg.Done()
|
| 239 |
+
_ = NewWalker(context, filepath.Join(testenv.GOROOT(nil), "src"))
|
| 240 |
+
}()
|
| 241 |
+
}
|
| 242 |
+
wg.Wait()
|
| 243 |
+
})
|
| 244 |
+
|
| 245 |
+
func TestIssue21181(t *testing.T) {
|
| 246 |
+
if testing.Short() {
|
| 247 |
+
t.Skip("skipping with -short")
|
| 248 |
+
}
|
| 249 |
+
if *flagCheck {
|
| 250 |
+
// slow, not worth repeating in -check
|
| 251 |
+
t.Skip("skipping with -check set")
|
| 252 |
+
}
|
| 253 |
+
testenv.MustHaveGoBuild(t)
|
| 254 |
+
|
| 255 |
+
warmupCache()
|
| 256 |
+
|
| 257 |
+
for _, context := range contexts {
|
| 258 |
+
w := NewWalker(context, "testdata/src/issue21181")
|
| 259 |
+
pkg, err := w.import_("p")
|
| 260 |
+
if err != nil {
|
| 261 |
+
t.Fatalf("import %s (%s-%s): %v", "p", context.GOOS, context.GOARCH, err)
|
| 262 |
+
}
|
| 263 |
+
w.export(pkg)
|
| 264 |
+
}
|
| 265 |
+
}
|
| 266 |
+
|
| 267 |
+
func TestIssue29837(t *testing.T) {
|
| 268 |
+
if testing.Short() {
|
| 269 |
+
t.Skip("skipping with -short")
|
| 270 |
+
}
|
| 271 |
+
if *flagCheck {
|
| 272 |
+
// slow, not worth repeating in -check
|
| 273 |
+
t.Skip("skipping with -check set")
|
| 274 |
+
}
|
| 275 |
+
testenv.MustHaveGoBuild(t)
|
| 276 |
+
|
| 277 |
+
warmupCache()
|
| 278 |
+
|
| 279 |
+
for _, context := range contexts {
|
| 280 |
+
w := NewWalker(context, "testdata/src/issue29837")
|
| 281 |
+
_, err := w.ImportFrom("p", "", 0)
|
| 282 |
+
if _, nogo := err.(*build.NoGoError); !nogo {
|
| 283 |
+
t.Errorf("expected *build.NoGoError, got %T", err)
|
| 284 |
+
}
|
| 285 |
+
}
|
| 286 |
+
}
|
| 287 |
+
|
| 288 |
+
func TestIssue41358(t *testing.T) {
|
| 289 |
+
if *flagCheck {
|
| 290 |
+
// slow, not worth repeating in -check
|
| 291 |
+
t.Skip("skipping with -check set")
|
| 292 |
+
}
|
| 293 |
+
testenv.MustHaveGoBuild(t)
|
| 294 |
+
context := new(build.Context)
|
| 295 |
+
*context = build.Default
|
| 296 |
+
context.Dir = filepath.Join(testenv.GOROOT(t), "src")
|
| 297 |
+
|
| 298 |
+
w := NewWalker(context, context.Dir)
|
| 299 |
+
for _, pkg := range w.stdPackages {
|
| 300 |
+
if strings.HasPrefix(pkg, "vendor/") || strings.HasPrefix(pkg, "golang.org/x/") {
|
| 301 |
+
t.Fatalf("stdPackages contains unexpected package %s", pkg)
|
| 302 |
+
}
|
| 303 |
+
}
|
| 304 |
+
}
|
| 305 |
+
|
| 306 |
+
func TestIssue64958(t *testing.T) {
|
| 307 |
+
if testing.Short() {
|
| 308 |
+
t.Skip("skipping with -short")
|
| 309 |
+
}
|
| 310 |
+
if *flagCheck {
|
| 311 |
+
// slow, not worth repeating in -check
|
| 312 |
+
t.Skip("skipping with -check set")
|
| 313 |
+
}
|
| 314 |
+
testenv.MustHaveGoBuild(t)
|
| 315 |
+
|
| 316 |
+
defer func() {
|
| 317 |
+
if x := recover(); x != nil {
|
| 318 |
+
t.Errorf("expected no panic; recovered %v", x)
|
| 319 |
+
}
|
| 320 |
+
}()
|
| 321 |
+
for _, context := range contexts {
|
| 322 |
+
w := NewWalker(context, "testdata/src/issue64958")
|
| 323 |
+
pkg, err := w.importFrom("p", "", 0)
|
| 324 |
+
if err != nil {
|
| 325 |
+
t.Errorf("expected no error importing; got %T", err)
|
| 326 |
+
}
|
| 327 |
+
w.export(pkg)
|
| 328 |
+
}
|
| 329 |
+
}
|
| 330 |
+
|
| 331 |
+
func TestCheck(t *testing.T) {
|
| 332 |
+
if !*flagCheck {
|
| 333 |
+
t.Skip("-check not specified")
|
| 334 |
+
}
|
| 335 |
+
testenv.MustHaveGoBuild(t)
|
| 336 |
+
Check(t)
|
| 337 |
+
}
|
go/src/cmd/api/boring_test.go
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
//go:build boringcrypto
|
| 6 |
+
|
| 7 |
+
package main
|
| 8 |
+
|
| 9 |
+
import (
|
| 10 |
+
"fmt"
|
| 11 |
+
"os"
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
func init() {
|
| 15 |
+
fmt.Printf("SKIP with boringcrypto enabled\n")
|
| 16 |
+
os.Exit(0)
|
| 17 |
+
}
|
go/src/cmd/api/main_test.go
ADDED
|
@@ -0,0 +1,1244 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Copyright 2011 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 package computes the exported API of a set of Go packages.
|
| 6 |
+
// It is only a test, not a command, nor a usefully importable package.
|
| 7 |
+
|
| 8 |
+
package main
|
| 9 |
+
|
| 10 |
+
import (
|
| 11 |
+
"bufio"
|
| 12 |
+
"bytes"
|
| 13 |
+
"encoding/json"
|
| 14 |
+
"fmt"
|
| 15 |
+
"go/ast"
|
| 16 |
+
"go/build"
|
| 17 |
+
"go/parser"
|
| 18 |
+
"go/token"
|
| 19 |
+
"go/types"
|
| 20 |
+
"internal/testenv"
|
| 21 |
+
"io"
|
| 22 |
+
"log"
|
| 23 |
+
"os"
|
| 24 |
+
"os/exec"
|
| 25 |
+
"path/filepath"
|
| 26 |
+
"regexp"
|
| 27 |
+
"runtime"
|
| 28 |
+
"slices"
|
| 29 |
+
"strconv"
|
| 30 |
+
"strings"
|
| 31 |
+
"sync"
|
| 32 |
+
"testing"
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
const verbose = false
|
| 36 |
+
|
| 37 |
+
func goCmd() string {
|
| 38 |
+
var exeSuffix string
|
| 39 |
+
if runtime.GOOS == "windows" {
|
| 40 |
+
exeSuffix = ".exe"
|
| 41 |
+
}
|
| 42 |
+
path := filepath.Join(testenv.GOROOT(nil), "bin", "go"+exeSuffix)
|
| 43 |
+
if _, err := os.Stat(path); err == nil {
|
| 44 |
+
return path
|
| 45 |
+
}
|
| 46 |
+
return "go"
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
// contexts are the default contexts which are scanned.
|
| 50 |
+
var contexts = []*build.Context{
|
| 51 |
+
{GOOS: "linux", GOARCH: "386", CgoEnabled: true},
|
| 52 |
+
{GOOS: "linux", GOARCH: "386"},
|
| 53 |
+
{GOOS: "linux", GOARCH: "amd64", CgoEnabled: true},
|
| 54 |
+
{GOOS: "linux", GOARCH: "amd64"},
|
| 55 |
+
{GOOS: "linux", GOARCH: "arm", CgoEnabled: true},
|
| 56 |
+
{GOOS: "linux", GOARCH: "arm"},
|
| 57 |
+
{GOOS: "darwin", GOARCH: "amd64", CgoEnabled: true},
|
| 58 |
+
{GOOS: "darwin", GOARCH: "amd64"},
|
| 59 |
+
{GOOS: "darwin", GOARCH: "arm64", CgoEnabled: true},
|
| 60 |
+
{GOOS: "darwin", GOARCH: "arm64"},
|
| 61 |
+
{GOOS: "windows", GOARCH: "amd64"},
|
| 62 |
+
{GOOS: "windows", GOARCH: "386"},
|
| 63 |
+
{GOOS: "freebsd", GOARCH: "386", CgoEnabled: true},
|
| 64 |
+
{GOOS: "freebsd", GOARCH: "386"},
|
| 65 |
+
{GOOS: "freebsd", GOARCH: "amd64", CgoEnabled: true},
|
| 66 |
+
{GOOS: "freebsd", GOARCH: "amd64"},
|
| 67 |
+
{GOOS: "freebsd", GOARCH: "arm", CgoEnabled: true},
|
| 68 |
+
{GOOS: "freebsd", GOARCH: "arm"},
|
| 69 |
+
{GOOS: "freebsd", GOARCH: "arm64", CgoEnabled: true},
|
| 70 |
+
{GOOS: "freebsd", GOARCH: "arm64"},
|
| 71 |
+
{GOOS: "freebsd", GOARCH: "riscv64", CgoEnabled: true},
|
| 72 |
+
{GOOS: "freebsd", GOARCH: "riscv64"},
|
| 73 |
+
{GOOS: "netbsd", GOARCH: "386", CgoEnabled: true},
|
| 74 |
+
{GOOS: "netbsd", GOARCH: "386"},
|
| 75 |
+
{GOOS: "netbsd", GOARCH: "amd64", CgoEnabled: true},
|
| 76 |
+
{GOOS: "netbsd", GOARCH: "amd64"},
|
| 77 |
+
{GOOS: "netbsd", GOARCH: "arm", CgoEnabled: true},
|
| 78 |
+
{GOOS: "netbsd", GOARCH: "arm"},
|
| 79 |
+
{GOOS: "netbsd", GOARCH: "arm64", CgoEnabled: true},
|
| 80 |
+
{GOOS: "netbsd", GOARCH: "arm64"},
|
| 81 |
+
{GOOS: "openbsd", GOARCH: "386", CgoEnabled: true},
|
| 82 |
+
{GOOS: "openbsd", GOARCH: "386"},
|
| 83 |
+
{GOOS: "openbsd", GOARCH: "amd64", CgoEnabled: true},
|
| 84 |
+
{GOOS: "openbsd", GOARCH: "amd64"},
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
func contextName(c *build.Context) string {
|
| 88 |
+
s := c.GOOS + "-" + c.GOARCH
|
| 89 |
+
if c.CgoEnabled {
|
| 90 |
+
s += "-cgo"
|
| 91 |
+
}
|
| 92 |
+
if c.Dir != "" {
|
| 93 |
+
s += fmt.Sprintf(" [%s]", c.Dir)
|
| 94 |
+
}
|
| 95 |
+
return s
|
| 96 |
+
}
|
| 97 |
+
|
| 98 |
+
var internalPkg = regexp.MustCompile(`(^|/)internal($|/)`)
|
| 99 |
+
|
| 100 |
+
var exitCode = 0
|
| 101 |
+
|
| 102 |
+
func Check(t *testing.T) {
|
| 103 |
+
checkFiles, err := filepath.Glob(filepath.Join(testenv.GOROOT(t), "api/go1*.txt"))
|
| 104 |
+
if err != nil {
|
| 105 |
+
t.Fatal(err)
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
var nextFiles []string
|
| 109 |
+
if v := runtime.Version(); strings.Contains(v, "devel") || strings.Contains(v, "beta") {
|
| 110 |
+
next, err := filepath.Glob(filepath.Join(testenv.GOROOT(t), "api/next/*.txt"))
|
| 111 |
+
if err != nil {
|
| 112 |
+
t.Fatal(err)
|
| 113 |
+
}
|
| 114 |
+
nextFiles = next
|
| 115 |
+
}
|
| 116 |
+
|
| 117 |
+
for _, c := range contexts {
|
| 118 |
+
c.Compiler = build.Default.Compiler
|
| 119 |
+
}
|
| 120 |
+
|
| 121 |
+
walkers := make([]*Walker, len(contexts))
|
| 122 |
+
var wg sync.WaitGroup
|
| 123 |
+
for i, context := range contexts {
|
| 124 |
+
i, context := i, context
|
| 125 |
+
wg.Add(1)
|
| 126 |
+
go func() {
|
| 127 |
+
defer wg.Done()
|
| 128 |
+
walkers[i] = NewWalker(context, filepath.Join(testenv.GOROOT(t), "src"))
|
| 129 |
+
}()
|
| 130 |
+
}
|
| 131 |
+
wg.Wait()
|
| 132 |
+
|
| 133 |
+
var featureCtx = make(map[string]map[string]bool) // feature -> context name -> true
|
| 134 |
+
for _, w := range walkers {
|
| 135 |
+
for _, name := range w.stdPackages {
|
| 136 |
+
pkg, err := w.import_(name)
|
| 137 |
+
if _, nogo := err.(*build.NoGoError); nogo {
|
| 138 |
+
continue
|
| 139 |
+
}
|
| 140 |
+
if err != nil {
|
| 141 |
+
log.Fatalf("Import(%q): %v", name, err)
|
| 142 |
+
}
|
| 143 |
+
w.export(pkg)
|
| 144 |
+
}
|
| 145 |
+
|
| 146 |
+
ctxName := contextName(w.context)
|
| 147 |
+
for _, f := range w.Features() {
|
| 148 |
+
if featureCtx[f] == nil {
|
| 149 |
+
featureCtx[f] = make(map[string]bool)
|
| 150 |
+
}
|
| 151 |
+
featureCtx[f][ctxName] = true
|
| 152 |
+
}
|
| 153 |
+
}
|
| 154 |
+
|
| 155 |
+
var features []string
|
| 156 |
+
for f, cmap := range featureCtx {
|
| 157 |
+
if len(cmap) == len(contexts) {
|
| 158 |
+
features = append(features, f)
|
| 159 |
+
continue
|
| 160 |
+
}
|
| 161 |
+
comma := strings.Index(f, ",")
|
| 162 |
+
for cname := range cmap {
|
| 163 |
+
f2 := fmt.Sprintf("%s (%s)%s", f[:comma], cname, f[comma:])
|
| 164 |
+
features = append(features, f2)
|
| 165 |
+
}
|
| 166 |
+
}
|
| 167 |
+
|
| 168 |
+
bw := bufio.NewWriter(os.Stdout)
|
| 169 |
+
defer bw.Flush()
|
| 170 |
+
|
| 171 |
+
var required []string
|
| 172 |
+
for _, file := range checkFiles {
|
| 173 |
+
required = append(required, fileFeatures(file, needApproval(file))...)
|
| 174 |
+
}
|
| 175 |
+
for _, file := range nextFiles {
|
| 176 |
+
required = append(required, fileFeatures(file, true)...)
|
| 177 |
+
}
|
| 178 |
+
exception := fileFeatures(filepath.Join(testenv.GOROOT(t), "api/except.txt"), false)
|
| 179 |
+
|
| 180 |
+
if exitCode == 1 {
|
| 181 |
+
t.Errorf("API database problems found")
|
| 182 |
+
}
|
| 183 |
+
if !compareAPI(bw, features, required, exception) {
|
| 184 |
+
t.Errorf("API differences found")
|
| 185 |
+
}
|
| 186 |
+
}
|
| 187 |
+
|
| 188 |
+
// export emits the exported package features.
|
| 189 |
+
func (w *Walker) export(pkg *apiPackage) {
|
| 190 |
+
if verbose {
|
| 191 |
+
log.Println(pkg)
|
| 192 |
+
}
|
| 193 |
+
pop := w.pushScope("pkg " + pkg.Path())
|
| 194 |
+
w.current = pkg
|
| 195 |
+
w.collectDeprecated()
|
| 196 |
+
scope := pkg.Scope()
|
| 197 |
+
for _, name := range scope.Names() {
|
| 198 |
+
if token.IsExported(name) {
|
| 199 |
+
w.emitObj(scope.Lookup(name))
|
| 200 |
+
}
|
| 201 |
+
}
|
| 202 |
+
pop()
|
| 203 |
+
}
|
| 204 |
+
|
| 205 |
+
func set(items []string) map[string]bool {
|
| 206 |
+
s := make(map[string]bool)
|
| 207 |
+
for _, v := range items {
|
| 208 |
+
s[v] = true
|
| 209 |
+
}
|
| 210 |
+
return s
|
| 211 |
+
}
|
| 212 |
+
|
| 213 |
+
var spaceParensRx = regexp.MustCompile(` \(\S+?\)`)
|
| 214 |
+
|
| 215 |
+
func featureWithoutContext(f string) string {
|
| 216 |
+
if !strings.Contains(f, "(") {
|
| 217 |
+
return f
|
| 218 |
+
}
|
| 219 |
+
return spaceParensRx.ReplaceAllString(f, "")
|
| 220 |
+
}
|
| 221 |
+
|
| 222 |
+
// portRemoved reports whether the given port-specific API feature is
|
| 223 |
+
// okay to no longer exist because its port was removed.
|
| 224 |
+
func portRemoved(feature string) bool {
|
| 225 |
+
return strings.Contains(feature, "(darwin-386)") ||
|
| 226 |
+
strings.Contains(feature, "(darwin-386-cgo)")
|
| 227 |
+
}
|
| 228 |
+
|
| 229 |
+
func compareAPI(w io.Writer, features, required, exception []string) (ok bool) {
|
| 230 |
+
ok = true
|
| 231 |
+
|
| 232 |
+
featureSet := set(features)
|
| 233 |
+
exceptionSet := set(exception)
|
| 234 |
+
|
| 235 |
+
slices.Sort(features)
|
| 236 |
+
slices.Sort(required)
|
| 237 |
+
|
| 238 |
+
take := func(sl *[]string) string {
|
| 239 |
+
s := (*sl)[0]
|
| 240 |
+
*sl = (*sl)[1:]
|
| 241 |
+
return s
|
| 242 |
+
}
|
| 243 |
+
|
| 244 |
+
for len(features) > 0 || len(required) > 0 {
|
| 245 |
+
switch {
|
| 246 |
+
case len(features) == 0 || (len(required) > 0 && required[0] < features[0]):
|
| 247 |
+
feature := take(&required)
|
| 248 |
+
if exceptionSet[feature] {
|
| 249 |
+
// An "unfortunate" case: the feature was once
|
| 250 |
+
// included in the API (e.g. go1.txt), but was
|
| 251 |
+
// subsequently removed. These are already
|
| 252 |
+
// acknowledged by being in the file
|
| 253 |
+
// "api/except.txt". No need to print them out
|
| 254 |
+
// here.
|
| 255 |
+
} else if portRemoved(feature) {
|
| 256 |
+
// okay.
|
| 257 |
+
} else if featureSet[featureWithoutContext(feature)] {
|
| 258 |
+
// okay.
|
| 259 |
+
} else {
|
| 260 |
+
fmt.Fprintf(w, "-%s\n", feature)
|
| 261 |
+
ok = false // broke compatibility
|
| 262 |
+
}
|
| 263 |
+
case len(required) == 0 || (len(features) > 0 && required[0] > features[0]):
|
| 264 |
+
newFeature := take(&features)
|
| 265 |
+
fmt.Fprintf(w, "+%s\n", newFeature)
|
| 266 |
+
ok = false // feature not in api/next/*
|
| 267 |
+
default:
|
| 268 |
+
take(&required)
|
| 269 |
+
take(&features)
|
| 270 |
+
}
|
| 271 |
+
}
|
| 272 |
+
|
| 273 |
+
return ok
|
| 274 |
+
}
|
| 275 |
+
|
| 276 |
+
// aliasReplacer applies type aliases to earlier API files,
|
| 277 |
+
// to avoid misleading negative results.
|
| 278 |
+
// This makes all the references to os.FileInfo in go1.txt
|
| 279 |
+
// be read as if they said fs.FileInfo, since os.FileInfo is now an alias.
|
| 280 |
+
// If there are many of these, we could do a more general solution,
|
| 281 |
+
// but for now the replacer is fine.
|
| 282 |
+
var aliasReplacer = strings.NewReplacer(
|
| 283 |
+
"os.FileInfo", "fs.FileInfo",
|
| 284 |
+
"os.FileMode", "fs.FileMode",
|
| 285 |
+
"os.PathError", "fs.PathError",
|
| 286 |
+
)
|
| 287 |
+
|
| 288 |
+
func fileFeatures(filename string, needApproval bool) []string {
|
| 289 |
+
bs, err := os.ReadFile(filename)
|
| 290 |
+
if err != nil {
|
| 291 |
+
log.Fatal(err)
|
| 292 |
+
}
|
| 293 |
+
s := string(bs)
|
| 294 |
+
|
| 295 |
+
// Diagnose common mistakes people make,
|
| 296 |
+
// since there is no apifmt to format these files.
|
| 297 |
+
// The missing final newline is important for the
|
| 298 |
+
// final release step of cat next/*.txt >go1.X.txt.
|
| 299 |
+
// If the files don't end in full lines, the concatenation goes awry.
|
| 300 |
+
if strings.Contains(s, "\r") {
|
| 301 |
+
log.Printf("%s: contains CRLFs", filename)
|
| 302 |
+
exitCode = 1
|
| 303 |
+
}
|
| 304 |
+
if filepath.Base(filename) == "go1.4.txt" {
|
| 305 |
+
// No use for blank lines in api files, except go1.4.txt
|
| 306 |
+
// used them in a reasonable way and we should let it be.
|
| 307 |
+
} else if strings.HasPrefix(s, "\n") || strings.Contains(s, "\n\n") {
|
| 308 |
+
log.Printf("%s: contains a blank line", filename)
|
| 309 |
+
exitCode = 1
|
| 310 |
+
}
|
| 311 |
+
if s == "" {
|
| 312 |
+
log.Printf("%s: empty file", filename)
|
| 313 |
+
exitCode = 1
|
| 314 |
+
} else if s[len(s)-1] != '\n' {
|
| 315 |
+
log.Printf("%s: missing final newline", filename)
|
| 316 |
+
exitCode = 1
|
| 317 |
+
}
|
| 318 |
+
s = aliasReplacer.Replace(s)
|
| 319 |
+
lines := strings.Split(s, "\n")
|
| 320 |
+
var nonblank []string
|
| 321 |
+
for i, line := range lines {
|
| 322 |
+
line = strings.TrimSpace(line)
|
| 323 |
+
if line == "" || strings.HasPrefix(line, "#") {
|
| 324 |
+
continue
|
| 325 |
+
}
|
| 326 |
+
if needApproval {
|
| 327 |
+
feature, approval, ok := strings.Cut(line, "#")
|
| 328 |
+
if !ok {
|
| 329 |
+
log.Printf("%s:%d: missing proposal approval\n", filename, i+1)
|
| 330 |
+
exitCode = 1
|
| 331 |
+
} else {
|
| 332 |
+
_, err := strconv.Atoi(approval)
|
| 333 |
+
if err != nil {
|
| 334 |
+
log.Printf("%s:%d: malformed proposal approval #%s\n", filename, i+1, approval)
|
| 335 |
+
exitCode = 1
|
| 336 |
+
}
|
| 337 |
+
}
|
| 338 |
+
line = strings.TrimSpace(feature)
|
| 339 |
+
} else {
|
| 340 |
+
if strings.Contains(line, " #") {
|
| 341 |
+
log.Printf("%s:%d: unexpected approval\n", filename, i+1)
|
| 342 |
+
exitCode = 1
|
| 343 |
+
}
|
| 344 |
+
}
|
| 345 |
+
nonblank = append(nonblank, line)
|
| 346 |
+
}
|
| 347 |
+
return nonblank
|
| 348 |
+
}
|
| 349 |
+
|
| 350 |
+
var fset = token.NewFileSet()
|
| 351 |
+
|
| 352 |
+
type Walker struct {
|
| 353 |
+
context *build.Context
|
| 354 |
+
root string
|
| 355 |
+
scope []string
|
| 356 |
+
current *apiPackage
|
| 357 |
+
deprecated map[token.Pos]bool
|
| 358 |
+
features map[string]bool // set
|
| 359 |
+
imported map[string]*apiPackage // packages already imported
|
| 360 |
+
stdPackages []string // names, omitting "unsafe", internal, and vendored packages
|
| 361 |
+
importMap map[string]map[string]string // importer dir -> import path -> canonical path
|
| 362 |
+
importDir map[string]string // canonical import path -> dir
|
| 363 |
+
|
| 364 |
+
}
|
| 365 |
+
|
| 366 |
+
func NewWalker(context *build.Context, root string) *Walker {
|
| 367 |
+
w := &Walker{
|
| 368 |
+
context: context,
|
| 369 |
+
root: root,
|
| 370 |
+
features: map[string]bool{},
|
| 371 |
+
imported: map[string]*apiPackage{"unsafe": &apiPackage{Package: types.Unsafe}},
|
| 372 |
+
}
|
| 373 |
+
w.loadImports()
|
| 374 |
+
return w
|
| 375 |
+
}
|
| 376 |
+
|
| 377 |
+
func (w *Walker) Features() (fs []string) {
|
| 378 |
+
for f := range w.features {
|
| 379 |
+
fs = append(fs, f)
|
| 380 |
+
}
|
| 381 |
+
slices.Sort(fs)
|
| 382 |
+
return
|
| 383 |
+
}
|
| 384 |
+
|
| 385 |
+
var parsedFileCache = make(map[string]*ast.File)
|
| 386 |
+
|
| 387 |
+
func (w *Walker) parseFile(dir, file string) (*ast.File, error) {
|
| 388 |
+
filename := filepath.Join(dir, file)
|
| 389 |
+
if f := parsedFileCache[filename]; f != nil {
|
| 390 |
+
return f, nil
|
| 391 |
+
}
|
| 392 |
+
|
| 393 |
+
f, err := parser.ParseFile(fset, filename, nil, parser.ParseComments)
|
| 394 |
+
if err != nil {
|
| 395 |
+
return nil, err
|
| 396 |
+
}
|
| 397 |
+
parsedFileCache[filename] = f
|
| 398 |
+
|
| 399 |
+
return f, nil
|
| 400 |
+
}
|
| 401 |
+
|
| 402 |
+
// Disable before debugging non-obvious errors from the type-checker.
|
| 403 |
+
const usePkgCache = true
|
| 404 |
+
|
| 405 |
+
var (
|
| 406 |
+
pkgCache = map[string]*apiPackage{} // map tagKey to package
|
| 407 |
+
pkgTags = map[string][]string{} // map import dir to list of relevant tags
|
| 408 |
+
)
|
| 409 |
+
|
| 410 |
+
// tagKey returns the tag-based key to use in the pkgCache.
|
| 411 |
+
// It is a comma-separated string; the first part is dir, the rest tags.
|
| 412 |
+
// The satisfied tags are derived from context but only those that
|
| 413 |
+
// matter (the ones listed in the tags argument plus GOOS and GOARCH) are used.
|
| 414 |
+
// The tags list, which came from go/build's Package.AllTags,
|
| 415 |
+
// is known to be sorted.
|
| 416 |
+
func tagKey(dir string, context *build.Context, tags []string) string {
|
| 417 |
+
ctags := map[string]bool{
|
| 418 |
+
context.GOOS: true,
|
| 419 |
+
context.GOARCH: true,
|
| 420 |
+
}
|
| 421 |
+
if context.CgoEnabled {
|
| 422 |
+
ctags["cgo"] = true
|
| 423 |
+
}
|
| 424 |
+
for _, tag := range context.BuildTags {
|
| 425 |
+
ctags[tag] = true
|
| 426 |
+
}
|
| 427 |
+
// TODO: ReleaseTags (need to load default)
|
| 428 |
+
key := dir
|
| 429 |
+
|
| 430 |
+
// explicit on GOOS and GOARCH as global cache will use "all" cached packages for
|
| 431 |
+
// an indirect imported package. See https://github.com/golang/go/issues/21181
|
| 432 |
+
// for more detail.
|
| 433 |
+
tags = append(tags, context.GOOS, context.GOARCH)
|
| 434 |
+
slices.Sort(tags)
|
| 435 |
+
|
| 436 |
+
for _, tag := range tags {
|
| 437 |
+
if ctags[tag] {
|
| 438 |
+
key += "," + tag
|
| 439 |
+
ctags[tag] = false
|
| 440 |
+
}
|
| 441 |
+
}
|
| 442 |
+
return key
|
| 443 |
+
}
|
| 444 |
+
|
| 445 |
+
type listImports struct {
|
| 446 |
+
stdPackages []string // names, omitting "unsafe", internal, and vendored packages
|
| 447 |
+
importDir map[string]string // canonical import path → directory
|
| 448 |
+
importMap map[string]map[string]string // import path → canonical import path
|
| 449 |
+
}
|
| 450 |
+
|
| 451 |
+
var listCache sync.Map // map[string]listImports, keyed by contextName
|
| 452 |
+
|
| 453 |
+
// listSem is a semaphore restricting concurrent invocations of 'go list'. 'go
|
| 454 |
+
// list' has its own internal concurrency, so we use a hard-coded constant (to
|
| 455 |
+
// allow the I/O-intensive phases of 'go list' to overlap) instead of scaling
|
| 456 |
+
// all the way up to GOMAXPROCS.
|
| 457 |
+
var listSem = make(chan semToken, 2)
|
| 458 |
+
|
| 459 |
+
type semToken struct{}
|
| 460 |
+
|
| 461 |
+
// loadImports populates w with information about the packages in the standard
|
| 462 |
+
// library and the packages they themselves import in w's build context.
|
| 463 |
+
//
|
| 464 |
+
// The source import path and expanded import path are identical except for vendored packages.
|
| 465 |
+
// For example, on return:
|
| 466 |
+
//
|
| 467 |
+
// w.importMap["math"] = "math"
|
| 468 |
+
// w.importDir["math"] = "<goroot>/src/math"
|
| 469 |
+
//
|
| 470 |
+
// w.importMap["golang.org/x/net/route"] = "vendor/golang.org/x/net/route"
|
| 471 |
+
// w.importDir["vendor/golang.org/x/net/route"] = "<goroot>/src/vendor/golang.org/x/net/route"
|
| 472 |
+
//
|
| 473 |
+
// Since the set of packages that exist depends on context, the result of
|
| 474 |
+
// loadImports also depends on context. However, to improve test running time
|
| 475 |
+
// the configuration for each environment is cached across runs.
|
| 476 |
+
func (w *Walker) loadImports() {
|
| 477 |
+
if w.context == nil {
|
| 478 |
+
return // test-only Walker; does not use the import map
|
| 479 |
+
}
|
| 480 |
+
|
| 481 |
+
name := contextName(w.context)
|
| 482 |
+
|
| 483 |
+
imports, ok := listCache.Load(name)
|
| 484 |
+
if !ok {
|
| 485 |
+
listSem <- semToken{}
|
| 486 |
+
defer func() { <-listSem }()
|
| 487 |
+
|
| 488 |
+
cmd := exec.Command(goCmd(), "list", "-e", "-deps", "-json", "std")
|
| 489 |
+
cmd.Env = listEnv(w.context)
|
| 490 |
+
if w.context.Dir != "" {
|
| 491 |
+
cmd.Dir = w.context.Dir
|
| 492 |
+
}
|
| 493 |
+
cmd.Stderr = os.Stderr
|
| 494 |
+
out, err := cmd.Output()
|
| 495 |
+
if err != nil {
|
| 496 |
+
log.Fatalf("loading imports: %v\n%s", err, out)
|
| 497 |
+
}
|
| 498 |
+
|
| 499 |
+
var stdPackages []string
|
| 500 |
+
importMap := make(map[string]map[string]string)
|
| 501 |
+
importDir := make(map[string]string)
|
| 502 |
+
dec := json.NewDecoder(bytes.NewReader(out))
|
| 503 |
+
for {
|
| 504 |
+
var pkg struct {
|
| 505 |
+
ImportPath, Dir string
|
| 506 |
+
ImportMap map[string]string
|
| 507 |
+
Standard bool
|
| 508 |
+
}
|
| 509 |
+
err := dec.Decode(&pkg)
|
| 510 |
+
if err == io.EOF {
|
| 511 |
+
break
|
| 512 |
+
}
|
| 513 |
+
if err != nil {
|
| 514 |
+
log.Fatalf("go list: invalid output: %v", err)
|
| 515 |
+
}
|
| 516 |
+
|
| 517 |
+
// - Package "unsafe" contains special signatures requiring
|
| 518 |
+
// extra care when printing them - ignore since it is not
|
| 519 |
+
// going to change w/o a language change.
|
| 520 |
+
// - Internal and vendored packages do not contribute to our
|
| 521 |
+
// API surface. (If we are running within the "std" module,
|
| 522 |
+
// vendored dependencies appear as themselves instead of
|
| 523 |
+
// their "vendor/" standard-library copies.)
|
| 524 |
+
// - 'go list std' does not include commands, which cannot be
|
| 525 |
+
// imported anyway.
|
| 526 |
+
if ip := pkg.ImportPath; pkg.Standard && ip != "unsafe" && !strings.HasPrefix(ip, "vendor/") && !internalPkg.MatchString(ip) {
|
| 527 |
+
stdPackages = append(stdPackages, ip)
|
| 528 |
+
}
|
| 529 |
+
importDir[pkg.ImportPath] = pkg.Dir
|
| 530 |
+
if len(pkg.ImportMap) > 0 {
|
| 531 |
+
importMap[pkg.Dir] = make(map[string]string, len(pkg.ImportMap))
|
| 532 |
+
}
|
| 533 |
+
for k, v := range pkg.ImportMap {
|
| 534 |
+
importMap[pkg.Dir][k] = v
|
| 535 |
+
}
|
| 536 |
+
}
|
| 537 |
+
|
| 538 |
+
slices.Sort(stdPackages)
|
| 539 |
+
imports = listImports{
|
| 540 |
+
stdPackages: stdPackages,
|
| 541 |
+
importMap: importMap,
|
| 542 |
+
importDir: importDir,
|
| 543 |
+
}
|
| 544 |
+
imports, _ = listCache.LoadOrStore(name, imports)
|
| 545 |
+
}
|
| 546 |
+
|
| 547 |
+
li := imports.(listImports)
|
| 548 |
+
w.stdPackages = li.stdPackages
|
| 549 |
+
w.importDir = li.importDir
|
| 550 |
+
w.importMap = li.importMap
|
| 551 |
+
}
|
| 552 |
+
|
| 553 |
+
// listEnv returns the process environment to use when invoking 'go list' for
|
| 554 |
+
// the given context.
|
| 555 |
+
func listEnv(c *build.Context) []string {
|
| 556 |
+
if c == nil {
|
| 557 |
+
return os.Environ()
|
| 558 |
+
}
|
| 559 |
+
|
| 560 |
+
environ := append(os.Environ(),
|
| 561 |
+
"GOOS="+c.GOOS,
|
| 562 |
+
"GOARCH="+c.GOARCH)
|
| 563 |
+
if c.CgoEnabled {
|
| 564 |
+
environ = append(environ, "CGO_ENABLED=1")
|
| 565 |
+
} else {
|
| 566 |
+
environ = append(environ, "CGO_ENABLED=0")
|
| 567 |
+
}
|
| 568 |
+
return environ
|
| 569 |
+
}
|
| 570 |
+
|
| 571 |
+
type apiPackage struct {
|
| 572 |
+
*types.Package
|
| 573 |
+
Files []*ast.File
|
| 574 |
+
}
|
| 575 |
+
|
| 576 |
+
// Importing is a sentinel taking the place in Walker.imported
|
| 577 |
+
// for a package that is in the process of being imported.
|
| 578 |
+
var importing apiPackage
|
| 579 |
+
|
| 580 |
+
// Import implements types.Importer.
|
| 581 |
+
func (w *Walker) Import(name string) (*types.Package, error) {
|
| 582 |
+
return w.ImportFrom(name, "", 0)
|
| 583 |
+
}
|
| 584 |
+
|
| 585 |
+
// ImportFrom implements types.ImporterFrom.
|
| 586 |
+
func (w *Walker) ImportFrom(fromPath, fromDir string, mode types.ImportMode) (*types.Package, error) {
|
| 587 |
+
pkg, err := w.importFrom(fromPath, fromDir, mode)
|
| 588 |
+
if err != nil {
|
| 589 |
+
return nil, err
|
| 590 |
+
}
|
| 591 |
+
return pkg.Package, nil
|
| 592 |
+
}
|
| 593 |
+
|
| 594 |
+
func (w *Walker) import_(name string) (*apiPackage, error) {
|
| 595 |
+
return w.importFrom(name, "", 0)
|
| 596 |
+
}
|
| 597 |
+
|
| 598 |
+
func (w *Walker) importFrom(fromPath, fromDir string, mode types.ImportMode) (*apiPackage, error) {
|
| 599 |
+
name := fromPath
|
| 600 |
+
if canonical, ok := w.importMap[fromDir][fromPath]; ok {
|
| 601 |
+
name = canonical
|
| 602 |
+
}
|
| 603 |
+
|
| 604 |
+
pkg := w.imported[name]
|
| 605 |
+
if pkg != nil {
|
| 606 |
+
if pkg == &importing {
|
| 607 |
+
log.Fatalf("cycle importing package %q", name)
|
| 608 |
+
}
|
| 609 |
+
return pkg, nil
|
| 610 |
+
}
|
| 611 |
+
w.imported[name] = &importing
|
| 612 |
+
|
| 613 |
+
// Determine package files.
|
| 614 |
+
dir := w.importDir[name]
|
| 615 |
+
if dir == "" {
|
| 616 |
+
dir = filepath.Join(w.root, filepath.FromSlash(name))
|
| 617 |
+
}
|
| 618 |
+
if fi, err := os.Stat(dir); err != nil || !fi.IsDir() {
|
| 619 |
+
log.Panicf("no source in tree for import %q (from import %s in %s): %v", name, fromPath, fromDir, err)
|
| 620 |
+
}
|
| 621 |
+
|
| 622 |
+
context := w.context
|
| 623 |
+
if context == nil {
|
| 624 |
+
context = &build.Default
|
| 625 |
+
}
|
| 626 |
+
|
| 627 |
+
// Look in cache.
|
| 628 |
+
// If we've already done an import with the same set
|
| 629 |
+
// of relevant tags, reuse the result.
|
| 630 |
+
var key string
|
| 631 |
+
if usePkgCache {
|
| 632 |
+
if tags, ok := pkgTags[dir]; ok {
|
| 633 |
+
key = tagKey(dir, context, tags)
|
| 634 |
+
if pkg := pkgCache[key]; pkg != nil {
|
| 635 |
+
w.imported[name] = pkg
|
| 636 |
+
return pkg, nil
|
| 637 |
+
}
|
| 638 |
+
}
|
| 639 |
+
}
|
| 640 |
+
|
| 641 |
+
info, err := context.ImportDir(dir, 0)
|
| 642 |
+
if err != nil {
|
| 643 |
+
if _, nogo := err.(*build.NoGoError); nogo {
|
| 644 |
+
return nil, err
|
| 645 |
+
}
|
| 646 |
+
log.Fatalf("pkg %q, dir %q: ScanDir: %v", name, dir, err)
|
| 647 |
+
}
|
| 648 |
+
|
| 649 |
+
// Save tags list first time we see a directory.
|
| 650 |
+
if usePkgCache {
|
| 651 |
+
if _, ok := pkgTags[dir]; !ok {
|
| 652 |
+
pkgTags[dir] = info.AllTags
|
| 653 |
+
key = tagKey(dir, context, info.AllTags)
|
| 654 |
+
}
|
| 655 |
+
}
|
| 656 |
+
|
| 657 |
+
filenames := append(append([]string{}, info.GoFiles...), info.CgoFiles...)
|
| 658 |
+
|
| 659 |
+
// Parse package files.
|
| 660 |
+
var files []*ast.File
|
| 661 |
+
for _, file := range filenames {
|
| 662 |
+
f, err := w.parseFile(dir, file)
|
| 663 |
+
if err != nil {
|
| 664 |
+
log.Fatalf("error parsing package %s: %s", name, err)
|
| 665 |
+
}
|
| 666 |
+
files = append(files, f)
|
| 667 |
+
}
|
| 668 |
+
|
| 669 |
+
// Type-check package files.
|
| 670 |
+
var sizes types.Sizes
|
| 671 |
+
if w.context != nil {
|
| 672 |
+
sizes = types.SizesFor(w.context.Compiler, w.context.GOARCH)
|
| 673 |
+
}
|
| 674 |
+
conf := types.Config{
|
| 675 |
+
IgnoreFuncBodies: true,
|
| 676 |
+
FakeImportC: true,
|
| 677 |
+
Importer: w,
|
| 678 |
+
Sizes: sizes,
|
| 679 |
+
}
|
| 680 |
+
tpkg, err := conf.Check(name, fset, files, nil)
|
| 681 |
+
if err != nil {
|
| 682 |
+
ctxt := "<no context>"
|
| 683 |
+
if w.context != nil {
|
| 684 |
+
ctxt = fmt.Sprintf("%s-%s", w.context.GOOS, w.context.GOARCH)
|
| 685 |
+
}
|
| 686 |
+
log.Fatalf("error typechecking package %s: %s (%s)", name, err, ctxt)
|
| 687 |
+
}
|
| 688 |
+
pkg = &apiPackage{tpkg, files}
|
| 689 |
+
|
| 690 |
+
if usePkgCache {
|
| 691 |
+
pkgCache[key] = pkg
|
| 692 |
+
}
|
| 693 |
+
|
| 694 |
+
w.imported[name] = pkg
|
| 695 |
+
return pkg, nil
|
| 696 |
+
}
|
| 697 |
+
|
| 698 |
+
// pushScope enters a new scope (walking a package, type, node, etc)
|
| 699 |
+
// and returns a function that will leave the scope (with sanity checking
|
| 700 |
+
// for mismatched pushes & pops)
|
| 701 |
+
func (w *Walker) pushScope(name string) (popFunc func()) {
|
| 702 |
+
w.scope = append(w.scope, name)
|
| 703 |
+
return func() {
|
| 704 |
+
if len(w.scope) == 0 {
|
| 705 |
+
log.Fatalf("attempt to leave scope %q with empty scope list", name)
|
| 706 |
+
}
|
| 707 |
+
if w.scope[len(w.scope)-1] != name {
|
| 708 |
+
log.Fatalf("attempt to leave scope %q, but scope is currently %#v", name, w.scope)
|
| 709 |
+
}
|
| 710 |
+
w.scope = w.scope[:len(w.scope)-1]
|
| 711 |
+
}
|
| 712 |
+
}
|
| 713 |
+
|
| 714 |
+
func sortedMethodNames(typ *types.Interface) []string {
|
| 715 |
+
n := typ.NumMethods()
|
| 716 |
+
list := make([]string, n)
|
| 717 |
+
for i := range list {
|
| 718 |
+
list[i] = typ.Method(i).Name()
|
| 719 |
+
}
|
| 720 |
+
slices.Sort(list)
|
| 721 |
+
return list
|
| 722 |
+
}
|
| 723 |
+
|
| 724 |
+
// sortedEmbeddeds returns constraint types embedded in an
|
| 725 |
+
// interface. It does not include embedded interface types or methods.
|
| 726 |
+
func (w *Walker) sortedEmbeddeds(typ *types.Interface) []string {
|
| 727 |
+
n := typ.NumEmbeddeds()
|
| 728 |
+
list := make([]string, 0, n)
|
| 729 |
+
for i := 0; i < n; i++ {
|
| 730 |
+
emb := typ.EmbeddedType(i)
|
| 731 |
+
switch emb := emb.(type) {
|
| 732 |
+
case *types.Interface:
|
| 733 |
+
list = append(list, w.sortedEmbeddeds(emb)...)
|
| 734 |
+
case *types.Union:
|
| 735 |
+
var buf bytes.Buffer
|
| 736 |
+
nu := emb.Len()
|
| 737 |
+
for i := 0; i < nu; i++ {
|
| 738 |
+
if i > 0 {
|
| 739 |
+
buf.WriteString(" | ")
|
| 740 |
+
}
|
| 741 |
+
term := emb.Term(i)
|
| 742 |
+
if term.Tilde() {
|
| 743 |
+
buf.WriteByte('~')
|
| 744 |
+
}
|
| 745 |
+
w.writeType(&buf, term.Type())
|
| 746 |
+
}
|
| 747 |
+
list = append(list, buf.String())
|
| 748 |
+
}
|
| 749 |
+
}
|
| 750 |
+
slices.Sort(list)
|
| 751 |
+
return list
|
| 752 |
+
}
|
| 753 |
+
|
| 754 |
+
func (w *Walker) writeType(buf *bytes.Buffer, typ types.Type) {
|
| 755 |
+
switch typ := typ.(type) {
|
| 756 |
+
case *types.Basic:
|
| 757 |
+
s := typ.Name()
|
| 758 |
+
switch typ.Kind() {
|
| 759 |
+
case types.UnsafePointer:
|
| 760 |
+
s = "unsafe.Pointer"
|
| 761 |
+
case types.UntypedBool:
|
| 762 |
+
s = "ideal-bool"
|
| 763 |
+
case types.UntypedInt:
|
| 764 |
+
s = "ideal-int"
|
| 765 |
+
case types.UntypedRune:
|
| 766 |
+
// "ideal-char" for compatibility with old tool
|
| 767 |
+
// TODO(gri) change to "ideal-rune"
|
| 768 |
+
s = "ideal-char"
|
| 769 |
+
case types.UntypedFloat:
|
| 770 |
+
s = "ideal-float"
|
| 771 |
+
case types.UntypedComplex:
|
| 772 |
+
s = "ideal-complex"
|
| 773 |
+
case types.UntypedString:
|
| 774 |
+
s = "ideal-string"
|
| 775 |
+
case types.UntypedNil:
|
| 776 |
+
panic("should never see untyped nil type")
|
| 777 |
+
default:
|
| 778 |
+
switch s {
|
| 779 |
+
case "byte":
|
| 780 |
+
s = "uint8"
|
| 781 |
+
case "rune":
|
| 782 |
+
s = "int32"
|
| 783 |
+
}
|
| 784 |
+
}
|
| 785 |
+
buf.WriteString(s)
|
| 786 |
+
|
| 787 |
+
case *types.Array:
|
| 788 |
+
fmt.Fprintf(buf, "[%d]", typ.Len())
|
| 789 |
+
w.writeType(buf, typ.Elem())
|
| 790 |
+
|
| 791 |
+
case *types.Slice:
|
| 792 |
+
buf.WriteString("[]")
|
| 793 |
+
w.writeType(buf, typ.Elem())
|
| 794 |
+
|
| 795 |
+
case *types.Struct:
|
| 796 |
+
buf.WriteString("struct")
|
| 797 |
+
|
| 798 |
+
case *types.Pointer:
|
| 799 |
+
buf.WriteByte('*')
|
| 800 |
+
w.writeType(buf, typ.Elem())
|
| 801 |
+
|
| 802 |
+
case *types.Tuple:
|
| 803 |
+
panic("should never see a tuple type")
|
| 804 |
+
|
| 805 |
+
case *types.Signature:
|
| 806 |
+
buf.WriteString("func")
|
| 807 |
+
w.writeSignature(buf, typ)
|
| 808 |
+
|
| 809 |
+
case *types.Interface:
|
| 810 |
+
buf.WriteString("interface{")
|
| 811 |
+
if typ.NumMethods() > 0 || typ.NumEmbeddeds() > 0 {
|
| 812 |
+
buf.WriteByte(' ')
|
| 813 |
+
}
|
| 814 |
+
if typ.NumMethods() > 0 {
|
| 815 |
+
buf.WriteString(strings.Join(sortedMethodNames(typ), ", "))
|
| 816 |
+
}
|
| 817 |
+
if typ.NumEmbeddeds() > 0 {
|
| 818 |
+
buf.WriteString(strings.Join(w.sortedEmbeddeds(typ), ", "))
|
| 819 |
+
}
|
| 820 |
+
if typ.NumMethods() > 0 || typ.NumEmbeddeds() > 0 {
|
| 821 |
+
buf.WriteByte(' ')
|
| 822 |
+
}
|
| 823 |
+
buf.WriteString("}")
|
| 824 |
+
|
| 825 |
+
case *types.Map:
|
| 826 |
+
buf.WriteString("map[")
|
| 827 |
+
w.writeType(buf, typ.Key())
|
| 828 |
+
buf.WriteByte(']')
|
| 829 |
+
w.writeType(buf, typ.Elem())
|
| 830 |
+
|
| 831 |
+
case *types.Chan:
|
| 832 |
+
var s string
|
| 833 |
+
switch typ.Dir() {
|
| 834 |
+
case types.SendOnly:
|
| 835 |
+
s = "chan<- "
|
| 836 |
+
case types.RecvOnly:
|
| 837 |
+
s = "<-chan "
|
| 838 |
+
case types.SendRecv:
|
| 839 |
+
s = "chan "
|
| 840 |
+
default:
|
| 841 |
+
panic("unreachable")
|
| 842 |
+
}
|
| 843 |
+
buf.WriteString(s)
|
| 844 |
+
w.writeType(buf, typ.Elem())
|
| 845 |
+
|
| 846 |
+
case *types.Alias:
|
| 847 |
+
w.writeType(buf, types.Unalias(typ))
|
| 848 |
+
|
| 849 |
+
case *types.Named:
|
| 850 |
+
obj := typ.Obj()
|
| 851 |
+
pkg := obj.Pkg()
|
| 852 |
+
if pkg != nil && pkg != w.current.Package {
|
| 853 |
+
buf.WriteString(pkg.Name())
|
| 854 |
+
buf.WriteByte('.')
|
| 855 |
+
}
|
| 856 |
+
buf.WriteString(typ.Obj().Name())
|
| 857 |
+
if targs := typ.TypeArgs(); targs.Len() > 0 {
|
| 858 |
+
buf.WriteByte('[')
|
| 859 |
+
for i := 0; i < targs.Len(); i++ {
|
| 860 |
+
if i > 0 {
|
| 861 |
+
buf.WriteString(", ")
|
| 862 |
+
}
|
| 863 |
+
w.writeType(buf, targs.At(i))
|
| 864 |
+
}
|
| 865 |
+
buf.WriteByte(']')
|
| 866 |
+
}
|
| 867 |
+
|
| 868 |
+
case *types.TypeParam:
|
| 869 |
+
// Type parameter names may change, so use a placeholder instead.
|
| 870 |
+
fmt.Fprintf(buf, "$%d", typ.Index())
|
| 871 |
+
|
| 872 |
+
default:
|
| 873 |
+
panic(fmt.Sprintf("unknown type %T", typ))
|
| 874 |
+
}
|
| 875 |
+
}
|
| 876 |
+
|
| 877 |
+
func (w *Walker) writeSignature(buf *bytes.Buffer, sig *types.Signature) {
|
| 878 |
+
if tparams := sig.TypeParams(); tparams != nil {
|
| 879 |
+
w.writeTypeParams(buf, tparams, true)
|
| 880 |
+
}
|
| 881 |
+
w.writeParams(buf, sig.Params(), sig.Variadic())
|
| 882 |
+
switch res := sig.Results(); res.Len() {
|
| 883 |
+
case 0:
|
| 884 |
+
// nothing to do
|
| 885 |
+
case 1:
|
| 886 |
+
buf.WriteByte(' ')
|
| 887 |
+
w.writeType(buf, res.At(0).Type())
|
| 888 |
+
default:
|
| 889 |
+
buf.WriteByte(' ')
|
| 890 |
+
w.writeParams(buf, res, false)
|
| 891 |
+
}
|
| 892 |
+
}
|
| 893 |
+
|
| 894 |
+
func (w *Walker) writeTypeParams(buf *bytes.Buffer, tparams *types.TypeParamList, withConstraints bool) {
|
| 895 |
+
buf.WriteByte('[')
|
| 896 |
+
c := tparams.Len()
|
| 897 |
+
for i := 0; i < c; i++ {
|
| 898 |
+
if i > 0 {
|
| 899 |
+
buf.WriteString(", ")
|
| 900 |
+
}
|
| 901 |
+
tp := tparams.At(i)
|
| 902 |
+
w.writeType(buf, tp)
|
| 903 |
+
if withConstraints {
|
| 904 |
+
buf.WriteByte(' ')
|
| 905 |
+
w.writeType(buf, tp.Constraint())
|
| 906 |
+
}
|
| 907 |
+
}
|
| 908 |
+
buf.WriteByte(']')
|
| 909 |
+
}
|
| 910 |
+
|
| 911 |
+
func (w *Walker) writeParams(buf *bytes.Buffer, t *types.Tuple, variadic bool) {
|
| 912 |
+
buf.WriteByte('(')
|
| 913 |
+
for i, n := 0, t.Len(); i < n; i++ {
|
| 914 |
+
if i > 0 {
|
| 915 |
+
buf.WriteString(", ")
|
| 916 |
+
}
|
| 917 |
+
typ := t.At(i).Type()
|
| 918 |
+
if variadic && i+1 == n {
|
| 919 |
+
buf.WriteString("...")
|
| 920 |
+
typ = typ.(*types.Slice).Elem()
|
| 921 |
+
}
|
| 922 |
+
w.writeType(buf, typ)
|
| 923 |
+
}
|
| 924 |
+
buf.WriteByte(')')
|
| 925 |
+
}
|
| 926 |
+
|
| 927 |
+
func (w *Walker) typeString(typ types.Type) string {
|
| 928 |
+
var buf bytes.Buffer
|
| 929 |
+
w.writeType(&buf, typ)
|
| 930 |
+
return buf.String()
|
| 931 |
+
}
|
| 932 |
+
|
| 933 |
+
func (w *Walker) signatureString(sig *types.Signature) string {
|
| 934 |
+
var buf bytes.Buffer
|
| 935 |
+
w.writeSignature(&buf, sig)
|
| 936 |
+
return buf.String()
|
| 937 |
+
}
|
| 938 |
+
|
| 939 |
+
func (w *Walker) emitObj(obj types.Object) {
|
| 940 |
+
switch obj := obj.(type) {
|
| 941 |
+
case *types.Const:
|
| 942 |
+
if w.isDeprecated(obj) {
|
| 943 |
+
w.emitf("const %s //deprecated", obj.Name())
|
| 944 |
+
}
|
| 945 |
+
w.emitf("const %s %s", obj.Name(), w.typeString(obj.Type()))
|
| 946 |
+
x := obj.Val()
|
| 947 |
+
short := x.String()
|
| 948 |
+
exact := x.ExactString()
|
| 949 |
+
if short == exact {
|
| 950 |
+
w.emitf("const %s = %s", obj.Name(), short)
|
| 951 |
+
} else {
|
| 952 |
+
w.emitf("const %s = %s // %s", obj.Name(), short, exact)
|
| 953 |
+
}
|
| 954 |
+
case *types.Var:
|
| 955 |
+
if w.isDeprecated(obj) {
|
| 956 |
+
w.emitf("var %s //deprecated", obj.Name())
|
| 957 |
+
}
|
| 958 |
+
w.emitf("var %s %s", obj.Name(), w.typeString(obj.Type()))
|
| 959 |
+
case *types.TypeName:
|
| 960 |
+
w.emitType(obj)
|
| 961 |
+
case *types.Func:
|
| 962 |
+
w.emitFunc(obj)
|
| 963 |
+
default:
|
| 964 |
+
panic("unknown object: " + obj.String())
|
| 965 |
+
}
|
| 966 |
+
}
|
| 967 |
+
|
| 968 |
+
func (w *Walker) emitType(obj *types.TypeName) {
|
| 969 |
+
name := obj.Name()
|
| 970 |
+
if w.isDeprecated(obj) {
|
| 971 |
+
w.emitf("type %s //deprecated", name)
|
| 972 |
+
}
|
| 973 |
+
typ := obj.Type()
|
| 974 |
+
if obj.IsAlias() {
|
| 975 |
+
w.emitf("type %s = %s", name, w.typeString(typ))
|
| 976 |
+
return
|
| 977 |
+
}
|
| 978 |
+
if tparams := obj.Type().(*types.Named).TypeParams(); tparams != nil {
|
| 979 |
+
var buf bytes.Buffer
|
| 980 |
+
buf.WriteString(name)
|
| 981 |
+
w.writeTypeParams(&buf, tparams, true)
|
| 982 |
+
name = buf.String()
|
| 983 |
+
}
|
| 984 |
+
switch typ := typ.Underlying().(type) {
|
| 985 |
+
case *types.Struct:
|
| 986 |
+
w.emitStructType(name, typ)
|
| 987 |
+
case *types.Interface:
|
| 988 |
+
w.emitIfaceType(name, typ)
|
| 989 |
+
return // methods are handled by emitIfaceType
|
| 990 |
+
default:
|
| 991 |
+
w.emitf("type %s %s", name, w.typeString(typ.Underlying()))
|
| 992 |
+
}
|
| 993 |
+
|
| 994 |
+
// emit methods with value receiver
|
| 995 |
+
var methodNames map[string]bool
|
| 996 |
+
vset := types.NewMethodSet(typ)
|
| 997 |
+
for i, n := 0, vset.Len(); i < n; i++ {
|
| 998 |
+
m := vset.At(i)
|
| 999 |
+
if m.Obj().Exported() {
|
| 1000 |
+
w.emitMethod(m)
|
| 1001 |
+
if methodNames == nil {
|
| 1002 |
+
methodNames = make(map[string]bool)
|
| 1003 |
+
}
|
| 1004 |
+
methodNames[m.Obj().Name()] = true
|
| 1005 |
+
}
|
| 1006 |
+
}
|
| 1007 |
+
|
| 1008 |
+
// emit methods with pointer receiver; exclude
|
| 1009 |
+
// methods that we have emitted already
|
| 1010 |
+
// (the method set of *T includes the methods of T)
|
| 1011 |
+
pset := types.NewMethodSet(types.NewPointer(typ))
|
| 1012 |
+
for i, n := 0, pset.Len(); i < n; i++ {
|
| 1013 |
+
m := pset.At(i)
|
| 1014 |
+
if m.Obj().Exported() && !methodNames[m.Obj().Name()] {
|
| 1015 |
+
w.emitMethod(m)
|
| 1016 |
+
}
|
| 1017 |
+
}
|
| 1018 |
+
}
|
| 1019 |
+
|
| 1020 |
+
func (w *Walker) emitStructType(name string, typ *types.Struct) {
|
| 1021 |
+
typeStruct := fmt.Sprintf("type %s struct", name)
|
| 1022 |
+
w.emitf("%s", typeStruct)
|
| 1023 |
+
defer w.pushScope(typeStruct)()
|
| 1024 |
+
|
| 1025 |
+
for i := 0; i < typ.NumFields(); i++ {
|
| 1026 |
+
f := typ.Field(i)
|
| 1027 |
+
if !f.Exported() {
|
| 1028 |
+
continue
|
| 1029 |
+
}
|
| 1030 |
+
typ := f.Type()
|
| 1031 |
+
if f.Anonymous() {
|
| 1032 |
+
if w.isDeprecated(f) {
|
| 1033 |
+
w.emitf("embedded %s //deprecated", w.typeString(typ))
|
| 1034 |
+
}
|
| 1035 |
+
w.emitf("embedded %s", w.typeString(typ))
|
| 1036 |
+
continue
|
| 1037 |
+
}
|
| 1038 |
+
if w.isDeprecated(f) {
|
| 1039 |
+
w.emitf("%s //deprecated", f.Name())
|
| 1040 |
+
}
|
| 1041 |
+
w.emitf("%s %s", f.Name(), w.typeString(typ))
|
| 1042 |
+
}
|
| 1043 |
+
}
|
| 1044 |
+
|
| 1045 |
+
func (w *Walker) emitIfaceType(name string, typ *types.Interface) {
|
| 1046 |
+
pop := w.pushScope("type " + name + " interface")
|
| 1047 |
+
|
| 1048 |
+
var methodNames []string
|
| 1049 |
+
complete := true
|
| 1050 |
+
mset := types.NewMethodSet(typ)
|
| 1051 |
+
for i, n := 0, mset.Len(); i < n; i++ {
|
| 1052 |
+
m := mset.At(i).Obj().(*types.Func)
|
| 1053 |
+
if !m.Exported() {
|
| 1054 |
+
complete = false
|
| 1055 |
+
continue
|
| 1056 |
+
}
|
| 1057 |
+
methodNames = append(methodNames, m.Name())
|
| 1058 |
+
if w.isDeprecated(m) {
|
| 1059 |
+
w.emitf("%s //deprecated", m.Name())
|
| 1060 |
+
}
|
| 1061 |
+
w.emitf("%s%s", m.Name(), w.signatureString(m.Signature()))
|
| 1062 |
+
}
|
| 1063 |
+
|
| 1064 |
+
if !complete {
|
| 1065 |
+
// The method set has unexported methods, so all the
|
| 1066 |
+
// implementations are provided by the same package,
|
| 1067 |
+
// so the method set can be extended. Instead of recording
|
| 1068 |
+
// the full set of names (below), record only that there were
|
| 1069 |
+
// unexported methods. (If the interface shrinks, we will notice
|
| 1070 |
+
// because a method signature emitted during the last loop
|
| 1071 |
+
// will disappear.)
|
| 1072 |
+
w.emitf("unexported methods")
|
| 1073 |
+
}
|
| 1074 |
+
|
| 1075 |
+
pop()
|
| 1076 |
+
|
| 1077 |
+
if !complete {
|
| 1078 |
+
return
|
| 1079 |
+
}
|
| 1080 |
+
|
| 1081 |
+
if len(methodNames) == 0 {
|
| 1082 |
+
w.emitf("type %s interface {}", name)
|
| 1083 |
+
return
|
| 1084 |
+
}
|
| 1085 |
+
|
| 1086 |
+
slices.Sort(methodNames)
|
| 1087 |
+
w.emitf("type %s interface { %s }", name, strings.Join(methodNames, ", "))
|
| 1088 |
+
}
|
| 1089 |
+
|
| 1090 |
+
func (w *Walker) emitFunc(f *types.Func) {
|
| 1091 |
+
sig := f.Signature()
|
| 1092 |
+
if sig.Recv() != nil {
|
| 1093 |
+
panic("method considered a regular function: " + f.String())
|
| 1094 |
+
}
|
| 1095 |
+
if w.isDeprecated(f) {
|
| 1096 |
+
w.emitf("func %s //deprecated", f.Name())
|
| 1097 |
+
}
|
| 1098 |
+
w.emitf("func %s%s", f.Name(), w.signatureString(sig))
|
| 1099 |
+
}
|
| 1100 |
+
|
| 1101 |
+
func (w *Walker) emitMethod(m *types.Selection) {
|
| 1102 |
+
sig := m.Type().(*types.Signature)
|
| 1103 |
+
recv := sig.Recv().Type()
|
| 1104 |
+
// report exported methods with unexported receiver base type
|
| 1105 |
+
if true {
|
| 1106 |
+
base := recv
|
| 1107 |
+
if p, _ := recv.(*types.Pointer); p != nil {
|
| 1108 |
+
base = p.Elem()
|
| 1109 |
+
}
|
| 1110 |
+
if obj := base.(*types.Named).Obj(); !obj.Exported() {
|
| 1111 |
+
log.Fatalf("exported method with unexported receiver base type: %s", m)
|
| 1112 |
+
}
|
| 1113 |
+
}
|
| 1114 |
+
tps := ""
|
| 1115 |
+
if rtp := sig.RecvTypeParams(); rtp != nil {
|
| 1116 |
+
var buf bytes.Buffer
|
| 1117 |
+
w.writeTypeParams(&buf, rtp, false)
|
| 1118 |
+
tps = buf.String()
|
| 1119 |
+
}
|
| 1120 |
+
if w.isDeprecated(m.Obj()) {
|
| 1121 |
+
w.emitf("method (%s%s) %s //deprecated", w.typeString(recv), tps, m.Obj().Name())
|
| 1122 |
+
}
|
| 1123 |
+
w.emitf("method (%s%s) %s%s", w.typeString(recv), tps, m.Obj().Name(), w.signatureString(sig))
|
| 1124 |
+
}
|
| 1125 |
+
|
| 1126 |
+
func (w *Walker) emitf(format string, args ...any) {
|
| 1127 |
+
f := strings.Join(w.scope, ", ") + ", " + fmt.Sprintf(format, args...)
|
| 1128 |
+
if strings.Contains(f, "\n") {
|
| 1129 |
+
panic("feature contains newlines: " + f)
|
| 1130 |
+
}
|
| 1131 |
+
|
| 1132 |
+
if _, dup := w.features[f]; dup {
|
| 1133 |
+
panic("duplicate feature inserted: " + f)
|
| 1134 |
+
}
|
| 1135 |
+
w.features[f] = true
|
| 1136 |
+
|
| 1137 |
+
if verbose {
|
| 1138 |
+
log.Printf("feature: %s", f)
|
| 1139 |
+
}
|
| 1140 |
+
}
|
| 1141 |
+
|
| 1142 |
+
func needApproval(filename string) bool {
|
| 1143 |
+
name := filepath.Base(filename)
|
| 1144 |
+
if name == "go1.txt" {
|
| 1145 |
+
return false
|
| 1146 |
+
}
|
| 1147 |
+
minor := strings.TrimSuffix(strings.TrimPrefix(name, "go1."), ".txt")
|
| 1148 |
+
n, err := strconv.Atoi(minor)
|
| 1149 |
+
if err != nil {
|
| 1150 |
+
log.Fatalf("unexpected api file: %v", name)
|
| 1151 |
+
}
|
| 1152 |
+
return n >= 19 // started tracking approvals in Go 1.19
|
| 1153 |
+
}
|
| 1154 |
+
|
| 1155 |
+
func (w *Walker) collectDeprecated() {
|
| 1156 |
+
isDeprecated := func(doc *ast.CommentGroup) bool {
|
| 1157 |
+
if doc != nil {
|
| 1158 |
+
for _, c := range doc.List {
|
| 1159 |
+
if strings.HasPrefix(c.Text, "// Deprecated:") {
|
| 1160 |
+
return true
|
| 1161 |
+
}
|
| 1162 |
+
}
|
| 1163 |
+
}
|
| 1164 |
+
return false
|
| 1165 |
+
}
|
| 1166 |
+
|
| 1167 |
+
w.deprecated = make(map[token.Pos]bool)
|
| 1168 |
+
mark := func(id *ast.Ident) {
|
| 1169 |
+
if id != nil {
|
| 1170 |
+
w.deprecated[id.Pos()] = true
|
| 1171 |
+
}
|
| 1172 |
+
}
|
| 1173 |
+
for _, file := range w.current.Files {
|
| 1174 |
+
ast.Inspect(file, func(n ast.Node) bool {
|
| 1175 |
+
switch n := n.(type) {
|
| 1176 |
+
case *ast.File:
|
| 1177 |
+
if isDeprecated(n.Doc) {
|
| 1178 |
+
mark(n.Name)
|
| 1179 |
+
}
|
| 1180 |
+
return true
|
| 1181 |
+
case *ast.GenDecl:
|
| 1182 |
+
if isDeprecated(n.Doc) {
|
| 1183 |
+
for _, spec := range n.Specs {
|
| 1184 |
+
switch spec := spec.(type) {
|
| 1185 |
+
case *ast.ValueSpec:
|
| 1186 |
+
for _, id := range spec.Names {
|
| 1187 |
+
mark(id)
|
| 1188 |
+
}
|
| 1189 |
+
case *ast.TypeSpec:
|
| 1190 |
+
mark(spec.Name)
|
| 1191 |
+
}
|
| 1192 |
+
}
|
| 1193 |
+
}
|
| 1194 |
+
return true // look at specs
|
| 1195 |
+
case *ast.FuncDecl:
|
| 1196 |
+
if isDeprecated(n.Doc) {
|
| 1197 |
+
mark(n.Name)
|
| 1198 |
+
}
|
| 1199 |
+
return false
|
| 1200 |
+
case *ast.TypeSpec:
|
| 1201 |
+
if isDeprecated(n.Doc) {
|
| 1202 |
+
mark(n.Name)
|
| 1203 |
+
}
|
| 1204 |
+
return true // recurse into struct or interface type
|
| 1205 |
+
case *ast.StructType:
|
| 1206 |
+
return true // recurse into fields
|
| 1207 |
+
case *ast.InterfaceType:
|
| 1208 |
+
return true // recurse into methods
|
| 1209 |
+
case *ast.FieldList:
|
| 1210 |
+
return true // recurse into fields
|
| 1211 |
+
case *ast.ValueSpec:
|
| 1212 |
+
if isDeprecated(n.Doc) {
|
| 1213 |
+
for _, id := range n.Names {
|
| 1214 |
+
mark(id)
|
| 1215 |
+
}
|
| 1216 |
+
}
|
| 1217 |
+
return false
|
| 1218 |
+
case *ast.Field:
|
| 1219 |
+
if isDeprecated(n.Doc) {
|
| 1220 |
+
for _, id := range n.Names {
|
| 1221 |
+
mark(id)
|
| 1222 |
+
}
|
| 1223 |
+
if len(n.Names) == 0 {
|
| 1224 |
+
// embedded field T or *T?
|
| 1225 |
+
typ := n.Type
|
| 1226 |
+
if ptr, ok := typ.(*ast.StarExpr); ok {
|
| 1227 |
+
typ = ptr.X
|
| 1228 |
+
}
|
| 1229 |
+
if id, ok := typ.(*ast.Ident); ok {
|
| 1230 |
+
mark(id)
|
| 1231 |
+
}
|
| 1232 |
+
}
|
| 1233 |
+
}
|
| 1234 |
+
return false
|
| 1235 |
+
default:
|
| 1236 |
+
return false
|
| 1237 |
+
}
|
| 1238 |
+
})
|
| 1239 |
+
}
|
| 1240 |
+
}
|
| 1241 |
+
|
| 1242 |
+
func (w *Walker) isDeprecated(obj types.Object) bool {
|
| 1243 |
+
return w.deprecated[obj.Pos()]
|
| 1244 |
+
}
|
go/src/cmd/asm/doc.go
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Copyright 2015 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 |
+
/*
|
| 6 |
+
Asm, typically invoked as “go tool asm”, assembles the source file into an object
|
| 7 |
+
file named for the basename of the argument source file with a .o suffix. The
|
| 8 |
+
object file can then be combined with other objects into a package archive.
|
| 9 |
+
|
| 10 |
+
# Command Line
|
| 11 |
+
|
| 12 |
+
Usage:
|
| 13 |
+
|
| 14 |
+
go tool asm [flags] file
|
| 15 |
+
|
| 16 |
+
The specified file must be a Go assembly file.
|
| 17 |
+
The same assembler is used for all target operating systems and architectures.
|
| 18 |
+
The GOOS and GOARCH environment variables set the desired target.
|
| 19 |
+
|
| 20 |
+
Flags:
|
| 21 |
+
|
| 22 |
+
-D name[=value]
|
| 23 |
+
Predefine symbol name with an optional simple value.
|
| 24 |
+
Can be repeated to define multiple symbols.
|
| 25 |
+
-I dir1 -I dir2
|
| 26 |
+
Search for #include files in dir1, dir2, etc,
|
| 27 |
+
after consulting $GOROOT/pkg/$GOOS_$GOARCH.
|
| 28 |
+
-S
|
| 29 |
+
Print assembly and machine code.
|
| 30 |
+
-V
|
| 31 |
+
Print assembler version and exit.
|
| 32 |
+
-debug
|
| 33 |
+
Dump instructions as they are parsed.
|
| 34 |
+
-dynlink
|
| 35 |
+
Support references to Go symbols defined in other shared libraries.
|
| 36 |
+
-e
|
| 37 |
+
No limit on number of errors reported.
|
| 38 |
+
-gensymabis
|
| 39 |
+
Write symbol ABI information to output file. Don't assemble.
|
| 40 |
+
-o file
|
| 41 |
+
Write output to file. The default is foo.o for /a/b/c/foo.s.
|
| 42 |
+
-p pkgpath
|
| 43 |
+
Set expected package import to pkgpath.
|
| 44 |
+
-shared
|
| 45 |
+
Generate code that can be linked into a shared library.
|
| 46 |
+
-spectre list
|
| 47 |
+
Enable spectre mitigations in list (all, ret).
|
| 48 |
+
-trimpath prefix
|
| 49 |
+
Remove prefix from recorded source file paths.
|
| 50 |
+
-v
|
| 51 |
+
Print debug output.
|
| 52 |
+
|
| 53 |
+
Input language:
|
| 54 |
+
|
| 55 |
+
The assembler uses mostly the same syntax for all architectures,
|
| 56 |
+
the main variation having to do with addressing modes. Input is
|
| 57 |
+
run through a simplified C preprocessor that implements #include,
|
| 58 |
+
#define, #ifdef/endif, but not #if or ##.
|
| 59 |
+
|
| 60 |
+
For more information, see https://golang.org/doc/asm.
|
| 61 |
+
*/
|
| 62 |
+
package main
|
go/src/cmd/asm/main.go
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Copyright 2014 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 |
+
package main
|
| 6 |
+
|
| 7 |
+
import (
|
| 8 |
+
"bufio"
|
| 9 |
+
"flag"
|
| 10 |
+
"fmt"
|
| 11 |
+
"internal/buildcfg"
|
| 12 |
+
"log"
|
| 13 |
+
"os"
|
| 14 |
+
|
| 15 |
+
"cmd/asm/internal/arch"
|
| 16 |
+
"cmd/asm/internal/asm"
|
| 17 |
+
"cmd/asm/internal/flags"
|
| 18 |
+
"cmd/asm/internal/lex"
|
| 19 |
+
|
| 20 |
+
"cmd/internal/bio"
|
| 21 |
+
"cmd/internal/obj"
|
| 22 |
+
"cmd/internal/objabi"
|
| 23 |
+
"cmd/internal/telemetry/counter"
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
func main() {
|
| 27 |
+
log.SetFlags(0)
|
| 28 |
+
log.SetPrefix("asm: ")
|
| 29 |
+
counter.Open()
|
| 30 |
+
|
| 31 |
+
buildcfg.Check()
|
| 32 |
+
GOARCH := buildcfg.GOARCH
|
| 33 |
+
|
| 34 |
+
flags.Parse()
|
| 35 |
+
counter.Inc("asm/invocations")
|
| 36 |
+
counter.CountFlags("asm/flag:", *flag.CommandLine)
|
| 37 |
+
|
| 38 |
+
architecture := arch.Set(GOARCH, *flags.Shared || *flags.Dynlink)
|
| 39 |
+
if architecture == nil {
|
| 40 |
+
log.Fatalf("unrecognized architecture %s", GOARCH)
|
| 41 |
+
}
|
| 42 |
+
ctxt := obj.Linknew(architecture.LinkArch)
|
| 43 |
+
ctxt.CompressInstructions = flags.DebugFlags.CompressInstructions != 0
|
| 44 |
+
ctxt.Debugasm = flags.PrintOut
|
| 45 |
+
ctxt.Debugvlog = flags.DebugV
|
| 46 |
+
ctxt.Flag_dynlink = *flags.Dynlink
|
| 47 |
+
ctxt.Flag_linkshared = *flags.Linkshared
|
| 48 |
+
ctxt.Flag_shared = *flags.Shared || *flags.Dynlink
|
| 49 |
+
ctxt.Flag_maymorestack = flags.DebugFlags.MayMoreStack
|
| 50 |
+
ctxt.Debugpcln = flags.DebugFlags.PCTab
|
| 51 |
+
ctxt.IsAsm = true
|
| 52 |
+
ctxt.Pkgpath = *flags.Importpath
|
| 53 |
+
ctxt.DwTextCount = objabi.DummyDwarfFunctionCountForAssembler()
|
| 54 |
+
switch *flags.Spectre {
|
| 55 |
+
default:
|
| 56 |
+
log.Printf("unknown setting -spectre=%s", *flags.Spectre)
|
| 57 |
+
os.Exit(2)
|
| 58 |
+
case "":
|
| 59 |
+
// nothing
|
| 60 |
+
case "index":
|
| 61 |
+
// known to compiler; ignore here so people can use
|
| 62 |
+
// the same list with -gcflags=-spectre=LIST and -asmflags=-spectre=LIST
|
| 63 |
+
case "all", "ret":
|
| 64 |
+
ctxt.Retpoline = true
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
ctxt.Bso = bufio.NewWriter(os.Stdout)
|
| 68 |
+
defer ctxt.Bso.Flush()
|
| 69 |
+
|
| 70 |
+
architecture.Init(ctxt)
|
| 71 |
+
|
| 72 |
+
// Create object file, write header.
|
| 73 |
+
buf, err := bio.Create(*flags.OutputFile)
|
| 74 |
+
if err != nil {
|
| 75 |
+
log.Fatal(err)
|
| 76 |
+
}
|
| 77 |
+
defer buf.Close()
|
| 78 |
+
|
| 79 |
+
if !*flags.SymABIs {
|
| 80 |
+
buf.WriteString(objabi.HeaderString())
|
| 81 |
+
fmt.Fprintf(buf, "!\n")
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
// Set macros for GOEXPERIMENTs so we can easily switch
|
| 85 |
+
// runtime assembly code based on them.
|
| 86 |
+
if objabi.LookupPkgSpecial(ctxt.Pkgpath).AllowAsmABI {
|
| 87 |
+
for _, exp := range buildcfg.Experiment.Enabled() {
|
| 88 |
+
flags.D = append(flags.D, "GOEXPERIMENT_"+exp)
|
| 89 |
+
}
|
| 90 |
+
}
|
| 91 |
+
|
| 92 |
+
var ok, diag bool
|
| 93 |
+
var failedFile string
|
| 94 |
+
for _, f := range flag.Args() {
|
| 95 |
+
lexer := lex.NewLexer(f)
|
| 96 |
+
parser := asm.NewParser(ctxt, architecture, lexer)
|
| 97 |
+
ctxt.DiagFunc = func(format string, args ...any) {
|
| 98 |
+
diag = true
|
| 99 |
+
log.Printf(format, args...)
|
| 100 |
+
}
|
| 101 |
+
if *flags.SymABIs {
|
| 102 |
+
ok = parser.ParseSymABIs(buf)
|
| 103 |
+
} else {
|
| 104 |
+
pList := new(obj.Plist)
|
| 105 |
+
pList.Firstpc, ok = parser.Parse()
|
| 106 |
+
// reports errors to parser.Errorf
|
| 107 |
+
if ok {
|
| 108 |
+
obj.Flushplist(ctxt, pList, nil)
|
| 109 |
+
}
|
| 110 |
+
}
|
| 111 |
+
if !ok {
|
| 112 |
+
failedFile = f
|
| 113 |
+
break
|
| 114 |
+
}
|
| 115 |
+
}
|
| 116 |
+
if ok && !*flags.SymABIs {
|
| 117 |
+
ctxt.NumberSyms()
|
| 118 |
+
obj.WriteObjFile(ctxt, buf)
|
| 119 |
+
}
|
| 120 |
+
if !ok || diag {
|
| 121 |
+
if failedFile != "" {
|
| 122 |
+
log.Printf("assembly of %s failed", failedFile)
|
| 123 |
+
} else {
|
| 124 |
+
log.Print("assembly failed")
|
| 125 |
+
}
|
| 126 |
+
buf.Close()
|
| 127 |
+
os.Remove(*flags.OutputFile)
|
| 128 |
+
os.Exit(1)
|
| 129 |
+
}
|
| 130 |
+
}
|
go/src/cmd/buildid/buildid.go
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Copyright 2017 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 |
+
package main
|
| 6 |
+
|
| 7 |
+
import (
|
| 8 |
+
"flag"
|
| 9 |
+
"fmt"
|
| 10 |
+
"log"
|
| 11 |
+
"os"
|
| 12 |
+
"strings"
|
| 13 |
+
|
| 14 |
+
"cmd/internal/buildid"
|
| 15 |
+
"cmd/internal/telemetry/counter"
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
func usage() {
|
| 19 |
+
fmt.Fprintf(os.Stderr, "usage: go tool buildid [-w] file\n")
|
| 20 |
+
flag.PrintDefaults()
|
| 21 |
+
os.Exit(2)
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
var wflag = flag.Bool("w", false, "write build ID")
|
| 25 |
+
|
| 26 |
+
func main() {
|
| 27 |
+
log.SetPrefix("buildid: ")
|
| 28 |
+
log.SetFlags(0)
|
| 29 |
+
counter.Open()
|
| 30 |
+
flag.Usage = usage
|
| 31 |
+
flag.Parse()
|
| 32 |
+
counter.Inc("buildid/invocations")
|
| 33 |
+
counter.CountFlags("buildid/flag:", *flag.CommandLine)
|
| 34 |
+
if flag.NArg() != 1 {
|
| 35 |
+
usage()
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
file := flag.Arg(0)
|
| 39 |
+
id, err := buildid.ReadFile(file)
|
| 40 |
+
if err != nil {
|
| 41 |
+
log.Fatal(err)
|
| 42 |
+
}
|
| 43 |
+
if !*wflag {
|
| 44 |
+
fmt.Printf("%s\n", id)
|
| 45 |
+
return
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
// Keep in sync with src/cmd/go/internal/work/buildid.go:updateBuildID
|
| 49 |
+
|
| 50 |
+
f, err := os.Open(file)
|
| 51 |
+
if err != nil {
|
| 52 |
+
log.Fatal(err)
|
| 53 |
+
}
|
| 54 |
+
matches, hash, err := buildid.FindAndHash(f, id, 0)
|
| 55 |
+
f.Close()
|
| 56 |
+
if err != nil {
|
| 57 |
+
log.Fatal(err)
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
// <= go 1.7 doesn't embed the contentID or actionID, so no slash is present
|
| 61 |
+
if !strings.Contains(id, "/") {
|
| 62 |
+
log.Fatalf("%s: build ID is a legacy format...binary too old for this tool", file)
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
newID := id[:strings.LastIndex(id, "/")] + "/" + buildid.HashToString(hash)
|
| 66 |
+
if len(newID) != len(id) {
|
| 67 |
+
log.Fatalf("%s: build ID length mismatch %q vs %q", file, id, newID)
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
if len(matches) == 0 {
|
| 71 |
+
return
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
f, err = os.OpenFile(file, os.O_RDWR, 0)
|
| 75 |
+
if err != nil {
|
| 76 |
+
log.Fatal(err)
|
| 77 |
+
}
|
| 78 |
+
if err := buildid.Rewrite(f, matches, newID); err != nil {
|
| 79 |
+
log.Fatal(err)
|
| 80 |
+
}
|
| 81 |
+
if err := f.Close(); err != nil {
|
| 82 |
+
log.Fatal(err)
|
| 83 |
+
}
|
| 84 |
+
}
|
go/src/cmd/buildid/doc.go
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Copyright 2017 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 |
+
/*
|
| 6 |
+
Buildid displays or updates the build ID stored in a Go package or binary.
|
| 7 |
+
|
| 8 |
+
Usage:
|
| 9 |
+
|
| 10 |
+
go tool buildid [-w] file
|
| 11 |
+
|
| 12 |
+
By default, buildid prints the build ID found in the named file.
|
| 13 |
+
If the -w option is given, buildid rewrites the build ID found in
|
| 14 |
+
the file to accurately record a content hash of the file.
|
| 15 |
+
|
| 16 |
+
This tool is only intended for use by the go command or
|
| 17 |
+
other build systems.
|
| 18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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Copyright 2009 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 |
+
// Parse input AST and prepare Prog structure.
|
| 6 |
+
|
| 7 |
+
package main
|
| 8 |
+
|
| 9 |
+
import (
|
| 10 |
+
"fmt"
|
| 11 |
+
"go/ast"
|
| 12 |
+
"go/format"
|
| 13 |
+
"go/parser"
|
| 14 |
+
"go/scanner"
|
| 15 |
+
"go/token"
|
| 16 |
+
"os"
|
| 17 |
+
"strings"
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
func parse(name string, src []byte, flags parser.Mode) *ast.File {
|
| 21 |
+
ast1, err := parser.ParseFile(fset, name, src, flags)
|
| 22 |
+
if err != nil {
|
| 23 |
+
if list, ok := err.(scanner.ErrorList); ok {
|
| 24 |
+
// If err is a scanner.ErrorList, its String will print just
|
| 25 |
+
// the first error and then (+n more errors).
|
| 26 |
+
// Instead, turn it into a new Error that will return
|
| 27 |
+
// details for all the errors.
|
| 28 |
+
for _, e := range list {
|
| 29 |
+
fmt.Fprintln(os.Stderr, e)
|
| 30 |
+
}
|
| 31 |
+
os.Exit(2)
|
| 32 |
+
}
|
| 33 |
+
fatalf("parsing %s: %s", name, err)
|
| 34 |
+
}
|
| 35 |
+
return ast1
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
func sourceLine(n ast.Node) int {
|
| 39 |
+
return fset.Position(n.Pos()).Line
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
// ParseGo populates f with information learned from the Go source code
|
| 43 |
+
// which was read from the named file. It gathers the C preamble
|
| 44 |
+
// attached to the import "C" comment, a list of references to C.xxx,
|
| 45 |
+
// a list of exported functions, and the actual AST, to be rewritten and
|
| 46 |
+
// printed.
|
| 47 |
+
func (f *File) ParseGo(abspath string, src []byte) {
|
| 48 |
+
// Two different parses: once with comments, once without.
|
| 49 |
+
// The printer is not good enough at printing comments in the
|
| 50 |
+
// right place when we start editing the AST behind its back,
|
| 51 |
+
// so we use ast1 to look for the doc comments on import "C"
|
| 52 |
+
// and on exported functions, and we use ast2 for translating
|
| 53 |
+
// and reprinting.
|
| 54 |
+
// In cgo mode, we ignore ast2 and just apply edits directly
|
| 55 |
+
// the text behind ast1. In godefs mode we modify and print ast2.
|
| 56 |
+
ast1 := parse(abspath, src, parser.SkipObjectResolution|parser.ParseComments)
|
| 57 |
+
ast2 := parse(abspath, src, parser.SkipObjectResolution)
|
| 58 |
+
|
| 59 |
+
f.Package = ast1.Name.Name
|
| 60 |
+
f.Name = make(map[string]*Name)
|
| 61 |
+
f.NamePos = make(map[*Name]token.Pos)
|
| 62 |
+
|
| 63 |
+
// In ast1, find the import "C" line and get any extra C preamble.
|
| 64 |
+
sawC := false
|
| 65 |
+
for _, decl := range ast1.Decls {
|
| 66 |
+
switch decl := decl.(type) {
|
| 67 |
+
case *ast.GenDecl:
|
| 68 |
+
for _, spec := range decl.Specs {
|
| 69 |
+
s, ok := spec.(*ast.ImportSpec)
|
| 70 |
+
if !ok || s.Path.Value != `"C"` {
|
| 71 |
+
continue
|
| 72 |
+
}
|
| 73 |
+
sawC = true
|
| 74 |
+
if s.Name != nil {
|
| 75 |
+
error_(s.Path.Pos(), `cannot rename import "C"`)
|
| 76 |
+
}
|
| 77 |
+
cg := s.Doc
|
| 78 |
+
if cg == nil && len(decl.Specs) == 1 {
|
| 79 |
+
cg = decl.Doc
|
| 80 |
+
}
|
| 81 |
+
if cg != nil {
|
| 82 |
+
if strings.ContainsAny(abspath, "\r\n") {
|
| 83 |
+
// This should have been checked when the file path was first resolved,
|
| 84 |
+
// but we double check here just to be sure.
|
| 85 |
+
fatalf("internal error: ParseGo: abspath contains unexpected newline character: %q", abspath)
|
| 86 |
+
}
|
| 87 |
+
f.Preamble += fmt.Sprintf("#line %d %q\n", sourceLine(cg), abspath)
|
| 88 |
+
f.Preamble += commentText(cg) + "\n"
|
| 89 |
+
f.Preamble += "#line 1 \"cgo-generated-wrapper\"\n"
|
| 90 |
+
}
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
case *ast.FuncDecl:
|
| 94 |
+
// Also, reject attempts to declare methods on C.T or *C.T.
|
| 95 |
+
// (The generated code would otherwise accept this
|
| 96 |
+
// invalid input; see issue #57926.)
|
| 97 |
+
if decl.Recv != nil && len(decl.Recv.List) > 0 {
|
| 98 |
+
recvType := decl.Recv.List[0].Type
|
| 99 |
+
if recvType != nil {
|
| 100 |
+
t := recvType
|
| 101 |
+
if star, ok := unparen(t).(*ast.StarExpr); ok {
|
| 102 |
+
t = star.X
|
| 103 |
+
}
|
| 104 |
+
if sel, ok := unparen(t).(*ast.SelectorExpr); ok {
|
| 105 |
+
var buf strings.Builder
|
| 106 |
+
format.Node(&buf, fset, recvType)
|
| 107 |
+
error_(sel.Pos(), `cannot define new methods on non-local type %s`, &buf)
|
| 108 |
+
}
|
| 109 |
+
}
|
| 110 |
+
}
|
| 111 |
+
}
|
| 112 |
+
|
| 113 |
+
}
|
| 114 |
+
if !sawC {
|
| 115 |
+
error_(ast1.Package, `cannot find import "C"`)
|
| 116 |
+
}
|
| 117 |
+
|
| 118 |
+
// In ast2, strip the import "C" line.
|
| 119 |
+
if *godefs {
|
| 120 |
+
w := 0
|
| 121 |
+
for _, decl := range ast2.Decls {
|
| 122 |
+
d, ok := decl.(*ast.GenDecl)
|
| 123 |
+
if !ok {
|
| 124 |
+
ast2.Decls[w] = decl
|
| 125 |
+
w++
|
| 126 |
+
continue
|
| 127 |
+
}
|
| 128 |
+
ws := 0
|
| 129 |
+
for _, spec := range d.Specs {
|
| 130 |
+
s, ok := spec.(*ast.ImportSpec)
|
| 131 |
+
if !ok || s.Path.Value != `"C"` {
|
| 132 |
+
d.Specs[ws] = spec
|
| 133 |
+
ws++
|
| 134 |
+
}
|
| 135 |
+
}
|
| 136 |
+
if ws == 0 {
|
| 137 |
+
continue
|
| 138 |
+
}
|
| 139 |
+
d.Specs = d.Specs[0:ws]
|
| 140 |
+
ast2.Decls[w] = d
|
| 141 |
+
w++
|
| 142 |
+
}
|
| 143 |
+
ast2.Decls = ast2.Decls[0:w]
|
| 144 |
+
} else {
|
| 145 |
+
for _, decl := range ast2.Decls {
|
| 146 |
+
d, ok := decl.(*ast.GenDecl)
|
| 147 |
+
if !ok {
|
| 148 |
+
continue
|
| 149 |
+
}
|
| 150 |
+
for _, spec := range d.Specs {
|
| 151 |
+
if s, ok := spec.(*ast.ImportSpec); ok && s.Path.Value == `"C"` {
|
| 152 |
+
// Replace "C" with _ "unsafe", to keep program valid.
|
| 153 |
+
// (Deleting import statement or clause is not safe if it is followed
|
| 154 |
+
// in the source by an explicit semicolon.)
|
| 155 |
+
f.Edit.Replace(f.offset(s.Path.Pos()), f.offset(s.Path.End()), `_ "unsafe"`)
|
| 156 |
+
}
|
| 157 |
+
}
|
| 158 |
+
}
|
| 159 |
+
}
|
| 160 |
+
|
| 161 |
+
// Accumulate pointers to uses of C.x.
|
| 162 |
+
if f.Ref == nil {
|
| 163 |
+
f.Ref = make([]*Ref, 0, 8)
|
| 164 |
+
}
|
| 165 |
+
f.walk(ast2, ctxProg, (*File).validateIdents)
|
| 166 |
+
f.walk(ast2, ctxProg, (*File).saveExprs)
|
| 167 |
+
|
| 168 |
+
// Accumulate exported functions.
|
| 169 |
+
// The comments are only on ast1 but we need to
|
| 170 |
+
// save the function bodies from ast2.
|
| 171 |
+
// The first walk fills in ExpFunc, and the
|
| 172 |
+
// second walk changes the entries to
|
| 173 |
+
// refer to ast2 instead.
|
| 174 |
+
f.walk(ast1, ctxProg, (*File).saveExport)
|
| 175 |
+
f.walk(ast2, ctxProg, (*File).saveExport2)
|
| 176 |
+
|
| 177 |
+
f.Comments = ast1.Comments
|
| 178 |
+
f.AST = ast2
|
| 179 |
+
}
|
| 180 |
+
|
| 181 |
+
// Like ast.CommentGroup's Text method but preserves
|
| 182 |
+
// leading blank lines, so that line numbers line up.
|
| 183 |
+
func commentText(g *ast.CommentGroup) string {
|
| 184 |
+
pieces := make([]string, 0, len(g.List))
|
| 185 |
+
for _, com := range g.List {
|
| 186 |
+
c := com.Text
|
| 187 |
+
// Remove comment markers.
|
| 188 |
+
// The parser has given us exactly the comment text.
|
| 189 |
+
switch c[1] {
|
| 190 |
+
case '/':
|
| 191 |
+
//-style comment (no newline at the end)
|
| 192 |
+
c = c[2:] + "\n"
|
| 193 |
+
case '*':
|
| 194 |
+
/*-style comment */
|
| 195 |
+
c = c[2 : len(c)-2]
|
| 196 |
+
}
|
| 197 |
+
pieces = append(pieces, c)
|
| 198 |
+
}
|
| 199 |
+
return strings.Join(pieces, "")
|
| 200 |
+
}
|
| 201 |
+
|
| 202 |
+
func (f *File) validateIdents(x any, context astContext) {
|
| 203 |
+
if x, ok := x.(*ast.Ident); ok {
|
| 204 |
+
if f.isMangledName(x.Name) {
|
| 205 |
+
error_(x.Pos(), "identifier %q may conflict with identifiers generated by cgo", x.Name)
|
| 206 |
+
}
|
| 207 |
+
}
|
| 208 |
+
}
|
| 209 |
+
|
| 210 |
+
// Save various references we are going to need later.
|
| 211 |
+
func (f *File) saveExprs(x any, context astContext) {
|
| 212 |
+
switch x := x.(type) {
|
| 213 |
+
case *ast.Expr:
|
| 214 |
+
switch (*x).(type) {
|
| 215 |
+
case *ast.SelectorExpr:
|
| 216 |
+
f.saveRef(x, context)
|
| 217 |
+
}
|
| 218 |
+
case *ast.CallExpr:
|
| 219 |
+
f.saveCall(x, context)
|
| 220 |
+
}
|
| 221 |
+
}
|
| 222 |
+
|
| 223 |
+
// Save references to C.xxx for later processing.
|
| 224 |
+
func (f *File) saveRef(n *ast.Expr, context astContext) {
|
| 225 |
+
sel := (*n).(*ast.SelectorExpr)
|
| 226 |
+
// For now, assume that the only instance of capital C is when
|
| 227 |
+
// used as the imported package identifier.
|
| 228 |
+
// The parser should take care of scoping in the future, so
|
| 229 |
+
// that we will be able to distinguish a "top-level C" from a
|
| 230 |
+
// local C.
|
| 231 |
+
if l, ok := sel.X.(*ast.Ident); !ok || l.Name != "C" {
|
| 232 |
+
return
|
| 233 |
+
}
|
| 234 |
+
if context == ctxAssign2 {
|
| 235 |
+
context = ctxExpr
|
| 236 |
+
}
|
| 237 |
+
if context == ctxEmbedType {
|
| 238 |
+
error_(sel.Pos(), "cannot embed C type")
|
| 239 |
+
}
|
| 240 |
+
goname := sel.Sel.Name
|
| 241 |
+
if goname == "errno" {
|
| 242 |
+
error_(sel.Pos(), "cannot refer to errno directly; see documentation")
|
| 243 |
+
return
|
| 244 |
+
}
|
| 245 |
+
if goname == "_CMalloc" {
|
| 246 |
+
error_(sel.Pos(), "cannot refer to C._CMalloc; use C.malloc")
|
| 247 |
+
return
|
| 248 |
+
}
|
| 249 |
+
if goname == "malloc" {
|
| 250 |
+
goname = "_CMalloc"
|
| 251 |
+
}
|
| 252 |
+
name := f.Name[goname]
|
| 253 |
+
if name == nil {
|
| 254 |
+
name = &Name{
|
| 255 |
+
Go: goname,
|
| 256 |
+
}
|
| 257 |
+
f.Name[goname] = name
|
| 258 |
+
f.NamePos[name] = sel.Pos()
|
| 259 |
+
}
|
| 260 |
+
f.Ref = append(f.Ref, &Ref{
|
| 261 |
+
Name: name,
|
| 262 |
+
Expr: n,
|
| 263 |
+
Context: context,
|
| 264 |
+
})
|
| 265 |
+
}
|
| 266 |
+
|
| 267 |
+
// Save calls to C.xxx for later processing.
|
| 268 |
+
func (f *File) saveCall(call *ast.CallExpr, context astContext) {
|
| 269 |
+
sel, ok := call.Fun.(*ast.SelectorExpr)
|
| 270 |
+
if !ok {
|
| 271 |
+
return
|
| 272 |
+
}
|
| 273 |
+
if l, ok := sel.X.(*ast.Ident); !ok || l.Name != "C" {
|
| 274 |
+
return
|
| 275 |
+
}
|
| 276 |
+
c := &Call{Call: call, Deferred: context == ctxDefer}
|
| 277 |
+
f.Calls = append(f.Calls, c)
|
| 278 |
+
}
|
| 279 |
+
|
| 280 |
+
// If a function should be exported add it to ExpFunc.
|
| 281 |
+
func (f *File) saveExport(x any, context astContext) {
|
| 282 |
+
n, ok := x.(*ast.FuncDecl)
|
| 283 |
+
if !ok {
|
| 284 |
+
return
|
| 285 |
+
}
|
| 286 |
+
|
| 287 |
+
if n.Doc == nil {
|
| 288 |
+
return
|
| 289 |
+
}
|
| 290 |
+
for _, c := range n.Doc.List {
|
| 291 |
+
if !strings.HasPrefix(c.Text, "//export ") {
|
| 292 |
+
continue
|
| 293 |
+
}
|
| 294 |
+
|
| 295 |
+
name := strings.TrimSpace(c.Text[9:])
|
| 296 |
+
if name == "" {
|
| 297 |
+
error_(c.Pos(), "export missing name")
|
| 298 |
+
}
|
| 299 |
+
|
| 300 |
+
if name != n.Name.Name {
|
| 301 |
+
error_(c.Pos(), "export comment has wrong name %q, want %q", name, n.Name.Name)
|
| 302 |
+
}
|
| 303 |
+
|
| 304 |
+
f.ExpFunc = append(f.ExpFunc, &ExpFunc{
|
| 305 |
+
Func: n,
|
| 306 |
+
ExpName: name,
|
| 307 |
+
// Caution: Do not set the Doc field on purpose
|
| 308 |
+
// to ensure that there are no unintended artifacts
|
| 309 |
+
// in the binary. See https://go.dev/issue/76697.
|
| 310 |
+
})
|
| 311 |
+
break
|
| 312 |
+
}
|
| 313 |
+
}
|
| 314 |
+
|
| 315 |
+
// Make f.ExpFunc[i] point at the Func from this AST instead of the other one.
|
| 316 |
+
func (f *File) saveExport2(x any, context astContext) {
|
| 317 |
+
n, ok := x.(*ast.FuncDecl)
|
| 318 |
+
if !ok {
|
| 319 |
+
return
|
| 320 |
+
}
|
| 321 |
+
|
| 322 |
+
for _, exp := range f.ExpFunc {
|
| 323 |
+
if exp.Func.Name.Name == n.Name.Name {
|
| 324 |
+
exp.Func = n
|
| 325 |
+
break
|
| 326 |
+
}
|
| 327 |
+
}
|
| 328 |
+
}
|
| 329 |
+
|
| 330 |
+
type astContext int
|
| 331 |
+
|
| 332 |
+
const (
|
| 333 |
+
ctxProg astContext = iota
|
| 334 |
+
ctxEmbedType
|
| 335 |
+
ctxType
|
| 336 |
+
ctxStmt
|
| 337 |
+
ctxExpr
|
| 338 |
+
ctxField
|
| 339 |
+
ctxParam
|
| 340 |
+
ctxAssign2 // assignment of a single expression to two variables
|
| 341 |
+
ctxSwitch
|
| 342 |
+
ctxTypeSwitch
|
| 343 |
+
ctxFile
|
| 344 |
+
ctxDecl
|
| 345 |
+
ctxSpec
|
| 346 |
+
ctxDefer
|
| 347 |
+
ctxCall // any function call other than ctxCall2
|
| 348 |
+
ctxCall2 // function call whose result is assigned to two variables
|
| 349 |
+
ctxSelector
|
| 350 |
+
)
|
| 351 |
+
|
| 352 |
+
// walk walks the AST x, calling visit(f, x, context) for each node.
|
| 353 |
+
func (f *File) walk(x any, context astContext, visit func(*File, any, astContext)) {
|
| 354 |
+
visit(f, x, context)
|
| 355 |
+
switch n := x.(type) {
|
| 356 |
+
case *ast.Expr:
|
| 357 |
+
f.walk(*n, context, visit)
|
| 358 |
+
|
| 359 |
+
// everything else just recurs
|
| 360 |
+
default:
|
| 361 |
+
error_(token.NoPos, "unexpected type %T in walk", x)
|
| 362 |
+
panic("unexpected type")
|
| 363 |
+
|
| 364 |
+
case nil:
|
| 365 |
+
|
| 366 |
+
// These are ordered and grouped to match ../../go/ast/ast.go
|
| 367 |
+
case *ast.Field:
|
| 368 |
+
if len(n.Names) == 0 && context == ctxField {
|
| 369 |
+
f.walk(&n.Type, ctxEmbedType, visit)
|
| 370 |
+
} else {
|
| 371 |
+
f.walk(&n.Type, ctxType, visit)
|
| 372 |
+
}
|
| 373 |
+
case *ast.FieldList:
|
| 374 |
+
for _, field := range n.List {
|
| 375 |
+
f.walk(field, context, visit)
|
| 376 |
+
}
|
| 377 |
+
case *ast.BadExpr:
|
| 378 |
+
case *ast.Ident:
|
| 379 |
+
case *ast.Ellipsis:
|
| 380 |
+
f.walk(&n.Elt, ctxType, visit)
|
| 381 |
+
case *ast.BasicLit:
|
| 382 |
+
case *ast.FuncLit:
|
| 383 |
+
f.walk(n.Type, ctxType, visit)
|
| 384 |
+
f.walk(n.Body, ctxStmt, visit)
|
| 385 |
+
case *ast.CompositeLit:
|
| 386 |
+
f.walk(&n.Type, ctxType, visit)
|
| 387 |
+
f.walk(n.Elts, ctxExpr, visit)
|
| 388 |
+
case *ast.ParenExpr:
|
| 389 |
+
f.walk(&n.X, context, visit)
|
| 390 |
+
case *ast.SelectorExpr:
|
| 391 |
+
f.walk(&n.X, ctxSelector, visit)
|
| 392 |
+
case *ast.IndexExpr:
|
| 393 |
+
f.walk(&n.X, ctxExpr, visit)
|
| 394 |
+
f.walk(&n.Index, ctxExpr, visit)
|
| 395 |
+
case *ast.IndexListExpr:
|
| 396 |
+
f.walk(&n.X, ctxExpr, visit)
|
| 397 |
+
f.walk(n.Indices, ctxExpr, visit)
|
| 398 |
+
case *ast.SliceExpr:
|
| 399 |
+
f.walk(&n.X, ctxExpr, visit)
|
| 400 |
+
if n.Low != nil {
|
| 401 |
+
f.walk(&n.Low, ctxExpr, visit)
|
| 402 |
+
}
|
| 403 |
+
if n.High != nil {
|
| 404 |
+
f.walk(&n.High, ctxExpr, visit)
|
| 405 |
+
}
|
| 406 |
+
if n.Max != nil {
|
| 407 |
+
f.walk(&n.Max, ctxExpr, visit)
|
| 408 |
+
}
|
| 409 |
+
case *ast.TypeAssertExpr:
|
| 410 |
+
f.walk(&n.X, ctxExpr, visit)
|
| 411 |
+
f.walk(&n.Type, ctxType, visit)
|
| 412 |
+
case *ast.CallExpr:
|
| 413 |
+
if context == ctxAssign2 {
|
| 414 |
+
f.walk(&n.Fun, ctxCall2, visit)
|
| 415 |
+
} else {
|
| 416 |
+
f.walk(&n.Fun, ctxCall, visit)
|
| 417 |
+
}
|
| 418 |
+
f.walk(n.Args, ctxExpr, visit)
|
| 419 |
+
case *ast.StarExpr:
|
| 420 |
+
f.walk(&n.X, context, visit)
|
| 421 |
+
case *ast.UnaryExpr:
|
| 422 |
+
f.walk(&n.X, ctxExpr, visit)
|
| 423 |
+
case *ast.BinaryExpr:
|
| 424 |
+
f.walk(&n.X, ctxExpr, visit)
|
| 425 |
+
f.walk(&n.Y, ctxExpr, visit)
|
| 426 |
+
case *ast.KeyValueExpr:
|
| 427 |
+
f.walk(&n.Key, ctxExpr, visit)
|
| 428 |
+
f.walk(&n.Value, ctxExpr, visit)
|
| 429 |
+
|
| 430 |
+
case *ast.ArrayType:
|
| 431 |
+
f.walk(&n.Len, ctxExpr, visit)
|
| 432 |
+
f.walk(&n.Elt, ctxType, visit)
|
| 433 |
+
case *ast.StructType:
|
| 434 |
+
f.walk(n.Fields, ctxField, visit)
|
| 435 |
+
case *ast.FuncType:
|
| 436 |
+
if n.TypeParams != nil {
|
| 437 |
+
f.walk(n.TypeParams, ctxParam, visit)
|
| 438 |
+
}
|
| 439 |
+
f.walk(n.Params, ctxParam, visit)
|
| 440 |
+
if n.Results != nil {
|
| 441 |
+
f.walk(n.Results, ctxParam, visit)
|
| 442 |
+
}
|
| 443 |
+
case *ast.InterfaceType:
|
| 444 |
+
f.walk(n.Methods, ctxField, visit)
|
| 445 |
+
case *ast.MapType:
|
| 446 |
+
f.walk(&n.Key, ctxType, visit)
|
| 447 |
+
f.walk(&n.Value, ctxType, visit)
|
| 448 |
+
case *ast.ChanType:
|
| 449 |
+
f.walk(&n.Value, ctxType, visit)
|
| 450 |
+
|
| 451 |
+
case *ast.BadStmt:
|
| 452 |
+
case *ast.DeclStmt:
|
| 453 |
+
f.walk(n.Decl, ctxDecl, visit)
|
| 454 |
+
case *ast.EmptyStmt:
|
| 455 |
+
case *ast.LabeledStmt:
|
| 456 |
+
f.walk(n.Stmt, ctxStmt, visit)
|
| 457 |
+
case *ast.ExprStmt:
|
| 458 |
+
f.walk(&n.X, ctxExpr, visit)
|
| 459 |
+
case *ast.SendStmt:
|
| 460 |
+
f.walk(&n.Chan, ctxExpr, visit)
|
| 461 |
+
f.walk(&n.Value, ctxExpr, visit)
|
| 462 |
+
case *ast.IncDecStmt:
|
| 463 |
+
f.walk(&n.X, ctxExpr, visit)
|
| 464 |
+
case *ast.AssignStmt:
|
| 465 |
+
f.walk(n.Lhs, ctxExpr, visit)
|
| 466 |
+
if len(n.Lhs) == 2 && len(n.Rhs) == 1 {
|
| 467 |
+
f.walk(n.Rhs, ctxAssign2, visit)
|
| 468 |
+
} else {
|
| 469 |
+
f.walk(n.Rhs, ctxExpr, visit)
|
| 470 |
+
}
|
| 471 |
+
case *ast.GoStmt:
|
| 472 |
+
f.walk(n.Call, ctxExpr, visit)
|
| 473 |
+
case *ast.DeferStmt:
|
| 474 |
+
f.walk(n.Call, ctxDefer, visit)
|
| 475 |
+
case *ast.ReturnStmt:
|
| 476 |
+
f.walk(n.Results, ctxExpr, visit)
|
| 477 |
+
case *ast.BranchStmt:
|
| 478 |
+
case *ast.BlockStmt:
|
| 479 |
+
f.walk(n.List, context, visit)
|
| 480 |
+
case *ast.IfStmt:
|
| 481 |
+
f.walk(n.Init, ctxStmt, visit)
|
| 482 |
+
f.walk(&n.Cond, ctxExpr, visit)
|
| 483 |
+
f.walk(n.Body, ctxStmt, visit)
|
| 484 |
+
f.walk(n.Else, ctxStmt, visit)
|
| 485 |
+
case *ast.CaseClause:
|
| 486 |
+
if context == ctxTypeSwitch {
|
| 487 |
+
context = ctxType
|
| 488 |
+
} else {
|
| 489 |
+
context = ctxExpr
|
| 490 |
+
}
|
| 491 |
+
f.walk(n.List, context, visit)
|
| 492 |
+
f.walk(n.Body, ctxStmt, visit)
|
| 493 |
+
case *ast.SwitchStmt:
|
| 494 |
+
f.walk(n.Init, ctxStmt, visit)
|
| 495 |
+
f.walk(&n.Tag, ctxExpr, visit)
|
| 496 |
+
f.walk(n.Body, ctxSwitch, visit)
|
| 497 |
+
case *ast.TypeSwitchStmt:
|
| 498 |
+
f.walk(n.Init, ctxStmt, visit)
|
| 499 |
+
f.walk(n.Assign, ctxStmt, visit)
|
| 500 |
+
f.walk(n.Body, ctxTypeSwitch, visit)
|
| 501 |
+
case *ast.CommClause:
|
| 502 |
+
f.walk(n.Comm, ctxStmt, visit)
|
| 503 |
+
f.walk(n.Body, ctxStmt, visit)
|
| 504 |
+
case *ast.SelectStmt:
|
| 505 |
+
f.walk(n.Body, ctxStmt, visit)
|
| 506 |
+
case *ast.ForStmt:
|
| 507 |
+
f.walk(n.Init, ctxStmt, visit)
|
| 508 |
+
f.walk(&n.Cond, ctxExpr, visit)
|
| 509 |
+
f.walk(n.Post, ctxStmt, visit)
|
| 510 |
+
f.walk(n.Body, ctxStmt, visit)
|
| 511 |
+
case *ast.RangeStmt:
|
| 512 |
+
f.walk(&n.Key, ctxExpr, visit)
|
| 513 |
+
f.walk(&n.Value, ctxExpr, visit)
|
| 514 |
+
f.walk(&n.X, ctxExpr, visit)
|
| 515 |
+
f.walk(n.Body, ctxStmt, visit)
|
| 516 |
+
|
| 517 |
+
case *ast.ImportSpec:
|
| 518 |
+
case *ast.ValueSpec:
|
| 519 |
+
f.walk(&n.Type, ctxType, visit)
|
| 520 |
+
if len(n.Names) == 2 && len(n.Values) == 1 {
|
| 521 |
+
f.walk(&n.Values[0], ctxAssign2, visit)
|
| 522 |
+
} else {
|
| 523 |
+
f.walk(n.Values, ctxExpr, visit)
|
| 524 |
+
}
|
| 525 |
+
case *ast.TypeSpec:
|
| 526 |
+
if n.TypeParams != nil {
|
| 527 |
+
f.walk(n.TypeParams, ctxParam, visit)
|
| 528 |
+
}
|
| 529 |
+
f.walk(&n.Type, ctxType, visit)
|
| 530 |
+
|
| 531 |
+
case *ast.BadDecl:
|
| 532 |
+
case *ast.GenDecl:
|
| 533 |
+
f.walk(n.Specs, ctxSpec, visit)
|
| 534 |
+
case *ast.FuncDecl:
|
| 535 |
+
if n.Recv != nil {
|
| 536 |
+
f.walk(n.Recv, ctxParam, visit)
|
| 537 |
+
}
|
| 538 |
+
f.walk(n.Type, ctxType, visit)
|
| 539 |
+
if n.Body != nil {
|
| 540 |
+
f.walk(n.Body, ctxStmt, visit)
|
| 541 |
+
}
|
| 542 |
+
|
| 543 |
+
case *ast.File:
|
| 544 |
+
f.walk(n.Decls, ctxDecl, visit)
|
| 545 |
+
|
| 546 |
+
case *ast.Package:
|
| 547 |
+
for _, file := range n.Files {
|
| 548 |
+
f.walk(file, ctxFile, visit)
|
| 549 |
+
}
|
| 550 |
+
|
| 551 |
+
case []ast.Decl:
|
| 552 |
+
for _, d := range n {
|
| 553 |
+
f.walk(d, context, visit)
|
| 554 |
+
}
|
| 555 |
+
case []ast.Expr:
|
| 556 |
+
for i := range n {
|
| 557 |
+
f.walk(&n[i], context, visit)
|
| 558 |
+
}
|
| 559 |
+
case []ast.Stmt:
|
| 560 |
+
for _, s := range n {
|
| 561 |
+
f.walk(s, context, visit)
|
| 562 |
+
}
|
| 563 |
+
case []ast.Spec:
|
| 564 |
+
for _, s := range n {
|
| 565 |
+
f.walk(s, context, visit)
|
| 566 |
+
}
|
| 567 |
+
}
|
| 568 |
+
}
|
| 569 |
+
|
| 570 |
+
// If x is of the form (T), unparen returns unparen(T), otherwise it returns x.
|
| 571 |
+
func unparen(x ast.Expr) ast.Expr {
|
| 572 |
+
if p, isParen := x.(*ast.ParenExpr); isParen {
|
| 573 |
+
x = unparen(p.X)
|
| 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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Copyright 2009 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 |
+
/*
|
| 6 |
+
Cgo enables the creation of Go packages that call C code.
|
| 7 |
+
|
| 8 |
+
# Using cgo with the go command
|
| 9 |
+
|
| 10 |
+
To use cgo write normal Go code that imports a pseudo-package "C".
|
| 11 |
+
The Go code can then refer to types such as C.size_t, variables such
|
| 12 |
+
as C.stdout, or functions such as C.putchar.
|
| 13 |
+
|
| 14 |
+
If the import of "C" is immediately preceded by a comment, that
|
| 15 |
+
comment, called the preamble, is used as a header when compiling
|
| 16 |
+
the C parts of the package. For example:
|
| 17 |
+
|
| 18 |
+
// #include <stdio.h>
|
| 19 |
+
// #include <errno.h>
|
| 20 |
+
import "C"
|
| 21 |
+
|
| 22 |
+
The preamble may contain any C code, including function and variable
|
| 23 |
+
declarations and definitions. These may then be referred to from Go
|
| 24 |
+
code as though they were defined in the package "C". All names
|
| 25 |
+
declared in the preamble may be used, even if they start with a
|
| 26 |
+
lower-case letter. Exception: static variables in the preamble may
|
| 27 |
+
not be referenced from Go code; static functions are permitted.
|
| 28 |
+
|
| 29 |
+
See $GOROOT/cmd/cgo/internal/teststdio and $GOROOT/misc/cgo/gmp for examples. See
|
| 30 |
+
"C? Go? Cgo!" for an introduction to using cgo:
|
| 31 |
+
https://golang.org/doc/articles/c_go_cgo.html.
|
| 32 |
+
|
| 33 |
+
CFLAGS, CPPFLAGS, CXXFLAGS, FFLAGS and LDFLAGS may be defined with pseudo
|
| 34 |
+
#cgo directives within these comments to tweak the behavior of the C, C++
|
| 35 |
+
or Fortran compiler. Values defined in multiple directives are concatenated
|
| 36 |
+
together. The directive can include a list of build constraints limiting its
|
| 37 |
+
effect to systems satisfying one of the constraints
|
| 38 |
+
(see https://golang.org/pkg/go/build/#hdr-Build_Constraints for details about the constraint syntax).
|
| 39 |
+
For example:
|
| 40 |
+
|
| 41 |
+
// #cgo CFLAGS: -DPNG_DEBUG=1
|
| 42 |
+
// #cgo amd64 386 CFLAGS: -DX86=1
|
| 43 |
+
// #cgo LDFLAGS: -lpng
|
| 44 |
+
// #include <png.h>
|
| 45 |
+
import "C"
|
| 46 |
+
|
| 47 |
+
Alternatively, CPPFLAGS and LDFLAGS may be obtained via the pkg-config tool
|
| 48 |
+
using a '#cgo pkg-config:' directive followed by the package names.
|
| 49 |
+
For example:
|
| 50 |
+
|
| 51 |
+
// #cgo pkg-config: png cairo
|
| 52 |
+
// #include <png.h>
|
| 53 |
+
import "C"
|
| 54 |
+
|
| 55 |
+
The default pkg-config tool may be changed by setting the PKG_CONFIG environment variable.
|
| 56 |
+
|
| 57 |
+
For security reasons, only a limited set of flags are allowed, notably -D, -U, -I, and -l.
|
| 58 |
+
To allow additional flags, set CGO_CFLAGS_ALLOW to a regular expression
|
| 59 |
+
matching the new flags. To disallow flags that would otherwise be allowed,
|
| 60 |
+
set CGO_CFLAGS_DISALLOW to a regular expression matching arguments
|
| 61 |
+
that must be disallowed. In both cases the regular expression must match
|
| 62 |
+
a full argument: to allow -mfoo=bar, use CGO_CFLAGS_ALLOW='-mfoo.*',
|
| 63 |
+
not just CGO_CFLAGS_ALLOW='-mfoo'. Similarly named variables control
|
| 64 |
+
the allowed CPPFLAGS, CXXFLAGS, FFLAGS, and LDFLAGS.
|
| 65 |
+
|
| 66 |
+
Also for security reasons, only a limited set of characters are
|
| 67 |
+
permitted, notably alphanumeric characters and a few symbols, such as
|
| 68 |
+
'.', that will not be interpreted in unexpected ways. Attempts to use
|
| 69 |
+
forbidden characters will get a "malformed #cgo argument" error.
|
| 70 |
+
|
| 71 |
+
When building, the CGO_CFLAGS, CGO_CPPFLAGS, CGO_CXXFLAGS, CGO_FFLAGS and
|
| 72 |
+
CGO_LDFLAGS environment variables are added to the flags derived from
|
| 73 |
+
these directives. Package-specific flags should be set using the
|
| 74 |
+
directives, not the environment variables, so that builds work in
|
| 75 |
+
unmodified environments. Flags obtained from environment variables
|
| 76 |
+
are not subject to the security limitations described above.
|
| 77 |
+
|
| 78 |
+
All the cgo CPPFLAGS and CFLAGS directives in a package are concatenated and
|
| 79 |
+
used to compile C files in that package. All the CPPFLAGS and CXXFLAGS
|
| 80 |
+
directives in a package are concatenated and used to compile C++ files in that
|
| 81 |
+
package. All the CPPFLAGS and FFLAGS directives in a package are concatenated
|
| 82 |
+
and used to compile Fortran files in that package. All the LDFLAGS directives
|
| 83 |
+
in any package in the program are concatenated and used at link time. All the
|
| 84 |
+
pkg-config directives are concatenated and sent to pkg-config simultaneously
|
| 85 |
+
to add to each appropriate set of command-line flags.
|
| 86 |
+
|
| 87 |
+
When the cgo directives are parsed, any occurrence of the string ${SRCDIR}
|
| 88 |
+
will be replaced by the absolute path to the directory containing the source
|
| 89 |
+
file. This allows pre-compiled static libraries to be included in the package
|
| 90 |
+
directory and linked properly.
|
| 91 |
+
For example if package foo is in the directory /go/src/foo:
|
| 92 |
+
|
| 93 |
+
// #cgo LDFLAGS: -L${SRCDIR}/libs -lfoo
|
| 94 |
+
|
| 95 |
+
Will be expanded to:
|
| 96 |
+
|
| 97 |
+
// #cgo LDFLAGS: -L/go/src/foo/libs -lfoo
|
| 98 |
+
|
| 99 |
+
When the Go tool sees that one or more Go files use the special import
|
| 100 |
+
"C", it will look for other non-Go files in the directory and compile
|
| 101 |
+
them as part of the Go package. Any .c, .s, .S or .sx files will be
|
| 102 |
+
compiled with the C compiler. Any .cc, .cpp, or .cxx files will be
|
| 103 |
+
compiled with the C++ compiler. Any .f, .F, .for or .f90 files will be
|
| 104 |
+
compiled with the fortran compiler. Any .h, .hh, .hpp, or .hxx files will
|
| 105 |
+
not be compiled separately, but, if these header files are changed,
|
| 106 |
+
the package (including its non-Go source files) will be recompiled.
|
| 107 |
+
Note that changes to files in other directories do not cause the package
|
| 108 |
+
to be recompiled, so all non-Go source code for the package should be
|
| 109 |
+
stored in the package directory, not in subdirectories.
|
| 110 |
+
The default C and C++ compilers may be changed by the CC and CXX
|
| 111 |
+
environment variables, respectively; those environment variables
|
| 112 |
+
may include command line options.
|
| 113 |
+
|
| 114 |
+
The cgo tool will always invoke the C compiler with the source file's
|
| 115 |
+
directory in the include path; i.e. -I${SRCDIR} is always implied. This
|
| 116 |
+
means that if a header file foo/bar.h exists both in the source
|
| 117 |
+
directory and also in the system include directory (or some other place
|
| 118 |
+
specified by a -I flag), then "#include <foo/bar.h>" will always find the
|
| 119 |
+
local version in preference to any other version.
|
| 120 |
+
|
| 121 |
+
The cgo tool is enabled by default for native builds on systems where
|
| 122 |
+
it is expected to work. It is disabled by default when cross-compiling
|
| 123 |
+
as well as when the CC environment variable is unset and the default
|
| 124 |
+
C compiler (typically gcc or clang) cannot be found on the system PATH.
|
| 125 |
+
You can override the default by setting the CGO_ENABLED
|
| 126 |
+
environment variable when running the go tool: set it to 1 to enable
|
| 127 |
+
the use of cgo, and to 0 to disable it. The go tool will set the
|
| 128 |
+
build constraint "cgo" if cgo is enabled. The special import "C"
|
| 129 |
+
implies the "cgo" build constraint, as though the file also said
|
| 130 |
+
"//go:build cgo". Therefore, if cgo is disabled, files that import
|
| 131 |
+
"C" will not be built by the go tool. (For more about build constraints
|
| 132 |
+
see https://golang.org/pkg/go/build/#hdr-Build_Constraints).
|
| 133 |
+
|
| 134 |
+
When cross-compiling, you must specify a C cross-compiler for cgo to
|
| 135 |
+
use. You can do this by setting the generic CC_FOR_TARGET or the
|
| 136 |
+
more specific CC_FOR_${GOOS}_${GOARCH} (for example, CC_FOR_linux_arm)
|
| 137 |
+
environment variable when building the toolchain using make.bash,
|
| 138 |
+
or you can set the CC environment variable any time you run the go tool.
|
| 139 |
+
|
| 140 |
+
The CXX_FOR_TARGET, CXX_FOR_${GOOS}_${GOARCH}, and CXX
|
| 141 |
+
environment variables work in a similar way for C++ code.
|
| 142 |
+
|
| 143 |
+
# Go references to C
|
| 144 |
+
|
| 145 |
+
Within the Go file, C's struct field names that are keywords in Go
|
| 146 |
+
can be accessed by prefixing them with an underscore: if x points at a C
|
| 147 |
+
struct with a field named "type", x._type accesses the field.
|
| 148 |
+
C struct fields that cannot be expressed in Go, such as bit fields
|
| 149 |
+
or misaligned data, are omitted in the Go struct, replaced by
|
| 150 |
+
appropriate padding to reach the next field or the end of the struct.
|
| 151 |
+
|
| 152 |
+
The standard C numeric types are available under the names
|
| 153 |
+
C.char, C.schar (signed char), C.uchar (unsigned char),
|
| 154 |
+
C.short, C.ushort (unsigned short), C.int, C.uint (unsigned int),
|
| 155 |
+
C.long, C.ulong (unsigned long), C.longlong (long long),
|
| 156 |
+
C.ulonglong (unsigned long long), C.float, C.double,
|
| 157 |
+
C.complexfloat (complex float), and C.complexdouble (complex double).
|
| 158 |
+
The C type void* is represented by Go's unsafe.Pointer.
|
| 159 |
+
The C types __int128_t and __uint128_t are represented by [16]byte.
|
| 160 |
+
|
| 161 |
+
A few special C types which would normally be represented by a pointer
|
| 162 |
+
type in Go are instead represented by a uintptr. See the Special
|
| 163 |
+
cases section below.
|
| 164 |
+
|
| 165 |
+
To access a struct, union, or enum type directly, prefix it with
|
| 166 |
+
struct_, union_, or enum_, as in C.struct_stat. The size of any C type
|
| 167 |
+
T is available as C.sizeof_T, as in C.sizeof_struct_stat. These
|
| 168 |
+
special prefixes means that there is no way to directly reference a C
|
| 169 |
+
identifier that starts with "struct_", "union_", "enum_", or
|
| 170 |
+
"sizeof_", such as a function named "struct_function".
|
| 171 |
+
A workaround is to use a "#define" in the preamble, as in
|
| 172 |
+
"#define c_struct_function struct_function" and then in the
|
| 173 |
+
Go code refer to "C.c_struct_function".
|
| 174 |
+
|
| 175 |
+
A C function may be declared in the Go file with a parameter type of
|
| 176 |
+
the special name _GoString_. This function may be called with an
|
| 177 |
+
ordinary Go string value. The string length, and a pointer to the
|
| 178 |
+
string contents, may be accessed by calling the C functions
|
| 179 |
+
|
| 180 |
+
size_t _GoStringLen(_GoString_ s);
|
| 181 |
+
const char *_GoStringPtr(_GoString_ s);
|
| 182 |
+
|
| 183 |
+
These functions are only available in the preamble, not in other C
|
| 184 |
+
files. The C code must not modify the contents of the pointer returned
|
| 185 |
+
by _GoStringPtr. Note that the string contents may not have a trailing
|
| 186 |
+
NUL byte.
|
| 187 |
+
|
| 188 |
+
As Go doesn't have support for C's union type in the general case,
|
| 189 |
+
C's union types are represented as a Go byte array with the same length.
|
| 190 |
+
|
| 191 |
+
Go structs cannot embed fields with C types.
|
| 192 |
+
|
| 193 |
+
Go code cannot refer to zero-sized fields that occur at the end of
|
| 194 |
+
non-empty C structs. To get the address of such a field (which is the
|
| 195 |
+
only operation you can do with a zero-sized field) you must take the
|
| 196 |
+
address of the struct and add the size of the struct.
|
| 197 |
+
|
| 198 |
+
Cgo translates C types into equivalent unexported Go types.
|
| 199 |
+
Because the translations are unexported, a Go package should not
|
| 200 |
+
expose C types in its exported API: a C type used in one Go package
|
| 201 |
+
is different from the same C type used in another.
|
| 202 |
+
|
| 203 |
+
Any C function (even void functions) may be called in a multiple
|
| 204 |
+
assignment context to retrieve both the return value (if any) and the
|
| 205 |
+
C errno variable as an error (use _ to skip the result value if the
|
| 206 |
+
function returns void). For example:
|
| 207 |
+
|
| 208 |
+
n, err = C.sqrt(-1)
|
| 209 |
+
_, err := C.voidFunc()
|
| 210 |
+
var n, err = C.sqrt(1)
|
| 211 |
+
|
| 212 |
+
Note that the C errno value may be non-zero, and thus the err result may be
|
| 213 |
+
non-nil, even if the function call is successful. Unlike normal Go conventions,
|
| 214 |
+
you should first check whether the call succeeded before checking the error
|
| 215 |
+
result. For example:
|
| 216 |
+
|
| 217 |
+
n, err := C.setenv(key, value, 1)
|
| 218 |
+
if n != 0 {
|
| 219 |
+
// we know the call failed, so it is now valid to use err
|
| 220 |
+
return err
|
| 221 |
+
}
|
| 222 |
+
|
| 223 |
+
Calling C function pointers is currently not supported, however you can
|
| 224 |
+
declare Go variables which hold C function pointers and pass them
|
| 225 |
+
back and forth between Go and C. C code may call function pointers
|
| 226 |
+
received from Go. For example:
|
| 227 |
+
|
| 228 |
+
package main
|
| 229 |
+
|
| 230 |
+
// typedef int (*intFunc) ();
|
| 231 |
+
//
|
| 232 |
+
// int
|
| 233 |
+
// bridge_int_func(intFunc f)
|
| 234 |
+
// {
|
| 235 |
+
// return f();
|
| 236 |
+
// }
|
| 237 |
+
//
|
| 238 |
+
// int fortytwo()
|
| 239 |
+
// {
|
| 240 |
+
// return 42;
|
| 241 |
+
// }
|
| 242 |
+
import "C"
|
| 243 |
+
import "fmt"
|
| 244 |
+
|
| 245 |
+
func main() {
|
| 246 |
+
f := C.intFunc(C.fortytwo)
|
| 247 |
+
fmt.Println(int(C.bridge_int_func(f)))
|
| 248 |
+
// Output: 42
|
| 249 |
+
}
|
| 250 |
+
|
| 251 |
+
In C, a function argument written as a fixed size array
|
| 252 |
+
actually requires a pointer to the first element of the array.
|
| 253 |
+
C compilers are aware of this calling convention and adjust
|
| 254 |
+
the call accordingly, but Go cannot. In Go, you must pass
|
| 255 |
+
the pointer to the first element explicitly: C.f(&C.x[0]).
|
| 256 |
+
|
| 257 |
+
Calling variadic C functions is not supported. It is possible to
|
| 258 |
+
circumvent this by using a C function wrapper. For example:
|
| 259 |
+
|
| 260 |
+
package main
|
| 261 |
+
|
| 262 |
+
// #include <stdio.h>
|
| 263 |
+
// #include <stdlib.h>
|
| 264 |
+
//
|
| 265 |
+
// static void myprint(char* s) {
|
| 266 |
+
// printf("%s\n", s);
|
| 267 |
+
// }
|
| 268 |
+
import "C"
|
| 269 |
+
import "unsafe"
|
| 270 |
+
|
| 271 |
+
func main() {
|
| 272 |
+
cs := C.CString("Hello from stdio")
|
| 273 |
+
C.myprint(cs)
|
| 274 |
+
C.free(unsafe.Pointer(cs))
|
| 275 |
+
}
|
| 276 |
+
|
| 277 |
+
A few special functions convert between Go and C types
|
| 278 |
+
by making copies of the data. In pseudo-Go definitions:
|
| 279 |
+
|
| 280 |
+
// Go string to C string
|
| 281 |
+
// The C string is allocated in the C heap using malloc.
|
| 282 |
+
// It is the caller's responsibility to arrange for it to be
|
| 283 |
+
// freed, such as by calling C.free (be sure to include stdlib.h
|
| 284 |
+
// if C.free is needed).
|
| 285 |
+
func C.CString(string) *C.char
|
| 286 |
+
|
| 287 |
+
// Go []byte slice to C array
|
| 288 |
+
// The C array is allocated in the C heap using malloc.
|
| 289 |
+
// It is the caller's responsibility to arrange for it to be
|
| 290 |
+
// freed, such as by calling C.free (be sure to include stdlib.h
|
| 291 |
+
// if C.free is needed).
|
| 292 |
+
func C.CBytes([]byte) unsafe.Pointer
|
| 293 |
+
|
| 294 |
+
// C string to Go string
|
| 295 |
+
func C.GoString(*C.char) string
|
| 296 |
+
|
| 297 |
+
// C data with explicit length to Go string
|
| 298 |
+
func C.GoStringN(*C.char, C.int) string
|
| 299 |
+
|
| 300 |
+
// C data with explicit length to Go []byte
|
| 301 |
+
func C.GoBytes(unsafe.Pointer, C.int) []byte
|
| 302 |
+
|
| 303 |
+
As a special case, C.malloc does not call the C library malloc directly
|
| 304 |
+
but instead calls a Go helper function that wraps the C library malloc
|
| 305 |
+
but guarantees never to return nil. If C's malloc indicates out of memory,
|
| 306 |
+
the helper function crashes the program, like when Go itself runs out
|
| 307 |
+
of memory. Because C.malloc cannot fail, it has no two-result form
|
| 308 |
+
that returns errno.
|
| 309 |
+
|
| 310 |
+
# C references to Go
|
| 311 |
+
|
| 312 |
+
Go functions can be exported for use by C code in the following way:
|
| 313 |
+
|
| 314 |
+
//export MyFunction
|
| 315 |
+
func MyFunction(arg1, arg2 int, arg3 string) int64 {...}
|
| 316 |
+
|
| 317 |
+
//export MyFunction2
|
| 318 |
+
func MyFunction2(arg1, arg2 int, arg3 string) (int64, *C.char) {...}
|
| 319 |
+
|
| 320 |
+
They will be available in the C code as:
|
| 321 |
+
|
| 322 |
+
extern GoInt64 MyFunction(int arg1, int arg2, GoString arg3);
|
| 323 |
+
extern struct MyFunction2_return MyFunction2(int arg1, int arg2, GoString arg3);
|
| 324 |
+
|
| 325 |
+
found in the _cgo_export.h generated header, after any preambles
|
| 326 |
+
copied from the cgo input files. Functions with multiple
|
| 327 |
+
return values are mapped to functions returning a struct.
|
| 328 |
+
|
| 329 |
+
Not all Go types can be mapped to C types in a useful way.
|
| 330 |
+
Go struct types are not supported; use a C struct type.
|
| 331 |
+
Go array types are not supported; use a C pointer.
|
| 332 |
+
|
| 333 |
+
Go functions that take arguments of type string may be called with the
|
| 334 |
+
C type _GoString_, described above. The _GoString_ type will be
|
| 335 |
+
automatically defined in the preamble. Note that there is no way for C
|
| 336 |
+
code to create a value of this type; this is only useful for passing
|
| 337 |
+
string values from Go to C and back to Go.
|
| 338 |
+
|
| 339 |
+
Using //export in a file places a restriction on the preamble:
|
| 340 |
+
since it is copied into two different C output files, it must not
|
| 341 |
+
contain any definitions, only declarations. If a file contains both
|
| 342 |
+
definitions and declarations, then the two output files will produce
|
| 343 |
+
duplicate symbols and the linker will fail. To avoid this, definitions
|
| 344 |
+
must be placed in preambles in other files, or in C source files.
|
| 345 |
+
|
| 346 |
+
# Passing pointers
|
| 347 |
+
|
| 348 |
+
Go is a garbage collected language, and the garbage collector needs to
|
| 349 |
+
know the location of every pointer to Go memory. Because of this,
|
| 350 |
+
there are restrictions on passing pointers between Go and C.
|
| 351 |
+
|
| 352 |
+
In this section the term Go pointer means a pointer to memory
|
| 353 |
+
allocated by Go (such as by using the & operator or calling the
|
| 354 |
+
predefined new function) and the term C pointer means a pointer to
|
| 355 |
+
memory allocated by C (such as by a call to C.malloc). Whether a
|
| 356 |
+
pointer is a Go pointer or a C pointer is a dynamic property
|
| 357 |
+
determined by how the memory was allocated; it has nothing to do with
|
| 358 |
+
the type of the pointer.
|
| 359 |
+
|
| 360 |
+
Note that values of some Go types, other than the type's zero value,
|
| 361 |
+
always include Go pointers. This is true of interface, channel, map,
|
| 362 |
+
and function types. A pointer type may hold a Go pointer or a C pointer.
|
| 363 |
+
Array, slice, string, and struct types may or may not include Go pointers,
|
| 364 |
+
depending on their type and how they are constructed. All the discussion
|
| 365 |
+
below about Go pointers applies not just to pointer types,
|
| 366 |
+
but also to other types that include Go pointers.
|
| 367 |
+
|
| 368 |
+
All Go pointers passed to C must point to pinned Go memory. Go pointers
|
| 369 |
+
passed as function arguments to C functions have the memory they point to
|
| 370 |
+
implicitly pinned for the duration of the call. Go memory reachable from
|
| 371 |
+
these function arguments must be pinned as long as the C code has access
|
| 372 |
+
to it. Whether Go memory is pinned is a dynamic property of that memory
|
| 373 |
+
region; it has nothing to do with the type of the pointer.
|
| 374 |
+
|
| 375 |
+
Go values created by calling new, by taking the address of a composite
|
| 376 |
+
literal, or by taking the address of a local variable may also have their
|
| 377 |
+
memory pinned using [runtime.Pinner]. This type may be used to manage
|
| 378 |
+
the duration of the memory's pinned status, potentially beyond the
|
| 379 |
+
duration of a C function call. Memory may be pinned more than once and
|
| 380 |
+
must be unpinned exactly the same number of times it has been pinned.
|
| 381 |
+
|
| 382 |
+
Go code may pass a Go pointer to C provided the memory to which it
|
| 383 |
+
points does not contain any Go pointers to memory that is unpinned. When
|
| 384 |
+
passing a pointer to a field in a struct, the Go memory in question is
|
| 385 |
+
the memory occupied by the field, not the entire struct. When passing a
|
| 386 |
+
pointer to an element in an array or slice, the Go memory in question is
|
| 387 |
+
the entire array or the entire backing array of the slice.
|
| 388 |
+
|
| 389 |
+
C code may keep a copy of a Go pointer only as long as the memory it
|
| 390 |
+
points to is pinned.
|
| 391 |
+
|
| 392 |
+
C code may not keep a copy of a Go pointer after the call returns,
|
| 393 |
+
unless the memory it points to is pinned with [runtime.Pinner] and the
|
| 394 |
+
Pinner is not unpinned while the Go pointer is stored in C memory.
|
| 395 |
+
This implies that C code may not keep a copy of a string, slice,
|
| 396 |
+
channel, and so forth, because they cannot be pinned with
|
| 397 |
+
[runtime.Pinner].
|
| 398 |
+
|
| 399 |
+
The _GoString_ type also may not be pinned with [runtime.Pinner].
|
| 400 |
+
Because it includes a Go pointer, the memory it points to is only pinned
|
| 401 |
+
for the duration of the call; _GoString_ values may not be retained by C
|
| 402 |
+
code.
|
| 403 |
+
|
| 404 |
+
A Go function called by C code may return a Go pointer to pinned memory
|
| 405 |
+
(which implies that it may not return a string, slice, channel, and so
|
| 406 |
+
forth). A Go function called by C code may take C pointers as arguments,
|
| 407 |
+
and it may store non-pointer data, C pointers, or Go pointers to pinned
|
| 408 |
+
memory through those pointers. It may not store a Go pointer to unpinned
|
| 409 |
+
memory in memory pointed to by a C pointer (which again, implies that it
|
| 410 |
+
may not store a string, slice, channel, and so forth). A Go function
|
| 411 |
+
called by C code may take a Go pointer but it must preserve the property
|
| 412 |
+
that the Go memory to which it points (and the Go memory to which that
|
| 413 |
+
memory points, and so on) is pinned.
|
| 414 |
+
|
| 415 |
+
These rules are checked dynamically at runtime. The checking is
|
| 416 |
+
controlled by the cgocheck setting of the GODEBUG environment
|
| 417 |
+
variable. The default setting is GODEBUG=cgocheck=1, which implements
|
| 418 |
+
reasonably cheap dynamic checks. These checks may be disabled
|
| 419 |
+
entirely using GODEBUG=cgocheck=0. Complete checking of pointer
|
| 420 |
+
handling, at some cost in run time, is available by setting
|
| 421 |
+
GOEXPERIMENT=cgocheck2 at build time.
|
| 422 |
+
|
| 423 |
+
It is possible to defeat this enforcement by using the unsafe package,
|
| 424 |
+
and of course there is nothing stopping the C code from doing anything
|
| 425 |
+
it likes. However, programs that break these rules are likely to fail
|
| 426 |
+
in unexpected and unpredictable ways.
|
| 427 |
+
|
| 428 |
+
The type [runtime/cgo.Handle] can be used to safely pass Go values
|
| 429 |
+
between Go and C.
|
| 430 |
+
|
| 431 |
+
Note: the current implementation has a bug. While Go code is permitted
|
| 432 |
+
to write nil or a C pointer (but not a Go pointer) to C memory, the
|
| 433 |
+
current implementation may sometimes cause a runtime error if the
|
| 434 |
+
contents of the C memory appear to be a Go pointer. Therefore, avoid
|
| 435 |
+
passing uninitialized C memory to Go code if the Go code is going to
|
| 436 |
+
store pointer values in it. Zero out the memory in C before passing it
|
| 437 |
+
to Go.
|
| 438 |
+
|
| 439 |
+
# Optimizing calls of C code
|
| 440 |
+
|
| 441 |
+
When passing a Go pointer to a C function the compiler normally ensures
|
| 442 |
+
that the Go object lives on the heap. If the C function does not keep
|
| 443 |
+
a copy of the Go pointer, and never passes the Go pointer back to Go code,
|
| 444 |
+
then this is unnecessary. The #cgo noescape directive may be used to tell
|
| 445 |
+
the compiler that no Go pointers escape via the named C function.
|
| 446 |
+
If the noescape directive is used and the C function does not handle the
|
| 447 |
+
pointer safely, the program may crash or see memory corruption.
|
| 448 |
+
|
| 449 |
+
For example:
|
| 450 |
+
|
| 451 |
+
// #cgo noescape cFunctionName
|
| 452 |
+
|
| 453 |
+
When a Go function calls a C function, it prepares for the C function to
|
| 454 |
+
call back to a Go function. The #cgo nocallback directive may be used to
|
| 455 |
+
tell the compiler that these preparations are not necessary.
|
| 456 |
+
If the nocallback directive is used and the C function does call back into
|
| 457 |
+
Go code, the program will panic.
|
| 458 |
+
|
| 459 |
+
For example:
|
| 460 |
+
|
| 461 |
+
// #cgo nocallback cFunctionName
|
| 462 |
+
|
| 463 |
+
# Special cases
|
| 464 |
+
|
| 465 |
+
A few special C types which would normally be represented by a pointer
|
| 466 |
+
type in Go are instead represented by a uintptr. Those include:
|
| 467 |
+
|
| 468 |
+
1. The *Ref types on Darwin, rooted at CoreFoundation's CFTypeRef type.
|
| 469 |
+
|
| 470 |
+
2. The object types from Java's JNI interface:
|
| 471 |
+
|
| 472 |
+
jobject
|
| 473 |
+
jclass
|
| 474 |
+
jthrowable
|
| 475 |
+
jstring
|
| 476 |
+
jarray
|
| 477 |
+
jbooleanArray
|
| 478 |
+
jbyteArray
|
| 479 |
+
jcharArray
|
| 480 |
+
jshortArray
|
| 481 |
+
jintArray
|
| 482 |
+
jlongArray
|
| 483 |
+
jfloatArray
|
| 484 |
+
jdoubleArray
|
| 485 |
+
jobjectArray
|
| 486 |
+
jweak
|
| 487 |
+
|
| 488 |
+
3. The EGLDisplay and EGLConfig types from the EGL API.
|
| 489 |
+
|
| 490 |
+
These types are uintptr on the Go side because they would otherwise
|
| 491 |
+
confuse the Go garbage collector; they are sometimes not really
|
| 492 |
+
pointers but data structures encoded in a pointer type. All operations
|
| 493 |
+
on these types must happen in C. The proper constant to initialize an
|
| 494 |
+
empty such reference is 0, not nil.
|
| 495 |
+
|
| 496 |
+
These special cases were introduced in Go 1.10. For auto-updating code
|
| 497 |
+
from Go 1.9 and earlier, use the cftype or jni rewrites in the Go fix tool:
|
| 498 |
+
|
| 499 |
+
go tool fix -r cftype <pkg>
|
| 500 |
+
go tool fix -r jni <pkg>
|
| 501 |
+
|
| 502 |
+
It will replace nil with 0 in the appropriate places.
|
| 503 |
+
|
| 504 |
+
The EGLDisplay case was introduced in Go 1.12. Use the egl rewrite
|
| 505 |
+
to auto-update code from Go 1.11 and earlier:
|
| 506 |
+
|
| 507 |
+
go tool fix -r egl <pkg>
|
| 508 |
+
|
| 509 |
+
The EGLConfig case was introduced in Go 1.15. Use the eglconf rewrite
|
| 510 |
+
to auto-update code from Go 1.14 and earlier:
|
| 511 |
+
|
| 512 |
+
go tool fix -r eglconf <pkg>
|
| 513 |
+
|
| 514 |
+
# Using cgo directly
|
| 515 |
+
|
| 516 |
+
Usage:
|
| 517 |
+
|
| 518 |
+
go tool cgo [cgo options] [-- compiler options] gofiles...
|
| 519 |
+
|
| 520 |
+
Cgo transforms the specified input Go source files into several output
|
| 521 |
+
Go and C source files.
|
| 522 |
+
|
| 523 |
+
The compiler options are passed through uninterpreted when
|
| 524 |
+
invoking the C compiler to compile the C parts of the package.
|
| 525 |
+
|
| 526 |
+
The following options are available when running cgo directly:
|
| 527 |
+
|
| 528 |
+
-V
|
| 529 |
+
Print cgo version and exit.
|
| 530 |
+
-debug-define
|
| 531 |
+
Debugging option. Print #defines.
|
| 532 |
+
-debug-gcc
|
| 533 |
+
Debugging option. Trace C compiler execution and output.
|
| 534 |
+
-dynimport file
|
| 535 |
+
Write list of symbols imported by file. Write to
|
| 536 |
+
-dynout argument or to standard output. Used by go
|
| 537 |
+
build when building a cgo package.
|
| 538 |
+
-dynlinker
|
| 539 |
+
Write dynamic linker as part of -dynimport output.
|
| 540 |
+
-dynout file
|
| 541 |
+
Write -dynimport output to file.
|
| 542 |
+
-dynpackage package
|
| 543 |
+
Set Go package for -dynimport output.
|
| 544 |
+
-exportheader file
|
| 545 |
+
If there are any exported functions, write the
|
| 546 |
+
generated export declarations to file.
|
| 547 |
+
C code can #include this to see the declarations.
|
| 548 |
+
-gccgo
|
| 549 |
+
Generate output for the gccgo compiler rather than the
|
| 550 |
+
gc compiler.
|
| 551 |
+
-gccgoprefix prefix
|
| 552 |
+
The -fgo-prefix option to be used with gccgo.
|
| 553 |
+
-gccgopkgpath path
|
| 554 |
+
The -fgo-pkgpath option to be used with gccgo.
|
| 555 |
+
-gccgo_define_cgoincomplete
|
| 556 |
+
Define cgo.Incomplete locally rather than importing it from
|
| 557 |
+
the "runtime/cgo" package. Used for old gccgo versions.
|
| 558 |
+
-godefs
|
| 559 |
+
Write out input file in Go syntax replacing C package
|
| 560 |
+
names with real values. Used to generate files in the
|
| 561 |
+
syscall package when bootstrapping a new target.
|
| 562 |
+
-importpath string
|
| 563 |
+
The import path for the Go package. Optional; used for
|
| 564 |
+
nicer comments in the generated files.
|
| 565 |
+
-import_runtime_cgo
|
| 566 |
+
If set (which it is by default) import runtime/cgo in
|
| 567 |
+
generated output.
|
| 568 |
+
-import_syscall
|
| 569 |
+
If set (which it is by default) import syscall in
|
| 570 |
+
generated output.
|
| 571 |
+
-ldflags flags
|
| 572 |
+
Flags to pass to the C linker. The cmd/go tool uses
|
| 573 |
+
this to pass in the flags in the CGO_LDFLAGS variable.
|
| 574 |
+
-objdir directory
|
| 575 |
+
Put all generated files in directory.
|
| 576 |
+
-srcdir directory
|
| 577 |
+
Find the Go input files, listed on the command line,
|
| 578 |
+
in directory.
|
| 579 |
+
-trimpath rewrites
|
| 580 |
+
Apply trims and rewrites to source file paths.
|
| 581 |
+
*/
|
| 582 |
+
package main
|
| 583 |
+
|
| 584 |
+
/*
|
| 585 |
+
Implementation details.
|
| 586 |
+
|
| 587 |
+
Cgo provides a way for Go programs to call C code linked into the same
|
| 588 |
+
address space. This comment explains the operation of cgo.
|
| 589 |
+
|
| 590 |
+
Cgo reads a set of Go source files and looks for statements saying
|
| 591 |
+
import "C". If the import has a doc comment, that comment is
|
| 592 |
+
taken as literal C code to be used as a preamble to any C code
|
| 593 |
+
generated by cgo. A typical preamble #includes necessary definitions:
|
| 594 |
+
|
| 595 |
+
// #include <stdio.h>
|
| 596 |
+
import "C"
|
| 597 |
+
|
| 598 |
+
For more details about the usage of cgo, see the documentation
|
| 599 |
+
comment at the top of this file.
|
| 600 |
+
|
| 601 |
+
Understanding C
|
| 602 |
+
|
| 603 |
+
Cgo scans the Go source files that import "C" for uses of that
|
| 604 |
+
package, such as C.puts. It collects all such identifiers. The next
|
| 605 |
+
step is to determine each kind of name. In C.xxx the xxx might refer
|
| 606 |
+
to a type, a function, a constant, or a global variable. Cgo must
|
| 607 |
+
decide which.
|
| 608 |
+
|
| 609 |
+
The obvious thing for cgo to do is to process the preamble, expanding
|
| 610 |
+
#includes and processing the corresponding C code. That would require
|
| 611 |
+
a full C parser and type checker that was also aware of any extensions
|
| 612 |
+
known to the system compiler (for example, all the GNU C extensions) as
|
| 613 |
+
well as the system-specific header locations and system-specific
|
| 614 |
+
pre-#defined macros. This is certainly possible to do, but it is an
|
| 615 |
+
enormous amount of work.
|
| 616 |
+
|
| 617 |
+
Cgo takes a different approach. It determines the meaning of C
|
| 618 |
+
identifiers not by parsing C code but by feeding carefully constructed
|
| 619 |
+
programs into the system C compiler and interpreting the generated
|
| 620 |
+
error messages, debug information, and object files. In practice,
|
| 621 |
+
parsing these is significantly less work and more robust than parsing
|
| 622 |
+
C source.
|
| 623 |
+
|
| 624 |
+
Cgo first invokes gcc -E -dM on the preamble, in order to find out
|
| 625 |
+
about simple #defines for constants and the like. These are recorded
|
| 626 |
+
for later use.
|
| 627 |
+
|
| 628 |
+
Next, cgo needs to identify the kinds for each identifier. For the
|
| 629 |
+
identifiers C.foo, cgo generates this C program:
|
| 630 |
+
|
| 631 |
+
<preamble>
|
| 632 |
+
#line 1 "not-declared"
|
| 633 |
+
void __cgo_f_1_1(void) { __typeof__(foo) *__cgo_undefined__1; }
|
| 634 |
+
#line 1 "not-type"
|
| 635 |
+
void __cgo_f_1_2(void) { foo *__cgo_undefined__2; }
|
| 636 |
+
#line 1 "not-int-const"
|
| 637 |
+
void __cgo_f_1_3(void) { enum { __cgo_undefined__3 = (foo)*1 }; }
|
| 638 |
+
#line 1 "not-num-const"
|
| 639 |
+
void __cgo_f_1_4(void) { static const double __cgo_undefined__4 = (foo); }
|
| 640 |
+
#line 1 "not-str-lit"
|
| 641 |
+
void __cgo_f_1_5(void) { static const char __cgo_undefined__5[] = (foo); }
|
| 642 |
+
|
| 643 |
+
This program will not compile, but cgo can use the presence or absence
|
| 644 |
+
of an error message on a given line to deduce the information it
|
| 645 |
+
needs. The program is syntactically valid regardless of whether each
|
| 646 |
+
name is a type or an ordinary identifier, so there will be no syntax
|
| 647 |
+
errors that might stop parsing early.
|
| 648 |
+
|
| 649 |
+
An error on not-declared:1 indicates that foo is undeclared.
|
| 650 |
+
An error on not-type:1 indicates that foo is not a type (if declared at all, it is an identifier).
|
| 651 |
+
An error on not-int-const:1 indicates that foo is not an integer constant.
|
| 652 |
+
An error on not-num-const:1 indicates that foo is not a number constant.
|
| 653 |
+
An error on not-str-lit:1 indicates that foo is not a string literal.
|
| 654 |
+
An error on not-signed-int-const:1 indicates that foo is not a signed integer constant.
|
| 655 |
+
|
| 656 |
+
The line number specifies the name involved. In the example, 1 is foo.
|
| 657 |
+
|
| 658 |
+
Next, cgo must learn the details of each type, variable, function, or
|
| 659 |
+
constant. It can do this by reading object files. If cgo has decided
|
| 660 |
+
that t1 is a type, v2 and v3 are variables or functions, and i4, i5
|
| 661 |
+
are integer constants, u6 is an unsigned integer constant, and f7 and f8
|
| 662 |
+
are float constants, and s9 and s10 are string constants, it generates:
|
| 663 |
+
|
| 664 |
+
<preamble>
|
| 665 |
+
__typeof__(t1) *__cgo__1;
|
| 666 |
+
__typeof__(v2) *__cgo__2;
|
| 667 |
+
__typeof__(v3) *__cgo__3;
|
| 668 |
+
__typeof__(i4) *__cgo__4;
|
| 669 |
+
enum { __cgo_enum__4 = i4 };
|
| 670 |
+
__typeof__(i5) *__cgo__5;
|
| 671 |
+
enum { __cgo_enum__5 = i5 };
|
| 672 |
+
__typeof__(u6) *__cgo__6;
|
| 673 |
+
enum { __cgo_enum__6 = u6 };
|
| 674 |
+
__typeof__(f7) *__cgo__7;
|
| 675 |
+
__typeof__(f8) *__cgo__8;
|
| 676 |
+
__typeof__(s9) *__cgo__9;
|
| 677 |
+
__typeof__(s10) *__cgo__10;
|
| 678 |
+
|
| 679 |
+
long long __cgodebug_ints[] = {
|
| 680 |
+
0, // t1
|
| 681 |
+
0, // v2
|
| 682 |
+
0, // v3
|
| 683 |
+
i4,
|
| 684 |
+
i5,
|
| 685 |
+
u6,
|
| 686 |
+
0, // f7
|
| 687 |
+
0, // f8
|
| 688 |
+
0, // s9
|
| 689 |
+
0, // s10
|
| 690 |
+
1
|
| 691 |
+
};
|
| 692 |
+
|
| 693 |
+
double __cgodebug_floats[] = {
|
| 694 |
+
0, // t1
|
| 695 |
+
0, // v2
|
| 696 |
+
0, // v3
|
| 697 |
+
0, // i4
|
| 698 |
+
0, // i5
|
| 699 |
+
0, // u6
|
| 700 |
+
f7,
|
| 701 |
+
f8,
|
| 702 |
+
0, // s9
|
| 703 |
+
0, // s10
|
| 704 |
+
1
|
| 705 |
+
};
|
| 706 |
+
|
| 707 |
+
const char __cgodebug_str__9[] = s9;
|
| 708 |
+
const unsigned long long __cgodebug_strlen__9 = sizeof(s9)-1;
|
| 709 |
+
const char __cgodebug_str__10[] = s10;
|
| 710 |
+
const unsigned long long __cgodebug_strlen__10 = sizeof(s10)-1;
|
| 711 |
+
|
| 712 |
+
and again invokes the system C compiler, to produce an object file
|
| 713 |
+
containing debug information. Cgo parses the DWARF debug information
|
| 714 |
+
for __cgo__N to learn the type of each identifier. (The types also
|
| 715 |
+
distinguish functions from global variables.) Cgo reads the constant
|
| 716 |
+
values from the __cgodebug_* from the object file's data segment.
|
| 717 |
+
|
| 718 |
+
At this point cgo knows the meaning of each C.xxx well enough to start
|
| 719 |
+
the translation process.
|
| 720 |
+
|
| 721 |
+
Translating Go
|
| 722 |
+
|
| 723 |
+
Given the input Go files x.go and y.go, cgo generates these source
|
| 724 |
+
files:
|
| 725 |
+
|
| 726 |
+
x.cgo1.go # for gc (cmd/compile)
|
| 727 |
+
y.cgo1.go # for gc
|
| 728 |
+
_cgo_gotypes.go # for gc
|
| 729 |
+
_cgo_import.go # for gc (if -dynout _cgo_import.go)
|
| 730 |
+
x.cgo2.c # for gcc
|
| 731 |
+
y.cgo2.c # for gcc
|
| 732 |
+
_cgo_defun.c # for gcc (if -gccgo)
|
| 733 |
+
_cgo_export.c # for gcc
|
| 734 |
+
_cgo_export.h # for gcc
|
| 735 |
+
_cgo_main.c # for gcc
|
| 736 |
+
_cgo_flags # for build tool (if -gccgo)
|
| 737 |
+
|
| 738 |
+
The file x.cgo1.go is a copy of x.go with the import "C" removed and
|
| 739 |
+
references to C.xxx replaced with names like _Cfunc_xxx or _Ctype_xxx.
|
| 740 |
+
The definitions of those identifiers, written as Go functions, types,
|
| 741 |
+
or variables, are provided in _cgo_gotypes.go.
|
| 742 |
+
|
| 743 |
+
Here is a _cgo_gotypes.go containing definitions for needed C types:
|
| 744 |
+
|
| 745 |
+
type _Ctype_char int8
|
| 746 |
+
type _Ctype_int int32
|
| 747 |
+
type _Ctype_void [0]byte
|
| 748 |
+
|
| 749 |
+
The _cgo_gotypes.go file also contains the definitions of the
|
| 750 |
+
functions. They all have similar bodies that invoke runtime·cgocall
|
| 751 |
+
to make a switch from the Go runtime world to the system C (GCC-based)
|
| 752 |
+
world.
|
| 753 |
+
|
| 754 |
+
For example, here is the definition of _Cfunc_puts:
|
| 755 |
+
|
| 756 |
+
//go:cgo_import_static _cgo_be59f0f25121_Cfunc_puts
|
| 757 |
+
//go:linkname __cgofn__cgo_be59f0f25121_Cfunc_puts _cgo_be59f0f25121_Cfunc_puts
|
| 758 |
+
var __cgofn__cgo_be59f0f25121_Cfunc_puts byte
|
| 759 |
+
var _cgo_be59f0f25121_Cfunc_puts = unsafe.Pointer(&__cgofn__cgo_be59f0f25121_Cfunc_puts)
|
| 760 |
+
|
| 761 |
+
func _Cfunc_puts(p0 *_Ctype_char) (r1 _Ctype_int) {
|
| 762 |
+
_cgo_runtime_cgocall(_cgo_be59f0f25121_Cfunc_puts, uintptr(unsafe.Pointer(&p0)))
|
| 763 |
+
return
|
| 764 |
+
}
|
| 765 |
+
|
| 766 |
+
The hexadecimal number is a hash of cgo's input, chosen to be
|
| 767 |
+
deterministic yet unlikely to collide with other uses. The actual
|
| 768 |
+
function _cgo_be59f0f25121_Cfunc_puts is implemented in a C source
|
| 769 |
+
file compiled by gcc, the file x.cgo2.c:
|
| 770 |
+
|
| 771 |
+
void
|
| 772 |
+
_cgo_be59f0f25121_Cfunc_puts(void *v)
|
| 773 |
+
{
|
| 774 |
+
struct {
|
| 775 |
+
char* p0;
|
| 776 |
+
int r;
|
| 777 |
+
char __pad12[4];
|
| 778 |
+
} __attribute__((__packed__, __gcc_struct__)) *a = v;
|
| 779 |
+
a->r = puts((void*)a->p0);
|
| 780 |
+
}
|
| 781 |
+
|
| 782 |
+
It extracts the arguments from the pointer to _Cfunc_puts's argument
|
| 783 |
+
frame, invokes the system C function (in this case, puts), stores the
|
| 784 |
+
result in the frame, and returns.
|
| 785 |
+
|
| 786 |
+
Linking
|
| 787 |
+
|
| 788 |
+
Once the _cgo_export.c and *.cgo2.c files have been compiled with gcc,
|
| 789 |
+
they need to be linked into the final binary, along with the libraries
|
| 790 |
+
they might depend on (in the case of puts, stdio). cmd/link has been
|
| 791 |
+
extended to understand basic ELF files, but it does not understand ELF
|
| 792 |
+
in the full complexity that modern C libraries embrace, so it cannot
|
| 793 |
+
in general generate direct references to the system libraries.
|
| 794 |
+
|
| 795 |
+
Instead, the build process generates an object file using dynamic
|
| 796 |
+
linkage to the desired libraries. The main function is provided by
|
| 797 |
+
_cgo_main.c:
|
| 798 |
+
|
| 799 |
+
int main(int argc, char **argv) { return 0; }
|
| 800 |
+
void crosscall2(void(*fn)(void*), void *a, int c, uintptr_t ctxt) { }
|
| 801 |
+
uintptr_t _cgo_wait_runtime_init_done(void) { return 0; }
|
| 802 |
+
void _cgo_release_context(uintptr_t ctxt) { }
|
| 803 |
+
char* _cgo_topofstack(void) { return (char*)0; }
|
| 804 |
+
void _cgo_allocate(void *a, int c) { }
|
| 805 |
+
void _cgo_panic(void *a, int c) { }
|
| 806 |
+
void _cgo_reginit(void) { }
|
| 807 |
+
|
| 808 |
+
The extra functions here are stubs to satisfy the references in the C
|
| 809 |
+
code generated for gcc. The build process links this stub, along with
|
| 810 |
+
_cgo_export.c and *.cgo2.c, into a dynamic executable and then lets
|
| 811 |
+
cgo examine the executable. Cgo records the list of shared library
|
| 812 |
+
references and resolved names and writes them into a new file
|
| 813 |
+
_cgo_import.go, which looks like:
|
| 814 |
+
|
| 815 |
+
//go:cgo_dynamic_linker "/lib64/ld-linux-x86-64.so.2"
|
| 816 |
+
//go:cgo_import_dynamic puts puts#GLIBC_2.2.5 "libc.so.6"
|
| 817 |
+
//go:cgo_import_dynamic __libc_start_main __libc_start_main#GLIBC_2.2.5 "libc.so.6"
|
| 818 |
+
//go:cgo_import_dynamic stdout stdout#GLIBC_2.2.5 "libc.so.6"
|
| 819 |
+
//go:cgo_import_dynamic fflush fflush#GLIBC_2.2.5 "libc.so.6"
|
| 820 |
+
//go:cgo_import_dynamic _ _ "libpthread.so.0"
|
| 821 |
+
//go:cgo_import_dynamic _ _ "libc.so.6"
|
| 822 |
+
|
| 823 |
+
In the end, the compiled Go package, which will eventually be
|
| 824 |
+
presented to cmd/link as part of a larger program, contains:
|
| 825 |
+
|
| 826 |
+
_go_.o # gc-compiled object for _cgo_gotypes.go, _cgo_import.go, *.cgo1.go
|
| 827 |
+
_all.o # gcc-compiled object for _cgo_export.c, *.cgo2.c
|
| 828 |
+
|
| 829 |
+
If there is an error generating the _cgo_import.go file, then, instead
|
| 830 |
+
of adding _cgo_import.go to the package, the go tool adds an empty
|
| 831 |
+
file named dynimportfail. The _cgo_import.go file is only needed when
|
| 832 |
+
using internal linking mode, which is not the default when linking
|
| 833 |
+
programs that use cgo (as described below). If the linker sees a file
|
| 834 |
+
named dynimportfail it reports an error if it has been told to use
|
| 835 |
+
internal linking mode. This approach is taken because generating
|
| 836 |
+
_cgo_import.go requires doing a full C link of the package, which can
|
| 837 |
+
fail for reasons that are irrelevant when using external linking mode.
|
| 838 |
+
|
| 839 |
+
The final program will be a dynamic executable, so that cmd/link can avoid
|
| 840 |
+
needing to process arbitrary .o files. It only needs to process the .o
|
| 841 |
+
files generated from C files that cgo writes, and those are much more
|
| 842 |
+
limited in the ELF or other features that they use.
|
| 843 |
+
|
| 844 |
+
In essence, the _cgo_import.o file includes the extra linking
|
| 845 |
+
directives that cmd/link is not sophisticated enough to derive from _all.o
|
| 846 |
+
on its own. Similarly, the _all.o uses dynamic references to real
|
| 847 |
+
system object code because cmd/link is not sophisticated enough to process
|
| 848 |
+
the real code.
|
| 849 |
+
|
| 850 |
+
The main benefits of this system are that cmd/link remains relatively simple
|
| 851 |
+
(it does not need to implement a complete ELF and Mach-O linker) and
|
| 852 |
+
that gcc is not needed after the package is compiled. For example,
|
| 853 |
+
package net uses cgo for access to name resolution functions provided
|
| 854 |
+
by libc. Although gcc is needed to compile package net, gcc is not
|
| 855 |
+
needed to link programs that import package net.
|
| 856 |
+
|
| 857 |
+
Runtime
|
| 858 |
+
|
| 859 |
+
When using cgo, Go must not assume that it owns all details of the
|
| 860 |
+
process. In particular it needs to coordinate with C in the use of
|
| 861 |
+
threads and thread-local storage. The runtime package declares a few
|
| 862 |
+
variables:
|
| 863 |
+
|
| 864 |
+
var (
|
| 865 |
+
iscgo bool
|
| 866 |
+
_cgo_init unsafe.Pointer
|
| 867 |
+
_cgo_thread_start unsafe.Pointer
|
| 868 |
+
)
|
| 869 |
+
|
| 870 |
+
Any package using cgo imports "runtime/cgo", which provides
|
| 871 |
+
initializations for these variables. It sets iscgo to true, _cgo_init
|
| 872 |
+
to a gcc-compiled function that can be called early during program
|
| 873 |
+
startup, and _cgo_thread_start to a gcc-compiled function that can be
|
| 874 |
+
used to create a new thread, in place of the runtime's usual direct
|
| 875 |
+
system calls.
|
| 876 |
+
|
| 877 |
+
Internal and External Linking
|
| 878 |
+
|
| 879 |
+
The text above describes "internal" linking, in which cmd/link parses and
|
| 880 |
+
links host object files (ELF, Mach-O, PE, and so on) into the final
|
| 881 |
+
executable itself. Keeping cmd/link simple means we cannot possibly
|
| 882 |
+
implement the full semantics of the host linker, so the kinds of
|
| 883 |
+
objects that can be linked directly into the binary is limited (other
|
| 884 |
+
code can only be used as a dynamic library). On the other hand, when
|
| 885 |
+
using internal linking, cmd/link can generate Go binaries by itself.
|
| 886 |
+
|
| 887 |
+
In order to allow linking arbitrary object files without requiring
|
| 888 |
+
dynamic libraries, cgo supports an "external" linking mode too. In
|
| 889 |
+
external linking mode, cmd/link does not process any host object files.
|
| 890 |
+
Instead, it collects all the Go code and writes a single go.o object
|
| 891 |
+
file containing it. Then it invokes the host linker (usually gcc) to
|
| 892 |
+
combine the go.o object file and any supporting non-Go code into a
|
| 893 |
+
final executable. External linking avoids the dynamic library
|
| 894 |
+
requirement but introduces a requirement that the host linker be
|
| 895 |
+
present to create such a binary.
|
| 896 |
+
|
| 897 |
+
Most builds both compile source code and invoke the linker to create a
|
| 898 |
+
binary. When cgo is involved, the compile step already requires gcc, so
|
| 899 |
+
it is not problematic for the link step to require gcc too.
|
| 900 |
+
|
| 901 |
+
An important exception is builds using a pre-compiled copy of the
|
| 902 |
+
standard library. In particular, package net uses cgo on most systems,
|
| 903 |
+
and we want to preserve the ability to compile pure Go code that
|
| 904 |
+
imports net without requiring gcc to be present at link time. (In this
|
| 905 |
+
case, the dynamic library requirement is less significant, because the
|
| 906 |
+
only library involved is libc.so, which can usually be assumed
|
| 907 |
+
present.)
|
| 908 |
+
|
| 909 |
+
This conflict between functionality and the gcc requirement means we
|
| 910 |
+
must support both internal and external linking, depending on the
|
| 911 |
+
circumstances: if net is the only cgo-using package, then internal
|
| 912 |
+
linking is probably fine, but if other packages are involved, so that there
|
| 913 |
+
are dependencies on libraries beyond libc, external linking is likely
|
| 914 |
+
to work better. The compilation of a package records the relevant
|
| 915 |
+
information to support both linking modes, leaving the decision
|
| 916 |
+
to be made when linking the final binary.
|
| 917 |
+
|
| 918 |
+
Linking Directives
|
| 919 |
+
|
| 920 |
+
In either linking mode, package-specific directives must be passed
|
| 921 |
+
through to cmd/link. These are communicated by writing //go: directives in a
|
| 922 |
+
Go source file compiled by gc. The directives are copied into the .o
|
| 923 |
+
object file and then processed by the linker.
|
| 924 |
+
|
| 925 |
+
The directives are:
|
| 926 |
+
|
| 927 |
+
//go:cgo_import_dynamic <local> [<remote> ["<library>"]]
|
| 928 |
+
|
| 929 |
+
In internal linking mode, allow an unresolved reference to
|
| 930 |
+
<local>, assuming it will be resolved by a dynamic library
|
| 931 |
+
symbol. The optional <remote> specifies the symbol's name and
|
| 932 |
+
possibly version in the dynamic library, and the optional "<library>"
|
| 933 |
+
names the specific library where the symbol should be found.
|
| 934 |
+
|
| 935 |
+
On AIX, the library pattern is slightly different. It must be
|
| 936 |
+
"lib.a/obj.o" with obj.o the member of this library exporting
|
| 937 |
+
this symbol.
|
| 938 |
+
|
| 939 |
+
In the <remote>, # or @ can be used to introduce a symbol version.
|
| 940 |
+
|
| 941 |
+
Examples:
|
| 942 |
+
//go:cgo_import_dynamic puts
|
| 943 |
+
//go:cgo_import_dynamic puts puts#GLIBC_2.2.5
|
| 944 |
+
//go:cgo_import_dynamic puts puts#GLIBC_2.2.5 "libc.so.6"
|
| 945 |
+
|
| 946 |
+
A side effect of the cgo_import_dynamic directive with a
|
| 947 |
+
library is to make the final binary depend on that dynamic
|
| 948 |
+
library. To get the dependency without importing any specific
|
| 949 |
+
symbols, use _ for local and remote.
|
| 950 |
+
|
| 951 |
+
Example:
|
| 952 |
+
//go:cgo_import_dynamic _ _ "libc.so.6"
|
| 953 |
+
|
| 954 |
+
For compatibility with current versions of SWIG,
|
| 955 |
+
#pragma dynimport is an alias for //go:cgo_import_dynamic.
|
| 956 |
+
|
| 957 |
+
//go:cgo_dynamic_linker "<path>"
|
| 958 |
+
|
| 959 |
+
In internal linking mode, use "<path>" as the dynamic linker
|
| 960 |
+
in the final binary. This directive is only needed from one
|
| 961 |
+
package when constructing a binary; by convention it is
|
| 962 |
+
supplied by runtime/cgo.
|
| 963 |
+
|
| 964 |
+
Example:
|
| 965 |
+
//go:cgo_dynamic_linker "/lib/ld-linux.so.2"
|
| 966 |
+
|
| 967 |
+
//go:cgo_export_dynamic <local> <remote>
|
| 968 |
+
|
| 969 |
+
In internal linking mode, put the Go symbol
|
| 970 |
+
named <local> into the program's exported symbol table as
|
| 971 |
+
<remote>, so that C code can refer to it by that name. This
|
| 972 |
+
mechanism makes it possible for C code to call back into Go or
|
| 973 |
+
to share Go's data.
|
| 974 |
+
|
| 975 |
+
For compatibility with current versions of SWIG,
|
| 976 |
+
#pragma dynexport is an alias for //go:cgo_export_dynamic.
|
| 977 |
+
|
| 978 |
+
//go:cgo_import_static <local>
|
| 979 |
+
|
| 980 |
+
In external linking mode, allow unresolved references to
|
| 981 |
+
<local> in the go.o object file prepared for the host linker,
|
| 982 |
+
under the assumption that <local> will be supplied by the
|
| 983 |
+
other object files that will be linked with go.o.
|
| 984 |
+
|
| 985 |
+
Example:
|
| 986 |
+
//go:cgo_import_static puts_wrapper
|
| 987 |
+
|
| 988 |
+
//go:cgo_export_static <local> <remote>
|
| 989 |
+
|
| 990 |
+
In external linking mode, put the Go symbol
|
| 991 |
+
named <local> into the program's exported symbol table as
|
| 992 |
+
<remote>, so that C code can refer to it by that name. This
|
| 993 |
+
mechanism makes it possible for C code to call back into Go or
|
| 994 |
+
to share Go's data.
|
| 995 |
+
|
| 996 |
+
//go:cgo_ldflag "<arg>"
|
| 997 |
+
|
| 998 |
+
In external linking mode, invoke the host linker (usually gcc)
|
| 999 |
+
with "<arg>" as a command-line argument following the .o files.
|
| 1000 |
+
Note that the arguments are for "gcc", not "ld".
|
| 1001 |
+
|
| 1002 |
+
Example:
|
| 1003 |
+
//go:cgo_ldflag "-lpthread"
|
| 1004 |
+
//go:cgo_ldflag "-L/usr/local/sqlite3/lib"
|
| 1005 |
+
|
| 1006 |
+
A package compiled with cgo will include directives for both
|
| 1007 |
+
internal and external linking; the linker will select the appropriate
|
| 1008 |
+
subset for the chosen linking mode.
|
| 1009 |
+
|
| 1010 |
+
Example
|
| 1011 |
+
|
| 1012 |
+
As a simple example, consider a package that uses cgo to call C.sin.
|
| 1013 |
+
The following code will be generated by cgo:
|
| 1014 |
+
|
| 1015 |
+
// compiled by gc
|
| 1016 |
+
|
| 1017 |
+
//go:cgo_ldflag "-lm"
|
| 1018 |
+
|
| 1019 |
+
type _Ctype_double float64
|
| 1020 |
+
|
| 1021 |
+
//go:cgo_import_static _cgo_gcc_Cfunc_sin
|
| 1022 |
+
//go:linkname __cgo_gcc_Cfunc_sin _cgo_gcc_Cfunc_sin
|
| 1023 |
+
var __cgo_gcc_Cfunc_sin byte
|
| 1024 |
+
var _cgo_gcc_Cfunc_sin = unsafe.Pointer(&__cgo_gcc_Cfunc_sin)
|
| 1025 |
+
|
| 1026 |
+
func _Cfunc_sin(p0 _Ctype_double) (r1 _Ctype_double) {
|
| 1027 |
+
_cgo_runtime_cgocall(_cgo_gcc_Cfunc_sin, uintptr(unsafe.Pointer(&p0)))
|
| 1028 |
+
return
|
| 1029 |
+
}
|
| 1030 |
+
|
| 1031 |
+
// compiled by gcc, into foo.cgo2.o
|
| 1032 |
+
|
| 1033 |
+
void
|
| 1034 |
+
_cgo_gcc_Cfunc_sin(void *v)
|
| 1035 |
+
{
|
| 1036 |
+
struct {
|
| 1037 |
+
double p0;
|
| 1038 |
+
double r;
|
| 1039 |
+
} __attribute__((__packed__)) *a = v;
|
| 1040 |
+
a->r = sin(a->p0);
|
| 1041 |
+
}
|
| 1042 |
+
|
| 1043 |
+
What happens at link time depends on whether the final binary is linked
|
| 1044 |
+
using the internal or external mode. If other packages are compiled in
|
| 1045 |
+
"external only" mode, then the final link will be an external one.
|
| 1046 |
+
Otherwise the link will be an internal one.
|
| 1047 |
+
|
| 1048 |
+
The linking directives are used according to the kind of final link
|
| 1049 |
+
used.
|
| 1050 |
+
|
| 1051 |
+
In internal mode, cmd/link itself processes all the host object files, in
|
| 1052 |
+
particular foo.cgo2.o. To do so, it uses the cgo_import_dynamic and
|
| 1053 |
+
cgo_dynamic_linker directives to learn that the otherwise undefined
|
| 1054 |
+
reference to sin in foo.cgo2.o should be rewritten to refer to the
|
| 1055 |
+
symbol sin with version GLIBC_2.2.5 from the dynamic library
|
| 1056 |
+
"libm.so.6", and the binary should request "/lib/ld-linux.so.2" as its
|
| 1057 |
+
runtime dynamic linker.
|
| 1058 |
+
|
| 1059 |
+
In external mode, cmd/link does not process any host object files, in
|
| 1060 |
+
particular foo.cgo2.o. It links together the gc-generated object
|
| 1061 |
+
files, along with any other Go code, into a go.o file. While doing
|
| 1062 |
+
that, cmd/link will discover that there is no definition for
|
| 1063 |
+
_cgo_gcc_Cfunc_sin, referred to by the gc-compiled source file. This
|
| 1064 |
+
is okay, because cmd/link also processes the cgo_import_static directive and
|
| 1065 |
+
knows that _cgo_gcc_Cfunc_sin is expected to be supplied by a host
|
| 1066 |
+
object file, so cmd/link does not treat the missing symbol as an error when
|
| 1067 |
+
creating go.o. Indeed, the definition for _cgo_gcc_Cfunc_sin will be
|
| 1068 |
+
provided to the host linker by foo2.cgo.o, which in turn will need the
|
| 1069 |
+
symbol 'sin'. cmd/link also processes the cgo_ldflag directives, so that it
|
| 1070 |
+
knows that the eventual host link command must include the -lm
|
| 1071 |
+
argument, so that the host linker will be able to find 'sin' in the
|
| 1072 |
+
math library.
|
| 1073 |
+
|
| 1074 |
+
cmd/link Command Line Interface
|
| 1075 |
+
|
| 1076 |
+
The go command and any other Go-aware build systems invoke cmd/link
|
| 1077 |
+
to link a collection of packages into a single binary. By default, cmd/link will
|
| 1078 |
+
present the same interface it does today:
|
| 1079 |
+
|
| 1080 |
+
cmd/link main.a
|
| 1081 |
+
|
| 1082 |
+
produces a file named a.out, even if cmd/link does so by invoking the host
|
| 1083 |
+
linker in external linking mode.
|
| 1084 |
+
|
| 1085 |
+
By default, cmd/link will decide the linking mode as follows: if the only
|
| 1086 |
+
packages using cgo are those on a list of known standard library
|
| 1087 |
+
packages (net, os/user, runtime/cgo), cmd/link will use internal linking
|
| 1088 |
+
mode. Otherwise, there are non-standard cgo packages involved, and cmd/link
|
| 1089 |
+
will use external linking mode. The first rule means that a build of
|
| 1090 |
+
the godoc binary, which uses net but no other cgo, can run without
|
| 1091 |
+
needing gcc available. The second rule means that a build of a
|
| 1092 |
+
cgo-wrapped library like sqlite3 can generate a standalone executable
|
| 1093 |
+
instead of needing to refer to a dynamic library. The specific choice
|
| 1094 |
+
can be overridden using a command line flag: cmd/link -linkmode=internal or
|
| 1095 |
+
cmd/link -linkmode=external.
|
| 1096 |
+
|
| 1097 |
+
In an external link, cmd/link will create a temporary directory, write any
|
| 1098 |
+
host object files found in package archives to that directory (renamed
|
| 1099 |
+
to avoid conflicts), write the go.o file to that directory, and invoke
|
| 1100 |
+
the host linker. The default value for the host linker is $CC, split
|
| 1101 |
+
into fields, or else "gcc". The specific host linker command line can
|
| 1102 |
+
be overridden using command line flags: cmd/link -extld=clang
|
| 1103 |
+
-extldflags='-ggdb -O3'. If any package in a build includes a .cc or
|
| 1104 |
+
other file compiled by the C++ compiler, the go tool will use the
|
| 1105 |
+
-extld option to set the host linker to the C++ compiler.
|
| 1106 |
+
|
| 1107 |
+
These defaults mean that Go-aware build systems can ignore the linking
|
| 1108 |
+
changes and keep running plain 'cmd/link' and get reasonable results, but
|
| 1109 |
+
they can also control the linking details if desired.
|
| 1110 |
+
|
| 1111 |
+
*/
|
go/src/cmd/cgo/gcc.go
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
go/src/cmd/cgo/godefs.go
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Copyright 2011 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 |
+
package main
|
| 6 |
+
|
| 7 |
+
import (
|
| 8 |
+
"fmt"
|
| 9 |
+
"go/ast"
|
| 10 |
+
"go/printer"
|
| 11 |
+
"go/token"
|
| 12 |
+
"os"
|
| 13 |
+
"path/filepath"
|
| 14 |
+
"strings"
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
// godefs returns the output for -godefs mode.
|
| 18 |
+
func (p *Package) godefs(f *File, args []string) string {
|
| 19 |
+
var buf strings.Builder
|
| 20 |
+
|
| 21 |
+
fmt.Fprintf(&buf, "// Code generated by cmd/cgo -godefs; DO NOT EDIT.\n")
|
| 22 |
+
fmt.Fprintf(&buf, "// %s %s\n", filepath.Base(args[0]), strings.Join(args[1:], " "))
|
| 23 |
+
fmt.Fprintf(&buf, "\n")
|
| 24 |
+
|
| 25 |
+
override := make(map[string]string)
|
| 26 |
+
|
| 27 |
+
// Allow source file to specify override mappings.
|
| 28 |
+
// For example, the socket data structures refer
|
| 29 |
+
// to in_addr and in_addr6 structs but we want to be
|
| 30 |
+
// able to treat them as byte arrays, so the godefs
|
| 31 |
+
// inputs in package syscall say
|
| 32 |
+
//
|
| 33 |
+
// // +godefs map struct_in_addr [4]byte
|
| 34 |
+
// // +godefs map struct_in_addr6 [16]byte
|
| 35 |
+
//
|
| 36 |
+
for _, g := range f.Comments {
|
| 37 |
+
for _, c := range g.List {
|
| 38 |
+
i := strings.Index(c.Text, "+godefs map")
|
| 39 |
+
if i < 0 {
|
| 40 |
+
continue
|
| 41 |
+
}
|
| 42 |
+
s := strings.TrimSpace(c.Text[i+len("+godefs map"):])
|
| 43 |
+
i = strings.Index(s, " ")
|
| 44 |
+
if i < 0 {
|
| 45 |
+
fmt.Fprintf(os.Stderr, "invalid +godefs map comment: %s\n", c.Text)
|
| 46 |
+
continue
|
| 47 |
+
}
|
| 48 |
+
override["_Ctype_"+strings.TrimSpace(s[:i])] = strings.TrimSpace(s[i:])
|
| 49 |
+
}
|
| 50 |
+
}
|
| 51 |
+
for _, n := range f.Name {
|
| 52 |
+
if s := override[n.Go]; s != "" {
|
| 53 |
+
override[n.Mangle] = s
|
| 54 |
+
}
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
// Otherwise, if the source file says type T C.whatever,
|
| 58 |
+
// use "T" as the mangling of C.whatever,
|
| 59 |
+
// except in the definition (handled at end of function).
|
| 60 |
+
refName := make(map[*ast.Expr]*Name)
|
| 61 |
+
for _, r := range f.Ref {
|
| 62 |
+
refName[r.Expr] = r.Name
|
| 63 |
+
}
|
| 64 |
+
for _, d := range f.AST.Decls {
|
| 65 |
+
d, ok := d.(*ast.GenDecl)
|
| 66 |
+
if !ok || d.Tok != token.TYPE {
|
| 67 |
+
continue
|
| 68 |
+
}
|
| 69 |
+
for _, s := range d.Specs {
|
| 70 |
+
s := s.(*ast.TypeSpec)
|
| 71 |
+
n := refName[&s.Type]
|
| 72 |
+
if n != nil && n.Mangle != "" {
|
| 73 |
+
override[n.Mangle] = s.Name.Name
|
| 74 |
+
}
|
| 75 |
+
}
|
| 76 |
+
}
|
| 77 |
+
|
| 78 |
+
// Extend overrides using typedefs:
|
| 79 |
+
// If we know that C.xxx should format as T
|
| 80 |
+
// and xxx is a typedef for yyy, make C.yyy format as T.
|
| 81 |
+
for typ, def := range typedef {
|
| 82 |
+
if new := override[typ]; new != "" {
|
| 83 |
+
if id, ok := def.Go.(*ast.Ident); ok {
|
| 84 |
+
override[id.Name] = new
|
| 85 |
+
}
|
| 86 |
+
}
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
// Apply overrides.
|
| 90 |
+
for old, new := range override {
|
| 91 |
+
if id := goIdent[old]; id != nil {
|
| 92 |
+
id.Name = new
|
| 93 |
+
}
|
| 94 |
+
}
|
| 95 |
+
|
| 96 |
+
// Any names still using the _C syntax are not going to compile,
|
| 97 |
+
// although in general we don't know whether they all made it
|
| 98 |
+
// into the file, so we can't warn here.
|
| 99 |
+
//
|
| 100 |
+
// The most common case is union types, which begin with
|
| 101 |
+
// _Ctype_union and for which typedef[name] is a Go byte
|
| 102 |
+
// array of the appropriate size (such as [4]byte).
|
| 103 |
+
// Substitute those union types with byte arrays.
|
| 104 |
+
for name, id := range goIdent {
|
| 105 |
+
if id.Name == name && strings.Contains(name, "_Ctype_union") {
|
| 106 |
+
if def := typedef[name]; def != nil {
|
| 107 |
+
id.Name = gofmt(def)
|
| 108 |
+
}
|
| 109 |
+
}
|
| 110 |
+
}
|
| 111 |
+
|
| 112 |
+
conf.Fprint(&buf, fset, f.AST)
|
| 113 |
+
|
| 114 |
+
return buf.String()
|
| 115 |
+
}
|
| 116 |
+
|
| 117 |
+
var gofmtBuf strings.Builder
|
| 118 |
+
|
| 119 |
+
// gofmt returns the gofmt-formatted string for an AST node.
|
| 120 |
+
func gofmt(n any) string {
|
| 121 |
+
gofmtBuf.Reset()
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Copyright 2009 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 |
+
// Cgo; see doc.go for an overview.
|
| 6 |
+
|
| 7 |
+
// TODO(rsc):
|
| 8 |
+
// Emit correct line number annotations.
|
| 9 |
+
// Make gc understand the annotations.
|
| 10 |
+
|
| 11 |
+
package main
|
| 12 |
+
|
| 13 |
+
import (
|
| 14 |
+
"flag"
|
| 15 |
+
"fmt"
|
| 16 |
+
"go/ast"
|
| 17 |
+
"go/printer"
|
| 18 |
+
"go/token"
|
| 19 |
+
"internal/buildcfg"
|
| 20 |
+
"io"
|
| 21 |
+
"maps"
|
| 22 |
+
"os"
|
| 23 |
+
"path/filepath"
|
| 24 |
+
"reflect"
|
| 25 |
+
"runtime"
|
| 26 |
+
"sort"
|
| 27 |
+
"strings"
|
| 28 |
+
"sync"
|
| 29 |
+
|
| 30 |
+
"cmd/internal/edit"
|
| 31 |
+
"cmd/internal/hash"
|
| 32 |
+
"cmd/internal/objabi"
|
| 33 |
+
"cmd/internal/par"
|
| 34 |
+
"cmd/internal/telemetry/counter"
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
// A Package collects information about the package we're going to write.
|
| 38 |
+
type Package struct {
|
| 39 |
+
PackageName string // name of package
|
| 40 |
+
PackagePath string
|
| 41 |
+
PtrSize int64
|
| 42 |
+
IntSize int64
|
| 43 |
+
GccOptions []string
|
| 44 |
+
GccIsClang bool
|
| 45 |
+
LdFlags []string // #cgo LDFLAGS
|
| 46 |
+
Written map[string]bool
|
| 47 |
+
Name map[string]*Name // accumulated Name from Files
|
| 48 |
+
ExpFunc []*ExpFunc // accumulated ExpFunc from Files
|
| 49 |
+
Decl []ast.Decl
|
| 50 |
+
GoFiles []string // list of Go files
|
| 51 |
+
GccFiles []string // list of gcc output files
|
| 52 |
+
Preamble string // collected preamble for _cgo_export.h
|
| 53 |
+
noCallbacks map[string]bool // C function names with #cgo nocallback directive
|
| 54 |
+
noEscapes map[string]bool // C function names with #cgo noescape directive
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
// A typedefInfo is an element on Package.typedefList: a typedef name
|
| 58 |
+
// and the position where it was required.
|
| 59 |
+
type typedefInfo struct {
|
| 60 |
+
typedef string
|
| 61 |
+
pos token.Pos
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
// A File collects information about a single Go input file.
|
| 65 |
+
type File struct {
|
| 66 |
+
AST *ast.File // parsed AST
|
| 67 |
+
Comments []*ast.CommentGroup // comments from file
|
| 68 |
+
Package string // Package name
|
| 69 |
+
Preamble string // C preamble (doc comment on import "C")
|
| 70 |
+
Ref []*Ref // all references to C.xxx in AST
|
| 71 |
+
Calls []*Call // all calls to C.xxx in AST
|
| 72 |
+
ExpFunc []*ExpFunc // exported functions for this file
|
| 73 |
+
Name map[string]*Name // map from Go name to Name
|
| 74 |
+
NamePos map[*Name]token.Pos // map from Name to position of the first reference
|
| 75 |
+
NoCallbacks map[string]bool // C function names with #cgo nocallback directive
|
| 76 |
+
NoEscapes map[string]bool // C function names with #cgo noescape directive
|
| 77 |
+
Edit *edit.Buffer
|
| 78 |
+
|
| 79 |
+
debugs []*debug // debug data from iterations of gccDebug. Initialized by File.loadDebug.
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
func (f *File) offset(p token.Pos) int {
|
| 83 |
+
return fset.Position(p).Offset
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
func nameKeys(m map[string]*Name) []string {
|
| 87 |
+
ks := make([]string, 0, len(m))
|
| 88 |
+
for k := range m {
|
| 89 |
+
ks = append(ks, k)
|
| 90 |
+
}
|
| 91 |
+
sort.Strings(ks)
|
| 92 |
+
return ks
|
| 93 |
+
}
|
| 94 |
+
|
| 95 |
+
// A Call refers to a call of a C.xxx function in the AST.
|
| 96 |
+
type Call struct {
|
| 97 |
+
Call *ast.CallExpr
|
| 98 |
+
Deferred bool
|
| 99 |
+
Done bool
|
| 100 |
+
}
|
| 101 |
+
|
| 102 |
+
// A Ref refers to an expression of the form C.xxx in the AST.
|
| 103 |
+
type Ref struct {
|
| 104 |
+
Name *Name
|
| 105 |
+
Expr *ast.Expr
|
| 106 |
+
Context astContext
|
| 107 |
+
Done bool
|
| 108 |
+
}
|
| 109 |
+
|
| 110 |
+
func (r *Ref) Pos() token.Pos {
|
| 111 |
+
return (*r.Expr).Pos()
|
| 112 |
+
}
|
| 113 |
+
|
| 114 |
+
var nameKinds = []string{"iconst", "fconst", "sconst", "type", "var", "fpvar", "func", "macro", "not-type"}
|
| 115 |
+
|
| 116 |
+
// A Name collects information about C.xxx.
|
| 117 |
+
type Name struct {
|
| 118 |
+
Go string // name used in Go referring to package C
|
| 119 |
+
Mangle string // name used in generated Go
|
| 120 |
+
C string // name used in C
|
| 121 |
+
Define string // #define expansion
|
| 122 |
+
Kind string // one of the nameKinds
|
| 123 |
+
Type *Type // the type of xxx
|
| 124 |
+
FuncType *FuncType
|
| 125 |
+
AddError bool
|
| 126 |
+
Const string // constant definition
|
| 127 |
+
}
|
| 128 |
+
|
| 129 |
+
// IsVar reports whether Kind is either "var" or "fpvar"
|
| 130 |
+
func (n *Name) IsVar() bool {
|
| 131 |
+
return n.Kind == "var" || n.Kind == "fpvar"
|
| 132 |
+
}
|
| 133 |
+
|
| 134 |
+
// IsConst reports whether Kind is either "iconst", "fconst" or "sconst"
|
| 135 |
+
func (n *Name) IsConst() bool {
|
| 136 |
+
return strings.HasSuffix(n.Kind, "const")
|
| 137 |
+
}
|
| 138 |
+
|
| 139 |
+
// An ExpFunc is an exported function, callable from C.
|
| 140 |
+
// Such functions are identified in the Go input file
|
| 141 |
+
// by doc comments containing the line //export ExpName
|
| 142 |
+
type ExpFunc struct {
|
| 143 |
+
Func *ast.FuncDecl
|
| 144 |
+
ExpName string // name to use from C
|
| 145 |
+
Doc string
|
| 146 |
+
}
|
| 147 |
+
|
| 148 |
+
// A TypeRepr contains the string representation of a type.
|
| 149 |
+
type TypeRepr struct {
|
| 150 |
+
Repr string
|
| 151 |
+
FormatArgs []any
|
| 152 |
+
}
|
| 153 |
+
|
| 154 |
+
// A Type collects information about a type in both the C and Go worlds.
|
| 155 |
+
type Type struct {
|
| 156 |
+
Size int64
|
| 157 |
+
Align int64
|
| 158 |
+
C *TypeRepr
|
| 159 |
+
Go ast.Expr
|
| 160 |
+
EnumValues map[string]int64
|
| 161 |
+
Typedef string
|
| 162 |
+
BadPointer bool // this pointer type should be represented as a uintptr (deprecated)
|
| 163 |
+
}
|
| 164 |
+
|
| 165 |
+
func (t *Type) fuzzyMatch(t2 *Type) bool {
|
| 166 |
+
if t == nil || t2 == nil {
|
| 167 |
+
return false
|
| 168 |
+
}
|
| 169 |
+
return t.Size == t2.Size && t.Align == t2.Align
|
| 170 |
+
}
|
| 171 |
+
|
| 172 |
+
// A FuncType collects information about a function type in both the C and Go worlds.
|
| 173 |
+
type FuncType struct {
|
| 174 |
+
Params []*Type
|
| 175 |
+
Result *Type
|
| 176 |
+
Go *ast.FuncType
|
| 177 |
+
}
|
| 178 |
+
|
| 179 |
+
func (t *FuncType) fuzzyMatch(t2 *FuncType) bool {
|
| 180 |
+
if t == nil || t2 == nil {
|
| 181 |
+
return false
|
| 182 |
+
}
|
| 183 |
+
if !t.Result.fuzzyMatch(t2.Result) {
|
| 184 |
+
return false
|
| 185 |
+
}
|
| 186 |
+
if len(t.Params) != len(t2.Params) {
|
| 187 |
+
return false
|
| 188 |
+
}
|
| 189 |
+
for i := range t.Params {
|
| 190 |
+
if !t.Params[i].fuzzyMatch(t2.Params[i]) {
|
| 191 |
+
return false
|
| 192 |
+
}
|
| 193 |
+
}
|
| 194 |
+
return true
|
| 195 |
+
}
|
| 196 |
+
|
| 197 |
+
func usage() {
|
| 198 |
+
fmt.Fprint(os.Stderr, "usage: cgo -- [compiler options] file.go ...\n")
|
| 199 |
+
flag.PrintDefaults()
|
| 200 |
+
os.Exit(2)
|
| 201 |
+
}
|
| 202 |
+
|
| 203 |
+
var ptrSizeMap = map[string]int64{
|
| 204 |
+
"386": 4,
|
| 205 |
+
"alpha": 8,
|
| 206 |
+
"amd64": 8,
|
| 207 |
+
"arm": 4,
|
| 208 |
+
"arm64": 8,
|
| 209 |
+
"loong64": 8,
|
| 210 |
+
"m68k": 4,
|
| 211 |
+
"mips": 4,
|
| 212 |
+
"mipsle": 4,
|
| 213 |
+
"mips64": 8,
|
| 214 |
+
"mips64le": 8,
|
| 215 |
+
"nios2": 4,
|
| 216 |
+
"ppc": 4,
|
| 217 |
+
"ppc64": 8,
|
| 218 |
+
"ppc64le": 8,
|
| 219 |
+
"riscv": 4,
|
| 220 |
+
"riscv64": 8,
|
| 221 |
+
"s390": 4,
|
| 222 |
+
"s390x": 8,
|
| 223 |
+
"sh": 4,
|
| 224 |
+
"shbe": 4,
|
| 225 |
+
"sparc": 4,
|
| 226 |
+
"sparc64": 8,
|
| 227 |
+
}
|
| 228 |
+
|
| 229 |
+
var intSizeMap = map[string]int64{
|
| 230 |
+
"386": 4,
|
| 231 |
+
"alpha": 8,
|
| 232 |
+
"amd64": 8,
|
| 233 |
+
"arm": 4,
|
| 234 |
+
"arm64": 8,
|
| 235 |
+
"loong64": 8,
|
| 236 |
+
"m68k": 4,
|
| 237 |
+
"mips": 4,
|
| 238 |
+
"mipsle": 4,
|
| 239 |
+
"mips64": 8,
|
| 240 |
+
"mips64le": 8,
|
| 241 |
+
"nios2": 4,
|
| 242 |
+
"ppc": 4,
|
| 243 |
+
"ppc64": 8,
|
| 244 |
+
"ppc64le": 8,
|
| 245 |
+
"riscv": 4,
|
| 246 |
+
"riscv64": 8,
|
| 247 |
+
"s390": 4,
|
| 248 |
+
"s390x": 8,
|
| 249 |
+
"sh": 4,
|
| 250 |
+
"shbe": 4,
|
| 251 |
+
"sparc": 4,
|
| 252 |
+
"sparc64": 8,
|
| 253 |
+
}
|
| 254 |
+
|
| 255 |
+
var cPrefix string
|
| 256 |
+
|
| 257 |
+
var fset = token.NewFileSet()
|
| 258 |
+
|
| 259 |
+
var dynobj = flag.String("dynimport", "", "if non-empty, print dynamic import data for that file")
|
| 260 |
+
var dynout = flag.String("dynout", "", "write -dynimport output to this file")
|
| 261 |
+
var dynpackage = flag.String("dynpackage", "main", "set Go package for -dynimport output")
|
| 262 |
+
var dynlinker = flag.Bool("dynlinker", false, "record dynamic linker information in -dynimport mode")
|
| 263 |
+
|
| 264 |
+
// This flag is for bootstrapping a new Go implementation,
|
| 265 |
+
// to generate Go types that match the data layout and
|
| 266 |
+
// constant values used in the host's C libraries and system calls.
|
| 267 |
+
var godefs = flag.Bool("godefs", false, "for bootstrap: write Go definitions for C file to standard output")
|
| 268 |
+
|
| 269 |
+
var srcDir = flag.String("srcdir", "", "source directory")
|
| 270 |
+
var objDir = flag.String("objdir", "", "object directory")
|
| 271 |
+
var importPath = flag.String("importpath", "", "import path of package being built (for comments in generated files)")
|
| 272 |
+
var exportHeader = flag.String("exportheader", "", "where to write export header if any exported functions")
|
| 273 |
+
|
| 274 |
+
var ldflags = flag.String("ldflags", "", "flags to pass to C linker")
|
| 275 |
+
|
| 276 |
+
var gccgo = flag.Bool("gccgo", false, "generate files for use with gccgo")
|
| 277 |
+
var gccgoprefix = flag.String("gccgoprefix", "", "-fgo-prefix option used with gccgo")
|
| 278 |
+
var gccgopkgpath = flag.String("gccgopkgpath", "", "-fgo-pkgpath option used with gccgo")
|
| 279 |
+
var gccgoMangler func(string) string
|
| 280 |
+
var gccgoDefineCgoIncomplete = flag.Bool("gccgo_define_cgoincomplete", false, "define cgo.Incomplete for older gccgo/GoLLVM")
|
| 281 |
+
var importRuntimeCgo = flag.Bool("import_runtime_cgo", true, "import runtime/cgo in generated code")
|
| 282 |
+
var importSyscall = flag.Bool("import_syscall", true, "import syscall in generated code")
|
| 283 |
+
var trimpath = flag.String("trimpath", "", "applies supplied rewrites or trims prefixes to recorded source file paths")
|
| 284 |
+
|
| 285 |
+
var goarch, goos, gomips, gomips64 string
|
| 286 |
+
var gccBaseCmd []string
|
| 287 |
+
|
| 288 |
+
func main() {
|
| 289 |
+
counter.Open()
|
| 290 |
+
objabi.AddVersionFlag() // -V
|
| 291 |
+
objabi.Flagparse(usage)
|
| 292 |
+
counter.Inc("cgo/invocations")
|
| 293 |
+
counter.CountFlags("cgo/flag:", *flag.CommandLine)
|
| 294 |
+
|
| 295 |
+
if *gccgoDefineCgoIncomplete {
|
| 296 |
+
if !*gccgo {
|
| 297 |
+
fmt.Fprintf(os.Stderr, "cgo: -gccgo_define_cgoincomplete without -gccgo\n")
|
| 298 |
+
os.Exit(2)
|
| 299 |
+
}
|
| 300 |
+
incomplete = "_cgopackage_Incomplete"
|
| 301 |
+
}
|
| 302 |
+
|
| 303 |
+
if *dynobj != "" {
|
| 304 |
+
// cgo -dynimport is essentially a separate helper command
|
| 305 |
+
// built into the cgo binary. It scans a gcc-produced executable
|
| 306 |
+
// and dumps information about the imported symbols and the
|
| 307 |
+
// imported libraries. The 'go build' rules for cgo prepare an
|
| 308 |
+
// appropriate executable and then use its import information
|
| 309 |
+
// instead of needing to make the linkers duplicate all the
|
| 310 |
+
// specialized knowledge gcc has about where to look for imported
|
| 311 |
+
// symbols and which ones to use.
|
| 312 |
+
dynimport(*dynobj)
|
| 313 |
+
return
|
| 314 |
+
}
|
| 315 |
+
|
| 316 |
+
if *godefs {
|
| 317 |
+
// Generating definitions pulled from header files,
|
| 318 |
+
// to be checked into Go repositories.
|
| 319 |
+
// Line numbers are just noise.
|
| 320 |
+
conf.Mode &^= printer.SourcePos
|
| 321 |
+
}
|
| 322 |
+
|
| 323 |
+
args := flag.Args()
|
| 324 |
+
if len(args) < 1 {
|
| 325 |
+
usage()
|
| 326 |
+
}
|
| 327 |
+
|
| 328 |
+
// Find first arg that looks like a go file and assume everything before
|
| 329 |
+
// that are options to pass to gcc.
|
| 330 |
+
var i int
|
| 331 |
+
for i = len(args); i > 0; i-- {
|
| 332 |
+
if !strings.HasSuffix(args[i-1], ".go") {
|
| 333 |
+
break
|
| 334 |
+
}
|
| 335 |
+
}
|
| 336 |
+
if i == len(args) {
|
| 337 |
+
usage()
|
| 338 |
+
}
|
| 339 |
+
|
| 340 |
+
// Save original command line arguments for the godefs generated comment. Relative file
|
| 341 |
+
// paths in os.Args will be rewritten to absolute file paths in the loop below.
|
| 342 |
+
osArgs := make([]string, len(os.Args))
|
| 343 |
+
copy(osArgs, os.Args[:])
|
| 344 |
+
goFiles := args[i:]
|
| 345 |
+
|
| 346 |
+
for _, arg := range args[:i] {
|
| 347 |
+
if arg == "-fsanitize=thread" {
|
| 348 |
+
tsanProlog = yesTsanProlog
|
| 349 |
+
}
|
| 350 |
+
if arg == "-fsanitize=memory" {
|
| 351 |
+
msanProlog = yesMsanProlog
|
| 352 |
+
}
|
| 353 |
+
}
|
| 354 |
+
|
| 355 |
+
p := newPackage(args[:i])
|
| 356 |
+
|
| 357 |
+
// We need a C compiler to be available. Check this.
|
| 358 |
+
var err error
|
| 359 |
+
gccBaseCmd, err = checkGCCBaseCmd()
|
| 360 |
+
if err != nil {
|
| 361 |
+
fatalf("%v", err)
|
| 362 |
+
os.Exit(2)
|
| 363 |
+
}
|
| 364 |
+
|
| 365 |
+
// Record linker flags for external linking.
|
| 366 |
+
if *ldflags != "" {
|
| 367 |
+
args, err := splitQuoted(*ldflags)
|
| 368 |
+
if err != nil {
|
| 369 |
+
fatalf("bad -ldflags option: %q (%s)", *ldflags, err)
|
| 370 |
+
}
|
| 371 |
+
p.addToFlag("LDFLAGS", args)
|
| 372 |
+
}
|
| 373 |
+
|
| 374 |
+
// For backward compatibility for Bazel, record CGO_LDFLAGS
|
| 375 |
+
// from the environment for external linking.
|
| 376 |
+
// This should not happen with cmd/go, which removes CGO_LDFLAGS
|
| 377 |
+
// from the environment when invoking cgo.
|
| 378 |
+
// This can be removed when we no longer need to support
|
| 379 |
+
// older versions of Bazel. See issue #66456 and
|
| 380 |
+
// https://github.com/bazelbuild/rules_go/issues/3979.
|
| 381 |
+
if envFlags := os.Getenv("CGO_LDFLAGS"); envFlags != "" {
|
| 382 |
+
args, err := splitQuoted(envFlags)
|
| 383 |
+
if err != nil {
|
| 384 |
+
fatalf("bad CGO_LDFLAGS: %q (%s)", envFlags, err)
|
| 385 |
+
}
|
| 386 |
+
p.addToFlag("LDFLAGS", args)
|
| 387 |
+
}
|
| 388 |
+
|
| 389 |
+
// Need a unique prefix for the global C symbols that
|
| 390 |
+
// we use to coordinate between gcc and ourselves.
|
| 391 |
+
// We already put _cgo_ at the beginning, so the main
|
| 392 |
+
// concern is other cgo wrappers for the same functions.
|
| 393 |
+
// Use the beginning of the 16 bytes hash of the input to disambiguate.
|
| 394 |
+
h := hash.New32()
|
| 395 |
+
io.WriteString(h, *importPath)
|
| 396 |
+
var once sync.Once
|
| 397 |
+
q := par.NewQueue(runtime.GOMAXPROCS(0))
|
| 398 |
+
fs := make([]*File, len(goFiles))
|
| 399 |
+
for i, input := range goFiles {
|
| 400 |
+
if *srcDir != "" {
|
| 401 |
+
input = filepath.Join(*srcDir, input)
|
| 402 |
+
}
|
| 403 |
+
|
| 404 |
+
// Create absolute path for file, so that it will be used in error
|
| 405 |
+
// messages and recorded in debug line number information.
|
| 406 |
+
// This matches the rest of the toolchain. See golang.org/issue/5122.
|
| 407 |
+
if aname, err := filepath.Abs(input); err == nil {
|
| 408 |
+
input = aname
|
| 409 |
+
}
|
| 410 |
+
|
| 411 |
+
b, err := os.ReadFile(input)
|
| 412 |
+
if err != nil {
|
| 413 |
+
fatalf("%s", err)
|
| 414 |
+
}
|
| 415 |
+
if _, err = h.Write(b); err != nil {
|
| 416 |
+
fatalf("%s", err)
|
| 417 |
+
}
|
| 418 |
+
|
| 419 |
+
q.Add(func() {
|
| 420 |
+
// Apply trimpath to the file path. The path won't be read from after this point.
|
| 421 |
+
input, _ = objabi.ApplyRewrites(input, *trimpath)
|
| 422 |
+
if strings.ContainsAny(input, "\r\n") {
|
| 423 |
+
// ParseGo, (*Package).writeOutput, and printer.Fprint in SourcePos mode
|
| 424 |
+
// all emit line directives, which don't permit newlines in the file path.
|
| 425 |
+
// Bail early if we see anything newline-like in the trimmed path.
|
| 426 |
+
fatalf("input path contains newline character: %q", input)
|
| 427 |
+
}
|
| 428 |
+
goFiles[i] = input
|
| 429 |
+
|
| 430 |
+
f := new(File)
|
| 431 |
+
f.Edit = edit.NewBuffer(b)
|
| 432 |
+
f.ParseGo(input, b)
|
| 433 |
+
f.ProcessCgoDirectives()
|
| 434 |
+
gccIsClang := f.loadDefines(p.GccOptions)
|
| 435 |
+
once.Do(func() {
|
| 436 |
+
p.GccIsClang = gccIsClang
|
| 437 |
+
})
|
| 438 |
+
|
| 439 |
+
fs[i] = f
|
| 440 |
+
|
| 441 |
+
f.loadDebug(p)
|
| 442 |
+
})
|
| 443 |
+
}
|
| 444 |
+
|
| 445 |
+
<-q.Idle()
|
| 446 |
+
|
| 447 |
+
cPrefix = fmt.Sprintf("_%x", h.Sum(nil)[0:6])
|
| 448 |
+
|
| 449 |
+
if *objDir == "" {
|
| 450 |
+
*objDir = "_obj"
|
| 451 |
+
}
|
| 452 |
+
// make sure that `objDir` directory exists, so that we can write
|
| 453 |
+
// all the output files there.
|
| 454 |
+
os.MkdirAll(*objDir, 0o700)
|
| 455 |
+
*objDir += string(filepath.Separator)
|
| 456 |
+
|
| 457 |
+
for i, input := range goFiles {
|
| 458 |
+
f := fs[i]
|
| 459 |
+
p.Translate(f)
|
| 460 |
+
for _, cref := range f.Ref {
|
| 461 |
+
switch cref.Context {
|
| 462 |
+
case ctxCall, ctxCall2:
|
| 463 |
+
if cref.Name.Kind != "type" {
|
| 464 |
+
break
|
| 465 |
+
}
|
| 466 |
+
old := *cref.Expr
|
| 467 |
+
*cref.Expr = cref.Name.Type.Go
|
| 468 |
+
f.Edit.Replace(f.offset(old.Pos()), f.offset(old.End()), gofmt(cref.Name.Type.Go))
|
| 469 |
+
}
|
| 470 |
+
}
|
| 471 |
+
if nerrors > 0 {
|
| 472 |
+
os.Exit(2)
|
| 473 |
+
}
|
| 474 |
+
p.PackagePath = f.Package
|
| 475 |
+
p.Record(f)
|
| 476 |
+
if *godefs {
|
| 477 |
+
os.Stdout.WriteString(p.godefs(f, osArgs))
|
| 478 |
+
} else {
|
| 479 |
+
p.writeOutput(f, input)
|
| 480 |
+
}
|
| 481 |
+
}
|
| 482 |
+
cFunctions := make(map[string]bool)
|
| 483 |
+
for _, key := range nameKeys(p.Name) {
|
| 484 |
+
n := p.Name[key]
|
| 485 |
+
if n.FuncType != nil {
|
| 486 |
+
cFunctions[n.C] = true
|
| 487 |
+
}
|
| 488 |
+
}
|
| 489 |
+
|
| 490 |
+
for funcName := range p.noEscapes {
|
| 491 |
+
if _, found := cFunctions[funcName]; !found {
|
| 492 |
+
error_(token.NoPos, "#cgo noescape %s: no matched C function", funcName)
|
| 493 |
+
}
|
| 494 |
+
}
|
| 495 |
+
|
| 496 |
+
for funcName := range p.noCallbacks {
|
| 497 |
+
if _, found := cFunctions[funcName]; !found {
|
| 498 |
+
error_(token.NoPos, "#cgo nocallback %s: no matched C function", funcName)
|
| 499 |
+
}
|
| 500 |
+
}
|
| 501 |
+
|
| 502 |
+
if !*godefs {
|
| 503 |
+
p.writeDefs()
|
| 504 |
+
}
|
| 505 |
+
if nerrors > 0 {
|
| 506 |
+
os.Exit(2)
|
| 507 |
+
}
|
| 508 |
+
}
|
| 509 |
+
|
| 510 |
+
// newPackage returns a new Package that will invoke
|
| 511 |
+
// gcc with the additional arguments specified in args.
|
| 512 |
+
func newPackage(args []string) *Package {
|
| 513 |
+
goarch = runtime.GOARCH
|
| 514 |
+
if s := os.Getenv("GOARCH"); s != "" {
|
| 515 |
+
goarch = s
|
| 516 |
+
}
|
| 517 |
+
goos = runtime.GOOS
|
| 518 |
+
if s := os.Getenv("GOOS"); s != "" {
|
| 519 |
+
goos = s
|
| 520 |
+
}
|
| 521 |
+
buildcfg.Check()
|
| 522 |
+
gomips = buildcfg.GOMIPS
|
| 523 |
+
gomips64 = buildcfg.GOMIPS64
|
| 524 |
+
ptrSize := ptrSizeMap[goarch]
|
| 525 |
+
if ptrSize == 0 {
|
| 526 |
+
fatalf("unknown ptrSize for $GOARCH %q", goarch)
|
| 527 |
+
}
|
| 528 |
+
intSize := intSizeMap[goarch]
|
| 529 |
+
if intSize == 0 {
|
| 530 |
+
fatalf("unknown intSize for $GOARCH %q", goarch)
|
| 531 |
+
}
|
| 532 |
+
|
| 533 |
+
// Reset locale variables so gcc emits English errors [sic].
|
| 534 |
+
os.Setenv("LANG", "en_US.UTF-8")
|
| 535 |
+
os.Setenv("LC_ALL", "C")
|
| 536 |
+
|
| 537 |
+
p := &Package{
|
| 538 |
+
PtrSize: ptrSize,
|
| 539 |
+
IntSize: intSize,
|
| 540 |
+
Written: make(map[string]bool),
|
| 541 |
+
noCallbacks: make(map[string]bool),
|
| 542 |
+
noEscapes: make(map[string]bool),
|
| 543 |
+
}
|
| 544 |
+
p.addToFlag("CFLAGS", args)
|
| 545 |
+
return p
|
| 546 |
+
}
|
| 547 |
+
|
| 548 |
+
// Record what needs to be recorded about f.
|
| 549 |
+
func (p *Package) Record(f *File) {
|
| 550 |
+
if p.PackageName == "" {
|
| 551 |
+
p.PackageName = f.Package
|
| 552 |
+
} else if p.PackageName != f.Package {
|
| 553 |
+
error_(token.NoPos, "inconsistent package names: %s, %s", p.PackageName, f.Package)
|
| 554 |
+
}
|
| 555 |
+
|
| 556 |
+
if p.Name == nil {
|
| 557 |
+
p.Name = f.Name
|
| 558 |
+
} else {
|
| 559 |
+
// Merge the new file's names in with the existing names.
|
| 560 |
+
for k, v := range f.Name {
|
| 561 |
+
if p.Name[k] == nil {
|
| 562 |
+
// Never seen before, just save it.
|
| 563 |
+
p.Name[k] = v
|
| 564 |
+
} else if p.incompleteTypedef(p.Name[k].Type) && p.Name[k].FuncType == nil {
|
| 565 |
+
// Old one is incomplete, just use new one.
|
| 566 |
+
p.Name[k] = v
|
| 567 |
+
} else if p.incompleteTypedef(v.Type) && v.FuncType == nil {
|
| 568 |
+
// New one is incomplete, just use old one.
|
| 569 |
+
// Nothing to do.
|
| 570 |
+
} else if _, ok := nameToC[k]; ok {
|
| 571 |
+
// Names we predefine may appear inconsistent
|
| 572 |
+
// if some files typedef them and some don't.
|
| 573 |
+
// Issue 26743.
|
| 574 |
+
} else if !reflect.DeepEqual(p.Name[k], v) {
|
| 575 |
+
// We don't require strict func type equality, because some functions
|
| 576 |
+
// can have things like typedef'd arguments that are equivalent to
|
| 577 |
+
// the standard arguments. e.g.
|
| 578 |
+
// int usleep(unsigned);
|
| 579 |
+
// int usleep(useconds_t);
|
| 580 |
+
// So we just check size/alignment of arguments. At least that
|
| 581 |
+
// avoids problems like those in #67670 and #67699.
|
| 582 |
+
ok := false
|
| 583 |
+
ft1 := p.Name[k].FuncType
|
| 584 |
+
ft2 := v.FuncType
|
| 585 |
+
if ft1.fuzzyMatch(ft2) {
|
| 586 |
+
// Retry DeepEqual with the FuncType field cleared.
|
| 587 |
+
x1 := *p.Name[k]
|
| 588 |
+
x2 := *v
|
| 589 |
+
x1.FuncType = nil
|
| 590 |
+
x2.FuncType = nil
|
| 591 |
+
if reflect.DeepEqual(&x1, &x2) {
|
| 592 |
+
ok = true
|
| 593 |
+
}
|
| 594 |
+
}
|
| 595 |
+
if !ok {
|
| 596 |
+
error_(token.NoPos, "inconsistent definitions for C.%s", fixGo(k))
|
| 597 |
+
}
|
| 598 |
+
}
|
| 599 |
+
}
|
| 600 |
+
}
|
| 601 |
+
|
| 602 |
+
// merge nocallback & noescape
|
| 603 |
+
maps.Copy(p.noCallbacks, f.NoCallbacks)
|
| 604 |
+
maps.Copy(p.noEscapes, f.NoEscapes)
|
| 605 |
+
|
| 606 |
+
if f.ExpFunc != nil {
|
| 607 |
+
p.ExpFunc = append(p.ExpFunc, f.ExpFunc...)
|
| 608 |
+
p.Preamble += "\n" + f.Preamble
|
| 609 |
+
}
|
| 610 |
+
p.Decl = append(p.Decl, f.AST.Decls...)
|
| 611 |
+
}
|
| 612 |
+
|
| 613 |
+
// incompleteTypedef reports whether t appears to be an incomplete
|
| 614 |
+
// typedef definition.
|
| 615 |
+
func (p *Package) incompleteTypedef(t *Type) bool {
|
| 616 |
+
return t == nil || (t.Size == 0 && t.Align == -1)
|
| 617 |
+
}
|
go/src/cmd/cgo/out.go
ADDED
|
@@ -0,0 +1,2099 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Copyright 2009 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 |
+
package main
|
| 6 |
+
|
| 7 |
+
import (
|
| 8 |
+
"bytes"
|
| 9 |
+
"cmd/internal/pkgpath"
|
| 10 |
+
"debug/elf"
|
| 11 |
+
"debug/macho"
|
| 12 |
+
"debug/pe"
|
| 13 |
+
"fmt"
|
| 14 |
+
"go/ast"
|
| 15 |
+
"go/printer"
|
| 16 |
+
"go/token"
|
| 17 |
+
"internal/xcoff"
|
| 18 |
+
"io"
|
| 19 |
+
"os"
|
| 20 |
+
"os/exec"
|
| 21 |
+
"path/filepath"
|
| 22 |
+
"regexp"
|
| 23 |
+
"sort"
|
| 24 |
+
"strings"
|
| 25 |
+
"unicode"
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
var (
|
| 29 |
+
conf = printer.Config{Mode: printer.SourcePos, Tabwidth: 8}
|
| 30 |
+
noSourceConf = printer.Config{Tabwidth: 8}
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
// writeDefs creates output files to be compiled by gc and gcc.
|
| 34 |
+
func (p *Package) writeDefs() {
|
| 35 |
+
var fgo2, fc io.Writer
|
| 36 |
+
f := creat(*objDir + "_cgo_gotypes.go")
|
| 37 |
+
defer f.Close()
|
| 38 |
+
fgo2 = f
|
| 39 |
+
if *gccgo {
|
| 40 |
+
f := creat(*objDir + "_cgo_defun.c")
|
| 41 |
+
defer f.Close()
|
| 42 |
+
fc = f
|
| 43 |
+
}
|
| 44 |
+
fm := creat(*objDir + "_cgo_main.c")
|
| 45 |
+
|
| 46 |
+
var gccgoInit strings.Builder
|
| 47 |
+
|
| 48 |
+
if !*gccgo {
|
| 49 |
+
for _, arg := range p.LdFlags {
|
| 50 |
+
fmt.Fprintf(fgo2, "//go:cgo_ldflag %q\n", arg)
|
| 51 |
+
}
|
| 52 |
+
} else {
|
| 53 |
+
fflg := creat(*objDir + "_cgo_flags")
|
| 54 |
+
for _, arg := range p.LdFlags {
|
| 55 |
+
fmt.Fprintf(fflg, "_CGO_LDFLAGS=%s\n", arg)
|
| 56 |
+
}
|
| 57 |
+
fflg.Close()
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
// Write C main file for using gcc to resolve imports.
|
| 61 |
+
fmt.Fprintf(fm, "#include <stddef.h>\n") // For size_t below.
|
| 62 |
+
fmt.Fprintf(fm, "int main(int argc __attribute__((unused)), char **argv __attribute__((unused))) { return 0; }\n")
|
| 63 |
+
if *importRuntimeCgo {
|
| 64 |
+
fmt.Fprintf(fm, "void crosscall2(void(*fn)(void*) __attribute__((unused)), void *a __attribute__((unused)), int c __attribute__((unused)), size_t ctxt __attribute__((unused))) { }\n")
|
| 65 |
+
fmt.Fprintf(fm, "size_t _cgo_wait_runtime_init_done(void) { return 0; }\n")
|
| 66 |
+
fmt.Fprintf(fm, "void _cgo_release_context(size_t ctxt __attribute__((unused))) { }\n")
|
| 67 |
+
fmt.Fprintf(fm, "char* _cgo_topofstack(void) { return (char*)0; }\n")
|
| 68 |
+
} else {
|
| 69 |
+
// If we're not importing runtime/cgo, we *are* runtime/cgo,
|
| 70 |
+
// which provides these functions. We just need a prototype.
|
| 71 |
+
fmt.Fprintf(fm, "void crosscall2(void(*fn)(void*), void *a, int c, size_t ctxt);\n")
|
| 72 |
+
fmt.Fprintf(fm, "size_t _cgo_wait_runtime_init_done(void);\n")
|
| 73 |
+
fmt.Fprintf(fm, "void _cgo_release_context(size_t);\n")
|
| 74 |
+
}
|
| 75 |
+
fmt.Fprintf(fm, "void _cgo_allocate(void *a __attribute__((unused)), int c __attribute__((unused))) { }\n")
|
| 76 |
+
fmt.Fprintf(fm, "void _cgo_panic(void *a __attribute__((unused)), int c __attribute__((unused))) { }\n")
|
| 77 |
+
fmt.Fprintf(fm, "void _cgo_reginit(void) { }\n")
|
| 78 |
+
|
| 79 |
+
// Write second Go output: definitions of _C_xxx.
|
| 80 |
+
// In a separate file so that the import of "unsafe" does not
|
| 81 |
+
// pollute the original file.
|
| 82 |
+
fmt.Fprintf(fgo2, "// Code generated by cmd/cgo; DO NOT EDIT.\n\n")
|
| 83 |
+
fmt.Fprintf(fgo2, "package %s\n\n", p.PackageName)
|
| 84 |
+
fmt.Fprintf(fgo2, "import \"unsafe\"\n\n")
|
| 85 |
+
if *importSyscall {
|
| 86 |
+
fmt.Fprintf(fgo2, "import \"syscall\"\n\n")
|
| 87 |
+
}
|
| 88 |
+
if *importRuntimeCgo {
|
| 89 |
+
if !*gccgoDefineCgoIncomplete {
|
| 90 |
+
fmt.Fprintf(fgo2, "import _cgopackage \"runtime/cgo\"\n\n")
|
| 91 |
+
fmt.Fprintf(fgo2, "type _ _cgopackage.Incomplete\n") // prevent import-not-used error
|
| 92 |
+
} else {
|
| 93 |
+
fmt.Fprintf(fgo2, "//go:notinheap\n")
|
| 94 |
+
fmt.Fprintf(fgo2, "type _cgopackage_Incomplete struct{ _ struct{ _ struct{} } }\n")
|
| 95 |
+
}
|
| 96 |
+
}
|
| 97 |
+
if *importSyscall {
|
| 98 |
+
fmt.Fprintf(fgo2, "var _ syscall.Errno\n")
|
| 99 |
+
}
|
| 100 |
+
fmt.Fprintf(fgo2, "func _Cgo_ptr(ptr unsafe.Pointer) unsafe.Pointer { return ptr }\n\n")
|
| 101 |
+
|
| 102 |
+
if !*gccgo {
|
| 103 |
+
fmt.Fprintf(fgo2, "//go:linkname _Cgo_always_false runtime.cgoAlwaysFalse\n")
|
| 104 |
+
fmt.Fprintf(fgo2, "var _Cgo_always_false bool\n")
|
| 105 |
+
fmt.Fprintf(fgo2, "//go:linkname _Cgo_use runtime.cgoUse\n")
|
| 106 |
+
fmt.Fprintf(fgo2, "func _Cgo_use(interface{})\n")
|
| 107 |
+
fmt.Fprintf(fgo2, "//go:linkname _Cgo_keepalive runtime.cgoKeepAlive\n")
|
| 108 |
+
fmt.Fprintf(fgo2, "//go:noescape\n")
|
| 109 |
+
fmt.Fprintf(fgo2, "func _Cgo_keepalive(interface{})\n")
|
| 110 |
+
}
|
| 111 |
+
fmt.Fprintf(fgo2, "//go:linkname _Cgo_no_callback runtime.cgoNoCallback\n")
|
| 112 |
+
fmt.Fprintf(fgo2, "func _Cgo_no_callback(bool)\n")
|
| 113 |
+
|
| 114 |
+
typedefNames := make([]string, 0, len(typedef))
|
| 115 |
+
for name := range typedef {
|
| 116 |
+
if name == "_Ctype_void" {
|
| 117 |
+
// We provide an appropriate declaration for
|
| 118 |
+
// _Ctype_void below (#39877).
|
| 119 |
+
continue
|
| 120 |
+
}
|
| 121 |
+
typedefNames = append(typedefNames, name)
|
| 122 |
+
}
|
| 123 |
+
sort.Strings(typedefNames)
|
| 124 |
+
for _, name := range typedefNames {
|
| 125 |
+
def := typedef[name]
|
| 126 |
+
fmt.Fprintf(fgo2, "type %s ", name)
|
| 127 |
+
// We don't have source info for these types, so write them out without source info.
|
| 128 |
+
// Otherwise types would look like:
|
| 129 |
+
//
|
| 130 |
+
// type _Ctype_struct_cb struct {
|
| 131 |
+
// //line :1
|
| 132 |
+
// on_test *[0]byte
|
| 133 |
+
// //line :1
|
| 134 |
+
// }
|
| 135 |
+
//
|
| 136 |
+
// Which is not useful. Moreover we never override source info,
|
| 137 |
+
// so subsequent source code uses the same source info.
|
| 138 |
+
// Moreover, empty file name makes compile emit no source debug info at all.
|
| 139 |
+
var buf bytes.Buffer
|
| 140 |
+
noSourceConf.Fprint(&buf, fset, def.Go)
|
| 141 |
+
if bytes.HasPrefix(buf.Bytes(), []byte("_Ctype_")) ||
|
| 142 |
+
strings.HasPrefix(name, "_Ctype_enum_") ||
|
| 143 |
+
strings.HasPrefix(name, "_Ctype_union_") {
|
| 144 |
+
// This typedef is of the form `typedef a b` and should be an alias.
|
| 145 |
+
fmt.Fprintf(fgo2, "= ")
|
| 146 |
+
}
|
| 147 |
+
fmt.Fprintf(fgo2, "%s", buf.Bytes())
|
| 148 |
+
fmt.Fprintf(fgo2, "\n\n")
|
| 149 |
+
}
|
| 150 |
+
if *gccgo {
|
| 151 |
+
fmt.Fprintf(fgo2, "type _Ctype_void byte\n")
|
| 152 |
+
} else {
|
| 153 |
+
fmt.Fprintf(fgo2, "type _Ctype_void [0]byte\n")
|
| 154 |
+
}
|
| 155 |
+
|
| 156 |
+
if *gccgo {
|
| 157 |
+
fmt.Fprint(fgo2, gccgoGoProlog)
|
| 158 |
+
fmt.Fprint(fc, p.cPrologGccgo())
|
| 159 |
+
} else {
|
| 160 |
+
fmt.Fprint(fgo2, goProlog)
|
| 161 |
+
}
|
| 162 |
+
|
| 163 |
+
if fc != nil {
|
| 164 |
+
fmt.Fprintf(fc, "#line 1 \"cgo-generated-wrappers\"\n")
|
| 165 |
+
}
|
| 166 |
+
if fm != nil {
|
| 167 |
+
fmt.Fprintf(fm, "#line 1 \"cgo-generated-wrappers\"\n")
|
| 168 |
+
}
|
| 169 |
+
|
| 170 |
+
gccgoSymbolPrefix := p.gccgoSymbolPrefix()
|
| 171 |
+
|
| 172 |
+
cVars := make(map[string]bool)
|
| 173 |
+
for _, key := range nameKeys(p.Name) {
|
| 174 |
+
n := p.Name[key]
|
| 175 |
+
if !n.IsVar() {
|
| 176 |
+
continue
|
| 177 |
+
}
|
| 178 |
+
|
| 179 |
+
if !cVars[n.C] {
|
| 180 |
+
if *gccgo {
|
| 181 |
+
fmt.Fprintf(fc, "extern byte *%s;\n", n.C)
|
| 182 |
+
} else {
|
| 183 |
+
// Force a reference to all symbols so that
|
| 184 |
+
// the external linker will add DT_NEEDED
|
| 185 |
+
// entries as needed on ELF systems.
|
| 186 |
+
// Treat function variables differently
|
| 187 |
+
// to avoid type conflict errors from LTO
|
| 188 |
+
// (Link Time Optimization).
|
| 189 |
+
if n.Kind == "fpvar" {
|
| 190 |
+
fmt.Fprintf(fm, "extern void %s();\n", n.C)
|
| 191 |
+
} else {
|
| 192 |
+
fmt.Fprintf(fm, "extern char %s[];\n", n.C)
|
| 193 |
+
fmt.Fprintf(fm, "void *_cgohack_%s = %s;\n\n", n.C, n.C)
|
| 194 |
+
}
|
| 195 |
+
fmt.Fprintf(fgo2, "//go:linkname __cgo_%s %s\n", n.C, n.C)
|
| 196 |
+
fmt.Fprintf(fgo2, "//go:cgo_import_static %s\n", n.C)
|
| 197 |
+
fmt.Fprintf(fgo2, "var __cgo_%s byte\n", n.C)
|
| 198 |
+
}
|
| 199 |
+
cVars[n.C] = true
|
| 200 |
+
}
|
| 201 |
+
|
| 202 |
+
var node ast.Node
|
| 203 |
+
if n.Kind == "var" {
|
| 204 |
+
node = &ast.StarExpr{X: n.Type.Go}
|
| 205 |
+
} else if n.Kind == "fpvar" {
|
| 206 |
+
node = n.Type.Go
|
| 207 |
+
} else {
|
| 208 |
+
panic(fmt.Errorf("invalid var kind %q", n.Kind))
|
| 209 |
+
}
|
| 210 |
+
if *gccgo {
|
| 211 |
+
fmt.Fprintf(fc, `extern void *%s __asm__("%s.%s");`, n.Mangle, gccgoSymbolPrefix, gccgoToSymbol(n.Mangle))
|
| 212 |
+
fmt.Fprintf(&gccgoInit, "\t%s = &%s;\n", n.Mangle, n.C)
|
| 213 |
+
fmt.Fprintf(fc, "\n")
|
| 214 |
+
}
|
| 215 |
+
|
| 216 |
+
fmt.Fprintf(fgo2, "var %s ", n.Mangle)
|
| 217 |
+
conf.Fprint(fgo2, fset, node)
|
| 218 |
+
if !*gccgo {
|
| 219 |
+
fmt.Fprintf(fgo2, " = (")
|
| 220 |
+
conf.Fprint(fgo2, fset, node)
|
| 221 |
+
fmt.Fprintf(fgo2, ")(unsafe.Pointer(&__cgo_%s))", n.C)
|
| 222 |
+
}
|
| 223 |
+
fmt.Fprintf(fgo2, "\n")
|
| 224 |
+
}
|
| 225 |
+
if *gccgo {
|
| 226 |
+
fmt.Fprintf(fc, "\n")
|
| 227 |
+
}
|
| 228 |
+
|
| 229 |
+
for _, key := range nameKeys(p.Name) {
|
| 230 |
+
n := p.Name[key]
|
| 231 |
+
if n.Const != "" {
|
| 232 |
+
fmt.Fprintf(fgo2, "const %s = %s\n", n.Mangle, n.Const)
|
| 233 |
+
}
|
| 234 |
+
}
|
| 235 |
+
fmt.Fprintf(fgo2, "\n")
|
| 236 |
+
|
| 237 |
+
callsMalloc := false
|
| 238 |
+
for _, key := range nameKeys(p.Name) {
|
| 239 |
+
n := p.Name[key]
|
| 240 |
+
if n.FuncType != nil {
|
| 241 |
+
p.writeDefsFunc(fgo2, n, &callsMalloc)
|
| 242 |
+
}
|
| 243 |
+
}
|
| 244 |
+
|
| 245 |
+
fgcc := creat(*objDir + "_cgo_export.c")
|
| 246 |
+
fgcch := creat(*objDir + "_cgo_export.h")
|
| 247 |
+
if *gccgo {
|
| 248 |
+
p.writeGccgoExports(fgo2, fm, fgcc, fgcch)
|
| 249 |
+
} else {
|
| 250 |
+
p.writeExports(fgo2, fm, fgcc, fgcch)
|
| 251 |
+
}
|
| 252 |
+
|
| 253 |
+
if callsMalloc && !*gccgo {
|
| 254 |
+
fmt.Fprint(fgo2, strings.ReplaceAll(cMallocDefGo, "PREFIX", cPrefix))
|
| 255 |
+
fmt.Fprint(fgcc, strings.ReplaceAll(strings.Replace(cMallocDefC, "PREFIX", cPrefix, -1), "PACKED", p.packedAttribute()))
|
| 256 |
+
}
|
| 257 |
+
|
| 258 |
+
if err := fgcc.Close(); err != nil {
|
| 259 |
+
fatalf("%s", err)
|
| 260 |
+
}
|
| 261 |
+
if err := fgcch.Close(); err != nil {
|
| 262 |
+
fatalf("%s", err)
|
| 263 |
+
}
|
| 264 |
+
|
| 265 |
+
if *exportHeader != "" && len(p.ExpFunc) > 0 {
|
| 266 |
+
fexp := creat(*exportHeader)
|
| 267 |
+
fgcch, err := os.Open(*objDir + "_cgo_export.h")
|
| 268 |
+
if err != nil {
|
| 269 |
+
fatalf("%s", err)
|
| 270 |
+
}
|
| 271 |
+
defer fgcch.Close()
|
| 272 |
+
_, err = io.Copy(fexp, fgcch)
|
| 273 |
+
if err != nil {
|
| 274 |
+
fatalf("%s", err)
|
| 275 |
+
}
|
| 276 |
+
if err = fexp.Close(); err != nil {
|
| 277 |
+
fatalf("%s", err)
|
| 278 |
+
}
|
| 279 |
+
}
|
| 280 |
+
|
| 281 |
+
init := gccgoInit.String()
|
| 282 |
+
if init != "" {
|
| 283 |
+
// The init function does nothing but simple
|
| 284 |
+
// assignments, so it won't use much stack space, so
|
| 285 |
+
// it's OK to not split the stack. Splitting the stack
|
| 286 |
+
// can run into a bug in clang (as of 2018-11-09):
|
| 287 |
+
// this is a leaf function, and when clang sees a leaf
|
| 288 |
+
// function it won't emit the split stack prologue for
|
| 289 |
+
// the function. However, if this function refers to a
|
| 290 |
+
// non-split-stack function, which will happen if the
|
| 291 |
+
// cgo code refers to a C function not compiled with
|
| 292 |
+
// -fsplit-stack, then the linker will think that it
|
| 293 |
+
// needs to adjust the split stack prologue, but there
|
| 294 |
+
// won't be one. Marking the function explicitly
|
| 295 |
+
// no_split_stack works around this problem by telling
|
| 296 |
+
// the linker that it's OK if there is no split stack
|
| 297 |
+
// prologue.
|
| 298 |
+
fmt.Fprintln(fc, "static void init(void) __attribute__ ((constructor, no_split_stack));")
|
| 299 |
+
fmt.Fprintln(fc, "static void init(void) {")
|
| 300 |
+
fmt.Fprint(fc, init)
|
| 301 |
+
fmt.Fprintln(fc, "}")
|
| 302 |
+
}
|
| 303 |
+
}
|
| 304 |
+
|
| 305 |
+
// elfImportedSymbols is like elf.File.ImportedSymbols, but it
|
| 306 |
+
// includes weak symbols.
|
| 307 |
+
//
|
| 308 |
+
// A bug in some versions of LLD (at least LLD 8) cause it to emit
|
| 309 |
+
// several pthreads symbols as weak, but we need to import those. See
|
| 310 |
+
// issue #31912 or https://bugs.llvm.org/show_bug.cgi?id=42442.
|
| 311 |
+
//
|
| 312 |
+
// When doing external linking, we hand everything off to the external
|
| 313 |
+
// linker, which will create its own dynamic symbol tables. For
|
| 314 |
+
// internal linking, this may turn weak imports into strong imports,
|
| 315 |
+
// which could cause dynamic linking to fail if a symbol really isn't
|
| 316 |
+
// defined. However, the standard library depends on everything it
|
| 317 |
+
// imports, and this is the primary use of dynamic symbol tables with
|
| 318 |
+
// internal linking.
|
| 319 |
+
func elfImportedSymbols(f *elf.File) []elf.ImportedSymbol {
|
| 320 |
+
syms, _ := f.DynamicSymbols()
|
| 321 |
+
var imports []elf.ImportedSymbol
|
| 322 |
+
for _, s := range syms {
|
| 323 |
+
if (elf.ST_BIND(s.Info) == elf.STB_GLOBAL || elf.ST_BIND(s.Info) == elf.STB_WEAK) && s.Section == elf.SHN_UNDEF {
|
| 324 |
+
imports = append(imports, elf.ImportedSymbol{
|
| 325 |
+
Name: s.Name,
|
| 326 |
+
Library: s.Library,
|
| 327 |
+
Version: s.Version,
|
| 328 |
+
})
|
| 329 |
+
}
|
| 330 |
+
}
|
| 331 |
+
return imports
|
| 332 |
+
}
|
| 333 |
+
|
| 334 |
+
func dynimport(obj string) {
|
| 335 |
+
stdout := os.Stdout
|
| 336 |
+
if *dynout != "" {
|
| 337 |
+
f, err := os.Create(*dynout)
|
| 338 |
+
if err != nil {
|
| 339 |
+
fatalf("%s", err)
|
| 340 |
+
}
|
| 341 |
+
defer func() {
|
| 342 |
+
if err = f.Close(); err != nil {
|
| 343 |
+
fatalf("error closing %s: %v", *dynout, err)
|
| 344 |
+
}
|
| 345 |
+
}()
|
| 346 |
+
|
| 347 |
+
stdout = f
|
| 348 |
+
}
|
| 349 |
+
|
| 350 |
+
fmt.Fprintf(stdout, "package %s\n", *dynpackage)
|
| 351 |
+
|
| 352 |
+
if f, err := elf.Open(obj); err == nil {
|
| 353 |
+
defer f.Close()
|
| 354 |
+
if *dynlinker {
|
| 355 |
+
// Emit the cgo_dynamic_linker line.
|
| 356 |
+
if sec := f.Section(".interp"); sec != nil {
|
| 357 |
+
if data, err := sec.Data(); err == nil && len(data) > 1 {
|
| 358 |
+
// skip trailing \0 in data
|
| 359 |
+
fmt.Fprintf(stdout, "//go:cgo_dynamic_linker %q\n", string(data[:len(data)-1]))
|
| 360 |
+
}
|
| 361 |
+
}
|
| 362 |
+
}
|
| 363 |
+
sym := elfImportedSymbols(f)
|
| 364 |
+
for _, s := range sym {
|
| 365 |
+
targ := s.Name
|
| 366 |
+
if s.Version != "" {
|
| 367 |
+
targ += "#" + s.Version
|
| 368 |
+
}
|
| 369 |
+
checkImportSymName(s.Name)
|
| 370 |
+
checkImportSymName(targ)
|
| 371 |
+
fmt.Fprintf(stdout, "//go:cgo_import_dynamic %s %s %q\n", s.Name, targ, s.Library)
|
| 372 |
+
}
|
| 373 |
+
lib, _ := f.ImportedLibraries()
|
| 374 |
+
for _, l := range lib {
|
| 375 |
+
fmt.Fprintf(stdout, "//go:cgo_import_dynamic _ _ %q\n", l)
|
| 376 |
+
}
|
| 377 |
+
return
|
| 378 |
+
}
|
| 379 |
+
|
| 380 |
+
if f, err := macho.Open(obj); err == nil {
|
| 381 |
+
defer f.Close()
|
| 382 |
+
sym, _ := f.ImportedSymbols()
|
| 383 |
+
for _, s := range sym {
|
| 384 |
+
s = strings.TrimPrefix(s, "_")
|
| 385 |
+
checkImportSymName(s)
|
| 386 |
+
fmt.Fprintf(stdout, "//go:cgo_import_dynamic %s %s %q\n", s, s, "")
|
| 387 |
+
}
|
| 388 |
+
lib, _ := f.ImportedLibraries()
|
| 389 |
+
for _, l := range lib {
|
| 390 |
+
fmt.Fprintf(stdout, "//go:cgo_import_dynamic _ _ %q\n", l)
|
| 391 |
+
}
|
| 392 |
+
return
|
| 393 |
+
}
|
| 394 |
+
|
| 395 |
+
if f, err := pe.Open(obj); err == nil {
|
| 396 |
+
defer f.Close()
|
| 397 |
+
sym, _ := f.ImportedSymbols()
|
| 398 |
+
for _, s := range sym {
|
| 399 |
+
ss := strings.Split(s, ":")
|
| 400 |
+
name := strings.Split(ss[0], "@")[0]
|
| 401 |
+
checkImportSymName(name)
|
| 402 |
+
checkImportSymName(ss[0])
|
| 403 |
+
fmt.Fprintf(stdout, "//go:cgo_import_dynamic %s %s %q\n", name, ss[0], strings.ToLower(ss[1]))
|
| 404 |
+
}
|
| 405 |
+
return
|
| 406 |
+
}
|
| 407 |
+
|
| 408 |
+
if f, err := xcoff.Open(obj); err == nil {
|
| 409 |
+
defer f.Close()
|
| 410 |
+
sym, err := f.ImportedSymbols()
|
| 411 |
+
if err != nil {
|
| 412 |
+
fatalf("cannot load imported symbols from XCOFF file %s: %v", obj, err)
|
| 413 |
+
}
|
| 414 |
+
for _, s := range sym {
|
| 415 |
+
if s.Name == "runtime_rt0_go" || s.Name == "_rt0_ppc64_aix_lib" {
|
| 416 |
+
// These symbols are imported by runtime/cgo but
|
| 417 |
+
// must not be added to _cgo_import.go as there are
|
| 418 |
+
// Go symbols.
|
| 419 |
+
continue
|
| 420 |
+
}
|
| 421 |
+
checkImportSymName(s.Name)
|
| 422 |
+
fmt.Fprintf(stdout, "//go:cgo_import_dynamic %s %s %q\n", s.Name, s.Name, s.Library)
|
| 423 |
+
}
|
| 424 |
+
lib, err := f.ImportedLibraries()
|
| 425 |
+
if err != nil {
|
| 426 |
+
fatalf("cannot load imported libraries from XCOFF file %s: %v", obj, err)
|
| 427 |
+
}
|
| 428 |
+
for _, l := range lib {
|
| 429 |
+
fmt.Fprintf(stdout, "//go:cgo_import_dynamic _ _ %q\n", l)
|
| 430 |
+
}
|
| 431 |
+
return
|
| 432 |
+
}
|
| 433 |
+
|
| 434 |
+
fatalf("cannot parse %s as ELF, Mach-O, PE or XCOFF", obj)
|
| 435 |
+
}
|
| 436 |
+
|
| 437 |
+
// checkImportSymName checks a symbol name we are going to emit as part
|
| 438 |
+
// of a //go:cgo_import_dynamic pragma. These names come from object
|
| 439 |
+
// files, so they may be corrupt. We are going to emit them unquoted,
|
| 440 |
+
// so while they don't need to be valid symbol names (and in some cases,
|
| 441 |
+
// involving symbol versions, they won't be) they must contain only
|
| 442 |
+
// graphic characters and must not contain Go comments.
|
| 443 |
+
func checkImportSymName(s string) {
|
| 444 |
+
for _, c := range s {
|
| 445 |
+
if !unicode.IsGraphic(c) || unicode.IsSpace(c) {
|
| 446 |
+
fatalf("dynamic symbol %q contains unsupported character", s)
|
| 447 |
+
}
|
| 448 |
+
}
|
| 449 |
+
if strings.Contains(s, "//") || strings.Contains(s, "/*") {
|
| 450 |
+
fatalf("dynamic symbol %q contains Go comment", s)
|
| 451 |
+
}
|
| 452 |
+
}
|
| 453 |
+
|
| 454 |
+
// Construct a gcc struct matching the gc argument frame.
|
| 455 |
+
// Assumes that in gcc, char is 1 byte, short 2 bytes, int 4 bytes, long long 8 bytes.
|
| 456 |
+
// These assumptions are checked by the gccProlog.
|
| 457 |
+
// Also assumes that gc convention is to word-align the
|
| 458 |
+
// input and output parameters.
|
| 459 |
+
func (p *Package) structType(n *Name) (string, int64) {
|
| 460 |
+
// It's possible for us to see a type with a top-level const here,
|
| 461 |
+
// which will give us an unusable struct type. See #75751.
|
| 462 |
+
// The top-level const will always appear as a final qualifier,
|
| 463 |
+
// constructed by typeConv.loadType in the dwarf.QualType case.
|
| 464 |
+
// The top-level const is meaningless here and can simply be removed.
|
| 465 |
+
stripConst := func(s string) string {
|
| 466 |
+
i := strings.LastIndex(s, "const")
|
| 467 |
+
if i == -1 {
|
| 468 |
+
return s
|
| 469 |
+
}
|
| 470 |
+
|
| 471 |
+
// A top-level const can only be followed by other qualifiers.
|
| 472 |
+
if r, ok := strings.CutSuffix(s, "const"); ok {
|
| 473 |
+
return strings.TrimSpace(r)
|
| 474 |
+
}
|
| 475 |
+
|
| 476 |
+
var nonConst []string
|
| 477 |
+
for _, f := range strings.Fields(s[i:]) {
|
| 478 |
+
switch f {
|
| 479 |
+
case "const":
|
| 480 |
+
case "restrict", "volatile":
|
| 481 |
+
nonConst = append(nonConst, f)
|
| 482 |
+
default:
|
| 483 |
+
return s
|
| 484 |
+
}
|
| 485 |
+
}
|
| 486 |
+
|
| 487 |
+
return strings.TrimSpace(s[:i]) + " " + strings.Join(nonConst, " ")
|
| 488 |
+
}
|
| 489 |
+
|
| 490 |
+
var buf strings.Builder
|
| 491 |
+
fmt.Fprint(&buf, "struct {\n")
|
| 492 |
+
off := int64(0)
|
| 493 |
+
for i, t := range n.FuncType.Params {
|
| 494 |
+
if off%t.Align != 0 {
|
| 495 |
+
pad := t.Align - off%t.Align
|
| 496 |
+
fmt.Fprintf(&buf, "\t\tchar __pad%d[%d];\n", off, pad)
|
| 497 |
+
off += pad
|
| 498 |
+
}
|
| 499 |
+
c := t.Typedef
|
| 500 |
+
if c == "" {
|
| 501 |
+
c = stripConst(t.C.String())
|
| 502 |
+
}
|
| 503 |
+
fmt.Fprintf(&buf, "\t\t%s p%d;\n", c, i)
|
| 504 |
+
off += t.Size
|
| 505 |
+
}
|
| 506 |
+
if off%p.PtrSize != 0 {
|
| 507 |
+
pad := p.PtrSize - off%p.PtrSize
|
| 508 |
+
fmt.Fprintf(&buf, "\t\tchar __pad%d[%d];\n", off, pad)
|
| 509 |
+
off += pad
|
| 510 |
+
}
|
| 511 |
+
if t := n.FuncType.Result; t != nil {
|
| 512 |
+
if off%t.Align != 0 {
|
| 513 |
+
pad := t.Align - off%t.Align
|
| 514 |
+
fmt.Fprintf(&buf, "\t\tchar __pad%d[%d];\n", off, pad)
|
| 515 |
+
off += pad
|
| 516 |
+
}
|
| 517 |
+
fmt.Fprintf(&buf, "\t\t%s r;\n", stripConst(t.C.String()))
|
| 518 |
+
off += t.Size
|
| 519 |
+
}
|
| 520 |
+
if off%p.PtrSize != 0 {
|
| 521 |
+
pad := p.PtrSize - off%p.PtrSize
|
| 522 |
+
fmt.Fprintf(&buf, "\t\tchar __pad%d[%d];\n", off, pad)
|
| 523 |
+
off += pad
|
| 524 |
+
}
|
| 525 |
+
if off == 0 {
|
| 526 |
+
fmt.Fprintf(&buf, "\t\tchar unused;\n") // avoid empty struct
|
| 527 |
+
}
|
| 528 |
+
fmt.Fprintf(&buf, "\t}")
|
| 529 |
+
return buf.String(), off
|
| 530 |
+
}
|
| 531 |
+
|
| 532 |
+
func (p *Package) writeDefsFunc(fgo2 io.Writer, n *Name, callsMalloc *bool) {
|
| 533 |
+
name := n.Go
|
| 534 |
+
gtype := n.FuncType.Go
|
| 535 |
+
void := gtype.Results == nil || len(gtype.Results.List) == 0
|
| 536 |
+
if n.AddError {
|
| 537 |
+
// Add "error" to return type list.
|
| 538 |
+
// Type list is known to be 0 or 1 element - it's a C function.
|
| 539 |
+
err := &ast.Field{Type: ast.NewIdent("error")}
|
| 540 |
+
l := gtype.Results.List
|
| 541 |
+
if len(l) == 0 {
|
| 542 |
+
l = []*ast.Field{err}
|
| 543 |
+
} else {
|
| 544 |
+
l = []*ast.Field{l[0], err}
|
| 545 |
+
}
|
| 546 |
+
t := new(ast.FuncType)
|
| 547 |
+
*t = *gtype
|
| 548 |
+
t.Results = &ast.FieldList{List: l}
|
| 549 |
+
gtype = t
|
| 550 |
+
}
|
| 551 |
+
|
| 552 |
+
// Go func declaration.
|
| 553 |
+
d := &ast.FuncDecl{
|
| 554 |
+
Name: ast.NewIdent(n.Mangle),
|
| 555 |
+
Type: gtype,
|
| 556 |
+
}
|
| 557 |
+
|
| 558 |
+
// Builtins defined in the C prolog.
|
| 559 |
+
inProlog := builtinDefs[name] != ""
|
| 560 |
+
cname := fmt.Sprintf("_cgo%s%s", cPrefix, n.Mangle)
|
| 561 |
+
paramnames := []string(nil)
|
| 562 |
+
if d.Type.Params != nil {
|
| 563 |
+
for i, param := range d.Type.Params.List {
|
| 564 |
+
paramName := fmt.Sprintf("p%d", i)
|
| 565 |
+
param.Names = []*ast.Ident{ast.NewIdent(paramName)}
|
| 566 |
+
paramnames = append(paramnames, paramName)
|
| 567 |
+
}
|
| 568 |
+
}
|
| 569 |
+
|
| 570 |
+
if *gccgo {
|
| 571 |
+
// Gccgo style hooks.
|
| 572 |
+
fmt.Fprint(fgo2, "\n")
|
| 573 |
+
conf.Fprint(fgo2, fset, d)
|
| 574 |
+
fmt.Fprint(fgo2, " {\n")
|
| 575 |
+
if !inProlog {
|
| 576 |
+
fmt.Fprint(fgo2, "\tdefer syscall.CgocallDone()\n")
|
| 577 |
+
fmt.Fprint(fgo2, "\tsyscall.Cgocall()\n")
|
| 578 |
+
}
|
| 579 |
+
if n.AddError {
|
| 580 |
+
fmt.Fprint(fgo2, "\tsyscall.SetErrno(0)\n")
|
| 581 |
+
}
|
| 582 |
+
fmt.Fprint(fgo2, "\t")
|
| 583 |
+
if !void {
|
| 584 |
+
fmt.Fprint(fgo2, "r := ")
|
| 585 |
+
}
|
| 586 |
+
fmt.Fprintf(fgo2, "%s(%s)\n", cname, strings.Join(paramnames, ", "))
|
| 587 |
+
|
| 588 |
+
if n.AddError {
|
| 589 |
+
fmt.Fprint(fgo2, "\te := syscall.GetErrno()\n")
|
| 590 |
+
fmt.Fprint(fgo2, "\tif e != 0 {\n")
|
| 591 |
+
fmt.Fprint(fgo2, "\t\treturn ")
|
| 592 |
+
if !void {
|
| 593 |
+
fmt.Fprint(fgo2, "r, ")
|
| 594 |
+
}
|
| 595 |
+
fmt.Fprint(fgo2, "e\n")
|
| 596 |
+
fmt.Fprint(fgo2, "\t}\n")
|
| 597 |
+
fmt.Fprint(fgo2, "\treturn ")
|
| 598 |
+
if !void {
|
| 599 |
+
fmt.Fprint(fgo2, "r, ")
|
| 600 |
+
}
|
| 601 |
+
fmt.Fprint(fgo2, "nil\n")
|
| 602 |
+
} else if !void {
|
| 603 |
+
fmt.Fprint(fgo2, "\treturn r\n")
|
| 604 |
+
}
|
| 605 |
+
|
| 606 |
+
fmt.Fprint(fgo2, "}\n")
|
| 607 |
+
|
| 608 |
+
// declare the C function.
|
| 609 |
+
fmt.Fprintf(fgo2, "//extern %s\n", cname)
|
| 610 |
+
d.Name = ast.NewIdent(cname)
|
| 611 |
+
if n.AddError {
|
| 612 |
+
l := d.Type.Results.List
|
| 613 |
+
d.Type.Results.List = l[:len(l)-1]
|
| 614 |
+
}
|
| 615 |
+
conf.Fprint(fgo2, fset, d)
|
| 616 |
+
fmt.Fprint(fgo2, "\n")
|
| 617 |
+
|
| 618 |
+
return
|
| 619 |
+
}
|
| 620 |
+
|
| 621 |
+
if inProlog {
|
| 622 |
+
fmt.Fprint(fgo2, builtinDefs[name])
|
| 623 |
+
if strings.Contains(builtinDefs[name], "_cgo_cmalloc") {
|
| 624 |
+
*callsMalloc = true
|
| 625 |
+
}
|
| 626 |
+
return
|
| 627 |
+
}
|
| 628 |
+
|
| 629 |
+
// Wrapper calls into gcc, passing a pointer to the argument frame.
|
| 630 |
+
fmt.Fprintf(fgo2, "//go:cgo_import_static %s\n", cname)
|
| 631 |
+
fmt.Fprintf(fgo2, "//go:linkname __cgofn_%s %s\n", cname, cname)
|
| 632 |
+
fmt.Fprintf(fgo2, "var __cgofn_%s byte\n", cname)
|
| 633 |
+
fmt.Fprintf(fgo2, "var %s = unsafe.Pointer(&__cgofn_%s)\n", cname, cname)
|
| 634 |
+
|
| 635 |
+
nret := 0
|
| 636 |
+
if !void {
|
| 637 |
+
d.Type.Results.List[0].Names = []*ast.Ident{ast.NewIdent("r1")}
|
| 638 |
+
nret = 1
|
| 639 |
+
}
|
| 640 |
+
if n.AddError {
|
| 641 |
+
d.Type.Results.List[nret].Names = []*ast.Ident{ast.NewIdent("r2")}
|
| 642 |
+
}
|
| 643 |
+
|
| 644 |
+
fmt.Fprint(fgo2, "\n")
|
| 645 |
+
fmt.Fprint(fgo2, "//go:cgo_unsafe_args\n")
|
| 646 |
+
conf.Fprint(fgo2, fset, d)
|
| 647 |
+
fmt.Fprint(fgo2, " {\n")
|
| 648 |
+
|
| 649 |
+
// NOTE: Using uintptr to hide from escape analysis.
|
| 650 |
+
arg := "0"
|
| 651 |
+
if len(paramnames) > 0 {
|
| 652 |
+
arg = "uintptr(unsafe.Pointer(&p0))"
|
| 653 |
+
} else if !void {
|
| 654 |
+
arg = "uintptr(unsafe.Pointer(&r1))"
|
| 655 |
+
}
|
| 656 |
+
|
| 657 |
+
noCallback := p.noCallbacks[n.C]
|
| 658 |
+
if noCallback {
|
| 659 |
+
// disable cgocallback, will check it in runtime.
|
| 660 |
+
fmt.Fprintf(fgo2, "\t_Cgo_no_callback(true)\n")
|
| 661 |
+
}
|
| 662 |
+
|
| 663 |
+
prefix := ""
|
| 664 |
+
if n.AddError {
|
| 665 |
+
prefix = "errno := "
|
| 666 |
+
}
|
| 667 |
+
fmt.Fprintf(fgo2, "\t%s_cgo_runtime_cgocall(%s, %s)\n", prefix, cname, arg)
|
| 668 |
+
if n.AddError {
|
| 669 |
+
fmt.Fprintf(fgo2, "\tif errno != 0 { r2 = syscall.Errno(errno) }\n")
|
| 670 |
+
}
|
| 671 |
+
if noCallback {
|
| 672 |
+
fmt.Fprintf(fgo2, "\t_Cgo_no_callback(false)\n")
|
| 673 |
+
}
|
| 674 |
+
|
| 675 |
+
// Use _Cgo_keepalive instead of _Cgo_use when noescape & nocallback exist,
|
| 676 |
+
// so that the compiler won't force to escape them to heap.
|
| 677 |
+
// Instead, make the compiler keep them alive by using _Cgo_keepalive.
|
| 678 |
+
touchFunc := "_Cgo_use"
|
| 679 |
+
if p.noEscapes[n.C] && p.noCallbacks[n.C] {
|
| 680 |
+
touchFunc = "_Cgo_keepalive"
|
| 681 |
+
}
|
| 682 |
+
|
| 683 |
+
if len(paramnames) > 0 {
|
| 684 |
+
fmt.Fprintf(fgo2, "\tif _Cgo_always_false {\n")
|
| 685 |
+
for _, name := range paramnames {
|
| 686 |
+
fmt.Fprintf(fgo2, "\t\t%s(%s)\n", touchFunc, name)
|
| 687 |
+
}
|
| 688 |
+
fmt.Fprintf(fgo2, "\t}\n")
|
| 689 |
+
}
|
| 690 |
+
|
| 691 |
+
fmt.Fprintf(fgo2, "\treturn\n")
|
| 692 |
+
fmt.Fprintf(fgo2, "}\n")
|
| 693 |
+
}
|
| 694 |
+
|
| 695 |
+
// writeOutput creates stubs for a specific source file to be compiled by gc
|
| 696 |
+
func (p *Package) writeOutput(f *File, srcfile string) {
|
| 697 |
+
base := srcfile
|
| 698 |
+
base = strings.TrimSuffix(base, ".go")
|
| 699 |
+
base = filepath.Base(base)
|
| 700 |
+
fgo1 := creat(*objDir + base + ".cgo1.go")
|
| 701 |
+
fgcc := creat(*objDir + base + ".cgo2.c")
|
| 702 |
+
|
| 703 |
+
p.GoFiles = append(p.GoFiles, base+".cgo1.go")
|
| 704 |
+
p.GccFiles = append(p.GccFiles, base+".cgo2.c")
|
| 705 |
+
|
| 706 |
+
// Write Go output: Go input with rewrites of C.xxx to _C_xxx.
|
| 707 |
+
fmt.Fprintf(fgo1, "// Code generated by cmd/cgo; DO NOT EDIT.\n\n")
|
| 708 |
+
if strings.ContainsAny(srcfile, "\r\n") {
|
| 709 |
+
// This should have been checked when the file path was first resolved,
|
| 710 |
+
// but we double check here just to be sure.
|
| 711 |
+
fatalf("internal error: writeOutput: srcfile contains unexpected newline character: %q", srcfile)
|
| 712 |
+
}
|
| 713 |
+
fmt.Fprintf(fgo1, "//line %s:1:1\n", srcfile)
|
| 714 |
+
fgo1.Write(f.Edit.Bytes())
|
| 715 |
+
|
| 716 |
+
// While we process the vars and funcs, also write gcc output.
|
| 717 |
+
// Gcc output starts with the preamble.
|
| 718 |
+
fmt.Fprintf(fgcc, "%s\n", builtinProlog)
|
| 719 |
+
fmt.Fprintf(fgcc, "%s\n", f.Preamble)
|
| 720 |
+
fmt.Fprintf(fgcc, "%s\n", gccProlog)
|
| 721 |
+
fmt.Fprintf(fgcc, "%s\n", tsanProlog)
|
| 722 |
+
fmt.Fprintf(fgcc, "%s\n", msanProlog)
|
| 723 |
+
|
| 724 |
+
for _, key := range nameKeys(f.Name) {
|
| 725 |
+
n := f.Name[key]
|
| 726 |
+
if n.FuncType != nil {
|
| 727 |
+
p.writeOutputFunc(fgcc, n)
|
| 728 |
+
}
|
| 729 |
+
}
|
| 730 |
+
|
| 731 |
+
fgo1.Close()
|
| 732 |
+
fgcc.Close()
|
| 733 |
+
}
|
| 734 |
+
|
| 735 |
+
// fixGo converts the internal Name.Go field into the name we should show
|
| 736 |
+
// to users in error messages. There's only one for now: on input we rewrite
|
| 737 |
+
// C.malloc into C._CMalloc, so change it back here.
|
| 738 |
+
func fixGo(name string) string {
|
| 739 |
+
if name == "_CMalloc" {
|
| 740 |
+
return "malloc"
|
| 741 |
+
}
|
| 742 |
+
return name
|
| 743 |
+
}
|
| 744 |
+
|
| 745 |
+
var isBuiltin = map[string]bool{
|
| 746 |
+
"_Cfunc_CString": true,
|
| 747 |
+
"_Cfunc_CBytes": true,
|
| 748 |
+
"_Cfunc_GoString": true,
|
| 749 |
+
"_Cfunc_GoStringN": true,
|
| 750 |
+
"_Cfunc_GoBytes": true,
|
| 751 |
+
"_Cfunc__CMalloc": true,
|
| 752 |
+
}
|
| 753 |
+
|
| 754 |
+
func (p *Package) writeOutputFunc(fgcc *os.File, n *Name) {
|
| 755 |
+
name := n.Mangle
|
| 756 |
+
if isBuiltin[name] || p.Written[name] {
|
| 757 |
+
// The builtins are already defined in the C prolog, and we don't
|
| 758 |
+
// want to duplicate function definitions we've already done.
|
| 759 |
+
return
|
| 760 |
+
}
|
| 761 |
+
p.Written[name] = true
|
| 762 |
+
|
| 763 |
+
if *gccgo {
|
| 764 |
+
p.writeGccgoOutputFunc(fgcc, n)
|
| 765 |
+
return
|
| 766 |
+
}
|
| 767 |
+
|
| 768 |
+
ctype, _ := p.structType(n)
|
| 769 |
+
|
| 770 |
+
// Gcc wrapper unpacks the C argument struct
|
| 771 |
+
// and calls the actual C function.
|
| 772 |
+
fmt.Fprintf(fgcc, "CGO_NO_SANITIZE_THREAD\n")
|
| 773 |
+
if n.AddError {
|
| 774 |
+
fmt.Fprintf(fgcc, "int\n")
|
| 775 |
+
} else {
|
| 776 |
+
fmt.Fprintf(fgcc, "void\n")
|
| 777 |
+
}
|
| 778 |
+
fmt.Fprintf(fgcc, "_cgo%s%s(void *v)\n", cPrefix, n.Mangle)
|
| 779 |
+
fmt.Fprintf(fgcc, "{\n")
|
| 780 |
+
if n.AddError {
|
| 781 |
+
fmt.Fprintf(fgcc, "\tint _cgo_errno;\n")
|
| 782 |
+
}
|
| 783 |
+
// We're trying to write a gcc struct that matches gc's layout.
|
| 784 |
+
// Use packed attribute to force no padding in this struct in case
|
| 785 |
+
// gcc has different packing requirements.
|
| 786 |
+
tr := n.FuncType.Result
|
| 787 |
+
if (n.Kind != "macro" && len(n.FuncType.Params) > 0) || tr != nil {
|
| 788 |
+
fmt.Fprintf(fgcc, "\t%s %v *_cgo_a = v;\n", ctype, p.packedAttribute())
|
| 789 |
+
}
|
| 790 |
+
if tr != nil {
|
| 791 |
+
// Save the stack top for use below.
|
| 792 |
+
fmt.Fprintf(fgcc, "\tchar *_cgo_stktop = _cgo_topofstack();\n")
|
| 793 |
+
fmt.Fprintf(fgcc, "\t__typeof__(_cgo_a->r) _cgo_r;\n")
|
| 794 |
+
}
|
| 795 |
+
fmt.Fprintf(fgcc, "\t_cgo_tsan_acquire();\n")
|
| 796 |
+
if n.AddError {
|
| 797 |
+
fmt.Fprintf(fgcc, "\terrno = 0;\n")
|
| 798 |
+
}
|
| 799 |
+
fmt.Fprintf(fgcc, "\t")
|
| 800 |
+
if tr != nil {
|
| 801 |
+
fmt.Fprintf(fgcc, "_cgo_r = ")
|
| 802 |
+
if c := tr.C.String(); c[len(c)-1] == '*' {
|
| 803 |
+
fmt.Fprint(fgcc, "(__typeof__(_cgo_a->r)) ")
|
| 804 |
+
}
|
| 805 |
+
}
|
| 806 |
+
if n.Kind == "macro" {
|
| 807 |
+
fmt.Fprintf(fgcc, "%s;\n", n.C)
|
| 808 |
+
} else {
|
| 809 |
+
fmt.Fprintf(fgcc, "%s(", n.C)
|
| 810 |
+
for i := range n.FuncType.Params {
|
| 811 |
+
if i > 0 {
|
| 812 |
+
fmt.Fprintf(fgcc, ", ")
|
| 813 |
+
}
|
| 814 |
+
fmt.Fprintf(fgcc, "_cgo_a->p%d", i)
|
| 815 |
+
}
|
| 816 |
+
fmt.Fprintf(fgcc, ");\n")
|
| 817 |
+
}
|
| 818 |
+
if n.AddError {
|
| 819 |
+
fmt.Fprintf(fgcc, "\t_cgo_errno = errno;\n")
|
| 820 |
+
}
|
| 821 |
+
fmt.Fprintf(fgcc, "\t_cgo_tsan_release();\n")
|
| 822 |
+
if tr != nil {
|
| 823 |
+
// The cgo call may have caused a stack copy (via a callback).
|
| 824 |
+
// Adjust the return value pointer appropriately.
|
| 825 |
+
fmt.Fprintf(fgcc, "\t_cgo_a = (void*)((char*)_cgo_a + (_cgo_topofstack() - _cgo_stktop));\n")
|
| 826 |
+
// Save the return value.
|
| 827 |
+
fmt.Fprintf(fgcc, "\t_cgo_a->r = _cgo_r;\n")
|
| 828 |
+
// The return value is on the Go stack. If we are using msan,
|
| 829 |
+
// and if the C value is partially or completely uninitialized,
|
| 830 |
+
// the assignment will mark the Go stack as uninitialized.
|
| 831 |
+
// The Go compiler does not update msan for changes to the
|
| 832 |
+
// stack. It is possible that the stack will remain
|
| 833 |
+
// uninitialized, and then later be used in a way that is
|
| 834 |
+
// visible to msan, possibly leading to a false positive.
|
| 835 |
+
// Mark the stack space as written, to avoid this problem.
|
| 836 |
+
// See issue 26209.
|
| 837 |
+
fmt.Fprintf(fgcc, "\t_cgo_msan_write(&_cgo_a->r, sizeof(_cgo_a->r));\n")
|
| 838 |
+
}
|
| 839 |
+
if n.AddError {
|
| 840 |
+
fmt.Fprintf(fgcc, "\treturn _cgo_errno;\n")
|
| 841 |
+
}
|
| 842 |
+
fmt.Fprintf(fgcc, "}\n")
|
| 843 |
+
fmt.Fprintf(fgcc, "\n")
|
| 844 |
+
}
|
| 845 |
+
|
| 846 |
+
// Write out a wrapper for a function when using gccgo. This is a
|
| 847 |
+
// simple wrapper that just calls the real function. We only need a
|
| 848 |
+
// wrapper to support static functions in the prologue--without a
|
| 849 |
+
// wrapper, we can't refer to the function, since the reference is in
|
| 850 |
+
// a different file.
|
| 851 |
+
func (p *Package) writeGccgoOutputFunc(fgcc *os.File, n *Name) {
|
| 852 |
+
fmt.Fprintf(fgcc, "CGO_NO_SANITIZE_THREAD\n")
|
| 853 |
+
if t := n.FuncType.Result; t != nil {
|
| 854 |
+
fmt.Fprintf(fgcc, "%s\n", t.C.String())
|
| 855 |
+
} else {
|
| 856 |
+
fmt.Fprintf(fgcc, "void\n")
|
| 857 |
+
}
|
| 858 |
+
fmt.Fprintf(fgcc, "_cgo%s%s(", cPrefix, n.Mangle)
|
| 859 |
+
for i, t := range n.FuncType.Params {
|
| 860 |
+
if i > 0 {
|
| 861 |
+
fmt.Fprintf(fgcc, ", ")
|
| 862 |
+
}
|
| 863 |
+
c := t.Typedef
|
| 864 |
+
if c == "" {
|
| 865 |
+
c = t.C.String()
|
| 866 |
+
}
|
| 867 |
+
fmt.Fprintf(fgcc, "%s p%d", c, i)
|
| 868 |
+
}
|
| 869 |
+
fmt.Fprintf(fgcc, ")\n")
|
| 870 |
+
fmt.Fprintf(fgcc, "{\n")
|
| 871 |
+
if t := n.FuncType.Result; t != nil {
|
| 872 |
+
fmt.Fprintf(fgcc, "\t%s _cgo_r;\n", t.C.String())
|
| 873 |
+
}
|
| 874 |
+
fmt.Fprintf(fgcc, "\t_cgo_tsan_acquire();\n")
|
| 875 |
+
fmt.Fprintf(fgcc, "\t")
|
| 876 |
+
if t := n.FuncType.Result; t != nil {
|
| 877 |
+
fmt.Fprintf(fgcc, "_cgo_r = ")
|
| 878 |
+
// Cast to void* to avoid warnings due to omitted qualifiers.
|
| 879 |
+
if c := t.C.String(); c[len(c)-1] == '*' {
|
| 880 |
+
fmt.Fprintf(fgcc, "(void*)")
|
| 881 |
+
}
|
| 882 |
+
}
|
| 883 |
+
if n.Kind == "macro" {
|
| 884 |
+
fmt.Fprintf(fgcc, "%s;\n", n.C)
|
| 885 |
+
} else {
|
| 886 |
+
fmt.Fprintf(fgcc, "%s(", n.C)
|
| 887 |
+
for i := range n.FuncType.Params {
|
| 888 |
+
if i > 0 {
|
| 889 |
+
fmt.Fprintf(fgcc, ", ")
|
| 890 |
+
}
|
| 891 |
+
fmt.Fprintf(fgcc, "p%d", i)
|
| 892 |
+
}
|
| 893 |
+
fmt.Fprintf(fgcc, ");\n")
|
| 894 |
+
}
|
| 895 |
+
fmt.Fprintf(fgcc, "\t_cgo_tsan_release();\n")
|
| 896 |
+
if t := n.FuncType.Result; t != nil {
|
| 897 |
+
fmt.Fprintf(fgcc, "\treturn ")
|
| 898 |
+
// Cast to void* to avoid warnings due to omitted qualifiers
|
| 899 |
+
// and explicit incompatible struct types.
|
| 900 |
+
if c := t.C.String(); c[len(c)-1] == '*' {
|
| 901 |
+
fmt.Fprintf(fgcc, "(void*)")
|
| 902 |
+
}
|
| 903 |
+
fmt.Fprintf(fgcc, "_cgo_r;\n")
|
| 904 |
+
}
|
| 905 |
+
fmt.Fprintf(fgcc, "}\n")
|
| 906 |
+
fmt.Fprintf(fgcc, "\n")
|
| 907 |
+
}
|
| 908 |
+
|
| 909 |
+
// packedAttribute returns host compiler struct attribute that will be
|
| 910 |
+
// used to match gc's struct layout. For example, on 386 Windows,
|
| 911 |
+
// gcc wants to 8-align int64s, but gc does not.
|
| 912 |
+
// Use __gcc_struct__ to work around https://gcc.gnu.org/PR52991 on x86,
|
| 913 |
+
// and https://golang.org/issue/5603.
|
| 914 |
+
func (p *Package) packedAttribute() string {
|
| 915 |
+
s := "__attribute__((__packed__"
|
| 916 |
+
if !p.GccIsClang && (goarch == "amd64" || goarch == "386") {
|
| 917 |
+
s += ", __gcc_struct__"
|
| 918 |
+
}
|
| 919 |
+
return s + "))"
|
| 920 |
+
}
|
| 921 |
+
|
| 922 |
+
// exportParamName returns the value of param as it should be
|
| 923 |
+
// displayed in a c header file. If param contains any non-ASCII
|
| 924 |
+
// characters, this function will return the character p followed by
|
| 925 |
+
// the value of position; otherwise, this function will return the
|
| 926 |
+
// value of param.
|
| 927 |
+
func exportParamName(param string, position int) string {
|
| 928 |
+
if param == "" {
|
| 929 |
+
return fmt.Sprintf("p%d", position)
|
| 930 |
+
}
|
| 931 |
+
|
| 932 |
+
pname := param
|
| 933 |
+
|
| 934 |
+
for i := 0; i < len(param); i++ {
|
| 935 |
+
if param[i] > unicode.MaxASCII {
|
| 936 |
+
pname = fmt.Sprintf("p%d", position)
|
| 937 |
+
break
|
| 938 |
+
}
|
| 939 |
+
}
|
| 940 |
+
|
| 941 |
+
return pname
|
| 942 |
+
}
|
| 943 |
+
|
| 944 |
+
// Write out the various stubs we need to support functions exported
|
| 945 |
+
// from Go so that they are callable from C.
|
| 946 |
+
func (p *Package) writeExports(fgo2, fm, fgcc, fgcch io.Writer) {
|
| 947 |
+
p.writeExportHeader(fgcch)
|
| 948 |
+
|
| 949 |
+
fmt.Fprintf(fgcc, "/* Code generated by cmd/cgo; DO NOT EDIT. */\n\n")
|
| 950 |
+
fmt.Fprintf(fgcc, "#include <stdlib.h>\n")
|
| 951 |
+
fmt.Fprintf(fgcc, "#include \"_cgo_export.h\"\n\n")
|
| 952 |
+
|
| 953 |
+
// We use packed structs, but they are always aligned.
|
| 954 |
+
// The pragmas and address-of-packed-member are only recognized as
|
| 955 |
+
// warning groups in clang 4.0+, so ignore unknown pragmas first.
|
| 956 |
+
fmt.Fprintf(fgcc, "#pragma GCC diagnostic ignored \"-Wunknown-pragmas\"\n")
|
| 957 |
+
fmt.Fprintf(fgcc, "#pragma GCC diagnostic ignored \"-Wpragmas\"\n")
|
| 958 |
+
fmt.Fprintf(fgcc, "#pragma GCC diagnostic ignored \"-Waddress-of-packed-member\"\n")
|
| 959 |
+
fmt.Fprintf(fgcc, "#pragma GCC diagnostic ignored \"-Wunknown-warning-option\"\n")
|
| 960 |
+
fmt.Fprintf(fgcc, "#pragma GCC diagnostic ignored \"-Wunaligned-access\"\n")
|
| 961 |
+
|
| 962 |
+
fmt.Fprintf(fgcc, "extern void crosscall2(void (*fn)(void *), void *, int, size_t);\n")
|
| 963 |
+
fmt.Fprintf(fgcc, "extern size_t _cgo_wait_runtime_init_done(void);\n")
|
| 964 |
+
fmt.Fprintf(fgcc, "extern void _cgo_release_context(size_t);\n\n")
|
| 965 |
+
fmt.Fprintf(fgcc, "extern char* _cgo_topofstack(void);")
|
| 966 |
+
fmt.Fprintf(fgcc, "%s\n", tsanProlog)
|
| 967 |
+
fmt.Fprintf(fgcc, "%s\n", msanProlog)
|
| 968 |
+
|
| 969 |
+
for _, exp := range p.ExpFunc {
|
| 970 |
+
fn := exp.Func
|
| 971 |
+
|
| 972 |
+
// Construct a struct that will be used to communicate
|
| 973 |
+
// arguments from C to Go. The C and Go definitions
|
| 974 |
+
// just have to agree. The gcc struct will be compiled
|
| 975 |
+
// with __attribute__((packed)) so all padding must be
|
| 976 |
+
// accounted for explicitly.
|
| 977 |
+
var ctype strings.Builder
|
| 978 |
+
const start = "struct {\n"
|
| 979 |
+
ctype.WriteString(start)
|
| 980 |
+
gotype := new(bytes.Buffer)
|
| 981 |
+
fmt.Fprintf(gotype, "struct {\n")
|
| 982 |
+
off := int64(0)
|
| 983 |
+
npad := 0
|
| 984 |
+
// the align is at least 1 (for char)
|
| 985 |
+
maxAlign := int64(1)
|
| 986 |
+
argField := func(typ ast.Expr, namePat string, args ...any) {
|
| 987 |
+
name := fmt.Sprintf(namePat, args...)
|
| 988 |
+
t := p.cgoType(typ)
|
| 989 |
+
if off%t.Align != 0 {
|
| 990 |
+
pad := t.Align - off%t.Align
|
| 991 |
+
fmt.Fprintf(&ctype, "\t\tchar __pad%d[%d];\n", npad, pad)
|
| 992 |
+
off += pad
|
| 993 |
+
npad++
|
| 994 |
+
}
|
| 995 |
+
fmt.Fprintf(&ctype, "\t\t%s %s;\n", t.C, name)
|
| 996 |
+
fmt.Fprintf(gotype, "\t\t%s ", name)
|
| 997 |
+
noSourceConf.Fprint(gotype, fset, typ)
|
| 998 |
+
fmt.Fprintf(gotype, "\n")
|
| 999 |
+
off += t.Size
|
| 1000 |
+
// keep track of the maximum alignment among all fields
|
| 1001 |
+
// so that we can align the struct correctly
|
| 1002 |
+
if t.Align > maxAlign {
|
| 1003 |
+
maxAlign = t.Align
|
| 1004 |
+
}
|
| 1005 |
+
}
|
| 1006 |
+
if fn.Recv != nil {
|
| 1007 |
+
argField(fn.Recv.List[0].Type, "recv")
|
| 1008 |
+
}
|
| 1009 |
+
fntype := fn.Type
|
| 1010 |
+
forFieldList(fntype.Params,
|
| 1011 |
+
func(i int, aname string, atype ast.Expr) {
|
| 1012 |
+
argField(atype, "p%d", i)
|
| 1013 |
+
})
|
| 1014 |
+
forFieldList(fntype.Results,
|
| 1015 |
+
func(i int, aname string, atype ast.Expr) {
|
| 1016 |
+
argField(atype, "r%d", i)
|
| 1017 |
+
})
|
| 1018 |
+
if ctype.Len() == len(start) {
|
| 1019 |
+
ctype.WriteString("\t\tchar unused;\n") // avoid empty struct
|
| 1020 |
+
}
|
| 1021 |
+
ctype.WriteString("\t}")
|
| 1022 |
+
fmt.Fprintf(gotype, "\t}")
|
| 1023 |
+
|
| 1024 |
+
// Get the return type of the wrapper function
|
| 1025 |
+
// compiled by gcc.
|
| 1026 |
+
gccResult := ""
|
| 1027 |
+
if fntype.Results == nil || len(fntype.Results.List) == 0 {
|
| 1028 |
+
gccResult = "void"
|
| 1029 |
+
} else if len(fntype.Results.List) == 1 && len(fntype.Results.List[0].Names) <= 1 {
|
| 1030 |
+
gccResult = p.cgoType(fntype.Results.List[0].Type).C.String()
|
| 1031 |
+
} else {
|
| 1032 |
+
fmt.Fprintf(fgcch, "\n/* Return type for %s */\n", exp.ExpName)
|
| 1033 |
+
fmt.Fprintf(fgcch, "struct %s_return {\n", exp.ExpName)
|
| 1034 |
+
forFieldList(fntype.Results,
|
| 1035 |
+
func(i int, aname string, atype ast.Expr) {
|
| 1036 |
+
fmt.Fprintf(fgcch, "\t%s r%d;", p.cgoType(atype).C, i)
|
| 1037 |
+
if len(aname) > 0 {
|
| 1038 |
+
fmt.Fprintf(fgcch, " /* %s */", aname)
|
| 1039 |
+
}
|
| 1040 |
+
fmt.Fprint(fgcch, "\n")
|
| 1041 |
+
})
|
| 1042 |
+
fmt.Fprintf(fgcch, "};\n")
|
| 1043 |
+
gccResult = "struct " + exp.ExpName + "_return"
|
| 1044 |
+
}
|
| 1045 |
+
|
| 1046 |
+
// Build the wrapper function compiled by gcc.
|
| 1047 |
+
var s strings.Builder
|
| 1048 |
+
fmt.Fprintf(&s, "%s %s(", gccResult, exp.ExpName)
|
| 1049 |
+
if fn.Recv != nil {
|
| 1050 |
+
s.WriteString(p.cgoType(fn.Recv.List[0].Type).C.String())
|
| 1051 |
+
s.WriteString(" recv")
|
| 1052 |
+
}
|
| 1053 |
+
|
| 1054 |
+
if len(fntype.Params.List) > 0 {
|
| 1055 |
+
forFieldList(fntype.Params,
|
| 1056 |
+
func(i int, aname string, atype ast.Expr) {
|
| 1057 |
+
if i > 0 || fn.Recv != nil {
|
| 1058 |
+
s.WriteString(", ")
|
| 1059 |
+
}
|
| 1060 |
+
fmt.Fprintf(&s, "%s %s", p.cgoType(atype).C, exportParamName(aname, i))
|
| 1061 |
+
})
|
| 1062 |
+
} else {
|
| 1063 |
+
s.WriteString("void")
|
| 1064 |
+
}
|
| 1065 |
+
s.WriteByte(')')
|
| 1066 |
+
|
| 1067 |
+
if len(exp.Doc) > 0 {
|
| 1068 |
+
fmt.Fprintf(fgcch, "\n%s", exp.Doc)
|
| 1069 |
+
if !strings.HasSuffix(exp.Doc, "\n") {
|
| 1070 |
+
fmt.Fprint(fgcch, "\n")
|
| 1071 |
+
}
|
| 1072 |
+
}
|
| 1073 |
+
fmt.Fprintf(fgcch, "extern %s;\n", s.String())
|
| 1074 |
+
|
| 1075 |
+
fmt.Fprintf(fgcc, "extern void _cgoexp%s_%s(void *);\n", cPrefix, exp.ExpName)
|
| 1076 |
+
fmt.Fprintf(fgcc, "\nCGO_NO_SANITIZE_THREAD")
|
| 1077 |
+
fmt.Fprintf(fgcc, "\n%s\n", s.String())
|
| 1078 |
+
fmt.Fprintf(fgcc, "{\n")
|
| 1079 |
+
fmt.Fprintf(fgcc, "\tsize_t _cgo_ctxt = _cgo_wait_runtime_init_done();\n")
|
| 1080 |
+
// The results part of the argument structure must be
|
| 1081 |
+
// initialized to 0 so the write barriers generated by
|
| 1082 |
+
// the assignments to these fields in Go are safe.
|
| 1083 |
+
//
|
| 1084 |
+
// We use a local static variable to get the zeroed
|
| 1085 |
+
// value of the argument type. This avoids including
|
| 1086 |
+
// string.h for memset, and is also robust to C++
|
| 1087 |
+
// types with constructors. Both GCC and LLVM optimize
|
| 1088 |
+
// this into just zeroing _cgo_a.
|
| 1089 |
+
//
|
| 1090 |
+
// The struct should be aligned to the maximum alignment
|
| 1091 |
+
// of any of its fields. This to avoid alignment
|
| 1092 |
+
// issues.
|
| 1093 |
+
fmt.Fprintf(fgcc, "\ttypedef %s %v __attribute__((aligned(%d))) _cgo_argtype;\n", ctype.String(), p.packedAttribute(), maxAlign)
|
| 1094 |
+
fmt.Fprintf(fgcc, "\tstatic _cgo_argtype _cgo_zero;\n")
|
| 1095 |
+
fmt.Fprintf(fgcc, "\t_cgo_argtype _cgo_a = _cgo_zero;\n")
|
| 1096 |
+
if gccResult != "void" && (len(fntype.Results.List) > 1 || len(fntype.Results.List[0].Names) > 1) {
|
| 1097 |
+
fmt.Fprintf(fgcc, "\t%s r;\n", gccResult)
|
| 1098 |
+
}
|
| 1099 |
+
if fn.Recv != nil {
|
| 1100 |
+
fmt.Fprintf(fgcc, "\t_cgo_a.recv = recv;\n")
|
| 1101 |
+
}
|
| 1102 |
+
forFieldList(fntype.Params,
|
| 1103 |
+
func(i int, aname string, atype ast.Expr) {
|
| 1104 |
+
fmt.Fprintf(fgcc, "\t_cgo_a.p%d = %s;\n", i, exportParamName(aname, i))
|
| 1105 |
+
})
|
| 1106 |
+
fmt.Fprintf(fgcc, "\t_cgo_tsan_release();\n")
|
| 1107 |
+
fmt.Fprintf(fgcc, "\tcrosscall2(_cgoexp%s_%s, &_cgo_a, %d, _cgo_ctxt);\n", cPrefix, exp.ExpName, off)
|
| 1108 |
+
fmt.Fprintf(fgcc, "\t_cgo_tsan_acquire();\n")
|
| 1109 |
+
fmt.Fprintf(fgcc, "\t_cgo_release_context(_cgo_ctxt);\n")
|
| 1110 |
+
if gccResult != "void" {
|
| 1111 |
+
if len(fntype.Results.List) == 1 && len(fntype.Results.List[0].Names) <= 1 {
|
| 1112 |
+
fmt.Fprintf(fgcc, "\treturn _cgo_a.r0;\n")
|
| 1113 |
+
} else {
|
| 1114 |
+
forFieldList(fntype.Results,
|
| 1115 |
+
func(i int, aname string, atype ast.Expr) {
|
| 1116 |
+
fmt.Fprintf(fgcc, "\tr.r%d = _cgo_a.r%d;\n", i, i)
|
| 1117 |
+
})
|
| 1118 |
+
fmt.Fprintf(fgcc, "\treturn r;\n")
|
| 1119 |
+
}
|
| 1120 |
+
}
|
| 1121 |
+
fmt.Fprintf(fgcc, "}\n")
|
| 1122 |
+
|
| 1123 |
+
// In internal linking mode, the Go linker sees both
|
| 1124 |
+
// the C wrapper written above and the Go wrapper it
|
| 1125 |
+
// references. Hence, export the C wrapper (e.g., for
|
| 1126 |
+
// if we're building a shared object). The Go linker
|
| 1127 |
+
// will resolve the C wrapper's reference to the Go
|
| 1128 |
+
// wrapper without a separate export.
|
| 1129 |
+
fmt.Fprintf(fgo2, "//go:cgo_export_dynamic %s\n", exp.ExpName)
|
| 1130 |
+
// cgo_export_static refers to a symbol by its linker
|
| 1131 |
+
// name, so set the linker name of the Go wrapper.
|
| 1132 |
+
fmt.Fprintf(fgo2, "//go:linkname _cgoexp%s_%s _cgoexp%s_%s\n", cPrefix, exp.ExpName, cPrefix, exp.ExpName)
|
| 1133 |
+
// In external linking mode, the Go linker sees the Go
|
| 1134 |
+
// wrapper, but not the C wrapper. For this case,
|
| 1135 |
+
// export the Go wrapper so the host linker can
|
| 1136 |
+
// resolve the reference from the C wrapper to the Go
|
| 1137 |
+
// wrapper.
|
| 1138 |
+
fmt.Fprintf(fgo2, "//go:cgo_export_static _cgoexp%s_%s\n", cPrefix, exp.ExpName)
|
| 1139 |
+
|
| 1140 |
+
// Build the wrapper function compiled by cmd/compile.
|
| 1141 |
+
// This unpacks the argument struct above and calls the Go function.
|
| 1142 |
+
fmt.Fprintf(fgo2, "func _cgoexp%s_%s(a *%s) {\n", cPrefix, exp.ExpName, gotype)
|
| 1143 |
+
|
| 1144 |
+
fmt.Fprintf(fm, "void _cgoexp%s_%s(void* p __attribute__((unused))){}\n", cPrefix, exp.ExpName)
|
| 1145 |
+
|
| 1146 |
+
fmt.Fprintf(fgo2, "\t")
|
| 1147 |
+
|
| 1148 |
+
if gccResult != "void" {
|
| 1149 |
+
// Write results back to frame.
|
| 1150 |
+
forFieldList(fntype.Results,
|
| 1151 |
+
func(i int, aname string, atype ast.Expr) {
|
| 1152 |
+
if i > 0 {
|
| 1153 |
+
fmt.Fprintf(fgo2, ", ")
|
| 1154 |
+
}
|
| 1155 |
+
fmt.Fprintf(fgo2, "a.r%d", i)
|
| 1156 |
+
})
|
| 1157 |
+
fmt.Fprintf(fgo2, " = ")
|
| 1158 |
+
}
|
| 1159 |
+
if fn.Recv != nil {
|
| 1160 |
+
fmt.Fprintf(fgo2, "a.recv.")
|
| 1161 |
+
}
|
| 1162 |
+
fmt.Fprintf(fgo2, "%s(", exp.Func.Name)
|
| 1163 |
+
forFieldList(fntype.Params,
|
| 1164 |
+
func(i int, aname string, atype ast.Expr) {
|
| 1165 |
+
if i > 0 {
|
| 1166 |
+
fmt.Fprint(fgo2, ", ")
|
| 1167 |
+
}
|
| 1168 |
+
fmt.Fprintf(fgo2, "a.p%d", i)
|
| 1169 |
+
})
|
| 1170 |
+
fmt.Fprint(fgo2, ")\n")
|
| 1171 |
+
if gccResult != "void" {
|
| 1172 |
+
// Verify that any results don't contain any
|
| 1173 |
+
// Go pointers.
|
| 1174 |
+
forFieldList(fntype.Results,
|
| 1175 |
+
func(i int, aname string, atype ast.Expr) {
|
| 1176 |
+
if !p.hasPointer(nil, atype, false) {
|
| 1177 |
+
return
|
| 1178 |
+
}
|
| 1179 |
+
|
| 1180 |
+
// Use the export'ed file/line in error messages.
|
| 1181 |
+
pos := fset.Position(exp.Func.Pos())
|
| 1182 |
+
fmt.Fprintf(fgo2, "//line %s:%d\n", pos.Filename, pos.Line)
|
| 1183 |
+
fmt.Fprintf(fgo2, "\t_cgoCheckResult(a.r%d)\n", i)
|
| 1184 |
+
})
|
| 1185 |
+
}
|
| 1186 |
+
fmt.Fprint(fgo2, "}\n")
|
| 1187 |
+
}
|
| 1188 |
+
|
| 1189 |
+
fmt.Fprintf(fgcch, "%s", gccExportHeaderEpilog)
|
| 1190 |
+
}
|
| 1191 |
+
|
| 1192 |
+
// Write out the C header allowing C code to call exported gccgo functions.
|
| 1193 |
+
func (p *Package) writeGccgoExports(fgo2, fm, fgcc, fgcch io.Writer) {
|
| 1194 |
+
gccgoSymbolPrefix := p.gccgoSymbolPrefix()
|
| 1195 |
+
|
| 1196 |
+
p.writeExportHeader(fgcch)
|
| 1197 |
+
|
| 1198 |
+
fmt.Fprintf(fgcc, "/* Code generated by cmd/cgo; DO NOT EDIT. */\n\n")
|
| 1199 |
+
fmt.Fprintf(fgcc, "#include \"_cgo_export.h\"\n")
|
| 1200 |
+
|
| 1201 |
+
fmt.Fprintf(fgcc, "%s\n", gccgoExportFileProlog)
|
| 1202 |
+
fmt.Fprintf(fgcc, "%s\n", tsanProlog)
|
| 1203 |
+
fmt.Fprintf(fgcc, "%s\n", msanProlog)
|
| 1204 |
+
|
| 1205 |
+
for _, exp := range p.ExpFunc {
|
| 1206 |
+
fn := exp.Func
|
| 1207 |
+
fntype := fn.Type
|
| 1208 |
+
|
| 1209 |
+
cdeclBuf := new(strings.Builder)
|
| 1210 |
+
resultCount := 0
|
| 1211 |
+
forFieldList(fntype.Results,
|
| 1212 |
+
func(i int, aname string, atype ast.Expr) { resultCount++ })
|
| 1213 |
+
switch resultCount {
|
| 1214 |
+
case 0:
|
| 1215 |
+
fmt.Fprintf(cdeclBuf, "void")
|
| 1216 |
+
case 1:
|
| 1217 |
+
forFieldList(fntype.Results,
|
| 1218 |
+
func(i int, aname string, atype ast.Expr) {
|
| 1219 |
+
t := p.cgoType(atype)
|
| 1220 |
+
fmt.Fprintf(cdeclBuf, "%s", t.C)
|
| 1221 |
+
})
|
| 1222 |
+
default:
|
| 1223 |
+
// Declare a result struct.
|
| 1224 |
+
fmt.Fprintf(fgcch, "\n/* Return type for %s */\n", exp.ExpName)
|
| 1225 |
+
fmt.Fprintf(fgcch, "struct %s_return {\n", exp.ExpName)
|
| 1226 |
+
forFieldList(fntype.Results,
|
| 1227 |
+
func(i int, aname string, atype ast.Expr) {
|
| 1228 |
+
t := p.cgoType(atype)
|
| 1229 |
+
fmt.Fprintf(fgcch, "\t%s r%d;", t.C, i)
|
| 1230 |
+
if len(aname) > 0 {
|
| 1231 |
+
fmt.Fprintf(fgcch, " /* %s */", aname)
|
| 1232 |
+
}
|
| 1233 |
+
fmt.Fprint(fgcch, "\n")
|
| 1234 |
+
})
|
| 1235 |
+
fmt.Fprintf(fgcch, "};\n")
|
| 1236 |
+
fmt.Fprintf(cdeclBuf, "struct %s_return", exp.ExpName)
|
| 1237 |
+
}
|
| 1238 |
+
|
| 1239 |
+
cRet := cdeclBuf.String()
|
| 1240 |
+
|
| 1241 |
+
cdeclBuf = new(strings.Builder)
|
| 1242 |
+
fmt.Fprintf(cdeclBuf, "(")
|
| 1243 |
+
if fn.Recv != nil {
|
| 1244 |
+
fmt.Fprintf(cdeclBuf, "%s recv", p.cgoType(fn.Recv.List[0].Type).C.String())
|
| 1245 |
+
}
|
| 1246 |
+
// Function parameters.
|
| 1247 |
+
forFieldList(fntype.Params,
|
| 1248 |
+
func(i int, aname string, atype ast.Expr) {
|
| 1249 |
+
if i > 0 || fn.Recv != nil {
|
| 1250 |
+
fmt.Fprintf(cdeclBuf, ", ")
|
| 1251 |
+
}
|
| 1252 |
+
t := p.cgoType(atype)
|
| 1253 |
+
fmt.Fprintf(cdeclBuf, "%s p%d", t.C, i)
|
| 1254 |
+
})
|
| 1255 |
+
fmt.Fprintf(cdeclBuf, ")")
|
| 1256 |
+
cParams := cdeclBuf.String()
|
| 1257 |
+
|
| 1258 |
+
if len(exp.Doc) > 0 {
|
| 1259 |
+
fmt.Fprintf(fgcch, "\n%s", exp.Doc)
|
| 1260 |
+
}
|
| 1261 |
+
|
| 1262 |
+
fmt.Fprintf(fgcch, "extern %s %s%s;\n", cRet, exp.ExpName, cParams)
|
| 1263 |
+
|
| 1264 |
+
// We need to use a name that will be exported by the
|
| 1265 |
+
// Go code; otherwise gccgo will make it static and we
|
| 1266 |
+
// will not be able to link against it from the C
|
| 1267 |
+
// code.
|
| 1268 |
+
goName := "Cgoexp_" + exp.ExpName
|
| 1269 |
+
fmt.Fprintf(fgcc, `extern %s %s %s __asm__("%s.%s");`, cRet, goName, cParams, gccgoSymbolPrefix, gccgoToSymbol(goName))
|
| 1270 |
+
fmt.Fprint(fgcc, "\n")
|
| 1271 |
+
|
| 1272 |
+
fmt.Fprint(fgcc, "\nCGO_NO_SANITIZE_THREAD\n")
|
| 1273 |
+
fmt.Fprintf(fgcc, "%s %s %s {\n", cRet, exp.ExpName, cParams)
|
| 1274 |
+
if resultCount > 0 {
|
| 1275 |
+
fmt.Fprintf(fgcc, "\t%s r;\n", cRet)
|
| 1276 |
+
}
|
| 1277 |
+
fmt.Fprintf(fgcc, "\tif(_cgo_wait_runtime_init_done)\n")
|
| 1278 |
+
fmt.Fprintf(fgcc, "\t\t_cgo_wait_runtime_init_done();\n")
|
| 1279 |
+
fmt.Fprintf(fgcc, "\t_cgo_tsan_release();\n")
|
| 1280 |
+
fmt.Fprint(fgcc, "\t")
|
| 1281 |
+
if resultCount > 0 {
|
| 1282 |
+
fmt.Fprint(fgcc, "r = ")
|
| 1283 |
+
}
|
| 1284 |
+
fmt.Fprintf(fgcc, "%s(", goName)
|
| 1285 |
+
if fn.Recv != nil {
|
| 1286 |
+
fmt.Fprint(fgcc, "recv")
|
| 1287 |
+
}
|
| 1288 |
+
forFieldList(fntype.Params,
|
| 1289 |
+
func(i int, aname string, atype ast.Expr) {
|
| 1290 |
+
if i > 0 || fn.Recv != nil {
|
| 1291 |
+
fmt.Fprintf(fgcc, ", ")
|
| 1292 |
+
}
|
| 1293 |
+
fmt.Fprintf(fgcc, "p%d", i)
|
| 1294 |
+
})
|
| 1295 |
+
fmt.Fprint(fgcc, ");\n")
|
| 1296 |
+
fmt.Fprintf(fgcc, "\t_cgo_tsan_acquire();\n")
|
| 1297 |
+
if resultCount > 0 {
|
| 1298 |
+
fmt.Fprint(fgcc, "\treturn r;\n")
|
| 1299 |
+
}
|
| 1300 |
+
fmt.Fprint(fgcc, "}\n")
|
| 1301 |
+
|
| 1302 |
+
// Dummy declaration for _cgo_main.c
|
| 1303 |
+
fmt.Fprintf(fm, `char %s[1] __asm__("%s.%s");`, goName, gccgoSymbolPrefix, gccgoToSymbol(goName))
|
| 1304 |
+
fmt.Fprint(fm, "\n")
|
| 1305 |
+
|
| 1306 |
+
// For gccgo we use a wrapper function in Go, in order
|
| 1307 |
+
// to call CgocallBack and CgocallBackDone.
|
| 1308 |
+
|
| 1309 |
+
// This code uses printer.Fprint, not conf.Fprint,
|
| 1310 |
+
// because we don't want //line comments in the middle
|
| 1311 |
+
// of the function types.
|
| 1312 |
+
fmt.Fprint(fgo2, "\n")
|
| 1313 |
+
fmt.Fprintf(fgo2, "func %s(", goName)
|
| 1314 |
+
if fn.Recv != nil {
|
| 1315 |
+
fmt.Fprint(fgo2, "recv ")
|
| 1316 |
+
printer.Fprint(fgo2, fset, fn.Recv.List[0].Type)
|
| 1317 |
+
}
|
| 1318 |
+
forFieldList(fntype.Params,
|
| 1319 |
+
func(i int, aname string, atype ast.Expr) {
|
| 1320 |
+
if i > 0 || fn.Recv != nil {
|
| 1321 |
+
fmt.Fprintf(fgo2, ", ")
|
| 1322 |
+
}
|
| 1323 |
+
fmt.Fprintf(fgo2, "p%d ", i)
|
| 1324 |
+
printer.Fprint(fgo2, fset, atype)
|
| 1325 |
+
})
|
| 1326 |
+
fmt.Fprintf(fgo2, ")")
|
| 1327 |
+
if resultCount > 0 {
|
| 1328 |
+
fmt.Fprintf(fgo2, " (")
|
| 1329 |
+
forFieldList(fntype.Results,
|
| 1330 |
+
func(i int, aname string, atype ast.Expr) {
|
| 1331 |
+
if i > 0 {
|
| 1332 |
+
fmt.Fprint(fgo2, ", ")
|
| 1333 |
+
}
|
| 1334 |
+
printer.Fprint(fgo2, fset, atype)
|
| 1335 |
+
})
|
| 1336 |
+
fmt.Fprint(fgo2, ")")
|
| 1337 |
+
}
|
| 1338 |
+
fmt.Fprint(fgo2, " {\n")
|
| 1339 |
+
fmt.Fprint(fgo2, "\tsyscall.CgocallBack()\n")
|
| 1340 |
+
fmt.Fprint(fgo2, "\tdefer syscall.CgocallBackDone()\n")
|
| 1341 |
+
fmt.Fprint(fgo2, "\t")
|
| 1342 |
+
if resultCount > 0 {
|
| 1343 |
+
fmt.Fprint(fgo2, "return ")
|
| 1344 |
+
}
|
| 1345 |
+
if fn.Recv != nil {
|
| 1346 |
+
fmt.Fprint(fgo2, "recv.")
|
| 1347 |
+
}
|
| 1348 |
+
fmt.Fprintf(fgo2, "%s(", exp.Func.Name)
|
| 1349 |
+
forFieldList(fntype.Params,
|
| 1350 |
+
func(i int, aname string, atype ast.Expr) {
|
| 1351 |
+
if i > 0 {
|
| 1352 |
+
fmt.Fprint(fgo2, ", ")
|
| 1353 |
+
}
|
| 1354 |
+
fmt.Fprintf(fgo2, "p%d", i)
|
| 1355 |
+
})
|
| 1356 |
+
fmt.Fprint(fgo2, ")\n")
|
| 1357 |
+
fmt.Fprint(fgo2, "}\n")
|
| 1358 |
+
}
|
| 1359 |
+
|
| 1360 |
+
fmt.Fprintf(fgcch, "%s", gccExportHeaderEpilog)
|
| 1361 |
+
}
|
| 1362 |
+
|
| 1363 |
+
// writeExportHeader writes out the start of the _cgo_export.h file.
|
| 1364 |
+
func (p *Package) writeExportHeader(fgcch io.Writer) {
|
| 1365 |
+
fmt.Fprintf(fgcch, "/* Code generated by cmd/cgo; DO NOT EDIT. */\n\n")
|
| 1366 |
+
pkg := *importPath
|
| 1367 |
+
if pkg == "" {
|
| 1368 |
+
pkg = p.PackagePath
|
| 1369 |
+
}
|
| 1370 |
+
fmt.Fprintf(fgcch, "/* package %s */\n\n", pkg)
|
| 1371 |
+
fmt.Fprintf(fgcch, "%s\n", builtinExportProlog)
|
| 1372 |
+
|
| 1373 |
+
// Remove absolute paths from #line comments in the preamble.
|
| 1374 |
+
// They aren't useful for people using the header file,
|
| 1375 |
+
// and they mean that the header files change based on the
|
| 1376 |
+
// exact location of GOPATH.
|
| 1377 |
+
re := regexp.MustCompile(`(?m)^(#line\s+\d+\s+")[^"]*[/\\]([^"]*")`)
|
| 1378 |
+
preamble := re.ReplaceAllString(p.Preamble, "$1$2")
|
| 1379 |
+
|
| 1380 |
+
fmt.Fprintf(fgcch, "/* Start of preamble from import \"C\" comments. */\n\n")
|
| 1381 |
+
fmt.Fprintf(fgcch, "%s\n", preamble)
|
| 1382 |
+
fmt.Fprintf(fgcch, "\n/* End of preamble from import \"C\" comments. */\n\n")
|
| 1383 |
+
|
| 1384 |
+
fmt.Fprintf(fgcch, "%s\n", p.gccExportHeaderProlog())
|
| 1385 |
+
}
|
| 1386 |
+
|
| 1387 |
+
// gccgoToSymbol converts a name to a mangled symbol for gccgo.
|
| 1388 |
+
func gccgoToSymbol(ppath string) string {
|
| 1389 |
+
if gccgoMangler == nil {
|
| 1390 |
+
var err error
|
| 1391 |
+
cmd := os.Getenv("GCCGO")
|
| 1392 |
+
if cmd == "" {
|
| 1393 |
+
cmd, err = exec.LookPath("gccgo")
|
| 1394 |
+
if err != nil {
|
| 1395 |
+
fatalf("unable to locate gccgo: %v", err)
|
| 1396 |
+
}
|
| 1397 |
+
}
|
| 1398 |
+
gccgoMangler, err = pkgpath.ToSymbolFunc(cmd, *objDir)
|
| 1399 |
+
if err != nil {
|
| 1400 |
+
fatalf("%v", err)
|
| 1401 |
+
}
|
| 1402 |
+
}
|
| 1403 |
+
return gccgoMangler(ppath)
|
| 1404 |
+
}
|
| 1405 |
+
|
| 1406 |
+
// Return the package prefix when using gccgo.
|
| 1407 |
+
func (p *Package) gccgoSymbolPrefix() string {
|
| 1408 |
+
if !*gccgo {
|
| 1409 |
+
return ""
|
| 1410 |
+
}
|
| 1411 |
+
|
| 1412 |
+
if *gccgopkgpath != "" {
|
| 1413 |
+
return gccgoToSymbol(*gccgopkgpath)
|
| 1414 |
+
}
|
| 1415 |
+
if *gccgoprefix == "" && p.PackageName == "main" {
|
| 1416 |
+
return "main"
|
| 1417 |
+
}
|
| 1418 |
+
prefix := gccgoToSymbol(*gccgoprefix)
|
| 1419 |
+
if prefix == "" {
|
| 1420 |
+
prefix = "go"
|
| 1421 |
+
}
|
| 1422 |
+
return prefix + "." + p.PackageName
|
| 1423 |
+
}
|
| 1424 |
+
|
| 1425 |
+
// Call a function for each entry in an ast.FieldList, passing the
|
| 1426 |
+
// index into the list, the name if any, and the type.
|
| 1427 |
+
func forFieldList(fl *ast.FieldList, fn func(int, string, ast.Expr)) {
|
| 1428 |
+
if fl == nil {
|
| 1429 |
+
return
|
| 1430 |
+
}
|
| 1431 |
+
i := 0
|
| 1432 |
+
for _, r := range fl.List {
|
| 1433 |
+
if r.Names == nil {
|
| 1434 |
+
fn(i, "", r.Type)
|
| 1435 |
+
i++
|
| 1436 |
+
} else {
|
| 1437 |
+
for _, n := range r.Names {
|
| 1438 |
+
fn(i, n.Name, r.Type)
|
| 1439 |
+
i++
|
| 1440 |
+
}
|
| 1441 |
+
}
|
| 1442 |
+
}
|
| 1443 |
+
}
|
| 1444 |
+
|
| 1445 |
+
func c(repr string, args ...any) *TypeRepr {
|
| 1446 |
+
return &TypeRepr{repr, args}
|
| 1447 |
+
}
|
| 1448 |
+
|
| 1449 |
+
// Map predeclared Go types to Type.
|
| 1450 |
+
var goTypes = map[string]*Type{
|
| 1451 |
+
"bool": {Size: 1, Align: 1, C: c("GoUint8")},
|
| 1452 |
+
"byte": {Size: 1, Align: 1, C: c("GoUint8")},
|
| 1453 |
+
"int": {Size: 0, Align: 0, C: c("GoInt")},
|
| 1454 |
+
"uint": {Size: 0, Align: 0, C: c("GoUint")},
|
| 1455 |
+
"rune": {Size: 4, Align: 4, C: c("GoInt32")},
|
| 1456 |
+
"int8": {Size: 1, Align: 1, C: c("GoInt8")},
|
| 1457 |
+
"uint8": {Size: 1, Align: 1, C: c("GoUint8")},
|
| 1458 |
+
"int16": {Size: 2, Align: 2, C: c("GoInt16")},
|
| 1459 |
+
"uint16": {Size: 2, Align: 2, C: c("GoUint16")},
|
| 1460 |
+
"int32": {Size: 4, Align: 4, C: c("GoInt32")},
|
| 1461 |
+
"uint32": {Size: 4, Align: 4, C: c("GoUint32")},
|
| 1462 |
+
"int64": {Size: 8, Align: 8, C: c("GoInt64")},
|
| 1463 |
+
"uint64": {Size: 8, Align: 8, C: c("GoUint64")},
|
| 1464 |
+
"float32": {Size: 4, Align: 4, C: c("GoFloat32")},
|
| 1465 |
+
"float64": {Size: 8, Align: 8, C: c("GoFloat64")},
|
| 1466 |
+
"complex64": {Size: 8, Align: 4, C: c("GoComplex64")},
|
| 1467 |
+
"complex128": {Size: 16, Align: 8, C: c("GoComplex128")},
|
| 1468 |
+
}
|
| 1469 |
+
|
| 1470 |
+
// Map an ast type to a Type.
|
| 1471 |
+
func (p *Package) cgoType(e ast.Expr) *Type {
|
| 1472 |
+
return p.doCgoType(e, make(map[ast.Expr]bool))
|
| 1473 |
+
}
|
| 1474 |
+
|
| 1475 |
+
// Map an ast type to a Type, avoiding cycles.
|
| 1476 |
+
func (p *Package) doCgoType(e ast.Expr, m map[ast.Expr]bool) *Type {
|
| 1477 |
+
if m[e] {
|
| 1478 |
+
fatalf("%s: invalid recursive type", fset.Position(e.Pos()))
|
| 1479 |
+
}
|
| 1480 |
+
m[e] = true
|
| 1481 |
+
switch t := e.(type) {
|
| 1482 |
+
case *ast.StarExpr:
|
| 1483 |
+
x := p.doCgoType(t.X, m)
|
| 1484 |
+
return &Type{Size: p.PtrSize, Align: p.PtrSize, C: c("%s*", x.C)}
|
| 1485 |
+
case *ast.ArrayType:
|
| 1486 |
+
if t.Len == nil {
|
| 1487 |
+
// Slice: pointer, len, cap.
|
| 1488 |
+
return &Type{Size: p.PtrSize * 3, Align: p.PtrSize, C: c("GoSlice")}
|
| 1489 |
+
}
|
| 1490 |
+
// Non-slice array types are not supported.
|
| 1491 |
+
case *ast.StructType:
|
| 1492 |
+
// Not supported.
|
| 1493 |
+
case *ast.FuncType:
|
| 1494 |
+
return &Type{Size: p.PtrSize, Align: p.PtrSize, C: c("void*")}
|
| 1495 |
+
case *ast.InterfaceType:
|
| 1496 |
+
return &Type{Size: 2 * p.PtrSize, Align: p.PtrSize, C: c("GoInterface")}
|
| 1497 |
+
case *ast.MapType:
|
| 1498 |
+
return &Type{Size: p.PtrSize, Align: p.PtrSize, C: c("GoMap")}
|
| 1499 |
+
case *ast.ChanType:
|
| 1500 |
+
return &Type{Size: p.PtrSize, Align: p.PtrSize, C: c("GoChan")}
|
| 1501 |
+
case *ast.Ident:
|
| 1502 |
+
goTypesFixup := func(r *Type) *Type {
|
| 1503 |
+
if r.Size == 0 { // int or uint
|
| 1504 |
+
rr := new(Type)
|
| 1505 |
+
*rr = *r
|
| 1506 |
+
rr.Size = p.IntSize
|
| 1507 |
+
rr.Align = p.IntSize
|
| 1508 |
+
r = rr
|
| 1509 |
+
}
|
| 1510 |
+
if r.Align > p.PtrSize {
|
| 1511 |
+
r.Align = p.PtrSize
|
| 1512 |
+
}
|
| 1513 |
+
return r
|
| 1514 |
+
}
|
| 1515 |
+
// Look up the type in the top level declarations.
|
| 1516 |
+
// TODO: Handle types defined within a function.
|
| 1517 |
+
for _, d := range p.Decl {
|
| 1518 |
+
gd, ok := d.(*ast.GenDecl)
|
| 1519 |
+
if !ok || gd.Tok != token.TYPE {
|
| 1520 |
+
continue
|
| 1521 |
+
}
|
| 1522 |
+
for _, spec := range gd.Specs {
|
| 1523 |
+
ts, ok := spec.(*ast.TypeSpec)
|
| 1524 |
+
if !ok {
|
| 1525 |
+
continue
|
| 1526 |
+
}
|
| 1527 |
+
if ts.Name.Name == t.Name {
|
| 1528 |
+
// Give a better error than the one
|
| 1529 |
+
// above if we detect a recursive type.
|
| 1530 |
+
if m[ts.Type] {
|
| 1531 |
+
fatalf("%s: invalid recursive type: %s refers to itself", fset.Position(e.Pos()), t.Name)
|
| 1532 |
+
}
|
| 1533 |
+
return p.doCgoType(ts.Type, m)
|
| 1534 |
+
}
|
| 1535 |
+
}
|
| 1536 |
+
}
|
| 1537 |
+
if def := typedef[t.Name]; def != nil {
|
| 1538 |
+
if defgo, ok := def.Go.(*ast.Ident); ok {
|
| 1539 |
+
switch defgo.Name {
|
| 1540 |
+
case "complex64", "complex128":
|
| 1541 |
+
// MSVC does not support the _Complex keyword
|
| 1542 |
+
// nor the complex macro.
|
| 1543 |
+
// Use GoComplex64 and GoComplex128 instead,
|
| 1544 |
+
// which are typedef-ed to a compatible type.
|
| 1545 |
+
// See go.dev/issues/36233.
|
| 1546 |
+
return goTypesFixup(goTypes[defgo.Name])
|
| 1547 |
+
}
|
| 1548 |
+
}
|
| 1549 |
+
return def
|
| 1550 |
+
}
|
| 1551 |
+
if t.Name == "uintptr" {
|
| 1552 |
+
return &Type{Size: p.PtrSize, Align: p.PtrSize, C: c("GoUintptr")}
|
| 1553 |
+
}
|
| 1554 |
+
if t.Name == "string" {
|
| 1555 |
+
// The string data is 1 pointer + 1 (pointer-sized) int.
|
| 1556 |
+
return &Type{Size: 2 * p.PtrSize, Align: p.PtrSize, C: c("GoString")}
|
| 1557 |
+
}
|
| 1558 |
+
if t.Name == "error" {
|
| 1559 |
+
return &Type{Size: 2 * p.PtrSize, Align: p.PtrSize, C: c("GoInterface")}
|
| 1560 |
+
}
|
| 1561 |
+
if t.Name == "any" {
|
| 1562 |
+
return &Type{Size: 2 * p.PtrSize, Align: p.PtrSize, C: c("GoInterface")}
|
| 1563 |
+
}
|
| 1564 |
+
if r, ok := goTypes[t.Name]; ok {
|
| 1565 |
+
return goTypesFixup(r)
|
| 1566 |
+
}
|
| 1567 |
+
error_(e.Pos(), "unrecognized Go type %s", t.Name)
|
| 1568 |
+
return &Type{Size: 4, Align: 4, C: c("int")}
|
| 1569 |
+
case *ast.SelectorExpr:
|
| 1570 |
+
id, ok := t.X.(*ast.Ident)
|
| 1571 |
+
if ok && id.Name == "unsafe" && t.Sel.Name == "Pointer" {
|
| 1572 |
+
return &Type{Size: p.PtrSize, Align: p.PtrSize, C: c("void*")}
|
| 1573 |
+
}
|
| 1574 |
+
}
|
| 1575 |
+
error_(e.Pos(), "Go type not supported in export: %s", gofmt(e))
|
| 1576 |
+
return &Type{Size: 4, Align: 4, C: c("int")}
|
| 1577 |
+
}
|
| 1578 |
+
|
| 1579 |
+
const gccProlog = `
|
| 1580 |
+
#line 1 "cgo-gcc-prolog"
|
| 1581 |
+
/*
|
| 1582 |
+
If x and y are not equal, the type will be invalid
|
| 1583 |
+
(have a negative array count) and an inscrutable error will come
|
| 1584 |
+
out of the compiler and hopefully mention "name".
|
| 1585 |
+
*/
|
| 1586 |
+
#define __cgo_compile_assert_eq(x, y, name) typedef char name[(x-y)*(x-y)*-2UL+1UL];
|
| 1587 |
+
|
| 1588 |
+
/* Check at compile time that the sizes we use match our expectations. */
|
| 1589 |
+
#define __cgo_size_assert(t, n) __cgo_compile_assert_eq(sizeof(t), (size_t)n, _cgo_sizeof_##t##_is_not_##n)
|
| 1590 |
+
|
| 1591 |
+
__cgo_size_assert(char, 1)
|
| 1592 |
+
__cgo_size_assert(short, 2)
|
| 1593 |
+
__cgo_size_assert(int, 4)
|
| 1594 |
+
typedef long long __cgo_long_long;
|
| 1595 |
+
__cgo_size_assert(__cgo_long_long, 8)
|
| 1596 |
+
__cgo_size_assert(float, 4)
|
| 1597 |
+
__cgo_size_assert(double, 8)
|
| 1598 |
+
|
| 1599 |
+
extern char* _cgo_topofstack(void);
|
| 1600 |
+
|
| 1601 |
+
/*
|
| 1602 |
+
We use packed structs, but they are always aligned.
|
| 1603 |
+
The pragmas and address-of-packed-member are only recognized as warning
|
| 1604 |
+
groups in clang 4.0+, so ignore unknown pragmas first.
|
| 1605 |
+
*/
|
| 1606 |
+
#pragma GCC diagnostic ignored "-Wunknown-pragmas"
|
| 1607 |
+
#pragma GCC diagnostic ignored "-Wpragmas"
|
| 1608 |
+
#pragma GCC diagnostic ignored "-Waddress-of-packed-member"
|
| 1609 |
+
#pragma GCC diagnostic ignored "-Wunknown-warning-option"
|
| 1610 |
+
#pragma GCC diagnostic ignored "-Wunaligned-access"
|
| 1611 |
+
|
| 1612 |
+
#include <errno.h>
|
| 1613 |
+
#include <string.h>
|
| 1614 |
+
`
|
| 1615 |
+
|
| 1616 |
+
// Prologue defining TSAN functions in C.
|
| 1617 |
+
const noTsanProlog = `
|
| 1618 |
+
#define CGO_NO_SANITIZE_THREAD
|
| 1619 |
+
#define _cgo_tsan_acquire()
|
| 1620 |
+
#define _cgo_tsan_release()
|
| 1621 |
+
`
|
| 1622 |
+
|
| 1623 |
+
// This must match the TSAN code in runtime/cgo/libcgo.h.
|
| 1624 |
+
// This is used when the code is built with the C/C++ Thread SANitizer,
|
| 1625 |
+
// which is not the same as the Go race detector.
|
| 1626 |
+
// __tsan_acquire tells TSAN that we are acquiring a lock on a variable,
|
| 1627 |
+
// in this case _cgo_sync. __tsan_release releases the lock.
|
| 1628 |
+
// (There is no actual lock, we are just telling TSAN that there is.)
|
| 1629 |
+
//
|
| 1630 |
+
// When we call from Go to C we call _cgo_tsan_acquire.
|
| 1631 |
+
// When the C function returns we call _cgo_tsan_release.
|
| 1632 |
+
// Similarly, when C calls back into Go we call _cgo_tsan_release
|
| 1633 |
+
// and then call _cgo_tsan_acquire when we return to C.
|
| 1634 |
+
// These calls tell TSAN that there is a serialization point at the C call.
|
| 1635 |
+
//
|
| 1636 |
+
// This is necessary because TSAN, which is a C/C++ tool, can not see
|
| 1637 |
+
// the synchronization in the Go code. Without these calls, when
|
| 1638 |
+
// multiple goroutines call into C code, TSAN does not understand
|
| 1639 |
+
// that the calls are properly synchronized on the Go side.
|
| 1640 |
+
//
|
| 1641 |
+
// To be clear, if the calls are not properly synchronized on the Go side,
|
| 1642 |
+
// we will be hiding races. But when using TSAN on mixed Go C/C++ code
|
| 1643 |
+
// it is more important to avoid false positives, which reduce confidence
|
| 1644 |
+
// in the tool, than to avoid false negatives.
|
| 1645 |
+
const yesTsanProlog = `
|
| 1646 |
+
#line 1 "cgo-tsan-prolog"
|
| 1647 |
+
#define CGO_NO_SANITIZE_THREAD __attribute__ ((no_sanitize_thread))
|
| 1648 |
+
|
| 1649 |
+
long long _cgo_sync __attribute__ ((common));
|
| 1650 |
+
|
| 1651 |
+
extern void __tsan_acquire(void*);
|
| 1652 |
+
extern void __tsan_release(void*);
|
| 1653 |
+
|
| 1654 |
+
__attribute__ ((unused))
|
| 1655 |
+
static void _cgo_tsan_acquire() {
|
| 1656 |
+
__tsan_acquire(&_cgo_sync);
|
| 1657 |
+
}
|
| 1658 |
+
|
| 1659 |
+
__attribute__ ((unused))
|
| 1660 |
+
static void _cgo_tsan_release() {
|
| 1661 |
+
__tsan_release(&_cgo_sync);
|
| 1662 |
+
}
|
| 1663 |
+
`
|
| 1664 |
+
|
| 1665 |
+
// Set to yesTsanProlog if we see -fsanitize=thread in the flags for gcc.
|
| 1666 |
+
var tsanProlog = noTsanProlog
|
| 1667 |
+
|
| 1668 |
+
// noMsanProlog is a prologue defining an MSAN function in C.
|
| 1669 |
+
// This is used when not compiling with -fsanitize=memory.
|
| 1670 |
+
const noMsanProlog = `
|
| 1671 |
+
#define _cgo_msan_write(addr, sz)
|
| 1672 |
+
`
|
| 1673 |
+
|
| 1674 |
+
// yesMsanProlog is a prologue defining an MSAN function in C.
|
| 1675 |
+
// This is used when compiling with -fsanitize=memory.
|
| 1676 |
+
// See the comment above where _cgo_msan_write is called.
|
| 1677 |
+
const yesMsanProlog = `
|
| 1678 |
+
extern void __msan_unpoison(const volatile void *, size_t);
|
| 1679 |
+
|
| 1680 |
+
#define _cgo_msan_write(addr, sz) __msan_unpoison((addr), (sz))
|
| 1681 |
+
`
|
| 1682 |
+
|
| 1683 |
+
// msanProlog is set to yesMsanProlog if we see -fsanitize=memory in the flags
|
| 1684 |
+
// for the C compiler.
|
| 1685 |
+
var msanProlog = noMsanProlog
|
| 1686 |
+
|
| 1687 |
+
const builtinProlog = `
|
| 1688 |
+
#line 1 "cgo-builtin-prolog"
|
| 1689 |
+
#include <stddef.h>
|
| 1690 |
+
|
| 1691 |
+
/* Define intgo when compiling with GCC. */
|
| 1692 |
+
typedef ptrdiff_t intgo;
|
| 1693 |
+
|
| 1694 |
+
#define GO_CGO_GOSTRING_TYPEDEF
|
| 1695 |
+
typedef struct { const char *p; intgo n; } _GoString_;
|
| 1696 |
+
typedef struct { char *p; intgo n; intgo c; } _GoBytes_;
|
| 1697 |
+
_GoString_ GoString(char *p);
|
| 1698 |
+
_GoString_ GoStringN(char *p, int l);
|
| 1699 |
+
_GoBytes_ GoBytes(void *p, int n);
|
| 1700 |
+
char *CString(_GoString_);
|
| 1701 |
+
void *CBytes(_GoBytes_);
|
| 1702 |
+
void *_CMalloc(size_t);
|
| 1703 |
+
|
| 1704 |
+
__attribute__ ((unused))
|
| 1705 |
+
static size_t _GoStringLen(_GoString_ s) { return (size_t)s.n; }
|
| 1706 |
+
|
| 1707 |
+
__attribute__ ((unused))
|
| 1708 |
+
static const char *_GoStringPtr(_GoString_ s) { return s.p; }
|
| 1709 |
+
`
|
| 1710 |
+
|
| 1711 |
+
const goProlog = `
|
| 1712 |
+
//go:linkname _cgo_runtime_cgocall runtime.cgocall
|
| 1713 |
+
func _cgo_runtime_cgocall(unsafe.Pointer, uintptr) int32
|
| 1714 |
+
|
| 1715 |
+
//go:linkname _cgoCheckPointer runtime.cgoCheckPointer
|
| 1716 |
+
//go:noescape
|
| 1717 |
+
func _cgoCheckPointer(interface{}, interface{})
|
| 1718 |
+
|
| 1719 |
+
//go:linkname _cgoCheckResult runtime.cgoCheckResult
|
| 1720 |
+
//go:noescape
|
| 1721 |
+
func _cgoCheckResult(interface{})
|
| 1722 |
+
`
|
| 1723 |
+
|
| 1724 |
+
const gccgoGoProlog = `
|
| 1725 |
+
func _cgoCheckPointer(interface{}, interface{})
|
| 1726 |
+
|
| 1727 |
+
func _cgoCheckResult(interface{})
|
| 1728 |
+
`
|
| 1729 |
+
|
| 1730 |
+
const goStringDef = `
|
| 1731 |
+
//go:linkname _cgo_runtime_gostring runtime.gostring
|
| 1732 |
+
func _cgo_runtime_gostring(*_Ctype_char) string
|
| 1733 |
+
|
| 1734 |
+
// GoString converts the C string p into a Go string.
|
| 1735 |
+
func _Cfunc_GoString(p *_Ctype_char) string {
|
| 1736 |
+
return _cgo_runtime_gostring(p)
|
| 1737 |
+
}
|
| 1738 |
+
`
|
| 1739 |
+
|
| 1740 |
+
const goStringNDef = `
|
| 1741 |
+
//go:linkname _cgo_runtime_gostringn runtime.gostringn
|
| 1742 |
+
func _cgo_runtime_gostringn(*_Ctype_char, int) string
|
| 1743 |
+
|
| 1744 |
+
// GoStringN converts the C data p with explicit length l to a Go string.
|
| 1745 |
+
func _Cfunc_GoStringN(p *_Ctype_char, l _Ctype_int) string {
|
| 1746 |
+
return _cgo_runtime_gostringn(p, int(l))
|
| 1747 |
+
}
|
| 1748 |
+
`
|
| 1749 |
+
|
| 1750 |
+
const goBytesDef = `
|
| 1751 |
+
//go:linkname _cgo_runtime_gobytes runtime.gobytes
|
| 1752 |
+
func _cgo_runtime_gobytes(unsafe.Pointer, int) []byte
|
| 1753 |
+
|
| 1754 |
+
// GoBytes converts the C data p with explicit length l to a Go []byte.
|
| 1755 |
+
func _Cfunc_GoBytes(p unsafe.Pointer, l _Ctype_int) []byte {
|
| 1756 |
+
return _cgo_runtime_gobytes(p, int(l))
|
| 1757 |
+
}
|
| 1758 |
+
`
|
| 1759 |
+
|
| 1760 |
+
const cStringDef = `
|
| 1761 |
+
// CString converts the Go string s to a C string.
|
| 1762 |
+
//
|
| 1763 |
+
// The C string is allocated in the C heap using malloc.
|
| 1764 |
+
// It is the caller's responsibility to arrange for it to be
|
| 1765 |
+
// freed, such as by calling C.free (be sure to include stdlib.h
|
| 1766 |
+
// if C.free is needed).
|
| 1767 |
+
func _Cfunc_CString(s string) *_Ctype_char {
|
| 1768 |
+
if len(s)+1 <= 0 {
|
| 1769 |
+
panic("string too large")
|
| 1770 |
+
}
|
| 1771 |
+
p := _cgo_cmalloc(uint64(len(s)+1))
|
| 1772 |
+
sliceHeader := struct {
|
| 1773 |
+
p unsafe.Pointer
|
| 1774 |
+
len int
|
| 1775 |
+
cap int
|
| 1776 |
+
}{p, len(s)+1, len(s)+1}
|
| 1777 |
+
b := *(*[]byte)(unsafe.Pointer(&sliceHeader))
|
| 1778 |
+
copy(b, s)
|
| 1779 |
+
b[len(s)] = 0
|
| 1780 |
+
return (*_Ctype_char)(p)
|
| 1781 |
+
}
|
| 1782 |
+
`
|
| 1783 |
+
|
| 1784 |
+
const cBytesDef = `
|
| 1785 |
+
// CBytes converts the Go []byte slice b to a C array.
|
| 1786 |
+
//
|
| 1787 |
+
// The C array is allocated in the C heap using malloc.
|
| 1788 |
+
// It is the caller's responsibility to arrange for it to be
|
| 1789 |
+
// freed, such as by calling C.free (be sure to include stdlib.h
|
| 1790 |
+
// if C.free is needed).
|
| 1791 |
+
func _Cfunc_CBytes(b []byte) unsafe.Pointer {
|
| 1792 |
+
p := _cgo_cmalloc(uint64(len(b)))
|
| 1793 |
+
sliceHeader := struct {
|
| 1794 |
+
p unsafe.Pointer
|
| 1795 |
+
len int
|
| 1796 |
+
cap int
|
| 1797 |
+
}{p, len(b), len(b)}
|
| 1798 |
+
s := *(*[]byte)(unsafe.Pointer(&sliceHeader))
|
| 1799 |
+
copy(s, b)
|
| 1800 |
+
return p
|
| 1801 |
+
}
|
| 1802 |
+
`
|
| 1803 |
+
|
| 1804 |
+
const cMallocDef = `
|
| 1805 |
+
func _Cfunc__CMalloc(n _Ctype_size_t) unsafe.Pointer {
|
| 1806 |
+
return _cgo_cmalloc(uint64(n))
|
| 1807 |
+
}
|
| 1808 |
+
`
|
| 1809 |
+
|
| 1810 |
+
var builtinDefs = map[string]string{
|
| 1811 |
+
"GoString": goStringDef,
|
| 1812 |
+
"GoStringN": goStringNDef,
|
| 1813 |
+
"GoBytes": goBytesDef,
|
| 1814 |
+
"CString": cStringDef,
|
| 1815 |
+
"CBytes": cBytesDef,
|
| 1816 |
+
"_CMalloc": cMallocDef,
|
| 1817 |
+
}
|
| 1818 |
+
|
| 1819 |
+
// Definitions for C.malloc in Go and in C. We define it ourselves
|
| 1820 |
+
// since we call it from functions we define, such as C.CString.
|
| 1821 |
+
// Also, we have historically ensured that C.malloc does not return
|
| 1822 |
+
// nil even for an allocation of 0.
|
| 1823 |
+
|
| 1824 |
+
const cMallocDefGo = `
|
| 1825 |
+
//go:cgo_import_static _cgoPREFIX_Cfunc__Cmalloc
|
| 1826 |
+
//go:linkname __cgofn__cgoPREFIX_Cfunc__Cmalloc _cgoPREFIX_Cfunc__Cmalloc
|
| 1827 |
+
var __cgofn__cgoPREFIX_Cfunc__Cmalloc byte
|
| 1828 |
+
var _cgoPREFIX_Cfunc__Cmalloc = unsafe.Pointer(&__cgofn__cgoPREFIX_Cfunc__Cmalloc)
|
| 1829 |
+
|
| 1830 |
+
//go:linkname runtime_throw runtime.throw
|
| 1831 |
+
func runtime_throw(string)
|
| 1832 |
+
|
| 1833 |
+
//go:cgo_unsafe_args
|
| 1834 |
+
func _cgo_cmalloc(p0 uint64) (r1 unsafe.Pointer) {
|
| 1835 |
+
_cgo_runtime_cgocall(_cgoPREFIX_Cfunc__Cmalloc, uintptr(unsafe.Pointer(&p0)))
|
| 1836 |
+
if r1 == nil {
|
| 1837 |
+
runtime_throw("runtime: C malloc failed")
|
| 1838 |
+
}
|
| 1839 |
+
return
|
| 1840 |
+
}
|
| 1841 |
+
`
|
| 1842 |
+
|
| 1843 |
+
// cMallocDefC defines the C version of C.malloc for the gc compiler.
|
| 1844 |
+
// It is defined here because C.CString and friends need a definition.
|
| 1845 |
+
// We define it by hand, rather than simply inventing a reference to
|
| 1846 |
+
// C.malloc, because <stdlib.h> may not have been included.
|
| 1847 |
+
// This is approximately what writeOutputFunc would generate, but
|
| 1848 |
+
// skips the cgo_topofstack code (which is only needed if the C code
|
| 1849 |
+
// calls back into Go). This also avoids returning nil for an
|
| 1850 |
+
// allocation of 0 bytes.
|
| 1851 |
+
const cMallocDefC = `
|
| 1852 |
+
CGO_NO_SANITIZE_THREAD
|
| 1853 |
+
void _cgoPREFIX_Cfunc__Cmalloc(void *v) {
|
| 1854 |
+
struct {
|
| 1855 |
+
unsigned long long p0;
|
| 1856 |
+
void *r1;
|
| 1857 |
+
} PACKED *a = v;
|
| 1858 |
+
void *ret;
|
| 1859 |
+
_cgo_tsan_acquire();
|
| 1860 |
+
ret = malloc(a->p0);
|
| 1861 |
+
if (ret == NULL && a->p0 == 0) {
|
| 1862 |
+
ret = malloc(1);
|
| 1863 |
+
}
|
| 1864 |
+
a->r1 = ret;
|
| 1865 |
+
_cgo_tsan_release();
|
| 1866 |
+
}
|
| 1867 |
+
`
|
| 1868 |
+
|
| 1869 |
+
func (p *Package) cPrologGccgo() string {
|
| 1870 |
+
r := strings.NewReplacer(
|
| 1871 |
+
"PREFIX", cPrefix,
|
| 1872 |
+
"GCCGOSYMBOLPREF", p.gccgoSymbolPrefix(),
|
| 1873 |
+
"_cgoCheckPointer", gccgoToSymbol("_cgoCheckPointer"),
|
| 1874 |
+
"_cgoCheckResult", gccgoToSymbol("_cgoCheckResult"))
|
| 1875 |
+
return r.Replace(cPrologGccgo)
|
| 1876 |
+
}
|
| 1877 |
+
|
| 1878 |
+
const cPrologGccgo = `
|
| 1879 |
+
#line 1 "cgo-c-prolog-gccgo"
|
| 1880 |
+
#include <stdint.h>
|
| 1881 |
+
#include <stdlib.h>
|
| 1882 |
+
#include <string.h>
|
| 1883 |
+
|
| 1884 |
+
typedef unsigned char byte;
|
| 1885 |
+
typedef intptr_t intgo;
|
| 1886 |
+
|
| 1887 |
+
struct __go_string {
|
| 1888 |
+
const unsigned char *__data;
|
| 1889 |
+
intgo __length;
|
| 1890 |
+
};
|
| 1891 |
+
|
| 1892 |
+
typedef struct __go_open_array {
|
| 1893 |
+
void* __values;
|
| 1894 |
+
intgo __count;
|
| 1895 |
+
intgo __capacity;
|
| 1896 |
+
} Slice;
|
| 1897 |
+
|
| 1898 |
+
struct __go_string __go_byte_array_to_string(const void* p, intgo len);
|
| 1899 |
+
struct __go_open_array __go_string_to_byte_array (struct __go_string str);
|
| 1900 |
+
|
| 1901 |
+
extern void runtime_throw(const char *);
|
| 1902 |
+
|
| 1903 |
+
const char *_cgoPREFIX_Cfunc_CString(struct __go_string s) {
|
| 1904 |
+
char *p = malloc(s.__length+1);
|
| 1905 |
+
if(p == NULL)
|
| 1906 |
+
runtime_throw("runtime: C malloc failed");
|
| 1907 |
+
memmove(p, s.__data, s.__length);
|
| 1908 |
+
p[s.__length] = 0;
|
| 1909 |
+
return p;
|
| 1910 |
+
}
|
| 1911 |
+
|
| 1912 |
+
void *_cgoPREFIX_Cfunc_CBytes(struct __go_open_array b) {
|
| 1913 |
+
char *p = malloc(b.__count);
|
| 1914 |
+
if(p == NULL)
|
| 1915 |
+
runtime_throw("runtime: C malloc failed");
|
| 1916 |
+
memmove(p, b.__values, b.__count);
|
| 1917 |
+
return p;
|
| 1918 |
+
}
|
| 1919 |
+
|
| 1920 |
+
struct __go_string _cgoPREFIX_Cfunc_GoString(char *p) {
|
| 1921 |
+
intgo len = (p != NULL) ? strlen(p) : 0;
|
| 1922 |
+
return __go_byte_array_to_string(p, len);
|
| 1923 |
+
}
|
| 1924 |
+
|
| 1925 |
+
struct __go_string _cgoPREFIX_Cfunc_GoStringN(char *p, int32_t n) {
|
| 1926 |
+
return __go_byte_array_to_string(p, n);
|
| 1927 |
+
}
|
| 1928 |
+
|
| 1929 |
+
Slice _cgoPREFIX_Cfunc_GoBytes(char *p, int32_t n) {
|
| 1930 |
+
struct __go_string s = { (const unsigned char *)p, n };
|
| 1931 |
+
return __go_string_to_byte_array(s);
|
| 1932 |
+
}
|
| 1933 |
+
|
| 1934 |
+
void *_cgoPREFIX_Cfunc__CMalloc(size_t n) {
|
| 1935 |
+
void *p = malloc(n);
|
| 1936 |
+
if(p == NULL && n == 0)
|
| 1937 |
+
p = malloc(1);
|
| 1938 |
+
if(p == NULL)
|
| 1939 |
+
runtime_throw("runtime: C malloc failed");
|
| 1940 |
+
return p;
|
| 1941 |
+
}
|
| 1942 |
+
|
| 1943 |
+
struct __go_type_descriptor;
|
| 1944 |
+
typedef struct __go_empty_interface {
|
| 1945 |
+
const struct __go_type_descriptor *__type_descriptor;
|
| 1946 |
+
void *__object;
|
| 1947 |
+
} Eface;
|
| 1948 |
+
|
| 1949 |
+
extern void runtimeCgoCheckPointer(Eface, Eface)
|
| 1950 |
+
__asm__("runtime.cgoCheckPointer")
|
| 1951 |
+
__attribute__((weak));
|
| 1952 |
+
|
| 1953 |
+
extern void localCgoCheckPointer(Eface, Eface)
|
| 1954 |
+
__asm__("GCCGOSYMBOLPREF._cgoCheckPointer");
|
| 1955 |
+
|
| 1956 |
+
void localCgoCheckPointer(Eface ptr, Eface arg) {
|
| 1957 |
+
if(runtimeCgoCheckPointer) {
|
| 1958 |
+
runtimeCgoCheckPointer(ptr, arg);
|
| 1959 |
+
}
|
| 1960 |
+
}
|
| 1961 |
+
|
| 1962 |
+
extern void runtimeCgoCheckResult(Eface)
|
| 1963 |
+
__asm__("runtime.cgoCheckResult")
|
| 1964 |
+
__attribute__((weak));
|
| 1965 |
+
|
| 1966 |
+
extern void localCgoCheckResult(Eface)
|
| 1967 |
+
__asm__("GCCGOSYMBOLPREF._cgoCheckResult");
|
| 1968 |
+
|
| 1969 |
+
void localCgoCheckResult(Eface val) {
|
| 1970 |
+
if(runtimeCgoCheckResult) {
|
| 1971 |
+
runtimeCgoCheckResult(val);
|
| 1972 |
+
}
|
| 1973 |
+
}
|
| 1974 |
+
`
|
| 1975 |
+
|
| 1976 |
+
// builtinExportProlog is a shorter version of builtinProlog,
|
| 1977 |
+
// to be put into the _cgo_export.h file.
|
| 1978 |
+
// For historical reasons we can't use builtinProlog in _cgo_export.h,
|
| 1979 |
+
// because _cgo_export.h defines GoString as a struct while builtinProlog
|
| 1980 |
+
// defines it as a function. We don't change this to avoid unnecessarily
|
| 1981 |
+
// breaking existing code.
|
| 1982 |
+
// The test of GO_CGO_GOSTRING_TYPEDEF avoids a duplicate definition
|
| 1983 |
+
// error if a Go file with a cgo comment #include's the export header
|
| 1984 |
+
// generated by a different package.
|
| 1985 |
+
const builtinExportProlog = `
|
| 1986 |
+
#line 1 "cgo-builtin-export-prolog"
|
| 1987 |
+
|
| 1988 |
+
#include <stddef.h>
|
| 1989 |
+
|
| 1990 |
+
#ifndef GO_CGO_EXPORT_PROLOGUE_H
|
| 1991 |
+
#define GO_CGO_EXPORT_PROLOGUE_H
|
| 1992 |
+
|
| 1993 |
+
#ifndef GO_CGO_GOSTRING_TYPEDEF
|
| 1994 |
+
typedef struct { const char *p; ptrdiff_t n; } _GoString_;
|
| 1995 |
+
extern size_t _GoStringLen(_GoString_ s);
|
| 1996 |
+
extern const char *_GoStringPtr(_GoString_ s);
|
| 1997 |
+
#endif
|
| 1998 |
+
|
| 1999 |
+
#endif
|
| 2000 |
+
`
|
| 2001 |
+
|
| 2002 |
+
func (p *Package) gccExportHeaderProlog() string {
|
| 2003 |
+
return strings.ReplaceAll(gccExportHeaderProlog, "GOINTBITS", fmt.Sprint(8*p.IntSize))
|
| 2004 |
+
}
|
| 2005 |
+
|
| 2006 |
+
// gccExportHeaderProlog is written to the exported header, after the
|
| 2007 |
+
// import "C" comment preamble but before the generated declarations
|
| 2008 |
+
// of exported functions. This permits the generated declarations to
|
| 2009 |
+
// use the type names that appear in goTypes, above.
|
| 2010 |
+
//
|
| 2011 |
+
// The test of GO_CGO_GOSTRING_TYPEDEF avoids a duplicate definition
|
| 2012 |
+
// error if a Go file with a cgo comment #include's the export header
|
| 2013 |
+
// generated by a different package. Unfortunately GoString means two
|
| 2014 |
+
// different things: in this prolog it means a C name for the Go type,
|
| 2015 |
+
// while in the prolog written into the start of the C code generated
|
| 2016 |
+
// from a cgo-using Go file it means the C.GoString function. There is
|
| 2017 |
+
// no way to resolve this conflict, but it also doesn't make much
|
| 2018 |
+
// difference, as Go code never wants to refer to the latter meaning.
|
| 2019 |
+
const gccExportHeaderProlog = `
|
| 2020 |
+
/* Start of boilerplate cgo prologue. */
|
| 2021 |
+
#line 1 "cgo-gcc-export-header-prolog"
|
| 2022 |
+
|
| 2023 |
+
#ifndef GO_CGO_PROLOGUE_H
|
| 2024 |
+
#define GO_CGO_PROLOGUE_H
|
| 2025 |
+
|
| 2026 |
+
typedef signed char GoInt8;
|
| 2027 |
+
typedef unsigned char GoUint8;
|
| 2028 |
+
typedef short GoInt16;
|
| 2029 |
+
typedef unsigned short GoUint16;
|
| 2030 |
+
typedef int GoInt32;
|
| 2031 |
+
typedef unsigned int GoUint32;
|
| 2032 |
+
typedef long long GoInt64;
|
| 2033 |
+
typedef unsigned long long GoUint64;
|
| 2034 |
+
typedef GoIntGOINTBITS GoInt;
|
| 2035 |
+
typedef GoUintGOINTBITS GoUint;
|
| 2036 |
+
typedef size_t GoUintptr;
|
| 2037 |
+
typedef float GoFloat32;
|
| 2038 |
+
typedef double GoFloat64;
|
| 2039 |
+
#ifdef _MSC_VER
|
| 2040 |
+
#if !defined(__cplusplus) || _MSVC_LANG <= 201402L
|
| 2041 |
+
#include <complex.h>
|
| 2042 |
+
typedef _Fcomplex GoComplex64;
|
| 2043 |
+
typedef _Dcomplex GoComplex128;
|
| 2044 |
+
#else
|
| 2045 |
+
#include <complex>
|
| 2046 |
+
typedef std::complex<float> GoComplex64;
|
| 2047 |
+
typedef std::complex<double> GoComplex128;
|
| 2048 |
+
#endif
|
| 2049 |
+
#else
|
| 2050 |
+
typedef float _Complex GoComplex64;
|
| 2051 |
+
typedef double _Complex GoComplex128;
|
| 2052 |
+
#endif
|
| 2053 |
+
|
| 2054 |
+
/*
|
| 2055 |
+
static assertion to make sure the file is being used on architecture
|
| 2056 |
+
at least with matching size of GoInt.
|
| 2057 |
+
*/
|
| 2058 |
+
typedef char _check_for_GOINTBITS_bit_pointer_matching_GoInt[sizeof(void*)==GOINTBITS/8 ? 1:-1];
|
| 2059 |
+
|
| 2060 |
+
#ifndef GO_CGO_GOSTRING_TYPEDEF
|
| 2061 |
+
typedef _GoString_ GoString;
|
| 2062 |
+
#endif
|
| 2063 |
+
typedef void *GoMap;
|
| 2064 |
+
typedef void *GoChan;
|
| 2065 |
+
typedef struct { void *t; void *v; } GoInterface;
|
| 2066 |
+
typedef struct { void *data; GoInt len; GoInt cap; } GoSlice;
|
| 2067 |
+
|
| 2068 |
+
#endif
|
| 2069 |
+
|
| 2070 |
+
/* End of boilerplate cgo prologue. */
|
| 2071 |
+
|
| 2072 |
+
#ifdef __cplusplus
|
| 2073 |
+
extern "C" {
|
| 2074 |
+
#endif
|
| 2075 |
+
`
|
| 2076 |
+
|
| 2077 |
+
// gccExportHeaderEpilog goes at the end of the generated header file.
|
| 2078 |
+
const gccExportHeaderEpilog = `
|
| 2079 |
+
#ifdef __cplusplus
|
| 2080 |
+
}
|
| 2081 |
+
#endif
|
| 2082 |
+
`
|
| 2083 |
+
|
| 2084 |
+
// gccgoExportFileProlog is written to the _cgo_export.c file when
|
| 2085 |
+
// using gccgo.
|
| 2086 |
+
// We use weak declarations, and test the addresses, so that this code
|
| 2087 |
+
// works with older versions of gccgo.
|
| 2088 |
+
const gccgoExportFileProlog = `
|
| 2089 |
+
#line 1 "cgo-gccgo-export-file-prolog"
|
| 2090 |
+
extern _Bool runtime_iscgo __attribute__ ((weak));
|
| 2091 |
+
|
| 2092 |
+
static void GoInit(void) __attribute__ ((constructor));
|
| 2093 |
+
static void GoInit(void) {
|
| 2094 |
+
if(&runtime_iscgo)
|
| 2095 |
+
runtime_iscgo = 1;
|
| 2096 |
+
}
|
| 2097 |
+
|
| 2098 |
+
extern size_t _cgo_wait_runtime_init_done(void) __attribute__ ((weak));
|
| 2099 |
+
`
|
go/src/cmd/cgo/util.go
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Copyright 2009 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 |
+
package main
|
| 6 |
+
|
| 7 |
+
import (
|
| 8 |
+
"bytes"
|
| 9 |
+
"fmt"
|
| 10 |
+
"go/token"
|
| 11 |
+
"os"
|
| 12 |
+
"os/exec"
|
| 13 |
+
"slices"
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
// run runs the command argv, feeding in stdin on standard input.
|
| 17 |
+
// It returns the output to standard output and standard error.
|
| 18 |
+
// ok indicates whether the command exited successfully.
|
| 19 |
+
func run(stdin []byte, argv []string) (stdout, stderr []byte, ok bool) {
|
| 20 |
+
if i := slices.Index(argv, "-xc"); i >= 0 && argv[len(argv)-1] == "-" {
|
| 21 |
+
// Some compilers have trouble with standard input.
|
| 22 |
+
// Others have trouble with -xc.
|
| 23 |
+
// Avoid both problems by writing a file with a .c extension.
|
| 24 |
+
f, err := os.CreateTemp("", "cgo-gcc-input-")
|
| 25 |
+
if err != nil {
|
| 26 |
+
fatalf("%s", err)
|
| 27 |
+
}
|
| 28 |
+
name := f.Name()
|
| 29 |
+
f.Close()
|
| 30 |
+
if err := os.WriteFile(name+".c", stdin, 0666); err != nil {
|
| 31 |
+
os.Remove(name)
|
| 32 |
+
fatalf("%s", err)
|
| 33 |
+
}
|
| 34 |
+
defer os.Remove(name)
|
| 35 |
+
defer os.Remove(name + ".c")
|
| 36 |
+
|
| 37 |
+
// Build new argument list without -xc and trailing -.
|
| 38 |
+
new := append(argv[:i:i], argv[i+1:len(argv)-1]...)
|
| 39 |
+
|
| 40 |
+
// Since we are going to write the file to a temporary directory,
|
| 41 |
+
// we will need to add -I . explicitly to the command line:
|
| 42 |
+
// any #include "foo" before would have looked in the current
|
| 43 |
+
// directory as the directory "holding" standard input, but now
|
| 44 |
+
// the temporary directory holds the input.
|
| 45 |
+
// We've also run into compilers that reject "-I." but allow "-I", ".",
|
| 46 |
+
// so be sure to use two arguments.
|
| 47 |
+
// This matters mainly for people invoking cgo -godefs by hand.
|
| 48 |
+
new = append(new, "-I", ".")
|
| 49 |
+
|
| 50 |
+
// Finish argument list with path to C file.
|
| 51 |
+
new = append(new, name+".c")
|
| 52 |
+
|
| 53 |
+
argv = new
|
| 54 |
+
stdin = nil
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
p := exec.Command(argv[0], argv[1:]...)
|
| 58 |
+
p.Stdin = bytes.NewReader(stdin)
|
| 59 |
+
var bout, berr bytes.Buffer
|
| 60 |
+
p.Stdout = &bout
|
| 61 |
+
p.Stderr = &berr
|
| 62 |
+
// Disable escape codes in clang error messages.
|
| 63 |
+
p.Env = append(os.Environ(), "TERM=dumb")
|
| 64 |
+
err := p.Run()
|
| 65 |
+
if _, ok := err.(*exec.ExitError); err != nil && !ok {
|
| 66 |
+
fatalf("exec %s: %s", argv[0], err)
|
| 67 |
+
}
|
| 68 |
+
ok = p.ProcessState.Success()
|
| 69 |
+
stdout, stderr = bout.Bytes(), berr.Bytes()
|
| 70 |
+
return
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
func lineno(pos token.Pos) string {
|
| 74 |
+
return fset.Position(pos).String()
|
| 75 |
+
}
|
| 76 |
+
|
| 77 |
+
// Die with an error message.
|
| 78 |
+
func fatalf(msg string, args ...any) {
|
| 79 |
+
// If we've already printed other errors, they might have
|
| 80 |
+
// caused the fatal condition. Assume they're enough.
|
| 81 |
+
if nerrors == 0 {
|
| 82 |
+
fmt.Fprintf(os.Stderr, "cgo: "+msg+"\n", args...)
|
| 83 |
+
}
|
| 84 |
+
os.Exit(2)
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
var nerrors int
|
| 88 |
+
|
| 89 |
+
func error_(pos token.Pos, msg string, args ...any) {
|
| 90 |
+
nerrors++
|
| 91 |
+
if pos.IsValid() {
|
| 92 |
+
fmt.Fprintf(os.Stderr, "%s: ", fset.Position(pos).String())
|
| 93 |
+
} else {
|
| 94 |
+
fmt.Fprintf(os.Stderr, "cgo: ")
|
| 95 |
+
}
|
| 96 |
+
fmt.Fprintf(os.Stderr, msg, args...)
|
| 97 |
+
fmt.Fprintf(os.Stderr, "\n")
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
func creat(name string) *os.File {
|
| 101 |
+
f, err := os.Create(name)
|
| 102 |
+
if err != nil {
|
| 103 |
+
fatalf("%s", err)
|
| 104 |
+
}
|
| 105 |
+
return f
|
| 106 |
+
}
|
go/src/cmd/cgo/zdefaultcc.go
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Code generated by go tool dist; DO NOT EDIT.
|
| 2 |
+
|
| 3 |
+
package main
|
| 4 |
+
|
| 5 |
+
const defaultPkgConfig = `pkg-config`
|
| 6 |
+
func defaultCC(goos, goarch string) string {
|
| 7 |
+
switch goos+`/`+goarch {
|
| 8 |
+
}
|
| 9 |
+
switch goos {
|
| 10 |
+
case "darwin", "ios", "freebsd", "openbsd":
|
| 11 |
+
return "clang"
|
| 12 |
+
}
|
| 13 |
+
return "gcc"
|
| 14 |
+
}
|
| 15 |
+
func defaultCXX(goos, goarch string) string {
|
| 16 |
+
switch goos+`/`+goarch {
|
| 17 |
+
}
|
| 18 |
+
switch goos {
|
| 19 |
+
case "darwin", "ios", "freebsd", "openbsd":
|
| 20 |
+
return "clang++"
|
| 21 |
+
}
|
| 22 |
+
return "g++"
|
| 23 |
+
}
|
go/src/cmd/compile/README.md
ADDED
|
@@ -0,0 +1,366 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
// Copyright 2018 The Go Authors. All rights reserved.
|
| 3 |
+
// Use of this source code is governed by a BSD-style
|
| 4 |
+
// license that can be found in the LICENSE file.
|
| 5 |
+
-->
|
| 6 |
+
|
| 7 |
+
## Introduction to the Go compiler
|
| 8 |
+
|
| 9 |
+
`cmd/compile` contains the main packages that form the Go compiler. The compiler
|
| 10 |
+
may be logically split in four phases, which we will briefly describe alongside
|
| 11 |
+
the list of packages that contain their code.
|
| 12 |
+
|
| 13 |
+
You may sometimes hear the terms "front-end" and "back-end" when referring to
|
| 14 |
+
the compiler. Roughly speaking, these translate to the first two and last two
|
| 15 |
+
phases we are going to list here. A third term, "middle-end", often refers to
|
| 16 |
+
much of the work that happens in the second phase.
|
| 17 |
+
|
| 18 |
+
Note that the `go/*` family of packages, such as `go/parser` and
|
| 19 |
+
`go/types`, are mostly unused by the compiler. Since the compiler was
|
| 20 |
+
initially written in C, the `go/*` packages were developed to enable
|
| 21 |
+
writing tools working with Go code, such as `gofmt` and `vet`.
|
| 22 |
+
However, over time the compiler's internal APIs have slowly evolved to
|
| 23 |
+
be more familiar to users of the `go/*` packages.
|
| 24 |
+
|
| 25 |
+
It should be clarified that the name "gc" stands for "Go compiler", and has
|
| 26 |
+
little to do with uppercase "GC", which stands for garbage collection.
|
| 27 |
+
|
| 28 |
+
### 1. Parsing
|
| 29 |
+
|
| 30 |
+
* `cmd/compile/internal/syntax` (lexer, parser, syntax tree)
|
| 31 |
+
|
| 32 |
+
In the first phase of compilation, source code is tokenized (lexical analysis),
|
| 33 |
+
parsed (syntax analysis), and a syntax tree is constructed for each source
|
| 34 |
+
file.
|
| 35 |
+
|
| 36 |
+
Each syntax tree is an exact representation of the respective source file, with
|
| 37 |
+
nodes corresponding to the various elements of the source such as expressions,
|
| 38 |
+
declarations, and statements. The syntax tree also includes position information
|
| 39 |
+
which is used for error reporting and the creation of debugging information.
|
| 40 |
+
|
| 41 |
+
### 2. Type checking
|
| 42 |
+
|
| 43 |
+
* `cmd/compile/internal/types2` (type checking)
|
| 44 |
+
|
| 45 |
+
The types2 package is a port of `go/types` to use the syntax package's
|
| 46 |
+
AST instead of `go/ast`.
|
| 47 |
+
|
| 48 |
+
### 3. IR construction ("noding")
|
| 49 |
+
|
| 50 |
+
* `cmd/compile/internal/types` (compiler types)
|
| 51 |
+
* `cmd/compile/internal/ir` (compiler AST)
|
| 52 |
+
* `cmd/compile/internal/noder` (create compiler AST)
|
| 53 |
+
|
| 54 |
+
The compiler middle end uses its own AST definition and representation of Go
|
| 55 |
+
types carried over from when it was written in C. All of its code is written in
|
| 56 |
+
terms of these, so the next step after type checking is to convert the syntax
|
| 57 |
+
and types2 representations to ir and types. This process is referred to as
|
| 58 |
+
"noding."
|
| 59 |
+
|
| 60 |
+
Noding uses a process called Unified IR, which builds a node representation
|
| 61 |
+
using a serialized version of the typechecked code from step 2.
|
| 62 |
+
Unified IR is also involved in import/export of packages and inlining.
|
| 63 |
+
|
| 64 |
+
### 4. Middle end
|
| 65 |
+
|
| 66 |
+
* `cmd/compile/internal/inline` (function call inlining)
|
| 67 |
+
* `cmd/compile/internal/devirtualize` (devirtualization of known interface method calls)
|
| 68 |
+
* `cmd/compile/internal/escape` (escape analysis)
|
| 69 |
+
|
| 70 |
+
Several optimization passes are performed on the IR representation:
|
| 71 |
+
dead code elimination, (early) devirtualization, function call
|
| 72 |
+
inlining, and escape analysis.
|
| 73 |
+
|
| 74 |
+
The early dead code elimination pass is integrated into the unified IR writer phase.
|
| 75 |
+
|
| 76 |
+
### 5. Walk
|
| 77 |
+
|
| 78 |
+
* `cmd/compile/internal/walk` (order of evaluation, desugaring)
|
| 79 |
+
|
| 80 |
+
The final pass over the IR representation is "walk," which serves two purposes:
|
| 81 |
+
|
| 82 |
+
1. It decomposes complex statements into individual, simpler statements,
|
| 83 |
+
introducing temporary variables and respecting order of evaluation. This step
|
| 84 |
+
is also referred to as "order."
|
| 85 |
+
|
| 86 |
+
2. It desugars higher-level Go constructs into more primitive ones. For example,
|
| 87 |
+
`switch` statements are turned into binary search or jump tables, and
|
| 88 |
+
operations on maps and channels are replaced with runtime calls.
|
| 89 |
+
|
| 90 |
+
### 6. Generic SSA
|
| 91 |
+
|
| 92 |
+
* `cmd/compile/internal/ssa` (SSA passes and rules)
|
| 93 |
+
* `cmd/compile/internal/ssagen` (converting IR to SSA)
|
| 94 |
+
|
| 95 |
+
In this phase, IR is converted into Static Single Assignment (SSA) form, a
|
| 96 |
+
lower-level intermediate representation with specific properties that make it
|
| 97 |
+
easier to implement optimizations and to eventually generate machine code from
|
| 98 |
+
it.
|
| 99 |
+
|
| 100 |
+
During this conversion, function intrinsics are applied. These are special
|
| 101 |
+
functions that the compiler has been taught to replace with heavily optimized
|
| 102 |
+
code on a case-by-case basis.
|
| 103 |
+
|
| 104 |
+
Certain nodes are also lowered into simpler components during the AST to SSA
|
| 105 |
+
conversion, so that the rest of the compiler can work with them. For instance,
|
| 106 |
+
the copy builtin is replaced by memory moves, and range loops are rewritten into
|
| 107 |
+
for loops. Some of these currently happen before the conversion to SSA due to
|
| 108 |
+
historical reasons, but the long-term plan is to move all of them here.
|
| 109 |
+
|
| 110 |
+
Then, a series of machine-independent passes and rules are applied. These do not
|
| 111 |
+
concern any single computer architecture, and thus run on all `GOARCH` variants.
|
| 112 |
+
These passes include dead code elimination, removal of
|
| 113 |
+
unneeded nil checks, and removal of unused branches. The generic rewrite rules
|
| 114 |
+
mainly concern expressions, such as replacing some expressions with constant
|
| 115 |
+
values, and optimizing multiplications and float operations.
|
| 116 |
+
|
| 117 |
+
### 7. Generating machine code
|
| 118 |
+
|
| 119 |
+
* `cmd/compile/internal/ssa` (SSA lowering and arch-specific passes)
|
| 120 |
+
* `cmd/internal/obj` (machine code generation)
|
| 121 |
+
|
| 122 |
+
The machine-dependent phase of the compiler begins with the "lower" pass, which
|
| 123 |
+
rewrites generic values into their machine-specific variants. For example, on
|
| 124 |
+
amd64 memory operands are possible, so many load-store operations may be combined.
|
| 125 |
+
|
| 126 |
+
Note that the lower pass runs all machine-specific rewrite rules, and thus it
|
| 127 |
+
currently applies lots of optimizations too.
|
| 128 |
+
|
| 129 |
+
Once the SSA has been "lowered" and is more specific to the target architecture,
|
| 130 |
+
the final code optimization passes are run. This includes yet another dead code
|
| 131 |
+
elimination pass, moving values closer to their uses, the removal of local
|
| 132 |
+
variables that are never read from, and register allocation.
|
| 133 |
+
|
| 134 |
+
Other important pieces of work done as part of this step include stack frame
|
| 135 |
+
layout, which assigns stack offsets to local variables, and pointer liveness
|
| 136 |
+
analysis, which computes which on-stack pointers are live at each GC safe point.
|
| 137 |
+
|
| 138 |
+
At the end of the SSA generation phase, Go functions have been transformed into
|
| 139 |
+
a series of obj.Prog instructions. These are passed to the assembler
|
| 140 |
+
(`cmd/internal/obj`), which turns them into machine code and writes out the
|
| 141 |
+
final object file. The object file will also contain reflect data, export data,
|
| 142 |
+
and debugging information.
|
| 143 |
+
|
| 144 |
+
### 7a. Export
|
| 145 |
+
|
| 146 |
+
In addition to writing a file of object code for the linker, the
|
| 147 |
+
compiler also writes a file of "export data" for downstream
|
| 148 |
+
compilation units. The export data file holds all the information
|
| 149 |
+
computed during compilation of package P that may be needed when
|
| 150 |
+
compiling a package Q that directly imports P. It includes type
|
| 151 |
+
information for all exported declarations, IR for bodies of functions
|
| 152 |
+
that are candidates for inlining, IR for bodies of generic functions
|
| 153 |
+
that may be instantiated in another package, and a summary of the
|
| 154 |
+
findings of escape analysis on function parameters.
|
| 155 |
+
|
| 156 |
+
The format of the export data file has gone through a number of
|
| 157 |
+
iterations. Its current form is called "unified", and it is a
|
| 158 |
+
serialized representation of an object graph, with an index allowing
|
| 159 |
+
lazy decoding of parts of the whole (since most imports are used to
|
| 160 |
+
provide only a handful of symbols).
|
| 161 |
+
|
| 162 |
+
The GOROOT repository contains a reader and a writer for the unified
|
| 163 |
+
format; it encodes from/decodes to the compiler's IR.
|
| 164 |
+
The golang.org/x/tools repository also provides a public API for an export
|
| 165 |
+
data reader (using the go/types representation) that always supports the
|
| 166 |
+
compiler's current file format and a small number of historic versions.
|
| 167 |
+
(It is used by x/tools/go/packages in modes that require type information
|
| 168 |
+
but not type-annotated syntax.)
|
| 169 |
+
|
| 170 |
+
The x/tools repository also provides public APIs for reading and
|
| 171 |
+
writing exported type information (but nothing more) using the older
|
| 172 |
+
"indexed" format. (For example, gopls uses this version for its
|
| 173 |
+
database of workspace information, which includes types.)
|
| 174 |
+
|
| 175 |
+
Export data usually provides a "deep" summary, so that compilation of
|
| 176 |
+
package Q can read the export data files only for each direct import,
|
| 177 |
+
and be assured that these provide all necessary information about
|
| 178 |
+
declarations in indirect imports, such as the methods and struct
|
| 179 |
+
fields of types referred to in P's public API. Deep export data is
|
| 180 |
+
simpler for build systems, since only one file is needed per direct
|
| 181 |
+
dependency. However, it does have a tendency to grow as one gets
|
| 182 |
+
higher up the import graph of a big repository: if there is a set of
|
| 183 |
+
very commonly used types with a large API, nearly every package's
|
| 184 |
+
export data will include a copy. This problem motivated the "indexed"
|
| 185 |
+
design, which allowed partial loading on demand.
|
| 186 |
+
(gopls does less work than the compiler for each import and is thus
|
| 187 |
+
more sensitive to export data overheads. For this reason, it uses
|
| 188 |
+
"shallow" export data, in which indirect information is not recorded
|
| 189 |
+
at all. This demands random access to the export data files of all
|
| 190 |
+
dependencies, so is not suitable for distributed build systems.)
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
### 8. Tips
|
| 194 |
+
|
| 195 |
+
#### Getting Started
|
| 196 |
+
|
| 197 |
+
* If you have never contributed to the compiler before, a simple way to begin
|
| 198 |
+
can be adding a log statement or `panic("here")` to get some
|
| 199 |
+
initial insight into whatever you are investigating.
|
| 200 |
+
|
| 201 |
+
* The compiler itself provides logging, debugging and visualization capabilities,
|
| 202 |
+
such as:
|
| 203 |
+
```
|
| 204 |
+
$ go build -gcflags=-m=2 # print optimization info, including inlining, escape analysis
|
| 205 |
+
$ go build -gcflags=-d=ssa/check_bce/debug # print bounds check info
|
| 206 |
+
$ go build -gcflags=-W # print internal parse tree after type checking
|
| 207 |
+
$ GOSSAFUNC=Foo go build # generate ssa.html file for func Foo
|
| 208 |
+
$ go build -gcflags=-S # print assembly
|
| 209 |
+
$ go tool compile -bench=out.txt x.go # print timing of compiler phases
|
| 210 |
+
```
|
| 211 |
+
|
| 212 |
+
Some flags alter the compiler behavior, such as:
|
| 213 |
+
```
|
| 214 |
+
$ go tool compile -h file.go # panic on first compile error encountered
|
| 215 |
+
$ go build -gcflags=-d=checkptr=2 # enable additional unsafe pointer checking
|
| 216 |
+
```
|
| 217 |
+
|
| 218 |
+
There are many additional flags. Some descriptions are available via:
|
| 219 |
+
```
|
| 220 |
+
$ go tool compile -h # compiler flags, e.g., go build -gcflags='-m=1 -l'
|
| 221 |
+
$ go tool compile -d help # debug flags, e.g., go build -gcflags=-d=checkptr=2
|
| 222 |
+
$ go tool compile -d ssa/help # ssa flags, e.g., go build -gcflags=-d=ssa/prove/debug=2
|
| 223 |
+
```
|
| 224 |
+
|
| 225 |
+
There are some additional details about `-gcflags` and the differences between `go build`
|
| 226 |
+
vs. `go tool compile` in a [section below](#-gcflags-and-go-build-vs-go-tool-compile).
|
| 227 |
+
|
| 228 |
+
* In general, when investigating a problem in the compiler you usually want to
|
| 229 |
+
start with the simplest possible reproduction and understand exactly what is
|
| 230 |
+
happening with it.
|
| 231 |
+
|
| 232 |
+
#### Testing your changes
|
| 233 |
+
|
| 234 |
+
* Be sure to read the [Quickly testing your changes](https://go.dev/doc/contribute#quick_test)
|
| 235 |
+
section of the Go Contribution Guide.
|
| 236 |
+
|
| 237 |
+
* Some tests live within the cmd/compile packages and can be run by `go test ./...` or similar,
|
| 238 |
+
but many cmd/compile tests are in the top-level
|
| 239 |
+
[test](https://github.com/golang/go/tree/master/test) directory:
|
| 240 |
+
|
| 241 |
+
```
|
| 242 |
+
$ go test cmd/internal/testdir # all tests in 'test' dir
|
| 243 |
+
$ go test cmd/internal/testdir -run='Test/escape.*.go' # test specific files in 'test' dir
|
| 244 |
+
```
|
| 245 |
+
For details, see the [testdir README](https://github.com/golang/go/tree/master/test#readme).
|
| 246 |
+
The `errorCheck` method in [testdir_test.go](https://github.com/golang/go/blob/master/src/cmd/internal/testdir/testdir_test.go)
|
| 247 |
+
is helpful for a description of the `ERROR` comments used in many of those tests.
|
| 248 |
+
|
| 249 |
+
In addition, the `go/types` package from the standard library and `cmd/compile/internal/types2`
|
| 250 |
+
have shared tests in `src/internal/types/testdata`, and both type checkers
|
| 251 |
+
should be checked if anything changes there.
|
| 252 |
+
|
| 253 |
+
* The new [application-based coverage profiling](https://go.dev/testing/coverage/) can be used
|
| 254 |
+
with the compiler, such as:
|
| 255 |
+
|
| 256 |
+
```
|
| 257 |
+
$ go install -cover -coverpkg=cmd/compile/... cmd/compile # build compiler with coverage instrumentation
|
| 258 |
+
$ mkdir /tmp/coverdir # pick location for coverage data
|
| 259 |
+
$ GOCOVERDIR=/tmp/coverdir go test [...] # use compiler, saving coverage data
|
| 260 |
+
$ go tool covdata textfmt -i=/tmp/coverdir -o coverage.out # convert to traditional coverage format
|
| 261 |
+
$ go tool cover -html coverage.out # view coverage via traditional tools
|
| 262 |
+
```
|
| 263 |
+
|
| 264 |
+
#### Juggling compiler versions
|
| 265 |
+
|
| 266 |
+
* Many of the compiler tests use the version of the `go` command found in your PATH and
|
| 267 |
+
its corresponding `compile` binary.
|
| 268 |
+
|
| 269 |
+
* If you are in a branch and your PATH includes `<go-repo>/bin`,
|
| 270 |
+
doing `go install cmd/compile` will build the compiler using the code from your
|
| 271 |
+
branch and install it to the proper location so that subsequent `go` commands
|
| 272 |
+
like `go build` or `go test ./...` will exercise your freshly built compiler.
|
| 273 |
+
|
| 274 |
+
* [toolstash](https://pkg.go.dev/golang.org/x/tools/cmd/toolstash) provides a way
|
| 275 |
+
to save, run, and restore a known good copy of the Go toolchain. For example, it can be
|
| 276 |
+
a good practice to initially build your branch, save that version of
|
| 277 |
+
the toolchain, then restore the known good version of the tools to compile
|
| 278 |
+
your work-in-progress version of the compiler.
|
| 279 |
+
|
| 280 |
+
Sample set up steps:
|
| 281 |
+
```
|
| 282 |
+
$ go install golang.org/x/tools/cmd/toolstash@latest
|
| 283 |
+
$ git clone https://go.googlesource.com/go
|
| 284 |
+
$ export PATH=$PWD/go/bin:$PATH
|
| 285 |
+
$ cd go/src
|
| 286 |
+
$ git checkout -b mybranch
|
| 287 |
+
$ ./all.bash # build and confirm good starting point
|
| 288 |
+
$ toolstash save # save current tools
|
| 289 |
+
```
|
| 290 |
+
After that, your edit/compile/test cycle can be similar to:
|
| 291 |
+
```
|
| 292 |
+
[... make edits to cmd/compile source ...]
|
| 293 |
+
$ toolstash restore && go install cmd/compile # restore known good tools to build compiler
|
| 294 |
+
[... 'go build', 'go test', etc. ...] # use freshly built compiler
|
| 295 |
+
```
|
| 296 |
+
|
| 297 |
+
* toolstash also allows comparing the installed vs. stashed copy of
|
| 298 |
+
the compiler, such as if you expect equivalent behavior after a refactor.
|
| 299 |
+
For example, to check that your changed compiler produces identical object files to
|
| 300 |
+
the stashed compiler while building the standard library:
|
| 301 |
+
```
|
| 302 |
+
$ toolstash restore && go install cmd/compile # build latest compiler
|
| 303 |
+
$ go build -toolexec "toolstash -cmp" -a -v std # compare latest vs. saved compiler
|
| 304 |
+
```
|
| 305 |
+
|
| 306 |
+
* If versions appear to get out of sync (for example, with errors like
|
| 307 |
+
`linked object header mismatch` with version strings like
|
| 308 |
+
`devel go1.21-db3f952b1f`), you might need to do
|
| 309 |
+
`toolstash restore && go install cmd/...` to update all the tools under cmd.
|
| 310 |
+
|
| 311 |
+
#### Additional helpful tools
|
| 312 |
+
|
| 313 |
+
* [compilebench](https://pkg.go.dev/golang.org/x/tools/cmd/compilebench) benchmarks
|
| 314 |
+
the speed of the compiler.
|
| 315 |
+
|
| 316 |
+
* [benchstat](https://pkg.go.dev/golang.org/x/perf/cmd/benchstat) is the standard tool
|
| 317 |
+
for reporting performance changes resulting from compiler modifications,
|
| 318 |
+
including whether any improvements are statistically significant:
|
| 319 |
+
```
|
| 320 |
+
$ go test -bench=SomeBenchmarks -count=20 > new.txt # use new compiler
|
| 321 |
+
$ toolstash restore # restore old compiler
|
| 322 |
+
$ go test -bench=SomeBenchmarks -count=20 > old.txt # use old compiler
|
| 323 |
+
$ benchstat old.txt new.txt # compare old vs. new
|
| 324 |
+
```
|
| 325 |
+
|
| 326 |
+
* [bent](https://pkg.go.dev/golang.org/x/benchmarks/cmd/bent) facilitates running a
|
| 327 |
+
large set of benchmarks from various community Go projects inside a Docker container.
|
| 328 |
+
|
| 329 |
+
* [perflock](https://github.com/aclements/perflock) helps obtain more consistent
|
| 330 |
+
benchmark results, including by manipulating CPU frequency scaling settings on Linux.
|
| 331 |
+
|
| 332 |
+
* [view-annotated-file](https://github.com/loov/view-annotated-file) (from the community)
|
| 333 |
+
overlays inlining, bounds check, and escape info back onto the source code.
|
| 334 |
+
|
| 335 |
+
* [godbolt.org](https://go.godbolt.org) is widely used to examine
|
| 336 |
+
and share assembly output from many compilers, including the Go compiler. It can also
|
| 337 |
+
[compare](https://go.godbolt.org/z/5Gs1G4bKG) assembly for different versions of
|
| 338 |
+
a function or across Go compiler versions, which can be helpful for investigations and
|
| 339 |
+
bug reports.
|
| 340 |
+
|
| 341 |
+
#### -gcflags and 'go build' vs. 'go tool compile'
|
| 342 |
+
|
| 343 |
+
* `-gcflags` is a go command [build flag](https://pkg.go.dev/cmd/go#hdr-Compile_packages_and_dependencies).
|
| 344 |
+
`go build -gcflags=<args>` passes the supplied `<args>` to the underlying
|
| 345 |
+
`compile` invocation(s) while still doing everything that the `go build` command
|
| 346 |
+
normally does (e.g., handling the build cache, modules, and so on). In contrast,
|
| 347 |
+
`go tool compile <args>` asks the `go` command to invoke `compile <args>` a single time
|
| 348 |
+
without involving the standard `go build` machinery. In some cases, it can be helpful to have
|
| 349 |
+
fewer moving parts by doing `go tool compile <args>`, such as if you have a
|
| 350 |
+
small standalone source file that can be compiled without any assistance from `go build`.
|
| 351 |
+
In other cases, it is more convenient to pass `-gcflags` to a build command like
|
| 352 |
+
`go build`, `go test`, or `go install`.
|
| 353 |
+
|
| 354 |
+
* `-gcflags` by default applies to the packages named on the command line, but can
|
| 355 |
+
use package patterns such as `-gcflags='all=-m=1 -l'`, or multiple package patterns such as
|
| 356 |
+
`-gcflags='all=-m=1' -gcflags='fmt=-m=2'`. For details, see the
|
| 357 |
+
[cmd/go documentation](https://pkg.go.dev/cmd/go#hdr-Compile_packages_and_dependencies).
|
| 358 |
+
|
| 359 |
+
### Further reading
|
| 360 |
+
|
| 361 |
+
To dig deeper into how the SSA package works, including its passes and rules,
|
| 362 |
+
head to [cmd/compile/internal/ssa/README.md](internal/ssa/README.md).
|
| 363 |
+
|
| 364 |
+
Finally, if something in this README or the SSA README is unclear
|
| 365 |
+
or if you have an idea for an improvement, feel free to leave a comment in
|
| 366 |
+
[issue 30074](https://go.dev/issue/30074).
|
go/src/cmd/compile/abi-internal.md
ADDED
|
@@ -0,0 +1,1016 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Go internal ABI specification
|
| 2 |
+
|
| 3 |
+
Self-link: [go.dev/s/regabi](https://go.dev/s/regabi)
|
| 4 |
+
|
| 5 |
+
This document describes Go’s internal application binary interface
|
| 6 |
+
(ABI), known as ABIInternal.
|
| 7 |
+
Go's ABI defines the layout of data in memory and the conventions for
|
| 8 |
+
calling between Go functions.
|
| 9 |
+
This ABI is *unstable* and will change between Go versions.
|
| 10 |
+
If you’re writing assembly code, please instead refer to Go’s
|
| 11 |
+
[assembly documentation](/doc/asm.html), which describes Go’s stable
|
| 12 |
+
ABI, known as ABI0.
|
| 13 |
+
|
| 14 |
+
All functions defined in Go source follow ABIInternal.
|
| 15 |
+
However, ABIInternal and ABI0 functions are able to call each other
|
| 16 |
+
through transparent *ABI wrappers*, described in the [internal calling
|
| 17 |
+
convention proposal](https://golang.org/design/27539-internal-abi).
|
| 18 |
+
|
| 19 |
+
Go uses a common ABI design across all architectures.
|
| 20 |
+
We first describe the common ABI, and then cover per-architecture
|
| 21 |
+
specifics.
|
| 22 |
+
|
| 23 |
+
*Rationale*: For the reasoning behind using a common ABI across
|
| 24 |
+
architectures instead of the platform ABI, see the [register-based Go
|
| 25 |
+
calling convention proposal](https://golang.org/design/40724-register-calling).
|
| 26 |
+
|
| 27 |
+
## Memory layout
|
| 28 |
+
|
| 29 |
+
Go's built-in types have the following sizes and alignments.
|
| 30 |
+
Many, though not all, of these sizes are guaranteed by the [language
|
| 31 |
+
specification](/doc/go_spec.html#Size_and_alignment_guarantees).
|
| 32 |
+
Those that aren't guaranteed may change in future versions of Go (for
|
| 33 |
+
example, we've considered changing the alignment of int64 on 32-bit).
|
| 34 |
+
|
| 35 |
+
| Type | 64-bit | | 32-bit | |
|
| 36 |
+
|-----------------------------|--------|-------|--------|-------|
|
| 37 |
+
| | Size | Align | Size | Align |
|
| 38 |
+
| bool, uint8, int8 | 1 | 1 | 1 | 1 |
|
| 39 |
+
| uint16, int16 | 2 | 2 | 2 | 2 |
|
| 40 |
+
| uint32, int32 | 4 | 4 | 4 | 4 |
|
| 41 |
+
| uint64, int64 | 8 | 8 | 8 | 4 |
|
| 42 |
+
| int, uint | 8 | 8 | 4 | 4 |
|
| 43 |
+
| float32 | 4 | 4 | 4 | 4 |
|
| 44 |
+
| float64 | 8 | 8 | 8 | 4 |
|
| 45 |
+
| complex64 | 8 | 4 | 8 | 4 |
|
| 46 |
+
| complex128 | 16 | 8 | 16 | 4 |
|
| 47 |
+
| uintptr, *T, unsafe.Pointer | 8 | 8 | 4 | 4 |
|
| 48 |
+
|
| 49 |
+
The types `byte` and `rune` are aliases for `uint8` and `int32`,
|
| 50 |
+
respectively, and hence have the same size and alignment as these
|
| 51 |
+
types.
|
| 52 |
+
|
| 53 |
+
The layout of `map`, `chan`, and `func` types is equivalent to *T.
|
| 54 |
+
|
| 55 |
+
To describe the layout of the remaining composite types, we first
|
| 56 |
+
define the layout of a *sequence* S of N fields with types
|
| 57 |
+
t<sub>1</sub>, t<sub>2</sub>, ..., t<sub>N</sub>.
|
| 58 |
+
We define the byte offset at which each field begins relative to a
|
| 59 |
+
base address of 0, as well as the size and alignment of the sequence
|
| 60 |
+
as follows:
|
| 61 |
+
|
| 62 |
+
```
|
| 63 |
+
offset(S, i) = 0 if i = 1
|
| 64 |
+
= align(offset(S, i-1) + sizeof(t_(i-1)), alignof(t_i))
|
| 65 |
+
alignof(S) = 1 if N = 0
|
| 66 |
+
= max(alignof(t_i) | 1 <= i <= N)
|
| 67 |
+
sizeof(S) = 0 if N = 0
|
| 68 |
+
= align(offset(S, N) + sizeof(t_N), alignof(S))
|
| 69 |
+
```
|
| 70 |
+
|
| 71 |
+
Where sizeof(T) and alignof(T) are the size and alignment of type T,
|
| 72 |
+
respectively, and align(x, y) rounds x up to a multiple of y.
|
| 73 |
+
|
| 74 |
+
The `interface{}` type is a sequence of 1. a pointer to the runtime type
|
| 75 |
+
description for the interface's dynamic type and 2. an `unsafe.Pointer`
|
| 76 |
+
data field.
|
| 77 |
+
Any other interface type (besides the empty interface) is a sequence
|
| 78 |
+
of 1. a pointer to the runtime "itab" that gives the method pointers and
|
| 79 |
+
the type of the data field and 2. an `unsafe.Pointer` data field.
|
| 80 |
+
An interface can be "direct" or "indirect" depending on the dynamic
|
| 81 |
+
type: a direct interface stores the value directly in the data field,
|
| 82 |
+
and an indirect interface stores a pointer to the value in the data
|
| 83 |
+
field.
|
| 84 |
+
An interface can only be direct if the value consists of a single
|
| 85 |
+
pointer word.
|
| 86 |
+
|
| 87 |
+
An array type `[N]T` is a sequence of N fields of type T.
|
| 88 |
+
|
| 89 |
+
The slice type `[]T` is a sequence of a `*[cap]T` pointer to the slice
|
| 90 |
+
backing store, an `int` giving the `len` of the slice, and an `int`
|
| 91 |
+
giving the `cap` of the slice.
|
| 92 |
+
|
| 93 |
+
The `string` type is a sequence of a `*[len]byte` pointer to the
|
| 94 |
+
string backing store, and an `int` giving the `len` of the string.
|
| 95 |
+
|
| 96 |
+
A struct type `struct { f1 t1; ...; fM tM }` is laid out as the
|
| 97 |
+
sequence t1, ..., tM, tP, where tP is either:
|
| 98 |
+
|
| 99 |
+
- Type `byte` if sizeof(tM) = 0 and any of sizeof(t*i*) ≠ 0.
|
| 100 |
+
- Empty (size 0 and align 1) otherwise.
|
| 101 |
+
|
| 102 |
+
The padding byte prevents creating a past-the-end pointer by taking
|
| 103 |
+
the address of the final, empty fN field.
|
| 104 |
+
|
| 105 |
+
Note that user-written assembly code should generally not depend on Go
|
| 106 |
+
type layout and should instead use the constants defined in
|
| 107 |
+
[`go_asm.h`](/doc/asm.html#data-offsets).
|
| 108 |
+
|
| 109 |
+
## Function call argument and result passing
|
| 110 |
+
|
| 111 |
+
Function calls pass arguments and results using a combination of the
|
| 112 |
+
stack and machine registers.
|
| 113 |
+
Each argument or result is passed either entirely in registers or
|
| 114 |
+
entirely on the stack.
|
| 115 |
+
Because access to registers is generally faster than access to the
|
| 116 |
+
stack, arguments and results are preferentially passed in registers.
|
| 117 |
+
However, any argument or result that contains a non-trivial array or
|
| 118 |
+
does not fit entirely in the remaining available registers is passed
|
| 119 |
+
on the stack.
|
| 120 |
+
|
| 121 |
+
Each architecture defines a sequence of integer registers and a
|
| 122 |
+
sequence of floating-point registers.
|
| 123 |
+
At a high level, arguments and results are recursively broken down
|
| 124 |
+
into values of base types and these base values are assigned to
|
| 125 |
+
registers from these sequences.
|
| 126 |
+
|
| 127 |
+
Arguments and results can share the same registers, but do not share
|
| 128 |
+
the same stack space.
|
| 129 |
+
Beyond the arguments and results passed on the stack, the caller also
|
| 130 |
+
reserves spill space on the stack for all register-based arguments
|
| 131 |
+
(but does not populate this space).
|
| 132 |
+
|
| 133 |
+
The receiver, arguments, and results of function or method F are
|
| 134 |
+
assigned to registers or the stack using the following algorithm:
|
| 135 |
+
|
| 136 |
+
1. Let NI and NFP be the length of integer and floating-point register
|
| 137 |
+
sequences defined by the architecture.
|
| 138 |
+
Let I and FP be 0; these are the indexes of the next integer and
|
| 139 |
+
floating-point register.
|
| 140 |
+
Let S, the type sequence defining the stack frame, be empty.
|
| 141 |
+
1. If F is a method, assign F’s receiver.
|
| 142 |
+
1. For each argument A of F, assign A.
|
| 143 |
+
1. Add a pointer-alignment field to S. This has size 0 and the same
|
| 144 |
+
alignment as `uintptr`.
|
| 145 |
+
1. Reset I and FP to 0.
|
| 146 |
+
1. For each result R of F, assign R.
|
| 147 |
+
1. Add a pointer-alignment field to S.
|
| 148 |
+
1. For each register-assigned receiver and argument of F, let T be its
|
| 149 |
+
type and add T to the stack sequence S.
|
| 150 |
+
This is the argument's (or receiver's) spill space and will be
|
| 151 |
+
uninitialized at the call.
|
| 152 |
+
1. Add a pointer-alignment field to S.
|
| 153 |
+
|
| 154 |
+
Assigning a receiver, argument, or result V of underlying type T works
|
| 155 |
+
as follows:
|
| 156 |
+
|
| 157 |
+
1. Remember I and FP.
|
| 158 |
+
1. If T has zero size, add T to the stack sequence S and return.
|
| 159 |
+
1. Try to register-assign V.
|
| 160 |
+
1. If step 3 failed, reset I and FP to the values from step 1, add T
|
| 161 |
+
to the stack sequence S, and assign V to this field in S.
|
| 162 |
+
|
| 163 |
+
Register-assignment of a value V of underlying type T works as follows:
|
| 164 |
+
|
| 165 |
+
1. If T is a boolean or integral type that fits in an integer
|
| 166 |
+
register, assign V to register I and increment I.
|
| 167 |
+
1. If T is an integral type that fits in two integer registers, assign
|
| 168 |
+
the least significant and most significant halves of V to registers
|
| 169 |
+
I and I+1, respectively, and increment I by 2
|
| 170 |
+
1. If T is a floating-point type and can be represented without loss
|
| 171 |
+
of precision in a floating-point register, assign V to register FP
|
| 172 |
+
and increment FP.
|
| 173 |
+
1. If T is a complex type, recursively register-assign its real and
|
| 174 |
+
imaginary parts.
|
| 175 |
+
1. If T is a pointer type, map type, channel type, or function type,
|
| 176 |
+
assign V to register I and increment I.
|
| 177 |
+
1. If T is a string type, interface type, or slice type, recursively
|
| 178 |
+
register-assign V’s components (2 for strings and interfaces, 3 for
|
| 179 |
+
slices).
|
| 180 |
+
1. If T is a struct type, recursively register-assign each field of V.
|
| 181 |
+
1. If T is an array type of length 0, do nothing.
|
| 182 |
+
1. If T is an array type of length 1, recursively register-assign its
|
| 183 |
+
one element.
|
| 184 |
+
1. If T is an array type of length > 1, fail.
|
| 185 |
+
1. If I > NI or FP > NFP, fail.
|
| 186 |
+
1. If any recursive assignment above fails, fail.
|
| 187 |
+
|
| 188 |
+
The above algorithm produces an assignment of each receiver, argument,
|
| 189 |
+
and result to registers or to a field in the stack sequence.
|
| 190 |
+
The final stack sequence looks like: stack-assigned receiver,
|
| 191 |
+
stack-assigned arguments, pointer-alignment, stack-assigned results,
|
| 192 |
+
pointer-alignment, spill space for each register-assigned argument,
|
| 193 |
+
pointer-alignment.
|
| 194 |
+
The following diagram shows what this stack frame looks like on the
|
| 195 |
+
stack, using the typical convention where address 0 is at the bottom:
|
| 196 |
+
|
| 197 |
+
+------------------------------+
|
| 198 |
+
| . . . |
|
| 199 |
+
| 2nd reg argument spill space |
|
| 200 |
+
| 1st reg argument spill space |
|
| 201 |
+
| <pointer-sized alignment> |
|
| 202 |
+
| . . . |
|
| 203 |
+
| 2nd stack-assigned result |
|
| 204 |
+
| 1st stack-assigned result |
|
| 205 |
+
| <pointer-sized alignment> |
|
| 206 |
+
| . . . |
|
| 207 |
+
| 2nd stack-assigned argument |
|
| 208 |
+
| 1st stack-assigned argument |
|
| 209 |
+
| stack-assigned receiver |
|
| 210 |
+
+------------------------------+ ↓ lower addresses
|
| 211 |
+
|
| 212 |
+
To perform a call, the caller reserves space starting at the lowest
|
| 213 |
+
address in its stack frame for the call stack frame, stores arguments
|
| 214 |
+
in the registers and argument stack fields determined by the above
|
| 215 |
+
algorithm, and performs the call.
|
| 216 |
+
At the time of a call, spill space, result stack fields, and result
|
| 217 |
+
registers are left uninitialized.
|
| 218 |
+
Upon return, the callee must have stored results to all result
|
| 219 |
+
registers and result stack fields determined by the above algorithm.
|
| 220 |
+
|
| 221 |
+
There are no callee-save registers, so a call may overwrite any
|
| 222 |
+
register that doesn’t have a fixed meaning, including argument
|
| 223 |
+
registers.
|
| 224 |
+
|
| 225 |
+
### Example
|
| 226 |
+
|
| 227 |
+
Consider the function `func f(a1 uint8, a2 [2]uintptr, a3 uint8) (r1
|
| 228 |
+
struct { x uintptr; y [2]uintptr }, r2 string)` on a 64-bit
|
| 229 |
+
architecture with hypothetical integer registers R0–R9.
|
| 230 |
+
|
| 231 |
+
On entry, `a1` is assigned to `R0`, `a3` is assigned to `R1` and the
|
| 232 |
+
stack frame is laid out in the following sequence:
|
| 233 |
+
|
| 234 |
+
a2 [2]uintptr
|
| 235 |
+
r1.x uintptr
|
| 236 |
+
r1.y [2]uintptr
|
| 237 |
+
a1Spill uint8
|
| 238 |
+
a3Spill uint8
|
| 239 |
+
_ [6]uint8 // alignment padding
|
| 240 |
+
|
| 241 |
+
In the stack frame, only the `a2` field is initialized on entry; the
|
| 242 |
+
rest of the frame is left uninitialized.
|
| 243 |
+
|
| 244 |
+
On exit, `r2.base` is assigned to `R0`, `r2.len` is assigned to `R1`,
|
| 245 |
+
and `r1.x` and `r1.y` are initialized in the stack frame.
|
| 246 |
+
|
| 247 |
+
There are several things to note in this example.
|
| 248 |
+
First, `a2` and `r1` are stack-assigned because they contain arrays.
|
| 249 |
+
The other arguments and results are register-assigned.
|
| 250 |
+
Result `r2` is decomposed into its components, which are individually
|
| 251 |
+
register-assigned.
|
| 252 |
+
On the stack, the stack-assigned arguments appear at lower addresses
|
| 253 |
+
than the stack-assigned results, which appear at lower addresses than
|
| 254 |
+
the argument spill area.
|
| 255 |
+
Only arguments, not results, are assigned a spill area on the stack.
|
| 256 |
+
|
| 257 |
+
### Rationale
|
| 258 |
+
|
| 259 |
+
Each base value is assigned to its own register to optimize
|
| 260 |
+
construction and access.
|
| 261 |
+
An alternative would be to pack multiple sub-word values into
|
| 262 |
+
registers, or to simply map an argument's in-memory layout to
|
| 263 |
+
registers (this is common in C ABIs), but this typically adds cost to
|
| 264 |
+
pack and unpack these values.
|
| 265 |
+
Modern architectures have more than enough registers to pass all
|
| 266 |
+
arguments and results this way for nearly all functions (see the
|
| 267 |
+
appendix), so there’s little downside to spreading base values across
|
| 268 |
+
registers.
|
| 269 |
+
|
| 270 |
+
Arguments that can’t be fully assigned to registers are passed
|
| 271 |
+
entirely on the stack in case the callee takes the address of that
|
| 272 |
+
argument.
|
| 273 |
+
If an argument could be split across the stack and registers and the
|
| 274 |
+
callee took its address, it would need to be reconstructed in memory,
|
| 275 |
+
a process that would be proportional to the size of the argument.
|
| 276 |
+
|
| 277 |
+
Non-trivial arrays are always passed on the stack because indexing
|
| 278 |
+
into an array typically requires a computed offset, which generally
|
| 279 |
+
isn’t possible with registers.
|
| 280 |
+
Arrays in general are rare in function signatures (only 0.7% of
|
| 281 |
+
functions in the Go 1.15 standard library and 0.2% in kubelet).
|
| 282 |
+
We considered allowing array fields to be passed on the stack while
|
| 283 |
+
the rest of an argument’s fields are passed in registers, but this
|
| 284 |
+
creates the same problems as other large structs if the callee takes
|
| 285 |
+
the address of an argument, and would benefit <0.1% of functions in
|
| 286 |
+
kubelet (and even these very little).
|
| 287 |
+
|
| 288 |
+
We make exceptions for 0 and 1-element arrays because these don’t
|
| 289 |
+
require computed offsets, and 1-element arrays are already decomposed
|
| 290 |
+
in the compiler’s SSA representation.
|
| 291 |
+
|
| 292 |
+
The ABI assignment algorithm above is equivalent to Go’s stack-based
|
| 293 |
+
ABI0 calling convention if there are zero architecture registers.
|
| 294 |
+
This is intended to ease the transition to the register-based internal
|
| 295 |
+
ABI and make it easy for the compiler to generate either calling
|
| 296 |
+
convention.
|
| 297 |
+
An architecture may still define register meanings that aren’t
|
| 298 |
+
compatible with ABI0, but these differences should be easy to account
|
| 299 |
+
for in the compiler.
|
| 300 |
+
|
| 301 |
+
The assignment algorithm assigns zero-sized values to the stack
|
| 302 |
+
(assignment step 2) in order to support ABI0-equivalence.
|
| 303 |
+
While these values take no space themselves, they do result in
|
| 304 |
+
alignment padding on the stack in ABI0.
|
| 305 |
+
Without this step, the internal ABI would register-assign zero-sized
|
| 306 |
+
values even on architectures that provide no argument registers
|
| 307 |
+
because they don't consume any registers, and hence not add alignment
|
| 308 |
+
padding to the stack.
|
| 309 |
+
|
| 310 |
+
The algorithm reserves spill space for arguments in the caller’s frame
|
| 311 |
+
so that the compiler can generate a stack growth path that spills into
|
| 312 |
+
this reserved space.
|
| 313 |
+
If the callee has to grow the stack, it may not be able to reserve
|
| 314 |
+
enough additional stack space in its own frame to spill these, which
|
| 315 |
+
is why it’s important that the caller do so.
|
| 316 |
+
These slots also act as the home location if these arguments need to
|
| 317 |
+
be spilled for any other reason, which simplifies traceback printing.
|
| 318 |
+
|
| 319 |
+
There are several options for how to lay out the argument spill space.
|
| 320 |
+
We chose to lay out each argument according to its type's usual memory
|
| 321 |
+
layout but to separate the spill space from the regular argument
|
| 322 |
+
space.
|
| 323 |
+
Using the usual memory layout simplifies the compiler because it
|
| 324 |
+
already understands this layout.
|
| 325 |
+
Also, if a function takes the address of a register-assigned argument,
|
| 326 |
+
the compiler must spill that argument to memory in its usual memory
|
| 327 |
+
layout and it's more convenient to use the argument spill space for
|
| 328 |
+
this purpose.
|
| 329 |
+
|
| 330 |
+
Alternatively, the spill space could be structured around argument
|
| 331 |
+
registers.
|
| 332 |
+
In this approach, the stack growth spill path would spill each
|
| 333 |
+
argument register to a register-sized stack word.
|
| 334 |
+
However, if the function takes the address of a register-assigned
|
| 335 |
+
argument, the compiler would have to reconstruct it in memory layout
|
| 336 |
+
elsewhere on the stack.
|
| 337 |
+
|
| 338 |
+
The spill space could also be interleaved with the stack-assigned
|
| 339 |
+
arguments so the arguments appear in order whether they are register-
|
| 340 |
+
or stack-assigned.
|
| 341 |
+
This would be close to ABI0, except that register-assigned arguments
|
| 342 |
+
would be uninitialized on the stack and there's no need to reserve
|
| 343 |
+
stack space for register-assigned results.
|
| 344 |
+
We expect separating the spill space to perform better because of
|
| 345 |
+
memory locality.
|
| 346 |
+
Separating the space is also potentially simpler for `reflect` calls
|
| 347 |
+
because this allows `reflect` to summarize the spill space as a single
|
| 348 |
+
number.
|
| 349 |
+
Finally, the long-term intent is to remove reserved spill slots
|
| 350 |
+
entirely – allowing most functions to be called without any stack
|
| 351 |
+
setup and easing the introduction of callee-save registers – and
|
| 352 |
+
separating the spill space makes that transition easier.
|
| 353 |
+
|
| 354 |
+
## Closures
|
| 355 |
+
|
| 356 |
+
A func value (e.g., `var x func()`) is a pointer to a closure object.
|
| 357 |
+
A closure object begins with a pointer-sized program counter
|
| 358 |
+
representing the entry point of the function, followed by zero or more
|
| 359 |
+
bytes containing the closed-over environment.
|
| 360 |
+
|
| 361 |
+
Closure calls follow the same conventions as static function and
|
| 362 |
+
method calls, with one addition. Each architecture specifies a
|
| 363 |
+
*closure context pointer* register and calls to closures store the
|
| 364 |
+
address of the closure object in the closure context pointer register
|
| 365 |
+
prior to the call.
|
| 366 |
+
|
| 367 |
+
## Software floating-point mode
|
| 368 |
+
|
| 369 |
+
In "softfloat" mode, the ABI simply treats the hardware as having zero
|
| 370 |
+
floating-point registers.
|
| 371 |
+
As a result, any arguments containing floating-point values will be
|
| 372 |
+
passed on the stack.
|
| 373 |
+
|
| 374 |
+
*Rationale*: Softfloat mode is about compatibility over performance
|
| 375 |
+
and is not commonly used.
|
| 376 |
+
Hence, we keep the ABI as simple as possible in this case, rather than
|
| 377 |
+
adding additional rules for passing floating-point values in integer
|
| 378 |
+
registers.
|
| 379 |
+
|
| 380 |
+
## Architecture specifics
|
| 381 |
+
|
| 382 |
+
This section describes per-architecture register mappings, as well as
|
| 383 |
+
other per-architecture special cases.
|
| 384 |
+
|
| 385 |
+
### amd64 architecture
|
| 386 |
+
|
| 387 |
+
The amd64 architecture uses the following sequence of 9 registers for
|
| 388 |
+
integer arguments and results:
|
| 389 |
+
|
| 390 |
+
RAX, RBX, RCX, RDI, RSI, R8, R9, R10, R11
|
| 391 |
+
|
| 392 |
+
It uses X0 – X14 for floating-point arguments and results.
|
| 393 |
+
|
| 394 |
+
*Rationale*: These sequences are chosen from the available registers
|
| 395 |
+
to be relatively easy to remember.
|
| 396 |
+
|
| 397 |
+
Registers R12 and R13 are permanent scratch registers.
|
| 398 |
+
R15 is a scratch register except in dynamically linked binaries.
|
| 399 |
+
|
| 400 |
+
*Rationale*: Some operations such as stack growth and reflection calls
|
| 401 |
+
need dedicated scratch registers in order to manipulate call frames
|
| 402 |
+
without corrupting arguments or results.
|
| 403 |
+
|
| 404 |
+
Special-purpose registers are as follows:
|
| 405 |
+
|
| 406 |
+
| Register | Call meaning | Return meaning | Body meaning |
|
| 407 |
+
| --- | --- | --- | --- |
|
| 408 |
+
| RSP | Stack pointer | Same | Same |
|
| 409 |
+
| RBP | Frame pointer | Same | Same |
|
| 410 |
+
| RDX | Closure context pointer | Scratch | Scratch |
|
| 411 |
+
| R12 | Scratch | Scratch | Scratch |
|
| 412 |
+
| R13 | Scratch | Scratch | Scratch |
|
| 413 |
+
| R14 | Current goroutine | Same | Same |
|
| 414 |
+
| R15 | GOT reference temporary if dynlink | Same | Same |
|
| 415 |
+
| X15 | Zero value (*) | Same | Scratch |
|
| 416 |
+
|
| 417 |
+
(*) Except on Plan 9, where X15 is a scratch register because SSE
|
| 418 |
+
registers cannot be used in note handlers (so the compiler avoids
|
| 419 |
+
using them except when absolutely necessary).
|
| 420 |
+
|
| 421 |
+
*Rationale*: These register meanings are compatible with Go’s
|
| 422 |
+
stack-based calling convention except for R14 and X15, which will have
|
| 423 |
+
to be restored on transitions from ABI0 code to ABIInternal code.
|
| 424 |
+
In ABI0, these are undefined, so transitions from ABIInternal to ABI0
|
| 425 |
+
can ignore these registers.
|
| 426 |
+
|
| 427 |
+
*Rationale*: For the current goroutine pointer, we chose a register
|
| 428 |
+
that requires an additional REX byte.
|
| 429 |
+
While this adds one byte to every function prologue, it is hardly ever
|
| 430 |
+
accessed outside the function prologue and we expect making more
|
| 431 |
+
single-byte registers available to be a net win.
|
| 432 |
+
|
| 433 |
+
*Rationale*: We could allow R14 (the current goroutine pointer) to be
|
| 434 |
+
a scratch register in function bodies because it can always be
|
| 435 |
+
restored from TLS on amd64.
|
| 436 |
+
However, we designate it as a fixed register for simplicity and for
|
| 437 |
+
consistency with other architectures that may not have a copy of the
|
| 438 |
+
current goroutine pointer in TLS.
|
| 439 |
+
|
| 440 |
+
*Rationale*: We designate X15 as a fixed zero register because
|
| 441 |
+
functions often have to bulk zero their stack frames, and this is more
|
| 442 |
+
efficient with a designated zero register.
|
| 443 |
+
|
| 444 |
+
*Implementation note*: Registers with fixed meaning at calls but not
|
| 445 |
+
in function bodies must be initialized by "injected" calls such as
|
| 446 |
+
signal-based panics.
|
| 447 |
+
|
| 448 |
+
#### Stack layout
|
| 449 |
+
|
| 450 |
+
The stack pointer, RSP, grows down and is always aligned to 8 bytes.
|
| 451 |
+
|
| 452 |
+
The amd64 architecture does not use a link register.
|
| 453 |
+
|
| 454 |
+
A function's stack frame is laid out as follows:
|
| 455 |
+
|
| 456 |
+
+------------------------------+
|
| 457 |
+
| return PC |
|
| 458 |
+
| RBP on entry |
|
| 459 |
+
| ... locals ... |
|
| 460 |
+
| ... outgoing arguments ... |
|
| 461 |
+
+------------------------------+ ↓ lower addresses
|
| 462 |
+
|
| 463 |
+
The "return PC" is pushed as part of the standard amd64 `CALL`
|
| 464 |
+
operation.
|
| 465 |
+
On entry, a function subtracts from RSP to open its stack frame and
|
| 466 |
+
saves the value of RBP directly below the return PC.
|
| 467 |
+
A leaf function that does not require any stack space may omit the
|
| 468 |
+
saved RBP.
|
| 469 |
+
|
| 470 |
+
The Go ABI's use of RBP as a frame pointer register is compatible with
|
| 471 |
+
amd64 platform conventions so that Go can inter-operate with platform
|
| 472 |
+
debuggers and profilers.
|
| 473 |
+
|
| 474 |
+
#### Flags
|
| 475 |
+
|
| 476 |
+
The direction flag (D) is always cleared (set to the “forward”
|
| 477 |
+
direction) at a call.
|
| 478 |
+
The arithmetic status flags are treated like scratch registers and not
|
| 479 |
+
preserved across calls.
|
| 480 |
+
All other bits in RFLAGS are system flags.
|
| 481 |
+
|
| 482 |
+
At function calls and returns, the CPU is in x87 mode (not MMX
|
| 483 |
+
technology mode).
|
| 484 |
+
|
| 485 |
+
*Rationale*: Go on amd64 does not use either the x87 registers or MMX
|
| 486 |
+
registers. Hence, we follow the SysV platform conventions in order to
|
| 487 |
+
simplify transitions to and from the C ABI.
|
| 488 |
+
|
| 489 |
+
At calls, the MXCSR control bits are always set as follows:
|
| 490 |
+
|
| 491 |
+
| Flag | Bit | Value | Meaning |
|
| 492 |
+
| --- | --- | --- | --- |
|
| 493 |
+
| FZ | 15 | 0 | Do not flush to zero |
|
| 494 |
+
| RC | 14/13 | 0 (RN) | Round to nearest |
|
| 495 |
+
| PM | 12 | 1 | Precision masked |
|
| 496 |
+
| UM | 11 | 1 | Underflow masked |
|
| 497 |
+
| OM | 10 | 1 | Overflow masked |
|
| 498 |
+
| ZM | 9 | 1 | Divide-by-zero masked |
|
| 499 |
+
| DM | 8 | 1 | Denormal operations masked |
|
| 500 |
+
| IM | 7 | 1 | Invalid operations masked |
|
| 501 |
+
| DAZ | 6 | 0 | Do not zero de-normals |
|
| 502 |
+
|
| 503 |
+
The MXCSR status bits are callee-save.
|
| 504 |
+
|
| 505 |
+
*Rationale*: Having a fixed MXCSR control configuration allows Go
|
| 506 |
+
functions to use SSE operations without modifying or saving the MXCSR.
|
| 507 |
+
Functions are allowed to modify it between calls (as long as they
|
| 508 |
+
restore it), but as of this writing Go code never does.
|
| 509 |
+
The above fixed configuration matches the process initialization
|
| 510 |
+
control bits specified by the ELF AMD64 ABI.
|
| 511 |
+
|
| 512 |
+
The x87 floating-point control word is not used by Go on amd64.
|
| 513 |
+
|
| 514 |
+
### arm64 architecture
|
| 515 |
+
|
| 516 |
+
The arm64 architecture uses R0 – R15 for integer arguments and results.
|
| 517 |
+
|
| 518 |
+
It uses F0 – F15 for floating-point arguments and results.
|
| 519 |
+
|
| 520 |
+
*Rationale*: 16 integer registers and 16 floating-point registers are
|
| 521 |
+
more than enough for passing arguments and results for practically all
|
| 522 |
+
functions (see Appendix). While there are more registers available,
|
| 523 |
+
using more registers provides little benefit. Additionally, it will add
|
| 524 |
+
overhead on code paths where the number of arguments are not statically
|
| 525 |
+
known (e.g. reflect call), and will consume more stack space when there
|
| 526 |
+
is only limited stack space available to fit in the nosplit limit.
|
| 527 |
+
|
| 528 |
+
Registers R16 and R17 are permanent scratch registers. They are also
|
| 529 |
+
used as scratch registers by the linker (Go linker and external
|
| 530 |
+
linker) in trampolines.
|
| 531 |
+
|
| 532 |
+
Register R18 is reserved and never used. It is reserved for the OS
|
| 533 |
+
on some platforms (e.g. macOS).
|
| 534 |
+
|
| 535 |
+
Registers R19 – R25 are permanent scratch registers. In addition,
|
| 536 |
+
R27 is a permanent scratch register used by the assembler when
|
| 537 |
+
expanding instructions.
|
| 538 |
+
|
| 539 |
+
Floating-point registers F16 – F31 are also permanent scratch
|
| 540 |
+
registers.
|
| 541 |
+
|
| 542 |
+
Special-purpose registers are as follows:
|
| 543 |
+
|
| 544 |
+
| Register | Call meaning | Return meaning | Body meaning |
|
| 545 |
+
| --- | --- | --- | --- |
|
| 546 |
+
| RSP | Stack pointer | Same | Same |
|
| 547 |
+
| R30 | Link register | Same | Scratch (non-leaf functions) |
|
| 548 |
+
| R29 | Frame pointer | Same | Same |
|
| 549 |
+
| R28 | Current goroutine | Same | Same |
|
| 550 |
+
| R27 | Scratch | Scratch | Scratch |
|
| 551 |
+
| R26 | Closure context pointer | Scratch | Scratch |
|
| 552 |
+
| R18 | Reserved (not used) | Same | Same |
|
| 553 |
+
| ZR | Zero value | Same | Same |
|
| 554 |
+
|
| 555 |
+
*Rationale*: These register meanings are compatible with Go’s
|
| 556 |
+
stack-based calling convention.
|
| 557 |
+
|
| 558 |
+
*Rationale*: The link register, R30, holds the function return
|
| 559 |
+
address at the function entry. For functions that have frames
|
| 560 |
+
(including most non-leaf functions), R30 is saved to stack in the
|
| 561 |
+
function prologue and restored in the epilogue. Within the function
|
| 562 |
+
body, R30 can be used as a scratch register.
|
| 563 |
+
|
| 564 |
+
*Implementation note*: Registers with fixed meaning at calls but not
|
| 565 |
+
in function bodies must be initialized by "injected" calls such as
|
| 566 |
+
signal-based panics.
|
| 567 |
+
|
| 568 |
+
#### Stack layout
|
| 569 |
+
|
| 570 |
+
The stack pointer, RSP, grows down and is always aligned to 16 bytes.
|
| 571 |
+
|
| 572 |
+
*Rationale*: The arm64 architecture requires the stack pointer to be
|
| 573 |
+
16-byte aligned.
|
| 574 |
+
|
| 575 |
+
A function's stack frame, after the frame is created, is laid out as
|
| 576 |
+
follows:
|
| 577 |
+
|
| 578 |
+
+------------------------------+
|
| 579 |
+
| ... locals ... |
|
| 580 |
+
| ... outgoing arguments ... |
|
| 581 |
+
| return PC | ← RSP points to
|
| 582 |
+
| frame pointer on entry |
|
| 583 |
+
+------------------------------+ ↓ lower addresses
|
| 584 |
+
|
| 585 |
+
The "return PC" is loaded to the link register, R30, as part of the
|
| 586 |
+
arm64 `CALL` operation.
|
| 587 |
+
|
| 588 |
+
On entry, a function subtracts from RSP to open its stack frame, and
|
| 589 |
+
saves the values of R30 and R29 at the bottom of the frame.
|
| 590 |
+
Specifically, R30 is saved at 0(RSP) and R29 is saved at -8(RSP),
|
| 591 |
+
after RSP is updated.
|
| 592 |
+
|
| 593 |
+
A leaf function that does not require any stack space may omit the
|
| 594 |
+
saved R30 and R29.
|
| 595 |
+
|
| 596 |
+
The Go ABI's use of R29 as a frame pointer register is compatible with
|
| 597 |
+
arm64 architecture requirement so that Go can inter-operate with platform
|
| 598 |
+
debuggers and profilers.
|
| 599 |
+
|
| 600 |
+
This stack layout is used by both register-based (ABIInternal) and
|
| 601 |
+
stack-based (ABI0) calling conventions.
|
| 602 |
+
|
| 603 |
+
#### Flags
|
| 604 |
+
|
| 605 |
+
The arithmetic status flags (NZCV) are treated like scratch registers
|
| 606 |
+
and not preserved across calls.
|
| 607 |
+
All other bits in PSTATE are system flags and are not modified by Go.
|
| 608 |
+
|
| 609 |
+
The floating-point status register (FPSR) is treated like scratch
|
| 610 |
+
registers and not preserved across calls.
|
| 611 |
+
|
| 612 |
+
At calls, the floating-point control register (FPCR) bits are always
|
| 613 |
+
set as follows:
|
| 614 |
+
|
| 615 |
+
| Flag | Bit | Value | Meaning |
|
| 616 |
+
| --- | --- | --- | --- |
|
| 617 |
+
| DN | 25 | 0 | Propagate NaN operands |
|
| 618 |
+
| FZ | 24 | 0 | Do not flush to zero |
|
| 619 |
+
| RC | 23/22 | 0 (RN) | Round to nearest, choose even if tied |
|
| 620 |
+
| IDE | 15 | 0 | Denormal operations trap disabled |
|
| 621 |
+
| IXE | 12 | 0 | Inexact trap disabled |
|
| 622 |
+
| UFE | 11 | 0 | Underflow trap disabled |
|
| 623 |
+
| OFE | 10 | 0 | Overflow trap disabled |
|
| 624 |
+
| DZE | 9 | 0 | Divide-by-zero trap disabled |
|
| 625 |
+
| IOE | 8 | 0 | Invalid operations trap disabled |
|
| 626 |
+
| NEP | 2 | 0 | Scalar operations do not affect higher elements in vector registers |
|
| 627 |
+
| AH | 1 | 0 | No alternate handling of de-normal inputs |
|
| 628 |
+
| FIZ | 0 | 0 | Do not zero de-normals |
|
| 629 |
+
|
| 630 |
+
*Rationale*: Having a fixed FPCR control configuration allows Go
|
| 631 |
+
functions to use floating-point and vector (SIMD) operations without
|
| 632 |
+
modifying or saving the FPCR.
|
| 633 |
+
Functions are allowed to modify it between calls (as long as they
|
| 634 |
+
restore it), but as of this writing Go code never does.
|
| 635 |
+
|
| 636 |
+
### loong64 architecture
|
| 637 |
+
|
| 638 |
+
The loong64 architecture uses R4 – R19 for integer arguments and integer results.
|
| 639 |
+
|
| 640 |
+
It uses F0 – F15 for floating-point arguments and results.
|
| 641 |
+
|
| 642 |
+
Registers R20 - R21, R23 – R28, R30 - R31, F16 – F31 are permanent scratch registers.
|
| 643 |
+
|
| 644 |
+
Register R2 is reserved and never used.
|
| 645 |
+
|
| 646 |
+
Register R20, R21 is Used by runtime.duffcopy, runtime.duffzero.
|
| 647 |
+
|
| 648 |
+
Special-purpose registers used within Go generated code and Go assembly code
|
| 649 |
+
are as follows:
|
| 650 |
+
|
| 651 |
+
| Register | Call meaning | Return meaning | Body meaning |
|
| 652 |
+
| --- | --- | --- | --- |
|
| 653 |
+
| R0 | Zero value | Same | Same |
|
| 654 |
+
| R1 | Link register | Link register | Scratch |
|
| 655 |
+
| R3 | Stack pointer | Same | Same |
|
| 656 |
+
| R20,R21 | Scratch | Scratch | Used by duffcopy, duffzero |
|
| 657 |
+
| R22 | Current goroutine | Same | Same |
|
| 658 |
+
| R29 | Closure context pointer | Same | Same |
|
| 659 |
+
| R30, R31 | used by the assembler | Same | Same |
|
| 660 |
+
|
| 661 |
+
*Rationale*: These register meanings are compatible with Go’s stack-based
|
| 662 |
+
calling convention.
|
| 663 |
+
|
| 664 |
+
#### Stack layout
|
| 665 |
+
|
| 666 |
+
The stack pointer, R3, grows down and is aligned to 8 bytes.
|
| 667 |
+
|
| 668 |
+
A function's stack frame, after the frame is created, is laid out as
|
| 669 |
+
follows:
|
| 670 |
+
|
| 671 |
+
+------------------------------+
|
| 672 |
+
| ... locals ... |
|
| 673 |
+
| ... outgoing arguments ... |
|
| 674 |
+
| return PC | ← R3 points to
|
| 675 |
+
+------------------------------+ ↓ lower addresses
|
| 676 |
+
|
| 677 |
+
This stack layout is used by both register-based (ABIInternal) and
|
| 678 |
+
stack-based (ABI0) calling conventions.
|
| 679 |
+
|
| 680 |
+
The "return PC" is loaded to the link register, R1, as part of the
|
| 681 |
+
loong64 `JAL` operation.
|
| 682 |
+
|
| 683 |
+
#### Flags
|
| 684 |
+
All bits in CSR are system flags and are not modified by Go.
|
| 685 |
+
|
| 686 |
+
### ppc64 architecture
|
| 687 |
+
|
| 688 |
+
The ppc64 architecture uses R3 – R10 and R14 – R17 for integer arguments
|
| 689 |
+
and results.
|
| 690 |
+
|
| 691 |
+
It uses F1 – F12 for floating-point arguments and results.
|
| 692 |
+
|
| 693 |
+
Register R31 is a permanent scratch register in Go.
|
| 694 |
+
|
| 695 |
+
Special-purpose registers used within Go generated code and Go
|
| 696 |
+
assembly code are as follows:
|
| 697 |
+
|
| 698 |
+
| Register | Call meaning | Return meaning | Body meaning |
|
| 699 |
+
| --- | --- | --- | --- |
|
| 700 |
+
| R0 | Zero value | Same | Same |
|
| 701 |
+
| R1 | Stack pointer | Same | Same |
|
| 702 |
+
| R2 | TOC register | Same | Same |
|
| 703 |
+
| R11 | Closure context pointer | Scratch | Scratch |
|
| 704 |
+
| R12 | Function address on indirect calls | Scratch | Scratch |
|
| 705 |
+
| R13 | TLS pointer | Same | Same |
|
| 706 |
+
| R20,R21 | Scratch | Scratch | Used by duffcopy, duffzero |
|
| 707 |
+
| R30 | Current goroutine | Same | Same |
|
| 708 |
+
| R31 | Scratch | Scratch | Scratch |
|
| 709 |
+
| LR | Link register | Link register | Scratch |
|
| 710 |
+
*Rationale*: These register meanings are compatible with Go’s
|
| 711 |
+
stack-based calling convention.
|
| 712 |
+
|
| 713 |
+
The link register, LR, holds the function return
|
| 714 |
+
address at the function entry and is set to the correct return
|
| 715 |
+
address before exiting the function. It is also used
|
| 716 |
+
in some cases as the function address when doing an indirect call.
|
| 717 |
+
|
| 718 |
+
The register R2 contains the address of the TOC (table of contents) which
|
| 719 |
+
contains data or code addresses used when generating position independent
|
| 720 |
+
code. Non-Go code generated when using cgo contains TOC-relative addresses
|
| 721 |
+
which depend on R2 holding a valid TOC. Go code compiled with -shared or
|
| 722 |
+
-dynlink initializes and maintains R2 and uses it in some cases for
|
| 723 |
+
function calls; Go code compiled without these options does not modify R2.
|
| 724 |
+
|
| 725 |
+
When making a function call R12 contains the function address for use by the
|
| 726 |
+
code to generate R2 at the beginning of the function. R12 can be used for
|
| 727 |
+
other purposes within the body of the function, such as trampoline generation.
|
| 728 |
+
|
| 729 |
+
R20 and R21 are used in duffcopy and duffzero which could be generated
|
| 730 |
+
before arguments are saved so should not be used for register arguments.
|
| 731 |
+
|
| 732 |
+
The Count register CTR can be used as the call target for some branch instructions.
|
| 733 |
+
It holds the return address when preemption has occurred.
|
| 734 |
+
|
| 735 |
+
On PPC64 when a float32 is loaded it becomes a float64 in the register, which is
|
| 736 |
+
different from other platforms and that needs to be recognized by the internal
|
| 737 |
+
implementation of reflection so that float32 arguments are passed correctly.
|
| 738 |
+
|
| 739 |
+
Registers R18 - R29 and F13 - F31 are considered scratch registers.
|
| 740 |
+
|
| 741 |
+
#### Stack layout
|
| 742 |
+
|
| 743 |
+
The stack pointer, R1, grows down and is aligned to 8 bytes in Go, but changed
|
| 744 |
+
to 16 bytes when calling cgo.
|
| 745 |
+
|
| 746 |
+
A function's stack frame, after the frame is created, is laid out as
|
| 747 |
+
follows:
|
| 748 |
+
|
| 749 |
+
+------------------------------+
|
| 750 |
+
| ... locals ... |
|
| 751 |
+
| ... outgoing arguments ... |
|
| 752 |
+
| 24 TOC register R2 save | When compiled with -shared/-dynlink
|
| 753 |
+
| 16 Unused in Go | Not used in Go
|
| 754 |
+
| 8 CR save | nonvolatile CR fields
|
| 755 |
+
| 0 return PC | ← R1 points to
|
| 756 |
+
+------------------------------+ ↓ lower addresses
|
| 757 |
+
|
| 758 |
+
The "return PC" is loaded to the link register, LR, as part of the
|
| 759 |
+
ppc64 `BL` operations.
|
| 760 |
+
|
| 761 |
+
On entry to a non-leaf function, the stack frame size is subtracted from R1 to
|
| 762 |
+
create its stack frame, and saves the value of LR at the bottom of the frame.
|
| 763 |
+
|
| 764 |
+
A leaf function that does not require any stack space does not modify R1 and
|
| 765 |
+
does not save LR.
|
| 766 |
+
|
| 767 |
+
*NOTE*: We might need to save the frame pointer on the stack as
|
| 768 |
+
in the PPC64 ELF v2 ABI so Go can inter-operate with platform debuggers
|
| 769 |
+
and profilers.
|
| 770 |
+
|
| 771 |
+
This stack layout is used by both register-based (ABIInternal) and
|
| 772 |
+
stack-based (ABI0) calling conventions.
|
| 773 |
+
|
| 774 |
+
#### Flags
|
| 775 |
+
|
| 776 |
+
The condition register consists of 8 condition code register fields
|
| 777 |
+
CR0-CR7. Go generated code only sets and uses CR0, commonly set by
|
| 778 |
+
compare functions and use to determine the target of a conditional
|
| 779 |
+
branch. The generated code does not set or use CR1-CR7.
|
| 780 |
+
|
| 781 |
+
The floating point status and control register (FPSCR) is initialized
|
| 782 |
+
to 0 by the kernel at startup of the Go program and not changed by
|
| 783 |
+
the Go generated code.
|
| 784 |
+
|
| 785 |
+
### riscv64 architecture
|
| 786 |
+
|
| 787 |
+
The riscv64 architecture uses X10 – X17, X8, X9, X18 – X23 for integer arguments
|
| 788 |
+
and results.
|
| 789 |
+
|
| 790 |
+
It uses F10 – F17, F8, F9, F18 – F23 for floating-point arguments and results.
|
| 791 |
+
|
| 792 |
+
Special-purpose registers used within Go generated code and Go
|
| 793 |
+
assembly code are as follows:
|
| 794 |
+
|
| 795 |
+
| Register | Call meaning | Return meaning | Body meaning |
|
| 796 |
+
| --- | --- | --- | --- |
|
| 797 |
+
| X0 | Zero value | Same | Same |
|
| 798 |
+
| X1 | Link register | Link register | Scratch |
|
| 799 |
+
| X2 | Stack pointer | Same | Same |
|
| 800 |
+
| X3 | Global pointer | Same | Used by dynamic linker |
|
| 801 |
+
| X4 | TLS (thread pointer) | TLS | Scratch |
|
| 802 |
+
| X26 | Closure context pointer | Scratch | Scratch |
|
| 803 |
+
| X27 | Current goroutine | Same | Same |
|
| 804 |
+
| X31 | Scratch | Scratch | Scratch |
|
| 805 |
+
|
| 806 |
+
*Rationale*: These register meanings are compatible with Go’s
|
| 807 |
+
stack-based calling convention.
|
| 808 |
+
X10 – X17, X8, X9, X18 – X23, is the same order as A0 – A7, S0 – S7 in platform ABI.
|
| 809 |
+
F10 – F17, F8, F9, F18 – F23, is the same order as FA0 – FA7, FS0 – FS7 in platform ABI.
|
| 810 |
+
X8 – X23, F8 – F15 are used for compressed instruction (RVC) which benefits code size.
|
| 811 |
+
|
| 812 |
+
#### Stack layout
|
| 813 |
+
|
| 814 |
+
The stack pointer, X2, grows down and is aligned to 8 bytes.
|
| 815 |
+
|
| 816 |
+
A function's stack frame, after the frame is created, is laid out as
|
| 817 |
+
follows:
|
| 818 |
+
|
| 819 |
+
+------------------------------+
|
| 820 |
+
| ... locals ... |
|
| 821 |
+
| ... outgoing arguments ... |
|
| 822 |
+
| return PC | ← X2 points to
|
| 823 |
+
+------------------------------+ ↓ lower addresses
|
| 824 |
+
|
| 825 |
+
The "return PC" is loaded to the link register, X1, as part of the
|
| 826 |
+
riscv64 `CALL` operation.
|
| 827 |
+
|
| 828 |
+
#### Flags
|
| 829 |
+
|
| 830 |
+
The riscv64 has Zicsr extension for control and status register (CSR) and
|
| 831 |
+
treated as scratch register.
|
| 832 |
+
All bits in CSR are system flags and are not modified by Go.
|
| 833 |
+
|
| 834 |
+
### s390x architecture
|
| 835 |
+
|
| 836 |
+
The s390x architecture uses R2 – R9 for integer arguments and integer results.
|
| 837 |
+
|
| 838 |
+
It uses F0 – F15 for floating-point arguments and results.
|
| 839 |
+
|
| 840 |
+
Special-purpose registers used within Go generated code and Go assembly code
|
| 841 |
+
are as follows:
|
| 842 |
+
|
| 843 |
+
| Register | Call meaning | Return meaning | Body meaning |
|
| 844 |
+
| --- | --- | --- | --- |
|
| 845 |
+
| R0 | Zero value | Same | Same |
|
| 846 |
+
| R1 | Scratch | Scratch | Scratch |
|
| 847 |
+
| R10, R11 | used by the assembler | Same | Same |
|
| 848 |
+
| R12 | Closure context pointer | Same | Same |
|
| 849 |
+
| R13 | Current goroutine | Same | Same |
|
| 850 |
+
| R14 | Link register | Link register | Scratch |
|
| 851 |
+
| R15 | Stack pointer | Same | Same |
|
| 852 |
+
|
| 853 |
+
*Rationale*: These register meanings are compatible with Go’s stack-based
|
| 854 |
+
calling convention.
|
| 855 |
+
|
| 856 |
+
#### Stack layout
|
| 857 |
+
|
| 858 |
+
The stack pointer, R15, grows down and is aligned to 8 bytes.
|
| 859 |
+
|
| 860 |
+
A function's stack frame, after the frame is created, is laid out as
|
| 861 |
+
follows:
|
| 862 |
+
|
| 863 |
+
+------------------------------+
|
| 864 |
+
| ... locals ... |
|
| 865 |
+
| ... outgoing arguments ... |
|
| 866 |
+
| return PC | ← R15 points to
|
| 867 |
+
+------------------------------+ ↓ lower addresses
|
| 868 |
+
|
| 869 |
+
This stack layout is used by both register-based (ABIInternal) and
|
| 870 |
+
stack-based (ABI0) calling conventions.
|
| 871 |
+
|
| 872 |
+
The "return PC" is loaded to the link register R14, as part of the
|
| 873 |
+
s390x `BL` operation.
|
| 874 |
+
|
| 875 |
+
#### Flags
|
| 876 |
+
The s390x architecture maintains a single condition code (CC) field in the Program Status Word (PSW).
|
| 877 |
+
Go-generated code sets and tests this condition code to control conditional branches.
|
| 878 |
+
|
| 879 |
+
## Future directions
|
| 880 |
+
|
| 881 |
+
### Spill path improvements
|
| 882 |
+
|
| 883 |
+
The ABI currently reserves spill space for argument registers so the
|
| 884 |
+
compiler can statically generate an argument spill path before calling
|
| 885 |
+
into `runtime.morestack` to grow the stack.
|
| 886 |
+
This ensures there will be sufficient spill space even when the stack
|
| 887 |
+
is nearly exhausted and keeps stack growth and stack scanning
|
| 888 |
+
essentially unchanged from ABI0.
|
| 889 |
+
|
| 890 |
+
However, this wastes stack space (the median wastage is 16 bytes per
|
| 891 |
+
call), resulting in larger stacks and increased cache footprint.
|
| 892 |
+
A better approach would be to reserve stack space only when spilling.
|
| 893 |
+
One way to ensure enough space is available to spill would be for
|
| 894 |
+
every function to ensure there is enough space for the function's own
|
| 895 |
+
frame *as well as* the spill space of all functions it calls.
|
| 896 |
+
For most functions, this would change the threshold for the prologue
|
| 897 |
+
stack growth check.
|
| 898 |
+
For `nosplit` functions, this would change the threshold used in the
|
| 899 |
+
linker's static stack size check.
|
| 900 |
+
|
| 901 |
+
Allocating spill space in the callee rather than the caller may also
|
| 902 |
+
allow for faster reflection calls in the common case where a function
|
| 903 |
+
takes only register arguments, since it would allow reflection to make
|
| 904 |
+
these calls directly without allocating any frame.
|
| 905 |
+
|
| 906 |
+
The statically-generated spill path also increases code size.
|
| 907 |
+
It is possible to instead have a generic spill path in the runtime, as
|
| 908 |
+
part of `morestack`.
|
| 909 |
+
However, this complicates reserving the spill space, since spilling
|
| 910 |
+
all possible register arguments would, in most cases, take
|
| 911 |
+
significantly more space than spilling only those used by a particular
|
| 912 |
+
function.
|
| 913 |
+
Some options are to spill to a temporary space and copy back only the
|
| 914 |
+
registers used by the function, or to grow the stack if necessary
|
| 915 |
+
before spilling to it (using a temporary space if necessary), or to
|
| 916 |
+
use a heap-allocated space if insufficient stack space is available.
|
| 917 |
+
These options all add enough complexity that we will have to make this
|
| 918 |
+
decision based on the actual code size growth caused by the static
|
| 919 |
+
spill paths.
|
| 920 |
+
|
| 921 |
+
### Clobber sets
|
| 922 |
+
|
| 923 |
+
As defined, the ABI does not use callee-save registers.
|
| 924 |
+
This significantly simplifies the garbage collector and the compiler's
|
| 925 |
+
register allocator, but at some performance cost.
|
| 926 |
+
A potentially better balance for Go code would be to use *clobber
|
| 927 |
+
sets*: for each function, the compiler records the set of registers it
|
| 928 |
+
clobbers (including those clobbered by functions it calls) and any
|
| 929 |
+
register not clobbered by function F can remain live across calls to
|
| 930 |
+
F.
|
| 931 |
+
|
| 932 |
+
This is generally a good fit for Go because Go's package DAG allows
|
| 933 |
+
function metadata like the clobber set to flow up the call graph, even
|
| 934 |
+
across package boundaries.
|
| 935 |
+
Clobber sets would require relatively little change to the garbage
|
| 936 |
+
collector, unlike general callee-save registers.
|
| 937 |
+
One disadvantage of clobber sets over callee-save registers is that
|
| 938 |
+
they don't help with indirect function calls or interface method
|
| 939 |
+
calls, since static information isn't available in these cases.
|
| 940 |
+
|
| 941 |
+
### Large aggregates
|
| 942 |
+
|
| 943 |
+
Go encourages passing composite values by value, and this simplifies
|
| 944 |
+
reasoning about mutation and races.
|
| 945 |
+
However, this comes at a performance cost for large composite values.
|
| 946 |
+
It may be possible to instead transparently pass large composite
|
| 947 |
+
values by reference and delay copying until it is actually necessary.
|
| 948 |
+
|
| 949 |
+
## Appendix: Register usage analysis
|
| 950 |
+
|
| 951 |
+
In order to understand the impacts of the above design on register
|
| 952 |
+
usage, we
|
| 953 |
+
[analyzed](https://github.com/aclements/go-misc/tree/master/abi) the
|
| 954 |
+
impact of the above ABI on a large code base: cmd/kubelet from
|
| 955 |
+
[Kubernetes](https://github.com/kubernetes/kubernetes) at tag v1.18.8.
|
| 956 |
+
|
| 957 |
+
The following table shows the impact of different numbers of available
|
| 958 |
+
integer and floating-point registers on argument assignment:
|
| 959 |
+
|
| 960 |
+
```
|
| 961 |
+
| | | | stack args | spills | stack total |
|
| 962 |
+
| ints | floats | % fit | p50 | p95 | p99 | p50 | p95 | p99 | p50 | p95 | p99 |
|
| 963 |
+
| 0 | 0 | 6.3% | 32 | 152 | 256 | 0 | 0 | 0 | 32 | 152 | 256 |
|
| 964 |
+
| 0 | 8 | 6.4% | 32 | 152 | 256 | 0 | 0 | 0 | 32 | 152 | 256 |
|
| 965 |
+
| 1 | 8 | 21.3% | 24 | 144 | 248 | 8 | 8 | 8 | 32 | 152 | 256 |
|
| 966 |
+
| 2 | 8 | 38.9% | 16 | 128 | 224 | 8 | 16 | 16 | 24 | 136 | 240 |
|
| 967 |
+
| 3 | 8 | 57.0% | 0 | 120 | 224 | 16 | 24 | 24 | 24 | 136 | 240 |
|
| 968 |
+
| 4 | 8 | 73.0% | 0 | 120 | 216 | 16 | 32 | 32 | 24 | 136 | 232 |
|
| 969 |
+
| 5 | 8 | 83.3% | 0 | 112 | 216 | 16 | 40 | 40 | 24 | 136 | 232 |
|
| 970 |
+
| 6 | 8 | 87.5% | 0 | 112 | 208 | 16 | 48 | 48 | 24 | 136 | 232 |
|
| 971 |
+
| 7 | 8 | 89.8% | 0 | 112 | 208 | 16 | 48 | 56 | 24 | 136 | 232 |
|
| 972 |
+
| 8 | 8 | 91.3% | 0 | 112 | 200 | 16 | 56 | 64 | 24 | 136 | 232 |
|
| 973 |
+
| 9 | 8 | 92.1% | 0 | 112 | 192 | 16 | 56 | 72 | 24 | 136 | 232 |
|
| 974 |
+
| 10 | 8 | 92.6% | 0 | 104 | 192 | 16 | 56 | 72 | 24 | 136 | 232 |
|
| 975 |
+
| 11 | 8 | 93.1% | 0 | 104 | 184 | 16 | 56 | 80 | 24 | 128 | 232 |
|
| 976 |
+
| 12 | 8 | 93.4% | 0 | 104 | 176 | 16 | 56 | 88 | 24 | 128 | 232 |
|
| 977 |
+
| 13 | 8 | 94.0% | 0 | 88 | 176 | 16 | 56 | 96 | 24 | 128 | 232 |
|
| 978 |
+
| 14 | 8 | 94.4% | 0 | 80 | 152 | 16 | 64 | 104 | 24 | 128 | 232 |
|
| 979 |
+
| 15 | 8 | 94.6% | 0 | 80 | 152 | 16 | 64 | 112 | 24 | 128 | 232 |
|
| 980 |
+
| 16 | 8 | 94.9% | 0 | 16 | 152 | 16 | 64 | 112 | 24 | 128 | 232 |
|
| 981 |
+
| ∞ | 8 | 99.8% | 0 | 0 | 0 | 24 | 112 | 216 | 24 | 120 | 216 |
|
| 982 |
+
```
|
| 983 |
+
|
| 984 |
+
The first two columns show the number of available integer and
|
| 985 |
+
floating-point registers.
|
| 986 |
+
The first row shows the results for 0 integer and 0 floating-point
|
| 987 |
+
registers, which is equivalent to ABI0.
|
| 988 |
+
We found that any reasonable number of floating-point registers has
|
| 989 |
+
the same effect, so we fixed it at 8 for all other rows.
|
| 990 |
+
|
| 991 |
+
The “% fit” column gives the fraction of functions where all arguments
|
| 992 |
+
and results are register-assigned and no arguments are passed on the
|
| 993 |
+
stack.
|
| 994 |
+
The three “stack args” columns give the median, 95th and 99th
|
| 995 |
+
percentile number of bytes of stack arguments.
|
| 996 |
+
The “spills” columns likewise summarize the number of bytes in
|
| 997 |
+
on-stack spill space.
|
| 998 |
+
And “stack total” summarizes the sum of stack arguments and on-stack
|
| 999 |
+
spill slots.
|
| 1000 |
+
Note that these are three different distributions; for example,
|
| 1001 |
+
there’s no single function that takes 0 stack argument bytes, 16 spill
|
| 1002 |
+
bytes, and 24 total stack bytes.
|
| 1003 |
+
|
| 1004 |
+
From this, we can see that the fraction of functions that fit entirely
|
| 1005 |
+
in registers grows very slowly once it reaches about 90%, though
|
| 1006 |
+
curiously there is a small minority of functions that could benefit
|
| 1007 |
+
from a huge number of registers.
|
| 1008 |
+
Making 9 integer registers available on amd64 puts it in this realm.
|
| 1009 |
+
We also see that the stack space required for most functions is fairly
|
| 1010 |
+
small.
|
| 1011 |
+
While the increasing space required for spills largely balances out
|
| 1012 |
+
the decreasing space required for stack arguments as the number of
|
| 1013 |
+
available registers increases, there is a general reduction in the
|
| 1014 |
+
total stack space required with more available registers.
|
| 1015 |
+
This does, however, suggest that eliminating spill slots in the future
|
| 1016 |
+
would noticeably reduce stack requirements.
|
go/src/cmd/compile/doc.go
ADDED
|
@@ -0,0 +1,360 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Copyright 2009 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 |
+
/*
|
| 6 |
+
Compile, typically invoked as ``go tool compile,'' compiles a single Go package
|
| 7 |
+
comprising the files named on the command line. It then writes a single
|
| 8 |
+
object file named for the basename of the first source file with a .o suffix.
|
| 9 |
+
The object file can then be combined with other objects into a package archive
|
| 10 |
+
or passed directly to the linker (``go tool link''). If invoked with -pack, the compiler
|
| 11 |
+
writes an archive directly, bypassing the intermediate object file.
|
| 12 |
+
|
| 13 |
+
The generated files contain type information about the symbols exported by
|
| 14 |
+
the package and about types used by symbols imported by the package from
|
| 15 |
+
other packages. It is therefore not necessary when compiling client C of
|
| 16 |
+
package P to read the files of P's dependencies, only the compiled output of P.
|
| 17 |
+
|
| 18 |
+
# Command Line
|
| 19 |
+
|
| 20 |
+
Usage:
|
| 21 |
+
|
| 22 |
+
go tool compile [flags] file...
|
| 23 |
+
|
| 24 |
+
The specified files must be Go source files and all part of the same package.
|
| 25 |
+
The same compiler is used for all target operating systems and architectures.
|
| 26 |
+
The GOOS and GOARCH environment variables set the desired target.
|
| 27 |
+
|
| 28 |
+
Flags:
|
| 29 |
+
|
| 30 |
+
-D path
|
| 31 |
+
Set relative path for local imports.
|
| 32 |
+
-I dir1 -I dir2
|
| 33 |
+
Search for imported packages in dir1, dir2, etc,
|
| 34 |
+
after consulting $GOROOT/pkg/$GOOS_$GOARCH.
|
| 35 |
+
-L
|
| 36 |
+
Show complete file path in error messages.
|
| 37 |
+
-N
|
| 38 |
+
Disable optimizations.
|
| 39 |
+
-S
|
| 40 |
+
Print assembly listing to standard output (code only).
|
| 41 |
+
-S -S
|
| 42 |
+
Print assembly listing to standard output (code and data).
|
| 43 |
+
-V
|
| 44 |
+
Print compiler version and exit.
|
| 45 |
+
-asmhdr file
|
| 46 |
+
Write assembly header to file.
|
| 47 |
+
-asan
|
| 48 |
+
Insert calls to C/C++ address sanitizer.
|
| 49 |
+
-buildid id
|
| 50 |
+
Record id as the build id in the export metadata.
|
| 51 |
+
-blockprofile file
|
| 52 |
+
Write block profile for the compilation to file.
|
| 53 |
+
-c int
|
| 54 |
+
Concurrency during compilation. Set 1 for no concurrency (default is 1).
|
| 55 |
+
-complete
|
| 56 |
+
Assume package has no non-Go components.
|
| 57 |
+
-cpuprofile file
|
| 58 |
+
Write a CPU profile for the compilation to file.
|
| 59 |
+
-dynlink
|
| 60 |
+
Allow references to Go symbols in shared libraries (experimental).
|
| 61 |
+
-e
|
| 62 |
+
Remove the limit on the number of errors reported (default limit is 10).
|
| 63 |
+
-embedcfg file
|
| 64 |
+
Read go:embed configuration from file.
|
| 65 |
+
This is required if any //go:embed directives are used.
|
| 66 |
+
The file is a JSON file mapping patterns to lists of filenames
|
| 67 |
+
and filenames to full path names.
|
| 68 |
+
-goversion string
|
| 69 |
+
Specify required go tool version of the runtime.
|
| 70 |
+
Exits when the runtime go version does not match goversion.
|
| 71 |
+
-h
|
| 72 |
+
Halt with a stack trace at the first error detected.
|
| 73 |
+
-importcfg file
|
| 74 |
+
Read import configuration from file.
|
| 75 |
+
In the file, set importmap, packagefile to specify import resolution.
|
| 76 |
+
-installsuffix suffix
|
| 77 |
+
Look for packages in $GOROOT/pkg/$GOOS_$GOARCH_suffix
|
| 78 |
+
instead of $GOROOT/pkg/$GOOS_$GOARCH.
|
| 79 |
+
-l
|
| 80 |
+
Disable inlining.
|
| 81 |
+
-lang version
|
| 82 |
+
Set language version to compile, as in -lang=go1.12.
|
| 83 |
+
Default is current version.
|
| 84 |
+
-linkobj file
|
| 85 |
+
Write linker-specific object to file and compiler-specific
|
| 86 |
+
object to usual output file (as specified by -o).
|
| 87 |
+
Without this flag, the -o output is a combination of both
|
| 88 |
+
linker and compiler input.
|
| 89 |
+
-m
|
| 90 |
+
Print optimization decisions. Higher values or repetition
|
| 91 |
+
produce more detail.
|
| 92 |
+
-memprofile file
|
| 93 |
+
Write memory profile for the compilation to file.
|
| 94 |
+
-memprofilerate rate
|
| 95 |
+
Set runtime.MemProfileRate for the compilation to rate.
|
| 96 |
+
-msan
|
| 97 |
+
Insert calls to C/C++ memory sanitizer.
|
| 98 |
+
-mutexprofile file
|
| 99 |
+
Write mutex profile for the compilation to file.
|
| 100 |
+
-nolocalimports
|
| 101 |
+
Disallow local (relative) imports.
|
| 102 |
+
-o file
|
| 103 |
+
Write object to file (default file.o or, with -pack, file.a).
|
| 104 |
+
-p path
|
| 105 |
+
Set expected package import path for the code being compiled,
|
| 106 |
+
and diagnose imports that would cause a circular dependency.
|
| 107 |
+
-pack
|
| 108 |
+
Write a package (archive) file rather than an object file
|
| 109 |
+
-race
|
| 110 |
+
Compile with race detector enabled.
|
| 111 |
+
-s
|
| 112 |
+
Warn about composite literals that can be simplified.
|
| 113 |
+
-shared
|
| 114 |
+
Generate code that can be linked into a shared library.
|
| 115 |
+
-spectre list
|
| 116 |
+
Enable spectre mitigations in list (all, index, ret).
|
| 117 |
+
-traceprofile file
|
| 118 |
+
Write an execution trace to file.
|
| 119 |
+
-trimpath prefix
|
| 120 |
+
Remove prefix from recorded source file paths.
|
| 121 |
+
|
| 122 |
+
Flags related to debugging information:
|
| 123 |
+
|
| 124 |
+
-dwarf
|
| 125 |
+
Generate DWARF symbols.
|
| 126 |
+
-dwarflocationlists
|
| 127 |
+
Add location lists to DWARF in optimized mode.
|
| 128 |
+
-gendwarfinl int
|
| 129 |
+
Generate DWARF inline info records (default 2).
|
| 130 |
+
|
| 131 |
+
Flags to debug the compiler itself:
|
| 132 |
+
|
| 133 |
+
-E
|
| 134 |
+
Debug symbol export.
|
| 135 |
+
-K
|
| 136 |
+
Debug missing line numbers.
|
| 137 |
+
-d list
|
| 138 |
+
Print debug information about items in list. Try -d help for further information.
|
| 139 |
+
-live
|
| 140 |
+
Debug liveness analysis.
|
| 141 |
+
-v
|
| 142 |
+
Increase debug verbosity.
|
| 143 |
+
-%
|
| 144 |
+
Debug non-static initializers.
|
| 145 |
+
-W
|
| 146 |
+
Debug parse tree after type checking.
|
| 147 |
+
-f
|
| 148 |
+
Debug stack frames.
|
| 149 |
+
-i
|
| 150 |
+
Debug line number stack.
|
| 151 |
+
-j
|
| 152 |
+
Debug runtime-initialized variables.
|
| 153 |
+
-r
|
| 154 |
+
Debug generated wrappers.
|
| 155 |
+
-w
|
| 156 |
+
Debug type checking.
|
| 157 |
+
|
| 158 |
+
# Compiler Directives
|
| 159 |
+
|
| 160 |
+
The compiler accepts directives in the form of comments.
|
| 161 |
+
Each directive must be placed its own line, with only leading spaces and tabs
|
| 162 |
+
allowed before the comment, and there must be no space between the comment
|
| 163 |
+
opening and the name of the directive, to distinguish it from a regular comment.
|
| 164 |
+
Tools unaware of the directive convention or of a particular
|
| 165 |
+
directive can skip over a directive like any other comment.
|
| 166 |
+
|
| 167 |
+
Other than the line directive, which is a historical special case;
|
| 168 |
+
all other compiler directives are of the form
|
| 169 |
+
//go:name, indicating that they are defined by the Go toolchain.
|
| 170 |
+
*/
|
| 171 |
+
// # Line Directives
|
| 172 |
+
//
|
| 173 |
+
// Line directives come in several forms:
|
| 174 |
+
//
|
| 175 |
+
// //line :line
|
| 176 |
+
// //line :line:col
|
| 177 |
+
// //line filename:line
|
| 178 |
+
// //line filename:line:col
|
| 179 |
+
// /*line :line*/
|
| 180 |
+
// /*line :line:col*/
|
| 181 |
+
// /*line filename:line*/
|
| 182 |
+
// /*line filename:line:col*/
|
| 183 |
+
//
|
| 184 |
+
// In order to be recognized as a line directive, the comment must start with
|
| 185 |
+
// //line or /*line followed by a space, and must contain at least one colon.
|
| 186 |
+
// The //line form must start at the beginning of a line.
|
| 187 |
+
// A line directive specifies the source position for the character immediately following
|
| 188 |
+
// the comment as having come from the specified file, line and column:
|
| 189 |
+
// For a //line comment, this is the first character of the next line, and
|
| 190 |
+
// for a /*line comment this is the character position immediately following the closing */.
|
| 191 |
+
// If no filename is given, the recorded filename is empty if there is also no column number;
|
| 192 |
+
// otherwise it is the most recently recorded filename (actual filename or filename specified
|
| 193 |
+
// by previous line directive).
|
| 194 |
+
// If a line directive doesn't specify a column number, the column is "unknown" until
|
| 195 |
+
// the next directive and the compiler does not report column numbers for that range.
|
| 196 |
+
// The line directive text is interpreted from the back: First the trailing :ddd is peeled
|
| 197 |
+
// off from the directive text if ddd is a valid number > 0. Then the second :ddd
|
| 198 |
+
// is peeled off the same way if it is valid. Anything before that is considered the filename
|
| 199 |
+
// (possibly including blanks and colons). Invalid line or column values are reported as errors.
|
| 200 |
+
//
|
| 201 |
+
// Examples:
|
| 202 |
+
//
|
| 203 |
+
// //line foo.go:10 the filename is foo.go, and the line number is 10 for the next line
|
| 204 |
+
// //line C:foo.go:10 colons are permitted in filenames, here the filename is C:foo.go, and the line is 10
|
| 205 |
+
// //line a:100 :10 blanks are permitted in filenames, here the filename is " a:100 " (excluding quotes)
|
| 206 |
+
// /*line :10:20*/x the position of x is in the current file with line number 10 and column number 20
|
| 207 |
+
// /*line foo: 10 */ this comment is recognized as invalid line directive (extra blanks around line number)
|
| 208 |
+
//
|
| 209 |
+
// Line directives typically appear in machine-generated code, so that compilers and debuggers
|
| 210 |
+
// will report positions in the original input to the generator.
|
| 211 |
+
/*
|
| 212 |
+
# Function Directives
|
| 213 |
+
|
| 214 |
+
A function directive applies to the Go function that immediately follows it.
|
| 215 |
+
|
| 216 |
+
//go:noescape
|
| 217 |
+
|
| 218 |
+
The //go:noescape directive must be followed by a function declaration without
|
| 219 |
+
a body (meaning that the function has an implementation not written in Go).
|
| 220 |
+
It specifies that the function does not allow any of the pointers passed as
|
| 221 |
+
arguments to escape into the heap or into the values returned from the function.
|
| 222 |
+
This information can be used during the compiler's escape analysis of Go code
|
| 223 |
+
calling the function.
|
| 224 |
+
|
| 225 |
+
//go:uintptrescapes
|
| 226 |
+
|
| 227 |
+
The //go:uintptrescapes directive must be followed by a function declaration.
|
| 228 |
+
It specifies that the function's uintptr arguments may be pointer values that
|
| 229 |
+
have been converted to uintptr and must be on the heap and kept alive for the
|
| 230 |
+
duration of the call, even though from the types alone it would appear that the
|
| 231 |
+
object is no longer needed during the call. The conversion from pointer to
|
| 232 |
+
uintptr must appear in the argument list of any call to this function. This
|
| 233 |
+
directive is necessary for some low-level system call implementations and
|
| 234 |
+
should be avoided otherwise.
|
| 235 |
+
|
| 236 |
+
//go:noinline
|
| 237 |
+
|
| 238 |
+
The //go:noinline directive must be followed by a function declaration.
|
| 239 |
+
It specifies that calls to the function should not be inlined, overriding
|
| 240 |
+
the compiler's usual optimization rules. This is typically only needed
|
| 241 |
+
for special runtime functions or when debugging the compiler.
|
| 242 |
+
|
| 243 |
+
//go:norace
|
| 244 |
+
|
| 245 |
+
The //go:norace directive must be followed by a function declaration.
|
| 246 |
+
It specifies that the function's memory accesses must be ignored by the
|
| 247 |
+
race detector. This is most commonly used in low-level code invoked
|
| 248 |
+
at times when it is unsafe to call into the race detector runtime.
|
| 249 |
+
|
| 250 |
+
//go:nosplit
|
| 251 |
+
|
| 252 |
+
The //go:nosplit directive must be followed by a function declaration.
|
| 253 |
+
It specifies that the function must omit its usual stack overflow check.
|
| 254 |
+
This is most commonly used by low-level runtime code invoked
|
| 255 |
+
at times when it is unsafe for the calling goroutine to be preempted.
|
| 256 |
+
Using this directive outside of low-level runtime code is not safe,
|
| 257 |
+
because it permits the nosplit function to overwrite the end of stack,
|
| 258 |
+
leading to memory corruption and arbitrary program failure.
|
| 259 |
+
|
| 260 |
+
# Linkname Directive
|
| 261 |
+
|
| 262 |
+
//go:linkname localname [importpath.name]
|
| 263 |
+
|
| 264 |
+
The //go:linkname directive conventionally precedes the var or func
|
| 265 |
+
declaration named by ``localname``, though its position does not
|
| 266 |
+
change its effect.
|
| 267 |
+
This directive determines the object-file symbol used for a Go var or
|
| 268 |
+
func declaration, allowing two Go symbols to alias the same
|
| 269 |
+
object-file symbol, thereby enabling one package to access a symbol in
|
| 270 |
+
another package even when this would violate the usual encapsulation
|
| 271 |
+
of unexported declarations, or even type safety.
|
| 272 |
+
For that reason, it is only enabled in files that have imported "unsafe".
|
| 273 |
+
|
| 274 |
+
It may be used in two scenarios. Let's assume that package upper
|
| 275 |
+
imports package lower, perhaps indirectly. In the first scenario,
|
| 276 |
+
package lower defines a symbol whose object file name belongs to
|
| 277 |
+
package upper. Both packages contain a linkname directive: package
|
| 278 |
+
lower uses the two-argument form and package upper uses the
|
| 279 |
+
one-argument form. In the example below, lower.f is an alias for the
|
| 280 |
+
function upper.g:
|
| 281 |
+
|
| 282 |
+
package upper
|
| 283 |
+
import _ "unsafe"
|
| 284 |
+
//go:linkname g
|
| 285 |
+
func g()
|
| 286 |
+
|
| 287 |
+
package lower
|
| 288 |
+
import _ "unsafe"
|
| 289 |
+
//go:linkname f upper.g
|
| 290 |
+
func f() { ... }
|
| 291 |
+
|
| 292 |
+
The linkname directive in package upper suppresses the usual error for
|
| 293 |
+
a function that lacks a body. (That check may alternatively be
|
| 294 |
+
suppressed by including a .s file, even an empty one, in the package.)
|
| 295 |
+
|
| 296 |
+
In the second scenario, package upper unilaterally creates an alias
|
| 297 |
+
for a symbol in package lower. In the example below, upper.g is an alias
|
| 298 |
+
for the function lower.f.
|
| 299 |
+
|
| 300 |
+
package upper
|
| 301 |
+
import _ "unsafe"
|
| 302 |
+
//go:linkname g lower.f
|
| 303 |
+
func g()
|
| 304 |
+
|
| 305 |
+
package lower
|
| 306 |
+
func f() { ... }
|
| 307 |
+
|
| 308 |
+
The declaration of lower.f may also have a linkname directive with a
|
| 309 |
+
single argument, f. This is optional, but helps alert the reader that
|
| 310 |
+
the function is accessed from outside the package.
|
| 311 |
+
|
| 312 |
+
# WebAssembly Directives
|
| 313 |
+
|
| 314 |
+
//go:wasmimport importmodule importname
|
| 315 |
+
|
| 316 |
+
The //go:wasmimport directive is wasm-only and must be followed by a
|
| 317 |
+
function declaration with no body.
|
| 318 |
+
It specifies that the function is provided by a wasm module identified
|
| 319 |
+
by ``importmodule'' and ``importname''. For example,
|
| 320 |
+
|
| 321 |
+
//go:wasmimport a_module f
|
| 322 |
+
func g()
|
| 323 |
+
|
| 324 |
+
causes g to refer to the WebAssembly function f from module a_module.
|
| 325 |
+
|
| 326 |
+
//go:wasmexport exportname
|
| 327 |
+
|
| 328 |
+
The //go:wasmexport directive is wasm-only and must be followed by a
|
| 329 |
+
function definition.
|
| 330 |
+
It specifies that the function is exported to the wasm host as ``exportname''.
|
| 331 |
+
For example,
|
| 332 |
+
|
| 333 |
+
//go:wasmexport h
|
| 334 |
+
func hWasm() { ... }
|
| 335 |
+
|
| 336 |
+
make Go function hWasm available outside this WebAssembly module as h.
|
| 337 |
+
|
| 338 |
+
For both go:wasmimport and go:wasmexport,
|
| 339 |
+
the types of parameters and return values to the Go function are translated to
|
| 340 |
+
Wasm according to the following table:
|
| 341 |
+
|
| 342 |
+
Go types Wasm types
|
| 343 |
+
bool i32
|
| 344 |
+
int32, uint32 i32
|
| 345 |
+
int64, uint64 i64
|
| 346 |
+
float32 f32
|
| 347 |
+
float64 f64
|
| 348 |
+
unsafe.Pointer i32
|
| 349 |
+
pointer i32 (more restrictions below)
|
| 350 |
+
string (i32, i32) (only permitted as a parameters, not a result)
|
| 351 |
+
|
| 352 |
+
Any other parameter types are disallowed by the compiler.
|
| 353 |
+
|
| 354 |
+
For a pointer type, its element type must be a bool, int8, uint8, int16, uint16,
|
| 355 |
+
int32, uint32, int64, uint64, float32, float64, an array whose element type is
|
| 356 |
+
a permitted pointer element type, or a struct, which, if non-empty, embeds
|
| 357 |
+
[structs.HostLayout], and contains only fields whose types are permitted pointer
|
| 358 |
+
element types.
|
| 359 |
+
*/
|
| 360 |
+
package main
|
go/src/cmd/compile/main.go
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Copyright 2015 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 |
+
package main
|
| 6 |
+
|
| 7 |
+
import (
|
| 8 |
+
"cmd/compile/internal/amd64"
|
| 9 |
+
"cmd/compile/internal/arm"
|
| 10 |
+
"cmd/compile/internal/arm64"
|
| 11 |
+
"cmd/compile/internal/base"
|
| 12 |
+
"cmd/compile/internal/gc"
|
| 13 |
+
"cmd/compile/internal/loong64"
|
| 14 |
+
"cmd/compile/internal/mips"
|
| 15 |
+
"cmd/compile/internal/mips64"
|
| 16 |
+
"cmd/compile/internal/ppc64"
|
| 17 |
+
"cmd/compile/internal/riscv64"
|
| 18 |
+
"cmd/compile/internal/s390x"
|
| 19 |
+
"cmd/compile/internal/ssagen"
|
| 20 |
+
"cmd/compile/internal/wasm"
|
| 21 |
+
"cmd/compile/internal/x86"
|
| 22 |
+
"fmt"
|
| 23 |
+
"internal/buildcfg"
|
| 24 |
+
"log"
|
| 25 |
+
"os"
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
var archInits = map[string]func(*ssagen.ArchInfo){
|
| 29 |
+
"386": x86.Init,
|
| 30 |
+
"amd64": amd64.Init,
|
| 31 |
+
"arm": arm.Init,
|
| 32 |
+
"arm64": arm64.Init,
|
| 33 |
+
"loong64": loong64.Init,
|
| 34 |
+
"mips": mips.Init,
|
| 35 |
+
"mipsle": mips.Init,
|
| 36 |
+
"mips64": mips64.Init,
|
| 37 |
+
"mips64le": mips64.Init,
|
| 38 |
+
"ppc64": ppc64.Init,
|
| 39 |
+
"ppc64le": ppc64.Init,
|
| 40 |
+
"riscv64": riscv64.Init,
|
| 41 |
+
"s390x": s390x.Init,
|
| 42 |
+
"wasm": wasm.Init,
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
func main() {
|
| 46 |
+
// disable timestamps for reproducible output
|
| 47 |
+
log.SetFlags(0)
|
| 48 |
+
log.SetPrefix("compile: ")
|
| 49 |
+
|
| 50 |
+
buildcfg.Check()
|
| 51 |
+
archInit, ok := archInits[buildcfg.GOARCH]
|
| 52 |
+
if !ok {
|
| 53 |
+
fmt.Fprintf(os.Stderr, "compile: unknown architecture %q\n", buildcfg.GOARCH)
|
| 54 |
+
os.Exit(2)
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
gc.Main(archInit)
|
| 58 |
+
base.Exit(0)
|
| 59 |
+
}
|
go/src/cmd/compile/profile.sh
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023 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 script collects a CPU profile of the compiler
|
| 6 |
+
# for building all targets in std and cmd, and puts
|
| 7 |
+
# the profile at cmd/compile/default.pgo.
|
| 8 |
+
|
| 9 |
+
dir=$(mktemp -d)
|
| 10 |
+
cd $dir
|
| 11 |
+
seed=$(date)
|
| 12 |
+
|
| 13 |
+
for p in $(go list std cmd); do
|
| 14 |
+
h=$(echo $seed $p | md5sum | cut -d ' ' -f 1)
|
| 15 |
+
echo $p $h
|
| 16 |
+
go build -o /dev/null -gcflags=-cpuprofile=$PWD/prof.$h $p
|
| 17 |
+
done
|
| 18 |
+
|
| 19 |
+
go tool pprof -proto prof.* > $(go env GOROOT)/src/cmd/compile/default.pgo
|
| 20 |
+
|
| 21 |
+
rm -r $dir
|
go/src/cmd/compile/script_test.go
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Copyright 2024 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 |
+
package main
|
| 6 |
+
|
| 7 |
+
import (
|
| 8 |
+
"cmd/internal/script/scripttest"
|
| 9 |
+
"flag"
|
| 10 |
+
"internal/testenv"
|
| 11 |
+
"os"
|
| 12 |
+
"runtime"
|
| 13 |
+
"testing"
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
//go:generate go test cmd/compile -v -run=TestScript/README --fixreadme
|
| 17 |
+
|
| 18 |
+
var fixReadme = flag.Bool("fixreadme", false, "if true, update README for script tests")
|
| 19 |
+
|
| 20 |
+
var testCompiler string
|
| 21 |
+
|
| 22 |
+
// TestMain allows this test binary to run as the compiler
|
| 23 |
+
// itself, which is helpful for running script tests.
|
| 24 |
+
// If COMPILE_TEST_EXEC_COMPILE is set, we treat the run
|
| 25 |
+
// as a 'go tool compile' invocation, otherwise behave
|
| 26 |
+
// as a normal test binary.
|
| 27 |
+
func TestMain(m *testing.M) {
|
| 28 |
+
// Are we being asked to run as the compiler?
|
| 29 |
+
// If so then kick off main.
|
| 30 |
+
if os.Getenv("COMPILE_TEST_EXEC_COMPILE") != "" {
|
| 31 |
+
main()
|
| 32 |
+
os.Exit(0)
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
if testExe, err := os.Executable(); err == nil {
|
| 36 |
+
// on wasm, some phones, we expect an error from os.Executable()
|
| 37 |
+
testCompiler = testExe
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
// Regular run, just execute tests.
|
| 41 |
+
os.Exit(m.Run())
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
func TestScript(t *testing.T) {
|
| 45 |
+
testenv.MustHaveGoBuild(t)
|
| 46 |
+
doReplacement := true
|
| 47 |
+
switch runtime.GOOS {
|
| 48 |
+
case "wasip1", "js":
|
| 49 |
+
// wasm doesn't support os.Executable, so we'll skip replacing
|
| 50 |
+
// the installed linker with our test binary.
|
| 51 |
+
doReplacement = false
|
| 52 |
+
}
|
| 53 |
+
repls := []scripttest.ToolReplacement{}
|
| 54 |
+
if doReplacement {
|
| 55 |
+
if testCompiler == "" {
|
| 56 |
+
t.Fatalf("testCompiler not set, can't replace")
|
| 57 |
+
}
|
| 58 |
+
repls = []scripttest.ToolReplacement{
|
| 59 |
+
scripttest.ToolReplacement{
|
| 60 |
+
ToolName: "compile",
|
| 61 |
+
ReplacementPath: testCompiler,
|
| 62 |
+
EnvVar: "COMPILE_TEST_EXEC_COMPILE=1",
|
| 63 |
+
},
|
| 64 |
+
}
|
| 65 |
+
}
|
| 66 |
+
scripttest.RunToolScriptTest(t, repls, "testdata/script", *fixReadme)
|
| 67 |
+
}
|
go/src/cmd/covdata/argsmerge.go
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
package main
|
| 6 |
+
|
| 7 |
+
import (
|
| 8 |
+
"fmt"
|
| 9 |
+
"slices"
|
| 10 |
+
"strconv"
|
| 11 |
+
)
|
| 12 |
+
|
| 13 |
+
type argvalues struct {
|
| 14 |
+
osargs []string
|
| 15 |
+
goos string
|
| 16 |
+
goarch string
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
type argstate struct {
|
| 20 |
+
state argvalues
|
| 21 |
+
initialized bool
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
func (a *argstate) Merge(state argvalues) {
|
| 25 |
+
if !a.initialized {
|
| 26 |
+
a.state = state
|
| 27 |
+
a.initialized = true
|
| 28 |
+
return
|
| 29 |
+
}
|
| 30 |
+
if !slices.Equal(a.state.osargs, state.osargs) {
|
| 31 |
+
a.state.osargs = nil
|
| 32 |
+
}
|
| 33 |
+
if state.goos != a.state.goos {
|
| 34 |
+
a.state.goos = ""
|
| 35 |
+
}
|
| 36 |
+
if state.goarch != a.state.goarch {
|
| 37 |
+
a.state.goarch = ""
|
| 38 |
+
}
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
func (a *argstate) ArgsSummary() map[string]string {
|
| 42 |
+
m := make(map[string]string)
|
| 43 |
+
if len(a.state.osargs) != 0 {
|
| 44 |
+
m["argc"] = strconv.Itoa(len(a.state.osargs))
|
| 45 |
+
for k, a := range a.state.osargs {
|
| 46 |
+
m[fmt.Sprintf("argv%d", k)] = a
|
| 47 |
+
}
|
| 48 |
+
}
|
| 49 |
+
if a.state.goos != "" {
|
| 50 |
+
m["GOOS"] = a.state.goos
|
| 51 |
+
}
|
| 52 |
+
if a.state.goarch != "" {
|
| 53 |
+
m["GOARCH"] = a.state.goarch
|
| 54 |
+
}
|
| 55 |
+
return m
|
| 56 |
+
}
|
go/src/cmd/covdata/covdata.go
ADDED
|
@@ -0,0 +1,237 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
package main
|
| 6 |
+
|
| 7 |
+
import (
|
| 8 |
+
"cmd/internal/cov"
|
| 9 |
+
"cmd/internal/pkgpattern"
|
| 10 |
+
"cmd/internal/telemetry/counter"
|
| 11 |
+
"flag"
|
| 12 |
+
"fmt"
|
| 13 |
+
"os"
|
| 14 |
+
"runtime"
|
| 15 |
+
"runtime/pprof"
|
| 16 |
+
"strings"
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
var verbflag = flag.Int("v", 0, "Verbose trace output level")
|
| 20 |
+
var hflag = flag.Bool("h", false, "Panic on fatal errors (for stack trace)")
|
| 21 |
+
var hwflag = flag.Bool("hw", false, "Panic on warnings (for stack trace)")
|
| 22 |
+
var indirsflag = flag.String("i", "", "Input dirs to examine (comma separated)")
|
| 23 |
+
var pkgpatflag = flag.String("pkg", "", "Restrict output to package(s) matching specified package pattern.")
|
| 24 |
+
var cpuprofileflag = flag.String("cpuprofile", "", "Write CPU profile to specified file")
|
| 25 |
+
var memprofileflag = flag.String("memprofile", "", "Write memory profile to specified file")
|
| 26 |
+
var memprofilerateflag = flag.Int("memprofilerate", 0, "Set memprofile sampling rate to value")
|
| 27 |
+
|
| 28 |
+
var matchpkg func(name string) bool
|
| 29 |
+
|
| 30 |
+
var atExitFuncs []func()
|
| 31 |
+
|
| 32 |
+
func atExit(f func()) {
|
| 33 |
+
atExitFuncs = append(atExitFuncs, f)
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
func Exit(code int) {
|
| 37 |
+
for i := len(atExitFuncs) - 1; i >= 0; i-- {
|
| 38 |
+
f := atExitFuncs[i]
|
| 39 |
+
atExitFuncs = atExitFuncs[:i]
|
| 40 |
+
f()
|
| 41 |
+
}
|
| 42 |
+
os.Exit(code)
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
func dbgtrace(vlevel int, s string, a ...any) {
|
| 46 |
+
if *verbflag >= vlevel {
|
| 47 |
+
fmt.Printf(s, a...)
|
| 48 |
+
fmt.Printf("\n")
|
| 49 |
+
}
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
func warn(s string, a ...any) {
|
| 53 |
+
fmt.Fprintf(os.Stderr, "warning: ")
|
| 54 |
+
fmt.Fprintf(os.Stderr, s, a...)
|
| 55 |
+
fmt.Fprintf(os.Stderr, "\n")
|
| 56 |
+
if *hwflag {
|
| 57 |
+
panic("unexpected warning")
|
| 58 |
+
}
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
func fatal(s string, a ...any) {
|
| 62 |
+
fmt.Fprintf(os.Stderr, "error: ")
|
| 63 |
+
fmt.Fprintf(os.Stderr, s, a...)
|
| 64 |
+
fmt.Fprintf(os.Stderr, "\n")
|
| 65 |
+
if *hflag {
|
| 66 |
+
panic("fatal error")
|
| 67 |
+
}
|
| 68 |
+
Exit(1)
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
func usage(msg string) {
|
| 72 |
+
if len(msg) > 0 {
|
| 73 |
+
fmt.Fprintf(os.Stderr, "error: %s\n", msg)
|
| 74 |
+
}
|
| 75 |
+
fmt.Fprintf(os.Stderr, "usage: go tool covdata [command]\n")
|
| 76 |
+
fmt.Fprintf(os.Stderr, `
|
| 77 |
+
Commands are:
|
| 78 |
+
|
| 79 |
+
textfmt convert coverage data to textual format
|
| 80 |
+
percent output total percentage of statements covered
|
| 81 |
+
pkglist output list of package import paths
|
| 82 |
+
func output coverage profile information for each function
|
| 83 |
+
merge merge data files together
|
| 84 |
+
subtract subtract one set of data files from another set
|
| 85 |
+
intersect generate intersection of two sets of data files
|
| 86 |
+
debugdump dump data in human-readable format for debugging purposes
|
| 87 |
+
`)
|
| 88 |
+
fmt.Fprintf(os.Stderr, "\nFor help on a specific subcommand, try:\n")
|
| 89 |
+
fmt.Fprintf(os.Stderr, "\ngo tool covdata <cmd> -help\n")
|
| 90 |
+
Exit(2)
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
type covOperation interface {
|
| 94 |
+
cov.CovDataVisitor
|
| 95 |
+
Setup()
|
| 96 |
+
Usage(string)
|
| 97 |
+
}
|
| 98 |
+
|
| 99 |
+
// Modes of operation.
|
| 100 |
+
const (
|
| 101 |
+
funcMode = "func"
|
| 102 |
+
mergeMode = "merge"
|
| 103 |
+
intersectMode = "intersect"
|
| 104 |
+
subtractMode = "subtract"
|
| 105 |
+
percentMode = "percent"
|
| 106 |
+
pkglistMode = "pkglist"
|
| 107 |
+
textfmtMode = "textfmt"
|
| 108 |
+
debugDumpMode = "debugdump"
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
func main() {
|
| 112 |
+
counter.Open()
|
| 113 |
+
|
| 114 |
+
// First argument should be mode/subcommand.
|
| 115 |
+
if len(os.Args) < 2 {
|
| 116 |
+
usage("missing command selector")
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
// Select mode
|
| 120 |
+
var op covOperation
|
| 121 |
+
cmd := os.Args[1]
|
| 122 |
+
switch cmd {
|
| 123 |
+
case mergeMode:
|
| 124 |
+
op = makeMergeOp()
|
| 125 |
+
case debugDumpMode:
|
| 126 |
+
op = makeDumpOp(debugDumpMode)
|
| 127 |
+
case textfmtMode:
|
| 128 |
+
op = makeDumpOp(textfmtMode)
|
| 129 |
+
case percentMode:
|
| 130 |
+
op = makeDumpOp(percentMode)
|
| 131 |
+
case funcMode:
|
| 132 |
+
op = makeDumpOp(funcMode)
|
| 133 |
+
case pkglistMode:
|
| 134 |
+
op = makeDumpOp(pkglistMode)
|
| 135 |
+
case subtractMode:
|
| 136 |
+
op = makeSubtractIntersectOp(subtractMode)
|
| 137 |
+
case intersectMode:
|
| 138 |
+
op = makeSubtractIntersectOp(intersectMode)
|
| 139 |
+
default:
|
| 140 |
+
usage(fmt.Sprintf("unknown command selector %q", cmd))
|
| 141 |
+
}
|
| 142 |
+
|
| 143 |
+
// Edit out command selector, then parse flags.
|
| 144 |
+
os.Args = append(os.Args[:1], os.Args[2:]...)
|
| 145 |
+
flag.Usage = func() {
|
| 146 |
+
op.Usage("")
|
| 147 |
+
}
|
| 148 |
+
flag.Parse()
|
| 149 |
+
counter.Inc("covdata/invocations")
|
| 150 |
+
counter.CountFlags("covdata/flag:", *flag.CommandLine)
|
| 151 |
+
|
| 152 |
+
// Mode-independent flag setup
|
| 153 |
+
dbgtrace(1, "starting mode-independent setup")
|
| 154 |
+
if flag.NArg() != 0 {
|
| 155 |
+
op.Usage("unknown extra arguments")
|
| 156 |
+
}
|
| 157 |
+
if *pkgpatflag != "" {
|
| 158 |
+
pats := strings.Split(*pkgpatflag, ",")
|
| 159 |
+
matchers := []func(name string) bool{}
|
| 160 |
+
for _, p := range pats {
|
| 161 |
+
if p == "" {
|
| 162 |
+
continue
|
| 163 |
+
}
|
| 164 |
+
f := pkgpattern.MatchSimplePattern(p)
|
| 165 |
+
matchers = append(matchers, f)
|
| 166 |
+
}
|
| 167 |
+
matchpkg = func(name string) bool {
|
| 168 |
+
for _, f := range matchers {
|
| 169 |
+
if f(name) {
|
| 170 |
+
return true
|
| 171 |
+
}
|
| 172 |
+
}
|
| 173 |
+
return false
|
| 174 |
+
}
|
| 175 |
+
}
|
| 176 |
+
if *cpuprofileflag != "" {
|
| 177 |
+
f, err := os.Create(*cpuprofileflag)
|
| 178 |
+
if err != nil {
|
| 179 |
+
fatal("%v", err)
|
| 180 |
+
}
|
| 181 |
+
if err := pprof.StartCPUProfile(f); err != nil {
|
| 182 |
+
fatal("%v", err)
|
| 183 |
+
}
|
| 184 |
+
atExit(func() {
|
| 185 |
+
pprof.StopCPUProfile()
|
| 186 |
+
if err = f.Close(); err != nil {
|
| 187 |
+
fatal("error closing cpu profile: %v", err)
|
| 188 |
+
}
|
| 189 |
+
})
|
| 190 |
+
}
|
| 191 |
+
if *memprofileflag != "" {
|
| 192 |
+
if *memprofilerateflag != 0 {
|
| 193 |
+
runtime.MemProfileRate = *memprofilerateflag
|
| 194 |
+
}
|
| 195 |
+
f, err := os.Create(*memprofileflag)
|
| 196 |
+
if err != nil {
|
| 197 |
+
fatal("%v", err)
|
| 198 |
+
}
|
| 199 |
+
atExit(func() {
|
| 200 |
+
runtime.GC()
|
| 201 |
+
const writeLegacyFormat = 1
|
| 202 |
+
if err := pprof.Lookup("heap").WriteTo(f, writeLegacyFormat); err != nil {
|
| 203 |
+
fatal("%v", err)
|
| 204 |
+
}
|
| 205 |
+
if err = f.Close(); err != nil {
|
| 206 |
+
fatal("error closing memory profile: %v", err)
|
| 207 |
+
}
|
| 208 |
+
})
|
| 209 |
+
} else {
|
| 210 |
+
// Not doing memory profiling; disable it entirely.
|
| 211 |
+
runtime.MemProfileRate = 0
|
| 212 |
+
}
|
| 213 |
+
|
| 214 |
+
// Mode-dependent setup.
|
| 215 |
+
op.Setup()
|
| 216 |
+
|
| 217 |
+
// ... off and running now.
|
| 218 |
+
dbgtrace(1, "starting perform")
|
| 219 |
+
|
| 220 |
+
indirs := strings.Split(*indirsflag, ",")
|
| 221 |
+
vis := cov.CovDataVisitor(op)
|
| 222 |
+
var flags cov.CovDataReaderFlags
|
| 223 |
+
if *hflag {
|
| 224 |
+
flags |= cov.PanicOnError
|
| 225 |
+
}
|
| 226 |
+
if *hwflag {
|
| 227 |
+
flags |= cov.PanicOnWarning
|
| 228 |
+
}
|
| 229 |
+
reader := cov.MakeCovDataReader(vis, indirs, *verbflag, flags, matchpkg)
|
| 230 |
+
st := 0
|
| 231 |
+
if err := reader.Visit(); err != nil {
|
| 232 |
+
fmt.Fprintf(os.Stderr, "error: %v\n", err)
|
| 233 |
+
st = 1
|
| 234 |
+
}
|
| 235 |
+
dbgtrace(1, "leaving main")
|
| 236 |
+
Exit(st)
|
| 237 |
+
}
|
go/src/cmd/covdata/doc.go
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
/*
|
| 6 |
+
Covdata is a program for manipulating and generating reports
|
| 7 |
+
from 2nd-generation coverage testing output files, those produced
|
| 8 |
+
from running applications or integration tests. E.g.
|
| 9 |
+
|
| 10 |
+
$ mkdir ./profiledir
|
| 11 |
+
$ go build -cover -o myapp.exe .
|
| 12 |
+
$ GOCOVERDIR=./profiledir ./myapp.exe <arguments>
|
| 13 |
+
$ ls ./profiledir
|
| 14 |
+
covcounters.cce1b350af34b6d0fb59cc1725f0ee27.821598.1663006712821344241
|
| 15 |
+
covmeta.cce1b350af34b6d0fb59cc1725f0ee27
|
| 16 |
+
$
|
| 17 |
+
|
| 18 |
+
Run covdata via "go tool covdata <mode>", where 'mode' is a subcommand
|
| 19 |
+
selecting a specific reporting, merging, or data manipulation operation.
|
| 20 |
+
Descriptions on the various modes (run "go tool cover <mode> -help" for
|
| 21 |
+
specifics on usage of a given mode):
|
| 22 |
+
|
| 23 |
+
1. Report percent of statements covered in each profiled package
|
| 24 |
+
|
| 25 |
+
$ go tool covdata percent -i=profiledir
|
| 26 |
+
cov-example/p coverage: 41.1% of statements
|
| 27 |
+
main coverage: 87.5% of statements
|
| 28 |
+
$
|
| 29 |
+
|
| 30 |
+
2. Report import paths of packages profiled
|
| 31 |
+
|
| 32 |
+
$ go tool covdata pkglist -i=profiledir
|
| 33 |
+
cov-example/p
|
| 34 |
+
main
|
| 35 |
+
$
|
| 36 |
+
|
| 37 |
+
3. Report percent statements covered by function:
|
| 38 |
+
|
| 39 |
+
$ go tool covdata func -i=profiledir
|
| 40 |
+
cov-example/p/p.go:12: emptyFn 0.0%
|
| 41 |
+
cov-example/p/p.go:32: Small 100.0%
|
| 42 |
+
cov-example/p/p.go:47: Medium 90.9%
|
| 43 |
+
...
|
| 44 |
+
$
|
| 45 |
+
|
| 46 |
+
4. Convert coverage data to legacy textual format:
|
| 47 |
+
|
| 48 |
+
$ go tool covdata textfmt -i=profiledir -o=cov.txt
|
| 49 |
+
$ head cov.txt
|
| 50 |
+
mode: set
|
| 51 |
+
cov-example/p/p.go:12.22,13.2 0 0
|
| 52 |
+
cov-example/p/p.go:15.31,16.2 1 0
|
| 53 |
+
cov-example/p/p.go:16.3,18.3 0 0
|
| 54 |
+
cov-example/p/p.go:19.3,21.3 0 0
|
| 55 |
+
...
|
| 56 |
+
$ go tool cover -html=cov.txt
|
| 57 |
+
$
|
| 58 |
+
|
| 59 |
+
5. Merge profiles together:
|
| 60 |
+
|
| 61 |
+
$ go tool covdata merge -i=indir1,indir2 -o=outdir -modpaths=github.com/go-delve/delve
|
| 62 |
+
$
|
| 63 |
+
|
| 64 |
+
6. Subtract one profile from another
|
| 65 |
+
|
| 66 |
+
$ go tool covdata subtract -i=indir1,indir2 -o=outdir
|
| 67 |
+
$
|
| 68 |
+
|
| 69 |
+
7. Intersect profiles
|
| 70 |
+
|
| 71 |
+
$ go tool covdata intersect -i=indir1,indir2 -o=outdir
|
| 72 |
+
$
|
| 73 |
+
|
| 74 |
+
8. Dump a profile for debugging purposes.
|
| 75 |
+
|
| 76 |
+
$ go tool covdata debugdump -i=indir
|
| 77 |
+
<human readable output>
|
| 78 |
+
$
|
| 79 |
+
*/
|
| 80 |
+
package main
|
go/src/cmd/covdata/dump.go
ADDED
|
@@ -0,0 +1,357 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
package main
|
| 6 |
+
|
| 7 |
+
// This file contains functions and apis to support the "go tool
|
| 8 |
+
// covdata" sub-commands that relate to dumping text format summaries
|
| 9 |
+
// and reports: "pkglist", "func", "debugdump", "percent", and
|
| 10 |
+
// "textfmt".
|
| 11 |
+
|
| 12 |
+
import (
|
| 13 |
+
"flag"
|
| 14 |
+
"fmt"
|
| 15 |
+
"internal/coverage"
|
| 16 |
+
"internal/coverage/calloc"
|
| 17 |
+
"internal/coverage/cformat"
|
| 18 |
+
"internal/coverage/cmerge"
|
| 19 |
+
"internal/coverage/decodecounter"
|
| 20 |
+
"internal/coverage/decodemeta"
|
| 21 |
+
"internal/coverage/pods"
|
| 22 |
+
"os"
|
| 23 |
+
"sort"
|
| 24 |
+
"strings"
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
var textfmtoutflag *string
|
| 28 |
+
var liveflag *bool
|
| 29 |
+
|
| 30 |
+
func makeDumpOp(cmd string) covOperation {
|
| 31 |
+
if cmd == textfmtMode || cmd == percentMode {
|
| 32 |
+
textfmtoutflag = flag.String("o", "", "Output text format to file")
|
| 33 |
+
}
|
| 34 |
+
if cmd == debugDumpMode {
|
| 35 |
+
liveflag = flag.Bool("live", false, "Select only live (executed) functions for dump output.")
|
| 36 |
+
}
|
| 37 |
+
d := &dstate{
|
| 38 |
+
cmd: cmd,
|
| 39 |
+
cm: &cmerge.Merger{},
|
| 40 |
+
}
|
| 41 |
+
// For these modes (percent, pkglist, func, etc), use a relaxed
|
| 42 |
+
// policy when it comes to counter mode clashes. For a percent
|
| 43 |
+
// report, for example, we only care whether a given line is
|
| 44 |
+
// executed at least once, so it's ok to (effectively) merge
|
| 45 |
+
// together runs derived from different counter modes.
|
| 46 |
+
if d.cmd == percentMode || d.cmd == funcMode || d.cmd == pkglistMode {
|
| 47 |
+
d.cm.SetModeMergePolicy(cmerge.ModeMergeRelaxed)
|
| 48 |
+
}
|
| 49 |
+
if d.cmd == pkglistMode {
|
| 50 |
+
d.pkgpaths = make(map[string]struct{})
|
| 51 |
+
}
|
| 52 |
+
return d
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
// dstate encapsulates state and provides methods for implementing
|
| 56 |
+
// various dump operations. Specifically, dstate implements the
|
| 57 |
+
// CovDataVisitor interface, and is designed to be used in
|
| 58 |
+
// concert with the CovDataReader utility, which abstracts away most
|
| 59 |
+
// of the grubby details of reading coverage data files.
|
| 60 |
+
type dstate struct {
|
| 61 |
+
// for batch allocation of counter arrays
|
| 62 |
+
calloc.BatchCounterAlloc
|
| 63 |
+
|
| 64 |
+
// counter merging state + methods
|
| 65 |
+
cm *cmerge.Merger
|
| 66 |
+
|
| 67 |
+
// counter data formatting helper
|
| 68 |
+
format *cformat.Formatter
|
| 69 |
+
|
| 70 |
+
// 'mm' stores values read from a counter data file; the pkfunc key
|
| 71 |
+
// is a pkgid/funcid pair that uniquely identifies a function in
|
| 72 |
+
// instrumented application.
|
| 73 |
+
mm map[pkfunc]decodecounter.FuncPayload
|
| 74 |
+
|
| 75 |
+
// pkm maps package ID to the number of functions in the package
|
| 76 |
+
// with that ID. It is used to report inconsistencies in counter
|
| 77 |
+
// data (for example, a counter data entry with pkgid=N funcid=10
|
| 78 |
+
// where package N only has 3 functions).
|
| 79 |
+
pkm map[uint32]uint32
|
| 80 |
+
|
| 81 |
+
// pkgpaths records all package import paths encountered while
|
| 82 |
+
// visiting coverage data files (used to implement the "pkglist"
|
| 83 |
+
// subcommand).
|
| 84 |
+
pkgpaths map[string]struct{}
|
| 85 |
+
|
| 86 |
+
// Current package name and import path.
|
| 87 |
+
pkgName string
|
| 88 |
+
pkgImportPath string
|
| 89 |
+
|
| 90 |
+
// Module path for current package (may be empty).
|
| 91 |
+
modulePath string
|
| 92 |
+
|
| 93 |
+
// Dump subcommand (ex: "textfmt", "debugdump", etc).
|
| 94 |
+
cmd string
|
| 95 |
+
|
| 96 |
+
// File to which we will write text format output, if enabled.
|
| 97 |
+
textfmtoutf *os.File
|
| 98 |
+
|
| 99 |
+
// Total and covered statements (used by "debugdump" subcommand).
|
| 100 |
+
totalStmts, coveredStmts int
|
| 101 |
+
|
| 102 |
+
// Records whether preamble has been emitted for current pkg
|
| 103 |
+
// (used when in "debugdump" mode)
|
| 104 |
+
preambleEmitted bool
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
func (d *dstate) Usage(msg string) {
|
| 108 |
+
if len(msg) > 0 {
|
| 109 |
+
fmt.Fprintf(os.Stderr, "error: %s\n", msg)
|
| 110 |
+
}
|
| 111 |
+
fmt.Fprintf(os.Stderr, "usage: go tool covdata %s -i=<directories>\n\n", d.cmd)
|
| 112 |
+
flag.PrintDefaults()
|
| 113 |
+
fmt.Fprintf(os.Stderr, "\nExamples:\n\n")
|
| 114 |
+
switch d.cmd {
|
| 115 |
+
case pkglistMode:
|
| 116 |
+
fmt.Fprintf(os.Stderr, " go tool covdata pkglist -i=dir1,dir2\n\n")
|
| 117 |
+
fmt.Fprintf(os.Stderr, " \treads coverage data files from dir1+dirs2\n")
|
| 118 |
+
fmt.Fprintf(os.Stderr, " \tand writes out a list of the import paths\n")
|
| 119 |
+
fmt.Fprintf(os.Stderr, " \tof all compiled packages.\n")
|
| 120 |
+
case textfmtMode:
|
| 121 |
+
fmt.Fprintf(os.Stderr, " go tool covdata textfmt -i=dir1,dir2 -o=out.txt\n\n")
|
| 122 |
+
fmt.Fprintf(os.Stderr, " \tmerges data from input directories dir1+dir2\n")
|
| 123 |
+
fmt.Fprintf(os.Stderr, " \tand emits text format into file 'out.txt'\n")
|
| 124 |
+
case percentMode:
|
| 125 |
+
fmt.Fprintf(os.Stderr, " go tool covdata percent -i=dir1,dir2\n\n")
|
| 126 |
+
fmt.Fprintf(os.Stderr, " \tmerges data from input directories dir1+dir2\n")
|
| 127 |
+
fmt.Fprintf(os.Stderr, " \tand emits percentage of statements covered\n\n")
|
| 128 |
+
case funcMode:
|
| 129 |
+
fmt.Fprintf(os.Stderr, " go tool covdata func -i=dir1,dir2\n\n")
|
| 130 |
+
fmt.Fprintf(os.Stderr, " \treads coverage data files from dir1+dirs2\n")
|
| 131 |
+
fmt.Fprintf(os.Stderr, " \tand writes out coverage profile data for\n")
|
| 132 |
+
fmt.Fprintf(os.Stderr, " \teach function.\n")
|
| 133 |
+
case debugDumpMode:
|
| 134 |
+
fmt.Fprintf(os.Stderr, " go tool covdata debugdump [flags] -i=dir1,dir2\n\n")
|
| 135 |
+
fmt.Fprintf(os.Stderr, " \treads coverage data from dir1+dir2 and dumps\n")
|
| 136 |
+
fmt.Fprintf(os.Stderr, " \tcontents in human-readable form to stdout, for\n")
|
| 137 |
+
fmt.Fprintf(os.Stderr, " \tdebugging purposes.\n")
|
| 138 |
+
default:
|
| 139 |
+
panic("unexpected")
|
| 140 |
+
}
|
| 141 |
+
Exit(2)
|
| 142 |
+
}
|
| 143 |
+
|
| 144 |
+
// Setup is called once at program startup time to vet flag values
|
| 145 |
+
// and do any necessary setup operations.
|
| 146 |
+
func (d *dstate) Setup() {
|
| 147 |
+
if *indirsflag == "" {
|
| 148 |
+
d.Usage("select input directories with '-i' option")
|
| 149 |
+
}
|
| 150 |
+
if d.cmd == textfmtMode || (d.cmd == percentMode && *textfmtoutflag != "") {
|
| 151 |
+
if *textfmtoutflag == "" {
|
| 152 |
+
d.Usage("select output file name with '-o' option")
|
| 153 |
+
}
|
| 154 |
+
var err error
|
| 155 |
+
d.textfmtoutf, err = os.Create(*textfmtoutflag)
|
| 156 |
+
if err != nil {
|
| 157 |
+
d.Usage(fmt.Sprintf("unable to open textfmt output file %q: %v", *textfmtoutflag, err))
|
| 158 |
+
}
|
| 159 |
+
}
|
| 160 |
+
if d.cmd == debugDumpMode {
|
| 161 |
+
fmt.Printf("/* WARNING: the format of this dump is not stable and is\n")
|
| 162 |
+
fmt.Printf(" * expected to change from one Go release to the next.\n")
|
| 163 |
+
fmt.Printf(" *\n")
|
| 164 |
+
fmt.Printf(" * produced by:\n")
|
| 165 |
+
args := append([]string{os.Args[0]}, debugDumpMode)
|
| 166 |
+
args = append(args, os.Args[1:]...)
|
| 167 |
+
fmt.Printf(" *\t%s\n", strings.Join(args, " "))
|
| 168 |
+
fmt.Printf(" */\n")
|
| 169 |
+
}
|
| 170 |
+
}
|
| 171 |
+
|
| 172 |
+
func (d *dstate) BeginPod(p pods.Pod) {
|
| 173 |
+
d.mm = make(map[pkfunc]decodecounter.FuncPayload)
|
| 174 |
+
}
|
| 175 |
+
|
| 176 |
+
func (d *dstate) EndPod(p pods.Pod) {
|
| 177 |
+
if d.cmd == debugDumpMode {
|
| 178 |
+
d.cm.ResetModeAndGranularity()
|
| 179 |
+
}
|
| 180 |
+
}
|
| 181 |
+
|
| 182 |
+
func (d *dstate) BeginCounterDataFile(cdf string, cdr *decodecounter.CounterDataReader, dirIdx int) {
|
| 183 |
+
dbgtrace(2, "visit counter data file %s dirIdx %d", cdf, dirIdx)
|
| 184 |
+
if d.cmd == debugDumpMode {
|
| 185 |
+
fmt.Printf("data file %s", cdf)
|
| 186 |
+
if cdr.Goos() != "" {
|
| 187 |
+
fmt.Printf(" GOOS=%s", cdr.Goos())
|
| 188 |
+
}
|
| 189 |
+
if cdr.Goarch() != "" {
|
| 190 |
+
fmt.Printf(" GOARCH=%s", cdr.Goarch())
|
| 191 |
+
}
|
| 192 |
+
if len(cdr.OsArgs()) != 0 {
|
| 193 |
+
fmt.Printf(" program args: %+v\n", cdr.OsArgs())
|
| 194 |
+
}
|
| 195 |
+
fmt.Printf("\n")
|
| 196 |
+
}
|
| 197 |
+
}
|
| 198 |
+
|
| 199 |
+
func (d *dstate) EndCounterDataFile(cdf string, cdr *decodecounter.CounterDataReader, dirIdx int) {
|
| 200 |
+
}
|
| 201 |
+
|
| 202 |
+
func (d *dstate) VisitFuncCounterData(data decodecounter.FuncPayload) {
|
| 203 |
+
if nf, ok := d.pkm[data.PkgIdx]; !ok || data.FuncIdx > nf {
|
| 204 |
+
warn("func payload inconsistency: id [p=%d,f=%d] nf=%d len(ctrs)=%d in VisitFuncCounterData, ignored", data.PkgIdx, data.FuncIdx, nf, len(data.Counters))
|
| 205 |
+
return
|
| 206 |
+
}
|
| 207 |
+
key := pkfunc{pk: data.PkgIdx, fcn: data.FuncIdx}
|
| 208 |
+
val, found := d.mm[key]
|
| 209 |
+
|
| 210 |
+
dbgtrace(5, "ctr visit pk=%d fid=%d found=%v len(val.ctrs)=%d len(data.ctrs)=%d", data.PkgIdx, data.FuncIdx, found, len(val.Counters), len(data.Counters))
|
| 211 |
+
|
| 212 |
+
if len(val.Counters) < len(data.Counters) {
|
| 213 |
+
t := val.Counters
|
| 214 |
+
val.Counters = d.AllocateCounters(len(data.Counters))
|
| 215 |
+
copy(val.Counters, t)
|
| 216 |
+
}
|
| 217 |
+
err, overflow := d.cm.MergeCounters(val.Counters, data.Counters)
|
| 218 |
+
if err != nil {
|
| 219 |
+
fatal("%v", err)
|
| 220 |
+
}
|
| 221 |
+
if overflow {
|
| 222 |
+
warn("uint32 overflow during counter merge")
|
| 223 |
+
}
|
| 224 |
+
d.mm[key] = val
|
| 225 |
+
}
|
| 226 |
+
|
| 227 |
+
func (d *dstate) EndCounters() {
|
| 228 |
+
}
|
| 229 |
+
|
| 230 |
+
func (d *dstate) VisitMetaDataFile(mdf string, mfr *decodemeta.CoverageMetaFileReader) {
|
| 231 |
+
newgran := mfr.CounterGranularity()
|
| 232 |
+
newmode := mfr.CounterMode()
|
| 233 |
+
if err := d.cm.SetModeAndGranularity(mdf, newmode, newgran); err != nil {
|
| 234 |
+
fatal("%v", err)
|
| 235 |
+
}
|
| 236 |
+
if d.cmd == debugDumpMode {
|
| 237 |
+
fmt.Printf("Cover mode: %s\n", newmode.String())
|
| 238 |
+
fmt.Printf("Cover granularity: %s\n", newgran.String())
|
| 239 |
+
}
|
| 240 |
+
if d.format == nil {
|
| 241 |
+
d.format = cformat.NewFormatter(mfr.CounterMode())
|
| 242 |
+
}
|
| 243 |
+
|
| 244 |
+
// To provide an additional layer of checking when reading counter
|
| 245 |
+
// data, walk the meta-data file to determine the set of legal
|
| 246 |
+
// package/function combinations. This will help catch bugs in the
|
| 247 |
+
// counter file reader.
|
| 248 |
+
d.pkm = make(map[uint32]uint32)
|
| 249 |
+
np := uint32(mfr.NumPackages())
|
| 250 |
+
payload := []byte{}
|
| 251 |
+
for pkIdx := uint32(0); pkIdx < np; pkIdx++ {
|
| 252 |
+
var pd *decodemeta.CoverageMetaDataDecoder
|
| 253 |
+
var err error
|
| 254 |
+
pd, payload, err = mfr.GetPackageDecoder(pkIdx, payload)
|
| 255 |
+
if err != nil {
|
| 256 |
+
fatal("reading pkg %d from meta-file %s: %s", pkIdx, mdf, err)
|
| 257 |
+
}
|
| 258 |
+
d.pkm[pkIdx] = pd.NumFuncs()
|
| 259 |
+
}
|
| 260 |
+
}
|
| 261 |
+
|
| 262 |
+
func (d *dstate) BeginPackage(pd *decodemeta.CoverageMetaDataDecoder, pkgIdx uint32) {
|
| 263 |
+
d.preambleEmitted = false
|
| 264 |
+
d.pkgImportPath = pd.PackagePath()
|
| 265 |
+
d.pkgName = pd.PackageName()
|
| 266 |
+
d.modulePath = pd.ModulePath()
|
| 267 |
+
if d.cmd == pkglistMode {
|
| 268 |
+
d.pkgpaths[d.pkgImportPath] = struct{}{}
|
| 269 |
+
}
|
| 270 |
+
d.format.SetPackage(pd.PackagePath())
|
| 271 |
+
}
|
| 272 |
+
|
| 273 |
+
func (d *dstate) EndPackage(pd *decodemeta.CoverageMetaDataDecoder, pkgIdx uint32) {
|
| 274 |
+
}
|
| 275 |
+
|
| 276 |
+
func (d *dstate) VisitFunc(pkgIdx uint32, fnIdx uint32, fd *coverage.FuncDesc) {
|
| 277 |
+
var counters []uint32
|
| 278 |
+
key := pkfunc{pk: pkgIdx, fcn: fnIdx}
|
| 279 |
+
v, haveCounters := d.mm[key]
|
| 280 |
+
|
| 281 |
+
dbgtrace(5, "meta visit pk=%d fid=%d fname=%s file=%s found=%v len(val.ctrs)=%d", pkgIdx, fnIdx, fd.Funcname, fd.Srcfile, haveCounters, len(v.Counters))
|
| 282 |
+
|
| 283 |
+
suppressOutput := false
|
| 284 |
+
if haveCounters {
|
| 285 |
+
counters = v.Counters
|
| 286 |
+
} else if d.cmd == debugDumpMode && *liveflag {
|
| 287 |
+
suppressOutput = true
|
| 288 |
+
}
|
| 289 |
+
|
| 290 |
+
if d.cmd == debugDumpMode && !suppressOutput {
|
| 291 |
+
if !d.preambleEmitted {
|
| 292 |
+
fmt.Printf("\nPackage path: %s\n", d.pkgImportPath)
|
| 293 |
+
fmt.Printf("Package name: %s\n", d.pkgName)
|
| 294 |
+
fmt.Printf("Module path: %s\n", d.modulePath)
|
| 295 |
+
d.preambleEmitted = true
|
| 296 |
+
}
|
| 297 |
+
fmt.Printf("\nFunc: %s\n", fd.Funcname)
|
| 298 |
+
fmt.Printf("Srcfile: %s\n", fd.Srcfile)
|
| 299 |
+
fmt.Printf("Literal: %v\n", fd.Lit)
|
| 300 |
+
}
|
| 301 |
+
for i := 0; i < len(fd.Units); i++ {
|
| 302 |
+
u := fd.Units[i]
|
| 303 |
+
var count uint32
|
| 304 |
+
if counters != nil {
|
| 305 |
+
count = counters[i]
|
| 306 |
+
}
|
| 307 |
+
d.format.AddUnit(fd.Srcfile, fd.Funcname, fd.Lit, u, count)
|
| 308 |
+
if d.cmd == debugDumpMode && !suppressOutput {
|
| 309 |
+
fmt.Printf("%d: L%d:C%d -- L%d:C%d ",
|
| 310 |
+
i, u.StLine, u.StCol, u.EnLine, u.EnCol)
|
| 311 |
+
if u.Parent != 0 {
|
| 312 |
+
fmt.Printf("Parent:%d = %d\n", u.Parent, count)
|
| 313 |
+
} else {
|
| 314 |
+
fmt.Printf("NS=%d = %d\n", u.NxStmts, count)
|
| 315 |
+
}
|
| 316 |
+
}
|
| 317 |
+
d.totalStmts += int(u.NxStmts)
|
| 318 |
+
if count != 0 {
|
| 319 |
+
d.coveredStmts += int(u.NxStmts)
|
| 320 |
+
}
|
| 321 |
+
}
|
| 322 |
+
}
|
| 323 |
+
|
| 324 |
+
func (d *dstate) Finish() {
|
| 325 |
+
// d.format maybe nil here if the specified input dir was empty.
|
| 326 |
+
if d.format != nil {
|
| 327 |
+
if d.cmd == percentMode {
|
| 328 |
+
d.format.EmitPercent(os.Stdout, nil, "", false, false)
|
| 329 |
+
}
|
| 330 |
+
if d.cmd == funcMode {
|
| 331 |
+
d.format.EmitFuncs(os.Stdout)
|
| 332 |
+
}
|
| 333 |
+
if d.textfmtoutf != nil {
|
| 334 |
+
if err := d.format.EmitTextual(nil, d.textfmtoutf); err != nil {
|
| 335 |
+
fatal("writing to %s: %v", *textfmtoutflag, err)
|
| 336 |
+
}
|
| 337 |
+
}
|
| 338 |
+
}
|
| 339 |
+
if d.textfmtoutf != nil {
|
| 340 |
+
if err := d.textfmtoutf.Close(); err != nil {
|
| 341 |
+
fatal("closing textfmt output file %s: %v", *textfmtoutflag, err)
|
| 342 |
+
}
|
| 343 |
+
}
|
| 344 |
+
if d.cmd == debugDumpMode {
|
| 345 |
+
fmt.Printf("totalStmts: %d coveredStmts: %d\n", d.totalStmts, d.coveredStmts)
|
| 346 |
+
}
|
| 347 |
+
if d.cmd == pkglistMode {
|
| 348 |
+
pkgs := make([]string, 0, len(d.pkgpaths))
|
| 349 |
+
for p := range d.pkgpaths {
|
| 350 |
+
pkgs = append(pkgs, p)
|
| 351 |
+
}
|
| 352 |
+
sort.Strings(pkgs)
|
| 353 |
+
for _, p := range pkgs {
|
| 354 |
+
fmt.Printf("%s\n", p)
|
| 355 |
+
}
|
| 356 |
+
}
|
| 357 |
+
}
|
go/src/cmd/covdata/export_test.go
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
package main
|
| 6 |
+
|
| 7 |
+
func Main() { main() }
|
go/src/cmd/covdata/merge.go
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
package main
|
| 6 |
+
|
| 7 |
+
// This file contains functions and apis to support the "merge"
|
| 8 |
+
// subcommand of "go tool covdata".
|
| 9 |
+
|
| 10 |
+
import (
|
| 11 |
+
"flag"
|
| 12 |
+
"fmt"
|
| 13 |
+
"internal/coverage"
|
| 14 |
+
"internal/coverage/cmerge"
|
| 15 |
+
"internal/coverage/decodecounter"
|
| 16 |
+
"internal/coverage/decodemeta"
|
| 17 |
+
"internal/coverage/pods"
|
| 18 |
+
"os"
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
var outdirflag *string
|
| 22 |
+
var pcombineflag *bool
|
| 23 |
+
|
| 24 |
+
func makeMergeOp() covOperation {
|
| 25 |
+
outdirflag = flag.String("o", "", "Output directory to write")
|
| 26 |
+
pcombineflag = flag.Bool("pcombine", false, "Combine profiles derived from distinct program executables")
|
| 27 |
+
m := &mstate{
|
| 28 |
+
mm: newMetaMerge(),
|
| 29 |
+
}
|
| 30 |
+
return m
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
// mstate encapsulates state and provides methods for implementing the
|
| 34 |
+
// merge operation. This type implements the CovDataVisitor interface,
|
| 35 |
+
// and is designed to be used in concert with the CovDataReader
|
| 36 |
+
// utility, which abstracts away most of the grubby details of reading
|
| 37 |
+
// coverage data files. Most of the heavy lifting for merging is done
|
| 38 |
+
// using apis from 'metaMerge' (this is mainly a wrapper around that
|
| 39 |
+
// functionality).
|
| 40 |
+
type mstate struct {
|
| 41 |
+
mm *metaMerge
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
func (m *mstate) Usage(msg string) {
|
| 45 |
+
if len(msg) > 0 {
|
| 46 |
+
fmt.Fprintf(os.Stderr, "error: %s\n", msg)
|
| 47 |
+
}
|
| 48 |
+
fmt.Fprintf(os.Stderr, "usage: go tool covdata merge -i=<directories> -o=<dir>\n\n")
|
| 49 |
+
flag.PrintDefaults()
|
| 50 |
+
fmt.Fprintf(os.Stderr, "\nExamples:\n\n")
|
| 51 |
+
fmt.Fprintf(os.Stderr, " go tool covdata merge -i=dir1,dir2,dir3 -o=outdir\n\n")
|
| 52 |
+
fmt.Fprintf(os.Stderr, " \tmerges all files in dir1/dir2/dir3\n")
|
| 53 |
+
fmt.Fprintf(os.Stderr, " \tinto output dir outdir\n")
|
| 54 |
+
Exit(2)
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
func (m *mstate) Setup() {
|
| 58 |
+
if *indirsflag == "" {
|
| 59 |
+
m.Usage("select input directories with '-i' option")
|
| 60 |
+
}
|
| 61 |
+
if *outdirflag == "" {
|
| 62 |
+
m.Usage("select output directory with '-o' option")
|
| 63 |
+
}
|
| 64 |
+
m.mm.SetModeMergePolicy(cmerge.ModeMergeRelaxed)
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
func (m *mstate) BeginPod(p pods.Pod) {
|
| 68 |
+
m.mm.beginPod()
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
func (m *mstate) EndPod(p pods.Pod) {
|
| 72 |
+
m.mm.endPod(*pcombineflag)
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
func (m *mstate) BeginCounterDataFile(cdf string, cdr *decodecounter.CounterDataReader, dirIdx int) {
|
| 76 |
+
dbgtrace(2, "visit counter data file %s dirIdx %d", cdf, dirIdx)
|
| 77 |
+
m.mm.beginCounterDataFile(cdr)
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
func (m *mstate) EndCounterDataFile(cdf string, cdr *decodecounter.CounterDataReader, dirIdx int) {
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
func (m *mstate) VisitFuncCounterData(data decodecounter.FuncPayload) {
|
| 84 |
+
m.mm.visitFuncCounterData(data)
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
func (m *mstate) EndCounters() {
|
| 88 |
+
}
|
| 89 |
+
|
| 90 |
+
func (m *mstate) VisitMetaDataFile(mdf string, mfr *decodemeta.CoverageMetaFileReader) {
|
| 91 |
+
m.mm.visitMetaDataFile(mdf, mfr)
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
func (m *mstate) BeginPackage(pd *decodemeta.CoverageMetaDataDecoder, pkgIdx uint32) {
|
| 95 |
+
dbgtrace(3, "VisitPackage(pk=%d path=%s)", pkgIdx, pd.PackagePath())
|
| 96 |
+
m.mm.visitPackage(pd, pkgIdx, *pcombineflag)
|
| 97 |
+
}
|
| 98 |
+
|
| 99 |
+
func (m *mstate) EndPackage(pd *decodemeta.CoverageMetaDataDecoder, pkgIdx uint32) {
|
| 100 |
+
}
|
| 101 |
+
|
| 102 |
+
func (m *mstate) VisitFunc(pkgIdx uint32, fnIdx uint32, fd *coverage.FuncDesc) {
|
| 103 |
+
m.mm.visitFunc(pkgIdx, fnIdx, fd, mergeMode, *pcombineflag)
|
| 104 |
+
}
|
| 105 |
+
|
| 106 |
+
func (m *mstate) Finish() {
|
| 107 |
+
if *pcombineflag {
|
| 108 |
+
finalHash := m.mm.emitMeta(*outdirflag, true)
|
| 109 |
+
m.mm.emitCounters(*outdirflag, finalHash)
|
| 110 |
+
}
|
| 111 |
+
}
|
go/src/cmd/covdata/metamerge.go
ADDED
|
@@ -0,0 +1,431 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
package main
|
| 6 |
+
|
| 7 |
+
// This file contains functions and apis that support merging of
|
| 8 |
+
// meta-data information. It helps implement the "merge", "subtract",
|
| 9 |
+
// and "intersect" subcommands.
|
| 10 |
+
|
| 11 |
+
import (
|
| 12 |
+
"fmt"
|
| 13 |
+
"hash/fnv"
|
| 14 |
+
"internal/coverage"
|
| 15 |
+
"internal/coverage/calloc"
|
| 16 |
+
"internal/coverage/cmerge"
|
| 17 |
+
"internal/coverage/decodecounter"
|
| 18 |
+
"internal/coverage/decodemeta"
|
| 19 |
+
"internal/coverage/encodecounter"
|
| 20 |
+
"internal/coverage/encodemeta"
|
| 21 |
+
"internal/coverage/slicewriter"
|
| 22 |
+
"io"
|
| 23 |
+
"os"
|
| 24 |
+
"path/filepath"
|
| 25 |
+
"sort"
|
| 26 |
+
"time"
|
| 27 |
+
"unsafe"
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
// metaMerge provides state and methods to help manage the process
|
| 31 |
+
// of selecting or merging meta data files. There are three cases
|
| 32 |
+
// of interest here: the "-pcombine" flag provided by merge, the
|
| 33 |
+
// "-pkg" option provided by all merge/subtract/intersect, and
|
| 34 |
+
// a regular vanilla merge with no package selection
|
| 35 |
+
//
|
| 36 |
+
// In the -pcombine case, we're essentially glomming together all the
|
| 37 |
+
// meta-data for all packages and all functions, meaning that
|
| 38 |
+
// everything we see in a given package needs to be added into the
|
| 39 |
+
// meta-data file builder; we emit a single meta-data file at the end
|
| 40 |
+
// of the run.
|
| 41 |
+
//
|
| 42 |
+
// In the -pkg case, we will typically emit a single meta-data file
|
| 43 |
+
// per input pod, where that new meta-data file contains entries for
|
| 44 |
+
// just the selected packages.
|
| 45 |
+
//
|
| 46 |
+
// In the third case (vanilla merge with no combining or package
|
| 47 |
+
// selection) we can carry over meta-data files without touching them
|
| 48 |
+
// at all (only counter data files will be merged).
|
| 49 |
+
type metaMerge struct {
|
| 50 |
+
calloc.BatchCounterAlloc
|
| 51 |
+
cmerge.Merger
|
| 52 |
+
// maps package import path to package state
|
| 53 |
+
pkm map[string]*pkstate
|
| 54 |
+
// list of packages
|
| 55 |
+
pkgs []*pkstate
|
| 56 |
+
// current package state
|
| 57 |
+
p *pkstate
|
| 58 |
+
// current pod state
|
| 59 |
+
pod *podstate
|
| 60 |
+
// counter data file osargs/goos/goarch state
|
| 61 |
+
astate *argstate
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
// pkstate
|
| 65 |
+
type pkstate struct {
|
| 66 |
+
// index of package within meta-data file.
|
| 67 |
+
pkgIdx uint32
|
| 68 |
+
// this maps function index within the package to counter data payload
|
| 69 |
+
ctab map[uint32]decodecounter.FuncPayload
|
| 70 |
+
// pointer to meta-data blob for package
|
| 71 |
+
mdblob []byte
|
| 72 |
+
// filled in only for -pcombine merges
|
| 73 |
+
*pcombinestate
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
type podstate struct {
|
| 77 |
+
pmm map[pkfunc]decodecounter.FuncPayload
|
| 78 |
+
mdf string
|
| 79 |
+
mfr *decodemeta.CoverageMetaFileReader
|
| 80 |
+
fileHash [16]byte
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
type pkfunc struct {
|
| 84 |
+
pk, fcn uint32
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
// pcombinestate
|
| 88 |
+
type pcombinestate struct {
|
| 89 |
+
// Meta-data builder for the package.
|
| 90 |
+
cmdb *encodemeta.CoverageMetaDataBuilder
|
| 91 |
+
// Maps function meta-data hash to new function index in the
|
| 92 |
+
// new version of the package we're building.
|
| 93 |
+
ftab map[[16]byte]uint32
|
| 94 |
+
}
|
| 95 |
+
|
| 96 |
+
func newMetaMerge() *metaMerge {
|
| 97 |
+
return &metaMerge{
|
| 98 |
+
pkm: make(map[string]*pkstate),
|
| 99 |
+
astate: &argstate{},
|
| 100 |
+
}
|
| 101 |
+
}
|
| 102 |
+
|
| 103 |
+
func (mm *metaMerge) visitMetaDataFile(mdf string, mfr *decodemeta.CoverageMetaFileReader) {
|
| 104 |
+
dbgtrace(2, "visitMetaDataFile(mdf=%s)", mdf)
|
| 105 |
+
|
| 106 |
+
// Record meta-data file name.
|
| 107 |
+
mm.pod.mdf = mdf
|
| 108 |
+
// Keep a pointer to the file-level reader.
|
| 109 |
+
mm.pod.mfr = mfr
|
| 110 |
+
// Record file hash.
|
| 111 |
+
mm.pod.fileHash = mfr.FileHash()
|
| 112 |
+
// Counter mode and granularity -- detect and record clashes here.
|
| 113 |
+
newgran := mfr.CounterGranularity()
|
| 114 |
+
newmode := mfr.CounterMode()
|
| 115 |
+
if err := mm.SetModeAndGranularity(mdf, newmode, newgran); err != nil {
|
| 116 |
+
fatal("%v", err)
|
| 117 |
+
}
|
| 118 |
+
}
|
| 119 |
+
|
| 120 |
+
func (mm *metaMerge) beginCounterDataFile(cdr *decodecounter.CounterDataReader) {
|
| 121 |
+
state := argvalues{
|
| 122 |
+
osargs: cdr.OsArgs(),
|
| 123 |
+
goos: cdr.Goos(),
|
| 124 |
+
goarch: cdr.Goarch(),
|
| 125 |
+
}
|
| 126 |
+
mm.astate.Merge(state)
|
| 127 |
+
}
|
| 128 |
+
|
| 129 |
+
func copyMetaDataFile(inpath, outpath string) {
|
| 130 |
+
inf, err := os.Open(inpath)
|
| 131 |
+
if err != nil {
|
| 132 |
+
fatal("opening input meta-data file %s: %v", inpath, err)
|
| 133 |
+
}
|
| 134 |
+
defer inf.Close()
|
| 135 |
+
|
| 136 |
+
fi, err := inf.Stat()
|
| 137 |
+
if err != nil {
|
| 138 |
+
fatal("accessing input meta-data file %s: %v", inpath, err)
|
| 139 |
+
}
|
| 140 |
+
|
| 141 |
+
outf, err := os.OpenFile(outpath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, fi.Mode())
|
| 142 |
+
if err != nil {
|
| 143 |
+
fatal("opening output meta-data file %s: %v", outpath, err)
|
| 144 |
+
}
|
| 145 |
+
|
| 146 |
+
_, err = io.Copy(outf, inf)
|
| 147 |
+
outf.Close()
|
| 148 |
+
if err != nil {
|
| 149 |
+
fatal("writing output meta-data file %s: %v", outpath, err)
|
| 150 |
+
}
|
| 151 |
+
}
|
| 152 |
+
|
| 153 |
+
func (mm *metaMerge) beginPod() {
|
| 154 |
+
mm.pod = &podstate{
|
| 155 |
+
pmm: make(map[pkfunc]decodecounter.FuncPayload),
|
| 156 |
+
}
|
| 157 |
+
}
|
| 158 |
+
|
| 159 |
+
// metaEndPod handles actions needed when we're done visiting all of
|
| 160 |
+
// the things in a pod -- counter files and meta-data file. There are
|
| 161 |
+
// three cases of interest here:
|
| 162 |
+
//
|
| 163 |
+
// Case 1: in an unconditional merge (we're not selecting a specific set of
|
| 164 |
+
// packages using "-pkg", and the "-pcombine" option is not in use),
|
| 165 |
+
// we can simply copy over the meta-data file from input to output.
|
| 166 |
+
//
|
| 167 |
+
// Case 2: if this is a select merge (-pkg is in effect), then at
|
| 168 |
+
// this point we write out a new smaller meta-data file that includes
|
| 169 |
+
// only the packages of interest. At this point we also emit a merged
|
| 170 |
+
// counter data file as well.
|
| 171 |
+
//
|
| 172 |
+
// Case 3: if "-pcombine" is in effect, we don't write anything at
|
| 173 |
+
// this point (all writes will happen at the end of the run).
|
| 174 |
+
func (mm *metaMerge) endPod(pcombine bool) {
|
| 175 |
+
if pcombine {
|
| 176 |
+
// Just clear out the pod data, we'll do all the
|
| 177 |
+
// heavy lifting at the end.
|
| 178 |
+
mm.pod = nil
|
| 179 |
+
return
|
| 180 |
+
}
|
| 181 |
+
|
| 182 |
+
finalHash := mm.pod.fileHash
|
| 183 |
+
if matchpkg != nil {
|
| 184 |
+
// Emit modified meta-data file for this pod.
|
| 185 |
+
finalHash = mm.emitMeta(*outdirflag, pcombine)
|
| 186 |
+
} else {
|
| 187 |
+
// Copy meta-data file for this pod to the output directory.
|
| 188 |
+
inpath := mm.pod.mdf
|
| 189 |
+
mdfbase := filepath.Base(mm.pod.mdf)
|
| 190 |
+
outpath := filepath.Join(*outdirflag, mdfbase)
|
| 191 |
+
copyMetaDataFile(inpath, outpath)
|
| 192 |
+
}
|
| 193 |
+
|
| 194 |
+
// Emit accumulated counter data for this pod.
|
| 195 |
+
mm.emitCounters(*outdirflag, finalHash)
|
| 196 |
+
|
| 197 |
+
// Reset package state.
|
| 198 |
+
mm.pkm = make(map[string]*pkstate)
|
| 199 |
+
mm.pkgs = nil
|
| 200 |
+
mm.pod = nil
|
| 201 |
+
|
| 202 |
+
// Reset counter mode and granularity
|
| 203 |
+
mm.ResetModeAndGranularity()
|
| 204 |
+
}
|
| 205 |
+
|
| 206 |
+
// emitMeta encodes and writes out a new coverage meta-data file as
|
| 207 |
+
// part of a merge operation, specifically a merge with the
|
| 208 |
+
// "-pcombine" flag.
|
| 209 |
+
func (mm *metaMerge) emitMeta(outdir string, pcombine bool) [16]byte {
|
| 210 |
+
fh := fnv.New128a()
|
| 211 |
+
fhSum := fnv.New128a()
|
| 212 |
+
blobs := [][]byte{}
|
| 213 |
+
tlen := uint64(unsafe.Sizeof(coverage.MetaFileHeader{}))
|
| 214 |
+
for _, p := range mm.pkgs {
|
| 215 |
+
var blob []byte
|
| 216 |
+
if pcombine {
|
| 217 |
+
mdw := &slicewriter.WriteSeeker{}
|
| 218 |
+
p.cmdb.Emit(mdw)
|
| 219 |
+
blob = mdw.BytesWritten()
|
| 220 |
+
} else {
|
| 221 |
+
blob = p.mdblob
|
| 222 |
+
}
|
| 223 |
+
fhSum.Reset()
|
| 224 |
+
fhSum.Write(blob)
|
| 225 |
+
ph := fhSum.Sum(nil)
|
| 226 |
+
blobs = append(blobs, blob)
|
| 227 |
+
if _, err := fh.Write(ph[:]); err != nil {
|
| 228 |
+
panic(fmt.Sprintf("internal error: md5 sum failed: %v", err))
|
| 229 |
+
}
|
| 230 |
+
tlen += uint64(len(blob))
|
| 231 |
+
}
|
| 232 |
+
var finalHash [16]byte
|
| 233 |
+
fhh := fh.Sum(nil)
|
| 234 |
+
copy(finalHash[:], fhh)
|
| 235 |
+
|
| 236 |
+
// Open meta-file for writing.
|
| 237 |
+
fn := fmt.Sprintf("%s.%x", coverage.MetaFilePref, finalHash)
|
| 238 |
+
fpath := filepath.Join(outdir, fn)
|
| 239 |
+
mf, err := os.OpenFile(fpath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
|
| 240 |
+
if err != nil {
|
| 241 |
+
fatal("unable to open output meta-data file %s: %v", fpath, err)
|
| 242 |
+
}
|
| 243 |
+
|
| 244 |
+
defer func() {
|
| 245 |
+
if err := mf.Close(); err != nil {
|
| 246 |
+
fatal("error closing output meta-data file %s: %v", fpath, err)
|
| 247 |
+
}
|
| 248 |
+
}()
|
| 249 |
+
|
| 250 |
+
// Encode and write.
|
| 251 |
+
mfw := encodemeta.NewCoverageMetaFileWriter(fpath, mf)
|
| 252 |
+
err = mfw.Write(finalHash, blobs, mm.Mode(), mm.Granularity())
|
| 253 |
+
if err != nil {
|
| 254 |
+
fatal("error writing %s: %v\n", fpath, err)
|
| 255 |
+
}
|
| 256 |
+
return finalHash
|
| 257 |
+
}
|
| 258 |
+
|
| 259 |
+
func (mm *metaMerge) emitCounters(outdir string, metaHash [16]byte) {
|
| 260 |
+
// Open output file. The file naming scheme is intended to mimic
|
| 261 |
+
// that used when running a coverage-instrumented binary, for
|
| 262 |
+
// consistency (however the process ID is not meaningful here, so
|
| 263 |
+
// use a value of zero).
|
| 264 |
+
var dummyPID int
|
| 265 |
+
fn := fmt.Sprintf(coverage.CounterFileTempl, coverage.CounterFilePref, metaHash, dummyPID, time.Now().UnixNano())
|
| 266 |
+
fpath := filepath.Join(outdir, fn)
|
| 267 |
+
cf, err := os.OpenFile(fpath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
|
| 268 |
+
if err != nil {
|
| 269 |
+
fatal("opening counter data file %s: %v", fpath, err)
|
| 270 |
+
}
|
| 271 |
+
defer func() {
|
| 272 |
+
if err := cf.Close(); err != nil {
|
| 273 |
+
fatal("error closing output meta-data file %s: %v", fpath, err)
|
| 274 |
+
}
|
| 275 |
+
}()
|
| 276 |
+
|
| 277 |
+
args := mm.astate.ArgsSummary()
|
| 278 |
+
cfw := encodecounter.NewCoverageDataWriter(cf, coverage.CtrULeb128)
|
| 279 |
+
if err := cfw.Write(metaHash, args, mm); err != nil {
|
| 280 |
+
fatal("counter file write failed: %v", err)
|
| 281 |
+
}
|
| 282 |
+
mm.astate = &argstate{}
|
| 283 |
+
}
|
| 284 |
+
|
| 285 |
+
// VisitFuncs is used while writing the counter data files; it
|
| 286 |
+
// implements the 'VisitFuncs' method required by the interface
|
| 287 |
+
// internal/coverage/encodecounter/CounterVisitor.
|
| 288 |
+
func (mm *metaMerge) VisitFuncs(f encodecounter.CounterVisitorFn) error {
|
| 289 |
+
if *verbflag >= 4 {
|
| 290 |
+
fmt.Printf("counterVisitor invoked\n")
|
| 291 |
+
}
|
| 292 |
+
// For each package, for each function, construct counter
|
| 293 |
+
// array and then call "f" on it.
|
| 294 |
+
for pidx, p := range mm.pkgs {
|
| 295 |
+
fids := make([]int, 0, len(p.ctab))
|
| 296 |
+
for fid := range p.ctab {
|
| 297 |
+
fids = append(fids, int(fid))
|
| 298 |
+
}
|
| 299 |
+
sort.Ints(fids)
|
| 300 |
+
if *verbflag >= 4 {
|
| 301 |
+
fmt.Printf("fids for pk=%d: %+v\n", pidx, fids)
|
| 302 |
+
}
|
| 303 |
+
for _, fid := range fids {
|
| 304 |
+
fp := p.ctab[uint32(fid)]
|
| 305 |
+
if *verbflag >= 4 {
|
| 306 |
+
fmt.Printf("counter write for pk=%d fid=%d len(ctrs)=%d\n", pidx, fid, len(fp.Counters))
|
| 307 |
+
}
|
| 308 |
+
if err := f(uint32(pidx), uint32(fid), fp.Counters); err != nil {
|
| 309 |
+
return err
|
| 310 |
+
}
|
| 311 |
+
}
|
| 312 |
+
}
|
| 313 |
+
return nil
|
| 314 |
+
}
|
| 315 |
+
|
| 316 |
+
func (mm *metaMerge) visitPackage(pd *decodemeta.CoverageMetaDataDecoder, pkgIdx uint32, pcombine bool) {
|
| 317 |
+
p, ok := mm.pkm[pd.PackagePath()]
|
| 318 |
+
if !ok {
|
| 319 |
+
p = &pkstate{
|
| 320 |
+
pkgIdx: uint32(len(mm.pkgs)),
|
| 321 |
+
}
|
| 322 |
+
mm.pkgs = append(mm.pkgs, p)
|
| 323 |
+
mm.pkm[pd.PackagePath()] = p
|
| 324 |
+
if pcombine {
|
| 325 |
+
p.pcombinestate = new(pcombinestate)
|
| 326 |
+
cmdb, err := encodemeta.NewCoverageMetaDataBuilder(pd.PackagePath(), pd.PackageName(), pd.ModulePath())
|
| 327 |
+
if err != nil {
|
| 328 |
+
fatal("fatal error creating meta-data builder: %v", err)
|
| 329 |
+
}
|
| 330 |
+
dbgtrace(2, "install new pkm entry for package %s pk=%d", pd.PackagePath(), pkgIdx)
|
| 331 |
+
p.cmdb = cmdb
|
| 332 |
+
p.ftab = make(map[[16]byte]uint32)
|
| 333 |
+
} else {
|
| 334 |
+
var err error
|
| 335 |
+
p.mdblob, err = mm.pod.mfr.GetPackagePayload(pkgIdx, nil)
|
| 336 |
+
if err != nil {
|
| 337 |
+
fatal("error extracting package %d payload from %s: %v",
|
| 338 |
+
pkgIdx, mm.pod.mdf, err)
|
| 339 |
+
}
|
| 340 |
+
}
|
| 341 |
+
p.ctab = make(map[uint32]decodecounter.FuncPayload)
|
| 342 |
+
}
|
| 343 |
+
mm.p = p
|
| 344 |
+
}
|
| 345 |
+
|
| 346 |
+
func (mm *metaMerge) visitFuncCounterData(data decodecounter.FuncPayload) {
|
| 347 |
+
key := pkfunc{pk: data.PkgIdx, fcn: data.FuncIdx}
|
| 348 |
+
val := mm.pod.pmm[key]
|
| 349 |
+
// FIXME: in theory either A) len(val.Counters) is zero, or B)
|
| 350 |
+
// the two lengths are equal. Assert if not? Of course, we could
|
| 351 |
+
// see odd stuff if there is source file skew.
|
| 352 |
+
if *verbflag > 4 {
|
| 353 |
+
fmt.Printf("visit pk=%d fid=%d len(counters)=%d\n", data.PkgIdx, data.FuncIdx, len(data.Counters))
|
| 354 |
+
}
|
| 355 |
+
if len(val.Counters) < len(data.Counters) {
|
| 356 |
+
t := val.Counters
|
| 357 |
+
val.Counters = mm.AllocateCounters(len(data.Counters))
|
| 358 |
+
copy(val.Counters, t)
|
| 359 |
+
}
|
| 360 |
+
err, overflow := mm.MergeCounters(val.Counters, data.Counters)
|
| 361 |
+
if err != nil {
|
| 362 |
+
fatal("%v", err)
|
| 363 |
+
}
|
| 364 |
+
if overflow {
|
| 365 |
+
warn("uint32 overflow during counter merge")
|
| 366 |
+
}
|
| 367 |
+
mm.pod.pmm[key] = val
|
| 368 |
+
}
|
| 369 |
+
|
| 370 |
+
func (mm *metaMerge) visitFunc(pkgIdx uint32, fnIdx uint32, fd *coverage.FuncDesc, verb string, pcombine bool) {
|
| 371 |
+
if *verbflag >= 3 {
|
| 372 |
+
fmt.Printf("visit pk=%d fid=%d func %s\n", pkgIdx, fnIdx, fd.Funcname)
|
| 373 |
+
}
|
| 374 |
+
|
| 375 |
+
var counters []uint32
|
| 376 |
+
key := pkfunc{pk: pkgIdx, fcn: fnIdx}
|
| 377 |
+
v, haveCounters := mm.pod.pmm[key]
|
| 378 |
+
if haveCounters {
|
| 379 |
+
counters = v.Counters
|
| 380 |
+
}
|
| 381 |
+
|
| 382 |
+
if pcombine {
|
| 383 |
+
// If the merge is running in "combine programs" mode, then hash
|
| 384 |
+
// the function and look it up in the package ftab to see if we've
|
| 385 |
+
// encountered it before. If we haven't, then register it with the
|
| 386 |
+
// meta-data builder.
|
| 387 |
+
fnhash := encodemeta.HashFuncDesc(fd)
|
| 388 |
+
gfidx, ok := mm.p.ftab[fnhash]
|
| 389 |
+
if !ok {
|
| 390 |
+
// We haven't seen this function before, need to add it to
|
| 391 |
+
// the meta data.
|
| 392 |
+
gfidx = uint32(mm.p.cmdb.AddFunc(*fd))
|
| 393 |
+
mm.p.ftab[fnhash] = gfidx
|
| 394 |
+
if *verbflag >= 3 {
|
| 395 |
+
fmt.Printf("new meta entry for fn %s fid=%d\n", fd.Funcname, gfidx)
|
| 396 |
+
}
|
| 397 |
+
}
|
| 398 |
+
fnIdx = gfidx
|
| 399 |
+
}
|
| 400 |
+
if !haveCounters {
|
| 401 |
+
return
|
| 402 |
+
}
|
| 403 |
+
|
| 404 |
+
// Install counters in package ctab.
|
| 405 |
+
gfp, ok := mm.p.ctab[fnIdx]
|
| 406 |
+
if ok {
|
| 407 |
+
if verb == "subtract" || verb == "intersect" {
|
| 408 |
+
panic("should never see this for intersect/subtract")
|
| 409 |
+
}
|
| 410 |
+
if *verbflag >= 3 {
|
| 411 |
+
fmt.Printf("counter merge for %s fidx=%d\n", fd.Funcname, fnIdx)
|
| 412 |
+
}
|
| 413 |
+
// Merge.
|
| 414 |
+
err, overflow := mm.MergeCounters(gfp.Counters, counters)
|
| 415 |
+
if err != nil {
|
| 416 |
+
fatal("%v", err)
|
| 417 |
+
}
|
| 418 |
+
if overflow {
|
| 419 |
+
warn("uint32 overflow during counter merge")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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
package main
|
| 6 |
+
|
| 7 |
+
// This file contains functions and apis to support the "subtract" and
|
| 8 |
+
// "intersect" subcommands of "go tool covdata".
|
| 9 |
+
|
| 10 |
+
import (
|
| 11 |
+
"flag"
|
| 12 |
+
"fmt"
|
| 13 |
+
"internal/coverage"
|
| 14 |
+
"internal/coverage/decodecounter"
|
| 15 |
+
"internal/coverage/decodemeta"
|
| 16 |
+
"internal/coverage/pods"
|
| 17 |
+
"os"
|
| 18 |
+
"strings"
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
// makeSubtractIntersectOp creates a subtract or intersect operation.
|
| 22 |
+
// 'mode' here must be either "subtract" or "intersect".
|
| 23 |
+
func makeSubtractIntersectOp(mode string) covOperation {
|
| 24 |
+
outdirflag = flag.String("o", "", "Output directory to write")
|
| 25 |
+
s := &sstate{
|
| 26 |
+
mode: mode,
|
| 27 |
+
mm: newMetaMerge(),
|
| 28 |
+
inidx: -1,
|
| 29 |
+
}
|
| 30 |
+
return s
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
// sstate holds state needed to implement subtraction and intersection
|
| 34 |
+
// operations on code coverage data files. This type provides methods
|
| 35 |
+
// to implement the CovDataVisitor interface, and is designed to be
|
| 36 |
+
// used in concert with the CovDataReader utility, which abstracts
|
| 37 |
+
// away most of the grubby details of reading coverage data files.
|
| 38 |
+
type sstate struct {
|
| 39 |
+
mm *metaMerge
|
| 40 |
+
inidx int
|
| 41 |
+
mode string
|
| 42 |
+
// Used only for intersection; keyed by pkg/fn ID, it keeps track of
|
| 43 |
+
// just the set of functions for which we have data in the current
|
| 44 |
+
// input directory.
|
| 45 |
+
imm map[pkfunc]struct{}
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
func (s *sstate) Usage(msg string) {
|
| 49 |
+
if len(msg) > 0 {
|
| 50 |
+
fmt.Fprintf(os.Stderr, "error: %s\n", msg)
|
| 51 |
+
}
|
| 52 |
+
fmt.Fprintf(os.Stderr, "usage: go tool covdata %s -i=dir1,dir2 -o=<dir>\n\n", s.mode)
|
| 53 |
+
flag.PrintDefaults()
|
| 54 |
+
fmt.Fprintf(os.Stderr, "\nExamples:\n\n")
|
| 55 |
+
op := "from"
|
| 56 |
+
if s.mode == intersectMode {
|
| 57 |
+
op = "with"
|
| 58 |
+
}
|
| 59 |
+
fmt.Fprintf(os.Stderr, " go tool covdata %s -i=dir1,dir2 -o=outdir\n\n", s.mode)
|
| 60 |
+
fmt.Fprintf(os.Stderr, " \t%ss dir2 %s dir1, writing result\n", s.mode, op)
|
| 61 |
+
fmt.Fprintf(os.Stderr, " \tinto output dir outdir.\n")
|
| 62 |
+
os.Exit(2)
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
func (s *sstate) Setup() {
|
| 66 |
+
if *indirsflag == "" {
|
| 67 |
+
usage("select input directories with '-i' option")
|
| 68 |
+
}
|
| 69 |
+
indirs := strings.Split(*indirsflag, ",")
|
| 70 |
+
if s.mode == subtractMode && len(indirs) != 2 {
|
| 71 |
+
usage("supply exactly two input dirs for subtract operation")
|
| 72 |
+
}
|
| 73 |
+
if *outdirflag == "" {
|
| 74 |
+
usage("select output directory with '-o' option")
|
| 75 |
+
}
|
| 76 |
+
}
|
| 77 |
+
|
| 78 |
+
func (s *sstate) BeginPod(p pods.Pod) {
|
| 79 |
+
s.mm.beginPod()
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
func (s *sstate) EndPod(p pods.Pod) {
|
| 83 |
+
const pcombine = false
|
| 84 |
+
s.mm.endPod(pcombine)
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
func (s *sstate) EndCounters() {
|
| 88 |
+
if s.imm != nil {
|
| 89 |
+
s.pruneCounters()
|
| 90 |
+
}
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
// pruneCounters performs a function-level partial intersection using the
|
| 94 |
+
// current POD counter data (s.mm.pod.pmm) and the intersected data from
|
| 95 |
+
// PODs in previous dirs (s.imm).
|
| 96 |
+
func (s *sstate) pruneCounters() {
|
| 97 |
+
pkeys := make([]pkfunc, 0, len(s.mm.pod.pmm))
|
| 98 |
+
for k := range s.mm.pod.pmm {
|
| 99 |
+
pkeys = append(pkeys, k)
|
| 100 |
+
}
|
| 101 |
+
// Remove anything from pmm not found in imm. We don't need to
|
| 102 |
+
// go the other way (removing things from imm not found in pmm)
|
| 103 |
+
// since we don't add anything to imm if there is no pmm entry.
|
| 104 |
+
for _, k := range pkeys {
|
| 105 |
+
if _, found := s.imm[k]; !found {
|
| 106 |
+
delete(s.mm.pod.pmm, k)
|
| 107 |
+
}
|
| 108 |
+
}
|
| 109 |
+
s.imm = nil
|
| 110 |
+
}
|
| 111 |
+
|
| 112 |
+
func (s *sstate) BeginCounterDataFile(cdf string, cdr *decodecounter.CounterDataReader, dirIdx int) {
|
| 113 |
+
dbgtrace(2, "visiting counter data file %s diridx %d", cdf, dirIdx)
|
| 114 |
+
if s.inidx != dirIdx {
|
| 115 |
+
if s.inidx > dirIdx {
|
| 116 |
+
// We're relying on having data files presented in
|
| 117 |
+
// the order they appear in the inputs (e.g. first all
|
| 118 |
+
// data files from input dir 0, then dir 1, etc).
|
| 119 |
+
panic("decreasing dir index, internal error")
|
| 120 |
+
}
|
| 121 |
+
if dirIdx == 0 {
|
| 122 |
+
// No need to keep track of the functions in the first
|
| 123 |
+
// directory, since that info will be replicated in
|
| 124 |
+
// s.mm.pod.pmm.
|
| 125 |
+
s.imm = nil
|
| 126 |
+
} else {
|
| 127 |
+
// We're now starting to visit the Nth directory, N != 0.
|
| 128 |
+
if s.mode == intersectMode {
|
| 129 |
+
if s.imm != nil {
|
| 130 |
+
s.pruneCounters()
|
| 131 |
+
}
|
| 132 |
+
s.imm = make(map[pkfunc]struct{})
|
| 133 |
+
}
|
| 134 |
+
}
|
| 135 |
+
s.inidx = dirIdx
|
| 136 |
+
}
|
| 137 |
+
}
|
| 138 |
+
|
| 139 |
+
func (s *sstate) EndCounterDataFile(cdf string, cdr *decodecounter.CounterDataReader, dirIdx int) {
|
| 140 |
+
}
|
| 141 |
+
|
| 142 |
+
func (s *sstate) VisitFuncCounterData(data decodecounter.FuncPayload) {
|
| 143 |
+
key := pkfunc{pk: data.PkgIdx, fcn: data.FuncIdx}
|
| 144 |
+
|
| 145 |
+
if *verbflag >= 5 {
|
| 146 |
+
fmt.Printf("ctr visit fid=%d pk=%d inidx=%d data.Counters=%+v\n", data.FuncIdx, data.PkgIdx, s.inidx, data.Counters)
|
| 147 |
+
}
|
| 148 |
+
|
| 149 |
+
// If we're processing counter data from the initial (first) input
|
| 150 |
+
// directory, then just install it into the counter data map
|
| 151 |
+
// as usual.
|
| 152 |
+
if s.inidx == 0 {
|
| 153 |
+
s.mm.visitFuncCounterData(data)
|
| 154 |
+
return
|
| 155 |
+
}
|
| 156 |
+
|
| 157 |
+
// If we're looking at counter data from a dir other than
|
| 158 |
+
// the first, then perform the intersect/subtract.
|
| 159 |
+
if val, ok := s.mm.pod.pmm[key]; ok {
|
| 160 |
+
if s.mode == subtractMode {
|
| 161 |
+
for i := 0; i < len(data.Counters); i++ {
|
| 162 |
+
if data.Counters[i] != 0 {
|
| 163 |
+
val.Counters[i] = 0
|
| 164 |
+
}
|
| 165 |
+
}
|
| 166 |
+
} else if s.mode == intersectMode {
|
| 167 |
+
s.imm[key] = struct{}{}
|
| 168 |
+
for i := 0; i < len(data.Counters); i++ {
|
| 169 |
+
if data.Counters[i] == 0 {
|
| 170 |
+
val.Counters[i] = 0
|
| 171 |
+
}
|
| 172 |
+
}
|
| 173 |
+
}
|
| 174 |
+
}
|
| 175 |
+
}
|
| 176 |
+
|
| 177 |
+
func (s *sstate) VisitMetaDataFile(mdf string, mfr *decodemeta.CoverageMetaFileReader) {
|
| 178 |
+
if s.mode == intersectMode {
|
| 179 |
+
s.imm = make(map[pkfunc]struct{})
|
| 180 |
+
}
|
| 181 |
+
s.mm.visitMetaDataFile(mdf, mfr)
|
| 182 |
+
}
|
| 183 |
+
|
| 184 |
+
func (s *sstate) BeginPackage(pd *decodemeta.CoverageMetaDataDecoder, pkgIdx uint32) {
|
| 185 |
+
s.mm.visitPackage(pd, pkgIdx, false)
|
| 186 |
+
}
|
| 187 |
+
|
| 188 |
+
func (s *sstate) EndPackage(pd *decodemeta.CoverageMetaDataDecoder, pkgIdx uint32) {
|
| 189 |
+
}
|
| 190 |
+
|
| 191 |
+
func (s *sstate) VisitFunc(pkgIdx uint32, fnIdx uint32, fd *coverage.FuncDesc) {
|
| 192 |
+
s.mm.visitFunc(pkgIdx, fnIdx, fd, s.mode, false)
|
| 193 |
+
}
|
| 194 |
+
|
| 195 |
+
func (s *sstate) Finish() {
|
| 196 |
+
}
|
go/src/cmd/covdata/tool_test.go
ADDED
|
@@ -0,0 +1,943 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
package main_test
|
| 6 |
+
|
| 7 |
+
import (
|
| 8 |
+
cmdcovdata "cmd/covdata"
|
| 9 |
+
"flag"
|
| 10 |
+
"fmt"
|
| 11 |
+
"internal/coverage/pods"
|
| 12 |
+
"internal/testenv"
|
| 13 |
+
"log"
|
| 14 |
+
"os"
|
| 15 |
+
"path/filepath"
|
| 16 |
+
"regexp"
|
| 17 |
+
"strconv"
|
| 18 |
+
"strings"
|
| 19 |
+
"sync"
|
| 20 |
+
"testing"
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
// Top level tempdir for test.
|
| 24 |
+
var testTempDir string
|
| 25 |
+
|
| 26 |
+
// If set, this will preserve all the tmpdir files from the test run.
|
| 27 |
+
var preserveTmp = flag.Bool("preservetmp", false, "keep tmpdir files for debugging")
|
| 28 |
+
|
| 29 |
+
// TestMain used here so that we can leverage the test executable
|
| 30 |
+
// itself as a cmd/covdata executable; compare to similar usage in
|
| 31 |
+
// the cmd/go tests.
|
| 32 |
+
func TestMain(m *testing.M) {
|
| 33 |
+
// When CMDCOVDATA_TEST_RUN_MAIN is set, we're reusing the test
|
| 34 |
+
// binary as cmd/cover. In this case we run the main func exported
|
| 35 |
+
// via export_test.go, and exit; CMDCOVDATA_TEST_RUN_MAIN is set below
|
| 36 |
+
// for actual test invocations.
|
| 37 |
+
if os.Getenv("CMDCOVDATA_TEST_RUN_MAIN") != "" {
|
| 38 |
+
cmdcovdata.Main()
|
| 39 |
+
os.Exit(0)
|
| 40 |
+
}
|
| 41 |
+
flag.Parse()
|
| 42 |
+
topTmpdir, err := os.MkdirTemp("", "cmd-covdata-test-")
|
| 43 |
+
if err != nil {
|
| 44 |
+
log.Fatal(err)
|
| 45 |
+
}
|
| 46 |
+
testTempDir = topTmpdir
|
| 47 |
+
if !*preserveTmp {
|
| 48 |
+
defer os.RemoveAll(topTmpdir)
|
| 49 |
+
} else {
|
| 50 |
+
fmt.Fprintf(os.Stderr, "debug: preserving tmpdir %s\n", topTmpdir)
|
| 51 |
+
}
|
| 52 |
+
os.Setenv("CMDCOVDATA_TEST_RUN_MAIN", "true")
|
| 53 |
+
os.Exit(m.Run())
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
var tdmu sync.Mutex
|
| 57 |
+
var tdcount int
|
| 58 |
+
|
| 59 |
+
func tempDir(t *testing.T) string {
|
| 60 |
+
tdmu.Lock()
|
| 61 |
+
dir := filepath.Join(testTempDir, fmt.Sprintf("%03d", tdcount))
|
| 62 |
+
tdcount++
|
| 63 |
+
if err := os.Mkdir(dir, 0777); err != nil {
|
| 64 |
+
t.Fatal(err)
|
| 65 |
+
}
|
| 66 |
+
defer tdmu.Unlock()
|
| 67 |
+
return dir
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
const debugtrace = false
|
| 71 |
+
|
| 72 |
+
func gobuild(t *testing.T, indir string, bargs []string) {
|
| 73 |
+
t.Helper()
|
| 74 |
+
|
| 75 |
+
if debugtrace {
|
| 76 |
+
if indir != "" {
|
| 77 |
+
t.Logf("in dir %s: ", indir)
|
| 78 |
+
}
|
| 79 |
+
t.Logf("cmd: %s %+v\n", testenv.GoToolPath(t), bargs)
|
| 80 |
+
}
|
| 81 |
+
cmd := testenv.Command(t, testenv.GoToolPath(t), bargs...)
|
| 82 |
+
cmd.Dir = indir
|
| 83 |
+
b, err := cmd.CombinedOutput()
|
| 84 |
+
if len(b) != 0 {
|
| 85 |
+
t.Logf("## build output:\n%s", b)
|
| 86 |
+
}
|
| 87 |
+
if err != nil {
|
| 88 |
+
t.Fatalf("build error: %v", err)
|
| 89 |
+
}
|
| 90 |
+
}
|
| 91 |
+
|
| 92 |
+
func emitFile(t *testing.T, dst, src string) {
|
| 93 |
+
payload, err := os.ReadFile(src)
|
| 94 |
+
if err != nil {
|
| 95 |
+
t.Fatalf("error reading %q: %v", src, err)
|
| 96 |
+
}
|
| 97 |
+
if err := os.WriteFile(dst, payload, 0666); err != nil {
|
| 98 |
+
t.Fatalf("writing %q: %v", dst, err)
|
| 99 |
+
}
|
| 100 |
+
}
|
| 101 |
+
|
| 102 |
+
const mainPkgPath = "prog"
|
| 103 |
+
|
| 104 |
+
func buildProg(t *testing.T, prog string, dir string, tag string, flags []string) (string, string) {
|
| 105 |
+
// Create subdirs.
|
| 106 |
+
subdir := filepath.Join(dir, prog+"dir"+tag)
|
| 107 |
+
if err := os.Mkdir(subdir, 0777); err != nil {
|
| 108 |
+
t.Fatalf("can't create outdir %s: %v", subdir, err)
|
| 109 |
+
}
|
| 110 |
+
depdir := filepath.Join(subdir, "dep")
|
| 111 |
+
if err := os.Mkdir(depdir, 0777); err != nil {
|
| 112 |
+
t.Fatalf("can't create outdir %s: %v", depdir, err)
|
| 113 |
+
}
|
| 114 |
+
|
| 115 |
+
// Emit program.
|
| 116 |
+
insrc := filepath.Join("testdata", prog+".go")
|
| 117 |
+
src := filepath.Join(subdir, prog+".go")
|
| 118 |
+
emitFile(t, src, insrc)
|
| 119 |
+
indep := filepath.Join("testdata", "dep.go")
|
| 120 |
+
dep := filepath.Join(depdir, "dep.go")
|
| 121 |
+
emitFile(t, dep, indep)
|
| 122 |
+
|
| 123 |
+
// Emit go.mod.
|
| 124 |
+
mod := filepath.Join(subdir, "go.mod")
|
| 125 |
+
modsrc := "\nmodule " + mainPkgPath + "\n\ngo 1.19\n"
|
| 126 |
+
if err := os.WriteFile(mod, []byte(modsrc), 0666); err != nil {
|
| 127 |
+
t.Fatal(err)
|
| 128 |
+
}
|
| 129 |
+
exepath := filepath.Join(subdir, prog+".exe")
|
| 130 |
+
bargs := []string{"build", "-cover", "-o", exepath}
|
| 131 |
+
bargs = append(bargs, flags...)
|
| 132 |
+
gobuild(t, subdir, bargs)
|
| 133 |
+
return exepath, subdir
|
| 134 |
+
}
|
| 135 |
+
|
| 136 |
+
type state struct {
|
| 137 |
+
dir string
|
| 138 |
+
exedir1 string
|
| 139 |
+
exedir2 string
|
| 140 |
+
exedir3 string
|
| 141 |
+
exepath1 string
|
| 142 |
+
exepath2 string
|
| 143 |
+
exepath3 string
|
| 144 |
+
tool string
|
| 145 |
+
outdirs [4]string
|
| 146 |
+
}
|
| 147 |
+
|
| 148 |
+
const debugWorkDir = false
|
| 149 |
+
|
| 150 |
+
func TestCovTool(t *testing.T) {
|
| 151 |
+
testenv.MustHaveGoBuild(t)
|
| 152 |
+
dir := tempDir(t)
|
| 153 |
+
if testing.Short() {
|
| 154 |
+
t.Skip()
|
| 155 |
+
}
|
| 156 |
+
if debugWorkDir {
|
| 157 |
+
// debugging
|
| 158 |
+
dir = "/tmp/qqq"
|
| 159 |
+
os.RemoveAll(dir)
|
| 160 |
+
os.Mkdir(dir, 0777)
|
| 161 |
+
}
|
| 162 |
+
|
| 163 |
+
s := state{
|
| 164 |
+
dir: dir,
|
| 165 |
+
}
|
| 166 |
+
s.exepath1, s.exedir1 = buildProg(t, "prog1", dir, "", nil)
|
| 167 |
+
s.exepath2, s.exedir2 = buildProg(t, "prog2", dir, "", nil)
|
| 168 |
+
flags := []string{"-covermode=atomic"}
|
| 169 |
+
s.exepath3, s.exedir3 = buildProg(t, "prog1", dir, "atomic", flags)
|
| 170 |
+
|
| 171 |
+
// Reuse unit test executable as tool to be tested.
|
| 172 |
+
s.tool = testenv.Executable(t)
|
| 173 |
+
|
| 174 |
+
// Create a few coverage output dirs.
|
| 175 |
+
for i := 0; i < 4; i++ {
|
| 176 |
+
d := filepath.Join(dir, fmt.Sprintf("covdata%d", i))
|
| 177 |
+
s.outdirs[i] = d
|
| 178 |
+
if err := os.Mkdir(d, 0777); err != nil {
|
| 179 |
+
t.Fatalf("can't create outdir %s: %v", d, err)
|
| 180 |
+
}
|
| 181 |
+
}
|
| 182 |
+
|
| 183 |
+
// Run instrumented program to generate some coverage data output files,
|
| 184 |
+
// as follows:
|
| 185 |
+
//
|
| 186 |
+
// <tmp>/covdata0 -- prog1.go compiled -cover
|
| 187 |
+
// <tmp>/covdata1 -- prog1.go compiled -cover
|
| 188 |
+
// <tmp>/covdata2 -- prog1.go compiled -covermode=atomic
|
| 189 |
+
// <tmp>/covdata3 -- prog1.go compiled -covermode=atomic
|
| 190 |
+
//
|
| 191 |
+
for m := 0; m < 2; m++ {
|
| 192 |
+
for k := 0; k < 2; k++ {
|
| 193 |
+
args := []string{}
|
| 194 |
+
if k != 0 {
|
| 195 |
+
args = append(args, "foo", "bar")
|
| 196 |
+
}
|
| 197 |
+
for i := 0; i <= k; i++ {
|
| 198 |
+
exepath := s.exepath1
|
| 199 |
+
if m != 0 {
|
| 200 |
+
exepath = s.exepath3
|
| 201 |
+
}
|
| 202 |
+
cmd := testenv.Command(t, exepath, args...)
|
| 203 |
+
cmd.Env = append(cmd.Env, "GOCOVERDIR="+s.outdirs[m*2+k])
|
| 204 |
+
b, err := cmd.CombinedOutput()
|
| 205 |
+
if len(b) != 0 {
|
| 206 |
+
t.Logf("## instrumented run output:\n%s", b)
|
| 207 |
+
}
|
| 208 |
+
if err != nil {
|
| 209 |
+
t.Fatalf("instrumented run error: %v", err)
|
| 210 |
+
}
|
| 211 |
+
}
|
| 212 |
+
}
|
| 213 |
+
}
|
| 214 |
+
|
| 215 |
+
// At this point we can fork off a bunch of child tests
|
| 216 |
+
// to check different tool modes.
|
| 217 |
+
t.Run("MergeSimple", func(t *testing.T) {
|
| 218 |
+
t.Parallel()
|
| 219 |
+
testMergeSimple(t, s, s.outdirs[0], s.outdirs[1], "set")
|
| 220 |
+
testMergeSimple(t, s, s.outdirs[2], s.outdirs[3], "atomic")
|
| 221 |
+
})
|
| 222 |
+
t.Run("MergeSelect", func(t *testing.T) {
|
| 223 |
+
t.Parallel()
|
| 224 |
+
testMergeSelect(t, s, s.outdirs[0], s.outdirs[1], "set")
|
| 225 |
+
testMergeSelect(t, s, s.outdirs[2], s.outdirs[3], "atomic")
|
| 226 |
+
})
|
| 227 |
+
t.Run("MergePcombine", func(t *testing.T) {
|
| 228 |
+
t.Parallel()
|
| 229 |
+
testMergeCombinePrograms(t, s)
|
| 230 |
+
})
|
| 231 |
+
t.Run("Dump", func(t *testing.T) {
|
| 232 |
+
t.Parallel()
|
| 233 |
+
testDump(t, s)
|
| 234 |
+
})
|
| 235 |
+
t.Run("Percent", func(t *testing.T) {
|
| 236 |
+
t.Parallel()
|
| 237 |
+
testPercent(t, s)
|
| 238 |
+
})
|
| 239 |
+
t.Run("PkgList", func(t *testing.T) {
|
| 240 |
+
t.Parallel()
|
| 241 |
+
testPkgList(t, s)
|
| 242 |
+
})
|
| 243 |
+
t.Run("Textfmt", func(t *testing.T) {
|
| 244 |
+
t.Parallel()
|
| 245 |
+
testTextfmt(t, s)
|
| 246 |
+
})
|
| 247 |
+
t.Run("Subtract", func(t *testing.T) {
|
| 248 |
+
t.Parallel()
|
| 249 |
+
testSubtract(t, s)
|
| 250 |
+
})
|
| 251 |
+
t.Run("Intersect", func(t *testing.T) {
|
| 252 |
+
t.Parallel()
|
| 253 |
+
testIntersect(t, s, s.outdirs[0], s.outdirs[1], "set")
|
| 254 |
+
testIntersect(t, s, s.outdirs[2], s.outdirs[3], "atomic")
|
| 255 |
+
})
|
| 256 |
+
t.Run("CounterClash", func(t *testing.T) {
|
| 257 |
+
t.Parallel()
|
| 258 |
+
testCounterClash(t, s)
|
| 259 |
+
})
|
| 260 |
+
t.Run("TestEmpty", func(t *testing.T) {
|
| 261 |
+
t.Parallel()
|
| 262 |
+
testEmpty(t, s)
|
| 263 |
+
})
|
| 264 |
+
t.Run("TestCommandLineErrors", func(t *testing.T) {
|
| 265 |
+
t.Parallel()
|
| 266 |
+
testCommandLineErrors(t, s, s.outdirs[0])
|
| 267 |
+
})
|
| 268 |
+
}
|
| 269 |
+
|
| 270 |
+
const showToolInvocations = true
|
| 271 |
+
|
| 272 |
+
func runToolOp(t *testing.T, s state, op string, args []string) []string {
|
| 273 |
+
// Perform tool run.
|
| 274 |
+
t.Helper()
|
| 275 |
+
args = append([]string{op}, args...)
|
| 276 |
+
if showToolInvocations {
|
| 277 |
+
t.Logf("%s cmd is: %s %+v", op, s.tool, args)
|
| 278 |
+
}
|
| 279 |
+
cmd := testenv.Command(t, s.tool, args...)
|
| 280 |
+
b, err := cmd.CombinedOutput()
|
| 281 |
+
if err != nil {
|
| 282 |
+
fmt.Fprintf(os.Stderr, "## %s output: %s\n", op, b)
|
| 283 |
+
t.Fatalf("%q run error: %v", op, err)
|
| 284 |
+
}
|
| 285 |
+
output := strings.TrimSpace(string(b))
|
| 286 |
+
lines := strings.Split(output, "\n")
|
| 287 |
+
if len(lines) == 1 && lines[0] == "" {
|
| 288 |
+
lines = nil
|
| 289 |
+
}
|
| 290 |
+
return lines
|
| 291 |
+
}
|
| 292 |
+
|
| 293 |
+
func testDump(t *testing.T, s state) {
|
| 294 |
+
// Run the dumper on the two dirs we generated.
|
| 295 |
+
dargs := []string{"-pkg=" + mainPkgPath, "-live", "-i=" + s.outdirs[0] + "," + s.outdirs[1]}
|
| 296 |
+
lines := runToolOp(t, s, "debugdump", dargs)
|
| 297 |
+
|
| 298 |
+
// Sift through the output to make sure it has some key elements.
|
| 299 |
+
testpoints := []struct {
|
| 300 |
+
tag string
|
| 301 |
+
re *regexp.Regexp
|
| 302 |
+
}{
|
| 303 |
+
{
|
| 304 |
+
"args",
|
| 305 |
+
regexp.MustCompile(`^data file .+ GOOS=.+ GOARCH=.+ program args: .+$`),
|
| 306 |
+
},
|
| 307 |
+
{
|
| 308 |
+
"main package",
|
| 309 |
+
regexp.MustCompile(`^Package path: ` + mainPkgPath + `\s*$`),
|
| 310 |
+
},
|
| 311 |
+
{
|
| 312 |
+
"main function",
|
| 313 |
+
regexp.MustCompile(`^Func: main\s*$`),
|
| 314 |
+
},
|
| 315 |
+
}
|
| 316 |
+
|
| 317 |
+
bad := false
|
| 318 |
+
for _, testpoint := range testpoints {
|
| 319 |
+
found := false
|
| 320 |
+
for _, line := range lines {
|
| 321 |
+
if m := testpoint.re.FindStringSubmatch(line); m != nil {
|
| 322 |
+
found = true
|
| 323 |
+
break
|
| 324 |
+
}
|
| 325 |
+
}
|
| 326 |
+
if !found {
|
| 327 |
+
t.Errorf("dump output regexp match failed for %q", testpoint.tag)
|
| 328 |
+
bad = true
|
| 329 |
+
}
|
| 330 |
+
}
|
| 331 |
+
if bad {
|
| 332 |
+
dumplines(lines)
|
| 333 |
+
}
|
| 334 |
+
}
|
| 335 |
+
|
| 336 |
+
func testPercent(t *testing.T, s state) {
|
| 337 |
+
// Run the dumper on the two dirs we generated.
|
| 338 |
+
dargs := []string{"-pkg=" + mainPkgPath, "-i=" + s.outdirs[0] + "," + s.outdirs[1]}
|
| 339 |
+
lines := runToolOp(t, s, "percent", dargs)
|
| 340 |
+
|
| 341 |
+
// Sift through the output to make sure it has the needful.
|
| 342 |
+
testpoints := []struct {
|
| 343 |
+
tag string
|
| 344 |
+
re *regexp.Regexp
|
| 345 |
+
}{
|
| 346 |
+
{
|
| 347 |
+
"statement coverage percent",
|
| 348 |
+
regexp.MustCompile(`coverage: \d+\.\d% of statements\s*$`),
|
| 349 |
+
},
|
| 350 |
+
}
|
| 351 |
+
|
| 352 |
+
bad := false
|
| 353 |
+
for _, testpoint := range testpoints {
|
| 354 |
+
found := false
|
| 355 |
+
for _, line := range lines {
|
| 356 |
+
if m := testpoint.re.FindStringSubmatch(line); m != nil {
|
| 357 |
+
found = true
|
| 358 |
+
break
|
| 359 |
+
}
|
| 360 |
+
}
|
| 361 |
+
if !found {
|
| 362 |
+
t.Errorf("percent output regexp match failed for %s", testpoint.tag)
|
| 363 |
+
bad = true
|
| 364 |
+
}
|
| 365 |
+
}
|
| 366 |
+
if bad {
|
| 367 |
+
dumplines(lines)
|
| 368 |
+
}
|
| 369 |
+
}
|
| 370 |
+
|
| 371 |
+
func testPkgList(t *testing.T, s state) {
|
| 372 |
+
dargs := []string{"-i=" + s.outdirs[0] + "," + s.outdirs[1]}
|
| 373 |
+
lines := runToolOp(t, s, "pkglist", dargs)
|
| 374 |
+
|
| 375 |
+
want := []string{mainPkgPath, mainPkgPath + "/dep"}
|
| 376 |
+
bad := false
|
| 377 |
+
if len(lines) != 2 {
|
| 378 |
+
t.Errorf("expect pkglist to return two lines")
|
| 379 |
+
bad = true
|
| 380 |
+
} else {
|
| 381 |
+
for i := 0; i < 2; i++ {
|
| 382 |
+
lines[i] = strings.TrimSpace(lines[i])
|
| 383 |
+
if want[i] != lines[i] {
|
| 384 |
+
t.Errorf("line %d want %s got %s", i, want[i], lines[i])
|
| 385 |
+
bad = true
|
| 386 |
+
}
|
| 387 |
+
}
|
| 388 |
+
}
|
| 389 |
+
if bad {
|
| 390 |
+
dumplines(lines)
|
| 391 |
+
}
|
| 392 |
+
}
|
| 393 |
+
|
| 394 |
+
func testTextfmt(t *testing.T, s state) {
|
| 395 |
+
outf := s.dir + "/" + "t.txt"
|
| 396 |
+
dargs := []string{"-pkg=" + mainPkgPath, "-i=" + s.outdirs[0] + "," + s.outdirs[1],
|
| 397 |
+
"-o", outf}
|
| 398 |
+
lines := runToolOp(t, s, "textfmt", dargs)
|
| 399 |
+
|
| 400 |
+
// No output expected.
|
| 401 |
+
if len(lines) != 0 {
|
| 402 |
+
dumplines(lines)
|
| 403 |
+
t.Errorf("unexpected output from go tool covdata textfmt")
|
| 404 |
+
}
|
| 405 |
+
|
| 406 |
+
// Open and read the first few bits of the file.
|
| 407 |
+
payload, err := os.ReadFile(outf)
|
| 408 |
+
if err != nil {
|
| 409 |
+
t.Errorf("opening %s: %v\n", outf, err)
|
| 410 |
+
}
|
| 411 |
+
lines = strings.Split(string(payload), "\n")
|
| 412 |
+
want0 := "mode: set"
|
| 413 |
+
if lines[0] != want0 {
|
| 414 |
+
dumplines(lines[0:10])
|
| 415 |
+
t.Errorf("textfmt: want %s got %s", want0, lines[0])
|
| 416 |
+
}
|
| 417 |
+
want1 := mainPkgPath + "/prog1.go:13.14,15.2 1 1"
|
| 418 |
+
if lines[1] != want1 {
|
| 419 |
+
dumplines(lines[0:10])
|
| 420 |
+
t.Errorf("textfmt: want %s got %s", want1, lines[1])
|
| 421 |
+
}
|
| 422 |
+
}
|
| 423 |
+
|
| 424 |
+
func dumplines(lines []string) {
|
| 425 |
+
for i := range lines {
|
| 426 |
+
fmt.Fprintf(os.Stderr, "%s\n", lines[i])
|
| 427 |
+
}
|
| 428 |
+
}
|
| 429 |
+
|
| 430 |
+
type dumpCheck struct {
|
| 431 |
+
tag string
|
| 432 |
+
re *regexp.Regexp
|
| 433 |
+
negate bool
|
| 434 |
+
nonzero bool
|
| 435 |
+
zero bool
|
| 436 |
+
}
|
| 437 |
+
|
| 438 |
+
// runDumpChecks examines the output of "go tool covdata debugdump"
|
| 439 |
+
// for a given output directory, looking for the presence or absence
|
| 440 |
+
// of specific markers.
|
| 441 |
+
func runDumpChecks(t *testing.T, s state, dir string, flags []string, checks []dumpCheck) {
|
| 442 |
+
dargs := []string{"-i", dir}
|
| 443 |
+
dargs = append(dargs, flags...)
|
| 444 |
+
lines := runToolOp(t, s, "debugdump", dargs)
|
| 445 |
+
if len(lines) == 0 {
|
| 446 |
+
t.Fatalf("dump run produced no output")
|
| 447 |
+
}
|
| 448 |
+
|
| 449 |
+
bad := false
|
| 450 |
+
for _, check := range checks {
|
| 451 |
+
found := false
|
| 452 |
+
for _, line := range lines {
|
| 453 |
+
if m := check.re.FindStringSubmatch(line); m != nil {
|
| 454 |
+
found = true
|
| 455 |
+
if check.negate {
|
| 456 |
+
t.Errorf("tag %q: unexpected match", check.tag)
|
| 457 |
+
bad = true
|
| 458 |
+
|
| 459 |
+
}
|
| 460 |
+
if check.nonzero || check.zero {
|
| 461 |
+
if len(m) < 2 {
|
| 462 |
+
t.Errorf("tag %s: submatch failed (short m)", check.tag)
|
| 463 |
+
bad = true
|
| 464 |
+
continue
|
| 465 |
+
}
|
| 466 |
+
if m[1] == "" {
|
| 467 |
+
t.Errorf("tag %s: submatch failed", check.tag)
|
| 468 |
+
bad = true
|
| 469 |
+
continue
|
| 470 |
+
}
|
| 471 |
+
i, err := strconv.Atoi(m[1])
|
| 472 |
+
if err != nil {
|
| 473 |
+
t.Errorf("tag %s: match Atoi failed on %s",
|
| 474 |
+
check.tag, m[1])
|
| 475 |
+
continue
|
| 476 |
+
}
|
| 477 |
+
if check.zero && i != 0 {
|
| 478 |
+
t.Errorf("tag %s: match zero failed on %s",
|
| 479 |
+
check.tag, m[1])
|
| 480 |
+
} else if check.nonzero && i == 0 {
|
| 481 |
+
t.Errorf("tag %s: match nonzero failed on %s",
|
| 482 |
+
check.tag, m[1])
|
| 483 |
+
}
|
| 484 |
+
}
|
| 485 |
+
break
|
| 486 |
+
}
|
| 487 |
+
}
|
| 488 |
+
if !found && !check.negate {
|
| 489 |
+
t.Errorf("dump output regexp match failed for %s", check.tag)
|
| 490 |
+
bad = true
|
| 491 |
+
}
|
| 492 |
+
}
|
| 493 |
+
if bad {
|
| 494 |
+
fmt.Printf("output from 'dump' run:\n")
|
| 495 |
+
dumplines(lines)
|
| 496 |
+
}
|
| 497 |
+
}
|
| 498 |
+
|
| 499 |
+
func testMergeSimple(t *testing.T, s state, indir1, indir2, tag string) {
|
| 500 |
+
outdir := filepath.Join(s.dir, "simpleMergeOut"+tag)
|
| 501 |
+
if err := os.Mkdir(outdir, 0777); err != nil {
|
| 502 |
+
t.Fatalf("can't create outdir %s: %v", outdir, err)
|
| 503 |
+
}
|
| 504 |
+
|
| 505 |
+
// Merge the two dirs into a final result.
|
| 506 |
+
ins := fmt.Sprintf("-i=%s,%s", indir1, indir2)
|
| 507 |
+
out := fmt.Sprintf("-o=%s", outdir)
|
| 508 |
+
margs := []string{ins, out}
|
| 509 |
+
lines := runToolOp(t, s, "merge", margs)
|
| 510 |
+
if len(lines) != 0 {
|
| 511 |
+
t.Errorf("merge run produced %d lines of unexpected output", len(lines))
|
| 512 |
+
dumplines(lines)
|
| 513 |
+
}
|
| 514 |
+
|
| 515 |
+
// We expect the merge tool to produce exactly two files: a meta
|
| 516 |
+
// data file and a counter file. If we get more than just this one
|
| 517 |
+
// pair, something went wrong.
|
| 518 |
+
podlist, err := pods.CollectPods([]string{outdir}, true)
|
| 519 |
+
if err != nil {
|
| 520 |
+
t.Fatal(err)
|
| 521 |
+
}
|
| 522 |
+
if len(podlist) != 1 {
|
| 523 |
+
t.Fatalf("expected 1 pod, got %d pods", len(podlist))
|
| 524 |
+
}
|
| 525 |
+
ncdfs := len(podlist[0].CounterDataFiles)
|
| 526 |
+
if ncdfs != 1 {
|
| 527 |
+
t.Fatalf("expected 1 counter data file, got %d", ncdfs)
|
| 528 |
+
}
|
| 529 |
+
|
| 530 |
+
// Sift through the output to make sure it has some key elements.
|
| 531 |
+
// In particular, we want to see entries for all three functions
|
| 532 |
+
// ("first", "second", and "third").
|
| 533 |
+
testpoints := []dumpCheck{
|
| 534 |
+
{
|
| 535 |
+
tag: "first function",
|
| 536 |
+
re: regexp.MustCompile(`^Func: first\s*$`),
|
| 537 |
+
},
|
| 538 |
+
{
|
| 539 |
+
tag: "second function",
|
| 540 |
+
re: regexp.MustCompile(`^Func: second\s*$`),
|
| 541 |
+
},
|
| 542 |
+
{
|
| 543 |
+
tag: "third function",
|
| 544 |
+
re: regexp.MustCompile(`^Func: third\s*$`),
|
| 545 |
+
},
|
| 546 |
+
{
|
| 547 |
+
tag: "third function unit 0",
|
| 548 |
+
re: regexp.MustCompile(`^0: L23:C23 -- L24:C12 NS=1 = (\d+)$`),
|
| 549 |
+
nonzero: true,
|
| 550 |
+
},
|
| 551 |
+
{
|
| 552 |
+
tag: "third function unit 1",
|
| 553 |
+
re: regexp.MustCompile(`^1: L27:C2 -- L28:C10 NS=2 = (\d+)$`),
|
| 554 |
+
nonzero: true,
|
| 555 |
+
},
|
| 556 |
+
{
|
| 557 |
+
tag: "third function unit 2",
|
| 558 |
+
re: regexp.MustCompile(`^2: L24:C12 -- L26:C3 NS=1 = (\d+)$`),
|
| 559 |
+
nonzero: true,
|
| 560 |
+
},
|
| 561 |
+
}
|
| 562 |
+
flags := []string{"-live", "-pkg=" + mainPkgPath}
|
| 563 |
+
runDumpChecks(t, s, outdir, flags, testpoints)
|
| 564 |
+
}
|
| 565 |
+
|
| 566 |
+
func testMergeSelect(t *testing.T, s state, indir1, indir2 string, tag string) {
|
| 567 |
+
outdir := filepath.Join(s.dir, "selectMergeOut"+tag)
|
| 568 |
+
if err := os.Mkdir(outdir, 0777); err != nil {
|
| 569 |
+
t.Fatalf("can't create outdir %s: %v", outdir, err)
|
| 570 |
+
}
|
| 571 |
+
|
| 572 |
+
// Merge two input dirs into a final result, but filter
|
| 573 |
+
// based on package.
|
| 574 |
+
ins := fmt.Sprintf("-i=%s,%s", indir1, indir2)
|
| 575 |
+
out := fmt.Sprintf("-o=%s", outdir)
|
| 576 |
+
margs := []string{"-pkg=" + mainPkgPath + "/dep", ins, out}
|
| 577 |
+
lines := runToolOp(t, s, "merge", margs)
|
| 578 |
+
if len(lines) != 0 {
|
| 579 |
+
t.Errorf("merge run produced %d lines of unexpected output", len(lines))
|
| 580 |
+
dumplines(lines)
|
| 581 |
+
}
|
| 582 |
+
|
| 583 |
+
// Dump the files in the merged output dir and examine the result.
|
| 584 |
+
// We expect to see only the functions in package "dep".
|
| 585 |
+
dargs := []string{"-i=" + outdir}
|
| 586 |
+
lines = runToolOp(t, s, "debugdump", dargs)
|
| 587 |
+
if len(lines) == 0 {
|
| 588 |
+
t.Fatalf("dump run produced no output")
|
| 589 |
+
}
|
| 590 |
+
want := map[string]int{
|
| 591 |
+
"Package path: " + mainPkgPath + "/dep": 0,
|
| 592 |
+
"Func: Dep1": 0,
|
| 593 |
+
"Func: PDep": 0,
|
| 594 |
+
}
|
| 595 |
+
bad := false
|
| 596 |
+
for _, line := range lines {
|
| 597 |
+
if v, ok := want[line]; ok {
|
| 598 |
+
if v != 0 {
|
| 599 |
+
t.Errorf("duplicate line %s", line)
|
| 600 |
+
bad = true
|
| 601 |
+
break
|
| 602 |
+
}
|
| 603 |
+
want[line] = 1
|
| 604 |
+
continue
|
| 605 |
+
}
|
| 606 |
+
// no other functions or packages expected.
|
| 607 |
+
if strings.HasPrefix(line, "Func:") || strings.HasPrefix(line, "Package path:") {
|
| 608 |
+
t.Errorf("unexpected line: %s", line)
|
| 609 |
+
bad = true
|
| 610 |
+
break
|
| 611 |
+
}
|
| 612 |
+
}
|
| 613 |
+
if bad {
|
| 614 |
+
dumplines(lines)
|
| 615 |
+
}
|
| 616 |
+
}
|
| 617 |
+
|
| 618 |
+
func testMergeCombinePrograms(t *testing.T, s state) {
|
| 619 |
+
|
| 620 |
+
// Run the new program, emitting output into a new set
|
| 621 |
+
// of outdirs.
|
| 622 |
+
runout := [2]string{}
|
| 623 |
+
for k := 0; k < 2; k++ {
|
| 624 |
+
runout[k] = filepath.Join(s.dir, fmt.Sprintf("newcovdata%d", k))
|
| 625 |
+
if err := os.Mkdir(runout[k], 0777); err != nil {
|
| 626 |
+
t.Fatalf("can't create outdir %s: %v", runout[k], err)
|
| 627 |
+
}
|
| 628 |
+
args := []string{}
|
| 629 |
+
if k != 0 {
|
| 630 |
+
args = append(args, "foo", "bar")
|
| 631 |
+
}
|
| 632 |
+
cmd := testenv.Command(t, s.exepath2, args...)
|
| 633 |
+
cmd.Env = append(cmd.Env, "GOCOVERDIR="+runout[k])
|
| 634 |
+
b, err := cmd.CombinedOutput()
|
| 635 |
+
if len(b) != 0 {
|
| 636 |
+
t.Logf("## instrumented run output:\n%s", b)
|
| 637 |
+
}
|
| 638 |
+
if err != nil {
|
| 639 |
+
t.Fatalf("instrumented run error: %v", err)
|
| 640 |
+
}
|
| 641 |
+
}
|
| 642 |
+
|
| 643 |
+
// Create out dir for -pcombine merge.
|
| 644 |
+
moutdir := filepath.Join(s.dir, "mergeCombineOut")
|
| 645 |
+
if err := os.Mkdir(moutdir, 0777); err != nil {
|
| 646 |
+
t.Fatalf("can't create outdir %s: %v", moutdir, err)
|
| 647 |
+
}
|
| 648 |
+
|
| 649 |
+
// Run a merge over both programs, using the -pcombine
|
| 650 |
+
// flag to do maximal combining.
|
| 651 |
+
ins := fmt.Sprintf("-i=%s,%s,%s,%s", s.outdirs[0], s.outdirs[1],
|
| 652 |
+
runout[0], runout[1])
|
| 653 |
+
out := fmt.Sprintf("-o=%s", moutdir)
|
| 654 |
+
margs := []string{"-pcombine", ins, out}
|
| 655 |
+
lines := runToolOp(t, s, "merge", margs)
|
| 656 |
+
if len(lines) != 0 {
|
| 657 |
+
t.Errorf("merge run produced unexpected output: %v", lines)
|
| 658 |
+
}
|
| 659 |
+
|
| 660 |
+
// We expect the merge tool to produce exactly two files: a meta
|
| 661 |
+
// data file and a counter file. If we get more than just this one
|
| 662 |
+
// pair, something went wrong.
|
| 663 |
+
podlist, err := pods.CollectPods([]string{moutdir}, true)
|
| 664 |
+
if err != nil {
|
| 665 |
+
t.Fatal(err)
|
| 666 |
+
}
|
| 667 |
+
if len(podlist) != 1 {
|
| 668 |
+
t.Fatalf("expected 1 pod, got %d pods", len(podlist))
|
| 669 |
+
}
|
| 670 |
+
ncdfs := len(podlist[0].CounterDataFiles)
|
| 671 |
+
if ncdfs != 1 {
|
| 672 |
+
t.Fatalf("expected 1 counter data file, got %d", ncdfs)
|
| 673 |
+
}
|
| 674 |
+
|
| 675 |
+
// Sift through the output to make sure it has some key elements.
|
| 676 |
+
testpoints := []dumpCheck{
|
| 677 |
+
{
|
| 678 |
+
tag: "first function",
|
| 679 |
+
re: regexp.MustCompile(`^Func: first\s*$`),
|
| 680 |
+
},
|
| 681 |
+
{
|
| 682 |
+
tag: "sixth function",
|
| 683 |
+
re: regexp.MustCompile(`^Func: sixth\s*$`),
|
| 684 |
+
},
|
| 685 |
+
}
|
| 686 |
+
|
| 687 |
+
flags := []string{"-live", "-pkg=" + mainPkgPath}
|
| 688 |
+
runDumpChecks(t, s, moutdir, flags, testpoints)
|
| 689 |
+
}
|
| 690 |
+
|
| 691 |
+
func testSubtract(t *testing.T, s state) {
|
| 692 |
+
// Create out dir for subtract merge.
|
| 693 |
+
soutdir := filepath.Join(s.dir, "subtractOut")
|
| 694 |
+
if err := os.Mkdir(soutdir, 0777); err != nil {
|
| 695 |
+
t.Fatalf("can't create outdir %s: %v", soutdir, err)
|
| 696 |
+
}
|
| 697 |
+
|
| 698 |
+
// Subtract the two dirs into a final result.
|
| 699 |
+
ins := fmt.Sprintf("-i=%s,%s", s.outdirs[0], s.outdirs[1])
|
| 700 |
+
out := fmt.Sprintf("-o=%s", soutdir)
|
| 701 |
+
sargs := []string{ins, out}
|
| 702 |
+
lines := runToolOp(t, s, "subtract", sargs)
|
| 703 |
+
if len(lines) != 0 {
|
| 704 |
+
t.Errorf("subtract run produced unexpected output: %+v", lines)
|
| 705 |
+
}
|
| 706 |
+
|
| 707 |
+
// Dump the files in the subtract output dir and examine the result.
|
| 708 |
+
dargs := []string{"-pkg=" + mainPkgPath, "-live", "-i=" + soutdir}
|
| 709 |
+
lines = runToolOp(t, s, "debugdump", dargs)
|
| 710 |
+
if len(lines) == 0 {
|
| 711 |
+
t.Errorf("dump run produced no output")
|
| 712 |
+
}
|
| 713 |
+
|
| 714 |
+
// Vet the output.
|
| 715 |
+
testpoints := []dumpCheck{
|
| 716 |
+
{
|
| 717 |
+
tag: "first function",
|
| 718 |
+
re: regexp.MustCompile(`^Func: first\s*$`),
|
| 719 |
+
},
|
| 720 |
+
{
|
| 721 |
+
tag: "dep function",
|
| 722 |
+
re: regexp.MustCompile(`^Func: Dep1\s*$`),
|
| 723 |
+
},
|
| 724 |
+
{
|
| 725 |
+
tag: "third function",
|
| 726 |
+
re: regexp.MustCompile(`^Func: third\s*$`),
|
| 727 |
+
},
|
| 728 |
+
{
|
| 729 |
+
tag: "third function unit 0",
|
| 730 |
+
re: regexp.MustCompile(`^0: L23:C23 -- L24:C12 NS=1 = (\d+)$`),
|
| 731 |
+
zero: true,
|
| 732 |
+
},
|
| 733 |
+
{
|
| 734 |
+
tag: "third function unit 1",
|
| 735 |
+
re: regexp.MustCompile(`^1: L27:C2 -- L28:C10 NS=2 = (\d+)$`),
|
| 736 |
+
nonzero: true,
|
| 737 |
+
},
|
| 738 |
+
{
|
| 739 |
+
tag: "third function unit 2",
|
| 740 |
+
re: regexp.MustCompile(`^2: L24:C12 -- L26:C3 NS=1 = (\d+)$`),
|
| 741 |
+
zero: true,
|
| 742 |
+
},
|
| 743 |
+
}
|
| 744 |
+
flags := []string{}
|
| 745 |
+
runDumpChecks(t, s, soutdir, flags, testpoints)
|
| 746 |
+
}
|
| 747 |
+
|
| 748 |
+
func testIntersect(t *testing.T, s state, indir1, indir2, tag string) {
|
| 749 |
+
// Create out dir for intersection.
|
| 750 |
+
ioutdir := filepath.Join(s.dir, "intersectOut"+tag)
|
| 751 |
+
if err := os.Mkdir(ioutdir, 0777); err != nil {
|
| 752 |
+
t.Fatalf("can't create outdir %s: %v", ioutdir, err)
|
| 753 |
+
}
|
| 754 |
+
|
| 755 |
+
// Intersect the two dirs into a final result.
|
| 756 |
+
ins := fmt.Sprintf("-i=%s,%s", indir1, indir2)
|
| 757 |
+
out := fmt.Sprintf("-o=%s", ioutdir)
|
| 758 |
+
sargs := []string{ins, out}
|
| 759 |
+
lines := runToolOp(t, s, "intersect", sargs)
|
| 760 |
+
if len(lines) != 0 {
|
| 761 |
+
t.Errorf("intersect run produced unexpected output: %+v", lines)
|
| 762 |
+
}
|
| 763 |
+
|
| 764 |
+
// Dump the files in the subtract output dir and examine the result.
|
| 765 |
+
dargs := []string{"-pkg=" + mainPkgPath, "-live", "-i=" + ioutdir}
|
| 766 |
+
lines = runToolOp(t, s, "debugdump", dargs)
|
| 767 |
+
if len(lines) == 0 {
|
| 768 |
+
t.Errorf("dump run produced no output")
|
| 769 |
+
}
|
| 770 |
+
|
| 771 |
+
// Vet the output.
|
| 772 |
+
testpoints := []dumpCheck{
|
| 773 |
+
{
|
| 774 |
+
tag: "first function",
|
| 775 |
+
re: regexp.MustCompile(`^Func: first\s*$`),
|
| 776 |
+
negate: true,
|
| 777 |
+
},
|
| 778 |
+
{
|
| 779 |
+
tag: "third function",
|
| 780 |
+
re: regexp.MustCompile(`^Func: third\s*$`),
|
| 781 |
+
},
|
| 782 |
+
}
|
| 783 |
+
flags := []string{"-live"}
|
| 784 |
+
runDumpChecks(t, s, ioutdir, flags, testpoints)
|
| 785 |
+
}
|
| 786 |
+
|
| 787 |
+
func testCounterClash(t *testing.T, s state) {
|
| 788 |
+
// Create out dir.
|
| 789 |
+
ccoutdir := filepath.Join(s.dir, "ccOut")
|
| 790 |
+
if err := os.Mkdir(ccoutdir, 0777); err != nil {
|
| 791 |
+
t.Fatalf("can't create outdir %s: %v", ccoutdir, err)
|
| 792 |
+
}
|
| 793 |
+
|
| 794 |
+
// Try to merge covdata0 (from prog1.go -countermode=set) with
|
| 795 |
+
// covdata1 (from prog1.go -countermode=atomic"). This should
|
| 796 |
+
// work properly, but result in multiple meta-data files.
|
| 797 |
+
ins := fmt.Sprintf("-i=%s,%s", s.outdirs[0], s.outdirs[3])
|
| 798 |
+
out := fmt.Sprintf("-o=%s", ccoutdir)
|
| 799 |
+
args := append([]string{}, "merge", ins, out, "-pcombine")
|
| 800 |
+
if debugtrace {
|
| 801 |
+
t.Logf("cc merge command is %s %v\n", s.tool, args)
|
| 802 |
+
}
|
| 803 |
+
cmd := testenv.Command(t, s.tool, args...)
|
| 804 |
+
b, err := cmd.CombinedOutput()
|
| 805 |
+
t.Logf("%% output: %s\n", string(b))
|
| 806 |
+
if err != nil {
|
| 807 |
+
t.Fatalf("clash merge failed: %v", err)
|
| 808 |
+
}
|
| 809 |
+
|
| 810 |
+
// Ask for a textual report from the two dirs. Here we have
|
| 811 |
+
// to report the mode clash.
|
| 812 |
+
out = "-o=" + filepath.Join(ccoutdir, "file.txt")
|
| 813 |
+
args = append([]string{}, "textfmt", ins, out)
|
| 814 |
+
if debugtrace {
|
| 815 |
+
t.Logf("clash textfmt command is %s %v\n", s.tool, args)
|
| 816 |
+
}
|
| 817 |
+
cmd = testenv.Command(t, s.tool, args...)
|
| 818 |
+
b, err = cmd.CombinedOutput()
|
| 819 |
+
t.Logf("%% output: %s\n", string(b))
|
| 820 |
+
if err == nil {
|
| 821 |
+
t.Fatalf("expected mode clash")
|
| 822 |
+
}
|
| 823 |
+
got := string(b)
|
| 824 |
+
want := "counter mode clash while reading meta-data"
|
| 825 |
+
if !strings.Contains(got, want) {
|
| 826 |
+
t.Errorf("counter clash textfmt: wanted %s got %s", want, got)
|
| 827 |
+
}
|
| 828 |
+
}
|
| 829 |
+
|
| 830 |
+
func testEmpty(t *testing.T, s state) {
|
| 831 |
+
|
| 832 |
+
// Create a new empty directory.
|
| 833 |
+
empty := filepath.Join(s.dir, "empty")
|
| 834 |
+
if err := os.Mkdir(empty, 0777); err != nil {
|
| 835 |
+
t.Fatalf("can't create dir %s: %v", empty, err)
|
| 836 |
+
}
|
| 837 |
+
|
| 838 |
+
// Create out dir.
|
| 839 |
+
eoutdir := filepath.Join(s.dir, "emptyOut")
|
| 840 |
+
if err := os.Mkdir(eoutdir, 0777); err != nil {
|
| 841 |
+
t.Fatalf("can't create outdir %s: %v", eoutdir, err)
|
| 842 |
+
}
|
| 843 |
+
|
| 844 |
+
// Run various operations (merge, dump, textfmt, and so on)
|
| 845 |
+
// using the empty directory. We're not interested in the output
|
| 846 |
+
// here, just making sure that you can do these runs without
|
| 847 |
+
// any error or crash.
|
| 848 |
+
|
| 849 |
+
scenarios := []struct {
|
| 850 |
+
tag string
|
| 851 |
+
args []string
|
| 852 |
+
}{
|
| 853 |
+
{
|
| 854 |
+
tag: "merge",
|
| 855 |
+
args: []string{"merge", "-o", eoutdir},
|
| 856 |
+
},
|
| 857 |
+
{
|
| 858 |
+
tag: "textfmt",
|
| 859 |
+
args: []string{"textfmt", "-o", filepath.Join(eoutdir, "foo.txt")},
|
| 860 |
+
},
|
| 861 |
+
{
|
| 862 |
+
tag: "func",
|
| 863 |
+
args: []string{"func"},
|
| 864 |
+
},
|
| 865 |
+
{
|
| 866 |
+
tag: "pkglist",
|
| 867 |
+
args: []string{"pkglist"},
|
| 868 |
+
},
|
| 869 |
+
{
|
| 870 |
+
tag: "debugdump",
|
| 871 |
+
args: []string{"debugdump"},
|
| 872 |
+
},
|
| 873 |
+
{
|
| 874 |
+
tag: "percent",
|
| 875 |
+
args: []string{"percent"},
|
| 876 |
+
},
|
| 877 |
+
}
|
| 878 |
+
|
| 879 |
+
for _, x := range scenarios {
|
| 880 |
+
ins := fmt.Sprintf("-i=%s", empty)
|
| 881 |
+
args := append([]string{}, x.args...)
|
| 882 |
+
args = append(args, ins)
|
| 883 |
+
if false {
|
| 884 |
+
t.Logf("cmd is %s %v\n", s.tool, args)
|
| 885 |
+
}
|
| 886 |
+
cmd := testenv.Command(t, s.tool, args...)
|
| 887 |
+
b, err := cmd.CombinedOutput()
|
| 888 |
+
t.Logf("%% output: %s\n", string(b))
|
| 889 |
+
if err != nil {
|
| 890 |
+
t.Fatalf("command %s %+v failed with %v",
|
| 891 |
+
s.tool, x.args, err)
|
| 892 |
+
}
|
| 893 |
+
}
|
| 894 |
+
}
|
| 895 |
+
|
| 896 |
+
func testCommandLineErrors(t *testing.T, s state, outdir string) {
|
| 897 |
+
|
| 898 |
+
// Create out dir.
|
| 899 |
+
eoutdir := filepath.Join(s.dir, "errorsOut")
|
| 900 |
+
if err := os.Mkdir(eoutdir, 0777); err != nil {
|
| 901 |
+
t.Fatalf("can't create outdir %s: %v", eoutdir, err)
|
| 902 |
+
}
|
| 903 |
+
|
| 904 |
+
// Run various operations (merge, dump, textfmt, and so on)
|
| 905 |
+
// using the empty directory. We're not interested in the output
|
| 906 |
+
// here, just making sure that you can do these runs without
|
| 907 |
+
// any error or crash.
|
| 908 |
+
|
| 909 |
+
scenarios := []struct {
|
| 910 |
+
tag string
|
| 911 |
+
args []string
|
| 912 |
+
exp string
|
| 913 |
+
}{
|
| 914 |
+
{
|
| 915 |
+
tag: "input missing",
|
| 916 |
+
args: []string{"merge", "-o", eoutdir, "-i", "not there"},
|
| 917 |
+
exp: "error: reading inputs: ",
|
| 918 |
+
},
|
| 919 |
+
{
|
| 920 |
+
tag: "badv",
|
| 921 |
+
args: []string{"textfmt", "-i", outdir, "-v=abc"},
|
| 922 |
+
},
|
| 923 |
+
}
|
| 924 |
+
|
| 925 |
+
for _, x := range scenarios {
|
| 926 |
+
args := append([]string{}, x.args...)
|
| 927 |
+
if false {
|
| 928 |
+
t.Logf("cmd is %s %v\n", s.tool, args)
|
| 929 |
+
}
|
| 930 |
+
cmd := testenv.Command(t, s.tool, args...)
|
| 931 |
+
b, err := cmd.CombinedOutput()
|
| 932 |
+
if err == nil {
|
| 933 |
+
t.Logf("%% output: %s\n", string(b))
|
| 934 |
+
t.Fatalf("command %s %+v unexpectedly succeeded",
|
| 935 |
+
s.tool, x.args)
|
| 936 |
+
} else {
|
| 937 |
+
if !strings.Contains(string(b), x.exp) {
|
| 938 |
+
t.Fatalf("command %s %+v:\ngot:\n%s\nwanted to see: %v\n",
|
| 939 |
+
s.tool, x.args, string(b), x.exp)
|
| 940 |
+
}
|
| 941 |
+
}
|
| 942 |
+
}
|
| 943 |
+
}
|
go/src/cmd/cover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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
package main_test
|
| 6 |
+
|
| 7 |
+
import (
|
| 8 |
+
"cmd/internal/cov/covcmd"
|
| 9 |
+
"encoding/json"
|
| 10 |
+
"fmt"
|
| 11 |
+
"internal/testenv"
|
| 12 |
+
"os"
|
| 13 |
+
"path/filepath"
|
| 14 |
+
"strings"
|
| 15 |
+
"testing"
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
func writeFile(t *testing.T, path string, contents []byte) {
|
| 19 |
+
if err := os.WriteFile(path, contents, 0666); err != nil {
|
| 20 |
+
t.Fatalf("os.WriteFile(%s) failed: %v", path, err)
|
| 21 |
+
}
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
func writePkgConfig(t *testing.T, outdir, tag, ppath, pname string, gran string, mpath string) string {
|
| 25 |
+
incfg := filepath.Join(outdir, tag+"incfg.txt")
|
| 26 |
+
outcfg := filepath.Join(outdir, "outcfg.txt")
|
| 27 |
+
p := covcmd.CoverPkgConfig{
|
| 28 |
+
PkgPath: ppath,
|
| 29 |
+
PkgName: pname,
|
| 30 |
+
Granularity: gran,
|
| 31 |
+
OutConfig: outcfg,
|
| 32 |
+
EmitMetaFile: mpath,
|
| 33 |
+
}
|
| 34 |
+
data, err := json.Marshal(p)
|
| 35 |
+
if err != nil {
|
| 36 |
+
t.Fatalf("json.Marshal failed: %v", err)
|
| 37 |
+
}
|
| 38 |
+
writeFile(t, incfg, data)
|
| 39 |
+
return incfg
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
func writeOutFileList(t *testing.T, infiles []string, outdir, tag string) ([]string, string) {
|
| 43 |
+
outfilelist := filepath.Join(outdir, tag+"outfilelist.txt")
|
| 44 |
+
var sb strings.Builder
|
| 45 |
+
cv := filepath.Join(outdir, "covervars.go")
|
| 46 |
+
outfs := []string{cv}
|
| 47 |
+
fmt.Fprintf(&sb, "%s\n", cv)
|
| 48 |
+
for _, inf := range infiles {
|
| 49 |
+
base := filepath.Base(inf)
|
| 50 |
+
of := filepath.Join(outdir, tag+".cov."+base)
|
| 51 |
+
outfs = append(outfs, of)
|
| 52 |
+
fmt.Fprintf(&sb, "%s\n", of)
|
| 53 |
+
}
|
| 54 |
+
if err := os.WriteFile(outfilelist, []byte(sb.String()), 0666); err != nil {
|
| 55 |
+
t.Fatalf("writing %s: %v", outfilelist, err)
|
| 56 |
+
}
|
| 57 |
+
return outfs, outfilelist
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
func runPkgCover(t *testing.T, outdir string, tag string, incfg string, mode string, infiles []string, errExpected bool) ([]string, string, string) {
|
| 61 |
+
// Write the pkgcfg file.
|
| 62 |
+
outcfg := filepath.Join(outdir, "outcfg.txt")
|
| 63 |
+
|
| 64 |
+
// Form up the arguments and run the tool.
|
| 65 |
+
outfiles, outfilelist := writeOutFileList(t, infiles, outdir, tag)
|
| 66 |
+
args := []string{"-pkgcfg", incfg, "-mode=" + mode, "-var=var" + tag, "-outfilelist", outfilelist}
|
| 67 |
+
args = append(args, infiles...)
|
| 68 |
+
cmd := testenv.Command(t, testcover(t), args...)
|
| 69 |
+
if errExpected {
|
| 70 |
+
errmsg := runExpectingError(cmd, t)
|
| 71 |
+
return nil, "", errmsg
|
| 72 |
+
} else {
|
| 73 |
+
run(cmd, t)
|
| 74 |
+
return outfiles, outcfg, ""
|
| 75 |
+
}
|
| 76 |
+
}
|
| 77 |
+
|
| 78 |
+
func TestCoverWithCfg(t *testing.T) {
|
| 79 |
+
testenv.MustHaveGoRun(t)
|
| 80 |
+
|
| 81 |
+
t.Parallel()
|
| 82 |
+
|
| 83 |
+
// Subdir in testdata that has our input files of interest.
|
| 84 |
+
tpath := filepath.Join("testdata", "pkgcfg")
|
| 85 |
+
dir := tempDir(t)
|
| 86 |
+
instdira := filepath.Join(dir, "insta")
|
| 87 |
+
if err := os.Mkdir(instdira, 0777); err != nil {
|
| 88 |
+
t.Fatal(err)
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
scenarios := []struct {
|
| 92 |
+
mode, gran string
|
| 93 |
+
}{
|
| 94 |
+
{
|
| 95 |
+
mode: "count",
|
| 96 |
+
gran: "perblock",
|
| 97 |
+
},
|
| 98 |
+
{
|
| 99 |
+
mode: "set",
|
| 100 |
+
gran: "perfunc",
|
| 101 |
+
},
|
| 102 |
+
{
|
| 103 |
+
mode: "regonly",
|
| 104 |
+
gran: "perblock",
|
| 105 |
+
},
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
var incfg string
|
| 109 |
+
apkgfiles := []string{filepath.Join(tpath, "a", "a.go")}
|
| 110 |
+
for _, scenario := range scenarios {
|
| 111 |
+
// Instrument package "a", producing a set of instrumented output
|
| 112 |
+
// files and an 'output config' file to pass on to the compiler.
|
| 113 |
+
ppath := "cfg/a"
|
| 114 |
+
pname := "a"
|
| 115 |
+
mode := scenario.mode
|
| 116 |
+
gran := scenario.gran
|
| 117 |
+
tag := mode + "_" + gran
|
| 118 |
+
incfg = writePkgConfig(t, instdira, tag, ppath, pname, gran, "")
|
| 119 |
+
ofs, outcfg, _ := runPkgCover(t, instdira, tag, incfg, mode,
|
| 120 |
+
apkgfiles, false)
|
| 121 |
+
t.Logf("outfiles: %+v\n", ofs)
|
| 122 |
+
|
| 123 |
+
// Run the compiler on the files to make sure the result is
|
| 124 |
+
// buildable.
|
| 125 |
+
bargs := []string{"tool", "compile", "-p", "a", "-coveragecfg", outcfg}
|
| 126 |
+
bargs = append(bargs, ofs...)
|
| 127 |
+
cmd := testenv.Command(t, testenv.GoToolPath(t), bargs...)
|
| 128 |
+
cmd.Dir = instdira
|
| 129 |
+
run(cmd, t)
|
| 130 |
+
}
|
| 131 |
+
|
| 132 |
+
// Do some error testing to ensure that various bad options and
|
| 133 |
+
// combinations are properly rejected.
|
| 134 |
+
|
| 135 |
+
// Expect error if config file inaccessible/unreadable.
|
| 136 |
+
mode := "atomic"
|
| 137 |
+
errExpected := true
|
| 138 |
+
tag := "errors"
|
| 139 |
+
_, _, errmsg := runPkgCover(t, instdira, tag, "/not/a/file", mode,
|
| 140 |
+
apkgfiles, errExpected)
|
| 141 |
+
want := "error reading pkgconfig file"
|
| 142 |
+
if !strings.Contains(errmsg, want) {
|
| 143 |
+
t.Errorf("'bad config file' test: wanted %s got %s", want, errmsg)
|
| 144 |
+
}
|
| 145 |
+
|
| 146 |
+
// Expect err if config file contains unknown stuff.
|
| 147 |
+
t.Logf("mangling in config")
|
| 148 |
+
writeFile(t, incfg, []byte("blah=foo\n"))
|
| 149 |
+
_, _, errmsg = runPkgCover(t, instdira, tag, incfg, mode,
|
| 150 |
+
apkgfiles, errExpected)
|
| 151 |
+
want = "error reading pkgconfig file"
|
| 152 |
+
if !strings.Contains(errmsg, want) {
|
| 153 |
+
t.Errorf("'bad config file' test: wanted %s got %s", want, errmsg)
|
| 154 |
+
}
|
| 155 |
+
|
| 156 |
+
// Expect error on empty config file.
|
| 157 |
+
t.Logf("writing empty config")
|
| 158 |
+
writeFile(t, incfg, []byte("\n"))
|
| 159 |
+
_, _, errmsg = runPkgCover(t, instdira, tag, incfg, mode,
|
| 160 |
+
apkgfiles, errExpected)
|
| 161 |
+
if !strings.Contains(errmsg, want) {
|
| 162 |
+
t.Errorf("'bad config file' test: wanted %s got %s", want, errmsg)
|
| 163 |
+
}
|
| 164 |
+
}
|
| 165 |
+
|
| 166 |
+
func TestCoverOnPackageWithNoTestFiles(t *testing.T) {
|
| 167 |
+
testenv.MustHaveGoRun(t)
|
| 168 |
+
|
| 169 |
+
// For packages with no test files, the new "go test -cover"
|
| 170 |
+
// strategy is to run cmd/cover on the package in a special
|
| 171 |
+
// "EmitMetaFile" mode. When running in this mode, cmd/cover walks
|
| 172 |
+
// the package doing instrumentation, but when finished, instead of
|
| 173 |
+
// writing out instrumented source files, it directly emits a
|
| 174 |
+
// meta-data file for the package in question, essentially
|
| 175 |
+
// simulating the effect that you would get if you added a dummy
|
| 176 |
+
// "no-op" x_test.go file and then did a build and run of the test.
|
| 177 |
+
|
| 178 |
+
t.Run("YesFuncsNoTests", func(t *testing.T) {
|
| 179 |
+
testCoverNoTestsYesFuncs(t)
|
| 180 |
+
})
|
| 181 |
+
t.Run("NoFuncsNoTests", func(t *testing.T) {
|
| 182 |
+
testCoverNoTestsNoFuncs(t)
|
| 183 |
+
})
|
| 184 |
+
}
|
| 185 |
+
|
| 186 |
+
func testCoverNoTestsYesFuncs(t *testing.T) {
|
| 187 |
+
t.Parallel()
|
| 188 |
+
dir := tempDir(t)
|
| 189 |
+
|
| 190 |
+
// Run the cover command with "emit meta" enabled on a package
|
| 191 |
+
// with functions but no test files.
|
| 192 |
+
tpath := filepath.Join("testdata", "pkgcfg")
|
| 193 |
+
pkg1files := []string{filepath.Join(tpath, "yesFuncsNoTests", "yfnt.go")}
|
| 194 |
+
ppath := "cfg/yesFuncsNoTests"
|
| 195 |
+
pname := "yesFuncsNoTests"
|
| 196 |
+
mode := "count"
|
| 197 |
+
gran := "perblock"
|
| 198 |
+
tag := mode + "_" + gran
|
| 199 |
+
instdir := filepath.Join(dir, "inst")
|
| 200 |
+
if err := os.Mkdir(instdir, 0777); err != nil {
|
| 201 |
+
t.Fatal(err)
|
| 202 |
+
}
|
| 203 |
+
mdir := filepath.Join(dir, "meta")
|
| 204 |
+
if err := os.Mkdir(mdir, 0777); err != nil {
|
| 205 |
+
t.Fatal(err)
|
| 206 |
+
}
|
| 207 |
+
mpath := filepath.Join(mdir, "covmeta.xxx")
|
| 208 |
+
incfg := writePkgConfig(t, instdir, tag, ppath, pname, gran, mpath)
|
| 209 |
+
_, _, errmsg := runPkgCover(t, instdir, tag, incfg, mode,
|
| 210 |
+
pkg1files, false)
|
| 211 |
+
if errmsg != "" {
|
| 212 |
+
t.Fatalf("runPkgCover err: %q", errmsg)
|
| 213 |
+
}
|
| 214 |
+
|
| 215 |
+
// Check for existence of meta-data file.
|
| 216 |
+
if inf, err := os.Open(mpath); err != nil {
|
| 217 |
+
t.Fatalf("meta-data file not created: %v", err)
|
| 218 |
+
} else {
|
| 219 |
+
inf.Close()
|
| 220 |
+
}
|
| 221 |
+
|
| 222 |
+
// Make sure it is digestible.
|
| 223 |
+
cdargs := []string{"tool", "covdata", "percent", "-i", mdir}
|
| 224 |
+
cmd := testenv.Command(t, testenv.GoToolPath(t), cdargs...)
|
| 225 |
+
run(cmd, t)
|
| 226 |
+
}
|
| 227 |
+
|
| 228 |
+
func testCoverNoTestsNoFuncs(t *testing.T) {
|
| 229 |
+
t.Parallel()
|
| 230 |
+
dir := tempDir(t)
|
| 231 |
+
|
| 232 |
+
// Run the cover command with "emit meta" enabled on a package
|
| 233 |
+
// with no functions and no test files.
|
| 234 |
+
tpath := filepath.Join("testdata", "pkgcfg")
|
| 235 |
+
pkgfiles := []string{filepath.Join(tpath, "noFuncsNoTests", "nfnt.go")}
|
| 236 |
+
pname := "noFuncsNoTests"
|
| 237 |
+
mode := "count"
|
| 238 |
+
gran := "perblock"
|
| 239 |
+
ppath := "cfg/" + pname
|
| 240 |
+
tag := mode + "_" + gran
|
| 241 |
+
instdir := filepath.Join(dir, "inst2")
|
| 242 |
+
if err := os.Mkdir(instdir, 0777); err != nil {
|
| 243 |
+
t.Fatal(err)
|
| 244 |
+
}
|
| 245 |
+
mdir := filepath.Join(dir, "meta2")
|
| 246 |
+
if err := os.Mkdir(mdir, 0777); err != nil {
|
| 247 |
+
t.Fatal(err)
|
| 248 |
+
}
|
| 249 |
+
mpath := filepath.Join(mdir, "covmeta.yyy")
|
| 250 |
+
incfg := writePkgConfig(t, instdir, tag, ppath, pname, gran, mpath)
|
| 251 |
+
_, _, errmsg := runPkgCover(t, instdir, tag, incfg, mode,
|
| 252 |
+
pkgfiles, false)
|
| 253 |
+
if errmsg != "" {
|
| 254 |
+
t.Fatalf("runPkgCover err: %q", errmsg)
|
| 255 |
+
}
|
| 256 |
+
|
| 257 |
+
// We expect to see an empty meta-data file in this case.
|
| 258 |
+
if inf, err := os.Open(mpath); err != nil {
|
| 259 |
+
t.Fatalf("opening meta-data file: error %v", err)
|
| 260 |
+
} else {
|
| 261 |
+
defer inf.Close()
|
| 262 |
+
fi, err := inf.Stat()
|
| 263 |
+
if err != nil {
|
| 264 |
+
t.Fatalf("stat meta-data file: %v", err)
|
| 265 |
+
}
|
| 266 |
+
if fi.Size() != 0 {
|
| 267 |
+
t.Fatalf("want zero-sized meta-data file got size %d",
|
| 268 |
+
fi.Size())
|
| 269 |
+
}
|
| 270 |
+
}
|
| 271 |
+
}
|
go/src/cmd/cover/cover.go
ADDED
|
@@ -0,0 +1,1211 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Copyright 2013 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 |
+
package main
|
| 6 |
+
|
| 7 |
+
import (
|
| 8 |
+
"bytes"
|
| 9 |
+
"cmd/internal/cov/covcmd"
|
| 10 |
+
"cmp"
|
| 11 |
+
"encoding/json"
|
| 12 |
+
"flag"
|
| 13 |
+
"fmt"
|
| 14 |
+
"go/ast"
|
| 15 |
+
"go/parser"
|
| 16 |
+
"go/token"
|
| 17 |
+
"internal/coverage"
|
| 18 |
+
"internal/coverage/encodemeta"
|
| 19 |
+
"internal/coverage/slicewriter"
|
| 20 |
+
"io"
|
| 21 |
+
"log"
|
| 22 |
+
"os"
|
| 23 |
+
"path/filepath"
|
| 24 |
+
"slices"
|
| 25 |
+
"strconv"
|
| 26 |
+
"strings"
|
| 27 |
+
|
| 28 |
+
"cmd/internal/edit"
|
| 29 |
+
"cmd/internal/objabi"
|
| 30 |
+
"cmd/internal/telemetry/counter"
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
const usageMessage = "" +
|
| 34 |
+
`Usage of 'go tool cover':
|
| 35 |
+
Given a coverage profile produced by 'go test':
|
| 36 |
+
go test -coverprofile=c.out
|
| 37 |
+
|
| 38 |
+
Open a web browser displaying annotated source code:
|
| 39 |
+
go tool cover -html=c.out
|
| 40 |
+
|
| 41 |
+
Write out an HTML file instead of launching a web browser:
|
| 42 |
+
go tool cover -html=c.out -o coverage.html
|
| 43 |
+
|
| 44 |
+
Display coverage percentages to stdout for each function:
|
| 45 |
+
go tool cover -func=c.out
|
| 46 |
+
|
| 47 |
+
Finally, to generate modified source code with coverage annotations
|
| 48 |
+
for a package (what go test -cover does):
|
| 49 |
+
go tool cover -mode=set -var=CoverageVariableName \
|
| 50 |
+
-pkgcfg=<config> -outfilelist=<file> file1.go ... fileN.go
|
| 51 |
+
|
| 52 |
+
where -pkgcfg points to a file containing the package path,
|
| 53 |
+
package name, module path, and related info from "go build",
|
| 54 |
+
and -outfilelist points to a file containing the filenames
|
| 55 |
+
of the instrumented output files (one per input file).
|
| 56 |
+
See https://pkg.go.dev/cmd/internal/cov/covcmd#CoverPkgConfig for
|
| 57 |
+
more on the package config.
|
| 58 |
+
`
|
| 59 |
+
|
| 60 |
+
func usage() {
|
| 61 |
+
fmt.Fprint(os.Stderr, usageMessage)
|
| 62 |
+
fmt.Fprintln(os.Stderr, "\nFlags:")
|
| 63 |
+
flag.PrintDefaults()
|
| 64 |
+
fmt.Fprintln(os.Stderr, "\n Only one of -html, -func, or -mode may be set.")
|
| 65 |
+
os.Exit(2)
|
| 66 |
+
}
|
| 67 |
+
|
| 68 |
+
var (
|
| 69 |
+
mode = flag.String("mode", "", "coverage mode: set, count, atomic")
|
| 70 |
+
varVar = flag.String("var", "GoCover", "name of coverage variable to generate")
|
| 71 |
+
output = flag.String("o", "", "file for output")
|
| 72 |
+
outfilelist = flag.String("outfilelist", "", "file containing list of output files (one per line) if -pkgcfg is in use")
|
| 73 |
+
htmlOut = flag.String("html", "", "generate HTML representation of coverage profile")
|
| 74 |
+
funcOut = flag.String("func", "", "output coverage profile information for each function")
|
| 75 |
+
pkgcfg = flag.String("pkgcfg", "", "enable full-package instrumentation mode using params from specified config file")
|
| 76 |
+
pkgconfig covcmd.CoverPkgConfig
|
| 77 |
+
outputfiles []string // list of *.cover.go instrumented outputs to write, one per input (set when -pkgcfg is in use)
|
| 78 |
+
profile string // The profile to read; the value of -html or -func
|
| 79 |
+
counterStmt func(*File, string) string
|
| 80 |
+
covervarsoutfile string // an additional Go source file into which we'll write definitions of coverage counter variables + meta data variables (set when -pkgcfg is in use).
|
| 81 |
+
cmode coverage.CounterMode
|
| 82 |
+
cgran coverage.CounterGranularity
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
const (
|
| 86 |
+
atomicPackagePath = "sync/atomic"
|
| 87 |
+
atomicPackageName = "_cover_atomic_"
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
func main() {
|
| 91 |
+
counter.Open()
|
| 92 |
+
|
| 93 |
+
objabi.AddVersionFlag()
|
| 94 |
+
flag.Usage = usage
|
| 95 |
+
objabi.Flagparse(usage)
|
| 96 |
+
counter.Inc("cover/invocations")
|
| 97 |
+
counter.CountFlags("cover/flag:", *flag.CommandLine)
|
| 98 |
+
|
| 99 |
+
// Usage information when no arguments.
|
| 100 |
+
if flag.NFlag() == 0 && flag.NArg() == 0 {
|
| 101 |
+
flag.Usage()
|
| 102 |
+
}
|
| 103 |
+
|
| 104 |
+
err := parseFlags()
|
| 105 |
+
if err != nil {
|
| 106 |
+
fmt.Fprintln(os.Stderr, err)
|
| 107 |
+
fmt.Fprintln(os.Stderr, `For usage information, run "go tool cover -help"`)
|
| 108 |
+
os.Exit(2)
|
| 109 |
+
}
|
| 110 |
+
|
| 111 |
+
// Generate coverage-annotated source.
|
| 112 |
+
if *mode != "" {
|
| 113 |
+
annotate(flag.Args())
|
| 114 |
+
return
|
| 115 |
+
}
|
| 116 |
+
|
| 117 |
+
// Output HTML or function coverage information.
|
| 118 |
+
if *htmlOut != "" {
|
| 119 |
+
err = htmlOutput(profile, *output)
|
| 120 |
+
} else {
|
| 121 |
+
err = funcOutput(profile, *output)
|
| 122 |
+
}
|
| 123 |
+
|
| 124 |
+
if err != nil {
|
| 125 |
+
fmt.Fprintf(os.Stderr, "cover: %v\n", err)
|
| 126 |
+
os.Exit(2)
|
| 127 |
+
}
|
| 128 |
+
}
|
| 129 |
+
|
| 130 |
+
// parseFlags sets the profile and counterStmt globals and performs validations.
|
| 131 |
+
func parseFlags() error {
|
| 132 |
+
profile = *htmlOut
|
| 133 |
+
if *funcOut != "" {
|
| 134 |
+
if profile != "" {
|
| 135 |
+
return fmt.Errorf("too many options")
|
| 136 |
+
}
|
| 137 |
+
profile = *funcOut
|
| 138 |
+
}
|
| 139 |
+
|
| 140 |
+
// Must either display a profile or rewrite Go source.
|
| 141 |
+
if (profile == "") == (*mode == "") {
|
| 142 |
+
return fmt.Errorf("too many options")
|
| 143 |
+
}
|
| 144 |
+
|
| 145 |
+
if *varVar != "" && !token.IsIdentifier(*varVar) {
|
| 146 |
+
return fmt.Errorf("-var: %q is not a valid identifier", *varVar)
|
| 147 |
+
}
|
| 148 |
+
|
| 149 |
+
if *mode != "" {
|
| 150 |
+
switch *mode {
|
| 151 |
+
case "set":
|
| 152 |
+
counterStmt = setCounterStmt
|
| 153 |
+
cmode = coverage.CtrModeSet
|
| 154 |
+
case "count":
|
| 155 |
+
counterStmt = incCounterStmt
|
| 156 |
+
cmode = coverage.CtrModeCount
|
| 157 |
+
case "atomic":
|
| 158 |
+
counterStmt = atomicCounterStmt
|
| 159 |
+
cmode = coverage.CtrModeAtomic
|
| 160 |
+
case "regonly":
|
| 161 |
+
counterStmt = nil
|
| 162 |
+
cmode = coverage.CtrModeRegOnly
|
| 163 |
+
case "testmain":
|
| 164 |
+
counterStmt = nil
|
| 165 |
+
cmode = coverage.CtrModeTestMain
|
| 166 |
+
default:
|
| 167 |
+
return fmt.Errorf("unknown -mode %v", *mode)
|
| 168 |
+
}
|
| 169 |
+
|
| 170 |
+
if flag.NArg() == 0 {
|
| 171 |
+
return fmt.Errorf("missing source file(s)")
|
| 172 |
+
} else {
|
| 173 |
+
if *pkgcfg != "" {
|
| 174 |
+
if *output != "" {
|
| 175 |
+
return fmt.Errorf("please use '-outfilelist' flag instead of '-o'")
|
| 176 |
+
}
|
| 177 |
+
var err error
|
| 178 |
+
if outputfiles, err = readOutFileList(*outfilelist); err != nil {
|
| 179 |
+
return err
|
| 180 |
+
}
|
| 181 |
+
covervarsoutfile = outputfiles[0]
|
| 182 |
+
outputfiles = outputfiles[1:]
|
| 183 |
+
numInputs := len(flag.Args())
|
| 184 |
+
numOutputs := len(outputfiles)
|
| 185 |
+
if numOutputs != numInputs {
|
| 186 |
+
return fmt.Errorf("number of output files (%d) not equal to number of input files (%d)", numOutputs, numInputs)
|
| 187 |
+
}
|
| 188 |
+
if err := readPackageConfig(*pkgcfg); err != nil {
|
| 189 |
+
return err
|
| 190 |
+
}
|
| 191 |
+
return nil
|
| 192 |
+
} else {
|
| 193 |
+
if *outfilelist != "" {
|
| 194 |
+
return fmt.Errorf("'-outfilelist' flag applicable only when -pkgcfg used")
|
| 195 |
+
}
|
| 196 |
+
}
|
| 197 |
+
if flag.NArg() == 1 {
|
| 198 |
+
return nil
|
| 199 |
+
}
|
| 200 |
+
}
|
| 201 |
+
} else if flag.NArg() == 0 {
|
| 202 |
+
return nil
|
| 203 |
+
}
|
| 204 |
+
return fmt.Errorf("too many arguments")
|
| 205 |
+
}
|
| 206 |
+
|
| 207 |
+
func readOutFileList(path string) ([]string, error) {
|
| 208 |
+
data, err := os.ReadFile(path)
|
| 209 |
+
if err != nil {
|
| 210 |
+
return nil, fmt.Errorf("error reading -outfilelist file %q: %v", path, err)
|
| 211 |
+
}
|
| 212 |
+
return strings.Split(strings.TrimSpace(string(data)), "\n"), nil
|
| 213 |
+
}
|
| 214 |
+
|
| 215 |
+
func readPackageConfig(path string) error {
|
| 216 |
+
data, err := os.ReadFile(path)
|
| 217 |
+
if err != nil {
|
| 218 |
+
return fmt.Errorf("error reading pkgconfig file %q: %v", path, err)
|
| 219 |
+
}
|
| 220 |
+
if err := json.Unmarshal(data, &pkgconfig); err != nil {
|
| 221 |
+
return fmt.Errorf("error reading pkgconfig file %q: %v", path, err)
|
| 222 |
+
}
|
| 223 |
+
switch pkgconfig.Granularity {
|
| 224 |
+
case "perblock":
|
| 225 |
+
cgran = coverage.CtrGranularityPerBlock
|
| 226 |
+
case "perfunc":
|
| 227 |
+
cgran = coverage.CtrGranularityPerFunc
|
| 228 |
+
default:
|
| 229 |
+
return fmt.Errorf(`%s: pkgconfig requires perblock/perfunc value`, path)
|
| 230 |
+
}
|
| 231 |
+
return nil
|
| 232 |
+
}
|
| 233 |
+
|
| 234 |
+
// Block represents the information about a basic block to be recorded in the analysis.
|
| 235 |
+
// Note: Our definition of basic block is based on control structures; we don't break
|
| 236 |
+
// apart && and ||. We could but it doesn't seem important enough to bother.
|
| 237 |
+
type Block struct {
|
| 238 |
+
startByte token.Pos
|
| 239 |
+
endByte token.Pos
|
| 240 |
+
numStmt int
|
| 241 |
+
}
|
| 242 |
+
|
| 243 |
+
// Package holds package-specific state.
|
| 244 |
+
type Package struct {
|
| 245 |
+
mdb *encodemeta.CoverageMetaDataBuilder
|
| 246 |
+
counterLengths []int
|
| 247 |
+
}
|
| 248 |
+
|
| 249 |
+
// Function holds func-specific state.
|
| 250 |
+
type Func struct {
|
| 251 |
+
units []coverage.CoverableUnit
|
| 252 |
+
counterVar string
|
| 253 |
+
}
|
| 254 |
+
|
| 255 |
+
// File is a wrapper for the state of a file used in the parser.
|
| 256 |
+
// The basic parse tree walker is a method of this type.
|
| 257 |
+
type File struct {
|
| 258 |
+
fset *token.FileSet
|
| 259 |
+
name string // Name of file.
|
| 260 |
+
astFile *ast.File
|
| 261 |
+
blocks []Block
|
| 262 |
+
content []byte
|
| 263 |
+
edit *edit.Buffer
|
| 264 |
+
mdb *encodemeta.CoverageMetaDataBuilder
|
| 265 |
+
fn Func
|
| 266 |
+
pkg *Package
|
| 267 |
+
}
|
| 268 |
+
|
| 269 |
+
// findText finds text in the original source, starting at pos.
|
| 270 |
+
// It correctly skips over comments and assumes it need not
|
| 271 |
+
// handle quoted strings.
|
| 272 |
+
// It returns a byte offset within f.src.
|
| 273 |
+
func (f *File) findText(pos token.Pos, text string) int {
|
| 274 |
+
b := []byte(text)
|
| 275 |
+
start := f.offset(pos)
|
| 276 |
+
i := start
|
| 277 |
+
s := f.content
|
| 278 |
+
for i < len(s) {
|
| 279 |
+
if bytes.HasPrefix(s[i:], b) {
|
| 280 |
+
return i
|
| 281 |
+
}
|
| 282 |
+
if i+2 <= len(s) && s[i] == '/' && s[i+1] == '/' {
|
| 283 |
+
for i < len(s) && s[i] != '\n' {
|
| 284 |
+
i++
|
| 285 |
+
}
|
| 286 |
+
continue
|
| 287 |
+
}
|
| 288 |
+
if i+2 <= len(s) && s[i] == '/' && s[i+1] == '*' {
|
| 289 |
+
for i += 2; ; i++ {
|
| 290 |
+
if i+2 > len(s) {
|
| 291 |
+
return 0
|
| 292 |
+
}
|
| 293 |
+
if s[i] == '*' && s[i+1] == '/' {
|
| 294 |
+
i += 2
|
| 295 |
+
break
|
| 296 |
+
}
|
| 297 |
+
}
|
| 298 |
+
continue
|
| 299 |
+
}
|
| 300 |
+
i++
|
| 301 |
+
}
|
| 302 |
+
return -1
|
| 303 |
+
}
|
| 304 |
+
|
| 305 |
+
// Visit implements the ast.Visitor interface.
|
| 306 |
+
func (f *File) Visit(node ast.Node) ast.Visitor {
|
| 307 |
+
switch n := node.(type) {
|
| 308 |
+
case *ast.BlockStmt:
|
| 309 |
+
// If it's a switch or select, the body is a list of case clauses; don't tag the block itself.
|
| 310 |
+
if len(n.List) > 0 {
|
| 311 |
+
switch n.List[0].(type) {
|
| 312 |
+
case *ast.CaseClause: // switch
|
| 313 |
+
for _, n := range n.List {
|
| 314 |
+
clause := n.(*ast.CaseClause)
|
| 315 |
+
f.addCounters(clause.Colon+1, clause.Colon+1, clause.End(), clause.Body, false)
|
| 316 |
+
}
|
| 317 |
+
return f
|
| 318 |
+
case *ast.CommClause: // select
|
| 319 |
+
for _, n := range n.List {
|
| 320 |
+
clause := n.(*ast.CommClause)
|
| 321 |
+
f.addCounters(clause.Colon+1, clause.Colon+1, clause.End(), clause.Body, false)
|
| 322 |
+
}
|
| 323 |
+
return f
|
| 324 |
+
}
|
| 325 |
+
}
|
| 326 |
+
f.addCounters(n.Lbrace, n.Lbrace+1, n.Rbrace+1, n.List, true) // +1 to step past closing brace.
|
| 327 |
+
case *ast.IfStmt:
|
| 328 |
+
if n.Init != nil {
|
| 329 |
+
ast.Walk(f, n.Init)
|
| 330 |
+
}
|
| 331 |
+
ast.Walk(f, n.Cond)
|
| 332 |
+
ast.Walk(f, n.Body)
|
| 333 |
+
if n.Else == nil {
|
| 334 |
+
return nil
|
| 335 |
+
}
|
| 336 |
+
// The elses are special, because if we have
|
| 337 |
+
// if x {
|
| 338 |
+
// } else if y {
|
| 339 |
+
// }
|
| 340 |
+
// we want to cover the "if y". To do this, we need a place to drop the counter,
|
| 341 |
+
// so we add a hidden block:
|
| 342 |
+
// if x {
|
| 343 |
+
// } else {
|
| 344 |
+
// if y {
|
| 345 |
+
// }
|
| 346 |
+
// }
|
| 347 |
+
elseOffset := f.findText(n.Body.End(), "else")
|
| 348 |
+
if elseOffset < 0 {
|
| 349 |
+
panic("lost else")
|
| 350 |
+
}
|
| 351 |
+
f.edit.Insert(elseOffset+4, "{")
|
| 352 |
+
f.edit.Insert(f.offset(n.Else.End()), "}")
|
| 353 |
+
|
| 354 |
+
// We just created a block, now walk it.
|
| 355 |
+
// Adjust the position of the new block to start after
|
| 356 |
+
// the "else". That will cause it to follow the "{"
|
| 357 |
+
// we inserted above.
|
| 358 |
+
pos := f.fset.File(n.Body.End()).Pos(elseOffset + 4)
|
| 359 |
+
switch stmt := n.Else.(type) {
|
| 360 |
+
case *ast.IfStmt:
|
| 361 |
+
block := &ast.BlockStmt{
|
| 362 |
+
Lbrace: pos,
|
| 363 |
+
List: []ast.Stmt{stmt},
|
| 364 |
+
Rbrace: stmt.End(),
|
| 365 |
+
}
|
| 366 |
+
n.Else = block
|
| 367 |
+
case *ast.BlockStmt:
|
| 368 |
+
stmt.Lbrace = pos
|
| 369 |
+
default:
|
| 370 |
+
panic("unexpected node type in if")
|
| 371 |
+
}
|
| 372 |
+
ast.Walk(f, n.Else)
|
| 373 |
+
return nil
|
| 374 |
+
case *ast.SelectStmt:
|
| 375 |
+
// Don't annotate an empty select - creates a syntax error.
|
| 376 |
+
if n.Body == nil || len(n.Body.List) == 0 {
|
| 377 |
+
return nil
|
| 378 |
+
}
|
| 379 |
+
case *ast.SwitchStmt:
|
| 380 |
+
// Don't annotate an empty switch - creates a syntax error.
|
| 381 |
+
if n.Body == nil || len(n.Body.List) == 0 {
|
| 382 |
+
if n.Init != nil {
|
| 383 |
+
ast.Walk(f, n.Init)
|
| 384 |
+
}
|
| 385 |
+
if n.Tag != nil {
|
| 386 |
+
ast.Walk(f, n.Tag)
|
| 387 |
+
}
|
| 388 |
+
return nil
|
| 389 |
+
}
|
| 390 |
+
case *ast.TypeSwitchStmt:
|
| 391 |
+
// Don't annotate an empty type switch - creates a syntax error.
|
| 392 |
+
if n.Body == nil || len(n.Body.List) == 0 {
|
| 393 |
+
if n.Init != nil {
|
| 394 |
+
ast.Walk(f, n.Init)
|
| 395 |
+
}
|
| 396 |
+
ast.Walk(f, n.Assign)
|
| 397 |
+
return nil
|
| 398 |
+
}
|
| 399 |
+
case *ast.FuncDecl:
|
| 400 |
+
// Don't annotate functions with blank names - they cannot be executed.
|
| 401 |
+
// Similarly for bodyless funcs.
|
| 402 |
+
if n.Name.Name == "_" || n.Body == nil {
|
| 403 |
+
return nil
|
| 404 |
+
}
|
| 405 |
+
fname := n.Name.Name
|
| 406 |
+
// Skip AddUint32 and StoreUint32 if we're instrumenting
|
| 407 |
+
// sync/atomic itself in atomic mode (out of an abundance of
|
| 408 |
+
// caution), since as part of the instrumentation process we
|
| 409 |
+
// add calls to AddUint32/StoreUint32, and we don't want to
|
| 410 |
+
// somehow create an infinite loop.
|
| 411 |
+
//
|
| 412 |
+
// Note that in the current implementation (Go 1.20) both
|
| 413 |
+
// routines are assembly stubs that forward calls to the
|
| 414 |
+
// internal/runtime/atomic equivalents, hence the infinite
|
| 415 |
+
// loop scenario is purely theoretical (maybe if in some
|
| 416 |
+
// future implementation one of these functions might be
|
| 417 |
+
// written in Go). See #57445 for more details.
|
| 418 |
+
if atomicOnAtomic() && (fname == "AddUint32" || fname == "StoreUint32") {
|
| 419 |
+
return nil
|
| 420 |
+
}
|
| 421 |
+
// Determine proper function or method name.
|
| 422 |
+
if r := n.Recv; r != nil && len(r.List) == 1 {
|
| 423 |
+
t := r.List[0].Type
|
| 424 |
+
star := ""
|
| 425 |
+
if p, _ := t.(*ast.StarExpr); p != nil {
|
| 426 |
+
t = p.X
|
| 427 |
+
star = "*"
|
| 428 |
+
}
|
| 429 |
+
if p, _ := t.(*ast.Ident); p != nil {
|
| 430 |
+
fname = star + p.Name + "." + fname
|
| 431 |
+
}
|
| 432 |
+
}
|
| 433 |
+
walkBody := true
|
| 434 |
+
if *pkgcfg != "" {
|
| 435 |
+
f.preFunc(n, fname)
|
| 436 |
+
if pkgconfig.Granularity == "perfunc" {
|
| 437 |
+
walkBody = false
|
| 438 |
+
}
|
| 439 |
+
}
|
| 440 |
+
if walkBody {
|
| 441 |
+
ast.Walk(f, n.Body)
|
| 442 |
+
}
|
| 443 |
+
if *pkgcfg != "" {
|
| 444 |
+
flit := false
|
| 445 |
+
f.postFunc(n, fname, flit, n.Body)
|
| 446 |
+
}
|
| 447 |
+
return nil
|
| 448 |
+
case *ast.FuncLit:
|
| 449 |
+
// For function literals enclosed in functions, just glom the
|
| 450 |
+
// code for the literal in with the enclosing function (for now).
|
| 451 |
+
if f.fn.counterVar != "" {
|
| 452 |
+
return f
|
| 453 |
+
}
|
| 454 |
+
|
| 455 |
+
// Hack: function literals aren't named in the go/ast representation,
|
| 456 |
+
// and we don't know what name the compiler will choose. For now,
|
| 457 |
+
// just make up a descriptive name.
|
| 458 |
+
pos := n.Pos()
|
| 459 |
+
p := f.fset.File(pos).Position(pos)
|
| 460 |
+
fname := fmt.Sprintf("func.L%d.C%d", p.Line, p.Column)
|
| 461 |
+
if *pkgcfg != "" {
|
| 462 |
+
f.preFunc(n, fname)
|
| 463 |
+
}
|
| 464 |
+
if pkgconfig.Granularity != "perfunc" {
|
| 465 |
+
ast.Walk(f, n.Body)
|
| 466 |
+
}
|
| 467 |
+
if *pkgcfg != "" {
|
| 468 |
+
flit := true
|
| 469 |
+
f.postFunc(n, fname, flit, n.Body)
|
| 470 |
+
}
|
| 471 |
+
return nil
|
| 472 |
+
}
|
| 473 |
+
return f
|
| 474 |
+
}
|
| 475 |
+
|
| 476 |
+
func mkCounterVarName(idx int) string {
|
| 477 |
+
return fmt.Sprintf("%s_%d", *varVar, idx)
|
| 478 |
+
}
|
| 479 |
+
|
| 480 |
+
func mkPackageIdVar() string {
|
| 481 |
+
return *varVar + "P"
|
| 482 |
+
}
|
| 483 |
+
|
| 484 |
+
func mkMetaVar() string {
|
| 485 |
+
return *varVar + "M"
|
| 486 |
+
}
|
| 487 |
+
|
| 488 |
+
func mkPackageIdExpression() string {
|
| 489 |
+
ppath := pkgconfig.PkgPath
|
| 490 |
+
if hcid := coverage.HardCodedPkgID(ppath); hcid != -1 {
|
| 491 |
+
return fmt.Sprintf("uint32(%d)", uint32(hcid))
|
| 492 |
+
}
|
| 493 |
+
return mkPackageIdVar()
|
| 494 |
+
}
|
| 495 |
+
|
| 496 |
+
func (f *File) preFunc(fn ast.Node, fname string) {
|
| 497 |
+
f.fn.units = f.fn.units[:0]
|
| 498 |
+
|
| 499 |
+
// create a new counter variable for this function.
|
| 500 |
+
cv := mkCounterVarName(len(f.pkg.counterLengths))
|
| 501 |
+
f.fn.counterVar = cv
|
| 502 |
+
}
|
| 503 |
+
|
| 504 |
+
func (f *File) postFunc(fn ast.Node, funcname string, flit bool, body *ast.BlockStmt) {
|
| 505 |
+
|
| 506 |
+
// Tack on single counter write if we are in "perfunc" mode.
|
| 507 |
+
singleCtr := ""
|
| 508 |
+
if pkgconfig.Granularity == "perfunc" {
|
| 509 |
+
singleCtr = "; " + f.newCounter(fn.Pos(), fn.Pos(), 1)
|
| 510 |
+
}
|
| 511 |
+
|
| 512 |
+
// record the length of the counter var required.
|
| 513 |
+
nc := len(f.fn.units) + coverage.FirstCtrOffset
|
| 514 |
+
f.pkg.counterLengths = append(f.pkg.counterLengths, nc)
|
| 515 |
+
|
| 516 |
+
// FIXME: for windows, do we want "\" and not "/"? Need to test here.
|
| 517 |
+
// Currently filename is formed as packagepath + "/" + basename.
|
| 518 |
+
fnpos := f.fset.Position(fn.Pos())
|
| 519 |
+
ppath := pkgconfig.PkgPath
|
| 520 |
+
filename := ppath + "/" + filepath.Base(fnpos.Filename)
|
| 521 |
+
|
| 522 |
+
// The convention for cmd/cover is that if the go command that
|
| 523 |
+
// kicks off coverage specifies a local import path (e.g. "go test
|
| 524 |
+
// -cover ./thispackage"), the tool will capture full pathnames
|
| 525 |
+
// for source files instead of relative paths, which tend to work
|
| 526 |
+
// more smoothly for "go tool cover -html". See also issue #56433
|
| 527 |
+
// for more details.
|
| 528 |
+
if pkgconfig.Local {
|
| 529 |
+
filename = f.name
|
| 530 |
+
}
|
| 531 |
+
|
| 532 |
+
// Hand off function to meta-data builder.
|
| 533 |
+
fd := coverage.FuncDesc{
|
| 534 |
+
Funcname: funcname,
|
| 535 |
+
Srcfile: filename,
|
| 536 |
+
Units: f.fn.units,
|
| 537 |
+
Lit: flit,
|
| 538 |
+
}
|
| 539 |
+
funcId := f.mdb.AddFunc(fd)
|
| 540 |
+
|
| 541 |
+
hookWrite := func(cv string, which int, val string) string {
|
| 542 |
+
return fmt.Sprintf("%s[%d] = %s", cv, which, val)
|
| 543 |
+
}
|
| 544 |
+
if *mode == "atomic" {
|
| 545 |
+
hookWrite = func(cv string, which int, val string) string {
|
| 546 |
+
return fmt.Sprintf("%sStoreUint32(&%s[%d], %s)",
|
| 547 |
+
atomicPackagePrefix(), cv, which, val)
|
| 548 |
+
}
|
| 549 |
+
}
|
| 550 |
+
|
| 551 |
+
// Generate the registration hook sequence for the function. This
|
| 552 |
+
// sequence looks like
|
| 553 |
+
//
|
| 554 |
+
// counterVar[0] = <num_units>
|
| 555 |
+
// counterVar[1] = pkgId
|
| 556 |
+
// counterVar[2] = fnId
|
| 557 |
+
//
|
| 558 |
+
cv := f.fn.counterVar
|
| 559 |
+
regHook := hookWrite(cv, 0, strconv.Itoa(len(f.fn.units))) + " ; " +
|
| 560 |
+
hookWrite(cv, 1, mkPackageIdExpression()) + " ; " +
|
| 561 |
+
hookWrite(cv, 2, strconv.Itoa(int(funcId))) + singleCtr
|
| 562 |
+
|
| 563 |
+
// Insert the registration sequence into the function. We want this sequence to
|
| 564 |
+
// appear before any counter updates, so use a hack to ensure that this edit
|
| 565 |
+
// applies before the edit corresponding to the prolog counter update.
|
| 566 |
+
|
| 567 |
+
boff := f.offset(body.Pos())
|
| 568 |
+
ipos := f.fset.File(body.Pos()).Pos(boff)
|
| 569 |
+
ip := f.offset(ipos)
|
| 570 |
+
f.edit.Replace(ip, ip+1, string(f.content[ipos-1])+regHook+" ; ")
|
| 571 |
+
|
| 572 |
+
f.fn.counterVar = ""
|
| 573 |
+
}
|
| 574 |
+
|
| 575 |
+
func annotate(names []string) {
|
| 576 |
+
var p *Package
|
| 577 |
+
if *pkgcfg != "" {
|
| 578 |
+
pp := pkgconfig.PkgPath
|
| 579 |
+
pn := pkgconfig.PkgName
|
| 580 |
+
mp := pkgconfig.ModulePath
|
| 581 |
+
mdb, err := encodemeta.NewCoverageMetaDataBuilder(pp, pn, mp)
|
| 582 |
+
if err != nil {
|
| 583 |
+
log.Fatalf("creating coverage meta-data builder: %v\n", err)
|
| 584 |
+
}
|
| 585 |
+
p = &Package{
|
| 586 |
+
mdb: mdb,
|
| 587 |
+
}
|
| 588 |
+
}
|
| 589 |
+
// TODO: process files in parallel here if it matters.
|
| 590 |
+
for k, name := range names {
|
| 591 |
+
if strings.ContainsAny(name, "\r\n") {
|
| 592 |
+
// annotateFile uses '//line' directives, which don't permit newlines.
|
| 593 |
+
log.Fatalf("cover: input path contains newline character: %q", name)
|
| 594 |
+
}
|
| 595 |
+
|
| 596 |
+
fd := os.Stdout
|
| 597 |
+
isStdout := true
|
| 598 |
+
if *pkgcfg != "" {
|
| 599 |
+
var err error
|
| 600 |
+
fd, err = os.Create(outputfiles[k])
|
| 601 |
+
if err != nil {
|
| 602 |
+
log.Fatalf("cover: %s", err)
|
| 603 |
+
}
|
| 604 |
+
isStdout = false
|
| 605 |
+
} else if *output != "" {
|
| 606 |
+
var err error
|
| 607 |
+
fd, err = os.Create(*output)
|
| 608 |
+
if err != nil {
|
| 609 |
+
log.Fatalf("cover: %s", err)
|
| 610 |
+
}
|
| 611 |
+
isStdout = false
|
| 612 |
+
}
|
| 613 |
+
p.annotateFile(name, fd)
|
| 614 |
+
if !isStdout {
|
| 615 |
+
if err := fd.Close(); err != nil {
|
| 616 |
+
log.Fatalf("cover: %s", err)
|
| 617 |
+
}
|
| 618 |
+
}
|
| 619 |
+
}
|
| 620 |
+
|
| 621 |
+
if *pkgcfg != "" {
|
| 622 |
+
fd, err := os.Create(covervarsoutfile)
|
| 623 |
+
if err != nil {
|
| 624 |
+
log.Fatalf("cover: %s", err)
|
| 625 |
+
}
|
| 626 |
+
p.emitMetaData(fd)
|
| 627 |
+
if err := fd.Close(); err != nil {
|
| 628 |
+
log.Fatalf("cover: %s", err)
|
| 629 |
+
}
|
| 630 |
+
}
|
| 631 |
+
}
|
| 632 |
+
|
| 633 |
+
func (p *Package) annotateFile(name string, fd io.Writer) {
|
| 634 |
+
fset := token.NewFileSet()
|
| 635 |
+
content, err := os.ReadFile(name)
|
| 636 |
+
if err != nil {
|
| 637 |
+
log.Fatalf("cover: %s: %s", name, err)
|
| 638 |
+
}
|
| 639 |
+
parsedFile, err := parser.ParseFile(fset, name, content, parser.ParseComments)
|
| 640 |
+
if err != nil {
|
| 641 |
+
log.Fatalf("cover: %s: %s", name, err)
|
| 642 |
+
}
|
| 643 |
+
|
| 644 |
+
file := &File{
|
| 645 |
+
fset: fset,
|
| 646 |
+
name: name,
|
| 647 |
+
content: content,
|
| 648 |
+
edit: edit.NewBuffer(content),
|
| 649 |
+
astFile: parsedFile,
|
| 650 |
+
}
|
| 651 |
+
if p != nil {
|
| 652 |
+
file.mdb = p.mdb
|
| 653 |
+
file.pkg = p
|
| 654 |
+
}
|
| 655 |
+
|
| 656 |
+
if *mode == "atomic" {
|
| 657 |
+
// Add import of sync/atomic immediately after package clause.
|
| 658 |
+
// We do this even if there is an existing import, because the
|
| 659 |
+
// existing import may be shadowed at any given place we want
|
| 660 |
+
// to refer to it, and our name (_cover_atomic_) is less likely to
|
| 661 |
+
// be shadowed. The one exception is if we're visiting the
|
| 662 |
+
// sync/atomic package itself, in which case we can refer to
|
| 663 |
+
// functions directly without an import prefix. See also #57445.
|
| 664 |
+
if pkgconfig.PkgPath != "sync/atomic" {
|
| 665 |
+
file.edit.Insert(file.offset(file.astFile.Name.End()),
|
| 666 |
+
fmt.Sprintf("; import %s %q", atomicPackageName, atomicPackagePath))
|
| 667 |
+
}
|
| 668 |
+
}
|
| 669 |
+
if pkgconfig.PkgName == "main" {
|
| 670 |
+
file.edit.Insert(file.offset(file.astFile.Name.End()),
|
| 671 |
+
"; import _ \"runtime/coverage\"")
|
| 672 |
+
}
|
| 673 |
+
|
| 674 |
+
if counterStmt != nil {
|
| 675 |
+
ast.Walk(file, file.astFile)
|
| 676 |
+
}
|
| 677 |
+
newContent := file.edit.Bytes()
|
| 678 |
+
|
| 679 |
+
if strings.ContainsAny(name, "\r\n") {
|
| 680 |
+
// This should have been checked by the caller already, but we double check
|
| 681 |
+
// here just to be sure we haven't missed a caller somewhere.
|
| 682 |
+
panic(fmt.Sprintf("annotateFile: name contains unexpected newline character: %q", name))
|
| 683 |
+
}
|
| 684 |
+
fmt.Fprintf(fd, "//line %s:1:1\n", name)
|
| 685 |
+
fd.Write(newContent)
|
| 686 |
+
|
| 687 |
+
// After printing the source tree, add some declarations for the
|
| 688 |
+
// counters etc. We could do this by adding to the tree, but it's
|
| 689 |
+
// easier just to print the text.
|
| 690 |
+
file.addVariables(fd)
|
| 691 |
+
|
| 692 |
+
// Emit a reference to the atomic package to avoid
|
| 693 |
+
// import and not used error when there's no code in a file.
|
| 694 |
+
if *mode == "atomic" {
|
| 695 |
+
fmt.Fprintf(fd, "\nvar _ = %sLoadUint32\n", atomicPackagePrefix())
|
| 696 |
+
}
|
| 697 |
+
}
|
| 698 |
+
|
| 699 |
+
// setCounterStmt returns the expression: __count[23] = 1.
|
| 700 |
+
func setCounterStmt(f *File, counter string) string {
|
| 701 |
+
return fmt.Sprintf("%s = 1", counter)
|
| 702 |
+
}
|
| 703 |
+
|
| 704 |
+
// incCounterStmt returns the expression: __count[23]++.
|
| 705 |
+
func incCounterStmt(f *File, counter string) string {
|
| 706 |
+
return fmt.Sprintf("%s++", counter)
|
| 707 |
+
}
|
| 708 |
+
|
| 709 |
+
// atomicCounterStmt returns the expression: atomic.AddUint32(&__count[23], 1)
|
| 710 |
+
func atomicCounterStmt(f *File, counter string) string {
|
| 711 |
+
return fmt.Sprintf("%sAddUint32(&%s, 1)", atomicPackagePrefix(), counter)
|
| 712 |
+
}
|
| 713 |
+
|
| 714 |
+
// newCounter creates a new counter expression of the appropriate form.
|
| 715 |
+
func (f *File) newCounter(start, end token.Pos, numStmt int) string {
|
| 716 |
+
var stmt string
|
| 717 |
+
if *pkgcfg != "" {
|
| 718 |
+
slot := len(f.fn.units) + coverage.FirstCtrOffset
|
| 719 |
+
if f.fn.counterVar == "" {
|
| 720 |
+
panic("internal error: counter var unset")
|
| 721 |
+
}
|
| 722 |
+
stmt = counterStmt(f, fmt.Sprintf("%s[%d]", f.fn.counterVar, slot))
|
| 723 |
+
stpos := f.fset.Position(start)
|
| 724 |
+
enpos := f.fset.Position(end)
|
| 725 |
+
stpos, enpos = dedup(stpos, enpos)
|
| 726 |
+
unit := coverage.CoverableUnit{
|
| 727 |
+
StLine: uint32(stpos.Line),
|
| 728 |
+
StCol: uint32(stpos.Column),
|
| 729 |
+
EnLine: uint32(enpos.Line),
|
| 730 |
+
EnCol: uint32(enpos.Column),
|
| 731 |
+
NxStmts: uint32(numStmt),
|
| 732 |
+
}
|
| 733 |
+
f.fn.units = append(f.fn.units, unit)
|
| 734 |
+
} else {
|
| 735 |
+
stmt = counterStmt(f, fmt.Sprintf("%s.Count[%d]", *varVar,
|
| 736 |
+
len(f.blocks)))
|
| 737 |
+
f.blocks = append(f.blocks, Block{start, end, numStmt})
|
| 738 |
+
}
|
| 739 |
+
return stmt
|
| 740 |
+
}
|
| 741 |
+
|
| 742 |
+
// addCounters takes a list of statements and adds counters to the beginning of
|
| 743 |
+
// each basic block at the top level of that list. For instance, given
|
| 744 |
+
//
|
| 745 |
+
// S1
|
| 746 |
+
// if cond {
|
| 747 |
+
// S2
|
| 748 |
+
// }
|
| 749 |
+
// S3
|
| 750 |
+
//
|
| 751 |
+
// counters will be added before S1 and before S3. The block containing S2
|
| 752 |
+
// will be visited in a separate call.
|
| 753 |
+
// TODO: Nested simple blocks get unnecessary (but correct) counters
|
| 754 |
+
func (f *File) addCounters(pos, insertPos, blockEnd token.Pos, list []ast.Stmt, extendToClosingBrace bool) {
|
| 755 |
+
// Special case: make sure we add a counter to an empty block. Can't do this below
|
| 756 |
+
// or we will add a counter to an empty statement list after, say, a return statement.
|
| 757 |
+
if len(list) == 0 {
|
| 758 |
+
f.edit.Insert(f.offset(insertPos), f.newCounter(insertPos, blockEnd, 0)+";")
|
| 759 |
+
return
|
| 760 |
+
}
|
| 761 |
+
// Make a copy of the list, as we may mutate it and should leave the
|
| 762 |
+
// existing list intact.
|
| 763 |
+
list = append([]ast.Stmt(nil), list...)
|
| 764 |
+
// We have a block (statement list), but it may have several basic blocks due to the
|
| 765 |
+
// appearance of statements that affect the flow of control.
|
| 766 |
+
for {
|
| 767 |
+
// Find first statement that affects flow of control (break, continue, if, etc.).
|
| 768 |
+
// It will be the last statement of this basic block.
|
| 769 |
+
var last int
|
| 770 |
+
end := blockEnd
|
| 771 |
+
for last = 0; last < len(list); last++ {
|
| 772 |
+
stmt := list[last]
|
| 773 |
+
end = f.statementBoundary(stmt)
|
| 774 |
+
if f.endsBasicSourceBlock(stmt) {
|
| 775 |
+
// If it is a labeled statement, we need to place a counter between
|
| 776 |
+
// the label and its statement because it may be the target of a goto
|
| 777 |
+
// and thus start a basic block. That is, given
|
| 778 |
+
// foo: stmt
|
| 779 |
+
// we need to create
|
| 780 |
+
// foo: ; stmt
|
| 781 |
+
// and mark the label as a block-terminating statement.
|
| 782 |
+
// The result will then be
|
| 783 |
+
// foo: COUNTER[n]++; stmt
|
| 784 |
+
// However, we can't do this if the labeled statement is already
|
| 785 |
+
// a control statement, such as a labeled for.
|
| 786 |
+
if label, isLabel := stmt.(*ast.LabeledStmt); isLabel && !f.isControl(label.Stmt) {
|
| 787 |
+
newLabel := *label
|
| 788 |
+
newLabel.Stmt = &ast.EmptyStmt{
|
| 789 |
+
Semicolon: label.Stmt.Pos(),
|
| 790 |
+
Implicit: true,
|
| 791 |
+
}
|
| 792 |
+
end = label.Pos() // Previous block ends before the label.
|
| 793 |
+
list[last] = &newLabel
|
| 794 |
+
// Open a gap and drop in the old statement, now without a label.
|
| 795 |
+
list = append(list, nil)
|
| 796 |
+
copy(list[last+1:], list[last:])
|
| 797 |
+
list[last+1] = label.Stmt
|
| 798 |
+
}
|
| 799 |
+
last++
|
| 800 |
+
extendToClosingBrace = false // Block is broken up now.
|
| 801 |
+
break
|
| 802 |
+
}
|
| 803 |
+
}
|
| 804 |
+
if extendToClosingBrace {
|
| 805 |
+
end = blockEnd
|
| 806 |
+
}
|
| 807 |
+
if pos != end { // Can have no source to cover if e.g. blocks abut.
|
| 808 |
+
f.edit.Insert(f.offset(insertPos), f.newCounter(pos, end, last)+";")
|
| 809 |
+
}
|
| 810 |
+
list = list[last:]
|
| 811 |
+
if len(list) == 0 {
|
| 812 |
+
break
|
| 813 |
+
}
|
| 814 |
+
pos = list[0].Pos()
|
| 815 |
+
insertPos = pos
|
| 816 |
+
}
|
| 817 |
+
}
|
| 818 |
+
|
| 819 |
+
// hasFuncLiteral reports the existence and position of the first func literal
|
| 820 |
+
// in the node, if any. If a func literal appears, it usually marks the termination
|
| 821 |
+
// of a basic block because the function body is itself a block.
|
| 822 |
+
// Therefore we draw a line at the start of the body of the first function literal we find.
|
| 823 |
+
// TODO: what if there's more than one? Probably doesn't matter much.
|
| 824 |
+
func hasFuncLiteral(n ast.Node) (bool, token.Pos) {
|
| 825 |
+
if n == nil {
|
| 826 |
+
return false, 0
|
| 827 |
+
}
|
| 828 |
+
var literal funcLitFinder
|
| 829 |
+
ast.Walk(&literal, n)
|
| 830 |
+
return literal.found(), token.Pos(literal)
|
| 831 |
+
}
|
| 832 |
+
|
| 833 |
+
// statementBoundary finds the location in s that terminates the current basic
|
| 834 |
+
// block in the source.
|
| 835 |
+
func (f *File) statementBoundary(s ast.Stmt) token.Pos {
|
| 836 |
+
// Control flow statements are easy.
|
| 837 |
+
switch s := s.(type) {
|
| 838 |
+
case *ast.BlockStmt:
|
| 839 |
+
// Treat blocks like basic blocks to avoid overlapping counters.
|
| 840 |
+
return s.Lbrace
|
| 841 |
+
case *ast.IfStmt:
|
| 842 |
+
found, pos := hasFuncLiteral(s.Init)
|
| 843 |
+
if found {
|
| 844 |
+
return pos
|
| 845 |
+
}
|
| 846 |
+
found, pos = hasFuncLiteral(s.Cond)
|
| 847 |
+
if found {
|
| 848 |
+
return pos
|
| 849 |
+
}
|
| 850 |
+
return s.Body.Lbrace
|
| 851 |
+
case *ast.ForStmt:
|
| 852 |
+
found, pos := hasFuncLiteral(s.Init)
|
| 853 |
+
if found {
|
| 854 |
+
return pos
|
| 855 |
+
}
|
| 856 |
+
found, pos = hasFuncLiteral(s.Cond)
|
| 857 |
+
if found {
|
| 858 |
+
return pos
|
| 859 |
+
}
|
| 860 |
+
found, pos = hasFuncLiteral(s.Post)
|
| 861 |
+
if found {
|
| 862 |
+
return pos
|
| 863 |
+
}
|
| 864 |
+
return s.Body.Lbrace
|
| 865 |
+
case *ast.LabeledStmt:
|
| 866 |
+
return f.statementBoundary(s.Stmt)
|
| 867 |
+
case *ast.RangeStmt:
|
| 868 |
+
found, pos := hasFuncLiteral(s.X)
|
| 869 |
+
if found {
|
| 870 |
+
return pos
|
| 871 |
+
}
|
| 872 |
+
return s.Body.Lbrace
|
| 873 |
+
case *ast.SwitchStmt:
|
| 874 |
+
found, pos := hasFuncLiteral(s.Init)
|
| 875 |
+
if found {
|
| 876 |
+
return pos
|
| 877 |
+
}
|
| 878 |
+
found, pos = hasFuncLiteral(s.Tag)
|
| 879 |
+
if found {
|
| 880 |
+
return pos
|
| 881 |
+
}
|
| 882 |
+
return s.Body.Lbrace
|
| 883 |
+
case *ast.SelectStmt:
|
| 884 |
+
return s.Body.Lbrace
|
| 885 |
+
case *ast.TypeSwitchStmt:
|
| 886 |
+
found, pos := hasFuncLiteral(s.Init)
|
| 887 |
+
if found {
|
| 888 |
+
return pos
|
| 889 |
+
}
|
| 890 |
+
return s.Body.Lbrace
|
| 891 |
+
}
|
| 892 |
+
// If not a control flow statement, it is a declaration, expression, call, etc. and it may have a function literal.
|
| 893 |
+
// If it does, that's tricky because we want to exclude the body of the function from this block.
|
| 894 |
+
// Draw a line at the start of the body of the first function literal we find.
|
| 895 |
+
// TODO: what if there's more than one? Probably doesn't matter much.
|
| 896 |
+
found, pos := hasFuncLiteral(s)
|
| 897 |
+
if found {
|
| 898 |
+
return pos
|
| 899 |
+
}
|
| 900 |
+
return s.End()
|
| 901 |
+
}
|
| 902 |
+
|
| 903 |
+
// endsBasicSourceBlock reports whether s changes the flow of control: break, if, etc.,
|
| 904 |
+
// or if it's just problematic, for instance contains a function literal, which will complicate
|
| 905 |
+
// accounting due to the block-within-an expression.
|
| 906 |
+
func (f *File) endsBasicSourceBlock(s ast.Stmt) bool {
|
| 907 |
+
switch s := s.(type) {
|
| 908 |
+
case *ast.BlockStmt:
|
| 909 |
+
// Treat blocks like basic blocks to avoid overlapping counters.
|
| 910 |
+
return true
|
| 911 |
+
case *ast.BranchStmt:
|
| 912 |
+
return true
|
| 913 |
+
case *ast.ForStmt:
|
| 914 |
+
return true
|
| 915 |
+
case *ast.IfStmt:
|
| 916 |
+
return true
|
| 917 |
+
case *ast.LabeledStmt:
|
| 918 |
+
return true // A goto may branch here, starting a new basic block.
|
| 919 |
+
case *ast.RangeStmt:
|
| 920 |
+
return true
|
| 921 |
+
case *ast.SwitchStmt:
|
| 922 |
+
return true
|
| 923 |
+
case *ast.SelectStmt:
|
| 924 |
+
return true
|
| 925 |
+
case *ast.TypeSwitchStmt:
|
| 926 |
+
return true
|
| 927 |
+
case *ast.ExprStmt:
|
| 928 |
+
// Calls to panic change the flow.
|
| 929 |
+
// We really should verify that "panic" is the predefined function,
|
| 930 |
+
// but without type checking we can't and the likelihood of it being
|
| 931 |
+
// an actual problem is vanishingly small.
|
| 932 |
+
if call, ok := s.X.(*ast.CallExpr); ok {
|
| 933 |
+
if ident, ok := call.Fun.(*ast.Ident); ok && ident.Name == "panic" && len(call.Args) == 1 {
|
| 934 |
+
return true
|
| 935 |
+
}
|
| 936 |
+
}
|
| 937 |
+
}
|
| 938 |
+
found, _ := hasFuncLiteral(s)
|
| 939 |
+
return found
|
| 940 |
+
}
|
| 941 |
+
|
| 942 |
+
// isControl reports whether s is a control statement that, if labeled, cannot be
|
| 943 |
+
// separated from its label.
|
| 944 |
+
func (f *File) isControl(s ast.Stmt) bool {
|
| 945 |
+
switch s.(type) {
|
| 946 |
+
case *ast.ForStmt, *ast.RangeStmt, *ast.SwitchStmt, *ast.SelectStmt, *ast.TypeSwitchStmt:
|
| 947 |
+
return true
|
| 948 |
+
}
|
| 949 |
+
return false
|
| 950 |
+
}
|
| 951 |
+
|
| 952 |
+
// funcLitFinder implements the ast.Visitor pattern to find the location of any
|
| 953 |
+
// function literal in a subtree.
|
| 954 |
+
type funcLitFinder token.Pos
|
| 955 |
+
|
| 956 |
+
func (f *funcLitFinder) Visit(node ast.Node) (w ast.Visitor) {
|
| 957 |
+
if f.found() {
|
| 958 |
+
return nil // Prune search.
|
| 959 |
+
}
|
| 960 |
+
switch n := node.(type) {
|
| 961 |
+
case *ast.FuncLit:
|
| 962 |
+
*f = funcLitFinder(n.Body.Lbrace)
|
| 963 |
+
return nil // Prune search.
|
| 964 |
+
}
|
| 965 |
+
return f
|
| 966 |
+
}
|
| 967 |
+
|
| 968 |
+
func (f *funcLitFinder) found() bool {
|
| 969 |
+
return token.Pos(*f) != token.NoPos
|
| 970 |
+
}
|
| 971 |
+
|
| 972 |
+
// Sort interface for []block1; used for self-check in addVariables.
|
| 973 |
+
|
| 974 |
+
type block1 struct {
|
| 975 |
+
Block
|
| 976 |
+
index int
|
| 977 |
+
}
|
| 978 |
+
|
| 979 |
+
// offset translates a token position into a 0-indexed byte offset.
|
| 980 |
+
func (f *File) offset(pos token.Pos) int {
|
| 981 |
+
return f.fset.Position(pos).Offset
|
| 982 |
+
}
|
| 983 |
+
|
| 984 |
+
// addVariables adds to the end of the file the declarations to set up the counter and position variables.
|
| 985 |
+
func (f *File) addVariables(w io.Writer) {
|
| 986 |
+
if *pkgcfg != "" {
|
| 987 |
+
return
|
| 988 |
+
}
|
| 989 |
+
// Self-check: Verify that the instrumented basic blocks are disjoint.
|
| 990 |
+
t := make([]block1, len(f.blocks))
|
| 991 |
+
for i := range f.blocks {
|
| 992 |
+
t[i].Block = f.blocks[i]
|
| 993 |
+
t[i].index = i
|
| 994 |
+
}
|
| 995 |
+
slices.SortFunc(t, func(a, b block1) int {
|
| 996 |
+
return cmp.Compare(a.startByte, b.startByte)
|
| 997 |
+
})
|
| 998 |
+
for i := 1; i < len(t); i++ {
|
| 999 |
+
if t[i-1].endByte > t[i].startByte {
|
| 1000 |
+
fmt.Fprintf(os.Stderr, "cover: internal error: block %d overlaps block %d\n", t[i-1].index, t[i].index)
|
| 1001 |
+
// Note: error message is in byte positions, not token positions.
|
| 1002 |
+
fmt.Fprintf(os.Stderr, "\t%s:#%d,#%d %s:#%d,#%d\n",
|
| 1003 |
+
f.name, f.offset(t[i-1].startByte), f.offset(t[i-1].endByte),
|
| 1004 |
+
f.name, f.offset(t[i].startByte), f.offset(t[i].endByte))
|
| 1005 |
+
}
|
| 1006 |
+
}
|
| 1007 |
+
|
| 1008 |
+
// Declare the coverage struct as a package-level variable.
|
| 1009 |
+
fmt.Fprintf(w, "\nvar %s = struct {\n", *varVar)
|
| 1010 |
+
fmt.Fprintf(w, "\tCount [%d]uint32\n", len(f.blocks))
|
| 1011 |
+
fmt.Fprintf(w, "\tPos [3 * %d]uint32\n", len(f.blocks))
|
| 1012 |
+
fmt.Fprintf(w, "\tNumStmt [%d]uint16\n", len(f.blocks))
|
| 1013 |
+
fmt.Fprintf(w, "} {\n")
|
| 1014 |
+
|
| 1015 |
+
// Initialize the position array field.
|
| 1016 |
+
fmt.Fprintf(w, "\tPos: [3 * %d]uint32{\n", len(f.blocks))
|
| 1017 |
+
|
| 1018 |
+
// A nice long list of positions. Each position is encoded as follows to reduce size:
|
| 1019 |
+
// - 32-bit starting line number
|
| 1020 |
+
// - 32-bit ending line number
|
| 1021 |
+
// - (16 bit ending column number << 16) | (16-bit starting column number).
|
| 1022 |
+
for i, block := range f.blocks {
|
| 1023 |
+
start := f.fset.Position(block.startByte)
|
| 1024 |
+
end := f.fset.Position(block.endByte)
|
| 1025 |
+
|
| 1026 |
+
start, end = dedup(start, end)
|
| 1027 |
+
|
| 1028 |
+
fmt.Fprintf(w, "\t\t%d, %d, %#x, // [%d]\n", start.Line, end.Line, (end.Column&0xFFFF)<<16|(start.Column&0xFFFF), i)
|
| 1029 |
+
}
|
| 1030 |
+
|
| 1031 |
+
// Close the position array.
|
| 1032 |
+
fmt.Fprintf(w, "\t},\n")
|
| 1033 |
+
|
| 1034 |
+
// Initialize the position array field.
|
| 1035 |
+
fmt.Fprintf(w, "\tNumStmt: [%d]uint16{\n", len(f.blocks))
|
| 1036 |
+
|
| 1037 |
+
// A nice long list of statements-per-block, so we can give a conventional
|
| 1038 |
+
// valuation of "percent covered". To save space, it's a 16-bit number, so we
|
| 1039 |
+
// clamp it if it overflows - won't matter in practice.
|
| 1040 |
+
for i, block := range f.blocks {
|
| 1041 |
+
n := block.numStmt
|
| 1042 |
+
if n > 1<<16-1 {
|
| 1043 |
+
n = 1<<16 - 1
|
| 1044 |
+
}
|
| 1045 |
+
fmt.Fprintf(w, "\t\t%d, // %d\n", n, i)
|
| 1046 |
+
}
|
| 1047 |
+
|
| 1048 |
+
// Close the statements-per-block array.
|
| 1049 |
+
fmt.Fprintf(w, "\t},\n")
|
| 1050 |
+
|
| 1051 |
+
// Close the struct initialization.
|
| 1052 |
+
fmt.Fprintf(w, "}\n")
|
| 1053 |
+
}
|
| 1054 |
+
|
| 1055 |
+
// It is possible for positions to repeat when there is a line
|
| 1056 |
+
// directive that does not specify column information and the input
|
| 1057 |
+
// has not been passed through gofmt.
|
| 1058 |
+
// See issues #27530 and #30746.
|
| 1059 |
+
// Tests are TestHtmlUnformatted and TestLineDup.
|
| 1060 |
+
// We use a map to avoid duplicates.
|
| 1061 |
+
|
| 1062 |
+
// pos2 is a pair of token.Position values, used as a map key type.
|
| 1063 |
+
type pos2 struct {
|
| 1064 |
+
p1, p2 token.Position
|
| 1065 |
+
}
|
| 1066 |
+
|
| 1067 |
+
// seenPos2 tracks whether we have seen a token.Position pair.
|
| 1068 |
+
var seenPos2 = make(map[pos2]bool)
|
| 1069 |
+
|
| 1070 |
+
// dedup takes a token.Position pair and returns a pair that does not
|
| 1071 |
+
// duplicate any existing pair. The returned pair will have the Offset
|
| 1072 |
+
// fields cleared.
|
| 1073 |
+
func dedup(p1, p2 token.Position) (r1, r2 token.Position) {
|
| 1074 |
+
key := pos2{
|
| 1075 |
+
p1: p1,
|
| 1076 |
+
p2: p2,
|
| 1077 |
+
}
|
| 1078 |
+
|
| 1079 |
+
// We want to ignore the Offset fields in the map,
|
| 1080 |
+
// since cover uses only file/line/column.
|
| 1081 |
+
key.p1.Offset = 0
|
| 1082 |
+
key.p2.Offset = 0
|
| 1083 |
+
|
| 1084 |
+
for seenPos2[key] {
|
| 1085 |
+
key.p2.Column++
|
| 1086 |
+
}
|
| 1087 |
+
seenPos2[key] = true
|
| 1088 |
+
|
| 1089 |
+
return key.p1, key.p2
|
| 1090 |
+
}
|
| 1091 |
+
|
| 1092 |
+
func (p *Package) emitMetaData(w io.Writer) {
|
| 1093 |
+
if *pkgcfg == "" {
|
| 1094 |
+
return
|
| 1095 |
+
}
|
| 1096 |
+
|
| 1097 |
+
// If the "EmitMetaFile" path has been set, invoke a helper
|
| 1098 |
+
// that will write out a pre-cooked meta-data file for this package
|
| 1099 |
+
// to the specified location, in effect simulating the execution
|
| 1100 |
+
// of a test binary that doesn't do any testing to speak of.
|
| 1101 |
+
if pkgconfig.EmitMetaFile != "" {
|
| 1102 |
+
p.emitMetaFile(pkgconfig.EmitMetaFile)
|
| 1103 |
+
}
|
| 1104 |
+
|
| 1105 |
+
// Something went wrong if regonly/testmain mode is in effect and
|
| 1106 |
+
// we have instrumented functions.
|
| 1107 |
+
if counterStmt == nil && len(p.counterLengths) != 0 {
|
| 1108 |
+
panic("internal error: seen functions with regonly/testmain")
|
| 1109 |
+
}
|
| 1110 |
+
|
| 1111 |
+
// Emit package name.
|
| 1112 |
+
fmt.Fprintf(w, "\npackage %s\n\n", pkgconfig.PkgName)
|
| 1113 |
+
|
| 1114 |
+
// Emit package ID var.
|
| 1115 |
+
fmt.Fprintf(w, "\nvar %sP uint32\n", *varVar)
|
| 1116 |
+
|
| 1117 |
+
// Emit all of the counter variables.
|
| 1118 |
+
for k := range p.counterLengths {
|
| 1119 |
+
cvn := mkCounterVarName(k)
|
| 1120 |
+
fmt.Fprintf(w, "var %s [%d]uint32\n", cvn, p.counterLengths[k])
|
| 1121 |
+
}
|
| 1122 |
+
|
| 1123 |
+
// Emit encoded meta-data.
|
| 1124 |
+
var sws slicewriter.WriteSeeker
|
| 1125 |
+
digest, err := p.mdb.Emit(&sws)
|
| 1126 |
+
if err != nil {
|
| 1127 |
+
log.Fatalf("encoding meta-data: %v", err)
|
| 1128 |
+
}
|
| 1129 |
+
p.mdb = nil
|
| 1130 |
+
fmt.Fprintf(w, "var %s = [...]byte{\n", mkMetaVar())
|
| 1131 |
+
payload := sws.BytesWritten()
|
| 1132 |
+
for k, b := range payload {
|
| 1133 |
+
fmt.Fprintf(w, " 0x%x,", b)
|
| 1134 |
+
if k != 0 && k%8 == 0 {
|
| 1135 |
+
fmt.Fprintf(w, "\n")
|
| 1136 |
+
}
|
| 1137 |
+
}
|
| 1138 |
+
fmt.Fprintf(w, "}\n")
|
| 1139 |
+
|
| 1140 |
+
fixcfg := covcmd.CoverFixupConfig{
|
| 1141 |
+
Strategy: "normal",
|
| 1142 |
+
MetaVar: mkMetaVar(),
|
| 1143 |
+
MetaLen: len(payload),
|
| 1144 |
+
MetaHash: fmt.Sprintf("%x", digest),
|
| 1145 |
+
PkgIdVar: mkPackageIdVar(),
|
| 1146 |
+
CounterPrefix: *varVar,
|
| 1147 |
+
CounterGranularity: pkgconfig.Granularity,
|
| 1148 |
+
CounterMode: *mode,
|
| 1149 |
+
}
|
| 1150 |
+
fixdata, err := json.Marshal(fixcfg)
|
| 1151 |
+
if err != nil {
|
| 1152 |
+
log.Fatalf("marshal fixupcfg: %v", err)
|
| 1153 |
+
}
|
| 1154 |
+
if err := os.WriteFile(pkgconfig.OutConfig, fixdata, 0666); err != nil {
|
| 1155 |
+
log.Fatalf("error writing %s: %v", pkgconfig.OutConfig, err)
|
| 1156 |
+
}
|
| 1157 |
+
}
|
| 1158 |
+
|
| 1159 |
+
// atomicOnAtomic returns true if we're instrumenting
|
| 1160 |
+
// the sync/atomic package AND using atomic mode.
|
| 1161 |
+
func atomicOnAtomic() bool {
|
| 1162 |
+
return *mode == "atomic" && pkgconfig.PkgPath == "sync/atomic"
|
| 1163 |
+
}
|
| 1164 |
+
|
| 1165 |
+
// atomicPackagePrefix returns the import path prefix used to refer to
|
| 1166 |
+
// our special import of sync/atomic; this is either set to the
|
| 1167 |
+
// constant atomicPackageName plus a dot or the empty string if we're
|
| 1168 |
+
// instrumenting the sync/atomic package itself.
|
| 1169 |
+
func atomicPackagePrefix() string {
|
| 1170 |
+
if atomicOnAtomic() {
|
| 1171 |
+
return ""
|
| 1172 |
+
}
|
| 1173 |
+
return atomicPackageName + "."
|
| 1174 |
+
}
|
| 1175 |
+
|
| 1176 |
+
func (p *Package) emitMetaFile(outpath string) {
|
| 1177 |
+
// Open output file.
|
| 1178 |
+
of, err := os.OpenFile(outpath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
|
| 1179 |
+
if err != nil {
|
| 1180 |
+
log.Fatalf("opening covmeta %s: %v", outpath, err)
|
| 1181 |
+
}
|
| 1182 |
+
|
| 1183 |
+
if len(p.counterLengths) == 0 {
|
| 1184 |
+
// This corresponds to the case where we have no functions
|
| 1185 |
+
// in the package to instrument. Leave the file empty file if
|
| 1186 |
+
// this happens.
|
| 1187 |
+
if err = of.Close(); err != nil {
|
| 1188 |
+
log.Fatalf("closing meta-data file: %v", err)
|
| 1189 |
+
}
|
| 1190 |
+
return
|
| 1191 |
+
}
|
| 1192 |
+
|
| 1193 |
+
// Encode meta-data.
|
| 1194 |
+
var sws slicewriter.WriteSeeker
|
| 1195 |
+
digest, err := p.mdb.Emit(&sws)
|
| 1196 |
+
if err != nil {
|
| 1197 |
+
log.Fatalf("encoding meta-data: %v", err)
|
| 1198 |
+
}
|
| 1199 |
+
payload := sws.BytesWritten()
|
| 1200 |
+
blobs := [][]byte{payload}
|
| 1201 |
+
|
| 1202 |
+
// Write meta-data file directly.
|
| 1203 |
+
mfw := encodemeta.NewCoverageMetaFileWriter(outpath, of)
|
| 1204 |
+
err = mfw.Write(digest, blobs, cmode, cgran)
|
| 1205 |
+
if err != nil {
|
| 1206 |
+
log.Fatalf("writing meta-data file: %v", err)
|
| 1207 |
+
}
|
| 1208 |
+
if err = of.Close(); err != nil {
|
| 1209 |
+
log.Fatalf("closing meta-data file: %v", err)
|
| 1210 |
+
}
|
| 1211 |
+
}
|
go/src/cmd/cover/cover_test.go
ADDED
|
@@ -0,0 +1,640 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Copyright 2013 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 |
+
package main_test
|
| 6 |
+
|
| 7 |
+
import (
|
| 8 |
+
"bufio"
|
| 9 |
+
"bytes"
|
| 10 |
+
cmdcover "cmd/cover"
|
| 11 |
+
"flag"
|
| 12 |
+
"fmt"
|
| 13 |
+
"go/ast"
|
| 14 |
+
"go/parser"
|
| 15 |
+
"go/token"
|
| 16 |
+
"internal/testenv"
|
| 17 |
+
"log"
|
| 18 |
+
"os"
|
| 19 |
+
"os/exec"
|
| 20 |
+
"path/filepath"
|
| 21 |
+
"regexp"
|
| 22 |
+
"strings"
|
| 23 |
+
"sync"
|
| 24 |
+
"testing"
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
const (
|
| 28 |
+
// Data directory, also the package directory for the test.
|
| 29 |
+
testdata = "testdata"
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
// testcover returns the path to the cmd/cover binary that we are going to
|
| 33 |
+
// test. At one point this was created via "go build"; we now reuse the unit
|
| 34 |
+
// test executable itself.
|
| 35 |
+
func testcover(t testing.TB) string {
|
| 36 |
+
return testenv.Executable(t)
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
// testTempDir is a temporary directory created in TestMain.
|
| 40 |
+
var testTempDir string
|
| 41 |
+
|
| 42 |
+
// If set, this will preserve all the tmpdir files from the test run.
|
| 43 |
+
var debug = flag.Bool("debug", false, "keep tmpdir files for debugging")
|
| 44 |
+
|
| 45 |
+
// TestMain used here so that we can leverage the test executable
|
| 46 |
+
// itself as a cmd/cover executable; compare to similar usage in
|
| 47 |
+
// the cmd/go tests.
|
| 48 |
+
func TestMain(m *testing.M) {
|
| 49 |
+
if os.Getenv("CMDCOVER_TOOLEXEC") != "" {
|
| 50 |
+
// When CMDCOVER_TOOLEXEC is set, the test binary is also
|
| 51 |
+
// running as a -toolexec wrapper.
|
| 52 |
+
tool := strings.TrimSuffix(filepath.Base(os.Args[1]), ".exe")
|
| 53 |
+
if tool == "cover" {
|
| 54 |
+
// Inject this test binary as cmd/cover in place of the
|
| 55 |
+
// installed tool, so that the go command's invocations of
|
| 56 |
+
// cover produce coverage for the configuration in which
|
| 57 |
+
// the test was built.
|
| 58 |
+
os.Args = os.Args[1:]
|
| 59 |
+
cmdcover.Main()
|
| 60 |
+
} else {
|
| 61 |
+
cmd := exec.Command(os.Args[1], os.Args[2:]...)
|
| 62 |
+
cmd.Stdout = os.Stdout
|
| 63 |
+
cmd.Stderr = os.Stderr
|
| 64 |
+
if err := cmd.Run(); err != nil {
|
| 65 |
+
os.Exit(1)
|
| 66 |
+
}
|
| 67 |
+
}
|
| 68 |
+
os.Exit(0)
|
| 69 |
+
}
|
| 70 |
+
if os.Getenv("CMDCOVER_TEST_RUN_MAIN") != "" {
|
| 71 |
+
// When CMDCOVER_TEST_RUN_MAIN is set, we're reusing the test
|
| 72 |
+
// binary as cmd/cover. In this case we run the main func exported
|
| 73 |
+
// via export_test.go, and exit; CMDCOVER_TEST_RUN_MAIN is set below
|
| 74 |
+
// for actual test invocations.
|
| 75 |
+
cmdcover.Main()
|
| 76 |
+
os.Exit(0)
|
| 77 |
+
}
|
| 78 |
+
flag.Parse()
|
| 79 |
+
topTmpdir, err := os.MkdirTemp("", "cmd-cover-test-")
|
| 80 |
+
if err != nil {
|
| 81 |
+
log.Fatal(err)
|
| 82 |
+
}
|
| 83 |
+
testTempDir = topTmpdir
|
| 84 |
+
if !*debug {
|
| 85 |
+
defer os.RemoveAll(topTmpdir)
|
| 86 |
+
} else {
|
| 87 |
+
fmt.Fprintf(os.Stderr, "debug: preserving tmpdir %s\n", topTmpdir)
|
| 88 |
+
}
|
| 89 |
+
os.Setenv("CMDCOVER_TEST_RUN_MAIN", "normal")
|
| 90 |
+
os.Exit(m.Run())
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
var tdmu sync.Mutex
|
| 94 |
+
var tdcount int
|
| 95 |
+
|
| 96 |
+
func tempDir(t *testing.T) string {
|
| 97 |
+
tdmu.Lock()
|
| 98 |
+
dir := filepath.Join(testTempDir, fmt.Sprintf("%03d", tdcount))
|
| 99 |
+
tdcount++
|
| 100 |
+
if err := os.Mkdir(dir, 0777); err != nil {
|
| 101 |
+
t.Fatal(err)
|
| 102 |
+
}
|
| 103 |
+
defer tdmu.Unlock()
|
| 104 |
+
return dir
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
// TestCoverWithToolExec runs a set of subtests that all make use of a
|
| 108 |
+
// "-toolexec" wrapper program to invoke the cover test executable
|
| 109 |
+
// itself via "go test -cover".
|
| 110 |
+
func TestCoverWithToolExec(t *testing.T) {
|
| 111 |
+
toolexecArg := "-toolexec=" + testcover(t)
|
| 112 |
+
|
| 113 |
+
t.Run("CoverHTML", func(t *testing.T) {
|
| 114 |
+
testCoverHTML(t, toolexecArg)
|
| 115 |
+
})
|
| 116 |
+
t.Run("HtmlUnformatted", func(t *testing.T) {
|
| 117 |
+
testHtmlUnformatted(t, toolexecArg)
|
| 118 |
+
})
|
| 119 |
+
t.Run("FuncWithDuplicateLines", func(t *testing.T) {
|
| 120 |
+
testFuncWithDuplicateLines(t, toolexecArg)
|
| 121 |
+
})
|
| 122 |
+
t.Run("MissingTrailingNewlineIssue58370", func(t *testing.T) {
|
| 123 |
+
testMissingTrailingNewlineIssue58370(t, toolexecArg)
|
| 124 |
+
})
|
| 125 |
+
}
|
| 126 |
+
|
| 127 |
+
// Execute this command sequence:
|
| 128 |
+
//
|
| 129 |
+
// replace the word LINE with the line number < testdata/test.go > testdata/test_line.go
|
| 130 |
+
// testcover -mode=count -var=CoverTest -o ./testdata/test_cover.go testdata/test_line.go
|
| 131 |
+
// go run ./testdata/main.go ./testdata/test.go
|
| 132 |
+
func TestCover(t *testing.T) {
|
| 133 |
+
testenv.MustHaveGoRun(t)
|
| 134 |
+
t.Parallel()
|
| 135 |
+
dir := tempDir(t)
|
| 136 |
+
|
| 137 |
+
// Read in the test file (testTest) and write it, with LINEs specified, to coverInput.
|
| 138 |
+
testTest := filepath.Join(testdata, "test.go")
|
| 139 |
+
file, err := os.ReadFile(testTest)
|
| 140 |
+
if err != nil {
|
| 141 |
+
t.Fatal(err)
|
| 142 |
+
}
|
| 143 |
+
lines := bytes.Split(file, []byte("\n"))
|
| 144 |
+
for i, line := range lines {
|
| 145 |
+
lines[i] = bytes.ReplaceAll(line, []byte("LINE"), []byte(fmt.Sprint(i+1)))
|
| 146 |
+
}
|
| 147 |
+
|
| 148 |
+
// Add a function that is not gofmt'ed. This used to cause a crash.
|
| 149 |
+
// We don't put it in test.go because then we would have to gofmt it.
|
| 150 |
+
// Issue 23927.
|
| 151 |
+
lines = append(lines, []byte("func unFormatted() {"),
|
| 152 |
+
[]byte("\tif true {"),
|
| 153 |
+
[]byte("\t}else{"),
|
| 154 |
+
[]byte("\t}"),
|
| 155 |
+
[]byte("}"))
|
| 156 |
+
lines = append(lines, []byte("func unFormatted2(b bool) {if b{}else{}}"))
|
| 157 |
+
|
| 158 |
+
coverInput := filepath.Join(dir, "test_line.go")
|
| 159 |
+
if err := os.WriteFile(coverInput, bytes.Join(lines, []byte("\n")), 0666); err != nil {
|
| 160 |
+
t.Fatal(err)
|
| 161 |
+
}
|
| 162 |
+
|
| 163 |
+
// testcover -mode=count -var=thisNameMustBeVeryLongToCauseOverflowOfCounterIncrementStatementOntoNextLineForTest -o ./testdata/test_cover.go testdata/test_line.go
|
| 164 |
+
coverOutput := filepath.Join(dir, "test_cover.go")
|
| 165 |
+
cmd := testenv.Command(t, testcover(t), "-mode=count", "-var=thisNameMustBeVeryLongToCauseOverflowOfCounterIncrementStatementOntoNextLineForTest", "-o", coverOutput, coverInput)
|
| 166 |
+
run(cmd, t)
|
| 167 |
+
|
| 168 |
+
cmd = testenv.Command(t, testcover(t), "-mode=set", "-var=Not_an-identifier", "-o", coverOutput, coverInput)
|
| 169 |
+
err = cmd.Run()
|
| 170 |
+
if err == nil {
|
| 171 |
+
t.Error("Expected cover to fail with an error")
|
| 172 |
+
}
|
| 173 |
+
|
| 174 |
+
// Copy testmain to tmpdir, so that it is in the same directory
|
| 175 |
+
// as coverOutput.
|
| 176 |
+
testMain := filepath.Join(testdata, "main.go")
|
| 177 |
+
b, err := os.ReadFile(testMain)
|
| 178 |
+
if err != nil {
|
| 179 |
+
t.Fatal(err)
|
| 180 |
+
}
|
| 181 |
+
tmpTestMain := filepath.Join(dir, "main.go")
|
| 182 |
+
if err := os.WriteFile(tmpTestMain, b, 0444); err != nil {
|
| 183 |
+
t.Fatal(err)
|
| 184 |
+
}
|
| 185 |
+
|
| 186 |
+
// go run ./testdata/main.go ./testdata/test.go
|
| 187 |
+
cmd = testenv.Command(t, testenv.GoToolPath(t), "run", tmpTestMain, coverOutput)
|
| 188 |
+
run(cmd, t)
|
| 189 |
+
|
| 190 |
+
file, err = os.ReadFile(coverOutput)
|
| 191 |
+
if err != nil {
|
| 192 |
+
t.Fatal(err)
|
| 193 |
+
}
|
| 194 |
+
// compiler directive must appear right next to function declaration.
|
| 195 |
+
if got, err := regexp.MatchString(".*\n//go:nosplit\nfunc someFunction().*", string(file)); err != nil || !got {
|
| 196 |
+
t.Error("misplaced compiler directive")
|
| 197 |
+
}
|
| 198 |
+
// "go:linkname" compiler directive should be present.
|
| 199 |
+
if got, err := regexp.MatchString(`.*go\:linkname some\_name some\_name.*`, string(file)); err != nil || !got {
|
| 200 |
+
t.Error("'go:linkname' compiler directive not found")
|
| 201 |
+
}
|
| 202 |
+
|
| 203 |
+
// Other comments should be preserved too.
|
| 204 |
+
c := ".*// This comment didn't appear in generated go code.*"
|
| 205 |
+
if got, err := regexp.MatchString(c, string(file)); err != nil || !got {
|
| 206 |
+
t.Errorf("non compiler directive comment %q not found", c)
|
| 207 |
+
}
|
| 208 |
+
}
|
| 209 |
+
|
| 210 |
+
// TestDirectives checks that compiler directives are preserved and positioned
|
| 211 |
+
// correctly. Directives that occur before top-level declarations should remain
|
| 212 |
+
// above those declarations, even if they are not part of the block of
|
| 213 |
+
// documentation comments.
|
| 214 |
+
func TestDirectives(t *testing.T) {
|
| 215 |
+
testenv.MustHaveExec(t)
|
| 216 |
+
t.Parallel()
|
| 217 |
+
|
| 218 |
+
// Read the source file and find all the directives. We'll keep
|
| 219 |
+
// track of whether each one has been seen in the output.
|
| 220 |
+
testDirectives := filepath.Join(testdata, "directives.go")
|
| 221 |
+
source, err := os.ReadFile(testDirectives)
|
| 222 |
+
if err != nil {
|
| 223 |
+
t.Fatal(err)
|
| 224 |
+
}
|
| 225 |
+
sourceDirectives := findDirectives(source)
|
| 226 |
+
|
| 227 |
+
// testcover -mode=atomic ./testdata/directives.go
|
| 228 |
+
cmd := testenv.Command(t, testcover(t), "-mode=atomic", testDirectives)
|
| 229 |
+
cmd.Stderr = os.Stderr
|
| 230 |
+
output, err := cmd.Output()
|
| 231 |
+
if err != nil {
|
| 232 |
+
t.Fatal(err)
|
| 233 |
+
}
|
| 234 |
+
|
| 235 |
+
// Check that all directives are present in the output.
|
| 236 |
+
outputDirectives := findDirectives(output)
|
| 237 |
+
foundDirective := make(map[string]bool)
|
| 238 |
+
for _, p := range sourceDirectives {
|
| 239 |
+
foundDirective[p.name] = false
|
| 240 |
+
}
|
| 241 |
+
for _, p := range outputDirectives {
|
| 242 |
+
if found, ok := foundDirective[p.name]; !ok {
|
| 243 |
+
t.Errorf("unexpected directive in output: %s", p.text)
|
| 244 |
+
} else if found {
|
| 245 |
+
t.Errorf("directive found multiple times in output: %s", p.text)
|
| 246 |
+
}
|
| 247 |
+
foundDirective[p.name] = true
|
| 248 |
+
}
|
| 249 |
+
for name, found := range foundDirective {
|
| 250 |
+
if !found {
|
| 251 |
+
t.Errorf("missing directive: %s", name)
|
| 252 |
+
}
|
| 253 |
+
}
|
| 254 |
+
|
| 255 |
+
// Check that directives that start with the name of top-level declarations
|
| 256 |
+
// come before the beginning of the named declaration and after the end
|
| 257 |
+
// of the previous declaration.
|
| 258 |
+
fset := token.NewFileSet()
|
| 259 |
+
astFile, err := parser.ParseFile(fset, testDirectives, output, 0)
|
| 260 |
+
if err != nil {
|
| 261 |
+
t.Fatal(err)
|
| 262 |
+
}
|
| 263 |
+
|
| 264 |
+
prevEnd := 0
|
| 265 |
+
for _, decl := range astFile.Decls {
|
| 266 |
+
var name string
|
| 267 |
+
switch d := decl.(type) {
|
| 268 |
+
case *ast.FuncDecl:
|
| 269 |
+
name = d.Name.Name
|
| 270 |
+
case *ast.GenDecl:
|
| 271 |
+
if len(d.Specs) == 0 {
|
| 272 |
+
// An empty group declaration. We still want to check that
|
| 273 |
+
// directives can be associated with it, so we make up a name
|
| 274 |
+
// to match directives in the test data.
|
| 275 |
+
name = "_empty"
|
| 276 |
+
} else if spec, ok := d.Specs[0].(*ast.TypeSpec); ok {
|
| 277 |
+
name = spec.Name.Name
|
| 278 |
+
}
|
| 279 |
+
}
|
| 280 |
+
pos := fset.Position(decl.Pos()).Offset
|
| 281 |
+
end := fset.Position(decl.End()).Offset
|
| 282 |
+
if name == "" {
|
| 283 |
+
prevEnd = end
|
| 284 |
+
continue
|
| 285 |
+
}
|
| 286 |
+
for _, p := range outputDirectives {
|
| 287 |
+
if !strings.HasPrefix(p.name, name) {
|
| 288 |
+
continue
|
| 289 |
+
}
|
| 290 |
+
if p.offset < prevEnd || pos < p.offset {
|
| 291 |
+
t.Errorf("directive %s does not appear before definition %s", p.text, name)
|
| 292 |
+
}
|
| 293 |
+
}
|
| 294 |
+
prevEnd = end
|
| 295 |
+
}
|
| 296 |
+
}
|
| 297 |
+
|
| 298 |
+
type directiveInfo struct {
|
| 299 |
+
text string // full text of the comment, not including newline
|
| 300 |
+
name string // text after //go:
|
| 301 |
+
offset int // byte offset of first slash in comment
|
| 302 |
+
}
|
| 303 |
+
|
| 304 |
+
func findDirectives(source []byte) []directiveInfo {
|
| 305 |
+
var directives []directiveInfo
|
| 306 |
+
directivePrefix := []byte("\n//go:")
|
| 307 |
+
offset := 0
|
| 308 |
+
for {
|
| 309 |
+
i := bytes.Index(source[offset:], directivePrefix)
|
| 310 |
+
if i < 0 {
|
| 311 |
+
break
|
| 312 |
+
}
|
| 313 |
+
i++ // skip newline
|
| 314 |
+
p := source[offset+i:]
|
| 315 |
+
j := bytes.IndexByte(p, '\n')
|
| 316 |
+
if j < 0 {
|
| 317 |
+
// reached EOF
|
| 318 |
+
j = len(p)
|
| 319 |
+
}
|
| 320 |
+
directive := directiveInfo{
|
| 321 |
+
text: string(p[:j]),
|
| 322 |
+
name: string(p[len(directivePrefix)-1 : j]),
|
| 323 |
+
offset: offset + i,
|
| 324 |
+
}
|
| 325 |
+
directives = append(directives, directive)
|
| 326 |
+
offset += i + j
|
| 327 |
+
}
|
| 328 |
+
return directives
|
| 329 |
+
}
|
| 330 |
+
|
| 331 |
+
// Makes sure that `cover -func=profile.cov` reports accurate coverage.
|
| 332 |
+
// Issue #20515.
|
| 333 |
+
func TestCoverFunc(t *testing.T) {
|
| 334 |
+
// testcover -func ./testdata/profile.cov
|
| 335 |
+
coverProfile := filepath.Join(testdata, "profile.cov")
|
| 336 |
+
cmd := testenv.Command(t, testcover(t), "-func", coverProfile)
|
| 337 |
+
out, err := cmd.Output()
|
| 338 |
+
if err != nil {
|
| 339 |
+
if ee, ok := err.(*exec.ExitError); ok {
|
| 340 |
+
t.Logf("%s", ee.Stderr)
|
| 341 |
+
}
|
| 342 |
+
t.Fatal(err)
|
| 343 |
+
}
|
| 344 |
+
|
| 345 |
+
if got, err := regexp.Match(".*total:.*100.0.*", out); err != nil || !got {
|
| 346 |
+
t.Logf("%s", out)
|
| 347 |
+
t.Errorf("invalid coverage counts. got=(%v, %v); want=(true; nil)", got, err)
|
| 348 |
+
}
|
| 349 |
+
}
|
| 350 |
+
|
| 351 |
+
// Check that cover produces correct HTML.
|
| 352 |
+
// Issue #25767.
|
| 353 |
+
func testCoverHTML(t *testing.T, toolexecArg string) {
|
| 354 |
+
testenv.MustHaveGoRun(t)
|
| 355 |
+
dir := tempDir(t)
|
| 356 |
+
|
| 357 |
+
t.Parallel()
|
| 358 |
+
|
| 359 |
+
// go test -coverprofile testdata/html/html.cov cmd/cover/testdata/html
|
| 360 |
+
htmlProfile := filepath.Join(dir, "html.cov")
|
| 361 |
+
cmd := testenv.Command(t, testenv.GoToolPath(t), "test", toolexecArg, "-coverprofile", htmlProfile, "cmd/cover/testdata/html")
|
| 362 |
+
cmd.Env = append(cmd.Environ(), "CMDCOVER_TOOLEXEC=true")
|
| 363 |
+
run(cmd, t)
|
| 364 |
+
// testcover -html testdata/html/html.cov -o testdata/html/html.html
|
| 365 |
+
htmlHTML := filepath.Join(dir, "html.html")
|
| 366 |
+
cmd = testenv.Command(t, testcover(t), "-html", htmlProfile, "-o", htmlHTML)
|
| 367 |
+
run(cmd, t)
|
| 368 |
+
|
| 369 |
+
// Extract the parts of the HTML with comment markers,
|
| 370 |
+
// and compare against a golden file.
|
| 371 |
+
entireHTML, err := os.ReadFile(htmlHTML)
|
| 372 |
+
if err != nil {
|
| 373 |
+
t.Fatal(err)
|
| 374 |
+
}
|
| 375 |
+
var out strings.Builder
|
| 376 |
+
scan := bufio.NewScanner(bytes.NewReader(entireHTML))
|
| 377 |
+
in := false
|
| 378 |
+
for scan.Scan() {
|
| 379 |
+
line := scan.Text()
|
| 380 |
+
if strings.Contains(line, "// START") {
|
| 381 |
+
in = true
|
| 382 |
+
}
|
| 383 |
+
if in {
|
| 384 |
+
fmt.Fprintln(&out, line)
|
| 385 |
+
}
|
| 386 |
+
if strings.Contains(line, "// END") {
|
| 387 |
+
in = false
|
| 388 |
+
}
|
| 389 |
+
}
|
| 390 |
+
if scan.Err() != nil {
|
| 391 |
+
t.Error(scan.Err())
|
| 392 |
+
}
|
| 393 |
+
htmlGolden := filepath.Join(testdata, "html", "html.golden")
|
| 394 |
+
golden, err := os.ReadFile(htmlGolden)
|
| 395 |
+
if err != nil {
|
| 396 |
+
t.Fatalf("reading golden file: %v", err)
|
| 397 |
+
}
|
| 398 |
+
// Ignore white space differences.
|
| 399 |
+
// Break into lines, then compare by breaking into words.
|
| 400 |
+
goldenLines := strings.Split(string(golden), "\n")
|
| 401 |
+
outLines := strings.Split(out.String(), "\n")
|
| 402 |
+
// Compare at the line level, stopping at first different line so
|
| 403 |
+
// we don't generate tons of output if there's an inserted or deleted line.
|
| 404 |
+
for i, goldenLine := range goldenLines {
|
| 405 |
+
if i >= len(outLines) {
|
| 406 |
+
t.Fatalf("output shorter than golden; stops before line %d: %s\n", i+1, goldenLine)
|
| 407 |
+
}
|
| 408 |
+
// Convert all white space to simple spaces, for easy comparison.
|
| 409 |
+
goldenLine = strings.Join(strings.Fields(goldenLine), " ")
|
| 410 |
+
outLine := strings.Join(strings.Fields(outLines[i]), " ")
|
| 411 |
+
if outLine != goldenLine {
|
| 412 |
+
t.Fatalf("line %d differs: got:\n\t%s\nwant:\n\t%s", i+1, outLine, goldenLine)
|
| 413 |
+
}
|
| 414 |
+
}
|
| 415 |
+
if len(goldenLines) != len(outLines) {
|
| 416 |
+
t.Fatalf("output longer than golden; first extra output line %d: %q\n", len(goldenLines)+1, outLines[len(goldenLines)])
|
| 417 |
+
}
|
| 418 |
+
}
|
| 419 |
+
|
| 420 |
+
// Test HTML processing with a source file not run through gofmt.
|
| 421 |
+
// Issue #27350.
|
| 422 |
+
func testHtmlUnformatted(t *testing.T, toolexecArg string) {
|
| 423 |
+
testenv.MustHaveGoRun(t)
|
| 424 |
+
dir := tempDir(t)
|
| 425 |
+
|
| 426 |
+
t.Parallel()
|
| 427 |
+
|
| 428 |
+
htmlUDir := filepath.Join(dir, "htmlunformatted")
|
| 429 |
+
htmlU := filepath.Join(htmlUDir, "htmlunformatted.go")
|
| 430 |
+
htmlUTest := filepath.Join(htmlUDir, "htmlunformatted_test.go")
|
| 431 |
+
htmlUProfile := filepath.Join(htmlUDir, "htmlunformatted.cov")
|
| 432 |
+
htmlUHTML := filepath.Join(htmlUDir, "htmlunformatted.html")
|
| 433 |
+
|
| 434 |
+
if err := os.Mkdir(htmlUDir, 0777); err != nil {
|
| 435 |
+
t.Fatal(err)
|
| 436 |
+
}
|
| 437 |
+
|
| 438 |
+
if err := os.WriteFile(filepath.Join(htmlUDir, "go.mod"), []byte("module htmlunformatted\n"), 0666); err != nil {
|
| 439 |
+
t.Fatal(err)
|
| 440 |
+
}
|
| 441 |
+
|
| 442 |
+
const htmlUContents = `
|
| 443 |
+
package htmlunformatted
|
| 444 |
+
|
| 445 |
+
var g int
|
| 446 |
+
|
| 447 |
+
func F() {
|
| 448 |
+
//line x.go:1
|
| 449 |
+
{ { F(); goto lab } }
|
| 450 |
+
lab:
|
| 451 |
+
}`
|
| 452 |
+
|
| 453 |
+
const htmlUTestContents = `package htmlunformatted`
|
| 454 |
+
|
| 455 |
+
if err := os.WriteFile(htmlU, []byte(htmlUContents), 0444); err != nil {
|
| 456 |
+
t.Fatal(err)
|
| 457 |
+
}
|
| 458 |
+
if err := os.WriteFile(htmlUTest, []byte(htmlUTestContents), 0444); err != nil {
|
| 459 |
+
t.Fatal(err)
|
| 460 |
+
}
|
| 461 |
+
|
| 462 |
+
// go test -covermode=count -coverprofile TMPDIR/htmlunformatted.cov
|
| 463 |
+
cmd := testenv.Command(t, testenv.GoToolPath(t), "test", "-test.v", toolexecArg, "-covermode=count", "-coverprofile", htmlUProfile)
|
| 464 |
+
cmd.Env = append(cmd.Environ(), "CMDCOVER_TOOLEXEC=true")
|
| 465 |
+
cmd.Dir = htmlUDir
|
| 466 |
+
run(cmd, t)
|
| 467 |
+
|
| 468 |
+
// testcover -html TMPDIR/htmlunformatted.cov -o unformatted.html
|
| 469 |
+
cmd = testenv.Command(t, testcover(t), "-html", htmlUProfile, "-o", htmlUHTML)
|
| 470 |
+
cmd.Dir = htmlUDir
|
| 471 |
+
run(cmd, t)
|
| 472 |
+
}
|
| 473 |
+
|
| 474 |
+
// lineDupContents becomes linedup.go in testFuncWithDuplicateLines.
|
| 475 |
+
const lineDupContents = `
|
| 476 |
+
package linedup
|
| 477 |
+
|
| 478 |
+
var G int
|
| 479 |
+
|
| 480 |
+
func LineDup(c int) {
|
| 481 |
+
for i := 0; i < c; i++ {
|
| 482 |
+
//line ld.go:100
|
| 483 |
+
if i % 2 == 0 {
|
| 484 |
+
G++
|
| 485 |
+
}
|
| 486 |
+
if i % 3 == 0 {
|
| 487 |
+
G++; G++
|
| 488 |
+
}
|
| 489 |
+
//line ld.go:100
|
| 490 |
+
if i % 4 == 0 {
|
| 491 |
+
G++; G++; G++
|
| 492 |
+
}
|
| 493 |
+
if i % 5 == 0 {
|
| 494 |
+
G++; G++; G++; G++
|
| 495 |
+
}
|
| 496 |
+
}
|
| 497 |
+
}
|
| 498 |
+
`
|
| 499 |
+
|
| 500 |
+
// lineDupTestContents becomes linedup_test.go in testFuncWithDuplicateLines.
|
| 501 |
+
const lineDupTestContents = `
|
| 502 |
+
package linedup
|
| 503 |
+
|
| 504 |
+
import "testing"
|
| 505 |
+
|
| 506 |
+
func TestLineDup(t *testing.T) {
|
| 507 |
+
LineDup(100)
|
| 508 |
+
}
|
| 509 |
+
`
|
| 510 |
+
|
| 511 |
+
// Test -func with duplicate //line directives with different numbers
|
| 512 |
+
// of statements.
|
| 513 |
+
func testFuncWithDuplicateLines(t *testing.T, toolexecArg string) {
|
| 514 |
+
testenv.MustHaveGoRun(t)
|
| 515 |
+
dir := tempDir(t)
|
| 516 |
+
|
| 517 |
+
t.Parallel()
|
| 518 |
+
|
| 519 |
+
lineDupDir := filepath.Join(dir, "linedup")
|
| 520 |
+
lineDupGo := filepath.Join(lineDupDir, "linedup.go")
|
| 521 |
+
lineDupTestGo := filepath.Join(lineDupDir, "linedup_test.go")
|
| 522 |
+
lineDupProfile := filepath.Join(lineDupDir, "linedup.out")
|
| 523 |
+
|
| 524 |
+
if err := os.Mkdir(lineDupDir, 0777); err != nil {
|
| 525 |
+
t.Fatal(err)
|
| 526 |
+
}
|
| 527 |
+
|
| 528 |
+
if err := os.WriteFile(filepath.Join(lineDupDir, "go.mod"), []byte("module linedup\n"), 0666); err != nil {
|
| 529 |
+
t.Fatal(err)
|
| 530 |
+
}
|
| 531 |
+
if err := os.WriteFile(lineDupGo, []byte(lineDupContents), 0444); err != nil {
|
| 532 |
+
t.Fatal(err)
|
| 533 |
+
}
|
| 534 |
+
if err := os.WriteFile(lineDupTestGo, []byte(lineDupTestContents), 0444); err != nil {
|
| 535 |
+
t.Fatal(err)
|
| 536 |
+
}
|
| 537 |
+
|
| 538 |
+
// go test -cover -covermode count -coverprofile TMPDIR/linedup.out
|
| 539 |
+
cmd := testenv.Command(t, testenv.GoToolPath(t), "test", toolexecArg, "-cover", "-covermode", "count", "-coverprofile", lineDupProfile)
|
| 540 |
+
cmd.Env = append(cmd.Environ(), "CMDCOVER_TOOLEXEC=true")
|
| 541 |
+
cmd.Dir = lineDupDir
|
| 542 |
+
run(cmd, t)
|
| 543 |
+
|
| 544 |
+
// testcover -func=TMPDIR/linedup.out
|
| 545 |
+
cmd = testenv.Command(t, testcover(t), "-func", lineDupProfile)
|
| 546 |
+
cmd.Dir = lineDupDir
|
| 547 |
+
run(cmd, t)
|
| 548 |
+
}
|
| 549 |
+
|
| 550 |
+
func run(c *exec.Cmd, t *testing.T) {
|
| 551 |
+
t.Helper()
|
| 552 |
+
t.Log("running", c.Args)
|
| 553 |
+
out, err := c.CombinedOutput()
|
| 554 |
+
if len(out) > 0 {
|
| 555 |
+
t.Logf("%s", out)
|
| 556 |
+
}
|
| 557 |
+
if err != nil {
|
| 558 |
+
t.Fatal(err)
|
| 559 |
+
}
|
| 560 |
+
}
|
| 561 |
+
|
| 562 |
+
func runExpectingError(c *exec.Cmd, t *testing.T) string {
|
| 563 |
+
t.Helper()
|
| 564 |
+
t.Log("running", c.Args)
|
| 565 |
+
out, err := c.CombinedOutput()
|
| 566 |
+
if err == nil {
|
| 567 |
+
return fmt.Sprintf("unexpected pass for %+v", c.Args)
|
| 568 |
+
}
|
| 569 |
+
return string(out)
|
| 570 |
+
}
|
| 571 |
+
|
| 572 |
+
// Test instrumentation of package that ends before an expected
|
| 573 |
+
// trailing newline following package clause. Issue #58370.
|
| 574 |
+
func testMissingTrailingNewlineIssue58370(t *testing.T, toolexecArg string) {
|
| 575 |
+
testenv.MustHaveGoBuild(t)
|
| 576 |
+
dir := tempDir(t)
|
| 577 |
+
|
| 578 |
+
t.Parallel()
|
| 579 |
+
|
| 580 |
+
noeolDir := filepath.Join(dir, "issue58370")
|
| 581 |
+
noeolGo := filepath.Join(noeolDir, "noeol.go")
|
| 582 |
+
noeolTestGo := filepath.Join(noeolDir, "noeol_test.go")
|
| 583 |
+
|
| 584 |
+
if err := os.Mkdir(noeolDir, 0777); err != nil {
|
| 585 |
+
t.Fatal(err)
|
| 586 |
+
}
|
| 587 |
+
|
| 588 |
+
if err := os.WriteFile(filepath.Join(noeolDir, "go.mod"), []byte("module noeol\n"), 0666); err != nil {
|
| 589 |
+
t.Fatal(err)
|
| 590 |
+
}
|
| 591 |
+
const noeolContents = `package noeol`
|
| 592 |
+
if err := os.WriteFile(noeolGo, []byte(noeolContents), 0444); err != nil {
|
| 593 |
+
t.Fatal(err)
|
| 594 |
+
}
|
| 595 |
+
const noeolTestContents = `
|
| 596 |
+
package noeol
|
| 597 |
+
import "testing"
|
| 598 |
+
func TestCoverage(t *testing.T) { }
|
| 599 |
+
`
|
| 600 |
+
if err := os.WriteFile(noeolTestGo, []byte(noeolTestContents), 0444); err != nil {
|
| 601 |
+
t.Fatal(err)
|
| 602 |
+
}
|
| 603 |
+
|
| 604 |
+
// go test -covermode atomic
|
| 605 |
+
cmd := testenv.Command(t, testenv.GoToolPath(t), "test", toolexecArg, "-covermode", "atomic")
|
| 606 |
+
cmd.Env = append(cmd.Environ(), "CMDCOVER_TOOLEXEC=true")
|
| 607 |
+
cmd.Dir = noeolDir
|
| 608 |
+
run(cmd, t)
|
| 609 |
+
}
|
| 610 |
+
|
| 611 |
+
func TestSrcPathWithNewline(t *testing.T) {
|
| 612 |
+
testenv.MustHaveExec(t)
|
| 613 |
+
t.Parallel()
|
| 614 |
+
|
| 615 |
+
// srcPath is intentionally not clean so that the path passed to testcover
|
| 616 |
+
// will not normalize the trailing / to a \ on Windows.
|
| 617 |
+
srcPath := t.TempDir() + string(filepath.Separator) + "\npackage main\nfunc main() { panic(string([]rune{'u', 'h', '-', 'o', 'h'}))\n/*/main.go"
|
| 618 |
+
mainSrc := ` package main
|
| 619 |
+
|
| 620 |
+
func main() {
|
| 621 |
+
/* nothing here */
|
| 622 |
+
println("ok")
|
| 623 |
+
}
|
| 624 |
+
`
|
| 625 |
+
if err := os.MkdirAll(filepath.Dir(srcPath), 0777); err != nil {
|
| 626 |
+
t.Skipf("creating directory with bogus path: %v", err)
|
| 627 |
+
}
|
| 628 |
+
if err := os.WriteFile(srcPath, []byte(mainSrc), 0666); err != nil {
|
| 629 |
+
t.Skipf("writing file with bogus directory: %v", err)
|
| 630 |
+
}
|
| 631 |
+
|
| 632 |
+
cmd := testenv.Command(t, testcover(t), "-mode=atomic", srcPath)
|
| 633 |
+
cmd.Stderr = new(bytes.Buffer)
|
| 634 |
+
out, err := cmd.Output()
|
| 635 |
+
t.Logf("%v:\n%s", cmd, out)
|
| 636 |
+
t.Logf("stderr:\n%s", cmd.Stderr)
|
| 637 |
+
if err == nil {
|
| 638 |
+
t.Errorf("unexpected success; want failure due to newline in file path")
|
| 639 |
+
}
|
| 640 |
+
}
|
go/src/cmd/cover/doc.go
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Copyright 2013 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 |
+
/*
|
| 6 |
+
Cover is a program for analyzing the coverage profiles generated by
|
| 7 |
+
'go test -coverprofile=cover.out'.
|
| 8 |
+
|
| 9 |
+
Cover is also used by 'go test -cover' to rewrite the source code with
|
| 10 |
+
annotations to track which parts of each function are executed (this
|
| 11 |
+
is referred to "instrumentation"). Cover can operate in "legacy mode"
|
| 12 |
+
on a single Go source file at a time, or when invoked by the Go tool
|
| 13 |
+
it will process all the source files in a single package at a time
|
| 14 |
+
(package-scope instrumentation is enabled via "-pkgcfg" option).
|
| 15 |
+
|
| 16 |
+
When generated instrumented code, the cover tool computes approximate
|
| 17 |
+
basic block information by studying the source. It is thus more
|
| 18 |
+
portable than binary-rewriting coverage tools, but also a little less
|
| 19 |
+
capable. For instance, it does not probe inside && and || expressions,
|
| 20 |
+
and can be mildly confused by single statements with multiple function
|
| 21 |
+
literals.
|
| 22 |
+
|
| 23 |
+
When computing coverage of a package that uses cgo, the cover tool
|
| 24 |
+
must be applied to the output of cgo preprocessing, not the input,
|
| 25 |
+
because cover deletes comments that are significant to cgo.
|
| 26 |
+
|
| 27 |
+
For usage information, please see:
|
| 28 |
+
|
| 29 |
+
go help testflag
|
| 30 |
+
go tool cover -help
|
| 31 |
+
*/
|
| 32 |
+
package main
|
go/src/cmd/cover/export_test.go
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
package main
|
| 6 |
+
|
| 7 |
+
func Main() { main() }
|
go/src/cmd/cover/func.go
ADDED
|
@@ -0,0 +1,248 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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. 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 implements the visitor that computes the (line, column)-(line-column) range for each function.
|
| 6 |
+
|
| 7 |
+
package main
|
| 8 |
+
|
| 9 |
+
import (
|
| 10 |
+
"bufio"
|
| 11 |
+
"bytes"
|
| 12 |
+
"encoding/json"
|
| 13 |
+
"errors"
|
| 14 |
+
"fmt"
|
| 15 |
+
"go/ast"
|
| 16 |
+
"go/parser"
|
| 17 |
+
"go/token"
|
| 18 |
+
"io"
|
| 19 |
+
"os"
|
| 20 |
+
"os/exec"
|
| 21 |
+
"path"
|
| 22 |
+
"path/filepath"
|
| 23 |
+
"runtime"
|
| 24 |
+
"strings"
|
| 25 |
+
"text/tabwriter"
|
| 26 |
+
|
| 27 |
+
"golang.org/x/tools/cover"
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
// funcOutput takes two file names as arguments, a coverage profile to read as input and an output
|
| 31 |
+
// file to write ("" means to write to standard output). The function reads the profile and produces
|
| 32 |
+
// as output the coverage data broken down by function, like this:
|
| 33 |
+
//
|
| 34 |
+
// fmt/format.go:30: init 100.0%
|
| 35 |
+
// fmt/format.go:57: clearflags 100.0%
|
| 36 |
+
// ...
|
| 37 |
+
// fmt/scan.go:1046: doScan 100.0%
|
| 38 |
+
// fmt/scan.go:1075: advance 96.2%
|
| 39 |
+
// fmt/scan.go:1119: doScanf 96.8%
|
| 40 |
+
// total: (statements) 91.9%
|
| 41 |
+
|
| 42 |
+
func funcOutput(profile, outputFile string) error {
|
| 43 |
+
profiles, err := cover.ParseProfiles(profile)
|
| 44 |
+
if err != nil {
|
| 45 |
+
return err
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
dirs, err := findPkgs(profiles)
|
| 49 |
+
if err != nil {
|
| 50 |
+
return err
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
var out *bufio.Writer
|
| 54 |
+
if outputFile == "" {
|
| 55 |
+
out = bufio.NewWriter(os.Stdout)
|
| 56 |
+
} else {
|
| 57 |
+
fd, err := os.Create(outputFile)
|
| 58 |
+
if err != nil {
|
| 59 |
+
return err
|
| 60 |
+
}
|
| 61 |
+
defer fd.Close()
|
| 62 |
+
out = bufio.NewWriter(fd)
|
| 63 |
+
}
|
| 64 |
+
defer out.Flush()
|
| 65 |
+
|
| 66 |
+
tabber := tabwriter.NewWriter(out, 1, 8, 1, '\t', 0)
|
| 67 |
+
defer tabber.Flush()
|
| 68 |
+
|
| 69 |
+
var total, covered int64
|
| 70 |
+
for _, profile := range profiles {
|
| 71 |
+
fn := profile.FileName
|
| 72 |
+
file, err := findFile(dirs, fn)
|
| 73 |
+
if err != nil {
|
| 74 |
+
return err
|
| 75 |
+
}
|
| 76 |
+
funcs, err := findFuncs(file)
|
| 77 |
+
if err != nil {
|
| 78 |
+
return err
|
| 79 |
+
}
|
| 80 |
+
// Now match up functions and profile blocks.
|
| 81 |
+
for _, f := range funcs {
|
| 82 |
+
c, t := f.coverage(profile)
|
| 83 |
+
fmt.Fprintf(tabber, "%s:%d:\t%s\t%.1f%%\n", fn, f.startLine, f.name, percent(c, t))
|
| 84 |
+
total += t
|
| 85 |
+
covered += c
|
| 86 |
+
}
|
| 87 |
+
}
|
| 88 |
+
fmt.Fprintf(tabber, "total:\t(statements)\t%.1f%%\n", percent(covered, total))
|
| 89 |
+
|
| 90 |
+
return nil
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
// findFuncs parses the file and returns a slice of FuncExtent descriptors.
|
| 94 |
+
func findFuncs(name string) ([]*FuncExtent, error) {
|
| 95 |
+
fset := token.NewFileSet()
|
| 96 |
+
parsedFile, err := parser.ParseFile(fset, name, nil, 0)
|
| 97 |
+
if err != nil {
|
| 98 |
+
return nil, err
|
| 99 |
+
}
|
| 100 |
+
visitor := &FuncVisitor{
|
| 101 |
+
fset: fset,
|
| 102 |
+
name: name,
|
| 103 |
+
astFile: parsedFile,
|
| 104 |
+
}
|
| 105 |
+
ast.Walk(visitor, visitor.astFile)
|
| 106 |
+
return visitor.funcs, nil
|
| 107 |
+
}
|
| 108 |
+
|
| 109 |
+
// FuncExtent describes a function's extent in the source by file and position.
|
| 110 |
+
type FuncExtent struct {
|
| 111 |
+
name string
|
| 112 |
+
startLine int
|
| 113 |
+
startCol int
|
| 114 |
+
endLine int
|
| 115 |
+
endCol int
|
| 116 |
+
}
|
| 117 |
+
|
| 118 |
+
// FuncVisitor implements the visitor that builds the function position list for a file.
|
| 119 |
+
type FuncVisitor struct {
|
| 120 |
+
fset *token.FileSet
|
| 121 |
+
name string // Name of file.
|
| 122 |
+
astFile *ast.File
|
| 123 |
+
funcs []*FuncExtent
|
| 124 |
+
}
|
| 125 |
+
|
| 126 |
+
// Visit implements the ast.Visitor interface.
|
| 127 |
+
func (v *FuncVisitor) Visit(node ast.Node) ast.Visitor {
|
| 128 |
+
switch n := node.(type) {
|
| 129 |
+
case *ast.FuncDecl:
|
| 130 |
+
if n.Body == nil {
|
| 131 |
+
// Do not count declarations of assembly functions.
|
| 132 |
+
break
|
| 133 |
+
}
|
| 134 |
+
start := v.fset.Position(n.Pos())
|
| 135 |
+
end := v.fset.Position(n.End())
|
| 136 |
+
fe := &FuncExtent{
|
| 137 |
+
name: n.Name.Name,
|
| 138 |
+
startLine: start.Line,
|
| 139 |
+
startCol: start.Column,
|
| 140 |
+
endLine: end.Line,
|
| 141 |
+
endCol: end.Column,
|
| 142 |
+
}
|
| 143 |
+
v.funcs = append(v.funcs, fe)
|
| 144 |
+
}
|
| 145 |
+
return v
|
| 146 |
+
}
|
| 147 |
+
|
| 148 |
+
// coverage returns the fraction of the statements in the function that were covered, as a numerator and denominator.
|
| 149 |
+
func (f *FuncExtent) coverage(profile *cover.Profile) (num, den int64) {
|
| 150 |
+
// We could avoid making this n^2 overall by doing a single scan and annotating the functions,
|
| 151 |
+
// but the sizes of the data structures is never very large and the scan is almost instantaneous.
|
| 152 |
+
var covered, total int64
|
| 153 |
+
// The blocks are sorted, so we can stop counting as soon as we reach the end of the relevant block.
|
| 154 |
+
for _, b := range profile.Blocks {
|
| 155 |
+
if b.StartLine > f.endLine || (b.StartLine == f.endLine && b.StartCol >= f.endCol) {
|
| 156 |
+
// Past the end of the function.
|
| 157 |
+
break
|
| 158 |
+
}
|
| 159 |
+
if b.EndLine < f.startLine || (b.EndLine == f.startLine && b.EndCol <= f.startCol) {
|
| 160 |
+
// Before the beginning of the function
|
| 161 |
+
continue
|
| 162 |
+
}
|
| 163 |
+
total += int64(b.NumStmt)
|
| 164 |
+
if b.Count > 0 {
|
| 165 |
+
covered += int64(b.NumStmt)
|
| 166 |
+
}
|
| 167 |
+
}
|
| 168 |
+
return covered, total
|
| 169 |
+
}
|
| 170 |
+
|
| 171 |
+
// Pkg describes a single package, compatible with the JSON output from 'go list'; see 'go help list'.
|
| 172 |
+
type Pkg struct {
|
| 173 |
+
ImportPath string
|
| 174 |
+
Dir string
|
| 175 |
+
Error *struct {
|
| 176 |
+
Err string
|
| 177 |
+
}
|
| 178 |
+
}
|
| 179 |
+
|
| 180 |
+
func findPkgs(profiles []*cover.Profile) (map[string]*Pkg, error) {
|
| 181 |
+
// Run go list to find the location of every package we care about.
|
| 182 |
+
pkgs := make(map[string]*Pkg)
|
| 183 |
+
var list []string
|
| 184 |
+
for _, profile := range profiles {
|
| 185 |
+
if strings.HasPrefix(profile.FileName, ".") || filepath.IsAbs(profile.FileName) {
|
| 186 |
+
// Relative or absolute path.
|
| 187 |
+
continue
|
| 188 |
+
}
|
| 189 |
+
pkg := path.Dir(profile.FileName)
|
| 190 |
+
if _, ok := pkgs[pkg]; !ok {
|
| 191 |
+
pkgs[pkg] = nil
|
| 192 |
+
list = append(list, pkg)
|
| 193 |
+
}
|
| 194 |
+
}
|
| 195 |
+
|
| 196 |
+
if len(list) == 0 {
|
| 197 |
+
return pkgs, nil
|
| 198 |
+
}
|
| 199 |
+
|
| 200 |
+
// Note: usually run as "go tool cover" in which case $GOROOT is set,
|
| 201 |
+
// in which case runtime.GOROOT() does exactly what we want.
|
| 202 |
+
goTool := filepath.Join(runtime.GOROOT(), "bin/go")
|
| 203 |
+
cmd := exec.Command(goTool, append([]string{"list", "-e", "-json"}, list...)...)
|
| 204 |
+
var stderr bytes.Buffer
|
| 205 |
+
cmd.Stderr = &stderr
|
| 206 |
+
stdout, err := cmd.Output()
|
| 207 |
+
if err != nil {
|
| 208 |
+
return nil, fmt.Errorf("cannot run go list: %v\n%s", err, stderr.Bytes())
|
| 209 |
+
}
|
| 210 |
+
dec := json.NewDecoder(bytes.NewReader(stdout))
|
| 211 |
+
for {
|
| 212 |
+
var pkg Pkg
|
| 213 |
+
err := dec.Decode(&pkg)
|
| 214 |
+
if err == io.EOF {
|
| 215 |
+
break
|
| 216 |
+
}
|
| 217 |
+
if err != nil {
|
| 218 |
+
return nil, fmt.Errorf("decoding go list json: %v", err)
|
| 219 |
+
}
|
| 220 |
+
pkgs[pkg.ImportPath] = &pkg
|
| 221 |
+
}
|
| 222 |
+
return pkgs, nil
|
| 223 |
+
}
|
| 224 |
+
|
| 225 |
+
// findFile finds the location of the named file in GOROOT, GOPATH etc.
|
| 226 |
+
func findFile(pkgs map[string]*Pkg, file string) (string, error) {
|
| 227 |
+
if strings.HasPrefix(file, ".") || filepath.IsAbs(file) {
|
| 228 |
+
// Relative or absolute path.
|
| 229 |
+
return file, nil
|
| 230 |
+
}
|
| 231 |
+
pkg := pkgs[path.Dir(file)]
|
| 232 |
+
if pkg != nil {
|
| 233 |
+
if pkg.Dir != "" {
|
| 234 |
+
return filepath.Join(pkg.Dir, path.Base(file)), nil
|
| 235 |
+
}
|
| 236 |
+
if pkg.Error != nil {
|
| 237 |
+
return "", errors.New(pkg.Error.Err)
|
| 238 |
+
}
|
| 239 |
+
}
|
| 240 |
+
return "", fmt.Errorf("did not find package for %s in go list output", file)
|
| 241 |
+
}
|
| 242 |
+
|
| 243 |
+
func percent(covered, total int64) float64 {
|
| 244 |
+
if total == 0 {
|
|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|
| 4 |
+
|
| 5 |
+
package main
|
| 6 |
+
|
| 7 |
+
import (
|
| 8 |
+
"bufio"
|
| 9 |
+
"cmd/internal/browser"
|
| 10 |
+
"fmt"
|
| 11 |
+
"html/template"
|
| 12 |
+
"io"
|
| 13 |
+
"math"
|
| 14 |
+
"os"
|
| 15 |
+
"path/filepath"
|
| 16 |
+
"strings"
|
| 17 |
+
|
| 18 |
+
"golang.org/x/tools/cover"
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
// htmlOutput reads the profile data from profile and generates an HTML
|
| 22 |
+
// coverage report, writing it to outfile. If outfile is empty,
|
| 23 |
+
// it writes the report to a temporary file and opens it in a web browser.
|
| 24 |
+
func htmlOutput(profile, outfile string) error {
|
| 25 |
+
profiles, err := cover.ParseProfiles(profile)
|
| 26 |
+
if err != nil {
|
| 27 |
+
return err
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
var d templateData
|
| 31 |
+
|
| 32 |
+
dirs, err := findPkgs(profiles)
|
| 33 |
+
if err != nil {
|
| 34 |
+
return err
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
for _, profile := range profiles {
|
| 38 |
+
fn := profile.FileName
|
| 39 |
+
if profile.Mode == "set" {
|
| 40 |
+
d.Set = true
|
| 41 |
+
}
|
| 42 |
+
file, err := findFile(dirs, fn)
|
| 43 |
+
if err != nil {
|
| 44 |
+
return err
|
| 45 |
+
}
|
| 46 |
+
src, err := os.ReadFile(file)
|
| 47 |
+
if err != nil {
|
| 48 |
+
return fmt.Errorf("can't read %q: %v", fn, err)
|
| 49 |
+
}
|
| 50 |
+
var buf strings.Builder
|
| 51 |
+
err = htmlGen(&buf, src, profile.Boundaries(src))
|
| 52 |
+
if err != nil {
|
| 53 |
+
return err
|
| 54 |
+
}
|
| 55 |
+
d.Files = append(d.Files, &templateFile{
|
| 56 |
+
Name: fn,
|
| 57 |
+
Body: template.HTML(buf.String()),
|
| 58 |
+
Coverage: percentCovered(profile),
|
| 59 |
+
})
|
| 60 |
+
}
|
| 61 |
+
|
| 62 |
+
var out *os.File
|
| 63 |
+
if outfile == "" {
|
| 64 |
+
var dir string
|
| 65 |
+
dir, err = os.MkdirTemp("", "cover")
|
| 66 |
+
if err != nil {
|
| 67 |
+
return err
|
| 68 |
+
}
|
| 69 |
+
out, err = os.Create(filepath.Join(dir, "coverage.html"))
|
| 70 |
+
} else {
|
| 71 |
+
out, err = os.Create(outfile)
|
| 72 |
+
}
|
| 73 |
+
if err != nil {
|
| 74 |
+
return err
|
| 75 |
+
}
|
| 76 |
+
err = htmlTemplate.Execute(out, d)
|
| 77 |
+
if err2 := out.Close(); err == nil {
|
| 78 |
+
err = err2
|
| 79 |
+
}
|
| 80 |
+
if err != nil {
|
| 81 |
+
return err
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
if outfile == "" {
|
| 85 |
+
if !browser.Open("file://" + out.Name()) {
|
| 86 |
+
fmt.Fprintf(os.Stderr, "HTML output written to %s\n", out.Name())
|
| 87 |
+
}
|
| 88 |
+
}
|
| 89 |
+
|
| 90 |
+
return nil
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
// percentCovered returns, as a percentage, the fraction of the statements in
|
| 94 |
+
// the profile covered by the test run.
|
| 95 |
+
// In effect, it reports the coverage of a given source file.
|
| 96 |
+
func percentCovered(p *cover.Profile) float64 {
|
| 97 |
+
var total, covered int64
|
| 98 |
+
for _, b := range p.Blocks {
|
| 99 |
+
total += int64(b.NumStmt)
|
| 100 |
+
if b.Count > 0 {
|
| 101 |
+
covered += int64(b.NumStmt)
|
| 102 |
+
}
|
| 103 |
+
}
|
| 104 |
+
if total == 0 {
|
| 105 |
+
return 0
|
| 106 |
+
}
|
| 107 |
+
return float64(covered) / float64(total) * 100
|
| 108 |
+
}
|
| 109 |
+
|
| 110 |
+
// htmlGen generates an HTML coverage report with the provided filename,
|
| 111 |
+
// source code, and tokens, and writes it to the given Writer.
|
| 112 |
+
func htmlGen(w io.Writer, src []byte, boundaries []cover.Boundary) error {
|
| 113 |
+
dst := bufio.NewWriter(w)
|
| 114 |
+
for i := range src {
|
| 115 |
+
for len(boundaries) > 0 && boundaries[0].Offset == i {
|
| 116 |
+
b := boundaries[0]
|
| 117 |
+
if b.Start {
|
| 118 |
+
n := 0
|
| 119 |
+
if b.Count > 0 {
|
| 120 |
+
n = int(math.Floor(b.Norm*9)) + 1
|
| 121 |
+
}
|
| 122 |
+
fmt.Fprintf(dst, `<span class="cov%v" title="%v">`, n, b.Count)
|
| 123 |
+
} else {
|
| 124 |
+
dst.WriteString("</span>")
|
| 125 |
+
}
|
| 126 |
+
boundaries = boundaries[1:]
|
| 127 |
+
}
|
| 128 |
+
switch b := src[i]; b {
|
| 129 |
+
case '>':
|
| 130 |
+
dst.WriteString(">")
|
| 131 |
+
case '<':
|
| 132 |
+
dst.WriteString("<")
|
| 133 |
+
case '&':
|
| 134 |
+
dst.WriteString("&")
|
| 135 |
+
case '\t':
|
| 136 |
+
dst.WriteString(" ")
|
| 137 |
+
default:
|
| 138 |
+
dst.WriteByte(b)
|
| 139 |
+
}
|
| 140 |
+
}
|
| 141 |
+
return dst.Flush()
|
| 142 |
+
}
|
| 143 |
+
|
| 144 |
+
// rgb returns an rgb value for the specified coverage value
|
| 145 |
+
// between 0 (no coverage) and 10 (max coverage).
|
| 146 |
+
func rgb(n int) string {
|
| 147 |
+
if n == 0 {
|
| 148 |
+
return "rgb(192, 0, 0)" // Red
|
| 149 |
+
}
|
| 150 |
+
// Gradient from gray to green.
|
| 151 |
+
r := 128 - 12*(n-1)
|
| 152 |
+
g := 128 + 12*(n-1)
|
| 153 |
+
b := 128 + 3*(n-1)
|
| 154 |
+
return fmt.Sprintf("rgb(%v, %v, %v)", r, g, b)
|
| 155 |
+
}
|
| 156 |
+
|
| 157 |
+
// colors generates the CSS rules for coverage colors.
|
| 158 |
+
func colors() template.CSS {
|
| 159 |
+
var buf strings.Builder
|
| 160 |
+
for i := 0; i < 11; i++ {
|
| 161 |
+
fmt.Fprintf(&buf, ".cov%v { color: %v }\n", i, rgb(i))
|
| 162 |
+
}
|
| 163 |
+
return template.CSS(buf.String())
|
| 164 |
+
}
|
| 165 |
+
|
| 166 |
+
var htmlTemplate = template.Must(template.New("html").Funcs(template.FuncMap{
|
| 167 |
+
"colors": colors,
|
| 168 |
+
}).Parse(tmplHTML))
|
| 169 |
+
|
| 170 |
+
type templateData struct {
|
| 171 |
+
Files []*templateFile
|
| 172 |
+
Set bool
|
| 173 |
+
}
|
| 174 |
+
|
| 175 |
+
// PackageName returns a name for the package being shown.
|
| 176 |
+
// It does this by choosing the penultimate element of the path
|
| 177 |
+
// name, so foo.bar/baz/foo.go chooses 'baz'. This is cheap
|
| 178 |
+
// and easy, avoids parsing the Go file, and gets a better answer
|
| 179 |
+
// for package main. It returns the empty string if there is
|
| 180 |
+
// a problem.
|
| 181 |
+
func (td templateData) PackageName() string {
|
| 182 |
+
if len(td.Files) == 0 {
|
| 183 |
+
return ""
|
| 184 |
+
}
|
| 185 |
+
fileName := td.Files[0].Name
|
| 186 |
+
elems := strings.Split(fileName, "/") // Package path is always slash-separated.
|
| 187 |
+
// Return the penultimate non-empty element.
|
| 188 |
+
for i := len(elems) - 2; i >= 0; i-- {
|
| 189 |
+
if elems[i] != "" {
|
| 190 |
+
return elems[i]
|
| 191 |
+
}
|
| 192 |
+
}
|
| 193 |
+
return ""
|
| 194 |
+
}
|
| 195 |
+
|
| 196 |
+
type templateFile struct {
|
| 197 |
+
Name string
|
| 198 |
+
Body template.HTML
|
| 199 |
+
Coverage float64
|
| 200 |
+
}
|
| 201 |
+
|
| 202 |
+
const tmplHTML = `
|
| 203 |
+
<!DOCTYPE html>
|
| 204 |
+
<html>
|
| 205 |
+
<head>
|
| 206 |
+
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
|
| 207 |
+
<title>{{$pkg := .PackageName}}{{if $pkg}}{{$pkg}}: {{end}}Go Coverage Report</title>
|
| 208 |
+
<style>
|
| 209 |
+
body {
|
| 210 |
+
background: black;
|
| 211 |
+
color: rgb(80, 80, 80);
|
| 212 |
+
}
|
| 213 |
+
body, pre, #legend span {
|
| 214 |
+
font-family: Menlo, monospace;
|
| 215 |
+
font-weight: bold;
|
| 216 |
+
}
|
| 217 |
+
#topbar {
|
| 218 |
+
background: black;
|
| 219 |
+
position: fixed;
|
| 220 |
+
top: 0; left: 0; right: 0;
|
| 221 |
+
height: 42px;
|
| 222 |
+
border-bottom: 1px solid rgb(80, 80, 80);
|
| 223 |
+
}
|
| 224 |
+
#content {
|
| 225 |
+
margin-top: 50px;
|
| 226 |
+
}
|
| 227 |
+
#nav, #legend {
|
| 228 |
+
float: left;
|
| 229 |
+
margin-left: 10px;
|
| 230 |
+
}
|
| 231 |
+
#legend {
|
| 232 |
+
margin-top: 12px;
|
| 233 |
+
}
|
| 234 |
+
#nav {
|
| 235 |
+
margin-top: 10px;
|
| 236 |
+
}
|
| 237 |
+
#legend span {
|
| 238 |
+
margin: 0 5px;
|
| 239 |
+
}
|
| 240 |
+
{{colors}}
|
| 241 |
+
</style>
|
| 242 |
+
</head>
|
| 243 |
+
<body>
|
| 244 |
+
<div id="topbar">
|
| 245 |
+
<div id="nav">
|
| 246 |
+
<select id="files">
|
| 247 |
+
{{range $i, $f := .Files}}
|
| 248 |
+
<option value="file{{$i}}">{{$f.Name}} ({{printf "%.1f" $f.Coverage}}%)</option>
|
| 249 |
+
{{end}}
|
| 250 |
+
</select>
|
| 251 |
+
</div>
|
| 252 |
+
<div id="legend">
|
| 253 |
+
<span>not tracked</span>
|
| 254 |
+
{{if .Set}}
|
| 255 |
+
<span class="cov0">not covered</span>
|
| 256 |
+
<span class="cov8">covered</span>
|
| 257 |
+
{{else}}
|
| 258 |
+
<span class="cov0">no coverage</span>
|
| 259 |
+
<span class="cov1">low coverage</span>
|
| 260 |
+
<span class="cov2">*</span>
|
| 261 |
+
<span class="cov3">*</span>
|
| 262 |
+
<span class="cov4">*</span>
|
| 263 |
+
<span class="cov5">*</span>
|
| 264 |
+
<span class="cov6">*</span>
|
| 265 |
+
<span class="cov7">*</span>
|
| 266 |
+
<span class="cov8">*</span>
|
| 267 |
+
<span class="cov9">*</span>
|
| 268 |
+
<span class="cov10">high coverage</span>
|
| 269 |
+
{{end}}
|
| 270 |
+
</div>
|
| 271 |
+
</div>
|
| 272 |
+
<div id="content">
|
| 273 |
+
{{range $i, $f := .Files}}
|
| 274 |
+
<pre class="file" id="file{{$i}}" style="display: none">{{$f.Body}}</pre>
|
| 275 |
+
{{end}}
|
| 276 |
+
</div>
|
| 277 |
+
</body>
|
| 278 |
+
<script>
|
| 279 |
+
(function() {
|
| 280 |
+
var files = document.getElementById('files');
|
| 281 |
+
var visible;
|
| 282 |
+
files.addEventListener('change', onChange, false);
|
| 283 |
+
function select(part) {
|
| 284 |
+
if (visible)
|
| 285 |
+
visible.style.display = 'none';
|
| 286 |
+
visible = document.getElementById(part);
|
| 287 |
+
if (!visible)
|
| 288 |
+
return;
|
| 289 |
+
files.value = part;
|
| 290 |
+
visible.style.display = 'block';
|
| 291 |
+
location.hash = part;
|
| 292 |
+
}
|
| 293 |
+
function onChange() {
|
| 294 |
+
select(files.value);
|
| 295 |
+
window.scrollTo(0, 0);
|
| 296 |
+
}
|
| 297 |
+
if (location.hash != "") {
|
| 298 |
+
select(location.hash.substr(1));
|
| 299 |
+
}
|
| 300 |
+
if (!visible) {
|
| 301 |
+
select("file0");
|
| 302 |
+
}
|
| 303 |
+
})();
|
| 304 |
+
</script>
|
| 305 |
+
</html>
|
| 306 |
+
`
|
go/src/cmd/cover/pkgname_test.go
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Copyright 2020 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 |
+
package main
|
| 6 |
+
|
| 7 |
+
import "testing"
|
| 8 |
+
|
| 9 |
+
func TestPackageName(t *testing.T) {
|
| 10 |
+
var tests = []struct {
|
| 11 |
+
fileName, pkgName string
|
| 12 |
+
}{
|
| 13 |
+
{"", ""},
|
| 14 |
+
{"///", ""},
|
| 15 |
+
{"fmt", ""}, // No Go file, improper form.
|
| 16 |
+
{"fmt/foo.go", "fmt"},
|
| 17 |
+
{"encoding/binary/foo.go", "binary"},
|
| 18 |
+
{"encoding/binary/////foo.go", "binary"},
|
| 19 |
+
}
|
| 20 |
+
var tf templateFile
|
| 21 |
+
for _, test := range tests {
|
| 22 |
+
tf.Name = test.fileName
|
| 23 |
+
td := templateData{
|
| 24 |
+
Files: []*templateFile{&tf},
|
| 25 |
+
}
|
| 26 |
+
got := td.PackageName()
|
| 27 |
+
if got != test.pkgName {
|
| 28 |
+
t.Errorf("%s: got %s want %s", test.fileName, got, test.pkgName)
|
| 29 |
+
}
|
| 30 |
+
}
|
| 31 |
+
}
|
go/src/cmd/dist/README
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
This program, dist, is the bootstrapping tool for the Go distribution.
|
| 2 |
+
|
| 3 |
+
As of Go 1.5, dist and other parts of the compiler toolchain are written
|
| 4 |
+
in Go, making bootstrapping a little more involved than in the past.
|
| 5 |
+
The approach is to build the current release of Go with an earlier one.
|
| 6 |
+
|
| 7 |
+
The process to install Go 1.x, for x ≥ 26, is:
|
| 8 |
+
|
| 9 |
+
1. Build cmd/dist with Go 1.24.6.
|
| 10 |
+
2. Using dist, build Go 1.x compiler toolchain with Go 1.24.6.
|
| 11 |
+
3. Using dist, rebuild Go 1.x compiler toolchain with itself.
|
| 12 |
+
4. Using dist, build Go 1.x cmd/go (as go_bootstrap) with Go 1.x compiler toolchain.
|
| 13 |
+
5. Using go_bootstrap, build the remaining Go 1.x standard library and commands.
|
| 14 |
+
|
| 15 |
+
Because of backward compatibility, although the steps above say Go 1.24.6,
|
| 16 |
+
in practice any release ≥ Go 1.24.6 but < Go 1.x will work as the bootstrap base.
|
| 17 |
+
Releases ≥ Go 1.x are very likely to work as well.
|
| 18 |
+
|
| 19 |
+
See go.dev/s/go15bootstrap for more details about the original bootstrap
|
| 20 |
+
and go.dev/issue/54265 for details about later bootstrap version bumps.
|
go/src/cmd/dist/build.go
ADDED
|
@@ -0,0 +1,2020 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
package main
|
| 6 |
+
|
| 7 |
+
import (
|
| 8 |
+
"bytes"
|
| 9 |
+
"encoding/json"
|
| 10 |
+
"flag"
|
| 11 |
+
"fmt"
|
| 12 |
+
"io"
|
| 13 |
+
"io/fs"
|
| 14 |
+
"log"
|
| 15 |
+
"os"
|
| 16 |
+
"os/exec"
|
| 17 |
+
"path/filepath"
|
| 18 |
+
"regexp"
|
| 19 |
+
"slices"
|
| 20 |
+
"sort"
|
| 21 |
+
"strconv"
|
| 22 |
+
"strings"
|
| 23 |
+
"sync"
|
| 24 |
+
"time"
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
// Initialization for any invocation.
|
| 28 |
+
|
| 29 |
+
// The usual variables.
|
| 30 |
+
var (
|
| 31 |
+
goarch string
|
| 32 |
+
gorootBin string
|
| 33 |
+
gorootBinGo string
|
| 34 |
+
gohostarch string
|
| 35 |
+
gohostos string
|
| 36 |
+
goos string
|
| 37 |
+
goarm string
|
| 38 |
+
goarm64 string
|
| 39 |
+
go386 string
|
| 40 |
+
goamd64 string
|
| 41 |
+
gomips string
|
| 42 |
+
gomips64 string
|
| 43 |
+
goppc64 string
|
| 44 |
+
goriscv64 string
|
| 45 |
+
goroot string
|
| 46 |
+
goextlinkenabled string
|
| 47 |
+
gogcflags string // For running built compiler
|
| 48 |
+
goldflags string
|
| 49 |
+
goexperiment string
|
| 50 |
+
gofips140 string
|
| 51 |
+
workdir string
|
| 52 |
+
tooldir string
|
| 53 |
+
oldgoos string
|
| 54 |
+
oldgoarch string
|
| 55 |
+
oldgocache string
|
| 56 |
+
exe string
|
| 57 |
+
defaultcc map[string]string
|
| 58 |
+
defaultcxx map[string]string
|
| 59 |
+
defaultpkgconfig string
|
| 60 |
+
defaultldso string
|
| 61 |
+
|
| 62 |
+
rebuildall bool
|
| 63 |
+
noOpt bool
|
| 64 |
+
isRelease bool
|
| 65 |
+
|
| 66 |
+
vflag int // verbosity
|
| 67 |
+
)
|
| 68 |
+
|
| 69 |
+
// The known architectures.
|
| 70 |
+
var okgoarch = []string{
|
| 71 |
+
"386",
|
| 72 |
+
"amd64",
|
| 73 |
+
"arm",
|
| 74 |
+
"arm64",
|
| 75 |
+
"loong64",
|
| 76 |
+
"mips",
|
| 77 |
+
"mipsle",
|
| 78 |
+
"mips64",
|
| 79 |
+
"mips64le",
|
| 80 |
+
"ppc64",
|
| 81 |
+
"ppc64le",
|
| 82 |
+
"riscv64",
|
| 83 |
+
"s390x",
|
| 84 |
+
"sparc64",
|
| 85 |
+
"wasm",
|
| 86 |
+
}
|
| 87 |
+
|
| 88 |
+
// The known operating systems.
|
| 89 |
+
var okgoos = []string{
|
| 90 |
+
"darwin",
|
| 91 |
+
"dragonfly",
|
| 92 |
+
"illumos",
|
| 93 |
+
"ios",
|
| 94 |
+
"js",
|
| 95 |
+
"wasip1",
|
| 96 |
+
"linux",
|
| 97 |
+
"android",
|
| 98 |
+
"solaris",
|
| 99 |
+
"freebsd",
|
| 100 |
+
"nacl", // keep;
|
| 101 |
+
"netbsd",
|
| 102 |
+
"openbsd",
|
| 103 |
+
"plan9",
|
| 104 |
+
"windows",
|
| 105 |
+
"aix",
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
// xinit handles initialization of the various global state, like goroot and goarch.
|
| 109 |
+
func xinit() {
|
| 110 |
+
b := os.Getenv("GOROOT")
|
| 111 |
+
if b == "" {
|
| 112 |
+
fatalf("$GOROOT must be set")
|
| 113 |
+
}
|
| 114 |
+
goroot = filepath.Clean(b)
|
| 115 |
+
gorootBin = pathf("%s/bin", goroot)
|
| 116 |
+
|
| 117 |
+
// Don't run just 'go' because the build infrastructure
|
| 118 |
+
// runs cmd/dist inside go/bin often, and on Windows
|
| 119 |
+
// it will be found in the current directory and refuse to exec.
|
| 120 |
+
// All exec calls rewrite "go" into gorootBinGo.
|
| 121 |
+
gorootBinGo = pathf("%s/bin/go", goroot)
|
| 122 |
+
|
| 123 |
+
b = os.Getenv("GOOS")
|
| 124 |
+
if b == "" {
|
| 125 |
+
b = gohostos
|
| 126 |
+
}
|
| 127 |
+
goos = b
|
| 128 |
+
if slices.Index(okgoos, goos) < 0 {
|
| 129 |
+
fatalf("unknown $GOOS %s", goos)
|
| 130 |
+
}
|
| 131 |
+
|
| 132 |
+
b = os.Getenv("GOARM")
|
| 133 |
+
if b == "" {
|
| 134 |
+
b = xgetgoarm()
|
| 135 |
+
}
|
| 136 |
+
goarm = b
|
| 137 |
+
|
| 138 |
+
b = os.Getenv("GOARM64")
|
| 139 |
+
if b == "" {
|
| 140 |
+
b = "v8.0"
|
| 141 |
+
}
|
| 142 |
+
goarm64 = b
|
| 143 |
+
|
| 144 |
+
b = os.Getenv("GO386")
|
| 145 |
+
if b == "" {
|
| 146 |
+
b = "sse2"
|
| 147 |
+
}
|
| 148 |
+
go386 = b
|
| 149 |
+
|
| 150 |
+
b = os.Getenv("GOAMD64")
|
| 151 |
+
if b == "" {
|
| 152 |
+
b = "v1"
|
| 153 |
+
}
|
| 154 |
+
goamd64 = b
|
| 155 |
+
|
| 156 |
+
b = os.Getenv("GOMIPS")
|
| 157 |
+
if b == "" {
|
| 158 |
+
b = "hardfloat"
|
| 159 |
+
}
|
| 160 |
+
gomips = b
|
| 161 |
+
|
| 162 |
+
b = os.Getenv("GOMIPS64")
|
| 163 |
+
if b == "" {
|
| 164 |
+
b = "hardfloat"
|
| 165 |
+
}
|
| 166 |
+
gomips64 = b
|
| 167 |
+
|
| 168 |
+
b = os.Getenv("GOPPC64")
|
| 169 |
+
if b == "" {
|
| 170 |
+
b = "power8"
|
| 171 |
+
}
|
| 172 |
+
goppc64 = b
|
| 173 |
+
|
| 174 |
+
b = os.Getenv("GORISCV64")
|
| 175 |
+
if b == "" {
|
| 176 |
+
b = "rva20u64"
|
| 177 |
+
}
|
| 178 |
+
goriscv64 = b
|
| 179 |
+
|
| 180 |
+
b = os.Getenv("GOFIPS140")
|
| 181 |
+
if b == "" {
|
| 182 |
+
b = "off"
|
| 183 |
+
}
|
| 184 |
+
gofips140 = b
|
| 185 |
+
|
| 186 |
+
if p := pathf("%s/src/all.bash", goroot); !isfile(p) {
|
| 187 |
+
fatalf("$GOROOT is not set correctly or not exported\n"+
|
| 188 |
+
"\tGOROOT=%s\n"+
|
| 189 |
+
"\t%s does not exist", goroot, p)
|
| 190 |
+
}
|
| 191 |
+
|
| 192 |
+
b = os.Getenv("GOHOSTARCH")
|
| 193 |
+
if b != "" {
|
| 194 |
+
gohostarch = b
|
| 195 |
+
}
|
| 196 |
+
if slices.Index(okgoarch, gohostarch) < 0 {
|
| 197 |
+
fatalf("unknown $GOHOSTARCH %s", gohostarch)
|
| 198 |
+
}
|
| 199 |
+
|
| 200 |
+
b = os.Getenv("GOARCH")
|
| 201 |
+
if b == "" {
|
| 202 |
+
b = gohostarch
|
| 203 |
+
}
|
| 204 |
+
goarch = b
|
| 205 |
+
if slices.Index(okgoarch, goarch) < 0 {
|
| 206 |
+
fatalf("unknown $GOARCH %s", goarch)
|
| 207 |
+
}
|
| 208 |
+
|
| 209 |
+
b = os.Getenv("GO_EXTLINK_ENABLED")
|
| 210 |
+
if b != "" {
|
| 211 |
+
if b != "0" && b != "1" {
|
| 212 |
+
fatalf("unknown $GO_EXTLINK_ENABLED %s", b)
|
| 213 |
+
}
|
| 214 |
+
goextlinkenabled = b
|
| 215 |
+
}
|
| 216 |
+
|
| 217 |
+
goexperiment = os.Getenv("GOEXPERIMENT")
|
| 218 |
+
// TODO(mdempsky): Validate known experiments?
|
| 219 |
+
|
| 220 |
+
gogcflags = os.Getenv("BOOT_GO_GCFLAGS")
|
| 221 |
+
goldflags = os.Getenv("BOOT_GO_LDFLAGS")
|
| 222 |
+
|
| 223 |
+
defaultcc = compilerEnv("CC", "")
|
| 224 |
+
defaultcxx = compilerEnv("CXX", "")
|
| 225 |
+
|
| 226 |
+
b = os.Getenv("PKG_CONFIG")
|
| 227 |
+
if b == "" {
|
| 228 |
+
b = "pkg-config"
|
| 229 |
+
}
|
| 230 |
+
defaultpkgconfig = b
|
| 231 |
+
|
| 232 |
+
defaultldso = os.Getenv("GO_LDSO")
|
| 233 |
+
|
| 234 |
+
// For tools being invoked but also for os.ExpandEnv.
|
| 235 |
+
os.Setenv("GO386", go386)
|
| 236 |
+
os.Setenv("GOAMD64", goamd64)
|
| 237 |
+
os.Setenv("GOARCH", goarch)
|
| 238 |
+
os.Setenv("GOARM", goarm)
|
| 239 |
+
os.Setenv("GOARM64", goarm64)
|
| 240 |
+
os.Setenv("GOHOSTARCH", gohostarch)
|
| 241 |
+
os.Setenv("GOHOSTOS", gohostos)
|
| 242 |
+
os.Setenv("GOOS", goos)
|
| 243 |
+
os.Setenv("GOMIPS", gomips)
|
| 244 |
+
os.Setenv("GOMIPS64", gomips64)
|
| 245 |
+
os.Setenv("GOPPC64", goppc64)
|
| 246 |
+
os.Setenv("GORISCV64", goriscv64)
|
| 247 |
+
os.Setenv("GOROOT", goroot)
|
| 248 |
+
os.Setenv("GOFIPS140", gofips140)
|
| 249 |
+
|
| 250 |
+
// Set GOBIN to GOROOT/bin. The meaning of GOBIN has drifted over time
|
| 251 |
+
// (see https://go.dev/issue/3269, https://go.dev/cl/183058,
|
| 252 |
+
// https://go.dev/issue/31576). Since we want binaries installed by 'dist' to
|
| 253 |
+
// always go to GOROOT/bin anyway.
|
| 254 |
+
os.Setenv("GOBIN", gorootBin)
|
| 255 |
+
|
| 256 |
+
// Make the environment more predictable.
|
| 257 |
+
os.Setenv("LANG", "C")
|
| 258 |
+
os.Setenv("LANGUAGE", "en_US.UTF8")
|
| 259 |
+
os.Unsetenv("GO111MODULE")
|
| 260 |
+
os.Setenv("GOENV", "off")
|
| 261 |
+
os.Unsetenv("GOFLAGS")
|
| 262 |
+
os.Setenv("GOWORK", "off")
|
| 263 |
+
|
| 264 |
+
// Create the go.mod for building toolchain2 and toolchain3. Toolchain1 and go_bootstrap are built with
|
| 265 |
+
// a separate go.mod (with a lower required go version to allow all allowed bootstrap toolchain versions)
|
| 266 |
+
// in bootstrapBuildTools.
|
| 267 |
+
modVer := goModVersion()
|
| 268 |
+
workdir = xworkdir()
|
| 269 |
+
if err := os.WriteFile(pathf("%s/go.mod", workdir), []byte("module bootstrap\n\ngo "+modVer+"\n"), 0666); err != nil {
|
| 270 |
+
fatalf("cannot write stub go.mod: %s", err)
|
| 271 |
+
}
|
| 272 |
+
xatexit(rmworkdir)
|
| 273 |
+
|
| 274 |
+
tooldir = pathf("%s/pkg/tool/%s_%s", goroot, gohostos, gohostarch)
|
| 275 |
+
|
| 276 |
+
goversion := findgoversion()
|
| 277 |
+
isRelease = (strings.HasPrefix(goversion, "release.") || strings.HasPrefix(goversion, "go")) &&
|
| 278 |
+
!strings.Contains(goversion, "devel")
|
| 279 |
+
}
|
| 280 |
+
|
| 281 |
+
// compilerEnv returns a map from "goos/goarch" to the
|
| 282 |
+
// compiler setting to use for that platform.
|
| 283 |
+
// The entry for key "" covers any goos/goarch not explicitly set in the map.
|
| 284 |
+
// For example, compilerEnv("CC", "gcc") returns the C compiler settings
|
| 285 |
+
// read from $CC, defaulting to gcc.
|
| 286 |
+
//
|
| 287 |
+
// The result is a map because additional environment variables
|
| 288 |
+
// can be set to change the compiler based on goos/goarch settings.
|
| 289 |
+
// The following applies to all envNames but CC is assumed to simplify
|
| 290 |
+
// the presentation.
|
| 291 |
+
//
|
| 292 |
+
// If no environment variables are set, we use def for all goos/goarch.
|
| 293 |
+
// $CC, if set, applies to all goos/goarch but is overridden by the following.
|
| 294 |
+
// $CC_FOR_TARGET, if set, applies to all goos/goarch except gohostos/gohostarch,
|
| 295 |
+
// but is overridden by the following.
|
| 296 |
+
// If gohostos=goos and gohostarch=goarch, then $CC_FOR_TARGET applies even for gohostos/gohostarch.
|
| 297 |
+
// $CC_FOR_goos_goarch, if set, applies only to goos/goarch.
|
| 298 |
+
func compilerEnv(envName, def string) map[string]string {
|
| 299 |
+
m := map[string]string{"": def}
|
| 300 |
+
|
| 301 |
+
if env := os.Getenv(envName); env != "" {
|
| 302 |
+
m[""] = env
|
| 303 |
+
}
|
| 304 |
+
if env := os.Getenv(envName + "_FOR_TARGET"); env != "" {
|
| 305 |
+
if gohostos != goos || gohostarch != goarch {
|
| 306 |
+
m[gohostos+"/"+gohostarch] = m[""]
|
| 307 |
+
}
|
| 308 |
+
m[""] = env
|
| 309 |
+
}
|
| 310 |
+
|
| 311 |
+
for _, goos := range okgoos {
|
| 312 |
+
for _, goarch := range okgoarch {
|
| 313 |
+
if env := os.Getenv(envName + "_FOR_" + goos + "_" + goarch); env != "" {
|
| 314 |
+
m[goos+"/"+goarch] = env
|
| 315 |
+
}
|
| 316 |
+
}
|
| 317 |
+
}
|
| 318 |
+
|
| 319 |
+
return m
|
| 320 |
+
}
|
| 321 |
+
|
| 322 |
+
// clangos lists the operating systems where we prefer clang to gcc.
|
| 323 |
+
var clangos = []string{
|
| 324 |
+
"darwin", "ios", // macOS 10.9 and later require clang
|
| 325 |
+
"freebsd", // FreeBSD 10 and later do not ship gcc
|
| 326 |
+
"openbsd", // OpenBSD ships with GCC 4.2, which is now quite old.
|
| 327 |
+
}
|
| 328 |
+
|
| 329 |
+
// compilerEnvLookup returns the compiler settings for goos/goarch in map m.
|
| 330 |
+
// kind is "CC" or "CXX".
|
| 331 |
+
func compilerEnvLookup(kind string, m map[string]string, goos, goarch string) string {
|
| 332 |
+
if !needCC() {
|
| 333 |
+
return ""
|
| 334 |
+
}
|
| 335 |
+
if cc := m[goos+"/"+goarch]; cc != "" {
|
| 336 |
+
return cc
|
| 337 |
+
}
|
| 338 |
+
if cc := m[""]; cc != "" {
|
| 339 |
+
return cc
|
| 340 |
+
}
|
| 341 |
+
for _, os := range clangos {
|
| 342 |
+
if goos == os {
|
| 343 |
+
if kind == "CXX" {
|
| 344 |
+
return "clang++"
|
| 345 |
+
}
|
| 346 |
+
return "clang"
|
| 347 |
+
}
|
| 348 |
+
}
|
| 349 |
+
if kind == "CXX" {
|
| 350 |
+
return "g++"
|
| 351 |
+
}
|
| 352 |
+
return "gcc"
|
| 353 |
+
}
|
| 354 |
+
|
| 355 |
+
// rmworkdir deletes the work directory.
|
| 356 |
+
func rmworkdir() {
|
| 357 |
+
if vflag > 1 {
|
| 358 |
+
errprintf("rm -rf %s\n", workdir)
|
| 359 |
+
}
|
| 360 |
+
xremoveall(workdir)
|
| 361 |
+
}
|
| 362 |
+
|
| 363 |
+
// Remove trailing spaces.
|
| 364 |
+
func chomp(s string) string {
|
| 365 |
+
return strings.TrimRight(s, " \t\r\n")
|
| 366 |
+
}
|
| 367 |
+
|
| 368 |
+
// findgoversion determines the Go version to use in the version string.
|
| 369 |
+
// It also parses any other metadata found in the version file.
|
| 370 |
+
func findgoversion() string {
|
| 371 |
+
// The $GOROOT/VERSION file takes priority, for distributions
|
| 372 |
+
// without the source repo.
|
| 373 |
+
path := pathf("%s/VERSION", goroot)
|
| 374 |
+
if isfile(path) {
|
| 375 |
+
b := chomp(readfile(path))
|
| 376 |
+
|
| 377 |
+
// Starting in Go 1.21 the VERSION file starts with the
|
| 378 |
+
// version on a line by itself but then can contain other
|
| 379 |
+
// metadata about the release, one item per line.
|
| 380 |
+
if i := strings.Index(b, "\n"); i >= 0 {
|
| 381 |
+
rest := b[i+1:]
|
| 382 |
+
b = chomp(b[:i])
|
| 383 |
+
for line := range strings.SplitSeq(rest, "\n") {
|
| 384 |
+
f := strings.Fields(line)
|
| 385 |
+
if len(f) == 0 {
|
| 386 |
+
continue
|
| 387 |
+
}
|
| 388 |
+
switch f[0] {
|
| 389 |
+
default:
|
| 390 |
+
fatalf("VERSION: unexpected line: %s", line)
|
| 391 |
+
case "time":
|
| 392 |
+
if len(f) != 2 {
|
| 393 |
+
fatalf("VERSION: unexpected time line: %s", line)
|
| 394 |
+
}
|
| 395 |
+
_, err := time.Parse(time.RFC3339, f[1])
|
| 396 |
+
if err != nil {
|
| 397 |
+
fatalf("VERSION: bad time: %s", err)
|
| 398 |
+
}
|
| 399 |
+
}
|
| 400 |
+
}
|
| 401 |
+
}
|
| 402 |
+
|
| 403 |
+
// Commands such as "dist version > VERSION" will cause
|
| 404 |
+
// the shell to create an empty VERSION file and set dist's
|
| 405 |
+
// stdout to its fd. dist in turn looks at VERSION and uses
|
| 406 |
+
// its content if available, which is empty at this point.
|
| 407 |
+
// Only use the VERSION file if it is non-empty.
|
| 408 |
+
if b != "" {
|
| 409 |
+
return b
|
| 410 |
+
}
|
| 411 |
+
}
|
| 412 |
+
|
| 413 |
+
// The $GOROOT/VERSION.cache file is a cache to avoid invoking
|
| 414 |
+
// git every time we run this command. Unlike VERSION, it gets
|
| 415 |
+
// deleted by the clean command.
|
| 416 |
+
path = pathf("%s/VERSION.cache", goroot)
|
| 417 |
+
if isfile(path) {
|
| 418 |
+
return chomp(readfile(path))
|
| 419 |
+
}
|
| 420 |
+
|
| 421 |
+
// Show a nicer error message if this isn't a Git repo.
|
| 422 |
+
if !isGitRepo() {
|
| 423 |
+
fatalf("FAILED: not a Git repo; must put a VERSION file in $GOROOT")
|
| 424 |
+
}
|
| 425 |
+
|
| 426 |
+
// Otherwise, use Git.
|
| 427 |
+
//
|
| 428 |
+
// Include 1.x base version, hash, and date in the version.
|
| 429 |
+
// Make sure it includes the substring "devel", but otherwise
|
| 430 |
+
// use a format compatible with https://go.dev/doc/toolchain#name
|
| 431 |
+
// so that it's possible to use go/version.Lang, Compare and so on.
|
| 432 |
+
// See go.dev/issue/73372.
|
| 433 |
+
//
|
| 434 |
+
// Note that we lightly parse internal/goversion/goversion.go to
|
| 435 |
+
// obtain the base version. We can't just import the package,
|
| 436 |
+
// because cmd/dist is built with a bootstrap GOROOT which could
|
| 437 |
+
// be an entirely different version of Go. We assume
|
| 438 |
+
// that the file contains "const Version = <Integer>".
|
| 439 |
+
goversionSource := readfile(pathf("%s/src/internal/goversion/goversion.go", goroot))
|
| 440 |
+
m := regexp.MustCompile(`(?m)^const Version = (\d+)`).FindStringSubmatch(goversionSource)
|
| 441 |
+
if m == nil {
|
| 442 |
+
fatalf("internal/goversion/goversion.go does not contain 'const Version = ...'")
|
| 443 |
+
}
|
| 444 |
+
version := fmt.Sprintf("go1.%s-devel_", m[1])
|
| 445 |
+
version += chomp(run(goroot, CheckExit, "git", "log", "-n", "1", "--format=format:%h %cd", "HEAD"))
|
| 446 |
+
|
| 447 |
+
// Cache version.
|
| 448 |
+
writefile(version, path, 0)
|
| 449 |
+
|
| 450 |
+
return version
|
| 451 |
+
}
|
| 452 |
+
|
| 453 |
+
// goModVersion returns the go version declared in src/go.mod. This is the
|
| 454 |
+
// go version to use in the go.mod building go_bootstrap, toolchain2, and toolchain3.
|
| 455 |
+
// (toolchain1 must be built with requiredBootstrapVersion(goModVersion))
|
| 456 |
+
func goModVersion() string {
|
| 457 |
+
goMod := readfile(pathf("%s/src/go.mod", goroot))
|
| 458 |
+
m := regexp.MustCompile(`(?m)^go (1.\d+)$`).FindStringSubmatch(goMod)
|
| 459 |
+
if m == nil {
|
| 460 |
+
fatalf("std go.mod does not contain go 1.X")
|
| 461 |
+
}
|
| 462 |
+
return m[1]
|
| 463 |
+
}
|
| 464 |
+
|
| 465 |
+
func requiredBootstrapVersion(v string) string {
|
| 466 |
+
minorstr, ok := strings.CutPrefix(v, "1.")
|
| 467 |
+
if !ok {
|
| 468 |
+
fatalf("go version %q in go.mod does not start with %q", v, "1.")
|
| 469 |
+
}
|
| 470 |
+
minor, err := strconv.Atoi(minorstr)
|
| 471 |
+
if err != nil {
|
| 472 |
+
fatalf("invalid go version minor component %q: %v", minorstr, err)
|
| 473 |
+
}
|
| 474 |
+
// Per go.dev/doc/install/source, for N >= 22, Go version 1.N will require a Go 1.M compiler,
|
| 475 |
+
// where M is N-2 rounded down to an even number. Example: Go 1.24 and 1.25 require Go 1.22.
|
| 476 |
+
requiredMinor := minor - 2 - minor%2
|
| 477 |
+
return "1." + strconv.Itoa(requiredMinor)
|
| 478 |
+
}
|
| 479 |
+
|
| 480 |
+
// isGitRepo reports whether the working directory is inside a Git repository.
|
| 481 |
+
func isGitRepo() bool {
|
| 482 |
+
// NB: simply checking the exit code of `git rev-parse --git-dir` would
|
| 483 |
+
// suffice here, but that requires deviating from the infrastructure
|
| 484 |
+
// provided by `run`.
|
| 485 |
+
gitDir := chomp(run(goroot, 0, "git", "rev-parse", "--git-dir"))
|
| 486 |
+
if !filepath.IsAbs(gitDir) {
|
| 487 |
+
gitDir = filepath.Join(goroot, gitDir)
|
| 488 |
+
}
|
| 489 |
+
return isdir(gitDir)
|
| 490 |
+
}
|
| 491 |
+
|
| 492 |
+
/*
|
| 493 |
+
* Initial tree setup.
|
| 494 |
+
*/
|
| 495 |
+
|
| 496 |
+
// The old tools that no longer live in $GOBIN or $GOROOT/bin.
|
| 497 |
+
var oldtool = []string{
|
| 498 |
+
"5a", "5c", "5g", "5l",
|
| 499 |
+
"6a", "6c", "6g", "6l",
|
| 500 |
+
"8a", "8c", "8g", "8l",
|
| 501 |
+
"9a", "9c", "9g", "9l",
|
| 502 |
+
"6cov",
|
| 503 |
+
"6nm",
|
| 504 |
+
"6prof",
|
| 505 |
+
"cgo",
|
| 506 |
+
"ebnflint",
|
| 507 |
+
"goapi",
|
| 508 |
+
"gofix",
|
| 509 |
+
"goinstall",
|
| 510 |
+
"gomake",
|
| 511 |
+
"gopack",
|
| 512 |
+
"gopprof",
|
| 513 |
+
"gotest",
|
| 514 |
+
"gotype",
|
| 515 |
+
"govet",
|
| 516 |
+
"goyacc",
|
| 517 |
+
"quietgcc",
|
| 518 |
+
}
|
| 519 |
+
|
| 520 |
+
// Unreleased directories (relative to $GOROOT) that should
|
| 521 |
+
// not be in release branches.
|
| 522 |
+
var unreleased = []string{
|
| 523 |
+
"src/cmd/newlink",
|
| 524 |
+
"src/cmd/objwriter",
|
| 525 |
+
"src/debug/goobj",
|
| 526 |
+
"src/old",
|
| 527 |
+
}
|
| 528 |
+
|
| 529 |
+
// setup sets up the tree for the initial build.
|
| 530 |
+
func setup() {
|
| 531 |
+
// Create bin directory.
|
| 532 |
+
if p := pathf("%s/bin", goroot); !isdir(p) {
|
| 533 |
+
xmkdir(p)
|
| 534 |
+
}
|
| 535 |
+
|
| 536 |
+
// Create package directory.
|
| 537 |
+
if p := pathf("%s/pkg", goroot); !isdir(p) {
|
| 538 |
+
xmkdir(p)
|
| 539 |
+
}
|
| 540 |
+
|
| 541 |
+
goosGoarch := pathf("%s/pkg/%s_%s", goroot, gohostos, gohostarch)
|
| 542 |
+
if rebuildall {
|
| 543 |
+
xremoveall(goosGoarch)
|
| 544 |
+
}
|
| 545 |
+
xmkdirall(goosGoarch)
|
| 546 |
+
xatexit(func() {
|
| 547 |
+
if files := xreaddir(goosGoarch); len(files) == 0 {
|
| 548 |
+
xremove(goosGoarch)
|
| 549 |
+
}
|
| 550 |
+
})
|
| 551 |
+
|
| 552 |
+
if goos != gohostos || goarch != gohostarch {
|
| 553 |
+
p := pathf("%s/pkg/%s_%s", goroot, goos, goarch)
|
| 554 |
+
if rebuildall {
|
| 555 |
+
xremoveall(p)
|
| 556 |
+
}
|
| 557 |
+
xmkdirall(p)
|
| 558 |
+
}
|
| 559 |
+
|
| 560 |
+
// Create object directory.
|
| 561 |
+
// We used to use it for C objects.
|
| 562 |
+
// Now we use it for the build cache, to separate dist's cache
|
| 563 |
+
// from any other cache the user might have, and for the location
|
| 564 |
+
// to build the bootstrap versions of the standard library.
|
| 565 |
+
obj := pathf("%s/pkg/obj", goroot)
|
| 566 |
+
if !isdir(obj) {
|
| 567 |
+
xmkdir(obj)
|
| 568 |
+
}
|
| 569 |
+
xatexit(func() { xremove(obj) })
|
| 570 |
+
|
| 571 |
+
// Create build cache directory.
|
| 572 |
+
objGobuild := pathf("%s/pkg/obj/go-build", goroot)
|
| 573 |
+
if rebuildall {
|
| 574 |
+
xremoveall(objGobuild)
|
| 575 |
+
}
|
| 576 |
+
xmkdirall(objGobuild)
|
| 577 |
+
xatexit(func() { xremoveall(objGobuild) })
|
| 578 |
+
|
| 579 |
+
// Create directory for bootstrap versions of standard library .a files.
|
| 580 |
+
objGoBootstrap := pathf("%s/pkg/obj/go-bootstrap", goroot)
|
| 581 |
+
if rebuildall {
|
| 582 |
+
xremoveall(objGoBootstrap)
|
| 583 |
+
}
|
| 584 |
+
xmkdirall(objGoBootstrap)
|
| 585 |
+
xatexit(func() { xremoveall(objGoBootstrap) })
|
| 586 |
+
|
| 587 |
+
// Create tool directory.
|
| 588 |
+
// We keep it in pkg/, just like the object directory above.
|
| 589 |
+
if rebuildall {
|
| 590 |
+
xremoveall(tooldir)
|
| 591 |
+
}
|
| 592 |
+
xmkdirall(tooldir)
|
| 593 |
+
|
| 594 |
+
// Remove tool binaries from before the tool/gohostos_gohostarch
|
| 595 |
+
xremoveall(pathf("%s/bin/tool", goroot))
|
| 596 |
+
|
| 597 |
+
// Remove old pre-tool binaries.
|
| 598 |
+
for _, old := range oldtool {
|
| 599 |
+
xremove(pathf("%s/bin/%s", goroot, old))
|
| 600 |
+
}
|
| 601 |
+
|
| 602 |
+
// Special release-specific setup.
|
| 603 |
+
if isRelease {
|
| 604 |
+
// Make sure release-excluded things are excluded.
|
| 605 |
+
for _, dir := range unreleased {
|
| 606 |
+
if p := pathf("%s/%s", goroot, dir); isdir(p) {
|
| 607 |
+
fatalf("%s should not exist in release build", p)
|
| 608 |
+
}
|
| 609 |
+
}
|
| 610 |
+
}
|
| 611 |
+
}
|
| 612 |
+
|
| 613 |
+
/*
|
| 614 |
+
* Tool building
|
| 615 |
+
*/
|
| 616 |
+
|
| 617 |
+
// mustLinkExternal is a copy of internal/platform.MustLinkExternal,
|
| 618 |
+
// duplicated here to avoid version skew in the MustLinkExternal function
|
| 619 |
+
// during bootstrapping.
|
| 620 |
+
func mustLinkExternal(goos, goarch string, cgoEnabled bool) bool {
|
| 621 |
+
if cgoEnabled {
|
| 622 |
+
switch goarch {
|
| 623 |
+
case "mips", "mipsle", "mips64", "mips64le":
|
| 624 |
+
// Internally linking cgo is incomplete on some architectures.
|
| 625 |
+
// https://golang.org/issue/14449
|
| 626 |
+
return true
|
| 627 |
+
case "ppc64":
|
| 628 |
+
// Big Endian PPC64 cgo internal linking is not implemented for aix or linux.
|
| 629 |
+
if goos == "aix" || goos == "linux" {
|
| 630 |
+
return true
|
| 631 |
+
}
|
| 632 |
+
}
|
| 633 |
+
|
| 634 |
+
switch goos {
|
| 635 |
+
case "android":
|
| 636 |
+
return true
|
| 637 |
+
case "dragonfly":
|
| 638 |
+
// It seems that on Dragonfly thread local storage is
|
| 639 |
+
// set up by the dynamic linker, so internal cgo linking
|
| 640 |
+
// doesn't work. Test case is "go test runtime/cgo".
|
| 641 |
+
return true
|
| 642 |
+
}
|
| 643 |
+
}
|
| 644 |
+
|
| 645 |
+
switch goos {
|
| 646 |
+
case "android":
|
| 647 |
+
if goarch != "arm64" {
|
| 648 |
+
return true
|
| 649 |
+
}
|
| 650 |
+
case "ios":
|
| 651 |
+
if goarch == "arm64" {
|
| 652 |
+
return true
|
| 653 |
+
}
|
| 654 |
+
}
|
| 655 |
+
return false
|
| 656 |
+
}
|
| 657 |
+
|
| 658 |
+
// depsuffix records the allowed suffixes for source files.
|
| 659 |
+
var depsuffix = []string{
|
| 660 |
+
".s",
|
| 661 |
+
".go",
|
| 662 |
+
}
|
| 663 |
+
|
| 664 |
+
// gentab records how to generate some trivial files.
|
| 665 |
+
// Files listed here should also be listed in ../distpack/pack.go's srcArch.Remove list.
|
| 666 |
+
var gentab = []struct {
|
| 667 |
+
pkg string // Relative to $GOROOT/src
|
| 668 |
+
file string
|
| 669 |
+
gen func(dir, file string)
|
| 670 |
+
}{
|
| 671 |
+
{"cmd/go/internal/cfg", "zdefaultcc.go", mkzdefaultcc},
|
| 672 |
+
{"internal/runtime/sys", "zversion.go", mkzversion},
|
| 673 |
+
{"time/tzdata", "zzipdata.go", mktzdata},
|
| 674 |
+
}
|
| 675 |
+
|
| 676 |
+
// installed maps from a dir name (as given to install) to a chan
|
| 677 |
+
// closed when the dir's package is installed.
|
| 678 |
+
var installed = make(map[string]chan struct{})
|
| 679 |
+
var installedMu sync.Mutex
|
| 680 |
+
|
| 681 |
+
func install(dir string) {
|
| 682 |
+
<-startInstall(dir)
|
| 683 |
+
}
|
| 684 |
+
|
| 685 |
+
func startInstall(dir string) chan struct{} {
|
| 686 |
+
installedMu.Lock()
|
| 687 |
+
ch := installed[dir]
|
| 688 |
+
if ch == nil {
|
| 689 |
+
ch = make(chan struct{})
|
| 690 |
+
installed[dir] = ch
|
| 691 |
+
go runInstall(dir, ch)
|
| 692 |
+
}
|
| 693 |
+
installedMu.Unlock()
|
| 694 |
+
return ch
|
| 695 |
+
}
|
| 696 |
+
|
| 697 |
+
// runInstall installs the library, package, or binary associated with pkg,
|
| 698 |
+
// which is relative to $GOROOT/src.
|
| 699 |
+
func runInstall(pkg string, ch chan struct{}) {
|
| 700 |
+
if pkg == "net" || pkg == "os/user" || pkg == "crypto/x509" {
|
| 701 |
+
fatalf("go_bootstrap cannot depend on cgo package %s", pkg)
|
| 702 |
+
}
|
| 703 |
+
|
| 704 |
+
defer close(ch)
|
| 705 |
+
|
| 706 |
+
if pkg == "unsafe" {
|
| 707 |
+
return
|
| 708 |
+
}
|
| 709 |
+
|
| 710 |
+
if vflag > 0 {
|
| 711 |
+
if goos != gohostos || goarch != gohostarch {
|
| 712 |
+
errprintf("%s (%s/%s)\n", pkg, goos, goarch)
|
| 713 |
+
} else {
|
| 714 |
+
errprintf("%s\n", pkg)
|
| 715 |
+
}
|
| 716 |
+
}
|
| 717 |
+
|
| 718 |
+
workdir := pathf("%s/%s", workdir, pkg)
|
| 719 |
+
xmkdirall(workdir)
|
| 720 |
+
|
| 721 |
+
var clean []string
|
| 722 |
+
defer func() {
|
| 723 |
+
for _, name := range clean {
|
| 724 |
+
xremove(name)
|
| 725 |
+
}
|
| 726 |
+
}()
|
| 727 |
+
|
| 728 |
+
// dir = full path to pkg.
|
| 729 |
+
dir := pathf("%s/src/%s", goroot, pkg)
|
| 730 |
+
name := filepath.Base(dir)
|
| 731 |
+
|
| 732 |
+
// ispkg predicts whether the package should be linked as a binary, based
|
| 733 |
+
// on the name. There should be no "main" packages in vendor, since
|
| 734 |
+
// 'go mod vendor' will only copy imported packages there.
|
| 735 |
+
ispkg := !strings.HasPrefix(pkg, "cmd/") || strings.Contains(pkg, "/internal/") || strings.Contains(pkg, "/vendor/")
|
| 736 |
+
|
| 737 |
+
// Start final link command line.
|
| 738 |
+
// Note: code below knows that link.p[targ] is the target.
|
| 739 |
+
var (
|
| 740 |
+
link []string
|
| 741 |
+
targ int
|
| 742 |
+
ispackcmd bool
|
| 743 |
+
)
|
| 744 |
+
if ispkg {
|
| 745 |
+
// Go library (package).
|
| 746 |
+
ispackcmd = true
|
| 747 |
+
link = []string{"pack", packagefile(pkg)}
|
| 748 |
+
targ = len(link) - 1
|
| 749 |
+
xmkdirall(filepath.Dir(link[targ]))
|
| 750 |
+
} else {
|
| 751 |
+
// Go command.
|
| 752 |
+
elem := name
|
| 753 |
+
if elem == "go" {
|
| 754 |
+
elem = "go_bootstrap"
|
| 755 |
+
}
|
| 756 |
+
link = []string{pathf("%s/link", tooldir)}
|
| 757 |
+
if goos == "android" {
|
| 758 |
+
link = append(link, "-buildmode=pie")
|
| 759 |
+
}
|
| 760 |
+
if goldflags != "" {
|
| 761 |
+
link = append(link, goldflags)
|
| 762 |
+
}
|
| 763 |
+
link = append(link, "-extld="+compilerEnvLookup("CC", defaultcc, goos, goarch))
|
| 764 |
+
link = append(link, "-L="+pathf("%s/pkg/obj/go-bootstrap/%s_%s", goroot, goos, goarch))
|
| 765 |
+
link = append(link, "-o", pathf("%s/%s%s", tooldir, elem, exe))
|
| 766 |
+
targ = len(link) - 1
|
| 767 |
+
}
|
| 768 |
+
ttarg := mtime(link[targ])
|
| 769 |
+
|
| 770 |
+
// Gather files that are sources for this target.
|
| 771 |
+
// Everything in that directory, and any target-specific
|
| 772 |
+
// additions.
|
| 773 |
+
files := xreaddir(dir)
|
| 774 |
+
|
| 775 |
+
// Remove files beginning with . or _,
|
| 776 |
+
// which are likely to be editor temporary files.
|
| 777 |
+
// This is the same heuristic build.ScanDir uses.
|
| 778 |
+
// There do exist real C files beginning with _,
|
| 779 |
+
// so limit that check to just Go files.
|
| 780 |
+
files = filter(files, func(p string) bool {
|
| 781 |
+
return !strings.HasPrefix(p, ".") && (!strings.HasPrefix(p, "_") || !strings.HasSuffix(p, ".go"))
|
| 782 |
+
})
|
| 783 |
+
|
| 784 |
+
// Add generated files for this package.
|
| 785 |
+
for _, gt := range gentab {
|
| 786 |
+
if gt.pkg == pkg {
|
| 787 |
+
files = append(files, gt.file)
|
| 788 |
+
}
|
| 789 |
+
}
|
| 790 |
+
files = uniq(files)
|
| 791 |
+
|
| 792 |
+
// Convert to absolute paths.
|
| 793 |
+
for i, p := range files {
|
| 794 |
+
if !filepath.IsAbs(p) {
|
| 795 |
+
files[i] = pathf("%s/%s", dir, p)
|
| 796 |
+
}
|
| 797 |
+
}
|
| 798 |
+
|
| 799 |
+
// Is the target up-to-date?
|
| 800 |
+
var gofiles, sfiles []string
|
| 801 |
+
stale := rebuildall
|
| 802 |
+
files = filter(files, func(p string) bool {
|
| 803 |
+
for _, suf := range depsuffix {
|
| 804 |
+
if strings.HasSuffix(p, suf) {
|
| 805 |
+
goto ok
|
| 806 |
+
}
|
| 807 |
+
}
|
| 808 |
+
return false
|
| 809 |
+
ok:
|
| 810 |
+
t := mtime(p)
|
| 811 |
+
if !t.IsZero() && !strings.HasSuffix(p, ".a") && !shouldbuild(p, pkg) {
|
| 812 |
+
return false
|
| 813 |
+
}
|
| 814 |
+
if strings.HasSuffix(p, ".go") {
|
| 815 |
+
gofiles = append(gofiles, p)
|
| 816 |
+
} else if strings.HasSuffix(p, ".s") {
|
| 817 |
+
sfiles = append(sfiles, p)
|
| 818 |
+
}
|
| 819 |
+
if t.After(ttarg) {
|
| 820 |
+
stale = true
|
| 821 |
+
}
|
| 822 |
+
return true
|
| 823 |
+
})
|
| 824 |
+
|
| 825 |
+
// If there are no files to compile, we're done.
|
| 826 |
+
if len(files) == 0 {
|
| 827 |
+
return
|
| 828 |
+
}
|
| 829 |
+
|
| 830 |
+
if !stale {
|
| 831 |
+
return
|
| 832 |
+
}
|
| 833 |
+
|
| 834 |
+
// For package runtime, copy some files into the work space.
|
| 835 |
+
if pkg == "runtime" {
|
| 836 |
+
xmkdirall(pathf("%s/pkg/include", goroot))
|
| 837 |
+
// For use by assembly and C files.
|
| 838 |
+
copyfile(pathf("%s/pkg/include/textflag.h", goroot),
|
| 839 |
+
pathf("%s/src/runtime/textflag.h", goroot), 0)
|
| 840 |
+
copyfile(pathf("%s/pkg/include/funcdata.h", goroot),
|
| 841 |
+
pathf("%s/src/runtime/funcdata.h", goroot), 0)
|
| 842 |
+
copyfile(pathf("%s/pkg/include/asm_ppc64x.h", goroot),
|
| 843 |
+
pathf("%s/src/runtime/asm_ppc64x.h", goroot), 0)
|
| 844 |
+
copyfile(pathf("%s/pkg/include/asm_amd64.h", goroot),
|
| 845 |
+
pathf("%s/src/runtime/asm_amd64.h", goroot), 0)
|
| 846 |
+
copyfile(pathf("%s/pkg/include/asm_riscv64.h", goroot),
|
| 847 |
+
pathf("%s/src/runtime/asm_riscv64.h", goroot), 0)
|
| 848 |
+
}
|
| 849 |
+
|
| 850 |
+
// Generate any missing files; regenerate existing ones.
|
| 851 |
+
for _, gt := range gentab {
|
| 852 |
+
if gt.pkg != pkg {
|
| 853 |
+
continue
|
| 854 |
+
}
|
| 855 |
+
p := pathf("%s/%s", dir, gt.file)
|
| 856 |
+
if vflag > 1 {
|
| 857 |
+
errprintf("generate %s\n", p)
|
| 858 |
+
}
|
| 859 |
+
gt.gen(dir, p)
|
| 860 |
+
// Do not add generated file to clean list.
|
| 861 |
+
// In runtime, we want to be able to
|
| 862 |
+
// build the package with the go tool,
|
| 863 |
+
// and it assumes these generated files already
|
| 864 |
+
// exist (it does not know how to build them).
|
| 865 |
+
// The 'clean' command can remove
|
| 866 |
+
// the generated files.
|
| 867 |
+
}
|
| 868 |
+
|
| 869 |
+
// Resolve imported packages to actual package paths.
|
| 870 |
+
// Make sure they're installed.
|
| 871 |
+
importMap := make(map[string]string)
|
| 872 |
+
for _, p := range gofiles {
|
| 873 |
+
for _, imp := range readimports(p) {
|
| 874 |
+
if imp == "C" {
|
| 875 |
+
fatalf("%s imports C", p)
|
| 876 |
+
}
|
| 877 |
+
importMap[imp] = resolveVendor(imp, dir)
|
| 878 |
+
}
|
| 879 |
+
}
|
| 880 |
+
sortedImports := make([]string, 0, len(importMap))
|
| 881 |
+
for imp := range importMap {
|
| 882 |
+
sortedImports = append(sortedImports, imp)
|
| 883 |
+
}
|
| 884 |
+
sort.Strings(sortedImports)
|
| 885 |
+
|
| 886 |
+
for _, dep := range importMap {
|
| 887 |
+
if dep == "C" {
|
| 888 |
+
fatalf("%s imports C", pkg)
|
| 889 |
+
}
|
| 890 |
+
startInstall(dep)
|
| 891 |
+
}
|
| 892 |
+
for _, dep := range importMap {
|
| 893 |
+
install(dep)
|
| 894 |
+
}
|
| 895 |
+
|
| 896 |
+
if goos != gohostos || goarch != gohostarch {
|
| 897 |
+
// We've generated the right files; the go command can do the build.
|
| 898 |
+
if vflag > 1 {
|
| 899 |
+
errprintf("skip build for cross-compile %s\n", pkg)
|
| 900 |
+
}
|
| 901 |
+
return
|
| 902 |
+
}
|
| 903 |
+
|
| 904 |
+
asmArgs := []string{
|
| 905 |
+
pathf("%s/asm", tooldir),
|
| 906 |
+
"-I", workdir,
|
| 907 |
+
"-I", pathf("%s/pkg/include", goroot),
|
| 908 |
+
"-D", "GOOS_" + goos,
|
| 909 |
+
"-D", "GOARCH_" + goarch,
|
| 910 |
+
"-D", "GOOS_GOARCH_" + goos + "_" + goarch,
|
| 911 |
+
"-p", pkg,
|
| 912 |
+
}
|
| 913 |
+
if goarch == "mips" || goarch == "mipsle" {
|
| 914 |
+
// Define GOMIPS_value from gomips.
|
| 915 |
+
asmArgs = append(asmArgs, "-D", "GOMIPS_"+gomips)
|
| 916 |
+
}
|
| 917 |
+
if goarch == "mips64" || goarch == "mips64le" {
|
| 918 |
+
// Define GOMIPS64_value from gomips64.
|
| 919 |
+
asmArgs = append(asmArgs, "-D", "GOMIPS64_"+gomips64)
|
| 920 |
+
}
|
| 921 |
+
if goarch == "ppc64" || goarch == "ppc64le" {
|
| 922 |
+
// We treat each powerpc version as a superset of functionality.
|
| 923 |
+
switch goppc64 {
|
| 924 |
+
case "power10":
|
| 925 |
+
asmArgs = append(asmArgs, "-D", "GOPPC64_power10")
|
| 926 |
+
fallthrough
|
| 927 |
+
case "power9":
|
| 928 |
+
asmArgs = append(asmArgs, "-D", "GOPPC64_power9")
|
| 929 |
+
fallthrough
|
| 930 |
+
default: // This should always be power8.
|
| 931 |
+
asmArgs = append(asmArgs, "-D", "GOPPC64_power8")
|
| 932 |
+
}
|
| 933 |
+
}
|
| 934 |
+
if goarch == "riscv64" {
|
| 935 |
+
// Define GORISCV64_value from goriscv64
|
| 936 |
+
asmArgs = append(asmArgs, "-D", "GORISCV64_"+goriscv64)
|
| 937 |
+
}
|
| 938 |
+
if goarch == "arm" {
|
| 939 |
+
// Define GOARM_value from goarm, which can be either a version
|
| 940 |
+
// like "6", or a version and a FP mode, like "7,hardfloat".
|
| 941 |
+
switch {
|
| 942 |
+
case strings.Contains(goarm, "7"):
|
| 943 |
+
asmArgs = append(asmArgs, "-D", "GOARM_7")
|
| 944 |
+
fallthrough
|
| 945 |
+
case strings.Contains(goarm, "6"):
|
| 946 |
+
asmArgs = append(asmArgs, "-D", "GOARM_6")
|
| 947 |
+
fallthrough
|
| 948 |
+
default:
|
| 949 |
+
asmArgs = append(asmArgs, "-D", "GOARM_5")
|
| 950 |
+
}
|
| 951 |
+
}
|
| 952 |
+
goasmh := pathf("%s/go_asm.h", workdir)
|
| 953 |
+
|
| 954 |
+
// Collect symabis from assembly code.
|
| 955 |
+
var symabis string
|
| 956 |
+
if len(sfiles) > 0 {
|
| 957 |
+
symabis = pathf("%s/symabis", workdir)
|
| 958 |
+
var wg sync.WaitGroup
|
| 959 |
+
asmabis := append(asmArgs[:len(asmArgs):len(asmArgs)], "-gensymabis", "-o", symabis)
|
| 960 |
+
asmabis = append(asmabis, sfiles...)
|
| 961 |
+
if err := os.WriteFile(goasmh, nil, 0666); err != nil {
|
| 962 |
+
fatalf("cannot write empty go_asm.h: %s", err)
|
| 963 |
+
}
|
| 964 |
+
bgrun(&wg, dir, asmabis...)
|
| 965 |
+
bgwait(&wg)
|
| 966 |
+
}
|
| 967 |
+
|
| 968 |
+
// Build an importcfg file for the compiler.
|
| 969 |
+
buf := &bytes.Buffer{}
|
| 970 |
+
for _, imp := range sortedImports {
|
| 971 |
+
if imp == "unsafe" {
|
| 972 |
+
continue
|
| 973 |
+
}
|
| 974 |
+
dep := importMap[imp]
|
| 975 |
+
if imp != dep {
|
| 976 |
+
fmt.Fprintf(buf, "importmap %s=%s\n", imp, dep)
|
| 977 |
+
}
|
| 978 |
+
fmt.Fprintf(buf, "packagefile %s=%s\n", dep, packagefile(dep))
|
| 979 |
+
}
|
| 980 |
+
importcfg := pathf("%s/importcfg", workdir)
|
| 981 |
+
if err := os.WriteFile(importcfg, buf.Bytes(), 0666); err != nil {
|
| 982 |
+
fatalf("cannot write importcfg file: %v", err)
|
| 983 |
+
}
|
| 984 |
+
|
| 985 |
+
var archive string
|
| 986 |
+
// The next loop will compile individual non-Go files.
|
| 987 |
+
// Hand the Go files to the compiler en masse.
|
| 988 |
+
// For packages containing assembly, this writes go_asm.h, which
|
| 989 |
+
// the assembly files will need.
|
| 990 |
+
pkgName := pkg
|
| 991 |
+
if strings.HasPrefix(pkg, "cmd/") && strings.Count(pkg, "/") == 1 {
|
| 992 |
+
pkgName = "main"
|
| 993 |
+
}
|
| 994 |
+
b := pathf("%s/_go_.a", workdir)
|
| 995 |
+
clean = append(clean, b)
|
| 996 |
+
if !ispackcmd {
|
| 997 |
+
link = append(link, b)
|
| 998 |
+
} else {
|
| 999 |
+
archive = b
|
| 1000 |
+
}
|
| 1001 |
+
|
| 1002 |
+
// Compile Go code.
|
| 1003 |
+
compile := []string{pathf("%s/compile", tooldir), "-std", "-pack", "-o", b, "-p", pkgName, "-importcfg", importcfg}
|
| 1004 |
+
if gogcflags != "" {
|
| 1005 |
+
compile = append(compile, strings.Fields(gogcflags)...)
|
| 1006 |
+
}
|
| 1007 |
+
if len(sfiles) > 0 {
|
| 1008 |
+
compile = append(compile, "-asmhdr", goasmh)
|
| 1009 |
+
}
|
| 1010 |
+
if symabis != "" {
|
| 1011 |
+
compile = append(compile, "-symabis", symabis)
|
| 1012 |
+
}
|
| 1013 |
+
if goos == "android" {
|
| 1014 |
+
compile = append(compile, "-shared")
|
| 1015 |
+
}
|
| 1016 |
+
|
| 1017 |
+
compile = append(compile, gofiles...)
|
| 1018 |
+
var wg sync.WaitGroup
|
| 1019 |
+
// We use bgrun and immediately wait for it instead of calling run() synchronously.
|
| 1020 |
+
// This executes all jobs through the bgwork channel and allows the process
|
| 1021 |
+
// to exit cleanly in case an error occurs.
|
| 1022 |
+
bgrun(&wg, dir, compile...)
|
| 1023 |
+
bgwait(&wg)
|
| 1024 |
+
|
| 1025 |
+
// Compile the files.
|
| 1026 |
+
for _, p := range sfiles {
|
| 1027 |
+
// Assembly file for a Go package.
|
| 1028 |
+
compile := asmArgs[:len(asmArgs):len(asmArgs)]
|
| 1029 |
+
|
| 1030 |
+
doclean := true
|
| 1031 |
+
b := pathf("%s/%s", workdir, filepath.Base(p))
|
| 1032 |
+
|
| 1033 |
+
// Change the last character of the output file (which was c or s).
|
| 1034 |
+
b = b[:len(b)-1] + "o"
|
| 1035 |
+
compile = append(compile, "-o", b, p)
|
| 1036 |
+
bgrun(&wg, dir, compile...)
|
| 1037 |
+
|
| 1038 |
+
link = append(link, b)
|
| 1039 |
+
if doclean {
|
| 1040 |
+
clean = append(clean, b)
|
| 1041 |
+
}
|
| 1042 |
+
}
|
| 1043 |
+
bgwait(&wg)
|
| 1044 |
+
|
| 1045 |
+
if ispackcmd {
|
| 1046 |
+
xremove(link[targ])
|
| 1047 |
+
dopack(link[targ], archive, link[targ+1:])
|
| 1048 |
+
return
|
| 1049 |
+
}
|
| 1050 |
+
|
| 1051 |
+
// Remove target before writing it.
|
| 1052 |
+
xremove(link[targ])
|
| 1053 |
+
bgrun(&wg, "", link...)
|
| 1054 |
+
bgwait(&wg)
|
| 1055 |
+
}
|
| 1056 |
+
|
| 1057 |
+
// packagefile returns the path to a compiled .a file for the given package
|
| 1058 |
+
// path. Paths may need to be resolved with resolveVendor first.
|
| 1059 |
+
func packagefile(pkg string) string {
|
| 1060 |
+
return pathf("%s/pkg/obj/go-bootstrap/%s_%s/%s.a", goroot, goos, goarch, pkg)
|
| 1061 |
+
}
|
| 1062 |
+
|
| 1063 |
+
// unixOS is the set of GOOS values matched by the "unix" build tag.
|
| 1064 |
+
// This is the same list as in internal/syslist/syslist.go.
|
| 1065 |
+
var unixOS = map[string]bool{
|
| 1066 |
+
"aix": true,
|
| 1067 |
+
"android": true,
|
| 1068 |
+
"darwin": true,
|
| 1069 |
+
"dragonfly": true,
|
| 1070 |
+
"freebsd": true,
|
| 1071 |
+
"hurd": true,
|
| 1072 |
+
"illumos": true,
|
| 1073 |
+
"ios": true,
|
| 1074 |
+
"linux": true,
|
| 1075 |
+
"netbsd": true,
|
| 1076 |
+
"openbsd": true,
|
| 1077 |
+
"solaris": true,
|
| 1078 |
+
}
|
| 1079 |
+
|
| 1080 |
+
// matchtag reports whether the tag matches this build.
|
| 1081 |
+
func matchtag(tag string) bool {
|
| 1082 |
+
switch tag {
|
| 1083 |
+
case "gc", "cmd_go_bootstrap", "go1.1":
|
| 1084 |
+
return true
|
| 1085 |
+
case "linux":
|
| 1086 |
+
return goos == "linux" || goos == "android"
|
| 1087 |
+
case "solaris":
|
| 1088 |
+
return goos == "solaris" || goos == "illumos"
|
| 1089 |
+
case "darwin":
|
| 1090 |
+
return goos == "darwin" || goos == "ios"
|
| 1091 |
+
case goos, goarch:
|
| 1092 |
+
return true
|
| 1093 |
+
case "unix":
|
| 1094 |
+
return unixOS[goos]
|
| 1095 |
+
default:
|
| 1096 |
+
return false
|
| 1097 |
+
}
|
| 1098 |
+
}
|
| 1099 |
+
|
| 1100 |
+
// shouldbuild reports whether we should build this file.
|
| 1101 |
+
// It applies the same rules that are used with context tags
|
| 1102 |
+
// in package go/build, except it's less picky about the order
|
| 1103 |
+
// of GOOS and GOARCH.
|
| 1104 |
+
// We also allow the special tag cmd_go_bootstrap.
|
| 1105 |
+
// See ../go/bootstrap.go and package go/build.
|
| 1106 |
+
func shouldbuild(file, pkg string) bool {
|
| 1107 |
+
// Check file name for GOOS or GOARCH.
|
| 1108 |
+
name := filepath.Base(file)
|
| 1109 |
+
excluded := func(list []string, ok string) bool {
|
| 1110 |
+
for _, x := range list {
|
| 1111 |
+
if x == ok || (ok == "android" && x == "linux") || (ok == "illumos" && x == "solaris") || (ok == "ios" && x == "darwin") {
|
| 1112 |
+
continue
|
| 1113 |
+
}
|
| 1114 |
+
i := strings.Index(name, x)
|
| 1115 |
+
if i <= 0 || name[i-1] != '_' {
|
| 1116 |
+
continue
|
| 1117 |
+
}
|
| 1118 |
+
i += len(x)
|
| 1119 |
+
if i == len(name) || name[i] == '.' || name[i] == '_' {
|
| 1120 |
+
return true
|
| 1121 |
+
}
|
| 1122 |
+
}
|
| 1123 |
+
return false
|
| 1124 |
+
}
|
| 1125 |
+
if excluded(okgoos, goos) || excluded(okgoarch, goarch) {
|
| 1126 |
+
return false
|
| 1127 |
+
}
|
| 1128 |
+
|
| 1129 |
+
// Omit test files.
|
| 1130 |
+
if strings.Contains(name, "_test") {
|
| 1131 |
+
return false
|
| 1132 |
+
}
|
| 1133 |
+
|
| 1134 |
+
// Check file contents for //go:build lines.
|
| 1135 |
+
for p := range strings.SplitSeq(readfile(file), "\n") {
|
| 1136 |
+
p = strings.TrimSpace(p)
|
| 1137 |
+
if p == "" {
|
| 1138 |
+
continue
|
| 1139 |
+
}
|
| 1140 |
+
code := p
|
| 1141 |
+
i := strings.Index(code, "//")
|
| 1142 |
+
if i > 0 {
|
| 1143 |
+
code = strings.TrimSpace(code[:i])
|
| 1144 |
+
}
|
| 1145 |
+
if code == "package documentation" {
|
| 1146 |
+
return false
|
| 1147 |
+
}
|
| 1148 |
+
if code == "package main" && pkg != "cmd/go" && pkg != "cmd/cgo" {
|
| 1149 |
+
return false
|
| 1150 |
+
}
|
| 1151 |
+
if !strings.HasPrefix(p, "//") {
|
| 1152 |
+
break
|
| 1153 |
+
}
|
| 1154 |
+
if strings.HasPrefix(p, "//go:build ") {
|
| 1155 |
+
matched, err := matchexpr(p[len("//go:build "):])
|
| 1156 |
+
if err != nil {
|
| 1157 |
+
errprintf("%s: %v", file, err)
|
| 1158 |
+
}
|
| 1159 |
+
return matched
|
| 1160 |
+
}
|
| 1161 |
+
}
|
| 1162 |
+
|
| 1163 |
+
return true
|
| 1164 |
+
}
|
| 1165 |
+
|
| 1166 |
+
// copyfile copies the file src to dst, via memory (so only good for small files).
|
| 1167 |
+
func copyfile(dst, src string, flag int) {
|
| 1168 |
+
if vflag > 1 {
|
| 1169 |
+
errprintf("cp %s %s\n", src, dst)
|
| 1170 |
+
}
|
| 1171 |
+
writefile(readfile(src), dst, flag)
|
| 1172 |
+
}
|
| 1173 |
+
|
| 1174 |
+
// dopack copies the package src to dst,
|
| 1175 |
+
// appending the files listed in extra.
|
| 1176 |
+
// The archive format is the traditional Unix ar format.
|
| 1177 |
+
func dopack(dst, src string, extra []string) {
|
| 1178 |
+
bdst := bytes.NewBufferString(readfile(src))
|
| 1179 |
+
for _, file := range extra {
|
| 1180 |
+
b := readfile(file)
|
| 1181 |
+
// find last path element for archive member name
|
| 1182 |
+
i := strings.LastIndex(file, "/") + 1
|
| 1183 |
+
j := strings.LastIndex(file, `\`) + 1
|
| 1184 |
+
if i < j {
|
| 1185 |
+
i = j
|
| 1186 |
+
}
|
| 1187 |
+
fmt.Fprintf(bdst, "%-16.16s%-12d%-6d%-6d%-8o%-10d`\n", file[i:], 0, 0, 0, 0644, len(b))
|
| 1188 |
+
bdst.WriteString(b)
|
| 1189 |
+
if len(b)&1 != 0 {
|
| 1190 |
+
bdst.WriteByte(0)
|
| 1191 |
+
}
|
| 1192 |
+
}
|
| 1193 |
+
writefile(bdst.String(), dst, 0)
|
| 1194 |
+
}
|
| 1195 |
+
|
| 1196 |
+
func clean() {
|
| 1197 |
+
generated := []byte(generatedHeader)
|
| 1198 |
+
|
| 1199 |
+
// Remove generated source files.
|
| 1200 |
+
filepath.WalkDir(pathf("%s/src", goroot), func(path string, d fs.DirEntry, err error) error {
|
| 1201 |
+
switch {
|
| 1202 |
+
case err != nil:
|
| 1203 |
+
// ignore
|
| 1204 |
+
case d.IsDir() && (d.Name() == "vendor" || d.Name() == "testdata"):
|
| 1205 |
+
return filepath.SkipDir
|
| 1206 |
+
case d.IsDir() && d.Name() != "dist":
|
| 1207 |
+
// Remove generated binary named for directory, but not dist out from under us.
|
| 1208 |
+
exe := filepath.Join(path, d.Name())
|
| 1209 |
+
if info, err := os.Stat(exe); err == nil && !info.IsDir() {
|
| 1210 |
+
xremove(exe)
|
| 1211 |
+
}
|
| 1212 |
+
xremove(exe + ".exe")
|
| 1213 |
+
case !d.IsDir() && strings.HasPrefix(d.Name(), "z"):
|
| 1214 |
+
// Remove generated file, identified by marker string.
|
| 1215 |
+
head := make([]byte, 512)
|
| 1216 |
+
if f, err := os.Open(path); err == nil {
|
| 1217 |
+
io.ReadFull(f, head)
|
| 1218 |
+
f.Close()
|
| 1219 |
+
}
|
| 1220 |
+
if bytes.HasPrefix(head, generated) {
|
| 1221 |
+
xremove(path)
|
| 1222 |
+
}
|
| 1223 |
+
}
|
| 1224 |
+
return nil
|
| 1225 |
+
})
|
| 1226 |
+
|
| 1227 |
+
if rebuildall {
|
| 1228 |
+
// Remove object tree.
|
| 1229 |
+
xremoveall(pathf("%s/pkg/obj/%s_%s", goroot, gohostos, gohostarch))
|
| 1230 |
+
|
| 1231 |
+
// Remove installed packages and tools.
|
| 1232 |
+
xremoveall(pathf("%s/pkg/%s_%s", goroot, gohostos, gohostarch))
|
| 1233 |
+
xremoveall(pathf("%s/pkg/%s_%s", goroot, goos, goarch))
|
| 1234 |
+
xremoveall(pathf("%s/pkg/%s_%s_race", goroot, gohostos, gohostarch))
|
| 1235 |
+
xremoveall(pathf("%s/pkg/%s_%s_race", goroot, goos, goarch))
|
| 1236 |
+
xremoveall(tooldir)
|
| 1237 |
+
|
| 1238 |
+
// Remove cached version info.
|
| 1239 |
+
xremove(pathf("%s/VERSION.cache", goroot))
|
| 1240 |
+
|
| 1241 |
+
// Remove distribution packages.
|
| 1242 |
+
xremoveall(pathf("%s/pkg/distpack", goroot))
|
| 1243 |
+
}
|
| 1244 |
+
}
|
| 1245 |
+
|
| 1246 |
+
/*
|
| 1247 |
+
* command implementations
|
| 1248 |
+
*/
|
| 1249 |
+
|
| 1250 |
+
// The env command prints the default environment.
|
| 1251 |
+
func cmdenv() {
|
| 1252 |
+
path := flag.Bool("p", false, "emit updated PATH")
|
| 1253 |
+
plan9 := flag.Bool("9", gohostos == "plan9", "emit plan 9 syntax")
|
| 1254 |
+
windows := flag.Bool("w", gohostos == "windows", "emit windows syntax")
|
| 1255 |
+
xflagparse(0)
|
| 1256 |
+
|
| 1257 |
+
format := "%s=\"%s\";\n" // Include ; to separate variables when 'dist env' output is used with eval.
|
| 1258 |
+
switch {
|
| 1259 |
+
case *plan9:
|
| 1260 |
+
format = "%s='%s'\n"
|
| 1261 |
+
case *windows:
|
| 1262 |
+
format = "set %s=%s\r\n"
|
| 1263 |
+
}
|
| 1264 |
+
|
| 1265 |
+
xprintf(format, "GO111MODULE", "")
|
| 1266 |
+
xprintf(format, "GOARCH", goarch)
|
| 1267 |
+
xprintf(format, "GOBIN", gorootBin)
|
| 1268 |
+
xprintf(format, "GODEBUG", os.Getenv("GODEBUG"))
|
| 1269 |
+
xprintf(format, "GOENV", "off")
|
| 1270 |
+
xprintf(format, "GOFLAGS", "")
|
| 1271 |
+
xprintf(format, "GOHOSTARCH", gohostarch)
|
| 1272 |
+
xprintf(format, "GOHOSTOS", gohostos)
|
| 1273 |
+
xprintf(format, "GOOS", goos)
|
| 1274 |
+
xprintf(format, "GOPROXY", os.Getenv("GOPROXY"))
|
| 1275 |
+
xprintf(format, "GOROOT", goroot)
|
| 1276 |
+
xprintf(format, "GOTMPDIR", os.Getenv("GOTMPDIR"))
|
| 1277 |
+
xprintf(format, "GOTOOLDIR", tooldir)
|
| 1278 |
+
if goarch == "arm" {
|
| 1279 |
+
xprintf(format, "GOARM", goarm)
|
| 1280 |
+
}
|
| 1281 |
+
if goarch == "arm64" {
|
| 1282 |
+
xprintf(format, "GOARM64", goarm64)
|
| 1283 |
+
}
|
| 1284 |
+
if goarch == "386" {
|
| 1285 |
+
xprintf(format, "GO386", go386)
|
| 1286 |
+
}
|
| 1287 |
+
if goarch == "amd64" {
|
| 1288 |
+
xprintf(format, "GOAMD64", goamd64)
|
| 1289 |
+
}
|
| 1290 |
+
if goarch == "mips" || goarch == "mipsle" {
|
| 1291 |
+
xprintf(format, "GOMIPS", gomips)
|
| 1292 |
+
}
|
| 1293 |
+
if goarch == "mips64" || goarch == "mips64le" {
|
| 1294 |
+
xprintf(format, "GOMIPS64", gomips64)
|
| 1295 |
+
}
|
| 1296 |
+
if goarch == "ppc64" || goarch == "ppc64le" {
|
| 1297 |
+
xprintf(format, "GOPPC64", goppc64)
|
| 1298 |
+
}
|
| 1299 |
+
if goarch == "riscv64" {
|
| 1300 |
+
xprintf(format, "GORISCV64", goriscv64)
|
| 1301 |
+
}
|
| 1302 |
+
xprintf(format, "GOWORK", "off")
|
| 1303 |
+
|
| 1304 |
+
if *path {
|
| 1305 |
+
sep := ":"
|
| 1306 |
+
if gohostos == "windows" {
|
| 1307 |
+
sep = ";"
|
| 1308 |
+
}
|
| 1309 |
+
xprintf(format, "PATH", fmt.Sprintf("%s%s%s", gorootBin, sep, os.Getenv("PATH")))
|
| 1310 |
+
|
| 1311 |
+
// Also include $DIST_UNMODIFIED_PATH with the original $PATH
|
| 1312 |
+
// for the internal needs of "dist banner", along with export
|
| 1313 |
+
// so that it reaches the dist process. See its comment below.
|
| 1314 |
+
var exportFormat string
|
| 1315 |
+
if !*windows && !*plan9 {
|
| 1316 |
+
exportFormat = "export " + format
|
| 1317 |
+
} else {
|
| 1318 |
+
exportFormat = format
|
| 1319 |
+
}
|
| 1320 |
+
xprintf(exportFormat, "DIST_UNMODIFIED_PATH", os.Getenv("PATH"))
|
| 1321 |
+
}
|
| 1322 |
+
}
|
| 1323 |
+
|
| 1324 |
+
var (
|
| 1325 |
+
timeLogEnabled = os.Getenv("GOBUILDTIMELOGFILE") != ""
|
| 1326 |
+
timeLogMu sync.Mutex
|
| 1327 |
+
timeLogFile *os.File
|
| 1328 |
+
timeLogStart time.Time
|
| 1329 |
+
)
|
| 1330 |
+
|
| 1331 |
+
func timelog(op, name string) {
|
| 1332 |
+
if !timeLogEnabled {
|
| 1333 |
+
return
|
| 1334 |
+
}
|
| 1335 |
+
timeLogMu.Lock()
|
| 1336 |
+
defer timeLogMu.Unlock()
|
| 1337 |
+
if timeLogFile == nil {
|
| 1338 |
+
f, err := os.OpenFile(os.Getenv("GOBUILDTIMELOGFILE"), os.O_RDWR|os.O_APPEND, 0666)
|
| 1339 |
+
if err != nil {
|
| 1340 |
+
log.Fatal(err)
|
| 1341 |
+
}
|
| 1342 |
+
buf := make([]byte, 100)
|
| 1343 |
+
n, _ := f.Read(buf)
|
| 1344 |
+
s := string(buf[:n])
|
| 1345 |
+
if i := strings.Index(s, "\n"); i >= 0 {
|
| 1346 |
+
s = s[:i]
|
| 1347 |
+
}
|
| 1348 |
+
i := strings.Index(s, " start")
|
| 1349 |
+
if i < 0 {
|
| 1350 |
+
log.Fatalf("time log %s does not begin with start line", os.Getenv("GOBUILDTIMELOGFILE"))
|
| 1351 |
+
}
|
| 1352 |
+
t, err := time.Parse(time.UnixDate, s[:i])
|
| 1353 |
+
if err != nil {
|
| 1354 |
+
log.Fatalf("cannot parse time log line %q: %v", s, err)
|
| 1355 |
+
}
|
| 1356 |
+
timeLogStart = t
|
| 1357 |
+
timeLogFile = f
|
| 1358 |
+
}
|
| 1359 |
+
t := time.Now()
|
| 1360 |
+
fmt.Fprintf(timeLogFile, "%s %+.1fs %s %s\n", t.Format(time.UnixDate), t.Sub(timeLogStart).Seconds(), op, name)
|
| 1361 |
+
}
|
| 1362 |
+
|
| 1363 |
+
// toolenv returns the environment to use when building commands in cmd.
|
| 1364 |
+
//
|
| 1365 |
+
// This is a function instead of a variable because the exact toolenv depends
|
| 1366 |
+
// on the GOOS and GOARCH, and (at least for now) those are modified in place
|
| 1367 |
+
// to switch between the host and target configurations when cross-compiling.
|
| 1368 |
+
func toolenv() []string {
|
| 1369 |
+
var env []string
|
| 1370 |
+
if !mustLinkExternal(goos, goarch, false) {
|
| 1371 |
+
// Unless the platform requires external linking,
|
| 1372 |
+
// we disable cgo to get static binaries for cmd/go and cmd/pprof,
|
| 1373 |
+
// so that they work on systems without the same dynamic libraries
|
| 1374 |
+
// as the original build system.
|
| 1375 |
+
env = append(env, "CGO_ENABLED=0")
|
| 1376 |
+
}
|
| 1377 |
+
if isRelease || os.Getenv("GO_BUILDER_NAME") != "" {
|
| 1378 |
+
// Add -trimpath for reproducible builds of releases.
|
| 1379 |
+
// Include builders so that -trimpath is well-tested ahead of releases.
|
| 1380 |
+
// Do not include local development, so that people working in the
|
| 1381 |
+
// main branch for day-to-day work on the Go toolchain itself can
|
| 1382 |
+
// still have full paths for stack traces for compiler crashes and the like.
|
| 1383 |
+
env = append(env, "GOFLAGS=-trimpath -ldflags=-w -gcflags=cmd/...=-dwarf=false")
|
| 1384 |
+
}
|
| 1385 |
+
return env
|
| 1386 |
+
}
|
| 1387 |
+
|
| 1388 |
+
var (
|
| 1389 |
+
toolchain = []string{"cmd/asm", "cmd/cgo", "cmd/compile", "cmd/link", "cmd/preprofile"}
|
| 1390 |
+
|
| 1391 |
+
// Keep in sync with binExes in cmd/distpack/pack.go.
|
| 1392 |
+
binExesIncludedInDistpack = []string{"cmd/go", "cmd/gofmt"}
|
| 1393 |
+
|
| 1394 |
+
// Keep in sync with the filter in cmd/distpack/pack.go.
|
| 1395 |
+
toolsIncludedInDistpack = []string{"cmd/asm", "cmd/cgo", "cmd/compile", "cmd/cover", "cmd/fix", "cmd/link", "cmd/preprofile", "cmd/vet"}
|
| 1396 |
+
|
| 1397 |
+
// We could install all tools in "cmd", but is unnecessary because we will
|
| 1398 |
+
// remove them in distpack, so instead install the tools that will actually
|
| 1399 |
+
// be included in distpack, which is a superset of toolchain. Not installing
|
| 1400 |
+
// the tools will help us test what happens when the tools aren't present.
|
| 1401 |
+
toolsToInstall = slices.Concat(binExesIncludedInDistpack, toolsIncludedInDistpack)
|
| 1402 |
+
)
|
| 1403 |
+
|
| 1404 |
+
// The bootstrap command runs a build from scratch,
|
| 1405 |
+
// stopping at having installed the go_bootstrap command.
|
| 1406 |
+
//
|
| 1407 |
+
// WARNING: This command runs after cmd/dist is built with the Go bootstrap toolchain.
|
| 1408 |
+
// It rebuilds and installs cmd/dist with the new toolchain, so other
|
| 1409 |
+
// commands (like "go tool dist test" in run.bash) can rely on bug fixes
|
| 1410 |
+
// made since the Go bootstrap version, but this function cannot.
|
| 1411 |
+
func cmdbootstrap() {
|
| 1412 |
+
timelog("start", "dist bootstrap")
|
| 1413 |
+
defer timelog("end", "dist bootstrap")
|
| 1414 |
+
|
| 1415 |
+
var debug, distpack, force, noBanner, noClean bool
|
| 1416 |
+
flag.BoolVar(&rebuildall, "a", rebuildall, "rebuild all")
|
| 1417 |
+
flag.BoolVar(&debug, "d", debug, "enable debugging of bootstrap process")
|
| 1418 |
+
flag.BoolVar(&distpack, "distpack", distpack, "write distribution files to pkg/distpack")
|
| 1419 |
+
flag.BoolVar(&force, "force", force, "build even if the port is marked as broken")
|
| 1420 |
+
flag.BoolVar(&noBanner, "no-banner", noBanner, "do not print banner")
|
| 1421 |
+
flag.BoolVar(&noClean, "no-clean", noClean, "print deprecation warning")
|
| 1422 |
+
|
| 1423 |
+
xflagparse(0)
|
| 1424 |
+
|
| 1425 |
+
if noClean {
|
| 1426 |
+
xprintf("warning: --no-clean is deprecated and has no effect; use 'go install std cmd' instead\n")
|
| 1427 |
+
}
|
| 1428 |
+
|
| 1429 |
+
// Don't build broken ports by default.
|
| 1430 |
+
if broken[goos+"/"+goarch] && !force {
|
| 1431 |
+
fatalf("build stopped because the port %s/%s is marked as broken\n\n"+
|
| 1432 |
+
"Use the -force flag to build anyway.\n", goos, goarch)
|
| 1433 |
+
}
|
| 1434 |
+
|
| 1435 |
+
// Set GOPATH to an internal directory. We shouldn't actually
|
| 1436 |
+
// need to store files here, since the toolchain won't
|
| 1437 |
+
// depend on modules outside of vendor directories, but if
|
| 1438 |
+
// GOPATH points somewhere else (e.g., to GOROOT), the
|
| 1439 |
+
// go tool may complain.
|
| 1440 |
+
os.Setenv("GOPATH", pathf("%s/pkg/obj/gopath", goroot))
|
| 1441 |
+
|
| 1442 |
+
// Set GOPROXY=off to avoid downloading modules to the modcache in
|
| 1443 |
+
// the GOPATH set above to be inside GOROOT. The modcache is read
|
| 1444 |
+
// only so if we downloaded to the modcache, we'd create readonly
|
| 1445 |
+
// files in GOROOT, which is undesirable. See #67463)
|
| 1446 |
+
os.Setenv("GOPROXY", "off")
|
| 1447 |
+
|
| 1448 |
+
// Use a build cache separate from the default user one.
|
| 1449 |
+
// Also one that will be wiped out during startup, so that
|
| 1450 |
+
// make.bash really does start from a clean slate.
|
| 1451 |
+
oldgocache = os.Getenv("GOCACHE")
|
| 1452 |
+
os.Setenv("GOCACHE", pathf("%s/pkg/obj/go-build", goroot))
|
| 1453 |
+
|
| 1454 |
+
// Disable GOEXPERIMENT when building toolchain1 and
|
| 1455 |
+
// go_bootstrap. We don't need any experiments for the
|
| 1456 |
+
// bootstrap toolchain, and this lets us avoid duplicating the
|
| 1457 |
+
// GOEXPERIMENT-related build logic from cmd/go here. If the
|
| 1458 |
+
// bootstrap toolchain is < Go 1.17, it will ignore this
|
| 1459 |
+
// anyway since GOEXPERIMENT is baked in; otherwise it will
|
| 1460 |
+
// pick it up from the environment we set here. Once we're
|
| 1461 |
+
// using toolchain1 with dist as the build system, we need to
|
| 1462 |
+
// override this to keep the experiments assumed by the
|
| 1463 |
+
// toolchain and by dist consistent. Once go_bootstrap takes
|
| 1464 |
+
// over the build process, we'll set this back to the original
|
| 1465 |
+
// GOEXPERIMENT.
|
| 1466 |
+
os.Setenv("GOEXPERIMENT", "none")
|
| 1467 |
+
|
| 1468 |
+
if isdir(pathf("%s/src/pkg", goroot)) {
|
| 1469 |
+
fatalf("\n\n"+
|
| 1470 |
+
"The Go package sources have moved to $GOROOT/src.\n"+
|
| 1471 |
+
"*** %s still exists. ***\n"+
|
| 1472 |
+
"It probably contains stale files that may confuse the build.\n"+
|
| 1473 |
+
"Please (check what's there and) remove it and try again.\n"+
|
| 1474 |
+
"See https://golang.org/s/go14nopkg\n",
|
| 1475 |
+
pathf("%s/src/pkg", goroot))
|
| 1476 |
+
}
|
| 1477 |
+
|
| 1478 |
+
if rebuildall {
|
| 1479 |
+
clean()
|
| 1480 |
+
}
|
| 1481 |
+
|
| 1482 |
+
setup()
|
| 1483 |
+
|
| 1484 |
+
timelog("build", "toolchain1")
|
| 1485 |
+
checkCC()
|
| 1486 |
+
bootstrapBuildTools()
|
| 1487 |
+
|
| 1488 |
+
// Remember old content of $GOROOT/bin for comparison below.
|
| 1489 |
+
oldBinFiles, err := filepath.Glob(pathf("%s/bin/*", goroot))
|
| 1490 |
+
if err != nil {
|
| 1491 |
+
fatalf("glob: %v", err)
|
| 1492 |
+
}
|
| 1493 |
+
|
| 1494 |
+
// For the main bootstrap, building for host os/arch.
|
| 1495 |
+
oldgoos = goos
|
| 1496 |
+
oldgoarch = goarch
|
| 1497 |
+
goos = gohostos
|
| 1498 |
+
goarch = gohostarch
|
| 1499 |
+
os.Setenv("GOHOSTARCH", gohostarch)
|
| 1500 |
+
os.Setenv("GOHOSTOS", gohostos)
|
| 1501 |
+
os.Setenv("GOARCH", goarch)
|
| 1502 |
+
os.Setenv("GOOS", goos)
|
| 1503 |
+
|
| 1504 |
+
timelog("build", "go_bootstrap")
|
| 1505 |
+
xprintf("Building Go bootstrap cmd/go (go_bootstrap) using Go toolchain1.\n")
|
| 1506 |
+
install("runtime") // dependency not visible in sources; also sets up textflag.h
|
| 1507 |
+
install("time/tzdata") // no dependency in sources; creates generated file
|
| 1508 |
+
install("cmd/go")
|
| 1509 |
+
if vflag > 0 {
|
| 1510 |
+
xprintf("\n")
|
| 1511 |
+
}
|
| 1512 |
+
|
| 1513 |
+
gogcflags = os.Getenv("GO_GCFLAGS") // we were using $BOOT_GO_GCFLAGS until now
|
| 1514 |
+
setNoOpt()
|
| 1515 |
+
goldflags = os.Getenv("GO_LDFLAGS") // we were using $BOOT_GO_LDFLAGS until now
|
| 1516 |
+
goBootstrap := pathf("%s/go_bootstrap", tooldir)
|
| 1517 |
+
if debug {
|
| 1518 |
+
run("", ShowOutput|CheckExit, pathf("%s/compile", tooldir), "-V=full")
|
| 1519 |
+
copyfile(pathf("%s/compile1", tooldir), pathf("%s/compile", tooldir), writeExec)
|
| 1520 |
+
}
|
| 1521 |
+
|
| 1522 |
+
// To recap, so far we have built the new toolchain
|
| 1523 |
+
// (cmd/asm, cmd/cgo, cmd/compile, cmd/link, cmd/preprofile)
|
| 1524 |
+
// using the Go bootstrap toolchain and go command.
|
| 1525 |
+
// Then we built the new go command (as go_bootstrap)
|
| 1526 |
+
// using the new toolchain and our own build logic (above).
|
| 1527 |
+
//
|
| 1528 |
+
// toolchain1 = mk(new toolchain, go1.17 toolchain, go1.17 cmd/go)
|
| 1529 |
+
// go_bootstrap = mk(new cmd/go, toolchain1, cmd/dist)
|
| 1530 |
+
//
|
| 1531 |
+
// The toolchain1 we built earlier is built from the new sources,
|
| 1532 |
+
// but because it was built using cmd/go it has no build IDs.
|
| 1533 |
+
// The eventually installed toolchain needs build IDs, so we need
|
| 1534 |
+
// to do another round:
|
| 1535 |
+
//
|
| 1536 |
+
// toolchain2 = mk(new toolchain, toolchain1, go_bootstrap)
|
| 1537 |
+
//
|
| 1538 |
+
timelog("build", "toolchain2")
|
| 1539 |
+
if vflag > 0 {
|
| 1540 |
+
xprintf("\n")
|
| 1541 |
+
}
|
| 1542 |
+
xprintf("Building Go toolchain2 using go_bootstrap and Go toolchain1.\n")
|
| 1543 |
+
os.Setenv("CC", compilerEnvLookup("CC", defaultcc, goos, goarch))
|
| 1544 |
+
// Now that cmd/go is in charge of the build process, enable GOEXPERIMENT.
|
| 1545 |
+
os.Setenv("GOEXPERIMENT", goexperiment)
|
| 1546 |
+
// No need to enable PGO for toolchain2.
|
| 1547 |
+
goInstall(toolenv(), goBootstrap, append([]string{"-pgo=off"}, toolchain...)...)
|
| 1548 |
+
if debug {
|
| 1549 |
+
run("", ShowOutput|CheckExit, pathf("%s/compile", tooldir), "-V=full")
|
| 1550 |
+
copyfile(pathf("%s/compile2", tooldir), pathf("%s/compile", tooldir), writeExec)
|
| 1551 |
+
}
|
| 1552 |
+
|
| 1553 |
+
// Toolchain2 should be semantically equivalent to toolchain1,
|
| 1554 |
+
// but it was built using the newly built compiler instead of the Go bootstrap compiler,
|
| 1555 |
+
// so it should at the least run faster. Also, toolchain1 had no build IDs
|
| 1556 |
+
// in the binaries, while toolchain2 does. In non-release builds, the
|
| 1557 |
+
// toolchain's build IDs feed into constructing the build IDs of built targets,
|
| 1558 |
+
// so in non-release builds, everything now looks out-of-date due to
|
| 1559 |
+
// toolchain2 having build IDs - that is, due to the go command seeing
|
| 1560 |
+
// that there are new compilers. In release builds, the toolchain's reported
|
| 1561 |
+
// version is used in place of the build ID, and the go command does not
|
| 1562 |
+
// see that change from toolchain1 to toolchain2, so in release builds,
|
| 1563 |
+
// nothing looks out of date.
|
| 1564 |
+
// To keep the behavior the same in both non-release and release builds,
|
| 1565 |
+
// we force-install everything here.
|
| 1566 |
+
//
|
| 1567 |
+
// toolchain3 = mk(new toolchain, toolchain2, go_bootstrap)
|
| 1568 |
+
//
|
| 1569 |
+
timelog("build", "toolchain3")
|
| 1570 |
+
if vflag > 0 {
|
| 1571 |
+
xprintf("\n")
|
| 1572 |
+
}
|
| 1573 |
+
xprintf("Building Go toolchain3 using go_bootstrap and Go toolchain2.\n")
|
| 1574 |
+
goInstall(toolenv(), goBootstrap, append([]string{"-a"}, toolchain...)...)
|
| 1575 |
+
if debug {
|
| 1576 |
+
run("", ShowOutput|CheckExit, pathf("%s/compile", tooldir), "-V=full")
|
| 1577 |
+
copyfile(pathf("%s/compile3", tooldir), pathf("%s/compile", tooldir), writeExec)
|
| 1578 |
+
}
|
| 1579 |
+
|
| 1580 |
+
// Now that toolchain3 has been built from scratch, its compiler and linker
|
| 1581 |
+
// should have accurate build IDs suitable for caching.
|
| 1582 |
+
// Now prime the build cache with the rest of the standard library for
|
| 1583 |
+
// testing, and so that the user can run 'go install std cmd' to quickly
|
| 1584 |
+
// iterate on local changes without waiting for a full rebuild.
|
| 1585 |
+
if _, err := os.Stat(pathf("%s/VERSION", goroot)); err == nil {
|
| 1586 |
+
// If we have a VERSION file, then we use the Go version
|
| 1587 |
+
// instead of build IDs as a cache key, and there is no guarantee
|
| 1588 |
+
// that code hasn't changed since the last time we ran a build
|
| 1589 |
+
// with this exact VERSION file (especially if someone is working
|
| 1590 |
+
// on a release branch). We must not fall back to the shared build cache
|
| 1591 |
+
// in this case. Leave $GOCACHE alone.
|
| 1592 |
+
} else {
|
| 1593 |
+
os.Setenv("GOCACHE", oldgocache)
|
| 1594 |
+
}
|
| 1595 |
+
|
| 1596 |
+
if goos == oldgoos && goarch == oldgoarch {
|
| 1597 |
+
// Common case - not setting up for cross-compilation.
|
| 1598 |
+
timelog("build", "toolchain")
|
| 1599 |
+
if vflag > 0 {
|
| 1600 |
+
xprintf("\n")
|
| 1601 |
+
}
|
| 1602 |
+
xprintf("Building packages and commands for %s/%s.\n", goos, goarch)
|
| 1603 |
+
} else {
|
| 1604 |
+
// GOOS/GOARCH does not match GOHOSTOS/GOHOSTARCH.
|
| 1605 |
+
// Finish GOHOSTOS/GOHOSTARCH installation and then
|
| 1606 |
+
// run GOOS/GOARCH installation.
|
| 1607 |
+
timelog("build", "host toolchain")
|
| 1608 |
+
if vflag > 0 {
|
| 1609 |
+
xprintf("\n")
|
| 1610 |
+
}
|
| 1611 |
+
xprintf("Building commands for host, %s/%s.\n", goos, goarch)
|
| 1612 |
+
goInstall(toolenv(), goBootstrap, toolsToInstall...)
|
| 1613 |
+
checkNotStale(toolenv(), goBootstrap, toolsToInstall...)
|
| 1614 |
+
checkNotStale(toolenv(), gorootBinGo, toolsToInstall...)
|
| 1615 |
+
|
| 1616 |
+
timelog("build", "target toolchain")
|
| 1617 |
+
if vflag > 0 {
|
| 1618 |
+
xprintf("\n")
|
| 1619 |
+
}
|
| 1620 |
+
goos = oldgoos
|
| 1621 |
+
goarch = oldgoarch
|
| 1622 |
+
os.Setenv("GOOS", goos)
|
| 1623 |
+
os.Setenv("GOARCH", goarch)
|
| 1624 |
+
os.Setenv("CC", compilerEnvLookup("CC", defaultcc, goos, goarch))
|
| 1625 |
+
xprintf("Building packages and commands for target, %s/%s.\n", goos, goarch)
|
| 1626 |
+
}
|
| 1627 |
+
goInstall(nil, goBootstrap, "std")
|
| 1628 |
+
goInstall(toolenv(), goBootstrap, toolsToInstall...)
|
| 1629 |
+
checkNotStale(toolenv(), goBootstrap, toolchain...)
|
| 1630 |
+
checkNotStale(nil, goBootstrap, "std")
|
| 1631 |
+
checkNotStale(toolenv(), goBootstrap, toolsToInstall...)
|
| 1632 |
+
checkNotStale(nil, gorootBinGo, "std")
|
| 1633 |
+
checkNotStale(toolenv(), gorootBinGo, toolsToInstall...)
|
| 1634 |
+
if debug {
|
| 1635 |
+
run("", ShowOutput|CheckExit, pathf("%s/compile", tooldir), "-V=full")
|
| 1636 |
+
checkNotStale(toolenv(), goBootstrap, toolchain...)
|
| 1637 |
+
copyfile(pathf("%s/compile4", tooldir), pathf("%s/compile", tooldir), writeExec)
|
| 1638 |
+
}
|
| 1639 |
+
|
| 1640 |
+
// Check that there are no new files in $GOROOT/bin other than
|
| 1641 |
+
// go and gofmt and $GOOS_$GOARCH (target bin when cross-compiling).
|
| 1642 |
+
binFiles, err := filepath.Glob(pathf("%s/bin/*", goroot))
|
| 1643 |
+
if err != nil {
|
| 1644 |
+
fatalf("glob: %v", err)
|
| 1645 |
+
}
|
| 1646 |
+
|
| 1647 |
+
ok := map[string]bool{}
|
| 1648 |
+
for _, f := range oldBinFiles {
|
| 1649 |
+
ok[f] = true
|
| 1650 |
+
}
|
| 1651 |
+
for _, f := range binFiles {
|
| 1652 |
+
if gohostos == "darwin" && filepath.Base(f) == ".DS_Store" {
|
| 1653 |
+
continue // unfortunate but not unexpected
|
| 1654 |
+
}
|
| 1655 |
+
elem := strings.TrimSuffix(filepath.Base(f), ".exe")
|
| 1656 |
+
if !ok[f] && elem != "go" && elem != "gofmt" && elem != goos+"_"+goarch {
|
| 1657 |
+
fatalf("unexpected new file in $GOROOT/bin: %s", elem)
|
| 1658 |
+
}
|
| 1659 |
+
}
|
| 1660 |
+
|
| 1661 |
+
// Remove go_bootstrap now that we're done.
|
| 1662 |
+
xremove(pathf("%s/go_bootstrap"+exe, tooldir))
|
| 1663 |
+
|
| 1664 |
+
if goos == "android" {
|
| 1665 |
+
// Make sure the exec wrapper will sync a fresh $GOROOT to the device.
|
| 1666 |
+
xremove(pathf("%s/go_android_exec-adb-sync-status", os.TempDir()))
|
| 1667 |
+
}
|
| 1668 |
+
|
| 1669 |
+
if wrapperPath := wrapperPathFor(goos, goarch); wrapperPath != "" {
|
| 1670 |
+
oldcc := os.Getenv("CC")
|
| 1671 |
+
os.Setenv("GOOS", gohostos)
|
| 1672 |
+
os.Setenv("GOARCH", gohostarch)
|
| 1673 |
+
os.Setenv("CC", compilerEnvLookup("CC", defaultcc, gohostos, gohostarch))
|
| 1674 |
+
goCmd(nil, gorootBinGo, "build", "-o", pathf("%s/go_%s_%s_exec%s", gorootBin, goos, goarch, exe), wrapperPath)
|
| 1675 |
+
// Restore environment.
|
| 1676 |
+
// TODO(elias.naur): support environment variables in goCmd?
|
| 1677 |
+
os.Setenv("GOOS", goos)
|
| 1678 |
+
os.Setenv("GOARCH", goarch)
|
| 1679 |
+
os.Setenv("CC", oldcc)
|
| 1680 |
+
}
|
| 1681 |
+
|
| 1682 |
+
if distpack {
|
| 1683 |
+
xprintf("Packaging archives for %s/%s.\n", goos, goarch)
|
| 1684 |
+
run("", ShowOutput|CheckExit, gorootBinGo, "tool", "distpack")
|
| 1685 |
+
}
|
| 1686 |
+
|
| 1687 |
+
// Print trailing banner unless instructed otherwise.
|
| 1688 |
+
if !noBanner {
|
| 1689 |
+
banner()
|
| 1690 |
+
}
|
| 1691 |
+
}
|
| 1692 |
+
|
| 1693 |
+
func wrapperPathFor(goos, goarch string) string {
|
| 1694 |
+
switch {
|
| 1695 |
+
case goos == "android":
|
| 1696 |
+
if gohostos != "android" {
|
| 1697 |
+
return pathf("%s/misc/go_android_exec/main.go", goroot)
|
| 1698 |
+
}
|
| 1699 |
+
case goos == "ios":
|
| 1700 |
+
if gohostos != "ios" {
|
| 1701 |
+
return pathf("%s/misc/ios/go_ios_exec.go", goroot)
|
| 1702 |
+
}
|
| 1703 |
+
}
|
| 1704 |
+
return ""
|
| 1705 |
+
}
|
| 1706 |
+
|
| 1707 |
+
func goInstall(env []string, goBinary string, args ...string) {
|
| 1708 |
+
goCmd(env, goBinary, "install", args...)
|
| 1709 |
+
}
|
| 1710 |
+
|
| 1711 |
+
func appendCompilerFlags(args []string) []string {
|
| 1712 |
+
if gogcflags != "" {
|
| 1713 |
+
args = append(args, "-gcflags=all="+gogcflags)
|
| 1714 |
+
}
|
| 1715 |
+
if goldflags != "" {
|
| 1716 |
+
args = append(args, "-ldflags=all="+goldflags)
|
| 1717 |
+
}
|
| 1718 |
+
return args
|
| 1719 |
+
}
|
| 1720 |
+
|
| 1721 |
+
func goCmd(env []string, goBinary string, cmd string, args ...string) {
|
| 1722 |
+
goCmd := []string{goBinary, cmd}
|
| 1723 |
+
if noOpt {
|
| 1724 |
+
goCmd = append(goCmd, "-tags=noopt")
|
| 1725 |
+
}
|
| 1726 |
+
goCmd = appendCompilerFlags(goCmd)
|
| 1727 |
+
if vflag > 0 {
|
| 1728 |
+
goCmd = append(goCmd, "-v")
|
| 1729 |
+
}
|
| 1730 |
+
|
| 1731 |
+
// Force only one process at a time on vx32 emulation.
|
| 1732 |
+
if gohostos == "plan9" && os.Getenv("sysname") == "vx32" {
|
| 1733 |
+
goCmd = append(goCmd, "-p=1")
|
| 1734 |
+
}
|
| 1735 |
+
|
| 1736 |
+
runEnv(workdir, ShowOutput|CheckExit, env, append(goCmd, args...)...)
|
| 1737 |
+
}
|
| 1738 |
+
|
| 1739 |
+
func checkNotStale(env []string, goBinary string, targets ...string) {
|
| 1740 |
+
goCmd := []string{goBinary, "list"}
|
| 1741 |
+
if noOpt {
|
| 1742 |
+
goCmd = append(goCmd, "-tags=noopt")
|
| 1743 |
+
}
|
| 1744 |
+
goCmd = appendCompilerFlags(goCmd)
|
| 1745 |
+
goCmd = append(goCmd, "-f={{if .Stale}}\tSTALE {{.ImportPath}}: {{.StaleReason}}{{end}}")
|
| 1746 |
+
|
| 1747 |
+
out := runEnv(workdir, CheckExit, env, append(goCmd, targets...)...)
|
| 1748 |
+
if strings.Contains(out, "\tSTALE ") {
|
| 1749 |
+
os.Setenv("GODEBUG", "gocachehash=1")
|
| 1750 |
+
for _, target := range []string{"internal/runtime/sys", "cmd/dist", "cmd/link"} {
|
| 1751 |
+
if strings.Contains(out, "STALE "+target) {
|
| 1752 |
+
run(workdir, ShowOutput|CheckExit, goBinary, "list", "-f={{.ImportPath}} {{.Stale}}", target)
|
| 1753 |
+
break
|
| 1754 |
+
}
|
| 1755 |
+
}
|
| 1756 |
+
fatalf("unexpected stale targets reported by %s list -gcflags=\"%s\" -ldflags=\"%s\" for %v (consider rerunning with GOMAXPROCS=1 GODEBUG=gocachehash=1):\n%s", goBinary, gogcflags, goldflags, targets, out)
|
| 1757 |
+
}
|
| 1758 |
+
}
|
| 1759 |
+
|
| 1760 |
+
// Cannot use go/build directly because cmd/dist for a new release
|
| 1761 |
+
// builds against an old release's go/build, which may be out of sync.
|
| 1762 |
+
// To reduce duplication, we generate the list for go/build from this.
|
| 1763 |
+
//
|
| 1764 |
+
// We list all supported platforms in this list, so that this is the
|
| 1765 |
+
// single point of truth for supported platforms. This list is used
|
| 1766 |
+
// by 'go tool dist list'.
|
| 1767 |
+
var cgoEnabled = map[string]bool{
|
| 1768 |
+
"aix/ppc64": true,
|
| 1769 |
+
"darwin/amd64": true,
|
| 1770 |
+
"darwin/arm64": true,
|
| 1771 |
+
"dragonfly/amd64": true,
|
| 1772 |
+
"freebsd/386": true,
|
| 1773 |
+
"freebsd/amd64": true,
|
| 1774 |
+
"freebsd/arm": true,
|
| 1775 |
+
"freebsd/arm64": true,
|
| 1776 |
+
"freebsd/riscv64": true,
|
| 1777 |
+
"illumos/amd64": true,
|
| 1778 |
+
"linux/386": true,
|
| 1779 |
+
"linux/amd64": true,
|
| 1780 |
+
"linux/arm": true,
|
| 1781 |
+
"linux/arm64": true,
|
| 1782 |
+
"linux/loong64": true,
|
| 1783 |
+
"linux/ppc64": false,
|
| 1784 |
+
"linux/ppc64le": true,
|
| 1785 |
+
"linux/mips": true,
|
| 1786 |
+
"linux/mipsle": true,
|
| 1787 |
+
"linux/mips64": true,
|
| 1788 |
+
"linux/mips64le": true,
|
| 1789 |
+
"linux/riscv64": true,
|
| 1790 |
+
"linux/s390x": true,
|
| 1791 |
+
"linux/sparc64": true,
|
| 1792 |
+
"android/386": true,
|
| 1793 |
+
"android/amd64": true,
|
| 1794 |
+
"android/arm": true,
|
| 1795 |
+
"android/arm64": true,
|
| 1796 |
+
"ios/arm64": true,
|
| 1797 |
+
"ios/amd64": true,
|
| 1798 |
+
"js/wasm": false,
|
| 1799 |
+
"wasip1/wasm": false,
|
| 1800 |
+
"netbsd/386": true,
|
| 1801 |
+
"netbsd/amd64": true,
|
| 1802 |
+
"netbsd/arm": true,
|
| 1803 |
+
"netbsd/arm64": true,
|
| 1804 |
+
"openbsd/386": true,
|
| 1805 |
+
"openbsd/amd64": true,
|
| 1806 |
+
"openbsd/arm": true,
|
| 1807 |
+
"openbsd/arm64": true,
|
| 1808 |
+
"openbsd/mips64": true,
|
| 1809 |
+
"openbsd/ppc64": false,
|
| 1810 |
+
"openbsd/riscv64": true,
|
| 1811 |
+
"plan9/386": false,
|
| 1812 |
+
"plan9/amd64": false,
|
| 1813 |
+
"plan9/arm": false,
|
| 1814 |
+
"solaris/amd64": true,
|
| 1815 |
+
"windows/386": true,
|
| 1816 |
+
"windows/amd64": true,
|
| 1817 |
+
"windows/arm64": true,
|
| 1818 |
+
}
|
| 1819 |
+
|
| 1820 |
+
// List of platforms that are marked as broken ports.
|
| 1821 |
+
// These require -force flag to build, and also
|
| 1822 |
+
// get filtered out of cgoEnabled for 'dist list'.
|
| 1823 |
+
// See go.dev/issue/56679.
|
| 1824 |
+
var broken = map[string]bool{
|
| 1825 |
+
"freebsd/riscv64": true, // Broken: go.dev/issue/76475.
|
| 1826 |
+
"linux/sparc64": true, // An incomplete port. See CL 132155.
|
| 1827 |
+
"openbsd/mips64": true, // Broken: go.dev/issue/58110.
|
| 1828 |
+
}
|
| 1829 |
+
|
| 1830 |
+
// List of platforms which are first class ports. See go.dev/issue/38874.
|
| 1831 |
+
var firstClass = map[string]bool{
|
| 1832 |
+
"darwin/amd64": true,
|
| 1833 |
+
"darwin/arm64": true,
|
| 1834 |
+
"linux/386": true,
|
| 1835 |
+
"linux/amd64": true,
|
| 1836 |
+
"linux/arm": true,
|
| 1837 |
+
"linux/arm64": true,
|
| 1838 |
+
"windows/386": true,
|
| 1839 |
+
"windows/amd64": true,
|
| 1840 |
+
}
|
| 1841 |
+
|
| 1842 |
+
// We only need CC if cgo is forced on, or if the platform requires external linking.
|
| 1843 |
+
// Otherwise the go command will automatically disable it.
|
| 1844 |
+
func needCC() bool {
|
| 1845 |
+
return os.Getenv("CGO_ENABLED") == "1" || mustLinkExternal(gohostos, gohostarch, false)
|
| 1846 |
+
}
|
| 1847 |
+
|
| 1848 |
+
func checkCC() {
|
| 1849 |
+
if !needCC() {
|
| 1850 |
+
return
|
| 1851 |
+
}
|
| 1852 |
+
cc1 := defaultcc[""]
|
| 1853 |
+
if cc1 == "" {
|
| 1854 |
+
cc1 = "gcc"
|
| 1855 |
+
for _, os := range clangos {
|
| 1856 |
+
if gohostos == os {
|
| 1857 |
+
cc1 = "clang"
|
| 1858 |
+
break
|
| 1859 |
+
}
|
| 1860 |
+
}
|
| 1861 |
+
}
|
| 1862 |
+
cc, err := quotedSplit(cc1)
|
| 1863 |
+
if err != nil {
|
| 1864 |
+
fatalf("split CC: %v", err)
|
| 1865 |
+
}
|
| 1866 |
+
var ccHelp = append(cc, "--help")
|
| 1867 |
+
|
| 1868 |
+
if output, err := exec.Command(ccHelp[0], ccHelp[1:]...).CombinedOutput(); err != nil {
|
| 1869 |
+
outputHdr := ""
|
| 1870 |
+
if len(output) > 0 {
|
| 1871 |
+
outputHdr = "\nCommand output:\n\n"
|
| 1872 |
+
}
|
| 1873 |
+
fatalf("cannot invoke C compiler %q: %v\n\n"+
|
| 1874 |
+
"Go needs a system C compiler for use with cgo.\n"+
|
| 1875 |
+
"To set a C compiler, set CC=the-compiler.\n"+
|
| 1876 |
+
"To disable cgo, set CGO_ENABLED=0.\n%s%s", cc, err, outputHdr, output)
|
| 1877 |
+
}
|
| 1878 |
+
}
|
| 1879 |
+
|
| 1880 |
+
func defaulttarg() string {
|
| 1881 |
+
// xgetwd might return a path with symlinks fully resolved, and if
|
| 1882 |
+
// there happens to be symlinks in goroot, then the hasprefix test
|
| 1883 |
+
// will never succeed. Instead, we use xrealwd to get a canonical
|
| 1884 |
+
// goroot/src before the comparison to avoid this problem.
|
| 1885 |
+
pwd := xgetwd()
|
| 1886 |
+
src := pathf("%s/src/", goroot)
|
| 1887 |
+
real_src := xrealwd(src)
|
| 1888 |
+
if !strings.HasPrefix(pwd, real_src) {
|
| 1889 |
+
fatalf("current directory %s is not under %s", pwd, real_src)
|
| 1890 |
+
}
|
| 1891 |
+
pwd = pwd[len(real_src):]
|
| 1892 |
+
// guard against xrealwd returning the directory without the trailing /
|
| 1893 |
+
pwd = strings.TrimPrefix(pwd, "/")
|
| 1894 |
+
|
| 1895 |
+
return pwd
|
| 1896 |
+
}
|
| 1897 |
+
|
| 1898 |
+
// Install installs the list of packages named on the command line.
|
| 1899 |
+
func cmdinstall() {
|
| 1900 |
+
xflagparse(-1)
|
| 1901 |
+
|
| 1902 |
+
if flag.NArg() == 0 {
|
| 1903 |
+
install(defaulttarg())
|
| 1904 |
+
}
|
| 1905 |
+
|
| 1906 |
+
for _, arg := range flag.Args() {
|
| 1907 |
+
install(arg)
|
| 1908 |
+
}
|
| 1909 |
+
}
|
| 1910 |
+
|
| 1911 |
+
// Clean deletes temporary objects.
|
| 1912 |
+
func cmdclean() {
|
| 1913 |
+
xflagparse(0)
|
| 1914 |
+
clean()
|
| 1915 |
+
}
|
| 1916 |
+
|
| 1917 |
+
// Banner prints the 'now you've installed Go' banner.
|
| 1918 |
+
func cmdbanner() {
|
| 1919 |
+
xflagparse(0)
|
| 1920 |
+
banner()
|
| 1921 |
+
}
|
| 1922 |
+
|
| 1923 |
+
func banner() {
|
| 1924 |
+
if vflag > 0 {
|
| 1925 |
+
xprintf("\n")
|
| 1926 |
+
}
|
| 1927 |
+
xprintf("---\n")
|
| 1928 |
+
xprintf("Installed Go for %s/%s in %s\n", goos, goarch, goroot)
|
| 1929 |
+
xprintf("Installed commands in %s\n", gorootBin)
|
| 1930 |
+
|
| 1931 |
+
if gohostos == "plan9" {
|
| 1932 |
+
// Check that GOROOT/bin is bound before /bin.
|
| 1933 |
+
pid := strings.ReplaceAll(readfile("#c/pid"), " ", "")
|
| 1934 |
+
ns := fmt.Sprintf("/proc/%s/ns", pid)
|
| 1935 |
+
if !strings.Contains(readfile(ns), fmt.Sprintf("bind -b %s /bin", gorootBin)) {
|
| 1936 |
+
xprintf("*** You need to bind %s before /bin.\n", gorootBin)
|
| 1937 |
+
}
|
| 1938 |
+
} else {
|
| 1939 |
+
// Check that GOROOT/bin appears in $PATH.
|
| 1940 |
+
pathsep := ":"
|
| 1941 |
+
if gohostos == "windows" {
|
| 1942 |
+
pathsep = ";"
|
| 1943 |
+
}
|
| 1944 |
+
path := os.Getenv("PATH")
|
| 1945 |
+
if p, ok := os.LookupEnv("DIST_UNMODIFIED_PATH"); ok {
|
| 1946 |
+
// Scripts that modify $PATH and then run dist should also provide
|
| 1947 |
+
// dist with an unmodified copy of $PATH via $DIST_UNMODIFIED_PATH.
|
| 1948 |
+
// Use it here when determining if the user still needs to update
|
| 1949 |
+
// their $PATH. See go.dev/issue/42563.
|
| 1950 |
+
path = p
|
| 1951 |
+
}
|
| 1952 |
+
if !strings.Contains(pathsep+path+pathsep, pathsep+gorootBin+pathsep) {
|
| 1953 |
+
xprintf("*** You need to add %s to your PATH.\n", gorootBin)
|
| 1954 |
+
}
|
| 1955 |
+
}
|
| 1956 |
+
}
|
| 1957 |
+
|
| 1958 |
+
// Version prints the Go version.
|
| 1959 |
+
func cmdversion() {
|
| 1960 |
+
xflagparse(0)
|
| 1961 |
+
xprintf("%s\n", findgoversion())
|
| 1962 |
+
}
|
| 1963 |
+
|
| 1964 |
+
// cmdlist lists all supported platforms.
|
| 1965 |
+
func cmdlist() {
|
| 1966 |
+
jsonFlag := flag.Bool("json", false, "produce JSON output")
|
| 1967 |
+
brokenFlag := flag.Bool("broken", false, "include broken ports")
|
| 1968 |
+
xflagparse(0)
|
| 1969 |
+
|
| 1970 |
+
var plats []string
|
| 1971 |
+
for p := range cgoEnabled {
|
| 1972 |
+
if broken[p] && !*brokenFlag {
|
| 1973 |
+
continue
|
| 1974 |
+
}
|
| 1975 |
+
plats = append(plats, p)
|
| 1976 |
+
}
|
| 1977 |
+
sort.Strings(plats)
|
| 1978 |
+
|
| 1979 |
+
if !*jsonFlag {
|
| 1980 |
+
for _, p := range plats {
|
| 1981 |
+
xprintf("%s\n", p)
|
| 1982 |
+
}
|
| 1983 |
+
return
|
| 1984 |
+
}
|
| 1985 |
+
|
| 1986 |
+
type jsonResult struct {
|
| 1987 |
+
GOOS string
|
| 1988 |
+
GOARCH string
|
| 1989 |
+
CgoSupported bool
|
| 1990 |
+
FirstClass bool
|
| 1991 |
+
Broken bool `json:",omitempty"`
|
| 1992 |
+
}
|
| 1993 |
+
var results []jsonResult
|
| 1994 |
+
for _, p := range plats {
|
| 1995 |
+
fields := strings.Split(p, "/")
|
| 1996 |
+
results = append(results, jsonResult{
|
| 1997 |
+
GOOS: fields[0],
|
| 1998 |
+
GOARCH: fields[1],
|
| 1999 |
+
CgoSupported: cgoEnabled[p],
|
| 2000 |
+
FirstClass: firstClass[p],
|
| 2001 |
+
Broken: broken[p],
|
| 2002 |
+
})
|
| 2003 |
+
}
|
| 2004 |
+
out, err := json.MarshalIndent(results, "", "\t")
|
| 2005 |
+
if err != nil {
|
| 2006 |
+
fatalf("json marshal error: %v", err)
|
| 2007 |
+
}
|
| 2008 |
+
if _, err := os.Stdout.Write(out); err != nil {
|
| 2009 |
+
fatalf("write failed: %v", err)
|
| 2010 |
+
}
|
| 2011 |
+
}
|
| 2012 |
+
|
| 2013 |
+
func setNoOpt() {
|
| 2014 |
+
for gcflag := range strings.SplitSeq(gogcflags, " ") {
|
| 2015 |
+
if gcflag == "-N" || gcflag == "-l" {
|
| 2016 |
+
noOpt = true
|
| 2017 |
+
break
|
| 2018 |
+
}
|
| 2019 |
+
}
|
| 2020 |
+
}
|
go/src/cmd/dist/build_test.go
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Copyright 2023 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 |
+
package main
|
| 6 |
+
|
| 7 |
+
import (
|
| 8 |
+
"internal/platform"
|
| 9 |
+
"testing"
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
// TestMustLinkExternal verifies that the mustLinkExternal helper
|
| 13 |
+
// function matches internal/platform.MustLinkExternal.
|
| 14 |
+
func TestMustLinkExternal(t *testing.T) {
|
| 15 |
+
for _, goos := range okgoos {
|
| 16 |
+
for _, goarch := range okgoarch {
|
| 17 |
+
for _, cgoEnabled := range []bool{true, false} {
|
| 18 |
+
got := mustLinkExternal(goos, goarch, cgoEnabled)
|
| 19 |
+
want := platform.MustLinkExternal(goos, goarch, cgoEnabled)
|
| 20 |
+
if got != want {
|
| 21 |
+
t.Errorf("mustLinkExternal(%q, %q, %v) = %v; want %v", goos, goarch, cgoEnabled, got, want)
|
| 22 |
+
}
|
| 23 |
+
}
|
| 24 |
+
}
|
| 25 |
+
}
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
func TestRequiredBootstrapVersion(t *testing.T) {
|
| 29 |
+
testCases := map[string]string{
|
| 30 |
+
"1.22": "1.20",
|
| 31 |
+
"1.23": "1.20",
|
| 32 |
+
"1.24": "1.22",
|
| 33 |
+
"1.25": "1.22",
|
| 34 |
+
"1.26": "1.24",
|
| 35 |
+
"1.27": "1.24",
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
for v, want := range testCases {
|
| 39 |
+
if got := requiredBootstrapVersion(v); got != want {
|
| 40 |
+
t.Errorf("requiredBootstrapVersion(%v): got %v, want %v", v, got, want)
|
| 41 |
+
}
|
| 42 |
+
}
|
| 43 |
+
}
|
go/src/cmd/dist/buildgo.go
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
package main
|
| 6 |
+
|
| 7 |
+
import (
|
| 8 |
+
"fmt"
|
| 9 |
+
"io"
|
| 10 |
+
"path/filepath"
|
| 11 |
+
"sort"
|
| 12 |
+
"strings"
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
/*
|
| 16 |
+
* Helpers for building cmd/go and cmd/cgo.
|
| 17 |
+
*/
|
| 18 |
+
|
| 19 |
+
// generatedHeader is the string that all source files generated by dist start with.
|
| 20 |
+
//
|
| 21 |
+
// DO NOT CHANGE THIS STRING. If this string is changed then during
|
| 22 |
+
//
|
| 23 |
+
// ./make.bash
|
| 24 |
+
// git checkout other-rev
|
| 25 |
+
// ./make.bash
|
| 26 |
+
//
|
| 27 |
+
// the second make.bash will not find the files generated by the first make.bash
|
| 28 |
+
// and will not clean up properly.
|
| 29 |
+
const generatedHeader = "// Code generated by go tool dist; DO NOT EDIT.\n\n"
|
| 30 |
+
|
| 31 |
+
// writeHeader emits the standard "generated by" header for all files generated
|
| 32 |
+
// by dist.
|
| 33 |
+
func writeHeader(w io.Writer) {
|
| 34 |
+
fmt.Fprint(w, generatedHeader)
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
// mkzdefaultcc writes zdefaultcc.go:
|
| 38 |
+
//
|
| 39 |
+
// package main
|
| 40 |
+
// const defaultCC = <defaultcc>
|
| 41 |
+
// const defaultCXX = <defaultcxx>
|
| 42 |
+
// const defaultPkgConfig = <defaultpkgconfig>
|
| 43 |
+
//
|
| 44 |
+
// It is invoked to write cmd/go/internal/cfg/zdefaultcc.go
|
| 45 |
+
// but we also write cmd/cgo/zdefaultcc.go
|
| 46 |
+
func mkzdefaultcc(dir, file string) {
|
| 47 |
+
if strings.Contains(file, filepath.FromSlash("go/internal/cfg")) {
|
| 48 |
+
var buf strings.Builder
|
| 49 |
+
writeHeader(&buf)
|
| 50 |
+
fmt.Fprintf(&buf, "package cfg\n")
|
| 51 |
+
fmt.Fprintln(&buf)
|
| 52 |
+
fmt.Fprintf(&buf, "const DefaultPkgConfig = `%s`\n", defaultpkgconfig)
|
| 53 |
+
buf.WriteString(defaultCCFunc("DefaultCC", defaultcc))
|
| 54 |
+
buf.WriteString(defaultCCFunc("DefaultCXX", defaultcxx))
|
| 55 |
+
writefile(buf.String(), file, writeSkipSame)
|
| 56 |
+
return
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
var buf strings.Builder
|
| 60 |
+
writeHeader(&buf)
|
| 61 |
+
fmt.Fprintf(&buf, "package main\n")
|
| 62 |
+
fmt.Fprintln(&buf)
|
| 63 |
+
fmt.Fprintf(&buf, "const defaultPkgConfig = `%s`\n", defaultpkgconfig)
|
| 64 |
+
buf.WriteString(defaultCCFunc("defaultCC", defaultcc))
|
| 65 |
+
buf.WriteString(defaultCCFunc("defaultCXX", defaultcxx))
|
| 66 |
+
writefile(buf.String(), file, writeSkipSame)
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
func defaultCCFunc(name string, defaultcc map[string]string) string {
|
| 70 |
+
var buf strings.Builder
|
| 71 |
+
|
| 72 |
+
fmt.Fprintf(&buf, "func %s(goos, goarch string) string {\n", name)
|
| 73 |
+
fmt.Fprintf(&buf, "\tswitch goos+`/`+goarch {\n")
|
| 74 |
+
var keys []string
|
| 75 |
+
for k := range defaultcc {
|
| 76 |
+
if k != "" {
|
| 77 |
+
keys = append(keys, k)
|
| 78 |
+
}
|
| 79 |
+
}
|
| 80 |
+
sort.Strings(keys)
|
| 81 |
+
for _, k := range keys {
|
| 82 |
+
fmt.Fprintf(&buf, "\tcase %s:\n\t\treturn %s\n", quote(k), quote(defaultcc[k]))
|
| 83 |
+
}
|
| 84 |
+
fmt.Fprintf(&buf, "\t}\n")
|
| 85 |
+
if cc := defaultcc[""]; cc != "" {
|
| 86 |
+
fmt.Fprintf(&buf, "\treturn %s\n", quote(cc))
|
| 87 |
+
} else {
|
| 88 |
+
clang, gcc := "clang", "gcc"
|
| 89 |
+
if strings.HasSuffix(name, "CXX") {
|
| 90 |
+
clang, gcc = "clang++", "g++"
|
| 91 |
+
}
|
| 92 |
+
fmt.Fprintf(&buf, "\tswitch goos {\n")
|
| 93 |
+
fmt.Fprintf(&buf, "\tcase ")
|
| 94 |
+
for i, os := range clangos {
|
| 95 |
+
if i > 0 {
|
| 96 |
+
fmt.Fprintf(&buf, ", ")
|
| 97 |
+
}
|
| 98 |
+
fmt.Fprintf(&buf, "%s", quote(os))
|
| 99 |
+
}
|
| 100 |
+
fmt.Fprintf(&buf, ":\n")
|
| 101 |
+
fmt.Fprintf(&buf, "\t\treturn %s\n", quote(clang))
|
| 102 |
+
fmt.Fprintf(&buf, "\t}\n")
|
| 103 |
+
fmt.Fprintf(&buf, "\treturn %s\n", quote(gcc))
|
| 104 |
+
}
|
| 105 |
+
fmt.Fprintf(&buf, "}\n")
|
| 106 |
+
|
| 107 |
+
return buf.String()
|
| 108 |
+
}
|
| 109 |
+
|
| 110 |
+
// mktzdata src/time/tzdata/zzipdata.go:
|
| 111 |
+
//
|
| 112 |
+
// package tzdata
|
| 113 |
+
// const zipdata = "PK..."
|
| 114 |
+
func mktzdata(dir, file string) {
|
| 115 |
+
zip := readfile(filepath.Join(dir, "../../../lib/time/zoneinfo.zip"))
|
| 116 |
+
|
| 117 |
+
var buf strings.Builder
|
| 118 |
+
writeHeader(&buf)
|
| 119 |
+
fmt.Fprintf(&buf, "package tzdata\n")
|
| 120 |
+
fmt.Fprintln(&buf)
|
| 121 |
+
fmt.Fprintf(&buf, "const zipdata = %s\n", quote(zip))
|
| 122 |
+
|
| 123 |
+
writefile(buf.String(), file, writeSkipSame)
|
| 124 |
+
}
|
| 125 |
+
|
| 126 |
+
// quote is like strconv.Quote but simpler and has output
|
| 127 |
+
// that does not depend on the exact Go bootstrap version.
|
| 128 |
+
func quote(s string) string {
|
| 129 |
+
const hex = "0123456789abcdef"
|
| 130 |
+
var out strings.Builder
|
| 131 |
+
out.WriteByte('"')
|
| 132 |
+
for i := 0; i < len(s); i++ {
|
| 133 |
+
c := s[i]
|
| 134 |
+
if 0x20 <= c && c <= 0x7E && c != '"' && c != '\\' {
|
| 135 |
+
out.WriteByte(c)
|
| 136 |
+
} else {
|
| 137 |
+
out.WriteByte('\\')
|
| 138 |
+
out.WriteByte('x')
|
| 139 |
+
out.WriteByte(hex[c>>4])
|
| 140 |
+
out.WriteByte(hex[c&0xf])
|
| 141 |
+
}
|
| 142 |
+
}
|
| 143 |
+
out.WriteByte('"')
|
| 144 |
+
return out.String()
|
| 145 |
+
}
|
go/src/cmd/dist/buildruntime.go
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
package main
|
| 6 |
+
|
| 7 |
+
import (
|
| 8 |
+
"fmt"
|
| 9 |
+
"os"
|
| 10 |
+
"strings"
|
| 11 |
+
)
|
| 12 |
+
|
| 13 |
+
/*
|
| 14 |
+
* Helpers for building runtime.
|
| 15 |
+
*/
|
| 16 |
+
|
| 17 |
+
// mkzversion writes zversion.go:
|
| 18 |
+
//
|
| 19 |
+
// package sys
|
| 20 |
+
//
|
| 21 |
+
// (Nothing right now!)
|
| 22 |
+
func mkzversion(dir, file string) {
|
| 23 |
+
var buf strings.Builder
|
| 24 |
+
writeHeader(&buf)
|
| 25 |
+
fmt.Fprintf(&buf, "package sys\n")
|
| 26 |
+
writefile(buf.String(), file, writeSkipSame)
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
// mkbuildcfg writes internal/buildcfg/zbootstrap.go:
|
| 30 |
+
//
|
| 31 |
+
// package buildcfg
|
| 32 |
+
//
|
| 33 |
+
// const defaultGOROOT = <goroot>
|
| 34 |
+
// const defaultGO386 = <go386>
|
| 35 |
+
// ...
|
| 36 |
+
// const defaultGOOS = runtime.GOOS
|
| 37 |
+
// const defaultGOARCH = runtime.GOARCH
|
| 38 |
+
//
|
| 39 |
+
// The use of runtime.GOOS and runtime.GOARCH makes sure that
|
| 40 |
+
// a cross-compiled compiler expects to compile for its own target
|
| 41 |
+
// system. That is, if on a Mac you do:
|
| 42 |
+
//
|
| 43 |
+
// GOOS=linux GOARCH=ppc64 go build cmd/compile
|
| 44 |
+
//
|
| 45 |
+
// the resulting compiler will default to generating linux/ppc64 object files.
|
| 46 |
+
// This is more useful than having it default to generating objects for the
|
| 47 |
+
// original target (in this example, a Mac).
|
| 48 |
+
func mkbuildcfg(file string) {
|
| 49 |
+
var buf strings.Builder
|
| 50 |
+
writeHeader(&buf)
|
| 51 |
+
fmt.Fprintf(&buf, "package buildcfg\n")
|
| 52 |
+
fmt.Fprintln(&buf)
|
| 53 |
+
fmt.Fprintf(&buf, "import \"runtime\"\n")
|
| 54 |
+
fmt.Fprintln(&buf)
|
| 55 |
+
fmt.Fprintf(&buf, "const DefaultGO386 = `%s`\n", go386)
|
| 56 |
+
fmt.Fprintf(&buf, "const DefaultGOAMD64 = `%s`\n", goamd64)
|
| 57 |
+
fmt.Fprintf(&buf, "const DefaultGOARM = `%s`\n", goarm)
|
| 58 |
+
fmt.Fprintf(&buf, "const DefaultGOARM64 = `%s`\n", goarm64)
|
| 59 |
+
fmt.Fprintf(&buf, "const DefaultGOMIPS = `%s`\n", gomips)
|
| 60 |
+
fmt.Fprintf(&buf, "const DefaultGOMIPS64 = `%s`\n", gomips64)
|
| 61 |
+
fmt.Fprintf(&buf, "const DefaultGOPPC64 = `%s`\n", goppc64)
|
| 62 |
+
fmt.Fprintf(&buf, "const DefaultGORISCV64 = `%s`\n", goriscv64)
|
| 63 |
+
fmt.Fprintf(&buf, "const defaultGOEXPERIMENT = `%s`\n", goexperiment)
|
| 64 |
+
fmt.Fprintf(&buf, "const defaultGO_EXTLINK_ENABLED = `%s`\n", goextlinkenabled)
|
| 65 |
+
fmt.Fprintf(&buf, "const defaultGO_LDSO = `%s`\n", defaultldso)
|
| 66 |
+
fmt.Fprintf(&buf, "const version = `%s`\n", findgoversion())
|
| 67 |
+
fmt.Fprintf(&buf, "const defaultGOOS = runtime.GOOS\n")
|
| 68 |
+
fmt.Fprintf(&buf, "const defaultGOARCH = runtime.GOARCH\n")
|
| 69 |
+
fmt.Fprintf(&buf, "const DefaultGOFIPS140 = `%s`\n", gofips140)
|
| 70 |
+
fmt.Fprintf(&buf, "const DefaultCGO_ENABLED = %s\n", quote(os.Getenv("CGO_ENABLED")))
|
| 71 |
+
|
| 72 |
+
writefile(buf.String(), file, writeSkipSame)
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
// mkobjabi writes cmd/internal/objabi/zbootstrap.go:
|
| 76 |
+
//
|
| 77 |
+
// package objabi
|
| 78 |
+
//
|
| 79 |
+
// (Nothing right now!)
|
| 80 |
+
func mkobjabi(file string) {
|
| 81 |
+
var buf strings.Builder
|
| 82 |
+
writeHeader(&buf)
|
| 83 |
+
fmt.Fprintf(&buf, "package objabi\n")
|
| 84 |
+
|
| 85 |
+
writefile(buf.String(), file, writeSkipSame)
|
| 86 |
+
}
|
go/src/cmd/dist/buildtag.go
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Copyright 2021 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 |
+
package main
|
| 6 |
+
|
| 7 |
+
import (
|
| 8 |
+
"fmt"
|
| 9 |
+
"strings"
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
// exprParser is a //go:build expression parser and evaluator.
|
| 13 |
+
// The parser is a trivial precedence-based parser which is still
|
| 14 |
+
// almost overkill for these very simple expressions.
|
| 15 |
+
type exprParser struct {
|
| 16 |
+
x string
|
| 17 |
+
t exprToken // upcoming token
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
// val is the value type result of parsing.
|
| 21 |
+
// We don't keep a parse tree, just the value of the expression.
|
| 22 |
+
type val bool
|
| 23 |
+
|
| 24 |
+
// exprToken describes a single token in the input.
|
| 25 |
+
// Prefix operators define a prefix func that parses the
|
| 26 |
+
// upcoming value. Binary operators define an infix func
|
| 27 |
+
// that combines two values according to the operator.
|
| 28 |
+
// In that case, the parsing loop parses the two values.
|
| 29 |
+
type exprToken struct {
|
| 30 |
+
tok string
|
| 31 |
+
prec int
|
| 32 |
+
prefix func(*exprParser) val
|
| 33 |
+
infix func(val, val) val
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
var exprTokens []exprToken
|
| 37 |
+
|
| 38 |
+
func init() { // init to break init cycle
|
| 39 |
+
exprTokens = []exprToken{
|
| 40 |
+
{tok: "&&", prec: 1, infix: func(x, y val) val { return x && y }},
|
| 41 |
+
{tok: "||", prec: 2, infix: func(x, y val) val { return x || y }},
|
| 42 |
+
{tok: "!", prec: 3, prefix: (*exprParser).not},
|
| 43 |
+
{tok: "(", prec: 3, prefix: (*exprParser).paren},
|
| 44 |
+
{tok: ")"},
|
| 45 |
+
}
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
// matchexpr parses and evaluates the //go:build expression x.
|
| 49 |
+
func matchexpr(x string) (matched bool, err error) {
|
| 50 |
+
defer func() {
|
| 51 |
+
if e := recover(); e != nil {
|
| 52 |
+
matched = false
|
| 53 |
+
err = fmt.Errorf("parsing //go:build line: %v", e)
|
| 54 |
+
}
|
| 55 |
+
}()
|
| 56 |
+
|
| 57 |
+
p := &exprParser{x: x}
|
| 58 |
+
p.next()
|
| 59 |
+
v := p.parse(0)
|
| 60 |
+
if p.t.tok != "end of expression" {
|
| 61 |
+
panic("unexpected " + p.t.tok)
|
| 62 |
+
}
|
| 63 |
+
return bool(v), nil
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
// parse parses an expression, including binary operators at precedence >= prec.
|
| 67 |
+
func (p *exprParser) parse(prec int) val {
|
| 68 |
+
if p.t.prefix == nil {
|
| 69 |
+
panic("unexpected " + p.t.tok)
|
| 70 |
+
}
|
| 71 |
+
v := p.t.prefix(p)
|
| 72 |
+
for p.t.prec >= prec && p.t.infix != nil {
|
| 73 |
+
t := p.t
|
| 74 |
+
p.next()
|
| 75 |
+
v = t.infix(v, p.parse(t.prec+1))
|
| 76 |
+
}
|
| 77 |
+
return v
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
// not is the prefix parser for a ! token.
|
| 81 |
+
func (p *exprParser) not() val {
|
| 82 |
+
p.next()
|
| 83 |
+
return !p.parse(100)
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
// paren is the prefix parser for a ( token.
|
| 87 |
+
func (p *exprParser) paren() val {
|
| 88 |
+
p.next()
|
| 89 |
+
v := p.parse(0)
|
| 90 |
+
if p.t.tok != ")" {
|
| 91 |
+
panic("missing )")
|
| 92 |
+
}
|
| 93 |
+
p.next()
|
| 94 |
+
return v
|
| 95 |
+
}
|
| 96 |
+
|
| 97 |
+
// next advances the parser to the next token,
|
| 98 |
+
// leaving the token in p.t.
|
| 99 |
+
func (p *exprParser) next() {
|
| 100 |
+
p.x = strings.TrimSpace(p.x)
|
| 101 |
+
if p.x == "" {
|
| 102 |
+
p.t = exprToken{tok: "end of expression"}
|
| 103 |
+
return
|
| 104 |
+
}
|
| 105 |
+
for _, t := range exprTokens {
|
| 106 |
+
if strings.HasPrefix(p.x, t.tok) {
|
| 107 |
+
p.x = p.x[len(t.tok):]
|
| 108 |
+
p.t = t
|
| 109 |
+
return
|
| 110 |
+
}
|
| 111 |
+
}
|
| 112 |
+
|
| 113 |
+
i := 0
|
| 114 |
+
for i < len(p.x) && validtag(p.x[i]) {
|
| 115 |
+
i++
|
| 116 |
+
}
|
| 117 |
+
if i == 0 {
|
| 118 |
+
panic(fmt.Sprintf("syntax error near %#q", rune(p.x[i])))
|
| 119 |
+
}
|
| 120 |
+
tag := p.x[:i]
|
| 121 |
+
p.x = p.x[i:]
|
| 122 |
+
p.t = exprToken{
|
| 123 |
+
tok: "tag",
|
| 124 |
+
prefix: func(p *exprParser) val {
|
| 125 |
+
p.next()
|
| 126 |
+
return val(matchtag(tag))
|
| 127 |
+
},
|
| 128 |
+
}
|
| 129 |
+
}
|
| 130 |
+
|
| 131 |
+
func validtag(c byte) bool {
|
| 132 |
+
return 'A' <= c && c <= 'Z' || 'a' <= c && c <= 'z' || '0' <= c && c <= '9' || c == '.' || c == '_'
|
| 133 |
+
}
|
go/src/cmd/dist/buildtag_test.go
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Copyright 2021 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 |
+
package main
|
| 6 |
+
|
| 7 |
+
import (
|
| 8 |
+
"fmt"
|
| 9 |
+
"reflect"
|
| 10 |
+
"testing"
|
| 11 |
+
)
|
| 12 |
+
|
| 13 |
+
var buildParserTests = []struct {
|
| 14 |
+
x string
|
| 15 |
+
matched bool
|
| 16 |
+
err error
|
| 17 |
+
}{
|
| 18 |
+
{"gc", true, nil},
|
| 19 |
+
{"gccgo", false, nil},
|
| 20 |
+
{"!gc", false, nil},
|
| 21 |
+
{"gc && gccgo", false, nil},
|
| 22 |
+
{"gc || gccgo", true, nil},
|
| 23 |
+
{"gc || (gccgo && !gccgo)", true, nil},
|
| 24 |
+
{"gc && (gccgo || !gccgo)", true, nil},
|
| 25 |
+
{"!(gc && (gccgo || !gccgo))", false, nil},
|
| 26 |
+
{"gccgo || gc", true, nil},
|
| 27 |
+
{"!(!(!(gccgo || gc)))", false, nil},
|
| 28 |
+
{"compiler_bootstrap", false, nil},
|
| 29 |
+
{"cmd_go_bootstrap", true, nil},
|
| 30 |
+
{"syntax(error", false, fmt.Errorf("parsing //go:build line: unexpected (")},
|
| 31 |
+
{"(gc", false, fmt.Errorf("parsing //go:build line: missing )")},
|
| 32 |
+
{"gc gc", false, fmt.Errorf("parsing //go:build line: unexpected tag")},
|
| 33 |
+
{"(gc))", false, fmt.Errorf("parsing //go:build line: unexpected )")},
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
func TestBuildParser(t *testing.T) {
|
| 37 |
+
for _, tt := range buildParserTests {
|
| 38 |
+
matched, err := matchexpr(tt.x)
|
| 39 |
+
if matched != tt.matched || !reflect.DeepEqual(err, tt.err) {
|
| 40 |
+
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Copyright 2015 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 |
+
// Build toolchain using Go bootstrap version.
|
| 6 |
+
//
|
| 7 |
+
// The general strategy is to copy the source files we need into
|
| 8 |
+
// a new GOPATH workspace, adjust import paths appropriately,
|
| 9 |
+
// invoke the Go bootstrap toolchains go command to build those sources,
|
| 10 |
+
// and then copy the binaries back.
|
| 11 |
+
|
| 12 |
+
package main
|
| 13 |
+
|
| 14 |
+
import (
|
| 15 |
+
"fmt"
|
| 16 |
+
"go/version"
|
| 17 |
+
"os"
|
| 18 |
+
"path/filepath"
|
| 19 |
+
"regexp"
|
| 20 |
+
"strings"
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
// bootstrapDirs is a list of directories holding code that must be
|
| 24 |
+
// compiled with the Go bootstrap toolchain to produce the bootstrapTargets.
|
| 25 |
+
// All directories in this list are relative to and must be below $GOROOT/src.
|
| 26 |
+
//
|
| 27 |
+
// The list has two kinds of entries: names beginning with cmd/ with
|
| 28 |
+
// no other slashes, which are commands, and other paths, which are packages
|
| 29 |
+
// supporting the commands. Packages in the standard library can be listed
|
| 30 |
+
// if a newer copy needs to be substituted for the Go bootstrap copy when used
|
| 31 |
+
// by the command packages. Paths ending with /... automatically
|
| 32 |
+
// include all packages within subdirectories as well.
|
| 33 |
+
// These will be imported during bootstrap as bootstrap/name, like bootstrap/math/big.
|
| 34 |
+
var bootstrapDirs = []string{
|
| 35 |
+
"cmp",
|
| 36 |
+
"cmd/asm",
|
| 37 |
+
"cmd/asm/internal/...",
|
| 38 |
+
"cmd/cgo",
|
| 39 |
+
"cmd/compile",
|
| 40 |
+
"cmd/compile/internal/...",
|
| 41 |
+
"cmd/internal/archive",
|
| 42 |
+
"cmd/internal/bio",
|
| 43 |
+
"cmd/internal/codesign",
|
| 44 |
+
"cmd/internal/dwarf",
|
| 45 |
+
"cmd/internal/edit",
|
| 46 |
+
"cmd/internal/gcprog",
|
| 47 |
+
"cmd/internal/goobj",
|
| 48 |
+
"cmd/internal/hash",
|
| 49 |
+
"cmd/internal/macho",
|
| 50 |
+
"cmd/internal/obj/...",
|
| 51 |
+
"cmd/internal/objabi",
|
| 52 |
+
"cmd/internal/par",
|
| 53 |
+
"cmd/internal/pgo",
|
| 54 |
+
"cmd/internal/pkgpath",
|
| 55 |
+
"cmd/internal/quoted",
|
| 56 |
+
"cmd/internal/src",
|
| 57 |
+
"cmd/internal/sys",
|
| 58 |
+
"cmd/internal/telemetry",
|
| 59 |
+
"cmd/internal/telemetry/counter",
|
| 60 |
+
"cmd/link",
|
| 61 |
+
"cmd/link/internal/...",
|
| 62 |
+
"compress/flate",
|
| 63 |
+
"compress/zlib",
|
| 64 |
+
"container/heap",
|
| 65 |
+
"debug/dwarf",
|
| 66 |
+
"debug/elf",
|
| 67 |
+
"debug/macho",
|
| 68 |
+
"debug/pe",
|
| 69 |
+
"go/build/constraint",
|
| 70 |
+
"go/constant",
|
| 71 |
+
"go/version",
|
| 72 |
+
"internal/abi",
|
| 73 |
+
"internal/coverage",
|
| 74 |
+
"cmd/internal/cov/covcmd",
|
| 75 |
+
"internal/bisect",
|
| 76 |
+
"internal/buildcfg",
|
| 77 |
+
"internal/exportdata",
|
| 78 |
+
"internal/goarch",
|
| 79 |
+
"internal/godebugs",
|
| 80 |
+
"internal/goexperiment",
|
| 81 |
+
"internal/goroot",
|
| 82 |
+
"internal/gover",
|
| 83 |
+
"internal/goversion",
|
| 84 |
+
// internal/lazyregexp is provided by Go 1.17, which permits it to
|
| 85 |
+
// be imported by other packages in this list, but is not provided
|
| 86 |
+
// by the Go 1.17 version of gccgo. It's on this list only to
|
| 87 |
+
// support gccgo, and can be removed if we require gccgo 14 or later.
|
| 88 |
+
"internal/lazyregexp",
|
| 89 |
+
"internal/pkgbits",
|
| 90 |
+
"internal/platform",
|
| 91 |
+
"internal/profile",
|
| 92 |
+
"internal/race",
|
| 93 |
+
"internal/runtime/gc",
|
| 94 |
+
"internal/saferio",
|
| 95 |
+
"internal/strconv",
|
| 96 |
+
"internal/syscall/unix",
|
| 97 |
+
"internal/types/errors",
|
| 98 |
+
"internal/unsafeheader",
|
| 99 |
+
"internal/xcoff",
|
| 100 |
+
"internal/zstd",
|
| 101 |
+
"math/bits",
|
| 102 |
+
"sort",
|
| 103 |
+
}
|
| 104 |
+
|
| 105 |
+
// File prefixes that are ignored by go/build anyway, and cause
|
| 106 |
+
// problems with editor generated temporary files (#18931).
|
| 107 |
+
var ignorePrefixes = []string{
|
| 108 |
+
".",
|
| 109 |
+
"_",
|
| 110 |
+
"#",
|
| 111 |
+
}
|
| 112 |
+
|
| 113 |
+
// File suffixes that use build tags introduced since Go 1.17.
|
| 114 |
+
// These must not be copied into the bootstrap build directory.
|
| 115 |
+
// Also ignore test files.
|
| 116 |
+
var ignoreSuffixes = []string{
|
| 117 |
+
"_test.s",
|
| 118 |
+
"_test.go",
|
| 119 |
+
// Skip PGO profile. No need to build toolchain1 compiler
|
| 120 |
+
// with PGO. And as it is not a text file the import path
|
| 121 |
+
// rewrite will break it.
|
| 122 |
+
".pgo",
|
| 123 |
+
// Skip editor backup files.
|
| 124 |
+
"~",
|
| 125 |
+
}
|
| 126 |
+
|
| 127 |
+
const minBootstrap = "go1.24.6"
|
| 128 |
+
|
| 129 |
+
var tryDirs = []string{
|
| 130 |
+
"sdk/" + minBootstrap,
|
| 131 |
+
minBootstrap,
|
| 132 |
+
}
|
| 133 |
+
|
| 134 |
+
func bootstrapBuildTools() {
|
| 135 |
+
goroot_bootstrap := os.Getenv("GOROOT_BOOTSTRAP")
|
| 136 |
+
if goroot_bootstrap == "" {
|
| 137 |
+
home := os.Getenv("HOME")
|
| 138 |
+
goroot_bootstrap = pathf("%s/go1.4", home)
|
| 139 |
+
for _, d := range tryDirs {
|
| 140 |
+
if p := pathf("%s/%s", home, d); isdir(p) {
|
| 141 |
+
goroot_bootstrap = p
|
| 142 |
+
}
|
| 143 |
+
}
|
| 144 |
+
}
|
| 145 |
+
|
| 146 |
+
// check bootstrap version.
|
| 147 |
+
ver := run(pathf("%s/bin", goroot_bootstrap), CheckExit, pathf("%s/bin/go", goroot_bootstrap), "env", "GOVERSION")
|
| 148 |
+
// go env GOVERSION output like "go1.22.6\n" or "devel go1.24-ffb3e574 Thu Aug 29 20:16:26 2024 +0000\n".
|
| 149 |
+
ver = ver[:len(ver)-1]
|
| 150 |
+
if version.Compare(ver, version.Lang(minBootstrap)) > 0 && version.Compare(ver, minBootstrap) < 0 {
|
| 151 |
+
fatalf("%s does not meet the minimum bootstrap requirement of %s or later", ver, minBootstrap)
|
| 152 |
+
}
|
| 153 |
+
|
| 154 |
+
xprintf("Building Go toolchain1 using %s.\n", goroot_bootstrap)
|
| 155 |
+
|
| 156 |
+
mkbuildcfg(pathf("%s/src/internal/buildcfg/zbootstrap.go", goroot))
|
| 157 |
+
mkobjabi(pathf("%s/src/cmd/internal/objabi/zbootstrap.go", goroot))
|
| 158 |
+
|
| 159 |
+
// Use $GOROOT/pkg/bootstrap as the bootstrap workspace root.
|
| 160 |
+
// We use a subdirectory of $GOROOT/pkg because that's the
|
| 161 |
+
// space within $GOROOT where we store all generated objects.
|
| 162 |
+
// We could use a temporary directory outside $GOROOT instead,
|
| 163 |
+
// but it is easier to debug on failure if the files are in a known location.
|
| 164 |
+
workspace := pathf("%s/pkg/bootstrap", goroot)
|
| 165 |
+
xremoveall(workspace)
|
| 166 |
+
xatexit(func() { xremoveall(workspace) })
|
| 167 |
+
base := pathf("%s/src/bootstrap", workspace)
|
| 168 |
+
xmkdirall(base)
|
| 169 |
+
|
| 170 |
+
// Copy source code into $GOROOT/pkg/bootstrap and rewrite import paths.
|
| 171 |
+
minBootstrapVers := requiredBootstrapVersion(goModVersion()) // require the minimum required go version to build this go version in the go.mod file
|
| 172 |
+
writefile("module bootstrap\ngo "+minBootstrapVers+"\n", pathf("%s/%s", base, "go.mod"), 0)
|
| 173 |
+
for _, dir := range bootstrapDirs {
|
| 174 |
+
recurse := strings.HasSuffix(dir, "/...")
|
| 175 |
+
dir = strings.TrimSuffix(dir, "/...")
|
| 176 |
+
filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
|
| 177 |
+
if err != nil {
|
| 178 |
+
fatalf("walking bootstrap dirs failed: %v: %v", path, err)
|
| 179 |
+
}
|
| 180 |
+
|
| 181 |
+
name := filepath.Base(path)
|
| 182 |
+
src := pathf("%s/src/%s", goroot, path)
|
| 183 |
+
dst := pathf("%s/%s", base, path)
|
| 184 |
+
|
| 185 |
+
if info.IsDir() {
|
| 186 |
+
if !recurse && path != dir || name == "testdata" {
|
| 187 |
+
return filepath.SkipDir
|
| 188 |
+
}
|
| 189 |
+
|
| 190 |
+
xmkdirall(dst)
|
| 191 |
+
if path == "cmd/cgo" {
|
| 192 |
+
// Write to src because we need the file both for bootstrap
|
| 193 |
+
// and for later in the main build.
|
| 194 |
+
mkzdefaultcc("", pathf("%s/zdefaultcc.go", src))
|
| 195 |
+
mkzdefaultcc("", pathf("%s/zdefaultcc.go", dst))
|
| 196 |
+
}
|
| 197 |
+
return nil
|
| 198 |
+
}
|
| 199 |
+
|
| 200 |
+
for _, pre := range ignorePrefixes {
|
| 201 |
+
if strings.HasPrefix(name, pre) {
|
| 202 |
+
return nil
|
| 203 |
+
}
|
| 204 |
+
}
|
| 205 |
+
for _, suf := range ignoreSuffixes {
|
| 206 |
+
if strings.HasSuffix(name, suf) {
|
| 207 |
+
return nil
|
| 208 |
+
}
|
| 209 |
+
}
|
| 210 |
+
|
| 211 |
+
text := bootstrapRewriteFile(src)
|
| 212 |
+
writefile(text, dst, 0)
|
| 213 |
+
return nil
|
| 214 |
+
})
|
| 215 |
+
}
|
| 216 |
+
|
| 217 |
+
// Set up environment for invoking Go bootstrap toolchains go command.
|
| 218 |
+
// GOROOT points at Go bootstrap GOROOT,
|
| 219 |
+
// GOPATH points at our bootstrap workspace,
|
| 220 |
+
// GOBIN is empty, so that binaries are installed to GOPATH/bin,
|
| 221 |
+
// and GOOS, GOHOSTOS, GOARCH, and GOHOSTOS are empty,
|
| 222 |
+
// so that Go bootstrap toolchain builds whatever kind of binary it knows how to build.
|
| 223 |
+
// Restore GOROOT, GOPATH, and GOBIN when done.
|
| 224 |
+
// Don't bother with GOOS, GOHOSTOS, GOARCH, and GOHOSTARCH,
|
| 225 |
+
// because setup will take care of those when bootstrapBuildTools returns.
|
| 226 |
+
|
| 227 |
+
defer os.Setenv("GOROOT", os.Getenv("GOROOT"))
|
| 228 |
+
os.Setenv("GOROOT", goroot_bootstrap)
|
| 229 |
+
|
| 230 |
+
defer os.Setenv("GOPATH", os.Getenv("GOPATH"))
|
| 231 |
+
os.Setenv("GOPATH", workspace)
|
| 232 |
+
|
| 233 |
+
defer os.Setenv("GOBIN", os.Getenv("GOBIN"))
|
| 234 |
+
os.Setenv("GOBIN", "")
|
| 235 |
+
|
| 236 |
+
os.Setenv("GOOS", "")
|
| 237 |
+
os.Setenv("GOHOSTOS", "")
|
| 238 |
+
os.Setenv("GOARCH", "")
|
| 239 |
+
os.Setenv("GOHOSTARCH", "")
|
| 240 |
+
|
| 241 |
+
// Run Go bootstrap to build binaries.
|
| 242 |
+
// Use the math_big_pure_go build tag to disable the assembly in math/big
|
| 243 |
+
// which may contain unsupported instructions.
|
| 244 |
+
// Use the purego build tag to disable other assembly code.
|
| 245 |
+
cmd := []string{
|
| 246 |
+
pathf("%s/bin/go", goroot_bootstrap),
|
| 247 |
+
"install",
|
| 248 |
+
"-tags=math_big_pure_go compiler_bootstrap purego",
|
| 249 |
+
}
|
| 250 |
+
if vflag > 0 {
|
| 251 |
+
cmd = append(cmd, "-v")
|
| 252 |
+
}
|
| 253 |
+
if tool := os.Getenv("GOBOOTSTRAP_TOOLEXEC"); tool != "" {
|
| 254 |
+
cmd = append(cmd, "-toolexec="+tool)
|
| 255 |
+
}
|
| 256 |
+
cmd = append(cmd, "bootstrap/cmd/...")
|
| 257 |
+
run(base, ShowOutput|CheckExit, cmd...)
|
| 258 |
+
|
| 259 |
+
// Copy binaries into tool binary directory.
|
| 260 |
+
for _, name := range bootstrapDirs {
|
| 261 |
+
if !strings.HasPrefix(name, "cmd/") {
|
| 262 |
+
continue
|
| 263 |
+
}
|
| 264 |
+
name = name[len("cmd/"):]
|
| 265 |
+
if !strings.Contains(name, "/") {
|
| 266 |
+
copyfile(pathf("%s/%s%s", tooldir, name, exe), pathf("%s/bin/%s%s", workspace, name, exe), writeExec)
|
| 267 |
+
}
|
| 268 |
+
}
|
| 269 |
+
|
| 270 |
+
if vflag > 0 {
|
| 271 |
+
xprintf("\n")
|
| 272 |
+
}
|
| 273 |
+
}
|
| 274 |
+
|
| 275 |
+
var ssaRewriteFileSubstring = filepath.FromSlash("src/cmd/compile/internal/ssa/rewrite")
|
| 276 |
+
|
| 277 |
+
// isUnneededSSARewriteFile reports whether srcFile is a
|
| 278 |
+
// src/cmd/compile/internal/ssa/rewriteARCHNAME.go file for an
|
| 279 |
+
// architecture that isn't for the given GOARCH.
|
| 280 |
+
//
|
| 281 |
+
// When unneeded is true archCaps is the rewrite base filename without
|
| 282 |
+
// the "rewrite" prefix or ".go" suffix: AMD64, 386, ARM, ARM64, etc.
|
| 283 |
+
func isUnneededSSARewriteFile(srcFile, goArch string) (archCaps string, unneeded bool) {
|
| 284 |
+
if !strings.Contains(srcFile, ssaRewriteFileSubstring) {
|
| 285 |
+
return "", false
|
| 286 |
+
}
|
| 287 |
+
fileArch := strings.TrimSuffix(strings.TrimPrefix(filepath.Base(srcFile), "rewrite"), ".go")
|
| 288 |
+
if fileArch == "" {
|
| 289 |
+
return "", false
|
| 290 |
+
}
|
| 291 |
+
b := fileArch[0]
|
| 292 |
+
if b == '_' || ('a' <= b && b <= 'z') {
|
| 293 |
+
return "", false
|
| 294 |
+
}
|
| 295 |
+
archCaps = fileArch
|
| 296 |
+
fileArch = strings.ToLower(fileArch)
|
| 297 |
+
fileArch = strings.TrimSuffix(fileArch, "splitload")
|
| 298 |
+
fileArch = strings.TrimSuffix(fileArch, "latelower")
|
| 299 |
+
if fileArch == goArch {
|
| 300 |
+
return "", false
|
| 301 |
+
}
|
| 302 |
+
if fileArch == strings.TrimSuffix(goArch, "le") {
|
| 303 |
+
return "", false
|
| 304 |
+
}
|
| 305 |
+
return archCaps, true
|
| 306 |
+
}
|
| 307 |
+
|
| 308 |
+
func bootstrapRewriteFile(srcFile string) string {
|
| 309 |
+
// During bootstrap, generate dummy rewrite files for
|
| 310 |
+
// irrelevant architectures. We only need to build a bootstrap
|
| 311 |
+
// binary that works for the current gohostarch.
|
| 312 |
+
// This saves 6+ seconds of bootstrap.
|
| 313 |
+
if archCaps, ok := isUnneededSSARewriteFile(srcFile, gohostarch); ok {
|
| 314 |
+
return fmt.Sprintf(`%spackage ssa
|
| 315 |
+
|
| 316 |
+
func rewriteValue%s(v *Value) bool { panic("unused during bootstrap") }
|
| 317 |
+
func rewriteBlock%s(b *Block) bool { panic("unused during bootstrap") }
|
| 318 |
+
`, generatedHeader, archCaps, archCaps)
|
| 319 |
+
}
|
| 320 |
+
|
| 321 |
+
return bootstrapFixImports(srcFile)
|
| 322 |
+
}
|
| 323 |
+
|
| 324 |
+
var (
|
| 325 |
+
importRE = regexp.MustCompile(`\Aimport\s+(\.|[A-Za-z0-9_]+)?\s*"([^"]+)"\s*(//.*)?\n\z`)
|
| 326 |
+
importBlockRE = regexp.MustCompile(`\A\s*(?:(\.|[A-Za-z0-9_]+)?\s*"([^"]+)")?\s*(//.*)?\n\z`)
|
| 327 |
+
)
|
| 328 |
+
|
| 329 |
+
func bootstrapFixImports(srcFile string) string {
|
| 330 |
+
text := readfile(srcFile)
|
| 331 |
+
lines := strings.SplitAfter(text, "\n")
|
| 332 |
+
inBlock := false
|
| 333 |
+
inComment := false
|
| 334 |
+
for i, line := range lines {
|
| 335 |
+
if strings.HasSuffix(line, "*/\n") {
|
| 336 |
+
inComment = false
|
| 337 |
+
}
|
| 338 |
+
if strings.HasSuffix(line, "/*\n") {
|
| 339 |
+
inComment = true
|
| 340 |
+
}
|
| 341 |
+
if inComment {
|
| 342 |
+
continue
|
| 343 |
+
}
|
| 344 |
+
if strings.HasPrefix(line, "import (") {
|
| 345 |
+
inBlock = true
|
| 346 |
+
continue
|
| 347 |
+
}
|
| 348 |
+
if inBlock && strings.HasPrefix(line, ")") {
|
| 349 |
+
inBlock = false
|
| 350 |
+
continue
|
| 351 |
+
}
|
| 352 |
+
|
| 353 |
+
var m []string
|
| 354 |
+
if !inBlock {
|
| 355 |
+
if !strings.HasPrefix(line, "import ") {
|
| 356 |
+
continue
|
| 357 |
+
}
|
| 358 |
+
m = importRE.FindStringSubmatch(line)
|
| 359 |
+
if m == nil {
|
| 360 |
+
fatalf("%s:%d: invalid import declaration: %q", srcFile, i+1, line)
|
| 361 |
+
}
|
| 362 |
+
} else {
|
| 363 |
+
m = importBlockRE.FindStringSubmatch(line)
|
| 364 |
+
if m == nil {
|
| 365 |
+
fatalf("%s:%d: invalid import block line", srcFile, i+1)
|
| 366 |
+
}
|
| 367 |
+
if m[2] == "" {
|
| 368 |
+
continue
|
| 369 |
+
}
|
| 370 |
+
}
|
| 371 |
+
|
| 372 |
+
path := m[2]
|
| 373 |
+
if strings.HasPrefix(path, "cmd/") {
|
| 374 |
+
path = "bootstrap/" + path
|
| 375 |
+
} else {
|
| 376 |
+
for _, dir := range bootstrapDirs {
|
| 377 |
+
if path == dir {
|
| 378 |
+
path = "bootstrap/" + dir
|
| 379 |
+
break
|
| 380 |
+
}
|
| 381 |
+
}
|
| 382 |
+
}
|
| 383 |
+
|
| 384 |
+
// Rewrite use of internal/reflectlite to be plain reflect.
|
| 385 |
+
if path == "internal/reflectlite" {
|
| 386 |
+
lines[i] = strings.ReplaceAll(line, `"reflect"`, `reflectlite "reflect"`)
|
| 387 |
+
continue
|
| 388 |
+
}
|
| 389 |
+
|
| 390 |
+
// Otherwise, reject direct imports of internal packages,
|
| 391 |
+
// since that implies knowledge of internal details that might
|
| 392 |
+
// change from one bootstrap toolchain to the next.
|
| 393 |
+
// There are many internal packages that are listed in
|
| 394 |
+
// bootstrapDirs and made into bootstrap copies based on the
|
| 395 |
+
// current repo's source code. Those are fine; this is catching
|
| 396 |
+
// references to internal packages in the older bootstrap toolchain.
|
| 397 |
+
if strings.HasPrefix(path, "internal/") {
|
| 398 |
+
fatalf("%s:%d: bootstrap-copied source file cannot import %s", srcFile, i+1, path)
|
| 399 |
+
}
|
| 400 |
+
if path != m[2] {
|
| 401 |
+
lines[i] = strings.ReplaceAll(line, `"`+m[2]+`"`, `"`+path+`"`)
|
| 402 |
+
}
|
| 403 |
+
}
|
| 404 |
+
|
| 405 |
+
lines[0] = generatedHeader + "// This is a bootstrap copy of " + srcFile + "\n\n//line " + srcFile + ":1\n" + lines[0]
|
| 406 |
+
|
| 407 |
+
return strings.Join(lines, "")
|
| 408 |
+
}
|
go/src/cmd/dist/doc.go
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Copyright 2017 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 |
+
// Dist helps bootstrap, build, and test the Go distribution.
|
| 6 |
+
//
|
| 7 |
+
// Usage:
|
| 8 |
+
//
|
| 9 |
+
// go tool dist [command]
|
| 10 |
+
//
|
| 11 |
+
// The commands are:
|
| 12 |
+
//
|
| 13 |
+
// banner print installation banner
|
| 14 |
+
// bootstrap rebuild everything
|
| 15 |
+
// clean deletes all built files
|
| 16 |
+
// env [-p] print environment (-p: include $PATH)
|
| 17 |
+
// install [dir] install individual directory
|
| 18 |
+
// list [-json] list all supported platforms
|
| 19 |
+
// test [-h] run Go test(s)
|
| 20 |
+
// version print Go version
|
| 21 |
+
package main
|
go/src/cmd/dist/exec.go
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
package main
|
| 6 |
+
|
| 7 |
+
import (
|
| 8 |
+
"os/exec"
|
| 9 |
+
"strings"
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
// setDir sets cmd.Dir to dir, and also adds PWD=dir to cmd's environment.
|
| 13 |
+
func setDir(cmd *exec.Cmd, dir string) {
|
| 14 |
+
cmd.Dir = dir
|
| 15 |
+
if cmd.Env != nil {
|
| 16 |
+
// os/exec won't set PWD automatically.
|
| 17 |
+
setEnv(cmd, "PWD", dir)
|
| 18 |
+
}
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
// setEnv sets cmd.Env so that key = value.
|
| 22 |
+
func setEnv(cmd *exec.Cmd, key, value string) {
|
| 23 |
+
cmd.Env = append(cmd.Environ(), key+"="+value)
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
// unsetEnv sets cmd.Env so that key is not present in the environment.
|
| 27 |
+
func unsetEnv(cmd *exec.Cmd, key string) {
|
| 28 |
+
cmd.Env = cmd.Environ()
|
| 29 |
+
|
| 30 |
+
prefix := key + "="
|
| 31 |
+
newEnv := []string{}
|
| 32 |
+
for _, entry := range cmd.Env {
|
| 33 |
+
if strings.HasPrefix(entry, prefix) {
|
| 34 |
+
continue
|
| 35 |
+
}
|
| 36 |
+
newEnv = append(newEnv, entry)
|
| 37 |
+
// key may appear multiple times, so keep going.
|
| 38 |
+
}
|
| 39 |
+
cmd.Env = newEnv
|
| 40 |
+
}
|