exec_test.go 25.6 KB
Newer Older
1 2 3 4
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

5 6 7 8
// Use an external test to avoid os/exec -> net/http -> crypto/x509 -> os/exec
// circular dependency on non-cgo darwin.

package exec_test
9 10

import (
11 12
	"bufio"
	"bytes"
13
	"context"
14
	"fmt"
15
	"internal/testenv"
16
	"io"
17
	"io/ioutil"
18
	"log"
19 20 21
	"net"
	"net/http"
	"net/http/httptest"
22
	"os"
23
	"os/exec"
24
	"path/filepath"
25
	"runtime"
26 27
	"strconv"
	"strings"
28
	"testing"
29
	"time"
30 31
)

32
func helperCommandContext(t *testing.T, ctx context.Context, s ...string) (cmd *exec.Cmd) {
33 34
	testenv.MustHaveExec(t)

35
	cs := []string{"-test.run=TestHelperProcess", "--"}
36
	cs = append(cs, s...)
37 38 39 40 41
	if ctx != nil {
		cmd = exec.CommandContext(ctx, os.Args[0], cs...)
	} else {
		cmd = exec.Command(os.Args[0], cs...)
	}
42 43 44 45 46
	cmd.Env = []string{"GO_WANT_HELPER_PROCESS=1"}
	path := os.Getenv("LD_LIBRARY_PATH")
	if path != "" {
		cmd.Env = append(cmd.Env, "LD_LIBRARY_PATH="+path)
	}
47
	return cmd
48 49
}

50 51 52 53
func helperCommand(t *testing.T, s ...string) *exec.Cmd {
	return helperCommandContext(t, nil, s...)
}

54
func TestEcho(t *testing.T) {
55
	bs, err := helperCommand(t, "echo", "foo bar", "baz").Output()
56
	if err != nil {
57
		t.Errorf("echo: %v", err)
58
	}
59 60
	if g, e := string(bs), "foo bar baz\n"; g != e {
		t.Errorf("echo: want %q, got %q", e, g)
61 62 63
	}
}

64
func TestCommandRelativeName(t *testing.T) {
65 66
	testenv.MustHaveExec(t)

67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
	// Run our own binary as a relative path
	// (e.g. "_test/exec.test") our parent directory.
	base := filepath.Base(os.Args[0]) // "exec.test"
	dir := filepath.Dir(os.Args[0])   // "/tmp/go-buildNNNN/os/exec/_test"
	if dir == "." {
		t.Skip("skipping; running test at root somehow")
	}
	parentDir := filepath.Dir(dir) // "/tmp/go-buildNNNN/os/exec"
	dirBase := filepath.Base(dir)  // "_test"
	if dirBase == "." {
		t.Skipf("skipping; unexpected shallow dir of %q", dir)
	}

	cmd := exec.Command(filepath.Join(dirBase, base), "-test.run=TestHelperProcess", "--", "echo", "foo")
	cmd.Dir = parentDir
	cmd.Env = []string{"GO_WANT_HELPER_PROCESS=1"}

	out, err := cmd.Output()
	if err != nil {
		t.Errorf("echo: %v", err)
	}
	if g, e := string(out), "foo\n"; g != e {
		t.Errorf("echo: want %q, got %q", e, g)
	}
}

93 94 95
func TestCatStdin(t *testing.T) {
	// Cat, testing stdin and stdout.
	input := "Input string\nLine 2"
96
	p := helperCommand(t, "cat")
97 98
	p.Stdin = strings.NewReader(input)
	bs, err := p.Output()
99
	if err != nil {
100
		t.Errorf("cat: %v", err)
101
	}
102 103 104
	s := string(bs)
	if s != input {
		t.Errorf("cat: want %q, got %q", input, s)
105 106 107
	}
}

108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
func TestEchoFileRace(t *testing.T) {
	cmd := helperCommand(t, "echo")
	stdin, err := cmd.StdinPipe()
	if err != nil {
		t.Fatalf("StdinPipe: %v", err)
	}
	if err := cmd.Start(); err != nil {
		t.Fatalf("Start: %v", err)
	}
	wrote := make(chan bool)
	go func() {
		defer close(wrote)
		fmt.Fprint(stdin, "echo\n")
	}()
	if err := cmd.Wait(); err != nil {
		t.Fatalf("Wait: %v", err)
	}
	<-wrote
}

