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