FileWatcherMacOS.mm 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. /*
  2. * Copyright (c) 2023, Tim Flynn <trflynn89@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "FileWatcher.h"
  7. #include <AK/Debug.h>
  8. #include <AK/LexicalPath.h>
  9. #include <AK/OwnPtr.h>
  10. #include <LibCore/EventLoop.h>
  11. #include <LibCore/Notifier.h>
  12. #include <LibCore/System.h>
  13. #include <errno.h>
  14. #include <limits.h>
  15. #if !defined(AK_OS_MACOS)
  16. static_assert(false, "This file must only be used for macOS");
  17. #endif
  18. #import <CoreServices/CoreServices.h>
  19. #import <dispatch/dispatch.h>
  20. namespace Core {
  21. struct MonitoredPath {
  22. ByteString path;
  23. FileWatcherEvent::Type event_mask { FileWatcherEvent::Type::Invalid };
  24. };
  25. static void on_file_system_event(ConstFSEventStreamRef, void*, size_t, void*, FSEventStreamEventFlags const[], FSEventStreamEventId const[]);
  26. static ErrorOr<ino_t> inode_id_from_path(StringView path)
  27. {
  28. auto stat = TRY(System::stat(path));
  29. return stat.st_ino;
  30. }
  31. class FileWatcherMacOS final : public FileWatcher {
  32. AK_MAKE_NONCOPYABLE(FileWatcherMacOS);
  33. public:
  34. virtual ~FileWatcherMacOS() override
  35. {
  36. close_event_stream();
  37. dispatch_release(m_dispatch_queue);
  38. }
  39. static ErrorOr<NonnullRefPtr<FileWatcherMacOS>> create(FileWatcherFlags)
  40. {
  41. auto context = TRY(try_make<FSEventStreamContext>());
  42. auto queue_name = ByteString::formatted("Serenity.FileWatcher.{:p}", context.ptr());
  43. auto dispatch_queue = dispatch_queue_create(queue_name.characters(), DISPATCH_QUEUE_SERIAL);
  44. if (dispatch_queue == nullptr)
  45. return Error::from_errno(errno);
  46. // NOTE: This isn't actually used on macOS, but is needed for FileWatcherBase.
  47. // Creating it with an FD of -1 will effectively disable the notifier.
  48. auto notifier = TRY(Notifier::try_create(-1, Notifier::Type::None));
  49. return adopt_nonnull_ref_or_enomem(new (nothrow) FileWatcherMacOS(move(context), dispatch_queue, move(notifier)));
  50. }
  51. ErrorOr<bool> add_watch(ByteString path, FileWatcherEvent::Type event_mask)
  52. {
  53. if (m_path_to_inode_id.contains(path)) {
  54. dbgln_if(FILE_WATCHER_DEBUG, "add_watch: path '{}' is already being watched", path);
  55. return false;
  56. }
  57. auto inode_id = TRY(inode_id_from_path(path));
  58. TRY(m_path_to_inode_id.try_set(path, inode_id));
  59. TRY(m_inode_id_to_path.try_set(inode_id, { path, event_mask }));
  60. TRY(refresh_monitored_paths());
  61. dbgln_if(FILE_WATCHER_DEBUG, "add_watch: watching path '{}' inode {}", path, inode_id);
  62. return true;
  63. }
  64. ErrorOr<bool> remove_watch(ByteString path)
  65. {
  66. auto it = m_path_to_inode_id.find(path);
  67. if (it == m_path_to_inode_id.end()) {
  68. dbgln_if(FILE_WATCHER_DEBUG, "remove_watch: path '{}' is not being watched", path);
  69. return false;
  70. }
  71. m_inode_id_to_path.remove(it->value);
  72. m_path_to_inode_id.remove(it);
  73. TRY(refresh_monitored_paths());
  74. dbgln_if(FILE_WATCHER_DEBUG, "remove_watch: stopped watching path '{}'", path);
  75. return true;
  76. }
  77. ErrorOr<MonitoredPath> canonicalize_path(ByteString path)
  78. {
  79. LexicalPath lexical_path { move(path) };
  80. auto parent_path = lexical_path.parent();
  81. auto inode_id = TRY(inode_id_from_path(parent_path.string()));
  82. auto it = m_inode_id_to_path.find(inode_id);
  83. if (it == m_inode_id_to_path.end())
  84. return Error::from_string_literal("Got an event for a non-existent inode ID");
  85. return MonitoredPath {
  86. LexicalPath::join(it->value.path, lexical_path.basename()).string(),
  87. it->value.event_mask
  88. };
  89. }
  90. void handle_event(FileWatcherEvent event)
  91. {
  92. NonnullRefPtr strong_this { *this };
  93. m_main_event_loop.deferred_invoke(
  94. [strong_this = move(strong_this), event = move(event)]() {
  95. strong_this->on_change(event);
  96. });
  97. }
  98. private:
  99. FileWatcherMacOS(NonnullOwnPtr<FSEventStreamContext> context, dispatch_queue_t dispatch_queue, NonnullRefPtr<Notifier> notifier)
  100. : FileWatcher(-1, move(notifier))
  101. , m_main_event_loop(EventLoop::current())
  102. , m_context(move(context))
  103. , m_dispatch_queue(dispatch_queue)
  104. {
  105. m_context->info = this;
  106. }
  107. void close_event_stream()
  108. {
  109. if (!m_stream)
  110. return;
  111. dispatch_sync(m_dispatch_queue, ^{
  112. FSEventStreamStop(m_stream);
  113. FSEventStreamInvalidate(m_stream);
  114. FSEventStreamRelease(m_stream);
  115. m_stream = nullptr;
  116. });
  117. }
  118. ErrorOr<void> refresh_monitored_paths()
  119. {
  120. static constexpr FSEventStreamCreateFlags stream_flags = kFSEventStreamCreateFlagFileEvents | kFSEventStreamCreateFlagUseCFTypes | kFSEventStreamCreateFlagUseExtendedData;
  121. static constexpr CFAbsoluteTime stream_latency = 0.25;
  122. close_event_stream();
  123. if (m_path_to_inode_id.is_empty())
  124. return {};
  125. auto monitored_paths = CFArrayCreateMutable(kCFAllocatorDefault, m_path_to_inode_id.size(), &kCFTypeArrayCallBacks);
  126. if (monitored_paths == nullptr)
  127. return Error::from_errno(ENOMEM);
  128. for (auto it : m_path_to_inode_id) {
  129. auto path = CFStringCreateWithCString(kCFAllocatorDefault, it.key.characters(), kCFStringEncodingUTF8);
  130. if (path == nullptr)
  131. return Error::from_errno(ENOMEM);
  132. CFArrayAppendValue(monitored_paths, static_cast<void const*>(path));
  133. }
  134. dispatch_sync(m_dispatch_queue, ^{
  135. m_stream = FSEventStreamCreate(
  136. kCFAllocatorDefault,
  137. &on_file_system_event,
  138. m_context.ptr(),
  139. monitored_paths,
  140. kFSEventStreamEventIdSinceNow,
  141. stream_latency,
  142. stream_flags);
  143. if (m_stream) {
  144. FSEventStreamSetDispatchQueue(m_stream, m_dispatch_queue);
  145. FSEventStreamStart(m_stream);
  146. }
  147. });
  148. if (!m_stream)
  149. return Error::from_string_literal("Could not create an FSEventStream");
  150. return {};
  151. }
  152. EventLoop& m_main_event_loop;
  153. NonnullOwnPtr<FSEventStreamContext> m_context;
  154. dispatch_queue_t m_dispatch_queue { nullptr };
  155. FSEventStreamRef m_stream { nullptr };
  156. HashMap<ByteString, ino_t> m_path_to_inode_id;
  157. HashMap<ino_t, MonitoredPath> m_inode_id_to_path;
  158. };
  159. void on_file_system_event(ConstFSEventStreamRef, void* user_data, size_t event_size, void* event_paths, FSEventStreamEventFlags const event_flags[], FSEventStreamEventId const[])
  160. {
  161. auto& file_watcher = *reinterpret_cast<FileWatcherMacOS*>(user_data);
  162. auto paths = reinterpret_cast<CFArrayRef>(event_paths);
  163. for (size_t i = 0; i < event_size; ++i) {
  164. auto path_dictionary = static_cast<CFDictionaryRef>(CFArrayGetValueAtIndex(paths, static_cast<CFIndex>(i)));
  165. auto path = static_cast<CFStringRef>(CFDictionaryGetValue(path_dictionary, kFSEventStreamEventExtendedDataPathKey));
  166. char file_path_buffer[PATH_MAX] {};
  167. if (!CFStringGetFileSystemRepresentation(path, file_path_buffer, sizeof(file_path_buffer))) {
  168. dbgln_if(FILE_WATCHER_DEBUG, "Could not convert event to a file path");
  169. continue;
  170. }
  171. auto maybe_monitored_path = file_watcher.canonicalize_path(ByteString { file_path_buffer });
  172. if (maybe_monitored_path.is_error()) {
  173. dbgln_if(FILE_WATCHER_DEBUG, "Could not canonicalize path {}: {}", file_path_buffer, maybe_monitored_path.error());
  174. continue;
  175. }
  176. auto monitored_path = maybe_monitored_path.release_value();
  177. FileWatcherEvent event;
  178. event.event_path = move(monitored_path.path);
  179. auto flags = event_flags[i];
  180. if ((flags & kFSEventStreamEventFlagItemCreated) != 0)
  181. event.type |= FileWatcherEvent::Type::ChildCreated;
  182. if ((flags & kFSEventStreamEventFlagItemRemoved) != 0)
  183. event.type |= FileWatcherEvent::Type::ChildDeleted;
  184. if ((flags & kFSEventStreamEventFlagItemModified) != 0)
  185. event.type |= FileWatcherEvent::Type::ContentModified;
  186. if ((flags & kFSEventStreamEventFlagItemInodeMetaMod) != 0)
  187. event.type |= FileWatcherEvent::Type::MetadataModified;
  188. if (event.type == FileWatcherEvent::Type::Invalid) {
  189. dbgln_if(FILE_WATCHER_DEBUG, "Unknown event type {:x} returned by the FS event for {}", flags, path);
  190. continue;
  191. }
  192. if ((event.type & monitored_path.event_mask) == FileWatcherEvent::Type::Invalid) {
  193. dbgln_if(FILE_WATCHER_DEBUG, "Dropping unwanted FS event {} for {}", flags, path);
  194. continue;
  195. }
  196. file_watcher.handle_event(move(event));
  197. }
  198. }
  199. ErrorOr<NonnullRefPtr<FileWatcher>> FileWatcher::create(FileWatcherFlags flags)
  200. {
  201. return TRY(FileWatcherMacOS::create(flags));
  202. }
  203. FileWatcher::FileWatcher(int watcher_fd, NonnullRefPtr<Notifier> notifier)
  204. : FileWatcherBase(watcher_fd)
  205. , m_notifier(move(notifier))
  206. {
  207. }
  208. FileWatcher::~FileWatcher() = default;
  209. ErrorOr<bool> FileWatcherBase::add_watch(ByteString path, FileWatcherEvent::Type event_mask)
  210. {
  211. auto& file_watcher = verify_cast<FileWatcherMacOS>(*this);
  212. return file_watcher.add_watch(move(path), event_mask);
  213. }
  214. ErrorOr<bool> FileWatcherBase::remove_watch(ByteString path)
  215. {
  216. auto& file_watcher = verify_cast<FileWatcherMacOS>(*this);
  217. return file_watcher.remove_watch(move(path));
  218. }
  219. }