Black Lives Matter. Support the Equal Justice Initiative.

Source file src/os/file_unix.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  // +build aix darwin dragonfly freebsd js,wasm linux netbsd openbsd solaris
     6  
     7  package os
     8  
     9  import (
    10  	"internal/poll"
    11  	"internal/syscall/unix"
    12  	"io"
    13  	"runtime"
    14  	"syscall"
    15  )
    16  
    17  // fixLongPath is a noop on non-Windows platforms.
    18  func fixLongPath(path string) string {
    19  	return path
    20  }
    21  
    22  func rename(oldname, newname string) error {
    23  	fi, err := Lstat(newname)
    24  	if err == nil && fi.IsDir() {
    25  		// There are two independent errors this function can return:
    26  		// one for a bad oldname, and one for a bad newname.
    27  		// At this point we've determined the newname is bad.
    28  		// But just in case oldname is also bad, prioritize returning
    29  		// the oldname error because that's what we did historically.
    30  		// However, if the old name and new name are not the same, yet
    31  		// they refer to the same file, it implies a case-only
    32  		// rename on a case-insensitive filesystem, which is ok.
    33  		if ofi, err := Lstat(oldname); err != nil {
    34  			if pe, ok := err.(*PathError); ok {
    35  				err = pe.Err
    36  			}
    37  			return &LinkError{"rename", oldname, newname, err}
    38  		} else if newname == oldname || !SameFile(fi, ofi) {
    39  			return &LinkError{"rename", oldname, newname, syscall.EEXIST}
    40  		}
    41  	}
    42  	err = syscall.Rename(oldname, newname)
    43  	if err != nil {
    44  		return &LinkError{"rename", oldname, newname, err}
    45  	}
    46  	return nil
    47  }
    48  
    49  // file is the real representation of *File.
    50  // The extra level of indirection ensures that no clients of os
    51  // can overwrite this data, which could cause the finalizer
    52  // to close the wrong file descriptor.
    53  type file struct {
    54  	pfd         poll.FD
    55  	name        string
    56  	dirinfo     *dirInfo // nil unless directory being read
    57  	nonblock    bool     // whether we set nonblocking mode
    58  	stdoutOrErr bool     // whether this is stdout or stderr
    59  	appendMode  bool     // whether file is opened for appending
    60  }
    61  
    62  // Fd returns the integer Unix file descriptor referencing the open file.
    63  // The file descriptor is valid only until f.Close is called or f is garbage collected.
    64  // On Unix systems this will cause the SetDeadline methods to stop working.
    65  func (f *File) Fd() uintptr {
    66  	if f == nil {
    67  		return ^(uintptr(0))
    68  	}
    69  
    70  	// If we put the file descriptor into nonblocking mode,
    71  	// then set it to blocking mode before we return it,
    72  	// because historically we have always returned a descriptor
    73  	// opened in blocking mode. The File will continue to work,
    74  	// but any blocking operation will tie up a thread.
    75  	if f.nonblock {
    76  		f.pfd.SetBlocking()
    77  	}
    78  
    79  	return uintptr(f.pfd.Sysfd)
    80  }
    81  
    82  // NewFile returns a new File with the given file descriptor and
    83  // name. The returned value will be nil if fd is not a valid file
    84  // descriptor. On Unix systems, if the file descriptor is in
    85  // non-blocking mode, NewFile will attempt to return a pollable File
    86  // (one for which the SetDeadline methods work).
    87  func NewFile(fd uintptr, name string) *File {
    88  	kind := kindNewFile
    89  	if nb, err := unix.IsNonblock(int(fd)); err == nil && nb {
    90  		kind = kindNonBlock
    91  	}
    92  	return newFile(fd, name, kind)
    93  }
    94  
    95  // newFileKind describes the kind of file to newFile.
    96  type newFileKind int
    97  
    98  const (
    99  	kindNewFile newFileKind = iota
   100  	kindOpenFile
   101  	kindPipe
   102  	kindNonBlock
   103  )
   104  
   105  // newFile is like NewFile, but if called from OpenFile or Pipe
   106  // (as passed in the kind parameter) it tries to add the file to
   107  // the runtime poller.
   108  func newFile(fd uintptr, name string, kind newFileKind) *File {
   109  	fdi := int(fd)
   110  	if fdi < 0 {
   111  		return nil
   112  	}
   113  	f := &File{&file{
   114  		pfd: poll.FD{
   115  			Sysfd:         fdi,
   116  			IsStream:      true,
   117  			ZeroReadIsEOF: true,
   118  		},
   119  		name:        name,
   120  		stdoutOrErr: fdi == 1 || fdi == 2,
   121  	}}
   122  
   123  	pollable := kind == kindOpenFile || kind == kindPipe || kind == kindNonBlock
   124  
   125  	// If the caller passed a non-blocking filedes (kindNonBlock),
   126  	// we assume they know what they are doing so we allow it to be
   127  	// used with kqueue.
   128  	if kind == kindOpenFile {
   129  		switch runtime.GOOS {
   130  		case "darwin", "dragonfly", "freebsd", "netbsd", "openbsd":
   131  			var st syscall.Stat_t
   132  			err := syscall.Fstat(fdi, &st)
   133  			typ := st.Mode & syscall.S_IFMT
   134  			// Don't try to use kqueue with regular files on *BSDs.
   135  			// On FreeBSD a regular file is always
   136  			// reported as ready for writing.
   137  			// On Dragonfly, NetBSD and OpenBSD the fd is signaled
   138  			// only once as ready (both read and write).
   139  			// Issue 19093.
   140  			// Also don't add directories to the netpoller.
   141  			if err == nil && (typ == syscall.S_IFREG || typ == syscall.S_IFDIR) {
   142  				pollable = false
   143  			}
   144  
   145  			// In addition to the behavior described above for regular files,
   146  			// on Darwin, kqueue does not work properly with fifos:
   147  			// closing the last writer does not cause a kqueue event
   148  			// for any readers. See issue #24164.
   149  			if runtime.GOOS == "darwin" && typ == syscall.S_IFIFO {
   150  				pollable = false
   151  			}
   152  		}
   153  	}
   154  
   155  	if err := f.pfd.Init("file", pollable); err != nil {
   156  		// An error here indicates a failure to register
   157  		// with the netpoll system. That can happen for
   158  		// a file descriptor that is not supported by
   159  		// epoll/kqueue; for example, disk files on
   160  		// GNU/Linux systems. We assume that any real error
   161  		// will show up in later I/O.
   162  	} else if pollable {
   163  		// We successfully registered with netpoll, so put
   164  		// the file into nonblocking mode.
   165  		if err := syscall.SetNonblock(fdi, true); err == nil {
   166  			f.nonblock = true
   167  		}
   168  	}
   169  
   170  	runtime.SetFinalizer(f.file, (*file).close)
   171  	return f
   172  }
   173  
   174  // epipecheck raises SIGPIPE if we get an EPIPE error on standard
   175  // output or standard error. See the SIGPIPE docs in os/signal, and
   176  // issue 11845.
   177  func epipecheck(file *File, e error) {
   178  	if e == syscall.EPIPE && file.stdoutOrErr {
   179  		sigpipe()
   180  	}
   181  }
   182  
   183  // DevNull is the name of the operating system's ``null device.''
   184  // On Unix-like systems, it is "/dev/null"; on Windows, "NUL".
   185  const DevNull = "/dev/null"
   186  
   187  // openFileNolog is the Unix implementation of OpenFile.
   188  // Changes here should be reflected in openFdAt, if relevant.
   189  func openFileNolog(name string, flag int, perm FileMode) (*File, error) {
   190  	setSticky := false
   191  	if !supportsCreateWithStickyBit && flag&O_CREATE != 0 && perm&ModeSticky != 0 {
   192  		if _, err := Stat(name); IsNotExist(err) {
   193  			setSticky = true
   194  		}
   195  	}
   196  
   197  	var r int
   198  	for {
   199  		var e error
   200  		r, e = syscall.Open(name, flag|syscall.O_CLOEXEC, syscallMode(perm))
   201  		if e == nil {
   202  			break
   203  		}
   204  
   205  		// On OS X, sigaction(2) doesn't guarantee that SA_RESTART will cause
   206  		// open(2) to be restarted for regular files. This is easy to reproduce on
   207  		// fuse file systems (see https://golang.org/issue/11180).
   208  		if runtime.GOOS == "darwin" && e == syscall.EINTR {
   209  			continue
   210  		}
   211  
   212  		return nil, &PathError{"open", name, e}
   213  	}
   214  
   215  	// open(2) itself won't handle the sticky bit on *BSD and Solaris
   216  	if setSticky {
   217  		setStickyBit(name)
   218  	}
   219  
   220  	// There's a race here with fork/exec, which we are
   221  	// content to live with. See ../syscall/exec_unix.go.
   222  	if !supportsCloseOnExec {
   223  		syscall.CloseOnExec(r)
   224  	}
   225  
   226  	return newFile(uintptr(r), name, kindOpenFile), nil
   227  }
   228  
   229  // Close closes the File, rendering it unusable for I/O.
   230  // On files that support SetDeadline, any pending I/O operations will
   231  // be canceled and return immediately with an error.
   232  // Close will return an error if it has already been called.
   233  func (f *File) Close() error {
   234  	if f == nil {
   235  		return ErrInvalid
   236  	}
   237  	return f.file.close()
   238  }
   239  
   240  func (file *file) close() error {
   241  	if file == nil {
   242  		return syscall.EINVAL
   243  	}
   244  	if file.dirinfo != nil {
   245  		file.dirinfo.close()
   246  	}
   247  	var err error
   248  	if e := file.pfd.Close(); e != nil {
   249  		if e == poll.ErrFileClosing {
   250  			e = ErrClosed
   251  		}
   252  		err = &PathError{"close", file.name, e}
   253  	}
   254  
   255  	// no need for a finalizer anymore
   256  	runtime.SetFinalizer(file, nil)
   257  	return err
   258  }
   259  
   260  // read reads up to len(b) bytes from the File.
   261  // It returns the number of bytes read and an error, if any.
   262  func (f *File) read(b []byte) (n int, err error) {
   263  	n, err = f.pfd.Read(b)
   264  	runtime.KeepAlive(f)
   265  	return n, err
   266  }
   267  
   268  // pread reads len(b) bytes from the File starting at byte offset off.
   269  // It returns the number of bytes read and the error, if any.
   270  // EOF is signaled by a zero count with err set to nil.
   271  func (f *File) pread(b []byte, off int64) (n int, err error) {
   272  	n, err = f.pfd.Pread(b, off)
   273  	runtime.KeepAlive(f)
   274  	return n, err
   275  }
   276  
   277  // write writes len(b) bytes to the File.
   278  // It returns the number of bytes written and an error, if any.
   279  func (f *File) write(b []byte) (n int, err error) {
   280  	n, err = f.pfd.Write(b)
   281  	runtime.KeepAlive(f)
   282  	return n, err
   283  }
   284  
   285  // pwrite writes len(b) bytes to the File starting at byte offset off.
   286  // It returns the number of bytes written and an error, if any.
   287  func (f *File) pwrite(b []byte, off int64) (n int, err error) {
   288  	n, err = f.pfd.Pwrite(b, off)
   289  	runtime.KeepAlive(f)
   290  	return n, err
   291  }
   292  
   293  // seek sets the offset for the next Read or Write on file to offset, interpreted
   294  // according to whence: 0 means relative to the origin of the file, 1 means
   295  // relative to the current offset, and 2 means relative to the end.
   296  // It returns the new offset and an error, if any.
   297  func (f *File) seek(offset int64, whence int) (ret int64, err error) {
   298  	f.seekInvalidate()
   299  	ret, err = f.pfd.Seek(offset, whence)
   300  	runtime.KeepAlive(f)
   301  	return ret, err
   302  }
   303  
   304  // Truncate changes the size of the named file.
   305  // If the file is a symbolic link, it changes the size of the link's target.
   306  // If there is an error, it will be of type *PathError.
   307  func Truncate(name string, size int64) error {
   308  	if e := syscall.Truncate(name, size); e != nil {
   309  		return &PathError{"truncate", name, e}
   310  	}
   311  	return nil
   312  }
   313  
   314  // Remove removes the named file or (empty) directory.
   315  // If there is an error, it will be of type *PathError.
   316  func Remove(name string) error {
   317  	// System call interface forces us to know
   318  	// whether name is a file or directory.
   319  	// Try both: it is cheaper on average than
   320  	// doing a Stat plus the right one.
   321  	e := syscall.Unlink(name)
   322  	if e == nil {
   323  		return nil
   324  	}
   325  	e1 := syscall.Rmdir(name)
   326  	if e1 == nil {
   327  		return nil
   328  	}
   329  
   330  	// Both failed: figure out which error to return.
   331  	// OS X and Linux differ on whether unlink(dir)
   332  	// returns EISDIR, so can't use that. However,
   333  	// both agree that rmdir(file) returns ENOTDIR,
   334  	// so we can use that to decide which error is real.
   335  	// Rmdir might also return ENOTDIR if given a bad
   336  	// file path, like /etc/passwd/foo, but in that case,
   337  	// both errors will be ENOTDIR, so it's okay to
   338  	// use the error from unlink.
   339  	if e1 != syscall.ENOTDIR {
   340  		e = e1
   341  	}
   342  	return &PathError{"remove", name, e}
   343  }
   344  
   345  func tempDir() string {
   346  	dir := Getenv("TMPDIR")
   347  	if dir == "" {
   348  		if runtime.GOOS == "android" {
   349  			dir = "/data/local/tmp"
   350  		} else {
   351  			dir = "/tmp"
   352  		}
   353  	}
   354  	return dir
   355  }
   356  
   357  // Link creates newname as a hard link to the oldname file.
   358  // If there is an error, it will be of type *LinkError.
   359  func Link(oldname, newname string) error {
   360  	e := syscall.Link(oldname, newname)
   361  	if e != nil {
   362  		return &LinkError{"link", oldname, newname, e}
   363  	}
   364  	return nil
   365  }
   366  
   367  // Symlink creates newname as a symbolic link to oldname.
   368  // If there is an error, it will be of type *LinkError.
   369  func Symlink(oldname, newname string) error {
   370  	e := syscall.Symlink(oldname, newname)
   371  	if e != nil {
   372  		return &LinkError{"symlink", oldname, newname, e}
   373  	}
   374  	return nil
   375  }
   376  
   377  func (f *File) readdir(n int) (fi []FileInfo, err error) {
   378  	dirname := f.name
   379  	if dirname == "" {
   380  		dirname = "."
   381  	}
   382  	names, err := f.Readdirnames(n)
   383  	fi = make([]FileInfo, 0, len(names))
   384  	for _, filename := range names {
   385  		fip, lerr := lstat(dirname + "/" + filename)
   386  		if IsNotExist(lerr) {
   387  			// File disappeared between readdir + stat.
   388  			// Just treat it as if it didn't exist.
   389  			continue
   390  		}
   391  		if lerr != nil {
   392  			return fi, lerr
   393  		}
   394  		fi = append(fi, fip)
   395  	}
   396  	if len(fi) == 0 && err == nil && n > 0 {
   397  		// Per File.Readdir, the slice must be non-empty or err
   398  		// must be non-nil if n > 0.
   399  		err = io.EOF
   400  	}
   401  	return fi, err
   402  }
   403  
   404  // Readlink returns the destination of the named symbolic link.
   405  // If there is an error, it will be of type *PathError.
   406  func Readlink(name string) (string, error) {
   407  	for len := 128; ; len *= 2 {
   408  		b := make([]byte, len)
   409  		n, e := fixCount(syscall.Readlink(name, b))
   410  		// buffer too small
   411  		if runtime.GOOS == "aix" && e == syscall.ERANGE {
   412  			continue
   413  		}
   414  		if e != nil {
   415  			return "", &PathError{"readlink", name, e}
   416  		}
   417  		if n < len {
   418  			return string(b[0:n]), nil
   419  		}
   420  	}
   421  }
   422  

View as plain text