...
Run Format

Source file src/os/file_unix.go

     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	// fixLongPath is a noop on non-Windows platforms.
    15	func fixLongPath(path string) string {
    16		return path
    17	}
    18	
    19	func rename(oldname, newname string) error {
    20		fi, err := Lstat(newname)
    21		if err == nil && fi.IsDir() {
    22			return &LinkError{"rename", oldname, newname, syscall.EEXIST}
    23		}
    24		e := syscall.Rename(oldname, newname)
    25		if e != nil {
    26			return &LinkError{"rename", oldname, newname, e}
    27		}
    28		return nil
    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 == badFd {
   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	// Darwin and FreeBSD can't read or write 2GB+ at a time,
   151	// even on 64-bit systems. See golang.org/issue/7812.
   152	// Use 1GB instead of, say, 2GB-1, to keep subsequent
   153	// reads aligned.
   154	const (
   155		needsMaxRW = runtime.GOOS == "darwin" || runtime.GOOS == "freebsd"
   156		maxRW      = 1 << 30
   157	)
   158	
   159	// read reads up to len(b) bytes from the File.
   160	// It returns the number of bytes read and an error, if any.
   161	func (f *File) read(b []byte) (n int, err error) {
   162		if needsMaxRW && len(b) > maxRW {
   163			b = b[:maxRW]
   164		}
   165		return fixCount(syscall.Read(f.fd, b))
   166	}
   167	
   168	// pread reads len(b) bytes from the File starting at byte offset off.
   169	// It returns the number of bytes read and the error, if any.
   170	// EOF is signaled by a zero count with err set to nil.
   171	func (f *File) pread(b []byte, off int64) (n int, err error) {
   172		if needsMaxRW && len(b) > maxRW {
   173			b = b[:maxRW]
   174		}
   175		return fixCount(syscall.Pread(f.fd, b, off))
   176	}
   177	
   178	// write writes len(b) bytes to the File.
   179	// It returns the number of bytes written and an error, if any.
   180	func (f *File) write(b []byte) (n int, err error) {
   181		for {
   182			bcap := b
   183			if needsMaxRW && len(bcap) > maxRW {
   184				bcap = bcap[:maxRW]
   185			}
   186			m, err := fixCount(syscall.Write(f.fd, bcap))
   187			n += m
   188	
   189			// If the syscall wrote some data but not all (short write)
   190			// or it returned EINTR, then assume it stopped early for
   191			// reasons that are uninteresting to the caller, and try again.
   192			if 0 < m && m < len(bcap) || err == syscall.EINTR {
   193				b = b[m:]
   194				continue
   195			}
   196	
   197			if needsMaxRW && len(bcap) != len(b) && err == nil {
   198				b = b[m:]
   199				continue
   200			}
   201	
   202			return n, err
   203		}
   204	}
   205	
   206	// pwrite writes len(b) bytes to the File starting at byte offset off.
   207	// It returns the number of bytes written and an error, if any.
   208	func (f *File) pwrite(b []byte, off int64) (n int, err error) {
   209		if needsMaxRW && len(b) > maxRW {
   210			b = b[:maxRW]
   211		}
   212		return fixCount(syscall.Pwrite(f.fd, b, off))
   213	}
   214	
   215	// seek sets the offset for the next Read or Write on file to offset, interpreted
   216	// according to whence: 0 means relative to the origin of the file, 1 means
   217	// relative to the current offset, and 2 means relative to the end.
   218	// It returns the new offset and an error, if any.
   219	func (f *File) seek(offset int64, whence int) (ret int64, err error) {
   220		return syscall.Seek(f.fd, offset, whence)
   221	}
   222	
   223	// Truncate changes the size of the named file.
   224	// If the file is a symbolic link, it changes the size of the link's target.
   225	// If there is an error, it will be of type *PathError.
   226	func Truncate(name string, size int64) error {
   227		if e := syscall.Truncate(name, size); e != nil {
   228			return &PathError{"truncate", name, e}
   229		}
   230		return nil
   231	}
   232	
   233	// Remove removes the named file or directory.
   234	// If there is an error, it will be of type *PathError.
   235	func Remove(name string) error {
   236		// System call interface forces us to know
   237		// whether name is a file or directory.
   238		// Try both: it is cheaper on average than
   239		// doing a Stat plus the right one.
   240		e := syscall.Unlink(name)
   241		if e == nil {
   242			return nil
   243		}
   244		e1 := syscall.Rmdir(name)
   245		if e1 == nil {
   246			return nil
   247		}
   248	
   249		// Both failed: figure out which error to return.
   250		// OS X and Linux differ on whether unlink(dir)
   251		// returns EISDIR, so can't use that. However,
   252		// both agree that rmdir(file) returns ENOTDIR,
   253		// so we can use that to decide which error is real.
   254		// Rmdir might also return ENOTDIR if given a bad
   255		// file path, like /etc/passwd/foo, but in that case,
   256		// both errors will be ENOTDIR, so it's okay to
   257		// use the error from unlink.
   258		if e1 != syscall.ENOTDIR {
   259			e = e1
   260		}
   261		return &PathError{"remove", name, e}
   262	}
   263	
   264	// TempDir returns the default directory to use for temporary files.
   265	func TempDir() string {
   266		dir := Getenv("TMPDIR")
   267		if dir == "" {
   268			if runtime.GOOS == "android" {
   269				dir = "/data/local/tmp"
   270			} else {
   271				dir = "/tmp"
   272			}
   273		}
   274		return dir
   275	}
   276	
   277	// Link creates newname as a hard link to the oldname file.
   278	// If there is an error, it will be of type *LinkError.
   279	func Link(oldname, newname string) error {
   280		e := syscall.Link(oldname, newname)
   281		if e != nil {
   282			return &LinkError{"link", oldname, newname, e}
   283		}
   284		return nil
   285	}
   286	
   287	// Symlink creates newname as a symbolic link to oldname.
   288	// If there is an error, it will be of type *LinkError.
   289	func Symlink(oldname, newname string) error {
   290		e := syscall.Symlink(oldname, newname)
   291		if e != nil {
   292			return &LinkError{"symlink", oldname, newname, e}
   293		}
   294		return nil
   295	}
   296	

View as plain text