...
Run Format

Source file src/os/exec/exec_test.go

Documentation: os/exec

     1  // Copyright 2009 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Use an external test to avoid os/exec -> net/http -> crypto/x509 -> os/exec
     6  // circular dependency on non-cgo darwin.
     7  
     8  package exec_test
     9  
    10  import (
    11  	"bufio"
    12  	"bytes"
    13  	"context"
    14  	"fmt"
    15  	"internal/poll"
    16  	"internal/testenv"
    17  	"io"
    18  	"io/ioutil"
    19  	"log"
    20  	"net"
    21  	"net/http"
    22  	"net/http/httptest"
    23  	"os"
    24  	"os/exec"
    25  	"path/filepath"
    26  	"runtime"
    27  	"strconv"
    28  	"strings"
    29  	"testing"
    30  	"time"
    31  )
    32  
    33  func helperCommandContext(t *testing.T, ctx context.Context, s ...string) (cmd *exec.Cmd) {
    34  	testenv.MustHaveExec(t)
    35  
    36  	cs := []string{"-test.run=TestHelperProcess", "--"}
    37  	cs = append(cs, s...)
    38  	if ctx != nil {
    39  		cmd = exec.CommandContext(ctx, os.Args[0], cs...)
    40  	} else {
    41  		cmd = exec.Command(os.Args[0], cs...)
    42  	}
    43  	cmd.Env = []string{"GO_WANT_HELPER_PROCESS=1"}
    44  	return cmd
    45  }
    46  
    47  func helperCommand(t *testing.T, s ...string) *exec.Cmd {
    48  	return helperCommandContext(t, nil, s...)
    49  }
    50  
    51  func TestEcho(t *testing.T) {
    52  	bs, err := helperCommand(t, "echo", "foo bar", "baz").Output()
    53  	if err != nil {
    54  		t.Errorf("echo: %v", err)
    55  	}
    56  	if g, e := string(bs), "foo bar baz\n"; g != e {
    57  		t.Errorf("echo: want %q, got %q", e, g)
    58  	}
    59  }
    60  
    61  func TestCommandRelativeName(t *testing.T) {
    62  	testenv.MustHaveExec(t)
    63  
    64  	// Run our own binary as a relative path
    65  	// (e.g. "_test/exec.test") our parent directory.
    66  	base := filepath.Base(os.Args[0]) // "exec.test"
    67  	dir := filepath.Dir(os.Args[0])   // "/tmp/go-buildNNNN/os/exec/_test"
    68  	if dir == "." {
    69  		t.Skip("skipping; running test at root somehow")
    70  	}
    71  	parentDir := filepath.Dir(dir) // "/tmp/go-buildNNNN/os/exec"
    72  	dirBase := filepath.Base(dir)  // "_test"
    73  	if dirBase == "." {
    74  		t.Skipf("skipping; unexpected shallow dir of %q", dir)
    75  	}
    76  
    77  	cmd := exec.Command(filepath.Join(dirBase, base), "-test.run=TestHelperProcess", "--", "echo", "foo")
    78  	cmd.Dir = parentDir
    79  	cmd.Env = []string{"GO_WANT_HELPER_PROCESS=1"}
    80  
    81  	out, err := cmd.Output()
    82  	if err != nil {
    83  		t.Errorf("echo: %v", err)
    84  	}
    85  	if g, e := string(out), "foo\n"; g != e {
    86  		t.Errorf("echo: want %q, got %q", e, g)
    87  	}
    88  }
    89  
    90  func TestCatStdin(t *testing.T) {
    91  	// Cat, testing stdin and stdout.
    92  	input := "Input string\nLine 2"
    93  	p := helperCommand(t, "cat")
    94  	p.Stdin = strings.NewReader(input)
    95  	bs, err := p.Output()
    96  	if err != nil {
    97  		t.Errorf("cat: %v", err)
    98  	}
    99  	s := string(bs)
   100  	if s != input {
   101  		t.Errorf("cat: want %q, got %q", input, s)
   102  	}
   103  }
   104  
   105  func TestEchoFileRace(t *testing.T) {
   106  	cmd := helperCommand(t, "echo")
   107  	stdin, err := cmd.StdinPipe()
   108  	if err != nil {
   109  		t.Fatalf("StdinPipe: %v", err)
   110  	}
   111  	if err := cmd.Start(); err != nil {
   112  		t.Fatalf("Start: %v", err)
   113  	}
   114  	wrote := make(chan bool)
   115  	go func() {
   116  		defer close(wrote)
   117  		fmt.Fprint(stdin, "echo\n")
   118  	}()
   119  	if err := cmd.Wait(); err != nil {
   120  		t.Fatalf("Wait: %v", err)
   121  	}
   122  	<-wrote
   123  }
   124  
   125  func TestCatGoodAndBadFile(t *testing.T) {
   126  	// Testing combined output and error values.
   127  	bs, err := helperCommand(t, "cat", "/bogus/file.foo", "exec_test.go").CombinedOutput()
   128  	if _, ok := err.(*exec.ExitError); !ok {
   129  		t.Errorf("expected *exec.ExitError from cat combined; got %T: %v", err, err)
   130  	}
   131  	s := string(bs)
   132  	sp := strings.SplitN(s, "\n", 2)
   133  	if len(sp) != 2 {
   134  		t.Fatalf("expected two lines from cat; got %q", s)
   135  	}
   136  	errLine, body := sp[0], sp[1]
   137  	if !strings.HasPrefix(errLine, "Error: open /bogus/file.foo") {
   138  		t.Errorf("expected stderr to complain about file; got %q", errLine)
   139  	}
   140  	if !strings.Contains(body, "func TestHelperProcess(t *testing.T)") {
   141  		t.Errorf("expected test code; got %q (len %d)", body, len(body))
   142  	}
   143  }
   144  
   145  func TestNoExistExecutable(t *testing.T) {
   146  	// Can't run a non-existent executable
   147  	err := exec.Command("/no-exist-executable").Run()
   148  	if err == nil {
   149  		t.Error("expected error from /no-exist-executable")
   150  	}
   151  }
   152  
   153  func TestExitStatus(t *testing.T) {
   154  	// Test that exit values are returned correctly
   155  	cmd := helperCommand(t, "exit", "42")
   156  	err := cmd.Run()
   157  	want := "exit status 42"
   158  	switch runtime.GOOS {
   159  	case "plan9":
   160  		want = fmt.Sprintf("exit status: '%s %d: 42'", filepath.Base(cmd.Path), cmd.ProcessState.Pid())
   161  	}
   162  	if werr, ok := err.(*exec.ExitError); ok {
   163  		if s := werr.Error(); s != want {
   164  			t.Errorf("from exit 42 got exit %q, want %q", s, want)
   165  		}
   166  	} else {
   167  		t.Fatalf("expected *exec.ExitError from exit 42; got %T: %v", err, err)
   168  	}
   169  }
   170  
   171  func TestPipes(t *testing.T) {
   172  	check := func(what string, err error) {
   173  		if err != nil {
   174  			t.Fatalf("%s: %v", what, err)
   175  		}
   176  	}
   177  	// Cat, testing stdin and stdout.
   178  	c := helperCommand(t, "pipetest")
   179  	stdin, err := c.StdinPipe()
   180  	check("StdinPipe", err)
   181  	stdout, err := c.StdoutPipe()
   182  	check("StdoutPipe", err)
   183  	stderr, err := c.StderrPipe()
   184  	check("StderrPipe", err)
   185  
   186  	outbr := bufio.NewReader(stdout)
   187  	errbr := bufio.NewReader(stderr)
   188  	line := func(what string, br *bufio.Reader) string {
   189  		line, _, err := br.ReadLine()
   190  		if err != nil {
   191  			t.Fatalf("%s: %v", what, err)
   192  		}
   193  		return string(line)
   194  	}
   195  
   196  	err = c.Start()
   197  	check("Start", err)
   198  
   199  	_, err = stdin.Write([]byte("O:I am output\n"))
   200  	check("first stdin Write", err)
   201  	if g, e := line("first output line", outbr), "O:I am output"; g != e {
   202  		t.Errorf("got %q, want %q", g, e)
   203  	}
   204  
   205  	_, err = stdin.Write([]byte("E:I am error\n"))
   206  	check("second stdin Write", err)
   207  	if g, e := line("first error line", errbr), "E:I am error"; g != e {
   208  		t.Errorf("got %q, want %q", g, e)
   209  	}
   210  
   211  	_, err = stdin.Write([]byte("O:I am output2\n"))
   212  	check("third stdin Write 3", err)
   213  	if g, e := line("second output line", outbr), "O:I am output2"; g != e {
   214  		t.Errorf("got %q, want %q", g, e)
   215  	}
   216  
   217  	stdin.Close()
   218  	err = c.Wait()
   219  	check("Wait", err)
   220  }
   221  
   222  const stdinCloseTestString = "Some test string."
   223  
   224  // Issue 6270.
   225  func TestStdinClose(t *testing.T) {
   226  	check := func(what string, err error) {
   227  		if err != nil {
   228  			t.Fatalf("%s: %v", what, err)
   229  		}
   230  	}
   231  	cmd := helperCommand(t, "stdinClose")
   232  	stdin, err := cmd.StdinPipe()
   233  	check("StdinPipe", err)
   234  	// Check that we can access methods of the underlying os.File.`
   235  	if _, ok := stdin.(interface {
   236  		Fd() uintptr
   237  	}); !ok {
   238  		t.Error("can't access methods of underlying *os.File")
   239  	}
   240  	check("Start", cmd.Start())
   241  	go func() {
   242  		_, err := io.Copy(stdin, strings.NewReader(stdinCloseTestString))
   243  		check("Copy", err)
   244  		// Before the fix, this next line would race with cmd.Wait.
   245  		check("Close", stdin.Close())
   246  	}()
   247  	check("Wait", cmd.Wait())
   248  }
   249  
   250  // Issue 17647.
   251  // It used to be the case that TestStdinClose, above, would fail when
   252  // run under the race detector. This test is a variant of TestStdinClose
   253  // that also used to fail when run under the race detector.
   254  // This test is run by cmd/dist under the race detector to verify that
   255  // the race detector no longer reports any problems.
   256  func TestStdinCloseRace(t *testing.T) {
   257  	cmd := helperCommand(t, "stdinClose")
   258  	stdin, err := cmd.StdinPipe()
   259  	if err != nil {
   260  		t.Fatalf("StdinPipe: %v", err)
   261  	}
   262  	if err := cmd.Start(); err != nil {
   263  		t.Fatalf("Start: %v", err)
   264  	}
   265  	go func() {
   266  		// We don't check the error return of Kill. It is
   267  		// possible that the process has already exited, in
   268  		// which case Kill will return an error "process
   269  		// already finished". The purpose of this test is to
   270  		// see whether the race detector reports an error; it
   271  		// doesn't matter whether this Kill succeeds or not.
   272  		cmd.Process.Kill()
   273  	}()
   274  	go func() {
   275  		// Send the wrong string, so that the child fails even
   276  		// if the other goroutine doesn't manage to kill it first.
   277  		// This test is to check that the race detector does not
   278  		// falsely report an error, so it doesn't matter how the
   279  		// child process fails.
   280  		io.Copy(stdin, strings.NewReader("unexpected string"))
   281  		if err := stdin.Close(); err != nil {
   282  			t.Errorf("stdin.Close: %v", err)
   283  		}
   284  	}()
   285  	if err := cmd.Wait(); err == nil {
   286  		t.Fatalf("Wait: succeeded unexpectedly")
   287  	}
   288  }
   289  
   290  // Issue 5071
   291  func TestPipeLookPathLeak(t *testing.T) {
   292  	// If we are reading from /proc/self/fd we (should) get an exact result.
   293  	tolerance := 0
   294  
   295  	// Reading /proc/self/fd is more reliable than calling lsof, so try that
   296  	// first.
   297  	numOpenFDs := func() (int, []byte, error) {
   298  		fds, err := ioutil.ReadDir("/proc/self/fd")
   299  		if err != nil {
   300  			return 0, nil, err
   301  		}
   302  		return len(fds), nil, nil
   303  	}
   304  	want, before, err := numOpenFDs()
   305  	if err != nil {
   306  		// We encountered a problem reading /proc/self/fd (we might be on
   307  		// a platform that doesn't have it). Fall back onto lsof.
   308  		t.Logf("using lsof because: %v", err)
   309  		numOpenFDs = func() (int, []byte, error) {
   310  			// Android's stock lsof does not obey the -p option,
   311  			// so extra filtering is needed.
   312  			// https://golang.org/issue/10206
   313  			if runtime.GOOS == "android" {
   314  				// numOpenFDsAndroid handles errors itself and
   315  				// might skip or fail the test.
   316  				n, lsof := numOpenFDsAndroid(t)
   317  				return n, lsof, nil
   318  			}
   319  			lsof, err := exec.Command("lsof", "-b", "-n", "-p", strconv.Itoa(os.Getpid())).Output()
   320  			return bytes.Count(lsof, []byte("\n")), lsof, err
   321  		}
   322  
   323  		// lsof may see file descriptors associated with the fork itself,
   324  		// so we allow some extra margin if we have to use it.
   325  		// https://golang.org/issue/19243
   326  		tolerance = 5
   327  
   328  		// Retry reading the number of open file descriptors.
   329  		want, before, err = numOpenFDs()
   330  		if err != nil {
   331  			t.Log(err)
   332  			t.Skipf("skipping test; error finding or running lsof")
   333  		}
   334  	}
   335  
   336  	for i := 0; i < 6; i++ {
   337  		cmd := exec.Command("something-that-does-not-exist-executable")
   338  		cmd.StdoutPipe()
   339  		cmd.StderrPipe()
   340  		cmd.StdinPipe()
   341  		if err := cmd.Run(); err == nil {
   342  			t.Fatal("unexpected success")
   343  		}
   344  	}
   345  	got, after, err := numOpenFDs()
   346  	if err != nil {
   347  		// numOpenFDs has already succeeded once, it should work here.
   348  		t.Errorf("unexpected failure: %v", err)
   349  	}
   350  	if got-want > tolerance {
   351  		t.Errorf("number of open file descriptors changed: got %v, want %v", got, want)
   352  		if before != nil {
   353  			t.Errorf("before:\n%v\n", before)
   354  		}
   355  		if after != nil {
   356  			t.Errorf("after:\n%v\n", after)
   357  		}
   358  	}
   359  }
   360  
   361  func numOpenFDsAndroid(t *testing.T) (n int, lsof []byte) {
   362  	raw, err := exec.Command("lsof").Output()
   363  	if err != nil {
   364  		t.Skip("skipping test; error finding or running lsof")
   365  	}
   366  
   367  	// First find the PID column index by parsing the first line, and
   368  	// select lines containing pid in the column.
   369  	pid := []byte(strconv.Itoa(os.Getpid()))
   370  	pidCol := -1
   371  
   372  	s := bufio.NewScanner(bytes.NewReader(raw))
   373  	for s.Scan() {
   374  		line := s.Bytes()
   375  		fields := bytes.Fields(line)
   376  		if pidCol < 0 {
   377  			for i, v := range fields {
   378  				if bytes.Equal(v, []byte("PID")) {
   379  					pidCol = i
   380  					break
   381  				}
   382  			}
   383  			lsof = append(lsof, line...)
   384  			continue
   385  		}
   386  		if bytes.Equal(fields[pidCol], pid) {
   387  			lsof = append(lsof, '\n')
   388  			lsof = append(lsof, line...)
   389  		}
   390  	}
   391  	if pidCol < 0 {
   392  		t.Fatal("error processing lsof output: unexpected header format")
   393  	}
   394  	if err := s.Err(); err != nil {
   395  		t.Fatalf("error processing lsof output: %v", err)
   396  	}
   397  	return bytes.Count(lsof, []byte("\n")), lsof
   398  }
   399  
   400  var testedAlreadyLeaked = false
   401  
   402  // basefds returns the number of expected file descriptors
   403  // to be present in a process at start.
   404  // stdin, stdout, stderr, epoll/kqueue, maybe testlog
   405  func basefds() uintptr {
   406  	n := os.Stderr.Fd() + 1
   407  	// The poll (epoll/kqueue) descriptor can be numerically
   408  	// either between stderr and the testlog-fd, or after
   409  	// testlog-fd.
   410  	if poll.PollDescriptor() == n {
   411  		n++
   412  	}
   413  	for _, arg := range os.Args {
   414  		if strings.HasPrefix(arg, "-test.testlogfile=") {
   415  			n++
   416  		}
   417  	}
   418  	return n
   419  }
   420  
   421  func closeUnexpectedFds(t *testing.T, m string) {
   422  	for fd := basefds(); fd <= 101; fd++ {
   423  		if fd == poll.PollDescriptor() {
   424  			continue
   425  		}
   426  		err := os.NewFile(fd, "").Close()
   427  		if err == nil {
   428  			t.Logf("%s: Something already leaked - closed fd %d", m, fd)
   429  		}
   430  	}
   431  }
   432  
   433  func TestExtraFilesFDShuffle(t *testing.T) {
   434  	t.Skip("flaky test; see https://golang.org/issue/5780")
   435  	switch runtime.GOOS {
   436  	case "darwin":
   437  		// TODO(cnicolaou): https://golang.org/issue/2603
   438  		// leads to leaked file descriptors in this test when it's
   439  		// run from a builder.
   440  		closeUnexpectedFds(t, "TestExtraFilesFDShuffle")
   441  	case "netbsd":
   442  		// https://golang.org/issue/3955
   443  		closeUnexpectedFds(t, "TestExtraFilesFDShuffle")
   444  	case "windows":
   445  		t.Skip("no operating system support; skipping")
   446  	}
   447  
   448  	// syscall.StartProcess maps all the FDs passed to it in
   449  	// ProcAttr.Files (the concatenation of stdin,stdout,stderr and
   450  	// ExtraFiles) into consecutive FDs in the child, that is:
   451  	// Files{11, 12, 6, 7, 9, 3} should result in the file
   452  	// represented by FD 11 in the parent being made available as 0
   453  	// in the child, 12 as 1, etc.
   454  	//
   455  	// We want to test that FDs in the child do not get overwritten
   456  	// by one another as this shuffle occurs. The original implementation
   457  	// was buggy in that in some data dependent cases it would overwrite
   458  	// stderr in the child with one of the ExtraFile members.
   459  	// Testing for this case is difficult because it relies on using
   460  	// the same FD values as that case. In particular, an FD of 3
   461  	// must be at an index of 4 or higher in ProcAttr.Files and
   462  	// the FD of the write end of the Stderr pipe (as obtained by
   463  	// StderrPipe()) must be the same as the size of ProcAttr.Files;
   464  	// therefore we test that the read end of this pipe (which is what
   465  	// is returned to the parent by StderrPipe() being one less than
   466  	// the size of ProcAttr.Files, i.e. 3+len(cmd.ExtraFiles).
   467  	//
   468  	// Moving this test case around within the overall tests may
   469  	// affect the FDs obtained and hence the checks to catch these cases.
   470  	npipes := 2
   471  	c := helperCommand(t, "extraFilesAndPipes", strconv.Itoa(npipes+1))
   472  	rd, wr, _ := os.Pipe()
   473  	defer rd.Close()
   474  	if rd.Fd() != 3 {
   475  		t.Errorf("bad test value for test pipe: fd %d", rd.Fd())
   476  	}
   477  	stderr, _ := c.StderrPipe()
   478  	wr.WriteString("_LAST")
   479  	wr.Close()
   480  
   481  	pipes := make([]struct {
   482  		r, w *os.File
   483  	}, npipes)
   484  	data := []string{"a", "b"}
   485  
   486  	for i := 0; i < npipes; i++ {
   487  		r, w, err := os.Pipe()
   488  		if err != nil {
   489  			t.Fatalf("unexpected error creating pipe: %s", err)
   490  		}
   491  		pipes[i].r = r
   492  		pipes[i].w = w
   493  		w.WriteString(data[i])
   494  		c.ExtraFiles = append(c.ExtraFiles, pipes[i].r)
   495  		defer func() {
   496  			r.Close()
   497  			w.Close()
   498  		}()
   499  	}
   500  	// Put fd 3 at the end.
   501  	c.ExtraFiles = append(c.ExtraFiles, rd)
   502  
   503  	stderrFd := int(stderr.(*os.File).Fd())
   504  	if stderrFd != ((len(c.ExtraFiles) + 3) - 1) {
   505  		t.Errorf("bad test value for stderr pipe")
   506  	}
   507  
   508  	expected := "child: " + strings.Join(data, "") + "_LAST"
   509  
   510  	err := c.Start()
   511  	if err != nil {
   512  		t.Fatalf("Run: %v", err)
   513  	}
   514  	ch := make(chan string, 1)
   515  	go func(ch chan string) {
   516  		buf := make([]byte, 512)
   517  		n, err := stderr.Read(buf)
   518  		if err != nil {
   519  			t.Errorf("Read: %s", err)
   520  			ch <- err.Error()
   521  		} else {
   522  			ch <- string(buf[:n])
   523  		}
   524  		close(ch)
   525  	}(ch)
   526  	select {
   527  	case m := <-ch:
   528  		if m != expected {
   529  			t.Errorf("Read: '%s' not '%s'", m, expected)
   530  		}
   531  	case <-time.After(5 * time.Second):
   532  		t.Errorf("Read timedout")
   533  	}
   534  	c.Wait()
   535  }
   536  
   537  func TestExtraFiles(t *testing.T) {
   538  	testenv.MustHaveExec(t)
   539  
   540  	if runtime.GOOS == "windows" {
   541  		t.Skipf("skipping test on %q", runtime.GOOS)
   542  	}
   543  
   544  	// Ensure that file descriptors have not already been leaked into
   545  	// our environment.
   546  	if !testedAlreadyLeaked {
   547  		testedAlreadyLeaked = true
   548  		closeUnexpectedFds(t, "TestExtraFiles")
   549  	}
   550  
   551  	// Force network usage, to verify the epoll (or whatever) fd
   552  	// doesn't leak to the child,
   553  	ln, err := net.Listen("tcp", "127.0.0.1:0")
   554  	if err != nil {
   555  		t.Fatal(err)
   556  	}
   557  	defer ln.Close()
   558  
   559  	// Make sure duplicated fds don't leak to the child.
   560  	f, err := ln.(*net.TCPListener).File()
   561  	if err != nil {
   562  		t.Fatal(err)
   563  	}
   564  	defer f.Close()
   565  	ln2, err := net.FileListener(f)
   566  	if err != nil {
   567  		t.Fatal(err)
   568  	}
   569  	defer ln2.Close()
   570  
   571  	// Force TLS root certs to be loaded (which might involve
   572  	// cgo), to make sure none of that potential C code leaks fds.
   573  	ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
   574  	// quiet expected TLS handshake error "remote error: bad certificate"
   575  	ts.Config.ErrorLog = log.New(ioutil.Discard, "", 0)
   576  	ts.StartTLS()
   577  	defer ts.Close()
   578  	_, err = http.Get(ts.URL)
   579  	if err == nil {
   580  		t.Errorf("success trying to fetch %s; want an error", ts.URL)
   581  	}
   582  
   583  	tf, err := ioutil.TempFile("", "")
   584  	if err != nil {
   585  		t.Fatalf("TempFile: %v", err)
   586  	}
   587  	defer os.Remove(tf.Name())
   588  	defer tf.Close()
   589  
   590  	const text = "Hello, fd 3!"
   591  	_, err = tf.Write([]byte(text))
   592  	if err != nil {
   593  		t.Fatalf("Write: %v", err)
   594  	}
   595  	_, err = tf.Seek(0, io.SeekStart)
   596  	if err != nil {
   597  		t.Fatalf("Seek: %v", err)
   598  	}
   599  
   600  	c := helperCommand(t, "read3")
   601  	var stdout, stderr bytes.Buffer
   602  	c.Stdout = &stdout
   603  	c.Stderr = &stderr
   604  	c.ExtraFiles = []*os.File{tf}
   605  	err = c.Run()
   606  	if err != nil {
   607  		t.Fatalf("Run: %v; stdout %q, stderr %q", err, stdout.Bytes(), stderr.Bytes())
   608  	}
   609  	if stdout.String() != text {
   610  		t.Errorf("got stdout %q, stderr %q; want %q on stdout", stdout.String(), stderr.String(), text)
   611  	}
   612  }
   613  
   614  func TestExtraFilesRace(t *testing.T) {
   615  	if runtime.GOOS == "windows" {
   616  		t.Skip("no operating system support; skipping")
   617  	}
   618  	listen := func() net.Listener {
   619  		ln, err := net.Listen("tcp", "127.0.0.1:0")
   620  		if err != nil {
   621  			t.Fatal(err)
   622  		}
   623  		return ln
   624  	}
   625  	listenerFile := func(ln net.Listener) *os.File {
   626  		f, err := ln.(*net.TCPListener).File()
   627  		if err != nil {
   628  			t.Fatal(err)
   629  		}
   630  		return f
   631  	}
   632  	runCommand := func(c *exec.Cmd, out chan<- string) {
   633  		bout, err := c.CombinedOutput()
   634  		if err != nil {
   635  			out <- "ERROR:" + err.Error()
   636  		} else {
   637  			out <- string(bout)
   638  		}
   639  	}
   640  
   641  	for i := 0; i < 10; i++ {
   642  		la := listen()
   643  		ca := helperCommand(t, "describefiles")
   644  		ca.ExtraFiles = []*os.File{listenerFile(la)}
   645  		lb := listen()
   646  		cb := helperCommand(t, "describefiles")
   647  		cb.ExtraFiles = []*os.File{listenerFile(lb)}
   648  		ares := make(chan string)
   649  		bres := make(chan string)
   650  		go runCommand(ca, ares)
   651  		go runCommand(cb, bres)
   652  		if got, want := <-ares, fmt.Sprintf("fd3: listener %s\n", la.Addr()); got != want {
   653  			t.Errorf("iteration %d, process A got:\n%s\nwant:\n%s\n", i, got, want)
   654  		}
   655  		if got, want := <-bres, fmt.Sprintf("fd3: listener %s\n", lb.Addr()); got != want {
   656  			t.Errorf("iteration %d, process B got:\n%s\nwant:\n%s\n", i, got, want)
   657  		}
   658  		la.Close()
   659  		lb.Close()
   660  		for _, f := range ca.ExtraFiles {
   661  			f.Close()
   662  		}
   663  		for _, f := range cb.ExtraFiles {
   664  			f.Close()
   665  		}
   666  
   667  	}
   668  }
   669  
   670  // TestHelperProcess isn't a real test. It's used as a helper process
   671  // for TestParameterRun.
   672  func TestHelperProcess(*testing.T) {
   673  	if os.Getenv("GO_WANT_HELPER_PROCESS") != "1" {
   674  		return
   675  	}
   676  	defer os.Exit(0)
   677  
   678  	// Determine which command to use to display open files.
   679  	ofcmd := "lsof"
   680  	switch runtime.GOOS {
   681  	case "dragonfly", "freebsd", "netbsd", "openbsd":
   682  		ofcmd = "fstat"
   683  	case "plan9":
   684  		ofcmd = "/bin/cat"
   685  	}
   686  
   687  	args := os.Args
   688  	for len(args) > 0 {
   689  		if args[0] == "--" {
   690  			args = args[1:]
   691  			break
   692  		}
   693  		args = args[1:]
   694  	}
   695  	if len(args) == 0 {
   696  		fmt.Fprintf(os.Stderr, "No command\n")
   697  		os.Exit(2)
   698  	}
   699  
   700  	cmd, args := args[0], args[1:]
   701  	switch cmd {
   702  	case "echo":
   703  		iargs := []interface{}{}
   704  		for _, s := range args {
   705  			iargs = append(iargs, s)
   706  		}
   707  		fmt.Println(iargs...)
   708  	case "echoenv":
   709  		for _, s := range args {
   710  			fmt.Println(os.Getenv(s))
   711  		}
   712  		os.Exit(0)
   713  	case "cat":
   714  		if len(args) == 0 {
   715  			io.Copy(os.Stdout, os.Stdin)
   716  			return
   717  		}
   718  		exit := 0
   719  		for _, fn := range args {
   720  			f, err := os.Open(fn)
   721  			if err != nil {
   722  				fmt.Fprintf(os.Stderr, "Error: %v\n", err)
   723  				exit = 2
   724  			} else {
   725  				defer f.Close()
   726  				io.Copy(os.Stdout, f)
   727  			}
   728  		}
   729  		os.Exit(exit)
   730  	case "pipetest":
   731  		bufr := bufio.NewReader(os.Stdin)
   732  		for {
   733  			line, _, err := bufr.ReadLine()
   734  			if err == io.EOF {
   735  				break
   736  			} else if err != nil {
   737  				os.Exit(1)
   738  			}
   739  			if bytes.HasPrefix(line, []byte("O:")) {
   740  				os.Stdout.Write(line)
   741  				os.Stdout.Write([]byte{'\n'})
   742  			} else if bytes.HasPrefix(line, []byte("E:")) {
   743  				os.Stderr.Write(line)
   744  				os.Stderr.Write([]byte{'\n'})
   745  			} else {
   746  				os.Exit(1)
   747  			}
   748  		}
   749  	case "stdinClose":
   750  		b, err := ioutil.ReadAll(os.Stdin)
   751  		if err != nil {
   752  			fmt.Fprintf(os.Stderr, "Error: %v\n", err)
   753  			os.Exit(1)
   754  		}
   755  		if s := string(b); s != stdinCloseTestString {
   756  			fmt.Fprintf(os.Stderr, "Error: Read %q, want %q", s, stdinCloseTestString)
   757  			os.Exit(1)
   758  		}
   759  		os.Exit(0)
   760  	case "read3": // read fd 3
   761  		fd3 := os.NewFile(3, "fd3")
   762  		bs, err := ioutil.ReadAll(fd3)
   763  		if err != nil {
   764  			fmt.Printf("ReadAll from fd 3: %v", err)
   765  			os.Exit(1)
   766  		}
   767  		switch runtime.GOOS {
   768  		case "dragonfly":
   769  			// TODO(jsing): Determine why DragonFly is leaking
   770  			// file descriptors...
   771  		case "darwin":
   772  			// TODO(bradfitz): broken? Sometimes.
   773  			// https://golang.org/issue/2603
   774  			// Skip this additional part of the test for now.
   775  		case "netbsd":
   776  			// TODO(jsing): This currently fails on NetBSD due to
   777  			// the cloned file descriptors that result from opening
   778  			// /dev/urandom.
   779  			// https://golang.org/issue/3955
   780  		case "solaris":
   781  			// TODO(aram): This fails on Solaris because libc opens
   782  			// its own files, as it sees fit. Darwin does the same,
   783  			// see: https://golang.org/issue/2603
   784  		default:
   785  			// Now verify that there are no other open fds.
   786  			var files []*os.File
   787  			for wantfd := basefds() + 1; wantfd <= 100; wantfd++ {
   788  				if wantfd == poll.PollDescriptor() {
   789  					continue
   790  				}
   791  				f, err := os.Open(os.Args[0])
   792  				if err != nil {
   793  					fmt.Printf("error opening file with expected fd %d: %v", wantfd, err)
   794  					os.Exit(1)
   795  				}
   796  				if got := f.Fd(); got != wantfd {
   797  					fmt.Printf("leaked parent file. fd = %d; want %d\n", got, wantfd)
   798  					var args []string
   799  					switch runtime.GOOS {
   800  					case "plan9":
   801  						args = []string{fmt.Sprintf("/proc/%d/fd", os.Getpid())}
   802  					default:
   803  						args = []string{"-p", fmt.Sprint(os.Getpid())}
   804  					}
   805  					out, _ := exec.Command(ofcmd, args...).CombinedOutput()
   806  					fmt.Print(string(out))
   807  					os.Exit(1)
   808  				}
   809  				files = append(files, f)
   810  			}
   811  			for _, f := range files {
   812  				f.Close()
   813  			}
   814  		}
   815  		// Referring to fd3 here ensures that it is not
   816  		// garbage collected, and therefore closed, while
   817  		// executing the wantfd loop above. It doesn't matter
   818  		// what we do with fd3 as long as we refer to it;
   819  		// closing it is the easy choice.
   820  		fd3.Close()
   821  		os.Stdout.Write(bs)
   822  	case "exit":
   823  		n, _ := strconv.Atoi(args[0])
   824  		os.Exit(n)
   825  	case "describefiles":
   826  		f := os.NewFile(3, fmt.Sprintf("fd3"))
   827  		ln, err := net.FileListener(f)
   828  		if err == nil {
   829  			fmt.Printf("fd3: listener %s\n", ln.Addr())
   830  			ln.Close()
   831  		}
   832  		os.Exit(0)
   833  	case "extraFilesAndPipes":
   834  		n, _ := strconv.Atoi(args[0])
   835  		pipes := make([]*os.File, n)
   836  		for i := 0; i < n; i++ {
   837  			pipes[i] = os.NewFile(uintptr(3+i), strconv.Itoa(i))
   838  		}
   839  		response := ""
   840  		for i, r := range pipes {
   841  			ch := make(chan string, 1)
   842  			go func(c chan string) {
   843  				buf := make([]byte, 10)
   844  				n, err := r.Read(buf)
   845  				if err != nil {
   846  					fmt.Fprintf(os.Stderr, "Child: read error: %v on pipe %d\n", err, i)
   847  					os.Exit(1)
   848  				}
   849  				c <- string(buf[:n])
   850  				close(c)
   851  			}(ch)
   852  			select {
   853  			case m := <-ch:
   854  				response = response + m
   855  			case <-time.After(5 * time.Second):
   856  				fmt.Fprintf(os.Stderr, "Child: Timeout reading from pipe: %d\n", i)
   857  				os.Exit(1)
   858  			}
   859  		}
   860  		fmt.Fprintf(os.Stderr, "child: %s", response)
   861  		os.Exit(0)
   862  	case "exec":
   863  		cmd := exec.Command(args[1])
   864  		cmd.Dir = args[0]
   865  		output, err := cmd.CombinedOutput()
   866  		if err != nil {
   867  			fmt.Fprintf(os.Stderr, "Child: %s %s", err, string(output))
   868  			os.Exit(1)
   869  		}
   870  		fmt.Printf("%s", string(output))
   871  		os.Exit(0)
   872  	case "lookpath":
   873  		p, err := exec.LookPath(args[0])
   874  		if err != nil {
   875  			fmt.Fprintf(os.Stderr, "LookPath failed: %v\n", err)
   876  			os.Exit(1)
   877  		}
   878  		fmt.Print(p)
   879  		os.Exit(0)
   880  	case "stderrfail":
   881  		fmt.Fprintf(os.Stderr, "some stderr text\n")
   882  		os.Exit(1)
   883  	case "sleep":
   884  		time.Sleep(3 * time.Second)
   885  		os.Exit(0)
   886  	default:
   887  		fmt.Fprintf(os.Stderr, "Unknown command %q\n", cmd)
   888  		os.Exit(2)
   889  	}
   890  }
   891  
   892  type delayedInfiniteReader struct{}
   893  
   894  func (delayedInfiniteReader) Read(b []byte) (int, error) {
   895  	time.Sleep(100 * time.Millisecond)
   896  	for i := range b {
   897  		b[i] = 'x'
   898  	}
   899  	return len(b), nil
   900  }
   901  
   902  // Issue 9173: ignore stdin pipe writes if the program completes successfully.
   903  func TestIgnorePipeErrorOnSuccess(t *testing.T) {
   904  	testenv.MustHaveExec(t)
   905  
   906  	// We really only care about testing this on Unixy and Windowsy things.
   907  	if runtime.GOOS == "plan9" {
   908  		t.Skipf("skipping test on %q", runtime.GOOS)
   909  	}
   910  
   911  	testWith := func(r io.Reader) func(*testing.T) {
   912  		return func(t *testing.T) {
   913  			cmd := helperCommand(t, "echo", "foo")
   914  			var out bytes.Buffer
   915  			cmd.Stdin = r
   916  			cmd.Stdout = &out
   917  			if err := cmd.Run(); err != nil {
   918  				t.Fatal(err)
   919  			}
   920  			if got, want := out.String(), "foo\n"; got != want {
   921  				t.Errorf("output = %q; want %q", got, want)
   922  			}
   923  		}
   924  	}
   925  	t.Run("10MB", testWith(strings.NewReader(strings.Repeat("x", 10<<20))))
   926  	t.Run("Infinite", testWith(delayedInfiniteReader{}))
   927  }
   928  
   929  type badWriter struct{}
   930  
   931  func (w *badWriter) Write(data []byte) (int, error) {
   932  	return 0, io.ErrUnexpectedEOF
   933  }
   934  
   935  func TestClosePipeOnCopyError(t *testing.T) {
   936  	testenv.MustHaveExec(t)
   937  
   938  	if runtime.GOOS == "windows" || runtime.GOOS == "plan9" {
   939  		t.Skipf("skipping test on %s - no yes command", runtime.GOOS)
   940  	}
   941  	cmd := exec.Command("yes")
   942  	cmd.Stdout = new(badWriter)
   943  	c := make(chan int, 1)
   944  	go func() {
   945  		err := cmd.Run()
   946  		if err == nil {
   947  			t.Errorf("yes completed successfully")
   948  		}
   949  		c <- 1
   950  	}()
   951  	select {
   952  	case <-c:
   953  		// ok
   954  	case <-time.After(5 * time.Second):
   955  		t.Fatalf("yes got stuck writing to bad writer")
   956  	}
   957  }
   958  
   959  func TestOutputStderrCapture(t *testing.T) {
   960  	testenv.MustHaveExec(t)
   961  
   962  	cmd := helperCommand(t, "stderrfail")
   963  	_, err := cmd.Output()
   964  	ee, ok := err.(*exec.ExitError)
   965  	if !ok {
   966  		t.Fatalf("Output error type = %T; want ExitError", err)
   967  	}
   968  	got := string(ee.Stderr)
   969  	want := "some stderr text\n"
   970  	if got != want {
   971  		t.Errorf("ExitError.Stderr = %q; want %q", got, want)
   972  	}
   973  }
   974  
   975  func TestContext(t *testing.T) {
   976  	ctx, cancel := context.WithCancel(context.Background())
   977  	c := helperCommandContext(t, ctx, "pipetest")
   978  	stdin, err := c.StdinPipe()
   979  	if err != nil {
   980  		t.Fatal(err)
   981  	}
   982  	stdout, err := c.StdoutPipe()
   983  	if err != nil {
   984  		t.Fatal(err)
   985  	}
   986  	if err := c.Start(); err != nil {
   987  		t.Fatal(err)
   988  	}
   989  
   990  	if _, err := stdin.Write([]byte("O:hi\n")); err != nil {
   991  		t.Fatal(err)
   992  	}
   993  	buf := make([]byte, 5)
   994  	n, err := io.ReadFull(stdout, buf)
   995  	if n != len(buf) || err != nil || string(buf) != "O:hi\n" {
   996  		t.Fatalf("ReadFull = %d, %v, %q", n, err, buf[:n])
   997  	}
   998  	waitErr := make(chan error, 1)
   999  	go func() {
  1000  		waitErr <- c.Wait()
  1001  	}()
  1002  	cancel()
  1003  	select {
  1004  	case err := <-waitErr:
  1005  		if err == nil {
  1006  			t.Fatal("expected Wait failure")
  1007  		}
  1008  	case <-time.After(3 * time.Second):
  1009  		t.Fatal("timeout waiting for child process death")
  1010  	}
  1011  }
  1012  
  1013  func TestContextCancel(t *testing.T) {
  1014  	ctx, cancel := context.WithCancel(context.Background())
  1015  	defer cancel()
  1016  	c := helperCommandContext(t, ctx, "cat")
  1017  
  1018  	r, w, err := os.Pipe()
  1019  	if err != nil {
  1020  		t.Fatal(err)
  1021  	}
  1022  	c.Stdin = r
  1023  
  1024  	stdout, err := c.StdoutPipe()
  1025  	if err != nil {
  1026  		t.Fatal(err)
  1027  	}
  1028  	readDone := make(chan struct{})
  1029  	go func() {
  1030  		defer close(readDone)
  1031  		var a [1024]byte
  1032  		for {
  1033  			n, err := stdout.Read(a[:])
  1034  			if err != nil {
  1035  				if err != io.EOF {
  1036  					t.Errorf("unexpected read error: %v", err)
  1037  				}
  1038  				return
  1039  			}
  1040  			t.Logf("%s", a[:n])
  1041  		}
  1042  	}()
  1043  
  1044  	if err := c.Start(); err != nil {
  1045  		t.Fatal(err)
  1046  	}
  1047  
  1048  	if err := r.Close(); err != nil {
  1049  		t.Fatal(err)
  1050  	}
  1051  
  1052  	if _, err := io.WriteString(w, "echo"); err != nil {
  1053  		t.Fatal(err)
  1054  	}
  1055  
  1056  	cancel()
  1057  
  1058  	// Calling cancel should have killed the process, so writes
  1059  	// should now fail.  Give the process a little while to die.
  1060  	start := time.Now()
  1061  	for {
  1062  		if _, err := io.WriteString(w, "echo"); err != nil {
  1063  			break
  1064  		}
  1065  		if time.Since(start) > time.Second {
  1066  			t.Fatal("canceling context did not stop program")
  1067  		}
  1068  		time.Sleep(time.Millisecond)
  1069  	}
  1070  
  1071  	if err := w.Close(); err != nil {
  1072  		t.Errorf("error closing write end of pipe: %v", err)
  1073  	}
  1074  	<-readDone
  1075  
  1076  	if err := c.Wait(); err == nil {
  1077  		t.Error("program unexpectedly exited successfully")
  1078  	} else {
  1079  		t.Logf("exit status: %v", err)
  1080  	}
  1081  }
  1082  
  1083  // test that environment variables are de-duped.
  1084  func TestDedupEnvEcho(t *testing.T) {
  1085  	testenv.MustHaveExec(t)
  1086  
  1087  	cmd := helperCommand(t, "echoenv", "FOO")
  1088  	cmd.Env = append(cmd.Env, "FOO=bad", "FOO=good")
  1089  	out, err := cmd.CombinedOutput()
  1090  	if err != nil {
  1091  		t.Fatal(err)
  1092  	}
  1093  	if got, want := strings.TrimSpace(string(out)), "good"; got != want {
  1094  		t.Errorf("output = %q; want %q", got, want)
  1095  	}
  1096  }
  1097  

View as plain text