128 129
func TestCatGoodAndBadFile(t *testing.T) {
	// Testing combined output and error values.
130
	bs, err := helperCommand(t, "cat", "/bogus/file.foo", "exec_test.go").CombinedOutput()
131 132
	if _, ok := err.(*exec.ExitError); !ok {
		t.Errorf("expected *exec.ExitError from cat combined; got %T: %v", err, err)
133
	}
134 135 136 137
	s := string(bs)
	sp := strings.SplitN(s, "\n", 2)
	if len(sp) != 2 {
		t.Fatalf("expected two lines from cat; got %q", s)
138
	}
139 140 141
	errLine, body := sp[0], sp[1]
	if !strings.HasPrefix(errLine, "Error: open /bogus/file.foo") {
		t.Errorf("expected stderr to complain about file; got %q", errLine)
142
	}
143 144
	if !strings.Contains(body, "func TestHelperProcess(t *testing.T)") {
		t.Errorf("expected test code; got %q (len %d)", body, len(body))
145 146 147
	}
}

148 149
func TestNoExistBinary(t *testing.T) {
	// Can't run a non-existent binary
150
	err := exec.Command("/no-exist-binary").Run()
151 152
	if err == nil {
		t.Error("expected error from /no-exist-binary")
153
	}
154 155 156 157
}

func TestExitStatus(t *testing.T) {
	// Test that exit values are returned correctly
158
	cmd := helperCommand(t, "exit", "42")
159 160 161 162 163 164
	err := cmd.Run()
	want := "exit status 42"
	switch runtime.GOOS {
	case "plan9":
		want = fmt.Sprintf("exit status: '%s %d: 42'", filepath.Base(cmd.Path), cmd.ProcessState.Pid())
	}
165
	if werr, ok := err.(*exec.ExitError); ok {
166 167
		if s := werr.Error(); s != want {
			t.Errorf("from exit 42 got exit %q, want %q", s, want)
168 169
		}
	} else {
170
		t.Fatalf("expected *exec.ExitError from exit 42; got %T: %v", err, err)
171 172 173
	}
}

174
func TestPipes(t *testing.T) {
175
	check := func(what string, err error) {
176 177 178
		if err != nil {
			t.Fatalf("%s: %v", what, err)
		}
179
	}
180
	// Cat, testing stdin and stdout.
181
	c := helperCommand(t, "pipetest")
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
	stdin, err := c.StdinPipe()
	check("StdinPipe", err)
	stdout, err := c.StdoutPipe()
	check("StdoutPipe", err)
	stderr, err := c.StderrPipe()
	check("StderrPipe", err)

	outbr := bufio.NewReader(stdout)
	errbr := bufio.NewReader(stderr)
	line := func(what string, br *bufio.Reader) string {
		line, _, err := br.ReadLine()
		if err != nil {
			t.Fatalf("%s: %v", what, err)
		}
		return string(line)
197
	}
198 199 200 201 202 203 204 205

	err = c.Start()
	check("Start", err)

	_, err = stdin.Write([]byte("O:I am output\n"))
	check("first stdin Write", err)
	if g, e := line("first output line", outbr), "O:I am output"; g != e {
		t.Errorf("got %q, want %q", g, e)
206
	}
207 208 209 210 211

	_, err = stdin.Write([]byte("E:I am error\n"))
	check("second stdin Write", err)
	if g, e := line("first error line", errbr), "E:I am error"; g != e {
		t.Errorf("got %q, want %q", g, e)
212
	}
213 214 215 216 217

	_, err = stdin.Write([]byte("O:I am output2\n"))
	check("third stdin Write 3", err)
	if g, e := line("second output line", outbr), "O:I am output2"; g != e {
		t.Errorf("got %q, want %q", g, e)
218
	}
219

220 221 222
	stdin.Close()
	err = c.Wait()
	check("Wait", err)
223 224
}

225 226 227 228 229 230 231 232 233
const stdinCloseTestString = "Some test string."

// Issue 6270.
func TestStdinClose(t *testing.T) {
	check := func(what string, err error) {
		if err != nil {
			t.Fatalf("%s: %v", what, err)
		}
	}
234
	cmd := helperCommand(t, "stdinClose")
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
	stdin, err := cmd.StdinPipe()
	check("StdinPipe", err)
	// Check that we can access methods of the underlying os.File.`
	if _, ok := stdin.(interface {
		Fd() uintptr
	}); !ok {
		t.Error("can't access methods of underlying *os.File")
	}
	check("Start", cmd.Start())
	go func() {
		_, err := io.Copy(stdin, strings.NewReader(stdinCloseTestString))
		check("Copy", err)
		// Before the fix, this next line would race with cmd.Wait.
		check("Close", stdin.Close())
	}()
	check("Wait", cmd.Wait())
}

