]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/go/internal/work/exec.go
internal/buildcfg: move build configuration out of cmd/internal/objabi
[gostls13.git] / src / cmd / go / internal / work / exec.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 // Action graph execution.
6
7 package work
8
9 import (
10         "bytes"
11         "context"
12         "encoding/json"
13         "errors"
14         "fmt"
15         "internal/buildcfg"
16         exec "internal/execabs"
17         "internal/lazyregexp"
18         "io"
19         "io/fs"
20         "log"
21         "math/rand"
22         "os"
23         "path/filepath"
24         "regexp"
25         "runtime"
26         "strconv"
27         "strings"
28         "sync"
29         "time"
30
31         "cmd/go/internal/base"
32         "cmd/go/internal/cache"
33         "cmd/go/internal/cfg"
34         "cmd/go/internal/fsys"
35         "cmd/go/internal/load"
36         "cmd/go/internal/modload"
37         "cmd/go/internal/str"
38         "cmd/go/internal/trace"
39 )
40
41 // actionList returns the list of actions in the dag rooted at root
42 // as visited in a depth-first post-order traversal.
43 func actionList(root *Action) []*Action {
44         seen := map[*Action]bool{}
45         all := []*Action{}
46         var walk func(*Action)
47         walk = func(a *Action) {
48                 if seen[a] {
49                         return
50                 }
51                 seen[a] = true
52                 for _, a1 := range a.Deps {
53                         walk(a1)
54                 }
55                 all = append(all, a)
56         }
57         walk(root)
58         return all
59 }
60
61 // do runs the action graph rooted at root.
62 func (b *Builder) Do(ctx context.Context, root *Action) {
63         ctx, span := trace.StartSpan(ctx, "exec.Builder.Do ("+root.Mode+" "+root.Target+")")
64         defer span.Done()
65
66         if !b.IsCmdList {
67                 // If we're doing real work, take time at the end to trim the cache.
68                 c := cache.Default()
69                 defer c.Trim()
70         }
71
72         // Build list of all actions, assigning depth-first post-order priority.
73         // The original implementation here was a true queue
74         // (using a channel) but it had the effect of getting
75         // distracted by low-level leaf actions to the detriment
76         // of completing higher-level actions. The order of
77         // work does not matter much to overall execution time,
78         // but when running "go test std" it is nice to see each test
79         // results as soon as possible. The priorities assigned
80         // ensure that, all else being equal, the execution prefers
81         // to do what it would have done first in a simple depth-first
82         // dependency order traversal.
83         all := actionList(root)
84         for i, a := range all {
85                 a.priority = i
86         }
87
88         // Write action graph, without timing information, in case we fail and exit early.
89         writeActionGraph := func() {
90                 if file := cfg.DebugActiongraph; file != "" {
91                         if strings.HasSuffix(file, ".go") {
92                                 // Do not overwrite Go source code in:
93                                 //      go build -debug-actiongraph x.go
94                                 base.Fatalf("go: refusing to write action graph to %v\n", file)
95                         }
96                         js := actionGraphJSON(root)
97                         if err := os.WriteFile(file, []byte(js), 0666); err != nil {
98                                 fmt.Fprintf(os.Stderr, "go: writing action graph: %v\n", err)
99                                 base.SetExitStatus(1)
100                         }
101                 }
102         }
103         writeActionGraph()
104
105         b.readySema = make(chan bool, len(all))
106
107         // Initialize per-action execution state.
108         for _, a := range all {
109                 for _, a1 := range a.Deps {
110                         a1.triggers = append(a1.triggers, a)
111                 }
112                 a.pending = len(a.Deps)
113                 if a.pending == 0 {
114                         b.ready.push(a)
115                         b.readySema <- true
116                 }
117         }
118
119         // Handle runs a single action and takes care of triggering
120         // any actions that are runnable as a result.
121         handle := func(ctx context.Context, a *Action) {
122                 if a.json != nil {
123                         a.json.TimeStart = time.Now()
124                 }
125                 var err error
126                 if a.Func != nil && (!a.Failed || a.IgnoreFail) {
127                         // TODO(matloob): Better action descriptions
128                         desc := "Executing action "
129                         if a.Package != nil {
130                                 desc += "(" + a.Mode + " " + a.Package.Desc() + ")"
131                         }
132                         ctx, span := trace.StartSpan(ctx, desc)
133                         a.traceSpan = span
134                         for _, d := range a.Deps {
135                                 trace.Flow(ctx, d.traceSpan, a.traceSpan)
136                         }
137                         err = a.Func(b, ctx, a)
138                         span.Done()
139                 }
140                 if a.json != nil {
141                         a.json.TimeDone = time.Now()
142                 }
143
144                 // The actions run in parallel but all the updates to the
145                 // shared work state are serialized through b.exec.
146                 b.exec.Lock()
147                 defer b.exec.Unlock()
148
149                 if err != nil {
150                         if err == errPrintedOutput {
151                                 base.SetExitStatus(2)
152                         } else {
153                                 base.Errorf("%s", err)
154                         }
155                         a.Failed = true
156                 }
157
158                 for _, a0 := range a.triggers {
159                         if a.Failed {
160                                 a0.Failed = true
161                         }
162                         if a0.pending--; a0.pending == 0 {
163                                 b.ready.push(a0)
164                                 b.readySema <- true
165                         }
166                 }
167
168                 if a == root {
169                         close(b.readySema)
170                 }
171         }
172
173         var wg sync.WaitGroup
174
175         // Kick off goroutines according to parallelism.
176         // If we are using the -n flag (just printing commands)
177         // drop the parallelism to 1, both to make the output
178         // deterministic and because there is no real work anyway.
179         par := cfg.BuildP
180         if cfg.BuildN {
181                 par = 1
182         }
183         for i := 0; i < par; i++ {
184                 wg.Add(1)
185                 go func() {
186                         ctx := trace.StartGoroutine(ctx)
187                         defer wg.Done()
188                         for {
189                                 select {
190                                 case _, ok := <-b.readySema:
191                                         if !ok {
192                                                 return
193                                         }
194                                         // Receiving a value from b.readySema entitles
195                                         // us to take from the ready queue.
196                                         b.exec.Lock()
197                                         a := b.ready.pop()
198                                         b.exec.Unlock()
199                                         handle(ctx, a)
200                                 case <-base.Interrupted:
201                                         base.SetExitStatus(1)
202                                         return
203                                 }
204                         }
205                 }()
206         }
207
208         wg.Wait()
209
210         // Write action graph again, this time with timing information.
211         writeActionGraph()
212 }
213
214 // buildActionID computes the action ID for a build action.
215 func (b *Builder) buildActionID(a *Action) cache.ActionID {
216         p := a.Package
217         h := cache.NewHash("build " + p.ImportPath)
218
219         // Configuration independent of compiler toolchain.
220         // Note: buildmode has already been accounted for in buildGcflags
221         // and should not be inserted explicitly. Most buildmodes use the
222         // same compiler settings and can reuse each other's results.
223         // If not, the reason is already recorded in buildGcflags.
224         fmt.Fprintf(h, "compile\n")
225         // Only include the package directory if it may affect the output.
226         // We trim workspace paths for all packages when -trimpath is set.
227         // The compiler hides the exact value of $GOROOT
228         // when building things in GOROOT.
229         // Assume b.WorkDir is being trimmed properly.
230         // When -trimpath is used with a package built from the module cache,
231         // use the module path and version instead of the directory.
232         if !p.Goroot && !cfg.BuildTrimpath && !strings.HasPrefix(p.Dir, b.WorkDir) {
233                 fmt.Fprintf(h, "dir %s\n", p.Dir)
234         } else if cfg.BuildTrimpath && p.Module != nil {
235                 fmt.Fprintf(h, "module %s@%s\n", p.Module.Path, p.Module.Version)
236         }
237         if p.Module != nil {
238                 fmt.Fprintf(h, "go %s\n", p.Module.GoVersion)
239         }
240         fmt.Fprintf(h, "goos %s goarch %s\n", cfg.Goos, cfg.Goarch)
241         fmt.Fprintf(h, "import %q\n", p.ImportPath)
242         fmt.Fprintf(h, "omitdebug %v standard %v local %v prefix %q\n", p.Internal.OmitDebug, p.Standard, p.Internal.Local, p.Internal.LocalPrefix)
243         if cfg.BuildTrimpath {
244                 fmt.Fprintln(h, "trimpath")
245         }
246         if p.Internal.ForceLibrary {
247                 fmt.Fprintf(h, "forcelibrary\n")
248         }
249         if len(p.CgoFiles)+len(p.SwigFiles) > 0 {
250                 fmt.Fprintf(h, "cgo %q\n", b.toolID("cgo"))
251                 cppflags, cflags, cxxflags, fflags, ldflags, _ := b.CFlags(p)
252                 fmt.Fprintf(h, "CC=%q %q %q %q\n", b.ccExe(), cppflags, cflags, ldflags)
253                 if len(p.CXXFiles)+len(p.SwigFiles) > 0 {
254                         fmt.Fprintf(h, "CXX=%q %q\n", b.cxxExe(), cxxflags)
255                 }
256                 if len(p.FFiles) > 0 {
257                         fmt.Fprintf(h, "FC=%q %q\n", b.fcExe(), fflags)
258                 }
259                 // TODO(rsc): Should we include the SWIG version or Fortran/GCC/G++/Objective-C compiler versions?
260         }
261         if p.Internal.CoverMode != "" {
262                 fmt.Fprintf(h, "cover %q %q\n", p.Internal.CoverMode, b.toolID("cover"))
263         }
264         fmt.Fprintf(h, "modinfo %q\n", p.Internal.BuildInfo)
265
266         // Configuration specific to compiler toolchain.
267         switch cfg.BuildToolchainName {
268         default:
269                 base.Fatalf("buildActionID: unknown build toolchain %q", cfg.BuildToolchainName)
270         case "gc":
271                 fmt.Fprintf(h, "compile %s %q %q\n", b.toolID("compile"), forcedGcflags, p.Internal.Gcflags)
272                 if len(p.SFiles) > 0 {
273                         fmt.Fprintf(h, "asm %q %q %q\n", b.toolID("asm"), forcedAsmflags, p.Internal.Asmflags)
274                 }
275
276                 // GOARM, GOMIPS, etc.
277                 key, val := cfg.GetArchEnv()
278                 fmt.Fprintf(h, "%s=%s\n", key, val)
279
280                 if goexperiment := buildcfg.GOEXPERIMENT(); goexperiment != "" {
281                         fmt.Fprintf(h, "GOEXPERIMENT=%q\n", goexperiment)
282                 }
283
284                 // TODO(rsc): Convince compiler team not to add more magic environment variables,
285                 // or perhaps restrict the environment variables passed to subprocesses.
286                 // Because these are clumsy, undocumented special-case hacks
287                 // for debugging the compiler, they are not settable using 'go env -w',
288                 // and so here we use os.Getenv, not cfg.Getenv.
289                 magic := []string{
290                         "GOCLOBBERDEADHASH",
291                         "GOSSAFUNC",
292                         "GO_SSA_PHI_LOC_CUTOFF",
293                         "GOSSAHASH",
294                 }
295                 for _, env := range magic {
296                         if x := os.Getenv(env); x != "" {
297                                 fmt.Fprintf(h, "magic %s=%s\n", env, x)
298                         }
299                 }
300                 if os.Getenv("GOSSAHASH") != "" {
301                         for i := 0; ; i++ {
302                                 env := fmt.Sprintf("GOSSAHASH%d", i)
303                                 x := os.Getenv(env)
304                                 if x == "" {
305                                         break
306                                 }
307                                 fmt.Fprintf(h, "magic %s=%s\n", env, x)
308                         }
309                 }
310                 if os.Getenv("GSHS_LOGFILE") != "" {
311                         // Clumsy hack. Compiler writes to this log file,
312                         // so do not allow use of cache at all.
313                         // We will still write to the cache but it will be
314                         // essentially unfindable.
315                         fmt.Fprintf(h, "nocache %d\n", time.Now().UnixNano())
316                 }
317
318         case "gccgo":
319                 id, err := b.gccgoToolID(BuildToolchain.compiler(), "go")
320                 if err != nil {
321                         base.Fatalf("%v", err)
322                 }
323                 fmt.Fprintf(h, "compile %s %q %q\n", id, forcedGccgoflags, p.Internal.Gccgoflags)
324                 fmt.Fprintf(h, "pkgpath %s\n", gccgoPkgpath(p))
325                 fmt.Fprintf(h, "ar %q\n", BuildToolchain.(gccgoToolchain).ar())
326                 if len(p.SFiles) > 0 {
327                         id, _ = b.gccgoToolID(BuildToolchain.compiler(), "assembler-with-cpp")
328                         // Ignore error; different assembler versions
329                         // are unlikely to make any difference anyhow.
330                         fmt.Fprintf(h, "asm %q\n", id)
331                 }
332         }
333
334         // Input files.
335         inputFiles := str.StringList(
336                 p.GoFiles,
337                 p.CgoFiles,
338                 p.CFiles,
339                 p.CXXFiles,
340                 p.FFiles,
341                 p.MFiles,
342                 p.HFiles,
343                 p.SFiles,
344                 p.SysoFiles,
345                 p.SwigFiles,
346                 p.SwigCXXFiles,
347                 p.EmbedFiles,
348         )
349         for _, file := range inputFiles {
350                 fmt.Fprintf(h, "file %s %s\n", file, b.fileHash(filepath.Join(p.Dir, file)))
351         }
352         for _, a1 := range a.Deps {
353                 p1 := a1.Package
354                 if p1 != nil {
355                         fmt.Fprintf(h, "import %s %s\n", p1.ImportPath, contentID(a1.buildID))
356                 }
357         }
358
359         return h.Sum()
360 }
361
362 // needCgoHdr reports whether the actions triggered by this one
363 // expect to be able to access the cgo-generated header file.
364 func (b *Builder) needCgoHdr(a *Action) bool {
365         // If this build triggers a header install, run cgo to get the header.
366         if !b.IsCmdList && (a.Package.UsesCgo() || a.Package.UsesSwig()) && (cfg.BuildBuildmode == "c-archive" || cfg.BuildBuildmode == "c-shared") {
367                 for _, t1 := range a.triggers {
368                         if t1.Mode == "install header" {
369                                 return true
370                         }
371                 }
372                 for _, t1 := range a.triggers {
373                         for _, t2 := range t1.triggers {
374                                 if t2.Mode == "install header" {
375                                         return true
376                                 }
377                         }
378                 }
379         }
380         return false
381 }
382
383 // allowedVersion reports whether the version v is an allowed version of go
384 // (one that we can compile).
385 // v is known to be of the form "1.23".
386 func allowedVersion(v string) bool {
387         // Special case: no requirement.
388         if v == "" {
389                 return true
390         }
391         // Special case "1.0" means "go1", which is OK.
392         if v == "1.0" {
393                 return true
394         }
395         // Otherwise look through release tags of form "go1.23" for one that matches.
396         for _, tag := range cfg.BuildContext.ReleaseTags {
397                 if strings.HasPrefix(tag, "go") && tag[2:] == v {
398                         return true
399                 }
400         }
401         return false
402 }
403
404 const (
405         needBuild uint32 = 1 << iota
406         needCgoHdr
407         needVet
408         needCompiledGoFiles
409         needStale
410 )
411
412 // build is the action for building a single package.
413 // Note that any new influence on this logic must be reported in b.buildActionID above as well.
414 func (b *Builder) build(ctx context.Context, a *Action) (err error) {
415         p := a.Package
416
417         bit := func(x uint32, b bool) uint32 {
418                 if b {
419                         return x
420                 }
421                 return 0
422         }
423
424         cachedBuild := false
425         need := bit(needBuild, !b.IsCmdList && a.needBuild || b.NeedExport) |
426                 bit(needCgoHdr, b.needCgoHdr(a)) |
427                 bit(needVet, a.needVet) |
428                 bit(needCompiledGoFiles, b.NeedCompiledGoFiles)
429
430         if !p.BinaryOnly {
431                 if b.useCache(a, b.buildActionID(a), p.Target) {
432                         // We found the main output in the cache.
433                         // If we don't need any other outputs, we can stop.
434                         // Otherwise, we need to write files to a.Objdir (needVet, needCgoHdr).
435                         // Remember that we might have them in cache
436                         // and check again after we create a.Objdir.
437                         cachedBuild = true
438                         a.output = []byte{} // start saving output in case we miss any cache results
439                         need &^= needBuild
440                         if b.NeedExport {
441                                 p.Export = a.built
442                                 p.BuildID = a.buildID
443                         }
444                         if need&needCompiledGoFiles != 0 {
445                                 if err := b.loadCachedSrcFiles(a); err == nil {
446                                         need &^= needCompiledGoFiles
447                                 }
448                         }
449                 }
450
451                 // Source files might be cached, even if the full action is not
452                 // (e.g., go list -compiled -find).
453                 if !cachedBuild && need&needCompiledGoFiles != 0 {
454                         if err := b.loadCachedSrcFiles(a); err == nil {
455                                 need &^= needCompiledGoFiles
456                         }
457                 }
458
459                 if need == 0 {
460                         return nil
461                 }
462                 defer b.flushOutput(a)
463         }
464
465         defer func() {
466                 if err != nil && err != errPrintedOutput {
467                         err = fmt.Errorf("go build %s: %v", a.Package.ImportPath, err)
468                 }
469                 if err != nil && b.IsCmdList && b.NeedError && p.Error == nil {
470                         p.Error = &load.PackageError{Err: err}
471                 }
472         }()
473         if cfg.BuildN {
474                 // In -n mode, print a banner between packages.
475                 // The banner is five lines so that when changes to
476                 // different sections of the bootstrap script have to
477                 // be merged, the banners give patch something
478                 // to use to find its context.
479                 b.Print("\n#\n# " + a.Package.ImportPath + "\n#\n\n")
480         }
481
482         if cfg.BuildV {
483                 b.Print(a.Package.ImportPath + "\n")
484         }
485
486         if a.Package.BinaryOnly {
487                 p.Stale = true
488                 p.StaleReason = "binary-only packages are no longer supported"
489                 if b.IsCmdList {
490                         return nil
491                 }
492                 return errors.New("binary-only packages are no longer supported")
493         }
494
495         if err := b.Mkdir(a.Objdir); err != nil {
496                 return err
497         }
498         objdir := a.Objdir
499
500         // Load cached cgo header, but only if we're skipping the main build (cachedBuild==true).
501         if cachedBuild && need&needCgoHdr != 0 {
502                 if err := b.loadCachedCgoHdr(a); err == nil {
503                         need &^= needCgoHdr
504                 }
505         }
506
507         // Load cached vet config, but only if that's all we have left
508         // (need == needVet, not testing just the one bit).
509         // If we are going to do a full build anyway,
510         // we're going to regenerate the files below anyway.
511         if need == needVet {
512                 if err := b.loadCachedVet(a); err == nil {
513                         need &^= needVet
514                 }
515         }
516         if need == 0 {
517                 return nil
518         }
519
520         if err := allowInstall(a); err != nil {
521                 return err
522         }
523
524         // make target directory
525         dir, _ := filepath.Split(a.Target)
526         if dir != "" {
527                 if err := b.Mkdir(dir); err != nil {
528                         return err
529                 }
530         }
531
532         gofiles := str.StringList(a.Package.GoFiles)
533         cgofiles := str.StringList(a.Package.CgoFiles)
534         cfiles := str.StringList(a.Package.CFiles)
535         sfiles := str.StringList(a.Package.SFiles)
536         cxxfiles := str.StringList(a.Package.CXXFiles)
537         var objects, cgoObjects, pcCFLAGS, pcLDFLAGS []string
538
539         if a.Package.UsesCgo() || a.Package.UsesSwig() {
540                 if pcCFLAGS, pcLDFLAGS, err = b.getPkgConfigFlags(a.Package); err != nil {
541                         return
542                 }
543         }
544
545         // Compute overlays for .c/.cc/.h/etc. and if there are any overlays
546         // put correct contents of all those files in the objdir, to ensure
547         // the correct headers are included. nonGoOverlay is the overlay that
548         // points from nongo files to the copied files in objdir.
549         nonGoFileLists := [][]string{a.Package.CFiles, a.Package.SFiles, a.Package.CXXFiles, a.Package.HFiles, a.Package.FFiles}
550 OverlayLoop:
551         for _, fs := range nonGoFileLists {
552                 for _, f := range fs {
553                         if _, ok := fsys.OverlayPath(mkAbs(p.Dir, f)); ok {
554                                 a.nonGoOverlay = make(map[string]string)
555                                 break OverlayLoop
556                         }
557                 }
558         }
559         if a.nonGoOverlay != nil {
560                 for _, fs := range nonGoFileLists {
561                         for i := range fs {
562                                 from := mkAbs(p.Dir, fs[i])
563                                 opath, _ := fsys.OverlayPath(from)
564                                 dst := objdir + filepath.Base(fs[i])
565                                 if err := b.copyFile(dst, opath, 0666, false); err != nil {
566                                         return err
567                                 }
568                                 a.nonGoOverlay[from] = dst
569                         }
570                 }
571         }
572
573         // Run SWIG on each .swig and .swigcxx file.
574         // Each run will generate two files, a .go file and a .c or .cxx file.
575         // The .go file will use import "C" and is to be processed by cgo.
576         if a.Package.UsesSwig() {
577                 outGo, outC, outCXX, err := b.swig(a, a.Package, objdir, pcCFLAGS)
578                 if err != nil {
579                         return err
580                 }
581                 cgofiles = append(cgofiles, outGo...)
582                 cfiles = append(cfiles, outC...)
583                 cxxfiles = append(cxxfiles, outCXX...)
584         }
585
586         // If we're doing coverage, preprocess the .go files and put them in the work directory
587         if a.Package.Internal.CoverMode != "" {
588                 for i, file := range str.StringList(gofiles, cgofiles) {
589                         var sourceFile string
590                         var coverFile string
591                         var key string
592                         if strings.HasSuffix(file, ".cgo1.go") {
593                                 // cgo files have absolute paths
594                                 base := filepath.Base(file)
595                                 sourceFile = file
596                                 coverFile = objdir + base
597                                 key = strings.TrimSuffix(base, ".cgo1.go") + ".go"
598                         } else {
599                                 sourceFile = filepath.Join(a.Package.Dir, file)
600                                 coverFile = objdir + file
601                                 key = file
602                         }
603                         coverFile = strings.TrimSuffix(coverFile, ".go") + ".cover.go"
604                         cover := a.Package.Internal.CoverVars[key]
605                         if cover == nil || base.IsTestFile(file) {
606                                 // Not covering this file.
607                                 continue
608                         }
609                         if err := b.cover(a, coverFile, sourceFile, cover.Var); err != nil {
610                                 return err
611                         }
612                         if i < len(gofiles) {
613                                 gofiles[i] = coverFile
614                         } else {
615                                 cgofiles[i-len(gofiles)] = coverFile
616                         }
617                 }
618         }
619
620         // Run cgo.
621         if a.Package.UsesCgo() || a.Package.UsesSwig() {
622                 // In a package using cgo, cgo compiles the C, C++ and assembly files with gcc.
623                 // There is one exception: runtime/cgo's job is to bridge the
624                 // cgo and non-cgo worlds, so it necessarily has files in both.
625                 // In that case gcc only gets the gcc_* files.
626                 var gccfiles []string
627                 gccfiles = append(gccfiles, cfiles...)
628                 cfiles = nil
629                 if a.Package.Standard && a.Package.ImportPath == "runtime/cgo" {
630                         filter := func(files, nongcc, gcc []string) ([]string, []string) {
631                                 for _, f := range files {
632                                         if strings.HasPrefix(f, "gcc_") {
633                                                 gcc = append(gcc, f)
634                                         } else {
635                                                 nongcc = append(nongcc, f)
636                                         }
637                                 }
638                                 return nongcc, gcc
639                         }
640                         sfiles, gccfiles = filter(sfiles, sfiles[:0], gccfiles)
641                 } else {
642                         for _, sfile := range sfiles {
643                                 data, err := os.ReadFile(filepath.Join(a.Package.Dir, sfile))
644                                 if err == nil {
645                                         if bytes.HasPrefix(data, []byte("TEXT")) || bytes.Contains(data, []byte("\nTEXT")) ||
646                                                 bytes.HasPrefix(data, []byte("DATA")) || bytes.Contains(data, []byte("\nDATA")) ||
647                                                 bytes.HasPrefix(data, []byte("GLOBL")) || bytes.Contains(data, []byte("\nGLOBL")) {
648                                                 return fmt.Errorf("package using cgo has Go assembly file %s", sfile)
649                                         }
650                                 }
651                         }
652                         gccfiles = append(gccfiles, sfiles...)
653                         sfiles = nil
654                 }
655
656                 outGo, outObj, err := b.cgo(a, base.Tool("cgo"), objdir, pcCFLAGS, pcLDFLAGS, mkAbsFiles(a.Package.Dir, cgofiles), gccfiles, cxxfiles, a.Package.MFiles, a.Package.FFiles)
657                 if err != nil {
658                         return err
659                 }
660                 if cfg.BuildToolchainName == "gccgo" {
661                         cgoObjects = append(cgoObjects, a.Objdir+"_cgo_flags")
662                 }
663                 cgoObjects = append(cgoObjects, outObj...)
664                 gofiles = append(gofiles, outGo...)
665
666                 switch cfg.BuildBuildmode {
667                 case "c-archive", "c-shared":
668                         b.cacheCgoHdr(a)
669                 }
670         }
671
672         var srcfiles []string // .go and non-.go
673         srcfiles = append(srcfiles, gofiles...)
674         srcfiles = append(srcfiles, sfiles...)
675         srcfiles = append(srcfiles, cfiles...)
676         srcfiles = append(srcfiles, cxxfiles...)
677         b.cacheSrcFiles(a, srcfiles)
678
679         // Running cgo generated the cgo header.
680         need &^= needCgoHdr
681
682         // Sanity check only, since Package.load already checked as well.
683         if len(gofiles) == 0 {
684                 return &load.NoGoError{Package: a.Package}
685         }
686
687         // Prepare Go vet config if needed.
688         if need&needVet != 0 {
689                 buildVetConfig(a, srcfiles)
690                 need &^= needVet
691         }
692         if need&needCompiledGoFiles != 0 {
693                 if err := b.loadCachedSrcFiles(a); err != nil {
694                         return fmt.Errorf("loading compiled Go files from cache: %w", err)
695                 }
696                 need &^= needCompiledGoFiles
697         }
698         if need == 0 {
699                 // Nothing left to do.
700                 return nil
701         }
702
703         // Collect symbol ABI requirements from assembly.
704         symabis, err := BuildToolchain.symabis(b, a, sfiles)
705         if err != nil {
706                 return err
707         }
708
709         // Prepare Go import config.
710         // We start it off with a comment so it can't be empty, so icfg.Bytes() below is never nil.
711         // It should never be empty anyway, but there have been bugs in the past that resulted
712         // in empty configs, which then unfortunately turn into "no config passed to compiler",
713         // and the compiler falls back to looking in pkg itself, which mostly works,
714         // except when it doesn't.
715         var icfg bytes.Buffer
716         fmt.Fprintf(&icfg, "# import config\n")
717         for i, raw := range a.Package.Internal.RawImports {
718                 final := a.Package.Imports[i]
719                 if final != raw {
720                         fmt.Fprintf(&icfg, "importmap %s=%s\n", raw, final)
721                 }
722         }
723         for _, a1 := range a.Deps {
724                 p1 := a1.Package
725                 if p1 == nil || p1.ImportPath == "" || a1.built == "" {
726                         continue
727                 }
728                 fmt.Fprintf(&icfg, "packagefile %s=%s\n", p1.ImportPath, a1.built)
729         }
730
731         // Prepare Go embed config if needed.
732         // Unlike the import config, it's okay for the embed config to be empty.
733         var embedcfg []byte
734         if len(p.Internal.Embed) > 0 {
735                 var embed struct {
736                         Patterns map[string][]string
737                         Files    map[string]string
738                 }
739                 embed.Patterns = p.Internal.Embed
740                 embed.Files = make(map[string]string)
741                 for _, file := range p.EmbedFiles {
742                         embed.Files[file] = filepath.Join(p.Dir, file)
743                 }
744                 js, err := json.MarshalIndent(&embed, "", "\t")
745                 if err != nil {
746                         return fmt.Errorf("marshal embedcfg: %v", err)
747                 }
748                 embedcfg = js
749         }
750
751         if p.Internal.BuildInfo != "" && cfg.ModulesEnabled {
752                 if err := b.writeFile(objdir+"_gomod_.go", modload.ModInfoProg(p.Internal.BuildInfo, cfg.BuildToolchainName == "gccgo")); err != nil {
753                         return err
754                 }
755                 gofiles = append(gofiles, objdir+"_gomod_.go")
756         }
757
758         // Compile Go.
759         objpkg := objdir + "_pkg_.a"
760         ofile, out, err := BuildToolchain.gc(b, a, objpkg, icfg.Bytes(), embedcfg, symabis, len(sfiles) > 0, gofiles)
761         if len(out) > 0 {
762                 output := b.processOutput(out)
763                 if p.Module != nil && !allowedVersion(p.Module.GoVersion) {
764                         output += "note: module requires Go " + p.Module.GoVersion + "\n"
765                 }
766                 b.showOutput(a, a.Package.Dir, a.Package.Desc(), output)
767                 if err != nil {
768                         return errPrintedOutput
769                 }
770         }
771         if err != nil {
772                 if p.Module != nil && !allowedVersion(p.Module.GoVersion) {
773                         b.showOutput(a, a.Package.Dir, a.Package.Desc(), "note: module requires Go "+p.Module.GoVersion+"\n")
774                 }
775                 return err
776         }
777         if ofile != objpkg {
778                 objects = append(objects, ofile)
779         }
780
781         // Copy .h files named for goos or goarch or goos_goarch
782         // to names using GOOS and GOARCH.
783         // For example, defs_linux_amd64.h becomes defs_GOOS_GOARCH.h.
784         _goos_goarch := "_" + cfg.Goos + "_" + cfg.Goarch
785         _goos := "_" + cfg.Goos
786         _goarch := "_" + cfg.Goarch
787         for _, file := range a.Package.HFiles {
788                 name, ext := fileExtSplit(file)
789                 switch {
790                 case strings.HasSuffix(name, _goos_goarch):
791                         targ := file[:len(name)-len(_goos_goarch)] + "_GOOS_GOARCH." + ext
792                         if err := b.copyFile(objdir+targ, filepath.Join(a.Package.Dir, file), 0666, true); err != nil {
793                                 return err
794                         }
795                 case strings.HasSuffix(name, _goarch):
796                         targ := file[:len(name)-len(_goarch)] + "_GOARCH." + ext
797                         if err := b.copyFile(objdir+targ, filepath.Join(a.Package.Dir, file), 0666, true); err != nil {
798                                 return err
799                         }
800                 case strings.HasSuffix(name, _goos):
801                         targ := file[:len(name)-len(_goos)] + "_GOOS." + ext
802                         if err := b.copyFile(objdir+targ, filepath.Join(a.Package.Dir, file), 0666, true); err != nil {
803                                 return err
804                         }
805                 }
806         }
807
808         for _, file := range cfiles {
809                 out := file[:len(file)-len(".c")] + ".o"
810                 if err := BuildToolchain.cc(b, a, objdir+out, file); err != nil {
811                         return err
812                 }
813                 objects = append(objects, out)
814         }
815
816         // Assemble .s files.
817         if len(sfiles) > 0 {
818                 ofiles, err := BuildToolchain.asm(b, a, sfiles)
819                 if err != nil {
820                         return err
821                 }
822                 objects = append(objects, ofiles...)
823         }
824
825         // For gccgo on ELF systems, we write the build ID as an assembler file.
826         // This lets us set the SHF_EXCLUDE flag.
827         // This is read by readGccgoArchive in cmd/internal/buildid/buildid.go.
828         if a.buildID != "" && cfg.BuildToolchainName == "gccgo" {
829                 switch cfg.Goos {
830                 case "aix", "android", "dragonfly", "freebsd", "illumos", "linux", "netbsd", "openbsd", "solaris":
831                         asmfile, err := b.gccgoBuildIDFile(a)
832                         if err != nil {
833                                 return err
834                         }
835                         ofiles, err := BuildToolchain.asm(b, a, []string{asmfile})
836                         if err != nil {
837                                 return err
838                         }
839                         objects = append(objects, ofiles...)
840                 }
841         }
842
843         // NOTE(rsc): On Windows, it is critically important that the
844         // gcc-compiled objects (cgoObjects) be listed after the ordinary
845         // objects in the archive. I do not know why this is.
846         // https://golang.org/issue/2601
847         objects = append(objects, cgoObjects...)
848
849         // Add system object files.
850         for _, syso := range a.Package.SysoFiles {
851                 objects = append(objects, filepath.Join(a.Package.Dir, syso))
852         }
853
854         // Pack into archive in objdir directory.
855         // If the Go compiler wrote an archive, we only need to add the
856         // object files for non-Go sources to the archive.
857         // If the Go compiler wrote an archive and the package is entirely
858         // Go sources, there is no pack to execute at all.
859         if len(objects) > 0 {
860                 if err := BuildToolchain.pack(b, a, objpkg, objects); err != nil {
861                         return err
862                 }
863         }
864
865         if err := b.updateBuildID(a, objpkg, true); err != nil {
866                 return err
867         }
868
869         a.built = objpkg
870         return nil
871 }
872
873 func (b *Builder) cacheObjdirFile(a *Action, c *cache.Cache, name string) error {
874         f, err := os.Open(a.Objdir + name)
875         if err != nil {
876                 return err
877         }
878         defer f.Close()
879         _, _, err = c.Put(cache.Subkey(a.actionID, name), f)
880         return err
881 }
882
883 func (b *Builder) findCachedObjdirFile(a *Action, c *cache.Cache, name string) (string, error) {
884         file, _, err := c.GetFile(cache.Subkey(a.actionID, name))
885         if err != nil {
886                 return "", fmt.Errorf("loading cached file %s: %w", name, err)
887         }
888         return file, nil
889 }
890
891 func (b *Builder) loadCachedObjdirFile(a *Action, c *cache.Cache, name string) error {
892         cached, err := b.findCachedObjdirFile(a, c, name)
893         if err != nil {
894                 return err
895         }
896         return b.copyFile(a.Objdir+name, cached, 0666, true)
897 }
898
899 func (b *Builder) cacheCgoHdr(a *Action) {
900         c := cache.Default()
901         b.cacheObjdirFile(a, c, "_cgo_install.h")
902 }
903
904 func (b *Builder) loadCachedCgoHdr(a *Action) error {
905         c := cache.Default()
906         return b.loadCachedObjdirFile(a, c, "_cgo_install.h")
907 }
908
909 func (b *Builder) cacheSrcFiles(a *Action, srcfiles []string) {
910         c := cache.Default()
911         var buf bytes.Buffer
912         for _, file := range srcfiles {
913                 if !strings.HasPrefix(file, a.Objdir) {
914                         // not generated
915                         buf.WriteString("./")
916                         buf.WriteString(file)
917                         buf.WriteString("\n")
918                         continue
919                 }
920                 name := file[len(a.Objdir):]
921                 buf.WriteString(name)
922                 buf.WriteString("\n")
923                 if err := b.cacheObjdirFile(a, c, name); err != nil {
924                         return
925                 }
926         }
927         c.PutBytes(cache.Subkey(a.actionID, "srcfiles"), buf.Bytes())
928 }
929
930 func (b *Builder) loadCachedVet(a *Action) error {
931         c := cache.Default()
932         list, _, err := c.GetBytes(cache.Subkey(a.actionID, "srcfiles"))
933         if err != nil {
934                 return fmt.Errorf("reading srcfiles list: %w", err)
935         }
936         var srcfiles []string
937         for _, name := range strings.Split(string(list), "\n") {
938                 if name == "" { // end of list
939                         continue
940                 }
941                 if strings.HasPrefix(name, "./") {
942                         srcfiles = append(srcfiles, name[2:])
943                         continue
944                 }
945                 if err := b.loadCachedObjdirFile(a, c, name); err != nil {
946                         return err
947                 }
948                 srcfiles = append(srcfiles, a.Objdir+name)
949         }
950         buildVetConfig(a, srcfiles)
951         return nil
952 }
953
954 func (b *Builder) loadCachedSrcFiles(a *Action) error {
955         c := cache.Default()
956         list, _, err := c.GetBytes(cache.Subkey(a.actionID, "srcfiles"))
957         if err != nil {
958                 return fmt.Errorf("reading srcfiles list: %w", err)
959         }
960         var files []string
961         for _, name := range strings.Split(string(list), "\n") {
962                 if name == "" { // end of list
963                         continue
964                 }
965                 if strings.HasPrefix(name, "./") {
966                         files = append(files, name[len("./"):])
967                         continue
968                 }
969                 file, err := b.findCachedObjdirFile(a, c, name)
970                 if err != nil {
971                         return fmt.Errorf("finding %s: %w", name, err)
972                 }
973                 files = append(files, file)
974         }
975         a.Package.CompiledGoFiles = files
976         return nil
977 }
978
979 // vetConfig is the configuration passed to vet describing a single package.
980 type vetConfig struct {
981         ID           string   // package ID (example: "fmt [fmt.test]")
982         Compiler     string   // compiler name (gc, gccgo)
983         Dir          string   // directory containing package
984         ImportPath   string   // canonical import path ("package path")
985         GoFiles      []string // absolute paths to package source files
986         NonGoFiles   []string // absolute paths to package non-Go files
987         IgnoredFiles []string // absolute paths to ignored source files
988
989         ImportMap   map[string]string // map import path in source code to package path
990         PackageFile map[string]string // map package path to .a file with export data
991         Standard    map[string]bool   // map package path to whether it's in the standard library
992         PackageVetx map[string]string // map package path to vetx data from earlier vet run
993         VetxOnly    bool              // only compute vetx data; don't report detected problems
994         VetxOutput  string            // write vetx data to this output file
995
996         SucceedOnTypecheckFailure bool // awful hack; see #18395 and below
997 }
998
999 func buildVetConfig(a *Action, srcfiles []string) {
1000         // Classify files based on .go extension.
1001         // srcfiles does not include raw cgo files.
1002         var gofiles, nongofiles []string
1003         for _, name := range srcfiles {
1004                 if strings.HasSuffix(name, ".go") {
1005                         gofiles = append(gofiles, name)
1006                 } else {
1007                         nongofiles = append(nongofiles, name)
1008                 }
1009         }
1010
1011         ignored := str.StringList(a.Package.IgnoredGoFiles, a.Package.IgnoredOtherFiles)
1012
1013         // Pass list of absolute paths to vet,
1014         // so that vet's error messages will use absolute paths,
1015         // so that we can reformat them relative to the directory
1016         // in which the go command is invoked.
1017         vcfg := &vetConfig{
1018                 ID:           a.Package.ImportPath,
1019                 Compiler:     cfg.BuildToolchainName,
1020                 Dir:          a.Package.Dir,
1021                 GoFiles:      mkAbsFiles(a.Package.Dir, gofiles),
1022                 NonGoFiles:   mkAbsFiles(a.Package.Dir, nongofiles),
1023                 IgnoredFiles: mkAbsFiles(a.Package.Dir, ignored),
1024                 ImportPath:   a.Package.ImportPath,
1025                 ImportMap:    make(map[string]string),
1026                 PackageFile:  make(map[string]string),
1027                 Standard:     make(map[string]bool),
1028         }
1029         a.vetCfg = vcfg
1030         for i, raw := range a.Package.Internal.RawImports {
1031                 final := a.Package.Imports[i]
1032                 vcfg.ImportMap[raw] = final
1033         }
1034
1035         // Compute the list of mapped imports in the vet config
1036         // so that we can add any missing mappings below.
1037         vcfgMapped := make(map[string]bool)
1038         for _, p := range vcfg.ImportMap {
1039                 vcfgMapped[p] = true
1040         }
1041
1042         for _, a1 := range a.Deps {
1043                 p1 := a1.Package
1044                 if p1 == nil || p1.ImportPath == "" {
1045                         continue
1046                 }
1047                 // Add import mapping if needed
1048                 // (for imports like "runtime/cgo" that appear only in generated code).
1049                 if !vcfgMapped[p1.ImportPath] {
1050                         vcfg.ImportMap[p1.ImportPath] = p1.ImportPath
1051                 }
1052                 if a1.built != "" {
1053                         vcfg.PackageFile[p1.ImportPath] = a1.built
1054                 }
1055                 if p1.Standard {
1056                         vcfg.Standard[p1.ImportPath] = true
1057                 }
1058         }
1059 }
1060
1061 // VetTool is the path to an alternate vet tool binary.
1062 // The caller is expected to set it (if needed) before executing any vet actions.
1063 var VetTool string
1064
1065 // VetFlags are the default flags to pass to vet.
1066 // The caller is expected to set them before executing any vet actions.
1067 var VetFlags []string
1068
1069 // VetExplicit records whether the vet flags were set explicitly on the command line.
1070 var VetExplicit bool
1071
1072 func (b *Builder) vet(ctx context.Context, a *Action) error {
1073         // a.Deps[0] is the build of the package being vetted.
1074         // a.Deps[1] is the build of the "fmt" package.
1075
1076         a.Failed = false // vet of dependency may have failed but we can still succeed
1077
1078         if a.Deps[0].Failed {
1079                 // The build of the package has failed. Skip vet check.
1080                 // Vet could return export data for non-typecheck errors,
1081                 // but we ignore it because the package cannot be compiled.
1082                 return nil
1083         }
1084
1085         vcfg := a.Deps[0].vetCfg
1086         if vcfg == nil {
1087                 // Vet config should only be missing if the build failed.
1088                 return fmt.Errorf("vet config not found")
1089         }
1090
1091         vcfg.VetxOnly = a.VetxOnly
1092         vcfg.VetxOutput = a.Objdir + "vet.out"
1093         vcfg.PackageVetx = make(map[string]string)
1094
1095         h := cache.NewHash("vet " + a.Package.ImportPath)
1096         fmt.Fprintf(h, "vet %q\n", b.toolID("vet"))
1097
1098         vetFlags := VetFlags
1099
1100         // In GOROOT, we enable all the vet tests during 'go test',
1101         // not just the high-confidence subset. This gets us extra
1102         // checking for the standard library (at some compliance cost)
1103         // and helps us gain experience about how well the checks
1104         // work, to help decide which should be turned on by default.
1105         // The command-line still wins.
1106         //
1107         // Note that this flag change applies even when running vet as
1108         // a dependency of vetting a package outside std.
1109         // (Otherwise we'd have to introduce a whole separate
1110         // space of "vet fmt as a dependency of a std top-level vet"
1111         // versus "vet fmt as a dependency of a non-std top-level vet".)
1112         // This is OK as long as the packages that are farther down the
1113         // dependency tree turn on *more* analysis, as here.
1114         // (The unsafeptr check does not write any facts for use by
1115         // later vet runs, nor does unreachable.)
1116         if a.Package.Goroot && !VetExplicit && VetTool == "" {
1117                 // Turn off -unsafeptr checks.
1118                 // There's too much unsafe.Pointer code
1119                 // that vet doesn't like in low-level packages
1120                 // like runtime, sync, and reflect.
1121                 // Note that $GOROOT/src/buildall.bash
1122                 // does the same for the misc-compile trybots
1123                 // and should be updated if these flags are
1124                 // changed here.
1125                 vetFlags = []string{"-unsafeptr=false"}
1126
1127                 // Also turn off -unreachable checks during go test.
1128                 // During testing it is very common to make changes
1129                 // like hard-coded forced returns or panics that make
1130                 // code unreachable. It's unreasonable to insist on files
1131                 // not having any unreachable code during "go test".
1132                 // (buildall.bash still runs with -unreachable enabled
1133                 // for the overall whole-tree scan.)
1134                 if cfg.CmdName == "test" {
1135                         vetFlags = append(vetFlags, "-unreachable=false")
1136                 }
1137         }
1138
1139         // Note: We could decide that vet should compute export data for
1140         // all analyses, in which case we don't need to include the flags here.
1141         // But that would mean that if an analysis causes problems like
1142         // unexpected crashes there would be no way to turn it off.
1143         // It seems better to let the flags disable export analysis too.
1144         fmt.Fprintf(h, "vetflags %q\n", vetFlags)
1145
1146         fmt.Fprintf(h, "pkg %q\n", a.Deps[0].actionID)
1147         for _, a1 := range a.Deps {
1148                 if a1.Mode == "vet" && a1.built != "" {
1149                         fmt.Fprintf(h, "vetout %q %s\n", a1.Package.ImportPath, b.fileHash(a1.built))
1150                         vcfg.PackageVetx[a1.Package.ImportPath] = a1.built
1151                 }
1152         }
1153         key := cache.ActionID(h.Sum())
1154
1155         if vcfg.VetxOnly && !cfg.BuildA {
1156                 c := cache.Default()
1157                 if file, _, err := c.GetFile(key); err == nil {
1158                         a.built = file
1159                         return nil
1160                 }
1161         }
1162
1163         js, err := json.MarshalIndent(vcfg, "", "\t")
1164         if err != nil {
1165                 return fmt.Errorf("internal error marshaling vet config: %v", err)
1166         }
1167         js = append(js, '\n')
1168         if err := b.writeFile(a.Objdir+"vet.cfg", js); err != nil {
1169                 return err
1170         }
1171
1172         // TODO(rsc): Why do we pass $GCCGO to go vet?
1173         env := b.cCompilerEnv()
1174         if cfg.BuildToolchainName == "gccgo" {
1175                 env = append(env, "GCCGO="+BuildToolchain.compiler())
1176         }
1177
1178         p := a.Package
1179         tool := VetTool
1180         if tool == "" {
1181                 tool = base.Tool("vet")
1182         }
1183         runErr := b.run(a, p.Dir, p.ImportPath, env, cfg.BuildToolexec, tool, vetFlags, a.Objdir+"vet.cfg")
1184
1185         // If vet wrote export data, save it for input to future vets.
1186         if f, err := os.Open(vcfg.VetxOutput); err == nil {
1187                 a.built = vcfg.VetxOutput
1188                 cache.Default().Put(key, f)
1189                 f.Close()
1190         }
1191
1192         return runErr
1193 }
1194
1195 // linkActionID computes the action ID for a link action.
1196 func (b *Builder) linkActionID(a *Action) cache.ActionID {
1197         p := a.Package
1198         h := cache.NewHash("link " + p.ImportPath)
1199
1200         // Toolchain-independent configuration.
1201         fmt.Fprintf(h, "link\n")
1202         fmt.Fprintf(h, "buildmode %s goos %s goarch %s\n", cfg.BuildBuildmode, cfg.Goos, cfg.Goarch)
1203         fmt.Fprintf(h, "import %q\n", p.ImportPath)
1204         fmt.Fprintf(h, "omitdebug %v standard %v local %v prefix %q\n", p.Internal.OmitDebug, p.Standard, p.Internal.Local, p.Internal.LocalPrefix)
1205         if cfg.BuildTrimpath {
1206                 fmt.Fprintln(h, "trimpath")
1207         }
1208
1209         // Toolchain-dependent configuration, shared with b.linkSharedActionID.
1210         b.printLinkerConfig(h, p)
1211
1212         // Input files.
1213         for _, a1 := range a.Deps {
1214                 p1 := a1.Package
1215                 if p1 != nil {
1216                         if a1.built != "" || a1.buildID != "" {
1217                                 buildID := a1.buildID
1218                                 if buildID == "" {
1219                                         buildID = b.buildID(a1.built)
1220                                 }
1221                                 fmt.Fprintf(h, "packagefile %s=%s\n", p1.ImportPath, contentID(buildID))
1222                         }
1223                         // Because we put package main's full action ID into the binary's build ID,
1224                         // we must also put the full action ID into the binary's action ID hash.
1225                         if p1.Name == "main" {
1226                                 fmt.Fprintf(h, "packagemain %s\n", a1.buildID)
1227                         }
1228                         if p1.Shlib != "" {
1229                                 fmt.Fprintf(h, "packageshlib %s=%s\n", p1.ImportPath, contentID(b.buildID(p1.Shlib)))
1230                         }
1231                 }
1232         }
1233
1234         return h.Sum()
1235 }
1236
1237 // printLinkerConfig prints the linker config into the hash h,
1238 // as part of the computation of a linker-related action ID.
1239 func (b *Builder) printLinkerConfig(h io.Writer, p *load.Package) {
1240         switch cfg.BuildToolchainName {
1241         default:
1242                 base.Fatalf("linkActionID: unknown toolchain %q", cfg.BuildToolchainName)
1243
1244         case "gc":
1245                 fmt.Fprintf(h, "link %s %q %s\n", b.toolID("link"), forcedLdflags, ldBuildmode)
1246                 if p != nil {
1247                         fmt.Fprintf(h, "linkflags %q\n", p.Internal.Ldflags)
1248                 }
1249
1250                 // GOARM, GOMIPS, etc.
1251                 key, val := cfg.GetArchEnv()
1252                 fmt.Fprintf(h, "%s=%s\n", key, val)
1253
1254                 if goexperiment := buildcfg.GOEXPERIMENT(); goexperiment != "" {
1255                         fmt.Fprintf(h, "GOEXPERIMENT=%q\n", goexperiment)
1256                 }
1257
1258                 // The linker writes source file paths that say GOROOT_FINAL, but
1259                 // only if -trimpath is not specified (see ld() in gc.go).
1260                 gorootFinal := cfg.GOROOT_FINAL
1261                 if cfg.BuildTrimpath {
1262                         gorootFinal = trimPathGoRootFinal
1263                 }
1264                 fmt.Fprintf(h, "GOROOT=%s\n", gorootFinal)
1265
1266                 // GO_EXTLINK_ENABLED controls whether the external linker is used.
1267                 fmt.Fprintf(h, "GO_EXTLINK_ENABLED=%s\n", cfg.Getenv("GO_EXTLINK_ENABLED"))
1268
1269                 // TODO(rsc): Do cgo settings and flags need to be included?
1270                 // Or external linker settings and flags?
1271
1272         case "gccgo":
1273                 id, err := b.gccgoToolID(BuildToolchain.linker(), "go")
1274                 if err != nil {
1275                         base.Fatalf("%v", err)
1276                 }
1277                 fmt.Fprintf(h, "link %s %s\n", id, ldBuildmode)
1278                 // TODO(iant): Should probably include cgo flags here.
1279         }
1280 }
1281
1282 // link is the action for linking a single command.
1283 // Note that any new influence on this logic must be reported in b.linkActionID above as well.
1284 func (b *Builder) link(ctx context.Context, a *Action) (err error) {
1285         if b.useCache(a, b.linkActionID(a), a.Package.Target) || b.IsCmdList {
1286                 return nil
1287         }
1288         defer b.flushOutput(a)
1289
1290         if err := b.Mkdir(a.Objdir); err != nil {
1291                 return err
1292         }
1293
1294         importcfg := a.Objdir + "importcfg.link"
1295         if err := b.writeLinkImportcfg(a, importcfg); err != nil {
1296                 return err
1297         }
1298
1299         if err := allowInstall(a); err != nil {
1300                 return err
1301         }
1302
1303         // make target directory
1304         dir, _ := filepath.Split(a.Target)
1305         if dir != "" {
1306                 if err := b.Mkdir(dir); err != nil {
1307                         return err
1308                 }
1309         }
1310
1311         if err := BuildToolchain.ld(b, a, a.Target, importcfg, a.Deps[0].built); err != nil {
1312                 return err
1313         }
1314
1315         // Update the binary with the final build ID.
1316         // But if OmitDebug is set, don't rewrite the binary, because we set OmitDebug
1317         // on binaries that we are going to run and then delete.
1318         // There's no point in doing work on such a binary.
1319         // Worse, opening the binary for write here makes it
1320         // essentially impossible to safely fork+exec due to a fundamental
1321         // incompatibility between ETXTBSY and threads on modern Unix systems.
1322         // See golang.org/issue/22220.
1323         // We still call updateBuildID to update a.buildID, which is important
1324         // for test result caching, but passing rewrite=false (final arg)
1325         // means we don't actually rewrite the binary, nor store the
1326         // result into the cache. That's probably a net win:
1327         // less cache space wasted on large binaries we are not likely to
1328         // need again. (On the other hand it does make repeated go test slower.)
1329         // It also makes repeated go run slower, which is a win in itself:
1330         // we don't want people to treat go run like a scripting environment.
1331         if err := b.updateBuildID(a, a.Target, !a.Package.Internal.OmitDebug); err != nil {
1332                 return err
1333         }
1334
1335         a.built = a.Target
1336         return nil
1337 }
1338
1339 func (b *Builder) writeLinkImportcfg(a *Action, file string) error {
1340         // Prepare Go import cfg.
1341         var icfg bytes.Buffer
1342         for _, a1 := range a.Deps {
1343                 p1 := a1.Package
1344                 if p1 == nil {
1345                         continue
1346                 }
1347                 fmt.Fprintf(&icfg, "packagefile %s=%s\n", p1.ImportPath, a1.built)
1348                 if p1.Shlib != "" {
1349                         fmt.Fprintf(&icfg, "packageshlib %s=%s\n", p1.ImportPath, p1.Shlib)
1350                 }
1351         }
1352         return b.writeFile(file, icfg.Bytes())
1353 }
1354
1355 // PkgconfigCmd returns a pkg-config binary name
1356 // defaultPkgConfig is defined in zdefaultcc.go, written by cmd/dist.
1357 func (b *Builder) PkgconfigCmd() string {
1358         return envList("PKG_CONFIG", cfg.DefaultPkgConfig)[0]
1359 }
1360
1361 // splitPkgConfigOutput parses the pkg-config output into a slice of
1362 // flags. This implements the algorithm from pkgconf/libpkgconf/argvsplit.c.
1363 func splitPkgConfigOutput(out []byte) ([]string, error) {
1364         if len(out) == 0 {
1365                 return nil, nil
1366         }
1367         var flags []string
1368         flag := make([]byte, 0, len(out))
1369         escaped := false
1370         quote := byte(0)
1371
1372         for _, c := range out {
1373                 if escaped {
1374                         if quote != 0 {
1375                                 switch c {
1376                                 case '$', '`', '"', '\\':
1377                                 default:
1378                                         flag = append(flag, '\\')
1379                                 }
1380                                 flag = append(flag, c)
1381                         } else {
1382                                 flag = append(flag, c)
1383                         }
1384                         escaped = false
1385                 } else if quote != 0 {
1386                         if c == quote {
1387                                 quote = 0
1388                         } else {
1389                                 switch c {
1390                                 case '\\':
1391                                         escaped = true
1392                                 default:
1393                                         flag = append(flag, c)
1394                                 }
1395                         }
1396                 } else if strings.IndexByte(" \t\n\v\f\r", c) < 0 {
1397                         switch c {
1398                         case '\\':
1399                                 escaped = true
1400                         case '\'', '"':
1401                                 quote = c
1402                         default:
1403                                 flag = append(flag, c)
1404                         }
1405                 } else if len(flag) != 0 {
1406                         flags = append(flags, string(flag))
1407                         flag = flag[:0]
1408                 }
1409         }
1410         if escaped {
1411                 return nil, errors.New("broken character escaping in pkgconf output ")
1412         }
1413         if quote != 0 {
1414                 return nil, errors.New("unterminated quoted string in pkgconf output ")
1415         } else if len(flag) != 0 {
1416                 flags = append(flags, string(flag))
1417         }
1418
1419         return flags, nil
1420 }
1421
1422 // Calls pkg-config if needed and returns the cflags/ldflags needed to build the package.
1423 func (b *Builder) getPkgConfigFlags(p *load.Package) (cflags, ldflags []string, err error) {
1424         if pcargs := p.CgoPkgConfig; len(pcargs) > 0 {
1425                 // pkg-config permits arguments to appear anywhere in
1426                 // the command line. Move them all to the front, before --.
1427                 var pcflags []string
1428                 var pkgs []string
1429                 for _, pcarg := range pcargs {
1430                         if pcarg == "--" {
1431                                 // We're going to add our own "--" argument.
1432                         } else if strings.HasPrefix(pcarg, "--") {
1433                                 pcflags = append(pcflags, pcarg)
1434                         } else {
1435                                 pkgs = append(pkgs, pcarg)
1436                         }
1437                 }
1438                 for _, pkg := range pkgs {
1439                         if !load.SafeArg(pkg) {
1440                                 return nil, nil, fmt.Errorf("invalid pkg-config package name: %s", pkg)
1441                         }
1442                 }
1443                 var out []byte
1444                 out, err = b.runOut(nil, p.Dir, nil, b.PkgconfigCmd(), "--cflags", pcflags, "--", pkgs)
1445                 if err != nil {
1446                         b.showOutput(nil, p.Dir, b.PkgconfigCmd()+" --cflags "+strings.Join(pcflags, " ")+" -- "+strings.Join(pkgs, " "), string(out))
1447                         b.Print(err.Error() + "\n")
1448                         return nil, nil, errPrintedOutput
1449                 }
1450                 if len(out) > 0 {
1451                         cflags, err = splitPkgConfigOutput(out)
1452                         if err != nil {
1453                                 return nil, nil, err
1454                         }
1455                         if err := checkCompilerFlags("CFLAGS", "pkg-config --cflags", cflags); err != nil {
1456                                 return nil, nil, err
1457                         }
1458                 }
1459                 out, err = b.runOut(nil, p.Dir, nil, b.PkgconfigCmd(), "--libs", pcflags, "--", pkgs)
1460                 if err != nil {
1461                         b.showOutput(nil, p.Dir, b.PkgconfigCmd()+" --libs "+strings.Join(pcflags, " ")+" -- "+strings.Join(pkgs, " "), string(out))
1462                         b.Print(err.Error() + "\n")
1463                         return nil, nil, errPrintedOutput
1464                 }
1465                 if len(out) > 0 {
1466                         ldflags = strings.Fields(string(out))
1467                         if err := checkLinkerFlags("LDFLAGS", "pkg-config --libs", ldflags); err != nil {
1468                                 return nil, nil, err
1469                         }
1470                 }
1471         }
1472
1473         return
1474 }
1475
1476 func (b *Builder) installShlibname(ctx context.Context, a *Action) error {
1477         if err := allowInstall(a); err != nil {
1478                 return err
1479         }
1480
1481         // TODO: BuildN
1482         a1 := a.Deps[0]
1483         err := os.WriteFile(a.Target, []byte(filepath.Base(a1.Target)+"\n"), 0666)
1484         if err != nil {
1485                 return err
1486         }
1487         if cfg.BuildX {
1488                 b.Showcmd("", "echo '%s' > %s # internal", filepath.Base(a1.Target), a.Target)
1489         }
1490         return nil
1491 }
1492
1493 func (b *Builder) linkSharedActionID(a *Action) cache.ActionID {
1494         h := cache.NewHash("linkShared")
1495
1496         // Toolchain-independent configuration.
1497         fmt.Fprintf(h, "linkShared\n")
1498         fmt.Fprintf(h, "goos %s goarch %s\n", cfg.Goos, cfg.Goarch)
1499
1500         // Toolchain-dependent configuration, shared with b.linkActionID.
1501         b.printLinkerConfig(h, nil)
1502
1503         // Input files.
1504         for _, a1 := range a.Deps {
1505                 p1 := a1.Package
1506                 if a1.built == "" {
1507                         continue
1508                 }
1509                 if p1 != nil {
1510                         fmt.Fprintf(h, "packagefile %s=%s\n", p1.ImportPath, contentID(b.buildID(a1.built)))
1511                         if p1.Shlib != "" {
1512                                 fmt.Fprintf(h, "packageshlib %s=%s\n", p1.ImportPath, contentID(b.buildID(p1.Shlib)))
1513                         }
1514                 }
1515         }
1516         // Files named on command line are special.
1517         for _, a1 := range a.Deps[0].Deps {
1518                 p1 := a1.Package
1519                 fmt.Fprintf(h, "top %s=%s\n", p1.ImportPath, contentID(b.buildID(a1.built)))
1520         }
1521
1522         return h.Sum()
1523 }
1524
1525 func (b *Builder) linkShared(ctx context.Context, a *Action) (err error) {
1526         if b.useCache(a, b.linkSharedActionID(a), a.Target) || b.IsCmdList {
1527                 return nil
1528         }
1529         defer b.flushOutput(a)
1530
1531         if err := allowInstall(a); err != nil {
1532                 return err
1533         }
1534
1535         if err := b.Mkdir(a.Objdir); err != nil {
1536                 return err
1537         }
1538
1539         importcfg := a.Objdir + "importcfg.link"
1540         if err := b.writeLinkImportcfg(a, importcfg); err != nil {
1541                 return err
1542         }
1543
1544         // TODO(rsc): There is a missing updateBuildID here,
1545         // but we have to decide where to store the build ID in these files.
1546         a.built = a.Target
1547         return BuildToolchain.ldShared(b, a, a.Deps[0].Deps, a.Target, importcfg, a.Deps)
1548 }
1549
1550 // BuildInstallFunc is the action for installing a single package or executable.
1551 func BuildInstallFunc(b *Builder, ctx context.Context, a *Action) (err error) {
1552         defer func() {
1553                 if err != nil && err != errPrintedOutput {
1554                         // a.Package == nil is possible for the go install -buildmode=shared
1555                         // action that installs libmangledname.so, which corresponds to
1556                         // a list of packages, not just one.
1557                         sep, path := "", ""
1558                         if a.Package != nil {
1559                                 sep, path = " ", a.Package.ImportPath
1560                         }
1561                         err = fmt.Errorf("go %s%s%s: %v", cfg.CmdName, sep, path, err)
1562                 }
1563         }()
1564
1565         a1 := a.Deps[0]
1566         a.buildID = a1.buildID
1567         if a.json != nil {
1568                 a.json.BuildID = a.buildID
1569         }
1570
1571         // If we are using the eventual install target as an up-to-date
1572         // cached copy of the thing we built, then there's no need to
1573         // copy it into itself (and that would probably fail anyway).
1574         // In this case a1.built == a.Target because a1.built == p.Target,
1575         // so the built target is not in the a1.Objdir tree that b.cleanup(a1) removes.
1576         if a1.built == a.Target {
1577                 a.built = a.Target
1578                 if !a.buggyInstall {
1579                         b.cleanup(a1)
1580                 }
1581                 // Whether we're smart enough to avoid a complete rebuild
1582                 // depends on exactly what the staleness and rebuild algorithms
1583                 // are, as well as potentially the state of the Go build cache.
1584                 // We don't really want users to be able to infer (or worse start depending on)
1585                 // those details from whether the modification time changes during
1586                 // "go install", so do a best-effort update of the file times to make it
1587                 // look like we rewrote a.Target even if we did not. Updating the mtime
1588                 // may also help other mtime-based systems that depend on our
1589                 // previous mtime updates that happened more often.
1590                 // This is still not perfect - we ignore the error result, and if the file was
1591                 // unwritable for some reason then pretending to have written it is also
1592                 // confusing - but it's probably better than not doing the mtime update.
1593                 //
1594                 // But don't do that for the special case where building an executable
1595                 // with -linkshared implicitly installs all its dependent libraries.
1596                 // We want to hide that awful detail as much as possible, so don't
1597                 // advertise it by touching the mtimes (usually the libraries are up
1598                 // to date).
1599                 if !a.buggyInstall && !b.IsCmdList {
1600                         if cfg.BuildN {
1601                                 b.Showcmd("", "touch %s", a.Target)
1602                         } else if err := allowInstall(a); err == nil {
1603                                 now := time.Now()
1604                                 os.Chtimes(a.Target, now, now)
1605                         }
1606                 }
1607                 return nil
1608         }
1609
1610         // If we're building for go list -export,
1611         // never install anything; just keep the cache reference.
1612         if b.IsCmdList {
1613                 a.built = a1.built
1614                 return nil
1615         }
1616         if err := allowInstall(a); err != nil {
1617                 return err
1618         }
1619
1620         if err := b.Mkdir(a.Objdir); err != nil {
1621                 return err
1622         }
1623
1624         perm := fs.FileMode(0666)
1625         if a1.Mode == "link" {
1626                 switch cfg.BuildBuildmode {
1627                 case "c-archive", "c-shared", "plugin":
1628                 default:
1629                         perm = 0777
1630                 }
1631         }
1632
1633         // make target directory
1634         dir, _ := filepath.Split(a.Target)
1635         if dir != "" {
1636                 if err := b.Mkdir(dir); err != nil {
1637                         return err
1638                 }
1639         }
1640
1641         if !a.buggyInstall {
1642                 defer b.cleanup(a1)
1643         }
1644
1645         return b.moveOrCopyFile(a.Target, a1.built, perm, false)
1646 }
1647
1648 // allowInstall returns a non-nil error if this invocation of the go command is
1649 // allowed to install a.Target.
1650 //
1651 // (The build of cmd/go running under its own test is forbidden from installing
1652 // to its original GOROOT.)
1653 var allowInstall = func(*Action) error { return nil }
1654
1655 // cleanup removes a's object dir to keep the amount of
1656 // on-disk garbage down in a large build. On an operating system
1657 // with aggressive buffering, cleaning incrementally like
1658 // this keeps the intermediate objects from hitting the disk.
1659 func (b *Builder) cleanup(a *Action) {
1660         if !cfg.BuildWork {
1661                 if cfg.BuildX {
1662                         // Don't say we are removing the directory if
1663                         // we never created it.
1664                         if _, err := os.Stat(a.Objdir); err == nil || cfg.BuildN {
1665                                 b.Showcmd("", "rm -r %s", a.Objdir)
1666                         }
1667                 }
1668                 os.RemoveAll(a.Objdir)
1669         }
1670 }
1671
1672 // moveOrCopyFile is like 'mv src dst' or 'cp src dst'.
1673 func (b *Builder) moveOrCopyFile(dst, src string, perm fs.FileMode, force bool) error {
1674         if cfg.BuildN {
1675                 b.Showcmd("", "mv %s %s", src, dst)
1676                 return nil
1677         }
1678
1679         // If we can update the mode and rename to the dst, do it.
1680         // Otherwise fall back to standard copy.
1681
1682         // If the source is in the build cache, we need to copy it.
1683         if strings.HasPrefix(src, cache.DefaultDir()) {
1684                 return b.copyFile(dst, src, perm, force)
1685         }
1686
1687         // On Windows, always copy the file, so that we respect the NTFS
1688         // permissions of the parent folder. https://golang.org/issue/22343.
1689         // What matters here is not cfg.Goos (the system we are building
1690         // for) but runtime.GOOS (the system we are building on).
1691         if runtime.GOOS == "windows" {
1692                 return b.copyFile(dst, src, perm, force)
1693         }
1694
1695         // If the destination directory has the group sticky bit set,
1696         // we have to copy the file to retain the correct permissions.
1697         // https://golang.org/issue/18878
1698         if fi, err := os.Stat(filepath.Dir(dst)); err == nil {
1699                 if fi.IsDir() && (fi.Mode()&fs.ModeSetgid) != 0 {
1700                         return b.copyFile(dst, src, perm, force)
1701                 }
1702         }
1703
1704         // The perm argument is meant to be adjusted according to umask,
1705         // but we don't know what the umask is.
1706         // Create a dummy file to find out.
1707         // This avoids build tags and works even on systems like Plan 9
1708         // where the file mask computation incorporates other information.
1709         mode := perm
1710         f, err := os.OpenFile(filepath.Clean(dst)+"-go-tmp-umask", os.O_WRONLY|os.O_CREATE|os.O_EXCL, perm)
1711         if err == nil {
1712                 fi, err := f.Stat()
1713                 if err == nil {
1714                         mode = fi.Mode() & 0777
1715                 }
1716                 name := f.Name()
1717                 f.Close()
1718                 os.Remove(name)
1719         }
1720
1721         if err := os.Chmod(src, mode); err == nil {
1722                 if err := os.Rename(src, dst); err == nil {
1723                         if cfg.BuildX {
1724                                 b.Showcmd("", "mv %s %s", src, dst)
1725                         }
1726                         return nil
1727                 }
1728         }
1729
1730         return b.copyFile(dst, src, perm, force)
1731 }
1732
1733 // copyFile is like 'cp src dst'.
1734 func (b *Builder) copyFile(dst, src string, perm fs.FileMode, force bool) error {
1735         if cfg.BuildN || cfg.BuildX {
1736                 b.Showcmd("", "cp %s %s", src, dst)
1737                 if cfg.BuildN {
1738                         return nil
1739                 }
1740         }
1741
1742         sf, err := os.Open(src)
1743         if err != nil {
1744                 return err
1745         }
1746         defer sf.Close()
1747
1748         // Be careful about removing/overwriting dst.
1749         // Do not remove/overwrite if dst exists and is a directory
1750         // or a non-empty non-object file.
1751         if fi, err := os.Stat(dst); err == nil {
1752                 if fi.IsDir() {
1753                         return fmt.Errorf("build output %q already exists and is a directory", dst)
1754                 }
1755                 if !force && fi.Mode().IsRegular() && fi.Size() != 0 && !isObject(dst) {
1756                         return fmt.Errorf("build output %q already exists and is not an object file", dst)
1757                 }
1758         }
1759
1760         // On Windows, remove lingering ~ file from last attempt.
1761         if base.ToolIsWindows {
1762                 if _, err := os.Stat(dst + "~"); err == nil {
1763                         os.Remove(dst + "~")
1764                 }
1765         }
1766
1767         mayberemovefile(dst)
1768         df, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm)
1769         if err != nil && base.ToolIsWindows {
1770                 // Windows does not allow deletion of a binary file
1771                 // while it is executing. Try to move it out of the way.
1772                 // If the move fails, which is likely, we'll try again the
1773                 // next time we do an install of this binary.
1774                 if err := os.Rename(dst, dst+"~"); err == nil {
1775                         os.Remove(dst + "~")
1776                 }
1777                 df, err = os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm)
1778         }
1779         if err != nil {
1780                 return fmt.Errorf("copying %s: %w", src, err) // err should already refer to dst
1781         }
1782
1783         _, err = io.Copy(df, sf)
1784         df.Close()
1785         if err != nil {
1786                 mayberemovefile(dst)
1787                 return fmt.Errorf("copying %s to %s: %v", src, dst, err)
1788         }
1789         return nil
1790 }
1791
1792 // writeFile writes the text to file.
1793 func (b *Builder) writeFile(file string, text []byte) error {
1794         if cfg.BuildN || cfg.BuildX {
1795                 b.Showcmd("", "cat >%s << 'EOF' # internal\n%sEOF", file, text)
1796         }
1797         if cfg.BuildN {
1798                 return nil
1799         }
1800         return os.WriteFile(file, text, 0666)
1801 }
1802
1803 // Install the cgo export header file, if there is one.
1804 func (b *Builder) installHeader(ctx context.Context, a *Action) error {
1805         src := a.Objdir + "_cgo_install.h"
1806         if _, err := os.Stat(src); os.IsNotExist(err) {
1807                 // If the file does not exist, there are no exported
1808                 // functions, and we do not install anything.
1809                 // TODO(rsc): Once we know that caching is rebuilding
1810                 // at the right times (not missing rebuilds), here we should
1811                 // probably delete the installed header, if any.
1812                 if cfg.BuildX {
1813                         b.Showcmd("", "# %s not created", src)
1814                 }
1815                 return nil
1816         }
1817
1818         if err := allowInstall(a); err != nil {
1819                 return err
1820         }
1821
1822         dir, _ := filepath.Split(a.Target)
1823         if dir != "" {
1824                 if err := b.Mkdir(dir); err != nil {
1825                         return err
1826                 }
1827         }
1828
1829         return b.moveOrCopyFile(a.Target, src, 0666, true)
1830 }
1831
1832 // cover runs, in effect,
1833 //      go tool cover -mode=b.coverMode -var="varName" -o dst.go src.go
1834 func (b *Builder) cover(a *Action, dst, src string, varName string) error {
1835         return b.run(a, a.Objdir, "cover "+a.Package.ImportPath, nil,
1836                 cfg.BuildToolexec,
1837                 base.Tool("cover"),
1838                 "-mode", a.Package.Internal.CoverMode,
1839                 "-var", varName,
1840                 "-o", dst,
1841                 src)
1842 }
1843
1844 var objectMagic = [][]byte{
1845         {'!', '<', 'a', 'r', 'c', 'h', '>', '\n'}, // Package archive
1846         {'<', 'b', 'i', 'g', 'a', 'f', '>', '\n'}, // Package AIX big archive
1847         {'\x7F', 'E', 'L', 'F'},                   // ELF
1848         {0xFE, 0xED, 0xFA, 0xCE},                  // Mach-O big-endian 32-bit
1849         {0xFE, 0xED, 0xFA, 0xCF},                  // Mach-O big-endian 64-bit
1850         {0xCE, 0xFA, 0xED, 0xFE},                  // Mach-O little-endian 32-bit
1851         {0xCF, 0xFA, 0xED, 0xFE},                  // Mach-O little-endian 64-bit
1852         {0x4d, 0x5a, 0x90, 0x00, 0x03, 0x00},      // PE (Windows) as generated by 6l/8l and gcc
1853         {0x4d, 0x5a, 0x78, 0x00, 0x01, 0x00},      // PE (Windows) as generated by llvm for dll
1854         {0x00, 0x00, 0x01, 0xEB},                  // Plan 9 i386
1855         {0x00, 0x00, 0x8a, 0x97},                  // Plan 9 amd64
1856         {0x00, 0x00, 0x06, 0x47},                  // Plan 9 arm
1857         {0x00, 0x61, 0x73, 0x6D},                  // WASM
1858         {0x01, 0xDF},                              // XCOFF 32bit
1859         {0x01, 0xF7},                              // XCOFF 64bit
1860 }
1861
1862 func isObject(s string) bool {
1863         f, err := os.Open(s)
1864         if err != nil {
1865                 return false
1866         }
1867         defer f.Close()
1868         buf := make([]byte, 64)
1869         io.ReadFull(f, buf)
1870         for _, magic := range objectMagic {
1871                 if bytes.HasPrefix(buf, magic) {
1872                         return true
1873                 }
1874         }
1875         return false
1876 }
1877
1878 // mayberemovefile removes a file only if it is a regular file
1879 // When running as a user with sufficient privileges, we may delete
1880 // even device files, for example, which is not intended.
1881 func mayberemovefile(s string) {
1882         if fi, err := os.Lstat(s); err == nil && !fi.Mode().IsRegular() {
1883                 return
1884         }
1885         os.Remove(s)
1886 }
1887
1888 // fmtcmd formats a command in the manner of fmt.Sprintf but also:
1889 //
1890 //      If dir is non-empty and the script is not in dir right now,
1891 //      fmtcmd inserts "cd dir\n" before the command.
1892 //
1893 //      fmtcmd replaces the value of b.WorkDir with $WORK.
1894 //      fmtcmd replaces the value of goroot with $GOROOT.
1895 //      fmtcmd replaces the value of b.gobin with $GOBIN.
1896 //
1897 //      fmtcmd replaces the name of the current directory with dot (.)
1898 //      but only when it is at the beginning of a space-separated token.
1899 //
1900 func (b *Builder) fmtcmd(dir string, format string, args ...interface{}) string {
1901         cmd := fmt.Sprintf(format, args...)
1902         if dir != "" && dir != "/" {
1903                 dot := " ."
1904                 if dir[len(dir)-1] == filepath.Separator {
1905                         dot += string(filepath.Separator)
1906                 }
1907                 cmd = strings.ReplaceAll(" "+cmd, " "+dir, dot)[1:]
1908                 if b.scriptDir != dir {
1909                         b.scriptDir = dir
1910                         cmd = "cd " + dir + "\n" + cmd
1911                 }
1912         }
1913         if b.WorkDir != "" {
1914                 cmd = strings.ReplaceAll(cmd, b.WorkDir, "$WORK")
1915                 escaped := strconv.Quote(b.WorkDir)
1916                 escaped = escaped[1 : len(escaped)-1] // strip quote characters
1917                 if escaped != b.WorkDir {
1918                         cmd = strings.ReplaceAll(cmd, escaped, "$WORK")
1919                 }
1920         }
1921         return cmd
1922 }
1923
1924 // showcmd prints the given command to standard output
1925 // for the implementation of -n or -x.
1926 func (b *Builder) Showcmd(dir string, format string, args ...interface{}) {
1927         b.output.Lock()
1928         defer b.output.Unlock()
1929         b.Print(b.fmtcmd(dir, format, args...) + "\n")
1930 }
1931
1932 // showOutput prints "# desc" followed by the given output.
1933 // The output is expected to contain references to 'dir', usually
1934 // the source directory for the package that has failed to build.
1935 // showOutput rewrites mentions of dir with a relative path to dir
1936 // when the relative path is shorter. This is usually more pleasant.
1937 // For example, if fmt doesn't compile and we are in src/html,
1938 // the output is
1939 //
1940 //      $ go build
1941 //      # fmt
1942 //      ../fmt/print.go:1090: undefined: asdf
1943 //      $
1944 //
1945 // instead of
1946 //
1947 //      $ go build
1948 //      # fmt
1949 //      /usr/gopher/go/src/fmt/print.go:1090: undefined: asdf
1950 //      $
1951 //
1952 // showOutput also replaces references to the work directory with $WORK.
1953 //
1954 // If a is not nil and a.output is not nil, showOutput appends to that slice instead of
1955 // printing to b.Print.
1956 //
1957 func (b *Builder) showOutput(a *Action, dir, desc, out string) {
1958         prefix := "# " + desc
1959         suffix := "\n" + out
1960         if reldir := base.ShortPath(dir); reldir != dir {
1961                 suffix = strings.ReplaceAll(suffix, " "+dir, " "+reldir)
1962                 suffix = strings.ReplaceAll(suffix, "\n"+dir, "\n"+reldir)
1963         }
1964         suffix = strings.ReplaceAll(suffix, " "+b.WorkDir, " $WORK")
1965
1966         if a != nil && a.output != nil {
1967                 a.output = append(a.output, prefix...)
1968                 a.output = append(a.output, suffix...)
1969                 return
1970         }
1971
1972         b.output.Lock()
1973         defer b.output.Unlock()
1974         b.Print(prefix, suffix)
1975 }
1976
1977 // errPrintedOutput is a special error indicating that a command failed
1978 // but that it generated output as well, and that output has already
1979 // been printed, so there's no point showing 'exit status 1' or whatever
1980 // the wait status was. The main executor, builder.do, knows not to
1981 // print this error.
1982 var errPrintedOutput = errors.New("already printed output - no need to show error")
1983
1984 var cgoLine = lazyregexp.New(`\[[^\[\]]+\.(cgo1|cover)\.go:[0-9]+(:[0-9]+)?\]`)
1985 var cgoTypeSigRe = lazyregexp.New(`\b_C2?(type|func|var|macro)_\B`)
1986
1987 // run runs the command given by cmdline in the directory dir.
1988 // If the command fails, run prints information about the failure
1989 // and returns a non-nil error.
1990 func (b *Builder) run(a *Action, dir string, desc string, env []string, cmdargs ...interface{}) error {
1991         out, err := b.runOut(a, dir, env, cmdargs...)
1992         if len(out) > 0 {
1993                 if desc == "" {
1994                         desc = b.fmtcmd(dir, "%s", strings.Join(str.StringList(cmdargs...), " "))
1995                 }
1996                 b.showOutput(a, dir, desc, b.processOutput(out))
1997                 if err != nil {
1998                         err = errPrintedOutput
1999                 }
2000         }
2001         return err
2002 }
2003
2004 // processOutput prepares the output of runOut to be output to the console.
2005 func (b *Builder) processOutput(out []byte) string {
2006         if out[len(out)-1] != '\n' {
2007                 out = append(out, '\n')
2008         }
2009         messages := string(out)
2010         // Fix up output referring to cgo-generated code to be more readable.
2011         // Replace x.go:19[/tmp/.../x.cgo1.go:18] with x.go:19.
2012         // Replace *[100]_Ctype_foo with *[100]C.foo.
2013         // If we're using -x, assume we're debugging and want the full dump, so disable the rewrite.
2014         if !cfg.BuildX && cgoLine.MatchString(messages) {
2015                 messages = cgoLine.ReplaceAllString(messages, "")
2016                 messages = cgoTypeSigRe.ReplaceAllString(messages, "C.")
2017         }
2018         return messages
2019 }
2020
2021 // runOut runs the command given by cmdline in the directory dir.
2022 // It returns the command output and any errors that occurred.
2023 // It accumulates execution time in a.
2024 func (b *Builder) runOut(a *Action, dir string, env []string, cmdargs ...interface{}) ([]byte, error) {
2025         cmdline := str.StringList(cmdargs...)
2026
2027         for _, arg := range cmdline {
2028                 // GNU binutils commands, including gcc and gccgo, interpret an argument
2029                 // @foo anywhere in the command line (even following --) as meaning
2030                 // "read and insert arguments from the file named foo."
2031                 // Don't say anything that might be misinterpreted that way.
2032                 if strings.HasPrefix(arg, "@") {
2033                         return nil, fmt.Errorf("invalid command-line argument %s in command: %s", arg, joinUnambiguously(cmdline))
2034                 }
2035         }
2036
2037         if cfg.BuildN || cfg.BuildX {
2038                 var envcmdline string
2039                 for _, e := range env {
2040                         if j := strings.IndexByte(e, '='); j != -1 {
2041                                 if strings.ContainsRune(e[j+1:], '\'') {
2042                                         envcmdline += fmt.Sprintf("%s=%q", e[:j], e[j+1:])
2043                                 } else {
2044                                         envcmdline += fmt.Sprintf("%s='%s'", e[:j], e[j+1:])
2045                                 }
2046                                 envcmdline += " "
2047                         }
2048                 }
2049                 envcmdline += joinUnambiguously(cmdline)
2050                 b.Showcmd(dir, "%s", envcmdline)
2051                 if cfg.BuildN {
2052                         return nil, nil
2053                 }
2054         }
2055
2056         var buf bytes.Buffer
2057         cmd := exec.Command(cmdline[0], cmdline[1:]...)
2058         if cmd.Path != "" {
2059                 cmd.Args[0] = cmd.Path
2060         }
2061         cmd.Stdout = &buf
2062         cmd.Stderr = &buf
2063         cleanup := passLongArgsInResponseFiles(cmd)
2064         defer cleanup()
2065         cmd.Dir = dir
2066         cmd.Env = base.AppendPWD(os.Environ(), cmd.Dir)
2067
2068         // Add the TOOLEXEC_IMPORTPATH environment variable for -toolexec tools.
2069         // It doesn't really matter if -toolexec isn't being used.
2070         if a != nil && a.Package != nil {
2071                 cmd.Env = append(cmd.Env, "TOOLEXEC_IMPORTPATH="+a.Package.ImportPath)
2072         }
2073
2074         cmd.Env = append(cmd.Env, env...)
2075         start := time.Now()
2076         err := cmd.Run()
2077         if a != nil && a.json != nil {
2078                 aj := a.json
2079                 aj.Cmd = append(aj.Cmd, joinUnambiguously(cmdline))
2080                 aj.CmdReal += time.Since(start)
2081                 if ps := cmd.ProcessState; ps != nil {
2082                         aj.CmdUser += ps.UserTime()
2083                         aj.CmdSys += ps.SystemTime()
2084                 }
2085         }
2086
2087         // err can be something like 'exit status 1'.
2088         // Add information about what program was running.
2089         // Note that if buf.Bytes() is non-empty, the caller usually
2090         // shows buf.Bytes() and does not print err at all, so the
2091         // prefix here does not make most output any more verbose.
2092         if err != nil {
2093                 err = errors.New(cmdline[0] + ": " + err.Error())
2094         }
2095         return buf.Bytes(), err
2096 }
2097
2098 // joinUnambiguously prints the slice, quoting where necessary to make the
2099 // output unambiguous.
2100 // TODO: See issue 5279. The printing of commands needs a complete redo.
2101 func joinUnambiguously(a []string) string {
2102         var buf bytes.Buffer
2103         for i, s := range a {
2104                 if i > 0 {
2105                         buf.WriteByte(' ')
2106                 }
2107                 q := strconv.Quote(s)
2108                 // A gccgo command line can contain -( and -).
2109                 // Make sure we quote them since they are special to the shell.
2110                 // The trimpath argument can also contain > (part of =>) and ;. Quote those too.
2111                 if s == "" || strings.ContainsAny(s, " ()>;") || len(q) > len(s)+2 {
2112                         buf.WriteString(q)
2113                 } else {
2114                         buf.WriteString(s)
2115                 }
2116         }
2117         return buf.String()
2118 }
2119
2120 // cCompilerEnv returns environment variables to set when running the
2121 // C compiler. This is needed to disable escape codes in clang error
2122 // messages that confuse tools like cgo.
2123 func (b *Builder) cCompilerEnv() []string {
2124         return []string{"TERM=dumb"}
2125 }
2126
2127 // mkdir makes the named directory.
2128 func (b *Builder) Mkdir(dir string) error {
2129         // Make Mkdir(a.Objdir) a no-op instead of an error when a.Objdir == "".
2130         if dir == "" {
2131                 return nil
2132         }
2133
2134         b.exec.Lock()
2135         defer b.exec.Unlock()
2136         // We can be a little aggressive about being
2137         // sure directories exist. Skip repeated calls.
2138         if b.mkdirCache[dir] {
2139                 return nil
2140         }
2141         b.mkdirCache[dir] = true
2142
2143         if cfg.BuildN || cfg.BuildX {
2144                 b.Showcmd("", "mkdir -p %s", dir)
2145                 if cfg.BuildN {
2146                         return nil
2147                 }
2148         }
2149
2150         if err := os.MkdirAll(dir, 0777); err != nil {
2151                 return err
2152         }
2153         return nil
2154 }
2155
2156 // symlink creates a symlink newname -> oldname.
2157 func (b *Builder) Symlink(oldname, newname string) error {
2158         // It's not an error to try to recreate an existing symlink.
2159         if link, err := os.Readlink(newname); err == nil && link == oldname {
2160                 return nil
2161         }
2162
2163         if cfg.BuildN || cfg.BuildX {
2164                 b.Showcmd("", "ln -s %s %s", oldname, newname)
2165                 if cfg.BuildN {
2166                         return nil
2167                 }
2168         }
2169         return os.Symlink(oldname, newname)
2170 }
2171
2172 // mkAbs returns an absolute path corresponding to
2173 // evaluating f in the directory dir.
2174 // We always pass absolute paths of source files so that
2175 // the error messages will include the full path to a file
2176 // in need of attention.
2177 func mkAbs(dir, f string) string {
2178         // Leave absolute paths alone.
2179         // Also, during -n mode we use the pseudo-directory $WORK
2180         // instead of creating an actual work directory that won't be used.
2181         // Leave paths beginning with $WORK alone too.
2182         if filepath.IsAbs(f) || strings.HasPrefix(f, "$WORK") {
2183                 return f
2184         }
2185         return filepath.Join(dir, f)
2186 }
2187
2188 type toolchain interface {
2189         // gc runs the compiler in a specific directory on a set of files
2190         // and returns the name of the generated output file.
2191         gc(b *Builder, a *Action, archive string, importcfg, embedcfg []byte, symabis string, asmhdr bool, gofiles []string) (ofile string, out []byte, err error)
2192         // cc runs the toolchain's C compiler in a directory on a C file
2193         // to produce an output file.
2194         cc(b *Builder, a *Action, ofile, cfile string) error
2195         // asm runs the assembler in a specific directory on specific files
2196         // and returns a list of named output files.
2197         asm(b *Builder, a *Action, sfiles []string) ([]string, error)
2198         // symabis scans the symbol ABIs from sfiles and returns the
2199         // path to the output symbol ABIs file, or "" if none.
2200         symabis(b *Builder, a *Action, sfiles []string) (string, error)
2201         // pack runs the archive packer in a specific directory to create
2202         // an archive from a set of object files.
2203         // typically it is run in the object directory.
2204         pack(b *Builder, a *Action, afile string, ofiles []string) error
2205         // ld runs the linker to create an executable starting at mainpkg.
2206         ld(b *Builder, root *Action, out, importcfg, mainpkg string) error
2207         // ldShared runs the linker to create a shared library containing the pkgs built by toplevelactions
2208         ldShared(b *Builder, root *Action, toplevelactions []*Action, out, importcfg string, allactions []*Action) error
2209
2210         compiler() string
2211         linker() string
2212 }
2213
2214 type noToolchain struct{}
2215
2216 func noCompiler() error {
2217         log.Fatalf("unknown compiler %q", cfg.BuildContext.Compiler)
2218         return nil
2219 }
2220
2221 func (noToolchain) compiler() string {
2222         noCompiler()
2223         return ""
2224 }
2225
2226 func (noToolchain) linker() string {
2227         noCompiler()
2228         return ""
2229 }
2230
2231 func (noToolchain) gc(b *Builder, a *Action, archive string, importcfg, embedcfg []byte, symabis string, asmhdr bool, gofiles []string) (ofile string, out []byte, err error) {
2232         return "", nil, noCompiler()
2233 }
2234
2235 func (noToolchain) asm(b *Builder, a *Action, sfiles []string) ([]string, error) {
2236         return nil, noCompiler()
2237 }
2238
2239 func (noToolchain) symabis(b *Builder, a *Action, sfiles []string) (string, error) {
2240         return "", noCompiler()
2241 }
2242
2243 func (noToolchain) pack(b *Builder, a *Action, afile string, ofiles []string) error {
2244         return noCompiler()
2245 }
2246
2247 func (noToolchain) ld(b *Builder, root *Action, out, importcfg, mainpkg string) error {
2248         return noCompiler()
2249 }
2250
2251 func (noToolchain) ldShared(b *Builder, root *Action, toplevelactions []*Action, out, importcfg string, allactions []*Action) error {
2252         return noCompiler()
2253 }
2254
2255 func (noToolchain) cc(b *Builder, a *Action, ofile, cfile string) error {
2256         return noCompiler()
2257 }
2258
2259 // gcc runs the gcc C compiler to create an object from a single C file.
2260 func (b *Builder) gcc(a *Action, p *load.Package, workdir, out string, flags []string, cfile string) error {
2261         return b.ccompile(a, p, out, flags, cfile, b.GccCmd(p.Dir, workdir))
2262 }
2263
2264 // gxx runs the g++ C++ compiler to create an object from a single C++ file.
2265 func (b *Builder) gxx(a *Action, p *load.Package, workdir, out string, flags []string, cxxfile string) error {
2266         return b.ccompile(a, p, out, flags, cxxfile, b.GxxCmd(p.Dir, workdir))
2267 }
2268
2269 // gfortran runs the gfortran Fortran compiler to create an object from a single Fortran file.
2270 func (b *Builder) gfortran(a *Action, p *load.Package, workdir, out string, flags []string, ffile string) error {
2271         return b.ccompile(a, p, out, flags, ffile, b.gfortranCmd(p.Dir, workdir))
2272 }
2273
2274 // ccompile runs the given C or C++ compiler and creates an object from a single source file.
2275 func (b *Builder) ccompile(a *Action, p *load.Package, outfile string, flags []string, file string, compiler []string) error {
2276         file = mkAbs(p.Dir, file)
2277         desc := p.ImportPath
2278         outfile = mkAbs(p.Dir, outfile)
2279
2280         // Elide source directory paths if -trimpath or GOROOT_FINAL is set.
2281         // This is needed for source files (e.g., a .c file in a package directory).
2282         // TODO(golang.org/issue/36072): cgo also generates files with #line
2283         // directives pointing to the source directory. It should not generate those
2284         // when -trimpath is enabled.
2285         if b.gccSupportsFlag(compiler, "-fdebug-prefix-map=a=b") {
2286                 if cfg.BuildTrimpath {
2287                         // Keep in sync with Action.trimpath.
2288                         // The trimmed paths are a little different, but we need to trim in the
2289                         // same situations.
2290                         var from, toPath string
2291                         if m := p.Module; m != nil {
2292                                 from = m.Dir
2293                                 toPath = m.Path + "@" + m.Version
2294                         } else {
2295                                 from = p.Dir
2296                                 toPath = p.ImportPath
2297                         }
2298                         // -fdebug-prefix-map requires an absolute "to" path (or it joins the path
2299                         // with the working directory). Pick something that makes sense for the
2300                         // target platform.
2301                         var to string
2302                         if cfg.BuildContext.GOOS == "windows" {
2303                                 to = filepath.Join(`\\_\_`, toPath)
2304                         } else {
2305                                 to = filepath.Join("/_", toPath)
2306                         }
2307                         flags = append(flags[:len(flags):len(flags)], "-fdebug-prefix-map="+from+"="+to)
2308                 } else if p.Goroot && cfg.GOROOT_FINAL != cfg.GOROOT {
2309                         flags = append(flags[:len(flags):len(flags)], "-fdebug-prefix-map="+cfg.GOROOT+"="+cfg.GOROOT_FINAL)
2310                 }
2311         }
2312
2313         overlayPath := file
2314         if p, ok := a.nonGoOverlay[overlayPath]; ok {
2315                 overlayPath = p
2316         }
2317         output, err := b.runOut(a, filepath.Dir(overlayPath), b.cCompilerEnv(), compiler, flags, "-o", outfile, "-c", filepath.Base(overlayPath))
2318         if len(output) > 0 {
2319                 // On FreeBSD 11, when we pass -g to clang 3.8 it
2320                 // invokes its internal assembler with -dwarf-version=2.
2321                 // When it sees .section .note.GNU-stack, it warns
2322                 // "DWARF2 only supports one section per compilation unit".
2323                 // This warning makes no sense, since the section is empty,
2324                 // but it confuses people.
2325                 // We work around the problem by detecting the warning
2326                 // and dropping -g and trying again.
2327                 if bytes.Contains(output, []byte("DWARF2 only supports one section per compilation unit")) {
2328                         newFlags := make([]string, 0, len(flags))
2329                         for _, f := range flags {
2330                                 if !strings.HasPrefix(f, "-g") {
2331                                         newFlags = append(newFlags, f)
2332                                 }
2333                         }
2334                         if len(newFlags) < len(flags) {
2335                                 return b.ccompile(a, p, outfile, newFlags, file, compiler)
2336                         }
2337                 }
2338
2339                 b.showOutput(a, p.Dir, desc, b.processOutput(output))
2340                 if err != nil {
2341                         err = errPrintedOutput
2342                 } else if os.Getenv("GO_BUILDER_NAME") != "" {
2343                         return errors.New("C compiler warning promoted to error on Go builders")
2344                 }
2345         }
2346         return err
2347 }
2348
2349 // gccld runs the gcc linker to create an executable from a set of object files.
2350 func (b *Builder) gccld(a *Action, p *load.Package, objdir, outfile string, flags []string, objs []string) error {
2351         var cmd []string
2352         if len(p.CXXFiles) > 0 || len(p.SwigCXXFiles) > 0 {
2353                 cmd = b.GxxCmd(p.Dir, objdir)
2354         } else {
2355                 cmd = b.GccCmd(p.Dir, objdir)
2356         }
2357
2358         cmdargs := []interface{}{cmd, "-o", outfile, objs, flags}
2359         dir := p.Dir
2360         out, err := b.runOut(a, base.Cwd, b.cCompilerEnv(), cmdargs...)
2361
2362         if len(out) > 0 {
2363                 // Filter out useless linker warnings caused by bugs outside Go.
2364                 // See also cmd/link/internal/ld's hostlink method.
2365                 var save [][]byte
2366                 var skipLines int
2367                 for _, line := range bytes.SplitAfter(out, []byte("\n")) {
2368                         // golang.org/issue/26073 - Apple Xcode bug
2369                         if bytes.Contains(line, []byte("ld: warning: text-based stub file")) {
2370                                 continue
2371                         }
2372
2373                         if skipLines > 0 {
2374                                 skipLines--
2375                                 continue
2376                         }
2377
2378                         // Remove duplicate main symbol with runtime/cgo on AIX.
2379                         // With runtime/cgo, two main are available:
2380                         // One is generated by cgo tool with {return 0;}.
2381                         // The other one is the main calling runtime.rt0_go
2382                         // in runtime/cgo.
2383                         // The second can't be used by cgo programs because
2384                         // runtime.rt0_go is unknown to them.
2385                         // Therefore, we let ld remove this main version
2386                         // and used the cgo generated one.
2387                         if p.ImportPath == "runtime/cgo" && bytes.Contains(line, []byte("ld: 0711-224 WARNING: Duplicate symbol: .main")) {
2388                                 skipLines = 1
2389                                 continue
2390                         }
2391
2392                         save = append(save, line)
2393                 }
2394                 out = bytes.Join(save, nil)
2395                 if len(out) > 0 {
2396                         b.showOutput(nil, dir, p.ImportPath, b.processOutput(out))
2397                         if err != nil {
2398                                 err = errPrintedOutput
2399                         }
2400                 }
2401         }
2402         return err
2403 }
2404
2405 // Grab these before main helpfully overwrites them.
2406 var (
2407         origCC  = cfg.Getenv("CC")
2408         origCXX = cfg.Getenv("CXX")
2409 )
2410
2411 // gccCmd returns a gcc command line prefix
2412 // defaultCC is defined in zdefaultcc.go, written by cmd/dist.
2413 func (b *Builder) GccCmd(incdir, workdir string) []string {
2414         return b.compilerCmd(b.ccExe(), incdir, workdir)
2415 }
2416
2417 // gxxCmd returns a g++ command line prefix
2418 // defaultCXX is defined in zdefaultcc.go, written by cmd/dist.
2419 func (b *Builder) GxxCmd(incdir, workdir string) []string {
2420         return b.compilerCmd(b.cxxExe(), incdir, workdir)
2421 }
2422
2423 // gfortranCmd returns a gfortran command line prefix.
2424 func (b *Builder) gfortranCmd(incdir, workdir string) []string {
2425         return b.compilerCmd(b.fcExe(), incdir, workdir)
2426 }
2427
2428 // ccExe returns the CC compiler setting without all the extra flags we add implicitly.
2429 func (b *Builder) ccExe() []string {
2430         return b.compilerExe(origCC, cfg.DefaultCC(cfg.Goos, cfg.Goarch))
2431 }
2432
2433 // cxxExe returns the CXX compiler setting without all the extra flags we add implicitly.
2434 func (b *Builder) cxxExe() []string {
2435         return b.compilerExe(origCXX, cfg.DefaultCXX(cfg.Goos, cfg.Goarch))
2436 }
2437
2438 // fcExe returns the FC compiler setting without all the extra flags we add implicitly.
2439 func (b *Builder) fcExe() []string {
2440         return b.compilerExe(cfg.Getenv("FC"), "gfortran")
2441 }
2442
2443 // compilerExe returns the compiler to use given an
2444 // environment variable setting (the value not the name)
2445 // and a default. The resulting slice is usually just the name
2446 // of the compiler but can have additional arguments if they
2447 // were present in the environment value.
2448 // For example if CC="gcc -DGOPHER" then the result is ["gcc", "-DGOPHER"].
2449 func (b *Builder) compilerExe(envValue string, def string) []string {
2450         compiler := strings.Fields(envValue)
2451         if len(compiler) == 0 {
2452                 compiler = strings.Fields(def)
2453         }
2454         return compiler
2455 }
2456
2457 // compilerCmd returns a command line prefix for the given environment
2458 // variable and using the default command when the variable is empty.
2459 func (b *Builder) compilerCmd(compiler []string, incdir, workdir string) []string {
2460         // NOTE: env.go's mkEnv knows that the first three
2461         // strings returned are "gcc", "-I", incdir (and cuts them off).
2462         a := []string{compiler[0], "-I", incdir}
2463         a = append(a, compiler[1:]...)
2464
2465         // Definitely want -fPIC but on Windows gcc complains
2466         // "-fPIC ignored for target (all code is position independent)"
2467         if cfg.Goos != "windows" {
2468                 a = append(a, "-fPIC")
2469         }
2470         a = append(a, b.gccArchArgs()...)
2471         // gcc-4.5 and beyond require explicit "-pthread" flag
2472         // for multithreading with pthread library.
2473         if cfg.BuildContext.CgoEnabled {
2474                 switch cfg.Goos {
2475                 case "windows":
2476                         a = append(a, "-mthreads")
2477                 default:
2478                         a = append(a, "-pthread")
2479                 }
2480         }
2481
2482         if cfg.Goos == "aix" {
2483                 // mcmodel=large must always be enabled to allow large TOC.
2484                 a = append(a, "-mcmodel=large")
2485         }
2486
2487         // disable ASCII art in clang errors, if possible
2488         if b.gccSupportsFlag(compiler, "-fno-caret-diagnostics") {
2489                 a = append(a, "-fno-caret-diagnostics")
2490         }
2491         // clang is too smart about command-line arguments
2492         if b.gccSupportsFlag(compiler, "-Qunused-arguments") {
2493                 a = append(a, "-Qunused-arguments")
2494         }
2495
2496         // disable word wrapping in error messages
2497         a = append(a, "-fmessage-length=0")
2498
2499         // Tell gcc not to include the work directory in object files.
2500         if b.gccSupportsFlag(compiler, "-fdebug-prefix-map=a=b") {
2501                 if workdir == "" {
2502                         workdir = b.WorkDir
2503                 }
2504                 workdir = strings.TrimSuffix(workdir, string(filepath.Separator))
2505                 a = append(a, "-fdebug-prefix-map="+workdir+"=/tmp/go-build")
2506         }
2507
2508         // Tell gcc not to include flags in object files, which defeats the
2509         // point of -fdebug-prefix-map above.
2510         if b.gccSupportsFlag(compiler, "-gno-record-gcc-switches") {
2511                 a = append(a, "-gno-record-gcc-switches")
2512         }
2513
2514         // On OS X, some of the compilers behave as if -fno-common
2515         // is always set, and the Mach-O linker in 6l/8l assumes this.
2516         // See https://golang.org/issue/3253.
2517         if cfg.Goos == "darwin" || cfg.Goos == "ios" {
2518                 a = append(a, "-fno-common")
2519         }
2520
2521         return a
2522 }
2523
2524 // gccNoPie returns the flag to use to request non-PIE. On systems
2525 // with PIE (position independent executables) enabled by default,
2526 // -no-pie must be passed when doing a partial link with -Wl,-r.
2527 // But -no-pie is not supported by all compilers, and clang spells it -nopie.
2528 func (b *Builder) gccNoPie(linker []string) string {
2529         if b.gccSupportsFlag(linker, "-no-pie") {
2530                 return "-no-pie"
2531         }
2532         if b.gccSupportsFlag(linker, "-nopie") {
2533                 return "-nopie"
2534         }
2535         return ""
2536 }
2537
2538 // gccSupportsFlag checks to see if the compiler supports a flag.
2539 func (b *Builder) gccSupportsFlag(compiler []string, flag string) bool {
2540         key := [2]string{compiler[0], flag}
2541
2542         b.exec.Lock()
2543         defer b.exec.Unlock()
2544         if b, ok := b.flagCache[key]; ok {
2545                 return b
2546         }
2547         if b.flagCache == nil {
2548                 b.flagCache = make(map[[2]string]bool)
2549         }
2550
2551         tmp := os.DevNull
2552         if runtime.GOOS == "windows" {
2553                 f, err := os.CreateTemp(b.WorkDir, "")
2554                 if err != nil {
2555                         return false
2556                 }
2557                 f.Close()
2558                 tmp = f.Name()
2559                 defer os.Remove(tmp)
2560         }
2561
2562         // We used to write an empty C file, but that gets complicated with
2563         // go build -n. We tried using a file that does not exist, but that
2564         // fails on systems with GCC version 4.2.1; that is the last GPLv2
2565         // version of GCC, so some systems have frozen on it.
2566         // Now we pass an empty file on stdin, which should work at least for
2567         // GCC and clang.
2568         cmdArgs := str.StringList(compiler, flag, "-c", "-x", "c", "-", "-o", tmp)
2569         if cfg.BuildN || cfg.BuildX {
2570                 b.Showcmd(b.WorkDir, "%s || true", joinUnambiguously(cmdArgs))
2571                 if cfg.BuildN {
2572                         return false
2573                 }
2574         }
2575         cmd := exec.Command(cmdArgs[0], cmdArgs[1:]...)
2576         cmd.Dir = b.WorkDir
2577         cmd.Env = base.AppendPWD(os.Environ(), cmd.Dir)
2578         cmd.Env = append(cmd.Env, "LC_ALL=C")
2579         out, _ := cmd.CombinedOutput()
2580         // GCC says "unrecognized command line option".
2581         // clang says "unknown argument".
2582         // Older versions of GCC say "unrecognised debug output level".
2583         // For -fsplit-stack GCC says "'-fsplit-stack' is not supported".
2584         supported := !bytes.Contains(out, []byte("unrecognized")) &&
2585                 !bytes.Contains(out, []byte("unknown")) &&
2586                 !bytes.Contains(out, []byte("unrecognised")) &&
2587                 !bytes.Contains(out, []byte("is not supported"))
2588         b.flagCache[key] = supported
2589         return supported
2590 }
2591
2592 // gccArchArgs returns arguments to pass to gcc based on the architecture.
2593 func (b *Builder) gccArchArgs() []string {
2594         switch cfg.Goarch {
2595         case "386":
2596                 return []string{"-m32"}
2597         case "amd64":
2598                 if cfg.Goos == "darwin" {
2599                         return []string{"-arch", "x86_64", "-m64"}
2600                 }
2601                 return []string{"-m64"}
2602         case "arm64":
2603                 if cfg.Goos == "darwin" {
2604                         return []string{"-arch", "arm64"}
2605                 }
2606         case "arm":
2607                 return []string{"-marm"} // not thumb
2608         case "s390x":
2609                 return []string{"-m64", "-march=z196"}
2610         case "mips64", "mips64le":
2611                 args := []string{"-mabi=64"}
2612                 if cfg.GOMIPS64 == "hardfloat" {
2613                         return append(args, "-mhard-float")
2614                 } else if cfg.GOMIPS64 == "softfloat" {
2615                         return append(args, "-msoft-float")
2616                 }
2617         case "mips", "mipsle":
2618                 args := []string{"-mabi=32", "-march=mips32"}
2619                 if cfg.GOMIPS == "hardfloat" {
2620                         return append(args, "-mhard-float", "-mfp32", "-mno-odd-spreg")
2621                 } else if cfg.GOMIPS == "softfloat" {
2622                         return append(args, "-msoft-float")
2623                 }
2624         case "ppc64":
2625                 if cfg.Goos == "aix" {
2626                         return []string{"-maix64"}
2627                 }
2628         }
2629         return nil
2630 }
2631
2632 // envList returns the value of the given environment variable broken
2633 // into fields, using the default value when the variable is empty.
2634 func envList(key, def string) []string {
2635         v := cfg.Getenv(key)
2636         if v == "" {
2637                 v = def
2638         }
2639         return strings.Fields(v)
2640 }
2641
2642 // CFlags returns the flags to use when invoking the C, C++ or Fortran compilers, or cgo.
2643 func (b *Builder) CFlags(p *load.Package) (cppflags, cflags, cxxflags, fflags, ldflags []string, err error) {
2644         defaults := "-g -O2"
2645
2646         if cppflags, err = buildFlags("CPPFLAGS", "", p.CgoCPPFLAGS, checkCompilerFlags); err != nil {
2647                 return
2648         }
2649         if cflags, err = buildFlags("CFLAGS", defaults, p.CgoCFLAGS, checkCompilerFlags); err != nil {
2650                 return
2651         }
2652         if cxxflags, err = buildFlags("CXXFLAGS", defaults, p.CgoCXXFLAGS, checkCompilerFlags); err != nil {
2653                 return
2654         }
2655         if fflags, err = buildFlags("FFLAGS", defaults, p.CgoFFLAGS, checkCompilerFlags); err != nil {
2656                 return
2657         }
2658         if ldflags, err = buildFlags("LDFLAGS", defaults, p.CgoLDFLAGS, checkLinkerFlags); err != nil {
2659                 return
2660         }
2661
2662         return
2663 }
2664
2665 func buildFlags(name, defaults string, fromPackage []string, check func(string, string, []string) error) ([]string, error) {
2666         if err := check(name, "#cgo "+name, fromPackage); err != nil {
2667                 return nil, err
2668         }
2669         return str.StringList(envList("CGO_"+name, defaults), fromPackage), nil
2670 }
2671
2672 var cgoRe = lazyregexp.New(`[/\\:]`)
2673
2674 func (b *Builder) cgo(a *Action, cgoExe, objdir string, pcCFLAGS, pcLDFLAGS, cgofiles, gccfiles, gxxfiles, mfiles, ffiles []string) (outGo, outObj []string, err error) {
2675         p := a.Package
2676         cgoCPPFLAGS, cgoCFLAGS, cgoCXXFLAGS, cgoFFLAGS, cgoLDFLAGS, err := b.CFlags(p)
2677         if err != nil {
2678                 return nil, nil, err
2679         }
2680
2681         cgoCPPFLAGS = append(cgoCPPFLAGS, pcCFLAGS...)
2682         cgoLDFLAGS = append(cgoLDFLAGS, pcLDFLAGS...)
2683         // If we are compiling Objective-C code, then we need to link against libobjc
2684         if len(mfiles) > 0 {
2685                 cgoLDFLAGS = append(cgoLDFLAGS, "-lobjc")
2686         }
2687
2688         // Likewise for Fortran, except there are many Fortran compilers.
2689         // Support gfortran out of the box and let others pass the correct link options
2690         // via CGO_LDFLAGS
2691         if len(ffiles) > 0 {
2692                 fc := cfg.Getenv("FC")
2693                 if fc == "" {
2694                         fc = "gfortran"
2695                 }
2696                 if strings.Contains(fc, "gfortran") {
2697                         cgoLDFLAGS = append(cgoLDFLAGS, "-lgfortran")
2698                 }
2699         }
2700
2701         if cfg.BuildMSan {
2702                 cgoCFLAGS = append([]string{"-fsanitize=memory"}, cgoCFLAGS...)
2703                 cgoLDFLAGS = append([]string{"-fsanitize=memory"}, cgoLDFLAGS...)
2704         }
2705
2706         // Allows including _cgo_export.h, as well as the user's .h files,
2707         // from .[ch] files in the package.
2708         cgoCPPFLAGS = append(cgoCPPFLAGS, "-I", objdir)
2709
2710         // cgo
2711         // TODO: CGO_FLAGS?
2712         gofiles := []string{objdir + "_cgo_gotypes.go"}
2713         cfiles := []string{"_cgo_export.c"}
2714         for _, fn := range cgofiles {
2715                 f := strings.TrimSuffix(filepath.Base(fn), ".go")
2716                 gofiles = append(gofiles, objdir+f+".cgo1.go")
2717                 cfiles = append(cfiles, f+".cgo2.c")
2718         }
2719
2720         // TODO: make cgo not depend on $GOARCH?
2721
2722         cgoflags := []string{}
2723         if p.Standard && p.ImportPath == "runtime/cgo" {
2724                 cgoflags = append(cgoflags, "-import_runtime_cgo=false")
2725         }
2726         if p.Standard && (p.ImportPath == "runtime/race" || p.ImportPath == "runtime/msan" || p.ImportPath == "runtime/cgo") {
2727                 cgoflags = append(cgoflags, "-import_syscall=false")
2728         }
2729
2730         // Update $CGO_LDFLAGS with p.CgoLDFLAGS.
2731         // These flags are recorded in the generated _cgo_gotypes.go file
2732         // using //go:cgo_ldflag directives, the compiler records them in the
2733         // object file for the package, and then the Go linker passes them
2734         // along to the host linker. At this point in the code, cgoLDFLAGS
2735         // consists of the original $CGO_LDFLAGS (unchecked) and all the
2736         // flags put together from source code (checked).
2737         cgoenv := b.cCompilerEnv()
2738         if len(cgoLDFLAGS) > 0 {
2739                 flags := make([]string, len(cgoLDFLAGS))
2740                 for i, f := range cgoLDFLAGS {
2741                         flags[i] = strconv.Quote(f)
2742                 }
2743                 cgoenv = append(cgoenv, "CGO_LDFLAGS="+strings.Join(flags, " "))
2744         }
2745
2746         if cfg.BuildToolchainName == "gccgo" {
2747                 if b.gccSupportsFlag([]string{BuildToolchain.compiler()}, "-fsplit-stack") {
2748                         cgoCFLAGS = append(cgoCFLAGS, "-fsplit-stack")
2749                 }
2750                 cgoflags = append(cgoflags, "-gccgo")
2751                 if pkgpath := gccgoPkgpath(p); pkgpath != "" {
2752                         cgoflags = append(cgoflags, "-gccgopkgpath="+pkgpath)
2753                 }
2754         }
2755
2756         switch cfg.BuildBuildmode {
2757         case "c-archive", "c-shared":
2758                 // Tell cgo that if there are any exported functions
2759                 // it should generate a header file that C code can
2760                 // #include.
2761                 cgoflags = append(cgoflags, "-exportheader="+objdir+"_cgo_install.h")
2762         }
2763
2764         execdir := p.Dir
2765
2766         // Rewrite overlaid paths in cgo files.
2767         // cgo adds //line and #line pragmas in generated files with these paths.
2768         var trimpath []string
2769         for i := range cgofiles {
2770                 path := mkAbs(p.Dir, cgofiles[i])
2771                 if opath, ok := fsys.OverlayPath(path); ok {
2772                         cgofiles[i] = opath
2773                         trimpath = append(trimpath, opath+"=>"+path)
2774                 }
2775         }
2776         if len(trimpath) > 0 {
2777                 cgoflags = append(cgoflags, "-trimpath", strings.Join(trimpath, ";"))
2778         }
2779
2780         if err := b.run(a, execdir, p.ImportPath, cgoenv, cfg.BuildToolexec, cgoExe, "-objdir", objdir, "-importpath", p.ImportPath, cgoflags, "--", cgoCPPFLAGS, cgoCFLAGS, cgofiles); err != nil {
2781                 return nil, nil, err
2782         }
2783         outGo = append(outGo, gofiles...)
2784
2785         // Use sequential object file names to keep them distinct
2786         // and short enough to fit in the .a header file name slots.
2787         // We no longer collect them all into _all.o, and we'd like
2788         // tools to see both the .o suffix and unique names, so
2789         // we need to make them short enough not to be truncated
2790         // in the final archive.
2791         oseq := 0
2792         nextOfile := func() string {
2793                 oseq++
2794                 return objdir + fmt.Sprintf("_x%03d.o", oseq)
2795         }
2796
2797         // gcc
2798         cflags := str.StringList(cgoCPPFLAGS, cgoCFLAGS)
2799         for _, cfile := range cfiles {
2800                 ofile := nextOfile()
2801                 if err := b.gcc(a, p, a.Objdir, ofile, cflags, objdir+cfile); err != nil {
2802                         return nil, nil, err
2803                 }
2804                 outObj = append(outObj, ofile)
2805         }
2806
2807         for _, file := range gccfiles {
2808                 ofile := nextOfile()
2809                 if err := b.gcc(a, p, a.Objdir, ofile, cflags, file); err != nil {
2810                         return nil, nil, err
2811                 }
2812                 outObj = append(outObj, ofile)
2813         }
2814
2815         cxxflags := str.StringList(cgoCPPFLAGS, cgoCXXFLAGS)
2816         for _, file := range gxxfiles {
2817                 ofile := nextOfile()
2818                 if err := b.gxx(a, p, a.Objdir, ofile, cxxflags, file); err != nil {
2819                         return nil, nil, err
2820                 }
2821                 outObj = append(outObj, ofile)
2822         }
2823
2824         for _, file := range mfiles {
2825                 ofile := nextOfile()
2826                 if err := b.gcc(a, p, a.Objdir, ofile, cflags, file); err != nil {
2827                         return nil, nil, err
2828                 }
2829                 outObj = append(outObj, ofile)
2830         }
2831
2832         fflags := str.StringList(cgoCPPFLAGS, cgoFFLAGS)
2833         for _, file := range ffiles {
2834                 ofile := nextOfile()
2835                 if err := b.gfortran(a, p, a.Objdir, ofile, fflags, file); err != nil {
2836                         return nil, nil, err
2837                 }
2838                 outObj = append(outObj, ofile)
2839         }
2840
2841         switch cfg.BuildToolchainName {
2842         case "gc":
2843                 importGo := objdir + "_cgo_import.go"
2844                 if err := b.dynimport(a, p, objdir, importGo, cgoExe, cflags, cgoLDFLAGS, outObj); err != nil {
2845                         return nil, nil, err
2846                 }
2847                 outGo = append(outGo, importGo)
2848
2849         case "gccgo":
2850                 defunC := objdir + "_cgo_defun.c"
2851                 defunObj := objdir + "_cgo_defun.o"
2852                 if err := BuildToolchain.cc(b, a, defunObj, defunC); err != nil {
2853                         return nil, nil, err
2854                 }
2855                 outObj = append(outObj, defunObj)
2856
2857         default:
2858                 noCompiler()
2859         }
2860
2861         // Double check the //go:cgo_ldflag comments in the generated files.
2862         // The compiler only permits such comments in files whose base name
2863         // starts with "_cgo_". Make sure that the comments in those files
2864         // are safe. This is a backstop against people somehow smuggling
2865         // such a comment into a file generated by cgo.
2866         if cfg.BuildToolchainName == "gc" && !cfg.BuildN {
2867                 var flags []string
2868                 for _, f := range outGo {
2869                         if !strings.HasPrefix(filepath.Base(f), "_cgo_") {
2870                                 continue
2871                         }
2872
2873                         src, err := os.ReadFile(f)
2874                         if err != nil {
2875                                 return nil, nil, err
2876                         }
2877
2878                         const cgoLdflag = "//go:cgo_ldflag"
2879                         idx := bytes.Index(src, []byte(cgoLdflag))
2880                         for idx >= 0 {
2881                                 // We are looking at //go:cgo_ldflag.
2882                                 // Find start of line.
2883                                 start := bytes.LastIndex(src[:idx], []byte("\n"))
2884                                 if start == -1 {
2885                                         start = 0
2886                                 }
2887
2888                                 // Find end of line.
2889                                 end := bytes.Index(src[idx:], []byte("\n"))
2890                                 if end == -1 {
2891                                         end = len(src)
2892                                 } else {
2893                                         end += idx
2894                                 }
2895
2896                                 // Check for first line comment in line.
2897                                 // We don't worry about /* */ comments,
2898                                 // which normally won't appear in files
2899                                 // generated by cgo.
2900                                 commentStart := bytes.Index(src[start:], []byte("//"))
2901                                 commentStart += start
2902                                 // If that line comment is //go:cgo_ldflag,
2903                                 // it's a match.
2904                                 if bytes.HasPrefix(src[commentStart:], []byte(cgoLdflag)) {
2905                                         // Pull out the flag, and unquote it.
2906                                         // This is what the compiler does.
2907                                         flag := string(src[idx+len(cgoLdflag) : end])
2908                                         flag = strings.TrimSpace(flag)
2909                                         flag = strings.Trim(flag, `"`)
2910                                         flags = append(flags, flag)
2911                                 }
2912                                 src = src[end:]
2913                                 idx = bytes.Index(src, []byte(cgoLdflag))
2914                         }
2915                 }
2916
2917                 // We expect to find the contents of cgoLDFLAGS in flags.
2918                 if len(cgoLDFLAGS) > 0 {
2919                 outer:
2920                         for i := range flags {
2921                                 for j, f := range cgoLDFLAGS {
2922                                         if f != flags[i+j] {
2923                                                 continue outer
2924                                         }
2925                                 }
2926                                 flags = append(flags[:i], flags[i+len(cgoLDFLAGS):]...)
2927                                 break
2928                         }
2929                 }
2930
2931                 if err := checkLinkerFlags("LDFLAGS", "go:cgo_ldflag", flags); err != nil {
2932                         return nil, nil, err
2933                 }
2934         }
2935
2936         return outGo, outObj, nil
2937 }
2938
2939 // dynimport creates a Go source file named importGo containing
2940 // //go:cgo_import_dynamic directives for each symbol or library
2941 // dynamically imported by the object files outObj.
2942 func (b *Builder) dynimport(a *Action, p *load.Package, objdir, importGo, cgoExe string, cflags, cgoLDFLAGS, outObj []string) error {
2943         cfile := objdir + "_cgo_main.c"
2944         ofile := objdir + "_cgo_main.o"
2945         if err := b.gcc(a, p, objdir, ofile, cflags, cfile); err != nil {
2946                 return err
2947         }
2948
2949         linkobj := str.StringList(ofile, outObj, mkAbsFiles(p.Dir, p.SysoFiles))
2950         dynobj := objdir + "_cgo_.o"
2951
2952         // we need to use -pie for Linux/ARM to get accurate imported sym
2953         ldflags := cgoLDFLAGS
2954         if (cfg.Goarch == "arm" && cfg.Goos == "linux") || cfg.Goos == "android" {
2955                 // -static -pie doesn't make sense, and causes link errors.
2956                 // Issue 26197.
2957                 n := make([]string, 0, len(ldflags))
2958                 for _, flag := range ldflags {
2959                         if flag != "-static" {
2960                                 n = append(n, flag)
2961                         }
2962                 }
2963                 ldflags = append(n, "-pie")
2964         }
2965         if err := b.gccld(a, p, objdir, dynobj, ldflags, linkobj); err != nil {
2966                 return err
2967         }
2968
2969         // cgo -dynimport
2970         var cgoflags []string
2971         if p.Standard && p.ImportPath == "runtime/cgo" {
2972                 cgoflags = []string{"-dynlinker"} // record path to dynamic linker
2973         }
2974         return b.run(a, base.Cwd, p.ImportPath, b.cCompilerEnv(), cfg.BuildToolexec, cgoExe, "-dynpackage", p.Name, "-dynimport", dynobj, "-dynout", importGo, cgoflags)
2975 }
2976
2977 // Run SWIG on all SWIG input files.
2978 // TODO: Don't build a shared library, once SWIG emits the necessary
2979 // pragmas for external linking.
2980 func (b *Builder) swig(a *Action, p *load.Package, objdir string, pcCFLAGS []string) (outGo, outC, outCXX []string, err error) {
2981         if err := b.swigVersionCheck(); err != nil {
2982                 return nil, nil, nil, err
2983         }
2984
2985         intgosize, err := b.swigIntSize(objdir)
2986         if err != nil {
2987                 return nil, nil, nil, err
2988         }
2989
2990         for _, f := range p.SwigFiles {
2991                 goFile, cFile, err := b.swigOne(a, p, f, objdir, pcCFLAGS, false, intgosize)
2992                 if err != nil {
2993                         return nil, nil, nil, err
2994                 }
2995                 if goFile != "" {
2996                         outGo = append(outGo, goFile)
2997                 }
2998                 if cFile != "" {
2999                         outC = append(outC, cFile)
3000                 }
3001         }
3002         for _, f := range p.SwigCXXFiles {
3003                 goFile, cxxFile, err := b.swigOne(a, p, f, objdir, pcCFLAGS, true, intgosize)
3004                 if err != nil {
3005                         return nil, nil, nil, err
3006                 }
3007                 if goFile != "" {
3008                         outGo = append(outGo, goFile)
3009                 }
3010                 if cxxFile != "" {
3011                         outCXX = append(outCXX, cxxFile)
3012                 }
3013         }
3014         return outGo, outC, outCXX, nil
3015 }
3016
3017 // Make sure SWIG is new enough.
3018 var (
3019         swigCheckOnce sync.Once
3020         swigCheck     error
3021 )
3022
3023 func (b *Builder) swigDoVersionCheck() error {
3024         out, err := b.runOut(nil, "", nil, "swig", "-version")
3025         if err != nil {
3026                 return err
3027         }
3028         re := regexp.MustCompile(`[vV]ersion +([\d]+)([.][\d]+)?([.][\d]+)?`)
3029         matches := re.FindSubmatch(out)
3030         if matches == nil {
3031                 // Can't find version number; hope for the best.
3032                 return nil
3033         }
3034
3035         major, err := strconv.Atoi(string(matches[1]))
3036         if err != nil {
3037                 // Can't find version number; hope for the best.
3038                 return nil
3039         }
3040         const errmsg = "must have SWIG version >= 3.0.6"
3041         if major < 3 {
3042                 return errors.New(errmsg)
3043         }
3044         if major > 3 {
3045                 // 4.0 or later
3046                 return nil
3047         }
3048
3049         // We have SWIG version 3.x.
3050         if len(matches[2]) > 0 {
3051                 minor, err := strconv.Atoi(string(matches[2][1:]))
3052                 if err != nil {
3053                         return nil
3054                 }
3055                 if minor > 0 {
3056                         // 3.1 or later
3057                         return nil
3058                 }
3059         }
3060
3061         // We have SWIG version 3.0.x.
3062         if len(matches[3]) > 0 {
3063                 patch, err := strconv.Atoi(string(matches[3][1:]))
3064                 if err != nil {
3065                         return nil
3066                 }
3067                 if patch < 6 {
3068                         // Before 3.0.6.
3069                         return errors.New(errmsg)
3070                 }
3071         }
3072
3073         return nil
3074 }
3075
3076 func (b *Builder) swigVersionCheck() error {
3077         swigCheckOnce.Do(func() {
3078                 swigCheck = b.swigDoVersionCheck()
3079         })
3080         return swigCheck
3081 }
3082
3083 // Find the value to pass for the -intgosize option to swig.
3084 var (
3085         swigIntSizeOnce  sync.Once
3086         swigIntSize      string
3087         swigIntSizeError error
3088 )
3089
3090 // This code fails to build if sizeof(int) <= 32
3091 const swigIntSizeCode = `
3092 package main
3093 const i int = 1 << 32
3094 `
3095
3096 // Determine the size of int on the target system for the -intgosize option
3097 // of swig >= 2.0.9. Run only once.
3098 func (b *Builder) swigDoIntSize(objdir string) (intsize string, err error) {
3099         if cfg.BuildN {
3100                 return "$INTBITS", nil
3101         }
3102         src := filepath.Join(b.WorkDir, "swig_intsize.go")
3103         if err = os.WriteFile(src, []byte(swigIntSizeCode), 0666); err != nil {
3104                 return
3105         }
3106         srcs := []string{src}
3107
3108         p := load.GoFilesPackage(context.TODO(), load.PackageOpts{}, srcs)
3109
3110         if _, _, e := BuildToolchain.gc(b, &Action{Mode: "swigDoIntSize", Package: p, Objdir: objdir}, "", nil, nil, "", false, srcs); e != nil {
3111                 return "32", nil
3112         }
3113         return "64", nil
3114 }
3115
3116 // Determine the size of int on the target system for the -intgosize option
3117 // of swig >= 2.0.9.
3118 func (b *Builder) swigIntSize(objdir string) (intsize string, err error) {
3119         swigIntSizeOnce.Do(func() {
3120                 swigIntSize, swigIntSizeError = b.swigDoIntSize(objdir)
3121         })
3122         return swigIntSize, swigIntSizeError
3123 }
3124
3125 // Run SWIG on one SWIG input file.
3126 func (b *Builder) swigOne(a *Action, p *load.Package, file, objdir string, pcCFLAGS []string, cxx bool, intgosize string) (outGo, outC string, err error) {
3127         cgoCPPFLAGS, cgoCFLAGS, cgoCXXFLAGS, _, _, err := b.CFlags(p)
3128         if err != nil {
3129                 return "", "", err
3130         }
3131
3132         var cflags []string
3133         if cxx {
3134                 cflags = str.StringList(cgoCPPFLAGS, pcCFLAGS, cgoCXXFLAGS)
3135         } else {
3136                 cflags = str.StringList(cgoCPPFLAGS, pcCFLAGS, cgoCFLAGS)
3137         }
3138
3139         n := 5 // length of ".swig"
3140         if cxx {
3141                 n = 8 // length of ".swigcxx"
3142         }
3143         base := file[:len(file)-n]
3144         goFile := base + ".go"
3145         gccBase := base + "_wrap."
3146         gccExt := "c"
3147         if cxx {
3148                 gccExt = "cxx"
3149         }
3150
3151         gccgo := cfg.BuildToolchainName == "gccgo"
3152
3153         // swig
3154         args := []string{
3155                 "-go",
3156                 "-cgo",
3157                 "-intgosize", intgosize,
3158                 "-module", base,
3159                 "-o", objdir + gccBase + gccExt,
3160                 "-outdir", objdir,
3161         }
3162
3163         for _, f := range cflags {
3164                 if len(f) > 3 && f[:2] == "-I" {
3165                         args = append(args, f)
3166                 }
3167         }
3168
3169         if gccgo {
3170                 args = append(args, "-gccgo")
3171                 if pkgpath := gccgoPkgpath(p); pkgpath != "" {
3172                         args = append(args, "-go-pkgpath", pkgpath)
3173                 }
3174         }
3175         if cxx {
3176                 args = append(args, "-c++")
3177         }
3178
3179         out, err := b.runOut(a, p.Dir, nil, "swig", args, file)
3180         if err != nil {
3181                 if len(out) > 0 {
3182                         if bytes.Contains(out, []byte("-intgosize")) || bytes.Contains(out, []byte("-cgo")) {
3183                                 return "", "", errors.New("must have SWIG version >= 3.0.6")
3184                         }
3185                         b.showOutput(a, p.Dir, p.Desc(), b.processOutput(out)) // swig error
3186                         return "", "", errPrintedOutput
3187                 }
3188                 return "", "", err
3189         }
3190         if len(out) > 0 {
3191                 b.showOutput(a, p.Dir, p.Desc(), b.processOutput(out)) // swig warning
3192         }
3193
3194         // If the input was x.swig, the output is x.go in the objdir.
3195         // But there might be an x.go in the original dir too, and if it
3196         // uses cgo as well, cgo will be processing both and will
3197         // translate both into x.cgo1.go in the objdir, overwriting one.
3198         // Rename x.go to _x_swig.go to avoid this problem.
3199         // We ignore files in the original dir that begin with underscore
3200         // so _x_swig.go cannot conflict with an original file we were
3201         // going to compile.
3202         goFile = objdir + goFile
3203         newGoFile := objdir + "_" + base + "_swig.go"
3204         if err := os.Rename(goFile, newGoFile); err != nil {
3205                 return "", "", err
3206         }
3207         return newGoFile, objdir + gccBase + gccExt, nil
3208 }
3209
3210 // disableBuildID adjusts a linker command line to avoid creating a
3211 // build ID when creating an object file rather than an executable or
3212 // shared library. Some systems, such as Ubuntu, always add
3213 // --build-id to every link, but we don't want a build ID when we are
3214 // producing an object file. On some of those system a plain -r (not
3215 // -Wl,-r) will turn off --build-id, but clang 3.0 doesn't support a
3216 // plain -r. I don't know how to turn off --build-id when using clang
3217 // other than passing a trailing --build-id=none. So that is what we
3218 // do, but only on systems likely to support it, which is to say,
3219 // systems that normally use gold or the GNU linker.
3220 func (b *Builder) disableBuildID(ldflags []string) []string {
3221         switch cfg.Goos {
3222         case "android", "dragonfly", "linux", "netbsd":
3223                 ldflags = append(ldflags, "-Wl,--build-id=none")
3224         }
3225         return ldflags
3226 }
3227
3228 // mkAbsFiles converts files into a list of absolute files,
3229 // assuming they were originally relative to dir,
3230 // and returns that new list.
3231 func mkAbsFiles(dir string, files []string) []string {
3232         abs := make([]string, len(files))
3233         for i, f := range files {
3234                 if !filepath.IsAbs(f) {
3235                         f = filepath.Join(dir, f)
3236                 }
3237                 abs[i] = f
3238         }
3239         return abs
3240 }
3241
3242 // passLongArgsInResponseFiles modifies cmd such that, for
3243 // certain programs, long arguments are passed in "response files", a
3244 // file on disk with the arguments, with one arg per line. An actual
3245 // argument starting with '@' means that the rest of the argument is
3246 // a filename of arguments to expand.
3247 //
3248 // See issues 18468 (Windows) and 37768 (Darwin).
3249 func passLongArgsInResponseFiles(cmd *exec.Cmd) (cleanup func()) {
3250         cleanup = func() {} // no cleanup by default
3251
3252         var argLen int
3253         for _, arg := range cmd.Args {
3254                 argLen += len(arg)
3255         }
3256
3257         // If we're not approaching 32KB of args, just pass args normally.
3258         // (use 30KB instead to be conservative; not sure how accounting is done)
3259         if !useResponseFile(cmd.Path, argLen) {
3260                 return
3261         }
3262
3263         tf, err := os.CreateTemp("", "args")
3264         if err != nil {
3265                 log.Fatalf("error writing long arguments to response file: %v", err)
3266         }
3267         cleanup = func() { os.Remove(tf.Name()) }
3268         var buf bytes.Buffer
3269         for _, arg := range cmd.Args[1:] {
3270                 fmt.Fprintf(&buf, "%s\n", encodeArg(arg))
3271         }
3272         if _, err := tf.Write(buf.Bytes()); err != nil {
3273                 tf.Close()
3274                 cleanup()
3275                 log.Fatalf("error writing long arguments to response file: %v", err)
3276         }
3277         if err := tf.Close(); err != nil {
3278                 cleanup()
3279                 log.Fatalf("error writing long arguments to response file: %v", err)
3280         }
3281         cmd.Args = []string{cmd.Args[0], "@" + tf.Name()}
3282         return cleanup
3283 }
3284
3285 // Windows has a limit of 32 KB arguments. To be conservative and not worry
3286 // about whether that includes spaces or not, just use 30 KB. Darwin's limit is
3287 // less clear. The OS claims 256KB, but we've seen failures with arglen as
3288 // small as 50KB.
3289 const ArgLengthForResponseFile = (30 << 10)
3290
3291 func useResponseFile(path string, argLen int) bool {
3292         // Unless the program uses objabi.Flagparse, which understands
3293         // response files, don't use response files.
3294         // TODO: do we need more commands? asm? cgo? For now, no.
3295         prog := strings.TrimSuffix(filepath.Base(path), ".exe")
3296         switch prog {
3297         case "compile", "link":
3298         default:
3299                 return false
3300         }
3301
3302         if argLen > ArgLengthForResponseFile {
3303                 return true
3304         }
3305
3306         // On the Go build system, use response files about 10% of the
3307         // time, just to exercise this codepath.
3308         isBuilder := os.Getenv("GO_BUILDER_NAME") != ""
3309         if isBuilder && rand.Intn(10) == 0 {
3310                 return true
3311         }
3312
3313         return false
3314 }
3315
3316 // encodeArg encodes an argument for response file writing.
3317 func encodeArg(arg string) string {
3318         // If there aren't any characters we need to reencode, fastpath out.
3319         if !strings.ContainsAny(arg, "\\\n") {
3320                 return arg
3321         }
3322         var b strings.Builder
3323         for _, r := range arg {
3324                 switch r {
3325                 case '\\':
3326                         b.WriteByte('\\')
3327                         b.WriteByte('\\')
3328                 case '\n':
3329                         b.WriteByte('\\')
3330                         b.WriteByte('n')
3331                 default:
3332                         b.WriteRune(r)
3333                 }
3334         }
3335         return b.String()
3336 }