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