src/pkg/os/file_unix.go - The Go Programming Language

Golang

Source file src/pkg/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 freebsd linux netbsd openbsd
     6	
     7	package os
     8	
     9	import (
    10		"runtime"
    11		"syscall"
    12	)
    13	
    14	// File represents an open file descriptor.
    15	type File struct {
    16		*file
    17	}
    18	
    19	// file is the real representation of *File.
    20	// The extra level of indirection ensures that no clients of os
    21	// can overwrite this data, which could cause the finalizer
    22	// to close the wrong file descriptor.
    23	type file struct {
    24		fd      int
    25		name    string
    26		dirinfo *dirInfo // nil unless directory being read
    27		nepipe  int      // number of consecutive EPIPE in Write
    28	}
    29	
    30	// Fd returns the integer Unix file descriptor referencing the open file.
    31	func (f *File) Fd() uintptr {
    32		if f == nil {
    33			return ^(uintptr(0))
    34		}
    35		return uintptr(f.fd)
    36	}
    37	
    38	// NewFile returns a new File with the given file descriptor and name.
    39	func NewFile(fd uintptr, name string) *File {
    40		fdi := int(fd)
    41		if fdi < 0 {
    42			return nil
    43		}
    44		f := &File{&file{fd: fdi, name: name}}
    45		runtime.SetFinalizer(f.file, (*file).close)
    46		return f
    47	}
    48	
    49	// Auxiliary information if the File describes a directory
    50	type dirInfo struct {
    51		buf  []byte // buffer for directory I/O
    52		nbuf int    // length of buf; return value from Getdirentries
    53		bufp int    // location of next record in buf.
    54	}
    55	
    56	// DevNull is the name of the operating system's ``null device.''
    57	// On Unix-like systems, it is "/dev/null"; on Windows, "NUL".
    58	const DevNull = "/dev/null"
    59	
    60	// OpenFile is the generalized open call; most users will use Open
    61	// or Create instead.  It opens the named file with specified flag
    62	// (O_RDONLY etc.) and perm, (0666 etc.) if applicable.  If successful,
    63	// methods on the returned File can be used for I/O.
    64	// If there is an error, it will be of type *PathError.
    65	func OpenFile(name string, flag int, perm FileMode) (file *File, err error) {
    66		r, e := syscall.Open(name, flag|syscall.O_CLOEXEC, syscallMode(perm))
    67		if e != nil {
    68			return nil, &PathError{"open", name, e}
    69		}
    70	
    71		// There's a race here with fork/exec, which we are
    72		// content to live with.  See ../syscall/exec_unix.go.
    73		// On OS X 10.6, the O_CLOEXEC flag is not respected.
    74		// On OS X 10.7, the O_CLOEXEC flag works.
    75		// Without a cheap & reliable way to detect 10.6 vs 10.7 at
    76		// runtime, we just always call syscall.CloseOnExec on Darwin.
    77		// Once >=10.7 is prevalent, this extra call can removed.
    78		if syscall.O_CLOEXEC == 0 || runtime.GOOS == "darwin" { // O_CLOEXEC not supported
    79			syscall.CloseOnExec(r)
    80		}
    81	
    82		return NewFile(uintptr(r), name), nil
    83	}
    84	
    85	// Close closes the File, rendering it unusable for I/O.
    86	// It returns an error, if any.
    87	func (f *File) Close() error {
    88		return f.file.close()
    89	}
    90	
    91	func (file *file) close() error {
    92		if file == nil || file.fd < 0 {
    93			return syscall.EINVAL
    94		}
    95		var err error
    96		if e := syscall.Close(file.fd); e != nil {
    97			err = &PathError{"close", file.name, e}
    98		}
    99		file.fd = -1 // so it can't be closed again
   100	
   101		// no need for a finalizer anymore
   102		runtime.SetFinalizer(file, nil)
   103		return err
   104	}
   105	
   106	// Stat returns the FileInfo structure describing file.
   107	// If there is an error, it will be of type *PathError.
   108	func (f *File) Stat() (fi FileInfo, err error) {
   109		var stat syscall.Stat_t
   110		err = syscall.Fstat(f.fd, &stat)
   111		if err != nil {
   112			return nil, &PathError{"stat", f.name, err}
   113		}
   114		return fileInfoFromStat(&stat, f.name), nil
   115	}
   116	
   117	// Stat returns a FileInfo describing the named file.
   118	// If there is an error, it will be of type *PathError.
   119	func Stat(name string) (fi FileInfo, err error) {
   120		var stat syscall.Stat_t
   121		err = syscall.Stat(name, &stat)
   122		if err != nil {
   123			return nil, &PathError{"stat", name, err}
   124		}
   125		return fileInfoFromStat(&stat, name), nil
   126	}
   127	
   128	// Lstat returns a FileInfo describing the named file.
   129	// If the file is a symbolic link, the returned FileInfo
   130	// describes the symbolic link.  Lstat makes no attempt to follow the link.
   131	// If there is an error, it will be of type *PathError.
   132	func Lstat(name string) (fi FileInfo, err error) {
   133		var stat syscall.Stat_t
   134		err = syscall.Lstat(name, &stat)
   135		if err != nil {
   136			return nil, &PathError{"lstat", name, err}
   137		}
   138		return fileInfoFromStat(&stat, name), nil
   139	}
   140	
   141	func (f *File) readdir(n int) (fi []FileInfo, err error) {
   142		dirname := f.name
   143		if dirname == "" {
   144			dirname = "."
   145		}
   146		dirname += "/"
   147		names, err := f.Readdirnames(n)
   148		fi = make([]FileInfo, len(names))
   149		for i, filename := range names {
   150			fip, err := Lstat(dirname + filename)
   151			if err == nil {
   152				fi[i] = fip
   153			} else {
   154				fi[i] = &fileStat{name: filename}
   155			}
   156		}
   157		return fi, err
   158	}
   159	
   160	// read reads up to len(b) bytes from the File.
   161	// It returns the number of bytes read and an error, if any.
   162	func (f *File) read(b []byte) (n int, err error) {
   163		return syscall.Read(f.fd, b)
   164	}
   165	
   166	// pread reads len(b) bytes from the File starting at byte offset off.
   167	// It returns the number of bytes read and the error, if any.
   168	// EOF is signaled by a zero count with err set to 0.
   169	func (f *File) pread(b []byte, off int64) (n int, err error) {
   170		return syscall.Pread(f.fd, b, off)
   171	}
   172	
   173	// write writes len(b) bytes to the File.
   174	// It returns the number of bytes written and an error, if any.
   175	func (f *File) write(b []byte) (n int, err error) {
   176		for {
   177			m, err := syscall.Write(f.fd, b)
   178			n += m
   179	
   180			// If the syscall wrote some data but not all (short write)
   181			// or it returned EINTR, then assume it stopped early for
   182			// reasons that are uninteresting to the caller, and try again.
   183			if 0 < m && m < len(b) || err == syscall.EINTR {
   184				b = b[m:]
   185				continue
   186			}
   187	
   188			return n, err
   189		}
   190		panic("not reached")
   191	}
   192	
   193	// pwrite writes len(b) bytes to the File starting at byte offset off.
   194	// It returns the number of bytes written and an error, if any.
   195	func (f *File) pwrite(b []byte, off int64) (n int, err error) {
   196		return syscall.Pwrite(f.fd, b, off)
   197	}
   198	
   199	// seek sets the offset for the next Read or Write on file to offset, interpreted
   200	// according to whence: 0 means relative to the origin of the file, 1 means
   201	// relative to the current offset, and 2 means relative to the end.
   202	// It returns the new offset and an error, if any.
   203	func (f *File) seek(offset int64, whence int) (ret int64, err error) {
   204		return syscall.Seek(f.fd, offset, whence)
   205	}
   206	
   207	// Truncate changes the size of the named file.
   208	// If the file is a symbolic link, it changes the size of the link's target.
   209	// If there is an error, it will be of type *PathError.
   210	func Truncate(name string, size int64) error {
   211		if e := syscall.Truncate(name, size); e != nil {
   212			return &PathError{"truncate", name, e}
   213		}
   214		return nil
   215	}
   216	
   217	// Remove removes the named file or directory.
   218	// If there is an error, it will be of type *PathError.
   219	func Remove(name string) error {
   220		// System call interface forces us to know
   221		// whether name is a file or directory.
   222		// Try both: it is cheaper on average than
   223		// doing a Stat plus the right one.
   224		e := syscall.Unlink(name)
   225		if e == nil {
   226			return nil
   227		}
   228		e1 := syscall.Rmdir(name)
   229		if e1 == nil {
   230			return nil
   231		}
   232	
   233		// Both failed: figure out which error to return.
   234		// OS X and Linux differ on whether unlink(dir)
   235		// returns EISDIR, so can't use that.  However,
   236		// both agree that rmdir(file) returns ENOTDIR,
   237		// so we can use that to decide which error is real.
   238		// Rmdir might also return ENOTDIR if given a bad
   239		// file path, like /etc/passwd/foo, but in that case,
   240		// both errors will be ENOTDIR, so it's okay to
   241		// use the error from unlink.
   242		if e1 != syscall.ENOTDIR {
   243			e = e1
   244		}
   245		return &PathError{"remove", name, e}
   246	}
   247	
   248	// basename removes trailing slashes and the leading directory name from path name
   249	func basename(name string) string {
   250		i := len(name) - 1
   251		// Remove trailing slashes
   252		for ; i > 0 && name[i] == '/'; i-- {
   253			name = name[:i]
   254		}
   255		// Remove leading directory name
   256		for i--; i >= 0; i-- {
   257			if name[i] == '/' {
   258				name = name[i+1:]
   259				break
   260			}
   261		}
   262	
   263		return name
   264	}
   265	
   266	// Pipe returns a connected pair of Files; reads from r return bytes written to w.
   267	// It returns the files and an error, if any.
   268	func Pipe() (r *File, w *File, err error) {
   269		var p [2]int
   270	
   271		// See ../syscall/exec.go for description of lock.
   272		syscall.ForkLock.RLock()
   273		e := syscall.Pipe(p[0:])
   274		if e != nil {
   275			syscall.ForkLock.RUnlock()
   276			return nil, nil, NewSyscallError("pipe", e)
   277		}
   278		syscall.CloseOnExec(p[0])
   279		syscall.CloseOnExec(p[1])
   280		syscall.ForkLock.RUnlock()
   281	
   282		return NewFile(uintptr(p[0]), "|0"), NewFile(uintptr(p[1]), "|1"), nil
   283	}
   284	
   285	// TempDir returns the default directory to use for temporary files.
   286	func TempDir() string {
   287		dir := Getenv("TMPDIR")
   288		if dir == "" {
   289			dir = "/tmp"
   290		}
   291		return dir
   292	}