253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
// Issue 17647.
// It used to be the case that TestStdinClose, above, would fail when
// run under the race detector. This test is a variant of TestStdinClose
// that also used to fail when run under the race detector.
// This test is run by cmd/dist under the race detector to verify that
// the race detector no longer reports any problems.
func TestStdinCloseRace(t *testing.T) {
	cmd := helperCommand(t, "stdinClose")
	stdin, err := cmd.StdinPipe()
	if err != nil {
		t.Fatalf("StdinPipe: %v", err)
	}
	if err := cmd.Start(); err != nil {
		t.Fatalf("Start: %v", err)
	}
	go func() {
269 270 271 272 273 274 275
		// We don't check the error return of Kill. It is
		// possible that the process has already exited, in
		// which case Kill will return an error "process
		// already finished". The purpose of this test is to
		// see whether the race detector reports an error; it
		// doesn't matter whether this Kill succeeds or not.
		cmd.Process.Kill()
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
	}()
	go func() {
		// Send the wrong string, so that the child fails even
		// if the other goroutine doesn't manage to kill it first.
		// This test is to check that the race detector does not
		// falsely report an error, so it doesn't matter how the
		// child process fails.
		io.Copy(stdin, strings.NewReader("unexpected string"))
		if err := stdin.Close(); err != nil {
			t.Errorf("stdin.Close: %v", err)
		}
	}()
	if err := cmd.Wait(); err == nil {
		t.Fatalf("Wait: succeeded unexpectedly")
	}
}

293 294
// Issue 5071
func TestPipeLookPathLeak(t *testing.T) {
295
	fd0, lsof0 := numOpenFDS(t)
296
	for i := 0; i < 4; i++ {
297
		cmd := exec.Command("something-that-does-not-exist-binary")
298 299 300 301 302 303 304
		cmd.StdoutPipe()
		cmd.StderrPipe()
		cmd.StdinPipe()
		if err := cmd.Run(); err == nil {
			t.Fatal("unexpected success")
		}
	}
305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
	for triesLeft := 3; triesLeft >= 0; triesLeft-- {
		open, lsof := numOpenFDS(t)
		fdGrowth := open - fd0
		if fdGrowth > 2 {
			if triesLeft > 0 {
				// Work around what appears to be a race with Linux's
				// proc filesystem (as used by lsof). It seems to only
				// be eventually consistent. Give it awhile to settle.
				// See golang.org/issue/7808
				time.Sleep(100 * time.Millisecond)
				continue
			}
			t.Errorf("leaked %d fds; want ~0; have:\n%s\noriginally:\n%s", fdGrowth, lsof, lsof0)
		}
		break
320 321 322
	}
}

323
func numOpenFDS(t *testing.T) (n int, lsof []byte) {
324 325 326 327 328 329
	if runtime.GOOS == "android" {
		// Android's stock lsof does not obey the -p option,
		// so extra filtering is needed. (golang.org/issue/10206)
		return numOpenFDsAndroid(t)
	}

330
	lsof, err := exec.Command("lsof", "-b", "-n", "-p", strconv.Itoa(os.Getpid())).Output()
331 332 333
	if err != nil {
		t.Skip("skipping test; error finding or running lsof")
	}
334
	return bytes.Count(lsof, []byte("\n")), lsof
335 336
}

337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375
func numOpenFDsAndroid(t *testing.T) (n int, lsof []byte) {
	raw, err := exec.Command("lsof").Output()
	if err != nil {
		t.Skip("skipping test; error finding or running lsof")
	}

	// First find the PID column index by parsing the first line, and
	// select lines containing pid in the column.
	pid := []byte(strconv.Itoa(os.Getpid()))
	pidCol := -1

	s := bufio.NewScanner(bytes.NewReader(raw))
	for s.Scan() {
		line := s.Bytes()
		fields := bytes.Fields(line)
		if pidCol < 0 {
			for i, v := range fields {
				if bytes.Equal(v, []byte("PID")) {
					pidCol = i
					break
				}
			}
			lsof = append(lsof, line...)
			continue
		}
		if bytes.Equal(fields[pidCol], pid) {
			lsof = append(lsof, '\n')
			lsof = append(lsof, line...)
		}
	}
	if pidCol < 0 {
		t.Fatal("error processing lsof output: unexpected header format")
	}
	if err := s.Err(); err != nil {
		t.Fatalf("error processing lsof output: %v", err)
	}
	return bytes.Count(lsof, []byte("\n")), lsof
}

