github.com/euank/go@v0.0.0-20160829210321-495514729181/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/syscall/windows"
     9  	"io"
    10  	"runtime"
    11  	"sync"
    12  	"syscall"
    13  	"unicode/utf16"
    14  	"unicode/utf8"
    15  	"unsafe"
    16  )
    17  
    18  // File represents an open file descriptor.
    19  type File struct {
    20  	*file
    21  }
    22  
    23  // file is the real representation of *File.
    24  // The extra level of indirection ensures that no clients of os
    25  // can overwrite this data, which could cause the finalizer
    26  // to close the wrong file descriptor.
    27  type file struct {
    28  	fd      syscall.Handle
    29  	name    string
    30  	dirinfo *dirInfo   // nil unless directory being read
    31  	l       sync.Mutex // used to implement windows pread/pwrite
    32  
    33  	// only for console io
    34  	isConsole bool
    35  	lastbits  []byte // first few bytes of the last incomplete rune in last write
    36  	readbuf   []rune // input console buffer
    37  }
    38  
    39  // Fd returns the Windows handle referencing the open file.
    40  // The handle is valid only until f.Close is called or f is garbage collected.
    41  func (file *File) Fd() uintptr {
    42  	if file == nil {
    43  		return uintptr(syscall.InvalidHandle)
    44  	}
    45  	return uintptr(file.fd)
    46  }
    47  
    48  // newFile returns a new File with the given file handle and name.
    49  // Unlike NewFile, it does not check that h is syscall.InvalidHandle.
    50  func newFile(h syscall.Handle, name string) *File {
    51  	f := &File{&file{fd: h, name: name}}
    52  	var m uint32
    53  	if syscall.GetConsoleMode(f.fd, &m) == nil {
    54  		f.isConsole = true
    55  	}
    56  	runtime.SetFinalizer(f.file, (*file).close)
    57  	return f
    58  }
    59  
    60  // NewFile returns a new File with the given file descriptor and name.
    61  func NewFile(fd uintptr, name string) *File {
    62  	h := syscall.Handle(fd)
    63  	if h == syscall.InvalidHandle {
    64  		return nil
    65  	}
    66  	return newFile(h, name)
    67  }
    68  
    69  // Auxiliary information if the File describes a directory
    70  type dirInfo struct {
    71  	data     syscall.Win32finddata
    72  	needdata bool
    73  	path     string
    74  	isempty  bool // set if FindFirstFile returns ERROR_FILE_NOT_FOUND
    75  }
    76  
    77  func epipecheck(file *File, e error) {
    78  }
    79  
    80  const DevNull = "NUL"
    81  
    82  func (f *file) isdir() bool { return f != nil && f.dirinfo != nil }
    83  
    84  func openFile(name string, flag int, perm FileMode) (file *File, err error) {
    85  	r, e := syscall.Open(name, flag|syscall.O_CLOEXEC, syscallMode(perm))
    86  	if e != nil {
    87  		return nil, e
    88  	}
    89  	return NewFile(uintptr(r), name), nil
    90  }
    91  
    92  func openDir(name string) (file *File, err error) {
    93  	var mask string
    94  	if len(name) == 2 && name[1] == ':' { // it is a drive letter, like C:
    95  		mask = name + `*`
    96  	} else {
    97  		mask = name + `\*`
    98  	}
    99  	maskp, e := syscall.UTF16PtrFromString(mask)
   100  	if e != nil {
   101  		return nil, e
   102  	}
   103  	d := new(dirInfo)
   104  	r, e := syscall.FindFirstFile(maskp, &d.data)
   105  	if e != nil {
   106  		// FindFirstFile returns ERROR_FILE_NOT_FOUND when
   107  		// no matching files can be found. Then, if directory
   108  		// exists, we should proceed.
   109  		if e != syscall.ERROR_FILE_NOT_FOUND {
   110  			return nil, e
   111  		}
   112  		var fa syscall.Win32FileAttributeData
   113  		namep, e := syscall.UTF16PtrFromString(name)
   114  		if e != nil {
   115  			return nil, e
   116  		}
   117  		e = syscall.GetFileAttributesEx(namep, syscall.GetFileExInfoStandard, (*byte)(unsafe.Pointer(&fa)))
   118  		if e != nil {
   119  			return nil, e
   120  		}
   121  		if fa.FileAttributes&syscall.FILE_ATTRIBUTE_DIRECTORY == 0 {
   122  			return nil, e
   123  		}
   124  		d.isempty = true
   125  	}
   126  	d.path = name
   127  	if !isAbs(d.path) {
   128  		d.path, e = syscall.FullPath(d.path)
   129  		if e != nil {
   130  			return nil, e
   131  		}
   132  	}
   133  	f := newFile(r, name)
   134  	f.dirinfo = d
   135  	return f, nil
   136  }
   137  
   138  // OpenFile is the generalized open call; most users will use Open
   139  // or Create instead. It opens the named file with specified flag
   140  // (O_RDONLY etc.) and perm, (0666 etc.) if applicable. If successful,
   141  // methods on the returned File can be used for I/O.
   142  // If there is an error, it will be of type *PathError.
   143  func OpenFile(name string, flag int, perm FileMode) (*File, error) {
   144  	if name == "" {
   145  		return nil, &PathError{"open", name, syscall.ENOENT}
   146  	}
   147  	r, errf := openFile(name, flag, perm)
   148  	if errf == nil {
   149  		return r, nil
   150  	}
   151  	r, errd := openDir(name)
   152  	if errd == nil {
   153  		if flag&O_WRONLY != 0 || flag&O_RDWR != 0 {
   154  			r.Close()
   155  			return nil, &PathError{"open", name, syscall.EISDIR}
   156  		}
   157  		return r, nil
   158  	}
   159  	return nil, &PathError{"open", name, errf}
   160  }
   161  
   162  // Close closes the File, rendering it unusable for I/O.
   163  // It returns an error, if any.
   164  func (file *File) Close() error {
   165  	if file == nil {
   166  		return ErrInvalid
   167  	}
   168  	return file.file.close()
   169  }
   170  
   171  func (file *file) close() error {
   172  	if file == nil {
   173  		return syscall.EINVAL
   174  	}
   175  	if file.isdir() && file.dirinfo.isempty {
   176  		// "special" empty directories
   177  		return nil
   178  	}
   179  	if file.fd == syscall.InvalidHandle {
   180  		return syscall.EINVAL
   181  	}
   182  	var e error
   183  	if file.isdir() {
   184  		e = syscall.FindClose(file.fd)
   185  	} else {
   186  		e = syscall.CloseHandle(file.fd)
   187  	}
   188  	var err error
   189  	if e != nil {
   190  		err = &PathError{"close", file.name, e}
   191  	}
   192  	file.fd = syscall.InvalidHandle // so it can't be closed again
   193  
   194  	// no need for a finalizer anymore
   195  	runtime.SetFinalizer(file, nil)
   196  	return err
   197  }
   198  
   199  // readConsole reads utf16 characters from console File,
   200  // encodes them into utf8 and stores them in buffer b.
   201  // It returns the number of utf8 bytes read and an error, if any.
   202  func (f *File) readConsole(b []byte) (n int, err error) {
   203  	if len(b) == 0 {
   204  		return 0, nil
   205  	}
   206  	if len(f.readbuf) == 0 {
   207  		numBytes := len(b)
   208  		// Windows  can't read bytes over max of int16.
   209  		// Some versions of Windows can read even less.
   210  		// See golang.org/issue/13697.
   211  		if numBytes > 10000 {
   212  			numBytes = 10000
   213  		}
   214  		mbytes := make([]byte, numBytes)
   215  		var nmb uint32
   216  		err := syscall.ReadFile(f.fd, mbytes, &nmb, nil)
   217  		if err != nil {
   218  			return 0, err
   219  		}
   220  		if nmb > 0 {
   221  			var pmb *byte
   222  			if len(b) > 0 {
   223  				pmb = &mbytes[0]
   224  			}
   225  			acp := windows.GetACP()
   226  			nwc, err := windows.MultiByteToWideChar(acp, 2, pmb, int32(nmb), nil, 0)
   227  			if err != nil {
   228  				return 0, err
   229  			}
   230  			wchars := make([]uint16, nwc)
   231  			pwc := &wchars[0]
   232  			nwc, err = windows.MultiByteToWideChar(acp, 2, pmb, int32(nmb), pwc, nwc)
   233  			if err != nil {
   234  				return 0, err
   235  			}
   236  			f.readbuf = utf16.Decode(wchars[:nwc])
   237  		}
   238  	}
   239  	for i, r := range f.readbuf {
   240  		if utf8.RuneLen(r) > len(b) {
   241  			f.readbuf = f.readbuf[i:]
   242  			return n, nil
   243  		}
   244  		nr := utf8.EncodeRune(b, r)
   245  		b = b[nr:]
   246  		n += nr
   247  	}
   248  	f.readbuf = nil
   249  	return n, nil
   250  }
   251  
   252  // read reads up to len(b) bytes from the File.
   253  // It returns the number of bytes read and an error, if any.
   254  func (f *File) read(b []byte) (n int, err error) {
   255  	f.l.Lock()
   256  	defer f.l.Unlock()
   257  	if f.isConsole {
   258  		return f.readConsole(b)
   259  	}
   260  	return fixCount(syscall.Read(f.fd, b))
   261  }
   262  
   263  // pread reads len(b) bytes from the File starting at byte offset off.
   264  // It returns the number of bytes read and the error, if any.
   265  // EOF is signaled by a zero count with err set to 0.
   266  func (f *File) pread(b []byte, off int64) (n int, err error) {
   267  	f.l.Lock()
   268  	defer f.l.Unlock()
   269  	curoffset, e := syscall.Seek(f.fd, 0, io.SeekCurrent)
   270  	if e != nil {
   271  		return 0, e
   272  	}
   273  	defer syscall.Seek(f.fd, curoffset, io.SeekStart)
   274  	o := syscall.Overlapped{
   275  		OffsetHigh: uint32(off >> 32),
   276  		Offset:     uint32(off),
   277  	}
   278  	var done uint32
   279  	e = syscall.ReadFile(f.fd, b, &done, &o)
   280  	if e != nil {
   281  		if e == syscall.ERROR_HANDLE_EOF {
   282  			// end of file
   283  			return 0, nil
   284  		}
   285  		return 0, e
   286  	}
   287  	return int(done), nil
   288  }
   289  
   290  // writeConsole writes len(b) bytes to the console File.
   291  // It returns the number of bytes written and an error, if any.
   292  func (f *File) writeConsole(b []byte) (n int, err error) {
   293  	n = len(b)
   294  	runes := make([]rune, 0, 256)
   295  	if len(f.lastbits) > 0 {
   296  		b = append(f.lastbits, b...)
   297  		f.lastbits = nil
   298  
   299  	}
   300  	for len(b) >= utf8.UTFMax || utf8.FullRune(b) {
   301  		r, l := utf8.DecodeRune(b)
   302  		runes = append(runes, r)
   303  		b = b[l:]
   304  	}
   305  	if len(b) > 0 {
   306  		f.lastbits = make([]byte, len(b))
   307  		copy(f.lastbits, b)
   308  	}
   309  	// syscall.WriteConsole seems to fail, if given large buffer.
   310  	// So limit the buffer to 16000 characters. This number was
   311  	// discovered by experimenting with syscall.WriteConsole.
   312  	const maxWrite = 16000
   313  	for len(runes) > 0 {
   314  		m := len(runes)
   315  		if m > maxWrite {
   316  			m = maxWrite
   317  		}
   318  		chunk := runes[:m]
   319  		runes = runes[m:]
   320  		uint16s := utf16.Encode(chunk)
   321  		for len(uint16s) > 0 {
   322  			var written uint32
   323  			err = syscall.WriteConsole(f.fd, &uint16s[0], uint32(len(uint16s)), &written, nil)
   324  			if err != nil {
   325  				return 0, nil
   326  			}
   327  			uint16s = uint16s[written:]
   328  		}
   329  	}
   330  	return n, nil
   331  }
   332  
   333  // write writes len(b) bytes to the File.
   334  // It returns the number of bytes written and an error, if any.
   335  func (f *File) write(b []byte) (n int, err error) {
   336  	f.l.Lock()
   337  	defer f.l.Unlock()
   338  	if f.isConsole {
   339  		return f.writeConsole(b)
   340  	}
   341  	return fixCount(syscall.Write(f.fd, b))
   342  }
   343  
   344  // pwrite writes len(b) bytes to the File starting at byte offset off.
   345  // It returns the number of bytes written and an error, if any.
   346  func (f *File) pwrite(b []byte, off int64) (n int, err error) {
   347  	f.l.Lock()
   348  	defer f.l.Unlock()
   349  	curoffset, e := syscall.Seek(f.fd, 0, io.SeekCurrent)
   350  	if e != nil {
   351  		return 0, e
   352  	}
   353  	defer syscall.Seek(f.fd, curoffset, io.SeekStart)
   354  	o := syscall.Overlapped{
   355  		OffsetHigh: uint32(off >> 32),
   356  		Offset:     uint32(off),
   357  	}
   358  	var done uint32
   359  	e = syscall.WriteFile(f.fd, b, &done, &o)
   360  	if e != nil {
   361  		return 0, e
   362  	}
   363  	return int(done), nil
   364  }
   365  
   366  // seek sets the offset for the next Read or Write on file to offset, interpreted
   367  // according to whence: 0 means relative to the origin of the file, 1 means
   368  // relative to the current offset, and 2 means relative to the end.
   369  // It returns the new offset and an error, if any.
   370  func (f *File) seek(offset int64, whence int) (ret int64, err error) {
   371  	f.l.Lock()
   372  	defer f.l.Unlock()
   373  	return syscall.Seek(f.fd, offset, whence)
   374  }
   375  
   376  // Truncate changes the size of the named file.
   377  // If the file is a symbolic link, it changes the size of the link's target.
   378  func Truncate(name string, size int64) error {
   379  	f, e := OpenFile(name, O_WRONLY|O_CREATE, 0666)
   380  	if e != nil {
   381  		return e
   382  	}
   383  	defer f.Close()
   384  	e1 := f.Truncate(size)
   385  	if e1 != nil {
   386  		return e1
   387  	}
   388  	return nil
   389  }
   390  
   391  // Remove removes the named file or directory.
   392  // If there is an error, it will be of type *PathError.
   393  func Remove(name string) error {
   394  	p, e := syscall.UTF16PtrFromString(name)
   395  	if e != nil {
   396  		return &PathError{"remove", name, e}
   397  	}
   398  
   399  	// Go file interface forces us to know whether
   400  	// name is a file or directory. Try both.
   401  	e = syscall.DeleteFile(p)
   402  	if e == nil {
   403  		return nil
   404  	}
   405  	e1 := syscall.RemoveDirectory(p)
   406  	if e1 == nil {
   407  		return nil
   408  	}
   409  
   410  	// Both failed: figure out which error to return.
   411  	if e1 != e {
   412  		a, e2 := syscall.GetFileAttributes(p)
   413  		if e2 != nil {
   414  			e = e2
   415  		} else {
   416  			if a&syscall.FILE_ATTRIBUTE_DIRECTORY != 0 {
   417  				e = e1
   418  			} else if a&syscall.FILE_ATTRIBUTE_READONLY != 0 {
   419  				if e1 = syscall.SetFileAttributes(p, a&^syscall.FILE_ATTRIBUTE_READONLY); e1 == nil {
   420  					if e = syscall.DeleteFile(p); e == nil {
   421  						return nil
   422  					}
   423  				}
   424  			}
   425  		}
   426  	}
   427  	return &PathError{"remove", name, e}
   428  }
   429  
   430  func rename(oldname, newname string) error {
   431  	e := windows.Rename(oldname, newname)
   432  	if e != nil {
   433  		return &LinkError{"rename", oldname, newname, e}
   434  	}
   435  	return nil
   436  }
   437  
   438  // Pipe returns a connected pair of Files; reads from r return bytes written to w.
   439  // It returns the files and an error, if any.
   440  func Pipe() (r *File, w *File, err error) {
   441  	var p [2]syscall.Handle
   442  
   443  	// See ../syscall/exec.go for description of lock.
   444  	syscall.ForkLock.RLock()
   445  	e := syscall.Pipe(p[0:])
   446  	if e != nil {
   447  		syscall.ForkLock.RUnlock()
   448  		return nil, nil, NewSyscallError("pipe", e)
   449  	}
   450  	syscall.CloseOnExec(p[0])
   451  	syscall.CloseOnExec(p[1])
   452  	syscall.ForkLock.RUnlock()
   453  
   454  	return NewFile(uintptr(p[0]), "|0"), NewFile(uintptr(p[1]), "|1"), nil
   455  }
   456  
   457  // TempDir returns the default directory to use for temporary files.
   458  func TempDir() string {
   459  	n := uint32(syscall.MAX_PATH)
   460  	for {
   461  		b := make([]uint16, n)
   462  		n, _ = syscall.GetTempPath(uint32(len(b)), &b[0])
   463  		if n > uint32(len(b)) {
   464  			continue
   465  		}
   466  		if n > 0 && b[n-1] == '\\' {
   467  			n--
   468  		}
   469  		return string(utf16.Decode(b[:n]))
   470  	}
   471  }
   472  
   473  // Link creates newname as a hard link to the oldname file.
   474  // If there is an error, it will be of type *LinkError.
   475  func Link(oldname, newname string) error {
   476  	n, err := syscall.UTF16PtrFromString(newname)
   477  	if err != nil {
   478  		return &LinkError{"link", oldname, newname, err}
   479  	}
   480  	o, err := syscall.UTF16PtrFromString(oldname)
   481  	if err != nil {
   482  		return &LinkError{"link", oldname, newname, err}
   483  	}
   484  	err = syscall.CreateHardLink(n, o, 0)
   485  	if err != nil {
   486  		return &LinkError{"link", oldname, newname, err}
   487  	}
   488  	return nil
   489  }
   490  
   491  // Symlink creates newname as a symbolic link to oldname.
   492  // If there is an error, it will be of type *LinkError.
   493  func Symlink(oldname, newname string) error {
   494  	// CreateSymbolicLink is not supported before Windows Vista
   495  	if syscall.LoadCreateSymbolicLink() != nil {
   496  		return &LinkError{"symlink", oldname, newname, syscall.EWINDOWS}
   497  	}
   498  
   499  	// '/' does not work in link's content
   500  	oldname = fromSlash(oldname)
   501  
   502  	// need the exact location of the oldname when its relative to determine if its a directory
   503  	destpath := oldname
   504  	if !isAbs(oldname) {
   505  		destpath = dirname(newname) + `\` + oldname
   506  	}
   507  
   508  	fi, err := Lstat(destpath)
   509  	isdir := err == nil && fi.IsDir()
   510  
   511  	n, err := syscall.UTF16PtrFromString(newname)
   512  	if err != nil {
   513  		return &LinkError{"symlink", oldname, newname, err}
   514  	}
   515  	o, err := syscall.UTF16PtrFromString(oldname)
   516  	if err != nil {
   517  		return &LinkError{"symlink", oldname, newname, err}
   518  	}
   519  
   520  	var flags uint32
   521  	if isdir {
   522  		flags |= syscall.SYMBOLIC_LINK_FLAG_DIRECTORY
   523  	}
   524  	err = syscall.CreateSymbolicLink(n, o, flags)
   525  	if err != nil {
   526  		return &LinkError{"symlink", oldname, newname, err}
   527  	}
   528  	return nil
   529  }