| 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 |
"bufio" |
| 9 |
"fmt" |
| 10 |
"internal/buildcfg" |
| 11 |
"internal/platform" |
| 12 |
"io" |
| 13 |
"os" |
| 14 |
"path/filepath" |
| 15 |
"runtime" |
| 16 |
"strings" |
| 17 |
"sync" |
| 18 |
|
| 19 |
"cmd/go/internal/base" |
| 20 |
"cmd/go/internal/cfg" |
| 21 |
"cmd/go/internal/fips140" |
| 22 |
"cmd/go/internal/fsys" |
| 23 |
"cmd/go/internal/gover" |
| 24 |
"cmd/go/internal/load" |
| 25 |
"cmd/go/internal/str" |
| 26 |
"cmd/internal/quoted" |
| 27 |
"crypto/sha1" |
| 28 |
) |
| 29 |
|
| 30 |
// Tests can override this by setting $TESTGO_TOOLCHAIN_VERSION. |
| 31 |
var ToolchainVersion = runtime.Version() |
| 32 |
|
| 33 |
// The Go toolchain. |
| 34 |
|
| 35 |
type gcToolchain struct{} |
| 36 |
|
| 37 |
func (gcToolchain) compiler() string { |
| 38 |
return base.Tool("compile") |
| 39 |
} |
| 40 |
|
| 41 |
func (gcToolchain) linker() string { |
| 42 |
return base.Tool("link") |
| 43 |
} |
| 44 |
|
| 45 |
func pkgPath(a *Action) string { |
| 46 |
p := a.Package |
| 47 |
ppath := p.ImportPath |
| 48 |
if cfg.BuildBuildmode == "plugin" { |
| 49 |
ppath = pluginPath(a) |
| 50 |
} else if p.Name == "main" && !p.Internal.ForceLibrary { |
| 51 |
ppath = "main" |
| 52 |
} |
| 53 |
return ppath |
| 54 |
} |
| 55 |
|
| 56 |
func (gcToolchain) gc(b *Builder, a *Action, archive string, importcfg, embedcfg []byte, symabis string, asmhdr bool, pgoProfile string, gofiles []string) (ofile string, output []byte, err error) { |
| 57 |
p := a.Package |
| 58 |
sh := b.Shell(a) |
| 59 |
objdir := a.Objdir |
| 60 |
if archive != "" { |
| 61 |
ofile = archive |
| 62 |
} else { |
| 63 |
out := "_go_.o" |
| 64 |
ofile = objdir + out |
| 65 |
} |
| 66 |
|
| 67 |
pkgpath := pkgPath(a) |
| 68 |
defaultGcFlags := []string{"-p", pkgpath} |
| 69 |
vers := gover.Local() |
| 70 |
if p.Module != nil { |
| 71 |
v := p.Module.GoVersion |
| 72 |
if v == "" { |
| 73 |
v = gover.DefaultGoModVersion |
| 74 |
} |
| 75 |
// TODO(samthanawalla): Investigate when allowedVersion is not true. |
| 76 |
if allowedVersion(v) { |
| 77 |
vers = v |
| 78 |
} |
| 79 |
} |
| 80 |
defaultGcFlags = append(defaultGcFlags, "-lang=go"+gover.Lang(vers)) |
| 81 |
if p.Standard { |
| 82 |
defaultGcFlags = append(defaultGcFlags, "-std") |
| 83 |
} |
| 84 |
|
| 85 |
// If we're giving the compiler the entire package (no C etc files), tell it that, |
| 86 |
// so that it can give good error messages about forward declarations. |
| 87 |
// Exceptions: a few standard packages have forward declarations for |
| 88 |
// pieces supplied behind-the-scenes by package runtime. |
| 89 |
extFiles := len(p.CgoFiles) + len(p.CFiles) + len(p.CXXFiles) + len(p.MFiles) + len(p.FFiles) + len(p.SFiles) + len(p.SysoFiles) + len(p.SwigFiles) + len(p.SwigCXXFiles) |
| 90 |
if p.Standard { |
| 91 |
switch p.ImportPath { |
| 92 |
case "bytes", "internal/poll", "net", "os": |
| 93 |
fallthrough |
| 94 |
case "runtime/metrics", "runtime/pprof", "runtime/trace": |
| 95 |
fallthrough |
| 96 |
case "sync", "syscall", "time": |
| 97 |
extFiles++ |
| 98 |
} |
| 99 |
} |
| 100 |
if extFiles == 0 { |
| 101 |
defaultGcFlags = append(defaultGcFlags, "-complete") |
| 102 |
} |
| 103 |
if cfg.BuildContext.InstallSuffix != "" { |
| 104 |
defaultGcFlags = append(defaultGcFlags, "-installsuffix", cfg.BuildContext.InstallSuffix) |
| 105 |
} |
| 106 |
if a.buildID != "" { |
| 107 |
defaultGcFlags = append(defaultGcFlags, "-buildid", a.buildID) |
| 108 |
} |
| 109 |
if p.Internal.OmitDebug || cfg.Goos == "plan9" || cfg.Goarch == "wasm" { |
| 110 |
defaultGcFlags = append(defaultGcFlags, "-dwarf=false") |
| 111 |
} |
| 112 |
if strings.HasPrefix(ToolchainVersion, "go1") && !strings.Contains(os.Args[0], "go_bootstrap") { |
| 113 |
defaultGcFlags = append(defaultGcFlags, "-goversion", ToolchainVersion) |
| 114 |
} |
| 115 |
if p.Internal.Cover.Cfg != "" { |
| 116 |
defaultGcFlags = append(defaultGcFlags, "-coveragecfg="+p.Internal.Cover.Cfg) |
| 117 |
} |
| 118 |
if pgoProfile != "" { |
| 119 |
defaultGcFlags = append(defaultGcFlags, "-pgoprofile="+pgoProfile) |
| 120 |
} |
| 121 |
if symabis != "" { |
| 122 |
defaultGcFlags = append(defaultGcFlags, "-symabis", symabis) |
| 123 |
} |
| 124 |
|
| 125 |
gcflags := str.StringList(forcedGcflags, p.Internal.Gcflags) |
| 126 |
if p.Internal.FuzzInstrument { |
| 127 |
gcflags = append(gcflags, fuzzInstrumentFlags()...) |
| 128 |
} |
| 129 |
// Add -c=N to use concurrent backend compilation, if possible. |
| 130 |
c, release := compilerConcurrency() |
| 131 |
defer release() |
| 132 |
if c > 1 { |
| 133 |
defaultGcFlags = append(defaultGcFlags, fmt.Sprintf("-c=%d", c)) |
| 134 |
} |
| 135 |
|
| 136 |
args := []any{cfg.BuildToolexec, base.Tool("compile"), "-o", ofile, "-trimpath", a.trimpath(), defaultGcFlags, gcflags} |
| 137 |
if p.Internal.LocalPrefix == "" { |
| 138 |
args = append(args, "-nolocalimports") |
| 139 |
} else { |
| 140 |
args = append(args, "-D", p.Internal.LocalPrefix) |
| 141 |
} |
| 142 |
if importcfg != nil { |
| 143 |
if err := sh.writeFile(objdir+"importcfg", importcfg); err != nil { |
| 144 |
return "", nil, err |
| 145 |
} |
| 146 |
args = append(args, "-importcfg", objdir+"importcfg") |
| 147 |
} |
| 148 |
if embedcfg != nil { |
| 149 |
if err := sh.writeFile(objdir+"embedcfg", embedcfg); err != nil { |
| 150 |
return "", nil, err |
| 151 |
} |
| 152 |
args = append(args, "-embedcfg", objdir+"embedcfg") |
| 153 |
} |
| 154 |
if ofile == archive { |
| 155 |
args = append(args, "-pack") |
| 156 |
} |
| 157 |
if asmhdr { |
| 158 |
args = append(args, "-asmhdr", objdir+"go_asm.h") |
| 159 |
} |
| 160 |
|
| 161 |
for _, f := range gofiles { |
| 162 |
f := mkAbs(p.Dir, f) |
| 163 |
|
| 164 |
// Handle overlays. Convert path names using fsys.Actual |
| 165 |
// so these paths can be handed directly to tools. |
| 166 |
// Deleted files won't show up in when scanning directories earlier, |
| 167 |
// so Actual will never return "" (meaning a deleted file) here. |
| 168 |
// TODO(#39958): Handle cases where the package directory |
| 169 |
// doesn't exist on disk (this can happen when all the package's |
| 170 |
// files are in an overlay): the code expects the package directory |
| 171 |
// to exist and runs some tools in that directory. |
| 172 |
// TODO(#39958): Process the overlays when the |
| 173 |
// gofiles, cgofiles, cfiles, sfiles, and cxxfiles variables are |
| 174 |
// created in (*Builder).build. Doing that requires rewriting the |
| 175 |
// code that uses those values to expect absolute paths. |
| 176 |
args = append(args, fsys.Actual(f)) |
| 177 |
} |
| 178 |
output, err = sh.runOut(base.Cwd(), cfgChangedEnv, args...) |
| 179 |
return ofile, output, err |
| 180 |
} |
| 181 |
|
| 182 |
// compilerConcurrency returns the compiler concurrency level for a package compilation. |
| 183 |
// The returned function must be called after the compile finishes. |
| 184 |
func compilerConcurrency() (int, func()) { |
| 185 |
// Decide how many concurrent backend compilations to allow. |
| 186 |
// |
| 187 |
// If we allow too many, in theory we might end up with p concurrent processes, |
| 188 |
// each with c concurrent backend compiles, all fighting over the same resources. |
| 189 |
// However, in practice, that seems not to happen too much. |
| 190 |
// Most build graphs are surprisingly serial, so p==1 for much of the build. |
| 191 |
// Furthermore, concurrent backend compilation is only enabled for a part |
| 192 |
// of the overall compiler execution, so c==1 for much of the build. |
| 193 |
// So don't worry too much about that interaction for now. |
| 194 |
// |
| 195 |
// But to keep things reasonable, we maintain a cap on the total number of |
| 196 |
// concurrent backend compiles. (If we gave each compile action the full GOMAXPROCS, we could |
| 197 |
// potentially have GOMAXPROCS^2 running compile goroutines) In the past, we'd limit |
| 198 |
// the number of concurrent backend compiles per process to 4, which would result in a worst-case number |
| 199 |
// of backend compiles of 4*cfg.BuildP. Because some compile processes benefit from having |
| 200 |
// a larger number of compiles, especially when the compile action is the only |
| 201 |
// action running, we'll allow the max value to be larger, but ensure that the |
| 202 |
// total number of backend compiles never exceeds that previous worst-case number. |
| 203 |
// This is implemented using a pool of tokens that are given out. We'll set aside enough |
| 204 |
// tokens to make sure we don't run out, and then give half of the remaining tokens (up to |
| 205 |
// GOMAXPROCS) to each compile action that requests it. |
| 206 |
// |
| 207 |
// As a user, to limit parallelism, set GOMAXPROCS below numCPU; this may be useful |
| 208 |
// on a low-memory builder, or if a deterministic build order is required. |
| 209 |
if cfg.BuildP == 1 { |
| 210 |
// No process parallelism, do not cap compiler parallelism. |
| 211 |
return maxCompilerConcurrency, func() {} |
| 212 |
} |
| 213 |
|
| 214 |
// Cap compiler parallelism using the pool. |
| 215 |
tokensMu.Lock() |
| 216 |
defer tokensMu.Unlock() |
| 217 |
concurrentProcesses++ |
| 218 |
// Set aside tokens so that we don't run out if we were running cfg.BuildP concurrent compiles. |
| 219 |
// We'll set aside one token for each of the action goroutines that aren't currently running a compile. |
| 220 |
setAside := (cfg.BuildP - concurrentProcesses) * minTokens |
| 221 |
availableTokens := tokens - setAside |
| 222 |
// Grab half the remaining tokens: but with a floor of at least minTokens token, and |
| 223 |
// a ceiling of the max backend concurrency. |
| 224 |
c := max(min(availableTokens/2, maxCompilerConcurrency), minTokens) |
| 225 |
tokens -= c |
| 226 |
// Successfully grabbed the tokens. |
| 227 |
return c, func() { |
| 228 |
tokensMu.Lock() |
| 229 |
defer tokensMu.Unlock() |
| 230 |
concurrentProcesses-- |
| 231 |
tokens += c |
| 232 |
} |
| 233 |
} |
| 234 |
|
| 235 |
var maxCompilerConcurrency = runtime.GOMAXPROCS(0) // max value we will use for -c |
| 236 |
|
| 237 |
var ( |
| 238 |
tokensMu sync.Mutex |
| 239 |
totalTokens int // total number of tokens: this is used for checking that we get them all back in the end |
| 240 |
tokens int // number of available tokens |
| 241 |
concurrentProcesses int // number of currently running compiles |
| 242 |
minTokens int // minimum number of tokens to give out |
| 243 |
) |
| 244 |
|
| 245 |
// initCompilerConcurrencyPool sets the number of tokens in the pool. It needs |
| 246 |
// to be run after init, so that it can use the value of cfg.BuildP. |
| 247 |
func initCompilerConcurrencyPool() { |
| 248 |
// Size the pool to allow 2*maxCompilerConcurrency extra tokens to |
| 249 |
// be distributed amongst the compile actions in addition to the minimum |
| 250 |
// of min(4,GOMAXPROCS) tokens for each of the potentially cfg.BuildP |
| 251 |
// concurrently running compile actions. |
| 252 |
minTokens = min(4, maxCompilerConcurrency) |
| 253 |
tokens = 2*maxCompilerConcurrency + minTokens*cfg.BuildP |
| 254 |
totalTokens = tokens |
| 255 |
} |
| 256 |
|
| 257 |
// trimpath returns the -trimpath argument to use |
| 258 |
// when compiling the action. |
| 259 |
func (a *Action) trimpath() string { |
| 260 |
// Keep in sync with Builder.ccompile |
| 261 |
// The trimmed paths are a little different, but we need to trim in the |
| 262 |
// same situations. |
| 263 |
|
| 264 |
// Strip the object directory entirely. |
| 265 |
objdir := strings.TrimSuffix(a.Objdir, string(filepath.Separator)) |
| 266 |
rewrite := "" |
| 267 |
|
| 268 |
rewriteDir := a.Package.Dir |
| 269 |
if cfg.BuildTrimpath { |
| 270 |
importPath := a.Package.Internal.OrigImportPath |
| 271 |
if m := a.Package.Module; m != nil && m.Version != "" { |
| 272 |
rewriteDir = m.Path + "@" + m.Version + strings.TrimPrefix(importPath, m.Path) |
| 273 |
} else { |
| 274 |
rewriteDir = importPath |
| 275 |
} |
| 276 |
rewrite += a.Package.Dir + "=>" + rewriteDir + ";" |
| 277 |
} |
| 278 |
|
| 279 |
// Add rewrites for overlays. The 'from' and 'to' paths in overlays don't need to have |
| 280 |
// same basename, so go from the overlay contents file path (passed to the compiler) |
| 281 |
// to the path the disk path would be rewritten to. |
| 282 |
|
| 283 |
cgoFiles := make(map[string]bool) |
| 284 |
for _, f := range a.Package.CgoFiles { |
| 285 |
cgoFiles[f] = true |
| 286 |
} |
| 287 |
|
| 288 |
// TODO(matloob): Higher up in the stack, when the logic for deciding when to make copies |
| 289 |
// of c/c++/m/f/hfiles is consolidated, use the same logic that Build uses to determine |
| 290 |
// whether to create the copies in objdir to decide whether to rewrite objdir to the |
| 291 |
// package directory here. |
| 292 |
var overlayNonGoRewrites string // rewrites for non-go files |
| 293 |
hasCgoOverlay := false |
| 294 |
if fsys.OverlayFile != "" { |
| 295 |
for _, filename := range a.Package.AllFiles() { |
| 296 |
path := filename |
| 297 |
if !filepath.IsAbs(path) { |
| 298 |
path = filepath.Join(a.Package.Dir, path) |
| 299 |
} |
| 300 |
base := filepath.Base(path) |
| 301 |
isGo := strings.HasSuffix(filename, ".go") || strings.HasSuffix(filename, ".s") |
| 302 |
isCgo := cgoFiles[filename] || !isGo |
| 303 |
if fsys.Replaced(path) { |
| 304 |
if isCgo { |
| 305 |
hasCgoOverlay = true |
| 306 |
} else { |
| 307 |
rewrite += fsys.Actual(path) + "=>" + filepath.Join(rewriteDir, base) + ";" |
| 308 |
} |
| 309 |
} else if isCgo { |
| 310 |
// Generate rewrites for non-Go files copied to files in objdir. |
| 311 |
if filepath.Dir(path) == a.Package.Dir { |
| 312 |
// This is a file copied to objdir. |
| 313 |
overlayNonGoRewrites += filepath.Join(objdir, base) + "=>" + filepath.Join(rewriteDir, base) + ";" |
| 314 |
} |
| 315 |
} else { |
| 316 |
// Non-overlay Go files are covered by the a.Package.Dir rewrite rule above. |
| 317 |
} |
| 318 |
} |
| 319 |
} |
| 320 |
if hasCgoOverlay { |
| 321 |
rewrite += overlayNonGoRewrites |
| 322 |
} |
| 323 |
rewrite += objdir + "=>" |
| 324 |
|
| 325 |
return rewrite |
| 326 |
} |
| 327 |
|
| 328 |
func asmArgs(a *Action, p *load.Package) []any { |
| 329 |
// Add -I pkg/GOOS_GOARCH so #include "textflag.h" works in .s files. |
| 330 |
inc := filepath.Join(cfg.GOROOT, "pkg", "include") |
| 331 |
pkgpath := pkgPath(a) |
| 332 |
args := []any{cfg.BuildToolexec, base.Tool("asm"), "-p", pkgpath, "-trimpath", a.trimpath(), "-I", a.Objdir, "-I", inc, "-D", "GOOS_" + cfg.Goos, "-D", "GOARCH_" + cfg.Goarch, forcedAsmflags, p.Internal.Asmflags} |
| 333 |
if p.ImportPath == "runtime" && cfg.Goarch == "386" { |
| 334 |
for _, arg := range forcedAsmflags { |
| 335 |
if arg == "-dynlink" { |
| 336 |
args = append(args, "-D=GOBUILDMODE_shared=1") |
| 337 |
} |
| 338 |
} |
| 339 |
} |
| 340 |
|
| 341 |
if cfg.Goarch == "386" { |
| 342 |
// Define GO386_value from cfg.GO386. |
| 343 |
args = append(args, "-D", "GO386_"+cfg.GO386) |
| 344 |
} |
| 345 |
|
| 346 |
if cfg.Goarch == "amd64" { |
| 347 |
// Define GOAMD64_value from cfg.GOAMD64. |
| 348 |
args = append(args, "-D", "GOAMD64_"+cfg.GOAMD64) |
| 349 |
} |
| 350 |
|
| 351 |
if cfg.Goarch == "mips" || cfg.Goarch == "mipsle" { |
| 352 |
// Define GOMIPS_value from cfg.GOMIPS. |
| 353 |
args = append(args, "-D", "GOMIPS_"+cfg.GOMIPS) |
| 354 |
} |
| 355 |
|
| 356 |
if cfg.Goarch == "mips64" || cfg.Goarch == "mips64le" { |
| 357 |
// Define GOMIPS64_value from cfg.GOMIPS64. |
| 358 |
args = append(args, "-D", "GOMIPS64_"+cfg.GOMIPS64) |
| 359 |
} |
| 360 |
|
| 361 |
if cfg.Goarch == "ppc64" || cfg.Goarch == "ppc64le" { |
| 362 |
// Define GOPPC64_power8..N from cfg.PPC64. |
| 363 |
// We treat each powerpc version as a superset of functionality. |
| 364 |
switch cfg.GOPPC64 { |
| 365 |
case "power10": |
| 366 |
args = append(args, "-D", "GOPPC64_power10") |
| 367 |
fallthrough |
| 368 |
case "power9": |
| 369 |
args = append(args, "-D", "GOPPC64_power9") |
| 370 |
fallthrough |
| 371 |
default: // This should always be power8. |
| 372 |
args = append(args, "-D", "GOPPC64_power8") |
| 373 |
} |
| 374 |
} |
| 375 |
|
| 376 |
if cfg.Goarch == "riscv64" { |
| 377 |
// Define GORISCV64_value from cfg.GORISCV64. |
| 378 |
args = append(args, "-D", "GORISCV64_"+cfg.GORISCV64) |
| 379 |
} |
| 380 |
|
| 381 |
if cfg.Goarch == "arm" { |
| 382 |
// Define GOARM_value from cfg.GOARM, which can be either a version |
| 383 |
// like "6", or a version and a FP mode, like "7,hardfloat". |
| 384 |
switch { |
| 385 |
case strings.Contains(cfg.GOARM, "7"): |
| 386 |
args = append(args, "-D", "GOARM_7") |
| 387 |
fallthrough |
| 388 |
case strings.Contains(cfg.GOARM, "6"): |
| 389 |
args = append(args, "-D", "GOARM_6") |
| 390 |
fallthrough |
| 391 |
default: |
| 392 |
args = append(args, "-D", "GOARM_5") |
| 393 |
} |
| 394 |
} |
| 395 |
|
| 396 |
if cfg.Goarch == "arm64" { |
| 397 |
g, err := buildcfg.ParseGoarm64(cfg.GOARM64) |
| 398 |
if err == nil && g.LSE { |
| 399 |
args = append(args, "-D", "GOARM64_LSE") |
| 400 |
} |
| 401 |
} |
| 402 |
|
| 403 |
return args |
| 404 |
} |
| 405 |
|
| 406 |
func (gcToolchain) asm(b *Builder, a *Action, sfiles []string) ([]string, error) { |
| 407 |
p := a.Package |
| 408 |
args := asmArgs(a, p) |
| 409 |
|
| 410 |
var ofiles []string |
| 411 |
for _, sfile := range sfiles { |
| 412 |
ofile := a.Objdir + sfile[:len(sfile)-len(".s")] + ".o" |
| 413 |
ofiles = append(ofiles, ofile) |
| 414 |
args1 := append(args, "-o", ofile, fsys.Actual(mkAbs(p.Dir, sfile))) |
| 415 |
if err := b.Shell(a).run(p.Dir, p.ImportPath, cfgChangedEnv, args1...); err != nil { |
| 416 |
return nil, err |
| 417 |
} |
| 418 |
} |
| 419 |
return ofiles, nil |
| 420 |
} |
| 421 |
|
| 422 |
func (gcToolchain) symabis(b *Builder, a *Action, sfiles []string) (string, error) { |
| 423 |
sh := b.Shell(a) |
| 424 |
|
| 425 |
mkSymabis := func(p *load.Package, sfiles []string, path string) error { |
| 426 |
args := asmArgs(a, p) |
| 427 |
args = append(args, "-gensymabis", "-o", path) |
| 428 |
for _, sfile := range sfiles { |
| 429 |
if p.ImportPath == "runtime/cgo" && strings.HasPrefix(sfile, "gcc_") { |
| 430 |
continue |
| 431 |
} |
| 432 |
args = append(args, fsys.Actual(mkAbs(p.Dir, sfile))) |
| 433 |
} |
| 434 |
|
| 435 |
// Supply an empty go_asm.h as if the compiler had been run. |
| 436 |
// -gensymabis parsing is lax enough that we don't need the |
| 437 |
// actual definitions that would appear in go_asm.h. |
| 438 |
if err := sh.writeFile(a.Objdir+"go_asm.h", nil); err != nil { |
| 439 |
return err |
| 440 |
} |
| 441 |
|
| 442 |
return sh.run(p.Dir, p.ImportPath, cfgChangedEnv, args...) |
| 443 |
} |
| 444 |
|
| 445 |
var symabis string // Only set if we actually create the file |
| 446 |
p := a.Package |
| 447 |
if len(sfiles) != 0 { |
| 448 |
symabis = a.Objdir + "symabis" |
| 449 |
if err := mkSymabis(p, sfiles, symabis); err != nil { |
| 450 |
return "", err |
| 451 |
} |
| 452 |
} |
| 453 |
|
| 454 |
return symabis, nil |
| 455 |
} |
| 456 |
|
| 457 |
func (gcToolchain) pack(b *Builder, a *Action, afile string, ofiles []string) error { |
| 458 |
absOfiles := make([]string, 0, len(ofiles)) |
| 459 |
for _, f := range ofiles { |
| 460 |
absOfiles = append(absOfiles, mkAbs(a.Objdir, f)) |
| 461 |
} |
| 462 |
absAfile := mkAbs(a.Objdir, afile) |
| 463 |
|
| 464 |
// The archive file should have been created by the compiler. |
| 465 |
// Since it used to not work that way, verify. |
| 466 |
if !cfg.BuildN { |
| 467 |
if _, err := os.Stat(absAfile); err != nil { |
| 468 |
base.Fatalf("os.Stat of archive file failed: %v", err) |
| 469 |
} |
| 470 |
} |
| 471 |
|
| 472 |
p := a.Package |
| 473 |
sh := b.Shell(a) |
| 474 |
if cfg.BuildN || cfg.BuildX { |
| 475 |
cmdline := str.StringList("go", "tool", "pack", "r", absAfile, absOfiles) |
| 476 |
sh.ShowCmd(p.Dir, "%s # internal", joinUnambiguously(cmdline)) |
| 477 |
} |
| 478 |
if cfg.BuildN { |
| 479 |
return nil |
| 480 |
} |
| 481 |
if err := packInternal(absAfile, absOfiles); err != nil { |
| 482 |
return sh.reportCmd("", "", nil, err) |
| 483 |
} |
| 484 |
return nil |
| 485 |
} |
| 486 |
|
| 487 |
func packInternal(afile string, ofiles []string) error { |
| 488 |
dst, err := os.OpenFile(afile, os.O_WRONLY|os.O_APPEND, 0) |
| 489 |
if err != nil { |
| 490 |
return err |
| 491 |
} |
| 492 |
defer dst.Close() // only for error returns or panics |
| 493 |
w := bufio.NewWriter(dst) |
| 494 |
|
| 495 |
for _, ofile := range ofiles { |
| 496 |
src, err := os.Open(ofile) |
| 497 |
if err != nil { |
| 498 |
return err |
| 499 |
} |
| 500 |
fi, err := src.Stat() |
| 501 |
if err != nil { |
| 502 |
src.Close() |
| 503 |
return err |
| 504 |
} |
| 505 |
// Note: Not using %-16.16s format because we care |
| 506 |
// about bytes, not runes. |
| 507 |
name := fi.Name() |
| 508 |
if len(name) > 16 { |
| 509 |
name = name[:16] |
| 510 |
} else { |
| 511 |
name += strings.Repeat(" ", 16-len(name)) |
| 512 |
} |
| 513 |
size := fi.Size() |
| 514 |
fmt.Fprintf(w, "%s%-12d%-6d%-6d%-8o%-10d`\n", |
| 515 |
name, 0, 0, 0, 0644, size) |
| 516 |
n, err := io.Copy(w, src) |
| 517 |
src.Close() |
| 518 |
if err == nil && n < size { |
| 519 |
err = io.ErrUnexpectedEOF |
| 520 |
} else if err == nil && n > size { |
| 521 |
err = fmt.Errorf("file larger than size reported by stat") |
| 522 |
} |
| 523 |
if err != nil { |
| 524 |
return fmt.Errorf("copying %s to %s: %v", ofile, afile, err) |
| 525 |
} |
| 526 |
if size&1 != 0 { |
| 527 |
w.WriteByte(0) |
| 528 |
} |
| 529 |
} |
| 530 |
|
| 531 |
if err := w.Flush(); err != nil { |
| 532 |
return err |
| 533 |
} |
| 534 |
return dst.Close() |
| 535 |
} |
| 536 |
|
| 537 |
// setextld sets the appropriate linker flags for the specified compiler. |
| 538 |
func setextld(ldflags []string, compiler []string) ([]string, error) { |
| 539 |
for _, f := range ldflags { |
| 540 |
if f == "-extld" || strings.HasPrefix(f, "-extld=") { |
| 541 |
// don't override -extld if supplied |
| 542 |
return ldflags, nil |
| 543 |
} |
| 544 |
} |
| 545 |
joined, err := quoted.Join(compiler) |
| 546 |
if err != nil { |
| 547 |
return nil, err |
| 548 |
} |
| 549 |
return append(ldflags, "-extld="+joined), nil |
| 550 |
} |
| 551 |
|
| 552 |
// pluginPath computes the package path for a plugin main package. |
| 553 |
// |
| 554 |
// This is typically the import path of the main package p, unless the |
| 555 |
// plugin is being built directly from source files. In that case we |
| 556 |
// combine the package build ID with the contents of the main package |
| 557 |
// source files. This allows us to identify two different plugins |
| 558 |
// built from two source files with the same name. |
| 559 |
func pluginPath(a *Action) string { |
| 560 |
p := a.Package |
| 561 |
if p.ImportPath != "command-line-arguments" { |
| 562 |
return p.ImportPath |
| 563 |
} |
| 564 |
h := sha1.New() |
| 565 |
buildID := a.buildID |
| 566 |
if a.Mode == "link" { |
| 567 |
// For linking, use the main package's build ID instead of |
| 568 |
// the binary's build ID, so it is the same hash used in |
| 569 |
// compiling and linking. |
| 570 |
// When compiling, we use actionID/actionID (instead of |
| 571 |
// actionID/contentID) as a temporary build ID to compute |
| 572 |
// the hash. Do the same here. (See buildid.go:useCache) |
| 573 |
// The build ID matters because it affects the overall hash |
| 574 |
// in the plugin's pseudo-import path returned below. |
| 575 |
// We need to use the same import path when compiling and linking. |
| 576 |
id := strings.Split(buildID, buildIDSeparator) |
| 577 |
buildID = id[1] + buildIDSeparator + id[1] |
| 578 |
} |
| 579 |
fmt.Fprintf(h, "build ID: %s\n", buildID) |
| 580 |
for _, file := range str.StringList(p.GoFiles, p.CgoFiles, p.SFiles) { |
| 581 |
data, err := os.ReadFile(filepath.Join(p.Dir, file)) |
| 582 |
if err != nil { |
| 583 |
base.Fatalf("go: %s", err) |
| 584 |
} |
| 585 |
h.Write(data) |
| 586 |
} |
| 587 |
return fmt.Sprintf("plugin/unnamed-%x", h.Sum(nil)) |
| 588 |
} |
| 589 |
|
| 590 |
func (gcToolchain) ld(b *Builder, root *Action, targetPath, importcfg, mainpkg string) error { |
| 591 |
cxx := len(root.Package.CXXFiles) > 0 || len(root.Package.SwigCXXFiles) > 0 |
| 592 |
for _, a := range root.Deps { |
| 593 |
if a.Package != nil && (len(a.Package.CXXFiles) > 0 || len(a.Package.SwigCXXFiles) > 0) { |
| 594 |
cxx = true |
| 595 |
} |
| 596 |
} |
| 597 |
var ldflags []string |
| 598 |
if cfg.BuildContext.InstallSuffix != "" { |
| 599 |
ldflags = append(ldflags, "-installsuffix", cfg.BuildContext.InstallSuffix) |
| 600 |
} |
| 601 |
if root.Package.Internal.OmitDebug { |
| 602 |
ldflags = append(ldflags, "-s", "-w") |
| 603 |
} |
| 604 |
if cfg.BuildBuildmode == "plugin" { |
| 605 |
ldflags = append(ldflags, "-pluginpath", pluginPath(root)) |
| 606 |
} |
| 607 |
if fips140.Enabled() { |
| 608 |
ldflags = append(ldflags, "-fipso", filepath.Join(root.Objdir, "fips.o")) |
| 609 |
} |
| 610 |
|
| 611 |
// Store BuildID inside toolchain binaries as a unique identifier of the |
| 612 |
// tool being run, for use by content-based staleness determination. |
| 613 |
if root.Package.Goroot && strings.HasPrefix(root.Package.ImportPath, "cmd/") { |
| 614 |
// External linking will include our build id in the external |
| 615 |
// linker's build id, which will cause our build id to not |
| 616 |
// match the next time the tool is built. |
| 617 |
// Rely on the external build id instead. |
| 618 |
if !platform.MustLinkExternal(cfg.Goos, cfg.Goarch, false) { |
| 619 |
ldflags = append(ldflags, "-X=cmd/internal/objabi.buildID="+root.buildID) |
| 620 |
} |
| 621 |
} |
| 622 |
|
| 623 |
// Store default GODEBUG in binaries. |
| 624 |
if root.Package.DefaultGODEBUG != "" { |
| 625 |
ldflags = append(ldflags, "-X=runtime.godebugDefault="+root.Package.DefaultGODEBUG) |
| 626 |
} |
| 627 |
|
| 628 |
// If the user has not specified the -extld option, then specify the |
| 629 |
// appropriate linker. In case of C++ code, use the compiler named |
| 630 |
// by the CXX environment variable or defaultCXX if CXX is not set. |
| 631 |
// Else, use the CC environment variable and defaultCC as fallback. |
| 632 |
var compiler []string |
| 633 |
if cxx { |
| 634 |
compiler = envList("CXX", cfg.DefaultCXX(cfg.Goos, cfg.Goarch)) |
| 635 |
} else { |
| 636 |
compiler = envList("CC", cfg.DefaultCC(cfg.Goos, cfg.Goarch)) |
| 637 |
} |
| 638 |
ldflags = append(ldflags, "-buildmode="+ldBuildmode) |
| 639 |
if root.buildID != "" { |
| 640 |
ldflags = append(ldflags, "-buildid="+root.buildID) |
| 641 |
} |
| 642 |
ldflags = append(ldflags, forcedLdflags...) |
| 643 |
ldflags = append(ldflags, root.Package.Internal.Ldflags...) |
| 644 |
ldflags, err := setextld(ldflags, compiler) |
| 645 |
if err != nil { |
| 646 |
return err |
| 647 |
} |
| 648 |
|
| 649 |
// On OS X when using external linking to build a shared library, |
| 650 |
// the argument passed here to -o ends up recorded in the final |
| 651 |
// shared library in the LC_ID_DYLIB load command. |
| 652 |
// To avoid putting the temporary output directory name there |
| 653 |
// (and making the resulting shared library useless), |
| 654 |
// run the link in the output directory so that -o can name |
| 655 |
// just the final path element. |
| 656 |
// On Windows, DLL file name is recorded in PE file |
| 657 |
// export section, so do like on OS X. |
| 658 |
// On Linux, for a shared object, at least with the Gold linker, |
| 659 |
// the output file path is recorded in the .gnu.version_d section. |
| 660 |
dir := "." |
| 661 |
if cfg.BuildBuildmode == "c-shared" || cfg.BuildBuildmode == "plugin" { |
| 662 |
dir, targetPath = filepath.Split(targetPath) |
| 663 |
} |
| 664 |
|
| 665 |
env := cfgChangedEnv |
| 666 |
// When -trimpath is used, GOROOT is cleared |
| 667 |
if cfg.BuildTrimpath { |
| 668 |
env = append(env, "GOROOT=") |
| 669 |
} else { |
| 670 |
env = append(env, "GOROOT="+cfg.GOROOT) |
| 671 |
} |
| 672 |
return b.Shell(root).run(dir, root.Package.ImportPath, env, cfg.BuildToolexec, base.Tool("link"), "-o", targetPath, "-importcfg", importcfg, ldflags, mainpkg) |
| 673 |
} |
| 674 |
|
| 675 |
func (gcToolchain) ldShared(b *Builder, root *Action, toplevelactions []*Action, targetPath, importcfg string, allactions []*Action) error { |
| 676 |
ldflags := []string{"-installsuffix", cfg.BuildContext.InstallSuffix} |
| 677 |
ldflags = append(ldflags, "-buildmode=shared") |
| 678 |
ldflags = append(ldflags, forcedLdflags...) |
| 679 |
ldflags = append(ldflags, root.Package.Internal.Ldflags...) |
| 680 |
cxx := false |
| 681 |
for _, a := range allactions { |
| 682 |
if a.Package != nil && (len(a.Package.CXXFiles) > 0 || len(a.Package.SwigCXXFiles) > 0) { |
| 683 |
cxx = true |
| 684 |
} |
| 685 |
} |
| 686 |
// If the user has not specified the -extld option, then specify the |
| 687 |
// appropriate linker. In case of C++ code, use the compiler named |
| 688 |
// by the CXX environment variable or defaultCXX if CXX is not set. |
| 689 |
// Else, use the CC environment variable and defaultCC as fallback. |
| 690 |
var compiler []string |
| 691 |
if cxx { |
| 692 |
compiler = envList("CXX", cfg.DefaultCXX(cfg.Goos, cfg.Goarch)) |
| 693 |
} else { |
| 694 |
compiler = envList("CC", cfg.DefaultCC(cfg.Goos, cfg.Goarch)) |
| 695 |
} |
| 696 |
ldflags, err := setextld(ldflags, compiler) |
| 697 |
if err != nil { |
| 698 |
return err |
| 699 |
} |
| 700 |
for _, d := range toplevelactions { |
| 701 |
if !strings.HasSuffix(d.Target, ".a") { // omit unsafe etc and actions for other shared libraries |
| 702 |
continue |
| 703 |
} |
| 704 |
ldflags = append(ldflags, d.Package.ImportPath+"="+d.Target) |
| 705 |
} |
| 706 |
|
| 707 |
// On OS X when using external linking to build a shared library, |
| 708 |
// the argument passed here to -o ends up recorded in the final |
| 709 |
// shared library in the LC_ID_DYLIB load command. |
| 710 |
// To avoid putting the temporary output directory name there |
| 711 |
// (and making the resulting shared library useless), |
| 712 |
// run the link in the output directory so that -o can name |
| 713 |
// just the final path element. |
| 714 |
// On Windows, DLL file name is recorded in PE file |
| 715 |
// export section, so do like on OS X. |
| 716 |
// On Linux, for a shared object, at least with the Gold linker, |
| 717 |
// the output file path is recorded in the .gnu.version_d section. |
| 718 |
dir, targetPath := filepath.Split(targetPath) |
| 719 |
|
| 720 |
return b.Shell(root).run(dir, targetPath, cfgChangedEnv, cfg.BuildToolexec, base.Tool("link"), "-o", targetPath, "-importcfg", importcfg, ldflags) |
| 721 |
} |
| 722 |
|
| 723 |
func (gcToolchain) cc(b *Builder, a *Action, ofile, cfile string) error { |
| 724 |
return fmt.Errorf("%s: C source files not supported without cgo", mkAbs(a.Package.Dir, cfile)) |
| 725 |
} |