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

View as plain text