github.com/corona10/go@v0.0.0-20180224231303-7a218942be57/src/cmd/go/internal/work/action.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 creation (planning). 6 7 package work 8 9 import ( 10 "bufio" 11 "bytes" 12 "container/heap" 13 "debug/elf" 14 "encoding/json" 15 "fmt" 16 "io/ioutil" 17 "os" 18 "path/filepath" 19 "strings" 20 "sync" 21 22 "cmd/go/internal/base" 23 "cmd/go/internal/cache" 24 "cmd/go/internal/cfg" 25 "cmd/go/internal/load" 26 "cmd/internal/buildid" 27 ) 28 29 // A Builder holds global state about a build. 30 // It does not hold per-package state, because we 31 // build packages in parallel, and the builder is shared. 32 type Builder struct { 33 WorkDir string // the temporary work directory (ends in filepath.Separator) 34 actionCache map[cacheKey]*Action // a cache of already-constructed actions 35 mkdirCache map[string]bool // a cache of created directories 36 flagCache map[[2]string]bool // a cache of supported compiler flags 37 Print func(args ...interface{}) (int, error) 38 39 ComputeStaleOnly bool // compute staleness for go list; no actual build 40 41 objdirSeq int // counter for NewObjdir 42 pkgSeq int 43 44 output sync.Mutex 45 scriptDir string // current directory in printed script 46 47 exec sync.Mutex 48 readySema chan bool 49 ready actionQueue 50 51 id sync.Mutex 52 toolIDCache map[string]string // tool name -> tool ID 53 buildIDCache map[string]string // file name -> build ID 54 } 55 56 // NOTE: Much of Action would not need to be exported if not for test. 57 // Maybe test functionality should move into this package too? 58 59 // An Action represents a single action in the action graph. 60 type Action struct { 61 Mode string // description of action operation 62 Package *load.Package // the package this action works on 63 Deps []*Action // actions that must happen before this one 64 Func func(*Builder, *Action) error // the action itself (nil = no-op) 65 IgnoreFail bool // whether to run f even if dependencies fail 66 TestOutput *bytes.Buffer // test output buffer 67 Args []string // additional args for runProgram 68 69 triggers []*Action // inverse of deps 70 71 buggyInstall bool // is this a buggy install (see -linkshared)? 72 73 TryCache func(*Builder, *Action) bool // callback for cache bypass 74 75 // Generated files, directories. 76 Objdir string // directory for intermediate objects 77 Target string // goal of the action: the created package or executable 78 built string // the actual created package or executable 79 actionID cache.ActionID // cache ID of action input 80 buildID string // build ID of action output 81 82 needVet bool // Mode=="build": need to fill in vet config 83 vetCfg *vetConfig // vet config 84 output []byte // output redirect buffer (nil means use b.Print) 85 86 // Execution state. 87 pending int // number of deps yet to complete 88 priority int // relative execution priority 89 Failed bool // whether the action failed 90 } 91 92 // BuildActionID returns the action ID section of a's build ID. 93 func (a *Action) BuildActionID() string { return actionID(a.buildID) } 94 95 // BuildContentID returns the content ID section of a's build ID. 96 func (a *Action) BuildContentID() string { return contentID(a.buildID) } 97 98 // BuildID returns a's build ID. 99 func (a *Action) BuildID() string { return a.buildID } 100 101 // BuiltTarget returns the actual file that was built. This differs 102 // from Target when the result was cached. 103 func (a *Action) BuiltTarget() string { return a.built } 104 105 // An actionQueue is a priority queue of actions. 106 type actionQueue []*Action 107 108 // Implement heap.Interface 109 func (q *actionQueue) Len() int { return len(*q) } 110 func (q *actionQueue) Swap(i, j int) { (*q)[i], (*q)[j] = (*q)[j], (*q)[i] } 111 func (q *actionQueue) Less(i, j int) bool { return (*q)[i].priority < (*q)[j].priority } 112 func (q *actionQueue) Push(x interface{}) { *q = append(*q, x.(*Action)) } 113 func (q *actionQueue) Pop() interface{} { 114 n := len(*q) - 1 115 x := (*q)[n] 116 *q = (*q)[:n] 117 return x 118 } 119 120 func (q *actionQueue) push(a *Action) { 121 heap.Push(q, a) 122 } 123 124 func (q *actionQueue) pop() *Action { 125 return heap.Pop(q).(*Action) 126 } 127 128 type actionJSON struct { 129 ID int 130 Mode string 131 Package string 132 Deps []int `json:",omitempty"` 133 IgnoreFail bool `json:",omitempty"` 134 Args []string `json:",omitempty"` 135 Link bool `json:",omitempty"` 136 Objdir string `json:",omitempty"` 137 Target string `json:",omitempty"` 138 Priority int `json:",omitempty"` 139 Failed bool `json:",omitempty"` 140 Built string `json:",omitempty"` 141 } 142 143 // cacheKey is the key for the action cache. 144 type cacheKey struct { 145 mode string 146 p *load.Package 147 } 148 149 func actionGraphJSON(a *Action) string { 150 var workq []*Action 151 var inWorkq = make(map[*Action]int) 152 153 add := func(a *Action) { 154 if _, ok := inWorkq[a]; ok { 155 return 156 } 157 inWorkq[a] = len(workq) 158 workq = append(workq, a) 159 } 160 add(a) 161 162 for i := 0; i < len(workq); i++ { 163 for _, dep := range workq[i].Deps { 164 add(dep) 165 } 166 } 167 168 var list []*actionJSON 169 for id, a := range workq { 170 aj := &actionJSON{ 171 Mode: a.Mode, 172 ID: id, 173 IgnoreFail: a.IgnoreFail, 174 Args: a.Args, 175 Objdir: a.Objdir, 176 Target: a.Target, 177 Failed: a.Failed, 178 Priority: a.priority, 179 Built: a.built, 180 } 181 if a.Package != nil { 182 // TODO(rsc): Make this a unique key for a.Package somehow. 183 aj.Package = a.Package.ImportPath 184 } 185 for _, a1 := range a.Deps { 186 aj.Deps = append(aj.Deps, inWorkq[a1]) 187 } 188 list = append(list, aj) 189 } 190 191 js, err := json.MarshalIndent(list, "", "\t") 192 if err != nil { 193 fmt.Fprintf(os.Stderr, "go: writing debug action graph: %v\n", err) 194 return "" 195 } 196 return string(js) 197 } 198 199 // BuildMode specifies the build mode: 200 // are we just building things or also installing the results? 201 type BuildMode int 202 203 const ( 204 ModeBuild BuildMode = iota 205 ModeInstall 206 ModeBuggyInstall 207 ) 208 209 func (b *Builder) Init() { 210 var err error 211 b.Print = func(a ...interface{}) (int, error) { 212 return fmt.Fprint(os.Stderr, a...) 213 } 214 b.actionCache = make(map[cacheKey]*Action) 215 b.mkdirCache = make(map[string]bool) 216 b.toolIDCache = make(map[string]string) 217 b.buildIDCache = make(map[string]string) 218 219 if cfg.BuildN { 220 b.WorkDir = "$WORK" 221 } else { 222 b.WorkDir, err = ioutil.TempDir(os.Getenv("GOTMPDIR"), "go-build") 223 if err != nil { 224 base.Fatalf("%s", err) 225 } 226 if cfg.BuildX || cfg.BuildWork { 227 fmt.Fprintf(os.Stderr, "WORK=%s\n", b.WorkDir) 228 } 229 if !cfg.BuildWork { 230 workdir := b.WorkDir 231 base.AtExit(func() { os.RemoveAll(workdir) }) 232 } 233 } 234 235 if _, ok := cfg.OSArchSupportsCgo[cfg.Goos+"/"+cfg.Goarch]; !ok && cfg.BuildContext.Compiler == "gc" { 236 fmt.Fprintf(os.Stderr, "cmd/go: unsupported GOOS/GOARCH pair %s/%s\n", cfg.Goos, cfg.Goarch) 237 os.Exit(2) 238 } 239 for _, tag := range cfg.BuildContext.BuildTags { 240 if strings.Contains(tag, ",") { 241 fmt.Fprintf(os.Stderr, "cmd/go: -tags space-separated list contains comma\n") 242 os.Exit(2) 243 } 244 } 245 } 246 247 // NewObjdir returns the name of a fresh object directory under b.WorkDir. 248 // It is up to the caller to call b.Mkdir on the result at an appropriate time. 249 // The result ends in a slash, so that file names in that directory 250 // can be constructed with direct string addition. 251 // 252 // NewObjdir must be called only from a single goroutine at a time, 253 // so it is safe to call during action graph construction, but it must not 254 // be called during action graph execution. 255 func (b *Builder) NewObjdir() string { 256 b.objdirSeq++ 257 return filepath.Join(b.WorkDir, fmt.Sprintf("b%03d", b.objdirSeq)) + string(filepath.Separator) 258 } 259 260 // readpkglist returns the list of packages that were built into the shared library 261 // at shlibpath. For the native toolchain this list is stored, newline separated, in 262 // an ELF note with name "Go\x00\x00" and type 1. For GCCGO it is extracted from the 263 // .go_export section. 264 func readpkglist(shlibpath string) (pkgs []*load.Package) { 265 var stk load.ImportStack 266 if cfg.BuildToolchainName == "gccgo" { 267 f, _ := elf.Open(shlibpath) 268 sect := f.Section(".go_export") 269 data, _ := sect.Data() 270 scanner := bufio.NewScanner(bytes.NewBuffer(data)) 271 for scanner.Scan() { 272 t := scanner.Text() 273 if strings.HasPrefix(t, "pkgpath ") { 274 t = strings.TrimPrefix(t, "pkgpath ") 275 t = strings.TrimSuffix(t, ";") 276 pkgs = append(pkgs, load.LoadPackage(t, &stk)) 277 } 278 } 279 } else { 280 pkglistbytes, err := buildid.ReadELFNote(shlibpath, "Go\x00\x00", 1) 281 if err != nil { 282 base.Fatalf("readELFNote failed: %v", err) 283 } 284 scanner := bufio.NewScanner(bytes.NewBuffer(pkglistbytes)) 285 for scanner.Scan() { 286 t := scanner.Text() 287 pkgs = append(pkgs, load.LoadPackage(t, &stk)) 288 } 289 } 290 return 291 } 292 293 // cacheAction looks up {mode, p} in the cache and returns the resulting action. 294 // If the cache has no such action, f() is recorded and returned. 295 // TODO(rsc): Change the second key from *load.Package to interface{}, 296 // to make the caching in linkShared less awkward? 297 func (b *Builder) cacheAction(mode string, p *load.Package, f func() *Action) *Action { 298 a := b.actionCache[cacheKey{mode, p}] 299 if a == nil { 300 a = f() 301 b.actionCache[cacheKey{mode, p}] = a 302 } 303 return a 304 } 305 306 // AutoAction returns the "right" action for go build or go install of p. 307 func (b *Builder) AutoAction(mode, depMode BuildMode, p *load.Package) *Action { 308 if p.Name == "main" { 309 return b.LinkAction(mode, depMode, p) 310 } 311 return b.CompileAction(mode, depMode, p) 312 } 313 314 // CompileAction returns the action for compiling and possibly installing 315 // (according to mode) the given package. The resulting action is only 316 // for building packages (archives), never for linking executables. 317 // depMode is the action (build or install) to use when building dependencies. 318 // To turn package main into an executable, call b.Link instead. 319 func (b *Builder) CompileAction(mode, depMode BuildMode, p *load.Package) *Action { 320 if mode != ModeBuild && p.Internal.Local && p.Target == "" { 321 // Imported via local path. No permanent target. 322 mode = ModeBuild 323 } 324 if mode != ModeBuild && p.Name == "main" { 325 // We never install the .a file for a main package. 326 mode = ModeBuild 327 } 328 329 // Construct package build action. 330 a := b.cacheAction("build", p, func() *Action { 331 a := &Action{ 332 Mode: "build", 333 Package: p, 334 Func: (*Builder).build, 335 Objdir: b.NewObjdir(), 336 } 337 338 for _, p1 := range p.Internal.Imports { 339 a.Deps = append(a.Deps, b.CompileAction(depMode, depMode, p1)) 340 } 341 342 if p.Standard { 343 switch p.ImportPath { 344 case "builtin", "unsafe": 345 // Fake packages - nothing to build. 346 a.Mode = "built-in package" 347 a.Func = nil 348 return a 349 } 350 351 // gccgo standard library is "fake" too. 352 if cfg.BuildToolchainName == "gccgo" { 353 // the target name is needed for cgo. 354 a.Mode = "gccgo stdlib" 355 a.Target = p.Target 356 a.Func = nil 357 return a 358 } 359 } 360 361 return a 362 }) 363 364 // Construct install action. 365 if mode == ModeInstall || mode == ModeBuggyInstall { 366 a = b.installAction(a, mode) 367 } 368 369 return a 370 } 371 372 // VetAction returns the action for running go vet on package p. 373 // It depends on the action for compiling p. 374 // If the caller may be causing p to be installed, it is up to the caller 375 // to make sure that the install depends on (runs after) vet. 376 func (b *Builder) VetAction(mode, depMode BuildMode, p *load.Package) *Action { 377 // Construct vet action. 378 a := b.cacheAction("vet", p, func() *Action { 379 a1 := b.CompileAction(mode, depMode, p) 380 381 // vet expects to be able to import "fmt". 382 var stk load.ImportStack 383 stk.Push("vet") 384 p1 := load.LoadPackage("fmt", &stk) 385 stk.Pop() 386 aFmt := b.CompileAction(ModeBuild, depMode, p1) 387 388 a := &Action{ 389 Mode: "vet", 390 Package: p, 391 Deps: []*Action{a1, aFmt}, 392 Objdir: a1.Objdir, 393 } 394 if a1.Func == nil { 395 // Built-in packages like unsafe. 396 return a 397 } 398 a1.needVet = true 399 a.Func = (*Builder).vet 400 401 return a 402 }) 403 return a 404 } 405 406 // LinkAction returns the action for linking p into an executable 407 // and possibly installing the result (according to mode). 408 // depMode is the action (build or install) to use when compiling dependencies. 409 func (b *Builder) LinkAction(mode, depMode BuildMode, p *load.Package) *Action { 410 // Construct link action. 411 a := b.cacheAction("link", p, func() *Action { 412 a := &Action{ 413 Mode: "link", 414 Package: p, 415 } 416 417 a1 := b.CompileAction(ModeBuild, depMode, p) 418 a.Func = (*Builder).link 419 a.Deps = []*Action{a1} 420 a.Objdir = a1.Objdir 421 422 // An executable file. (This is the name of a temporary file.) 423 // Because we run the temporary file in 'go run' and 'go test', 424 // the name will show up in ps listings. If the caller has specified 425 // a name, use that instead of a.out. The binary is generated 426 // in an otherwise empty subdirectory named exe to avoid 427 // naming conflicts. The only possible conflict is if we were 428 // to create a top-level package named exe. 429 name := "a.out" 430 if p.Internal.ExeName != "" { 431 name = p.Internal.ExeName 432 } else if (cfg.Goos == "darwin" || cfg.Goos == "windows") && cfg.BuildBuildmode == "c-shared" && p.Target != "" { 433 // On OS X, the linker output name gets recorded in the 434 // shared library's LC_ID_DYLIB load command. 435 // The code invoking the linker knows to pass only the final 436 // path element. Arrange that the path element matches what 437 // we'll install it as; otherwise the library is only loadable as "a.out". 438 // On Windows, DLL file name is recorded in PE file 439 // export section, so do like on OS X. 440 _, name = filepath.Split(p.Target) 441 } 442 a.Target = a.Objdir + filepath.Join("exe", name) + cfg.ExeSuffix 443 a.built = a.Target 444 b.addTransitiveLinkDeps(a, a1, "") 445 446 // Sequence the build of the main package (a1) strictly after the build 447 // of all other dependencies that go into the link. It is likely to be after 448 // them anyway, but just make sure. This is required by the build ID-based 449 // shortcut in (*Builder).useCache(a1), which will call b.linkActionID(a). 450 // In order for that linkActionID call to compute the right action ID, all the 451 // dependencies of a (except a1) must have completed building and have 452 // recorded their build IDs. 453 a1.Deps = append(a1.Deps, &Action{Mode: "nop", Deps: a.Deps[1:]}) 454 return a 455 }) 456 457 if mode == ModeInstall || mode == ModeBuggyInstall { 458 a = b.installAction(a, mode) 459 } 460 461 return a 462 } 463 464 // installAction returns the action for installing the result of a1. 465 func (b *Builder) installAction(a1 *Action, mode BuildMode) *Action { 466 // Because we overwrite the build action with the install action below, 467 // a1 may already be an install action fetched from the "build" cache key, 468 // and the caller just doesn't realize. 469 if strings.HasSuffix(a1.Mode, "-install") { 470 if a1.buggyInstall && mode == ModeInstall { 471 // Congratulations! The buggy install is now a proper install. 472 a1.buggyInstall = false 473 } 474 return a1 475 } 476 477 // If there's no actual action to build a1, 478 // there's nothing to install either. 479 // This happens if a1 corresponds to reusing an already-built object. 480 if a1.Func == nil { 481 return a1 482 } 483 484 p := a1.Package 485 return b.cacheAction(a1.Mode+"-install", p, func() *Action { 486 // The install deletes the temporary build result, 487 // so we need all other actions, both past and future, 488 // that attempt to depend on the build to depend instead 489 // on the install. 490 491 // Make a private copy of a1 (the build action), 492 // no longer accessible to any other rules. 493 buildAction := new(Action) 494 *buildAction = *a1 495 496 // Overwrite a1 with the install action. 497 // This takes care of updating past actions that 498 // point at a1 for the build action; now they will 499 // point at a1 and get the install action. 500 // We also leave a1 in the action cache as the result 501 // for "build", so that actions not yet created that 502 // try to depend on the build will instead depend 503 // on the install. 504 *a1 = Action{ 505 Mode: buildAction.Mode + "-install", 506 Func: BuildInstallFunc, 507 Package: p, 508 Objdir: buildAction.Objdir, 509 Deps: []*Action{buildAction}, 510 Target: p.Target, 511 built: p.Target, 512 513 buggyInstall: mode == ModeBuggyInstall, 514 } 515 516 b.addInstallHeaderAction(a1) 517 return a1 518 }) 519 } 520 521 // addTransitiveLinkDeps adds to the link action a all packages 522 // that are transitive dependencies of a1.Deps. 523 // That is, if a is a link of package main, a1 is the compile of package main 524 // and a1.Deps is the actions for building packages directly imported by 525 // package main (what the compiler needs). The linker needs all packages 526 // transitively imported by the whole program; addTransitiveLinkDeps 527 // makes sure those are present in a.Deps. 528 // If shlib is non-empty, then a corresponds to the build and installation of shlib, 529 // so any rebuild of shlib should not be added as a dependency. 530 func (b *Builder) addTransitiveLinkDeps(a, a1 *Action, shlib string) { 531 // Expand Deps to include all built packages, for the linker. 532 // Use breadth-first search to find rebuilt-for-test packages 533 // before the standard ones. 534 // TODO(rsc): Eliminate the standard ones from the action graph, 535 // which will require doing a little bit more rebuilding. 536 workq := []*Action{a1} 537 haveDep := map[string]bool{} 538 if a1.Package != nil { 539 haveDep[a1.Package.ImportPath] = true 540 } 541 for i := 0; i < len(workq); i++ { 542 a1 := workq[i] 543 for _, a2 := range a1.Deps { 544 // TODO(rsc): Find a better discriminator than the Mode strings, once the dust settles. 545 if a2.Package == nil || (a2.Mode != "build-install" && a2.Mode != "build") || haveDep[a2.Package.ImportPath] { 546 continue 547 } 548 haveDep[a2.Package.ImportPath] = true 549 a.Deps = append(a.Deps, a2) 550 if a2.Mode == "build-install" { 551 a2 = a2.Deps[0] // walk children of "build" action 552 } 553 workq = append(workq, a2) 554 } 555 } 556 557 // If this is go build -linkshared, then the link depends on the shared libraries 558 // in addition to the packages themselves. (The compile steps do not.) 559 if cfg.BuildLinkshared { 560 haveShlib := map[string]bool{shlib: true} 561 for _, a1 := range a.Deps { 562 p1 := a1.Package 563 if p1 == nil || p1.Shlib == "" || haveShlib[filepath.Base(p1.Shlib)] { 564 continue 565 } 566 haveShlib[filepath.Base(p1.Shlib)] = true 567 // TODO(rsc): The use of ModeInstall here is suspect, but if we only do ModeBuild, 568 // we'll end up building an overall library or executable that depends at runtime 569 // on other libraries that are out-of-date, which is clearly not good either. 570 // We call it ModeBuggyInstall to make clear that this is not right. 571 a.Deps = append(a.Deps, b.linkSharedAction(ModeBuggyInstall, ModeBuggyInstall, p1.Shlib, nil)) 572 } 573 } 574 } 575 576 // addInstallHeaderAction adds an install header action to a, if needed. 577 // The action a should be an install action as generated by either 578 // b.CompileAction or b.LinkAction with mode=ModeInstall, 579 // and so a.Deps[0] is the corresponding build action. 580 func (b *Builder) addInstallHeaderAction(a *Action) { 581 // Install header for cgo in c-archive and c-shared modes. 582 p := a.Package 583 if p.UsesCgo() && (cfg.BuildBuildmode == "c-archive" || cfg.BuildBuildmode == "c-shared") { 584 hdrTarget := a.Target[:len(a.Target)-len(filepath.Ext(a.Target))] + ".h" 585 if cfg.BuildContext.Compiler == "gccgo" { 586 // For the header file, remove the "lib" 587 // added by go/build, so we generate pkg.h 588 // rather than libpkg.h. 589 dir, file := filepath.Split(hdrTarget) 590 file = strings.TrimPrefix(file, "lib") 591 hdrTarget = filepath.Join(dir, file) 592 } 593 ah := &Action{ 594 Mode: "install header", 595 Package: a.Package, 596 Deps: []*Action{a.Deps[0]}, 597 Func: (*Builder).installHeader, 598 Objdir: a.Deps[0].Objdir, 599 Target: hdrTarget, 600 } 601 a.Deps = append(a.Deps, ah) 602 } 603 } 604 605 // buildmodeShared takes the "go build" action a1 into the building of a shared library of a1.Deps. 606 // That is, the input a1 represents "go build pkgs" and the result represents "go build -buidmode=shared pkgs". 607 func (b *Builder) buildmodeShared(mode, depMode BuildMode, args []string, pkgs []*load.Package, a1 *Action) *Action { 608 name, err := libname(args, pkgs) 609 if err != nil { 610 base.Fatalf("%v", err) 611 } 612 return b.linkSharedAction(mode, depMode, name, a1) 613 } 614 615 // linkSharedAction takes a grouping action a1 corresponding to a list of built packages 616 // and returns an action that links them together into a shared library with the name shlib. 617 // If a1 is nil, shlib should be an absolute path to an existing shared library, 618 // and then linkSharedAction reads that library to find out the package list. 619 func (b *Builder) linkSharedAction(mode, depMode BuildMode, shlib string, a1 *Action) *Action { 620 fullShlib := shlib 621 shlib = filepath.Base(shlib) 622 a := b.cacheAction("build-shlib "+shlib, nil, func() *Action { 623 if a1 == nil { 624 // TODO(rsc): Need to find some other place to store config, 625 // not in pkg directory. See golang.org/issue/22196. 626 pkgs := readpkglist(fullShlib) 627 a1 = &Action{ 628 Mode: "shlib packages", 629 } 630 for _, p := range pkgs { 631 a1.Deps = append(a1.Deps, b.CompileAction(mode, depMode, p)) 632 } 633 } 634 635 // Fake package to hold ldflags. 636 // As usual shared libraries are a kludgy, abstraction-violating special case: 637 // we let them use the flags specified for the command-line arguments. 638 p := &load.Package{} 639 p.Internal.CmdlinePkg = true 640 p.Internal.Ldflags = load.BuildLdflags.For(p) 641 p.Internal.Gccgoflags = load.BuildGccgoflags.For(p) 642 643 // Add implicit dependencies to pkgs list. 644 // Currently buildmode=shared forces external linking mode, and 645 // external linking mode forces an import of runtime/cgo (and 646 // math on arm). So if it was not passed on the command line and 647 // it is not present in another shared library, add it here. 648 // TODO(rsc): Maybe this should only happen if "runtime" is in the original package set. 649 // TODO(rsc): This should probably be changed to use load.LinkerDeps(p). 650 // TODO(rsc): We don't add standard library imports for gccgo 651 // because they are all always linked in anyhow. 652 // Maybe load.LinkerDeps should be used and updated. 653 a := &Action{ 654 Mode: "go build -buildmode=shared", 655 Package: p, 656 Objdir: b.NewObjdir(), 657 Func: (*Builder).linkShared, 658 Deps: []*Action{a1}, 659 } 660 a.Target = filepath.Join(a.Objdir, shlib) 661 if cfg.BuildToolchainName != "gccgo" { 662 add := func(a1 *Action, pkg string, force bool) { 663 for _, a2 := range a1.Deps { 664 if a2.Package != nil && a2.Package.ImportPath == pkg { 665 return 666 } 667 } 668 var stk load.ImportStack 669 p := load.LoadPackage(pkg, &stk) 670 if p.Error != nil { 671 base.Fatalf("load %s: %v", pkg, p.Error) 672 } 673 // Assume that if pkg (runtime/cgo or math) 674 // is already accounted for in a different shared library, 675 // then that shared library also contains runtime, 676 // so that anything we do will depend on that library, 677 // so we don't need to include pkg in our shared library. 678 if force || p.Shlib == "" || filepath.Base(p.Shlib) == pkg { 679 a1.Deps = append(a1.Deps, b.CompileAction(depMode, depMode, p)) 680 } 681 } 682 add(a1, "runtime/cgo", false) 683 if cfg.Goarch == "arm" { 684 add(a1, "math", false) 685 } 686 687 // The linker step still needs all the usual linker deps. 688 // (For example, the linker always opens runtime.a.) 689 for _, dep := range load.LinkerDeps(nil) { 690 add(a, dep, true) 691 } 692 } 693 b.addTransitiveLinkDeps(a, a1, shlib) 694 return a 695 }) 696 697 // Install result. 698 if (mode == ModeInstall || mode == ModeBuggyInstall) && a.Func != nil { 699 buildAction := a 700 701 a = b.cacheAction("install-shlib "+shlib, nil, func() *Action { 702 // Determine the eventual install target. 703 // The install target is root/pkg/shlib, where root is the source root 704 // in which all the packages lie. 705 // TODO(rsc): Perhaps this cross-root check should apply to the full 706 // transitive package dependency list, not just the ones named 707 // on the command line? 708 pkgDir := a1.Deps[0].Package.Internal.Build.PkgTargetRoot 709 for _, a2 := range a1.Deps { 710 if dir := a2.Package.Internal.Build.PkgTargetRoot; dir != pkgDir { 711 base.Fatalf("installing shared library: cannot use packages %s and %s from different roots %s and %s", 712 a1.Deps[0].Package.ImportPath, 713 a2.Package.ImportPath, 714 pkgDir, 715 dir) 716 } 717 } 718 // TODO(rsc): Find out and explain here why gccgo is different. 719 if cfg.BuildToolchainName == "gccgo" { 720 pkgDir = filepath.Join(pkgDir, "shlibs") 721 } 722 target := filepath.Join(pkgDir, shlib) 723 724 a := &Action{ 725 Mode: "go install -buildmode=shared", 726 Objdir: buildAction.Objdir, 727 Func: BuildInstallFunc, 728 Deps: []*Action{buildAction}, 729 Target: target, 730 } 731 for _, a2 := range buildAction.Deps[0].Deps { 732 p := a2.Package 733 if p.Target == "" { 734 continue 735 } 736 a.Deps = append(a.Deps, &Action{ 737 Mode: "shlibname", 738 Package: p, 739 Func: (*Builder).installShlibname, 740 Target: strings.TrimSuffix(p.Target, ".a") + ".shlibname", 741 Deps: []*Action{a.Deps[0]}, 742 }) 743 } 744 return a 745 }) 746 } 747 748 return a 749 }