github.com/llvm-mirror/llgo@v0.0.0-20190322182713-bf6f0a60fce1/third_party/gofrontend/libgo/go/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  	dir *syscall.DIR // from opendir
    63  }
    64  
    65  func epipecheck(file *File, e error) {
    66  	if e == syscall.EPIPE {
    67  		if atomic.AddInt32(&file.nepipe, 1) >= 10 {
    68  			sigpipe()
    69  		}
    70  	} else {
    71  		atomic.StoreInt32(&file.nepipe, 0)
    72  	}
    73  }
    74  
    75  // DevNull is the name of the operating system's ``null device.''
    76  // On Unix-like systems, it is "/dev/null"; on Windows, "NUL".
    77  const DevNull = "/dev/null"
    78  
    79  // OpenFile is the generalized open call; most users will use Open
    80  // or Create instead.  It opens the named file with specified flag
    81  // (O_RDONLY etc.) and perm, (0666 etc.) if applicable.  If successful,
    82  // methods on the returned File can be used for I/O.
    83  // If there is an error, it will be of type *PathError.
    84  func OpenFile(name string, flag int, perm FileMode) (*File, error) {
    85  	chmod := false
    86  	if !supportsCreateWithStickyBit && flag&O_CREATE != 0 && perm&ModeSticky != 0 {
    87  		if _, err := Stat(name); IsNotExist(err) {
    88  			chmod = true
    89  		}
    90  	}
    91  
    92  	r, e := syscall.Open(name, flag|syscall.O_CLOEXEC, syscallMode(perm))
    93  	if e != nil {
    94  		return nil, &PathError{"open", name, e}
    95  	}
    96  
    97  	// open(2) itself won't handle the sticky bit on *BSD and Solaris
    98  	if chmod {
    99  		Chmod(name, perm)
   100  	}
   101  
   102  	// There's a race here with fork/exec, which we are
   103  	// content to live with.  See ../syscall/exec_unix.go.
   104  	if !supportsCloseOnExec {
   105  		syscall.CloseOnExec(r)
   106  	}
   107  
   108  	return NewFile(uintptr(r), name), nil
   109  }
   110  
   111  // Close closes the File, rendering it unusable for I/O.
   112  // It returns an error, if any.
   113  func (f *File) Close() error {
   114  	if f == nil {
   115  		return ErrInvalid
   116  	}
   117  	return f.file.close()
   118  }
   119  
   120  func (file *file) close() error {
   121  	if file == nil || file.fd < 0 {
   122  		return syscall.EINVAL
   123  	}
   124  	var err error
   125  	if e := syscall.Close(file.fd); e != nil {
   126  		err = &PathError{"close", file.name, e}
   127  	}
   128  
   129  	if file.dirinfo != nil {
   130  		syscall.Entersyscall()
   131  		i := libc_closedir(file.dirinfo.dir)
   132  		errno := syscall.GetErrno()
   133  		syscall.Exitsyscall()
   134  		file.dirinfo = nil
   135  		if i < 0 && err == nil {
   136  			err = &PathError{"closedir", file.name, errno}
   137  		}
   138  	}
   139  
   140  	file.fd = -1 // so it can't be closed again
   141  
   142  	// no need for a finalizer anymore
   143  	runtime.SetFinalizer(file, nil)
   144  	return err
   145  }
   146  
   147  // Stat returns the FileInfo structure describing file.
   148  // If there is an error, it will be of type *PathError.
   149  func (f *File) Stat() (FileInfo, error) {
   150  	if f == nil {
   151  		return nil, ErrInvalid
   152  	}
   153  	var stat syscall.Stat_t
   154  	err := syscall.Fstat(f.fd, &stat)
   155  	if err != nil {
   156  		return nil, &PathError{"stat", f.name, err}
   157  	}
   158  	return fileInfoFromStat(&stat, f.name), nil
   159  }
   160  
   161  // Stat returns a FileInfo describing the named file.
   162  // If there is an error, it will be of type *PathError.
   163  func Stat(name string) (FileInfo, error) {
   164  	var stat syscall.Stat_t
   165  	err := syscall.Stat(name, &stat)
   166  	if err != nil {
   167  		return nil, &PathError{"stat", name, err}
   168  	}
   169  	return fileInfoFromStat(&stat, name), nil
   170  }
   171  
   172  // Lstat returns a FileInfo describing the named file.
   173  // If the file is a symbolic link, the returned FileInfo
   174  // describes the symbolic link.  Lstat makes no attempt to follow the link.
   175  // If there is an error, it will be of type *PathError.
   176  func Lstat(name string) (FileInfo, error) {
   177  	var stat syscall.Stat_t
   178  	err := syscall.Lstat(name, &stat)
   179  	if err != nil {
   180  		return nil, &PathError{"lstat", name, err}
   181  	}
   182  	return fileInfoFromStat(&stat, name), nil
   183  }
   184  
   185  func (f *File) readdir(n int) (fi []FileInfo, err error) {
   186  	dirname := f.name
   187  	if dirname == "" {
   188  		dirname = "."
   189  	}
   190  	names, err := f.Readdirnames(n)
   191  	fi = make([]FileInfo, 0, len(names))
   192  	for _, filename := range names {
   193  		fip, lerr := lstat(dirname + "/" + filename)
   194  		if IsNotExist(lerr) {
   195  			// File disappeared between readdir + stat.
   196  			// Just treat it as if it didn't exist.
   197  			continue
   198  		}
   199  		if lerr != nil {
   200  			return fi, lerr
   201  		}
   202  		fi = append(fi, fip)
   203  	}
   204  	return fi, err
   205  }
   206  
   207  // Darwin and FreeBSD can't read or write 2GB+ at a time,
   208  // even on 64-bit systems. See golang.org/issue/7812.
   209  // Use 1GB instead of, say, 2GB-1, to keep subsequent
   210  // reads aligned.
   211  const (
   212  	needsMaxRW = runtime.GOOS == "darwin" || runtime.GOOS == "freebsd"
   213  	maxRW      = 1 << 30
   214  )
   215  
   216  // read reads up to len(b) bytes from the File.
   217  // It returns the number of bytes read and an error, if any.
   218  func (f *File) read(b []byte) (n int, err error) {
   219  	if needsMaxRW && len(b) > maxRW {
   220  		b = b[:maxRW]
   221  	}
   222  	return fixCount(syscall.Read(f.fd, b))
   223  }
   224  
   225  // pread reads len(b) bytes from the File starting at byte offset off.
   226  // It returns the number of bytes read and the error, if any.
   227  // EOF is signaled by a zero count with err set to nil.
   228  func (f *File) pread(b []byte, off int64) (n int, err error) {
   229  	if needsMaxRW && len(b) > maxRW {
   230  		b = b[:maxRW]
   231  	}
   232  	return fixCount(syscall.Pread(f.fd, b, off))
   233  }
   234  
   235  // write writes len(b) bytes to the File.
   236  // It returns the number of bytes written and an error, if any.
   237  func (f *File) write(b []byte) (n int, err error) {
   238  	for {
   239  		bcap := b
   240  		if needsMaxRW && len(bcap) > maxRW {
   241  			bcap = bcap[:maxRW]
   242  		}
   243  		m, err := fixCount(syscall.Write(f.fd, bcap))
   244  		n += m
   245  
   246  		// If the syscall wrote some data but not all (short write)
   247  		// or it returned EINTR, then assume it stopped early for
   248  		// reasons that are uninteresting to the caller, and try again.
   249  		if 0 < m && m < len(bcap) || err == syscall.EINTR {
   250  			b = b[m:]
   251  			continue
   252  		}
   253  
   254  		if needsMaxRW && len(bcap) != len(b) && err == nil {
   255  			b = b[m:]
   256  			continue
   257  		}
   258  
   259  		return n, err
   260  	}
   261  }
   262  
   263  // pwrite writes len(b) bytes to the File starting at byte offset off.
   264  // It returns the number of bytes written and an error, if any.
   265  func (f *File) pwrite(b []byte, off int64) (n int, err error) {
   266  	if needsMaxRW && len(b) > maxRW {
   267  		b = b[:maxRW]
   268  	}
   269  	return fixCount(syscall.Pwrite(f.fd, b, off))
   270  }
   271  
   272  // seek sets the offset for the next Read or Write on file to offset, interpreted
   273  // according to whence: 0 means relative to the origin of the file, 1 means
   274  // relative to the current offset, and 2 means relative to the end.
   275  // It returns the new offset and an error, if any.
   276  func (f *File) seek(offset int64, whence int) (ret int64, err error) {
   277  	return syscall.Seek(f.fd, offset, whence)
   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  	if e := syscall.Truncate(name, size); e != nil {
   285  		return &PathError{"truncate", name, e}
   286  	}
   287  	return nil
   288  }
   289  
   290  // Remove removes the named file or directory.
   291  // If there is an error, it will be of type *PathError.
   292  func Remove(name string) error {
   293  	// System call interface forces us to know
   294  	// whether name is a file or directory.
   295  	// Try both: it is cheaper on average than
   296  	// doing a Stat plus the right one.
   297  	e := syscall.Unlink(name)
   298  	if e == nil {
   299  		return nil
   300  	}
   301  	e1 := syscall.Rmdir(name)
   302  	if e1 == nil {
   303  		return nil
   304  	}
   305  
   306  	// Both failed: figure out which error to return.
   307  	// OS X and Linux differ on whether unlink(dir)
   308  	// returns EISDIR, so can't use that.  However,
   309  	// both agree that rmdir(file) returns ENOTDIR,
   310  	// so we can use that to decide which error is real.
   311  	// Rmdir might also return ENOTDIR if given a bad
   312  	// file path, like /etc/passwd/foo, but in that case,
   313  	// both errors will be ENOTDIR, so it's okay to
   314  	// use the error from unlink.
   315  	if e1 != syscall.ENOTDIR {
   316  		e = e1
   317  	}
   318  	return &PathError{"remove", name, e}
   319  }
   320  
   321  // basename removes trailing slashes and the leading directory name from path name
   322  func basename(name string) string {
   323  	i := len(name) - 1
   324  	// Remove trailing slashes
   325  	for ; i > 0 && name[i] == '/'; i-- {
   326  		name = name[:i]
   327  	}
   328  	// Remove leading directory name
   329  	for i--; i >= 0; i-- {
   330  		if name[i] == '/' {
   331  			name = name[i+1:]
   332  			break
   333  		}
   334  	}
   335  
   336  	return name
   337  }
   338  
   339  // TempDir returns the default directory to use for temporary files.
   340  func TempDir() string {
   341  	dir := Getenv("TMPDIR")
   342  	if dir == "" {
   343  		if runtime.GOOS == "android" {
   344  			dir = "/data/local/tmp"
   345  		} else {
   346  			dir = "/tmp"
   347  		}
   348  	}
   349  	return dir
   350  }
   351  
   352  // Link creates newname as a hard link to the oldname file.
   353  // If there is an error, it will be of type *LinkError.
   354  func Link(oldname, newname string) error {
   355  	e := syscall.Link(oldname, newname)
   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  // If there is an error, it will be of type *LinkError.
   364  func Symlink(oldname, newname string) error {
   365  	e := syscall.Symlink(oldname, newname)
   366  	if e != nil {
   367  		return &LinkError{"symlink", oldname, newname, e}
   368  	}
   369  	return nil
   370  }