file_unix.go 8.36 KB
Newer Older
1 2 3 4
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

5
// +build darwin freebsd linux netbsd openbsd
6

7 8 9 10 11 12 13
package os

import (
	"runtime"
	"syscall"
)

14 15
// File represents an open file descriptor.
type File struct {
16 17 18 19 20 21 22 23
	*file
}

// file is the real representation of *File.
// The extra level of indirection ensures that no clients of os
// can overwrite this data, which could cause the finalizer
// to close the wrong file descriptor.
type file struct {
24 25
	fd      int
	name    string
Fazlul Shahriar's avatar
Fazlul Shahriar committed
26 27
	dirinfo *dirInfo // nil unless directory being read
	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 40 41
func NewFile(fd uintptr, name string) *File {
	fdi := int(fd)
	if fdi < 0 {
42 43
		return nil
	}
44
	f := &File{&file{fd: fdi, name: name}}
45
	runtime.SetFinalizer(f.file, (*file).close)
46 47 48
	return f
}

49 50 51 52 53 54 55
// Auxiliary information if the File describes a directory
type dirInfo struct {
	buf  []byte // buffer for directory I/O
	nbuf int    // length of buf; return value from Getdirentries
	bufp int    // location of next record in buf.
}

Peter Mundy's avatar
Peter Mundy committed
56 57 58 59
// DevNull is the name of the operating system's ``null device.''
// On Unix-like systems, it is "/dev/null"; on Windows, "NUL".
const DevNull = "/dev/null"

Rob Pike's avatar
Rob Pike committed
60 61 62 63
// OpenFile is the generalized open call; most users will use Open
// or Create instead.  It opens the named file with specified flag
// (O_RDONLY etc.) and perm, (0666 etc.) if applicable.  If successful,
// methods on the returned File can be used for I/O.
64
// If there is an error, it will be of type *PathError.
65 66
func OpenFile(name string, flag int, perm FileMode) (file *File, err error) {
	r, e := syscall.Open(name, flag|syscall.O_CLOEXEC, syscallMode(perm))
Russ Cox's avatar
Russ Cox committed
67 68
	if e != nil {
		return nil, &PathError{"open", name, e}
69 70 71
	}

	// There's a race here with fork/exec, which we are
72 73 74 75 76 77 78
	// content to live with.  See ../syscall/exec_unix.go.
	// On OS X 10.6, the O_CLOEXEC flag is not respected.
	// On OS X 10.7, the O_CLOEXEC flag works.
	// Without a cheap & reliable way to detect 10.6 vs 10.7 at
	// runtime, we just always call syscall.CloseOnExec on Darwin.
	// Once >=10.7 is prevalent, this extra call can removed.
	if syscall.O_CLOEXEC == 0 || runtime.GOOS == "darwin" { // O_CLOEXEC not supported
79 80 81
		syscall.CloseOnExec(r)
	}

82
	return NewFile(uintptr(r), name), nil
83 84 85
}

// Close closes the File, rendering it unusable for I/O.
Russ Cox's avatar
Russ Cox committed
86
// It returns an error, if any.
87 88
func (f *File) Close() error {
	return f.file.close()
89 90 91
}

func (file *file) close() error {
92
	if file == nil || file.fd < 0 {
Rob Pike's avatar
Rob Pike committed
93
		return syscall.EINVAL
94
	}
Russ Cox's avatar
Russ Cox committed
95
	var err error
Russ Cox's avatar
Russ Cox committed
96 97
	if e := syscall.Close(file.fd); e != nil {
		err = &PathError{"close", file.name, e}
98 99 100 101 102 103 104 105
	}
	file.fd = -1 // so it can't be closed again

	// no need for a finalizer anymore
	runtime.SetFinalizer(file, nil)
	return err
}

Alex Brainman's avatar
Alex Brainman committed
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) {
Alex Brainman's avatar
Alex Brainman committed
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}
Alex Brainman's avatar
Alex Brainman committed
113
	}
114
	return fileInfoFromStat(&stat, f.name), nil
Alex Brainman's avatar
Alex Brainman committed
115 116
}

117 118
// Stat returns a FileInfo describing the named file.
// If there is an error, it will be of type *PathError.
119 120 121 122 123
func Stat(name string) (fi FileInfo, err error) {
	var stat syscall.Stat_t
	err = syscall.Stat(name, &stat)
	if err != nil {
		return nil, &PathError{"stat", name, err}
124
	}
125
	return fileInfoFromStat(&stat, name), nil
126 127
}

128 129
// Lstat returns a FileInfo describing the named file.
// 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 135 136
	err = syscall.Lstat(name, &stat)
	if err != nil {
		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 144 145 146
	if dirname == "" {
		dirname = "."
	}
	dirname += "/"
147
	names, err := f.Readdirnames(n)
148 149 150
	fi = make([]FileInfo, len(names))
	for i, filename := range names {
		fip, err := Lstat(dirname + filename)
151 152
		if err == nil {
			fi[i] = fip
153
		} else {
154
			fi[i] = &fileStat{name: filename}
155 156
		}
	}
157
	return fi, err
158
}
Alex Brainman's avatar
Alex Brainman committed
159

