github.com/karrick/go@v0.0.0-20170817181416-d5b0ec858b37/src/os/file_windows.go (about)

     1  // Copyright 2009 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  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  func (file *File) Fd() uintptr {
    29  	if file == nil {
    30  		return uintptr(syscall.InvalidHandle)
    31  	}
    32  	return uintptr(file.pfd.Sysfd)
    33  }
    34  
    35  // newFile returns a new File with the given file handle and name.
    36  // Unlike NewFile, it does not check that h is syscall.InvalidHandle.
    37  func newFile(h syscall.Handle, name string, kind string) *File {
    38  	if kind == "file" {
    39  		var m uint32
    40  		if syscall.GetConsoleMode(h, &m) == nil {
    41  			kind = "console"
    42  		}
    43  	}
    44  
    45  	f := &File{&file{
    46  		pfd: poll.FD{
    47  			Sysfd:         h,
    48  			IsStream:      true,
    49  			ZeroReadIsEOF: true,
    50  		},
    51  		name: name,
    52  	}}
    53  	runtime.SetFinalizer(f.file, (*file).close)
    54  
    55  	// Ignore initialization errors.
    56  	// Assume any problems will show up in later I/O.
    57  	f.pfd.Init(kind)
    58  
    59  	return f
    60  }
    61  
    62  // newConsoleFile creates new File that will be used as console.
    63  func newConsoleFile(h syscall.Handle, name string) *File {
    64  	return newFile(h, name, "console")
    65  }
    66  
    67  // NewFile returns a new File with the given file descriptor and
    68  // name. The returned value will be nil if fd is not a valid file
    69  // descriptor.
    70  func NewFile(fd uintptr, name string) *File {
    71  	h := syscall.Handle(fd)
    72  	if h == syscall.InvalidHandle {
    73  		return nil
    74  	}
    75  	return newFile(h, name, "file")
    76  }
    77  
    78  // Auxiliary information if the File describes a directory
    79  type dirInfo struct {
    80  	data     syscall.Win32finddata
    81  	needdata bool
    82  	path     string
    83  	isempty  bool // set if FindFirstFile returns ERROR_FILE_NOT_FOUND
    84  }
    85  
    86  func epipecheck(file *File, e error) {
    87  }
    88  
    89  const DevNull = "NUL"
    90  
    91  func (f *file) isdir() bool { return f != nil && f.dirinfo != nil }
    92  
    93  func openFile(name string, flag int, perm FileMode) (file *File, err error) {
    94  	r, e := syscall.Open(fixLongPath(name), flag|syscall.O_CLOEXEC, syscallMode(perm))
    95  	if e != nil {
    96  		return nil, e
    97  	}
    98  	return newFile(r, name, "file"), nil
    99  }
   100  
   101  func openDir(name string) (file *File, err error) {
   102  	var mask string
   103  
   104  	path := fixLongPath(name)
   105  
   106  	if len(path) == 2 && path[1] == ':' || (len(path) > 0 && path[len(path)-1] == '\\') { // it is a drive letter, like C:
   107  		mask = path + `*`
   108  	} else {
   109  		mask = path + `\*`
   110  	}
   111  	maskp, e := syscall.UTF16PtrFromString(mask)
   112  	if e != nil {
   113  		return nil, e
   114  	}
   115  	d := new(dirInfo)
   116  	r, e := syscall.FindFirstFile(maskp, &d.data)
   117  	if e != nil {
   118  		// FindFirstFile returns ERROR_FILE_NOT_FOUND when
   119  		// no matching files can be found. Then, if directory
   120  		// exists, we should proceed.
   121  		if e != syscall.ERROR_FILE_NOT_FOUND {
   122  			return nil, e
   123  		}
   124  		var fa syscall.Win32FileAttributeData
   125  		pathp, e := syscall.UTF16PtrFromString(path)
   126  		if e != nil {
   127  			return nil, e
   128  		}
   129  		e = syscall.GetFileAttributesEx(pathp, syscall.GetFileExInfoStandard, (*byte)(unsafe.Pointer(&fa)))
   130  		if e != nil {
   131  			return nil, e
   132  		}
   133  		if fa.FileAttributes&syscall.FILE_ATTRIBUTE_DIRECTORY == 0 {
   134  			return nil, e
   135  		}
   136  		d.isempty = true
   137  	}
   138  	d.path = path
   139  	if !isAbs(d.path) {
   140  		d.path, e = syscall.FullPath(d.path)
   141  		if e != nil {
   142  			return nil, e
   143  		}
   144  	}
   145  	f := newFile(r, name, "dir")
   146  	f.dirinfo = d
   147  	return f, nil
   148  }
   149  
   150  // OpenFile is the generalized open call; most users will use Open
   151  // or Create instead. It opens the named file with specified flag
   152  // (O_RDONLY etc.) and perm, (0666 etc.) if applicable. If successful,
   153  // methods on the returned File can be used for I/O.
   154  // If there is an error, it will be of type *PathError.
   155  func OpenFile(name string, flag int, perm FileMode) (*File, error) {
   156  	if name == "" {
   157  		return nil, &PathError{"open", name, syscall.ENOENT}
   158  	}
   159  	r, errf := openFile(name, flag, perm)
   160  	if errf == nil {
   161  		return r, nil
   162  	}
   163  	r, errd := openDir(name)
   164  	if errd == nil {
   165  		if flag&O_WRONLY != 0 || flag&O_RDWR != 0 {
   166  			r.Close()
   167  			return nil, &PathError{"open", name, syscall.EISDIR}
   168  		}
   169  		return r, nil
   170  	}
   171  	return nil, &PathError{"open", name, errf}
   172  }
   173  
   174  // Close closes the File, rendering it unusable for I/O.
   175  // It returns an error, if any.
   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  
   314  	// See ../syscall/exec.go for description of lock.
   315  	syscall.ForkLock.RLock()
   316  	e := syscall.Pipe(p[0:])
   317  	if e != nil {
   318  		syscall.ForkLock.RUnlock()
   319  		return nil, nil, NewSyscallError("pipe", e)
   320  	}
   321  	syscall.CloseOnExec(p[0])
   322  	syscall.CloseOnExec(p[1])
   323  	syscall.ForkLock.RUnlock()
   324  
   325  	return newFile(p[0], "|0", "file"), newFile(p[1], "|1", "file"), nil
   326  }
   327  
   328  func tempDir() string {
   329  	n := uint32(syscall.MAX_PATH)
   330  	for {
   331  		b := make([]uint16, n)
   332  		n, _ = syscall.GetTempPath(uint32(len(b)), &b[0])
   333  		if n > uint32(len(b)) {
   334  			continue
   335  		}
   336  		if n > 0 && b[n-1] == '\\' {
   337  			n--
   338  		}
   339  		return string(utf16.Decode(b[:n]))
   340  	}
   341  }
   342  
   343  // Link creates newname as a hard link to the oldname file.
   344  // If there is an error, it will be of type *LinkError.
   345  func Link(oldname, newname string) error {
   346  	n, err := syscall.UTF16PtrFromString(fixLongPath(newname))
   347  	if err != nil {
   348  		return &LinkError{"link", oldname, newname, err}
   349  	}
   350  	o, err := syscall.UTF16PtrFromString(fixLongPath(oldname))
   351  	if err != nil {
   352  		return &LinkError{"link", oldname, newname, err}
   353  	}
   354  	err = syscall.CreateHardLink(n, o, 0)
   355  	if err != nil {
   356  		return &LinkError{"link", oldname, newname, err}
   357  	}
   358  	return nil
   359  }
   360  
   361  // Symlink creates newname as a symbolic link to oldname.
   362  // If there is an error, it will be of type *LinkError.
   363  func Symlink(oldname, newname string) error {
   364  	// CreateSymbolicLink is not supported before Windows Vista
   365  	if syscall.LoadCreateSymbolicLink() != nil {
   366  		return &LinkError{"symlink", oldname, newname, syscall.EWINDOWS}
   367  	}
   368  
   369  	// '/' does not work in link's content
   370  	oldname = fromSlash(oldname)
   371  
   372  	// need the exact location of the oldname when its relative to determine if its a directory
   373  	destpath := oldname
   374  	if !isAbs(oldname) {
   375  		destpath = dirname(newname) + `\` + oldname
   376  	}
   377  
   378  	fi, err := Lstat(destpath)
   379  	isdir := err == nil && fi.IsDir()
   380  
   381  	n, err := syscall.UTF16PtrFromString(fixLongPath(newname))
   382  	if err != nil {
   383  		return &LinkError{"symlink", oldname, newname, err}
   384  	}
   385  	o, err := syscall.UTF16PtrFromString(fixLongPath(oldname))
   386  	if err != nil {
   387  		return &LinkError{"symlink", oldname, newname, err}
   388  	}
   389  
   390  	var flags uint32
   391  	if isdir {
   392  		flags |= syscall.SYMBOLIC_LINK_FLAG_DIRECTORY
   393  	}
   394  	err = syscall.CreateSymbolicLink(n, o, flags)
   395  	if err != nil {
   396  		return &LinkError{"symlink", oldname, newname, err}
   397  	}
   398  	return nil
   399  }