Debian Codegraph @

src/cmd/go/internal/work/build.go

raw
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 work
6
7 import (
8 "context"
9 "errors"
10 "flag"
11 "fmt"
12 "go/build"
13 "os"
14 "path/filepath"
15 "runtime"
16 "strconv"
17 "strings"
18
19 "cmd/go/internal/base"
20 "cmd/go/internal/cfg"
21 "cmd/go/internal/fsys"
22 "cmd/go/internal/load"
23 "cmd/go/internal/modload"
24 "cmd/go/internal/search"
25 "cmd/go/internal/trace"
26 "cmd/internal/pathcache"
27 )
28
29 var CmdBuild = &base.Command{
30 UsageLine: "go build [-o output] [build flags] [packages]",
31 Short: "compile packages and dependencies",
32 Long: `
33 Build compiles the packages named by the import paths,
34 along with their dependencies, but it does not install the results.
35
36 If the arguments to build are a list of .go files from a single directory,
37 build treats them as a list of source files specifying a single package.
38
39 When compiling packages, build ignores files that end in '_test.go'.
40
41 When compiling a single main package, build writes the resulting
42 executable to an output file named after the last non-major-version
43 component of the package import path. The '.exe' suffix is added
44 when writing a Windows executable.
45 So 'go build example/sam' writes 'sam' or 'sam.exe'.
46 'go build example.com/foo/v2' writes 'foo' or 'foo.exe', not 'v2.exe'.
47
48 When compiling a package from a list of .go files, the executable
49 is named after the first source file.
50 'go build ed.go rx.go' writes 'ed' or 'ed.exe'.
51
52 When compiling multiple packages or a single non-main package,
53 build compiles the packages but discards the resulting object,
54 serving only as a check that the packages can be built.
55
56 The -o flag forces build to write the resulting executable or object
57 to the named output file or directory, instead of the default behavior described
58 in the last two paragraphs. If the named output is an existing directory or
59 ends with a slash or backslash, then any resulting executables
60 will be written to that directory.
61
62 The build flags are shared by the build, clean, get, install, list, run,
63 and test commands:
64
65 -C dir
66 Change to dir before running the command.
67 Any files named on the command line are interpreted after
68 changing directories.
69 If used, this flag must be the first one in the command line.
70 -a
71 force rebuilding of packages that are already up-to-date.
72 -n
73 print the commands but do not run them.
74 -p n
75 the number of programs, such as build commands or
76 test binaries, that can be run in parallel.
77 The default is GOMAXPROCS, normally the number of CPUs available.
78 -race
79 enable data race detection.
80 Supported only on linux/amd64, freebsd/amd64, darwin/amd64, darwin/arm64, windows/amd64,
81 linux/ppc64le and linux/arm64 (only for 48-bit VMA).
82 -msan
83 enable interoperation with memory sanitizer.
84 Supported only on linux/amd64, linux/arm64, linux/loong64, freebsd/amd64
85 and only with Clang/LLVM as the host C compiler.
86 PIE build mode will be used on all platforms except linux/amd64.
87 -asan
88 enable interoperation with address sanitizer.
89 Supported only on linux/arm64, linux/amd64, linux/loong64.
90 Supported on linux/amd64 or linux/arm64 and only with GCC 7 and higher
91 or Clang/LLVM 9 and higher.
92 And supported on linux/loong64 only with Clang/LLVM 16 and higher.
93 -cover
94 enable code coverage instrumentation.
95 -covermode set,count,atomic
96 set the mode for coverage analysis.
97 The default is "set" unless -race is enabled,
98 in which case it is "atomic".
99 The values:
100 set: bool: does this statement run?
101 count: int: how many times does this statement run?
102 atomic: int: count, but correct in multithreaded tests;
103 significantly more expensive.
104 Sets -cover.
105 -coverpkg pattern1,pattern2,pattern3
106 For a build that targets package 'main' (e.g. building a Go
107 executable), apply coverage analysis to each package whose
108 import path matches the patterns. The default is to apply
109 coverage analysis to packages in the main Go module. See
110 'go help packages' for a description of package patterns.
111 Sets -cover.
112 -v
113 print the names of packages as they are compiled.
114 -work
115 print the name of the temporary work directory and
116 do not delete it when exiting.
117 -x
118 print the commands.
119 -asmflags '[pattern=]arg list'
120 arguments to pass on each go tool asm invocation.
121 -buildmode mode
122 build mode to use. See 'go help buildmode' for more.
123 -buildvcs
124 Whether to stamp binaries with version control information
125 ("true", "false", or "auto"). By default ("auto"), version control
126 information is stamped into a binary if the main package, the main module
127 containing it, and the current directory are all in the same repository.
128 Use -buildvcs=false to always omit version control information, or
129 -buildvcs=true to error out if version control information is available but
130 cannot be included due to a missing tool or ambiguous directory structure.
131 -compiler name
132 name of compiler to use, as in runtime.Compiler (gccgo or gc).
133 -gccgoflags '[pattern=]arg list'
134 arguments to pass on each gccgo compiler/linker invocation.
135 -gcflags '[pattern=]arg list'
136 arguments to pass on each go tool compile invocation.
137 -installsuffix suffix
138 a suffix to use in the name of the package installation directory,
139 in order to keep output separate from default builds.
140 If using the -race flag, the install suffix is automatically set to race
141 or, if set explicitly, has _race appended to it. Likewise for the -msan
142 and -asan flags. Using a -buildmode option that requires non-default compile
143 flags has a similar effect.
144 -json
145 Emit build output in JSON suitable for automated processing.
146 See 'go help buildjson' for the encoding details.
147 -ldflags '[pattern=]arg list'
148 arguments to pass on each go tool link invocation.
149 -linkshared
150 build code that will be linked against shared libraries previously
151 created with -buildmode=shared.
152 -mod mode
153 module download mode to use: readonly, vendor, or mod.
154 By default, if a vendor directory is present and the go version in go.mod
155 is 1.14 or higher, the go command acts as if -mod=vendor were set.
156 Otherwise, the go command acts as if -mod=readonly were set.
157 See https://golang.org/ref/mod#build-commands for details.
158 -modcacherw
159 leave newly-created directories in the module cache read-write
160 instead of making them read-only.
161 -modfile file
162 in module aware mode, read (and possibly write) an alternate go.mod
163 file instead of the one in the module root directory. A file named
164 "go.mod" must still be present in order to determine the module root
165 directory, but it is not accessed. When -modfile is specified, an
166 alternate go.sum file is also used: its path is derived from the
167 -modfile flag by trimming the ".mod" extension and appending ".sum".
168 -overlay file
169 read a JSON config file that provides an overlay for build operations.
170 The file is a JSON object with a single field, named 'Replace', that
171 maps each disk file path (a string) to its backing file path, so that
172 a build will run as if the disk file path exists with the contents
173 given by the backing file paths, or as if the disk file path does not
174 exist if its backing file path is empty. Support for the -overlay flag
175 has some limitations: importantly, cgo files included from outside the
176 include path must be in the same directory as the Go package they are
177 included from, overlays will not appear when binaries and tests are
178 run through go run and go test respectively, and files beneath
179 GOMODCACHE may not be replaced.
180 -pgo file
181 specify the file path of a profile for profile-guided optimization (PGO).
182 When the special name "auto" is specified, for each main package in the
183 build, the go command selects a file named "default.pgo" in the package's
184 directory if that file exists, and applies it to the (transitive)
185 dependencies of the main package (other packages are not affected).
186 Special name "off" turns off PGO. The default is "auto".
187 -pkgdir dir
188 install and load all packages from dir instead of the usual locations.
189 For example, when building with a non-standard configuration,
190 use -pkgdir to keep generated packages in a separate location.
191 -tags tag,list
192 a comma-separated list of additional build tags to consider satisfied
193 during the build. For more information about build tags, see
194 'go help buildconstraint'. (Earlier versions of Go used a
195 space-separated list, and that form is deprecated but still recognized.)
196 -trimpath
197 remove all file system paths from the resulting executable.
198 Instead of absolute file system paths, the recorded file names
199 will begin either a module path@version (when using modules),
200 or a plain import path (when using the standard library, or GOPATH).
201 -toolexec 'cmd args'
202 a program to use to invoke toolchain programs like vet and asm.
203 For example, instead of running asm, the go command will run
204 'cmd args /path/to/asm <arguments for asm>'.
205 The TOOLEXEC_IMPORTPATH environment variable will be set,
206 matching 'go list -f {{.ImportPath}}' for the package being built.
207
208 The -asmflags, -gccgoflags, -gcflags, and -ldflags flags accept a
209 space-separated list of arguments to pass to an underlying tool
210 during the build. To embed spaces in an element in the list, surround
211 it with either single or double quotes. The argument list may be
212 preceded by a package pattern and an equal sign, which restricts
213 the use of that argument list to the building of packages matching
214 that pattern (see 'go help packages' for a description of package
215 patterns). Without a pattern, the argument list applies only to the
216 packages named on the command line. The flags may be repeated
217 with different patterns in order to specify different arguments for
218 different sets of packages. If a package matches patterns given in
219 multiple flags, the latest match on the command line wins.
220 For example, 'go build -gcflags=-S fmt' prints the disassembly
221 only for package fmt, while 'go build -gcflags=all=-S fmt'
222 prints the disassembly for fmt and all its dependencies.
223
224 For more about specifying packages, see 'go help packages'.
225 For more about where packages and binaries are installed,
226 run 'go help gopath'.
227 For more about calling between Go and C/C++, run 'go help c'.
228
229 Note: Build adheres to certain conventions such as those described
230 by 'go help gopath'. Not all projects can follow these conventions,
231 however. Installations that have their own conventions or that use
232 a separate software build system may choose to use lower-level
233 invocations such as 'go tool compile' and 'go tool link' to avoid
234 some of the overheads and design decisions of the build tool.
235
236 See also: go install, go get, go clean.
237 `,
238 }
239
240 const concurrentGCBackendCompilationEnabledByDefault = true
241
242 func init() {
243 // break init cycle
244 CmdBuild.Run = runBuild
245 CmdInstall.Run = runInstall
246
247 CmdBuild.Flag.StringVar(&cfg.BuildO, "o", "", "output file or directory")
248
249 AddBuildFlags(CmdBuild, DefaultBuildFlags)
250 AddBuildFlags(CmdInstall, DefaultBuildFlags)
251 AddCoverFlags(CmdBuild, nil)
252 AddCoverFlags(CmdInstall, nil)
253 }
254
255 // Note that flags consulted by other parts of the code
256 // (for example, buildV) are in cmd/go/internal/cfg.
257
258 var (
259 forcedAsmflags []string // internally-forced flags for cmd/asm
260 forcedGcflags []string // internally-forced flags for cmd/compile
261 forcedLdflags []string // internally-forced flags for cmd/link
262 forcedGccgoflags []string // internally-forced flags for gccgo
263 )
264
265 var BuildToolchain toolchain = noToolchain{}
266 var ldBuildmode string
267
268 // buildCompiler implements flag.Var.
269 // It implements Set by updating both
270 // BuildToolchain and buildContext.Compiler.
271 type buildCompiler struct{}
272
273 func (c buildCompiler) Set(value string) error {
274 switch value {
275 case "gc":
276 BuildToolchain = gcToolchain{}
277 case "gccgo":
278 BuildToolchain = gccgoToolchain{}
279 default:
280 return fmt.Errorf("unknown compiler %q", value)
281 }
282 cfg.BuildToolchainName = value
283 cfg.BuildContext.Compiler = value
284 return nil
285 }
286
287 func (c buildCompiler) String() string {
288 return cfg.BuildContext.Compiler
289 }
290
291 func init() {
292 switch build.Default.Compiler {
293 case "gc", "gccgo":
294 buildCompiler{}.Set(build.Default.Compiler)
295 }
296 }
297
298 type BuildFlagMask int
299
300 const (
301 DefaultBuildFlags BuildFlagMask = 0
302 OmitModFlag BuildFlagMask = 1 << iota
303 OmitModCommonFlags
304 OmitVFlag
305 OmitBuildOnlyFlags // Omit flags that only affect building packages
306 OmitJSONFlag
307 )
308
309 // AddBuildFlags adds the flags common to the build, clean, get,
310 // install, list, run, and test commands.
311 func AddBuildFlags(cmd *base.Command, mask BuildFlagMask) {
312 base.AddBuildFlagsNX(&cmd.Flag)
313 base.AddChdirFlag(&cmd.Flag)
314 cmd.Flag.BoolVar(&cfg.BuildA, "a", false, "")
315 cmd.Flag.IntVar(&cfg.BuildP, "p", cfg.BuildP, "")
316 if mask&OmitVFlag == 0 {
317 cmd.Flag.BoolVar(&cfg.BuildV, "v", false, "")
318 }
319
320 cmd.Flag.BoolVar(&cfg.BuildASan, "asan", false, "")
321 cmd.Flag.Var(&load.BuildAsmflags, "asmflags", "")
322 cmd.Flag.Var(buildCompiler{}, "compiler", "")
323 cmd.Flag.StringVar(&cfg.BuildBuildmode, "buildmode", "default", "")
324 cmd.Flag.Var((*buildvcsFlag)(&cfg.BuildBuildvcs), "buildvcs", "")
325 cmd.Flag.Var(&load.BuildGcflags, "gcflags", "")
326 cmd.Flag.Var(&load.BuildGccgoflags, "gccgoflags", "")
327 if mask&OmitModFlag == 0 {
328 base.AddModFlag(&cmd.Flag)
329 }
330 if mask&OmitModCommonFlags == 0 {
331 base.AddModCommonFlags(&cmd.Flag)
332 } else {
333 // Add the overlay flag even when we don't add the rest of the mod common flags.
334 // This only affects 'go get' in GOPATH mode, but add the flag anyway for
335 // consistency.
336 cmd.Flag.StringVar(&fsys.OverlayFile, "overlay", "", "")
337 }
338 cmd.Flag.StringVar(&cfg.BuildContext.InstallSuffix, "installsuffix", "", "")
339 if mask&(OmitBuildOnlyFlags|OmitJSONFlag) == 0 {
340 // TODO(#62250): OmitBuildOnlyFlags should apply to many more flags
341 // here, but we let a bunch of flags slip in before we realized that
342 // many of them don't make sense for most subcommands. We might even
343 // want to separate "AddBuildFlags" and "AddSelectionFlags".
344 cmd.Flag.BoolVar(&cfg.BuildJSON, "json", false, "")
345 }
346 cmd.Flag.Var(&load.BuildLdflags, "ldflags", "")
347 cmd.Flag.BoolVar(&cfg.BuildLinkshared, "linkshared", false, "")
348 cmd.Flag.BoolVar(&cfg.BuildMSan, "msan", false, "")
349 cmd.Flag.StringVar(&cfg.BuildPGO, "pgo", "auto", "")
350 cmd.Flag.StringVar(&cfg.BuildPkgdir, "pkgdir", "", "")
351 cmd.Flag.BoolVar(&cfg.BuildRace, "race", false, "")
352 cmd.Flag.Var((*tagsFlag)(&cfg.BuildContext.BuildTags), "tags", "")
353 cmd.Flag.Var((*base.StringsFlag)(&cfg.BuildToolexec), "toolexec", "")
354 cmd.Flag.BoolVar(&cfg.BuildTrimpath, "trimpath", false, "")
355 cmd.Flag.BoolVar(&cfg.BuildWork, "work", false, "")
356
357 // Undocumented, unstable debugging flags.
358 cmd.Flag.StringVar(&cfg.DebugActiongraph, "debug-actiongraph", "", "")
359 cmd.Flag.StringVar(&cfg.DebugRuntimeTrace, "debug-runtime-trace", "", "")
360 cmd.Flag.StringVar(&cfg.DebugTrace, "debug-trace", "", "")
361 }
362
363 // AddCoverFlags adds coverage-related flags to "cmd".
364 // We add -cover{mode,pkg} to the build command and only
365 // -coverprofile to the test command.
366 func AddCoverFlags(cmd *base.Command, coverProfileFlag *string) {
367 cmd.Flag.BoolVar(&cfg.BuildCover, "cover", false, "")
368 cmd.Flag.Var(coverFlag{(*coverModeFlag)(&cfg.BuildCoverMode)}, "covermode", "")
369 cmd.Flag.Var(coverFlag{commaListFlag{&cfg.BuildCoverPkg}}, "coverpkg", "")
370 if coverProfileFlag != nil {
371 cmd.Flag.Var(coverFlag{V: stringFlag{coverProfileFlag}}, "coverprofile", "")
372 }
373 }
374
375 // tagsFlag is the implementation of the -tags flag.
376 type tagsFlag []string
377
378 func (v *tagsFlag) Set(s string) error {
379 // For compatibility with Go 1.12 and earlier, allow "-tags='a b c'" or even just "-tags='a'".
380 if strings.Contains(s, " ") || strings.Contains(s, "'") {
381 return (*base.StringsFlag)(v).Set(s)
382 }
383
384 // Split on commas, ignore empty strings.
385 *v = []string{}
386 for _, s := range strings.Split(s, ",") {
387 if s != "" {
388 *v = append(*v, s)
389 }
390 }
391 return nil
392 }
393
394 func (v *tagsFlag) String() string {
395 return "<TagsFlag>"
396 }
397
398 // buildvcsFlag is the implementation of the -buildvcs flag.
399 type buildvcsFlag string
400
401 func (f *buildvcsFlag) IsBoolFlag() bool { return true } // allow -buildvcs (without arguments)
402
403 func (f *buildvcsFlag) Set(s string) error {
404 // https://go.dev/issue/51748: allow "-buildvcs=auto",
405 // in addition to the usual "true" and "false".
406 if s == "" || s == "auto" {
407 *f = "auto"
408 return nil
409 }
410
411 b, err := strconv.ParseBool(s)
412 if err != nil {
413 return errors.New("value is neither 'auto' nor a valid bool")
414 }
415 *f = (buildvcsFlag)(strconv.FormatBool(b)) // convert to canonical "true" or "false"
416 return nil
417 }
418
419 func (f *buildvcsFlag) String() string { return string(*f) }
420
421 // fileExtSplit expects a filename and returns the name
422 // and ext (without the dot). If the file has no
423 // extension, ext will be empty.
424 func fileExtSplit(file string) (name, ext string) {
425 dotExt := filepath.Ext(file)
426 name = file[:len(file)-len(dotExt)]
427 if dotExt != "" {
428 ext = dotExt[1:]
429 }
430 return
431 }
432
433 func pkgsMain(pkgs []*load.Package) (res []*load.Package) {
434 for _, p := range pkgs {
435 if p.Name == "main" {
436 res = append(res, p)
437 }
438 }
439 return res
440 }
441
442 func pkgsNotMain(pkgs []*load.Package) (res []*load.Package) {
443 for _, p := range pkgs {
444 if p.Name != "main" {
445 res = append(res, p)
446 }
447 }
448 return res
449 }
450
451 func oneMainPkg(pkgs []*load.Package) []*load.Package {
452 if len(pkgs) != 1 || pkgs[0].Name != "main" {
453 base.Fatalf("-buildmode=%s requires exactly one main package", cfg.BuildBuildmode)
454 }
455 return pkgs
456 }
457
458 var pkgsFilter = func(pkgs []*load.Package) []*load.Package { return pkgs }
459
460 func runBuild(ctx context.Context, cmd *base.Command, args []string) {
461 modload.InitWorkfile()
462 BuildInit()
463 b := NewBuilder("")
464 defer func() {
465 if err := b.Close(); err != nil {
466 base.Fatal(err)
467 }
468 }()
469
470 pkgs := load.PackagesAndErrors(ctx, load.PackageOpts{AutoVCS: true}, args)
471 load.CheckPackageErrors(pkgs)
472
473 explicitO := len(cfg.BuildO) > 0
474
475 if len(pkgs) == 1 && pkgs[0].Name == "main" && cfg.BuildO == "" {
476 cfg.BuildO = pkgs[0].DefaultExecName()
477 cfg.BuildO += cfg.ExeSuffix
478 }
479
480 // sanity check some often mis-used options
481 switch cfg.BuildContext.Compiler {
482 case "gccgo":
483 if load.BuildGcflags.Present() {
484 fmt.Println("go build: when using gccgo toolchain, please pass compiler flags using -gccgoflags, not -gcflags")
485 }
486 if load.BuildLdflags.Present() {
487 fmt.Println("go build: when using gccgo toolchain, please pass linker flags using -gccgoflags, not -ldflags")
488 }
489 case "gc":
490 if load.BuildGccgoflags.Present() {
491 fmt.Println("go build: when using gc toolchain, please pass compile flags using -gcflags, and linker flags using -ldflags")
492 }
493 }
494
495 depMode := ModeBuild
496
497 pkgs = omitTestOnly(pkgsFilter(pkgs))
498
499 // Special case -o /dev/null by not writing at all.
500 if base.IsNull(cfg.BuildO) {
501 cfg.BuildO = ""
502 }
503
504 if cfg.BuildCover {
505 load.PrepareForCoverageBuild(pkgs)
506 }
507
508 if cfg.BuildO != "" {
509 // If the -o name exists and is a directory or
510 // ends with a slash or backslash, then
511 // write all main packages to that directory.
512 // Otherwise require only a single package be built.
513 if fi, err := os.Stat(cfg.BuildO); (err == nil && fi.IsDir()) ||
514 strings.HasSuffix(cfg.BuildO, "/") ||
515 strings.HasSuffix(cfg.BuildO, string(os.PathSeparator)) {
516 if !explicitO {
517 base.Fatalf("go: build output %q already exists and is a directory", cfg.BuildO)
518 }
519 a := &Action{Mode: "go build"}
520 for _, p := range pkgs {
521 if p.Name != "main" {
522 continue
523 }
524
525 p.Target = filepath.Join(cfg.BuildO, p.DefaultExecName())
526 p.Target += cfg.ExeSuffix
527 p.Stale = true
528 p.StaleReason = "build -o flag in use"
529 a.Deps = append(a.Deps, b.AutoAction(ModeInstall, depMode, p))
530 }
531 if len(a.Deps) == 0 {
532 base.Fatalf("go: no main packages to build")
533 }
534 b.Do(ctx, a)
535 return
536 }
537 if len(pkgs) > 1 {
538 base.Fatalf("go: cannot write multiple packages to non-directory %s", cfg.BuildO)
539 } else if len(pkgs) == 0 {
540 base.Fatalf("no packages to build")
541 }
542 p := pkgs[0]
543 p.Target = cfg.BuildO
544 p.Stale = true // must build - not up to date
545 p.StaleReason = "build -o flag in use"
546 a := b.AutoAction(ModeInstall, depMode, p)
547 b.Do(ctx, a)
548 return
549 }
550
551 a := &Action{Mode: "go build"}
552 for _, p := range pkgs {
553 a.Deps = append(a.Deps, b.AutoAction(ModeBuild, depMode, p))
554 }
555 if cfg.BuildBuildmode == "shared" {
556 a = b.buildmodeShared(ModeBuild, depMode, args, pkgs, a)
557 }
558 b.Do(ctx, a)
559 }
560
561 var CmdInstall = &base.Command{
562 UsageLine: "go install [build flags] [packages]",
563 Short: "compile and install packages and dependencies",
564 Long: `
565 Install compiles and installs the packages named by the import paths.
566
567 Executables are installed in the directory named by the GOBIN environment
568 variable, which defaults to $GOPATH/bin or $HOME/go/bin if the GOPATH
569 environment variable is not set. Executables in $GOROOT
570 are installed in $GOROOT/bin or $GOTOOLDIR instead of $GOBIN.
571
572 If the arguments have version suffixes (like @latest or @v1.0.0), "go install"
573 builds packages in module-aware mode, ignoring the go.mod file in the current
574 directory or any parent directory, if there is one. This is useful for
575 installing executables without affecting the dependencies of the main module.
576 To eliminate ambiguity about which module versions are used in the build, the
577 arguments must satisfy the following constraints:
578
579 - Arguments must be package paths or package patterns (with "..." wildcards).
580 They must not be standard packages (like fmt), meta-patterns (std, cmd,
581 all), or relative or absolute file paths.
582
583 - All arguments must have the same version suffix. Different queries are not
584 allowed, even if they refer to the same version.
585
586 - All arguments must refer to packages in the same module at the same version.
587
588 - Package path arguments must refer to main packages. Pattern arguments
589 will only match main packages.
590
591 - No module is considered the "main" module. If the module containing
592 packages named on the command line has a go.mod file, it must not contain
593 directives (replace and exclude) that would cause it to be interpreted
594 differently than if it were the main module. The module must not require
595 a higher version of itself.
596
597 - Vendor directories are not used in any module. (Vendor directories are not
598 included in the module zip files downloaded by 'go install'.)
599
600 If the arguments don't have version suffixes, "go install" may run in
601 module-aware mode or GOPATH mode, depending on the GO111MODULE environment
602 variable and the presence of a go.mod file. See 'go help modules' for details.
603 If module-aware mode is enabled, "go install" runs in the context of the main
604 module.
605
606 When module-aware mode is disabled, non-main packages are installed in the
607 directory $GOPATH/pkg/$GOOS_$GOARCH. When module-aware mode is enabled,
608 non-main packages are built and cached but not installed.
609
610 Before Go 1.20, the standard library was installed to
611 $GOROOT/pkg/$GOOS_$GOARCH.
612 Starting in Go 1.20, the standard library is built and cached but not installed.
613 Setting GODEBUG=installgoroot=all restores the use of
614 $GOROOT/pkg/$GOOS_$GOARCH.
615
616 For more about build flags, see 'go help build'.
617
618 For more about specifying packages, see 'go help packages'.
619
620 See also: go build, go get, go clean.
621 `,
622 }
623
624 // libname returns the filename to use for the shared library when using
625 // -buildmode=shared. The rules we use are:
626 // Use arguments for special 'meta' packages:
627 //
628 // std --> libstd.so
629 // std cmd --> libstd,cmd.so
630 //
631 // A single non-meta argument with trailing "/..." is special cased:
632 //
633 // foo/... --> libfoo.so
634 // (A relative path like "./..." expands the "." first)
635 //
636 // Use import paths for other cases, changing '/' to '-':
637 //
638 // somelib --> libsubdir-somelib.so
639 // ./ or ../ --> libsubdir-somelib.so
640 // gopkg.in/tomb.v2 -> libgopkg.in-tomb.v2.so
641 // a/... b/... ---> liba/c,b/d.so - all matching import paths
642 //
643 // Name parts are joined with ','.
644 func libname(args []string, pkgs []*load.Package) (string, error) {
645 var libname string
646 appendName := func(arg string) {
647 if libname == "" {
648 libname = arg
649 } else {
650 libname += "," + arg
651 }
652 }
653 var haveNonMeta bool
654 for _, arg := range args {
655 if search.IsMetaPackage(arg) {
656 appendName(arg)
657 } else {
658 haveNonMeta = true
659 }
660 }
661 if len(libname) == 0 { // non-meta packages only. use import paths
662 if len(args) == 1 && strings.HasSuffix(args[0], "/...") {
663 // Special case of "foo/..." as mentioned above.
664 arg := strings.TrimSuffix(args[0], "/...")
665 if build.IsLocalImport(arg) {
666 cwd, _ := os.Getwd()
667 bp, _ := cfg.BuildContext.ImportDir(filepath.Join(cwd, arg), build.FindOnly)
668 if bp.ImportPath != "" && bp.ImportPath != "." {
669 arg = bp.ImportPath
670 }
671 }
672 appendName(strings.ReplaceAll(arg, "/", "-"))
673 } else {
674 for _, pkg := range pkgs {
675 appendName(strings.ReplaceAll(pkg.ImportPath, "/", "-"))
676 }
677 }
678 } else if haveNonMeta { // have both meta package and a non-meta one
679 return "", errors.New("mixing of meta and non-meta packages is not allowed")
680 }
681 // TODO(mwhudson): Needs to change for platforms that use different naming
682 // conventions...
683 return "lib" + libname + ".so", nil
684 }
685
686 func runInstall(ctx context.Context, cmd *base.Command, args []string) {
687 for _, arg := range args {
688 if strings.Contains(arg, "@") && !build.IsLocalImport(arg) && !filepath.IsAbs(arg) {
689 installOutsideModule(ctx, args)
690 return
691 }
692 }
693
694 modload.InitWorkfile()
695 BuildInit()
696 pkgs := load.PackagesAndErrors(ctx, load.PackageOpts{AutoVCS: true}, args)
697 if cfg.ModulesEnabled && !modload.HasModRoot() {
698 haveErrors := false
699 allMissingErrors := true
700 for _, pkg := range pkgs {
701 if pkg.Error == nil {
702 continue
703 }
704 haveErrors = true
705 if missingErr := (*modload.ImportMissingError)(nil); !errors.As(pkg.Error, &missingErr) {
706 allMissingErrors = false
707 break
708 }
709 }
710 if haveErrors && allMissingErrors {
711 latestArgs := make([]string, len(args))
712 for i := range args {
713 latestArgs[i] = args[i] + "@latest"
714 }
715 hint := strings.Join(latestArgs, " ")
716 base.Fatalf("go: 'go install' requires a version when current directory is not in a module\n\tTry 'go install %s' to install the latest version", hint)
717 }
718 }
719 load.CheckPackageErrors(pkgs)
720
721 if cfg.BuildCover {
722 load.PrepareForCoverageBuild(pkgs)
723 }
724
725 InstallPackages(ctx, args, pkgs)
726 }
727
728 // omitTestOnly returns pkgs with test-only packages removed.
729 func omitTestOnly(pkgs []*load.Package) []*load.Package {
730 var list []*load.Package
731 for _, p := range pkgs {
732 if len(p.GoFiles)+len(p.CgoFiles) == 0 && !p.Internal.CmdlinePkgLiteral {
733 // Package has no source files,
734 // perhaps due to build tags or perhaps due to only having *_test.go files.
735 // Also, it is only being processed as the result of a wildcard match
736 // like ./..., not because it was listed as a literal path on the command line.
737 // Ignore it.
738 continue
739 }
740 list = append(list, p)
741 }
742 return list
743 }
744
745 func InstallPackages(ctx context.Context, patterns []string, pkgs []*load.Package) {
746 ctx, span := trace.StartSpan(ctx, "InstallPackages "+strings.Join(patterns, " "))
747 defer span.Done()
748
749 if cfg.GOBIN != "" && !filepath.IsAbs(cfg.GOBIN) {
750 base.Fatalf("cannot install, GOBIN must be an absolute path")
751 }
752
753 pkgs = omitTestOnly(pkgsFilter(pkgs))
754 for _, p := range pkgs {
755 if p.Target == "" {
756 switch {
757 case p.Name != "main" && p.Internal.Local && p.ConflictDir == "":
758 // Non-executables outside GOPATH need not have a target:
759 // we can use the cache to hold the built package archive for use in future builds.
760 // The ones inside GOPATH should have a target (in GOPATH/pkg)
761 // or else something is wrong and worth reporting (like a ConflictDir).
762 case p.Name != "main" && p.Module != nil:
763 // Non-executables have no target (except the cache) when building with modules.
764 case p.Name != "main" && p.Standard && p.Internal.Build.PkgObj == "":
765 // Most packages in std do not need an installed .a, because they can be
766 // rebuilt and used directly from the build cache.
767 // A few targets (notably those using cgo) still do need to be installed
768 // in case the user's environment lacks a C compiler.
769 case p.Internal.GobinSubdir:
770 base.Errorf("go: cannot install cross-compiled binaries when GOBIN is set")
771 case p.Internal.CmdlineFiles:
772 base.Errorf("go: no install location for .go files listed on command line (GOBIN not set)")
773 case p.ConflictDir != "":
774 base.Errorf("go: no install location for %s: hidden by %s", p.Dir, p.ConflictDir)
775 default:
776 base.Errorf("go: no install location for directory %s outside GOPATH\n"+
777 "\tFor more details see: 'go help gopath'", p.Dir)
778 }
779 }
780 }
781 base.ExitIfErrors()
782
783 b := NewBuilder("")
784 defer func() {
785 if err := b.Close(); err != nil {
786 base.Fatal(err)
787 }
788 }()
789
790 depMode := ModeBuild
791 a := &Action{Mode: "go install"}
792 var tools []*Action
793 for _, p := range pkgs {
794 // If p is a tool, delay the installation until the end of the build.
795 // This avoids installing assemblers/compilers that are being executed
796 // by other steps in the build.
797 a1 := b.AutoAction(ModeInstall, depMode, p)
798 if load.InstallTargetDir(p) == load.ToTool {
799 a.Deps = append(a.Deps, a1.Deps...)
800 a1.Deps = append(a1.Deps, a)
801 tools = append(tools, a1)
802 continue
803 }
804 a.Deps = append(a.Deps, a1)
805 }
806 if len(tools) > 0 {
807 a = &Action{
808 Mode: "go install (tools)",
809 Deps: tools,
810 }
811 }
812
813 if cfg.BuildBuildmode == "shared" {
814 // Note: If buildmode=shared then only non-main packages
815 // are present in the pkgs list, so all the special case code about
816 // tools above did not apply, and a is just a simple Action
817 // with a list of Deps, one per package named in pkgs,
818 // the same as in runBuild.
819 a = b.buildmodeShared(ModeInstall, ModeInstall, patterns, pkgs, a)
820 }
821
822 b.Do(ctx, a)
823 base.ExitIfErrors()
824
825 // Success. If this command is 'go install' with no arguments
826 // and the current directory (the implicit argument) is a command,
827 // remove any leftover command binary from a previous 'go build'.
828 // The binary is installed; it's not needed here anymore.
829 // And worse it might be a stale copy, which you don't want to find
830 // instead of the installed one if $PATH contains dot.
831 // One way to view this behavior is that it is as if 'go install' first
832 // runs 'go build' and the moves the generated file to the install dir.
833 // See issue 9645.
834 if len(patterns) == 0 && len(pkgs) == 1 && pkgs[0].Name == "main" {
835 // Compute file 'go build' would have created.
836 // If it exists and is an executable file, remove it.
837 targ := pkgs[0].DefaultExecName()
838 targ += cfg.ExeSuffix
839 if filepath.Join(pkgs[0].Dir, targ) != pkgs[0].Target { // maybe $GOBIN is the current directory
840 fi, err := os.Stat(targ)
841 if err == nil {
842 m := fi.Mode()
843 if m.IsRegular() {
844 if m&0111 != 0 || cfg.Goos == "windows" { // windows never sets executable bit
845 os.Remove(targ)
846 }
847 }
848 }
849 }
850 }
851 }
852
853 // installOutsideModule implements 'go install pkg@version'. It builds and
854 // installs one or more main packages in module mode while ignoring any go.mod
855 // in the current directory or parent directories.
856 //
857 // See golang.org/issue/40276 for details and rationale.
858 func installOutsideModule(ctx context.Context, args []string) {
859 modload.ForceUseModules = true
860 modload.RootMode = modload.NoRoot
861 modload.AllowMissingModuleImports()
862 modload.Init()
863 BuildInit()
864
865 // Load packages. Ignore non-main packages.
866 // Print a warning if an argument contains "..." and matches no main packages.
867 // PackagesAndErrors already prints warnings for patterns that don't match any
868 // packages, so be careful not to double print.
869 // TODO(golang.org/issue/40276): don't report errors loading non-main packages
870 // matched by a pattern.
871 pkgOpts := load.PackageOpts{MainOnly: true}
872 pkgs, err := load.PackagesAndErrorsOutsideModule(ctx, pkgOpts, args)
873 if err != nil {
874 base.Fatal(err)
875 }
876 load.CheckPackageErrors(pkgs)
877 patterns := make([]string, len(args))
878 for i, arg := range args {
879 patterns[i] = arg[:strings.Index(arg, "@")]
880 }
881
882 // Build and install the packages.
883 InstallPackages(ctx, patterns, pkgs)
884 }
885
886 // ExecCmd is the command to use to run user binaries.
887 // Normally it is empty, meaning run the binaries directly.
888 // If cross-compiling and running on a remote system or
889 // simulator, it is typically go_GOOS_GOARCH_exec, with
890 // the target GOOS and GOARCH substituted.
891 // The -exec flag overrides these defaults.
892 var ExecCmd []string
893
894 // FindExecCmd derives the value of ExecCmd to use.
895 // It returns that value and leaves ExecCmd set for direct use.
896 func FindExecCmd() []string {
897 if ExecCmd != nil {
898 return ExecCmd
899 }
900 ExecCmd = []string{} // avoid work the second time
901 if cfg.Goos == runtime.GOOS && cfg.Goarch == runtime.GOARCH {
902 return ExecCmd
903 }
904 path, err := pathcache.LookPath(fmt.Sprintf("go_%s_%s_exec", cfg.Goos, cfg.Goarch))
905 if err == nil {
906 ExecCmd = []string{path}
907 }
908 return ExecCmd
909 }
910
911 // A coverFlag is a flag.Value that also implies -cover.
912 type coverFlag struct{ V flag.Value }
913
914 func (f coverFlag) String() string { return f.V.String() }
915
916 func (f coverFlag) Set(value string) error {
917 if err := f.V.Set(value); err != nil {
918 return err
919 }
920 cfg.BuildCover = true
921 return nil
922 }
923
924 type coverModeFlag string
925
926 func (f *coverModeFlag) String() string { return string(*f) }
927 func (f *coverModeFlag) Set(value string) error {
928 switch value {
929 case "", "set", "count", "atomic":
930 *f = coverModeFlag(value)
931 cfg.BuildCoverMode = value
932 return nil
933 default:
934 return errors.New(`valid modes are "set", "count", or "atomic"`)
935 }
936 }
937
938 // A commaListFlag is a flag.Value representing a comma-separated list.
939 type commaListFlag struct{ Vals *[]string }
940
941 func (f commaListFlag) String() string { return strings.Join(*f.Vals, ",") }
942
943 func (f commaListFlag) Set(value string) error {
944 if value == "" {
945 *f.Vals = nil
946 } else {
947 *f.Vals = strings.Split(value, ",")
948 }
949 return nil
950 }
951
952 // A stringFlag is a flag.Value representing a single string.
953 type stringFlag struct{ val *string }
954
955 func (f stringFlag) String() string { return *f.val }
956 func (f stringFlag) Set(value string) error {
957 *f.val = value
958 return nil
959 }