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