160 161
// read reads up to len(b) bytes from the File.
// It returns the number of bytes read and an error, if any.
Russ Cox's avatar
Russ Cox committed
162
func (f *File) read(b []byte) (n int, err error) {
163 164 165 166 167 168
	return syscall.Read(f.fd, b)
}

// pread reads len(b) bytes from the File starting at byte offset off.
// It returns the number of bytes read and the error, if any.
// EOF is signaled by a zero count with err set to 0.
Russ Cox's avatar
Russ Cox committed
169
func (f *File) pread(b []byte, off int64) (n int, err error) {
170 171 172 173 174
	return syscall.Pread(f.fd, b, off)
}

// write writes len(b) bytes to the File.
// It returns the number of bytes written and an error, if any.
Russ Cox's avatar
Russ Cox committed
175
func (f *File) write(b []byte) (n int, err error) {
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
	for {
		m, err := syscall.Write(f.fd, b)
		n += m

		// If the syscall wrote some data but not all (short write)
		// or it returned EINTR, then assume it stopped early for
		// reasons that are uninteresting to the caller, and try again.
		if 0 < m && m < len(b) || err == syscall.EINTR {
			b = b[m:]
			continue
		}

		return n, err
	}
	panic("not reached")
191 192 193 194
}

// pwrite writes len(b) bytes to the File starting at byte offset off.
// It returns the number of bytes written and an error, if any.
Russ Cox's avatar
Russ Cox committed
195
func (f *File) pwrite(b []byte, off int64) (n int, err error) {
196 197 198 199 200 201 202
	return syscall.Pwrite(f.fd, b, off)
}

// seek sets the offset for the next Read or Write on file to offset, interpreted
// according to whence: 0 means relative to the origin of the file, 1 means
// relative to the current offset, and 2 means relative to the end.
// It returns the new offset and an error, if any.
Russ Cox's avatar
Russ Cox committed
203
func (f *File) seek(offset int64, whence int) (ret int64, err error) {
204 205 206
	return syscall.Seek(f.fd, offset, whence)
}

Alex Brainman's avatar
Alex Brainman committed
207 208
// Truncate changes the size of the named file.
// 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.
Russ Cox's avatar
Russ Cox committed
210
func Truncate(name string, size int64) error {
Russ Cox's avatar
Russ Cox committed
211 212
	if e := syscall.Truncate(name, size); e != nil {
		return &PathError{"truncate", name, e}
Alex Brainman's avatar
Alex Brainman committed
213 214 215
	}
	return nil
}
216

217
// Remove removes the named file or directory.
218
// If there is an error, it will be of type *PathError.
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
func Remove(name string) error {
	// System call interface forces us to know
	// whether name is a file or directory.
	// Try both: it is cheaper on average than
	// doing a Stat plus the right one.
	e := syscall.Unlink(name)
	if e == nil {
		return nil
	}
	e1 := syscall.Rmdir(name)
	if e1 == nil {
		return nil
	}

	// Both failed: figure out which error to return.
	// OS X and Linux differ on whether unlink(dir)
	// returns EISDIR, so can't use that.  However,
	// both agree that rmdir(file) returns ENOTDIR,
	// so we can use that to decide which error is real.
	// Rmdir might also return ENOTDIR if given a bad
	// file path, like /etc/passwd/foo, but in that case,
	// both errors will be ENOTDIR, so it's okay to
	// use the error from unlink.
	if e1 != syscall.ENOTDIR {
		e = e1
	}
	return &PathError{"remove", name, e}
}

248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
// basename removes trailing slashes and the leading directory name from path name
func basename(name string) string {
	i := len(name) - 1
	// Remove trailing slashes
	for ; i > 0 && name[i] == '/'; i-- {
		name = name[:i]
	}
	// Remove leading directory name
	for i--; i >= 0; i-- {
		if name[i] == '/' {
			name = name[i+1:]
			break
		}
	}

	return name
}
265 266

// Pipe returns a connected pair of Files; reads from r return bytes written to w.
Russ Cox's avatar
Russ Cox committed
267 268
// It returns the files and an error, if any.
func Pipe() (r *File, w *File, err error) {
269 270 271 272 273
	var p [2]int

	// See ../syscall/exec.go for description of lock.
	syscall.ForkLock.RLock()
	e := syscall.Pipe(p[0:])
Russ Cox's avatar
Russ Cox committed
274
	if e != nil {
275 276 277 278 279 280 281
		syscall.ForkLock.RUnlock()
		return nil, nil, NewSyscallError("pipe", e)
	}
	syscall.CloseOnExec(p[0])
	syscall.CloseOnExec(p[1])
	syscall.ForkLock.RUnlock()

282
	return NewFile(uintptr(p[0]), "|0"), NewFile(uintptr(p[1]), "|1"), nil
283
}
284 285 286 287 288 289 290 291 292

// TempDir returns the default directory to use for temporary files.
func TempDir() string {
	dir := Getenv("TMPDIR")
	if dir == "" {
		dir = "/tmp"
	}
	return dir
}