work

Imports

Imports #

"context"
"errors"
"flag"
"fmt"
"go/build"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"cmd/go/internal/base"
"cmd/go/internal/cfg"
"cmd/go/internal/fsys"
"cmd/go/internal/load"
"cmd/go/internal/modload"
"cmd/go/internal/search"
"cmd/go/internal/trace"
"cmd/internal/pathcache"
"cmd/go/internal/base"
"cmd/go/internal/cfg"
"cmd/go/internal/str"
"cmd/internal/cov/covcmd"
"context"
"encoding/json"
"fmt"
"internal/coverage"
"io"
"os"
"path/filepath"
"bytes"
"cmd/internal/cov/covcmd"
"cmd/internal/pathcache"
"context"
"crypto/sha256"
"encoding/json"
"errors"
"fmt"
"go/token"
"internal/lazyregexp"
"io"
"io/fs"
"log"
"math/rand"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"slices"
"sort"
"strconv"
"strings"
"sync"
"time"
"cmd/go/internal/base"
"cmd/go/internal/cache"
"cmd/go/internal/cfg"
"cmd/go/internal/fsys"
"cmd/go/internal/gover"
"cmd/go/internal/load"
"cmd/go/internal/modload"
"cmd/go/internal/str"
"cmd/go/internal/trace"
"cmd/internal/buildid"
"cmd/internal/quoted"
"cmd/internal/sys"
"bytes"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
"cmd/go/internal/base"
"cmd/go/internal/cfg"
"cmd/go/internal/fsys"
"cmd/go/internal/load"
"cmd/go/internal/str"
"cmd/internal/pathcache"
"cmd/internal/pkgpath"
"fmt"
"internal/lazyregexp"
"regexp"
"strings"
"cmd/go/internal/cfg"
"cmd/go/internal/load"
"bytes"
"cmd/go/internal/base"
"cmd/go/internal/cache"
"cmd/go/internal/cfg"
"cmd/go/internal/load"
"cmd/go/internal/str"
"cmd/internal/par"
"cmd/internal/pathcache"
"errors"
"fmt"
"internal/lazyregexp"
"io"
"io/fs"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"strings"
"sync"
"time"
"bytes"
"fmt"
"os"
"os/exec"
"strings"
"sync"
"cmd/go/internal/base"
"cmd/go/internal/cache"
"cmd/go/internal/cfg"
"cmd/go/internal/fsys"
"cmd/go/internal/str"
"cmd/internal/buildid"
"cmd/internal/pathcache"
"cmd/internal/quoted"
"cmd/internal/telemetry/counter"
"bufio"
"bytes"
"fmt"
"internal/buildcfg"
"internal/platform"
"io"
"log"
"os"
"path/filepath"
"runtime"
"strings"
"cmd/go/internal/base"
"cmd/go/internal/cfg"
"cmd/go/internal/fips140"
"cmd/go/internal/fsys"
"cmd/go/internal/gover"
"cmd/go/internal/load"
"cmd/go/internal/str"
"cmd/internal/quoted"
"crypto/sha1"
"bytes"
"cmd/go/internal/base"
"cmd/go/internal/cfg"
"cmd/go/internal/fsys"
"cmd/go/internal/modload"
"cmd/internal/quoted"
"fmt"
"internal/platform"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"strconv"
"sync"
"bufio"
"bytes"
"cmd/internal/cov/covcmd"
"container/heap"
"context"
"debug/elf"
"encoding/json"
"fmt"
"internal/platform"
"os"
"path/filepath"
"strings"
"sync"
"time"
"cmd/go/internal/base"
"cmd/go/internal/cache"
"cmd/go/internal/cfg"
"cmd/go/internal/load"
"cmd/go/internal/str"
"cmd/go/internal/trace"
"cmd/internal/buildid"
"cmd/internal/robustio"

Constants & Variables

AllowInstall var #

AllowInstall returns a non-nil error if this invocation of the go command is allowed to install a.Target. The build of cmd/go running under its own test is forbidden from installing to its original GOROOT. The var is exported so it can be set by TestMain.

var AllowInstall = *ast.FuncLit

BuildToolchain var #

var BuildToolchain toolchain = noToolchain{...}

CmdBuild var #

var CmdBuild = *ast.UnaryExpr

CmdInstall var #

var CmdInstall = *ast.UnaryExpr

DefaultBuildFlags const #

const DefaultBuildFlags BuildFlagMask = 0

DefaultCFlags const #

const DefaultCFlags = "-O2 -g"

ExecCmd var #

ExecCmd is the command to use to run user binaries. Normally it is empty, meaning run the binaries directly. If cross-compiling and running on a remote system or simulator, it is typically go_GOOS_GOARCH_exec, with the target GOOS and GOARCH substituted. The -exec flag overrides these defaults.

var ExecCmd []string

GccgoBin var #

var GccgoBin string

GccgoName var #

var GccgoName string

ModeBuggyInstall const #

const ModeBuggyInstall

ModeBuild const #

const ModeBuild BuildMode = iota

ModeInstall const #

const ModeInstall

ModeVetOnly const #

const ModeVetOnly = *ast.BinaryExpr

OmitBuildOnlyFlags const #

const OmitBuildOnlyFlags

OmitJSONFlag const #

const OmitJSONFlag

OmitModCommonFlags const #

const OmitModCommonFlags

OmitModFlag const #

const OmitModFlag BuildFlagMask = *ast.BinaryExpr

OmitVFlag const #

const OmitVFlag

ToolchainVersion var #

Tests can override this by setting $TESTGO_TOOLCHAIN_VERSION.

var ToolchainVersion = *ast.CallExpr

VetExplicit var #

VetExplicit records whether the vet flags were set explicitly on the command line.

var VetExplicit bool

VetFlags var #

VetFlags are the default flags to pass to vet. The caller is expected to set them before executing any vet actions.

var VetFlags []string

VetTool var #

VetTool is the path to an alternate vet tool binary. The caller is expected to set it (if needed) before executing any vet actions.

var VetTool string

buildIDSeparator const #

const buildIDSeparator = "/"

buildInitStarted var #

var buildInitStarted = false

builderWorkDirs var #

var builderWorkDirs sync.Map

cgoLine var #

var cgoLine = *ast.CallExpr

cgoRe var #

var cgoRe = *ast.CallExpr

cgoTypeSigRe var #

var cgoTypeSigRe = *ast.CallExpr

compiler var #

var compiler struct{...}

concurrentGCBackendCompilationEnabledByDefault const #

const concurrentGCBackendCompilationEnabledByDefault = true

counterCacheHit var #

var counterCacheHit = *ast.CallExpr

counterCacheMiss var #

var counterCacheMiss = *ast.CallExpr

forcedAsmflags var #

var forcedAsmflags []string

forcedGccgoflags var #

var forcedGccgoflags []string

forcedGcflags var #

var forcedGcflags []string

forcedLdflags var #

var forcedLdflags []string

gccgoErr var #

var gccgoErr error

gccgoSupportsCgoIncomplete var #

