OSDN Git Service

Update Go compiler, library, and testsuite on gcc 4.7 branch.
[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         return syscall.Write(f.fd, b)
183 }
184
185 // pwrite writes len(b) bytes to the File starting at byte offset off.
186 // It returns the number of bytes written and an error, if any.
187 func (f *File) pwrite(b []byte, off int64) (n int, err error) {
188         return syscall.Pwrite(f.fd, b, off)
189 }
190
191 // seek sets the offset for the next Read or Write on file to offset, interpreted
192 // according to whence: 0 means relative to the origin of the file, 1 means
193 // relative to the current offset, and 2 means relative to the end.
194 // It returns the new offset and an error, if any.
195 func (f *File) seek(offset int64, whence int) (ret int64, err error) {
196         return syscall.Seek(f.fd, offset, whence)
197 }
198
199 // Truncate changes the size of the named file.
200 // If the file is a symbolic link, it changes the size of the link's target.
201 // If there is an error, it will be of type *PathError.
202 func Truncate(name string, size int64) error {
203         if e := syscall.Truncate(name, size); e != nil {
204                 return &PathError{"truncate", name, e}
205         }
206         return nil
207 }
208
209 // Remove removes the named file or directory.
210 // If there is an error, it will be of type *PathError.
211 func Remove(name string) error {
212         // System call interface forces us to know
213         // whether name is a file or directory.
214         // Try both: it is cheaper on average than
215         // doing a Stat plus the right one.
216         e := syscall.Unlink(name)
217         if e == nil {
218                 return nil
219         }
220         e1 := syscall.Rmdir(name)
221         if e1 == nil {
222                 return nil
223         }
224
225         // Both failed: figure out which error to return.
226         // OS X and Linux differ on whether unlink(dir)
227         // returns EISDIR, so can't use that.  However,
228         // both agree that rmdir(file) returns ENOTDIR,
229         // so we can use that to decide which error is real.
230         // Rmdir might also return ENOTDIR if given a bad
231         // file path, like /etc/passwd/foo, but in that case,
232         // both errors will be ENOTDIR, so it's okay to
233         // use the error from unlink.
234         if e1 != syscall.ENOTDIR {
235                 e = e1
236         }
237         return &PathError{"remove", name, e}
238 }
239
240 // basename removes trailing slashes and the leading directory name from path name
241 func basename(name string) string {
242         i := len(name) - 1
243         // Remove trailing slashes
244         for ; i > 0 && name[i] == '/'; i-- {
245                 name = name[:i]
246         }
247         // Remove leading directory name
248         for i--; i >= 0; i-- {
249                 if name[i] == '/' {
250                         name = name[i+1:]
251                         break
252                 }
253         }
254
255         return name
256 }
257
258 // Pipe returns a connected pair of Files; reads from r return bytes written to w.
259 // It returns the files and an error, if any.
260 func Pipe() (r *File, w *File, err error) {
261         var p [2]int
262
263         // See ../syscall/exec.go for description of lock.
264         syscall.ForkLock.RLock()
265         e := syscall.Pipe(p[0:])
266         if e != nil {
267                 syscall.ForkLock.RUnlock()
268                 return nil, nil, NewSyscallError("pipe", e)
269         }
270         syscall.CloseOnExec(p[0])
271         syscall.CloseOnExec(p[1])
272         syscall.ForkLock.RUnlock()
273
274         return NewFile(uintptr(p[0]), "|0"), NewFile(uintptr(p[1]), "|1"), nil
275 }
276
277 // TempDir returns the default directory to use for temporary files.
278 func TempDir() string {
279         dir := Getenv("TMPDIR")
280         if dir == "" {
281                 dir = "/tmp"
282         }
283         return dir
284 }