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