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