Source file src/cmd/go/internal/work/security_test.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  package work
     6  
     7  import (
     8  	"encoding/binary"
     9  	"fmt"
    10  	"os"
    11  	"path/filepath"
    12  	"strings"
    13  	"testing"
    14  
    15  	"cmd/go/internal/cfg"
    16  	"cmd/go/internal/load"
    17  )
    18  
    19  var goodCompilerFlags = [][]string{
    20  	{"-DFOO"},
    21  	{"-Dfoo=bar"},
    22  	{"-Ufoo"},
    23  	{"-Ufoo1"},
    24  	{"-F/Qt"},
    25  	{"-F", "/Qt"},
    26  	{"-I/"},
    27  	{"-I/etc/passwd"},
    28  	{"-I."},
    29  	{"-O"},
    30  	{"-O2"},
    31  	{"-Osmall"},
    32  	{"-W"},
    33  	{"-Wall"},
    34  	{"-Wp,-Dfoo=bar"},
    35  	{"-Wp,-Ufoo"},
    36  	{"-Wp,-Dfoo1"},
    37  	{"-Wp,-Ufoo1"},
    38  	{"-flto"},
    39  	{"-fobjc-arc"},
    40  	{"-fno-objc-arc"},
    41  	{"-fomit-frame-pointer"},
    42  	{"-fno-omit-frame-pointer"},
    43  	{"-fpic"},
    44  	{"-fno-pic"},
    45  	{"-fPIC"},
    46  	{"-fno-PIC"},
    47  	{"-fpie"},
    48  	{"-fno-pie"},
    49  	{"-fPIE"},
    50  	{"-fno-PIE"},
    51  	{"-fsplit-stack"},
    52  	{"-fno-split-stack"},
    53  	{"-fstack-xxx"},
    54  	{"-fno-stack-xxx"},
    55  	{"-fsanitize=hands"},
    56  	{"-ftls-model=local-dynamic"},
    57  	{"-g"},
    58  	{"-ggdb"},
    59  	{"-mabi=lp64d"},
    60  	{"-march=souza"},
    61  	{"-mcmodel=medium"},
    62  	{"-mcpu=123"},
    63  	{"-mfpu=123"},
    64  	{"-mtls-dialect=gnu"},
    65  	{"-mtls-dialect=gnu2"},
    66  	{"-mtls-dialect=trad"},
    67  	{"-mtls-dialect=desc"},
    68  	{"-mtls-dialect=xyz"},
    69  	{"-msimd=lasx"},
    70  	{"-msimd=xyz"},
    71  	{"-mdouble-float"},
    72  	{"-mrelax"},
    73  	{"-mstrict-align"},
    74  	{"-mlsx"},
    75  	{"-mlasx"},
    76  	{"-mfrecipe"},
    77  	{"-mlam-bh"},
    78  	{"-mlamcas"},
    79  	{"-mld-seq-sa"},
    80  	{"-mno-relax"},
    81  	{"-mno-strict-align"},
    82  	{"-mno-lsx"},
    83  	{"-mno-lasx"},
    84  	{"-mno-frecipe"},
    85  	{"-mno-lam-bh"},
    86  	{"-mno-lamcas"},
    87  	{"-mno-ld-seq-sa"},
    88  	{"-mlarge-data-threshold=16"},
    89  	{"-mtune=happybirthday"},
    90  	{"-mstack-overflow"},
    91  	{"-mno-stack-overflow"},
    92  	{"-mmacosx-version"},
    93  	{"-mnop-fun-dllimport"},
    94  	{"-pthread"},
    95  	{"-std=c99"},
    96  	{"-xc"},
    97  	{"-D", "FOO"},
    98  	{"-D", "foo=bar"},
    99  	{"-I", "."},
   100  	{"-I", "/etc/passwd"},
   101  	{"-I", "世界"},
   102  	{"-I", "=/usr/include/libxml2"},
   103  	{"-I", "dir"},
   104  	{"-I", "$SYSROOT/dir"},
   105  	{"-isystem", "/usr/include/mozjs-68"},
   106  	{"-include", "/usr/include/mozjs-68/RequiredDefines.h"},
   107  	{"-framework", "Chocolate"},
   108  	{"-isysroot", "/tmp"},
   109  	{"-x", "c"},
   110  	{"-v"},
   111  }
   112  
   113  var badCompilerFlags = [][]string{
   114  	{"-D@X"},
   115  	{"-D-X"},
   116  	{"-Ufoo=bar"},
   117  	{"-F@dir"},
   118  	{"-F-dir"},
   119  	{"-I@dir"},
   120  	{"-I-dir"},
   121  	{"-O@1"},
   122  	{"-Wa,-foo"},
   123  	{"-W@foo"},
   124  	{"-Wp,-DX,-D@X"},
   125  	{"-Wp,-UX,-U@X"},
   126  	{"-g@gdb"},
   127  	{"-g-gdb"},
   128  	{"-march=@dawn"},
   129  	{"-march=-dawn"},
   130  	{"-mcmodel=@model"},
   131  	{"-mfpu=@0"},
   132  	{"-mfpu=-0"},
   133  	{"-mlarge-data-threshold=@12"},
   134  	{"-mtls-dialect=@gnu"},
   135  	{"-mtls-dialect=-gnu"},
   136  	{"-msimd=@none"},
   137  	{"-msimd=-none"},
   138  	{"-std=@c99"},
   139  	{"-std=-c99"},
   140  	{"-x@c"},
   141  	{"-x-c"},
   142  	{"-D", "@foo"},
   143  	{"-D", "-foo"},
   144  	{"-I", "@foo"},
   145  	{"-I", "-foo"},
   146  	{"-I", "=@obj"},
   147  	{"-include", "@foo"},
   148  	{"-framework", "-Caffeine"},
   149  	{"-framework", "@Home"},
   150  	{"-x", "--c"},
   151  	{"-x", "@obj"},
   152  	{"-xada"},
   153  	{"-x", "ada"},
   154  	{"-x", "none"},
   155  	{"--sysroot=/tmp"},
   156  	{"--sysroot", "/tmp"},
   157  	{"-target", "x86_64-scei-ps4"},
   158  	{"-target", "x86_64-linux-gnu"},
   159  	{"-fsanitize=@foo"},
   160  	{"-fsanitize=-foo"},
   161  	{"-gnatO"},
   162  	{"-gnatO", "foo.o"},
   163  	{"-gen-cdb-fragment-path"},
   164  	{"-gen-cdb-fragment-path", "."},
   165  }
   166  
   167  func TestCheckCompilerFlags(t *testing.T) {
   168  	for _, f := range goodCompilerFlags {
   169  		if err := checkCompilerFlags("test", "test", f); err != nil {
   170  			t.Errorf("unexpected error for %q: %v", f, err)
   171  		}
   172  	}
   173  	for _, f := range badCompilerFlags {
   174  		if err := checkCompilerFlags("test", "test", f); err == nil {
   175  			t.Errorf("missing error for %q", f)
   176  		}
   177  	}
   178  }
   179  
   180  var goodLinkerFlags = [][]string{
   181  	{"-Fbar"},
   182  	{"-lbar"},
   183  	{"-Lbar"},
   184  	{"-fpic"},
   185  	{"-fno-pic"},
   186  	{"-fPIC"},
   187  	{"-fno-PIC"},
   188  	{"-fpie"},
   189  	{"-fno-pie"},
   190  	{"-fPIE"},
   191  	{"-fno-PIE"},
   192  	{"-fsanitize=hands"},
   193  	{"-g"},
   194  	{"-ggdb"},
   195  	{"-march=souza"},
   196  	{"-mcpu=123"},
   197  	{"-mfpu=123"},
   198  	{"-mtune=happybirthday"},
   199  	{"-pic"},
   200  	{"-pthread"},
   201  	{"-Wl,--hash-style=both"},
   202  	{"-Wl,-rpath,foo"},
   203  	{"-Wl,-rpath,$ORIGIN/foo"},
   204  	{"-Wl,-R", "/foo"},
   205  	{"-Wl,-R", "foo"},
   206  	{"-Wl,-R,foo"},
   207  	{"-Wl,-R=foo"},
   208  	{"-Wl,--just-symbols=foo"},
   209  	{"-Wl,--just-symbols,foo"},
   210  	{"-Wl,--warn-error"},
   211  	{"-Wl,--no-warn-error"},
   212  	{"-Wl,--warn-backrefs-exclude=foo*"},
   213  	{"-Wl,-subsystem,console"},
   214  	{"-Wl,--subsystem,console"},
   215  	{"foo.so"},
   216  	{"_世界.dll"},
   217  	{"./x.o"},
   218  	{"libcgosotest.dylib"},
   219  	{"-F", "framework"},
   220  	{"-l", "."},
   221  	{"-l", "世界"},
   222  	{"-L", "framework"},
   223  	{"-framework", "Chocolate"},
   224  	{"-v"},
   225  	{"-Wl,-sectcreate,__TEXT,__info_plist,${SRCDIR}/Info.plist"},
   226  	{"-Wl,-framework", "-Wl,Chocolate"},
   227  	{"-Wl,-framework,Chocolate"},
   228  	{"-Wl,-unresolved-symbols=ignore-all"},
   229  	{"-Wl,-z,relro"},
   230  	{"-Wl,-z,relro,-z,now"},
   231  	{"-Wl,-z,now"},
   232  	{"-Wl,-z,noexecstack"},
   233  	{"libcgotbdtest.tbd"},
   234  	{"./libcgotbdtest.tbd"},
   235  	{"-Wl,--push-state"},
   236  	{"-Wl,--pop-state"},
   237  	{"-Wl,--push-state,--as-needed"},
   238  	{"-Wl,--push-state,--no-as-needed,-Bstatic"},
   239  	{"-Wl,--just-symbols,."},
   240  	{"-Wl,-framework,."},
   241  	{"-Wl,-rpath,."},
   242  	{"-Wl,-rpath-link,."},
   243  	{"-Wl,-sectcreate,.,.,."},
   244  	{"-Wl,-syslibroot,."},
   245  	{"-Wl,-undefined,."},
   246  }
   247  
   248  var badLinkerFlags = [][]string{
   249  	{"-DFOO"},
   250  	{"-Dfoo=bar"},
   251  	{"-W"},
   252  	{"-Wall"},
   253  	{"-fobjc-arc"},
   254  	{"-fno-objc-arc"},
   255  	{"-fomit-frame-pointer"},
   256  	{"-fno-omit-frame-pointer"},
   257  	{"-fsplit-stack"},
   258  	{"-fno-split-stack"},
   259  	{"-fstack-xxx"},
   260  	{"-fno-stack-xxx"},
   261  	{"-mstack-overflow"},
   262  	{"-mno-stack-overflow"},
   263  	{"-mnop-fun-dllimport"},
   264  	{"-std=c99"},
   265  	{"-xc"},
   266  	{"-D", "FOO"},
   267  	{"-D", "foo=bar"},
   268  	{"-I", "FOO"},
   269  	{"-L", "@foo"},
   270  	{"-L", "-foo"},
   271  	{"-x", "c"},
   272  	{"-D@X"},
   273  	{"-D-X"},
   274  	{"-I@dir"},
   275  	{"-I-dir"},
   276  	{"-O@1"},
   277  	{"-Wa,-foo"},
   278  	{"-W@foo"},
   279  	{"-g@gdb"},
   280  	{"-g-gdb"},
   281  	{"-march=@dawn"},
   282  	{"-march=-dawn"},
   283  	{"-std=@c99"},
   284  	{"-std=-c99"},
   285  	{"-x@c"},
   286  	{"-x-c"},
   287  	{"-D", "@foo"},
   288  	{"-D", "-foo"},
   289  	{"-I", "@foo"},
   290  	{"-I", "-foo"},
   291  	{"-l", "@foo"},
   292  	{"-l", "-foo"},
   293  	{"-l", "to_library"},
   294  	{"-l", "azy_library"},
   295  	{"-l", "azy_framework"},
   296  	{"-l", "oad_hidden"},
   297  	{"-l", "ibrary"},
   298  	{"-l", "ibrary=:pwn.ld"},
   299  	{"-l", "ibrary-path"},
   300  	{"-l", "ibrary-path=/tmp"},
   301  	{"-lazy_library"},
   302  	{"-lazy_framework"},
   303  	{"-load_hidden"},
   304  	{"-library"},
   305  	{"-library=:pwn.ld"},
   306  	{"-library-path"},
   307  	{"-library-path=/tmp"},
   308  	{"-framework", "-Caffeine"},
   309  	{"-framework", "@Home"},
   310  	{"-Wl,-framework,-Caffeine"},
   311  	{"-Wl,-framework", "-Wl,@Home"},
   312  	{"-Wl,-framework", "@Home"},
   313  	{"-Wl,-framework", "Chocolate"},
   314  	{"-Wl,-framework,/tmp/pwn.ld"},
   315  	{"-Wl,-framework", "-Wl,/tmp/pwn.ld"},
   316  	{"-framework", "./pwn.ld"},
   317  	{"-framework", "/tmp/pwn.ld"},
   318  	{"-Wl,-framework,Chocolate,@Home"},
   319  	{"-Wl,--hash-style=foo"},
   320  	{"-x", "--c"},
   321  	{"-x", "@obj"},
   322  	{"-Wl,-rpath,@foo"},
   323  	{"-Wl,-rpath", "foo"},
   324  	{"-Wl,-R,foo,bar"},
   325  	{"-Wl,-R,@foo"},
   326  	{"-Wl,--just-symbols,@foo"},
   327  	{"-Wl,--just-symbols", "foo"},
   328  	{"-Wl,-undefined", "foo"},
   329  	{"-Wl,-undefined,/tmp/pwn.ld"},
   330  	{"-Wl,-undefined", "-Wl,/tmp/pwn.ld"},
   331  	{"-Wl,--push-state,-undefined=/tmp/pwn.ld"},
   332  	{"../x.o"},
   333  	{"-Wl,-R,"},
   334  	{"-Wl,-R="},
   335  	{"-Wl,-O"},
   336  	{"-Wl,-e="},
   337  	{"-Wl,-e,"},
   338  	{"-Wl,-R,-flag"},
   339  	{"-Wl,-R=-flag"},
   340  	{"-Wl,-R=@foo"},
   341  	{"-Wl,-R==foo"},
   342  	{"-Wl,-R,=foo"},
   343  	{"-Wl,--warn-backrefs-exclude"},
   344  	{"-Wl,--push-state,--warn-backrefs-exclude"},
   345  	{"-Wl,--push-state,"},
   346  	{"-Wl,--push-state,@foo"},
   347  	{"-fplugin=./-Wl,--push-state,-R.so"},
   348  	{"./-Wl,--push-state,-R.c"},
   349  	{"--sysroot=/tmp"},
   350  	{"--sysroot", "/tmp"},
   351  	{"-target", "x86_64-scei-ps4"},
   352  	{"-target", "x86_64-linux-gnu"},
   353  	{"-fsanitize=@foo"},
   354  	{"-fsanitize=-foo"},
   355  	{"-gnatO"},
   356  	{"-gnatO", "-L", "foo.ld"},
   357  	{"-gen-cdb-fragment-path"},
   358  	{"-gen-cdb-fragment-path", "-Wl,-framework", "-Wl,foo.so"},
   359  	{"-l:pwn.ld"},
   360  	{"-l:libc.a"},
   361  	{"-lfoo:bar"},
   362  	{"-lfoo=bar"},
   363  	{"-lsub/foo"},
   364  	{`-lsub\foo`},
   365  	{"-l", ":pwn.ld"},
   366  	{"-l", "foo:bar"},
   367  	{"-l", "foo=bar"},
   368  	{"-l", "/etc/passwd"},
   369  	{"-l", "sub/foo"},
   370  	{"-l", `sub\foo`},
   371  }
   372  
   373  func TestCheckLinkerFlags(t *testing.T) {
   374  	for _, f := range goodLinkerFlags {
   375  		if err := checkLinkerFlags("test", "test", f); err != nil {
   376  			t.Errorf("unexpected error for %q: %v", f, err)
   377  		}
   378  	}
   379  	for _, f := range badLinkerFlags {
   380  		if err := checkLinkerFlags("test", "test", f); err == nil {
   381  			t.Errorf("missing error for %q", f)
   382  		}
   383  	}
   384  }
   385  
   386  func TestCheckLinkerSysrootFlags(t *testing.T) {
   387  	dir := t.TempDir()
   388  	script := filepath.Join(dir, "script.ld")
   389  	if err := os.WriteFile(script, []byte("PLUGIN(\"/tmp/pwn.so\")\n"), 0644); err != nil {
   390  		t.Fatal(err)
   391  	}
   392  	for _, f := range [][]string{
   393  		{"-isysroot", dir},
   394  		{"-Wl,-syslibroot," + dir},
   395  		{"-Wl,-syslibroot=" + dir},
   396  	} {
   397  		if err := checkLinkerFlags("test", "test", f); err != nil {
   398  			t.Errorf("unexpected error for %q: %v", f, err)
   399  		}
   400  	}
   401  	for _, f := range [][]string{
   402  		{"-isysroot", script},
   403  		{"-Wl,-syslibroot," + script},
   404  		{"-Wl,-syslibroot=" + script},
   405  		{"-Wl,--push-state,-syslibroot=" + script},
   406  	} {
   407  		if err := checkLinkerFlags("test", "test", f); err == nil {
   408  			t.Errorf("missing error for %q", f)
   409  		}
   410  	}
   411  }
   412  
   413  func TestCheckGCCSpecFiles(t *testing.T) {
   414  	// Compiler invocations always pass -c, which never evaluates GCC's
   415  	// *link_command spec (%:include(libsanitizer.spec) / %:include(libgomp.spec)).
   416  	cwdSpecDir := t.TempDir()
   417  	if err := os.WriteFile(filepath.Join(cwdSpecDir, "libsanitizer.spec"), []byte("*link_libubsan:\n"), 0644); err != nil {
   418  		t.Fatal(err)
   419  	}
   420  	t.Chdir(cwdSpecDir)
   421  	for _, f := range [][]string{
   422  		{"-fsanitize=memory"},
   423  		{"-fsanitize=undefined"},
   424  		{"-fopenmp"},
   425  	} {
   426  		if err := checkCompilerFlags("test", "test", f); err != nil {
   427  			t.Errorf("unexpected error for compiler flag %q with libsanitizer.spec in CWD: %v", f, err)
   428  		}
   429  	}
   430  
   431  	// Verify -L, -isysroot, and -Wl,-syslibroot reject directories containing
   432  	// GCC spec files (directly, in subdirectories, or in multilib sibling dirs).
   433  	specDir := t.TempDir()
   434  	if err := os.WriteFile(filepath.Join(specDir, "libgomp.spec"), []byte("*link_gomp: %{!static:}\n"), 0644); err != nil {
   435  		t.Fatal(err)
   436  	}
   437  	for _, f := range [][]string{
   438  		{"-L" + specDir, "-fopenmp"},
   439  		{"-L", specDir, "-fopenmp"},
   440  		{"-L=" + specDir, "-fopenmp"},
   441  		{"-L$SYSROOT" + specDir, "-fopenmp"},
   442  		{"-isysroot", specDir, "-fopenmp"},
   443  		{"-Wl,-syslibroot," + specDir, "-fopenmp"},
   444  		{"-Wl,--push-state,-syslibroot=" + specDir, "-fopenmp"},
   445  	} {
   446  		if err := checkLinkerFlags("test", "test", f); err == nil {
   447  			t.Errorf("expected error for GCC spec file in %q, got nil", f)
   448  		}
   449  	}
   450  
   451  	// Subdirectory spec file inside sysroot or -L directory.
   452  	nestedRoot := t.TempDir()
   453  	nestedLib := filepath.Join(nestedRoot, "usr", "lib")
   454  	if err := os.MkdirAll(nestedLib, 0755); err != nil {
   455  		t.Fatal(err)
   456  	}
   457  	if err := os.WriteFile(filepath.Join(nestedLib, "libsanitizer.spec"), []byte("*link_libasan: -lasan\n"), 0644); err != nil {
   458  		t.Fatal(err)
   459  	}
   460  	if err := checkLinkerFlags("test", "test", []string{"-L" + nestedRoot, "-fsanitize=address"}); err == nil {
   461  		t.Errorf("expected error for nested spec file in -L directory, got nil")
   462  	}
   463  
   464  	// Multilib sibling directory (../lib64/libgomp.spec relative to -L<dir>/sub,
   465  	// both when <dir>/sub exists and when <dir>/nonexistent does not exist).
   466  	multiRoot := t.TempDir()
   467  	subDir := filepath.Join(multiRoot, "sub")
   468  	lib64Dir := filepath.Join(multiRoot, "lib64")
   469  	if err := os.MkdirAll(subDir, 0755); err != nil {
   470  		t.Fatal(err)
   471  	}
   472  	if err := os.MkdirAll(lib64Dir, 0755); err != nil {
   473  		t.Fatal(err)
   474  	}
   475  	if err := os.WriteFile(filepath.Join(lib64Dir, "libgomp.spec"), []byte("*link_gomp:\n"), 0644); err != nil {
   476  		t.Fatal(err)
   477  	}
   478  	if err := checkLinkerFlags("test", "test", []string{"-L" + subDir, "-fopenmp"}); err == nil {
   479  		t.Errorf("expected error for multilib sibling spec file in ../lib64, got nil")
   480  	}
   481  	if err := checkLinkerFlags("test", "test", []string{"-L" + filepath.Join(multiRoot, "nonexistent"), "-fopenmp"}); err == nil {
   482  		t.Errorf("expected error for multilib sibling spec file via nonexistent child dir, got nil")
   483  	}
   484  
   485  	// Symlinked directory pointing to a directory with a spec file, and
   486  	// subdirectory symlink inside a -L directory (N-2).
   487  	linkParent := t.TempDir()
   488  	symDir := filepath.Join(linkParent, "symlink-lib")
   489  	if err := os.Symlink(specDir, symDir); err == nil {
   490  		if err := checkLinkerFlags("test", "test", []string{"-L" + symDir, "-fopenmp"}); err == nil {
   491  			t.Errorf("expected error for symlinked -L directory containing spec file, got nil")
   492  		}
   493  		if err := checkLinkerFlags("test", "test", []string{"-L" + linkParent, "-fopenmp"}); err == nil {
   494  			t.Errorf("expected error for -L directory with subdirectory symlink to spec file, got nil")
   495  		}
   496  	}
   497  	// Symlinked directory pointing to a child directory whose real parent has ../lib64/libgomp.spec.
   498  	symSub := filepath.Join(linkParent, "symlink-sub")
   499  	if err := os.Symlink(subDir, symSub); err == nil {
   500  		if err := checkLinkerFlags("test", "test", []string{"-L" + symSub, "-fopenmp"}); err == nil {
   501  			t.Errorf("expected error for symlinked -L directory with multilib sibling spec file, got nil")
   502  		}
   503  	}
   504  
   505  	// CWD fallback when -fsanitize= is combined with -static/-static-lib* or
   506  	// when -fopenmp is used without -L (N-3), while preserving standalone
   507  	// -fsanitize=memory, -fsanitize=address, -fno-openmp, -fopenmp-simd, and -static.
   508  	t.Chdir(specDir)
   509  	for _, f := range [][]string{
   510  		{"-fsanitize=memory"},
   511  		{"-fsanitize=address"},
   512  		{"-fsanitize=undefined"},
   513  		{"-fno-openmp"},
   514  		{"-fopenmp-simd"},
   515  		{"-static"},
   516  	} {
   517  		if err := checkLinkerFlags("test", "test", f); err != nil {
   518  			t.Errorf("unexpected error for safe flag %q with spec file in CWD: %v", f, err)
   519  		}
   520  	}
   521  	for _, f := range [][]string{
   522  		{"-fsanitize=undefined", "-static-libubsan"},
   523  		{"-fsanitize=address", "-static"},
   524  		{"-fopenmp"},
   525  	} {
   526  		if err := checkLinkerFlags("test", "test", f); err == nil {
   527  			t.Errorf("expected error for %q with spec file in CWD and no -L, got nil", f)
   528  		}
   529  	}
   530  
   531  	// CWD/package-dir spec checks must not walk ../lib* multilib siblings
   532  	// (e.g. ./../lib -> host /lib when CWD is a depth-1 directory).
   533  	cwdParent := t.TempDir()
   534  	cwdChild := filepath.Join(cwdParent, "app")
   535  	cwdSiblingLib := filepath.Join(cwdParent, "lib")
   536  	if err := os.MkdirAll(cwdChild, 0755); err != nil {
   537  		t.Fatal(err)
   538  	}
   539  	if err := os.MkdirAll(cwdSiblingLib, 0755); err != nil {
   540  		t.Fatal(err)
   541  	}
   542  	if err := os.WriteFile(filepath.Join(cwdSiblingLib, "libgomp.spec"), []byte("*link_gomp: -lgomp\n"), 0644); err != nil {
   543  		t.Fatal(err)
   544  	}
   545  	t.Chdir(cwdChild)
   546  	if err := checkLinkerFlags("test", "test", []string{"-fopenmp"}); err != nil {
   547  		t.Errorf("unexpected error for CWD check with ../lib/libgomp.spec sibling: %v", err)
   548  	}
   549  
   550  	// Host default library trees (/lib*, /usr/lib*) must be skipped when passed
   551  	// without a sysroot prefix (e.g. -L/usr/lib or -L/usr/local/../lib), while
   552  	// sysroot-prefixed -L= paths are still scanned.
   553  	if cfg.Goos != "windows" {
   554  		for _, sysFlag := range [][]string{
   555  			{"-L/usr/lib", "-fopenmp"},
   556  			{"-L/usr/lib64", "-fopenmp"},
   557  		} {
   558  			if err := checkLinkerFlags("test", "test", sysFlag); err != nil {
   559  				t.Errorf("unexpected error for host system %q: %v", sysFlag, err)
   560  			}
   561  		}
   562  	}
   563  }
   564  
   565  func TestCheckLinkerWlFlags(t *testing.T) {
   566  	dir := t.TempDir()
   567  	script := filepath.Join(dir, "script.ld")
   568  	if err := os.WriteFile(script, []byte("PLUGIN(\"/tmp/pwn.so\")\n"), 0644); err != nil {
   569  		t.Fatal(err)
   570  	}
   571  	elfObj := filepath.Join(dir, "valid.o")
   572  	if err := os.WriteFile(elfObj, makeTestCOFFSection(".text", []byte{0x90}), 0644); err != nil {
   573  		t.Fatal(err)
   574  	}
   575  	for _, f := range [][]string{
   576  		{"-Wl,-rpath", "-Wl,foo"},
   577  		{"-Wl,-undefined", "-Wl,dynamic_lookup"},
   578  		{"-Wl,--just-symbols", "-Wl," + elfObj},
   579  		{"-Wl,--just-symbols=" + elfObj},
   580  		{"-Wl,-R", dir},
   581  		{"-Wl,-R," + dir},
   582  		{"-Wl,-R=" + dir},
   583  		{"-Wl,-R=" + elfObj},
   584  	} {
   585  		if err := checkLinkerFlags("test", "test", f); err != nil {
   586  			t.Errorf("unexpected error for %q: %v", f, err)
   587  		}
   588  	}
   589  	for _, f := range [][]string{
   590  		{"-Wl,--just-symbols=" + script},
   591  		{"-Wl,--just-symbols," + script},
   592  		{"-Wl,--just-symbols", "-Wl," + script},
   593  		{"-Wl,--push-state,--just-symbols=" + script},
   594  		{"-Wl,-R," + script},
   595  		{"-Wl,-R=" + script},
   596  		{"-Wl,-R" + script},
   597  		{"-Wl,-R", script},
   598  		{"-Wl,-R", "-Wl," + script},
   599  		{"-Wl,--push-state,-R" + script},
   600  		{"-Wl,--push-state,-R=" + script},
   601  		{"-Wl,-sectcreate," + script + ",__info_plist,foo"},
   602  		{"-Wl,-sectcreate,__TEXT," + script + ",foo"},
   603  	} {
   604  		if err := checkLinkerFlags("test", "test", f); err == nil {
   605  			t.Errorf("missing error for %q", f)
   606  		}
   607  	}
   608  	if cfg.Goos != "darwin" && cfg.Goos != "ios" {
   609  		if err := checkLinkerFlags("test", "test", []string{"-Wl,-sectcreate,__TEXT,__info_plist," + script}); err == nil {
   610  			t.Errorf("missing error for -Wl,-sectcreate with existing file on %s", cfg.Goos)
   611  		}
   612  	}
   613  	if cfg.Goos != "windows" {
   614  		if err := os.WriteFile(filepath.Join(dir, "console"), []byte("OUTPUT(/tmp/pwn)\n"), 0644); err != nil {
   615  			t.Fatal(err)
   616  		}
   617  		t.Chdir(dir)
   618  		if err := checkLinkerFlags("test", "test", []string{"-Wl,-subsystem,console"}); err == nil {
   619  			t.Errorf("missing error for -Wl,-subsystem,console with existing file in CWD on %s", cfg.Goos)
   620  		}
   621  		if err := checkLinkerFlags("test", "test", []string{"-Wl,-subsystem,windows"}); err != nil {
   622  			t.Errorf("unexpected error for -Wl,-subsystem,windows without matching file in CWD: %v", err)
   623  		}
   624  		if err := checkLinkerFlags("test", "test", []string{"-Wl,--subsystem,console"}); err != nil {
   625  			t.Errorf("unexpected error for -Wl,--subsystem,console: %v", err)
   626  		}
   627  	}
   628  }
   629  
   630  func TestCheckPkgConfigFlags(t *testing.T) {
   631  	good := [][]string{
   632  		{"--define-variable=prefix=/opt/mypkg/lib"},
   633  		{"--prefix-variable=prefix"},
   634  	}
   635  	for _, f := range good {
   636  		if err := checkPkgConfigFlags("test", "test", f); err != nil {
   637  			t.Errorf("unexpected error for %q: %v", f, err)
   638  		}
   639  	}
   640  
   641  	bad := [][]string{
   642  		{"--define-variable=A=-b"},
   643  		{"--define-variable=A=@b"},
   644  		{"--define-variable=A=b-c"},
   645  		{"--define-variable=A=b@c"},
   646  		{"--define-variable=libdir==/tmp/sub"},
   647  		{"--define-variable=libdir=$SYSROOT/tmp/sub"},
   648  		{"--define-variable=A=b$c"},
   649  		{"--define-variable=A="},
   650  		{"--define-variable=1A=b"},
   651  		{"--define-variable=A"},
   652  		{"--log-file=/tmp/log"},
   653  		{"--with-path=."},
   654  		{"--with-path=/tmp"},
   655  		{"--personality=triplet"},
   656  		{"--personality=filename"},
   657  	}
   658  	for _, f := range bad {
   659  		if err := checkPkgConfigFlags("test", "test", f); err == nil {
   660  			t.Errorf("missing error for %q", f)
   661  		}
   662  	}
   663  }
   664  
   665  func TestGetPkgConfigFlagsPackageNames(t *testing.T) {
   666  	for _, pkg := range []string{
   667  		"zlib",
   668  		"libfoo.pc2",
   669  		"glib-2.0,gobject-2.0",
   670  		"glib-2.0,",
   671  		"png cairo",
   672  		"foo = 1.0",
   673  		"foo != 1.0",
   674  		"foo >= 1.0, bar <= 2.0",
   675  		"foo>=1.0",
   676  	} {
   677  		if !validPkgConfigName(pkg) {
   678  			t.Errorf("validPkgConfigName(%q) = false, want true", pkg)
   679  		}
   680  	}
   681  
   682  	b := Builder{backgroundSh: &Shell{}}
   683  	for _, pkg := range []string{
   684  		"pwn.pc",
   685  		"PWN.PC",
   686  		".pc",
   687  		"pwn.pc>=0",
   688  		"pwn.pc=1.0",
   689  		"a!b.pc>=0",
   690  		"foo=pwn.pc",
   691  		"./pwn.pc",
   692  		"sub/pwn",
   693  		`sub\pwn`,
   694  		"C:pwn",
   695  		"..",
   696  		"../pwn",
   697  		"pwn.pc,pkg-config",
   698  		"pkg-config,pwn.pc",
   699  		"pwn.pc,",
   700  		"pkg-config pwn.pc",
   701  		"pkg-config\tpwn.pc",
   702  		"pwn.pc = 1.0",
   703  		"pkg-config = 1.0 pwn.pc",
   704  		"\u00a0pwn.pc",
   705  		"pwn.pc\xa0pkg-config",
   706  	} {
   707  		func() {
   708  			defer func() {
   709  				if r := recover(); r != nil {
   710  					t.Errorf("missing invalid package name error for %q (panicked in getPkgConfigFlags: %v)", pkg, r)
   711  				}
   712  			}()
   713  			_, _, err := b.getPkgConfigFlags(&Action{}, &load.Package{
   714  				PackagePublic: load.PackagePublic{
   715  					CgoPkgConfig: []string{pkg},
   716  				},
   717  			})
   718  			if err == nil || !strings.Contains(err.Error(), "invalid pkg-config package name") {
   719  				t.Errorf("expected invalid pkg-config package name error for %q, got %v", pkg, err)
   720  			}
   721  		}()
   722  	}
   723  }
   724  
   725  func TestCheckFlagAllowDisallow(t *testing.T) {
   726  	if err := checkCompilerFlags("TEST", "test", []string{"-disallow"}); err == nil {
   727  		t.Fatalf("missing error for -disallow")
   728  	}
   729  	os.Setenv("CGO_TEST_ALLOW", "-disallo")
   730  	if err := checkCompilerFlags("TEST", "test", []string{"-disallow"}); err == nil {
   731  		t.Fatalf("missing error for -disallow with CGO_TEST_ALLOW=-disallo")
   732  	}
   733  	os.Setenv("CGO_TEST_ALLOW", "-disallow")
   734  	if err := checkCompilerFlags("TEST", "test", []string{"-disallow"}); err != nil {
   735  		t.Fatalf("unexpected error for -disallow with CGO_TEST_ALLOW=-disallow: %v", err)
   736  	}
   737  	os.Unsetenv("CGO_TEST_ALLOW")
   738  
   739  	if err := checkCompilerFlags("TEST", "test", []string{"-Wall"}); err != nil {
   740  		t.Fatalf("unexpected error for -Wall: %v", err)
   741  	}
   742  	os.Setenv("CGO_TEST_DISALLOW", "-Wall")
   743  	if err := checkCompilerFlags("TEST", "test", []string{"-Wall"}); err == nil {
   744  		t.Fatalf("missing error for -Wall with CGO_TEST_DISALLOW=-Wall")
   745  	}
   746  	os.Setenv("CGO_TEST_ALLOW", "-Wall") // disallow wins
   747  	if err := checkCompilerFlags("TEST", "test", []string{"-Wall"}); err == nil {
   748  		t.Fatalf("missing error for -Wall with CGO_TEST_DISALLOW=-Wall and CGO_TEST_ALLOW=-Wall")
   749  	}
   750  
   751  	os.Setenv("CGO_TEST_ALLOW", "-fplugin.*")
   752  	os.Setenv("CGO_TEST_DISALLOW", "-fplugin=lint.so")
   753  	if err := checkCompilerFlags("TEST", "test", []string{"-fplugin=faster.so"}); err != nil {
   754  		t.Fatalf("unexpected error for -fplugin=faster.so: %v", err)
   755  	}
   756  	if err := checkCompilerFlags("TEST", "test", []string{"-fplugin=lint.so"}); err == nil {
   757  		t.Fatalf("missing error for -fplugin=lint.so: %v", err)
   758  	}
   759  
   760  	os.Setenv("CGO_TEST_DISALLOW", "-lfoo")
   761  	os.Unsetenv("CGO_TEST_ALLOW")
   762  	if err := checkLinkerFlags("TEST", "test", []string{"-l", "foo"}); err == nil {
   763  		t.Fatalf("missing error for -l foo with CGO_TEST_DISALLOW=-lfoo")
   764  	}
   765  	os.Setenv("CGO_TEST_ALLOW", "-lto_library")
   766  	os.Unsetenv("CGO_TEST_DISALLOW")
   767  	if err := checkLinkerFlags("TEST", "test", []string{"-l", "to_library"}); err != nil {
   768  		t.Fatalf("unexpected error for -l to_library with CGO_TEST_ALLOW=-lto_library: %v", err)
   769  	}
   770  	os.Unsetenv("CGO_TEST_ALLOW")
   771  }
   772  
   773  func TestCheckCompilerFlagsForInternalLink(t *testing.T) {
   774  	// Any "bad" compiler flag should trigger external linking.
   775  	for _, f := range badCompilerFlags {
   776  		if err := checkCompilerFlagsForInternalLink("test", "test", f); err == nil {
   777  			t.Errorf("missing error for %q", f)
   778  		}
   779  	}
   780  
   781  	// All "good" compiler flags should not trigger external linking,
   782  	// except for anything that begins with "-flto".
   783  	for _, f := range goodCompilerFlags {
   784  		foundLTO := false
   785  		for _, s := range f {
   786  			if strings.Contains(s, "-flto") {
   787  				foundLTO = true
   788  			}
   789  		}
   790  		if err := checkCompilerFlagsForInternalLink("test", "test", f); err != nil {
   791  			// expect error for -flto
   792  			if !foundLTO {
   793  				t.Errorf("unexpected error for %q: %v", f, err)
   794  			}
   795  		} else {
   796  			// expect no error for everything else
   797  			if foundLTO {
   798  				t.Errorf("missing error for %q: %v", f, err)
   799  			}
   800  		}
   801  	}
   802  }
   803  
   804  func makeTestCOFFSection(secName string, dataBytes []byte) []byte {
   805  	hdrAndSec := 20 + 40
   806  	buf := make([]byte, hdrAndSec+len(dataBytes))
   807  	binary.LittleEndian.PutUint16(buf[0:2], 0x8664) // IMAGE_FILE_MACHINE_AMD64
   808  	binary.LittleEndian.PutUint16(buf[2:4], 1)      // NumberOfSections = 1
   809  	copy(buf[20:28], secName)
   810  	binary.LittleEndian.PutUint32(buf[20+16:20+20], uint32(len(dataBytes))) // SizeOfRawData
   811  	binary.LittleEndian.PutUint32(buf[20+20:20+24], uint32(hdrAndSec))      // PointerToRawData
   812  	copy(buf[hdrAndSec:], dataBytes)
   813  	return buf
   814  }
   815  
   816  func makeTestCOFFLongSection(longName string) []byte {
   817  	strTab := append(make([]byte, 4), append([]byte(longName), 0)...)
   818  	binary.LittleEndian.PutUint32(strTab[0:4], uint32(len(strTab)))
   819  	buf := make([]byte, 20+40+len(strTab))
   820  	binary.LittleEndian.PutUint16(buf[0:2], 0x8664)
   821  	binary.LittleEndian.PutUint16(buf[2:4], 1)
   822  	binary.LittleEndian.PutUint32(buf[8:12], 60) // PointerToSymbolTable = 60
   823  	binary.LittleEndian.PutUint32(buf[12:16], 0) // NumberOfSymbols = 0
   824  	copy(buf[20:28], "/4")
   825  	copy(buf[60:], strTab)
   826  	return buf
   827  }
   828  
   829  func TestCheckLinkerInputFiles(t *testing.T) {
   830  	dir := t.TempDir()
   831  
   832  	// 1. GNU ld implicit linker script disguised as a direct .so input (A-4),
   833  	// or passed via -Wl, flags ending in an object/library extension.
   834  	evilSo := filepath.Join(dir, "evil.so")
   835  	if err := os.WriteFile(evilSo, []byte("PLUGIN(\"/tmp/pwn.so\")\n"), 0644); err != nil {
   836  		t.Fatal(err)
   837  	}
   838  	for _, f := range [][]string{
   839  		{evilSo},
   840  		{"-Wl,--just-symbols=" + evilSo},
   841  		{"-Wl,--just-symbols," + evilSo},
   842  		{"-Wl,-R," + evilSo},
   843  		{"-Wl,-R" + evilSo},
   844  		{"-Wl,-syslibroot=" + evilSo},
   845  		{"-Wl,--push-state,-R," + evilSo},
   846  	} {
   847  		if err := checkLinkerFlags("LDFLAGS", "#cgo LDFLAGS", f); err == nil {
   848  			t.Errorf("expected error for GNU ld script disguised as .so in %q, got nil", f)
   849  		}
   850  	}
   851  	t.Chdir(dir)
   852  	for _, f := range [][]string{
   853  		{"-Wl,-framework,evil.so"},
   854  		{"-Wl,-undefined=evil.so"},
   855  	} {
   856  		if err := checkLinkerFlags("LDFLAGS", "#cgo LDFLAGS", f); err == nil {
   857  			t.Errorf("expected error for CWD file with .so suffix in %q, got nil", f)
   858  		}
   859  	}
   860  	if cfg.Goos != "darwin" && cfg.Goos != "ios" {
   861  		if err := checkLinkerFlags("LDFLAGS", "#cgo LDFLAGS", []string{"-Wl,-sectcreate,__TEXT,__text,evil.so"}); err == nil {
   862  			t.Errorf("expected error for -Wl,-sectcreate with existing .so file on %s, got nil", cfg.Goos)
   863  		}
   864  	}
   865  
   866  	// 2. GNU ld implicit linker script named libc.so, foo.lib, or ..dll inside a -L directory (A-3c, N-2, N-5).
   867  	libDir := filepath.Join(dir, "lib")
   868  	if err := os.MkdirAll(libDir, 0755); err != nil {
   869  		t.Fatal(err)
   870  	}
   871  	if err := os.WriteFile(filepath.Join(libDir, "libc.so"), []byte("GROUP(\"/tmp/pwn.so\")\n"), 0644); err != nil {
   872  		t.Fatal(err)
   873  	}
   874  	for _, f := range [][]string{
   875  		{"-L" + libDir},
   876  		{"-L", libDir},
   877  		{"-L=" + libDir},
   878  		{"-L$SYSROOT" + libDir},
   879  	} {
   880  		if err := checkLinkerFlags("LDFLAGS", "#cgo LDFLAGS", f); err == nil {
   881  			t.Errorf("expected error for -L directory %q containing linker script libc.so, got nil", f)
   882  		}
   883  	}
   884  	// Subdirectory symlink inside -L directory pointing to a directory with a linker script (N-2).
   885  	symSearchDir := t.TempDir()
   886  	if err := os.Symlink(libDir, filepath.Join(symSearchDir, "sub")); err == nil {
   887  		if err := checkLinkerFlags("LDFLAGS", "#cgo LDFLAGS", []string{"-L" + symSearchDir}); err == nil {
   888  			t.Errorf("expected error for -L directory containing symlinked subdirectory with linker script, got nil")
   889  		}
   890  	}
   891  
   892  	winLibDir := filepath.Join(dir, "winlib")
   893  	if err := os.MkdirAll(winLibDir, 0755); err != nil {
   894  		t.Fatal(err)
   895  	}
   896  	if err := os.WriteFile(filepath.Join(winLibDir, "foo.lib"), []byte("INPUT(\"/tmp/pwn.dll\")\n"), 0644); err != nil {
   897  		t.Fatal(err)
   898  	}
   899  	if err := checkLinkerFlags("LDFLAGS", "#cgo LDFLAGS", []string{"-L" + winLibDir}); err == nil {
   900  		t.Errorf("expected error for -L directory containing linker script foo.lib, got nil")
   901  	}
   902  	dotDllDir := filepath.Join(dir, "dotdll")
   903  	if err := os.MkdirAll(dotDllDir, 0755); err != nil {
   904  		t.Fatal(err)
   905  	}
   906  	if err := os.WriteFile(filepath.Join(dotDllDir, "..dll"), []byte("INPUT(\"/tmp/pwn.dll\")\n"), 0644); err != nil {
   907  		t.Fatal(err)
   908  	}
   909  	if err := checkLinkerFlags("LDFLAGS", "#cgo LDFLAGS", []string{"-L" + dotDllDir}); err == nil {
   910  		t.Errorf("expected error for -L directory containing linker script ..dll, got nil")
   911  	}
   912  
   913  	// 3. ar archive containing a PE/COFF member with dangerous .drectve,
   914  	// including N-6 bypass variants (BSD #1/<len> __.SYMDEF.o prefix, >64-byte
   915  	// #1/<len> name, non-first SVR4 __.SYMDEF member, and truncated !<arch>\n).
   916  	peBuf := makeTestCOFFSection(".drectve", []byte(`--plugin /tmp/pwn.so`))
   917  	arPath := filepath.Join(dir, "libevil.a")
   918  	memberSize := fmt.Sprintf("%-10d", len(peBuf))
   919  	arHdr := []byte("!<arch>\nevil.o          0           0     0     644     " + memberSize + "`\n")
   920  	if err := os.WriteFile(arPath, append(arHdr, peBuf...), 0644); err != nil {
   921  		t.Fatal(err)
   922  	}
   923  	if err := checkLinkerFlags("LDFLAGS", "#cgo LDFLAGS", []string{arPath}); err == nil {
   924  		t.Errorf("expected error for archive containing dangerous .drectve member, got nil")
   925  	}
   926  	if err := checkLinkerInputFile(".syso", arPath); err == nil {
   927  		t.Errorf("expected error for archive used as .syso, got nil")
   928  	}
   929  
   930  	// N-6a: BSD #1/12 member named "__.SYMDEF.o\x00".
   931  	bsdSymdefPrefix := filepath.Join(dir, "libbsd_symdef_prefix.a")
   932  	bsdName := []byte("__.SYMDEF.o\x00")
   933  	bsdSize := fmt.Sprintf("%-10d", len(bsdName)+len(peBuf))
   934  	bsdHdr := []byte("!<arch>\n#1/12           0           0     0     644     " + bsdSize + "`\n")
   935  	if err := os.WriteFile(bsdSymdefPrefix, append(append(bsdHdr, bsdName...), peBuf...), 0644); err != nil {
   936  		t.Fatal(err)
   937  	}
   938  	if err := checkLinkerFlags("LDFLAGS", "#cgo LDFLAGS", []string{bsdSymdefPrefix}); err == nil {
   939  		t.Errorf("expected error for BSD archive member named __.SYMDEF.o, got nil")
   940  	}
   941  
   942  	// N-6b: BSD #1/68 member named "__.SYMDEF" + 55*'A' + ".o\x00\x00" (>64 bytes).
   943  	bsdLongName := append([]byte("__.SYMDEF"+strings.Repeat("A", 55)+".o"), 0, 0)
   944  	bsdLongPath := filepath.Join(dir, "libbsd_long.a")
   945  	bsdLongSize := fmt.Sprintf("%-10d", len(bsdLongName)+len(peBuf))
   946  	bsdLongHdr := []byte(fmt.Sprintf("!<arch>\n#1/%-13d0           0     0     644     %s`\n", len(bsdLongName), bsdLongSize))
   947  	if err := os.WriteFile(bsdLongPath, append(append(bsdLongHdr, bsdLongName...), peBuf...), 0644); err != nil {
   948  		t.Fatal(err)
   949  	}
   950  	if err := checkLinkerFlags("LDFLAGS", "#cgo LDFLAGS", []string{bsdLongPath}); err == nil {
   951  		t.Errorf("expected error for BSD archive member with >64-byte __.SYMDEF* name, got nil")
   952  	}
   953  
   954  	// N-6c: Non-first archive member named "__.SYMDEF" containing dangerous COFF object.
   955  	svr4SecondSymdef := filepath.Join(dir, "libsvr4_second.a")
   956  	firstHdr := []byte("!<arch>\n/               0           0     0     0       4         `\n\x00\x00\x00\x00")
   957  	secondHdr := []byte("__.SYMDEF       0           0     0     644     " + memberSize + "`\n")
   958  	if err := os.WriteFile(svr4SecondSymdef, append(append(firstHdr, secondHdr...), peBuf...), 0644); err != nil {
   959  		t.Fatal(err)
   960  	}
   961  	if err := checkLinkerFlags("LDFLAGS", "#cgo LDFLAGS", []string{svr4SecondSymdef}); err == nil {
   962  		t.Errorf("expected error for second archive member named __.SYMDEF, got nil")
   963  	}
   964  
   965  	// N-6d: Truncated archive ("!<arch>\nPLUGIN(...)" < 68 bytes).
   966  	truncAr := filepath.Join(dir, "libtrunc.a")
   967  	if err := os.WriteFile(truncAr, []byte("!<arch>\nPLUGIN(\"/tmp/pwn.so\")\n"), 0644); err != nil {
   968  		t.Fatal(err)
   969  	}
   970  	if err := checkLinkerFlags("LDFLAGS", "#cgo LDFLAGS", []string{truncAr}); err == nil {
   971  		t.Errorf("expected error for truncated !<arch> file, got nil")
   972  	}
   973  }
   974  
   975  func TestCheckLinkerCOFFDrectve(t *testing.T) {
   976  	dir := t.TempDir()
   977  
   978  	// 1. PE/COFF object with safe .drectve directives should be allowed.
   979  	safeObj := filepath.Join(dir, "safe_drectve.o")
   980  	if err := os.WriteFile(safeObj, makeTestCOFFSection(".drectve", []byte(`/DEFAULTLIB:msvcrt /EXPORT:MyFunc`)), 0644); err != nil {
   981  		t.Fatal(err)
   982  	}
   983  	if err := checkLinkerFlags("LDFLAGS", "#cgo LDFLAGS", []string{safeObj}); err != nil {
   984  		t.Errorf("unexpected error for PE/COFF with safe .drectve: %v", err)
   985  	}
   986  
   987  	safeMinGW := filepath.Join(dir, "safe_mingw.o")
   988  	if err := os.WriteFile(safeMinGW, makeTestCOFFSection(".drectve", []byte("\xef\xbb\xbf"+`-lkernel32 --enable-auto-import "/DEFAULTLIB:uuid.lib" /MANIFESTDEPENDENCY:"type='win32' name='Microsoft.Windows.Common-Controls'"`+"\x00\x00"+`-export:Bar /CETCOMPAT /GUARD:EHCONT --exclude-all-symbols`)), 0644); err != nil {
   989  		t.Fatal(err)
   990  	}
   991  	if err := checkLinkerFlags("LDFLAGS", "#cgo LDFLAGS", []string{safeMinGW}); err != nil {
   992  		t.Errorf("unexpected error for PE/COFF with safe MinGW/MSVC .drectve: %v", err)
   993  	}
   994  
   995  	// 2. PE/COFF object with dangerous .drectve content must be rejected.
   996  	drectveObj := filepath.Join(dir, "drectve.o")
   997  	if err := os.WriteFile(drectveObj, makeTestCOFFSection(".drectve", []byte(`--plugin /tmp/pwn.so`)), 0644); err != nil {
   998  		t.Fatal(err)
   999  	}
  1000  	if err := checkLinkerFlags("LDFLAGS", "#cgo LDFLAGS", []string{drectveObj}); err == nil {
  1001  		t.Errorf("expected error for PE/COFF object with dangerous .drectve, got nil")
  1002  	}
  1003  
  1004  	evilDrectve := filepath.Join(dir, "evil_drectve.o")
  1005  	if err := os.WriteFile(evilDrectve, makeTestCOFFSection(".drectve", []byte(`-L/tmp/evil -T/tmp/evil.ld`)), 0644); err != nil {
  1006  		t.Fatal(err)
  1007  	}
  1008  	if err := checkLinkerFlags("LDFLAGS", "#cgo LDFLAGS", []string{evilDrectve}); err == nil {
  1009  		t.Errorf("expected error for PE/COFF object with -L/-T .drectve, got nil")
  1010  	}
  1011  
  1012  	driveRelDrectve := filepath.Join(dir, "drive_rel_drectve.o")
  1013  	if err := os.WriteFile(driveRelDrectve, makeTestCOFFSection(".drectve", []byte(`/DEFAULTLIB:C:evil.lib`)), 0644); err != nil {
  1014  		t.Fatal(err)
  1015  	}
  1016  	if err := checkLinkerFlags("LDFLAGS", "#cgo LDFLAGS", []string{driveRelDrectve}); err == nil {
  1017  		t.Errorf("expected error for PE/COFF object with drive-relative /DEFAULTLIB:C:evil.lib, got nil")
  1018  	}
  1019  
  1020  	// 3. PE/COFF object with a valid long DWARF section name (/4 -> .debug_info) in string table.
  1021  	dwarfObj := filepath.Join(dir, "dwarf.o")
  1022  	if err := os.WriteFile(dwarfObj, makeTestCOFFLongSection(".debug_info"), 0644); err != nil {
  1023  		t.Fatal(err)
  1024  	}
  1025  	if err := checkLinkerFlags("LDFLAGS", "#cgo LDFLAGS", []string{dwarfObj}); err != nil {
  1026  		t.Errorf("unexpected error for PE/COFF object with /4 .debug_info section: %v", err)
  1027  	}
  1028  }
  1029  
  1030  func TestCheckLinkerObjectSections(t *testing.T) {
  1031  	dir := t.TempDir()
  1032  
  1033  	// 1. PE/COFF object with GCC/LLVM LTO sections (.llvmbc or /4 -> .gnu.lto_.symtab.1234) must be rejected.
  1034  	coffLtoShort := filepath.Join(dir, "coff_lto_short.o")
  1035  	if err := os.WriteFile(coffLtoShort, makeTestCOFFSection(".llvmbc", []byte("BC\xc0\xde")), 0644); err != nil {
  1036  		t.Fatal(err)
  1037  	}
  1038  	if err := checkLinkerFlags("LDFLAGS", "#cgo LDFLAGS", []string{coffLtoShort}); err == nil {
  1039  		t.Errorf("expected error for PE/COFF object with .llvmbc section, got nil")
  1040  	}
  1041  	coffLtoLong := filepath.Join(dir, "coff_lto_long.o")
  1042  	if err := os.WriteFile(coffLtoLong, makeTestCOFFLongSection(".gnu.lto_.symtab.12345678"), 0644); err != nil {
  1043  		t.Fatal(err)
  1044  	}
  1045  	if err := checkLinkerFlags("LDFLAGS", "#cgo LDFLAGS", []string{coffLtoLong}); err == nil {
  1046  		t.Errorf("expected error for PE/COFF object with /4 .gnu.lto_.symtab.* section, got nil")
  1047  	}
  1048  
  1049  	// 2. Mach-O 64-bit object containing LC_LINKER_OPTION (0x2d) (B-1 macOS):
  1050  	// dangerous/malformed options must be rejected, while safe -l and -framework options are allowed.
  1051  	makeMachOLinkerOpt := func(count uint32, payload []byte) []byte {
  1052  		cmdSize := 12 + len(payload)
  1053  		if cmdSize%8 != 0 {
  1054  			cmdSize += 8 - (cmdSize % 8)
  1055  		}
  1056  		buf := make([]byte, 32+cmdSize)
  1057  		binary.LittleEndian.PutUint32(buf[0:4], 0xfeedfacf) // MH_MAGIC_64
  1058  		binary.LittleEndian.PutUint32(buf[12:16], 1)        // MH_OBJECT
  1059  		binary.LittleEndian.PutUint32(buf[16:20], 1)        // ncmds = 1
  1060  		binary.LittleEndian.PutUint32(buf[20:24], uint32(cmdSize))
  1061  		binary.LittleEndian.PutUint32(buf[32:36], 0x2d) // LC_LINKER_OPTION
  1062  		binary.LittleEndian.PutUint32(buf[36:40], uint32(cmdSize))
  1063  		binary.LittleEndian.PutUint32(buf[40:44], count)
  1064  		copy(buf[44:], payload)
  1065  		return buf
  1066  	}
  1067  	for _, badOpt := range [][]byte{
  1068  		makeMachOLinkerOpt(0, nil),
  1069  		makeMachOLinkerOpt(2, []byte("-lto_library\x00/tmp/pwn.dylib\x00")),
  1070  		makeMachOLinkerOpt(1, []byte("-l:evil.ld\x00")),
  1071  		makeMachOLinkerOpt(2, []byte("-framework\x00/tmp/pwn.ld\x00")),
  1072  	} {
  1073  		machoObj := filepath.Join(dir, "macho_opt.o")
  1074  		if err := os.WriteFile(machoObj, badOpt, 0644); err != nil {
  1075  			t.Fatal(err)
  1076  		}
  1077  		if err := checkLinkerFlags("LDFLAGS", "#cgo LDFLAGS", []string{machoObj}); err == nil {
  1078  			t.Errorf("expected error for Mach-O object with disallowed LC_LINKER_OPTION, got nil")
  1079  		}
  1080  	}
  1081  	for _, goodOpt := range [][]byte{
  1082  		makeMachOLinkerOpt(1, []byte("-lSystem\x00")),
  1083  		makeMachOLinkerOpt(2, []byte("-framework\x00CoreFoundation\x00")),
  1084  	} {
  1085  		machoGood := filepath.Join(dir, "macho_good_opt.o")
  1086  		if err := os.WriteFile(machoGood, goodOpt, 0644); err != nil {
  1087  			t.Fatal(err)
  1088  		}
  1089  		if err := checkLinkerFlags("LDFLAGS", "#cgo LDFLAGS", []string{machoGood}); err != nil {
  1090  			t.Errorf("unexpected error for Mach-O object with safe LC_LINKER_OPTION: %v", err)
  1091  		}
  1092  	}
  1093  
  1094  	// 3. ELF 64-bit relocatable object containing GCC/LLVM LTO sections (.gnu.lto_.opts, SHT_LLVM_LTO)
  1095  	// must be rejected, while normal ELF objects are allowed.
  1096  	makeELF64 := func(eType uint16, secName string, shType uint32) []byte {
  1097  		shstrtab := append([]byte{0}, append([]byte(secName), 0)...)
  1098  		shOff := 64 + len(shstrtab)
  1099  		if shOff%8 != 0 {
  1100  			shOff += 8 - (shOff % 8)
  1101  		}
  1102  		buf := make([]byte, shOff+3*64)
  1103  		copy(buf[0:4], "\x7fELF")
  1104  		buf[4] = 2                                       // ELFCLASS64
  1105  		buf[5] = 1                                       // ELFDATA2LSB
  1106  		buf[6] = 1                                       // EV_CURRENT
  1107  		binary.LittleEndian.PutUint16(buf[16:18], eType) // e_type
  1108  		binary.LittleEndian.PutUint16(buf[18:20], 0x3e)  // EM_X86_64
  1109  		binary.LittleEndian.PutUint32(buf[20:24], 1)     // EV_CURRENT
  1110  		binary.LittleEndian.PutUint64(buf[40:48], uint64(shOff))
  1111  		binary.LittleEndian.PutUint16(buf[52:54], 64) // e_ehsize
  1112  		binary.LittleEndian.PutUint16(buf[58:60], 64) // e_shentsize
  1113  		binary.LittleEndian.PutUint16(buf[60:62], 3)  // e_shnum (NULL, target sec, .shstrtab)
  1114  		binary.LittleEndian.PutUint16(buf[62:64], 2)  // e_shstrndx = 2
  1115  		copy(buf[64:], shstrtab)
  1116  		// Section 1: target section
  1117  		sec1 := buf[shOff+64 : shOff+128]
  1118  		binary.LittleEndian.PutUint32(sec1[0:4], 1)      // sh_name = 1
  1119  		binary.LittleEndian.PutUint32(sec1[4:8], shType) // sh_type
  1120  		// Section 2: .shstrtab
  1121  		sec2 := buf[shOff+128 : shOff+192]
  1122  		binary.LittleEndian.PutUint32(sec2[4:8], 3)                       // SHT_STRTAB
  1123  		binary.LittleEndian.PutUint64(sec2[24:32], 64)                    // sh_offset = 64
  1124  		binary.LittleEndian.PutUint64(sec2[32:40], uint64(len(shstrtab))) // sh_size
  1125  		return buf
  1126  	}
  1127  
  1128  	normalELF := filepath.Join(dir, "normal.o")
  1129  	if err := os.WriteFile(normalELF, makeELF64(1, ".text", 1), 0644); err != nil {
  1130  		t.Fatal(err)
  1131  	}
  1132  	if err := checkLinkerFlags("LDFLAGS", "#cgo LDFLAGS", []string{normalELF}); err != nil {
  1133  		t.Errorf("unexpected error for normal ELF64 .o: %v", err)
  1134  	}
  1135  
  1136  	gccLtoELF := filepath.Join(dir, "gcc_lto.o")
  1137  	if err := os.WriteFile(gccLtoELF, makeELF64(1, ".gnu.lto_.opts", 1), 0644); err != nil {
  1138  		t.Fatal(err)
  1139  	}
  1140  	if err := checkLinkerFlags("LDFLAGS", "#cgo LDFLAGS", []string{gccLtoELF}); err == nil {
  1141  		t.Errorf("expected error for ELF64 object with .gnu.lto_.opts section, got nil")
  1142  	}
  1143  	if err := checkLinkerInputFile(".syso", gccLtoELF); err == nil {
  1144  		t.Errorf("expected error for ELF64 .syso with .gnu.lto_.opts section, got nil")
  1145  	}
  1146  
  1147  	llvmLtoELF := filepath.Join(dir, "llvm_lto.o")
  1148  	if err := os.WriteFile(llvmLtoELF, makeELF64(1, ".text", 0x6fff4c0c), 0644); err != nil {
  1149  		t.Fatal(err)
  1150  	}
  1151  	if err := checkLinkerFlags("LDFLAGS", "#cgo LDFLAGS", []string{llvmLtoELF}); err == nil {
  1152  		t.Errorf("expected error for ELF64 object with SHT_LLVM_LTO section, got nil")
  1153  	}
  1154  
  1155  	llvmLinkerOptsELF := filepath.Join(dir, "llvm_linker_opts.o")
  1156  	if err := os.WriteFile(llvmLinkerOptsELF, makeELF64(1, ".linker-options", 0x6fff4c01), 0644); err != nil {
  1157  		t.Fatal(err)
  1158  	}
  1159  	if err := checkLinkerFlags("LDFLAGS", "#cgo LDFLAGS", []string{llvmLinkerOptsELF}); err == nil {
  1160  		t.Errorf("expected error for ELF64 object with SHT_LLVM_LINKER_OPTIONS section, got nil")
  1161  	}
  1162  
  1163  	// Polyglot linker script starting with "MZ=0;/*..." and fake PE header at offset 0x80.
  1164  	mzScript := make([]byte, 256)
  1165  	copy(mzScript, "MZ=0; PLUGIN(\"/tmp/pwn.so\") /*")
  1166  	binary.LittleEndian.PutUint32(mzScript[0x3c:0x40], 0x80)
  1167  	copy(mzScript[0x80:], "PE\x00\x00")
  1168  	binary.LittleEndian.PutUint16(mzScript[0x84:0x86], 0x8664)
  1169  	mzScriptPath := filepath.Join(dir, "mz_script.dll")
  1170  	if err := os.WriteFile(mzScriptPath, mzScript, 0644); err != nil {
  1171  		t.Fatal(err)
  1172  	}
  1173  	if err := checkLinkerFlags("LDFLAGS", "#cgo LDFLAGS", []string{mzScriptPath}); err == nil {
  1174  		t.Errorf("expected error for MZ polyglot linker script, got nil")
  1175  	}
  1176  
  1177  	// AIX big archive ("<bigaf>\n") containing an invalid/script member.
  1178  	bigAr := make([]byte, 128+112+4+2+16)
  1179  	copy(bigAr[0:8], "<bigaf>\n")
  1180  	copy(bigAr[68:88], fmt.Sprintf("%-20d", 128))
  1181  	copy(bigAr[88:108], fmt.Sprintf("%-20d", 128))
  1182  	copy(bigAr[128+0:128+20], fmt.Sprintf("%-20d", 16))
  1183  	copy(bigAr[128+108:128+112], fmt.Sprintf("%-4d", 4))
  1184  	copy(bigAr[128+112:128+116], "a.o\x00")
  1185  	copy(bigAr[128+116:128+118], "`\n")
  1186  	copy(bigAr[128+118:], "INPUT(/tmp/pwn)\n")
  1187  	bigArPath := filepath.Join(dir, "libbig.a")
  1188  	if err := os.WriteFile(bigArPath, bigAr, 0644); err != nil {
  1189  		t.Fatal(err)
  1190  	}
  1191  	if err := checkLinkerFlags("LDFLAGS", "#cgo LDFLAGS", []string{bigArPath}); err == nil {
  1192  		t.Errorf("expected error for AIX big archive with linker script member, got nil")
  1193  	}
  1194  
  1195  	// ASCII polyglot linker script starting with COFF LOONGARCH64 magic ("db") and >=256 sections must fail.
  1196  	coffPoly := make([]byte, 20+0x3020*40)
  1197  	copy(coffPoly, "db /*               ")
  1198  	coffPolyPath := filepath.Join(dir, "coff_poly.o")
  1199  	if err := os.WriteFile(coffPolyPath, coffPoly, 0644); err != nil {
  1200  		t.Fatal(err)
  1201  	}
  1202  	if err := checkLinkerFlags("LDFLAGS", "#cgo LDFLAGS", []string{coffPolyPath}); err == nil {
  1203  		t.Errorf("expected error for ASCII COFF polyglot linker script, got nil")
  1204  	}
  1205  
  1206  	// GNU ar archive whose "//" long-filename table starts with "db" (0x6264 == LOONGARCH64) must pass,
  1207  	// while a binary COFF object disguised as "//" must fail.
  1208  	arMember := func(name string, body []byte) []byte {
  1209  		hdr := fmt.Sprintf("%-16s%-12d%-6d%-6d%-8s%-10d`\n", name, 0, 0, 0, "644", len(body))
  1210  		out := append([]byte(hdr), body...)
  1211  		if len(out)%2 != 0 {
  1212  			out = append(out, '\n')
  1213  		}
  1214  		return out
  1215  	}
  1216  	validMemberObj := makeTestCOFFSection(".text", []byte{0xc3})
  1217  	gnuStrTab := []byte("db_impl_write.cc.o/\n")
  1218  	gnuArBytes := append([]byte("!<arch>\n"), arMember("//", gnuStrTab)...)
  1219  	gnuArBytes = append(gnuArBytes, arMember("/0", validMemberObj)...)
  1220  	gnuArPath := filepath.Join(dir, "librocksdb_like.a")
  1221  	if err := os.WriteFile(gnuArPath, gnuArBytes, 0644); err != nil {
  1222  		t.Fatal(err)
  1223  	}
  1224  	if err := checkLinkerFlags("LDFLAGS", "#cgo LDFLAGS", []string{gnuArPath}); err != nil {
  1225  		t.Errorf("unexpected error for GNU archive with 'db*' long-name string table: %v", err)
  1226  	}
  1227  
  1228  	disguisedStrTabAr := append([]byte("!<arch>\n"), arMember("//", makeTestCOFFSection(".drectve", []byte("--plugin /tmp/pwn.so")))...)
  1229  	disguisedPath := filepath.Join(dir, "libdisguised_strtab.a")
  1230  	if err := os.WriteFile(disguisedPath, disguisedStrTabAr, 0644); err != nil {
  1231  		t.Fatal(err)
  1232  	}
  1233  	if err := checkLinkerFlags("LDFLAGS", "#cgo LDFLAGS", []string{disguisedPath}); err == nil {
  1234  		t.Errorf("expected error for COFF object disguised as '//' archive string table, got nil")
  1235  	}
  1236  
  1237  	// Windows PE/COFF import library (.dll.a / .lib): dual "/" linker members + "//" at index 2 +
  1238  	// short import member (IMPORT_OBJECT_HEADER: 00 00 FF FF Version=0) must pass.
  1239  	impPayload := []byte("SymName\x00foo.dll\x00")
  1240  	impObj := make([]byte, 20+len(impPayload))
  1241  	binary.LittleEndian.PutUint16(impObj[0:2], 0x0000)
  1242  	binary.LittleEndian.PutUint16(impObj[2:4], 0xffff)
  1243  	binary.LittleEndian.PutUint16(impObj[4:6], 0)
  1244  	binary.LittleEndian.PutUint16(impObj[6:8], 0x8664)
  1245  	binary.LittleEndian.PutUint32(impObj[12:16], uint32(len(impPayload)))
  1246  	binary.LittleEndian.PutUint16(impObj[18:20], 0x0004) // IMPORT_CODE | IMPORT_NAME
  1247  	copy(impObj[20:], impPayload)
  1248  
  1249  	firstSlash := make([]byte, 4) // 0 symbols (BE)
  1250  	secondSlash := make([]byte, 12)
  1251  	binary.LittleEndian.PutUint32(secondSlash[0:4], 1) // 1 member offset
  1252  	binary.LittleEndian.PutUint32(secondSlash[8:12], 0)
  1253  	peStrTab := []byte("long_import_member.dll\x00")
  1254  	impLibBytes := []byte("!<arch>\n")
  1255  	impLibBytes = append(impLibBytes, arMember("/", firstSlash)...)
  1256  	impLibBytes = append(impLibBytes, arMember("/", secondSlash)...)
  1257  	impLibBytes = append(impLibBytes, arMember("//", peStrTab)...)
  1258  	impLibBytes = append(impLibBytes, arMember("/0", impObj)...)
  1259  	impLibPath := filepath.Join(dir, "foo.dll.a")
  1260  	if err := os.WriteFile(impLibPath, impLibBytes, 0644); err != nil {
  1261  		t.Fatal(err)
  1262  	}
  1263  	if err := checkLinkerFlags("LDFLAGS", "#cgo LDFLAGS", []string{impLibPath}); err != nil {
  1264  		t.Errorf("unexpected error for valid PE import library (.dll.a): %v", err)
  1265  	}
  1266  	if err := checkLinkerInputFile(".syso", impLibPath); err == nil {
  1267  		t.Errorf("expected error for import archive used as .syso, got nil")
  1268  	}
  1269  
  1270  	// Host default library directory (-L/usr/lib) must not fail on GNU ld stub scripts (libc.so, libm.so).
  1271  	if cfg.Goos != "windows" {
  1272  		if err := checkLinkerFlags("LDFLAGS", "#cgo LDFLAGS", []string{"-L/usr/lib"}); err != nil {
  1273  			t.Errorf("unexpected error for host -L/usr/lib: %v", err)
  1274  		}
  1275  	}
  1276  }
  1277  

View as plain text