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  		// We have to check EINTR here, per issues 11180 and 39237.
   206  		if e == syscall.EINTR {
   207  			continue
   208  		}
   209  
   210  		return nil, &PathError{"open", name, e}
   211  	}
   212  
   213  	// open(2) itself won't handle the sticky bit on *BSD and Solaris
   214  	if setSticky {
   215  		setStickyBit(name)
   216  	}
   217  
   218  	// There's a race here with fork/exec, which we are
   219  	// content to live with. See ../syscall/exec_unix.go.
   220  	if !supportsCloseOnExec {
   221  		syscall.CloseOnExec(r)
   222  	}
   223  
   224  	return newFile(uintptr(r), name, kindOpenFile), nil
   225  }
   226  
   227  func (file *file) close() error {
   228  	if file == nil {
   229  		return syscall.EINVAL
   230  	}
   231  	if file.dirinfo != nil {
   232  		file.dirinfo.close()
   233  	}
   234  	var err error
   235  	if e := file.pfd.Close(); e != nil {
   236  		if e == poll.ErrFileClosing {
   237  			e = ErrClosed
   238  		}
   239  		err = &PathError{"close", file.name, e}
   240  	}
   241  
   242  	// no need for a finalizer anymore
   243  	runtime.SetFinalizer(file, nil)
   244  	return err
   245  }
   246  
   247  // seek sets the offset for the next Read or Write on file to offset, interpreted
   248  // according to whence: 0 means relative to the origin of the file, 1 means
   249  // relative to the current offset, and 2 means relative to the end.
   250  // It returns the new offset and an error, if any.
   251  func (f *File) seek(offset int64, whence int) (ret int64, err error) {
   252  	if f.dirinfo != nil {
   253  		// Free cached dirinfo, so we allocate a new one if we
   254  		// access this file as a directory again. See #35767 and #37161.
   255  		f.dirinfo.close()
   256  		f.dirinfo = nil
   257  	}
   258  	ret, err = f.pfd.Seek(offset, whence)
   259  	runtime.KeepAlive(f)
   260  	return ret, err
   261  }
   262  
   263  // Truncate changes the size of the named file.
   264  // If the file is a symbolic link, it changes the size of the link's target.
   265  // If there is an error, it will be of type *PathError.
   266  func Truncate(name string, size int64) error {
   267  	if e := syscall.Truncate(name, size); e != nil {
   268  		return &PathError{"truncate", name, e}
   269  	}
   270  	return nil
   271  }
   272  
   273  // Remove removes the named file or (empty) directory.
   274  // If there is an error, it will be of type *PathError.
   275  func Remove(name string) error {
   276  	// System call interface forces us to know
   277  	// whether name is a file or directory.
   278  	// Try both: it is cheaper on average than
   279  	// doing a Stat plus the right one.
   280  	e := syscall.Unlink(name)
   281  	if e == nil {
   282  		return nil
   283  	}
   284  	e1 := syscall.Rmdir(name)
   285  	if e1 == nil {
   286  		return nil
   287  	}
   288  
   289  	// Both failed: figure out which error to return.
   290  	// OS X and Linux differ on whether unlink(dir)
   291  	// returns EISDIR, so can't use that. However,
   292  	// both agree that rmdir(file) returns ENOTDIR,
   293  	// so we can use that to decide which error is real.
   294  	// Rmdir might also return ENOTDIR if given a bad
   295  	// file path, like /etc/passwd/foo, but in that case,
   296  	// both errors will be ENOTDIR, so it's okay to
   297  	// use the error from unlink.
   298  	if e1 != syscall.ENOTDIR {
   299  		e = e1
   300  	}
   301  	return &PathError{"remove", name, e}
   302  }
   303  
   304  func tempDir() string {
   305  	dir := Getenv("TMPDIR")
   306  	if dir == "" {
   307  		if runtime.GOOS == "android" {
   308  			dir = "/data/local/tmp"
   309  		} else {
   310  			dir = "/tmp"
   311  		}
   312  	}
   313  	return dir
   314  }
   315  
   316  // Link creates newname as a hard link to the oldname file.
   317  // If there is an error, it will be of type *LinkError.
   318  func Link(oldname, newname string) error {
   319  	e := syscall.Link(oldname, newname)
   320  	if e != nil {
   321  		return &LinkError{"link", oldname, newname, e}
   322  	}
   323  	return nil
   324  }
   325  
   326  // Symlink creates newname as a symbolic link to oldname.
   327  // If there is an error, it will be of type *LinkError.
   328  func Symlink(oldname, newname string) error {
   329  	e := syscall.Symlink(oldname, newname)
   330  	if e != nil {
   331  		return &LinkError{"symlink", oldname, newname, e}
   332  	}
   333  	return nil
   334  }
   335  
   336  func (f *File) readdir(n int) (fi []FileInfo, err error) {
   337  	dirname := f.name
   338  	if dirname == "" {
   339  		dirname = "."
   340  	}
   341  	names, err := f.Readdirnames(n)
   342  	fi = make([]FileInfo, 0, len(names))
   343  	for _, filename := range names {
   344  		fip, lerr := lstat(dirname + "/" + filename)
   345  		if IsNotExist(lerr) {
   346  			// File disappeared between readdir + stat.
   347  			// Just treat it as if it didn't exist.
   348  			continue
   349  		}
   350  		if lerr != nil {
   351  			return fi, lerr
   352  		}
   353  		fi = append(fi, fip)
   354  	}
   355  	if len(fi) == 0 && err == nil && n > 0 {
   356  		// Per File.Readdir, the slice must be non-empty or err
   357  		// must be non-nil if n > 0.
   358  		err = io.EOF
   359  	}
   360  	return fi, err
   361  }
   362  
   363  // Readlink returns the destination of the named symbolic link.
   364  // If there is an error, it will be of type *PathError.
   365  func Readlink(name string) (string, error) {
   366  	for len := 128; ; len *= 2 {
   367  		b := make([]byte, len)
   368  		n, e := fixCount(syscall.Readlink(name, b))
   369  		// buffer too small
   370  		if runtime.GOOS == "aix" && e == syscall.ERANGE {
   371  			continue
   372  		}
   373  		if e != nil {
   374  			return "", &PathError{"readlink", name, e}
   375  		}
   376  		if n < len {
   377  			return string(b[0:n]), nil
   378  		}
   379  	}
   380  }
   381  

View as plain text