376 377
var testedAlreadyLeaked = false

378 379 380
// basefds returns the number of expected file descriptors
// to be present in a process at start.
func basefds() uintptr {
381
	return os.Stderr.Fd() + 1
382 383
}

384 385 386 387 388 389 390 391 392
func closeUnexpectedFds(t *testing.T, m string) {
	for fd := basefds(); fd <= 101; fd++ {
		err := os.NewFile(fd, "").Close()
		if err == nil {
			t.Logf("%s: Something already leaked - closed fd %d", m, fd)
		}
	}
}

393
func TestExtraFilesFDShuffle(t *testing.T) {
394
	t.Skip("flaky test; see https://golang.org/issue/5780")
395 396
	switch runtime.GOOS {
	case "darwin":
397
		// TODO(cnicolaou): https://golang.org/issue/2603
398 399 400 401
		// leads to leaked file descriptors in this test when it's
		// run from a builder.
		closeUnexpectedFds(t, "TestExtraFilesFDShuffle")
	case "netbsd":
402
		// https://golang.org/issue/3955
403 404 405 406
		closeUnexpectedFds(t, "TestExtraFilesFDShuffle")
	case "windows":
		t.Skip("no operating system support; skipping")
	}
407 408 409 410 411 412 413 414 415 416

	// syscall.StartProcess maps all the FDs passed to it in
	// ProcAttr.Files (the concatenation of stdin,stdout,stderr and
	// ExtraFiles) into consecutive FDs in the child, that is:
	// Files{11, 12, 6, 7, 9, 3} should result in the file
	// represented by FD 11 in the parent being made available as 0
	// in the child, 12 as 1, etc.
	//
	// We want to test that FDs in the child do not get overwritten
	// by one another as this shuffle occurs. The original implementation
417
	// was buggy in that in some data dependent cases it would overwrite
418 419 420 421 422 423 424 425 426 427 428 429 430
	// stderr in the child with one of the ExtraFile members.
	// Testing for this case is difficult because it relies on using
	// the same FD values as that case. In particular, an FD of 3
	// must be at an index of 4 or higher in ProcAttr.Files and
	// the FD of the write end of the Stderr pipe (as obtained by
	// StderrPipe()) must be the same as the size of ProcAttr.Files;
	// therefore we test that the read end of this pipe (which is what
	// is returned to the parent by StderrPipe() being one less than
	// the size of ProcAttr.Files, i.e. 3+len(cmd.ExtraFiles).
	//
	// Moving this test case around within the overall tests may
	// affect the FDs obtained and hence the checks to catch these cases.
	npipes := 2
431
	c := helperCommand(t, "extraFilesAndPipes", strconv.Itoa(npipes+1))
432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478
	rd, wr, _ := os.Pipe()
	defer rd.Close()
	if rd.Fd() != 3 {
		t.Errorf("bad test value for test pipe: fd %d", rd.Fd())
	}
	stderr, _ := c.StderrPipe()
	wr.WriteString("_LAST")
	wr.Close()

	pipes := make([]struct {
		r, w *os.File
	}, npipes)
	data := []string{"a", "b"}

	for i := 0; i < npipes; i++ {
		r, w, err := os.Pipe()
		if err != nil {
			t.Fatalf("unexpected error creating pipe: %s", err)
		}
		pipes[i].r = r
		pipes[i].w = w
		w.WriteString(data[i])
		c.ExtraFiles = append(c.ExtraFiles, pipes[i].r)
		defer func() {
			r.Close()
			w.Close()
		}()
	}
	// Put fd 3 at the end.
	c.ExtraFiles = append(c.ExtraFiles, rd)

	stderrFd := int(stderr.(*os.File).Fd())
	if stderrFd != ((len(c.ExtraFiles) + 3) - 1) {
		t.Errorf("bad test value for stderr pipe")
	}

	expected := "child: " + strings.Join(data, "") + "_LAST"

	err := c.Start()
	if err != nil {
		t.Fatalf("Run: %v", err)
	}
	ch := make(chan string, 1)
	go func(ch chan string) {
		buf := make([]byte, 512)
		n, err := stderr.Read(buf)
		if err != nil {
479
			t.Errorf("Read: %s", err)
480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
			ch <- err.Error()
		} else {
			ch <- string(buf[:n])
		}
		close(ch)
	}(ch)
	select {
	case m := <-ch:
		if m != expected {
			t.Errorf("Read: '%s' not '%s'", m, expected)
		}
	case <-time.After(5 * time.Second):
		t.Errorf("Read timedout")
	}
	c.Wait()
}

