github.com/goproxy0/go@v0.0.0-20171111080102-49cc0c489d2c/src/os/file_unix.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  // +build darwin dragonfly freebsd linux nacl netbsd openbsd solaris
     6  
     7  package os
     8  
     9  import (
    10  	"internal/poll"
    11  	"runtime"
    12  	"syscall"
    13  )
    14  
    15  // fixLongPath is a noop on non-Windows platforms.
    16  func fixLongPath(path string) string {
    17  	return path
    18  }
    19  
    20  func rename(oldname, newname string) error {
    21  	fi, err := Lstat(newname)
    22  	if err == nil && fi.IsDir() {
    23  		// There are two independent errors this function can return:
    24  		// one for a bad oldname, and one for a bad newname.
    25  		// At this point we've determined the newname is bad.
    26  		// But just in case oldname is also bad, prioritize returning
    27  		// the oldname error because that's what we did historically.
    28  		if _, err := Lstat(oldname); err != nil {
    29  			if pe, ok := err.(*PathError); ok {
    30  				err = pe.Err
    31  			}
    32  			return &LinkError{"rename", oldname, newname, err}
    33  		}
    34  		return &LinkError{"rename", oldname, newname, syscall.EEXIST}
    35  	}
    36  	err = syscall.Rename(oldname, newname)
    37  	if err != nil {
    38  		return &LinkError{"rename", oldname, newname, err}
    39  	}
    40  	return nil
    41  }
    42  
    43  // file is the real representation of *File.
    44  // The extra level of indirection ensures that no clients of os
    45  // can overwrite this data, which could cause the finalizer
    46  // to close the wrong file descriptor.
    47  type file struct {
    48  	pfd         poll.FD
    49  	name        string
    50  	dirinfo     *dirInfo // nil unless directory being read
    51  	nonblock    bool     // whether we set nonblocking mode
    52  	stdoutOrErr bool     // whether this is stdout or stderr
    53  }
    54  
    55  // Fd returns the integer Unix file descriptor referencing the open file.
    56  // The file descriptor is valid only until f.Close is called or f is garbage collected.
    57  func (f *File) Fd() uintptr {
    58  	if f == nil {
    59  		return ^(uintptr(0))
    60  	}
    61  
    62  	// If we put the file descriptor into nonblocking mode,
    63  	// then set it to blocking mode before we return it,
    64  	// because historically we have always returned a descriptor
    65  	// opened in blocking mode. The File will continue to work,
    66  	// but any blocking operation will tie up a thread.
    67  	if f.nonblock {
    68  		syscall.SetNonblock(f.pfd.Sysfd, false)
    69  	}
    70  
    71  	return uintptr(f.pfd.Sysfd)
    72  }
    73  
    74  // NewFile returns a new File with the given file descriptor and
    75  // name. The returned value will be nil if fd is not a valid file
    76  // descriptor.
    77  func NewFile(fd uintptr, name string) *File {
    78  	return newFile(fd, name, kindNewFile)
    79  }
    80  
    81  // newFileKind describes the kind of file to newFile.
    82  type newFileKind int
    83  
    84  const (
    85  	kindNewFile newFileKind = iota
    86  	kindOpenFile
    87  	kindPipe
    88  )
    89  
    90  // newFile is like NewFile, but if called from OpenFile or Pipe
    91  // (as passed in the kind parameter) it tries to add the file to
    92  // the runtime poller.
    93  func newFile(fd uintptr, name string, kind newFileKind) *File {
    94  	fdi := int(fd)
    95  	if fdi < 0 {
    96  		return nil
    97  	}
    98  	f := &File{&file{
    99  		pfd: poll.FD{
   100  			Sysfd:         fdi,
   101  			IsStream:      true,
   102  			ZeroReadIsEOF: true,
   103  		},
   104  		name:        name,
   105  		stdoutOrErr: fdi == 1 || fdi == 2,
   106  	}}
   107  
   108  	// Don't try to use kqueue with regular files on FreeBSD.
   109  	// It crashes the system unpredictably while running all.bash.
   110  	// Issue 19093.
   111  	if runtime.GOOS == "freebsd" && kind == kindOpenFile {
   112  		kind = kindNewFile
   113  	}
   114  
   115  	pollable := kind == kindOpenFile || kind == kindPipe
   116  	if err := f.pfd.Init("file", pollable); err != nil {
   117  		// An error here indicates a failure to register
   118  		// with the netpoll system. That can happen for
   119  		// a file descriptor that is not supported by
   120  		// epoll/kqueue; for example, disk files on
   121  		// GNU/Linux systems. We assume that any real error
   122  		// will show up in later I/O.
   123  	} else if pollable {
   124  		// We successfully registered with netpoll, so put
   125  		// the file into nonblocking mode.
   126  		if err := syscall.SetNonblock(fdi, true); err == nil {
   127  			f.nonblock = true
   128  		}
   129  	}
   130  
   131  	runtime.SetFinalizer(f.file, (*file).close)
   132  	return f
   133  }
   134  
   135  // Auxiliary information if the File describes a directory
   136  type dirInfo struct {
   137  	buf  []byte // buffer for directory I/O
   138  	nbuf int    // length of buf; return value from Getdirentries
   139  	bufp int    // location of next record in buf.
   140  }
   141  
   142  // epipecheck raises SIGPIPE if we get an EPIPE error on standard
   143  // output or standard error. See the SIGPIPE docs in os/signal, and
   144  // issue 11845.
   145  func epipecheck(file *File, e error) {
   146  	if e == syscall.EPIPE && file.stdoutOrErr {
   147  		sigpipe()
   148  	}
   149  }
   150  
   151  // DevNull is the name of the operating system's ``null device.''
   152  // On Unix-like systems, it is "/dev/null"; on Windows, "NUL".
   153  const DevNull = "/dev/null"
   154  
   155  // OpenFile is the generalized open call; most users will use Open
   156  // or Create instead. It opens the named file with specified flag
   157  // (O_RDONLY etc.) and perm, (0666 etc.) if applicable. If successful,
   158  // methods on the returned File can be used for I/O.
   159  // If there is an error, it will be of type *PathError.
   160  func OpenFile(name string, flag int, perm FileMode) (*File, error) {
   161  	chmod := false
   162  	if !supportsCreateWithStickyBit && flag&O_CREATE != 0 && perm&ModeSticky != 0 {
   163  		if _, err := Stat(name); IsNotExist(err) {
   164  			chmod = true
   165  		}
   166  	}
   167  
   168  	var r int
   169  	for {
   170  		var e error
   171  		r, e = syscall.Open(name, flag|syscall.O_CLOEXEC, syscallMode(perm))
   172  		if e == nil {
   173  			break
   174  		}
   175  
   176  		// On OS X, sigaction(2) doesn't guarantee that SA_RESTART will cause
   177  		// open(2) to be restarted for regular files. This is easy to reproduce on
   178  		// fuse file systems (see http://golang.org/issue/11180).
   179  		if runtime.GOOS == "darwin" && e == syscall.EINTR {
   180  			continue
   181  		}
   182  
   183  		return nil, &PathError{"open", name, e}
   184  	}
   185  
   186  	// open(2) itself won't handle the sticky bit on *BSD and Solaris
   187  	if chmod {
   188  		Chmod(name, perm)
   189  	}
   190  
   191  	// There's a race here with fork/exec, which we are
   192  	// content to live with. See ../syscall/exec_unix.go.
   193  	if !supportsCloseOnExec {
   194  		syscall.CloseOnExec(r)
   195  	}
   196  
   197  	return newFile(uintptr(r), name, kindOpenFile), nil
   198  }
   199  
   200  // Close closes the File, rendering it unusable for I/O.
   201  // It returns an error, if any.
   202  func (f *File) Close() error {
   203  	if f == nil {
   204  		return ErrInvalid
   205  	}
   206  	return f.file.close()
   207  }
   208  
   209  func (file *file) close() error {
   210  	if file == nil {
   211  		return syscall.EINVAL
   212  	}
   213  	var err error
   214  	if e := file.pfd.Close(); e != nil {
   215  		if e == poll.ErrFileClosing {
   216  			e = ErrClosed
   217  		}
   218  		err = &PathError{"close", file.name, e}
   219  	}
   220  
   221  	// no need for a finalizer anymore
   222  	runtime.SetFinalizer(file, nil)
   223  	return err
   224  }
   225  
   226  // read reads up to len(b) bytes from the File.
   227  // It returns the number of bytes read and an error, if any.
   228  func (f *File) read(b []byte) (n int, err error) {
   229  	n, err = f.pfd.Read(b)
   230  	runtime.KeepAlive(f)
   231  	return n, err
   232  }
   233  
   234  // pread reads len(b) bytes from the File starting at byte offset off.
   235  // It returns the number of bytes read and the error, if any.
   236  // EOF is signaled by a zero count with err set to nil.
   237  func (f *File) pread(b []byte, off int64) (n int, err error) {
   238  	n, err = f.pfd.Pread(b, off)
   239  	runtime.KeepAlive(f)
   240  	return n, err
   241  }
   242  
   243  // write writes len(b) bytes to the File.
   244  // It returns the number of bytes written and an error, if any.
   245  func (f *File) write(b []byte) (n int, err error) {
   246  	n, err = f.pfd.Write(b)
   247  	runtime.KeepAlive(f)
   248  	return n, err
   249  }
   250  
   251  // pwrite writes len(b) bytes to the File starting at byte offset off.
   252  // It returns the number of bytes written and an error, if any.
   253  func (f *File) pwrite(b []byte, off int64) (n int, err error) {
   254  	n, err = f.pfd.Pwrite(b, off)
   255  	runtime.KeepAlive(f)
   256  	return n, err
   257  }
   258  
   259  // seek sets the offset for the next Read or Write on file to offset, interpreted
   260  // according to whence: 0 means relative to the origin of the file, 1 means
   261  // relative to the current offset, and 2 means relative to the end.
   262  // It returns the new offset and an error, if any.
   263  func (f *File) seek(offset int64, whence int) (ret int64, err error) {
   264  	ret, err = f.pfd.Seek(offset, whence)
   265  	runtime.KeepAlive(f)
   266  	return ret, err
   267  }
   268  
   269  // Truncate changes the size of the named file.
   270  // If the file is a symbolic link, it changes the size of the link's target.
   271  // If there is an error, it will be of type *PathError.
   272  func Truncate(name string, size int64) error {
   273  	if e := syscall.Truncate(name, size); e != nil {
   274  		return &PathError{"truncate", name, e}
   275  	}
   276  	return nil
   277  }
   278  
   279  // Remove removes the named file or directory.
   280  // If there is an error, it will be of type *PathError.
   281  func Remove(name string) error {
   282  	// System call interface forces us to know
   283  	// whether name is a file or directory.
   284  	// Try both: it is cheaper on average than
   285  	// doing a Stat plus the right one.
   286  	e := syscall.Unlink(name)
   287  	if e == nil {
   288  		return nil
   289  	}
   290  	e1 := syscall.Rmdir(name)
   291  	if e1 == nil {
   292  		return nil
   293  	}
   294  
   295  	// Both failed: figure out which error to return.
   296  	// OS X and Linux differ on whether unlink(dir)
   297  	// returns EISDIR, so can't use that. However,
   298  	// both agree that rmdir(file) returns ENOTDIR,
   299  	// so we can use that to decide which error is real.
   300  	// Rmdir might also return ENOTDIR if given a bad
   301  	// file path, like /etc/passwd/foo, but in that case,
   302  	// both errors will be ENOTDIR, so it's okay to
   303  	// use the error from unlink.
   304  	if e1 != syscall.ENOTDIR {
   305  		e = e1
   306  	}
   307  	return &PathError{"remove", name, e}
   308  }
   309  
   310  func tempDir() string {
   311  	dir := Getenv("TMPDIR")
   312  	if dir == "" {
   313  		if runtime.GOOS == "android" {
   314  			dir = "/data/local/tmp"
   315  		} else {
   316  			dir = "/tmp"
   317  		}
   318  	}
   319  	return dir
   320  }
   321  
   322  // Link creates newname as a hard link to the oldname file.
   323  // If there is an error, it will be of type *LinkError.
   324  func Link(oldname, newname string) error {
   325  	e := syscall.Link(oldname, newname)
   326  	if e != nil {
   327  		return &LinkError{"link", oldname, newname, e}
   328  	}
   329  	return nil
   330  }
   331  
   332  // Symlink creates newname as a symbolic link to oldname.
   333  // If there is an error, it will be of type *LinkError.
   334  func Symlink(oldname, newname string) error {
   335  	e := syscall.Symlink(oldname, newname)
   336  	if e != nil {
   337  		return &LinkError{"symlink", oldname, newname, e}
   338  	}
   339  	return nil
   340  }