1 // Copyright 2018 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.
5 // Package packagesdriver fetches type sizes for go/packages and go/analysis.
23 // GetSizes returns the sizes used by the underlying driver with the given parameters.
24 func GetSizes(ctx context.Context, buildFlags, env []string, dir string, usesExportData bool) (types.Sizes, error) {
25 // TODO(matloob): Clean this up. This code is mostly a copy of packages.findExternalDriver.
26 const toolPrefix = "GOPACKAGESDRIVER="
28 for _, env := range env {
29 if val := strings.TrimPrefix(env, toolPrefix); val != env {
36 tool, err = exec.LookPath("gopackagesdriver")
38 // We did not find the driver, so use "go list".
44 return GetSizesGolist(ctx, buildFlags, env, dir, usesExportData)
47 req, err := json.Marshal(struct {
48 Command string `json:"command"`
49 Env []string `json:"env"`
50 BuildFlags []string `json:"build_flags"`
54 BuildFlags: buildFlags,
57 return nil, fmt.Errorf("failed to encode message to driver tool: %v", err)
60 buf := new(bytes.Buffer)
61 cmd := exec.CommandContext(ctx, tool)
64 cmd.Stdin = bytes.NewReader(req)
66 cmd.Stderr = new(bytes.Buffer)
67 if err := cmd.Run(); err != nil {
68 return nil, fmt.Errorf("%v: %v: %s", tool, err, cmd.Stderr)
71 // Sizes, if not nil, is the types.Sizes to use when type checking.
74 if err := json.Unmarshal(buf.Bytes(), &response); err != nil {
77 return response.Sizes, nil
80 func GetSizesGolist(ctx context.Context, buildFlags, env []string, dir string, usesExportData bool) (types.Sizes, error) {
81 args := []string{"list", "-f", "{{context.GOARCH}} {{context.Compiler}}"}
82 args = append(args, buildFlags...)
83 args = append(args, "--", "unsafe")
84 stdout, err := InvokeGo(ctx, env, dir, usesExportData, args...)
88 fields := strings.Fields(stdout.String())
90 return nil, fmt.Errorf("could not determine GOARCH and Go compiler")
94 return types.SizesFor(compiler, goarch), nil
97 // InvokeGo returns the stdout of a go command invocation.
98 func InvokeGo(ctx context.Context, env []string, dir string, usesExportData bool, args ...string) (*bytes.Buffer, error) {
100 defer func(start time.Time) { log.Printf("%s for %v", time.Since(start), cmdDebugStr(env, args...)) }(time.Now())
102 stdout := new(bytes.Buffer)
103 stderr := new(bytes.Buffer)
104 cmd := exec.CommandContext(ctx, "go", args...)
105 // On darwin the cwd gets resolved to the real path, which breaks anything that
106 // expects the working directory to keep the original path, including the
107 // go command when dealing with modules.
108 // The Go stdlib has a special feature where if the cwd and the PWD are the
109 // same node then it trusts the PWD, so by setting it in the env for the child
110 // process we fix up all the paths returned by the go command.
111 cmd.Env = append(append([]string{}, env...), "PWD="+dir)
115 if err := cmd.Run(); err != nil {
116 exitErr, ok := err.(*exec.ExitError)
118 // Catastrophic error:
119 // - executable not found
120 // - context cancellation
121 return nil, fmt.Errorf("couldn't exec 'go %v': %s %T", args, err, err)
124 // Export mode entails a build.
125 // If that build fails, errors appear on stderr
126 // (despite the -e flag) and the Export field is blank.
127 // Do not fail in that case.
129 return nil, fmt.Errorf("go %v: %s: %s", args, exitErr, stderr)
133 // As of writing, go list -export prints some non-fatal compilation
134 // errors to stderr, even with -e set. We would prefer that it put
135 // them in the Package.Error JSON (see https://golang.org/issue/26319).
136 // In the meantime, there's nowhere good to put them, but they can
137 // be useful for debugging. Print them if $GOPACKAGESPRINTGOLISTERRORS
139 if len(stderr.Bytes()) != 0 && os.Getenv("GOPACKAGESPRINTGOLISTERRORS") != "" {
140 fmt.Fprintf(os.Stderr, "%s stderr: <<%s>>\n", cmdDebugStr(env, args...), stderr)
145 fmt.Fprintf(os.Stderr, "%s stdout: <<%s>>\n", cmdDebugStr(env, args...), stdout)
151 func cmdDebugStr(envlist []string, args ...string) string {
152 env := make(map[string]string)
153 for _, kv := range envlist {
154 split := strings.Split(kv, "=")
155 k, v := split[0], split[1]
159 return fmt.Sprintf("GOROOT=%v GOPATH=%v GO111MODULE=%v PWD=%v go %v", env["GOROOT"], env["GOPATH"], env["GO111MODULE"], env["PWD"], args)