OSDN Git Service

libgo: Update to weekly.2011-11-18.
[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 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 (file *File) Fd() int {
32         if file == nil {
33                 return -1
34         }
35         return file.fd
36 }
37
38 // NewFile returns a new File with the given file descriptor and name.
39 func NewFile(fd int, name string) *File {
40         if fd < 0 {
41                 return nil
42         }
43         f := &File{&file{fd: fd, name: name}}
44         runtime.SetFinalizer(f.file, (*file).close)
45         return f
46 }
47
48 // Auxiliary information if the File describes a directory
49 type dirInfo struct {
50         buf []byte       // buffer for directory I/O
51         dir *syscall.DIR // from opendir
52 }
53
54 // DevNull is the name of the operating system's ``null device.''
55 // On Unix-like systems, it is "/dev/null"; on Windows, "NUL".
56 const DevNull = "/dev/null"
57
58 // OpenFile is the generalized open call; most users will use Open
59 // or Create instead.  It opens the named file with specified flag
60 // (O_RDONLY etc.) and perm, (0666 etc.) if applicable.  If successful,
61 // methods on the returned File can be used for I/O.
62 // It returns the File and an error, if any.
63 func OpenFile(name string, flag int, perm uint32) (file *File, err error) {
64         r, e := syscall.Open(name, flag|syscall.O_CLOEXEC, perm)
65         if e != nil {
66                 return nil, &PathError{"open", name, e}
67         }
68
69         // There's a race here with fork/exec, which we are
70         // content to live with.  See ../syscall/exec.go
71         if syscall.O_CLOEXEC == 0 { // O_CLOEXEC not supported
72                 syscall.CloseOnExec(r)
73         }
74
75         return NewFile(r, name), nil
76 }
77
78 // Close closes the File, rendering it unusable for I/O.
79 // It returns an error, if any.
80 func (file *File) Close() error {
81         return file.file.close()
82 }
83
84 func (file *file) close() error {
85         if file == nil || file.fd < 0 {
86                 return EINVAL
87         }
88         var err error
89         if e := syscall.Close(file.fd); e != nil {
90                 err = &PathError{"close", file.name, e}
91         }
92
93         if file.dirinfo != nil {
94                 if libc_closedir(file.dirinfo.dir) < 0 && err == nil {
95                         err = &PathError{"closedir", file.name, syscall.GetErrno()}
96                 }
97         }
98
99         file.fd = -1 // so it can't be closed again
100
101         // no need for a finalizer anymore
102         runtime.SetFinalizer(file, nil)
103         return err
104 }
105
106 // Stat returns the FileInfo structure describing file.
107 // It returns the FileInfo and an error, if any.
108 func (file *File) Stat() (fi *FileInfo, err error) {
109         var stat syscall.Stat_t
110         e := syscall.Fstat(file.fd, &stat)
111         if e != nil {
112                 return nil, &PathError{"stat", file.name, e}
113         }
114         return fileInfoFromStat(file.name, new(FileInfo), &stat, &stat), nil
115 }
116
117 // Stat returns a FileInfo structure describing the named file and an error, if any.
118 // If name names a valid symbolic link, the returned FileInfo describes
119 // the file pointed at by the link and has fi.FollowedSymlink set to true.
120 // If name names an invalid symbolic link, the returned FileInfo describes
121 // the link itself and has fi.FollowedSymlink set to false.
122 func Stat(name string) (fi *FileInfo, err error) {
123         var lstat, stat syscall.Stat_t
124         e := syscall.Lstat(name, &lstat)
125         if e != nil {
126                 return nil, &PathError{"stat", name, e}
127         }
128         statp := &lstat
129         if lstat.Mode&syscall.S_IFMT == syscall.S_IFLNK {
130                 e := syscall.Stat(name, &stat)
131                 if e == nil {
132                         statp = &stat
133                 }
134         }
135         return fileInfoFromStat(name, new(FileInfo), &lstat, statp), nil
136 }
137
138 // Lstat returns the FileInfo structure describing the named file and an
139 // error, if any.  If the file is a symbolic link, the returned FileInfo
140 // describes the symbolic link.  Lstat makes no attempt to follow the link.
141 func Lstat(name string) (fi *FileInfo, err error) {
142         var stat syscall.Stat_t
143         e := syscall.Lstat(name, &stat)
144         if e != nil {
145                 return nil, &PathError{"lstat", name, e}
146         }
147         return fileInfoFromStat(name, new(FileInfo), &stat, &stat), nil
148 }
149
150 // Readdir reads the contents of the directory associated with file and
151 // returns an array of up to n FileInfo structures, as would be returned
152 // by Lstat, in directory order. Subsequent calls on the same file will yield
153 // further FileInfos.
154 //
155 // If n > 0, Readdir returns at most n FileInfo structures. In this case, if
156 // Readdir returns an empty slice, it will return a non-nil error
157 // explaining why. At the end of a directory, the error is io.EOF.
158 //
159 // If n <= 0, Readdir returns all the FileInfo from the directory in
160 // a single slice. In this case, if Readdir succeeds (reads all
161 // the way to the end of the directory), it returns the slice and a
162 // nil error. If it encounters an error before the end of the
163 // directory, Readdir returns the FileInfo read until that point
164 // and a non-nil error.
165 func (file *File) Readdir(n int) (fi []FileInfo, err error) {
166         dirname := file.name
167         if dirname == "" {
168                 dirname = "."
169         }
170         dirname += "/"
171         names, err := file.Readdirnames(n)
172         fi = make([]FileInfo, len(names))
173         for i, filename := range names {
174                 fip, err := Lstat(dirname + filename)
175                 if fip == nil || err != nil {
176                         fi[i].Name = filename // rest is already zeroed out
177                 } else {
178                         fi[i] = *fip
179                 }
180         }
181         return
182 }
183
184 // read reads up to len(b) bytes from the File.
185 // It returns the number of bytes read and an error, if any.
186 func (f *File) read(b []byte) (n int, err error) {
187         return syscall.Read(f.fd, b)
188 }
189
190 // pread reads len(b) bytes from the File starting at byte offset off.
191 // It returns the number of bytes read and the error, if any.
192 // EOF is signaled by a zero count with err set to 0.
193 func (f *File) pread(b []byte, off int64) (n int, err error) {
194         return syscall.Pread(f.fd, b, off)
195 }
196
197 // write writes len(b) bytes to the File.
198 // It returns the number of bytes written and an error, if any.
199 func (f *File) write(b []byte) (n int, err error) {
200         return syscall.Write(f.fd, b)
201 }
202
203 // pwrite writes len(b) bytes to the File starting at byte offset off.
204 // It returns the number of bytes written and an error, if any.
205 func (f *File) pwrite(b []byte, off int64) (n int, err error) {
206         return syscall.Pwrite(f.fd, b, off)
207 }
208
209 // seek sets the offset for the next Read or Write on file to offset, interpreted
210 // according to whence: 0 means relative to the origin of the file, 1 means
211 // relative to the current offset, and 2 means relative to the end.
212 // It returns the new offset and an error, if any.
213 func (f *File) seek(offset int64, whence int) (ret int64, err error) {
214         return syscall.Seek(f.fd, offset, whence)
215 }
216
217 // Truncate changes the size of the named file.
218 // If the file is a symbolic link, it changes the size of the link's target.
219 func Truncate(name string, size int64) error {
220         if e := syscall.Truncate(name, size); e != nil {
221                 return &PathError{"truncate", name, e}
222         }
223         return nil
224 }
225
226 // basename removes trailing slashes and the leading directory name from path name
227 func basename(name string) string {
228         i := len(name) - 1
229         // Remove trailing slashes
230         for ; i > 0 && name[i] == '/'; i-- {
231                 name = name[:i]
232         }
233         // Remove leading directory name
234         for i--; i >= 0; i-- {
235                 if name[i] == '/' {
236                         name = name[i+1:]
237                         break
238                 }
239         }
240
241         return name
242 }
243
244 // Pipe returns a connected pair of Files; reads from r return bytes written to w.
245 // It returns the files and an error, if any.
246 func Pipe() (r *File, w *File, err error) {
247         var p [2]int
248
249         // See ../syscall/exec.go for description of lock.
250         syscall.ForkLock.RLock()
251         e := syscall.Pipe(p[0:])
252         if e != nil {
253                 syscall.ForkLock.RUnlock()
254                 return nil, nil, NewSyscallError("pipe", e)
255         }
256         syscall.CloseOnExec(p[0])
257         syscall.CloseOnExec(p[1])
258         syscall.ForkLock.RUnlock()
259
260         return NewFile(p[0], "|0"), NewFile(p[1], "|1"), nil
261 }
262
263 // TempDir returns the default directory to use for temporary files.
264 func TempDir() string {
265         dir := Getenv("TMPDIR")
266         if dir == "" {
267                 dir = "/tmp"
268         }
269         return dir
270 }