1
2
3
4
5 package base
6
7 import (
8 "cmd/internal/cov/covcmd"
9 "cmd/internal/telemetry/counter"
10 "encoding/json"
11 "flag"
12 "fmt"
13 "internal/buildcfg"
14 "internal/platform"
15 "log"
16 "os"
17 "reflect"
18 "runtime"
19 "strings"
20
21 "cmd/internal/obj"
22 "cmd/internal/objabi"
23 "cmd/internal/sys"
24 )
25
26 func usage() {
27 fmt.Fprintf(os.Stderr, "usage: compile [options] file.go...\n")
28 objabi.Flagprint(os.Stderr)
29 Exit(2)
30 }
31
32
33
34 var Flag CmdFlags
35
36
37
38
39 type CountFlag int
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55 type CmdFlags struct {
56
57 B CountFlag "help:\"disable bounds checking\""
58 C CountFlag "help:\"disable printing of columns in error messages\""
59 D string "help:\"set relative `path` for local imports\""
60 E CountFlag "help:\"debug symbol export\""
61 I func(string) "help:\"add `directory` to import search path\""
62 K CountFlag "help:\"debug missing line numbers\""
63 L CountFlag "help:\"also show actual source file names in error messages for positions affected by //line directives\""
64 N CountFlag "help:\"disable optimizations\""
65 S CountFlag "help:\"print assembly listing\""
66
67 W CountFlag "help:\"debug parse tree after type checking\""
68
69 LowerC int "help:\"concurrency during compilation (1 means no concurrency)\""
70 LowerD flag.Value "help:\"enable debugging settings; try -d help\""
71 LowerE CountFlag "help:\"no limit on number of errors reported\""
72 LowerH CountFlag "help:\"halt on error\""
73 LowerJ CountFlag "help:\"debug runtime-initialized variables\""
74 LowerL CountFlag "help:\"disable inlining\""
75 LowerM CountFlag "help:\"print optimization decisions\""
76 LowerO string "help:\"write output to `file`\""
77 LowerP *string "help:\"set expected package import `path`\""
78 LowerR CountFlag "help:\"debug generated wrappers\""
79 LowerT bool "help:\"enable tracing for debugging the compiler\""
80 LowerW CountFlag "help:\"debug type checking\""
81 LowerU CountFlag "help:\"emit unsorted warnings/errors\""
82 LowerV *bool "help:\"increase debug verbosity\""
83
84
85 Percent CountFlag "flag:\"%\" help:\"debug non-static initializers\""
86 CompilingRuntime bool "flag:\"+\" help:\"compiling runtime\""
87
88
89 AsmHdr string "help:\"write assembly header to `file`\""
90 ASan bool "help:\"build code compatible with C/C++ address sanitizer\""
91 Bench string "help:\"append benchmark times to `file`\""
92 BlockProfile string "help:\"write block profile to `file`\""
93 BuildID string "help:\"record `id` as the build id in the export metadata\""
94 CPUProfile string "help:\"write cpu profile to `file`\""
95 Complete bool "help:\"compiling complete package (no C or assembly)\""
96 ClobberDead bool "help:\"clobber dead stack slots (for debugging)\""
97 ClobberDeadReg bool "help:\"clobber dead registers (for debugging)\""
98 Dwarf bool "help:\"generate DWARF symbols\""
99 DwarfBASEntries *bool "help:\"use base address selection entries in DWARF\""
100 DwarfLocationLists *bool "help:\"add location lists to DWARF in optimized mode\""
101 Dynlink *bool "help:\"support references to Go symbols defined in other shared libraries\""
102 EmbedCfg func(string) "help:\"read go:embed configuration from `file`\""
103 Env func(string) "help:\"add `definition` of the form key=value to environment\""
104 ExportPipe string "help:\"write a byte to named `pipe` once the export data has been written\""
105 GenDwarfInl int "help:\"generate DWARF inline info records\""
106 GoVersion string "help:\"required version of the runtime\""
107 ImportCfg func(string) "help:\"read import configuration from `file`\""
108 InstallSuffix string "help:\"set pkg directory `suffix`\""
109 JSON string "help:\"version,file for JSON compiler/optimizer detail output\""
110 Lang string "help:\"Go language version source code expects\""
111 LinkObj string "help:\"write linker-specific object to `file`\""
112 LinkShared *bool "help:\"generate code that will be linked against Go shared libraries\""
113 Live CountFlag "help:\"debug liveness analysis\""
114 MSan bool "help:\"build code compatible with C/C++ memory sanitizer\""
115 MemProfile string "help:\"write memory profile to `file`\""
116 MemProfileRate int "help:\"set runtime.MemProfileRate to `rate`\""
117 MutexProfile string "help:\"write mutex profile to `file`\""
118 NoLocalImports bool "help:\"reject local (relative) imports\""
119 CoverageCfg func(string) "help:\"read coverage configuration from `file`\""
120 Pack bool "help:\"write to file.a instead of file.o\""
121 Race bool "help:\"enable race detector\""
122 Shared *bool "help:\"generate code that can be linked into a shared library\""
123 SmallFrames bool "help:\"reduce the size limit for stack allocated objects\""
124 Spectre string "help:\"enable spectre mitigations in `list` (all, index, ret)\""
125 Stats bool "help:\"print compiler statistics\""
126 Std bool "help:\"compiling standard library\""
127 SymABIs string "help:\"read symbol ABIs from `file`\""
128 TraceProfile string "help:\"write an execution trace to `file`\""
129 TrimPath string "help:\"remove `prefix` from recorded source file paths\""
130 WB bool "help:\"enable write barrier\""
131 PgoProfile string "help:\"read profile or pre-process profile from `file`\""
132 ErrorURL bool "help:\"print explanatory URL with error message if applicable\""
133
134
135 Cfg struct {
136 Embed struct {
137 Patterns map[string][]string
138 Files map[string]string
139 }
140 ImportDirs []string
141 ImportMap map[string]string
142 PackageFile map[string]string
143 CoverageInfo *covcmd.CoverFixupConfig
144 SpectreIndex bool
145
146
147 Instrumenting bool
148 }
149 }
150
151 func addEnv(s string) {
152 i := strings.Index(s, "=")
153 if i < 0 {
154 log.Fatal("-env argument must be of the form key=value")
155 }
156 os.Setenv(s[:i], s[i+1:])
157 }
158
159
160 func ParseFlags() {
161 Flag.I = addImportDir
162
163 Flag.LowerC = runtime.GOMAXPROCS(0)
164 Flag.LowerD = objabi.NewDebugFlag(&Debug, DebugSSA)
165 Flag.LowerP = &Ctxt.Pkgpath
166 Flag.LowerV = &Ctxt.Debugvlog
167
168 Flag.Dwarf = buildcfg.GOARCH != "wasm" && buildcfg.GOARCH != "wasm32"
169 Flag.DwarfBASEntries = &Ctxt.UseBASEntries
170 Flag.DwarfLocationLists = &Ctxt.Flag_locationlists
171 *Flag.DwarfLocationLists = true
172 Flag.Dynlink = &Ctxt.Flag_dynlink
173 Flag.EmbedCfg = readEmbedCfg
174 Flag.Env = addEnv
175 Flag.GenDwarfInl = 2
176 Flag.ImportCfg = readImportCfg
177 Flag.CoverageCfg = readCoverageCfg
178 Flag.LinkShared = &Ctxt.Flag_linkshared
179 Flag.Shared = &Ctxt.Flag_shared
180 Flag.WB = true
181
182 Debug.ConcurrentOk = true
183 Debug.CompressInstructions = 1
184 Debug.MaxShapeLen = DefaultMaxShapeLen
185 Debug.AlignHot = 1
186 Debug.InlFuncsWithClosures = 1
187 Debug.InlStaticInit = 1
188 Debug.GenericsDedup = 1
189 Debug.FreeAppend = 1
190 Debug.PGOInline = 1
191 Debug.PGODevirtualize = 2
192 Debug.SyncFrames = -1
193 Debug.VariableMakeThreshold = 32
194 Debug.ZeroCopy = 1
195 Debug.RangeFuncCheck = 1
196 Debug.MergeLocals = 1
197 Debug.RewriteResults = 1
198
199 Debug.Checkptr = -1
200
201 Flag.Cfg.ImportMap = make(map[string]string)
202
203 objabi.AddVersionFlag()
204 registerFlags()
205 objabi.Flagparse(usage)
206 counter.CountFlags("compile/flag:", *flag.CommandLine)
207
208 if gcd := os.Getenv("GOCOMPILEDEBUG"); gcd != "" {
209
210
211 Flag.LowerD.Set(gcd)
212 }
213
214 if Debug.Gossahash != "" {
215 hashDebug = NewHashDebug("gossahash", Debug.Gossahash, nil)
216 }
217 obj.SetFIPSDebugHash(Debug.FIPSHash)
218
219
220
221 if Flag.Std && objabi.LookupPkgSpecial(Ctxt.Pkgpath).Runtime {
222 Flag.CompilingRuntime = true
223 }
224
225 Ctxt.Std = Flag.Std
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250 if Debug.LoopVarHash != "" {
251
252 mostInlineOnly := true
253 if strings.HasPrefix(Debug.LoopVarHash, "IL") {
254
255
256
257
258
259 Debug.LoopVarHash = Debug.LoopVarHash[2:]
260 mostInlineOnly = false
261 }
262
263 LoopVarHash = NewHashDebug("loopvarhash", Debug.LoopVarHash, nil)
264 if Debug.LoopVar < 11 {
265 Debug.LoopVar = 1
266 }
267 LoopVarHash.SetInlineSuffixOnly(mostInlineOnly)
268 } else if buildcfg.Experiment.LoopVar && Debug.LoopVar == 0 {
269 Debug.LoopVar = 1
270 }
271
272 if Debug.Converthash != "" {
273 ConvertHash = NewHashDebug("converthash", Debug.Converthash, nil)
274 } else {
275
276 ConvertHash = NewHashDebug("converthash", "qn", nil)
277 }
278 if Debug.Fmahash != "" {
279 FmaHash = NewHashDebug("fmahash", Debug.Fmahash, nil)
280 }
281 if Debug.PGOHash != "" {
282 PGOHash = NewHashDebug("pgohash", Debug.PGOHash, nil)
283 }
284 if Debug.LiteralAllocHash != "" {
285 LiteralAllocHash = NewHashDebug("literalalloc", Debug.LiteralAllocHash, nil)
286 }
287
288 if Debug.MergeLocalsHash != "" {
289 MergeLocalsHash = NewHashDebug("mergelocals", Debug.MergeLocalsHash, nil)
290 }
291 if Debug.VariableMakeHash != "" {
292 VariableMakeHash = NewHashDebug("variablemake", Debug.VariableMakeHash, nil)
293 }
294
295 if Flag.MSan && !platform.MSanSupported(buildcfg.GOOS, buildcfg.GOARCH) {
296 log.Fatalf("%s/%s does not support -msan", buildcfg.GOOS, buildcfg.GOARCH)
297 }
298 if Flag.ASan && !platform.ASanSupported(buildcfg.GOOS, buildcfg.GOARCH) {
299 log.Fatalf("%s/%s does not support -asan", buildcfg.GOOS, buildcfg.GOARCH)
300 }
301 if Flag.Race && !platform.RaceDetectorSupported(buildcfg.GOOS, buildcfg.GOARCH) {
302 log.Fatalf("%s/%s does not support -race", buildcfg.GOOS, buildcfg.GOARCH)
303 }
304 if (*Flag.Shared || *Flag.Dynlink || *Flag.LinkShared) && !Ctxt.Arch.InFamily(sys.AMD64, sys.ARM, sys.ARM64, sys.I386, sys.Loong64, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X) {
305 log.Fatalf("%s/%s does not support -shared", buildcfg.GOOS, buildcfg.GOARCH)
306 }
307 parseSpectre(Flag.Spectre)
308
309 Ctxt.CompressInstructions = Debug.CompressInstructions != 0
310 Ctxt.Flag_shared = Ctxt.Flag_dynlink || Ctxt.Flag_shared
311 Ctxt.Flag_optimize = Flag.N == 0
312 Ctxt.Debugasm = int(Flag.S)
313 Ctxt.Flag_maymorestack = Debug.MayMoreStack
314 Ctxt.Flag_noRefName = Debug.NoRefName != 0
315
316 if flag.NArg() < 1 {
317 usage()
318 }
319
320 if Flag.GoVersion != "" && Flag.GoVersion != runtime.Version() {
321 fmt.Printf("compile: version %q does not match go tool version %q\n", runtime.Version(), Flag.GoVersion)
322 Exit(2)
323 }
324
325 if *Flag.LowerP == "" {
326 *Flag.LowerP = obj.UnlinkablePkg
327 }
328
329 if Flag.LowerO == "" {
330 p := flag.Arg(0)
331 if i := strings.LastIndex(p, "/"); i >= 0 {
332 p = p[i+1:]
333 }
334 if runtime.GOOS == "windows" {
335 if i := strings.LastIndex(p, `\`); i >= 0 {
336 p = p[i+1:]
337 }
338 }
339 if i := strings.LastIndex(p, "."); i >= 0 {
340 p = p[:i]
341 }
342 suffix := ".o"
343 if Flag.Pack {
344 suffix = ".a"
345 }
346 Flag.LowerO = p + suffix
347 }
348 switch {
349 case Flag.Race && Flag.MSan:
350 log.Fatal("cannot use both -race and -msan")
351 case Flag.Race && Flag.ASan:
352 log.Fatal("cannot use both -race and -asan")
353 case Flag.MSan && Flag.ASan:
354 log.Fatal("cannot use both -msan and -asan")
355 }
356 if Flag.Race || Flag.MSan || Flag.ASan {
357
358 if Debug.Checkptr == -1 {
359 Debug.Checkptr = 1
360 }
361 }
362
363 if Flag.LowerC < 1 {
364 log.Fatalf("-c must be at least 1, got %d", Flag.LowerC)
365 }
366 if Flag.ExportPipe != "" && Flag.LinkObj == "" {
367 log.Fatalf("-exportpipe requires -linkobj")
368 }
369 if !concurrentBackendAllowed() {
370 Flag.LowerC = 1
371 }
372
373 if Flag.CompilingRuntime {
374
375
376 Flag.N = 0
377 Ctxt.Flag_optimize = true
378
379
380 Debug.Checkptr = 0
381
382
383 Debug.Libfuzzer = 0
384 }
385
386 if len(Flag.Cfg.ImportDirs) > 0 && Flag.Cfg.PackageFile != nil {
387 log.Fatalf("cannot use both -I and -importcfg")
388 }
389
390 if Debug.Checkptr == -1 {
391 Debug.Checkptr = 0
392 }
393
394
395 Ctxt.Debugpcln = Debug.PCTab
396
397
398 if buildcfg.GOOS == "plan9" && buildcfg.GOARCH == "386" {
399 Debug.AlignHot = 0
400 }
401 }
402
403
404
405 func registerFlags() {
406 var (
407 boolType = reflect.TypeFor[bool]()
408 intType = reflect.TypeFor[int]()
409 stringType = reflect.TypeFor[string]()
410 ptrBoolType = reflect.TypeFor[*bool]()
411 ptrIntType = reflect.TypeFor[*int]()
412 ptrStringType = reflect.TypeFor[*string]()
413 countType = reflect.TypeFor[CountFlag]()
414 funcType = reflect.TypeFor[func(string)]()
415 )
416
417 v := reflect.ValueOf(&Flag).Elem()
418 t := v.Type()
419 for i := 0; i < t.NumField(); i++ {
420 f := t.Field(i)
421 if f.Name == "Cfg" {
422 continue
423 }
424
425 var name string
426 if len(f.Name) == 1 {
427 name = f.Name
428 } else if len(f.Name) == 6 && f.Name[:5] == "Lower" && 'A' <= f.Name[5] && f.Name[5] <= 'Z' {
429 name = string(rune(f.Name[5] + 'a' - 'A'))
430 } else {
431 name = strings.ToLower(f.Name)
432 }
433 if tag := f.Tag.Get("flag"); tag != "" {
434 name = tag
435 }
436
437 help := f.Tag.Get("help")
438 if help == "" {
439 panic(fmt.Sprintf("base.Flag.%s is missing help text", f.Name))
440 }
441
442 if k := f.Type.Kind(); (k == reflect.Ptr || k == reflect.Func) && v.Field(i).IsNil() {
443 panic(fmt.Sprintf("base.Flag.%s is uninitialized %v", f.Name, f.Type))
444 }
445
446 switch f.Type {
447 case boolType:
448 p := v.Field(i).Addr().Interface().(*bool)
449 flag.BoolVar(p, name, *p, help)
450 case intType:
451 p := v.Field(i).Addr().Interface().(*int)
452 flag.IntVar(p, name, *p, help)
453 case stringType:
454 p := v.Field(i).Addr().Interface().(*string)
455 flag.StringVar(p, name, *p, help)
456 case ptrBoolType:
457 p := v.Field(i).Interface().(*bool)
458 flag.BoolVar(p, name, *p, help)
459 case ptrIntType:
460 p := v.Field(i).Interface().(*int)
461 flag.IntVar(p, name, *p, help)
462 case ptrStringType:
463 p := v.Field(i).Interface().(*string)
464 flag.StringVar(p, name, *p, help)
465 case countType:
466 p := (*int)(v.Field(i).Addr().Interface().(*CountFlag))
467 objabi.Flagcount(name, help, p)
468 case funcType:
469 f := v.Field(i).Interface().(func(string))
470 objabi.Flagfn1(name, help, f)
471 default:
472 if val, ok := v.Field(i).Interface().(flag.Value); ok {
473 flag.Var(val, name, help)
474 } else {
475 panic(fmt.Sprintf("base.Flag.%s has unexpected type %s", f.Name, f.Type))
476 }
477 }
478 }
479 }
480
481
482
483 func concurrentFlagOk() bool {
484
485 return Flag.Percent == 0 &&
486 Flag.E == 0 &&
487 Flag.K == 0 &&
488 Flag.L == 0 &&
489 Flag.LowerJ == 0 &&
490 Flag.LowerM == 0 &&
491 Flag.LowerR == 0
492 }
493
494 func concurrentBackendAllowed() bool {
495 if !concurrentFlagOk() {
496 return false
497 }
498
499
500
501
502
503 if Ctxt.Debugvlog || !Debug.ConcurrentOk || Flag.Live > 0 {
504 return false
505 }
506
507 if buildcfg.Experiment.FieldTrack {
508 return false
509 }
510
511 if Ctxt.Flag_dynlink {
512 return false
513 }
514 return true
515 }
516
517 func addImportDir(dir string) {
518 if dir != "" {
519 Flag.Cfg.ImportDirs = append(Flag.Cfg.ImportDirs, dir)
520 }
521 }
522
523 func readImportCfg(file string) {
524 if Flag.Cfg.ImportMap == nil {
525 Flag.Cfg.ImportMap = make(map[string]string)
526 }
527 Flag.Cfg.PackageFile = map[string]string{}
528 data, err := os.ReadFile(file)
529 if err != nil {
530 log.Fatalf("-importcfg: %v", err)
531 }
532
533 for lineNum, line := range strings.Split(string(data), "\n") {
534 lineNum++
535 line = strings.TrimSpace(line)
536 if line == "" || strings.HasPrefix(line, "#") {
537 continue
538 }
539
540 verb, args, found := strings.Cut(line, " ")
541 if found {
542 args = strings.TrimSpace(args)
543 }
544 before, after, hasEq := strings.Cut(args, "=")
545
546 switch verb {
547 default:
548 log.Fatalf("%s:%d: unknown directive %q", file, lineNum, verb)
549 case "importmap":
550 if !hasEq || before == "" || after == "" {
551 log.Fatalf(`%s:%d: invalid importmap: syntax is "importmap old=new"`, file, lineNum)
552 }
553 Flag.Cfg.ImportMap[before] = after
554 case "packagefile":
555 if !hasEq || before == "" || after == "" {
556 log.Fatalf(`%s:%d: invalid packagefile: syntax is "packagefile path=filename"`, file, lineNum)
557 }
558 Flag.Cfg.PackageFile[before] = after
559 }
560 }
561 }
562
563 func readCoverageCfg(file string) {
564 var cfg covcmd.CoverFixupConfig
565 data, err := os.ReadFile(file)
566 if err != nil {
567 log.Fatalf("-coveragecfg: %v", err)
568 }
569 if err := json.Unmarshal(data, &cfg); err != nil {
570 log.Fatalf("error reading -coveragecfg file %q: %v", file, err)
571 }
572 Flag.Cfg.CoverageInfo = &cfg
573 }
574
575 func readEmbedCfg(file string) {
576 data, err := os.ReadFile(file)
577 if err != nil {
578 log.Fatalf("-embedcfg: %v", err)
579 }
580 if err := json.Unmarshal(data, &Flag.Cfg.Embed); err != nil {
581 log.Fatalf("%s: %v", file, err)
582 }
583 if Flag.Cfg.Embed.Patterns == nil {
584 log.Fatalf("%s: invalid embedcfg: missing Patterns", file)
585 }
586 if Flag.Cfg.Embed.Files == nil {
587 log.Fatalf("%s: invalid embedcfg: missing Files", file)
588 }
589 }
590
591
592 func parseSpectre(s string) {
593 for f := range strings.SplitSeq(s, ",") {
594 f = strings.TrimSpace(f)
595 switch f {
596 default:
597 log.Fatalf("unknown setting -spectre=%s", f)
598 case "":
599
600 case "all":
601 Flag.Cfg.SpectreIndex = true
602 Ctxt.Retpoline = true
603 case "index":
604 Flag.Cfg.SpectreIndex = true
605 case "ret":
606 Ctxt.Retpoline = true
607 }
608 }
609
610 if Flag.Cfg.SpectreIndex {
611 switch buildcfg.GOARCH {
612 case "amd64":
613
614 default:
615 log.Fatalf("GOARCH=%s does not support -spectre=index", buildcfg.GOARCH)
616 }
617 }
618 }
619
View as plain text