Source file src/os/os_windows_test.go

     1  // Copyright 2014 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  package os_test
     6  
     7  import (
     8  	"bytes"
     9  	"errors"
    10  	"fmt"
    11  	"internal/godebug"
    12  	"internal/poll"
    13  	"internal/syscall/windows"
    14  	"internal/syscall/windows/registry"
    15  	"internal/testenv"
    16  	"io"
    17  	"io/fs"
    18  	"os"
    19  	"os/exec"
    20  	"path/filepath"
    21  	"runtime"
    22  	"slices"
    23  	"strconv"
    24  	"strings"
    25  	"sync"
    26  	"sync/atomic"
    27  	"syscall"
    28  	"testing"
    29  	"testing/synctest"
    30  	"time"
    31  	"unicode/utf16"
    32  	"unsafe"
    33  )
    34  
    35  var winsymlink = godebug.New("winsymlink")
    36  var winreadlinkvolume = godebug.New("winreadlinkvolume")
    37  
    38  // For TestRawConnReadWrite.
    39  type syscallDescriptor = syscall.Handle
    40  
    41  func TestSameWindowsFile(t *testing.T) {
    42  	t.Chdir(t.TempDir())
    43  
    44  	f, err := os.Create("a")
    45  	if err != nil {
    46  		t.Fatal(err)
    47  	}
    48  	f.Close()
    49  
    50  	ia1, err := os.Stat("a")
    51  	if err != nil {
    52  		t.Fatal(err)
    53  	}
    54  
    55  	path, err := filepath.Abs("a")
    56  	if err != nil {
    57  		t.Fatal(err)
    58  	}
    59  	ia2, err := os.Stat(path)
    60  	if err != nil {
    61  		t.Fatal(err)
    62  	}
    63  	if !os.SameFile(ia1, ia2) {
    64  		t.Errorf("files should be same")
    65  	}
    66  
    67  	p := filepath.VolumeName(path) + filepath.Base(path)
    68  	ia3, err := os.Stat(p)
    69  	if err != nil {
    70  		t.Fatal(err)
    71  	}
    72  	if !os.SameFile(ia1, ia3) {
    73  		t.Errorf("files should be same")
    74  	}
    75  }
    76  
    77  type dirLinkTest struct {
    78  	name         string
    79  	mklink       func(link, target string) error
    80  	isMountPoint bool
    81  }
    82  
    83  func testDirLinks(t *testing.T, tests []dirLinkTest) {
    84  	tmpdir := t.TempDir()
    85  	t.Chdir(tmpdir)
    86  
    87  	dir := filepath.Join(tmpdir, "dir")
    88  	err := os.Mkdir(dir, 0777)
    89  	if err != nil {
    90  		t.Fatal(err)
    91  	}
    92  	fi, err := os.Stat(dir)
    93  	if err != nil {
    94  		t.Fatal(err)
    95  	}
    96  	err = os.WriteFile(filepath.Join(dir, "abc"), []byte("abc"), 0644)
    97  	if err != nil {
    98  		t.Fatal(err)
    99  	}
   100  	for _, test := range tests {
   101  		link := filepath.Join(tmpdir, test.name+"_link")
   102  		err := test.mklink(link, dir)
   103  		if err != nil {
   104  			t.Errorf("creating link for %q test failed: %v", test.name, err)
   105  			continue
   106  		}
   107  
   108  		data, err := os.ReadFile(filepath.Join(link, "abc"))
   109  		if err != nil {
   110  			t.Errorf("failed to read abc file: %v", err)
   111  			continue
   112  		}
   113  		if string(data) != "abc" {
   114  			t.Errorf(`abc file is expected to have "abc" in it, but has %v`, data)
   115  			continue
   116  		}
   117  
   118  		fi1, err := os.Stat(link)
   119  		if err != nil {
   120  			t.Errorf("failed to stat link %v: %v", link, err)
   121  			continue
   122  		}
   123  		if tp := fi1.Mode().Type(); tp != fs.ModeDir {
   124  			t.Errorf("Stat(%q) is type %v; want %v", link, tp, fs.ModeDir)
   125  			continue
   126  		}
   127  		if fi1.Name() != filepath.Base(link) {
   128  			t.Errorf("Stat(%q).Name() = %q, want %q", link, fi1.Name(), filepath.Base(link))
   129  			continue
   130  		}
   131  		if !os.SameFile(fi, fi1) {
   132  			t.Errorf("%q should point to %q", link, dir)
   133  			continue
   134  		}
   135  
   136  		fi2, err := os.Lstat(link)
   137  		if err != nil {
   138  			t.Errorf("failed to lstat link %v: %v", link, err)
   139  			continue
   140  		}
   141  		var wantType fs.FileMode
   142  		if test.isMountPoint && winsymlink.Value() != "0" {
   143  			// Mount points are reparse points, and we no longer treat them as symlinks.
   144  			wantType = fs.ModeIrregular
   145  		} else {
   146  			// This is either a real symlink, or a mount point treated as a symlink.
   147  			wantType = fs.ModeSymlink
   148  		}
   149  		if tp := fi2.Mode().Type(); tp != wantType {
   150  			t.Errorf("Lstat(%q) is type %v; want %v", link, tp, wantType)
   151  		}
   152  	}
   153  }
   154  
   155  // reparseData is used to build reparse buffer data required for tests.
   156  type reparseData struct {
   157  	substituteName namePosition
   158  	printName      namePosition
   159  	pathBuf        []uint16
   160  }
   161  
   162  type namePosition struct {
   163  	offset uint16
   164  	length uint16
   165  }
   166  
   167  func (rd *reparseData) addUTF16s(s []uint16) (offset uint16) {
   168  	off := len(rd.pathBuf) * 2
   169  	rd.pathBuf = append(rd.pathBuf, s...)
   170  	return uint16(off)
   171  }
   172  
   173  func (rd *reparseData) addString(s string) (offset, length uint16) {
   174  	p := syscall.StringToUTF16(s)
   175  	return rd.addUTF16s(p), uint16(len(p)-1) * 2 // do not include terminating NUL in the length (as per PrintNameLength and SubstituteNameLength documentation)
   176  }
   177  
   178  func (rd *reparseData) addSubstituteName(name string) {
   179  	rd.substituteName.offset, rd.substituteName.length = rd.addString(name)
   180  }
   181  
   182  func (rd *reparseData) addPrintName(name string) {
   183  	rd.printName.offset, rd.printName.length = rd.addString(name)
   184  }
   185  
   186  func (rd *reparseData) addStringNoNUL(s string) (offset, length uint16) {
   187  	p := syscall.StringToUTF16(s)
   188  	p = p[:len(p)-1]
   189  	return rd.addUTF16s(p), uint16(len(p)) * 2
   190  }
   191  
   192  func (rd *reparseData) addSubstituteNameNoNUL(name string) {
   193  	rd.substituteName.offset, rd.substituteName.length = rd.addStringNoNUL(name)
   194  }
   195  
   196  func (rd *reparseData) addPrintNameNoNUL(name string) {
   197  	rd.printName.offset, rd.printName.length = rd.addStringNoNUL(name)
   198  }
   199  
   200  // pathBuffeLen returns length of rd pathBuf in bytes.
   201  func (rd *reparseData) pathBuffeLen() uint16 {
   202  	return uint16(len(rd.pathBuf)) * 2
   203  }
   204  
   205  // Windows REPARSE_DATA_BUFFER contains union member, and cannot be
   206  // translated into Go directly. _REPARSE_DATA_BUFFER type is to help
   207  // construct alternative versions of Windows REPARSE_DATA_BUFFER with
   208  // different layouts for its union member.
   209  type _REPARSE_DATA_BUFFER struct {
   210  	header windows.REPARSE_DATA_BUFFER_HEADER
   211  	detail [syscall.MAXIMUM_REPARSE_DATA_BUFFER_SIZE]byte
   212  }
   213  
   214  func createDirLink(link string, rdb *_REPARSE_DATA_BUFFER) error {
   215  	err := os.Mkdir(link, 0777)
   216  	if err != nil {
   217  		return err
   218  	}
   219  
   220  	linkp := syscall.StringToUTF16(link)
   221  	fd, err := syscall.CreateFile(&linkp[0], syscall.GENERIC_WRITE, 0, nil, syscall.OPEN_EXISTING,
   222  		syscall.FILE_FLAG_OPEN_REPARSE_POINT|syscall.FILE_FLAG_BACKUP_SEMANTICS, 0)
   223  	if err != nil {
   224  		return err
   225  	}
   226  	defer syscall.CloseHandle(fd)
   227  
   228  	return setReparsePoint(fd, rdb)
   229  }
   230  
   231  func setReparsePoint(fd syscall.Handle, rdb *_REPARSE_DATA_BUFFER) error {
   232  	buflen := uint32(rdb.header.ReparseDataLength) + uint32(unsafe.Sizeof(rdb.header))
   233  	var bytesReturned uint32
   234  	return syscall.DeviceIoControl(fd, windows.FSCTL_SET_REPARSE_POINT,
   235  		(*byte)(unsafe.Pointer(&rdb.header)), buflen, nil, 0, &bytesReturned, nil)
   236  }
   237  
   238  func createMountPoint(link string, target *reparseData) error {
   239  	var buf *windows.MountPointReparseBuffer
   240  	buflen := uint16(unsafe.Offsetof(buf.PathBuffer)) + target.pathBuffeLen() // see ReparseDataLength documentation
   241  	byteblob := make([]byte, buflen)
   242  	buf = (*windows.MountPointReparseBuffer)(unsafe.Pointer(&byteblob[0]))
   243  	buf.SubstituteNameOffset = target.substituteName.offset
   244  	buf.SubstituteNameLength = target.substituteName.length
   245  	buf.PrintNameOffset = target.printName.offset
   246  	buf.PrintNameLength = target.printName.length
   247  	pbuflen := len(target.pathBuf)
   248  	copy((*[2048]uint16)(unsafe.Pointer(&buf.PathBuffer[0]))[:pbuflen:pbuflen], target.pathBuf)
   249  
   250  	var rdb _REPARSE_DATA_BUFFER
   251  	rdb.header.ReparseTag = windows.IO_REPARSE_TAG_MOUNT_POINT
   252  	rdb.header.ReparseDataLength = buflen
   253  	copy(rdb.detail[:], byteblob)
   254  
   255  	return createDirLink(link, &rdb)
   256  }
   257  
   258  func TestDirectoryJunction(t *testing.T) {
   259  	var tests = []dirLinkTest{
   260  		{
   261  			// Create link similar to what mklink does, by inserting \??\ at the front of absolute target.
   262  			name:         "standard",
   263  			isMountPoint: true,
   264  			mklink: func(link, target string) error {
   265  				var t reparseData
   266  				t.addSubstituteName(`\??\` + target)
   267  				t.addPrintName(target)
   268  				return createMountPoint(link, &t)
   269  			},
   270  		},
   271  		{
   272  			// Do as junction utility https://learn.microsoft.com/en-us/sysinternals/downloads/junction does - set PrintNameLength to 0.
   273  			name:         "have_blank_print_name",
   274  			isMountPoint: true,
   275  			mklink: func(link, target string) error {
   276  				var t reparseData
   277  				t.addSubstituteName(`\??\` + target)
   278  				t.addPrintName("")
   279  				return createMountPoint(link, &t)
   280  			},
   281  		},
   282  	}
   283  	output, _ := testenv.Command(t, "cmd", "/c", "mklink", "/?").Output()
   284  	mklinkSupportsJunctionLinks := strings.Contains(string(output), " /J ")
   285  	if mklinkSupportsJunctionLinks {
   286  		tests = append(tests,
   287  			dirLinkTest{
   288  				name:         "use_mklink_cmd",
   289  				isMountPoint: true,
   290  				mklink: func(link, target string) error {
   291  					output, err := testenv.Command(t, "cmd", "/c", "mklink", "/J", link, target).CombinedOutput()
   292  					if err != nil {
   293  						t.Errorf("failed to run mklink %v %v: %v %q", link, target, err, output)
   294  					}
   295  					return nil
   296  				},
   297  			},
   298  		)
   299  	} else {
   300  		t.Log(`skipping "use_mklink_cmd" test, mklink does not supports directory junctions`)
   301  	}
   302  	testDirLinks(t, tests)
   303  }
   304  
   305  func enableCurrentThreadPrivilege(privilegeName string) error {
   306  	ct, err := windows.GetCurrentThread()
   307  	if err != nil {
   308  		return err
   309  	}
   310  	var t syscall.Token
   311  	err = windows.OpenThreadToken(ct, syscall.TOKEN_QUERY|windows.TOKEN_ADJUST_PRIVILEGES, false, &t)
   312  	if err != nil {
   313  		return err
   314  	}
   315  	defer syscall.CloseHandle(syscall.Handle(t))
   316  
   317  	var tp windows.TOKEN_PRIVILEGES
   318  
   319  	privStr, err := syscall.UTF16PtrFromString(privilegeName)
   320  	if err != nil {
   321  		return err
   322  	}
   323  	err = windows.LookupPrivilegeValue(nil, privStr, &tp.Privileges[0].Luid)
   324  	if err != nil {
   325  		return err
   326  	}
   327  	tp.PrivilegeCount = 1
   328  	tp.Privileges[0].Attributes = windows.SE_PRIVILEGE_ENABLED
   329  	return windows.AdjustTokenPrivileges(t, false, &tp, 0, nil, nil)
   330  }
   331  
   332  func createSymbolicLink(link string, target *reparseData, isrelative bool) error {
   333  	var buf *windows.SymbolicLinkReparseBuffer
   334  	buflen := uint16(unsafe.Offsetof(buf.PathBuffer)) + target.pathBuffeLen() // see ReparseDataLength documentation
   335  	byteblob := make([]byte, buflen)
   336  	buf = (*windows.SymbolicLinkReparseBuffer)(unsafe.Pointer(&byteblob[0]))
   337  	buf.SubstituteNameOffset = target.substituteName.offset
   338  	buf.SubstituteNameLength = target.substituteName.length
   339  	buf.PrintNameOffset = target.printName.offset
   340  	buf.PrintNameLength = target.printName.length
   341  	if isrelative {
   342  		buf.Flags = windows.SYMLINK_FLAG_RELATIVE
   343  	}
   344  	pbuflen := len(target.pathBuf)
   345  	copy((*[2048]uint16)(unsafe.Pointer(&buf.PathBuffer[0]))[:pbuflen:pbuflen], target.pathBuf)
   346  
   347  	var rdb _REPARSE_DATA_BUFFER
   348  	rdb.header.ReparseTag = syscall.IO_REPARSE_TAG_SYMLINK
   349  	rdb.header.ReparseDataLength = buflen
   350  	copy(rdb.detail[:], byteblob)
   351  
   352  	return createDirLink(link, &rdb)
   353  }
   354  
   355  func TestDirectorySymbolicLink(t *testing.T) {
   356  	var tests []dirLinkTest
   357  	output, _ := testenv.Command(t, "cmd", "/c", "mklink", "/?").Output()
   358  	mklinkSupportsDirectorySymbolicLinks := strings.Contains(string(output), " /D ")
   359  	if mklinkSupportsDirectorySymbolicLinks {
   360  		tests = append(tests,
   361  			dirLinkTest{
   362  				name: "use_mklink_cmd",
   363  				mklink: func(link, target string) error {
   364  					output, err := testenv.Command(t, "cmd", "/c", "mklink", "/D", link, target).CombinedOutput()
   365  					if err != nil {
   366  						t.Errorf("failed to run mklink %v %v: %v %q", link, target, err, output)
   367  					}
   368  					return nil
   369  				},
   370  			},
   371  		)
   372  	} else {
   373  		t.Log(`skipping "use_mklink_cmd" test, mklink does not supports directory symbolic links`)
   374  	}
   375  
   376  	// The rest of these test requires SeCreateSymbolicLinkPrivilege to be held.
   377  	runtime.LockOSThread()
   378  	defer runtime.UnlockOSThread()
   379  
   380  	err := windows.ImpersonateSelf(windows.SecurityImpersonation)
   381  	if err != nil {
   382  		t.Fatal(err)
   383  	}
   384  	defer windows.RevertToSelf()
   385  
   386  	err = enableCurrentThreadPrivilege("SeCreateSymbolicLinkPrivilege")
   387  	if err != nil {
   388  		t.Skipf(`skipping some tests, could not enable "SeCreateSymbolicLinkPrivilege": %v`, err)
   389  	}
   390  	tests = append(tests,
   391  		dirLinkTest{
   392  			name: "use_os_pkg",
   393  			mklink: func(link, target string) error {
   394  				return os.Symlink(target, link)
   395  			},
   396  		},
   397  		dirLinkTest{
   398  			// Create link similar to what mklink does, by inserting \??\ at the front of absolute target.
   399  			name: "standard",
   400  			mklink: func(link, target string) error {
   401  				var t reparseData
   402  				t.addPrintName(target)
   403  				t.addSubstituteName(`\??\` + target)
   404  				return createSymbolicLink(link, &t, false)
   405  			},
   406  		},
   407  		dirLinkTest{
   408  			name: "relative",
   409  			mklink: func(link, target string) error {
   410  				var t reparseData
   411  				t.addSubstituteNameNoNUL(filepath.Base(target))
   412  				t.addPrintNameNoNUL(filepath.Base(target))
   413  				return createSymbolicLink(link, &t, true)
   414  			},
   415  		},
   416  	)
   417  	testDirLinks(t, tests)
   418  }
   419  
   420  func mustHaveWorkstation(t *testing.T) {
   421  	mar, err := windows.OpenSCManager(nil, nil, windows.SERVICE_QUERY_STATUS)
   422  	if err != nil {
   423  		return
   424  	}
   425  	defer syscall.CloseHandle(mar)
   426  	//LanmanWorkstation is the service name, and Workstation is the display name.
   427  	srv, err := windows.OpenService(mar, syscall.StringToUTF16Ptr("LanmanWorkstation"), windows.SERVICE_QUERY_STATUS)
   428  	if err != nil {
   429  		return
   430  	}
   431  	defer syscall.CloseHandle(srv)
   432  	var state windows.SERVICE_STATUS
   433  	err = windows.QueryServiceStatus(srv, &state)
   434  	if err != nil {
   435  		return
   436  	}
   437  	if state.CurrentState != windows.SERVICE_RUNNING {
   438  		t.Skip("Requires the Windows service Workstation, but it is detected that it is not enabled.")
   439  	}
   440  }
   441  
   442  func TestNetworkSymbolicLink(t *testing.T) {
   443  	testenv.MustHaveSymlink(t)
   444  
   445  	const _NERR_ServerNotStarted = syscall.Errno(2114)
   446  
   447  	dir := t.TempDir()
   448  	t.Chdir(dir)
   449  
   450  	pid := os.Getpid()
   451  	shareName := fmt.Sprintf("GoSymbolicLinkTestShare%d", pid)
   452  	sharePath := filepath.Join(dir, shareName)
   453  	testDir := "TestDir"
   454  
   455  	err := os.MkdirAll(filepath.Join(sharePath, testDir), 0777)
   456  	if err != nil {
   457  		t.Fatal(err)
   458  	}
   459  
   460  	wShareName, err := syscall.UTF16PtrFromString(shareName)
   461  	if err != nil {
   462  		t.Fatal(err)
   463  	}
   464  	wSharePath, err := syscall.UTF16PtrFromString(sharePath)
   465  	if err != nil {
   466  		t.Fatal(err)
   467  	}
   468  
   469  	// Per https://learn.microsoft.com/en-us/windows/win32/api/lmshare/ns-lmshare-share_info_2:
   470  	//
   471  	// “[The shi2_permissions field] indicates the shared resource's permissions
   472  	// for servers running with share-level security. A server running user-level
   473  	// security ignores this member.
   474  	// …
   475  	// Note that Windows does not support share-level security.”
   476  	//
   477  	// So it shouldn't matter what permissions we set here.
   478  	const permissions = 0
   479  
   480  	p := windows.SHARE_INFO_2{
   481  		Netname:     wShareName,
   482  		Type:        windows.STYPE_DISKTREE | windows.STYPE_TEMPORARY,
   483  		Remark:      nil,
   484  		Permissions: permissions,
   485  		MaxUses:     1,
   486  		CurrentUses: 0,
   487  		Path:        wSharePath,
   488  		Passwd:      nil,
   489  	}
   490  
   491  	err = windows.NetShareAdd(nil, 2, (*byte)(unsafe.Pointer(&p)), nil)
   492  	if err != nil {
   493  		if err == syscall.ERROR_ACCESS_DENIED || err == _NERR_ServerNotStarted {
   494  			t.Skipf("skipping: NetShareAdd: %v", err)
   495  		}
   496  		t.Fatal(err)
   497  	}
   498  	defer func() {
   499  		err := windows.NetShareDel(nil, wShareName, 0)
   500  		if err != nil {
   501  			t.Fatal(err)
   502  		}
   503  	}()
   504  
   505  	UNCPath := `\\localhost\` + shareName + `\`
   506  
   507  	fi1, err := os.Stat(sharePath)
   508  	if err != nil {
   509  		t.Fatal(err)
   510  	}
   511  	fi2, err := os.Stat(UNCPath)
   512  	if err != nil {
   513  		mustHaveWorkstation(t)
   514  		t.Fatal(err)
   515  	}
   516  	if !os.SameFile(fi1, fi2) {
   517  		t.Fatalf("%q and %q should be the same directory, but not", sharePath, UNCPath)
   518  	}
   519  
   520  	target := filepath.Join(UNCPath, testDir)
   521  	link := "link"
   522  
   523  	err = os.Symlink(target, link)
   524  	if err != nil {
   525  		t.Fatal(err)
   526  	}
   527  	defer os.Remove(link)
   528  
   529  	got, err := os.Readlink(link)
   530  	if err != nil {
   531  		t.Fatal(err)
   532  	}
   533  	if got != target {
   534  		t.Errorf(`os.Readlink(%#q): got %v, want %v`, link, got, target)
   535  	}
   536  
   537  	got, err = filepath.EvalSymlinks(link)
   538  	if err != nil {
   539  		t.Fatal(err)
   540  	}
   541  	if got != target {
   542  		t.Errorf(`filepath.EvalSymlinks(%#q): got %v, want %v`, link, got, target)
   543  	}
   544  }
   545  
   546  func TestStatLxSymLink(t *testing.T) {
   547  	tmpdir := t.TempDir()
   548  	const target = "target"
   549  	if err := os.Mkdir(filepath.Join(tmpdir, target), 0777); err != nil {
   550  		t.Fatal(err)
   551  	}
   552  
   553  	link := filepath.Join(tmpdir, "link")
   554  	f, err := os.Create(link)
   555  	if err != nil {
   556  		t.Fatal(err)
   557  	}
   558  	defer f.Close()
   559  
   560  	// Create the reparse point directly so the test doesn't depend on WSL.
   561  	// Version 1 stores the UTF-8 link target in the file data.
   562  	const IO_REPARSE_TAG_LX_SYMLINK = 0xA000001D
   563  	var rdb _REPARSE_DATA_BUFFER
   564  	rdb.header.ReparseTag = IO_REPARSE_TAG_LX_SYMLINK
   565  	rdb.header.ReparseDataLength = 4
   566  	rdb.detail[0] = 1
   567  	if err := setReparsePoint(syscall.Handle(f.Fd()), &rdb); err != nil {
   568  		t.Fatal(err)
   569  	}
   570  	if _, err := f.WriteString(target); err != nil {
   571  		t.Fatal(err)
   572  	}
   573  	if err := f.Close(); err != nil {
   574  		t.Fatal(err)
   575  	}
   576  
   577  	fi, err := os.Lstat(link)
   578  	if err != nil {
   579  		t.Fatal(err)
   580  	}
   581  	if m := fi.Mode(); m&fs.ModeSymlink != 0 {
   582  		t.Fatalf("os.Lstat(%q).Mode() = %v, want ModeSymlink unset", link, m)
   583  	}
   584  	// Stat'ing an IO_REPARSE_TAG_LX_SYMLINK from outside WSL always returns ERROR_CANT_ACCESS_FILE.
   585  	// We check this condition to validate that os.Stat has tried to follow the link.
   586  	_, err = os.Stat(link)
   587  	const ERROR_CANT_ACCESS_FILE = syscall.Errno(1920)
   588  	if err == nil || !errors.Is(err, ERROR_CANT_ACCESS_FILE) {
   589  		t.Fatalf("os.Stat(%q): got %v, want ERROR_CANT_ACCESS_FILE", link, err)
   590  	}
   591  }
   592  
   593  func TestStartProcessAttr(t *testing.T) {
   594  	t.Parallel()
   595  
   596  	p, err := os.StartProcess(os.Getenv("COMSPEC"), []string{"/c", "cd"}, new(os.ProcAttr))
   597  	if err != nil {
   598  		return
   599  	}
   600  	defer p.Wait()
   601  	t.Fatalf("StartProcess expected to fail, but succeeded.")
   602  }
   603  
   604  func TestShareNotExistError(t *testing.T) {
   605  	if testing.Short() {
   606  		t.Skip("slow test that uses network; skipping")
   607  	}
   608  	t.Parallel()
   609  
   610  	_, err := os.Stat(`\\no_such_server\no_such_share\no_such_file`)
   611  	if err == nil {
   612  		t.Fatal("stat succeeded, but expected to fail")
   613  	}
   614  	if !os.IsNotExist(err) {
   615  		t.Fatalf("os.Stat failed with %q, but os.IsNotExist(err) is false", err)
   616  	}
   617  }
   618  
   619  func TestBadNetPathError(t *testing.T) {
   620  	const ERROR_BAD_NETPATH = syscall.Errno(53)
   621  	if !os.IsNotExist(ERROR_BAD_NETPATH) {
   622  		t.Fatal("os.IsNotExist(syscall.Errno(53)) is false, but want true")
   623  	}
   624  }
   625  
   626  func TestStatDir(t *testing.T) {
   627  	t.Chdir(t.TempDir())
   628  
   629  	f, err := os.Open(".")
   630  	if err != nil {
   631  		t.Fatal(err)
   632  	}
   633  	defer f.Close()
   634  
   635  	fi, err := f.Stat()
   636  	if err != nil {
   637  		t.Fatal(err)
   638  	}
   639  
   640  	err = os.Chdir("..")
   641  	if err != nil {
   642  		t.Fatal(err)
   643  	}
   644  
   645  	fi2, err := f.Stat()
   646  	if err != nil {
   647  		t.Fatal(err)
   648  	}
   649  
   650  	if !os.SameFile(fi, fi2) {
   651  		t.Fatal("race condition occurred")
   652  	}
   653  }
   654  
   655  func TestOpenVolumeName(t *testing.T) {
   656  	tmpdir := t.TempDir()
   657  	t.Chdir(tmpdir)
   658  
   659  	want := []string{"file1", "file2", "file3", "gopher.txt"}
   660  	slices.Sort(want)
   661  	for _, name := range want {
   662  		err := os.WriteFile(filepath.Join(tmpdir, name), nil, 0777)
   663  		if err != nil {
   664  			t.Fatal(err)
   665  		}
   666  	}
   667  
   668  	f, err := os.Open(filepath.VolumeName(tmpdir))
   669  	if err != nil {
   670  		t.Fatal(err)
   671  	}
   672  	defer f.Close()
   673  
   674  	have, err := f.Readdirnames(-1)
   675  	if err != nil {
   676  		t.Fatal(err)
   677  	}
   678  	slices.Sort(have)
   679  
   680  	if !slices.Equal(want, have) {
   681  		t.Fatalf("unexpected file list %q, want %q", have, want)
   682  	}
   683  }
   684  
   685  func TestDeleteReadOnly(t *testing.T) {
   686  	t.Parallel()
   687  
   688  	tmpdir := t.TempDir()
   689  	p := filepath.Join(tmpdir, "a")
   690  	// This sets FILE_ATTRIBUTE_READONLY.
   691  	f, err := os.OpenFile(p, os.O_CREATE, 0400)
   692  	if err != nil {
   693  		t.Fatal(err)
   694  	}
   695  	f.Close()
   696  
   697  	if err = os.Chmod(p, 0400); err != nil {
   698  		t.Fatal(err)
   699  	}
   700  	if err = os.Remove(p); err != nil {
   701  		t.Fatal(err)
   702  	}
   703  }
   704  
   705  func TestReadStdin(t *testing.T) {
   706  	old := poll.ReadConsole
   707  	defer func() {
   708  		poll.ReadConsole = old
   709  	}()
   710  
   711  	p, err := syscall.GetCurrentProcess()
   712  	if err != nil {
   713  		t.Fatalf("Unable to get handle to current process: %v", err)
   714  	}
   715  	var stdinDuplicate syscall.Handle
   716  	err = syscall.DuplicateHandle(p, syscall.Handle(syscall.Stdin), p, &stdinDuplicate, 0, false, syscall.DUPLICATE_SAME_ACCESS)
   717  	if err != nil {
   718  		t.Fatalf("Unable to duplicate stdin: %v", err)
   719  	}
   720  	testConsole := os.NewConsoleFile(stdinDuplicate, "test")
   721  
   722  	var tests = []string{
   723  		"abc",
   724  		"äöü",
   725  		"\u3042",
   726  		"“hi”™",
   727  		"hello\x1aworld",
   728  		"\U0001F648\U0001F649\U0001F64A",
   729  	}
   730  
   731  	for _, consoleSize := range []int{1, 2, 3, 10, 16, 100, 1000} {
   732  		for _, readSize := range []int{1, 2, 3, 4, 5, 8, 10, 16, 20, 50, 100} {
   733  			for _, s := range tests {
   734  				t.Run(fmt.Sprintf("c%d/r%d/%s", consoleSize, readSize, s), func(t *testing.T) {
   735  					s16 := utf16.Encode([]rune(s))
   736  					poll.ReadConsole = func(h syscall.Handle, buf *uint16, toread uint32, read *uint32, inputControl *byte) error {
   737  						if inputControl != nil {
   738  							t.Fatalf("inputControl not nil")
   739  						}
   740  						n := int(toread)
   741  						if n > consoleSize {
   742  							n = consoleSize
   743  						}
   744  						n = copy((*[10000]uint16)(unsafe.Pointer(buf))[:n:n], s16)
   745  						s16 = s16[n:]
   746  						*read = uint32(n)
   747  						t.Logf("read %d -> %d", toread, *read)
   748  						return nil
   749  					}
   750  
   751  					var all []string
   752  					var buf []byte
   753  					chunk := make([]byte, readSize)
   754  					for {
   755  						n, err := testConsole.Read(chunk)
   756  						buf = append(buf, chunk[:n]...)
   757  						if err == io.EOF {
   758  							all = append(all, string(buf))
   759  							if len(all) >= 5 {
   760  								break
   761  							}
   762  							buf = buf[:0]
   763  						} else if err != nil {
   764  							t.Fatalf("reading %q: error: %v", s, err)
   765  						}
   766  						if len(buf) >= 2000 {
   767  							t.Fatalf("reading %q: stuck in loop: %q", s, buf)
   768  						}
   769  					}
   770  
   771  					want := strings.Split(s, "\x1a")
   772  					for len(want) < 5 {
   773  						want = append(want, "")
   774  					}
   775  					if !slices.Equal(all, want) {
   776  						t.Errorf("reading %q:\nhave %x\nwant %x", s, all, want)
   777  					}
   778  				})
   779  			}
   780  		}
   781  	}
   782  }
   783  
   784  func TestStatPagefile(t *testing.T) {
   785  	t.Parallel()
   786  
   787  	const path = `c:\pagefile.sys`
   788  	fi, err := os.Stat(path)
   789  	if err == nil {
   790  		if fi.Name() == "" {
   791  			t.Fatalf("Stat(%q).Name() is empty", path)
   792  		}
   793  		t.Logf("Stat(%q).Size() = %v", path, fi.Size())
   794  		return
   795  	}
   796  	if os.IsNotExist(err) {
   797  		t.Skip(`skipping because c:\pagefile.sys is not found`)
   798  	}
   799  	t.Fatal(err)
   800  }
   801  
   802  // syscallCommandLineToArgv calls syscall.CommandLineToArgv
   803  // and converts returned result into []string.
   804  func syscallCommandLineToArgv(cmd string) ([]string, error) {
   805  	var argc int32
   806  	argv, err := syscall.CommandLineToArgv(&syscall.StringToUTF16(cmd)[0], &argc)
   807  	if err != nil {
   808  		return nil, err
   809  	}
   810  	defer syscall.LocalFree(syscall.Handle(uintptr(unsafe.Pointer(argv))))
   811  
   812  	var args []string
   813  	for _, v := range (*argv)[:argc] {
   814  		args = append(args, syscall.UTF16ToString((*v)[:]))
   815  	}
   816  	return args, nil
   817  }
   818  
   819  // compareCommandLineToArgvWithSyscall ensures that
   820  // os.CommandLineToArgv(cmd) and syscall.CommandLineToArgv(cmd)
   821  // return the same result.
   822  func compareCommandLineToArgvWithSyscall(t *testing.T, cmd string) {
   823  	syscallArgs, err := syscallCommandLineToArgv(cmd)
   824  	if err != nil {
   825  		t.Fatal(err)
   826  	}
   827  	args := os.CommandLineToArgv(cmd)
   828  	if want, have := fmt.Sprintf("%q", syscallArgs), fmt.Sprintf("%q", args); want != have {
   829  		t.Errorf("testing os.commandLineToArgv(%q) failed: have %q want %q", cmd, args, syscallArgs)
   830  		return
   831  	}
   832  }
   833  
   834  func TestCmdArgs(t *testing.T) {
   835  	if testing.Short() {
   836  		t.Skipf("in short mode; skipping test that builds a binary")
   837  	}
   838  	t.Parallel()
   839  
   840  	tmpdir := t.TempDir()
   841  
   842  	const prog = `
   843  package main
   844  
   845  import (
   846  	"fmt"
   847  	"os"
   848  )
   849  
   850  func main() {
   851  	fmt.Printf("%q", os.Args)
   852  }
   853  `
   854  	src := filepath.Join(tmpdir, "main.go")
   855  	if err := os.WriteFile(src, []byte(prog), 0666); err != nil {
   856  		t.Fatal(err)
   857  	}
   858  
   859  	exe := filepath.Join(tmpdir, "main.exe")
   860  	cmd := testenv.Command(t, testenv.GoToolPath(t), "build", "-o", exe, src)
   861  	cmd.Dir = tmpdir
   862  	out, err := cmd.CombinedOutput()
   863  	if err != nil {
   864  		t.Fatalf("building main.exe failed: %v\n%s", err, out)
   865  	}
   866  
   867  	var cmds = []string{
   868  		``,
   869  		` a b c`,
   870  		` "`,
   871  		` ""`,
   872  		` """`,
   873  		` "" a`,
   874  		` "123"`,
   875  		` \"123\"`,
   876  		` \"123 456\"`,
   877  		` \\"`,
   878  		` \\\"`,
   879  		` \\\\\"`,
   880  		` \\\"x`,
   881  		` """"\""\\\"`,
   882  		` abc`,
   883  		` \\\\\""x"""y z`,
   884  		"\tb\t\"x\ty\"",
   885  		` "Брад" d e`,
   886  		// examples from https://learn.microsoft.com/en-us/cpp/cpp/main-function-command-line-args
   887  		` "abc" d e`,
   888  		` a\\b d"e f"g h`,
   889  		` a\\\"b c d`,
   890  		` a\\\\"b c" d e`,
   891  		// http://daviddeley.com/autohotkey/parameters/parameters.htm#WINARGV
   892  		// from 5.4  Examples
   893  		` CallMeIshmael`,
   894  		` "Call Me Ishmael"`,
   895  		` Cal"l Me I"shmael`,
   896  		` CallMe\"Ishmael`,
   897  		` "CallMe\"Ishmael"`,
   898  		` "Call Me Ishmael\\"`,
   899  		` "CallMe\\\"Ishmael"`,
   900  		` a\\\b`,
   901  		` "a\\\b"`,
   902  		// from 5.5  Some Common Tasks
   903  		` "\"Call Me Ishmael\""`,
   904  		` "C:\TEST A\\"`,
   905  		` "\"C:\TEST A\\\""`,
   906  		// from 5.6  The Microsoft Examples Explained
   907  		` "a b c"  d  e`,
   908  		` "ab\"c"  "\\"  d`,
   909  		` a\\\b d"e f"g h`,
   910  		` a\\\"b c d`,
   911  		` a\\\\"b c" d e`,
   912  		// from 5.7  Double Double Quote Examples (pre 2008)
   913  		` "a b c""`,
   914  		` """CallMeIshmael"""  b  c`,
   915  		` """Call Me Ishmael"""`,
   916  		` """"Call Me Ishmael"" b c`,
   917  	}
   918  	for _, cmd := range cmds {
   919  		compareCommandLineToArgvWithSyscall(t, "test"+cmd)
   920  		compareCommandLineToArgvWithSyscall(t, `"cmd line"`+cmd)
   921  		compareCommandLineToArgvWithSyscall(t, exe+cmd)
   922  
   923  		// test both syscall.EscapeArg and os.commandLineToArgv
   924  		args := os.CommandLineToArgv(exe + cmd)
   925  		out, err := testenv.Command(t, args[0], args[1:]...).CombinedOutput()
   926  		if err != nil {
   927  			t.Fatalf("running %q failed: %v\n%v", args, err, string(out))
   928  		}
   929  		if want, have := fmt.Sprintf("%q", args), string(out); want != have {
   930  			t.Errorf("wrong output of executing %q: have %q want %q", args, have, want)
   931  			continue
   932  		}
   933  	}
   934  }
   935  
   936  func findOneDriveDir() (string, error) {
   937  	// as per https://stackoverflow.com/questions/42519624/how-to-determine-location-of-onedrive-on-windows-7-and-8-in-c
   938  	const onedrivekey = `SOFTWARE\Microsoft\OneDrive`
   939  	k, err := registry.OpenKey(registry.CURRENT_USER, onedrivekey, registry.READ)
   940  	if err != nil {
   941  		return "", fmt.Errorf("OpenKey(%q) failed: %v", onedrivekey, err)
   942  	}
   943  	defer k.Close()
   944  
   945  	path, valtype, err := k.GetStringValue("UserFolder")
   946  	if err != nil {
   947  		return "", fmt.Errorf("reading UserFolder failed: %v", err)
   948  	}
   949  
   950  	// REG_SZ values may also contain environment variables that need to be expanded.
   951  	// It's recommended but not required to use REG_EXPAND_SZ for paths that contain environment variables.
   952  	if valtype == registry.EXPAND_SZ || valtype == registry.SZ {
   953  		expanded, err := registry.ExpandString(path)
   954  		if err != nil {
   955  			return "", fmt.Errorf("expanding UserFolder failed: %v", err)
   956  		}
   957  		path = expanded
   958  	}
   959  
   960  	return path, nil
   961  }
   962  
   963  // TestOneDrive verifies that OneDrive folder is a directory and not a symlink.
   964  func TestOneDrive(t *testing.T) {
   965  	t.Parallel()
   966  
   967  	dir, err := findOneDriveDir()
   968  	if err != nil {
   969  		t.Skipf("Skipping, because we did not find OneDrive directory: %v", err)
   970  	}
   971  	testDirStats(t, dir)
   972  }
   973  
   974  func TestWindowsDevNullFile(t *testing.T) {
   975  	t.Parallel()
   976  
   977  	f1, err := os.Open("NUL")
   978  	if err != nil {
   979  		t.Fatal(err)
   980  	}
   981  	defer f1.Close()
   982  
   983  	fi1, err := f1.Stat()
   984  	if err != nil {
   985  		t.Fatal(err)
   986  	}
   987  
   988  	f2, err := os.Open("nul")
   989  	if err != nil {
   990  		t.Fatal(err)
   991  	}
   992  	defer f2.Close()
   993  
   994  	fi2, err := f2.Stat()
   995  	if err != nil {
   996  		t.Fatal(err)
   997  	}
   998  
   999  	if !os.SameFile(fi1, fi2) {
  1000  		t.Errorf(`"NUL" and "nul" are not the same file`)
  1001  	}
  1002  }
  1003  
  1004  func TestFileStatNUL(t *testing.T) {
  1005  	t.Parallel()
  1006  
  1007  	f, err := os.Open("NUL")
  1008  	if err != nil {
  1009  		t.Fatal(err)
  1010  	}
  1011  	defer f.Close()
  1012  
  1013  	fi, err := f.Stat()
  1014  	if err != nil {
  1015  		t.Fatal(err)
  1016  	}
  1017  	if got, want := fi.Mode(), os.ModeDevice|os.ModeCharDevice|0666; got != want {
  1018  		t.Errorf("Open(%q).Stat().Mode() = %v, want %v", "NUL", got, want)
  1019  	}
  1020  }
  1021  
  1022  func TestStatNUL(t *testing.T) {
  1023  	t.Parallel()
  1024  
  1025  	fi, err := os.Stat("NUL")
  1026  	if err != nil {
  1027  		t.Fatal(err)
  1028  	}
  1029  	if got, want := fi.Mode(), os.ModeDevice|os.ModeCharDevice|0666; got != want {
  1030  		t.Errorf("Stat(%q).Mode() = %v, want %v", "NUL", got, want)
  1031  	}
  1032  }
  1033  
  1034  // TestSymlinkCreation verifies that creating a symbolic link
  1035  // works on Windows when developer mode is active.
  1036  // This is supported starting Windows 10 (1703, v10.0.14972).
  1037  func TestSymlinkCreation(t *testing.T) {
  1038  	if !testenv.HasSymlink() {
  1039  		t.Skip("skipping test; no symlink support")
  1040  	}
  1041  	t.Parallel()
  1042  
  1043  	temp := t.TempDir()
  1044  	dummyFile := filepath.Join(temp, "file")
  1045  	if err := os.WriteFile(dummyFile, []byte(""), 0644); err != nil {
  1046  		t.Fatal(err)
  1047  	}
  1048  
  1049  	linkFile := filepath.Join(temp, "link")
  1050  	if err := os.Symlink(dummyFile, linkFile); err != nil {
  1051  		t.Fatal(err)
  1052  	}
  1053  }
  1054  
  1055  // TestRootRelativeDirSymlink verifies that symlinks to paths relative to the
  1056  // drive root (beginning with "\" but no volume name) are created with the
  1057  // correct symlink type.
  1058  // (See https://golang.org/issue/39183#issuecomment-632175728.)
  1059  func TestRootRelativeDirSymlink(t *testing.T) {
  1060  	testenv.MustHaveSymlink(t)
  1061  	t.Parallel()
  1062  
  1063  	temp := t.TempDir()
  1064  	dir := filepath.Join(temp, "dir")
  1065  	if err := os.Mkdir(dir, 0755); err != nil {
  1066  		t.Fatal(err)
  1067  	}
  1068  
  1069  	volumeRelDir := strings.TrimPrefix(dir, filepath.VolumeName(dir)) // leaves leading backslash
  1070  
  1071  	link := filepath.Join(temp, "link")
  1072  	err := os.Symlink(volumeRelDir, link)
  1073  	if err != nil {
  1074  		t.Fatal(err)
  1075  	}
  1076  	t.Logf("Symlink(%#q, %#q)", volumeRelDir, link)
  1077  
  1078  	f, err := os.Open(link)
  1079  	if err != nil {
  1080  		t.Fatal(err)
  1081  	}
  1082  	defer f.Close()
  1083  	if fi, err := f.Stat(); err != nil {
  1084  		t.Fatal(err)
  1085  	} else if !fi.IsDir() {
  1086  		t.Errorf("Open(%#q).Stat().IsDir() = false; want true", f.Name())
  1087  	}
  1088  }
  1089  
  1090  // TestWorkingDirectoryRelativeSymlink verifies that symlinks to paths relative
  1091  // to the current working directory for the drive, such as "C:File.txt", are
  1092  // correctly converted to absolute links of the correct symlink type (per
  1093  // https://docs.microsoft.com/en-us/windows/win32/fileio/creating-symbolic-links).
  1094  func TestWorkingDirectoryRelativeSymlink(t *testing.T) {
  1095  	testenv.MustHaveSymlink(t)
  1096  
  1097  	// Construct a directory to be symlinked.
  1098  	temp := t.TempDir()
  1099  	if v := filepath.VolumeName(temp); len(v) < 2 || v[1] != ':' {
  1100  		t.Skipf("Can't test relative symlinks: t.TempDir() (%#q) does not begin with a drive letter.", temp)
  1101  	}
  1102  
  1103  	absDir := filepath.Join(temp, `dir\sub`)
  1104  	if err := os.MkdirAll(absDir, 0755); err != nil {
  1105  		t.Fatal(err)
  1106  	}
  1107  
  1108  	// Change to the temporary directory and construct a
  1109  	// working-directory-relative symlink.
  1110  	oldwd, err := os.Getwd()
  1111  	if err != nil {
  1112  		t.Fatal(err)
  1113  	}
  1114  	t.Chdir(temp)
  1115  	t.Logf("Chdir(%#q)", temp)
  1116  
  1117  	wdRelDir := filepath.VolumeName(temp) + `dir\sub` // no backslash after volume.
  1118  	absLink := filepath.Join(temp, "link")
  1119  	err = os.Symlink(wdRelDir, absLink)
  1120  	if err != nil {
  1121  		t.Fatal(err)
  1122  	}
  1123  	t.Logf("Symlink(%#q, %#q)", wdRelDir, absLink)
  1124  
  1125  	// Now change back to the original working directory and verify that the
  1126  	// symlink still refers to its original path and is correctly marked as a
  1127  	// directory.
  1128  	if err := os.Chdir(oldwd); err != nil {
  1129  		t.Fatal(err)
  1130  	}
  1131  	t.Logf("Chdir(%#q)", oldwd)
  1132  
  1133  	resolved, err := os.Readlink(absLink)
  1134  	if err != nil {
  1135  		t.Errorf("Readlink(%#q): %v", absLink, err)
  1136  	} else if resolved != absDir {
  1137  		t.Errorf("Readlink(%#q) = %#q; want %#q", absLink, resolved, absDir)
  1138  	}
  1139  
  1140  	linkFile, err := os.Open(absLink)
  1141  	if err != nil {
  1142  		t.Fatal(err)
  1143  	}
  1144  	defer linkFile.Close()
  1145  
  1146  	linkInfo, err := linkFile.Stat()
  1147  	if err != nil {
  1148  		t.Fatal(err)
  1149  	}
  1150  	if !linkInfo.IsDir() {
  1151  		t.Errorf("Open(%#q).Stat().IsDir() = false; want true", absLink)
  1152  	}
  1153  
  1154  	absInfo, err := os.Stat(absDir)
  1155  	if err != nil {
  1156  		t.Fatal(err)
  1157  	}
  1158  
  1159  	if !os.SameFile(absInfo, linkInfo) {
  1160  		t.Errorf("SameFile(Stat(%#q), Open(%#q).Stat()) = false; want true", absDir, absLink)
  1161  	}
  1162  }
  1163  
  1164  // TestStatOfInvalidName is regression test for issue #24999.
  1165  func TestStatOfInvalidName(t *testing.T) {
  1166  	t.Parallel()
  1167  
  1168  	_, err := os.Stat("*.go")
  1169  	if err == nil {
  1170  		t.Fatal(`os.Stat("*.go") unexpectedly succeeded`)
  1171  	}
  1172  }
  1173  
  1174  // findUnusedDriveLetter searches mounted drive list on the system
  1175  // (starting from Z: and ending at D:) for unused drive letter.
  1176  // It returns path to the found drive root directory (like Z:\) or error.
  1177  func findUnusedDriveLetter() (string, error) {
  1178  	// Do not use A: and B:, because they are reserved for floppy drive.
  1179  	// Do not use C:, because it is normally used for main drive.
  1180  	for l := 'Z'; l >= 'D'; l-- {
  1181  		p := string(l) + `:\`
  1182  		_, err := os.Stat(p)
  1183  		if os.IsNotExist(err) {
  1184  			return p, nil
  1185  		}
  1186  	}
  1187  	return "", errors.New("Could not find unused drive letter.")
  1188  }
  1189  
  1190  func TestRootDirAsTemp(t *testing.T) {
  1191  	if os.Getenv("GO_WANT_HELPER_PROCESS") == "1" {
  1192  		fmt.Print(os.TempDir())
  1193  		os.Exit(0)
  1194  	}
  1195  
  1196  	testenv.MustHaveExec(t)
  1197  	t.Parallel()
  1198  
  1199  	exe := testenv.Executable(t)
  1200  
  1201  	newtmp, err := findUnusedDriveLetter()
  1202  	if err != nil {
  1203  		t.Skip(err)
  1204  	}
  1205  
  1206  	cmd := testenv.Command(t, exe, "-test.run=^TestRootDirAsTemp$")
  1207  	cmd.Env = cmd.Environ()
  1208  	cmd.Env = append(cmd.Env, "GO_WANT_HELPER_PROCESS=1")
  1209  	cmd.Env = append(cmd.Env, "TMP="+newtmp)
  1210  	cmd.Env = append(cmd.Env, "TEMP="+newtmp)
  1211  	output, err := cmd.CombinedOutput()
  1212  	if err != nil {
  1213  		t.Fatalf("Failed to spawn child process: %v %q", err, string(output))
  1214  	}
  1215  	if want, have := newtmp, string(output); have != want {
  1216  		t.Fatalf("unexpected child process output %q, want %q", have, want)
  1217  	}
  1218  }
  1219  
  1220  // replaceDriveWithVolumeID returns path with its volume name replaced with
  1221  // the mounted volume ID. E.g. C:\foo -> \\?\Volume{GUID}\foo.
  1222  func replaceDriveWithVolumeID(t *testing.T, path string) string {
  1223  	t.Helper()
  1224  	cmd := testenv.Command(t, "cmd", "/c", "mountvol", filepath.VolumeName(path), "/L")
  1225  	out, err := cmd.CombinedOutput()
  1226  	if err != nil {
  1227  		t.Fatalf("%v: %v\n%s", cmd, err, out)
  1228  	}
  1229  	vol := strings.Trim(string(out), " \n\r")
  1230  	return filepath.Join(vol, path[len(filepath.VolumeName(path)):])
  1231  }
  1232  
  1233  func TestReadlink(t *testing.T) {
  1234  	tests := []struct {
  1235  		junction bool
  1236  		dir      bool
  1237  		drive    bool
  1238  		relative bool
  1239  	}{
  1240  		{junction: true, dir: true, drive: true, relative: false},
  1241  		{junction: true, dir: true, drive: false, relative: false},
  1242  		{junction: true, dir: true, drive: false, relative: true},
  1243  		{junction: false, dir: true, drive: true, relative: false},
  1244  		{junction: false, dir: true, drive: false, relative: false},
  1245  		{junction: false, dir: true, drive: false, relative: true},
  1246  		{junction: false, dir: false, drive: true, relative: false},
  1247  		{junction: false, dir: false, drive: false, relative: false},
  1248  		{junction: false, dir: false, drive: false, relative: true},
  1249  	}
  1250  	for _, tt := range tests {
  1251  		tt := tt
  1252  		var name string
  1253  		if tt.junction {
  1254  			name = "junction"
  1255  		} else {
  1256  			name = "symlink"
  1257  		}
  1258  		if tt.dir {
  1259  			name += "_dir"
  1260  		} else {
  1261  			name += "_file"
  1262  		}
  1263  		if tt.drive {
  1264  			name += "_drive"
  1265  		} else {
  1266  			name += "_volume"
  1267  		}
  1268  		if tt.relative {
  1269  			name += "_relative"
  1270  		} else {
  1271  			name += "_absolute"
  1272  		}
  1273  
  1274  		t.Run(name, func(t *testing.T) {
  1275  			if !tt.junction {
  1276  				testenv.MustHaveSymlink(t)
  1277  			}
  1278  			if !tt.relative {
  1279  				t.Parallel()
  1280  			}
  1281  			// Make sure tmpdir is not a symlink, otherwise tests will fail.
  1282  			tmpdir, err := filepath.EvalSymlinks(t.TempDir())
  1283  			if err != nil {
  1284  				t.Fatal(err)
  1285  			}
  1286  			link := filepath.Join(tmpdir, "link")
  1287  			target := filepath.Join(tmpdir, "target")
  1288  			if tt.dir {
  1289  				if err := os.MkdirAll(target, 0777); err != nil {
  1290  					t.Fatal(err)
  1291  				}
  1292  			} else {
  1293  				if err := os.WriteFile(target, nil, 0666); err != nil {
  1294  					t.Fatal(err)
  1295  				}
  1296  			}
  1297  			var want string
  1298  			if tt.relative {
  1299  				relTarget := filepath.Base(target)
  1300  				if tt.junction {
  1301  					want = target // relative directory junction resolves to absolute path
  1302  				} else {
  1303  					want = relTarget
  1304  				}
  1305  				t.Chdir(tmpdir)
  1306  				link = filepath.Base(link)
  1307  				target = relTarget
  1308  			} else {
  1309  				if tt.drive {
  1310  					want = target
  1311  				} else {
  1312  					volTarget := replaceDriveWithVolumeID(t, target)
  1313  					if winreadlinkvolume.Value() == "0" {
  1314  						want = target
  1315  					} else {
  1316  						want = volTarget
  1317  					}
  1318  					target = volTarget
  1319  				}
  1320  			}
  1321  			if tt.junction {
  1322  				cmd := testenv.Command(t, "cmd", "/c", "mklink", "/J", link, target)
  1323  				if out, err := cmd.CombinedOutput(); err != nil {
  1324  					t.Fatalf("%v: %v\n%s", cmd, err, out)
  1325  				}
  1326  			} else {
  1327  				if err := os.Symlink(target, link); err != nil {
  1328  					t.Fatalf("Symlink(%#q, %#q): %v", target, link, err)
  1329  				}
  1330  			}
  1331  			got, err := os.Readlink(link)
  1332  			if err != nil {
  1333  				t.Fatal(err)
  1334  			}
  1335  			if got != want {
  1336  				t.Fatalf("Readlink(%#q) = %#q; want %#q", target, got, want)
  1337  			}
  1338  		})
  1339  	}
  1340  }
  1341  
  1342  func TestOpenDirTOCTOU(t *testing.T) {
  1343  	t.Parallel()
  1344  
  1345  	// Check opened directories can't be renamed until the handle is closed.
  1346  	// See issue 52747.
  1347  	tmpdir := t.TempDir()
  1348  	dir := filepath.Join(tmpdir, "dir")
  1349  	if err := os.Mkdir(dir, 0777); err != nil {
  1350  		t.Fatal(err)
  1351  	}
  1352  	f, err := os.Open(dir)
  1353  	if err != nil {
  1354  		t.Fatal(err)
  1355  	}
  1356  	newpath := filepath.Join(tmpdir, "dir1")
  1357  	err = os.Rename(dir, newpath)
  1358  	if err == nil || !errors.Is(err, windows.ERROR_SHARING_VIOLATION) {
  1359  		f.Close()
  1360  		t.Fatalf("Rename(%q, %q) = %v; want windows.ERROR_SHARING_VIOLATION", dir, newpath, err)
  1361  	}
  1362  	f.Close()
  1363  	err = os.Rename(dir, newpath)
  1364  	if err != nil {
  1365  		t.Error(err)
  1366  	}
  1367  }
  1368  
  1369  func TestAppExecLinkStat(t *testing.T) {
  1370  	// We expect executables installed to %LOCALAPPDATA%\Microsoft\WindowsApps to
  1371  	// be reparse points with tag IO_REPARSE_TAG_APPEXECLINK. Here we check that
  1372  	// such reparse points are treated as irregular (but executable) files, not
  1373  	// broken symlinks.
  1374  	appdata := os.Getenv("LOCALAPPDATA")
  1375  	if appdata == "" {
  1376  		t.Skipf("skipping: LOCALAPPDATA not set")
  1377  	}
  1378  
  1379  	pythonExeName := "python3.exe"
  1380  	pythonPath := filepath.Join(appdata, `Microsoft\WindowsApps`, pythonExeName)
  1381  
  1382  	lfi, err := os.Lstat(pythonPath)
  1383  	if err != nil {
  1384  		t.Skip("skipping test, because Python 3 is not installed via the Windows App Store on this system; see https://golang.org/issue/42919")
  1385  	}
  1386  
  1387  	// An APPEXECLINK reparse point is not a symlink, so os.Readlink should return
  1388  	// a non-nil error for it, and Stat should return results identical to Lstat.
  1389  	linkName, err := os.Readlink(pythonPath)
  1390  	if err == nil {
  1391  		t.Errorf("os.Readlink(%q) = %q, but expected an error\n(should be an APPEXECLINK reparse point, not a symlink)", pythonPath, linkName)
  1392  	}
  1393  
  1394  	sfi, err := os.Stat(pythonPath)
  1395  	if err != nil {
  1396  		t.Fatalf("Stat %s: %v", pythonPath, err)
  1397  	}
  1398  
  1399  	if lfi.Name() != sfi.Name() {
  1400  		t.Logf("os.Lstat(%q) = %+v", pythonPath, lfi)
  1401  		t.Logf("os.Stat(%q)  = %+v", pythonPath, sfi)
  1402  		t.Errorf("files should be same")
  1403  	}
  1404  
  1405  	if lfi.Name() != pythonExeName {
  1406  		t.Errorf("Stat %s: got %q, but wanted %q", pythonPath, lfi.Name(), pythonExeName)
  1407  	}
  1408  	if tp := lfi.Mode().Type(); tp != fs.ModeIrregular {
  1409  		// A reparse point is not a regular file, but we don't have a more appropriate
  1410  		// ModeType bit for it, so it should be marked as irregular.
  1411  		t.Errorf("%q should not be a an irregular file (mode=0x%x)", pythonPath, uint32(tp))
  1412  	}
  1413  
  1414  	if sfi.Name() != pythonExeName {
  1415  		t.Errorf("Stat %s: got %q, but wanted %q", pythonPath, sfi.Name(), pythonExeName)
  1416  	}
  1417  	if m := sfi.Mode(); m&fs.ModeSymlink != 0 {
  1418  		t.Errorf("%q should be a file, not a link (mode=0x%x)", pythonPath, uint32(m))
  1419  	}
  1420  	if m := sfi.Mode(); m&fs.ModeDir != 0 {
  1421  		t.Errorf("%q should be a file, not a directory (mode=0x%x)", pythonPath, uint32(m))
  1422  	}
  1423  	if m := sfi.Mode(); m&fs.ModeIrregular == 0 {
  1424  		// A reparse point is not a regular file, but we don't have a more appropriate
  1425  		// ModeType bit for it, so it should be marked as irregular.
  1426  		t.Errorf("%q should not be a regular file (mode=0x%x)", pythonPath, uint32(m))
  1427  	}
  1428  
  1429  	p, err := exec.LookPath(pythonPath)
  1430  	if err != nil {
  1431  		t.Errorf("exec.LookPath(%q): %v", pythonPath, err)
  1432  	}
  1433  	if p != pythonPath {
  1434  		t.Errorf("exec.LookPath(%q) = %q; want %q", pythonPath, p, pythonPath)
  1435  	}
  1436  }
  1437  
  1438  func TestIllformedUTF16FileName(t *testing.T) {
  1439  	dir := t.TempDir()
  1440  	const sep = string(os.PathSeparator)
  1441  	if !strings.HasSuffix(dir, sep) {
  1442  		dir += sep
  1443  	}
  1444  
  1445  	// This UTF-16 file name is ill-formed as it contains low surrogates that are not preceded by high surrogates ([1:5]).
  1446  	namew := []uint16{0x2e, 0xdc6d, 0xdc73, 0xdc79, 0xdc73, 0x30, 0x30, 0x30, 0x31, 0}
  1447  
  1448  	// Create a file whose name contains unpaired surrogates.
  1449  	// Use syscall.CreateFile instead of os.Create to simulate a file that is created by
  1450  	// a non-Go program so the file name hasn't gone through syscall.UTF16FromString.
  1451  	dirw := utf16.Encode([]rune(dir))
  1452  	pathw := append(dirw, namew...)
  1453  	fd, err := syscall.CreateFile(&pathw[0], syscall.GENERIC_ALL, 0, nil, syscall.CREATE_NEW, 0, 0)
  1454  	if err != nil {
  1455  		t.Fatal(err)
  1456  	}
  1457  	syscall.CloseHandle(fd)
  1458  
  1459  	name := syscall.UTF16ToString(namew)
  1460  	path := filepath.Join(dir, name)
  1461  	// Verify that os.Lstat can query the file.
  1462  	fi, err := os.Lstat(path)
  1463  	if err != nil {
  1464  		t.Fatal(err)
  1465  	}
  1466  	if got := fi.Name(); got != name {
  1467  		t.Errorf("got %q, want %q", got, name)
  1468  	}
  1469  	// Verify that File.Readdirnames lists the file.
  1470  	f, err := os.Open(dir)
  1471  	if err != nil {
  1472  		t.Fatal(err)
  1473  	}
  1474  	files, err := f.Readdirnames(0)
  1475  	f.Close()
  1476  	if err != nil {
  1477  		t.Fatal(err)
  1478  	}
  1479  	if !slices.Contains(files, name) {
  1480  		t.Error("file not listed")
  1481  	}
  1482  	// Verify that os.RemoveAll can remove the directory
  1483  	// and that it doesn't hang.
  1484  	err = os.RemoveAll(dir)
  1485  	if err != nil {
  1486  		t.Error(err)
  1487  	}
  1488  }
  1489  
  1490  func TestUTF16Alloc(t *testing.T) {
  1491  	allocsPerRun := func(want int, f func()) {
  1492  		t.Helper()
  1493  		got := int(testing.AllocsPerRun(5, f))
  1494  		if got != want {
  1495  			t.Errorf("got %d allocs, want %d", got, want)
  1496  		}
  1497  	}
  1498  	allocsPerRun(1, func() {
  1499  		syscall.UTF16ToString([]uint16{'a', 'b', 'c'})
  1500  	})
  1501  	want := 0
  1502  	if testenv.OptimizationOff() {
  1503  		want = 1
  1504  	}
  1505  	allocsPerRun(want, func() {
  1506  		syscall.UTF16FromString("abc")
  1507  	})
  1508  }
  1509  
  1510  func TestNewFileInvalid(t *testing.T) {
  1511  	t.Parallel()
  1512  	if f := os.NewFile(uintptr(syscall.InvalidHandle), "invalid"); f != nil {
  1513  		t.Errorf("NewFile(InvalidHandle) got %v want nil", f)
  1514  	}
  1515  }
  1516  
  1517  func TestReadDirPipe(t *testing.T) {
  1518  	dir := `\\.\pipe\`
  1519  	fi, err := os.Stat(dir)
  1520  	if err != nil || !fi.IsDir() {
  1521  		t.Skipf("%s is not a directory", dir)
  1522  	}
  1523  	_, err = os.ReadDir(dir)
  1524  	if err != nil {
  1525  		t.Errorf("ReadDir(%q) = %v", dir, err)
  1526  	}
  1527  }
  1528  
  1529  func TestReadDirNoFileID(t *testing.T) {
  1530  	*os.AllowReadDirFileID = false
  1531  	defer func() { *os.AllowReadDirFileID = true }()
  1532  
  1533  	dir := t.TempDir()
  1534  	pathA := filepath.Join(dir, "a")
  1535  	pathB := filepath.Join(dir, "b")
  1536  	if err := os.WriteFile(pathA, nil, 0666); err != nil {
  1537  		t.Fatal(err)
  1538  	}
  1539  	if err := os.WriteFile(pathB, nil, 0666); err != nil {
  1540  		t.Fatal(err)
  1541  	}
  1542  
  1543  	files, err := os.ReadDir(dir)
  1544  	if err != nil {
  1545  		t.Fatal(err)
  1546  	}
  1547  	if len(files) != 2 {
  1548  		t.Fatalf("ReadDir(%q) = %v; want 2 files", dir, files)
  1549  	}
  1550  
  1551  	// Check that os.SameFile works with files returned by os.ReadDir.
  1552  	f1, err := files[0].Info()
  1553  	if err != nil {
  1554  		t.Fatal(err)
  1555  	}
  1556  	f2, err := files[1].Info()
  1557  	if err != nil {
  1558  		t.Fatal(err)
  1559  	}
  1560  	if !os.SameFile(f1, f1) {
  1561  		t.Errorf("SameFile(%v, %v) = false; want true", f1, f1)
  1562  	}
  1563  	if !os.SameFile(f2, f2) {
  1564  		t.Errorf("SameFile(%v, %v) = false; want true", f2, f2)
  1565  	}
  1566  	if os.SameFile(f1, f2) {
  1567  		t.Errorf("SameFile(%v, %v) = true; want false", f1, f2)
  1568  	}
  1569  
  1570  	// Check that os.SameFile works with a mix of os.ReadDir and os.Stat files.
  1571  	f1s, err := os.Stat(pathA)
  1572  	if err != nil {
  1573  		t.Fatal(err)
  1574  	}
  1575  	f2s, err := os.Stat(pathB)
  1576  	if err != nil {
  1577  		t.Fatal(err)
  1578  	}
  1579  	if !os.SameFile(f1, f1s) {
  1580  		t.Errorf("SameFile(%v, %v) = false; want true", f1, f1s)
  1581  	}
  1582  	if !os.SameFile(f2, f2s) {
  1583  		t.Errorf("SameFile(%v, %v) = false; want true", f2, f2s)
  1584  	}
  1585  }
  1586  
  1587  func TestReadWriteFileOverlapped(t *testing.T) {
  1588  	// See https://go.dev/issue/15388.
  1589  	t.Parallel()
  1590  
  1591  	name := filepath.Join(t.TempDir(), "test.txt")
  1592  	f, err := os.OpenFile(name, os.O_RDWR|os.O_CREATE|windows.O_FILE_FLAG_OVERLAPPED, 0666)
  1593  	if err != nil {
  1594  		t.Fatal(err)
  1595  	}
  1596  	defer f.Close()
  1597  
  1598  	data := []byte("test")
  1599  	n, err := f.Write(data)
  1600  	if err != nil {
  1601  		t.Fatal(err)
  1602  	}
  1603  	if n != len(data) {
  1604  		t.Fatalf("Write = %d; want %d", n, len(data))
  1605  	}
  1606  
  1607  	if _, err := f.Seek(0, io.SeekStart); err != nil {
  1608  		t.Fatal(err)
  1609  	}
  1610  
  1611  	got, err := io.ReadAll(f)
  1612  	if err != nil {
  1613  		t.Fatal(err)
  1614  	}
  1615  	if !bytes.Equal(got, data) {
  1616  		t.Fatalf("Read = %q; want %q", got, data)
  1617  	}
  1618  }
  1619  
  1620  func TestStdinOverlappedPipe(t *testing.T) {
  1621  	// Test that we can read from a named pipe open with FILE_FLAG_OVERLAPPED.
  1622  	// See https://go.dev/issue/15388.
  1623  	if os.Getenv("GO_WANT_HELPER_PROCESS") == "1" {
  1624  		var buf string
  1625  		_, err := fmt.Scanln(&buf)
  1626  		if err != nil {
  1627  			fmt.Print(err)
  1628  			os.Exit(1)
  1629  		}
  1630  		fmt.Println(buf)
  1631  		os.Exit(0)
  1632  	}
  1633  
  1634  	t.Parallel()
  1635  	name := pipeName()
  1636  
  1637  	// Create the read handle inherited by the child process.
  1638  	r := newPipe(t, name, 4096, false, true)
  1639  	defer r.Close()
  1640  
  1641  	// Create a write handle.
  1642  	w, err := os.OpenFile(name, os.O_WRONLY, 0666)
  1643  	if err != nil {
  1644  		t.Fatal(err)
  1645  	}
  1646  	defer w.Close()
  1647  
  1648  	// Write some data to the pipe. The child process will read it.
  1649  	want := []byte("test\n")
  1650  	if _, err := w.Write(want); err != nil {
  1651  		t.Fatal(err)
  1652  	}
  1653  
  1654  	// Create a child process that will read from the pipe
  1655  	// and write the data to stdout.
  1656  	cmd := testenv.Command(t, testenv.Executable(t), fmt.Sprintf("-test.run=^%s$", t.Name()), "-test.v")
  1657  	cmd = testenv.CleanCmdEnv(cmd)
  1658  	cmd.Env = append(cmd.Env, "GO_WANT_HELPER_PROCESS=1")
  1659  	cmd.Stdin = r
  1660  	got, err := cmd.CombinedOutput()
  1661  	if err != nil {
  1662  		t.Fatalf("running %q failed: %v\n%s", cmd, err, got)
  1663  	}
  1664  
  1665  	if !bytes.Contains(got, want) {
  1666  		t.Fatalf("output %q does not contain %q", got, want)
  1667  	}
  1668  }
  1669  
  1670  func newFileOverlapped(t testing.TB, name string, overlapped bool) *os.File {
  1671  	flags := os.O_RDWR | os.O_CREATE
  1672  	if overlapped {
  1673  		flags |= windows.O_FILE_FLAG_OVERLAPPED
  1674  	}
  1675  	f, err := os.OpenFile(name, flags, 0666)
  1676  	if err != nil {
  1677  		t.Fatal(err)
  1678  	}
  1679  	t.Cleanup(func() {
  1680  		if err := f.Close(); err != nil && !errors.Is(err, os.ErrClosed) {
  1681  			t.Fatal(err)
  1682  		}
  1683  	})
  1684  	return f
  1685  }
  1686  
  1687  var currentProcess = sync.OnceValue(func() string {
  1688  	// Convert the process ID to a string.
  1689  	return strconv.FormatUint(uint64(os.Getpid()), 10)
  1690  })
  1691  
  1692  var pipeCounter atomic.Uint64
  1693  
  1694  func newBytePipe(t testing.TB, name string, overlapped bool) *os.File {
  1695  	return newPipe(t, name, 4096, false, overlapped)
  1696  }
  1697  
  1698  func newMessagePipe(t testing.TB, name string, overlapped bool) *os.File {
  1699  	return newPipe(t, name, 4096, true, overlapped)
  1700  }
  1701  
  1702  func pipeName() string {
  1703  	return `\\.\pipe\go-os-test-` + currentProcess() + `-` + strconv.FormatUint(pipeCounter.Add(1), 10)
  1704  }
  1705  
  1706  func newPipe(t testing.TB, name string, bufSize uint32, message, overlapped bool) *os.File {
  1707  	wname, err := syscall.UTF16PtrFromString(name)
  1708  	if err != nil {
  1709  		t.Fatal(err)
  1710  	}
  1711  	// Create the read handle.
  1712  	flags := windows.PIPE_ACCESS_DUPLEX
  1713  	if overlapped {
  1714  		flags |= windows.O_FILE_FLAG_OVERLAPPED
  1715  	}
  1716  	typ := windows.PIPE_TYPE_BYTE | windows.PIPE_READMODE_BYTE
  1717  	if message {
  1718  		typ = windows.PIPE_TYPE_MESSAGE | windows.PIPE_READMODE_MESSAGE
  1719  	}
  1720  	h, err := windows.CreateNamedPipe(wname, uint32(flags), uint32(typ), 1, bufSize, bufSize, 0, nil)
  1721  	if err != nil {
  1722  		t.Fatal(err)
  1723  	}
  1724  	f := os.NewFile(uintptr(h), name)
  1725  	t.Cleanup(func() {
  1726  		if err := f.Close(); err != nil && !errors.Is(err, os.ErrClosed) {
  1727  			t.Fatal(err)
  1728  		}
  1729  	})
  1730  	return f
  1731  }
  1732  
  1733  func testReadWrite(t *testing.T, fdr, fdw *os.File) {
  1734  	write := make(chan string, 1)
  1735  	read := make(chan struct{}, 1)
  1736  	go func() {
  1737  		for s := range write {
  1738  			n, err := fdw.Write([]byte(s))
  1739  			read <- struct{}{}
  1740  			if err != nil {
  1741  				t.Error(err)
  1742  			}
  1743  			if n != len(s) {
  1744  				t.Errorf("expected to write %d bytes, got %d", len(s), n)
  1745  			}
  1746  		}
  1747  	}()
  1748  	for i := range 10 {
  1749  		s := strconv.Itoa(i)
  1750  		write <- s
  1751  		<-read
  1752  		buf := make([]byte, len(s))
  1753  		_, err := io.ReadFull(fdr, buf)
  1754  		if err != nil {
  1755  			t.Fatalf("read failed: %v", err)
  1756  		}
  1757  		if !bytes.Equal(buf, []byte(s)) {
  1758  			t.Fatalf("expected %q, got %q", s, buf)
  1759  		}
  1760  	}
  1761  	close(read)
  1762  	close(write)
  1763  }
  1764  
  1765  func testPreadPwrite(t *testing.T, fdr, fdw *os.File) {
  1766  	type op struct {
  1767  		s   string
  1768  		off int64
  1769  	}
  1770  	write := make(chan op, 1)
  1771  	read := make(chan struct{}, 1)
  1772  	go func() {
  1773  		for o := range write {
  1774  			n, err := fdw.WriteAt([]byte(o.s), o.off)
  1775  			read <- struct{}{}
  1776  			if err != nil {
  1777  				t.Error(err)
  1778  			}
  1779  			if n != len(o.s) {
  1780  				t.Errorf("expected to write %d bytes, got %d", len(o.s), n)
  1781  			}
  1782  		}
  1783  	}()
  1784  	for i := range 10 {
  1785  		off := int64(i % 3) // exercise some back and forth
  1786  		s := strconv.Itoa(i)
  1787  		write <- op{s, off}
  1788  		<-read
  1789  		buf := make([]byte, len(s))
  1790  		n, err := fdr.ReadAt(buf, off)
  1791  		if err != nil {
  1792  			t.Fatal(err)
  1793  		}
  1794  		if n != len(s) {
  1795  			t.Fatalf("expected to read %d bytes, got %d", len(s), n)
  1796  		}
  1797  		if !bytes.Equal(buf, []byte(s)) {
  1798  			t.Fatalf("expected %q, got %q", s, buf)
  1799  		}
  1800  	}
  1801  	close(read)
  1802  	close(write)
  1803  }
  1804  
  1805  func testFileReadEOF(t *testing.T, f *os.File) {
  1806  	end, err := f.Seek(0, io.SeekEnd)
  1807  	if err != nil {
  1808  		t.Fatal(err)
  1809  	}
  1810  	var buf [1]byte
  1811  	n, err := f.Read(buf[:])
  1812  	if err != nil && err != io.EOF {
  1813  		t.Errorf("expected EOF, got %v", err)
  1814  	}
  1815  	if n != 0 {
  1816  		t.Errorf("expected 0 bytes, got %d", n)
  1817  	}
  1818  
  1819  	n, err = f.ReadAt(buf[:], end)
  1820  	if err != nil && err != io.EOF {
  1821  		t.Errorf("expected EOF, got %v", err)
  1822  	}
  1823  	if n != 0 {
  1824  		t.Errorf("expected 0 bytes, got %d", n)
  1825  	}
  1826  }
  1827  
  1828  func TestFile(t *testing.T) {
  1829  	t.Parallel()
  1830  	tests := []struct {
  1831  		name            string
  1832  		overlappedRead  bool
  1833  		overlappedWrite bool
  1834  	}{
  1835  		{"overlapped", true, true},
  1836  		{"overlapped-read", true, false},
  1837  		{"overlapped-write", false, true},
  1838  		{"sync", false, false},
  1839  	}
  1840  	for _, tt := range tests {
  1841  		t.Run(tt.name, func(t *testing.T) {
  1842  			t.Parallel()
  1843  			name := filepath.Join(t.TempDir(), "foo")
  1844  			rh := newFileOverlapped(t, name, tt.overlappedRead)
  1845  			wh := newFileOverlapped(t, name, tt.overlappedWrite)
  1846  			testReadWrite(t, rh, wh)
  1847  			testPreadPwrite(t, rh, wh)
  1848  			testFileReadEOF(t, rh)
  1849  		})
  1850  	}
  1851  }
  1852  
  1853  func TestFileOverlappedSeek(t *testing.T) {
  1854  	t.Parallel()
  1855  	name := filepath.Join(t.TempDir(), "foo")
  1856  	f := newFileOverlapped(t, name, true)
  1857  	content := []byte("foo")
  1858  	if _, err := f.Write(content); err != nil {
  1859  		t.Fatal(err)
  1860  	}
  1861  	// Check that the file pointer is at the expected offset.
  1862  	n, err := f.Seek(0, io.SeekCurrent)
  1863  	if err != nil {
  1864  		t.Fatal(err)
  1865  	}
  1866  	if n != int64(len(content)) {
  1867  		t.Errorf("expected file pointer to be at offset %d, got %d", len(content), n)
  1868  	}
  1869  	// Set the file pointer to the start of the file.
  1870  	if _, err := f.Seek(0, io.SeekStart); err != nil {
  1871  		t.Fatal(err)
  1872  	}
  1873  	// Read the first byte.
  1874  	var buf [1]byte
  1875  	if _, err := f.Read(buf[:]); err != nil {
  1876  		t.Fatal(err)
  1877  	}
  1878  	if !bytes.Equal(buf[:], content[:len(buf)]) {
  1879  		t.Errorf("expected %q, got %q", content[:len(buf)], buf[:])
  1880  	}
  1881  	// Check that the file pointer is at the expected offset.
  1882  	n, err = f.Seek(0, io.SeekCurrent)
  1883  	if err != nil {
  1884  		t.Fatal(err)
  1885  	}
  1886  	if n != int64(len(buf)) {
  1887  		t.Errorf("expected file pointer to be at offset %d, got %d", len(buf), n)
  1888  	}
  1889  	if n, err = f.Seek(1, io.SeekStart); err != nil {
  1890  		t.Fatal(err)
  1891  	} else if n != 1 {
  1892  		t.Errorf("expected file pointer to be at offset %d, got %d", 1, n)
  1893  	}
  1894  	if n, err = f.Seek(-1, io.SeekEnd); err != nil {
  1895  		t.Fatal(err)
  1896  	} else if n != int64(len(content)-1) {
  1897  		t.Errorf("expected file pointer to be at offset %d, got %d", len(content)-1, n)
  1898  	}
  1899  	if _, err := f.Seek(-1, io.SeekStart); !errors.Is(err, windows.ERROR_NEGATIVE_SEEK) {
  1900  		t.Errorf("expected ERROR_NEGATIVE_SEEK, got %v", err)
  1901  	}
  1902  	if _, err := f.Seek(0, -1); !errors.Is(err, windows.ERROR_INVALID_PARAMETER) {
  1903  		t.Errorf("expected ERROR_INVALID_PARAMETER, got %v", err)
  1904  	}
  1905  }
  1906  
  1907  func TestFileOverlappedReadAtSeekVolume(t *testing.T) {
  1908  	// Test that we can use File.ReadAt and File.Seek with an overlapped volume handle.
  1909  	// See https://go.dev/issues/74951.
  1910  	t.Parallel()
  1911  	name := `\\.\` + filepath.VolumeName(t.TempDir())
  1912  	f, err := os.OpenFile(name, os.O_RDWR|os.O_CREATE|windows.O_FILE_FLAG_OVERLAPPED, 0666)
  1913  	if err != nil {
  1914  		if errors.Is(err, syscall.ERROR_ACCESS_DENIED) {
  1915  			t.Skip("skipping test: access denied")
  1916  		}
  1917  		t.Fatal(err)
  1918  	}
  1919  	defer f.Close()
  1920  
  1921  	var buf [0]byte
  1922  	if _, err := f.ReadAt(buf[:], 0); err != nil {
  1923  		t.Fatal(err)
  1924  	}
  1925  	if _, err := f.Seek(0, io.SeekCurrent); err != nil {
  1926  		t.Fatal(err)
  1927  	}
  1928  }
  1929  
  1930  func TestPipe(t *testing.T) {
  1931  	t.Parallel()
  1932  	r, w, err := os.Pipe()
  1933  	if err != nil {
  1934  		t.Fatal(err)
  1935  	}
  1936  	defer func() {
  1937  		if err := r.Close(); err != nil {
  1938  			t.Fatal(err)
  1939  		}
  1940  		if err := w.Close(); err != nil {
  1941  			t.Fatal(err)
  1942  		}
  1943  	}()
  1944  	testReadWrite(t, r, w)
  1945  }
  1946  
  1947  func TestPipeCloseInvalidHandle(t *testing.T) {
  1948  	// Closing the same handle through distinct Files must return an error,
  1949  	// not panic. See go.dev/issue/82273.
  1950  	for _, first := range []string{"original", "new"} {
  1951  		t.Run(first, func(t *testing.T) {
  1952  			r, w, err := os.Pipe()
  1953  			if err != nil {
  1954  				t.Fatal(err)
  1955  			}
  1956  			defer r.Close()
  1957  			defer w.Close()
  1958  
  1959  			for _, f := range []*os.File{r, w} {
  1960  				other := os.NewFile(f.Fd(), f.Name())
  1961  				defer other.Close()
  1962  				if first == "new" {
  1963  					f, other = other, f
  1964  				}
  1965  				if err := f.Close(); err != nil {
  1966  					t.Fatal(err)
  1967  				}
  1968  				if err := other.Close(); !errors.Is(err, windows.ERROR_INVALID_HANDLE) {
  1969  					t.Errorf("Close = %v; want ERROR_INVALID_HANDLE", err)
  1970  				}
  1971  			}
  1972  		})
  1973  	}
  1974  }
  1975  
  1976  func TestPipeCloseRaceThreadReuse(t *testing.T) {
  1977  	// A read can finish while Close is still canceling it. Starting a blocking
  1978  	// operation on the same thread must not prevent that Close from returning.
  1979  	// See go.dev/issue/74754.
  1980  	t.Parallel()
  1981  
  1982  	for range 100 {
  1983  		r, w, err := os.Pipe()
  1984  		if err != nil {
  1985  			t.Fatal(err)
  1986  		}
  1987  		r2, w2, err := os.Pipe()
  1988  		if err != nil {
  1989  			r.Close()
  1990  			w.Close()
  1991  			t.Fatal(err)
  1992  		}
  1993  		var wg sync.WaitGroup
  1994  		wg.Go(func() {
  1995  			runtime.LockOSThread()
  1996  			defer runtime.UnlockOSThread()
  1997  			defer r2.Close()
  1998  			if _, err := io.Copy(io.Discard, r); !errors.Is(err, os.ErrClosed) {
  1999  				t.Errorf("Read interrupted by Close = %v; want ErrClosed", err)
  2000  			}
  2001  			// Reuse the thread before waiting for Close to finish.
  2002  			var b [1]byte
  2003  			if _, err := r2.Read(b[:]); err != io.EOF {
  2004  				t.Errorf("Read from second pipe = %v; want EOF", err)
  2005  			}
  2006  		})
  2007  		wg.Go(func() {
  2008  			defer w.Close()
  2009  			for {
  2010  				if _, err := w.Write([]byte("x")); err != nil {
  2011  					return
  2012  				}
  2013  			}
  2014  		})
  2015  		time.Sleep(time.Millisecond) // Let reads and writes race with Close.
  2016  		if err := r.Close(); err != nil {
  2017  			t.Error(err)
  2018  		}
  2019  		// Release the second read only after Close returns.
  2020  		w2.Close()
  2021  		wg.Wait()
  2022  	}
  2023  }
  2024  
  2025  func TestPipeConcurrentReadWrite(t *testing.T) {
  2026  	test := func(t *testing.T) {
  2027  		t.Helper()
  2028  		writers := make([]*os.File, 32)
  2029  		started := make(chan struct{}, len(writers))
  2030  		var wg sync.WaitGroup
  2031  		defer wg.Wait()
  2032  		for i := range writers {
  2033  			r, w, err := os.Pipe()
  2034  			if err != nil {
  2035  				t.Fatal(err)
  2036  			}
  2037  			defer r.Close()
  2038  			defer w.Close()
  2039  			writers[i] = w
  2040  			wg.Go(func() {
  2041  				started <- struct{}{}
  2042  				var b [1]byte
  2043  				if _, err := io.ReadFull(r, b[:]); err != nil {
  2044  					t.Error(err)
  2045  				} else if b[0] != byte(i) {
  2046  					t.Errorf("Read = %d; want %d", b[0], i)
  2047  				}
  2048  			})
  2049  		}
  2050  		for range writers {
  2051  			<-started
  2052  		}
  2053  		runtime.GC()
  2054  		for i, w := range writers {
  2055  			if _, err := w.Write([]byte{byte(i)}); err != nil {
  2056  				t.Error(err)
  2057  			}
  2058  			w.Close()
  2059  		}
  2060  		wg.Wait()
  2061  	}
  2062  	// Pipe I/O must keep working across GC and successive synctest bubbles.
  2063  	for range 2 {
  2064  		test(t)
  2065  		runtime.GC()
  2066  		runtime.GC()
  2067  		synctest.Test(t, test)
  2068  	}
  2069  	test(t)
  2070  }
  2071  
  2072  func TestNamedPipe(t *testing.T) {
  2073  	t.Parallel()
  2074  	tests := []struct {
  2075  		name            string
  2076  		overlappedRead  bool
  2077  		overlappedWrite bool
  2078  	}{
  2079  		{"overlapped", true, true},
  2080  		{"overlapped-write", false, true},
  2081  		{"overlapped-read", true, false},
  2082  		{"sync", false, false},
  2083  	}
  2084  	for _, tt := range tests {
  2085  		t.Run(tt.name, func(t *testing.T) {
  2086  			t.Parallel()
  2087  			name := pipeName()
  2088  			pipe := newBytePipe(t, name, tt.overlappedWrite)
  2089  			file := newFileOverlapped(t, name, tt.overlappedRead)
  2090  			testReadWrite(t, pipe, file)
  2091  		})
  2092  	}
  2093  }
  2094  
  2095  func TestNamedPipeConcurrentReadWrite(t *testing.T) {
  2096  	t.Parallel()
  2097  	name := pipeName()
  2098  	server := newBytePipe(t, name, true)
  2099  	client := newFileOverlapped(t, name, true)
  2100  
  2101  	// Read and Write use separate locks. In particular, neither may
  2102  	// access the shared file offset, which is unused by pipes.
  2103  	const count = 100
  2104  	var wg sync.WaitGroup
  2105  	for _, f := range []*os.File{server, client} {
  2106  		wg.Go(func() {
  2107  			var buf [1]byte
  2108  			for i := range count {
  2109  				if _, err := io.ReadFull(f, buf[:]); err != nil {
  2110  					t.Error(err)
  2111  					f.Close() // Unblock the peer.
  2112  					return
  2113  				}
  2114  				if buf[0] != byte(i) {
  2115  					t.Errorf("Read = %d; want %d", buf[0], i)
  2116  				}
  2117  			}
  2118  		})
  2119  		wg.Go(func() {
  2120  			for i := range count {
  2121  				if _, err := f.Write([]byte{byte(i)}); err != nil {
  2122  					t.Error(err)
  2123  					f.Close()
  2124  					return
  2125  				}
  2126  			}
  2127  		})
  2128  	}
  2129  	wg.Wait()
  2130  }
  2131  
  2132  func TestPipeMessageReadEOF(t *testing.T) {
  2133  	t.Parallel()
  2134  	name := pipeName()
  2135  	pipe := newMessagePipe(t, name, true)
  2136  	file := newFileOverlapped(t, name, true)
  2137  
  2138  	_, err := pipe.Write(nil)
  2139  	if err != nil {
  2140  		t.Error(err)
  2141  	}
  2142  
  2143  	var buf [10]byte
  2144  	n, err := file.Read(buf[:])
  2145  	if err != io.EOF {
  2146  		t.Errorf("expected EOF, got %v", err)
  2147  	}
  2148  	if n != 0 {
  2149  		t.Errorf("expected 0 bytes, got %d", n)
  2150  	}
  2151  }
  2152  
  2153  func TestPipeClosedEOF(t *testing.T) {
  2154  	t.Parallel()
  2155  	name := pipeName()
  2156  	pipe := newBytePipe(t, name, true)
  2157  	file := newFileOverlapped(t, name, true)
  2158  
  2159  	pipe.Close()
  2160  
  2161  	var buf [10]byte
  2162  	n, err := file.Read(buf[:])
  2163  	if err != io.EOF {
  2164  		t.Errorf("expected EOF, got %v", err)
  2165  	}
  2166  	if n != 0 {
  2167  		t.Errorf("expected 0 bytes, got %d", n)
  2168  	}
  2169  }
  2170  
  2171  func TestPipeReadTimeout(t *testing.T) {
  2172  	t.Parallel()
  2173  	name := pipeName()
  2174  	_ = newBytePipe(t, name, true)
  2175  	file := newFileOverlapped(t, name, true)
  2176  
  2177  	err := file.SetReadDeadline(time.Now().Add(time.Millisecond))
  2178  	if err != nil {
  2179  		t.Fatal(err)
  2180  	}
  2181  
  2182  	var buf [10]byte
  2183  	_, err = file.Read(buf[:])
  2184  	if !errors.Is(err, os.ErrDeadlineExceeded) {
  2185  		t.Errorf("expected deadline exceeded, got %v", err)
  2186  	}
  2187  }
  2188  
  2189  func TestPipeCanceled(t *testing.T) {
  2190  	t.Parallel()
  2191  	name := pipeName()
  2192  	_ = newBytePipe(t, name, true)
  2193  	file := newFileOverlapped(t, name, true)
  2194  	ch := make(chan struct{}, 1)
  2195  	go func() {
  2196  		for {
  2197  			select {
  2198  			case <-ch:
  2199  				return
  2200  			default:
  2201  				sc, err := file.SyscallConn()
  2202  				if err != nil {
  2203  					t.Error(err)
  2204  					return
  2205  				}
  2206  				if err := sc.Control(func(fd uintptr) {
  2207  					syscall.CancelIoEx(syscall.Handle(fd), nil)
  2208  				}); err != nil {
  2209  					t.Error(err)
  2210  					return
  2211  				}
  2212  				time.Sleep(100 * time.Millisecond)
  2213  			}
  2214  		}
  2215  	}()
  2216  	var tmp [1]byte
  2217  	// Read will block until the cancel is complete.
  2218  	_, err := file.Read(tmp[:])
  2219  	ch <- struct{}{}
  2220  	if errors.Is(err, os.ErrDeadlineExceeded) {
  2221  		t.Skip("took too long to cancel")
  2222  	}
  2223  	if !errors.Is(err, syscall.ERROR_OPERATION_ABORTED) {
  2224  		t.Errorf("expected ERROR_OPERATION_ABORTED, got %v", err)
  2225  	}
  2226  }
  2227  
  2228  func iocpAssociateFile(f *os.File, iocp syscall.Handle) error {
  2229  	_, err := windows.CreateIoCompletionPort(syscall.Handle(f.Fd()), iocp, 0, 0)
  2230  	return err
  2231  }
  2232  
  2233  func TestFileAssociatedWithExternalIOCP(t *testing.T) {
  2234  	// Test that a caller can associate an overlapped handle to an external IOCP
  2235  	// after the handle has been passed to os.NewFile.
  2236  	// Also test that the File can perform I/O after it is associated with the
  2237  	// external IOCP and that those operations do not post to the external IOCP.
  2238  	t.Parallel()
  2239  	name := pipeName()
  2240  	pipe := newMessagePipe(t, name, true)
  2241  	_ = newFileOverlapped(t, name, true) // just open a pipe client
  2242  
  2243  	// Use a file to exercise WriteAt.
  2244  	file := newFileOverlapped(t, filepath.Join(t.TempDir(), "a"), true)
  2245  
  2246  	iocp, err := windows.CreateIoCompletionPort(syscall.InvalidHandle, 0, 0, 0)
  2247  	if err != nil {
  2248  		t.Fatal(err)
  2249  	}
  2250  	defer func() {
  2251  		if iocp == syscall.InvalidHandle {
  2252  			// Already closed at the end of the test.
  2253  			return
  2254  		}
  2255  		if err := syscall.CloseHandle(iocp); err != nil {
  2256  			t.Fatal(err)
  2257  		}
  2258  	}()
  2259  
  2260  	ch := make(chan error, 1)
  2261  	go func() {
  2262  		var bytes, key uint32
  2263  		var overlapped *syscall.Overlapped
  2264  		err := syscall.GetQueuedCompletionStatus(syscall.Handle(iocp), &bytes, &key, &overlapped, syscall.INFINITE)
  2265  		ch <- err
  2266  	}()
  2267  
  2268  	if err := iocpAssociateFile(pipe, iocp); err != nil {
  2269  		t.Fatal(err)
  2270  	}
  2271  	if err := iocpAssociateFile(file, iocp); err != nil {
  2272  		t.Fatal(err)
  2273  	}
  2274  
  2275  	if _, err := pipe.Write([]byte("hello")); err != nil {
  2276  		t.Fatal(err)
  2277  	}
  2278  	if _, err := file.Write([]byte("hello")); err != nil {
  2279  		t.Fatal(err)
  2280  	}
  2281  	if _, err := file.WriteAt([]byte("hello"), 0); err != nil {
  2282  		t.Fatal(err)
  2283  	}
  2284  
  2285  	// Wait fot he goroutine to call GetQueuedCompletionStatus.
  2286  	time.Sleep(100 * time.Millisecond)
  2287  
  2288  	// Trigger ERROR_ABANDONED_WAIT_0.
  2289  	if err := syscall.CloseHandle(iocp); err != nil {
  2290  		t.Fatal(err)
  2291  	}
  2292  
  2293  	// Wait for the completion to be posted to the IOCP.
  2294  	err = <-ch
  2295  	iocp = syscall.InvalidHandle
  2296  	const ERROR_ABANDONED_WAIT_0 = syscall.Errno(735)
  2297  	switch err {
  2298  	case ERROR_ABANDONED_WAIT_0:
  2299  		// This is what we expect.
  2300  	case nil:
  2301  		t.Error("unexpected queued completion")
  2302  	default:
  2303  		t.Error(err)
  2304  	}
  2305  }
  2306  
  2307  func TestPipePendingIOAfterFd(t *testing.T) {
  2308  	t.Parallel()
  2309  	name := pipeName()
  2310  	writer := newPipe(t, name, 0, false, true)
  2311  	reader := newFileOverlapped(t, name, true)
  2312  	writer.Fd()
  2313  	reader.Fd()
  2314  
  2315  	// An unbuffered pipe keeps the write pending until all bytes are read.
  2316  	// Both handles use events rather than the runtime IOCP.
  2317  	const want = "ab"
  2318  	writeDone := make(chan struct{})
  2319  	var wg sync.WaitGroup
  2320  	wg.Go(func() {
  2321  		var buf [len(want)]byte
  2322  		if _, err := io.ReadFull(reader, buf[:1]); err != nil {
  2323  			t.Error(err)
  2324  			reader.Close()
  2325  			return
  2326  		}
  2327  		select {
  2328  		case <-writeDone:
  2329  			t.Error("Write returned before all bytes were read")
  2330  		default:
  2331  		}
  2332  		if _, err := io.ReadFull(reader, buf[1:]); err != nil {
  2333  			t.Error(err)
  2334  			reader.Close()
  2335  			return
  2336  		}
  2337  		if string(buf[:]) != want {
  2338  			t.Errorf("Read = %q; want %q", buf[:], want)
  2339  		}
  2340  	})
  2341  	if n, err := writer.Write([]byte(want)); err != nil || n != len(want) {
  2342  		t.Errorf("Write = %d, %v; want %d, nil", n, err, len(want))
  2343  		writer.Close()
  2344  	}
  2345  	close(writeDone)
  2346  	wg.Wait()
  2347  }
  2348  
  2349  func TestPipeReadCloseRace(t *testing.T) {
  2350  	t.Parallel()
  2351  	for i := range 100 {
  2352  		name := pipeName()
  2353  		writer := newBytePipe(t, name, true)
  2354  		reader := newFileOverlapped(t, name, true)
  2355  		reader.Fd() // Use event-backed I/O.
  2356  
  2357  		var wg sync.WaitGroup
  2358  		readDone := make(chan error, 1)
  2359  		wg.Go(func() {
  2360  			var buf [1]byte
  2361  			_, err := reader.Read(buf[:])
  2362  			readDone <- err
  2363  		})
  2364  		// Give Read a chance to acquire its FD reference, then race Close
  2365  		// against submission of the I/O request.
  2366  		time.Sleep(time.Nanosecond)
  2367  		closeDone := make(chan error, 1)
  2368  		wg.Go(func() { closeDone <- reader.Close() })
  2369  		select {
  2370  		case err := <-closeDone:
  2371  			if err != nil {
  2372  				t.Error(err)
  2373  			}
  2374  		case <-time.After(5 * time.Second):
  2375  			// Release the read even if Close missed its cancellation.
  2376  			writer.Close()
  2377  			wg.Wait()
  2378  			t.Fatalf("iteration %d: Close did not unblock Read", i)
  2379  		}
  2380  		wg.Wait()
  2381  		writer.Close()
  2382  		if err := <-readDone; !errors.Is(err, os.ErrClosed) {
  2383  			t.Fatalf("iteration %d: Read error = %v; want ErrClosed", i, err)
  2384  		}
  2385  	}
  2386  }
  2387  
  2388  func TestFileWriteFdRace(t *testing.T) {
  2389  	t.Parallel()
  2390  
  2391  	f := newFileOverlapped(t, filepath.Join(t.TempDir(), "a"), true)
  2392  
  2393  	var wg sync.WaitGroup
  2394  	wg.Add(2)
  2395  
  2396  	go func() {
  2397  		defer wg.Done()
  2398  		n, err := f.Write([]byte("hi"))
  2399  		if err != nil {
  2400  			// We look at error strings as the
  2401  			// expected errors are OS-specific.
  2402  			switch {
  2403  			case errors.Is(err, windows.ERROR_INVALID_HANDLE):
  2404  				// Ignore an expected error.
  2405  			default:
  2406  				// Unexpected error.
  2407  				t.Error(err)
  2408  			}
  2409  			return
  2410  		}
  2411  		if n != 2 {
  2412  			t.Errorf("wrote %d bytes, expected 2", n)
  2413  			return
  2414  		}
  2415  	}()
  2416  	go func() {
  2417  		defer wg.Done()
  2418  		f.Fd()
  2419  	}()
  2420  	wg.Wait()
  2421  
  2422  	iocp, err := windows.CreateIoCompletionPort(syscall.InvalidHandle, 0, 0, 0)
  2423  	if err != nil {
  2424  		t.Fatal(err)
  2425  	}
  2426  	defer syscall.CloseHandle(iocp)
  2427  	if err := iocpAssociateFile(f, iocp); err != nil {
  2428  		t.Fatal(err)
  2429  	}
  2430  
  2431  	if _, err := f.Write([]byte("hi")); err != nil {
  2432  		t.Error(err)
  2433  	}
  2434  }
  2435  
  2436  func TestFileFdWithConcurrentIO(t *testing.T) {
  2437  	t.Parallel()
  2438  	name := pipeName()
  2439  	pipe := newPipe(t, name, 0, true, true) // unbuffered pipe so Write blocks
  2440  	file := newFileOverlapped(t, name, true)
  2441  	const writeSize = 2
  2442  	var wg sync.WaitGroup
  2443  	wg.Go(func() {
  2444  		// Ensure the Write is pending.
  2445  		var tmp [writeSize / 2]byte
  2446  		if _, err := file.Read(tmp[:]); err != nil {
  2447  			t.Error(err)
  2448  		}
  2449  		// Try to dissaciate the file from any IOCP.
  2450  		pipe.Fd()
  2451  		// Complete the Write.
  2452  		if _, err := file.Read(tmp[:]); err != nil {
  2453  			t.Error(err)
  2454  		}
  2455  	})
  2456  	// Write will block until the goroutine reads all 2 bytes.
  2457  	var tmp [writeSize]byte
  2458  	n, err := pipe.Write(tmp[:])
  2459  	if err != nil {
  2460  		t.Fatal(err)
  2461  	}
  2462  	if n != writeSize {
  2463  		t.Fatalf("expected to write %d bytes, got %d", writeSize, n)
  2464  	}
  2465  	wg.Wait()
  2466  
  2467  	// Verify that the pipe is still associated with the Go runtime IOCP
  2468  	// by trying to associate it with a new IOCP, which should fail.
  2469  	iocp, err := windows.CreateIoCompletionPort(syscall.InvalidHandle, 0, 0, 0)
  2470  	if err != nil {
  2471  		t.Fatal(err)
  2472  	}
  2473  	defer syscall.CloseHandle(iocp)
  2474  	sc, err := pipe.SyscallConn()
  2475  	if err != nil {
  2476  		t.Fatal(err)
  2477  	}
  2478  	if err := sc.Control(func(fd uintptr) {
  2479  		_, err = windows.CreateIoCompletionPort(syscall.Handle(fd), iocp, 0, 0)
  2480  		if err == nil {
  2481  			t.Fatal("pipe should still be associated with the Go runtime IOCP")
  2482  		}
  2483  	}); err != nil {
  2484  		t.Fatal(err)
  2485  	}
  2486  }
  2487  
  2488  func TestSplitPath(t *testing.T) {
  2489  	t.Parallel()
  2490  	for _, tt := range []struct{ path, wantDir, wantBase string }{
  2491  		{`a`, `.`, `a`},
  2492  		{`a\`, `.`, `a`},
  2493  		{`a\\`, `.`, `a`},
  2494  		{`a\b`, `a`, `b`},
  2495  		{`a\\b`, `a`, `b`},
  2496  		{`a\b\`, `a`, `b`},
  2497  		{`a\b\c`, `a\b`, `c`},
  2498  		{`\a`, `\`, `a`},
  2499  		{`\a\`, `\`, `a`},
  2500  		{`\a\b`, `\a`, `b`},
  2501  		{`\a\b\`, `\a`, `b`},
  2502  		{`\a\b\c`, `\a\b`, `c`},
  2503  		{`\\a`, `\\a`, `.`},
  2504  		{`\\a\`, `\\a\`, `.`},
  2505  		{`\\\a`, `\\\a`, `.`},
  2506  		{`\\\a\`, `\\\a`, `.`},
  2507  		{`\\a\b\c`, `\\a\b`, `c`},
  2508  		{`c:`, `c:`, `.`},
  2509  		{`c:\`, `c:\`, `.`},
  2510  		{`c:\a`, `c:\`, `a`},
  2511  		{`c:a`, `c:`, `a`},
  2512  		{`c:a\b\`, `c:a`, `b`},
  2513  		{`c:base`, `c:`, `base`},
  2514  		{`a/b/c`, `a/b`, `c`},
  2515  		{`a/b/c/`, `a/b`, `c`},
  2516  		{`\\?\c:\a`, `\\?\c:\`, `a`},
  2517  	} {
  2518  		if dir, base := os.SplitPath(tt.path); dir != tt.wantDir || base != tt.wantBase {
  2519  			t.Errorf("splitPath(%q) = %q, %q, want %q, %q", tt.path, dir, base, tt.wantDir, tt.wantBase)
  2520  		}
  2521  	}
  2522  }
  2523  
  2524  func TestOpenFileFlags(t *testing.T) {
  2525  	t.Parallel()
  2526  
  2527  	// The only way to retrieve some of the flags passed in CreateFile
  2528  	// is using NtQueryInformationFile, which returns the file flags
  2529  	// NT equivalent. Note that FILE_SYNCHRONOUS_IO_NONALERT is always
  2530  	// set when FILE_FLAG_OVERLAPPED is not passed.
  2531  	// The flags that can't be retrieved using NtQueryInformationFile won't
  2532  	// be tested in here, but we at least know that the logic to handle them is correct.
  2533  	tests := []struct {
  2534  		flag     uint32
  2535  		wantMode uint32
  2536  	}{
  2537  		{0, windows.FILE_SYNCHRONOUS_IO_NONALERT},
  2538  		{windows.O_FILE_FLAG_OVERLAPPED, 0},
  2539  		{windows.O_FILE_FLAG_NO_BUFFERING, windows.FILE_NO_INTERMEDIATE_BUFFERING | windows.FILE_SYNCHRONOUS_IO_NONALERT},
  2540  		{windows.O_FILE_FLAG_NO_BUFFERING | windows.O_FILE_FLAG_OVERLAPPED, windows.FILE_NO_INTERMEDIATE_BUFFERING},
  2541  		{windows.O_FILE_FLAG_SEQUENTIAL_SCAN, windows.FILE_SEQUENTIAL_ONLY | windows.FILE_SYNCHRONOUS_IO_NONALERT},
  2542  		{windows.O_FILE_FLAG_WRITE_THROUGH, windows.FILE_WRITE_THROUGH | windows.FILE_SYNCHRONOUS_IO_NONALERT},
  2543  	}
  2544  	for i, tt := range tests {
  2545  		t.Run(strconv.Itoa(i), func(t *testing.T) {
  2546  			t.Parallel()
  2547  			f, err := os.OpenFile(filepath.Join(t.TempDir(), "test.txt"), syscall.O_RDWR|syscall.O_CREAT|int(tt.flag), 0666)
  2548  			if err != nil {
  2549  				t.Fatal(err)
  2550  			}
  2551  			defer f.Close()
  2552  			var info windows.FILE_MODE_INFORMATION
  2553  			if err := windows.NtQueryInformationFile(syscall.Handle(f.Fd()), &windows.IO_STATUS_BLOCK{},
  2554  				unsafe.Pointer(&info), uint32(unsafe.Sizeof(info)), windows.FileModeInformation); err != nil {
  2555  				t.Fatal(err)
  2556  			}
  2557  			if info.Mode != tt.wantMode {
  2558  				t.Errorf("file mode = 0x%x; want 0x%x", info.Mode, tt.wantMode)
  2559  			}
  2560  		})
  2561  	}
  2562  }
  2563  
  2564  func TestOpenFileDeleteOnClose(t *testing.T) {
  2565  	t.Parallel()
  2566  	name := filepath.Join(t.TempDir(), "test.txt")
  2567  	f, err := os.OpenFile(name, syscall.O_RDWR|syscall.O_CREAT|windows.O_FILE_FLAG_DELETE_ON_CLOSE, 0666)
  2568  	if err != nil {
  2569  		t.Fatal(err)
  2570  	}
  2571  	if err := f.Close(); err != nil {
  2572  		t.Fatal(err)
  2573  	}
  2574  	// The file should be deleted after closing.
  2575  	if _, err := os.Stat(name); !errors.Is(err, os.ErrNotExist) {
  2576  		t.Errorf("expected file to be deleted, got %v", err)
  2577  	}
  2578  }
  2579  
  2580  func TestOpenFileFlagInvalid(t *testing.T) {
  2581  	t.Parallel()
  2582  	// invalidFileFlag is the only value in the file flag range that is not supported,
  2583  	// as it is not defined in the Windows API.
  2584  	const invalidFileFlag = 0x00400000
  2585  	f, err := os.OpenFile(filepath.Join(t.TempDir(), "test.txt"), syscall.O_RDWR|syscall.O_CREAT|invalidFileFlag, 0666)
  2586  	if !errors.Is(err, os.ErrInvalid) {
  2587  		t.Fatalf("expected os.ErrInvalid, got %v", err)
  2588  	}
  2589  	f.Close()
  2590  }
  2591  
  2592  func TestOpenFileTruncateNamedPipe(t *testing.T) {
  2593  	t.Parallel()
  2594  	name := pipeName()
  2595  	pipe := newBytePipe(t, name, false)
  2596  	defer pipe.Close()
  2597  
  2598  	f, err := os.OpenFile(name, os.O_TRUNC|os.O_RDWR|os.O_CREATE, 0666)
  2599  	if err != nil {
  2600  		t.Fatal(err)
  2601  	}
  2602  	f.Close()
  2603  }
  2604  
  2605  func TestFileKeepsCompletionNotificationModes(t *testing.T) {
  2606  	// NewFile must preserve completion notification modes and perform I/O
  2607  	// correctly with each combination. See go.dev/issue/80979.
  2608  	t.Parallel()
  2609  	for _, tt := range []struct {
  2610  		name  string
  2611  		modes uint8
  2612  	}{
  2613  		{"none", 0},
  2614  		{"skipSuccess", syscall.FILE_SKIP_COMPLETION_PORT_ON_SUCCESS},
  2615  		{"skipEvent", syscall.FILE_SKIP_SET_EVENT_ON_HANDLE},
  2616  		{"both", syscall.FILE_SKIP_COMPLETION_PORT_ON_SUCCESS | syscall.FILE_SKIP_SET_EVENT_ON_HANDLE},
  2617  	} {
  2618  		t.Run(tt.name, func(t *testing.T) {
  2619  			t.Parallel()
  2620  			name := filepath.Join(t.TempDir(), "file")
  2621  			namep, err := syscall.UTF16PtrFromString(name)
  2622  			if err != nil {
  2623  				t.Fatal(err)
  2624  			}
  2625  			h, err := syscall.CreateFile(namep, syscall.GENERIC_READ|syscall.GENERIC_WRITE,
  2626  				0, nil, syscall.CREATE_ALWAYS, syscall.FILE_FLAG_OVERLAPPED, 0)
  2627  			if err != nil {
  2628  				t.Fatal(err)
  2629  			}
  2630  			if err := syscall.SetFileCompletionNotificationModes(h, tt.modes); err != nil {
  2631  				syscall.CloseHandle(h)
  2632  				t.Fatal(err)
  2633  			}
  2634  			f := os.NewFile(uintptr(h), name)
  2635  			if f == nil {
  2636  				syscall.CloseHandle(h)
  2637  				t.Fatal("NewFile returned nil")
  2638  			}
  2639  			defer f.Close()
  2640  
  2641  			// Query h directly: calling f.Fd would disassociate it from the poller.
  2642  			var info windows.FILE_IO_COMPLETION_NOTIFICATION_INFORMATION
  2643  			if err := windows.NtQueryInformationFile(h, &windows.IO_STATUS_BLOCK{},
  2644  				unsafe.Pointer(&info), uint32(unsafe.Sizeof(info)), windows.FileIoCompletionNotificationInformation); err != nil {
  2645  				t.Fatal(err)
  2646  			}
  2647  			if info.Flags != uint32(tt.modes) {
  2648  				t.Fatalf("completion modes = %#x; want %#x", info.Flags, tt.modes)
  2649  			}
  2650  			// Check that NewFile has initialized the runtime poller.
  2651  			if err := f.SetDeadline(time.Time{}); err != nil {
  2652  				t.Fatal(err)
  2653  			}
  2654  			const want = "hello"
  2655  			if n, err := f.Write([]byte(want)); err != nil || n != len(want) {
  2656  				t.Fatalf("Write = %d, %v; want %d, nil", n, err, len(want))
  2657  			}
  2658  			buf := make([]byte, len(want))
  2659  			if n, err := f.ReadAt(buf, 0); err != nil || n != len(want) {
  2660  				t.Fatalf("ReadAt = %d, %v; want %d, nil", n, err, len(want))
  2661  			}
  2662  			if string(buf) != want {
  2663  				t.Fatalf("ReadAt returned %q; want %q", buf, want)
  2664  			}
  2665  		})
  2666  	}
  2667  }
  2668  
  2669  func TestNewFileStdinBlocked(t *testing.T) {
  2670  	// See https://go.dev/issue/75949.
  2671  	t.Parallel()
  2672  
  2673  	// Use a subprocess to test that os.NewFile on a blocked stdin works.
  2674  	// Can't do it in the same process because os.NewFile would close
  2675  	// stdin for the whole test process once the test ends.
  2676  	if os.Getenv("GO_WANT_HELPER_PROCESS") == "1" {
  2677  		// In the child process, just exit.
  2678  		// If we get here, the os package successfully initialized.
  2679  		os.Exit(0)
  2680  	}
  2681  	name := pipeName()
  2682  	stdin := newBytePipe(t, name, false)
  2683  	file := newFileOverlapped(t, name, false)
  2684  
  2685  	var wg sync.WaitGroup
  2686  	wg.Go(func() {
  2687  		// Block stdin on a read.
  2688  		if _, err := stdin.Read(make([]byte, 1)); err != nil {
  2689  			t.Error(err)
  2690  		}
  2691  	})
  2692  
  2693  	time.Sleep(100 * time.Millisecond) // Give time for the read to start.
  2694  	cmd := testenv.CommandContext(t, t.Context(), testenv.Executable(t), fmt.Sprintf("-test.run=^%s$", t.Name()))
  2695  	cmd.Env = cmd.Environ()
  2696  	cmd.Env = append(cmd.Env, "GO_WANT_HELPER_PROCESS=1")
  2697  	cmd.Stdin = stdin
  2698  	if err := cmd.Run(); err != nil {
  2699  		t.Fatal(err)
  2700  	}
  2701  	// Unblock the read to let the goroutine exit.
  2702  	if _, err := file.Write(make([]byte, 1)); err != nil {
  2703  		t.Fatal(err)
  2704  	}
  2705  	wg.Wait() // Don't leave goroutines behind.
  2706  }
  2707  

View as plain text