github.com/mtsmfm/go/src@v0.0.0-20221020090648-44bdcb9f8fde/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  //go:build unix || (js && wasm)
     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  	clearNonBlock := false
   172  	if pollable {
   173  		if kind == kindNonBlock {
   174  			f.nonblock = true
   175  		} else if err := syscall.SetNonblock(fdi, true); err == nil {
   176  			f.nonblock = true
   177  			clearNonBlock = true
   178  		} else {
   179  			pollable = false
   180  		}
   181  	}
   182  
   183  	// An error here indicates a failure to register
   184  	// with the netpoll system. That can happen for
   185  	// a file descriptor that is not supported by
   186  	// epoll/kqueue; for example, disk files on
   187  	// Linux systems. We assume that any real error
   188  	// will show up in later I/O.
   189  	// We do restore the blocking behavior if it was set by us.
   190  	if pollErr := f.pfd.Init("file", pollable); pollErr != nil && clearNonBlock {
   191  		if err := syscall.SetNonblock(fdi, false); err == nil {
   192  			f.nonblock = false
   193  		}
   194  	}
   195  
   196  	runtime.SetFinalizer(f.file, (*file).close)
   197  	return f
   198  }
   199  
   200  // epipecheck raises SIGPIPE if we get an EPIPE error on standard
   201  // output or standard error. See the SIGPIPE docs in os/signal, and
   202  // issue 11845.
   203  func epipecheck(file *File, e error) {
   204  	if e == syscall.EPIPE && file.stdoutOrErr {
   205  		sigpipe()
   206  	}
   207  }
   208  
   209  // DevNull is the name of the operating system's “null device.”
   210  // On Unix-like systems, it is "/dev/null"; on Windows, "NUL".
   211  const DevNull = "/dev/null"
   212  
   213  // openFileNolog is the Unix implementation of OpenFile.
   214  // Changes here should be reflected in openFdAt, if relevant.
   215  func openFileNolog(name string, flag int, perm FileMode) (*File, error) {
   216  	setSticky := false
   217  	if !supportsCreateWithStickyBit && flag&O_CREATE != 0 && perm&ModeSticky != 0 {
   218  		if _, err := Stat(name); IsNotExist(err) {
   219  			setSticky = true
   220  		}
   221  	}
   222  
   223  	var r int
   224  	for {
   225  		var e error
   226  		r, e = syscall.Open(name, flag|syscall.O_CLOEXEC, syscallMode(perm))
   227  		if e == nil {
   228  			break
   229  		}
   230  
   231  		// We have to check EINTR here, per issues 11180 and 39237.
   232  		if e == syscall.EINTR {
   233  			continue
   234  		}
   235  
   236  		return nil, &PathError{Op: "open", Path: name, Err: e}
   237  	}
   238  
   239  	// open(2) itself won't handle the sticky bit on *BSD and Solaris
   240  	if setSticky {
   241  		setStickyBit(name)
   242  	}
   243  
   244  	// There's a race here with fork/exec, which we are
   245  	// content to live with. See ../syscall/exec_unix.go.
   246  	if !supportsCloseOnExec {
   247  		syscall.CloseOnExec(r)
   248  	}
   249  
   250  	return newFile(uintptr(r), name, kindOpenFile), nil
   251  }
   252  
   253  func (file *file) close() error {
   254  	if file == nil {
   255  		return syscall.EINVAL
   256  	}
   257  	if file.dirinfo != nil {
   258  		file.dirinfo.close()
   259  		file.dirinfo = nil
   260  	}
   261  	var err error
   262  	if e := file.pfd.Close(); e != nil {
   263  		if e == poll.ErrFileClosing {
   264  			e = ErrClosed
   265  		}
   266  		err = &PathError{Op: "close", Path: file.name, Err: e}
   267  	}
   268  
   269  	// no need for a finalizer anymore
   270  	runtime.SetFinalizer(file, nil)
   271  	return err
   272  }
   273  
   274  // seek sets the offset for the next Read or Write on file to offset, interpreted
   275  // according to whence: 0 means relative to the origin of the file, 1 means
   276  // relative to the current offset, and 2 means relative to the end.
   277  // It returns the new offset and an error, if any.
   278  func (f *File) seek(offset int64, whence int) (ret int64, err error) {
   279  	if f.dirinfo != nil {
   280  		// Free cached dirinfo, so we allocate a new one if we
   281  		// access this file as a directory again. See #35767 and #37161.
   282  		f.dirinfo.close()
   283  		f.dirinfo = nil
   284  	}
   285  	ret, err = f.pfd.Seek(offset, whence)
   286  	runtime.KeepAlive(f)
   287  	return ret, err
   288  }
   289  
   290  // Truncate changes the size of the named file.
   291  // If the file is a symbolic link, it changes the size of the link's target.
   292  // If there is an error, it will be of type *PathError.
   293  func Truncate(name string, size int64) error {
   294  	e := ignoringEINTR(func() error {
   295  		return syscall.Truncate(name, size)
   296  	})
   297  	if e != nil {
   298  		return &PathError{Op: "truncate", Path: name, Err: e}
   299  	}
   300  	return nil
   301  }
   302  
   303  // Remove removes the named file or (empty) directory.
   304  // If there is an error, it will be of type *PathError.
   305  func Remove(name string) error {
   306  	// System call interface forces us to know
   307  	// whether name is a file or directory.
   308  	// Try both: it is cheaper on average than
   309  	// doing a Stat plus the right one.
   310  	e := ignoringEINTR(func() error {
   311  		return syscall.Unlink(name)
   312  	})
   313  	if e == nil {
   314  		return nil
   315  	}
   316  	e1 := ignoringEINTR(func() error {
   317  		return syscall.Rmdir(name)
   318  	})
   319  	if e1 == nil {
   320  		return nil
   321  	}
   322  
   323  	// Both failed: figure out which error to return.
   324  	// OS X and Linux differ on whether unlink(dir)
   325  	// returns EISDIR, so can't use that. However,
   326  	// both agree that rmdir(file) returns ENOTDIR,
   327  	// so we can use that to decide which error is real.
   328  	// Rmdir might also return ENOTDIR if given a bad
   329  	// file path, like /etc/passwd/foo, but in that case,
   330  	// both errors will be ENOTDIR, so it's okay to
   331  	// use the error from unlink.
   332  	if e1 != syscall.ENOTDIR {
   333  		e = e1
   334  	}
   335  	return &PathError{Op: "remove", Path: name, Err: e}
   336  }
   337  
   338  func tempDir() string {
   339  	dir := Getenv("TMPDIR")
   340  	if dir == "" {
   341  		if runtime.GOOS == "android" {
   342  			dir = "/data/local/tmp"
   343  		} else {
   344  			dir = "/tmp"
   345  		}
   346  	}
   347  	return dir
   348  }
   349  
   350  // Link creates newname as a hard link to the oldname file.
   351  // If there is an error, it will be of type *LinkError.
   352  func Link(oldname, newname string) error {
   353  	e := ignoringEINTR(func() error {
   354  		return syscall.Link(oldname, newname)
   355  	})
   356  	if e != nil {
   357  		return &LinkError{"link", oldname, newname, e}
   358  	}
   359  	return nil
   360  }
   361  
   362  // Symlink creates newname as a symbolic link to oldname.
   363  // On Windows, a symlink to a non-existent oldname creates a file symlink;
   364  // if oldname is later created as a directory the symlink will not work.
   365  // If there is an error, it will be of type *LinkError.
   366  func Symlink(oldname, newname string) error {
   367  	e := ignoringEINTR(func() error {
   368  		return syscall.Symlink(oldname, newname)
   369  	})
   370  	if e != nil {
   371  		return &LinkError{"symlink", oldname, newname, e}
   372  	}
   373  	return nil
   374  }
   375  
   376  // Readlink returns the destination of the named symbolic link.
   377  // If there is an error, it will be of type *PathError.
   378  func Readlink(name string) (string, error) {
   379  	for len := 128; ; len *= 2 {
   380  		b := make([]byte, len)
   381  		var (
   382  			n int
   383  			e error
   384  		)
   385  		for {
   386  			n, e = fixCount(syscall.Readlink(name, b))
   387  			if e != syscall.EINTR {
   388  				break
   389  			}
   390  		}
   391  		// buffer too small
   392  		if runtime.GOOS == "aix" && e == syscall.ERANGE {
   393  			continue
   394  		}
   395  		if e != nil {
   396  			return "", &PathError{Op: "readlink", Path: name, Err: e}
   397  		}
   398  		if n < len {
   399  			return string(b[0:n]), nil
   400  		}
   401  	}
   402  }
   403  
   404  type unixDirent struct {
   405  	parent string
   406  	name   string
   407  	typ    FileMode
   408  	info   FileInfo
   409  }
   410  
   411  func (d *unixDirent) Name() string   { return d.name }
   412  func (d *unixDirent) IsDir() bool    { return d.typ.IsDir() }
   413  func (d *unixDirent) Type() FileMode { return d.typ }
   414  
   415  func (d *unixDirent) Info() (FileInfo, error) {
   416  	if d.info != nil {
   417  		return d.info, nil
   418  	}
   419  	return lstat(d.parent + "/" + d.name)
   420  }
   421  
   422  func newUnixDirent(parent, name string, typ FileMode) (DirEntry, error) {
   423  	ude := &unixDirent{
   424  		parent: parent,
   425  		name:   name,
   426  		typ:    typ,
   427  	}
   428  	if typ != ^FileMode(0) && !testingForceReadDirLstat {
   429  		return ude, nil
   430  	}
   431  
   432  	info, err := lstat(parent + "/" + name)
   433  	if err != nil {
   434  		return nil, err
   435  	}
   436  
   437  	ude.typ = info.Mode().Type()
   438  	ude.info = info
   439  	return ude, nil
   440  }