File.cpp 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  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. return buffer.trim(nread);
  104. }
  105. ErrorOr<ByteBuffer> File::read_until_eof(size_t block_size)
  106. {
  107. // Note: This is used as a heuristic, it's not valid for devices or virtual files.
  108. auto const potential_file_size = TRY(System::fstat(m_fd)).st_size;
  109. return read_until_eof_impl(block_size, potential_file_size);
  110. }
  111. ErrorOr<size_t> File::write_some(ReadonlyBytes buffer)
  112. {
  113. if (!has_flag(m_mode, OpenMode::Write)) {
  114. // NOTE: Same deal as Read.
  115. return Error::from_errno(EBADF);
  116. }
  117. return TRY(System::write(m_fd, buffer));
  118. }
  119. bool File::is_eof() const { return m_last_read_was_eof; }
  120. bool File::is_open() const { return m_fd >= 0; }
  121. void File::close()
  122. {
  123. if (!is_open()) {
  124. return;
  125. }
  126. // NOTE: The closing of the file can be interrupted by a signal, in which
  127. // case EINTR will be returned by the close syscall. So let's try closing
  128. // the file until we aren't interrupted by rude signals. :^)
  129. ErrorOr<void> result;
  130. do {
  131. result = System::close(m_fd);
  132. } while (result.is_error() && result.error().code() == EINTR);
  133. VERIFY(!result.is_error());
  134. m_fd = -1;
  135. }
  136. ErrorOr<size_t> File::seek(i64 offset, SeekMode mode)
  137. {
  138. int syscall_mode;
  139. switch (mode) {
  140. case SeekMode::SetPosition:
  141. syscall_mode = SEEK_SET;
  142. break;
  143. case SeekMode::FromCurrentPosition:
  144. syscall_mode = SEEK_CUR;
  145. break;
  146. case SeekMode::FromEndPosition:
  147. syscall_mode = SEEK_END;
  148. break;
  149. default:
  150. VERIFY_NOT_REACHED();
  151. }
  152. size_t seek_result = TRY(System::lseek(m_fd, offset, syscall_mode));
  153. m_last_read_was_eof = false;
  154. return seek_result;
  155. }
  156. ErrorOr<void> File::truncate(size_t length)
  157. {
  158. if (length > static_cast<size_t>(NumericLimits<off_t>::max()))
  159. return Error::from_string_literal("Length is larger than the maximum supported length");
  160. return System::ftruncate(m_fd, length);
  161. }
  162. ErrorOr<void> File::set_blocking(bool enabled)
  163. {
  164. // 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.
  165. // Therefore, this method shouldn't be used in Lagom.
  166. // https://github.com/SerenityOS/serenity/pull/18965#discussion_r1207951840
  167. int value = enabled ? 0 : 1;
  168. return System::ioctl(fd(), FIONBIO, &value);
  169. }
  170. }