PageRenderTime 63ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

/src/cmd/go/build.go

https://bitbucket.org/jpoirier/go
Go | 2102 lines | 2072 code | 17 blank | 13 comment | 19 complexity | 55d28a701f19a92b2c5cce567b039047 MD5 | raw file
Possible License(s): BSD-3-Clause

Large files files are truncated, but you can click here to view the full file

  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. package main
  5. import (
  6. "bytes"
  7. "container/heap"
  8. "errors"
  9. "flag"
  10. "fmt"
  11. "go/build"
  12. "io"
  13. "io/ioutil"
  14. "log"
  15. "os"
  16. "os/exec"
  17. "path"
  18. "path/filepath"
  19. "regexp"
  20. "runtime"
  21. "strings"
  22. "sync"
  23. "time"
  24. )
  25. var cmdBuild = &Command{
  26. UsageLine: "build [-o output] [build flags] [packages]",
  27. Short: "compile packages and dependencies",
  28. Long: `
  29. Build compiles the packages named by the import paths,
  30. along with their dependencies, but it does not install the results.
  31. If the arguments are a list of .go files, build treats them as a list
  32. of source files specifying a single package.
  33. When the command line specifies a single main package,
  34. build writes the resulting executable to output.
  35. Otherwise build compiles the packages but discards the results,
  36. serving only as a check that the packages can be built.
  37. The -o flag specifies the output file name. If not specified, the
  38. output file name depends on the arguments and derives from the name
  39. of the package, such as p.a for package p, unless p is 'main'. If
  40. the package is main and file names are provided, the file name
  41. derives from the first file name mentioned, such as f1 for 'go build
  42. f1.go f2.go'; with no files provided ('go build'), the output file
  43. name is the base name of the containing directory.
  44. The build flags are shared by the build, install, run, and test commands:
  45. -a
  46. force rebuilding of packages that are already up-to-date.
  47. -n
  48. print the commands but do not run them.
  49. -p n
  50. the number of builds that can be run in parallel.
  51. The default is the number of CPUs available.
  52. -race
  53. enable data race detection.
  54. Supported only on linux/amd64, darwin/amd64 and windows/amd64.
  55. -v
  56. print the names of packages as they are compiled.
  57. -work
  58. print the name of the temporary work directory and
  59. do not delete it when exiting.
  60. -x
  61. print the commands.
  62. -ccflags 'arg list'
  63. arguments to pass on each 5c, 6c, or 8c compiler invocation.
  64. -compiler name
  65. name of compiler to use, as in runtime.Compiler (gccgo or gc).
  66. -gccgoflags 'arg list'
  67. arguments to pass on each gccgo compiler/linker invocation.
  68. -gcflags 'arg list'
  69. arguments to pass on each 5g, 6g, or 8g compiler invocation.
  70. -installsuffix suffix
  71. a suffix to use in the name of the package installation directory,
  72. in order to keep output separate from default builds.
  73. If using the -race flag, the install suffix is automatically set to race
  74. or, if set explicitly, has _race appended to it.
  75. -ldflags 'flag list'
  76. arguments to pass on each 5l, 6l, or 8l linker invocation.
  77. -tags 'tag list'
  78. a list of build tags to consider satisfied during the build.
  79. See the documentation for the go/build package for
  80. more information about build tags.
  81. The list flags accept a space-separated list of strings. To embed spaces
  82. in an element in the list, surround it with either single or double quotes.
  83. For more about specifying packages, see 'go help packages'.
  84. For more about where packages and binaries are installed,
  85. see 'go help gopath'.
  86. See also: go install, go get, go clean.
  87. `,
  88. }
  89. func init() {
  90. // break init cycle
  91. cmdBuild.Run = runBuild
  92. cmdInstall.Run = runInstall
  93. addBuildFlags(cmdBuild)
  94. addBuildFlags(cmdInstall)
  95. }
  96. // Flags set by multiple commands.
  97. var buildA bool // -a flag
  98. var buildN bool // -n flag
  99. var buildP = runtime.NumCPU() // -p flag
  100. var buildV bool // -v flag
  101. var buildX bool // -x flag
  102. var buildO = cmdBuild.Flag.String("o", "", "output file")
  103. var buildWork bool // -work flag
  104. var buildGcflags []string // -gcflags flag
  105. var buildCcflags []string // -ccflags flag
  106. var buildLdflags []string // -ldflags flag
  107. var buildGccgoflags []string // -gccgoflags flag
  108. var buildRace bool // -race flag
  109. var buildContext = build.Default
  110. var buildToolchain toolchain = noToolchain{}
  111. // buildCompiler implements flag.Var.
  112. // It implements Set by updating both
  113. // buildToolchain and buildContext.Compiler.
  114. type buildCompiler struct{}
  115. func (c buildCompiler) Set(value string) error {
  116. switch value {
  117. case "gc":
  118. buildToolchain = gcToolchain{}
  119. case "gccgo":
  120. buildToolchain = gccgoToolchain{}
  121. default:
  122. return fmt.Errorf("unknown compiler %q", value)
  123. }
  124. buildContext.Compiler = value
  125. return nil
  126. }
  127. func (c buildCompiler) String() string {
  128. return buildContext.Compiler
  129. }
  130. func init() {
  131. switch build.Default.Compiler {
  132. case "gc":
  133. buildToolchain = gcToolchain{}
  134. case "gccgo":
  135. buildToolchain = gccgoToolchain{}
  136. }
  137. }
  138. // addBuildFlags adds the flags common to the build and install commands.
  139. func addBuildFlags(cmd *Command) {
  140. // NOTE: If you add flags here, also add them to testflag.go.
  141. cmd.Flag.BoolVar(&buildA, "a", false, "")
  142. cmd.Flag.BoolVar(&buildN, "n", false, "")
  143. cmd.Flag.IntVar(&buildP, "p", buildP, "")
  144. cmd.Flag.StringVar(&buildContext.InstallSuffix, "installsuffix", "", "")
  145. cmd.Flag.BoolVar(&buildV, "v", false, "")
  146. cmd.Flag.BoolVar(&buildX, "x", false, "")
  147. cmd.Flag.BoolVar(&buildWork, "work", false, "")
  148. cmd.Flag.Var((*stringsFlag)(&buildGcflags), "gcflags", "")
  149. cmd.Flag.Var((*stringsFlag)(&buildCcflags), "ccflags", "")
  150. cmd.Flag.Var((*stringsFlag)(&buildLdflags), "ldflags", "")
  151. cmd.Flag.Var((*stringsFlag)(&buildGccgoflags), "gccgoflags", "")
  152. cmd.Flag.Var((*stringsFlag)(&buildContext.BuildTags), "tags", "")
  153. cmd.Flag.Var(buildCompiler{}, "compiler", "")
  154. cmd.Flag.BoolVar(&buildRace, "race", false, "")
  155. }
  156. func addBuildFlagsNX(cmd *Command) {
  157. cmd.Flag.BoolVar(&buildN, "n", false, "")
  158. cmd.Flag.BoolVar(&buildX, "x", false, "")
  159. }
  160. func isSpaceByte(c byte) bool {
  161. return c == ' ' || c == '\t' || c == '\n' || c == '\r'
  162. }
  163. type stringsFlag []string
  164. func (v *stringsFlag) Set(s string) error {
  165. var err error
  166. *v, err = splitQuotedFields(s)
  167. return err
  168. }
  169. func splitQuotedFields(s string) ([]string, error) {
  170. // Split fields allowing '' or "" around elements.
  171. // Quotes further inside the string do not count.
  172. var f []string
  173. for len(s) > 0 {
  174. for len(s) > 0 && isSpaceByte(s[0]) {
  175. s = s[1:]
  176. }
  177. if len(s) == 0 {
  178. break
  179. }
  180. // Accepted quoted string. No unescaping inside.
  181. if s[0] == '"' || s[0] == '\'' {
  182. quote := s[0]
  183. s = s[1:]
  184. i := 0
  185. for i < len(s) && s[i] != quote {
  186. i++
  187. }
  188. if i >= len(s) {
  189. return nil, fmt.Errorf("unterminated %c string", quote)
  190. }
  191. f = append(f, s[:i])
  192. s = s[i+1:]
  193. continue
  194. }
  195. i := 0
  196. for i < len(s) && !isSpaceByte(s[i]) {
  197. i++
  198. }
  199. f = append(f, s[:i])
  200. s = s[i:]
  201. }
  202. return f, nil
  203. }
  204. func (v *stringsFlag) String() string {
  205. return "<stringsFlag>"
  206. }
  207. func runBuild(cmd *Command, args []string) {
  208. raceInit()
  209. var b builder
  210. b.init()
  211. pkgs := packagesForBuild(args)
  212. if len(pkgs) == 1 && pkgs[0].Name == "main" && *buildO == "" {
  213. _, *buildO = path.Split(pkgs[0].ImportPath)
  214. *buildO += exeSuffix
  215. }
  216. // sanity check some often mis-used options
  217. switch buildContext.Compiler {
  218. case "gccgo":
  219. if len(buildGcflags) != 0 {
  220. fmt.Println("go build: when using gccgo toolchain, please pass compiler flags using -gccgoflags, not -gcflags")
  221. }
  222. if len(buildLdflags) != 0 {
  223. fmt.Println("go build: when using gccgo toolchain, please pass linker flags using -gccgoflags, not -ldflags")
  224. }
  225. case "gc":
  226. if len(buildGccgoflags) != 0 {
  227. fmt.Println("go build: when using gc toolchain, please pass compile flags using -gcflags, and linker flags using -ldflags")
  228. }
  229. }
  230. if *buildO != "" {
  231. if len(pkgs) > 1 {
  232. fatalf("go build: cannot use -o with multiple packages")
  233. }
  234. p := pkgs[0]
  235. p.target = "" // must build - not up to date
  236. a := b.action(modeInstall, modeBuild, p)
  237. a.target = *buildO
  238. b.do(a)
  239. return
  240. }
  241. a := &action{}
  242. for _, p := range packages(args) {
  243. a.deps = append(a.deps, b.action(modeBuild, modeBuild, p))
  244. }
  245. b.do(a)
  246. }
  247. var cmdInstall = &Command{
  248. UsageLine: "install [build flags] [packages]",
  249. Short: "compile and install packages and dependencies",
  250. Long: `
  251. Install compiles and installs the packages named by the import paths,
  252. along with their dependencies.
  253. For more about the build flags, see 'go help build'.
  254. For more about specifying packages, see 'go help packages'.
  255. See also: go build, go get, go clean.
  256. `,
  257. }
  258. func runInstall(cmd *Command, args []string) {
  259. raceInit()
  260. pkgs := packagesForBuild(args)
  261. for _, p := range pkgs {
  262. if p.Target == "" && (!p.Standard || p.ImportPath != "unsafe") {
  263. errorf("go install: no install location for directory %s outside GOPATH", p.Dir)
  264. }
  265. }
  266. exitIfErrors()
  267. var b builder
  268. b.init()
  269. a := &action{}
  270. for _, p := range pkgs {
  271. a.deps = append(a.deps, b.action(modeInstall, modeInstall, p))
  272. }
  273. b.do(a)
  274. }
  275. // Global build parameters (used during package load)
  276. var (
  277. goarch string
  278. goos string
  279. archChar string
  280. exeSuffix string
  281. )
  282. func init() {
  283. goarch = buildContext.GOARCH
  284. goos = buildContext.GOOS
  285. if goos == "windows" {
  286. exeSuffix = ".exe"
  287. }
  288. var err error
  289. archChar, err = build.ArchChar(goarch)
  290. if err != nil {
  291. fatalf("%s", err)
  292. }
  293. }
  294. // A builder holds global state about a build.
  295. // It does not hold per-package state, because we
  296. // build packages in parallel, and the builder is shared.
  297. type builder struct {
  298. work string // the temporary work directory (ends in filepath.Separator)
  299. actionCache map[cacheKey]*action // a cache of already-constructed actions
  300. mkdirCache map[string]bool // a cache of created directories
  301. print func(args ...interface{}) (int, error)
  302. output sync.Mutex
  303. scriptDir string // current directory in printed script
  304. exec sync.Mutex
  305. readySema chan bool
  306. ready actionQueue
  307. }
  308. // An action represents a single action in the action graph.
  309. type action struct {
  310. p *Package // the package this action works on
  311. deps []*action // actions that must happen before this one
  312. triggers []*action // inverse of deps
  313. cgo *action // action for cgo binary if needed
  314. args []string // additional args for runProgram
  315. testOutput *bytes.Buffer // test output buffer
  316. f func(*builder, *action) error // the action itself (nil = no-op)
  317. ignoreFail bool // whether to run f even if dependencies fail
  318. // Generated files, directories.
  319. link bool // target is executable, not just package
  320. pkgdir string // the -I or -L argument to use when importing this package
  321. objdir string // directory for intermediate objects
  322. objpkg string // the intermediate package .a file created during the action
  323. target string // goal of the action: the created package or executable
  324. // Execution state.
  325. pending int // number of deps yet to complete
  326. priority int // relative execution priority
  327. failed bool // whether the action failed
  328. }
  329. // cacheKey is the key for the action cache.
  330. type cacheKey struct {
  331. mode buildMode
  332. p *Package
  333. }
  334. // buildMode specifies the build mode:
  335. // are we just building things or also installing the results?
  336. type buildMode int
  337. const (
  338. modeBuild buildMode = iota
  339. modeInstall
  340. )
  341. var (
  342. goroot = filepath.Clean(runtime.GOROOT())
  343. gobin = os.Getenv("GOBIN")
  344. gorootBin = filepath.Join(goroot, "bin")
  345. gorootSrcPkg = filepath.Join(goroot, "src/pkg")
  346. gorootPkg = filepath.Join(goroot, "pkg")
  347. gorootSrc = filepath.Join(goroot, "src")
  348. )
  349. func (b *builder) init() {
  350. var err error
  351. b.print = func(a ...interface{}) (int, error) {
  352. return fmt.Fprint(os.Stderr, a...)
  353. }
  354. b.actionCache = make(map[cacheKey]*action)
  355. b.mkdirCache = make(map[string]bool)
  356. if buildN {
  357. b.work = "$WORK"
  358. } else {
  359. b.work, err = ioutil.TempDir("", "go-build")
  360. if err != nil {
  361. fatalf("%s", err)
  362. }
  363. if buildX || buildWork {
  364. fmt.Printf("WORK=%s\n", b.work)
  365. }
  366. if !buildWork {
  367. atexit(func() { os.RemoveAll(b.work) })
  368. }
  369. }
  370. }
  371. // goFilesPackage creates a package for building a collection of Go files
  372. // (typically named on the command line). The target is named p.a for
  373. // package p or named after the first Go file for package main.
  374. func goFilesPackage(gofiles []string) *Package {
  375. // TODO: Remove this restriction.
  376. for _, f := range gofiles {
  377. if !strings.HasSuffix(f, ".go") {
  378. fatalf("named files must be .go files")
  379. }
  380. }
  381. var stk importStack
  382. ctxt := buildContext
  383. ctxt.UseAllFiles = true
  384. // Synthesize fake "directory" that only shows the named files,
  385. // to make it look like this is a standard package or
  386. // command directory. So that local imports resolve
  387. // consistently, the files must all be in the same directory.
  388. var dirent []os.FileInfo
  389. var dir string
  390. for _, file := range gofiles {
  391. fi, err := os.Stat(file)
  392. if err != nil {
  393. fatalf("%s", err)
  394. }
  395. if fi.IsDir() {
  396. fatalf("%s is a directory, should be a Go file", file)
  397. }
  398. dir1, _ := filepath.Split(file)
  399. if dir == "" {
  400. dir = dir1
  401. } else if dir != dir1 {
  402. fatalf("named files must all be in one directory; have %s and %s", dir, dir1)
  403. }
  404. dirent = append(dirent, fi)
  405. }
  406. ctxt.ReadDir = func(string) ([]os.FileInfo, error) { return dirent, nil }
  407. if !filepath.IsAbs(dir) {
  408. dir = filepath.Join(cwd, dir)
  409. }
  410. bp, err := ctxt.ImportDir(dir, 0)
  411. pkg := new(Package)
  412. pkg.local = true
  413. pkg.load(&stk, bp, err)
  414. pkg.localPrefix = dirToImportPath(dir)
  415. pkg.ImportPath = "command-line-arguments"
  416. pkg.target = ""
  417. if pkg.Name == "main" {
  418. _, elem := filepath.Split(gofiles[0])
  419. exe := elem[:len(elem)-len(".go")] + exeSuffix
  420. if *buildO == "" {
  421. *buildO = exe
  422. }
  423. if gobin != "" {
  424. pkg.target = filepath.Join(gobin, exe)
  425. }
  426. } else {
  427. if *buildO == "" {
  428. *buildO = pkg.Name + ".a"
  429. }
  430. }
  431. pkg.Target = pkg.target
  432. pkg.Stale = true
  433. computeStale(pkg)
  434. return pkg
  435. }
  436. // action returns the action for applying the given operation (mode) to the package.
  437. // depMode is the action to use when building dependencies.
  438. func (b *builder) action(mode buildMode, depMode buildMode, p *Package) *action {
  439. key := cacheKey{mode, p}
  440. a := b.actionCache[key]
  441. if a != nil {
  442. return a
  443. }
  444. a = &action{p: p, pkgdir: p.build.PkgRoot}
  445. if p.pkgdir != "" { // overrides p.t
  446. a.pkgdir = p.pkgdir
  447. }
  448. b.actionCache[key] = a
  449. for _, p1 := range p.imports {
  450. a.deps = append(a.deps, b.action(depMode, depMode, p1))
  451. }
  452. // If we are not doing a cross-build, then record the binary we'll
  453. // generate for cgo as a dependency of the build of any package
  454. // using cgo, to make sure we do not overwrite the binary while
  455. // a package is using it. If this is a cross-build, then the cgo we
  456. // are writing is not the cgo we need to use.
  457. if goos == runtime.GOOS && goarch == runtime.GOARCH && !buildRace {
  458. if len(p.CgoFiles) > 0 || p.Standard && p.ImportPath == "runtime/cgo" {
  459. var stk importStack
  460. p1 := loadPackage("cmd/cgo", &stk)
  461. if p1.Error != nil {
  462. fatalf("load cmd/cgo: %v", p1.Error)
  463. }
  464. a.cgo = b.action(depMode, depMode, p1)
  465. a.deps = append(a.deps, a.cgo)
  466. }
  467. }
  468. if p.Standard {
  469. switch p.ImportPath {
  470. case "builtin", "unsafe":
  471. // Fake packages - nothing to build.
  472. return a
  473. }
  474. // gccgo standard library is "fake" too.
  475. if _, ok := buildToolchain.(gccgoToolchain); ok {
  476. // the target name is needed for cgo.
  477. a.target = p.target
  478. return a
  479. }
  480. }
  481. if !p.Stale && p.target != "" {
  482. // p.Stale==false implies that p.target is up-to-date.
  483. // Record target name for use by actions depending on this one.
  484. a.target = p.target
  485. return a
  486. }
  487. if p.local && p.target == "" {
  488. // Imported via local path. No permanent target.
  489. mode = modeBuild
  490. }
  491. a.objdir = filepath.Join(b.work, a.p.ImportPath, "_obj") + string(filepath.Separator)
  492. a.objpkg = buildToolchain.pkgpath(b.work, a.p)
  493. a.link = p.Name == "main"
  494. switch mode {
  495. case modeInstall:
  496. a.f = (*builder).install
  497. a.deps = []*action{b.action(modeBuild, depMode, p)}
  498. a.target = a.p.target
  499. case modeBuild:
  500. a.f = (*builder).build
  501. a.target = a.objpkg
  502. if a.link {
  503. // An executable file. (This is the name of a temporary file.)
  504. // Because we run the temporary file in 'go run' and 'go test',
  505. // the name will show up in ps listings. If the caller has specified
  506. // a name, use that instead of a.out. The binary is generated
  507. // in an otherwise empty subdirectory named exe to avoid
  508. // naming conflicts. The only possible conflict is if we were
  509. // to create a top-level package named exe.
  510. name := "a.out"
  511. if p.exeName != "" {
  512. name = p.exeName
  513. }
  514. a.target = a.objdir + filepath.Join("exe", name) + exeSuffix
  515. }
  516. }
  517. return a
  518. }
  519. // actionList returns the list of actions in the dag rooted at root
  520. // as visited in a depth-first post-order traversal.
  521. func actionList(root *action) []*action {
  522. seen := map[*action]bool{}
  523. all := []*action{}
  524. var walk func(*action)
  525. walk = func(a *action) {
  526. if seen[a] {
  527. return
  528. }
  529. seen[a] = true
  530. for _, a1 := range a.deps {
  531. walk(a1)
  532. }
  533. all = append(all, a)
  534. }
  535. walk(root)
  536. return all
  537. }
  538. // do runs the action graph rooted at root.
  539. func (b *builder) do(root *action) {
  540. // Build list of all actions, assigning depth-first post-order priority.
  541. // The original implementation here was a true queue
  542. // (using a channel) but it had the effect of getting
  543. // distracted by low-level leaf actions to the detriment
  544. // of completing higher-level actions. The order of
  545. // work does not matter much to overall execution time,
  546. // but when running "go test std" it is nice to see each test
  547. // results as soon as possible. The priorities assigned
  548. // ensure that, all else being equal, the execution prefers
  549. // to do what it would have done first in a simple depth-first
  550. // dependency order traversal.
  551. all := actionList(root)
  552. for i, a := range all {
  553. a.priority = i
  554. }
  555. b.readySema = make(chan bool, len(all))
  556. // Initialize per-action execution state.
  557. for _, a := range all {
  558. for _, a1 := range a.deps {
  559. a1.triggers = append(a1.triggers, a)
  560. }
  561. a.pending = len(a.deps)
  562. if a.pending == 0 {
  563. b.ready.push(a)
  564. b.readySema <- true
  565. }
  566. }
  567. // Handle runs a single action and takes care of triggering
  568. // any actions that are runnable as a result.
  569. handle := func(a *action) {
  570. var err error
  571. if a.f != nil && (!a.failed || a.ignoreFail) {
  572. err = a.f(b, a)
  573. }
  574. // The actions run in parallel but all the updates to the
  575. // shared work state are serialized through b.exec.
  576. b.exec.Lock()
  577. defer b.exec.Unlock()
  578. if err != nil {
  579. if err == errPrintedOutput {
  580. setExitStatus(2)
  581. } else {
  582. errorf("%s", err)
  583. }
  584. a.failed = true
  585. }
  586. for _, a0 := range a.triggers {
  587. if a.failed {
  588. a0.failed = true
  589. }
  590. if a0.pending--; a0.pending == 0 {
  591. b.ready.push(a0)
  592. b.readySema <- true
  593. }
  594. }
  595. if a == root {
  596. close(b.readySema)
  597. }
  598. }
  599. var wg sync.WaitGroup
  600. // Kick off goroutines according to parallelism.
  601. // If we are using the -n flag (just printing commands)
  602. // drop the parallelism to 1, both to make the output
  603. // deterministic and because there is no real work anyway.
  604. par := buildP
  605. if buildN {
  606. par = 1
  607. }
  608. for i := 0; i < par; i++ {
  609. wg.Add(1)
  610. go func() {
  611. defer wg.Done()
  612. for {
  613. select {
  614. case _, ok := <-b.readySema:
  615. if !ok {
  616. return
  617. }
  618. // Receiving a value from b.readySema entitles
  619. // us to take from the ready queue.
  620. b.exec.Lock()
  621. a := b.ready.pop()
  622. b.exec.Unlock()
  623. handle(a)
  624. case <-interrupted:
  625. setExitStatus(1)
  626. return
  627. }
  628. }
  629. }()
  630. }
  631. wg.Wait()
  632. }
  633. // hasString reports whether s appears in the list of strings.
  634. func hasString(strings []string, s string) bool {
  635. for _, t := range strings {
  636. if s == t {
  637. return true
  638. }
  639. }
  640. return false
  641. }
  642. // build is the action for building a single package or command.
  643. func (b *builder) build(a *action) (err error) {
  644. defer func() {
  645. if err != nil && err != errPrintedOutput {
  646. err = fmt.Errorf("go build %s: %v", a.p.ImportPath, err)
  647. }
  648. }()
  649. if buildN {
  650. // In -n mode, print a banner between packages.
  651. // The banner is five lines so that when changes to
  652. // different sections of the bootstrap script have to
  653. // be merged, the banners give patch something
  654. // to use to find its context.
  655. fmt.Printf("\n#\n# %s\n#\n\n", a.p.ImportPath)
  656. }
  657. if buildV {
  658. fmt.Fprintf(os.Stderr, "%s\n", a.p.ImportPath)
  659. }
  660. if a.p.Standard && a.p.ImportPath == "runtime" && buildContext.Compiler == "gc" &&
  661. !hasString(a.p.HFiles, "zasm_"+buildContext.GOOS+"_"+buildContext.GOARCH+".h") {
  662. return fmt.Errorf("%s/%s must be bootstrapped using make.bash", buildContext.GOOS, buildContext.GOARCH)
  663. }
  664. // Make build directory.
  665. obj := a.objdir
  666. if err := b.mkdir(obj); err != nil {
  667. return err
  668. }
  669. // make target directory
  670. dir, _ := filepath.Split(a.target)
  671. if dir != "" {
  672. if err := b.mkdir(dir); err != nil {
  673. return err
  674. }
  675. }
  676. var gofiles, cfiles, sfiles, objects, cgoObjects []string
  677. gofiles = append(gofiles, a.p.GoFiles...)
  678. cfiles = append(cfiles, a.p.CFiles...)
  679. sfiles = append(sfiles, a.p.SFiles...)
  680. // Run cgo.
  681. if len(a.p.CgoFiles) > 0 {
  682. // In a package using cgo, cgo compiles the C and assembly files with gcc.
  683. // There is one exception: runtime/cgo's job is to bridge the
  684. // cgo and non-cgo worlds, so it necessarily has files in both.
  685. // In that case gcc only gets the gcc_* files.
  686. var gccfiles []string
  687. if a.p.Standard && a.p.ImportPath == "runtime/cgo" {
  688. filter := func(files, nongcc, gcc []string) ([]string, []string) {
  689. for _, f := range files {
  690. if strings.HasPrefix(f, "gcc_") {
  691. gcc = append(gcc, f)
  692. } else {
  693. nongcc = append(nongcc, f)
  694. }
  695. }
  696. return nongcc, gcc
  697. }
  698. cfiles, gccfiles = filter(cfiles, cfiles[:0], gccfiles)
  699. sfiles, gccfiles = filter(sfiles, sfiles[:0], gccfiles)
  700. } else {
  701. gccfiles = append(cfiles, sfiles...)
  702. cfiles = nil
  703. sfiles = nil
  704. }
  705. cgoExe := tool("cgo")
  706. if a.cgo != nil && a.cgo.target != "" {
  707. cgoExe = a.cgo.target
  708. }
  709. outGo, outObj, err := b.cgo(a.p, cgoExe, obj, gccfiles)
  710. if err != nil {
  711. return err
  712. }
  713. cgoObjects = append(cgoObjects, outObj...)
  714. gofiles = append(gofiles, outGo...)
  715. }
  716. // Run SWIG.
  717. if a.p.usesSwig() {
  718. // In a package using SWIG, any .c or .s files are
  719. // compiled with gcc.
  720. gccfiles := append(cfiles, sfiles...)
  721. cfiles = nil
  722. sfiles = nil
  723. outGo, outObj, err := b.swig(a.p, obj, gccfiles)
  724. if err != nil {
  725. return err
  726. }
  727. cgoObjects = append(cgoObjects, outObj...)
  728. gofiles = append(gofiles, outGo...)
  729. }
  730. // Prepare Go import path list.
  731. inc := b.includeArgs("-I", a.deps)
  732. // Compile Go.
  733. if len(gofiles) > 0 {
  734. ofile, out, err := buildToolchain.gc(b, a.p, obj, inc, gofiles)
  735. if len(out) > 0 {
  736. b.showOutput(a.p.Dir, a.p.ImportPath, b.processOutput(out))
  737. if err != nil {
  738. return errPrintedOutput
  739. }
  740. }
  741. if err != nil {
  742. return err
  743. }
  744. objects = append(objects, ofile)
  745. }
  746. // Copy .h files named for goos or goarch or goos_goarch
  747. // to names using GOOS and GOARCH.
  748. // For example, defs_linux_amd64.h becomes defs_GOOS_GOARCH.h.
  749. _goos_goarch := "_" + goos + "_" + goarch + ".h"
  750. _goos := "_" + goos + ".h"
  751. _goarch := "_" + goarch + ".h"
  752. for _, file := range a.p.HFiles {
  753. switch {
  754. case strings.HasSuffix(file, _goos_goarch):
  755. targ := file[:len(file)-len(_goos_goarch)] + "_GOOS_GOARCH.h"
  756. if err := b.copyFile(a, obj+targ, filepath.Join(a.p.Dir, file), 0666); err != nil {
  757. return err
  758. }
  759. case strings.HasSuffix(file, _goarch):
  760. targ := file[:len(file)-len(_goarch)] + "_GOARCH.h"
  761. if err := b.copyFile(a, obj+targ, filepath.Join(a.p.Dir, file), 0666); err != nil {
  762. return err
  763. }
  764. case strings.HasSuffix(file, _goos):
  765. targ := file[:len(file)-len(_goos)] + "_GOOS.h"
  766. if err := b.copyFile(a, obj+targ, filepath.Join(a.p.Dir, file), 0666); err != nil {
  767. return err
  768. }
  769. }
  770. }
  771. objExt := archChar
  772. if _, ok := buildToolchain.(gccgoToolchain); ok {
  773. objExt = "o"
  774. }
  775. for _, file := range cfiles {
  776. out := file[:len(file)-len(".c")] + "." + objExt
  777. if err := buildToolchain.cc(b, a.p, obj, obj+out, file); err != nil {
  778. return err
  779. }
  780. objects = append(objects, out)
  781. }
  782. // Assemble .s files.
  783. for _, file := range sfiles {
  784. out := file[:len(file)-len(".s")] + "." + objExt
  785. if err := buildToolchain.asm(b, a.p, obj, obj+out, file); err != nil {
  786. return err
  787. }
  788. objects = append(objects, out)
  789. }
  790. // NOTE(rsc): On Windows, it is critically important that the
  791. // gcc-compiled objects (cgoObjects) be listed after the ordinary
  792. // objects in the archive. I do not know why this is.
  793. // http://golang.org/issue/2601
  794. objects = append(objects, cgoObjects...)
  795. // Add system object files.
  796. for _, syso := range a.p.SysoFiles {
  797. objects = append(objects, filepath.Join(a.p.Dir, syso))
  798. }
  799. // Pack into archive in obj directory
  800. if err := buildToolchain.pack(b, a.p, obj, a.objpkg, objects); err != nil {
  801. return err
  802. }
  803. // Link if needed.
  804. if a.link {
  805. // The compiler only cares about direct imports, but the
  806. // linker needs the whole dependency tree.
  807. all := actionList(a)
  808. all = all[:len(all)-1] // drop a
  809. if err := buildToolchain.ld(b, a.p, a.target, all, a.objpkg, objects); err != nil {
  810. return err
  811. }
  812. }
  813. return nil
  814. }
  815. // install is the action for installing a single package or executable.
  816. func (b *builder) install(a *action) (err error) {
  817. defer func() {
  818. if err != nil && err != errPrintedOutput {
  819. err = fmt.Errorf("go install %s: %v", a.p.ImportPath, err)
  820. }
  821. }()
  822. a1 := a.deps[0]
  823. perm := os.FileMode(0666)
  824. if a1.link {
  825. perm = 0777
  826. }
  827. // make target directory
  828. dir, _ := filepath.Split(a.target)
  829. if dir != "" {
  830. if err := b.mkdir(dir); err != nil {
  831. return err
  832. }
  833. }
  834. // remove object dir to keep the amount of
  835. // garbage down in a large build. On an operating system
  836. // with aggressive buffering, cleaning incrementally like
  837. // this keeps the intermediate objects from hitting the disk.
  838. if !buildWork {
  839. defer os.RemoveAll(a1.objdir)
  840. defer os.Remove(a1.target)
  841. }
  842. if a.p.usesSwig() {
  843. for _, f := range stringList(a.p.SwigFiles, a.p.SwigCXXFiles) {
  844. dir = a.p.swigDir(&buildContext)
  845. if err := b.mkdir(dir); err != nil {
  846. return err
  847. }
  848. soname := a.p.swigSoname(f)
  849. target := filepath.Join(dir, soname)
  850. if err = b.copyFile(a, target, soname, perm); err != nil {
  851. return err
  852. }
  853. }
  854. }
  855. return b.copyFile(a, a.target, a1.target, perm)
  856. }
  857. // includeArgs returns the -I or -L directory list for access
  858. // to the results of the list of actions.
  859. func (b *builder) includeArgs(flag string, all []*action) []string {
  860. inc := []string{}
  861. incMap := map[string]bool{
  862. b.work: true, // handled later
  863. gorootPkg: true,
  864. "": true, // ignore empty strings
  865. }
  866. // Look in the temporary space for results of test-specific actions.
  867. // This is the $WORK/my/package/_test directory for the
  868. // package being built, so there are few of these.
  869. for _, a1 := range all {
  870. if dir := a1.pkgdir; dir != a1.p.build.PkgRoot && !incMap[dir] {
  871. incMap[dir] = true
  872. inc = append(inc, flag, dir)
  873. }
  874. }
  875. // Also look in $WORK for any non-test packages that have
  876. // been built but not installed.
  877. inc = append(inc, flag, b.work)
  878. // Finally, look in the installed package directories for each action.
  879. for _, a1 := range all {
  880. if dir := a1.pkgdir; dir == a1.p.build.PkgRoot && !incMap[dir] {
  881. incMap[dir] = true
  882. if _, ok := buildToolchain.(gccgoToolchain); ok {
  883. dir = filepath.Join(dir, "gccgo_"+goos+"_"+goarch)
  884. } else {
  885. dir = filepath.Join(dir, goos+"_"+goarch)
  886. if buildRace {
  887. dir += "_race"
  888. }
  889. }
  890. inc = append(inc, flag, dir)
  891. }
  892. }
  893. return inc
  894. }
  895. // copyFile is like 'cp src dst'.
  896. func (b *builder) copyFile(a *action, dst, src string, perm os.FileMode) error {
  897. if buildN || buildX {
  898. b.showcmd("", "cp %s %s", src, dst)
  899. if buildN {
  900. return nil
  901. }
  902. }
  903. sf, err := os.Open(src)
  904. if err != nil {
  905. return err
  906. }
  907. defer sf.Close()
  908. // Be careful about removing/overwriting dst.
  909. // Do not remove/overwrite if dst exists and is a directory
  910. // or a non-object file.
  911. if fi, err := os.Stat(dst); err == nil {
  912. if fi.IsDir() {
  913. return fmt.Errorf("build output %q already exists and is a directory", dst)
  914. }
  915. if !isObject(dst) {
  916. return fmt.Errorf("build output %q already exists and is not an object file", dst)
  917. }
  918. }
  919. // On Windows, remove lingering ~ file from last attempt.
  920. if toolIsWindows {
  921. if _, err := os.Stat(dst + "~"); err == nil {
  922. os.Remove(dst + "~")
  923. }
  924. }
  925. os.Remove(dst)
  926. df, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm)
  927. if err != nil && toolIsWindows {
  928. // Windows does not allow deletion of a binary file
  929. // while it is executing. Try to move it out of the way.
  930. // If the remove fails, which is likely, we'll try again the
  931. // next time we do an install of this binary.
  932. if err := os.Rename(dst, dst+"~"); err == nil {
  933. os.Remove(dst + "~")
  934. }
  935. df, err = os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm)
  936. }
  937. if err != nil {
  938. return err
  939. }
  940. _, err = io.Copy(df, sf)
  941. df.Close()
  942. if err != nil {
  943. os.Remove(dst)
  944. return fmt.Errorf("copying %s to %s: %v", src, dst, err)
  945. }
  946. return nil
  947. }
  948. var objectMagic = [][]byte{
  949. {'!', '<', 'a', 'r', 'c', 'h', '>', '\n'}, // Package archive
  950. {'\x7F', 'E', 'L', 'F'}, // ELF
  951. {0xFE, 0xED, 0xFA, 0xCE}, // Mach-O big-endian 32-bit
  952. {0xFE, 0xED, 0xFA, 0xCF}, // Mach-O big-endian 64-bit
  953. {0xCE, 0xFA, 0xED, 0xFE}, // Mach-O little-endian 32-bit
  954. {0xCF, 0xFA, 0xED, 0xFE}, // Mach-O little-endian 64-bit
  955. {0x4d, 0x5a, 0x90, 0x00, 0x03, 0x00, 0x04, 0x00}, // PE (Windows) as generated by 6l/8l
  956. {0x00, 0x00, 0x01, 0xEB}, // Plan 9 i386
  957. {0x00, 0x00, 0x8a, 0x97}, // Plan 9 amd64
  958. }
  959. func isObject(s string) bool {
  960. f, err := os.Open(s)
  961. if err != nil {
  962. return false
  963. }
  964. defer f.Close()
  965. buf := make([]byte, 64)
  966. io.ReadFull(f, buf)
  967. for _, magic := range objectMagic {
  968. if bytes.HasPrefix(buf, magic) {
  969. return true
  970. }
  971. }
  972. return false
  973. }
  974. // fmtcmd formats a command in the manner of fmt.Sprintf but also:
  975. //
  976. // If dir is non-empty and the script is not in dir right now,
  977. // fmtcmd inserts "cd dir\n" before the command.
  978. //
  979. // fmtcmd replaces the value of b.work with $WORK.
  980. // fmtcmd replaces the value of goroot with $GOROOT.
  981. // fmtcmd replaces the value of b.gobin with $GOBIN.
  982. //
  983. // fmtcmd replaces the name of the current directory with dot (.)
  984. // but only when it is at the beginning of a space-separated token.
  985. //
  986. func (b *builder) fmtcmd(dir string, format string, args ...interface{}) string {
  987. cmd := fmt.Sprintf(format, args...)
  988. if dir != "" && dir != "/" {
  989. cmd = strings.Replace(" "+cmd, " "+dir, " .", -1)[1:]
  990. if b.scriptDir != dir {
  991. b.scriptDir = dir
  992. cmd = "cd " + dir + "\n" + cmd
  993. }
  994. }
  995. if b.work != "" {
  996. cmd = strings.Replace(cmd, b.work, "$WORK", -1)
  997. }
  998. return cmd
  999. }
  1000. // showcmd prints the given command to standard output
  1001. // for the implementation of -n or -x.
  1002. func (b *builder) showcmd(dir string, format string, args ...interface{}) {
  1003. b.output.Lock()
  1004. defer b.output.Unlock()
  1005. b.print(b.fmtcmd(dir, format, args...) + "\n")
  1006. }
  1007. // showOutput prints "# desc" followed by the given output.
  1008. // The output is expected to contain references to 'dir', usually
  1009. // the source directory for the package that has failed to build.
  1010. // showOutput rewrites mentions of dir with a relative path to dir
  1011. // when the relative path is shorter. This is usually more pleasant.
  1012. // For example, if fmt doesn't compile and we are in src/pkg/html,
  1013. // the output is
  1014. //
  1015. // $ go build
  1016. // # fmt
  1017. // ../fmt/print.go:1090: undefined: asdf
  1018. // $
  1019. //
  1020. // instead of
  1021. //
  1022. // $ go build
  1023. // # fmt
  1024. // /usr/gopher/go/src/pkg/fmt/print.go:1090: undefined: asdf
  1025. // $
  1026. //
  1027. // showOutput also replaces references to the work directory with $WORK.
  1028. //
  1029. func (b *builder) showOutput(dir, desc, out string) {
  1030. prefix := "# " + desc
  1031. suffix := "\n" + out
  1032. if reldir := shortPath(dir); reldir != dir {
  1033. suffix = strings.Replace(suffix, " "+dir, " "+reldir, -1)
  1034. suffix = strings.Replace(suffix, "\n"+dir, "\n"+reldir, -1)
  1035. }
  1036. suffix = strings.Replace(suffix, " "+b.work, " $WORK", -1)
  1037. b.output.Lock()
  1038. defer b.output.Unlock()
  1039. b.print(prefix, suffix)
  1040. }
  1041. // shortPath returns an absolute or relative name for path, whatever is shorter.
  1042. func shortPath(path string) string {
  1043. if rel, err := filepath.Rel(cwd, path); err == nil && len(rel) < len(path) {
  1044. return rel
  1045. }
  1046. return path
  1047. }
  1048. // relPaths returns a copy of paths with absolute paths
  1049. // made relative to the current directory if they would be shorter.
  1050. func relPaths(paths []string) []string {
  1051. var out []string
  1052. pwd, _ := os.Getwd()
  1053. for _, p := range paths {
  1054. rel, err := filepath.Rel(pwd, p)
  1055. if err == nil && len(rel) < len(p) {
  1056. p = rel
  1057. }
  1058. out = append(out, p)
  1059. }
  1060. return out
  1061. }
  1062. // errPrintedOutput is a special error indicating that a command failed
  1063. // but that it generated output as well, and that output has already
  1064. // been printed, so there's no point showing 'exit status 1' or whatever
  1065. // the wait status was. The main executor, builder.do, knows not to
  1066. // print this error.
  1067. var errPrintedOutput = errors.New("already printed output - no need to show error")
  1068. var cgoLine = regexp.MustCompile(`\[[^\[\]]+\.cgo1\.go:[0-9]+\]`)
  1069. // run runs the command given by cmdline in the directory dir.
  1070. // If the command fails, run prints information about the failure
  1071. // and returns a non-nil error.
  1072. func (b *builder) run(dir string, desc string, cmdargs ...interface{}) error {
  1073. out, err := b.runOut(dir, desc, cmdargs...)
  1074. if len(out) > 0 {
  1075. if desc == "" {
  1076. desc = b.fmtcmd(dir, "%s", strings.Join(stringList(cmdargs...), " "))
  1077. }
  1078. b.showOutput(dir, desc, b.processOutput(out))
  1079. if err != nil {
  1080. err = errPrintedOutput
  1081. }
  1082. }
  1083. return err
  1084. }
  1085. // processOutput prepares the output of runOut to be output to the console.
  1086. func (b *builder) processOutput(out []byte) string {
  1087. if out[len(out)-1] != '\n' {
  1088. out = append(out, '\n')
  1089. }
  1090. messages := string(out)
  1091. // Fix up output referring to cgo-generated code to be more readable.
  1092. // Replace x.go:19[/tmp/.../x.cgo1.go:18] with x.go:19.
  1093. // Replace _Ctype_foo with C.foo.
  1094. // If we're using -x, assume we're debugging and want the full dump, so disable the rewrite.
  1095. if !buildX && cgoLine.MatchString(messages) {
  1096. messages = cgoLine.ReplaceAllString(messages, "")
  1097. messages = strings.Replace(messages, "type _Ctype_", "type C.", -1)
  1098. }
  1099. return messages
  1100. }
  1101. // runOut runs the command given by cmdline in the directory dir.
  1102. // It returns the command output and any errors that occurred.
  1103. func (b *builder) runOut(dir string, desc string, cmdargs ...interface{}) ([]byte, error) {
  1104. cmdline := stringList(cmdargs...)
  1105. if buildN || buildX {
  1106. b.showcmd(dir, "%s", strings.Join(cmdline, " "))
  1107. if buildN {
  1108. return nil, nil
  1109. }
  1110. }
  1111. nbusy := 0
  1112. for {
  1113. var buf bytes.Buffer
  1114. cmd := exec.Command(cmdline[0], cmdline[1:]...)
  1115. cmd.Stdout = &buf
  1116. cmd.Stderr = &buf
  1117. cmd.Dir = dir
  1118. cmd.Env = envForDir(cmd.Dir)
  1119. err := cmd.Run()
  1120. // cmd.Run will fail on Unix if some other process has the binary
  1121. // we want to run open for writing. This can happen here because
  1122. // we build and install the cgo command and then run it.
  1123. // If another command was kicked off while we were writing the
  1124. // cgo binary, the child process for that command may be holding
  1125. // a reference to the fd, keeping us from running exec.
  1126. //
  1127. // But, you might reasonably wonder, how can this happen?
  1128. // The cgo fd, like all our fds, is close-on-exec, so that we need
  1129. // not worry about other processes inheriting the fd accidentally.
  1130. // The answer is that running a command is fork and exec.
  1131. // A child forked while the cgo fd is open inherits that fd.
  1132. // Until the child has called exec, it holds the fd open and the
  1133. // kernel will not let us run cgo. Even if the child were to close
  1134. // the fd explicitly, it would still be open from the time of the fork
  1135. // until the time of the explicit close, and the race would remain.
  1136. //
  1137. // On Unix systems, this results in ETXTBSY, which formats
  1138. // as "text file busy". Rather than hard-code specific error cases,
  1139. // we just look for that string. If this happens, sleep a little
  1140. // and try again. We let this happen three times, with increasing
  1141. // sleep lengths: 100+200+400 ms = 0.7 seconds.
  1142. //
  1143. // An alternate solution might be to split the cmd.Run into
  1144. // separate cmd.Start and cmd.Wait, and then use an RWLock
  1145. // to make sure that copyFile only executes when no cmd.Start
  1146. // call is in progress. However, cmd.Start (really syscall.forkExec)
  1147. // only guarantees that when it returns, the exec is committed to
  1148. // happen and succeed. It uses a close-on-exec file descriptor
  1149. // itself to determine this, so we know that when cmd.Start returns,
  1150. // at least one close-on-exec file descriptor has been closed.
  1151. // However, we cannot be sure that all of them have been closed,
  1152. // so the program might still encounter ETXTBSY even with such
  1153. // an RWLock. The race window would be smaller, perhaps, but not
  1154. // guaranteed to be gone.
  1155. //
  1156. // Sleeping when we observe the race seems to be the most reliable
  1157. // option we have.
  1158. //
  1159. // http://golang.org/issue/3001
  1160. //
  1161. if err != nil && nbusy < 3 && strings.Contains(err.Error(), "text file busy") {
  1162. time.Sleep(100 * time.Millisecond << uint(nbusy))
  1163. nbusy++
  1164. continue
  1165. }
  1166. return buf.Bytes(), err
  1167. }
  1168. }
  1169. // mkdir makes the named directory.
  1170. func (b *builder) mkdir(dir string) error {
  1171. b.exec.Lock()
  1172. defer b.exec.Unlock()
  1173. // We can be a little aggressive about being
  1174. // sure directories exist. Skip repeated calls.
  1175. if b.mkdirCache[dir] {
  1176. return nil
  1177. }
  1178. b.mkdirCache[dir] = true
  1179. if buildN || buildX {
  1180. b.showcmd("", "mkdir -p %s", dir)
  1181. if buildN {
  1182. return nil
  1183. }
  1184. }
  1185. if err := os.MkdirAll(dir, 0777); err != nil {
  1186. return err
  1187. }
  1188. return nil
  1189. }
  1190. // mkAbs returns an absolute path corresponding to
  1191. // evaluating f in the directory dir.
  1192. // We always pass absolute paths of source files so that
  1193. // the error messages will include the full path to a file
  1194. // in need of attention.
  1195. func mkAbs(dir, f string) string {
  1196. // Leave absolute paths alone.
  1197. // Also, during -n mode we use the pseudo-directory $WORK
  1198. // instead of creating an actual work directory that won't be used.
  1199. // Leave paths beginning with $WORK alone too.
  1200. if filepath.IsAbs(f) || strings.HasPrefix(f, "$WORK") {
  1201. return f
  1202. }
  1203. return filepath.Join(dir, f)
  1204. }
  1205. type toolchain interface {
  1206. // gc runs the compiler in a specific directory on a set of files
  1207. // and returns the name of the generated output file.
  1208. // The compiler runs in the directory dir.
  1209. gc(b *builder, p *Package, obj string, importArgs []string, gofiles []string) (ofile string, out []byte, err error)
  1210. // cc runs the toolchain's C compiler in a directory on a C file
  1211. // to produce an output file.
  1212. cc(b *builder, p *Package, objdir, ofile, cfile string) error
  1213. // asm runs the assembler in a specific directory on a specific file
  1214. // to generate the named output file.
  1215. asm(b *builder, p *Package, obj, ofile, sfile string) error
  1216. // pkgpath builds an appropriate path for a temporary package file.
  1217. pkgpath(basedir string, p *Package) string
  1218. // pack runs the archive packer in a specific directory to create
  1219. // an archive from a set of object files.
  1220. // typically it is run in the object directory.
  1221. pack(b *builder, p *Package, objDir, afile string, ofiles []string) error
  1222. // ld runs the linker to create a package starting at mainpkg.
  1223. ld(b *builder, p *Package, out string, allactions []*action, mainpkg string, ofiles []string) error
  1224. compiler() string
  1225. linker() string
  1226. }
  1227. type noToolchain struct{}
  1228. func noCompiler() error {
  1229. log.Fatalf("unknown compiler %q", buildContext.Compiler)
  1230. return nil
  1231. }
  1232. func (noToolchain) compiler() string {
  1233. noCompiler()
  1234. return ""
  1235. }
  1236. func (noToolchain) linker() string {
  1237. noCompiler()
  1238. return ""
  1239. }
  1240. func (noToolchain) gc(b *builder, p *Package, obj string, importArgs []string, gofiles []string) (ofile string, out []byte, err error) {
  1241. return "", nil, noCompiler()
  1242. }
  1243. func (noToolchain) asm(b *builder, p *Package, obj, ofile, sfile string) error {
  1244. return noCompiler()
  1245. }
  1246. func (noToolchain) pkgpath(basedir string, p *Package) string {
  1247. noCompiler()
  1248. return ""
  1249. }
  1250. func (noToolchain) pack(b *builder, p *Package, objDir, afile string, ofiles []string) error {
  1251. return noCompiler()
  1252. }
  1253. func (noToolchain) ld(b *builder, p *Package, out string, allactions []*action, mainpkg string, ofiles []string) error {
  1254. return noCompiler()
  1255. }
  1256. func (noToolchain) cc(b *builder, p *Package, objdir, ofile, cfile string) error {
  1257. return noCompiler()
  1258. }
  1259. // The Go toolchain.
  1260. type gcToolchain struct{}
  1261. func (gcToolchain) compiler() string {
  1262. return tool(archChar + "g")
  1263. }
  1264. func (gcToolchain) linker() string {
  1265. return tool(archChar + "l")
  1266. }
  1267. func (gcToolchain) gc(b *builder, p *Package, obj string, importArgs []string, gofiles []string) (ofile string, output []byte, err error) {
  1268. out := "_go_." + archChar
  1269. ofile = obj + out
  1270. gcargs := []string{"-p", p.ImportPath}
  1271. if p.Standard && p.ImportPath == "runtime" {
  1272. // runtime compiles with a special 6g flag to emit
  1273. // additional reflect type data.
  1274. gcargs = append(gcargs, "-+")
  1275. }
  1276. // If we're giving the compiler the entire package (no C etc files), tell it that,
  1277. // so that it can give good error messages about forward declarations.
  1278. // Exceptions: a few standard packages have forward declarations for
  1279. // pieces supplied behind-the-scenes by package runtime.
  1280. extFiles := len(p.CgoFiles) + len(p.CFiles) + len(p.SFiles) + len(p.SysoFiles) + len(p.SwigFiles) + len(p.SwigCXXFiles)
  1281. if p.Standard {
  1282. switch p.ImportPath {
  1283. case "os", "runtime/pprof", "sync", "time":
  1284. extFiles++
  1285. }
  1286. }
  1287. if extFiles == 0 {
  1288. gcargs = append(gcargs, "-complete")
  1289. }
  1290. args := stringList(tool(archChar+"g"), "-o", ofile, buildGcflags, gcargs, "-D", p.localPrefix, importArgs)
  1291. for _, f := range gofiles {
  1292. args = append(args, mkAbs(p.Dir, f))
  1293. }
  1294. output, err = b.runOut(p.Dir, p.ImportPath, args)
  1295. return ofile, output, err
  1296. }
  1297. func (gcToolchain) asm(b *builder, p *Package, obj, ofile, sfile string) error {
  1298. sfile = mkAbs(p.Dir, sfile)
  1299. return b.run(p.Dir, p.ImportPath, tool(archChar+"a"), "-I", obj, "-o", ofile, "-D", "GOOS_"+goos, "-D", "GOARCH_"+goarch, sfile)
  1300. }
  1301. func (gcToolchain) pkgpath(basedir string, p *Package) string {
  1302. end := filepath.FromSlash(p.ImportPath + ".a")
  1303. return filepath.Join(basedir, end)
  1304. }
  1305. func (gcToolchain) pack(b *builder, p *Package, objDir, afile string, ofiles []string) error {
  1306. var absOfiles []string
  1307. for _, f := range ofiles {
  1308. absOfiles = append(absOfiles, mkAbs(objDir, f))
  1309. }
  1310. return b.run(p.Dir, p.ImportPath, tool("pack"), "grcP", b.work, mkAbs(objDir, afile), absOfiles)
  1311. }
  1312. func (gcToolchain) ld(b *builder, p *Package, out string, allactions []*action, mainpkg string, ofiles []string) error {
  1313. importArgs := b.includeArgs("-L", allactions)
  1314. swigDirs := make(map[string]bool)
  1315. swigArg := []string{}
  1316. for _, a := range allactions {
  1317. if a.p != nil && a.p.usesSwig() {
  1318. sd := a.p.swigDir(&buildContext)
  1319. if len(swigArg) == 0 {
  1320. swigArg = []string{"-r", sd}
  1321. } else if !swigDirs[sd] {
  1322. swigArg[1] += ":"
  1323. swigArg[1] += sd
  1324. }
  1325. swigDirs[sd] = true
  1326. }
  1327. }
  1328. return b.run(".", p.ImportPath, tool(archChar+"l"), "-o", out, importArgs, swigArg, buildLdflags, mainpkg)
  1329. }
  1330. func (gcToolchain) cc(b *builder, p *Package, objdir, ofile, cfile string) error {
  1331. inc := filepath.Join(goroot, "pkg", fmt.Sprintf("%s_%s", goos, goarch))
  1332. cfile = mkAbs(p.Dir, cfile)
  1333. args := stringList(tool(archChar+"c"), "-F", "-V", "-w", "-I", objdir, "-I", inc, "-o", ofile, buildCcflags, "-D", "GOOS_"+goos, "-D", "GOARCH_"+goarch, cfile)
  1334. return b.run(p.Dir, p.ImportPath, args)
  1335. }
  1336. // The Gccgo toolchain.
  1337. type gccgoToolchain struct{}
  1338. var gccgoBin, _ = exec.LookPath("gccgo")
  1339. func (gccgoToolchain) compiler() string {
  1340. return gccgoBin
  1341. }
  1342. func (gccgoToolchain) linker() string {
  1343. return gccgoBin
  1344. }
  1345. func (gccgoToolchain) gc(b *builder, p *Package, obj string, importArgs []string, gofiles []string) (ofile string, output []byte, err error) {
  1346. out := p.Name + ".o"
  1347. ofile = obj + out
  1348. gcargs := []string{"-g"}
  1349. gcargs = append(gcargs, b.gccArchArgs()...)
  1350. if pkgpath := gccgoPkgpath(p); pkgpath != "" {
  1351. gcargs = append(gcargs, "-fgo-pkgpath="+pkgpath)
  1352. }
  1353. if p.localPrefix != "" {
  1354. gcargs = append(gcargs, "-fgo-relative-import-path="+p.localPrefix)
  1355. }
  1356. args := stringList("gccgo", importArgs, "-c", gcargs, "-o", ofile, buildGccgoflags)
  1357. for _, f := range gofiles {
  1358. args = append(args, mkAbs(p.Dir, f))
  1359. }
  1360. output, err = b.runOut(p.Dir, p.ImportPath, args)
  1361. return ofile, output, err
  1362. }
  1363. func (gccgoToolchain) asm(b *builder, p *Package, obj, ofile, sfile string) error {
  1364. sfile = mkAbs(p.Dir, sfile)
  1365. defs := []string{"-D", "GOOS_" + goos, "-D", "GOARCH_" + goarch}
  1366. if pkgpath := gccgoCleanPkgpath(p); pkgpath != "" {
  1367. defs = append(defs, `-D`, `GOPKGPATH="`+pkgpath+`"`)
  1368. }
  1369. defs = append(defs, b.gccArchArgs()...)
  1370. return b.run(p.Dir, p.ImportPath, "gccgo", "-I", obj, "-o", ofile, defs, sfile)
  1371. }
  1372. func (gccgoToolchain) pkgpath(basedir string, p *Package) string {
  1373. end := filepath.FromSlash(p.ImportPath + ".a")
  1374. afile := filepath.Join(basedir, end)
  1375. // add "lib" to the final element
  1376. return filepath.Join(filepath.Dir(afile), "lib"+filepath.Base(afile))
  1377. }
  1378. func (gccgoToolchain) pack(b *builder, p *Package, objDir, afile string, ofiles []string) error {
  1379. var absOfiles []string
  1380. for _, f := range ofiles {
  1381. absOfiles = append(absOfiles, mkAbs(objDir, f))
  1382. }
  1383. return b.run(p.Dir, p.ImportPath, "ar", "cru", mkAbs(objDir, afile), absOfiles)
  1384. }
  1385. func (tools gccgoToolchain) ld(b *builder, p *Package, out string, allactions []*action, mainpkg string, ofiles []string) error {
  1386. // gccgo needs explicit linking with all package dependencies,
  1387. // and all LDFLAGS from cgo dependencies.
  1388. afiles := make(map[*Package]string)
  1389. sfiles := make(map[*Package][]string)
  1390. ldflags := b.gccArchArgs()
  1391. cgoldflags := []string{}
  1392. usesCgo := false
  1393. for _, a := range allactions {
  1394. if a.p != nil {
  1395. if !a.p.Standard {
  1396. if afiles[a.p] == "" || a.objpkg != a.target {
  1397. afiles[a.p] = a.target
  1398. }
  1399. }
  1400. cgoldflags = append(cgoldflags, a.p.CgoLDFLAGS...)
  1401. if len(a.p.CgoFiles) > 0 {
  1402. usesCgo = true
  1403. }
  1404. if a.p.usesSwig() {
  1405. sd := a.p.swigDir(&buildContext)
  1406. for _, f := range stringList(a.p.SwigFiles, a.p.SwigCXXFiles) {
  1407. soname := a.p.swigSoname(f)
  1408. sfiles[a.p] = append(sfiles[a.p], filepath.Join(sd, soname))
  1409. }
  1410. usesCgo = true
  1411. }
  1412. }
  1413. }
  1414. for _, afile := range afiles {
  1415. ldflags = append(ldflags, afile)
  1416. }
  1417. for _, sfiles := range sfiles {
  1418. ldflags = append(ldflags, sfiles...)
  1419. }
  1420. ldflags = append(ldflags, cgoldflags...)
  1421. if usesCgo && goos == "linux" {
  1422. ldflags = append(ldflags, "-Wl,-E")
  1423. }
  1424. return b.run(".", p.ImportPath, "gccgo", "-o", out, ofiles, "-Wl,-(", ldflags, "-Wl,-)", buildGccgoflags)
  1425. }
  1426. func (gccgoToolchain) cc(b *builder, p *Package, objdir, ofile, cfile string) error {
  1427. inc := filepath.Join(goroot, "pkg", fmt.Sprintf("%s_%s", goos, goarch))
  1428. cfile = mkAbs(p.Dir, cfile)
  1429. defs := []string{"-D", "GOOS_" + goos, "-D", "GOARCH_" + goarch}
  1430. defs = append(defs, b.gccArchArgs()...)
  1431. if pkgpath := gccgoCleanPkgpath(p); pkgpath != "" {
  1432. defs = append(defs, `-D`, `GOPKGPATH="`+pkgpath+`"`)
  1433. }
  1434. // TODO: Support using clang here (during gccgo build)?
  1435. return b.run(p.Dir, p.ImportPath, "gcc", "-Wall", "-g",
  1436. "-I", objdir, "-I", inc, "-o", ofile, defs, "-c", cfile)
  1437. }
  1438. func gccgoPkgpath(p *Package) string {
  1439. if p.build.IsCommand() && !p.forceLibrary {
  1440. return ""
  1441. }
  1442. return p.ImportPath
  1443. }
  1444. func gccgoCleanPkgpath(p *Package) string {
  1445. clean := func(r rune) rune {
  1446. switch {
  1447. case 'A' <= r && r <= 'Z', 'a' <= r && r <= 'z',
  1448. '0' <= r && r <= '9':
  1449. return r
  1450. }
  1451. return '_'
  1452. }
  1453. return strings.Map(clean, gccgoPkgpath(p))
  1454. }
  1455. // libgcc returns the filename for libgcc, as determined by invoking gcc with
  1456. // the -print-libgcc-file-name option.
  1457. func (b *builder) libgcc(p *Package) (string, error) {
  1458. var buf bytes.Buffer
  1459. gccCmd := b.gccCmd(p.Dir)
  1460. prev := b.print
  1461. if buildN {
  1462. // In -n mode we temporarily swap out the builder's
  1463. // print function to capture the command-line. This
  1464. // let's us assign it to $LIBGCC and produce a valid
  1465. // buildscript for cgo packages.
  1466. b.print = func(a ...interface{}) (int, error) {
  1467. return fmt.Fprint(&buf, a...)
  1468. }
  1469. }
  1470. f, err := b.runOut(p.Dir, p.ImportPath, gccCmd, "-print-libgcc-file-name")
  1471. if err != nil {
  1472. return "", fmt.Errorf("gcc -print-libgcc-file-name: %v (%s)", err, f)
  1473. }
  1474. if buildN {
  1475. s := fmt.Sprintf("LIBGCC=$(%s)\n", buf.Next(buf.Len()-1))
  1476. b.print = prev
  1477. b.print(s)
  1478. return "$LIBGCC", nil
  1479. }
  1480. // clang might not be able to find libgcc, and in that case,
  1481. // it will simply return "libgcc.a", which is of no use to us.
  1482. if strings.Contains(gccCmd[0], "clang") && !filepath.IsAbs(string(f)) {
  1483. return "", nil
  1484. }
  1485. return strings.Trim(string(f), "\r\n"), nil
  1486. }
  1487. // gcc runs the gcc C compiler to create an object from a single C file.
  1488. func (b *builder) gcc(p *Package, out string, flags []string, cfile string) error {
  1489. cfile = mkAbs(p.Dir, cfile)
  1490. return b.run(p.Dir, p.ImportPath, b.gccCmd(p.Dir), flags, "-o", out, "-c", cfile)
  1491. }
  1492. // gccld runs the gcc linker to create an executable from a set of object files
  1493. func (b *builder) gccld(p *Package, out string, flags []string, obj []string) error {
  1494. return b.run(p.Dir, p.ImportPath, b.gccCmd(p.Dir), "-o", out, obj, flags)
  1495. }
  1496. // gccCmd returns a gcc command line prefix
  1497. func (b *builder) gccCmd(objdir string) []string {
  1498. // NOTE: env.go's mkEnv knows that the first three
  1499. // strings returned are "gcc", "-I", objdir (and cuts them off).
  1500. gcc := strings.Fields(os.Getenv("CC"))
  1501. if len(gcc) == 0 {
  1502. gcc = append(gcc, "gcc")
  1503. }
  1504. a := []string{gcc[0], "-I", objdir, "-g", "-O2"}
  1505. a = append(a, gcc[1:]...)
  1506. // Definitely want -fPIC but on Windows gcc complains
  1507. // "-fPIC ignored for target (all code is position independent)"
  1508. if goos != "windows" {

Large files files are truncated, but you can click here to view the full file