Debian Codegraph @

libgo/go/os/file_unix.go

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