github.com/reiver/go@v0.0.0-20150109200633-1d0c7792f172/src/os/file_unix.go (about) 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 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 // The file descriptor is valid only until f.Close is called or f is garbage collected. 33 func (f *File) Fd() uintptr { 34 if f == nil { 35 return ^(uintptr(0)) 36 } 37 return uintptr(f.fd) 38 } 39 40 // NewFile returns a new File with the given file descriptor and name. 41 func NewFile(fd uintptr, name string) *File { 42 fdi := int(fd) 43 if fdi < 0 { 44 return nil 45 } 46 f := &File{&file{fd: fdi, name: name}} 47 runtime.SetFinalizer(f.file, (*file).close) 48 return f 49 } 50 51 // Auxiliary information if the File describes a directory 52 type dirInfo struct { 53 buf []byte // buffer for directory I/O 54 nbuf int // length of buf; return value from Getdirentries 55 bufp int // location of next record in buf. 56 } 57 58 func epipecheck(file *File, e error) { 59 if e == syscall.EPIPE { 60 if atomic.AddInt32(&file.nepipe, 1) >= 10 { 61 sigpipe() 62 } 63 } else { 64 atomic.StoreInt32(&file.nepipe, 0) 65 } 66 } 67 68 // DevNull is the name of the operating system's ``null device.'' 69 // On Unix-like systems, it is "/dev/null"; on Windows, "NUL". 70 const DevNull = "/dev/null" 71 72 // OpenFile is the generalized open call; most users will use Open 73 // or Create instead. It opens the named file with specified flag 74 // (O_RDONLY etc.) and perm, (0666 etc.) if applicable. If successful, 75 // methods on the returned File can be used for I/O. 76 // If there is an error, it will be of type *PathError. 77 func OpenFile(name string, flag int, perm FileMode) (file *File, err error) { 78 chmod := false 79 if !supportsCreateWithStickyBit && flag&O_CREATE != 0 && perm&ModeSticky != 0 { 80 if _, err := Stat(name); IsNotExist(err) { 81 chmod = true 82 } 83 } 84 85 r, e := syscall.Open(name, flag|syscall.O_CLOEXEC, syscallMode(perm)) 86 if e != nil { 87 return nil, &PathError{"open", name, e} 88 } 89 90 // open(2) itself won't handle the sticky bit on *BSD and Solaris 91 if chmod && e == nil { 92 e = Chmod(name, perm) 93 } 94 95 // There's a race here with fork/exec, which we are 96 // content to live with. See ../syscall/exec_unix.go. 97 if !supportsCloseOnExec { 98 syscall.CloseOnExec(r) 99 } 100 101 return NewFile(uintptr(r), name), nil 102 } 103 104 // Close closes the File, rendering it unusable for I/O. 105 // It returns an error, if any. 106 func (f *File) Close() error { 107 if f == nil { 108 return ErrInvalid 109 } 110 return f.file.close() 111 } 112 113 func (file *file) close() error { 114 if file == nil || file.fd < 0 { 115 return syscall.EINVAL 116 } 117 var err error 118 if e := syscall.Close(file.fd); e != nil { 119 err = &PathError{"close", file.name, e} 120 } 121 file.fd = -1 // so it can't be closed again 122 123 // no need for a finalizer anymore 124 runtime.SetFinalizer(file, nil) 125 return err 126 } 127 128 // Stat returns the FileInfo structure describing file. 129 // If there is an error, it will be of type *PathError. 130 func (f *File) Stat() (fi FileInfo, err error) { 131 if f == nil { 132 return nil, ErrInvalid 133 } 134 var stat syscall.Stat_t 135 err = syscall.Fstat(f.fd, &stat) 136 if err != nil { 137 return nil, &PathError{"stat", f.name, err} 138 } 139 return fileInfoFromStat(&stat, f.name), nil 140 } 141 142 // Stat returns a FileInfo describing the named file. 143 // If there is an error, it will be of type *PathError. 144 func Stat(name string) (fi FileInfo, err error) { 145 var stat syscall.Stat_t 146 err = syscall.Stat(name, &stat) 147 if err != nil { 148 return nil, &PathError{"stat", name, err} 149 } 150 return fileInfoFromStat(&stat, name), nil 151 } 152 153 // Lstat returns a FileInfo describing the named file. 154 // If the file is a symbolic link, the returned FileInfo 155 // describes the symbolic link. Lstat makes no attempt to follow the link. 156 // If there is an error, it will be of type *PathError. 157 func Lstat(name string) (fi FileInfo, err error) { 158 var stat syscall.Stat_t 159 err = syscall.Lstat(name, &stat) 160 if err != nil { 161 return nil, &PathError{"lstat", name, err} 162 } 163 return fileInfoFromStat(&stat, name), nil 164 } 165 166 func (f *File) readdir(n int) (fi []FileInfo, err error) { 167 dirname := f.name 168 if dirname == "" { 169 dirname = "." 170 } 171 names, err := f.Readdirnames(n) 172 fi = make([]FileInfo, 0, len(names)) 173 for _, filename := range names { 174 fip, lerr := lstat(dirname + "/" + filename) 175 if IsNotExist(lerr) { 176 // File disappeared between readdir + stat. 177 // Just treat it as if it didn't exist. 178 continue 179 } 180 if lerr != nil { 181 return fi, lerr 182 } 183 fi = append(fi, fip) 184 } 185 return fi, err 186 } 187 188 // Darwin and FreeBSD can't read or write 2GB+ at a time, 189 // even on 64-bit systems. See golang.org/issue/7812. 190 // Use 1GB instead of, say, 2GB-1, to keep subsequent 191 // reads aligned. 192 const ( 193 needsMaxRW = runtime.GOOS == "darwin" || runtime.GOOS == "freebsd" 194 maxRW = 1 << 30 195 ) 196 197 // read reads up to len(b) bytes from the File. 198 // It returns the number of bytes read and an error, if any. 199 func (f *File) read(b []byte) (n int, err error) { 200 if needsMaxRW && len(b) > maxRW { 201 b = b[:maxRW] 202 } 203 return fixCount(syscall.Read(f.fd, b)) 204 } 205 206 // pread reads len(b) bytes from the File starting at byte offset off. 207 // It returns the number of bytes read and the error, if any. 208 // EOF is signaled by a zero count with err set to nil. 209 func (f *File) pread(b []byte, off int64) (n int, err error) { 210 if needsMaxRW && len(b) > maxRW { 211 b = b[:maxRW] 212 } 213 return fixCount(syscall.Pread(f.fd, b, off)) 214 } 215 216 // write writes len(b) bytes to the File. 217 // It returns the number of bytes written and an error, if any. 218 func (f *File) write(b []byte) (n int, err error) { 219 for { 220 bcap := b 221 if needsMaxRW && len(bcap) > maxRW { 222 bcap = bcap[:maxRW] 223 } 224 m, err := fixCount(syscall.Write(f.fd, bcap)) 225 n += m 226 227 // If the syscall wrote some data but not all (short write) 228 // or it returned EINTR, then assume it stopped early for 229 // reasons that are uninteresting to the caller, and try again. 230 if 0 < m && m < len(bcap) || err == syscall.EINTR { 231 b = b[m:] 232 continue 233 } 234 235 if needsMaxRW && len(bcap) != len(b) && err == nil { 236 b = b[m:] 237 continue 238 } 239 240 return n, err 241 } 242 } 243 244 // pwrite writes len(b) bytes to the File starting at byte offset off. 245 // It returns the number of bytes written and an error, if any. 246 func (f *File) pwrite(b []byte, off int64) (n int, err error) { 247 if needsMaxRW && len(b) > maxRW { 248 b = b[:maxRW] 249 } 250 return fixCount(syscall.Pwrite(f.fd, b, off)) 251 } 252 253 // seek sets the offset for the next Read or Write on file to offset, interpreted 254 // according to whence: 0 means relative to the origin of the file, 1 means 255 // relative to the current offset, and 2 means relative to the end. 256 // It returns the new offset and an error, if any. 257 func (f *File) seek(offset int64, whence int) (ret int64, err error) { 258 return syscall.Seek(f.fd, offset, whence) 259 } 260 261 // Truncate changes the size of the named file. 262 // If the file is a symbolic link, it changes the size of the link's target. 263 // If there is an error, it will be of type *PathError. 264 func Truncate(name string, size int64) error { 265 if e := syscall.Truncate(name, size); e != nil { 266 return &PathError{"truncate", name, e} 267 } 268 return nil 269 } 270 271 // Remove removes the named file or directory. 272 // If there is an error, it will be of type *PathError. 273 func Remove(name string) error { 274 // System call interface forces us to know 275 // whether name is a file or directory. 276 // Try both: it is cheaper on average than 277 // doing a Stat plus the right one. 278 e := syscall.Unlink(name) 279 if e == nil { 280 return nil 281 } 282 e1 := syscall.Rmdir(name) 283 if e1 == nil { 284 return nil 285 } 286 287 // Both failed: figure out which error to return. 288 // OS X and Linux differ on whether unlink(dir) 289 // returns EISDIR, so can't use that. However, 290 // both agree that rmdir(file) returns ENOTDIR, 291 // so we can use that to decide which error is real. 292 // Rmdir might also return ENOTDIR if given a bad 293 // file path, like /etc/passwd/foo, but in that case, 294 // both errors will be ENOTDIR, so it's okay to 295 // use the error from unlink. 296 if e1 != syscall.ENOTDIR { 297 e = e1 298 } 299 return &PathError{"remove", name, e} 300 } 301 302 // basename removes trailing slashes and the leading directory name from path name 303 func basename(name string) string { 304 i := len(name) - 1 305 // Remove trailing slashes 306 for ; i > 0 && name[i] == '/'; i-- { 307 name = name[:i] 308 } 309 // Remove leading directory name 310 for i--; i >= 0; i-- { 311 if name[i] == '/' { 312 name = name[i+1:] 313 break 314 } 315 } 316 317 return name 318 } 319 320 // TempDir returns the default directory to use for temporary files. 321 func TempDir() string { 322 dir := Getenv("TMPDIR") 323 if dir == "" { 324 if runtime.GOOS == "android" { 325 dir = "/data/local/tmp" 326 } else { 327 dir = "/tmp" 328 } 329 } 330 return dir 331 } 332 333 // Link creates newname as a hard link to the oldname file. 334 // If there is an error, it will be of type *LinkError. 335 func Link(oldname, newname string) error { 336 e := syscall.Link(oldname, newname) 337 if e != nil { 338 return &LinkError{"link", oldname, newname, e} 339 } 340 return nil 341 } 342 343 // Symlink creates newname as a symbolic link to oldname. 344 // If there is an error, it will be of type *LinkError. 345 func Symlink(oldname, newname string) error { 346 e := syscall.Symlink(oldname, newname) 347 if e != nil { 348 return &LinkError{"symlink", oldname, newname, e} 349 } 350 return nil 351 }