Source file src/cmd/go/internal/work/buildid.go

     1  // Copyright 2017 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package work
     6  
     7  import (
     8  	"bytes"
     9  	"fmt"
    10  	"os"
    11  	"os/exec"
    12  	"strings"
    13  	"sync"
    14  
    15  	"cmd/go/internal/base"
    16  	"cmd/go/internal/cache"
    17  	"cmd/go/internal/cfg"
    18  	"cmd/go/internal/fsys"
    19  	"cmd/go/internal/str"
    20  	"cmd/internal/buildid"
    21  	"cmd/internal/pathcache"
    22  	"cmd/internal/quoted"
    23  	"cmd/internal/telemetry/counter"
    24  )
    25  
    26  // Build IDs
    27  //
    28  // Go packages and binaries are stamped with build IDs that record both
    29  // the action ID, which is a hash of the inputs to the action that produced
    30  // the packages or binary, and the content ID, which is a hash of the action
    31  // output, namely the archive or binary itself. The hash is the same one
    32  // used by the build artifact cache (see cmd/go/internal/cache), but
    33  // truncated when stored in packages and binaries, as the full length is not
    34  // needed and is a bit unwieldy. The precise form is
    35  //
    36  //	actionID/[.../]contentID
    37  //
    38  // where the actionID and contentID are prepared by buildid.HashToString below.
    39  // and are found by looking for the first or last slash.
    40  // Usually the buildID is simply actionID/contentID, but see below for an
    41  // exception.
    42  //
    43  // The build ID serves two primary purposes.
    44  //
    45  // 1. The action ID half allows installed packages and binaries to serve as
    46  // one-element cache entries. If we intend to build math.a with a given
    47  // set of inputs summarized in the action ID, and the installed math.a already
    48  // has that action ID, we can reuse the installed math.a instead of rebuilding it.
    49  //
    50  // 2. The content ID half allows the easy preparation of action IDs for steps
    51  // that consume a particular package or binary. The content hash of every
    52  // input file for a given action must be included in the action ID hash.
    53  // Storing the content ID in the build ID lets us read it from the file with
    54  // minimal I/O, instead of reading and hashing the entire file.
    55  // This is especially effective since packages and binaries are typically
    56  // the largest inputs to an action.
    57  //
    58  // Separating action ID from content ID is important for reproducible builds.
    59  // The compiler is compiled with itself. If an output were represented by its
    60  // own action ID (instead of content ID) when computing the action ID of
    61  // the next step in the build process, then the compiler could never have its
    62  // own input action ID as its output action ID (short of a miraculous hash collision).
    63  // Instead we use the content IDs to compute the next action ID, and because
    64  // the content IDs converge, so too do the action IDs and therefore the
    65  // build IDs and the overall compiler binary. See cmd/dist's cmdbootstrap
    66  // for the actual convergence sequence.
    67  //
    68  // The “one-element cache” purpose is a bit more complex for installed
    69  // binaries. For a binary, like cmd/gofmt, there are two steps: compile
    70  // cmd/gofmt/*.go into main.a, and then link main.a into the gofmt binary.
    71  // We do not install gofmt's main.a, only the gofmt binary. Being able to
    72  // decide that the gofmt binary is up-to-date means computing the action ID
    73  // for the final link of the gofmt binary and comparing it against the
    74  // already-installed gofmt binary. But computing the action ID for the link
    75  // means knowing the content ID of main.a, which we did not keep.
    76  // To sidestep this problem, each binary actually stores an expanded build ID:
    77  //
    78  //	actionID(binary)/actionID(main.a)/contentID(main.a)/contentID(binary)
    79  //
    80  // (Note that this can be viewed equivalently as:
    81  //
    82  //	actionID(binary)/buildID(main.a)/contentID(binary)
    83  //
    84  // Storing the buildID(main.a) in the middle lets the computations that care
    85  // about the prefix or suffix halves ignore the middle and preserves the
    86  // original build ID as a contiguous string.)
    87  //
    88  // During the build, when it's time to build main.a, the gofmt binary has the
    89  // information needed to decide whether the eventual link would produce
    90  // the same binary: if the action ID for main.a's inputs matches and then
    91  // the action ID for the link step matches when assuming the given main.a
    92  // content ID, then the binary as a whole is up-to-date and need not be rebuilt.
    93  //
    94  // This is all a bit complex and may be simplified once we can rely on the
    95  // main cache, but at least at the start we will be using the content-based
    96  // staleness determination without a cache beyond the usual installed
    97  // package and binary locations.
    98  
    99  const buildIDSeparator = "/"
   100  
   101  // actionID returns the action ID half of a build ID.
   102  func actionID(buildID string) string {
   103  	i := strings.Index(buildID, buildIDSeparator)
   104  	if i < 0 {
   105  		return buildID
   106  	}
   107  	return buildID[:i]
   108  }
   109  
   110  // contentID returns the content ID half of a build ID.
   111  func contentID(buildID string) string {
   112  	return buildID[strings.LastIndex(buildID, buildIDSeparator)+1:]
   113  }
   114  
   115  // toolID returns the unique ID to use for the current copy of the
   116  // named tool (asm, compile, cover, link).
   117  //
   118  // It is important that if the tool changes (for example a compiler bug is fixed
   119  // and the compiler reinstalled), toolID returns a different string, so that old
   120  // package archives look stale and are rebuilt (with the fixed compiler).
   121  // This suggests using a content hash of the tool binary, as stored in the build ID.
   122  //
   123  // Unfortunately, we can't just open the tool binary, because the tool might be
   124  // invoked via a wrapper program specified by -toolexec and we don't know
   125  // what the wrapper program does. In particular, we want "-toolexec toolstash"
   126  // to continue working: it does no good if "-toolexec toolstash" is executing a
   127  // stashed copy of the compiler but the go command is acting as if it will run
   128  // the standard copy of the compiler. The solution is to ask the tool binary to tell
   129  // us its own build ID using the "-V=full" flag now supported by all tools.
   130  // Then we know we're getting the build ID of the compiler that will actually run
   131  // during the build. (How does the compiler binary know its own content hash?
   132  // We store it there using updateBuildID after the standard link step.)
   133  //
   134  // A final twist is that we'd prefer to have reproducible builds for release toolchains.
   135  // It should be possible to cross-compile for Windows from either Linux or Mac
   136  // or Windows itself and produce the same binaries, bit for bit. If the tool ID,
   137  // which influences the action ID half of the build ID, is based on the content ID,
   138  // then the Linux compiler binary and Mac compiler binary will have different tool IDs
   139  // and therefore produce executables with different action IDs.
   140  // To avoid this problem, for releases we use the release version string instead
   141  // of the compiler binary's content hash. This assumes that all compilers built
   142  // on all different systems are semantically equivalent, which is of course only true
   143  // modulo bugs. (Producing the exact same executables also requires that the different
   144  // build setups agree on details like $GOROOT and file name paths, but at least the
   145  // tool IDs do not make it impossible.)
   146  func (b *Builder) toolID(name string) string {
   147  	b.id.Lock()
   148  	id := b.toolIDCache[name]
   149  	b.id.Unlock()
   150  
   151  	if id != "" {
   152  		return id
   153  	}
   154  
   155  	path := base.Tool(name)
   156  	desc := "go tool " + name
   157  
   158  	// Special case: undocumented -vettool overrides usual vet,
   159  	// for testing vet or supplying an alternative analysis tool.
   160  	if name == "vet" && VetTool != "" {
   161  		path = VetTool
   162  		desc = VetTool
   163  	}
   164  
   165  	cmdline := str.StringList(cfg.BuildToolexec, path, "-V=full")
   166  	cmd := exec.Command(cmdline[0], cmdline[1:]...)
   167  	var stdout, stderr strings.Builder
   168  	cmd.Stdout = &stdout
   169  	cmd.Stderr = &stderr
   170  	if err := cmd.Run(); err != nil {
   171  		if stderr.Len() > 0 {
   172  			os.Stderr.WriteString(stderr.String())
   173  		}
   174  		base.Fatalf("go: error obtaining buildID for %s: %v", desc, err)
   175  	}
   176  
   177  	line := stdout.String()
   178  	f := strings.Fields(line)
   179  	if len(f) < 3 || f[0] != name && path != VetTool || f[1] != "version" || f[2] == "devel" && !strings.HasPrefix(f[len(f)-1], "buildID=") {
   180  		base.Fatalf("go: parsing buildID from %s -V=full: unexpected output:\n\t%s", desc, line)
   181  	}
   182  	if f[2] == "devel" {
   183  		// On the development branch, use the content ID part of the build ID.
   184  		id = contentID(f[len(f)-1])
   185  	} else {
   186  		// For a release, the output is like: "compile version go1.9.1 X:framepointer".
   187  		// Use the whole line.
   188  		id = strings.TrimSpace(line)
   189  	}
   190  
   191  	b.id.Lock()
   192  	b.toolIDCache[name] = id
   193  	b.id.Unlock()
   194  
   195  	return id
   196  }
   197  
   198  // gccToolID returns the unique ID to use for a tool that is invoked
   199  // by the GCC driver. This is used particularly for gccgo, but this can also
   200  // be used for gcc, g++, gfortran, etc.; those tools all use the GCC
   201  // driver under different names. The approach used here should also
   202  // work for sufficiently new versions of clang. Unlike toolID, the
   203  // name argument is the program to run. The language argument is the
   204  // type of input file as passed to the GCC driver's -x option.
   205  //
   206  // For these tools we have no -V=full option to dump the build ID,
   207  // but we can run the tool with -v -### to reliably get the compiler proper
   208  // and hash that. That will work in the presence of -toolexec.
   209  //
   210  // In order to get reproducible builds for released compilers, we
   211  // detect a released compiler by the absence of "experimental" in the
   212  // --version output, and in that case we just use the version string.
   213  //
   214  // gccToolID also returns the underlying executable for the compiler.
   215  // The caller assumes that stat of the exe can be used, combined with the id,
   216  // to detect changes in the underlying compiler. The returned exe can be empty,
   217  // which means to rely only on the id.
   218  func (b *Builder) gccToolID(name, language string) (id, exe string, err error) {
   219  	key := name + "." + language
   220  	b.id.Lock()
   221  	id = b.toolIDCache[key]
   222  	exe = b.toolIDCache[key+".exe"]
   223  	b.id.Unlock()
   224  
   225  	if id != "" {
   226  		return id, exe, nil
   227  	}
   228  
   229  	// Invoke the driver with -### to see the subcommands and the
   230  	// version strings. Use -x to set the language. Pretend to
   231  	// compile an empty file on standard input.
   232  	cmdline := str.StringList(cfg.BuildToolexec, name, "-###", "-x", language, "-c", "-")
   233  	cmd := exec.Command(cmdline[0], cmdline[1:]...)
   234  	// Force untranslated output so that we see the string "version".
   235  	cmd.Env = append(os.Environ(), "LC_ALL=C")
   236  	out, err := cmd.CombinedOutput()
   237  	if err != nil {
   238  		return "", "", fmt.Errorf("%s: %v; output: %q", name, err, out)
   239  	}
   240  
   241  	version := ""
   242  	lines := strings.Split(string(out), "\n")
   243  	for _, line := range lines {
   244  		fields := strings.Fields(line)
   245  		for i, field := range fields {
   246  			if strings.HasSuffix(field, ":") {
   247  				// Avoid parsing fields of lines like "Configured with: …", which may
   248  				// contain arbitrary substrings.
   249  				break
   250  			}
   251  			if field == "version" && i < len(fields)-1 {
   252  				// Check that the next field is plausibly a version number.
   253  				// We require only that it begins with an ASCII digit,
   254  				// since we don't know what version numbering schemes a given
   255  				// C compiler may use. (Clang and GCC mostly seem to follow the scheme X.Y.Z,
   256  				// but in https://go.dev/issue/64619 we saw "8.3 [DragonFly]", and who knows
   257  				// what other C compilers like "zig cc" might report?)
   258  				next := fields[i+1]
   259  				if len(next) > 0 && next[0] >= '0' && next[0] <= '9' {
   260  					version = line
   261  					break
   262  				}
   263  			}
   264  		}
   265  		if version != "" {
   266  			break
   267  		}
   268  	}
   269  	if version == "" {
   270  		return "", "", fmt.Errorf("%s: can not find version number in %q", name, out)
   271  	}
   272  
   273  	if !strings.Contains(version, "experimental") {
   274  		// This is a release. Use this line as the tool ID.
   275  		id = version
   276  	} else {
   277  		// This is a development version. The first line with
   278  		// a leading space is the compiler proper.
   279  		compiler := ""
   280  		for _, line := range lines {
   281  			if strings.HasPrefix(line, " ") && !strings.HasPrefix(line, " (in-process)") {
   282  				compiler = line
   283  				break
   284  			}
   285  		}
   286  		if compiler == "" {
   287  			return "", "", fmt.Errorf("%s: can not find compilation command in %q", name, out)
   288  		}
   289  
   290  		fields, _ := quoted.Split(compiler)
   291  		if len(fields) == 0 {
   292  			return "", "", fmt.Errorf("%s: compilation command confusion %q", name, out)
   293  		}
   294  		exe = fields[0]
   295  		if !strings.ContainsAny(exe, `/\`) {
   296  			if lp, err := pathcache.LookPath(exe); err == nil {
   297  				exe = lp
   298  			}
   299  		}
   300  		id, err = buildid.ReadFile(exe)
   301  		if err != nil {
   302  			return "", "", err
   303  		}
   304  
   305  		// If we can't find a build ID, use a hash.
   306  		if id == "" {
   307  			id = b.fileHash(exe)
   308  		}
   309  	}
   310  
   311  	b.id.Lock()
   312  	b.toolIDCache[key] = id
   313  	b.toolIDCache[key+".exe"] = exe
   314  	b.id.Unlock()
   315  
   316  	return id, exe, nil
   317  }
   318  
   319  // Check if assembler used by gccgo is GNU as.
   320  func assemblerIsGas() bool {
   321  	cmd := exec.Command(BuildToolchain.compiler(), "-print-prog-name=as")
   322  	assembler, err := cmd.Output()
   323  	if err == nil {
   324  		cmd := exec.Command(strings.TrimSpace(string(assembler)), "--version")
   325  		out, err := cmd.Output()
   326  		return err == nil && strings.Contains(string(out), "GNU")
   327  	} else {
   328  		return false
   329  	}
   330  }
   331  
   332  // gccgoBuildIDFile creates an assembler file that records the
   333  // action's build ID in an SHF_EXCLUDE section for ELF files or
   334  // in a CSECT in XCOFF files.
   335  func (b *Builder) gccgoBuildIDFile(a *Action) (string, error) {
   336  	sfile := a.Objdir + "_buildid.s"
   337  
   338  	var buf bytes.Buffer
   339  	if cfg.Goos == "aix" {
   340  		fmt.Fprintf(&buf, "\t.csect .go.buildid[XO]\n")
   341  	} else if (cfg.Goos != "solaris" && cfg.Goos != "illumos") || assemblerIsGas() {
   342  		fmt.Fprintf(&buf, "\t"+`.section .go.buildid,"e"`+"\n")
   343  	} else if cfg.Goarch == "sparc" || cfg.Goarch == "sparc64" {
   344  		fmt.Fprintf(&buf, "\t"+`.section ".go.buildid",#exclude`+"\n")
   345  	} else { // cfg.Goarch == "386" || cfg.Goarch == "amd64"
   346  		fmt.Fprintf(&buf, "\t"+`.section .go.buildid,#exclude`+"\n")
   347  	}
   348  	fmt.Fprintf(&buf, "\t.byte ")
   349  	for i := 0; i < len(a.buildID); i++ {
   350  		if i > 0 {
   351  			if i%8 == 0 {
   352  				fmt.Fprintf(&buf, "\n\t.byte ")
   353  			} else {
   354  				fmt.Fprintf(&buf, ",")
   355  			}
   356  		}
   357  		fmt.Fprintf(&buf, "%#02x", a.buildID[i])
   358  	}
   359  	fmt.Fprintf(&buf, "\n")
   360  	if cfg.Goos != "solaris" && cfg.Goos != "illumos" && cfg.Goos != "aix" {
   361  		secType := "@progbits"
   362  		if cfg.Goarch == "arm" {
   363  			secType = "%progbits"
   364  		}
   365  		fmt.Fprintf(&buf, "\t"+`.section .note.GNU-stack,"",%s`+"\n", secType)
   366  		fmt.Fprintf(&buf, "\t"+`.section .note.GNU-split-stack,"",%s`+"\n", secType)
   367  	}
   368  
   369  	if err := b.Shell(a).writeFile(sfile, buf.Bytes()); err != nil {
   370  		return "", err
   371  	}
   372  
   373  	return sfile, nil
   374  }
   375  
   376  // buildID returns the build ID found in the given file.
   377  // If no build ID is found, buildID returns the content hash of the file.
   378  func (b *Builder) buildID(file string) string {
   379  	b.id.Lock()
   380  	id := b.buildIDCache[file]
   381  	b.id.Unlock()
   382  
   383  	if id != "" {
   384  		return id
   385  	}
   386  
   387  	id, err := buildid.ReadFile(file)
   388  	if err != nil {
   389  		id = b.fileHash(file)
   390  	}
   391  
   392  	b.id.Lock()
   393  	b.buildIDCache[file] = id
   394  	b.id.Unlock()
   395  
   396  	return id
   397  }
   398  
   399  // fileHash returns the content hash of the named file.
   400  func (b *Builder) fileHash(file string) string {
   401  	file, _ = fsys.OverlayPath(file)
   402  	sum, err := cache.FileHash(file)
   403  	if err != nil {
   404  		return ""
   405  	}
   406  	return buildid.HashToString(sum)
   407  }
   408  
   409  var (
   410  	counterCacheHit  = counter.New("go/buildcache/hit")
   411  	counterCacheMiss = counter.New("go/buildcache/miss")
   412  
   413  	stdlibRecompiled        = counter.New("go/buildcache/stdlib-recompiled")
   414  	stdlibRecompiledIncOnce = sync.OnceFunc(stdlibRecompiled.Inc)
   415  )
   416  
   417  // useCache tries to satisfy the action a, which has action ID actionHash,
   418  // by using a cached result from an earlier build. At the moment, the only
   419  // cached result is the installed package or binary at target.
   420  // If useCache decides that the cache can be used, it sets a.buildID
   421  // and a.built for use by parent actions and then returns true.
   422  // Otherwise it sets a.buildID to a temporary build ID for use in the build
   423  // and returns false. When useCache returns false the expectation is that
   424  // the caller will build the target and then call updateBuildID to finish the
   425  // build ID computation.
   426  // When useCache returns false, it may have initiated buffering of output
   427  // during a's work. The caller should defer b.flushOutput(a), to make sure
   428  // that flushOutput is eventually called regardless of whether the action
   429  // succeeds. The flushOutput call must happen after updateBuildID.
   430  func (b *Builder) useCache(a *Action, actionHash cache.ActionID, target string, printOutput bool) (ok bool) {
   431  	// The second half of the build ID here is a placeholder for the content hash.
   432  	// It's important that the overall buildID be unlikely verging on impossible
   433  	// to appear in the output by chance, but that should be taken care of by
   434  	// the actionID half; if it also appeared in the input that would be like an
   435  	// engineered 120-bit partial SHA256 collision.
   436  	a.actionID = actionHash
   437  	actionID := buildid.HashToString(actionHash)
   438  	if a.json != nil {
   439  		a.json.ActionID = actionID
   440  	}
   441  	contentID := actionID // temporary placeholder, likely unique
   442  	a.buildID = actionID + buildIDSeparator + contentID
   443  
   444  	// Executable binaries also record the main build ID in the middle.
   445  	// See "Build IDs" comment above.
   446  	if a.Mode == "link" {
   447  		mainpkg := a.Deps[0]
   448  		a.buildID = actionID + buildIDSeparator + mainpkg.buildID + buildIDSeparator + contentID
   449  	}
   450  
   451  	// If user requested -a, we force a rebuild, so don't use the cache.
   452  	if cfg.BuildA {
   453  		if p := a.Package; p != nil && !p.Stale {
   454  			p.Stale = true
   455  			p.StaleReason = "build -a flag in use"
   456  		}
   457  		// Begin saving output for later writing to cache.
   458  		a.output = []byte{}
   459  		return false
   460  	}
   461  
   462  	defer func() {
   463  		// Increment counters for cache hits and misses based on the return value
   464  		// of this function. Don't increment counters if we return early because of
   465  		// cfg.BuildA above because we don't even look at the cache in that case.
   466  		if ok {
   467  			counterCacheHit.Inc()
   468  		} else {
   469  			if a.Package != nil && a.Package.Standard {
   470  				stdlibRecompiledIncOnce()
   471  			}
   472  			counterCacheMiss.Inc()
   473  		}
   474  	}()
   475  
   476  	c := cache.Default()
   477  
   478  	if target != "" {
   479  		buildID, _ := buildid.ReadFile(target)
   480  		if strings.HasPrefix(buildID, actionID+buildIDSeparator) {
   481  			a.buildID = buildID
   482  			if a.json != nil {
   483  				a.json.BuildID = a.buildID
   484  			}
   485  			a.built = target
   486  			// Poison a.Target to catch uses later in the build.
   487  			a.Target = "DO NOT USE - " + a.Mode
   488  			return true
   489  		}
   490  		// Special case for building a main package: if the only thing we
   491  		// want the package for is to link a binary, and the binary is
   492  		// already up-to-date, then to avoid a rebuild, report the package
   493  		// as up-to-date as well. See "Build IDs" comment above.
   494  		// TODO(rsc): Rewrite this code to use a TryCache func on the link action.
   495  		if !b.NeedExport && a.Mode == "build" && len(a.triggers) == 1 && a.triggers[0].Mode == "link" {
   496  			if id := strings.Split(buildID, buildIDSeparator); len(id) == 4 && id[1] == actionID {
   497  				// Temporarily assume a.buildID is the package build ID
   498  				// stored in the installed binary, and see if that makes
   499  				// the upcoming link action ID a match. If so, report that
   500  				// we built the package, safe in the knowledge that the
   501  				// link step will not ask us for the actual package file.
   502  				// Note that (*Builder).LinkAction arranged that all of
   503  				// a.triggers[0]'s dependencies other than a are also
   504  				// dependencies of a, so that we can be sure that,
   505  				// other than a.buildID, b.linkActionID is only accessing
   506  				// build IDs of completed actions.
   507  				oldBuildID := a.buildID
   508  				a.buildID = id[1] + buildIDSeparator + id[2]
   509  				linkID := buildid.HashToString(b.linkActionID(a.triggers[0]))
   510  				if id[0] == linkID {
   511  					// Best effort attempt to display output from the compile and link steps.
   512  					// If it doesn't work, it doesn't work: reusing the cached binary is more
   513  					// important than reprinting diagnostic information.
   514  					if printOutput {
   515  						showStdout(b, c, a, "stdout")      // compile output
   516  						showStdout(b, c, a, "link-stdout") // link output
   517  					}
   518  
   519  					// Poison a.Target to catch uses later in the build.
   520  					a.Target = "DO NOT USE - main build pseudo-cache Target"
   521  					a.built = "DO NOT USE - main build pseudo-cache built"
   522  					if a.json != nil {
   523  						a.json.BuildID = a.buildID
   524  					}
   525  					return true
   526  				}
   527  				// Otherwise restore old build ID for main build.
   528  				a.buildID = oldBuildID
   529  			}
   530  		}
   531  	}
   532  
   533  	// Special case for linking a test binary: if the only thing we
   534  	// want the binary for is to run the test, and the test result is cached,
   535  	// then to avoid the link step, report the link as up-to-date.
   536  	// We avoid the nested build ID problem in the previous special case
   537  	// by recording the test results in the cache under the action ID half.
   538  	if len(a.triggers) == 1 && a.triggers[0].TryCache != nil && a.triggers[0].TryCache(b, a.triggers[0]) {
   539  		// Best effort attempt to display output from the compile and link steps.
   540  		// If it doesn't work, it doesn't work: reusing the test result is more
   541  		// important than reprinting diagnostic information.
   542  		if printOutput {
   543  			showStdout(b, c, a.Deps[0], "stdout")      // compile output
   544  			showStdout(b, c, a.Deps[0], "link-stdout") // link output
   545  		}
   546  
   547  		// Poison a.Target to catch uses later in the build.
   548  		a.Target = "DO NOT USE -  pseudo-cache Target"
   549  		a.built = "DO NOT USE - pseudo-cache built"
   550  		return true
   551  	}
   552  
   553  	// Check to see if the action output is cached.
   554  	if file, _, err := cache.GetFile(c, actionHash); err == nil {
   555  		if a.Mode == "preprocess PGO profile" {
   556  			// Preprocessed PGO profiles don't embed a build ID, so
   557  			// skip the build ID lookup.
   558  			// TODO(prattmic): better would be to add a build ID to the format.
   559  			a.built = file
   560  			a.Target = "DO NOT USE - using cache"
   561  			return true
   562  		}
   563  		if buildID, err := buildid.ReadFile(file); err == nil {
   564  			if printOutput {
   565  				showStdout(b, c, a, "stdout")
   566  			}
   567  			a.built = file
   568  			a.Target = "DO NOT USE - using cache"
   569  			a.buildID = buildID
   570  			if a.json != nil {
   571  				a.json.BuildID = a.buildID
   572  			}
   573  			if p := a.Package; p != nil && target != "" {
   574  				p.Stale = true
   575  				// Clearer than explaining that something else is stale.
   576  				p.StaleReason = "not installed but available in build cache"
   577  			}
   578  			return true
   579  		}
   580  	}
   581  
   582  	// If we've reached this point, we can't use the cache for the action.
   583  	if p := a.Package; p != nil && !p.Stale {
   584  		p.Stale = true
   585  		p.StaleReason = "build ID mismatch"
   586  		if b.IsCmdList {
   587  			// Since we may end up printing StaleReason, include more detail.
   588  			for _, p1 := range p.Internal.Imports {
   589  				if p1.Stale && p1.StaleReason != "" {
   590  					if strings.HasPrefix(p1.StaleReason, "stale dependency: ") {
   591  						p.StaleReason = p1.StaleReason
   592  						break
   593  					}
   594  					if strings.HasPrefix(p.StaleReason, "build ID mismatch") {
   595  						p.StaleReason = "stale dependency: " + p1.ImportPath
   596  					}
   597  				}
   598  			}
   599  		}
   600  	}
   601  
   602  	// Begin saving output for later writing to cache.
   603  	a.output = []byte{}
   604  	return false
   605  }
   606  
   607  func showStdout(b *Builder, c cache.Cache, a *Action, key string) error {
   608  	actionID := a.actionID
   609  
   610  	stdout, stdoutEntry, err := cache.GetBytes(c, cache.Subkey(actionID, key))
   611  	if err != nil {
   612  		return err
   613  	}
   614  
   615  	if len(stdout) > 0 {
   616  		sh := b.Shell(a)
   617  		if cfg.BuildX || cfg.BuildN {
   618  			sh.ShowCmd("", "%s  # internal", joinUnambiguously(str.StringList("cat", c.OutputFile(stdoutEntry.OutputID))))
   619  		}
   620  		if !cfg.BuildN {
   621  			sh.Print(string(stdout))
   622  		}
   623  	}
   624  	return nil
   625  }
   626  
   627  // flushOutput flushes the output being queued in a.
   628  func (b *Builder) flushOutput(a *Action) {
   629  	b.Shell(a).Print(string(a.output))
   630  	a.output = nil
   631  }
   632  
   633  // updateBuildID updates the build ID in the target written by action a.
   634  // It requires that useCache was called for action a and returned false,
   635  // and that the build was then carried out and given the temporary
   636  // a.buildID to record as the build ID in the resulting package or binary.
   637  // updateBuildID computes the final content ID and updates the build IDs
   638  // in the binary.
   639  //
   640  // Keep in sync with src/cmd/buildid/buildid.go
   641  func (b *Builder) updateBuildID(a *Action, target string, rewrite bool) error {
   642  	sh := b.Shell(a)
   643  
   644  	if cfg.BuildX || cfg.BuildN {
   645  		if rewrite {
   646  			sh.ShowCmd("", "%s # internal", joinUnambiguously(str.StringList(base.Tool("buildid"), "-w", target)))
   647  		}
   648  		if cfg.BuildN {
   649  			return nil
   650  		}
   651  	}
   652  
   653  	c := cache.Default()
   654  
   655  	// Cache output from compile/link, even if we don't do the rest.
   656  	switch a.Mode {
   657  	case "build":
   658  		cache.PutBytes(c, cache.Subkey(a.actionID, "stdout"), a.output)
   659  	case "link":
   660  		// Even though we don't cache the binary, cache the linker text output.
   661  		// We might notice that an installed binary is up-to-date but still
   662  		// want to pretend to have run the linker.
   663  		// Store it under the main package's action ID
   664  		// to make it easier to find when that's all we have.
   665  		for _, a1 := range a.Deps {
   666  			if p1 := a1.Package; p1 != nil && p1.Name == "main" {
   667  				cache.PutBytes(c, cache.Subkey(a1.actionID, "link-stdout"), a.output)
   668  				break
   669  			}
   670  		}
   671  	}
   672  
   673  	// Find occurrences of old ID and compute new content-based ID.
   674  	r, err := os.Open(target)
   675  	if err != nil {
   676  		return err
   677  	}
   678  	matches, hash, err := buildid.FindAndHash(r, a.buildID, 0)
   679  	r.Close()
   680  	if err != nil {
   681  		return err
   682  	}
   683  	newID := a.buildID[:strings.LastIndex(a.buildID, buildIDSeparator)] + buildIDSeparator + buildid.HashToString(hash)
   684  	if len(newID) != len(a.buildID) {
   685  		return fmt.Errorf("internal error: build ID length mismatch %q vs %q", a.buildID, newID)
   686  	}
   687  
   688  	// Replace with new content-based ID.
   689  	a.buildID = newID
   690  	if a.json != nil {
   691  		a.json.BuildID = a.buildID
   692  	}
   693  	if len(matches) == 0 {
   694  		// Assume the user specified -buildid= to override what we were going to choose.
   695  		return nil
   696  	}
   697  
   698  	if rewrite {
   699  		w, err := os.OpenFile(target, os.O_RDWR, 0)
   700  		if err != nil {
   701  			return err
   702  		}
   703  		err = buildid.Rewrite(w, matches, newID)
   704  		if err != nil {
   705  			w.Close()
   706  			return err
   707  		}
   708  		if err := w.Close(); err != nil {
   709  			return err
   710  		}
   711  	}
   712  
   713  	// Cache package builds, but not binaries (link steps).
   714  	// The expectation is that binaries are not reused
   715  	// nearly as often as individual packages, and they're
   716  	// much larger, so the cache-footprint-to-utility ratio
   717  	// of binaries is much lower for binaries.
   718  	// Not caching the link step also makes sure that repeated "go run" at least
   719  	// always rerun the linker, so that they don't get too fast.
   720  	// (We don't want people thinking go is a scripting language.)
   721  	// Note also that if we start caching binaries, then we will
   722  	// copy the binaries out of the cache to run them, and then
   723  	// that will mean the go process is itself writing a binary
   724  	// and then executing it, so we will need to defend against
   725  	// ETXTBSY problems as discussed in exec.go and golang.org/issue/22220.
   726  	if a.Mode == "build" {
   727  		r, err := os.Open(target)
   728  		if err == nil {
   729  			if a.output == nil {
   730  				panic("internal error: a.output not set")
   731  			}
   732  			outputID, _, err := c.Put(a.actionID, r)
   733  			r.Close()
   734  			if err == nil && cfg.BuildX {
   735  				sh.ShowCmd("", "%s # internal", joinUnambiguously(str.StringList("cp", target, c.OutputFile(outputID))))
   736  			}
   737  			if b.NeedExport {
   738  				if err != nil {
   739  					return err
   740  				}
   741  				a.Package.Export = c.OutputFile(outputID)
   742  				a.Package.BuildID = a.buildID
   743  			}
   744  		}
   745  	}
   746  
   747  	return nil
   748  }
   749  

View as plain text