1
2
3
4
5 package base
6
7 import (
8 "cmd/internal/cov/covcmd"
9 "cmd/internal/telemetry"
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.MaxShapeLen = 500
181 Debug.AlignHot = 1
182 Debug.InlFuncsWithClosures = 1
183 Debug.InlStaticInit = 1
184 Debug.PGOInline = 1
185 Debug.PGODevirtualize = 2
186 Debug.SyncFrames = -1
187 Debug.ZeroCopy = 1
188 Debug.RangeFuncCheck = 1
189 Debug.MergeLocals = 1
190
191 Debug.Checkptr = -1
192
193 Flag.Cfg.ImportMap = make(map[string]string)
194
195 objabi.AddVersionFlag()
196 registerFlags()
197 objabi.Flagparse(usage)
198 telemetry.CountFlags("compile/flag:", *flag.CommandLine)
199
200 if gcd := os.Getenv("GOCOMPILEDEBUG"); gcd != "" {
201
202
203 Flag.LowerD.Set(gcd)
204 }
205
206 if Debug.Gossahash != "" {
207 hashDebug = NewHashDebug("gossahash", Debug.Gossahash, nil)
208 }
209
210
211
212 if Flag.Std && objabi.LookupPkgSpecial(Ctxt.Pkgpath).Runtime {
213 Flag.CompilingRuntime = true
214 }
215
216 Ctxt.Std = Flag.Std
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241 if Debug.LoopVarHash != "" {
242
243 mostInlineOnly := true
244 if strings.HasPrefix(Debug.LoopVarHash, "IL") {
245
246
247
248
249
250 Debug.LoopVarHash = Debug.LoopVarHash[2:]
251 mostInlineOnly = false
252 }
253
254 LoopVarHash = NewHashDebug("loopvarhash", Debug.LoopVarHash, nil)
255 if Debug.LoopVar < 11 {
256 Debug.LoopVar = 1
257 }
258 LoopVarHash.SetInlineSuffixOnly(mostInlineOnly)
259 } else if buildcfg.Experiment.LoopVar && Debug.LoopVar == 0 {
260 Debug.LoopVar = 1
261 }
262
263 if Debug.Fmahash != "" {
264 FmaHash = NewHashDebug("fmahash", Debug.Fmahash, nil)
265 }
266 if Debug.PGOHash != "" {
267 PGOHash = NewHashDebug("pgohash", Debug.PGOHash, nil)
268 }
269 if Debug.MergeLocalsHash != "" {
270 MergeLocalsHash = NewHashDebug("mergelocals", Debug.MergeLocalsHash, nil)
271 }
272
273 if Flag.MSan && !platform.MSanSupported(buildcfg.GOOS, buildcfg.GOARCH) {
274 log.Fatalf("%s/%s does not support -msan", buildcfg.GOOS, buildcfg.GOARCH)
275 }
276 if Flag.ASan && !platform.ASanSupported(buildcfg.GOOS, buildcfg.GOARCH) {
277 log.Fatalf("%s/%s does not support -asan", buildcfg.GOOS, buildcfg.GOARCH)
278 }
279 if Flag.Race && !platform.RaceDetectorSupported(buildcfg.GOOS, buildcfg.GOARCH) {
280 log.Fatalf("%s/%s does not support -race", buildcfg.GOOS, buildcfg.GOARCH)
281 }
282 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) {
283 log.Fatalf("%s/%s does not support -shared", buildcfg.GOOS, buildcfg.GOARCH)
284 }
285 parseSpectre(Flag.Spectre)
286
287 Ctxt.Flag_shared = Ctxt.Flag_dynlink || Ctxt.Flag_shared
288 Ctxt.Flag_optimize = Flag.N == 0
289 Ctxt.Debugasm = int(Flag.S)
290 Ctxt.Flag_maymorestack = Debug.MayMoreStack
291 Ctxt.Flag_noRefName = Debug.NoRefName != 0
292
293 if flag.NArg() < 1 {
294 usage()
295 }
296
297 if Flag.GoVersion != "" && Flag.GoVersion != runtime.Version() {
298 fmt.Printf("compile: version %q does not match go tool version %q\n", runtime.Version(), Flag.GoVersion)
299 Exit(2)
300 }
301
302 if *Flag.LowerP == "" {
303 *Flag.LowerP = obj.UnlinkablePkg
304 }
305
306 if Flag.LowerO == "" {
307 p := flag.Arg(0)
308 if i := strings.LastIndex(p, "/"); i >= 0 {
309 p = p[i+1:]
310 }
311 if runtime.GOOS == "windows" {
312 if i := strings.LastIndex(p, `\`); i >= 0 {
313 p = p[i+1:]
314 }
315 }
316 if i := strings.LastIndex(p, "."); i >= 0 {
317 p = p[:i]
318 }
319 suffix := ".o"
320 if Flag.Pack {
321 suffix = ".a"
322 }
323 Flag.LowerO = p + suffix
324 }
325 switch {
326 case Flag.Race && Flag.MSan:
327 log.Fatal("cannot use both -race and -msan")
328 case Flag.Race && Flag.ASan:
329 log.Fatal("cannot use both -race and -asan")
330 case Flag.MSan && Flag.ASan:
331 log.Fatal("cannot use both -msan and -asan")
332 }
333 if Flag.Race || Flag.MSan || Flag.ASan {
334
335 if Debug.Checkptr == -1 {
336 Debug.Checkptr = 1
337 }
338 }
339
340 if Flag.LowerC < 1 {
341 log.Fatalf("-c must be at least 1, got %d", Flag.LowerC)
342 }
343 if !concurrentBackendAllowed() {
344 Flag.LowerC = 1
345 }
346
347 if Flag.CompilingRuntime {
348
349
350 Flag.N = 0
351 Ctxt.Flag_optimize = true
352
353
354 Debug.Checkptr = 0
355
356
357 Debug.Libfuzzer = 0
358 }
359
360 if Debug.Checkptr == -1 {
361 Debug.Checkptr = 0
362 }
363
364
365 Ctxt.Debugpcln = Debug.PCTab
366 }
367
368
369
370 func registerFlags() {
371 var (
372 boolType = reflect.TypeOf(bool(false))
373 intType = reflect.TypeOf(int(0))
374 stringType = reflect.TypeOf(string(""))
375 ptrBoolType = reflect.TypeOf(new(bool))
376 ptrIntType = reflect.TypeOf(new(int))
377 ptrStringType = reflect.TypeOf(new(string))
378 countType = reflect.TypeOf(CountFlag(0))
379 funcType = reflect.TypeOf((func(string))(nil))
380 )
381
382 v := reflect.ValueOf(&Flag).Elem()
383 t := v.Type()
384 for i := 0; i < t.NumField(); i++ {
385 f := t.Field(i)
386 if f.Name == "Cfg" {
387 continue
388 }
389
390 var name string
391 if len(f.Name) == 1 {
392 name = f.Name
393 } else if len(f.Name) == 6 && f.Name[:5] == "Lower" && 'A' <= f.Name[5] && f.Name[5] <= 'Z' {
394 name = string(rune(f.Name[5] + 'a' - 'A'))
395 } else {
396 name = strings.ToLower(f.Name)
397 }
398 if tag := f.Tag.Get("flag"); tag != "" {
399 name = tag
400 }
401
402 help := f.Tag.Get("help")
403 if help == "" {
404 panic(fmt.Sprintf("base.Flag.%s is missing help text", f.Name))
405 }
406
407 if k := f.Type.Kind(); (k == reflect.Ptr || k == reflect.Func) && v.Field(i).IsNil() {
408 panic(fmt.Sprintf("base.Flag.%s is uninitialized %v", f.Name, f.Type))
409 }
410
411 switch f.Type {
412 case boolType:
413 p := v.Field(i).Addr().Interface().(*bool)
414 flag.BoolVar(p, name, *p, help)
415 case intType:
416 p := v.Field(i).Addr().Interface().(*int)
417 flag.IntVar(p, name, *p, help)
418 case stringType:
419 p := v.Field(i).Addr().Interface().(*string)
420 flag.StringVar(p, name, *p, help)
421 case ptrBoolType:
422 p := v.Field(i).Interface().(*bool)
423 flag.BoolVar(p, name, *p, help)
424 case ptrIntType:
425 p := v.Field(i).Interface().(*int)
426 flag.IntVar(p, name, *p, help)
427 case ptrStringType:
428 p := v.Field(i).Interface().(*string)
429 flag.StringVar(p, name, *p, help)
430 case countType:
431 p := (*int)(v.Field(i).Addr().Interface().(*CountFlag))
432 objabi.Flagcount(name, help, p)
433 case funcType:
434 f := v.Field(i).Interface().(func(string))
435 objabi.Flagfn1(name, help, f)
436 default:
437 if val, ok := v.Field(i).Interface().(flag.Value); ok {
438 flag.Var(val, name, help)
439 } else {
440 panic(fmt.Sprintf("base.Flag.%s has unexpected type %s", f.Name, f.Type))
441 }
442 }
443 }
444 }
445
446
447
448 func concurrentFlagOk() bool {
449
450 return Flag.Percent == 0 &&
451 Flag.E == 0 &&
452 Flag.K == 0 &&
453 Flag.L == 0 &&
454 Flag.LowerH == 0 &&
455 Flag.LowerJ == 0 &&
456 Flag.LowerM == 0 &&
457 Flag.LowerR == 0
458 }
459
460 func concurrentBackendAllowed() bool {
461 if !concurrentFlagOk() {
462 return false
463 }
464
465
466
467
468
469 if Ctxt.Debugvlog || !Debug.ConcurrentOk || Flag.Live > 0 {
470 return false
471 }
472
473 if buildcfg.Experiment.FieldTrack {
474 return false
475 }
476
477 if Ctxt.Flag_dynlink || Flag.Race {
478 return false
479 }
480 return true
481 }
482
483 func addImportDir(dir string) {
484 if dir != "" {
485 Flag.Cfg.ImportDirs = append(Flag.Cfg.ImportDirs, dir)
486 }
487 }
488
489 func readImportCfg(file string) {
490 if Flag.Cfg.ImportMap == nil {
491 Flag.Cfg.ImportMap = make(map[string]string)
492 }
493 Flag.Cfg.PackageFile = map[string]string{}
494 data, err := os.ReadFile(file)
495 if err != nil {
496 log.Fatalf("-importcfg: %v", err)
497 }
498
499 for lineNum, line := range strings.Split(string(data), "\n") {
500 lineNum++
501 line = strings.TrimSpace(line)
502 if line == "" || strings.HasPrefix(line, "#") {
503 continue
504 }
505
506 verb, args, found := strings.Cut(line, " ")
507 if found {
508 args = strings.TrimSpace(args)
509 }
510 before, after, hasEq := strings.Cut(args, "=")
511
512 switch verb {
513 default:
514 log.Fatalf("%s:%d: unknown directive %q", file, lineNum, verb)
515 case "importmap":
516 if !hasEq || before == "" || after == "" {
517 log.Fatalf(`%s:%d: invalid importmap: syntax is "importmap old=new"`, file, lineNum)
518 }
519 Flag.Cfg.ImportMap[before] = after
520 case "packagefile":
521 if !hasEq || before == "" || after == "" {
522 log.Fatalf(`%s:%d: invalid packagefile: syntax is "packagefile path=filename"`, file, lineNum)
523 }
524 Flag.Cfg.PackageFile[before] = after
525 }
526 }
527 }
528
529 func readCoverageCfg(file string) {
530 var cfg covcmd.CoverFixupConfig
531 data, err := os.ReadFile(file)
532 if err != nil {
533 log.Fatalf("-coveragecfg: %v", err)
534 }
535 if err := json.Unmarshal(data, &cfg); err != nil {
536 log.Fatalf("error reading -coveragecfg file %q: %v", file, err)
537 }
538 Flag.Cfg.CoverageInfo = &cfg
539 }
540
541 func readEmbedCfg(file string) {
542 data, err := os.ReadFile(file)
543 if err != nil {
544 log.Fatalf("-embedcfg: %v", err)
545 }
546 if err := json.Unmarshal(data, &Flag.Cfg.Embed); err != nil {
547 log.Fatalf("%s: %v", file, err)
548 }
549 if Flag.Cfg.Embed.Patterns == nil {
550 log.Fatalf("%s: invalid embedcfg: missing Patterns", file)
551 }
552 if Flag.Cfg.Embed.Files == nil {
553 log.Fatalf("%s: invalid embedcfg: missing Files", file)
554 }
555 }
556
557
558 func parseSpectre(s string) {
559 for _, f := range strings.Split(s, ",") {
560 f = strings.TrimSpace(f)
561 switch f {
562 default:
563 log.Fatalf("unknown setting -spectre=%s", f)
564 case "":
565
566 case "all":
567 Flag.Cfg.SpectreIndex = true
568 Ctxt.Retpoline = true
569 case "index":
570 Flag.Cfg.SpectreIndex = true
571 case "ret":
572 Ctxt.Retpoline = true
573 }
574 }
575
576 if Flag.Cfg.SpectreIndex {
577 switch buildcfg.GOARCH {
578 case "amd64":
579
580 default:
581 log.Fatalf("GOARCH=%s does not support -spectre=index", buildcfg.GOARCH)
582 }
583 }
584 }
585
View as plain text