github.com/c12o16h1/go/src@v0.0.0-20200114212001-5a151c0f00ed/os/file.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 // Package os provides a platform-independent interface to operating system 6 // functionality. The design is Unix-like, although the error handling is 7 // Go-like; failing calls return values of type error rather than error numbers. 8 // Often, more information is available within the error. For example, 9 // if a call that takes a file name fails, such as Open or Stat, the error 10 // will include the failing file name when printed and will be of type 11 // *PathError, which may be unpacked for more information. 12 // 13 // The os interface is intended to be uniform across all operating systems. 14 // Features not generally available appear in the system-specific package syscall. 15 // 16 // Here is a simple example, opening a file and reading some of it. 17 // 18 // file, err := os.Open("file.go") // For read access. 19 // if err != nil { 20 // log.Fatal(err) 21 // } 22 // 23 // If the open fails, the error string will be self-explanatory, like 24 // 25 // open file.go: no such file or directory 26 // 27 // The file's data can then be read into a slice of bytes. Read and 28 // Write take their byte counts from the length of the argument slice. 29 // 30 // data := make([]byte, 100) 31 // count, err := file.Read(data) 32 // if err != nil { 33 // log.Fatal(err) 34 // } 35 // fmt.Printf("read %d bytes: %q\n", count, data[:count]) 36 // 37 // Note: The maximum number of concurrent operations on a File may be limited by 38 // the OS or the system. The number should be high, but exceeding it may degrade 39 // performance or cause other issues. 40 // 41 package os 42 43 import ( 44 "errors" 45 "github.com/c12o16h1/go/src/internal/poll" 46 "github.com/c12o16h1/go/src/internal/testlog" 47 "io" 48 "runtime" 49 "syscall" 50 "time" 51 ) 52 53 // Name returns the name of the file as presented to Open. 54 func (f *File) Name() string { return f.name } 55 56 // Stdin, Stdout, and Stderr are open Files pointing to the standard input, 57 // standard output, and standard error file descriptors. 58 // 59 // Note that the Go runtime writes to standard error for panics and crashes; 60 // closing Stderr may cause those messages to go elsewhere, perhaps 61 // to a file opened later. 62 var ( 63 Stdin = NewFile(uintptr(syscall.Stdin), "/dev/stdin") 64 Stdout = NewFile(uintptr(syscall.Stdout), "/dev/stdout") 65 Stderr = NewFile(uintptr(syscall.Stderr), "/dev/stderr") 66 ) 67 68 // Flags to OpenFile wrapping those of the underlying system. Not all 69 // flags may be implemented on a given system. 70 const ( 71 // Exactly one of O_RDONLY, O_WRONLY, or O_RDWR must be specified. 72 O_RDONLY int = syscall.O_RDONLY // open the file read-only. 73 O_WRONLY int = syscall.O_WRONLY // open the file write-only. 74 O_RDWR int = syscall.O_RDWR // open the file read-write. 75 // The remaining values may be or'ed in to control behavior. 76 O_APPEND int = syscall.O_APPEND // append data to the file when writing. 77 O_CREATE int = syscall.O_CREAT // create a new file if none exists. 78 O_EXCL int = syscall.O_EXCL // used with O_CREATE, file must not exist. 79 O_SYNC int = syscall.O_SYNC // open for synchronous I/O. 80 O_TRUNC int = syscall.O_TRUNC // truncate regular writable file when opened. 81 ) 82 83 // Seek whence values. 84 // 85 // Deprecated: Use io.SeekStart, io.SeekCurrent, and io.SeekEnd. 86 const ( 87 SEEK_SET int = 0 // seek relative to the origin of the file 88 SEEK_CUR int = 1 // seek relative to the current offset 89 SEEK_END int = 2 // seek relative to the end 90 ) 91 92 // LinkError records an error during a link or symlink or rename 93 // system call and the paths that caused it. 94 type LinkError struct { 95 Op string 96 Old string 97 New string 98 Err error 99 } 100 101 func (e *LinkError) Error() string { 102 return e.Op + " " + e.Old + " " + e.New + ": " + e.Err.Error() 103 } 104 105 func (e *LinkError) Unwrap() error { 106 return e.Err 107 } 108 109 // Read reads up to len(b) bytes from the File. 110 // It returns the number of bytes read and any error encountered. 111 // At end of file, Read returns 0, io.EOF. 112 func (f *File) Read(b []byte) (n int, err error) { 113 if err := f.checkValid("read"); err != nil { 114 return 0, err 115 } 116 n, e := f.read(b) 117 return n, f.wrapErr("read", e) 118 } 119 120 // ReadAt reads len(b) bytes from the File starting at byte offset off. 121 // It returns the number of bytes read and the error, if any. 122 // ReadAt always returns a non-nil error when n < len(b). 123 // At end of file, that error is io.EOF. 124 func (f *File) ReadAt(b []byte, off int64) (n int, err error) { 125 if err := f.checkValid("read"); err != nil { 126 return 0, err 127 } 128 129 if off < 0 { 130 return 0, &PathError{"readat", f.name, errors.New("negative offset")} 131 } 132 133 for len(b) > 0 { 134 m, e := f.pread(b, off) 135 if e != nil { 136 err = f.wrapErr("read", e) 137 break 138 } 139 n += m 140 b = b[m:] 141 off += int64(m) 142 } 143 return 144 } 145 146 // Write writes len(b) bytes to the File. 147 // It returns the number of bytes written and an error, if any. 148 // Write returns a non-nil error when n != len(b). 149 func (f *File) Write(b []byte) (n int, err error) { 150 if err := f.checkValid("write"); err != nil { 151 return 0, err 152 } 153 n, e := f.write(b) 154 if n < 0 { 155 n = 0 156 } 157 if n != len(b) { 158 err = io.ErrShortWrite 159 } 160 161 epipecheck(f, e) 162 163 if e != nil { 164 err = f.wrapErr("write", e) 165 } 166 167 return n, err 168 } 169 170 var errWriteAtInAppendMode = errors.New("os: invalid use of WriteAt on file opened with O_APPEND") 171 172 // WriteAt writes len(b) bytes to the File starting at byte offset off. 173 // It returns the number of bytes written and an error, if any. 174 // WriteAt returns a non-nil error when n != len(b). 175 // 176 // If file was opened with the O_APPEND flag, WriteAt returns an error. 177 func (f *File) WriteAt(b []byte, off int64) (n int, err error) { 178 if err := f.checkValid("write"); err != nil { 179 return 0, err 180 } 181 if f.appendMode { 182 return 0, errWriteAtInAppendMode 183 } 184 185 if off < 0 { 186 return 0, &PathError{"writeat", f.name, errors.New("negative offset")} 187 } 188 189 for len(b) > 0 { 190 m, e := f.pwrite(b, off) 191 if e != nil { 192 err = f.wrapErr("write", e) 193 break 194 } 195 n += m 196 b = b[m:] 197 off += int64(m) 198 } 199 return 200 } 201 202 // Seek sets the offset for the next Read or Write on file to offset, interpreted 203 // according to whence: 0 means relative to the origin of the file, 1 means 204 // relative to the current offset, and 2 means relative to the end. 205 // It returns the new offset and an error, if any. 206 // The behavior of Seek on a file opened with O_APPEND is not specified. 207 // 208 // If f is a directory, the behavior of Seek varies by operating 209 // system; you can seek to the beginning of the directory on Unix-like 210 // operating systems, but not on Windows. 211 func (f *File) Seek(offset int64, whence int) (ret int64, err error) { 212 if err := f.checkValid("seek"); err != nil { 213 return 0, err 214 } 215 r, e := f.seek(offset, whence) 216 if e == nil && f.dirinfo != nil && r != 0 { 217 e = syscall.EISDIR 218 } 219 if e != nil { 220 return 0, f.wrapErr("seek", e) 221 } 222 return r, nil 223 } 224 225 // WriteString is like Write, but writes the contents of string s rather than 226 // a slice of bytes. 227 func (f *File) WriteString(s string) (n int, err error) { 228 return f.Write([]byte(s)) 229 } 230 231 // Mkdir creates a new directory with the specified name and permission 232 // bits (before umask). 233 // If there is an error, it will be of type *PathError. 234 func Mkdir(name string, perm FileMode) error { 235 if runtime.GOOS == "windows" && isWindowsNulName(name) { 236 return &PathError{"mkdir", name, syscall.ENOTDIR} 237 } 238 e := syscall.Mkdir(fixLongPath(name), syscallMode(perm)) 239 240 if e != nil { 241 return &PathError{"mkdir", name, e} 242 } 243 244 // mkdir(2) itself won't handle the sticky bit on *BSD and Solaris 245 if !supportsCreateWithStickyBit && perm&ModeSticky != 0 { 246 e = setStickyBit(name) 247 248 if e != nil { 249 Remove(name) 250 return e 251 } 252 } 253 254 return nil 255 } 256 257 // setStickyBit adds ModeSticky to the permission bits of path, non atomic. 258 func setStickyBit(name string) error { 259 fi, err := Stat(name) 260 if err != nil { 261 return err 262 } 263 return Chmod(name, fi.Mode()|ModeSticky) 264 } 265 266 // Chdir changes the current working directory to the named directory. 267 // If there is an error, it will be of type *PathError. 268 func Chdir(dir string) error { 269 if e := syscall.Chdir(dir); e != nil { 270 testlog.Open(dir) // observe likely non-existent directory 271 return &PathError{"chdir", dir, e} 272 } 273 if log := testlog.Logger(); log != nil { 274 wd, err := Getwd() 275 if err == nil { 276 log.Chdir(wd) 277 } 278 } 279 return nil 280 } 281 282 // Open opens the named file for reading. If successful, methods on 283 // the returned file can be used for reading; the associated file 284 // descriptor has mode O_RDONLY. 285 // If there is an error, it will be of type *PathError. 286 func Open(name string) (*File, error) { 287 return OpenFile(name, O_RDONLY, 0) 288 } 289 290 // Create creates or truncates the named file. If the file already exists, 291 // it is truncated. If the file does not exist, it is created with mode 0666 292 // (before umask). If successful, methods on the returned File can 293 // be used for I/O; the associated file descriptor has mode O_RDWR. 294 // If there is an error, it will be of type *PathError. 295 func Create(name string) (*File, error) { 296 return OpenFile(name, O_RDWR|O_CREATE|O_TRUNC, 0666) 297 } 298 299 // OpenFile is the generalized open call; most users will use Open 300 // or Create instead. It opens the named file with specified flag 301 // (O_RDONLY etc.). If the file does not exist, and the O_CREATE flag 302 // is passed, it is created with mode perm (before umask). If successful, 303 // methods on the returned File can be used for I/O. 304 // If there is an error, it will be of type *PathError. 305 func OpenFile(name string, flag int, perm FileMode) (*File, error) { 306 testlog.Open(name) 307 f, err := openFileNolog(name, flag, perm) 308 if err != nil { 309 return nil, err 310 } 311 f.appendMode = flag&O_APPEND != 0 312 313 return f, nil 314 } 315 316 // lstat is overridden in tests. 317 var lstat = Lstat 318 319 // Rename renames (moves) oldpath to newpath. 320 // If newpath already exists and is not a directory, Rename replaces it. 321 // OS-specific restrictions may apply when oldpath and newpath are in different directories. 322 // If there is an error, it will be of type *LinkError. 323 func Rename(oldpath, newpath string) error { 324 return rename(oldpath, newpath) 325 } 326 327 // Many functions in package syscall return a count of -1 instead of 0. 328 // Using fixCount(call()) instead of call() corrects the count. 329 func fixCount(n int, err error) (int, error) { 330 if n < 0 { 331 n = 0 332 } 333 return n, err 334 } 335 336 // wrapErr wraps an error that occurred during an operation on an open file. 337 // It passes io.EOF through unchanged, otherwise converts 338 // poll.ErrFileClosing to ErrClosed and wraps the error in a PathError. 339 func (f *File) wrapErr(op string, err error) error { 340 if err == nil || err == io.EOF { 341 return err 342 } 343 if err == poll.ErrFileClosing { 344 err = ErrClosed 345 } 346 return &PathError{op, f.name, err} 347 } 348 349 // TempDir returns the default directory to use for temporary files. 350 // 351 // On Unix systems, it returns $TMPDIR if non-empty, else /tmp. 352 // On Windows, it uses GetTempPath, returning the first non-empty 353 // value from %TMP%, %TEMP%, %USERPROFILE%, or the Windows directory. 354 // On Plan 9, it returns /tmp. 355 // 356 // The directory is neither guaranteed to exist nor have accessible 357 // permissions. 358 func TempDir() string { 359 return tempDir() 360 } 361 362 // UserCacheDir returns the default root directory to use for user-specific 363 // cached data. Users should create their own application-specific subdirectory 364 // within this one and use that. 365 // 366 // On Unix systems, it returns $XDG_CACHE_HOME as specified by 367 // https://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html if 368 // non-empty, else $HOME/.cache. 369 // On Darwin, it returns $HOME/Library/Caches. 370 // On Windows, it returns %LocalAppData%. 371 // On Plan 9, it returns $home/lib/cache. 372 // 373 // If the location cannot be determined (for example, $HOME is not defined), 374 // then it will return an error. 375 func UserCacheDir() (string, error) { 376 var dir string 377 378 switch runtime.GOOS { 379 case "windows": 380 dir = Getenv("LocalAppData") 381 if dir == "" { 382 return "", errors.New("%LocalAppData% is not defined") 383 } 384 385 case "darwin": 386 dir = Getenv("HOME") 387 if dir == "" { 388 return "", errors.New("$HOME is not defined") 389 } 390 dir += "/Library/Caches" 391 392 case "plan9": 393 dir = Getenv("home") 394 if dir == "" { 395 return "", errors.New("$home is not defined") 396 } 397 dir += "/lib/cache" 398 399 default: // Unix 400 dir = Getenv("XDG_CACHE_HOME") 401 if dir == "" { 402 dir = Getenv("HOME") 403 if dir == "" { 404 return "", errors.New("neither $XDG_CACHE_HOME nor $HOME are defined") 405 } 406 dir += "/.cache" 407 } 408 } 409 410 return dir, nil 411 } 412 413 // UserConfigDir returns the default root directory to use for user-specific 414 // configuration data. Users should create their own application-specific 415 // subdirectory within this one and use that. 416 // 417 // On Unix systems, it returns $XDG_CONFIG_HOME as specified by 418 // https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html if 419 // non-empty, else $HOME/.config. 420 // On Darwin, it returns $HOME/Library/Application Support. 421 // On Windows, it returns %AppData%. 422 // On Plan 9, it returns $home/lib. 423 // 424 // If the location cannot be determined (for example, $HOME is not defined), 425 // then it will return an error. 426 func UserConfigDir() (string, error) { 427 var dir string 428 429 switch runtime.GOOS { 430 case "windows": 431 dir = Getenv("AppData") 432 if dir == "" { 433 return "", errors.New("%AppData% is not defined") 434 } 435 436 case "darwin": 437 dir = Getenv("HOME") 438 if dir == "" { 439 return "", errors.New("$HOME is not defined") 440 } 441 dir += "/Library/Application Support" 442 443 case "plan9": 444 dir = Getenv("home") 445 if dir == "" { 446 return "", errors.New("$home is not defined") 447 } 448 dir += "/lib" 449 450 default: // Unix 451 dir = Getenv("XDG_CONFIG_HOME") 452 if dir == "" { 453 dir = Getenv("HOME") 454 if dir == "" { 455 return "", errors.New("neither $XDG_CONFIG_HOME nor $HOME are defined") 456 } 457 dir += "/.config" 458 } 459 } 460 461 return dir, nil 462 } 463 464 // UserHomeDir returns the current user's home directory. 465 // 466 // On Unix, including macOS, it returns the $HOME environment variable. 467 // On Windows, it returns %USERPROFILE%. 468 // On Plan 9, it returns the $home environment variable. 469 func UserHomeDir() (string, error) { 470 env, enverr := "HOME", "$HOME" 471 switch runtime.GOOS { 472 case "windows": 473 env, enverr = "USERPROFILE", "%userprofile%" 474 case "plan9": 475 env, enverr = "home", "$home" 476 } 477 if v := Getenv(env); v != "" { 478 return v, nil 479 } 480 // On some geese the home directory is not always defined. 481 switch runtime.GOOS { 482 case "android": 483 return "/sdcard", nil 484 case "darwin": 485 if runtime.GOARCH == "arm" || runtime.GOARCH == "arm64" { 486 return "/", nil 487 } 488 } 489 return "", errors.New(enverr + " is not defined") 490 } 491 492 // Chmod changes the mode of the named file to mode. 493 // If the file is a symbolic link, it changes the mode of the link's target. 494 // If there is an error, it will be of type *PathError. 495 // 496 // A different subset of the mode bits are used, depending on the 497 // operating system. 498 // 499 // On Unix, the mode's permission bits, ModeSetuid, ModeSetgid, and 500 // ModeSticky are used. 501 // 502 // On Windows, only the 0200 bit (owner writable) of mode is used; it 503 // controls whether the file's read-only attribute is set or cleared. 504 // The other bits are currently unused. For compatibility with Go 1.12 505 // and earlier, use a non-zero mode. Use mode 0400 for a read-only 506 // file and 0600 for a readable+writable file. 507 // 508 // On Plan 9, the mode's permission bits, ModeAppend, ModeExclusive, 509 // and ModeTemporary are used. 510 func Chmod(name string, mode FileMode) error { return chmod(name, mode) } 511 512 // Chmod changes the mode of the file to mode. 513 // If there is an error, it will be of type *PathError. 514 func (f *File) Chmod(mode FileMode) error { return f.chmod(mode) } 515 516 // SetDeadline sets the read and write deadlines for a File. 517 // It is equivalent to calling both SetReadDeadline and SetWriteDeadline. 518 // 519 // Only some kinds of files support setting a deadline. Calls to SetDeadline 520 // for files that do not support deadlines will return ErrNoDeadline. 521 // On most systems ordinary files do not support deadlines, but pipes do. 522 // 523 // A deadline is an absolute time after which I/O operations fail with an 524 // error instead of blocking. The deadline applies to all future and pending 525 // I/O, not just the immediately following call to Read or Write. 526 // After a deadline has been exceeded, the connection can be refreshed 527 // by setting a deadline in the future. 528 // 529 // An error returned after a timeout fails will implement the 530 // Timeout method, and calling the Timeout method will return true. 531 // The PathError and SyscallError types implement the Timeout method. 532 // In general, call IsTimeout to test whether an error indicates a timeout. 533 // 534 // An idle timeout can be implemented by repeatedly extending 535 // the deadline after successful Read or Write calls. 536 // 537 // A zero value for t means I/O operations will not time out. 538 func (f *File) SetDeadline(t time.Time) error { 539 return f.setDeadline(t) 540 } 541 542 // SetReadDeadline sets the deadline for future Read calls and any 543 // currently-blocked Read call. 544 // A zero value for t means Read will not time out. 545 // Not all files support setting deadlines; see SetDeadline. 546 func (f *File) SetReadDeadline(t time.Time) error { 547 return f.setReadDeadline(t) 548 } 549 550 // SetWriteDeadline sets the deadline for any future Write calls and any 551 // currently-blocked Write call. 552 // Even if Write times out, it may return n > 0, indicating that 553 // some of the data was successfully written. 554 // A zero value for t means Write will not time out. 555 // Not all files support setting deadlines; see SetDeadline. 556 func (f *File) SetWriteDeadline(t time.Time) error { 557 return f.setWriteDeadline(t) 558 } 559 560 // SyscallConn returns a raw file. 561 // This implements the syscall.Conn interface. 562 func (f *File) SyscallConn() (syscall.RawConn, error) { 563 if err := f.checkValid("SyscallConn"); err != nil { 564 return nil, err 565 } 566 return newRawConn(f) 567 } 568 569 // isWindowsNulName reports whether name is os.DevNull ('NUL') on Windows. 570 // True is returned if name is 'NUL' whatever the case. 571 func isWindowsNulName(name string) bool { 572 if len(name) != 3 { 573 return false 574 } 575 if name[0] != 'n' && name[0] != 'N' { 576 return false 577 } 578 if name[1] != 'u' && name[1] != 'U' { 579 return false 580 } 581 if name[2] != 'l' && name[2] != 'L' { 582 return false 583 } 584 return true 585 }