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

     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  package work
     6  
     7  import (
     8  	"bufio"
     9  	"bytes"
    10  	"fmt"
    11  	"internal/buildcfg"
    12  	"internal/platform"
    13  	"io"
    14  	"log"
    15  	"os"
    16  	"path/filepath"
    17  	"runtime"
    18  	"strings"
    19  
    20  	"cmd/go/internal/base"
    21  	"cmd/go/internal/cfg"
    22  	"cmd/go/internal/fsys"
    23  	"cmd/go/internal/gover"
    24  	"cmd/go/internal/load"
    25  	"cmd/go/internal/str"
    26  	"cmd/internal/quoted"
    27  	"crypto/sha1"
    28  )
    29  
    30  // Tests can override this by setting $TESTGO_TOOLCHAIN_VERSION.
    31  var ToolchainVersion = runtime.Version()
    32  
    33  // The Go toolchain.
    34  
    35  type gcToolchain struct{}
    36  
    37  func (gcToolchain) compiler() string {
    38  	return base.Tool("compile")
    39  }
    40  
    41  func (gcToolchain) linker() string {
    42  	return base.Tool("link")
    43  }
    44  
    45  func pkgPath(a *Action) string {
    46  	p := a.Package
    47  	ppath := p.ImportPath
    48  	if cfg.BuildBuildmode == "plugin" {
    49  		ppath = pluginPath(a)
    50  	} else if p.Name == "main" && !p.Internal.ForceLibrary {
    51  		ppath = "main"
    52  	}
    53  	return ppath
    54  }
    55  
    56  func (gcToolchain) gc(b *Builder, a *Action, archive string, importcfg, embedcfg []byte, symabis string, asmhdr bool, pgoProfile string, gofiles []string) (ofile string, output []byte, err error) {
    57  	p := a.Package
    58  	sh := b.Shell(a)
    59  	objdir := a.Objdir
    60  	if archive != "" {
    61  		ofile = archive
    62  	} else {
    63  		out := "_go_.o"
    64  		ofile = objdir + out
    65  	}
    66  
    67  	pkgpath := pkgPath(a)
    68  	defaultGcFlags := []string{"-p", pkgpath}
    69  	if p.Module != nil {
    70  		v := p.Module.GoVersion
    71  		if v == "" {
    72  			v = gover.DefaultGoModVersion
    73  		}
    74  		if allowedVersion(v) {
    75  			defaultGcFlags = append(defaultGcFlags, "-lang=go"+gover.Lang(v))
    76  		}
    77  	}
    78  	if p.Standard {
    79  		defaultGcFlags = append(defaultGcFlags, "-std")
    80  	}
    81  
    82  	// If we're giving the compiler the entire package (no C etc files), tell it that,
    83  	// so that it can give good error messages about forward declarations.
    84  	// Exceptions: a few standard packages have forward declarations for
    85  	// pieces supplied behind-the-scenes by package runtime.
    86  	extFiles := len(p.CgoFiles) + len(p.CFiles) + len(p.CXXFiles) + len(p.MFiles) + len(p.FFiles) + len(p.SFiles) + len(p.SysoFiles) + len(p.SwigFiles) + len(p.SwigCXXFiles)
    87  	if p.Standard {
    88  		switch p.ImportPath {
    89  		case "bytes", "internal/poll", "net", "os":
    90  			fallthrough
    91  		case "runtime/metrics", "runtime/pprof", "runtime/trace":
    92  			fallthrough
    93  		case "sync", "syscall", "time":
    94  			extFiles++
    95  		}
    96  	}
    97  	if extFiles == 0 {
    98  		defaultGcFlags = append(defaultGcFlags, "-complete")
    99  	}
   100  	if cfg.BuildContext.InstallSuffix != "" {
   101  		defaultGcFlags = append(defaultGcFlags, "-installsuffix", cfg.BuildContext.InstallSuffix)
   102  	}
   103  	if a.buildID != "" {
   104  		defaultGcFlags = append(defaultGcFlags, "-buildid", a.buildID)
   105  	}
   106  	if p.Internal.OmitDebug || cfg.Goos == "plan9" || cfg.Goarch == "wasm" {
   107  		defaultGcFlags = append(defaultGcFlags, "-dwarf=false")
   108  	}
   109  	if strings.HasPrefix(ToolchainVersion, "go1") && !strings.Contains(os.Args[0], "go_bootstrap") {
   110  		defaultGcFlags = append(defaultGcFlags, "-goversion", ToolchainVersion)
   111  	}
   112  	if p.Internal.Cover.Cfg != "" {
   113  		defaultGcFlags = append(defaultGcFlags, "-coveragecfg="+p.Internal.Cover.Cfg)
   114  	}
   115  	if pgoProfile != "" {
   116  		defaultGcFlags = append(defaultGcFlags, "-pgoprofile="+pgoProfile)
   117  	}
   118  	if symabis != "" {
   119  		defaultGcFlags = append(defaultGcFlags, "-symabis", symabis)
   120  	}
   121  
   122  	gcflags := str.StringList(forcedGcflags, p.Internal.Gcflags)
   123  	if p.Internal.FuzzInstrument {
   124  		gcflags = append(gcflags, fuzzInstrumentFlags()...)
   125  	}
   126  	// Add -c=N to use concurrent backend compilation, if possible.
   127  	if c := gcBackendConcurrency(gcflags); c > 1 {
   128  		defaultGcFlags = append(defaultGcFlags, fmt.Sprintf("-c=%d", c))
   129  	}
   130  
   131  	args := []any{cfg.BuildToolexec, base.Tool("compile"), "-o", ofile, "-trimpath", a.trimpath(), defaultGcFlags, gcflags}
   132  	if p.Internal.LocalPrefix == "" {
   133  		args = append(args, "-nolocalimports")
   134  	} else {
   135  		args = append(args, "-D", p.Internal.LocalPrefix)
   136  	}
   137  	if importcfg != nil {
   138  		if err := sh.writeFile(objdir+"importcfg", importcfg); err != nil {
   139  			return "", nil, err
   140  		}
   141  		args = append(args, "-importcfg", objdir+"importcfg")
   142  	}
   143  	if embedcfg != nil {
   144  		if err := sh.writeFile(objdir+"embedcfg", embedcfg); err != nil {
   145  			return "", nil, err
   146  		}
   147  		args = append(args, "-embedcfg", objdir+"embedcfg")
   148  	}
   149  	if ofile == archive {
   150  		args = append(args, "-pack")
   151  	}
   152  	if asmhdr {
   153  		args = append(args, "-asmhdr", objdir+"go_asm.h")
   154  	}
   155  
   156  	for _, f := range gofiles {
   157  		f := mkAbs(p.Dir, f)
   158  
   159  		// Handle overlays. Convert path names using OverlayPath
   160  		// so these paths can be handed directly to tools.
   161  		// Deleted files won't show up in when scanning directories earlier,
   162  		// so OverlayPath will never return "" (meaning a deleted file) here.
   163  		// TODO(#39958): Handle cases where the package directory
   164  		// doesn't exist on disk (this can happen when all the package's
   165  		// files are in an overlay): the code expects the package directory
   166  		// to exist and runs some tools in that directory.
   167  		// TODO(#39958): Process the overlays when the
   168  		// gofiles, cgofiles, cfiles, sfiles, and cxxfiles variables are
   169  		// created in (*Builder).build. Doing that requires rewriting the
   170  		// code that uses those values to expect absolute paths.
   171  		f, _ = fsys.OverlayPath(f)
   172  
   173  		args = append(args, f)
   174  	}
   175  
   176  	output, err = sh.runOut(base.Cwd(), nil, args...)
   177  	return ofile, output, err
   178  }
   179  
   180  // gcBackendConcurrency returns the backend compiler concurrency level for a package compilation.
   181  func gcBackendConcurrency(gcflags []string) int {
   182  	// First, check whether we can use -c at all for this compilation.
   183  	canDashC := concurrentGCBackendCompilationEnabledByDefault
   184  
   185  	switch e := os.Getenv("GO19CONCURRENTCOMPILATION"); e {
   186  	case "0":
   187  		canDashC = false
   188  	case "1":
   189  		canDashC = true
   190  	case "":
   191  		// Not set. Use default.
   192  	default:
   193  		log.Fatalf("GO19CONCURRENTCOMPILATION must be 0, 1, or unset, got %q", e)
   194  	}
   195  
   196  	// TODO: Test and delete these conditions.
   197  	if cfg.ExperimentErr != nil || cfg.Experiment.FieldTrack || cfg.Experiment.PreemptibleLoops {
   198  		canDashC = false
   199  	}
   200  
   201  	if !canDashC {
   202  		return 1
   203  	}
   204  
   205  	// Decide how many concurrent backend compilations to allow.
   206  	//
   207  	// If we allow too many, in theory we might end up with p concurrent processes,
   208  	// each with c concurrent backend compiles, all fighting over the same resources.
   209  	// However, in practice, that seems not to happen too much.
   210  	// Most build graphs are surprisingly serial, so p==1 for much of the build.
   211  	// Furthermore, concurrent backend compilation is only enabled for a part
   212  	// of the overall compiler execution, so c==1 for much of the build.
   213  	// So don't worry too much about that interaction for now.
   214  	//
   215  	// However, in practice, setting c above 4 tends not to help very much.
   216  	// See the analysis in CL 41192.
   217  	//
   218  	// TODO(josharian): attempt to detect whether this particular compilation
   219  	// is likely to be a bottleneck, e.g. when:
   220  	//   - it has no successor packages to compile (usually package main)
   221  	//   - all paths through the build graph pass through it
   222  	//   - critical path scheduling says it is high priority
   223  	// and in such a case, set c to runtime.GOMAXPROCS(0).
   224  	// By default this is the same as runtime.NumCPU.
   225  	// We do this now when p==1.
   226  	// To limit parallelism, set GOMAXPROCS below numCPU; this may be useful
   227  	// on a low-memory builder, or if a deterministic build order is required.
   228  	c := runtime.GOMAXPROCS(0)
   229  	if cfg.BuildP == 1 {
   230  		// No process parallelism, do not cap compiler parallelism.
   231  		return c
   232  	}
   233  	// Some process parallelism. Set c to min(4, maxprocs).
   234  	if c > 4 {
   235  		c = 4
   236  	}
   237  	return c
   238  }
   239  
   240  // trimpath returns the -trimpath argument to use
   241  // when compiling the action.
   242  func (a *Action) trimpath() string {
   243  	// Keep in sync with Builder.ccompile
   244  	// The trimmed paths are a little different, but we need to trim in the
   245  	// same situations.
   246  
   247  	// Strip the object directory entirely.
   248  	objdir := a.Objdir
   249  	if len(objdir) > 1 && objdir[len(objdir)-1] == filepath.Separator {
   250  		objdir = objdir[:len(objdir)-1]
   251  	}
   252  	rewrite := ""
   253  
   254  	rewriteDir := a.Package.Dir
   255  	if cfg.BuildTrimpath {
   256  		importPath := a.Package.Internal.OrigImportPath
   257  		if m := a.Package.Module; m != nil && m.Version != "" {
   258  			rewriteDir = m.Path + "@" + m.Version + strings.TrimPrefix(importPath, m.Path)
   259  		} else {
   260  			rewriteDir = importPath
   261  		}
   262  		rewrite += a.Package.Dir + "=>" + rewriteDir + ";"
   263  	}
   264  
   265  	// Add rewrites for overlays. The 'from' and 'to' paths in overlays don't need to have
   266  	// same basename, so go from the overlay contents file path (passed to the compiler)
   267  	// to the path the disk path would be rewritten to.
   268  
   269  	cgoFiles := make(map[string]bool)
   270  	for _, f := range a.Package.CgoFiles {
   271  		cgoFiles[f] = true
   272  	}
   273  
   274  	// TODO(matloob): Higher up in the stack, when the logic for deciding when to make copies
   275  	// of c/c++/m/f/hfiles is consolidated, use the same logic that Build uses to determine
   276  	// whether to create the copies in objdir to decide whether to rewrite objdir to the
   277  	// package directory here.
   278  	var overlayNonGoRewrites string // rewrites for non-go files
   279  	hasCgoOverlay := false
   280  	if fsys.OverlayFile != "" {
   281  		for _, filename := range a.Package.AllFiles() {
   282  			path := filename
   283  			if !filepath.IsAbs(path) {
   284  				path = filepath.Join(a.Package.Dir, path)
   285  			}
   286  			base := filepath.Base(path)
   287  			isGo := strings.HasSuffix(filename, ".go") || strings.HasSuffix(filename, ".s")
   288  			isCgo := cgoFiles[filename] || !isGo
   289  			overlayPath, isOverlay := fsys.OverlayPath(path)
   290  			if isCgo && isOverlay {
   291  				hasCgoOverlay = true
   292  			}
   293  			if !isCgo && isOverlay {
   294  				rewrite += overlayPath + "=>" + filepath.Join(rewriteDir, base) + ";"
   295  			} else if isCgo {
   296  				// Generate rewrites for non-Go files copied to files in objdir.
   297  				if filepath.Dir(path) == a.Package.Dir {
   298  					// This is a file copied to objdir.
   299  					overlayNonGoRewrites += filepath.Join(objdir, base) + "=>" + filepath.Join(rewriteDir, base) + ";"
   300  				}
   301  			} else {
   302  				// Non-overlay Go files are covered by the a.Package.Dir rewrite rule above.
   303  			}
   304  		}
   305  	}
   306  	if hasCgoOverlay {
   307  		rewrite += overlayNonGoRewrites
   308  	}
   309  	rewrite += objdir + "=>"
   310  
   311  	return rewrite
   312  }
   313  
   314  func asmArgs(a *Action, p *load.Package) []any {
   315  	// Add -I pkg/GOOS_GOARCH so #include "textflag.h" works in .s files.
   316  	inc := filepath.Join(cfg.GOROOT, "pkg", "include")
   317  	pkgpath := pkgPath(a)
   318  	args := []any{cfg.BuildToolexec, base.Tool("asm"), "-p", pkgpath, "-trimpath", a.trimpath(), "-I", a.Objdir, "-I", inc, "-D", "GOOS_" + cfg.Goos, "-D", "GOARCH_" + cfg.Goarch, forcedAsmflags, p.Internal.Asmflags}
   319  	if p.ImportPath == "runtime" && cfg.Goarch == "386" {
   320  		for _, arg := range forcedAsmflags {
   321  			if arg == "-dynlink" {
   322  				args = append(args, "-D=GOBUILDMODE_shared=1")
   323  			}
   324  		}
   325  	}
   326  
   327  	if cfg.Goarch == "386" {
   328  		// Define GO386_value from cfg.GO386.
   329  		args = append(args, "-D", "GO386_"+cfg.GO386)
   330  	}
   331  
   332  	if cfg.Goarch == "amd64" {
   333  		// Define GOAMD64_value from cfg.GOAMD64.
   334  		args = append(args, "-D", "GOAMD64_"+cfg.GOAMD64)
   335  	}
   336  
   337  	if cfg.Goarch == "mips" || cfg.Goarch == "mipsle" {
   338  		// Define GOMIPS_value from cfg.GOMIPS.
   339  		args = append(args, "-D", "GOMIPS_"+cfg.GOMIPS)
   340  	}
   341  
   342  	if cfg.Goarch == "mips64" || cfg.Goarch == "mips64le" {
   343  		// Define GOMIPS64_value from cfg.GOMIPS64.
   344  		args = append(args, "-D", "GOMIPS64_"+cfg.GOMIPS64)
   345  	}
   346  
   347  	if cfg.Goarch == "ppc64" || cfg.Goarch == "ppc64le" {
   348  		// Define GOPPC64_power8..N from cfg.PPC64.
   349  		// We treat each powerpc version as a superset of functionality.
   350  		switch cfg.GOPPC64 {
   351  		case "power10":
   352  			args = append(args, "-D", "GOPPC64_power10")
   353  			fallthrough
   354  		case "power9":
   355  			args = append(args, "-D", "GOPPC64_power9")
   356  			fallthrough
   357  		default: // This should always be power8.
   358  			args = append(args, "-D", "GOPPC64_power8")
   359  		}
   360  	}
   361  
   362  	if cfg.Goarch == "riscv64" {
   363  		// Define GORISCV64_value from cfg.GORISCV64.
   364  		args = append(args, "-D", "GORISCV64_"+cfg.GORISCV64)
   365  	}
   366  
   367  	if cfg.Goarch == "arm" {
   368  		// Define GOARM_value from cfg.GOARM, which can be either a version
   369  		// like "6", or a version and a FP mode, like "7,hardfloat".
   370  		switch {
   371  		case strings.Contains(cfg.GOARM, "7"):
   372  			args = append(args, "-D", "GOARM_7")
   373  			fallthrough
   374  		case strings.Contains(cfg.GOARM, "6"):
   375  			args = append(args, "-D", "GOARM_6")
   376  			fallthrough
   377  		default:
   378  			args = append(args, "-D", "GOARM_5")
   379  		}
   380  	}
   381  
   382  	if cfg.Goarch == "arm64" {
   383  		g, err := buildcfg.ParseGoarm64(cfg.GOARM64)
   384  		if err == nil && g.LSE {
   385  			args = append(args, "-D", "GOARM64_LSE")
   386  		}
   387  	}
   388  
   389  	return args
   390  }
   391  
   392  func (gcToolchain) asm(b *Builder, a *Action, sfiles []string) ([]string, error) {
   393  	p := a.Package
   394  	args := asmArgs(a, p)
   395  
   396  	var ofiles []string
   397  	for _, sfile := range sfiles {
   398  		overlayPath, _ := fsys.OverlayPath(mkAbs(p.Dir, sfile))
   399  		ofile := a.Objdir + sfile[:len(sfile)-len(".s")] + ".o"
   400  		ofiles = append(ofiles, ofile)
   401  		args1 := append(args, "-o", ofile, overlayPath)
   402  		if err := b.Shell(a).run(p.Dir, p.ImportPath, nil, args1...); err != nil {
   403  			return nil, err
   404  		}
   405  	}
   406  	return ofiles, nil
   407  }
   408  
   409  func (gcToolchain) symabis(b *Builder, a *Action, sfiles []string) (string, error) {
   410  	sh := b.Shell(a)
   411  
   412  	mkSymabis := func(p *load.Package, sfiles []string, path string) error {
   413  		args := asmArgs(a, p)
   414  		args = append(args, "-gensymabis", "-o", path)
   415  		for _, sfile := range sfiles {
   416  			if p.ImportPath == "runtime/cgo" && strings.HasPrefix(sfile, "gcc_") {
   417  				continue
   418  			}
   419  			op, _ := fsys.OverlayPath(mkAbs(p.Dir, sfile))
   420  			args = append(args, op)
   421  		}
   422  
   423  		// Supply an empty go_asm.h as if the compiler had been run.
   424  		// -gensymabis parsing is lax enough that we don't need the
   425  		// actual definitions that would appear in go_asm.h.
   426  		if err := sh.writeFile(a.Objdir+"go_asm.h", nil); err != nil {
   427  			return err
   428  		}
   429  
   430  		return sh.run(p.Dir, p.ImportPath, nil, args...)
   431  	}
   432  
   433  	var symabis string // Only set if we actually create the file
   434  	p := a.Package
   435  	if len(sfiles) != 0 {
   436  		symabis = a.Objdir + "symabis"
   437  		if err := mkSymabis(p, sfiles, symabis); err != nil {
   438  			return "", err
   439  		}
   440  	}
   441  
   442  	return symabis, nil
   443  }
   444  
   445  // toolVerify checks that the command line args writes the same output file
   446  // if run using newTool instead.
   447  // Unused now but kept around for future use.
   448  func toolVerify(a *Action, b *Builder, p *load.Package, newTool string, ofile string, args []any) error {
   449  	newArgs := make([]any, len(args))
   450  	copy(newArgs, args)
   451  	newArgs[1] = base.Tool(newTool)
   452  	newArgs[3] = ofile + ".new" // x.6 becomes x.6.new
   453  	if err := b.Shell(a).run(p.Dir, p.ImportPath, nil, newArgs...); err != nil {
   454  		return err
   455  	}
   456  	data1, err := os.ReadFile(ofile)
   457  	if err != nil {
   458  		return err
   459  	}
   460  	data2, err := os.ReadFile(ofile + ".new")
   461  	if err != nil {
   462  		return err
   463  	}
   464  	if !bytes.Equal(data1, data2) {
   465  		return fmt.Errorf("%s and %s produced different output files:\n%s\n%s", filepath.Base(args[1].(string)), newTool, strings.Join(str.StringList(args...), " "), strings.Join(str.StringList(newArgs...), " "))
   466  	}
   467  	os.Remove(ofile + ".new")
   468  	return nil
   469  }
   470  
   471  func (gcToolchain) pack(b *Builder, a *Action, afile string, ofiles []string) error {
   472  	var absOfiles []string
   473  	for _, f := range ofiles {
   474  		absOfiles = append(absOfiles, mkAbs(a.Objdir, f))
   475  	}
   476  	absAfile := mkAbs(a.Objdir, afile)
   477  
   478  	// The archive file should have been created by the compiler.
   479  	// Since it used to not work that way, verify.
   480  	if !cfg.BuildN {
   481  		if _, err := os.Stat(absAfile); err != nil {
   482  			base.Fatalf("os.Stat of archive file failed: %v", err)
   483  		}
   484  	}
   485  
   486  	p := a.Package
   487  	sh := b.Shell(a)
   488  	if cfg.BuildN || cfg.BuildX {
   489  		cmdline := str.StringList(base.Tool("pack"), "r", absAfile, absOfiles)
   490  		sh.ShowCmd(p.Dir, "%s # internal", joinUnambiguously(cmdline))
   491  	}
   492  	if cfg.BuildN {
   493  		return nil
   494  	}
   495  	if err := packInternal(absAfile, absOfiles); err != nil {
   496  		return sh.reportCmd("", "", nil, err)
   497  	}
   498  	return nil
   499  }
   500  
   501  func packInternal(afile string, ofiles []string) error {
   502  	dst, err := os.OpenFile(afile, os.O_WRONLY|os.O_APPEND, 0)
   503  	if err != nil {
   504  		return err
   505  	}
   506  	defer dst.Close() // only for error returns or panics
   507  	w := bufio.NewWriter(dst)
   508  
   509  	for _, ofile := range ofiles {
   510  		src, err := os.Open(ofile)
   511  		if err != nil {
   512  			return err
   513  		}
   514  		fi, err := src.Stat()
   515  		if err != nil {
   516  			src.Close()
   517  			return err
   518  		}
   519  		// Note: Not using %-16.16s format because we care
   520  		// about bytes, not runes.
   521  		name := fi.Name()
   522  		if len(name) > 16 {
   523  			name = name[:16]
   524  		} else {
   525  			name += strings.Repeat(" ", 16-len(name))
   526  		}
   527  		size := fi.Size()
   528  		fmt.Fprintf(w, "%s%-12d%-6d%-6d%-8o%-10d`\n",
   529  			name, 0, 0, 0, 0644, size)
   530  		n, err := io.Copy(w, src)
   531  		src.Close()
   532  		if err == nil && n < size {
   533  			err = io.ErrUnexpectedEOF
   534  		} else if err == nil && n > size {
   535  			err = fmt.Errorf("file larger than size reported by stat")
   536  		}
   537  		if err != nil {
   538  			return fmt.Errorf("copying %s to %s: %v", ofile, afile, err)
   539  		}
   540  		if size&1 != 0 {
   541  			w.WriteByte(0)
   542  		}
   543  	}
   544  
   545  	if err := w.Flush(); err != nil {
   546  		return err
   547  	}
   548  	return dst.Close()
   549  }
   550  
   551  // setextld sets the appropriate linker flags for the specified compiler.
   552  func setextld(ldflags []string, compiler []string) ([]string, error) {
   553  	for _, f := range ldflags {
   554  		if f == "-extld" || strings.HasPrefix(f, "-extld=") {
   555  			// don't override -extld if supplied
   556  			return ldflags, nil
   557  		}
   558  	}
   559  	joined, err := quoted.Join(compiler)
   560  	if err != nil {
   561  		return nil, err
   562  	}
   563  	return append(ldflags, "-extld="+joined), nil
   564  }
   565  
   566  // pluginPath computes the package path for a plugin main package.
   567  //
   568  // This is typically the import path of the main package p, unless the
   569  // plugin is being built directly from source files. In that case we
   570  // combine the package build ID with the contents of the main package
   571  // source files. This allows us to identify two different plugins
   572  // built from two source files with the same name.
   573  func pluginPath(a *Action) string {
   574  	p := a.Package
   575  	if p.ImportPath != "command-line-arguments" {
   576  		return p.ImportPath
   577  	}
   578  	h := sha1.New()
   579  	buildID := a.buildID
   580  	if a.Mode == "link" {
   581  		// For linking, use the main package's build ID instead of
   582  		// the binary's build ID, so it is the same hash used in
   583  		// compiling and linking.
   584  		// When compiling, we use actionID/actionID (instead of
   585  		// actionID/contentID) as a temporary build ID to compute
   586  		// the hash. Do the same here. (See buildid.go:useCache)
   587  		// The build ID matters because it affects the overall hash
   588  		// in the plugin's pseudo-import path returned below.
   589  		// We need to use the same import path when compiling and linking.
   590  		id := strings.Split(buildID, buildIDSeparator)
   591  		buildID = id[1] + buildIDSeparator + id[1]
   592  	}
   593  	fmt.Fprintf(h, "build ID: %s\n", buildID)
   594  	for _, file := range str.StringList(p.GoFiles, p.CgoFiles, p.SFiles) {
   595  		data, err := os.ReadFile(filepath.Join(p.Dir, file))
   596  		if err != nil {
   597  			base.Fatalf("go: %s", err)
   598  		}
   599  		h.Write(data)
   600  	}
   601  	return fmt.Sprintf("plugin/unnamed-%x", h.Sum(nil))
   602  }
   603  
   604  func (gcToolchain) ld(b *Builder, root *Action, targetPath, importcfg, mainpkg string) error {
   605  	cxx := len(root.Package.CXXFiles) > 0 || len(root.Package.SwigCXXFiles) > 0
   606  	for _, a := range root.Deps {
   607  		if a.Package != nil && (len(a.Package.CXXFiles) > 0 || len(a.Package.SwigCXXFiles) > 0) {
   608  			cxx = true
   609  		}
   610  	}
   611  	var ldflags []string
   612  	if cfg.BuildContext.InstallSuffix != "" {
   613  		ldflags = append(ldflags, "-installsuffix", cfg.BuildContext.InstallSuffix)
   614  	}
   615  	if root.Package.Internal.OmitDebug {
   616  		ldflags = append(ldflags, "-s", "-w")
   617  	}
   618  	if cfg.BuildBuildmode == "plugin" {
   619  		ldflags = append(ldflags, "-pluginpath", pluginPath(root))
   620  	}
   621  
   622  	// Store BuildID inside toolchain binaries as a unique identifier of the
   623  	// tool being run, for use by content-based staleness determination.
   624  	if root.Package.Goroot && strings.HasPrefix(root.Package.ImportPath, "cmd/") {
   625  		// External linking will include our build id in the external
   626  		// linker's build id, which will cause our build id to not
   627  		// match the next time the tool is built.
   628  		// Rely on the external build id instead.
   629  		if !platform.MustLinkExternal(cfg.Goos, cfg.Goarch, false) {
   630  			ldflags = append(ldflags, "-X=cmd/internal/objabi.buildID="+root.buildID)
   631  		}
   632  	}
   633  
   634  	// Store default GODEBUG in binaries.
   635  	if root.Package.DefaultGODEBUG != "" {
   636  		ldflags = append(ldflags, "-X=runtime.godebugDefault="+root.Package.DefaultGODEBUG)
   637  	}
   638  
   639  	// If the user has not specified the -extld option, then specify the
   640  	// appropriate linker. In case of C++ code, use the compiler named
   641  	// by the CXX environment variable or defaultCXX if CXX is not set.
   642  	// Else, use the CC environment variable and defaultCC as fallback.
   643  	var compiler []string
   644  	if cxx {
   645  		compiler = envList("CXX", cfg.DefaultCXX(cfg.Goos, cfg.Goarch))
   646  	} else {
   647  		compiler = envList("CC", cfg.DefaultCC(cfg.Goos, cfg.Goarch))
   648  	}
   649  	ldflags = append(ldflags, "-buildmode="+ldBuildmode)
   650  	if root.buildID != "" {
   651  		ldflags = append(ldflags, "-buildid="+root.buildID)
   652  	}
   653  	ldflags = append(ldflags, forcedLdflags...)
   654  	ldflags = append(ldflags, root.Package.Internal.Ldflags...)
   655  	ldflags, err := setextld(ldflags, compiler)
   656  	if err != nil {
   657  		return err
   658  	}
   659  
   660  	// On OS X when using external linking to build a shared library,
   661  	// the argument passed here to -o ends up recorded in the final
   662  	// shared library in the LC_ID_DYLIB load command.
   663  	// To avoid putting the temporary output directory name there
   664  	// (and making the resulting shared library useless),
   665  	// run the link in the output directory so that -o can name
   666  	// just the final path element.
   667  	// On Windows, DLL file name is recorded in PE file
   668  	// export section, so do like on OS X.
   669  	// On Linux, for a shared object, at least with the Gold linker,
   670  	// the output file path is recorded in the .gnu.version_d section.
   671  	dir := "."
   672  	if cfg.BuildBuildmode == "c-shared" || cfg.BuildBuildmode == "plugin" {
   673  		dir, targetPath = filepath.Split(targetPath)
   674  	}
   675  
   676  	env := []string{}
   677  	// When -trimpath is used, GOROOT is cleared
   678  	if cfg.BuildTrimpath {
   679  		env = append(env, "GOROOT=")
   680  	} else {
   681  		env = append(env, "GOROOT="+cfg.GOROOT)
   682  	}
   683  	return b.Shell(root).run(dir, root.Package.ImportPath, env, cfg.BuildToolexec, base.Tool("link"), "-o", targetPath, "-importcfg", importcfg, ldflags, mainpkg)
   684  }
   685  
   686  func (gcToolchain) ldShared(b *Builder, root *Action, toplevelactions []*Action, targetPath, importcfg string, allactions []*Action) error {
   687  	ldflags := []string{"-installsuffix", cfg.BuildContext.InstallSuffix}
   688  	ldflags = append(ldflags, "-buildmode=shared")
   689  	ldflags = append(ldflags, forcedLdflags...)
   690  	ldflags = append(ldflags, root.Package.Internal.Ldflags...)
   691  	cxx := false
   692  	for _, a := range allactions {
   693  		if a.Package != nil && (len(a.Package.CXXFiles) > 0 || len(a.Package.SwigCXXFiles) > 0) {
   694  			cxx = true
   695  		}
   696  	}
   697  	// If the user has not specified the -extld option, then specify the
   698  	// appropriate linker. In case of C++ code, use the compiler named
   699  	// by the CXX environment variable or defaultCXX if CXX is not set.
   700  	// Else, use the CC environment variable and defaultCC as fallback.
   701  	var compiler []string
   702  	if cxx {
   703  		compiler = envList("CXX", cfg.DefaultCXX(cfg.Goos, cfg.Goarch))
   704  	} else {
   705  		compiler = envList("CC", cfg.DefaultCC(cfg.Goos, cfg.Goarch))
   706  	}
   707  	ldflags, err := setextld(ldflags, compiler)
   708  	if err != nil {
   709  		return err
   710  	}
   711  	for _, d := range toplevelactions {
   712  		if !strings.HasSuffix(d.Target, ".a") { // omit unsafe etc and actions for other shared libraries
   713  			continue
   714  		}
   715  		ldflags = append(ldflags, d.Package.ImportPath+"="+d.Target)
   716  	}
   717  	return b.Shell(root).run(".", targetPath, nil, cfg.BuildToolexec, base.Tool("link"), "-o", targetPath, "-importcfg", importcfg, ldflags)
   718  }
   719  
   720  func (gcToolchain) cc(b *Builder, a *Action, ofile, cfile string) error {
   721  	return fmt.Errorf("%s: C source files not supported without cgo", mkAbs(a.Package.Dir, cfile))
   722  }
   723  

View as plain text