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