github.com/rafaeltorres324/go/src@v0.0.0-20210519164414-9fdf653a9838/os/exec/lp_windows_test.go (about)

     1  // Copyright 2013 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  // Use an external test to avoid os/exec -> internal/testenv -> os/exec
     6  // circular dependency.
     7  
     8  package exec_test
     9  
    10  import (
    11  	"fmt"
    12  	"internal/testenv"
    13  	"io"
    14  	"os"
    15  	"os/exec"
    16  	"path/filepath"
    17  	"strconv"
    18  	"strings"
    19  	"testing"
    20  )
    21  
    22  func installExe(t *testing.T, dest, src string) {
    23  	fsrc, err := os.Open(src)
    24  	if err != nil {
    25  		t.Fatal("os.Open failed: ", err)
    26  	}
    27  	defer fsrc.Close()
    28  	fdest, err := os.Create(dest)
    29  	if err != nil {
    30  		t.Fatal("os.Create failed: ", err)
    31  	}
    32  	defer fdest.Close()
    33  	_, err = io.Copy(fdest, fsrc)
    34  	if err != nil {
    35  		t.Fatal("io.Copy failed: ", err)
    36  	}
    37  }
    38  
    39  func installBat(t *testing.T, dest string) {
    40  	f, err := os.Create(dest)
    41  	if err != nil {
    42  		t.Fatalf("failed to create batch file: %v", err)
    43  	}
    44  	defer f.Close()
    45  	fmt.Fprintf(f, "@echo %s\n", dest)
    46  }
    47  
    48  func installProg(t *testing.T, dest, srcExe string) {
    49  	err := os.MkdirAll(filepath.Dir(dest), 0700)
    50  	if err != nil {
    51  		t.Fatal("os.MkdirAll failed: ", err)
    52  	}
    53  	if strings.ToLower(filepath.Ext(dest)) == ".bat" {
    54  		installBat(t, dest)
    55  		return
    56  	}
    57  	installExe(t, dest, srcExe)
    58  }
    59  
    60  type lookPathTest struct {
    61  	rootDir   string
    62  	PATH      string
    63  	PATHEXT   string
    64  	files     []string
    65  	searchFor string
    66  	fails     bool // test is expected to fail
    67  }
    68  
    69  func (test lookPathTest) runProg(t *testing.T, env []string, args ...string) (string, error) {
    70  	cmd := exec.Command(args[0], args[1:]...)
    71  	cmd.Env = env
    72  	cmd.Dir = test.rootDir
    73  	args[0] = filepath.Base(args[0])
    74  	cmdText := fmt.Sprintf("%q command", strings.Join(args, " "))
    75  	out, err := cmd.CombinedOutput()
    76  	if (err != nil) != test.fails {
    77  		if test.fails {
    78  			t.Fatalf("test=%+v: %s succeeded, but expected to fail", test, cmdText)
    79  		}
    80  		t.Fatalf("test=%+v: %s failed, but expected to succeed: %v - %v", test, cmdText, err, string(out))
    81  	}
    82  	if err != nil {
    83  		return "", fmt.Errorf("test=%+v: %s failed: %v - %v", test, cmdText, err, string(out))
    84  	}
    85  	// normalise program output
    86  	p := string(out)
    87  	// trim terminating \r and \n that batch file outputs
    88  	for len(p) > 0 && (p[len(p)-1] == '\n' || p[len(p)-1] == '\r') {
    89  		p = p[:len(p)-1]
    90  	}
    91  	if !filepath.IsAbs(p) {
    92  		return p, nil
    93  	}
    94  	if p[:len(test.rootDir)] != test.rootDir {
    95  		t.Fatalf("test=%+v: %s output is wrong: %q must have %q prefix", test, cmdText, p, test.rootDir)
    96  	}
    97  	return p[len(test.rootDir)+1:], nil
    98  }
    99  
   100  func updateEnv(env []string, name, value string) []string {
   101  	for i, e := range env {
   102  		if strings.HasPrefix(strings.ToUpper(e), name+"=") {
   103  			env[i] = name + "=" + value
   104  			return env
   105  		}
   106  	}
   107  	return append(env, name+"="+value)
   108  }
   109  
   110  func createEnv(dir, PATH, PATHEXT string) []string {
   111  	env := os.Environ()
   112  	env = updateEnv(env, "PATHEXT", PATHEXT)
   113  	// Add dir in front of every directory in the PATH.
   114  	dirs := filepath.SplitList(PATH)
   115  	for i := range dirs {
   116  		dirs[i] = filepath.Join(dir, dirs[i])
   117  	}
   118  	path := strings.Join(dirs, ";")
   119  	env = updateEnv(env, "PATH", os.Getenv("SystemRoot")+"/System32;"+path)
   120  	return env
   121  }
   122  
   123  // createFiles copies srcPath file into multiply files.
   124  // It uses dir as prefix for all destination files.
   125  func createFiles(t *testing.T, dir string, files []string, srcPath string) {
   126  	for _, f := range files {
   127  		installProg(t, filepath.Join(dir, f), srcPath)
   128  	}
   129  }
   130  
   131  func (test lookPathTest) run(t *testing.T, tmpdir, printpathExe string) {
   132  	test.rootDir = tmpdir
   133  	createFiles(t, test.rootDir, test.files, printpathExe)
   134  	env := createEnv(test.rootDir, test.PATH, test.PATHEXT)
   135  	// Run "cmd.exe /c test.searchFor" with new environment and
   136  	// work directory set. All candidates are copies of printpath.exe.
   137  	// These will output their program paths when run.
   138  	should, errCmd := test.runProg(t, env, "cmd", "/c", test.searchFor)
   139  	// Run the lookpath program with new environment and work directory set.
   140  	env = append(env, "GO_WANT_HELPER_PROCESS=1")
   141  	have, errLP := test.runProg(t, env, os.Args[0], "-test.run=TestHelperProcess", "--", "lookpath", test.searchFor)
   142  	// Compare results.
   143  	if errCmd == nil && errLP == nil {
   144  		// both succeeded
   145  		if should != have {
   146  			t.Fatalf("test=%+v failed: expected to find %q, but found %q", test, should, have)
   147  		}
   148  		return
   149  	}
   150  	if errCmd != nil && errLP != nil {
   151  		// both failed -> continue
   152  		return
   153  	}
   154  	if errCmd != nil {
   155  		t.Fatal(errCmd)
   156  	}
   157  	if errLP != nil {
   158  		t.Fatal(errLP)
   159  	}
   160  }
   161  
   162  var lookPathTests = []lookPathTest{
   163  	{
   164  		PATHEXT:   `.COM;.EXE;.BAT`,
   165  		PATH:      `p1;p2`,
   166  		files:     []string{`p1\a.exe`, `p2\a.exe`, `p2\a`},
   167  		searchFor: `a`,
   168  	},
   169  	{
   170  		PATHEXT:   `.COM;.EXE;.BAT`,
   171  		PATH:      `p1.dir;p2.dir`,
   172  		files:     []string{`p1.dir\a`, `p2.dir\a.exe`},
   173  		searchFor: `a`,
   174  	},
   175  	{
   176  		PATHEXT:   `.COM;.EXE;.BAT`,
   177  		PATH:      `p1;p2`,
   178  		files:     []string{`p1\a.exe`, `p2\a.exe`},
   179  		searchFor: `a.exe`,
   180  	},
   181  	{
   182  		PATHEXT:   `.COM;.EXE;.BAT`,
   183  		PATH:      `p1;p2`,
   184  		files:     []string{`p1\a.exe`, `p2\b.exe`},
   185  		searchFor: `b`,
   186  	},
   187  	{
   188  		PATHEXT:   `.COM;.EXE;.BAT`,
   189  		PATH:      `p1;p2`,
   190  		files:     []string{`p1\b`, `p2\a`},
   191  		searchFor: `a`,
   192  		fails:     true, // TODO(brainman): do not know why this fails
   193  	},
   194  	// If the command name specifies a path, the shell searches
   195  	// the specified path for an executable file matching
   196  	// the command name. If a match is found, the external
   197  	// command (the executable file) executes.
   198  	{
   199  		PATHEXT:   `.COM;.EXE;.BAT`,
   200  		PATH:      `p1;p2`,
   201  		files:     []string{`p1\a.exe`, `p2\a.exe`},
   202  		searchFor: `p2\a`,
   203  	},
   204  	// If the command name specifies a path, the shell searches
   205  	// the specified path for an executable file matching the command
   206  	// name. ... If no match is found, the shell reports an error
   207  	// and command processing completes.
   208  	{
   209  		PATHEXT:   `.COM;.EXE;.BAT`,
   210  		PATH:      `p1;p2`,
   211  		files:     []string{`p1\b.exe`, `p2\a.exe`},
   212  		searchFor: `p2\b`,
   213  		fails:     true,
   214  	},
   215  	// If the command name does not specify a path, the shell
   216  	// searches the current directory for an executable file
   217  	// matching the command name. If a match is found, the external
   218  	// command (the executable file) executes.
   219  	{
   220  		PATHEXT:   `.COM;.EXE;.BAT`,
   221  		PATH:      `p1;p2`,
   222  		files:     []string{`a`, `p1\a.exe`, `p2\a.exe`},
   223  		searchFor: `a`,
   224  	},
   225  	// The shell now searches each directory specified by the
   226  	// PATH environment variable, in the order listed, for an
   227  	// executable file matching the command name. If a match
   228  	// is found, the external command (the executable file) executes.
   229  	{
   230  		PATHEXT:   `.COM;.EXE;.BAT`,
   231  		PATH:      `p1;p2`,
   232  		files:     []string{`p1\a.exe`, `p2\a.exe`},
   233  		searchFor: `a`,
   234  	},
   235  	// The shell now searches each directory specified by the
   236  	// PATH environment variable, in the order listed, for an
   237  	// executable file matching the command name. If no match
   238  	// is found, the shell reports an error and command processing
   239  	// completes.
   240  	{
   241  		PATHEXT:   `.COM;.EXE;.BAT`,
   242  		PATH:      `p1;p2`,
   243  		files:     []string{`p1\a.exe`, `p2\a.exe`},
   244  		searchFor: `b`,
   245  		fails:     true,
   246  	},
   247  	// If the command name includes a file extension, the shell
   248  	// searches each directory for the exact file name specified
   249  	// by the command name.
   250  	{
   251  		PATHEXT:   `.COM;.EXE;.BAT`,
   252  		PATH:      `p1;p2`,
   253  		files:     []string{`p1\a.exe`, `p2\a.exe`},
   254  		searchFor: `a.exe`,
   255  	},
   256  	{
   257  		PATHEXT:   `.COM;.EXE;.BAT`,
   258  		PATH:      `p1;p2`,
   259  		files:     []string{`p1\a.exe`, `p2\a.exe`},
   260  		searchFor: `a.com`,
   261  		fails:     true, // includes extension and not exact file name match
   262  	},
   263  	{
   264  		PATHEXT:   `.COM;.EXE;.BAT`,
   265  		PATH:      `p1`,
   266  		files:     []string{`p1\a.exe.exe`},
   267  		searchFor: `a.exe`,
   268  	},
   269  	{
   270  		PATHEXT:   `.COM;.BAT`,
   271  		PATH:      `p1;p2`,
   272  		files:     []string{`p1\a.exe`, `p2\a.exe`},
   273  		searchFor: `a.exe`,
   274  	},
   275  	// If the command name does not include a file extension, the shell
   276  	// adds the extensions listed in the PATHEXT environment variable,
   277  	// one by one, and searches the directory for that file name. Note
   278  	// that the shell tries all possible file extensions in a specific
   279  	// directory before moving on to search the next directory
   280  	// (if there is one).
   281  	{
   282  		PATHEXT:   `.COM;.EXE`,
   283  		PATH:      `p1;p2`,
   284  		files:     []string{`p1\a.bat`, `p2\a.exe`},
   285  		searchFor: `a`,
   286  	},
   287  	{
   288  		PATHEXT:   `.COM;.EXE;.BAT`,
   289  		PATH:      `p1;p2`,
   290  		files:     []string{`p1\a.bat`, `p2\a.exe`},
   291  		searchFor: `a`,
   292  	},
   293  	{
   294  		PATHEXT:   `.COM;.EXE;.BAT`,
   295  		PATH:      `p1;p2`,
   296  		files:     []string{`p1\a.bat`, `p1\a.exe`, `p2\a.bat`, `p2\a.exe`},
   297  		searchFor: `a`,
   298  	},
   299  	{
   300  		PATHEXT:   `.COM`,
   301  		PATH:      `p1;p2`,
   302  		files:     []string{`p1\a.bat`, `p2\a.exe`},
   303  		searchFor: `a`,
   304  		fails:     true, // tried all extensions in PATHEXT, but none matches
   305  	},
   306  }
   307  
   308  func TestLookPath(t *testing.T) {
   309  	tmp, err := os.MkdirTemp("", "TestLookPath")
   310  	if err != nil {
   311  		t.Fatal("TempDir failed: ", err)
   312  	}
   313  	defer os.RemoveAll(tmp)
   314  
   315  	printpathExe := buildPrintPathExe(t, tmp)
   316  
   317  	// Run all tests.
   318  	for i, test := range lookPathTests {
   319  		dir := filepath.Join(tmp, "d"+strconv.Itoa(i))
   320  		err := os.Mkdir(dir, 0700)
   321  		if err != nil {
   322  			t.Fatal("Mkdir failed: ", err)
   323  		}
   324  		test.run(t, dir, printpathExe)
   325  	}
   326  }
   327  
   328  type commandTest struct {
   329  	PATH  string
   330  	files []string
   331  	dir   string
   332  	arg0  string
   333  	want  string
   334  	fails bool // test is expected to fail
   335  }
   336  
   337  func (test commandTest) isSuccess(rootDir, output string, err error) error {
   338  	if err != nil {
   339  		return fmt.Errorf("test=%+v: exec: %v %v", test, err, output)
   340  	}
   341  	path := output
   342  	if path[:len(rootDir)] != rootDir {
   343  		return fmt.Errorf("test=%+v: %q must have %q prefix", test, path, rootDir)
   344  	}
   345  	path = path[len(rootDir)+1:]
   346  	if path != test.want {
   347  		return fmt.Errorf("test=%+v: want %q, got %q", test, test.want, path)
   348  	}
   349  	return nil
   350  }
   351  
   352  func (test commandTest) runOne(rootDir string, env []string, dir, arg0 string) error {
   353  	cmd := exec.Command(os.Args[0], "-test.run=TestHelperProcess", "--", "exec", dir, arg0)
   354  	cmd.Dir = rootDir
   355  	cmd.Env = env
   356  	output, err := cmd.CombinedOutput()
   357  	err = test.isSuccess(rootDir, string(output), err)
   358  	if (err != nil) != test.fails {
   359  		if test.fails {
   360  			return fmt.Errorf("test=%+v: succeeded, but expected to fail", test)
   361  		}
   362  		return err
   363  	}
   364  	return nil
   365  }
   366  
   367  func (test commandTest) run(t *testing.T, rootDir, printpathExe string) {
   368  	createFiles(t, rootDir, test.files, printpathExe)
   369  	PATHEXT := `.COM;.EXE;.BAT`
   370  	env := createEnv(rootDir, test.PATH, PATHEXT)
   371  	env = append(env, "GO_WANT_HELPER_PROCESS=1")
   372  	err := test.runOne(rootDir, env, test.dir, test.arg0)
   373  	if err != nil {
   374  		t.Error(err)
   375  	}
   376  }
   377  
   378  var commandTests = []commandTest{
   379  	// testing commands with no slash, like `a.exe`
   380  	{
   381  		// should find a.exe in current directory
   382  		files: []string{`a.exe`},
   383  		arg0:  `a.exe`,
   384  		want:  `a.exe`,
   385  	},
   386  	{
   387  		// like above, but add PATH in attempt to break the test
   388  		PATH:  `p2;p`,
   389  		files: []string{`a.exe`, `p\a.exe`, `p2\a.exe`},
   390  		arg0:  `a.exe`,
   391  		want:  `a.exe`,
   392  	},
   393  	{
   394  		// like above, but use "a" instead of "a.exe" for command
   395  		PATH:  `p2;p`,
   396  		files: []string{`a.exe`, `p\a.exe`, `p2\a.exe`},
   397  		arg0:  `a`,
   398  		want:  `a.exe`,
   399  	},
   400  	// testing commands with slash, like `.\a.exe`
   401  	{
   402  		// should find p\a.exe
   403  		files: []string{`p\a.exe`},
   404  		arg0:  `p\a.exe`,
   405  		want:  `p\a.exe`,
   406  	},
   407  	{
   408  		// like above, but adding `.` in front of executable should still be OK
   409  		files: []string{`p\a.exe`},
   410  		arg0:  `.\p\a.exe`,
   411  		want:  `p\a.exe`,
   412  	},
   413  	{
   414  		// like above, but with PATH added in attempt to break it
   415  		PATH:  `p2`,
   416  		files: []string{`p\a.exe`, `p2\a.exe`},
   417  		arg0:  `p\a.exe`,
   418  		want:  `p\a.exe`,
   419  	},
   420  	{
   421  		// like above, but make sure .exe is tried even for commands with slash
   422  		PATH:  `p2`,
   423  		files: []string{`p\a.exe`, `p2\a.exe`},
   424  		arg0:  `p\a`,
   425  		want:  `p\a.exe`,
   426  	},
   427  	// tests commands, like `a.exe`, with c.Dir set
   428  	{
   429  		// should not find a.exe in p, because LookPath(`a.exe`) will fail
   430  		files: []string{`p\a.exe`},
   431  		dir:   `p`,
   432  		arg0:  `a.exe`,
   433  		want:  `p\a.exe`,
   434  		fails: true,
   435  	},
   436  	{
   437  		// LookPath(`a.exe`) will find `.\a.exe`, but prefixing that with
   438  		// dir `p\a.exe` will refer to a non-existent file
   439  		files: []string{`a.exe`, `p\not_important_file`},
   440  		dir:   `p`,
   441  		arg0:  `a.exe`,
   442  		want:  `a.exe`,
   443  		fails: true,
   444  	},
   445  	{
   446  		// like above, but making test succeed by installing file
   447  		// in referred destination (so LookPath(`a.exe`) will still
   448  		// find `.\a.exe`, but we successfully execute `p\a.exe`)
   449  		files: []string{`a.exe`, `p\a.exe`},
   450  		dir:   `p`,
   451  		arg0:  `a.exe`,
   452  		want:  `p\a.exe`,
   453  	},
   454  	{
   455  		// like above, but add PATH in attempt to break the test
   456  		PATH:  `p2;p`,
   457  		files: []string{`a.exe`, `p\a.exe`, `p2\a.exe`},
   458  		dir:   `p`,
   459  		arg0:  `a.exe`,
   460  		want:  `p\a.exe`,
   461  	},
   462  	{
   463  		// like above, but use "a" instead of "a.exe" for command
   464  		PATH:  `p2;p`,
   465  		files: []string{`a.exe`, `p\a.exe`, `p2\a.exe`},
   466  		dir:   `p`,
   467  		arg0:  `a`,
   468  		want:  `p\a.exe`,
   469  	},
   470  	{
   471  		// finds `a.exe` in the PATH regardless of dir set
   472  		// because LookPath returns full path in that case
   473  		PATH:  `p2;p`,
   474  		files: []string{`p\a.exe`, `p2\a.exe`},
   475  		dir:   `p`,
   476  		arg0:  `a.exe`,
   477  		want:  `p2\a.exe`,
   478  	},
   479  	// tests commands, like `.\a.exe`, with c.Dir set
   480  	{
   481  		// should use dir when command is path, like ".\a.exe"
   482  		files: []string{`p\a.exe`},
   483  		dir:   `p`,
   484  		arg0:  `.\a.exe`,
   485  		want:  `p\a.exe`,
   486  	},
   487  	{
   488  		// like above, but with PATH added in attempt to break it
   489  		PATH:  `p2`,
   490  		files: []string{`p\a.exe`, `p2\a.exe`},
   491  		dir:   `p`,
   492  		arg0:  `.\a.exe`,
   493  		want:  `p\a.exe`,
   494  	},
   495  	{
   496  		// like above, but make sure .exe is tried even for commands with slash
   497  		PATH:  `p2`,
   498  		files: []string{`p\a.exe`, `p2\a.exe`},
   499  		dir:   `p`,
   500  		arg0:  `.\a`,
   501  		want:  `p\a.exe`,
   502  	},
   503  }
   504  
   505  func TestCommand(t *testing.T) {
   506  	tmp, err := os.MkdirTemp("", "TestCommand")
   507  	if err != nil {
   508  		t.Fatal("TempDir failed: ", err)
   509  	}
   510  	defer os.RemoveAll(tmp)
   511  
   512  	printpathExe := buildPrintPathExe(t, tmp)
   513  
   514  	// Run all tests.
   515  	for i, test := range commandTests {
   516  		dir := filepath.Join(tmp, "d"+strconv.Itoa(i))
   517  		err := os.Mkdir(dir, 0700)
   518  		if err != nil {
   519  			t.Fatal("Mkdir failed: ", err)
   520  		}
   521  		test.run(t, dir, printpathExe)
   522  	}
   523  }
   524  
   525  // buildPrintPathExe creates a Go program that prints its own path.
   526  // dir is a temp directory where executable will be created.
   527  // The function returns full path to the created program.
   528  func buildPrintPathExe(t *testing.T, dir string) string {
   529  	const name = "printpath"
   530  	srcname := name + ".go"
   531  	err := os.WriteFile(filepath.Join(dir, srcname), []byte(printpathSrc), 0644)
   532  	if err != nil {
   533  		t.Fatalf("failed to create source: %v", err)
   534  	}
   535  	if err != nil {
   536  		t.Fatalf("failed to execute template: %v", err)
   537  	}
   538  	outname := name + ".exe"
   539  	cmd := exec.Command(testenv.GoToolPath(t), "build", "-o", outname, srcname)
   540  	cmd.Dir = dir
   541  	out, err := cmd.CombinedOutput()
   542  	if err != nil {
   543  		t.Fatalf("failed to build executable: %v - %v", err, string(out))
   544  	}
   545  	return filepath.Join(dir, outname)
   546  }
   547  
   548  const printpathSrc = `
   549  package main
   550  
   551  import (
   552  	"os"
   553  	"syscall"
   554  	"unicode/utf16"
   555  	"unsafe"
   556  )
   557  
   558  func getMyName() (string, error) {
   559  	var sysproc = syscall.MustLoadDLL("kernel32.dll").MustFindProc("GetModuleFileNameW")
   560  	b := make([]uint16, syscall.MAX_PATH)
   561  	r, _, err := sysproc.Call(0, uintptr(unsafe.Pointer(&b[0])), uintptr(len(b)))
   562  	n := uint32(r)
   563  	if n == 0 {
   564  		return "", err
   565  	}
   566  	return string(utf16.Decode(b[0:n])), nil
   567  }
   568  
   569  func main() {
   570  	path, err := getMyName()
   571  	if err != nil {
   572  		os.Stderr.Write([]byte("getMyName failed: " + err.Error() + "\n"))
   573  		os.Exit(1)
   574  	}
   575  	os.Stdout.Write([]byte(path))
   576  }
   577  `