var gccgoSupportsCgoIncomplete bool

gccgoSupportsCgoIncompleteCode const #

const gccgoSupportsCgoIncompleteCode = `
package p

import "runtime/cgo"

type I cgo.Incomplete
`

gccgoSupportsCgoIncompleteOnce var #

var gccgoSupportsCgoIncompleteOnce sync.Once

gccgoToSymbolFunc var #

var gccgoToSymbolFunc func(string) string

gccgoToSymbolFuncOnce var #

var gccgoToSymbolFuncOnce sync.Once

invalidLinkerFlags var #

var invalidLinkerFlags = []*lazyregexp.Regexp{...}

ldBuildmode var #

var ldBuildmode string

needBuild const #

const needBuild uint32 = *ast.BinaryExpr

needCgoHdr const #

const needCgoHdr

needCompiledGoFiles const #

const needCompiledGoFiles

needCovMetaFile const #

const needCovMetaFile

needStale const #

const needStale

needVet const #

const needVet

objectMagic var #

var objectMagic = [][]byte{...}

pkgsFilter var #

var pkgsFilter = *ast.FuncLit

re var #

var re = lazyregexp.New

stdlibRecompiled var #

var stdlibRecompiled = *ast.CallExpr

stdlibRecompiledIncOnce var #

var stdlibRecompiledIncOnce = *ast.CallExpr

swigCheck var #

Make sure SWIG is new enough.

var swigCheck error

swigCheckOnce var #

Make sure SWIG is new enough.

var swigCheckOnce sync.Once

swigIntSize var #

Find the value to pass for the -intgosize option to swig.

var swigIntSize string

swigIntSizeCode const #

This code fails to build if sizeof(int) <= 32

const swigIntSizeCode = `
package main
const i int = 1 << 32
`

swigIntSizeError var #

Find the value to pass for the -intgosize option to swig.

var swigIntSizeError error

swigIntSizeOnce var #

Find the value to pass for the -intgosize option to swig.

var swigIntSizeOnce sync.Once

validCompilerFlags var #

var validCompilerFlags = []*lazyregexp.Regexp{...}

validCompilerFlagsWithNextArg var #

var validCompilerFlagsWithNextArg = []string{...}

validLinkerFlags var #

var validLinkerFlags = []*lazyregexp.Regexp{...}

validLinkerFlagsWithNextArg var #

var validLinkerFlagsWithNextArg = []string{...}

Type Aliases

ActorFunc type #

An ActorFunc is an Actor that calls the function.

type ActorFunc func(*Builder, context.Context, *Action) error

BuildFlagMask type #

type BuildFlagMask int

BuildMode type #

BuildMode specifies the build mode: are we just building things or also installing the results?

type BuildMode int

actionQueue type #

An actionQueue is a priority queue of actions.

type actionQueue []*Action

buildvcsFlag type #

buildvcsFlag is the implementation of the -buildvcs flag.

type buildvcsFlag string

coverModeFlag type #

type coverModeFlag string

tagsFlag type #

tagsFlag is the implementation of the -tags flag.

type tagsFlag []string

Interfaces

Actor interface #

An Actor runs an action.

type Actor interface {
Act(*Builder, context.Context, *Action) error
}

toolchain interface #

type toolchain interface {
gc(b *Builder, a *Action, archive string, importcfg []byte, embedcfg []byte, symabis string, asmhdr bool, pgoProfile string, gofiles []string) (ofile string, out []byte, err error)
cc(b *Builder, a *Action, ofile string, cfile string) error
asm(b *Builder, a *Action, sfiles []string) ([]string, error)
symabis(b *Builder, a *Action, sfiles []string) (string, error)
pack(b *Builder, a *Action, afile string, ofiles []string) error
ld(b *Builder, root *Action, targetPath string, importcfg string, mainpkg string) error
ldShared(b *Builder, root *Action, toplevelactions []*Action, targetPath string, importcfg string, allactions []*Action) error
compiler() string
linker() string
}

Structs

Action struct #

An Action represents a single action in the action graph.

type Action struct {
Mode string
Package *load.Package
Deps []*Action
Actor Actor
IgnoreFail bool
TestOutput *bytes.Buffer
Args []string
triggers []*Action
buggyInstall bool
TryCache func(*Builder, *Action) bool
CacheExecutable bool
Objdir string
Target string
built string
actionID cache.ActionID
buildID string
VetxOnly bool
needVet bool
needBuild bool
vetCfg *vetConfig
output []byte
sh *Shell
pending int
priority int
Failed *Action
json *actionJSON
nonGoOverlay map[string]string
traceSpan *trace.Span
}

Builder struct #

A Builder holds global state about a build. It does not hold per-package state, because we build packages in parallel, and the builder is shared.

type Builder struct {
WorkDir string
actionCache map[cacheKey]*Action
flagCache map[[2]string]bool
gccCompilerIDCache map[string]cache.ActionID
IsCmdList bool
NeedError bool
NeedExport bool
NeedCompiledGoFiles bool
AllowErrors bool
objdirSeq int
pkgSeq int
backgroundSh *Shell
exec sync.Mutex
readySema chan bool
ready actionQueue
id sync.Mutex
toolIDCache map[string]string
buildIDCache map[string]string
}

Shell struct #

A Shell runs shell commands and performs shell-like file system operations. Shell tracks context related to running commands, and form a tree much like context.Context.

type Shell struct {
action *Action
*shellShared
}

actionJSON struct #

type actionJSON struct {
ID int
Mode string
Package string
Deps []int `json:",omitempty"`
IgnoreFail bool `json:",omitempty"`
Args []string `json:",omitempty"`
Link bool `json:",omitempty"`
Objdir string `json:",omitempty"`
Target string `json:",omitempty"`
Priority int `json:",omitempty"`
Failed bool `json:",omitempty"`
Built string `json:",omitempty"`
VetxOnly bool `json:",omitempty"`
NeedVet bool `json:",omitempty"`
NeedBuild bool `json:",omitempty"`
ActionID string `json:",omitempty"`
BuildID string `json:",omitempty"`
TimeReady time.Time `json:",omitempty"`
TimeStart time.Time `json:",omitempty"`
TimeDone time.Time `json:",omitempty"`
Cmd []string
CmdReal time.Duration `json:",omitempty"`
CmdUser time.Duration `json:",omitempty"`
CmdSys time.Duration `json:",omitempty"`
}

buildActor struct #

buildActor implements the Actor interface for package build actions. For most package builds this simply means invoking th *Builder.build method; in the case of "go test -cover" for a package with no test files, we stores some additional state information in the build actor to help with reporting.

type buildActor struct {
covMetaFileName string
}

buildCompiler struct #

buildCompiler implements flag.Var. It implements Set by updating both BuildToolchain and buildContext.Compiler.

type buildCompiler struct {

}

cacheKey struct #

cacheKey is the key for the action cache.

type cacheKey struct {
mode string
p *load.Package
}

cmdError struct #

type cmdError struct {
desc string
text string
importPath string
needsPath bool
}

commaListFlag struct #

