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

View as plain text