File.h 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /*
  2. * Copyright (c) 2020, Sergey Bugaev <bugaevc@serenityos.org>
  3. * Copyright (c) 2021, Andreas Kling <kling@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #pragma once
  8. #include <AK/Noncopyable.h>
  9. #include <AK/StdLibExtras.h>
  10. #include <LibCore/File.h>
  11. #include <unistd.h>
  12. namespace IPC {
  13. class File {
  14. AK_MAKE_NONCOPYABLE(File);
  15. public:
  16. // Must have a default constructor, because LibIPC
  17. // default-constructs arguments prior to decoding them.
  18. File() = default;
  19. // Intentionally not `explicit`.
  20. File(int fd)
  21. : m_fd(fd)
  22. {
  23. }
  24. // Tagged constructor for fd's that should be closed on destruction unless take_fd() is called.
  25. // Note that the tags are the same, this is intentional to allow expressive invocation.
  26. enum Tag {
  27. ConstructWithReceivedFileDescriptor = 1,
  28. CloseAfterSending = 1,
  29. };
  30. File(int fd, Tag)
  31. : m_fd(fd)
  32. , m_close_on_destruction(true)
  33. {
  34. }
  35. explicit File(Core::File& file)
  36. : File(file.leak_fd(Badge<File> {}), CloseAfterSending)
  37. {
  38. }
  39. File(File&& other)
  40. : m_fd(exchange(other.m_fd, -1))
  41. , m_close_on_destruction(exchange(other.m_close_on_destruction, false))
  42. {
  43. }
  44. File& operator=(File&& other)
  45. {
  46. if (this != &other) {
  47. m_fd = exchange(other.m_fd, -1);
  48. m_close_on_destruction = exchange(other.m_close_on_destruction, false);
  49. }
  50. return *this;
  51. }
  52. ~File()
  53. {
  54. if (m_close_on_destruction && m_fd != -1)
  55. close(m_fd);
  56. }
  57. int fd() const { return m_fd; }
  58. // NOTE: This is 'const' since generated IPC messages expose all parameters by const reference.
  59. [[nodiscard]] int take_fd() const
  60. {
  61. return exchange(m_fd, -1);
  62. }
  63. private:
  64. mutable int m_fd { -1 };
  65. bool m_close_on_destruction { false };
  66. };
  67. }