A commaListFlag is a flag.Value representing a comma-separated list.

type commaListFlag struct {
Vals *[]string
}

coverFlag struct #

A coverFlag is a flag.Value that also implies -cover.

type coverFlag struct {
V flag.Value
}

gcToolchain struct #

type gcToolchain struct {

}

gccgoToolchain struct #

type gccgoToolchain struct {

}

noToolchain struct #

type noToolchain struct {

}

pgoActor struct #

pgoActor implements the Actor interface for preprocessing PGO profiles.

type pgoActor struct {
input string
}

shellShared struct #

shellShared is Shell state shared across all Shells derived from a single root shell (generally a single Builder).

type shellShared struct {
workDir string
printLock sync.Mutex
printer load.Printer
scriptDir string
mkdirCache *ast.IndexListExpr
}

stringFlag struct #

A stringFlag is a flag.Value representing a single string.

type stringFlag struct {
val *string
}

version struct #

type version struct {
name string
major int
minor int
}

vetConfig struct #

vetConfig is the configuration passed to vet describing a single package.

type vetConfig struct {
ID string
Compiler string
Dir string
ImportPath string
GoFiles []string
NonGoFiles []string
IgnoredFiles []string
ModulePath string
ModuleVersion string
ImportMap map[string]string
PackageFile map[string]string
Standard map[string]bool
PackageVetx map[string]string
VetxOnly bool
VetxOutput string
GoVersion string
SucceedOnTypecheckFailure bool
}

Functions

Act method #

func (ba *buildActor) Act(b *Builder, ctx context.Context, a *Action) error

Act method #

func (p *pgoActor) Act(b *Builder, ctx context.Context, a *Action) error

Act method #

func (f ActorFunc) Act(b *Builder, ctx context.Context, a *Action) error

AddBuildFlags function #

AddBuildFlags adds the flags common to the build, clean, get, install, list, run, and test commands.

func AddBuildFlags(cmd *base.Command, mask BuildFlagMask)

AddCoverFlags function #

AddCoverFlags adds coverage-related flags to "cmd". If the CoverageRedesign experiment is enabled, we add -cover{mode,pkg} to the build command and only -coverprofile to the test command. If the CoverageRedesign experiment is disabled, -cover* flags are added only to the test command.

func AddCoverFlags(cmd *base.Command, coverProfileFlag *string)

AutoAction method #

AutoAction returns the "right" action for go build or go install of p.

func (b *Builder) AutoAction(mode BuildMode, depMode BuildMode, p *load.Package) *Action

BackgroundShell method #

BackgroundShell returns a Builder-wide Shell that's not bound to any Action. Try not to use this unless there's really no sensible Action available.

func (b *Builder) BackgroundShell() *Shell

BuildActionCoverMetaFile function #

BuildActionCoverMetaFile locates and returns the path of the meta-data file written by the "go tool cover" step as part of the build action for the "go test -cover" run action 'runAct'. Note that if the package has no functions the meta-data file will exist but will be empty; in this case the return is an empty string.

func BuildActionCoverMetaFile(runAct *Action) (string, error)

BuildActionID method #

BuildActionID returns the action ID section of a's build ID.

func (a *Action) BuildActionID() string

BuildContentID method #

BuildContentID returns the content ID section of a's build ID.

func (a *Action) BuildContentID() string

BuildID method #

BuildID returns a's build ID.

func (a *Action) BuildID() string

BuildInit function #

func BuildInit()

BuildInstallFunc function #

BuildInstallFunc is the action for installing a single package or executable.

func BuildInstallFunc(b *Builder, ctx context.Context, a *Action) (err error)

BuiltTarget method #

BuiltTarget returns the actual file that was built. This differs from Target when the result was cached.

func (a *Action) BuiltTarget() string

CFlags method #

CFlags returns the flags to use when invoking the C, C++ or Fortran compilers, or cgo.

func (b *Builder) CFlags(p *load.Package) (cppflags []string, cflags []string, cxxflags []string, fflags []string, ldflags []string, err error)

CheckGOOSARCHPair function #

func CheckGOOSARCHPair(goos string, goarch string) error

Close method #

func (b *Builder) Close() error

CompileAction method #

CompileAction returns the action for compiling and possibly installing (according to mode) the given package. The resulting action is only for building packages (archives), never for linking executables. depMode is the action (build or install) to use when building dependencies. To turn package main into an executable, call b.Link instead.

func (b *Builder) CompileAction(mode BuildMode, depMode BuildMode, p *load.Package) *Action

CopyFile method #

copyFile is like 'cp src dst'.

func (sh *Shell) CopyFile(dst string, src string, perm fs.FileMode, force bool) error

CovData method #

CovData invokes "go tool covdata" with the specified arguments as part of the execution of action 'a'.

func (b *Builder) CovData(a *Action, cmdargs ...any) ([]byte, error)

Do method #

Do runs the action graph rooted at root.

func (b *Builder) Do(ctx context.Context, root *Action)

Error method #

func (e *cmdError) Error() string

Errorf method #

Errorf reports an error on sh's package and sets the process exit status to 1.

func (sh *Shell) Errorf(format string, a ...any)

FindExecCmd function #

FindExecCmd derives the value of ExecCmd to use. It returns that value and leaves ExecCmd set for direct use.

func FindExecCmd() []string

GccCmd method #

GccCmd returns a gcc command line prefix defaultCC is defined in zdefaultcc.go, written by cmd/dist.

func (b *Builder) GccCmd(incdir string, workdir string) []string

GxxCmd method #

GxxCmd returns a g++ command line prefix defaultCXX is defined in zdefaultcc.go, written by cmd/dist.

func (b *Builder) GxxCmd(incdir string, workdir string) []string

ImportPath method #

func (e *cmdError) ImportPath() string

InstallPackages function #

func InstallPackages(ctx context.Context, patterns []string, pkgs []*load.Package)

IsBoolFlag method #

func (f *buildvcsFlag) IsBoolFlag() bool

Len method #

Implement heap.Interface

func (q *actionQueue) Len() int

Less method #

func (q *actionQueue) Less(i int, j int) bool

LinkAction method #

LinkAction returns the action for linking p into an executable and possibly installing the result (according to mode). depMode is the action (build or install) to use when compiling dependencies.

func (b *Builder) LinkAction(mode BuildMode, depMode BuildMode, p *load.Package) *Action

Mkdir method #

Mkdir makes the named directory.

func (sh *Shell) Mkdir(dir string) error

NewBuilder function #

NewBuilder returns a new Builder ready for use. If workDir is the empty string, NewBuilder creates a WorkDir if needed and arranges for it to be removed in case of an unclean exit. The caller must Close the builder explicitly to clean up the WorkDir before a clean exit.

func NewBuilder(workDir string) *Builder

NewObjdir method #

NewObjdir returns the name of a fresh object directory under b.WorkDir. It is up to the caller to call b.Mkdir on the result at an appropriate time. The result ends in a slash, so that file names in that directory can be constructed with direct string addition. NewObjdir must be called only from a single goroutine at a time, so it is safe to call during action graph construction, but it must not be called during action graph execution.