497
func TestExtraFiles(t *testing.T) {
498 499 500
	testenv.MustHaveExec(t)

	if runtime.GOOS == "windows" {
501
		t.Skipf("skipping test on %q", runtime.GOOS)
502
	}
503

504 505
	// Ensure that file descriptors have not already been leaked into
	// our environment.
506 507
	if !testedAlreadyLeaked {
		testedAlreadyLeaked = true
508
		closeUnexpectedFds(t, "TestExtraFiles")
509 510
	}

511 512 513 514 515 516 517 518
	// Force network usage, to verify the epoll (or whatever) fd
	// doesn't leak to the child,
	ln, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		t.Fatal(err)
	}
	defer ln.Close()

519 520 521 522 523 524 525 526 527 528 529 530
	// Make sure duplicated fds don't leak to the child.
	f, err := ln.(*net.TCPListener).File()
	if err != nil {
		t.Fatal(err)
	}
	defer f.Close()
	ln2, err := net.FileListener(f)
	if err != nil {
		t.Fatal(err)
	}
	defer ln2.Close()

531 532
	// Force TLS root certs to be loaded (which might involve
	// cgo), to make sure none of that potential C code leaks fds.
533 534 535 536
	ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
	// quiet expected TLS handshake error "remote error: bad certificate"
	ts.Config.ErrorLog = log.New(ioutil.Discard, "", 0)
	ts.StartTLS()
537
	defer ts.Close()
538 539 540 541
	_, err = http.Get(ts.URL)
	if err == nil {
		t.Errorf("success trying to fetch %s; want an error", ts.URL)
	}
542

543 544 545 546 547 548 549 550 551 552 553 554
	tf, err := ioutil.TempFile("", "")
	if err != nil {
		t.Fatalf("TempFile: %v", err)
	}
	defer os.Remove(tf.Name())
	defer tf.Close()

	const text = "Hello, fd 3!"
	_, err = tf.Write([]byte(text))
	if err != nil {
		t.Fatalf("Write: %v", err)
	}
555
	_, err = tf.Seek(0, io.SeekStart)
556 557 558 559
	if err != nil {
		t.Fatalf("Seek: %v", err)
	}

560
	c := helperCommand(t, "read3")
561 562 563
	var stdout, stderr bytes.Buffer
	c.Stdout = &stdout
	c.Stderr = &stderr
564
	c.ExtraFiles = []*os.File{tf}
565
	err = c.Run()
566
	if err != nil {
567
		t.Fatalf("Run: %v; stdout %q, stderr %q", err, stdout.Bytes(), stderr.Bytes())
568
	}
569 570
	if stdout.String() != text {
		t.Errorf("got stdout %q, stderr %q; want %q on stdout", stdout.String(), stderr.String(), text)
571 572 573
	}
}

574 575
func TestExtraFilesRace(t *testing.T) {
	if runtime.GOOS == "windows" {
576
		t.Skip("no operating system support; skipping")
577 578 579 580 581 582 583 584 585 586 587 588 589 590 591
	}
	listen := func() net.Listener {
		ln, err := net.Listen("tcp", "127.0.0.1:0")
		if err != nil {
			t.Fatal(err)
		}
		return ln
	}
	listenerFile := func(ln net.Listener) *os.File {
		f, err := ln.(*net.TCPListener).File()
		if err != nil {
			t.Fatal(err)
		}
		return f
	}
592
	runCommand := func(c *exec.Cmd, out chan<- string) {
593 594 595 596 597 598 599 600 601 602
		bout, err := c.CombinedOutput()
		if err != nil {
			out <- "ERROR:" + err.Error()
		} else {
			out <- string(bout)
		}
	}

	for i := 0; i < 10; i++ {
		la := listen()
603
		ca := helperCommand(t, "describefiles")
604 605
		ca.ExtraFiles = []*os.File{listenerFile(la)}
		lb := listen()
606
		cb := helperCommand(t, "describefiles")
607 608 609 610 611 612 613 614 615 616 617 618 619
		cb.ExtraFiles = []*os.File{listenerFile(lb)}
		ares := make(chan string)
		bres := make(chan string)
		go runCommand(ca, ares)
		go runCommand(cb, bres)
		if got, want := <-ares, fmt.Sprintf("fd3: listener %s\n", la.Addr()); got != want {
			t.Errorf("iteration %d, process A got:\n%s\nwant:\n%s\n", i, got, want)
		}
		if got, want := <-bres, fmt.Sprintf("fd3: listener %s\n", lb.Addr()); got != want {
			t.Errorf("iteration %d, process B got:\n%s\nwant:\n%s\n", i, got, want)
		}
		la.Close()
		lb.Close()
620 621 622 623 624 625 626
		for _, f := range ca.ExtraFiles {
			f.Close()
		}
		for _, f := range cb.ExtraFiles {
			f.Close()
		}

627 628 629
	}
}

