github.com/guyezi/gofrontend@v0.0.0-20200228202240-7a62a49e62c0/libgo/go/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 aix darwin dragonfly freebsd hurd js,wasm linux netbsd openbsd solaris 6 7 package os 8 9 import ( 10 "internal/poll" 11 "internal/syscall/unix" 12 "io" 13 "runtime" 14 "syscall" 15 ) 16 17 // fixLongPath is a noop on non-Windows platforms. 18 func fixLongPath(path string) string { 19 return path 20 } 21 22 func rename(oldname, newname string) error { 23 fi, err := Lstat(newname) 24 if err == nil && fi.IsDir() { 25 // There are two independent errors this function can return: 26 // one for a bad oldname, and one for a bad newname. 27 // At this point we've determined the newname is bad. 28 // But just in case oldname is also bad, prioritize returning 29 // the oldname error because that's what we did historically. 30 // However, if the old name and new name are not the same, yet 31 // they refer to the same file, it implies a case-only 32 // rename on a case-insensitive filesystem, which is ok. 33 if ofi, err := Lstat(oldname); err != nil { 34 if pe, ok := err.(*PathError); ok { 35 err = pe.Err 36 } 37 return &LinkError{"rename", oldname, newname, err} 38 } else if newname == oldname || !SameFile(fi, ofi) { 39 return &LinkError{"rename", oldname, newname, syscall.EEXIST} 40 } 41 } 42 err = syscall.Rename(oldname, newname) 43 if err != nil { 44 return &LinkError{"rename", oldname, newname, err} 45 } 46 return nil 47 } 48 49 // file is the real representation of *File. 50 // The extra level of indirection ensures that no clients of os 51 // can overwrite this data, which could cause the finalizer 52 // to close the wrong file descriptor. 53 type file struct { 54 pfd poll.FD 55 name string 56 dirinfo *dirInfo // nil unless directory being read 57 nonblock bool // whether we set nonblocking mode 58 stdoutOrErr bool // whether this is stdout or stderr 59 appendMode bool // whether file is opened for appending 60 } 61 62 // Fd returns the integer Unix file descriptor referencing the open file. 63 // The file descriptor is valid only until f.Close is called or f is garbage collected. 64 // On Unix systems this will cause the SetDeadline methods to stop working. 65 func (f *File) Fd() uintptr { 66 if f == nil { 67 return ^(uintptr(0)) 68 } 69 70 // If we put the file descriptor into nonblocking mode, 71 // then set it to blocking mode before we return it, 72 // because historically we have always returned a descriptor 73 // opened in blocking mode. The File will continue to work, 74 // but any blocking operation will tie up a thread. 75 if f.nonblock { 76 f.pfd.SetBlocking() 77 } 78 79 return uintptr(f.pfd.Sysfd) 80 } 81 82 // NewFile returns a new File with the given file descriptor and 83 // name. The returned value will be nil if fd is not a valid file 84 // descriptor. On Unix systems, if the file descriptor is in 85 // non-blocking mode, NewFile will attempt to return a pollable File 86 // (one for which the SetDeadline methods work). 87 func NewFile(fd uintptr, name string) *File { 88 kind := kindNewFile 89 if nb, err := unix.IsNonblock(int(fd)); err == nil && nb { 90 kind = kindNonBlock 91 } 92 return newFile(fd, name, kind) 93 } 94 95 // newFileKind describes the kind of file to newFile. 96 type newFileKind int 97 98 const ( 99 kindNewFile newFileKind = iota 100 kindOpenFile 101 kindPipe 102 kindNonBlock 103 ) 104 105 // newFile is like NewFile, but if called from OpenFile or Pipe 106 // (as passed in the kind parameter) it tries to add the file to 107 // the runtime poller. 108 func newFile(fd uintptr, name string, kind newFileKind) *File { 109 fdi := int(fd) 110 if fdi < 0 { 111 return nil 112 } 113 f := &File{&file{ 114 pfd: poll.FD{ 115 Sysfd: fdi, 116 IsStream: true, 117 ZeroReadIsEOF: true, 118 }, 119 name: name, 120 stdoutOrErr: fdi == 1 || fdi == 2, 121 }} 122 123 pollable := kind == kindOpenFile || kind == kindPipe || kind == kindNonBlock 124 125 // If the caller passed a non-blocking filedes (kindNonBlock), 126 // we assume they know what they are doing so we allow it to be 127 // used with kqueue. 128 if kind == kindOpenFile { 129 switch runtime.GOOS { 130 case "darwin", "dragonfly", "freebsd", "netbsd", "openbsd": 131 var st syscall.Stat_t 132 err := syscall.Fstat(fdi, &st) 133 typ := st.Mode & syscall.S_IFMT 134 // Don't try to use kqueue with regular files on *BSDs. 135 // On FreeBSD a regular file is always 136 // reported as ready for writing. 137 // On Dragonfly, NetBSD and OpenBSD the fd is signaled 138 // only once as ready (both read and write). 139 // Issue 19093. 140 // Also don't add directories to the netpoller. 141 if err == nil && (typ == syscall.S_IFREG || typ == syscall.S_IFDIR) { 142 pollable = false 143 } 144 145 // In addition to the behavior described above for regular files, 146 // on Darwin, kqueue does not work properly with fifos: 147 // closing the last writer does not cause a kqueue event 148 // for any readers. See issue #24164. 149 if runtime.GOOS == "darwin" && typ == syscall.S_IFIFO { 150 pollable = false 151 } 152 } 153 } 154 155 if err := f.pfd.Init("file", pollable); err != nil { 156 // An error here indicates a failure to register 157 // with the netpoll system. That can happen for 158 // a file descriptor that is not supported by 159 // epoll/kqueue; for example, disk files on 160 // GNU/Linux systems. We assume that any real error 161 // will show up in later I/O. 162 } else if pollable { 163 // We successfully registered with netpoll, so put 164 // the file into nonblocking mode. 165 if err := syscall.SetNonblock(fdi, true); err == nil { 166 f.nonblock = true 167 } 168 } 169 170 runtime.SetFinalizer(f.file, (*file).close) 171 return f 172 } 173 174 // Auxiliary information if the File describes a directory 175 type dirInfo struct { 176 buf []byte // buffer for directory I/O 177 dir *syscall.DIR // from opendir 178 } 179 180 // epipecheck raises SIGPIPE if we get an EPIPE error on standard 181 // output or standard error. See the SIGPIPE docs in os/signal, and 182 // issue 11845. 183 func epipecheck(file *File, e error) { 184 if e == syscall.EPIPE && file.stdoutOrErr { 185 sigpipe() 186 } 187 } 188 189 // DevNull is the name of the operating system's ``null device.'' 190 // On Unix-like systems, it is "/dev/null"; on Windows, "NUL". 191 const DevNull = "/dev/null" 192 193 // openFileNolog is the Unix implementation of OpenFile. 194 // Changes here should be reflected in openFdAt, if relevant. 195 func openFileNolog(name string, flag int, perm FileMode) (*File, error) { 196 setSticky := false 197 if !supportsCreateWithStickyBit && flag&O_CREATE != 0 && perm&ModeSticky != 0 { 198 if _, err := Stat(name); IsNotExist(err) { 199 setSticky = true 200 } 201 } 202 203 var r int 204 for { 205 var e error 206 r, e = syscall.Open(name, flag|syscall.O_CLOEXEC, syscallMode(perm)) 207 if e == nil { 208 break 209 } 210 211 // On OS X, sigaction(2) doesn't guarantee that SA_RESTART will cause 212 // open(2) to be restarted for regular files. This is easy to reproduce on 213 // fuse file systems (see https://golang.org/issue/11180). 214 if runtime.GOOS == "darwin" && e == syscall.EINTR { 215 continue 216 } 217 218 return nil, &PathError{"open", name, e} 219 } 220 221 // open(2) itself won't handle the sticky bit on *BSD and Solaris 222 if setSticky { 223 setStickyBit(name) 224 } 225 226 // There's a race here with fork/exec, which we are 227 // content to live with. See ../syscall/exec_unix.go. 228 if !supportsCloseOnExec { 229 syscall.CloseOnExec(r) 230 } 231 232 return newFile(uintptr(r), name, kindOpenFile), nil 233 } 234 235 // Close closes the File, rendering it unusable for I/O. 236 // On files that support SetDeadline, any pending I/O operations will 237 // be canceled and return immediately with an error. 238 // Close will return an error if it has already been called. 239 func (f *File) Close() error { 240 if f == nil { 241 return ErrInvalid 242 } 243 return f.file.close() 244 } 245 246 func (file *file) close() error { 247 if file == nil { 248 return syscall.EINVAL 249 } 250 var err error 251 if file.dirinfo != nil { 252 syscall.Entersyscall() 253 i := libc_closedir(file.dirinfo.dir) 254 errno := syscall.GetErrno() 255 syscall.Exitsyscall() 256 file.dirinfo = nil 257 if i < 0 && errno != 0 { 258 err = &PathError{"closedir", file.name, errno} 259 } 260 } 261 if e := file.pfd.Close(); e != nil { 262 if e == poll.ErrFileClosing { 263 e = ErrClosed 264 } 265 err = &PathError{"close", file.name, e} 266 } 267 268 // no need for a finalizer anymore 269 runtime.SetFinalizer(file, nil) 270 return err 271 } 272 273 // read reads up to len(b) bytes from the File. 274 // It returns the number of bytes read and an error, if any. 275 func (f *File) read(b []byte) (n int, err error) { 276 n, err = f.pfd.Read(b) 277 runtime.KeepAlive(f) 278 return n, err 279 } 280 281 // pread reads len(b) bytes from the File starting at byte offset off. 282 // It returns the number of bytes read and the error, if any. 283 // EOF is signaled by a zero count with err set to nil. 284 func (f *File) pread(b []byte, off int64) (n int, err error) { 285 n, err = f.pfd.Pread(b, off) 286 runtime.KeepAlive(f) 287 return n, err 288 } 289 290 // write writes len(b) bytes to the File. 291 // It returns the number of bytes written and an error, if any. 292 func (f *File) write(b []byte) (n int, err error) { 293 n, err = f.pfd.Write(b) 294 runtime.KeepAlive(f) 295 return n, err 296 } 297 298 // pwrite writes len(b) bytes to the File starting at byte offset off. 299 // It returns the number of bytes written and an error, if any. 300 func (f *File) pwrite(b []byte, off int64) (n int, err error) { 301 n, err = f.pfd.Pwrite(b, off) 302 runtime.KeepAlive(f) 303 return n, err 304 } 305 306 // seek sets the offset for the next Read or Write on file to offset, interpreted 307 // according to whence: 0 means relative to the origin of the file, 1 means 308 // relative to the current offset, and 2 means relative to the end. 309 // It returns the new offset and an error, if any. 310 func (f *File) seek(offset int64, whence int) (ret int64, err error) { 311 f.seekInvalidate() 312 ret, err = f.pfd.Seek(offset, whence) 313 runtime.KeepAlive(f) 314 return ret, err 315 } 316 317 // Truncate changes the size of the named file. 318 // If the file is a symbolic link, it changes the size of the link's target. 319 // If there is an error, it will be of type *PathError. 320 func Truncate(name string, size int64) error { 321 if e := syscall.Truncate(name, size); e != nil { 322 return &PathError{"truncate", name, e} 323 } 324 return nil 325 } 326 327 // Remove removes the named file or (empty) directory. 328 // If there is an error, it will be of type *PathError. 329 func Remove(name string) error { 330 // System call interface forces us to know 331 // whether name is a file or directory. 332 // Try both: it is cheaper on average than 333 // doing a Stat plus the right one. 334 e := syscall.Unlink(name) 335 if e == nil { 336 return nil 337 } 338 e1 := syscall.Rmdir(name) 339 if e1 == nil { 340 return nil 341 } 342 343 // Both failed: figure out which error to return. 344 // OS X and Linux differ on whether unlink(dir) 345 // returns EISDIR, so can't use that. However, 346 // both agree that rmdir(file) returns ENOTDIR, 347 // so we can use that to decide which error is real. 348 // Rmdir might also return ENOTDIR if given a bad 349 // file path, like /etc/passwd/foo, but in that case, 350 // both errors will be ENOTDIR, so it's okay to 351 // use the error from unlink. 352 if e1 != syscall.ENOTDIR { 353 e = e1 354 } 355 return &PathError{"remove", name, e} 356 } 357 358 func tempDir() string { 359 dir := Getenv("TMPDIR") 360 if dir == "" { 361 if runtime.GOOS == "android" { 362 dir = "/data/local/tmp" 363 } else { 364 dir = "/tmp" 365 } 366 } 367 return dir 368 } 369 370 // Link creates newname as a hard link to the oldname file. 371 // If there is an error, it will be of type *LinkError. 372 func Link(oldname, newname string) error { 373 e := syscall.Link(oldname, newname) 374 if e != nil { 375 return &LinkError{"link", oldname, newname, e} 376 } 377 return nil 378 } 379 380 // Symlink creates newname as a symbolic link to oldname. 381 // If there is an error, it will be of type *LinkError. 382 func Symlink(oldname, newname string) error { 383 e := syscall.Symlink(oldname, newname) 384 if e != nil { 385 return &LinkError{"symlink", oldname, newname, e} 386 } 387 return nil 388 } 389 390 func (f *File) readdir(n int) (fi []FileInfo, err error) { 391 dirname := f.name 392 if dirname == "" { 393 dirname = "." 394 } 395 names, err := f.Readdirnames(n) 396 fi = make([]FileInfo, 0, len(names)) 397 for _, filename := range names { 398 fip, lerr := lstat(dirname + "/" + filename) 399 if IsNotExist(lerr) { 400 // File disappeared between readdir + stat. 401 // Just treat it as if it didn't exist. 402 continue 403 } 404 if lerr != nil { 405 return fi, lerr 406 } 407 fi = append(fi, fip) 408 } 409 if len(fi) == 0 && err == nil && n > 0 { 410 // Per File.Readdir, the slice must be non-empty or err 411 // must be non-nil if n > 0. 412 err = io.EOF 413 } 414 return fi, err 415 } 416 417 // Readlink returns the destination of the named symbolic link. 418 // If there is an error, it will be of type *PathError. 419 func Readlink(name string) (string, error) { 420 for len := 128; ; len *= 2 { 421 b := make([]byte, len) 422 n, e := fixCount(syscall.Readlink(name, b)) 423 // buffer too small 424 if runtime.GOOS == "aix" && e == syscall.ERANGE { 425 continue 426 } 427 if e != nil { 428 return "", &PathError{"readlink", name, e} 429 } 430 if n < len { 431 return string(b[0:n]), nil 432 } 433 } 434 }