github.com/eun/go@v0.0.0-20170811110501-92cfd07a6cfd/src/os/exec/exec_test.go (about)

     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 TestNoExistBinary(t *testing.T) {
   146  	// Can't run a non-existent binary
   147  	err := exec.Command("/no-exist-binary").Run()
   148  	if err == nil {
   149  		t.Error("expected error from /no-exist-binary")
   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-binary")
   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
   405  func basefds() uintptr {
   406  	return os.Stderr.Fd() + 1
   407  }
   408  
   409  func closeUnexpectedFds(t *testing.T, m string) {
   410  	for fd := basefds(); fd <= 101; fd++ {
   411  		if fd == poll.PollDescriptor() {
   412  			continue
   413  		}
   414  		err := os.NewFile(fd, "").Close()
   415  		if err == nil {
   416  			t.Logf("%s: Something already leaked - closed fd %d", m, fd)
   417  		}
   418  	}
   419  }
   420  
   421  func TestExtraFilesFDShuffle(t *testing.T) {
   422  	t.Skip("flaky test; see https://golang.org/issue/5780")
   423  	switch runtime.GOOS {
   424  	case "darwin":
   425  		// TODO(cnicolaou): https://golang.org/issue/2603
   426  		// leads to leaked file descriptors in this test when it's
   427  		// run from a builder.
   428  		closeUnexpectedFds(t, "TestExtraFilesFDShuffle")
   429  	case "netbsd":
   430  		// https://golang.org/issue/3955
   431  		closeUnexpectedFds(t, "TestExtraFilesFDShuffle")
   432  	case "windows":
   433  		t.Skip("no operating system support; skipping")
   434  	}
   435  
   436  	// syscall.StartProcess maps all the FDs passed to it in
   437  	// ProcAttr.Files (the concatenation of stdin,stdout,stderr and
   438  	// ExtraFiles) into consecutive FDs in the child, that is:
   439  	// Files{11, 12, 6, 7, 9, 3} should result in the file
   440  	// represented by FD 11 in the parent being made available as 0
   441  	// in the child, 12 as 1, etc.
   442  	//
   443  	// We want to test that FDs in the child do not get overwritten
   444  	// by one another as this shuffle occurs. The original implementation
   445  	// was buggy in that in some data dependent cases it would overwrite
   446  	// stderr in the child with one of the ExtraFile members.
   447  	// Testing for this case is difficult because it relies on using
   448  	// the same FD values as that case. In particular, an FD of 3
   449  	// must be at an index of 4 or higher in ProcAttr.Files and
   450  	// the FD of the write end of the Stderr pipe (as obtained by
   451  	// StderrPipe()) must be the same as the size of ProcAttr.Files;
   452  	// therefore we test that the read end of this pipe (which is what
   453  	// is returned to the parent by StderrPipe() being one less than
   454  	// the size of ProcAttr.Files, i.e. 3+len(cmd.ExtraFiles).
   455  	//
   456  	// Moving this test case around within the overall tests may
   457  	// affect the FDs obtained and hence the checks to catch these cases.
   458  	npipes := 2
   459  	c := helperCommand(t, "extraFilesAndPipes", strconv.Itoa(npipes+1))
   460  	rd, wr, _ := os.Pipe()
   461  	defer rd.Close()
   462  	if rd.Fd() != 3 {
   463  		t.Errorf("bad test value for test pipe: fd %d", rd.Fd())
   464  	}
   465  	stderr, _ := c.StderrPipe()
   466  	wr.WriteString("_LAST")
   467  	wr.Close()
   468  
   469  	pipes := make([]struct {
   470  		r, w *os.File
   471  	}, npipes)
   472  	data := []string{"a", "b"}
   473  
   474  	for i := 0; i < npipes; i++ {
   475  		r, w, err := os.Pipe()
   476  		if err != nil {
   477  			t.Fatalf("unexpected error creating pipe: %s", err)
   478  		}
   479  		pipes[i].r = r
   480  		pipes[i].w = w
   481  		w.WriteString(data[i])
   482  		c.ExtraFiles = append(c.ExtraFiles, pipes[i].r)
   483  		defer func() {
   484  			r.Close()
   485  			w.Close()
   486  		}()
   487  	}
   488  	// Put fd 3 at the end.
   489  	c.ExtraFiles = append(c.ExtraFiles, rd)
   490  
   491  	stderrFd := int(stderr.(*os.File).Fd())
   492  	if stderrFd != ((len(c.ExtraFiles) + 3) - 1) {
   493  		t.Errorf("bad test value for stderr pipe")
   494  	}
   495  
   496  	expected := "child: " + strings.Join(data, "") + "_LAST"
   497  
   498  	err := c.Start()
   499  	if err != nil {
   500  		t.Fatalf("Run: %v", err)
   501  	}
   502  	ch := make(chan string, 1)
   503  	go func(ch chan string) {
   504  		buf := make([]byte, 512)
   505  		n, err := stderr.Read(buf)
   506  		if err != nil {
   507  			t.Errorf("Read: %s", err)
   508  			ch <- err.Error()
   509  		} else {
   510  			ch <- string(buf[:n])
   511  		}
   512  		close(ch)
   513  	}(ch)
   514  	select {
   515  	case m := <-ch:
   516  		if m != expected {
   517  			t.Errorf("Read: '%s' not '%s'", m, expected)
   518  		}
   519  	case <-time.After(5 * time.Second):
   520  		t.Errorf("Read timedout")
   521  	}
   522  	c.Wait()
   523  }
   524  
   525  func TestExtraFiles(t *testing.T) {
   526  	testenv.MustHaveExec(t)
   527  
   528  	if runtime.GOOS == "windows" {
   529  		t.Skipf("skipping test on %q", runtime.GOOS)
   530  	}
   531  
   532  	// Ensure that file descriptors have not already been leaked into
   533  	// our environment.
   534  	if !testedAlreadyLeaked {
   535  		testedAlreadyLeaked = true
   536  		closeUnexpectedFds(t, "TestExtraFiles")
   537  	}
   538  
   539  	// Force network usage, to verify the epoll (or whatever) fd
   540  	// doesn't leak to the child,
   541  	ln, err := net.Listen("tcp", "127.0.0.1:0")
   542  	if err != nil {
   543  		t.Fatal(err)
   544  	}
   545  	defer ln.Close()
   546  
   547  	// Make sure duplicated fds don't leak to the child.
   548  	f, err := ln.(*net.TCPListener).File()
   549  	if err != nil {
   550  		t.Fatal(err)
   551  	}
   552  	defer f.Close()
   553  	ln2, err := net.FileListener(f)
   554  	if err != nil {
   555  		t.Fatal(err)
   556  	}
   557  	defer ln2.Close()
   558  
   559  	// Force TLS root certs to be loaded (which might involve
   560  	// cgo), to make sure none of that potential C code leaks fds.
   561  	ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
   562  	// quiet expected TLS handshake error "remote error: bad certificate"
   563  	ts.Config.ErrorLog = log.New(ioutil.Discard, "", 0)
   564  	ts.StartTLS()
   565  	defer ts.Close()
   566  	_, err = http.Get(ts.URL)
   567  	if err == nil {
   568  		t.Errorf("success trying to fetch %s; want an error", ts.URL)
   569  	}
   570  
   571  	tf, err := ioutil.TempFile("", "")
   572  	if err != nil {
   573  		t.Fatalf("TempFile: %v", err)
   574  	}
   575  	defer os.Remove(tf.Name())
   576  	defer tf.Close()
   577  
   578  	const text = "Hello, fd 3!"
   579  	_, err = tf.Write([]byte(text))
   580  	if err != nil {
   581  		t.Fatalf("Write: %v", err)
   582  	}
   583  	_, err = tf.Seek(0, io.SeekStart)
   584  	if err != nil {
   585  		t.Fatalf("Seek: %v", err)
   586  	}
   587  
   588  	c := helperCommand(t, "read3")
   589  	var stdout, stderr bytes.Buffer
   590  	c.Stdout = &stdout
   591  	c.Stderr = &stderr
   592  	c.ExtraFiles = []*os.File{tf}
   593  	err = c.Run()
   594  	if err != nil {
   595  		t.Fatalf("Run: %v; stdout %q, stderr %q", err, stdout.Bytes(), stderr.Bytes())
   596  	}
   597  	if stdout.String() != text {
   598  		t.Errorf("got stdout %q, stderr %q; want %q on stdout", stdout.String(), stderr.String(), text)
   599  	}
   600  }
   601  
   602  func TestExtraFilesRace(t *testing.T) {
   603  	if runtime.GOOS == "windows" {
   604  		t.Skip("no operating system support; skipping")
   605  	}
   606  	listen := func() net.Listener {
   607  		ln, err := net.Listen("tcp", "127.0.0.1:0")
   608  		if err != nil {
   609  			t.Fatal(err)
   610  		}
   611  		return ln
   612  	}
   613  	listenerFile := func(ln net.Listener) *os.File {
   614  		f, err := ln.(*net.TCPListener).File()
   615  		if err != nil {
   616  			t.Fatal(err)
   617  		}
   618  		return f
   619  	}
   620  	runCommand := func(c *exec.Cmd, out chan<- string) {
   621  		bout, err := c.CombinedOutput()
   622  		if err != nil {
   623  			out <- "ERROR:" + err.Error()
   624  		} else {
   625  			out <- string(bout)
   626  		}
   627  	}
   628  
   629  	for i := 0; i < 10; i++ {
   630  		la := listen()
   631  		ca := helperCommand(t, "describefiles")
   632  		ca.ExtraFiles = []*os.File{listenerFile(la)}
   633  		lb := listen()
   634  		cb := helperCommand(t, "describefiles")
   635  		cb.ExtraFiles = []*os.File{listenerFile(lb)}
   636  		ares := make(chan string)
   637  		bres := make(chan string)
   638  		go runCommand(ca, ares)
   639  		go runCommand(cb, bres)
   640  		if got, want := <-ares, fmt.Sprintf("fd3: listener %s\n", la.Addr()); got != want {
   641  			t.Errorf("iteration %d, process A got:\n%s\nwant:\n%s\n", i, got, want)
   642  		}
   643  		if got, want := <-bres, fmt.Sprintf("fd3: listener %s\n", lb.Addr()); got != want {
   644  			t.Errorf("iteration %d, process B got:\n%s\nwant:\n%s\n", i, got, want)
   645  		}
   646  		la.Close()
   647  		lb.Close()
   648  		for _, f := range ca.ExtraFiles {
   649  			f.Close()
   650  		}
   651  		for _, f := range cb.ExtraFiles {
   652  			f.Close()
   653  		}
   654  
   655  	}
   656  }
   657  
   658  // TestHelperProcess isn't a real test. It's used as a helper process
   659  // for TestParameterRun.
   660  func TestHelperProcess(*testing.T) {
   661  	if os.Getenv("GO_WANT_HELPER_PROCESS") != "1" {
   662  		return
   663  	}
   664  	defer os.Exit(0)
   665  
   666  	// Determine which command to use to display open files.
   667  	ofcmd := "lsof"
   668  	switch runtime.GOOS {
   669  	case "dragonfly", "freebsd", "netbsd", "openbsd":
   670  		ofcmd = "fstat"
   671  	case "plan9":
   672  		ofcmd = "/bin/cat"
   673  	}
   674  
   675  	args := os.Args
   676  	for len(args) > 0 {
   677  		if args[0] == "--" {
   678  			args = args[1:]
   679  			break
   680  		}
   681  		args = args[1:]
   682  	}
   683  	if len(args) == 0 {
   684  		fmt.Fprintf(os.Stderr, "No command\n")
   685  		os.Exit(2)
   686  	}
   687  
   688  	cmd, args := args[0], args[1:]
   689  	switch cmd {
   690  	case "echo":
   691  		iargs := []interface{}{}
   692  		for _, s := range args {
   693  			iargs = append(iargs, s)
   694  		}
   695  		fmt.Println(iargs...)
   696  	case "echoenv":
   697  		for _, s := range args {
   698  			fmt.Println(os.Getenv(s))
   699  		}
   700  		os.Exit(0)
   701  	case "cat":
   702  		if len(args) == 0 {
   703  			io.Copy(os.Stdout, os.Stdin)
   704  			return
   705  		}
   706  		exit := 0
   707  		for _, fn := range args {
   708  			f, err := os.Open(fn)
   709  			if err != nil {
   710  				fmt.Fprintf(os.Stderr, "Error: %v\n", err)
   711  				exit = 2
   712  			} else {
   713  				defer f.Close()
   714  				io.Copy(os.Stdout, f)
   715  			}
   716  		}
   717  		os.Exit(exit)
   718  	case "pipetest":
   719  		bufr := bufio.NewReader(os.Stdin)
   720  		for {
   721  			line, _, err := bufr.ReadLine()
   722  			if err == io.EOF {
   723  				break
   724  			} else if err != nil {
   725  				os.Exit(1)
   726  			}
   727  			if bytes.HasPrefix(line, []byte("O:")) {
   728  				os.Stdout.Write(line)
   729  				os.Stdout.Write([]byte{'\n'})
   730  			} else if bytes.HasPrefix(line, []byte("E:")) {
   731  				os.Stderr.Write(line)
   732  				os.Stderr.Write([]byte{'\n'})
   733  			} else {
   734  				os.Exit(1)
   735  			}
   736  		}
   737  	case "stdinClose":
   738  		b, err := ioutil.ReadAll(os.Stdin)
   739  		if err != nil {
   740  			fmt.Fprintf(os.Stderr, "Error: %v\n", err)
   741  			os.Exit(1)
   742  		}
   743  		if s := string(b); s != stdinCloseTestString {
   744  			fmt.Fprintf(os.Stderr, "Error: Read %q, want %q", s, stdinCloseTestString)
   745  			os.Exit(1)
   746  		}
   747  		os.Exit(0)
   748  	case "read3": // read fd 3
   749  		fd3 := os.NewFile(3, "fd3")
   750  		bs, err := ioutil.ReadAll(fd3)
   751  		if err != nil {
   752  			fmt.Printf("ReadAll from fd 3: %v", err)
   753  			os.Exit(1)
   754  		}
   755  		switch runtime.GOOS {
   756  		case "dragonfly":
   757  			// TODO(jsing): Determine why DragonFly is leaking
   758  			// file descriptors...
   759  		case "darwin":
   760  			// TODO(bradfitz): broken? Sometimes.
   761  			// https://golang.org/issue/2603
   762  			// Skip this additional part of the test for now.
   763  		case "netbsd":
   764  			// TODO(jsing): This currently fails on NetBSD due to
   765  			// the cloned file descriptors that result from opening
   766  			// /dev/urandom.
   767  			// https://golang.org/issue/3955
   768  		case "solaris":
   769  			// TODO(aram): This fails on Solaris because libc opens
   770  			// its own files, as it sees fit. Darwin does the same,
   771  			// see: https://golang.org/issue/2603
   772  		default:
   773  			// Now verify that there are no other open fds.
   774  			var files []*os.File
   775  			for wantfd := basefds() + 1; wantfd <= 100; wantfd++ {
   776  				if wantfd == poll.PollDescriptor() {
   777  					continue
   778  				}
   779  				f, err := os.Open(os.Args[0])
   780  				if err != nil {
   781  					fmt.Printf("error opening file with expected fd %d: %v", wantfd, err)
   782  					os.Exit(1)
   783  				}
   784  				if got := f.Fd(); got != wantfd {
   785  					fmt.Printf("leaked parent file. fd = %d; want %d\n", got, wantfd)
   786  					var args []string
   787  					switch runtime.GOOS {
   788  					case "plan9":
   789  						args = []string{fmt.Sprintf("/proc/%d/fd", os.Getpid())}
   790  					default:
   791  						args = []string{"-p", fmt.Sprint(os.Getpid())}
   792  					}
   793  					out, _ := exec.Command(ofcmd, args...).CombinedOutput()
   794  					fmt.Print(string(out))
   795  					os.Exit(1)
   796  				}
   797  				files = append(files, f)
   798  			}
   799  			for _, f := range files {
   800  				f.Close()
   801  			}
   802  		}
   803  		// Referring to fd3 here ensures that it is not
   804  		// garbage collected, and therefore closed, while
   805  		// executing the wantfd loop above. It doesn't matter
   806  		// what we do with fd3 as long as we refer to it;
   807  		// closing it is the easy choice.
   808  		fd3.Close()
   809  		os.Stdout.Write(bs)
   810  	case "exit":
   811  		n, _ := strconv.Atoi(args[0])
   812  		os.Exit(n)
   813  	case "describefiles":
   814  		f := os.NewFile(3, fmt.Sprintf("fd3"))
   815  		ln, err := net.FileListener(f)
   816  		if err == nil {
   817  			fmt.Printf("fd3: listener %s\n", ln.Addr())
   818  			ln.Close()
   819  		}
   820  		os.Exit(0)
   821  	case "extraFilesAndPipes":
   822  		n, _ := strconv.Atoi(args[0])
   823  		pipes := make([]*os.File, n)
   824  		for i := 0; i < n; i++ {
   825  			pipes[i] = os.NewFile(uintptr(3+i), strconv.Itoa(i))
   826  		}
   827  		response := ""
   828  		for i, r := range pipes {
   829  			ch := make(chan string, 1)
   830  			go func(c chan string) {
   831  				buf := make([]byte, 10)
   832  				n, err := r.Read(buf)
   833  				if err != nil {
   834  					fmt.Fprintf(os.Stderr, "Child: read error: %v on pipe %d\n", err, i)
   835  					os.Exit(1)
   836  				}
   837  				c <- string(buf[:n])
   838  				close(c)
   839  			}(ch)
   840  			select {
   841  			case m := <-ch:
   842  				response = response + m
   843  			case <-time.After(5 * time.Second):
   844  				fmt.Fprintf(os.Stderr, "Child: Timeout reading from pipe: %d\n", i)
   845  				os.Exit(1)
   846  			}
   847  		}
   848  		fmt.Fprintf(os.Stderr, "child: %s", response)
   849  		os.Exit(0)
   850  	case "exec":
   851  		cmd := exec.Command(args[1])
   852  		cmd.Dir = args[0]
   853  		output, err := cmd.CombinedOutput()
   854  		if err != nil {
   855  			fmt.Fprintf(os.Stderr, "Child: %s %s", err, string(output))
   856  			os.Exit(1)
   857  		}
   858  		fmt.Printf("%s", string(output))
   859  		os.Exit(0)
   860  	case "lookpath":
   861  		p, err := exec.LookPath(args[0])
   862  		if err != nil {
   863  			fmt.Fprintf(os.Stderr, "LookPath failed: %v\n", err)
   864  			os.Exit(1)
   865  		}
   866  		fmt.Print(p)
   867  		os.Exit(0)
   868  	case "stderrfail":
   869  		fmt.Fprintf(os.Stderr, "some stderr text\n")
   870  		os.Exit(1)
   871  	case "sleep":
   872  		time.Sleep(3 * time.Second)
   873  		os.Exit(0)
   874  	default:
   875  		fmt.Fprintf(os.Stderr, "Unknown command %q\n", cmd)
   876  		os.Exit(2)
   877  	}
   878  }
   879  
   880  type delayedInfiniteReader struct{}
   881  
   882  func (delayedInfiniteReader) Read(b []byte) (int, error) {
   883  	time.Sleep(100 * time.Millisecond)
   884  	for i := range b {
   885  		b[i] = 'x'
   886  	}
   887  	return len(b), nil
   888  }
   889  
   890  // Issue 9173: ignore stdin pipe writes if the program completes successfully.
   891  func TestIgnorePipeErrorOnSuccess(t *testing.T) {
   892  	testenv.MustHaveExec(t)
   893  
   894  	// We really only care about testing this on Unixy and Windowsy things.
   895  	if runtime.GOOS == "plan9" {
   896  		t.Skipf("skipping test on %q", runtime.GOOS)
   897  	}
   898  
   899  	testWith := func(r io.Reader) func(*testing.T) {
   900  		return func(t *testing.T) {
   901  			cmd := helperCommand(t, "echo", "foo")
   902  			var out bytes.Buffer
   903  			cmd.Stdin = r
   904  			cmd.Stdout = &out
   905  			if err := cmd.Run(); err != nil {
   906  				t.Fatal(err)
   907  			}
   908  			if got, want := out.String(), "foo\n"; got != want {
   909  				t.Errorf("output = %q; want %q", got, want)
   910  			}
   911  		}
   912  	}
   913  	t.Run("10MB", testWith(strings.NewReader(strings.Repeat("x", 10<<20))))
   914  	t.Run("Infinite", testWith(delayedInfiniteReader{}))
   915  }
   916  
   917  type badWriter struct{}
   918  
   919  func (w *badWriter) Write(data []byte) (int, error) {
   920  	return 0, io.ErrUnexpectedEOF
   921  }
   922  
   923  func TestClosePipeOnCopyError(t *testing.T) {
   924  	testenv.MustHaveExec(t)
   925  
   926  	if runtime.GOOS == "windows" || runtime.GOOS == "plan9" {
   927  		t.Skipf("skipping test on %s - no yes command", runtime.GOOS)
   928  	}
   929  	cmd := exec.Command("yes")
   930  	cmd.Stdout = new(badWriter)
   931  	c := make(chan int, 1)
   932  	go func() {
   933  		err := cmd.Run()
   934  		if err == nil {
   935  			t.Errorf("yes completed successfully")
   936  		}
   937  		c <- 1
   938  	}()
   939  	select {
   940  	case <-c:
   941  		// ok
   942  	case <-time.After(5 * time.Second):
   943  		t.Fatalf("yes got stuck writing to bad writer")
   944  	}
   945  }
   946  
   947  func TestOutputStderrCapture(t *testing.T) {
   948  	testenv.MustHaveExec(t)
   949  
   950  	cmd := helperCommand(t, "stderrfail")
   951  	_, err := cmd.Output()
   952  	ee, ok := err.(*exec.ExitError)
   953  	if !ok {
   954  		t.Fatalf("Output error type = %T; want ExitError", err)
   955  	}
   956  	got := string(ee.Stderr)
   957  	want := "some stderr text\n"
   958  	if got != want {
   959  		t.Errorf("ExitError.Stderr = %q; want %q", got, want)
   960  	}
   961  }
   962  
   963  func TestContext(t *testing.T) {
   964  	ctx, cancel := context.WithCancel(context.Background())
   965  	c := helperCommandContext(t, ctx, "pipetest")
   966  	stdin, err := c.StdinPipe()
   967  	if err != nil {
   968  		t.Fatal(err)
   969  	}
   970  	stdout, err := c.StdoutPipe()
   971  	if err != nil {
   972  		t.Fatal(err)
   973  	}
   974  	if err := c.Start(); err != nil {
   975  		t.Fatal(err)
   976  	}
   977  
   978  	if _, err := stdin.Write([]byte("O:hi\n")); err != nil {
   979  		t.Fatal(err)
   980  	}
   981  	buf := make([]byte, 5)
   982  	n, err := io.ReadFull(stdout, buf)
   983  	if n != len(buf) || err != nil || string(buf) != "O:hi\n" {
   984  		t.Fatalf("ReadFull = %d, %v, %q", n, err, buf[:n])
   985  	}
   986  	waitErr := make(chan error, 1)
   987  	go func() {
   988  		waitErr <- c.Wait()
   989  	}()
   990  	cancel()
   991  	select {
   992  	case err := <-waitErr:
   993  		if err == nil {
   994  			t.Fatal("expected Wait failure")
   995  		}
   996  	case <-time.After(3 * time.Second):
   997  		t.Fatal("timeout waiting for child process death")
   998  	}
   999  }
  1000  
  1001  func TestContextCancel(t *testing.T) {
  1002  	ctx, cancel := context.WithCancel(context.Background())
  1003  	defer cancel()
  1004  	c := helperCommandContext(t, ctx, "cat")
  1005  
  1006  	r, w, err := os.Pipe()
  1007  	if err != nil {
  1008  		t.Fatal(err)
  1009  	}
  1010  	c.Stdin = r
  1011  
  1012  	stdout, err := c.StdoutPipe()
  1013  	if err != nil {
  1014  		t.Fatal(err)
  1015  	}
  1016  	readDone := make(chan struct{})
  1017  	go func() {
  1018  		defer close(readDone)
  1019  		var a [1024]byte
  1020  		for {
  1021  			n, err := stdout.Read(a[:])
  1022  			if err != nil {
  1023  				if err != io.EOF {
  1024  					t.Errorf("unexpected read error: %v", err)
  1025  				}
  1026  				return
  1027  			}
  1028  			t.Logf("%s", a[:n])
  1029  		}
  1030  	}()
  1031  
  1032  	if err := c.Start(); err != nil {
  1033  		t.Fatal(err)
  1034  	}
  1035  
  1036  	if err := r.Close(); err != nil {
  1037  		t.Fatal(err)
  1038  	}
  1039  
  1040  	if _, err := io.WriteString(w, "echo"); err != nil {
  1041  		t.Fatal(err)
  1042  	}
  1043  
  1044  	cancel()
  1045  
  1046  	// Calling cancel should have killed the process, so writes
  1047  	// should now fail.  Give the process a little while to die.
  1048  	start := time.Now()
  1049  	for {
  1050  		if _, err := io.WriteString(w, "echo"); err != nil {
  1051  			break
  1052  		}
  1053  		if time.Since(start) > time.Second {
  1054  			t.Fatal("canceling context did not stop program")
  1055  		}
  1056  		time.Sleep(time.Millisecond)
  1057  	}
  1058  
  1059  	if err := w.Close(); err != nil {
  1060  		t.Errorf("error closing write end of pipe: %v", err)
  1061  	}
  1062  	<-readDone
  1063  
  1064  	if err := c.Wait(); err == nil {
  1065  		t.Error("program unexpectedly exited successfully")
  1066  	} else {
  1067  		t.Logf("exit status: %v", err)
  1068  	}
  1069  }
  1070  
  1071  // test that environment variables are de-duped.
  1072  func TestDedupEnvEcho(t *testing.T) {
  1073  	testenv.MustHaveExec(t)
  1074  
  1075  	cmd := helperCommand(t, "echoenv", "FOO")
  1076  	cmd.Env = append(cmd.Env, "FOO=bad", "FOO=good")
  1077  	out, err := cmd.CombinedOutput()
  1078  	if err != nil {
  1079  		t.Fatal(err)
  1080  	}
  1081  	if got, want := strings.TrimSpace(string(out)), "good"; got != want {
  1082  		t.Errorf("output = %q; want %q", got, want)
  1083  	}
  1084  }