...
Run Format

Source file src/os/file_windows.go

Documentation: os

     1  // Copyright 2009 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package os
     6  
     7  import (
     8  	"internal/poll"
     9  	"internal/syscall/windows"
    10  	"runtime"
    11  	"syscall"
    12  	"unicode/utf16"
    13  	"unsafe"
    14  )
    15  
    16  // file is the real representation of *File.
    17  // The extra level of indirection ensures that no clients of os
    18  // can overwrite this data, which could cause the finalizer
    19  // to close the wrong file descriptor.
    20  type file struct {
    21  	pfd     poll.FD
    22  	name    string
    23  	dirinfo *dirInfo // nil unless directory being read
    24  }
    25  
    26  // Fd returns the Windows handle referencing the open file.
    27  // The handle is valid only until f.Close is called or f is garbage collected.
    28  // On Unix systems this will cause the SetDeadline methods to stop working.
    29  func (file *File) Fd() uintptr {
    30  	if file == nil {
    31  		return uintptr(syscall.InvalidHandle)
    32  	}
    33  	return uintptr(file.pfd.Sysfd)
    34  }
    35  
    36  // newFile returns a new File with the given file handle and name.
    37  // Unlike NewFile, it does not check that h is syscall.InvalidHandle.
    38  func newFile(h syscall.Handle, name string, kind string) *File {
    39  	if kind == "file" {
    40  		var m uint32
    41  		if syscall.GetConsoleMode(h, &m) == nil {
    42  			kind = "console"
    43  		}
    44  	}
    45  
    46  	f := &File{&file{
    47  		pfd: poll.FD{
    48  			Sysfd:         h,
    49  			IsStream:      true,
    50  			ZeroReadIsEOF: true,
    51  		},
    52  		name: name,
    53  	}}
    54  	runtime.SetFinalizer(f.file, (*file).close)
    55  
    56  	// Ignore initialization errors.
    57  	// Assume any problems will show up in later I/O.
    58  	f.pfd.Init(kind, false)
    59  
    60  	return f
    61  }
    62  
    63  // newConsoleFile creates new File that will be used as console.
    64  func newConsoleFile(h syscall.Handle, name string) *File {
    65  	return newFile(h, name, "console")
    66  }
    67  
    68  // NewFile returns a new File with the given file descriptor and
    69  // name. The returned value will be nil if fd is not a valid file
    70  // descriptor.
    71  func NewFile(fd uintptr, name string) *File {
    72  	h := syscall.Handle(fd)
    73  	if h == syscall.InvalidHandle {
    74  		return nil
    75  	}
    76  	return newFile(h, name, "file")
    77  }
    78  
    79  // Auxiliary information if the File describes a directory
    80  type dirInfo struct {
    81  	data     syscall.Win32finddata
    82  	needdata bool
    83  	path     string
    84  	isempty  bool // set if FindFirstFile returns ERROR_FILE_NOT_FOUND
    85  }
    86  
    87  func epipecheck(file *File, e error) {
    88  }
    89  
    90  // DevNull is the name of the operating system's ``null device.''
    91  // On Unix-like systems, it is "/dev/null"; on Windows, "NUL".
    92  const DevNull = "NUL"
    93  
    94  func (f *file) isdir() bool { return f != nil && f.dirinfo != nil }
    95  
    96  func openFile(name string, flag int, perm FileMode) (file *File, err error) {
    97  	r, e := syscall.Open(fixLongPath(name), flag|syscall.O_CLOEXEC, syscallMode(perm))
    98  	if e != nil {
    99  		return nil, e
   100  	}
   101  	return newFile(r, name, "file"), nil
   102  }
   103  
   104  func openDir(name string) (file *File, err error) {
   105  	var mask string
   106  
   107  	path := fixLongPath(name)
   108  
   109  	if len(path) == 2 && path[1] == ':' || (len(path) > 0 && path[len(path)-1] == '\\') { // it is a drive letter, like C:
   110  		mask = path + `*`
   111  	} else {
   112  		mask = path + `\*`
   113  	}
   114  	maskp, e := syscall.UTF16PtrFromString(mask)
   115  	if e != nil {
   116  		return nil, e
   117  	}
   118  	d := new(dirInfo)
   119  	r, e := syscall.FindFirstFile(maskp, &d.data)
   120  	if e != nil {
   121  		// FindFirstFile returns ERROR_FILE_NOT_FOUND when
   122  		// no matching files can be found. Then, if directory
   123  		// exists, we should proceed.
   124  		if e != syscall.ERROR_FILE_NOT_FOUND {
   125  			return nil, e
   126  		}
   127  		var fa syscall.Win32FileAttributeData
   128  		pathp, e := syscall.UTF16PtrFromString(path)
   129  		if e != nil {
   130  			return nil, e
   131  		}
   132  		e = syscall.GetFileAttributesEx(pathp, syscall.GetFileExInfoStandard, (*byte)(unsafe.Pointer(&fa)))
   133  		if e != nil {
   134  			return nil, e
   135  		}
   136  		if fa.FileAttributes&syscall.FILE_ATTRIBUTE_DIRECTORY == 0 {
   137  			return nil, e
   138  		}
   139  		d.isempty = true
   140  	}
   141  	d.path = path
   142  	if !isAbs(d.path) {
   143  		d.path, e = syscall.FullPath(d.path)
   144  		if e != nil {
   145  			return nil, e
   146  		}
   147  	}
   148  	f := newFile(r, name, "dir")
   149  	f.dirinfo = d
   150  	return f, nil
   151  }
   152  
   153  // openFileNolog is the Windows implementation of OpenFile.
   154  func openFileNolog(name string, flag int, perm FileMode) (*File, error) {
   155  	if name == "" {
   156  		return nil, &PathError{"open", name, syscall.ENOENT}
   157  	}
   158  	r, errf := openFile(name, flag, perm)
   159  	if errf == nil {
   160  		return r, nil
   161  	}
   162  	r, errd := openDir(name)
   163  	if errd == nil {
   164  		if flag&O_WRONLY != 0 || flag&O_RDWR != 0 {
   165  			r.Close()
   166  			return nil, &PathError{"open", name, syscall.EISDIR}
   167  		}
   168  		return r, nil
   169  	}
   170  	return nil, &PathError{"open", name, errf}
   171  }
   172  
   173  // Close closes the File, rendering it unusable for I/O.
   174  // On files that support SetDeadline, any pending I/O operations will
   175  // be canceled and return immediately with an error.
   176  func (file *File) Close() error {
   177  	if file == nil {
   178  		return ErrInvalid
   179  	}
   180  	return file.file.close()
   181  }
   182  
   183  func (file *file) close() error {
   184  	if file == nil {
   185  		return syscall.EINVAL
   186  	}
   187  	if file.isdir() && file.dirinfo.isempty {
   188  		// "special" empty directories
   189  		return nil
   190  	}
   191  	var err error
   192  	if e := file.pfd.Close(); e != nil {
   193  		if e == poll.ErrFileClosing {
   194  			e = ErrClosed
   195  		}
   196  		err = &PathError{"close", file.name, e}
   197  	}
   198  
   199  	// no need for a finalizer anymore
   200  	runtime.SetFinalizer(file, nil)
   201  	return err
   202  }
   203  
   204  // read reads up to len(b) bytes from the File.
   205  // It returns the number of bytes read and an error, if any.
   206  func (f *File) read(b []byte) (n int, err error) {
   207  	n, err = f.pfd.Read(b)
   208  	runtime.KeepAlive(f)
   209  	return n, err
   210  }
   211  
   212  // pread reads len(b) bytes from the File starting at byte offset off.
   213  // It returns the number of bytes read and the error, if any.
   214  // EOF is signaled by a zero count with err set to 0.
   215  func (f *File) pread(b []byte, off int64) (n int, err error) {
   216  	n, err = f.pfd.Pread(b, off)
   217  	runtime.KeepAlive(f)
   218  	return n, err
   219  }
   220  
   221  // write writes len(b) bytes to the File.
   222  // It returns the number of bytes written and an error, if any.
   223  func (f *File) write(b []byte) (n int, err error) {
   224  	n, err = f.pfd.Write(b)
   225  	runtime.KeepAlive(f)
   226  	return n, err
   227  }
   228  
   229  // pwrite writes len(b) bytes to the File starting at byte offset off.
   230  // It returns the number of bytes written and an error, if any.
   231  func (f *File) pwrite(b []byte, off int64) (n int, err error) {
   232  	n, err = f.pfd.Pwrite(b, off)
   233  	runtime.KeepAlive(f)
   234  	return n, err
   235  }
   236  
   237  // seek sets the offset for the next Read or Write on file to offset, interpreted
   238  // according to whence: 0 means relative to the origin of the file, 1 means
   239  // relative to the current offset, and 2 means relative to the end.
   240  // It returns the new offset and an error, if any.
   241  func (f *File) seek(offset int64, whence int) (ret int64, err error) {
   242  	ret, err = f.pfd.Seek(offset, whence)
   243  	runtime.KeepAlive(f)
   244  	return ret, err
   245  }
   246  
   247  // Truncate changes the size of the named file.
   248  // If the file is a symbolic link, it changes the size of the link's target.
   249  func Truncate(name string, size int64) error {
   250  	f, e := OpenFile(name, O_WRONLY|O_CREATE, 0666)
   251  	if e != nil {
   252  		return e
   253  	}
   254  	defer f.Close()
   255  	e1 := f.Truncate(size)
   256  	if e1 != nil {
   257  		return e1
   258  	}
   259  	return nil
   260  }
   261  
   262  // Remove removes the named file or directory.
   263  // If there is an error, it will be of type *PathError.
   264  func Remove(name string) error {
   265  	p, e := syscall.UTF16PtrFromString(fixLongPath(name))
   266  	if e != nil {
   267  		return &PathError{"remove", name, e}
   268  	}
   269  
   270  	// Go file interface forces us to know whether
   271  	// name is a file or directory. Try both.
   272  	e = syscall.DeleteFile(p)
   273  	if e == nil {
   274  		return nil
   275  	}
   276  	e1 := syscall.RemoveDirectory(p)
   277  	if e1 == nil {
   278  		return nil
   279  	}
   280  
   281  	// Both failed: figure out which error to return.
   282  	if e1 != e {
   283  		a, e2 := syscall.GetFileAttributes(p)
   284  		if e2 != nil {
   285  			e = e2
   286  		} else {
   287  			if a&syscall.FILE_ATTRIBUTE_DIRECTORY != 0 {
   288  				e = e1
   289  			} else if a&syscall.FILE_ATTRIBUTE_READONLY != 0 {
   290  				if e1 = syscall.SetFileAttributes(p, a&^syscall.FILE_ATTRIBUTE_READONLY); e1 == nil {
   291  					if e = syscall.DeleteFile(p); e == nil {
   292  						return nil
   293  					}
   294  				}
   295  			}
   296  		}
   297  	}
   298  	return &PathError{"remove", name, e}
   299  }
   300  
   301  func rename(oldname, newname string) error {
   302  	e := windows.Rename(fixLongPath(oldname), fixLongPath(newname))
   303  	if e != nil {
   304  		return &LinkError{"rename", oldname, newname, e}
   305  	}
   306  	return nil
   307  }
   308  
   309  // Pipe returns a connected pair of Files; reads from r return bytes written to w.
   310  // It returns the files and an error, if any.
   311  func Pipe() (r *File, w *File, err error) {
   312  	var p [2]syscall.Handle
   313  	e := syscall.CreatePipe(&p[0], &p[1], nil, 0)
   314  	if e != nil {
   315  		return nil, nil, NewSyscallError("pipe", e)
   316  	}
   317  	return newFile(p[0], "|0", "file"), newFile(p[1], "|1", "file"), nil
   318  }
   319  
   320  func tempDir() string {
   321  	n := uint32(syscall.MAX_PATH)
   322  	for {
   323  		b := make([]uint16, n)
   324  		n, _ = syscall.GetTempPath(uint32(len(b)), &b[0])
   325  		if n > uint32(len(b)) {
   326  			continue
   327  		}
   328  		if n > 0 && b[n-1] == '\\' {
   329  			n--
   330  		}
   331  		return string(utf16.Decode(b[:n]))
   332  	}
   333  }
   334  
   335  // Link creates newname as a hard link to the oldname file.
   336  // If there is an error, it will be of type *LinkError.
   337  func Link(oldname, newname string) error {
   338  	n, err := syscall.UTF16PtrFromString(fixLongPath(newname))
   339  	if err != nil {
   340  		return &LinkError{"link", oldname, newname, err}
   341  	}
   342  	o, err := syscall.UTF16PtrFromString(fixLongPath(oldname))
   343  	if err != nil {
   344  		return &LinkError{"link", oldname, newname, err}
   345  	}
   346  	err = syscall.CreateHardLink(n, o, 0)
   347  	if err != nil {
   348  		return &LinkError{"link", oldname, newname, err}
   349  	}
   350  	return nil
   351  }
   352  
   353  // Symlink creates newname as a symbolic link to oldname.
   354  // If there is an error, it will be of type *LinkError.
   355  func Symlink(oldname, newname string) error {
   356  	// '/' does not work in link's content
   357  	oldname = fromSlash(oldname)
   358  
   359  	// need the exact location of the oldname when its relative to determine if its a directory
   360  	destpath := oldname
   361  	if !isAbs(oldname) {
   362  		destpath = dirname(newname) + `\` + oldname
   363  	}
   364  
   365  	fi, err := Lstat(destpath)
   366  	isdir := err == nil && fi.IsDir()
   367  
   368  	n, err := syscall.UTF16PtrFromString(fixLongPath(newname))
   369  	if err != nil {
   370  		return &LinkError{"symlink", oldname, newname, err}
   371  	}
   372  	o, err := syscall.UTF16PtrFromString(fixLongPath(oldname))
   373  	if err != nil {
   374  		return &LinkError{"symlink", oldname, newname, err}
   375  	}
   376  
   377  	var flags uint32 = windows.SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE
   378  	if isdir {
   379  		flags |= syscall.SYMBOLIC_LINK_FLAG_DIRECTORY
   380  	}
   381  	err = syscall.CreateSymbolicLink(n, o, flags)
   382  
   383  	if err != nil {
   384  		// the unprivileged create flag is unsupported
   385  		// below Windows 10 (1703, v10.0.14972). retry without it.
   386  		flags &^= windows.SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE
   387  
   388  		err = syscall.CreateSymbolicLink(n, o, flags)
   389  	}
   390  
   391  	if err != nil {
   392  		return &LinkError{"symlink", oldname, newname, err}
   393  	}
   394  	return nil
   395  }
   396  

View as plain text