func (b *Builder) NewObjdir() string

NewShell function #

NewShell returns a new Shell. Shell will internally serialize calls to the printer. If printer is nil, it uses load.DefaultPrinter.

func NewShell(workDir string, printer load.Printer) *Shell

PkgconfigCmd method #

PkgconfigCmd returns a pkg-config binary name defaultPkgConfig is defined in zdefaultcc.go, written by cmd/dist.

func (b *Builder) PkgconfigCmd() string

Pop method #

func (q *actionQueue) Pop() any

Printf method #

Printf emits a to this Shell's output stream, formatting it like fmt.Printf. It is safe to call concurrently.

func (sh *Shell) Printf(format string, a ...any)

Push method #

func (q *actionQueue) Push(x any)

RemoveAll method #

RemoveAll is like 'rm -rf'. It attempts to remove all paths even if there's an error, and returns the first error.

func (sh *Shell) RemoveAll(paths ...string) error

Set method #

func (f commaListFlag) Set(value string) error

Set method #

func (f *buildvcsFlag) Set(s string) error

Set method #

func (v *tagsFlag) Set(s string) error

Set method #

func (c buildCompiler) Set(value string) error

Set method #

func (f stringFlag) Set(value string) error

Set method #

func (f *coverModeFlag) Set(value string) error

Set method #

func (f coverFlag) Set(value string) error

Shell method #

Shell returns a shell for running commands on behalf of Action a.

func (b *Builder) Shell(a *Action) *Shell

ShowCmd method #

ShowCmd prints the given command to standard output for the implementation of -n or -x. ShowCmd also replaces the name of the current script directory with dot (.) but only when it is at the beginning of a space-separated token. If dir is not "" or "/" and not the current script directory, ShowCmd first prints a "cd" command to switch to dir and updates the script directory.

func (sh *Shell) ShowCmd(dir string, format string, args ...any)

String method #

func (f *buildvcsFlag) String() string

String method #

func (v *tagsFlag) String() string

String method #

func (c buildCompiler) String() string

String method #

func (f coverFlag) String() string

String method #

func (f *coverModeFlag) String() string

String method #

func (f commaListFlag) String() string

String method #

func (f stringFlag) String() string

Swap method #

func (q *actionQueue) Swap(i int, j int)

VetAction method #

VetAction returns the action for running go vet on package p. It depends on the action for compiling p. If the caller may be causing p to be installed, it is up to the caller to make sure that the install depends on (runs after) vet.

func (b *Builder) VetAction(mode BuildMode, depMode BuildMode, p *load.Package) *Action

WithAction method #

WithAction returns a Shell identical to sh, but bound to Action a.

func (sh *Shell) WithAction(a *Action) *Shell

WriteCoverMetaFilesFile function #

WriteCoverMetaFilesFile writes out a summary file ("meta-files file") as part of the action function for the "writeCoverMeta" pseudo action employed during "go test -coverpkg" runs where there are multiple tests and multiple packages covered. It builds up a table mapping package import path to meta-data file fragment and writes it out to a file where it can be read by the various test run actions. Note that this function has to be called A) after the build actions are complete for all packages being tested, and B) before any of the "run test" actions for those packages happen. This requirement is enforced by adding making this action ("a") dependent on all test package build actions, and making all test run actions dependent on this action.

func WriteCoverMetaFilesFile(b *Builder, ctx context.Context, a *Action) error

WriteCoveragePercent function #

WriteCoveragePercent writes out to the writer 'w' a "percent statements covered" for the package whose test-run action is 'runAct', based on the meta-data file 'mf'. This helper is used in cases where a user runs "go test -cover" on a package that has functions but no tests; in the normal case (package has tests) the percentage is written by the test binary when it runs.

func WriteCoveragePercent(b *Builder, runAct *Action, mf string, w io.Writer) error

WriteCoverageProfile function #

WriteCoverageProfile writes out a coverage profile fragment for the package whose test-run action is 'runAct'; content is written to the file 'outf' based on the coverage meta-data info found in 'mf'. This helper is used in cases where a user runs "go test -cover" on a package that has functions but no tests.

func WriteCoverageProfile(b *Builder, runAct *Action, mf string, outf string, w io.Writer) error

actionGraphJSON function #

func actionGraphJSON(a *Action) string

actionID function #

actionID returns the action ID half of a build ID.

func actionID(buildID string) string

actionList function #

actionList returns the list of actions in the dag rooted at root as visited in a depth-first post-order traversal.

func actionList(root *Action) []*Action

actualFiles function #

actualFiles applies fsys.Actual to the list of files.

func actualFiles(files []string) []string

addInstallHeaderAction method #

addInstallHeaderAction adds an install header action to a, if needed. The action a should be an install action as generated by either b.CompileAction or b.LinkAction with mode=ModeInstall, and so a.Deps[0] is the corresponding build action.

func (b *Builder) addInstallHeaderAction(a *Action)

addTransitiveLinkDeps method #

addTransitiveLinkDeps adds to the link action a all packages that are transitive dependencies of a1.Deps. That is, if a is a link of package main, a1 is the compile of package main and a1.Deps is the actions for building packages directly imported by package main (what the compiler needs). The linker needs all packages transitively imported by the whole program; addTransitiveLinkDeps makes sure those are present in a.Deps. If shlib is non-empty, then a corresponds to the build and installation of shlib, so any rebuild of shlib should not be added as a dependency.

func (b *Builder) addTransitiveLinkDeps(a *Action, a1 *Action, shlib string)

allowedVersion function #

allowedVersion reports whether the version v is an allowed version of go (one that we can compile). v is known to be of the form "1.23".

func allowedVersion(v string) bool

ar method #

func (gccgoToolchain) ar() []string

asm method #

func (tools gccgoToolchain) asm(b *Builder, a *Action, sfiles []string) ([]string, error)

asm method #

func (noToolchain) asm(b *Builder, a *Action, sfiles []string) ([]string, error)

asm method #

func (gcToolchain) asm(b *Builder, a *Action, sfiles []string) ([]string, error)

asmArgs function #

func asmArgs(a *Action, p *load.Package) []any

assemblerIsGas function #

Check if assembler used by gccgo is GNU as.

func assemblerIsGas() bool

build method #

build is the action for building a single package. Note that any new influence on this logic must be reported in b.buildActionID above as well.

func (b *Builder) build(ctx context.Context, a *Action) (err error)

buildActionID method #

buildActionID computes the action ID for a build action.

func (b *Builder) buildActionID(a *Action) cache.ActionID

buildFlags function #

func buildFlags(name string, defaults string, fromPackage []string, check func(string, string, []string) error) ([]string, error)

buildID method #

buildID returns the build ID found in the given file. If no build ID is found, buildID returns the content hash of the file.

func (b *Builder) buildID(file string) string

buildModeInit function #

func buildModeInit()

buildVetConfig function #

func buildVetConfig(a *Action, srcfiles []string)

buildmodeShared method #

