]> git.ipfire.org Git - thirdparty/gcc.git/blob - libgo/go/os/file.go
libgo: update to Go1.14beta1
[thirdparty/gcc.git] / libgo / go / 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 // 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 "internal/poll"
46 "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 func (f *File) Seek(offset int64, whence int) (ret int64, err error) {
208 if err := f.checkValid("seek"); err != nil {
209 return 0, err
210 }
211 r, e := f.seek(offset, whence)
212 if e == nil && f.dirinfo != nil && r != 0 {
213 e = syscall.EISDIR
214 }
215 if e != nil {
216 return 0, f.wrapErr("seek", e)
217 }
218 return r, nil
219 }
220
221 // WriteString is like Write, but writes the contents of string s rather than
222 // a slice of bytes.
223 func (f *File) WriteString(s string) (n int, err error) {
224 return f.Write([]byte(s))
225 }
226
227 // Mkdir creates a new directory with the specified name and permission
228 // bits (before umask).
229 // If there is an error, it will be of type *PathError.
230 func Mkdir(name string, perm FileMode) error {
231 if runtime.GOOS == "windows" && isWindowsNulName(name) {
232 return &PathError{"mkdir", name, syscall.ENOTDIR}
233 }
234 e := syscall.Mkdir(fixLongPath(name), syscallMode(perm))
235
236 if e != nil {
237 return &PathError{"mkdir", name, e}
238 }
239
240 // mkdir(2) itself won't handle the sticky bit on *BSD and Solaris
241 if !supportsCreateWithStickyBit && perm&ModeSticky != 0 {
242 e = setStickyBit(name)
243
244 if e != nil {
245 Remove(name)
246 return e
247 }
248 }
249
250 return nil
251 }
252
253 // setStickyBit adds ModeSticky to the permission bits of path, non atomic.
254 func setStickyBit(name string) error {
255 fi, err := Stat(name)
256 if err != nil {
257 return err
258 }
259 return Chmod(name, fi.Mode()|ModeSticky)
260 }
261
262 // Chdir changes the current working directory to the named directory.
263 // If there is an error, it will be of type *PathError.
264 func Chdir(dir string) error {
265 if e := syscall.Chdir(dir); e != nil {
266 testlog.Open(dir) // observe likely non-existent directory
267 return &PathError{"chdir", dir, e}
268 }
269 if log := testlog.Logger(); log != nil {
270 wd, err := Getwd()
271 if err == nil {
272 log.Chdir(wd)
273 }
274 }
275 return nil
276 }
277
278 // Open opens the named file for reading. If successful, methods on
279 // the returned file can be used for reading; the associated file
280 // descriptor has mode O_RDONLY.
281 // If there is an error, it will be of type *PathError.
282 func Open(name string) (*File, error) {
283 return OpenFile(name, O_RDONLY, 0)
284 }
285
286 // Create creates or truncates the named file. If the file already exists,
287 // it is truncated. If the file does not exist, it is created with mode 0666
288 // (before umask). If successful, methods on the returned File can
289 // be used for I/O; the associated file descriptor has mode O_RDWR.
290 // If there is an error, it will be of type *PathError.
291 func Create(name string) (*File, error) {
292 return OpenFile(name, O_RDWR|O_CREATE|O_TRUNC, 0666)
293 }
294
295 // OpenFile is the generalized open call; most users will use Open
296 // or Create instead. It opens the named file with specified flag
297 // (O_RDONLY etc.). If the file does not exist, and the O_CREATE flag
298 // is passed, it is created with mode perm (before umask). If successful,
299 // methods on the returned File can be used for I/O.
300 // If there is an error, it will be of type *PathError.
301 func OpenFile(name string, flag int, perm FileMode) (*File, error) {
302 testlog.Open(name)
303 f, err := openFileNolog(name, flag, perm)
304 if err != nil {
305 return nil, err
306 }
307 f.appendMode = flag&O_APPEND != 0
308
309 return f, nil
310 }
311
312 // lstat is overridden in tests.
313 var lstat = Lstat
314
315 // Rename renames (moves) oldpath to newpath.
316 // If newpath already exists and is not a directory, Rename replaces it.
317 // OS-specific restrictions may apply when oldpath and newpath are in different directories.
318 // If there is an error, it will be of type *LinkError.
319 func Rename(oldpath, newpath string) error {
320 return rename(oldpath, newpath)
321 }
322
323 // Many functions in package syscall return a count of -1 instead of 0.
324 // Using fixCount(call()) instead of call() corrects the count.
325 func fixCount(n int, err error) (int, error) {
326 if n < 0 {
327 n = 0
328 }
329 return n, err
330 }
331
332 // wrapErr wraps an error that occurred during an operation on an open file.
333 // It passes io.EOF through unchanged, otherwise converts
334 // poll.ErrFileClosing to ErrClosed and wraps the error in a PathError.
335 func (f *File) wrapErr(op string, err error) error {
336 if err == nil || err == io.EOF {
337 return err
338 }
339 if err == poll.ErrFileClosing {
340 err = ErrClosed
341 }
342 return &PathError{op, f.name, err}
343 }
344
345 // TempDir returns the default directory to use for temporary files.
346 //
347 // On Unix systems, it returns $TMPDIR if non-empty, else /tmp.
348 // On Windows, it uses GetTempPath, returning the first non-empty
349 // value from %TMP%, %TEMP%, %USERPROFILE%, or the Windows directory.
350 // On Plan 9, it returns /tmp.
351 //
352 // The directory is neither guaranteed to exist nor have accessible
353 // permissions.
354 func TempDir() string {
355 return tempDir()
356 }
357
358 // UserCacheDir returns the default root directory to use for user-specific
359 // cached data. Users should create their own application-specific subdirectory
360 // within this one and use that.
361 //
362 // On Unix systems, it returns $XDG_CACHE_HOME as specified by
363 // https://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html if
364 // non-empty, else $HOME/.cache.
365 // On Darwin, it returns $HOME/Library/Caches.
366 // On Windows, it returns %LocalAppData%.
367 // On Plan 9, it returns $home/lib/cache.
368 //
369 // If the location cannot be determined (for example, $HOME is not defined),
370 // then it will return an error.
371 func UserCacheDir() (string, error) {
372 var dir string
373
374 switch runtime.GOOS {
375 case "windows":
376 dir = Getenv("LocalAppData")
377 if dir == "" {
378 return "", errors.New("%LocalAppData% is not defined")
379 }
380
381 case "darwin":
382 dir = Getenv("HOME")
383 if dir == "" {
384 return "", errors.New("$HOME is not defined")
385 }
386 dir += "/Library/Caches"
387
388 case "plan9":
389 dir = Getenv("home")
390 if dir == "" {
391 return "", errors.New("$home is not defined")
392 }
393 dir += "/lib/cache"
394
395 default: // Unix
396 dir = Getenv("XDG_CACHE_HOME")
397 if dir == "" {
398 dir = Getenv("HOME")
399 if dir == "" {
400 return "", errors.New("neither $XDG_CACHE_HOME nor $HOME are defined")
401 }
402 dir += "/.cache"
403 }
404 }
405
406 return dir, nil
407 }
408
409 // UserConfigDir returns the default root directory to use for user-specific
410 // configuration data. Users should create their own application-specific
411 // subdirectory within this one and use that.
412 //
413 // On Unix systems, it returns $XDG_CONFIG_HOME as specified by
414 // https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html if
415 // non-empty, else $HOME/.config.
416 // On Darwin, it returns $HOME/Library/Application Support.
417 // On Windows, it returns %AppData%.
418 // On Plan 9, it returns $home/lib.
419 //
420 // If the location cannot be determined (for example, $HOME is not defined),
421 // then it will return an error.
422 func UserConfigDir() (string, error) {
423 var dir string
424
425 switch runtime.GOOS {
426 case "windows":
427 dir = Getenv("AppData")
428 if dir == "" {
429 return "", errors.New("%AppData% is not defined")
430 }
431
432 case "darwin":
433 dir = Getenv("HOME")
434 if dir == "" {
435 return "", errors.New("$HOME is not defined")
436 }
437 dir += "/Library/Application Support"
438
439 case "plan9":
440 dir = Getenv("home")
441 if dir == "" {
442 return "", errors.New("$home is not defined")
443 }
444 dir += "/lib"
445
446 default: // Unix
447 dir = Getenv("XDG_CONFIG_HOME")
448 if dir == "" {
449 dir = Getenv("HOME")
450 if dir == "" {
451 return "", errors.New("neither $XDG_CONFIG_HOME nor $HOME are defined")
452 }
453 dir += "/.config"
454 }
455 }
456
457 return dir, nil
458 }
459
460 // UserHomeDir returns the current user's home directory.
461 //
462 // On Unix, including macOS, it returns the $HOME environment variable.
463 // On Windows, it returns %USERPROFILE%.
464 // On Plan 9, it returns the $home environment variable.
465 func UserHomeDir() (string, error) {
466 env, enverr := "HOME", "$HOME"
467 switch runtime.GOOS {
468 case "windows":
469 env, enverr = "USERPROFILE", "%userprofile%"
470 case "plan9":
471 env, enverr = "home", "$home"
472 }
473 if v := Getenv(env); v != "" {
474 return v, nil
475 }
476 // On some geese the home directory is not always defined.
477 switch runtime.GOOS {
478 case "android":
479 return "/sdcard", nil
480 case "darwin":
481 if runtime.GOARCH == "arm" || runtime.GOARCH == "arm64" {
482 return "/", nil
483 }
484 }
485 return "", errors.New(enverr + " is not defined")
486 }
487
488 // Chmod changes the mode of the named file to mode.
489 // If the file is a symbolic link, it changes the mode of the link's target.
490 // If there is an error, it will be of type *PathError.
491 //
492 // A different subset of the mode bits are used, depending on the
493 // operating system.
494 //
495 // On Unix, the mode's permission bits, ModeSetuid, ModeSetgid, and
496 // ModeSticky are used.
497 //
498 // On Windows, only the 0200 bit (owner writable) of mode is used; it
499 // controls whether the file's read-only attribute is set or cleared.
500 // The other bits are currently unused. For compatibility with Go 1.12
501 // and earlier, use a non-zero mode. Use mode 0400 for a read-only
502 // file and 0600 for a readable+writable file.
503 //
504 // On Plan 9, the mode's permission bits, ModeAppend, ModeExclusive,
505 // and ModeTemporary are used.
506 func Chmod(name string, mode FileMode) error { return chmod(name, mode) }
507
508 // Chmod changes the mode of the file to mode.
509 // If there is an error, it will be of type *PathError.
510 func (f *File) Chmod(mode FileMode) error { return f.chmod(mode) }
511
512 // SetDeadline sets the read and write deadlines for a File.
513 // It is equivalent to calling both SetReadDeadline and SetWriteDeadline.
514 //
515 // Only some kinds of files support setting a deadline. Calls to SetDeadline
516 // for files that do not support deadlines will return ErrNoDeadline.
517 // On most systems ordinary files do not support deadlines, but pipes do.
518 //
519 // A deadline is an absolute time after which I/O operations fail with an
520 // error instead of blocking. The deadline applies to all future and pending
521 // I/O, not just the immediately following call to Read or Write.
522 // After a deadline has been exceeded, the connection can be refreshed
523 // by setting a deadline in the future.
524 //
525 // An error returned after a timeout fails will implement the
526 // Timeout method, and calling the Timeout method will return true.
527 // The PathError and SyscallError types implement the Timeout method.
528 // In general, call IsTimeout to test whether an error indicates a timeout.
529 //
530 // An idle timeout can be implemented by repeatedly extending
531 // the deadline after successful Read or Write calls.
532 //
533 // A zero value for t means I/O operations will not time out.
534 func (f *File) SetDeadline(t time.Time) error {
535 return f.setDeadline(t)
536 }
537
538 // SetReadDeadline sets the deadline for future Read calls and any
539 // currently-blocked Read call.
540 // A zero value for t means Read will not time out.
541 // Not all files support setting deadlines; see SetDeadline.
542 func (f *File) SetReadDeadline(t time.Time) error {
543 return f.setReadDeadline(t)
544 }
545
546 // SetWriteDeadline sets the deadline for any future Write calls and any
547 // currently-blocked Write call.
548 // Even if Write times out, it may return n > 0, indicating that
549 // some of the data was successfully written.
550 // A zero value for t means Write will not time out.
551 // Not all files support setting deadlines; see SetDeadline.
552 func (f *File) SetWriteDeadline(t time.Time) error {
553 return f.setWriteDeadline(t)
554 }
555
556 // SyscallConn returns a raw file.
557 // This implements the syscall.Conn interface.
558 func (f *File) SyscallConn() (syscall.RawConn, error) {
559 if err := f.checkValid("SyscallConn"); err != nil {
560 return nil, err
561 }
562 return newRawConn(f)
563 }
564
565 // isWindowsNulName reports whether name is os.DevNull ('NUL') on Windows.
566 // True is returned if name is 'NUL' whatever the case.
567 func isWindowsNulName(name string) bool {
568 if len(name) != 3 {
569 return false
570 }
571 if name[0] != 'n' && name[0] != 'N' {
572 return false
573 }
574 if name[1] != 'u' && name[1] != 'U' {
575 return false
576 }
577 if name[2] != 'l' && name[2] != 'L' {
578 return false
579 }
580 return true
581 }