file_unix.go 8.33 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 dragonfly freebsd linux nacl netbsd openbsd solaris
6

7 8 9 10 11 12 13
package os

import (
	"runtime"
	"syscall"
)

14 15 16
// fixLongPath is a noop on non-Windows platforms.
func fixLongPath(path string) string {
	return path
17 18
}

19
func rename(oldname, newname string) error {
20 21 22 23
	fi, err := Lstat(newname)
	if err == nil && fi.IsDir() {
		return &LinkError{"rename", oldname, newname, syscall.EEXIST}
	}
24 25 26 27 28 29 30
	e := syscall.Rename(oldname, newname)
	if e != nil {
		return &LinkError{"rename", oldname, newname, e}
	}
	return nil
}

31 32 33 34 35
// 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 {
36 37 38 39 40 41
	fd      int
	name    string
	dirinfo *dirInfo // nil unless directory being read
}

// 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 52 53
func NewFile(fd uintptr, name string) *File {
	fdi := int(fd)
	if fdi < 0 {
54 55
		return nil
	}
56
	f := &File{&file{fd: fdi, name: name}}
57
	runtime.SetFinalizer(f.file, (*file).close)
58 59 60
	return f
}

61 62
// Auxiliary information if the File describes a directory
type dirInfo struct {
63
	buf []byte       // buffer for directory I/O
64 65 66
	dir *syscall.DIR // from opendir
}

67 68 69
// epipecheck raises SIGPIPE if we get an EPIPE error on standard
// output or standard error. See the SIGPIPE docs in os/signal, and
// issue 11845.
70
func epipecheck(file *File, e error) {
71 72
	if e == syscall.EPIPE && (file.fd == 1 || file.fd == 2) {
		sigpipe()
73 74 75
	}
}

76 77 78 79
// 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"

80
// OpenFile is the generalized open call; most users will use Open
81 82
// or Create instead. It opens the named file with specified flag
// (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 86 87 88 89 90 91 92
func OpenFile(name string, flag int, perm FileMode) (*File, error) {
	chmod := false
	if !supportsCreateWithStickyBit && flag&O_CREATE != 0 && perm&ModeSticky != 0 {
		if _, err := Stat(name); IsNotExist(err) {
			chmod = true
		}
	}

93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
	var r int
	for {
		var e error
		r, e = syscall.Open(name, flag|syscall.O_CLOEXEC, syscallMode(perm))
		if e == nil {
			break
		}

		// On OS X, sigaction(2) doesn't guarantee that SA_RESTART will cause
		// open(2) to be restarted for regular files. This is easy to reproduce on
		// fuse file systems (see http://golang.org/issue/11180).
		if runtime.GOOS == "darwin" && e == syscall.EINTR {
			continue
		}

108
		return nil, &PathError{"open", name, e}
109 110
	}

111 112 113 114 115
	// open(2) itself won't handle the sticky bit on *BSD and Solaris
	if chmod {
		Chmod(name, perm)
	}

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 120 121
		syscall.CloseOnExec(r)
	}

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 129 130
	if f == nil {
		return ErrInvalid
	}
131
	return f.file.close()
132 133 134
}

