file_unix.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  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. // +build darwin dragonfly freebsd linux nacl netbsd openbsd solaris
  5. package os
  6. import (
  7. "runtime"
  8. "sync/atomic"
  9. "syscall"
  10. )
  11. // File represents an open file descriptor.
  12. type File struct {
  13. *file
  14. }
  15. // file is the real representation of *File.
  16. // The extra level of indirection ensures that no clients of os
  17. // can overwrite this data, which could cause the finalizer
  18. // to close the wrong file descriptor.
  19. type file struct {
  20. fd int
  21. name string
  22. dirinfo *dirInfo // nil unless directory being read
  23. nepipe int32 // number of consecutive EPIPE in Write
  24. }
  25. // Fd returns the integer Unix file descriptor referencing the open file.
  26. // The file descriptor is valid only until f.Close is called or f is garbage collected.
  27. func (f *File) Fd() uintptr {
  28. if f == nil {
  29. return ^(uintptr(0))
  30. }
  31. return uintptr(f.fd)
  32. }
  33. // NewFile returns a new File with the given file descriptor and name.
  34. func NewFile(fd uintptr, name string) *File {
  35. fdi := int(fd)
  36. if fdi < 0 {
  37. return nil
  38. }
  39. f := &File{&file{fd: fdi, name: name}}
  40. runtime.SetFinalizer(f.file, (*file).close)
  41. return f
  42. }
  43. // Auxiliary information if the File describes a directory
  44. type dirInfo struct {
  45. buf []byte // buffer for directory I/O
  46. dir *syscall.DIR // from opendir
  47. }
  48. func epipecheck(file *File, e error) {
  49. if e == syscall.EPIPE {
  50. if atomic.AddInt32(&file.nepipe, 1) >= 10 {
  51. sigpipe()
  52. }
  53. } else {
  54. atomic.StoreInt32(&file.nepipe, 0)
  55. }
  56. }
  57. // DevNull is the name of the operating system's ``null device.''
  58. // On Unix-like systems, it is "/dev/null"; on Windows, "NUL".
  59. const DevNull = "/dev/null"
  60. // OpenFile is the generalized open call; most users will use Open
  61. // or Create instead. It opens the named file with specified flag
  62. // (O_RDONLY etc.) and perm, (0666 etc.) if applicable. If successful,
  63. // methods on the returned File can be used for I/O.
  64. // If there is an error, it will be of type *PathError.
  65. func OpenFile(name string, flag int, perm FileMode) (file *File, err error) {
  66. r, e := syscall.Open(name, flag|syscall.O_CLOEXEC, syscallMode(perm))
  67. if e != nil {
  68. return nil, &PathError{"open", name, e}
  69. }
  70. // There's a race here with fork/exec, which we are
  71. // content to live with. See ../syscall/exec_unix.go.
  72. if !supportsCloseOnExec {
  73. syscall.CloseOnExec(r)
  74. }
  75. return NewFile(uintptr(r), name), nil
  76. }
  77. // Close closes the File, rendering it unusable for I/O.
  78. // It returns an error, if any.
  79. func (f *File) Close() error {
  80. if f == nil {
  81. return ErrInvalid
  82. }
  83. return f.file.close()
  84. }
  85. func (file *file) close() error {
  86. if file == nil || file.fd < 0 {
  87. return syscall.EINVAL
  88. }
  89. var err error
  90. if e := syscall.Close(file.fd); e != nil {
  91. err = &PathError{"close", file.name, e}
  92. }
  93. if file.dirinfo != nil {
  94. syscall.Entersyscall()
  95. i := libc_closedir(file.dirinfo.dir)
  96. errno := syscall.GetErrno()
  97. syscall.Exitsyscall()
  98. file.dirinfo = nil
  99. if i < 0 && err == nil {
  100. err = &PathError{"closedir", file.name, errno}
  101. }
  102. }
  103. file.fd = -1 // so it can't be closed again
  104. // no need for a finalizer anymore
  105. runtime.SetFinalizer(file, nil)
  106. return err
  107. }
  108. // Stat returns the FileInfo structure describing file.
  109. // If there is an error, it will be of type *PathError.
  110. func (f *File) Stat() (fi FileInfo, err error) {
  111. if f == nil {
  112. return nil, ErrInvalid
  113. }
  114. var stat syscall.Stat_t
  115. err = syscall.Fstat(f.fd, &stat)
  116. if err != nil {
  117. return nil, &PathError{"stat", f.name, err}
  118. }
  119. return fileInfoFromStat(&stat, f.name), nil
  120. }
  121. // Stat returns a FileInfo describing the named file.
  122. // If there is an error, it will be of type *PathError.
  123. func Stat(name string) (fi FileInfo, err error) {
  124. var stat syscall.Stat_t
  125. err = syscall.Stat(name, &stat)
  126. if err != nil {
  127. return nil, &PathError{"stat", name, err}
  128. }
  129. return fileInfoFromStat(&stat, name), nil
  130. }
  131. // Lstat returns a FileInfo describing the named file.
  132. // If the file is a symbolic link, the returned FileInfo
  133. // describes the symbolic link. Lstat makes no attempt to follow the link.
  134. // If there is an error, it will be of type *PathError.
  135. func Lstat(name string) (fi FileInfo, err error) {
  136. var stat syscall.Stat_t
  137. err = syscall.Lstat(name, &stat)
  138. if err != nil {
  139. return nil, &PathError{"lstat", name, err}
  140. }
  141. return fileInfoFromStat(&stat, name), nil
  142. }
  143. func (f *File) readdir(n int) (fi []FileInfo, err error) {
  144. dirname := f.name
  145. if dirname == "" {
  146. dirname = "."
  147. }
  148. names, err := f.Readdirnames(n)
  149. fi = make([]FileInfo, 0, len(names))
  150. for _, filename := range names {
  151. fip, lerr := lstat(dirname + "/" + filename)
  152. if IsNotExist(lerr) {
  153. // File disappeared between readdir + stat.
  154. // Just treat it as if it didn't exist.
  155. continue
  156. }
  157. if lerr != nil {
  158. return fi, lerr
  159. }
  160. fi = append(fi, fip)
  161. }
  162. return fi, err
  163. }
  164. // Darwin and FreeBSD can't read or write 2GB+ at a time,
  165. // even on 64-bit systems. See golang.org/issue/7812.
  166. // Use 1GB instead of, say, 2GB-1, to keep subsequent
  167. // reads aligned.
  168. const (
  169. needsMaxRW = runtime.GOOS == "darwin" || runtime.GOOS == "freebsd"
  170. maxRW = 1 << 30
  171. )
  172. // read reads up to len(b) bytes from the File.
  173. // It returns the number of bytes read and an error, if any.
  174. func (f *File) read(b []byte) (n int, err error) {
  175. if needsMaxRW && len(b) > maxRW {
  176. b = b[:maxRW]
  177. }
  178. return fixCount(syscall.Read(f.fd, b))
  179. }
  180. // pread reads len(b) bytes from the File starting at byte offset off.
  181. // It returns the number of bytes read and the error, if any.
  182. // EOF is signaled by a zero count with err set to nil.
  183. func (f *File) pread(b []byte, off int64) (n int, err error) {
  184. if needsMaxRW && len(b) > maxRW {
  185. b = b[:maxRW]
  186. }
  187. return fixCount(syscall.Pread(f.fd, b, off))
  188. }
  189. // write writes len(b) bytes to the File.
  190. // It returns the number of bytes written and an error, if any.
  191. func (f *File) write(b []byte) (n int, err error) {
  192. for {
  193. bcap := b
  194. if needsMaxRW && len(bcap) > maxRW {
  195. bcap = bcap[:maxRW]
  196. }
  197. m, err := fixCount(syscall.Write(f.fd, bcap))
  198. n += m
  199. // If the syscall wrote some data but not all (short write)
  200. // or it returned EINTR, then assume it stopped early for
  201. // reasons that are uninteresting to the caller, and try again.
  202. if 0 < m && m < len(bcap) || err == syscall.EINTR {
  203. b = b[m:]
  204. continue
  205. }
  206. if needsMaxRW && len(bcap) != len(b) && err == nil {
  207. b = b[m:]
  208. continue
  209. }
  210. return n, err
  211. }
  212. }
  213. // pwrite writes len(b) bytes to the File starting at byte offset off.
  214. // It returns the number of bytes written and an error, if any.
  215. func (f *File) pwrite(b []byte, off int64) (n int, err error) {
  216. if needsMaxRW && len(b) > maxRW {
  217. b = b[:maxRW]
  218. }
  219. return fixCount(syscall.Pwrite(f.fd, b, off))
  220. }
  221. // seek sets the offset for the next Read or Write on file to offset, interpreted
  222. // according to whence: 0 means relative to the origin of the file, 1 means
  223. // relative to the current offset, and 2 means relative to the end.
  224. // It returns the new offset and an error, if any.
  225. func (f *File) seek(offset int64, whence int) (ret int64, err error) {
  226. return syscall.Seek(f.fd, offset, whence)
  227. }
  228. // Truncate changes the size of the named file.
  229. // If the file is a symbolic link, it changes the size of the link's target.
  230. // If there is an error, it will be of type *PathError.
  231. func Truncate(name string, size int64) error {
  232. if e := syscall.Truncate(name, size); e != nil {
  233. return &PathError{"truncate", name, e}
  234. }
  235. return nil
  236. }
  237. // Remove removes the named file or directory.
  238. // If there is an error, it will be of type *PathError.
  239. func Remove(name string) error {
  240. // System call interface forces us to know
  241. // whether name is a file or directory.
  242. // Try both: it is cheaper on average than
  243. // doing a Stat plus the right one.
  244. e := syscall.Unlink(name)
  245. if e == nil {
  246. return nil
  247. }
  248. e1 := syscall.Rmdir(name)
  249. if e1 == nil {
  250. return nil
  251. }
  252. // Both failed: figure out which error to return.
  253. // OS X and Linux differ on whether unlink(dir)
  254. // returns EISDIR, so can't use that. However,
  255. // both agree that rmdir(file) returns ENOTDIR,
  256. // so we can use that to decide which error is real.
  257. // Rmdir might also return ENOTDIR if given a bad
  258. // file path, like /etc/passwd/foo, but in that case,
  259. // both errors will be ENOTDIR, so it's okay to
  260. // use the error from unlink.
  261. if e1 != syscall.ENOTDIR {
  262. e = e1
  263. }
  264. return &PathError{"remove", name, e}
  265. }
  266. // basename removes trailing slashes and the leading directory name from path name
  267. func basename(name string) string {
  268. i := len(name) - 1
  269. // Remove trailing slashes
  270. for ; i > 0 && name[i] == '/'; i-- {
  271. name = name[:i]
  272. }
  273. // Remove leading directory name
  274. for i--; i >= 0; i-- {
  275. if name[i] == '/' {
  276. name = name[i+1:]
  277. break
  278. }
  279. }
  280. return name
  281. }
  282. // TempDir returns the default directory to use for temporary files.
  283. func TempDir() string {
  284. dir := Getenv("TMPDIR")
  285. if dir == "" {
  286. if runtime.GOOS == "android" {
  287. dir = "/data/local/tmp"
  288. } else {
  289. dir = "/tmp"
  290. }
  291. }
  292. return dir
  293. }
  294. // Link creates newname as a hard link to the oldname file.
  295. // If there is an error, it will be of type *LinkError.
  296. func Link(oldname, newname string) error {
  297. e := syscall.Link(oldname, newname)
  298. if e != nil {
  299. return &LinkError{"link", oldname, newname, e}
  300. }
  301. return nil
  302. }
  303. // Symlink creates newname as a symbolic link to oldname.
  304. // If there is an error, it will be of type *LinkError.
  305. func Symlink(oldname, newname string) error {
  306. e := syscall.Symlink(oldname, newname)
  307. if e != nil {
  308. return &LinkError{"symlink", oldname, newname, e}
  309. }
  310. return nil
  311. }