buildmodeShared takes the "go build" action a1 into the building of a shared library of a1.Deps. That is, the input a1 represents "go build pkgs" and the result represents "go build -buildmode=shared pkgs".

func (b *Builder) buildmodeShared(mode BuildMode, depMode BuildMode, args []string, pkgs []*load.Package, a1 *Action) *Action

cCompilerEnv method #

cCompilerEnv returns environment variables to set when running the C compiler. This is needed to disable escape codes in clang error messages that confuse tools like cgo.

func (b *Builder) cCompilerEnv() []string

cacheAction method #

cacheAction looks up {mode, p} in the cache and returns the resulting action. If the cache has no such action, f() is recorded and returned. TODO(rsc): Change the second key from *load.Package to interface{}, to make the caching in linkShared less awkward?

func (b *Builder) cacheAction(mode string, p *load.Package, f func() *Action) *Action

cacheCgoHdr method #

func (b *Builder) cacheCgoHdr(a *Action)

cacheObjdirFile method #

func (b *Builder) cacheObjdirFile(a *Action, c cache.Cache, name string) error

cacheSrcFiles method #

func (b *Builder) cacheSrcFiles(a *Action, srcfiles []string)

cc method #

func (gcToolchain) cc(b *Builder, a *Action, ofile string, cfile string) error

cc method #

func (tools gccgoToolchain) cc(b *Builder, a *Action, ofile string, cfile string) error

cc method #

func (noToolchain) cc(b *Builder, a *Action, ofile string, cfile string) error

ccExe method #

ccExe returns the CC compiler setting without all the extra flags we add implicitly.

func (b *Builder) ccExe() []string

ccompile method #

ccompile runs the given C or C++ compiler and creates an object from a single source file.

func (b *Builder) ccompile(a *Action, outfile string, flags []string, file string, compiler []string) error

cgo method #

func (b *Builder) cgo(a *Action, cgoExe string, objdir string, pcCFLAGS []string, pcLDFLAGS []string, cgofiles []string, gccfiles []string, gxxfiles []string, mfiles []string, ffiles []string) (outGo []string, outObj []string, err error)

checkCompilerFlags function #

func checkCompilerFlags(name string, source string, list []string) error

checkDirectives method #

func (b *Builder) checkDirectives(a *Action) error

checkFlags function #

func checkFlags(name string, source string, list []string, invalid []*lazyregexp.Regexp, valid []*lazyregexp.Regexp, validNext []string, checkOverrides bool) error

checkGccgoBin function #

func checkGccgoBin()

checkLinkerFlags function #

func checkLinkerFlags(name string, source string, list []string) error

cleanup method #

cleanup removes a's object dir to keep the amount of on-disk garbage down in a large build. On an operating system with aggressive buffering, cleaning incrementally like this keeps the intermediate objects from hitting the disk.

func (b *Builder) cleanup(a *Action)

closeBuilders function #

func closeBuilders()

compiler method #

func (gcToolchain) compiler() string

compiler method #

func (gccgoToolchain) compiler() string

compiler method #

func (noToolchain) compiler() string

compilerCmd method #

compilerCmd returns a command line prefix for the given environment variable and using the default command when the variable is empty.

func (b *Builder) compilerCmd(compiler []string, incdir string, workdir string) []string

compilerRequiredAsanVersion function #

compilerRequiredAsanVersion is a copy of the function defined in cmd/cgo/internal/testsanitizers/cc_test.go compilerRequiredAsanVersion reports whether the compiler is the version required by Asan.

func compilerRequiredAsanVersion() error

compilerVersion function #

compilerVersion detects the version of $(go env CC). It returns a non-nil error if the compiler matches a known version schema but the version could not be parsed, or if $(go env CC) could not be determined.

func compilerVersion() (version, error)

contentID function #

contentID returns the content ID half of a build ID.

func contentID(buildID string) string

cover method #

cover runs, in effect, go tool cover -mode=b.coverMode -var="varName" -o dst.go src.go

func (b *Builder) cover(a *Action, dst string, src string, varName string) error

cover2 method #

cover2 runs, in effect, go tool cover -pkgcfg= -mode=b.coverMode -var="varName" -o Return value is an updated output files list; in addition to the regular outputs (instrumented source files) the cover tool also writes a separate file (appearing first in the list of outputs) that will contain coverage counters and meta-data.

func (b *Builder) cover2(a *Action, infiles []string, outfiles []string, varName string, mode string) ([]string, error)

cxxExe method #

cxxExe returns the CXX compiler setting without all the extra flags we add implicitly.

func (b *Builder) cxxExe() []string

disableBuildID method #

disableBuildID adjusts a linker command line to avoid creating a build ID when creating an object file rather than an executable or shared library. Some systems, such as Ubuntu, always add --build-id to every link, but we don't want a build ID when we are producing an object file. On some of those system a plain -r (not -Wl,-r) will turn off --build-id, but clang 3.0 doesn't support a plain -r. I don't know how to turn off --build-id when using clang other than passing a trailing --build-id=none. So that is what we do, but only on systems likely to support it, which is to say, systems that normally use gold or the GNU linker.

func (b *Builder) disableBuildID(ldflags []string) []string

dynimport method #

dynimport creates a Go source file named importGo containing //go:cgo_import_dynamic directives for each symbol or library dynamically imported by the object files outObj. dynOutGo, if not empty, is a new Go file to build as part of the package. dynOutObj, if not empty, is a new file to add to the generated archive.

func (b *Builder) dynimport(a *Action, objdir string, importGo string, cgoExe string, cflags []string, cgoLDFLAGS []string, outObj []string) (dynOutGo string, dynOutObj string, err error)

encodeArg function #

encodeArg encodes an argument for response file writing.

func encodeArg(arg string) string

envList function #

envList returns the value of the given environment variable broken into fields, using the default value when the variable is empty. The environment variable must be quoted correctly for quoted.Split. This should be done before building anything, for example, in BuildInit.

func envList(key string, def string) []string

fcExe method #

fcExe returns the FC compiler setting without all the extra flags we add implicitly.

func (b *Builder) fcExe() []string

fileExtSplit function #

fileExtSplit expects a filename and returns the name and ext (without the dot). If the file has no extension, ext will be empty.

func fileExtSplit(file string) (name string, ext string)

fileHash method #

fileHash returns the content hash of the named file.

func (b *Builder) fileHash(file string) string

findCachedObjdirFile method #

func (b *Builder) findCachedObjdirFile(a *Action, c cache.Cache, name string) (string, error)

flagsNotCompatibleWithInternalLinking function #

flagsNotCompatibleWithInternalLinking scans the list of cgo compiler flags (C/C++/Fortran) looking for flags that might cause problems if the build in question uses internal linking. The primary culprits are use of plugins or use of LTO, but we err on the side of caution, supporting only those flags that are on the allow-list for safe flags from security perspective. Return is TRUE if a sensitive flag is found, FALSE otherwise.

func flagsNotCompatibleWithInternalLinking(sourceList []string, flagListList [][]string) bool

flushOutput method #

