FileWatcherMacOS.mm 9.5 KB

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