Source file src/os/exec/exec_posix_test.go

     1  // Copyright 2017 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  //go:build unix
     6  
     7  package exec_test
     8  
     9  import (
    10  	"fmt"
    11  	"internal/testenv"
    12  	"io"
    13  	"os"
    14  	"os/exec"
    15  	"os/signal"
    16  	"os/user"
    17  	"path/filepath"
    18  	"runtime"
    19  	"slices"
    20  	"strconv"
    21  	"strings"
    22  	"sync"
    23  	"syscall"
    24  	"testing"
    25  	"time"
    26  )
    27  
    28  func init() {
    29  	registerHelperCommand("pwd", cmdPwd)
    30  	registerHelperCommand("signaltest", cmdSignalTest)
    31  }
    32  
    33  func cmdPwd(...string) {
    34  	pwd, err := os.Getwd()
    35  	if err != nil {
    36  		fmt.Fprintln(os.Stderr, err)
    37  		os.Exit(1)
    38  	}
    39  	fmt.Println(pwd)
    40  }
    41  
    42  func TestCredentialNoSetGroups(t *testing.T) {
    43  	if runtime.GOOS == "android" {
    44  		maySkipHelperCommand("echo")
    45  		t.Skip("unsupported on Android")
    46  	}
    47  	t.Parallel()
    48  
    49  	u, err := user.Current()
    50  	if err != nil {
    51  		t.Fatalf("error getting current user: %v", err)
    52  	}
    53  
    54  	uid, err := strconv.Atoi(u.Uid)
    55  	if err != nil {
    56  		t.Fatalf("error converting Uid=%s to integer: %v", u.Uid, err)
    57  	}
    58  
    59  	gid, err := strconv.Atoi(u.Gid)
    60  	if err != nil {
    61  		t.Fatalf("error converting Gid=%s to integer: %v", u.Gid, err)
    62  	}
    63  
    64  	// If NoSetGroups is true, setgroups isn't called and cmd.Run should succeed
    65  	cmd := helperCommand(t, "echo", "foo")
    66  	cmd.SysProcAttr = &syscall.SysProcAttr{
    67  		Credential: &syscall.Credential{
    68  			Uid:         uint32(uid),
    69  			Gid:         uint32(gid),
    70  			NoSetGroups: true,
    71  		},
    72  	}
    73  
    74  	if err = cmd.Run(); err != nil {
    75  		t.Errorf("Failed to run command: %v", err)
    76  	}
    77  }
    78  
    79  // For issue #19314: make sure that SIGSTOP does not cause the process
    80  // to appear done.
    81  func TestWaitid(t *testing.T) {
    82  	t.Parallel()
    83  
    84  	cmd := helperCommand(t, "pipetest")
    85  	stdin, err := cmd.StdinPipe()
    86  	if err != nil {
    87  		t.Fatal(err)
    88  	}
    89  	stdout, err := cmd.StdoutPipe()
    90  	if err != nil {
    91  		t.Fatal(err)
    92  	}
    93  	if err := cmd.Start(); err != nil {
    94  		t.Fatal(err)
    95  	}
    96  
    97  	// Wait for the child process to come up and register any signal handlers.
    98  	const msg = "O:ping\n"
    99  	if _, err := io.WriteString(stdin, msg); err != nil {
   100  		t.Fatal(err)
   101  	}
   102  	buf := make([]byte, len(msg))
   103  	if _, err := io.ReadFull(stdout, buf); err != nil {
   104  		t.Fatal(err)
   105  	}
   106  	// Now leave the pipes open so that the process will hang until we close stdin.
   107  
   108  	if err := cmd.Process.Signal(syscall.SIGSTOP); err != nil {
   109  		cmd.Process.Kill()
   110  		t.Fatal(err)
   111  	}
   112  
   113  	ch := make(chan error)
   114  	go func() {
   115  		ch <- cmd.Wait()
   116  	}()
   117  
   118  	// Give a little time for Wait to block on waiting for the process.
   119  	// (This is just to give some time to trigger the bug; it should not be
   120  	// necessary for the test to pass.)
   121  	if testing.Short() {
   122  		time.Sleep(1 * time.Millisecond)
   123  	} else {
   124  		time.Sleep(10 * time.Millisecond)
   125  	}
   126  
   127  	// This call to Signal should succeed because the process still exists.
   128  	// (Prior to the fix for #19314, this would fail with os.ErrProcessDone
   129  	// or an equivalent error.)
   130  	if err := cmd.Process.Signal(syscall.SIGCONT); err != nil {
   131  		t.Error(err)
   132  		syscall.Kill(cmd.Process.Pid, syscall.SIGCONT)
   133  	}
   134  
   135  	// The SIGCONT should allow the process to wake up, notice that stdin
   136  	// is closed, and exit successfully.
   137  	stdin.Close()
   138  	err = <-ch
   139  	if err != nil {
   140  		t.Fatal(err)
   141  	}
   142  }
   143  
   144  // https://go.dev/issue/50599: if Env is not set explicitly, setting Dir should
   145  // implicitly update PWD to the correct path, and Environ should list the
   146  // updated value.
   147  func TestImplicitPWD(t *testing.T) {
   148  	t.Parallel()
   149  
   150  	cwd, err := os.Getwd()
   151  	if err != nil {
   152  		t.Fatal(err)
   153  	}
   154  
   155  	cases := []struct {
   156  		name string
   157  		dir  string
   158  		want string
   159  	}{
   160  		{"empty", "", cwd},
   161  		{"dot", ".", cwd},
   162  		{"dotdot", "..", filepath.Dir(cwd)},
   163  		{"PWD", cwd, cwd},
   164  		{"PWDdotdot", cwd + string(filepath.Separator) + "..", filepath.Dir(cwd)},
   165  	}
   166  
   167  	for _, tc := range cases {
   168  		t.Run(tc.name, func(t *testing.T) {
   169  			t.Parallel()
   170  
   171  			cmd := helperCommand(t, "pwd")
   172  			if cmd.Env != nil {
   173  				t.Fatalf("test requires helperCommand not to set Env field")
   174  			}
   175  			cmd.Dir = tc.dir
   176  
   177  			var pwds []string
   178  			for _, kv := range cmd.Environ() {
   179  				if strings.HasPrefix(kv, "PWD=") {
   180  					pwds = append(pwds, strings.TrimPrefix(kv, "PWD="))
   181  				}
   182  			}
   183  
   184  			wantPWDs := []string{tc.want}
   185  			if tc.dir == "" {
   186  				if _, ok := os.LookupEnv("PWD"); !ok {
   187  					wantPWDs = nil
   188  				}
   189  			}
   190  			if !slices.Equal(pwds, wantPWDs) {
   191  				t.Errorf("PWD entries in cmd.Environ():\n\t%s\nwant:\n\t%s", strings.Join(pwds, "\n\t"), strings.Join(wantPWDs, "\n\t"))
   192  			}
   193  
   194  			cmd.Stderr = new(strings.Builder)
   195  			out, err := cmd.Output()
   196  			if err != nil {
   197  				t.Fatalf("%v:\n%s", err, cmd.Stderr)
   198  			}
   199  			got := strings.Trim(string(out), "\r\n")
   200  			t.Logf("in\n\t%s\n`pwd` reported\n\t%s", tc.dir, got)
   201  			if got != tc.want {
   202  				t.Errorf("want\n\t%s", tc.want)
   203  			}
   204  		})
   205  	}
   206  }
   207  
   208  // However, if cmd.Env is set explicitly, setting Dir should not override it.
   209  // (This checks that the implementation for https://go.dev/issue/50599 doesn't
   210  // break existing users who may have explicitly mismatched the PWD variable.)
   211  func TestExplicitPWD(t *testing.T) {
   212  	t.Parallel()
   213  
   214  	maySkipHelperCommand("pwd")
   215  	testenv.MustHaveSymlink(t)
   216  
   217  	cwd, err := os.Getwd()
   218  	if err != nil {
   219  		t.Fatal(err)
   220  	}
   221  
   222  	link := filepath.Join(t.TempDir(), "link")
   223  	if err := os.Symlink(cwd, link); err != nil {
   224  		t.Fatal(err)
   225  	}
   226  
   227  	// Now link is another equally-valid name for cwd. If we set Dir to one and
   228  	// PWD to the other, the subprocess should report the PWD version.
   229  	cases := []struct {
   230  		name string
   231  		dir  string
   232  		pwd  string
   233  	}{
   234  		{name: "original PWD", pwd: cwd},
   235  		{name: "link PWD", pwd: link},
   236  		{name: "in link with original PWD", dir: link, pwd: cwd},
   237  		{name: "in dir with link PWD", dir: cwd, pwd: link},
   238  		// Ideally we would also like to test what happens if we set PWD to
   239  		// something totally bogus (or the empty string), but then we would have no
   240  		// idea what output the subprocess should actually produce: cwd itself may
   241  		// contain symlinks preserved from the PWD value in the test's environment.
   242  	}
   243  	for _, tc := range cases {
   244  		t.Run(tc.name, func(t *testing.T) {
   245  			t.Parallel()
   246  
   247  			cmd := helperCommand(t, "pwd")
   248  			// This is intentionally opposite to the usual order of setting cmd.Dir
   249  			// and then calling cmd.Environ. Here, we *want* PWD not to match cmd.Dir,
   250  			// so we don't care whether cmd.Dir is reflected in cmd.Environ.
   251  			cmd.Env = append(cmd.Environ(), "PWD="+tc.pwd)
   252  			cmd.Dir = tc.dir
   253  
   254  			var pwds []string
   255  			for _, kv := range cmd.Environ() {
   256  				if strings.HasPrefix(kv, "PWD=") {
   257  					pwds = append(pwds, strings.TrimPrefix(kv, "PWD="))
   258  				}
   259  			}
   260  
   261  			wantPWDs := []string{tc.pwd}
   262  			if !slices.Equal(pwds, wantPWDs) {
   263  				t.Errorf("PWD entries in cmd.Environ():\n\t%s\nwant:\n\t%s", strings.Join(pwds, "\n\t"), strings.Join(wantPWDs, "\n\t"))
   264  			}
   265  
   266  			cmd.Stderr = new(strings.Builder)
   267  			out, err := cmd.Output()
   268  			if err != nil {
   269  				t.Fatalf("%v:\n%s", err, cmd.Stderr)
   270  			}
   271  			got := strings.Trim(string(out), "\r\n")
   272  			t.Logf("in\n\t%s\nwith PWD=%s\nsubprocess os.Getwd() reported\n\t%s", tc.dir, tc.pwd, got)
   273  			if got != tc.pwd {
   274  				t.Errorf("want\n\t%s", tc.pwd)
   275  			}
   276  		})
   277  	}
   278  }
   279  
   280  // Issue 71828.
   281  func TestSIGCHLD(t *testing.T) {
   282  	cmd := helperCommand(t, "signaltest")
   283  	out, err := cmd.CombinedOutput()
   284  	t.Logf("%s", out)
   285  	if err != nil {
   286  		t.Error(err)
   287  	}
   288  }
   289  
   290  // cmdSignaltest is for TestSIGCHLD.
   291  // This runs in a separate process because the bug only happened
   292  // the first time that a child process was started.
   293  func cmdSignalTest(...string) {
   294  	chSig := make(chan os.Signal, 1)
   295  	signal.Notify(chSig, syscall.SIGCHLD)
   296  
   297  	var wg sync.WaitGroup
   298  	wg.Add(1)
   299  	go func() {
   300  		defer wg.Done()
   301  		c := 0
   302  		for range chSig {
   303  			c++
   304  			fmt.Printf("SIGCHLD %d\n", c)
   305  			if c > 1 {
   306  				fmt.Println("too many SIGCHLD signals")
   307  				os.Exit(1)
   308  			}
   309  		}
   310  	}()
   311  	defer func() {
   312  		signal.Reset(syscall.SIGCHLD)
   313  		close(chSig)
   314  		wg.Wait()
   315  	}()
   316  
   317  	exe, err := os.Executable()
   318  	if err != nil {
   319  		fmt.Printf("os.Executable failed: %v\n", err)
   320  		os.Exit(1)
   321  	}
   322  
   323  	cmd := exec.Command(exe, "hang", "200ms")
   324  	cmd.Stdout = os.Stdout
   325  	cmd.Stderr = os.Stderr
   326  	if err := cmd.Run(); err != nil {
   327  		fmt.Printf("failed to run child process: %v\n", err)
   328  		os.Exit(1)
   329  	}
   330  }
   331  

View as plain text