flushOutput flushes the output being queued in a.

func (b *Builder) flushOutput(a *Action)

fmtCmd method #

fmtCmd formats a command in the manner of fmt.Sprintf but also: fmtCmd replaces the value of b.WorkDir with $WORK.

func (sh *Shell) fmtCmd(dir string, format string, args ...any) string

fuzzInstrumentFlags function #

fuzzInstrumentFlags returns compiler flags that enable fuzzing instrumentation on supported platforms. On unsupported platforms, fuzzInstrumentFlags returns nil, meaning no instrumentation is added. 'go test -fuzz' still works without coverage, but it generates random inputs without guidance, so it's much less effective.

func fuzzInstrumentFlags() []string

gc method #

func (noToolchain) gc(b *Builder, a *Action, archive string, importcfg []byte, embedcfg []byte, symabis string, asmhdr bool, pgoProfile string, gofiles []string) (ofile string, out []byte, err error)

gc method #

func (gcToolchain) gc(b *Builder, a *Action, archive string, importcfg []byte, embedcfg []byte, symabis string, asmhdr bool, pgoProfile string, gofiles []string) (ofile string, output []byte, err error)

gc method #

func (tools gccgoToolchain) gc(b *Builder, a *Action, archive string, importcfg []byte, embedcfg []byte, symabis string, asmhdr bool, pgoProfile string, gofiles []string) (ofile string, output []byte, err error)

gcBackendConcurrency function #

gcBackendConcurrency returns the backend compiler concurrency level for a package compilation.

func gcBackendConcurrency(gcflags []string) int

gcc method #

gcc runs the gcc C compiler to create an object from a single C file.

func (b *Builder) gcc(a *Action, workdir string, out string, flags []string, cfile string) error

gccArchArgs method #

gccArchArgs returns arguments to pass to gcc based on the architecture.

func (b *Builder) gccArchArgs() []string

gccCompilerID method #

gccCompilerID returns a build cache key for the current gcc, as identified by running 'compiler'. The caller can use subkeys of the key. Other parts of cmd/go can use the id as a hash of the installed compiler version.

func (b *Builder) gccCompilerID(compiler string) (id cache.ActionID, ok bool)

gccNoPie method #

gccNoPie returns the flag to use to request non-PIE. On systems with PIE (position independent executables) enabled by default, -no-pie must be passed when doing a partial link with -Wl,-r. But -no-pie is not supported by all compilers, and clang spells it -nopie.

func (b *Builder) gccNoPie(linker []string) string

gccSupportsFlag method #

gccSupportsFlag checks to see if the compiler supports a flag.

func (b *Builder) gccSupportsFlag(compiler []string, flag string) bool

gccToolID method #

gccToolID returns the unique ID to use for a tool that is invoked by the GCC driver. This is used particularly for gccgo, but this can also be used for gcc, g++, gfortran, etc.; those tools all use the GCC driver under different names. The approach used here should also work for sufficiently new versions of clang. Unlike toolID, the name argument is the program to run. The language argument is the type of input file as passed to the GCC driver's -x option. For these tools we have no -V=full option to dump the build ID, but we can run the tool with -v -### to reliably get the compiler proper and hash that. That will work in the presence of -toolexec. In order to get reproducible builds for released compilers, we detect a released compiler by the absence of "experimental" in the --version output, and in that case we just use the version string. gccToolID also returns the underlying executable for the compiler. The caller assumes that stat of the exe can be used, combined with the id, to detect changes in the underlying compiler. The returned exe can be empty, which means to rely only on the id.

func (b *Builder) gccToolID(name string, language string) (id string, exe string, err error)

gccgoArchive function #

func gccgoArchive(basedir string, imp string) string

gccgoBuildIDFile method #

gccgoBuildIDFile creates an assembler file that records the action's build ID in an SHF_EXCLUDE section for ELF files or in a CSECT in XCOFF files.

func (b *Builder) gccgoBuildIDFile(a *Action) (string, error)

gccgoCleanPkgpath method #

func (tools gccgoToolchain) gccgoCleanPkgpath(b *Builder, p *load.Package) string

gccgoPkgpath function #

func gccgoPkgpath(p *load.Package) string

gccld method #

gccld runs the gcc linker to create an executable from a set of object files.

func (b *Builder) gccld(a *Action, objdir string, outfile string, flags []string, objs []string) error

getPkgConfigFlags method #

Calls pkg-config if needed and returns the cflags/ldflags needed to build a's package.

func (b *Builder) getPkgConfigFlags(a *Action) (cflags []string, ldflags []string, err error)

gfortran method #

gfortran runs the gfortran Fortran compiler to create an object from a single Fortran file.

func (b *Builder) gfortran(a *Action, workdir string, out string, flags []string, ffile string) error

gfortranCmd method #

gfortranCmd returns a gfortran command line prefix.

func (b *Builder) gfortranCmd(incdir string, workdir string) []string

gxx method #

gxx runs the g++ C++ compiler to create an object from a single C++ file.

func (b *Builder) gxx(a *Action, workdir string, out string, flags []string, cxxfile string) error

init function #

func init()

init function #

func init()

init function #

func init()

installAction method #

installAction returns the action for installing the result of a1.

func (b *Builder) installAction(a1 *Action, mode BuildMode) *Action

installHeader method #

Install the cgo export header file, if there is one.

func (b *Builder) installHeader(ctx context.Context, a *Action) error

installOutsideModule function #

installOutsideModule implements 'go install pkg@version'. It builds and installs one or more main packages in module mode while ignoring any go.mod in the current directory or parent directories. See golang.org/issue/40276 for details and rationale.

func installOutsideModule(ctx context.Context, args []string)

installShlibname method #

func (b *Builder) installShlibname(ctx context.Context, a *Action) error

instrumentInit function #

func instrumentInit()

isObject function #

func isObject(s string) bool

joinUnambiguously function #

joinUnambiguously prints the slice, quoting where necessary to make the output unambiguous. TODO: See issue 5279. The printing of commands needs a complete redo.

func joinUnambiguously(a []string) string

ld method #

func (tools gccgoToolchain) ld(b *Builder, root *Action, targetPath string, importcfg string, mainpkg string) error

ld method #

func (noToolchain) ld(b *Builder, root *Action, targetPath string, importcfg string, mainpkg string) error

ld method #

func (gcToolchain) ld(b *Builder, root *Action, targetPath string, importcfg string, mainpkg string) error

ldShared method #

func (noToolchain) ldShared(b *Builder, root *Action, toplevelactions []*Action, targetPath string, importcfg string, allactions []*Action) error

ldShared method #

func (gcToolchain) ldShared(b *Builder, root *Action, toplevelactions []*Action, targetPath string, importcfg string, allactions []*Action) error

ldShared method #

func (tools gccgoToolchain) ldShared(b *Builder, root *Action, toplevelactions []*Action, targetPath string, importcfg string, allactions []*Action) error

libname function #

