| 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 |
// Action graph execution. |
| 6 |
|
| 7 |
package work |
| 8 |
|
| 9 |
import ( |
| 10 |
"bytes" |
| 11 |
"cmd/internal/cov/covcmd" |
| 12 |
"cmd/internal/pathcache" |
| 13 |
"context" |
| 14 |
"crypto/sha256" |
| 15 |
"encoding/json" |
| 16 |
"errors" |
| 17 |
"fmt" |
| 18 |
"go/token" |
| 19 |
"internal/lazyregexp" |
| 20 |
"io" |
| 21 |
"io/fs" |
| 22 |
"log" |
| 23 |
"math/rand" |
| 24 |
"os" |
| 25 |
"os/exec" |
| 26 |
"path/filepath" |
| 27 |
"regexp" |
| 28 |
"runtime" |
| 29 |
"slices" |
| 30 |
"sort" |
| 31 |
"strconv" |
| 32 |
"strings" |
| 33 |
"sync" |
| 34 |
"time" |
| 35 |
|
| 36 |
"cmd/go/internal/base" |
| 37 |
"cmd/go/internal/cache" |
| 38 |
"cmd/go/internal/cfg" |
| 39 |
"cmd/go/internal/fsys" |
| 40 |
"cmd/go/internal/gover" |
| 41 |
"cmd/go/internal/load" |
| 42 |
"cmd/go/internal/modload" |
| 43 |
"cmd/go/internal/str" |
| 44 |
"cmd/go/internal/trace" |
| 45 |
"cmd/internal/buildid" |
| 46 |
"cmd/internal/quoted" |
| 47 |
"cmd/internal/sys" |
| 48 |
) |
| 49 |
|
| 50 |
const DefaultCFlags = "-O2 -g" |
| 51 |
|
| 52 |
// actionList returns the list of actions in the dag rooted at root |
| 53 |
// as visited in a depth-first post-order traversal. |
| 54 |
func actionList(root *Action) []*Action { |
| 55 |
seen := map[*Action]bool{} |
| 56 |
all := []*Action{} |
| 57 |
var walk func(*Action) |
| 58 |
walk = func(a *Action) { |
| 59 |
if seen[a] { |
| 60 |
return |
| 61 |
} |
| 62 |
seen[a] = true |
| 63 |
for _, a1 := range a.Deps { |
| 64 |
walk(a1) |
| 65 |
} |
| 66 |
all = append(all, a) |
| 67 |
} |
| 68 |
walk(root) |
| 69 |
return all |
| 70 |
} |
| 71 |
|
| 72 |
// Do runs the action graph rooted at root. |
| 73 |
func (b *Builder) Do(ctx context.Context, root *Action) { |
| 74 |
ctx, span := trace.StartSpan(ctx, "exec.Builder.Do ("+root.Mode+" "+root.Target+")") |
| 75 |
defer span.Done() |
| 76 |
|
| 77 |
if !b.IsCmdList { |
| 78 |
// If we're doing real work, take time at the end to trim the cache. |
| 79 |
c := cache.Default() |
| 80 |
defer func() { |
| 81 |
if err := c.Close(); err != nil { |
| 82 |
base.Fatalf("go: failed to trim cache: %v", err) |
| 83 |
} |
| 84 |
}() |
| 85 |
} |
| 86 |
|
| 87 |
// Build list of all actions, assigning depth-first post-order priority. |
| 88 |
// The original implementation here was a true queue |
| 89 |
// (using a channel) but it had the effect of getting |
| 90 |
// distracted by low-level leaf actions to the detriment |
| 91 |
// of completing higher-level actions. The order of |
| 92 |
// work does not matter much to overall execution time, |
| 93 |
// but when running "go test std" it is nice to see each test |
| 94 |
// results as soon as possible. The priorities assigned |
| 95 |
// ensure that, all else being equal, the execution prefers |
| 96 |
// to do what it would have done first in a simple depth-first |
| 97 |
// dependency order traversal. |
| 98 |
all := actionList(root) |
| 99 |
for i, a := range all { |
| 100 |
a.priority = i |
| 101 |
} |
| 102 |
|
| 103 |
// Write action graph, without timing information, in case we fail and exit early. |
| 104 |
writeActionGraph := func() { |
| 105 |
if file := cfg.DebugActiongraph; file != "" { |
| 106 |
if strings.HasSuffix(file, ".go") { |
| 107 |
// Do not overwrite Go source code in: |
| 108 |
// go build -debug-actiongraph x.go |
| 109 |
base.Fatalf("go: refusing to write action graph to %v\n", file) |
| 110 |
} |
| 111 |
js := actionGraphJSON(root) |
| 112 |
if err := os.WriteFile(file, []byte(js), 0666); err != nil { |
| 113 |
fmt.Fprintf(os.Stderr, "go: writing action graph: %v\n", err) |
| 114 |
base.SetExitStatus(1) |
| 115 |
} |
| 116 |
} |
| 117 |
} |
| 118 |
writeActionGraph() |
| 119 |
|
| 120 |
b.readySema = make(chan bool, len(all)) |
| 121 |
|
| 122 |
// Initialize per-action execution state. |
| 123 |
for _, a := range all { |
| 124 |
for _, a1 := range a.Deps { |
| 125 |
a1.triggers = append(a1.triggers, a) |
| 126 |
} |
| 127 |
a.pending = len(a.Deps) |
| 128 |
if a.pending == 0 { |
| 129 |
b.ready.push(a) |
| 130 |
b.readySema <- true |
| 131 |
} |
| 132 |
} |
| 133 |
|
| 134 |
// Handle runs a single action and takes care of triggering |
| 135 |
// any actions that are runnable as a result. |
| 136 |
handle := func(ctx context.Context, a *Action) { |
| 137 |
if a.json != nil { |
| 138 |
a.json.TimeStart = time.Now() |
| 139 |
} |
| 140 |
var err error |
| 141 |
if a.Actor != nil && (a.Failed == nil || a.IgnoreFail) { |
| 142 |
// TODO(matloob): Better action descriptions |
| 143 |
desc := "Executing action (" + a.Mode |
| 144 |
if a.Package != nil { |
| 145 |
desc += " " + a.Package.Desc() |
| 146 |
} |
| 147 |
desc += ")" |
| 148 |
ctx, span := trace.StartSpan(ctx, desc) |
| 149 |
a.traceSpan = span |
| 150 |
for _, d := range a.Deps { |
| 151 |
trace.Flow(ctx, d.traceSpan, a.traceSpan) |
| 152 |
} |
| 153 |
err = a.Actor.Act(b, ctx, a) |
| 154 |
span.Done() |
| 155 |
} |
| 156 |
if a.json != nil { |
| 157 |
a.json.TimeDone = time.Now() |
| 158 |
} |
| 159 |
|
| 160 |
// The actions run in parallel but all the updates to the |
| 161 |
// shared work state are serialized through b.exec. |
| 162 |
b.exec.Lock() |
| 163 |
defer b.exec.Unlock() |
| 164 |
|
| 165 |
if err != nil { |
| 166 |
if b.AllowErrors && a.Package != nil { |
| 167 |
if a.Package.Error == nil { |
| 168 |
a.Package.Error = &load.PackageError{Err: err} |
| 169 |
a.Package.Incomplete = true |
| 170 |
} |
| 171 |
} else { |
| 172 |
if a.Package != nil { |
| 173 |
if ipe, ok := errors.AsType[load.ImportPathError](err); !ok || ipe.ImportPath() != a.Package.ImportPath { |
| 174 |
err = fmt.Errorf("%s: %v", a.Package.ImportPath, err) |
| 175 |
} |
| 176 |
} |
| 177 |
sh := b.Shell(a) |
| 178 |
sh.Errorf("%s", err) |
| 179 |
} |
| 180 |
if a.Failed == nil { |
| 181 |
a.Failed = a |
| 182 |
} |
| 183 |
} |
| 184 |
|
| 185 |
for _, a0 := range a.triggers { |
| 186 |
if a.Failed != nil { |
| 187 |
if a0.Mode == "test barrier" { |
| 188 |
// If this action was triggered by a test, there |
| 189 |
// will be a test barrier action in between the test |
| 190 |
// and the true trigger. But there will be other |
| 191 |
// triggers that are other barriers that are waiting |
| 192 |
// for this one. Propagate the failure to the true |
| 193 |
// trigger, but not to the other barriers. |
| 194 |
for _, bt := range a0.triggers { |
| 195 |
if bt.Mode != "test barrier" { |
| 196 |
bt.Failed = a.Failed |
| 197 |
} |
| 198 |
} |
| 199 |
} else { |
| 200 |
a0.Failed = a.Failed |
| 201 |
} |
| 202 |
} |
| 203 |
if a0.pending--; a0.pending == 0 { |
| 204 |
b.ready.push(a0) |
| 205 |
b.readySema <- true |
| 206 |
} |
| 207 |
} |
| 208 |
|
| 209 |
if a == root { |
| 210 |
close(b.readySema) |
| 211 |
} |
| 212 |
} |
| 213 |
|
| 214 |
var wg sync.WaitGroup |
| 215 |
|
| 216 |
// Kick off goroutines according to parallelism. |
| 217 |
// If we are using the -n flag (just printing commands) |
| 218 |
// drop the parallelism to 1, both to make the output |
| 219 |
// deterministic and because there is no real work anyway. |
| 220 |
par := cfg.BuildP |
| 221 |
if cfg.BuildN { |
| 222 |
par = 1 |
| 223 |
} |
| 224 |
for i := 0; i < par; i++ { |
| 225 |
wg.Add(1) |
| 226 |
go func() { |
| 227 |
ctx := trace.StartGoroutine(ctx) |
| 228 |
defer wg.Done() |
| 229 |
for { |
| 230 |
select { |
| 231 |
case _, ok := <-b.readySema: |
| 232 |
if !ok { |
| 233 |
return |
| 234 |
} |
| 235 |
// Receiving a value from b.readySema entitles |
| 236 |
// us to take from the ready queue. |
| 237 |
b.exec.Lock() |
| 238 |
a := b.ready.pop() |
| 239 |
b.exec.Unlock() |
| 240 |
handle(ctx, a) |
| 241 |
case <-base.Interrupted: |
| 242 |
base.SetExitStatus(1) |
| 243 |
return |
| 244 |
} |
| 245 |
} |
| 246 |
}() |
| 247 |
} |
| 248 |
|
| 249 |
wg.Wait() |
| 250 |
|
| 251 |
if tokens != totalTokens || concurrentProcesses != 0 { |
| 252 |
base.Fatalf("internal error: tokens not restored at end of build: tokens: %d, totalTokens: %d, concurrentProcesses: %d", |
| 253 |
tokens, totalTokens, concurrentProcesses) |
| 254 |
} |
| 255 |
|
| 256 |
// Write action graph again, this time with timing information. |
| 257 |
writeActionGraph() |
| 258 |
} |
| 259 |
|
| 260 |
// buildActionID computes the action ID for a build action. |
| 261 |
func (b *Builder) buildActionID(a *Action) cache.ActionID { |
| 262 |
p := a.Package |
| 263 |
h := cache.NewHash("build " + p.ImportPath) |
| 264 |
|
| 265 |
// Configuration independent of compiler toolchain. |
| 266 |
// Note: buildmode has already been accounted for in buildGcflags |
| 267 |
// and should not be inserted explicitly. Most buildmodes use the |
| 268 |
// same compiler settings and can reuse each other's results. |
| 269 |
// If not, the reason is already recorded in buildGcflags. |
| 270 |
fmt.Fprintf(h, "compile\n") |
| 271 |
|
| 272 |
// Include information about the origin of the package that |
| 273 |
// may be embedded in the debug info for the object file. |
| 274 |
if cfg.BuildTrimpath { |
| 275 |
// When -trimpath is used with a package built from the module cache, |
| 276 |
// its debug information refers to the module path and version |
| 277 |
// instead of the directory. |
| 278 |
if p.Module != nil { |
| 279 |
fmt.Fprintf(h, "module %s@%s\n", p.Module.Path, p.Module.Version) |
| 280 |
} |
| 281 |
} else if p.Goroot { |
| 282 |
// The Go compiler always hides the exact value of $GOROOT |
| 283 |
// when building things in GOROOT. |
| 284 |
// |
| 285 |
// The C compiler does not, but for packages in GOROOT we rewrite the path |
| 286 |
// as though -trimpath were set. This used to be so that we did not invalidate |
| 287 |
// the build cache (and especially precompiled archive files) when changing |
| 288 |
// GOROOT_FINAL, but we no longer ship precompiled archive files as of Go 1.20 |
| 289 |
// (https://go.dev/issue/47257) and no longer support GOROOT_FINAL |
| 290 |
// (https://go.dev/issue/62047). |
| 291 |
// TODO(bcmills): Figure out whether this behavior is still useful. |
| 292 |
// |
| 293 |
// b.WorkDir is always either trimmed or rewritten to |
| 294 |
// the literal string "/tmp/go-build". |
| 295 |
} else if !strings.HasPrefix(p.Dir, b.WorkDir) { |
| 296 |
// -trimpath is not set and no other rewrite rules apply, |
| 297 |
// so the object file may refer to the absolute directory |
| 298 |
// containing the package. |
| 299 |
fmt.Fprintf(h, "dir %s\n", p.Dir) |
| 300 |
} |
| 301 |
|
| 302 |
if p.Module != nil { |
| 303 |
fmt.Fprintf(h, "go %s\n", p.Module.GoVersion) |
| 304 |
} |
| 305 |
fmt.Fprintf(h, "goos %s goarch %s\n", cfg.Goos, cfg.Goarch) |
| 306 |
fmt.Fprintf(h, "import %q\n", p.ImportPath) |
| 307 |
fmt.Fprintf(h, "omitdebug %v standard %v local %v prefix %q\n", p.Internal.OmitDebug, p.Standard, p.Internal.Local, p.Internal.LocalPrefix) |
| 308 |
if cfg.BuildTrimpath { |
| 309 |
fmt.Fprintln(h, "trimpath") |
| 310 |
} |
| 311 |
if p.Internal.ForceLibrary { |
| 312 |
fmt.Fprintf(h, "forcelibrary\n") |
| 313 |
} |
| 314 |
if len(p.CgoFiles)+len(p.SwigFiles)+len(p.SwigCXXFiles) > 0 { |
| 315 |
fmt.Fprintf(h, "cgo %q\n", b.toolID("cgo")) |
| 316 |
cppflags, cflags, cxxflags, fflags, ldflags, _ := b.CFlags(p) |
| 317 |
|
| 318 |
ccExe := b.ccExe() |
| 319 |
fmt.Fprintf(h, "CC=%q %q %q %q\n", ccExe, cppflags, cflags, ldflags) |
| 320 |
// Include the C compiler tool ID so that if the C |
| 321 |
// compiler changes we rebuild the package. |
| 322 |
if ccID, _, err := b.gccToolID(ccExe[0], "c"); err == nil { |
| 323 |
fmt.Fprintf(h, "CC ID=%q\n", ccID) |
| 324 |
} else { |
| 325 |
fmt.Fprintf(h, "CC ID ERROR=%q\n", err) |
| 326 |
} |
| 327 |
if len(p.CXXFiles)+len(p.SwigCXXFiles) > 0 { |
| 328 |
cxxExe := b.cxxExe() |
| 329 |
fmt.Fprintf(h, "CXX=%q %q\n", cxxExe, cxxflags) |
| 330 |
if cxxID, _, err := b.gccToolID(cxxExe[0], "c++"); err == nil { |
| 331 |
fmt.Fprintf(h, "CXX ID=%q\n", cxxID) |
| 332 |
} else { |
| 333 |
fmt.Fprintf(h, "CXX ID ERROR=%q\n", err) |
| 334 |
} |
| 335 |
} |
| 336 |
if len(p.FFiles) > 0 { |
| 337 |
fcExe := b.fcExe() |
| 338 |
fmt.Fprintf(h, "FC=%q %q\n", fcExe, fflags) |
| 339 |
if fcID, _, err := b.gccToolID(fcExe[0], "f95"); err == nil { |
| 340 |
fmt.Fprintf(h, "FC ID=%q\n", fcID) |
| 341 |
} else { |
| 342 |
fmt.Fprintf(h, "FC ID ERROR=%q\n", err) |
| 343 |
} |
| 344 |
} |
| 345 |
// TODO(rsc): Should we include the SWIG version? |
| 346 |
} |
| 347 |
if p.Internal.Cover.Mode != "" { |
| 348 |
fmt.Fprintf(h, "cover %q %q\n", p.Internal.Cover.Mode, b.toolID("cover")) |
| 349 |
} |
| 350 |
if p.Internal.FuzzInstrument { |
| 351 |
if fuzzFlags := fuzzInstrumentFlags(); fuzzFlags != nil { |
| 352 |
fmt.Fprintf(h, "fuzz %q\n", fuzzFlags) |
| 353 |
} |
| 354 |
} |
| 355 |
if p.Internal.BuildInfo != nil { |
| 356 |
fmt.Fprintf(h, "modinfo %q\n", p.Internal.BuildInfo.String()) |
| 357 |
} |
| 358 |
|
| 359 |
// Configuration specific to compiler toolchain. |
| 360 |
switch cfg.BuildToolchainName { |
| 361 |
default: |
| 362 |
base.Fatalf("buildActionID: unknown build toolchain %q", cfg.BuildToolchainName) |
| 363 |
case "gc": |
| 364 |
fmt.Fprintf(h, "compile %s %q %q\n", b.toolID("compile"), forcedGcflags, p.Internal.Gcflags) |
| 365 |
if len(p.SFiles) > 0 { |
| 366 |
fmt.Fprintf(h, "asm %q %q %q\n", b.toolID("asm"), forcedAsmflags, p.Internal.Asmflags) |
| 367 |
} |
| 368 |
|
| 369 |
// GOARM, GOMIPS, etc. |
| 370 |
key, val, _ := cfg.GetArchEnv() |
| 371 |
fmt.Fprintf(h, "%s=%s\n", key, val) |
| 372 |
|
| 373 |
if cfg.CleanGOEXPERIMENT != "" { |
| 374 |
fmt.Fprintf(h, "GOEXPERIMENT=%q\n", cfg.CleanGOEXPERIMENT) |
| 375 |
} |
| 376 |
|
| 377 |
// TODO(rsc): Convince compiler team not to add more magic environment variables, |
| 378 |
// or perhaps restrict the environment variables passed to subprocesses. |
| 379 |
// Because these are clumsy, undocumented special-case hacks |
| 380 |
// for debugging the compiler, they are not settable using 'go env -w', |
| 381 |
// and so here we use os.Getenv, not cfg.Getenv. |
| 382 |
magic := []string{ |
| 383 |
"GOCLOBBERDEADHASH", |
| 384 |
"GOSSAFUNC", |
| 385 |
"GOSSADIR", |
| 386 |
"GOCOMPILEDEBUG", |
| 387 |
} |
| 388 |
for _, env := range magic { |
| 389 |
if x := os.Getenv(env); x != "" { |
| 390 |
fmt.Fprintf(h, "magic %s=%s\n", env, x) |
| 391 |
} |
| 392 |
} |
| 393 |
|
| 394 |
case "gccgo": |
| 395 |
id, _, err := b.gccToolID(BuildToolchain.compiler(), "go") |
| 396 |
if err != nil { |
| 397 |
base.Fatalf("%v", err) |
| 398 |
} |
| 399 |
fmt.Fprintf(h, "compile %s %q %q\n", id, forcedGccgoflags, p.Internal.Gccgoflags) |
| 400 |
fmt.Fprintf(h, "pkgpath %s\n", gccgoPkgpath(p)) |
| 401 |
fmt.Fprintf(h, "ar %q\n", BuildToolchain.(gccgoToolchain).ar()) |
| 402 |
if len(p.SFiles) > 0 { |
| 403 |
id, _, _ = b.gccToolID(BuildToolchain.compiler(), "assembler-with-cpp") |
| 404 |
// Ignore error; different assembler versions |
| 405 |
// are unlikely to make any difference anyhow. |
| 406 |
fmt.Fprintf(h, "asm %q\n", id) |
| 407 |
} |
| 408 |
} |
| 409 |
|
| 410 |
// Input files. |
| 411 |
inputFiles := str.StringList( |
| 412 |
p.GoFiles, |
| 413 |
p.CgoFiles, |
| 414 |
p.CFiles, |
| 415 |
p.CXXFiles, |
| 416 |
p.FFiles, |
| 417 |
p.MFiles, |
| 418 |
p.HFiles, |
| 419 |
p.SFiles, |
| 420 |
p.SysoFiles, |
| 421 |
p.SwigFiles, |
| 422 |
p.SwigCXXFiles, |
| 423 |
p.EmbedFiles, |
| 424 |
) |
| 425 |
for _, file := range inputFiles { |
| 426 |
fmt.Fprintf(h, "file %s %s\n", file, b.fileHash(filepath.Join(p.Dir, file))) |
| 427 |
} |
| 428 |
for _, a1 := range a.Deps { |
| 429 |
p1 := a1.Package |
| 430 |
if p1 != nil { |
| 431 |
fmt.Fprintf(h, "import %s %s\n", p1.ImportPath, contentID(a1.buildID)) |
| 432 |
} |
| 433 |
if a1.Mode == "preprocess PGO profile" { |
| 434 |
fmt.Fprintf(h, "pgofile %s\n", b.fileHash(a1.built)) |
| 435 |
} |
| 436 |
} |
| 437 |
|
| 438 |
return h.Sum() |
| 439 |
} |
| 440 |
|
| 441 |
// needCgoHdr reports whether the actions triggered by this one |
| 442 |
// expect to be able to access the cgo-generated header file. |
| 443 |
func (b *Builder) needCgoHdr(a *Action) bool { |
| 444 |
// If this build triggers a header install, run cgo to get the header. |
| 445 |
if !b.IsCmdList && (a.Package.UsesCgo() || a.Package.UsesSwig()) && (cfg.BuildBuildmode == "c-archive" || cfg.BuildBuildmode == "c-shared") { |
| 446 |
for _, t1 := range a.triggers { |
| 447 |
if t1.Mode == "install header" { |
| 448 |
return true |
| 449 |
} |
| 450 |
} |
| 451 |
for _, t1 := range a.triggers { |
| 452 |
for _, t2 := range t1.triggers { |
| 453 |
if t2.Mode == "install header" { |
| 454 |
return true |
| 455 |
} |
| 456 |
} |
| 457 |
} |
| 458 |
} |
| 459 |
return false |
| 460 |
} |
| 461 |
|
| 462 |
// allowedVersion reports whether the version v is an allowed version of go |
| 463 |
// (one that we can compile). |
| 464 |
// v is known to be of the form "1.23". |
| 465 |
func allowedVersion(v string) bool { |
| 466 |
// Special case: no requirement. |
| 467 |
if v == "" { |
| 468 |
return true |
| 469 |
} |
| 470 |
return gover.Compare(gover.Local(), v) >= 0 |
| 471 |
} |
| 472 |
|
| 473 |
func (b *Builder) computeNonGoOverlay(a *Action, p *load.Package, sh *Shell, objdir string, nonGoFileLists [][]string) error { |
| 474 |
OverlayLoop: |
| 475 |
for _, fs := range nonGoFileLists { |
| 476 |
for _, f := range fs { |
| 477 |
if fsys.Replaced(mkAbs(p.Dir, f)) { |
| 478 |
a.nonGoOverlay = make(map[string]string) |
| 479 |
break OverlayLoop |
| 480 |
} |
| 481 |
} |
| 482 |
} |
| 483 |
if a.nonGoOverlay != nil { |
| 484 |
for _, fs := range nonGoFileLists { |
| 485 |
for i := range fs { |
| 486 |
from := mkAbs(p.Dir, fs[i]) |
| 487 |
dst := objdir + filepath.Base(fs[i]) |
| 488 |
if err := sh.CopyFile(dst, fsys.Actual(from), 0666, false); err != nil { |
| 489 |
return err |
| 490 |
} |
| 491 |
a.nonGoOverlay[from] = dst |
| 492 |
} |
| 493 |
} |
| 494 |
} |
| 495 |
|
| 496 |
return nil |
| 497 |
} |
| 498 |
|
| 499 |
// needsBuild reports whether the Action (which must be mode "build") needs |
| 500 |
// to produce the built output. |
| 501 |
func (b *Builder) needsBuild(a *Action) bool { |
| 502 |
return !b.IsCmdList && a.needBuild || b.NeedExport |
| 503 |
} |
| 504 |
|
| 505 |
const ( |
| 506 |
needBuild uint32 = 1 << iota |
| 507 |
needCgoHdr |
| 508 |
needVet |
| 509 |
needCompiledGoFiles |
| 510 |
needCovMetaFile |
| 511 |
needStale |
| 512 |
) |
| 513 |
|
| 514 |
// checkCacheForBuild checks the cache for the outputs of the buildAction to determine |
| 515 |
// what work needs to be done by it and the actions preceding it. a is the action |
| 516 |
// currently being run, which has an actor of type *checkCacheActor and is a dependency |
| 517 |
// of the buildAction. |
| 518 |
func (b *Builder) checkCacheForBuild(a, buildAction *Action, covMetaFileName string) (_ *checkCacheProvider, err error) { |
| 519 |
p := buildAction.Package |
| 520 |
sh := b.Shell(a) |
| 521 |
|
| 522 |
bit := func(x uint32, b bool) uint32 { |
| 523 |
if b { |
| 524 |
return x |
| 525 |
} |
| 526 |
return 0 |
| 527 |
} |
| 528 |
|
| 529 |
cachedBuild := false |
| 530 |
needCovMeta := p.Internal.Cover.GenMeta |
| 531 |
need := bit(needBuild, !b.IsCmdList && buildAction.needBuild || b.NeedExport) | |
| 532 |
bit(needCgoHdr, b.needCgoHdr(buildAction)) | |
| 533 |
bit(needVet, buildAction.needVet) | |
| 534 |
bit(needCovMetaFile, needCovMeta) | |
| 535 |
bit(needCompiledGoFiles, b.NeedCompiledGoFiles) |
| 536 |
|
| 537 |
if !p.BinaryOnly { |
| 538 |
// We pass 'a' (this checkCacheAction) to buildActionID so that we use its dependencies, |
| 539 |
// which are the actual package dependencies, rather than the buildAction's dependencies |
| 540 |
// which also includes this action and the cover action. |
| 541 |
if b.useCache(buildAction, b.buildActionID(a), p.Target, need&needBuild != 0) { |
| 542 |
// We found the main output in the cache. |
| 543 |
// If we don't need any other outputs, we can stop. |
| 544 |
// Otherwise, we need to write files to a.Objdir (needVet, needCgoHdr). |
| 545 |
// Remember that we might have them in cache |
| 546 |
// and check again after we create a.Objdir. |
| 547 |
cachedBuild = true |
| 548 |
buildAction.output = []byte{} // start saving output in case we miss any cache results |
| 549 |
need &^= needBuild |
| 550 |
if b.NeedExport { |
| 551 |
p.Export = buildAction.built |
| 552 |
p.BuildID = buildAction.buildID |
| 553 |
} |
| 554 |
if need&needCompiledGoFiles != 0 { |
| 555 |
if err := b.loadCachedCompiledGoFiles(buildAction); err == nil { |
| 556 |
need &^= needCompiledGoFiles |
| 557 |
} |
| 558 |
} |
| 559 |
} |
| 560 |
|
| 561 |
// Source files might be cached, even if the full action is not |
| 562 |
// (e.g., go list -compiled -find). |
| 563 |
if !cachedBuild && need&needCompiledGoFiles != 0 { |
| 564 |
if err := b.loadCachedCompiledGoFiles(buildAction); err == nil { |
| 565 |
need &^= needCompiledGoFiles |
| 566 |
} |
| 567 |
} |
| 568 |
|
| 569 |
if need == 0 { |
| 570 |
return &checkCacheProvider{need: need}, nil |
| 571 |
} |
| 572 |
defer b.flushOutput(a) |
| 573 |
} |
| 574 |
|
| 575 |
defer func() { |
| 576 |
if err != nil && b.IsCmdList && b.NeedError && p.Error == nil { |
| 577 |
p.Error = &load.PackageError{Err: err} |
| 578 |
} |
| 579 |
}() |
| 580 |
|
| 581 |
if p.Error != nil { |
| 582 |
// Don't try to build anything for packages with errors. There may be a |
| 583 |
// problem with the inputs that makes the package unsafe to build. |
| 584 |
return nil, p.Error |
| 585 |
} |
| 586 |
|
| 587 |
// TODO(matloob): return early for binary-only packages so that we don't need to indent |
| 588 |
// the core of this function in the if !p.BinaryOnly block above. |
| 589 |
if p.BinaryOnly { |
| 590 |
p.Stale = true |
| 591 |
p.StaleReason = "binary-only packages are no longer supported" |
| 592 |
if b.IsCmdList { |
| 593 |
return &checkCacheProvider{need: 0}, nil |
| 594 |
} |
| 595 |
return nil, errors.New("binary-only packages are no longer supported") |
| 596 |
} |
| 597 |
|
| 598 |
if p.Module != nil && !allowedVersion(p.Module.GoVersion) { |
| 599 |
return nil, errors.New("module requires Go " + p.Module.GoVersion + " or later") |
| 600 |
} |
| 601 |
|
| 602 |
if err := b.checkDirectives(buildAction); err != nil { |
| 603 |
return nil, err |
| 604 |
} |
| 605 |
|
| 606 |
if err := sh.Mkdir(buildAction.Objdir); err != nil { |
| 607 |
return nil, err |
| 608 |
} |
| 609 |
|
| 610 |
// Load cached cgo header, but only if we're skipping the main build (cachedBuild==true). |
| 611 |
if cachedBuild && need&needCgoHdr != 0 { |
| 612 |
if err := b.loadCachedCgoHdr(buildAction); err == nil { |
| 613 |
need &^= needCgoHdr |
| 614 |
} |
| 615 |
} |
| 616 |
|
| 617 |
// Load cached coverage meta-data file fragment, but only if we're |
| 618 |
// skipping the main build (cachedBuild==true). |
| 619 |
if cachedBuild && need&needCovMetaFile != 0 { |
| 620 |
if err := b.loadCachedObjdirFile(buildAction, cache.Default(), covMetaFileName); err == nil { |
| 621 |
need &^= needCovMetaFile |
| 622 |
} |
| 623 |
} |
| 624 |
|
| 625 |
// Load cached vet config, but only if that's all we have left |
| 626 |
// (need == needVet, not testing just the one bit). |
| 627 |
// If we are going to do a full build anyway, |
| 628 |
// we're going to regenerate the files in the build action anyway. |
| 629 |
if need == needVet { |
| 630 |
if err := b.loadCachedVet(buildAction, a.Deps); err == nil { |
| 631 |
need &^= needVet |
| 632 |
} |
| 633 |
} |
| 634 |
|
| 635 |
return &checkCacheProvider{need: need}, nil |
| 636 |
} |
| 637 |
|
| 638 |
func (b *Builder) runCover(a, buildAction *Action, objdir string, gofiles, cgofiles []string) (*coverProvider, error) { |
| 639 |
p := a.Package |
| 640 |
sh := b.Shell(a) |
| 641 |
|
| 642 |
var cacheProvider *checkCacheProvider |
| 643 |
for _, dep := range a.Deps { |
| 644 |
if pr, ok := dep.Provider.(*checkCacheProvider); ok { |
| 645 |
cacheProvider = pr |
| 646 |
} |
| 647 |
} |
| 648 |
if cacheProvider == nil { |
| 649 |
base.Fatalf("internal error: could not find checkCacheProvider") |
| 650 |
} |
| 651 |
need := cacheProvider.need |
| 652 |
|
| 653 |
if need == 0 { |
| 654 |
return nil, nil |
| 655 |
} |
| 656 |
|
| 657 |
if err := sh.Mkdir(a.Objdir); err != nil { |
| 658 |
return nil, err |
| 659 |
} |
| 660 |
|
| 661 |
gofiles = slices.Clone(gofiles) |
| 662 |
cgofiles = slices.Clone(cgofiles) |
| 663 |
|
| 664 |
outfiles := []string{} |
| 665 |
infiles := []string{} |
| 666 |
for i, file := range str.StringList(gofiles, cgofiles) { |
| 667 |
if base.IsTestFile(file) { |
| 668 |
continue // Not covering this file. |
| 669 |
} |
| 670 |
|
| 671 |
var sourceFile string |
| 672 |
var coverFile string |
| 673 |
if base, found := strings.CutSuffix(file, ".cgo1.go"); found { |
| 674 |
// cgo files have absolute paths |
| 675 |
base = filepath.Base(base) |
| 676 |
sourceFile = file |
| 677 |
coverFile = objdir + base + ".cgo1.go" |
| 678 |
} else { |
| 679 |
sourceFile = filepath.Join(p.Dir, file) |
| 680 |
coverFile = objdir + file |
| 681 |
} |
| 682 |
coverFile = strings.TrimSuffix(coverFile, ".go") + ".cover.go" |
| 683 |
infiles = append(infiles, sourceFile) |
| 684 |
outfiles = append(outfiles, coverFile) |
| 685 |
if i < len(gofiles) { |
| 686 |
gofiles[i] = coverFile |
| 687 |
} else { |
| 688 |
cgofiles[i-len(gofiles)] = coverFile |
| 689 |
} |
| 690 |
} |
| 691 |
|
| 692 |
if len(infiles) != 0 { |
| 693 |
// Coverage instrumentation creates new top level |
| 694 |
// variables in the target package for things like |
| 695 |
// meta-data containers, counter vars, etc. To avoid |
| 696 |
// collisions with user variables, suffix the var name |
| 697 |
// with 12 hex digits from the SHA-256 hash of the |
| 698 |
// import path. Choice of 12 digits is historical/arbitrary, |
| 699 |
// we just need enough of the hash to avoid accidents, |
| 700 |
// as opposed to precluding determined attempts by |
| 701 |
// users to break things. |
| 702 |
sum := sha256.Sum256([]byte(a.Package.ImportPath)) |
| 703 |
coverVar := fmt.Sprintf("goCover_%x_", sum[:6]) |
| 704 |
mode := a.Package.Internal.Cover.Mode |
| 705 |
if mode == "" { |
| 706 |
panic("covermode should be set at this point") |
| 707 |
} |
| 708 |
if newoutfiles, err := b.cover(a, infiles, outfiles, coverVar, mode); err != nil { |
| 709 |
return nil, err |
| 710 |
} else { |
| 711 |
outfiles = newoutfiles |
| 712 |
gofiles = append([]string{newoutfiles[0]}, gofiles...) |
| 713 |
} |
| 714 |
if ca, ok := a.Actor.(*coverActor); ok && ca.covMetaFileName != "" { |
| 715 |
b.cacheObjdirFile(buildAction, cache.Default(), ca.covMetaFileName) |
| 716 |
} |
| 717 |
} |
| 718 |
return &coverProvider{gofiles, cgofiles}, nil |
| 719 |
} |
| 720 |
|
| 721 |
// build is the action for building a single package. |
| 722 |
// Note that any new influence on this logic must be reported in b.buildActionID above as well. |
| 723 |
func (b *Builder) build(ctx context.Context, a *Action) (err error) { |
| 724 |
p := a.Package |
| 725 |
sh := b.Shell(a) |
| 726 |
|
| 727 |
var cacheProvider *checkCacheProvider |
| 728 |
var coverPr *coverProvider |
| 729 |
var runCgoPr *runCgoProvider |
| 730 |
for _, dep := range a.Deps { |
| 731 |
switch pr := dep.Provider.(type) { |
| 732 |
case *coverProvider: |
| 733 |
coverPr = pr |
| 734 |
case *checkCacheProvider: |
| 735 |
cacheProvider = pr |
| 736 |
case *runCgoProvider: |
| 737 |
runCgoPr = pr |
| 738 |
} |
| 739 |
} |
| 740 |
if cacheProvider == nil { |
| 741 |
base.Fatalf("internal error: could not find checkCacheProvider") |
| 742 |
} |
| 743 |
|
| 744 |
need := cacheProvider.need |
| 745 |
need &^= needCovMetaFile // handled by cover action |
| 746 |
need &^= needCgoHdr // handled by run cgo action // TODO: accumulate "negative" need bits from actions |
| 747 |
|
| 748 |
if need == 0 { |
| 749 |
return |
| 750 |
} |
| 751 |
defer b.flushOutput(a) |
| 752 |
|
| 753 |
if cfg.BuildN { |
| 754 |
// In -n mode, print a banner between packages. |
| 755 |
// The banner is five lines so that when changes to |
| 756 |
// different sections of the bootstrap script have to |
| 757 |
// be merged, the banners give patch something |
| 758 |
// to use to find its context. |
| 759 |
sh.Printf("\n#\n# %s\n#\n\n", p.ImportPath) |
| 760 |
} |
| 761 |
|
| 762 |
if cfg.BuildV { |
| 763 |
sh.Printf("%s\n", p.ImportPath) |
| 764 |
} |
| 765 |
|
| 766 |
objdir := a.Objdir |
| 767 |
|
| 768 |
if err := AllowInstall(a); err != nil { |
| 769 |
return err |
| 770 |
} |
| 771 |
|
| 772 |
// make target directory |
| 773 |
dir, _ := filepath.Split(a.Target) |
| 774 |
if dir != "" { |
| 775 |
if err := sh.Mkdir(dir); err != nil { |
| 776 |
return err |
| 777 |
} |
| 778 |
} |
| 779 |
|
| 780 |
gofiles := str.StringList(p.GoFiles) |
| 781 |
cfiles := str.StringList(p.CFiles) |
| 782 |
sfiles := str.StringList(p.SFiles) |
| 783 |
var objects, cgoObjects []string |
| 784 |
|
| 785 |
// If we're doing coverage, preprocess the .go files and put them in the work directory |
| 786 |
if p.Internal.Cover.Mode != "" { |
| 787 |
gofiles = coverPr.goSources |
| 788 |
} |
| 789 |
|
| 790 |
if p.UsesCgo() || p.UsesSwig() { |
| 791 |
if runCgoPr == nil { |
| 792 |
base.Fatalf("internal error: could not find runCgoProvider") |
| 793 |
} |
| 794 |
|
| 795 |
// In a package using cgo, cgo compiles the C, C++ and assembly files with gcc. |
| 796 |
// There is one exception: runtime/cgo's job is to bridge the |
| 797 |
// cgo and non-cgo worlds, so it necessarily has files in both. |
| 798 |
// In that case gcc only gets the gcc_* files. |
| 799 |
cfiles = nil |
| 800 |
if p.Standard && p.ImportPath == "runtime/cgo" { |
| 801 |
// filter to the non-gcc files. |
| 802 |
i := 0 |
| 803 |
for _, f := range sfiles { |
| 804 |
if !strings.HasPrefix(f, "gcc_") { |
| 805 |
sfiles[i] = f |
| 806 |
i++ |
| 807 |
} |
| 808 |
} |
| 809 |
sfiles = sfiles[:i] |
| 810 |
} else { |
| 811 |
sfiles = nil |
| 812 |
} |
| 813 |
|
| 814 |
outGo, outObj, err := b.processCgoOutputs(a, runCgoPr, base.Tool("cgo"), objdir) |
| 815 |
|
| 816 |
if err != nil { |
| 817 |
return err |
| 818 |
} |
| 819 |
if cfg.BuildToolchainName == "gccgo" { |
| 820 |
cgoObjects = append(cgoObjects, a.Objdir+"_cgo_flags") |
| 821 |
} |
| 822 |
cgoObjects = append(cgoObjects, outObj...) |
| 823 |
gofiles = append(gofiles, outGo...) |
| 824 |
|
| 825 |
switch cfg.BuildBuildmode { |
| 826 |
case "c-archive", "c-shared": |
| 827 |
b.cacheCgoHdr(a) |
| 828 |
} |
| 829 |
} |
| 830 |
|
| 831 |
var srcfiles []string // .go and non-.go |
| 832 |
srcfiles = append(srcfiles, gofiles...) |
| 833 |
srcfiles = append(srcfiles, sfiles...) |
| 834 |
srcfiles = append(srcfiles, cfiles...) |
| 835 |
b.cacheSrcFiles(a, srcfiles) |
| 836 |
|
| 837 |
// Sanity check only, since Package.load already checked as well. |
| 838 |
if len(gofiles) == 0 { |
| 839 |
return &load.NoGoError{Package: p} |
| 840 |
} |
| 841 |
|
| 842 |
// Prepare Go vet config if needed. |
| 843 |
if need&needVet != 0 { |
| 844 |
buildVetConfig(a, srcfiles, a.Deps) |
| 845 |
need &^= needVet |
| 846 |
} |
| 847 |
if need&needCompiledGoFiles != 0 { |
| 848 |
if err := b.loadCachedCompiledGoFiles(a); err != nil { |
| 849 |
return fmt.Errorf("loading compiled Go files from cache: %w", err) |
| 850 |
} |
| 851 |
need &^= needCompiledGoFiles |
| 852 |
} |
| 853 |
if need == 0 { |
| 854 |
// Nothing left to do. |
| 855 |
return nil |
| 856 |
} |
| 857 |
|
| 858 |
// Collect symbol ABI requirements from assembly. |
| 859 |
symabis, err := BuildToolchain.symabis(b, a, sfiles) |
| 860 |
if err != nil { |
| 861 |
return err |
| 862 |
} |
| 863 |
|
| 864 |
// Prepare Go import config. |
| 865 |
// We start it off with a comment so it can't be empty, so icfg.Bytes() below is never nil. |
| 866 |
// It should never be empty anyway, but there have been bugs in the past that resulted |
| 867 |
// in empty configs, which then unfortunately turn into "no config passed to compiler", |
| 868 |
// and the compiler falls back to looking in pkg itself, which mostly works, |
| 869 |
// except when it doesn't. |
| 870 |
var icfg bytes.Buffer |
| 871 |
fmt.Fprintf(&icfg, "# import config\n") |
| 872 |
for i, raw := range p.Internal.RawImports { |
| 873 |
final := p.Imports[i] |
| 874 |
if final != raw { |
| 875 |
fmt.Fprintf(&icfg, "importmap %s=%s\n", raw, final) |
| 876 |
} |
| 877 |
} |
| 878 |
for _, a1 := range a.Deps { |
| 879 |
p1 := a1.Package |
| 880 |
if p1 == nil || p1.ImportPath == "" || a1.built == "" { |
| 881 |
continue |
| 882 |
} |
| 883 |
fmt.Fprintf(&icfg, "packagefile %s=%s\n", p1.ImportPath, a1.built) |
| 884 |
} |
| 885 |
|
| 886 |
// Prepare Go embed config if needed. |
| 887 |
// Unlike the import config, it's okay for the embed config to be empty. |
| 888 |
var embedcfg []byte |
| 889 |
if len(p.Internal.Embed) > 0 { |
| 890 |
var embed struct { |
| 891 |
Patterns map[string][]string |
| 892 |
Files map[string]string |
| 893 |
} |
| 894 |
embed.Patterns = p.Internal.Embed |
| 895 |
embed.Files = make(map[string]string) |
| 896 |
for _, file := range p.EmbedFiles { |
| 897 |
embed.Files[file] = fsys.Actual(filepath.Join(p.Dir, file)) |
| 898 |
} |
| 899 |
js, err := json.MarshalIndent(&embed, "", "\t") |
| 900 |
if err != nil { |
| 901 |
return fmt.Errorf("marshal embedcfg: %v", err) |
| 902 |
} |
| 903 |
embedcfg = js |
| 904 |
} |
| 905 |
|
| 906 |
// Find PGO profile if needed. |
| 907 |
var pgoProfile string |
| 908 |
for _, a1 := range a.Deps { |
| 909 |
if a1.Mode != "preprocess PGO profile" { |
| 910 |
continue |
| 911 |
} |
| 912 |
if pgoProfile != "" { |
| 913 |
return fmt.Errorf("action contains multiple PGO profile dependencies") |
| 914 |
} |
| 915 |
pgoProfile = a1.built |
| 916 |
} |
| 917 |
|
| 918 |
if p.Internal.BuildInfo != nil && cfg.ModulesEnabled { |
| 919 |
prog := modload.ModInfoProg(p.Internal.BuildInfo.String(), cfg.BuildToolchainName == "gccgo") |
| 920 |
if len(prog) > 0 { |
| 921 |
if err := sh.writeFile(objdir+"_gomod_.go", prog); err != nil { |
| 922 |
return err |
| 923 |
} |
| 924 |
gofiles = append(gofiles, objdir+"_gomod_.go") |
| 925 |
} |
| 926 |
} |
| 927 |
|
| 928 |
// Compile Go. |
| 929 |
objpkg := objdir + "_pkg_.a" |
| 930 |
ofile, out, err := BuildToolchain.gc(b, a, objpkg, icfg.Bytes(), embedcfg, symabis, len(sfiles) > 0, pgoProfile, gofiles) |
| 931 |
if err := sh.reportCmd("", "", out, err); err != nil { |
| 932 |
return err |
| 933 |
} |
| 934 |
if ofile != objpkg { |
| 935 |
objects = append(objects, ofile) |
| 936 |
} |
| 937 |
|
| 938 |
// Copy .h files named for goos or goarch or goos_goarch |
| 939 |
// to names using GOOS and GOARCH. |
| 940 |
// For example, defs_linux_amd64.h becomes defs_GOOS_GOARCH.h. |
| 941 |
_goos_goarch := "_" + cfg.Goos + "_" + cfg.Goarch |
| 942 |
_goos := "_" + cfg.Goos |
| 943 |
_goarch := "_" + cfg.Goarch |
| 944 |
for _, file := range p.HFiles { |
| 945 |
name, ext := fileExtSplit(file) |
| 946 |
switch { |
| 947 |
case strings.HasSuffix(name, _goos_goarch): |
| 948 |
targ := file[:len(name)-len(_goos_goarch)] + "_GOOS_GOARCH." + ext |
| 949 |
if err := sh.CopyFile(objdir+targ, filepath.Join(p.Dir, file), 0666, true); err != nil { |
| 950 |
return err |
| 951 |
} |
| 952 |
case strings.HasSuffix(name, _goarch): |
| 953 |
targ := file[:len(name)-len(_goarch)] + "_GOARCH." + ext |
| 954 |
if err := sh.CopyFile(objdir+targ, filepath.Join(p.Dir, file), 0666, true); err != nil { |
| 955 |
return err |
| 956 |
} |
| 957 |
case strings.HasSuffix(name, _goos): |
| 958 |
targ := file[:len(name)-len(_goos)] + "_GOOS." + ext |
| 959 |
if err := sh.CopyFile(objdir+targ, filepath.Join(p.Dir, file), 0666, true); err != nil { |
| 960 |
return err |
| 961 |
} |
| 962 |
} |
| 963 |
} |
| 964 |
|
| 965 |
if err := b.computeNonGoOverlay(a, p, sh, objdir, [][]string{cfiles}); err != nil { |
| 966 |
return err |
| 967 |
} |
| 968 |
|
| 969 |
// Compile C files in a package being built with gccgo. We disallow |
| 970 |
// C files when compiling with gc unless swig or cgo is used. |
| 971 |
for _, file := range cfiles { |
| 972 |
out := file[:len(file)-len(".c")] + ".o" |
| 973 |
if err := BuildToolchain.cc(b, a, objdir+out, file); err != nil { |
| 974 |
return err |
| 975 |
} |
| 976 |
objects = append(objects, out) |
| 977 |
} |
| 978 |
|
| 979 |
// Assemble .s files. |
| 980 |
if len(sfiles) > 0 { |
| 981 |
ofiles, err := BuildToolchain.asm(b, a, sfiles) |
| 982 |
if err != nil { |
| 983 |
return err |
| 984 |
} |
| 985 |
objects = append(objects, ofiles...) |
| 986 |
} |
| 987 |
|
| 988 |
// For gccgo on ELF systems, we write the build ID as an assembler file. |
| 989 |
// This lets us set the SHF_EXCLUDE flag. |
| 990 |
// This is read by readGccgoArchive in cmd/internal/buildid/buildid.go. |
| 991 |
if a.buildID != "" && cfg.BuildToolchainName == "gccgo" { |
| 992 |
switch cfg.Goos { |
| 993 |
case "aix", "android", "dragonfly", "freebsd", "illumos", "linux", "netbsd", "openbsd", "solaris": |
| 994 |
asmfile, err := b.gccgoBuildIDFile(a) |
| 995 |
if err != nil { |
| 996 |
return err |
| 997 |
} |
| 998 |
ofiles, err := BuildToolchain.asm(b, a, []string{asmfile}) |
| 999 |
if err != nil { |
| 1000 |
return err |
| 1001 |
} |
| 1002 |
objects = append(objects, ofiles...) |
| 1003 |
} |
| 1004 |
} |
| 1005 |
|
| 1006 |
// NOTE(rsc): On Windows, it is critically important that the |
| 1007 |
// gcc-compiled objects (cgoObjects) be listed after the ordinary |
| 1008 |
// objects in the archive. I do not know why this is. |
| 1009 |
// https://golang.org/issue/2601 |
| 1010 |
objects = append(objects, cgoObjects...) |
| 1011 |
|
| 1012 |
// Add system object files. |
| 1013 |
for _, syso := range p.SysoFiles { |
| 1014 |
objects = append(objects, filepath.Join(p.Dir, syso)) |
| 1015 |
} |
| 1016 |
|
| 1017 |
// Pack into archive in objdir directory. |
| 1018 |
// If the Go compiler wrote an archive, we only need to add the |
| 1019 |
// object files for non-Go sources to the archive. |
| 1020 |
// If the Go compiler wrote an archive and the package is entirely |
| 1021 |
// Go sources, there is no pack to execute at all. |
| 1022 |
if len(objects) > 0 { |
| 1023 |
if err := BuildToolchain.pack(b, a, objpkg, objects); err != nil { |
| 1024 |
return err |
| 1025 |
} |
| 1026 |
} |
| 1027 |
|
| 1028 |
if err := b.updateBuildID(a, objpkg); err != nil { |
| 1029 |
return err |
| 1030 |
} |
| 1031 |
|
| 1032 |
a.built = objpkg |
| 1033 |
return nil |
| 1034 |
} |
| 1035 |
|
| 1036 |
func (b *Builder) checkDirectives(a *Action) error { |
| 1037 |
var msg []byte |
| 1038 |
p := a.Package |
| 1039 |
var seen map[string]token.Position |
| 1040 |
for _, d := range p.Internal.Build.Directives { |
| 1041 |
if strings.HasPrefix(d.Text, "//go:debug") { |
| 1042 |
key, _, err := load.ParseGoDebug(d.Text) |
| 1043 |
if err != nil && err != load.ErrNotGoDebug { |
| 1044 |
msg = fmt.Appendf(msg, "%s: invalid //go:debug: %v\n", d.Pos, err) |
| 1045 |
continue |
| 1046 |
} |
| 1047 |
if pos, ok := seen[key]; ok { |
| 1048 |
msg = fmt.Appendf(msg, "%s: repeated //go:debug for %v\n\t%s: previous //go:debug\n", d.Pos, key, pos) |
| 1049 |
continue |
| 1050 |
} |
| 1051 |
if seen == nil { |
| 1052 |
seen = make(map[string]token.Position) |
| 1053 |
} |
| 1054 |
seen[key] = d.Pos |
| 1055 |
} |
| 1056 |
} |
| 1057 |
if len(msg) > 0 { |
| 1058 |
// We pass a non-nil error to reportCmd to trigger the failure reporting |
| 1059 |
// path, but the content of the error doesn't matter because msg is |
| 1060 |
// non-empty. |
| 1061 |
err := errors.New("invalid directive") |
| 1062 |
return b.Shell(a).reportCmd("", "", msg, err) |
| 1063 |
} |
| 1064 |
return nil |
| 1065 |
} |
| 1066 |
|
| 1067 |
func (b *Builder) cacheObjdirFile(a *Action, c cache.Cache, name string) error { |
| 1068 |
f, err := os.Open(a.Objdir + name) |
| 1069 |
if err != nil { |
| 1070 |
return err |
| 1071 |
} |
| 1072 |
defer f.Close() |
| 1073 |
_, _, err = c.Put(cache.Subkey(a.actionID, name), f) |
| 1074 |
return err |
| 1075 |
} |
| 1076 |
|
| 1077 |
func (b *Builder) findCachedObjdirFile(a *Action, c cache.Cache, name string) (string, error) { |
| 1078 |
file, _, err := cache.GetFile(c, cache.Subkey(a.actionID, name)) |
| 1079 |
if err != nil { |
| 1080 |
return "", fmt.Errorf("loading cached file %s: %w", name, err) |
| 1081 |
} |
| 1082 |
return file, nil |
| 1083 |
} |
| 1084 |
|
| 1085 |
func (b *Builder) loadCachedObjdirFile(a *Action, c cache.Cache, name string) error { |
| 1086 |
cached, err := b.findCachedObjdirFile(a, c, name) |
| 1087 |
if err != nil { |
| 1088 |
return err |
| 1089 |
} |
| 1090 |
return b.Shell(a).CopyFile(a.Objdir+name, cached, 0666, true) |
| 1091 |
} |
| 1092 |
|
| 1093 |
func (b *Builder) cacheCgoHdr(a *Action) { |
| 1094 |
c := cache.Default() |
| 1095 |
b.cacheObjdirFile(a, c, "_cgo_install.h") |
| 1096 |
} |
| 1097 |
|
| 1098 |
func (b *Builder) loadCachedCgoHdr(a *Action) error { |
| 1099 |
c := cache.Default() |
| 1100 |
return b.loadCachedObjdirFile(a, c, "_cgo_install.h") |
| 1101 |
} |
| 1102 |
|
| 1103 |
func (b *Builder) cacheSrcFiles(a *Action, srcfiles []string) { |
| 1104 |
c := cache.Default() |
| 1105 |
var buf bytes.Buffer |
| 1106 |
for _, file := range srcfiles { |
| 1107 |
if !strings.HasPrefix(file, a.Objdir) { |
| 1108 |
// not generated |
| 1109 |
buf.WriteString("./") |
| 1110 |
buf.WriteString(file) |
| 1111 |
buf.WriteString("\n") |
| 1112 |
continue |
| 1113 |
} |
| 1114 |
name := file[len(a.Objdir):] |
| 1115 |
buf.WriteString(name) |
| 1116 |
buf.WriteString("\n") |
| 1117 |
if err := b.cacheObjdirFile(a, c, name); err != nil { |
| 1118 |
return |
| 1119 |
} |
| 1120 |
} |
| 1121 |
cache.PutBytes(c, cache.Subkey(a.actionID, "srcfiles"), buf.Bytes()) |
| 1122 |
} |
| 1123 |
|
| 1124 |
func (b *Builder) loadCachedVet(a *Action, vetDeps []*Action) error { |
| 1125 |
c := cache.Default() |
| 1126 |
list, _, err := cache.GetBytes(c, cache.Subkey(a.actionID, "srcfiles")) |
| 1127 |
if err != nil { |
| 1128 |
return fmt.Errorf("reading srcfiles list: %w", err) |
| 1129 |
} |
| 1130 |
var srcfiles []string |
| 1131 |
for name := range strings.SplitSeq(string(list), "\n") { |
| 1132 |
if name == "" { // end of list |
| 1133 |
continue |
| 1134 |
} |
| 1135 |
if strings.HasPrefix(name, "./") { |
| 1136 |
srcfiles = append(srcfiles, name[2:]) |
| 1137 |
continue |
| 1138 |
} |
| 1139 |
if err := b.loadCachedObjdirFile(a, c, name); err != nil { |
| 1140 |
return err |
| 1141 |
} |
| 1142 |
srcfiles = append(srcfiles, a.Objdir+name) |
| 1143 |
} |
| 1144 |
buildVetConfig(a, srcfiles, vetDeps) |
| 1145 |
return nil |
| 1146 |
} |
| 1147 |
|
| 1148 |
func (b *Builder) loadCachedCompiledGoFiles(a *Action) error { |
| 1149 |
c := cache.Default() |
| 1150 |
list, _, err := cache.GetBytes(c, cache.Subkey(a.actionID, "srcfiles")) |
| 1151 |
if err != nil { |
| 1152 |
return fmt.Errorf("reading srcfiles list: %w", err) |
| 1153 |
} |
| 1154 |
var gofiles []string |
| 1155 |
for name := range strings.SplitSeq(string(list), "\n") { |
| 1156 |
if name == "" { // end of list |
| 1157 |
continue |
| 1158 |
} else if !strings.HasSuffix(name, ".go") { |
| 1159 |
continue |
| 1160 |
} |
| 1161 |
if strings.HasPrefix(name, "./") { |
| 1162 |
gofiles = append(gofiles, name[len("./"):]) |
| 1163 |
continue |
| 1164 |
} |
| 1165 |
file, err := b.findCachedObjdirFile(a, c, name) |
| 1166 |
if err != nil { |
| 1167 |
return fmt.Errorf("finding %s: %w", name, err) |
| 1168 |
} |
| 1169 |
gofiles = append(gofiles, file) |
| 1170 |
} |
| 1171 |
a.Package.CompiledGoFiles = gofiles |
| 1172 |
return nil |
| 1173 |
} |
| 1174 |
|
| 1175 |
// vetConfig is the configuration passed to vet describing a single package. |
| 1176 |
type vetConfig struct { |
| 1177 |
ID string // package ID (example: "fmt [fmt.test]") |
| 1178 |
Compiler string // compiler name (gc, gccgo) |
| 1179 |
Dir string // directory containing package |
| 1180 |
ImportPath string // canonical import path ("package path") |
| 1181 |
GoFiles []string // absolute paths to package source files |
| 1182 |
NonGoFiles []string // absolute paths to package non-Go files |
| 1183 |
IgnoredFiles []string // absolute paths to ignored source files |
| 1184 |
|
| 1185 |
ModulePath string // module path (may be "" on module error) |
| 1186 |
ModuleVersion string // module version (may be "" on main module or module error) |
| 1187 |
ImportMap map[string]string // map import path in source code to package path |
| 1188 |
PackageFile map[string]string // map package path to .a file with export data |
| 1189 |
Standard map[string]bool // map package path to whether it's in the standard library |
| 1190 |
PackageVetx map[string]string // map package path to vetx data from earlier vet run |
| 1191 |
VetxOnly bool // only compute vetx data; don't report detected problems |
| 1192 |
VetxOutput string // write vetx data to this output file |
| 1193 |
Stdout string // write stdout (JSON, unified diff) to this output file |
| 1194 |
GoVersion string // Go version for package |
| 1195 |
FixArchive string // write fixed files to this zip archive, if non-empty |
| 1196 |
|
| 1197 |
SucceedOnTypecheckFailure bool // awful hack; see #18395 and below |
| 1198 |
} |
| 1199 |
|
| 1200 |
func buildVetConfig(a *Action, srcfiles []string, vetDeps []*Action) { |
| 1201 |
// Classify files based on .go extension. |
| 1202 |
// srcfiles does not include raw cgo files. |
| 1203 |
var gofiles, nongofiles []string |
| 1204 |
for _, name := range srcfiles { |
| 1205 |
if strings.HasSuffix(name, ".go") { |
| 1206 |
gofiles = append(gofiles, name) |
| 1207 |
} else { |
| 1208 |
nongofiles = append(nongofiles, name) |
| 1209 |
} |
| 1210 |
} |
| 1211 |
|
| 1212 |
ignored := str.StringList(a.Package.IgnoredGoFiles, a.Package.IgnoredOtherFiles) |
| 1213 |
|
| 1214 |
// Pass list of absolute paths to vet, |
| 1215 |
// so that vet's error messages will use absolute paths, |
| 1216 |
// so that we can reformat them relative to the directory |
| 1217 |
// in which the go command is invoked. |
| 1218 |
vcfg := &vetConfig{ |
| 1219 |
ID: a.Package.ImportPath, |
| 1220 |
Compiler: cfg.BuildToolchainName, |
| 1221 |
Dir: a.Package.Dir, |
| 1222 |
GoFiles: actualFiles(mkAbsFiles(a.Package.Dir, gofiles)), |
| 1223 |
NonGoFiles: actualFiles(mkAbsFiles(a.Package.Dir, nongofiles)), |
| 1224 |
IgnoredFiles: actualFiles(mkAbsFiles(a.Package.Dir, ignored)), |
| 1225 |
ImportPath: a.Package.ImportPath, |
| 1226 |
ImportMap: make(map[string]string), |
| 1227 |
PackageFile: make(map[string]string), |
| 1228 |
Standard: make(map[string]bool), |
| 1229 |
} |
| 1230 |
vcfg.GoVersion = "go" + gover.Local() |
| 1231 |
if a.Package.Module != nil { |
| 1232 |
v := a.Package.Module.GoVersion |
| 1233 |
if v == "" { |
| 1234 |
v = gover.DefaultGoModVersion |
| 1235 |
} |
| 1236 |
vcfg.GoVersion = "go" + v |
| 1237 |
|
| 1238 |
if a.Package.Module.Error == nil { |
| 1239 |
vcfg.ModulePath = a.Package.Module.Path |
| 1240 |
vcfg.ModuleVersion = a.Package.Module.Version |
| 1241 |
} |
| 1242 |
} |
| 1243 |
a.vetCfg = vcfg |
| 1244 |
for i, raw := range a.Package.Internal.RawImports { |
| 1245 |
final := a.Package.Imports[i] |
| 1246 |
vcfg.ImportMap[raw] = final |
| 1247 |
} |
| 1248 |
|
| 1249 |
// Compute the list of mapped imports in the vet config |
| 1250 |
// so that we can add any missing mappings below. |
| 1251 |
vcfgMapped := make(map[string]bool) |
| 1252 |
for _, p := range vcfg.ImportMap { |
| 1253 |
vcfgMapped[p] = true |
| 1254 |
} |
| 1255 |
|
| 1256 |
for _, a1 := range vetDeps { |
| 1257 |
p1 := a1.Package |
| 1258 |
if p1 == nil || p1.ImportPath == "" || p1 == a.Package { |
| 1259 |
continue |
| 1260 |
} |
| 1261 |
// Add import mapping if needed |
| 1262 |
// (for imports like "runtime/cgo" that appear only in generated code). |
| 1263 |
if !vcfgMapped[p1.ImportPath] { |
| 1264 |
vcfg.ImportMap[p1.ImportPath] = p1.ImportPath |
| 1265 |
} |
| 1266 |
if a1.built != "" { |
| 1267 |
vcfg.PackageFile[p1.ImportPath] = a1.built |
| 1268 |
} |
| 1269 |
if p1.Standard { |
| 1270 |
vcfg.Standard[p1.ImportPath] = true |
| 1271 |
} |
| 1272 |
} |
| 1273 |
} |
| 1274 |
|
| 1275 |
// VetTool is the path to the effective vet or fix tool binary. |
| 1276 |
// The user may specify a non-default value using -{vet,fix}tool. |
| 1277 |
// The caller is expected to set it (if needed) before executing any vet actions. |
| 1278 |
var VetTool string |
| 1279 |
|
| 1280 |
// VetFlags are the default flags to pass to vet. |
| 1281 |
// The caller is expected to set them before executing any vet actions. |
| 1282 |
var VetFlags []string |
| 1283 |
|
| 1284 |
// VetHandleStdout determines how the stdout output of each vet tool |
| 1285 |
// invocation should be handled. The default behavior is to copy it to |
| 1286 |
// the go command's stdout, atomically. |
| 1287 |
var VetHandleStdout = copyToStdout |
| 1288 |
|
| 1289 |
// VetExplicit records whether the vet flags (which may include |
| 1290 |
// -{vet,fix}tool) were set explicitly on the command line. |
| 1291 |
var VetExplicit bool |
| 1292 |
|
| 1293 |
func (b *Builder) vet(ctx context.Context, a *Action) error { |
| 1294 |
// a.Deps[0] is the build of the package being vetted. |
| 1295 |
|
| 1296 |
a.Failed = nil // vet of dependency may have failed but we can still succeed |
| 1297 |
|
| 1298 |
if a.Deps[0].Failed != nil { |
| 1299 |
// The build of the package has failed. Skip vet check. |
| 1300 |
// Vet could return export data for non-typecheck errors, |
| 1301 |
// but we ignore it because the package cannot be compiled. |
| 1302 |
return nil |
| 1303 |
} |
| 1304 |
|
| 1305 |
vcfg := a.Deps[0].vetCfg |
| 1306 |
if vcfg == nil { |
| 1307 |
// Vet config should only be missing if the build failed. |
| 1308 |
return fmt.Errorf("vet config not found") |
| 1309 |
} |
| 1310 |
|
| 1311 |
sh := b.Shell(a) |
| 1312 |
|
| 1313 |
// We use "vet" terminology even when building action graphs for go fix. |
| 1314 |
vcfg.VetxOnly = a.VetxOnly |
| 1315 |
vcfg.VetxOutput = a.Objdir + "vet.out" |
| 1316 |
vcfg.Stdout = a.Objdir + "vet.stdout" |
| 1317 |
if a.needFix { |
| 1318 |
vcfg.FixArchive = a.Objdir + "vet.fix.zip" |
| 1319 |
} |
| 1320 |
vcfg.PackageVetx = make(map[string]string) |
| 1321 |
|
| 1322 |
h := cache.NewHash("vet " + a.Package.ImportPath) |
| 1323 |
fmt.Fprintf(h, "vet %q\n", b.toolID("vet")) |
| 1324 |
|
| 1325 |
vetFlags := VetFlags |
| 1326 |
|
| 1327 |
// In GOROOT, we enable all the vet tests during 'go test', |
| 1328 |
// not just the high-confidence subset. This gets us extra |
| 1329 |
// checking for the standard library (at some compliance cost) |
| 1330 |
// and helps us gain experience about how well the checks |
| 1331 |
// work, to help decide which should be turned on by default. |
| 1332 |
// The command-line still wins. |
| 1333 |
// |
| 1334 |
// Note that this flag change applies even when running vet as |
| 1335 |
// a dependency of vetting a package outside std. |
| 1336 |
// (Otherwise we'd have to introduce a whole separate |
| 1337 |
// space of "vet fmt as a dependency of a std top-level vet" |
| 1338 |
// versus "vet fmt as a dependency of a non-std top-level vet".) |
| 1339 |
// This is OK as long as the packages that are farther down the |
| 1340 |
// dependency tree turn on *more* analysis, as here. |
| 1341 |
// (The unsafeptr check does not write any facts for use by |
| 1342 |
// later vet runs, nor does unreachable.) |
| 1343 |
if a.Package.Goroot && !VetExplicit && VetTool == base.Tool("vet") { |
| 1344 |
// Turn off -unsafeptr checks. |
| 1345 |
// There's too much unsafe.Pointer code |
| 1346 |
// that vet doesn't like in low-level packages |
| 1347 |
// like runtime, sync, and reflect. |
| 1348 |
// Note that $GOROOT/src/buildall.bash |
| 1349 |
// does the same |
| 1350 |
// and should be updated if these flags are |
| 1351 |
// changed here. |
| 1352 |
vetFlags = []string{"-unsafeptr=false"} |
| 1353 |
|
| 1354 |
// Also turn off -unreachable checks during go test. |
| 1355 |
// During testing it is very common to make changes |
| 1356 |
// like hard-coded forced returns or panics that make |
| 1357 |
// code unreachable. It's unreasonable to insist on files |
| 1358 |
// not having any unreachable code during "go test". |
| 1359 |
// (buildall.bash still has -unreachable enabled |
| 1360 |
// for the overall whole-tree scan.) |
| 1361 |
if cfg.CmdName == "test" { |
| 1362 |
vetFlags = append(vetFlags, "-unreachable=false") |
| 1363 |
} |
| 1364 |
} |
| 1365 |
|
| 1366 |
// Note: We could decide that vet should compute export data for |
| 1367 |
// all analyses, in which case we don't need to include the flags here. |
| 1368 |
// But that would mean that if an analysis causes problems like |
| 1369 |
// unexpected crashes there would be no way to turn it off. |
| 1370 |
// It seems better to let the flags disable export analysis too. |
| 1371 |
fmt.Fprintf(h, "vetflags %q\n", vetFlags) |
| 1372 |
|
| 1373 |
fmt.Fprintf(h, "pkg %q\n", a.Deps[0].actionID) |
| 1374 |
for _, a1 := range a.Deps { |
| 1375 |
if a1.Mode == "vet" && a1.built != "" { |
| 1376 |
fmt.Fprintf(h, "vetout %q %s\n", a1.Package.ImportPath, b.fileHash(a1.built)) |
| 1377 |
vcfg.PackageVetx[a1.Package.ImportPath] = a1.built |
| 1378 |
} |
| 1379 |
} |
| 1380 |
var ( |
| 1381 |
id = cache.ActionID(h.Sum()) // for .vetx file |
| 1382 |
stdoutKey = cache.Subkey(id, "stdout") // for .stdout file |
| 1383 |
fixArchiveKey = cache.Subkey(id, "fix.zip") // for .fix.zip file |
| 1384 |
) |
| 1385 |
|
| 1386 |
// Check the cache; -a forces a rebuild. |
| 1387 |
if !cfg.BuildA { |
| 1388 |
c := cache.Default() |
| 1389 |
|
| 1390 |
// There may be multiple artifacts in the cache. |
| 1391 |
// We need to retrieve them all, or none: |
| 1392 |
// the effect must be transactional. |
| 1393 |
var ( |
| 1394 |
vetxFile string // name of cached .vetx file |
| 1395 |
fixArchive string // name of cached .fix.zip file |
| 1396 |
stdout io.Reader = bytes.NewReader(nil) // cached stdout stream |
| 1397 |
) |
| 1398 |
|
| 1399 |
// Obtain location of cached .vetx file. |
| 1400 |
vetxFile, _, err := cache.GetFile(c, id) |
| 1401 |
if err != nil { |
| 1402 |
goto cachemiss |
| 1403 |
} |
| 1404 |
|
| 1405 |
// Obtain location of cached .fix.zip file (if needed). |
| 1406 |
if a.needFix { |
| 1407 |
file, _, err := cache.GetFile(c, fixArchiveKey) |
| 1408 |
if err != nil { |
| 1409 |
goto cachemiss |
| 1410 |
} |
| 1411 |
fixArchive = file |
| 1412 |
} |
| 1413 |
|
| 1414 |
// Copy cached .stdout file to stdout. |
| 1415 |
if file, _, err := cache.GetFile(c, stdoutKey); err == nil { |
| 1416 |
f, err := os.Open(file) |
| 1417 |
if err != nil { |
| 1418 |
goto cachemiss |
| 1419 |
} |
| 1420 |
defer f.Close() // ignore error (can't fail) |
| 1421 |
stdout = f |
| 1422 |
} |
| 1423 |
|
| 1424 |
// Cache hit: commit transaction. |
| 1425 |
a.built = vetxFile |
| 1426 |
a.FixArchive = fixArchive |
| 1427 |
if err := VetHandleStdout(stdout); err != nil { |
| 1428 |
return err // internal error (don't fall through to cachemiss) |
| 1429 |
} |
| 1430 |
|
| 1431 |
return nil |
| 1432 |
} |
| 1433 |
cachemiss: |
| 1434 |
|
| 1435 |
js, err := json.MarshalIndent(vcfg, "", "\t") |
| 1436 |
if err != nil { |
| 1437 |
return fmt.Errorf("internal error marshaling vet config: %v", err) |
| 1438 |
} |
| 1439 |
js = append(js, '\n') |
| 1440 |
if err := sh.writeFile(a.Objdir+"vet.cfg", js); err != nil { |
| 1441 |
return err |
| 1442 |
} |
| 1443 |
|
| 1444 |
// TODO(rsc): Why do we pass $GCCGO to go vet? |
| 1445 |
env := b.cCompilerEnv() |
| 1446 |
if cfg.BuildToolchainName == "gccgo" { |
| 1447 |
env = append(env, "GCCGO="+BuildToolchain.compiler()) |
| 1448 |
} |
| 1449 |
|
| 1450 |
p := a.Package |
| 1451 |
tool := VetTool |
| 1452 |
if tool == "" { |
| 1453 |
panic("VetTool unset") |
| 1454 |
} |
| 1455 |
|
| 1456 |
if err := sh.run(p.Dir, p.ImportPath, env, cfg.BuildToolexec, tool, vetFlags, a.Objdir+"vet.cfg"); err != nil { |
| 1457 |
return err |
| 1458 |
} |
| 1459 |
|
| 1460 |
// Vet tool succeeded, possibly with facts, fixes, or JSON stdout. |
| 1461 |
// Save all in cache. |
| 1462 |
|
| 1463 |
// Save facts. |
| 1464 |
if f, err := os.Open(vcfg.VetxOutput); err == nil { |
| 1465 |
defer f.Close() // ignore error |
| 1466 |
a.built = vcfg.VetxOutput |
| 1467 |
cache.Default().Put(id, f) // ignore error |
| 1468 |
} |
| 1469 |
|
| 1470 |
// Save fix archive (if any). |
| 1471 |
if a.needFix { |
| 1472 |
if f, err := os.Open(vcfg.FixArchive); err == nil { |
| 1473 |
defer f.Close() // ignore error |
| 1474 |
a.FixArchive = vcfg.FixArchive |
| 1475 |
cache.Default().Put(fixArchiveKey, f) // ignore error |
| 1476 |
} |
| 1477 |
} |
| 1478 |
|
| 1479 |
// Save stdout. |
| 1480 |
if f, err := os.Open(vcfg.Stdout); err == nil { |
| 1481 |
defer f.Close() // ignore error |
| 1482 |
if err := VetHandleStdout(f); err != nil { |
| 1483 |
return err |
| 1484 |
} |
| 1485 |
f.Seek(0, io.SeekStart) // ignore error |
| 1486 |
cache.Default().Put(stdoutKey, f) // ignore error |
| 1487 |
} |
| 1488 |
|
| 1489 |
return nil |
| 1490 |
} |
| 1491 |
|
| 1492 |
var stdoutMu sync.Mutex // serializes concurrent writes (of e.g. JSON values) to stdout |
| 1493 |
|
| 1494 |
// copyToStdout copies the stream to stdout while holding the lock. |
| 1495 |
func copyToStdout(r io.Reader) error { |
| 1496 |
stdoutMu.Lock() |
| 1497 |
defer stdoutMu.Unlock() |
| 1498 |
if _, err := io.Copy(os.Stdout, r); err != nil { |
| 1499 |
return fmt.Errorf("copying vet tool stdout: %w", err) |
| 1500 |
} |
| 1501 |
return nil |
| 1502 |
} |
| 1503 |
|
| 1504 |
// linkActionID computes the action ID for a link action. |
| 1505 |
func (b *Builder) linkActionID(a *Action) cache.ActionID { |
| 1506 |
p := a.Package |
| 1507 |
h := cache.NewHash("link " + p.ImportPath) |
| 1508 |
|
| 1509 |
// Toolchain-independent configuration. |
| 1510 |
fmt.Fprintf(h, "link\n") |
| 1511 |
fmt.Fprintf(h, "buildmode %s goos %s goarch %s\n", cfg.BuildBuildmode, cfg.Goos, cfg.Goarch) |
| 1512 |
fmt.Fprintf(h, "import %q\n", p.ImportPath) |
| 1513 |
fmt.Fprintf(h, "omitdebug %v standard %v local %v prefix %q\n", p.Internal.OmitDebug, p.Standard, p.Internal.Local, p.Internal.LocalPrefix) |
| 1514 |
fmt.Fprintf(h, "defaultgodebug %q\n", p.DefaultGODEBUG) |
| 1515 |
if cfg.BuildTrimpath { |
| 1516 |
fmt.Fprintln(h, "trimpath") |
| 1517 |
} |
| 1518 |
|
| 1519 |
// Toolchain-dependent configuration, shared with b.linkSharedActionID. |
| 1520 |
b.printLinkerConfig(h, p) |
| 1521 |
|
| 1522 |
// Input files. |
| 1523 |
for _, a1 := range a.Deps { |
| 1524 |
p1 := a1.Package |
| 1525 |
if p1 != nil { |
| 1526 |
if a1.built != "" || a1.buildID != "" { |
| 1527 |
buildID := a1.buildID |
| 1528 |
if buildID == "" { |
| 1529 |
buildID = b.buildID(a1.built) |
| 1530 |
} |
| 1531 |
fmt.Fprintf(h, "packagefile %s=%s\n", p1.ImportPath, contentID(buildID)) |
| 1532 |
} |
| 1533 |
// Because we put package main's full action ID into the binary's build ID, |
| 1534 |
// we must also put the full action ID into the binary's action ID hash. |
| 1535 |
if p1.Name == "main" { |
| 1536 |
fmt.Fprintf(h, "packagemain %s\n", a1.buildID) |
| 1537 |
} |
| 1538 |
if p1.Shlib != "" { |
| 1539 |
fmt.Fprintf(h, "packageshlib %s=%s\n", p1.ImportPath, contentID(b.buildID(p1.Shlib))) |
| 1540 |
} |
| 1541 |
} |
| 1542 |
} |
| 1543 |
|
| 1544 |
return h.Sum() |
| 1545 |
} |
| 1546 |
|
| 1547 |
// printLinkerConfig prints the linker config into the hash h, |
| 1548 |
// as part of the computation of a linker-related action ID. |
| 1549 |
func (b *Builder) printLinkerConfig(h io.Writer, p *load.Package) { |
| 1550 |
switch cfg.BuildToolchainName { |
| 1551 |
default: |
| 1552 |
base.Fatalf("linkActionID: unknown toolchain %q", cfg.BuildToolchainName) |
| 1553 |
|
| 1554 |
case "gc": |
| 1555 |
fmt.Fprintf(h, "link %s %q %s\n", b.toolID("link"), forcedLdflags, ldBuildmode) |
| 1556 |
if p != nil { |
| 1557 |
fmt.Fprintf(h, "linkflags %q\n", p.Internal.Ldflags) |
| 1558 |
} |
| 1559 |
|
| 1560 |
// GOARM, GOMIPS, etc. |
| 1561 |
key, val, _ := cfg.GetArchEnv() |
| 1562 |
fmt.Fprintf(h, "%s=%s\n", key, val) |
| 1563 |
|
| 1564 |
if cfg.CleanGOEXPERIMENT != "" { |
| 1565 |
fmt.Fprintf(h, "GOEXPERIMENT=%q\n", cfg.CleanGOEXPERIMENT) |
| 1566 |
} |
| 1567 |
|
| 1568 |
// The linker writes source file paths that refer to GOROOT, |
| 1569 |
// but only if -trimpath is not specified (see [gctoolchain.ld] in gc.go). |
| 1570 |
gorootFinal := cfg.GOROOT |
| 1571 |
if cfg.BuildTrimpath { |
| 1572 |
gorootFinal = "" |
| 1573 |
} |
| 1574 |
fmt.Fprintf(h, "GOROOT=%s\n", gorootFinal) |
| 1575 |
|
| 1576 |
// GO_EXTLINK_ENABLED controls whether the external linker is used. |
| 1577 |
fmt.Fprintf(h, "GO_EXTLINK_ENABLED=%s\n", cfg.Getenv("GO_EXTLINK_ENABLED")) |
| 1578 |
|
| 1579 |
// TODO(rsc): Do cgo settings and flags need to be included? |
| 1580 |
// Or external linker settings and flags? |
| 1581 |
|
| 1582 |
case "gccgo": |
| 1583 |
id, _, err := b.gccToolID(BuildToolchain.linker(), "go") |
| 1584 |
if err != nil { |
| 1585 |
base.Fatalf("%v", err) |
| 1586 |
} |
| 1587 |
fmt.Fprintf(h, "link %s %s\n", id, ldBuildmode) |
| 1588 |
// TODO(iant): Should probably include cgo flags here. |
| 1589 |
} |
| 1590 |
} |
| 1591 |
|
| 1592 |
// link is the action for linking a single command. |
| 1593 |
// Note that any new influence on this logic must be reported in b.linkActionID above as well. |
| 1594 |
func (b *Builder) link(ctx context.Context, a *Action) (err error) { |
| 1595 |
if b.useCache(a, b.linkActionID(a), a.Package.Target, !b.IsCmdList) || b.IsCmdList { |
| 1596 |
return nil |
| 1597 |
} |
| 1598 |
defer b.flushOutput(a) |
| 1599 |
|
| 1600 |
sh := b.Shell(a) |
| 1601 |
if err := sh.Mkdir(a.Objdir); err != nil { |
| 1602 |
return err |
| 1603 |
} |
| 1604 |
|
| 1605 |
importcfg := a.Objdir + "importcfg.link" |
| 1606 |
if err := b.writeLinkImportcfg(a, importcfg); err != nil { |
| 1607 |
return err |
| 1608 |
} |
| 1609 |
|
| 1610 |
if err := AllowInstall(a); err != nil { |
| 1611 |
return err |
| 1612 |
} |
| 1613 |
|
| 1614 |
// make target directory |
| 1615 |
dir, _ := filepath.Split(a.Target) |
| 1616 |
if dir != "" { |
| 1617 |
if err := sh.Mkdir(dir); err != nil { |
| 1618 |
return err |
| 1619 |
} |
| 1620 |
} |
| 1621 |
|
| 1622 |
if err := BuildToolchain.ld(b, a, a.Target, importcfg, a.Deps[0].built); err != nil { |
| 1623 |
return err |
| 1624 |
} |
| 1625 |
|
| 1626 |
// Update the binary with the final build ID. |
| 1627 |
if err := b.updateBuildID(a, a.Target); err != nil { |
| 1628 |
return err |
| 1629 |
} |
| 1630 |
|
| 1631 |
a.built = a.Target |
| 1632 |
return nil |
| 1633 |
} |
| 1634 |
|
| 1635 |
func (b *Builder) writeLinkImportcfg(a *Action, file string) error { |
| 1636 |
// Prepare Go import cfg. |
| 1637 |
var icfg bytes.Buffer |
| 1638 |
for _, a1 := range a.Deps { |
| 1639 |
p1 := a1.Package |
| 1640 |
if p1 == nil { |
| 1641 |
continue |
| 1642 |
} |
| 1643 |
fmt.Fprintf(&icfg, "packagefile %s=%s\n", p1.ImportPath, a1.built) |
| 1644 |
if p1.Shlib != "" { |
| 1645 |
fmt.Fprintf(&icfg, "packageshlib %s=%s\n", p1.ImportPath, p1.Shlib) |
| 1646 |
} |
| 1647 |
} |
| 1648 |
info := "" |
| 1649 |
if a.Package.Internal.BuildInfo != nil { |
| 1650 |
info = a.Package.Internal.BuildInfo.String() |
| 1651 |
} |
| 1652 |
fmt.Fprintf(&icfg, "modinfo %q\n", modload.ModInfoData(info)) |
| 1653 |
return b.Shell(a).writeFile(file, icfg.Bytes()) |
| 1654 |
} |
| 1655 |
|
| 1656 |
// PkgconfigCmd returns a pkg-config binary name |
| 1657 |
// defaultPkgConfig is defined in zdefaultcc.go, written by cmd/dist. |
| 1658 |
func (b *Builder) PkgconfigCmd() string { |
| 1659 |
return envList("PKG_CONFIG", cfg.DefaultPkgConfig)[0] |
| 1660 |
} |
| 1661 |
|
| 1662 |
// splitPkgConfigOutput parses the pkg-config output into a slice of flags. |
| 1663 |
// This implements the shell quoting semantics described in |
| 1664 |
// https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_02, |
| 1665 |
// except that it does not support parameter or arithmetic expansion or command |
| 1666 |
// substitution and hard-codes the <blank> delimiters instead of reading them |
| 1667 |
// from LC_LOCALE. |
| 1668 |
func splitPkgConfigOutput(out []byte) ([]string, error) { |
| 1669 |
if len(out) == 0 { |
| 1670 |
return nil, nil |
| 1671 |
} |
| 1672 |
var flags []string |
| 1673 |
flag := make([]byte, 0, len(out)) |
| 1674 |
didQuote := false // was the current flag parsed from a quoted string? |
| 1675 |
escaped := false // did we just read `\` in a non-single-quoted context? |
| 1676 |
quote := byte(0) // what is the quote character around the current string? |
| 1677 |
|
| 1678 |
for _, c := range out { |
| 1679 |
if escaped { |
| 1680 |
if quote == '"' { |
| 1681 |
// “The <backslash> shall retain its special meaning as an escape |
| 1682 |
// character … only when followed by one of the following characters |
| 1683 |
// when considered special:” |
| 1684 |
switch c { |
| 1685 |
case '$', '`', '"', '\\', '\n': |
| 1686 |
// Handle the escaped character normally. |
| 1687 |
default: |
| 1688 |
// Not an escape character after all. |
| 1689 |
flag = append(flag, '\\', c) |
| 1690 |
escaped = false |
| 1691 |
continue |
| 1692 |
} |
| 1693 |
} |
| 1694 |
|
| 1695 |
if c == '\n' { |
| 1696 |
// “If a <newline> follows the <backslash>, the shell shall interpret |
| 1697 |
// this as line continuation.” |
| 1698 |
} else { |
| 1699 |
flag = append(flag, c) |
| 1700 |
} |
| 1701 |
escaped = false |
| 1702 |
continue |
| 1703 |
} |
| 1704 |
|
| 1705 |
if quote != 0 && c == quote { |
| 1706 |
quote = 0 |
| 1707 |
continue |
| 1708 |
} |
| 1709 |
switch quote { |
| 1710 |
case '\'': |
| 1711 |
// “preserve the literal value of each character” |
| 1712 |
flag = append(flag, c) |
| 1713 |
continue |
| 1714 |
case '"': |
| 1715 |
// “preserve the literal value of all characters within the double-quotes, |
| 1716 |
// with the exception of …” |
| 1717 |
switch c { |
| 1718 |
case '`', '$', '\\': |
| 1719 |
default: |
| 1720 |
flag = append(flag, c) |
| 1721 |
continue |
| 1722 |
} |
| 1723 |
} |
| 1724 |
|
| 1725 |
// “The application shall quote the following characters if they are to |
| 1726 |
// represent themselves:” |
| 1727 |
switch c { |
| 1728 |
case '|', '&', ';', '<', '>', '(', ')', '$', '`': |
| 1729 |
return nil, fmt.Errorf("unexpected shell character %q in pkgconf output", c) |
| 1730 |
|
| 1731 |
case '\\': |
| 1732 |
// “A <backslash> that is not quoted shall preserve the literal value of |
| 1733 |
// the following character, with the exception of a <newline>.” |
| 1734 |
escaped = true |
| 1735 |
continue |
| 1736 |
|
| 1737 |
case '"', '\'': |
| 1738 |
quote = c |
| 1739 |
didQuote = true |
| 1740 |
continue |
| 1741 |
|
| 1742 |
case ' ', '\t', '\n': |
| 1743 |
if len(flag) > 0 || didQuote { |
| 1744 |
flags = append(flags, string(flag)) |
| 1745 |
} |
| 1746 |
flag, didQuote = flag[:0], false |
| 1747 |
continue |
| 1748 |
} |
| 1749 |
|
| 1750 |
flag = append(flag, c) |
| 1751 |
} |
| 1752 |
|
| 1753 |
// Prefer to report a missing quote instead of a missing escape. If the string |
| 1754 |
// is something like `"foo\`, it's ambiguous as to whether the trailing |
| 1755 |
// backslash is really an escape at all. |
| 1756 |
if quote != 0 { |
| 1757 |
return nil, errors.New("unterminated quoted string in pkgconf output") |
| 1758 |
} |
| 1759 |
if escaped { |
| 1760 |
return nil, errors.New("broken character escaping in pkgconf output") |
| 1761 |
} |
| 1762 |
|
| 1763 |
if len(flag) > 0 || didQuote { |
| 1764 |
flags = append(flags, string(flag)) |
| 1765 |
} |
| 1766 |
return flags, nil |
| 1767 |
} |
| 1768 |
|
| 1769 |
// Calls pkg-config if needed and returns the cflags/ldflags needed to build a's package. |
| 1770 |
func (b *Builder) getPkgConfigFlags(a *Action, p *load.Package) (cflags, ldflags []string, err error) { |
| 1771 |
sh := b.Shell(a) |
| 1772 |
if pcargs := p.CgoPkgConfig; len(pcargs) > 0 { |
| 1773 |
// pkg-config permits arguments to appear anywhere in |
| 1774 |
// the command line. Move them all to the front, before --. |
| 1775 |
var pcflags []string |
| 1776 |
var pkgs []string |
| 1777 |
for _, pcarg := range pcargs { |
| 1778 |
if pcarg == "--" { |
| 1779 |
// We're going to add our own "--" argument. |
| 1780 |
} else if strings.HasPrefix(pcarg, "--") { |
| 1781 |
pcflags = append(pcflags, pcarg) |
| 1782 |
} else { |
| 1783 |
pkgs = append(pkgs, pcarg) |
| 1784 |
} |
| 1785 |
} |
| 1786 |
for _, pkg := range pkgs { |
| 1787 |
if !load.SafeArg(pkg) { |
| 1788 |
return nil, nil, fmt.Errorf("invalid pkg-config package name: %s", pkg) |
| 1789 |
} |
| 1790 |
} |
| 1791 |
|
| 1792 |
if err := checkPkgConfigFlags("", "pkg-config", pcflags); err != nil { |
| 1793 |
return nil, nil, err |
| 1794 |
} |
| 1795 |
|
| 1796 |
var out []byte |
| 1797 |
out, err = sh.runOut(p.Dir, nil, b.PkgconfigCmd(), "--cflags", pcflags, "--", pkgs) |
| 1798 |
if err != nil { |
| 1799 |
desc := b.PkgconfigCmd() + " --cflags " + strings.Join(pcflags, " ") + " -- " + strings.Join(pkgs, " ") |
| 1800 |
return nil, nil, sh.reportCmd(desc, "", out, err) |
| 1801 |
} |
| 1802 |
if len(out) > 0 { |
| 1803 |
cflags, err = splitPkgConfigOutput(bytes.TrimSpace(out)) |
| 1804 |
if err != nil { |
| 1805 |
return nil, nil, err |
| 1806 |
} |
| 1807 |
if err := checkCompilerFlags("CFLAGS", "pkg-config --cflags", cflags); err != nil { |
| 1808 |
return nil, nil, err |
| 1809 |
} |
| 1810 |
} |
| 1811 |
out, err = sh.runOut(p.Dir, nil, b.PkgconfigCmd(), "--libs", pcflags, "--", pkgs) |
| 1812 |
if err != nil { |
| 1813 |
desc := b.PkgconfigCmd() + " --libs " + strings.Join(pcflags, " ") + " -- " + strings.Join(pkgs, " ") |
| 1814 |
return nil, nil, sh.reportCmd(desc, "", out, err) |
| 1815 |
} |
| 1816 |
if len(out) > 0 { |
| 1817 |
// We need to handle path with spaces so that C:/Program\ Files can pass |
| 1818 |
// checkLinkerFlags. Use splitPkgConfigOutput here just like we treat cflags. |
| 1819 |
ldflags, err = splitPkgConfigOutput(bytes.TrimSpace(out)) |
| 1820 |
if err != nil { |
| 1821 |
return nil, nil, err |
| 1822 |
} |
| 1823 |
if err := checkLinkerFlags("LDFLAGS", "pkg-config --libs", ldflags); err != nil { |
| 1824 |
return nil, nil, err |
| 1825 |
} |
| 1826 |
} |
| 1827 |
} |
| 1828 |
|
| 1829 |
return |
| 1830 |
} |
| 1831 |
|
| 1832 |
func (b *Builder) installShlibname(ctx context.Context, a *Action) error { |
| 1833 |
if err := AllowInstall(a); err != nil { |
| 1834 |
return err |
| 1835 |
} |
| 1836 |
|
| 1837 |
sh := b.Shell(a) |
| 1838 |
a1 := a.Deps[0] |
| 1839 |
if !cfg.BuildN { |
| 1840 |
if err := sh.Mkdir(filepath.Dir(a.Target)); err != nil { |
| 1841 |
return err |
| 1842 |
} |
| 1843 |
} |
| 1844 |
return sh.writeFile(a.Target, []byte(filepath.Base(a1.Target)+"\n")) |
| 1845 |
} |
| 1846 |
|
| 1847 |
func (b *Builder) linkSharedActionID(a *Action) cache.ActionID { |
| 1848 |
h := cache.NewHash("linkShared") |
| 1849 |
|
| 1850 |
// Toolchain-independent configuration. |
| 1851 |
fmt.Fprintf(h, "linkShared\n") |
| 1852 |
fmt.Fprintf(h, "goos %s goarch %s\n", cfg.Goos, cfg.Goarch) |
| 1853 |
|
| 1854 |
// Toolchain-dependent configuration, shared with b.linkActionID. |
| 1855 |
b.printLinkerConfig(h, nil) |
| 1856 |
|
| 1857 |
// Input files. |
| 1858 |
for _, a1 := range a.Deps { |
| 1859 |
p1 := a1.Package |
| 1860 |
if a1.built == "" { |
| 1861 |
continue |
| 1862 |
} |
| 1863 |
if p1 != nil { |
| 1864 |
fmt.Fprintf(h, "packagefile %s=%s\n", p1.ImportPath, contentID(b.buildID(a1.built))) |
| 1865 |
if p1.Shlib != "" { |
| 1866 |
fmt.Fprintf(h, "packageshlib %s=%s\n", p1.ImportPath, contentID(b.buildID(p1.Shlib))) |
| 1867 |
} |
| 1868 |
} |
| 1869 |
} |
| 1870 |
// Files named on command line are special. |
| 1871 |
for _, a1 := range a.Deps[0].Deps { |
| 1872 |
p1 := a1.Package |
| 1873 |
fmt.Fprintf(h, "top %s=%s\n", p1.ImportPath, contentID(b.buildID(a1.built))) |
| 1874 |
} |
| 1875 |
|
| 1876 |
return h.Sum() |
| 1877 |
} |
| 1878 |
|
| 1879 |
func (b *Builder) linkShared(ctx context.Context, a *Action) (err error) { |
| 1880 |
if b.useCache(a, b.linkSharedActionID(a), a.Target, !b.IsCmdList) || b.IsCmdList { |
| 1881 |
return nil |
| 1882 |
} |
| 1883 |
defer b.flushOutput(a) |
| 1884 |
|
| 1885 |
if err := AllowInstall(a); err != nil { |
| 1886 |
return err |
| 1887 |
} |
| 1888 |
|
| 1889 |
if err := b.Shell(a).Mkdir(a.Objdir); err != nil { |
| 1890 |
return err |
| 1891 |
} |
| 1892 |
|
| 1893 |
importcfg := a.Objdir + "importcfg.link" |
| 1894 |
if err := b.writeLinkImportcfg(a, importcfg); err != nil { |
| 1895 |
return err |
| 1896 |
} |
| 1897 |
|
| 1898 |
// TODO(rsc): There is a missing updateBuildID here, |
| 1899 |
// but we have to decide where to store the build ID in these files. |
| 1900 |
a.built = a.Target |
| 1901 |
return BuildToolchain.ldShared(b, a, a.Deps[0].Deps, a.Target, importcfg, a.Deps) |
| 1902 |
} |
| 1903 |
|
| 1904 |
// BuildInstallFunc is the action for installing a single package or executable. |
| 1905 |
func BuildInstallFunc(b *Builder, ctx context.Context, a *Action) (err error) { |
| 1906 |
defer func() { |
| 1907 |
if err != nil { |
| 1908 |
// a.Package == nil is possible for the go install -buildmode=shared |
| 1909 |
// action that installs libmangledname.so, which corresponds to |
| 1910 |
// a list of packages, not just one. |
| 1911 |
sep, path := "", "" |
| 1912 |
if a.Package != nil { |
| 1913 |
sep, path = " ", a.Package.ImportPath |
| 1914 |
} |
| 1915 |
err = fmt.Errorf("go %s%s%s: %v", cfg.CmdName, sep, path, err) |
| 1916 |
} |
| 1917 |
}() |
| 1918 |
sh := b.Shell(a) |
| 1919 |
|
| 1920 |
a1 := a.Deps[0] |
| 1921 |
a.buildID = a1.buildID |
| 1922 |
if a.json != nil { |
| 1923 |
a.json.BuildID = a.buildID |
| 1924 |
} |
| 1925 |
|
| 1926 |
// If we are using the eventual install target as an up-to-date |
| 1927 |
// cached copy of the thing we built, then there's no need to |
| 1928 |
// copy it into itself (and that would probably fail anyway). |
| 1929 |
// In this case a1.built == a.Target because a1.built == p.Target, |
| 1930 |
// so the built target is not in the a1.Objdir tree that b.cleanup(a1) removes. |
| 1931 |
if a1.built == a.Target { |
| 1932 |
a.built = a.Target |
| 1933 |
if !a.buggyInstall { |
| 1934 |
b.cleanup(a1) |
| 1935 |
} |
| 1936 |
// Whether we're smart enough to avoid a complete rebuild |
| 1937 |
// depends on exactly what the staleness and rebuild algorithms |
| 1938 |
// are, as well as potentially the state of the Go build cache. |
| 1939 |
// We don't really want users to be able to infer (or worse start depending on) |
| 1940 |
// those details from whether the modification time changes during |
| 1941 |
// "go install", so do a best-effort update of the file times to make it |
| 1942 |
// look like we rewrote a.Target even if we did not. Updating the mtime |
| 1943 |
// may also help other mtime-based systems that depend on our |
| 1944 |
// previous mtime updates that happened more often. |
| 1945 |
// This is still not perfect - we ignore the error result, and if the file was |
| 1946 |
// unwritable for some reason then pretending to have written it is also |
| 1947 |
// confusing - but it's probably better than not doing the mtime update. |
| 1948 |
// |
| 1949 |
// But don't do that for the special case where building an executable |
| 1950 |
// with -linkshared implicitly installs all its dependent libraries. |
| 1951 |
// We want to hide that awful detail as much as possible, so don't |
| 1952 |
// advertise it by touching the mtimes (usually the libraries are up |
| 1953 |
// to date). |
| 1954 |
if !a.buggyInstall && !b.IsCmdList { |
| 1955 |
if cfg.BuildN { |
| 1956 |
sh.ShowCmd("", "touch %s", a.Target) |
| 1957 |
} else if err := AllowInstall(a); err == nil { |
| 1958 |
now := time.Now() |
| 1959 |
os.Chtimes(a.Target, now, now) |
| 1960 |
} |
| 1961 |
} |
| 1962 |
return nil |
| 1963 |
} |
| 1964 |
|
| 1965 |
// If we're building for go list -export, |
| 1966 |
// never install anything; just keep the cache reference. |
| 1967 |
if b.IsCmdList { |
| 1968 |
a.built = a1.built |
| 1969 |
return nil |
| 1970 |
} |
| 1971 |
if err := AllowInstall(a); err != nil { |
| 1972 |
return err |
| 1973 |
} |
| 1974 |
|
| 1975 |
if err := sh.Mkdir(a.Objdir); err != nil { |
| 1976 |
return err |
| 1977 |
} |
| 1978 |
|
| 1979 |
perm := fs.FileMode(0666) |
| 1980 |
if a1.Mode == "link" { |
| 1981 |
switch cfg.BuildBuildmode { |
| 1982 |
case "c-archive", "c-shared", "plugin": |
| 1983 |
default: |
| 1984 |
perm = 0777 |
| 1985 |
} |
| 1986 |
} |
| 1987 |
|
| 1988 |
// make target directory |
| 1989 |
dir, _ := filepath.Split(a.Target) |
| 1990 |
if dir != "" { |
| 1991 |
if err := sh.Mkdir(dir); err != nil { |
| 1992 |
return err |
| 1993 |
} |
| 1994 |
} |
| 1995 |
|
| 1996 |
if !a.buggyInstall { |
| 1997 |
defer b.cleanup(a1) |
| 1998 |
} |
| 1999 |
|
| 2000 |
return sh.moveOrCopyFile(a.Target, a1.built, perm, false) |
| 2001 |
} |
| 2002 |
|
| 2003 |
// AllowInstall returns a non-nil error if this invocation of the go command is |
| 2004 |
// allowed to install a.Target. |
| 2005 |
// |
| 2006 |
// The build of cmd/go running under its own test is forbidden from installing |
| 2007 |
// to its original GOROOT. The var is exported so it can be set by TestMain. |
| 2008 |
var AllowInstall = func(*Action) error { return nil } |
| 2009 |
|
| 2010 |
// cleanup removes a's object dir to keep the amount of |
| 2011 |
// on-disk garbage down in a large build. On an operating system |
| 2012 |
// with aggressive buffering, cleaning incrementally like |
| 2013 |
// this keeps the intermediate objects from hitting the disk. |
| 2014 |
func (b *Builder) cleanup(a *Action) { |
| 2015 |
if !cfg.BuildWork { |
| 2016 |
b.Shell(a).RemoveAll(a.Objdir) |
| 2017 |
} |
| 2018 |
} |
| 2019 |
|
| 2020 |
// Install the cgo export header file, if there is one. |
| 2021 |
func (b *Builder) installHeader(ctx context.Context, a *Action) error { |
| 2022 |
sh := b.Shell(a) |
| 2023 |
|
| 2024 |
src := a.Objdir + "_cgo_install.h" |
| 2025 |
if _, err := os.Stat(src); os.IsNotExist(err) { |
| 2026 |
// If the file does not exist, there are no exported |
| 2027 |
// functions, and we do not install anything. |
| 2028 |
// TODO(rsc): Once we know that caching is rebuilding |
| 2029 |
// at the right times (not missing rebuilds), here we should |
| 2030 |
// probably delete the installed header, if any. |
| 2031 |
if cfg.BuildX { |
| 2032 |
sh.ShowCmd("", "# %s not created", src) |
| 2033 |
} |
| 2034 |
return nil |
| 2035 |
} |
| 2036 |
|
| 2037 |
if err := AllowInstall(a); err != nil { |
| 2038 |
return err |
| 2039 |
} |
| 2040 |
|
| 2041 |
dir, _ := filepath.Split(a.Target) |
| 2042 |
if dir != "" { |
| 2043 |
if err := sh.Mkdir(dir); err != nil { |
| 2044 |
return err |
| 2045 |
} |
| 2046 |
} |
| 2047 |
|
| 2048 |
return sh.moveOrCopyFile(a.Target, src, 0666, true) |
| 2049 |
} |
| 2050 |
|
| 2051 |
// cover runs, in effect, |
| 2052 |
// |
| 2053 |
// go tool cover -pkgcfg=<config file> -mode=b.coverMode -var="varName" -o <outfiles> <infiles> |
| 2054 |
// |
| 2055 |
// Return value is an updated output files list; in addition to the |
| 2056 |
// regular outputs (instrumented source files) the cover tool also |
| 2057 |
// writes a separate file (appearing first in the list of outputs) |
| 2058 |
// that will contain coverage counters and meta-data. |
| 2059 |
func (b *Builder) cover(a *Action, infiles, outfiles []string, varName string, mode string) ([]string, error) { |
| 2060 |
pkgcfg := a.Objdir + "pkgcfg.txt" |
| 2061 |
covoutputs := a.Objdir + "coveroutfiles.txt" |
| 2062 |
odir := filepath.Dir(outfiles[0]) |
| 2063 |
cv := filepath.Join(odir, "covervars.go") |
| 2064 |
outfiles = append([]string{cv}, outfiles...) |
| 2065 |
if err := b.writeCoverPkgInputs(a, pkgcfg, covoutputs, outfiles); err != nil { |
| 2066 |
return nil, err |
| 2067 |
} |
| 2068 |
args := []string{base.Tool("cover"), |
| 2069 |
"-pkgcfg", pkgcfg, |
| 2070 |
"-mode", mode, |
| 2071 |
"-var", varName, |
| 2072 |
"-outfilelist", covoutputs, |
| 2073 |
} |
| 2074 |
args = append(args, infiles...) |
| 2075 |
if err := b.Shell(a).run(a.Objdir, "", nil, |
| 2076 |
cfg.BuildToolexec, args); err != nil { |
| 2077 |
return nil, err |
| 2078 |
} |
| 2079 |
return outfiles, nil |
| 2080 |
} |
| 2081 |
|
| 2082 |
func (b *Builder) writeCoverPkgInputs(a *Action, pconfigfile string, covoutputsfile string, outfiles []string) error { |
| 2083 |
sh := b.Shell(a) |
| 2084 |
p := a.Package |
| 2085 |
p.Internal.Cover.Cfg = a.Objdir + "coveragecfg" |
| 2086 |
pcfg := covcmd.CoverPkgConfig{ |
| 2087 |
PkgPath: p.ImportPath, |
| 2088 |
PkgName: p.Name, |
| 2089 |
// Note: coverage granularity is currently hard-wired to |
| 2090 |
// 'perblock'; there isn't a way using "go build -cover" or "go |
| 2091 |
// test -cover" to select it. This may change in the future |
| 2092 |
// depending on user demand. |
| 2093 |
Granularity: "perblock", |
| 2094 |
OutConfig: p.Internal.Cover.Cfg, |
| 2095 |
Local: p.Internal.Local, |
| 2096 |
} |
| 2097 |
if ca, ok := a.Actor.(*coverActor); ok && ca.covMetaFileName != "" { |
| 2098 |
pcfg.EmitMetaFile = a.Objdir + ca.covMetaFileName |
| 2099 |
} |
| 2100 |
if a.Package.Module != nil { |
| 2101 |
pcfg.ModulePath = a.Package.Module.Path |
| 2102 |
} |
| 2103 |
data, err := json.Marshal(pcfg) |
| 2104 |
if err != nil { |
| 2105 |
return err |
| 2106 |
} |
| 2107 |
data = append(data, '\n') |
| 2108 |
if err := sh.writeFile(pconfigfile, data); err != nil { |
| 2109 |
return err |
| 2110 |
} |
| 2111 |
var sb strings.Builder |
| 2112 |
for i := range outfiles { |
| 2113 |
fmt.Fprintf(&sb, "%s\n", outfiles[i]) |
| 2114 |
} |
| 2115 |
return sh.writeFile(covoutputsfile, []byte(sb.String())) |
| 2116 |
} |
| 2117 |
|
| 2118 |
var objectMagic = [][]byte{ |
| 2119 |
{'!', '<', 'a', 'r', 'c', 'h', '>', '\n'}, // Package archive |
| 2120 |
{'<', 'b', 'i', 'g', 'a', 'f', '>', '\n'}, // Package AIX big archive |
| 2121 |
{'\x7F', 'E', 'L', 'F'}, // ELF |
| 2122 |
{0xFE, 0xED, 0xFA, 0xCE}, // Mach-O big-endian 32-bit |
| 2123 |
{0xFE, 0xED, 0xFA, 0xCF}, // Mach-O big-endian 64-bit |
| 2124 |
{0xCE, 0xFA, 0xED, 0xFE}, // Mach-O little-endian 32-bit |
| 2125 |
{0xCF, 0xFA, 0xED, 0xFE}, // Mach-O little-endian 64-bit |
| 2126 |
{0x4d, 0x5a, 0x90, 0x00, 0x03, 0x00}, // PE (Windows) as generated by 6l/8l and gcc |
| 2127 |
{0x4d, 0x5a, 0x78, 0x00, 0x01, 0x00}, // PE (Windows) as generated by llvm for dll |
| 2128 |
{0x00, 0x00, 0x01, 0xEB}, // Plan 9 i386 |
| 2129 |
{0x00, 0x00, 0x8a, 0x97}, // Plan 9 amd64 |
| 2130 |
{0x00, 0x00, 0x06, 0x47}, // Plan 9 arm |
| 2131 |
{0x00, 0x61, 0x73, 0x6D}, // WASM |
| 2132 |
{0x01, 0xDF}, // XCOFF 32bit |
| 2133 |
{0x01, 0xF7}, // XCOFF 64bit |
| 2134 |
} |
| 2135 |
|
| 2136 |
func isObject(s string) bool { |
| 2137 |
f, err := os.Open(s) |
| 2138 |
if err != nil { |
| 2139 |
return false |
| 2140 |
} |
| 2141 |
defer f.Close() |
| 2142 |
buf := make([]byte, 64) |
| 2143 |
io.ReadFull(f, buf) |
| 2144 |
for _, magic := range objectMagic { |
| 2145 |
if bytes.HasPrefix(buf, magic) { |
| 2146 |
return true |
| 2147 |
} |
| 2148 |
} |
| 2149 |
return false |
| 2150 |
} |
| 2151 |
|
| 2152 |
// cCompilerEnv returns environment variables to set when running the |
| 2153 |
// C compiler. This is needed to disable escape codes in clang error |
| 2154 |
// messages that confuse tools like cgo. |
| 2155 |
func (b *Builder) cCompilerEnv() []string { |
| 2156 |
return []string{"TERM=dumb"} |
| 2157 |
} |
| 2158 |
|
| 2159 |
// mkAbs returns an absolute path corresponding to |
| 2160 |
// evaluating f in the directory dir. |
| 2161 |
// We always pass absolute paths of source files so that |
| 2162 |
// the error messages will include the full path to a file |
| 2163 |
// in need of attention. |
| 2164 |
func mkAbs(dir, f string) string { |
| 2165 |
// Leave absolute paths alone. |
| 2166 |
// Also, during -n mode we use the pseudo-directory $WORK |
| 2167 |
// instead of creating an actual work directory that won't be used. |
| 2168 |
// Leave paths beginning with $WORK alone too. |
| 2169 |
if filepath.IsAbs(f) || strings.HasPrefix(f, "$WORK") { |
| 2170 |
return f |
| 2171 |
} |
| 2172 |
return filepath.Join(dir, f) |
| 2173 |
} |
| 2174 |
|
| 2175 |
type toolchain interface { |
| 2176 |
// gc runs the compiler in a specific directory on a set of files |
| 2177 |
// and returns the name of the generated output file. |
| 2178 |
gc(b *Builder, a *Action, archive string, importcfg, embedcfg []byte, symabis string, asmhdr bool, pgoProfile string, gofiles []string) (ofile string, out []byte, err error) |
| 2179 |
// cc runs the toolchain's C compiler in a directory on a C file |
| 2180 |
// to produce an output file. |
| 2181 |
cc(b *Builder, a *Action, ofile, cfile string) error |
| 2182 |
// asm runs the assembler in a specific directory on specific files |
| 2183 |
// and returns a list of named output files. |
| 2184 |
asm(b *Builder, a *Action, sfiles []string) ([]string, error) |
| 2185 |
// symabis scans the symbol ABIs from sfiles and returns the |
| 2186 |
// path to the output symbol ABIs file, or "" if none. |
| 2187 |
symabis(b *Builder, a *Action, sfiles []string) (string, error) |
| 2188 |
// pack runs the archive packer in a specific directory to create |
| 2189 |
// an archive from a set of object files. |
| 2190 |
// typically it is run in the object directory. |
| 2191 |
pack(b *Builder, a *Action, afile string, ofiles []string) error |
| 2192 |
// ld runs the linker to create an executable starting at mainpkg. |
| 2193 |
ld(b *Builder, root *Action, targetPath, importcfg, mainpkg string) error |
| 2194 |
// ldShared runs the linker to create a shared library containing the pkgs built by toplevelactions |
| 2195 |
ldShared(b *Builder, root *Action, toplevelactions []*Action, targetPath, importcfg string, allactions []*Action) error |
| 2196 |
|
| 2197 |
compiler() string |
| 2198 |
linker() string |
| 2199 |
} |
| 2200 |
|
| 2201 |
type noToolchain struct{} |
| 2202 |
|
| 2203 |
func noCompiler() error { |
| 2204 |
log.Fatalf("unknown compiler %q", cfg.BuildContext.Compiler) |
| 2205 |
return nil |
| 2206 |
} |
| 2207 |
|
| 2208 |
func (noToolchain) compiler() string { |
| 2209 |
noCompiler() |
| 2210 |
return "" |
| 2211 |
} |
| 2212 |
|
| 2213 |
func (noToolchain) linker() string { |
| 2214 |
noCompiler() |
| 2215 |
return "" |
| 2216 |
} |
| 2217 |
|
| 2218 |
func (noToolchain) gc(b *Builder, a *Action, archive string, importcfg, embedcfg []byte, symabis string, asmhdr bool, pgoProfile string, gofiles []string) (ofile string, out []byte, err error) { |
| 2219 |
return "", nil, noCompiler() |
| 2220 |
} |
| 2221 |
|
| 2222 |
func (noToolchain) asm(b *Builder, a *Action, sfiles []string) ([]string, error) { |
| 2223 |
return nil, noCompiler() |
| 2224 |
} |
| 2225 |
|
| 2226 |
func (noToolchain) symabis(b *Builder, a *Action, sfiles []string) (string, error) { |
| 2227 |
return "", noCompiler() |
| 2228 |
} |
| 2229 |
|
| 2230 |
func (noToolchain) pack(b *Builder, a *Action, afile string, ofiles []string) error { |
| 2231 |
return noCompiler() |
| 2232 |
} |
| 2233 |
|
| 2234 |
func (noToolchain) ld(b *Builder, root *Action, targetPath, importcfg, mainpkg string) error { |
| 2235 |
return noCompiler() |
| 2236 |
} |
| 2237 |
|
| 2238 |
func (noToolchain) ldShared(b *Builder, root *Action, toplevelactions []*Action, targetPath, importcfg string, allactions []*Action) error { |
| 2239 |
return noCompiler() |
| 2240 |
} |
| 2241 |
|
| 2242 |
func (noToolchain) cc(b *Builder, a *Action, ofile, cfile string) error { |
| 2243 |
return noCompiler() |
| 2244 |
} |
| 2245 |
|
| 2246 |
// gcc runs the gcc C compiler to create an object from a single C file. |
| 2247 |
func (b *Builder) gcc(a *Action, workdir, out string, flags []string, cfile string) error { |
| 2248 |
p := a.Package |
| 2249 |
return b.ccompile(a, out, flags, cfile, b.GccCmd(p.Dir, workdir)) |
| 2250 |
} |
| 2251 |
|
| 2252 |
// gas runs the gcc c compiler to create an object file from a single C assembly file. |
| 2253 |
func (b *Builder) gas(a *Action, workdir, out string, flags []string, sfile string) error { |
| 2254 |
p := a.Package |
| 2255 |
data, err := os.ReadFile(filepath.Join(p.Dir, sfile)) |
| 2256 |
if err == nil { |
| 2257 |
if bytes.HasPrefix(data, []byte("TEXT")) || bytes.Contains(data, []byte("\nTEXT")) || |
| 2258 |
bytes.HasPrefix(data, []byte("DATA")) || bytes.Contains(data, []byte("\nDATA")) || |
| 2259 |
bytes.HasPrefix(data, []byte("GLOBL")) || bytes.Contains(data, []byte("\nGLOBL")) { |
| 2260 |
return fmt.Errorf("package using cgo has Go assembly file %s", sfile) |
| 2261 |
} |
| 2262 |
} |
| 2263 |
return b.ccompile(a, out, flags, sfile, b.GccCmd(p.Dir, workdir)) |
| 2264 |
} |
| 2265 |
|
| 2266 |
// gxx runs the g++ C++ compiler to create an object from a single C++ file. |
| 2267 |
func (b *Builder) gxx(a *Action, workdir, out string, flags []string, cxxfile string) error { |
| 2268 |
p := a.Package |
| 2269 |
return b.ccompile(a, out, flags, cxxfile, b.GxxCmd(p.Dir, workdir)) |
| 2270 |
} |
| 2271 |
|
| 2272 |
// gfortran runs the gfortran Fortran compiler to create an object from a single Fortran file. |
| 2273 |
func (b *Builder) gfortran(a *Action, workdir, out string, flags []string, ffile string) error { |
| 2274 |
p := a.Package |
| 2275 |
return b.ccompile(a, out, flags, ffile, b.gfortranCmd(p.Dir, workdir)) |
| 2276 |
} |
| 2277 |
|
| 2278 |
// ccompile runs the given C or C++ compiler and creates an object from a single source file. |
| 2279 |
func (b *Builder) ccompile(a *Action, outfile string, flags []string, file string, compiler []string) error { |
| 2280 |
p := a.Package |
| 2281 |
sh := b.Shell(a) |
| 2282 |
file = mkAbs(p.Dir, file) |
| 2283 |
outfile = mkAbs(p.Dir, outfile) |
| 2284 |
|
| 2285 |
flags = slices.Clip(flags) // If we append to flags, write to a new slice that we own. |
| 2286 |
|
| 2287 |
// Elide source directory paths if -trimpath is set. |
| 2288 |
// This is needed for source files (e.g., a .c file in a package directory). |
| 2289 |
// TODO(golang.org/issue/36072): cgo also generates files with #line |
| 2290 |
// directives pointing to the source directory. It should not generate those |
| 2291 |
// when -trimpath is enabled. |
| 2292 |
if b.gccSupportsFlag(compiler, "-fdebug-prefix-map=a=b") { |
| 2293 |
if cfg.BuildTrimpath || p.Goroot { |
| 2294 |
prefixMapFlag := "-fdebug-prefix-map" |
| 2295 |
if b.gccSupportsFlag(compiler, "-ffile-prefix-map=a=b") { |
| 2296 |
prefixMapFlag = "-ffile-prefix-map" |
| 2297 |
} |
| 2298 |
// Keep in sync with Action.trimpath. |
| 2299 |
// The trimmed paths are a little different, but we need to trim in mostly the |
| 2300 |
// same situations. |
| 2301 |
var from, toPath string |
| 2302 |
if m := p.Module; m == nil { |
| 2303 |
if p.Root == "" { // command-line-arguments in GOPATH mode, maybe? |
| 2304 |
from = p.Dir |
| 2305 |
toPath = p.ImportPath |
| 2306 |
} else if p.Goroot { |
| 2307 |
from = p.Root |
| 2308 |
toPath = "GOROOT" |
| 2309 |
} else { |
| 2310 |
from = p.Root |
| 2311 |
toPath = "GOPATH" |
| 2312 |
} |
| 2313 |
} else if m.Dir == "" { |
| 2314 |
// The module is in the vendor directory. Replace the entire vendor |
| 2315 |
// directory path, because the module's Dir is not filled in. |
| 2316 |
from = b.getVendorDir() |
| 2317 |
toPath = "vendor" |
| 2318 |
} else { |
| 2319 |
from = m.Dir |
| 2320 |
toPath = m.Path |
| 2321 |
if m.Version != "" { |
| 2322 |
toPath += "@" + m.Version |
| 2323 |
} |
| 2324 |
} |
| 2325 |
// -fdebug-prefix-map (or -ffile-prefix-map) requires an absolute "to" |
| 2326 |
// path (or it joins the path with the working directory). Pick something |
| 2327 |
// that makes sense for the target platform. |
| 2328 |
var to string |
| 2329 |
if cfg.BuildContext.GOOS == "windows" { |
| 2330 |
to = filepath.Join(`\\_\_`, toPath) |
| 2331 |
} else { |
| 2332 |
to = filepath.Join("/_", toPath) |
| 2333 |
} |
| 2334 |
flags = append(slices.Clip(flags), prefixMapFlag+"="+from+"="+to) |
| 2335 |
} |
| 2336 |
} |
| 2337 |
|
| 2338 |
// Tell gcc to not insert truly random numbers into the build process |
| 2339 |
// this ensures LTO won't create random numbers for symbols. |
| 2340 |
if b.gccSupportsFlag(compiler, "-frandom-seed=1") { |
| 2341 |
flags = append(flags, "-frandom-seed="+buildid.HashToString(a.actionID)) |
| 2342 |
} |
| 2343 |
|
| 2344 |
overlayPath := file |
| 2345 |
if p, ok := a.nonGoOverlay[overlayPath]; ok { |
| 2346 |
overlayPath = p |
| 2347 |
} |
| 2348 |
output, err := sh.runOut(filepath.Dir(overlayPath), b.cCompilerEnv(), compiler, flags, "-o", outfile, "-c", filepath.Base(overlayPath)) |
| 2349 |
|
| 2350 |
// On FreeBSD 11, when we pass -g to clang 3.8 it |
| 2351 |
// invokes its internal assembler with -dwarf-version=2. |
| 2352 |
// When it sees .section .note.GNU-stack, it warns |
| 2353 |
// "DWARF2 only supports one section per compilation unit". |
| 2354 |
// This warning makes no sense, since the section is empty, |
| 2355 |
// but it confuses people. |
| 2356 |
// We work around the problem by detecting the warning |
| 2357 |
// and dropping -g and trying again. |
| 2358 |
if bytes.Contains(output, []byte("DWARF2 only supports one section per compilation unit")) { |
| 2359 |
newFlags := make([]string, 0, len(flags)) |
| 2360 |
for _, f := range flags { |
| 2361 |
if !strings.HasPrefix(f, "-g") { |
| 2362 |
newFlags = append(newFlags, f) |
| 2363 |
} |
| 2364 |
} |
| 2365 |
if len(newFlags) < len(flags) { |
| 2366 |
return b.ccompile(a, outfile, newFlags, file, compiler) |
| 2367 |
} |
| 2368 |
} |
| 2369 |
|
| 2370 |
if len(output) > 0 && err == nil && os.Getenv("GO_BUILDER_NAME") != "" { |
| 2371 |
output = append(output, "C compiler warning promoted to error on Go builders\n"...) |
| 2372 |
err = errors.New("warning promoted to error") |
| 2373 |
} |
| 2374 |
|
| 2375 |
return sh.reportCmd("", "", output, err) |
| 2376 |
} |
| 2377 |
|
| 2378 |
// gccld runs the gcc linker to create an executable from a set of object files. |
| 2379 |
func (b *Builder) gccld(a *Action, objdir, outfile string, flags []string, objs []string) error { |
| 2380 |
p := a.Package |
| 2381 |
sh := b.Shell(a) |
| 2382 |
var cmd []string |
| 2383 |
if len(p.CXXFiles) > 0 || len(p.SwigCXXFiles) > 0 { |
| 2384 |
cmd = b.GxxCmd(p.Dir, objdir) |
| 2385 |
} else { |
| 2386 |
cmd = b.GccCmd(p.Dir, objdir) |
| 2387 |
} |
| 2388 |
|
| 2389 |
cmdargs := []any{cmd, "-o", outfile, objs, flags} |
| 2390 |
_, err := sh.runOut(base.Cwd(), b.cCompilerEnv(), cmdargs...) |
| 2391 |
|
| 2392 |
// Note that failure is an expected outcome here, so we report output only |
| 2393 |
// in debug mode and don't report the error. |
| 2394 |
if cfg.BuildN || cfg.BuildX { |
| 2395 |
saw := "succeeded" |
| 2396 |
if err != nil { |
| 2397 |
saw = "failed" |
| 2398 |
} |
| 2399 |
sh.ShowCmd("", "%s # test for internal linking errors (%s)", joinUnambiguously(str.StringList(cmdargs...)), saw) |
| 2400 |
} |
| 2401 |
|
| 2402 |
return err |
| 2403 |
} |
| 2404 |
|
| 2405 |
// GccCmd returns a gcc command line prefix |
| 2406 |
// defaultCC is defined in zdefaultcc.go, written by cmd/dist. |
| 2407 |
func (b *Builder) GccCmd(incdir, workdir string) []string { |
| 2408 |
return b.compilerCmd(b.ccExe(), incdir, workdir) |
| 2409 |
} |
| 2410 |
|
| 2411 |
// GxxCmd returns a g++ command line prefix |
| 2412 |
// defaultCXX is defined in zdefaultcc.go, written by cmd/dist. |
| 2413 |
func (b *Builder) GxxCmd(incdir, workdir string) []string { |
| 2414 |
return b.compilerCmd(b.cxxExe(), incdir, workdir) |
| 2415 |
} |
| 2416 |
|
| 2417 |
// gfortranCmd returns a gfortran command line prefix. |
| 2418 |
func (b *Builder) gfortranCmd(incdir, workdir string) []string { |
| 2419 |
return b.compilerCmd(b.fcExe(), incdir, workdir) |
| 2420 |
} |
| 2421 |
|
| 2422 |
// ccExe returns the CC compiler setting without all the extra flags we add implicitly. |
| 2423 |
func (b *Builder) ccExe() []string { |
| 2424 |
return envList("CC", cfg.DefaultCC(cfg.Goos, cfg.Goarch)) |
| 2425 |
} |
| 2426 |
|
| 2427 |
// cxxExe returns the CXX compiler setting without all the extra flags we add implicitly. |
| 2428 |
func (b *Builder) cxxExe() []string { |
| 2429 |
return envList("CXX", cfg.DefaultCXX(cfg.Goos, cfg.Goarch)) |
| 2430 |
} |
| 2431 |
|
| 2432 |
// fcExe returns the FC compiler setting without all the extra flags we add implicitly. |
| 2433 |
func (b *Builder) fcExe() []string { |
| 2434 |
return envList("FC", "gfortran") |
| 2435 |
} |
| 2436 |
|
| 2437 |
// compilerCmd returns a command line prefix for the given environment |
| 2438 |
// variable and using the default command when the variable is empty. |
| 2439 |
func (b *Builder) compilerCmd(compiler []string, incdir, workdir string) []string { |
| 2440 |
a := append(compiler, "-I", incdir) |
| 2441 |
|
| 2442 |
// Definitely want -fPIC but on Windows gcc complains |
| 2443 |
// "-fPIC ignored for target (all code is position independent)" |
| 2444 |
if cfg.Goos != "windows" { |
| 2445 |
a = append(a, "-fPIC") |
| 2446 |
} |
| 2447 |
a = append(a, b.gccArchArgs()...) |
| 2448 |
// gcc-4.5 and beyond require explicit "-pthread" flag |
| 2449 |
// for multithreading with pthread library. |
| 2450 |
if cfg.BuildContext.CgoEnabled { |
| 2451 |
switch cfg.Goos { |
| 2452 |
case "windows": |
| 2453 |
a = append(a, "-mthreads") |
| 2454 |
default: |
| 2455 |
a = append(a, "-pthread") |
| 2456 |
} |
| 2457 |
} |
| 2458 |
|
| 2459 |
if cfg.Goos == "aix" { |
| 2460 |
// mcmodel=large must always be enabled to allow large TOC. |
| 2461 |
a = append(a, "-mcmodel=large") |
| 2462 |
} |
| 2463 |
|
| 2464 |
// disable ASCII art in clang errors, if possible |
| 2465 |
if b.gccSupportsFlag(compiler, "-fno-caret-diagnostics") { |
| 2466 |
a = append(a, "-fno-caret-diagnostics") |
| 2467 |
} |
| 2468 |
// clang is too smart about command-line arguments |
| 2469 |
if b.gccSupportsFlag(compiler, "-Qunused-arguments") { |
| 2470 |
a = append(a, "-Qunused-arguments") |
| 2471 |
} |
| 2472 |
|
| 2473 |
// zig cc passes --gc-sections to the underlying linker, which then causes |
| 2474 |
// undefined symbol errors when compiling with cgo but without C code. |
| 2475 |
// https://github.com/golang/go/issues/52690 |
| 2476 |
if b.gccSupportsFlag(compiler, "-Wl,--no-gc-sections") { |
| 2477 |
a = append(a, "-Wl,--no-gc-sections") |
| 2478 |
} |
| 2479 |
|
| 2480 |
// disable word wrapping in error messages |
| 2481 |
a = append(a, "-fmessage-length=0") |
| 2482 |
|
| 2483 |
// Tell gcc not to include the work directory in object files. |
| 2484 |
if b.gccSupportsFlag(compiler, "-fdebug-prefix-map=a=b") { |
| 2485 |
if workdir == "" { |
| 2486 |
workdir = b.WorkDir |
| 2487 |
} |
| 2488 |
workdir = strings.TrimSuffix(workdir, string(filepath.Separator)) |
| 2489 |
if b.gccSupportsFlag(compiler, "-ffile-prefix-map=a=b") { |
| 2490 |
a = append(a, "-ffile-prefix-map="+workdir+"=/tmp/go-build") |
| 2491 |
} else { |
| 2492 |
a = append(a, "-fdebug-prefix-map="+workdir+"=/tmp/go-build") |
| 2493 |
} |
| 2494 |
} |
| 2495 |
|
| 2496 |
// Tell gcc not to include flags in object files, which defeats the |
| 2497 |
// point of -fdebug-prefix-map above. |
| 2498 |
if b.gccSupportsFlag(compiler, "-gno-record-gcc-switches") { |
| 2499 |
a = append(a, "-gno-record-gcc-switches") |
| 2500 |
} |
| 2501 |
|
| 2502 |
// On OS X, some of the compilers behave as if -fno-common |
| 2503 |
// is always set, and the Mach-O linker in 6l/8l assumes this. |
| 2504 |
// See https://golang.org/issue/3253. |
| 2505 |
if cfg.Goos == "darwin" || cfg.Goos == "ios" { |
| 2506 |
a = append(a, "-fno-common") |
| 2507 |
} |
| 2508 |
|
| 2509 |
return a |
| 2510 |
} |
| 2511 |
|
| 2512 |
// gccNoPie returns the flag to use to request non-PIE. On systems |
| 2513 |
// with PIE (position independent executables) enabled by default, |
| 2514 |
// -no-pie must be passed when doing a partial link with -Wl,-r. |
| 2515 |
// But -no-pie is not supported by all compilers, and clang spells it -nopie. |
| 2516 |
func (b *Builder) gccNoPie(linker []string) string { |
| 2517 |
if b.gccSupportsFlag(linker, "-no-pie") { |
| 2518 |
return "-no-pie" |
| 2519 |
} |
| 2520 |
if b.gccSupportsFlag(linker, "-nopie") { |
| 2521 |
return "-nopie" |
| 2522 |
} |
| 2523 |
return "" |
| 2524 |
} |
| 2525 |
|
| 2526 |
// gccSupportsFlag checks to see if the compiler supports a flag. |
| 2527 |
func (b *Builder) gccSupportsFlag(compiler []string, flag string) bool { |
| 2528 |
// We use the background shell for operations here because, while this is |
| 2529 |
// triggered by some Action, it's not really about that Action, and often we |
| 2530 |
// just get the results from the global cache. |
| 2531 |
sh := b.BackgroundShell() |
| 2532 |
|
| 2533 |
key := [2]string{compiler[0], flag} |
| 2534 |
|
| 2535 |
// We used to write an empty C file, but that gets complicated with go |
| 2536 |
// build -n. We tried using a file that does not exist, but that fails on |
| 2537 |
// systems with GCC version 4.2.1; that is the last GPLv2 version of GCC, |
| 2538 |
// so some systems have frozen on it. Now we pass an empty file on stdin, |
| 2539 |
// which should work at least for GCC and clang. |
| 2540 |
// |
| 2541 |
// If the argument is "-Wl,", then it is testing the linker. In that case, |
| 2542 |
// skip "-c". If it's not "-Wl,", then we are testing the compiler and can |
| 2543 |
// omit the linking step with "-c". |
| 2544 |
// |
| 2545 |
// Using the same CFLAGS/LDFLAGS here and for building the program. |
| 2546 |
|
| 2547 |
// On the iOS builder the command |
| 2548 |
// $CC -Wl,--no-gc-sections -x c - -o /dev/null < /dev/null |
| 2549 |
// is failing with: |
| 2550 |
// Unable to remove existing file: Invalid argument |
| 2551 |
tmp := os.DevNull |
| 2552 |
if runtime.GOOS == "windows" || runtime.GOOS == "ios" { |
| 2553 |
f, err := os.CreateTemp(b.WorkDir, "") |
| 2554 |
if err != nil { |
| 2555 |
return false |
| 2556 |
} |
| 2557 |
f.Close() |
| 2558 |
tmp = f.Name() |
| 2559 |
defer os.Remove(tmp) |
| 2560 |
} |
| 2561 |
|
| 2562 |
cmdArgs := str.StringList(compiler, flag) |
| 2563 |
if strings.HasPrefix(flag, "-Wl,") /* linker flag */ { |
| 2564 |
ldflags, err := buildFlags("LDFLAGS", DefaultCFlags, nil, checkLinkerFlags) |
| 2565 |
if err != nil { |
| 2566 |
return false |
| 2567 |
} |
| 2568 |
cmdArgs = append(cmdArgs, ldflags...) |
| 2569 |
} else { /* compiler flag, add "-c" */ |
| 2570 |
cflags, err := buildFlags("CFLAGS", DefaultCFlags, nil, checkCompilerFlags) |
| 2571 |
if err != nil { |
| 2572 |
return false |
| 2573 |
} |
| 2574 |
cmdArgs = append(cmdArgs, cflags...) |
| 2575 |
cmdArgs = append(cmdArgs, "-c") |
| 2576 |
} |
| 2577 |
|
| 2578 |
cmdArgs = append(cmdArgs, "-x", "c", "-", "-o", tmp) |
| 2579 |
|
| 2580 |
if cfg.BuildN { |
| 2581 |
sh.ShowCmd(b.WorkDir, "%s || true", joinUnambiguously(cmdArgs)) |
| 2582 |
return false |
| 2583 |
} |
| 2584 |
|
| 2585 |
// gccCompilerID acquires b.exec, so do before acquiring lock. |
| 2586 |
compilerID, cacheOK := b.gccCompilerID(compiler[0]) |
| 2587 |
|
| 2588 |
b.exec.Lock() |
| 2589 |
defer b.exec.Unlock() |
| 2590 |
if b, ok := b.flagCache[key]; ok { |
| 2591 |
return b |
| 2592 |
} |
| 2593 |
if b.flagCache == nil { |
| 2594 |
b.flagCache = make(map[[2]string]bool) |
| 2595 |
} |
| 2596 |
|
| 2597 |
// Look in build cache. |
| 2598 |
var flagID cache.ActionID |
| 2599 |
if cacheOK { |
| 2600 |
flagID = cache.Subkey(compilerID, "gccSupportsFlag "+flag) |
| 2601 |
if data, _, err := cache.GetBytes(cache.Default(), flagID); err == nil { |
| 2602 |
supported := string(data) == "true" |
| 2603 |
b.flagCache[key] = supported |
| 2604 |
return supported |
| 2605 |
} |
| 2606 |
} |
| 2607 |
|
| 2608 |
if cfg.BuildX { |
| 2609 |
sh.ShowCmd(b.WorkDir, "%s || true", joinUnambiguously(cmdArgs)) |
| 2610 |
} |
| 2611 |
cmd := exec.Command(cmdArgs[0], cmdArgs[1:]...) |
| 2612 |
cmd.Dir = b.WorkDir |
| 2613 |
cmd.Env = append(cmd.Environ(), "LC_ALL=C") |
| 2614 |
out, _ := cmd.CombinedOutput() |
| 2615 |
// GCC says "unrecognized command line option". |
| 2616 |
// clang says "unknown argument". |
| 2617 |
// tcc says "unsupported" |
| 2618 |
// AIX says "not recognized" |
| 2619 |
// Older versions of GCC say "unrecognised debug output level". |
| 2620 |
// For -fsplit-stack GCC says "'-fsplit-stack' is not supported". |
| 2621 |
supported := !bytes.Contains(out, []byte("unrecognized")) && |
| 2622 |
!bytes.Contains(out, []byte("unknown")) && |
| 2623 |
!bytes.Contains(out, []byte("unrecognised")) && |
| 2624 |
!bytes.Contains(out, []byte("is not supported")) && |
| 2625 |
!bytes.Contains(out, []byte("not recognized")) && |
| 2626 |
!bytes.Contains(out, []byte("unsupported")) |
| 2627 |
|
| 2628 |
if cacheOK { |
| 2629 |
s := "false" |
| 2630 |
if supported { |
| 2631 |
s = "true" |
| 2632 |
} |
| 2633 |
cache.PutBytes(cache.Default(), flagID, []byte(s)) |
| 2634 |
} |
| 2635 |
|
| 2636 |
b.flagCache[key] = supported |
| 2637 |
return supported |
| 2638 |
} |
| 2639 |
|
| 2640 |
// statString returns a string form of an os.FileInfo, for serializing and comparison. |
| 2641 |
func statString(info os.FileInfo) string { |
| 2642 |
return fmt.Sprintf("stat %d %x %v %v\n", info.Size(), uint64(info.Mode()), info.ModTime(), info.IsDir()) |
| 2643 |
} |
| 2644 |
|
| 2645 |
// gccCompilerID returns a build cache key for the current gcc, |
| 2646 |
// as identified by running 'compiler'. |
| 2647 |
// The caller can use subkeys of the key. |
| 2648 |
// Other parts of cmd/go can use the id as a hash |
| 2649 |
// of the installed compiler version. |
| 2650 |
func (b *Builder) gccCompilerID(compiler string) (id cache.ActionID, ok bool) { |
| 2651 |
// We use the background shell for operations here because, while this is |
| 2652 |
// triggered by some Action, it's not really about that Action, and often we |
| 2653 |
// just get the results from the global cache. |
| 2654 |
sh := b.BackgroundShell() |
| 2655 |
|
| 2656 |
if cfg.BuildN { |
| 2657 |
sh.ShowCmd(b.WorkDir, "%s || true", joinUnambiguously([]string{compiler, "--version"})) |
| 2658 |
return cache.ActionID{}, false |
| 2659 |
} |
| 2660 |
|
| 2661 |
b.exec.Lock() |
| 2662 |
defer b.exec.Unlock() |
| 2663 |
|
| 2664 |
if id, ok := b.gccCompilerIDCache[compiler]; ok { |
| 2665 |
return id, ok |
| 2666 |
} |
| 2667 |
|
| 2668 |
// We hash the compiler's full path to get a cache entry key. |
| 2669 |
// That cache entry holds a validation description, |
| 2670 |
// which is of the form: |
| 2671 |
// |
| 2672 |
// filename \x00 statinfo \x00 |
| 2673 |
// ... |
| 2674 |
// compiler id |
| 2675 |
// |
| 2676 |
// If os.Stat of each filename matches statinfo, |
| 2677 |
// then the entry is still valid, and we can use the |
| 2678 |
// compiler id without any further expense. |
| 2679 |
// |
| 2680 |
// Otherwise, we compute a new validation description |
| 2681 |
// and compiler id (below). |
| 2682 |
exe, err := pathcache.LookPath(compiler) |
| 2683 |
if err != nil { |
| 2684 |
return cache.ActionID{}, false |
| 2685 |
} |
| 2686 |
|
| 2687 |
h := cache.NewHash("gccCompilerID") |
| 2688 |
fmt.Fprintf(h, "gccCompilerID %q", exe) |
| 2689 |
key := h.Sum() |
| 2690 |
data, _, err := cache.GetBytes(cache.Default(), key) |
| 2691 |
if err == nil && len(data) > len(id) { |
| 2692 |
stats := strings.Split(string(data[:len(data)-len(id)]), "\x00") |
| 2693 |
if len(stats)%2 != 0 { |
| 2694 |
goto Miss |
| 2695 |
} |
| 2696 |
for i := 0; i+2 <= len(stats); i++ { |
| 2697 |
info, err := os.Stat(stats[i]) |
| 2698 |
if err != nil || statString(info) != stats[i+1] { |
| 2699 |
goto Miss |
| 2700 |
} |
| 2701 |
} |
| 2702 |
copy(id[:], data[len(data)-len(id):]) |
| 2703 |
return id, true |
| 2704 |
Miss: |
| 2705 |
} |
| 2706 |
|
| 2707 |
// Validation failed. Compute a new description (in buf) and compiler ID (in h). |
| 2708 |
// For now, there are only at most two filenames in the stat information. |
| 2709 |
// The first one is the compiler executable we invoke. |
| 2710 |
// The second is the underlying compiler as reported by -v -### |
| 2711 |
// (see b.gccToolID implementation in buildid.go). |
| 2712 |
toolID, exe2, err := b.gccToolID(compiler, "c") |
| 2713 |
if err != nil { |
| 2714 |
return cache.ActionID{}, false |
| 2715 |
} |
| 2716 |
|
| 2717 |
exes := []string{exe, exe2} |
| 2718 |
str.Uniq(&exes) |
| 2719 |
fmt.Fprintf(h, "gccCompilerID %q %q\n", exes, toolID) |
| 2720 |
id = h.Sum() |
| 2721 |
|
| 2722 |
var buf bytes.Buffer |
| 2723 |
for _, exe := range exes { |
| 2724 |
if exe == "" { |
| 2725 |
continue |
| 2726 |
} |
| 2727 |
info, err := os.Stat(exe) |
| 2728 |
if err != nil { |
| 2729 |
return cache.ActionID{}, false |
| 2730 |
} |
| 2731 |
buf.WriteString(exe) |
| 2732 |
buf.WriteString("\x00") |
| 2733 |
buf.WriteString(statString(info)) |
| 2734 |
buf.WriteString("\x00") |
| 2735 |
} |
| 2736 |
buf.Write(id[:]) |
| 2737 |
|
| 2738 |
cache.PutBytes(cache.Default(), key, buf.Bytes()) |
| 2739 |
if b.gccCompilerIDCache == nil { |
| 2740 |
b.gccCompilerIDCache = make(map[string]cache.ActionID) |
| 2741 |
} |
| 2742 |
b.gccCompilerIDCache[compiler] = id |
| 2743 |
return id, true |
| 2744 |
} |
| 2745 |
|
| 2746 |
// gccArchArgs returns arguments to pass to gcc based on the architecture. |
| 2747 |
func (b *Builder) gccArchArgs() []string { |
| 2748 |
switch cfg.Goarch { |
| 2749 |
case "386": |
| 2750 |
return []string{"-m32"} |
| 2751 |
case "amd64": |
| 2752 |
if cfg.Goos == "darwin" { |
| 2753 |
return []string{"-arch", "x86_64", "-m64"} |
| 2754 |
} |
| 2755 |
return []string{"-m64"} |
| 2756 |
case "arm64": |
| 2757 |
if cfg.Goos == "darwin" { |
| 2758 |
return []string{"-arch", "arm64"} |
| 2759 |
} |
| 2760 |
case "arm": |
| 2761 |
return []string{"-marm"} // not thumb |
| 2762 |
case "s390x": |
| 2763 |
// minimum supported s390x version on Go is z13 |
| 2764 |
return []string{"-m64", "-march=z13"} |
| 2765 |
case "mips64", "mips64le": |
| 2766 |
args := []string{"-mabi=64"} |
| 2767 |
if cfg.GOMIPS64 == "hardfloat" { |
| 2768 |
return append(args, "-mhard-float") |
| 2769 |
} else if cfg.GOMIPS64 == "softfloat" { |
| 2770 |
return append(args, "-msoft-float") |
| 2771 |
} |
| 2772 |
case "mips", "mipsle": |
| 2773 |
args := []string{"-mabi=32", "-march=mips32"} |
| 2774 |
if cfg.GOMIPS == "hardfloat" { |
| 2775 |
return append(args, "-mhard-float", "-mfp32", "-mno-odd-spreg") |
| 2776 |
} else if cfg.GOMIPS == "softfloat" { |
| 2777 |
return append(args, "-msoft-float") |
| 2778 |
} |
| 2779 |
case "loong64": |
| 2780 |
return []string{"-mabi=lp64d"} |
| 2781 |
case "ppc64": |
| 2782 |
if cfg.Goos == "aix" { |
| 2783 |
return []string{"-maix64"} |
| 2784 |
} |
| 2785 |
} |
| 2786 |
return nil |
| 2787 |
} |
| 2788 |
|
| 2789 |
// envList returns the value of the given environment variable broken |
| 2790 |
// into fields, using the default value when the variable is empty. |
| 2791 |
// |
| 2792 |
// The environment variable must be quoted correctly for |
| 2793 |
// quoted.Split. This should be done before building |
| 2794 |
// anything, for example, in BuildInit. |
| 2795 |
func envList(key, def string) []string { |
| 2796 |
v := cfg.Getenv(key) |
| 2797 |
if v == "" { |
| 2798 |
v = def |
| 2799 |
} |
| 2800 |
args, err := quoted.Split(v) |
| 2801 |
if err != nil { |
| 2802 |
panic(fmt.Sprintf("could not parse environment variable %s with value %q: %v", key, v, err)) |
| 2803 |
} |
| 2804 |
return args |
| 2805 |
} |
| 2806 |
|
| 2807 |
// CFlags returns the flags to use when invoking the C, C++ or Fortran compilers, or cgo. |
| 2808 |
func (b *Builder) CFlags(p *load.Package) (cppflags, cflags, cxxflags, fflags, ldflags []string, err error) { |
| 2809 |
if cppflags, err = buildFlags("CPPFLAGS", "", p.CgoCPPFLAGS, checkCompilerFlags); err != nil { |
| 2810 |
return |
| 2811 |
} |
| 2812 |
if cflags, err = buildFlags("CFLAGS", DefaultCFlags, p.CgoCFLAGS, checkCompilerFlags); err != nil { |
| 2813 |
return |
| 2814 |
} |
| 2815 |
if cxxflags, err = buildFlags("CXXFLAGS", DefaultCFlags, p.CgoCXXFLAGS, checkCompilerFlags); err != nil { |
| 2816 |
return |
| 2817 |
} |
| 2818 |
if fflags, err = buildFlags("FFLAGS", DefaultCFlags, p.CgoFFLAGS, checkCompilerFlags); err != nil { |
| 2819 |
return |
| 2820 |
} |
| 2821 |
if ldflags, err = buildFlags("LDFLAGS", DefaultCFlags, p.CgoLDFLAGS, checkLinkerFlags); err != nil { |
| 2822 |
return |
| 2823 |
} |
| 2824 |
|
| 2825 |
return |
| 2826 |
} |
| 2827 |
|
| 2828 |
func buildFlags(name, defaults string, fromPackage []string, check func(string, string, []string) error) ([]string, error) { |
| 2829 |
if err := check(name, "#cgo "+name, fromPackage); err != nil { |
| 2830 |
return nil, err |
| 2831 |
} |
| 2832 |
return str.StringList(envList("CGO_"+name, defaults), fromPackage), nil |
| 2833 |
} |
| 2834 |
|
| 2835 |
var cgoRe = lazyregexp.New(`[/\\:]`) |
| 2836 |
|
| 2837 |
type runCgoProvider struct { |
| 2838 |
CFLAGS, CXXFLAGS, FFLAGS, LDFLAGS []string |
| 2839 |
notCompatibleForInternalLinking bool |
| 2840 |
nonGoOverlay map[string]string |
| 2841 |
goFiles []string // processed cgo files for the compiler |
| 2842 |
} |
| 2843 |
|
| 2844 |
func (pr *runCgoProvider) cflags() []string { |
| 2845 |
return pr.CFLAGS |
| 2846 |
} |
| 2847 |
|
| 2848 |
func (pr *runCgoProvider) cxxflags() []string { |
| 2849 |
return pr.CXXFLAGS |
| 2850 |
} |
| 2851 |
|
| 2852 |
func (pr *runCgoProvider) fflags() []string { |
| 2853 |
return pr.FFLAGS |
| 2854 |
} |
| 2855 |
|
| 2856 |
func (pr *runCgoProvider) ldflags() []string { |
| 2857 |
return pr.LDFLAGS |
| 2858 |
} |
| 2859 |
|
| 2860 |
func mustGetCoverInfo(a *Action) *coverProvider { |
| 2861 |
for _, dep := range a.Deps { |
| 2862 |
if dep.Mode == "cover" { |
| 2863 |
return dep.Provider.(*coverProvider) |
| 2864 |
} |
| 2865 |
} |
| 2866 |
base.Fatalf("internal error: cover provider not found") |
| 2867 |
panic("unreachable") |
| 2868 |
} |
| 2869 |
|
| 2870 |
func (b *Builder) runCgo(ctx context.Context, a *Action) error { |
| 2871 |
p := a.Package |
| 2872 |
sh := b.Shell(a) |
| 2873 |
objdir := a.Objdir |
| 2874 |
|
| 2875 |
if err := sh.Mkdir(objdir); err != nil { |
| 2876 |
return err |
| 2877 |
} |
| 2878 |
|
| 2879 |
nonGoFileLists := [][]string{p.CFiles, p.SFiles, p.CXXFiles, p.HFiles, p.FFiles} |
| 2880 |
if err := b.computeNonGoOverlay(a, p, sh, objdir, nonGoFileLists); err != nil { |
| 2881 |
return err |
| 2882 |
} |
| 2883 |
|
| 2884 |
cgofiles := slices.Clip(p.CgoFiles) |
| 2885 |
if a.Package.Internal.Cover.Mode != "" { |
| 2886 |
cp := mustGetCoverInfo(a) |
| 2887 |
cgofiles = cp.cgoSources |
| 2888 |
} |
| 2889 |
|
| 2890 |
pcCFLAGS, pcLDFLAGS, err := b.getPkgConfigFlags(a, p) |
| 2891 |
if err != nil { |
| 2892 |
return err |
| 2893 |
} |
| 2894 |
|
| 2895 |
// Run SWIG on each .swig and .swigcxx file. |
| 2896 |
// Each run will generate two files, a .go file and a .c or .cxx file. |
| 2897 |
// The .go file will use import "C" and is to be processed by cgo. |
| 2898 |
// For -cover test or build runs, this needs to happen after the cover |
| 2899 |
// tool is run; we don't want to instrument swig-generated Go files, |
| 2900 |
// see issue #64661. |
| 2901 |
if p.UsesSwig() { |
| 2902 |
if err := b.swig(a, objdir, pcCFLAGS); err != nil { |
| 2903 |
return err |
| 2904 |
} |
| 2905 |
outGo, _, _ := b.swigOutputs(p, objdir) |
| 2906 |
cgofiles = append(cgofiles, outGo...) |
| 2907 |
} |
| 2908 |
|
| 2909 |
cgoExe := base.Tool("cgo") |
| 2910 |
cgofiles = mkAbsFiles(p.Dir, cgofiles) |
| 2911 |
|
| 2912 |
cgoCPPFLAGS, cgoCFLAGS, cgoCXXFLAGS, cgoFFLAGS, cgoLDFLAGS, err := b.CFlags(p) |
| 2913 |
if err != nil { |
| 2914 |
return err |
| 2915 |
} |
| 2916 |
|
| 2917 |
cgoCPPFLAGS = append(cgoCPPFLAGS, pcCFLAGS...) |
| 2918 |
cgoLDFLAGS = append(cgoLDFLAGS, pcLDFLAGS...) |
| 2919 |
// If we are compiling Objective-C code, then we need to link against libobjc |
| 2920 |
if len(p.MFiles) > 0 { |
| 2921 |
cgoLDFLAGS = append(cgoLDFLAGS, "-lobjc") |
| 2922 |
} |
| 2923 |
|
| 2924 |
// Likewise for Fortran, except there are many Fortran compilers. |
| 2925 |
// Support gfortran out of the box and let others pass the correct link options |
| 2926 |
// via CGO_LDFLAGS |
| 2927 |
if len(p.FFiles) > 0 { |
| 2928 |
fc := cfg.Getenv("FC") |
| 2929 |
if fc == "" { |
| 2930 |
fc = "gfortran" |
| 2931 |
} |
| 2932 |
if strings.Contains(fc, "gfortran") { |
| 2933 |
cgoLDFLAGS = append(cgoLDFLAGS, "-lgfortran") |
| 2934 |
} |
| 2935 |
} |
| 2936 |
|
| 2937 |
// Scrutinize CFLAGS and related for flags that might cause |
| 2938 |
// problems if we are using internal linking (for example, use of |
| 2939 |
// plugins, LTO, etc) by calling a helper routine that builds on |
| 2940 |
// the existing CGO flags allow-lists. If we see anything |
| 2941 |
// suspicious, emit a special token file "preferlinkext" (known to |
| 2942 |
// the linker) in the object file to signal the that it should not |
| 2943 |
// try to link internally and should revert to external linking. |
| 2944 |
// The token we pass is a suggestion, not a mandate; if a user is |
| 2945 |
// explicitly asking for a specific linkmode via the "-linkmode" |
| 2946 |
// flag, the token will be ignored. NB: in theory we could ditch |
| 2947 |
// the token approach and just pass a flag to the linker when we |
| 2948 |
// eventually invoke it, and the linker flag could then be |
| 2949 |
// documented (although coming up with a simple explanation of the |
| 2950 |
// flag might be challenging). For more context see issues #58619, |
| 2951 |
// #58620, and #58848. |
| 2952 |
flagSources := []string{"CGO_CFLAGS", "CGO_CXXFLAGS", "CGO_FFLAGS"} |
| 2953 |
flagLists := [][]string{cgoCFLAGS, cgoCXXFLAGS, cgoFFLAGS} |
| 2954 |
notCompatibleWithInternalLinking := flagsNotCompatibleWithInternalLinking(flagSources, flagLists) |
| 2955 |
|
| 2956 |
if cfg.BuildMSan { |
| 2957 |
cgoCFLAGS = append([]string{"-fsanitize=memory"}, cgoCFLAGS...) |
| 2958 |
cgoLDFLAGS = append([]string{"-fsanitize=memory"}, cgoLDFLAGS...) |
| 2959 |
} |
| 2960 |
if cfg.BuildASan { |
| 2961 |
cgoCFLAGS = append([]string{"-fsanitize=address"}, cgoCFLAGS...) |
| 2962 |
cgoLDFLAGS = append([]string{"-fsanitize=address"}, cgoLDFLAGS...) |
| 2963 |
} |
| 2964 |
|
| 2965 |
// Allows including _cgo_export.h, as well as the user's .h files, |
| 2966 |
// from .[ch] files in the package. |
| 2967 |
cgoCPPFLAGS = append(cgoCPPFLAGS, "-I", objdir) |
| 2968 |
|
| 2969 |
// cgo |
| 2970 |
// TODO: CGO_FLAGS? |
| 2971 |
gofiles := []string{objdir + "_cgo_gotypes.go"} |
| 2972 |
cfiles := []string{objdir + "_cgo_export.c"} |
| 2973 |
for _, fn := range cgofiles { |
| 2974 |
f := strings.TrimSuffix(filepath.Base(fn), ".go") |
| 2975 |
gofiles = append(gofiles, objdir+f+".cgo1.go") |
| 2976 |
cfiles = append(cfiles, objdir+f+".cgo2.c") |
| 2977 |
} |
| 2978 |
|
| 2979 |
// TODO: make cgo not depend on $GOARCH? |
| 2980 |
|
| 2981 |
cgoflags := []string{} |
| 2982 |
if p.Standard && p.ImportPath == "runtime/cgo" { |
| 2983 |
cgoflags = append(cgoflags, "-import_runtime_cgo=false") |
| 2984 |
} |
| 2985 |
if p.Standard && (p.ImportPath == "runtime/race" || p.ImportPath == "runtime/msan" || p.ImportPath == "runtime/cgo" || p.ImportPath == "runtime/asan") { |
| 2986 |
cgoflags = append(cgoflags, "-import_syscall=false") |
| 2987 |
} |
| 2988 |
|
| 2989 |
// cgoLDFLAGS, which includes p.CgoLDFLAGS, can be very long. |
| 2990 |
// Pass it to cgo on the command line, so that we use a |
| 2991 |
// response file if necessary. |
| 2992 |
// |
| 2993 |
// These flags are recorded in the generated _cgo_gotypes.go file |
| 2994 |
// using //go:cgo_ldflag directives, the compiler records them in the |
| 2995 |
// object file for the package, and then the Go linker passes them |
| 2996 |
// along to the host linker. At this point in the code, cgoLDFLAGS |
| 2997 |
// consists of the original $CGO_LDFLAGS (unchecked) and all the |
| 2998 |
// flags put together from source code (checked). |
| 2999 |
cgoenv := b.cCompilerEnv() |
| 3000 |
cgoenv = append(cgoenv, cfgChangedEnv...) |
| 3001 |
var ldflagsOption []string |
| 3002 |
if len(cgoLDFLAGS) > 0 { |
| 3003 |
flags := make([]string, len(cgoLDFLAGS)) |
| 3004 |
for i, f := range cgoLDFLAGS { |
| 3005 |
flags[i] = strconv.Quote(f) |
| 3006 |
} |
| 3007 |
ldflagsOption = []string{"-ldflags=" + strings.Join(flags, " ")} |
| 3008 |
|
| 3009 |
// Remove CGO_LDFLAGS from the environment. |
| 3010 |
cgoenv = append(cgoenv, "CGO_LDFLAGS=") |
| 3011 |
} |
| 3012 |
|
| 3013 |
if cfg.BuildToolchainName == "gccgo" { |
| 3014 |
if b.gccSupportsFlag([]string{BuildToolchain.compiler()}, "-fsplit-stack") { |
| 3015 |
cgoCFLAGS = append(cgoCFLAGS, "-fsplit-stack") |
| 3016 |
} |
| 3017 |
cgoflags = append(cgoflags, "-gccgo") |
| 3018 |
if pkgpath := gccgoPkgpath(p); pkgpath != "" { |
| 3019 |
cgoflags = append(cgoflags, "-gccgopkgpath="+pkgpath) |
| 3020 |
} |
| 3021 |
if !BuildToolchain.(gccgoToolchain).supportsCgoIncomplete(b, a) { |
| 3022 |
cgoflags = append(cgoflags, "-gccgo_define_cgoincomplete") |
| 3023 |
} |
| 3024 |
} |
| 3025 |
|
| 3026 |
switch cfg.BuildBuildmode { |
| 3027 |
case "c-archive", "c-shared": |
| 3028 |
// Tell cgo that if there are any exported functions |
| 3029 |
// it should generate a header file that C code can |
| 3030 |
// #include. |
| 3031 |
cgoflags = append(cgoflags, "-exportheader="+objdir+"_cgo_install.h") |
| 3032 |
} |
| 3033 |
|
| 3034 |
// Rewrite overlaid paths in cgo files. |
| 3035 |
// cgo adds //line and #line pragmas in generated files with these paths. |
| 3036 |
var trimpath []string |
| 3037 |
for i := range cgofiles { |
| 3038 |
path := mkAbs(p.Dir, cgofiles[i]) |
| 3039 |
if fsys.Replaced(path) { |
| 3040 |
actual := fsys.Actual(path) |
| 3041 |
cgofiles[i] = actual |
| 3042 |
trimpath = append(trimpath, actual+"=>"+path) |
| 3043 |
} |
| 3044 |
} |
| 3045 |
if len(trimpath) > 0 { |
| 3046 |
cgoflags = append(cgoflags, "-trimpath", strings.Join(trimpath, ";")) |
| 3047 |
} |
| 3048 |
|
| 3049 |
if err := sh.run(p.Dir, p.ImportPath, cgoenv, cfg.BuildToolexec, cgoExe, "-objdir", objdir, "-importpath", p.ImportPath, cgoflags, ldflagsOption, "--", cgoCPPFLAGS, cgoCFLAGS, cgofiles); err != nil { |
| 3050 |
return err |
| 3051 |
} |
| 3052 |
|
| 3053 |
a.Provider = &runCgoProvider{ |
| 3054 |
CFLAGS: str.StringList(cgoCPPFLAGS, cgoCFLAGS), |
| 3055 |
CXXFLAGS: str.StringList(cgoCPPFLAGS, cgoCXXFLAGS), |
| 3056 |
FFLAGS: str.StringList(cgoCPPFLAGS, cgoFFLAGS), |
| 3057 |
LDFLAGS: cgoLDFLAGS, |
| 3058 |
notCompatibleForInternalLinking: notCompatibleWithInternalLinking, |
| 3059 |
nonGoOverlay: a.nonGoOverlay, |
| 3060 |
goFiles: gofiles, |
| 3061 |
} |
| 3062 |
|
| 3063 |
return nil |
| 3064 |
} |
| 3065 |
|
| 3066 |
func (b *Builder) processCgoOutputs(a *Action, runCgoProvider *runCgoProvider, cgoExe, objdir string) (outGo, outObj []string, err error) { |
| 3067 |
outGo = slices.Clip(runCgoProvider.goFiles) |
| 3068 |
|
| 3069 |
// TODO(matloob): Pretty much the only thing this function is doing is |
| 3070 |
// producing the dynimport go files. But we should be able to compile |
| 3071 |
// those separately from the package itself: we just need to get the |
| 3072 |
// compiled output to the linker. That means that we can remove the |
| 3073 |
// dependency of this build action on the outputs of the cgo compile actions |
| 3074 |
// (though we'd still need to depend on the runCgo action of course). |
| 3075 |
|
| 3076 |
sh := b.Shell(a) |
| 3077 |
|
| 3078 |
// Output the preferlinkext file if the run cgo action determined this package |
| 3079 |
// was not compatible for internal linking based on CFLAGS, CXXFLAGS, or FFLAGS. |
| 3080 |
if runCgoProvider.notCompatibleForInternalLinking { |
| 3081 |
tokenFile := objdir + "preferlinkext" |
| 3082 |
if err := sh.writeFile(tokenFile, nil); err != nil { |
| 3083 |
return nil, nil, err |
| 3084 |
} |
| 3085 |
outObj = append(outObj, tokenFile) |
| 3086 |
} |
| 3087 |
|
| 3088 |
var collectAction *Action |
| 3089 |
for _, dep := range a.Deps { |
| 3090 |
if dep.Mode == "collect cgo" { |
| 3091 |
collectAction = dep |
| 3092 |
} |
| 3093 |
} |
| 3094 |
if collectAction == nil { |
| 3095 |
base.Fatalf("internal error: no cgo collect action") |
| 3096 |
} |
| 3097 |
for _, dep := range collectAction.Deps { |
| 3098 |
outObj = append(outObj, dep.Target) |
| 3099 |
} |
| 3100 |
|
| 3101 |
switch cfg.BuildToolchainName { |
| 3102 |
case "gc": |
| 3103 |
importGo := objdir + "_cgo_import.go" |
| 3104 |
dynOutGo, dynOutObj, err := b.dynimport(a, objdir, importGo, cgoExe, runCgoProvider.CFLAGS, runCgoProvider.LDFLAGS, outObj) |
| 3105 |
if err != nil { |
| 3106 |
return nil, nil, err |
| 3107 |
} |
| 3108 |
if dynOutGo != "" { |
| 3109 |
outGo = append(outGo, dynOutGo) |
| 3110 |
} |
| 3111 |
if dynOutObj != "" { |
| 3112 |
outObj = append(outObj, dynOutObj) |
| 3113 |
} |
| 3114 |
|
| 3115 |
case "gccgo": |
| 3116 |
defunC := objdir + "_cgo_defun.c" |
| 3117 |
defunObj := objdir + "_cgo_defun.o" |
| 3118 |
if err := BuildToolchain.cc(b, a, defunObj, defunC); err != nil { |
| 3119 |
return nil, nil, err |
| 3120 |
} |
| 3121 |
outObj = append(outObj, defunObj) |
| 3122 |
|
| 3123 |
default: |
| 3124 |
noCompiler() |
| 3125 |
} |
| 3126 |
|
| 3127 |
// Double check the //go:cgo_ldflag comments in the generated files. |
| 3128 |
// The compiler only permits such comments in files whose base name |
| 3129 |
// starts with "_cgo_". Make sure that the comments in those files |
| 3130 |
// are safe. This is a backstop against people somehow smuggling |
| 3131 |
// such a comment into a file generated by cgo. |
| 3132 |
if cfg.BuildToolchainName == "gc" && !cfg.BuildN { |
| 3133 |
var flags []string |
| 3134 |
for _, f := range outGo { |
| 3135 |
if !strings.HasPrefix(filepath.Base(f), "_cgo_") { |
| 3136 |
continue |
| 3137 |
} |
| 3138 |
|
| 3139 |
src, err := os.ReadFile(f) |
| 3140 |
if err != nil { |
| 3141 |
return nil, nil, err |
| 3142 |
} |
| 3143 |
|
| 3144 |
const cgoLdflag = "//go:cgo_ldflag" |
| 3145 |
idx := bytes.Index(src, []byte(cgoLdflag)) |
| 3146 |
for idx >= 0 { |
| 3147 |
// We are looking at //go:cgo_ldflag. |
| 3148 |
// Find start of line. |
| 3149 |
start := bytes.LastIndex(src[:idx], []byte("\n")) |
| 3150 |
if start == -1 { |
| 3151 |
start = 0 |
| 3152 |
} |
| 3153 |
|
| 3154 |
// Find end of line. |
| 3155 |
end := bytes.Index(src[idx:], []byte("\n")) |
| 3156 |
if end == -1 { |
| 3157 |
end = len(src) |
| 3158 |
} else { |
| 3159 |
end += idx |
| 3160 |
} |
| 3161 |
|
| 3162 |
// Check for first line comment in line. |
| 3163 |
// We don't worry about /* */ comments, |
| 3164 |
// which normally won't appear in files |
| 3165 |
// generated by cgo. |
| 3166 |
commentStart := bytes.Index(src[start:], []byte("//")) |
| 3167 |
commentStart += start |
| 3168 |
// If that line comment is //go:cgo_ldflag, |
| 3169 |
// it's a match. |
| 3170 |
if bytes.HasPrefix(src[commentStart:], []byte(cgoLdflag)) { |
| 3171 |
// Pull out the flag, and unquote it. |
| 3172 |
// This is what the compiler does. |
| 3173 |
flag := string(src[idx+len(cgoLdflag) : end]) |
| 3174 |
flag = strings.TrimSpace(flag) |
| 3175 |
flag = strings.Trim(flag, `"`) |
| 3176 |
flags = append(flags, flag) |
| 3177 |
} |
| 3178 |
src = src[end:] |
| 3179 |
idx = bytes.Index(src, []byte(cgoLdflag)) |
| 3180 |
} |
| 3181 |
} |
| 3182 |
|
| 3183 |
// We expect to find the contents of cgoLDFLAGS used when running the CGO action in flags. |
| 3184 |
if len(runCgoProvider.LDFLAGS) > 0 { |
| 3185 |
outer: |
| 3186 |
for i := range flags { |
| 3187 |
for j, f := range runCgoProvider.LDFLAGS { |
| 3188 |
if f != flags[i+j] { |
| 3189 |
continue outer |
| 3190 |
} |
| 3191 |
} |
| 3192 |
flags = append(flags[:i], flags[i+len(runCgoProvider.LDFLAGS):]...) |
| 3193 |
break |
| 3194 |
} |
| 3195 |
} |
| 3196 |
|
| 3197 |
if err := checkLinkerFlags("LDFLAGS", "go:cgo_ldflag", flags); err != nil { |
| 3198 |
return nil, nil, err |
| 3199 |
} |
| 3200 |
} |
| 3201 |
|
| 3202 |
return outGo, outObj, nil |
| 3203 |
} |
| 3204 |
|
| 3205 |
// flagsNotCompatibleWithInternalLinking scans the list of cgo |
| 3206 |
// compiler flags (C/C++/Fortran) looking for flags that might cause |
| 3207 |
// problems if the build in question uses internal linking. The |
| 3208 |
// primary culprits are use of plugins or use of LTO, but we err on |
| 3209 |
// the side of caution, supporting only those flags that are on the |
| 3210 |
// allow-list for safe flags from security perspective. Return is TRUE |
| 3211 |
// if a sensitive flag is found, FALSE otherwise. |
| 3212 |
func flagsNotCompatibleWithInternalLinking(sourceList []string, flagListList [][]string) bool { |
| 3213 |
for i := range sourceList { |
| 3214 |
sn := sourceList[i] |
| 3215 |
fll := flagListList[i] |
| 3216 |
if err := checkCompilerFlagsForInternalLink(sn, sn, fll); err != nil { |
| 3217 |
return true |
| 3218 |
} |
| 3219 |
} |
| 3220 |
return false |
| 3221 |
} |
| 3222 |
|
| 3223 |
// dynimport creates a Go source file named importGo containing |
| 3224 |
// //go:cgo_import_dynamic directives for each symbol or library |
| 3225 |
// dynamically imported by the object files outObj. |
| 3226 |
// dynOutGo, if not empty, is a new Go file to build as part of the package. |
| 3227 |
// dynOutObj, if not empty, is a new file to add to the generated archive. |
| 3228 |
func (b *Builder) dynimport(a *Action, objdir, importGo, cgoExe string, cflags, cgoLDFLAGS, outObj []string) (dynOutGo, dynOutObj string, err error) { |
| 3229 |
p := a.Package |
| 3230 |
sh := b.Shell(a) |
| 3231 |
|
| 3232 |
cfile := objdir + "_cgo_main.c" |
| 3233 |
ofile := objdir + "_cgo_main.o" |
| 3234 |
if err := b.gcc(a, objdir, ofile, cflags, cfile); err != nil { |
| 3235 |
return "", "", err |
| 3236 |
} |
| 3237 |
|
| 3238 |
// Gather .syso files from this package and all (transitive) dependencies. |
| 3239 |
var syso []string |
| 3240 |
seen := make(map[*Action]bool) |
| 3241 |
var gatherSyso func(*Action) |
| 3242 |
gatherSyso = func(a1 *Action) { |
| 3243 |
if seen[a1] { |
| 3244 |
return |
| 3245 |
} |
| 3246 |
seen[a1] = true |
| 3247 |
if p1 := a1.Package; p1 != nil { |
| 3248 |
syso = append(syso, mkAbsFiles(p1.Dir, p1.SysoFiles)...) |
| 3249 |
} |
| 3250 |
for _, a2 := range a1.Deps { |
| 3251 |
gatherSyso(a2) |
| 3252 |
} |
| 3253 |
} |
| 3254 |
gatherSyso(a) |
| 3255 |
sort.Strings(syso) |
| 3256 |
str.Uniq(&syso) |
| 3257 |
linkobj := str.StringList(ofile, outObj, syso) |
| 3258 |
dynobj := objdir + "_cgo_.o" |
| 3259 |
|
| 3260 |
ldflags := cgoLDFLAGS |
| 3261 |
if (cfg.Goarch == "arm" && cfg.Goos == "linux") || cfg.Goos == "android" { |
| 3262 |
if !slices.Contains(ldflags, "-no-pie") { |
| 3263 |
// we need to use -pie for Linux/ARM to get accurate imported sym (added in https://golang.org/cl/5989058) |
| 3264 |
// this seems to be outdated, but we don't want to break existing builds depending on this (Issue 45940) |
| 3265 |
ldflags = append(ldflags, "-pie") |
| 3266 |
} |
| 3267 |
if slices.Contains(ldflags, "-pie") && slices.Contains(ldflags, "-static") { |
| 3268 |
// -static -pie doesn't make sense, and causes link errors. |
| 3269 |
// Issue 26197. |
| 3270 |
n := make([]string, 0, len(ldflags)-1) |
| 3271 |
for _, flag := range ldflags { |
| 3272 |
if flag != "-static" { |
| 3273 |
n = append(n, flag) |
| 3274 |
} |
| 3275 |
} |
| 3276 |
ldflags = n |
| 3277 |
} |
| 3278 |
} |
| 3279 |
if err := b.gccld(a, objdir, dynobj, ldflags, linkobj); err != nil { |
| 3280 |
// We only need this information for internal linking. |
| 3281 |
// If this link fails, mark the object as requiring |
| 3282 |
// external linking. This link can fail for things like |
| 3283 |
// syso files that have unexpected dependencies. |
| 3284 |
// cmd/link explicitly looks for the name "dynimportfail". |
| 3285 |
// See issue #52863. |
| 3286 |
fail := objdir + "dynimportfail" |
| 3287 |
if err := sh.writeFile(fail, nil); err != nil { |
| 3288 |
return "", "", err |
| 3289 |
} |
| 3290 |
return "", fail, nil |
| 3291 |
} |
| 3292 |
|
| 3293 |
// cgo -dynimport |
| 3294 |
var cgoflags []string |
| 3295 |
if p.Standard && p.ImportPath == "runtime/cgo" { |
| 3296 |
cgoflags = []string{"-dynlinker"} // record path to dynamic linker |
| 3297 |
} |
| 3298 |
err = sh.run(base.Cwd(), p.ImportPath, b.cCompilerEnv(), cfg.BuildToolexec, cgoExe, "-dynpackage", p.Name, "-dynimport", dynobj, "-dynout", importGo, cgoflags) |
| 3299 |
if err != nil { |
| 3300 |
return "", "", err |
| 3301 |
} |
| 3302 |
return importGo, "", nil |
| 3303 |
} |
| 3304 |
|
| 3305 |
// Run SWIG on all SWIG input files. |
| 3306 |
// TODO: Don't build a shared library, once SWIG emits the necessary |
| 3307 |
// pragmas for external linking. |
| 3308 |
func (b *Builder) swig(a *Action, objdir string, pcCFLAGS []string) error { |
| 3309 |
p := a.Package |
| 3310 |
|
| 3311 |
if err := b.swigVersionCheck(); err != nil { |
| 3312 |
return err |
| 3313 |
} |
| 3314 |
|
| 3315 |
intgosize, err := b.swigIntSize(objdir) |
| 3316 |
if err != nil { |
| 3317 |
return err |
| 3318 |
} |
| 3319 |
|
| 3320 |
for _, f := range p.SwigFiles { |
| 3321 |
if err := b.swigOne(a, f, objdir, pcCFLAGS, false, intgosize); err != nil { |
| 3322 |
return err |
| 3323 |
} |
| 3324 |
} |
| 3325 |
for _, f := range p.SwigCXXFiles { |
| 3326 |
if b.swigOne(a, f, objdir, pcCFLAGS, true, intgosize); err != nil { |
| 3327 |
return err |
| 3328 |
} |
| 3329 |
} |
| 3330 |
return nil |
| 3331 |
} |
| 3332 |
|
| 3333 |
func (b *Builder) swigOutputs(p *load.Package, objdir string) (outGo, outC, outCXX []string) { |
| 3334 |
for _, f := range p.SwigFiles { |
| 3335 |
goFile, cFile := swigOneOutputs(f, objdir, false) |
| 3336 |
outGo = append(outGo, goFile) |
| 3337 |
outC = append(outC, cFile) |
| 3338 |
} |
| 3339 |
for _, f := range p.SwigCXXFiles { |
| 3340 |
goFile, cxxFile := swigOneOutputs(f, objdir, true) |
| 3341 |
outGo = append(outGo, goFile) |
| 3342 |
outCXX = append(outCXX, cxxFile) |
| 3343 |
} |
| 3344 |
return outGo, outC, outCXX |
| 3345 |
} |
| 3346 |
|
| 3347 |
// Make sure SWIG is new enough. |
| 3348 |
var ( |
| 3349 |
swigCheckOnce sync.Once |
| 3350 |
swigCheck error |
| 3351 |
) |
| 3352 |
|
| 3353 |
func (b *Builder) swigDoVersionCheck() error { |
| 3354 |
sh := b.BackgroundShell() |
| 3355 |
out, err := sh.runOut(".", nil, "swig", "-version") |
| 3356 |
if err != nil { |
| 3357 |
return err |
| 3358 |
} |
| 3359 |
re := regexp.MustCompile(`[vV]ersion +(\d+)([.]\d+)?([.]\d+)?`) |
| 3360 |
matches := re.FindSubmatch(out) |
| 3361 |
if matches == nil { |
| 3362 |
// Can't find version number; hope for the best. |
| 3363 |
return nil |
| 3364 |
} |
| 3365 |
|
| 3366 |
major, err := strconv.Atoi(string(matches[1])) |
| 3367 |
if err != nil { |
| 3368 |
// Can't find version number; hope for the best. |
| 3369 |
return nil |
| 3370 |
} |
| 3371 |
const errmsg = "must have SWIG version >= 3.0.6" |
| 3372 |
if major < 3 { |
| 3373 |
return errors.New(errmsg) |
| 3374 |
} |
| 3375 |
if major > 3 { |
| 3376 |
// 4.0 or later |
| 3377 |
return nil |
| 3378 |
} |
| 3379 |
|
| 3380 |
// We have SWIG version 3.x. |
| 3381 |
if len(matches[2]) > 0 { |
| 3382 |
minor, err := strconv.Atoi(string(matches[2][1:])) |
| 3383 |
if err != nil { |
| 3384 |
return nil |
| 3385 |
} |
| 3386 |
if minor > 0 { |
| 3387 |
// 3.1 or later |
| 3388 |
return nil |
| 3389 |
} |
| 3390 |
} |
| 3391 |
|
| 3392 |
// We have SWIG version 3.0.x. |
| 3393 |
if len(matches[3]) > 0 { |
| 3394 |
patch, err := strconv.Atoi(string(matches[3][1:])) |
| 3395 |
if err != nil { |
| 3396 |
return nil |
| 3397 |
} |
| 3398 |
if patch < 6 { |
| 3399 |
// Before 3.0.6. |
| 3400 |
return errors.New(errmsg) |
| 3401 |
} |
| 3402 |
} |
| 3403 |
|
| 3404 |
return nil |
| 3405 |
} |
| 3406 |
|
| 3407 |
func (b *Builder) swigVersionCheck() error { |
| 3408 |
swigCheckOnce.Do(func() { |
| 3409 |
swigCheck = b.swigDoVersionCheck() |
| 3410 |
}) |
| 3411 |
return swigCheck |
| 3412 |
} |
| 3413 |
|
| 3414 |
// Find the value to pass for the -intgosize option to swig. |
| 3415 |
var ( |
| 3416 |
swigIntSizeOnce sync.Once |
| 3417 |
swigIntSize string |
| 3418 |
swigIntSizeError error |
| 3419 |
) |
| 3420 |
|
| 3421 |
// This code fails to build if sizeof(int) <= 32 |
| 3422 |
const swigIntSizeCode = ` |
| 3423 |
package main |
| 3424 |
const i int = 1 << 32 |
| 3425 |
` |
| 3426 |
|
| 3427 |
// Determine the size of int on the target system for the -intgosize option |
| 3428 |
// of swig >= 2.0.9. Run only once. |
| 3429 |
func (b *Builder) swigDoIntSize(objdir string) (intsize string, err error) { |
| 3430 |
if cfg.BuildN { |
| 3431 |
return "$INTBITS", nil |
| 3432 |
} |
| 3433 |
src := filepath.Join(b.WorkDir, "swig_intsize.go") |
| 3434 |
if err = os.WriteFile(src, []byte(swigIntSizeCode), 0666); err != nil { |
| 3435 |
return |
| 3436 |
} |
| 3437 |
srcs := []string{src} |
| 3438 |
|
| 3439 |
p := load.GoFilesPackage(modload.NewState(), context.TODO(), load.PackageOpts{}, srcs) |
| 3440 |
|
| 3441 |
if _, _, e := BuildToolchain.gc(b, &Action{Mode: "swigDoIntSize", Package: p, Objdir: objdir}, "", nil, nil, "", false, "", srcs); e != nil { |
| 3442 |
return "32", nil |
| 3443 |
} |
| 3444 |
return "64", nil |
| 3445 |
} |
| 3446 |
|
| 3447 |
// Determine the size of int on the target system for the -intgosize option |
| 3448 |
// of swig >= 2.0.9. |
| 3449 |
func (b *Builder) swigIntSize(objdir string) (intsize string, err error) { |
| 3450 |
swigIntSizeOnce.Do(func() { |
| 3451 |
swigIntSize, swigIntSizeError = b.swigDoIntSize(objdir) |
| 3452 |
}) |
| 3453 |
return swigIntSize, swigIntSizeError |
| 3454 |
} |
| 3455 |
|
| 3456 |
// Run SWIG on one SWIG input file. |
| 3457 |
func (b *Builder) swigOne(a *Action, file, objdir string, pcCFLAGS []string, cxx bool, intgosize string) error { |
| 3458 |
if strings.HasPrefix(file, "cgo") { |
| 3459 |
return errors.New("SWIG file must not use prefix 'cgo'") |
| 3460 |
} |
| 3461 |
|
| 3462 |
p := a.Package |
| 3463 |
sh := b.Shell(a) |
| 3464 |
|
| 3465 |
cgoCPPFLAGS, cgoCFLAGS, cgoCXXFLAGS, _, _, err := b.CFlags(p) |
| 3466 |
if err != nil { |
| 3467 |
return err |
| 3468 |
} |
| 3469 |
|
| 3470 |
var cflags []string |
| 3471 |
if cxx { |
| 3472 |
cflags = str.StringList(cgoCPPFLAGS, pcCFLAGS, cgoCXXFLAGS) |
| 3473 |
} else { |
| 3474 |
cflags = str.StringList(cgoCPPFLAGS, pcCFLAGS, cgoCFLAGS) |
| 3475 |
} |
| 3476 |
|
| 3477 |
base := swigBase(file, cxx) |
| 3478 |
newGoFile, outC := swigOneOutputs(file, objdir, cxx) |
| 3479 |
|
| 3480 |
gccgo := cfg.BuildToolchainName == "gccgo" |
| 3481 |
|
| 3482 |
// swig |
| 3483 |
args := []string{ |
| 3484 |
"-go", |
| 3485 |
"-cgo", |
| 3486 |
"-intgosize", intgosize, |
| 3487 |
"-module", base, |
| 3488 |
"-o", outC, |
| 3489 |
"-outdir", objdir, |
| 3490 |
} |
| 3491 |
|
| 3492 |
for _, f := range cflags { |
| 3493 |
if len(f) > 3 && f[:2] == "-I" { |
| 3494 |
args = append(args, f) |
| 3495 |
} |
| 3496 |
} |
| 3497 |
|
| 3498 |
if gccgo { |
| 3499 |
args = append(args, "-gccgo") |
| 3500 |
if pkgpath := gccgoPkgpath(p); pkgpath != "" { |
| 3501 |
args = append(args, "-go-pkgpath", pkgpath) |
| 3502 |
} |
| 3503 |
} |
| 3504 |
if cxx { |
| 3505 |
args = append(args, "-c++") |
| 3506 |
} |
| 3507 |
|
| 3508 |
out, err := sh.runOut(p.Dir, nil, "swig", args, file) |
| 3509 |
if err != nil && (bytes.Contains(out, []byte("-intgosize")) || bytes.Contains(out, []byte("-cgo"))) { |
| 3510 |
return errors.New("must have SWIG version >= 3.0.6") |
| 3511 |
} |
| 3512 |
if err := sh.reportCmd("", "", out, err); err != nil { |
| 3513 |
return err |
| 3514 |
} |
| 3515 |
|
| 3516 |
// If the input was x.swig, the output is x.go in the objdir. |
| 3517 |
// But there might be an x.go in the original dir too, and if it |
| 3518 |
// uses cgo as well, cgo will be processing both and will |
| 3519 |
// translate both into x.cgo1.go in the objdir, overwriting one. |
| 3520 |
// Rename x.go to _x_swig.go (newGoFile) to avoid this problem. |
| 3521 |
// We ignore files in the original dir that begin with underscore |
| 3522 |
// so _x_swig.go cannot conflict with an original file we were |
| 3523 |
// going to compile. |
| 3524 |
goFile := objdir + base + ".go" |
| 3525 |
if cfg.BuildX || cfg.BuildN { |
| 3526 |
sh.ShowCmd("", "mv %s %s", goFile, newGoFile) |
| 3527 |
} |
| 3528 |
if !cfg.BuildN { |
| 3529 |
if err := os.Rename(goFile, newGoFile); err != nil { |
| 3530 |
return err |
| 3531 |
} |
| 3532 |
} |
| 3533 |
|
| 3534 |
return nil |
| 3535 |
} |
| 3536 |
|
| 3537 |
func swigBase(file string, cxx bool) string { |
| 3538 |
n := 5 // length of ".swig" |
| 3539 |
if cxx { |
| 3540 |
n = 8 // length of ".swigcxx" |
| 3541 |
} |
| 3542 |
return file[:len(file)-n] |
| 3543 |
} |
| 3544 |
|
| 3545 |
func swigOneOutputs(file, objdir string, cxx bool) (outGo, outC string) { |
| 3546 |
base := swigBase(file, cxx) |
| 3547 |
gccBase := base + "_wrap." |
| 3548 |
gccExt := "c" |
| 3549 |
if cxx { |
| 3550 |
gccExt = "cxx" |
| 3551 |
} |
| 3552 |
|
| 3553 |
newGoFile := objdir + "_" + base + "_swig.go" |
| 3554 |
cFile := objdir + gccBase + gccExt |
| 3555 |
return newGoFile, cFile |
| 3556 |
} |
| 3557 |
|
| 3558 |
// disableBuildID adjusts a linker command line to avoid creating a |
| 3559 |
// build ID when creating an object file rather than an executable or |
| 3560 |
// shared library. Some systems, such as Ubuntu, always add |
| 3561 |
// --build-id to every link, but we don't want a build ID when we are |
| 3562 |
// producing an object file. On some of those system a plain -r (not |
| 3563 |
// -Wl,-r) will turn off --build-id, but clang 3.0 doesn't support a |
| 3564 |
// plain -r. I don't know how to turn off --build-id when using clang |
| 3565 |
// other than passing a trailing --build-id=none. So that is what we |
| 3566 |
// do, but only on systems likely to support it, which is to say, |
| 3567 |
// systems that normally use gold or the GNU linker. |
| 3568 |
func (b *Builder) disableBuildID(ldflags []string) []string { |
| 3569 |
switch cfg.Goos { |
| 3570 |
case "android", "dragonfly", "linux", "netbsd": |
| 3571 |
ldflags = append(ldflags, "-Wl,--build-id=none") |
| 3572 |
} |
| 3573 |
return ldflags |
| 3574 |
} |
| 3575 |
|
| 3576 |
// mkAbsFiles converts files into a list of absolute files, |
| 3577 |
// assuming they were originally relative to dir, |
| 3578 |
// and returns that new list. |
| 3579 |
func mkAbsFiles(dir string, files []string) []string { |
| 3580 |
abs := make([]string, len(files)) |
| 3581 |
for i, f := range files { |
| 3582 |
if !filepath.IsAbs(f) { |
| 3583 |
f = filepath.Join(dir, f) |
| 3584 |
} |
| 3585 |
abs[i] = f |
| 3586 |
} |
| 3587 |
return abs |
| 3588 |
} |
| 3589 |
|
| 3590 |
// actualFiles applies fsys.Actual to the list of files. |
| 3591 |
func actualFiles(files []string) []string { |
| 3592 |
a := make([]string, len(files)) |
| 3593 |
for i, f := range files { |
| 3594 |
a[i] = fsys.Actual(f) |
| 3595 |
} |
| 3596 |
return a |
| 3597 |
} |
| 3598 |
|
| 3599 |
// passLongArgsInResponseFiles modifies cmd such that, for |
| 3600 |
// certain programs, long arguments are passed in "response files", a |
| 3601 |
// file on disk with the arguments, with one arg per line. An actual |
| 3602 |
// argument starting with '@' means that the rest of the argument is |
| 3603 |
// a filename of arguments to expand. |
| 3604 |
// |
| 3605 |
// See issues 18468 (Windows) and 37768 (Darwin). |
| 3606 |
func passLongArgsInResponseFiles(cmd *exec.Cmd) (cleanup func()) { |
| 3607 |
cleanup = func() {} // no cleanup by default |
| 3608 |
|
| 3609 |
var argLen int |
| 3610 |
for _, arg := range cmd.Args { |
| 3611 |
argLen += len(arg) |
| 3612 |
} |
| 3613 |
|
| 3614 |
// If we're not approaching 32KB of args, just pass args normally. |
| 3615 |
// (use 30KB instead to be conservative; not sure how accounting is done) |
| 3616 |
if !useResponseFile(cmd.Path, argLen) { |
| 3617 |
return |
| 3618 |
} |
| 3619 |
|
| 3620 |
tf, err := os.CreateTemp("", "args") |
| 3621 |
if err != nil { |
| 3622 |
log.Fatalf("error writing long arguments to response file: %v", err) |
| 3623 |
} |
| 3624 |
cleanup = func() { os.Remove(tf.Name()) } |
| 3625 |
var buf bytes.Buffer |
| 3626 |
for _, arg := range cmd.Args[1:] { |
| 3627 |
fmt.Fprintf(&buf, "%s\n", encodeArg(arg)) |
| 3628 |
} |
| 3629 |
if _, err := tf.Write(buf.Bytes()); err != nil { |
| 3630 |
tf.Close() |
| 3631 |
cleanup() |
| 3632 |
log.Fatalf("error writing long arguments to response file: %v", err) |
| 3633 |
} |
| 3634 |
if err := tf.Close(); err != nil { |
| 3635 |
cleanup() |
| 3636 |
log.Fatalf("error writing long arguments to response file: %v", err) |
| 3637 |
} |
| 3638 |
cmd.Args = []string{cmd.Args[0], "@" + tf.Name()} |
| 3639 |
return cleanup |
| 3640 |
} |
| 3641 |
|
| 3642 |
func useResponseFile(path string, argLen int) bool { |
| 3643 |
// Unless the program uses objabi.Flagparse, which understands |
| 3644 |
// response files, don't use response files. |
| 3645 |
// TODO: Note that other toolchains like CC are missing here for now. |
| 3646 |
prog := strings.TrimSuffix(filepath.Base(path), ".exe") |
| 3647 |
switch prog { |
| 3648 |
case "compile", "link", "cgo", "asm", "cover": |
| 3649 |
default: |
| 3650 |
return false |
| 3651 |
} |
| 3652 |
|
| 3653 |
if argLen > sys.ExecArgLengthLimit { |
| 3654 |
return true |
| 3655 |
} |
| 3656 |
|
| 3657 |
// On the Go build system, use response files about 10% of the |
| 3658 |
// time, just to exercise this codepath. |
| 3659 |
isBuilder := os.Getenv("GO_BUILDER_NAME") != "" |
| 3660 |
if isBuilder && rand.Intn(10) == 0 { |
| 3661 |
return true |
| 3662 |
} |
| 3663 |
|
| 3664 |
return false |
| 3665 |
} |
| 3666 |
|
| 3667 |
// encodeArg encodes an argument for response file writing. |
| 3668 |
func encodeArg(arg string) string { |
| 3669 |
// If there aren't any characters we need to reencode, fastpath out. |
| 3670 |
if !strings.ContainsAny(arg, "\\\n") { |
| 3671 |
return arg |
| 3672 |
} |
| 3673 |
var b strings.Builder |
| 3674 |
for _, r := range arg { |
| 3675 |
switch r { |
| 3676 |
case '\\': |
| 3677 |
b.WriteByte('\\') |
| 3678 |
b.WriteByte('\\') |
| 3679 |
case '\n': |
| 3680 |
b.WriteByte('\\') |
| 3681 |
b.WriteByte('n') |
| 3682 |
default: |
| 3683 |
b.WriteRune(r) |
| 3684 |
} |
| 3685 |
} |
| 3686 |
return b.String() |
| 3687 |
} |