630 631 632 633 634 635 636 637
// TestHelperProcess isn't a real test. It's used as a helper process
// for TestParameterRun.
func TestHelperProcess(*testing.T) {
	if os.Getenv("GO_WANT_HELPER_PROCESS") != "1" {
		return
	}
	defer os.Exit(0)

638 639 640
	// Determine which command to use to display open files.
	ofcmd := "lsof"
	switch runtime.GOOS {
641
	case "dragonfly", "freebsd", "netbsd", "openbsd":
642
		ofcmd = "fstat"
643 644
	case "plan9":
		ofcmd = "/bin/cat"
645 646
	}

647 648 649 650 651
	args := os.Args
	for len(args) > 0 {
		if args[0] == "--" {
			args = args[1:]
			break
652
		}
653 654 655 656 657 658 659 660 661 662 663 664 665
		args = args[1:]
	}
	if len(args) == 0 {
		fmt.Fprintf(os.Stderr, "No command\n")
		os.Exit(2)
	}

	cmd, args := args[0], args[1:]
	switch cmd {
	case "echo":
		iargs := []interface{}{}
		for _, s := range args {
			iargs = append(iargs, s)
666
		}
667 668 669 670 671
		fmt.Println(iargs...)
	case "cat":
		if len(args) == 0 {
			io.Copy(os.Stdout, os.Stdin)
			return
672
		}
673 674 675 676 677 678 679 680 681 682
		exit := 0
		for _, fn := range args {
			f, err := os.Open(fn)
			if err != nil {
				fmt.Fprintf(os.Stderr, "Error: %v\n", err)
				exit = 2
			} else {
				defer f.Close()
				io.Copy(os.Stdout, f)
			}
683
		}
684 685 686 687 688
		os.Exit(exit)
	case "pipetest":
		bufr := bufio.NewReader(os.Stdin)
		for {
			line, _, err := bufr.ReadLine()
689
			if err == io.EOF {
690 691 692 693 694 695 696 697 698 699 700 701 702
				break
			} else if err != nil {
				os.Exit(1)
			}
			if bytes.HasPrefix(line, []byte("O:")) {
				os.Stdout.Write(line)
				os.Stdout.Write([]byte{'\n'})
			} else if bytes.HasPrefix(line, []byte("E:")) {
				os.Stderr.Write(line)
				os.Stderr.Write([]byte{'\n'})
			} else {
				os.Exit(1)
			}
703
		}
704 705 706 707 708 709 710 711 712 713 714
	case "stdinClose":
		b, err := ioutil.ReadAll(os.Stdin)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Error: %v\n", err)
			os.Exit(1)
		}
		if s := string(b); s != stdinCloseTestString {
			fmt.Fprintf(os.Stderr, "Error: Read %q, want %q", s, stdinCloseTestString)
			os.Exit(1)
		}
		os.Exit(0)
715 716 717 718 719 720 721
	case "read3": // read fd 3
		fd3 := os.NewFile(3, "fd3")
		bs, err := ioutil.ReadAll(fd3)
		if err != nil {
			fmt.Printf("ReadAll from fd 3: %v", err)
			os.Exit(1)
		}
722
		switch runtime.GOOS {
723 724 725
		case "dragonfly":
			// TODO(jsing): Determine why DragonFly is leaking
			// file descriptors...
726 727
		case "darwin":
			// TODO(bradfitz): broken? Sometimes.
728
			// https://golang.org/issue/2603
729
			// Skip this additional part of the test for now.
730 731 732 733
		case "netbsd":
			// TODO(jsing): This currently fails on NetBSD due to
			// the cloned file descriptors that result from opening
			// /dev/urandom.
734
			// https://golang.org/issue/3955
735 736 737
		case "solaris":
			// TODO(aram): This fails on Solaris because libc opens
			// its own files, as it sees fit. Darwin does the same,
738
			// see: https://golang.org/issue/2603
739 740 741
		default:
			// Now verify that there are no other open fds.
			var files []*os.File
742
			for wantfd := basefds() + 1; wantfd <= 100; wantfd++ {
743 744 745 746 747 748 749
				f, err := os.Open(os.Args[0])
				if err != nil {
					fmt.Printf("error opening file with expected fd %d: %v", wantfd, err)
					os.Exit(1)
				}
				if got := f.Fd(); got != wantfd {
					fmt.Printf("leaked parent file. fd = %d; want %d\n", got, wantfd)
750 751 752 753 754 755 756 757
					var args []string
					switch runtime.GOOS {
					case "plan9":
						args = []string{fmt.Sprintf("/proc/%d/fd", os.Getpid())}
					default:
						args = []string{"-p", fmt.Sprint(os.Getpid())}
					}
					out, _ := exec.Command(ofcmd, args...).CombinedOutput()
758 759 760 761 762 763 764 765 766
					fmt.Print(string(out))
					os.Exit(1)
				}
				files = append(files, f)
			}
			for _, f := range files {
				f.Close()
			}
		}
767 768
		// Referring to fd3 here ensures that it is not
		// garbage collected, and therefore closed, while
769
		// executing the wantfd loop above. It doesn't matter
770 771
		// what we do with fd3 as long as we refer to it;
		// closing it is the easy choice.
772
		fd3.Close()
773
		os.Stdout.Write(bs)
774 775 776
	case "exit":
		n, _ := strconv.Atoi(args[0])
		os.Exit(n)
777
	case "describefiles":
778 779 780 781 782
		f := os.NewFile(3, fmt.Sprintf("fd3"))
		ln, err := net.FileListener(f)
		if err == nil {
			fmt.Printf("fd3: listener %s\n", ln.Addr())
			ln.Close()
783 784
		}
		os.Exit(0)
785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813
	case "extraFilesAndPipes":
		n, _ := strconv.Atoi(args[0])
		pipes := make([]*os.File, n)
		for i := 0; i < n; i++ {
			pipes[i] = os.NewFile(uintptr(3+i), strconv.Itoa(i))
		}
		response := ""
		for i, r := range pipes {
			ch := make(chan string, 1)
			go func(c chan string) {
				buf := make([]byte, 10)
				n, err := r.Read(buf)
				if err != nil {
					fmt.Fprintf(os.Stderr, "Child: read error: %v on pipe %d\n", err, i)
					os.Exit(1)
				}
				c <- string(buf[:n])
				close(c)
			}(ch)
			select {
			case m := <-ch:
				response = response + m
			case <-time.After(5 * time.Second):
				fmt.Fprintf(os.Stderr, "Child: Timeout reading from pipe: %d\n", i)
				os.Exit(1)
			}
		}
		fmt.Fprintf(os.Stderr, "child: %s", response)
		os.Exit(0)
814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831
	case "exec":
		cmd := exec.Command(args[1])
		cmd.Dir = args[0]
		output, err := cmd.CombinedOutput()
		if err != nil {
			fmt.Fprintf(os.Stderr, "Child: %s %s", err, string(output))
			os.Exit(1)
		}
		fmt.Printf("%s", string(output))
		os.Exit(0)
	case "lookpath":
		p, err := exec.LookPath(args[0])
		if err != nil {
			fmt.Fprintf(os.Stderr, "LookPath failed: %v\n", err)
			os.Exit(1)
		}
		fmt.Print(p)
		os.Exit(0)
832 833 834
	case "stderrfail":
		fmt.Fprintf(os.Stderr, "some stderr text\n")
		os.Exit(1)
835 836 837
	default:
		fmt.Fprintf(os.Stderr, "Unknown command %q\n", cmd)
		os.Exit(2)
838 839
	}
}
840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890