libname returns the filename to use for the shared library when using -buildmode=shared. The rules we use are: Use arguments for special 'meta' packages: std --> libstd.so std cmd --> libstd,cmd.so A single non-meta argument with trailing "/..." is special cased: foo/... --> libfoo.so (A relative path like "./..." expands the "." first) Use import paths for other cases, changing '/' to '-': somelib --> libsubdir-somelib.so ./ or ../ --> libsubdir-somelib.so gopkg.in/tomb.v2 -> libgopkg.in-tomb.v2.so a/... b/... ---> liba/c,b/d.so - all matching import paths Name parts are joined with ','.

func libname(args []string, pkgs []*load.Package) (string, error)

linkActionID method #

linkActionID computes the action ID for a link action.

func (b *Builder) linkActionID(a *Action) cache.ActionID

linkShared method #

func (b *Builder) linkShared(ctx context.Context, a *Action) (err error)

linkSharedAction method #

linkSharedAction takes a grouping action a1 corresponding to a list of built packages and returns an action that links them together into a shared library with the name shlib. If a1 is nil, shlib should be an absolute path to an existing shared library, and then linkSharedAction reads that library to find out the package list.

func (b *Builder) linkSharedAction(mode BuildMode, depMode BuildMode, shlib string, a1 *Action) *Action

linkSharedActionID method #

func (b *Builder) linkSharedActionID(a *Action) cache.ActionID

linker method #

func (gccgoToolchain) linker() string

linker method #

func (gcToolchain) linker() string

linker method #

func (noToolchain) linker() string

loadCachedCgoHdr method #

func (b *Builder) loadCachedCgoHdr(a *Action) error

loadCachedCompiledGoFiles method #

func (b *Builder) loadCachedCompiledGoFiles(a *Action) error

loadCachedObjdirFile method #

func (b *Builder) loadCachedObjdirFile(a *Action, c cache.Cache, name string) error

loadCachedVet method #

func (b *Builder) loadCachedVet(a *Action) error

maybePIC method #

maybePIC adds -fPIC to the list of arguments if needed.

func (tools gccgoToolchain) maybePIC(args []string) []string

mayberemovefile function #

mayberemovefile removes a file only if it is a regular file When running as a user with sufficient privileges, we may delete even device files, for example, which is not intended.

func mayberemovefile(s string)

mkAbs function #

mkAbs returns an absolute path corresponding to evaluating f in the directory dir. We always pass absolute paths of source files so that the error messages will include the full path to a file in need of attention.

func mkAbs(dir string, f string) string

mkAbsFiles function #

mkAbsFiles converts files into a list of absolute files, assuming they were originally relative to dir, and returns that new list.

func mkAbsFiles(dir string, files []string) []string

moveOrCopyFile method #

moveOrCopyFile is like 'mv src dst' or 'cp src dst'.

func (sh *Shell) moveOrCopyFile(dst string, src string, perm fs.FileMode, force bool) error

needCgoHdr method #

needCgoHdr reports whether the actions triggered by this one expect to be able to access the cgo-generated header file.

func (b *Builder) needCgoHdr(a *Action) bool

newBuildActor function #

newBuildActor returns a new buildActor object, setting up the covMetaFileName field if 'genCoverMeta' flag is set.

func newBuildActor(p *load.Package, genCoverMeta bool) *buildActor

noCompiler function #

func noCompiler() error

omitTestOnly function #

omitTestOnly returns pkgs with test-only packages removed.

func omitTestOnly(pkgs []*load.Package) []*load.Package

oneMainPkg function #

func oneMainPkg(pkgs []*load.Package) []*load.Package

pack method #

func (gcToolchain) pack(b *Builder, a *Action, afile string, ofiles []string) error

pack method #

func (tools gccgoToolchain) pack(b *Builder, a *Action, afile string, ofiles []string) error

pack method #

func (noToolchain) pack(b *Builder, a *Action, afile string, ofiles []string) error

packInternal function #

func packInternal(afile string, ofiles []string) error

passLongArgsInResponseFiles function #

passLongArgsInResponseFiles modifies cmd such that, for certain programs, long arguments are passed in "response files", a file on disk with the arguments, with one arg per line. An actual argument starting with '@' means that the rest of the argument is a filename of arguments to expand. See issues 18468 (Windows) and 37768 (Darwin).

func passLongArgsInResponseFiles(cmd *exec.Cmd) (cleanup func())

pgoActionID method #

pgoActionID computes the action ID for a preprocess PGO action.

func (b *Builder) pgoActionID(input string) cache.ActionID

pkg method #

func (sh *Shell) pkg() *load.Package

pkgPath function #

func pkgPath(a *Action) string

pkgsMain function #

func pkgsMain(pkgs []*load.Package) (res []*load.Package)

pkgsNotMain function #

func pkgsNotMain(pkgs []*load.Package) (res []*load.Package)

pluginPath function #

pluginPath computes the package path for a plugin main package. This is typically the import path of the main package p, unless the plugin is being built directly from source files. In that case we combine the package build ID with the contents of the main package source files. This allows us to identify two different plugins built from two source files with the same name.

func pluginPath(a *Action) string

pop method #

func (q *actionQueue) pop() *Action

printLinkerConfig method #

printLinkerConfig prints the linker config into the hash h, as part of the computation of a linker-related action ID.

func (b *Builder) printLinkerConfig(h io.Writer, p *load.Package)

printfLocked method #

func (sh *Shell) printfLocked(format string, a ...any)

push method #

func (q *actionQueue) push(a *Action)

readpkglist function #

readpkglist returns the list of packages that were built into the shared library at shlibpath. For the native toolchain this list is stored, newline separated, in an ELF note with name "Go\x00\x00" and type 1. For GCCGO it is extracted from the .go_export section.

func readpkglist(shlibpath string) (pkgs []*load.Package)

replacePrefix function #

replacePrefix is like strings.ReplaceAll, but only replaces instances of old that are preceded by ' ', '\t', or appear at the beginning of a line.

func replacePrefix(s string, old string, new string) string

reportCmd method #

reportCmd reports the output and exit status of a command. The cmdOut and cmdErr arguments are the output and exit error of the command, respectively. The exact reporting behavior is as follows: cmdOut cmdErr Result "" nil print nothing, return nil !="" nil print output, return nil "" !=nil print nothing, return cmdErr (later printed) !="" !=nil print nothing, ignore err, return output as error (later printed) reportCmd returns a non-nil error if and only if cmdErr != nil. It assumes that the command output, if non-empty, is more detailed than the command error (which is usually just an exit status), so prefers using the output as the ultimate error. Typically, the caller should return this error from an Action, which it will be printed by the Builder. reportCmd formats the output as "# desc" followed by the given output. The output is expected to contain references to 'dir', usually the source directory for the package that has failed to build. reportCmd rewrites mentions of dir with a relative path to dir when the relative path is shorter. This is usually more pleasant. For example, if fmt doesn't compile and we are in src/html, the output is $ go build # fmt ../fmt/print.go:1090: undefined: asdf $ instead of $ go build # fmt /usr/gopher/go/src/fmt/print.go:1090: undefined: asdf $ reportCmd also replaces references to the work directory with $WORK, replaces cgo file paths with the original file path, and replaces cgo-mangled names with "C.name". desc is optional. If "", a.Package.Desc() is used. dir is optional. If "", a.Package.Dir is used.

