Source file src/os/file_unix.go

     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  //go: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  		// 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  		file.dirinfo = nil
   250  	}
   251  	var err error
   252  	if e := file.pfd.Close(); e != nil {
   253  		if e == poll.ErrFileClosing {
   254  			e = ErrClosed
   255  		}
   256  		err = &PathError{Op: "close", Path: file.name, Err: e}
   257  	}
   258  
   259  	// no need for a finalizer anymore
   260  	runtime.SetFinalizer(file, nil)
   261  	return err
   262  }
   263  
   264  // seek sets the offset for the next Read or Write on file to offset, interpreted
   265  // according to whence: 0 means relative to the origin of the file, 1 means
   266  // relative to the current offset, and 2 means relative to the end.
   267  // It returns the new offset and an error, if any.
   268  func (f *File) seek(offset int64, whence int) (ret int64, err error) {
   269  	if f.dirinfo != nil {
   270  		// Free cached dirinfo, so we allocate a new one if we
   271  		// access this file as a directory again. See #35767 and #37161.
   272  		f.dirinfo.close()
   273  		f.dirinfo = nil
   274  	}
   275  	ret, err = f.pfd.Seek(offset, whence)
   276  	runtime.KeepAlive(f)
   277  	return ret, err
   278  }
   279  
   280  // Truncate changes the size of the named file.
   281  // If the file is a symbolic link, it changes the size of the link's target.
   282  // If there is an error, it will be of type *PathError.
   283  func Truncate(name string, size int64) error {
   284  	e := ignoringEINTR(func() error {
   285  		return syscall.Truncate(name, size)
   286  	})
   287  	if e != nil {
   288  		return &PathError{Op: "truncate", Path: name, Err: e}
   289  	}
   290  	return nil
   291  }
   292  
   293  // Remove removes the named file or (empty) directory.
   294  // If there is an error, it will be of type *PathError.
   295  func Remove(name string) error {
   296  	// System call interface forces us to know
   297  	// whether name is a file or directory.
   298  	// Try both: it is cheaper on average than
   299  	// doing a Stat plus the right one.
   300  	e := ignoringEINTR(func() error {
   301  		return syscall.Unlink(name)
   302  	})
   303  	if e == nil {
   304  		return nil
   305  	}
   306  	e1 := ignoringEINTR(func() error {
   307  		return syscall.Rmdir(name)
   308  	})
   309  	if e1 == nil {
   310  		return nil
   311  	}
   312  
   313  	// Both failed: figure out which error to return.
   314  	// OS X and Linux differ on whether unlink(dir)
   315  	// returns EISDIR, so can't use that. However,
   316  	// both agree that rmdir(file) returns ENOTDIR,
   317  	// so we can use that to decide which error is real.
   318  	// Rmdir might also return ENOTDIR if given a bad
   319  	// file path, like /etc/passwd/foo, but in that case,
   320  	// both errors will be ENOTDIR, so it's okay to
   321  	// use the error from unlink.
   322  	if e1 != syscall.ENOTDIR {
   323  		e = e1
   324  	}
   325  	return &PathError{Op: "remove", Path: name, Err: e}
   326  }
   327  
   328  func tempDir() string {
   329  	dir := Getenv("TMPDIR")
   330  	if dir == "" {
   331  		if runtime.GOOS == "android" {
   332  			dir = "/data/local/tmp"
   333  		} else {
   334  			dir = "/tmp"
   335  		}
   336  	}
   337  	return dir
   338  }
   339  
   340  // Link creates newname as a hard link to the oldname file.
   341  // If there is an error, it will be of type *LinkError.
   342  func Link(oldname, newname string) error {
   343  	e := ignoringEINTR(func() error {
   344  		return syscall.Link(oldname, newname)
   345  	})
   346  	if e != nil {
   347  		return &LinkError{"link", oldname, newname, e}
   348  	}
   349  	return nil
   350  }
   351  
   352  // Symlink creates newname as a symbolic link to oldname.
   353  // On Windows, a symlink to a non-existent oldname creates a file symlink;
   354  // if oldname is later created as a directory the symlink will not work.
   355  // If there is an error, it will be of type *LinkError.
   356  func Symlink(oldname, newname string) error {
   357  	e := ignoringEINTR(func() error {
   358  		return syscall.Symlink(oldname, newname)
   359  	})
   360  	if e != nil {
   361  		return &LinkError{"symlink", oldname, newname, e}
   362  	}
   363  	return nil
   364  }
   365  
   366  // Readlink returns the destination of the named symbolic link.
   367  // If there is an error, it will be of type *PathError.
   368  func Readlink(name string) (string, error) {
   369  	for len := 128; ; len *= 2 {
   370  		b := make([]byte, len)
   371  		var (
   372  			n int
   373  			e error
   374  		)
   375  		for {
   376  			n, e = fixCount(syscall.Readlink(name, b))
   377  			if e != syscall.EINTR {
   378  				break
   379  			}
   380  		}
   381  		// buffer too small
   382  		if runtime.GOOS == "aix" && e == syscall.ERANGE {
   383  			continue
   384  		}
   385  		if e != nil {
   386  			return "", &PathError{Op: "readlink", Path: name, Err: e}
   387  		}
   388  		if n < len {
   389  			return string(b[0:n]), nil
   390  		}
   391  	}
   392  }
   393  
   394  type unixDirent struct {
   395  	parent string
   396  	name   string
   397  	typ    FileMode
   398  	info   FileInfo
   399  }
   400  
   401  func (d *unixDirent) Name() string   { return d.name }
   402  func (d *unixDirent) IsDir() bool    { return d.typ.IsDir() }
   403  func (d *unixDirent) Type() FileMode { return d.typ }
   404  
   405  func (d *unixDirent) Info() (FileInfo, error) {
   406  	if d.info != nil {
   407  		return d.info, nil
   408  	}
   409  	return lstat(d.parent + "/" + d.name)
   410  }
   411  
   412  func newUnixDirent(parent, name string, typ FileMode) (DirEntry, error) {
   413  	ude := &unixDirent{
   414  		parent: parent,
   415  		name:   name,
   416  		typ:    typ,
   417  	}
   418  	if typ != ^FileMode(0) && !testingForceReadDirLstat {
   419  		return ude, nil
   420  	}
   421  
   422  	info, err := lstat(parent + "/" + name)
   423  	if err != nil {
   424  		return nil, err
   425  	}
   426  
   427  	ude.typ = info.Mode().Type()
   428  	ude.info = info
   429  	return ude, nil
   430  }
   431  

View as plain text