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
1640 if err := checkPkgConfigFlags("", "pkg-config", pcflags); err != nil {
1641 return nil, nil, err
1642 }
1643
1644 var out []byte
1645 out, err = sh.runOut(p.Dir, nil, b.PkgconfigCmd(), "--cflags", pcflags, "--", pkgs)
1646 if err != nil {
1647 desc := b.PkgconfigCmd() + " --cflags " + strings.Join(pcflags, " ") + " -- " + strings.Join(pkgs, " ")
1648 return nil, nil, sh.reportCmd(desc, "", out, err)
1649 }
1650 if len(out) > 0 {
1651 cflags, err = splitPkgConfigOutput(bytes.TrimSpace(out))
1652 if err != nil {
1653 return nil, nil, err
1654 }
1655 if err := checkCompilerFlags("CFLAGS", "pkg-config --cflags", cflags); err != nil {
1656 return nil, nil, err
1657 }
1658 }
1659 out, err = sh.runOut(p.Dir, nil, b.PkgconfigCmd(), "--libs", pcflags, "--", pkgs)
1660 if err != nil {
1661 desc := b.PkgconfigCmd() + " --libs " + strings.Join(pcflags, " ") + " -- " + strings.Join(pkgs, " ")
1662 return nil, nil, sh.reportCmd(desc, "", out, err)
1663 }
1664 if len(out) > 0 {
1665
1666
1667 ldflags, err = splitPkgConfigOutput(bytes.TrimSpace(out))
1668 if err != nil {
1669 return nil, nil, err
1670 }
1671 if err := checkLinkerFlags("LDFLAGS", "pkg-config --libs", ldflags); err != nil {
1672 return nil, nil, err
1673 }
1674 }
1675 }
1676
1677 return
1678 }
1679
1680 func (b *Builder) installShlibname(ctx context.Context, a *Action) error {
1681 if err := AllowInstall(a); err != nil {
1682 return err
1683 }
1684
1685 sh := b.Shell(a)
1686 a1 := a.Deps[0]
1687 if !cfg.BuildN {
1688 if err := sh.Mkdir(filepath.Dir(a.Target)); err != nil {
1689 return err
1690 }
1691 }
1692 return sh.writeFile(a.Target, []byte(filepath.Base(a1.Target)+"\n"))
1693 }
1694
1695 func (b *Builder) linkSharedActionID(a *Action) cache.ActionID {
1696 h := cache.NewHash("linkShared")
1697
1698
1699 fmt.Fprintf(h, "linkShared\n")
1700 fmt.Fprintf(h, "goos %s goarch %s\n", cfg.Goos, cfg.Goarch)
1701
1702
1703 b.printLinkerConfig(h, nil)
1704
1705
1706 for _, a1 := range a.Deps {
1707 p1 := a1.Package
1708 if a1.built == "" {
1709 continue
1710 }
1711 if p1 != nil {
1712 fmt.Fprintf(h, "packagefile %s=%s\n", p1.ImportPath, contentID(b.buildID(a1.built)))
1713 if p1.Shlib != "" {
1714 fmt.Fprintf(h, "packageshlib %s=%s\n", p1.ImportPath, contentID(b.buildID(p1.Shlib)))
1715 }
1716 }
1717 }
1718
1719 for _, a1 := range a.Deps[0].Deps {
1720 p1 := a1.Package
1721 fmt.Fprintf(h, "top %s=%s\n", p1.ImportPath, contentID(b.buildID(a1.built)))
1722 }
1723
1724 return h.Sum()
1725 }
1726
1727 func (b *Builder) linkShared(ctx context.Context, a *Action) (err error) {
1728 if b.useCache(a, b.linkSharedActionID(a), a.Target, !b.IsCmdList) || b.IsCmdList {
1729 return nil
1730 }
1731 defer b.flushOutput(a)
1732
1733 if err := AllowInstall(a); err != nil {
1734 return err
1735 }
1736
1737 if err := b.Shell(a).Mkdir(a.Objdir); err != nil {
1738 return err
1739 }
1740
1741 importcfg := a.Objdir + "importcfg.link"
1742 if err := b.writeLinkImportcfg(a, importcfg); err != nil {
1743 return err
1744 }
1745
1746
1747
1748 a.built = a.Target
1749 return BuildToolchain.ldShared(b, a, a.Deps[0].Deps, a.Target, importcfg, a.Deps)
1750 }
1751
1752
1753 func BuildInstallFunc(b *Builder, ctx context.Context, a *Action) (err error) {
1754 defer func() {
1755 if err != nil {
1756
1757
1758
1759 sep, path := "", ""
1760 if a.Package != nil {
1761 sep, path = " ", a.Package.ImportPath
1762 }
1763 err = fmt.Errorf("go %s%s%s: %v", cfg.CmdName, sep, path, err)
1764 }
1765 }()
1766 sh := b.Shell(a)
1767
1768 a1 := a.Deps[0]
1769 a.buildID = a1.buildID
1770 if a.json != nil {
1771 a.json.BuildID = a.buildID
1772 }
1773
1774
1775
1776
1777
1778
1779 if a1.built == a.Target {
1780 a.built = a.Target
1781 if !a.buggyInstall {
1782 b.cleanup(a1)
1783 }
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802 if !a.buggyInstall && !b.IsCmdList {
1803 if cfg.BuildN {
1804 sh.ShowCmd("", "touch %s", a.Target)
1805 } else if err := AllowInstall(a); err == nil {
1806 now := time.Now()
1807 os.Chtimes(a.Target, now, now)
1808 }
1809 }
1810 return nil
1811 }
1812
1813
1814
1815 if b.IsCmdList {
1816 a.built = a1.built
1817 return nil
1818 }
1819 if err := AllowInstall(a); err != nil {
1820 return err
1821 }
1822
1823 if err := sh.Mkdir(a.Objdir); err != nil {
1824 return err
1825 }
1826
1827 perm := fs.FileMode(0666)
1828 if a1.Mode == "link" {
1829 switch cfg.BuildBuildmode {
1830 case "c-archive", "c-shared", "plugin":
1831 default:
1832 perm = 0777
1833 }
1834 }
1835
1836
1837 dir, _ := filepath.Split(a.Target)
1838 if dir != "" {
1839 if err := sh.Mkdir(dir); err != nil {
1840 return err
1841 }
1842 }
1843
1844 if !a.buggyInstall {
1845 defer b.cleanup(a1)
1846 }
1847
1848 return sh.moveOrCopyFile(a.Target, a1.built, perm, false)
1849 }
1850
1851
1852
1853
1854
1855
1856 var AllowInstall = func(*Action) error { return nil }
1857
1858
1859
1860
1861
1862 func (b *Builder) cleanup(a *Action) {
1863 if !cfg.BuildWork {
1864 b.Shell(a).RemoveAll(a.Objdir)
1865 }
1866 }
1867
1868
1869 func (b *Builder) installHeader(ctx context.Context, a *Action) error {
1870 sh := b.Shell(a)
1871
1872 src := a.Objdir + "_cgo_install.h"
1873 if _, err := os.Stat(src); os.IsNotExist(err) {
1874
1875
1876
1877
1878
1879 if cfg.BuildX {
1880 sh.ShowCmd("", "# %s not created", src)
1881 }
1882 return nil
1883 }
1884
1885 if err := AllowInstall(a); err != nil {
1886 return err
1887 }
1888
1889 dir, _ := filepath.Split(a.Target)
1890 if dir != "" {
1891 if err := sh.Mkdir(dir); err != nil {
1892 return err
1893 }
1894 }
1895
1896 return sh.moveOrCopyFile(a.Target, src, 0666, true)
1897 }
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907 func (b *Builder) cover(a *Action, infiles, outfiles []string, varName string, mode string) ([]string, error) {
1908 pkgcfg := a.Objdir + "pkgcfg.txt"
1909 covoutputs := a.Objdir + "coveroutfiles.txt"
1910 odir := filepath.Dir(outfiles[0])
1911 cv := filepath.Join(odir, "covervars.go")
1912 outfiles = append([]string{cv}, outfiles...)
1913 if err := b.writeCoverPkgInputs(a, pkgcfg, covoutputs, outfiles); err != nil {
1914 return nil, err
1915 }
1916 args := []string{base.Tool("cover"),
1917 "-pkgcfg", pkgcfg,
1918 "-mode", mode,
1919 "-var", varName,
1920 "-outfilelist", covoutputs,
1921 }
1922 args = append(args, infiles...)
1923 if err := b.Shell(a).run(a.Objdir, "", nil,
1924 cfg.BuildToolexec, args); err != nil {
1925 return nil, err
1926 }
1927 return outfiles, nil
1928 }
1929
1930 func (b *Builder) writeCoverPkgInputs(a *Action, pconfigfile string, covoutputsfile string, outfiles []string) error {
1931 sh := b.Shell(a)
1932 p := a.Package
1933 p.Internal.Cover.Cfg = a.Objdir + "coveragecfg"
1934 pcfg := covcmd.CoverPkgConfig{
1935 PkgPath: p.ImportPath,
1936 PkgName: p.Name,
1937
1938
1939
1940
1941 Granularity: "perblock",
1942 OutConfig: p.Internal.Cover.Cfg,
1943 Local: p.Internal.Local,
1944 }
1945 if ba, ok := a.Actor.(*buildActor); ok && ba.covMetaFileName != "" {
1946 pcfg.EmitMetaFile = a.Objdir + ba.covMetaFileName
1947 }
1948 if a.Package.Module != nil {
1949 pcfg.ModulePath = a.Package.Module.Path
1950 }
1951 data, err := json.Marshal(pcfg)
1952 if err != nil {
1953 return err
1954 }
1955 data = append(data, '\n')
1956 if err := sh.writeFile(pconfigfile, data); err != nil {
1957 return err
1958 }
1959 var sb strings.Builder
1960 for i := range outfiles {
1961 fmt.Fprintf(&sb, "%s\n", outfiles[i])
1962 }
1963 return sh.writeFile(covoutputsfile, []byte(sb.String()))
1964 }
1965
1966 var objectMagic = [][]byte{
1967 {'!', '<', 'a', 'r', 'c', 'h', '>', '\n'},
1968 {'<', 'b', 'i', 'g', 'a', 'f', '>', '\n'},
1969 {'\x7F', 'E', 'L', 'F'},
1970 {0xFE, 0xED, 0xFA, 0xCE},
1971 {0xFE, 0xED, 0xFA, 0xCF},
1972 {0xCE, 0xFA, 0xED, 0xFE},
1973 {0xCF, 0xFA, 0xED, 0xFE},
1974 {0x4d, 0x5a, 0x90, 0x00, 0x03, 0x00},
1975 {0x4d, 0x5a, 0x78, 0x00, 0x01, 0x00},
1976 {0x00, 0x00, 0x01, 0xEB},
1977 {0x00, 0x00, 0x8a, 0x97},
1978 {0x00, 0x00, 0x06, 0x47},
1979 {0x00, 0x61, 0x73, 0x6D},
1980 {0x01, 0xDF},
1981 {0x01, 0xF7},
1982 }
1983
1984 func isObject(s string) bool {
1985 f, err := os.Open(s)
1986 if err != nil {
1987 return false
1988 }
1989 defer f.Close()
1990 buf := make([]byte, 64)
1991 io.ReadFull(f, buf)
1992 for _, magic := range objectMagic {
1993 if bytes.HasPrefix(buf, magic) {
1994 return true
1995 }
1996 }
1997 return false
1998 }
1999
2000
2001
2002
2003 func (b *Builder) cCompilerEnv() []string {
2004 return []string{"TERM=dumb"}
2005 }
2006
2007
2008
2009
2010
2011
2012 func mkAbs(dir, f string) string {
2013
2014
2015
2016
2017 if filepath.IsAbs(f) || strings.HasPrefix(f, "$WORK") {
2018 return f
2019 }
2020 return filepath.Join(dir, f)
2021 }
2022
2023 type toolchain interface {
2024
2025
2026 gc(b *Builder, a *Action, archive string, importcfg, embedcfg []byte, symabis string, asmhdr bool, pgoProfile string, gofiles []string) (ofile string, out []byte, err error)
2027
2028
2029 cc(b *Builder, a *Action, ofile, cfile string) error
2030
2031
2032 asm(b *Builder, a *Action, sfiles []string) ([]string, error)
2033
2034
2035 symabis(b *Builder, a *Action, sfiles []string) (string, error)
2036
2037
2038
2039 pack(b *Builder, a *Action, afile string, ofiles []string) error
2040
2041 ld(b *Builder, root *Action, targetPath, importcfg, mainpkg string) error
2042
2043 ldShared(b *Builder, root *Action, toplevelactions []*Action, targetPath, importcfg string, allactions []*Action) error
2044
2045 compiler() string
2046 linker() string
2047 }
2048
2049 type noToolchain struct{}
2050
2051 func noCompiler() error {
2052 log.Fatalf("unknown compiler %q", cfg.BuildContext.Compiler)
2053 return nil
2054 }
2055
2056 func (noToolchain) compiler() string {
2057 noCompiler()
2058 return ""
2059 }
2060
2061 func (noToolchain) linker() string {
2062 noCompiler()
2063 return ""
2064 }
2065
2066 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) {
2067 return "", nil, noCompiler()
2068 }
2069
2070 func (noToolchain) asm(b *Builder, a *Action, sfiles []string) ([]string, error) {
2071 return nil, noCompiler()
2072 }
2073
2074 func (noToolchain) symabis(b *Builder, a *Action, sfiles []string) (string, error) {
2075 return "", noCompiler()
2076 }
2077
2078 func (noToolchain) pack(b *Builder, a *Action, afile string, ofiles []string) error {
2079 return noCompiler()
2080 }
2081
2082 func (noToolchain) ld(b *Builder, root *Action, targetPath, importcfg, mainpkg string) error {
2083 return noCompiler()
2084 }
2085
2086 func (noToolchain) ldShared(b *Builder, root *Action, toplevelactions []*Action, targetPath, importcfg string, allactions []*Action) error {
2087 return noCompiler()
2088 }
2089
2090 func (noToolchain) cc(b *Builder, a *Action, ofile, cfile string) error {
2091 return noCompiler()
2092 }
2093
2094
2095 func (b *Builder) gcc(a *Action, workdir, out string, flags []string, cfile string) error {
2096 p := a.Package
2097 return b.ccompile(a, out, flags, cfile, b.GccCmd(p.Dir, workdir))
2098 }
2099
2100
2101 func (b *Builder) gxx(a *Action, workdir, out string, flags []string, cxxfile string) error {
2102 p := a.Package
2103 return b.ccompile(a, out, flags, cxxfile, b.GxxCmd(p.Dir, workdir))
2104 }
2105
2106
2107 func (b *Builder) gfortran(a *Action, workdir, out string, flags []string, ffile string) error {
2108 p := a.Package
2109 return b.ccompile(a, out, flags, ffile, b.gfortranCmd(p.Dir, workdir))
2110 }
2111
2112
2113 func (b *Builder) ccompile(a *Action, outfile string, flags []string, file string, compiler []string) error {
2114 p := a.Package
2115 sh := b.Shell(a)
2116 file = mkAbs(p.Dir, file)
2117 outfile = mkAbs(p.Dir, outfile)
2118
2119
2120
2121
2122
2123
2124 if b.gccSupportsFlag(compiler, "-fdebug-prefix-map=a=b") {
2125 if cfg.BuildTrimpath || p.Goroot {
2126 prefixMapFlag := "-fdebug-prefix-map"
2127 if b.gccSupportsFlag(compiler, "-ffile-prefix-map=a=b") {
2128 prefixMapFlag = "-ffile-prefix-map"
2129 }
2130
2131
2132
2133 var from, toPath string
2134 if m := p.Module; m == nil {
2135 if p.Root == "" {
2136 from = p.Dir
2137 toPath = p.ImportPath
2138 } else if p.Goroot {
2139 from = p.Root
2140 toPath = "GOROOT"
2141 } else {
2142 from = p.Root
2143 toPath = "GOPATH"
2144 }
2145 } else if m.Dir == "" {
2146
2147
2148 from = modload.VendorDir()
2149 toPath = "vendor"
2150 } else {
2151 from = m.Dir
2152 toPath = m.Path
2153 if m.Version != "" {
2154 toPath += "@" + m.Version
2155 }
2156 }
2157
2158
2159
2160 var to string
2161 if cfg.BuildContext.GOOS == "windows" {
2162 to = filepath.Join(`\\_\_`, toPath)
2163 } else {
2164 to = filepath.Join("/_", toPath)
2165 }
2166 flags = append(slices.Clip(flags), prefixMapFlag+"="+from+"="+to)
2167 }
2168 }
2169
2170
2171
2172 if b.gccSupportsFlag(compiler, "-frandom-seed=1") {
2173 flags = append(flags, "-frandom-seed="+buildid.HashToString(a.actionID))
2174 }
2175
2176 overlayPath := file
2177 if p, ok := a.nonGoOverlay[overlayPath]; ok {
2178 overlayPath = p
2179 }
2180 output, err := sh.runOut(filepath.Dir(overlayPath), b.cCompilerEnv(), compiler, flags, "-o", outfile, "-c", filepath.Base(overlayPath))
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190 if bytes.Contains(output, []byte("DWARF2 only supports one section per compilation unit")) {
2191 newFlags := make([]string, 0, len(flags))
2192 for _, f := range flags {
2193 if !strings.HasPrefix(f, "-g") {
2194 newFlags = append(newFlags, f)
2195 }
2196 }
2197 if len(newFlags) < len(flags) {
2198 return b.ccompile(a, outfile, newFlags, file, compiler)
2199 }
2200 }
2201
2202 if len(output) > 0 && err == nil && os.Getenv("GO_BUILDER_NAME") != "" {
2203 output = append(output, "C compiler warning promoted to error on Go builders\n"...)
2204 err = errors.New("warning promoted to error")
2205 }
2206
2207 return sh.reportCmd("", "", output, err)
2208 }
2209
2210
2211 func (b *Builder) gccld(a *Action, objdir, outfile string, flags []string, objs []string) error {
2212 p := a.Package
2213 sh := b.Shell(a)
2214 var cmd []string
2215 if len(p.CXXFiles) > 0 || len(p.SwigCXXFiles) > 0 {
2216 cmd = b.GxxCmd(p.Dir, objdir)
2217 } else {
2218 cmd = b.GccCmd(p.Dir, objdir)
2219 }
2220
2221 cmdargs := []any{cmd, "-o", outfile, objs, flags}
2222 _, err := sh.runOut(base.Cwd(), b.cCompilerEnv(), cmdargs...)
2223
2224
2225
2226 if cfg.BuildN || cfg.BuildX {
2227 saw := "succeeded"
2228 if err != nil {
2229 saw = "failed"
2230 }
2231 sh.ShowCmd("", "%s # test for internal linking errors (%s)", joinUnambiguously(str.StringList(cmdargs...)), saw)
2232 }
2233
2234 return err
2235 }
2236
2237
2238
2239 func (b *Builder) GccCmd(incdir, workdir string) []string {
2240 return b.compilerCmd(b.ccExe(), incdir, workdir)
2241 }
2242
2243
2244
2245 func (b *Builder) GxxCmd(incdir, workdir string) []string {
2246 return b.compilerCmd(b.cxxExe(), incdir, workdir)
2247 }
2248
2249
2250 func (b *Builder) gfortranCmd(incdir, workdir string) []string {
2251 return b.compilerCmd(b.fcExe(), incdir, workdir)
2252 }
2253
2254
2255 func (b *Builder) ccExe() []string {
2256 return envList("CC", cfg.DefaultCC(cfg.Goos, cfg.Goarch))
2257 }
2258
2259
2260 func (b *Builder) cxxExe() []string {
2261 return envList("CXX", cfg.DefaultCXX(cfg.Goos, cfg.Goarch))
2262 }
2263
2264
2265 func (b *Builder) fcExe() []string {
2266 return envList("FC", "gfortran")
2267 }
2268
2269
2270
2271 func (b *Builder) compilerCmd(compiler []string, incdir, workdir string) []string {
2272 a := append(compiler, "-I", incdir)
2273
2274
2275
2276 if cfg.Goos != "windows" {
2277 a = append(a, "-fPIC")
2278 }
2279 a = append(a, b.gccArchArgs()...)
2280
2281
2282 if cfg.BuildContext.CgoEnabled {
2283 switch cfg.Goos {
2284 case "windows":
2285 a = append(a, "-mthreads")
2286 default:
2287 a = append(a, "-pthread")
2288 }
2289 }
2290
2291 if cfg.Goos == "aix" {
2292
2293 a = append(a, "-mcmodel=large")
2294 }
2295
2296
2297 if b.gccSupportsFlag(compiler, "-fno-caret-diagnostics") {
2298 a = append(a, "-fno-caret-diagnostics")
2299 }
2300
2301 if b.gccSupportsFlag(compiler, "-Qunused-arguments") {
2302 a = append(a, "-Qunused-arguments")
2303 }
2304
2305
2306
2307
2308 if b.gccSupportsFlag(compiler, "-Wl,--no-gc-sections") {
2309 a = append(a, "-Wl,--no-gc-sections")
2310 }
2311
2312
2313 a = append(a, "-fmessage-length=0")
2314
2315
2316 if b.gccSupportsFlag(compiler, "-fdebug-prefix-map=a=b") {
2317 if workdir == "" {
2318 workdir = b.WorkDir
2319 }
2320 workdir = strings.TrimSuffix(workdir, string(filepath.Separator))
2321 if b.gccSupportsFlag(compiler, "-ffile-prefix-map=a=b") {
2322 a = append(a, "-ffile-prefix-map="+workdir+"=/tmp/go-build")
2323 } else {
2324 a = append(a, "-fdebug-prefix-map="+workdir+"=/tmp/go-build")
2325 }
2326 }
2327
2328
2329
2330 if b.gccSupportsFlag(compiler, "-gno-record-gcc-switches") {
2331 a = append(a, "-gno-record-gcc-switches")
2332 }
2333
2334
2335
2336
2337 if cfg.Goos == "darwin" || cfg.Goos == "ios" {
2338 a = append(a, "-fno-common")
2339 }
2340
2341 return a
2342 }
2343
2344
2345
2346
2347
2348 func (b *Builder) gccNoPie(linker []string) string {
2349 if b.gccSupportsFlag(linker, "-no-pie") {
2350 return "-no-pie"
2351 }
2352 if b.gccSupportsFlag(linker, "-nopie") {
2353 return "-nopie"
2354 }
2355 return ""
2356 }
2357
2358
2359 func (b *Builder) gccSupportsFlag(compiler []string, flag string) bool {
2360
2361
2362
2363 sh := b.BackgroundShell()
2364
2365 key := [2]string{compiler[0], flag}
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383 tmp := os.DevNull
2384 if runtime.GOOS == "windows" || runtime.GOOS == "ios" {
2385 f, err := os.CreateTemp(b.WorkDir, "")
2386 if err != nil {
2387 return false
2388 }
2389 f.Close()
2390 tmp = f.Name()
2391 defer os.Remove(tmp)
2392 }
2393
2394 cmdArgs := str.StringList(compiler, flag)
2395 if strings.HasPrefix(flag, "-Wl,") {
2396 ldflags, err := buildFlags("LDFLAGS", DefaultCFlags, nil, checkLinkerFlags)
2397 if err != nil {
2398 return false
2399 }
2400 cmdArgs = append(cmdArgs, ldflags...)
2401 } else {
2402 cflags, err := buildFlags("CFLAGS", DefaultCFlags, nil, checkCompilerFlags)
2403 if err != nil {
2404 return false
2405 }
2406 cmdArgs = append(cmdArgs, cflags...)
2407 cmdArgs = append(cmdArgs, "-c")
2408 }
2409
2410 cmdArgs = append(cmdArgs, "-x", "c", "-", "-o", tmp)
2411
2412 if cfg.BuildN {
2413 sh.ShowCmd(b.WorkDir, "%s || true", joinUnambiguously(cmdArgs))
2414 return false
2415 }
2416
2417
2418 compilerID, cacheOK := b.gccCompilerID(compiler[0])
2419
2420 b.exec.Lock()
2421 defer b.exec.Unlock()
2422 if b, ok := b.flagCache[key]; ok {
2423 return b
2424 }
2425 if b.flagCache == nil {
2426 b.flagCache = make(map[[2]string]bool)
2427 }
2428
2429
2430 var flagID cache.ActionID
2431 if cacheOK {
2432 flagID = cache.Subkey(compilerID, "gccSupportsFlag "+flag)
2433 if data, _, err := cache.GetBytes(cache.Default(), flagID); err == nil {
2434 supported := string(data) == "true"
2435 b.flagCache[key] = supported
2436 return supported
2437 }
2438 }
2439
2440 if cfg.BuildX {
2441 sh.ShowCmd(b.WorkDir, "%s || true", joinUnambiguously(cmdArgs))
2442 }
2443 cmd := exec.Command(cmdArgs[0], cmdArgs[1:]...)
2444 cmd.Dir = b.WorkDir
2445 cmd.Env = append(cmd.Environ(), "LC_ALL=C")
2446 out, _ := cmd.CombinedOutput()
2447
2448
2449
2450
2451
2452
2453 supported := !bytes.Contains(out, []byte("unrecognized")) &&
2454 !bytes.Contains(out, []byte("unknown")) &&
2455 !bytes.Contains(out, []byte("unrecognised")) &&
2456 !bytes.Contains(out, []byte("is not supported")) &&
2457 !bytes.Contains(out, []byte("not recognized")) &&
2458 !bytes.Contains(out, []byte("unsupported"))
2459
2460 if cacheOK {
2461 s := "false"
2462 if supported {
2463 s = "true"
2464 }
2465 cache.PutBytes(cache.Default(), flagID, []byte(s))
2466 }
2467
2468 b.flagCache[key] = supported
2469 return supported
2470 }
2471
2472
2473 func statString(info os.FileInfo) string {
2474 return fmt.Sprintf("stat %d %x %v %v\n", info.Size(), uint64(info.Mode()), info.ModTime(), info.IsDir())
2475 }
2476
2477
2478
2479
2480
2481
2482 func (b *Builder) gccCompilerID(compiler string) (id cache.ActionID, ok bool) {
2483
2484
2485
2486 sh := b.BackgroundShell()
2487
2488 if cfg.BuildN {
2489 sh.ShowCmd(b.WorkDir, "%s || true", joinUnambiguously([]string{compiler, "--version"}))
2490 return cache.ActionID{}, false
2491 }
2492
2493 b.exec.Lock()
2494 defer b.exec.Unlock()
2495
2496 if id, ok := b.gccCompilerIDCache[compiler]; ok {
2497 return id, ok
2498 }
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514 exe, err := pathcache.LookPath(compiler)
2515 if err != nil {
2516 return cache.ActionID{}, false
2517 }
2518
2519 h := cache.NewHash("gccCompilerID")
2520 fmt.Fprintf(h, "gccCompilerID %q", exe)
2521 key := h.Sum()
2522 data, _, err := cache.GetBytes(cache.Default(), key)
2523 if err == nil && len(data) > len(id) {
2524 stats := strings.Split(string(data[:len(data)-len(id)]), "\x00")
2525 if len(stats)%2 != 0 {
2526 goto Miss
2527 }
2528 for i := 0; i+2 <= len(stats); i++ {
2529 info, err := os.Stat(stats[i])
2530 if err != nil || statString(info) != stats[i+1] {
2531 goto Miss
2532 }
2533 }
2534 copy(id[:], data[len(data)-len(id):])
2535 return id, true
2536 Miss:
2537 }
2538
2539
2540
2541
2542
2543
2544 toolID, exe2, err := b.gccToolID(compiler, "c")
2545 if err != nil {
2546 return cache.ActionID{}, false
2547 }
2548
2549 exes := []string{exe, exe2}
2550 str.Uniq(&exes)
2551 fmt.Fprintf(h, "gccCompilerID %q %q\n", exes, toolID)
2552 id = h.Sum()
2553
2554 var buf bytes.Buffer
2555 for _, exe := range exes {
2556 if exe == "" {
2557 continue
2558 }
2559 info, err := os.Stat(exe)
2560 if err != nil {
2561 return cache.ActionID{}, false
2562 }
2563 buf.WriteString(exe)
2564 buf.WriteString("\x00")
2565 buf.WriteString(statString(info))
2566 buf.WriteString("\x00")
2567 }
2568 buf.Write(id[:])
2569
2570 cache.PutBytes(cache.Default(), key, buf.Bytes())
2571 if b.gccCompilerIDCache == nil {
2572 b.gccCompilerIDCache = make(map[string]cache.ActionID)
2573 }
2574 b.gccCompilerIDCache[compiler] = id
2575 return id, true
2576 }
2577
2578
2579 func (b *Builder) gccArchArgs() []string {
2580 switch cfg.Goarch {
2581 case "386":
2582 return []string{"-m32"}
2583 case "amd64":
2584 if cfg.Goos == "darwin" {
2585 return []string{"-arch", "x86_64", "-m64"}
2586 }
2587 return []string{"-m64"}
2588 case "arm64":
2589 if cfg.Goos == "darwin" {
2590 return []string{"-arch", "arm64"}
2591 }
2592 case "arm":
2593 return []string{"-marm"}
2594 case "s390x":
2595
2596 return []string{"-m64", "-march=z13"}
2597 case "mips64", "mips64le":
2598 args := []string{"-mabi=64"}
2599 if cfg.GOMIPS64 == "hardfloat" {
2600 return append(args, "-mhard-float")
2601 } else if cfg.GOMIPS64 == "softfloat" {
2602 return append(args, "-msoft-float")
2603 }
2604 case "mips", "mipsle":
2605 args := []string{"-mabi=32", "-march=mips32"}
2606 if cfg.GOMIPS == "hardfloat" {
2607 return append(args, "-mhard-float", "-mfp32", "-mno-odd-spreg")
2608 } else if cfg.GOMIPS == "softfloat" {
2609 return append(args, "-msoft-float")
2610 }
2611 case "loong64":
2612 return []string{"-mabi=lp64d"}
2613 case "ppc64":
2614 if cfg.Goos == "aix" {
2615 return []string{"-maix64"}
2616 }
2617 }
2618 return nil
2619 }
2620
2621
2622
2623
2624
2625
2626
2627 func envList(key, def string) []string {
2628 v := cfg.Getenv(key)
2629 if v == "" {
2630 v = def
2631 }
2632 args, err := quoted.Split(v)
2633 if err != nil {
2634 panic(fmt.Sprintf("could not parse environment variable %s with value %q: %v", key, v, err))
2635 }
2636 return args
2637 }
2638
2639
2640 func (b *Builder) CFlags(p *load.Package) (cppflags, cflags, cxxflags, fflags, ldflags []string, err error) {
2641 if cppflags, err = buildFlags("CPPFLAGS", "", p.CgoCPPFLAGS, checkCompilerFlags); err != nil {
2642 return
2643 }
2644 if cflags, err = buildFlags("CFLAGS", DefaultCFlags, p.CgoCFLAGS, checkCompilerFlags); err != nil {
2645 return
2646 }
2647 if cxxflags, err = buildFlags("CXXFLAGS", DefaultCFlags, p.CgoCXXFLAGS, checkCompilerFlags); err != nil {
2648 return
2649 }
2650 if fflags, err = buildFlags("FFLAGS", DefaultCFlags, p.CgoFFLAGS, checkCompilerFlags); err != nil {
2651 return
2652 }
2653 if ldflags, err = buildFlags("LDFLAGS", DefaultCFlags, p.CgoLDFLAGS, checkLinkerFlags); err != nil {
2654 return
2655 }
2656
2657 return
2658 }
2659
2660 func buildFlags(name, defaults string, fromPackage []string, check func(string, string, []string) error) ([]string, error) {
2661 if err := check(name, "#cgo "+name, fromPackage); err != nil {
2662 return nil, err
2663 }
2664 return str.StringList(envList("CGO_"+name, defaults), fromPackage), nil
2665 }
2666
2667 var cgoRe = lazyregexp.New(`[/\\:]`)
2668
2669 func (b *Builder) cgo(a *Action, cgoExe, objdir string, pcCFLAGS, pcLDFLAGS, cgofiles, gccfiles, gxxfiles, mfiles, ffiles []string) (outGo, outObj []string, err error) {
2670 p := a.Package
2671 sh := b.Shell(a)
2672
2673 cgoCPPFLAGS, cgoCFLAGS, cgoCXXFLAGS, cgoFFLAGS, cgoLDFLAGS, err := b.CFlags(p)
2674 if err != nil {
2675 return nil, nil, err
2676 }
2677
2678 cgoCPPFLAGS = append(cgoCPPFLAGS, pcCFLAGS...)
2679 cgoLDFLAGS = append(cgoLDFLAGS, pcLDFLAGS...)
2680
2681 if len(mfiles) > 0 {
2682 cgoLDFLAGS = append(cgoLDFLAGS, "-lobjc")
2683 }
2684
2685
2686
2687
2688 if len(ffiles) > 0 {
2689 fc := cfg.Getenv("FC")
2690 if fc == "" {
2691 fc = "gfortran"
2692 }
2693 if strings.Contains(fc, "gfortran") {
2694 cgoLDFLAGS = append(cgoLDFLAGS, "-lgfortran")
2695 }
2696 }
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713 flagSources := []string{"CGO_CFLAGS", "CGO_CXXFLAGS", "CGO_FFLAGS"}
2714 flagLists := [][]string{cgoCFLAGS, cgoCXXFLAGS, cgoFFLAGS}
2715 if flagsNotCompatibleWithInternalLinking(flagSources, flagLists) {
2716 tokenFile := objdir + "preferlinkext"
2717 if err := sh.writeFile(tokenFile, nil); err != nil {
2718 return nil, nil, err
2719 }
2720 outObj = append(outObj, tokenFile)
2721 }
2722
2723 if cfg.BuildMSan {
2724 cgoCFLAGS = append([]string{"-fsanitize=memory"}, cgoCFLAGS...)
2725 cgoLDFLAGS = append([]string{"-fsanitize=memory"}, cgoLDFLAGS...)
2726 }
2727 if cfg.BuildASan {
2728 cgoCFLAGS = append([]string{"-fsanitize=address"}, cgoCFLAGS...)
2729 cgoLDFLAGS = append([]string{"-fsanitize=address"}, cgoLDFLAGS...)
2730 }
2731
2732
2733
2734 cgoCPPFLAGS = append(cgoCPPFLAGS, "-I", objdir)
2735
2736
2737
2738 gofiles := []string{objdir + "_cgo_gotypes.go"}
2739 cfiles := []string{"_cgo_export.c"}
2740 for _, fn := range cgofiles {
2741 f := strings.TrimSuffix(filepath.Base(fn), ".go")
2742 gofiles = append(gofiles, objdir+f+".cgo1.go")
2743 cfiles = append(cfiles, f+".cgo2.c")
2744 }
2745
2746
2747
2748 cgoflags := []string{}
2749 if p.Standard && p.ImportPath == "runtime/cgo" {
2750 cgoflags = append(cgoflags, "-import_runtime_cgo=false")
2751 }
2752 if p.Standard && (p.ImportPath == "runtime/race" || p.ImportPath == "runtime/msan" || p.ImportPath == "runtime/cgo" || p.ImportPath == "runtime/asan") {
2753 cgoflags = append(cgoflags, "-import_syscall=false")
2754 }
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766 cgoenv := b.cCompilerEnv()
2767 cgoenv = append(cgoenv, cfgChangedEnv...)
2768 var ldflagsOption []string
2769 if len(cgoLDFLAGS) > 0 {
2770 flags := make([]string, len(cgoLDFLAGS))
2771 for i, f := range cgoLDFLAGS {
2772 flags[i] = strconv.Quote(f)
2773 }
2774 ldflagsOption = []string{"-ldflags=" + strings.Join(flags, " ")}
2775
2776
2777 cgoenv = append(cgoenv, "CGO_LDFLAGS=")
2778 }
2779
2780 if cfg.BuildToolchainName == "gccgo" {
2781 if b.gccSupportsFlag([]string{BuildToolchain.compiler()}, "-fsplit-stack") {
2782 cgoCFLAGS = append(cgoCFLAGS, "-fsplit-stack")
2783 }
2784 cgoflags = append(cgoflags, "-gccgo")
2785 if pkgpath := gccgoPkgpath(p); pkgpath != "" {
2786 cgoflags = append(cgoflags, "-gccgopkgpath="+pkgpath)
2787 }
2788 if !BuildToolchain.(gccgoToolchain).supportsCgoIncomplete(b, a) {
2789 cgoflags = append(cgoflags, "-gccgo_define_cgoincomplete")
2790 }
2791 }
2792
2793 switch cfg.BuildBuildmode {
2794 case "c-archive", "c-shared":
2795
2796
2797
2798 cgoflags = append(cgoflags, "-exportheader="+objdir+"_cgo_install.h")
2799 }
2800
2801
2802
2803 var trimpath []string
2804 for i := range cgofiles {
2805 path := mkAbs(p.Dir, cgofiles[i])
2806 if fsys.Replaced(path) {
2807 actual := fsys.Actual(path)
2808 cgofiles[i] = actual
2809 trimpath = append(trimpath, actual+"=>"+path)
2810 }
2811 }
2812 if len(trimpath) > 0 {
2813 cgoflags = append(cgoflags, "-trimpath", strings.Join(trimpath, ";"))
2814 }
2815
2816 if err := sh.run(p.Dir, p.ImportPath, cgoenv, cfg.BuildToolexec, cgoExe, "-objdir", objdir, "-importpath", p.ImportPath, cgoflags, ldflagsOption, "--", cgoCPPFLAGS, cgoCFLAGS, cgofiles); err != nil {
2817 return nil, nil, err
2818 }
2819 outGo = append(outGo, gofiles...)
2820
2821
2822
2823
2824
2825
2826
2827 oseq := 0
2828 nextOfile := func() string {
2829 oseq++
2830 return objdir + fmt.Sprintf("_x%03d.o", oseq)
2831 }
2832
2833
2834 cflags := str.StringList(cgoCPPFLAGS, cgoCFLAGS)
2835 for _, cfile := range cfiles {
2836 ofile := nextOfile()
2837 if err := b.gcc(a, a.Objdir, ofile, cflags, objdir+cfile); err != nil {
2838 return nil, nil, err
2839 }
2840 outObj = append(outObj, ofile)
2841 }
2842
2843 for _, file := range gccfiles {
2844 ofile := nextOfile()
2845 if err := b.gcc(a, a.Objdir, ofile, cflags, file); err != nil {
2846 return nil, nil, err
2847 }
2848 outObj = append(outObj, ofile)
2849 }
2850
2851 cxxflags := str.StringList(cgoCPPFLAGS, cgoCXXFLAGS)
2852 for _, file := range gxxfiles {
2853 ofile := nextOfile()
2854 if err := b.gxx(a, a.Objdir, ofile, cxxflags, file); err != nil {
2855 return nil, nil, err
2856 }
2857 outObj = append(outObj, ofile)
2858 }
2859
2860 for _, file := range mfiles {
2861 ofile := nextOfile()
2862 if err := b.gcc(a, a.Objdir, ofile, cflags, file); err != nil {
2863 return nil, nil, err
2864 }
2865 outObj = append(outObj, ofile)
2866 }
2867
2868 fflags := str.StringList(cgoCPPFLAGS, cgoFFLAGS)
2869 for _, file := range ffiles {
2870 ofile := nextOfile()
2871 if err := b.gfortran(a, a.Objdir, ofile, fflags, file); err != nil {
2872 return nil, nil, err
2873 }
2874 outObj = append(outObj, ofile)
2875 }
2876
2877 switch cfg.BuildToolchainName {
2878 case "gc":
2879 importGo := objdir + "_cgo_import.go"
2880 dynOutGo, dynOutObj, err := b.dynimport(a, objdir, importGo, cgoExe, cflags, cgoLDFLAGS, outObj)
2881 if err != nil {
2882 return nil, nil, err
2883 }
2884 if dynOutGo != "" {
2885 outGo = append(outGo, dynOutGo)
2886 }
2887 if dynOutObj != "" {
2888 outObj = append(outObj, dynOutObj)
2889 }
2890
2891 case "gccgo":
2892 defunC := objdir + "_cgo_defun.c"
2893 defunObj := objdir + "_cgo_defun.o"
2894 if err := BuildToolchain.cc(b, a, defunObj, defunC); err != nil {
2895 return nil, nil, err
2896 }
2897 outObj = append(outObj, defunObj)
2898
2899 default:
2900 noCompiler()
2901 }
2902
2903
2904
2905
2906
2907
2908 if cfg.BuildToolchainName == "gc" && !cfg.BuildN {
2909 var flags []string
2910 for _, f := range outGo {
2911 if !strings.HasPrefix(filepath.Base(f), "_cgo_") {
2912 continue
2913 }
2914
2915 src, err := os.ReadFile(f)
2916 if err != nil {
2917 return nil, nil, err
2918 }
2919
2920 const cgoLdflag = "//go:cgo_ldflag"
2921 idx := bytes.Index(src, []byte(cgoLdflag))
2922 for idx >= 0 {
2923
2924
2925 start := bytes.LastIndex(src[:idx], []byte("\n"))
2926 if start == -1 {
2927 start = 0
2928 }
2929
2930
2931 end := bytes.Index(src[idx:], []byte("\n"))
2932 if end == -1 {
2933 end = len(src)
2934 } else {
2935 end += idx
2936 }
2937
2938
2939
2940
2941
2942 commentStart := bytes.Index(src[start:], []byte("//"))
2943 commentStart += start
2944
2945
2946 if bytes.HasPrefix(src[commentStart:], []byte(cgoLdflag)) {
2947
2948
2949 flag := string(src[idx+len(cgoLdflag) : end])
2950 flag = strings.TrimSpace(flag)
2951 flag = strings.Trim(flag, `"`)
2952 flags = append(flags, flag)
2953 }
2954 src = src[end:]
2955 idx = bytes.Index(src, []byte(cgoLdflag))
2956 }
2957 }
2958
2959
2960 if len(cgoLDFLAGS) > 0 {
2961 outer:
2962 for i := range flags {
2963 for j, f := range cgoLDFLAGS {
2964 if f != flags[i+j] {
2965 continue outer
2966 }
2967 }
2968 flags = append(flags[:i], flags[i+len(cgoLDFLAGS):]...)
2969 break
2970 }
2971 }
2972
2973 if err := checkLinkerFlags("LDFLAGS", "go:cgo_ldflag", flags); err != nil {
2974 return nil, nil, err
2975 }
2976 }
2977
2978 return outGo, outObj, nil
2979 }
2980
2981
2982
2983
2984
2985
2986
2987
2988 func flagsNotCompatibleWithInternalLinking(sourceList []string, flagListList [][]string) bool {
2989 for i := range sourceList {
2990 sn := sourceList[i]
2991 fll := flagListList[i]
2992 if err := checkCompilerFlagsForInternalLink(sn, sn, fll); err != nil {
2993 return true
2994 }
2995 }
2996 return false
2997 }
2998
2999
3000
3001
3002
3003
3004 func (b *Builder) dynimport(a *Action, objdir, importGo, cgoExe string, cflags, cgoLDFLAGS, outObj []string) (dynOutGo, dynOutObj string, err error) {
3005 p := a.Package
3006 sh := b.Shell(a)
3007
3008 cfile := objdir + "_cgo_main.c"
3009 ofile := objdir + "_cgo_main.o"
3010 if err := b.gcc(a, objdir, ofile, cflags, cfile); err != nil {
3011 return "", "", err
3012 }
3013
3014
3015 var syso []string
3016 seen := make(map[*Action]bool)
3017 var gatherSyso func(*Action)
3018 gatherSyso = func(a1 *Action) {
3019 if seen[a1] {
3020 return
3021 }
3022 seen[a1] = true
3023 if p1 := a1.Package; p1 != nil {
3024 syso = append(syso, mkAbsFiles(p1.Dir, p1.SysoFiles)...)
3025 }
3026 for _, a2 := range a1.Deps {
3027 gatherSyso(a2)
3028 }
3029 }
3030 gatherSyso(a)
3031 sort.Strings(syso)
3032 str.Uniq(&syso)
3033 linkobj := str.StringList(ofile, outObj, syso)
3034 dynobj := objdir + "_cgo_.o"
3035
3036 ldflags := cgoLDFLAGS
3037 if (cfg.Goarch == "arm" && cfg.Goos == "linux") || cfg.Goos == "android" {
3038 if !slices.Contains(ldflags, "-no-pie") {
3039
3040
3041 ldflags = append(ldflags, "-pie")
3042 }
3043 if slices.Contains(ldflags, "-pie") && slices.Contains(ldflags, "-static") {
3044
3045
3046 n := make([]string, 0, len(ldflags)-1)
3047 for _, flag := range ldflags {
3048 if flag != "-static" {
3049 n = append(n, flag)
3050 }
3051 }
3052 ldflags = n
3053 }
3054 }
3055 if err := b.gccld(a, objdir, dynobj, ldflags, linkobj); err != nil {
3056
3057
3058
3059
3060
3061
3062 fail := objdir + "dynimportfail"
3063 if err := sh.writeFile(fail, nil); err != nil {
3064 return "", "", err
3065 }
3066 return "", fail, nil
3067 }
3068
3069
3070 var cgoflags []string
3071 if p.Standard && p.ImportPath == "runtime/cgo" {
3072 cgoflags = []string{"-dynlinker"}
3073 }
3074 err = sh.run(base.Cwd(), p.ImportPath, b.cCompilerEnv(), cfg.BuildToolexec, cgoExe, "-dynpackage", p.Name, "-dynimport", dynobj, "-dynout", importGo, cgoflags)
3075 if err != nil {
3076 return "", "", err
3077 }
3078 return importGo, "", nil
3079 }
3080
3081
3082
3083
3084 func (b *Builder) swig(a *Action, objdir string, pcCFLAGS []string) (outGo, outC, outCXX []string, err error) {
3085 p := a.Package
3086
3087 if err := b.swigVersionCheck(); err != nil {
3088 return nil, nil, nil, err
3089 }
3090
3091 intgosize, err := b.swigIntSize(objdir)
3092 if err != nil {
3093 return nil, nil, nil, err
3094 }
3095
3096 for _, f := range p.SwigFiles {
3097 goFile, cFile, err := b.swigOne(a, f, objdir, pcCFLAGS, false, intgosize)
3098 if err != nil {
3099 return nil, nil, nil, err
3100 }
3101 if goFile != "" {
3102 outGo = append(outGo, goFile)
3103 }
3104 if cFile != "" {
3105 outC = append(outC, cFile)
3106 }
3107 }
3108 for _, f := range p.SwigCXXFiles {
3109 goFile, cxxFile, err := b.swigOne(a, f, objdir, pcCFLAGS, true, intgosize)
3110 if err != nil {
3111 return nil, nil, nil, err
3112 }
3113 if goFile != "" {
3114 outGo = append(outGo, goFile)
3115 }
3116 if cxxFile != "" {
3117 outCXX = append(outCXX, cxxFile)
3118 }
3119 }
3120 return outGo, outC, outCXX, nil
3121 }
3122
3123
3124 var (
3125 swigCheckOnce sync.Once
3126 swigCheck error
3127 )
3128
3129 func (b *Builder) swigDoVersionCheck() error {
3130 sh := b.BackgroundShell()
3131 out, err := sh.runOut(".", nil, "swig", "-version")
3132 if err != nil {
3133 return err
3134 }
3135 re := regexp.MustCompile(`[vV]ersion +(\d+)([.]\d+)?([.]\d+)?`)
3136 matches := re.FindSubmatch(out)
3137 if matches == nil {
3138
3139 return nil
3140 }
3141
3142 major, err := strconv.Atoi(string(matches[1]))
3143 if err != nil {
3144
3145 return nil
3146 }
3147 const errmsg = "must have SWIG version >= 3.0.6"
3148 if major < 3 {
3149 return errors.New(errmsg)
3150 }
3151 if major > 3 {
3152
3153 return nil
3154 }
3155
3156
3157 if len(matches[2]) > 0 {
3158 minor, err := strconv.Atoi(string(matches[2][1:]))
3159 if err != nil {
3160 return nil
3161 }
3162 if minor > 0 {
3163
3164 return nil
3165 }
3166 }
3167
3168
3169 if len(matches[3]) > 0 {
3170 patch, err := strconv.Atoi(string(matches[3][1:]))
3171 if err != nil {
3172 return nil
3173 }
3174 if patch < 6 {
3175
3176 return errors.New(errmsg)
3177 }
3178 }
3179
3180 return nil
3181 }
3182
3183 func (b *Builder) swigVersionCheck() error {
3184 swigCheckOnce.Do(func() {
3185 swigCheck = b.swigDoVersionCheck()
3186 })
3187 return swigCheck
3188 }
3189
3190
3191 var (
3192 swigIntSizeOnce sync.Once
3193 swigIntSize string
3194 swigIntSizeError error
3195 )
3196
3197
3198 const swigIntSizeCode = `
3199 package main
3200 const i int = 1 << 32
3201 `
3202
3203
3204
3205 func (b *Builder) swigDoIntSize(objdir string) (intsize string, err error) {
3206 if cfg.BuildN {
3207 return "$INTBITS", nil
3208 }
3209 src := filepath.Join(b.WorkDir, "swig_intsize.go")
3210 if err = os.WriteFile(src, []byte(swigIntSizeCode), 0666); err != nil {
3211 return
3212 }
3213 srcs := []string{src}
3214
3215 p := load.GoFilesPackage(context.TODO(), load.PackageOpts{}, srcs)
3216
3217 if _, _, e := BuildToolchain.gc(b, &Action{Mode: "swigDoIntSize", Package: p, Objdir: objdir}, "", nil, nil, "", false, "", srcs); e != nil {
3218 return "32", nil
3219 }
3220 return "64", nil
3221 }
3222
3223
3224
3225 func (b *Builder) swigIntSize(objdir string) (intsize string, err error) {
3226 swigIntSizeOnce.Do(func() {
3227 swigIntSize, swigIntSizeError = b.swigDoIntSize(objdir)
3228 })
3229 return swigIntSize, swigIntSizeError
3230 }
3231
3232
3233 func (b *Builder) swigOne(a *Action, file, objdir string, pcCFLAGS []string, cxx bool, intgosize string) (outGo, outC string, err error) {
3234 if strings.HasPrefix(file, "cgo") {
3235 return "", "", errors.New("SWIG file must not use prefix 'cgo'")
3236 }
3237
3238 p := a.Package
3239 sh := b.Shell(a)
3240
3241 cgoCPPFLAGS, cgoCFLAGS, cgoCXXFLAGS, _, _, err := b.CFlags(p)
3242 if err != nil {
3243 return "", "", err
3244 }
3245
3246 var cflags []string
3247 if cxx {
3248 cflags = str.StringList(cgoCPPFLAGS, pcCFLAGS, cgoCXXFLAGS)
3249 } else {
3250 cflags = str.StringList(cgoCPPFLAGS, pcCFLAGS, cgoCFLAGS)
3251 }
3252
3253 n := 5
3254 if cxx {
3255 n = 8
3256 }
3257 base := file[:len(file)-n]
3258 goFile := base + ".go"
3259 gccBase := base + "_wrap."
3260 gccExt := "c"
3261 if cxx {
3262 gccExt = "cxx"
3263 }
3264
3265 gccgo := cfg.BuildToolchainName == "gccgo"
3266
3267
3268 args := []string{
3269 "-go",
3270 "-cgo",
3271 "-intgosize", intgosize,
3272 "-module", base,
3273 "-o", objdir + gccBase + gccExt,
3274 "-outdir", objdir,
3275 }
3276
3277 for _, f := range cflags {
3278 if len(f) > 3 && f[:2] == "-I" {
3279 args = append(args, f)
3280 }
3281 }
3282
3283 if gccgo {
3284 args = append(args, "-gccgo")
3285 if pkgpath := gccgoPkgpath(p); pkgpath != "" {
3286 args = append(args, "-go-pkgpath", pkgpath)
3287 }
3288 }
3289 if cxx {
3290 args = append(args, "-c++")
3291 }
3292
3293 out, err := sh.runOut(p.Dir, nil, "swig", args, file)
3294 if err != nil && (bytes.Contains(out, []byte("-intgosize")) || bytes.Contains(out, []byte("-cgo"))) {
3295 return "", "", errors.New("must have SWIG version >= 3.0.6")
3296 }
3297 if err := sh.reportCmd("", "", out, err); err != nil {
3298 return "", "", err
3299 }
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309 goFile = objdir + goFile
3310 newGoFile := objdir + "_" + base + "_swig.go"
3311 if cfg.BuildX || cfg.BuildN {
3312 sh.ShowCmd("", "mv %s %s", goFile, newGoFile)
3313 }
3314 if !cfg.BuildN {
3315 if err := os.Rename(goFile, newGoFile); err != nil {
3316 return "", "", err
3317 }
3318 }
3319 return newGoFile, objdir + gccBase + gccExt, nil
3320 }
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332 func (b *Builder) disableBuildID(ldflags []string) []string {
3333 switch cfg.Goos {
3334 case "android", "dragonfly", "linux", "netbsd":
3335 ldflags = append(ldflags, "-Wl,--build-id=none")
3336 }
3337 return ldflags
3338 }
3339
3340
3341
3342
3343 func mkAbsFiles(dir string, files []string) []string {
3344 abs := make([]string, len(files))
3345 for i, f := range files {
3346 if !filepath.IsAbs(f) {
3347 f = filepath.Join(dir, f)
3348 }
3349 abs[i] = f
3350 }
3351 return abs
3352 }
3353
3354
3355 func actualFiles(files []string) []string {
3356 a := make([]string, len(files))
3357 for i, f := range files {
3358 a[i] = fsys.Actual(f)
3359 }
3360 return a
3361 }
3362
3363
3364
3365
3366
3367
3368
3369
3370 func passLongArgsInResponseFiles(cmd *exec.Cmd) (cleanup func()) {
3371 cleanup = func() {}
3372
3373 var argLen int
3374 for _, arg := range cmd.Args {
3375 argLen += len(arg)
3376 }
3377
3378
3379
3380 if !useResponseFile(cmd.Path, argLen) {
3381 return
3382 }
3383
3384 tf, err := os.CreateTemp("", "args")
3385 if err != nil {
3386 log.Fatalf("error writing long arguments to response file: %v", err)
3387 }
3388 cleanup = func() { os.Remove(tf.Name()) }
3389 var buf bytes.Buffer
3390 for _, arg := range cmd.Args[1:] {
3391 fmt.Fprintf(&buf, "%s\n", encodeArg(arg))
3392 }
3393 if _, err := tf.Write(buf.Bytes()); err != nil {
3394 tf.Close()
3395 cleanup()
3396 log.Fatalf("error writing long arguments to response file: %v", err)
3397 }
3398 if err := tf.Close(); err != nil {
3399 cleanup()
3400 log.Fatalf("error writing long arguments to response file: %v", err)
3401 }
3402 cmd.Args = []string{cmd.Args[0], "@" + tf.Name()}
3403 return cleanup
3404 }
3405
3406 func useResponseFile(path string, argLen int) bool {
3407
3408
3409
3410 prog := strings.TrimSuffix(filepath.Base(path), ".exe")
3411 switch prog {
3412 case "compile", "link", "cgo", "asm", "cover":
3413 default:
3414 return false
3415 }
3416
3417 if argLen > sys.ExecArgLengthLimit {
3418 return true
3419 }
3420
3421
3422
3423 isBuilder := os.Getenv("GO_BUILDER_NAME") != ""
3424 if isBuilder && rand.Intn(10) == 0 {
3425 return true
3426 }
3427
3428 return false
3429 }
3430
3431
3432 func encodeArg(arg string) string {
3433
3434 if !strings.ContainsAny(arg, "\\\n") {
3435 return arg
3436 }
3437 var b strings.Builder
3438 for _, r := range arg {
3439 switch r {
3440 case '\\':
3441 b.WriteByte('\\')
3442 b.WriteByte('\\')
3443 case '\n':
3444 b.WriteByte('\\')
3445 b.WriteByte('n')
3446 default:
3447 b.WriteRune(r)
3448 }
3449 }
3450 return b.String()
3451 }
3452
View as plain text