func (sh *Shell) reportCmd(desc string, dir string, cmdOut []byte, cmdErr error) error

run method #

run runs the command given by cmdline in the directory dir. If the command fails, run prints information about the failure and returns a non-nil error.

func (sh *Shell) run(dir string, desc string, env []string, cmdargs ...any) error

runBuild function #

func runBuild(ctx context.Context, cmd *base.Command, args []string)

runInstall function #

func runInstall(ctx context.Context, cmd *base.Command, args []string)

runOut method #

runOut runs the command given by cmdline in the directory dir. It returns the command output and any errors that occurred. It accumulates execution time in a.

func (sh *Shell) runOut(dir string, env []string, cmdargs ...any) ([]byte, error)

setextld function #

setextld sets the appropriate linker flags for the specified compiler.

func setextld(ldflags []string, compiler []string) ([]string, error)

showStdout function #

func showStdout(b *Builder, c cache.Cache, a *Action, key string) error

splitPkgConfigOutput function #

splitPkgConfigOutput parses the pkg-config output into a slice of flags. This implements the shell quoting semantics described in https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_02, except that it does not support parameter or arithmetic expansion or command substitution and hard-codes the delimiters instead of reading them from LC_LOCALE.

func splitPkgConfigOutput(out []byte) ([]string, error)

statString function #

statString returns a string form of an os.FileInfo, for serializing and comparison.

func statString(info os.FileInfo) string

supportsCgoIncomplete method #

supportsCgoIncomplete reports whether the gccgo/GoLLVM compiler being used supports cgo.Incomplete, which was added in GCC 13. This takes an Action only for output reporting purposes. The result value is unrelated to the Action.

func (tools gccgoToolchain) supportsCgoIncomplete(b *Builder, a *Action) bool

swig method #

Run SWIG on all SWIG input files. TODO: Don't build a shared library, once SWIG emits the necessary pragmas for external linking.

func (b *Builder) swig(a *Action, objdir string, pcCFLAGS []string) (outGo []string, outC []string, outCXX []string, err error)

swigDoIntSize method #

Determine the size of int on the target system for the -intgosize option of swig >= 2.0.9. Run only once.

func (b *Builder) swigDoIntSize(objdir string) (intsize string, err error)

swigDoVersionCheck method #

func (b *Builder) swigDoVersionCheck() error

swigIntSize method #

Determine the size of int on the target system for the -intgosize option of swig >= 2.0.9.

func (b *Builder) swigIntSize(objdir string) (intsize string, err error)

swigOne method #

Run SWIG on one SWIG input file.

func (b *Builder) swigOne(a *Action, file string, objdir string, pcCFLAGS []string, cxx bool, intgosize string) (outGo string, outC string, err error)

swigVersionCheck method #

func (b *Builder) swigVersionCheck() error

symabis method #

func (gcToolchain) symabis(b *Builder, a *Action, sfiles []string) (string, error)

symabis method #

func (gccgoToolchain) symabis(b *Builder, a *Action, sfiles []string) (string, error)

symabis method #

func (noToolchain) symabis(b *Builder, a *Action, sfiles []string) (string, error)

toolID method #

toolID returns the unique ID to use for the current copy of the named tool (asm, compile, cover, link). It is important that if the tool changes (for example a compiler bug is fixed and the compiler reinstalled), toolID returns a different string, so that old package archives look stale and are rebuilt (with the fixed compiler). This suggests using a content hash of the tool binary, as stored in the build ID. Unfortunately, we can't just open the tool binary, because the tool might be invoked via a wrapper program specified by -toolexec and we don't know what the wrapper program does. In particular, we want "-toolexec toolstash" to continue working: it does no good if "-toolexec toolstash" is executing a stashed copy of the compiler but the go command is acting as if it will run the standard copy of the compiler. The solution is to ask the tool binary to tell us its own build ID using the "-V=full" flag now supported by all tools. Then we know we're getting the build ID of the compiler that will actually run during the build. (How does the compiler binary know its own content hash? We store it there using updateBuildID after the standard link step.) A final twist is that we'd prefer to have reproducible builds for release toolchains. It should be possible to cross-compile for Windows from either Linux or Mac or Windows itself and produce the same binaries, bit for bit. If the tool ID, which influences the action ID half of the build ID, is based on the content ID, then the Linux compiler binary and Mac compiler binary will have different tool IDs and therefore produce executables with different action IDs. To avoid this problem, for releases we use the release version string instead of the compiler binary's content hash. This assumes that all compilers built on all different systems are semantically equivalent, which is of course only true modulo bugs. (Producing the exact same executables also requires that the different build setups agree on details like $GOROOT and file name paths, but at least the tool IDs do not make it impossible.)

func (b *Builder) toolID(name string) string

toolVerify function #

toolVerify checks that the command line args writes the same output file if run using newTool instead. Unused now but kept around for future use.

func toolVerify(a *Action, b *Builder, p *load.Package, newTool string, ofile string, args []any) error

trimpath method #

trimpath returns the -trimpath argument to use when compiling the action.

func (a *Action) trimpath() string

updateBuildID method #

updateBuildID updates the build ID in the target written by action a. It requires that useCache was called for action a and returned false, and that the build was then carried out and given the temporary a.buildID to record as the build ID in the resulting package or binary. updateBuildID computes the final content ID and updates the build IDs in the binary. Keep in sync with src/cmd/buildid/buildid.go

func (b *Builder) updateBuildID(a *Action, target string) error

useCache method #

useCache tries to satisfy the action a, which has action ID actionHash, by using a cached result from an earlier build. If useCache decides that the cache can be used, it sets a.buildID and a.built for use by parent actions and then returns true. Otherwise it sets a.buildID to a temporary build ID for use in the build and returns false. When useCache returns false the expectation is that the caller will build the target and then call updateBuildID to finish the build ID computation. When useCache returns false, it may have initiated buffering of output during a's work. The caller should defer b.flushOutput(a), to make sure that flushOutput is eventually called regardless of whether the action succeeds. The flushOutput call must happen after updateBuildID.

func (b *Builder) useCache(a *Action, actionHash cache.ActionID, target string, printOutput bool) (ok bool)

useResponseFile function #

func useResponseFile(path string, argLen int) bool

vet method #

func (b *Builder) vet(ctx context.Context, a *Action) error

vetAction method #

func (b *Builder) vetAction(mode BuildMode, depMode BuildMode, p *load.Package) *Action

writeCoverPkgInputs method #

func (b *Builder) writeCoverPkgInputs(a *Action, pconfigfile string, covoutputsfile string, outfiles []string) error

writeFile method #

writeFile writes the text to file.

func (sh *Shell) writeFile(file string, text []byte) error

writeLinkImportcfg method #

func (b *Builder) writeLinkImportcfg(a *Action, file string) error

Generated with Arrow