OSDN Git Service

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