OSDN Git Service

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