github.com/mdempsky/go@v0.0.0-20151201204031-5dd372bd1e70/src/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  // +build darwin dragonfly freebsd linux nacl netbsd openbsd solaris
     6  
     7  package os
     8  
     9  import (
    10  	"runtime"
    11  	"sync/atomic"
    12  	"syscall"
    13  )
    14  
    15  func sameFile(fs1, fs2 *fileStat) bool {
    16  	return fs1.sys.Dev == fs2.sys.Dev && fs1.sys.Ino == fs2.sys.Ino
    17  }
    18  
    19  func rename(oldname, newname string) error {
    20  	e := syscall.Rename(oldname, newname)
    21  	if e != nil {
    22  		return &LinkError{"rename", oldname, newname, e}
    23  	}
    24  	return nil
    25  }
    26  
    27  // File represents an open file descriptor.
    28  type File struct {
    29  	*file
    30  }
    31  
    32  // file is the real representation of *File.
    33  // The extra level of indirection ensures that no clients of os
    34  // can overwrite this data, which could cause the finalizer
    35  // to close the wrong file descriptor.
    36  type file struct {
    37  	fd      int
    38  	name    string
    39  	dirinfo *dirInfo // nil unless directory being read
    40  	nepipe  int32    // number of consecutive EPIPE in Write
    41  }
    42  
    43  // Fd returns the integer Unix file descriptor referencing the open file.
    44  // The file descriptor is valid only until f.Close is called or f is garbage collected.
    45  func (f *File) Fd() uintptr {
    46  	if f == nil {
    47  		return ^(uintptr(0))
    48  	}
    49  	return uintptr(f.fd)
    50  }
    51  
    52  // NewFile returns a new File with the given file descriptor and name.
    53  func NewFile(fd uintptr, name string) *File {
    54  	fdi := int(fd)
    55  	if fdi < 0 {
    56  		return nil
    57  	}
    58  	f := &File{&file{fd: fdi, name: name}}
    59  	runtime.SetFinalizer(f.file, (*file).close)
    60  	return f
    61  }
    62  
    63  // Auxiliary information if the File describes a directory
    64  type dirInfo struct {
    65  	buf  []byte // buffer for directory I/O
    66  	nbuf int    // length of buf; return value from Getdirentries
    67  	bufp int    // location of next record in buf.
    68  }
    69  
    70  func epipecheck(file *File, e error) {
    71  	if e == syscall.EPIPE {
    72  		if atomic.AddInt32(&file.nepipe, 1) >= 10 {
    73  			sigpipe()
    74  		}
    75  	} else {
    76  		atomic.StoreInt32(&file.nepipe, 0)
    77  	}
    78  }
    79  
    80  // DevNull is the name of the operating system's ``null device.''
    81  // On Unix-like systems, it is "/dev/null"; on Windows, "NUL".
    82  const DevNull = "/dev/null"
    83  
    84  // OpenFile is the generalized open call; most users will use Open
    85  // or Create instead.  It opens the named file with specified flag
    86  // (O_RDONLY etc.) and perm, (0666 etc.) if applicable.  If successful,
    87  // methods on the returned File can be used for I/O.
    88  // If there is an error, it will be of type *PathError.
    89  func OpenFile(name string, flag int, perm FileMode) (*File, error) {
    90  	chmod := false
    91  	if !supportsCreateWithStickyBit && flag&O_CREATE != 0 && perm&ModeSticky != 0 {
    92  		if _, err := Stat(name); IsNotExist(err) {
    93  			chmod = true
    94  		}
    95  	}
    96  
    97  	var r int
    98  	for {
    99  		var e error
   100  		r, e = syscall.Open(name, flag|syscall.O_CLOEXEC, syscallMode(perm))
   101  		if e == nil {
   102  			break
   103  		}
   104  
   105  		// On OS X, sigaction(2) doesn't guarantee that SA_RESTART will cause
   106  		// open(2) to be restarted for regular files. This is easy to reproduce on
   107  		// fuse file systems (see http://golang.org/issue/11180).
   108  		if runtime.GOOS == "darwin" && e == syscall.EINTR {
   109  			continue
   110  		}
   111  
   112  		return nil, &PathError{"open", name, e}
   113  	}
   114  
   115  	// open(2) itself won't handle the sticky bit on *BSD and Solaris
   116  	if chmod {
   117  		Chmod(name, perm)
   118  	}
   119  
   120  	// There's a race here with fork/exec, which we are
   121  	// content to live with.  See ../syscall/exec_unix.go.
   122  	if !supportsCloseOnExec {
   123  		syscall.CloseOnExec(r)
   124  	}
   125  
   126  	return NewFile(uintptr(r), name), nil
   127  }
   128  
   129  // Close closes the File, rendering it unusable for I/O.
   130  // It returns an error, if any.
   131  func (f *File) Close() error {
   132  	if f == nil {
   133  		return ErrInvalid
   134  	}
   135  	return f.file.close()
   136  }
   137  
   138  func (file *file) close() error {
   139  	if file == nil || file.fd < 0 {
   140  		return syscall.EINVAL
   141  	}
   142  	var err error
   143  	if e := syscall.Close(file.fd); e != nil {
   144  		err = &PathError{"close", file.name, e}
   145  	}
   146  	file.fd = -1 // so it can't be closed again
   147  
   148  	// no need for a finalizer anymore
   149  	runtime.SetFinalizer(file, nil)
   150  	return err
   151  }
   152  
   153  // Stat returns the FileInfo structure describing file.
   154  // If there is an error, it will be of type *PathError.
   155  func (f *File) Stat() (FileInfo, error) {
   156  	if f == nil {
   157  		return nil, ErrInvalid
   158  	}
   159  	var fs fileStat
   160  	err := syscall.Fstat(f.fd, &fs.sys)
   161  	if err != nil {
   162  		return nil, &PathError{"stat", f.name, err}
   163  	}
   164  	fillFileStatFromSys(&fs, f.name)
   165  	return &fs, nil
   166  }
   167  
   168  // Stat returns a FileInfo describing the named file.
   169  // If there is an error, it will be of type *PathError.
   170  func Stat(name string) (FileInfo, error) {
   171  	var fs fileStat
   172  	err := syscall.Stat(name, &fs.sys)
   173  	if err != nil {
   174  		return nil, &PathError{"stat", name, err}
   175  	}
   176  	fillFileStatFromSys(&fs, name)
   177  	return &fs, nil
   178  }
   179  
   180  // Lstat returns a FileInfo describing the named file.
   181  // If the file is a symbolic link, the returned FileInfo
   182  // describes the symbolic link.  Lstat makes no attempt to follow the link.
   183  // If there is an error, it will be of type *PathError.
   184  func Lstat(name string) (FileInfo, error) {
   185  	var fs fileStat
   186  	err := syscall.Lstat(name, &fs.sys)
   187  	if err != nil {
   188  		return nil, &PathError{"lstat", name, err}
   189  	}
   190  	fillFileStatFromSys(&fs, name)
   191  	return &fs, nil
   192  }
   193  
   194  func (f *File) readdir(n int) (fi []FileInfo, err error) {
   195  	dirname := f.name
   196  	if dirname == "" {
   197  		dirname = "."
   198  	}
   199  	names, err := f.Readdirnames(n)
   200  	fi = make([]FileInfo, 0, len(names))
   201  	for _, filename := range names {
   202  		fip, lerr := lstat(dirname + "/" + filename)
   203  		if IsNotExist(lerr) {
   204  			// File disappeared between readdir + stat.
   205  			// Just treat it as if it didn't exist.
   206  			continue
   207  		}
   208  		if lerr != nil {
   209  			return fi, lerr
   210  		}
   211  		fi = append(fi, fip)
   212  	}
   213  	return fi, err
   214  }
   215  
   216  // Darwin and FreeBSD can't read or write 2GB+ at a time,
   217  // even on 64-bit systems. See golang.org/issue/7812.
   218  // Use 1GB instead of, say, 2GB-1, to keep subsequent
   219  // reads aligned.
   220  const (
   221  	needsMaxRW = runtime.GOOS == "darwin" || runtime.GOOS == "freebsd"
   222  	maxRW      = 1 << 30
   223  )
   224  
   225  // read reads up to len(b) bytes from the File.
   226  // It returns the number of bytes read and an error, if any.
   227  func (f *File) read(b []byte) (n int, err error) {
   228  	if needsMaxRW && len(b) > maxRW {
   229  		b = b[:maxRW]
   230  	}
   231  	return fixCount(syscall.Read(f.fd, b))
   232  }
   233  
   234  // pread reads len(b) bytes from the File starting at byte offset off.
   235  // It returns the number of bytes read and the error, if any.
   236  // EOF is signaled by a zero count with err set to nil.
   237  func (f *File) pread(b []byte, off int64) (n int, err error) {
   238  	if needsMaxRW && len(b) > maxRW {
   239  		b = b[:maxRW]
   240  	}
   241  	return fixCount(syscall.Pread(f.fd, b, off))
   242  }
   243  
   244  // write writes len(b) bytes to the File.
   245  // It returns the number of bytes written and an error, if any.
   246  func (f *File) write(b []byte) (n int, err error) {
   247  	for {
   248  		bcap := b
   249  		if needsMaxRW && len(bcap) > maxRW {
   250  			bcap = bcap[:maxRW]
   251  		}
   252  		m, err := fixCount(syscall.Write(f.fd, bcap))
   253  		n += m
   254  
   255  		// If the syscall wrote some data but not all (short write)
   256  		// or it returned EINTR, then assume it stopped early for
   257  		// reasons that are uninteresting to the caller, and try again.
   258  		if 0 < m && m < len(bcap) || err == syscall.EINTR {
   259  			b = b[m:]
   260  			continue
   261  		}
   262  
   263  		if needsMaxRW && len(bcap) != len(b) && err == nil {
   264  			b = b[m:]
   265  			continue
   266  		}
   267  
   268  		return n, err
   269  	}
   270  }
   271  
   272  // pwrite writes len(b) bytes to the File starting at byte offset off.
   273  // It returns the number of bytes written and an error, if any.
   274  func (f *File) pwrite(b []byte, off int64) (n int, err error) {
   275  	if needsMaxRW && len(b) > maxRW {
   276  		b = b[:maxRW]
   277  	}
   278  	return fixCount(syscall.Pwrite(f.fd, b, off))
   279  }
   280  
   281  // seek sets the offset for the next Read or Write on file to offset, interpreted
   282  // according to whence: 0 means relative to the origin of the file, 1 means
   283  // relative to the current offset, and 2 means relative to the end.
   284  // It returns the new offset and an error, if any.
   285  func (f *File) seek(offset int64, whence int) (ret int64, err error) {
   286  	return syscall.Seek(f.fd, offset, whence)
   287  }
   288  
   289  // Truncate changes the size of the named file.
   290  // If the file is a symbolic link, it changes the size of the link's target.
   291  // If there is an error, it will be of type *PathError.
   292  func Truncate(name string, size int64) error {
   293  	if e := syscall.Truncate(name, size); e != nil {
   294  		return &PathError{"truncate", name, e}
   295  	}
   296  	return nil
   297  }
   298  
   299  // Remove removes the named file or directory.
   300  // If there is an error, it will be of type *PathError.
   301  func Remove(name string) error {
   302  	// System call interface forces us to know
   303  	// whether name is a file or directory.
   304  	// Try both: it is cheaper on average than
   305  	// doing a Stat plus the right one.
   306  	e := syscall.Unlink(name)
   307  	if e == nil {
   308  		return nil
   309  	}
   310  	e1 := syscall.Rmdir(name)
   311  	if e1 == nil {
   312  		return nil
   313  	}
   314  
   315  	// Both failed: figure out which error to return.
   316  	// OS X and Linux differ on whether unlink(dir)
   317  	// returns EISDIR, so can't use that.  However,
   318  	// both agree that rmdir(file) returns ENOTDIR,
   319  	// so we can use that to decide which error is real.
   320  	// Rmdir might also return ENOTDIR if given a bad
   321  	// file path, like /etc/passwd/foo, but in that case,
   322  	// both errors will be ENOTDIR, so it's okay to
   323  	// use the error from unlink.
   324  	if e1 != syscall.ENOTDIR {
   325  		e = e1
   326  	}
   327  	return &PathError{"remove", name, e}
   328  }
   329  
   330  // basename removes trailing slashes and the leading directory name from path name
   331  func basename(name string) string {
   332  	i := len(name) - 1
   333  	// Remove trailing slashes
   334  	for ; i > 0 && name[i] == '/'; i-- {
   335  		name = name[:i]
   336  	}
   337  	// Remove leading directory name
   338  	for i--; i >= 0; i-- {
   339  		if name[i] == '/' {
   340  			name = name[i+1:]
   341  			break
   342  		}
   343  	}
   344  
   345  	return name
   346  }
   347  
   348  // TempDir returns the default directory to use for temporary files.
   349  func TempDir() string {
   350  	dir := Getenv("TMPDIR")
   351  	if dir == "" {
   352  		if runtime.GOOS == "android" {
   353  			dir = "/data/local/tmp"
   354  		} else {
   355  			dir = "/tmp"
   356  		}
   357  	}
   358  	return dir
   359  }
   360  
   361  // Link creates newname as a hard link to the oldname file.
   362  // If there is an error, it will be of type *LinkError.
   363  func Link(oldname, newname string) error {
   364  	e := syscall.Link(oldname, newname)
   365  	if e != nil {
   366  		return &LinkError{"link", oldname, newname, e}
   367  	}
   368  	return nil
   369  }
   370  
   371  // Symlink creates newname as a symbolic link to oldname.
   372  // If there is an error, it will be of type *LinkError.
   373  func Symlink(oldname, newname string) error {
   374  	e := syscall.Symlink(oldname, newname)
   375  	if e != nil {
   376  		return &LinkError{"symlink", oldname, newname, e}
   377  	}
   378  	return nil
   379  }