CEventLoop.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. #include <AK/JsonArray.h>
  2. #include <AK/JsonObject.h>
  3. #include <AK/JsonValue.h>
  4. #include <AK/Time.h>
  5. #include <LibCore/CEvent.h>
  6. #include <LibCore/CEventLoop.h>
  7. #include <LibCore/CLocalSocket.h>
  8. #include <LibCore/CNotifier.h>
  9. #include <LibCore/CObject.h>
  10. #include <LibCore/CSyscallUtils.h>
  11. #include <LibThread/Lock.h>
  12. #include <errno.h>
  13. #include <fcntl.h>
  14. #include <stdio.h>
  15. #include <stdlib.h>
  16. #include <string.h>
  17. #include <sys/select.h>
  18. #include <sys/socket.h>
  19. #include <sys/time.h>
  20. #include <time.h>
  21. #include <unistd.h>
  22. //#define CEVENTLOOP_DEBUG
  23. //#define DEFERRED_INVOKE_DEBUG
  24. static CEventLoop* s_main_event_loop;
  25. static Vector<CEventLoop*>* s_event_loop_stack;
  26. HashMap<int, NonnullOwnPtr<CEventLoop::EventLoopTimer>>* CEventLoop::s_timers;
  27. HashTable<CNotifier*>* CEventLoop::s_notifiers;
  28. int CEventLoop::s_next_timer_id = 1;
  29. int CEventLoop::s_wake_pipe_fds[2];
  30. RefPtr<CLocalServer> CEventLoop::s_rpc_server;
  31. class RPCClient : public CObject {
  32. C_OBJECT(RPCClient)
  33. public:
  34. explicit RPCClient(RefPtr<CLocalSocket> socket)
  35. : m_socket(move(socket))
  36. {
  37. add_child(*m_socket);
  38. m_socket->on_ready_to_read = [this] {
  39. i32 length;
  40. int nread = m_socket->read((u8*)&length, sizeof(length));
  41. if (nread == 0) {
  42. dbg() << "RPC client disconnected";
  43. shutdown();
  44. return;
  45. }
  46. ASSERT(nread == sizeof(length));
  47. auto request = m_socket->read(length);
  48. auto request_json = JsonValue::from_string(request);
  49. if (!request_json.is_object()) {
  50. dbg() << "RPC client sent invalid request";
  51. shutdown();
  52. return;
  53. }
  54. handle_request(request_json.as_object());
  55. };
  56. }
  57. virtual ~RPCClient() override
  58. {
  59. }
  60. void send_response(const JsonObject& response)
  61. {
  62. auto serialized = response.to_string();
  63. i32 length = serialized.length();
  64. m_socket->write((const u8*)&length, sizeof(length));
  65. m_socket->write(serialized);
  66. }
  67. void handle_request(const JsonObject& request)
  68. {
  69. auto type = request.get("type").as_string_or({});
  70. if (type.is_null()) {
  71. dbg() << "RPC client sent request without type field";
  72. return;
  73. }
  74. if (type == "Identify") {
  75. JsonObject response;
  76. response.set("type", type);
  77. response.set("pid", getpid());
  78. #ifdef __serenity__
  79. char buffer[1024];
  80. if (get_process_name(buffer, sizeof(buffer)) >= 0) {
  81. response.set("process_name", buffer);
  82. } else {
  83. response.set("process_name", JsonValue());
  84. }
  85. #endif
  86. send_response(response);
  87. return;
  88. }
  89. if (type == "GetAllObjects") {
  90. JsonObject response;
  91. response.set("type", type);
  92. JsonArray objects;
  93. for (auto& object : CObject::all_objects()) {
  94. JsonObject json_object;
  95. object.save_to(json_object);
  96. objects.append(move(json_object));
  97. }
  98. response.set("objects", move(objects));
  99. send_response(response);
  100. return;
  101. }
  102. if (type == "Disconnect") {
  103. shutdown();
  104. return;
  105. }
  106. }
  107. void shutdown()
  108. {
  109. // FIXME: This is quite a hackish way to clean ourselves up.
  110. delete this;
  111. }
  112. private:
  113. RefPtr<CLocalSocket> m_socket;
  114. };
  115. CEventLoop::CEventLoop()
  116. {
  117. if (!s_event_loop_stack) {
  118. s_event_loop_stack = new Vector<CEventLoop*>;
  119. s_timers = new HashMap<int, NonnullOwnPtr<CEventLoop::EventLoopTimer>>;
  120. s_notifiers = new HashTable<CNotifier*>;
  121. }
  122. if (!s_main_event_loop) {
  123. s_main_event_loop = this;
  124. #if defined(SOCK_NONBLOCK)
  125. int rc = pipe2(s_wake_pipe_fds, O_CLOEXEC);
  126. #else
  127. int rc = pipe(s_wake_pipe_fds);
  128. fcntl(s_wake_pipe_fds[0], F_SETFD, FD_CLOEXEC);
  129. fcntl(s_wake_pipe_fds[1], F_SETFD, FD_CLOEXEC);
  130. #endif
  131. ASSERT(rc == 0);
  132. s_event_loop_stack->append(this);
  133. auto rpc_path = String::format("/tmp/rpc.%d", getpid());
  134. rc = unlink(rpc_path.characters());
  135. if (rc < 0 && errno != ENOENT) {
  136. perror("unlink");
  137. ASSERT_NOT_REACHED();
  138. }
  139. s_rpc_server = CLocalServer::construct();
  140. s_rpc_server->set_name("CEventLoop_RPC_server");
  141. bool listening = s_rpc_server->listen(rpc_path);
  142. ASSERT(listening);
  143. s_rpc_server->on_ready_to_accept = [&] {
  144. auto client_socket = s_rpc_server->accept();
  145. ASSERT(client_socket);
  146. // NOTE: RPCClient will delete itself in RPCClient::shutdown().
  147. (void)RPCClient::construct(move(client_socket)).leak_ref();
  148. };
  149. }
  150. #ifdef CEVENTLOOP_DEBUG
  151. dbg() << getpid() << " CEventLoop constructed :)";
  152. #endif
  153. }
  154. CEventLoop::~CEventLoop()
  155. {
  156. }
  157. CEventLoop& CEventLoop::main()
  158. {
  159. ASSERT(s_main_event_loop);
  160. return *s_main_event_loop;
  161. }
  162. CEventLoop& CEventLoop::current()
  163. {
  164. CEventLoop* event_loop = s_event_loop_stack->last();
  165. ASSERT(event_loop != nullptr);
  166. return *event_loop;
  167. }
  168. void CEventLoop::quit(int code)
  169. {
  170. dbg() << "CEventLoop::quit(" << code << ")";
  171. m_exit_requested = true;
  172. m_exit_code = code;
  173. }
  174. void CEventLoop::unquit()
  175. {
  176. dbg() << "CEventLoop::unquit()";
  177. m_exit_requested = false;
  178. m_exit_code = 0;
  179. }
  180. struct CEventLoopPusher {
  181. public:
  182. CEventLoopPusher(CEventLoop& event_loop)
  183. : m_event_loop(event_loop)
  184. {
  185. if (&m_event_loop != s_main_event_loop) {
  186. m_event_loop.take_pending_events_from(CEventLoop::current());
  187. s_event_loop_stack->append(&event_loop);
  188. }
  189. }
  190. ~CEventLoopPusher()
  191. {
  192. if (&m_event_loop != s_main_event_loop) {
  193. s_event_loop_stack->take_last();
  194. CEventLoop::current().take_pending_events_from(m_event_loop);
  195. }
  196. }
  197. private:
  198. CEventLoop& m_event_loop;
  199. };
  200. int CEventLoop::exec()
  201. {
  202. CEventLoopPusher pusher(*this);
  203. for (;;) {
  204. if (m_exit_requested)
  205. return m_exit_code;
  206. pump();
  207. }
  208. ASSERT_NOT_REACHED();
  209. }
  210. void CEventLoop::pump(WaitMode mode)
  211. {
  212. if (m_queued_events.is_empty())
  213. wait_for_event(mode);
  214. decltype(m_queued_events) events;
  215. {
  216. LOCKER(m_lock);
  217. events = move(m_queued_events);
  218. }
  219. for (int i = 0; i < events.size(); ++i) {
  220. auto& queued_event = events.at(i);
  221. #ifndef __clang__
  222. ASSERT(queued_event.event);
  223. #endif
  224. auto* receiver = queued_event.receiver.ptr();
  225. auto& event = *queued_event.event;
  226. #ifdef CEVENTLOOP_DEBUG
  227. if (receiver)
  228. dbg() << "CEventLoop: " << *receiver << " event " << (int)event.type();
  229. #endif
  230. if (!receiver) {
  231. switch (event.type()) {
  232. case CEvent::Quit:
  233. ASSERT_NOT_REACHED();
  234. return;
  235. default:
  236. dbg() << "Event type " << event.type() << " with no receiver :(";
  237. }
  238. } else if (event.type() == CEvent::Type::DeferredInvoke) {
  239. #ifdef DEFERRED_INVOKE_DEBUG
  240. printf("DeferredInvoke: receiver=%s{%p}\n", receiver->class_name(), receiver);
  241. #endif
  242. static_cast<CDeferredInvocationEvent&>(event).m_invokee(*receiver);
  243. } else {
  244. NonnullRefPtr<CObject> protector(*receiver);
  245. receiver->dispatch_event(event);
  246. }
  247. if (m_exit_requested) {
  248. LOCKER(m_lock);
  249. #ifdef CEVENTLOOP_DEBUG
  250. dbg() << "CEventLoop: Exit requested. Rejigging " << (events.size() - i) << " events.";
  251. #endif
  252. decltype(m_queued_events) new_event_queue;
  253. new_event_queue.ensure_capacity(m_queued_events.size() + events.size());
  254. for (; i < events.size(); ++i)
  255. new_event_queue.unchecked_append(move(events[i]));
  256. new_event_queue.append(move(m_queued_events));
  257. m_queued_events = move(new_event_queue);
  258. return;
  259. }
  260. }
  261. }
  262. void CEventLoop::post_event(CObject& receiver, NonnullOwnPtr<CEvent>&& event)
  263. {
  264. LOCKER(m_lock);
  265. #ifdef CEVENTLOOP_DEBUG
  266. dbg() << "CEventLoop::post_event: {" << m_queued_events.size() << "} << receiver=" << receiver << ", event=" << event;
  267. #endif
  268. m_queued_events.append({ receiver.make_weak_ptr(), move(event) });
  269. }
  270. void CEventLoop::wait_for_event(WaitMode mode)
  271. {
  272. fd_set rfds;
  273. fd_set wfds;
  274. FD_ZERO(&rfds);
  275. FD_ZERO(&wfds);
  276. int max_fd = 0;
  277. auto add_fd_to_set = [&max_fd](int fd, fd_set& set) {
  278. FD_SET(fd, &set);
  279. if (fd > max_fd)
  280. max_fd = fd;
  281. };
  282. int max_fd_added = -1;
  283. add_fd_to_set(s_wake_pipe_fds[0], rfds);
  284. max_fd = max(max_fd, max_fd_added);
  285. for (auto& notifier : *s_notifiers) {
  286. if (notifier->event_mask() & CNotifier::Read)
  287. add_fd_to_set(notifier->fd(), rfds);
  288. if (notifier->event_mask() & CNotifier::Write)
  289. add_fd_to_set(notifier->fd(), wfds);
  290. if (notifier->event_mask() & CNotifier::Exceptional)
  291. ASSERT_NOT_REACHED();
  292. }
  293. bool queued_events_is_empty;
  294. {
  295. LOCKER(m_lock);
  296. queued_events_is_empty = m_queued_events.is_empty();
  297. }
  298. timeval now;
  299. struct timeval timeout = { 0, 0 };
  300. bool should_wait_forever = false;
  301. if (mode == WaitMode::WaitForEvents) {
  302. if (!s_timers->is_empty() && queued_events_is_empty) {
  303. gettimeofday(&now, nullptr);
  304. get_next_timer_expiration(timeout);
  305. timeval_sub(timeout, now, timeout);
  306. } else {
  307. should_wait_forever = true;
  308. }
  309. } else {
  310. should_wait_forever = false;
  311. }
  312. int marked_fd_count = CSyscallUtils::safe_syscall(select, max_fd + 1, &rfds, &wfds, nullptr, should_wait_forever ? nullptr : &timeout);
  313. if (FD_ISSET(s_wake_pipe_fds[0], &rfds)) {
  314. char buffer[32];
  315. auto nread = read(s_wake_pipe_fds[0], buffer, sizeof(buffer));
  316. if (nread < 0) {
  317. perror("read from wake pipe");
  318. ASSERT_NOT_REACHED();
  319. }
  320. ASSERT(nread > 0);
  321. }
  322. if (!s_timers->is_empty()) {
  323. gettimeofday(&now, nullptr);
  324. }
  325. for (auto& it : *s_timers) {
  326. auto& timer = *it.value;
  327. if (!timer.has_expired(now))
  328. continue;
  329. #ifdef CEVENTLOOP_DEBUG
  330. dbg() << "CEventLoop: Timer " << timer.timer_id << " has expired, sending CTimerEvent to " << timer.owner;
  331. #endif
  332. post_event(*timer.owner, make<CTimerEvent>(timer.timer_id));
  333. if (timer.should_reload) {
  334. timer.reload(now);
  335. } else {
  336. // FIXME: Support removing expired timers that don't want to reload.
  337. ASSERT_NOT_REACHED();
  338. }
  339. }
  340. if (!marked_fd_count)
  341. return;
  342. for (auto& notifier : *s_notifiers) {
  343. if (FD_ISSET(notifier->fd(), &rfds)) {
  344. if (notifier->on_ready_to_read)
  345. post_event(*notifier, make<CNotifierReadEvent>(notifier->fd()));
  346. }
  347. if (FD_ISSET(notifier->fd(), &wfds)) {
  348. if (notifier->on_ready_to_write)
  349. post_event(*notifier, make<CNotifierWriteEvent>(notifier->fd()));
  350. }
  351. }
  352. }
  353. bool CEventLoop::EventLoopTimer::has_expired(const timeval& now) const
  354. {
  355. return now.tv_sec > fire_time.tv_sec || (now.tv_sec == fire_time.tv_sec && now.tv_usec >= fire_time.tv_usec);
  356. }
  357. void CEventLoop::EventLoopTimer::reload(const timeval& now)
  358. {
  359. fire_time = now;
  360. fire_time.tv_sec += interval / 1000;
  361. fire_time.tv_usec += (interval % 1000) * 1000;
  362. }
  363. void CEventLoop::get_next_timer_expiration(timeval& soonest)
  364. {
  365. ASSERT(!s_timers->is_empty());
  366. bool has_checked_any = false;
  367. for (auto& it : *s_timers) {
  368. auto& fire_time = it.value->fire_time;
  369. if (!has_checked_any || fire_time.tv_sec < soonest.tv_sec || (fire_time.tv_sec == soonest.tv_sec && fire_time.tv_usec < soonest.tv_usec))
  370. soonest = fire_time;
  371. has_checked_any = true;
  372. }
  373. }
  374. int CEventLoop::register_timer(CObject& object, int milliseconds, bool should_reload)
  375. {
  376. ASSERT(milliseconds >= 0);
  377. auto timer = make<EventLoopTimer>();
  378. timer->owner = object.make_weak_ptr();
  379. timer->interval = milliseconds;
  380. timeval now;
  381. gettimeofday(&now, nullptr);
  382. timer->reload(now);
  383. timer->should_reload = should_reload;
  384. int timer_id = ++s_next_timer_id; // FIXME: This will eventually wrap around.
  385. ASSERT(timer_id); // FIXME: Aforementioned wraparound.
  386. timer->timer_id = timer_id;
  387. s_timers->set(timer_id, move(timer));
  388. return timer_id;
  389. }
  390. bool CEventLoop::unregister_timer(int timer_id)
  391. {
  392. auto it = s_timers->find(timer_id);
  393. if (it == s_timers->end())
  394. return false;
  395. s_timers->remove(it);
  396. return true;
  397. }
  398. void CEventLoop::register_notifier(Badge<CNotifier>, CNotifier& notifier)
  399. {
  400. s_notifiers->set(&notifier);
  401. }
  402. void CEventLoop::unregister_notifier(Badge<CNotifier>, CNotifier& notifier)
  403. {
  404. s_notifiers->remove(&notifier);
  405. }
  406. void CEventLoop::wake()
  407. {
  408. char ch = '!';
  409. int nwritten = write(s_wake_pipe_fds[1], &ch, 1);
  410. if (nwritten < 0) {
  411. perror("CEventLoop::wake: write");
  412. ASSERT_NOT_REACHED();
  413. }
  414. }