File.cpp 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. /*
  2. * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021, sin-ack <sin-ack@protonmail.com>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <LibCore/File.h>
  8. #include <LibCore/System.h>
  9. #include <fcntl.h>
  10. #include <unistd.h>
  11. namespace Core {
  12. ErrorOr<NonnullOwnPtr<File>> File::open(StringView filename, OpenMode mode, mode_t permissions)
  13. {
  14. auto file = TRY(adopt_nonnull_own_or_enomem(new (nothrow) File(mode)));
  15. TRY(file->open_path(filename, permissions));
  16. return file;
  17. }
  18. ErrorOr<NonnullOwnPtr<File>> File::adopt_fd(int fd, OpenMode mode, ShouldCloseFileDescriptor should_close_file_descriptor)
  19. {
  20. if (fd < 0) {
  21. return Error::from_errno(EBADF);
  22. }
  23. if (!has_any_flag(mode, OpenMode::ReadWrite)) {
  24. dbgln("Core::File::adopt_fd: Attempting to adopt a file with neither Read nor Write specified in mode");
  25. return Error::from_errno(EINVAL);
  26. }
  27. auto file = TRY(adopt_nonnull_own_or_enomem(new (nothrow) File(mode, should_close_file_descriptor)));
  28. file->m_fd = fd;
  29. return file;
  30. }
  31. ErrorOr<NonnullOwnPtr<File>> File::standard_input()
  32. {
  33. return File::adopt_fd(STDIN_FILENO, OpenMode::Read, ShouldCloseFileDescriptor::No);
  34. }
  35. ErrorOr<NonnullOwnPtr<File>> File::standard_output()
  36. {
  37. return File::adopt_fd(STDOUT_FILENO, OpenMode::Write, ShouldCloseFileDescriptor::No);
  38. }
  39. ErrorOr<NonnullOwnPtr<File>> File::standard_error()
  40. {
  41. return File::adopt_fd(STDERR_FILENO, OpenMode::Write, ShouldCloseFileDescriptor::No);
  42. }
  43. ErrorOr<NonnullOwnPtr<File>> File::open_file_or_standard_stream(StringView filename, OpenMode mode)
  44. {
  45. if (!filename.is_empty() && filename != "-"sv)
  46. return File::open(filename, mode);
  47. switch (mode) {
  48. case OpenMode::Read:
  49. return standard_input();
  50. case OpenMode::Write:
  51. return standard_output();
  52. default:
  53. VERIFY_NOT_REACHED();
  54. }
  55. }
  56. int File::open_mode_to_options(OpenMode mode)
  57. {
  58. int flags = 0;
  59. if (has_flag(mode, OpenMode::ReadWrite)) {
  60. flags |= O_RDWR | O_CREAT;
  61. } else if (has_flag(mode, OpenMode::Read)) {
  62. flags |= O_RDONLY;
  63. } else if (has_flag(mode, OpenMode::Write)) {
  64. flags |= O_WRONLY | O_CREAT;
  65. bool should_truncate = !has_any_flag(mode, OpenMode::Append | OpenMode::MustBeNew);
  66. if (should_truncate)
  67. flags |= O_TRUNC;
  68. }
  69. if (has_flag(mode, OpenMode::Append))
  70. flags |= O_APPEND;
  71. if (has_flag(mode, OpenMode::Truncate))
  72. flags |= O_TRUNC;
  73. if (has_flag(mode, OpenMode::MustBeNew))
  74. flags |= O_EXCL;
  75. if (!has_flag(mode, OpenMode::KeepOnExec))
  76. flags |= O_CLOEXEC;
  77. if (has_flag(mode, OpenMode::Nonblocking))
  78. flags |= O_NONBLOCK;
  79. // Some open modes, like `ReadWrite` imply the ability to create the file if it doesn't exist.
  80. // Certain applications may not want this privledge, and for compability reasons, this is
  81. // the easiest way to add this option.
  82. if (has_flag(mode, OpenMode::DontCreate))
  83. flags &= ~O_CREAT;
  84. return flags;
  85. }
  86. ErrorOr<void> File::open_path(StringView filename, mode_t permissions)
  87. {
  88. VERIFY(m_fd == -1);
  89. auto flags = open_mode_to_options(m_mode);
  90. m_fd = TRY(System::open(filename, flags, permissions));
  91. return {};
  92. }
  93. ErrorOr<Bytes> File::read_some(Bytes buffer)
  94. {
  95. if (!has_flag(m_mode, OpenMode::Read)) {
  96. // NOTE: POSIX says that if the fd is not open for reading, the call
  97. // will return EBADF. Since we already know whether we can or
  98. // can't read the file, let's avoid a syscall.
  99. return Error::from_errno(EBADF);
  100. }
  101. ssize_t nread = TRY(System::read(m_fd, buffer));
  102. m_last_read_was_eof = nread == 0;
  103. m_file_offset += nread;
  104. return buffer.trim(nread);
  105. }
  106. ErrorOr<ByteBuffer> File::read_until_eof(size_t block_size)
  107. {
  108. // Note: This is used as a heuristic, it's not valid for devices or virtual files.
  109. auto const potential_file_size = TRY(System::fstat(m_fd)).st_size;
  110. return read_until_eof_impl(block_size, potential_file_size);
  111. }
  112. ErrorOr<size_t> File::write_some(ReadonlyBytes buffer)
  113. {
  114. if (!has_flag(m_mode, OpenMode::Write)) {
  115. // NOTE: Same deal as Read.
  116. return Error::from_errno(EBADF);
  117. }
  118. auto nwritten = TRY(System::write(m_fd, buffer));
  119. m_file_offset += nwritten;
  120. return nwritten;
  121. }
  122. bool File::is_eof() const { return m_last_read_was_eof; }
  123. bool File::is_open() const { return m_fd >= 0; }
  124. void File::close()
  125. {
  126. if (!is_open()) {
  127. return;
  128. }
  129. // NOTE: The closing of the file can be interrupted by a signal, in which
  130. // case EINTR will be returned by the close syscall. So let's try closing
  131. // the file until we aren't interrupted by rude signals. :^)
  132. ErrorOr<void> result;
  133. do {
  134. result = System::close(m_fd);
  135. } while (result.is_error() && result.error().code() == EINTR);
  136. VERIFY(!result.is_error());
  137. m_fd = -1;
  138. }
  139. ErrorOr<size_t> File::seek(i64 offset, SeekMode mode)
  140. {
  141. int syscall_mode;
  142. switch (mode) {
  143. case SeekMode::SetPosition:
  144. syscall_mode = SEEK_SET;
  145. break;
  146. case SeekMode::FromCurrentPosition:
  147. syscall_mode = SEEK_CUR;
  148. break;
  149. case SeekMode::FromEndPosition:
  150. syscall_mode = SEEK_END;
  151. break;
  152. default:
  153. VERIFY_NOT_REACHED();
  154. }
  155. size_t seek_result = TRY(System::lseek(m_fd, offset, syscall_mode));
  156. m_file_offset = seek_result;
  157. m_last_read_was_eof = false;
  158. return seek_result;
  159. }
  160. ErrorOr<size_t> File::tell() const
  161. {
  162. return m_file_offset;
  163. }
  164. ErrorOr<void> File::truncate(size_t length)
  165. {
  166. if (length > static_cast<size_t>(NumericLimits<off_t>::max()))
  167. return Error::from_string_literal("Length is larger than the maximum supported length");
  168. m_file_offset = min(length, m_file_offset);
  169. return System::ftruncate(m_fd, length);
  170. }
  171. ErrorOr<void> File::set_blocking(bool enabled)
  172. {
  173. // NOTE: This works fine on Serenity, but some systems out there don't support changing the blocking state of certain POSIX objects (message queues, pipes, etc) after their creation.
  174. // Therefore, this method shouldn't be used in Lagom.
  175. // https://github.com/SerenityOS/serenity/pull/18965#discussion_r1207951840
  176. int value = enabled ? 0 : 1;
  177. return System::ioctl(fd(), FIONBIO, &value);
  178. }
  179. }