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

View as plain text