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