// Issue 9173: ignore stdin pipe writes if the program completes successfully.
func TestIgnorePipeErrorOnSuccess(t *testing.T) {
	testenv.MustHaveExec(t)

	// We really only care about testing this on Unixy things.
	if runtime.GOOS == "windows" || runtime.GOOS == "plan9" {
		t.Skipf("skipping test on %q", runtime.GOOS)
	}

	cmd := helperCommand(t, "echo", "foo")
	var out bytes.Buffer
	cmd.Stdin = strings.NewReader(strings.Repeat("x", 10<<20))
	cmd.Stdout = &out
	if err := cmd.Run(); err != nil {
		t.Fatal(err)
	}
	if got, want := out.String(), "foo\n"; got != want {
		t.Errorf("output = %q; want %q", got, want)
	}
}

type badWriter struct{}

func (w *badWriter) Write(data []byte) (int, error) {
	return 0, io.ErrUnexpectedEOF
}

func TestClosePipeOnCopyError(t *testing.T) {
	testenv.MustHaveExec(t)

	if runtime.GOOS == "windows" || runtime.GOOS == "plan9" {
		t.Skipf("skipping test on %s - no yes command", runtime.GOOS)
	}
	cmd := exec.Command("yes")
	cmd.Stdout = new(badWriter)
	c := make(chan int, 1)
	go func() {
		err := cmd.Run()
		if err == nil {
			t.Errorf("yes completed successfully")
		}
		c <- 1
	}()
	select {
	case <-c:
		// ok
	case <-time.After(5 * time.Second):
		t.Fatalf("yes got stuck writing to bad writer")
	}
}
891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906

