1
2
3
4
5 package work
6
7 import (
8 "bufio"
9 "fmt"
10 "internal/buildcfg"
11 "internal/platform"
12 "io"
13 "os"
14 "path/filepath"
15 "runtime"
16 "strings"
17 "sync"
18
19 "cmd/go/internal/base"
20 "cmd/go/internal/cfg"
21 "cmd/go/internal/fips140"
22 "cmd/go/internal/fsys"
23 "cmd/go/internal/gover"
24 "cmd/go/internal/load"
25 "cmd/go/internal/str"
26 "cmd/internal/quoted"
27 "crypto/sha1"
28 )
29
30
31 var ToolchainVersion = runtime.Version()
32
33
34
35 type gcToolchain struct{}
36
37 func (gcToolchain) compiler() string {
38 return base.Tool("compile")
39 }
40
41 func (gcToolchain) linker() string {
42 return base.Tool("link")
43 }
44
45 func pkgPath(a *Action) string {
46 p := a.Package
47 ppath := p.ImportPath
48 if cfg.BuildBuildmode == "plugin" {
49 ppath = pluginPath(a)
50 } else if p.Name == "main" && !p.Internal.ForceLibrary {
51 ppath = "main"
52 }
53 return ppath
54 }
55
56 func (gcToolchain) gc(b *Builder, a *Action, archive string, importcfg, embedcfg []byte, symabis string, asmhdr bool, pgoProfile string, gofiles []string) (ofile string, output []byte, err error) {
57 p := a.Package
58 sh := b.Shell(a)
59 objdir := a.Objdir
60 if archive != "" {
61 ofile = archive
62 } else {
63 out := "_go_.o"
64 ofile = objdir + out
65 }
66
67 pkgpath := pkgPath(a)
68 defaultGcFlags := []string{"-p", pkgpath}
69 vers := gover.Local()
70 if p.Module != nil {
71 v := p.Module.GoVersion
72 if v == "" {
73 v = gover.DefaultGoModVersion
74 }
75
76 if allowedVersion(v) {
77 vers = v
78 }
79 }
80 defaultGcFlags = append(defaultGcFlags, "-lang=go"+gover.Lang(vers))
81 if p.Standard {
82 defaultGcFlags = append(defaultGcFlags, "-std")
83 }
84
85
86
87
88
89 extFiles := len(p.CgoFiles) + len(p.CFiles) + len(p.CXXFiles) + len(p.MFiles) + len(p.FFiles) + len(p.SFiles) + len(p.SysoFiles) + len(p.SwigFiles) + len(p.SwigCXXFiles)
90 if p.Standard {
91 switch p.ImportPath {
92 case "bytes", "internal/poll", "net", "os":
93 fallthrough
94 case "runtime/metrics", "runtime/pprof", "runtime/trace":
95 fallthrough
96 case "sync", "syscall", "time":
97 extFiles++
98 }
99 }
100 if extFiles == 0 {
101 defaultGcFlags = append(defaultGcFlags, "-complete")
102 }
103 if cfg.BuildContext.InstallSuffix != "" {
104 defaultGcFlags = append(defaultGcFlags, "-installsuffix", cfg.BuildContext.InstallSuffix)
105 }
106 if a.buildID != "" {
107 defaultGcFlags = append(defaultGcFlags, "-buildid", a.buildID)
108 }
109 if p.Internal.OmitDebug || cfg.Goos == "plan9" || cfg.Goarch == "wasm" {
110 defaultGcFlags = append(defaultGcFlags, "-dwarf=false")
111 }
112 if strings.HasPrefix(ToolchainVersion, "go1") && !strings.Contains(os.Args[0], "go_bootstrap") {
113 defaultGcFlags = append(defaultGcFlags, "-goversion", ToolchainVersion)
114 }
115 if p.Internal.Cover.Cfg != "" {
116 defaultGcFlags = append(defaultGcFlags, "-coveragecfg="+p.Internal.Cover.Cfg)
117 }
118 if pgoProfile != "" {
119 defaultGcFlags = append(defaultGcFlags, "-pgoprofile="+pgoProfile)
120 }
121 if symabis != "" {
122 defaultGcFlags = append(defaultGcFlags, "-symabis", symabis)
123 }
124
125 gcflags := str.StringList(forcedGcflags, p.Internal.Gcflags)
126 if p.Internal.FuzzInstrument {
127 gcflags = append(gcflags, fuzzInstrumentFlags()...)
128 }
129
130 c, release := compilerConcurrency()
131 defer release()
132 if c > 1 {
133 defaultGcFlags = append(defaultGcFlags, fmt.Sprintf("-c=%d", c))
134 }
135
136 args := []any{cfg.BuildToolexec, base.Tool("compile"), "-o", ofile, "-trimpath", a.trimpath(), defaultGcFlags, gcflags}
137 if p.Internal.LocalPrefix == "" {
138 args = append(args, "-nolocalimports")
139 } else {
140 args = append(args, "-D", p.Internal.LocalPrefix)
141 }
142 if importcfg != nil {
143 if err := sh.writeFile(objdir+"importcfg", importcfg); err != nil {
144 return "", nil, err
145 }
146 args = append(args, "-importcfg", objdir+"importcfg")
147 }
148 if embedcfg != nil {
149 if err := sh.writeFile(objdir+"embedcfg", embedcfg); err != nil {
150 return "", nil, err
151 }
152 args = append(args, "-embedcfg", objdir+"embedcfg")
153 }
154 if ofile == archive {
155 args = append(args, "-pack")
156 }
157 if asmhdr {
158 args = append(args, "-asmhdr", objdir+"go_asm.h")
159 }
160
161 for _, f := range gofiles {
162 f := mkAbs(p.Dir, f)
163
164
165
166
167
168
169
170
171
172
173
174
175
176 args = append(args, fsys.Actual(f))
177 }
178 output, err = sh.runOut(base.Cwd(), cfgChangedEnv, args...)
179 return ofile, output, err
180 }
181
182
183
184 func compilerConcurrency() (int, func()) {
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209 if cfg.BuildP == 1 {
210
211 return maxCompilerConcurrency, func() {}
212 }
213
214
215 tokensMu.Lock()
216 defer tokensMu.Unlock()
217 concurrentProcesses++
218
219
220 setAside := (cfg.BuildP - concurrentProcesses) * minTokens
221 availableTokens := tokens - setAside
222
223
224 c := max(min(availableTokens/2, maxCompilerConcurrency), minTokens)
225 tokens -= c
226
227 return c, func() {
228 tokensMu.Lock()
229 defer tokensMu.Unlock()
230 concurrentProcesses--
231 tokens += c
232 }
233 }
234
235 var maxCompilerConcurrency = runtime.GOMAXPROCS(0)
236
237 var (
238 tokensMu sync.Mutex
239 totalTokens int
240 tokens int
241 concurrentProcesses int
242 minTokens int
243 )
244
245
246
247 func initCompilerConcurrencyPool() {
248
249
250
251
252 minTokens = min(4, maxCompilerConcurrency)
253 tokens = 2*maxCompilerConcurrency + minTokens*cfg.BuildP
254 totalTokens = tokens
255 }
256
257
258
259 func (a *Action) trimpath() string {
260
261
262
263
264
265 objdir := strings.TrimSuffix(a.Objdir, string(filepath.Separator))
266 rewrite := ""
267
268 rewriteDir := a.Package.Dir
269 if cfg.BuildTrimpath {
270 importPath := a.Package.Internal.OrigImportPath
271 if m := a.Package.Module; m != nil && m.Version != "" {
272 rewriteDir = m.Path + "@" + m.Version + strings.TrimPrefix(importPath, m.Path)
273 } else {
274 rewriteDir = importPath
275 }
276 rewrite += a.Package.Dir + "=>" + rewriteDir + ";"
277 }
278
279
280
281
282
283 cgoFiles := make(map[string]bool)
284 for _, f := range a.Package.CgoFiles {
285 cgoFiles[f] = true
286 }
287
288
289
290
291
292 var overlayNonGoRewrites string
293 hasCgoOverlay := false
294 if fsys.OverlayFile != "" {
295 for _, filename := range a.Package.AllFiles() {
296 path := filename
297 if !filepath.IsAbs(path) {
298 path = filepath.Join(a.Package.Dir, path)
299 }
300 base := filepath.Base(path)
301 isGo := strings.HasSuffix(filename, ".go") || strings.HasSuffix(filename, ".s")
302 isCgo := cgoFiles[filename] || !isGo
303 if fsys.Replaced(path) {
304 if isCgo {
305 hasCgoOverlay = true
306 } else {
307 rewrite += fsys.Actual(path) + "=>" + filepath.Join(rewriteDir, base) + ";"
308 }
309 } else if isCgo {
310
311 if filepath.Dir(path) == a.Package.Dir {
312
313 overlayNonGoRewrites += filepath.Join(objdir, base) + "=>" + filepath.Join(rewriteDir, base) + ";"
314 }
315 } else {
316
317 }
318 }
319 }
320 if hasCgoOverlay {
321 rewrite += overlayNonGoRewrites
322 }
323 rewrite += objdir + "=>"
324
325 return rewrite
326 }
327
328 func asmArgs(a *Action, p *load.Package) []any {
329
330 inc := filepath.Join(cfg.GOROOT, "pkg", "include")
331 pkgpath := pkgPath(a)
332 args := []any{cfg.BuildToolexec, base.Tool("asm"), "-p", pkgpath, "-trimpath", a.trimpath(), "-I", a.Objdir, "-I", inc, "-D", "GOOS_" + cfg.Goos, "-D", "GOARCH_" + cfg.Goarch, forcedAsmflags, p.Internal.Asmflags}
333 if p.ImportPath == "runtime" && cfg.Goarch == "386" {
334 for _, arg := range forcedAsmflags {
335 if arg == "-dynlink" {
336 args = append(args, "-D=GOBUILDMODE_shared=1")
337 }
338 }
339 }
340
341 if cfg.Goarch == "386" {
342
343 args = append(args, "-D", "GO386_"+cfg.GO386)
344 }
345
346 if cfg.Goarch == "amd64" {
347
348 args = append(args, "-D", "GOAMD64_"+cfg.GOAMD64)
349 }
350
351 if cfg.Goarch == "mips" || cfg.Goarch == "mipsle" {
352
353 args = append(args, "-D", "GOMIPS_"+cfg.GOMIPS)
354 }
355
356 if cfg.Goarch == "mips64" || cfg.Goarch == "mips64le" {
357
358 args = append(args, "-D", "GOMIPS64_"+cfg.GOMIPS64)
359 }
360
361 if cfg.Goarch == "ppc64" || cfg.Goarch == "ppc64le" {
362
363
364 switch cfg.GOPPC64 {
365 case "power10":
366 args = append(args, "-D", "GOPPC64_power10")
367 fallthrough
368 case "power9":
369 args = append(args, "-D", "GOPPC64_power9")
370 fallthrough
371 default:
372 args = append(args, "-D", "GOPPC64_power8")
373 }
374 }
375
376 if cfg.Goarch == "riscv64" {
377
378 args = append(args, "-D", "GORISCV64_"+cfg.GORISCV64)
379 }
380
381 if cfg.Goarch == "arm" {
382
383
384 switch {
385 case strings.Contains(cfg.GOARM, "7"):
386 args = append(args, "-D", "GOARM_7")
387 fallthrough
388 case strings.Contains(cfg.GOARM, "6"):
389 args = append(args, "-D", "GOARM_6")
390 fallthrough
391 default:
392 args = append(args, "-D", "GOARM_5")
393 }
394 }
395
396 if cfg.Goarch == "arm64" {
397 g, err := buildcfg.ParseGoarm64(cfg.GOARM64)
398 if err == nil && g.LSE {
399 args = append(args, "-D", "GOARM64_LSE")
400 }
401 }
402
403 return args
404 }
405
406 func (gcToolchain) asm(b *Builder, a *Action, sfiles []string) ([]string, error) {
407 p := a.Package
408 args := asmArgs(a, p)
409
410 var ofiles []string
411 for _, sfile := range sfiles {
412 ofile := a.Objdir + sfile[:len(sfile)-len(".s")] + ".o"
413 ofiles = append(ofiles, ofile)
414 args1 := append(args, "-o", ofile, fsys.Actual(mkAbs(p.Dir, sfile)))
415 if err := b.Shell(a).run(p.Dir, p.ImportPath, cfgChangedEnv, args1...); err != nil {
416 return nil, err
417 }
418 }
419 return ofiles, nil
420 }
421
422 func (gcToolchain) symabis(b *Builder, a *Action, sfiles []string) (string, error) {
423 sh := b.Shell(a)
424
425 mkSymabis := func(p *load.Package, sfiles []string, path string) error {
426 args := asmArgs(a, p)
427 args = append(args, "-gensymabis", "-o", path)
428 for _, sfile := range sfiles {
429 if p.ImportPath == "runtime/cgo" && strings.HasPrefix(sfile, "gcc_") {
430 continue
431 }
432 args = append(args, fsys.Actual(mkAbs(p.Dir, sfile)))
433 }
434
435
436
437
438 if err := sh.writeFile(a.Objdir+"go_asm.h", nil); err != nil {
439 return err
440 }
441
442 return sh.run(p.Dir, p.ImportPath, cfgChangedEnv, args...)
443 }
444
445 var symabis string
446 p := a.Package
447 if len(sfiles) != 0 {
448 symabis = a.Objdir + "symabis"
449 if err := mkSymabis(p, sfiles, symabis); err != nil {
450 return "", err
451 }
452 }
453
454 return symabis, nil
455 }
456
457 func (gcToolchain) pack(b *Builder, a *Action, afile string, ofiles []string) error {
458 absOfiles := make([]string, 0, len(ofiles))
459 for _, f := range ofiles {
460 absOfiles = append(absOfiles, mkAbs(a.Objdir, f))
461 }
462 absAfile := mkAbs(a.Objdir, afile)
463
464
465
466 if !cfg.BuildN {
467 if _, err := os.Stat(absAfile); err != nil {
468 base.Fatalf("os.Stat of archive file failed: %v", err)
469 }
470 }
471
472 p := a.Package
473 sh := b.Shell(a)
474 if cfg.BuildN || cfg.BuildX {
475 cmdline := str.StringList("go", "tool", "pack", "r", absAfile, absOfiles)
476 sh.ShowCmd(p.Dir, "%s # internal", joinUnambiguously(cmdline))
477 }
478 if cfg.BuildN {
479 return nil
480 }
481 if err := packInternal(absAfile, absOfiles); err != nil {
482 return sh.reportCmd("", "", nil, err)
483 }
484 return nil
485 }
486
487 func packInternal(afile string, ofiles []string) error {
488 dst, err := os.OpenFile(afile, os.O_WRONLY|os.O_APPEND, 0)
489 if err != nil {
490 return err
491 }
492 defer dst.Close()
493 w := bufio.NewWriter(dst)
494
495 for _, ofile := range ofiles {
496 src, err := os.Open(ofile)
497 if err != nil {
498 return err
499 }
500 fi, err := src.Stat()
501 if err != nil {
502 src.Close()
503 return err
504 }
505
506
507 name := fi.Name()
508 if len(name) > 16 {
509 name = name[:16]
510 } else {
511 name += strings.Repeat(" ", 16-len(name))
512 }
513 size := fi.Size()
514 fmt.Fprintf(w, "%s%-12d%-6d%-6d%-8o%-10d`\n",
515 name, 0, 0, 0, 0644, size)
516 n, err := io.Copy(w, src)
517 src.Close()
518 if err == nil && n < size {
519 err = io.ErrUnexpectedEOF
520 } else if err == nil && n > size {
521 err = fmt.Errorf("file larger than size reported by stat")
522 }
523 if err != nil {
524 return fmt.Errorf("copying %s to %s: %v", ofile, afile, err)
525 }
526 if size&1 != 0 {
527 w.WriteByte(0)
528 }
529 }
530
531 if err := w.Flush(); err != nil {
532 return err
533 }
534 return dst.Close()
535 }
536
537
538 func setextld(ldflags []string, compiler []string) ([]string, error) {
539 for _, f := range ldflags {
540 if f == "-extld" || strings.HasPrefix(f, "-extld=") {
541
542 return ldflags, nil
543 }
544 }
545 joined, err := quoted.Join(compiler)
546 if err != nil {
547 return nil, err
548 }
549 return append(ldflags, "-extld="+joined), nil
550 }
551
552
553
554
555
556
557
558
559 func pluginPath(a *Action) string {
560 p := a.Package
561 if p.ImportPath != "command-line-arguments" {
562 return p.ImportPath
563 }
564 h := sha1.New()
565 buildID := a.buildID
566 if a.Mode == "link" {
567
568
569
570
571
572
573
574
575
576 id := strings.Split(buildID, buildIDSeparator)
577 buildID = id[1] + buildIDSeparator + id[1]
578 }
579 fmt.Fprintf(h, "build ID: %s\n", buildID)
580 for _, file := range str.StringList(p.GoFiles, p.CgoFiles, p.SFiles) {
581 data, err := os.ReadFile(filepath.Join(p.Dir, file))
582 if err != nil {
583 base.Fatalf("go: %s", err)
584 }
585 h.Write(data)
586 }
587 return fmt.Sprintf("plugin/unnamed-%x", h.Sum(nil))
588 }
589
590 func (gcToolchain) ld(b *Builder, root *Action, targetPath, importcfg, mainpkg string) error {
591 cxx := len(root.Package.CXXFiles) > 0 || len(root.Package.SwigCXXFiles) > 0
592 for _, a := range root.Deps {
593 if a.Package != nil && (len(a.Package.CXXFiles) > 0 || len(a.Package.SwigCXXFiles) > 0) {
594 cxx = true
595 }
596 }
597 var ldflags []string
598 if cfg.BuildContext.InstallSuffix != "" {
599 ldflags = append(ldflags, "-installsuffix", cfg.BuildContext.InstallSuffix)
600 }
601 if root.Package.Internal.OmitDebug {
602 ldflags = append(ldflags, "-s", "-w")
603 }
604 if cfg.BuildBuildmode == "plugin" {
605 ldflags = append(ldflags, "-pluginpath", pluginPath(root))
606 }
607 if fips140.Enabled() {
608 ldflags = append(ldflags, "-fipso", filepath.Join(root.Objdir, "fips.o"))
609 }
610
611
612
613 if root.Package.Goroot && strings.HasPrefix(root.Package.ImportPath, "cmd/") {
614
615
616
617
618 if !platform.MustLinkExternal(cfg.Goos, cfg.Goarch, false) {
619 ldflags = append(ldflags, "-X=cmd/internal/objabi.buildID="+root.buildID)
620 }
621 }
622
623
624 if root.Package.DefaultGODEBUG != "" {
625 ldflags = append(ldflags, "-X=runtime.godebugDefault="+root.Package.DefaultGODEBUG)
626 }
627
628
629
630
631
632 var compiler []string
633 if cxx {
634 compiler = envList("CXX", cfg.DefaultCXX(cfg.Goos, cfg.Goarch))
635 } else {
636 compiler = envList("CC", cfg.DefaultCC(cfg.Goos, cfg.Goarch))
637 }
638 ldflags = append(ldflags, "-buildmode="+ldBuildmode)
639 if root.buildID != "" {
640 ldflags = append(ldflags, "-buildid="+root.buildID)
641 }
642 ldflags = append(ldflags, forcedLdflags...)
643 ldflags = append(ldflags, root.Package.Internal.Ldflags...)
644 ldflags, err := setextld(ldflags, compiler)
645 if err != nil {
646 return err
647 }
648
649
650
651
652
653
654
655
656
657
658
659
660 dir := "."
661 if cfg.BuildBuildmode == "c-shared" || cfg.BuildBuildmode == "plugin" {
662 dir, targetPath = filepath.Split(targetPath)
663 }
664
665 env := cfgChangedEnv
666
667 if cfg.BuildTrimpath {
668 env = append(env, "GOROOT=")
669 } else {
670 env = append(env, "GOROOT="+cfg.GOROOT)
671 }
672 return b.Shell(root).run(dir, root.Package.ImportPath, env, cfg.BuildToolexec, base.Tool("link"), "-o", targetPath, "-importcfg", importcfg, ldflags, mainpkg)
673 }
674
675 func (gcToolchain) ldShared(b *Builder, root *Action, toplevelactions []*Action, targetPath, importcfg string, allactions []*Action) error {
676 ldflags := []string{"-installsuffix", cfg.BuildContext.InstallSuffix}
677 ldflags = append(ldflags, "-buildmode=shared")
678 ldflags = append(ldflags, forcedLdflags...)
679 ldflags = append(ldflags, root.Package.Internal.Ldflags...)
680 cxx := false
681 for _, a := range allactions {
682 if a.Package != nil && (len(a.Package.CXXFiles) > 0 || len(a.Package.SwigCXXFiles) > 0) {
683 cxx = true
684 }
685 }
686
687
688
689
690 var compiler []string
691 if cxx {
692 compiler = envList("CXX", cfg.DefaultCXX(cfg.Goos, cfg.Goarch))
693 } else {
694 compiler = envList("CC", cfg.DefaultCC(cfg.Goos, cfg.Goarch))
695 }
696 ldflags, err := setextld(ldflags, compiler)
697 if err != nil {
698 return err
699 }
700 for _, d := range toplevelactions {
701 if !strings.HasSuffix(d.Target, ".a") {
702 continue
703 }
704 ldflags = append(ldflags, d.Package.ImportPath+"="+d.Target)
705 }
706
707
708
709
710
711
712
713
714
715
716
717
718 dir, targetPath := filepath.Split(targetPath)
719
720 return b.Shell(root).run(dir, targetPath, cfgChangedEnv, cfg.BuildToolexec, base.Tool("link"), "-o", targetPath, "-importcfg", importcfg, ldflags)
721 }
722
723 func (gcToolchain) cc(b *Builder, a *Action, ofile, cfile string) error {
724 return fmt.Errorf("%s: C source files not supported without cgo", mkAbs(a.Package.Dir, cfile))
725 }
726
View as plain text