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  	return b.toolIDCache.Do(name, func() string {
   148  		path := base.Tool(name)
   149  		desc := "go tool " + name
   150  
   151  		// Special case: undocumented -vettool overrides usual vet,
   152  		// for testing vet or supplying an alternative analysis tool.
   153  		if name == "vet" && VetTool != "" {
   154  			path = VetTool
   155  			desc = VetTool
   156  		}
   157  
   158  		cmdline := str.StringList(cfg.BuildToolexec, path, "-V=full")
   159  		cmd := exec.Command(cmdline[0], cmdline[1:]...)
   160  		var stdout, stderr strings.Builder
   161  		cmd.Stdout = &stdout
   162  		cmd.Stderr = &stderr
   163  		if err := cmd.Run(); err != nil {
   164  			if stderr.Len() > 0 {
   165  				os.Stderr.WriteString(stderr.String())
   166  			}
   167  			base.Fatalf("go: error obtaining buildID for %s: %v", desc, err)
   168  		}
   169  
   170  		line := stdout.String()
   171  		f := strings.Fields(line)
   172  		if len(f) < 3 || f[0] != name && path != VetTool || f[1] != "version" || f[2] == "devel" && !strings.HasPrefix(f[len(f)-1], "buildID=") {
   173  			base.Fatalf("go: parsing buildID from %s -V=full: unexpected output:\n\t%s", desc, line)
   174  		}
   175  		if f[2] == "devel" {
   176  			// On the development branch, use the content ID part of the build ID.
   177  			return contentID(f[len(f)-1])
   178  		}
   179  		// For a release, the output is like: "compile version go1.9.1 X:framepointer".
   180  		// Use the whole line.
   181  		return strings.TrimSpace(line)
   182  	})
   183  }
   184  
   185  // gccToolID returns the unique ID to use for a tool that is invoked
   186  // by the GCC driver. This is used particularly for gccgo, but this can also
   187  // be used for gcc, g++, gfortran, etc.; those tools all use the GCC
   188  // driver under different names. The approach used here should also
   189  // work for sufficiently new versions of clang. Unlike toolID, the
   190  // name argument is the program to run. The language argument is the
   191  // type of input file as passed to the GCC driver's -x option.
   192  //
   193  // For these tools we have no -V=full option to dump the build ID,
   194  // but we can run the tool with -v -### to reliably get the compiler proper
   195  // and hash that. That will work in the presence of -toolexec.
   196  //
   197  // In order to get reproducible builds for released compilers, we
   198  // detect a released compiler by the absence of "experimental" in the
   199  // --version output, and in that case we just use the version string.
   200  //
   201  // gccToolID also returns the underlying executable for the compiler.
   202  // The caller assumes that stat of the exe can be used, combined with the id,
   203  // to detect changes in the underlying compiler. The returned exe can be empty,
   204  // which means to rely only on the id.
   205  func (b *Builder) gccToolID(name, language string) (id, exe string, err error) {
   206  	//TODO: Use par.Cache instead of a mutex and a map. See Builder.toolID.
   207  	key := name + "." + language
   208  	b.id.Lock()
   209  	id = b.gccToolIDCache[key]
   210  	exe = b.gccToolIDCache[key+".exe"]
   211  	b.id.Unlock()
   212  
   213  	if id != "" {
   214  		return id, exe, nil
   215  	}
   216  
   217  	// Invoke the driver with -### to see the subcommands and the
   218  	// version strings. Use -x to set the language. Pretend to
   219  	// compile an empty file on standard input.
   220  	cmdline := str.StringList(cfg.BuildToolexec, name, "-###", "-x", language, "-c", "-")
   221  	cmd := exec.Command(cmdline[0], cmdline[1:]...)
   222  	// Force untranslated output so that we see the string "version".
   223  	cmd.Env = append(os.Environ(), "LC_ALL=C")
   224  	out, err := cmd.CombinedOutput()
   225  	if err != nil {
   226  		return "", "", fmt.Errorf("%s: %v; output: %q", name, err, out)
   227  	}
   228  
   229  	version := ""
   230  	lines := strings.Split(string(out), "\n")
   231  	for _, line := range lines {
   232  		fields := strings.Fields(line)
   233  		for i, field := range fields {
   234  			if strings.HasSuffix(field, ":") {
   235  				// Avoid parsing fields of lines like "Configured with: …", which may
   236  				// contain arbitrary substrings.
   237  				break
   238  			}
   239  			if field == "version" && i < len(fields)-1 {
   240  				// Check that the next field is plausibly a version number.
   241  				// We require only that it begins with an ASCII digit,
   242  				// since we don't know what version numbering schemes a given
   243  				// C compiler may use. (Clang and GCC mostly seem to follow the scheme X.Y.Z,
   244  				// but in https://go.dev/issue/64619 we saw "8.3 [DragonFly]", and who knows
   245  				// what other C compilers like "zig cc" might report?)
   246  				next := fields[i+1]
   247  				if len(next) > 0 && next[0] >= '0' && next[0] <= '9' {
   248  					version = line
   249  					break
   250  				}
   251  			}
   252  		}
   253  		if version != "" {
   254  			break
   255  		}
   256  	}
   257  	if version == "" {
   258  		return "", "", fmt.Errorf("%s: can not find version number in %q", name, out)
   259  	}
   260  
   261  	if !strings.Contains(version, "experimental") {
   262  		// This is a release. Use this line as the tool ID.
   263  		id = version
   264  	} else {
   265  		// This is a development version. The first line with
   266  		// a leading space is the compiler proper.
   267  		compiler := ""
   268  		for _, line := range lines {
   269  			if strings.HasPrefix(line, " ") && !strings.HasPrefix(line, " (in-process)") {
   270  				compiler = line
   271  				break
   272  			}
   273  		}
   274  		if compiler == "" {
   275  			return "", "", fmt.Errorf("%s: can not find compilation command in %q", name, out)
   276  		}
   277  
   278  		fields, _ := quoted.Split(compiler)
   279  		if len(fields) == 0 {
   280  			return "", "", fmt.Errorf("%s: compilation command confusion %q", name, out)
   281  		}
   282  		exe = fields[0]
   283  		if !strings.ContainsAny(exe, `/\`) {
   284  			if lp, err := pathcache.LookPath(exe); err == nil {
   285  				exe = lp
   286  			}
   287  		}
   288  		id, err = buildid.ReadFile(exe)
   289  		if err != nil {
   290  			return "", "", err
   291  		}
   292  
   293  		// If we can't find a build ID, use a hash.
   294  		if id == "" {
   295  			id = b.fileHash(exe)
   296  		}
   297  	}
   298  
   299  	b.id.Lock()
   300  	b.gccToolIDCache[key] = id
   301  	b.gccToolIDCache[key+".exe"] = exe
   302  	b.id.Unlock()
   303  
   304  	return id, exe, nil
   305  }
   306  
   307  // Check if assembler used by gccgo is GNU as.
   308  func assemblerIsGas() bool {
   309  	cmd := exec.Command(BuildToolchain.compiler(), "-print-prog-name=as")
   310  	assembler, err := cmd.Output()
   311  	if err == nil {
   312  		cmd := exec.Command(strings.TrimSpace(string(assembler)), "--version")
   313  		out, err := cmd.Output()
   314  		return err == nil && strings.Contains(string(out), "GNU")
   315  	} else {
   316  		return false
   317  	}
   318  }
   319  
   320  // gccgoBuildIDFile creates an assembler file that records the
   321  // action's build ID in an SHF_EXCLUDE section for ELF files or
   322  // in a CSECT in XCOFF files.
   323  func (b *Builder) gccgoBuildIDFile(a *Action) (string, error) {
   324  	sfile := a.Objdir + "_buildid.s"
   325  
   326  	var buf bytes.Buffer
   327  	if cfg.Goos == "aix" {
   328  		fmt.Fprintf(&buf, "\t.csect .go.buildid[XO]\n")
   329  	} else if (cfg.Goos != "solaris" && cfg.Goos != "illumos") || assemblerIsGas() {
   330  		fmt.Fprintf(&buf, "\t"+`.section .go.buildid,"e"`+"\n")
   331  	} else if cfg.Goarch == "sparc" || cfg.Goarch == "sparc64" {
   332  		fmt.Fprintf(&buf, "\t"+`.section ".go.buildid",#exclude`+"\n")
   333  	} else { // cfg.Goarch == "386" || cfg.Goarch == "amd64"
   334  		fmt.Fprintf(&buf, "\t"+`.section .go.buildid,#exclude`+"\n")
   335  	}
   336  	fmt.Fprintf(&buf, "\t.byte ")
   337  	for i := 0; i < len(a.buildID); i++ {
   338  		if i > 0 {
   339  			if i%8 == 0 {
   340  				fmt.Fprintf(&buf, "\n\t.byte ")
   341  			} else {
   342  				fmt.Fprintf(&buf, ",")
   343  			}
   344  		}
   345  		fmt.Fprintf(&buf, "%#02x", a.buildID[i])
   346  	}
   347  	fmt.Fprintf(&buf, "\n")
   348  	if cfg.Goos != "solaris" && cfg.Goos != "illumos" && cfg.Goos != "aix" {
   349  		secType := "@progbits"
   350  		if cfg.Goarch == "arm" {
   351  			secType = "%progbits"
   352  		}
   353  		fmt.Fprintf(&buf, "\t"+`.section .note.GNU-stack,"",%s`+"\n", secType)
   354  		fmt.Fprintf(&buf, "\t"+`.section .note.GNU-split-stack,"",%s`+"\n", secType)
   355  	}
   356  
   357  	if err := b.Shell(a).writeFile(sfile, buf.Bytes()); err != nil {
   358  		return "", err
   359  	}
   360  
   361  	return sfile, nil
   362  }
   363  
   364  // buildID returns the build ID found in the given file.
   365  // If no build ID is found, buildID returns the content hash of the file.
   366  func (b *Builder) buildID(file string) string {
   367  	b.id.Lock()
   368  	id := b.buildIDCache[file]
   369  	b.id.Unlock()
   370  
   371  	if id != "" {
   372  		return id
   373  	}
   374  
   375  	id, err := buildid.ReadFile(file)
   376  	if err != nil {
   377  		id = b.fileHash(file)
   378  	}
   379  
   380  	b.id.Lock()
   381  	b.buildIDCache[file] = id
   382  	b.id.Unlock()
   383  
   384  	return id
   385  }
   386  
   387  // fileHash returns the content hash of the named file.
   388  func (b *Builder) fileHash(file string) string {
   389  	sum, err := cache.FileHash(fsys.Actual(file))
   390  	if err != nil {
   391  		return ""
   392  	}
   393  	return buildid.HashToString(sum)
   394  }
   395  
   396  var (
   397  	counterCacheHit  = counter.New("go/buildcache/hit")
   398  	counterCacheMiss = counter.New("go/buildcache/miss")
   399  
   400  	stdlibRecompiled        = counter.New("go/buildcache/stdlib-recompiled")
   401  	stdlibRecompiledIncOnce = sync.OnceFunc(stdlibRecompiled.Inc)
   402  )
   403  
   404  // useCache tries to satisfy the action a, which has action ID actionHash,
   405  // by using a cached result from an earlier build.
   406  // If useCache decides that the cache can be used, it sets a.buildID
   407  // and a.built for use by parent actions and then returns true.
   408  // Otherwise it sets a.buildID to a temporary build ID for use in the build
   409  // and returns false. When useCache returns false the expectation is that
   410  // the caller will build the target and then call updateBuildID to finish the
   411  // build ID computation.
   412  // When useCache returns false, it may have initiated buffering of output
   413  // during a's work. The caller should defer b.flushOutput(a), to make sure
   414  // that flushOutput is eventually called regardless of whether the action
   415  // succeeds. The flushOutput call must happen after updateBuildID.
   416  func (b *Builder) useCache(a *Action, actionHash cache.ActionID, target string, printOutput bool) (ok bool) {
   417  	// The second half of the build ID here is a placeholder for the content hash.
   418  	// It's important that the overall buildID be unlikely verging on impossible
   419  	// to appear in the output by chance, but that should be taken care of by
   420  	// the actionID half; if it also appeared in the input that would be like an
   421  	// engineered 120-bit partial SHA256 collision.
   422  	a.actionID = actionHash
   423  	actionID := buildid.HashToString(actionHash)
   424  	if a.json != nil {
   425  		a.json.ActionID = actionID
   426  	}
   427  	contentID := actionID // temporary placeholder, likely unique
   428  	a.buildID = actionID + buildIDSeparator + contentID
   429  
   430  	// Executable binaries also record the main build ID in the middle.
   431  	// See "Build IDs" comment above.
   432  	if a.Mode == "link" {
   433  		mainpkg := a.Deps[0]
   434  		a.buildID = actionID + buildIDSeparator + mainpkg.buildID + buildIDSeparator + contentID
   435  	}
   436  
   437  	// If user requested -a, we force a rebuild, so don't use the cache.
   438  	if cfg.BuildA {
   439  		if p := a.Package; p != nil && !p.Stale {
   440  			p.Stale = true
   441  			p.StaleReason = "build -a flag in use"
   442  		}
   443  		// Begin saving output for later writing to cache.
   444  		a.output = []byte{}
   445  		return false
   446  	}
   447  
   448  	defer func() {
   449  		// Increment counters for cache hits and misses based on the return value
   450  		// of this function. Don't increment counters if we return early because of
   451  		// cfg.BuildA above because we don't even look at the cache in that case.
   452  		if ok {
   453  			counterCacheHit.Inc()
   454  		} else {
   455  			if a.Package != nil && a.Package.Standard {
   456  				stdlibRecompiledIncOnce()
   457  			}
   458  			counterCacheMiss.Inc()
   459  		}
   460  	}()
   461  
   462  	c := cache.Default()
   463  
   464  	if target != "" {
   465  		buildID, _ := buildid.ReadFile(target)
   466  		if strings.HasPrefix(buildID, actionID+buildIDSeparator) {
   467  			a.buildID = buildID
   468  			if a.json != nil {
   469  				a.json.BuildID = a.buildID
   470  			}
   471  			a.built = target
   472  			// Poison a.Target to catch uses later in the build.
   473  			a.Target = "DO NOT USE - " + a.Mode
   474  			return true
   475  		}
   476  		// Special case for building a main package: if the only thing we
   477  		// want the package for is to link a binary, and the binary is
   478  		// already up-to-date, then to avoid a rebuild, report the package
   479  		// as up-to-date as well. See "Build IDs" comment above.
   480  		// TODO(rsc): Rewrite this code to use a TryCache func on the link action.
   481  		if !b.NeedExport && a.Mode == "build" && len(a.triggers) == 1 && a.triggers[0].Mode == "link" {
   482  			if id := strings.Split(buildID, buildIDSeparator); len(id) == 4 && id[1] == actionID {
   483  				// Temporarily assume a.buildID is the package build ID
   484  				// stored in the installed binary, and see if that makes
   485  				// the upcoming link action ID a match. If so, report that
   486  				// we built the package, safe in the knowledge that the
   487  				// link step will not ask us for the actual package file.
   488  				// Note that (*Builder).LinkAction arranged that all of
   489  				// a.triggers[0]'s dependencies other than a are also
   490  				// dependencies of a, so that we can be sure that,
   491  				// other than a.buildID, b.linkActionID is only accessing
   492  				// build IDs of completed actions.
   493  				oldBuildID := a.buildID
   494  				a.buildID = id[1] + buildIDSeparator + id[2]
   495  				linkID := buildid.HashToString(b.linkActionID(a.triggers[0]))
   496  				if id[0] == linkID {
   497  					// Best effort attempt to display output from the compile and link steps.
   498  					// If it doesn't work, it doesn't work: reusing the cached binary is more
   499  					// important than reprinting diagnostic information.
   500  					if printOutput {
   501  						showStdout(b, c, a, "stdout")      // compile output
   502  						showStdout(b, c, a, "link-stdout") // link output
   503  					}
   504  
   505  					// Poison a.Target to catch uses later in the build.
   506  					a.Target = "DO NOT USE - main build pseudo-cache Target"
   507  					a.built = "DO NOT USE - main build pseudo-cache built"
   508  					if a.json != nil {
   509  						a.json.BuildID = a.buildID
   510  					}
   511  					return true
   512  				}
   513  				// Otherwise restore old build ID for main build.
   514  				a.buildID = oldBuildID
   515  			}
   516  		}
   517  	}
   518  
   519  	// TODO(matloob): If we end up caching all executables, the test executable will
   520  	// already be cached so building it won't do any work. But for now we won't
   521  	// cache all executables and instead only want to cache some:
   522  	// we only cache executables produced for 'go run' (and soon, for 'go tool').
   523  	//
   524  	// Special case for linking a test binary: if the only thing we
   525  	// want the binary for is to run the test, and the test result is cached,
   526  	// then to avoid the link step, report the link as up-to-date.
   527  	// We avoid the nested build ID problem in the previous special case
   528  	// by recording the test results in the cache under the action ID half.
   529  	if len(a.triggers) == 1 && a.triggers[0].TryCache != nil && a.triggers[0].TryCache(b, a.triggers[0]) {
   530  		// Best effort attempt to display output from the compile and link steps.
   531  		// If it doesn't work, it doesn't work: reusing the test result is more
   532  		// important than reprinting diagnostic information.
   533  		if printOutput {
   534  			showStdout(b, c, a.Deps[0], "stdout")      // compile output
   535  			showStdout(b, c, a.Deps[0], "link-stdout") // link output
   536  		}
   537  
   538  		// Poison a.Target to catch uses later in the build.
   539  		a.Target = "DO NOT USE -  pseudo-cache Target"
   540  		a.built = "DO NOT USE - pseudo-cache built"
   541  		return true
   542  	}
   543  
   544  	// Check to see if the action output is cached.
   545  	if file, _, err := cache.GetFile(c, actionHash); err == nil {
   546  		if a.Mode == "preprocess PGO profile" {
   547  			// Preprocessed PGO profiles don't embed a build ID, so
   548  			// skip the build ID lookup.
   549  			// TODO(prattmic): better would be to add a build ID to the format.
   550  			a.built = file
   551  			a.Target = "DO NOT USE - using cache"
   552  			return true
   553  		}
   554  		if buildID, err := buildid.ReadFile(file); err == nil {
   555  			if printOutput {
   556  				switch a.Mode {
   557  				case "link":
   558  					// The link output is stored using the build action's action ID.
   559  					// See corresponding code storing the link output in updateBuildID.
   560  					for _, a1 := range a.Deps {
   561  						showStdout(b, c, a1, "link-stdout") // link output
   562  					}
   563  				default:
   564  					showStdout(b, c, a, "stdout") // compile output
   565  				}
   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.Printf("%s", 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).Printf("%s", 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) error {
   642  	sh := b.Shell(a)
   643  
   644  	if cfg.BuildX || cfg.BuildN {
   645  		sh.ShowCmd("", "%s # internal", joinUnambiguously(str.StringList(base.Tool("buildid"), "-w", target)))
   646  		if cfg.BuildN {
   647  			return nil
   648  		}
   649  	}
   650  
   651  	c := cache.Default()
   652  
   653  	// Cache output from compile/link, even if we don't do the rest.
   654  	switch a.Mode {
   655  	case "build":
   656  		cache.PutBytes(c, cache.Subkey(a.actionID, "stdout"), a.output)
   657  	case "link":
   658  		// Even though we don't cache the binary, cache the linker text output.
   659  		// We might notice that an installed binary is up-to-date but still
   660  		// want to pretend to have run the linker.
   661  		// Store it under the main package's action ID
   662  		// to make it easier to find when that's all we have.
   663  		for _, a1 := range a.Deps {
   664  			if p1 := a1.Package; p1 != nil && p1.Name == "main" {
   665  				cache.PutBytes(c, cache.Subkey(a1.actionID, "link-stdout"), a.output)
   666  				break
   667  			}
   668  		}
   669  	}
   670  
   671  	// Find occurrences of old ID and compute new content-based ID.
   672  	r, err := os.Open(target)
   673  	if err != nil {
   674  		return err
   675  	}
   676  	matches, hash, err := buildid.FindAndHash(r, a.buildID, 0)
   677  	r.Close()
   678  	if err != nil {
   679  		return err
   680  	}
   681  	newID := a.buildID[:strings.LastIndex(a.buildID, buildIDSeparator)] + buildIDSeparator + buildid.HashToString(hash)
   682  	if len(newID) != len(a.buildID) {
   683  		return fmt.Errorf("internal error: build ID length mismatch %q vs %q", a.buildID, newID)
   684  	}
   685  
   686  	// Replace with new content-based ID.
   687  	a.buildID = newID
   688  	if a.json != nil {
   689  		a.json.BuildID = a.buildID
   690  	}
   691  	if len(matches) == 0 {
   692  		// Assume the user specified -buildid= to override what we were going to choose.
   693  		return nil
   694  	}
   695  
   696  	// Replace the build id in the file with the content-based ID.
   697  	w, err := os.OpenFile(target, os.O_RDWR, 0)
   698  	if err != nil {
   699  		return err
   700  	}
   701  	err = buildid.Rewrite(w, matches, newID)
   702  	if err != nil {
   703  		w.Close()
   704  		return err
   705  	}
   706  	if err := w.Close(); err != nil {
   707  		return err
   708  	}
   709  
   710  	// Cache package builds, and cache executable builds if
   711  	// executable caching was requested. Executables are not
   712  	// cached by default because they are not reused
   713  	// nearly as often as individual packages, and they're
   714  	// much larger, so the cache-footprint-to-utility ratio
   715  	// of executables is much lower for executables.
   716  	if a.Mode == "build" {
   717  		r, err := os.Open(target)
   718  		if err == nil {
   719  			if a.output == nil {
   720  				panic("internal error: a.output not set")
   721  			}
   722  			outputID, _, err := c.Put(a.actionID, r)
   723  			r.Close()
   724  			if err == nil && cfg.BuildX {
   725  				sh.ShowCmd("", "%s # internal", joinUnambiguously(str.StringList("cp", target, c.OutputFile(outputID))))
   726  			}
   727  			if b.NeedExport {
   728  				if err != nil {
   729  					return err
   730  				}
   731  				a.Package.Export = c.OutputFile(outputID)
   732  				a.Package.BuildID = a.buildID
   733  			}
   734  		}
   735  	}
   736  	if c, ok := c.(*cache.DiskCache); a.Mode == "link" && a.CacheExecutable && ok {
   737  		r, err := os.Open(target)
   738  		if err == nil {
   739  			if a.output == nil {
   740  				panic("internal error: a.output not set")
   741  			}
   742  			name := a.Package.Internal.ExeName
   743  			if name == "" {
   744  				name = a.Package.DefaultExecName()
   745  			}
   746  			outputID, _, err := c.PutExecutable(a.actionID, name+cfg.ExeSuffix, r)
   747  			r.Close()
   748  			if err == nil && cfg.BuildX {
   749  				sh.ShowCmd("", "%s # internal", joinUnambiguously(str.StringList("cp", target, c.OutputFile(outputID))))
   750  			}
   751  		}
   752  	}
   753  
   754  	return nil
   755  }
   756  

View as plain text