func TestOutputStderrCapture(t *testing.T) {
	testenv.MustHaveExec(t)

	cmd := helperCommand(t, "stderrfail")
	_, err := cmd.Output()
	ee, ok := err.(*exec.ExitError)
	if !ok {
		t.Fatalf("Output error type = %T; want ExitError", err)
	}
	got := string(ee.Stderr)
	want := "some stderr text\n"
	if got != want {
		t.Errorf("ExitError.Stderr = %q; want %q", got, want)
	}
}
907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998

func TestContext(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	c := helperCommandContext(t, ctx, "pipetest")
	stdin, err := c.StdinPipe()
	if err != nil {
		t.Fatal(err)
	}
	stdout, err := c.StdoutPipe()
	if err != nil {
		t.Fatal(err)
	}
	if err := c.Start(); err != nil {
		t.Fatal(err)
	}

	if _, err := stdin.Write([]byte("O:hi\n")); err != nil {
		t.Fatal(err)
	}
	buf := make([]byte, 5)
	n, err := io.ReadFull(stdout, buf)
	if n != len(buf) || err != nil || string(buf) != "O:hi\n" {
		t.Fatalf("ReadFull = %d, %v, %q", n, err, buf[:n])
	}
	waitErr := make(chan error, 1)
	go func() {
		waitErr <- c.Wait()
	}()
	cancel()
	select {
	case err := <-waitErr:
		if err == nil {
			t.Fatal("expected Wait failure")
		}
	case <-time.After(3 * time.Second):
		t.Fatal("timeout waiting for child process death")
	}
}

func TestContextCancel(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	c := helperCommandContext(t, ctx, "cat")

	r, w, err := os.Pipe()
	if err != nil {
		t.Fatal(err)
	}
	c.Stdin = r

	stdout, err := c.StdoutPipe()
	if err != nil {
		t.Fatal(err)
	}
	readDone := make(chan struct{})
	go func() {
		defer close(readDone)
		var a [1024]byte
		for {
			n, err := stdout.Read(a[:])
			if err != nil {
				if err != io.EOF {
					t.Errorf("unexpected read error: %v", err)
				}
				return
			}
			t.Logf("%s", a[:n])
		}
	}()

	if err := c.Start(); err != nil {
		t.Fatal(err)
	}

	if err := r.Close(); err != nil {
		t.Fatal(err)
	}

	if _, err := io.WriteString(w, "echo"); err != nil {
		t.Fatal(err)
	}

	cancel()

	// Calling cancel should have killed the process, so writes
	// should now fail.  Give the process a little while to die.
	start := time.Now()
	for {
		if _, err := io.WriteString(w, "echo"); err != nil {
			break
		}
		if time.Since(start) > time.Second {
999
			t.Fatal("canceling context did not stop program")
1000 1001 1002 1003 1004
		}
		time.Sleep(time.Millisecond)
	}

	if err := w.Close(); err != nil {
1005
		t.Errorf("error closing write end of pipe: %v", err)
1006 1007 1008 1009 1010 1011 1012 1013 1014
	}
	<-readDone

	if err := c.Wait(); err == nil {
		t.Error("program unexpectedly exited successfully")
	} else {
		t.Logf("exit status: %v", err)
	}
}