func (file *file) close() error {
135
	if file == nil || file.fd == badFd {
136
		return syscall.EINVAL
137
	}
138
	var err error
139 140
	if e := syscall.Close(file.fd); e != nil {
		err = &PathError{"close", file.name, e}
141
	}
142 143

	if file.dirinfo != nil {
144 145 146 147 148 149 150
		syscall.Entersyscall()
		i := libc_closedir(file.dirinfo.dir)
		errno := syscall.GetErrno()
		syscall.Exitsyscall()
		file.dirinfo = nil
		if i < 0 && err == nil {
			err = &PathError{"closedir", file.name, errno}
151 152 153
		}
	}

154 155 156 157 158 159 160
	file.fd = -1 // so it can't be closed again

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

161 162 163 164 165 166 167 168 169
// Darwin and FreeBSD can't read or write 2GB+ at a time,
// even on 64-bit systems. See golang.org/issue/7812.
// Use 1GB instead of, say, 2GB-1, to keep subsequent
// reads aligned.
const (
	needsMaxRW = runtime.GOOS == "darwin" || runtime.GOOS == "freebsd"
	maxRW      = 1 << 30
)

170 171
// read reads up to len(b) bytes from the File.
// It returns the number of bytes read and an error, if any.
172
func (f *File) read(b []byte) (n int, err error) {
173 174 175
	if needsMaxRW && len(b) > maxRW {
		b = b[:maxRW]
	}
176
	return fixCount(syscall.Read(f.fd, b))
177 178 179 180
}

// 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.
181
// EOF is signaled by a zero count with err set to nil.
182
func (f *File) pread(b []byte, off int64) (n int, err error) {
183 184 185
	if needsMaxRW && len(b) > maxRW {
		b = b[:maxRW]
	}
186
	return fixCount(syscall.Pread(f.fd, b, off))
187 188 189 190
}

// write writes len(b) bytes to the File.
// It returns the number of bytes written and an error, if any.
191
func (f *File) write(b []byte) (n int, err error) {
192
	for {
193 194 195 196
		bcap := b
		if needsMaxRW && len(bcap) > maxRW {
			bcap = bcap[:maxRW]
		}
197
		m, err := fixCount(syscall.Write(f.fd, bcap))
198 199 200 201 202
		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.
203 204 205 206 207 208
		if 0 < m && m < len(bcap) || err == syscall.EINTR {
			b = b[m:]
			continue
		}

		if needsMaxRW && len(bcap) != len(b) && err == nil {
209 210 211 212 213 214
			b = b[m:]
			continue
		}

		return n, err
	}
215 216 217 218
}

// 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.
219
func (f *File) pwrite(b []byte, off int64) (n int, err error) {
220 221 222
	if needsMaxRW && len(b) > maxRW {
		b = b[:maxRW]
	}
223
	return fixCount(syscall.Pwrite(f.fd, b, off))
224 225 226 227 228 229
}

// 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.
230
func (f *File) seek(offset int64, whence int) (ret int64, err error) {
231 232 233
	return syscall.Seek(f.fd, offset, whence)
}

234 235
// Truncate changes the size of the named file.
// If the file is a symbolic link, it changes the size of the link's target.
236
// If there is an error, it will be of type *PathError.
237
func Truncate(name string, size int64) error {
238 239
	if e := syscall.Truncate(name, size); e != nil {
		return &PathError{"truncate", name, e}
240 241 242
	}
	return nil
}
243

244
// Remove removes the named file or directory.
245
// If there is an error, it will be of type *PathError.
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
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)
262
	// returns EISDIR, so can't use that. However,
263 264 265 266 267 268 269 270 271 272 273 274
	// 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}
}

275 276 277 278
// TempDir returns the default directory to use for temporary files.
func TempDir() string {
	dir := Getenv("TMPDIR")
	if dir == "" {
279 280 281 282 283
		if runtime.GOOS == "android" {
			dir = "/data/local/tmp"
		} else {
			dir = "/tmp"
		}
284 285 286
	}
	return dir
}
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306

// Link creates newname as a hard link to the oldname file.
// If there is an error, it will be of type *LinkError.
func Link(oldname, newname string) error {
	e := syscall.Link(oldname, newname)
	if e != nil {
		return &LinkError{"link", oldname, newname, e}
	}
	return nil
}

// Symlink creates newname as a symbolic link to oldname.
// If there is an error, it will be of type *LinkError.
func Symlink(oldname, newname string) error {
	e := syscall.Symlink(oldname, newname)
	if e != nil {
		return &LinkError{"symlink", oldname, newname, e}
	}
	return nil
}