Source file src/cmd/compile/internal/base/flag.go

     1  // Copyright 2009 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     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  // Flag holds the parsed command-line flags.
    33  // See ParseFlag for non-zero defaults.
    34  var Flag CmdFlags
    35  
    36  // A CountFlag is a counting integer flag.
    37  // It accepts -name=value to set the value directly,
    38  // but it also accepts -name with no =value to increment the count.
    39  type CountFlag int
    40  
    41  // CmdFlags defines the command-line flags (see var Flag).
    42  // Each struct field is a different flag, by default named for the lower-case of the field name.
    43  // If the flag name is a single letter, the default flag name is left upper-case.
    44  // If the flag name is "Lower" followed by a single letter, the default flag name is the lower-case of the last letter.
    45  //
    46  // If this default flag name can't be made right, the `flag` struct tag can be used to replace it,
    47  // but this should be done only in exceptional circumstances: it helps everyone if the flag name
    48  // is obvious from the field name when the flag is used elsewhere in the compiler sources.
    49  // The `flag:"-"` struct tag makes a field invisible to the flag logic and should also be used sparingly.
    50  //
    51  // Each field must have a `help` struct tag giving the flag help message.
    52  //
    53  // The allowed field types are bool, int, string, pointers to those (for values stored elsewhere),
    54  // CountFlag (for a counting flag), and func(string) (for a flag that uses special code for parsing).
    55  type CmdFlags struct {
    56  	// Single letters
    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  	// V is added by objabi.AddVersionFlag
    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`\"" // &Ctxt.Pkgpath, set below
    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  	// Special characters
    85  	Percent          CountFlag "flag:\"%\" help:\"debug non-static initializers\""
    86  	CompilingRuntime bool      "flag:\"+\" help:\"compiling runtime\""
    87  
    88  	// Longer names
    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\""                        // &Ctxt.UseBASEntries, set below
   100  	DwarfLocationLists *bool        "help:\"add location lists to DWARF in optimized mode\""                      // &Ctxt.Flag_locationlists, set below
   101  	Dynlink            *bool        "help:\"support references to Go symbols defined in other shared libraries\"" // &Ctxt.Flag_dynlink, set below
   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\"" // 0=disabled, 1=funcs, 2=funcs+formals/locals
   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\"" // &Ctxt.Flag_linkshared, set below
   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\"" // &Ctxt.Flag_shared, set below
   123  	SmallFrames        bool         "help:\"reduce the size limit for stack allocated objects\""      // small stacks, to diagnose GC latency; see golang.org/issue/27732
   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\"" // TODO: remove
   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  	// Configuration derived from flags; not a flag itself.
   135  	Cfg struct {
   136  		Embed struct { // set by -embedcfg
   137  			Patterns map[string][]string
   138  			Files    map[string]string
   139  		}
   140  		ImportDirs   []string                 // appended to by -I
   141  		ImportMap    map[string]string        // set by -importcfg
   142  		PackageFile  map[string]string        // set by -importcfg; nil means not in use
   143  		CoverageInfo *covcmd.CoverFixupConfig // set by -coveragecfg
   144  		SpectreIndex bool                     // set by -spectre=index or -spectre=all
   145  		// Whether we are adding any sort of code instrumentation, such as
   146  		// when the race detector is enabled.
   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  // ParseFlags parses the command-line flags into Flag.
   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            // disable sync markers by default
   193  	Debug.VariableMakeThreshold = 32 // 32 byte default for stack allocated make results
   194  	Debug.ZeroCopy = 1
   195  	Debug.RangeFuncCheck = 1
   196  	Debug.MergeLocals = 1
   197  	Debug.RewriteResults = 1
   198  
   199  	Debug.Checkptr = -1 // so we can tell whether it is set explicitly
   200  
   201  	Flag.Cfg.ImportMap = make(map[string]string)
   202  
   203  	objabi.AddVersionFlag() // -V
   204  	registerFlags()
   205  	objabi.Flagparse(usage)
   206  	counter.CountFlags("compile/flag:", *flag.CommandLine)
   207  
   208  	if gcd := os.Getenv("GOCOMPILEDEBUG"); gcd != "" {
   209  		// This will only override the flags set in gcd;
   210  		// any others set on the command line remain set.
   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  	// Compute whether we're compiling the runtime from the package path. Test
   220  	// code can also use the flag to set this explicitly.
   221  	if Flag.Std && objabi.LookupPkgSpecial(Ctxt.Pkgpath).Runtime {
   222  		Flag.CompilingRuntime = true
   223  	}
   224  
   225  	Ctxt.Std = Flag.Std
   226  
   227  	// Three inputs govern loop iteration variable rewriting, hash, experiment, flag.
   228  	// The loop variable rewriting is:
   229  	// IF non-empty hash, then hash determines behavior (function+line match) (*)
   230  	// ELSE IF experiment and flag==0, then experiment (set flag=1)
   231  	// ELSE flag (note that build sets flag per-package), with behaviors:
   232  	//  -1 => no change to behavior.
   233  	//   0 => no change to behavior (unless non-empty hash, see above)
   234  	//   1 => apply change to likely-iteration-variable-escaping loops
   235  	//   2 => apply change, log results
   236  	//   11 => apply change EVERYWHERE, do not log results (for debugging/benchmarking)
   237  	//   12 => apply change EVERYWHERE, log results (for debugging/benchmarking)
   238  	//
   239  	// The expected uses of the these inputs are, in believed most-likely to least likely:
   240  	//  GOEXPERIMENT=loopvar -- apply change to entire application
   241  	//  -gcflags=some_package=-d=loopvar=1 -- apply change to some_package (**)
   242  	//  -gcflags=some_package=-d=loopvar=2 -- apply change to some_package, log it
   243  	//  GOEXPERIMENT=loopvar -gcflags=some_package=-d=loopvar=-1 -- apply change to all but one package
   244  	//  GOCOMPILEDEBUG=loopvarhash=... -- search for failure cause
   245  	//
   246  	//  (*) For debugging purposes, providing loopvar flag >= 11 will expand the hash-eligible set of loops to all.
   247  	// (**) Loop semantics, changed or not, follow code from a package when it is inlined; that is, the behavior
   248  	//      of an application compiled with partially modified loop semantics does not depend on inlining.
   249  
   250  	if Debug.LoopVarHash != "" {
   251  		// This first little bit controls the inputs for debug-hash-matching.
   252  		mostInlineOnly := true
   253  		if strings.HasPrefix(Debug.LoopVarHash, "IL") {
   254  			// When hash-searching on a position that is an inline site, default is to use the
   255  			// most-inlined position only.  This makes the hash faster, plus there's no point
   256  			// reporting a problem with all the inlining; there's only one copy of the source.
   257  			// However, if for some reason you wanted it per-site, you can get this.  (The default
   258  			// hash-search behavior for compiler debugging is at an inline site.)
   259  			Debug.LoopVarHash = Debug.LoopVarHash[2:]
   260  			mostInlineOnly = false
   261  		}
   262  		// end of testing trickiness
   263  		LoopVarHash = NewHashDebug("loopvarhash", Debug.LoopVarHash, nil)
   264  		if Debug.LoopVar < 11 { // >= 11 means all loops are rewrite-eligible
   265  			Debug.LoopVar = 1 // 1 means those loops that syntactically escape their dcl vars are eligible.
   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  		// quietly disable the convert hash changes
   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) // left as string for RecordFlags
   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  		// -race, -msan and -asan imply -d=checkptr for now.
   358  		if Debug.Checkptr == -1 { // if not set explicitly
   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  		// It is not possible to build the runtime with no optimizations,
   375  		// because the compiler cannot eliminate enough write barriers.
   376  		Flag.N = 0
   377  		Ctxt.Flag_optimize = true
   378  
   379  		// Runtime can't use -d=checkptr, at least not yet.
   380  		Debug.Checkptr = 0
   381  
   382  		// Fuzzing the runtime isn't interesting either.
   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 { // if not set explicitly
   391  		Debug.Checkptr = 0
   392  	}
   393  
   394  	// set via a -d flag
   395  	Ctxt.Debugpcln = Debug.PCTab
   396  
   397  	// https://golang.org/issue/67502
   398  	if buildcfg.GOOS == "plan9" && buildcfg.GOARCH == "386" {
   399  		Debug.AlignHot = 0
   400  	}
   401  }
   402  
   403  // registerFlags adds flag registrations for all the fields in Flag.
   404  // See the comment on type CmdFlags for the rules.
   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  // concurrentFlagOk reports whether the current compiler flags
   482  // are compatible with concurrent compilation.
   483  func concurrentFlagOk() bool {
   484  	// TODO(rsc): Many of these are fine. Remove them.
   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  	// Debug.S by itself is ok, because all printing occurs
   500  	// while writing the object file, and that is non-concurrent.
   501  	// Adding Debug_vlog, however, causes Debug.S to also print
   502  	// while flushing the plist, which happens concurrently.
   503  	if Ctxt.Debugvlog || !Debug.ConcurrentOk || Flag.Live > 0 {
   504  		return false
   505  	}
   506  	// TODO: Test and delete this condition.
   507  	if buildcfg.Experiment.FieldTrack {
   508  		return false
   509  	}
   510  	// TODO: fix races and enable the following flag
   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++ // 1-based
   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  // parseSpectre parses the spectre configuration from the string s.
   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  			// nothing
   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  			// ok
   614  		default:
   615  			log.Fatalf("GOARCH=%s does not support -spectre=index", buildcfg.GOARCH)
   616  		}
   617  	}
   618  }
   619  

View as plain text