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