Black Lives Matter. Support the Equal Justice Initiative.

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

Documentation: cmd/go/internal/work

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