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