Source file src/cmd/go/internal/work/security.go

     1  // Copyright 2018 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  // Checking of compiler and linker flags.
     6  // We must avoid flags like -fplugin=, which can allow
     7  // arbitrary code execution during the build.
     8  // Do not make changes here without carefully
     9  // considering the implications.
    10  // (That's why the code is isolated in a file named security.go.)
    11  //
    12  // Note that -Wl,foo means split foo on commas and pass to
    13  // the linker, so that -Wl,-foo,bar means pass -foo bar to
    14  // the linker. Similarly -Wa,foo for the assembler and so on.
    15  // If any of these are permitted, the wildcard portion must
    16  // disallow commas.
    17  //
    18  // Note also that GNU binutils accept any argument @foo
    19  // as meaning "read more flags from the file foo", so we must
    20  // guard against any command-line argument beginning with @,
    21  // even things like "-I @foo".
    22  // We use load.SafeArg (which is even more conservative)
    23  // to reject these.
    24  //
    25  // Even worse, gcc -I@foo (one arg) turns into cc1 -I @foo (two args),
    26  // so although gcc doesn't expand the @foo, cc1 will.
    27  // So out of paranoia, we reject @ at the beginning of every
    28  // flag argument that might be split into its own argument.
    29  
    30  package work
    31  
    32  import (
    33  	"bytes"
    34  	"debug/elf"
    35  	"debug/macho"
    36  	"debug/pe"
    37  	"debug/plan9obj"
    38  	"encoding/binary"
    39  	"fmt"
    40  	"internal/lazyregexp"
    41  	"internal/xcoff"
    42  	"io"
    43  	"os"
    44  	"path/filepath"
    45  	"regexp"
    46  	"slices"
    47  	"strconv"
    48  	"strings"
    49  	"unicode"
    50  	"unicode/utf8"
    51  
    52  	"cmd/go/internal/base"
    53  	"cmd/go/internal/cfg"
    54  	"cmd/go/internal/load"
    55  	"cmd/go/internal/str"
    56  )
    57  
    58  var re = lazyregexp.New
    59  
    60  var validCompilerFlags = []*lazyregexp.Regexp{
    61  	re(`-D([A-Za-z_][A-Za-z0-9_]*)(=[^@\-]*)?`),
    62  	re(`-U([A-Za-z_][A-Za-z0-9_]*)`),
    63  	re(`-F([^@\-].*)`),
    64  	re(`-I([^@\-].*)`),
    65  	re(`-O`),
    66  	re(`-O([^@\-].*)`),
    67  	re(`-W`),
    68  	re(`-W([^@,]+)`), // -Wall but not -Wa,-foo.
    69  	re(`-Wa,-mbig-obj`),
    70  	re(`-Wp,-D([A-Za-z_][A-Za-z0-9_]*)(=[^@,\-]*)?`),
    71  	re(`-Wp,-U([A-Za-z_][A-Za-z0-9_]*)`),
    72  	re(`-ansi`),
    73  	re(`-f(no-)?asynchronous-unwind-tables`),
    74  	re(`-f(no-)?blocks`),
    75  	re(`-f(no-)builtin-[a-zA-Z0-9_]*`),
    76  	re(`-f(no-)?common`),
    77  	re(`-f(no-)?constant-cfstrings`),
    78  	re(`-fdebug-prefix-map=([^@]+)=([^@]+)`),
    79  	re(`-fdiagnostics-show-note-include-stack`),
    80  	re(`-fexcess-precision=([A-Za-z0-9_]+)`),
    81  	re(`-ffile-prefix-map=([^@]+)=([^@]+)`),
    82  	re(`-fno-canonical-system-headers`),
    83  	re(`-f(no-)?eliminate-unused-debug-types`),
    84  	re(`-f(no-)?exceptions`),
    85  	re(`-f(no-)?fast-math`),
    86  	re(`-f(no-)?inline-functions`),
    87  	re(`-finput-charset=([^@\-].*)`),
    88  	re(`-f(no-)?fat-lto-objects`),
    89  	re(`-f(no-)?keep-inline-dllexport`),
    90  	re(`-f(no-)?lto`),
    91  	re(`-fmacro-backtrace-limit=(.+)`),
    92  	re(`-fmessage-length=(.+)`),
    93  	re(`-f(no-)?modules`),
    94  	re(`-f(no-)?objc-arc`),
    95  	re(`-f(no-)?objc-nonfragile-abi`),
    96  	re(`-f(no-)?objc-legacy-dispatch`),
    97  	re(`-f(no-)?omit-frame-pointer`),
    98  	re(`-f(no-)?openmp(-simd)?`),
    99  	re(`-f(no-)?permissive`),
   100  	re(`-f(no-)?(pic|PIC|pie|PIE)`),
   101  	re(`-f(no-)?plt`),
   102  	re(`-f(no-)?rtti`),
   103  	re(`-f(no-)?split-stack`),
   104  	re(`-f(no-)?stack-(.+)`),
   105  	re(`-f(no-)?strict-aliasing`),
   106  	re(`-f(un)signed-char`),
   107  	re(`-f(no-)?use-linker-plugin`), // safe if -B is not used; we don't permit -B
   108  	re(`-f(no-)?visibility-inlines-hidden`),
   109  	re(`-fsanitize=([^@\-].*)`),
   110  	re(`-fsanitize-undefined-strip-path-components=(-)?[0-9]+`),
   111  	re(`-ftemplate-depth-(.+)`),
   112  	re(`-ftls-model=(global-dynamic|local-dynamic|initial-exec|local-exec)`),
   113  	re(`-fvisibility=(.+)`),
   114  	re(`-g([^@\-].*)?`),
   115  	re(`-m32`),
   116  	re(`-m64`),
   117  	re(`-m(abi|arch|cpu|fpu|simd|tls-dialect|tune)=([^@\-].*)`),
   118  	re(`-m(no-)?v?aes`),
   119  	re(`-marm`),
   120  	re(`-mcmodel=[0-9a-z-]+`),
   121  	re(`-mfloat-abi=([^@\-].*)`),
   122  	re(`-m(soft|single|double)-float`),
   123  	re(`-mfpmath=[0-9a-z,+]*`),
   124  	re(`-m(no-)?avx[0-9a-z.]*`),
   125  	re(`-m(no-)?ms-bitfields`),
   126  	re(`-m(no-)?stack-(.+)`),
   127  	re(`-mmacosx-(.+)`),
   128  	re(`-m(no-)?relax`),
   129  	re(`-m(no-)?strict-align`),
   130  	re(`-m(no-)?(lsx|lasx|frecipe|div32|lam-bh|lamcas|ld-seq-sa)`),
   131  	re(`-mios-simulator-version-min=(.+)`),
   132  	re(`-miphoneos-version-min=(.+)`),
   133  	re(`-mlarge-data-threshold=[0-9]+`),
   134  	re(`-mtvos-simulator-version-min=(.+)`),
   135  	re(`-mtvos-version-min=(.+)`),
   136  	re(`-mwatchos-simulator-version-min=(.+)`),
   137  	re(`-mwatchos-version-min=(.+)`),
   138  	re(`-mnop-fun-dllimport`),
   139  	re(`-m(no-)?sse[0-9.]*`),
   140  	re(`-m(no-)?ssse3`),
   141  	re(`-mthumb(-interwork)?`),
   142  	re(`-mthreads`),
   143  	re(`-mwindows`),
   144  	re(`-no-canonical-prefixes`),
   145  	re(`--param=ssp-buffer-size=[0-9]*`),
   146  	re(`-pedantic(-errors)?`),
   147  	re(`-pipe`),
   148  	re(`-pthread`),
   149  	re(`--static`),
   150  	re(`-?-std=([^@\-].*)`),
   151  	re(`-?-stdlib=([^@\-].*)`),
   152  	re(`-w`),
   153  	re(`-x(c|c-header|cpp-output|c\+\+|c\+\+-header|c\+\+-cpp-output|objective-c|objective-c-header|objective-c-cpp-output|objective-c\+\+|objective-c\+\+-header|objective-c\+\+-cpp-output|assembler|assembler-with-cpp)`),
   154  	re(`-v`),
   155  }
   156  
   157  var validCompilerXLang = re(`^(c|c-header|cpp-output|c\+\+|c\+\+-header|c\+\+-cpp-output|objective-c|objective-c-header|objective-c-cpp-output|objective-c\+\+|objective-c\+\+-header|objective-c\+\+-cpp-output|assembler|assembler-with-cpp)$`)
   158  
   159  var validCompilerFlagsWithNextArg = []string{
   160  	"-arch",
   161  	"-D",
   162  	"-U",
   163  	"-I",
   164  	"-F",
   165  	"-framework",
   166  	"-include",
   167  	"-isysroot",
   168  	"-isystem",
   169  	"-x",
   170  }
   171  
   172  var invalidCompilerFlags = []*lazyregexp.Regexp{
   173  	// Clang's -gen-cdb-fragment-path takes a directory argument and writes
   174  	// compilation database fragments there; have to exclude separately because
   175  	// -g* is allowed in general. GCC's -gnatO similarly takes a separate
   176  	// output filename argument in the GCC driver.
   177  	re(`-gen-.*`),
   178  	re(`-gnat.*`),
   179  }
   180  
   181  var invalidLinkerFlags = []*lazyregexp.Regexp{
   182  	// On macOS this means the linker loads and executes the next argument.
   183  	// Have to exclude separately because -lfoo is allowed in general.
   184  	re(`-lto_library`),
   185  	re(`-lazy_library`),
   186  	re(`-lazy_framework`),
   187  	re(`-load_hidden`),
   188  	// GNU gold and LLD accept single-dash -library and -library-path.
   189  	re(`-library(-path)?(=.*)?`),
   190  	re(`-gen-.*`),
   191  	re(`-gnat.*`),
   192  	// In lld, --warn-backrefs-exclude takes a separate <glob> argument when not
   193  	// joined with '='; exclude the bare form because -Wl,--(no-)?warn-([^,]+) is
   194  	// allowed in general.
   195  	re(`-Wl,--warn-backrefs-exclude`),
   196  }
   197  
   198  var validLinkerFlags = []*lazyregexp.Regexp{
   199  	re(`-F([^@\-].*)`),
   200  	re(`-l([^@\-:=/\\][^:=/\\]*)`),
   201  	re(`-L([^@\-].*)`),
   202  	re(`-O`),
   203  	re(`-O([^@\-].*)`),
   204  	re(`-f(no-)?(pic|PIC|pie|PIE)`),
   205  	re(`-f(no-)?openmp(-simd)?`),
   206  	re(`-fsanitize=([^@\-].*)`),
   207  	re(`-flat_namespace`),
   208  	re(`-g([^@\-].*)?`),
   209  	re(`-headerpad_max_install_names`),
   210  	re(`-m(abi|arch|cpu|fpu|simd|tls-dialect|tune)=([^@\-].*)`),
   211  	re(`-mcmodel=[0-9a-z-]+`),
   212  	re(`-mfloat-abi=([^@\-].*)`),
   213  	re(`-m(soft|single|double)-float`),
   214  	re(`-m(no-)?relax`),
   215  	re(`-m(no-)?strict-align`),
   216  	re(`-m(no-)?(lsx|lasx|frecipe|div32|lam-bh|lamcas|ld-seq-sa)`),
   217  	re(`-mmacosx-(.+)`),
   218  	re(`-mios-simulator-version-min=(.+)`),
   219  	re(`-miphoneos-version-min=(.+)`),
   220  	re(`-mthreads`),
   221  	re(`-mwindows`),
   222  	re(`-(pic|PIC|pie|PIE)`),
   223  	re(`-pthread`),
   224  	re(`-rdynamic`),
   225  	re(`-shared`),
   226  	re(`-?-static([-a-z0-9+]*)`),
   227  	re(`-?-stdlib=([^@\-].*)`),
   228  	re(`-v`),
   229  
   230  	// Note that any wildcards in -Wl need to exclude comma,
   231  	// since -Wl splits its argument at commas and passes
   232  	// them all to the linker uninterpreted. Allowing comma
   233  	// in a wildcard would allow tunneling arbitrary additional
   234  	// linker arguments through one of these.
   235  	re(`-Wl,--(no-)?allow-multiple-definition`),
   236  	re(`-Wl,--(no-)?allow-shlib-undefined`),
   237  	re(`-Wl,--(no-)?as-needed`),
   238  	re(`-Wl,-Bdynamic`),
   239  	re(`-Wl,-berok`),
   240  	re(`-Wl,-Bstatic`),
   241  	re(`-Wl,-Bsymbolic-functions`),
   242  	re(`-Wl,-O[0-9]+`),
   243  	re(`-Wl,-d[ny]`),
   244  	re(`-Wl,--disable-new-dtags`),
   245  	re(`-Wl,-e[=,][a-zA-Z0-9]+`),
   246  	re(`-Wl,--enable-new-dtags`),
   247  	re(`-Wl,--end-group`),
   248  	re(`-Wl,--(no-)?export-dynamic`),
   249  	re(`-Wl,-E`),
   250  	re(`-Wl,-framework,[^,@\-][^,]*`),
   251  	re(`-Wl,--hash-style=(sysv|gnu|both)`),
   252  	re(`-Wl,-headerpad_max_install_names`),
   253  	re(`-Wl,--no-undefined`),
   254  	re(`-Wl,--pop-state`),
   255  	re(`-Wl,--push-state`),
   256  	re(`-Wl,-R[,=]?([^@\-,=][^,@]*$)`),
   257  	re(`-Wl,--just-symbols[=,]([^,@\-][^,@]*)`),
   258  	re(`-Wl,-rpath(-link)?[=,]([^,@\-][^,]*)`),
   259  	re(`-Wl,-s`),
   260  	re(`-Wl,-search_paths_first`),
   261  	re(`-Wl,-sectcreate,([^,@\-][^,]*),([^,@\-][^,]*),([^,@\-][^,]*)`),
   262  	re(`-Wl,--start-group`),
   263  	re(`-Wl,-?-static`),
   264  	re(`-Wl,-?-subsystem,(native|windows|console|posix|xbox)`),
   265  	re(`-Wl,-syslibroot[=,]([^,@\-][^,]*)`),
   266  	re(`-Wl,-undefined[=,]([^,@\-][^,]*)`),
   267  	re(`-Wl,-?-unresolved-symbols=[^,]+`),
   268  	re(`-Wl,--(no-)?warn-([^,]+)`),
   269  	re(`-Wl,-?-wrap[=,][^,@\-][^,]*`),
   270  	re(`-Wl(,-z,(relro|now|(no)?execstack))+`),
   271  
   272  	re(`[a-zA-Z0-9_/].*\.(a|o|obj|dll|dylib|lib|so|tbd)`), // direct linker inputs: x.o or libfoo.so (but not -foo.o or @foo.o)
   273  	re(`\./.*\.(a|o|obj|dll|dylib|lib|so|tbd)`),
   274  }
   275  
   276  var validLinkerFlagsWithNextArg = []string{
   277  	"-arch",
   278  	"-F",
   279  	"-l",
   280  	"-L",
   281  	"-framework",
   282  	"-isysroot",
   283  	"-Wl,-framework",
   284  	"-Wl,-rpath",
   285  	"-Wl,-R",
   286  	"-Wl,--just-symbols",
   287  	"-Wl,-undefined",
   288  }
   289  
   290  // recombinedLinkerFlagsWithNextArg lists flags in validLinkerFlagsWithNextArg
   291  // that GCC and Clang recombine with their following argument (e.g., "-l" "foo"
   292  // becomes "-lfoo"), which must also be checked against invalidLinkerFlags.
   293  var recombinedLinkerFlagsWithNextArg = []string{
   294  	"-l",
   295  }
   296  
   297  var validPkgConfigFlags = []*lazyregexp.Regexp{
   298  	re(`--atleast-pkgconfig-version=\d+\.\d+\.\d+`),
   299  	re(`--atleast-version=\d+\.\d+\.\d+`),
   300  	re(`--cflags-only-I`),
   301  	re(`--cflags`),
   302  	re(`--define-prefix`),
   303  	re(`--define-variable=[A-Za-z_][A-Za-z0-9_]*=[^@\-=$][^$]*`),
   304  	re(`--digraph`),
   305  	re(`--dont-define-prefix`),
   306  	re(`--dont-relocate-paths`),
   307  	re(`--dump-personality`),
   308  	re(`--env-only`),
   309  	re(`--errors-to-stdout`),
   310  	re(`--exact-version=\d+\.\d+\.\d+`),
   311  	re(`--exists`),
   312  	re(`--fragment-filter=[A-Za-z_][a-zA-Z0-9_]*`),
   313  	re(`--ignore-conflicts`),
   314  	re(`--internal-cflags`),
   315  	re(`--keep-system-cflags`),
   316  	re(`--keep-system-libs`),
   317  	re(`--libs-only-l`),
   318  	re(`--libs-only-L`),
   319  	re(`--libs`),
   320  	re(`--list-all`),
   321  	re(`--list-package-names`),
   322  	re(`--max-version=\d+\.\d+\.\d+`),
   323  	re(`--maximum-traverse-depth=[0-9]+`),
   324  	re(`--modversion`),
   325  	re(`--msvc-syntax`),
   326  	re(`--no-cache`),
   327  	re(`--no-provides`),
   328  	re(`--no-uninstalled`),
   329  	re(`--path`),
   330  	re(`--prefix-variable=[A-Za-z_][a-zA-Z0-9_]*`),
   331  	re(`--print-errors`),
   332  	re(`--print-provides`),
   333  	re(`--print-requires-private`),
   334  	re(`--print-requires`),
   335  	re(`--print-variables`),
   336  	re(`--pure`),
   337  	re(`--shared`),
   338  	re(`--short-errors`),
   339  	re(`--silence-errors`),
   340  	re(`--simulate`),
   341  	re(`--static`),
   342  	re(`--uninstalled`),
   343  	re(`--validate`),
   344  	re(`--variable=[A-Za-z_][a-zA-Z0-9_]*`),
   345  }
   346  
   347  // hasGCCSpecFlags reports whether list contains linker flags that cause GCC's
   348  // built-in *link_command spec to evaluate %:include(libgomp.spec) (-fopenmp or
   349  // -fopenacc) or %:include(libsanitizer.spec) (-fsanitize=* combined with
   350  // -static or -static-lib*).
   351  func hasGCCSpecFlags(list []string) bool {
   352  	hasSanitize := false
   353  	hasStatic := false
   354  	for _, arg := range list {
   355  		if arg == "-fopenmp" || arg == "-fopenacc" {
   356  			return true
   357  		}
   358  		if strings.HasPrefix(arg, "-fsanitize=") {
   359  			hasSanitize = true
   360  		}
   361  		if arg == "-static" || arg == "--static" || strings.HasPrefix(arg, "-static-") || strings.HasPrefix(arg, "--static-") {
   362  			hasStatic = true
   363  		}
   364  	}
   365  	return hasSanitize && hasStatic
   366  }
   367  
   368  func checkCompilerFlags(name, source string, list []string) error {
   369  	checkOverrides := true
   370  	return checkFlags(name, source, list, invalidCompilerFlags, validCompilerFlags, nil, validCompilerFlagsWithNextArg, checkOverrides)
   371  }
   372  
   373  func checkLinkerFlags(name, source string, list []string) error {
   374  	checkOverrides := true
   375  	if err := checkFlags(name, source, list, invalidLinkerFlags, validLinkerFlags, recombinedLinkerFlagsWithNextArg, validLinkerFlagsWithNextArg, checkOverrides); err != nil {
   376  		return err
   377  	}
   378  	if hasGCCSpecFlags(list) {
   379  		if err := checkLinkerSpecDir(source, "."); err != nil {
   380  			return err
   381  		}
   382  	}
   383  	for i := 0; i < len(list); i++ {
   384  		arg := list[i]
   385  		switch {
   386  		case strings.HasPrefix(arg, "-L"):
   387  			dir := arg[2:]
   388  			if dir == "" && i+1 < len(list) {
   389  				i++
   390  				dir = list[i]
   391  			}
   392  			if dir != "" {
   393  				if err := checkLinkerLibDir(source, dir); err != nil {
   394  					return err
   395  				}
   396  			}
   397  		// Although -isysroot is a preprocessor/compiler option in GCC, clang on
   398  		// Darwin also accepts it as a linker flag (forwarding it as -syslibroot)
   399  		// and we include it in validLinkerFlagsWithNextArg on all platforms.
   400  		case arg == "-isysroot" && i+1 < len(list):
   401  			i++ // consume next argument
   402  			if err := checkLinkerSysroot(source, arg+" "+list[i], list[i]); err != nil {
   403  				return err
   404  			}
   405  		case arg == "-framework" && i+1 < len(list):
   406  			i++
   407  			if err := checkLinkerNonPathNonFile(source, arg+" "+list[i], list[i]); err != nil {
   408  				return err
   409  			}
   410  		case strings.HasPrefix(arg, "-Wl,"):
   411  			raw := arg
   412  			warg := arg
   413  			if slices.Contains(validLinkerFlagsWithNextArg, arg) && i+1 < len(list) {
   414  				i++
   415  				raw = arg + " " + list[i]
   416  				warg = arg + "," + strings.TrimPrefix(list[i], "-Wl,")
   417  			}
   418  			if err := checkLinkerWlFlag(source, raw, warg); err != nil {
   419  				return err
   420  			}
   421  		case reDirectLinkerInput.MatchString(arg) && isLocalLinkerPath(arg):
   422  			if err := checkLinkerInputFile(source, arg); err != nil {
   423  				return err
   424  			}
   425  		}
   426  	}
   427  	return nil
   428  }
   429  
   430  // checkLinkerSysroot verifies that the target of -isysroot or -Wl,-syslibroot
   431  // does not name a regular file on disk, which GNU ld.bfd would treat as a
   432  // positional linker script.
   433  func checkLinkerSysroot(source, flag, dir string) error {
   434  	if fi, err := os.Stat(dir); err == nil && !fi.IsDir() {
   435  		return fmt.Errorf("invalid flag in %s: %s (not a directory)", source, flag)
   436  	}
   437  	return checkLinkerSpecDir(source, dir)
   438  }
   439  
   440  // checkLinkerNonPathNonFile verifies that val (such as a framework or symbol
   441  // name) is not a path and does not name a regular file in the current working
   442  // directory. If a Darwin-only or symbol flag is misinterpreted by GNU ld.bfd
   443  // (for example, -framework <val> parsed as -f ramework <val>, or -undefined
   444  // <val> parsed as -u ndefined <val>), ld.bfd treats <val> as a positional
   445  // input file and will execute it as a linker script if it is a regular file.
   446  // Directories (such as "." in existing tests or subdirectories in the working
   447  // directory that happen to share a framework or symbol name) are allowed
   448  // because ld.bfd only parses regular files as linker scripts.
   449  func checkLinkerNonPathNonFile(source, raw, val string) error {
   450  	if strings.ContainsAny(val, `/\`) {
   451  		return fmt.Errorf("invalid flag in %s: %s (see https://go.dev/s/invalidflag)", source, raw)
   452  	}
   453  	if fi, err := os.Stat(val); err == nil && !fi.IsDir() {
   454  		return fmt.Errorf("invalid flag in %s: %s (see https://go.dev/s/invalidflag)", source, raw)
   455  	}
   456  	return nil
   457  }
   458  
   459  func checkLinkerObjOrDir(source, raw, val string) error {
   460  	if !isLocalLinkerPath(val) {
   461  		return nil
   462  	}
   463  	if fi, err := os.Stat(val); err == nil && !fi.IsDir() {
   464  		if err := checkLinkerInputFile(source, val); err != nil {
   465  			return fmt.Errorf("invalid flag in %s: %s (%v)", source, raw, err)
   466  		}
   467  	}
   468  	return nil
   469  }
   470  
   471  func checkLinkerWlFlag(source, raw, arg string) error {
   472  	wargs := []string{arg}
   473  	if strings.HasPrefix(arg, "-Wl,--push-state,") {
   474  		for _, sub := range strings.Split(arg, ",")[2:] {
   475  			wargs = append(wargs, "-Wl,"+sub)
   476  		}
   477  	}
   478  	for _, warg := range wargs {
   479  		switch {
   480  		case strings.HasPrefix(warg, "-Wl,-syslibroot,"), strings.HasPrefix(warg, "-Wl,-syslibroot="):
   481  			dir := warg[len("-Wl,-syslibroot,"):]
   482  			if err := checkLinkerSysroot(source, raw, dir); err != nil {
   483  				return err
   484  			}
   485  		case strings.HasPrefix(warg, "-Wl,-framework,"):
   486  			if err := checkLinkerNonPathNonFile(source, raw, warg[len("-Wl,-framework,"):]); err != nil {
   487  				return err
   488  			}
   489  		case strings.HasPrefix(warg, "-Wl,-undefined,"), strings.HasPrefix(warg, "-Wl,-undefined="):
   490  			if err := checkLinkerNonPathNonFile(source, raw, warg[len("-Wl,-undefined,"):]); err != nil {
   491  				return err
   492  			}
   493  		case strings.HasPrefix(warg, "-Wl,--just-symbols,"), strings.HasPrefix(warg, "-Wl,--just-symbols="):
   494  			if err := checkLinkerObjOrDir(source, raw, warg[len("-Wl,--just-symbols,"):]); err != nil {
   495  				return err
   496  			}
   497  		case strings.HasPrefix(warg, "-Wl,-R"):
   498  			val := warg[len("-Wl,-R"):]
   499  			if after, ok := strings.CutPrefix(val, ","); ok {
   500  				val = after
   501  			} else if after, ok := strings.CutPrefix(val, "="); ok {
   502  				val = after
   503  			}
   504  			if err := checkLinkerObjOrDir(source, raw, val); err != nil {
   505  				return err
   506  			}
   507  		case strings.HasPrefix(warg, "-Wl,-subsystem,"):
   508  			// On non-Windows targets, GNU ld.gold (and older non-PE ld.bfd) parses
   509  			// single-dash -subsystem as -s -u bsystem and treats the following
   510  			// comma-split argument as a positional input file / linker script.
   511  			if cfg.Goos != "windows" {
   512  				if err := checkLinkerNonPathNonFile(source, raw, warg[len("-Wl,-subsystem,"):]); err != nil {
   513  					return err
   514  				}
   515  			}
   516  		case strings.HasPrefix(warg, "-Wl,-sectcreate,"):
   517  			// -sectcreate <seg> <sect> <file> is an Apple linker flag whose
   518  			// third argument is legitimately a regular file on Darwin/iOS.
   519  			// On other platforms, GNU ld.bfd parses -sectcreate as -s -e ctcreate
   520  			// and treats all three arguments as positional linker scripts; we still
   521  			// allow non-existent file arguments on non-Darwin so cross-platform
   522  			// flag validation tests continue to work.
   523  			parts := strings.SplitN(warg[len("-Wl,-sectcreate,"):], ",", 3)
   524  			if len(parts) == 3 {
   525  				if err := checkLinkerNonPathNonFile(source, raw, parts[0]); err != nil {
   526  					return err
   527  				}
   528  				if err := checkLinkerNonPathNonFile(source, raw, parts[1]); err != nil {
   529  					return err
   530  				}
   531  				if cfg.Goos != "darwin" && cfg.Goos != "ios" {
   532  					if fi, err := os.Stat(parts[2]); err == nil && !fi.IsDir() {
   533  						return fmt.Errorf("invalid flag in %s: %s (see https://go.dev/s/invalidflag)", source, raw)
   534  					}
   535  				}
   536  			}
   537  		}
   538  	}
   539  	return nil
   540  }
   541  
   542  func trimLinkerSysrootPrefix(dir string) string {
   543  	if strings.HasPrefix(dir, "=") {
   544  		return dir[1:]
   545  	}
   546  	if strings.HasPrefix(dir, "$SYSROOT") {
   547  		return dir[len("$SYSROOT"):]
   548  	}
   549  	return dir
   550  }
   551  
   552  var (
   553  	reDirectLinkerInput = re(`^(\./|[a-zA-Z0-9_/]).*\.(a|o|obj|dll|dylib|lib|so|tbd)$`)
   554  	reLinkerLibFile     = re(`(\.(a|o|obj|dll|dylib|lib|so|tbd)$|\.so\.)`)
   555  )
   556  
   557  // isLocalLinkerPath reports whether path is local to the build (a relative
   558  // path, or an absolute path within the working directory, module cache, or
   559  // temp/work directory, such as from ${SRCDIR} expansion). Non-local host
   560  // paths are outside the cmd/go threat model.
   561  func isLocalLinkerPath(path string) bool {
   562  	if !filepath.IsAbs(path) {
   563  		return true
   564  	}
   565  	clean := filepath.Clean(path)
   566  	for _, root := range []string{base.Cwd(), cfg.GOMODCACHE, os.TempDir()} {
   567  		if root == "" {
   568  			continue
   569  		}
   570  		if str.HasFilePathPrefix(clean, filepath.Clean(root)) {
   571  			return true
   572  		}
   573  		if realRoot, err := filepath.EvalSymlinks(root); err == nil {
   574  			if realClean, err := filepath.EvalSymlinks(clean); err == nil && str.HasFilePathPrefix(realClean, realRoot) {
   575  				return true
   576  			}
   577  		}
   578  	}
   579  	return false
   580  }
   581  
   582  func checkLinkerSpecDir(source, dir string) error {
   583  	return scanLinkerSearchDir(source, dir, false)
   584  }
   585  
   586  func checkLinkerLibDir(source, dir string) error {
   587  	return scanLinkerSearchDir(source, dir, true)
   588  }
   589  
   590  // scanLinkerSearchDir walks the directory rooted at dir and looks for .spec files,
   591  // which can inject arbitrary linker flags, or cause execution of arbitrary
   592  // commands. When checkLibs is true, it also validates library and object files in
   593  // the directory via checkLinkerInputFile to reject GNU ld linker scripts and
   594  // objects with embedded linker options or LTO sections.
   595  //
   596  // When GCC evaluates %:include(libgomp.spec) or %:include(libsanitizer.spec),
   597  // which can be caused by -fopenmp, -fopenacc, or -fsanitize=..., it looks for the specific
   598  // spec file in a number of places, including the current working directory and
   599  // sysroot or -L directories. GCC uses a search strategy that looks for target-triple
   600  // directories and GCC version directories inside of these directories, but since
   601  // we don't want to hard code those values, we use a much less targeted approach,
   602  // and just walk the directory looking for a spec file. In theory this can cause
   603  // failure when we find a spec file that GCC wouldn't load, but it seems better to
   604  // be safe here.
   605  func scanLinkerSearchDir(source, rawDir string, checkLibs bool) error {
   606  	dir := trimLinkerSysrootPrefix(rawDir)
   607  	if dir == "" || !isLocalLinkerPath(dir) {
   608  		return nil
   609  	}
   610  	visited := make(map[string]bool)
   611  	var checkTree func(root string) error
   612  	checkTree = func(root string) error {
   613  		if abs, err := filepath.Abs(root); err == nil {
   614  			root = abs
   615  		} else {
   616  			root = filepath.Clean(root)
   617  		}
   618  		if !isLocalLinkerPath(root) {
   619  			return nil
   620  		}
   621  		if resolved, err := filepath.EvalSymlinks(root); err == nil {
   622  			root = resolved
   623  		}
   624  		if visited[root] || !isLocalLinkerPath(root) {
   625  			return nil
   626  		}
   627  		visited[root] = true
   628  		if fi, err := os.Stat(root); err != nil || !fi.IsDir() {
   629  			return nil
   630  		}
   631  		return filepath.WalkDir(root, func(path string, d os.DirEntry, err error) error {
   632  			if err != nil {
   633  				return nil
   634  			}
   635  			if d.IsDir() {
   636  				if path != root && !isLocalLinkerPath(path) {
   637  					return filepath.SkipDir
   638  				}
   639  				return nil
   640  			}
   641  			if d.Type()&os.ModeSymlink != 0 {
   642  				if fi, err := os.Stat(path); err == nil && fi.IsDir() {
   643  					return checkTree(path)
   644  				}
   645  			}
   646  			lower := strings.ToLower(d.Name())
   647  			if lower == "specs" || strings.HasSuffix(lower, ".spec") {
   648  				return fmt.Errorf("disallowed GCC spec file in %s: %s", source, path)
   649  			}
   650  			if checkLibs && reLinkerLibFile.MatchString(lower) {
   651  				if err := checkLinkerInputFile(source, path); err != nil {
   652  					return err
   653  				}
   654  			}
   655  			return nil
   656  		})
   657  	}
   658  	if err := checkTree(dir); err != nil {
   659  		return err
   660  	}
   661  	if !checkLibs {
   662  		return nil
   663  	}
   664  	// GCC also searches multilib sibling directories (such as ../lib64)
   665  	// relative to each -L directory. Because filepath.Join cleans ".."
   666  	// lexically, if dir is a symlink its lexical parent and its resolved
   667  	// parent on disk may differ; check both.
   668  	absDir := filepath.Clean(dir)
   669  	if abs, err := filepath.Abs(dir); err == nil {
   670  		absDir = abs
   671  	}
   672  	bases := []string{absDir}
   673  	if resolved, err := filepath.EvalSymlinks(absDir); err == nil {
   674  		if abs, err := filepath.Abs(resolved); err == nil {
   675  			resolved = abs
   676  		}
   677  		if resolved != absDir {
   678  			bases = append(bases, resolved)
   679  		}
   680  	}
   681  	for _, base := range bases {
   682  		// Avoid walking host top-level /lib, /lib64, C:\lib, etc. when base is a
   683  		// filesystem root or depth-1 directory such as /tmp, /app, or C:\app
   684  		// (where filepath.Join(base, "..", "lib") would resolve to /lib or C:\lib).
   685  		if parent := filepath.Dir(base); parent == base || filepath.Dir(parent) == parent {
   686  			continue
   687  		}
   688  		for _, sub := range []string{"lib", "lib32", "lib64", "libx32"} {
   689  			if err := checkTree(filepath.Join(base, "..", sub)); err != nil {
   690  				return err
   691  			}
   692  		}
   693  	}
   694  	return nil
   695  }
   696  
   697  // checkLinkerInputFile verifies that an existing linker input or .syso file
   698  // is a valid binary object/archive (or macOS .tbd stub) rather than a GNU ld
   699  // linker script, and does not contain embedded linker flags (unallowlisted
   700  // .drectve directives, LC_LINKER_OPTION, or LTO IR sections).
   701  func checkLinkerInputFile(source, path string) error {
   702  	f, err := os.Open(path)
   703  	if err != nil {
   704  		if os.IsNotExist(err) {
   705  			return nil
   706  		}
   707  		return err
   708  	}
   709  	defer f.Close()
   710  
   711  	fi, err := f.Stat()
   712  	if err != nil {
   713  		return err
   714  	}
   715  
   716  	if strings.HasSuffix(strings.ToLower(path), ".tbd") && source != ".syso" {
   717  		var hdr [256]byte
   718  		n, _ := f.Read(hdr[:])
   719  		s := strings.TrimSpace(string(hdr[:n]))
   720  		if !strings.HasPrefix(s, "---") && !strings.HasPrefix(s, "{") {
   721  			return fmt.Errorf("invalid .tbd file in %s: %s", source, path)
   722  		}
   723  		return nil
   724  	}
   725  
   726  	return checkLinkerObjectRegion(source, path, io.NewSectionReader(f, 0, fi.Size()), 0)
   727  }
   728  
   729  func isDisallowedLTOSection(name string) bool {
   730  	return strings.HasPrefix(name, ".gnu.lto_") ||
   731  		strings.HasPrefix(name, ".gnu.debuglto_") ||
   732  		strings.HasPrefix(name, ".llvm.lto") ||
   733  		name == ".llvmbc" ||
   734  		name == ".llvmcmd"
   735  }
   736  
   737  func isCOFFMachine(mach uint16) bool {
   738  	switch mach {
   739  	case pe.IMAGE_FILE_MACHINE_I386,
   740  		pe.IMAGE_FILE_MACHINE_AMD64,
   741  		pe.IMAGE_FILE_MACHINE_ARM,
   742  		pe.IMAGE_FILE_MACHINE_ARMNT,
   743  		pe.IMAGE_FILE_MACHINE_ARM64,
   744  		pe.IMAGE_FILE_MACHINE_LOONGARCH32,
   745  		pe.IMAGE_FILE_MACHINE_LOONGARCH64,
   746  		pe.IMAGE_FILE_MACHINE_RISCV32,
   747  		pe.IMAGE_FILE_MACHINE_RISCV64,
   748  		pe.IMAGE_FILE_MACHINE_RISCV128:
   749  		return true
   750  	}
   751  	return false
   752  }
   753  
   754  // coffReaderAt wraps an io.SectionReader so debug/pe.NewFile's initial 96-byte
   755  // DOS-header probe succeeds on valid headerless COFF .o files smaller than 96 bytes.
   756  type coffReaderAt struct {
   757  	r *io.SectionReader
   758  }
   759  
   760  func (c coffReaderAt) ReadAt(p []byte, off int64) (int, error) {
   761  	if off == 0 && len(p) == 96 && c.r.Size() >= 20 && c.r.Size() < 96 {
   762  		clear(p)
   763  		if _, err := c.r.ReadAt(p[:c.r.Size()], 0); err != nil {
   764  			return 0, err
   765  		}
   766  		return len(p), nil
   767  	}
   768  	return c.r.ReadAt(p, off)
   769  }
   770  
   771  func checkLinkerArchive(source, path string, r *io.SectionReader, depth int) error {
   772  	if source == ".syso" {
   773  		return fmt.Errorf("archive not allowed as .syso in %s: %s", source, path)
   774  	}
   775  	off := int64(8)
   776  	memberIdx := 0
   777  	slashCount := 0
   778  	sawLongNames := false
   779  	var arhdr [60]byte
   780  	for off+60 <= r.Size() {
   781  		if _, err := r.ReadAt(arhdr[:], off); err != nil {
   782  			return fmt.Errorf("malformed archive in %s: %s", source, path)
   783  		}
   784  		if arhdr[58] != '`' || arhdr[59] != '\n' {
   785  			return fmt.Errorf("malformed archive header in %s: %s", source, path)
   786  		}
   787  		name := strings.TrimSpace(string(arhdr[0:16]))
   788  		sizeStr := strings.TrimSpace(string(arhdr[48:58]))
   789  		sz, err := strconv.ParseInt(sizeStr, 10, 64)
   790  		if err != nil || sz < 0 || off+60+sz > r.Size() {
   791  			return fmt.Errorf("malformed archive member size in %s: %s", source, path)
   792  		}
   793  		off += 60
   794  		switch {
   795  		case name == "__.SYMDEF" || name == "__.SYMDEF SORTED":
   796  			if memberIdx != 0 {
   797  				return fmt.Errorf("unexpected archive symbol table member %q in %s: %s", name, source, path)
   798  			}
   799  		case name == "/":
   800  			if memberIdx != slashCount || slashCount >= 2 || sawLongNames {
   801  				return fmt.Errorf("unexpected archive symbol table member %q in %s: %s", name, source, path)
   802  			}
   803  			if slashCount == 0 {
   804  				if err := checkArchiveFirstLinkerMember(source, path, r, off, sz); err != nil {
   805  					return err
   806  				}
   807  			} else {
   808  				if err := checkPESecondLinkerMember(source, path, r, off, sz); err != nil {
   809  					return err
   810  				}
   811  			}
   812  			slashCount++
   813  		case name == "//":
   814  			if memberIdx != slashCount || sawLongNames {
   815  				return fmt.Errorf("unexpected archive string table member in %s: %s", source, path)
   816  			}
   817  			sawLongNames = true
   818  			// Reject binary objects disguised as the "//" string table, which a
   819  			// symbol offset in "/" could otherwise target and cause the linker to load.
   820  			if sz >= 4 {
   821  				if err := checkLinkerObjectRegion(source, path, io.NewSectionReader(r, off, sz), depth+1); err == nil {
   822  					return fmt.Errorf("binary object disguised as archive string table in %s: %s", source, path)
   823  				} else if strings.Contains(err.Error(), "disallowed") {
   824  					return err
   825  				}
   826  			}
   827  		case strings.HasPrefix(name, "#1/"):
   828  			nameLen, err := strconv.ParseInt(name[3:], 10, 64)
   829  			if err != nil || nameLen <= 0 || nameLen > 4096 || nameLen > sz {
   830  				return fmt.Errorf("malformed BSD archive member in %s: %s", source, path)
   831  			}
   832  			nameBytes := make([]byte, nameLen)
   833  			if _, err := io.ReadFull(io.NewSectionReader(r, off, nameLen), nameBytes); err != nil {
   834  				return fmt.Errorf("malformed BSD archive member name in %s: %s", source, path)
   835  			}
   836  			realName := strings.TrimRight(string(nameBytes), "\x00")
   837  			isSymdef := memberIdx == 0 && (realName == "__.SYMDEF" || realName == "__.SYMDEF SORTED")
   838  			if !isSymdef {
   839  				if sz <= nameLen {
   840  					return fmt.Errorf("empty BSD archive member in %s: %s", source, path)
   841  				}
   842  				if err := checkLinkerObjectRegion(source, path, io.NewSectionReader(r, off+nameLen, sz-nameLen), depth+1); err != nil {
   843  					return err
   844  				}
   845  			}
   846  		default:
   847  			if sz <= 0 {
   848  				return fmt.Errorf("empty archive member in %s: %s", source, path)
   849  			}
   850  			if err := checkLinkerObjectRegion(source, path, io.NewSectionReader(r, off, sz), depth+1); err != nil {
   851  				return err
   852  			}
   853  		}
   854  		off += sz
   855  		if off&1 != 0 {
   856  			off++
   857  		}
   858  		memberIdx++
   859  	}
   860  	if off != r.Size() {
   861  		return fmt.Errorf("truncated or trailing data in archive in %s: %s", source, path)
   862  	}
   863  	return nil
   864  }
   865  
   866  // checkArchiveFirstLinkerMember validates the SVR4/GNU/PE first "/" archive
   867  // symbol table member. When resolving a symbol from "/", linkers seek directly
   868  // to the recorded file offset without checking the target member's header name.
   869  // The big-endian symbol count check (4+4*numSyms <= sz) rejects binary object
   870  // headers starting with a non-zero byte (\x7fELF, Mach-O, MZ, COFF); we also
   871  // explicitly reject the PE short import header magic (00 00 ff ff, which would
   872  // otherwise parse as numSyms = 65535).
   873  func checkArchiveFirstLinkerMember(source, path string, r *io.SectionReader, off, sz int64) error {
   874  	if sz == 0 {
   875  		return nil
   876  	}
   877  	if sz < 4 {
   878  		return fmt.Errorf("malformed archive symbol table in %s: %s", source, path)
   879  	}
   880  	var shdr [4]byte
   881  	if _, err := r.ReadAt(shdr[:], off); err != nil {
   882  		return fmt.Errorf("malformed archive symbol table in %s: %s", source, path)
   883  	}
   884  	if shdr == [4]byte{0, 0, 0xff, 0xff} {
   885  		return fmt.Errorf("binary object disguised as archive symbol table in %s: %s", source, path)
   886  	}
   887  	numSyms := int64(binary.BigEndian.Uint32(shdr[:]))
   888  	if 4+4*numSyms > sz {
   889  		return fmt.Errorf("malformed archive symbol table in %s: %s", source, path)
   890  	}
   891  	return nil
   892  }
   893  
   894  // checkPESecondLinkerMember validates the optional second "/" linker member in
   895  // a Microsoft PE/COFF archive (which lists little-endian member count, member
   896  // file offsets, symbol count, and symbol indices). The numMembers <= r.Size()/60
   897  // bound rejects binary object headers disguised as a second "/" member.
   898  func checkPESecondLinkerMember(source, path string, r *io.SectionReader, off, sz int64) error {
   899  	if sz < 8 {
   900  		return fmt.Errorf("malformed PE archive second linker member in %s: %s", source, path)
   901  	}
   902  	var mhdr [8]byte
   903  	if _, err := r.ReadAt(mhdr[:], off); err != nil {
   904  		return fmt.Errorf("malformed PE archive second linker member in %s: %s", source, path)
   905  	}
   906  	numMembers := int64(binary.LittleEndian.Uint32(mhdr[0:4]))
   907  	if numMembers > r.Size()/60 || 4+4*numMembers+4 > sz {
   908  		return fmt.Errorf("malformed PE archive second linker member in %s: %s", source, path)
   909  	}
   910  	var symCountBuf [4]byte
   911  	if _, err := r.ReadAt(symCountBuf[:], off+4+4*numMembers); err != nil {
   912  		return fmt.Errorf("malformed PE archive second linker member in %s: %s", source, path)
   913  	}
   914  	numSyms := int64(binary.LittleEndian.Uint32(symCountBuf[:]))
   915  	if 4+4*numMembers+4+2*numSyms > sz {
   916  		return fmt.Errorf("malformed PE archive second linker member in %s: %s", source, path)
   917  	}
   918  	return nil
   919  }
   920  
   921  // checkPEImportObject validates a PE short import library member
   922  // (IMPORT_OBJECT_HEADER: Sig1=0x0000, Sig2=0xFFFF, Version=0 followed by
   923  // null-terminated symbol and DLL name strings, which cannot contain .drectve).
   924  func checkPEImportObject(source, path string, r *io.SectionReader) error {
   925  	if r.Size() < 20 {
   926  		return fmt.Errorf("invalid PE import object header in %s: %s", source, path)
   927  	}
   928  	var hdr [20]byte
   929  	if _, err := r.ReadAt(hdr[:], 0); err != nil {
   930  		return fmt.Errorf("invalid PE import object header in %s: %s", source, path)
   931  	}
   932  	mach := binary.LittleEndian.Uint16(hdr[6:8])
   933  	if !isCOFFMachine(mach) {
   934  		return fmt.Errorf("invalid PE import object machine %#x in %s: %s", mach, source, path)
   935  	}
   936  	sizeOfData := binary.LittleEndian.Uint32(hdr[12:16])
   937  	if sizeOfData < 4 || sizeOfData > 1<<20 || 20+int64(sizeOfData) != r.Size() {
   938  		return fmt.Errorf("invalid PE import object size in %s: %s", source, path)
   939  	}
   940  	flags := binary.LittleEndian.Uint16(hdr[18:20])
   941  	typ := flags & 0x3
   942  	nameType := (flags >> 2) & 0x7
   943  	if typ > 2 || nameType > 3 || flags>>5 != 0 {
   944  		return fmt.Errorf("invalid PE import object type flags %#x in %s: %s", flags, source, path)
   945  	}
   946  	data := make([]byte, sizeOfData)
   947  	if _, err := io.ReadFull(io.NewSectionReader(r, 20, int64(sizeOfData)), data); err != nil {
   948  		return fmt.Errorf("cannot read PE import object data in %s: %s: %v", source, path, err)
   949  	}
   950  	sep := bytes.IndexByte(data, 0)
   951  	if sep <= 0 || sep >= len(data)-2 || data[len(data)-1] != 0 || bytes.IndexByte(data[sep+1:len(data)-1], 0) >= 0 {
   952  		return fmt.Errorf("invalid PE import object strings in %s: %s", source, path)
   953  	}
   954  	return nil
   955  }
   956  
   957  func checkLinkerBigArchive(source, path string, r *io.SectionReader, depth int) error {
   958  	if source == ".syso" {
   959  		return fmt.Errorf("archive not allowed as .syso in %s: %s", source, path)
   960  	}
   961  	if r.Size() < 128 {
   962  		return fmt.Errorf("malformed AIX big archive header in %s: %s", source, path)
   963  	}
   964  	var fhdr [128]byte
   965  	if _, err := r.ReadAt(fhdr[:], 0); err != nil {
   966  		return fmt.Errorf("malformed AIX big archive header in %s: %s", source, path)
   967  	}
   968  	parseDec := func(b []byte) (int64, error) {
   969  		return strconv.ParseInt(strings.TrimSpace(string(b)), 10, 64)
   970  	}
   971  	off, err := parseDec(fhdr[68:88])
   972  	if err != nil || off < 0 || (off > 0 && off < 128) || off > r.Size() {
   973  		return fmt.Errorf("malformed AIX big archive first member offset in %s: %s", source, path)
   974  	}
   975  	if off == 0 {
   976  		return nil
   977  	}
   978  	lastoff, err := parseDec(fhdr[88:108])
   979  	if err != nil || lastoff < off || lastoff > r.Size() {
   980  		return fmt.Errorf("malformed AIX big archive last member offset in %s: %s", source, path)
   981  	}
   982  	var mhdr [112]byte
   983  	for {
   984  		if off+112 > r.Size() {
   985  			return fmt.Errorf("malformed AIX big archive member header in %s: %s", source, path)
   986  		}
   987  		if _, err := r.ReadAt(mhdr[:], off); err != nil {
   988  			return fmt.Errorf("malformed AIX big archive member header in %s: %s", source, path)
   989  		}
   990  		sz, err := parseDec(mhdr[0:20])
   991  		if err != nil || sz < 0 {
   992  			return fmt.Errorf("malformed AIX big archive member size in %s: %s", source, path)
   993  		}
   994  		namlen, err := parseDec(mhdr[108:112])
   995  		if err != nil || namlen <= 0 || namlen > 4096 {
   996  			return fmt.Errorf("malformed AIX big archive member name length in %s: %s", source, path)
   997  		}
   998  		fileoff := off + 112 + namlen
   999  		if fileoff&1 != 0 {
  1000  			fileoff++
  1001  		}
  1002  		var fmag [2]byte
  1003  		if fileoff+2 > r.Size() || sz > r.Size()-(fileoff+2) {
  1004  			return fmt.Errorf("malformed AIX big archive member bounds in %s: %s", source, path)
  1005  		}
  1006  		if _, err := r.ReadAt(fmag[:], fileoff); err != nil || fmag[0] != '`' || fmag[1] != '\n' {
  1007  			return fmt.Errorf("malformed AIX big archive member magic in %s: %s", source, path)
  1008  		}
  1009  		fileoff += 2
  1010  		if namlen > 0 {
  1011  			if sz == 0 {
  1012  				return fmt.Errorf("empty AIX big archive member in %s: %s", source, path)
  1013  			}
  1014  			if err := checkLinkerObjectRegion(source, path, io.NewSectionReader(r, fileoff, sz), depth+1); err != nil {
  1015  				return err
  1016  			}
  1017  		}
  1018  		if off == lastoff {
  1019  			break
  1020  		}
  1021  		nextoff, err := parseDec(mhdr[20:40])
  1022  		if err != nil || nextoff < fileoff+sz || nextoff > lastoff {
  1023  			return fmt.Errorf("malformed AIX big archive next member offset in %s: %s", source, path)
  1024  		}
  1025  		off = nextoff
  1026  	}
  1027  	return nil
  1028  }
  1029  
  1030  // hasCOFFControlBeforeComment reports whether buf contains a non-whitespace C0
  1031  // control/null byte (or DEL) before any "/*" linker-script block comment can open.
  1032  // This rejects ASCII polyglot linker scripts starting with a COFF machine magic
  1033  // such as "db" (0x6264) or "dP" (0x5064) while allowing COFF objects with >= 256 sections.
  1034  func hasCOFFControlBeforeComment(buf []byte) bool {
  1035  	for i := 0; i < len(buf); i++ {
  1036  		if i+1 < len(buf) && buf[i] == '/' && buf[i+1] == '*' {
  1037  			return false
  1038  		}
  1039  		if buf[i] < 0x09 || (buf[i] > 0x0d && buf[i] < 0x20) || buf[i] == 0x7f {
  1040  			return true
  1041  		}
  1042  	}
  1043  	return false
  1044  }
  1045  
  1046  func checkLinkerObjectRegion(source, path string, r *io.SectionReader, depth int) error {
  1047  	if depth > 4 {
  1048  		return fmt.Errorf("nested archive/fat object too deep in %s: %s", source, path)
  1049  	}
  1050  	var hdr [64]byte
  1051  	n, _ := io.ReadFull(r, hdr[:])
  1052  	if n < 4 {
  1053  		return fmt.Errorf("invalid object file in %s: %s", source, path)
  1054  	}
  1055  	buf := hdr[:n]
  1056  
  1057  	if bytes.HasPrefix(buf, []byte("!<arch>\n")) {
  1058  		return checkLinkerArchive(source, path, r, depth)
  1059  	}
  1060  	if bytes.HasPrefix(buf, []byte("<bigaf>\n")) {
  1061  		return checkLinkerBigArchive(source, path, r, depth)
  1062  	}
  1063  
  1064  	// Check PE short import library member (IMPORT_OBJECT_HEADER: Sig1=0x0000, Sig2=0xFFFF, Version=0).
  1065  	// Leading 0x00 bytes at offset 0..1 prevent GNU ld ASCII linker-script polyglots.
  1066  	if source != ".syso" && n >= 6 && binary.LittleEndian.Uint16(buf[0:2]) == 0x0000 && binary.LittleEndian.Uint16(buf[2:4]) == 0xffff && binary.LittleEndian.Uint16(buf[4:6]) == 0 {
  1067  		return checkPEImportObject(source, path, r)
  1068  	}
  1069  
  1070  	// Check COFF object or PE image and validate .drectve and LTO sections via debug/pe.
  1071  	// Require buf[3] <= 1 for MZ (DOS header e_cblp < 0x200) and a non-whitespace control/null
  1072  	// byte in the 20-byte COFF FileHeader before any "/*" comment can open (plus structural
  1073  	// section/symbol table bounds checks), preventing an ASCII polyglot linker script starting
  1074  	// with "MZ" or an ASCII COFF machine magic (such as "db" or "dP") while allowing >= 256 sections.
  1075  	mach := binary.LittleEndian.Uint16(buf[0:2])
  1076  	isMZ := bytes.HasPrefix(buf, []byte("MZ")) && source != ".syso" && binary.LittleEndian.Uint16(buf[2:4]) < 0x200
  1077  	isCOFF := !isMZ && n >= 20 && isCOFFMachine(mach) && hasCOFFControlBeforeComment(buf[:20])
  1078  	if isCOFF || isMZ {
  1079  		var coffBase int64
  1080  		if isMZ {
  1081  			if n < 0x40 {
  1082  				return fmt.Errorf("invalid PE DOS header in %s: %s", source, path)
  1083  			}
  1084  			signoff := int64(binary.LittleEndian.Uint32(buf[0x3c:0x40]))
  1085  			if signoff < 0 || signoff+4 > r.Size() {
  1086  				return fmt.Errorf("invalid PE signature offset in %s: %s", source, path)
  1087  			}
  1088  			coffBase = signoff + 4
  1089  		}
  1090  		var rAt io.ReaderAt = r
  1091  		if !isMZ {
  1092  			rAt = coffReaderAt{r}
  1093  		}
  1094  		pf, err := pe.NewFile(rAt)
  1095  		if err != nil {
  1096  			return fmt.Errorf("invalid PE/COFF object in %s: %s: %v", source, path, err)
  1097  		}
  1098  		if !isCOFFMachine(pf.FileHeader.Machine) || (isMZ && pf.OptionalHeader == nil) || len(pf.Sections) == 0 {
  1099  			return fmt.Errorf("invalid PE/COFF header or missing sections in %s: %s", source, path)
  1100  		}
  1101  		hdrEnd := coffBase + 20 + int64(pf.FileHeader.SizeOfOptionalHeader) + int64(pf.FileHeader.NumberOfSections)*40
  1102  		if hdrEnd > r.Size() {
  1103  			return fmt.Errorf("truncated PE/COFF section table in %s: %s", source, path)
  1104  		}
  1105  		if pf.FileHeader.PointerToSymbolTable != 0 {
  1106  			symOff := int64(pf.FileHeader.PointerToSymbolTable)
  1107  			symEnd := symOff + int64(pf.FileHeader.NumberOfSymbols)*18
  1108  			if symOff < hdrEnd || symEnd > r.Size() {
  1109  				return fmt.Errorf("invalid PE/COFF symbol table bounds in %s: %s", source, path)
  1110  			}
  1111  		}
  1112  		for _, sec := range pf.Sections {
  1113  			if sec.Offset != 0 {
  1114  				secEnd := int64(sec.Offset) + int64(sec.Size)
  1115  				if secEnd > r.Size() || (sec.Size > 0 && int64(sec.Offset) < hdrEnd) {
  1116  					return fmt.Errorf("invalid PE/COFF section %q bounds in %s: %s", sec.Name, source, path)
  1117  				}
  1118  			}
  1119  			secName := strings.TrimSpace(sec.Name)
  1120  			if isDisallowedLTOSection(secName) {
  1121  				return fmt.Errorf("disallowed LTO section %q in %s: %s", secName, source, path)
  1122  			}
  1123  			if secName == ".drectve" {
  1124  				if sec.Size == 0 || sec.Size > 1<<20 {
  1125  					return fmt.Errorf("suspicious .drectve section size (%d) in %s: %s", sec.Size, source, path)
  1126  				}
  1127  				data, err := sec.Data()
  1128  				if err != nil {
  1129  					return fmt.Errorf("cannot read .drectve section in %s: %s: %v", source, path, err)
  1130  				}
  1131  				if err := checkDrectveDirectives(source, path, data); err != nil {
  1132  					return err
  1133  				}
  1134  			}
  1135  		}
  1136  		return nil
  1137  	}
  1138  
  1139  	// Check Mach-O object via debug/macho and reject LC_LINKER_OPTION (0x2d) and LTO segments/sections.
  1140  	magicLE := binary.LittleEndian.Uint32(buf[0:4])
  1141  	magicBE := binary.BigEndian.Uint32(buf[0:4])
  1142  	if magicLE == macho.Magic32 || magicLE == macho.Magic64 || magicBE == macho.Magic32 || magicBE == macho.Magic64 {
  1143  		mf, err := macho.NewFile(r)
  1144  		if err != nil {
  1145  			return fmt.Errorf("invalid Mach-O object in %s: %s: %v", source, path, err)
  1146  		}
  1147  		for _, l := range mf.Loads {
  1148  			if raw := l.Raw(); len(raw) >= 4 && mf.ByteOrder.Uint32(raw[:4]) == 0x2d { // LC_LINKER_OPTION
  1149  				if err := checkMachOLinkerOption(source, path, mf.ByteOrder, raw); err != nil {
  1150  					return err
  1151  				}
  1152  			}
  1153  			if seg, ok := l.(*macho.Segment); ok {
  1154  				if seg.Name == "__LLVM" || seg.Name == "__GNU_LTO" {
  1155  					return fmt.Errorf("disallowed LTO segment %q in %s: %s", seg.Name, source, path)
  1156  				}
  1157  			}
  1158  		}
  1159  		for _, sec := range mf.Sections {
  1160  			if sec.Seg == "__LLVM" || sec.Seg == "__GNU_LTO" || isDisallowedLTOSection(sec.Name) {
  1161  				return fmt.Errorf("disallowed LTO section %s,%s in %s: %s", sec.Seg, sec.Name, source, path)
  1162  			}
  1163  		}
  1164  		return nil
  1165  	}
  1166  
  1167  	// Check Universal (Fat) Mach-O (0xcafebabe) and validate each slice.
  1168  	// Note: slices inside a fat .a static library are !<arch>\n archives rather than
  1169  	// thin Mach-O files, so we read macho.FatArchHeader and recurse rather than calling macho.NewFatFile.
  1170  	if magicBE == macho.MagicFat {
  1171  		if n < 8 {
  1172  			return fmt.Errorf("truncated universal Mach-O header in %s: %s", source, path)
  1173  		}
  1174  		nfat := int(binary.BigEndian.Uint32(buf[4:8]))
  1175  		if nfat <= 0 || nfat > 32 {
  1176  			return fmt.Errorf("invalid universal Mach-O arch count in %s: %s", source, path)
  1177  		}
  1178  		sr := io.NewSectionReader(r, 8, int64(nfat)*20)
  1179  		for i := 0; i < nfat; i++ {
  1180  			var fa macho.FatArchHeader
  1181  			if err := binary.Read(sr, binary.BigEndian, &fa); err != nil {
  1182  				return fmt.Errorf("truncated universal Mach-O arch header in %s: %s", source, path)
  1183  			}
  1184  			sliceOff := int64(fa.Offset)
  1185  			sliceSz := int64(fa.Size)
  1186  			if sliceOff < 0 || sliceSz <= 0 || sliceOff+sliceSz > r.Size() {
  1187  				return fmt.Errorf("invalid universal Mach-O slice bounds in %s: %s", source, path)
  1188  			}
  1189  			if err := checkLinkerObjectRegion(source, path, io.NewSectionReader(r, sliceOff, sliceSz), depth+1); err != nil {
  1190  				return err
  1191  			}
  1192  		}
  1193  		return nil
  1194  	}
  1195  
  1196  	// Check ELF object via debug/elf and reject GCC/LLVM LTO sections.
  1197  	if bytes.HasPrefix(buf, []byte(elf.ELFMAG)) {
  1198  		ef, err := elf.NewFile(r)
  1199  		if err != nil {
  1200  			return fmt.Errorf("invalid ELF object in %s: %s: %v", source, path, err)
  1201  		}
  1202  		if ef.Type == elf.ET_REL && len(ef.Sections) == 0 {
  1203  			return fmt.Errorf("ELF relocatable object missing section headers in %s: %s", source, path)
  1204  		}
  1205  		for _, sec := range ef.Sections {
  1206  			if sec.Type == 0x6fff4c01 || sec.Type == 0x6fff4c04 { // SHT_LLVM_LINKER_OPTIONS, SHT_LLVM_DEPENDENT_LIBRARIES
  1207  				return fmt.Errorf("disallowed ELF embedded linker options section in %s: %s", source, path)
  1208  			}
  1209  			if sec.Type == 0x6fff4c0c { // SHT_LLVM_LTO
  1210  				return fmt.Errorf("disallowed LLVM LTO section in %s: %s", source, path)
  1211  			}
  1212  			if isDisallowedLTOSection(sec.Name) {
  1213  				return fmt.Errorf("disallowed LTO section %q in %s: %s", sec.Name, source, path)
  1214  			}
  1215  		}
  1216  		return nil
  1217  	}
  1218  
  1219  	// Check XCOFF object via internal/xcoff.
  1220  	magicBE16 := binary.BigEndian.Uint16(buf[0:2])
  1221  	if magicBE16 == xcoff.U802TOCMAGIC || magicBE16 == xcoff.U64_TOCMAGIC {
  1222  		if _, err := xcoff.NewFile(r); err != nil {
  1223  			return fmt.Errorf("invalid XCOFF object in %s: %s: %v", source, path, err)
  1224  		}
  1225  		return nil
  1226  	}
  1227  
  1228  	// Check Plan 9 object via debug/plan9obj.
  1229  	if magicBE == plan9obj.Magic386 || magicBE == plan9obj.MagicAMD64 || magicBE == plan9obj.MagicARM {
  1230  		if _, err := plan9obj.NewFile(r); err != nil {
  1231  			return fmt.Errorf("invalid Plan 9 object in %s: %s: %v", source, path, err)
  1232  		}
  1233  		return nil
  1234  	}
  1235  
  1236  	// Check WASM binary ("\x00asm\x01\x00\x00\x00").
  1237  	if bytes.HasPrefix(buf, []byte("\x00asm\x01\x00\x00\x00")) {
  1238  		return nil
  1239  	}
  1240  	return fmt.Errorf("invalid linker input file in %s: %s (unrecognized binary format)", source, path)
  1241  }
  1242  
  1243  // checkMachOLinkerOption validates an LC_LINKER_OPTION (0x2d) load command,
  1244  // allowing safe library (-l<name>) and framework (-framework/-weak_framework <name>)
  1245  // auto-link directives emitted by Clang (-fmodules) and Rust/Swift staticlibs
  1246  // while rejecting arbitrary linker flags (such as -lto_library or -lazy_library).
  1247  func checkMachOLinkerOption(source, path string, bo binary.ByteOrder, raw []byte) error {
  1248  	if len(raw) < 12 {
  1249  		return fmt.Errorf("malformed LC_LINKER_OPTION in %s: %s", source, path)
  1250  	}
  1251  	count := bo.Uint32(raw[8:12])
  1252  	if count == 0 || count > 2 {
  1253  		return fmt.Errorf("disallowed LC_LINKER_OPTION in %s: %s", source, path)
  1254  	}
  1255  	rest := raw[12:]
  1256  	opts := make([]string, 0, count)
  1257  	for range count {
  1258  		nul := bytes.IndexByte(rest, 0)
  1259  		if nul <= 0 {
  1260  			return fmt.Errorf("disallowed LC_LINKER_OPTION in %s: %s", source, path)
  1261  		}
  1262  		opts = append(opts, string(rest[:nul]))
  1263  		rest = rest[nul+1:]
  1264  	}
  1265  	for _, b := range rest {
  1266  		if b != 0 {
  1267  			return fmt.Errorf("disallowed LC_LINKER_OPTION in %s: %s", source, path)
  1268  		}
  1269  	}
  1270  	switch len(opts) {
  1271  	case 1:
  1272  		arg := opts[0]
  1273  		if !strings.HasPrefix(arg, "-l") || len(arg) <= 2 || !load.SafeArg(arg[2:]) || strings.ContainsAny(arg[2:], `:=/\`) {
  1274  			return fmt.Errorf("disallowed LC_LINKER_OPTION %q in %s: %s", arg, source, path)
  1275  		}
  1276  		for _, re := range invalidLinkerFlags {
  1277  			if re.FindString(arg) == arg {
  1278  				return fmt.Errorf("disallowed LC_LINKER_OPTION %q in %s: %s", arg, source, path)
  1279  			}
  1280  		}
  1281  		return nil
  1282  	case 2:
  1283  		if (opts[0] == "-framework" || opts[0] == "-weak_framework") && load.SafeArg(opts[1]) {
  1284  			if err := checkLinkerNonPathNonFile(source, opts[0]+" "+opts[1], opts[1]); err == nil {
  1285  				return nil
  1286  			}
  1287  		}
  1288  		return fmt.Errorf("disallowed LC_LINKER_OPTION %q in %s: %s", strings.Join(opts, " "), source, path)
  1289  	}
  1290  	return fmt.Errorf("disallowed LC_LINKER_OPTION in %s: %s", source, path)
  1291  }
  1292  
  1293  // checkDrectveDirectives validates the content of a COFF .drectve section,
  1294  // allowlisting known-safe MSVC and MinGW linker directives while rejecting
  1295  // anything that could inject dangerous linker behavior (e.g. --plugin, -T,
  1296  // --script, -L, --library-path, --dynamic-linker).
  1297  func checkDrectveDirectives(source, path string, data []byte) error {
  1298  	content := strings.TrimPrefix(string(data), "\xef\xbb\xbf")
  1299  	content = strings.TrimRight(content, "\x00 \t\r\n")
  1300  	if content == "" {
  1301  		return nil
  1302  	}
  1303  	tokens := tokenizeDrectve(content)
  1304  	for _, tok := range tokens {
  1305  		if !isAllowedDrectve(tok) {
  1306  			return fmt.Errorf("disallowed .drectve directive %q in %s: %s", tok, source, path)
  1307  		}
  1308  	}
  1309  	return nil
  1310  }
  1311  
  1312  const drectveSpace = " \t\r\n\v\f\x00"
  1313  
  1314  func tokenizeDrectve(s string) []string {
  1315  	var tokens []string
  1316  	s = strings.TrimLeft(s, drectveSpace)
  1317  	for len(s) > 0 {
  1318  		var tok strings.Builder
  1319  		inQuote := false
  1320  		i := 0
  1321  		for i < len(s) {
  1322  			if s[i] == '"' {
  1323  				inQuote = !inQuote
  1324  				i++
  1325  				continue
  1326  			}
  1327  			if !inQuote && strings.IndexByte(drectveSpace, s[i]) >= 0 {
  1328  				break
  1329  			}
  1330  			tok.WriteByte(s[i])
  1331  			i++
  1332  		}
  1333  		if tok.Len() > 0 {
  1334  			tokens = append(tokens, tok.String())
  1335  		}
  1336  		s = strings.TrimLeft(s[i:], drectveSpace)
  1337  	}
  1338  	return tokens
  1339  }
  1340  
  1341  var reDrectveSafeName = lazyregexp.New(`^[a-zA-Z0-9_.][a-zA-Z0-9_.+\-@$=]*$`)
  1342  
  1343  func isAllowedDrectve(tok string) bool {
  1344  	if strings.ContainsAny(tok, "\r\n\v\f\x00") {
  1345  		return false
  1346  	}
  1347  	norm := strings.ToUpper(tok)
  1348  	if strings.HasPrefix(norm, "-") && !strings.HasPrefix(norm, "--") {
  1349  		norm = "/" + norm[1:]
  1350  	}
  1351  	// MSVC, Clang, and MinGW directives: /FLAG:value or -flag:value
  1352  	if strings.HasPrefix(norm, "/DEFAULTLIB:") ||
  1353  		strings.HasPrefix(norm, "/DISALLOWLIB:") ||
  1354  		strings.HasPrefix(norm, "/EXPORT:") ||
  1355  		strings.HasPrefix(norm, "/INCLUDE:") ||
  1356  		strings.HasPrefix(norm, "/ALTERNATENAME:") ||
  1357  		strings.HasPrefix(norm, "/MERGE:") ||
  1358  		strings.HasPrefix(norm, "/SECTION:") ||
  1359  		strings.HasPrefix(norm, "/ALIGNCOMM:") ||
  1360  		strings.HasPrefix(norm, "/EXCLUDE-SYMBOLS:") ||
  1361  		strings.HasPrefix(norm, "/FAILIFMISMATCH:") ||
  1362  		strings.HasPrefix(norm, "/MANIFESTDEPENDENCY:") {
  1363  		val := tok[strings.IndexByte(tok, ':')+1:]
  1364  		val = strings.Trim(val, `"`)
  1365  		if val == "" {
  1366  			return false
  1367  		}
  1368  		if strings.ContainsAny(val, `/\`) && !strings.HasPrefix(norm, "/MANIFESTDEPENDENCY:") {
  1369  			return false
  1370  		}
  1371  		if (strings.HasPrefix(norm, "/DEFAULTLIB:") || strings.HasPrefix(norm, "/DISALLOWLIB:")) && (strings.Contains(val, ":") || strings.HasPrefix(val, "@")) {
  1372  			return false
  1373  		}
  1374  		if strings.Contains(val, "..") {
  1375  			return false
  1376  		}
  1377  		return true
  1378  	}
  1379  	// Flags with no value (or optional library name on NODEFAULTLIB) that are safe to pass through.
  1380  	if norm == "/NODEFAULTLIB" {
  1381  		return true
  1382  	}
  1383  	if strings.HasPrefix(norm, "/NODEFAULTLIB:") {
  1384  		val := strings.Trim(tok[strings.IndexByte(tok, ':')+1:], `"`)
  1385  		return val != "" && !strings.ContainsAny(val, `/\:`) && !strings.HasPrefix(val, "@") && !strings.Contains(val, "..")
  1386  	}
  1387  	if norm == "/SAFESEH" || norm == "/SAFESEH:NO" {
  1388  		return true
  1389  	}
  1390  	if norm == "/GUARD:CF" || norm == "/GUARD:NO" || norm == "/GUARD:EHCONT" || norm == "/GUARD:LONGJMP" {
  1391  		return true
  1392  	}
  1393  	if norm == "/DYNAMICBASE" || norm == "/DYNAMICBASE:NO" ||
  1394  		norm == "/NXCOMPAT" || norm == "/NXCOMPAT:NO" ||
  1395  		norm == "/CETCOMPAT" || norm == "/CETCOMPAT:NO" ||
  1396  		norm == "/HIGHENTROPYVA" || norm == "/HIGHENTROPYVA:NO" ||
  1397  		norm == "/LARGEADDRESSAWARE" || norm == "/LARGEADDRESSAWARE:NO" ||
  1398  		norm == "/TSAWARE" || norm == "/TSAWARE:NO" ||
  1399  		norm == "/EXPORT-ALL-SYMBOLS" || norm == "/EXCLUDE-ALL-SYMBOLS" {
  1400  		return true
  1401  	}
  1402  	// MinGW-style directives
  1403  	if strings.HasPrefix(tok, "-l") && len(tok) > 2 {
  1404  		libName := tok[2:]
  1405  		return reDrectveSafeName.MatchString(libName) && !strings.Contains(libName, "..")
  1406  	}
  1407  	switch tok {
  1408  	case "--enable-auto-import", "--disable-auto-import",
  1409  		"--enable-runtime-pseudo-reloc", "--disable-runtime-pseudo-reloc",
  1410  		"--enable-stdcall-fixup", "--disable-stdcall-fixup",
  1411  		"--export-all-symbols", "--exclude-all-symbols":
  1412  		return true
  1413  	}
  1414  	return false
  1415  }
  1416  
  1417  func checkPkgConfigFlags(name, source string, list []string) error {
  1418  	checkOverrides := false
  1419  	return checkFlags(name, source, list, nil, validPkgConfigFlags, nil, nil, checkOverrides)
  1420  }
  1421  
  1422  func validPkgConfigName(pkg string) bool {
  1423  	if !load.SafeArg(pkg) || !utf8.ValidString(pkg) {
  1424  		return false
  1425  	}
  1426  	if strings.ContainsAny(pkg, `/\:`) || strings.Contains(pkg, "..") {
  1427  		return false
  1428  	}
  1429  	fields := strings.FieldsFunc(pkg, func(r rune) bool {
  1430  		return r == ',' || unicode.IsSpace(r)
  1431  	})
  1432  	if len(fields) == 0 {
  1433  		return false
  1434  	}
  1435  	for _, field := range fields {
  1436  		lower := strings.ToLower(field)
  1437  		if strings.HasSuffix(lower, ".pc") {
  1438  			return false
  1439  		}
  1440  		for i := range len(lower) {
  1441  			if strings.IndexByte("<>=!", lower[i]) >= 0 && strings.HasSuffix(lower[:i], ".pc") {
  1442  				return false
  1443  			}
  1444  		}
  1445  	}
  1446  	return true
  1447  }
  1448  
  1449  // checkCompilerFlagsForInternalLink returns an error if 'list'
  1450  // contains a flag or flags that may not be fully supported by
  1451  // internal linking (meaning that we should punt the link to the
  1452  // external linker).
  1453  func checkCompilerFlagsForInternalLink(name, source string, list []string) error {
  1454  	checkOverrides := false
  1455  	if err := checkFlags(name, source, list, invalidCompilerFlags, validCompilerFlags, nil, validCompilerFlagsWithNextArg, checkOverrides); err != nil {
  1456  		return err
  1457  	}
  1458  	// Currently the only flag on the allow list that causes problems
  1459  	// for the linker is "-flto"; check for it manually here.
  1460  	// Also check for -static/--static, which some toolchains accept
  1461  	// as a compiler flag.
  1462  	for _, fl := range list {
  1463  		if strings.HasPrefix(fl, "-flto") {
  1464  			return fmt.Errorf("flag %q triggers external linking", fl)
  1465  		}
  1466  		if fl == "-static" || fl == "--static" {
  1467  			return fmt.Errorf("flag %q triggers external linking", fl)
  1468  		}
  1469  	}
  1470  	return nil
  1471  }
  1472  
  1473  // checkLinkerFlagsForInternalLink returns an error if 'list'
  1474  // contains linker flags that are not compatible with internal linking.
  1475  func checkLinkerFlagsForInternalLink(name, source string, list []string) error {
  1476  	checkOverrides := false
  1477  	if err := checkFlags(name, source, list, invalidLinkerFlags, validLinkerFlags, recombinedLinkerFlagsWithNextArg, validLinkerFlagsWithNextArg, checkOverrides); err != nil {
  1478  		return err
  1479  	}
  1480  	// Flags that force static linking require the external linker
  1481  	// to resolve libc symbols. See #77768.
  1482  	for _, fl := range list {
  1483  		if fl == "-static" || fl == "--static" ||
  1484  			fl == "-Wl,-static" || fl == "-Wl,--static" ||
  1485  			fl == "-Wl,-Bstatic" {
  1486  			return fmt.Errorf("flag %q triggers external linking", fl)
  1487  		}
  1488  	}
  1489  	return nil
  1490  }
  1491  
  1492  func checkFlags(name, source string, list []string, invalid, valid []*lazyregexp.Regexp, recombineNext, validNext []string, checkOverrides bool) error {
  1493  	// Let users override rules with $CGO_CFLAGS_ALLOW, $CGO_CFLAGS_DISALLOW, etc.
  1494  	var (
  1495  		allow    *regexp.Regexp
  1496  		disallow *regexp.Regexp
  1497  	)
  1498  	if checkOverrides {
  1499  		if env := cfg.Getenv("CGO_" + name + "_ALLOW"); env != "" {
  1500  			r, err := regexp.Compile(env)
  1501  			if err != nil {
  1502  				return fmt.Errorf("parsing $CGO_%s_ALLOW: %v", name, err)
  1503  			}
  1504  			allow = r
  1505  		}
  1506  		if env := cfg.Getenv("CGO_" + name + "_DISALLOW"); env != "" {
  1507  			r, err := regexp.Compile(env)
  1508  			if err != nil {
  1509  				return fmt.Errorf("parsing $CGO_%s_DISALLOW: %v", name, err)
  1510  			}
  1511  			disallow = r
  1512  		}
  1513  	}
  1514  
  1515  Args:
  1516  	for i := 0; i < len(list); i++ {
  1517  		arg := list[i]
  1518  		if disallow != nil && disallow.FindString(arg) == arg {
  1519  			goto Bad
  1520  		}
  1521  		if allow != nil && allow.FindString(arg) == arg {
  1522  			continue Args
  1523  		}
  1524  		for _, re := range invalid {
  1525  			if re.FindString(arg) == arg { // must be complete match
  1526  				goto Bad
  1527  			}
  1528  		}
  1529  		for _, re := range valid {
  1530  			if match := re.FindString(arg); match == arg { // must be complete match
  1531  				continue Args
  1532  			} else if strings.HasPrefix(arg, "-Wl,--push-state,") {
  1533  				// Examples for --push-state are written
  1534  				//     -Wl,--push-state,--as-needed
  1535  				// Support other commands in the same -Wl arg.
  1536  				args := strings.Split(arg, ",")
  1537  				for _, a := range args[1:] {
  1538  					a = "-Wl," + a
  1539  					var found bool
  1540  					for _, re := range valid {
  1541  						if re.FindString(a) == a {
  1542  							found = true
  1543  							break
  1544  						}
  1545  					}
  1546  					if !found {
  1547  						goto Bad
  1548  					}
  1549  					for _, re := range invalid {
  1550  						if re.FindString(a) == a {
  1551  							goto Bad
  1552  						}
  1553  					}
  1554  				}
  1555  				continue Args
  1556  			}
  1557  		}
  1558  		if slices.Contains(recombineNext, arg) && i+1 < len(list) {
  1559  			combined := arg + list[i+1]
  1560  			if disallow != nil && disallow.FindString(combined) == combined {
  1561  				goto Bad
  1562  			}
  1563  			if allow == nil || allow.FindString(combined) != combined {
  1564  				for _, re := range invalid {
  1565  					if re.FindString(combined) == combined {
  1566  						goto Bad
  1567  					}
  1568  				}
  1569  			}
  1570  		}
  1571  		for _, x := range validNext {
  1572  			if arg == x {
  1573  				if arg == "-x" {
  1574  					if i+1 < len(list) && validCompilerXLang.MatchString(list[i+1]) {
  1575  						i++
  1576  						continue Args
  1577  					}
  1578  					if i+1 < len(list) {
  1579  						return fmt.Errorf("invalid flag in %s: %s %s (see https://go.dev/s/invalidflag)", source, arg, list[i+1])
  1580  					}
  1581  					return fmt.Errorf("invalid flag in %s: %s without argument (see https://go.dev/s/invalidflag)", source, arg)
  1582  				}
  1583  				if strings.HasPrefix(arg, "-Wl,") {
  1584  					// Permit -Wl,-framework -Wl,name.
  1585  					if i+1 < len(list) &&
  1586  						strings.HasPrefix(list[i+1], "-Wl,") &&
  1587  						load.SafeArg(list[i+1][4:]) &&
  1588  						!strings.Contains(list[i+1][4:], ",") {
  1589  						i++
  1590  						continue Args
  1591  					}
  1592  					// Permit -Wl,-R /foo and -Wl,-R foo.
  1593  					if arg == "-Wl,-R" && i+1 < len(list) && load.SafeArg(list[i+1]) {
  1594  						i++
  1595  						continue Args
  1596  					}
  1597  					if i+1 < len(list) {
  1598  						return fmt.Errorf("invalid flag in %s: %s %s (see https://go.dev/s/invalidflag)", source, arg, list[i+1])
  1599  					}
  1600  					return fmt.Errorf("invalid flag in %s: %s without argument (see https://go.dev/s/invalidflag)", source, arg)
  1601  				}
  1602  				if arg == "-l" {
  1603  					if i+1 < len(list) && load.SafeArg(list[i+1]) && !strings.ContainsAny(list[i+1], `:=/\`) {
  1604  						i++
  1605  						continue Args
  1606  					}
  1607  					if i+1 < len(list) {
  1608  						return fmt.Errorf("invalid flag in %s: %s %s (see https://go.dev/s/invalidflag)", source, arg, list[i+1])
  1609  					}
  1610  					return fmt.Errorf("invalid flag in %s: %s without argument (see https://go.dev/s/invalidflag)", source, arg)
  1611  				}
  1612  				if i+1 < len(list) && load.SafeArg(list[i+1]) {
  1613  					i++
  1614  					continue Args
  1615  				}
  1616  
  1617  				// Permit -I= /path, -I $SYSROOT.
  1618  				if i+1 < len(list) && arg == "-I" {
  1619  					if (strings.HasPrefix(list[i+1], "=") || strings.HasPrefix(list[i+1], "$SYSROOT")) &&
  1620  						load.SafeArg(list[i+1][1:]) {
  1621  						i++
  1622  						continue Args
  1623  					}
  1624  				}
  1625  
  1626  				if i+1 < len(list) {
  1627  					return fmt.Errorf("invalid flag in %s: %s %s (see https://go.dev/s/invalidflag)", source, arg, list[i+1])
  1628  				}
  1629  				return fmt.Errorf("invalid flag in %s: %s without argument (see https://go.dev/s/invalidflag)", source, arg)
  1630  			}
  1631  		}
  1632  	Bad:
  1633  		return fmt.Errorf("invalid flag in %s: %s (see https://go.dev/s/invalidflag)", source, arg)
  1634  	}
  1635  	return nil
  1636  }
  1637  

View as plain text