github.com/dara-project/godist@v0.0.0-20200823115410-e0c80c8f0c78/src/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 package os 38 39 import ( 40 "dara" 41 "errors" 42 "internal/poll" 43 "internal/testlog" 44 "io" 45 "runtime" 46 "syscall" 47 "time" 48 ) 49 50 // Name returns the name of the file as presented to Open. 51 func (f *File) Name() string { return f.name } 52 53 // Stdin, Stdout, and Stderr are open Files pointing to the standard input, 54 // standard output, and standard error file descriptors. 55 // 56 // Note that the Go runtime writes to standard error for panics and crashes; 57 // closing Stderr may cause those messages to go elsewhere, perhaps 58 // to a file opened later. 59 var ( 60 Stdin = NewFile(uintptr(syscall.Stdin), "/dev/stdin") 61 Stdout = NewFile(uintptr(syscall.Stdout), "/dev/stdout") 62 Stderr = NewFile(uintptr(syscall.Stderr), "/dev/stderr") 63 ) 64 65 // Flags to OpenFile wrapping those of the underlying system. Not all 66 // flags may be implemented on a given system. 67 const ( 68 // Exactly one of O_RDONLY, O_WRONLY, or O_RDWR must be specified. 69 O_RDONLY int = syscall.O_RDONLY // open the file read-only. 70 O_WRONLY int = syscall.O_WRONLY // open the file write-only. 71 O_RDWR int = syscall.O_RDWR // open the file read-write. 72 // The remaining values may be or'ed in to control behavior. 73 O_APPEND int = syscall.O_APPEND // append data to the file when writing. 74 O_CREATE int = syscall.O_CREAT // create a new file if none exists. 75 O_EXCL int = syscall.O_EXCL // used with O_CREATE, file must not exist. 76 O_SYNC int = syscall.O_SYNC // open for synchronous I/O. 77 O_TRUNC int = syscall.O_TRUNC // if possible, truncate file when opened. 78 ) 79 80 // Seek whence values. 81 // 82 // Deprecated: Use io.SeekStart, io.SeekCurrent, and io.SeekEnd. 83 const ( 84 SEEK_SET int = 0 // seek relative to the origin of the file 85 SEEK_CUR int = 1 // seek relative to the current offset 86 SEEK_END int = 2 // seek relative to the end 87 ) 88 89 // LinkError records an error during a link or symlink or rename 90 // system call and the paths that caused it. 91 type LinkError struct { 92 Op string 93 Old string 94 New string 95 Err error 96 } 97 98 func (e *LinkError) Error() string { 99 return e.Op + " " + e.Old + " " + e.New + ": " + e.Err.Error() 100 } 101 102 // Read reads up to len(b) bytes from the File. 103 // It returns the number of bytes read and any error encountered. 104 // At end of file, Read returns 0, io.EOF. 105 func (f *File) Read(b []byte) (n int, err error) { 106 if err := f.checkValid("read"); err != nil { 107 return 0, err 108 } 109 n, e := f.read(b) 110 return n, f.wrapErr("read", e) 111 } 112 113 // ReadAt reads len(b) bytes from the File starting at byte offset off. 114 // It returns the number of bytes read and the error, if any. 115 // ReadAt always returns a non-nil error when n < len(b). 116 // At end of file, that error is io.EOF. 117 func (f *File) ReadAt(b []byte, off int64) (n int, err error) { 118 if err := f.checkValid("read"); err != nil { 119 return 0, err 120 } 121 122 if off < 0 { 123 return 0, &PathError{"readat", f.name, errors.New("negative offset")} 124 } 125 126 for len(b) > 0 { 127 m, e := f.pread(b, off) 128 if e != nil { 129 err = f.wrapErr("read", e) 130 break 131 } 132 n += m 133 b = b[m:] 134 off += int64(m) 135 } 136 return 137 } 138 139 // Write writes len(b) bytes to the File. 140 // It returns the number of bytes written and an error, if any. 141 // Write returns a non-nil error when n != len(b). 142 func (f *File) Write(b []byte) (n int, err error) { 143 if err := f.checkValid("write"); err != nil { 144 return 0, err 145 } 146 n, e := f.write(b) 147 if n < 0 { 148 n = 0 149 } 150 if n != len(b) { 151 err = io.ErrShortWrite 152 } 153 154 epipecheck(f, e) 155 156 if e != nil { 157 err = f.wrapErr("write", e) 158 } 159 160 return n, err 161 } 162 163 // WriteAt writes len(b) bytes to the File starting at byte offset off. 164 // It returns the number of bytes written and an error, if any. 165 // WriteAt returns a non-nil error when n != len(b). 166 func (f *File) WriteAt(b []byte, off int64) (n int, err error) { 167 if err := f.checkValid("write"); err != nil { 168 return 0, err 169 } 170 171 if off < 0 { 172 return 0, &PathError{"writeat", f.name, errors.New("negative offset")} 173 } 174 175 for len(b) > 0 { 176 m, e := f.pwrite(b, off) 177 if e != nil { 178 err = f.wrapErr("write", e) 179 break 180 } 181 n += m 182 b = b[m:] 183 off += int64(m) 184 } 185 return 186 } 187 188 // Seek sets the offset for the next Read or Write on file to offset, interpreted 189 // according to whence: 0 means relative to the origin of the file, 1 means 190 // relative to the current offset, and 2 means relative to the end. 191 // It returns the new offset and an error, if any. 192 // The behavior of Seek on a file opened with O_APPEND is not specified. 193 func (f *File) Seek(offset int64, whence int) (ret int64, err error) { 194 if err := f.checkValid("seek"); err != nil { 195 return 0, err 196 } 197 r, e := f.seek(offset, whence) 198 if e == nil && f.dirinfo != nil && r != 0 { 199 e = syscall.EISDIR 200 } 201 if e != nil { 202 return 0, f.wrapErr("seek", e) 203 } 204 return r, nil 205 } 206 207 // WriteString is like Write, but writes the contents of string s rather than 208 // a slice of bytes. 209 func (f *File) WriteString(s string) (n int, err error) { 210 return f.Write([]byte(s)) 211 } 212 213 // Mkdir creates a new directory with the specified name and permission 214 // bits (before umask). 215 // If there is an error, it will be of type *PathError. 216 func Mkdir(name string, perm FileMode) error { 217 e := syscall.Mkdir(fixLongPath(name), syscallMode(perm)) 218 219 // DARA Instrumentation 220 if runtime.Is_dara_profiling_on() { 221 runtime.Dara_Debug_Print(func() { 222 print("[MKDIR] : ") 223 print(name) 224 print(" ") 225 println(perm) 226 }) 227 argInfo1 := dara.GeneralType{Type: dara.STRING} 228 copy(argInfo1.String[:], name) 229 argInfo2 := dara.GeneralType{Type: dara.INTEGER, Integer : int(perm)} 230 retInfo := dara.GeneralType{Type: dara.ERROR, Unsupported : dara.UNSUPPORTEDVAL} 231 syscallInfo := dara.GeneralSyscall{dara.DSYS_MKDIR, 2, 1, [10]dara.GeneralType{argInfo1, argInfo2}, [10]dara.GeneralType{retInfo}} 232 runtime.Report_Syscall_To_Scheduler(dara.DSYS_MKDIR, syscallInfo) 233 } 234 if e != nil { 235 return &PathError{"mkdir", name, e} 236 } 237 238 // mkdir(2) itself won't handle the sticky bit on *BSD and Solaris 239 if !supportsCreateWithStickyBit && perm&ModeSticky != 0 { 240 Chmod(name, perm) 241 } 242 243 return nil 244 } 245 246 // Chdir changes the current working directory to the named directory. 247 // If there is an error, it will be of type *PathError. 248 func Chdir(dir string) error { 249 // DARA Instrumentation 250 if runtime.Is_dara_profiling_on() { 251 runtime.Dara_Debug_Print(func() { 252 print("[CHDIR] : ") 253 println(dir) 254 }) 255 argInfo := dara.GeneralType{Type: dara.STRING} 256 copy(argInfo.String[:], dir) 257 retInfo := dara.GeneralType{Type: dara.ERROR, Unsupported: dara.UNSUPPORTEDVAL} 258 syscallInfo := dara.GeneralSyscall{dara.DSYS_CHDIR, 1, 1, [10]dara.GeneralType{argInfo}, [10]dara.GeneralType{retInfo}} 259 runtime.Report_Syscall_To_Scheduler(dara.DSYS_CHDIR, syscallInfo) 260 } 261 if e := syscall.Chdir(dir); e != nil { 262 testlog.Open(dir) // observe likely non-existent directory 263 return &PathError{"chdir", dir, e} 264 } 265 if log := testlog.Logger(); log != nil { 266 wd, err := Getwd() 267 if err == nil { 268 log.Chdir(wd) 269 } 270 } 271 return nil 272 } 273 274 // Open opens the named file for reading. If successful, methods on 275 // the returned file can be used for reading; the associated file 276 // descriptor has mode O_RDONLY. 277 // If there is an error, it will be of type *PathError. 278 func Open(name string) (*File, error) { 279 return OpenFile(name, O_RDONLY, 0) 280 } 281 282 // Create creates the named file with mode 0666 (before umask), truncating 283 // it if it already exists. If successful, methods on the returned 284 // File can be used for I/O; the associated file descriptor has mode 285 // O_RDWR. 286 // If there is an error, it will be of type *PathError. 287 func Create(name string) (*File, error) { 288 return OpenFile(name, O_RDWR|O_CREATE|O_TRUNC, 0666) 289 } 290 291 // OpenFile is the generalized open call; most users will use Open 292 // or Create instead. It opens the named file with specified flag 293 // (O_RDONLY etc.) and perm (before umask), if applicable. If successful, 294 // methods on the returned File can be used for I/O. 295 // If there is an error, it will be of type *PathError. 296 func OpenFile(name string, flag int, perm FileMode) (*File, error) { 297 testlog.Open(name) 298 return openFileNolog(name, flag, perm) 299 } 300 301 // lstat is overridden in tests. 302 var lstat = Lstat 303 304 // Rename renames (moves) oldpath to newpath. 305 // If newpath already exists and is not a directory, Rename replaces it. 306 // OS-specific restrictions may apply when oldpath and newpath are in different directories. 307 // If there is an error, it will be of type *LinkError. 308 func Rename(oldpath, newpath string) error { 309 return rename(oldpath, newpath) 310 } 311 312 // Many functions in package syscall return a count of -1 instead of 0. 313 // Using fixCount(call()) instead of call() corrects the count. 314 func fixCount(n int, err error) (int, error) { 315 if n < 0 { 316 n = 0 317 } 318 return n, err 319 } 320 321 // wrapErr wraps an error that occurred during an operation on an open file. 322 // It passes io.EOF through unchanged, otherwise converts 323 // poll.ErrFileClosing to ErrClosed and wraps the error in a PathError. 324 func (f *File) wrapErr(op string, err error) error { 325 if err == nil || err == io.EOF { 326 return err 327 } 328 if err == poll.ErrFileClosing { 329 err = ErrClosed 330 } 331 return &PathError{op, f.name, err} 332 } 333 334 // TempDir returns the default directory to use for temporary files. 335 // 336 // On Unix systems, it returns $TMPDIR if non-empty, else /tmp. 337 // On Windows, it uses GetTempPath, returning the first non-empty 338 // value from %TMP%, %TEMP%, %USERPROFILE%, or the Windows directory. 339 // On Plan 9, it returns /tmp. 340 // 341 // The directory is neither guaranteed to exist nor have accessible 342 // permissions. 343 func TempDir() string { 344 return tempDir() 345 } 346 347 // Chmod changes the mode of the named file to mode. 348 // If the file is a symbolic link, it changes the mode of the link's target. 349 // If there is an error, it will be of type *PathError. 350 // 351 // A different subset of the mode bits are used, depending on the 352 // operating system. 353 // 354 // On Unix, the mode's permission bits, ModeSetuid, ModeSetgid, and 355 // ModeSticky are used. 356 // 357 // On Windows, the mode must be non-zero but otherwise only the 0200 358 // bit (owner writable) of mode is used; it controls whether the 359 // file's read-only attribute is set or cleared. attribute. The other 360 // bits are currently unused. Use mode 0400 for a read-only file and 361 // 0600 for a readable+writable file. 362 // 363 // On Plan 9, the mode's permission bits, ModeAppend, ModeExclusive, 364 // and ModeTemporary are used. 365 func Chmod(name string, mode FileMode) error { return chmod(name, mode) } 366 367 // Chmod changes the mode of the file to mode. 368 // If there is an error, it will be of type *PathError. 369 func (f *File) Chmod(mode FileMode) error { return f.chmod(mode) } 370 371 // SetDeadline sets the read and write deadlines for a File. 372 // It is equivalent to calling both SetReadDeadline and SetWriteDeadline. 373 // 374 // Only some kinds of files support setting a deadline. Calls to SetDeadline 375 // for files that do not support deadlines will return ErrNoDeadline. 376 // On most systems ordinary files do not support deadlines, but pipes do. 377 // 378 // A deadline is an absolute time after which I/O operations fail with an 379 // error instead of blocking. The deadline applies to all future and pending 380 // I/O, not just the immediately following call to Read or Write. 381 // After a deadline has been exceeded, the connection can be refreshed 382 // by setting a deadline in the future. 383 // 384 // An error returned after a timeout fails will implement the 385 // Timeout method, and calling the Timeout method will return true. 386 // The PathError and SyscallError types implement the Timeout method. 387 // In general, call IsTimeout to test whether an error indicates a timeout. 388 // 389 // An idle timeout can be implemented by repeatedly extending 390 // the deadline after successful Read or Write calls. 391 // 392 // A zero value for t means I/O operations will not time out. 393 func (f *File) SetDeadline(t time.Time) error { 394 return f.setDeadline(t) 395 } 396 397 // SetReadDeadline sets the deadline for future Read calls and any 398 // currently-blocked Read call. 399 // A zero value for t means Read will not time out. 400 // Not all files support setting deadlines; see SetDeadline. 401 func (f *File) SetReadDeadline(t time.Time) error { 402 return f.setReadDeadline(t) 403 } 404 405 // SetWriteDeadline sets the deadline for any future Write calls and any 406 // currently-blocked Write call. 407 // Even if Write times out, it may return n > 0, indicating that 408 // some of the data was successfully written. 409 // A zero value for t means Write will not time out. 410 // Not all files support setting deadlines; see SetDeadline. 411 func (f *File) SetWriteDeadline(t time.Time) error { 412 return f.setWriteDeadline(t) 413 }