1
2
3
4
5
6
7 package work
8
9 import (
10 "bytes"
11 "cmd/internal/cov/covcmd"
12 "cmd/internal/pathcache"
13 "context"
14 "crypto/sha256"
15 "encoding/json"
16 "errors"
17 "fmt"
18 "go/token"
19 "internal/lazyregexp"
20 "io"
21 "io/fs"
22 "log"
23 "math/rand"
24 "os"
25 "os/exec"
26 "path/filepath"
27 "regexp"
28 "runtime"
29 "slices"
30 "sort"
31 "strconv"
32 "strings"
33 "sync"
34 "time"
35
36 "cmd/go/internal/base"
37 "cmd/go/internal/cache"
38 "cmd/go/internal/cfg"
39 "cmd/go/internal/fsys"
40 "cmd/go/internal/gover"
41 "cmd/go/internal/load"
42 "cmd/go/internal/modinfo"
43 "cmd/go/internal/modload"
44 "cmd/go/internal/str"
45 "cmd/go/internal/trace"
46 "cmd/internal/buildid"
47 "cmd/internal/quoted"
48 "cmd/internal/sys"
49
50 "golang.org/x/tools/go/analysis"
51 )
52
53 const DefaultCFlags = "-O2 -g"
54
55
56
57 func actionList(root *Action) []*Action {
58 seen := map[*Action]bool{}
59 all := []*Action{}
60 var walk func(*Action)
61 walk = func(a *Action) {
62 if seen[a] {
63 return
64 }
65 seen[a] = true
66 for _, a1 := range a.Deps {
67 walk(a1)
68 }
69 all = append(all, a)
70 }
71 walk(root)
72 return all
73 }
74
75
76 func (b *Builder) Do(ctx context.Context, root *Action) {
77 ctx, span := trace.StartSpan(ctx, "exec.Builder.Do ("+root.Mode+" "+root.Target+")")
78 defer span.Done()
79
80 if !b.IsCmdList {
81
82 c := cache.Default()
83 defer func() {
84 if err := c.Close(); err != nil {
85 base.Fatalf("go: failed to trim cache: %v", err)
86 }
87 }()
88 }
89
90
91
92
93
94
95
96
97
98
99
100
101 all := actionList(root)
102 for i, a := range all {
103 a.priority = i
104 }
105
106
107 writeActionGraph := func() {
108 if file := cfg.DebugActiongraph; file != "" {
109 if strings.HasSuffix(file, ".go") {
110
111
112 base.Fatalf("go: refusing to write action graph to %v\n", file)
113 }
114 js := actionGraphJSON(root)
115 if err := os.WriteFile(file, []byte(js), 0666); err != nil {
116 fmt.Fprintf(os.Stderr, "go: writing action graph: %v\n", err)
117 base.SetExitStatus(1)
118 }
119 }
120 }
121 writeActionGraph()
122
123 b.readySema = make(chan bool, len(all))
124
125
126 for _, a := range all {
127 for _, a1 := range a.Deps {
128 a1.triggers = append(a1.triggers, a)
129 }
130 a.pending = len(a.Deps)
131 if a.pending == 0 {
132 b.ready.push(a)
133 b.readySema <- true
134 }
135 }
136
137
138
139 handle := func(ctx context.Context, a *Action) {
140 if a.json != nil {
141 a.json.TimeStart = time.Now()
142 }
143 var err error
144 if a.Actor != nil && (a.Failed == nil || a.IgnoreFail) {
145
146 desc := "Executing action (" + a.Mode
147 if a.Package != nil {
148 desc += " " + a.Package.Desc()
149 }
150 desc += ")"
151 ctx, span := trace.StartSpan(ctx, desc)
152 a.traceSpan = span
153 for _, d := range a.Deps {
154 trace.Flow(ctx, d.traceSpan, a.traceSpan)
155 }
156 err = a.Actor.Act(b, ctx, a)
157 span.Done()
158 }
159 if a.json != nil {
160 a.json.TimeDone = time.Now()
161 }
162
163
164
165 b.exec.Lock()
166 defer b.exec.Unlock()
167
168 if err != nil {
169 if b.AllowErrors && a.Package != nil {
170 if a.Package.Error == nil {
171 a.Package.Error = &load.PackageError{Err: err}
172 a.Package.Incomplete = true
173 }
174 } else {
175 if a.Package != nil {
176 if ipe, ok := errors.AsType[load.ImportPathError](err); !ok || ipe.ImportPath() != a.Package.ImportPath {
177 err = fmt.Errorf("%s: %v", a.Package.ImportPath, err)
178 }
179 }
180 sh := b.Shell(a)
181 sh.Errorf("%s", err)
182 }
183 if a.Failed == nil {
184 a.Failed = a
185 }
186 }
187
188 for _, a0 := range a.triggers {
189 if a.Failed != nil {
190 if a0.Mode == "test barrier" {
191
192
193
194
195
196
197 for _, bt := range a0.triggers {
198 if bt.Mode != "test barrier" {
199 bt.Failed = a.Failed
200 }
201 }
202 } else {
203 a0.Failed = a.Failed
204 }
205 }
206 if a0.pending--; a0.pending == 0 {
207 b.ready.push(a0)
208 b.readySema <- true
209 }
210 }
211
212 if a == root {
213 close(b.readySema)
214 }
215 }
216
217 var wg sync.WaitGroup
218
219
220
221
222
223 par := cfg.BuildP
224 if cfg.BuildN {
225 par = 1
226 }
227 for i := 0; i < par; i++ {
228 wg.Add(1)
229 go func() {
230 ctx := trace.StartGoroutine(ctx)
231 defer wg.Done()
232 for {
233 select {
234 case _, ok := <-b.readySema:
235 if !ok {
236 return
237 }
238
239
240 b.exec.Lock()
241 a := b.ready.pop()
242 b.exec.Unlock()
243 handle(ctx, a)
244 case <-base.Interrupted:
245 base.SetExitStatus(1)
246 return
247 }
248 }
249 }()
250 }
251
252 wg.Wait()
253
254 if tokens != totalTokens || concurrentProcesses != 0 {
255 base.Fatalf("internal error: tokens not restored at end of build: tokens: %d, totalTokens: %d, concurrentProcesses: %d",
256 tokens, totalTokens, concurrentProcesses)
257 }
258
259
260 writeActionGraph()
261 }
262
263
264 func (b *Builder) buildActionID(a *Action) cache.ActionID {
265 p := a.Package
266 h := cache.NewHash("build " + p.ImportPath)
267
268
269
270
271
272
273 fmt.Fprintf(h, "compile\n")
274
275 b.addPackageOrigin(h, p)
276
277 if p.Module != nil {
278 fmt.Fprintf(h, "go %s\n", p.Module.GoVersion)
279 }
280 fmt.Fprintf(h, "goos %s goarch %s\n", cfg.Goos, cfg.Goarch)
281 fmt.Fprintf(h, "import %q\n", p.ImportPath)
282 fmt.Fprintf(h, "omitdebug %v standard %v local %v prefix %q\n", p.Internal.OmitDebug, p.Standard, p.Internal.Local, p.Internal.LocalPrefix)
283 if cfg.BuildTrimpath {
284 fmt.Fprintln(h, "trimpath")
285 }
286 if p.Internal.ForceLibrary {
287 fmt.Fprintf(h, "forcelibrary\n")
288 }
289 b.addCToolchainIDs(h, p)
290 if p.Internal.Cover.Mode != "" {
291 fmt.Fprintf(h, "cover %q %q\n", p.Internal.Cover.Mode, b.toolID("cover"))
292 }
293 if p.Internal.FuzzInstrument {
294 if fuzzFlags := fuzzInstrumentFlags(); fuzzFlags != nil {
295 fmt.Fprintf(h, "fuzz %q\n", fuzzFlags)
296 }
297 }
298 if p.Internal.BuildInfo != nil {
299 fmt.Fprintf(h, "modinfo %q\n", p.Internal.BuildInfo.String())
300 }
301
302
303 switch cfg.BuildToolchainName {
304 default:
305 base.Fatalf("buildActionID: unknown build toolchain %q", cfg.BuildToolchainName)
306 case "gc":
307 fmt.Fprintf(h, "compile %s %q %q\n", b.toolID("compile"), forcedGcflags, p.Internal.Gcflags)
308 if len(p.SFiles) > 0 {
309 fmt.Fprintf(h, "asm %q %q %q\n", b.toolID("asm"), forcedAsmflags, p.Internal.Asmflags)
310 }
311
312
313 key, val, _ := cfg.GetArchEnv()
314 fmt.Fprintf(h, "%s=%s\n", key, val)
315
316 if cfg.CleanGOEXPERIMENT != "" {
317 fmt.Fprintf(h, "GOEXPERIMENT=%q\n", cfg.CleanGOEXPERIMENT)
318 }
319
320
321
322
323
324
325 magic := []string{
326 "GOCLOBBERDEADHASH",
327 "GOSSAFUNC",
328 "GOSSADIR",
329 "GOCOMPILEDEBUG",
330 }
331 for _, env := range magic {
332 if x := os.Getenv(env); x != "" {
333 fmt.Fprintf(h, "magic %s=%s\n", env, x)
334 }
335 }
336
337 case "gccgo":
338 id, _, err := b.gccgoToolID(BuildToolchain.compiler(), "go")
339 if err != nil {
340 base.Fatalf("%v", err)
341 }
342 fmt.Fprintf(h, "compile %s %q %q\n", id, forcedGccgoflags, p.Internal.Gccgoflags)
343 fmt.Fprintf(h, "pkgpath %s\n", gccgoPkgpath(p))
344 fmt.Fprintf(h, "ar %q\n", BuildToolchain.(gccgoToolchain).ar())
345 if len(p.SFiles) > 0 {
346 id, _, _ = b.gccgoToolID(BuildToolchain.compiler(), "assembler-with-cpp")
347
348
349 fmt.Fprintf(h, "asm %q\n", id)
350 }
351 }
352
353
354
355
356 inputFiles := str.StringList(
357 p.GoFiles,
358 p.CgoFiles,
359 p.CFiles,
360 p.CXXFiles,
361 p.FFiles,
362 p.MFiles,
363 p.HFiles,
364 p.SFiles,
365 p.SysoFiles,
366 p.SwigFiles,
367 p.SwigCXXFiles,
368 p.EmbedFiles,
369 )
370 for _, file := range inputFiles {
371 fmt.Fprintf(h, "file %s %s\n", file, b.fileHash(filepath.Join(p.Dir, file)))
372 }
373 for _, a1 := range a.Deps {
374 p1 := a1.Package
375 if p1 != nil && p1 != p {
376 fmt.Fprintf(h, "import %s %s\n", p1.ImportPath, contentID(a1.buildID))
377 }
378 if a1.Mode == "preprocess PGO profile" {
379 fmt.Fprintf(h, "pgofile %s\n", b.fileHash(a1.built))
380 }
381 }
382
383 return h.Sum()
384 }
385
386
387
388
389 func (b *Builder) addPackageOrigin(h io.Writer, p *load.Package) {
390 if cfg.BuildTrimpath {
391
392
393
394 if p.Module != nil {
395 fmt.Fprintf(h, "module %s@%s\n", p.Module.Path, p.Module.Version)
396 }
397 } else if p.Goroot {
398
399
400
401
402
403
404
405
406
407
408
409
410
411 } else if !strings.HasPrefix(p.Dir, b.WorkDir) {
412
413
414
415 fmt.Fprintf(h, "dir %s\n", p.Dir)
416 }
417 }
418
419
420
421 func (b *Builder) addCToolchainIDs(h io.Writer, p *load.Package) {
422 if len(p.CgoFiles)+len(p.SwigFiles)+len(p.SwigCXXFiles) > 0 {
423 fmt.Fprintf(h, "cgo %q\n", b.toolID("cgo"))
424 cppflags, cflags, cxxflags, fflags, ldflags, _ := b.CFlags(p)
425
426 ccExe := b.ccExe()
427 fmt.Fprintf(h, "CC=%q %q %q %q\n", ccExe, cppflags, cflags, ldflags)
428
429
430 if ccID, _, err := b.gccToolID(ccExe[0], "c"); err == nil {
431 fmt.Fprintf(h, "CC ID=%q\n", ccID)
432 } else {
433 fmt.Fprintf(h, "CC ID ERROR=%q\n", err)
434 }
435 if len(p.CXXFiles)+len(p.SwigCXXFiles) > 0 {
436 cxxExe := b.cxxExe()
437 fmt.Fprintf(h, "CXX=%q %q\n", cxxExe, cxxflags)
438 if cxxID, _, err := b.gccToolID(cxxExe[0], "c++"); err == nil {
439 fmt.Fprintf(h, "CXX ID=%q\n", cxxID)
440 } else {
441 fmt.Fprintf(h, "CXX ID ERROR=%q\n", err)
442 }
443 }
444 if len(p.FFiles) > 0 {
445 fcExe := b.fcExe()
446 fmt.Fprintf(h, "FC=%q %q\n", fcExe, fflags)
447 if fcID, _, err := b.gccToolID(fcExe[0], "f95"); err == nil {
448 fmt.Fprintf(h, "FC ID=%q\n", fcID)
449 } else {
450 fmt.Fprintf(h, "FC ID ERROR=%q\n", err)
451 }
452 }
453
454 }
455 }
456
457
458
459
460 func allowedVersion(v string) bool {
461
462 if v == "" {
463 return true
464 }
465 return gover.Compare(gover.Local(), v) >= 0
466 }
467
468 func (b *Builder) computeNonGoOverlay(a *Action, p *load.Package, sh *Shell, objdir string, nonGoFileLists [][]string) error {
469 OverlayLoop:
470 for _, fs := range nonGoFileLists {
471 for _, f := range fs {
472 if fsys.Replaced(mkAbs(p.Dir, f)) {
473 a.nonGoOverlay = make(map[string]string)
474 break OverlayLoop
475 }
476 }
477 }
478 if a.nonGoOverlay != nil {
479 for _, fs := range nonGoFileLists {
480 for i := range fs {
481 from := mkAbs(p.Dir, fs[i])
482 dst := objdir + filepath.Base(fs[i])
483 if err := sh.CopyFile(dst, fsys.Actual(from), 0666, false); err != nil {
484 return err
485 }
486 a.nonGoOverlay[from] = dst
487 }
488 }
489 }
490
491 return nil
492 }
493
494 func (b *Builder) runCover(ctx context.Context, a *Action) error {
495 p := a.Package
496 sh := b.Shell(a)
497
498
499 var covMetaFileName string
500 if a.Package.Internal.Cover.GenMeta {
501 covMetaFileName = a.Objdir + covcmd.MetaFileForPackage(a.Package.ImportPath)
502 }
503
504 if err := sh.Mkdir(a.Objdir); err != nil {
505 return err
506 }
507
508 a.actionID = b.coverActionID(a, covMetaFileName)
509 if pr, err := b.loadCachedCoverOutputs(a); err == nil {
510 a.Provider = pr
511 return nil
512 }
513
514 gofiles := slices.Clone(a.Package.GoFiles)
515 cgofiles := slices.Clone(a.Package.CgoFiles)
516
517 outfiles := []string{}
518 infiles := []string{}
519 for i, file := range str.StringList(gofiles, cgofiles) {
520 if base.IsTestFile(file) {
521 continue
522 }
523
524 var sourceFile string
525 var coverFile string
526 if base, found := strings.CutSuffix(file, ".cgo1.go"); found {
527
528 base = filepath.Base(base)
529 sourceFile = file
530 coverFile = a.Objdir + base + ".cgo1.go"
531 } else {
532 sourceFile = filepath.Join(p.Dir, file)
533 coverFile = a.Objdir + file
534 }
535 coverFile = strings.TrimSuffix(coverFile, ".go") + ".cover.go"
536 infiles = append(infiles, sourceFile)
537 outfiles = append(outfiles, coverFile)
538 if i < len(gofiles) {
539 gofiles[i] = coverFile
540 } else {
541 cgofiles[i-len(gofiles)] = coverFile
542 }
543 }
544
545 var coverCfg string
546 if len(infiles) != 0 {
547
548
549
550
551
552
553
554
555
556 sum := sha256.Sum256([]byte(a.Package.ImportPath))
557 coverVar := fmt.Sprintf("goCover_%x_", sum[:6])
558 mode := a.Package.Internal.Cover.Mode
559 if mode == "" {
560 panic("covermode should be set at this point")
561 }
562 coverCfg = a.Objdir + "coveragecfg"
563 if newoutfiles, err := b.cover(a, infiles, outfiles, coverVar, mode, covMetaFileName, coverCfg); err != nil {
564 return err
565 } else {
566 outfiles = newoutfiles
567 gofiles = append([]string{newoutfiles[0]}, gofiles...)
568 }
569 }
570
571 pr := &coverProvider{covMetaFileName, coverCfg, gofiles, cgofiles}
572 a.Provider = pr
573
574 if !cfg.BuildN {
575 if err := b.cacheCoverOutputs(a, pr); err != nil {
576 return err
577 }
578 }
579
580 return nil
581 }
582
583
584
585 func (b *Builder) build(ctx context.Context, a *Action) (err error) {
586 p := a.Package
587 sh := b.Shell(a)
588
589 bit := func(x uint32, b bool) uint32 {
590 if b {
591 return x
592 }
593 return 0
594 }
595
596 const (
597 needBuild uint32 = 1 << iota
598 needVet
599 needCompiledGoFiles
600 )
601
602 cachedBuild := false
603 need := bit(needBuild, !b.IsCmdList && a.needBuild || b.NeedExport) |
604 bit(needVet, a.needVet) |
605 bit(needCompiledGoFiles, b.NeedCompiledGoFiles)
606
607 if b.useCache(a, b.buildActionID(a), p.Target, need&needBuild != 0) {
608
609
610
611
612
613 cachedBuild = true
614 a.output = []byte{}
615 need &^= needBuild
616 if b.NeedExport {
617 p.Export = a.built
618 p.BuildID = a.buildID
619 }
620 if need&needCompiledGoFiles != 0 {
621 if err := b.loadCachedCompiledGoFiles(a); err == nil {
622 need &^= needCompiledGoFiles
623 }
624 }
625 }
626
627
628
629 if !cachedBuild && need&needCompiledGoFiles != 0 {
630 if err := b.loadCachedCompiledGoFiles(a); err == nil {
631 need &^= needCompiledGoFiles
632 }
633 }
634
635 if need == 0 {
636 return nil
637 }
638 defer b.flushOutput(a)
639
640 defer func() {
641 if err != nil && b.IsCmdList && b.NeedError && p.Error == nil {
642 p.Error = &load.PackageError{Err: err}
643 }
644 }()
645
646 if p.Error != nil {
647
648
649 return p.Error
650 }
651
652 if p.Module != nil && !allowedVersion(p.Module.GoVersion) {
653 return errors.New("module requires Go " + p.Module.GoVersion + " or later")
654 }
655
656 if err := b.checkDirectives(a); err != nil {
657 return err
658 }
659
660 if err := sh.Mkdir(a.Objdir); err != nil {
661 return err
662 }
663
664
665
666
667
668 if need == needVet {
669 if err := b.loadCachedVet(a, a.Deps); err == nil {
670 need &^= needVet
671 }
672 }
673
674 var coverPr *coverProvider
675 var runCgoPr *runCgoProvider
676 for _, dep := range a.Deps {
677 switch pr := dep.Provider.(type) {
678 case *coverProvider:
679 coverPr = pr
680 case *runCgoProvider:
681 runCgoPr = pr
682 }
683 }
684
685 if need == 0 {
686 return
687 }
688 defer b.flushOutput(a)
689
690 if cfg.BuildN {
691
692
693
694
695
696 sh.Printf("\n#\n# %s\n#\n\n", p.ImportPath)
697 }
698
699 if cfg.BuildV {
700 sh.Printf("%s\n", p.ImportPath)
701 }
702
703 objdir := a.Objdir
704
705 if err := AllowInstall(a); err != nil {
706 return err
707 }
708
709
710 dir, _ := filepath.Split(a.Target)
711 if dir != "" {
712 if err := sh.Mkdir(dir); err != nil {
713 return err
714 }
715 }
716
717 gofiles := str.StringList(p.GoFiles)
718 cfiles := str.StringList(p.CFiles)
719 sfiles := str.StringList(p.SFiles)
720 var objects, cgoObjects []string
721
722
723 if p.Internal.Cover.Mode != "" {
724 gofiles = coverPr.goSources
725 }
726
727 if p.UsesCgo() || p.UsesSwig() {
728 if runCgoPr == nil {
729 base.Fatalf("internal error: could not find runCgoProvider")
730 }
731
732
733
734
735
736 cfiles = nil
737 if p.Standard && p.ImportPath == "runtime/cgo" {
738
739 i := 0
740 for _, f := range sfiles {
741 if !strings.HasPrefix(f, "gcc_") {
742 sfiles[i] = f
743 i++
744 }
745 }
746 sfiles = sfiles[:i]
747 } else {
748 sfiles = nil
749 }
750 outGo, outObj, err := b.processCgoOutputs(a, runCgoPr, base.Tool("cgo"), objdir)
751
752 if err != nil {
753 return err
754 }
755 if cfg.BuildToolchainName == "gccgo" {
756 cgoObjects = append(cgoObjects, a.Objdir+"_cgo_flags")
757 }
758 cgoObjects = append(cgoObjects, outObj...)
759 gofiles = append(gofiles, outGo...)
760 }
761
762 var srcfiles []string
763 srcfiles = append(srcfiles, gofiles...)
764 srcfiles = append(srcfiles, sfiles...)
765 srcfiles = append(srcfiles, cfiles...)
766 b.cacheSrcFiles(a, srcfiles)
767
768
769 if len(gofiles) == 0 {
770 return &load.NoGoError{Package: p}
771 }
772
773
774 if need&needVet != 0 {
775 buildVetConfig(a, srcfiles, a.Deps)
776 need &^= needVet
777 }
778 if need&needCompiledGoFiles != 0 {
779 if err := b.loadCachedCompiledGoFiles(a); err != nil {
780 return fmt.Errorf("loading compiled Go files from cache: %w", err)
781 }
782 need &^= needCompiledGoFiles
783 }
784 if need == 0 {
785
786 return nil
787 }
788
789
790 symabis, err := BuildToolchain.symabis(b, a, sfiles)
791 if err != nil {
792 return err
793 }
794
795
796
797
798
799
800
801 var icfg bytes.Buffer
802 fmt.Fprintf(&icfg, "# import config\n")
803 for i, raw := range p.Internal.RawImports {
804 final := p.Imports[i]
805 if final != raw {
806 fmt.Fprintf(&icfg, "importmap %s=%s\n", raw, final)
807 }
808 }
809 for _, a1 := range a.Deps {
810 p1 := a1.Package
811 if p1 == nil || p1.ImportPath == "" || a1.built == "" {
812 continue
813 }
814 fmt.Fprintf(&icfg, "packagefile %s=%s\n", p1.ImportPath, a1.built)
815 }
816
817
818
819 var embedcfg []byte
820 if len(p.Internal.Embed) > 0 {
821 var embed struct {
822 Patterns map[string][]string
823 Files map[string]string
824 }
825 embed.Patterns = p.Internal.Embed
826 embed.Files = make(map[string]string)
827 for _, file := range p.EmbedFiles {
828 embed.Files[file] = fsys.Actual(filepath.Join(p.Dir, file))
829 }
830 js, err := json.MarshalIndent(&embed, "", "\t")
831 if err != nil {
832 return fmt.Errorf("marshal embedcfg: %v", err)
833 }
834 embedcfg = js
835 }
836
837
838 var pgoProfile string
839 for _, a1 := range a.Deps {
840 if a1.Mode != "preprocess PGO profile" {
841 continue
842 }
843 if pgoProfile != "" {
844 return fmt.Errorf("action contains multiple PGO profile dependencies")
845 }
846 pgoProfile = a1.built
847 }
848
849 var coverageConfig string
850 if coverPr != nil {
851 coverageConfig = coverPr.coverageConfig
852 }
853
854 if p.Internal.BuildInfo != nil && cfg.ModulesEnabled {
855 prog := modload.ModInfoProg(p.Internal.BuildInfo.String(), cfg.BuildToolchainName == "gccgo")
856 if len(prog) > 0 {
857 if err := sh.writeFile(objdir+"_gomod_.go", prog); err != nil {
858 return err
859 }
860 gofiles = append(gofiles, objdir+"_gomod_.go")
861 }
862 }
863
864
865 objpkg := objdir + "_pkg_.a"
866 ofile, out, err := BuildToolchain.gc(b, a, objpkg, icfg.Bytes(), embedcfg, symabis, len(sfiles) > 0, pgoProfile, coverageConfig, gofiles)
867 if len(out) > 0 && (p.UsesCgo() || p.UsesSwig()) && !cfg.BuildX {
868
869
870
871 out = cgoTypeSigRe.ReplaceAll(out, []byte("C."))
872 }
873 if err := sh.reportCmd("", "", out, err); err != nil {
874 return err
875 }
876 if ofile != objpkg {
877 objects = append(objects, ofile)
878 }
879
880
881
882
883 _goos_goarch := "_" + cfg.Goos + "_" + cfg.Goarch
884 _goos := "_" + cfg.Goos
885 _goarch := "_" + cfg.Goarch
886 for _, file := range p.HFiles {
887 name, ext := fileExtSplit(file)
888 switch {
889 case strings.HasSuffix(name, _goos_goarch):
890 targ := file[:len(name)-len(_goos_goarch)] + "_GOOS_GOARCH." + ext
891 if err := sh.CopyFile(objdir+targ, filepath.Join(p.Dir, file), 0666, true); err != nil {
892 return err
893 }
894 case strings.HasSuffix(name, _goarch):
895 targ := file[:len(name)-len(_goarch)] + "_GOARCH." + ext
896 if err := sh.CopyFile(objdir+targ, filepath.Join(p.Dir, file), 0666, true); err != nil {
897 return err
898 }
899 case strings.HasSuffix(name, _goos):
900 targ := file[:len(name)-len(_goos)] + "_GOOS." + ext
901 if err := sh.CopyFile(objdir+targ, filepath.Join(p.Dir, file), 0666, true); err != nil {
902 return err
903 }
904 }
905 }
906
907 if err := b.computeNonGoOverlay(a, p, sh, objdir, [][]string{cfiles}); err != nil {
908 return err
909 }
910
911
912
913 for _, file := range cfiles {
914 out := file[:len(file)-len(".c")] + ".o"
915 if err := BuildToolchain.cc(b, a, objdir+out, file); err != nil {
916 return err
917 }
918 objects = append(objects, out)
919 }
920
921
922 if len(sfiles) > 0 {
923 ofiles, err := BuildToolchain.asm(b, a, sfiles)
924 if err != nil {
925 return err
926 }
927 objects = append(objects, ofiles...)
928 }
929
930
931
932
933 if a.buildID != "" && cfg.BuildToolchainName == "gccgo" {
934 switch cfg.Goos {
935 case "aix", "android", "dragonfly", "freebsd", "illumos", "linux", "netbsd", "openbsd", "solaris":
936 asmfile, err := b.gccgoBuildIDFile(a)
937 if err != nil {
938 return err
939 }
940 ofiles, err := BuildToolchain.asm(b, a, []string{asmfile})
941 if err != nil {
942 return err
943 }
944 objects = append(objects, ofiles...)
945 }
946 }
947
948
949
950
951
952 objects = append(objects, cgoObjects...)
953
954
955 for _, syso := range p.SysoFiles {
956 objects = append(objects, filepath.Join(p.Dir, syso))
957 }
958
959
960
961
962
963
964 if len(objects) > 0 {
965 if err := BuildToolchain.pack(b, a, objpkg, objects); err != nil {
966 return err
967 }
968 }
969
970 if err := b.updateBuildID(a, objpkg); err != nil {
971 return err
972 }
973
974 a.built = objpkg
975 return nil
976 }
977
978 var cgoTypeSigRe = lazyregexp.New(`\b_C2?(type|func|var|macro)_\B`)
979
980 func (b *Builder) checkDirectives(a *Action) error {
981 var msg []byte
982 p := a.Package
983 var seen map[string]token.Position
984 for _, d := range p.Internal.Build.Directives {
985 if strings.HasPrefix(d.Text, "//go:debug") {
986 key, _, err := load.ParseGoDebug(d.Text)
987 if err != nil && err != load.ErrNotGoDebug {
988 msg = fmt.Appendf(msg, "%s: invalid //go:debug: %v\n", d.Pos, err)
989 continue
990 }
991 if pos, ok := seen[key]; ok {
992 msg = fmt.Appendf(msg, "%s: repeated //go:debug for %v\n\t%s: previous //go:debug\n", d.Pos, key, pos)
993 continue
994 }
995 if seen == nil {
996 seen = make(map[string]token.Position)
997 }
998 seen[key] = d.Pos
999 }
1000 }
1001 if len(msg) > 0 {
1002
1003
1004
1005 err := errors.New("invalid directive")
1006 return b.Shell(a).reportCmd("", "", msg, err)
1007 }
1008 return nil
1009 }
1010
1011 func (b *Builder) cacheObjdirFile(a *Action, c cache.Cache, name string) error {
1012 f, err := os.Open(a.Objdir + name)
1013 if err != nil {
1014 return err
1015 }
1016 defer f.Close()
1017 _, _, err = c.Put(cache.Subkey(a.actionID, name), f)
1018 return err
1019 }
1020
1021 func (b *Builder) findCachedObjdirFile(a *Action, c cache.Cache, name string) (string, error) {
1022 file, _, err := cache.GetFile(c, cache.Subkey(a.actionID, name))
1023 if err != nil {
1024 return "", fmt.Errorf("loading cached file %s: %w", name, err)
1025 }
1026 return file, nil
1027 }
1028
1029 func (b *Builder) loadCachedObjdirFile(a *Action, c cache.Cache, name string) error {
1030 cached, err := b.findCachedObjdirFile(a, c, name)
1031 if err != nil {
1032 return err
1033 }
1034 return b.Shell(a).CopyFile(a.Objdir+name, cached, 0666, true)
1035 }
1036
1037 func (b *Builder) cacheSrcFiles(a *Action, srcfiles []string) {
1038 c := cache.Default()
1039 var buf bytes.Buffer
1040 for _, file := range srcfiles {
1041 if !strings.HasPrefix(file, a.Objdir) {
1042
1043 buf.WriteString("./")
1044 buf.WriteString(file)
1045 buf.WriteString("\n")
1046 continue
1047 }
1048 name := file[len(a.Objdir):]
1049 buf.WriteString(name)
1050 buf.WriteString("\n")
1051 if err := b.cacheObjdirFile(a, c, name); err != nil {
1052 return
1053 }
1054 }
1055 cache.PutBytes(c, cache.Subkey(a.actionID, "srcfiles"), buf.Bytes())
1056 }
1057
1058
1059
1060
1061
1062 type coverProviderCached struct {
1063 CovMetaFile string
1064 CoverageConfig string
1065 GoSources, CgoSources []string
1066 }
1067
1068 func (b *Builder) cacheCoverOutputs(a *Action, pr *coverProvider) error {
1069 c := cache.Default()
1070
1071 cacheSrcFileName := func(a *Action, file string) string {
1072 if name, ok := strings.CutPrefix(file, a.Objdir); ok {
1073 return name
1074 }
1075 return "./" + file
1076 }
1077
1078 b.cacheSrcFiles(a, str.StringList(pr.goSources, pr.cgoSources))
1079 var cached coverProviderCached
1080 if pr.covMetaFileName != "" {
1081 cached.CovMetaFile = strings.TrimPrefix(pr.covMetaFileName, a.Objdir)
1082 if err := b.cacheObjdirFile(a, c, cached.CovMetaFile); err != nil {
1083 return err
1084 }
1085 }
1086 if pr.coverageConfig != "" {
1087 cached.CoverageConfig = strings.TrimPrefix(pr.coverageConfig, a.Objdir)
1088 if err := b.cacheObjdirFile(a, c, cached.CoverageConfig); err != nil {
1089 return err
1090 }
1091 }
1092
1093 for _, fn := range pr.goSources {
1094 cached.GoSources = append(cached.GoSources, cacheSrcFileName(a, fn))
1095 }
1096 for _, fn := range pr.cgoSources {
1097 cached.CgoSources = append(cached.CgoSources, cacheSrcFileName(a, fn))
1098 }
1099 js, err := json.Marshal(cached)
1100 if err != nil {
1101 return err
1102 }
1103 cache.PutBytes(c, cache.Subkey(a.actionID, "coverprovider"), js)
1104
1105 return nil
1106 }
1107
1108 func (b *Builder) loadCachedCoverOutputs(a *Action) (*coverProvider, error) {
1109 c := cache.Default()
1110
1111 if _, err := b.loadCachedSrcFiles(a); err != nil {
1112 return nil, err
1113 }
1114
1115 var cached coverProviderCached
1116 if js, _, err := cache.GetBytes(c, cache.Subkey(a.actionID, "coverprovider")); err != nil {
1117 return nil, err
1118 } else if err := json.Unmarshal(js, &cached); err != nil {
1119 return nil, err
1120 }
1121
1122 covMetaFile := cached.CovMetaFile
1123 if covMetaFile != "" {
1124 if err := b.loadCachedObjdirFile(a, c, covMetaFile); err != nil {
1125 return nil, err
1126 }
1127 covMetaFile = a.Objdir + covMetaFile
1128 }
1129 coverageConfig := cached.CoverageConfig
1130 if coverageConfig != "" {
1131 if err := b.loadCachedObjdirFile(a, c, coverageConfig); err != nil {
1132 return nil, err
1133 }
1134 coverageConfig = a.Objdir + coverageConfig
1135 }
1136
1137 var goSources, cgoSources []string
1138 for _, file := range cached.GoSources {
1139 name, ok := strings.CutPrefix(file, "./")
1140 if !ok {
1141 name = a.Objdir + name
1142 }
1143 goSources = append(goSources, name)
1144 }
1145 for _, file := range cached.CgoSources {
1146 name, ok := strings.CutPrefix(file, "./")
1147 if !ok {
1148 name = a.Objdir + name
1149 }
1150 cgoSources = append(cgoSources, name)
1151 }
1152
1153 pr := &coverProvider{
1154 covMetaFileName: covMetaFile,
1155 coverageConfig: coverageConfig,
1156 goSources: goSources,
1157 cgoSources: cgoSources,
1158 }
1159
1160 return pr, nil
1161 }
1162
1163 func (b *Builder) coverActionID(a *Action, covMetaFileName string) cache.ActionID {
1164 p := a.Package
1165 h := cache.NewHash("cover " + p.ImportPath)
1166 fmt.Fprintf(h, "cover %q\n", b.toolID("cover"))
1167 b.addPackageOrigin(h, p)
1168
1169
1170 fmt.Fprintf(h, "setup %s %v\n", p.Internal.Cover.Mode, p.Internal.Cover.GenMeta)
1171 fmt.Fprintf(h, "config ")
1172 if err := json.NewEncoder(h).Encode(coverConfig(p, filepath.Base(covMetaFileName), "")); err != nil {
1173 base.Fatal(err)
1174 }
1175 for _, file := range str.StringList(p.GoFiles, p.CgoFiles) {
1176 fmt.Fprintf(h, "file %s %s\n", file, b.fileHash(filepath.Join(p.Dir, file)))
1177 }
1178
1179 return h.Sum()
1180 }
1181
1182
1183
1184 func (b *Builder) cgoCompileActionID(a *Action, f string, flags []string) cache.ActionID {
1185 h := cache.NewHash("cgo compile file")
1186 p := a.Package
1187
1188 fmt.Fprintf(h, "goos %s goarch %s\n", cfg.Goos, cfg.Goarch)
1189
1190 fmt.Fprintf(h, "file %s %s\n", filepath.Base(f), b.fileHash(f))
1191 fmt.Fprintf(h, "flags %q\n", replaceAll(flags, a.Objdir, "$OBJDIR/"))
1192
1193
1194
1195
1196 b.addPackageOrigin(h, p)
1197 if cfg.BuildTrimpath {
1198 fmt.Fprintln(h, "trimpath")
1199 }
1200
1201
1202
1203
1204
1205
1206 b.addCToolchainIDs(h, p)
1207
1208 return h.Sum()
1209 }
1210
1211
1212
1213 func (b *Builder) cgoRunActionID(a *Action) cache.ActionID {
1214 p := a.Package
1215 h := cache.NewHash("cgo " + p.ImportPath)
1216
1217 fmt.Fprintf(h, "goos %s goarch %s\n", cfg.Goos, cfg.Goarch)
1218
1219 fmt.Fprintf(h, "cgo %q\n", b.toolID("cgo"))
1220
1221
1222
1223
1224
1225 fmt.Fprintf(h, "import %q\n", p.ImportPath)
1226
1227
1228
1229
1230 fmt.Fprintf(h, "dir %s\n", p.Dir)
1231 b.addCToolchainIDs(h, p)
1232
1233
1234 fmt.Fprintf(h, "msan %v asan %v\n", cfg.BuildMSan, cfg.BuildASan)
1235
1236 fmt.Fprintf(h, "exportheader %v\n", cfg.BuildBuildmode == "c-archive" || cfg.BuildBuildmode == "c-shared")
1237
1238 if cfg.BuildToolchainName == "gccgo" {
1239 fmt.Fprintf(h, "gccgopkgpath %s\n", gccgoPkgpath(p))
1240 }
1241
1242
1243 fmt.Fprintf(h, "mfiles %v cxxfiles %v ffiles %v\n", len(p.MFiles) > 0, len(p.CXXFiles)+len(p.SwigCXXFiles) > 0, len(p.FFiles) > 0)
1244
1245
1246 if p.Internal.Cover.Mode != "" {
1247
1248 for _, dep := range a.Deps {
1249 if dep.Mode == "cover" {
1250 fmt.Fprintf(h, "cover %x\n", dep.actionID)
1251 break
1252 }
1253 }
1254 } else {
1255 for _, file := range p.CgoFiles {
1256 fmt.Fprintf(h, "file %s %s\n", file, b.fileHash(filepath.Join(p.Dir, file)))
1257 }
1258 }
1259 for _, file := range str.StringList(p.SwigFiles, p.SwigCXXFiles) {
1260 fmt.Fprintf(h, "file %s %s\n", file, b.fileHash(filepath.Join(p.Dir, file)))
1261 }
1262
1263 return h.Sum()
1264 }
1265
1266
1267
1268 type runCgoProviderCached struct {
1269 CFLAGS, CXXFLAGS, FFLAGS, LDFLAGS []string
1270 NotCompatibleForInternalLinking bool
1271 GoFiles []string
1272 Files []string
1273 }
1274
1275 func replaceAll(strs []string, from, to string) []string {
1276 var replaced []string
1277 for _, s := range strs {
1278 replaced = append(replaced, strings.ReplaceAll(s, from, to))
1279 }
1280 return replaced
1281 }
1282
1283 func (b *Builder) cacheRunCgoOutputs(a *Action, pr *runCgoProvider) error {
1284 c := cache.Default()
1285
1286
1287 trimObjdirPrefix := func(files []string) []string {
1288 var trimmed []string
1289 for _, f := range files {
1290 trimmed = append(trimmed, strings.TrimPrefix(f, a.Objdir))
1291 }
1292 return trimmed
1293 }
1294
1295 cgo2Files := func(cgo1Files []string) []string {
1296 var cgo2 []string
1297 for _, f := range cgo1Files {
1298 if base, ok := strings.CutSuffix(f, ".cgo1.go"); ok {
1299 cgo2 = append(cgo2, base+".cgo2.c")
1300 }
1301 }
1302 return cgo2
1303 }
1304
1305 _, outC, outCXX := b.swigOutputs(a.Package, a.Objdir)
1306 files := str.StringList(
1307 []string{"_cgo_export.c", "_cgo_export.h", "_cgo_main.c"},
1308 trimObjdirPrefix(pr.goFiles),
1309 trimObjdirPrefix(cgo2Files(pr.goFiles)),
1310 trimObjdirPrefix(outC),
1311 trimObjdirPrefix(outCXX))
1312 for _, name := range []string{"_cgo_install.h", "_cgo_defun.c", "_cgo_flags"} {
1313 if _, err := os.Stat(a.Objdir + name); err == nil {
1314 files = append(files, name)
1315 }
1316 }
1317 for _, file := range files {
1318 if err := b.cacheObjdirFile(a, c, file); err != nil {
1319 return err
1320 }
1321 }
1322
1323 cached := runCgoProviderCached{
1324 CFLAGS: replaceAll(pr.CFLAGS, a.Objdir, "$OBJDIR/"),
1325 CXXFLAGS: replaceAll(pr.CXXFLAGS, a.Objdir, "$OBJDIR/"),
1326 FFLAGS: replaceAll(pr.FFLAGS, a.Objdir, "$OBJDIR/"),
1327 LDFLAGS: replaceAll(pr.LDFLAGS, a.Objdir, "$OBJDIR/"),
1328 NotCompatibleForInternalLinking: pr.notCompatibleForInternalLinking,
1329 GoFiles: trimObjdirPrefix(pr.goFiles),
1330 Files: files,
1331 }
1332 data, err := json.Marshal(cached)
1333 if err != nil {
1334 return err
1335 }
1336 cache.PutBytes(c, cache.Subkey(a.actionID, "cgorunprovider"), data)
1337 return nil
1338 }
1339
1340 func (b *Builder) loadCachedRunCgoOutputs(a *Action) (*runCgoProvider, error) {
1341 c := cache.Default()
1342
1343 var cached runCgoProviderCached
1344 js, _, err := cache.GetBytes(c, cache.Subkey(a.actionID, "cgorunprovider"))
1345 if err != nil {
1346 return nil, err
1347 } else if err := json.Unmarshal(js, &cached); err != nil {
1348 return nil, err
1349 }
1350
1351 for _, name := range cached.Files {
1352 if err := b.loadCachedObjdirFile(a, c, name); err != nil {
1353 return nil, err
1354 }
1355 }
1356
1357 var goFilesObjdir []string
1358 for _, f := range cached.GoFiles {
1359 goFilesObjdir = append(goFilesObjdir, a.Objdir+f)
1360 }
1361
1362 pr := &runCgoProvider{
1363 CFLAGS: replaceAll(cached.CFLAGS, "$OBJDIR/", a.Objdir),
1364 CXXFLAGS: replaceAll(cached.CXXFLAGS, "$OBJDIR/", a.Objdir),
1365 FFLAGS: replaceAll(cached.FFLAGS, "$OBJDIR/", a.Objdir),
1366 LDFLAGS: replaceAll(cached.LDFLAGS, "$OBJDIR/", a.Objdir),
1367 notCompatibleForInternalLinking: cached.NotCompatibleForInternalLinking,
1368 goFiles: goFilesObjdir,
1369 }
1370
1371 return pr, nil
1372 }
1373
1374 func (b *Builder) loadCachedSrcFiles(a *Action) ([]string, error) {
1375 c := cache.Default()
1376 list, _, err := cache.GetBytes(c, cache.Subkey(a.actionID, "srcfiles"))
1377 if err != nil {
1378 return nil, fmt.Errorf("reading srcfiles list: %w", err)
1379 }
1380 var srcfiles []string
1381 for name := range strings.SplitSeq(string(list), "\n") {
1382 if name == "" {
1383 continue
1384 }
1385 if strings.HasPrefix(name, "./") {
1386 srcfiles = append(srcfiles, name[2:])
1387 continue
1388 }
1389 if err := b.loadCachedObjdirFile(a, c, name); err != nil {
1390 return nil, err
1391 }
1392 srcfiles = append(srcfiles, a.Objdir+name)
1393 }
1394 return srcfiles, nil
1395 }
1396
1397 func (b *Builder) loadCachedVet(a *Action, vetDeps []*Action) error {
1398 srcfiles, err := b.loadCachedSrcFiles(a)
1399 if err != nil {
1400 return err
1401 }
1402 buildVetConfig(a, srcfiles, vetDeps)
1403 return nil
1404 }
1405
1406 func (b *Builder) loadCachedCompiledGoFiles(a *Action) error {
1407 c := cache.Default()
1408 list, _, err := cache.GetBytes(c, cache.Subkey(a.actionID, "srcfiles"))
1409 if err != nil {
1410 return fmt.Errorf("reading srcfiles list: %w", err)
1411 }
1412 var gofiles []string
1413 for name := range strings.SplitSeq(string(list), "\n") {
1414 if name == "" {
1415 continue
1416 } else if !strings.HasSuffix(name, ".go") {
1417 continue
1418 }
1419 if strings.HasPrefix(name, "./") {
1420 gofiles = append(gofiles, name[len("./"):])
1421 continue
1422 }
1423 file, err := b.findCachedObjdirFile(a, c, name)
1424 if err != nil {
1425 return fmt.Errorf("finding %s: %w", name, err)
1426 }
1427 gofiles = append(gofiles, file)
1428 }
1429 a.Package.CompiledGoFiles = gofiles
1430 return nil
1431 }
1432
1433
1434 type vetConfig struct {
1435 ID string
1436 Compiler string
1437 Dir string
1438 ImportPath string
1439 GoFiles []string
1440 NonGoFiles []string
1441 IgnoredFiles []string
1442
1443 Module *analysis.Module
1444 ImportMap map[string]string
1445 PackageFile map[string]string
1446 Standard map[string]bool
1447 PackageVetx map[string]string
1448 VetxOnly bool
1449 VetxOutput string
1450 Stdout string
1451 GoVersion string
1452 FixArchive string
1453
1454 SucceedOnTypecheckFailure bool
1455 }
1456
1457
1458 func analysisModuleFromModulePublic(m *modinfo.ModulePublic) *analysis.Module {
1459 if m == nil {
1460 return nil
1461 }
1462 vm := &analysis.Module{
1463 Path: m.Path,
1464 Version: m.Version,
1465 Replace: analysisModuleFromModulePublic(m.Replace),
1466 Time: m.Time,
1467 Main: m.Main,
1468 Indirect: m.Indirect,
1469 Dir: m.Dir,
1470 GoMod: m.GoMod,
1471 GoVersion: m.GoVersion,
1472 }
1473 if m.Error != nil {
1474 vm.Error = &analysis.ModuleError{Err: m.Error.Err}
1475 }
1476 return vm
1477 }
1478
1479 func buildVetConfig(a *Action, srcfiles []string, vetDeps []*Action) {
1480
1481
1482 var gofiles, nongofiles []string
1483 for _, name := range srcfiles {
1484 if strings.HasSuffix(name, ".go") {
1485 gofiles = append(gofiles, name)
1486 } else {
1487 nongofiles = append(nongofiles, name)
1488 }
1489 }
1490
1491 ignored := str.StringList(a.Package.IgnoredGoFiles, a.Package.IgnoredOtherFiles)
1492
1493
1494
1495
1496
1497 vcfg := &vetConfig{
1498 ID: a.Package.ImportPath,
1499 Compiler: cfg.BuildToolchainName,
1500 Dir: a.Package.Dir,
1501 GoFiles: actualFiles(mkAbsFiles(a.Package.Dir, gofiles)),
1502 NonGoFiles: actualFiles(mkAbsFiles(a.Package.Dir, nongofiles)),
1503 IgnoredFiles: actualFiles(mkAbsFiles(a.Package.Dir, ignored)),
1504 ImportPath: a.Package.ImportPath,
1505 ImportMap: make(map[string]string),
1506 PackageFile: make(map[string]string),
1507 Standard: make(map[string]bool),
1508 }
1509 vcfg.GoVersion = "go" + gover.Local()
1510 if a.Package.Module != nil {
1511 v := a.Package.Module.GoVersion
1512 if v == "" {
1513 v = gover.DefaultGoModVersion
1514 }
1515 vcfg.GoVersion = "go" + v
1516 vcfg.Module = analysisModuleFromModulePublic(a.Package.Module)
1517 }
1518 a.vetCfg = vcfg
1519 for i, raw := range a.Package.Internal.RawImports {
1520 final := a.Package.Imports[i]
1521 vcfg.ImportMap[raw] = final
1522 }
1523
1524
1525
1526 vcfgMapped := make(map[string]bool)
1527 for _, p := range vcfg.ImportMap {
1528 vcfgMapped[p] = true
1529 }
1530
1531 for _, a1 := range vetDeps {
1532 p1 := a1.Package
1533 if p1 == nil || p1.ImportPath == "" || p1 == a.Package {
1534 continue
1535 }
1536
1537
1538 if !vcfgMapped[p1.ImportPath] {
1539 vcfg.ImportMap[p1.ImportPath] = p1.ImportPath
1540 }
1541 if a1.built != "" {
1542 vcfg.PackageFile[p1.ImportPath] = a1.built
1543 }
1544 if p1.Standard {
1545 vcfg.Standard[p1.ImportPath] = true
1546 }
1547 }
1548 }
1549
1550
1551
1552
1553 var VetTool string
1554
1555
1556
1557 var VetFlags []string
1558
1559
1560
1561
1562 var VetHandleStdout = copyToStdout
1563
1564
1565
1566 var VetExplicit bool
1567
1568 func (b *Builder) vet(ctx context.Context, a *Action) error {
1569
1570
1571 a.Failed = nil
1572
1573 if a.Deps[0].Failed != nil {
1574
1575
1576
1577 return nil
1578 }
1579
1580 vcfg := a.Deps[0].vetCfg
1581 if vcfg == nil {
1582
1583 return fmt.Errorf("vet config not found")
1584 }
1585
1586 sh := b.Shell(a)
1587
1588
1589 vcfg.VetxOnly = a.VetxOnly
1590 vcfg.VetxOutput = a.Objdir + "vet.out"
1591 vcfg.Stdout = a.Objdir + "vet.stdout"
1592 if a.needFix {
1593 vcfg.FixArchive = a.Objdir + "vet.fix.zip"
1594 }
1595 vcfg.PackageVetx = make(map[string]string)
1596
1597 h := cache.NewHash("vet " + a.Package.ImportPath)
1598 fmt.Fprintf(h, "vet %q\n", b.toolID("vet"))
1599
1600 vetFlags := VetFlags
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624 if a.Package.Goroot && !VetExplicit && VetTool == base.Tool("vet") {
1625
1626
1627
1628
1629
1630
1631
1632
1633 vetFlags = []string{"-unsafeptr=false"}
1634
1635
1636
1637
1638
1639
1640
1641
1642 if cfg.CmdName == "test" {
1643 vetFlags = append(vetFlags, "-unreachable=false")
1644 }
1645 }
1646
1647
1648
1649
1650
1651
1652 fmt.Fprintf(h, "vetflags %q\n", vetFlags)
1653
1654 fmt.Fprintf(h, "pkg %q\n", a.Deps[0].actionID)
1655 for _, a1 := range a.Deps {
1656 if a1.Mode == "vet" && a1.built != "" {
1657 fmt.Fprintf(h, "vetout %q %s\n", a1.Package.ImportPath, b.fileHash(a1.built))
1658 vcfg.PackageVetx[a1.Package.ImportPath] = a1.built
1659 }
1660 }
1661 var (
1662 id = cache.ActionID(h.Sum())
1663 stdoutKey = cache.Subkey(id, "stdout")
1664 fixArchiveKey = cache.Subkey(id, "fix.zip")
1665 )
1666
1667
1668 if !cfg.BuildA {
1669 c := cache.Default()
1670
1671
1672
1673
1674 var (
1675 vetxFile string
1676 fixArchive string
1677 stdout io.Reader = bytes.NewReader(nil)
1678 )
1679
1680
1681 vetxFile, _, err := cache.GetFile(c, id)
1682 if err != nil {
1683 goto cachemiss
1684 }
1685
1686
1687 if a.needFix {
1688 file, _, err := cache.GetFile(c, fixArchiveKey)
1689 if err != nil {
1690 goto cachemiss
1691 }
1692 fixArchive = file
1693 }
1694
1695
1696 if file, _, err := cache.GetFile(c, stdoutKey); err == nil {
1697 f, err := os.Open(file)
1698 if err != nil {
1699 goto cachemiss
1700 }
1701 defer f.Close()
1702 stdout = f
1703 }
1704
1705
1706 a.built = vetxFile
1707 a.FixArchive = fixArchive
1708 if err := VetHandleStdout(stdout); err != nil {
1709 return err
1710 }
1711
1712 return nil
1713 }
1714 cachemiss:
1715
1716 js, err := json.MarshalIndent(vcfg, "", "\t")
1717 if err != nil {
1718 return fmt.Errorf("internal error marshaling vet config: %v", err)
1719 }
1720 js = append(js, '\n')
1721 if err := sh.writeFile(a.Objdir+"vet.cfg", js); err != nil {
1722 return err
1723 }
1724
1725
1726 env := b.cCompilerEnv()
1727 if cfg.BuildToolchainName == "gccgo" {
1728 env = append(env, "GCCGO="+BuildToolchain.compiler())
1729 }
1730
1731 p := a.Package
1732 tool := VetTool
1733 if tool == "" {
1734 panic("VetTool unset")
1735 }
1736
1737 if err := sh.run(p.Dir, p.ImportPath, env, cfg.BuildToolexec, tool, vetFlags, a.Objdir+"vet.cfg"); err != nil {
1738 return err
1739 }
1740
1741
1742
1743
1744
1745 if f, err := os.Open(vcfg.VetxOutput); err == nil {
1746 defer f.Close()
1747 a.built = vcfg.VetxOutput
1748 cache.Default().Put(id, f)
1749 }
1750
1751
1752 if a.needFix {
1753 if f, err := os.Open(vcfg.FixArchive); err == nil {
1754 defer f.Close()
1755 a.FixArchive = vcfg.FixArchive
1756 cache.Default().Put(fixArchiveKey, f)
1757 }
1758 }
1759
1760
1761 if f, err := os.Open(vcfg.Stdout); err == nil {
1762 defer f.Close()
1763 if err := VetHandleStdout(f); err != nil {
1764 return err
1765 }
1766 f.Seek(0, io.SeekStart)
1767 cache.Default().Put(stdoutKey, f)
1768 }
1769
1770 return nil
1771 }
1772
1773 var stdoutMu sync.Mutex
1774
1775
1776 func copyToStdout(r io.Reader) error {
1777 stdoutMu.Lock()
1778 defer stdoutMu.Unlock()
1779 if _, err := io.Copy(os.Stdout, r); err != nil {
1780 return fmt.Errorf("copying vet tool stdout: %w", err)
1781 }
1782 return nil
1783 }
1784
1785
1786 func (b *Builder) linkActionID(a *Action) cache.ActionID {
1787 p := a.Package
1788 h := cache.NewHash("link " + p.ImportPath)
1789
1790
1791 fmt.Fprintf(h, "link\n")
1792
1793
1794
1795 fmt.Fprintf(h, "buildmode %s goos %s goarch %s\n", ldBuildmode, cfg.Goos, cfg.Goarch)
1796 fmt.Fprintf(h, "import %q\n", p.ImportPath)
1797 fmt.Fprintf(h, "omitdebug %v standard %v local %v prefix %q\n", p.Internal.OmitDebug, p.Standard, p.Internal.Local, p.Internal.LocalPrefix)
1798 fmt.Fprintf(h, "defaultgodebug %q\n", p.DefaultGODEBUG)
1799 if cfg.BuildTrimpath {
1800 fmt.Fprintln(h, "trimpath")
1801 }
1802
1803
1804 b.printLinkerConfig(h, p)
1805
1806
1807 for _, a1 := range a.Deps {
1808 p1 := a1.Package
1809 if p1 != nil {
1810 if a1.built != "" || a1.buildID != "" {
1811 buildID := a1.buildID
1812 if buildID == "" {
1813 buildID = b.buildID(a1.built)
1814 }
1815 fmt.Fprintf(h, "packagefile %s=%s\n", p1.ImportPath, contentID(buildID))
1816 }
1817
1818
1819 if p1.Name == "main" {
1820 fmt.Fprintf(h, "packagemain %s\n", a1.buildID)
1821 }
1822 if p1.Shlib != "" {
1823 fmt.Fprintf(h, "packageshlib %s=%s\n", p1.ImportPath, contentID(b.buildID(p1.Shlib)))
1824 }
1825 }
1826 }
1827
1828 return h.Sum()
1829 }
1830
1831
1832
1833 func (b *Builder) printLinkerConfig(h io.Writer, p *load.Package) {
1834 switch cfg.BuildToolchainName {
1835 default:
1836 base.Fatalf("linkActionID: unknown toolchain %q", cfg.BuildToolchainName)
1837
1838 case "gc":
1839 fmt.Fprintf(h, "link %s %q %s\n", b.toolID("link"), forcedLdflags, ldBuildmode)
1840 if p != nil {
1841 fmt.Fprintf(h, "linkflags %q\n", p.Internal.Ldflags)
1842 }
1843
1844
1845 key, val, _ := cfg.GetArchEnv()
1846 fmt.Fprintf(h, "%s=%s\n", key, val)
1847
1848 if cfg.CleanGOEXPERIMENT != "" {
1849 fmt.Fprintf(h, "GOEXPERIMENT=%q\n", cfg.CleanGOEXPERIMENT)
1850 }
1851
1852
1853
1854 gorootFinal := cfg.GOROOT
1855 if cfg.BuildTrimpath {
1856 gorootFinal = ""
1857 }
1858 fmt.Fprintf(h, "GOROOT=%s\n", gorootFinal)
1859
1860
1861 fmt.Fprintf(h, "GO_EXTLINK_ENABLED=%s\n", cfg.Getenv("GO_EXTLINK_ENABLED"))
1862
1863
1864
1865
1866 case "gccgo":
1867 id, _, err := b.gccgoToolID(BuildToolchain.linker(), "go")
1868 if err != nil {
1869 base.Fatalf("%v", err)
1870 }
1871 fmt.Fprintf(h, "link %s %s\n", id, ldBuildmode)
1872
1873 }
1874 }
1875
1876
1877
1878 func (b *Builder) link(ctx context.Context, a *Action) (err error) {
1879 if b.useCache(a, b.linkActionID(a), a.Package.Target, !b.IsCmdList) || b.IsCmdList {
1880 return nil
1881 }
1882 defer b.flushOutput(a)
1883
1884 sh := b.Shell(a)
1885 if err := sh.Mkdir(a.Objdir); err != nil {
1886 return err
1887 }
1888
1889 importcfg := a.Objdir + "importcfg.link"
1890 if err := b.writeLinkImportcfg(a, importcfg); err != nil {
1891 return err
1892 }
1893
1894 if err := AllowInstall(a); err != nil {
1895 return err
1896 }
1897
1898
1899 dir, _ := filepath.Split(a.Target)
1900 if dir != "" {
1901 if err := sh.Mkdir(dir); err != nil {
1902 return err
1903 }
1904 }
1905
1906 if err := BuildToolchain.ld(b, a, a.Target, importcfg, a.Deps[0].built); err != nil {
1907 return err
1908 }
1909
1910
1911 if err := b.updateBuildID(a, a.Target); err != nil {
1912 return err
1913 }
1914
1915 a.built = a.Target
1916 return nil
1917 }
1918
1919 func (b *Builder) writeLinkImportcfg(a *Action, file string) error {
1920
1921 var icfg bytes.Buffer
1922 for _, a1 := range a.Deps {
1923 p1 := a1.Package
1924 if p1 == nil {
1925 continue
1926 }
1927 fmt.Fprintf(&icfg, "packagefile %s=%s\n", p1.ImportPath, a1.built)
1928 if p1.Shlib != "" {
1929 fmt.Fprintf(&icfg, "packageshlib %s=%s\n", p1.ImportPath, p1.Shlib)
1930 }
1931 }
1932 info := ""
1933 if a.Package.Internal.BuildInfo != nil {
1934 info = a.Package.Internal.BuildInfo.String()
1935 }
1936 fmt.Fprintf(&icfg, "modinfo %q\n", modload.ModInfoData(info))
1937 return b.Shell(a).writeFile(file, icfg.Bytes())
1938 }
1939
1940
1941
1942 func (b *Builder) PkgconfigCmd() string {
1943 return envList("PKG_CONFIG", cfg.DefaultPkgConfig)[0]
1944 }
1945
1946
1947
1948
1949
1950
1951
1952 func splitPkgConfigOutput(out []byte) ([]string, error) {
1953 if len(out) == 0 {
1954 return nil, nil
1955 }
1956 var flags []string
1957 flag := make([]byte, 0, len(out))
1958 didQuote := false
1959 escaped := false
1960 quote := byte(0)
1961
1962 for _, c := range out {
1963 if escaped {
1964 if quote == '"' {
1965
1966
1967
1968 switch c {
1969 case '$', '`', '"', '\\', '\n':
1970
1971 default:
1972
1973 flag = append(flag, '\\', c)
1974 escaped = false
1975 continue
1976 }
1977 }
1978
1979 if c == '\n' {
1980
1981
1982 } else {
1983 flag = append(flag, c)
1984 }
1985 escaped = false
1986 continue
1987 }
1988
1989 if quote != 0 && c == quote {
1990 quote = 0
1991 continue
1992 }
1993 switch quote {
1994 case '\'':
1995
1996 flag = append(flag, c)
1997 continue
1998 case '"':
1999
2000
2001 switch c {
2002 case '`', '$', '\\':
2003 default:
2004 flag = append(flag, c)
2005 continue
2006 }
2007 }
2008
2009
2010
2011 switch c {
2012 case '|', '&', ';', '<', '>', '(', ')', '$', '`':
2013 return nil, fmt.Errorf("unexpected shell character %q in pkgconf output", c)
2014
2015 case '\\':
2016
2017
2018 escaped = true
2019 continue
2020
2021 case '"', '\'':
2022 quote = c
2023 didQuote = true
2024 continue
2025
2026 case ' ', '\t', '\n':
2027 if len(flag) > 0 || didQuote {
2028 flags = append(flags, string(flag))
2029 }
2030 flag, didQuote = flag[:0], false
2031 continue
2032 }
2033
2034 flag = append(flag, c)
2035 }
2036
2037
2038
2039
2040 if quote != 0 {
2041 return nil, errors.New("unterminated quoted string in pkgconf output")
2042 }
2043 if escaped {
2044 return nil, errors.New("broken character escaping in pkgconf output")
2045 }
2046
2047 if len(flag) > 0 || didQuote {
2048 flags = append(flags, string(flag))
2049 }
2050 return flags, nil
2051 }
2052
2053
2054 func (b *Builder) getPkgConfigFlags(a *Action, p *load.Package) (cflags, ldflags []string, err error) {
2055 sh := b.Shell(a)
2056 if pcargs := p.CgoPkgConfig; len(pcargs) > 0 {
2057
2058
2059 var pcflags []string
2060 var pkgs []string
2061 for _, pcarg := range pcargs {
2062 if pcarg == "--" {
2063
2064 } else if strings.HasPrefix(pcarg, "--") {
2065 pcflags = append(pcflags, pcarg)
2066 } else {
2067 pkgs = append(pkgs, pcarg)
2068 }
2069 }
2070 for _, pkg := range pkgs {
2071 if !load.SafeArg(pkg) {
2072 return nil, nil, fmt.Errorf("invalid pkg-config package name: %s", pkg)
2073 }
2074 }
2075
2076 if err := checkPkgConfigFlags("", "pkg-config", pcflags); err != nil {
2077 return nil, nil, err
2078 }
2079
2080 var out []byte
2081 out, err = sh.runOut(p.Dir, nil, b.PkgconfigCmd(), "--cflags", pcflags, "--", pkgs)
2082 if err != nil {
2083 desc := b.PkgconfigCmd() + " --cflags " + strings.Join(pcflags, " ") + " -- " + strings.Join(pkgs, " ")
2084 return nil, nil, sh.reportCmd(desc, "", out, err)
2085 }
2086 if len(out) > 0 {
2087 cflags, err = splitPkgConfigOutput(bytes.TrimSpace(out))
2088 if err != nil {
2089 return nil, nil, err
2090 }
2091 if err := checkCompilerFlags("CFLAGS", "pkg-config --cflags", cflags); err != nil {
2092 return nil, nil, err
2093 }
2094 }
2095 out, err = sh.runOut(p.Dir, nil, b.PkgconfigCmd(), "--libs", pcflags, "--", pkgs)
2096 if err != nil {
2097 desc := b.PkgconfigCmd() + " --libs " + strings.Join(pcflags, " ") + " -- " + strings.Join(pkgs, " ")
2098 return nil, nil, sh.reportCmd(desc, "", out, err)
2099 }
2100 if len(out) > 0 {
2101
2102
2103 ldflags, err = splitPkgConfigOutput(bytes.TrimSpace(out))
2104 if err != nil {
2105 return nil, nil, err
2106 }
2107 if err := checkLinkerFlags("LDFLAGS", "pkg-config --libs", ldflags); err != nil {
2108 return nil, nil, err
2109 }
2110 }
2111 }
2112
2113 return
2114 }
2115
2116 func (b *Builder) installShlibname(ctx context.Context, a *Action) error {
2117 if err := AllowInstall(a); err != nil {
2118 return err
2119 }
2120
2121 sh := b.Shell(a)
2122 a1 := a.Deps[0]
2123 if !cfg.BuildN {
2124 if err := sh.Mkdir(filepath.Dir(a.Target)); err != nil {
2125 return err
2126 }
2127 }
2128 return sh.writeFile(a.Target, []byte(filepath.Base(a1.Target)+"\n"))
2129 }
2130
2131 func (b *Builder) linkSharedActionID(a *Action) cache.ActionID {
2132 h := cache.NewHash("linkShared")
2133
2134
2135 fmt.Fprintf(h, "linkShared\n")
2136 fmt.Fprintf(h, "goos %s goarch %s\n", cfg.Goos, cfg.Goarch)
2137
2138
2139 b.printLinkerConfig(h, nil)
2140
2141
2142 for _, a1 := range a.Deps {
2143 p1 := a1.Package
2144 if a1.built == "" {
2145 continue
2146 }
2147 if p1 != nil {
2148 fmt.Fprintf(h, "packagefile %s=%s\n", p1.ImportPath, contentID(b.buildID(a1.built)))
2149 if p1.Shlib != "" {
2150 fmt.Fprintf(h, "packageshlib %s=%s\n", p1.ImportPath, contentID(b.buildID(p1.Shlib)))
2151 }
2152 }
2153 }
2154
2155 for _, a1 := range a.Deps[0].Deps {
2156 p1 := a1.Package
2157 fmt.Fprintf(h, "top %s=%s\n", p1.ImportPath, contentID(b.buildID(a1.built)))
2158 }
2159
2160 return h.Sum()
2161 }
2162
2163 func (b *Builder) linkShared(ctx context.Context, a *Action) (err error) {
2164 if b.useCache(a, b.linkSharedActionID(a), a.Target, !b.IsCmdList) || b.IsCmdList {
2165 return nil
2166 }
2167 defer b.flushOutput(a)
2168
2169 if err := AllowInstall(a); err != nil {
2170 return err
2171 }
2172
2173 if err := b.Shell(a).Mkdir(a.Objdir); err != nil {
2174 return err
2175 }
2176
2177 importcfg := a.Objdir + "importcfg.link"
2178 if err := b.writeLinkImportcfg(a, importcfg); err != nil {
2179 return err
2180 }
2181
2182
2183
2184 a.built = a.Target
2185 return BuildToolchain.ldShared(b, a, a.Deps[0].Deps, a.Target, importcfg, a.Deps)
2186 }
2187
2188
2189 func BuildInstallFunc(b *Builder, ctx context.Context, a *Action) (err error) {
2190 defer func() {
2191 if err != nil {
2192
2193
2194
2195 sep, path := "", ""
2196 if a.Package != nil {
2197 sep, path = " ", a.Package.ImportPath
2198 }
2199 err = fmt.Errorf("go %s%s%s: %v", cfg.CmdName, sep, path, err)
2200 }
2201 }()
2202 sh := b.Shell(a)
2203
2204 a1 := a.Deps[0]
2205 a.buildID = a1.buildID
2206 if a.json != nil {
2207 a.json.BuildID = a.buildID
2208 }
2209
2210
2211
2212
2213
2214
2215 if a1.built == a.Target {
2216 a.built = a.Target
2217 if !a.buggyInstall {
2218 b.cleanup(a1)
2219 }
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238 if !a.buggyInstall && !b.IsCmdList {
2239 if cfg.BuildN {
2240 sh.ShowCmd("", "touch %s", a.Target)
2241 } else if err := AllowInstall(a); err == nil {
2242 now := time.Now()
2243 os.Chtimes(a.Target, now, now)
2244 }
2245 }
2246 return nil
2247 }
2248
2249
2250
2251 if b.IsCmdList {
2252 a.built = a1.built
2253 return nil
2254 }
2255 if err := AllowInstall(a); err != nil {
2256 return err
2257 }
2258
2259 if err := sh.Mkdir(a.Objdir); err != nil {
2260 return err
2261 }
2262
2263 perm := fs.FileMode(0666)
2264 if a1.Mode == "link" {
2265 switch cfg.BuildBuildmode {
2266 case "c-archive", "c-shared", "plugin":
2267 default:
2268 perm = 0777
2269 }
2270 }
2271
2272
2273 dir, _ := filepath.Split(a.Target)
2274 if dir != "" {
2275 if err := sh.Mkdir(dir); err != nil {
2276 return err
2277 }
2278 }
2279
2280 if !a.buggyInstall {
2281 defer b.cleanup(a1)
2282 }
2283
2284 return sh.moveOrCopyFile(a.Target, a1.built, perm, false)
2285 }
2286
2287
2288
2289
2290
2291
2292 var AllowInstall = func(*Action) error { return nil }
2293
2294
2295
2296
2297
2298 func (b *Builder) cleanup(a *Action) {
2299 if !cfg.BuildWork {
2300 b.Shell(a).RemoveAll(a.Objdir)
2301 }
2302 }
2303
2304
2305 func (b *Builder) installHeader(ctx context.Context, a *Action) error {
2306 sh := b.Shell(a)
2307
2308 src := a.Objdir + "_cgo_install.h"
2309 if _, err := os.Stat(src); os.IsNotExist(err) {
2310
2311
2312
2313
2314
2315 if cfg.BuildX {
2316 sh.ShowCmd("", "# %s not created", src)
2317 }
2318 return nil
2319 }
2320
2321 if err := AllowInstall(a); err != nil {
2322 return err
2323 }
2324
2325 dir, _ := filepath.Split(a.Target)
2326 if dir != "" {
2327 if err := sh.Mkdir(dir); err != nil {
2328 return err
2329 }
2330 }
2331
2332 return sh.moveOrCopyFile(a.Target, src, 0666, true)
2333 }
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343 func (b *Builder) cover(a *Action, infiles, outfiles []string, varName, mode, covMetaFileName, coverCfg string) ([]string, error) {
2344 pkgcfg := a.Objdir + "pkgcfg.txt"
2345 covoutputs := a.Objdir + "coveroutfiles.txt"
2346 odir := filepath.Dir(outfiles[0])
2347 cv := filepath.Join(odir, "covervars.go")
2348 outfiles = append([]string{cv}, outfiles...)
2349 if err := b.writeCoverPkgInputs(a, pkgcfg, covMetaFileName, coverCfg, covoutputs, outfiles); err != nil {
2350 return nil, err
2351 }
2352 args := []string{base.Tool("cover"),
2353 "-pkgcfg", pkgcfg,
2354 "-mode", mode,
2355 "-var", varName,
2356 "-outfilelist", covoutputs,
2357 }
2358 args = append(args, infiles...)
2359 if err := b.Shell(a).run(a.Objdir, "", nil,
2360 cfg.BuildToolexec, args); err != nil {
2361 return nil, err
2362 }
2363 return outfiles, nil
2364 }
2365
2366 func coverConfig(p *load.Package, covMetaFileName, outConfig string) covcmd.CoverPkgConfig {
2367 pcfg := covcmd.CoverPkgConfig{
2368 PkgPath: p.ImportPath,
2369 PkgName: p.Name,
2370
2371
2372
2373
2374 Granularity: "perblock",
2375 OutConfig: outConfig,
2376 Local: p.Internal.Local,
2377 EmitMetaFile: covMetaFileName,
2378 }
2379 if p.Module != nil {
2380 pcfg.ModulePath = p.Module.Path
2381 }
2382 return pcfg
2383 }
2384
2385 func (b *Builder) writeCoverPkgInputs(a *Action, pconfigfile, covMetaFileName, coverCfg, covoutputsfile string, outfiles []string) error {
2386 sh := b.Shell(a)
2387 p := a.Package
2388 pcfg := coverConfig(p, covMetaFileName, coverCfg)
2389 data, err := json.Marshal(pcfg)
2390 if err != nil {
2391 return err
2392 }
2393 data = append(data, '\n')
2394 if err := sh.writeFile(pconfigfile, data); err != nil {
2395 return err
2396 }
2397 var sb strings.Builder
2398 for i := range outfiles {
2399 fmt.Fprintf(&sb, "%s\n", outfiles[i])
2400 }
2401 return sh.writeFile(covoutputsfile, []byte(sb.String()))
2402 }
2403
2404 var objectMagic = [][]byte{
2405 {'!', '<', 'a', 'r', 'c', 'h', '>', '\n'},
2406 {'<', 'b', 'i', 'g', 'a', 'f', '>', '\n'},
2407 {'\x7F', 'E', 'L', 'F'},
2408 {0xFE, 0xED, 0xFA, 0xCE},
2409 {0xFE, 0xED, 0xFA, 0xCF},
2410 {0xCE, 0xFA, 0xED, 0xFE},
2411 {0xCF, 0xFA, 0xED, 0xFE},
2412 {0x4d, 0x5a, 0x90, 0x00, 0x03, 0x00},
2413 {0x4d, 0x5a, 0x78, 0x00, 0x01, 0x00},
2414 {0x00, 0x00, 0x01, 0xEB},
2415 {0x00, 0x00, 0x8a, 0x97},
2416 {0x00, 0x00, 0x06, 0x47},
2417 {0x00, 0x61, 0x73, 0x6D},
2418 {0x01, 0xDF},
2419 {0x01, 0xF7},
2420 }
2421
2422 func isObject(s string) bool {
2423 f, err := os.Open(s)
2424 if err != nil {
2425 return false
2426 }
2427 defer f.Close()
2428 buf := make([]byte, 64)
2429 io.ReadFull(f, buf)
2430 for _, magic := range objectMagic {
2431 if bytes.HasPrefix(buf, magic) {
2432 return true
2433 }
2434 }
2435 return false
2436 }
2437
2438
2439
2440
2441 func (b *Builder) cCompilerEnv() []string {
2442 return []string{"TERM=dumb"}
2443 }
2444
2445
2446
2447
2448
2449
2450 func mkAbs(dir, f string) string {
2451
2452
2453
2454
2455 if filepath.IsAbs(f) || strings.HasPrefix(f, "$WORK") {
2456 return f
2457 }
2458 return filepath.Join(dir, f)
2459 }
2460
2461 type toolchain interface {
2462
2463
2464 gc(b *Builder, a *Action, archive string, importcfg, embedcfg []byte, symabis string, asmhdr bool, pgoProfile, coverCfg string, gofiles []string) (ofile string, out []byte, err error)
2465
2466
2467 cc(b *Builder, a *Action, ofile, cfile string) error
2468
2469
2470 asm(b *Builder, a *Action, sfiles []string) ([]string, error)
2471
2472
2473 symabis(b *Builder, a *Action, sfiles []string) (string, error)
2474
2475
2476
2477 pack(b *Builder, a *Action, afile string, ofiles []string) error
2478
2479 ld(b *Builder, root *Action, targetPath, importcfg, mainpkg string) error
2480
2481 ldShared(b *Builder, root *Action, toplevelactions []*Action, targetPath, importcfg string, allactions []*Action) error
2482
2483 compiler() string
2484 linker() string
2485 }
2486
2487 type noToolchain struct{}
2488
2489 func noCompiler() error {
2490 log.Fatalf("unknown compiler %q", cfg.BuildContext.Compiler)
2491 return nil
2492 }
2493
2494 func (noToolchain) compiler() string {
2495 noCompiler()
2496 return ""
2497 }
2498
2499 func (noToolchain) linker() string {
2500 noCompiler()
2501 return ""
2502 }
2503
2504 func (noToolchain) gc(b *Builder, a *Action, archive string, importcfg, embedcfg []byte, symabis string, asmhdr bool, pgoProfile, coverCfg string, gofiles []string) (ofile string, out []byte, err error) {
2505 return "", nil, noCompiler()
2506 }
2507
2508 func (noToolchain) asm(b *Builder, a *Action, sfiles []string) ([]string, error) {
2509 return nil, noCompiler()
2510 }
2511
2512 func (noToolchain) symabis(b *Builder, a *Action, sfiles []string) (string, error) {
2513 return "", noCompiler()
2514 }
2515
2516 func (noToolchain) pack(b *Builder, a *Action, afile string, ofiles []string) error {
2517 return noCompiler()
2518 }
2519
2520 func (noToolchain) ld(b *Builder, root *Action, targetPath, importcfg, mainpkg string) error {
2521 return noCompiler()
2522 }
2523
2524 func (noToolchain) ldShared(b *Builder, root *Action, toplevelactions []*Action, targetPath, importcfg string, allactions []*Action) error {
2525 return noCompiler()
2526 }
2527
2528 func (noToolchain) cc(b *Builder, a *Action, ofile, cfile string) error {
2529 return noCompiler()
2530 }
2531
2532
2533 func (b *Builder) gcc(a *Action, workdir, out string, flags []string, cfile string) error {
2534 p := a.Package
2535 return b.ccompile(a, out, flags, cfile, b.GccCmd(p.Dir, workdir))
2536 }
2537
2538
2539 func (b *Builder) gas(a *Action, workdir, out string, flags []string, sfile string) error {
2540 p := a.Package
2541 data, err := os.ReadFile(sfile)
2542 if err == nil {
2543 if bytes.HasPrefix(data, []byte("TEXT")) || bytes.Contains(data, []byte("\nTEXT")) ||
2544 bytes.HasPrefix(data, []byte("DATA")) || bytes.Contains(data, []byte("\nDATA")) ||
2545 bytes.HasPrefix(data, []byte("GLOBL")) || bytes.Contains(data, []byte("\nGLOBL")) {
2546 return fmt.Errorf("package using cgo has Go assembly file %s", sfile)
2547 }
2548 }
2549 return b.ccompile(a, out, flags, sfile, b.GccCmd(p.Dir, workdir))
2550 }
2551
2552
2553 func (b *Builder) gxx(a *Action, workdir, out string, flags []string, cxxfile string) error {
2554 p := a.Package
2555 return b.ccompile(a, out, flags, cxxfile, b.GxxCmd(p.Dir, workdir))
2556 }
2557
2558
2559 func (b *Builder) gfortran(a *Action, workdir, out string, flags []string, ffile string) error {
2560 p := a.Package
2561 return b.ccompile(a, out, flags, ffile, b.gfortranCmd(p.Dir, workdir))
2562 }
2563
2564
2565 func (b *Builder) ccompile(a *Action, outfile string, flags []string, file string, compiler []string) error {
2566 p := a.Package
2567 sh := b.Shell(a)
2568 file = mkAbs(p.Dir, file)
2569 outfile = mkAbs(p.Dir, outfile)
2570
2571 flags = slices.Clip(flags)
2572
2573
2574
2575
2576
2577
2578 if b.gccSupportsFlag(compiler, "-fdebug-prefix-map=a=b") {
2579 if cfg.BuildTrimpath || p.Goroot {
2580 prefixMapFlag := "-fdebug-prefix-map"
2581 if b.gccSupportsFlag(compiler, "-ffile-prefix-map=a=b") {
2582 prefixMapFlag = "-ffile-prefix-map"
2583 }
2584
2585
2586
2587 var from, toPath string
2588 if m := p.Module; m == nil {
2589 if p.Root == "" {
2590 from = p.Dir
2591 toPath = p.ImportPath
2592 } else if p.Goroot {
2593 from = p.Root
2594 toPath = "GOROOT"
2595 } else {
2596 from = p.Root
2597 toPath = "GOPATH"
2598 }
2599 } else if m.Dir == "" {
2600
2601
2602 from = b.getVendorDir()
2603 toPath = "vendor"
2604 } else {
2605 from = m.Dir
2606 toPath = m.Path
2607 if m.Version != "" {
2608 toPath += "@" + m.Version
2609 }
2610 }
2611
2612
2613
2614 var to string
2615 if cfg.BuildContext.GOOS == "windows" {
2616 to = filepath.Join(`\\_\_`, toPath)
2617 } else {
2618 to = filepath.Join("/_", toPath)
2619 }
2620 flags = append(slices.Clip(flags), prefixMapFlag+"="+from+"="+to)
2621 }
2622 }
2623
2624
2625
2626 if b.gccSupportsFlag(compiler, "-frandom-seed=1") {
2627 flags = append(flags, "-frandom-seed="+buildid.HashToString(a.actionID))
2628 }
2629
2630 overlayPath := file
2631 if p, ok := a.nonGoOverlay[overlayPath]; ok {
2632 overlayPath = p
2633 }
2634 output, err := sh.runOut(filepath.Dir(overlayPath), b.cCompilerEnv(), compiler, flags, "-o", outfile, "-c", filepath.Base(overlayPath))
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644 if bytes.Contains(output, []byte("DWARF2 only supports one section per compilation unit")) {
2645 newFlags := make([]string, 0, len(flags))
2646 for _, f := range flags {
2647 if !strings.HasPrefix(f, "-g") {
2648 newFlags = append(newFlags, f)
2649 }
2650 }
2651 if len(newFlags) < len(flags) {
2652 return b.ccompile(a, outfile, newFlags, file, compiler)
2653 }
2654 }
2655
2656 if len(output) > 0 && err == nil && os.Getenv("GO_BUILDER_NAME") != "" {
2657 output = append(output, "C compiler warning promoted to error on Go builders\n"...)
2658 err = errors.New("warning promoted to error")
2659 }
2660
2661 return sh.reportCmd("", "", output, err)
2662 }
2663
2664
2665 func (b *Builder) gccld(a *Action, objdir, outfile string, flags []string, objs []string) error {
2666 p := a.Package
2667 sh := b.Shell(a)
2668 var cmd []string
2669 if len(p.CXXFiles) > 0 || len(p.SwigCXXFiles) > 0 {
2670 cmd = b.GxxCmd(p.Dir, objdir)
2671 } else {
2672 cmd = b.GccCmd(p.Dir, objdir)
2673 }
2674
2675 cmdargs := []any{cmd, "-o", outfile, objs, flags}
2676 _, err := sh.runOut(base.Cwd(), b.cCompilerEnv(), cmdargs...)
2677
2678
2679
2680 if cfg.BuildN || cfg.BuildX {
2681 saw := "succeeded"
2682 if err != nil {
2683 saw = "failed"
2684 }
2685 sh.ShowCmd("", "%s # test for internal linking errors (%s)", joinUnambiguously(str.StringList(cmdargs...)), saw)
2686 }
2687
2688 return err
2689 }
2690
2691
2692
2693 func (b *Builder) GccCmd(incdir, workdir string) []string {
2694 return b.compilerCmd(b.ccExe(), incdir, workdir)
2695 }
2696
2697
2698
2699 func (b *Builder) GxxCmd(incdir, workdir string) []string {
2700 return b.compilerCmd(b.cxxExe(), incdir, workdir)
2701 }
2702
2703
2704 func (b *Builder) gfortranCmd(incdir, workdir string) []string {
2705 return b.compilerCmd(b.fcExe(), incdir, workdir)
2706 }
2707
2708
2709 func (b *Builder) ccExe() []string {
2710 return envList("CC", cfg.DefaultCC(cfg.Goos, cfg.Goarch))
2711 }
2712
2713
2714 func (b *Builder) cxxExe() []string {
2715 return envList("CXX", cfg.DefaultCXX(cfg.Goos, cfg.Goarch))
2716 }
2717
2718
2719 func (b *Builder) fcExe() []string {
2720 return envList("FC", "gfortran")
2721 }
2722
2723
2724
2725 func (b *Builder) compilerCmd(compiler []string, incdir, workdir string) []string {
2726 a := append(compiler, "-I", incdir)
2727
2728
2729
2730 if cfg.Goos != "windows" {
2731 a = append(a, "-fPIC")
2732 }
2733 a = append(a, b.gccArchArgs()...)
2734
2735
2736 if cfg.BuildContext.CgoEnabled {
2737 a = append(a, "-pthread")
2738 }
2739
2740 if cfg.Goos == "aix" {
2741
2742 a = append(a, "-mcmodel=large")
2743 }
2744
2745
2746 if b.gccSupportsFlag(compiler, "-fno-caret-diagnostics") {
2747 a = append(a, "-fno-caret-diagnostics")
2748 }
2749
2750 if b.gccSupportsFlag(compiler, "-Qunused-arguments") {
2751 a = append(a, "-Qunused-arguments")
2752 }
2753
2754
2755
2756
2757 if b.gccSupportsFlag(compiler, "-Wl,--no-gc-sections") {
2758 a = append(a, "-Wl,--no-gc-sections")
2759 }
2760
2761
2762 a = append(a, "-fmessage-length=0")
2763
2764
2765 if b.gccSupportsFlag(compiler, "-fdebug-prefix-map=a=b") {
2766 if workdir == "" {
2767 workdir = b.WorkDir
2768 }
2769 workdir = strings.TrimSuffix(workdir, string(filepath.Separator))
2770 if b.gccSupportsFlag(compiler, "-ffile-prefix-map=a=b") {
2771 a = append(a, "-ffile-prefix-map="+workdir+"=/tmp/go-build")
2772 } else {
2773 a = append(a, "-fdebug-prefix-map="+workdir+"=/tmp/go-build")
2774 }
2775 }
2776
2777
2778
2779 if b.gccSupportsFlag(compiler, "-gno-record-gcc-switches") {
2780 a = append(a, "-gno-record-gcc-switches")
2781 }
2782
2783
2784
2785
2786 if cfg.Goos == "darwin" || cfg.Goos == "ios" {
2787 a = append(a, "-fno-common")
2788 }
2789
2790 return a
2791 }
2792
2793
2794
2795
2796
2797 func (b *Builder) gccNoPie(linker []string) string {
2798 if b.gccSupportsFlag(linker, "-no-pie") {
2799 return "-no-pie"
2800 }
2801 if b.gccSupportsFlag(linker, "-nopie") {
2802 return "-nopie"
2803 }
2804 return ""
2805 }
2806
2807
2808 func (b *Builder) gccSupportsFlag(compiler []string, flag string) bool {
2809
2810
2811
2812 sh := b.BackgroundShell()
2813
2814 key := [2]string{compiler[0], flag}
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832 tmp := os.DevNull
2833 if runtime.GOOS == "windows" || runtime.GOOS == "ios" {
2834 f, err := os.CreateTemp(b.WorkDir, "")
2835 if err != nil {
2836 return false
2837 }
2838 f.Close()
2839 tmp = f.Name()
2840 defer os.Remove(tmp)
2841 }
2842
2843 cmdArgs := str.StringList(compiler, flag)
2844 if strings.HasPrefix(flag, "-Wl,") {
2845 ldflags, err := buildFlags("LDFLAGS", DefaultCFlags, nil, checkLinkerFlags)
2846 if err != nil {
2847 return false
2848 }
2849 cmdArgs = append(cmdArgs, ldflags...)
2850 } else {
2851 cflags, err := buildFlags("CFLAGS", DefaultCFlags, nil, checkCompilerFlags)
2852 if err != nil {
2853 return false
2854 }
2855 cmdArgs = append(cmdArgs, cflags...)
2856 cmdArgs = append(cmdArgs, "-c")
2857 }
2858
2859 cmdArgs = append(cmdArgs, "-x", "c", "-", "-o", tmp)
2860
2861 if cfg.BuildN {
2862 sh.ShowCmd(b.WorkDir, "%s || true", joinUnambiguously(cmdArgs))
2863 return false
2864 }
2865
2866
2867 compilerID, cacheOK := b.gccCompilerID(compiler[0])
2868
2869 b.exec.Lock()
2870 defer b.exec.Unlock()
2871 if b, ok := b.flagCache[key]; ok {
2872 return b
2873 }
2874 if b.flagCache == nil {
2875 b.flagCache = make(map[[2]string]bool)
2876 }
2877
2878
2879 var flagID cache.ActionID
2880 if cacheOK {
2881 flagID = cache.Subkey(compilerID, "gccSupportsFlag "+flag)
2882 if data, _, err := cache.GetBytes(cache.Default(), flagID); err == nil {
2883 supported := string(data) == "true"
2884 b.flagCache[key] = supported
2885 return supported
2886 }
2887 }
2888
2889 if cfg.BuildX {
2890 sh.ShowCmd(b.WorkDir, "%s || true", joinUnambiguously(cmdArgs))
2891 }
2892 cmd := exec.Command(cmdArgs[0], cmdArgs[1:]...)
2893 cmd.Dir = b.WorkDir
2894 cmd.Env = append(cmd.Environ(), "LC_ALL=C")
2895 out, _ := cmd.CombinedOutput()
2896
2897
2898
2899
2900
2901
2902 supported := !bytes.Contains(out, []byte("unrecognized")) &&
2903 !bytes.Contains(out, []byte("unknown")) &&
2904 !bytes.Contains(out, []byte("unrecognised")) &&
2905 !bytes.Contains(out, []byte("is not supported")) &&
2906 !bytes.Contains(out, []byte("not recognized")) &&
2907 !bytes.Contains(out, []byte("unsupported"))
2908
2909 if cacheOK {
2910 s := "false"
2911 if supported {
2912 s = "true"
2913 }
2914 cache.PutBytes(cache.Default(), flagID, []byte(s))
2915 }
2916
2917 b.flagCache[key] = supported
2918 return supported
2919 }
2920
2921
2922 func statString(info os.FileInfo) string {
2923 return fmt.Sprintf("stat %d %x %v %v\n", info.Size(), uint64(info.Mode()), info.ModTime(), info.IsDir())
2924 }
2925
2926
2927
2928
2929
2930
2931 func (b *Builder) gccCompilerID(compiler string) (id cache.ActionID, ok bool) {
2932
2933
2934
2935 sh := b.BackgroundShell()
2936
2937 if cfg.BuildN {
2938 sh.ShowCmd(b.WorkDir, "%s || true", joinUnambiguously([]string{compiler, "--version"}))
2939 return cache.ActionID{}, false
2940 }
2941
2942 b.exec.Lock()
2943 defer b.exec.Unlock()
2944
2945 if id, ok := b.gccCompilerIDCache[compiler]; ok {
2946 return id, ok
2947 }
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963 exe, err := pathcache.LookPath(compiler)
2964 if err != nil {
2965 return cache.ActionID{}, false
2966 }
2967
2968 h := cache.NewHash("gccCompilerID")
2969 fmt.Fprintf(h, "gccCompilerID %q", exe)
2970 key := h.Sum()
2971 data, _, err := cache.GetBytes(cache.Default(), key)
2972 if err == nil && len(data) > len(id) {
2973 stats := strings.Split(string(data[:len(data)-len(id)]), "\x00")
2974 if len(stats)%2 != 0 {
2975 goto Miss
2976 }
2977 for i := 0; i+2 <= len(stats); i++ {
2978 info, err := os.Stat(stats[i])
2979 if err != nil || statString(info) != stats[i+1] {
2980 goto Miss
2981 }
2982 }
2983 copy(id[:], data[len(data)-len(id):])
2984 return id, true
2985 Miss:
2986 }
2987
2988
2989
2990
2991
2992
2993 toolID, exe2, err := b.gccToolID(compiler, "c")
2994 if err != nil {
2995 return cache.ActionID{}, false
2996 }
2997
2998 exes := []string{exe, exe2}
2999 str.Uniq(&exes)
3000 fmt.Fprintf(h, "gccCompilerID %q %q\n", exes, toolID)
3001 id = h.Sum()
3002
3003 var buf bytes.Buffer
3004 for _, exe := range exes {
3005 if exe == "" {
3006 continue
3007 }
3008 info, err := os.Stat(exe)
3009 if err != nil {
3010 return cache.ActionID{}, false
3011 }
3012 buf.WriteString(exe)
3013 buf.WriteString("\x00")
3014 buf.WriteString(statString(info))
3015 buf.WriteString("\x00")
3016 }
3017 buf.Write(id[:])
3018
3019 cache.PutBytes(cache.Default(), key, buf.Bytes())
3020 if b.gccCompilerIDCache == nil {
3021 b.gccCompilerIDCache = make(map[string]cache.ActionID)
3022 }
3023 b.gccCompilerIDCache[compiler] = id
3024 return id, true
3025 }
3026
3027
3028 func (b *Builder) gccArchArgs() []string {
3029 switch cfg.Goarch {
3030 case "386":
3031 return []string{"-m32"}
3032 case "amd64":
3033 if cfg.Goos == "darwin" {
3034 return []string{"-arch", "x86_64", "-m64"}
3035 }
3036 return []string{"-m64"}
3037 case "arm64":
3038 if cfg.Goos == "darwin" {
3039 return []string{"-arch", "arm64"}
3040 }
3041 case "arm":
3042 return []string{"-marm"}
3043 case "s390x":
3044
3045 return []string{"-m64", "-march=z13"}
3046 case "mips64", "mips64le":
3047 args := []string{"-mabi=64"}
3048 if cfg.GOMIPS64 == "hardfloat" {
3049 return append(args, "-mhard-float")
3050 } else if cfg.GOMIPS64 == "softfloat" {
3051 return append(args, "-msoft-float")
3052 }
3053 case "mips", "mipsle":
3054 args := []string{"-mabi=32", "-march=mips32"}
3055 if cfg.GOMIPS == "hardfloat" {
3056 return append(args, "-mhard-float", "-mfp32", "-mno-odd-spreg")
3057 } else if cfg.GOMIPS == "softfloat" {
3058 return append(args, "-msoft-float")
3059 }
3060 case "loong64":
3061
3062
3063
3064
3065
3066 return []string{"-mabi=lp64d", "-mno-relax"}
3067 case "ppc64":
3068 if cfg.Goos == "aix" {
3069 return []string{"-maix64"}
3070 }
3071 }
3072 return nil
3073 }
3074
3075
3076
3077
3078
3079
3080
3081 func envList(key, def string) []string {
3082 v := cfg.Getenv(key)
3083 if v == "" {
3084 v = def
3085 }
3086 args, err := quoted.Split(v)
3087 if err != nil {
3088 panic(fmt.Sprintf("could not parse environment variable %s with value %q: %v", key, v, err))
3089 }
3090 return args
3091 }
3092
3093
3094 func (b *Builder) CFlags(p *load.Package) (cppflags, cflags, cxxflags, fflags, ldflags []string, err error) {
3095 if cppflags, err = buildFlags("CPPFLAGS", "", p.CgoCPPFLAGS, checkCompilerFlags); err != nil {
3096 return
3097 }
3098 if cflags, err = buildFlags("CFLAGS", DefaultCFlags, p.CgoCFLAGS, checkCompilerFlags); err != nil {
3099 return
3100 }
3101 if cxxflags, err = buildFlags("CXXFLAGS", DefaultCFlags, p.CgoCXXFLAGS, checkCompilerFlags); err != nil {
3102 return
3103 }
3104 if fflags, err = buildFlags("FFLAGS", DefaultCFlags, p.CgoFFLAGS, checkCompilerFlags); err != nil {
3105 return
3106 }
3107 if ldflags, err = buildFlags("LDFLAGS", DefaultCFlags, p.CgoLDFLAGS, checkLinkerFlags); err != nil {
3108 return
3109 }
3110
3111 return
3112 }
3113
3114 func buildFlags(name, defaults string, fromPackage []string, check func(string, string, []string) error) ([]string, error) {
3115 if err := check(name, "#cgo "+name, fromPackage); err != nil {
3116 return nil, err
3117 }
3118 return str.StringList(envList("CGO_"+name, defaults), fromPackage), nil
3119 }
3120
3121 var cgoRe = lazyregexp.New(`[/\\:]`)
3122
3123 type runCgoProvider struct {
3124 CFLAGS, CXXFLAGS, FFLAGS, LDFLAGS []string
3125 notCompatibleForInternalLinking bool
3126 nonGoOverlay map[string]string
3127 goFiles []string
3128 }
3129
3130 func (pr *runCgoProvider) cflags() []string {
3131 return pr.CFLAGS
3132 }
3133
3134 func (pr *runCgoProvider) cxxflags() []string {
3135 return pr.CXXFLAGS
3136 }
3137
3138 func (pr *runCgoProvider) fflags() []string {
3139 return pr.FFLAGS
3140 }
3141
3142 func (pr *runCgoProvider) ldflags() []string {
3143 return pr.LDFLAGS
3144 }
3145
3146 func mustGetCoverInfo(a *Action) *coverProvider {
3147 for _, dep := range a.Deps {
3148 if dep.Mode == "cover" {
3149 return dep.Provider.(*coverProvider)
3150 }
3151 }
3152 base.Fatalf("internal error: cover provider not found")
3153 panic("unreachable")
3154 }
3155
3156 func (b *Builder) runCgo(_ context.Context, a *Action) error {
3157 p := a.Package
3158 sh := b.Shell(a)
3159 objdir := a.Objdir
3160
3161 if err := sh.Mkdir(objdir); err != nil {
3162 return err
3163 }
3164
3165 nonGoFileLists := [][]string{p.CFiles, p.SFiles, p.CXXFiles, p.HFiles, p.FFiles}
3166 if err := b.computeNonGoOverlay(a, p, sh, objdir, nonGoFileLists); err != nil {
3167 return err
3168 }
3169
3170 a.actionID = b.cgoRunActionID(a)
3171 if pr, err := b.loadCachedRunCgoOutputs(a); err == nil {
3172 pr.nonGoOverlay = a.nonGoOverlay
3173 a.Provider = pr
3174 return nil
3175 }
3176
3177 cgofiles := slices.Clip(p.CgoFiles)
3178 if a.Package.Internal.Cover.Mode != "" {
3179 cp := mustGetCoverInfo(a)
3180 cgofiles = cp.cgoSources
3181 }
3182
3183 pcCFLAGS, pcLDFLAGS, err := b.getPkgConfigFlags(a, p)
3184 if err != nil {
3185 return err
3186 }
3187
3188
3189
3190
3191
3192
3193
3194 if p.UsesSwig() {
3195 if err := b.swig(a, objdir, pcCFLAGS); err != nil {
3196 return err
3197 }
3198 outGo, _, _ := b.swigOutputs(p, objdir)
3199 cgofiles = append(cgofiles, outGo...)
3200 }
3201
3202 cgoExe := base.Tool("cgo")
3203 cgofiles = mkAbsFiles(p.Dir, cgofiles)
3204
3205 cgoCPPFLAGS, cgoCFLAGS, cgoCXXFLAGS, cgoFFLAGS, cgoLDFLAGS, err := b.CFlags(p)
3206 if err != nil {
3207 return err
3208 }
3209
3210 cgoCPPFLAGS = append(cgoCPPFLAGS, pcCFLAGS...)
3211 cgoLDFLAGS = append(cgoLDFLAGS, pcLDFLAGS...)
3212
3213 if len(p.MFiles) > 0 {
3214 cgoLDFLAGS = append(cgoLDFLAGS, "-lobjc")
3215 }
3216
3217
3218
3219
3220 if len(p.FFiles) > 0 {
3221 fc := cfg.Getenv("FC")
3222 if fc == "" {
3223 fc = "gfortran"
3224 }
3225 if strings.Contains(fc, "gfortran") {
3226 cgoLDFLAGS = append(cgoLDFLAGS, "-lgfortran")
3227 }
3228 }
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245 flagSources := []string{"CGO_CFLAGS", "CGO_CXXFLAGS", "CGO_FFLAGS"}
3246 flagLists := [][]string{cgoCFLAGS, cgoCXXFLAGS, cgoFFLAGS}
3247 notCompatibleWithInternalLinking := flagsNotCompatibleWithInternalLinking(flagSources, flagLists)
3248 if !notCompatibleWithInternalLinking {
3249 if err := checkLinkerFlagsForInternalLink("CGO_LDFLAGS", "CGO_LDFLAGS", cgoLDFLAGS); err != nil {
3250 notCompatibleWithInternalLinking = true
3251 }
3252 }
3253
3254 if cfg.BuildMSan {
3255 cgoCFLAGS = append([]string{"-fsanitize=memory"}, cgoCFLAGS...)
3256 cgoLDFLAGS = append([]string{"-fsanitize=memory"}, cgoLDFLAGS...)
3257 }
3258 if cfg.BuildASan {
3259 cgoCFLAGS = append([]string{"-fsanitize=address"}, cgoCFLAGS...)
3260 cgoLDFLAGS = append([]string{"-fsanitize=address"}, cgoLDFLAGS...)
3261 }
3262
3263
3264
3265 cgoCPPFLAGS = append(cgoCPPFLAGS, "-I", objdir)
3266
3267
3268
3269 gofiles := []string{objdir + "_cgo_gotypes.go"}
3270 cfiles := []string{objdir + "_cgo_export.c"}
3271 for _, fn := range cgofiles {
3272 f := strings.TrimSuffix(filepath.Base(fn), ".go")
3273 gofiles = append(gofiles, objdir+f+".cgo1.go")
3274 cfiles = append(cfiles, objdir+f+".cgo2.c")
3275 }
3276
3277
3278
3279 cgoflags := []string{}
3280 if p.Standard && p.ImportPath == "runtime/cgo" {
3281 cgoflags = append(cgoflags, "-import_runtime_cgo=false")
3282 }
3283 if p.Standard && (p.ImportPath == "runtime/race" || p.ImportPath == "runtime/msan" || p.ImportPath == "runtime/cgo" || p.ImportPath == "runtime/asan") {
3284 cgoflags = append(cgoflags, "-import_syscall=false")
3285 }
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297 cgoenv := b.cCompilerEnv()
3298 cgoenv = append(cgoenv, cfgChangedEnv...)
3299 var ldflagsOption []string
3300 if len(cgoLDFLAGS) > 0 {
3301 flags := make([]string, len(cgoLDFLAGS))
3302 for i, f := range cgoLDFLAGS {
3303 flags[i] = strconv.Quote(f)
3304 }
3305 ldflagsOption = []string{"-ldflags=" + strings.Join(flags, " ")}
3306
3307
3308 cgoenv = append(cgoenv, "CGO_LDFLAGS=")
3309 }
3310
3311 if cfg.BuildToolchainName == "gccgo" {
3312 if b.gccSupportsFlag([]string{BuildToolchain.compiler()}, "-fsplit-stack") {
3313 cgoCFLAGS = append(cgoCFLAGS, "-fsplit-stack")
3314 }
3315 cgoflags = append(cgoflags, "-gccgo")
3316 if pkgpath := gccgoPkgpath(p); pkgpath != "" {
3317 cgoflags = append(cgoflags, "-gccgopkgpath="+pkgpath)
3318 }
3319 if !BuildToolchain.(gccgoToolchain).supportsCgoIncomplete(b, a) {
3320 cgoflags = append(cgoflags, "-gccgo_define_cgoincomplete")
3321 }
3322 }
3323
3324 switch cfg.BuildBuildmode {
3325 case "c-archive", "c-shared":
3326
3327
3328
3329 cgoflags = append(cgoflags, "-exportheader="+objdir+"_cgo_install.h")
3330 }
3331
3332
3333
3334 var trimpath []string
3335 for i := range cgofiles {
3336 path := mkAbs(p.Dir, cgofiles[i])
3337 if fsys.Replaced(path) {
3338 actual := fsys.Actual(path)
3339 cgofiles[i] = actual
3340 trimpath = append(trimpath, actual+"=>"+path)
3341 }
3342 }
3343 if len(trimpath) > 0 {
3344 cgoflags = append(cgoflags, "-trimpath", strings.Join(trimpath, ";"))
3345 }
3346
3347 if err := sh.run(p.Dir, p.ImportPath, cgoenv, cfg.BuildToolexec, cgoExe, "-objdir", objdir, "-importpath", p.ImportPath, cgoflags, ldflagsOption, "--", cgoCPPFLAGS, cgoCFLAGS, cgofiles); err != nil {
3348 return err
3349 }
3350
3351 a.Provider = &runCgoProvider{
3352 CFLAGS: str.StringList(cgoCPPFLAGS, cgoCFLAGS),
3353 CXXFLAGS: str.StringList(cgoCPPFLAGS, cgoCXXFLAGS),
3354 FFLAGS: str.StringList(cgoCPPFLAGS, cgoFFLAGS),
3355 LDFLAGS: cgoLDFLAGS,
3356 notCompatibleForInternalLinking: notCompatibleWithInternalLinking,
3357 nonGoOverlay: a.nonGoOverlay,
3358 goFiles: gofiles,
3359 }
3360
3361 if !cfg.BuildN {
3362 pr := a.Provider.(*runCgoProvider)
3363 if err := b.cacheRunCgoOutputs(a, pr); err != nil {
3364 return err
3365 }
3366 }
3367
3368 return nil
3369 }
3370
3371 func (b *Builder) processCgoOutputs(a *Action, runCgoProvider *runCgoProvider, cgoExe, objdir string) (outGo, outObj []string, err error) {
3372 outGo = slices.Clip(runCgoProvider.goFiles)
3373
3374
3375
3376
3377
3378
3379
3380
3381 sh := b.Shell(a)
3382
3383
3384
3385 if runCgoProvider.notCompatibleForInternalLinking {
3386 tokenFile := objdir + "preferlinkext"
3387 if err := sh.writeFile(tokenFile, nil); err != nil {
3388 return nil, nil, err
3389 }
3390 outObj = append(outObj, tokenFile)
3391 }
3392
3393 var collectAction *Action
3394 for _, dep := range a.Deps {
3395 if dep.Mode == "collect cgo" {
3396 collectAction = dep
3397 }
3398 }
3399 if collectAction == nil {
3400 base.Fatalf("internal error: no cgo collect action")
3401 }
3402 for _, dep := range collectAction.Deps {
3403 outObj = append(outObj, dep.Target)
3404 }
3405
3406 switch cfg.BuildToolchainName {
3407 case "gc":
3408 importGo := objdir + "_cgo_import.go"
3409 dynOutGo, dynOutObj, err := b.dynimport(a, objdir, importGo, cgoExe, runCgoProvider.CFLAGS, runCgoProvider.LDFLAGS, outObj)
3410 if err != nil {
3411 return nil, nil, err
3412 }
3413 if dynOutGo != "" {
3414 outGo = append(outGo, dynOutGo)
3415 }
3416 if dynOutObj != "" {
3417 outObj = append(outObj, dynOutObj)
3418 }
3419
3420 case "gccgo":
3421 defunC := objdir + "_cgo_defun.c"
3422 defunObj := objdir + "_cgo_defun.o"
3423 if err := BuildToolchain.cc(b, a, defunObj, defunC); err != nil {
3424 return nil, nil, err
3425 }
3426 outObj = append(outObj, defunObj)
3427
3428 default:
3429 noCompiler()
3430 }
3431
3432
3433
3434
3435
3436
3437 if cfg.BuildToolchainName == "gc" && !cfg.BuildN {
3438 var flags []string
3439 for _, f := range outGo {
3440 if !strings.HasPrefix(filepath.Base(f), "_cgo_") {
3441 continue
3442 }
3443
3444 src, err := os.ReadFile(f)
3445 if err != nil {
3446 return nil, nil, err
3447 }
3448
3449 const cgoLdflag = "//go:cgo_ldflag"
3450 idx := bytes.Index(src, []byte(cgoLdflag))
3451 for idx >= 0 {
3452
3453
3454 start := bytes.LastIndex(src[:idx], []byte("\n"))
3455 if start == -1 {
3456 start = 0
3457 }
3458
3459
3460 end := bytes.Index(src[idx:], []byte("\n"))
3461 if end == -1 {
3462 end = len(src)
3463 } else {
3464 end += idx
3465 }
3466
3467
3468
3469
3470
3471 commentStart := bytes.Index(src[start:], []byte("//"))
3472 commentStart += start
3473
3474
3475 if bytes.HasPrefix(src[commentStart:], []byte(cgoLdflag)) {
3476
3477
3478 flag := string(src[idx+len(cgoLdflag) : end])
3479 flag = strings.TrimSpace(flag)
3480 flag = strings.Trim(flag, `"`)
3481 flags = append(flags, flag)
3482 }
3483 src = src[end:]
3484 idx = bytes.Index(src, []byte(cgoLdflag))
3485 }
3486 }
3487
3488
3489 if len(runCgoProvider.LDFLAGS) > 0 {
3490 outer:
3491 for i := range flags {
3492 for j, f := range runCgoProvider.LDFLAGS {
3493 if f != flags[i+j] {
3494 continue outer
3495 }
3496 }
3497 flags = append(flags[:i], flags[i+len(runCgoProvider.LDFLAGS):]...)
3498 break
3499 }
3500 }
3501
3502 if err := checkLinkerFlags("LDFLAGS", "go:cgo_ldflag", flags); err != nil {
3503 return nil, nil, err
3504 }
3505 }
3506
3507 return outGo, outObj, nil
3508 }
3509
3510
3511
3512
3513
3514
3515
3516
3517 func flagsNotCompatibleWithInternalLinking(sourceList []string, flagListList [][]string) bool {
3518 for i := range sourceList {
3519 sn := sourceList[i]
3520 fll := flagListList[i]
3521 if err := checkCompilerFlagsForInternalLink(sn, sn, fll); err != nil {
3522 return true
3523 }
3524 }
3525 return false
3526 }
3527
3528
3529
3530
3531
3532
3533 func (b *Builder) dynimport(a *Action, objdir, importGo, cgoExe string, cflags, cgoLDFLAGS, outObj []string) (dynOutGo, dynOutObj string, err error) {
3534 p := a.Package
3535 sh := b.Shell(a)
3536
3537 cfile := objdir + "_cgo_main.c"
3538 ofile := objdir + "_cgo_main.o"
3539 if err := b.gcc(a, objdir, ofile, cflags, cfile); err != nil {
3540 return "", "", err
3541 }
3542
3543
3544 var syso []string
3545 seen := make(map[*Action]bool)
3546 var gatherSyso func(*Action)
3547 gatherSyso = func(a1 *Action) {
3548 if seen[a1] {
3549 return
3550 }
3551 seen[a1] = true
3552 if p1 := a1.Package; p1 != nil {
3553 syso = append(syso, mkAbsFiles(p1.Dir, p1.SysoFiles)...)
3554 }
3555 for _, a2 := range a1.Deps {
3556 gatherSyso(a2)
3557 }
3558 }
3559 gatherSyso(a)
3560 sort.Strings(syso)
3561 str.Uniq(&syso)
3562 linkobj := str.StringList(ofile, outObj, syso)
3563 dynobj := objdir + "_cgo_.o"
3564
3565 ldflags := cgoLDFLAGS
3566 if (cfg.Goarch == "arm" && cfg.Goos == "linux") || cfg.Goos == "android" {
3567 if !slices.Contains(ldflags, "-no-pie") {
3568
3569
3570 ldflags = append(ldflags, "-pie")
3571 }
3572 if slices.Contains(ldflags, "-pie") && slices.Contains(ldflags, "-static") {
3573
3574
3575 n := make([]string, 0, len(ldflags)-1)
3576 for _, flag := range ldflags {
3577 if flag != "-static" {
3578 n = append(n, flag)
3579 }
3580 }
3581 ldflags = n
3582 }
3583 }
3584 if err := b.gccld(a, objdir, dynobj, ldflags, linkobj); err != nil {
3585
3586
3587
3588
3589
3590
3591 fail := objdir + "dynimportfail"
3592 if err := sh.writeFile(fail, nil); err != nil {
3593 return "", "", err
3594 }
3595 return "", fail, nil
3596 }
3597
3598
3599 var cgoflags []string
3600 if p.Standard && p.ImportPath == "runtime/cgo" {
3601 cgoflags = []string{"-dynlinker"}
3602 }
3603 err = sh.run(base.Cwd(), p.ImportPath, b.cCompilerEnv(), cfg.BuildToolexec, cgoExe, "-dynpackage", p.Name, "-dynimport", dynobj, "-dynout", importGo, cgoflags)
3604 if err != nil {
3605 return "", "", err
3606 }
3607 return importGo, "", nil
3608 }
3609
3610
3611
3612
3613 func (b *Builder) swig(a *Action, objdir string, pcCFLAGS []string) error {
3614 p := a.Package
3615
3616 if err := b.swigVersionCheck(); err != nil {
3617 return err
3618 }
3619
3620 intgosize, err := b.swigIntSize(objdir)
3621 if err != nil {
3622 return err
3623 }
3624
3625 for _, f := range p.SwigFiles {
3626 if err := b.swigOne(a, f, objdir, pcCFLAGS, false, intgosize); err != nil {
3627 return err
3628 }
3629 }
3630 for _, f := range p.SwigCXXFiles {
3631 if err := b.swigOne(a, f, objdir, pcCFLAGS, true, intgosize); err != nil {
3632 return err
3633 }
3634 }
3635 return nil
3636 }
3637
3638 func (b *Builder) swigOutputs(p *load.Package, objdir string) (outGo, outC, outCXX []string) {
3639 for _, f := range p.SwigFiles {
3640 goFile, cFile := swigOneOutputs(f, objdir, false)
3641 outGo = append(outGo, goFile)
3642 outC = append(outC, cFile)
3643 }
3644 for _, f := range p.SwigCXXFiles {
3645 goFile, cxxFile := swigOneOutputs(f, objdir, true)
3646 outGo = append(outGo, goFile)
3647 outCXX = append(outCXX, cxxFile)
3648 }
3649 return outGo, outC, outCXX
3650 }
3651
3652
3653 var (
3654 swigCheckOnce sync.Once
3655 swigCheck error
3656 )
3657
3658 func (b *Builder) swigDoVersionCheck() error {
3659 sh := b.BackgroundShell()
3660 out, err := sh.runOut(".", nil, "swig", "-version")
3661 if err != nil {
3662 return err
3663 }
3664 re := regexp.MustCompile(`[vV]ersion +(\d+)([.]\d+)?([.]\d+)?`)
3665 matches := re.FindSubmatch(out)
3666 if matches == nil {
3667
3668 return nil
3669 }
3670
3671 major, err := strconv.Atoi(string(matches[1]))
3672 if err != nil {
3673
3674 return nil
3675 }
3676 const errmsg = "must have SWIG version >= 3.0.6"
3677 if major < 3 {
3678 return errors.New(errmsg)
3679 }
3680 if major > 3 {
3681
3682 return nil
3683 }
3684
3685
3686 if len(matches[2]) > 0 {
3687 minor, err := strconv.Atoi(string(matches[2][1:]))
3688 if err != nil {
3689 return nil
3690 }
3691 if minor > 0 {
3692
3693 return nil
3694 }
3695 }
3696
3697
3698 if len(matches[3]) > 0 {
3699 patch, err := strconv.Atoi(string(matches[3][1:]))
3700 if err != nil {
3701 return nil
3702 }
3703 if patch < 6 {
3704
3705 return errors.New(errmsg)
3706 }
3707 }
3708
3709 return nil
3710 }
3711
3712 func (b *Builder) swigVersionCheck() error {
3713 swigCheckOnce.Do(func() {
3714 swigCheck = b.swigDoVersionCheck()
3715 })
3716 return swigCheck
3717 }
3718
3719
3720 var (
3721 swigIntSizeOnce sync.Once
3722 swigIntSize string
3723 swigIntSizeError error
3724 )
3725
3726
3727 const swigIntSizeCode = `
3728 package main
3729 const i int = 1 << 32
3730 `
3731
3732
3733
3734 func (b *Builder) swigDoIntSize(objdir string) (intsize string, err error) {
3735 if cfg.BuildN {
3736 return "$INTBITS", nil
3737 }
3738 src := filepath.Join(b.WorkDir, "swig_intsize.go")
3739 if err = os.WriteFile(src, []byte(swigIntSizeCode), 0666); err != nil {
3740 return
3741 }
3742 srcs := []string{src}
3743
3744 p := load.GoFilesPackage(modload.NewLoader(), context.TODO(), load.PackageOpts{}, srcs)
3745
3746 if _, _, e := BuildToolchain.gc(b, &Action{Mode: "swigDoIntSize", Package: p, Objdir: objdir}, "", nil, nil, "", false, "", "", srcs); e != nil {
3747 return "32", nil
3748 }
3749 return "64", nil
3750 }
3751
3752
3753
3754 func (b *Builder) swigIntSize(objdir string) (intsize string, err error) {
3755 swigIntSizeOnce.Do(func() {
3756 swigIntSize, swigIntSizeError = b.swigDoIntSize(objdir)
3757 })
3758 return swigIntSize, swigIntSizeError
3759 }
3760
3761
3762 func (b *Builder) swigOne(a *Action, file, objdir string, pcCFLAGS []string, cxx bool, intgosize string) error {
3763 if strings.HasPrefix(file, "cgo") {
3764 return errors.New("SWIG file must not use prefix 'cgo'")
3765 }
3766
3767 p := a.Package
3768 sh := b.Shell(a)
3769
3770 cgoCPPFLAGS, cgoCFLAGS, cgoCXXFLAGS, _, _, err := b.CFlags(p)
3771 if err != nil {
3772 return err
3773 }
3774
3775 var cflags []string
3776 if cxx {
3777 cflags = str.StringList(cgoCPPFLAGS, pcCFLAGS, cgoCXXFLAGS)
3778 } else {
3779 cflags = str.StringList(cgoCPPFLAGS, pcCFLAGS, cgoCFLAGS)
3780 }
3781
3782 base := swigBase(file, cxx)
3783 newGoFile, outC := swigOneOutputs(file, objdir, cxx)
3784
3785 gccgo := cfg.BuildToolchainName == "gccgo"
3786
3787
3788 args := []string{
3789 "-go",
3790 "-cgo",
3791 "-intgosize", intgosize,
3792 "-module", base,
3793 "-o", outC,
3794 "-outdir", objdir,
3795 }
3796
3797 for _, f := range cflags {
3798 if len(f) > 3 && f[:2] == "-I" {
3799 args = append(args, f)
3800 }
3801 }
3802
3803 if gccgo {
3804 args = append(args, "-gccgo")
3805 if pkgpath := gccgoPkgpath(p); pkgpath != "" {
3806 args = append(args, "-go-pkgpath", pkgpath)
3807 }
3808 }
3809 if cxx {
3810 args = append(args, "-c++")
3811 }
3812
3813 out, err := sh.runOut(p.Dir, nil, "swig", args, file)
3814 if err != nil && (bytes.Contains(out, []byte("-intgosize")) || bytes.Contains(out, []byte("-cgo"))) {
3815 return errors.New("must have SWIG version >= 3.0.6")
3816 }
3817 if err := sh.reportCmd("", "", out, err); err != nil {
3818 return err
3819 }
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829 goFile := objdir + base + ".go"
3830 if cfg.BuildX || cfg.BuildN {
3831 sh.ShowCmd("", "mv %s %s", goFile, newGoFile)
3832 }
3833 if !cfg.BuildN {
3834 if err := os.Rename(goFile, newGoFile); err != nil {
3835 return err
3836 }
3837 }
3838
3839 return nil
3840 }
3841
3842 func swigBase(file string, cxx bool) string {
3843 n := 5
3844 if cxx {
3845 n = 8
3846 }
3847 return file[:len(file)-n]
3848 }
3849
3850 func swigOneOutputs(file, objdir string, cxx bool) (outGo, outC string) {
3851 base := swigBase(file, cxx)
3852 gccBase := base + "_wrap."
3853 gccExt := "c"
3854 if cxx {
3855 gccExt = "cxx"
3856 }
3857
3858 newGoFile := objdir + "_" + base + "_swig.go"
3859 cFile := objdir + gccBase + gccExt
3860 return newGoFile, cFile
3861 }
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873 func (b *Builder) disableBuildID(ldflags []string) []string {
3874 switch cfg.Goos {
3875 case "android", "dragonfly", "linux", "netbsd":
3876 ldflags = append(ldflags, "-Wl,--build-id=none")
3877 }
3878 return ldflags
3879 }
3880
3881
3882
3883
3884 func mkAbsFiles(dir string, files []string) []string {
3885 abs := make([]string, len(files))
3886 for i, f := range files {
3887 if !filepath.IsAbs(f) {
3888 f = filepath.Join(dir, f)
3889 }
3890 abs[i] = f
3891 }
3892 return abs
3893 }
3894
3895
3896 func actualFiles(files []string) []string {
3897 a := make([]string, len(files))
3898 for i, f := range files {
3899 a[i] = fsys.Actual(f)
3900 }
3901 return a
3902 }
3903
3904
3905
3906
3907
3908
3909
3910
3911 func passLongArgsInResponseFiles(cmd *exec.Cmd) (cleanup func()) {
3912 cleanup = func() {}
3913
3914 var argLen int
3915 for _, arg := range cmd.Args {
3916 argLen += len(arg)
3917 }
3918
3919
3920
3921 if !useResponseFile(cmd.Path, argLen) {
3922 return
3923 }
3924
3925 tf, err := os.CreateTemp("", "args")
3926 if err != nil {
3927 log.Fatalf("error writing long arguments to response file: %v", err)
3928 }
3929 cleanup = func() { os.Remove(tf.Name()) }
3930 var buf bytes.Buffer
3931 for _, arg := range cmd.Args[1:] {
3932 fmt.Fprintf(&buf, "%s\n", encodeArg(arg))
3933 }
3934 if _, err := tf.Write(buf.Bytes()); err != nil {
3935 tf.Close()
3936 cleanup()
3937 log.Fatalf("error writing long arguments to response file: %v", err)
3938 }
3939 if err := tf.Close(); err != nil {
3940 cleanup()
3941 log.Fatalf("error writing long arguments to response file: %v", err)
3942 }
3943 cmd.Args = []string{cmd.Args[0], "@" + tf.Name()}
3944 return cleanup
3945 }
3946
3947 func useResponseFile(path string, argLen int) bool {
3948
3949
3950
3951 prog := strings.TrimSuffix(filepath.Base(path), ".exe")
3952 switch prog {
3953 case "compile", "link", "cgo", "asm", "cover", "pack":
3954 default:
3955 return false
3956 }
3957
3958 if argLen > sys.ExecArgLengthLimit {
3959 return true
3960 }
3961
3962
3963
3964 isBuilder := os.Getenv("GO_BUILDER_NAME") != ""
3965 if isBuilder && rand.Intn(10) == 0 {
3966 return true
3967 }
3968
3969 return false
3970 }
3971
3972
3973
3974 func encodeArg(arg string) string {
3975
3976 if arg == "" {
3977 return `""`
3978 }
3979
3980 if !strings.ContainsAny(arg, " \t\n\r'\"\\$`") {
3981 return arg
3982 }
3983
3984
3985 var b strings.Builder
3986 b.WriteByte('"')
3987 for _, r := range arg {
3988 switch r {
3989 case '\\':
3990 b.WriteString(`\\`)
3991 case '"':
3992 b.WriteString(`\"`)
3993 case '$':
3994 b.WriteString(`\$`)
3995 case '`':
3996 b.WriteString("\\`")
3997 default:
3998 b.WriteRune(r)
3999 }
4000 }
4001 b.WriteByte('"')
4002 return b.String()
4003 }
4004
View as plain text