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