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