github.com/corona10/go@v0.0.0-20180224231303-7a218942be57/src/cmd/go/internal/work/exec.go (about) 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 "encoding/json" 12 "errors" 13 "fmt" 14 "io" 15 "io/ioutil" 16 "log" 17 "os" 18 "os/exec" 19 "path/filepath" 20 "regexp" 21 "runtime" 22 "strconv" 23 "strings" 24 "sync" 25 "time" 26 27 "cmd/go/internal/base" 28 "cmd/go/internal/cache" 29 "cmd/go/internal/cfg" 30 "cmd/go/internal/load" 31 "cmd/go/internal/str" 32 ) 33 34 // actionList returns the list of actions in the dag rooted at root 35 // as visited in a depth-first post-order traversal. 36 func actionList(root *Action) []*Action { 37 seen := map[*Action]bool{} 38 all := []*Action{} 39 var walk func(*Action) 40 walk = func(a *Action) { 41 if seen[a] { 42 return 43 } 44 seen[a] = true 45 for _, a1 := range a.Deps { 46 walk(a1) 47 } 48 all = append(all, a) 49 } 50 walk(root) 51 return all 52 } 53 54 // do runs the action graph rooted at root. 55 func (b *Builder) Do(root *Action) { 56 if c := cache.Default(); c != nil && !b.ComputeStaleOnly { 57 // If we're doing real work, take time at the end to trim the cache. 58 defer c.Trim() 59 } 60 61 // Build list of all actions, assigning depth-first post-order priority. 62 // The original implementation here was a true queue 63 // (using a channel) but it had the effect of getting 64 // distracted by low-level leaf actions to the detriment 65 // of completing higher-level actions. The order of 66 // work does not matter much to overall execution time, 67 // but when running "go test std" it is nice to see each test 68 // results as soon as possible. The priorities assigned 69 // ensure that, all else being equal, the execution prefers 70 // to do what it would have done first in a simple depth-first 71 // dependency order traversal. 72 all := actionList(root) 73 for i, a := range all { 74 a.priority = i 75 } 76 77 if cfg.DebugActiongraph != "" { 78 js := actionGraphJSON(root) 79 if err := ioutil.WriteFile(cfg.DebugActiongraph, []byte(js), 0666); err != nil { 80 fmt.Fprintf(os.Stderr, "go: writing action graph: %v\n", err) 81 base.SetExitStatus(1) 82 } 83 } 84 85 b.readySema = make(chan bool, len(all)) 86 87 // Initialize per-action execution state. 88 for _, a := range all { 89 for _, a1 := range a.Deps { 90 a1.triggers = append(a1.triggers, a) 91 } 92 a.pending = len(a.Deps) 93 if a.pending == 0 { 94 b.ready.push(a) 95 b.readySema <- true 96 } 97 } 98 99 // Handle runs a single action and takes care of triggering 100 // any actions that are runnable as a result. 101 handle := func(a *Action) { 102 var err error 103 104 if a.Func != nil && (!a.Failed || a.IgnoreFail) { 105 if err == nil { 106 err = a.Func(b, a) 107 } 108 } 109 110 // The actions run in parallel but all the updates to the 111 // shared work state are serialized through b.exec. 112 b.exec.Lock() 113 defer b.exec.Unlock() 114 115 if err != nil { 116 if err == errPrintedOutput { 117 base.SetExitStatus(2) 118 } else { 119 base.Errorf("%s", err) 120 } 121 a.Failed = true 122 } 123 124 for _, a0 := range a.triggers { 125 if a.Failed { 126 a0.Failed = true 127 } 128 if a0.pending--; a0.pending == 0 { 129 b.ready.push(a0) 130 b.readySema <- true 131 } 132 } 133 134 if a == root { 135 close(b.readySema) 136 } 137 } 138 139 var wg sync.WaitGroup 140 141 // Kick off goroutines according to parallelism. 142 // If we are using the -n flag (just printing commands) 143 // drop the parallelism to 1, both to make the output 144 // deterministic and because there is no real work anyway. 145 par := cfg.BuildP 146 if cfg.BuildN { 147 par = 1 148 } 149 for i := 0; i < par; i++ { 150 wg.Add(1) 151 go func() { 152 defer wg.Done() 153 for { 154 select { 155 case _, ok := <-b.readySema: 156 if !ok { 157 return 158 } 159 // Receiving a value from b.readySema entitles 160 // us to take from the ready queue. 161 b.exec.Lock() 162 a := b.ready.pop() 163 b.exec.Unlock() 164 handle(a) 165 case <-base.Interrupted: 166 base.SetExitStatus(1) 167 return 168 } 169 } 170 }() 171 } 172 173 wg.Wait() 174 } 175 176 // buildActionID computes the action ID for a build action. 177 func (b *Builder) buildActionID(a *Action) cache.ActionID { 178 p := a.Package 179 h := cache.NewHash("build " + p.ImportPath) 180 181 // Configuration independent of compiler toolchain. 182 // Note: buildmode has already been accounted for in buildGcflags 183 // and should not be inserted explicitly. Most buildmodes use the 184 // same compiler settings and can reuse each other's results. 185 // If not, the reason is already recorded in buildGcflags. 186 fmt.Fprintf(h, "compile\n") 187 // The compiler hides the exact value of $GOROOT 188 // when building things in GOROOT, 189 // but it does not hide the exact value of $GOPATH. 190 // Include the full dir in that case. 191 // Assume b.WorkDir is being trimmed properly. 192 if !p.Goroot && !strings.HasPrefix(p.Dir, b.WorkDir) { 193 fmt.Fprintf(h, "dir %s\n", p.Dir) 194 } 195 fmt.Fprintf(h, "goos %s goarch %s\n", cfg.Goos, cfg.Goarch) 196 fmt.Fprintf(h, "import %q\n", p.ImportPath) 197 fmt.Fprintf(h, "omitdebug %v standard %v local %v prefix %q\n", p.Internal.OmitDebug, p.Standard, p.Internal.Local, p.Internal.LocalPrefix) 198 if len(p.CgoFiles)+len(p.SwigFiles) > 0 { 199 fmt.Fprintf(h, "cgo %q\n", b.toolID("cgo")) 200 cppflags, cflags, cxxflags, fflags, _, _ := b.CFlags(p) 201 fmt.Fprintf(h, "CC=%q %q %q\n", b.ccExe(), cppflags, cflags) 202 if len(p.CXXFiles)+len(p.SwigFiles) > 0 { 203 fmt.Fprintf(h, "CXX=%q %q\n", b.cxxExe(), cxxflags) 204 } 205 if len(p.FFiles) > 0 { 206 fmt.Fprintf(h, "FC=%q %q\n", b.fcExe(), fflags) 207 } 208 // TODO(rsc): Should we include the SWIG version or Fortran/GCC/G++/Objective-C compiler versions? 209 } 210 if p.Internal.CoverMode != "" { 211 fmt.Fprintf(h, "cover %q %q\n", p.Internal.CoverMode, b.toolID("cover")) 212 } 213 214 // Configuration specific to compiler toolchain. 215 switch cfg.BuildToolchainName { 216 default: 217 base.Fatalf("buildActionID: unknown build toolchain %q", cfg.BuildToolchainName) 218 case "gc": 219 fmt.Fprintf(h, "compile %s %q %q\n", b.toolID("compile"), forcedGcflags, p.Internal.Gcflags) 220 if len(p.SFiles) > 0 { 221 fmt.Fprintf(h, "asm %q %q %q\n", b.toolID("asm"), forcedAsmflags, p.Internal.Asmflags) 222 } 223 fmt.Fprintf(h, "GO$GOARCH=%s\n", os.Getenv("GO"+strings.ToUpper(cfg.BuildContext.GOARCH))) // GO386, GOARM, etc 224 225 // TODO(rsc): Convince compiler team not to add more magic environment variables, 226 // or perhaps restrict the environment variables passed to subprocesses. 227 magic := []string{ 228 "GOCLOBBERDEADHASH", 229 "GOSSAFUNC", 230 "GO_SSA_PHI_LOC_CUTOFF", 231 "GOSSAHASH", 232 } 233 for _, env := range magic { 234 if x := os.Getenv(env); x != "" { 235 fmt.Fprintf(h, "magic %s=%s\n", env, x) 236 } 237 } 238 if os.Getenv("GOSSAHASH") != "" { 239 for i := 0; ; i++ { 240 env := fmt.Sprintf("GOSSAHASH%d", i) 241 x := os.Getenv(env) 242 if x == "" { 243 break 244 } 245 fmt.Fprintf(h, "magic %s=%s\n", env, x) 246 } 247 } 248 if os.Getenv("GSHS_LOGFILE") != "" { 249 // Clumsy hack. Compiler writes to this log file, 250 // so do not allow use of cache at all. 251 // We will still write to the cache but it will be 252 // essentially unfindable. 253 fmt.Fprintf(h, "nocache %d\n", time.Now().UnixNano()) 254 } 255 256 case "gccgo": 257 id, err := b.gccgoToolID(BuildToolchain.compiler(), "go") 258 if err != nil { 259 base.Fatalf("%v", err) 260 } 261 fmt.Fprintf(h, "compile %s %q %q\n", id, forcedGccgoflags, p.Internal.Gccgoflags) 262 fmt.Fprintf(h, "pkgpath %s\n", gccgoPkgpath(p)) 263 if len(p.SFiles) > 0 { 264 id, err = b.gccgoToolID(BuildToolchain.compiler(), "assembler-with-cpp") 265 // Ignore error; different assembler versions 266 // are unlikely to make any difference anyhow. 267 fmt.Fprintf(h, "asm %q\n", id) 268 } 269 } 270 271 // Input files. 272 inputFiles := str.StringList( 273 p.GoFiles, 274 p.CgoFiles, 275 p.CFiles, 276 p.CXXFiles, 277 p.FFiles, 278 p.MFiles, 279 p.HFiles, 280 p.SFiles, 281 p.SysoFiles, 282 p.SwigFiles, 283 p.SwigCXXFiles, 284 ) 285 for _, file := range inputFiles { 286 fmt.Fprintf(h, "file %s %s\n", file, b.fileHash(filepath.Join(p.Dir, file))) 287 } 288 for _, a1 := range a.Deps { 289 p1 := a1.Package 290 if p1 != nil { 291 fmt.Fprintf(h, "import %s %s\n", p1.ImportPath, contentID(a1.buildID)) 292 } 293 } 294 295 return h.Sum() 296 } 297 298 // build is the action for building a single package. 299 // Note that any new influence on this logic must be reported in b.buildActionID above as well. 300 func (b *Builder) build(a *Action) (err error) { 301 p := a.Package 302 cached := false 303 if !p.BinaryOnly { 304 if b.useCache(a, p, b.buildActionID(a), p.Target) { 305 // If this build triggers a header install, run cgo to get the header. 306 // TODO(rsc): Once we can cache multiple file outputs from an action, 307 // the header should be cached, and then this awful test can be deleted. 308 // Need to look for install header actions depending on this action, 309 // or depending on a link that depends on this action. 310 needHeader := false 311 if (a.Package.UsesCgo() || a.Package.UsesSwig()) && (cfg.BuildBuildmode == "c-archive" || cfg.BuildBuildmode == "c-shared") { 312 for _, t1 := range a.triggers { 313 if t1.Mode == "install header" { 314 needHeader = true 315 goto CheckedHeader 316 } 317 } 318 for _, t1 := range a.triggers { 319 for _, t2 := range t1.triggers { 320 if t2.Mode == "install header" { 321 needHeader = true 322 goto CheckedHeader 323 } 324 } 325 } 326 } 327 CheckedHeader: 328 if b.ComputeStaleOnly || !a.needVet && !needHeader { 329 return nil 330 } 331 cached = true 332 } 333 defer b.flushOutput(a) 334 } 335 336 defer func() { 337 if err != nil && err != errPrintedOutput { 338 err = fmt.Errorf("go build %s: %v", a.Package.ImportPath, err) 339 } 340 }() 341 if cfg.BuildN { 342 // In -n mode, print a banner between packages. 343 // The banner is five lines so that when changes to 344 // different sections of the bootstrap script have to 345 // be merged, the banners give patch something 346 // to use to find its context. 347 b.Print("\n#\n# " + a.Package.ImportPath + "\n#\n\n") 348 } 349 350 if cfg.BuildV { 351 b.Print(a.Package.ImportPath + "\n") 352 } 353 354 if a.Package.BinaryOnly { 355 _, err := os.Stat(a.Package.Target) 356 if err == nil { 357 a.built = a.Package.Target 358 a.Target = a.Package.Target 359 a.buildID = b.fileHash(a.Package.Target) 360 a.Package.Stale = false 361 a.Package.StaleReason = "binary-only package" 362 return nil 363 } 364 if b.ComputeStaleOnly { 365 a.Package.Stale = true 366 a.Package.StaleReason = "missing or invalid binary-only package" 367 return nil 368 } 369 return fmt.Errorf("missing or invalid binary-only package") 370 } 371 372 if err := b.Mkdir(a.Objdir); err != nil { 373 return err 374 } 375 objdir := a.Objdir 376 377 // make target directory 378 dir, _ := filepath.Split(a.Target) 379 if dir != "" { 380 if err := b.Mkdir(dir); err != nil { 381 return err 382 } 383 } 384 385 var gofiles, cgofiles, cfiles, sfiles, cxxfiles, objects, cgoObjects, pcCFLAGS, pcLDFLAGS []string 386 387 gofiles = append(gofiles, a.Package.GoFiles...) 388 cgofiles = append(cgofiles, a.Package.CgoFiles...) 389 cfiles = append(cfiles, a.Package.CFiles...) 390 sfiles = append(sfiles, a.Package.SFiles...) 391 cxxfiles = append(cxxfiles, a.Package.CXXFiles...) 392 393 if a.Package.UsesCgo() || a.Package.UsesSwig() { 394 if pcCFLAGS, pcLDFLAGS, err = b.getPkgConfigFlags(a.Package); err != nil { 395 return 396 } 397 } 398 399 // Run SWIG on each .swig and .swigcxx file. 400 // Each run will generate two files, a .go file and a .c or .cxx file. 401 // The .go file will use import "C" and is to be processed by cgo. 402 if a.Package.UsesSwig() { 403 outGo, outC, outCXX, err := b.swig(a, a.Package, objdir, pcCFLAGS) 404 if err != nil { 405 return err 406 } 407 cgofiles = append(cgofiles, outGo...) 408 cfiles = append(cfiles, outC...) 409 cxxfiles = append(cxxfiles, outCXX...) 410 } 411 412 // If we're doing coverage, preprocess the .go files and put them in the work directory 413 if a.Package.Internal.CoverMode != "" { 414 for i, file := range str.StringList(gofiles, cgofiles) { 415 var sourceFile string 416 var coverFile string 417 var key string 418 if strings.HasSuffix(file, ".cgo1.go") { 419 // cgo files have absolute paths 420 base := filepath.Base(file) 421 sourceFile = file 422 coverFile = objdir + base 423 key = strings.TrimSuffix(base, ".cgo1.go") + ".go" 424 } else { 425 sourceFile = filepath.Join(a.Package.Dir, file) 426 coverFile = objdir + file 427 key = file 428 } 429 coverFile = strings.TrimSuffix(coverFile, ".go") + ".cover.go" 430 cover := a.Package.Internal.CoverVars[key] 431 if cover == nil || base.IsTestFile(file) { 432 // Not covering this file. 433 continue 434 } 435 if err := b.cover(a, coverFile, sourceFile, 0666, cover.Var); err != nil { 436 return err 437 } 438 if i < len(gofiles) { 439 gofiles[i] = coverFile 440 } else { 441 cgofiles[i-len(gofiles)] = coverFile 442 } 443 } 444 } 445 446 // Run cgo. 447 if a.Package.UsesCgo() || a.Package.UsesSwig() { 448 // In a package using cgo, cgo compiles the C, C++ and assembly files with gcc. 449 // There is one exception: runtime/cgo's job is to bridge the 450 // cgo and non-cgo worlds, so it necessarily has files in both. 451 // In that case gcc only gets the gcc_* files. 452 var gccfiles []string 453 gccfiles = append(gccfiles, cfiles...) 454 cfiles = nil 455 if a.Package.Standard && a.Package.ImportPath == "runtime/cgo" { 456 filter := func(files, nongcc, gcc []string) ([]string, []string) { 457 for _, f := range files { 458 if strings.HasPrefix(f, "gcc_") { 459 gcc = append(gcc, f) 460 } else { 461 nongcc = append(nongcc, f) 462 } 463 } 464 return nongcc, gcc 465 } 466 sfiles, gccfiles = filter(sfiles, sfiles[:0], gccfiles) 467 } else { 468 for _, sfile := range sfiles { 469 data, err := ioutil.ReadFile(filepath.Join(a.Package.Dir, sfile)) 470 if err == nil { 471 if bytes.HasPrefix(data, []byte("TEXT")) || bytes.Contains(data, []byte("\nTEXT")) || 472 bytes.HasPrefix(data, []byte("DATA")) || bytes.Contains(data, []byte("\nDATA")) || 473 bytes.HasPrefix(data, []byte("GLOBL")) || bytes.Contains(data, []byte("\nGLOBL")) { 474 return fmt.Errorf("package using cgo has Go assembly file %s", sfile) 475 } 476 } 477 } 478 gccfiles = append(gccfiles, sfiles...) 479 sfiles = nil 480 } 481 482 outGo, outObj, err := b.cgo(a, base.Tool("cgo"), objdir, pcCFLAGS, pcLDFLAGS, mkAbsFiles(a.Package.Dir, cgofiles), gccfiles, cxxfiles, a.Package.MFiles, a.Package.FFiles) 483 if err != nil { 484 return err 485 } 486 if cfg.BuildToolchainName == "gccgo" { 487 cgoObjects = append(cgoObjects, a.Objdir+"_cgo_flags") 488 } 489 cgoObjects = append(cgoObjects, outObj...) 490 gofiles = append(gofiles, outGo...) 491 } 492 if cached && !a.needVet { 493 return nil 494 } 495 496 // Sanity check only, since Package.load already checked as well. 497 if len(gofiles) == 0 { 498 return &load.NoGoError{Package: a.Package} 499 } 500 501 // Prepare Go vet config if needed. 502 var vcfg *vetConfig 503 if a.needVet { 504 // Pass list of absolute paths to vet, 505 // so that vet's error messages will use absolute paths, 506 // so that we can reformat them relative to the directory 507 // in which the go command is invoked. 508 vcfg = &vetConfig{ 509 Compiler: cfg.BuildToolchainName, 510 Dir: a.Package.Dir, 511 GoFiles: mkAbsFiles(a.Package.Dir, gofiles), 512 ImportPath: a.Package.ImportPath, 513 ImportMap: make(map[string]string), 514 PackageFile: make(map[string]string), 515 } 516 a.vetCfg = vcfg 517 for i, raw := range a.Package.Internal.RawImports { 518 final := a.Package.Imports[i] 519 vcfg.ImportMap[raw] = final 520 } 521 } 522 523 // Prepare Go import config. 524 // We start it off with a comment so it can't be empty, so icfg.Bytes() below is never nil. 525 // It should never be empty anyway, but there have been bugs in the past that resulted 526 // in empty configs, which then unfortunately turn into "no config passed to compiler", 527 // and the compiler falls back to looking in pkg itself, which mostly works, 528 // except when it doesn't. 529 var icfg bytes.Buffer 530 fmt.Fprintf(&icfg, "# import config\n") 531 532 for i, raw := range a.Package.Internal.RawImports { 533 final := a.Package.Imports[i] 534 if final != raw { 535 fmt.Fprintf(&icfg, "importmap %s=%s\n", raw, final) 536 } 537 } 538 539 // Compute the list of mapped imports in the vet config 540 // so that we can add any missing mappings below. 541 var vcfgMapped map[string]bool 542 if vcfg != nil { 543 vcfgMapped = make(map[string]bool) 544 for _, p := range vcfg.ImportMap { 545 vcfgMapped[p] = true 546 } 547 } 548 549 for _, a1 := range a.Deps { 550 p1 := a1.Package 551 if p1 == nil || p1.ImportPath == "" || a1.built == "" { 552 continue 553 } 554 fmt.Fprintf(&icfg, "packagefile %s=%s\n", p1.ImportPath, a1.built) 555 if vcfg != nil { 556 // Add import mapping if needed 557 // (for imports like "runtime/cgo" that appear only in generated code). 558 if !vcfgMapped[p1.ImportPath] { 559 vcfg.ImportMap[p1.ImportPath] = p1.ImportPath 560 } 561 vcfg.PackageFile[p1.ImportPath] = a1.built 562 } 563 } 564 565 if cached { 566 // The cached package file is OK, so we don't need to run the compile. 567 // We've only going through the motions to prepare the vet configuration, 568 // which is now complete. 569 return nil 570 } 571 572 // Compile Go. 573 objpkg := objdir + "_pkg_.a" 574 ofile, out, err := BuildToolchain.gc(b, a, objpkg, icfg.Bytes(), len(sfiles) > 0, gofiles) 575 if len(out) > 0 { 576 b.showOutput(a, a.Package.Dir, a.Package.ImportPath, b.processOutput(out)) 577 if err != nil { 578 return errPrintedOutput 579 } 580 } 581 if err != nil { 582 return err 583 } 584 if ofile != objpkg { 585 objects = append(objects, ofile) 586 } 587 588 // Copy .h files named for goos or goarch or goos_goarch 589 // to names using GOOS and GOARCH. 590 // For example, defs_linux_amd64.h becomes defs_GOOS_GOARCH.h. 591 _goos_goarch := "_" + cfg.Goos + "_" + cfg.Goarch 592 _goos := "_" + cfg.Goos 593 _goarch := "_" + cfg.Goarch 594 for _, file := range a.Package.HFiles { 595 name, ext := fileExtSplit(file) 596 switch { 597 case strings.HasSuffix(name, _goos_goarch): 598 targ := file[:len(name)-len(_goos_goarch)] + "_GOOS_GOARCH." + ext 599 if err := b.copyFile(a, objdir+targ, filepath.Join(a.Package.Dir, file), 0666, true); err != nil { 600 return err 601 } 602 case strings.HasSuffix(name, _goarch): 603 targ := file[:len(name)-len(_goarch)] + "_GOARCH." + ext 604 if err := b.copyFile(a, objdir+targ, filepath.Join(a.Package.Dir, file), 0666, true); err != nil { 605 return err 606 } 607 case strings.HasSuffix(name, _goos): 608 targ := file[:len(name)-len(_goos)] + "_GOOS." + ext 609 if err := b.copyFile(a, objdir+targ, filepath.Join(a.Package.Dir, file), 0666, true); err != nil { 610 return err 611 } 612 } 613 } 614 615 for _, file := range cfiles { 616 out := file[:len(file)-len(".c")] + ".o" 617 if err := BuildToolchain.cc(b, a, objdir+out, file); err != nil { 618 return err 619 } 620 objects = append(objects, out) 621 } 622 623 // Assemble .s files. 624 if len(sfiles) > 0 { 625 ofiles, err := BuildToolchain.asm(b, a, sfiles) 626 if err != nil { 627 return err 628 } 629 objects = append(objects, ofiles...) 630 } 631 632 // For gccgo on ELF systems, we write the build ID as an assembler file. 633 // This lets us set the SHF_EXCLUDE flag. 634 // This is read by readGccgoArchive in cmd/internal/buildid/buildid.go. 635 if a.buildID != "" && cfg.BuildToolchainName == "gccgo" { 636 switch cfg.Goos { 637 case "android", "dragonfly", "freebsd", "linux", "netbsd", "openbsd", "solaris": 638 asmfile, err := b.gccgoBuildIDELFFile(a) 639 if err != nil { 640 return err 641 } 642 ofiles, err := BuildToolchain.asm(b, a, []string{asmfile}) 643 if err != nil { 644 return err 645 } 646 objects = append(objects, ofiles...) 647 } 648 } 649 650 // NOTE(rsc): On Windows, it is critically important that the 651 // gcc-compiled objects (cgoObjects) be listed after the ordinary 652 // objects in the archive. I do not know why this is. 653 // https://golang.org/issue/2601 654 objects = append(objects, cgoObjects...) 655 656 // Add system object files. 657 for _, syso := range a.Package.SysoFiles { 658 objects = append(objects, filepath.Join(a.Package.Dir, syso)) 659 } 660 661 // Pack into archive in objdir directory. 662 // If the Go compiler wrote an archive, we only need to add the 663 // object files for non-Go sources to the archive. 664 // If the Go compiler wrote an archive and the package is entirely 665 // Go sources, there is no pack to execute at all. 666 if len(objects) > 0 { 667 if err := BuildToolchain.pack(b, a, objpkg, objects); err != nil { 668 return err 669 } 670 } 671 672 if err := b.updateBuildID(a, objpkg, true); err != nil { 673 return err 674 } 675 676 a.built = objpkg 677 return nil 678 } 679 680 type vetConfig struct { 681 Compiler string 682 Dir string 683 GoFiles []string 684 ImportMap map[string]string 685 PackageFile map[string]string 686 ImportPath string 687 688 SucceedOnTypecheckFailure bool 689 } 690 691 // VetTool is the path to an alternate vet tool binary. 692 // The caller is expected to set it (if needed) before executing any vet actions. 693 var VetTool string 694 695 // VetFlags are the flags to pass to vet. 696 // The caller is expected to set them before executing any vet actions. 697 var VetFlags []string 698 699 func (b *Builder) vet(a *Action) error { 700 // a.Deps[0] is the build of the package being vetted. 701 // a.Deps[1] is the build of the "fmt" package. 702 703 vcfg := a.Deps[0].vetCfg 704 if vcfg == nil { 705 // Vet config should only be missing if the build failed. 706 if !a.Deps[0].Failed { 707 return fmt.Errorf("vet config not found") 708 } 709 return nil 710 } 711 712 if vcfg.ImportMap["fmt"] == "" { 713 a1 := a.Deps[1] 714 vcfg.ImportMap["fmt"] = "fmt" 715 vcfg.PackageFile["fmt"] = a1.built 716 } 717 718 // During go test, ignore type-checking failures during vet. 719 // We only run vet if the compilation has succeeded, 720 // so at least for now assume the bug is in vet. 721 // We know of at least #18395. 722 // TODO(rsc,gri): Try to remove this for Go 1.11. 723 vcfg.SucceedOnTypecheckFailure = cfg.CmdName == "test" 724 725 js, err := json.MarshalIndent(vcfg, "", "\t") 726 if err != nil { 727 return fmt.Errorf("internal error marshaling vet config: %v", err) 728 } 729 js = append(js, '\n') 730 if err := b.writeFile(a.Objdir+"vet.cfg", js); err != nil { 731 return err 732 } 733 734 var env []string 735 if cfg.BuildToolchainName == "gccgo" { 736 env = append(env, "GCCGO="+BuildToolchain.compiler()) 737 } 738 739 p := a.Package 740 tool := VetTool 741 if tool == "" { 742 tool = base.Tool("vet") 743 } 744 return b.run(a, p.Dir, p.ImportPath, env, cfg.BuildToolexec, tool, VetFlags, a.Objdir+"vet.cfg") 745 } 746 747 // linkActionID computes the action ID for a link action. 748 func (b *Builder) linkActionID(a *Action) cache.ActionID { 749 p := a.Package 750 h := cache.NewHash("link " + p.ImportPath) 751 752 // Toolchain-independent configuration. 753 fmt.Fprintf(h, "link\n") 754 fmt.Fprintf(h, "buildmode %s goos %s goarch %s\n", cfg.BuildBuildmode, cfg.Goos, cfg.Goarch) 755 fmt.Fprintf(h, "import %q\n", p.ImportPath) 756 fmt.Fprintf(h, "omitdebug %v standard %v local %v prefix %q\n", p.Internal.OmitDebug, p.Standard, p.Internal.Local, p.Internal.LocalPrefix) 757 758 // Toolchain-dependent configuration, shared with b.linkSharedActionID. 759 b.printLinkerConfig(h, p) 760 761 // Input files. 762 for _, a1 := range a.Deps { 763 p1 := a1.Package 764 if p1 != nil { 765 if a1.built != "" || a1.buildID != "" { 766 buildID := a1.buildID 767 if buildID == "" { 768 buildID = b.buildID(a1.built) 769 } 770 fmt.Fprintf(h, "packagefile %s=%s\n", p1.ImportPath, contentID(buildID)) 771 } 772 // Because we put package main's full action ID into the binary's build ID, 773 // we must also put the full action ID into the binary's action ID hash. 774 if p1.Name == "main" { 775 fmt.Fprintf(h, "packagemain %s\n", a1.buildID) 776 } 777 if p1.Shlib != "" { 778 fmt.Fprintf(h, "packageshlib %s=%s\n", p1.ImportPath, contentID(b.buildID(p1.Shlib))) 779 } 780 } 781 } 782 783 return h.Sum() 784 } 785 786 // printLinkerConfig prints the linker config into the hash h, 787 // as part of the computation of a linker-related action ID. 788 func (b *Builder) printLinkerConfig(h io.Writer, p *load.Package) { 789 switch cfg.BuildToolchainName { 790 default: 791 base.Fatalf("linkActionID: unknown toolchain %q", cfg.BuildToolchainName) 792 793 case "gc": 794 fmt.Fprintf(h, "link %s %q %s\n", b.toolID("link"), forcedLdflags, ldBuildmode) 795 if p != nil { 796 fmt.Fprintf(h, "linkflags %q\n", p.Internal.Ldflags) 797 } 798 fmt.Fprintf(h, "GO$GOARCH=%s\n", os.Getenv("GO"+strings.ToUpper(cfg.BuildContext.GOARCH))) // GO386, GOARM, etc 799 800 // The linker writes source file paths that say GOROOT_FINAL. 801 fmt.Fprintf(h, "GOROOT=%s\n", cfg.GOROOT_FINAL) 802 803 // TODO(rsc): Convince linker team not to add more magic environment variables, 804 // or perhaps restrict the environment variables passed to subprocesses. 805 magic := []string{ 806 "GO_EXTLINK_ENABLED", 807 } 808 for _, env := range magic { 809 if x := os.Getenv(env); x != "" { 810 fmt.Fprintf(h, "magic %s=%s\n", env, x) 811 } 812 } 813 814 // TODO(rsc): Do cgo settings and flags need to be included? 815 // Or external linker settings and flags? 816 817 case "gccgo": 818 id, err := b.gccgoToolID(BuildToolchain.linker(), "go") 819 if err != nil { 820 base.Fatalf("%v", err) 821 } 822 fmt.Fprintf(h, "link %s %s\n", id, ldBuildmode) 823 // TODO(iant): Should probably include cgo flags here. 824 } 825 } 826 827 // link is the action for linking a single command. 828 // Note that any new influence on this logic must be reported in b.linkActionID above as well. 829 func (b *Builder) link(a *Action) (err error) { 830 if b.useCache(a, a.Package, b.linkActionID(a), a.Package.Target) { 831 return nil 832 } 833 defer b.flushOutput(a) 834 835 if err := b.Mkdir(a.Objdir); err != nil { 836 return err 837 } 838 839 importcfg := a.Objdir + "importcfg.link" 840 if err := b.writeLinkImportcfg(a, importcfg); err != nil { 841 return err 842 } 843 844 // make target directory 845 dir, _ := filepath.Split(a.Target) 846 if dir != "" { 847 if err := b.Mkdir(dir); err != nil { 848 return err 849 } 850 } 851 852 if err := BuildToolchain.ld(b, a, a.Target, importcfg, a.Deps[0].built); err != nil { 853 return err 854 } 855 856 // Update the binary with the final build ID. 857 // But if OmitDebug is set, don't rewrite the binary, because we set OmitDebug 858 // on binaries that we are going to run and then delete. 859 // There's no point in doing work on such a binary. 860 // Worse, opening the binary for write here makes it 861 // essentially impossible to safely fork+exec due to a fundamental 862 // incompatibility between ETXTBSY and threads on modern Unix systems. 863 // See golang.org/issue/22220. 864 // We still call updateBuildID to update a.buildID, which is important 865 // for test result caching, but passing rewrite=false (final arg) 866 // means we don't actually rewrite the binary, nor store the 867 // result into the cache. 868 // Not calling updateBuildID means we also don't insert these 869 // binaries into the build object cache. That's probably a net win: 870 // less cache space wasted on large binaries we are not likely to 871 // need again. (On the other hand it does make repeated go test slower.) 872 if err := b.updateBuildID(a, a.Target, !a.Package.Internal.OmitDebug); err != nil { 873 return err 874 } 875 876 a.built = a.Target 877 return nil 878 } 879 880 func (b *Builder) writeLinkImportcfg(a *Action, file string) error { 881 // Prepare Go import cfg. 882 var icfg bytes.Buffer 883 for _, a1 := range a.Deps { 884 p1 := a1.Package 885 if p1 == nil { 886 continue 887 } 888 fmt.Fprintf(&icfg, "packagefile %s=%s\n", p1.ImportPath, a1.built) 889 if p1.Shlib != "" { 890 fmt.Fprintf(&icfg, "packageshlib %s=%s\n", p1.ImportPath, p1.Shlib) 891 } 892 } 893 return b.writeFile(file, icfg.Bytes()) 894 } 895 896 // PkgconfigCmd returns a pkg-config binary name 897 // defaultPkgConfig is defined in zdefaultcc.go, written by cmd/dist. 898 func (b *Builder) PkgconfigCmd() string { 899 return envList("PKG_CONFIG", cfg.DefaultPkgConfig)[0] 900 } 901 902 // splitPkgConfigOutput parses the pkg-config output into a slice of 903 // flags. pkg-config always uses \ to escape special characters. 904 func splitPkgConfigOutput(out []byte) []string { 905 if len(out) == 0 { 906 return nil 907 } 908 var flags []string 909 flag := make([]byte, len(out)) 910 r, w := 0, 0 911 for r < len(out) { 912 switch out[r] { 913 case ' ', '\t', '\r', '\n': 914 if w > 0 { 915 flags = append(flags, string(flag[:w])) 916 } 917 w = 0 918 case '\\': 919 r++ 920 fallthrough 921 default: 922 if r < len(out) { 923 flag[w] = out[r] 924 w++ 925 } 926 } 927 r++ 928 } 929 if w > 0 { 930 flags = append(flags, string(flag[:w])) 931 } 932 return flags 933 } 934 935 // Calls pkg-config if needed and returns the cflags/ldflags needed to build the package. 936 func (b *Builder) getPkgConfigFlags(p *load.Package) (cflags, ldflags []string, err error) { 937 if pcargs := p.CgoPkgConfig; len(pcargs) > 0 { 938 // pkg-config permits arguments to appear anywhere in 939 // the command line. Move them all to the front, before --. 940 var pcflags []string 941 var pkgs []string 942 for _, pcarg := range pcargs { 943 if pcarg == "--" { 944 // We're going to add our own "--" argument. 945 } else if strings.HasPrefix(pcarg, "--") { 946 pcflags = append(pcflags, pcarg) 947 } else { 948 pkgs = append(pkgs, pcarg) 949 } 950 } 951 for _, pkg := range pkgs { 952 if !load.SafeArg(pkg) { 953 return nil, nil, fmt.Errorf("invalid pkg-config package name: %s", pkg) 954 } 955 } 956 var out []byte 957 out, err = b.runOut(p.Dir, p.ImportPath, nil, b.PkgconfigCmd(), "--cflags", pcflags, "--", pkgs) 958 if err != nil { 959 b.showOutput(nil, p.Dir, b.PkgconfigCmd()+" --cflags "+strings.Join(pcflags, " ")+strings.Join(pkgs, " "), string(out)) 960 b.Print(err.Error() + "\n") 961 return nil, nil, errPrintedOutput 962 } 963 if len(out) > 0 { 964 cflags = splitPkgConfigOutput(out) 965 if err := checkCompilerFlags("CFLAGS", "pkg-config --cflags", cflags); err != nil { 966 return nil, nil, err 967 } 968 } 969 out, err = b.runOut(p.Dir, p.ImportPath, nil, b.PkgconfigCmd(), "--libs", pcflags, "--", pkgs) 970 if err != nil { 971 b.showOutput(nil, p.Dir, b.PkgconfigCmd()+" --libs "+strings.Join(pcflags, " ")+strings.Join(pkgs, " "), string(out)) 972 b.Print(err.Error() + "\n") 973 return nil, nil, errPrintedOutput 974 } 975 if len(out) > 0 { 976 ldflags = strings.Fields(string(out)) 977 if err := checkLinkerFlags("LDFLAGS", "pkg-config --libs", ldflags); err != nil { 978 return nil, nil, err 979 } 980 } 981 } 982 983 return 984 } 985 986 func (b *Builder) installShlibname(a *Action) error { 987 // TODO: BuildN 988 a1 := a.Deps[0] 989 err := ioutil.WriteFile(a.Target, []byte(filepath.Base(a1.Target)+"\n"), 0666) 990 if err != nil { 991 return err 992 } 993 if cfg.BuildX { 994 b.Showcmd("", "echo '%s' > %s # internal", filepath.Base(a1.Target), a.Target) 995 } 996 return nil 997 } 998 999 func (b *Builder) linkSharedActionID(a *Action) cache.ActionID { 1000 h := cache.NewHash("linkShared") 1001 1002 // Toolchain-independent configuration. 1003 fmt.Fprintf(h, "linkShared\n") 1004 fmt.Fprintf(h, "goos %s goarch %s\n", cfg.Goos, cfg.Goarch) 1005 1006 // Toolchain-dependent configuration, shared with b.linkActionID. 1007 b.printLinkerConfig(h, nil) 1008 1009 // Input files. 1010 for _, a1 := range a.Deps { 1011 p1 := a1.Package 1012 if a1.built == "" { 1013 continue 1014 } 1015 if p1 != nil { 1016 fmt.Fprintf(h, "packagefile %s=%s\n", p1.ImportPath, contentID(b.buildID(a1.built))) 1017 if p1.Shlib != "" { 1018 fmt.Fprintf(h, "packageshlib %s=%s\n", p1.ImportPath, contentID(b.buildID(p1.Shlib))) 1019 } 1020 } 1021 } 1022 // Files named on command line are special. 1023 for _, a1 := range a.Deps[0].Deps { 1024 p1 := a1.Package 1025 fmt.Fprintf(h, "top %s=%s\n", p1.ImportPath, contentID(b.buildID(a1.built))) 1026 } 1027 1028 return h.Sum() 1029 } 1030 1031 func (b *Builder) linkShared(a *Action) (err error) { 1032 if b.useCache(a, nil, b.linkSharedActionID(a), a.Target) { 1033 return nil 1034 } 1035 defer b.flushOutput(a) 1036 1037 if err := b.Mkdir(a.Objdir); err != nil { 1038 return err 1039 } 1040 1041 importcfg := a.Objdir + "importcfg.link" 1042 if err := b.writeLinkImportcfg(a, importcfg); err != nil { 1043 return err 1044 } 1045 1046 // TODO(rsc): There is a missing updateBuildID here, 1047 // but we have to decide where to store the build ID in these files. 1048 a.built = a.Target 1049 return BuildToolchain.ldShared(b, a, a.Deps[0].Deps, a.Target, importcfg, a.Deps) 1050 } 1051 1052 // BuildInstallFunc is the action for installing a single package or executable. 1053 func BuildInstallFunc(b *Builder, a *Action) (err error) { 1054 defer func() { 1055 if err != nil && err != errPrintedOutput { 1056 // a.Package == nil is possible for the go install -buildmode=shared 1057 // action that installs libmangledname.so, which corresponds to 1058 // a list of packages, not just one. 1059 sep, path := "", "" 1060 if a.Package != nil { 1061 sep, path = " ", a.Package.ImportPath 1062 } 1063 err = fmt.Errorf("go %s%s%s: %v", cfg.CmdName, sep, path, err) 1064 } 1065 }() 1066 1067 a1 := a.Deps[0] 1068 a.buildID = a1.buildID 1069 1070 // If we are using the eventual install target as an up-to-date 1071 // cached copy of the thing we built, then there's no need to 1072 // copy it into itself (and that would probably fail anyway). 1073 // In this case a1.built == a.Target because a1.built == p.Target, 1074 // so the built target is not in the a1.Objdir tree that b.cleanup(a1) removes. 1075 if a1.built == a.Target { 1076 a.built = a.Target 1077 b.cleanup(a1) 1078 // Whether we're smart enough to avoid a complete rebuild 1079 // depends on exactly what the staleness and rebuild algorithms 1080 // are, as well as potentially the state of the Go build cache. 1081 // We don't really want users to be able to infer (or worse start depending on) 1082 // those details from whether the modification time changes during 1083 // "go install", so do a best-effort update of the file times to make it 1084 // look like we rewrote a.Target even if we did not. Updating the mtime 1085 // may also help other mtime-based systems that depend on our 1086 // previous mtime updates that happened more often. 1087 // This is still not perfect - we ignore the error result, and if the file was 1088 // unwritable for some reason then pretending to have written it is also 1089 // confusing - but it's probably better than not doing the mtime update. 1090 // 1091 // But don't do that for the special case where building an executable 1092 // with -linkshared implicitly installs all its dependent libraries. 1093 // We want to hide that awful detail as much as possible, so don't 1094 // advertise it by touching the mtimes (usually the libraries are up 1095 // to date). 1096 if !a.buggyInstall { 1097 now := time.Now() 1098 os.Chtimes(a.Target, now, now) 1099 } 1100 return nil 1101 } 1102 if b.ComputeStaleOnly { 1103 return nil 1104 } 1105 1106 if err := b.Mkdir(a.Objdir); err != nil { 1107 return err 1108 } 1109 1110 perm := os.FileMode(0666) 1111 if a1.Mode == "link" { 1112 switch cfg.BuildBuildmode { 1113 case "c-archive", "c-shared", "plugin": 1114 default: 1115 perm = 0777 1116 } 1117 } 1118 1119 // make target directory 1120 dir, _ := filepath.Split(a.Target) 1121 if dir != "" { 1122 if err := b.Mkdir(dir); err != nil { 1123 return err 1124 } 1125 } 1126 1127 defer b.cleanup(a1) 1128 1129 return b.moveOrCopyFile(a, a.Target, a1.built, perm, false) 1130 } 1131 1132 // cleanup removes a's object dir to keep the amount of 1133 // on-disk garbage down in a large build. On an operating system 1134 // with aggressive buffering, cleaning incrementally like 1135 // this keeps the intermediate objects from hitting the disk. 1136 func (b *Builder) cleanup(a *Action) { 1137 if !cfg.BuildWork { 1138 if cfg.BuildX { 1139 b.Showcmd("", "rm -r %s", a.Objdir) 1140 } 1141 os.RemoveAll(a.Objdir) 1142 } 1143 } 1144 1145 // moveOrCopyFile is like 'mv src dst' or 'cp src dst'. 1146 func (b *Builder) moveOrCopyFile(a *Action, dst, src string, perm os.FileMode, force bool) error { 1147 if cfg.BuildN { 1148 b.Showcmd("", "mv %s %s", src, dst) 1149 return nil 1150 } 1151 1152 // If we can update the mode and rename to the dst, do it. 1153 // Otherwise fall back to standard copy. 1154 1155 // If the source is in the build cache, we need to copy it. 1156 if strings.HasPrefix(src, cache.DefaultDir()) { 1157 return b.copyFile(a, dst, src, perm, force) 1158 } 1159 1160 // On Windows, always copy the file, so that we respect the NTFS 1161 // permissions of the parent folder. https://golang.org/issue/22343. 1162 // What matters here is not cfg.Goos (the system we are building 1163 // for) but runtime.GOOS (the system we are building on). 1164 if runtime.GOOS == "windows" { 1165 return b.copyFile(a, dst, src, perm, force) 1166 } 1167 1168 // If the destination directory has the group sticky bit set, 1169 // we have to copy the file to retain the correct permissions. 1170 // https://golang.org/issue/18878 1171 if fi, err := os.Stat(filepath.Dir(dst)); err == nil { 1172 if fi.IsDir() && (fi.Mode()&os.ModeSetgid) != 0 { 1173 return b.copyFile(a, dst, src, perm, force) 1174 } 1175 } 1176 1177 // The perm argument is meant to be adjusted according to umask, 1178 // but we don't know what the umask is. 1179 // Create a dummy file to find out. 1180 // This avoids build tags and works even on systems like Plan 9 1181 // where the file mask computation incorporates other information. 1182 mode := perm 1183 f, err := os.OpenFile(filepath.Clean(dst)+"-go-tmp-umask", os.O_WRONLY|os.O_CREATE|os.O_EXCL, perm) 1184 if err == nil { 1185 fi, err := f.Stat() 1186 if err == nil { 1187 mode = fi.Mode() & 0777 1188 } 1189 name := f.Name() 1190 f.Close() 1191 os.Remove(name) 1192 } 1193 1194 if err := os.Chmod(src, mode); err == nil { 1195 if err := os.Rename(src, dst); err == nil { 1196 if cfg.BuildX { 1197 b.Showcmd("", "mv %s %s", src, dst) 1198 } 1199 return nil 1200 } 1201 } 1202 1203 return b.copyFile(a, dst, src, perm, force) 1204 } 1205 1206 // copyFile is like 'cp src dst'. 1207 func (b *Builder) copyFile(a *Action, dst, src string, perm os.FileMode, force bool) error { 1208 if cfg.BuildN || cfg.BuildX { 1209 b.Showcmd("", "cp %s %s", src, dst) 1210 if cfg.BuildN { 1211 return nil 1212 } 1213 } 1214 1215 sf, err := os.Open(src) 1216 if err != nil { 1217 return err 1218 } 1219 defer sf.Close() 1220 1221 // Be careful about removing/overwriting dst. 1222 // Do not remove/overwrite if dst exists and is a directory 1223 // or a non-object file. 1224 if fi, err := os.Stat(dst); err == nil { 1225 if fi.IsDir() { 1226 return fmt.Errorf("build output %q already exists and is a directory", dst) 1227 } 1228 if !force && fi.Mode().IsRegular() && !isObject(dst) { 1229 return fmt.Errorf("build output %q already exists and is not an object file", dst) 1230 } 1231 } 1232 1233 // On Windows, remove lingering ~ file from last attempt. 1234 if base.ToolIsWindows { 1235 if _, err := os.Stat(dst + "~"); err == nil { 1236 os.Remove(dst + "~") 1237 } 1238 } 1239 1240 mayberemovefile(dst) 1241 df, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm) 1242 if err != nil && base.ToolIsWindows { 1243 // Windows does not allow deletion of a binary file 1244 // while it is executing. Try to move it out of the way. 1245 // If the move fails, which is likely, we'll try again the 1246 // next time we do an install of this binary. 1247 if err := os.Rename(dst, dst+"~"); err == nil { 1248 os.Remove(dst + "~") 1249 } 1250 df, err = os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm) 1251 } 1252 if err != nil { 1253 return err 1254 } 1255 1256 _, err = io.Copy(df, sf) 1257 df.Close() 1258 if err != nil { 1259 mayberemovefile(dst) 1260 return fmt.Errorf("copying %s to %s: %v", src, dst, err) 1261 } 1262 return nil 1263 } 1264 1265 // writeFile writes the text to file. 1266 func (b *Builder) writeFile(file string, text []byte) error { 1267 if cfg.BuildN || cfg.BuildX { 1268 b.Showcmd("", "cat >%s << 'EOF' # internal\n%sEOF", file, text) 1269 } 1270 if cfg.BuildN { 1271 return nil 1272 } 1273 return ioutil.WriteFile(file, text, 0666) 1274 } 1275 1276 // Install the cgo export header file, if there is one. 1277 func (b *Builder) installHeader(a *Action) error { 1278 src := a.Objdir + "_cgo_install.h" 1279 if _, err := os.Stat(src); os.IsNotExist(err) { 1280 // If the file does not exist, there are no exported 1281 // functions, and we do not install anything. 1282 // TODO(rsc): Once we know that caching is rebuilding 1283 // at the right times (not missing rebuilds), here we should 1284 // probably delete the installed header, if any. 1285 if cfg.BuildX { 1286 b.Showcmd("", "# %s not created", src) 1287 } 1288 return nil 1289 } 1290 1291 dir, _ := filepath.Split(a.Target) 1292 if dir != "" { 1293 if err := b.Mkdir(dir); err != nil { 1294 return err 1295 } 1296 } 1297 1298 return b.moveOrCopyFile(a, a.Target, src, 0666, true) 1299 } 1300 1301 // cover runs, in effect, 1302 // go tool cover -mode=b.coverMode -var="varName" -o dst.go src.go 1303 func (b *Builder) cover(a *Action, dst, src string, perm os.FileMode, varName string) error { 1304 return b.run(a, a.Objdir, "cover "+a.Package.ImportPath, nil, 1305 cfg.BuildToolexec, 1306 base.Tool("cover"), 1307 "-mode", a.Package.Internal.CoverMode, 1308 "-var", varName, 1309 "-o", dst, 1310 src) 1311 } 1312 1313 var objectMagic = [][]byte{ 1314 {'!', '<', 'a', 'r', 'c', 'h', '>', '\n'}, // Package archive 1315 {'\x7F', 'E', 'L', 'F'}, // ELF 1316 {0xFE, 0xED, 0xFA, 0xCE}, // Mach-O big-endian 32-bit 1317 {0xFE, 0xED, 0xFA, 0xCF}, // Mach-O big-endian 64-bit 1318 {0xCE, 0xFA, 0xED, 0xFE}, // Mach-O little-endian 32-bit 1319 {0xCF, 0xFA, 0xED, 0xFE}, // Mach-O little-endian 64-bit 1320 {0x4d, 0x5a, 0x90, 0x00, 0x03, 0x00}, // PE (Windows) as generated by 6l/8l and gcc 1321 {0x00, 0x00, 0x01, 0xEB}, // Plan 9 i386 1322 {0x00, 0x00, 0x8a, 0x97}, // Plan 9 amd64 1323 {0x00, 0x00, 0x06, 0x47}, // Plan 9 arm 1324 } 1325 1326 func isObject(s string) bool { 1327 f, err := os.Open(s) 1328 if err != nil { 1329 return false 1330 } 1331 defer f.Close() 1332 buf := make([]byte, 64) 1333 io.ReadFull(f, buf) 1334 for _, magic := range objectMagic { 1335 if bytes.HasPrefix(buf, magic) { 1336 return true 1337 } 1338 } 1339 return false 1340 } 1341 1342 // mayberemovefile removes a file only if it is a regular file 1343 // When running as a user with sufficient privileges, we may delete 1344 // even device files, for example, which is not intended. 1345 func mayberemovefile(s string) { 1346 if fi, err := os.Lstat(s); err == nil && !fi.Mode().IsRegular() { 1347 return 1348 } 1349 os.Remove(s) 1350 } 1351 1352 // fmtcmd formats a command in the manner of fmt.Sprintf but also: 1353 // 1354 // If dir is non-empty and the script is not in dir right now, 1355 // fmtcmd inserts "cd dir\n" before the command. 1356 // 1357 // fmtcmd replaces the value of b.WorkDir with $WORK. 1358 // fmtcmd replaces the value of goroot with $GOROOT. 1359 // fmtcmd replaces the value of b.gobin with $GOBIN. 1360 // 1361 // fmtcmd replaces the name of the current directory with dot (.) 1362 // but only when it is at the beginning of a space-separated token. 1363 // 1364 func (b *Builder) fmtcmd(dir string, format string, args ...interface{}) string { 1365 cmd := fmt.Sprintf(format, args...) 1366 if dir != "" && dir != "/" { 1367 cmd = strings.Replace(" "+cmd, " "+dir, " .", -1)[1:] 1368 if b.scriptDir != dir { 1369 b.scriptDir = dir 1370 cmd = "cd " + dir + "\n" + cmd 1371 } 1372 } 1373 if b.WorkDir != "" { 1374 cmd = strings.Replace(cmd, b.WorkDir, "$WORK", -1) 1375 } 1376 return cmd 1377 } 1378 1379 // showcmd prints the given command to standard output 1380 // for the implementation of -n or -x. 1381 func (b *Builder) Showcmd(dir string, format string, args ...interface{}) { 1382 b.output.Lock() 1383 defer b.output.Unlock() 1384 b.Print(b.fmtcmd(dir, format, args...) + "\n") 1385 } 1386 1387 // showOutput prints "# desc" followed by the given output. 1388 // The output is expected to contain references to 'dir', usually 1389 // the source directory for the package that has failed to build. 1390 // showOutput rewrites mentions of dir with a relative path to dir 1391 // when the relative path is shorter. This is usually more pleasant. 1392 // For example, if fmt doesn't compile and we are in src/html, 1393 // the output is 1394 // 1395 // $ go build 1396 // # fmt 1397 // ../fmt/print.go:1090: undefined: asdf 1398 // $ 1399 // 1400 // instead of 1401 // 1402 // $ go build 1403 // # fmt 1404 // /usr/gopher/go/src/fmt/print.go:1090: undefined: asdf 1405 // $ 1406 // 1407 // showOutput also replaces references to the work directory with $WORK. 1408 // 1409 // If a is not nil and a.output is not nil, showOutput appends to that slice instead of 1410 // printing to b.Print. 1411 // 1412 func (b *Builder) showOutput(a *Action, dir, desc, out string) { 1413 prefix := "# " + desc 1414 suffix := "\n" + out 1415 if reldir := base.ShortPath(dir); reldir != dir { 1416 suffix = strings.Replace(suffix, " "+dir, " "+reldir, -1) 1417 suffix = strings.Replace(suffix, "\n"+dir, "\n"+reldir, -1) 1418 } 1419 suffix = strings.Replace(suffix, " "+b.WorkDir, " $WORK", -1) 1420 1421 if a != nil && a.output != nil { 1422 a.output = append(a.output, prefix...) 1423 a.output = append(a.output, suffix...) 1424 return 1425 } 1426 1427 b.output.Lock() 1428 defer b.output.Unlock() 1429 b.Print(prefix, suffix) 1430 } 1431 1432 // errPrintedOutput is a special error indicating that a command failed 1433 // but that it generated output as well, and that output has already 1434 // been printed, so there's no point showing 'exit status 1' or whatever 1435 // the wait status was. The main executor, builder.do, knows not to 1436 // print this error. 1437 var errPrintedOutput = errors.New("already printed output - no need to show error") 1438 1439 var cgoLine = regexp.MustCompile(`\[[^\[\]]+\.(cgo1|cover)\.go:[0-9]+(:[0-9]+)?\]`) 1440 var cgoTypeSigRe = regexp.MustCompile(`\b_C2?(type|func|var|macro)_\B`) 1441 1442 // run runs the command given by cmdline in the directory dir. 1443 // If the command fails, run prints information about the failure 1444 // and returns a non-nil error. 1445 func (b *Builder) run(a *Action, dir string, desc string, env []string, cmdargs ...interface{}) error { 1446 out, err := b.runOut(dir, desc, env, cmdargs...) 1447 if len(out) > 0 { 1448 if desc == "" { 1449 desc = b.fmtcmd(dir, "%s", strings.Join(str.StringList(cmdargs...), " ")) 1450 } 1451 b.showOutput(a, dir, desc, b.processOutput(out)) 1452 if err != nil { 1453 err = errPrintedOutput 1454 } 1455 } 1456 return err 1457 } 1458 1459 // processOutput prepares the output of runOut to be output to the console. 1460 func (b *Builder) processOutput(out []byte) string { 1461 if out[len(out)-1] != '\n' { 1462 out = append(out, '\n') 1463 } 1464 messages := string(out) 1465 // Fix up output referring to cgo-generated code to be more readable. 1466 // Replace x.go:19[/tmp/.../x.cgo1.go:18] with x.go:19. 1467 // Replace *[100]_Ctype_foo with *[100]C.foo. 1468 // If we're using -x, assume we're debugging and want the full dump, so disable the rewrite. 1469 if !cfg.BuildX && cgoLine.MatchString(messages) { 1470 messages = cgoLine.ReplaceAllString(messages, "") 1471 messages = cgoTypeSigRe.ReplaceAllString(messages, "C.") 1472 } 1473 return messages 1474 } 1475 1476 // runOut runs the command given by cmdline in the directory dir. 1477 // It returns the command output and any errors that occurred. 1478 func (b *Builder) runOut(dir string, desc string, env []string, cmdargs ...interface{}) ([]byte, error) { 1479 cmdline := str.StringList(cmdargs...) 1480 1481 for _, arg := range cmdline { 1482 // GNU binutils commands, including gcc and gccgo, interpret an argument 1483 // @foo anywhere in the command line (even following --) as meaning 1484 // "read and insert arguments from the file named foo." 1485 // Don't say anything that might be misinterpreted that way. 1486 if strings.HasPrefix(arg, "@") { 1487 return nil, fmt.Errorf("invalid command-line argument %s in command: %s", arg, joinUnambiguously(cmdline)) 1488 } 1489 } 1490 1491 if cfg.BuildN || cfg.BuildX { 1492 var envcmdline string 1493 for _, e := range env { 1494 if j := strings.IndexByte(e, '='); j != -1 { 1495 if strings.ContainsRune(e[j+1:], '\'') { 1496 envcmdline += fmt.Sprintf("%s=%q", e[:j], e[j+1:]) 1497 } else { 1498 envcmdline += fmt.Sprintf("%s='%s'", e[:j], e[j+1:]) 1499 } 1500 envcmdline += " " 1501 } 1502 } 1503 envcmdline += joinUnambiguously(cmdline) 1504 b.Showcmd(dir, "%s", envcmdline) 1505 if cfg.BuildN { 1506 return nil, nil 1507 } 1508 } 1509 1510 var buf bytes.Buffer 1511 cmd := exec.Command(cmdline[0], cmdline[1:]...) 1512 cmd.Stdout = &buf 1513 cmd.Stderr = &buf 1514 cmd.Dir = dir 1515 cmd.Env = base.MergeEnvLists(env, base.EnvForDir(cmd.Dir, os.Environ())) 1516 err := cmd.Run() 1517 1518 // err can be something like 'exit status 1'. 1519 // Add information about what program was running. 1520 // Note that if buf.Bytes() is non-empty, the caller usually 1521 // shows buf.Bytes() and does not print err at all, so the 1522 // prefix here does not make most output any more verbose. 1523 if err != nil { 1524 err = errors.New(cmdline[0] + ": " + err.Error()) 1525 } 1526 return buf.Bytes(), err 1527 } 1528 1529 // joinUnambiguously prints the slice, quoting where necessary to make the 1530 // output unambiguous. 1531 // TODO: See issue 5279. The printing of commands needs a complete redo. 1532 func joinUnambiguously(a []string) string { 1533 var buf bytes.Buffer 1534 for i, s := range a { 1535 if i > 0 { 1536 buf.WriteByte(' ') 1537 } 1538 q := strconv.Quote(s) 1539 if s == "" || strings.Contains(s, " ") || len(q) > len(s)+2 { 1540 buf.WriteString(q) 1541 } else { 1542 buf.WriteString(s) 1543 } 1544 } 1545 return buf.String() 1546 } 1547 1548 // mkdir makes the named directory. 1549 func (b *Builder) Mkdir(dir string) error { 1550 // Make Mkdir(a.Objdir) a no-op instead of an error when a.Objdir == "". 1551 if dir == "" { 1552 return nil 1553 } 1554 1555 b.exec.Lock() 1556 defer b.exec.Unlock() 1557 // We can be a little aggressive about being 1558 // sure directories exist. Skip repeated calls. 1559 if b.mkdirCache[dir] { 1560 return nil 1561 } 1562 b.mkdirCache[dir] = true 1563 1564 if cfg.BuildN || cfg.BuildX { 1565 b.Showcmd("", "mkdir -p %s", dir) 1566 if cfg.BuildN { 1567 return nil 1568 } 1569 } 1570 1571 if err := os.MkdirAll(dir, 0777); err != nil { 1572 return err 1573 } 1574 return nil 1575 } 1576 1577 // symlink creates a symlink newname -> oldname. 1578 func (b *Builder) Symlink(oldname, newname string) error { 1579 if cfg.BuildN || cfg.BuildX { 1580 b.Showcmd("", "ln -s %s %s", oldname, newname) 1581 if cfg.BuildN { 1582 return nil 1583 } 1584 } 1585 return os.Symlink(oldname, newname) 1586 } 1587 1588 // mkAbs returns an absolute path corresponding to 1589 // evaluating f in the directory dir. 1590 // We always pass absolute paths of source files so that 1591 // the error messages will include the full path to a file 1592 // in need of attention. 1593 func mkAbs(dir, f string) string { 1594 // Leave absolute paths alone. 1595 // Also, during -n mode we use the pseudo-directory $WORK 1596 // instead of creating an actual work directory that won't be used. 1597 // Leave paths beginning with $WORK alone too. 1598 if filepath.IsAbs(f) || strings.HasPrefix(f, "$WORK") { 1599 return f 1600 } 1601 return filepath.Join(dir, f) 1602 } 1603 1604 type toolchain interface { 1605 // gc runs the compiler in a specific directory on a set of files 1606 // and returns the name of the generated output file. 1607 gc(b *Builder, a *Action, archive string, importcfg []byte, asmhdr bool, gofiles []string) (ofile string, out []byte, err error) 1608 // cc runs the toolchain's C compiler in a directory on a C file 1609 // to produce an output file. 1610 cc(b *Builder, a *Action, ofile, cfile string) error 1611 // asm runs the assembler in a specific directory on specific files 1612 // and returns a list of named output files. 1613 asm(b *Builder, a *Action, sfiles []string) ([]string, error) 1614 // pack runs the archive packer in a specific directory to create 1615 // an archive from a set of object files. 1616 // typically it is run in the object directory. 1617 pack(b *Builder, a *Action, afile string, ofiles []string) error 1618 // ld runs the linker to create an executable starting at mainpkg. 1619 ld(b *Builder, root *Action, out, importcfg, mainpkg string) error 1620 // ldShared runs the linker to create a shared library containing the pkgs built by toplevelactions 1621 ldShared(b *Builder, root *Action, toplevelactions []*Action, out, importcfg string, allactions []*Action) error 1622 1623 compiler() string 1624 linker() string 1625 } 1626 1627 type noToolchain struct{} 1628 1629 func noCompiler() error { 1630 log.Fatalf("unknown compiler %q", cfg.BuildContext.Compiler) 1631 return nil 1632 } 1633 1634 func (noToolchain) compiler() string { 1635 noCompiler() 1636 return "" 1637 } 1638 1639 func (noToolchain) linker() string { 1640 noCompiler() 1641 return "" 1642 } 1643 1644 func (noToolchain) gc(b *Builder, a *Action, archive string, importcfg []byte, asmhdr bool, gofiles []string) (ofile string, out []byte, err error) { 1645 return "", nil, noCompiler() 1646 } 1647 1648 func (noToolchain) asm(b *Builder, a *Action, sfiles []string) ([]string, error) { 1649 return nil, noCompiler() 1650 } 1651 1652 func (noToolchain) pack(b *Builder, a *Action, afile string, ofiles []string) error { 1653 return noCompiler() 1654 } 1655 1656 func (noToolchain) ld(b *Builder, root *Action, out, importcfg, mainpkg string) error { 1657 return noCompiler() 1658 } 1659 1660 func (noToolchain) ldShared(b *Builder, root *Action, toplevelactions []*Action, out, importcfg string, allactions []*Action) error { 1661 return noCompiler() 1662 } 1663 1664 func (noToolchain) cc(b *Builder, a *Action, ofile, cfile string) error { 1665 return noCompiler() 1666 } 1667 1668 // gcc runs the gcc C compiler to create an object from a single C file. 1669 func (b *Builder) gcc(a *Action, p *load.Package, workdir, out string, flags []string, cfile string) error { 1670 return b.ccompile(a, p, out, flags, cfile, b.GccCmd(p.Dir, workdir)) 1671 } 1672 1673 // gxx runs the g++ C++ compiler to create an object from a single C++ file. 1674 func (b *Builder) gxx(a *Action, p *load.Package, workdir, out string, flags []string, cxxfile string) error { 1675 return b.ccompile(a, p, out, flags, cxxfile, b.GxxCmd(p.Dir, workdir)) 1676 } 1677 1678 // gfortran runs the gfortran Fortran compiler to create an object from a single Fortran file. 1679 func (b *Builder) gfortran(a *Action, p *load.Package, workdir, out string, flags []string, ffile string) error { 1680 return b.ccompile(a, p, out, flags, ffile, b.gfortranCmd(p.Dir, workdir)) 1681 } 1682 1683 // ccompile runs the given C or C++ compiler and creates an object from a single source file. 1684 func (b *Builder) ccompile(a *Action, p *load.Package, outfile string, flags []string, file string, compiler []string) error { 1685 file = mkAbs(p.Dir, file) 1686 desc := p.ImportPath 1687 if !filepath.IsAbs(outfile) { 1688 outfile = filepath.Join(p.Dir, outfile) 1689 } 1690 output, err := b.runOut(filepath.Dir(file), desc, nil, compiler, flags, "-o", outfile, "-c", filepath.Base(file)) 1691 if len(output) > 0 { 1692 // On FreeBSD 11, when we pass -g to clang 3.8 it 1693 // invokes its internal assembler with -dwarf-version=2. 1694 // When it sees .section .note.GNU-stack, it warns 1695 // "DWARF2 only supports one section per compilation unit". 1696 // This warning makes no sense, since the section is empty, 1697 // but it confuses people. 1698 // We work around the problem by detecting the warning 1699 // and dropping -g and trying again. 1700 if bytes.Contains(output, []byte("DWARF2 only supports one section per compilation unit")) { 1701 newFlags := make([]string, 0, len(flags)) 1702 for _, f := range flags { 1703 if !strings.HasPrefix(f, "-g") { 1704 newFlags = append(newFlags, f) 1705 } 1706 } 1707 if len(newFlags) < len(flags) { 1708 return b.ccompile(a, p, outfile, newFlags, file, compiler) 1709 } 1710 } 1711 1712 b.showOutput(a, p.Dir, desc, b.processOutput(output)) 1713 if err != nil { 1714 err = errPrintedOutput 1715 } else if os.Getenv("GO_BUILDER_NAME") != "" { 1716 return errors.New("C compiler warning promoted to error on Go builders") 1717 } 1718 } 1719 return err 1720 } 1721 1722 // gccld runs the gcc linker to create an executable from a set of object files. 1723 func (b *Builder) gccld(p *load.Package, objdir, out string, flags []string, objs []string) error { 1724 var cmd []string 1725 if len(p.CXXFiles) > 0 || len(p.SwigCXXFiles) > 0 { 1726 cmd = b.GxxCmd(p.Dir, objdir) 1727 } else { 1728 cmd = b.GccCmd(p.Dir, objdir) 1729 } 1730 return b.run(nil, p.Dir, p.ImportPath, nil, cmd, "-o", out, objs, flags) 1731 } 1732 1733 // Grab these before main helpfully overwrites them. 1734 var ( 1735 origCC = os.Getenv("CC") 1736 origCXX = os.Getenv("CXX") 1737 ) 1738 1739 // gccCmd returns a gcc command line prefix 1740 // defaultCC is defined in zdefaultcc.go, written by cmd/dist. 1741 func (b *Builder) GccCmd(incdir, workdir string) []string { 1742 return b.compilerCmd(b.ccExe(), incdir, workdir) 1743 } 1744 1745 // gxxCmd returns a g++ command line prefix 1746 // defaultCXX is defined in zdefaultcc.go, written by cmd/dist. 1747 func (b *Builder) GxxCmd(incdir, workdir string) []string { 1748 return b.compilerCmd(b.cxxExe(), incdir, workdir) 1749 } 1750 1751 // gfortranCmd returns a gfortran command line prefix. 1752 func (b *Builder) gfortranCmd(incdir, workdir string) []string { 1753 return b.compilerCmd(b.fcExe(), incdir, workdir) 1754 } 1755 1756 // ccExe returns the CC compiler setting without all the extra flags we add implicitly. 1757 func (b *Builder) ccExe() []string { 1758 return b.compilerExe(origCC, cfg.DefaultCC(cfg.Goos, cfg.Goarch)) 1759 } 1760 1761 // cxxExe returns the CXX compiler setting without all the extra flags we add implicitly. 1762 func (b *Builder) cxxExe() []string { 1763 return b.compilerExe(origCXX, cfg.DefaultCXX(cfg.Goos, cfg.Goarch)) 1764 } 1765 1766 // fcExe returns the FC compiler setting without all the extra flags we add implicitly. 1767 func (b *Builder) fcExe() []string { 1768 return b.compilerExe(os.Getenv("FC"), "gfortran") 1769 } 1770 1771 // compilerExe returns the compiler to use given an 1772 // environment variable setting (the value not the name) 1773 // and a default. The resulting slice is usually just the name 1774 // of the compiler but can have additional arguments if they 1775 // were present in the environment value. 1776 // For example if CC="gcc -DGOPHER" then the result is ["gcc", "-DGOPHER"]. 1777 func (b *Builder) compilerExe(envValue string, def string) []string { 1778 compiler := strings.Fields(envValue) 1779 if len(compiler) == 0 { 1780 compiler = []string{def} 1781 } 1782 return compiler 1783 } 1784 1785 // compilerCmd returns a command line prefix for the given environment 1786 // variable and using the default command when the variable is empty. 1787 func (b *Builder) compilerCmd(compiler []string, incdir, workdir string) []string { 1788 // NOTE: env.go's mkEnv knows that the first three 1789 // strings returned are "gcc", "-I", incdir (and cuts them off). 1790 a := []string{compiler[0], "-I", incdir} 1791 a = append(a, compiler[1:]...) 1792 1793 // Definitely want -fPIC but on Windows gcc complains 1794 // "-fPIC ignored for target (all code is position independent)" 1795 if cfg.Goos != "windows" { 1796 a = append(a, "-fPIC") 1797 } 1798 a = append(a, b.gccArchArgs()...) 1799 // gcc-4.5 and beyond require explicit "-pthread" flag 1800 // for multithreading with pthread library. 1801 if cfg.BuildContext.CgoEnabled { 1802 switch cfg.Goos { 1803 case "windows": 1804 a = append(a, "-mthreads") 1805 default: 1806 a = append(a, "-pthread") 1807 } 1808 } 1809 1810 // disable ASCII art in clang errors, if possible 1811 if b.gccSupportsFlag(compiler, "-fno-caret-diagnostics") { 1812 a = append(a, "-fno-caret-diagnostics") 1813 } 1814 // clang is too smart about command-line arguments 1815 if b.gccSupportsFlag(compiler, "-Qunused-arguments") { 1816 a = append(a, "-Qunused-arguments") 1817 } 1818 1819 // disable word wrapping in error messages 1820 a = append(a, "-fmessage-length=0") 1821 1822 // Tell gcc not to include the work directory in object files. 1823 if b.gccSupportsFlag(compiler, "-fdebug-prefix-map=a=b") { 1824 if workdir == "" { 1825 workdir = b.WorkDir 1826 } 1827 workdir = strings.TrimSuffix(workdir, string(filepath.Separator)) 1828 a = append(a, "-fdebug-prefix-map="+workdir+"=/tmp/go-build") 1829 } 1830 1831 // Tell gcc not to include flags in object files, which defeats the 1832 // point of -fdebug-prefix-map above. 1833 if b.gccSupportsFlag(compiler, "-gno-record-gcc-switches") { 1834 a = append(a, "-gno-record-gcc-switches") 1835 } 1836 1837 // On OS X, some of the compilers behave as if -fno-common 1838 // is always set, and the Mach-O linker in 6l/8l assumes this. 1839 // See https://golang.org/issue/3253. 1840 if cfg.Goos == "darwin" { 1841 a = append(a, "-fno-common") 1842 } 1843 1844 return a 1845 } 1846 1847 // gccNoPie returns the flag to use to request non-PIE. On systems 1848 // with PIE (position independent executables) enabled by default, 1849 // -no-pie must be passed when doing a partial link with -Wl,-r. 1850 // But -no-pie is not supported by all compilers, and clang spells it -nopie. 1851 func (b *Builder) gccNoPie(linker []string) string { 1852 if b.gccSupportsFlag(linker, "-no-pie") { 1853 return "-no-pie" 1854 } 1855 if b.gccSupportsFlag(linker, "-nopie") { 1856 return "-nopie" 1857 } 1858 return "" 1859 } 1860 1861 // gccSupportsFlag checks to see if the compiler supports a flag. 1862 func (b *Builder) gccSupportsFlag(compiler []string, flag string) bool { 1863 key := [2]string{compiler[0], flag} 1864 1865 b.exec.Lock() 1866 defer b.exec.Unlock() 1867 if b, ok := b.flagCache[key]; ok { 1868 return b 1869 } 1870 if b.flagCache == nil { 1871 b.flagCache = make(map[[2]string]bool) 1872 } 1873 // We used to write an empty C file, but that gets complicated with 1874 // go build -n. We tried using a file that does not exist, but that 1875 // fails on systems with GCC version 4.2.1; that is the last GPLv2 1876 // version of GCC, so some systems have frozen on it. 1877 // Now we pass an empty file on stdin, which should work at least for 1878 // GCC and clang. 1879 cmdArgs := str.StringList(compiler, flag, "-c", "-x", "c", "-") 1880 if cfg.BuildN || cfg.BuildX { 1881 b.Showcmd(b.WorkDir, "%s || true", joinUnambiguously(cmdArgs)) 1882 if cfg.BuildN { 1883 return false 1884 } 1885 } 1886 cmd := exec.Command(cmdArgs[0], cmdArgs[1:]...) 1887 cmd.Dir = b.WorkDir 1888 cmd.Env = base.MergeEnvLists([]string{"LC_ALL=C"}, base.EnvForDir(cmd.Dir, os.Environ())) 1889 out, _ := cmd.CombinedOutput() 1890 // GCC says "unrecognized command line option". 1891 // clang says "unknown argument". 1892 // Older versions of GCC say "unrecognised debug output level". 1893 // For -fsplit-stack GCC says "'-fsplit-stack' is not supported". 1894 supported := !bytes.Contains(out, []byte("unrecognized")) && 1895 !bytes.Contains(out, []byte("unknown")) && 1896 !bytes.Contains(out, []byte("unrecognised")) && 1897 !bytes.Contains(out, []byte("is not supported")) 1898 b.flagCache[key] = supported 1899 return supported 1900 } 1901 1902 // gccArchArgs returns arguments to pass to gcc based on the architecture. 1903 func (b *Builder) gccArchArgs() []string { 1904 switch cfg.Goarch { 1905 case "386": 1906 return []string{"-m32"} 1907 case "amd64", "amd64p32": 1908 return []string{"-m64"} 1909 case "arm": 1910 return []string{"-marm"} // not thumb 1911 case "s390x": 1912 return []string{"-m64", "-march=z196"} 1913 case "mips64", "mips64le": 1914 return []string{"-mabi=64"} 1915 case "mips", "mipsle": 1916 return []string{"-mabi=32", "-march=mips32"} 1917 } 1918 return nil 1919 } 1920 1921 // envList returns the value of the given environment variable broken 1922 // into fields, using the default value when the variable is empty. 1923 func envList(key, def string) []string { 1924 v := os.Getenv(key) 1925 if v == "" { 1926 v = def 1927 } 1928 return strings.Fields(v) 1929 } 1930 1931 // CFlags returns the flags to use when invoking the C, C++ or Fortran compilers, or cgo. 1932 func (b *Builder) CFlags(p *load.Package) (cppflags, cflags, cxxflags, fflags, ldflags []string, err error) { 1933 defaults := "-g -O2" 1934 1935 if cppflags, err = buildFlags("CPPFLAGS", "", p.CgoCPPFLAGS, checkCompilerFlags); err != nil { 1936 return 1937 } 1938 if cflags, err = buildFlags("CFLAGS", defaults, p.CgoCFLAGS, checkCompilerFlags); err != nil { 1939 return 1940 } 1941 if cxxflags, err = buildFlags("CXXFLAGS", defaults, p.CgoCXXFLAGS, checkCompilerFlags); err != nil { 1942 return 1943 } 1944 if fflags, err = buildFlags("FFLAGS", defaults, p.CgoFFLAGS, checkCompilerFlags); err != nil { 1945 return 1946 } 1947 if ldflags, err = buildFlags("LDFLAGS", defaults, p.CgoLDFLAGS, checkLinkerFlags); err != nil { 1948 return 1949 } 1950 1951 return 1952 } 1953 1954 func buildFlags(name, defaults string, fromPackage []string, check func(string, string, []string) error) ([]string, error) { 1955 if err := check(name, "#cgo "+name, fromPackage); err != nil { 1956 return nil, err 1957 } 1958 return str.StringList(envList("CGO_"+name, defaults), fromPackage), nil 1959 } 1960 1961 var cgoRe = regexp.MustCompile(`[/\\:]`) 1962 1963 func (b *Builder) cgo(a *Action, cgoExe, objdir string, pcCFLAGS, pcLDFLAGS, cgofiles, gccfiles, gxxfiles, mfiles, ffiles []string) (outGo, outObj []string, err error) { 1964 p := a.Package 1965 cgoCPPFLAGS, cgoCFLAGS, cgoCXXFLAGS, cgoFFLAGS, cgoLDFLAGS, err := b.CFlags(p) 1966 if err != nil { 1967 return nil, nil, err 1968 } 1969 1970 cgoCPPFLAGS = append(cgoCPPFLAGS, pcCFLAGS...) 1971 cgoLDFLAGS = append(cgoLDFLAGS, pcLDFLAGS...) 1972 // If we are compiling Objective-C code, then we need to link against libobjc 1973 if len(mfiles) > 0 { 1974 cgoLDFLAGS = append(cgoLDFLAGS, "-lobjc") 1975 } 1976 1977 // Likewise for Fortran, except there are many Fortran compilers. 1978 // Support gfortran out of the box and let others pass the correct link options 1979 // via CGO_LDFLAGS 1980 if len(ffiles) > 0 { 1981 fc := os.Getenv("FC") 1982 if fc == "" { 1983 fc = "gfortran" 1984 } 1985 if strings.Contains(fc, "gfortran") { 1986 cgoLDFLAGS = append(cgoLDFLAGS, "-lgfortran") 1987 } 1988 } 1989 1990 if cfg.BuildMSan { 1991 cgoCFLAGS = append([]string{"-fsanitize=memory"}, cgoCFLAGS...) 1992 cgoLDFLAGS = append([]string{"-fsanitize=memory"}, cgoLDFLAGS...) 1993 } 1994 1995 // Allows including _cgo_export.h from .[ch] files in the package. 1996 cgoCPPFLAGS = append(cgoCPPFLAGS, "-I", objdir) 1997 1998 // cgo 1999 // TODO: CGO_FLAGS? 2000 gofiles := []string{objdir + "_cgo_gotypes.go"} 2001 cfiles := []string{"_cgo_export.c"} 2002 for _, fn := range cgofiles { 2003 f := strings.TrimSuffix(filepath.Base(fn), ".go") 2004 gofiles = append(gofiles, objdir+f+".cgo1.go") 2005 cfiles = append(cfiles, f+".cgo2.c") 2006 } 2007 2008 // TODO: make cgo not depend on $GOARCH? 2009 2010 cgoflags := []string{} 2011 if p.Standard && p.ImportPath == "runtime/cgo" { 2012 cgoflags = append(cgoflags, "-import_runtime_cgo=false") 2013 } 2014 if p.Standard && (p.ImportPath == "runtime/race" || p.ImportPath == "runtime/msan" || p.ImportPath == "runtime/cgo") { 2015 cgoflags = append(cgoflags, "-import_syscall=false") 2016 } 2017 2018 // Update $CGO_LDFLAGS with p.CgoLDFLAGS. 2019 // These flags are recorded in the generated _cgo_gotypes.go file 2020 // using //go:cgo_ldflag directives, the compiler records them in the 2021 // object file for the package, and then the Go linker passes them 2022 // along to the host linker. At this point in the code, cgoLDFLAGS 2023 // consists of the original $CGO_LDFLAGS (unchecked) and all the 2024 // flags put together from source code (checked). 2025 var cgoenv []string 2026 if len(cgoLDFLAGS) > 0 { 2027 flags := make([]string, len(cgoLDFLAGS)) 2028 for i, f := range cgoLDFLAGS { 2029 flags[i] = strconv.Quote(f) 2030 } 2031 cgoenv = []string{"CGO_LDFLAGS=" + strings.Join(flags, " ")} 2032 } 2033 2034 if cfg.BuildToolchainName == "gccgo" { 2035 switch cfg.Goarch { 2036 case "386", "amd64": 2037 cgoCFLAGS = append(cgoCFLAGS, "-fsplit-stack") 2038 } 2039 cgoflags = append(cgoflags, "-gccgo") 2040 if pkgpath := gccgoPkgpath(p); pkgpath != "" { 2041 cgoflags = append(cgoflags, "-gccgopkgpath="+pkgpath) 2042 } 2043 } 2044 2045 switch cfg.BuildBuildmode { 2046 case "c-archive", "c-shared": 2047 // Tell cgo that if there are any exported functions 2048 // it should generate a header file that C code can 2049 // #include. 2050 cgoflags = append(cgoflags, "-exportheader="+objdir+"_cgo_install.h") 2051 } 2052 2053 if err := b.run(a, p.Dir, p.ImportPath, cgoenv, cfg.BuildToolexec, cgoExe, "-objdir", objdir, "-importpath", p.ImportPath, cgoflags, "--", cgoCPPFLAGS, cgoCFLAGS, cgofiles); err != nil { 2054 return nil, nil, err 2055 } 2056 outGo = append(outGo, gofiles...) 2057 2058 // Use sequential object file names to keep them distinct 2059 // and short enough to fit in the .a header file name slots. 2060 // We no longer collect them all into _all.o, and we'd like 2061 // tools to see both the .o suffix and unique names, so 2062 // we need to make them short enough not to be truncated 2063 // in the final archive. 2064 oseq := 0 2065 nextOfile := func() string { 2066 oseq++ 2067 return objdir + fmt.Sprintf("_x%03d.o", oseq) 2068 } 2069 2070 // gcc 2071 cflags := str.StringList(cgoCPPFLAGS, cgoCFLAGS) 2072 for _, cfile := range cfiles { 2073 ofile := nextOfile() 2074 if err := b.gcc(a, p, a.Objdir, ofile, cflags, objdir+cfile); err != nil { 2075 return nil, nil, err 2076 } 2077 outObj = append(outObj, ofile) 2078 } 2079 2080 for _, file := range gccfiles { 2081 ofile := nextOfile() 2082 if err := b.gcc(a, p, a.Objdir, ofile, cflags, file); err != nil { 2083 return nil, nil, err 2084 } 2085 outObj = append(outObj, ofile) 2086 } 2087 2088 cxxflags := str.StringList(cgoCPPFLAGS, cgoCXXFLAGS) 2089 for _, file := range gxxfiles { 2090 ofile := nextOfile() 2091 if err := b.gxx(a, p, a.Objdir, ofile, cxxflags, file); err != nil { 2092 return nil, nil, err 2093 } 2094 outObj = append(outObj, ofile) 2095 } 2096 2097 for _, file := range mfiles { 2098 ofile := nextOfile() 2099 if err := b.gcc(a, p, a.Objdir, ofile, cflags, file); err != nil { 2100 return nil, nil, err 2101 } 2102 outObj = append(outObj, ofile) 2103 } 2104 2105 fflags := str.StringList(cgoCPPFLAGS, cgoFFLAGS) 2106 for _, file := range ffiles { 2107 ofile := nextOfile() 2108 if err := b.gfortran(a, p, a.Objdir, ofile, fflags, file); err != nil { 2109 return nil, nil, err 2110 } 2111 outObj = append(outObj, ofile) 2112 } 2113 2114 switch cfg.BuildToolchainName { 2115 case "gc": 2116 importGo := objdir + "_cgo_import.go" 2117 if err := b.dynimport(a, p, objdir, importGo, cgoExe, cflags, cgoLDFLAGS, outObj); err != nil { 2118 return nil, nil, err 2119 } 2120 outGo = append(outGo, importGo) 2121 2122 case "gccgo": 2123 defunC := objdir + "_cgo_defun.c" 2124 defunObj := objdir + "_cgo_defun.o" 2125 if err := BuildToolchain.cc(b, a, defunObj, defunC); err != nil { 2126 return nil, nil, err 2127 } 2128 outObj = append(outObj, defunObj) 2129 2130 default: 2131 noCompiler() 2132 } 2133 2134 return outGo, outObj, nil 2135 } 2136 2137 // dynimport creates a Go source file named importGo containing 2138 // //go:cgo_import_dynamic directives for each symbol or library 2139 // dynamically imported by the object files outObj. 2140 func (b *Builder) dynimport(a *Action, p *load.Package, objdir, importGo, cgoExe string, cflags, cgoLDFLAGS, outObj []string) error { 2141 cfile := objdir + "_cgo_main.c" 2142 ofile := objdir + "_cgo_main.o" 2143 if err := b.gcc(a, p, objdir, ofile, cflags, cfile); err != nil { 2144 return err 2145 } 2146 2147 linkobj := str.StringList(ofile, outObj, p.SysoFiles) 2148 dynobj := objdir + "_cgo_.o" 2149 2150 // we need to use -pie for Linux/ARM to get accurate imported sym 2151 ldflags := cgoLDFLAGS 2152 if (cfg.Goarch == "arm" && cfg.Goos == "linux") || cfg.Goos == "android" { 2153 ldflags = append(ldflags, "-pie") 2154 } 2155 if err := b.gccld(p, objdir, dynobj, ldflags, linkobj); err != nil { 2156 return err 2157 } 2158 2159 // cgo -dynimport 2160 var cgoflags []string 2161 if p.Standard && p.ImportPath == "runtime/cgo" { 2162 cgoflags = []string{"-dynlinker"} // record path to dynamic linker 2163 } 2164 return b.run(a, p.Dir, p.ImportPath, nil, cfg.BuildToolexec, cgoExe, "-dynpackage", p.Name, "-dynimport", dynobj, "-dynout", importGo, cgoflags) 2165 } 2166 2167 // Run SWIG on all SWIG input files. 2168 // TODO: Don't build a shared library, once SWIG emits the necessary 2169 // pragmas for external linking. 2170 func (b *Builder) swig(a *Action, p *load.Package, objdir string, pcCFLAGS []string) (outGo, outC, outCXX []string, err error) { 2171 if err := b.swigVersionCheck(); err != nil { 2172 return nil, nil, nil, err 2173 } 2174 2175 intgosize, err := b.swigIntSize(objdir) 2176 if err != nil { 2177 return nil, nil, nil, err 2178 } 2179 2180 for _, f := range p.SwigFiles { 2181 goFile, cFile, err := b.swigOne(a, p, f, objdir, pcCFLAGS, false, intgosize) 2182 if err != nil { 2183 return nil, nil, nil, err 2184 } 2185 if goFile != "" { 2186 outGo = append(outGo, goFile) 2187 } 2188 if cFile != "" { 2189 outC = append(outC, cFile) 2190 } 2191 } 2192 for _, f := range p.SwigCXXFiles { 2193 goFile, cxxFile, err := b.swigOne(a, p, f, objdir, pcCFLAGS, true, intgosize) 2194 if err != nil { 2195 return nil, nil, nil, err 2196 } 2197 if goFile != "" { 2198 outGo = append(outGo, goFile) 2199 } 2200 if cxxFile != "" { 2201 outCXX = append(outCXX, cxxFile) 2202 } 2203 } 2204 return outGo, outC, outCXX, nil 2205 } 2206 2207 // Make sure SWIG is new enough. 2208 var ( 2209 swigCheckOnce sync.Once 2210 swigCheck error 2211 ) 2212 2213 func (b *Builder) swigDoVersionCheck() error { 2214 out, err := b.runOut("", "", nil, "swig", "-version") 2215 if err != nil { 2216 return err 2217 } 2218 re := regexp.MustCompile(`[vV]ersion +([\d]+)([.][\d]+)?([.][\d]+)?`) 2219 matches := re.FindSubmatch(out) 2220 if matches == nil { 2221 // Can't find version number; hope for the best. 2222 return nil 2223 } 2224 2225 major, err := strconv.Atoi(string(matches[1])) 2226 if err != nil { 2227 // Can't find version number; hope for the best. 2228 return nil 2229 } 2230 const errmsg = "must have SWIG version >= 3.0.6" 2231 if major < 3 { 2232 return errors.New(errmsg) 2233 } 2234 if major > 3 { 2235 // 4.0 or later 2236 return nil 2237 } 2238 2239 // We have SWIG version 3.x. 2240 if len(matches[2]) > 0 { 2241 minor, err := strconv.Atoi(string(matches[2][1:])) 2242 if err != nil { 2243 return nil 2244 } 2245 if minor > 0 { 2246 // 3.1 or later 2247 return nil 2248 } 2249 } 2250 2251 // We have SWIG version 3.0.x. 2252 if len(matches[3]) > 0 { 2253 patch, err := strconv.Atoi(string(matches[3][1:])) 2254 if err != nil { 2255 return nil 2256 } 2257 if patch < 6 { 2258 // Before 3.0.6. 2259 return errors.New(errmsg) 2260 } 2261 } 2262 2263 return nil 2264 } 2265 2266 func (b *Builder) swigVersionCheck() error { 2267 swigCheckOnce.Do(func() { 2268 swigCheck = b.swigDoVersionCheck() 2269 }) 2270 return swigCheck 2271 } 2272 2273 // Find the value to pass for the -intgosize option to swig. 2274 var ( 2275 swigIntSizeOnce sync.Once 2276 swigIntSize string 2277 swigIntSizeError error 2278 ) 2279 2280 // This code fails to build if sizeof(int) <= 32 2281 const swigIntSizeCode = ` 2282 package main 2283 const i int = 1 << 32 2284 ` 2285 2286 // Determine the size of int on the target system for the -intgosize option 2287 // of swig >= 2.0.9. Run only once. 2288 func (b *Builder) swigDoIntSize(objdir string) (intsize string, err error) { 2289 if cfg.BuildN { 2290 return "$INTBITS", nil 2291 } 2292 src := filepath.Join(b.WorkDir, "swig_intsize.go") 2293 if err = ioutil.WriteFile(src, []byte(swigIntSizeCode), 0666); err != nil { 2294 return 2295 } 2296 srcs := []string{src} 2297 2298 p := load.GoFilesPackage(srcs) 2299 2300 if _, _, e := BuildToolchain.gc(b, &Action{Mode: "swigDoIntSize", Package: p, Objdir: objdir}, "", nil, false, srcs); e != nil { 2301 return "32", nil 2302 } 2303 return "64", nil 2304 } 2305 2306 // Determine the size of int on the target system for the -intgosize option 2307 // of swig >= 2.0.9. 2308 func (b *Builder) swigIntSize(objdir string) (intsize string, err error) { 2309 swigIntSizeOnce.Do(func() { 2310 swigIntSize, swigIntSizeError = b.swigDoIntSize(objdir) 2311 }) 2312 return swigIntSize, swigIntSizeError 2313 } 2314 2315 // Run SWIG on one SWIG input file. 2316 func (b *Builder) swigOne(a *Action, p *load.Package, file, objdir string, pcCFLAGS []string, cxx bool, intgosize string) (outGo, outC string, err error) { 2317 cgoCPPFLAGS, cgoCFLAGS, cgoCXXFLAGS, _, _, err := b.CFlags(p) 2318 if err != nil { 2319 return "", "", err 2320 } 2321 2322 var cflags []string 2323 if cxx { 2324 cflags = str.StringList(cgoCPPFLAGS, pcCFLAGS, cgoCXXFLAGS) 2325 } else { 2326 cflags = str.StringList(cgoCPPFLAGS, pcCFLAGS, cgoCFLAGS) 2327 } 2328 2329 n := 5 // length of ".swig" 2330 if cxx { 2331 n = 8 // length of ".swigcxx" 2332 } 2333 base := file[:len(file)-n] 2334 goFile := base + ".go" 2335 gccBase := base + "_wrap." 2336 gccExt := "c" 2337 if cxx { 2338 gccExt = "cxx" 2339 } 2340 2341 gccgo := cfg.BuildToolchainName == "gccgo" 2342 2343 // swig 2344 args := []string{ 2345 "-go", 2346 "-cgo", 2347 "-intgosize", intgosize, 2348 "-module", base, 2349 "-o", objdir + gccBase + gccExt, 2350 "-outdir", objdir, 2351 } 2352 2353 for _, f := range cflags { 2354 if len(f) > 3 && f[:2] == "-I" { 2355 args = append(args, f) 2356 } 2357 } 2358 2359 if gccgo { 2360 args = append(args, "-gccgo") 2361 if pkgpath := gccgoPkgpath(p); pkgpath != "" { 2362 args = append(args, "-go-pkgpath", pkgpath) 2363 } 2364 } 2365 if cxx { 2366 args = append(args, "-c++") 2367 } 2368 2369 out, err := b.runOut(p.Dir, p.ImportPath, nil, "swig", args, file) 2370 if err != nil { 2371 if len(out) > 0 { 2372 if bytes.Contains(out, []byte("-intgosize")) || bytes.Contains(out, []byte("-cgo")) { 2373 return "", "", errors.New("must have SWIG version >= 3.0.6") 2374 } 2375 b.showOutput(a, p.Dir, p.ImportPath, b.processOutput(out)) // swig error 2376 return "", "", errPrintedOutput 2377 } 2378 return "", "", err 2379 } 2380 if len(out) > 0 { 2381 b.showOutput(a, p.Dir, p.ImportPath, b.processOutput(out)) // swig warning 2382 } 2383 2384 // If the input was x.swig, the output is x.go in the objdir. 2385 // But there might be an x.go in the original dir too, and if it 2386 // uses cgo as well, cgo will be processing both and will 2387 // translate both into x.cgo1.go in the objdir, overwriting one. 2388 // Rename x.go to _x_swig.go to avoid this problem. 2389 // We ignore files in the original dir that begin with underscore 2390 // so _x_swig.go cannot conflict with an original file we were 2391 // going to compile. 2392 goFile = objdir + goFile 2393 newGoFile := objdir + "_" + base + "_swig.go" 2394 if err := os.Rename(goFile, newGoFile); err != nil { 2395 return "", "", err 2396 } 2397 return newGoFile, objdir + gccBase + gccExt, nil 2398 } 2399 2400 // disableBuildID adjusts a linker command line to avoid creating a 2401 // build ID when creating an object file rather than an executable or 2402 // shared library. Some systems, such as Ubuntu, always add 2403 // --build-id to every link, but we don't want a build ID when we are 2404 // producing an object file. On some of those system a plain -r (not 2405 // -Wl,-r) will turn off --build-id, but clang 3.0 doesn't support a 2406 // plain -r. I don't know how to turn off --build-id when using clang 2407 // other than passing a trailing --build-id=none. So that is what we 2408 // do, but only on systems likely to support it, which is to say, 2409 // systems that normally use gold or the GNU linker. 2410 func (b *Builder) disableBuildID(ldflags []string) []string { 2411 switch cfg.Goos { 2412 case "android", "dragonfly", "linux", "netbsd": 2413 ldflags = append(ldflags, "-Wl,--build-id=none") 2414 } 2415 return ldflags 2416 } 2417 2418 // mkAbsFiles converts files into a list of absolute files, 2419 // assuming they were originally relative to dir, 2420 // and returns that new list. 2421 func mkAbsFiles(dir string, files []string) []string { 2422 abs := make([]string, len(files)) 2423 for i, f := range files { 2424 if !filepath.IsAbs(f) { 2425 f = filepath.Join(dir, f) 2426 } 2427 abs[i] = f 2428 } 2429 return abs 2430 }