Source file src/os/file.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 // 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 // # Concurrency 38 // 39 // The methods of [File] correspond to file system operations. All are 40 // safe for concurrent use. The maximum number of concurrent 41 // operations on a File may be limited by the OS or the system. The 42 // number should be high, but exceeding it may degrade performance or 43 // cause other issues. 44 package os 45 46 import ( 47 "errors" 48 "internal/filepathlite" 49 "internal/poll" 50 "internal/testlog" 51 "io" 52 "io/fs" 53 "runtime" 54 "syscall" 55 "time" 56 "unsafe" 57 ) 58 59 // Name returns the name of the file as presented to Open. 60 // 61 // It is safe to call Name after [Close]. 62 func (f *File) Name() string { return f.name } 63 64 // Stdin, Stdout, and Stderr are open Files pointing to the standard input, 65 // standard output, and standard error file descriptors. 66 // 67 // Note that the Go runtime writes to standard error for panics and crashes; 68 // closing Stderr may cause those messages to go elsewhere, perhaps 69 // to a file opened later. 70 var ( 71 Stdin = NewFile(uintptr(syscall.Stdin), "/dev/stdin") 72 Stdout = NewFile(uintptr(syscall.Stdout), "/dev/stdout") 73 Stderr = NewFile(uintptr(syscall.Stderr), "/dev/stderr") 74 ) 75 76 // Flags to OpenFile wrapping those of the underlying system. Not all 77 // flags may be implemented on a given system. 78 const ( 79 // Exactly one of O_RDONLY, O_WRONLY, or O_RDWR must be specified. 80 O_RDONLY int = syscall.O_RDONLY // open the file read-only. 81 O_WRONLY int = syscall.O_WRONLY // open the file write-only. 82 O_RDWR int = syscall.O_RDWR // open the file read-write. 83 // The remaining values may be or'ed in to control behavior. 84 O_APPEND int = syscall.O_APPEND // append data to the file when writing. 85 O_CREATE int = syscall.O_CREAT // create a new file if none exists. 86 O_EXCL int = syscall.O_EXCL // used with O_CREATE, file must not exist. 87 O_SYNC int = syscall.O_SYNC // open for synchronous I/O. 88 O_TRUNC int = syscall.O_TRUNC // truncate regular writable file when opened. 89 ) 90 91 // Seek whence values. 92 // 93 // Deprecated: Use io.SeekStart, io.SeekCurrent, and io.SeekEnd. 94 const ( 95 SEEK_SET int = 0 // seek relative to the origin of the file 96 SEEK_CUR int = 1 // seek relative to the current offset 97 SEEK_END int = 2 // seek relative to the end 98 ) 99 100 // LinkError records an error during a link or symlink or rename 101 // system call and the paths that caused it. 102 type LinkError struct { 103 Op string 104 Old string 105 New string 106 Err error 107 } 108 109 func (e *LinkError) Error() string { 110 return e.Op + " " + e.Old + " " + e.New + ": " + e.Err.Error() 111 } 112 113 func (e *LinkError) Unwrap() error { 114 return e.Err 115 } 116 117 // Read reads up to len(b) bytes from the File and stores them in b. 118 // It returns the number of bytes read and any error encountered. 119 // At end of file, Read returns 0, io.EOF. 120 func (f *File) Read(b []byte) (n int, err error) { 121 if err := f.checkValid("read"); err != nil { 122 return 0, err 123 } 124 n, e := f.read(b) 125 return n, f.wrapErr("read", e) 126 } 127 128 // ReadAt reads len(b) bytes from the File starting at byte offset off. 129 // It returns the number of bytes read and the error, if any. 130 // ReadAt always returns a non-nil error when n < len(b). 131 // At end of file, that error is io.EOF. 132 func (f *File) ReadAt(b []byte, off int64) (n int, err error) { 133 if err := f.checkValid("read"); err != nil { 134 return 0, err 135 } 136 137 if off < 0 { 138 return 0, &PathError{Op: "readat", Path: f.name, Err: errors.New("negative offset")} 139 } 140 141 for len(b) > 0 { 142 m, e := f.pread(b, off) 143 if e != nil { 144 err = f.wrapErr("read", e) 145 break 146 } 147 n += m 148 b = b[m:] 149 off += int64(m) 150 } 151 return 152 } 153 154 // ReadFrom implements io.ReaderFrom. 155 func (f *File) ReadFrom(r io.Reader) (n int64, err error) { 156 if err := f.checkValid("write"); err != nil { 157 return 0, err 158 } 159 n, handled, e := f.readFrom(r) 160 if !handled { 161 return genericReadFrom(f, r) // without wrapping 162 } 163 return n, f.wrapErr("write", e) 164 } 165 166 // noReadFrom can be embedded alongside another type to 167 // hide the ReadFrom method of that other type. 168 type noReadFrom struct{} 169 170 // ReadFrom hides another ReadFrom method. 171 // It should never be called. 172 func (noReadFrom) ReadFrom(io.Reader) (int64, error) { 173 panic("can't happen") 174 } 175 176 // fileWithoutReadFrom implements all the methods of *File other 177 // than ReadFrom. This is used to permit ReadFrom to call io.Copy 178 // without leading to a recursive call to ReadFrom. 179 type fileWithoutReadFrom struct { 180 noReadFrom 181 *File 182 } 183 184 func genericReadFrom(f *File, r io.Reader) (int64, error) { 185 return io.Copy(fileWithoutReadFrom{File: f}, r) 186 } 187 188 // Write writes len(b) bytes from b to the File. 189 // It returns the number of bytes written and an error, if any. 190 // Write returns a non-nil error when n != len(b). 191 func (f *File) Write(b []byte) (n int, err error) { 192 if err := f.checkValid("write"); err != nil { 193 return 0, err 194 } 195 n, e := f.write(b) 196 if n < 0 { 197 n = 0 198 } 199 if n != len(b) { 200 err = io.ErrShortWrite 201 } 202 203 epipecheck(f, e) 204 205 if e != nil { 206 err = f.wrapErr("write", e) 207 } 208 209 return n, err 210 } 211 212 var errWriteAtInAppendMode = errors.New("os: invalid use of WriteAt on file opened with O_APPEND") 213 214 // WriteAt writes len(b) bytes to the File starting at byte offset off. 215 // It returns the number of bytes written and an error, if any. 216 // WriteAt returns a non-nil error when n != len(b). 217 // 218 // If file was opened with the O_APPEND flag, WriteAt returns an error. 219 func (f *File) WriteAt(b []byte, off int64) (n int, err error) { 220 if err := f.checkValid("write"); err != nil { 221 return 0, err 222 } 223 if f.appendMode { 224 return 0, errWriteAtInAppendMode 225 } 226 227 if off < 0 { 228 return 0, &PathError{Op: "writeat", Path: f.name, Err: errors.New("negative offset")} 229 } 230 231 for len(b) > 0 { 232 m, e := f.pwrite(b, off) 233 if e != nil { 234 err = f.wrapErr("write", e) 235 break 236 } 237 n += m 238 b = b[m:] 239 off += int64(m) 240 } 241 return 242 } 243 244 // WriteTo implements io.WriterTo. 245 func (f *File) WriteTo(w io.Writer) (n int64, err error) { 246 if err := f.checkValid("read"); err != nil { 247 return 0, err 248 } 249 n, handled, e := f.writeTo(w) 250 if handled { 251 return n, f.wrapErr("read", e) 252 } 253 return genericWriteTo(f, w) // without wrapping 254 } 255 256 // noWriteTo can be embedded alongside another type to 257 // hide the WriteTo method of that other type. 258 type noWriteTo struct{} 259 260 // WriteTo hides another WriteTo method. 261 // It should never be called. 262 func (noWriteTo) WriteTo(io.Writer) (int64, error) { 263 panic("can't happen") 264 } 265 266 // fileWithoutWriteTo implements all the methods of *File other 267 // than WriteTo. This is used to permit WriteTo to call io.Copy 268 // without leading to a recursive call to WriteTo. 269 type fileWithoutWriteTo struct { 270 noWriteTo 271 *File 272 } 273 274 func genericWriteTo(f *File, w io.Writer) (int64, error) { 275 return io.Copy(w, fileWithoutWriteTo{File: f}) 276 } 277 278 // Seek sets the offset for the next Read or Write on file to offset, interpreted 279 // according to whence: 0 means relative to the origin of the file, 1 means 280 // relative to the current offset, and 2 means relative to the end. 281 // It returns the new offset and an error, if any. 282 // The behavior of Seek on a file opened with O_APPEND is not specified. 283 func (f *File) Seek(offset int64, whence int) (ret int64, err error) { 284 if err := f.checkValid("seek"); err != nil { 285 return 0, err 286 } 287 r, e := f.seek(offset, whence) 288 if e == nil && f.dirinfo.Load() != nil && r != 0 { 289 e = syscall.EISDIR 290 } 291 if e != nil { 292 return 0, f.wrapErr("seek", e) 293 } 294 return r, nil 295 } 296 297 // WriteString is like Write, but writes the contents of string s rather than 298 // a slice of bytes. 299 func (f *File) WriteString(s string) (n int, err error) { 300 b := unsafe.Slice(unsafe.StringData(s), len(s)) 301 return f.Write(b) 302 } 303 304 // Mkdir creates a new directory with the specified name and permission 305 // bits (before umask). 306 // If there is an error, it will be of type *PathError. 307 func Mkdir(name string, perm FileMode) error { 308 longName := fixLongPath(name) 309 e := ignoringEINTR(func() error { 310 return syscall.Mkdir(longName, syscallMode(perm)) 311 }) 312 313 if e != nil { 314 return &PathError{Op: "mkdir", Path: name, Err: e} 315 } 316 317 // mkdir(2) itself won't handle the sticky bit on *BSD and Solaris 318 if !supportsCreateWithStickyBit && perm&ModeSticky != 0 { 319 e = setStickyBit(name) 320 321 if e != nil { 322 Remove(name) 323 return e 324 } 325 } 326 327 return nil 328 } 329 330 // setStickyBit adds ModeSticky to the permission bits of path, non atomic. 331 func setStickyBit(name string) error { 332 fi, err := Stat(name) 333 if err != nil { 334 return err 335 } 336 return Chmod(name, fi.Mode()|ModeSticky) 337 } 338 339 // Chdir changes the current working directory to the named directory. 340 // If there is an error, it will be of type *PathError. 341 func Chdir(dir string) error { 342 if e := syscall.Chdir(dir); e != nil { 343 testlog.Open(dir) // observe likely non-existent directory 344 return &PathError{Op: "chdir", Path: dir, Err: e} 345 } 346 if runtime.GOOS == "windows" { 347 abs := filepathlite.IsAbs(dir) 348 getwdCache.Lock() 349 if abs { 350 getwdCache.dir = dir 351 } else { 352 getwdCache.dir = "" 353 } 354 getwdCache.Unlock() 355 } 356 if log := testlog.Logger(); log != nil { 357 wd, err := Getwd() 358 if err == nil { 359 log.Chdir(wd) 360 } 361 } 362 return nil 363 } 364 365 // Open opens the named file for reading. If successful, methods on 366 // the returned file can be used for reading; the associated file 367 // descriptor has mode O_RDONLY. 368 // If there is an error, it will be of type *PathError. 369 func Open(name string) (*File, error) { 370 return OpenFile(name, O_RDONLY, 0) 371 } 372 373 // Create creates or truncates the named file. If the file already exists, 374 // it is truncated. If the file does not exist, it is created with mode 0o666 375 // (before umask). If successful, methods on the returned File can 376 // be used for I/O; the associated file descriptor has mode O_RDWR. 377 // The directory containing the file must already exist. 378 // If there is an error, it will be of type *PathError. 379 func Create(name string) (*File, error) { 380 return OpenFile(name, O_RDWR|O_CREATE|O_TRUNC, 0666) 381 } 382 383 // OpenFile is the generalized open call; most users will use Open 384 // or Create instead. It opens the named file with specified flag 385 // (O_RDONLY etc.). If the file does not exist, and the O_CREATE flag 386 // is passed, it is created with mode perm (before umask); 387 // the containing directory must exist. If successful, 388 // methods on the returned File can be used for I/O. 389 // If there is an error, it will be of type *PathError. 390 func OpenFile(name string, flag int, perm FileMode) (*File, error) { 391 testlog.Open(name) 392 f, err := openFileNolog(name, flag, perm) 393 if err != nil { 394 return nil, err 395 } 396 f.appendMode = flag&O_APPEND != 0 397 398 return f, nil 399 } 400 401 var errPathEscapes = errors.New("path escapes from parent") 402 403 // openDir opens a file which is assumed to be a directory. As such, it skips 404 // the syscalls that make the file descriptor non-blocking as these take time 405 // and will fail on file descriptors for directories. 406 func openDir(name string) (*File, error) { 407 testlog.Open(name) 408 return openDirNolog(name) 409 } 410 411 // lstat is overridden in tests. 412 var lstat = Lstat 413 414 // Rename renames (moves) oldpath to newpath. 415 // If newpath already exists and is not a directory, Rename replaces it. 416 // If newpath already exists and is a directory, Rename returns an error. 417 // OS-specific restrictions may apply when oldpath and newpath are in different directories. 418 // Even within the same directory, on non-Unix platforms Rename is not an atomic operation. 419 // If there is an error, it will be of type *LinkError. 420 func Rename(oldpath, newpath string) error { 421 return rename(oldpath, newpath) 422 } 423 424 // Readlink returns the destination of the named symbolic link. 425 // If there is an error, it will be of type *PathError. 426 // 427 // If the link destination is relative, Readlink returns the relative path 428 // without resolving it to an absolute one. 429 func Readlink(name string) (string, error) { 430 return readlink(name) 431 } 432 433 // Many functions in package syscall return a count of -1 instead of 0. 434 // Using fixCount(call()) instead of call() corrects the count. 435 func fixCount(n int, err error) (int, error) { 436 if n < 0 { 437 n = 0 438 } 439 return n, err 440 } 441 442 // checkWrapErr is the test hook to enable checking unexpected wrapped errors of poll.ErrFileClosing. 443 // It is set to true in the export_test.go for tests (including fuzz tests). 444 var checkWrapErr = false 445 446 // wrapErr wraps an error that occurred during an operation on an open file. 447 // It passes io.EOF through unchanged, otherwise converts 448 // poll.ErrFileClosing to ErrClosed and wraps the error in a PathError. 449 func (f *File) wrapErr(op string, err error) error { 450 if err == nil || err == io.EOF { 451 return err 452 } 453 if err == poll.ErrFileClosing { 454 err = ErrClosed 455 } else if checkWrapErr && errors.Is(err, poll.ErrFileClosing) { 456 panic("unexpected error wrapping poll.ErrFileClosing: " + err.Error()) 457 } 458 return &PathError{Op: op, Path: f.name, Err: err} 459 } 460 461 // TempDir returns the default directory to use for temporary files. 462 // 463 // On Unix systems, it returns $TMPDIR if non-empty, else /tmp. 464 // On Windows, it uses GetTempPath, returning the first non-empty 465 // value from %TMP%, %TEMP%, %USERPROFILE%, or the Windows directory. 466 // On Plan 9, it returns /tmp. 467 // 468 // The directory is neither guaranteed to exist nor have accessible 469 // permissions. 470 func TempDir() string { 471 return tempDir() 472 } 473 474 // UserCacheDir returns the default root directory to use for user-specific 475 // cached data. Users should create their own application-specific subdirectory 476 // within this one and use that. 477 // 478 // On Unix systems, it returns $XDG_CACHE_HOME as specified by 479 // https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html if 480 // non-empty, else $HOME/.cache. 481 // On Darwin, it returns $HOME/Library/Caches. 482 // On Windows, it returns %LocalAppData%. 483 // On Plan 9, it returns $home/lib/cache. 484 // 485 // If the location cannot be determined (for example, $HOME is not defined) or 486 // the path in $XDG_CACHE_HOME is relative, then it will return an error. 487 func UserCacheDir() (string, error) { 488 var dir string 489 490 switch runtime.GOOS { 491 case "windows": 492 dir = Getenv("LocalAppData") 493 if dir == "" { 494 return "", errors.New("%LocalAppData% is not defined") 495 } 496 497 case "darwin", "ios": 498 dir = Getenv("HOME") 499 if dir == "" { 500 return "", errors.New("$HOME is not defined") 501 } 502 dir += "/Library/Caches" 503 504 case "plan9": 505 dir = Getenv("home") 506 if dir == "" { 507 return "", errors.New("$home is not defined") 508 } 509 dir += "/lib/cache" 510 511 default: // Unix 512 dir = Getenv("XDG_CACHE_HOME") 513 if dir == "" { 514 dir = Getenv("HOME") 515 if dir == "" { 516 return "", errors.New("neither $XDG_CACHE_HOME nor $HOME are defined") 517 } 518 dir += "/.cache" 519 } else if !filepathlite.IsAbs(dir) { 520 return "", errors.New("path in $XDG_CACHE_HOME is relative") 521 } 522 } 523 524 return dir, nil 525 } 526 527 // UserConfigDir returns the default root directory to use for user-specific 528 // configuration data. Users should create their own application-specific 529 // subdirectory within this one and use that. 530 // 531 // On Unix systems, it returns $XDG_CONFIG_HOME as specified by 532 // https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html if 533 // non-empty, else $HOME/.config. 534 // On Darwin, it returns $HOME/Library/Application Support. 535 // On Windows, it returns %AppData%. 536 // On Plan 9, it returns $home/lib. 537 // 538 // If the location cannot be determined (for example, $HOME is not defined) or 539 // the path in $XDG_CONFIG_HOME is relative, then it will return an error. 540 func UserConfigDir() (string, error) { 541 var dir string 542 543 switch runtime.GOOS { 544 case "windows": 545 dir = Getenv("AppData") 546 if dir == "" { 547 return "", errors.New("%AppData% is not defined") 548 } 549 550 case "darwin", "ios": 551 dir = Getenv("HOME") 552 if dir == "" { 553 return "", errors.New("$HOME is not defined") 554 } 555 dir += "/Library/Application Support" 556 557 case "plan9": 558 dir = Getenv("home") 559 if dir == "" { 560 return "", errors.New("$home is not defined") 561 } 562 dir += "/lib" 563 564 default: // Unix 565 dir = Getenv("XDG_CONFIG_HOME") 566 if dir == "" { 567 dir = Getenv("HOME") 568 if dir == "" { 569 return "", errors.New("neither $XDG_CONFIG_HOME nor $HOME are defined") 570 } 571 dir += "/.config" 572 } else if !filepathlite.IsAbs(dir) { 573 return "", errors.New("path in $XDG_CONFIG_HOME is relative") 574 } 575 } 576 577 return dir, nil 578 } 579 580 // UserHomeDir returns the current user's home directory. 581 // 582 // On Unix, including macOS, it returns the $HOME environment variable. 583 // On Windows, it returns %USERPROFILE%. 584 // On Plan 9, it returns the $home environment variable. 585 // 586 // If the expected variable is not set in the environment, UserHomeDir 587 // returns either a platform-specific default value or a non-nil error. 588 func UserHomeDir() (string, error) { 589 env, enverr := "HOME", "$HOME" 590 switch runtime.GOOS { 591 case "windows": 592 env, enverr = "USERPROFILE", "%userprofile%" 593 case "plan9": 594 env, enverr = "home", "$home" 595 } 596 if v := Getenv(env); v != "" { 597 return v, nil 598 } 599 // On some geese the home directory is not always defined. 600 switch runtime.GOOS { 601 case "android": 602 return "/sdcard", nil 603 case "ios": 604 return "/", nil 605 } 606 return "", errors.New(enverr + " is not defined") 607 } 608 609 // Chmod changes the mode of the named file to mode. 610 // If the file is a symbolic link, it changes the mode of the link's target. 611 // If there is an error, it will be of type *PathError. 612 // 613 // A different subset of the mode bits are used, depending on the 614 // operating system. 615 // 616 // On Unix, the mode's permission bits, ModeSetuid, ModeSetgid, and 617 // ModeSticky are used. 618 // 619 // On Windows, only the 0o200 bit (owner writable) of mode is used; it 620 // controls whether the file's read-only attribute is set or cleared. 621 // The other bits are currently unused. For compatibility with Go 1.12 622 // and earlier, use a non-zero mode. Use mode 0o400 for a read-only 623 // file and 0o600 for a readable+writable file. 624 // 625 // On Plan 9, the mode's permission bits, ModeAppend, ModeExclusive, 626 // and ModeTemporary are used. 627 func Chmod(name string, mode FileMode) error { return chmod(name, mode) } 628 629 // Chmod changes the mode of the file to mode. 630 // If there is an error, it will be of type *PathError. 631 func (f *File) Chmod(mode FileMode) error { return f.chmod(mode) } 632 633 // SetDeadline sets the read and write deadlines for a File. 634 // It is equivalent to calling both SetReadDeadline and SetWriteDeadline. 635 // 636 // Only some kinds of files support setting a deadline. Calls to SetDeadline 637 // for files that do not support deadlines will return ErrNoDeadline. 638 // On most systems ordinary files do not support deadlines, but pipes do. 639 // 640 // A deadline is an absolute time after which I/O operations fail with an 641 // error instead of blocking. The deadline applies to all future and pending 642 // I/O, not just the immediately following call to Read or Write. 643 // After a deadline has been exceeded, the connection can be refreshed 644 // by setting a deadline in the future. 645 // 646 // If the deadline is exceeded a call to Read or Write or to other I/O 647 // methods will return an error that wraps ErrDeadlineExceeded. 648 // This can be tested using errors.Is(err, os.ErrDeadlineExceeded). 649 // That error implements the Timeout method, and calling the Timeout 650 // method will return true, but there are other possible errors for which 651 // the Timeout will return true even if the deadline has not been exceeded. 652 // 653 // An idle timeout can be implemented by repeatedly extending 654 // the deadline after successful Read or Write calls. 655 // 656 // A zero value for t means I/O operations will not time out. 657 func (f *File) SetDeadline(t time.Time) error { 658 return f.setDeadline(t) 659 } 660 661 // SetReadDeadline sets the deadline for future Read calls and any 662 // currently-blocked Read call. 663 // A zero value for t means Read will not time out. 664 // Not all files support setting deadlines; see SetDeadline. 665 func (f *File) SetReadDeadline(t time.Time) error { 666 return f.setReadDeadline(t) 667 } 668 669 // SetWriteDeadline sets the deadline for any future Write calls and any 670 // currently-blocked Write call. 671 // Even if Write times out, it may return n > 0, indicating that 672 // some of the data was successfully written. 673 // A zero value for t means Write will not time out. 674 // Not all files support setting deadlines; see SetDeadline. 675 func (f *File) SetWriteDeadline(t time.Time) error { 676 return f.setWriteDeadline(t) 677 } 678 679 // SyscallConn returns a raw file. 680 // This implements the syscall.Conn interface. 681 func (f *File) SyscallConn() (syscall.RawConn, error) { 682 if err := f.checkValid("SyscallConn"); err != nil { 683 return nil, err 684 } 685 return newRawConn(f) 686 } 687 688 // DirFS returns a file system (an fs.FS) for the tree of files rooted at the directory dir. 689 // 690 // Note that DirFS("/prefix") only guarantees that the Open calls it makes to the 691 // operating system will begin with "/prefix": DirFS("/prefix").Open("file") is the 692 // same as os.Open("/prefix/file"). So if /prefix/file is a symbolic link pointing outside 693 // the /prefix tree, then using DirFS does not stop the access any more than using 694 // os.Open does. Additionally, the root of the fs.FS returned for a relative path, 695 // DirFS("prefix"), will be affected by later calls to Chdir. DirFS is therefore not 696 // a general substitute for a chroot-style security mechanism when the directory tree 697 // contains arbitrary content. 698 // 699 // Use [Root.FS] to obtain a fs.FS that prevents escapes from the tree via symbolic links. 700 // 701 // The directory dir must not be "". 702 // 703 // The result implements [io/fs.StatFS], [io/fs.ReadFileFS] and 704 // [io/fs.ReadDirFS]. 705 func DirFS(dir string) fs.FS { 706 return dirFS(dir) 707 } 708 709 type dirFS string 710 711 func (dir dirFS) Open(name string) (fs.File, error) { 712 fullname, err := dir.join(name) 713 if err != nil { 714 return nil, &PathError{Op: "open", Path: name, Err: err} 715 } 716 f, err := Open(fullname) 717 if err != nil { 718 // DirFS takes a string appropriate for GOOS, 719 // while the name argument here is always slash separated. 720 // dir.join will have mixed the two; undo that for 721 // error reporting. 722 err.(*PathError).Path = name 723 return nil, err 724 } 725 return f, nil 726 } 727 728 // The ReadFile method calls the [ReadFile] function for the file 729 // with the given name in the directory. The function provides 730 // robust handling for small files and special file systems. 731 // Through this method, dirFS implements [io/fs.ReadFileFS]. 732 func (dir dirFS) ReadFile(name string) ([]byte, error) { 733 fullname, err := dir.join(name) 734 if err != nil { 735 return nil, &PathError{Op: "readfile", Path: name, Err: err} 736 } 737 b, err := ReadFile(fullname) 738 if err != nil { 739 if e, ok := err.(*PathError); ok { 740 // See comment in dirFS.Open. 741 e.Path = name 742 } 743 return nil, err 744 } 745 return b, nil 746 } 747 748 // ReadDir reads the named directory, returning all its directory entries sorted 749 // by filename. Through this method, dirFS implements [io/fs.ReadDirFS]. 750 func (dir dirFS) ReadDir(name string) ([]DirEntry, error) { 751 fullname, err := dir.join(name) 752 if err != nil { 753 return nil, &PathError{Op: "readdir", Path: name, Err: err} 754 } 755 entries, err := ReadDir(fullname) 756 if err != nil { 757 if e, ok := err.(*PathError); ok { 758 // See comment in dirFS.Open. 759 e.Path = name 760 } 761 return nil, err 762 } 763 return entries, nil 764 } 765 766 func (dir dirFS) Stat(name string) (fs.FileInfo, error) { 767 fullname, err := dir.join(name) 768 if err != nil { 769 return nil, &PathError{Op: "stat", Path: name, Err: err} 770 } 771 f, err := Stat(fullname) 772 if err != nil { 773 // See comment in dirFS.Open. 774 err.(*PathError).Path = name 775 return nil, err 776 } 777 return f, nil 778 } 779 780 // join returns the path for name in dir. 781 func (dir dirFS) join(name string) (string, error) { 782 if dir == "" { 783 return "", errors.New("os: DirFS with empty root") 784 } 785 name, err := filepathlite.Localize(name) 786 if err != nil { 787 return "", ErrInvalid 788 } 789 if IsPathSeparator(dir[len(dir)-1]) { 790 return string(dir) + name, nil 791 } 792 return string(dir) + string(PathSeparator) + name, nil 793 } 794 795 // ReadFile reads the named file and returns the contents. 796 // A successful call returns err == nil, not err == EOF. 797 // Because ReadFile reads the whole file, it does not treat an EOF from Read 798 // as an error to be reported. 799 func ReadFile(name string) ([]byte, error) { 800 f, err := Open(name) 801 if err != nil { 802 return nil, err 803 } 804 defer f.Close() 805 return readFileContents(f) 806 } 807 808 func readFileContents(f *File) ([]byte, error) { 809 var size int 810 if info, err := f.Stat(); err == nil { 811 size64 := info.Size() 812 if int64(int(size64)) == size64 { 813 size = int(size64) 814 } 815 } 816 size++ // one byte for final read at EOF 817 818 // If a file claims a small size, read at least 512 bytes. 819 // In particular, files in Linux's /proc claim size 0 but 820 // then do not work right if read in small pieces, 821 // so an initial read of 1 byte would not work correctly. 822 if size < 512 { 823 size = 512 824 } 825 826 data := make([]byte, 0, size) 827 for { 828 n, err := f.Read(data[len(data):cap(data)]) 829 data = data[:len(data)+n] 830 if err != nil { 831 if err == io.EOF { 832 err = nil 833 } 834 return data, err 835 } 836 837 if len(data) >= cap(data) { 838 d := append(data[:cap(data)], 0) 839 data = d[:len(data)] 840 } 841 } 842 } 843 844 // WriteFile writes data to the named file, creating it if necessary. 845 // If the file does not exist, WriteFile creates it with permissions perm (before umask); 846 // otherwise WriteFile truncates it before writing, without changing permissions. 847 // Since WriteFile requires multiple system calls to complete, a failure mid-operation 848 // can leave the file in a partially written state. 849 func WriteFile(name string, data []byte, perm FileMode) error { 850 f, err := OpenFile(name, O_WRONLY|O_CREATE|O_TRUNC, perm) 851 if err != nil { 852 return err 853 } 854 _, err = f.Write(data) 855 if err1 := f.Close(); err1 != nil && err == nil { 856 err = err1 857 } 858 return err 859 } 860